0006-surface-sam.patch 615 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718
  1. From 09ecd0a5dda6303ee651624092f4c02562d01014 Mon Sep 17 00:00:00 2001
  2. From: Maximilian Luz <luzmaximilian@gmail.com>
  3. Date: Mon, 17 Aug 2020 01:23:20 +0200
  4. Subject: [PATCH] misc: surface_sam: Add file2alias support for Surface SAM
  5. devices
  6. Implement file2alias support for Surface System Aggregator Module (SSAM)
  7. devices. This allows modules to be auto-loaded for specific devices via
  8. their respective module alias.
  9. Patchset: surface-sam
  10. ---
  11. include/linux/mod_devicetable.h | 17 +++++++++++++++++
  12. scripts/mod/devicetable-offsets.c | 7 +++++++
  13. scripts/mod/file2alias.c | 21 +++++++++++++++++++++
  14. 3 files changed, 45 insertions(+)
  15. diff --git a/include/linux/mod_devicetable.h b/include/linux/mod_devicetable.h
  16. index 5b08a473cdba..ef64063fac30 100644
  17. --- a/include/linux/mod_devicetable.h
  18. +++ b/include/linux/mod_devicetable.h
  19. @@ -838,4 +838,21 @@ struct mhi_device_id {
  20. kernel_ulong_t driver_data;
  21. };
  22. +/* Surface System Aggregator Module */
  23. +
  24. +#define SSAM_MATCH_CHANNEL 0x1
  25. +#define SSAM_MATCH_INSTANCE 0x2
  26. +#define SSAM_MATCH_FUNCTION 0x4
  27. +
  28. +struct ssam_device_id {
  29. + __u8 match_flags;
  30. +
  31. + __u8 category;
  32. + __u8 channel;
  33. + __u8 instance;
  34. + __u8 function;
  35. +
  36. + kernel_ulong_t driver_data;
  37. +};
  38. +
  39. #endif /* LINUX_MOD_DEVICETABLE_H */
  40. diff --git a/scripts/mod/devicetable-offsets.c b/scripts/mod/devicetable-offsets.c
  41. index 27007c18e754..bcff122d0dc8 100644
  42. --- a/scripts/mod/devicetable-offsets.c
  43. +++ b/scripts/mod/devicetable-offsets.c
  44. @@ -243,5 +243,12 @@ int main(void)
  45. DEVID(mhi_device_id);
  46. DEVID_FIELD(mhi_device_id, chan);
  47. + DEVID(ssam_device_id);
  48. + DEVID_FIELD(ssam_device_id, match_flags);
  49. + DEVID_FIELD(ssam_device_id, category);
  50. + DEVID_FIELD(ssam_device_id, channel);
  51. + DEVID_FIELD(ssam_device_id, instance);
  52. + DEVID_FIELD(ssam_device_id, function);
  53. +
  54. return 0;
  55. }
  56. diff --git a/scripts/mod/file2alias.c b/scripts/mod/file2alias.c
  57. index 2417dd1dee33..a6c583362b92 100644
  58. --- a/scripts/mod/file2alias.c
  59. +++ b/scripts/mod/file2alias.c
  60. @@ -1368,6 +1368,26 @@ static int do_mhi_entry(const char *filename, void *symval, char *alias)
  61. return 1;
  62. }
  63. +/* Looks like: ssam:cNtNiNfN
  64. + *
  65. + * N is exactly 2 digits, where each is an upper-case hex digit.
  66. + */
  67. +static int do_ssam_entry(const char *filename, void *symval, char *alias)
  68. +{
  69. + DEF_FIELD(symval, ssam_device_id, match_flags);
  70. + DEF_FIELD(symval, ssam_device_id, category);
  71. + DEF_FIELD(symval, ssam_device_id, channel);
  72. + DEF_FIELD(symval, ssam_device_id, instance);
  73. + DEF_FIELD(symval, ssam_device_id, function);
  74. +
  75. + sprintf(alias, "ssam:c%02X", category);
  76. + ADD(alias, "t", match_flags & SSAM_MATCH_CHANNEL, channel);
  77. + ADD(alias, "i", match_flags & SSAM_MATCH_INSTANCE, instance);
  78. + ADD(alias, "f", match_flags & SSAM_MATCH_FUNCTION, function);
  79. +
  80. + return 1;
  81. +}
  82. +
  83. /* Does namelen bytes of name exactly match the symbol? */
  84. static bool sym_is(const char *name, unsigned namelen, const char *symbol)
  85. {
  86. @@ -1442,6 +1462,7 @@ static const struct devtable devtable[] = {
  87. {"tee", SIZE_tee_client_device_id, do_tee_entry},
  88. {"wmi", SIZE_wmi_device_id, do_wmi_entry},
  89. {"mhi", SIZE_mhi_device_id, do_mhi_entry},
  90. + {"ssam", SIZE_ssam_device_id, do_ssam_entry},
  91. };
  92. /* Create MODULE_ALIAS() statements.
  93. --
  94. 2.29.2
  95. From e95b561277fc7223a61e0300abe942eb329af80e Mon Sep 17 00:00:00 2001
  96. From: Maximilian Luz <luzmaximilian@gmail.com>
  97. Date: Mon, 17 Aug 2020 01:44:30 +0200
  98. Subject: [PATCH] misc: Add support for Surface System Aggregator Module
  99. Add support for the Surface System Aggregator Module (SSAM), an embedded
  100. controller that can be found on 5th and later generation Microsoft
  101. Surface devices. The responsibilities of this EC vary from device to
  102. device. It provides battery information on all 5th and later generation
  103. devices, temperature sensor and cooling capability access, functionality
  104. for clipboard detaching on the Surface Books (2 and 3), as well as
  105. HID-over-SSAM input devices, including keyboard on the Surface Laptop 1
  106. and 2, and keyboard as well as touchpad input on the Surface Laptop 3
  107. and Surface Book 3.
  108. Patchset: surface-sam
  109. ---
  110. Documentation/driver-api/index.rst | 1 +
  111. .../surface_aggregator/client-api.rst | 38 +
  112. .../driver-api/surface_aggregator/client.rst | 393 +++
  113. .../surface_aggregator/clients/cdev.rst | 87 +
  114. .../surface_aggregator/clients/dtx.rst | 712 +++++
  115. .../surface_aggregator/clients/index.rst | 22 +
  116. .../surface_aggregator/clients/san.rst | 44 +
  117. .../driver-api/surface_aggregator/index.rst | 21 +
  118. .../surface_aggregator/internal-api.rst | 67 +
  119. .../surface_aggregator/internal.rst | 577 ++++
  120. .../surface_aggregator/overview.rst | 77 +
  121. .../driver-api/surface_aggregator/ssh.rst | 344 +++
  122. drivers/misc/Kconfig | 1 +
  123. drivers/misc/Makefile | 1 +
  124. drivers/misc/surface_aggregator/Kconfig | 67 +
  125. drivers/misc/surface_aggregator/Makefile | 18 +
  126. drivers/misc/surface_aggregator/bus.c | 416 +++
  127. drivers/misc/surface_aggregator/bus.h | 27 +
  128. .../misc/surface_aggregator/clients/Kconfig | 134 +
  129. .../misc/surface_aggregator/clients/Makefile | 10 +
  130. .../clients/surface_acpi_notify.c | 886 ++++++
  131. .../clients/surface_aggregator_cdev.c | 303 ++
  132. .../clients/surface_aggregator_registry.c | 665 +++++
  133. .../clients/surface_battery.c | 1168 ++++++++
  134. .../surface_aggregator/clients/surface_dtx.c | 1277 ++++++++
  135. .../surface_aggregator/clients/surface_hid.c | 924 ++++++
  136. .../clients/surface_perfmode.c | 122 +
  137. drivers/misc/surface_aggregator/controller.c | 2579 +++++++++++++++++
  138. drivers/misc/surface_aggregator/controller.h | 285 ++
  139. drivers/misc/surface_aggregator/core.c | 840 ++++++
  140. drivers/misc/surface_aggregator/ssh_msgb.h | 205 ++
  141. .../surface_aggregator/ssh_packet_layer.c | 2057 +++++++++++++
  142. .../surface_aggregator/ssh_packet_layer.h | 190 ++
  143. drivers/misc/surface_aggregator/ssh_parser.c | 228 ++
  144. drivers/misc/surface_aggregator/ssh_parser.h | 155 +
  145. .../surface_aggregator/ssh_request_layer.c | 1264 ++++++++
  146. .../surface_aggregator/ssh_request_layer.h | 143 +
  147. drivers/misc/surface_aggregator/trace.h | 632 ++++
  148. include/linux/mod_devicetable.h | 5 +-
  149. include/linux/surface_acpi_notify.h | 39 +
  150. include/linux/surface_aggregator/controller.h | 824 ++++++
  151. include/linux/surface_aggregator/device.h | 423 +++
  152. include/linux/surface_aggregator/serial_hub.h | 672 +++++
  153. include/uapi/linux/surface_aggregator/cdev.h | 78 +
  154. include/uapi/linux/surface_aggregator/dtx.h | 146 +
  155. scripts/mod/devicetable-offsets.c | 3 +-
  156. scripts/mod/file2alias.c | 10 +-
  157. 47 files changed, 19173 insertions(+), 7 deletions(-)
  158. create mode 100644 Documentation/driver-api/surface_aggregator/client-api.rst
  159. create mode 100644 Documentation/driver-api/surface_aggregator/client.rst
  160. create mode 100644 Documentation/driver-api/surface_aggregator/clients/cdev.rst
  161. create mode 100644 Documentation/driver-api/surface_aggregator/clients/dtx.rst
  162. create mode 100644 Documentation/driver-api/surface_aggregator/clients/index.rst
  163. create mode 100644 Documentation/driver-api/surface_aggregator/clients/san.rst
  164. create mode 100644 Documentation/driver-api/surface_aggregator/index.rst
  165. create mode 100644 Documentation/driver-api/surface_aggregator/internal-api.rst
  166. create mode 100644 Documentation/driver-api/surface_aggregator/internal.rst
  167. create mode 100644 Documentation/driver-api/surface_aggregator/overview.rst
  168. create mode 100644 Documentation/driver-api/surface_aggregator/ssh.rst
  169. create mode 100644 drivers/misc/surface_aggregator/Kconfig
  170. create mode 100644 drivers/misc/surface_aggregator/Makefile
  171. create mode 100644 drivers/misc/surface_aggregator/bus.c
  172. create mode 100644 drivers/misc/surface_aggregator/bus.h
  173. create mode 100644 drivers/misc/surface_aggregator/clients/Kconfig
  174. create mode 100644 drivers/misc/surface_aggregator/clients/Makefile
  175. create mode 100644 drivers/misc/surface_aggregator/clients/surface_acpi_notify.c
  176. create mode 100644 drivers/misc/surface_aggregator/clients/surface_aggregator_cdev.c
  177. create mode 100644 drivers/misc/surface_aggregator/clients/surface_aggregator_registry.c
  178. create mode 100644 drivers/misc/surface_aggregator/clients/surface_battery.c
  179. create mode 100644 drivers/misc/surface_aggregator/clients/surface_dtx.c
  180. create mode 100644 drivers/misc/surface_aggregator/clients/surface_hid.c
  181. create mode 100644 drivers/misc/surface_aggregator/clients/surface_perfmode.c
  182. create mode 100644 drivers/misc/surface_aggregator/controller.c
  183. create mode 100644 drivers/misc/surface_aggregator/controller.h
  184. create mode 100644 drivers/misc/surface_aggregator/core.c
  185. create mode 100644 drivers/misc/surface_aggregator/ssh_msgb.h
  186. create mode 100644 drivers/misc/surface_aggregator/ssh_packet_layer.c
  187. create mode 100644 drivers/misc/surface_aggregator/ssh_packet_layer.h
  188. create mode 100644 drivers/misc/surface_aggregator/ssh_parser.c
  189. create mode 100644 drivers/misc/surface_aggregator/ssh_parser.h
  190. create mode 100644 drivers/misc/surface_aggregator/ssh_request_layer.c
  191. create mode 100644 drivers/misc/surface_aggregator/ssh_request_layer.h
  192. create mode 100644 drivers/misc/surface_aggregator/trace.h
  193. create mode 100644 include/linux/surface_acpi_notify.h
  194. create mode 100644 include/linux/surface_aggregator/controller.h
  195. create mode 100644 include/linux/surface_aggregator/device.h
  196. create mode 100644 include/linux/surface_aggregator/serial_hub.h
  197. create mode 100644 include/uapi/linux/surface_aggregator/cdev.h
  198. create mode 100644 include/uapi/linux/surface_aggregator/dtx.h
  199. diff --git a/Documentation/driver-api/index.rst b/Documentation/driver-api/index.rst
  200. index 5ef2cfe3a16b..dbb5f7353022 100644
  201. --- a/Documentation/driver-api/index.rst
  202. +++ b/Documentation/driver-api/index.rst
  203. @@ -100,6 +100,7 @@ available subsections can be seen below.
  204. rfkill
  205. serial/index
  206. sm501
  207. + surface_aggregator/index
  208. switchtec
  209. sync_file
  210. vfio-mediated-device
  211. diff --git a/Documentation/driver-api/surface_aggregator/client-api.rst b/Documentation/driver-api/surface_aggregator/client-api.rst
  212. new file mode 100644
  213. index 000000000000..a1117d57036a
  214. --- /dev/null
  215. +++ b/Documentation/driver-api/surface_aggregator/client-api.rst
  216. @@ -0,0 +1,38 @@
  217. +.. SPDX-License-Identifier: GPL-2.0+
  218. +
  219. +===============================
  220. +Client Driver API Documentation
  221. +===============================
  222. +
  223. +.. contents::
  224. + :depth: 2
  225. +
  226. +
  227. +Serial Hub Communication
  228. +========================
  229. +
  230. +.. kernel-doc:: include/linux/surface_aggregator/serial_hub.h
  231. +
  232. +.. kernel-doc:: drivers/misc/surface_aggregator/ssh_packet_layer.c
  233. + :export:
  234. +
  235. +
  236. +Controller and Core Interface
  237. +=============================
  238. +
  239. +.. kernel-doc:: include/linux/surface_aggregator/controller.h
  240. +
  241. +.. kernel-doc:: drivers/misc/surface_aggregator/controller.c
  242. + :export:
  243. +
  244. +.. kernel-doc:: drivers/misc/surface_aggregator/core.c
  245. + :export:
  246. +
  247. +
  248. +Client Bus and Client Device API
  249. +================================
  250. +
  251. +.. kernel-doc:: include/linux/surface_aggregator/device.h
  252. +
  253. +.. kernel-doc:: drivers/misc/surface_aggregator/bus.c
  254. + :export:
  255. diff --git a/Documentation/driver-api/surface_aggregator/client.rst b/Documentation/driver-api/surface_aggregator/client.rst
  256. new file mode 100644
  257. index 000000000000..26d13085a117
  258. --- /dev/null
  259. +++ b/Documentation/driver-api/surface_aggregator/client.rst
  260. @@ -0,0 +1,393 @@
  261. +.. SPDX-License-Identifier: GPL-2.0+
  262. +
  263. +.. |ssam_controller| replace:: :c:type:`struct ssam_controller <ssam_controller>`
  264. +.. |ssam_device| replace:: :c:type:`struct ssam_device <ssam_device>`
  265. +.. |ssam_device_driver| replace:: :c:type:`struct ssam_device_driver <ssam_device_driver>`
  266. +.. |ssam_client_bind| replace:: :c:func:`ssam_client_bind`
  267. +.. |ssam_client_link| replace:: :c:func:`ssam_client_link`
  268. +.. |ssam_get_controller| replace:: :c:func:`ssam_get_controller`
  269. +.. |ssam_controller_get| replace:: :c:func:`ssam_controller_get`
  270. +.. |ssam_controller_put| replace:: :c:func:`ssam_controller_put`
  271. +.. |ssam_device_alloc| replace:: :c:func:`ssam_device_alloc`
  272. +.. |ssam_device_add| replace:: :c:func:`ssam_device_add`
  273. +.. |ssam_device_remove| replace:: :c:func:`ssam_device_remove`
  274. +.. |ssam_device_driver_register| replace:: :c:func:`ssam_device_driver_register`
  275. +.. |ssam_device_driver_unregister| replace:: :c:func:`ssam_device_driver_unregister`
  276. +.. |module_ssam_device_driver| replace:: :c:func:`module_ssam_device_driver`
  277. +.. |SSAM_DEVICE| replace:: :c:func:`SSAM_DEVICE`
  278. +.. |ssam_notifier_register| replace:: :c:func:`ssam_notifier_register`
  279. +.. |ssam_notifier_unregister| replace:: :c:func:`ssam_notifier_unregister`
  280. +.. |ssam_request_sync| replace:: :c:func:`ssam_request_sync`
  281. +.. |ssam_event_mask| replace:: :c:type:`enum ssam_event_mask <ssam_event_mask>`
  282. +
  283. +
  284. +======================
  285. +Writing Client Drivers
  286. +======================
  287. +
  288. +For the API documentation, refer to:
  289. +
  290. +.. toctree::
  291. + :maxdepth: 2
  292. +
  293. + client-api
  294. +
  295. +
  296. +Overview
  297. +========
  298. +
  299. +Client drivers can be set up in two main ways, depending on how the
  300. +corresponding device is made available to the system. We specifically
  301. +differentiate between devices that are presented to the system via one of
  302. +the conventional ways, e.g. as platform devices via ACPI, and devices that
  303. +are non-discoverable and instead need to be explicitly provided by some
  304. +other mechanism, as discussed further below.
  305. +
  306. +
  307. +Non-SSAM Client Drivers
  308. +=======================
  309. +
  310. +All communication with the SAM EC is handled via the |ssam_controller|
  311. +representing that EC to the kernel. Drivers targeting a non-SSAM device (and
  312. +thus not being a |ssam_device_driver|) need to explicitly establish a
  313. +connection/relation to that controller. This can be done via the
  314. +|ssam_client_bind| function. Said function returns a reference to the SSAM
  315. +controller, but, more importantly, also establishes a device link between
  316. +client device and controller (this can also be done separate via
  317. +|ssam_client_link|). It is important to do this, as it, first, guarantees
  318. +that the returned controller is valid for use in the client driver for as
  319. +long as this driver is bound to its device, i.e. that the driver gets
  320. +unbound before the controller ever becomes invalid, and, second, as it
  321. +ensures correct suspend/resume ordering. This setup should be done in the
  322. +driver's probe function, and may be used to defer probing in case the SSAM
  323. +subsystem is not ready yet, for example:
  324. +
  325. +.. code-block:: c
  326. +
  327. + static int client_driver_probe(struct platform_device *pdev)
  328. + {
  329. + struct ssam_controller *ctrl;
  330. +
  331. + ctrl = ssam_client_bind(&pdev->dev);
  332. + if (IS_ERR(ctrl))
  333. + return PTR_ERR(ctrl) == -ENODEV ? -EPROBE_DEFER : PTR_ERR(ctrl);
  334. +
  335. + // ...
  336. +
  337. + return 0;
  338. + }
  339. +
  340. +The controller may be separately obtained via |ssam_get_controller| and its
  341. +lifetime be guaranteed via |ssam_controller_get| and |ssam_controller_put|.
  342. +Note that none of these functions, however, guarantee that the controller
  343. +will not be shut down or suspended. These functions essentially only operate
  344. +on the reference, i.e. only guarantee a bare minimum of accessibility
  345. +without any guarantees at all on practical operability.
  346. +
  347. +
  348. +Adding SSAM Devices
  349. +===================
  350. +
  351. +If a device does not already exist/is not already provided via conventional
  352. +means, it should be provided as |ssam_device| via the SSAM client device
  353. +hub. New devices can be added to this hub by entering their UID into the
  354. +corresponding registry. SSAM devices can also be manually allocated via
  355. +|ssam_device_alloc|, subsequently to which they have to be added via
  356. +|ssam_device_add| and eventually removed via |ssam_device_remove|. By
  357. +default, the parent of the device is set to the controller device provided
  358. +for allocation, however this may be changed before the device is added. Note
  359. +that, when changing the parent device, care must be taken to ensure that the
  360. +controller lifetime and suspend/resume ordering guarantees, in the default
  361. +setup provided through the parent-child relation, are preserved. If
  362. +necessary, by use of |ssam_client_link| as is done for non-SSAM client
  363. +drivers and described in more detail above.
  364. +
  365. +A client device must always be removed by the party which added the
  366. +respective device before the controller shuts down. Such removal can be
  367. +guaranteed by linking the driver providing the SSAM device to the controller
  368. +via |ssam_client_link|, causing it to unbind before the controller driver
  369. +unbinds. Client devices registered with the controller as parent are
  370. +automatically removed when the controller shuts down, but this should not be
  371. +relied upon, especially as this does not extend to client devices with a
  372. +different parent.
  373. +
  374. +
  375. +SSAM Client Drivers
  376. +===================
  377. +
  378. +SSAM client device drivers are, in essence, no different than other device
  379. +driver types. They are represented via |ssam_device_driver| and bind to a
  380. +|ssam_device| via its UID (:c:type:`struct ssam_device.uid <ssam_device>`)
  381. +member and the match table
  382. +(:c:type:`struct ssam_device_driver.match_table <ssam_device_driver>`),
  383. +which should be set when declaring the driver struct instance. Refer to the
  384. +|SSAM_DEVICE| macro documentation for more details on how to define members
  385. +of the driver's match table.
  386. +
  387. +The UID for SSAM client devices consists of a ``domain``, a ``category``,
  388. +a ``target``, an ``instance``, and a ``function``. The ``domain`` is used
  389. +differentiate between physical SAM devices
  390. +(:c:type:`SSAM_DOMAIN_SERIALHUB <ssam_device_domain>`), i.e. devices that can
  391. +be accessed via the Surface Serial Hub, and virtual ones
  392. +(:c:type:`SSAM_DOMAIN_VIRTUAL <ssam_device_domain>`), such as client-device
  393. +hubs, that have no real representation on the SAM EC and are solely used on
  394. +the kernel/driver-side. For physical devices, ``category`` represents the
  395. +target category, ``target`` the target ID, and ``instance`` the instance ID
  396. +used to access the physical SAM device. In addition, ``function`` references
  397. +a specific device functionality, but has no meaning to the SAM EC. The
  398. +(default) name of a client device is generated based on its UID.
  399. +
  400. +A driver instance can be registered via |ssam_device_driver_register| and
  401. +unregistered via |ssam_device_driver_unregister|. For convenience, the
  402. +|module_ssam_device_driver| macro may be used to define module init- and
  403. +exit-functions registering the driver.
  404. +
  405. +The controller associated with a SSAM client device can be found in its
  406. +:c:type:`struct ssam_device.ctrl <ssam_device>` member. This reference is
  407. +guaranteed to be valid for at least as long as the client driver is bound,
  408. +but should also be valid for as long as the client device exists. Note,
  409. +however, that access outside of the bound client driver must ensure that the
  410. +controller device is not suspended while making any requests or
  411. +(un-)registering event notifiers (and thus should generally be avoided). This
  412. +is guaranteed when the controller is accessed from inside the bound client
  413. +driver.
  414. +
  415. +
  416. +Making Synchronous Requests
  417. +===========================
  418. +
  419. +Synchronous requests are (currently) the main form of host-initiated
  420. +communication with the EC. There are a couple of ways to define and execute
  421. +such requests, however, most of them boil down to something similar as shown
  422. +in the example below. This example defines a write-read request, meaning
  423. +that the caller provides an argument to the SAM EC and receives a response.
  424. +The caller needs to know the (maximum) length of the response payload and
  425. +provide a buffer for it.
  426. +
  427. +Care must be taken to ensure that any command payload data passed to the SAM
  428. +EC is provided in little-endian format and, similarly, any response payload
  429. +data received from it is converted from little-endian to host endianness.
  430. +
  431. +.. code-block:: c
  432. +
  433. + int perform_request(struct ssam_controller *ctrl, u32 arg, u32 *ret)
  434. + {
  435. + struct ssam_request rqst;
  436. + struct ssam_response resp;
  437. + int status;
  438. +
  439. + /* Convert request argument to little-endian. */
  440. + __le32 arg_le = cpu_to_le32(arg);
  441. + __le32 ret_le = cpu_to_le32(0);
  442. +
  443. + /*
  444. + * Initialize request specification. Replace this with your values.
  445. + * The rqst.payload field may be NULL if rqst.length is zero,
  446. + * indicating that the request does not have any argument.
  447. + *
  448. + * Note: The request parameters used here are not valid, i.e.
  449. + * they do not correspond to an actual SAM/EC request.
  450. + */
  451. + rqst.target_category = SSAM_SSH_TC_SAM;
  452. + rqst.target_id = 0x01;
  453. + rqst.command_id = 0x02;
  454. + rqst.instance_id = 0x03;
  455. + rqst.flags = SSAM_REQUEST_HAS_RESPONSE;
  456. + rqst.length = sizeof(arg_le);
  457. + rqst.payload = (u8 *)&arg_le;
  458. +
  459. + /* Initialize request response. */
  460. + resp.capacity = sizeof(ret_le);
  461. + resp.length = 0;
  462. + resp.pointer = (u8 *)&ret_le;
  463. +
  464. + /*
  465. + * Perform actual request. The response pointer may be null in case
  466. + * the request does not have any response. This must be consistent
  467. + * with the SSAM_REQUEST_HAS_RESPONSE flag set in the specification
  468. + * above.
  469. + */
  470. + status = ssam_request_sync(ctrl, &rqst, &resp);
  471. +
  472. + /*
  473. + * Alternatively use
  474. + *
  475. + * ssam_request_sync_onstack(ctrl, &rqst, &resp, sizeof(arg_le));
  476. + *
  477. + * to perform the request, allocating the message buffer directly
  478. + * on the stack as opposed to allocation via kzalloc().
  479. + */
  480. +
  481. + /*
  482. + * Convert request response back to native format. Note that in the
  483. + * error case, this value is not touched by the SSAM core, i.e.
  484. + * 'ret_le' will be zero as specified in its initialization.
  485. + */
  486. + *ret = le32_to_cpu(ret_le);
  487. +
  488. + return status;
  489. + }
  490. +
  491. +Note that |ssam_request_sync| in its essence is a wrapper over lower-level
  492. +request primitives, which may also be used to perform requests. Refer to its
  493. +implementation and documentation for more details.
  494. +
  495. +An arguably more user-friendly way of defining such functions is by using
  496. +one of the generator macros, for example via:
  497. +
  498. +.. code-block:: c
  499. +
  500. + SSAM_DEFINE_SYNC_REQUEST_W(__ssam_tmp_perf_mode_set, __le32, {
  501. + .target_category = SSAM_SSH_TC_TMP,
  502. + .target_id = 0x01,
  503. + .command_id = 0x03,
  504. + .instance_id = 0x00,
  505. + });
  506. +
  507. +This example defines a function
  508. +
  509. +.. code-block:: c
  510. +
  511. + int __ssam_tmp_perf_mode_set(struct ssam_controller *ctrl, const __le32 *arg);
  512. +
  513. +executing the specified request, with the controller passed in when calling
  514. +said function. In this example, the argument is provided via the ``arg``
  515. +pointer. Note that the generated function allocates the message buffer on
  516. +the stack. Thus, if the argument provided via the request is large, these
  517. +kinds of macros should be avoided. Also note that, in contrast to the
  518. +previous non-macro example, this function does not do any endianness
  519. +conversion, which has to be handled by the caller. Apart from those
  520. +differences the function generated by the macro is similar to the one
  521. +provided in the non-macro example above.
  522. +
  523. +The full list of such function-generating macros is
  524. +
  525. +- :c:func:`SSAM_DEFINE_SYNC_REQUEST_N` for requests without return value and
  526. + without argument.
  527. +- :c:func:`SSAM_DEFINE_SYNC_REQUEST_R` for requests with return value but no
  528. + argument.
  529. +- :c:func:`SSAM_DEFINE_SYNC_REQUEST_W` for requests without return value but
  530. + with argument.
  531. +
  532. +Refer to their respective documentation for more details. For each one of
  533. +these macros, a special variant is provided, which targets request types
  534. +applicable to multiple instances of the same device type:
  535. +
  536. +- :c:func:`SSAM_DEFINE_SYNC_REQUEST_MD_N`
  537. +- :c:func:`SSAM_DEFINE_SYNC_REQUEST_MD_R`
  538. +- :c:func:`SSAM_DEFINE_SYNC_REQUEST_MD_W`
  539. +
  540. +The difference of those macros to the previously mentioned versions is, that
  541. +the device target and instance IDs are not fixed for the generated function,
  542. +but instead have to be provided by the caller of said function.
  543. +
  544. +Additionally, variants for direct use with client devices, i.e.
  545. +|ssam_device|, are also provided. These can, for example, be used as
  546. +follows:
  547. +
  548. +.. code-block:: c
  549. +
  550. + SSAM_DEFINE_SYNC_REQUEST_CL_R(ssam_bat_get_sta, __le32, {
  551. + .target_category = SSAM_SSH_TC_BAT,
  552. + .command_id = 0x01,
  553. + });
  554. +
  555. +This invocation of the macro defines a function
  556. +
  557. +.. code-block:: c
  558. +
  559. + int ssam_bat_get_sta(struct ssam_device *sdev, __le32 *ret);
  560. +
  561. +executing the specified request, using the device IDs and controller given
  562. +in the client device. The full list of such macros for client devices is:
  563. +
  564. +- :c:func:`SSAM_DEFINE_SYNC_REQUEST_CL_N`
  565. +- :c:func:`SSAM_DEFINE_SYNC_REQUEST_CL_R`
  566. +- :c:func:`SSAM_DEFINE_SYNC_REQUEST_CL_W`
  567. +
  568. +
  569. +Handling Events
  570. +===============
  571. +
  572. +To receive events from the SAM EC, an event notifier must be registered for
  573. +the desired event via |ssam_notifier_register|. The notifier must be
  574. +unregistered via |ssam_notifier_unregister| once it is not required any
  575. +more.
  576. +
  577. +Event notifiers are registered by providing (at minimum) a callback to call
  578. +in case an event has been received, the registry specifying how the event
  579. +should be enabled, an event ID specifying for which target category and,
  580. +optionally and depending on the registry used, for which instance ID events
  581. +should be enabled, and finally, flags describing how the EC will send these
  582. +events. If the specific registry does not enable events by instance ID, the
  583. +instance ID must be set to zero. Additionally, a priority for the respective
  584. +notifier may be specified, which determines its order in relation to any
  585. +other notifier registered for the same target category.
  586. +
  587. +By default, event notifiers will receive all events for the specific target
  588. +category, regardless of the instance ID specified when registering the
  589. +notifier. The core may be instructed to only call a notifier if the target
  590. +ID or instance ID (or both) of the event match the ones implied by the
  591. +notifier IDs (in case of target ID, the target ID of the registry), by
  592. +providing an event mask (see |ssam_event_mask|).
  593. +
  594. +In general, the target ID of the registry is also the target ID of the
  595. +enabled event (with the notable exception being keyboard input events on the
  596. +Surface Laptop 1 and 2, which are enabled via a registry with target ID 1,
  597. +but provide events with target ID 2).
  598. +
  599. +A full example for registering an event notifier and handling received
  600. +events is provided below:
  601. +
  602. +.. code-block:: c
  603. +
  604. + u32 notifier_callback(struct ssam_event_notifier *nf,
  605. + const struct ssam_event *event)
  606. + {
  607. + int status = ...
  608. +
  609. + /* Handle the event here ... */
  610. +
  611. + /* Convert return value and indicate that we handled the event. */
  612. + return ssam_notifier_from_errno(status) | SSAM_NOTIF_HANDLED;
  613. + }
  614. +
  615. + int setup_notifier(struct ssam_device *sdev,
  616. + struct ssam_event_notifier *nf)
  617. + {
  618. + /* Set priority wrt. other handlers of same target category. */
  619. + nf->base.priority = 1;
  620. +
  621. + /* Set event/notifier callback. */
  622. + nf->base.fn = notifier_callback;
  623. +
  624. + /* Specify event registry, i.e. how events get enabled/disabled. */
  625. + nf->event.reg = SSAM_EVENT_REGISTRY_KIP;
  626. +
  627. + /* Specify which event to enable/disable */
  628. + nf->event.id.target_category = sdev->uid.category;
  629. + nf->event.id.instance = sdev->uid.instance;
  630. +
  631. + /*
  632. + * Specify for which events the notifier callback gets executed.
  633. + * This essentially tells the core if it can skip notifiers that
  634. + * don't have target or instance IDs matching those of the event.
  635. + */
  636. + nf->event.mask = SSAM_EVENT_MASK_STRICT;
  637. +
  638. + /* Specify event flags. */
  639. + nf->event.flags = SSAM_EVENT_SEQUENCED;
  640. +
  641. + return ssam_notifier_register(sdev->ctrl, nf);
  642. + }
  643. +
  644. +Multiple event notifiers can be registered for the same event. The event
  645. +handler core takes care of enabling and disabling events when notifiers are
  646. +registered and unregistered, by keeping track of how many notifiers for a
  647. +specific event (combination of registry, event target category, and event
  648. +instance ID) are currently registered. This means that a specific event will
  649. +be enabled when the first notifier for it is being registered and disabled
  650. +when the last notifier for it is being unregistered. Note that the event
  651. +flags are therefore only used on the first registered notifier, however, one
  652. +should take care that notifiers for a specific event are always registered
  653. +with the same flag and it is considered a bug to do otherwise.
  654. diff --git a/Documentation/driver-api/surface_aggregator/clients/cdev.rst b/Documentation/driver-api/surface_aggregator/clients/cdev.rst
  655. new file mode 100644
  656. index 000000000000..248c1372d879
  657. --- /dev/null
  658. +++ b/Documentation/driver-api/surface_aggregator/clients/cdev.rst
  659. @@ -0,0 +1,87 @@
  660. +.. SPDX-License-Identifier: GPL-2.0+
  661. +
  662. +.. |u8| replace:: :c:type:`u8 <u8>`
  663. +.. |u16| replace:: :c:type:`u16 <u16>`
  664. +.. |ssam_cdev_request| replace:: :c:type:`struct ssam_cdev_request <ssam_cdev_request>`
  665. +.. |ssam_cdev_request_flags| replace:: :c:type:`enum ssam_cdev_request_flags <ssam_cdev_request_flags>`
  666. +
  667. +==============================
  668. +User-Space EC Interface (cdev)
  669. +==============================
  670. +
  671. +The ``surface_aggregator_cdev`` module provides a misc-device for the SSAM
  672. +controller to allow for a (more or less) direct connection from user-space to
  673. +the SAM EC. It is intended to be used for development and debugging, and
  674. +therefore should not be used or relied upon in any other way. Note that this
  675. +module is not loaded automatically, but instead must be loaded manually.
  676. +
  677. +The provided interface is accessible through the ``/dev/surface/aggregator``
  678. +device-file. All functionality of this interface is provided via IOCTLs.
  679. +These IOCTLs and their respective input/output parameter structs are defined in
  680. +``include/uapi/linux/surface_aggregator/cdev.h``.
  681. +
  682. +A small python library and scripts for accessing this interface can be found
  683. +at https://github.com/linux-surface/surface-aggregator-module/tree/master/scripts/ssam.
  684. +
  685. +
  686. +Controller IOCTLs
  687. +=================
  688. +
  689. +The following IOCTLs are provided:
  690. +
  691. +.. flat-table:: Controller IOCTLs
  692. + :widths: 1 1 1 1 4
  693. + :header-rows: 1
  694. +
  695. + * - Type
  696. + - Number
  697. + - Direction
  698. + - Name
  699. + - Description
  700. +
  701. + * - ``0xA5``
  702. + - ``1``
  703. + - ``WR``
  704. + - ``REQUEST``
  705. + - Perform synchronous SAM request.
  706. +
  707. +
  708. +``REQUEST``
  709. +-----------
  710. +
  711. +Defined as ``_IOWR(0xA5, 1, struct ssam_cdev_request)``.
  712. +
  713. +Executes a synchronous SAM request. The request specification is passed in
  714. +as argument of type |ssam_cdev_request|, which is then written to/modified
  715. +by the IOCTL to return status and result of the request.
  716. +
  717. +Request payload data must be allocated separately and is passed in via the
  718. +``payload.data`` and ``payload.length`` members. If a response is required,
  719. +the response buffer must be allocated by the caller and passed in via the
  720. +``response.data`` member. The ``response.length`` member must be set to the
  721. +capacity of this buffer, or if no response is required, zero. Upon
  722. +completion of the request, the call will write the response to the response
  723. +buffer (if its capacity allows it) and overwrite the length field with the
  724. +actual size of the response, in bytes.
  725. +
  726. +Additionally, if the request has a response, this must be indicated via the
  727. +request flags, as is done with in-kernel requests. Request flags can be set
  728. +via the ``flags`` member and the values correspond to the values found in
  729. +|ssam_cdev_request_flags|.
  730. +
  731. +Finally, the status of the request itself is returned in the ``status``
  732. +member (a negative errno value indicating failure). Note that failure
  733. +indication of the IOCTL is separated from failure indication of the request:
  734. +The IOCTL returns a negative status code if anything failed during setup of
  735. +the request (``-EFAULT``) or if the provided argument or any of its fields
  736. +are invalid (``-EINVAL``). In this case, the status value of the request
  737. +argument may be set, providing more detail on what went wrong (e.g.
  738. +``-ENOMEM`` for out-of-memory), but this value may also be zero. The IOCTL
  739. +will return with a zero status code in case the request has been set up,
  740. +submitted, and completed (i.e. handed back to user-space) successfully from
  741. +inside the IOCTL, but the request ``status`` member may still be negative in
  742. +case the actual execution of the request failed after it has been submitted.
  743. +
  744. +A full definition of the argument struct is provided below:
  745. +
  746. +.. kernel-doc:: include/uapi/linux/surface_aggregator/cdev.h
  747. diff --git a/Documentation/driver-api/surface_aggregator/clients/dtx.rst b/Documentation/driver-api/surface_aggregator/clients/dtx.rst
  748. new file mode 100644
  749. index 000000000000..e974c2b04e9f
  750. --- /dev/null
  751. +++ b/Documentation/driver-api/surface_aggregator/clients/dtx.rst
  752. @@ -0,0 +1,712 @@
  753. +.. SPDX-License-Identifier: GPL-2.0+
  754. +
  755. +.. |__u16| replace:: :c:type:`__u16 <__u16>`
  756. +.. |sdtx_event| replace:: :c:type:`struct sdtx_event <sdtx_event>`
  757. +.. |sdtx_event_code| replace:: :c:type:`enum sdtx_event_code <sdtx_event_code>`
  758. +.. |sdtx_base_info| replace:: :c:type:`struct sdtx_base_info <sdtx_base_info>`
  759. +.. |sdtx_device_mode| replace:: :c:type:`struct sdtx_device_mode <sdtx_device_mode>`
  760. +
  761. +======================================================
  762. +User-Space DTX (Clipboard Detachment System) Interface
  763. +======================================================
  764. +
  765. +The ``surface_dtx`` driver is responsible for proper clipboard detachment
  766. +and re-attachment handling. To this end, it provides the ``/dev/surface/dtx``
  767. +device file, through which it can interface with a user-space daemon. This
  768. +daemon is then ultimately responsible for determining and taking necessary
  769. +actions, such as unmounting devices attached to the base,
  770. +unloading/reloading the graphics-driver, user-notifications, etc.
  771. +
  772. +There are two basic communication principles used in this driver: Commands
  773. +(in other parts of the documentation also referred to as requests) and
  774. +events. Commands are sent to the EC and may have a different implications in
  775. +different contexts. Events are sent by the EC upon some internal state
  776. +change. Commands are always driver-initiated, whereas events are always
  777. +initiated by the EC.
  778. +
  779. +.. contents::
  780. +
  781. +Nomenclature
  782. +============
  783. +
  784. +* **Clipboard:**
  785. + The detachable upper part of the Surface Book, housing the screen and CPU.
  786. +
  787. +* **Base:**
  788. + The lower part of the Surface Book from which the clipboard can be
  789. + detached, optionally (model dependent) housing the discrete GPU (dGPU).
  790. +
  791. +* **Latch:**
  792. + The mechanism keeping the clipboard attached to the base in normal
  793. + operation and allowing it to be detached when requested.
  794. +
  795. +* **Silently ignored commands:**
  796. + The command is accepted by the EC as a valid command and acknowledged
  797. + (following the standard communication protocol), but the EC does not act
  798. + upon it, i.e. ignores it.e upper part of the
  799. +
  800. +
  801. +Detachment Process
  802. +==================
  803. +
  804. +Warning: This part of the documentation is based on reverse engineering and
  805. +testing and thus may contain errors or be incomplete.
  806. +
  807. +Latch States
  808. +------------
  809. +
  810. +The latch mechanism has two major states: *open* and *closed*. In the
  811. +*closed* state (default), the clipboard is secured to the base, whereas in
  812. +the *open* state, the clipboard can be removed by a user.
  813. +
  814. +The latch can additionally be locked and, correspondingly, unlocked, which
  815. +can influence the detachment procedure. Specifically, this locking mechanism
  816. +is intended to prevent the the dGPU, positioned in the base of the device,
  817. +from being hot-unplugged while in use. More details can be found in the
  818. +documentation for the detachment procedure below. By default, the latch is
  819. +unlocked.
  820. +
  821. +Detachment Procedure
  822. +--------------------
  823. +
  824. +Note that the detachment process is governed fully by the EC. The
  825. +``surface_dtx`` driver only relays events from the EC to user-space and
  826. +commands from user-space to the EC, i.e. it does not influence this process.
  827. +
  828. +The detachment process is started with the user pressing the *detach* button
  829. +on the base of the device or executing the ``SDTX_IOCTL_LATCH_REQUEST`` IOCTL.
  830. +Following that:
  831. +
  832. +1. The EC turns on the indicator led on the detach-button, sends a
  833. + *detach-request* event (``SDTX_EVENT_REQUEST``), and awaits further
  834. + instructions/commands. In case the latch is unlocked, the led will flash
  835. + green. If the latch has been locked, the led will be solid red
  836. +
  837. +2. The event is, via the ``surface_dtx`` driver, relayed to user-space, where
  838. + an appropriate user-space daemon can handle it and send instructions back
  839. + to the EC via IOCTLs provided by this driver.
  840. +
  841. +3. The EC waits for instructions from user-space and acts according to them.
  842. + If the EC does not receive any instructions in a given period, it will
  843. + time out and continue as follows:
  844. +
  845. + - If the latch is unlocked, the EC will open the latch and the clipboard
  846. + can be detached from the base. This is the exact behavior as without
  847. + this driver or any user-space daemon. See the ``SDTX_IOCTL_LATCH_CONFIRM``
  848. + description below for more details on the follow-up behavior of the EC.
  849. +
  850. + - If the latch is locked, the EC will *not* open the latch, meaning the
  851. + clipboard cannot be detached from the base. Furthermore, the EC sends
  852. + an cancel event (``SDTX_EVENT_CANCEL``) detailing this with the cancel
  853. + reason ``SDTX_DETACH_TIMEDOUT`` (see :ref:`events` for details).
  854. +
  855. +Valid responses by a user-space daemon to a detachment request event are:
  856. +
  857. +- Execute ``SDTX_IOCTL_LATCH_REQUEST``. This will immediately abort the
  858. + detachment process. Furthermore, the EC will send a detach-request event,
  859. + similar to the user pressing the detach-button to cancel said process (see
  860. + below).
  861. +
  862. +- Execute ``SDTX_IOCTL_LATCH_CONFIRM``. This will cause the EC to open the
  863. + latch, after which the user can separate clipboard and base.
  864. +
  865. + As this changes the latch state, a *latch-status* event
  866. + (``SDTX_EVENT_LATCH_STATUS``) will be sent once the latch has been opened
  867. + successfully. If the EC fails to open the latch, e.g. due to hardware
  868. + error or low battery, a latch-cancel event (``SDTX_EVENT_CANCEL``) will be
  869. + sent with the cancel reason indicating the specific failure.
  870. +
  871. + If the latch is currently locked, the latch will automatically be
  872. + unlocked before it is opened.
  873. +
  874. +- Execute ``SDTX_IOCTL_LATCH_HEARTBEAT``. This will reset the internal timeout.
  875. + No other actions will be performed, i.e. the detachment process will neither
  876. + be completed nor canceled, and the EC will still be waiting for further
  877. + responses.
  878. +
  879. +- Execute ``SDTX_IOCTL_LATCH_CANCEL``. This will abort the detachment process,
  880. + similar to ``SDTX_IOCTL_LATCH_REQUEST``, described above, or the button
  881. + press, described below. A *generic request* event (``SDTX_EVENT_REQUEST``)
  882. + is send in response to this. In contrast to those, however, this command
  883. + does not trigger a new detachment process if none is currently in
  884. + progress.
  885. +
  886. +- Do nothing. The detachment process eventually times out as described in
  887. + point 3.
  888. +
  889. +See :ref:`ioctls` for more details on these responses.
  890. +
  891. +It is important to note that, if the user presses the detach button at any
  892. +point when a detachment operation is in progress (i.e. after the the EC has
  893. +sent the initial *detach-request* event (``SDTX_EVENT_REQUEST``) and before
  894. +it received the corresponding response concluding the process), the
  895. +detachment process is canceled on the EC-level and an identical event is
  896. +being sent. Thus a *detach-request* event, by itself, does not signal the
  897. +start of the detachment process.
  898. +
  899. +The detachment process may further be canceled by the EC due to hardware
  900. +failures or a low clipboard battery. This is done via a cancel event
  901. +(``SDTX_EVENT_CANCEL``) with the corresponding cancel reason.
  902. +
  903. +
  904. +User-Space Interface Documentation
  905. +==================================
  906. +
  907. +Error Codes and Status Values
  908. +-----------------------------
  909. +
  910. +Error and status codes are divided into different categories, which can be
  911. +used to determine if the status code is an error, and, if it is, the
  912. +severity and type of that error. The current categories are:
  913. +
  914. +.. flat-table:: Overview of Status/Error Categories.
  915. + :widths: 2 1 3
  916. + :header-rows: 1
  917. +
  918. + * - Name
  919. + - Value
  920. + - Short Description
  921. +
  922. + * - ``STATUS``
  923. + - ``0x0000``
  924. + - Non-error status codes.
  925. +
  926. + * - ``RUNTIME_ERROR``
  927. + - ``0x1000``
  928. + - Non-critical runtime errors.
  929. +
  930. + * - ``HARDWARE_ERROR``
  931. + - ``0x2000``
  932. + - Critical hardware failures.
  933. +
  934. + * - ``UNKNOWN``
  935. + - ``0xF000``
  936. + - Unknown error codes.
  937. +
  938. +Other categories are reserved for future use. The ``SDTX_CATEGORY()`` macro
  939. +can be used to determine the category of any status value. The
  940. +``SDTX_SUCCESS()`` macro can be used to check if the status value is a
  941. +success value (``SDTX_CATEGORY_STATUS``) or if it indicates a failure.
  942. +
  943. +Unknown status or error codes sent by the EC are assigned to the ``UNKNOWN``
  944. +category by the driver and may be implemented via their own code in the
  945. +future.
  946. +
  947. +Currently used error codes are:
  948. +
  949. +.. flat-table:: Overview of Error Codes.
  950. + :widths: 2 1 1 3
  951. + :header-rows: 1
  952. +
  953. + * - Name
  954. + - Category
  955. + - Value
  956. + - Short Description
  957. +
  958. + * - ``SDTX_DETACH_NOT_FEASIBLE``
  959. + - ``RUNTIME``
  960. + - ``0x1001``
  961. + - Detachment not feasible due to low clipboard battery.
  962. +
  963. + * - ``SDTX_DETACH_TIMEDOUT``
  964. + - ``RUNTIME``
  965. + - ``0x1002``
  966. + - Detachment process timed out while the latch was locked.
  967. +
  968. + * - ``SDTX_ERR_FAILED_TO_OPEN``
  969. + - ``HARDWARE``
  970. + - ``0x2001``
  971. + - Failed to open latch.
  972. +
  973. + * - ``SDTX_ERR_FAILED_TO_REMAIN_OPEN``
  974. + - ``HARDWARE``
  975. + - ``0x2002``
  976. + - Failed to keep latch open.
  977. +
  978. + * - ``SDTX_ERR_FAILED_TO_CLOSE``
  979. + - ``HARDWARE``
  980. + - ``0x2003``
  981. + - Failed to close latch.
  982. +
  983. +Other error codes are reserved for future use. Non-error status codes may
  984. +overlap and are generally only unique within their use-case:
  985. +
  986. +.. flat-table:: Latch Status Codes.
  987. + :widths: 2 1 1 3
  988. + :header-rows: 1
  989. +
  990. + * - Name
  991. + - Category
  992. + - Value
  993. + - Short Description
  994. +
  995. + * - ``SDTX_LATCH_CLOSED``
  996. + - ``STATUS``
  997. + - ``0x0000``
  998. + - Latch is closed/has been closed.
  999. +
  1000. + * - ``SDTX_LATCH_OPENED``
  1001. + - ``STATUS``
  1002. + - ``0x0001``
  1003. + - Latch is open/has been opened.
  1004. +
  1005. +.. flat-table:: Base State Codes.
  1006. + :widths: 2 1 1 3
  1007. + :header-rows: 1
  1008. +
  1009. + * - Name
  1010. + - Category
  1011. + - Value
  1012. + - Short Description
  1013. +
  1014. + * - ``SDTX_BASE_DETACHED``
  1015. + - ``STATUS``
  1016. + - ``0x0000``
  1017. + - Base has been detached/is not present.
  1018. +
  1019. + * - ``SDTX_BASE_ATTACHED``
  1020. + - ``STATUS``
  1021. + - ``0x0001``
  1022. + - Base has been attached/is present.
  1023. +
  1024. +Again, other codes are reserved for future use.
  1025. +
  1026. +.. _events:
  1027. +
  1028. +Events
  1029. +------
  1030. +
  1031. +Events can be received by reading from the device file. They are disabled by
  1032. +default and have to be enabled by executing ``SDTX_IOCTL_EVENTS_ENABLE``
  1033. +first. All events follow the layout prescribed by |sdtx_event|. Specific
  1034. +event types can be identified by their event code, described in
  1035. +|sdtx_event_code|. Note that other event codes are reserved for future use,
  1036. +thus an event parser must be able to handle any unknown/unsupported event
  1037. +types gracefully, by relying on the payload length given in the event header.
  1038. +
  1039. +Currently provided event types are:
  1040. +
  1041. +.. flat-table:: Overview of DTX events.
  1042. + :widths: 2 1 1 3
  1043. + :header-rows: 1
  1044. +
  1045. + * - Name
  1046. + - Code
  1047. + - Payload
  1048. + - Short Description
  1049. +
  1050. + * - ``SDTX_EVENT_REQUEST``
  1051. + - ``1``
  1052. + - ``0`` bytes
  1053. + - Detachment process initiated/aborted.
  1054. +
  1055. + * - ``SDTX_EVENT_CANCEL``
  1056. + - ``2``
  1057. + - ``2`` bytes
  1058. + - EC canceled detachment process.
  1059. +
  1060. + * - ``SDTX_EVENT_BASE_CONNECTION``
  1061. + - ``3``
  1062. + - ``4`` bytes
  1063. + - Base connection state changed.
  1064. +
  1065. + * - ``SDTX_EVENT_LATCH_STATUS``
  1066. + - ``4``
  1067. + - ``2`` bytes
  1068. + - Latch status changed.
  1069. +
  1070. + * - ``SDTX_EVENT_DEVICE_MODE``
  1071. + - ``5``
  1072. + - ``2`` bytes
  1073. + - Device mode changed.
  1074. +
  1075. +Individual events in more detail:
  1076. +
  1077. +``SDTX_EVENT_REQUEST``
  1078. +^^^^^^^^^^^^^^^^^^^^^^
  1079. +
  1080. +Sent when a detachment process is started or, if in progress, aborted by the
  1081. +user, either via a detach button press or a detach request
  1082. +(``SDTX_IOCTL_LATCH_REQUEST``) being sent from user-space.
  1083. +
  1084. +Does not have any payload.
  1085. +
  1086. +``SDTX_EVENT_CANCEL``
  1087. +^^^^^^^^^^^^^^^^^^^^^
  1088. +
  1089. +Sent when a detachment process is canceled by the EC due to unfulfilled
  1090. +preconditions (e.g. clipboard battery too low to detach) or hardware
  1091. +failure. The reason for cancellation is given in the event payload detailed
  1092. +below and can be one of
  1093. +
  1094. +* ``SDTX_DETACH_TIMEDOUT``: Detachment timed out while the latch was locked.
  1095. + The latch has neither been opened nor unlocked.
  1096. +
  1097. +* ``SDTX_DETACH_NOT_FEASIBLE``: Detachment not feasible due to low clipboard
  1098. + battery.
  1099. +
  1100. +* ``SDTX_ERR_FAILED_TO_OPEN``: Could not open the latch (hardware failure).
  1101. +
  1102. +* ``SDTX_ERR_FAILED_TO_REMAIN_OPEN``: Could not keep the latch open (hardware
  1103. + failure).
  1104. +
  1105. +* ``SDTX_ERR_FAILED_TO_CLOSE``: Could not close the latch (hardware failure).
  1106. +
  1107. +Other error codes in this context are reserved for future use.
  1108. +
  1109. +These codes can be classified via the ``SDTX_CATEGORY()`` macro to discern
  1110. +between critical hardware errors (``SDTX_CATEGORY_HARDWARE_ERROR``) or
  1111. +runtime errors (``SDTX_CATEGORY_RUNTIME_ERROR``), the latter of which may
  1112. +happen during normal operation if certain preconditions for detachment are
  1113. +not given.
  1114. +
  1115. +.. flat-table:: Detachment Cancel Event Payload
  1116. + :widths: 1 1 4
  1117. + :header-rows: 1
  1118. +
  1119. + * - Field
  1120. + - Type
  1121. + - Description
  1122. +
  1123. + * - ``reason``
  1124. + - |__u16|
  1125. + - Reason for cancellation.
  1126. +
  1127. +``SDTX_EVENT_BASE_CONNECTION``
  1128. +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1129. +
  1130. +Sent when the base connection state has changed, i.e. when the base has been
  1131. +attached, detached, or detachment has become infeasible due to low clipboard
  1132. +battery. The new state and, if a base is connected, ID of the base is
  1133. +provided as payload of type |sdtx_base_info| with its layout presented
  1134. +below:
  1135. +
  1136. +.. flat-table:: Base-Connection-Change Event Payload
  1137. + :widths: 1 1 4
  1138. + :header-rows: 1
  1139. +
  1140. + * - Field
  1141. + - Type
  1142. + - Description
  1143. +
  1144. + * - ``state``
  1145. + - |__u16|
  1146. + - Base connection state.
  1147. +
  1148. + * - ``base_id``
  1149. + - |__u16|
  1150. + - Type of base connected (zero if none).
  1151. +
  1152. +Possible values for ``state`` are:
  1153. +
  1154. +* ``SDTX_BASE_DETACHED``,
  1155. +* ``SDTX_BASE_ATTACHED``, and
  1156. +* ``SDTX_DETACH_NOT_FEASIBLE``.
  1157. +
  1158. +Other values are reserved for future use.
  1159. +
  1160. +``SDTX_EVENT_LATCH_STATUS``
  1161. +^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1162. +
  1163. +Sent when the latch status has changed, i.e. when the latch has been opened,
  1164. +closed, or an error occurred. The current status is provided as payload:
  1165. +
  1166. +.. flat-table:: Latch-Status-Change Event Payload
  1167. + :widths: 1 1 4
  1168. + :header-rows: 1
  1169. +
  1170. + * - Field
  1171. + - Type
  1172. + - Description
  1173. +
  1174. + * - ``status``
  1175. + - |__u16|
  1176. + - Latch status.
  1177. +
  1178. +Possible values for ``status`` are:
  1179. +
  1180. +* ``SDTX_LATCH_CLOSED``,
  1181. +* ``SDTX_LATCH_OPENED``,
  1182. +* ``SDTX_ERR_FAILED_TO_OPEN``,
  1183. +* ``SDTX_ERR_FAILED_TO_REMAIN_OPEN``, and
  1184. +* ``SDTX_ERR_FAILED_TO_CLOSE``.
  1185. +
  1186. +Other values are reserved for future use.
  1187. +
  1188. +``SDTX_EVENT_DEVICE_MODE``
  1189. +^^^^^^^^^^^^^^^^^^^^^^^^^^
  1190. +
  1191. +Sent when the device mode has changed. The new device mode is provided as
  1192. +payload:
  1193. +
  1194. +.. flat-table:: Device-Mode-Change Event Payload
  1195. + :widths: 1 1 4
  1196. + :header-rows: 1
  1197. +
  1198. + * - Field
  1199. + - Type
  1200. + - Description
  1201. +
  1202. + * - ``mode``
  1203. + - |__u16|
  1204. + - Device operation mode.
  1205. +
  1206. +Possible values for ``mode`` are:
  1207. +
  1208. +* ``SDTX_DEVICE_MODE_TABLET``,
  1209. +* ``SDTX_DEVICE_MODE_LAPTOP``, and
  1210. +* ``SDTX_DEVICE_MODE_STUDIO``.
  1211. +
  1212. +Other values are reserved for future use.
  1213. +
  1214. +.. _ioctls:
  1215. +
  1216. +IOCTLs
  1217. +------
  1218. +
  1219. +The following IOCTLs are provided:
  1220. +
  1221. +.. flat-table:: Overview of DTX IOCTLs
  1222. + :widths: 1 1 1 1 4
  1223. + :header-rows: 1
  1224. +
  1225. + * - Type
  1226. + - Number
  1227. + - Direction
  1228. + - Name
  1229. + - Description
  1230. +
  1231. + * - ``0xA5``
  1232. + - ``0x21``
  1233. + - ``-``
  1234. + - ``EVENTS_ENABLE``
  1235. + - Enable events for the current file descriptor.
  1236. +
  1237. + * - ``0xA5``
  1238. + - ``0x22``
  1239. + - ``-``
  1240. + - ``EVENTS_DISABLE``
  1241. + - Disable events for the current file descriptor.
  1242. +
  1243. + * - ``0xA5``
  1244. + - ``0x23``
  1245. + - ``-``
  1246. + - ``LATCH_LOCK``
  1247. + - Lock the latch.
  1248. +
  1249. + * - ``0xA5``
  1250. + - ``0x24``
  1251. + - ``-``
  1252. + - ``LATCH_UNLOCK``
  1253. + - Unlock the latch.
  1254. +
  1255. + * - ``0xA5``
  1256. + - ``0x25``
  1257. + - ``-``
  1258. + - ``LATCH_REQUEST``
  1259. + - Request clipboard detachment.
  1260. +
  1261. + * - ``0xA5``
  1262. + - ``0x26``
  1263. + - ``-``
  1264. + - ``LATCH_CONFIRM``
  1265. + - Confirm clipboard detachment request.
  1266. +
  1267. + * - ``0xA5``
  1268. + - ``0x27``
  1269. + - ``-``
  1270. + - ``LATCH_HEARTBEAT``
  1271. + - Send heartbeat signal to EC.
  1272. +
  1273. + * - ``0xA5``
  1274. + - ``0x28``
  1275. + - ``-``
  1276. + - ``LATCH_CANCEL``
  1277. + - Cancel detachment process.
  1278. +
  1279. + * - ``0xA5``
  1280. + - ``0x29``
  1281. + - ``R``
  1282. + - ``GET_BASE_INFO``
  1283. + - Get current base/connection information.
  1284. +
  1285. + * - ``0xA5``
  1286. + - ``0x2A``
  1287. + - ``R``
  1288. + - ``GET_DEVICE_MODE``
  1289. + - Get current device operation mode.
  1290. +
  1291. + * - ``0xA5``
  1292. + - ``0x2B``
  1293. + - ``R``
  1294. + - ``GET_LATCH_STATUS``
  1295. + - Get current device latch status.
  1296. +
  1297. +``SDTX_IOCTL_EVENTS_ENABLE``
  1298. +^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1299. +
  1300. +Defined as ``_IO(0xA5, 0x22)``.
  1301. +
  1302. +Enable events for the current file descriptor. Events can be obtained by
  1303. +reading from the device, if enabled. Events are disabled by default.
  1304. +
  1305. +``SDTX_IOCTL_EVENTS_DISABLE``
  1306. +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1307. +
  1308. +Defined as ``_IO(0xA5, 0x22)``.
  1309. +
  1310. +Disable events for the current file descriptor. Events can be obtained by
  1311. +reading from the device, if enabled. Events are disabled by default.
  1312. +
  1313. +``SDTX_IOCTL_LATCH_LOCK``
  1314. +^^^^^^^^^^^^^^^^^^^^^^^^^
  1315. +
  1316. +Defined as ``_IO(0xA5, 0x23)``.
  1317. +
  1318. +Locks the latch, causing the detachment procedure to abort without opening
  1319. +the latch on timeout. The latch is unlocked by default. This command will be
  1320. +silently ignored if the latch is already locked.
  1321. +
  1322. +``SDTX_IOCTL_LATCH_UNLOCK``
  1323. +^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1324. +
  1325. +Defined as ``_IO(0xA5, 0x24)``.
  1326. +
  1327. +Unlocks the latch, causing the detachment procedure to open the latch on
  1328. +timeout. The latch is unlocked by default. This command will not open the
  1329. +latch when sent during an ongoing detachment process. It will be silently
  1330. +ignored if the latch is already unlocked.
  1331. +
  1332. +``SDTX_IOCTL_LATCH_REQUEST``
  1333. +^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1334. +
  1335. +Defined as ``_IO(0xA5, 0x25)``.
  1336. +
  1337. +Generic latch request. Behavior depends on the context: If no
  1338. +detachment-process is active, detachment is requested. Otherwise the
  1339. +currently active detachment-process will be aborted.
  1340. +
  1341. +If a detachment process is canceled by this operation, a generic detachment
  1342. +request event (``SDTX_EVENT_REQUEST``) will be sent.
  1343. +
  1344. +This essentially behaves the same as a detachment button press.
  1345. +
  1346. +``SDTX_IOCTL_LATCH_CONFIRM``
  1347. +^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1348. +
  1349. +Defined as ``_IO(0xA5, 0x26)``.
  1350. +
  1351. +Acknowledges and confirms a latch request. If sent during an ongoing
  1352. +detachment process, this command causes the latch to be opened immediately.
  1353. +The latch will also be opened if it has been locked. In this case, the latch
  1354. +lock is reset to the unlocked state.
  1355. +
  1356. +This command will be silently ignored if there is currently no detachment
  1357. +procedure in progress.
  1358. +
  1359. +``SDTX_IOCTL_LATCH_HEARTBEAT``
  1360. +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1361. +
  1362. +Defined as ``_IO(0xA5, 0x27)``.
  1363. +
  1364. +Sends a heartbeat, essentially resetting the detachment timeout. This
  1365. +command can be used to keep the detachment process alive while work required
  1366. +for the detachment to succeed is still in progress.
  1367. +
  1368. +This command will be silently ignored if there is currently no detachment
  1369. +procedure in progress.
  1370. +
  1371. +``SDTX_IOCTL_LATCH_CANCEL``
  1372. +^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1373. +
  1374. +Defined as ``_IO(0xA5, 0x28)``.
  1375. +
  1376. +Cancels detachment in progress (if any). If a detachment process is canceled
  1377. +by this operation, a generic detachment request event
  1378. +(``SDTX_EVENT_REQUEST``) will be sent.
  1379. +
  1380. +This command will be silently ignored if there is currently no detachment
  1381. +procedure in progress.
  1382. +
  1383. +``SDTX_IOCTL_GET_BASE_INFO``
  1384. +^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1385. +
  1386. +Defined as ``_IOR(0xA5, 0x29, struct sdtx_base_info)``.
  1387. +
  1388. +Get the current base connection state (i.e. attached/detached) and the type
  1389. +of the base connected to the clipboard. This is command essentially provides
  1390. +a way to query the information provided by the base connection change event
  1391. +(``SDTX_EVENT_BASE_CONNECTION``).
  1392. +
  1393. +Possible values for ``struct sdtx_base_info.state`` are:
  1394. +
  1395. +* ``SDTX_BASE_DETACHED``,
  1396. +* ``SDTX_BASE_ATTACHED``, and
  1397. +* ``SDTX_DETACH_NOT_FEASIBLE``.
  1398. +
  1399. +Other values are reserved for future use.
  1400. +
  1401. +``SDTX_IOCTL_GET_DEVICE_MODE``
  1402. +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1403. +
  1404. +Defined as ``_IOR(0xA5, 0x2A, __u16)``.
  1405. +
  1406. +Returns the device operation mode, indicating if and how the base is
  1407. +attached to the clipboard. This is command essentially provides a way to
  1408. +query the information provided by the device mode change event
  1409. +(``SDTX_EVENT_DEVICE_MODE``).
  1410. +
  1411. +Returned values are:
  1412. +
  1413. +* ``SDTX_DEVICE_MODE_LAPTOP``
  1414. +* ``SDTX_DEVICE_MODE_TABLET``
  1415. +* ``SDTX_DEVICE_MODE_STUDIO``
  1416. +
  1417. +See |sdtx_device_mode| for details. Other values are reserved for future
  1418. +use.
  1419. +
  1420. +
  1421. +``SDTX_IOCTL_GET_LATCH_STATUS``
  1422. +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1423. +
  1424. +Defined as ``_IOR(0xA5, 0x2B, __u16)``.
  1425. +
  1426. +Get the current latch status or (presumably) the last error encountered when
  1427. +trying to open/close the latch. This is command essentially provides a way
  1428. +to query the information provided by the latch status change event
  1429. +(``SDTX_EVENT_LATCH_STATUS``).
  1430. +
  1431. +Returned values are:
  1432. +
  1433. +* ``SDTX_LATCH_CLOSED``,
  1434. +* ``SDTX_LATCH_OPENED``,
  1435. +* ``SDTX_ERR_FAILED_TO_OPEN``,
  1436. +* ``SDTX_ERR_FAILED_TO_REMAIN_OPEN``, and
  1437. +* ``SDTX_ERR_FAILED_TO_CLOSE``.
  1438. +
  1439. +Other values are reserved for future use.
  1440. +
  1441. +A Note on Base IDs
  1442. +------------------
  1443. +
  1444. +Base types/IDs provided via ``SDTX_EVENT_BASE_CONNECTION`` or
  1445. +``SDTX_IOCTL_GET_BASE_INFO`` are directly forwarded from from the EC in the
  1446. +lower byte of the combined |__u16| value, with the driver storing the EC
  1447. +type from which this ID comes in the high byte (without this, base IDs over
  1448. +different types of ECs may be overlapping).
  1449. +
  1450. +The ``SDTX_DEVICE_TYPE()`` macro can be used to determine the EC device
  1451. +type. This can be one of
  1452. +
  1453. +* ``SDTX_DEVICE_TYPE_HID``, for Surface Aggregator Module over HID, and
  1454. +
  1455. +* ``SDTX_DEVICE_TYPE_SSH``, for Surface Aggregator Module over Surface Serial
  1456. + Hub.
  1457. +
  1458. +Note that currently only the ``SSH`` type EC is supported, however ``HID``
  1459. +type is reserved for future use.
  1460. +
  1461. +Structures and Enums
  1462. +--------------------
  1463. +
  1464. +.. kernel-doc:: include/uapi/linux/surface_aggregator/dtx.h
  1465. diff --git a/Documentation/driver-api/surface_aggregator/clients/index.rst b/Documentation/driver-api/surface_aggregator/clients/index.rst
  1466. new file mode 100644
  1467. index 000000000000..98ea9946b8a2
  1468. --- /dev/null
  1469. +++ b/Documentation/driver-api/surface_aggregator/clients/index.rst
  1470. @@ -0,0 +1,22 @@
  1471. +.. SPDX-License-Identifier: GPL-2.0+
  1472. +
  1473. +===========================
  1474. +Client Driver Documentation
  1475. +===========================
  1476. +
  1477. +This is the documentation for client drivers themselves. Refer to
  1478. +:doc:`../client` for documentation on how to write client drivers.
  1479. +
  1480. +.. toctree::
  1481. + :maxdepth: 1
  1482. +
  1483. + cdev
  1484. + dtx
  1485. + san
  1486. +
  1487. +.. only:: subproject and html
  1488. +
  1489. + Indices
  1490. + =======
  1491. +
  1492. + * :ref:`genindex`
  1493. diff --git a/Documentation/driver-api/surface_aggregator/clients/san.rst b/Documentation/driver-api/surface_aggregator/clients/san.rst
  1494. new file mode 100644
  1495. index 000000000000..1bf830ad367d
  1496. --- /dev/null
  1497. +++ b/Documentation/driver-api/surface_aggregator/clients/san.rst
  1498. @@ -0,0 +1,44 @@
  1499. +.. SPDX-License-Identifier: GPL-2.0+
  1500. +
  1501. +.. |san_client_link| replace:: :c:func:`san_client_link`
  1502. +.. |san_dgpu_notifier_register| replace:: :c:func:`san_dgpu_notifier_register`
  1503. +.. |san_dgpu_notifier_unregister| replace:: :c:func:`san_dgpu_notifier_unregister`
  1504. +
  1505. +===================
  1506. +Surface ACPI Notify
  1507. +===================
  1508. +
  1509. +The Surface ACPI Notify (SAN) device provides the bridge between ACPI and
  1510. +SAM controller. Specifically, ACPI code can execute requests and handle
  1511. +battery and thermal events via this interface. In addition to this, events
  1512. +relating to the discrete GPU (dGPU) of the Surface Book 2 can be sent from
  1513. +ACPI code (note: the Surface Book 3 uses a different method for this). The
  1514. +only currently known event sent via this interface is a dGPU power-on
  1515. +notification. While this driver handles the former part internally, it only
  1516. +relays the dGPU events to any other driver interested via its public API and
  1517. +does not handle them.
  1518. +
  1519. +The public interface of this driver is split into two parts: Client
  1520. +registration and notifier-block registration.
  1521. +
  1522. +A client to the SAN interface can be linked as consumer to the SAN device
  1523. +via |san_client_link|. This can be used to ensure that the a client
  1524. +receiving dGPU events does not miss any events due to the SAN interface not
  1525. +being set up as this forces the client driver to unbind once the SAN driver
  1526. +is unbound.
  1527. +
  1528. +Notifier-blocks can be registered by any device for as long as the module is
  1529. +loaded, regardless of being linked as client or not. Registration is done
  1530. +with |san_dgpu_notifier_register|. If the notifier is not needed any more, it
  1531. +should be unregistered via |san_dgpu_notifier_unregister|.
  1532. +
  1533. +Consult the API documentation below for more details.
  1534. +
  1535. +
  1536. +API Documentation
  1537. +=================
  1538. +
  1539. +.. kernel-doc:: include/linux/surface_acpi_notify.h
  1540. +
  1541. +.. kernel-doc:: drivers/misc/surface_aggregator/clients/surface_acpi_notify.c
  1542. + :export:
  1543. diff --git a/Documentation/driver-api/surface_aggregator/index.rst b/Documentation/driver-api/surface_aggregator/index.rst
  1544. new file mode 100644
  1545. index 000000000000..6f3e1094904d
  1546. --- /dev/null
  1547. +++ b/Documentation/driver-api/surface_aggregator/index.rst
  1548. @@ -0,0 +1,21 @@
  1549. +.. SPDX-License-Identifier: GPL-2.0+
  1550. +
  1551. +=======================================
  1552. +Surface System Aggregator Module (SSAM)
  1553. +=======================================
  1554. +
  1555. +.. toctree::
  1556. + :maxdepth: 2
  1557. +
  1558. + overview
  1559. + client
  1560. + clients/index
  1561. + ssh
  1562. + internal
  1563. +
  1564. +.. only:: subproject and html
  1565. +
  1566. + Indices
  1567. + =======
  1568. +
  1569. + * :ref:`genindex`
  1570. diff --git a/Documentation/driver-api/surface_aggregator/internal-api.rst b/Documentation/driver-api/surface_aggregator/internal-api.rst
  1571. new file mode 100644
  1572. index 000000000000..db6a70119f49
  1573. --- /dev/null
  1574. +++ b/Documentation/driver-api/surface_aggregator/internal-api.rst
  1575. @@ -0,0 +1,67 @@
  1576. +.. SPDX-License-Identifier: GPL-2.0+
  1577. +
  1578. +==========================
  1579. +Internal API Documentation
  1580. +==========================
  1581. +
  1582. +.. contents::
  1583. + :depth: 2
  1584. +
  1585. +
  1586. +Packet Transport Layer
  1587. +======================
  1588. +
  1589. +.. kernel-doc:: drivers/misc/surface_aggregator/ssh_parser.h
  1590. + :internal:
  1591. +
  1592. +.. kernel-doc:: drivers/misc/surface_aggregator/ssh_parser.c
  1593. + :internal:
  1594. +
  1595. +.. kernel-doc:: drivers/misc/surface_aggregator/ssh_msgb.h
  1596. + :internal:
  1597. +
  1598. +.. kernel-doc:: drivers/misc/surface_aggregator/ssh_packet_layer.h
  1599. + :internal:
  1600. +
  1601. +.. kernel-doc:: drivers/misc/surface_aggregator/ssh_packet_layer.c
  1602. + :internal:
  1603. +
  1604. +
  1605. +Request Transport Layer
  1606. +=======================
  1607. +
  1608. +.. kernel-doc:: drivers/misc/surface_aggregator/ssh_request_layer.h
  1609. + :internal:
  1610. +
  1611. +.. kernel-doc:: drivers/misc/surface_aggregator/ssh_request_layer.c
  1612. + :internal:
  1613. +
  1614. +
  1615. +Controller
  1616. +==========
  1617. +
  1618. +.. kernel-doc:: drivers/misc/surface_aggregator/controller.h
  1619. + :internal:
  1620. +
  1621. +.. kernel-doc:: drivers/misc/surface_aggregator/controller.c
  1622. + :internal:
  1623. +
  1624. +
  1625. +Client Device Bus
  1626. +=================
  1627. +
  1628. +.. kernel-doc:: drivers/misc/surface_aggregator/bus.c
  1629. + :internal:
  1630. +
  1631. +
  1632. +Core
  1633. +====
  1634. +
  1635. +.. kernel-doc:: drivers/misc/surface_aggregator/core.c
  1636. + :internal:
  1637. +
  1638. +
  1639. +Trace Helpers
  1640. +=============
  1641. +
  1642. +.. kernel-doc:: drivers/misc/surface_aggregator/trace.h
  1643. diff --git a/Documentation/driver-api/surface_aggregator/internal.rst b/Documentation/driver-api/surface_aggregator/internal.rst
  1644. new file mode 100644
  1645. index 000000000000..72704734982a
  1646. --- /dev/null
  1647. +++ b/Documentation/driver-api/surface_aggregator/internal.rst
  1648. @@ -0,0 +1,577 @@
  1649. +.. SPDX-License-Identifier: GPL-2.0+
  1650. +
  1651. +.. |ssh_ptl| replace:: :c:type:`struct ssh_ptl <ssh_ptl>`
  1652. +.. |ssh_ptl_submit| replace:: :c:func:`ssh_ptl_submit`
  1653. +.. |ssh_ptl_cancel| replace:: :c:func:`ssh_ptl_cancel`
  1654. +.. |ssh_ptl_shutdown| replace:: :c:func:`ssh_ptl_shutdown`
  1655. +.. |ssh_ptl_rx_rcvbuf| replace:: :c:func:`ssh_ptl_rx_rcvbuf`
  1656. +.. |ssh_rtl| replace:: :c:type:`struct ssh_rtl <ssh_rtl>`
  1657. +.. |ssh_rtl_submit| replace:: :c:func:`ssh_rtl_submit`
  1658. +.. |ssh_rtl_cancel| replace:: :c:func:`ssh_rtl_cancel`
  1659. +.. |ssh_rtl_shutdown| replace:: :c:func:`ssh_rtl_shutdown`
  1660. +.. |ssh_packet| replace:: :c:type:`struct ssh_packet <ssh_packet>`
  1661. +.. |ssh_packet_get| replace:: :c:func:`ssh_packet_get`
  1662. +.. |ssh_packet_put| replace:: :c:func:`ssh_packet_put`
  1663. +.. |ssh_packet_ops| replace:: :c:type:`struct ssh_packet_ops <ssh_packet_ops>`
  1664. +.. |ssh_packet_base_priority| replace:: :c:type:`enum ssh_packet_base_priority <ssh_packet_base_priority>`
  1665. +.. |ssh_packet_flags| replace:: :c:type:`enum ssh_packet_flags <ssh_packet_flags>`
  1666. +.. |SSH_PACKET_PRIORITY| replace:: :c:func:`SSH_PACKET_PRIORITY`
  1667. +.. |ssh_frame| replace:: :c:type:`struct ssh_frame <ssh_frame>`
  1668. +.. |ssh_command| replace:: :c:type:`struct ssh_command <ssh_command>`
  1669. +.. |ssh_request| replace:: :c:type:`struct ssh_request <ssh_request>`
  1670. +.. |ssh_request_get| replace:: :c:func:`ssh_request_get`
  1671. +.. |ssh_request_put| replace:: :c:func:`ssh_request_put`
  1672. +.. |ssh_request_ops| replace:: :c:type:`struct ssh_request_ops <ssh_request_ops>`
  1673. +.. |ssh_request_init| replace:: :c:func:`ssh_request_init`
  1674. +.. |ssh_request_flags| replace:: :c:type:`enum ssh_request_flags <ssh_request_flags>`
  1675. +.. |ssam_controller| replace:: :c:type:`struct ssam_controller <ssam_controller>`
  1676. +.. |ssam_device| replace:: :c:type:`struct ssam_device <ssam_device>`
  1677. +.. |ssam_device_driver| replace:: :c:type:`struct ssam_device_driver <ssam_device_driver>`
  1678. +.. |ssam_client_bind| replace:: :c:func:`ssam_client_bind`
  1679. +.. |ssam_client_link| replace:: :c:func:`ssam_client_link`
  1680. +.. |ssam_request_sync| replace:: :c:type:`struct ssam_request_sync <ssam_request_sync>`
  1681. +.. |ssam_event_registry| replace:: :c:type:`struct ssam_event_registry <ssam_event_registry>`
  1682. +.. |ssam_event_id| replace:: :c:type:`struct ssam_event_id <ssam_event_id>`
  1683. +.. |ssam_nf| replace:: :c:type:`struct ssam_nf <ssam_nf>`
  1684. +.. |ssam_nf_refcount_inc| replace:: :c:func:`ssam_nf_refcount_inc`
  1685. +.. |ssam_nf_refcount_dec| replace:: :c:func:`ssam_nf_refcount_dec`
  1686. +.. |ssam_notifier_register| replace:: :c:func:`ssam_notifier_register`
  1687. +.. |ssam_notifier_unregister| replace:: :c:func:`ssam_notifier_unregister`
  1688. +.. |ssam_cplt| replace:: :c:type:`struct ssam_cplt <ssam_cplt>`
  1689. +.. |ssam_event_queue| replace:: :c:type:`struct ssam_event_queue <ssam_event_queue>`
  1690. +.. |ssam_request_sync_submit| replace:: :c:func:`ssam_request_sync_submit`
  1691. +
  1692. +=====================
  1693. +Core Driver Internals
  1694. +=====================
  1695. +
  1696. +Architectural overview of the Surface System Aggregator Module (SSAM) core
  1697. +and Surface Serial Hub (SSH) driver. For the API documentation, refer to:
  1698. +
  1699. +.. toctree::
  1700. + :maxdepth: 2
  1701. +
  1702. + internal-api
  1703. +
  1704. +
  1705. +Overview
  1706. +========
  1707. +
  1708. +The SSAM core implementation is structured in layers, somewhat following the
  1709. +SSH protocol structure:
  1710. +
  1711. +Lower-level packet transport is implemented in the *packet transport layer
  1712. +(PTL)*, directly building on top of the serial device (serdev)
  1713. +infrastructure of the kernel. As the name indicates, this layer deals with
  1714. +the packet transport logic and handles things like packet validation, packet
  1715. +acknowledgment (ACKing), packet (retransmission) timeouts, and relaying
  1716. +packet payloads to higher-level layers.
  1717. +
  1718. +Above this sits the *request transport layer (RTL)*. This layer is centered
  1719. +around command-type packet payloads, i.e. requests (sent from host to EC),
  1720. +responses of the EC to those requests, and events (sent from EC to host).
  1721. +It, specifically, distinguishes events from request responses, matches
  1722. +responses to their corresponding requests, and implements request timeouts.
  1723. +
  1724. +The *controller* layer is building on top of this and essentially decides
  1725. +how request responses and, especially, events are dealt with. It provides an
  1726. +event notifier system, handles event activation/deactivation, provides a
  1727. +workqueue for event and asynchronous request completion, and also manages
  1728. +the message counters required for building command messages (``SEQ``,
  1729. +``RQID``). This layer basically provides a fundamental interface to the SAM
  1730. +EC for use in other kernel drivers.
  1731. +
  1732. +While the controller layer already provides an interface for other kernel
  1733. +drivers, the client *bus* extends this interface to provide support for
  1734. +native SSAM devices, i.e. devices that are not defined in ACPI and not
  1735. +implemented as platform devices, via |ssam_device| and |ssam_device_driver|
  1736. +simplify management of client devices and client drivers.
  1737. +
  1738. +Refer to :doc:`client` for documentation regarding the client device/driver
  1739. +API and interface options for other kernel drivers. It is recommended to
  1740. +familiarize oneself with that chapter and the :doc:`ssh` before continuing
  1741. +with the architectural overview below.
  1742. +
  1743. +
  1744. +Packet Transport Layer
  1745. +======================
  1746. +
  1747. +The packet transport layer is represented via |ssh_ptl| and is structured
  1748. +around the following key concepts:
  1749. +
  1750. +Packets
  1751. +-------
  1752. +
  1753. +Packets are the fundamental transmission unit of the SSH protocol. They are
  1754. +managed by the packet transport layer, which is essentially the lowest layer
  1755. +of the driver and is built upon by other components of the SSAM core.
  1756. +Packets to be transmitted by the SSAM core are represented via |ssh_packet|
  1757. +(in contrast, packets received by the core do not have any specific
  1758. +structure and are managed entirely via the raw |ssh_frame|).
  1759. +
  1760. +This structure contains the required fields to manage the packet inside the
  1761. +transport layer, as well as a reference to the buffer containing the data to
  1762. +be transmitted (i.e. the message wrapped in |ssh_frame|). Most notably, it
  1763. +contains an internal reference count, which is used for managing its
  1764. +lifetime (accessible via |ssh_packet_get| and |ssh_packet_put|). When this
  1765. +counter reaches zero, the ``release()`` callback provided to the packet via
  1766. +its |ssh_packet_ops| reference is executed, which may then deallocate the
  1767. +packet or its enclosing structure (e.g. |ssh_request|).
  1768. +
  1769. +In addition to the ``release`` callback, the |ssh_packet_ops| reference also
  1770. +provides a ``complete()`` callback, which is run once the packet has been
  1771. +completed and provides the status of this completion, i.e. zero on success
  1772. +or a negative errno value in case of an error. Once the packet has been
  1773. +submitted to the packet transport layer, the ``complete()`` callback is
  1774. +always guaranteed to be executed before the ``release()`` callback, i.e. the
  1775. +packet will always be completed, either successfully, with an error, or due
  1776. +to cancellation, before it will be released.
  1777. +
  1778. +The state of a packet is managed via its ``state`` flags
  1779. +(|ssh_packet_flags|), which also contains the packet type. In particular,
  1780. +the following bits are noteworthy:
  1781. +
  1782. +* ``SSH_PACKET_SF_LOCKED_BIT``: This bit is set when completion, either
  1783. + through error or success, is imminent. It indicates that no further
  1784. + references of the packet should be taken and any existing references
  1785. + should be dropped as soon as possible. The process setting this bit is
  1786. + responsible for removing any references to this packet from the packet
  1787. + queue and pending set.
  1788. +
  1789. +* ``SSH_PACKET_SF_COMPLETED_BIT``: This bit is set by the process running the
  1790. + ``complete()`` callback and is used to ensure that this callback only runs
  1791. + once.
  1792. +
  1793. +* ``SSH_PACKET_SF_QUEUED_BIT``: This bit is set when the packet is queued on
  1794. + the packet queue and cleared when it is dequeued.
  1795. +
  1796. +* ``SSH_PACKET_SF_PENDING_BIT``: This bit is set when the packet is added to
  1797. + the pending set and cleared when it is removed from it.
  1798. +
  1799. +Packet Queue
  1800. +------------
  1801. +
  1802. +The packet queue is the first of the two fundamental collections in the
  1803. +packet transport layer. It is a priority queue, with priority of the
  1804. +respective packets based on the packet type (major) and number of tries
  1805. +(minor). See |SSH_PACKET_PRIORITY| for more details on the priority value.
  1806. +
  1807. +All packets to be transmitted by the transport layer must be submitted to
  1808. +this queue via |ssh_ptl_submit|. Note that this includes control packets
  1809. +sent by the transport layer itself. Internally, data packets can be
  1810. +re-submitted to this queue due to timeouts or NAK packets sent by the EC.
  1811. +
  1812. +Pending Set
  1813. +-----------
  1814. +
  1815. +The pending set is the second of the two fundamental collections in the
  1816. +packet transport layer. It stores references to packets that have already
  1817. +been transmitted, but wait for acknowledgment (e.g. the corresponding ACK
  1818. +packet) by the EC.
  1819. +
  1820. +Note that a packet may both be pending and queued if it has been
  1821. +re-submitted due to a packet acknowledgment timeout or NAK. On such a
  1822. +re-submission, packets are not removed from the pending set.
  1823. +
  1824. +Transmitter Thread
  1825. +------------------
  1826. +
  1827. +The transmitter thread is responsible for most of the actual work regarding
  1828. +packet transmission. In each iteration, it (waits for and) checks if the
  1829. +next packet on the queue (if any) can be transmitted and, if so, removes it
  1830. +from the queue and increments its counter for the number of transmission
  1831. +attempts, i.e. tries. If the packet is sequenced, i.e. requires an ACK by
  1832. +the EC, the packet is added to the pending set. Next, the packet's data is
  1833. +submitted to the serdev subsystem. In case of an error or timeout during
  1834. +this submission, the packet is completed by the transmitter thread with the
  1835. +status value of the callback set accordingly. In case the packet is
  1836. +unsequenced, i.e. does not require an ACK by the EC, the packet is completed
  1837. +with success on the transmitter thread.
  1838. +
  1839. +Transmission of sequenced packets is limited by the number of concurrently
  1840. +pending packets, i.e. a limit on how many packets may be waiting for an ACK
  1841. +from the EC in parallel. This limit is currently set to one (see :doc:`ssh`
  1842. +for the reasoning behind this). Control packets (i.e. ACK and NAK) can
  1843. +always be transmitted.
  1844. +
  1845. +Receiver Thread
  1846. +---------------
  1847. +
  1848. +Any data received from the EC is put into a FIFO buffer for further
  1849. +processing. This processing happens on the receiver thread. The receiver
  1850. +thread parses and validates the received message into its |ssh_frame| and
  1851. +corresponding payload. It prepares and submits the necessary ACK (and on
  1852. +validation error or invalid data NAK) packets for the received messages.
  1853. +
  1854. +This thread also handles further processing, such as matching ACK messages
  1855. +to the corresponding pending packet (via sequence ID) and completing it, as
  1856. +well as initiating re-submission of all currently pending packets on
  1857. +receival of a NAK message (re-submission in case of a NAK is similar to
  1858. +re-submission due to timeout, see below for more details on that). Note that
  1859. +the successful completion of a sequenced packet will always run on the
  1860. +receiver thread (whereas any failure-indicating completion will run on the
  1861. +process where the failure occurred).
  1862. +
  1863. +Any payload data is forwarded via a callback to the next upper layer, i.e.
  1864. +the request transport layer.
  1865. +
  1866. +Timeout Reaper
  1867. +--------------
  1868. +
  1869. +The packet acknowledgment timeout is a per-packet timeout for sequenced
  1870. +packets, started when the respective packet begins (re-)transmission (i.e.
  1871. +this timeout is armed once per transmission attempt on the transmitter
  1872. +thread). It is used to trigger re-submission or, when the number of tries
  1873. +has been exceeded, cancellation of the packet in question.
  1874. +
  1875. +This timeout is handled via a dedicated reaper task, which is essentially a
  1876. +work item (re-)scheduled to run when the next packet is set to time out. The
  1877. +work item then checks the set of pending packets for any packets that have
  1878. +exceeded the timeout and, if there are any remaining packets, re-schedules
  1879. +itself to the next appropriate point in time.
  1880. +
  1881. +If a timeout has been detected by the reaper, the packet will either be
  1882. +re-submitted if it still has some remaining tries left, or completed with
  1883. +``-ETIMEDOUT`` as status if not. Note that re-submission, in this case and
  1884. +triggered by receival of a NAK, means that the packet is added to the queue
  1885. +with a now incremented number of tries, yielding a higher priority. The
  1886. +timeout for the packet will be disabled until the next transmission attempt
  1887. +and the packet remains on the pending set.
  1888. +
  1889. +Note that due to transmission and packet acknowledgment timeouts, the packet
  1890. +transport layer is always guaranteed to make progress, if only through
  1891. +timing out packets, and will never fully block.
  1892. +
  1893. +Concurrency and Locking
  1894. +-----------------------
  1895. +
  1896. +There are two main locks in the packet transport layer: One guarding access
  1897. +to the packet queue and one guarding access to the pending set. These
  1898. +collections may only be accessed and modified under the respective lock. If
  1899. +access to both collections is needed, the pending lock must be acquired
  1900. +before the queue lock to avoid deadlocks.
  1901. +
  1902. +In addition to guarding the collections, after initial packet submission
  1903. +certain packet fields may only be accessed under one of the locks.
  1904. +Specifically, the packet priority must only be accessed while holding the
  1905. +queue lock and the packet timestamp must only be accessed while holding the
  1906. +pending lock.
  1907. +
  1908. +Other parts of the packet transport layer are guarded independently. State
  1909. +flags are managed by atomic bit operations and, if necessary, memory
  1910. +barriers. Modifications to the timeout reaper work item and expiration date
  1911. +are guarded by their own lock.
  1912. +
  1913. +The reference of the packet to the packet transport layer (``ptl``) is
  1914. +somewhat special. It is either set when the upper layer request is submitted
  1915. +or, if there is none, when the packet is first submitted. After it is set,
  1916. +it will not change its value. Functions that may run concurrently with
  1917. +submission, i.e. cancellation, can not rely on the ``ptl`` reference to be
  1918. +set. Access to it in these functions is guarded by ``READ_ONCE()``, whereas
  1919. +setting ``ptl`` is equally guarded with ``WRITE_ONCE()`` for symmetry.
  1920. +
  1921. +Some packet fields may be read outside of the respective locks guarding
  1922. +them, specifically priority and state for tracing. In those cases, proper
  1923. +access is ensured by employing ``WRITE_ONCE()`` and ``READ_ONCE()``. Such
  1924. +read-only access is only allowed when stale values are not critical.
  1925. +
  1926. +With respect to the interface for higher layers, packet submission
  1927. +(|ssh_ptl_submit|), packet cancellation (|ssh_ptl_cancel|), data receival
  1928. +(|ssh_ptl_rx_rcvbuf|), and layer shutdown (|ssh_ptl_shutdown|) may always be
  1929. +executed concurrently with respect to each other. Note that packet
  1930. +submission may not run concurrently with itself for the same packet.
  1931. +Equally, shutdown and data receival may also not run concurrently with
  1932. +themselves (but may run concurrently with each other).
  1933. +
  1934. +
  1935. +Request Transport Layer
  1936. +=======================
  1937. +
  1938. +The request transport layer is represented via |ssh_rtl| and builds on top
  1939. +of the packet transport layer. It deals with requests, i.e. SSH packets sent
  1940. +by the host containing a |ssh_command| as frame payload. This layer
  1941. +separates responses to requests from events, which are also sent by the EC
  1942. +via a |ssh_command| payload. While responses are handled in this layer,
  1943. +events are relayed to the next upper layer, i.e. the controller layer, via
  1944. +the corresponding callback. The request transport layer is structured around
  1945. +the following key concepts:
  1946. +
  1947. +Request
  1948. +-------
  1949. +
  1950. +Requests are packets with a command-type payload, sent from host to EC to
  1951. +query data from or trigger an action on it (or both simultaneously). They
  1952. +are represented by |ssh_request|, wrapping the underlying |ssh_packet|
  1953. +storing its message data (i.e. SSH frame with command payload). Note that
  1954. +all top-level representations, e.g. |ssam_request_sync| are built upon this
  1955. +struct.
  1956. +
  1957. +As |ssh_request| extends |ssh_packet|, its lifetime is also managed by the
  1958. +reference counter inside the packet struct (which can be accessed via
  1959. +|ssh_request_get| and |ssh_request_put|). Once the counter reaches zero, the
  1960. +``release()`` callback of the |ssh_request_ops| reference of the request is
  1961. +called.
  1962. +
  1963. +Requests can have an optional response that is equally sent via a SSH
  1964. +message with command-type payload (from EC to host). The party constructing
  1965. +the request must know if a response is expected and mark this in the request
  1966. +flags provided to |ssh_request_init|, so that the request transport layer
  1967. +can wait for this response.
  1968. +
  1969. +Similar to |ssh_packet|, |ssh_request| also has a ``complete()`` callback
  1970. +provided via its request ops reference and is guaranteed to be completed
  1971. +before it is released once it has been submitted to the request transport
  1972. +layer via |ssh_rtl_submit|. For a request without a response, successful
  1973. +completion will occur once the underlying packet has been successfully
  1974. +transmitted by the packet transport layer (i.e. from within the packet
  1975. +completion callback). For a request with response, successful completion
  1976. +will occur once the response has been received and matched to the request
  1977. +via its request ID (which happens on the packet layer's data-received
  1978. +callback running on the receiver thread). If the request is completed with
  1979. +an error, the status value will be set to the corresponding (negative) errno
  1980. +value.
  1981. +
  1982. +The state of a request is again managed via its ``state`` flags
  1983. +(|ssh_request_flags|), which also encode the request type. In particular,
  1984. +the following bits are noteworthy:
  1985. +
  1986. +* ``SSH_REQUEST_SF_LOCKED_BIT``: This bit is set when completion, either
  1987. + through error or success, is imminent. It indicates that no further
  1988. + references of the request should be taken and any existing references
  1989. + should be dropped as soon as possible. The process setting this bit is
  1990. + responsible for removing any references to this request from the request
  1991. + queue and pending set.
  1992. +
  1993. +* ``SSH_REQUEST_SF_COMPLETED_BIT``: This bit is set by the process running the
  1994. + ``complete()`` callback and is used to ensure that this callback only runs
  1995. + once.
  1996. +
  1997. +* ``SSH_REQUEST_SF_QUEUED_BIT``: This bit is set when the request is queued on
  1998. + the request queue and cleared when it is dequeued.
  1999. +
  2000. +* ``SSH_REQUEST_SF_PENDING_BIT``: This bit is set when the request is added to
  2001. + the pending set and cleared when it is removed from it.
  2002. +
  2003. +Request Queue
  2004. +-------------
  2005. +
  2006. +The request queue is the first of the two fundamental collections in the
  2007. +request transport layer. In contrast to the packet queue of the packet
  2008. +transport layer, it is not a priority queue and the simple first come first
  2009. +serve principle applies.
  2010. +
  2011. +All requests to be transmitted by the request transport layer must be
  2012. +submitted to this queue via |ssh_rtl_submit|. Once submitted, requests may
  2013. +not be re-submitted, and will not be re-submitted automatically on timeout.
  2014. +Instead, the request is completed with a timeout error. If desired, the
  2015. +caller can create and submit a new request for another try, but it must not
  2016. +submit the same request again.
  2017. +
  2018. +Pending Set
  2019. +-----------
  2020. +
  2021. +The pending set is the second of the two fundamental collections in the
  2022. +request transport layer. This collection stores references to all pending
  2023. +requests, i.e. requests awaiting a response from the EC (similar to what the
  2024. +pending set of the packet transport layer does for packets).
  2025. +
  2026. +Transmitter Task
  2027. +----------------
  2028. +
  2029. +The transmitter task is scheduled when a new request is available for
  2030. +transmission. It checks if the next request on the request queue can be
  2031. +transmitted and, if so, submits its underlying packet to the packet
  2032. +transport layer. This check ensures that only a limited number of
  2033. +requests can be pending, i.e. waiting for a response, at the same time. If
  2034. +the request requires a response, the request is added to the pending set
  2035. +before its packet is submitted.
  2036. +
  2037. +Packet Completion Callback
  2038. +--------------------------
  2039. +
  2040. +The packet completion callback is executed once the underlying packet of a
  2041. +request has been completed. In case of an error completion, the
  2042. +corresponding request is completed with the error value provided in this
  2043. +callback.
  2044. +
  2045. +On successful packet completion, further processing depends on the request.
  2046. +If the request expects a response, it is marked as transmitted and the
  2047. +request timeout is started. If the request does not expect a response, it is
  2048. +completed with success.
  2049. +
  2050. +Data-Received Callback
  2051. +----------------------
  2052. +
  2053. +The data received callback notifies the request transport layer of data
  2054. +being received by the underlying packet transport layer via a data-type
  2055. +frame. In general, this is expected to be a command-type payload.
  2056. +
  2057. +If the request ID of the command is one of the request IDs reserved for
  2058. +events (one to ``SSH_NUM_EVENTS``, inclusively), it is forwarded to the
  2059. +event callback registered in the request transport layer. If the request ID
  2060. +indicates a response to a request, the respective request is looked up in
  2061. +the pending set and, if found and marked as transmitted, completed with
  2062. +success.
  2063. +
  2064. +Timeout Reaper
  2065. +--------------
  2066. +
  2067. +The request-response-timeout is a per-request timeout for requests expecting
  2068. +a response. It is used to ensure that a request does not wait indefinitely
  2069. +on a response from the EC and is started after the underlying packet has
  2070. +been successfully completed.
  2071. +
  2072. +This timeout is, similar to the packet acknowledgment timeout on the packet
  2073. +transport layer, handled via a dedicated reaper task. This task is
  2074. +essentially a work-item (re-)scheduled to run when the next request is set
  2075. +to time out. The work item then scans the set of pending requests for any
  2076. +requests that have timed out and completes them with ``-ETIMEDOUT`` as
  2077. +status. Requests will not be re-submitted automatically. Instead, the issuer
  2078. +of the request must construct and submit a new request, if so desired.
  2079. +
  2080. +Note that this timeout, in combination with packet transmission and
  2081. +acknowledgment timeouts, guarantees that the request layer will always make
  2082. +progress, even if only through timing out packets, and never fully block.
  2083. +
  2084. +Concurrency and Locking
  2085. +-----------------------
  2086. +
  2087. +Similar to the packet transport layer, there are two main locks in the
  2088. +request transport layer: One guarding access to the request queue and one
  2089. +guarding access to the pending set. These collections may only be accessed
  2090. +and modified under the respective lock.
  2091. +
  2092. +Other parts of the request transport layer are guarded independently. State
  2093. +flags are (again) managed by atomic bit operations and, if necessary, memory
  2094. +barriers. Modifications to the timeout reaper work item and expiration date
  2095. +are guarded by their own lock.
  2096. +
  2097. +Some request fields may be read outside of the respective locks guarding
  2098. +them, specifically the state for tracing. In those cases, proper access is
  2099. +ensured by employing ``WRITE_ONCE()`` and ``READ_ONCE()``. Such read-only
  2100. +access is only allowed when stale values are not critical.
  2101. +
  2102. +With respect to the interface for higher layers, request submission
  2103. +(|ssh_rtl_submit|), request cancellation (|ssh_rtl_cancel|), and layer
  2104. +shutdown (|ssh_rtl_shutdown|) may always be executed concurrently with
  2105. +respect to each other. Note that request submission may not run concurrently
  2106. +with itself for the same request (and also may only be called once per
  2107. +request). Equally, shutdown may also not run concurrently with itself.
  2108. +
  2109. +
  2110. +Controller Layer
  2111. +================
  2112. +
  2113. +The controller layer extends on the request transport layer to provide an
  2114. +easy-to-use interface for client drivers. It is represented by
  2115. +|ssam_controller| and the SSH driver. While the lower level transport layers
  2116. +take care of transmitting and handling packets and requests, the controller
  2117. +layer takes on more of a management role. Specifically, it handles device
  2118. +initialization, power management, and event handling, including event
  2119. +delivery and registration via the (event) completion system (|ssam_cplt|).
  2120. +
  2121. +Event Registration
  2122. +------------------
  2123. +
  2124. +In general, an event (or rather a class of events) has to be explicitly
  2125. +requested by the host before the EC will send it (HID input events seem to
  2126. +be the exception). This is done via an event-enable request (similarly,
  2127. +events should be disabled via an event-disable request once no longer
  2128. +desired).
  2129. +
  2130. +The specific request used to enable (or disable) an event is given via an
  2131. +event registry, i.e. the governing authority of this event (so to speak),
  2132. +represented by |ssam_event_registry|. As parameters to this request, the
  2133. +target category and, depending on the event registry, instance ID of the
  2134. +event to be enabled must be provided. This (optional) instance ID must be
  2135. +zero if the registry does not use it. Together, target category and instance
  2136. +ID form the event ID, represented by |ssam_event_id|. In short, both, event
  2137. +registry and event ID, are required to uniquely identify a respective class
  2138. +of events.
  2139. +
  2140. +Note that a further *request ID* parameter must be provided for the
  2141. +enable-event request. This parameter does not influence the class of events
  2142. +being enabled, but instead is set as the request ID (RQID) on each event of
  2143. +this class sent by the EC. It is used to identify events (as a limited
  2144. +number of request IDs is reserved for use in events only, specifically one
  2145. +to ``SSH_NUM_EVENTS`` inclusively) and also map events to their specific
  2146. +class. Currently, the controller always sets this parameter to the target
  2147. +category specified in |ssam_event_id|.
  2148. +
  2149. +As multiple client drivers may rely on the same (or overlapping) classes of
  2150. +events and enable/disable calls are strictly binary (i.e. on/off), the
  2151. +controller has to manage access to these events. It does so via reference
  2152. +counting, storing the counter inside an RB-tree based mapping with event
  2153. +registry and ID as key (there is no known list of valid event registry and
  2154. +event ID combinations). See |ssam_nf|, |ssam_nf_refcount_inc|, and
  2155. +|ssam_nf_refcount_dec| for details.
  2156. +
  2157. +This management is done together with notifier registration (described in
  2158. +the next section) via the top-level |ssam_notifier_register| and
  2159. +|ssam_notifier_unregister| functions.
  2160. +
  2161. +Event Delivery
  2162. +--------------
  2163. +
  2164. +To receive events, a client driver has to register an event notifier via
  2165. +|ssam_notifier_register|. This increments the reference counter for that
  2166. +specific class of events (as detailed in the previous section), enables the
  2167. +class on the EC (if it has not been enabled already), and installs the
  2168. +provided notifier callback.
  2169. +
  2170. +Notifier callbacks are stored in lists, with one (RCU) list per target
  2171. +category (provided via the event ID; NB: there is a fixed known number of
  2172. +target categories). There is no known association from the combination of
  2173. +event registry and event ID to the command data (target ID, target category,
  2174. +command ID, and instance ID) that can be provided by an event class, apart
  2175. +from target category and instance ID given via the event ID.
  2176. +
  2177. +Note that due to the way notifiers are (or rather have to be) stored, client
  2178. +drivers may receive events that they have not requested and need to account
  2179. +for them. Specifically, they will, by default, receive all events from the
  2180. +same target category. To simplify dealing with this, filtering of events by
  2181. +target ID (provided via the event registry) and instance ID (provided via
  2182. +the event ID) can be requested when registering a notifier. This filtering
  2183. +is applied when iterating over the notifiers at the time they are executed.
  2184. +
  2185. +All notifier callbacks are executed on a dedicated workqueue, the so-called
  2186. +completion workqueue. After an event has been received via the callback
  2187. +installed in the request layer (running on the receiver thread of the packet
  2188. +transport layer), it will be put on its respective event queue
  2189. +(|ssam_event_queue|). From this event queue the completion work item of that
  2190. +queue (running on the completion workqueue) will pick up the event and
  2191. +execute the notifier callback. This is done to avoid blocking on the
  2192. +receiver thread.
  2193. +
  2194. +There is one event queue per combination of target ID and target category.
  2195. +This is done to ensure that notifier callbacks are executed in sequence for
  2196. +events of the same target ID and target category. Callbacks can be executed
  2197. +in parallel for events with a different combination of target ID and target
  2198. +category.
  2199. +
  2200. +Concurrency and Locking
  2201. +-----------------------
  2202. +
  2203. +Most of the concurrency related safety guarantees of the controller are
  2204. +provided by the lower-level request transport layer. In addition to this,
  2205. +event (un-)registration is guarded by its own lock.
  2206. +
  2207. +Access to the controller state is guarded by the state lock. This lock is a
  2208. +read/write semaphore. The reader part can be used to ensure that the state
  2209. +does not change while functions depending on the state to stay the same
  2210. +(e.g. |ssam_notifier_register|, |ssam_notifier_unregister|,
  2211. +|ssam_request_sync_submit|, and derivatives) are executed and this guarantee
  2212. +is not already provided otherwise (e.g. through |ssam_client_bind| or
  2213. +|ssam_client_link|). The writer part guards any transitions that will change
  2214. +the state, i.e. initialization, destruction, suspension, and resumption.
  2215. +
  2216. +The controller state may be accessed (read-only) outside the state lock for
  2217. +smoke-testing against invalid API usage (e.g. in |ssam_request_sync_submit|).
  2218. +Note that such checks are not supposed to (and will not) protect against all
  2219. +invalid usages, but rather aim to help catch them. In those cases, proper
  2220. +variable access is ensured by employing ``WRITE_ONCE()`` and ``READ_ONCE()``.
  2221. +
  2222. +Assuming any preconditions on the state not changing have been satisfied,
  2223. +all non-initialization and non-shutdown functions may run concurrently with
  2224. +each other. This includes |ssam_notifier_register|, |ssam_notifier_unregister|,
  2225. +|ssam_request_sync_submit|, as well as all functions building on top of those.
  2226. diff --git a/Documentation/driver-api/surface_aggregator/overview.rst b/Documentation/driver-api/surface_aggregator/overview.rst
  2227. new file mode 100644
  2228. index 000000000000..1e9d57e50063
  2229. --- /dev/null
  2230. +++ b/Documentation/driver-api/surface_aggregator/overview.rst
  2231. @@ -0,0 +1,77 @@
  2232. +.. SPDX-License-Identifier: GPL-2.0+
  2233. +
  2234. +========
  2235. +Overview
  2236. +========
  2237. +
  2238. +The Surface/System Aggregator Module (SAM, SSAM) is an (arguably *the*)
  2239. +embedded controller (EC) on Microsoft Surface devices. It has been originally
  2240. +introduced on 4th generation devices (Surface Pro 4, Surface Book 1), but
  2241. +its responsibilities and feature-set have since been expanded significantly
  2242. +with the following generations.
  2243. +
  2244. +
  2245. +Features and Integration
  2246. +========================
  2247. +
  2248. +Not much is currently known about SAM on 4th generation devices (Surface Pro
  2249. +4, Surface Book 1), due to the use of a different communication interface
  2250. +between host and EC (as detailed below). On 5th (Surface Pro 2017, Surface
  2251. +Book 2, Surface Laptop 1) and later generation devices, SAM is responsible
  2252. +for providing battery information (both current status and static values,
  2253. +such as maximum capacity etc.), as well as an assortment of temperature
  2254. +sensors (e.g. skin temperature) and cooling/performance-mode setting to the
  2255. +host. On the Surface Book 2, specifically, it additionally provides an
  2256. +interface for properly handling clipboard detachment (i.e. separating the
  2257. +display part from the keyboard part of the device), on the Surface Laptop 1
  2258. +and 2 it is required for keyboard HID input. This HID subsystem has been
  2259. +restructured for 7th generation devices and on those, specifically Surface
  2260. +Laptop 3 and Surface Book 3, is responsible for all major HID input (i.e.
  2261. +keyboard and touchpad).
  2262. +
  2263. +While features have not changed much on a coarse level since the 5th
  2264. +generation, internal interfaces have undergone some rather large changes. On
  2265. +5th and 6th generation devices, both battery and temperature information is
  2266. +exposed to ACPI via a shim driver (referred to as Surface ACPI Notify, or
  2267. +SAN), translating ACPI generic serial bus write-/read-accesses to SAM
  2268. +requests. On 7th generation devices, this additional layer is gone and these
  2269. +devices require a driver hooking directly into the SAM interface. Equally,
  2270. +on newer generations, less devices are declared in ACPI, making them a bit
  2271. +harder to discover and requiring us to hard-code a sort of device registry.
  2272. +Due to this, a SSAM bus and subsystem with client devices
  2273. +(:c:type:`struct ssam_device <ssam_device>`) has been implemented.
  2274. +
  2275. +
  2276. +Communication
  2277. +=============
  2278. +
  2279. +The type of communication interface between host and EC depends on the
  2280. +generation of the Surface device. On 4th generation devices, host and EC
  2281. +communicate via HID, specifically using a HID-over-I2C device, whereas on
  2282. +5th and later generations, communication takes place via a USART serial
  2283. +device. In accordance to the drivers found on other operating systems, we
  2284. +refer to the serial device and its driver as Surface Serial Hub (SSH). When
  2285. +needed, we differentiate between both types of SAM by referring to them as
  2286. +SAM-over-SSH and SAM-over-HID.
  2287. +
  2288. +Currently, this subsystem only supports SAM-over-SSH. The SSH communication
  2289. +interface is described in more detail below. The HID interface has not been
  2290. +reverse engineered yet and it is, at the moment, unclear how many (and
  2291. +which) concepts of the SSH interface detailed below can be transferred to
  2292. +it.
  2293. +
  2294. +Surface Serial Hub
  2295. +------------------
  2296. +
  2297. +As already elaborated above, the Surface Serial Hub (SSH) is the
  2298. +communication interface for SAM on 5th- and all later-generation Surface
  2299. +devices. On the highest level, communication can be separated into two main
  2300. +types: Requests, messages sent from host to EC that may trigger a direct
  2301. +response from the EC (explicitly associated with the request), and events
  2302. +(sometimes also referred to as notifications), sent from EC to host without
  2303. +being a direct response to a previous request. We may also refer to requests
  2304. +without response as commands. In general, events need to be enabled via one
  2305. +of multiple dedicated requests before they are sent by the EC.
  2306. +
  2307. +See :doc:`ssh` for a more technical protocol documentation and
  2308. +:doc:`internal` for an overview of the internal driver architecture.
  2309. diff --git a/Documentation/driver-api/surface_aggregator/ssh.rst b/Documentation/driver-api/surface_aggregator/ssh.rst
  2310. new file mode 100644
  2311. index 000000000000..bf007d6c9873
  2312. --- /dev/null
  2313. +++ b/Documentation/driver-api/surface_aggregator/ssh.rst
  2314. @@ -0,0 +1,344 @@
  2315. +.. SPDX-License-Identifier: GPL-2.0+
  2316. +
  2317. +.. |u8| replace:: :c:type:`u8 <u8>`
  2318. +.. |u16| replace:: :c:type:`u16 <u16>`
  2319. +.. |TYPE| replace:: ``TYPE``
  2320. +.. |LEN| replace:: ``LEN``
  2321. +.. |SEQ| replace:: ``SEQ``
  2322. +.. |SYN| replace:: ``SYN``
  2323. +.. |NAK| replace:: ``NAK``
  2324. +.. |ACK| replace:: ``ACK``
  2325. +.. |DATA| replace:: ``DATA``
  2326. +.. |DATA_SEQ| replace:: ``DATA_SEQ``
  2327. +.. |DATA_NSQ| replace:: ``DATA_NSQ``
  2328. +.. |TC| replace:: ``TC``
  2329. +.. |TID| replace:: ``TID``
  2330. +.. |IID| replace:: ``IID``
  2331. +.. |RQID| replace:: ``RQID``
  2332. +.. |CID| replace:: ``CID``
  2333. +
  2334. +===========================
  2335. +Surface Serial Hub Protocol
  2336. +===========================
  2337. +
  2338. +The Surface Serial Hub (SSH) is the central communication interface for the
  2339. +embedded Surface Aggregator Module controller (SAM or EC), found on newer
  2340. +Surface generations. We will refer to this protocol and interface as
  2341. +SAM-over-SSH, as opposed to SAM-over-HID for the older generations.
  2342. +
  2343. +On Surface devices with SAM-over-SSH, SAM is connected to the host via UART
  2344. +and defined in ACPI as device with ID ``MSHW0084``. On these devices,
  2345. +significant functionality is provided via SAM, including access to battery
  2346. +and power information and events, thermal read-outs and events, and many
  2347. +more. For Surface Laptops, keyboard input is handled via HID directed
  2348. +through SAM, on the Surface Laptop 3 and Surface Book 3 this also includes
  2349. +touchpad input.
  2350. +
  2351. +Note that the standard disclaimer for this subsystem also applies to this
  2352. +document: All of this has been reverse-engineered and may thus be erroneous
  2353. +and/or incomplete.
  2354. +
  2355. +All CRCs used in the following are two-byte ``crc_ccitt_false(0xffff, ...)``.
  2356. +All multi-byte values are little-endian, there is no implicit padding between
  2357. +values.
  2358. +
  2359. +
  2360. +SSH Packet Protocol: Definitions
  2361. +================================
  2362. +
  2363. +The fundamental communication unit of the SSH protocol is a frame
  2364. +(:c:type:`struct ssh_frame <ssh_frame>`). A frame consists of the following
  2365. +fields, packed together and in order:
  2366. +
  2367. +.. flat-table:: SSH Frame
  2368. + :widths: 1 1 4
  2369. + :header-rows: 1
  2370. +
  2371. + * - Field
  2372. + - Type
  2373. + - Description
  2374. +
  2375. + * - |TYPE|
  2376. + - |u8|
  2377. + - Type identifier of the frame.
  2378. +
  2379. + * - |LEN|
  2380. + - |u16|
  2381. + - Length of the payload associated with the frame.
  2382. +
  2383. + * - |SEQ|
  2384. + - |u8|
  2385. + - Sequence ID (see explanation below).
  2386. +
  2387. +Each frame structure is followed by a CRC over this structure. The CRC over
  2388. +the frame structure (|TYPE|, |LEN|, and |SEQ| fields) is placed directly
  2389. +after the frame structure and before the payload. The payload is followed by
  2390. +its own CRC (over all payload bytes). If the payload is not present (i.e.
  2391. +the frame has ``LEN=0``), the CRC of the payload is still present and will
  2392. +evaluate to ``0xffff``. The |LEN| field does not include any of the CRCs, it
  2393. +equals the number of bytes inbetween the CRC of the frame and the CRC of the
  2394. +payload.
  2395. +
  2396. +Additionally, the following fixed two-byte sequences are used:
  2397. +
  2398. +.. flat-table:: SSH Byte Sequences
  2399. + :widths: 1 1 4
  2400. + :header-rows: 1
  2401. +
  2402. + * - Name
  2403. + - Value
  2404. + - Description
  2405. +
  2406. + * - |SYN|
  2407. + - ``[0xAA, 0x55]``
  2408. + - Synchronization bytes.
  2409. +
  2410. +A message consists of |SYN|, followed by the frame (|TYPE|, |LEN|, |SEQ| and
  2411. +CRC) and, if specified in the frame (i.e. ``LEN > 0``), payload bytes,
  2412. +followed finally, regardless if the payload is present, the payload CRC. The
  2413. +messages corresponding to an exchange are, in part, identified by having the
  2414. +same sequence ID (|SEQ|), stored inside the frame (more on this in the next
  2415. +section). The sequence ID is a wrapping counter.
  2416. +
  2417. +A frame can have the following types
  2418. +(:c:type:`enum ssh_frame_type <ssh_frame_type>`):
  2419. +
  2420. +.. flat-table:: SSH Frame Types
  2421. + :widths: 1 1 4
  2422. + :header-rows: 1
  2423. +
  2424. + * - Name
  2425. + - Value
  2426. + - Short Description
  2427. +
  2428. + * - |NAK|
  2429. + - ``0x04``
  2430. + - Sent on error in previously received message.
  2431. +
  2432. + * - |ACK|
  2433. + - ``0x40``
  2434. + - Sent to acknowledge receival of |DATA| frame.
  2435. +
  2436. + * - |DATA_SEQ|
  2437. + - ``0x80``
  2438. + - Sent to transfer data. Sequenced.
  2439. +
  2440. + * - |DATA_NSQ|
  2441. + - ``0x00``
  2442. + - Same as |DATA_SEQ|, but does not need to be ACKed.
  2443. +
  2444. +Both |NAK|- and |ACK|-type frames are used to control flow of messages and
  2445. +thus do not carry a payload. |DATA_SEQ|- and |DATA_NSQ|-type frames on the
  2446. +other hand must carry a payload. The flow sequence and interaction of
  2447. +different frame types will be described in more depth in the next section.
  2448. +
  2449. +
  2450. +SSH Packet Protocol: Flow Sequence
  2451. +==================================
  2452. +
  2453. +Each exchange begins with |SYN|, followed by a |DATA_SEQ|- or
  2454. +|DATA_NSQ|-type frame, followed by its CRC, payload, and payload CRC. In
  2455. +case of a |DATA_NSQ|-type frame, the exchange is then finished. In case of a
  2456. +|DATA_SEQ|-type frame, the receiving party has to acknowledge receival of
  2457. +the frame by responding with a message containing an |ACK|-type frame with
  2458. +the same sequence ID of the |DATA| frame. In other words, the sequence ID of
  2459. +the |ACK| frame specifies the |DATA| frame to be acknowledged. In case of an
  2460. +error, e.g. an invalid CRC, the receiving party responds with a message
  2461. +containing an |NAK|-type frame. As the sequence ID of the previous data
  2462. +frame, for which an error is indicated via the |NAK| frame, cannot be relied
  2463. +upon, the sequence ID of the |NAK| frame should not be used and is set to
  2464. +zero. After receival of an |NAK| frame, the sending party should re-send all
  2465. +outstanding (non-ACKed) messages.
  2466. +
  2467. +Sequence IDs are not synchronized between the two parties, meaning that they
  2468. +are managed independently for each party. Identifying the messages
  2469. +corresponding to a single exchange thus relies on the sequence ID as well as
  2470. +the type of the message, and the context. Specifically, the sequence ID is
  2471. +used to associate an ``ACK`` with its ``DATA_SEQ``-type frame, but not
  2472. +``DATA_SEQ``- or ``DATA_NSQ``-type frames with other ``DATA``- type frames.
  2473. +
  2474. +An example exchange might look like this:
  2475. +
  2476. +::
  2477. +
  2478. + tx: -- SYN FRAME(D) CRC(F) PAYLOAD CRC(P) -----------------------------
  2479. + rx: ------------------------------------- SYN FRAME(A) CRC(F) CRC(P) --
  2480. +
  2481. +where both frames have the same sequence ID (``SEQ``). Here, ``FRAME(D)``
  2482. +indicates a |DATA_SEQ|-type frame, ``FRAME(A)`` an ``ACK``-type frame,
  2483. +``CRC(F)`` the CRC over the previous frame, ``CRC(P)`` the CRC over the
  2484. +previous payload. In case of an error, the exchange would look like this:
  2485. +
  2486. +::
  2487. +
  2488. + tx: -- SYN FRAME(D) CRC(F) PAYLOAD CRC(P) -----------------------------
  2489. + rx: ------------------------------------- SYN FRAME(N) CRC(F) CRC(P) --
  2490. +
  2491. +upon which the sender should re-send the message. ``FRAME(N)`` indicates an
  2492. +|NAK|-type frame. Note that the sequence ID of the |NAK|-type frame is fixed
  2493. +to zero. For |DATA_NSQ|-type frames, both exchanges are the same:
  2494. +
  2495. +::
  2496. +
  2497. + tx: -- SYN FRAME(DATA_NSQ) CRC(F) PAYLOAD CRC(P) ----------------------
  2498. + rx: -------------------------------------------------------------------
  2499. +
  2500. +Here, an error can be detected, but not corrected or indicated to the
  2501. +sending party. These exchanges are symmetric, i.e. switching ``rx`` and
  2502. +``tx`` results again in a valid exchange. Currently, no longer exchanges are
  2503. +known.
  2504. +
  2505. +
  2506. +Commands: Requests, Responses, and Events
  2507. +=========================================
  2508. +
  2509. +Commands are sent as payload inside a data frame. Currently, this is the
  2510. +only known payload type of |DATA| frames, with a payload-type value of
  2511. +``0x80`` (:c:type:`SSH_PLD_TYPE_CMD <ssh_payload_type>`).
  2512. +
  2513. +The command-type payload (:c:type:`struct ssh_command <ssh_command>`)
  2514. +consists of an eight-byte command structure, followed by optional and
  2515. +variable length command data. The length of this optional data is derived
  2516. +from the frame payload length given in the corresponding frame, i.e. it is
  2517. +``frame.len - sizeof(struct ssh_command)``. The command struct contains the
  2518. +following fields, packed together and in order:
  2519. +
  2520. +.. flat-table:: SSH Command
  2521. + :widths: 1 1 4
  2522. + :header-rows: 1
  2523. +
  2524. + * - Field
  2525. + - Type
  2526. + - Description
  2527. +
  2528. + * - |TYPE|
  2529. + - |u8|
  2530. + - Type of the payload. For commands always ``0x80``.
  2531. +
  2532. + * - |TC|
  2533. + - |u8|
  2534. + - Target category.
  2535. +
  2536. + * - |TID| (out)
  2537. + - |u8|
  2538. + - Target ID for outgoing (host to EC) commands.
  2539. +
  2540. + * - |TID| (in)
  2541. + - |u8|
  2542. + - Target ID for incoming (EC to host) commands.
  2543. +
  2544. + * - |IID|
  2545. + - |u8|
  2546. + - Instance ID.
  2547. +
  2548. + * - |RQID|
  2549. + - |u16|
  2550. + - Request ID.
  2551. +
  2552. + * - |CID|
  2553. + - |u8|
  2554. + - Command ID.
  2555. +
  2556. +The command struct and data, in general, does not contain any failure
  2557. +detection mechanism (e.g. CRCs), this is solely done on the frame level.
  2558. +
  2559. +Command-type payloads are used by the host to send commands and requests to
  2560. +the EC as well as by the EC to send responses and events back to the host.
  2561. +We differentiate between requests (sent by the host), responses (sent by the
  2562. +EC in response to a request), and events (sent by the EC without a preceding
  2563. +request).
  2564. +
  2565. +Commands and events are uniquely identified by their target category
  2566. +(``TC``) and command ID (``CID``). The target category specifies a general
  2567. +category for the command (e.g. system in general, vs. battery and AC, vs.
  2568. +temperature, and so on), while the command ID specifies the command inside
  2569. +that category. Only the combination of |TC| + |CID| is unique. Additionally,
  2570. +commands have an instance ID (``IID``), which is used to differentiate
  2571. +between different sub-devices. For example ``TC=3`` ``CID=1`` is a
  2572. +request to get the temperature on a thermal sensor, where |IID| specifies
  2573. +the respective sensor. If the instance ID is not used, it should be set to
  2574. +zero. If instance IDs are used, they, in general, start with a value of one,
  2575. +whereas zero may be used for instance independent queries, if applicable. A
  2576. +response to a request should have the same target category, command ID, and
  2577. +instance ID as the corresponding request.
  2578. +
  2579. +Responses are matched to their corresponding request via the request ID
  2580. +(``RQID``) field. This is a 16 bit wrapping counter similar to the sequence
  2581. +ID on the frames. Note that the sequence ID of the frames for a
  2582. +request-response pair does not match. Only the request ID has to match.
  2583. +Frame-protocol wise these are two separate exchanges, and may even be
  2584. +separated, e.g. by an event being sent after the request but before the
  2585. +response. Not all commands produce a response, and this is not detectable by
  2586. +|TC| + |CID|. It is the responsibility of the issuing party to wait for a
  2587. +response (or signal this to the communication framework, as is done in
  2588. +SAN/ACPI via the ``SNC`` flag).
  2589. +
  2590. +Events are identified by unique and reserved request IDs. These IDs should
  2591. +not be used by the host when sending a new request. They are used on the
  2592. +host to, first, detect events and, second, match them with a registered
  2593. +event handler. Request IDs for events are chosen by the host and directed to
  2594. +the EC when setting up and enabling an event source (via the
  2595. +enable-event-source request). The EC then uses the specified request ID for
  2596. +events sent from the respective source. Note that an event should still be
  2597. +identified by its target category, command ID, and, if applicable, instance
  2598. +ID, as a single event source can send multiple different event types. In
  2599. +general, however, a single target category should map to a single reserved
  2600. +event request ID.
  2601. +
  2602. +Furthermore, requests, responses, and events have an associated target ID
  2603. +(``TID``). This target ID is split into output (host to EC) and input (EC to
  2604. +host) fields, with the respecting other field (e.g. output field on incoming
  2605. +messages) set to zero. Two ``TID`` values are known: Primary (``0x01``) and
  2606. +secondary (``0x02``). In general, the response to a request should have the
  2607. +same ``TID`` value, however, the field (output vs. input) should be used in
  2608. +accordance to the direction in which the response is sent (i.e. on the input
  2609. +field, as responses are generally sent from the EC to the host).
  2610. +
  2611. +Note that, even though requests and events should be uniquely identifiable
  2612. +by target category and command ID alone, the EC may require specific
  2613. +target ID and instance ID values to accept a command. A command that is
  2614. +accepted for ``TID=1``, for example, may not be accepted for ``TID=2``
  2615. +and vice versa.
  2616. +
  2617. +
  2618. +Limitations and Observations
  2619. +============================
  2620. +
  2621. +The protocol can, in theory, handle up to ``U8_MAX`` frames in parallel,
  2622. +with up to ``U16_MAX`` pending requests (neglecting request IDs reserved for
  2623. +events). In practice, however, this is more limited. From our testing
  2624. +(although via a python and thus a user-space program), it seems that the EC
  2625. +can handle up to four requests (mostly) reliably in parallel at a certain
  2626. +time. With five or more requests in parallel, consistent discarding of
  2627. +commands (ACKed frame but no command response) has been observed. For five
  2628. +simultaneous commands, this reproducibly resulted in one command being
  2629. +dropped and four commands being handled.
  2630. +
  2631. +However, it has also been noted that, even with three requests in parallel,
  2632. +occasional frame drops happen. Apart from this, with a limit of three
  2633. +pending requests, no dropped commands (i.e. command being dropped but frame
  2634. +carrying command being ACKed) have been observed. In any case, frames (and
  2635. +possibly also commands) should be re-sent by the host if a certain timeout
  2636. +is exceeded. This is done by the EC for frames with a timeout of one second,
  2637. +up to two re-tries (i.e. three transmissions in total). The limit of
  2638. +re-tries also applies to received NAKs, and, in a worst case scenario, can
  2639. +lead to entire messages being dropped.
  2640. +
  2641. +While this also seems to work fine for pending data frames as long as no
  2642. +transmission failures occur, implementation and handling of these seems to
  2643. +depend on the assumption that there is only one non-acknowledged data frame.
  2644. +In particular, the detection of repeated frames relies on the last sequence
  2645. +number. This means that, if a frame that has been successfully received by
  2646. +the EC is sent again, e.g. due to the host not receiving an |ACK|, the EC
  2647. +will only detect this if it has the sequence ID of the last frame received
  2648. +by the EC. As an example: Sending two frames with ``SEQ=0`` and ``SEQ=1``
  2649. +followed by a repetition of ``SEQ=0`` will not detect the second ``SEQ=0``
  2650. +frame as such, and thus execute the command in this frame each time it has
  2651. +been received, i.e. twice in this example. Sending ``SEQ=0``, ``SEQ=1`` and
  2652. +then repeating ``SEQ=1`` will detect the second ``SEQ=1`` as repetition of
  2653. +the first one and ignore it, thus executing the contained command only once.
  2654. +
  2655. +In conclusion, this suggests a limit of at most one pending un-ACKed frame
  2656. +(per party, effectively leading to synchronous communication regarding
  2657. +frames) and at most three pending commands. The limit to synchronous frame
  2658. +transfers seems to be consistent with behavior observed on Windows.
  2659. diff --git a/drivers/misc/Kconfig b/drivers/misc/Kconfig
  2660. index 102969c546d7..1c9d36272ea6 100644
  2661. --- a/drivers/misc/Kconfig
  2662. +++ b/drivers/misc/Kconfig
  2663. @@ -472,5 +472,6 @@ source "drivers/misc/ocxl/Kconfig"
  2664. source "drivers/misc/cardreader/Kconfig"
  2665. source "drivers/misc/habanalabs/Kconfig"
  2666. source "drivers/misc/uacce/Kconfig"
  2667. +source "drivers/misc/surface_aggregator/Kconfig"
  2668. source "drivers/misc/ipts/Kconfig"
  2669. endmenu
  2670. diff --git a/drivers/misc/Makefile b/drivers/misc/Makefile
  2671. index f97938d777e1..b0caee1dd3b7 100644
  2672. --- a/drivers/misc/Makefile
  2673. +++ b/drivers/misc/Makefile
  2674. @@ -58,3 +58,4 @@ obj-$(CONFIG_HABANA_AI) += habanalabs/
  2675. obj-$(CONFIG_UACCE) += uacce/
  2676. obj-$(CONFIG_XILINX_SDFEC) += xilinx_sdfec.o
  2677. obj-$(CONFIG_MISC_IPTS) += ipts/
  2678. +obj-$(CONFIG_SURFACE_AGGREGATOR) += surface_aggregator/
  2679. diff --git a/drivers/misc/surface_aggregator/Kconfig b/drivers/misc/surface_aggregator/Kconfig
  2680. new file mode 100644
  2681. index 000000000000..47dd8fdffac3
  2682. --- /dev/null
  2683. +++ b/drivers/misc/surface_aggregator/Kconfig
  2684. @@ -0,0 +1,67 @@
  2685. +# SPDX-License-Identifier: GPL-2.0+
  2686. +# Copyright (C) 2019-2020 Maximilian Luz <luzmaximilian@gmail.com>
  2687. +
  2688. +menuconfig SURFACE_AGGREGATOR
  2689. + tristate "Microsoft Surface System Aggregator Module Subsystem and Drivers"
  2690. + depends on SERIAL_DEV_BUS
  2691. + depends on ACPI
  2692. + select CRC_CCITT
  2693. + help
  2694. + The Surface System Aggregator Module (Surface SAM or SSAM) is an
  2695. + embedded controller (EC) found on 5th- and later-generation Microsoft
  2696. + Surface devices (i.e. Surface Pro 5, Surface Book 2, Surface Laptop,
  2697. + and newer, with exception of Surface Go series devices).
  2698. +
  2699. + Depending on the device in question, this EC provides varying
  2700. + functionality, including:
  2701. + - EC access from ACPI via Surface ACPI Notify (5th- and 6th-generation)
  2702. + - battery status information (all devices)
  2703. + - thermal sensor access (all devices)
  2704. + - performance mode / cooling mode control (all devices)
  2705. + - clipboard detachment system control (Surface Book 2 and 3)
  2706. + - HID / keyboard input (Surface Laptops, Surface Book 3)
  2707. +
  2708. + This option controls whether the Surface SAM subsystem core will be
  2709. + built. This includes a driver for the Surface Serial Hub (SSH), which
  2710. + is the device responsible for the communication with the EC, and a
  2711. + basic kernel interface exposing the EC functionality to other client
  2712. + drivers, i.e. allowing them to make requests to the EC and receive
  2713. + events from it. Selecting this option alone will not provide any
  2714. + client drivers and therefore no functionality beyond the in-kernel
  2715. + interface. Said functionality is the repsonsibility of the respective
  2716. + client drivers.
  2717. +
  2718. + Note: While 4th-generation Surface devices also make use of a SAM EC,
  2719. + due to a difference in the communication interface of the controller,
  2720. + only 5th and later generations are currently supported. Specifically,
  2721. + devices using SAM-over-SSH are supported, whereas devices using
  2722. + SAM-over-HID, which is used on the 4th generation, are currently not
  2723. + supported.
  2724. +
  2725. +config SURFACE_AGGREGATOR_BUS
  2726. + bool "Surface System Aggregator Module Bus"
  2727. + depends on SURFACE_AGGREGATOR
  2728. + default y
  2729. + help
  2730. + Expands the Surface System Aggregator Module (SSAM) core driver by
  2731. + providing a dedicated bus and client-device type.
  2732. +
  2733. + This bus and device type are intended to provide and simplify support
  2734. + for non-platform and non-ACPI SSAM devices, i.e. SSAM devices that are
  2735. + not auto-detectable via the conventional means (e.g. ACPI).
  2736. +
  2737. +config SURFACE_AGGREGATOR_ERROR_INJECTION
  2738. + bool "Surface System Aggregator Module Error Injection Capabilities"
  2739. + depends on SURFACE_AGGREGATOR
  2740. + depends on FUNCTION_ERROR_INJECTION
  2741. + help
  2742. + Provides error-injection capabilities for the Surface System
  2743. + Aggregator Module subsystem and Surface Serial Hub driver.
  2744. +
  2745. + Specifically, exports error injection hooks to be used with the
  2746. + kernel's function error injection capabilities to simulate underlying
  2747. + transport and communication problems, such as invalid data sent to or
  2748. + received from the EC, dropped data, and communication timeouts.
  2749. + Intended for development and debugging.
  2750. +
  2751. +source "drivers/misc/surface_aggregator/clients/Kconfig"
  2752. diff --git a/drivers/misc/surface_aggregator/Makefile b/drivers/misc/surface_aggregator/Makefile
  2753. new file mode 100644
  2754. index 000000000000..b48ffc37ab52
  2755. --- /dev/null
  2756. +++ b/drivers/misc/surface_aggregator/Makefile
  2757. @@ -0,0 +1,18 @@
  2758. +# SPDX-License-Identifier: GPL-2.0+
  2759. +# Copyright (C) 2019-2020 Maximilian Luz <luzmaximilian@gmail.com>
  2760. +
  2761. +# For include/trace/define_trace.h to include trace.h
  2762. +CFLAGS_core.o = -I$(src)
  2763. +
  2764. +obj-$(CONFIG_SURFACE_AGGREGATOR) += surface_aggregator.o
  2765. +obj-$(CONFIG_SURFACE_AGGREGATOR) += clients/
  2766. +
  2767. +surface_aggregator-objs := core.o
  2768. +surface_aggregator-objs += ssh_parser.o
  2769. +surface_aggregator-objs += ssh_packet_layer.o
  2770. +surface_aggregator-objs += ssh_request_layer.o
  2771. +surface_aggregator-objs += controller.o
  2772. +
  2773. +ifeq ($(CONFIG_SURFACE_AGGREGATOR_BUS),y)
  2774. +surface_aggregator-objs += bus.o
  2775. +endif
  2776. diff --git a/drivers/misc/surface_aggregator/bus.c b/drivers/misc/surface_aggregator/bus.c
  2777. new file mode 100644
  2778. index 000000000000..fecfa1b6a140
  2779. --- /dev/null
  2780. +++ b/drivers/misc/surface_aggregator/bus.c
  2781. @@ -0,0 +1,416 @@
  2782. +// SPDX-License-Identifier: GPL-2.0+
  2783. +/*
  2784. + * Surface System Aggregator Module bus and device integration.
  2785. + *
  2786. + * Copyright (C) 2019-2020 Maximilian Luz <luzmaximilian@gmail.com>
  2787. + */
  2788. +
  2789. +#include <linux/device.h>
  2790. +#include <linux/slab.h>
  2791. +
  2792. +#include <linux/surface_aggregator/controller.h>
  2793. +#include <linux/surface_aggregator/device.h>
  2794. +
  2795. +#include "bus.h"
  2796. +#include "controller.h"
  2797. +
  2798. +static ssize_t modalias_show(struct device *dev, struct device_attribute *attr,
  2799. + char *buf)
  2800. +{
  2801. + struct ssam_device *sdev = to_ssam_device(dev);
  2802. +
  2803. + // FIXME: we should use sysfs_emit here, but that's not available on < 5.10
  2804. + return scnprintf(buf, PAGE_SIZE, "ssam:d%02Xc%02Xt%02Xi%02Xf%02X\n",
  2805. + sdev->uid.domain, sdev->uid.category, sdev->uid.target,
  2806. + sdev->uid.instance, sdev->uid.function);
  2807. +}
  2808. +static DEVICE_ATTR_RO(modalias);
  2809. +
  2810. +static struct attribute *ssam_device_attrs[] = {
  2811. + &dev_attr_modalias.attr,
  2812. + NULL,
  2813. +};
  2814. +ATTRIBUTE_GROUPS(ssam_device);
  2815. +
  2816. +static int ssam_device_uevent(struct device *dev, struct kobj_uevent_env *env)
  2817. +{
  2818. + struct ssam_device *sdev = to_ssam_device(dev);
  2819. +
  2820. + return add_uevent_var(env, "MODALIAS=ssam:d%02Xc%02Xt%02Xi%02Xf%02X",
  2821. + sdev->uid.domain, sdev->uid.category,
  2822. + sdev->uid.target, sdev->uid.instance,
  2823. + sdev->uid.function);
  2824. +}
  2825. +
  2826. +static void ssam_device_release(struct device *dev)
  2827. +{
  2828. + struct ssam_device *sdev = to_ssam_device(dev);
  2829. +
  2830. + ssam_controller_put(sdev->ctrl);
  2831. + kfree(sdev);
  2832. +}
  2833. +
  2834. +const struct device_type ssam_device_type = {
  2835. + .name = "surface_aggregator_device",
  2836. + .groups = ssam_device_groups,
  2837. + .uevent = ssam_device_uevent,
  2838. + .release = ssam_device_release,
  2839. +};
  2840. +EXPORT_SYMBOL_GPL(ssam_device_type);
  2841. +
  2842. +/**
  2843. + * ssam_device_alloc() - Allocate and initialize a SSAM client device.
  2844. + * @ctrl: The controller under which the device should be added.
  2845. + * @uid: The UID of the device to be added.
  2846. + *
  2847. + * Allocates and initializes a new client device. The parent of the device
  2848. + * will be set to the controller device and the name will be set based on the
  2849. + * UID. Note that the device still has to be added via ssam_device_add().
  2850. + * Refer to that function for more details.
  2851. + *
  2852. + * Return: Returns the newly allocated and initialized SSAM client device, or
  2853. + * %NULL if it could not be allocated.
  2854. + */
  2855. +struct ssam_device *ssam_device_alloc(struct ssam_controller *ctrl,
  2856. + struct ssam_device_uid uid)
  2857. +{
  2858. + struct ssam_device *sdev;
  2859. +
  2860. + sdev = kzalloc(sizeof(*sdev), GFP_KERNEL);
  2861. + if (!sdev)
  2862. + return NULL;
  2863. +
  2864. + device_initialize(&sdev->dev);
  2865. + sdev->dev.bus = &ssam_bus_type;
  2866. + sdev->dev.type = &ssam_device_type;
  2867. + sdev->dev.parent = ssam_controller_device(ctrl);
  2868. + sdev->ctrl = ssam_controller_get(ctrl);
  2869. + sdev->uid = uid;
  2870. +
  2871. + dev_set_name(&sdev->dev, "%02x:%02x:%02x:%02x:%02x",
  2872. + sdev->uid.domain, sdev->uid.category, sdev->uid.target,
  2873. + sdev->uid.instance, sdev->uid.function);
  2874. +
  2875. + return sdev;
  2876. +}
  2877. +EXPORT_SYMBOL_GPL(ssam_device_alloc);
  2878. +
  2879. +/**
  2880. + * ssam_device_add() - Add a SSAM client device.
  2881. + * @sdev: The SSAM client device to be added.
  2882. + *
  2883. + * Added client devices must be guaranteed to always have a valid and active
  2884. + * controller. Thus, this function will fail with %-ENODEV if the controller
  2885. + * of the device has not been initialized yet, has been suspended, or has been
  2886. + * shut down.
  2887. + *
  2888. + * The caller of this function should ensure that the corresponding call to
  2889. + * ssam_device_remove() is issued before the controller is shut down. If the
  2890. + * added device is a direct child of the controller device (default), it will
  2891. + * be automatically removed when the controller is shut down.
  2892. + *
  2893. + * By default, the controller device will become the parent of the newly
  2894. + * created client device. The parent may be changed before ssam_device_add is
  2895. + * called, but care must be taken that a) the correct suspend/resume ordering
  2896. + * is guaranteed and b) the client device does not outlive the controller,
  2897. + * i.e. that the device is removed before the controller is being shut down.
  2898. + * In case these guarantees have to be manually enforced, please refer to the
  2899. + * ssam_client_link() and ssam_client_bind() functions, which are intended to
  2900. + * set up device-links for this purpose.
  2901. + *
  2902. + * Return: Returns zero on success, a negative error code on failure.
  2903. + */
  2904. +int ssam_device_add(struct ssam_device *sdev)
  2905. +{
  2906. + int status;
  2907. +
  2908. + /*
  2909. + * Ensure that we can only add new devices to a controller if it has
  2910. + * been started and is not going away soon. This works in combination
  2911. + * with ssam_controller_remove_clients to ensure driver presence for the
  2912. + * controller device, i.e. it ensures that the controller (sdev->ctrl)
  2913. + * is always valid and can be used for requests as long as the client
  2914. + * device we add here is registered as child under it. This essentially
  2915. + * guarantees that the client driver can always expect the preconditions
  2916. + * for functions like ssam_request_sync (controller has to be started
  2917. + * and is not suspended) to hold and thus does not have to check for
  2918. + * them.
  2919. + *
  2920. + * Note that for this to work, the controller has to be a parent device.
  2921. + * If it is not a direct parent, care has to be taken that the device is
  2922. + * removed via ssam_device_remove(), as device_unregister does not
  2923. + * remove child devices recursively.
  2924. + */
  2925. + ssam_controller_statelock(sdev->ctrl);
  2926. +
  2927. + if (sdev->ctrl->state != SSAM_CONTROLLER_STARTED) {
  2928. + ssam_controller_stateunlock(sdev->ctrl);
  2929. + return -ENODEV;
  2930. + }
  2931. +
  2932. + status = device_add(&sdev->dev);
  2933. +
  2934. + ssam_controller_stateunlock(sdev->ctrl);
  2935. + return status;
  2936. +}
  2937. +EXPORT_SYMBOL_GPL(ssam_device_add);
  2938. +
  2939. +/**
  2940. + * ssam_device_remove() - Remove a SSAM client device.
  2941. + * @sdev: The device to remove.
  2942. + *
  2943. + * Removes and unregisters the provided SSAM client device.
  2944. + */
  2945. +void ssam_device_remove(struct ssam_device *sdev)
  2946. +{
  2947. + device_unregister(&sdev->dev);
  2948. +}
  2949. +EXPORT_SYMBOL_GPL(ssam_device_remove);
  2950. +
  2951. +/**
  2952. + * ssam_device_id_compatible() - Check if a device ID matches a UID.
  2953. + * @id: The device ID as potential match.
  2954. + * @uid: The device UID matching against.
  2955. + *
  2956. + * Check if the given ID is a match for the given UID, i.e. if a device with
  2957. + * the provided UID is compatible to the given ID following the match rules
  2958. + * described in its &ssam_device_id.match_flags member.
  2959. + *
  2960. + * Return: Returns %true if the given UID is compatible to the match rule
  2961. + * described by the given ID, %false otherwise.
  2962. + */
  2963. +static bool ssam_device_id_compatible(const struct ssam_device_id *id,
  2964. + struct ssam_device_uid uid)
  2965. +{
  2966. + if (id->domain != uid.domain || id->category != uid.category)
  2967. + return false;
  2968. +
  2969. + if ((id->match_flags & SSAM_MATCH_TARGET) && id->target != uid.target)
  2970. + return false;
  2971. +
  2972. + if ((id->match_flags & SSAM_MATCH_INSTANCE) && id->instance != uid.instance)
  2973. + return false;
  2974. +
  2975. + if ((id->match_flags & SSAM_MATCH_FUNCTION) && id->function != uid.function)
  2976. + return false;
  2977. +
  2978. + return true;
  2979. +}
  2980. +
  2981. +/**
  2982. + * ssam_device_id_is_null() - Check if a device ID is null.
  2983. + * @id: The device ID to check.
  2984. + *
  2985. + * Check if a given device ID is null, i.e. all zeros. Used to check for the
  2986. + * end of ``MODULE_DEVICE_TABLE(ssam, ...)`` or similar lists.
  2987. + *
  2988. + * Return: Returns %true if the given ID represents a null ID, %false
  2989. + * otherwise.
  2990. + */
  2991. +static bool ssam_device_id_is_null(const struct ssam_device_id *id)
  2992. +{
  2993. + return id->match_flags == 0 &&
  2994. + id->domain == 0 &&
  2995. + id->category == 0 &&
  2996. + id->target == 0 &&
  2997. + id->instance == 0 &&
  2998. + id->function == 0 &&
  2999. + id->driver_data == 0;
  3000. +}
  3001. +
  3002. +/**
  3003. + * ssam_device_id_match() - Find the matching ID table entry for the given UID.
  3004. + * @table: The table to search in.
  3005. + * @uid: The UID to matched against the individual table entries.
  3006. + *
  3007. + * Find the first match for the provided device UID in the provided ID table
  3008. + * and return it. Returns %NULL if no match could be found.
  3009. + */
  3010. +const struct ssam_device_id *ssam_device_id_match(const struct ssam_device_id *table,
  3011. + const struct ssam_device_uid uid)
  3012. +{
  3013. + const struct ssam_device_id *id;
  3014. +
  3015. + for (id = table; !ssam_device_id_is_null(id); ++id)
  3016. + if (ssam_device_id_compatible(id, uid))
  3017. + return id;
  3018. +
  3019. + return NULL;
  3020. +}
  3021. +EXPORT_SYMBOL_GPL(ssam_device_id_match);
  3022. +
  3023. +/**
  3024. + * ssam_device_get_match() - Find and return the ID matching the device in the
  3025. + * ID table of the bound driver.
  3026. + * @dev: The device for which to get the matching ID table entry.
  3027. + *
  3028. + * Find the fist match for the UID of the device in the ID table of the
  3029. + * currently bound driver and return it. Returns %NULL if the device does not
  3030. + * have a driver bound to it, the driver does not have match_table (i.e. it is
  3031. + * %NULL), or there is no match in the driver's match_table.
  3032. + *
  3033. + * This function essentially calls ssam_device_id_match() with the ID table of
  3034. + * the bound device driver and the UID of the device.
  3035. + *
  3036. + * Return: Returns the first match for the UID of the device in the device
  3037. + * driver's match table, or %NULL if no such match could be found.
  3038. + */
  3039. +const struct ssam_device_id *ssam_device_get_match(const struct ssam_device *dev)
  3040. +{
  3041. + const struct ssam_device_driver *sdrv;
  3042. +
  3043. + sdrv = to_ssam_device_driver(dev->dev.driver);
  3044. + if (!sdrv)
  3045. + return NULL;
  3046. +
  3047. + if (!sdrv->match_table)
  3048. + return NULL;
  3049. +
  3050. + return ssam_device_id_match(sdrv->match_table, dev->uid);
  3051. +}
  3052. +EXPORT_SYMBOL_GPL(ssam_device_get_match);
  3053. +
  3054. +/**
  3055. + * ssam_device_get_match_data() - Find the ID matching the device in the
  3056. + * ID table of the bound driver and return its ``driver_data`` member.
  3057. + * @dev: The device for which to get the match data.
  3058. + *
  3059. + * Find the fist match for the UID of the device in the ID table of the
  3060. + * corresponding driver and return its driver_data. Returns %NULL if the
  3061. + * device does not have a driver bound to it, the driver does not have
  3062. + * match_table (i.e. it is %NULL), there is no match in the driver's
  3063. + * match_table, or the match does not have any driver_data.
  3064. + *
  3065. + * This function essentially calls ssam_device_get_match() and, if any match
  3066. + * could be found, returns its ``struct ssam_device_id.driver_data`` member.
  3067. + *
  3068. + * Return: Returns the driver data associated with the first match for the UID
  3069. + * of the device in the device driver's match table, or %NULL if no such match
  3070. + * could be found.
  3071. + */
  3072. +const void *ssam_device_get_match_data(const struct ssam_device *dev)
  3073. +{
  3074. + const struct ssam_device_id *id;
  3075. +
  3076. + id = ssam_device_get_match(dev);
  3077. + if (!id)
  3078. + return NULL;
  3079. +
  3080. + return (const void *)id->driver_data;
  3081. +}
  3082. +EXPORT_SYMBOL_GPL(ssam_device_get_match_data);
  3083. +
  3084. +static int ssam_bus_match(struct device *dev, struct device_driver *drv)
  3085. +{
  3086. + struct ssam_device_driver *sdrv = to_ssam_device_driver(drv);
  3087. + struct ssam_device *sdev = to_ssam_device(dev);
  3088. +
  3089. + if (!is_ssam_device(dev))
  3090. + return 0;
  3091. +
  3092. + return !!ssam_device_id_match(sdrv->match_table, sdev->uid);
  3093. +}
  3094. +
  3095. +static int ssam_bus_probe(struct device *dev)
  3096. +{
  3097. + return to_ssam_device_driver(dev->driver)
  3098. + ->probe(to_ssam_device(dev));
  3099. +}
  3100. +
  3101. +static int ssam_bus_remove(struct device *dev)
  3102. +{
  3103. + struct ssam_device_driver *sdrv = to_ssam_device_driver(dev->driver);
  3104. +
  3105. + if (sdrv->remove)
  3106. + sdrv->remove(to_ssam_device(dev));
  3107. +
  3108. + return 0;
  3109. +}
  3110. +
  3111. +struct bus_type ssam_bus_type = {
  3112. + .name = "surface_aggregator",
  3113. + .match = ssam_bus_match,
  3114. + .probe = ssam_bus_probe,
  3115. + .remove = ssam_bus_remove,
  3116. +};
  3117. +EXPORT_SYMBOL_GPL(ssam_bus_type);
  3118. +
  3119. +/**
  3120. + * __ssam_device_driver_register() - Register a SSAM client device driver.
  3121. + * @sdrv: The driver to register.
  3122. + * @owner: The module owning the provided driver.
  3123. + *
  3124. + * Please refer to the ssam_device_driver_register() macro for the normal way
  3125. + * to register a driver from inside its owning module.
  3126. + */
  3127. +int __ssam_device_driver_register(struct ssam_device_driver *sdrv,
  3128. + struct module *owner)
  3129. +{
  3130. + sdrv->driver.owner = owner;
  3131. + sdrv->driver.bus = &ssam_bus_type;
  3132. +
  3133. + /* force drivers to async probe so I/O is possible in probe */
  3134. + sdrv->driver.probe_type = PROBE_PREFER_ASYNCHRONOUS;
  3135. +
  3136. + return driver_register(&sdrv->driver);
  3137. +}
  3138. +EXPORT_SYMBOL_GPL(__ssam_device_driver_register);
  3139. +
  3140. +/**
  3141. + * ssam_device_driver_unregister - Unregister a SSAM device driver.
  3142. + * @sdrv: The driver to unregister.
  3143. + */
  3144. +void ssam_device_driver_unregister(struct ssam_device_driver *sdrv)
  3145. +{
  3146. + driver_unregister(&sdrv->driver);
  3147. +}
  3148. +EXPORT_SYMBOL_GPL(ssam_device_driver_unregister);
  3149. +
  3150. +static int ssam_remove_device(struct device *dev, void *_data)
  3151. +{
  3152. + struct ssam_device *sdev = to_ssam_device(dev);
  3153. +
  3154. + if (is_ssam_device(dev))
  3155. + ssam_device_remove(sdev);
  3156. +
  3157. + return 0;
  3158. +}
  3159. +
  3160. +/**
  3161. + * ssam_controller_remove_clients() - Remove SSAM client devices registered as
  3162. + * direct children under the given controller.
  3163. + * @ctrl: The controller to remove all direct clients for.
  3164. + *
  3165. + * Remove all SSAM client devices registered as direct children under the
  3166. + * given controller. Note that this only accounts for direct children of the
  3167. + * controller device. This does not take care of any client devices where the
  3168. + * parent device has been manually set before calling ssam_device_add. Refer
  3169. + * to ssam_device_add()/ssam_device_remove() for more details on those cases.
  3170. + *
  3171. + * To avoid new devices being added in parallel to this call, the main
  3172. + * controller lock (not statelock) must be held during this (and if
  3173. + * necessary, any subsequent deinitialization) call.
  3174. + */
  3175. +void ssam_controller_remove_clients(struct ssam_controller *ctrl)
  3176. +{
  3177. + struct device *dev;
  3178. +
  3179. + dev = ssam_controller_device(ctrl);
  3180. + device_for_each_child_reverse(dev, NULL, ssam_remove_device);
  3181. +}
  3182. +
  3183. +/**
  3184. + * ssam_bus_register() - Register and set-up the SSAM client device bus.
  3185. + */
  3186. +int ssam_bus_register(void)
  3187. +{
  3188. + return bus_register(&ssam_bus_type);
  3189. +}
  3190. +
  3191. +/**
  3192. + * ssam_bus_unregister() - Unregister the SSAM client device bus.
  3193. + */
  3194. +void ssam_bus_unregister(void)
  3195. +{
  3196. + return bus_unregister(&ssam_bus_type);
  3197. +}
  3198. diff --git a/drivers/misc/surface_aggregator/bus.h b/drivers/misc/surface_aggregator/bus.h
  3199. new file mode 100644
  3200. index 000000000000..7712baaed6a5
  3201. --- /dev/null
  3202. +++ b/drivers/misc/surface_aggregator/bus.h
  3203. @@ -0,0 +1,27 @@
  3204. +/* SPDX-License-Identifier: GPL-2.0+ */
  3205. +/*
  3206. + * Surface System Aggregator Module bus and device integration.
  3207. + *
  3208. + * Copyright (C) 2019-2020 Maximilian Luz <luzmaximilian@gmail.com>
  3209. + */
  3210. +
  3211. +#ifndef _SURFACE_AGGREGATOR_BUS_H
  3212. +#define _SURFACE_AGGREGATOR_BUS_H
  3213. +
  3214. +#include <linux/surface_aggregator/controller.h>
  3215. +
  3216. +#ifdef CONFIG_SURFACE_AGGREGATOR_BUS
  3217. +
  3218. +void ssam_controller_remove_clients(struct ssam_controller *ctrl);
  3219. +
  3220. +int ssam_bus_register(void);
  3221. +void ssam_bus_unregister(void);
  3222. +
  3223. +#else /* CONFIG_SURFACE_AGGREGATOR_BUS */
  3224. +
  3225. +static inline void ssam_controller_remove_clients(struct ssam_controller *ctrl) {}
  3226. +static inline int ssam_bus_register(void) { return 0; }
  3227. +static inline void ssam_bus_unregister(void) {}
  3228. +
  3229. +#endif /* CONFIG_SURFACE_AGGREGATOR_BUS */
  3230. +#endif /* _SURFACE_AGGREGATOR_BUS_H */
  3231. diff --git a/drivers/misc/surface_aggregator/clients/Kconfig b/drivers/misc/surface_aggregator/clients/Kconfig
  3232. new file mode 100644
  3233. index 000000000000..4d2b0528ca2e
  3234. --- /dev/null
  3235. +++ b/drivers/misc/surface_aggregator/clients/Kconfig
  3236. @@ -0,0 +1,134 @@
  3237. +# SPDX-License-Identifier: GPL-2.0+
  3238. +# Copyright (C) 2019-2020 Maximilian Luz <luzmaximilian@gmail.com>
  3239. +
  3240. +config SURFACE_AGGREGATOR_CDEV
  3241. + tristate "Surface System Aggregator Module User-Space Interface"
  3242. + depends on SURFACE_AGGREGATOR
  3243. + help
  3244. + Provides a misc-device interface to the Surface System Aggregator
  3245. + Module (SSAM) controller.
  3246. +
  3247. + This option provides a module (called surface_aggregator_cdev), that,
  3248. + when loaded, will add a client device (and its respective driver) to
  3249. + the SSAM controller. Said client device manages a misc-device
  3250. + interface (/dev/surface/aggregator), which can be used by user-space
  3251. + tools to directly communicate with the SSAM EC by sending requests and
  3252. + receiving the correspondign responses.
  3253. +
  3254. + The provided interface is intended for debugging and development only,
  3255. + and should not be used otherwise.
  3256. +
  3257. +config SURFACE_AGGREGATOR_REGISTRY
  3258. + tristate "Surface System Aggregator Module Device Registry"
  3259. + depends on SURFACE_AGGREGATOR_BUS
  3260. + default m
  3261. + help
  3262. + Device-registry and device-hubs for Surface System Aggregator Module
  3263. + (SSAM) devices.
  3264. +
  3265. + Provides a module and driver which act as device-registry for SSAM
  3266. + client devices that cannot be detected automatically, e.g. via ACPI.
  3267. + Such devices are instead provided via this registry and attached via
  3268. + device hubs, also provided in this module.
  3269. +
  3270. + Devices provided via this registry are:
  3271. + - performance / cooling mode device (all generations)
  3272. + - battery/AC devices (7th generation)
  3273. + - HID input devices (7th generation)
  3274. +
  3275. + Note that this module only provides the respective client devices.
  3276. + Drivers for these devices still need to be selected via the other
  3277. + options.
  3278. +
  3279. +config SURFACE_ACPI_NOTIFY
  3280. + tristate "Surface ACPI Notify Driver"
  3281. + depends on SURFACE_AGGREGATOR
  3282. + default m
  3283. + help
  3284. + Surface ACPI Notify (SAN) driver for Microsoft Surface devices.
  3285. +
  3286. + This driver provides support for the ACPI interface (called SAN) of
  3287. + the Surface System Aggregator Module (SSAM) EC. This interface is used
  3288. + on 5th- and 6th-generation Microsoft Surface devices (including
  3289. + Surface Pro 5 and 6, Surface Book 2, Surface Laptops 1 and 2, and in
  3290. + reduced functionality on the Surface Laptop 3) to execute SSAM
  3291. + requests directly from ACPI code, as well as receive SSAM events and
  3292. + turn them into ACPI notifications. It essentially acts as a
  3293. + translation layer between the SSAM controller and ACPI.
  3294. +
  3295. + Specifically, this driver may be needed for battery status reporting,
  3296. + thermal sensor access, and real-time clock information, depending on
  3297. + the Surface device in question.
  3298. +
  3299. +config SURFACE_BATTERY
  3300. + tristate "Surface Battery Driver"
  3301. + depends on SURFACE_AGGREGATOR_BUS
  3302. + select POWER_SUPPLY
  3303. + default m
  3304. + help
  3305. + Driver for battery and AC-adapter devices connected/managed via the
  3306. + Surface System Aggregator Module (SSAM) EC.
  3307. +
  3308. + This driver provides battery-/AC-information and -status support for
  3309. + Surface devices where said data is not exposed via the standard ACPI
  3310. + devices. On those models (7th-generation, i.e. Surface pro 7, Surface
  3311. + Laptop 3, and Surface Book 3), battery-/AC-status and -information is
  3312. + instead handled directly via SSAM client devices.
  3313. +
  3314. +config SURFACE_DTX
  3315. + tristate "Surface Detachment System Driver"
  3316. + depends on SURFACE_AGGREGATOR
  3317. + depends on INPUT
  3318. + default m
  3319. + help
  3320. + Driver for the Surface Book clipboard detachment system (DTX).
  3321. +
  3322. + On the Surface Book series devices, the display part containing the
  3323. + CPU (called the clipboard) can be detached from the base (containing a
  3324. + battery, the keyboard, and, optionally, a discrete GPU) by (if
  3325. + necessary) unlocking and opening the latch connecting both parts.
  3326. +
  3327. + This driver provides a user-space interface that can influence the
  3328. + behavior of this process, which includes the option to abort it in
  3329. + case the base is still in use or speed it up in case it is not.
  3330. +
  3331. + Note that this module can be built without support for the Surface
  3332. + Aggregator Bus (i.e. CONFIG_SURFACE_AGGREGATOR_BUS=n). In that case,
  3333. + some devices, specifically the Surface Book 3, will not be supported.
  3334. +
  3335. +config SURFACE_HID
  3336. + tristate "Surface HID Transport Driver"
  3337. + depends on SURFACE_AGGREGATOR_BUS
  3338. + depends on HID
  3339. + default m
  3340. + help
  3341. + Transport driver for HID devices connected via the Surface System
  3342. + Aggregator Module (SSAM).
  3343. +
  3344. + This driver provides support for HID input devices (e.g. touchpad and
  3345. + keyboard) connected via SSAM. It is required for keyboard input on the
  3346. + Surface Laptop 1 and 2, as well as keyboard and touchpad input on the
  3347. + Surface Laptop 3 and Surface Book 3.
  3348. +
  3349. + Note that this module can be built without support for the Surface
  3350. + Aggregator Bus (i.e. CONFIG_SURFACE_AGGREGATOR_BUS=n). In that case,
  3351. + some devices, specifically the Surface Book 3 and Surface Laptop 3,
  3352. + will not be supported.
  3353. +
  3354. +config SURFACE_PERFMODE
  3355. + tristate "Surface Performance-Mode Driver"
  3356. + depends on SURFACE_AGGREGATOR_BUS
  3357. + depends on SYSFS
  3358. + default m
  3359. + help
  3360. + Driver for the performance-/cooling-mode interface of Microsoft
  3361. + Surface devices.
  3362. +
  3363. + Microsoft Surface devices using the Surface System Aggregator Module
  3364. + (SSAM) can be switched between different performance modes. This,
  3365. + depending on the device, can influence their cooling behavior and may
  3366. + influence power limits, allowing users to choose between performance
  3367. + and higher power-draw, or lower power-draw and more silent operation.
  3368. +
  3369. + This driver provides a user-space interface (via sysfs) for
  3370. + controlling said mode via the corresponding client device.
  3371. diff --git a/drivers/misc/surface_aggregator/clients/Makefile b/drivers/misc/surface_aggregator/clients/Makefile
  3372. new file mode 100644
  3373. index 000000000000..4249af06d738
  3374. --- /dev/null
  3375. +++ b/drivers/misc/surface_aggregator/clients/Makefile
  3376. @@ -0,0 +1,10 @@
  3377. +# SPDX-License-Identifier: GPL-2.0+
  3378. +# Copyright (C) 2019-2020 Maximilian Luz <luzmaximilian@gmail.com>
  3379. +
  3380. +obj-$(CONFIG_SURFACE_AGGREGATOR_CDEV) += surface_aggregator_cdev.o
  3381. +obj-$(CONFIG_SURFACE_AGGREGATOR_REGISTRY) += surface_aggregator_registry.o
  3382. +obj-$(CONFIG_SURFACE_ACPI_NOTIFY) += surface_acpi_notify.o
  3383. +obj-$(CONFIG_SURFACE_BATTERY) += surface_battery.o
  3384. +obj-$(CONFIG_SURFACE_DTX) += surface_dtx.o
  3385. +obj-$(CONFIG_SURFACE_HID) += surface_hid.o
  3386. +obj-$(CONFIG_SURFACE_PERFMODE) += surface_perfmode.o
  3387. diff --git a/drivers/misc/surface_aggregator/clients/surface_acpi_notify.c b/drivers/misc/surface_aggregator/clients/surface_acpi_notify.c
  3388. new file mode 100644
  3389. index 000000000000..8cd67a669c86
  3390. --- /dev/null
  3391. +++ b/drivers/misc/surface_aggregator/clients/surface_acpi_notify.c
  3392. @@ -0,0 +1,886 @@
  3393. +// SPDX-License-Identifier: GPL-2.0+
  3394. +/*
  3395. + * Driver for the Surface ACPI Notify (SAN) interface/shim.
  3396. + *
  3397. + * Translates communication from ACPI to Surface System Aggregator Module
  3398. + * (SSAM/SAM) requests and back, specifically SAM-over-SSH. Translates SSAM
  3399. + * events back to ACPI notifications. Allows handling of discrete GPU
  3400. + * notifications sent from ACPI via the SAN interface by providing them to any
  3401. + * registered external driver.
  3402. + *
  3403. + * Copyright (C) 2019-2020 Maximilian Luz <luzmaximilian@gmail.com>
  3404. + */
  3405. +
  3406. +#include <asm/unaligned.h>
  3407. +#include <linux/acpi.h>
  3408. +#include <linux/delay.h>
  3409. +#include <linux/jiffies.h>
  3410. +#include <linux/kernel.h>
  3411. +#include <linux/module.h>
  3412. +#include <linux/notifier.h>
  3413. +#include <linux/platform_device.h>
  3414. +#include <linux/rwsem.h>
  3415. +
  3416. +#include <linux/surface_aggregator/controller.h>
  3417. +#include <linux/surface_acpi_notify.h>
  3418. +
  3419. +struct san_data {
  3420. + struct device *dev;
  3421. + struct ssam_controller *ctrl;
  3422. +
  3423. + struct acpi_connection_info info;
  3424. +
  3425. + struct ssam_event_notifier nf_bat;
  3426. + struct ssam_event_notifier nf_tmp;
  3427. +};
  3428. +
  3429. +#define to_san_data(ptr, member) \
  3430. + container_of(ptr, struct san_data, member)
  3431. +
  3432. +
  3433. +/* -- dGPU notifier interface. ---------------------------------------------- */
  3434. +
  3435. +struct san_rqsg_if {
  3436. + struct rw_semaphore lock;
  3437. + struct device *dev;
  3438. + struct blocking_notifier_head nh;
  3439. +};
  3440. +
  3441. +static struct san_rqsg_if san_rqsg_if = {
  3442. + .lock = __RWSEM_INITIALIZER(san_rqsg_if.lock),
  3443. + .dev = NULL,
  3444. + .nh = BLOCKING_NOTIFIER_INIT(san_rqsg_if.nh),
  3445. +};
  3446. +
  3447. +static int san_set_rqsg_interface_device(struct device *dev)
  3448. +{
  3449. + int status = 0;
  3450. +
  3451. + down_write(&san_rqsg_if.lock);
  3452. + if (!san_rqsg_if.dev && dev)
  3453. + san_rqsg_if.dev = dev;
  3454. + else
  3455. + status = -EBUSY;
  3456. + up_write(&san_rqsg_if.lock);
  3457. +
  3458. + return status;
  3459. +}
  3460. +
  3461. +/**
  3462. + * san_client_link() - Link client as consumer to SAN device.
  3463. + * @client: The client to link.
  3464. + *
  3465. + * Sets up a device link between the provided client device as consumer and
  3466. + * the SAN device as provider. This function can be used to ensure that the
  3467. + * SAN interface has been set up and will be set up for as long as the driver
  3468. + * of the client device is bound. This guarantees that, during that time, all
  3469. + * dGPU events will be received by any registered notifier.
  3470. + *
  3471. + * The link will be automatically removed once the client device's driver is
  3472. + * unbound.
  3473. + *
  3474. + * Return: Returns zero on success, %-ENXIO if the SAN interface has not been
  3475. + * set up yet, and %-ENOMEM if device link creation failed.
  3476. + */
  3477. +int san_client_link(struct device *client)
  3478. +{
  3479. + const u32 flags = DL_FLAG_PM_RUNTIME | DL_FLAG_AUTOREMOVE_CONSUMER;
  3480. + struct device_link *link;
  3481. +
  3482. + down_read(&san_rqsg_if.lock);
  3483. +
  3484. + if (!san_rqsg_if.dev) {
  3485. + up_read(&san_rqsg_if.lock);
  3486. + return -ENXIO;
  3487. + }
  3488. +
  3489. + link = device_link_add(client, san_rqsg_if.dev, flags);
  3490. + if (!link) {
  3491. + up_read(&san_rqsg_if.lock);
  3492. + return -ENOMEM;
  3493. + }
  3494. +
  3495. + if (READ_ONCE(link->status) == DL_STATE_SUPPLIER_UNBIND) {
  3496. + up_read(&san_rqsg_if.lock);
  3497. + return -ENXIO;
  3498. + }
  3499. +
  3500. + up_read(&san_rqsg_if.lock);
  3501. + return 0;
  3502. +}
  3503. +EXPORT_SYMBOL_GPL(san_client_link);
  3504. +
  3505. +/**
  3506. + * san_dgpu_notifier_register() - Register a SAN dGPU notifier.
  3507. + * @nb: The notifier-block to register.
  3508. + *
  3509. + * Registers a SAN dGPU notifier, receiving any new SAN dGPU events sent from
  3510. + * ACPI. The registered notifier will be called with &struct san_dgpu_event
  3511. + * as notifier data and the command ID of that event as notifier action.
  3512. + */
  3513. +int san_dgpu_notifier_register(struct notifier_block *nb)
  3514. +{
  3515. + return blocking_notifier_chain_register(&san_rqsg_if.nh, nb);
  3516. +}
  3517. +EXPORT_SYMBOL_GPL(san_dgpu_notifier_register);
  3518. +
  3519. +/**
  3520. + * san_dgpu_notifier_unregister() - Unregister a SAN dGPU notifier.
  3521. + * @nb: The notifier-block to unregister.
  3522. + */
  3523. +int san_dgpu_notifier_unregister(struct notifier_block *nb)
  3524. +{
  3525. + return blocking_notifier_chain_unregister(&san_rqsg_if.nh, nb);
  3526. +}
  3527. +EXPORT_SYMBOL_GPL(san_dgpu_notifier_unregister);
  3528. +
  3529. +static int san_dgpu_notifier_call(struct san_dgpu_event *evt)
  3530. +{
  3531. + int ret;
  3532. +
  3533. + ret = blocking_notifier_call_chain(&san_rqsg_if.nh, evt->command, evt);
  3534. + return notifier_to_errno(ret);
  3535. +}
  3536. +
  3537. +
  3538. +/* -- ACPI _DSM event relay. ------------------------------------------------ */
  3539. +
  3540. +#define SAN_DSM_REVISION 0
  3541. +
  3542. +/* 93b666c5-70c6-469f-a215-3d487c91ab3c */
  3543. +static const guid_t SAN_DSM_UUID =
  3544. + GUID_INIT(0x93b666c5, 0x70c6, 0x469f, 0xa2, 0x15, 0x3d,
  3545. + 0x48, 0x7c, 0x91, 0xab, 0x3c);
  3546. +
  3547. +enum san_dsm_event_fn {
  3548. + SAN_DSM_EVENT_FN_BAT1_STAT = 0x03,
  3549. + SAN_DSM_EVENT_FN_BAT1_INFO = 0x04,
  3550. + SAN_DSM_EVENT_FN_ADP1_STAT = 0x05,
  3551. + SAN_DSM_EVENT_FN_ADP1_INFO = 0x06,
  3552. + SAN_DSM_EVENT_FN_BAT2_STAT = 0x07,
  3553. + SAN_DSM_EVENT_FN_BAT2_INFO = 0x08,
  3554. + SAN_DSM_EVENT_FN_THERMAL = 0x09,
  3555. + SAN_DSM_EVENT_FN_DPTF = 0x0a,
  3556. +};
  3557. +
  3558. +enum sam_event_cid_bat {
  3559. + SAM_EVENT_CID_BAT_BIX = 0x15,
  3560. + SAM_EVENT_CID_BAT_BST = 0x16,
  3561. + SAM_EVENT_CID_BAT_ADP = 0x17,
  3562. + SAM_EVENT_CID_BAT_PROT = 0x18,
  3563. + SAM_EVENT_CID_BAT_DPTF = 0x4f,
  3564. +};
  3565. +
  3566. +enum sam_event_cid_tmp {
  3567. + SAM_EVENT_CID_TMP_TRIP = 0x0b,
  3568. +};
  3569. +
  3570. +struct san_event_work {
  3571. + struct delayed_work work;
  3572. + struct device *dev;
  3573. + struct ssam_event event; /* must be last */
  3574. +};
  3575. +
  3576. +static int san_acpi_notify_event(struct device *dev, u64 func,
  3577. + union acpi_object *param)
  3578. +{
  3579. + acpi_handle san = ACPI_HANDLE(dev);
  3580. + union acpi_object *obj;
  3581. + int status = 0;
  3582. +
  3583. + if (!acpi_check_dsm(san, &SAN_DSM_UUID, SAN_DSM_REVISION, 1 << func))
  3584. + return 0;
  3585. +
  3586. + dev_dbg(dev, "notify event %#04llx\n", func);
  3587. +
  3588. + obj = acpi_evaluate_dsm_typed(san, &SAN_DSM_UUID, SAN_DSM_REVISION,
  3589. + func, param, ACPI_TYPE_BUFFER);
  3590. + if (!obj)
  3591. + return -EFAULT;
  3592. +
  3593. + if (obj->buffer.length != 1 || obj->buffer.pointer[0] != 0) {
  3594. + dev_err(dev, "got unexpected result from _DSM\n");
  3595. + status = -EPROTO;
  3596. + }
  3597. +
  3598. + ACPI_FREE(obj);
  3599. + return status;
  3600. +}
  3601. +
  3602. +static int san_evt_bat_adp(struct device *dev, const struct ssam_event *event)
  3603. +{
  3604. + int status;
  3605. +
  3606. + status = san_acpi_notify_event(dev, SAN_DSM_EVENT_FN_ADP1_STAT, NULL);
  3607. + if (status)
  3608. + return status;
  3609. +
  3610. + /*
  3611. + * Ensure that the battery states get updated correctly. When the
  3612. + * battery is fully charged and an adapter is plugged in, it sometimes
  3613. + * is not updated correctly, instead showing it as charging.
  3614. + * Explicitly trigger battery updates to fix this.
  3615. + */
  3616. +
  3617. + status = san_acpi_notify_event(dev, SAN_DSM_EVENT_FN_BAT1_STAT, NULL);
  3618. + if (status)
  3619. + return status;
  3620. +
  3621. + return san_acpi_notify_event(dev, SAN_DSM_EVENT_FN_BAT2_STAT, NULL);
  3622. +}
  3623. +
  3624. +static int san_evt_bat_bix(struct device *dev, const struct ssam_event *event)
  3625. +{
  3626. + enum san_dsm_event_fn fn;
  3627. +
  3628. + if (event->instance_id == 0x02)
  3629. + fn = SAN_DSM_EVENT_FN_BAT2_INFO;
  3630. + else
  3631. + fn = SAN_DSM_EVENT_FN_BAT1_INFO;
  3632. +
  3633. + return san_acpi_notify_event(dev, fn, NULL);
  3634. +}
  3635. +
  3636. +static int san_evt_bat_bst(struct device *dev, const struct ssam_event *event)
  3637. +{
  3638. + enum san_dsm_event_fn fn;
  3639. +
  3640. + if (event->instance_id == 0x02)
  3641. + fn = SAN_DSM_EVENT_FN_BAT2_STAT;
  3642. + else
  3643. + fn = SAN_DSM_EVENT_FN_BAT1_STAT;
  3644. +
  3645. + return san_acpi_notify_event(dev, fn, NULL);
  3646. +}
  3647. +
  3648. +static int san_evt_bat_dptf(struct device *dev, const struct ssam_event *event)
  3649. +{
  3650. + union acpi_object payload;
  3651. +
  3652. + /*
  3653. + * The Surface ACPI expects a buffer and not a package. It specifically
  3654. + * checks for ObjectType (Arg3) == 0x03. This will cause a warning in
  3655. + * acpica/nsarguments.c, but that warning can be safely ignored.
  3656. + */
  3657. + payload.type = ACPI_TYPE_BUFFER;
  3658. + payload.buffer.length = event->length;
  3659. + payload.buffer.pointer = (u8 *)&event->data[0];
  3660. +
  3661. + return san_acpi_notify_event(dev, SAN_DSM_EVENT_FN_DPTF, &payload);
  3662. +}
  3663. +
  3664. +static unsigned long san_evt_bat_delay(u8 cid)
  3665. +{
  3666. + switch (cid) {
  3667. + case SAM_EVENT_CID_BAT_ADP:
  3668. + /*
  3669. + * Wait for battery state to update before signaling adapter
  3670. + * change.
  3671. + */
  3672. + return msecs_to_jiffies(5000);
  3673. +
  3674. + case SAM_EVENT_CID_BAT_BST:
  3675. + /* Ensure we do not miss anything important due to caching. */
  3676. + return msecs_to_jiffies(2000);
  3677. +
  3678. + default:
  3679. + return 0;
  3680. + }
  3681. +}
  3682. +
  3683. +static bool san_evt_bat(const struct ssam_event *event, struct device *dev)
  3684. +{
  3685. + int status;
  3686. +
  3687. + switch (event->command_id) {
  3688. + case SAM_EVENT_CID_BAT_BIX:
  3689. + status = san_evt_bat_bix(dev, event);
  3690. + break;
  3691. +
  3692. + case SAM_EVENT_CID_BAT_BST:
  3693. + status = san_evt_bat_bst(dev, event);
  3694. + break;
  3695. +
  3696. + case SAM_EVENT_CID_BAT_ADP:
  3697. + status = san_evt_bat_adp(dev, event);
  3698. + break;
  3699. +
  3700. + case SAM_EVENT_CID_BAT_PROT:
  3701. + /*
  3702. + * TODO: Implement support for battery protection status change
  3703. + * event.
  3704. + */
  3705. + return true;
  3706. +
  3707. + case SAM_EVENT_CID_BAT_DPTF:
  3708. + status = san_evt_bat_dptf(dev, event);
  3709. + break;
  3710. +
  3711. + default:
  3712. + return false;
  3713. + }
  3714. +
  3715. + if (status) {
  3716. + dev_err(dev, "error handling power event (cid = %#04x)\n",
  3717. + event->command_id);
  3718. + }
  3719. +
  3720. + return true;
  3721. +}
  3722. +
  3723. +static void san_evt_bat_workfn(struct work_struct *work)
  3724. +{
  3725. + struct san_event_work *ev;
  3726. +
  3727. + ev = container_of(work, struct san_event_work, work.work);
  3728. + san_evt_bat(&ev->event, ev->dev);
  3729. + kfree(ev);
  3730. +}
  3731. +
  3732. +static u32 san_evt_bat_nf(struct ssam_event_notifier *nf,
  3733. + const struct ssam_event *event)
  3734. +{
  3735. + struct san_data *d = to_san_data(nf, nf_bat);
  3736. + struct san_event_work *work;
  3737. + unsigned long delay = san_evt_bat_delay(event->command_id);
  3738. +
  3739. + if (delay == 0)
  3740. + return san_evt_bat(event, d->dev) ? SSAM_NOTIF_HANDLED : 0;
  3741. +
  3742. + work = kzalloc(sizeof(*work) + event->length, GFP_KERNEL);
  3743. + if (!work)
  3744. + return ssam_notifier_from_errno(-ENOMEM);
  3745. +
  3746. + INIT_DELAYED_WORK(&work->work, san_evt_bat_workfn);
  3747. + work->dev = d->dev;
  3748. +
  3749. + memcpy(&work->event, event, sizeof(struct ssam_event) + event->length);
  3750. +
  3751. + schedule_delayed_work(&work->work, delay);
  3752. + return SSAM_NOTIF_HANDLED;
  3753. +}
  3754. +
  3755. +static int san_evt_tmp_trip(struct device *dev, const struct ssam_event *event)
  3756. +{
  3757. + union acpi_object param;
  3758. +
  3759. + /*
  3760. + * The Surface ACPI expects an integer and not a package. This will
  3761. + * cause a warning in acpica/nsarguments.c, but that warning can be
  3762. + * safely ignored.
  3763. + */
  3764. + param.type = ACPI_TYPE_INTEGER;
  3765. + param.integer.value = event->instance_id;
  3766. +
  3767. + return san_acpi_notify_event(dev, SAN_DSM_EVENT_FN_THERMAL, &param);
  3768. +}
  3769. +
  3770. +static bool san_evt_tmp(const struct ssam_event *event, struct device *dev)
  3771. +{
  3772. + int status;
  3773. +
  3774. + switch (event->command_id) {
  3775. + case SAM_EVENT_CID_TMP_TRIP:
  3776. + status = san_evt_tmp_trip(dev, event);
  3777. + break;
  3778. +
  3779. + default:
  3780. + return false;
  3781. + }
  3782. +
  3783. + if (status) {
  3784. + dev_err(dev, "error handling thermal event (cid = %#04x)\n",
  3785. + event->command_id);
  3786. + }
  3787. +
  3788. + return true;
  3789. +}
  3790. +
  3791. +static u32 san_evt_tmp_nf(struct ssam_event_notifier *nf,
  3792. + const struct ssam_event *event)
  3793. +{
  3794. + struct san_data *d = to_san_data(nf, nf_tmp);
  3795. +
  3796. + return san_evt_tmp(event, d->dev) ? SSAM_NOTIF_HANDLED : 0;
  3797. +}
  3798. +
  3799. +
  3800. +/* -- ACPI GSB OperationRegion handler -------------------------------------- */
  3801. +
  3802. +struct gsb_data_in {
  3803. + u8 cv;
  3804. +} __packed;
  3805. +
  3806. +struct gsb_data_rqsx {
  3807. + u8 cv; /* Command value (san_gsb_request_cv). */
  3808. + u8 tc; /* Target category. */
  3809. + u8 tid; /* Target ID. */
  3810. + u8 iid; /* Instance ID. */
  3811. + u8 snc; /* Expect-response-flag. */
  3812. + u8 cid; /* Command ID. */
  3813. + u16 cdl; /* Payload length. */
  3814. + u8 pld[]; /* Payload. */
  3815. +} __packed;
  3816. +
  3817. +struct gsb_data_etwl {
  3818. + u8 cv; /* Command value (should be 0x02). */
  3819. + u8 etw3; /* Unknown. */
  3820. + u8 etw4; /* Unknown. */
  3821. + u8 msg[]; /* Error message (ASCIIZ). */
  3822. +} __packed;
  3823. +
  3824. +struct gsb_data_out {
  3825. + u8 status; /* _SSH communication status. */
  3826. + u8 len; /* _SSH payload length. */
  3827. + u8 pld[]; /* _SSH payload. */
  3828. +} __packed;
  3829. +
  3830. +union gsb_buffer_data {
  3831. + struct gsb_data_in in; /* Common input. */
  3832. + struct gsb_data_rqsx rqsx; /* RQSX input. */
  3833. + struct gsb_data_etwl etwl; /* ETWL input. */
  3834. + struct gsb_data_out out; /* Output. */
  3835. +};
  3836. +
  3837. +struct gsb_buffer {
  3838. + u8 status; /* GSB AttribRawProcess status. */
  3839. + u8 len; /* GSB AttribRawProcess length. */
  3840. + union gsb_buffer_data data;
  3841. +} __packed;
  3842. +
  3843. +#define SAN_GSB_MAX_RQSX_PAYLOAD (U8_MAX - 2 - sizeof(struct gsb_data_rqsx))
  3844. +#define SAN_GSB_MAX_RESPONSE (U8_MAX - 2 - sizeof(struct gsb_data_out))
  3845. +
  3846. +#define SAN_GSB_COMMAND 0
  3847. +
  3848. +enum san_gsb_request_cv {
  3849. + SAN_GSB_REQUEST_CV_RQST = 0x01,
  3850. + SAN_GSB_REQUEST_CV_ETWL = 0x02,
  3851. + SAN_GSB_REQUEST_CV_RQSG = 0x03,
  3852. +};
  3853. +
  3854. +#define SAN_REQUEST_NUM_TRIES 5
  3855. +
  3856. +static acpi_status san_etwl(struct san_data *d, struct gsb_buffer *b)
  3857. +{
  3858. + struct gsb_data_etwl *etwl = &b->data.etwl;
  3859. +
  3860. + if (b->len < sizeof(struct gsb_data_etwl)) {
  3861. + dev_err(d->dev, "invalid ETWL package (len = %d)\n", b->len);
  3862. + return AE_OK;
  3863. + }
  3864. +
  3865. + dev_err(d->dev, "ETWL(%#04x, %#04x): %.*s\n", etwl->etw3, etwl->etw4,
  3866. + (unsigned int)(b->len - sizeof(struct gsb_data_etwl)),
  3867. + (char *)etwl->msg);
  3868. +
  3869. + /* Indicate success. */
  3870. + b->status = 0x00;
  3871. + b->len = 0x00;
  3872. +
  3873. + return AE_OK;
  3874. +}
  3875. +
  3876. +static
  3877. +struct gsb_data_rqsx *san_validate_rqsx(struct device *dev, const char *type,
  3878. + struct gsb_buffer *b)
  3879. +{
  3880. + struct gsb_data_rqsx *rqsx = &b->data.rqsx;
  3881. +
  3882. + if (b->len < sizeof(struct gsb_data_rqsx)) {
  3883. + dev_err(dev, "invalid %s package (len = %d)\n", type, b->len);
  3884. + return NULL;
  3885. + }
  3886. +
  3887. + if (get_unaligned(&rqsx->cdl) != b->len - sizeof(struct gsb_data_rqsx)) {
  3888. + dev_err(dev, "bogus %s package (len = %d, cdl = %d)\n",
  3889. + type, b->len, get_unaligned(&rqsx->cdl));
  3890. + return NULL;
  3891. + }
  3892. +
  3893. + if (get_unaligned(&rqsx->cdl) > SAN_GSB_MAX_RQSX_PAYLOAD) {
  3894. + dev_err(dev, "payload for %s package too large (cdl = %d)\n",
  3895. + type, get_unaligned(&rqsx->cdl));
  3896. + return NULL;
  3897. + }
  3898. +
  3899. + return rqsx;
  3900. +}
  3901. +
  3902. +static void gsb_rqsx_response_error(struct gsb_buffer *gsb, int status)
  3903. +{
  3904. + gsb->status = 0x00;
  3905. + gsb->len = 0x02;
  3906. + gsb->data.out.status = (u8)(-status);
  3907. + gsb->data.out.len = 0x00;
  3908. +}
  3909. +
  3910. +static void gsb_rqsx_response_success(struct gsb_buffer *gsb, u8 *ptr, size_t len)
  3911. +{
  3912. + gsb->status = 0x00;
  3913. + gsb->len = len + 2;
  3914. + gsb->data.out.status = 0x00;
  3915. + gsb->data.out.len = len;
  3916. +
  3917. + if (len)
  3918. + memcpy(&gsb->data.out.pld[0], ptr, len);
  3919. +}
  3920. +
  3921. +static acpi_status san_rqst_fixup_suspended(struct san_data *d,
  3922. + struct ssam_request *rqst,
  3923. + struct gsb_buffer *gsb)
  3924. +{
  3925. + if (rqst->target_category == SSAM_SSH_TC_BAS && rqst->command_id == 0x0D) {
  3926. + u8 base_state = 1;
  3927. +
  3928. + /* Base state quirk:
  3929. + * The base state may be queried from ACPI when the EC is still
  3930. + * suspended. In this case it will return '-EPERM'. This query
  3931. + * will only be triggered from the ACPI lid GPE interrupt, thus
  3932. + * we are either in laptop or studio mode (base status 0x01 or
  3933. + * 0x02). Furthermore, we will only get here if the device (and
  3934. + * EC) have been suspended.
  3935. + *
  3936. + * We now assume that the device is in laptop mode (0x01). This
  3937. + * has the drawback that it will wake the device when unfolding
  3938. + * it in studio mode, but it also allows us to avoid actively
  3939. + * waiting for the EC to wake up, which may incur a notable
  3940. + * delay.
  3941. + */
  3942. +
  3943. + dev_dbg(d->dev, "rqst: fixup: base-state quirk\n");
  3944. +
  3945. + gsb_rqsx_response_success(gsb, &base_state, sizeof(base_state));
  3946. + return AE_OK;
  3947. + }
  3948. +
  3949. + gsb_rqsx_response_error(gsb, -ENXIO);
  3950. + return AE_OK;
  3951. +}
  3952. +
  3953. +static acpi_status san_rqst(struct san_data *d, struct gsb_buffer *buffer)
  3954. +{
  3955. + u8 rspbuf[SAN_GSB_MAX_RESPONSE];
  3956. + struct gsb_data_rqsx *gsb_rqst;
  3957. + struct ssam_request rqst;
  3958. + struct ssam_response rsp;
  3959. + int status = 0;
  3960. +
  3961. + gsb_rqst = san_validate_rqsx(d->dev, "RQST", buffer);
  3962. + if (!gsb_rqst)
  3963. + return AE_OK;
  3964. +
  3965. + rqst.target_category = gsb_rqst->tc;
  3966. + rqst.target_id = gsb_rqst->tid;
  3967. + rqst.command_id = gsb_rqst->cid;
  3968. + rqst.instance_id = gsb_rqst->iid;
  3969. + rqst.flags = gsb_rqst->snc ? SSAM_REQUEST_HAS_RESPONSE : 0;
  3970. + rqst.length = get_unaligned(&gsb_rqst->cdl);
  3971. + rqst.payload = &gsb_rqst->pld[0];
  3972. +
  3973. + rsp.capacity = ARRAY_SIZE(rspbuf);
  3974. + rsp.length = 0;
  3975. + rsp.pointer = &rspbuf[0];
  3976. +
  3977. + /* Handle suspended device. */
  3978. + if (d->dev->power.is_suspended) {
  3979. + dev_warn(d->dev, "rqst: device is suspended, not executing\n");
  3980. + return san_rqst_fixup_suspended(d, &rqst, buffer);
  3981. + }
  3982. +
  3983. + status = __ssam_retry(ssam_request_sync_onstack, SAN_REQUEST_NUM_TRIES,
  3984. + d->ctrl, &rqst, &rsp, SAN_GSB_MAX_RQSX_PAYLOAD);
  3985. +
  3986. + if (!status) {
  3987. + gsb_rqsx_response_success(buffer, rsp.pointer, rsp.length);
  3988. + } else {
  3989. + dev_err(d->dev, "rqst: failed with error %d\n", status);
  3990. + gsb_rqsx_response_error(buffer, status);
  3991. + }
  3992. +
  3993. + return AE_OK;
  3994. +}
  3995. +
  3996. +static acpi_status san_rqsg(struct san_data *d, struct gsb_buffer *buffer)
  3997. +{
  3998. + struct gsb_data_rqsx *gsb_rqsg;
  3999. + struct san_dgpu_event evt;
  4000. + int status;
  4001. +
  4002. + gsb_rqsg = san_validate_rqsx(d->dev, "RQSG", buffer);
  4003. + if (!gsb_rqsg)
  4004. + return AE_OK;
  4005. +
  4006. + evt.category = gsb_rqsg->tc;
  4007. + evt.target = gsb_rqsg->tid;
  4008. + evt.command = gsb_rqsg->cid;
  4009. + evt.instance = gsb_rqsg->iid;
  4010. + evt.length = get_unaligned(&gsb_rqsg->cdl);
  4011. + evt.payload = &gsb_rqsg->pld[0];
  4012. +
  4013. + status = san_dgpu_notifier_call(&evt);
  4014. + if (!status) {
  4015. + gsb_rqsx_response_success(buffer, NULL, 0);
  4016. + } else {
  4017. + dev_err(d->dev, "rqsg: failed with error %d\n", status);
  4018. + gsb_rqsx_response_error(buffer, status);
  4019. + }
  4020. +
  4021. + return AE_OK;
  4022. +}
  4023. +
  4024. +static acpi_status san_opreg_handler(u32 function, acpi_physical_address command,
  4025. + u32 bits, u64 *value64, void *opreg_context,
  4026. + void *region_context)
  4027. +{
  4028. + struct san_data *d = to_san_data(opreg_context, info);
  4029. + struct gsb_buffer *buffer = (struct gsb_buffer *)value64;
  4030. + int accessor_type = (function & 0xFFFF0000) >> 16;
  4031. +
  4032. + if (command != SAN_GSB_COMMAND) {
  4033. + dev_warn(d->dev, "unsupported command: %#04llx\n", command);
  4034. + return AE_OK;
  4035. + }
  4036. +
  4037. + if (accessor_type != ACPI_GSB_ACCESS_ATTRIB_RAW_PROCESS) {
  4038. + dev_err(d->dev, "invalid access type: %#04x\n", accessor_type);
  4039. + return AE_OK;
  4040. + }
  4041. +
  4042. + /* Buffer must have at least contain the command-value. */
  4043. + if (buffer->len == 0) {
  4044. + dev_err(d->dev, "request-package too small\n");
  4045. + return AE_OK;
  4046. + }
  4047. +
  4048. + switch (buffer->data.in.cv) {
  4049. + case SAN_GSB_REQUEST_CV_RQST:
  4050. + return san_rqst(d, buffer);
  4051. +
  4052. + case SAN_GSB_REQUEST_CV_ETWL:
  4053. + return san_etwl(d, buffer);
  4054. +
  4055. + case SAN_GSB_REQUEST_CV_RQSG:
  4056. + return san_rqsg(d, buffer);
  4057. +
  4058. + default:
  4059. + dev_warn(d->dev, "unsupported SAN0 request (cv: %#04x)\n",
  4060. + buffer->data.in.cv);
  4061. + return AE_OK;
  4062. + }
  4063. +}
  4064. +
  4065. +
  4066. +/* -- Driver setup. --------------------------------------------------------- */
  4067. +
  4068. +static int san_events_register(struct platform_device *pdev)
  4069. +{
  4070. + struct san_data *d = platform_get_drvdata(pdev);
  4071. + int status;
  4072. +
  4073. + d->nf_bat.base.priority = 1;
  4074. + d->nf_bat.base.fn = san_evt_bat_nf;
  4075. + d->nf_bat.event.reg = SSAM_EVENT_REGISTRY_SAM;
  4076. + d->nf_bat.event.id.target_category = SSAM_SSH_TC_BAT;
  4077. + d->nf_bat.event.id.instance = 0;
  4078. + d->nf_bat.event.mask = SSAM_EVENT_MASK_TARGET;
  4079. + d->nf_bat.event.flags = SSAM_EVENT_SEQUENCED;
  4080. +
  4081. + d->nf_tmp.base.priority = 1;
  4082. + d->nf_tmp.base.fn = san_evt_tmp_nf;
  4083. + d->nf_tmp.event.reg = SSAM_EVENT_REGISTRY_SAM;
  4084. + d->nf_tmp.event.id.target_category = SSAM_SSH_TC_TMP;
  4085. + d->nf_tmp.event.id.instance = 0;
  4086. + d->nf_tmp.event.mask = SSAM_EVENT_MASK_TARGET;
  4087. + d->nf_tmp.event.flags = SSAM_EVENT_SEQUENCED;
  4088. +
  4089. + status = ssam_notifier_register(d->ctrl, &d->nf_bat);
  4090. + if (status)
  4091. + return status;
  4092. +
  4093. + status = ssam_notifier_register(d->ctrl, &d->nf_tmp);
  4094. + if (status)
  4095. + ssam_notifier_unregister(d->ctrl, &d->nf_bat);
  4096. +
  4097. + return status;
  4098. +}
  4099. +
  4100. +static void san_events_unregister(struct platform_device *pdev)
  4101. +{
  4102. + struct san_data *d = platform_get_drvdata(pdev);
  4103. +
  4104. + ssam_notifier_unregister(d->ctrl, &d->nf_bat);
  4105. + ssam_notifier_unregister(d->ctrl, &d->nf_tmp);
  4106. +}
  4107. +
  4108. +#define san_consumer_printk(level, dev, handle, fmt, ...) \
  4109. +do { \
  4110. + char *path = "<error getting consumer path>"; \
  4111. + struct acpi_buffer buffer = { \
  4112. + .length = ACPI_ALLOCATE_BUFFER, \
  4113. + .pointer = NULL, \
  4114. + }; \
  4115. + \
  4116. + if (ACPI_SUCCESS(acpi_get_name(handle, ACPI_FULL_PATHNAME, &buffer))) \
  4117. + path = buffer.pointer; \
  4118. + \
  4119. + dev_##level(dev, "[%s]: " fmt, path, ##__VA_ARGS__); \
  4120. + kfree(buffer.pointer); \
  4121. +} while (0)
  4122. +
  4123. +#define san_consumer_dbg(dev, handle, fmt, ...) \
  4124. + san_consumer_printk(dbg, dev, handle, fmt, ##__VA_ARGS__)
  4125. +
  4126. +#define san_consumer_warn(dev, handle, fmt, ...) \
  4127. + san_consumer_printk(warn, dev, handle, fmt, ##__VA_ARGS__)
  4128. +
  4129. +static bool is_san_consumer(struct platform_device *pdev, acpi_handle handle)
  4130. +{
  4131. + struct acpi_handle_list dep_devices;
  4132. + acpi_handle supplier = ACPI_HANDLE(&pdev->dev);
  4133. + acpi_status status;
  4134. + int i;
  4135. +
  4136. + if (!acpi_has_method(handle, "_DEP"))
  4137. + return false;
  4138. +
  4139. + status = acpi_evaluate_reference(handle, "_DEP", NULL, &dep_devices);
  4140. + if (ACPI_FAILURE(status)) {
  4141. + san_consumer_dbg(&pdev->dev, handle, "failed to evaluate _DEP\n");
  4142. + return false;
  4143. + }
  4144. +
  4145. + for (i = 0; i < dep_devices.count; i++) {
  4146. + if (dep_devices.handles[i] == supplier)
  4147. + return true;
  4148. + }
  4149. +
  4150. + return false;
  4151. +}
  4152. +
  4153. +static acpi_status san_consumer_setup(acpi_handle handle, u32 lvl,
  4154. + void *context, void **rv)
  4155. +{
  4156. + const u32 flags = DL_FLAG_PM_RUNTIME | DL_FLAG_AUTOREMOVE_SUPPLIER;
  4157. + struct platform_device *pdev = context;
  4158. + struct acpi_device *adev;
  4159. + struct device_link *link;
  4160. +
  4161. + if (!is_san_consumer(pdev, handle))
  4162. + return AE_OK;
  4163. +
  4164. + /* Ignore ACPI devices that are not present. */
  4165. + if (acpi_bus_get_device(handle, &adev) != 0)
  4166. + return AE_OK;
  4167. +
  4168. + san_consumer_dbg(&pdev->dev, handle, "creating device link\n");
  4169. +
  4170. + /* Try to set up device links, ignore but log errors. */
  4171. + link = device_link_add(&adev->dev, &pdev->dev, flags);
  4172. + if (!link) {
  4173. + san_consumer_warn(&pdev->dev, handle, "failed to create device link\n");
  4174. + return AE_OK;
  4175. + }
  4176. +
  4177. + return AE_OK;
  4178. +}
  4179. +
  4180. +static int san_consumer_links_setup(struct platform_device *pdev)
  4181. +{
  4182. + acpi_status status;
  4183. +
  4184. + status = acpi_walk_namespace(ACPI_TYPE_DEVICE, ACPI_ROOT_OBJECT,
  4185. + ACPI_UINT32_MAX, san_consumer_setup, NULL,
  4186. + pdev, NULL);
  4187. +
  4188. + return status ? -EFAULT : 0;
  4189. +}
  4190. +
  4191. +static int san_probe(struct platform_device *pdev)
  4192. +{
  4193. + acpi_handle san = ACPI_HANDLE(&pdev->dev);
  4194. + struct ssam_controller *ctrl;
  4195. + struct san_data *data;
  4196. + acpi_status astatus;
  4197. + int status;
  4198. +
  4199. + ctrl = ssam_client_bind(&pdev->dev);
  4200. + if (IS_ERR(ctrl))
  4201. + return PTR_ERR(ctrl) == -ENODEV ? -EPROBE_DEFER : PTR_ERR(ctrl);
  4202. +
  4203. + status = san_consumer_links_setup(pdev);
  4204. + if (status)
  4205. + return status;
  4206. +
  4207. + data = devm_kzalloc(&pdev->dev, sizeof(*data), GFP_KERNEL);
  4208. + if (!data)
  4209. + return -ENOMEM;
  4210. +
  4211. + data->dev = &pdev->dev;
  4212. + data->ctrl = ctrl;
  4213. +
  4214. + platform_set_drvdata(pdev, data);
  4215. +
  4216. + astatus = acpi_install_address_space_handler(san, ACPI_ADR_SPACE_GSBUS,
  4217. + &san_opreg_handler, NULL,
  4218. + &data->info);
  4219. + if (ACPI_FAILURE(astatus))
  4220. + return -ENXIO;
  4221. +
  4222. + status = san_events_register(pdev);
  4223. + if (status)
  4224. + goto err_enable_events;
  4225. +
  4226. + status = san_set_rqsg_interface_device(&pdev->dev);
  4227. + if (status)
  4228. + goto err_install_dev;
  4229. +
  4230. + acpi_walk_dep_device_list(san);
  4231. + return 0;
  4232. +
  4233. +err_install_dev:
  4234. + san_events_unregister(pdev);
  4235. +err_enable_events:
  4236. + acpi_remove_address_space_handler(san, ACPI_ADR_SPACE_GSBUS,
  4237. + &san_opreg_handler);
  4238. + return status;
  4239. +}
  4240. +
  4241. +static int san_remove(struct platform_device *pdev)
  4242. +{
  4243. + acpi_handle san = ACPI_HANDLE(&pdev->dev);
  4244. +
  4245. + san_set_rqsg_interface_device(NULL);
  4246. + acpi_remove_address_space_handler(san, ACPI_ADR_SPACE_GSBUS,
  4247. + &san_opreg_handler);
  4248. + san_events_unregister(pdev);
  4249. +
  4250. + /*
  4251. + * We have unregistered our event sources. Now we need to ensure that
  4252. + * all delayed works they may have spawned are run to completion.
  4253. + */
  4254. + flush_scheduled_work();
  4255. +
  4256. + return 0;
  4257. +}
  4258. +
  4259. +static const struct acpi_device_id san_match[] = {
  4260. + { "MSHW0091" },
  4261. + { },
  4262. +};
  4263. +MODULE_DEVICE_TABLE(acpi, san_match);
  4264. +
  4265. +static struct platform_driver surface_acpi_notify = {
  4266. + .probe = san_probe,
  4267. + .remove = san_remove,
  4268. + .driver = {
  4269. + .name = "surface_acpi_notify",
  4270. + .acpi_match_table = san_match,
  4271. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  4272. + },
  4273. +};
  4274. +module_platform_driver(surface_acpi_notify);
  4275. +
  4276. +MODULE_AUTHOR("Maximilian Luz <luzmaximilian@gmail.com>");
  4277. +MODULE_DESCRIPTION("Surface ACPI Notify driver for Surface System Aggregator Module");
  4278. +MODULE_LICENSE("GPL");
  4279. diff --git a/drivers/misc/surface_aggregator/clients/surface_aggregator_cdev.c b/drivers/misc/surface_aggregator/clients/surface_aggregator_cdev.c
  4280. new file mode 100644
  4281. index 000000000000..340d15b148b9
  4282. --- /dev/null
  4283. +++ b/drivers/misc/surface_aggregator/clients/surface_aggregator_cdev.c
  4284. @@ -0,0 +1,303 @@
  4285. +// SPDX-License-Identifier: GPL-2.0+
  4286. +/*
  4287. + * Provides user-space access to the SSAM EC via the /dev/surface/aggregator
  4288. + * misc device. Intended for debugging and development.
  4289. + *
  4290. + * Copyright (C) 2020 Maximilian Luz <luzmaximilian@gmail.com>
  4291. + */
  4292. +
  4293. +#include <linux/fs.h>
  4294. +#include <linux/kernel.h>
  4295. +#include <linux/kref.h>
  4296. +#include <linux/miscdevice.h>
  4297. +#include <linux/module.h>
  4298. +#include <linux/platform_device.h>
  4299. +#include <linux/rwsem.h>
  4300. +#include <linux/slab.h>
  4301. +#include <linux/uaccess.h>
  4302. +
  4303. +#include <linux/surface_aggregator/cdev.h>
  4304. +#include <linux/surface_aggregator/controller.h>
  4305. +
  4306. +#define SSAM_CDEV_DEVICE_NAME "surface_aggregator_cdev"
  4307. +
  4308. +struct ssam_cdev {
  4309. + struct kref kref;
  4310. + struct rw_semaphore lock;
  4311. + struct ssam_controller *ctrl;
  4312. + struct miscdevice mdev;
  4313. +};
  4314. +
  4315. +static void __ssam_cdev_release(struct kref *kref)
  4316. +{
  4317. + kfree(container_of(kref, struct ssam_cdev, kref));
  4318. +}
  4319. +
  4320. +static struct ssam_cdev *ssam_cdev_get(struct ssam_cdev *cdev)
  4321. +{
  4322. + if (cdev)
  4323. + kref_get(&cdev->kref);
  4324. +
  4325. + return cdev;
  4326. +}
  4327. +
  4328. +static void ssam_cdev_put(struct ssam_cdev *cdev)
  4329. +{
  4330. + if (cdev)
  4331. + kref_put(&cdev->kref, __ssam_cdev_release);
  4332. +}
  4333. +
  4334. +static int ssam_cdev_device_open(struct inode *inode, struct file *filp)
  4335. +{
  4336. + struct miscdevice *mdev = filp->private_data;
  4337. + struct ssam_cdev *cdev = container_of(mdev, struct ssam_cdev, mdev);
  4338. +
  4339. + filp->private_data = ssam_cdev_get(cdev);
  4340. + return stream_open(inode, filp);
  4341. +}
  4342. +
  4343. +static int ssam_cdev_device_release(struct inode *inode, struct file *filp)
  4344. +{
  4345. + ssam_cdev_put(filp->private_data);
  4346. + return 0;
  4347. +}
  4348. +
  4349. +static long ssam_cdev_request(struct ssam_cdev *cdev, unsigned long arg)
  4350. +{
  4351. + struct ssam_cdev_request __user *r;
  4352. + struct ssam_cdev_request rqst;
  4353. + struct ssam_request spec;
  4354. + struct ssam_response rsp;
  4355. + const void __user *plddata;
  4356. + void __user *rspdata;
  4357. + int status = 0, ret = 0, tmp;
  4358. +
  4359. + r = (struct ssam_cdev_request __user *)arg;
  4360. + ret = copy_struct_from_user(&rqst, sizeof(rqst), r, sizeof(*r));
  4361. + if (ret)
  4362. + goto out;
  4363. +
  4364. + plddata = u64_to_user_ptr(rqst.payload.data);
  4365. + rspdata = u64_to_user_ptr(rqst.response.data);
  4366. +
  4367. + /* Setup basic request fields. */
  4368. + spec.target_category = rqst.target_category;
  4369. + spec.target_id = rqst.target_id;
  4370. + spec.command_id = rqst.command_id;
  4371. + spec.instance_id = rqst.instance_id;
  4372. + spec.flags = 0;
  4373. + spec.length = rqst.payload.length;
  4374. + spec.payload = NULL;
  4375. +
  4376. + if (rqst.flags & SSAM_CDEV_REQUEST_HAS_RESPONSE)
  4377. + spec.flags |= SSAM_REQUEST_HAS_RESPONSE;
  4378. +
  4379. + if (rqst.flags & SSAM_CDEV_REQUEST_UNSEQUENCED)
  4380. + spec.flags |= SSAM_REQUEST_UNSEQUENCED;
  4381. +
  4382. + rsp.capacity = rqst.response.length;
  4383. + rsp.length = 0;
  4384. + rsp.pointer = NULL;
  4385. +
  4386. + /* Get request payload from user-space. */
  4387. + if (spec.length) {
  4388. + if (!plddata) {
  4389. + ret = -EINVAL;
  4390. + goto out;
  4391. + }
  4392. +
  4393. + spec.payload = kzalloc(spec.length, GFP_KERNEL);
  4394. + if (!spec.payload) {
  4395. + ret = -ENOMEM;
  4396. + goto out;
  4397. + }
  4398. +
  4399. + if (copy_from_user((void *)spec.payload, plddata, spec.length)) {
  4400. + ret = -EFAULT;
  4401. + goto out;
  4402. + }
  4403. + }
  4404. +
  4405. + /* Allocate response buffer. */
  4406. + if (rsp.capacity) {
  4407. + if (!rspdata) {
  4408. + ret = -EINVAL;
  4409. + goto out;
  4410. + }
  4411. +
  4412. + rsp.pointer = kzalloc(rsp.capacity, GFP_KERNEL);
  4413. + if (!rsp.pointer) {
  4414. + ret = -ENOMEM;
  4415. + goto out;
  4416. + }
  4417. + }
  4418. +
  4419. + /* Perform request. */
  4420. + status = ssam_request_sync(cdev->ctrl, &spec, &rsp);
  4421. + if (status)
  4422. + goto out;
  4423. +
  4424. + /* Copy response to user-space. */
  4425. + if (rsp.length && copy_to_user(rspdata, rsp.pointer, rsp.length))
  4426. + ret = -EFAULT;
  4427. +
  4428. +out:
  4429. + /* Always try to set response-length and status. */
  4430. + tmp = put_user(rsp.length, &r->response.length);
  4431. + if (tmp)
  4432. + ret = tmp;
  4433. +
  4434. + tmp = put_user(status, &r->status);
  4435. + if (tmp)
  4436. + ret = tmp;
  4437. +
  4438. + /* Cleanup. */
  4439. + kfree(spec.payload);
  4440. + kfree(rsp.pointer);
  4441. +
  4442. + return ret;
  4443. +}
  4444. +
  4445. +static long __ssam_cdev_device_ioctl(struct ssam_cdev *cdev, unsigned int cmd,
  4446. + unsigned long arg)
  4447. +{
  4448. + switch (cmd) {
  4449. + case SSAM_CDEV_REQUEST:
  4450. + return ssam_cdev_request(cdev, arg);
  4451. +
  4452. + default:
  4453. + return -ENOTTY;
  4454. + }
  4455. +}
  4456. +
  4457. +static long ssam_cdev_device_ioctl(struct file *file, unsigned int cmd,
  4458. + unsigned long arg)
  4459. +{
  4460. + struct ssam_cdev *cdev = file->private_data;
  4461. + long status;
  4462. +
  4463. + /* Ensure that controller is valid for as long as we need it. */
  4464. + if (down_read_killable(&cdev->lock))
  4465. + return -ERESTARTSYS;
  4466. +
  4467. + if (!cdev->ctrl) {
  4468. + up_read(&cdev->lock);
  4469. + return -ENODEV;
  4470. + }
  4471. +
  4472. + status = __ssam_cdev_device_ioctl(cdev, cmd, arg);
  4473. +
  4474. + up_read(&cdev->lock);
  4475. + return status;
  4476. +}
  4477. +
  4478. +static const struct file_operations ssam_controller_fops = {
  4479. + .owner = THIS_MODULE,
  4480. + .open = ssam_cdev_device_open,
  4481. + .release = ssam_cdev_device_release,
  4482. + .unlocked_ioctl = ssam_cdev_device_ioctl,
  4483. + .compat_ioctl = ssam_cdev_device_ioctl,
  4484. + .llseek = noop_llseek,
  4485. +};
  4486. +
  4487. +static int ssam_dbg_device_probe(struct platform_device *pdev)
  4488. +{
  4489. + struct ssam_controller *ctrl;
  4490. + struct ssam_cdev *cdev;
  4491. + int status;
  4492. +
  4493. + ctrl = ssam_client_bind(&pdev->dev);
  4494. + if (IS_ERR(ctrl))
  4495. + return PTR_ERR(ctrl) == -ENODEV ? -EPROBE_DEFER : PTR_ERR(ctrl);
  4496. +
  4497. + cdev = kzalloc(sizeof(*cdev), GFP_KERNEL);
  4498. + if (!cdev)
  4499. + return -ENOMEM;
  4500. +
  4501. + kref_init(&cdev->kref);
  4502. + init_rwsem(&cdev->lock);
  4503. + cdev->ctrl = ctrl;
  4504. +
  4505. + cdev->mdev.parent = &pdev->dev;
  4506. + cdev->mdev.minor = MISC_DYNAMIC_MINOR;
  4507. + cdev->mdev.name = "surface_aggregator";
  4508. + cdev->mdev.nodename = "surface/aggregator";
  4509. + cdev->mdev.fops = &ssam_controller_fops;
  4510. +
  4511. + status = misc_register(&cdev->mdev);
  4512. + if (status) {
  4513. + kfree(cdev);
  4514. + return status;
  4515. + }
  4516. +
  4517. + platform_set_drvdata(pdev, cdev);
  4518. + return 0;
  4519. +}
  4520. +
  4521. +static int ssam_dbg_device_remove(struct platform_device *pdev)
  4522. +{
  4523. + struct ssam_cdev *cdev = platform_get_drvdata(pdev);
  4524. +
  4525. + misc_deregister(&cdev->mdev);
  4526. +
  4527. + /*
  4528. + * The controller is only guaranteed to be valid for as long as the
  4529. + * driver is bound. Remove controller so that any lingering open files
  4530. + * cannot access it any more after we're gone.
  4531. + */
  4532. + down_write(&cdev->lock);
  4533. + cdev->ctrl = NULL;
  4534. + up_write(&cdev->lock);
  4535. +
  4536. + ssam_cdev_put(cdev);
  4537. + return 0;
  4538. +}
  4539. +
  4540. +static struct platform_device *ssam_cdev_device;
  4541. +
  4542. +static struct platform_driver ssam_cdev_driver = {
  4543. + .probe = ssam_dbg_device_probe,
  4544. + .remove = ssam_dbg_device_remove,
  4545. + .driver = {
  4546. + .name = SSAM_CDEV_DEVICE_NAME,
  4547. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  4548. + },
  4549. +};
  4550. +
  4551. +static int __init ssam_debug_init(void)
  4552. +{
  4553. + int status;
  4554. +
  4555. + ssam_cdev_device = platform_device_alloc(SSAM_CDEV_DEVICE_NAME,
  4556. + PLATFORM_DEVID_NONE);
  4557. + if (!ssam_cdev_device)
  4558. + return -ENOMEM;
  4559. +
  4560. + status = platform_device_add(ssam_cdev_device);
  4561. + if (status)
  4562. + goto err_device;
  4563. +
  4564. + status = platform_driver_register(&ssam_cdev_driver);
  4565. + if (status)
  4566. + goto err_driver;
  4567. +
  4568. + return 0;
  4569. +
  4570. +err_driver:
  4571. + platform_device_del(ssam_cdev_device);
  4572. +err_device:
  4573. + platform_device_put(ssam_cdev_device);
  4574. + return status;
  4575. +}
  4576. +module_init(ssam_debug_init);
  4577. +
  4578. +static void __exit ssam_debug_exit(void)
  4579. +{
  4580. + platform_driver_unregister(&ssam_cdev_driver);
  4581. + platform_device_unregister(ssam_cdev_device);
  4582. +}
  4583. +module_exit(ssam_debug_exit);
  4584. +
  4585. +MODULE_AUTHOR("Maximilian Luz <luzmaximilian@gmail.com>");
  4586. +MODULE_DESCRIPTION("User-space interface for Surface System Aggregator Module");
  4587. +MODULE_LICENSE("GPL");
  4588. diff --git a/drivers/misc/surface_aggregator/clients/surface_aggregator_registry.c b/drivers/misc/surface_aggregator/clients/surface_aggregator_registry.c
  4589. new file mode 100644
  4590. index 000000000000..b58930751404
  4591. --- /dev/null
  4592. +++ b/drivers/misc/surface_aggregator/clients/surface_aggregator_registry.c
  4593. @@ -0,0 +1,665 @@
  4594. +// SPDX-License-Identifier: GPL-2.0+
  4595. +/*
  4596. + * Surface System Aggregator Module (SSAM) client device registry.
  4597. + *
  4598. + * Registry for non-platform/non-ACPI SSAM client devices, i.e. devices that
  4599. + * cannot be auto-detected. Provides device-hubs for these devices.
  4600. + *
  4601. + * Copyright (C) 2020 Maximilian Luz <luzmaximilian@gmail.com>
  4602. + */
  4603. +
  4604. +#include <linux/acpi.h>
  4605. +#include <linux/kernel.h>
  4606. +#include <linux/module.h>
  4607. +#include <linux/mutex.h>
  4608. +#include <linux/notifier.h>
  4609. +#include <linux/platform_device.h>
  4610. +#include <linux/types.h>
  4611. +
  4612. +#include <linux/surface_aggregator/controller.h>
  4613. +#include <linux/surface_aggregator/device.h>
  4614. +
  4615. +
  4616. +/* -- Device registry. ------------------------------------------------------ */
  4617. +
  4618. +static const struct software_node ssam_node_root = {
  4619. + .name = "ssam_platform_hub",
  4620. +};
  4621. +
  4622. +static const struct software_node ssam_node_hub_main = {
  4623. + .name = "ssam:00:00:01:00:00",
  4624. + .parent = &ssam_node_root,
  4625. +};
  4626. +
  4627. +static const struct software_node ssam_node_hub_base = {
  4628. + .name = "ssam:00:00:02:00:00",
  4629. + .parent = &ssam_node_root,
  4630. +};
  4631. +
  4632. +static const struct software_node ssam_node_bat_ac = {
  4633. + .name = "ssam:01:02:01:01:01",
  4634. + .parent = &ssam_node_hub_main,
  4635. +};
  4636. +
  4637. +static const struct software_node ssam_node_bat_main = {
  4638. + .name = "ssam:01:02:01:01:00",
  4639. + .parent = &ssam_node_hub_main,
  4640. +};
  4641. +
  4642. +static const struct software_node ssam_node_bat_sb3base = {
  4643. + .name = "ssam:01:02:02:01:00",
  4644. + .parent = &ssam_node_hub_base,
  4645. +};
  4646. +
  4647. +static const struct software_node ssam_node_tmp_perf = {
  4648. + .name = "ssam:01:03:01:00:01",
  4649. + .parent = &ssam_node_hub_main,
  4650. +};
  4651. +
  4652. +static const struct software_node ssam_node_bas_dtx = {
  4653. + .name = "ssam:01:11:01:00:00",
  4654. + .parent = &ssam_node_hub_main,
  4655. +};
  4656. +
  4657. +static const struct software_node ssam_node_hid_main_keyboard = {
  4658. + .name = "ssam:01:15:02:01:00",
  4659. + .parent = &ssam_node_hub_main,
  4660. +};
  4661. +
  4662. +static const struct software_node ssam_node_hid_main_touchpad = {
  4663. + .name = "ssam:01:15:02:03:00",
  4664. + .parent = &ssam_node_hub_main,
  4665. +};
  4666. +
  4667. +static const struct software_node ssam_node_hid_main_iid5 = {
  4668. + .name = "ssam:01:15:02:05:00",
  4669. + .parent = &ssam_node_hub_main,
  4670. +};
  4671. +
  4672. +static const struct software_node ssam_node_hid_base_keyboard = {
  4673. + .name = "ssam:01:15:02:01:00",
  4674. + .parent = &ssam_node_hub_base,
  4675. +};
  4676. +
  4677. +static const struct software_node ssam_node_hid_base_touchpad = {
  4678. + .name = "ssam:01:15:02:03:00",
  4679. + .parent = &ssam_node_hub_base,
  4680. +};
  4681. +
  4682. +static const struct software_node ssam_node_hid_base_iid5 = {
  4683. + .name = "ssam:01:15:02:05:00",
  4684. + .parent = &ssam_node_hub_base,
  4685. +};
  4686. +
  4687. +static const struct software_node ssam_node_hid_base_iid6 = {
  4688. + .name = "ssam:01:15:02:06:00",
  4689. + .parent = &ssam_node_hub_base,
  4690. +};
  4691. +
  4692. +static const struct software_node *ssam_node_group_sb2[] = {
  4693. + &ssam_node_root,
  4694. + &ssam_node_hub_main,
  4695. + &ssam_node_tmp_perf,
  4696. + NULL,
  4697. +};
  4698. +
  4699. +static const struct software_node *ssam_node_group_sb3[] = {
  4700. + &ssam_node_root,
  4701. + &ssam_node_hub_main,
  4702. + &ssam_node_hub_base,
  4703. + &ssam_node_tmp_perf,
  4704. + &ssam_node_bat_ac,
  4705. + &ssam_node_bat_main,
  4706. + &ssam_node_bat_sb3base,
  4707. + &ssam_node_hid_base_keyboard,
  4708. + &ssam_node_hid_base_touchpad,
  4709. + &ssam_node_hid_base_iid5,
  4710. + &ssam_node_hid_base_iid6,
  4711. + &ssam_node_bas_dtx,
  4712. + NULL,
  4713. +};
  4714. +
  4715. +static const struct software_node *ssam_node_group_sl1[] = {
  4716. + &ssam_node_root,
  4717. + &ssam_node_hub_main,
  4718. + &ssam_node_tmp_perf,
  4719. + NULL,
  4720. +};
  4721. +
  4722. +static const struct software_node *ssam_node_group_sl2[] = {
  4723. + &ssam_node_root,
  4724. + &ssam_node_hub_main,
  4725. + &ssam_node_tmp_perf,
  4726. + NULL,
  4727. +};
  4728. +
  4729. +static const struct software_node *ssam_node_group_sl3[] = {
  4730. + &ssam_node_root,
  4731. + &ssam_node_hub_main,
  4732. + &ssam_node_tmp_perf,
  4733. + &ssam_node_bat_ac,
  4734. + &ssam_node_bat_main,
  4735. + &ssam_node_hid_main_keyboard,
  4736. + &ssam_node_hid_main_touchpad,
  4737. + &ssam_node_hid_main_iid5,
  4738. + NULL,
  4739. +};
  4740. +
  4741. +static const struct software_node *ssam_node_group_slg1[] = {
  4742. + &ssam_node_root,
  4743. + &ssam_node_hub_main,
  4744. + &ssam_node_tmp_perf,
  4745. + &ssam_node_bat_ac,
  4746. + &ssam_node_bat_main,
  4747. + NULL,
  4748. +};
  4749. +
  4750. +static const struct software_node *ssam_node_group_sp5[] = {
  4751. + &ssam_node_root,
  4752. + &ssam_node_hub_main,
  4753. + &ssam_node_tmp_perf,
  4754. + NULL,
  4755. +};
  4756. +
  4757. +static const struct software_node *ssam_node_group_sp6[] = {
  4758. + &ssam_node_root,
  4759. + &ssam_node_hub_main,
  4760. + &ssam_node_tmp_perf,
  4761. + NULL,
  4762. +};
  4763. +
  4764. +static const struct software_node *ssam_node_group_sp7[] = {
  4765. + &ssam_node_root,
  4766. + &ssam_node_hub_main,
  4767. + &ssam_node_tmp_perf,
  4768. + &ssam_node_bat_ac,
  4769. + &ssam_node_bat_main,
  4770. + NULL,
  4771. +};
  4772. +
  4773. +
  4774. +/* -- Device registry helper functions. ------------------------------------- */
  4775. +
  4776. +static int ssam_uid_from_string(const char *str, struct ssam_device_uid *uid)
  4777. +{
  4778. + u8 d, tc, tid, iid, fn;
  4779. + int n;
  4780. +
  4781. + n = sscanf(str, "ssam:%hhx:%hhx:%hhx:%hhx:%hhx", &d, &tc, &tid, &iid, &fn);
  4782. + if (n != 5)
  4783. + return -EINVAL;
  4784. +
  4785. + uid->domain = d;
  4786. + uid->category = tc;
  4787. + uid->target = tid;
  4788. + uid->instance = iid;
  4789. + uid->function = fn;
  4790. +
  4791. + return 0;
  4792. +}
  4793. +
  4794. +static int ssam_hub_remove_devices_fn(struct device *dev, void *data)
  4795. +{
  4796. + if (!is_ssam_device(dev))
  4797. + return 0;
  4798. +
  4799. + ssam_device_remove(to_ssam_device(dev));
  4800. + return 0;
  4801. +}
  4802. +
  4803. +static void ssam_hub_remove_devices(struct device *parent)
  4804. +{
  4805. + device_for_each_child_reverse(parent, NULL, ssam_hub_remove_devices_fn);
  4806. +}
  4807. +
  4808. +static int ssam_hub_add_device(struct device *parent,
  4809. + struct ssam_controller *ctrl,
  4810. + struct fwnode_handle *node)
  4811. +{
  4812. + struct ssam_device_uid uid;
  4813. + struct ssam_device *sdev;
  4814. + int status;
  4815. +
  4816. + status = ssam_uid_from_string(fwnode_get_name(node), &uid);
  4817. + if (status)
  4818. + return -ENODEV;
  4819. +
  4820. + sdev = ssam_device_alloc(ctrl, uid);
  4821. + if (!sdev)
  4822. + return -ENOMEM;
  4823. +
  4824. + sdev->dev.parent = parent;
  4825. + sdev->dev.fwnode = node;
  4826. +
  4827. + status = ssam_device_add(sdev);
  4828. + if (status)
  4829. + ssam_device_put(sdev);
  4830. +
  4831. + return status;
  4832. +}
  4833. +
  4834. +static int ssam_hub_add_devices(struct device *parent,
  4835. + struct ssam_controller *ctrl,
  4836. + struct fwnode_handle *node)
  4837. +{
  4838. + struct fwnode_handle *child;
  4839. + int status;
  4840. +
  4841. + fwnode_for_each_child_node(node, child) {
  4842. + status = ssam_hub_add_device(parent, ctrl, child);
  4843. + if (status && status != -ENODEV)
  4844. + goto err;
  4845. + }
  4846. +
  4847. + return 0;
  4848. +err:
  4849. + ssam_hub_remove_devices(parent);
  4850. + return status;
  4851. +}
  4852. +
  4853. +
  4854. +/* -- SSAM main-hub driver. ------------------------------------------------- */
  4855. +
  4856. +static int ssam_hub_probe(struct ssam_device *sdev)
  4857. +{
  4858. + struct fwnode_handle *node = dev_fwnode(&sdev->dev);
  4859. +
  4860. + if (!node)
  4861. + return -ENODEV;
  4862. +
  4863. + return ssam_hub_add_devices(&sdev->dev, sdev->ctrl, node);
  4864. +}
  4865. +
  4866. +static void ssam_hub_remove(struct ssam_device *sdev)
  4867. +{
  4868. + ssam_hub_remove_devices(&sdev->dev);
  4869. +}
  4870. +
  4871. +static const struct ssam_device_id ssam_hub_match[] = {
  4872. + { SSAM_VDEV(HUB, 0x01, 0x00, 0x00) },
  4873. + { },
  4874. +};
  4875. +
  4876. +static struct ssam_device_driver ssam_hub_driver = {
  4877. + .probe = ssam_hub_probe,
  4878. + .remove = ssam_hub_remove,
  4879. + .match_table = ssam_hub_match,
  4880. + .driver = {
  4881. + .name = "surface_aggregator_device_hub",
  4882. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  4883. + },
  4884. +};
  4885. +
  4886. +
  4887. +/* -- SSAM base-hub driver. ------------------------------------------------- */
  4888. +
  4889. +enum ssam_base_hub_state {
  4890. + SSAM_BASE_HUB_UNINITIALIZED,
  4891. + SSAM_BASE_HUB_CONNECTED,
  4892. + SSAM_BASE_HUB_DISCONNECTED,
  4893. +};
  4894. +
  4895. +struct ssam_base_hub {
  4896. + struct ssam_device *sdev;
  4897. +
  4898. + struct mutex lock;
  4899. + enum ssam_base_hub_state state;
  4900. +
  4901. + struct ssam_event_notifier notif;
  4902. +};
  4903. +
  4904. +static SSAM_DEFINE_SYNC_REQUEST_R(ssam_bas_query_opmode, u8, {
  4905. + .target_category = SSAM_SSH_TC_BAS,
  4906. + .target_id = 0x01,
  4907. + .command_id = 0x0d,
  4908. + .instance_id = 0x00,
  4909. +});
  4910. +
  4911. +#define SSAM_BAS_OPMODE_TABLET 0x00
  4912. +#define SSAM_EVENT_BAS_CID_CONNECTION 0x0c
  4913. +
  4914. +static int ssam_base_hub_query_state(struct ssam_device *sdev,
  4915. + enum ssam_base_hub_state *state)
  4916. +{
  4917. + u8 opmode;
  4918. + int status;
  4919. +
  4920. + status = ssam_retry(ssam_bas_query_opmode, sdev->ctrl, &opmode);
  4921. + if (status < 0) {
  4922. + dev_err(&sdev->dev, "failed to query base state: %d\n", status);
  4923. + return status;
  4924. + }
  4925. +
  4926. + if (opmode != SSAM_BAS_OPMODE_TABLET)
  4927. + *state = SSAM_BASE_HUB_CONNECTED;
  4928. + else
  4929. + *state = SSAM_BASE_HUB_DISCONNECTED;
  4930. +
  4931. + return 0;
  4932. +}
  4933. +
  4934. +static ssize_t ssam_base_hub_state_show(struct device *dev,
  4935. + struct device_attribute *attr,
  4936. + char *buf)
  4937. +{
  4938. + struct ssam_device *sdev = to_ssam_device(dev);
  4939. + struct ssam_base_hub *hub = ssam_device_get_drvdata(sdev);
  4940. + bool connected;
  4941. +
  4942. + mutex_lock(&hub->lock);
  4943. + connected = hub->state == SSAM_BASE_HUB_CONNECTED;
  4944. + mutex_unlock(&hub->lock);
  4945. +
  4946. + // FIXME: we should use sysfs_emit here, but that's not available on < 5.10
  4947. + return scnprintf(buf, PAGE_SIZE, "%d\n", connected);
  4948. +}
  4949. +
  4950. +static struct device_attribute ssam_base_hub_attr_state =
  4951. + __ATTR(state, 0444, ssam_base_hub_state_show, NULL);
  4952. +
  4953. +static struct attribute *ssam_base_hub_attrs[] = {
  4954. + &ssam_base_hub_attr_state.attr,
  4955. + NULL,
  4956. +};
  4957. +
  4958. +const struct attribute_group ssam_base_hub_group = {
  4959. + .attrs = ssam_base_hub_attrs,
  4960. +};
  4961. +
  4962. +static int ssam_base_hub_update(struct ssam_device *sdev,
  4963. + enum ssam_base_hub_state new)
  4964. +{
  4965. + struct ssam_base_hub *hub = ssam_device_get_drvdata(sdev);
  4966. + struct fwnode_handle *node = dev_fwnode(&sdev->dev);
  4967. + int status = 0;
  4968. +
  4969. + mutex_lock(&hub->lock);
  4970. + if (hub->state == new) {
  4971. + mutex_unlock(&hub->lock);
  4972. + return 0;
  4973. + }
  4974. + hub->state = new;
  4975. +
  4976. + if (hub->state == SSAM_BASE_HUB_CONNECTED)
  4977. + status = ssam_hub_add_devices(&sdev->dev, sdev->ctrl, node);
  4978. +
  4979. + if (hub->state != SSAM_BASE_HUB_CONNECTED || status)
  4980. + ssam_hub_remove_devices(&sdev->dev);
  4981. +
  4982. + mutex_unlock(&hub->lock);
  4983. +
  4984. + if (status) {
  4985. + dev_err(&sdev->dev, "failed to update base-hub devices: %d\n",
  4986. + status);
  4987. + }
  4988. +
  4989. + return status;
  4990. +}
  4991. +
  4992. +static u32 ssam_base_hub_notif(struct ssam_event_notifier *nf,
  4993. + const struct ssam_event *event)
  4994. +{
  4995. + struct ssam_base_hub *hub;
  4996. + struct ssam_device *sdev;
  4997. + enum ssam_base_hub_state new;
  4998. +
  4999. + hub = container_of(nf, struct ssam_base_hub, notif);
  5000. + sdev = hub->sdev;
  5001. +
  5002. + if (event->command_id != SSAM_EVENT_BAS_CID_CONNECTION)
  5003. + return 0;
  5004. +
  5005. + if (event->length < 1) {
  5006. + dev_err(&sdev->dev, "unexpected payload size: %u\n",
  5007. + event->length);
  5008. + return 0;
  5009. + }
  5010. +
  5011. + if (event->data[0])
  5012. + new = SSAM_BASE_HUB_CONNECTED;
  5013. + else
  5014. + new = SSAM_BASE_HUB_DISCONNECTED;
  5015. +
  5016. + ssam_base_hub_update(sdev, new);
  5017. +
  5018. + /*
  5019. + * Do not return SSAM_NOTIF_HANDLED: The event should be picked up and
  5020. + * consumed by the detachment system driver. We're just a (more or less)
  5021. + * silent observer.
  5022. + */
  5023. + return 0;
  5024. +}
  5025. +
  5026. +static int __maybe_unused ssam_base_hub_resume(struct device *dev)
  5027. +{
  5028. + struct ssam_device *sdev = to_ssam_device(dev);
  5029. + enum ssam_base_hub_state state;
  5030. + int status;
  5031. +
  5032. + status = ssam_base_hub_query_state(sdev, &state);
  5033. + if (status)
  5034. + return status;
  5035. +
  5036. + return ssam_base_hub_update(sdev, state);
  5037. +}
  5038. +static SIMPLE_DEV_PM_OPS(ssam_base_hub_pm_ops, NULL, ssam_base_hub_resume);
  5039. +
  5040. +static int ssam_base_hub_probe(struct ssam_device *sdev)
  5041. +{
  5042. + enum ssam_base_hub_state state;
  5043. + struct ssam_base_hub *hub;
  5044. + int status;
  5045. +
  5046. + hub = devm_kzalloc(&sdev->dev, sizeof(*hub), GFP_KERNEL);
  5047. + if (!hub)
  5048. + return -ENOMEM;
  5049. +
  5050. + mutex_init(&hub->lock);
  5051. +
  5052. + hub->sdev = sdev;
  5053. + hub->state = SSAM_BASE_HUB_UNINITIALIZED;
  5054. +
  5055. + hub->notif.base.priority = 1000; /* This notifier should run first. */
  5056. + hub->notif.base.fn = ssam_base_hub_notif;
  5057. + hub->notif.event.reg = SSAM_EVENT_REGISTRY_SAM;
  5058. + hub->notif.event.id.target_category = SSAM_SSH_TC_BAS,
  5059. + hub->notif.event.id.instance = 0,
  5060. + hub->notif.event.mask = SSAM_EVENT_MASK_NONE;
  5061. + hub->notif.event.flags = SSAM_EVENT_SEQUENCED;
  5062. +
  5063. + status = ssam_notifier_register(sdev->ctrl, &hub->notif);
  5064. + if (status)
  5065. + return status;
  5066. +
  5067. + ssam_device_set_drvdata(sdev, hub);
  5068. +
  5069. + status = ssam_base_hub_query_state(sdev, &state);
  5070. + if (status) {
  5071. + ssam_notifier_unregister(sdev->ctrl, &hub->notif);
  5072. + return status;
  5073. + }
  5074. +
  5075. + status = ssam_base_hub_update(sdev, state);
  5076. + if (status) {
  5077. + ssam_notifier_unregister(sdev->ctrl, &hub->notif);
  5078. + return status;
  5079. + }
  5080. +
  5081. + status = sysfs_create_group(&sdev->dev.kobj, &ssam_base_hub_group);
  5082. + if (status) {
  5083. + ssam_notifier_unregister(sdev->ctrl, &hub->notif);
  5084. + ssam_hub_remove_devices(&sdev->dev);
  5085. + }
  5086. +
  5087. + return status;
  5088. +}
  5089. +
  5090. +static void ssam_base_hub_remove(struct ssam_device *sdev)
  5091. +{
  5092. + struct ssam_base_hub *hub = ssam_device_get_drvdata(sdev);
  5093. +
  5094. + sysfs_remove_group(&sdev->dev.kobj, &ssam_base_hub_group);
  5095. +
  5096. + ssam_notifier_unregister(sdev->ctrl, &hub->notif);
  5097. + ssam_hub_remove_devices(&sdev->dev);
  5098. +
  5099. + mutex_destroy(&hub->lock);
  5100. +}
  5101. +
  5102. +static const struct ssam_device_id ssam_base_hub_match[] = {
  5103. + { SSAM_VDEV(HUB, 0x02, 0x00, 0x00) },
  5104. + { },
  5105. +};
  5106. +
  5107. +static struct ssam_device_driver ssam_base_hub_driver = {
  5108. + .probe = ssam_base_hub_probe,
  5109. + .remove = ssam_base_hub_remove,
  5110. + .match_table = ssam_base_hub_match,
  5111. + .driver = {
  5112. + .name = "surface_aggregator_base_hub",
  5113. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  5114. + .pm = &ssam_base_hub_pm_ops,
  5115. + },
  5116. +};
  5117. +
  5118. +
  5119. +/* -- SSAM platform/meta-hub driver. ---------------------------------------- */
  5120. +
  5121. +static const struct acpi_device_id ssam_platform_hub_match[] = {
  5122. + /* Surface Pro 4, 5, and 6 */
  5123. + { "MSHW0081", (unsigned long)ssam_node_group_sp5 },
  5124. +
  5125. + /* Surface Pro 6 (OMBR >= 0x10) */
  5126. + { "MSHW0111", (unsigned long)ssam_node_group_sp6 },
  5127. +
  5128. + /* Surface Pro 7 */
  5129. + { "MSHW0116", (unsigned long)ssam_node_group_sp7 },
  5130. +
  5131. + /* Surface Book 2 */
  5132. + { "MSHW0107", (unsigned long)ssam_node_group_sb2 },
  5133. +
  5134. + /* Surface Book 3 */
  5135. + { "MSHW0117", (unsigned long)ssam_node_group_sb3 },
  5136. +
  5137. + /* Surface Laptop 1 */
  5138. + { "MSHW0086", (unsigned long)ssam_node_group_sl1 },
  5139. +
  5140. + /* Surface Laptop 2 */
  5141. + { "MSHW0112", (unsigned long)ssam_node_group_sl2 },
  5142. +
  5143. + /* Surface Laptop 3 (13", Intel) */
  5144. + { "MSHW0114", (unsigned long)ssam_node_group_sl3 },
  5145. +
  5146. + /* Surface Laptop 3 (15", AMD) */
  5147. + { "MSHW0110", (unsigned long)ssam_node_group_sl3 },
  5148. +
  5149. + /* Surface Laptop Go 1 */
  5150. + { "MSHW0118", (unsigned long)ssam_node_group_slg1 },
  5151. +
  5152. + { },
  5153. +};
  5154. +MODULE_DEVICE_TABLE(acpi, ssam_platform_hub_match);
  5155. +
  5156. +static int ssam_platform_hub_probe(struct platform_device *pdev)
  5157. +{
  5158. + const struct software_node **nodes;
  5159. + struct ssam_controller *ctrl;
  5160. + struct fwnode_handle *root;
  5161. + int status;
  5162. +
  5163. + nodes = (const struct software_node **)acpi_device_get_match_data(&pdev->dev);
  5164. + if (!nodes)
  5165. + return -ENODEV;
  5166. +
  5167. + /*
  5168. + * As we're adding the SSAM client devices as children under this device
  5169. + * and not the SSAM controller, we need to add a device link to the
  5170. + * controller to ensure that we remove all of our devices before the
  5171. + * controller is removed. This also guarantees proper ordering for
  5172. + * suspend/resume of the devices on this hub.
  5173. + */
  5174. + ctrl = ssam_client_bind(&pdev->dev);
  5175. + if (IS_ERR(ctrl))
  5176. + return PTR_ERR(ctrl) == -ENODEV ? -EPROBE_DEFER : PTR_ERR(ctrl);
  5177. +
  5178. + status = software_node_register_node_group(nodes);
  5179. + if (status)
  5180. + return status;
  5181. +
  5182. + root = software_node_fwnode(&ssam_node_root);
  5183. + if (!root)
  5184. + return -ENOENT;
  5185. +
  5186. + set_secondary_fwnode(&pdev->dev, root);
  5187. +
  5188. + status = ssam_hub_add_devices(&pdev->dev, ctrl, root);
  5189. + if (status) {
  5190. + software_node_unregister_node_group(nodes);
  5191. + return status;
  5192. + }
  5193. +
  5194. + platform_set_drvdata(pdev, nodes);
  5195. + return 0;
  5196. +}
  5197. +
  5198. +static int ssam_platform_hub_remove(struct platform_device *pdev)
  5199. +{
  5200. + const struct software_node **nodes = platform_get_drvdata(pdev);
  5201. +
  5202. + ssam_hub_remove_devices(&pdev->dev);
  5203. + set_secondary_fwnode(&pdev->dev, NULL);
  5204. + software_node_unregister_node_group(nodes);
  5205. + return 0;
  5206. +}
  5207. +
  5208. +static struct platform_driver ssam_platform_hub_driver = {
  5209. + .probe = ssam_platform_hub_probe,
  5210. + .remove = ssam_platform_hub_remove,
  5211. + .driver = {
  5212. + .name = "surface_aggregator_platform_hub",
  5213. + .acpi_match_table = ssam_platform_hub_match,
  5214. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  5215. + },
  5216. +};
  5217. +
  5218. +
  5219. +/* -- Module initialization. ------------------------------------------------ */
  5220. +
  5221. +static int __init ssam_device_hub_init(void)
  5222. +{
  5223. + int status;
  5224. +
  5225. + status = platform_driver_register(&ssam_platform_hub_driver);
  5226. + if (status)
  5227. + goto err_platform;
  5228. +
  5229. + status = ssam_device_driver_register(&ssam_hub_driver);
  5230. + if (status)
  5231. + goto err_main;
  5232. +
  5233. + status = ssam_device_driver_register(&ssam_base_hub_driver);
  5234. + if (status)
  5235. + goto err_base;
  5236. +
  5237. + return 0;
  5238. +
  5239. +err_base:
  5240. + ssam_device_driver_unregister(&ssam_hub_driver);
  5241. +err_main:
  5242. + platform_driver_unregister(&ssam_platform_hub_driver);
  5243. +err_platform:
  5244. + return status;
  5245. +}
  5246. +module_init(ssam_device_hub_init);
  5247. +
  5248. +static void __exit ssam_device_hub_exit(void)
  5249. +{
  5250. + ssam_device_driver_unregister(&ssam_base_hub_driver);
  5251. + ssam_device_driver_unregister(&ssam_hub_driver);
  5252. + platform_driver_unregister(&ssam_platform_hub_driver);
  5253. +}
  5254. +module_exit(ssam_device_hub_exit);
  5255. +
  5256. +MODULE_AUTHOR("Maximilian Luz <luzmaximilian@gmail.com>");
  5257. +MODULE_DESCRIPTION("Device-registry for Surface System Aggregator Module");
  5258. +MODULE_LICENSE("GPL");
  5259. diff --git a/drivers/misc/surface_aggregator/clients/surface_battery.c b/drivers/misc/surface_aggregator/clients/surface_battery.c
  5260. new file mode 100644
  5261. index 000000000000..77f7842e05a4
  5262. --- /dev/null
  5263. +++ b/drivers/misc/surface_aggregator/clients/surface_battery.c
  5264. @@ -0,0 +1,1168 @@
  5265. +// SPDX-License-Identifier: GPL-2.0+
  5266. +/*
  5267. + * Surface battery and AC device driver.
  5268. + *
  5269. + * Provides support for battery and AC devices connected via the Surface
  5270. + * System Aggregator Module.
  5271. + *
  5272. + * Copyright (C) 2019-2020 Maximilian Luz <luzmaximilian@gmail.com>
  5273. + */
  5274. +
  5275. +#include <asm/unaligned.h>
  5276. +#include <linux/delay.h>
  5277. +#include <linux/jiffies.h>
  5278. +#include <linux/kernel.h>
  5279. +#include <linux/module.h>
  5280. +#include <linux/power_supply.h>
  5281. +#include <linux/types.h>
  5282. +#include <linux/workqueue.h>
  5283. +
  5284. +#include <linux/surface_aggregator/device.h>
  5285. +
  5286. +#define SPWR_AC_BAT_UPDATE_DELAY msecs_to_jiffies(5000)
  5287. +
  5288. +
  5289. +/* -- Module parameters. ---------------------------------------------------- */
  5290. +
  5291. +static unsigned int cache_time = 1000;
  5292. +module_param(cache_time, uint, 0644);
  5293. +MODULE_PARM_DESC(cache_time, "battery state caching time in milliseconds [default: 1000]");
  5294. +
  5295. +
  5296. +/* -- SAM Interface. -------------------------------------------------------- */
  5297. +
  5298. +enum sam_event_cid_bat {
  5299. + SAM_EVENT_CID_BAT_BIX = 0x15,
  5300. + SAM_EVENT_CID_BAT_BST = 0x16,
  5301. + SAM_EVENT_CID_BAT_ADP = 0x17,
  5302. + SAM_EVENT_CID_BAT_PROT = 0x18,
  5303. + SAM_EVENT_CID_BAT_DPTF = 0x53,
  5304. +};
  5305. +
  5306. +enum sam_battery_sta {
  5307. + SAM_BATTERY_STA_OK = 0x0f,
  5308. + SAM_BATTERY_STA_PRESENT = 0x10,
  5309. +};
  5310. +
  5311. +enum sam_battery_state {
  5312. + SAM_BATTERY_STATE_DISCHARGING = BIT(0),
  5313. + SAM_BATTERY_STATE_CHARGING = BIT(1),
  5314. + SAM_BATTERY_STATE_CRITICAL = BIT(2),
  5315. +};
  5316. +
  5317. +enum sam_battery_power_unit {
  5318. + SAM_BATTERY_POWER_UNIT_mW = 0,
  5319. + SAM_BATTERY_POWER_UNIT_mA = 1,
  5320. +};
  5321. +
  5322. +/* Equivalent to data returned in ACPI _BIX method, revision 0 */
  5323. +struct spwr_bix {
  5324. + u8 revision;
  5325. + __le32 power_unit;
  5326. + __le32 design_cap;
  5327. + __le32 last_full_charge_cap;
  5328. + __le32 technology;
  5329. + __le32 design_voltage;
  5330. + __le32 design_cap_warn;
  5331. + __le32 design_cap_low;
  5332. + __le32 cycle_count;
  5333. + __le32 measurement_accuracy;
  5334. + __le32 max_sampling_time;
  5335. + __le32 min_sampling_time;
  5336. + __le32 max_avg_interval;
  5337. + __le32 min_avg_interval;
  5338. + __le32 bat_cap_granularity_1;
  5339. + __le32 bat_cap_granularity_2;
  5340. + __u8 model[21];
  5341. + __u8 serial[11];
  5342. + __u8 type[5];
  5343. + __u8 oem_info[21];
  5344. +} __packed;
  5345. +
  5346. +static_assert(sizeof(struct spwr_bix) == 119);
  5347. +
  5348. +#define SPWR_BIX_REVISION 0
  5349. +
  5350. +/* Equivalent to data returned in ACPI _BST method */
  5351. +struct spwr_bst {
  5352. + __le32 state;
  5353. + __le32 present_rate;
  5354. + __le32 remaining_cap;
  5355. + __le32 present_voltage;
  5356. +} __packed;
  5357. +
  5358. +static_assert(sizeof(struct spwr_bst) == 16);
  5359. +
  5360. +#define SPWR_BATTERY_VALUE_UNKNOWN 0xffffffff
  5361. +
  5362. +/* Get battery status (_STA) */
  5363. +static SSAM_DEFINE_SYNC_REQUEST_CL_R(ssam_bat_get_sta, __le32, {
  5364. + .target_category = SSAM_SSH_TC_BAT,
  5365. + .command_id = 0x01,
  5366. +});
  5367. +
  5368. +/* Get battery static information (_BIX) */
  5369. +static SSAM_DEFINE_SYNC_REQUEST_CL_R(ssam_bat_get_bix, struct spwr_bix, {
  5370. + .target_category = SSAM_SSH_TC_BAT,
  5371. + .command_id = 0x02,
  5372. +});
  5373. +
  5374. +/* Get battery dynamic information (_BST) */
  5375. +static SSAM_DEFINE_SYNC_REQUEST_CL_R(ssam_bat_get_bst, struct spwr_bst, {
  5376. + .target_category = SSAM_SSH_TC_BAT,
  5377. + .command_id = 0x03,
  5378. +});
  5379. +
  5380. +/* Set battery trip point (_BTP) */
  5381. +static SSAM_DEFINE_SYNC_REQUEST_CL_W(ssam_bat_set_btp, __le32, {
  5382. + .target_category = SSAM_SSH_TC_BAT,
  5383. + .command_id = 0x04,
  5384. +});
  5385. +
  5386. +/* Get platform power source for battery (DPTF PSRC). */
  5387. +static SSAM_DEFINE_SYNC_REQUEST_CL_R(ssam_bat_get_psrc, __le32, {
  5388. + .target_category = SSAM_SSH_TC_BAT,
  5389. + .command_id = 0x0d,
  5390. +});
  5391. +
  5392. +/*
  5393. + * The following requests are currently unused. They are nevertheless included
  5394. + * for documentation of the SAM interface.
  5395. + */
  5396. +
  5397. +/* Get maximum platform power for battery (DPTF PMAX) */
  5398. +__always_unused
  5399. +static SSAM_DEFINE_SYNC_REQUEST_CL_R(ssam_bat_get_pmax, __le32, {
  5400. + .target_category = SSAM_SSH_TC_BAT,
  5401. + .command_id = 0x0b,
  5402. +});
  5403. +
  5404. +/* Get adapter rating (DPTF ARTG) */
  5405. +__always_unused
  5406. +static SSAM_DEFINE_SYNC_REQUEST_CL_R(ssam_bat_get_artg, __le32, {
  5407. + .target_category = SSAM_SSH_TC_BAT,
  5408. + .command_id = 0x0f,
  5409. +});
  5410. +
  5411. +/* Unknown (DPTF PSOC) */
  5412. +__always_unused
  5413. +static SSAM_DEFINE_SYNC_REQUEST_CL_R(ssam_bat_get_psoc, __le32, {
  5414. + .target_category = SSAM_SSH_TC_BAT,
  5415. + .command_id = 0x0c,
  5416. +});
  5417. +
  5418. +/* Unknown (DPTF CHGI/ INT3403 SPPC) */
  5419. +__always_unused
  5420. +static SSAM_DEFINE_SYNC_REQUEST_CL_W(ssam_bat_set_chgi, __le32, {
  5421. + .target_category = SSAM_SSH_TC_BAT,
  5422. + .command_id = 0x0e,
  5423. +});
  5424. +
  5425. +
  5426. +/* -- Common power-subsystem interface. ------------------------------------- */
  5427. +
  5428. +struct spwr_psy_properties {
  5429. + const char *name;
  5430. + struct ssam_event_registry registry;
  5431. +};
  5432. +
  5433. +struct spwr_battery_device {
  5434. + struct ssam_device *sdev;
  5435. +
  5436. + char name[32];
  5437. + struct power_supply *psy;
  5438. + struct power_supply_desc psy_desc;
  5439. +
  5440. + struct delayed_work update_work;
  5441. +
  5442. + struct ssam_event_notifier notif;
  5443. +
  5444. + struct mutex lock;
  5445. + unsigned long timestamp;
  5446. +
  5447. + __le32 sta;
  5448. + struct spwr_bix bix;
  5449. + struct spwr_bst bst;
  5450. + u32 alarm;
  5451. +};
  5452. +
  5453. +struct spwr_ac_device {
  5454. + struct ssam_device *sdev;
  5455. +
  5456. + char name[32];
  5457. + struct power_supply *psy;
  5458. + struct power_supply_desc psy_desc;
  5459. +
  5460. + struct ssam_event_notifier notif;
  5461. +
  5462. + struct mutex lock;
  5463. +
  5464. + __le32 state;
  5465. +};
  5466. +
  5467. +static enum power_supply_property spwr_ac_props[] = {
  5468. + POWER_SUPPLY_PROP_ONLINE,
  5469. +};
  5470. +
  5471. +static enum power_supply_property spwr_battery_props_chg[] = {
  5472. + POWER_SUPPLY_PROP_STATUS,
  5473. + POWER_SUPPLY_PROP_PRESENT,
  5474. + POWER_SUPPLY_PROP_TECHNOLOGY,
  5475. + POWER_SUPPLY_PROP_CYCLE_COUNT,
  5476. + POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN,
  5477. + POWER_SUPPLY_PROP_VOLTAGE_NOW,
  5478. + POWER_SUPPLY_PROP_CURRENT_NOW,
  5479. + POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN,
  5480. + POWER_SUPPLY_PROP_CHARGE_FULL,
  5481. + POWER_SUPPLY_PROP_CHARGE_NOW,
  5482. + POWER_SUPPLY_PROP_CAPACITY,
  5483. + POWER_SUPPLY_PROP_CAPACITY_LEVEL,
  5484. + POWER_SUPPLY_PROP_MODEL_NAME,
  5485. + POWER_SUPPLY_PROP_MANUFACTURER,
  5486. + POWER_SUPPLY_PROP_SERIAL_NUMBER,
  5487. +};
  5488. +
  5489. +static enum power_supply_property spwr_battery_props_eng[] = {
  5490. + POWER_SUPPLY_PROP_STATUS,
  5491. + POWER_SUPPLY_PROP_PRESENT,
  5492. + POWER_SUPPLY_PROP_TECHNOLOGY,
  5493. + POWER_SUPPLY_PROP_CYCLE_COUNT,
  5494. + POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN,
  5495. + POWER_SUPPLY_PROP_VOLTAGE_NOW,
  5496. + POWER_SUPPLY_PROP_POWER_NOW,
  5497. + POWER_SUPPLY_PROP_ENERGY_FULL_DESIGN,
  5498. + POWER_SUPPLY_PROP_ENERGY_FULL,
  5499. + POWER_SUPPLY_PROP_ENERGY_NOW,
  5500. + POWER_SUPPLY_PROP_CAPACITY,
  5501. + POWER_SUPPLY_PROP_CAPACITY_LEVEL,
  5502. + POWER_SUPPLY_PROP_MODEL_NAME,
  5503. + POWER_SUPPLY_PROP_MANUFACTURER,
  5504. + POWER_SUPPLY_PROP_SERIAL_NUMBER,
  5505. +};
  5506. +
  5507. +static bool spwr_battery_present(struct spwr_battery_device *bat)
  5508. +{
  5509. + return le32_to_cpu(bat->sta) & SAM_BATTERY_STA_PRESENT;
  5510. +}
  5511. +
  5512. +static int spwr_battery_load_sta(struct spwr_battery_device *bat)
  5513. +{
  5514. + return ssam_retry(ssam_bat_get_sta, bat->sdev, &bat->sta);
  5515. +}
  5516. +
  5517. +static int spwr_battery_load_bix(struct spwr_battery_device *bat)
  5518. +{
  5519. + int status;
  5520. +
  5521. + if (!spwr_battery_present(bat))
  5522. + return 0;
  5523. +
  5524. + status = ssam_retry(ssam_bat_get_bix, bat->sdev, &bat->bix);
  5525. +
  5526. + /* Enforce NULL terminated strings in case anything goes wrong... */
  5527. + bat->bix.model[ARRAY_SIZE(bat->bix.model) - 1] = 0;
  5528. + bat->bix.serial[ARRAY_SIZE(bat->bix.serial) - 1] = 0;
  5529. + bat->bix.type[ARRAY_SIZE(bat->bix.type) - 1] = 0;
  5530. + bat->bix.oem_info[ARRAY_SIZE(bat->bix.oem_info) - 1] = 0;
  5531. +
  5532. + return status;
  5533. +}
  5534. +
  5535. +static int spwr_battery_load_bst(struct spwr_battery_device *bat)
  5536. +{
  5537. + if (!spwr_battery_present(bat))
  5538. + return 0;
  5539. +
  5540. + return ssam_retry(ssam_bat_get_bst, bat->sdev, &bat->bst);
  5541. +}
  5542. +
  5543. +static int spwr_battery_set_alarm_unlocked(struct spwr_battery_device *bat,
  5544. + u32 value)
  5545. +{
  5546. + __le32 value_le = cpu_to_le32(value);
  5547. +
  5548. + bat->alarm = value;
  5549. + return ssam_retry(ssam_bat_set_btp, bat->sdev, &value_le);
  5550. +}
  5551. +
  5552. +static int spwr_battery_set_alarm(struct spwr_battery_device *bat, u32 value)
  5553. +{
  5554. + int status;
  5555. +
  5556. + mutex_lock(&bat->lock);
  5557. + status = spwr_battery_set_alarm_unlocked(bat, value);
  5558. + mutex_unlock(&bat->lock);
  5559. +
  5560. + return status;
  5561. +}
  5562. +
  5563. +static int spwr_battery_update_bst_unlocked(struct spwr_battery_device *bat,
  5564. + bool cached)
  5565. +{
  5566. + unsigned long cache_deadline;
  5567. + int status;
  5568. +
  5569. + cache_deadline = bat->timestamp + msecs_to_jiffies(cache_time);
  5570. + if (cached && bat->timestamp && time_is_after_jiffies(cache_deadline))
  5571. + return 0;
  5572. +
  5573. + status = spwr_battery_load_sta(bat);
  5574. + if (status)
  5575. + return status;
  5576. +
  5577. + status = spwr_battery_load_bst(bat);
  5578. + if (status)
  5579. + return status;
  5580. +
  5581. + bat->timestamp = jiffies;
  5582. + return 0;
  5583. +}
  5584. +
  5585. +static int spwr_battery_update_bst(struct spwr_battery_device *bat, bool cached)
  5586. +{
  5587. + int status;
  5588. +
  5589. + mutex_lock(&bat->lock);
  5590. + status = spwr_battery_update_bst_unlocked(bat, cached);
  5591. + mutex_unlock(&bat->lock);
  5592. +
  5593. + return status;
  5594. +}
  5595. +
  5596. +static int spwr_battery_update_bix_unlocked(struct spwr_battery_device *bat)
  5597. +{
  5598. + int status;
  5599. +
  5600. + status = spwr_battery_load_sta(bat);
  5601. + if (status)
  5602. + return status;
  5603. +
  5604. + status = spwr_battery_load_bix(bat);
  5605. + if (status)
  5606. + return status;
  5607. +
  5608. + status = spwr_battery_load_bst(bat);
  5609. + if (status)
  5610. + return status;
  5611. +
  5612. + if (bat->bix.revision != SPWR_BIX_REVISION) {
  5613. + dev_warn(&bat->sdev->dev, "unsupported battery revision: %u\n",
  5614. + bat->bix.revision);
  5615. + }
  5616. +
  5617. + bat->timestamp = jiffies;
  5618. + return 0;
  5619. +}
  5620. +
  5621. +static int spwr_ac_update_unlocked(struct spwr_ac_device *ac)
  5622. +{
  5623. + int status;
  5624. + u32 old = ac->state;
  5625. +
  5626. + status = ssam_retry(ssam_bat_get_psrc, ac->sdev, &ac->state);
  5627. + if (status < 0)
  5628. + return status;
  5629. +
  5630. + return old != ac->state;
  5631. +}
  5632. +
  5633. +static int spwr_ac_update(struct spwr_ac_device *ac)
  5634. +{
  5635. + int status;
  5636. +
  5637. + mutex_lock(&ac->lock);
  5638. + status = spwr_ac_update_unlocked(ac);
  5639. + mutex_unlock(&ac->lock);
  5640. +
  5641. + return status;
  5642. +}
  5643. +
  5644. +static u32 sprw_battery_get_full_cap_safe(struct spwr_battery_device *bat)
  5645. +{
  5646. + u32 full_cap = get_unaligned_le32(&bat->bix.last_full_charge_cap);
  5647. +
  5648. + if (full_cap == 0 || full_cap == SPWR_BATTERY_VALUE_UNKNOWN)
  5649. + full_cap = get_unaligned_le32(&bat->bix.design_cap);
  5650. +
  5651. + return full_cap;
  5652. +}
  5653. +
  5654. +static bool spwr_battery_is_full(struct spwr_battery_device *bat)
  5655. +{
  5656. + u32 state = get_unaligned_le32(&bat->bst.state);
  5657. + u32 full_cap = sprw_battery_get_full_cap_safe(bat);
  5658. + u32 remaining_cap = get_unaligned_le32(&bat->bst.remaining_cap);
  5659. +
  5660. + return full_cap != SPWR_BATTERY_VALUE_UNKNOWN && full_cap != 0 &&
  5661. + remaining_cap != SPWR_BATTERY_VALUE_UNKNOWN &&
  5662. + remaining_cap >= full_cap &&
  5663. + state == 0;
  5664. +}
  5665. +
  5666. +static int spwr_battery_recheck_full(struct spwr_battery_device *bat)
  5667. +{
  5668. + bool present;
  5669. + u32 unit;
  5670. + int status;
  5671. +
  5672. + mutex_lock(&bat->lock);
  5673. + unit = get_unaligned_le32(&bat->bix.power_unit);
  5674. + present = spwr_battery_present(bat);
  5675. +
  5676. + status = spwr_battery_update_bix_unlocked(bat);
  5677. + if (status)
  5678. + goto out;
  5679. +
  5680. + /* If battery has been attached, (re-)initialize alarm. */
  5681. + if (!present && spwr_battery_present(bat)) {
  5682. + u32 cap_warn = get_unaligned_le32(&bat->bix.design_cap_warn);
  5683. +
  5684. + status = spwr_battery_set_alarm_unlocked(bat, cap_warn);
  5685. + if (status)
  5686. + goto out;
  5687. + }
  5688. +
  5689. + /*
  5690. + * Warn if the unit has changed. This is something we genuinely don't
  5691. + * expect to happen, so make this a big warning. If it does, we'll
  5692. + * need to add support for it.
  5693. + */
  5694. + WARN_ON(unit != get_unaligned_le32(&bat->bix.power_unit));
  5695. +
  5696. +out:
  5697. + mutex_unlock(&bat->lock);
  5698. +
  5699. + if (!status)
  5700. + power_supply_changed(bat->psy);
  5701. +
  5702. + return status;
  5703. +}
  5704. +
  5705. +static int spwr_battery_recheck_status(struct spwr_battery_device *bat)
  5706. +{
  5707. + int status;
  5708. +
  5709. + status = spwr_battery_update_bst(bat, false);
  5710. + if (!status)
  5711. + power_supply_changed(bat->psy);
  5712. +
  5713. + return status;
  5714. +}
  5715. +
  5716. +static int spwr_battery_recheck_adapter(struct spwr_battery_device *bat)
  5717. +{
  5718. + /*
  5719. + * Handle battery update quirk: When the battery is fully charged (or
  5720. + * charged up to the limit imposed by the UEFI battery limit) and the
  5721. + * adapter is plugged in or removed, the EC does not send a separate
  5722. + * event for the state (charging/discharging) change. Furthermore it
  5723. + * may take some time until the state is updated on the battery.
  5724. + * Schedule an update to solve this.
  5725. + */
  5726. +
  5727. + schedule_delayed_work(&bat->update_work, SPWR_AC_BAT_UPDATE_DELAY);
  5728. + return 0;
  5729. +}
  5730. +
  5731. +static int spwr_ac_recheck(struct spwr_ac_device *ac)
  5732. +{
  5733. + int status;
  5734. +
  5735. + status = spwr_ac_update(ac);
  5736. + if (status > 0)
  5737. + power_supply_changed(ac->psy);
  5738. +
  5739. + return status >= 0 ? 0 : status;
  5740. +}
  5741. +
  5742. +static u32 spwr_notify_bat(struct ssam_event_notifier *nf,
  5743. + const struct ssam_event *event)
  5744. +{
  5745. + struct spwr_battery_device *bat;
  5746. + int status;
  5747. +
  5748. + bat = container_of(nf, struct spwr_battery_device, notif);
  5749. +
  5750. + dev_dbg(&bat->sdev->dev, "power event (cid = %#04x, iid = %#04x, tid = %#04x)\n",
  5751. + event->command_id, event->instance_id, event->target_id);
  5752. +
  5753. + /* Handled here, needs to be handled for all targets/instances. */
  5754. + if (event->command_id == SAM_EVENT_CID_BAT_ADP) {
  5755. + status = spwr_battery_recheck_adapter(bat);
  5756. + return ssam_notifier_from_errno(status) | SSAM_NOTIF_HANDLED;
  5757. + }
  5758. +
  5759. + if (bat->sdev->uid.target != event->target_id)
  5760. + return 0;
  5761. +
  5762. + if (bat->sdev->uid.instance != event->instance_id)
  5763. + return 0;
  5764. +
  5765. + switch (event->command_id) {
  5766. + case SAM_EVENT_CID_BAT_BIX:
  5767. + status = spwr_battery_recheck_full(bat);
  5768. + break;
  5769. +
  5770. + case SAM_EVENT_CID_BAT_BST:
  5771. + status = spwr_battery_recheck_status(bat);
  5772. + break;
  5773. +
  5774. + case SAM_EVENT_CID_BAT_PROT:
  5775. + /*
  5776. + * TODO: Implement support for battery protection status change
  5777. + * event.
  5778. + */
  5779. + status = 0;
  5780. + break;
  5781. +
  5782. + case SAM_EVENT_CID_BAT_DPTF:
  5783. + /*
  5784. + * TODO: Implement support for DPTF event.
  5785. + */
  5786. + status = 0;
  5787. + break;
  5788. +
  5789. + default:
  5790. + return 0;
  5791. + }
  5792. +
  5793. + return ssam_notifier_from_errno(status) | SSAM_NOTIF_HANDLED;
  5794. +}
  5795. +
  5796. +static u32 spwr_notify_ac(struct ssam_event_notifier *nf,
  5797. + const struct ssam_event *event)
  5798. +{
  5799. + struct spwr_ac_device *ac;
  5800. + int status;
  5801. +
  5802. + ac = container_of(nf, struct spwr_ac_device, notif);
  5803. +
  5804. + dev_dbg(&ac->sdev->dev, "power event (cid = %#04x, iid = %#04x, tid = %#04x)\n",
  5805. + event->command_id, event->instance_id, event->target_id);
  5806. +
  5807. + /*
  5808. + * Allow events of all targets/instances here. Global adapter status
  5809. + * seems to be handled via target=1 and instance=1, but events are
  5810. + * reported on all targets/instances in use.
  5811. + *
  5812. + * While it should be enough to just listen on 1/1, listen everywhere to
  5813. + * make sure we don't miss anything.
  5814. + */
  5815. +
  5816. + switch (event->command_id) {
  5817. + case SAM_EVENT_CID_BAT_ADP:
  5818. + status = spwr_ac_recheck(ac);
  5819. + return ssam_notifier_from_errno(status) | SSAM_NOTIF_HANDLED;
  5820. +
  5821. + default:
  5822. + return 0;
  5823. + }
  5824. +}
  5825. +
  5826. +static void spwr_battery_update_bst_workfn(struct work_struct *work)
  5827. +{
  5828. + struct delayed_work *dwork = to_delayed_work(work);
  5829. + struct spwr_battery_device *bat;
  5830. + int status;
  5831. +
  5832. + bat = container_of(dwork, struct spwr_battery_device, update_work);
  5833. +
  5834. + status = spwr_battery_update_bst(bat, false);
  5835. + if (!status)
  5836. + power_supply_changed(bat->psy);
  5837. +
  5838. + if (status) {
  5839. + dev_err(&bat->sdev->dev, "failed to update battery state: %d\n",
  5840. + status);
  5841. + }
  5842. +}
  5843. +
  5844. +static int spwr_battery_prop_status(struct spwr_battery_device *bat)
  5845. +{
  5846. + u32 state = get_unaligned_le32(&bat->bst.state);
  5847. + u32 present_rate = get_unaligned_le32(&bat->bst.present_rate);
  5848. +
  5849. + if (state & SAM_BATTERY_STATE_DISCHARGING)
  5850. + return POWER_SUPPLY_STATUS_DISCHARGING;
  5851. +
  5852. + if (state & SAM_BATTERY_STATE_CHARGING)
  5853. + return POWER_SUPPLY_STATUS_CHARGING;
  5854. +
  5855. + if (spwr_battery_is_full(bat))
  5856. + return POWER_SUPPLY_STATUS_FULL;
  5857. +
  5858. + if (present_rate == 0)
  5859. + return POWER_SUPPLY_STATUS_NOT_CHARGING;
  5860. +
  5861. + return POWER_SUPPLY_STATUS_UNKNOWN;
  5862. +}
  5863. +
  5864. +static int spwr_battery_prop_technology(struct spwr_battery_device *bat)
  5865. +{
  5866. + if (!strcasecmp("NiCd", bat->bix.type))
  5867. + return POWER_SUPPLY_TECHNOLOGY_NiCd;
  5868. +
  5869. + if (!strcasecmp("NiMH", bat->bix.type))
  5870. + return POWER_SUPPLY_TECHNOLOGY_NiMH;
  5871. +
  5872. + if (!strcasecmp("LION", bat->bix.type))
  5873. + return POWER_SUPPLY_TECHNOLOGY_LION;
  5874. +
  5875. + if (!strncasecmp("LI-ION", bat->bix.type, 6))
  5876. + return POWER_SUPPLY_TECHNOLOGY_LION;
  5877. +
  5878. + if (!strcasecmp("LiP", bat->bix.type))
  5879. + return POWER_SUPPLY_TECHNOLOGY_LIPO;
  5880. +
  5881. + return POWER_SUPPLY_TECHNOLOGY_UNKNOWN;
  5882. +}
  5883. +
  5884. +static int spwr_battery_prop_capacity(struct spwr_battery_device *bat)
  5885. +{
  5886. + u32 full_cap = sprw_battery_get_full_cap_safe(bat);
  5887. + u32 remaining_cap = get_unaligned_le32(&bat->bst.remaining_cap);
  5888. +
  5889. + if (full_cap == 0 || full_cap == SPWR_BATTERY_VALUE_UNKNOWN)
  5890. + return -ENODEV;
  5891. +
  5892. + if (remaining_cap == SPWR_BATTERY_VALUE_UNKNOWN)
  5893. + return -ENODEV;
  5894. +
  5895. + return remaining_cap * 100 / full_cap;
  5896. +}
  5897. +
  5898. +static int spwr_battery_prop_capacity_level(struct spwr_battery_device *bat)
  5899. +{
  5900. + u32 state = get_unaligned_le32(&bat->bst.state);
  5901. + u32 remaining_cap = get_unaligned_le32(&bat->bst.remaining_cap);
  5902. +
  5903. + if (state & SAM_BATTERY_STATE_CRITICAL)
  5904. + return POWER_SUPPLY_CAPACITY_LEVEL_CRITICAL;
  5905. +
  5906. + if (spwr_battery_is_full(bat))
  5907. + return POWER_SUPPLY_CAPACITY_LEVEL_FULL;
  5908. +
  5909. + if (remaining_cap <= bat->alarm)
  5910. + return POWER_SUPPLY_CAPACITY_LEVEL_LOW;
  5911. +
  5912. + return POWER_SUPPLY_CAPACITY_LEVEL_NORMAL;
  5913. +}
  5914. +
  5915. +static int spwr_ac_get_property(struct power_supply *psy,
  5916. + enum power_supply_property psp,
  5917. + union power_supply_propval *val)
  5918. +{
  5919. + struct spwr_ac_device *ac = power_supply_get_drvdata(psy);
  5920. + int status;
  5921. +
  5922. + mutex_lock(&ac->lock);
  5923. +
  5924. + status = spwr_ac_update_unlocked(ac);
  5925. + if (status)
  5926. + goto out;
  5927. +
  5928. + switch (psp) {
  5929. + case POWER_SUPPLY_PROP_ONLINE:
  5930. + val->intval = !!le32_to_cpu(ac->state);
  5931. + break;
  5932. +
  5933. + default:
  5934. + status = -EINVAL;
  5935. + goto out;
  5936. + }
  5937. +
  5938. +out:
  5939. + mutex_unlock(&ac->lock);
  5940. + return status;
  5941. +}
  5942. +
  5943. +static int spwr_battery_get_property(struct power_supply *psy,
  5944. + enum power_supply_property psp,
  5945. + union power_supply_propval *val)
  5946. +{
  5947. + struct spwr_battery_device *bat = power_supply_get_drvdata(psy);
  5948. + u32 value;
  5949. + int status;
  5950. +
  5951. + mutex_lock(&bat->lock);
  5952. +
  5953. + status = spwr_battery_update_bst_unlocked(bat, true);
  5954. + if (status)
  5955. + goto out;
  5956. +
  5957. + /* Abort if battery is not present. */
  5958. + if (!spwr_battery_present(bat) && psp != POWER_SUPPLY_PROP_PRESENT) {
  5959. + status = -ENODEV;
  5960. + goto out;
  5961. + }
  5962. +
  5963. + switch (psp) {
  5964. + case POWER_SUPPLY_PROP_STATUS:
  5965. + val->intval = spwr_battery_prop_status(bat);
  5966. + break;
  5967. +
  5968. + case POWER_SUPPLY_PROP_PRESENT:
  5969. + val->intval = spwr_battery_present(bat);
  5970. + break;
  5971. +
  5972. + case POWER_SUPPLY_PROP_TECHNOLOGY:
  5973. + val->intval = spwr_battery_prop_technology(bat);
  5974. + break;
  5975. +
  5976. + case POWER_SUPPLY_PROP_CYCLE_COUNT:
  5977. + value = get_unaligned_le32(&bat->bix.cycle_count);
  5978. + if (value != SPWR_BATTERY_VALUE_UNKNOWN)
  5979. + val->intval = value;
  5980. + else
  5981. + status = -ENODEV;
  5982. + break;
  5983. +
  5984. + case POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN:
  5985. + value = get_unaligned_le32(&bat->bix.design_voltage);
  5986. + if (value != SPWR_BATTERY_VALUE_UNKNOWN)
  5987. + val->intval = value * 1000;
  5988. + else
  5989. + status = -ENODEV;
  5990. + break;
  5991. +
  5992. + case POWER_SUPPLY_PROP_VOLTAGE_NOW:
  5993. + value = get_unaligned_le32(&bat->bst.present_voltage);
  5994. + if (value != SPWR_BATTERY_VALUE_UNKNOWN)
  5995. + val->intval = value * 1000;
  5996. + else
  5997. + status = -ENODEV;
  5998. + break;
  5999. +
  6000. + case POWER_SUPPLY_PROP_CURRENT_NOW:
  6001. + case POWER_SUPPLY_PROP_POWER_NOW:
  6002. + value = get_unaligned_le32(&bat->bst.present_rate);
  6003. + if (value != SPWR_BATTERY_VALUE_UNKNOWN)
  6004. + val->intval = value * 1000;
  6005. + else
  6006. + status = -ENODEV;
  6007. + break;
  6008. +
  6009. + case POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN:
  6010. + case POWER_SUPPLY_PROP_ENERGY_FULL_DESIGN:
  6011. + value = get_unaligned_le32(&bat->bix.design_cap);
  6012. + if (value != SPWR_BATTERY_VALUE_UNKNOWN)
  6013. + val->intval = value * 1000;
  6014. + else
  6015. + status = -ENODEV;
  6016. + break;
  6017. +
  6018. + case POWER_SUPPLY_PROP_CHARGE_FULL:
  6019. + case POWER_SUPPLY_PROP_ENERGY_FULL:
  6020. + value = get_unaligned_le32(&bat->bix.last_full_charge_cap);
  6021. + if (value != SPWR_BATTERY_VALUE_UNKNOWN)
  6022. + val->intval = value * 1000;
  6023. + else
  6024. + status = -ENODEV;
  6025. + break;
  6026. +
  6027. + case POWER_SUPPLY_PROP_CHARGE_NOW:
  6028. + case POWER_SUPPLY_PROP_ENERGY_NOW:
  6029. + value = get_unaligned_le32(&bat->bst.remaining_cap);
  6030. + if (value != SPWR_BATTERY_VALUE_UNKNOWN)
  6031. + val->intval = value * 1000;
  6032. + else
  6033. + status = -ENODEV;
  6034. + break;
  6035. +
  6036. + case POWER_SUPPLY_PROP_CAPACITY:
  6037. + val->intval = spwr_battery_prop_capacity(bat);
  6038. + break;
  6039. +
  6040. + case POWER_SUPPLY_PROP_CAPACITY_LEVEL:
  6041. + val->intval = spwr_battery_prop_capacity_level(bat);
  6042. + break;
  6043. +
  6044. + case POWER_SUPPLY_PROP_MODEL_NAME:
  6045. + val->strval = bat->bix.model;
  6046. + break;
  6047. +
  6048. + case POWER_SUPPLY_PROP_MANUFACTURER:
  6049. + val->strval = bat->bix.oem_info;
  6050. + break;
  6051. +
  6052. + case POWER_SUPPLY_PROP_SERIAL_NUMBER:
  6053. + val->strval = bat->bix.serial;
  6054. + break;
  6055. +
  6056. + default:
  6057. + status = -EINVAL;
  6058. + break;
  6059. + }
  6060. +
  6061. +out:
  6062. + mutex_unlock(&bat->lock);
  6063. + return status;
  6064. +}
  6065. +
  6066. +static ssize_t spwr_battery_alarm_show(struct device *dev,
  6067. + struct device_attribute *attr,
  6068. + char *buf)
  6069. +{
  6070. + struct power_supply *psy = dev_get_drvdata(dev);
  6071. + struct spwr_battery_device *bat = power_supply_get_drvdata(psy);
  6072. +
  6073. + return sprintf(buf, "%d\n", bat->alarm * 1000);
  6074. +}
  6075. +
  6076. +static ssize_t spwr_battery_alarm_store(struct device *dev,
  6077. + struct device_attribute *attr,
  6078. + const char *buf, size_t count)
  6079. +{
  6080. + struct power_supply *psy = dev_get_drvdata(dev);
  6081. + struct spwr_battery_device *bat = power_supply_get_drvdata(psy);
  6082. + unsigned long value;
  6083. + int status;
  6084. +
  6085. + status = kstrtoul(buf, 0, &value);
  6086. + if (status)
  6087. + return status;
  6088. +
  6089. + if (!spwr_battery_present(bat))
  6090. + return -ENODEV;
  6091. +
  6092. + status = spwr_battery_set_alarm(bat, value / 1000);
  6093. + if (status)
  6094. + return status;
  6095. +
  6096. + return count;
  6097. +}
  6098. +
  6099. +static const struct device_attribute alarm_attr = {
  6100. + .attr = {.name = "alarm", .mode = 0644},
  6101. + .show = spwr_battery_alarm_show,
  6102. + .store = spwr_battery_alarm_store,
  6103. +};
  6104. +
  6105. +static void spwr_ac_init(struct spwr_ac_device *ac, struct ssam_device *sdev,
  6106. + struct ssam_event_registry registry, const char *name)
  6107. +{
  6108. + mutex_init(&ac->lock);
  6109. + strncpy(ac->name, name, ARRAY_SIZE(ac->name) - 1);
  6110. +
  6111. + ac->sdev = sdev;
  6112. +
  6113. + ac->notif.base.priority = 1;
  6114. + ac->notif.base.fn = spwr_notify_ac;
  6115. + ac->notif.event.reg = registry;
  6116. + ac->notif.event.id.target_category = sdev->uid.category;
  6117. + ac->notif.event.id.instance = 0;
  6118. + ac->notif.event.mask = SSAM_EVENT_MASK_NONE;
  6119. + ac->notif.event.flags = SSAM_EVENT_SEQUENCED;
  6120. +
  6121. + ac->psy_desc.name = ac->name;
  6122. + ac->psy_desc.type = POWER_SUPPLY_TYPE_MAINS;
  6123. + ac->psy_desc.properties = spwr_ac_props;
  6124. + ac->psy_desc.num_properties = ARRAY_SIZE(spwr_ac_props);
  6125. + ac->psy_desc.get_property = spwr_ac_get_property;
  6126. +}
  6127. +
  6128. +static void spwr_ac_destroy(struct spwr_ac_device *ac)
  6129. +{
  6130. + mutex_destroy(&ac->lock);
  6131. +}
  6132. +
  6133. +static int spwr_ac_register(struct spwr_ac_device *ac)
  6134. +{
  6135. + struct power_supply_config psy_cfg = {};
  6136. + __le32 sta;
  6137. + int status;
  6138. +
  6139. + /* Make sure the device is there and functioning properly. */
  6140. + status = ssam_retry(ssam_bat_get_sta, ac->sdev, &sta);
  6141. + if (status)
  6142. + return status;
  6143. +
  6144. + if ((le32_to_cpu(sta) & SAM_BATTERY_STA_OK) != SAM_BATTERY_STA_OK)
  6145. + return -ENODEV;
  6146. +
  6147. + psy_cfg.drv_data = ac;
  6148. + ac->psy = power_supply_register(&ac->sdev->dev, &ac->psy_desc, &psy_cfg);
  6149. + if (IS_ERR(ac->psy))
  6150. + return PTR_ERR(ac->psy);
  6151. +
  6152. + status = ssam_notifier_register(ac->sdev->ctrl, &ac->notif);
  6153. + if (status)
  6154. + power_supply_unregister(ac->psy);
  6155. +
  6156. + return status;
  6157. +}
  6158. +
  6159. +static int spwr_ac_unregister(struct spwr_ac_device *ac)
  6160. +{
  6161. + ssam_notifier_unregister(ac->sdev->ctrl, &ac->notif);
  6162. + power_supply_unregister(ac->psy);
  6163. + return 0;
  6164. +}
  6165. +
  6166. +static void spwr_battery_init(struct spwr_battery_device *bat,
  6167. + struct ssam_device *sdev,
  6168. + struct ssam_event_registry registry,
  6169. + const char *name)
  6170. +{
  6171. + mutex_init(&bat->lock);
  6172. + strncpy(bat->name, name, ARRAY_SIZE(bat->name) - 1);
  6173. +
  6174. + bat->sdev = sdev;
  6175. +
  6176. + bat->notif.base.priority = 1;
  6177. + bat->notif.base.fn = spwr_notify_bat;
  6178. + bat->notif.event.reg = registry;
  6179. + bat->notif.event.id.target_category = sdev->uid.category;
  6180. + bat->notif.event.id.instance = 0;
  6181. + bat->notif.event.mask = SSAM_EVENT_MASK_NONE;
  6182. + bat->notif.event.flags = SSAM_EVENT_SEQUENCED;
  6183. +
  6184. + bat->psy_desc.name = bat->name;
  6185. + bat->psy_desc.type = POWER_SUPPLY_TYPE_BATTERY;
  6186. + bat->psy_desc.get_property = spwr_battery_get_property;
  6187. +
  6188. + INIT_DELAYED_WORK(&bat->update_work, spwr_battery_update_bst_workfn);
  6189. +}
  6190. +
  6191. +static void spwr_battery_destroy(struct spwr_battery_device *bat)
  6192. +{
  6193. + mutex_destroy(&bat->lock);
  6194. +}
  6195. +
  6196. +static int spwr_battery_register(struct spwr_battery_device *bat)
  6197. +{
  6198. + struct power_supply_config psy_cfg = {};
  6199. + __le32 sta;
  6200. + int status;
  6201. +
  6202. + /* Make sure the device is there and functioning properly. */
  6203. + status = ssam_retry(ssam_bat_get_sta, bat->sdev, &sta);
  6204. + if (status)
  6205. + return status;
  6206. +
  6207. + if ((le32_to_cpu(sta) & SAM_BATTERY_STA_OK) != SAM_BATTERY_STA_OK)
  6208. + return -ENODEV;
  6209. +
  6210. + status = spwr_battery_update_bix_unlocked(bat);
  6211. + if (status)
  6212. + return status;
  6213. +
  6214. + if (spwr_battery_present(bat)) {
  6215. + u32 cap_warn = get_unaligned_le32(&bat->bix.design_cap_warn);
  6216. +
  6217. + status = spwr_battery_set_alarm_unlocked(bat, cap_warn);
  6218. + if (status)
  6219. + return status;
  6220. + }
  6221. +
  6222. + switch (get_unaligned_le32(&bat->bix.power_unit)) {
  6223. + case SAM_BATTERY_POWER_UNIT_mW:
  6224. + bat->psy_desc.properties = spwr_battery_props_eng;
  6225. + bat->psy_desc.num_properties = ARRAY_SIZE(spwr_battery_props_eng);
  6226. + break;
  6227. +
  6228. + case SAM_BATTERY_POWER_UNIT_mA:
  6229. + bat->psy_desc.properties = spwr_battery_props_chg;
  6230. + bat->psy_desc.num_properties = ARRAY_SIZE(spwr_battery_props_chg);
  6231. + break;
  6232. +
  6233. + default:
  6234. + dev_err(&bat->sdev->dev, "unsupported battery power unit: %u\n",
  6235. + get_unaligned_le32(&bat->bix.power_unit));
  6236. + return -ENOTSUPP;
  6237. + }
  6238. +
  6239. + psy_cfg.drv_data = bat;
  6240. + bat->psy = power_supply_register(&bat->sdev->dev, &bat->psy_desc, &psy_cfg);
  6241. + if (IS_ERR(bat->psy))
  6242. + return PTR_ERR(bat->psy);
  6243. +
  6244. + status = ssam_notifier_register(bat->sdev->ctrl, &bat->notif);
  6245. + if (status)
  6246. + goto err_notif;
  6247. +
  6248. + status = device_create_file(&bat->psy->dev, &alarm_attr);
  6249. + if (status)
  6250. + goto err_file;
  6251. +
  6252. + return 0;
  6253. +
  6254. +err_file:
  6255. + ssam_notifier_unregister(bat->sdev->ctrl, &bat->notif);
  6256. +err_notif:
  6257. + power_supply_unregister(bat->psy);
  6258. + return status;
  6259. +}
  6260. +
  6261. +static void spwr_battery_unregister(struct spwr_battery_device *bat)
  6262. +{
  6263. + ssam_notifier_unregister(bat->sdev->ctrl, &bat->notif);
  6264. + cancel_delayed_work_sync(&bat->update_work);
  6265. + device_remove_file(&bat->psy->dev, &alarm_attr);
  6266. + power_supply_unregister(bat->psy);
  6267. +}
  6268. +
  6269. +
  6270. +/* -- Power management. ----------------------------------------------------- */
  6271. +
  6272. +static int __maybe_unused surface_battery_resume(struct device *dev)
  6273. +{
  6274. + return spwr_battery_recheck_full(dev_get_drvdata(dev));
  6275. +}
  6276. +SIMPLE_DEV_PM_OPS(surface_battery_pm_ops, NULL, surface_battery_resume);
  6277. +
  6278. +static int __maybe_unused surface_ac_resume(struct device *dev)
  6279. +{
  6280. + return spwr_ac_recheck(dev_get_drvdata(dev));
  6281. +}
  6282. +SIMPLE_DEV_PM_OPS(surface_ac_pm_ops, NULL, surface_ac_resume);
  6283. +
  6284. +
  6285. +/* -- Battery driver. ------------------------------------------------------- */
  6286. +
  6287. +static int surface_battery_probe(struct ssam_device *sdev)
  6288. +{
  6289. + const struct spwr_psy_properties *p;
  6290. + struct spwr_battery_device *bat;
  6291. + int status;
  6292. +
  6293. + p = ssam_device_get_match_data(sdev);
  6294. + if (!p)
  6295. + return -ENODEV;
  6296. +
  6297. + bat = devm_kzalloc(&sdev->dev, sizeof(*bat), GFP_KERNEL);
  6298. + if (!bat)
  6299. + return -ENOMEM;
  6300. +
  6301. + spwr_battery_init(bat, sdev, p->registry, p->name);
  6302. + ssam_device_set_drvdata(sdev, bat);
  6303. +
  6304. + status = spwr_battery_register(bat);
  6305. + if (status)
  6306. + spwr_battery_destroy(bat);
  6307. +
  6308. + return status;
  6309. +}
  6310. +
  6311. +static void surface_battery_remove(struct ssam_device *sdev)
  6312. +{
  6313. + struct spwr_battery_device *bat = ssam_device_get_drvdata(sdev);
  6314. +
  6315. + spwr_battery_unregister(bat);
  6316. + spwr_battery_destroy(bat);
  6317. +}
  6318. +
  6319. +static const struct spwr_psy_properties spwr_psy_props_bat1 = {
  6320. + .name = "BAT1",
  6321. + .registry = SSAM_EVENT_REGISTRY_SAM,
  6322. +};
  6323. +
  6324. +static const struct spwr_psy_properties spwr_psy_props_bat2_sb3 = {
  6325. + .name = "BAT2",
  6326. + .registry = SSAM_EVENT_REGISTRY_KIP,
  6327. +};
  6328. +
  6329. +static const struct ssam_device_id surface_battery_match[] = {
  6330. + { SSAM_SDEV(BAT, 0x01, 0x01, 0x00), (unsigned long)&spwr_psy_props_bat1 },
  6331. + { SSAM_SDEV(BAT, 0x02, 0x01, 0x00), (unsigned long)&spwr_psy_props_bat2_sb3 },
  6332. + { },
  6333. +};
  6334. +MODULE_DEVICE_TABLE(ssam, surface_battery_match);
  6335. +
  6336. +static struct ssam_device_driver surface_battery_driver = {
  6337. + .probe = surface_battery_probe,
  6338. + .remove = surface_battery_remove,
  6339. + .match_table = surface_battery_match,
  6340. + .driver = {
  6341. + .name = "surface_battery",
  6342. + .pm = &surface_battery_pm_ops,
  6343. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  6344. + },
  6345. +};
  6346. +
  6347. +
  6348. +/* -- AC driver. ------------------------------------------------------------ */
  6349. +
  6350. +static int surface_ac_probe(struct ssam_device *sdev)
  6351. +{
  6352. + const struct spwr_psy_properties *p;
  6353. + struct spwr_ac_device *ac;
  6354. + int status;
  6355. +
  6356. + p = ssam_device_get_match_data(sdev);
  6357. + if (!p)
  6358. + return -ENODEV;
  6359. +
  6360. + ac = devm_kzalloc(&sdev->dev, sizeof(*ac), GFP_KERNEL);
  6361. + if (!ac)
  6362. + return -ENOMEM;
  6363. +
  6364. + spwr_ac_init(ac, sdev, p->registry, p->name);
  6365. + ssam_device_set_drvdata(sdev, ac);
  6366. +
  6367. + status = spwr_ac_register(ac);
  6368. + if (status)
  6369. + spwr_ac_destroy(ac);
  6370. +
  6371. + return status;
  6372. +}
  6373. +
  6374. +static void surface_ac_remove(struct ssam_device *sdev)
  6375. +{
  6376. + struct spwr_ac_device *ac = ssam_device_get_drvdata(sdev);
  6377. +
  6378. + spwr_ac_unregister(ac);
  6379. + spwr_ac_destroy(ac);
  6380. +}
  6381. +
  6382. +static const struct spwr_psy_properties spwr_psy_props_adp1 = {
  6383. + .name = "ADP1",
  6384. + .registry = SSAM_EVENT_REGISTRY_SAM,
  6385. +};
  6386. +
  6387. +static const struct ssam_device_id surface_ac_match[] = {
  6388. + { SSAM_SDEV(BAT, 0x01, 0x01, 0x01), (unsigned long)&spwr_psy_props_adp1 },
  6389. + { },
  6390. +};
  6391. +MODULE_DEVICE_TABLE(ssam, surface_ac_match);
  6392. +
  6393. +static struct ssam_device_driver surface_ac_driver = {
  6394. + .probe = surface_ac_probe,
  6395. + .remove = surface_ac_remove,
  6396. + .match_table = surface_ac_match,
  6397. + .driver = {
  6398. + .name = "surface_ac",
  6399. + .pm = &surface_ac_pm_ops,
  6400. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  6401. + },
  6402. +};
  6403. +
  6404. +
  6405. +/* -- Module setup. --------------------------------------------------------- */
  6406. +
  6407. +static int __init surface_battery_init(void)
  6408. +{
  6409. + int status;
  6410. +
  6411. + status = ssam_device_driver_register(&surface_battery_driver);
  6412. + if (status)
  6413. + return status;
  6414. +
  6415. + status = ssam_device_driver_register(&surface_ac_driver);
  6416. + if (status)
  6417. + ssam_device_driver_unregister(&surface_battery_driver);
  6418. +
  6419. + return status;
  6420. +}
  6421. +module_init(surface_battery_init);
  6422. +
  6423. +static void __exit surface_battery_exit(void)
  6424. +{
  6425. + ssam_device_driver_unregister(&surface_battery_driver);
  6426. + ssam_device_driver_unregister(&surface_ac_driver);
  6427. +}
  6428. +module_exit(surface_battery_exit);
  6429. +
  6430. +MODULE_AUTHOR("Maximilian Luz <luzmaximilian@gmail.com>");
  6431. +MODULE_DESCRIPTION("Battery/AC driver for Surface System Aggregator Module");
  6432. +MODULE_LICENSE("GPL");
  6433. diff --git a/drivers/misc/surface_aggregator/clients/surface_dtx.c b/drivers/misc/surface_aggregator/clients/surface_dtx.c
  6434. new file mode 100644
  6435. index 000000000000..b7a3b8ce7726
  6436. --- /dev/null
  6437. +++ b/drivers/misc/surface_aggregator/clients/surface_dtx.c
  6438. @@ -0,0 +1,1277 @@
  6439. +// SPDX-License-Identifier: GPL-2.0+
  6440. +/*
  6441. + * Surface Book (gen. 2 and later) detachment system (DTX) driver.
  6442. + *
  6443. + * Provides a user-space interface to properly handle clipboard/tablet
  6444. + * (containing screen and processor) detachment from the base of the device
  6445. + * (containing the keyboard and optionally a discrete GPU). Allows to
  6446. + * acknowledge (to speed things up), abort (e.g. in case the dGPU is still in
  6447. + * use), or request detachment via user-space.
  6448. + *
  6449. + * Copyright (C) 2019-2020 Maximilian Luz <luzmaximilian@gmail.com>
  6450. + */
  6451. +
  6452. +#include <linux/acpi.h>
  6453. +#include <linux/delay.h>
  6454. +#include <linux/fs.h>
  6455. +#include <linux/input.h>
  6456. +#include <linux/ioctl.h>
  6457. +#include <linux/kernel.h>
  6458. +#include <linux/kfifo.h>
  6459. +#include <linux/kref.h>
  6460. +#include <linux/miscdevice.h>
  6461. +#include <linux/module.h>
  6462. +#include <linux/platform_device.h>
  6463. +#include <linux/poll.h>
  6464. +#include <linux/rwsem.h>
  6465. +#include <linux/slab.h>
  6466. +#include <linux/spinlock.h>
  6467. +
  6468. +#include <linux/surface_aggregator/controller.h>
  6469. +#include <linux/surface_aggregator/device.h>
  6470. +#include <linux/surface_aggregator/dtx.h>
  6471. +
  6472. +
  6473. +/* -- SSAM interface. ------------------------------------------------------- */
  6474. +
  6475. +enum sam_event_cid_bas {
  6476. + SAM_EVENT_CID_DTX_CONNECTION = 0x0c,
  6477. + SAM_EVENT_CID_DTX_REQUEST = 0x0e,
  6478. + SAM_EVENT_CID_DTX_CANCEL = 0x0f,
  6479. + SAM_EVENT_CID_DTX_LATCH_STATUS = 0x11,
  6480. +};
  6481. +
  6482. +enum ssam_bas_base_state {
  6483. + SSAM_BAS_BASE_STATE_DETACH_SUCCESS = 0x00,
  6484. + SSAM_BAS_BASE_STATE_ATTACHED = 0x01,
  6485. + SSAM_BAS_BASE_STATE_NOT_FEASIBLE = 0x02,
  6486. +};
  6487. +
  6488. +enum ssam_bas_latch_status {
  6489. + SSAM_BAS_LATCH_STATUS_CLOSED = 0x00,
  6490. + SSAM_BAS_LATCH_STATUS_OPENED = 0x01,
  6491. + SSAM_BAS_LATCH_STATUS_FAILED_TO_OPEN = 0x02,
  6492. + SSAM_BAS_LATCH_STATUS_FAILED_TO_REMAIN_OPEN = 0x03,
  6493. + SSAM_BAS_LATCH_STATUS_FAILED_TO_CLOSE = 0x04,
  6494. +};
  6495. +
  6496. +enum ssam_bas_cancel_reason {
  6497. + SSAM_BAS_CANCEL_REASON_NOT_FEASIBLE = 0x00, /* Low battery. */
  6498. + SSAM_BAS_CANCEL_REASON_TIMEOUT = 0x02,
  6499. + SSAM_BAS_CANCEL_REASON_FAILED_TO_OPEN = 0x03,
  6500. + SSAM_BAS_CANCEL_REASON_FAILED_TO_REMAIN_OPEN = 0x04,
  6501. + SSAM_BAS_CANCEL_REASON_FAILED_TO_CLOSE = 0x05,
  6502. +};
  6503. +
  6504. +struct ssam_bas_base_info {
  6505. + u8 state;
  6506. + u8 base_id;
  6507. +} __packed;
  6508. +
  6509. +static_assert(sizeof(struct ssam_bas_base_info) == 2);
  6510. +
  6511. +static SSAM_DEFINE_SYNC_REQUEST_N(ssam_bas_latch_lock, {
  6512. + .target_category = SSAM_SSH_TC_BAS,
  6513. + .target_id = 0x01,
  6514. + .command_id = 0x06,
  6515. + .instance_id = 0x00,
  6516. +});
  6517. +
  6518. +static SSAM_DEFINE_SYNC_REQUEST_N(ssam_bas_latch_unlock, {
  6519. + .target_category = SSAM_SSH_TC_BAS,
  6520. + .target_id = 0x01,
  6521. + .command_id = 0x07,
  6522. + .instance_id = 0x00,
  6523. +});
  6524. +
  6525. +static SSAM_DEFINE_SYNC_REQUEST_N(ssam_bas_latch_request, {
  6526. + .target_category = SSAM_SSH_TC_BAS,
  6527. + .target_id = 0x01,
  6528. + .command_id = 0x08,
  6529. + .instance_id = 0x00,
  6530. +});
  6531. +
  6532. +static SSAM_DEFINE_SYNC_REQUEST_N(ssam_bas_latch_confirm, {
  6533. + .target_category = SSAM_SSH_TC_BAS,
  6534. + .target_id = 0x01,
  6535. + .command_id = 0x09,
  6536. + .instance_id = 0x00,
  6537. +});
  6538. +
  6539. +static SSAM_DEFINE_SYNC_REQUEST_N(ssam_bas_latch_heartbeat, {
  6540. + .target_category = SSAM_SSH_TC_BAS,
  6541. + .target_id = 0x01,
  6542. + .command_id = 0x0a,
  6543. + .instance_id = 0x00,
  6544. +});
  6545. +
  6546. +static SSAM_DEFINE_SYNC_REQUEST_N(ssam_bas_latch_cancel, {
  6547. + .target_category = SSAM_SSH_TC_BAS,
  6548. + .target_id = 0x01,
  6549. + .command_id = 0x0b,
  6550. + .instance_id = 0x00,
  6551. +});
  6552. +
  6553. +static SSAM_DEFINE_SYNC_REQUEST_R(ssam_bas_get_base, struct ssam_bas_base_info, {
  6554. + .target_category = SSAM_SSH_TC_BAS,
  6555. + .target_id = 0x01,
  6556. + .command_id = 0x0c,
  6557. + .instance_id = 0x00,
  6558. +});
  6559. +
  6560. +static SSAM_DEFINE_SYNC_REQUEST_R(ssam_bas_get_device_mode, u8, {
  6561. + .target_category = SSAM_SSH_TC_BAS,
  6562. + .target_id = 0x01,
  6563. + .command_id = 0x0d,
  6564. + .instance_id = 0x00,
  6565. +});
  6566. +
  6567. +static SSAM_DEFINE_SYNC_REQUEST_R(ssam_bas_get_latch_status, u8, {
  6568. + .target_category = SSAM_SSH_TC_BAS,
  6569. + .target_id = 0x01,
  6570. + .command_id = 0x11,
  6571. + .instance_id = 0x00,
  6572. +});
  6573. +
  6574. +
  6575. +/* -- Main structures. ------------------------------------------------------ */
  6576. +
  6577. +enum sdtx_device_state {
  6578. + SDTX_DEVICE_SHUTDOWN_BIT = BIT(0),
  6579. + SDTX_DEVICE_DIRTY_BASE_BIT = BIT(1),
  6580. + SDTX_DEVICE_DIRTY_MODE_BIT = BIT(2),
  6581. + SDTX_DEVICE_DIRTY_LATCH_BIT = BIT(3),
  6582. +};
  6583. +
  6584. +struct sdtx_device {
  6585. + struct kref kref;
  6586. + struct rw_semaphore lock;
  6587. +
  6588. + struct device *dev;
  6589. + struct ssam_controller *ctrl;
  6590. + unsigned long flags;
  6591. +
  6592. + struct miscdevice mdev;
  6593. + wait_queue_head_t waitq;
  6594. + struct mutex write_lock;
  6595. + struct rw_semaphore client_lock;
  6596. + struct list_head client_list;
  6597. +
  6598. + struct delayed_work state_work;
  6599. + struct {
  6600. + struct ssam_bas_base_info base;
  6601. + u8 device_mode;
  6602. + u8 latch_status;
  6603. + } state;
  6604. +
  6605. + struct delayed_work mode_work;
  6606. + struct input_dev *mode_switch;
  6607. +
  6608. + struct ssam_event_notifier notif;
  6609. +};
  6610. +
  6611. +enum sdtx_client_state {
  6612. + SDTX_CLIENT_EVENTS_ENABLED_BIT = BIT(0),
  6613. +};
  6614. +
  6615. +struct sdtx_client {
  6616. + struct sdtx_device *ddev;
  6617. + struct list_head node;
  6618. + unsigned long flags;
  6619. +
  6620. + struct fasync_struct *fasync;
  6621. +
  6622. + struct mutex read_lock;
  6623. + DECLARE_KFIFO(buffer, u8, 512);
  6624. +};
  6625. +
  6626. +static void __sdtx_device_release(struct kref *kref)
  6627. +{
  6628. + struct sdtx_device *ddev = container_of(kref, struct sdtx_device, kref);
  6629. +
  6630. + mutex_destroy(&ddev->write_lock);
  6631. + kfree(ddev);
  6632. +}
  6633. +
  6634. +static struct sdtx_device *sdtx_device_get(struct sdtx_device *ddev)
  6635. +{
  6636. + if (ddev)
  6637. + kref_get(&ddev->kref);
  6638. +
  6639. + return ddev;
  6640. +}
  6641. +
  6642. +static void sdtx_device_put(struct sdtx_device *ddev)
  6643. +{
  6644. + if (ddev)
  6645. + kref_put(&ddev->kref, __sdtx_device_release);
  6646. +}
  6647. +
  6648. +
  6649. +/* -- Firmware value translations. ------------------------------------------ */
  6650. +
  6651. +static u16 sdtx_translate_base_state(struct sdtx_device *ddev, u8 state)
  6652. +{
  6653. + switch (state) {
  6654. + case SSAM_BAS_BASE_STATE_ATTACHED:
  6655. + return SDTX_BASE_ATTACHED;
  6656. +
  6657. + case SSAM_BAS_BASE_STATE_DETACH_SUCCESS:
  6658. + return SDTX_BASE_DETACHED;
  6659. +
  6660. + case SSAM_BAS_BASE_STATE_NOT_FEASIBLE:
  6661. + return SDTX_DETACH_NOT_FEASIBLE;
  6662. +
  6663. + default:
  6664. + dev_err(ddev->dev, "unknown base state: %#04x\n", state);
  6665. + return SDTX_UNKNOWN(state);
  6666. + }
  6667. +}
  6668. +
  6669. +static u16 sdtx_translate_latch_status(struct sdtx_device *ddev, u8 status)
  6670. +{
  6671. + switch (status) {
  6672. + case SSAM_BAS_LATCH_STATUS_CLOSED:
  6673. + return SDTX_LATCH_CLOSED;
  6674. +
  6675. + case SSAM_BAS_LATCH_STATUS_OPENED:
  6676. + return SDTX_LATCH_OPENED;
  6677. +
  6678. + case SSAM_BAS_LATCH_STATUS_FAILED_TO_OPEN:
  6679. + return SDTX_ERR_FAILED_TO_OPEN;
  6680. +
  6681. + case SSAM_BAS_LATCH_STATUS_FAILED_TO_REMAIN_OPEN:
  6682. + return SDTX_ERR_FAILED_TO_REMAIN_OPEN;
  6683. +
  6684. + case SSAM_BAS_LATCH_STATUS_FAILED_TO_CLOSE:
  6685. + return SDTX_ERR_FAILED_TO_CLOSE;
  6686. +
  6687. + default:
  6688. + dev_err(ddev->dev, "unknown latch status: %#04x\n", status);
  6689. + return SDTX_UNKNOWN(status);
  6690. + }
  6691. +}
  6692. +
  6693. +static u16 sdtx_translate_cancel_reason(struct sdtx_device *ddev, u8 reason)
  6694. +{
  6695. + switch (reason) {
  6696. + case SSAM_BAS_CANCEL_REASON_NOT_FEASIBLE:
  6697. + return SDTX_DETACH_NOT_FEASIBLE;
  6698. +
  6699. + case SSAM_BAS_CANCEL_REASON_TIMEOUT:
  6700. + return SDTX_DETACH_TIMEDOUT;
  6701. +
  6702. + case SSAM_BAS_CANCEL_REASON_FAILED_TO_OPEN:
  6703. + return SDTX_ERR_FAILED_TO_OPEN;
  6704. +
  6705. + case SSAM_BAS_CANCEL_REASON_FAILED_TO_REMAIN_OPEN:
  6706. + return SDTX_ERR_FAILED_TO_REMAIN_OPEN;
  6707. +
  6708. + case SSAM_BAS_CANCEL_REASON_FAILED_TO_CLOSE:
  6709. + return SDTX_ERR_FAILED_TO_CLOSE;
  6710. +
  6711. + default:
  6712. + dev_err(ddev->dev, "unknown cancel reason: %#04x\n", reason);
  6713. + return SDTX_UNKNOWN(reason);
  6714. + }
  6715. +}
  6716. +
  6717. +
  6718. +/* -- IOCTLs. --------------------------------------------------------------- */
  6719. +
  6720. +static int sdtx_ioctl_get_base_info(struct sdtx_device *ddev,
  6721. + struct sdtx_base_info __user *buf)
  6722. +{
  6723. + struct ssam_bas_base_info raw;
  6724. + struct sdtx_base_info info;
  6725. + int status;
  6726. +
  6727. + status = ssam_retry(ssam_bas_get_base, ddev->ctrl, &raw);
  6728. + if (status < 0)
  6729. + return status;
  6730. +
  6731. + info.state = sdtx_translate_base_state(ddev, raw.state);
  6732. + info.base_id = SDTX_BASE_TYPE_SSH(raw.base_id);
  6733. +
  6734. + if (copy_to_user(buf, &info, sizeof(info)))
  6735. + return -EFAULT;
  6736. +
  6737. + return 0;
  6738. +}
  6739. +
  6740. +static int sdtx_ioctl_get_device_mode(struct sdtx_device *ddev, u16 __user *buf)
  6741. +{
  6742. + u8 mode;
  6743. + int status;
  6744. +
  6745. + status = ssam_retry(ssam_bas_get_device_mode, ddev->ctrl, &mode);
  6746. + if (status < 0)
  6747. + return status;
  6748. +
  6749. + return put_user(mode, buf);
  6750. +}
  6751. +
  6752. +static int sdtx_ioctl_get_latch_status(struct sdtx_device *ddev, u16 __user *buf)
  6753. +{
  6754. + u8 latch;
  6755. + int status;
  6756. +
  6757. + status = ssam_retry(ssam_bas_get_latch_status, ddev->ctrl, &latch);
  6758. + if (status < 0)
  6759. + return status;
  6760. +
  6761. + return put_user(sdtx_translate_latch_status(ddev, latch), buf);
  6762. +}
  6763. +
  6764. +static long __surface_dtx_ioctl(struct sdtx_client *client, unsigned int cmd,
  6765. + unsigned long arg)
  6766. +{
  6767. + struct sdtx_device *ddev = client->ddev;
  6768. +
  6769. + switch (cmd) {
  6770. + case SDTX_IOCTL_EVENTS_ENABLE:
  6771. + set_bit(SDTX_CLIENT_EVENTS_ENABLED_BIT, &client->flags);
  6772. + return 0;
  6773. +
  6774. + case SDTX_IOCTL_EVENTS_DISABLE:
  6775. + clear_bit(SDTX_CLIENT_EVENTS_ENABLED_BIT, &client->flags);
  6776. + return 0;
  6777. +
  6778. + case SDTX_IOCTL_LATCH_LOCK:
  6779. + return ssam_retry(ssam_bas_latch_lock, ddev->ctrl);
  6780. +
  6781. + case SDTX_IOCTL_LATCH_UNLOCK:
  6782. + return ssam_retry(ssam_bas_latch_unlock, ddev->ctrl);
  6783. +
  6784. + case SDTX_IOCTL_LATCH_REQUEST:
  6785. + return ssam_retry(ssam_bas_latch_request, ddev->ctrl);
  6786. +
  6787. + case SDTX_IOCTL_LATCH_CONFIRM:
  6788. + return ssam_retry(ssam_bas_latch_confirm, ddev->ctrl);
  6789. +
  6790. + case SDTX_IOCTL_LATCH_HEARTBEAT:
  6791. + return ssam_retry(ssam_bas_latch_heartbeat, ddev->ctrl);
  6792. +
  6793. + case SDTX_IOCTL_LATCH_CANCEL:
  6794. + return ssam_retry(ssam_bas_latch_cancel, ddev->ctrl);
  6795. +
  6796. + case SDTX_IOCTL_GET_BASE_INFO:
  6797. + return sdtx_ioctl_get_base_info(ddev,
  6798. + (struct sdtx_base_info __user *)arg);
  6799. +
  6800. + case SDTX_IOCTL_GET_DEVICE_MODE:
  6801. + return sdtx_ioctl_get_device_mode(ddev, (u16 __user *)arg);
  6802. +
  6803. + case SDTX_IOCTL_GET_LATCH_STATUS:
  6804. + return sdtx_ioctl_get_latch_status(ddev, (u16 __user *)arg);
  6805. +
  6806. + default:
  6807. + return -EINVAL;
  6808. + }
  6809. +}
  6810. +
  6811. +static long surface_dtx_ioctl(struct file *file, unsigned int cmd,
  6812. + unsigned long arg)
  6813. +{
  6814. + struct sdtx_client *client = file->private_data;
  6815. + long status;
  6816. +
  6817. + if (down_read_killable(&client->ddev->lock))
  6818. + return -ERESTARTSYS;
  6819. +
  6820. + if (test_bit(SDTX_DEVICE_SHUTDOWN_BIT, &client->ddev->flags)) {
  6821. + up_read(&client->ddev->lock);
  6822. + return -ENODEV;
  6823. + }
  6824. +
  6825. + status = __surface_dtx_ioctl(client, cmd, arg);
  6826. +
  6827. + up_read(&client->ddev->lock);
  6828. + return status;
  6829. +}
  6830. +
  6831. +
  6832. +/* -- File operations. ------------------------------------------------------ */
  6833. +
  6834. +static int surface_dtx_open(struct inode *inode, struct file *file)
  6835. +{
  6836. + struct sdtx_device *ddev;
  6837. + struct sdtx_client *client;
  6838. +
  6839. + ddev = container_of(file->private_data, struct sdtx_device, mdev);
  6840. +
  6841. + /* Initialize client. */
  6842. + client = kzalloc(sizeof(*client), GFP_KERNEL);
  6843. + if (!client)
  6844. + return -ENOMEM;
  6845. +
  6846. + client->ddev = sdtx_device_get(ddev);
  6847. +
  6848. + INIT_LIST_HEAD(&client->node);
  6849. +
  6850. + mutex_init(&client->read_lock);
  6851. + INIT_KFIFO(client->buffer);
  6852. +
  6853. + file->private_data = client;
  6854. +
  6855. + /* Attach client. */
  6856. + down_write(&ddev->client_lock);
  6857. +
  6858. + /* Do not add a new client if the device has been shut down. */
  6859. + if (test_bit(SDTX_DEVICE_SHUTDOWN_BIT, &ddev->flags)) {
  6860. + up_write(&ddev->client_lock);
  6861. + sdtx_device_put(client->ddev);
  6862. + kfree(client);
  6863. + return -ENODEV;
  6864. + }
  6865. +
  6866. + list_add_tail(&client->node, &ddev->client_list);
  6867. + up_write(&ddev->client_lock);
  6868. +
  6869. + stream_open(inode, file);
  6870. + return 0;
  6871. +}
  6872. +
  6873. +static int surface_dtx_release(struct inode *inode, struct file *file)
  6874. +{
  6875. + struct sdtx_client *client = file->private_data;
  6876. +
  6877. + /* Detach client. */
  6878. + down_write(&client->ddev->client_lock);
  6879. + list_del(&client->node);
  6880. + up_write(&client->ddev->client_lock);
  6881. +
  6882. + sdtx_device_put(client->ddev);
  6883. + mutex_destroy(&client->read_lock);
  6884. + kfree(client);
  6885. +
  6886. + return 0;
  6887. +}
  6888. +
  6889. +static ssize_t surface_dtx_read(struct file *file, char __user *buf,
  6890. + size_t count, loff_t *offs)
  6891. +{
  6892. + struct sdtx_client *client = file->private_data;
  6893. + struct sdtx_device *ddev = client->ddev;
  6894. + unsigned int copied;
  6895. + int status = 0;
  6896. +
  6897. + if (down_read_killable(&ddev->lock))
  6898. + return -ERESTARTSYS;
  6899. +
  6900. + /* Make sure we're not shut down. */
  6901. + if (test_bit(SDTX_DEVICE_SHUTDOWN_BIT, &ddev->flags)) {
  6902. + up_read(&ddev->lock);
  6903. + return -ENODEV;
  6904. + }
  6905. +
  6906. + do {
  6907. + /* Check availability, wait if necessary. */
  6908. + if (kfifo_is_empty(&client->buffer)) {
  6909. + up_read(&ddev->lock);
  6910. +
  6911. + if (file->f_flags & O_NONBLOCK)
  6912. + return -EAGAIN;
  6913. +
  6914. + status = wait_event_interruptible(ddev->waitq,
  6915. + !kfifo_is_empty(&client->buffer) ||
  6916. + test_bit(SDTX_DEVICE_SHUTDOWN_BIT,
  6917. + &ddev->flags));
  6918. + if (status < 0)
  6919. + return status;
  6920. +
  6921. + if (down_read_killable(&client->ddev->lock))
  6922. + return -ERESTARTSYS;
  6923. +
  6924. + /* Need to check that we're not shut down again. */
  6925. + if (test_bit(SDTX_DEVICE_SHUTDOWN_BIT, &ddev->flags)) {
  6926. + up_read(&ddev->lock);
  6927. + return -ENODEV;
  6928. + }
  6929. + }
  6930. +
  6931. + /* Try to read from FIFO. */
  6932. + if (mutex_lock_interruptible(&client->read_lock)) {
  6933. + up_read(&ddev->lock);
  6934. + return -ERESTARTSYS;
  6935. + }
  6936. +
  6937. + status = kfifo_to_user(&client->buffer, buf, count, &copied);
  6938. + mutex_unlock(&client->read_lock);
  6939. +
  6940. + if (status < 0) {
  6941. + up_read(&ddev->lock);
  6942. + return status;
  6943. + }
  6944. +
  6945. + /* We might not have gotten anything, check this here. */
  6946. + if (copied == 0 && (file->f_flags & O_NONBLOCK)) {
  6947. + up_read(&ddev->lock);
  6948. + return -EAGAIN;
  6949. + }
  6950. + } while (copied == 0);
  6951. +
  6952. + up_read(&ddev->lock);
  6953. + return copied;
  6954. +}
  6955. +
  6956. +static __poll_t surface_dtx_poll(struct file *file, struct poll_table_struct *pt)
  6957. +{
  6958. + struct sdtx_client *client = file->private_data;
  6959. + __poll_t events = 0;
  6960. +
  6961. + if (down_read_killable(&client->ddev->lock))
  6962. + return -ERESTARTSYS;
  6963. +
  6964. + if (test_bit(SDTX_DEVICE_SHUTDOWN_BIT, &client->ddev->flags)) {
  6965. + up_read(&client->ddev->lock);
  6966. + return EPOLLHUP | EPOLLERR;
  6967. + }
  6968. +
  6969. + poll_wait(file, &client->ddev->waitq, pt);
  6970. +
  6971. + if (!kfifo_is_empty(&client->buffer))
  6972. + events |= EPOLLIN | EPOLLRDNORM;
  6973. +
  6974. + up_read(&client->ddev->lock);
  6975. + return events;
  6976. +}
  6977. +
  6978. +static int surface_dtx_fasync(int fd, struct file *file, int on)
  6979. +{
  6980. + struct sdtx_client *client = file->private_data;
  6981. +
  6982. + return fasync_helper(fd, file, on, &client->fasync);
  6983. +}
  6984. +
  6985. +static const struct file_operations surface_dtx_fops = {
  6986. + .owner = THIS_MODULE,
  6987. + .open = surface_dtx_open,
  6988. + .release = surface_dtx_release,
  6989. + .read = surface_dtx_read,
  6990. + .poll = surface_dtx_poll,
  6991. + .fasync = surface_dtx_fasync,
  6992. + .unlocked_ioctl = surface_dtx_ioctl,
  6993. + .compat_ioctl = surface_dtx_ioctl,
  6994. + .llseek = no_llseek,
  6995. +};
  6996. +
  6997. +
  6998. +/* -- Event handling/forwarding. -------------------------------------------- */
  6999. +
  7000. +/*
  7001. + * The device operation mode is not immediately updated on the EC when the
  7002. + * base has been connected, i.e. querying the device mode inside the
  7003. + * connection event callback yields an outdated value. Thus, we can only
  7004. + * determine the new tablet-mode switch and device mode values after some
  7005. + * time.
  7006. + *
  7007. + * These delays have been chosen by experimenting. We first delay on connect
  7008. + * events, then check and validate the device mode against the base state and
  7009. + * if invalid delay again by the "recheck" delay.
  7010. + */
  7011. +#define SDTX_DEVICE_MODE_DELAY_CONNECT msecs_to_jiffies(100)
  7012. +#define SDTX_DEVICE_MODE_DELAY_RECHECK msecs_to_jiffies(100)
  7013. +
  7014. +static void sdtx_update_device_mode(struct sdtx_device *ddev, unsigned long delay);
  7015. +
  7016. +struct sdtx_status_event {
  7017. + struct sdtx_event e;
  7018. + __u16 v;
  7019. +} __packed;
  7020. +
  7021. +struct sdtx_base_info_event {
  7022. + struct sdtx_event e;
  7023. + struct sdtx_base_info v;
  7024. +} __packed;
  7025. +
  7026. +union sdtx_generic_event {
  7027. + struct sdtx_event common;
  7028. + struct sdtx_status_event status;
  7029. + struct sdtx_base_info_event base;
  7030. +};
  7031. +
  7032. +/* Must be executed with ddev->write_lock held. */
  7033. +static void sdtx_push_event(struct sdtx_device *ddev, struct sdtx_event *evt)
  7034. +{
  7035. + const size_t len = sizeof(struct sdtx_event) + evt->length;
  7036. + struct sdtx_client *client;
  7037. +
  7038. + down_read(&ddev->client_lock);
  7039. + list_for_each_entry(client, &ddev->client_list, node) {
  7040. + if (!test_bit(SDTX_CLIENT_EVENTS_ENABLED_BIT, &client->flags))
  7041. + continue;
  7042. +
  7043. + if (likely(kfifo_avail(&client->buffer) >= len))
  7044. + kfifo_in(&client->buffer, (const u8 *)evt, len);
  7045. + else
  7046. + dev_warn(ddev->dev, "event buffer overrun\n");
  7047. +
  7048. + kill_fasync(&client->fasync, SIGIO, POLL_IN);
  7049. + }
  7050. + up_read(&ddev->client_lock);
  7051. +
  7052. + wake_up_interruptible(&ddev->waitq);
  7053. +}
  7054. +
  7055. +static u32 sdtx_notifier(struct ssam_event_notifier *nf,
  7056. + const struct ssam_event *in)
  7057. +{
  7058. + struct sdtx_device *ddev = container_of(nf, struct sdtx_device, notif);
  7059. + union sdtx_generic_event event;
  7060. + size_t len;
  7061. +
  7062. + /* Validate event payload length. */
  7063. + switch (in->command_id) {
  7064. + case SAM_EVENT_CID_DTX_CONNECTION:
  7065. + len = 2;
  7066. + break;
  7067. +
  7068. + case SAM_EVENT_CID_DTX_REQUEST:
  7069. + len = 0;
  7070. + break;
  7071. +
  7072. + case SAM_EVENT_CID_DTX_CANCEL:
  7073. + len = 1;
  7074. + break;
  7075. +
  7076. + case SAM_EVENT_CID_DTX_LATCH_STATUS:
  7077. + len = 1;
  7078. + break;
  7079. +
  7080. + default:
  7081. + return 0;
  7082. + };
  7083. +
  7084. + if (in->length != len) {
  7085. + dev_err(ddev->dev,
  7086. + "unexpected payload size for event %#04x: got %u, expected %zu\n",
  7087. + in->command_id, in->length, len);
  7088. + return 0;
  7089. + }
  7090. +
  7091. + mutex_lock(&ddev->write_lock);
  7092. +
  7093. + /* Translate event. */
  7094. + switch (in->command_id) {
  7095. + case SAM_EVENT_CID_DTX_CONNECTION:
  7096. + clear_bit(SDTX_DEVICE_DIRTY_BASE_BIT, &ddev->flags);
  7097. +
  7098. + /* If state has not changed: do not send new event. */
  7099. + if (ddev->state.base.state == in->data[0] &&
  7100. + ddev->state.base.base_id == in->data[1])
  7101. + goto out;
  7102. +
  7103. + ddev->state.base.state = in->data[0];
  7104. + ddev->state.base.base_id = in->data[1];
  7105. +
  7106. + event.base.e.length = sizeof(struct sdtx_base_info);
  7107. + event.base.e.code = SDTX_EVENT_BASE_CONNECTION;
  7108. + event.base.v.state = sdtx_translate_base_state(ddev, in->data[0]);
  7109. + event.base.v.base_id = SDTX_BASE_TYPE_SSH(in->data[1]);
  7110. + break;
  7111. +
  7112. + case SAM_EVENT_CID_DTX_REQUEST:
  7113. + event.common.code = SDTX_EVENT_REQUEST;
  7114. + event.common.length = 0;
  7115. + break;
  7116. +
  7117. + case SAM_EVENT_CID_DTX_CANCEL:
  7118. + event.status.e.length = sizeof(u16);
  7119. + event.status.e.code = SDTX_EVENT_CANCEL;
  7120. + event.status.v = sdtx_translate_cancel_reason(ddev, in->data[0]);
  7121. + break;
  7122. +
  7123. + case SAM_EVENT_CID_DTX_LATCH_STATUS:
  7124. + clear_bit(SDTX_DEVICE_DIRTY_LATCH_BIT, &ddev->flags);
  7125. +
  7126. + /* If state has not changed: do not send new event. */
  7127. + if (ddev->state.latch_status == in->data[0])
  7128. + goto out;
  7129. +
  7130. + ddev->state.latch_status = in->data[0];
  7131. +
  7132. + event.status.e.length = sizeof(u16);
  7133. + event.status.e.code = SDTX_EVENT_LATCH_STATUS;
  7134. + event.status.v = sdtx_translate_latch_status(ddev, in->data[0]);
  7135. + break;
  7136. + }
  7137. +
  7138. + sdtx_push_event(ddev, &event.common);
  7139. +
  7140. + /* Update device mode on base connection change. */
  7141. + if (in->command_id == SAM_EVENT_CID_DTX_CONNECTION) {
  7142. + unsigned long delay;
  7143. +
  7144. + delay = in->data[0] ? SDTX_DEVICE_MODE_DELAY_CONNECT : 0;
  7145. + sdtx_update_device_mode(ddev, delay);
  7146. + }
  7147. +
  7148. +out:
  7149. + mutex_unlock(&ddev->write_lock);
  7150. + return SSAM_NOTIF_HANDLED;
  7151. +}
  7152. +
  7153. +
  7154. +/* -- State update functions. ----------------------------------------------- */
  7155. +
  7156. +static bool sdtx_device_mode_invalid(u8 mode, u8 base_state)
  7157. +{
  7158. + return ((base_state == SSAM_BAS_BASE_STATE_ATTACHED) &&
  7159. + (mode == SDTX_DEVICE_MODE_TABLET)) ||
  7160. + ((base_state == SSAM_BAS_BASE_STATE_DETACH_SUCCESS) &&
  7161. + (mode != SDTX_DEVICE_MODE_TABLET));
  7162. +}
  7163. +
  7164. +static void sdtx_device_mode_workfn(struct work_struct *work)
  7165. +{
  7166. + struct sdtx_device *ddev;
  7167. + struct sdtx_status_event event;
  7168. + struct ssam_bas_base_info base;
  7169. + int status, tablet;
  7170. + u8 mode;
  7171. +
  7172. + ddev = container_of(work, struct sdtx_device, mode_work.work);
  7173. +
  7174. + /* Get operation mode. */
  7175. + status = ssam_retry(ssam_bas_get_device_mode, ddev->ctrl, &mode);
  7176. + if (status) {
  7177. + dev_err(ddev->dev, "failed to get device mode: %d\n", status);
  7178. + return;
  7179. + }
  7180. +
  7181. + /* Get base info. */
  7182. + status = ssam_retry(ssam_bas_get_base, ddev->ctrl, &base);
  7183. + if (status) {
  7184. + dev_err(ddev->dev, "failed to get base info: %d\n", status);
  7185. + return;
  7186. + }
  7187. +
  7188. + /*
  7189. + * In some cases (specifically when attaching the base), the device
  7190. + * mode isn't updated right away. Thus we check if the device mode
  7191. + * makes sense for the given base state and try again later if it
  7192. + * doesn't.
  7193. + */
  7194. + if (sdtx_device_mode_invalid(mode, base.state)) {
  7195. + dev_dbg(ddev->dev, "device mode is invalid, trying again\n");
  7196. + sdtx_update_device_mode(ddev, SDTX_DEVICE_MODE_DELAY_RECHECK);
  7197. + return;
  7198. + }
  7199. +
  7200. + mutex_lock(&ddev->write_lock);
  7201. + clear_bit(SDTX_DEVICE_DIRTY_MODE_BIT, &ddev->flags);
  7202. +
  7203. + /* Avoid sending duplicate device-mode events. */
  7204. + if (ddev->state.device_mode == mode) {
  7205. + mutex_unlock(&ddev->write_lock);
  7206. + return;
  7207. + }
  7208. +
  7209. + ddev->state.device_mode = mode;
  7210. +
  7211. + event.e.length = sizeof(u16);
  7212. + event.e.code = SDTX_EVENT_DEVICE_MODE;
  7213. + event.v = mode;
  7214. +
  7215. + sdtx_push_event(ddev, &event.e);
  7216. +
  7217. + /* Send SW_TABLET_MODE event. */
  7218. + tablet = mode != SDTX_DEVICE_MODE_LAPTOP;
  7219. + input_report_switch(ddev->mode_switch, SW_TABLET_MODE, tablet);
  7220. + input_sync(ddev->mode_switch);
  7221. +
  7222. + mutex_unlock(&ddev->write_lock);
  7223. +}
  7224. +
  7225. +static void sdtx_update_device_mode(struct sdtx_device *ddev, unsigned long delay)
  7226. +{
  7227. + schedule_delayed_work(&ddev->mode_work, delay);
  7228. +}
  7229. +
  7230. +static void __sdtx_device_state_update_base(struct sdtx_device *ddev,
  7231. + struct ssam_bas_base_info info)
  7232. +{
  7233. + struct sdtx_base_info_event event;
  7234. +
  7235. + /* Prevent duplicate events. */
  7236. + if (ddev->state.base.state == info.state &&
  7237. + ddev->state.base.base_id == info.base_id)
  7238. + return;
  7239. +
  7240. + ddev->state.base = info;
  7241. +
  7242. + event.e.length = sizeof(struct sdtx_base_info);
  7243. + event.e.code = SDTX_EVENT_BASE_CONNECTION;
  7244. + event.v.state = sdtx_translate_base_state(ddev, info.state);
  7245. + event.v.base_id = SDTX_BASE_TYPE_SSH(info.base_id);
  7246. +
  7247. + sdtx_push_event(ddev, &event.e);
  7248. +}
  7249. +
  7250. +static void __sdtx_device_state_update_mode(struct sdtx_device *ddev, u8 mode)
  7251. +{
  7252. + struct sdtx_status_event event;
  7253. + int tablet;
  7254. +
  7255. + /*
  7256. + * Note: This function must be called after updating the base state
  7257. + * via __sdtx_device_state_update_base(), as we rely on the updated
  7258. + * base state value in the validity check below.
  7259. + */
  7260. +
  7261. + if (sdtx_device_mode_invalid(mode, ddev->state.base.state)) {
  7262. + dev_dbg(ddev->dev, "device mode is invalid, trying again\n");
  7263. + sdtx_update_device_mode(ddev, SDTX_DEVICE_MODE_DELAY_RECHECK);
  7264. + return;
  7265. + }
  7266. +
  7267. + /* Prevent duplicate events. */
  7268. + if (ddev->state.device_mode == mode)
  7269. + return;
  7270. +
  7271. + ddev->state.device_mode = mode;
  7272. +
  7273. + /* Send event. */
  7274. + event.e.length = sizeof(u16);
  7275. + event.e.code = SDTX_EVENT_DEVICE_MODE;
  7276. + event.v = mode;
  7277. +
  7278. + sdtx_push_event(ddev, &event.e);
  7279. +
  7280. + /* Send SW_TABLET_MODE event. */
  7281. + tablet = mode != SDTX_DEVICE_MODE_LAPTOP;
  7282. + input_report_switch(ddev->mode_switch, SW_TABLET_MODE, tablet);
  7283. + input_sync(ddev->mode_switch);
  7284. +}
  7285. +
  7286. +static void __sdtx_device_state_update_latch(struct sdtx_device *ddev, u8 status)
  7287. +{
  7288. + struct sdtx_status_event event;
  7289. +
  7290. + /* Prevent duplicate events. */
  7291. + if (ddev->state.latch_status == status)
  7292. + return;
  7293. +
  7294. + ddev->state.latch_status = status;
  7295. +
  7296. + event.e.length = sizeof(struct sdtx_base_info);
  7297. + event.e.code = SDTX_EVENT_BASE_CONNECTION;
  7298. + event.v = sdtx_translate_latch_status(ddev, status);
  7299. +
  7300. + sdtx_push_event(ddev, &event.e);
  7301. +}
  7302. +
  7303. +static void sdtx_device_state_workfn(struct work_struct *work)
  7304. +{
  7305. + struct sdtx_device *ddev;
  7306. + struct ssam_bas_base_info base;
  7307. + u8 mode, latch;
  7308. + int status;
  7309. +
  7310. + ddev = container_of(work, struct sdtx_device, state_work.work);
  7311. +
  7312. + /* Mark everything as dirty. */
  7313. + set_bit(SDTX_DEVICE_DIRTY_BASE_BIT, &ddev->flags);
  7314. + set_bit(SDTX_DEVICE_DIRTY_MODE_BIT, &ddev->flags);
  7315. + set_bit(SDTX_DEVICE_DIRTY_LATCH_BIT, &ddev->flags);
  7316. +
  7317. + /*
  7318. + * Ensure that the state gets marked as dirty before continuing to
  7319. + * query it. Necessary to ensure that clear_bit() calls in
  7320. + * sdtx_notifier() and sdtx_device_mode_workfn() actually clear these
  7321. + * bits if an event is received while updating the state here.
  7322. + */
  7323. + smp_mb__after_atomic();
  7324. +
  7325. + status = ssam_retry(ssam_bas_get_base, ddev->ctrl, &base);
  7326. + if (status) {
  7327. + dev_err(ddev->dev, "failed to get base state: %d\n", status);
  7328. + return;
  7329. + }
  7330. +
  7331. + status = ssam_retry(ssam_bas_get_device_mode, ddev->ctrl, &mode);
  7332. + if (status) {
  7333. + dev_err(ddev->dev, "failed to get device mode: %d\n", status);
  7334. + return;
  7335. + }
  7336. +
  7337. + status = ssam_retry(ssam_bas_get_latch_status, ddev->ctrl, &latch);
  7338. + if (status) {
  7339. + dev_err(ddev->dev, "failed to get latch status: %d\n", status);
  7340. + return;
  7341. + }
  7342. +
  7343. + mutex_lock(&ddev->write_lock);
  7344. +
  7345. + /*
  7346. + * If the respective dirty-bit has been cleared, an event has been
  7347. + * received, updating this state. The queried state may thus be out of
  7348. + * date. At this point, we can safely assume that the state provided
  7349. + * by the event is either up to date, or we're about to receive
  7350. + * another event updating it.
  7351. + */
  7352. +
  7353. + if (test_and_clear_bit(SDTX_DEVICE_DIRTY_BASE_BIT, &ddev->flags))
  7354. + __sdtx_device_state_update_base(ddev, base);
  7355. +
  7356. + if (test_and_clear_bit(SDTX_DEVICE_DIRTY_MODE_BIT, &ddev->flags))
  7357. + __sdtx_device_state_update_mode(ddev, mode);
  7358. +
  7359. + if (test_and_clear_bit(SDTX_DEVICE_DIRTY_LATCH_BIT, &ddev->flags))
  7360. + __sdtx_device_state_update_latch(ddev, latch);
  7361. +
  7362. + mutex_unlock(&ddev->write_lock);
  7363. +}
  7364. +
  7365. +static void sdtx_update_device_state(struct sdtx_device *ddev, unsigned long delay)
  7366. +{
  7367. + schedule_delayed_work(&ddev->state_work, delay);
  7368. +}
  7369. +
  7370. +
  7371. +/* -- Common device initialization. ----------------------------------------- */
  7372. +
  7373. +static int sdtx_device_init(struct sdtx_device *ddev, struct device *dev,
  7374. + struct ssam_controller *ctrl)
  7375. +{
  7376. + int status, tablet_mode;
  7377. +
  7378. + /* Basic initialization. */
  7379. + kref_init(&ddev->kref);
  7380. + ddev->dev = dev;
  7381. + ddev->ctrl = ctrl;
  7382. +
  7383. + ddev->mdev.minor = MISC_DYNAMIC_MINOR;
  7384. + ddev->mdev.name = "surface_dtx";
  7385. + ddev->mdev.nodename = "surface/dtx";
  7386. + ddev->mdev.fops = &surface_dtx_fops;
  7387. +
  7388. + ddev->notif.base.priority = 1;
  7389. + ddev->notif.base.fn = sdtx_notifier;
  7390. + ddev->notif.event.reg = SSAM_EVENT_REGISTRY_SAM;
  7391. + ddev->notif.event.id.target_category = SSAM_SSH_TC_BAS;
  7392. + ddev->notif.event.id.instance = 0;
  7393. + ddev->notif.event.mask = SSAM_EVENT_MASK_NONE;
  7394. + ddev->notif.event.flags = SSAM_EVENT_SEQUENCED;
  7395. +
  7396. + init_waitqueue_head(&ddev->waitq);
  7397. + mutex_init(&ddev->write_lock);
  7398. + init_rwsem(&ddev->client_lock);
  7399. + INIT_LIST_HEAD(&ddev->client_list);
  7400. +
  7401. + INIT_DELAYED_WORK(&ddev->mode_work, sdtx_device_mode_workfn);
  7402. + INIT_DELAYED_WORK(&ddev->state_work, sdtx_device_state_workfn);
  7403. +
  7404. + /*
  7405. + * Get current device state. We want to guarantee that events are only
  7406. + * sent when state actually changes. Thus we cannot use special
  7407. + * "uninitialized" values, as that would cause problems when manually
  7408. + * querying the state in surface_dtx_pm_complete(). I.e. we would not
  7409. + * be able to detect state changes there if no change event has been
  7410. + * received between driver initialization and first device suspension.
  7411. + *
  7412. + * Note that we also need to do this before registering the event
  7413. + * notifier, as that may access the state values.
  7414. + */
  7415. + status = ssam_retry(ssam_bas_get_base, ddev->ctrl, &ddev->state.base);
  7416. + if (status)
  7417. + return status;
  7418. +
  7419. + status = ssam_retry(ssam_bas_get_device_mode, ddev->ctrl,
  7420. + &ddev->state.device_mode);
  7421. + if (status)
  7422. + return status;
  7423. +
  7424. + status = ssam_retry(ssam_bas_get_latch_status, ddev->ctrl,
  7425. + &ddev->state.latch_status);
  7426. + if (status)
  7427. + return status;
  7428. +
  7429. + /* Set up tablet mode switch. */
  7430. + ddev->mode_switch = input_allocate_device();
  7431. + if (!ddev->mode_switch)
  7432. + return -ENOMEM;
  7433. +
  7434. + ddev->mode_switch->name = "Microsoft Surface DTX Device Mode Switch";
  7435. + ddev->mode_switch->phys = "ssam/01:11:01:00:00/input0";
  7436. + ddev->mode_switch->id.bustype = BUS_HOST;
  7437. + ddev->mode_switch->dev.parent = ddev->dev;
  7438. +
  7439. + tablet_mode = (ddev->state.device_mode != SDTX_DEVICE_MODE_LAPTOP);
  7440. + input_set_capability(ddev->mode_switch, EV_SW, SW_TABLET_MODE);
  7441. + input_report_switch(ddev->mode_switch, SW_TABLET_MODE, tablet_mode);
  7442. +
  7443. + status = input_register_device(ddev->mode_switch);
  7444. + if (status) {
  7445. + input_free_device(ddev->mode_switch);
  7446. + return status;
  7447. + }
  7448. +
  7449. + /* Set up event notifier. */
  7450. + status = ssam_notifier_register(ddev->ctrl, &ddev->notif);
  7451. + if (status)
  7452. + goto err_notif;
  7453. +
  7454. + /* Register miscdevice. */
  7455. + status = misc_register(&ddev->mdev);
  7456. + if (status)
  7457. + goto err_mdev;
  7458. +
  7459. + /*
  7460. + * Update device state in case it has changed between getting the
  7461. + * initial mode and registering the event notifier.
  7462. + */
  7463. + sdtx_update_device_state(ddev, 0);
  7464. + return 0;
  7465. +
  7466. +err_notif:
  7467. + ssam_notifier_unregister(ddev->ctrl, &ddev->notif);
  7468. + cancel_delayed_work_sync(&ddev->mode_work);
  7469. +err_mdev:
  7470. + input_unregister_device(ddev->mode_switch);
  7471. + return status;
  7472. +}
  7473. +
  7474. +static struct sdtx_device *sdtx_device_setup(struct device *dev,
  7475. + struct ssam_controller *ctrl)
  7476. +{
  7477. + struct sdtx_device *ddev;
  7478. + int status;
  7479. +
  7480. + ddev = kzalloc(sizeof(*ddev), GFP_KERNEL);
  7481. + if (!ddev)
  7482. + return ERR_PTR(-ENOMEM);
  7483. +
  7484. + status = sdtx_device_init(ddev, dev, ctrl);
  7485. + if (status) {
  7486. + kfree(ddev);
  7487. + return ERR_PTR(status);
  7488. + }
  7489. +
  7490. + return ddev;
  7491. +}
  7492. +
  7493. +static void sdtx_device_destroy(struct sdtx_device *ddev)
  7494. +{
  7495. + struct sdtx_client *client;
  7496. +
  7497. + /* Disable notifiers, prevent new events from arriving. */
  7498. + ssam_notifier_unregister(ddev->ctrl, &ddev->notif);
  7499. +
  7500. + /* Stop mode_work, prevent access to mode_switch. */
  7501. + cancel_delayed_work_sync(&ddev->mode_work);
  7502. +
  7503. + /* Stop state_work. */
  7504. + cancel_delayed_work_sync(&ddev->state_work);
  7505. +
  7506. + /* With mode_work canceled, we can unregister the mode_switch. */
  7507. + input_unregister_device(ddev->mode_switch);
  7508. +
  7509. + /*
  7510. + * Mark device as shut-down. Prevent new clients from being added and
  7511. + * new operations from being executed.
  7512. + */
  7513. + set_bit(SDTX_DEVICE_SHUTDOWN_BIT, &ddev->flags);
  7514. +
  7515. + /* Wake up async clients. */
  7516. + down_write(&ddev->client_lock);
  7517. + list_for_each_entry(client, &ddev->client_list, node) {
  7518. + kill_fasync(&client->fasync, SIGIO, POLL_HUP);
  7519. + }
  7520. + up_write(&ddev->client_lock);
  7521. +
  7522. + /* Wake up blocking clients. */
  7523. + wake_up_interruptible(&ddev->waitq);
  7524. +
  7525. + /*
  7526. + * Wait for clients to finish their current operation. After this, the
  7527. + * controller and device references are guaranteed to be no longer in
  7528. + * use.
  7529. + */
  7530. + down_write(&ddev->lock);
  7531. + ddev->dev = NULL;
  7532. + ddev->ctrl = NULL;
  7533. + up_write(&ddev->lock);
  7534. +
  7535. + /* Finally remove the misc-device. */
  7536. + misc_deregister(&ddev->mdev);
  7537. +
  7538. + /*
  7539. + * We're now guaranteed that sdtx_device_open() won't be called any
  7540. + * more, so we can now drop out reference.
  7541. + */
  7542. + sdtx_device_put(ddev);
  7543. +}
  7544. +
  7545. +
  7546. +/* -- PM ops. --------------------------------------------------------------- */
  7547. +
  7548. +#ifdef CONFIG_PM_SLEEP
  7549. +
  7550. +static void surface_dtx_pm_complete(struct device *dev)
  7551. +{
  7552. + struct sdtx_device *ddev = dev_get_drvdata(dev);
  7553. +
  7554. + /*
  7555. + * Normally, the EC will store events while suspended (i.e. in
  7556. + * display-off state) and release them when resumed (i.e. transitioned
  7557. + * to display-on state). During hibernation, however, the EC will be
  7558. + * shut down and does not store events. Furthermore, events might be
  7559. + * dropped during prolonged suspension (it is currently unknown how
  7560. + * big this event buffer is and how it behaves on overruns).
  7561. + *
  7562. + * To prevent any problems, we update the device state here. We do
  7563. + * this delayed to ensure that any events sent by the EC directly
  7564. + * after resuming will be handled first. The delay below has been
  7565. + * chosen (experimentally), so that there should be ample time for
  7566. + * these events to be handled, before we check and, if necessary,
  7567. + * update the state.
  7568. + */
  7569. + sdtx_update_device_state(ddev, msecs_to_jiffies(1000));
  7570. +}
  7571. +
  7572. +static const struct dev_pm_ops surface_dtx_pm_ops = {
  7573. + .complete = surface_dtx_pm_complete,
  7574. +};
  7575. +
  7576. +#else /* CONFIG_PM_SLEEP */
  7577. +
  7578. +static const struct dev_pm_ops surface_dtx_pm_ops = {};
  7579. +
  7580. +#endif /* CONFIG_PM_SLEEP */
  7581. +
  7582. +
  7583. +/* -- Platform driver. ------------------------------------------------------ */
  7584. +
  7585. +static int surface_dtx_platform_probe(struct platform_device *pdev)
  7586. +{
  7587. + struct ssam_controller *ctrl;
  7588. + struct sdtx_device *ddev;
  7589. +
  7590. + /* Link to EC. */
  7591. + ctrl = ssam_client_bind(&pdev->dev);
  7592. + if (IS_ERR(ctrl))
  7593. + return PTR_ERR(ctrl) == -ENODEV ? -EPROBE_DEFER : PTR_ERR(ctrl);
  7594. +
  7595. + ddev = sdtx_device_setup(&pdev->dev, ctrl);
  7596. + if (IS_ERR(ddev))
  7597. + return PTR_ERR(ddev);
  7598. +
  7599. + platform_set_drvdata(pdev, ddev);
  7600. + return 0;
  7601. +}
  7602. +
  7603. +static int surface_dtx_platform_remove(struct platform_device *pdev)
  7604. +{
  7605. + sdtx_device_destroy(platform_get_drvdata(pdev));
  7606. + return 0;
  7607. +}
  7608. +
  7609. +static const struct acpi_device_id surface_dtx_acpi_match[] = {
  7610. + { "MSHW0133", 0 },
  7611. + { },
  7612. +};
  7613. +MODULE_DEVICE_TABLE(acpi, surface_dtx_acpi_match);
  7614. +
  7615. +static struct platform_driver surface_dtx_platform_driver = {
  7616. + .probe = surface_dtx_platform_probe,
  7617. + .remove = surface_dtx_platform_remove,
  7618. + .driver = {
  7619. + .name = "surface_dtx_pltf",
  7620. + .acpi_match_table = surface_dtx_acpi_match,
  7621. + .pm = &surface_dtx_pm_ops,
  7622. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  7623. + },
  7624. +};
  7625. +
  7626. +
  7627. +/* -- SSAM device driver. --------------------------------------------------- */
  7628. +
  7629. +#ifdef CONFIG_SURFACE_AGGREGATOR_BUS
  7630. +
  7631. +static int surface_dtx_ssam_probe(struct ssam_device *sdev)
  7632. +{
  7633. + struct sdtx_device *ddev;
  7634. +
  7635. + ddev = sdtx_device_setup(&sdev->dev, sdev->ctrl);
  7636. + if (IS_ERR(ddev))
  7637. + return PTR_ERR(ddev);
  7638. +
  7639. + ssam_device_set_drvdata(sdev, ddev);
  7640. + return 0;
  7641. +}
  7642. +
  7643. +static void surface_dtx_ssam_remove(struct ssam_device *sdev)
  7644. +{
  7645. + sdtx_device_destroy(ssam_device_get_drvdata(sdev));
  7646. +}
  7647. +
  7648. +static const struct ssam_device_id surface_dtx_ssam_match[] = {
  7649. + { SSAM_SDEV(BAS, 0x01, 0x00, 0x00) },
  7650. + { },
  7651. +};
  7652. +MODULE_DEVICE_TABLE(ssam, surface_dtx_ssam_match);
  7653. +
  7654. +static struct ssam_device_driver surface_dtx_ssam_driver = {
  7655. + .probe = surface_dtx_ssam_probe,
  7656. + .remove = surface_dtx_ssam_remove,
  7657. + .match_table = surface_dtx_ssam_match,
  7658. + .driver = {
  7659. + .name = "surface_dtx",
  7660. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  7661. + },
  7662. +};
  7663. +
  7664. +static int ssam_dtx_driver_register(void)
  7665. +{
  7666. + return ssam_device_driver_register(&surface_dtx_ssam_driver);
  7667. +}
  7668. +
  7669. +static void ssam_dtx_driver_unregister(void)
  7670. +{
  7671. + ssam_device_driver_unregister(&surface_dtx_ssam_driver);
  7672. +}
  7673. +
  7674. +#else /* CONFIG_SURFACE_AGGREGATOR_BUS */
  7675. +
  7676. +static int ssam_dtx_driver_register(void)
  7677. +{
  7678. + return 0;
  7679. +}
  7680. +
  7681. +static void ssam_dtx_driver_unregister(void)
  7682. +{
  7683. +}
  7684. +
  7685. +#endif /* CONFIG_SURFACE_AGGREGATOR_BUS */
  7686. +
  7687. +
  7688. +/* -- Module setup. --------------------------------------------------------- */
  7689. +
  7690. +static int __init surface_dtx_init(void)
  7691. +{
  7692. + int status;
  7693. +
  7694. + status = ssam_dtx_driver_register();
  7695. + if (status)
  7696. + return status;
  7697. +
  7698. + status = platform_driver_register(&surface_dtx_platform_driver);
  7699. + if (status)
  7700. + ssam_dtx_driver_unregister();
  7701. +
  7702. + return status;
  7703. +}
  7704. +module_init(surface_dtx_init);
  7705. +
  7706. +static void __exit surface_dtx_exit(void)
  7707. +{
  7708. + platform_driver_unregister(&surface_dtx_platform_driver);
  7709. + ssam_dtx_driver_unregister();
  7710. +}
  7711. +module_exit(surface_dtx_exit);
  7712. +
  7713. +MODULE_AUTHOR("Maximilian Luz <luzmaximilian@gmail.com>");
  7714. +MODULE_DESCRIPTION("Detachment-system driver for Surface System Aggregator Module");
  7715. +MODULE_LICENSE("GPL");
  7716. diff --git a/drivers/misc/surface_aggregator/clients/surface_hid.c b/drivers/misc/surface_aggregator/clients/surface_hid.c
  7717. new file mode 100644
  7718. index 000000000000..7d0362ae31d4
  7719. --- /dev/null
  7720. +++ b/drivers/misc/surface_aggregator/clients/surface_hid.c
  7721. @@ -0,0 +1,924 @@
  7722. +// SPDX-License-Identifier: GPL-2.0+
  7723. +/*
  7724. + * Surface System Aggregator Module (SSAM) HID device driver.
  7725. + *
  7726. + * Provides support for HID input devices connected via the Surface System
  7727. + * Aggregator Module.
  7728. + *
  7729. + * Copyright (C) 2019-2020 Blaž Hrastnik <blaz@mxxn.io>,
  7730. + * Maximilian Luz <luzmaximilian@gmail.com>
  7731. + */
  7732. +
  7733. +#include <asm/unaligned.h>
  7734. +#include <linux/acpi.h>
  7735. +#include <linux/hid.h>
  7736. +#include <linux/input.h>
  7737. +#include <linux/kernel.h>
  7738. +#include <linux/module.h>
  7739. +#include <linux/platform_device.h>
  7740. +#include <linux/types.h>
  7741. +#include <linux/usb/ch9.h>
  7742. +
  7743. +#include <linux/surface_aggregator/controller.h>
  7744. +#include <linux/surface_aggregator/device.h>
  7745. +
  7746. +enum surface_hid_descriptor_entry {
  7747. + SURFACE_HID_DESC_HID = 0,
  7748. + SURFACE_HID_DESC_REPORT = 1,
  7749. + SURFACE_HID_DESC_ATTRS = 2,
  7750. +};
  7751. +
  7752. +struct surface_hid_descriptor {
  7753. + __u8 desc_len; /* = 9 */
  7754. + __u8 desc_type; /* = HID_DT_HID */
  7755. + __le16 hid_version;
  7756. + __u8 country_code;
  7757. + __u8 num_descriptors; /* = 1 */
  7758. +
  7759. + __u8 report_desc_type; /* = HID_DT_REPORT */
  7760. + __le16 report_desc_len;
  7761. +} __packed;
  7762. +
  7763. +static_assert(sizeof(struct surface_hid_descriptor) == 9);
  7764. +
  7765. +struct surface_hid_attributes {
  7766. + __le32 length;
  7767. + __le16 vendor;
  7768. + __le16 product;
  7769. + __le16 version;
  7770. + __u8 _unknown[22];
  7771. +} __packed;
  7772. +
  7773. +static_assert(sizeof(struct surface_hid_attributes) == 32);
  7774. +
  7775. +struct surface_hid_device;
  7776. +
  7777. +struct surface_hid_device_ops {
  7778. + int (*get_descriptor)(struct surface_hid_device *shid, u8 entry,
  7779. + u8 *buf, size_t len);
  7780. + int (*output_report)(struct surface_hid_device *shid, u8 report_id,
  7781. + u8 *data, size_t len);
  7782. + int (*get_feature_report)(struct surface_hid_device *shid, u8 report_id,
  7783. + u8 *data, size_t len);
  7784. + int (*set_feature_report)(struct surface_hid_device *shid, u8 report_id,
  7785. + u8 *data, size_t len);
  7786. +};
  7787. +
  7788. +struct surface_hid_device {
  7789. + struct device *dev;
  7790. + struct ssam_controller *ctrl;
  7791. + struct ssam_device_uid uid;
  7792. +
  7793. + struct surface_hid_descriptor hid_desc;
  7794. + struct surface_hid_attributes attrs;
  7795. +
  7796. + struct ssam_event_notifier notif;
  7797. + struct hid_device *hid;
  7798. +
  7799. + struct surface_hid_device_ops ops;
  7800. +};
  7801. +
  7802. +
  7803. +/* -- SAM interface (HID). -------------------------------------------------- */
  7804. +
  7805. +#ifdef CONFIG_SURFACE_AGGREGATOR_BUS
  7806. +
  7807. +struct surface_hid_buffer_slice {
  7808. + __u8 entry;
  7809. + __le32 offset;
  7810. + __le32 length;
  7811. + __u8 end;
  7812. + __u8 data[];
  7813. +} __packed;
  7814. +
  7815. +static_assert(sizeof(struct surface_hid_buffer_slice) == 10);
  7816. +
  7817. +enum surface_hid_cid {
  7818. + SURFACE_HID_CID_OUTPUT_REPORT = 0x01,
  7819. + SURFACE_HID_CID_GET_FEATURE_REPORT = 0x02,
  7820. + SURFACE_HID_CID_SET_FEATURE_REPORT = 0x03,
  7821. + SURFACE_HID_CID_GET_DESCRIPTOR = 0x04,
  7822. +};
  7823. +
  7824. +static int ssam_hid_get_descriptor(struct surface_hid_device *shid, u8 entry,
  7825. + u8 *buf, size_t len)
  7826. +{
  7827. + u8 buffer[sizeof(struct surface_hid_buffer_slice) + 0x76];
  7828. + struct surface_hid_buffer_slice *slice;
  7829. + struct ssam_request rqst;
  7830. + struct ssam_response rsp;
  7831. + u32 buffer_len, offset, length;
  7832. + int status;
  7833. +
  7834. + /*
  7835. + * Note: The 0x76 above has been chosen because that's what's used by
  7836. + * the Windows driver. Together with the header, this leads to a 128
  7837. + * byte payload in total.
  7838. + */
  7839. +
  7840. + buffer_len = ARRAY_SIZE(buffer) - sizeof(struct surface_hid_buffer_slice);
  7841. +
  7842. + rqst.target_category = shid->uid.category;
  7843. + rqst.target_id = shid->uid.target;
  7844. + rqst.command_id = SURFACE_HID_CID_GET_DESCRIPTOR;
  7845. + rqst.instance_id = shid->uid.instance;
  7846. + rqst.flags = SSAM_REQUEST_HAS_RESPONSE;
  7847. + rqst.length = sizeof(struct surface_hid_buffer_slice);
  7848. + rqst.payload = buffer;
  7849. +
  7850. + rsp.capacity = ARRAY_SIZE(buffer);
  7851. + rsp.pointer = buffer;
  7852. +
  7853. + slice = (struct surface_hid_buffer_slice *)buffer;
  7854. + slice->entry = entry;
  7855. + slice->end = 0;
  7856. +
  7857. + offset = 0;
  7858. + length = buffer_len;
  7859. +
  7860. + while (!slice->end && offset < len) {
  7861. + put_unaligned_le32(offset, &slice->offset);
  7862. + put_unaligned_le32(length, &slice->length);
  7863. +
  7864. + rsp.length = 0;
  7865. +
  7866. + status = ssam_retry(ssam_request_sync_onstack, shid->ctrl,
  7867. + &rqst, &rsp, sizeof(*slice));
  7868. + if (status)
  7869. + return status;
  7870. +
  7871. + offset = get_unaligned_le32(&slice->offset);
  7872. + length = get_unaligned_le32(&slice->length);
  7873. +
  7874. + /* Don't mess stuff up in case we receive garbage. */
  7875. + if (length > buffer_len || offset > len)
  7876. + return -EPROTO;
  7877. +
  7878. + if (offset + length > len)
  7879. + length = len - offset;
  7880. +
  7881. + memcpy(buf + offset, &slice->data[0], length);
  7882. +
  7883. + offset += length;
  7884. + length = buffer_len;
  7885. + }
  7886. +
  7887. + if (offset != len) {
  7888. + dev_err(shid->dev,
  7889. + "unexpected descriptor length: got %u, expected %zu\n",
  7890. + offset, len);
  7891. + return -EPROTO;
  7892. + }
  7893. +
  7894. + return 0;
  7895. +}
  7896. +
  7897. +static int ssam_hid_set_raw_report(struct surface_hid_device *shid,
  7898. + u8 report_id, bool feature, u8 *buf,
  7899. + size_t len)
  7900. +{
  7901. + struct ssam_request rqst;
  7902. + u8 cid;
  7903. +
  7904. + if (feature)
  7905. + cid = SURFACE_HID_CID_SET_FEATURE_REPORT;
  7906. + else
  7907. + cid = SURFACE_HID_CID_OUTPUT_REPORT;
  7908. +
  7909. + rqst.target_category = shid->uid.category;
  7910. + rqst.target_id = shid->uid.target;
  7911. + rqst.instance_id = shid->uid.instance;
  7912. + rqst.command_id = cid;
  7913. + rqst.flags = 0;
  7914. + rqst.length = len;
  7915. + rqst.payload = buf;
  7916. +
  7917. + buf[0] = report_id;
  7918. +
  7919. + return ssam_retry(ssam_request_sync, shid->ctrl, &rqst, NULL);
  7920. +}
  7921. +
  7922. +static int ssam_hid_get_raw_report(struct surface_hid_device *shid,
  7923. + u8 report_id, u8 *buf, size_t len)
  7924. +{
  7925. + struct ssam_request rqst;
  7926. + struct ssam_response rsp;
  7927. +
  7928. + rqst.target_category = shid->uid.category;
  7929. + rqst.target_id = shid->uid.target;
  7930. + rqst.instance_id = shid->uid.instance;
  7931. + rqst.command_id = SURFACE_HID_CID_GET_FEATURE_REPORT;
  7932. + rqst.flags = 0;
  7933. + rqst.length = sizeof(report_id);
  7934. + rqst.payload = &report_id;
  7935. +
  7936. + rsp.capacity = len;
  7937. + rsp.length = 0;
  7938. + rsp.pointer = buf;
  7939. +
  7940. + return ssam_retry(ssam_request_sync_onstack, shid->ctrl, &rqst, &rsp,
  7941. + sizeof(report_id));
  7942. +}
  7943. +
  7944. +static u32 ssam_hid_event_fn(struct ssam_event_notifier *nf,
  7945. + const struct ssam_event *event)
  7946. +{
  7947. + struct surface_hid_device *shid;
  7948. + int status;
  7949. +
  7950. + shid = container_of(nf, struct surface_hid_device, notif);
  7951. +
  7952. + if (event->command_id != 0x00)
  7953. + return 0;
  7954. +
  7955. + status = hid_input_report(shid->hid, HID_INPUT_REPORT,
  7956. + (u8 *)&event->data[0], event->length, 0);
  7957. +
  7958. + return ssam_notifier_from_errno(status) | SSAM_NOTIF_HANDLED;
  7959. +}
  7960. +
  7961. +
  7962. +/* -- Transport driver (HID). ----------------------------------------------- */
  7963. +
  7964. +static int shid_output_report(struct surface_hid_device *shid, u8 report_id,
  7965. + u8 *data, size_t len)
  7966. +{
  7967. + int status;
  7968. +
  7969. + status = ssam_hid_set_raw_report(shid, report_id, false, data, len);
  7970. + return status >= 0 ? len : status;
  7971. +}
  7972. +
  7973. +static int shid_get_feature_report(struct surface_hid_device *shid,
  7974. + u8 report_id, u8 *data, size_t len)
  7975. +{
  7976. + int status;
  7977. +
  7978. + status = ssam_hid_get_raw_report(shid, report_id, data, len);
  7979. + return status >= 0 ? len : status;
  7980. +}
  7981. +
  7982. +static int shid_set_feature_report(struct surface_hid_device *shid,
  7983. + u8 report_id, u8 *data, size_t len)
  7984. +{
  7985. + int status;
  7986. +
  7987. + status = ssam_hid_set_raw_report(shid, report_id, true, data, len);
  7988. + return status >= 0 ? len : status;
  7989. +}
  7990. +
  7991. +#endif /* CONFIG_SURFACE_AGGREGATOR_BUS */
  7992. +
  7993. +
  7994. +/* -- SAM interface (KBD). -------------------------------------------------- */
  7995. +
  7996. +#define KBD_FEATURE_REPORT_SIZE 7 /* 6 + report ID */
  7997. +
  7998. +enum surface_kbd_cid {
  7999. + SURFACE_KBD_CID_GET_DESCRIPTOR = 0x00,
  8000. + SURFACE_KBD_CID_SET_CAPSLOCK_LED = 0x01,
  8001. + SURFACE_KBD_CID_EVT_INPUT_GENERIC = 0x03,
  8002. + SURFACE_KBD_CID_EVT_INPUT_HOTKEYS = 0x04,
  8003. + SURFACE_KBD_CID_GET_FEATURE_REPORT = 0x0b,
  8004. +};
  8005. +
  8006. +static int ssam_kbd_get_descriptor(struct surface_hid_device *shid, u8 entry,
  8007. + u8 *buf, size_t len)
  8008. +{
  8009. + struct ssam_request rqst;
  8010. + struct ssam_response rsp;
  8011. + int status;
  8012. +
  8013. + rqst.target_category = shid->uid.category;
  8014. + rqst.target_id = shid->uid.target;
  8015. + rqst.command_id = SURFACE_KBD_CID_GET_DESCRIPTOR;
  8016. + rqst.instance_id = shid->uid.instance;
  8017. + rqst.flags = SSAM_REQUEST_HAS_RESPONSE;
  8018. + rqst.length = sizeof(entry);
  8019. + rqst.payload = &entry;
  8020. +
  8021. + rsp.capacity = len;
  8022. + rsp.length = 0;
  8023. + rsp.pointer = buf;
  8024. +
  8025. + status = ssam_retry(ssam_request_sync_onstack, shid->ctrl, &rqst, &rsp,
  8026. + sizeof(entry));
  8027. + if (status)
  8028. + return status;
  8029. +
  8030. + if (rsp.length != len) {
  8031. + dev_err(shid->dev,
  8032. + "invalid descriptor length: got %zu, expected, %zu\n",
  8033. + rsp.length, len);
  8034. + return -EPROTO;
  8035. + }
  8036. +
  8037. + return 0;
  8038. +}
  8039. +
  8040. +static int ssam_kbd_set_caps_led(struct surface_hid_device *shid, bool value)
  8041. +{
  8042. + struct ssam_request rqst;
  8043. + u8 value_u8 = value;
  8044. +
  8045. + rqst.target_category = shid->uid.category;
  8046. + rqst.target_id = shid->uid.target;
  8047. + rqst.command_id = SURFACE_KBD_CID_SET_CAPSLOCK_LED;
  8048. + rqst.instance_id = shid->uid.instance;
  8049. + rqst.flags = 0;
  8050. + rqst.length = sizeof(value_u8);
  8051. + rqst.payload = &value_u8;
  8052. +
  8053. + return ssam_retry(ssam_request_sync_onstack, shid->ctrl, &rqst, NULL,
  8054. + sizeof(value_u8));
  8055. +}
  8056. +
  8057. +static int ssam_kbd_get_feature_report(struct surface_hid_device *shid, u8 *buf,
  8058. + size_t len)
  8059. +{
  8060. + struct ssam_request rqst;
  8061. + struct ssam_response rsp;
  8062. + u8 payload = 0;
  8063. + int status;
  8064. +
  8065. + rqst.target_category = shid->uid.category;
  8066. + rqst.target_id = shid->uid.target;
  8067. + rqst.command_id = SURFACE_KBD_CID_GET_FEATURE_REPORT;
  8068. + rqst.instance_id = shid->uid.instance;
  8069. + rqst.flags = SSAM_REQUEST_HAS_RESPONSE;
  8070. + rqst.length = sizeof(payload);
  8071. + rqst.payload = &payload;
  8072. +
  8073. + rsp.capacity = len;
  8074. + rsp.length = 0;
  8075. + rsp.pointer = buf;
  8076. +
  8077. + status = ssam_retry(ssam_request_sync_onstack, shid->ctrl, &rqst, &rsp,
  8078. + sizeof(payload));
  8079. + if (status)
  8080. + return status;
  8081. +
  8082. + if (rsp.length != len) {
  8083. + dev_err(shid->dev,
  8084. + "invalid feature report length: got %zu, expected, %zu\n",
  8085. + rsp.length, len);
  8086. + return -EPROTO;
  8087. + }
  8088. +
  8089. + return 0;
  8090. +}
  8091. +
  8092. +static bool ssam_kbd_is_input_event(const struct ssam_event *event)
  8093. +{
  8094. + if (event->command_id == SURFACE_KBD_CID_EVT_INPUT_GENERIC)
  8095. + return true;
  8096. +
  8097. + if (event->command_id == SURFACE_KBD_CID_EVT_INPUT_HOTKEYS)
  8098. + return true;
  8099. +
  8100. + return false;
  8101. +}
  8102. +
  8103. +static u32 ssam_kbd_event_fn(struct ssam_event_notifier *nf,
  8104. + const struct ssam_event *event)
  8105. +{
  8106. + struct surface_hid_device *shid;
  8107. + int status;
  8108. +
  8109. + shid = container_of(nf, struct surface_hid_device, notif);
  8110. +
  8111. + /*
  8112. + * Check against device UID manually, as registry and device target
  8113. + * category doesn't line up.
  8114. + */
  8115. +
  8116. + if (shid->uid.category != event->target_category)
  8117. + return 0;
  8118. +
  8119. + if (shid->uid.target != event->target_id)
  8120. + return 0;
  8121. +
  8122. + if (shid->uid.instance != event->instance_id)
  8123. + return 0;
  8124. +
  8125. + if (!ssam_kbd_is_input_event(event))
  8126. + return 0;
  8127. +
  8128. + status = hid_input_report(shid->hid, HID_INPUT_REPORT,
  8129. + (u8 *)&event->data[0], event->length, 0);
  8130. +
  8131. + return ssam_notifier_from_errno(status) | SSAM_NOTIF_HANDLED;
  8132. +}
  8133. +
  8134. +
  8135. +/* -- Transport driver (KBD). ----------------------------------------------- */
  8136. +
  8137. +static int skbd_get_caps_led_value(struct hid_device *hid, u8 report_id,
  8138. + u8 *data, size_t len)
  8139. +{
  8140. + struct hid_field *field;
  8141. + unsigned int offset, size;
  8142. + int i;
  8143. +
  8144. + /* Get led field. */
  8145. + field = hidinput_get_led_field(hid);
  8146. + if (!field)
  8147. + return -ENOENT;
  8148. +
  8149. + /* Check if we got the correct report. */
  8150. + if (len != hid_report_len(field->report))
  8151. + return -ENOENT;
  8152. +
  8153. + if (report_id != field->report->id)
  8154. + return -ENOENT;
  8155. +
  8156. + /* Get caps lock led index. */
  8157. + for (i = 0; i < field->report_count; i++)
  8158. + if ((field->usage[i].hid & 0xffff) == 0x02)
  8159. + break;
  8160. +
  8161. + if (i == field->report_count)
  8162. + return -ENOENT;
  8163. +
  8164. + /* Extract value. */
  8165. + size = field->report_size;
  8166. + offset = field->report_offset + i * size;
  8167. + return !!hid_field_extract(hid, data + 1, size, offset);
  8168. +}
  8169. +
  8170. +static int skbd_output_report(struct surface_hid_device *shid, u8 report_id,
  8171. + u8 *data, size_t len)
  8172. +{
  8173. + int caps_led;
  8174. + int status;
  8175. +
  8176. + caps_led = skbd_get_caps_led_value(shid->hid, report_id, data, len);
  8177. + if (caps_led < 0)
  8178. + return -EIO; /* Only caps output reports are supported. */
  8179. +
  8180. + status = ssam_kbd_set_caps_led(shid, caps_led);
  8181. + if (status < 0)
  8182. + return status;
  8183. +
  8184. + return len;
  8185. +}
  8186. +
  8187. +static int skbd_get_feature_report(struct surface_hid_device *shid,
  8188. + u8 report_id, u8 *data, size_t len)
  8189. +{
  8190. + u8 report[KBD_FEATURE_REPORT_SIZE];
  8191. + int status;
  8192. +
  8193. + /*
  8194. + * The keyboard only has a single hard-coded read-only feature report
  8195. + * of size KBD_FEATURE_REPORT_SIZE. Try to load it and compare its
  8196. + * report ID against the requested one.
  8197. + */
  8198. +
  8199. + if (len < ARRAY_SIZE(report))
  8200. + return -ENOSPC;
  8201. +
  8202. + status = ssam_kbd_get_feature_report(shid, report, ARRAY_SIZE(report));
  8203. + if (status < 0)
  8204. + return status;
  8205. +
  8206. + if (report_id != report[0])
  8207. + return -ENOENT;
  8208. +
  8209. + memcpy(data, report, ARRAY_SIZE(report));
  8210. + return len;
  8211. +}
  8212. +
  8213. +static int skbd_set_feature_report(struct surface_hid_device *shid,
  8214. + u8 report_id, u8 *data, size_t len)
  8215. +{
  8216. + return -EIO;
  8217. +}
  8218. +
  8219. +
  8220. +/* -- Device descriptor access. --------------------------------------------- */
  8221. +
  8222. +static int surface_hid_load_hid_descriptor(struct surface_hid_device *shid)
  8223. +{
  8224. + int status;
  8225. +
  8226. + status = shid->ops.get_descriptor(shid, SURFACE_HID_DESC_HID,
  8227. + (u8 *)&shid->hid_desc, sizeof(shid->hid_desc));
  8228. + if (status)
  8229. + return status;
  8230. +
  8231. + if (shid->hid_desc.desc_len != sizeof(shid->hid_desc)) {
  8232. + dev_err(shid->dev,
  8233. + "unexpected HID descriptor length: got %u, expected %zu\n",
  8234. + shid->hid_desc.desc_len, sizeof(shid->hid_desc));
  8235. + return -EPROTO;
  8236. + }
  8237. +
  8238. + if (shid->hid_desc.desc_type != HID_DT_HID) {
  8239. + dev_err(shid->dev,
  8240. + "unexpected HID descriptor type: got %#04x, expected %#04x\n",
  8241. + shid->hid_desc.desc_type, HID_DT_HID);
  8242. + return -EPROTO;
  8243. + }
  8244. +
  8245. + if (shid->hid_desc.num_descriptors != 1) {
  8246. + dev_err(shid->dev,
  8247. + "unexpected number of descriptors: got %u, expected 1\n",
  8248. + shid->hid_desc.num_descriptors);
  8249. + return -EPROTO;
  8250. + }
  8251. +
  8252. + if (shid->hid_desc.report_desc_type != HID_DT_REPORT) {
  8253. + dev_err(shid->dev,
  8254. + "unexpected report descriptor type: got %#04x, expected %#04x\n",
  8255. + shid->hid_desc.report_desc_type, HID_DT_REPORT);
  8256. + return -EPROTO;
  8257. + }
  8258. +
  8259. + return 0;
  8260. +}
  8261. +
  8262. +static int surface_hid_load_device_attributes(struct surface_hid_device *shid)
  8263. +{
  8264. + int status;
  8265. +
  8266. + status = shid->ops.get_descriptor(shid, SURFACE_HID_DESC_ATTRS,
  8267. + (u8 *)&shid->attrs, sizeof(shid->attrs));
  8268. + if (status)
  8269. + return status;
  8270. +
  8271. + if (get_unaligned_le32(&shid->attrs.length) != sizeof(shid->attrs)) {
  8272. + dev_err(shid->dev,
  8273. + "unexpected attribute length: got %u, expected %zu\n",
  8274. + get_unaligned_le32(&shid->attrs.length), sizeof(shid->attrs));
  8275. + return -EPROTO;
  8276. + }
  8277. +
  8278. + return 0;
  8279. +}
  8280. +
  8281. +
  8282. +/* -- Transport driver (common). -------------------------------------------- */
  8283. +
  8284. +static int surface_hid_start(struct hid_device *hid)
  8285. +{
  8286. + struct surface_hid_device *shid = hid->driver_data;
  8287. +
  8288. + return ssam_notifier_register(shid->ctrl, &shid->notif);
  8289. +}
  8290. +
  8291. +static void surface_hid_stop(struct hid_device *hid)
  8292. +{
  8293. + struct surface_hid_device *shid = hid->driver_data;
  8294. +
  8295. + /* Note: This call will log errors for us, so ignore them here. */
  8296. + ssam_notifier_unregister(shid->ctrl, &shid->notif);
  8297. +}
  8298. +
  8299. +static int surface_hid_open(struct hid_device *hid)
  8300. +{
  8301. + return 0;
  8302. +}
  8303. +
  8304. +static void surface_hid_close(struct hid_device *hid)
  8305. +{
  8306. +}
  8307. +
  8308. +static int surface_hid_parse(struct hid_device *hid)
  8309. +{
  8310. + struct surface_hid_device *shid = hid->driver_data;
  8311. + size_t len = get_unaligned_le16(&shid->hid_desc.report_desc_len);
  8312. + u8 *buf;
  8313. + int status;
  8314. +
  8315. + buf = kzalloc(len, GFP_KERNEL);
  8316. + if (!buf)
  8317. + return -ENOMEM;
  8318. +
  8319. + status = shid->ops.get_descriptor(shid, SURFACE_HID_DESC_REPORT, buf, len);
  8320. + if (!status)
  8321. + status = hid_parse_report(hid, buf, len);
  8322. +
  8323. + kfree(buf);
  8324. + return status;
  8325. +}
  8326. +
  8327. +static int surface_hid_raw_request(struct hid_device *hid, unsigned char reportnum,
  8328. + u8 *buf, size_t len, unsigned char rtype,
  8329. + int reqtype)
  8330. +{
  8331. + struct surface_hid_device *shid = hid->driver_data;
  8332. +
  8333. + if (rtype == HID_OUTPUT_REPORT && reqtype == HID_REQ_SET_REPORT)
  8334. + return shid->ops.output_report(shid, reportnum, buf, len);
  8335. +
  8336. + else if (rtype == HID_FEATURE_REPORT && reqtype == HID_REQ_GET_REPORT)
  8337. + return shid->ops.get_feature_report(shid, reportnum, buf, len);
  8338. +
  8339. + else if (rtype == HID_FEATURE_REPORT && reqtype == HID_REQ_SET_REPORT)
  8340. + return shid->ops.set_feature_report(shid, reportnum, buf, len);
  8341. +
  8342. + return -EIO;
  8343. +}
  8344. +
  8345. +static struct hid_ll_driver surface_hid_ll_driver = {
  8346. + .start = surface_hid_start,
  8347. + .stop = surface_hid_stop,
  8348. + .open = surface_hid_open,
  8349. + .close = surface_hid_close,
  8350. + .parse = surface_hid_parse,
  8351. + .raw_request = surface_hid_raw_request,
  8352. +};
  8353. +
  8354. +
  8355. +/* -- Common device setup. -------------------------------------------------- */
  8356. +
  8357. +static int surface_hid_device_add(struct surface_hid_device *shid)
  8358. +{
  8359. + int status;
  8360. +
  8361. + status = surface_hid_load_hid_descriptor(shid);
  8362. + if (status)
  8363. + return status;
  8364. +
  8365. + status = surface_hid_load_device_attributes(shid);
  8366. + if (status)
  8367. + return status;
  8368. +
  8369. + shid->hid = hid_allocate_device();
  8370. + if (IS_ERR(shid->hid))
  8371. + return PTR_ERR(shid->hid);
  8372. +
  8373. + shid->hid->dev.parent = shid->dev;
  8374. + shid->hid->bus = BUS_HOST; // TODO: BUS_SURFACE
  8375. + shid->hid->vendor = cpu_to_le16(shid->attrs.vendor);
  8376. + shid->hid->product = cpu_to_le16(shid->attrs.product);
  8377. + shid->hid->version = cpu_to_le16(shid->hid_desc.hid_version);
  8378. + shid->hid->country = shid->hid_desc.country_code;
  8379. +
  8380. + snprintf(shid->hid->name, sizeof(shid->hid->name),
  8381. + "Microsoft Surface %04X:%04X",
  8382. + shid->hid->vendor, shid->hid->product);
  8383. +
  8384. + strlcpy(shid->hid->phys, dev_name(shid->dev), sizeof(shid->hid->phys));
  8385. +
  8386. + shid->hid->driver_data = shid;
  8387. + shid->hid->ll_driver = &surface_hid_ll_driver;
  8388. +
  8389. + status = hid_add_device(shid->hid);
  8390. + if (status)
  8391. + hid_destroy_device(shid->hid);
  8392. +
  8393. + return status;
  8394. +}
  8395. +
  8396. +static void surface_hid_device_destroy(struct surface_hid_device *shid)
  8397. +{
  8398. + hid_destroy_device(shid->hid);
  8399. +}
  8400. +
  8401. +
  8402. +/* -- PM ops. --------------------------------------------------------------- */
  8403. +
  8404. +#ifdef CONFIG_PM_SLEEP
  8405. +
  8406. +static int surface_hid_suspend(struct device *dev)
  8407. +{
  8408. + struct surface_hid_device *d = dev_get_drvdata(dev);
  8409. +
  8410. + if (d->hid->driver && d->hid->driver->suspend)
  8411. + return d->hid->driver->suspend(d->hid, PMSG_SUSPEND);
  8412. +
  8413. + return 0;
  8414. +}
  8415. +
  8416. +static int surface_hid_resume(struct device *dev)
  8417. +{
  8418. + struct surface_hid_device *d = dev_get_drvdata(dev);
  8419. +
  8420. + if (d->hid->driver && d->hid->driver->resume)
  8421. + return d->hid->driver->resume(d->hid);
  8422. +
  8423. + return 0;
  8424. +}
  8425. +
  8426. +static int surface_hid_freeze(struct device *dev)
  8427. +{
  8428. + struct surface_hid_device *d = dev_get_drvdata(dev);
  8429. +
  8430. + if (d->hid->driver && d->hid->driver->suspend)
  8431. + return d->hid->driver->suspend(d->hid, PMSG_FREEZE);
  8432. +
  8433. + return 0;
  8434. +}
  8435. +
  8436. +static int surface_hid_poweroff(struct device *dev)
  8437. +{
  8438. + struct surface_hid_device *d = dev_get_drvdata(dev);
  8439. +
  8440. + if (d->hid->driver && d->hid->driver->suspend)
  8441. + return d->hid->driver->suspend(d->hid, PMSG_HIBERNATE);
  8442. +
  8443. + return 0;
  8444. +}
  8445. +
  8446. +static int surface_hid_restore(struct device *dev)
  8447. +{
  8448. + struct surface_hid_device *d = dev_get_drvdata(dev);
  8449. +
  8450. + if (d->hid->driver && d->hid->driver->reset_resume)
  8451. + return d->hid->driver->reset_resume(d->hid);
  8452. +
  8453. + return 0;
  8454. +}
  8455. +
  8456. +const struct dev_pm_ops surface_hid_pm_ops = {
  8457. + .freeze = surface_hid_freeze,
  8458. + .thaw = surface_hid_resume,
  8459. + .suspend = surface_hid_suspend,
  8460. + .resume = surface_hid_resume,
  8461. + .poweroff = surface_hid_poweroff,
  8462. + .restore = surface_hid_restore,
  8463. +};
  8464. +
  8465. +#else /* CONFIG_PM_SLEEP */
  8466. +
  8467. +const struct dev_pm_ops surface_hid_pm_ops = { };
  8468. +
  8469. +#endif /* CONFIG_PM_SLEEP */
  8470. +
  8471. +
  8472. +/* -- Driver setup (HID). --------------------------------------------------- */
  8473. +
  8474. +#ifdef CONFIG_SURFACE_AGGREGATOR_BUS
  8475. +
  8476. +static int surface_hid_probe(struct ssam_device *sdev)
  8477. +{
  8478. + struct surface_hid_device *shid;
  8479. +
  8480. + shid = devm_kzalloc(&sdev->dev, sizeof(*shid), GFP_KERNEL);
  8481. + if (!shid)
  8482. + return -ENOMEM;
  8483. +
  8484. + shid->dev = &sdev->dev;
  8485. + shid->ctrl = sdev->ctrl;
  8486. + shid->uid = sdev->uid;
  8487. +
  8488. + shid->notif.base.priority = 1;
  8489. + shid->notif.base.fn = ssam_hid_event_fn;
  8490. + shid->notif.event.reg = SSAM_EVENT_REGISTRY_REG;
  8491. + shid->notif.event.id.target_category = sdev->uid.category;
  8492. + shid->notif.event.id.instance = sdev->uid.instance;
  8493. + shid->notif.event.mask = SSAM_EVENT_MASK_STRICT;
  8494. + shid->notif.event.flags = 0;
  8495. +
  8496. + shid->ops.get_descriptor = ssam_hid_get_descriptor;
  8497. + shid->ops.output_report = shid_output_report;
  8498. + shid->ops.get_feature_report = shid_get_feature_report;
  8499. + shid->ops.set_feature_report = shid_set_feature_report;
  8500. +
  8501. + ssam_device_set_drvdata(sdev, shid);
  8502. + return surface_hid_device_add(shid);
  8503. +}
  8504. +
  8505. +static void surface_hid_remove(struct ssam_device *sdev)
  8506. +{
  8507. + surface_hid_device_destroy(ssam_device_get_drvdata(sdev));
  8508. +}
  8509. +
  8510. +static const struct ssam_device_id surface_hid_match[] = {
  8511. + { SSAM_SDEV(HID, 0x02, SSAM_ANY_IID, 0x00) },
  8512. + { },
  8513. +};
  8514. +MODULE_DEVICE_TABLE(ssam, surface_hid_match);
  8515. +
  8516. +static struct ssam_device_driver surface_hid_driver = {
  8517. + .probe = surface_hid_probe,
  8518. + .remove = surface_hid_remove,
  8519. + .match_table = surface_hid_match,
  8520. + .driver = {
  8521. + .name = "surface_hid",
  8522. + .pm = &surface_hid_pm_ops,
  8523. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  8524. + },
  8525. +};
  8526. +
  8527. +static int surface_hid_driver_register(void)
  8528. +{
  8529. + return ssam_device_driver_register(&surface_hid_driver);
  8530. +}
  8531. +
  8532. +static void surface_hid_driver_unregister(void)
  8533. +{
  8534. + ssam_device_driver_unregister(&surface_hid_driver);
  8535. +}
  8536. +
  8537. +#else /* CONFIG_SURFACE_AGGREGATOR_BUS */
  8538. +
  8539. +static int surface_hid_driver_register(void)
  8540. +{
  8541. + return 0;
  8542. +}
  8543. +
  8544. +static void surface_hid_driver_unregister(void)
  8545. +{
  8546. +}
  8547. +
  8548. +#endif /* CONFIG_SURFACE_AGGREGATOR_BUS */
  8549. +
  8550. +
  8551. +/* -- Driver setup (KBD). --------------------------------------------------- */
  8552. +
  8553. +static int surface_kbd_probe(struct platform_device *pdev)
  8554. +{
  8555. + struct ssam_controller *ctrl;
  8556. + struct surface_hid_device *shid;
  8557. +
  8558. + /* Add device link to EC. */
  8559. + ctrl = ssam_client_bind(&pdev->dev);
  8560. + if (IS_ERR(ctrl))
  8561. + return PTR_ERR(ctrl) == -ENODEV ? -EPROBE_DEFER : PTR_ERR(ctrl);
  8562. +
  8563. + shid = devm_kzalloc(&pdev->dev, sizeof(*shid), GFP_KERNEL);
  8564. + if (!shid)
  8565. + return -ENOMEM;
  8566. +
  8567. + shid->dev = &pdev->dev;
  8568. + shid->ctrl = ctrl;
  8569. +
  8570. + shid->uid.domain = SSAM_DOMAIN_SERIALHUB;
  8571. + shid->uid.category = SSAM_SSH_TC_KBD;
  8572. + shid->uid.target = 2;
  8573. + shid->uid.instance = 0;
  8574. + shid->uid.function = 0;
  8575. +
  8576. + shid->notif.base.priority = 1;
  8577. + shid->notif.base.fn = ssam_kbd_event_fn;
  8578. + shid->notif.event.reg = SSAM_EVENT_REGISTRY_SAM;
  8579. + shid->notif.event.id.target_category = shid->uid.category;
  8580. + shid->notif.event.id.instance = shid->uid.instance;
  8581. + shid->notif.event.mask = SSAM_EVENT_MASK_NONE;
  8582. + shid->notif.event.flags = 0;
  8583. +
  8584. + shid->ops.get_descriptor = ssam_kbd_get_descriptor;
  8585. + shid->ops.output_report = skbd_output_report;
  8586. + shid->ops.get_feature_report = skbd_get_feature_report;
  8587. + shid->ops.set_feature_report = skbd_set_feature_report;
  8588. +
  8589. + platform_set_drvdata(pdev, shid);
  8590. + return surface_hid_device_add(shid);
  8591. +}
  8592. +
  8593. +static int surface_kbd_remove(struct platform_device *pdev)
  8594. +{
  8595. + surface_hid_device_destroy(platform_get_drvdata(pdev));
  8596. + return 0;
  8597. +}
  8598. +
  8599. +static const struct acpi_device_id surface_kbd_match[] = {
  8600. + { "MSHW0096" },
  8601. + { },
  8602. +};
  8603. +MODULE_DEVICE_TABLE(acpi, surface_kbd_match);
  8604. +
  8605. +static struct platform_driver surface_kbd_driver = {
  8606. + .probe = surface_kbd_probe,
  8607. + .remove = surface_kbd_remove,
  8608. + .driver = {
  8609. + .name = "surface_keyboard",
  8610. + .acpi_match_table = surface_kbd_match,
  8611. + .pm = &surface_hid_pm_ops,
  8612. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  8613. + },
  8614. +};
  8615. +
  8616. +
  8617. +/* -- Module setup. --------------------------------------------------------- */
  8618. +
  8619. +static int __init surface_hid_init(void)
  8620. +{
  8621. + int status;
  8622. +
  8623. + status = surface_hid_driver_register();
  8624. + if (status)
  8625. + return status;
  8626. +
  8627. + status = platform_driver_register(&surface_kbd_driver);
  8628. + if (status)
  8629. + surface_hid_driver_unregister();
  8630. +
  8631. + return status;
  8632. +}
  8633. +module_init(surface_hid_init);
  8634. +
  8635. +static void __exit surface_hid_exit(void)
  8636. +{
  8637. + platform_driver_unregister(&surface_kbd_driver);
  8638. + surface_hid_driver_unregister();
  8639. +}
  8640. +module_exit(surface_hid_exit);
  8641. +
  8642. +MODULE_AUTHOR("Blaž Hrastnik <blaz@mxxn.io>");
  8643. +MODULE_AUTHOR("Maximilian Luz <luzmaximilian@gmail.com>");
  8644. +MODULE_DESCRIPTION("HID transport-/device-driver for Surface System Aggregator Module");
  8645. +MODULE_LICENSE("GPL");
  8646. diff --git a/drivers/misc/surface_aggregator/clients/surface_perfmode.c b/drivers/misc/surface_aggregator/clients/surface_perfmode.c
  8647. new file mode 100644
  8648. index 000000000000..cac7227f27ea
  8649. --- /dev/null
  8650. +++ b/drivers/misc/surface_aggregator/clients/surface_perfmode.c
  8651. @@ -0,0 +1,122 @@
  8652. +// SPDX-License-Identifier: GPL-2.0+
  8653. +/*
  8654. + * Surface performance-mode driver.
  8655. + *
  8656. + * Provides a user-space interface for the performance mode control provided
  8657. + * by the Surface System Aggregator Module (SSAM), influencing cooling
  8658. + * behavior of the device and potentially managing power limits.
  8659. + *
  8660. + * Copyright (C) 2019-2020 Maximilian Luz <luzmaximilian@gmail.com>
  8661. + */
  8662. +
  8663. +#include <asm/unaligned.h>
  8664. +#include <linux/kernel.h>
  8665. +#include <linux/module.h>
  8666. +#include <linux/sysfs.h>
  8667. +#include <linux/types.h>
  8668. +
  8669. +#include <linux/surface_aggregator/device.h>
  8670. +
  8671. +enum sam_perf_mode {
  8672. + SAM_PERF_MODE_NORMAL = 1,
  8673. + SAM_PERF_MODE_BATTERY = 2,
  8674. + SAM_PERF_MODE_PERF1 = 3,
  8675. + SAM_PERF_MODE_PERF2 = 4,
  8676. +
  8677. + __SAM_PERF_MODE__MIN = 1,
  8678. + __SAM_PERF_MODE__MAX = 4,
  8679. +};
  8680. +
  8681. +struct ssam_perf_info {
  8682. + __le32 mode;
  8683. + __le16 unknown1;
  8684. + __le16 unknown2;
  8685. +} __packed;
  8686. +
  8687. +static SSAM_DEFINE_SYNC_REQUEST_CL_R(ssam_tmp_perf_mode_get, struct ssam_perf_info, {
  8688. + .target_category = SSAM_SSH_TC_TMP,
  8689. + .command_id = 0x02,
  8690. +});
  8691. +
  8692. +static SSAM_DEFINE_SYNC_REQUEST_CL_W(__ssam_tmp_perf_mode_set, __le32, {
  8693. + .target_category = SSAM_SSH_TC_TMP,
  8694. + .command_id = 0x03,
  8695. +});
  8696. +
  8697. +static int ssam_tmp_perf_mode_set(struct ssam_device *sdev, u32 mode)
  8698. +{
  8699. + __le32 mode_le = cpu_to_le32(mode);
  8700. +
  8701. + if (mode < __SAM_PERF_MODE__MIN || mode > __SAM_PERF_MODE__MAX)
  8702. + return -EINVAL;
  8703. +
  8704. + return ssam_retry(__ssam_tmp_perf_mode_set, sdev, &mode_le);
  8705. +}
  8706. +
  8707. +static ssize_t perf_mode_show(struct device *dev, struct device_attribute *attr,
  8708. + char *data)
  8709. +{
  8710. + struct ssam_device *sdev = to_ssam_device(dev);
  8711. + struct ssam_perf_info info;
  8712. + int status;
  8713. +
  8714. + status = ssam_retry(ssam_tmp_perf_mode_get, sdev, &info);
  8715. + if (status) {
  8716. + dev_err(dev, "failed to get current performance mode: %d\n",
  8717. + status);
  8718. + return -EIO;
  8719. + }
  8720. +
  8721. + return sprintf(data, "%d\n", le32_to_cpu(info.mode));
  8722. +}
  8723. +
  8724. +static ssize_t perf_mode_store(struct device *dev, struct device_attribute *attr,
  8725. + const char *data, size_t count)
  8726. +{
  8727. + struct ssam_device *sdev = to_ssam_device(dev);
  8728. + int perf_mode;
  8729. + int status;
  8730. +
  8731. + status = kstrtoint(data, 0, &perf_mode);
  8732. + if (status < 0)
  8733. + return status;
  8734. +
  8735. + status = ssam_tmp_perf_mode_set(sdev, perf_mode);
  8736. + if (status < 0)
  8737. + return status;
  8738. +
  8739. + return count;
  8740. +}
  8741. +
  8742. +static const DEVICE_ATTR_RW(perf_mode);
  8743. +
  8744. +static int surface_sam_sid_perfmode_probe(struct ssam_device *sdev)
  8745. +{
  8746. + return sysfs_create_file(&sdev->dev.kobj, &dev_attr_perf_mode.attr);
  8747. +}
  8748. +
  8749. +static void surface_sam_sid_perfmode_remove(struct ssam_device *sdev)
  8750. +{
  8751. + sysfs_remove_file(&sdev->dev.kobj, &dev_attr_perf_mode.attr);
  8752. +}
  8753. +
  8754. +static const struct ssam_device_id ssam_perfmode_match[] = {
  8755. + { SSAM_SDEV(TMP, 0x01, 0x00, 0x01) },
  8756. + { },
  8757. +};
  8758. +MODULE_DEVICE_TABLE(ssam, ssam_perfmode_match);
  8759. +
  8760. +static struct ssam_device_driver surface_sam_sid_perfmode = {
  8761. + .probe = surface_sam_sid_perfmode_probe,
  8762. + .remove = surface_sam_sid_perfmode_remove,
  8763. + .match_table = ssam_perfmode_match,
  8764. + .driver = {
  8765. + .name = "surface_performance_mode",
  8766. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  8767. + },
  8768. +};
  8769. +module_ssam_device_driver(surface_sam_sid_perfmode);
  8770. +
  8771. +MODULE_AUTHOR("Maximilian Luz <luzmaximilian@gmail.com>");
  8772. +MODULE_DESCRIPTION("Performance mode interface for Surface System Aggregator Module");
  8773. +MODULE_LICENSE("GPL");
  8774. diff --git a/drivers/misc/surface_aggregator/controller.c b/drivers/misc/surface_aggregator/controller.c
  8775. new file mode 100644
  8776. index 000000000000..5bcb59ed579d
  8777. --- /dev/null
  8778. +++ b/drivers/misc/surface_aggregator/controller.c
  8779. @@ -0,0 +1,2579 @@
  8780. +// SPDX-License-Identifier: GPL-2.0+
  8781. +/*
  8782. + * Main SSAM/SSH controller structure and functionality.
  8783. + *
  8784. + * Copyright (C) 2019-2020 Maximilian Luz <luzmaximilian@gmail.com>
  8785. + */
  8786. +
  8787. +#include <linux/acpi.h>
  8788. +#include <linux/atomic.h>
  8789. +#include <linux/completion.h>
  8790. +#include <linux/gpio/consumer.h>
  8791. +#include <linux/interrupt.h>
  8792. +#include <linux/kref.h>
  8793. +#include <linux/limits.h>
  8794. +#include <linux/list.h>
  8795. +#include <linux/lockdep.h>
  8796. +#include <linux/mutex.h>
  8797. +#include <linux/rculist.h>
  8798. +#include <linux/rbtree.h>
  8799. +#include <linux/rwsem.h>
  8800. +#include <linux/serdev.h>
  8801. +#include <linux/slab.h>
  8802. +#include <linux/spinlock.h>
  8803. +#include <linux/srcu.h>
  8804. +#include <linux/types.h>
  8805. +#include <linux/workqueue.h>
  8806. +
  8807. +#include <linux/surface_aggregator/controller.h>
  8808. +#include <linux/surface_aggregator/serial_hub.h>
  8809. +
  8810. +#include "controller.h"
  8811. +#include "ssh_msgb.h"
  8812. +#include "ssh_request_layer.h"
  8813. +
  8814. +#include "trace.h"
  8815. +
  8816. +
  8817. +/* -- Safe counters. -------------------------------------------------------- */
  8818. +
  8819. +/**
  8820. + * ssh_seq_reset() - Reset/initialize sequence ID counter.
  8821. + * @c: The counter to reset.
  8822. + */
  8823. +static void ssh_seq_reset(struct ssh_seq_counter *c)
  8824. +{
  8825. + WRITE_ONCE(c->value, 0);
  8826. +}
  8827. +
  8828. +/**
  8829. + * ssh_seq_next() - Get next sequence ID.
  8830. + * @c: The counter providing the sequence IDs.
  8831. + *
  8832. + * Return: Returns the next sequence ID of the counter.
  8833. + */
  8834. +static u8 ssh_seq_next(struct ssh_seq_counter *c)
  8835. +{
  8836. + u8 old = READ_ONCE(c->value);
  8837. + u8 new = old + 1;
  8838. + u8 ret;
  8839. +
  8840. + while (unlikely((ret = cmpxchg(&c->value, old, new)) != old)) {
  8841. + old = ret;
  8842. + new = old + 1;
  8843. + }
  8844. +
  8845. + return old;
  8846. +}
  8847. +
  8848. +/**
  8849. + * ssh_rqid_reset() - Reset/initialize request ID counter.
  8850. + * @c: The counter to reset.
  8851. + */
  8852. +static void ssh_rqid_reset(struct ssh_rqid_counter *c)
  8853. +{
  8854. + WRITE_ONCE(c->value, 0);
  8855. +}
  8856. +
  8857. +/**
  8858. + * ssh_rqid_next() - Get next request ID.
  8859. + * @c: The counter providing the request IDs.
  8860. + *
  8861. + * Return: Returns the next request ID of the counter, skipping any reserved
  8862. + * request IDs.
  8863. + */
  8864. +static u16 ssh_rqid_next(struct ssh_rqid_counter *c)
  8865. +{
  8866. + u16 old = READ_ONCE(c->value);
  8867. + u16 new = ssh_rqid_next_valid(old);
  8868. + u16 ret;
  8869. +
  8870. + while (unlikely((ret = cmpxchg(&c->value, old, new)) != old)) {
  8871. + old = ret;
  8872. + new = ssh_rqid_next_valid(old);
  8873. + }
  8874. +
  8875. + return old;
  8876. +}
  8877. +
  8878. +
  8879. +/* -- Event notifier/callbacks. --------------------------------------------- */
  8880. +/*
  8881. + * The notifier system is based on linux/notifier.h, specifically the SRCU
  8882. + * implementation. The difference to that is, that some bits of the notifier
  8883. + * call return value can be tracked across multiple calls. This is done so
  8884. + * that handling of events can be tracked and a warning can be issued in case
  8885. + * an event goes unhandled. The idea of that warning is that it should help
  8886. + * discover and identify new/currently unimplemented features.
  8887. + */
  8888. +
  8889. +/**
  8890. + * ssam_event_matches_notifier() - Test if an event matches a notifier.
  8891. + * @n: The event notifier to test against.
  8892. + * @event: The event to test.
  8893. + *
  8894. + * Return: Returns %true if the given event matches the given notifier
  8895. + * according to the rules set in the notifier's event mask, %false otherwise.
  8896. + */
  8897. +static bool ssam_event_matches_notifier(const struct ssam_event_notifier *n,
  8898. + const struct ssam_event *event)
  8899. +{
  8900. + bool match = n->event.id.target_category == event->target_category;
  8901. +
  8902. + if (n->event.mask & SSAM_EVENT_MASK_TARGET)
  8903. + match &= n->event.reg.target_id == event->target_id;
  8904. +
  8905. + if (n->event.mask & SSAM_EVENT_MASK_INSTANCE)
  8906. + match &= n->event.id.instance == event->instance_id;
  8907. +
  8908. + return match;
  8909. +}
  8910. +
  8911. +/**
  8912. + * ssam_nfblk_call_chain() - Call event notifier callbacks of the given chain.
  8913. + * @nh: The notifier head for which the notifier callbacks should be called.
  8914. + * @event: The event data provided to the callbacks.
  8915. + *
  8916. + * Call all registered notifier callbacks in order of their priority until
  8917. + * either no notifier is left or a notifier returns a value with the
  8918. + * %SSAM_NOTIF_STOP bit set. Note that this bit is automatically set via
  8919. + * ssam_notifier_from_errno() on any non-zero error value.
  8920. + *
  8921. + * Return: Returns the notifier status value, which contains the notifier
  8922. + * status bits (%SSAM_NOTIF_HANDLED and %SSAM_NOTIF_STOP) as well as a
  8923. + * potential error value returned from the last executed notifier callback.
  8924. + * Use ssam_notifier_to_errno() to convert this value to the original error
  8925. + * value.
  8926. + */
  8927. +static int ssam_nfblk_call_chain(struct ssam_nf_head *nh, struct ssam_event *event)
  8928. +{
  8929. + struct ssam_event_notifier *nf;
  8930. + int ret = 0, idx;
  8931. +
  8932. + idx = srcu_read_lock(&nh->srcu);
  8933. +
  8934. + list_for_each_entry_rcu(nf, &nh->head, base.node,
  8935. + srcu_read_lock_held(&nh->srcu)) {
  8936. + if (ssam_event_matches_notifier(nf, event)) {
  8937. + ret = (ret & SSAM_NOTIF_STATE_MASK) | nf->base.fn(nf, event);
  8938. + if (ret & SSAM_NOTIF_STOP)
  8939. + break;
  8940. + }
  8941. + }
  8942. +
  8943. + srcu_read_unlock(&nh->srcu, idx);
  8944. + return ret;
  8945. +}
  8946. +
  8947. +/**
  8948. + * ssam_nfblk_insert() - Insert a new notifier block into the given notifier
  8949. + * list.
  8950. + * @nh: The notifier head into which the block should be inserted.
  8951. + * @nb: The notifier block to add.
  8952. + *
  8953. + * Note: This function must be synchronized by the caller with respect to other
  8954. + * insert, find, and/or remove calls by holding ``struct ssam_nf.lock``.
  8955. + *
  8956. + * Return: Returns zero on success, %-EEXIST if the notifier block has already
  8957. + * been registered.
  8958. + */
  8959. +static int ssam_nfblk_insert(struct ssam_nf_head *nh, struct ssam_notifier_block *nb)
  8960. +{
  8961. + struct ssam_notifier_block *p;
  8962. + struct list_head *h;
  8963. +
  8964. + /* Runs under lock, no need for RCU variant. */
  8965. + list_for_each(h, &nh->head) {
  8966. + p = list_entry(h, struct ssam_notifier_block, node);
  8967. +
  8968. + if (unlikely(p == nb)) {
  8969. + WARN(1, "double register detected");
  8970. + return -EEXIST;
  8971. + }
  8972. +
  8973. + if (nb->priority > p->priority)
  8974. + break;
  8975. + }
  8976. +
  8977. + list_add_tail_rcu(&nb->node, h);
  8978. + return 0;
  8979. +}
  8980. +
  8981. +/**
  8982. + * ssam_nfblk_find() - Check if a notifier block is registered on the given
  8983. + * notifier head.
  8984. + * list.
  8985. + * @nh: The notifier head on which to search.
  8986. + * @nb: The notifier block to search for.
  8987. + *
  8988. + * Note: This function must be synchronized by the caller with respect to other
  8989. + * insert, find, and/or remove calls by holding ``struct ssam_nf.lock``.
  8990. + *
  8991. + * Return: Returns true if the given notifier block is registered on the given
  8992. + * notifier head, false otherwise.
  8993. + */
  8994. +static bool ssam_nfblk_find(struct ssam_nf_head *nh, struct ssam_notifier_block *nb)
  8995. +{
  8996. + struct ssam_notifier_block *p;
  8997. +
  8998. + /* Runs under lock, no need for RCU variant. */
  8999. + list_for_each_entry(p, &nh->head, node) {
  9000. + if (p == nb)
  9001. + return true;
  9002. + }
  9003. +
  9004. + return false;
  9005. +}
  9006. +
  9007. +/**
  9008. + * ssam_nfblk_remove() - Remove a notifier block from its notifier list.
  9009. + * @nb: The notifier block to be removed.
  9010. + *
  9011. + * Note: This function must be synchronized by the caller with respect to
  9012. + * other insert, find, and/or remove calls by holding ``struct ssam_nf.lock``.
  9013. + * Furthermore, the caller _must_ ensure SRCU synchronization by calling
  9014. + * synchronize_srcu() with ``nh->srcu`` after leaving the critical section, to
  9015. + * ensure that the removed notifier block is not in use any more.
  9016. + */
  9017. +static void ssam_nfblk_remove(struct ssam_notifier_block *nb)
  9018. +{
  9019. + list_del_rcu(&nb->node);
  9020. +}
  9021. +
  9022. +/**
  9023. + * ssam_nf_head_init() - Initialize the given notifier head.
  9024. + * @nh: The notifier head to initialize.
  9025. + */
  9026. +static int ssam_nf_head_init(struct ssam_nf_head *nh)
  9027. +{
  9028. + int status;
  9029. +
  9030. + status = init_srcu_struct(&nh->srcu);
  9031. + if (status)
  9032. + return status;
  9033. +
  9034. + INIT_LIST_HEAD(&nh->head);
  9035. + return 0;
  9036. +}
  9037. +
  9038. +/**
  9039. + * ssam_nf_head_destroy() - Deinitialize the given notifier head.
  9040. + * @nh: The notifier head to deinitialize.
  9041. + */
  9042. +static void ssam_nf_head_destroy(struct ssam_nf_head *nh)
  9043. +{
  9044. + cleanup_srcu_struct(&nh->srcu);
  9045. +}
  9046. +
  9047. +
  9048. +/* -- Event/notification registry. ------------------------------------------ */
  9049. +
  9050. +/**
  9051. + * struct ssam_nf_refcount_key - Key used for event activation reference
  9052. + * counting.
  9053. + * @reg: The registry via which the event is enabled/disabled.
  9054. + * @id: The ID uniquely describing the event.
  9055. + */
  9056. +struct ssam_nf_refcount_key {
  9057. + struct ssam_event_registry reg;
  9058. + struct ssam_event_id id;
  9059. +};
  9060. +
  9061. +/**
  9062. + * struct ssam_nf_refcount_entry - RB-tree entry for reference counting event
  9063. + * activations.
  9064. + * @node: The node of this entry in the rb-tree.
  9065. + * @key: The key of the event.
  9066. + * @refcount: The reference-count of the event.
  9067. + * @flags: The flags used when enabling the event.
  9068. + */
  9069. +struct ssam_nf_refcount_entry {
  9070. + struct rb_node node;
  9071. + struct ssam_nf_refcount_key key;
  9072. + int refcount;
  9073. + u8 flags;
  9074. +};
  9075. +
  9076. +/**
  9077. + * ssam_nf_refcount_inc() - Increment reference-/activation-count of the given
  9078. + * event.
  9079. + * @nf: The notifier system reference.
  9080. + * @reg: The registry used to enable/disable the event.
  9081. + * @id: The event ID.
  9082. + *
  9083. + * Increments the reference-/activation-count associated with the specified
  9084. + * event type/ID, allocating a new entry for this event ID if necessary. A
  9085. + * newly allocated entry will have a refcount of one.
  9086. + *
  9087. + * Note: ``nf->lock`` must be held when calling this function.
  9088. + *
  9089. + * Return: Returns the refcount entry on success. Returns an error pointer
  9090. + * with %-ENOSPC if there have already been %INT_MAX events of the specified
  9091. + * ID and type registered, or %-ENOMEM if the entry could not be allocated.
  9092. + */
  9093. +static struct ssam_nf_refcount_entry *
  9094. +ssam_nf_refcount_inc(struct ssam_nf *nf, struct ssam_event_registry reg,
  9095. + struct ssam_event_id id)
  9096. +{
  9097. + struct ssam_nf_refcount_entry *entry;
  9098. + struct ssam_nf_refcount_key key;
  9099. + struct rb_node **link = &nf->refcount.rb_node;
  9100. + struct rb_node *parent = NULL;
  9101. + int cmp;
  9102. +
  9103. + lockdep_assert_held(&nf->lock);
  9104. +
  9105. + key.reg = reg;
  9106. + key.id = id;
  9107. +
  9108. + while (*link) {
  9109. + entry = rb_entry(*link, struct ssam_nf_refcount_entry, node);
  9110. + parent = *link;
  9111. +
  9112. + cmp = memcmp(&key, &entry->key, sizeof(key));
  9113. + if (cmp < 0) {
  9114. + link = &(*link)->rb_left;
  9115. + } else if (cmp > 0) {
  9116. + link = &(*link)->rb_right;
  9117. + } else if (entry->refcount < INT_MAX) {
  9118. + entry->refcount++;
  9119. + return entry;
  9120. + } else {
  9121. + WARN_ON(1);
  9122. + return ERR_PTR(-ENOSPC);
  9123. + }
  9124. + }
  9125. +
  9126. + entry = kzalloc(sizeof(*entry), GFP_KERNEL);
  9127. + if (!entry)
  9128. + return ERR_PTR(-ENOMEM);
  9129. +
  9130. + entry->key = key;
  9131. + entry->refcount = 1;
  9132. +
  9133. + rb_link_node(&entry->node, parent, link);
  9134. + rb_insert_color(&entry->node, &nf->refcount);
  9135. +
  9136. + return entry;
  9137. +}
  9138. +
  9139. +/**
  9140. + * ssam_nf_refcount_dec() - Decrement reference-/activation-count of the given
  9141. + * event.
  9142. + * @nf: The notifier system reference.
  9143. + * @reg: The registry used to enable/disable the event.
  9144. + * @id: The event ID.
  9145. + *
  9146. + * Decrements the reference-/activation-count of the specified event,
  9147. + * returning its entry. If the returned entry has a refcount of zero, the
  9148. + * caller is responsible for freeing it using kfree().
  9149. + *
  9150. + * Note: ``nf->lock`` must be held when calling this function.
  9151. + *
  9152. + * Return: Returns the refcount entry on success or %NULL if the entry has not
  9153. + * been found.
  9154. + */
  9155. +static struct ssam_nf_refcount_entry *
  9156. +ssam_nf_refcount_dec(struct ssam_nf *nf, struct ssam_event_registry reg,
  9157. + struct ssam_event_id id)
  9158. +{
  9159. + struct ssam_nf_refcount_entry *entry;
  9160. + struct ssam_nf_refcount_key key;
  9161. + struct rb_node *node = nf->refcount.rb_node;
  9162. + int cmp;
  9163. +
  9164. + lockdep_assert_held(&nf->lock);
  9165. +
  9166. + key.reg = reg;
  9167. + key.id = id;
  9168. +
  9169. + while (node) {
  9170. + entry = rb_entry(node, struct ssam_nf_refcount_entry, node);
  9171. +
  9172. + cmp = memcmp(&key, &entry->key, sizeof(key));
  9173. + if (cmp < 0) {
  9174. + node = node->rb_left;
  9175. + } else if (cmp > 0) {
  9176. + node = node->rb_right;
  9177. + } else {
  9178. + entry->refcount--;
  9179. + if (entry->refcount == 0)
  9180. + rb_erase(&entry->node, &nf->refcount);
  9181. +
  9182. + return entry;
  9183. + }
  9184. + }
  9185. +
  9186. + return NULL;
  9187. +}
  9188. +
  9189. +/**
  9190. + * ssam_nf_refcount_empty() - Test if the notification system has any
  9191. + * enabled/active events.
  9192. + * @nf: The notification system.
  9193. + */
  9194. +static bool ssam_nf_refcount_empty(struct ssam_nf *nf)
  9195. +{
  9196. + return RB_EMPTY_ROOT(&nf->refcount);
  9197. +}
  9198. +
  9199. +/**
  9200. + * ssam_nf_call() - Call notification callbacks for the provided event.
  9201. + * @nf: The notifier system
  9202. + * @dev: The associated device, only used for logging.
  9203. + * @rqid: The request ID of the event.
  9204. + * @event: The event provided to the callbacks.
  9205. + *
  9206. + * Execute registered callbacks in order of their priority until either no
  9207. + * callback is left or a callback returns a value with the %SSAM_NOTIF_STOP
  9208. + * bit set. Note that this bit is set automatically when converting non-zero
  9209. + * error values via ssam_notifier_from_errno() to notifier values.
  9210. + *
  9211. + * Also note that any callback that could handle an event should return a value
  9212. + * with bit %SSAM_NOTIF_HANDLED set, indicating that the event does not go
  9213. + * unhandled/ignored. In case no registered callback could handle an event,
  9214. + * this function will emit a warning.
  9215. + *
  9216. + * In case a callback failed, this function will emit an error message.
  9217. + */
  9218. +static void ssam_nf_call(struct ssam_nf *nf, struct device *dev, u16 rqid,
  9219. + struct ssam_event *event)
  9220. +{
  9221. + struct ssam_nf_head *nf_head;
  9222. + int status, nf_ret;
  9223. +
  9224. + if (!ssh_rqid_is_event(rqid)) {
  9225. + dev_warn(dev, "event: unsupported rqid: %#06x\n", rqid);
  9226. + return;
  9227. + }
  9228. +
  9229. + nf_head = &nf->head[ssh_rqid_to_event(rqid)];
  9230. + nf_ret = ssam_nfblk_call_chain(nf_head, event);
  9231. + status = ssam_notifier_to_errno(nf_ret);
  9232. +
  9233. + if (status < 0) {
  9234. + dev_err(dev,
  9235. + "event: error handling event: %d (tc: %#04x, tid: %#04x, cid: %#04x, iid: %#04x)\n",
  9236. + status, event->target_category, event->target_id,
  9237. + event->command_id, event->instance_id);
  9238. + } else if (!(nf_ret & SSAM_NOTIF_HANDLED)) {
  9239. + dev_warn(dev,
  9240. + "event: unhandled event (rqid: %#04x, tc: %#04x, tid: %#04x, cid: %#04x, iid: %#04x)\n",
  9241. + rqid, event->target_category, event->target_id,
  9242. + event->command_id, event->instance_id);
  9243. + }
  9244. +}
  9245. +
  9246. +/**
  9247. + * ssam_nf_init() - Initialize the notifier system.
  9248. + * @nf: The notifier system to initialize.
  9249. + */
  9250. +static int ssam_nf_init(struct ssam_nf *nf)
  9251. +{
  9252. + int i, status;
  9253. +
  9254. + for (i = 0; i < SSH_NUM_EVENTS; i++) {
  9255. + status = ssam_nf_head_init(&nf->head[i]);
  9256. + if (status)
  9257. + break;
  9258. + }
  9259. +
  9260. + if (status) {
  9261. + while (i--)
  9262. + ssam_nf_head_destroy(&nf->head[i]);
  9263. +
  9264. + return status;
  9265. + }
  9266. +
  9267. + mutex_init(&nf->lock);
  9268. + return 0;
  9269. +}
  9270. +
  9271. +/**
  9272. + * ssam_nf_destroy() - Deinitialize the notifier system.
  9273. + * @nf: The notifier system to deinitialize.
  9274. + */
  9275. +static void ssam_nf_destroy(struct ssam_nf *nf)
  9276. +{
  9277. + int i;
  9278. +
  9279. + for (i = 0; i < SSH_NUM_EVENTS; i++)
  9280. + ssam_nf_head_destroy(&nf->head[i]);
  9281. +
  9282. + mutex_destroy(&nf->lock);
  9283. +}
  9284. +
  9285. +
  9286. +/* -- Event/async request completion system. -------------------------------- */
  9287. +
  9288. +#define SSAM_CPLT_WQ_NAME "ssam_cpltq"
  9289. +
  9290. +/*
  9291. + * SSAM_CPLT_WQ_BATCH - Maximum number of event item completions executed per
  9292. + * work execution. Used to prevent livelocking of the workqueue. Value chosen
  9293. + * via educated guess, may be adjusted.
  9294. + */
  9295. +#define SSAM_CPLT_WQ_BATCH 10
  9296. +
  9297. +/*
  9298. + * SSAM_EVENT_ITEM_CACHE_PAYLOAD_LEN - Maximum payload length for a cached
  9299. + * &struct ssam_event_item.
  9300. + *
  9301. + * This length has been chosen to be accommodate standard touchpad and
  9302. + * keyboard input events. Events with larger payloads will be allocated
  9303. + * separately.
  9304. + */
  9305. +#define SSAM_EVENT_ITEM_CACHE_PAYLOAD_LEN 32
  9306. +
  9307. +static struct kmem_cache *ssam_event_item_cache;
  9308. +
  9309. +/**
  9310. + * ssam_event_item_cache_init() - Initialize the event item cache.
  9311. + */
  9312. +int ssam_event_item_cache_init(void)
  9313. +{
  9314. + const unsigned int size = sizeof(struct ssam_event_item)
  9315. + + SSAM_EVENT_ITEM_CACHE_PAYLOAD_LEN;
  9316. + const unsigned int align = __alignof__(struct ssam_event_item);
  9317. + struct kmem_cache *cache;
  9318. +
  9319. + cache = kmem_cache_create("ssam_event_item", size, align, 0, NULL);
  9320. + if (!cache)
  9321. + return -ENOMEM;
  9322. +
  9323. + ssam_event_item_cache = cache;
  9324. + return 0;
  9325. +}
  9326. +
  9327. +/**
  9328. + * ssam_event_item_cache_destroy() - Deinitialize the event item cache.
  9329. + */
  9330. +void ssam_event_item_cache_destroy(void)
  9331. +{
  9332. + kmem_cache_destroy(ssam_event_item_cache);
  9333. + ssam_event_item_cache = NULL;
  9334. +}
  9335. +
  9336. +static void __ssam_event_item_free_cached(struct ssam_event_item *item)
  9337. +{
  9338. + kmem_cache_free(ssam_event_item_cache, item);
  9339. +}
  9340. +
  9341. +static void __ssam_event_item_free_generic(struct ssam_event_item *item)
  9342. +{
  9343. + kfree(item);
  9344. +}
  9345. +
  9346. +/**
  9347. + * ssam_event_item_free() - Free the provided event item.
  9348. + * @item: The event item to free.
  9349. + */
  9350. +static void ssam_event_item_free(struct ssam_event_item *item)
  9351. +{
  9352. + trace_ssam_event_item_free(item);
  9353. + item->ops.free(item);
  9354. +}
  9355. +
  9356. +/**
  9357. + * ssam_event_item_alloc() - Allocate an event item with the given payload size.
  9358. + * @len: The event payload length.
  9359. + * @flags: The flags used for allocation.
  9360. + *
  9361. + * Allocate an event item with the given payload size, preferring allocation
  9362. + * from the event item cache if the payload is small enough (i.e. smaller than
  9363. + * %SSAM_EVENT_ITEM_CACHE_PAYLOAD_LEN). Sets the item operations and payload
  9364. + * length values. The item free callback (``ops.free``) should not be
  9365. + * overwritten after this call.
  9366. + *
  9367. + * Return: Returns the newly allocated event item.
  9368. + */
  9369. +static struct ssam_event_item *ssam_event_item_alloc(size_t len, gfp_t flags)
  9370. +{
  9371. + struct ssam_event_item *item;
  9372. +
  9373. + if (len <= SSAM_EVENT_ITEM_CACHE_PAYLOAD_LEN) {
  9374. + item = kmem_cache_alloc(ssam_event_item_cache, flags);
  9375. + if (!item)
  9376. + return NULL;
  9377. +
  9378. + item->ops.free = __ssam_event_item_free_cached;
  9379. + } else {
  9380. + item = kzalloc(struct_size(item, event.data, len), flags);
  9381. + if (!item)
  9382. + return NULL;
  9383. +
  9384. + item->ops.free = __ssam_event_item_free_generic;
  9385. + }
  9386. +
  9387. + item->event.length = len;
  9388. +
  9389. + trace_ssam_event_item_alloc(item, len);
  9390. + return item;
  9391. +}
  9392. +
  9393. +/**
  9394. + * ssam_event_queue_push() - Push an event item to the event queue.
  9395. + * @q: The event queue.
  9396. + * @item: The item to add.
  9397. + */
  9398. +static void ssam_event_queue_push(struct ssam_event_queue *q,
  9399. + struct ssam_event_item *item)
  9400. +{
  9401. + spin_lock(&q->lock);
  9402. + list_add_tail(&item->node, &q->head);
  9403. + spin_unlock(&q->lock);
  9404. +}
  9405. +
  9406. +/**
  9407. + * ssam_event_queue_pop() - Pop the next event item from the event queue.
  9408. + * @q: The event queue.
  9409. + *
  9410. + * Returns and removes the next event item from the queue. Returns %NULL If
  9411. + * there is no event item left.
  9412. + */
  9413. +static struct ssam_event_item *ssam_event_queue_pop(struct ssam_event_queue *q)
  9414. +{
  9415. + struct ssam_event_item *item;
  9416. +
  9417. + spin_lock(&q->lock);
  9418. + item = list_first_entry_or_null(&q->head, struct ssam_event_item, node);
  9419. + if (item)
  9420. + list_del(&item->node);
  9421. + spin_unlock(&q->lock);
  9422. +
  9423. + return item;
  9424. +}
  9425. +
  9426. +/**
  9427. + * ssam_event_queue_is_empty() - Check if the event queue is empty.
  9428. + * @q: The event queue.
  9429. + */
  9430. +static bool ssam_event_queue_is_empty(struct ssam_event_queue *q)
  9431. +{
  9432. + bool empty;
  9433. +
  9434. + spin_lock(&q->lock);
  9435. + empty = list_empty(&q->head);
  9436. + spin_unlock(&q->lock);
  9437. +
  9438. + return empty;
  9439. +}
  9440. +
  9441. +/**
  9442. + * ssam_cplt_get_event_queue() - Get the event queue for the given parameters.
  9443. + * @cplt: The completion system on which to look for the queue.
  9444. + * @tid: The target ID of the queue.
  9445. + * @rqid: The request ID representing the event ID for which to get the queue.
  9446. + *
  9447. + * Return: Returns the event queue corresponding to the event type described
  9448. + * by the given parameters. If the request ID does not represent an event,
  9449. + * this function returns %NULL. If the target ID is not supported, this
  9450. + * function will fall back to the default target ID (``tid = 1``).
  9451. + */
  9452. +static
  9453. +struct ssam_event_queue *ssam_cplt_get_event_queue(struct ssam_cplt *cplt,
  9454. + u8 tid, u16 rqid)
  9455. +{
  9456. + u16 event = ssh_rqid_to_event(rqid);
  9457. + u16 tidx = ssh_tid_to_index(tid);
  9458. +
  9459. + if (!ssh_rqid_is_event(rqid)) {
  9460. + dev_err(cplt->dev, "event: unsupported request ID: %#06x\n", rqid);
  9461. + return NULL;
  9462. + }
  9463. +
  9464. + if (!ssh_tid_is_valid(tid)) {
  9465. + dev_warn(cplt->dev, "event: unsupported target ID: %u\n", tid);
  9466. + tidx = 0;
  9467. + }
  9468. +
  9469. + return &cplt->event.target[tidx].queue[event];
  9470. +}
  9471. +
  9472. +/**
  9473. + * ssam_cplt_submit() - Submit a work item to the completion system workqueue.
  9474. + * @cplt: The completion system.
  9475. + * @work: The work item to submit.
  9476. + */
  9477. +static bool ssam_cplt_submit(struct ssam_cplt *cplt, struct work_struct *work)
  9478. +{
  9479. + return queue_work(cplt->wq, work);
  9480. +}
  9481. +
  9482. +/**
  9483. + * ssam_cplt_submit_event() - Submit an event to the completion system.
  9484. + * @cplt: The completion system.
  9485. + * @item: The event item to submit.
  9486. + *
  9487. + * Submits the event to the completion system by queuing it on the event item
  9488. + * queue and queuing the respective event queue work item on the completion
  9489. + * workqueue, which will eventually complete the event.
  9490. + *
  9491. + * Return: Returns zero on success, %-EINVAL if there is no event queue that
  9492. + * can handle the given event item.
  9493. + */
  9494. +static int ssam_cplt_submit_event(struct ssam_cplt *cplt,
  9495. + struct ssam_event_item *item)
  9496. +{
  9497. + struct ssam_event_queue *evq;
  9498. +
  9499. + evq = ssam_cplt_get_event_queue(cplt, item->event.target_id, item->rqid);
  9500. + if (!evq)
  9501. + return -EINVAL;
  9502. +
  9503. + ssam_event_queue_push(evq, item);
  9504. + ssam_cplt_submit(cplt, &evq->work);
  9505. + return 0;
  9506. +}
  9507. +
  9508. +/**
  9509. + * ssam_cplt_flush() - Flush the completion system.
  9510. + * @cplt: The completion system.
  9511. + *
  9512. + * Flush the completion system by waiting until all currently submitted work
  9513. + * items have been completed.
  9514. + *
  9515. + * Note: This function does not guarantee that all events will have been
  9516. + * handled once this call terminates. In case of a larger number of
  9517. + * to-be-completed events, the event queue work function may re-schedule its
  9518. + * work item, which this flush operation will ignore.
  9519. + *
  9520. + * This operation is only intended to, during normal operation prior to
  9521. + * shutdown, try to complete most events and requests to get them out of the
  9522. + * system while the system is still fully operational. It does not aim to
  9523. + * provide any guarantee that all of them have been handled.
  9524. + */
  9525. +static void ssam_cplt_flush(struct ssam_cplt *cplt)
  9526. +{
  9527. + flush_workqueue(cplt->wq);
  9528. +}
  9529. +
  9530. +static void ssam_event_queue_work_fn(struct work_struct *work)
  9531. +{
  9532. + struct ssam_event_queue *queue;
  9533. + struct ssam_event_item *item;
  9534. + struct ssam_nf *nf;
  9535. + struct device *dev;
  9536. + unsigned int iterations = SSAM_CPLT_WQ_BATCH;
  9537. +
  9538. + queue = container_of(work, struct ssam_event_queue, work);
  9539. + nf = &queue->cplt->event.notif;
  9540. + dev = queue->cplt->dev;
  9541. +
  9542. + /* Limit number of processed events to avoid livelocking. */
  9543. + do {
  9544. + item = ssam_event_queue_pop(queue);
  9545. + if (!item)
  9546. + return;
  9547. +
  9548. + ssam_nf_call(nf, dev, item->rqid, &item->event);
  9549. + ssam_event_item_free(item);
  9550. + } while (--iterations);
  9551. +
  9552. + if (!ssam_event_queue_is_empty(queue))
  9553. + ssam_cplt_submit(queue->cplt, &queue->work);
  9554. +}
  9555. +
  9556. +/**
  9557. + * ssam_event_queue_init() - Initialize an event queue.
  9558. + * @cplt: The completion system on which the queue resides.
  9559. + * @evq: The event queue to initialize.
  9560. + */
  9561. +static void ssam_event_queue_init(struct ssam_cplt *cplt,
  9562. + struct ssam_event_queue *evq)
  9563. +{
  9564. + evq->cplt = cplt;
  9565. + spin_lock_init(&evq->lock);
  9566. + INIT_LIST_HEAD(&evq->head);
  9567. + INIT_WORK(&evq->work, ssam_event_queue_work_fn);
  9568. +}
  9569. +
  9570. +/**
  9571. + * ssam_cplt_init() - Initialize completion system.
  9572. + * @cplt: The completion system to initialize.
  9573. + * @dev: The device used for logging.
  9574. + */
  9575. +static int ssam_cplt_init(struct ssam_cplt *cplt, struct device *dev)
  9576. +{
  9577. + struct ssam_event_target *target;
  9578. + int status, c, i;
  9579. +
  9580. + cplt->dev = dev;
  9581. +
  9582. + cplt->wq = create_workqueue(SSAM_CPLT_WQ_NAME);
  9583. + if (!cplt->wq)
  9584. + return -ENOMEM;
  9585. +
  9586. + for (c = 0; c < ARRAY_SIZE(cplt->event.target); c++) {
  9587. + target = &cplt->event.target[c];
  9588. +
  9589. + for (i = 0; i < ARRAY_SIZE(target->queue); i++)
  9590. + ssam_event_queue_init(cplt, &target->queue[i]);
  9591. + }
  9592. +
  9593. + status = ssam_nf_init(&cplt->event.notif);
  9594. + if (status)
  9595. + destroy_workqueue(cplt->wq);
  9596. +
  9597. + return status;
  9598. +}
  9599. +
  9600. +/**
  9601. + * ssam_cplt_destroy() - Deinitialize the completion system.
  9602. + * @cplt: The completion system to deinitialize.
  9603. + *
  9604. + * Deinitialize the given completion system and ensure that all pending, i.e.
  9605. + * yet-to-be-completed, event items and requests have been handled.
  9606. + */
  9607. +static void ssam_cplt_destroy(struct ssam_cplt *cplt)
  9608. +{
  9609. + /*
  9610. + * Note: destroy_workqueue ensures that all currently queued work will
  9611. + * be fully completed and the workqueue drained. This means that this
  9612. + * call will inherently also free any queued ssam_event_items, thus we
  9613. + * don't have to take care of that here explicitly.
  9614. + */
  9615. + destroy_workqueue(cplt->wq);
  9616. + ssam_nf_destroy(&cplt->event.notif);
  9617. +}
  9618. +
  9619. +
  9620. +/* -- Main SSAM device structures. ------------------------------------------ */
  9621. +
  9622. +/**
  9623. + * ssam_controller_device() - Get the &struct device associated with this
  9624. + * controller.
  9625. + * @c: The controller for which to get the device.
  9626. + *
  9627. + * Return: Returns the &struct device associated with this controller,
  9628. + * providing its lower-level transport.
  9629. + */
  9630. +struct device *ssam_controller_device(struct ssam_controller *c)
  9631. +{
  9632. + return ssh_rtl_get_device(&c->rtl);
  9633. +}
  9634. +EXPORT_SYMBOL_GPL(ssam_controller_device);
  9635. +
  9636. +static void __ssam_controller_release(struct kref *kref)
  9637. +{
  9638. + struct ssam_controller *ctrl = to_ssam_controller(kref, kref);
  9639. +
  9640. + /*
  9641. + * The lock-call here is to satisfy lockdep. At this point we really
  9642. + * expect this to be the last remaining reference to the controller.
  9643. + * Anything else is a bug.
  9644. + */
  9645. + ssam_controller_lock(ctrl);
  9646. + ssam_controller_destroy(ctrl);
  9647. + ssam_controller_unlock(ctrl);
  9648. +
  9649. + kfree(ctrl);
  9650. +}
  9651. +
  9652. +/**
  9653. + * ssam_controller_get() - Increment reference count of controller.
  9654. + * @c: The controller.
  9655. + *
  9656. + * Return: Returns the controller provided as input.
  9657. + */
  9658. +struct ssam_controller *ssam_controller_get(struct ssam_controller *c)
  9659. +{
  9660. + if (c)
  9661. + kref_get(&c->kref);
  9662. + return c;
  9663. +}
  9664. +EXPORT_SYMBOL_GPL(ssam_controller_get);
  9665. +
  9666. +/**
  9667. + * ssam_controller_put() - Decrement reference count of controller.
  9668. + * @c: The controller.
  9669. + */
  9670. +void ssam_controller_put(struct ssam_controller *c)
  9671. +{
  9672. + if (c)
  9673. + kref_put(&c->kref, __ssam_controller_release);
  9674. +}
  9675. +EXPORT_SYMBOL_GPL(ssam_controller_put);
  9676. +
  9677. +/**
  9678. + * ssam_controller_statelock() - Lock the controller against state transitions.
  9679. + * @c: The controller to lock.
  9680. + *
  9681. + * Lock the controller against state transitions. Holding this lock guarantees
  9682. + * that the controller will not transition between states, i.e. if the
  9683. + * controller is in state "started", when this lock has been acquired, it will
  9684. + * remain in this state at least until the lock has been released.
  9685. + *
  9686. + * Multiple clients may concurrently hold this lock. In other words: The
  9687. + * ``statelock`` functions represent the read-lock part of a r/w-semaphore.
  9688. + * Actions causing state transitions of the controller must be executed while
  9689. + * holding the write-part of this r/w-semaphore (see ssam_controller_lock()
  9690. + * and ssam_controller_unlock() for that).
  9691. + *
  9692. + * See ssam_controller_stateunlock() for the corresponding unlock function.
  9693. + */
  9694. +void ssam_controller_statelock(struct ssam_controller *c)
  9695. +{
  9696. + down_read(&c->lock);
  9697. +}
  9698. +EXPORT_SYMBOL_GPL(ssam_controller_statelock);
  9699. +
  9700. +/**
  9701. + * ssam_controller_stateunlock() - Unlock controller state transitions.
  9702. + * @c: The controller to unlock.
  9703. + *
  9704. + * See ssam_controller_statelock() for the corresponding lock function.
  9705. + */
  9706. +void ssam_controller_stateunlock(struct ssam_controller *c)
  9707. +{
  9708. + up_read(&c->lock);
  9709. +}
  9710. +EXPORT_SYMBOL_GPL(ssam_controller_stateunlock);
  9711. +
  9712. +/**
  9713. + * ssam_controller_lock() - Acquire the main controller lock.
  9714. + * @c: The controller to lock.
  9715. + *
  9716. + * This lock must be held for any state transitions, including transition to
  9717. + * suspend/resumed states and during shutdown. See ssam_controller_statelock()
  9718. + * for more details on controller locking.
  9719. + *
  9720. + * See ssam_controller_unlock() for the corresponding unlock function.
  9721. + */
  9722. +void ssam_controller_lock(struct ssam_controller *c)
  9723. +{
  9724. + down_write(&c->lock);
  9725. +}
  9726. +
  9727. +/*
  9728. + * ssam_controller_unlock() - Release the main controller lock.
  9729. + * @c: The controller to unlock.
  9730. + *
  9731. + * See ssam_controller_lock() for the corresponding lock function.
  9732. + */
  9733. +void ssam_controller_unlock(struct ssam_controller *c)
  9734. +{
  9735. + up_write(&c->lock);
  9736. +}
  9737. +
  9738. +static void ssam_handle_event(struct ssh_rtl *rtl,
  9739. + const struct ssh_command *cmd,
  9740. + const struct ssam_span *data)
  9741. +{
  9742. + struct ssam_controller *ctrl = to_ssam_controller(rtl, rtl);
  9743. + struct ssam_event_item *item;
  9744. +
  9745. + item = ssam_event_item_alloc(data->len, GFP_KERNEL);
  9746. + if (!item)
  9747. + return;
  9748. +
  9749. + item->rqid = get_unaligned_le16(&cmd->rqid);
  9750. + item->event.target_category = cmd->tc;
  9751. + item->event.target_id = cmd->tid_in;
  9752. + item->event.command_id = cmd->cid;
  9753. + item->event.instance_id = cmd->iid;
  9754. + memcpy(&item->event.data[0], data->ptr, data->len);
  9755. +
  9756. + if (WARN_ON(ssam_cplt_submit_event(&ctrl->cplt, item)))
  9757. + ssam_event_item_free(item);
  9758. +}
  9759. +
  9760. +static const struct ssh_rtl_ops ssam_rtl_ops = {
  9761. + .handle_event = ssam_handle_event,
  9762. +};
  9763. +
  9764. +static bool ssam_notifier_is_empty(struct ssam_controller *ctrl);
  9765. +static void ssam_notifier_unregister_all(struct ssam_controller *ctrl);
  9766. +
  9767. +#define SSAM_SSH_DSM_REVISION 0
  9768. +
  9769. +/* d5e383e1-d892-4a76-89fc-f6aaae7ed5b5 */
  9770. +static const guid_t SSAM_SSH_DSM_GUID =
  9771. + GUID_INIT(0xd5e383e1, 0xd892, 0x4a76,
  9772. + 0x89, 0xfc, 0xf6, 0xaa, 0xae, 0x7e, 0xd5, 0xb5);
  9773. +
  9774. +enum ssh_dsm_fn {
  9775. + SSH_DSM_FN_SSH_POWER_PROFILE = 0x05,
  9776. + SSH_DSM_FN_SCREEN_ON_SLEEP_IDLE_TIMEOUT = 0x06,
  9777. + SSH_DSM_FN_SCREEN_OFF_SLEEP_IDLE_TIMEOUT = 0x07,
  9778. + SSH_DSM_FN_D3_CLOSES_HANDLE = 0x08,
  9779. + SSH_DSM_FN_SSH_BUFFER_SIZE = 0x09,
  9780. +};
  9781. +
  9782. +static int ssam_dsm_get_functions(acpi_handle handle, u64 *funcs)
  9783. +{
  9784. + union acpi_object *obj;
  9785. + u64 mask = 0;
  9786. + int i;
  9787. +
  9788. + *funcs = 0;
  9789. +
  9790. + /*
  9791. + * The _DSM function is only present on newer models. It is not
  9792. + * present on 5th and 6th generation devices (i.e. up to and including
  9793. + * Surface Pro 6, Surface Laptop 2, Surface Book 2).
  9794. + *
  9795. + * If the _DSM is not present, indicate that no function is supported.
  9796. + * This will result in default values being set.
  9797. + */
  9798. + if (!acpi_has_method(handle, "_DSM"))
  9799. + return 0;
  9800. +
  9801. + obj = acpi_evaluate_dsm_typed(handle, &SSAM_SSH_DSM_GUID,
  9802. + SSAM_SSH_DSM_REVISION, 0, NULL,
  9803. + ACPI_TYPE_BUFFER);
  9804. + if (!obj)
  9805. + return -EIO;
  9806. +
  9807. + for (i = 0; i < obj->buffer.length && i < 8; i++)
  9808. + mask |= (((u64)obj->buffer.pointer[i]) << (i * 8));
  9809. +
  9810. + if (mask & BIT(0))
  9811. + *funcs = mask;
  9812. +
  9813. + ACPI_FREE(obj);
  9814. + return 0;
  9815. +}
  9816. +
  9817. +static int ssam_dsm_load_u32(acpi_handle handle, u64 funcs, u64 func, u32 *ret)
  9818. +{
  9819. + union acpi_object *obj;
  9820. + u64 val;
  9821. +
  9822. + if (!(funcs & BIT(func)))
  9823. + return 0; /* Not supported, leave *ret at its default value */
  9824. +
  9825. + obj = acpi_evaluate_dsm_typed(handle, &SSAM_SSH_DSM_GUID,
  9826. + SSAM_SSH_DSM_REVISION, func, NULL,
  9827. + ACPI_TYPE_INTEGER);
  9828. + if (!obj)
  9829. + return -EIO;
  9830. +
  9831. + val = obj->integer.value;
  9832. + ACPI_FREE(obj);
  9833. +
  9834. + if (val > U32_MAX)
  9835. + return -ERANGE;
  9836. +
  9837. + *ret = val;
  9838. + return 0;
  9839. +}
  9840. +
  9841. +/**
  9842. + * ssam_controller_caps_load_from_acpi() - Load controller capabilities from
  9843. + * ACPI _DSM.
  9844. + * @handle: The handle of the ACPI controller/SSH device.
  9845. + * @caps: Where to store the capabilities in.
  9846. + *
  9847. + * Initializes the given controller capabilities with default values, then
  9848. + * checks and, if the respective _DSM functions are available, loads the
  9849. + * actual capabilities from the _DSM.
  9850. + *
  9851. + * Return: Returns zero on success, a negative error code on failure.
  9852. + */
  9853. +static
  9854. +int ssam_controller_caps_load_from_acpi(acpi_handle handle,
  9855. + struct ssam_controller_caps *caps)
  9856. +{
  9857. + u32 d3_closes_handle = false;
  9858. + u64 funcs;
  9859. + int status;
  9860. +
  9861. + /* Set defaults. */
  9862. + caps->ssh_power_profile = U32_MAX;
  9863. + caps->screen_on_sleep_idle_timeout = U32_MAX;
  9864. + caps->screen_off_sleep_idle_timeout = U32_MAX;
  9865. + caps->d3_closes_handle = false;
  9866. + caps->ssh_buffer_size = U32_MAX;
  9867. +
  9868. + /* Pre-load supported DSM functions. */
  9869. + status = ssam_dsm_get_functions(handle, &funcs);
  9870. + if (status)
  9871. + return status;
  9872. +
  9873. + /* Load actual values from ACPI, if present. */
  9874. + status = ssam_dsm_load_u32(handle, funcs, SSH_DSM_FN_SSH_POWER_PROFILE,
  9875. + &caps->ssh_power_profile);
  9876. + if (status)
  9877. + return status;
  9878. +
  9879. + status = ssam_dsm_load_u32(handle, funcs,
  9880. + SSH_DSM_FN_SCREEN_ON_SLEEP_IDLE_TIMEOUT,
  9881. + &caps->screen_on_sleep_idle_timeout);
  9882. + if (status)
  9883. + return status;
  9884. +
  9885. + status = ssam_dsm_load_u32(handle, funcs,
  9886. + SSH_DSM_FN_SCREEN_OFF_SLEEP_IDLE_TIMEOUT,
  9887. + &caps->screen_off_sleep_idle_timeout);
  9888. + if (status)
  9889. + return status;
  9890. +
  9891. + status = ssam_dsm_load_u32(handle, funcs, SSH_DSM_FN_D3_CLOSES_HANDLE,
  9892. + &d3_closes_handle);
  9893. + if (status)
  9894. + return status;
  9895. +
  9896. + caps->d3_closes_handle = !!d3_closes_handle;
  9897. +
  9898. + status = ssam_dsm_load_u32(handle, funcs, SSH_DSM_FN_SSH_BUFFER_SIZE,
  9899. + &caps->ssh_buffer_size);
  9900. + if (status)
  9901. + return status;
  9902. +
  9903. + return 0;
  9904. +}
  9905. +
  9906. +/**
  9907. + * ssam_controller_init() - Initialize SSAM controller.
  9908. + * @ctrl: The controller to initialize.
  9909. + * @serdev: The serial device representing the underlying data transport.
  9910. + *
  9911. + * Initializes the given controller. Does neither start receiver nor
  9912. + * transmitter threads. After this call, the controller has to be hooked up to
  9913. + * the serdev core separately via &struct serdev_device_ops, relaying calls to
  9914. + * ssam_controller_receive_buf() and ssam_controller_write_wakeup(). Once the
  9915. + * controller has been hooked up, transmitter and receiver threads may be
  9916. + * started via ssam_controller_start(). These setup steps need to be completed
  9917. + * before controller can be used for requests.
  9918. + */
  9919. +int ssam_controller_init(struct ssam_controller *ctrl,
  9920. + struct serdev_device *serdev)
  9921. +{
  9922. + acpi_handle handle = ACPI_HANDLE(&serdev->dev);
  9923. + int status;
  9924. +
  9925. + init_rwsem(&ctrl->lock);
  9926. + kref_init(&ctrl->kref);
  9927. +
  9928. + status = ssam_controller_caps_load_from_acpi(handle, &ctrl->caps);
  9929. + if (status)
  9930. + return status;
  9931. +
  9932. + dev_dbg(&serdev->dev,
  9933. + "device capabilities:\n"
  9934. + " ssh_power_profile: %u\n"
  9935. + " ssh_buffer_size: %u\n"
  9936. + " screen_on_sleep_idle_timeout: %u\n"
  9937. + " screen_off_sleep_idle_timeout: %u\n"
  9938. + " d3_closes_handle: %u\n",
  9939. + ctrl->caps.ssh_power_profile,
  9940. + ctrl->caps.ssh_buffer_size,
  9941. + ctrl->caps.screen_on_sleep_idle_timeout,
  9942. + ctrl->caps.screen_off_sleep_idle_timeout,
  9943. + ctrl->caps.d3_closes_handle);
  9944. +
  9945. + ssh_seq_reset(&ctrl->counter.seq);
  9946. + ssh_rqid_reset(&ctrl->counter.rqid);
  9947. +
  9948. + /* Initialize event/request completion system. */
  9949. + status = ssam_cplt_init(&ctrl->cplt, &serdev->dev);
  9950. + if (status)
  9951. + return status;
  9952. +
  9953. + /* Initialize request and packet transport layers. */
  9954. + status = ssh_rtl_init(&ctrl->rtl, serdev, &ssam_rtl_ops);
  9955. + if (status) {
  9956. + ssam_cplt_destroy(&ctrl->cplt);
  9957. + return status;
  9958. + }
  9959. +
  9960. + /*
  9961. + * Set state via write_once even though we expect to be in an
  9962. + * exclusive context, due to smoke-testing in
  9963. + * ssam_request_sync_submit().
  9964. + */
  9965. + WRITE_ONCE(ctrl->state, SSAM_CONTROLLER_INITIALIZED);
  9966. + return 0;
  9967. +}
  9968. +
  9969. +/**
  9970. + * ssam_controller_start() - Start the receiver and transmitter threads of the
  9971. + * controller.
  9972. + * @ctrl: The controller.
  9973. + *
  9974. + * Note: When this function is called, the controller should be properly
  9975. + * hooked up to the serdev core via &struct serdev_device_ops. Please refer
  9976. + * to ssam_controller_init() for more details on controller initialization.
  9977. + *
  9978. + * This function must be called with the main controller lock held (i.e. by
  9979. + * calling ssam_controller_lock()).
  9980. + */
  9981. +int ssam_controller_start(struct ssam_controller *ctrl)
  9982. +{
  9983. + int status;
  9984. +
  9985. + lockdep_assert_held_write(&ctrl->lock);
  9986. +
  9987. + if (ctrl->state != SSAM_CONTROLLER_INITIALIZED)
  9988. + return -EINVAL;
  9989. +
  9990. + status = ssh_rtl_start(&ctrl->rtl);
  9991. + if (status)
  9992. + return status;
  9993. +
  9994. + /*
  9995. + * Set state via write_once even though we expect to be locked/in an
  9996. + * exclusive context, due to smoke-testing in
  9997. + * ssam_request_sync_submit().
  9998. + */
  9999. + WRITE_ONCE(ctrl->state, SSAM_CONTROLLER_STARTED);
  10000. + return 0;
  10001. +}
  10002. +
  10003. +/*
  10004. + * SSAM_CTRL_SHUTDOWN_FLUSH_TIMEOUT - Timeout for flushing requests during
  10005. + * shutdown.
  10006. + *
  10007. + * Chosen to be larger than one full request timeout, including packets timing
  10008. + * out. This value should give ample time to complete any outstanding requests
  10009. + * during normal operation and account for the odd package timeout.
  10010. + */
  10011. +#define SSAM_CTRL_SHUTDOWN_FLUSH_TIMEOUT msecs_to_jiffies(5000)
  10012. +
  10013. +/**
  10014. + * ssam_controller_shutdown() - Shut down the controller.
  10015. + * @ctrl: The controller.
  10016. + *
  10017. + * Shuts down the controller by flushing all pending requests and stopping the
  10018. + * transmitter and receiver threads. All requests submitted after this call
  10019. + * will fail with %-ESHUTDOWN. While it is discouraged to do so, this function
  10020. + * is safe to use in parallel with ongoing request submission.
  10021. + *
  10022. + * In the course of this shutdown procedure, all currently registered
  10023. + * notifiers will be unregistered. It is, however, strongly recommended to not
  10024. + * rely on this behavior, and instead the party registering the notifier
  10025. + * should unregister it before the controller gets shut down, e.g. via the
  10026. + * SSAM bus which guarantees client devices to be removed before a shutdown.
  10027. + *
  10028. + * Note that events may still be pending after this call, but, due to the
  10029. + * notifiers being unregistered, these events will be dropped when the
  10030. + * controller is subsequently destroyed via ssam_controller_destroy().
  10031. + *
  10032. + * This function must be called with the main controller lock held (i.e. by
  10033. + * calling ssam_controller_lock()).
  10034. + */
  10035. +void ssam_controller_shutdown(struct ssam_controller *ctrl)
  10036. +{
  10037. + enum ssam_controller_state s = ctrl->state;
  10038. + int status;
  10039. +
  10040. + lockdep_assert_held_write(&ctrl->lock);
  10041. +
  10042. + if (s == SSAM_CONTROLLER_UNINITIALIZED || s == SSAM_CONTROLLER_STOPPED)
  10043. + return;
  10044. +
  10045. + /*
  10046. + * Try to flush pending events and requests while everything still
  10047. + * works. Note: There may still be packets and/or requests in the
  10048. + * system after this call (e.g. via control packets submitted by the
  10049. + * packet transport layer or flush timeout / failure, ...). Those will
  10050. + * be handled with the ssh_rtl_shutdown() call below.
  10051. + */
  10052. + status = ssh_rtl_flush(&ctrl->rtl, SSAM_CTRL_SHUTDOWN_FLUSH_TIMEOUT);
  10053. + if (status) {
  10054. + ssam_err(ctrl, "failed to flush request transport layer: %d\n",
  10055. + status);
  10056. + }
  10057. +
  10058. + /* Try to flush all currently completing requests and events. */
  10059. + ssam_cplt_flush(&ctrl->cplt);
  10060. +
  10061. + /*
  10062. + * We expect all notifiers to have been removed by the respective client
  10063. + * driver that set them up at this point. If this warning occurs, some
  10064. + * client driver has not done that...
  10065. + */
  10066. + WARN_ON(!ssam_notifier_is_empty(ctrl));
  10067. +
  10068. + /*
  10069. + * Nevertheless, we should still take care of drivers that don't behave
  10070. + * well. Thus disable all enabled events, unregister all notifiers.
  10071. + */
  10072. + ssam_notifier_unregister_all(ctrl);
  10073. +
  10074. + /*
  10075. + * Cancel remaining requests. Ensure no new ones can be queued and stop
  10076. + * threads.
  10077. + */
  10078. + ssh_rtl_shutdown(&ctrl->rtl);
  10079. +
  10080. + /*
  10081. + * Set state via write_once even though we expect to be locked/in an
  10082. + * exclusive context, due to smoke-testing in
  10083. + * ssam_request_sync_submit().
  10084. + */
  10085. + WRITE_ONCE(ctrl->state, SSAM_CONTROLLER_STOPPED);
  10086. + ctrl->rtl.ptl.serdev = NULL;
  10087. +}
  10088. +
  10089. +/**
  10090. + * ssam_controller_destroy() - Destroy the controller and free its resources.
  10091. + * @ctrl: The controller.
  10092. + *
  10093. + * Ensures that all resources associated with the controller get freed. This
  10094. + * function should only be called after the controller has been stopped via
  10095. + * ssam_controller_shutdown(). In general, this function should not be called
  10096. + * directly. The only valid place to call this function directly is during
  10097. + * initialization, before the controller has been fully initialized and passed
  10098. + * to other processes. This function is called automatically when the
  10099. + * reference count of the controller reaches zero.
  10100. + *
  10101. + * This function must be called with the main controller lock held (i.e. by
  10102. + * calling ssam_controller_lock()).
  10103. + */
  10104. +void ssam_controller_destroy(struct ssam_controller *ctrl)
  10105. +{
  10106. + lockdep_assert_held_write(&ctrl->lock);
  10107. +
  10108. + if (ctrl->state == SSAM_CONTROLLER_UNINITIALIZED)
  10109. + return;
  10110. +
  10111. + WARN_ON(ctrl->state != SSAM_CONTROLLER_STOPPED);
  10112. +
  10113. + /*
  10114. + * Note: New events could still have been received after the previous
  10115. + * flush in ssam_controller_shutdown, before the request transport layer
  10116. + * has been shut down. At this point, after the shutdown, we can be sure
  10117. + * that no new events will be queued. The call to ssam_cplt_destroy will
  10118. + * ensure that those remaining are being completed and freed.
  10119. + */
  10120. +
  10121. + /* Actually free resources. */
  10122. + ssam_cplt_destroy(&ctrl->cplt);
  10123. + ssh_rtl_destroy(&ctrl->rtl);
  10124. +
  10125. + /*
  10126. + * Set state via write_once even though we expect to be locked/in an
  10127. + * exclusive context, due to smoke-testing in
  10128. + * ssam_request_sync_submit().
  10129. + */
  10130. + WRITE_ONCE(ctrl->state, SSAM_CONTROLLER_UNINITIALIZED);
  10131. +}
  10132. +
  10133. +/**
  10134. + * ssam_controller_suspend() - Suspend the controller.
  10135. + * @ctrl: The controller to suspend.
  10136. + *
  10137. + * Marks the controller as suspended. Note that display-off and D0-exit
  10138. + * notifications have to be sent manually before transitioning the controller
  10139. + * into the suspended state via this function.
  10140. + *
  10141. + * See ssam_controller_resume() for the corresponding resume function.
  10142. + *
  10143. + * Return: Returns %-EINVAL if the controller is currently not in the
  10144. + * "started" state.
  10145. + */
  10146. +int ssam_controller_suspend(struct ssam_controller *ctrl)
  10147. +{
  10148. + ssam_controller_lock(ctrl);
  10149. +
  10150. + if (ctrl->state != SSAM_CONTROLLER_STARTED) {
  10151. + ssam_controller_unlock(ctrl);
  10152. + return -EINVAL;
  10153. + }
  10154. +
  10155. + ssam_dbg(ctrl, "pm: suspending controller\n");
  10156. +
  10157. + /*
  10158. + * Set state via write_once even though we're locked, due to
  10159. + * smoke-testing in ssam_request_sync_submit().
  10160. + */
  10161. + WRITE_ONCE(ctrl->state, SSAM_CONTROLLER_SUSPENDED);
  10162. +
  10163. + ssam_controller_unlock(ctrl);
  10164. + return 0;
  10165. +}
  10166. +
  10167. +/**
  10168. + * ssam_controller_resume() - Resume the controller from suspend.
  10169. + * @ctrl: The controller to resume.
  10170. + *
  10171. + * Resume the controller from the suspended state it was put into via
  10172. + * ssam_controller_suspend(). This function does not issue display-on and
  10173. + * D0-entry notifications. If required, those have to be sent manually after
  10174. + * this call.
  10175. + *
  10176. + * Return: Returns %-EINVAL if the controller is currently not suspended.
  10177. + */
  10178. +int ssam_controller_resume(struct ssam_controller *ctrl)
  10179. +{
  10180. + ssam_controller_lock(ctrl);
  10181. +
  10182. + if (ctrl->state != SSAM_CONTROLLER_SUSPENDED) {
  10183. + ssam_controller_unlock(ctrl);
  10184. + return -EINVAL;
  10185. + }
  10186. +
  10187. + ssam_dbg(ctrl, "pm: resuming controller\n");
  10188. +
  10189. + /*
  10190. + * Set state via write_once even though we're locked, due to
  10191. + * smoke-testing in ssam_request_sync_submit().
  10192. + */
  10193. + WRITE_ONCE(ctrl->state, SSAM_CONTROLLER_STARTED);
  10194. +
  10195. + ssam_controller_unlock(ctrl);
  10196. + return 0;
  10197. +}
  10198. +
  10199. +
  10200. +/* -- Top-level request interface ------------------------------------------- */
  10201. +
  10202. +/**
  10203. + * ssam_request_write_data() - Construct and write SAM request message to
  10204. + * buffer.
  10205. + * @buf: The buffer to write the data to.
  10206. + * @ctrl: The controller via which the request will be sent.
  10207. + * @spec: The request data and specification.
  10208. + *
  10209. + * Constructs a SAM/SSH request message and writes it to the provided buffer.
  10210. + * The request and transport counters, specifically RQID and SEQ, will be set
  10211. + * in this call. These counters are obtained from the controller. It is thus
  10212. + * only valid to send the resulting message via the controller specified here.
  10213. + *
  10214. + * For calculation of the required buffer size, refer to the
  10215. + * SSH_COMMAND_MESSAGE_LENGTH() macro.
  10216. + *
  10217. + * Return: Returns the number of bytes used in the buffer on success. Returns
  10218. + * %-EINVAL if the payload length provided in the request specification is too
  10219. + * large (larger than %SSH_COMMAND_MAX_PAYLOAD_SIZE) or if the provided buffer
  10220. + * is too small.
  10221. + */
  10222. +ssize_t ssam_request_write_data(struct ssam_span *buf,
  10223. + struct ssam_controller *ctrl,
  10224. + const struct ssam_request *spec)
  10225. +{
  10226. + struct msgbuf msgb;
  10227. + u16 rqid;
  10228. + u8 seq;
  10229. +
  10230. + if (spec->length > SSH_COMMAND_MAX_PAYLOAD_SIZE)
  10231. + return -EINVAL;
  10232. +
  10233. + if (SSH_COMMAND_MESSAGE_LENGTH(spec->length) > buf->len)
  10234. + return -EINVAL;
  10235. +
  10236. + msgb_init(&msgb, buf->ptr, buf->len);
  10237. + seq = ssh_seq_next(&ctrl->counter.seq);
  10238. + rqid = ssh_rqid_next(&ctrl->counter.rqid);
  10239. + msgb_push_cmd(&msgb, seq, rqid, spec);
  10240. +
  10241. + return msgb_bytes_used(&msgb);
  10242. +}
  10243. +EXPORT_SYMBOL_GPL(ssam_request_write_data);
  10244. +
  10245. +static void ssam_request_sync_complete(struct ssh_request *rqst,
  10246. + const struct ssh_command *cmd,
  10247. + const struct ssam_span *data, int status)
  10248. +{
  10249. + struct ssh_rtl *rtl = ssh_request_rtl(rqst);
  10250. + struct ssam_request_sync *r;
  10251. +
  10252. + r = container_of(rqst, struct ssam_request_sync, base);
  10253. + r->status = status;
  10254. +
  10255. + if (r->resp)
  10256. + r->resp->length = 0;
  10257. +
  10258. + if (status) {
  10259. + rtl_dbg_cond(rtl, "rsp: request failed: %d\n", status);
  10260. + return;
  10261. + }
  10262. +
  10263. + if (!data) /* Handle requests without a response. */
  10264. + return;
  10265. +
  10266. + if (!r->resp || !r->resp->pointer) {
  10267. + if (data->len)
  10268. + rtl_warn(rtl, "rsp: no response buffer provided, dropping data\n");
  10269. + return;
  10270. + }
  10271. +
  10272. + if (data->len > r->resp->capacity) {
  10273. + rtl_err(rtl,
  10274. + "rsp: response buffer too small, capacity: %zu bytes, got: %zu bytes\n",
  10275. + r->resp->capacity, data->len);
  10276. + r->status = -ENOSPC;
  10277. + return;
  10278. + }
  10279. +
  10280. + r->resp->length = data->len;
  10281. + memcpy(r->resp->pointer, data->ptr, data->len);
  10282. +}
  10283. +
  10284. +static void ssam_request_sync_release(struct ssh_request *rqst)
  10285. +{
  10286. + complete_all(&container_of(rqst, struct ssam_request_sync, base)->comp);
  10287. +}
  10288. +
  10289. +static const struct ssh_request_ops ssam_request_sync_ops = {
  10290. + .release = ssam_request_sync_release,
  10291. + .complete = ssam_request_sync_complete,
  10292. +};
  10293. +
  10294. +/**
  10295. + * ssam_request_sync_alloc() - Allocate a synchronous request.
  10296. + * @payload_len: The length of the request payload.
  10297. + * @flags: Flags used for allocation.
  10298. + * @rqst: Where to store the pointer to the allocated request.
  10299. + * @buffer: Where to store the buffer descriptor for the message buffer of
  10300. + * the request.
  10301. + *
  10302. + * Allocates a synchronous request with corresponding message buffer. The
  10303. + * request still needs to be initialized ssam_request_sync_init() before
  10304. + * it can be submitted, and the message buffer data must still be set to the
  10305. + * returned buffer via ssam_request_sync_set_data() after it has been filled,
  10306. + * if need be with adjusted message length.
  10307. + *
  10308. + * After use, the request and its corresponding message buffer should be freed
  10309. + * via ssam_request_sync_free(). The buffer must not be freed separately.
  10310. + *
  10311. + * Return: Returns zero on success, %-ENOMEM if the request could not be
  10312. + * allocated.
  10313. + */
  10314. +int ssam_request_sync_alloc(size_t payload_len, gfp_t flags,
  10315. + struct ssam_request_sync **rqst,
  10316. + struct ssam_span *buffer)
  10317. +{
  10318. + size_t msglen = SSH_COMMAND_MESSAGE_LENGTH(payload_len);
  10319. +
  10320. + *rqst = kzalloc(sizeof(**rqst) + msglen, flags);
  10321. + if (!*rqst)
  10322. + return -ENOMEM;
  10323. +
  10324. + buffer->ptr = (u8 *)(*rqst + 1);
  10325. + buffer->len = msglen;
  10326. +
  10327. + return 0;
  10328. +}
  10329. +EXPORT_SYMBOL_GPL(ssam_request_sync_alloc);
  10330. +
  10331. +/**
  10332. + * ssam_request_sync_free() - Free a synchronous request.
  10333. + * @rqst: The request to be freed.
  10334. + *
  10335. + * Free a synchronous request and its corresponding buffer allocated with
  10336. + * ssam_request_sync_alloc(). Do not use for requests allocated on the stack
  10337. + * or via any other function.
  10338. + *
  10339. + * Warning: The caller must ensure that the request is not in use any more.
  10340. + * I.e. the caller must ensure that it has the only reference to the request
  10341. + * and the request is not currently pending. This means that the caller has
  10342. + * either never submitted the request, request submission has failed, or the
  10343. + * caller has waited until the submitted request has been completed via
  10344. + * ssam_request_sync_wait().
  10345. + */
  10346. +void ssam_request_sync_free(struct ssam_request_sync *rqst)
  10347. +{
  10348. + kfree(rqst);
  10349. +}
  10350. +EXPORT_SYMBOL_GPL(ssam_request_sync_free);
  10351. +
  10352. +/**
  10353. + * ssam_request_sync_init() - Initialize a synchronous request struct.
  10354. + * @rqst: The request to initialize.
  10355. + * @flags: The request flags.
  10356. + *
  10357. + * Initializes the given request struct. Does not initialize the request
  10358. + * message data. This has to be done explicitly after this call via
  10359. + * ssam_request_sync_set_data() and the actual message data has to be written
  10360. + * via ssam_request_write_data().
  10361. + *
  10362. + * Return: Returns zero on success or %-EINVAL if the given flags are invalid.
  10363. + */
  10364. +int ssam_request_sync_init(struct ssam_request_sync *rqst,
  10365. + enum ssam_request_flags flags)
  10366. +{
  10367. + int status;
  10368. +
  10369. + status = ssh_request_init(&rqst->base, flags, &ssam_request_sync_ops);
  10370. + if (status)
  10371. + return status;
  10372. +
  10373. + init_completion(&rqst->comp);
  10374. + rqst->resp = NULL;
  10375. + rqst->status = 0;
  10376. +
  10377. + return 0;
  10378. +}
  10379. +EXPORT_SYMBOL_GPL(ssam_request_sync_init);
  10380. +
  10381. +/**
  10382. + * ssam_request_sync_submit() - Submit a synchronous request.
  10383. + * @ctrl: The controller with which to submit the request.
  10384. + * @rqst: The request to submit.
  10385. + *
  10386. + * Submit a synchronous request. The request has to be initialized and
  10387. + * properly set up, including response buffer (may be %NULL if no response is
  10388. + * expected) and command message data. This function does not wait for the
  10389. + * request to be completed.
  10390. + *
  10391. + * If this function succeeds, ssam_request_sync_wait() must be used to ensure
  10392. + * that the request has been completed before the response data can be
  10393. + * accessed and/or the request can be freed. On failure, the request may
  10394. + * immediately be freed.
  10395. + *
  10396. + * This function may only be used if the controller is active, i.e. has been
  10397. + * initialized and not suspended.
  10398. + */
  10399. +int ssam_request_sync_submit(struct ssam_controller *ctrl,
  10400. + struct ssam_request_sync *rqst)
  10401. +{
  10402. + int status;
  10403. +
  10404. + /*
  10405. + * This is only a superficial check. In general, the caller needs to
  10406. + * ensure that the controller is initialized and is not (and does not
  10407. + * get) suspended during use, i.e. until the request has been completed
  10408. + * (if _absolutely_ necessary, by use of ssam_controller_statelock/
  10409. + * ssam_controller_stateunlock, but something like ssam_client_link
  10410. + * should be preferred as this needs to last until the request has been
  10411. + * completed).
  10412. + *
  10413. + * Note that it is actually safe to use this function while the
  10414. + * controller is in the process of being shut down (as ssh_rtl_submit
  10415. + * is safe with regards to this), but it is generally discouraged to do
  10416. + * so.
  10417. + */
  10418. + if (WARN_ON(READ_ONCE(ctrl->state) != SSAM_CONTROLLER_STARTED)) {
  10419. + ssh_request_put(&rqst->base);
  10420. + return -ENODEV;
  10421. + }
  10422. +
  10423. + status = ssh_rtl_submit(&ctrl->rtl, &rqst->base);
  10424. + ssh_request_put(&rqst->base);
  10425. +
  10426. + return status;
  10427. +}
  10428. +EXPORT_SYMBOL_GPL(ssam_request_sync_submit);
  10429. +
  10430. +/**
  10431. + * ssam_request_sync() - Execute a synchronous request.
  10432. + * @ctrl: The controller via which the request will be submitted.
  10433. + * @spec: The request specification and payload.
  10434. + * @rsp: The response buffer.
  10435. + *
  10436. + * Allocates a synchronous request with its message data buffer on the heap
  10437. + * via ssam_request_sync_alloc(), fully initializes it via the provided
  10438. + * request specification, submits it, and finally waits for its completion
  10439. + * before freeing it and returning its status.
  10440. + *
  10441. + * Return: Returns the status of the request or any failure during setup.
  10442. + */
  10443. +int ssam_request_sync(struct ssam_controller *ctrl,
  10444. + const struct ssam_request *spec,
  10445. + struct ssam_response *rsp)
  10446. +{
  10447. + struct ssam_request_sync *rqst;
  10448. + struct ssam_span buf;
  10449. + ssize_t len;
  10450. + int status;
  10451. +
  10452. + status = ssam_request_sync_alloc(spec->length, GFP_KERNEL, &rqst, &buf);
  10453. + if (status)
  10454. + return status;
  10455. +
  10456. + status = ssam_request_sync_init(rqst, spec->flags);
  10457. + if (status)
  10458. + return status;
  10459. +
  10460. + ssam_request_sync_set_resp(rqst, rsp);
  10461. +
  10462. + len = ssam_request_write_data(&buf, ctrl, spec);
  10463. + if (len < 0) {
  10464. + ssam_request_sync_free(rqst);
  10465. + return len;
  10466. + }
  10467. +
  10468. + ssam_request_sync_set_data(rqst, buf.ptr, len);
  10469. +
  10470. + status = ssam_request_sync_submit(ctrl, rqst);
  10471. + if (!status)
  10472. + status = ssam_request_sync_wait(rqst);
  10473. +
  10474. + ssam_request_sync_free(rqst);
  10475. + return status;
  10476. +}
  10477. +EXPORT_SYMBOL_GPL(ssam_request_sync);
  10478. +
  10479. +/**
  10480. + * ssam_request_sync_with_buffer() - Execute a synchronous request with the
  10481. + * provided buffer as back-end for the message buffer.
  10482. + * @ctrl: The controller via which the request will be submitted.
  10483. + * @spec: The request specification and payload.
  10484. + * @rsp: The response buffer.
  10485. + * @buf: The buffer for the request message data.
  10486. + *
  10487. + * Allocates a synchronous request struct on the stack, fully initializes it
  10488. + * using the provided buffer as message data buffer, submits it, and then
  10489. + * waits for its completion before returning its status. The
  10490. + * SSH_COMMAND_MESSAGE_LENGTH() macro can be used to compute the required
  10491. + * message buffer size.
  10492. + *
  10493. + * This function does essentially the same as ssam_request_sync(), but instead
  10494. + * of dynamically allocating the request and message data buffer, it uses the
  10495. + * provided message data buffer and stores the (small) request struct on the
  10496. + * heap.
  10497. + *
  10498. + * Return: Returns the status of the request or any failure during setup.
  10499. + */
  10500. +int ssam_request_sync_with_buffer(struct ssam_controller *ctrl,
  10501. + const struct ssam_request *spec,
  10502. + struct ssam_response *rsp,
  10503. + struct ssam_span *buf)
  10504. +{
  10505. + struct ssam_request_sync rqst;
  10506. + ssize_t len;
  10507. + int status;
  10508. +
  10509. + status = ssam_request_sync_init(&rqst, spec->flags);
  10510. + if (status)
  10511. + return status;
  10512. +
  10513. + ssam_request_sync_set_resp(&rqst, rsp);
  10514. +
  10515. + len = ssam_request_write_data(buf, ctrl, spec);
  10516. + if (len < 0)
  10517. + return len;
  10518. +
  10519. + ssam_request_sync_set_data(&rqst, buf->ptr, len);
  10520. +
  10521. + status = ssam_request_sync_submit(ctrl, &rqst);
  10522. + if (!status)
  10523. + status = ssam_request_sync_wait(&rqst);
  10524. +
  10525. + return status;
  10526. +}
  10527. +EXPORT_SYMBOL_GPL(ssam_request_sync_with_buffer);
  10528. +
  10529. +
  10530. +/* -- Internal SAM requests. ------------------------------------------------ */
  10531. +
  10532. +static SSAM_DEFINE_SYNC_REQUEST_R(ssam_ssh_get_firmware_version, __le32, {
  10533. + .target_category = SSAM_SSH_TC_SAM,
  10534. + .target_id = 0x01,
  10535. + .command_id = 0x13,
  10536. + .instance_id = 0x00,
  10537. +});
  10538. +
  10539. +static SSAM_DEFINE_SYNC_REQUEST_R(ssam_ssh_notif_display_off, u8, {
  10540. + .target_category = SSAM_SSH_TC_SAM,
  10541. + .target_id = 0x01,
  10542. + .command_id = 0x15,
  10543. + .instance_id = 0x00,
  10544. +});
  10545. +
  10546. +static SSAM_DEFINE_SYNC_REQUEST_R(ssam_ssh_notif_display_on, u8, {
  10547. + .target_category = SSAM_SSH_TC_SAM,
  10548. + .target_id = 0x01,
  10549. + .command_id = 0x16,
  10550. + .instance_id = 0x00,
  10551. +});
  10552. +
  10553. +static SSAM_DEFINE_SYNC_REQUEST_R(ssam_ssh_notif_d0_exit, u8, {
  10554. + .target_category = SSAM_SSH_TC_SAM,
  10555. + .target_id = 0x01,
  10556. + .command_id = 0x33,
  10557. + .instance_id = 0x00,
  10558. +});
  10559. +
  10560. +static SSAM_DEFINE_SYNC_REQUEST_R(ssam_ssh_notif_d0_entry, u8, {
  10561. + .target_category = SSAM_SSH_TC_SAM,
  10562. + .target_id = 0x01,
  10563. + .command_id = 0x34,
  10564. + .instance_id = 0x00,
  10565. +});
  10566. +
  10567. +/**
  10568. + * struct ssh_notification_params - Command payload to enable/disable SSH
  10569. + * notifications.
  10570. + * @target_category: The target category for which notifications should be
  10571. + * enabled/disabled.
  10572. + * @flags: Flags determining how notifications are being sent.
  10573. + * @request_id: The request ID that is used to send these notifications.
  10574. + * @instance_id: The specific instance in the given target category for
  10575. + * which notifications should be enabled.
  10576. + */
  10577. +struct ssh_notification_params {
  10578. + u8 target_category;
  10579. + u8 flags;
  10580. + __le16 request_id;
  10581. + u8 instance_id;
  10582. +} __packed;
  10583. +
  10584. +static_assert(sizeof(struct ssh_notification_params) == 5);
  10585. +
  10586. +static int __ssam_ssh_event_request(struct ssam_controller *ctrl,
  10587. + struct ssam_event_registry reg, u8 cid,
  10588. + struct ssam_event_id id, u8 flags)
  10589. +{
  10590. + struct ssh_notification_params params;
  10591. + struct ssam_request rqst;
  10592. + struct ssam_response result;
  10593. + int status;
  10594. +
  10595. + u16 rqid = ssh_tc_to_rqid(id.target_category);
  10596. + u8 buf = 0;
  10597. +
  10598. + /* Only allow RQIDs that lie within the event spectrum. */
  10599. + if (!ssh_rqid_is_event(rqid))
  10600. + return -EINVAL;
  10601. +
  10602. + params.target_category = id.target_category;
  10603. + params.instance_id = id.instance;
  10604. + params.flags = flags;
  10605. + put_unaligned_le16(rqid, &params.request_id);
  10606. +
  10607. + rqst.target_category = reg.target_category;
  10608. + rqst.target_id = reg.target_id;
  10609. + rqst.command_id = cid;
  10610. + rqst.instance_id = 0x00;
  10611. + rqst.flags = SSAM_REQUEST_HAS_RESPONSE;
  10612. + rqst.length = sizeof(params);
  10613. + rqst.payload = (u8 *)&params;
  10614. +
  10615. + result.capacity = sizeof(buf);
  10616. + result.length = 0;
  10617. + result.pointer = &buf;
  10618. +
  10619. + status = ssam_retry(ssam_request_sync_onstack, ctrl, &rqst, &result,
  10620. + sizeof(params));
  10621. +
  10622. + return status < 0 ? status : buf;
  10623. +}
  10624. +
  10625. +/**
  10626. + * ssam_ssh_event_enable() - Enable SSH event.
  10627. + * @ctrl: The controller for which to enable the event.
  10628. + * @reg: The event registry describing what request to use for enabling and
  10629. + * disabling the event.
  10630. + * @id: The event identifier.
  10631. + * @flags: The event flags.
  10632. + *
  10633. + * Enables the specified event on the EC. This function does not manage
  10634. + * reference counting of enabled events and is basically only a wrapper for
  10635. + * the raw EC request. If the specified event is already enabled, the EC will
  10636. + * ignore this request.
  10637. + *
  10638. + * Return: Returns the status of the executed SAM request (zero on success and
  10639. + * negative on direct failure) or %-EPROTO if the request response indicates a
  10640. + * failure.
  10641. + */
  10642. +static int ssam_ssh_event_enable(struct ssam_controller *ctrl,
  10643. + struct ssam_event_registry reg,
  10644. + struct ssam_event_id id, u8 flags)
  10645. +{
  10646. + int status;
  10647. +
  10648. + status = __ssam_ssh_event_request(ctrl, reg, reg.cid_enable, id, flags);
  10649. +
  10650. + if (status < 0 && status != -EINVAL) {
  10651. + ssam_err(ctrl,
  10652. + "failed to enable event source (tc: %#04x, iid: %#04x, reg: %#04x)\n",
  10653. + id.target_category, id.instance, reg.target_category);
  10654. + }
  10655. +
  10656. + if (status > 0) {
  10657. + ssam_err(ctrl,
  10658. + "unexpected result while enabling event source: %#04x (tc: %#04x, iid: %#04x, reg: %#04x)\n",
  10659. + status, id.target_category, id.instance, reg.target_category);
  10660. + return -EPROTO;
  10661. + }
  10662. +
  10663. + return status;
  10664. +}
  10665. +
  10666. +/**
  10667. + * ssam_ssh_event_disable() - Disable SSH event.
  10668. + * @ctrl: The controller for which to disable the event.
  10669. + * @reg: The event registry describing what request to use for enabling and
  10670. + * disabling the event (must be same as used when enabling the event).
  10671. + * @id: The event identifier.
  10672. + * @flags: The event flags (likely ignored for disabling of events).
  10673. + *
  10674. + * Disables the specified event on the EC. This function does not manage
  10675. + * reference counting of enabled events and is basically only a wrapper for
  10676. + * the raw EC request. If the specified event is already disabled, the EC will
  10677. + * ignore this request.
  10678. + *
  10679. + * Return: Returns the status of the executed SAM request (zero on success and
  10680. + * negative on direct failure) or %-EPROTO if the request response indicates a
  10681. + * failure.
  10682. + */
  10683. +static int ssam_ssh_event_disable(struct ssam_controller *ctrl,
  10684. + struct ssam_event_registry reg,
  10685. + struct ssam_event_id id, u8 flags)
  10686. +{
  10687. + int status;
  10688. +
  10689. + status = __ssam_ssh_event_request(ctrl, reg, reg.cid_enable, id, flags);
  10690. +
  10691. + if (status < 0 && status != -EINVAL) {
  10692. + ssam_err(ctrl,
  10693. + "failed to disable event source (tc: %#04x, iid: %#04x, reg: %#04x)\n",
  10694. + id.target_category, id.instance, reg.target_category);
  10695. + }
  10696. +
  10697. + if (status > 0) {
  10698. + ssam_err(ctrl,
  10699. + "unexpected result while disabling event source: %#04x (tc: %#04x, iid: %#04x, reg: %#04x)\n",
  10700. + status, id.target_category, id.instance, reg.target_category);
  10701. + return -EPROTO;
  10702. + }
  10703. +
  10704. + return status;
  10705. +}
  10706. +
  10707. +
  10708. +/* -- Wrappers for internal SAM requests. ----------------------------------- */
  10709. +
  10710. +/**
  10711. + * ssam_get_firmware_version() - Get the SAM/EC firmware version.
  10712. + * @ctrl: The controller.
  10713. + * @version: Where to store the version number.
  10714. + *
  10715. + * Return: Returns zero on success or the status of the executed SAM request
  10716. + * if that request failed.
  10717. + */
  10718. +int ssam_get_firmware_version(struct ssam_controller *ctrl, u32 *version)
  10719. +{
  10720. + __le32 __version;
  10721. + int status;
  10722. +
  10723. + status = ssam_retry(ssam_ssh_get_firmware_version, ctrl, &__version);
  10724. + if (status)
  10725. + return status;
  10726. +
  10727. + *version = le32_to_cpu(__version);
  10728. + return 0;
  10729. +}
  10730. +
  10731. +/**
  10732. + * ssam_ctrl_notif_display_off() - Notify EC that the display has been turned
  10733. + * off.
  10734. + * @ctrl: The controller.
  10735. + *
  10736. + * Notify the EC that the display has been turned off and the driver may enter
  10737. + * a lower-power state. This will prevent events from being sent directly.
  10738. + * Rather, the EC signals an event by pulling the wakeup GPIO high for as long
  10739. + * as there are pending events. The events then need to be manually released,
  10740. + * one by one, via the GPIO callback request. All pending events accumulated
  10741. + * during this state can also be released by issuing the display-on
  10742. + * notification, e.g. via ssam_ctrl_notif_display_on(), which will also reset
  10743. + * the GPIO.
  10744. + *
  10745. + * On some devices, specifically ones with an integrated keyboard, the keyboard
  10746. + * backlight will be turned off by this call.
  10747. + *
  10748. + * This function will only send the display-off notification command if
  10749. + * display notifications are supported by the EC. Currently all known devices
  10750. + * support these notifications.
  10751. + *
  10752. + * Use ssam_ctrl_notif_display_on() to reverse the effects of this function.
  10753. + *
  10754. + * Return: Returns zero on success or if no request has been executed, the
  10755. + * status of the executed SAM request if that request failed, or %-EPROTO if
  10756. + * an unexpected response has been received.
  10757. + */
  10758. +int ssam_ctrl_notif_display_off(struct ssam_controller *ctrl)
  10759. +{
  10760. + int status;
  10761. + u8 response;
  10762. +
  10763. + ssam_dbg(ctrl, "pm: notifying display off\n");
  10764. +
  10765. + status = ssam_retry(ssam_ssh_notif_display_off, ctrl, &response);
  10766. + if (status)
  10767. + return status;
  10768. +
  10769. + if (response != 0) {
  10770. + ssam_err(ctrl, "unexpected response from display-off notification: %#04x\n",
  10771. + response);
  10772. + return -EPROTO;
  10773. + }
  10774. +
  10775. + return 0;
  10776. +}
  10777. +
  10778. +/**
  10779. + * ssam_ctrl_notif_display_on() - Notify EC that the display has been turned on.
  10780. + * @ctrl: The controller.
  10781. + *
  10782. + * Notify the EC that the display has been turned back on and the driver has
  10783. + * exited its lower-power state. This notification is the counterpart to the
  10784. + * display-off notification sent via ssam_ctrl_notif_display_off() and will
  10785. + * reverse its effects, including resetting events to their default behavior.
  10786. + *
  10787. + * This function will only send the display-on notification command if display
  10788. + * notifications are supported by the EC. Currently all known devices support
  10789. + * these notifications.
  10790. + *
  10791. + * See ssam_ctrl_notif_display_off() for more details.
  10792. + *
  10793. + * Return: Returns zero on success or if no request has been executed, the
  10794. + * status of the executed SAM request if that request failed, or %-EPROTO if
  10795. + * an unexpected response has been received.
  10796. + */
  10797. +int ssam_ctrl_notif_display_on(struct ssam_controller *ctrl)
  10798. +{
  10799. + int status;
  10800. + u8 response;
  10801. +
  10802. + ssam_dbg(ctrl, "pm: notifying display on\n");
  10803. +
  10804. + status = ssam_retry(ssam_ssh_notif_display_on, ctrl, &response);
  10805. + if (status)
  10806. + return status;
  10807. +
  10808. + if (response != 0) {
  10809. + ssam_err(ctrl, "unexpected response from display-on notification: %#04x\n",
  10810. + response);
  10811. + return -EPROTO;
  10812. + }
  10813. +
  10814. + return 0;
  10815. +}
  10816. +
  10817. +/**
  10818. + * ssam_ctrl_notif_d0_exit() - Notify EC that the driver/device exits the D0
  10819. + * power state.
  10820. + * @ctrl: The controller
  10821. + *
  10822. + * Notifies the EC that the driver prepares to exit the D0 power state in
  10823. + * favor of a lower-power state. Exact effects of this function related to the
  10824. + * EC are currently unknown.
  10825. + *
  10826. + * This function will only send the D0-exit notification command if D0-state
  10827. + * notifications are supported by the EC. Only newer Surface generations
  10828. + * support these notifications.
  10829. + *
  10830. + * Use ssam_ctrl_notif_d0_entry() to reverse the effects of this function.
  10831. + *
  10832. + * Return: Returns zero on success or if no request has been executed, the
  10833. + * status of the executed SAM request if that request failed, or %-EPROTO if
  10834. + * an unexpected response has been received.
  10835. + */
  10836. +int ssam_ctrl_notif_d0_exit(struct ssam_controller *ctrl)
  10837. +{
  10838. + int status;
  10839. + u8 response;
  10840. +
  10841. + if (!ctrl->caps.d3_closes_handle)
  10842. + return 0;
  10843. +
  10844. + ssam_dbg(ctrl, "pm: notifying D0 exit\n");
  10845. +
  10846. + status = ssam_retry(ssam_ssh_notif_d0_exit, ctrl, &response);
  10847. + if (status)
  10848. + return status;
  10849. +
  10850. + if (response != 0) {
  10851. + ssam_err(ctrl, "unexpected response from D0-exit notification: %#04x\n",
  10852. + response);
  10853. + return -EPROTO;
  10854. + }
  10855. +
  10856. + return 0;
  10857. +}
  10858. +
  10859. +/**
  10860. + * ssam_ctrl_notif_d0_entry() - Notify EC that the driver/device enters the D0
  10861. + * power state.
  10862. + * @ctrl: The controller
  10863. + *
  10864. + * Notifies the EC that the driver has exited a lower-power state and entered
  10865. + * the D0 power state. Exact effects of this function related to the EC are
  10866. + * currently unknown.
  10867. + *
  10868. + * This function will only send the D0-entry notification command if D0-state
  10869. + * notifications are supported by the EC. Only newer Surface generations
  10870. + * support these notifications.
  10871. + *
  10872. + * See ssam_ctrl_notif_d0_exit() for more details.
  10873. + *
  10874. + * Return: Returns zero on success or if no request has been executed, the
  10875. + * status of the executed SAM request if that request failed, or %-EPROTO if
  10876. + * an unexpected response has been received.
  10877. + */
  10878. +int ssam_ctrl_notif_d0_entry(struct ssam_controller *ctrl)
  10879. +{
  10880. + int status;
  10881. + u8 response;
  10882. +
  10883. + if (!ctrl->caps.d3_closes_handle)
  10884. + return 0;
  10885. +
  10886. + ssam_dbg(ctrl, "pm: notifying D0 entry\n");
  10887. +
  10888. + status = ssam_retry(ssam_ssh_notif_d0_entry, ctrl, &response);
  10889. + if (status)
  10890. + return status;
  10891. +
  10892. + if (response != 0) {
  10893. + ssam_err(ctrl, "unexpected response from D0-entry notification: %#04x\n",
  10894. + response);
  10895. + return -EPROTO;
  10896. + }
  10897. +
  10898. + return 0;
  10899. +}
  10900. +
  10901. +
  10902. +/* -- Top-level event registry interface. ----------------------------------- */
  10903. +
  10904. +/**
  10905. + * ssam_notifier_register() - Register an event notifier.
  10906. + * @ctrl: The controller to register the notifier on.
  10907. + * @n: The event notifier to register.
  10908. + *
  10909. + * Register an event notifier and increment the usage counter of the
  10910. + * associated SAM event. If the event was previously not enabled, it will be
  10911. + * enabled during this call.
  10912. + *
  10913. + * Return: Returns zero on success, %-ENOSPC if there have already been
  10914. + * %INT_MAX notifiers for the event ID/type associated with the notifier block
  10915. + * registered, %-ENOMEM if the corresponding event entry could not be
  10916. + * allocated. If this is the first time that a notifier block is registered
  10917. + * for the specific associated event, returns the status of the event-enable
  10918. + * EC-command.
  10919. + */
  10920. +int ssam_notifier_register(struct ssam_controller *ctrl,
  10921. + struct ssam_event_notifier *n)
  10922. +{
  10923. + u16 rqid = ssh_tc_to_rqid(n->event.id.target_category);
  10924. + struct ssam_nf_refcount_entry *entry;
  10925. + struct ssam_nf_head *nf_head;
  10926. + struct ssam_nf *nf;
  10927. + int status;
  10928. +
  10929. + if (!ssh_rqid_is_event(rqid))
  10930. + return -EINVAL;
  10931. +
  10932. + nf = &ctrl->cplt.event.notif;
  10933. + nf_head = &nf->head[ssh_rqid_to_event(rqid)];
  10934. +
  10935. + mutex_lock(&nf->lock);
  10936. +
  10937. + entry = ssam_nf_refcount_inc(nf, n->event.reg, n->event.id);
  10938. + if (IS_ERR(entry)) {
  10939. + mutex_unlock(&nf->lock);
  10940. + return PTR_ERR(entry);
  10941. + }
  10942. +
  10943. + ssam_dbg(ctrl, "enabling event (reg: %#04x, tc: %#04x, iid: %#04x, rc: %d)\n",
  10944. + n->event.reg.target_category, n->event.id.target_category,
  10945. + n->event.id.instance, entry->refcount);
  10946. +
  10947. + status = ssam_nfblk_insert(nf_head, &n->base);
  10948. + if (status) {
  10949. + entry = ssam_nf_refcount_dec(nf, n->event.reg, n->event.id);
  10950. + if (entry->refcount == 0)
  10951. + kfree(entry);
  10952. +
  10953. + mutex_unlock(&nf->lock);
  10954. + return status;
  10955. + }
  10956. +
  10957. + if (entry->refcount == 1) {
  10958. + status = ssam_ssh_event_enable(ctrl, n->event.reg, n->event.id,
  10959. + n->event.flags);
  10960. + if (status) {
  10961. + ssam_nfblk_remove(&n->base);
  10962. + kfree(ssam_nf_refcount_dec(nf, n->event.reg, n->event.id));
  10963. + mutex_unlock(&nf->lock);
  10964. + synchronize_srcu(&nf_head->srcu);
  10965. + return status;
  10966. + }
  10967. +
  10968. + entry->flags = n->event.flags;
  10969. +
  10970. + } else if (entry->flags != n->event.flags) {
  10971. + ssam_warn(ctrl,
  10972. + "inconsistent flags when enabling event: got %#04x, expected %#04x (reg: %#04x, tc: %#04x, iid: %#04x)\n",
  10973. + n->event.flags, entry->flags, n->event.reg.target_category,
  10974. + n->event.id.target_category, n->event.id.instance);
  10975. + }
  10976. +
  10977. + mutex_unlock(&nf->lock);
  10978. + return 0;
  10979. +}
  10980. +EXPORT_SYMBOL_GPL(ssam_notifier_register);
  10981. +
  10982. +/**
  10983. + * ssam_notifier_unregister() - Unregister an event notifier.
  10984. + * @ctrl: The controller the notifier has been registered on.
  10985. + * @n: The event notifier to unregister.
  10986. + *
  10987. + * Unregister an event notifier and decrement the usage counter of the
  10988. + * associated SAM event. If the usage counter reaches zero, the event will be
  10989. + * disabled.
  10990. + *
  10991. + * Return: Returns zero on success, %-ENOENT if the given notifier block has
  10992. + * not been registered on the controller. If the given notifier block was the
  10993. + * last one associated with its specific event, returns the status of the
  10994. + * event-disable EC-command.
  10995. + */
  10996. +int ssam_notifier_unregister(struct ssam_controller *ctrl,
  10997. + struct ssam_event_notifier *n)
  10998. +{
  10999. + u16 rqid = ssh_tc_to_rqid(n->event.id.target_category);
  11000. + struct ssam_nf_refcount_entry *entry;
  11001. + struct ssam_nf_head *nf_head;
  11002. + struct ssam_nf *nf;
  11003. + int status = 0;
  11004. +
  11005. + if (!ssh_rqid_is_event(rqid))
  11006. + return -EINVAL;
  11007. +
  11008. + nf = &ctrl->cplt.event.notif;
  11009. + nf_head = &nf->head[ssh_rqid_to_event(rqid)];
  11010. +
  11011. + mutex_lock(&nf->lock);
  11012. +
  11013. + if (!ssam_nfblk_find(nf_head, &n->base)) {
  11014. + mutex_unlock(&nf->lock);
  11015. + return -ENOENT;
  11016. + }
  11017. +
  11018. + entry = ssam_nf_refcount_dec(nf, n->event.reg, n->event.id);
  11019. + if (WARN_ON(!entry)) {
  11020. + /*
  11021. + * If this does not return an entry, there's a logic error
  11022. + * somewhere: The notifier block is registered, but the event
  11023. + * refcount entry is not there. Remove the notifier block
  11024. + * anyways.
  11025. + */
  11026. + status = -ENOENT;
  11027. + goto remove;
  11028. + }
  11029. +
  11030. + ssam_dbg(ctrl, "disabling event (reg: %#04x, tc: %#04x, iid: %#04x, rc: %d)\n",
  11031. + n->event.reg.target_category, n->event.id.target_category,
  11032. + n->event.id.instance, entry->refcount);
  11033. +
  11034. + if (entry->flags != n->event.flags) {
  11035. + ssam_warn(ctrl,
  11036. + "inconsistent flags when disabling event: got %#04x, expected %#04x (reg: %#04x, tc: %#04x, iid: %#04x)\n",
  11037. + n->event.flags, entry->flags, n->event.reg.target_category,
  11038. + n->event.id.target_category, n->event.id.instance);
  11039. + }
  11040. +
  11041. + if (entry->refcount == 0) {
  11042. + status = ssam_ssh_event_disable(ctrl, n->event.reg, n->event.id,
  11043. + n->event.flags);
  11044. + kfree(entry);
  11045. + }
  11046. +
  11047. +remove:
  11048. + ssam_nfblk_remove(&n->base);
  11049. + mutex_unlock(&nf->lock);
  11050. + synchronize_srcu(&nf_head->srcu);
  11051. +
  11052. + return status;
  11053. +}
  11054. +EXPORT_SYMBOL_GPL(ssam_notifier_unregister);
  11055. +
  11056. +/**
  11057. + * ssam_notifier_disable_registered() - Disable events for all registered
  11058. + * notifiers.
  11059. + * @ctrl: The controller for which to disable the notifiers/events.
  11060. + *
  11061. + * Disables events for all currently registered notifiers. In case of an error
  11062. + * (EC command failing), all previously disabled events will be restored and
  11063. + * the error code returned.
  11064. + *
  11065. + * This function is intended to disable all events prior to hibernation entry.
  11066. + * See ssam_notifier_restore_registered() to restore/re-enable all events
  11067. + * disabled with this function.
  11068. + *
  11069. + * Note that this function will not disable events for notifiers registered
  11070. + * after calling this function. It should thus be made sure that no new
  11071. + * notifiers are going to be added after this call and before the corresponding
  11072. + * call to ssam_notifier_restore_registered().
  11073. + *
  11074. + * Return: Returns zero on success. In case of failure returns the error code
  11075. + * returned by the failed EC command to disable an event.
  11076. + */
  11077. +int ssam_notifier_disable_registered(struct ssam_controller *ctrl)
  11078. +{
  11079. + struct ssam_nf *nf = &ctrl->cplt.event.notif;
  11080. + struct rb_node *n;
  11081. + int status;
  11082. +
  11083. + mutex_lock(&nf->lock);
  11084. + for (n = rb_first(&nf->refcount); n; n = rb_next(n)) {
  11085. + struct ssam_nf_refcount_entry *e;
  11086. +
  11087. + e = rb_entry(n, struct ssam_nf_refcount_entry, node);
  11088. + status = ssam_ssh_event_disable(ctrl, e->key.reg,
  11089. + e->key.id, e->flags);
  11090. + if (status)
  11091. + goto err;
  11092. + }
  11093. + mutex_unlock(&nf->lock);
  11094. +
  11095. + return 0;
  11096. +
  11097. +err:
  11098. + for (n = rb_prev(n); n; n = rb_prev(n)) {
  11099. + struct ssam_nf_refcount_entry *e;
  11100. +
  11101. + e = rb_entry(n, struct ssam_nf_refcount_entry, node);
  11102. + ssam_ssh_event_enable(ctrl, e->key.reg, e->key.id, e->flags);
  11103. + }
  11104. + mutex_unlock(&nf->lock);
  11105. +
  11106. + return status;
  11107. +}
  11108. +
  11109. +/**
  11110. + * ssam_notifier_restore_registered() - Restore/re-enable events for all
  11111. + * registered notifiers.
  11112. + * @ctrl: The controller for which to restore the notifiers/events.
  11113. + *
  11114. + * Restores/re-enables all events for which notifiers have been registered on
  11115. + * the given controller. In case of a failure, the error is logged and the
  11116. + * function continues to try and enable the remaining events.
  11117. + *
  11118. + * This function is intended to restore/re-enable all registered events after
  11119. + * hibernation. See ssam_notifier_disable_registered() for the counter part
  11120. + * disabling the events and more details.
  11121. + */
  11122. +void ssam_notifier_restore_registered(struct ssam_controller *ctrl)
  11123. +{
  11124. + struct ssam_nf *nf = &ctrl->cplt.event.notif;
  11125. + struct rb_node *n;
  11126. +
  11127. + mutex_lock(&nf->lock);
  11128. + for (n = rb_first(&nf->refcount); n; n = rb_next(n)) {
  11129. + struct ssam_nf_refcount_entry *e;
  11130. +
  11131. + e = rb_entry(n, struct ssam_nf_refcount_entry, node);
  11132. +
  11133. + /* Ignore errors, will get logged in call. */
  11134. + ssam_ssh_event_enable(ctrl, e->key.reg, e->key.id, e->flags);
  11135. + }
  11136. + mutex_unlock(&nf->lock);
  11137. +}
  11138. +
  11139. +/**
  11140. + * ssam_notifier_is_empty() - Check if there are any registered notifiers.
  11141. + * @ctrl: The controller to check on.
  11142. + *
  11143. + * Return: Returns %true if there are currently no notifiers registered on the
  11144. + * controller, %false otherwise.
  11145. + */
  11146. +static bool ssam_notifier_is_empty(struct ssam_controller *ctrl)
  11147. +{
  11148. + struct ssam_nf *nf = &ctrl->cplt.event.notif;
  11149. + bool result;
  11150. +
  11151. + mutex_lock(&nf->lock);
  11152. + result = ssam_nf_refcount_empty(nf);
  11153. + mutex_unlock(&nf->lock);
  11154. +
  11155. + return result;
  11156. +}
  11157. +
  11158. +/**
  11159. + * ssam_notifier_unregister_all() - Unregister all currently registered
  11160. + * notifiers.
  11161. + * @ctrl: The controller to unregister the notifiers on.
  11162. + *
  11163. + * Unregisters all currently registered notifiers. This function is used to
  11164. + * ensure that all notifiers will be unregistered and associated
  11165. + * entries/resources freed when the controller is being shut down.
  11166. + */
  11167. +static void ssam_notifier_unregister_all(struct ssam_controller *ctrl)
  11168. +{
  11169. + struct ssam_nf *nf = &ctrl->cplt.event.notif;
  11170. + struct ssam_nf_refcount_entry *e, *n;
  11171. +
  11172. + mutex_lock(&nf->lock);
  11173. + rbtree_postorder_for_each_entry_safe(e, n, &nf->refcount, node) {
  11174. + /* Ignore errors, will get logged in call. */
  11175. + ssam_ssh_event_disable(ctrl, e->key.reg, e->key.id, e->flags);
  11176. + kfree(e);
  11177. + }
  11178. + nf->refcount = RB_ROOT;
  11179. + mutex_unlock(&nf->lock);
  11180. +}
  11181. +
  11182. +
  11183. +/* -- Wakeup IRQ. ----------------------------------------------------------- */
  11184. +
  11185. +static irqreturn_t ssam_irq_handle(int irq, void *dev_id)
  11186. +{
  11187. + struct ssam_controller *ctrl = dev_id;
  11188. +
  11189. + ssam_dbg(ctrl, "pm: wake irq triggered\n");
  11190. +
  11191. + /*
  11192. + * Note: Proper wakeup detection is currently unimplemented.
  11193. + * When the EC is in display-off or any other non-D0 state, it
  11194. + * does not send events/notifications to the host. Instead it
  11195. + * signals that there are events available via the wakeup IRQ.
  11196. + * This driver is responsible for calling back to the EC to
  11197. + * release these events one-by-one.
  11198. + *
  11199. + * This IRQ should not cause a full system resume by its own.
  11200. + * Instead, events should be handled by their respective subsystem
  11201. + * drivers, which in turn should signal whether a full system
  11202. + * resume should be performed.
  11203. + *
  11204. + * TODO: Send GPIO callback command repeatedly to EC until callback
  11205. + * returns 0x00. Return flag of callback is "has more events".
  11206. + * Each time the command is sent, one event is "released". Once
  11207. + * all events have been released (return = 0x00), the GPIO is
  11208. + * re-armed. Detect wakeup events during this process, go back to
  11209. + * sleep if no wakeup event has been received.
  11210. + */
  11211. +
  11212. + return IRQ_HANDLED;
  11213. +}
  11214. +
  11215. +/**
  11216. + * ssam_irq_setup() - Set up SAM EC wakeup-GPIO interrupt.
  11217. + * @ctrl: The controller for which the IRQ should be set up.
  11218. + *
  11219. + * Set up an IRQ for the wakeup-GPIO pin of the SAM EC. This IRQ can be used
  11220. + * to wake the device from a low power state.
  11221. + *
  11222. + * Note that this IRQ can only be triggered while the EC is in the display-off
  11223. + * state. In this state, events are not sent to the host in the usual way.
  11224. + * Instead the wakeup-GPIO gets pulled to "high" as long as there are pending
  11225. + * events and these events need to be released one-by-one via the GPIO
  11226. + * callback request, either until there are no events left and the GPIO is
  11227. + * reset, or all at once by transitioning the EC out of the display-off state,
  11228. + * which will also clear the GPIO.
  11229. + *
  11230. + * Not all events, however, should trigger a full system wakeup. Instead the
  11231. + * driver should, if necessary, inspect and forward each event to the
  11232. + * corresponding subsystem, which in turn should decide if the system needs to
  11233. + * be woken up. This logic has not been implemented yet, thus wakeup by this
  11234. + * IRQ should be disabled by default to avoid spurious wake-ups, caused, for
  11235. + * example, by the remaining battery percentage changing. Refer to comments in
  11236. + * this function and comments in the corresponding IRQ handler for more
  11237. + * details on how this should be implemented.
  11238. + *
  11239. + * See also ssam_ctrl_notif_display_off() and ssam_ctrl_notif_display_off()
  11240. + * for functions to transition the EC into and out of the display-off state as
  11241. + * well as more details on it.
  11242. + *
  11243. + * The IRQ is disabled by default and has to be enabled before it can wake up
  11244. + * the device from suspend via ssam_irq_arm_for_wakeup(). On teardown, the IRQ
  11245. + * should be freed via ssam_irq_free().
  11246. + */
  11247. +int ssam_irq_setup(struct ssam_controller *ctrl)
  11248. +{
  11249. + struct device *dev = ssam_controller_device(ctrl);
  11250. + struct gpio_desc *gpiod;
  11251. + int irq;
  11252. + int status;
  11253. +
  11254. + /*
  11255. + * The actual GPIO interrupt is declared in ACPI as TRIGGER_HIGH.
  11256. + * However, the GPIO line only gets reset by sending the GPIO callback
  11257. + * command to SAM (or alternatively the display-on notification). As
  11258. + * proper handling for this interrupt is not implemented yet, leaving
  11259. + * the IRQ at TRIGGER_HIGH would cause an IRQ storm (as the callback
  11260. + * never gets sent and thus the line never gets reset). To avoid this,
  11261. + * mark the IRQ as TRIGGER_RISING for now, only creating a single
  11262. + * interrupt, and let the SAM resume callback during the controller
  11263. + * resume process clear it.
  11264. + */
  11265. + const int irqf = IRQF_SHARED | IRQF_ONESHOT | IRQF_TRIGGER_RISING;
  11266. +
  11267. + gpiod = gpiod_get(dev, "ssam_wakeup-int", GPIOD_ASIS);
  11268. + if (IS_ERR(gpiod))
  11269. + return PTR_ERR(gpiod);
  11270. +
  11271. + irq = gpiod_to_irq(gpiod);
  11272. + gpiod_put(gpiod);
  11273. +
  11274. + if (irq < 0)
  11275. + return irq;
  11276. +
  11277. + status = request_threaded_irq(irq, NULL, ssam_irq_handle, irqf,
  11278. + "ssam_wakeup", ctrl);
  11279. + if (status)
  11280. + return status;
  11281. +
  11282. + ctrl->irq.num = irq;
  11283. + disable_irq(ctrl->irq.num);
  11284. + return 0;
  11285. +}
  11286. +
  11287. +/**
  11288. + * ssam_irq_free() - Free SAM EC wakeup-GPIO interrupt.
  11289. + * @ctrl: The controller for which the IRQ should be freed.
  11290. + *
  11291. + * Free the wakeup-GPIO IRQ previously set-up via ssam_irq_setup().
  11292. + */
  11293. +void ssam_irq_free(struct ssam_controller *ctrl)
  11294. +{
  11295. + free_irq(ctrl->irq.num, ctrl);
  11296. + ctrl->irq.num = -1;
  11297. +}
  11298. +
  11299. +/**
  11300. + * ssam_irq_arm_for_wakeup() - Arm the EC IRQ for wakeup, if enabled.
  11301. + * @ctrl: The controller for which the IRQ should be armed.
  11302. + *
  11303. + * Sets up the IRQ so that it can be used to wake the device. Specifically,
  11304. + * this function enables the irq and then, if the device is allowed to wake up
  11305. + * the system, calls enable_irq_wake(). See ssam_irq_disarm_wakeup() for the
  11306. + * corresponding function to disable the IRQ.
  11307. + *
  11308. + * This function is intended to arm the IRQ before entering S2idle suspend.
  11309. + *
  11310. + * Note: calls to ssam_irq_arm_for_wakeup() and ssam_irq_disarm_wakeup() must
  11311. + * be balanced.
  11312. + */
  11313. +int ssam_irq_arm_for_wakeup(struct ssam_controller *ctrl)
  11314. +{
  11315. + struct device *dev = ssam_controller_device(ctrl);
  11316. + int status;
  11317. +
  11318. + enable_irq(ctrl->irq.num);
  11319. + if (device_may_wakeup(dev)) {
  11320. + status = enable_irq_wake(ctrl->irq.num);
  11321. + if (status) {
  11322. + ssam_err(ctrl, "failed to enable wake IRQ: %d\n", status);
  11323. + disable_irq(ctrl->irq.num);
  11324. + return status;
  11325. + }
  11326. +
  11327. + ctrl->irq.wakeup_enabled = true;
  11328. + } else {
  11329. + ctrl->irq.wakeup_enabled = false;
  11330. + }
  11331. +
  11332. + return 0;
  11333. +}
  11334. +
  11335. +/**
  11336. + * ssam_irq_disarm_wakeup() - Disarm the wakeup IRQ.
  11337. + * @ctrl: The controller for which the IRQ should be disarmed.
  11338. + *
  11339. + * Disarm the IRQ previously set up for wake via ssam_irq_arm_for_wakeup().
  11340. + *
  11341. + * This function is intended to disarm the IRQ after exiting S2idle suspend.
  11342. + *
  11343. + * Note: calls to ssam_irq_arm_for_wakeup() and ssam_irq_disarm_wakeup() must
  11344. + * be balanced.
  11345. + */
  11346. +void ssam_irq_disarm_wakeup(struct ssam_controller *ctrl)
  11347. +{
  11348. + int status;
  11349. +
  11350. + if (ctrl->irq.wakeup_enabled) {
  11351. + status = disable_irq_wake(ctrl->irq.num);
  11352. + if (status)
  11353. + ssam_err(ctrl, "failed to disable wake IRQ: %d\n", status);
  11354. +
  11355. + ctrl->irq.wakeup_enabled = false;
  11356. + }
  11357. + disable_irq(ctrl->irq.num);
  11358. +}
  11359. diff --git a/drivers/misc/surface_aggregator/controller.h b/drivers/misc/surface_aggregator/controller.h
  11360. new file mode 100644
  11361. index 000000000000..8297d34e7489
  11362. --- /dev/null
  11363. +++ b/drivers/misc/surface_aggregator/controller.h
  11364. @@ -0,0 +1,285 @@
  11365. +/* SPDX-License-Identifier: GPL-2.0+ */
  11366. +/*
  11367. + * Main SSAM/SSH controller structure and functionality.
  11368. + *
  11369. + * Copyright (C) 2019-2020 Maximilian Luz <luzmaximilian@gmail.com>
  11370. + */
  11371. +
  11372. +#ifndef _SURFACE_AGGREGATOR_CONTROLLER_H
  11373. +#define _SURFACE_AGGREGATOR_CONTROLLER_H
  11374. +
  11375. +#include <linux/kref.h>
  11376. +#include <linux/list.h>
  11377. +#include <linux/mutex.h>
  11378. +#include <linux/rbtree.h>
  11379. +#include <linux/rwsem.h>
  11380. +#include <linux/serdev.h>
  11381. +#include <linux/spinlock.h>
  11382. +#include <linux/srcu.h>
  11383. +#include <linux/types.h>
  11384. +#include <linux/workqueue.h>
  11385. +
  11386. +#include <linux/surface_aggregator/controller.h>
  11387. +#include <linux/surface_aggregator/serial_hub.h>
  11388. +
  11389. +#include "ssh_request_layer.h"
  11390. +
  11391. +
  11392. +/* -- Safe counters. -------------------------------------------------------- */
  11393. +
  11394. +/**
  11395. + * struct ssh_seq_counter - Safe counter for SSH sequence IDs.
  11396. + * @value: The current counter value.
  11397. + */
  11398. +struct ssh_seq_counter {
  11399. + u8 value;
  11400. +};
  11401. +
  11402. +/**
  11403. + * struct ssh_rqid_counter - Safe counter for SSH request IDs.
  11404. + * @value: The current counter value.
  11405. + */
  11406. +struct ssh_rqid_counter {
  11407. + u16 value;
  11408. +};
  11409. +
  11410. +
  11411. +/* -- Event/notification system. -------------------------------------------- */
  11412. +
  11413. +/**
  11414. + * struct ssam_nf_head - Notifier head for SSAM events.
  11415. + * @srcu: The SRCU struct for synchronization.
  11416. + * @head: List-head for notifier blocks registered under this head.
  11417. + */
  11418. +struct ssam_nf_head {
  11419. + struct srcu_struct srcu;
  11420. + struct list_head head;
  11421. +};
  11422. +
  11423. +/**
  11424. + * struct ssam_nf - Notifier callback- and activation-registry for SSAM events.
  11425. + * @lock: Lock guarding (de-)registration of notifier blocks. Note: This
  11426. + * lock does not need to be held for notifier calls, only
  11427. + * registration and deregistration.
  11428. + * @refcount: The root of the RB-tree used for reference-counting enabled
  11429. + * events/notifications.
  11430. + * @head: The list of notifier heads for event/notification callbacks.
  11431. + */
  11432. +struct ssam_nf {
  11433. + struct mutex lock;
  11434. + struct rb_root refcount;
  11435. + struct ssam_nf_head head[SSH_NUM_EVENTS];
  11436. +};
  11437. +
  11438. +
  11439. +/* -- Event/async request completion system. -------------------------------- */
  11440. +
  11441. +struct ssam_cplt;
  11442. +
  11443. +/**
  11444. + * struct ssam_event_item - Struct for event queuing and completion.
  11445. + * @node: The node in the queue.
  11446. + * @rqid: The request ID of the event.
  11447. + * @ops: Instance specific functions.
  11448. + * @ops.free: Callback for freeing this event item.
  11449. + * @event: Actual event data.
  11450. + */
  11451. +struct ssam_event_item {
  11452. + struct list_head node;
  11453. + u16 rqid;
  11454. +
  11455. + struct {
  11456. + void (*free)(struct ssam_event_item *event);
  11457. + } ops;
  11458. +
  11459. + struct ssam_event event; /* must be last */
  11460. +};
  11461. +
  11462. +/**
  11463. + * struct ssam_event_queue - Queue for completing received events.
  11464. + * @cplt: Reference to the completion system on which this queue is active.
  11465. + * @lock: The lock for any operation on the queue.
  11466. + * @head: The list-head of the queue.
  11467. + * @work: The &struct work_struct performing completion work for this queue.
  11468. + */
  11469. +struct ssam_event_queue {
  11470. + struct ssam_cplt *cplt;
  11471. +
  11472. + spinlock_t lock;
  11473. + struct list_head head;
  11474. + struct work_struct work;
  11475. +};
  11476. +
  11477. +/**
  11478. + * struct ssam_event_target - Set of queues for a single SSH target ID.
  11479. + * @queue: The array of queues, one queue per event ID.
  11480. + */
  11481. +struct ssam_event_target {
  11482. + struct ssam_event_queue queue[SSH_NUM_EVENTS];
  11483. +};
  11484. +
  11485. +/**
  11486. + * struct ssam_cplt - SSAM event/async request completion system.
  11487. + * @dev: The device with which this system is associated. Only used
  11488. + * for logging.
  11489. + * @wq: The &struct workqueue_struct on which all completion work
  11490. + * items are queued.
  11491. + * @event: Event completion management.
  11492. + * @event.target: Array of &struct ssam_event_target, one for each target.
  11493. + * @event.notif: Notifier callbacks and event activation reference counting.
  11494. + */
  11495. +struct ssam_cplt {
  11496. + struct device *dev;
  11497. + struct workqueue_struct *wq;
  11498. +
  11499. + struct {
  11500. + struct ssam_event_target target[SSH_NUM_TARGETS];
  11501. + struct ssam_nf notif;
  11502. + } event;
  11503. +};
  11504. +
  11505. +
  11506. +/* -- Main SSAM device structures. ------------------------------------------ */
  11507. +
  11508. +/**
  11509. + * enum ssam_controller_state - State values for &struct ssam_controller.
  11510. + * @SSAM_CONTROLLER_UNINITIALIZED:
  11511. + * The controller has not been initialized yet or has been deinitialized.
  11512. + * @SSAM_CONTROLLER_INITIALIZED:
  11513. + * The controller is initialized, but has not been started yet.
  11514. + * @SSAM_CONTROLLER_STARTED:
  11515. + * The controller has been started and is ready to use.
  11516. + * @SSAM_CONTROLLER_STOPPED:
  11517. + * The controller has been stopped.
  11518. + * @SSAM_CONTROLLER_SUSPENDED:
  11519. + * The controller has been suspended.
  11520. + */
  11521. +enum ssam_controller_state {
  11522. + SSAM_CONTROLLER_UNINITIALIZED,
  11523. + SSAM_CONTROLLER_INITIALIZED,
  11524. + SSAM_CONTROLLER_STARTED,
  11525. + SSAM_CONTROLLER_STOPPED,
  11526. + SSAM_CONTROLLER_SUSPENDED,
  11527. +};
  11528. +
  11529. +/**
  11530. + * struct ssam_controller_caps - Controller device capabilities.
  11531. + * @ssh_power_profile: SSH power profile.
  11532. + * @ssh_buffer_size: SSH driver UART buffer size.
  11533. + * @screen_on_sleep_idle_timeout: SAM UART screen-on sleep idle timeout.
  11534. + * @screen_off_sleep_idle_timeout: SAM UART screen-off sleep idle timeout.
  11535. + * @d3_closes_handle: SAM closes UART handle in D3.
  11536. + *
  11537. + * Controller and SSH device capabilities found in ACPI.
  11538. + */
  11539. +struct ssam_controller_caps {
  11540. + u32 ssh_power_profile;
  11541. + u32 ssh_buffer_size;
  11542. + u32 screen_on_sleep_idle_timeout;
  11543. + u32 screen_off_sleep_idle_timeout;
  11544. + u32 d3_closes_handle:1;
  11545. +};
  11546. +
  11547. +/**
  11548. + * struct ssam_controller - SSAM controller device.
  11549. + * @kref: Reference count of the controller.
  11550. + * @lock: Main lock for the controller, used to guard state changes.
  11551. + * @state: Controller state.
  11552. + * @rtl: Request transport layer for SSH I/O.
  11553. + * @cplt: Completion system for SSH/SSAM events and asynchronous requests.
  11554. + * @counter: Safe SSH message ID counters.
  11555. + * @counter.seq: Sequence ID counter.
  11556. + * @counter.rqid: Request ID counter.
  11557. + * @irq: Wakeup IRQ resources.
  11558. + * @irq.num: The wakeup IRQ number.
  11559. + * @irq.wakeup_enabled: Whether wakeup by IRQ is enabled during suspend.
  11560. + * @caps: The controller device capabilities.
  11561. + */
  11562. +struct ssam_controller {
  11563. + struct kref kref;
  11564. +
  11565. + struct rw_semaphore lock;
  11566. + enum ssam_controller_state state;
  11567. +
  11568. + struct ssh_rtl rtl;
  11569. + struct ssam_cplt cplt;
  11570. +
  11571. + struct {
  11572. + struct ssh_seq_counter seq;
  11573. + struct ssh_rqid_counter rqid;
  11574. + } counter;
  11575. +
  11576. + struct {
  11577. + int num;
  11578. + bool wakeup_enabled;
  11579. + } irq;
  11580. +
  11581. + struct ssam_controller_caps caps;
  11582. +};
  11583. +
  11584. +#define to_ssam_controller(ptr, member) \
  11585. + container_of(ptr, struct ssam_controller, member)
  11586. +
  11587. +#define ssam_dbg(ctrl, fmt, ...) rtl_dbg(&(ctrl)->rtl, fmt, ##__VA_ARGS__)
  11588. +#define ssam_info(ctrl, fmt, ...) rtl_info(&(ctrl)->rtl, fmt, ##__VA_ARGS__)
  11589. +#define ssam_warn(ctrl, fmt, ...) rtl_warn(&(ctrl)->rtl, fmt, ##__VA_ARGS__)
  11590. +#define ssam_err(ctrl, fmt, ...) rtl_err(&(ctrl)->rtl, fmt, ##__VA_ARGS__)
  11591. +
  11592. +/**
  11593. + * ssam_controller_receive_buf() - Provide input-data to the controller.
  11594. + * @ctrl: The controller.
  11595. + * @buf: The input buffer.
  11596. + * @n: The number of bytes in the input buffer.
  11597. + *
  11598. + * Provide input data to be evaluated by the controller, which has been
  11599. + * received via the lower-level transport.
  11600. + *
  11601. + * Return: Returns the number of bytes consumed, or, if the packet transport
  11602. + * layer of the controller has been shut down, %-ESHUTDOWN.
  11603. + */
  11604. +static inline
  11605. +int ssam_controller_receive_buf(struct ssam_controller *ctrl,
  11606. + const unsigned char *buf, size_t n)
  11607. +{
  11608. + return ssh_ptl_rx_rcvbuf(&ctrl->rtl.ptl, buf, n);
  11609. +}
  11610. +
  11611. +/**
  11612. + * ssam_controller_write_wakeup() - Notify the controller that the underlying
  11613. + * device has space available for data to be written.
  11614. + * @ctrl: The controller.
  11615. + */
  11616. +static inline void ssam_controller_write_wakeup(struct ssam_controller *ctrl)
  11617. +{
  11618. + ssh_ptl_tx_wakeup_transfer(&ctrl->rtl.ptl);
  11619. +}
  11620. +
  11621. +int ssam_controller_init(struct ssam_controller *ctrl, struct serdev_device *s);
  11622. +int ssam_controller_start(struct ssam_controller *ctrl);
  11623. +void ssam_controller_shutdown(struct ssam_controller *ctrl);
  11624. +void ssam_controller_destroy(struct ssam_controller *ctrl);
  11625. +
  11626. +int ssam_notifier_disable_registered(struct ssam_controller *ctrl);
  11627. +void ssam_notifier_restore_registered(struct ssam_controller *ctrl);
  11628. +
  11629. +int ssam_irq_setup(struct ssam_controller *ctrl);
  11630. +void ssam_irq_free(struct ssam_controller *ctrl);
  11631. +int ssam_irq_arm_for_wakeup(struct ssam_controller *ctrl);
  11632. +void ssam_irq_disarm_wakeup(struct ssam_controller *ctrl);
  11633. +
  11634. +void ssam_controller_lock(struct ssam_controller *c);
  11635. +void ssam_controller_unlock(struct ssam_controller *c);
  11636. +
  11637. +int ssam_get_firmware_version(struct ssam_controller *ctrl, u32 *version);
  11638. +int ssam_ctrl_notif_display_off(struct ssam_controller *ctrl);
  11639. +int ssam_ctrl_notif_display_on(struct ssam_controller *ctrl);
  11640. +int ssam_ctrl_notif_d0_exit(struct ssam_controller *ctrl);
  11641. +int ssam_ctrl_notif_d0_entry(struct ssam_controller *ctrl);
  11642. +
  11643. +int ssam_controller_suspend(struct ssam_controller *ctrl);
  11644. +int ssam_controller_resume(struct ssam_controller *ctrl);
  11645. +
  11646. +int ssam_event_item_cache_init(void);
  11647. +void ssam_event_item_cache_destroy(void);
  11648. +
  11649. +#endif /* _SURFACE_AGGREGATOR_CONTROLLER_H */
  11650. diff --git a/drivers/misc/surface_aggregator/core.c b/drivers/misc/surface_aggregator/core.c
  11651. new file mode 100644
  11652. index 000000000000..b3e585484bc5
  11653. --- /dev/null
  11654. +++ b/drivers/misc/surface_aggregator/core.c
  11655. @@ -0,0 +1,840 @@
  11656. +// SPDX-License-Identifier: GPL-2.0+
  11657. +/*
  11658. + * Surface Serial Hub (SSH) driver for communication with the Surface/System
  11659. + * Aggregator Module (SSAM/SAM).
  11660. + *
  11661. + * Provides access to a SAM-over-SSH connected EC via a controller device.
  11662. + * Handles communication via requests as well as enabling, disabling, and
  11663. + * relaying of events.
  11664. + *
  11665. + * Copyright (C) 2019-2020 Maximilian Luz <luzmaximilian@gmail.com>
  11666. + */
  11667. +
  11668. +#include <linux/acpi.h>
  11669. +#include <linux/atomic.h>
  11670. +#include <linux/completion.h>
  11671. +#include <linux/gpio/consumer.h>
  11672. +#include <linux/kernel.h>
  11673. +#include <linux/kref.h>
  11674. +#include <linux/module.h>
  11675. +#include <linux/pm.h>
  11676. +#include <linux/serdev.h>
  11677. +#include <linux/sysfs.h>
  11678. +
  11679. +#include <linux/surface_aggregator/controller.h>
  11680. +
  11681. +#include "bus.h"
  11682. +#include "controller.h"
  11683. +
  11684. +#define CREATE_TRACE_POINTS
  11685. +#include "trace.h"
  11686. +
  11687. +
  11688. +/* -- Static controller reference. ------------------------------------------ */
  11689. +
  11690. +/*
  11691. + * Main controller reference. The corresponding lock must be held while
  11692. + * accessing (reading/writing) the reference.
  11693. + */
  11694. +static struct ssam_controller *__ssam_controller;
  11695. +static DEFINE_SPINLOCK(__ssam_controller_lock);
  11696. +
  11697. +/**
  11698. + * ssam_get_controller() - Get reference to SSAM controller.
  11699. + *
  11700. + * Returns a reference to the SSAM controller of the system or %NULL if there
  11701. + * is none, it hasn't been set up yet, or it has already been unregistered.
  11702. + * This function automatically increments the reference count of the
  11703. + * controller, thus the calling party must ensure that ssam_controller_put()
  11704. + * is called when it doesn't need the controller any more.
  11705. + */
  11706. +struct ssam_controller *ssam_get_controller(void)
  11707. +{
  11708. + struct ssam_controller *ctrl;
  11709. +
  11710. + spin_lock(&__ssam_controller_lock);
  11711. +
  11712. + ctrl = __ssam_controller;
  11713. + if (!ctrl)
  11714. + goto out;
  11715. +
  11716. + if (WARN_ON(!kref_get_unless_zero(&ctrl->kref)))
  11717. + ctrl = NULL;
  11718. +
  11719. +out:
  11720. + spin_unlock(&__ssam_controller_lock);
  11721. + return ctrl;
  11722. +}
  11723. +EXPORT_SYMBOL_GPL(ssam_get_controller);
  11724. +
  11725. +/**
  11726. + * ssam_try_set_controller() - Try to set the main controller reference.
  11727. + * @ctrl: The controller to which the reference should point.
  11728. + *
  11729. + * Set the main controller reference to the given pointer if the reference
  11730. + * hasn't been set already.
  11731. + *
  11732. + * Return: Returns zero on success or %-EEXIST if the reference has already
  11733. + * been set.
  11734. + */
  11735. +static int ssam_try_set_controller(struct ssam_controller *ctrl)
  11736. +{
  11737. + int status = 0;
  11738. +
  11739. + spin_lock(&__ssam_controller_lock);
  11740. + if (!__ssam_controller)
  11741. + __ssam_controller = ctrl;
  11742. + else
  11743. + status = -EEXIST;
  11744. + spin_unlock(&__ssam_controller_lock);
  11745. +
  11746. + return status;
  11747. +}
  11748. +
  11749. +/**
  11750. + * ssam_clear_controller() - Remove/clear the main controller reference.
  11751. + *
  11752. + * Clears the main controller reference, i.e. sets it to %NULL. This function
  11753. + * should be called before the controller is shut down.
  11754. + */
  11755. +static void ssam_clear_controller(void)
  11756. +{
  11757. + spin_lock(&__ssam_controller_lock);
  11758. + __ssam_controller = NULL;
  11759. + spin_unlock(&__ssam_controller_lock);
  11760. +}
  11761. +
  11762. +/**
  11763. + * ssam_client_link() - Link an arbitrary client device to the controller.
  11764. + * @c: The controller to link to.
  11765. + * @client: The client device.
  11766. + *
  11767. + * Link an arbitrary client device to the controller by creating a device link
  11768. + * between it as consumer and the controller device as provider. This function
  11769. + * can be used for non-SSAM devices (or SSAM devices not registered as child
  11770. + * under the controller) to guarantee that the controller is valid for as long
  11771. + * as the driver of the client device is bound, and that proper suspend and
  11772. + * resume ordering is guaranteed.
  11773. + *
  11774. + * The device link does not have to be destructed manually. It is removed
  11775. + * automatically once the driver of the client device unbinds.
  11776. + *
  11777. + * Return: Returns zero on success, %-ENODEV if the controller is not ready or
  11778. + * going to be removed soon, or %-ENOMEM if the device link could not be
  11779. + * created for other reasons.
  11780. + */
  11781. +int ssam_client_link(struct ssam_controller *c, struct device *client)
  11782. +{
  11783. + const u32 flags = DL_FLAG_PM_RUNTIME | DL_FLAG_AUTOREMOVE_CONSUMER;
  11784. + struct device_link *link;
  11785. + struct device *ctrldev;
  11786. +
  11787. + ssam_controller_statelock(c);
  11788. +
  11789. + if (c->state != SSAM_CONTROLLER_STARTED) {
  11790. + ssam_controller_stateunlock(c);
  11791. + return -ENODEV;
  11792. + }
  11793. +
  11794. + ctrldev = ssam_controller_device(c);
  11795. + if (!ctrldev) {
  11796. + ssam_controller_stateunlock(c);
  11797. + return -ENODEV;
  11798. + }
  11799. +
  11800. + link = device_link_add(client, ctrldev, flags);
  11801. + if (!link) {
  11802. + ssam_controller_stateunlock(c);
  11803. + return -ENOMEM;
  11804. + }
  11805. +
  11806. + /*
  11807. + * Return -ENODEV if supplier driver is on its way to be removed. In
  11808. + * this case, the controller won't be around for much longer and the
  11809. + * device link is not going to save us any more, as unbinding is
  11810. + * already in progress.
  11811. + */
  11812. + if (READ_ONCE(link->status) == DL_STATE_SUPPLIER_UNBIND) {
  11813. + ssam_controller_stateunlock(c);
  11814. + return -ENODEV;
  11815. + }
  11816. +
  11817. + ssam_controller_stateunlock(c);
  11818. + return 0;
  11819. +}
  11820. +EXPORT_SYMBOL_GPL(ssam_client_link);
  11821. +
  11822. +/**
  11823. + * ssam_client_bind() - Bind an arbitrary client device to the controller.
  11824. + * @client: The client device.
  11825. + *
  11826. + * Link an arbitrary client device to the controller by creating a device link
  11827. + * between it as consumer and the main controller device as provider. This
  11828. + * function can be used for non-SSAM devices to guarantee that the controller
  11829. + * returned by this function is valid for as long as the driver of the client
  11830. + * device is bound, and that proper suspend and resume ordering is guaranteed.
  11831. + *
  11832. + * This function does essentially the same as ssam_client_link(), except that
  11833. + * it first fetches the main controller reference, then creates the link, and
  11834. + * finally returns this reference. Note that this function does not increment
  11835. + * the reference counter of the controller, as, due to the link, the
  11836. + * controller lifetime is assured as long as the driver of the client device
  11837. + * is bound.
  11838. + *
  11839. + * It is not valid to use the controller reference obtained by this method
  11840. + * outside of the driver bound to the client device at the time of calling
  11841. + * this function, without first incrementing the reference count of the
  11842. + * controller via ssam_controller_get(). Even after doing this, care must be
  11843. + * taken that requests are only submitted and notifiers are only
  11844. + * (un-)registered when the controller is active and not suspended. In other
  11845. + * words: The device link only lives as long as the client driver is bound and
  11846. + * any guarantees enforced by this link (e.g. active controller state) can
  11847. + * only be relied upon as long as this link exists and may need to be enforced
  11848. + * in other ways afterwards.
  11849. + *
  11850. + * The created device link does not have to be destructed manually. It is
  11851. + * removed automatically once the driver of the client device unbinds.
  11852. + *
  11853. + * Return: Returns the controller on success, an error pointer with %-ENODEV
  11854. + * if the controller is not present, not ready or going to be removed soon, or
  11855. + * %-ENOMEM if the device link could not be created for other reasons.
  11856. + */
  11857. +struct ssam_controller *ssam_client_bind(struct device *client)
  11858. +{
  11859. + struct ssam_controller *c;
  11860. + int status;
  11861. +
  11862. + c = ssam_get_controller();
  11863. + if (!c)
  11864. + return ERR_PTR(-ENODEV);
  11865. +
  11866. + status = ssam_client_link(c, client);
  11867. +
  11868. + /*
  11869. + * Note that we can drop our controller reference in both success and
  11870. + * failure cases: On success, we have bound the controller lifetime
  11871. + * inherently to the client driver lifetime, i.e. it the controller is
  11872. + * now guaranteed to outlive the client driver. On failure, we're not
  11873. + * going to use the controller any more.
  11874. + */
  11875. + ssam_controller_put(c);
  11876. +
  11877. + return status >= 0 ? c : ERR_PTR(status);
  11878. +}
  11879. +EXPORT_SYMBOL_GPL(ssam_client_bind);
  11880. +
  11881. +
  11882. +/* -- Glue layer (serdev_device -> ssam_controller). ------------------------ */
  11883. +
  11884. +static int ssam_receive_buf(struct serdev_device *dev, const unsigned char *buf,
  11885. + size_t n)
  11886. +{
  11887. + struct ssam_controller *ctrl;
  11888. +
  11889. + ctrl = serdev_device_get_drvdata(dev);
  11890. + return ssam_controller_receive_buf(ctrl, buf, n);
  11891. +}
  11892. +
  11893. +static void ssam_write_wakeup(struct serdev_device *dev)
  11894. +{
  11895. + ssam_controller_write_wakeup(serdev_device_get_drvdata(dev));
  11896. +}
  11897. +
  11898. +static const struct serdev_device_ops ssam_serdev_ops = {
  11899. + .receive_buf = ssam_receive_buf,
  11900. + .write_wakeup = ssam_write_wakeup,
  11901. +};
  11902. +
  11903. +
  11904. +/* -- SysFS and misc. ------------------------------------------------------- */
  11905. +
  11906. +static int ssam_log_firmware_version(struct ssam_controller *ctrl)
  11907. +{
  11908. + u32 version, a, b, c;
  11909. + int status;
  11910. +
  11911. + status = ssam_get_firmware_version(ctrl, &version);
  11912. + if (status)
  11913. + return status;
  11914. +
  11915. + a = (version >> 24) & 0xff;
  11916. + b = ((version >> 8) & 0xffff);
  11917. + c = version & 0xff;
  11918. +
  11919. + ssam_info(ctrl, "SAM firmware version: %u.%u.%u\n", a, b, c);
  11920. + return 0;
  11921. +}
  11922. +
  11923. +static ssize_t firmware_version_show(struct device *dev,
  11924. + struct device_attribute *attr, char *buf)
  11925. +{
  11926. + struct ssam_controller *ctrl = dev_get_drvdata(dev);
  11927. + u32 version, a, b, c;
  11928. + int status;
  11929. +
  11930. + status = ssam_get_firmware_version(ctrl, &version);
  11931. + if (status < 0)
  11932. + return status;
  11933. +
  11934. + a = (version >> 24) & 0xff;
  11935. + b = ((version >> 8) & 0xffff);
  11936. + c = version & 0xff;
  11937. +
  11938. + // FIXME: we should use sysfs_emit here, but that's not available on < 5.10
  11939. + return scnprintf(buf, PAGE_SIZE, "%u.%u.%u\n", a, b, c);
  11940. +}
  11941. +static DEVICE_ATTR_RO(firmware_version);
  11942. +
  11943. +static struct attribute *ssam_sam_attrs[] = {
  11944. + &dev_attr_firmware_version.attr,
  11945. + NULL
  11946. +};
  11947. +
  11948. +static const struct attribute_group ssam_sam_group = {
  11949. + .name = "sam",
  11950. + .attrs = ssam_sam_attrs,
  11951. +};
  11952. +
  11953. +
  11954. +/* -- ACPI based device setup. ---------------------------------------------- */
  11955. +
  11956. +static acpi_status ssam_serdev_setup_via_acpi_crs(struct acpi_resource *rsc,
  11957. + void *ctx)
  11958. +{
  11959. + struct serdev_device *serdev = ctx;
  11960. + struct acpi_resource_common_serialbus *serial;
  11961. + struct acpi_resource_uart_serialbus *uart;
  11962. + bool flow_control;
  11963. + int status = 0;
  11964. +
  11965. + if (rsc->type != ACPI_RESOURCE_TYPE_SERIAL_BUS)
  11966. + return AE_OK;
  11967. +
  11968. + serial = &rsc->data.common_serial_bus;
  11969. + if (serial->type != ACPI_RESOURCE_SERIAL_TYPE_UART)
  11970. + return AE_OK;
  11971. +
  11972. + uart = &rsc->data.uart_serial_bus;
  11973. +
  11974. + /* Set up serdev device. */
  11975. + serdev_device_set_baudrate(serdev, uart->default_baud_rate);
  11976. +
  11977. + /* serdev currently only supports RTSCTS flow control. */
  11978. + if (uart->flow_control & (~((u8)ACPI_UART_FLOW_CONTROL_HW))) {
  11979. + dev_warn(&serdev->dev, "setup: unsupported flow control (value: %#04x)\n",
  11980. + uart->flow_control);
  11981. + }
  11982. +
  11983. + /* Set RTSCTS flow control. */
  11984. + flow_control = uart->flow_control & ACPI_UART_FLOW_CONTROL_HW;
  11985. + serdev_device_set_flow_control(serdev, flow_control);
  11986. +
  11987. + /* serdev currently only supports EVEN/ODD parity. */
  11988. + switch (uart->parity) {
  11989. + case ACPI_UART_PARITY_NONE:
  11990. + status = serdev_device_set_parity(serdev, SERDEV_PARITY_NONE);
  11991. + break;
  11992. + case ACPI_UART_PARITY_EVEN:
  11993. + status = serdev_device_set_parity(serdev, SERDEV_PARITY_EVEN);
  11994. + break;
  11995. + case ACPI_UART_PARITY_ODD:
  11996. + status = serdev_device_set_parity(serdev, SERDEV_PARITY_ODD);
  11997. + break;
  11998. + default:
  11999. + dev_warn(&serdev->dev, "setup: unsupported parity (value: %#04x)\n",
  12000. + uart->parity);
  12001. + break;
  12002. + }
  12003. +
  12004. + if (status) {
  12005. + dev_err(&serdev->dev, "setup: failed to set parity (value: %#04x, error: %d)\n",
  12006. + uart->parity, status);
  12007. + return AE_ERROR;
  12008. + }
  12009. +
  12010. + /* We've found the resource and are done. */
  12011. + return AE_CTRL_TERMINATE;
  12012. +}
  12013. +
  12014. +static acpi_status ssam_serdev_setup_via_acpi(acpi_handle handle,
  12015. + struct serdev_device *serdev)
  12016. +{
  12017. + return acpi_walk_resources(handle, METHOD_NAME__CRS,
  12018. + ssam_serdev_setup_via_acpi_crs, serdev);
  12019. +}
  12020. +
  12021. +
  12022. +/* -- Power management. ----------------------------------------------------- */
  12023. +
  12024. +static void ssam_serial_hub_shutdown(struct device *dev)
  12025. +{
  12026. + struct ssam_controller *c = dev_get_drvdata(dev);
  12027. + int status;
  12028. +
  12029. + /*
  12030. + * Try to disable notifiers, signal display-off and D0-exit, ignore any
  12031. + * errors.
  12032. + *
  12033. + * Note: It has not been established yet if this is actually
  12034. + * necessary/useful for shutdown.
  12035. + */
  12036. +
  12037. + status = ssam_notifier_disable_registered(c);
  12038. + if (status) {
  12039. + ssam_err(c, "pm: failed to disable notifiers for shutdown: %d\n",
  12040. + status);
  12041. + }
  12042. +
  12043. + status = ssam_ctrl_notif_display_off(c);
  12044. + if (status)
  12045. + ssam_err(c, "pm: display-off notification failed: %d\n", status);
  12046. +
  12047. + status = ssam_ctrl_notif_d0_exit(c);
  12048. + if (status)
  12049. + ssam_err(c, "pm: D0-exit notification failed: %d\n", status);
  12050. +}
  12051. +
  12052. +#ifdef CONFIG_PM_SLEEP
  12053. +
  12054. +static int ssam_serial_hub_pm_prepare(struct device *dev)
  12055. +{
  12056. + struct ssam_controller *c = dev_get_drvdata(dev);
  12057. + int status;
  12058. +
  12059. + /*
  12060. + * Try to signal display-off, This will quiesce events.
  12061. + *
  12062. + * Note: Signaling display-off/display-on should normally be done from
  12063. + * some sort of display state notifier. As that is not available,
  12064. + * signal it here.
  12065. + */
  12066. +
  12067. + status = ssam_ctrl_notif_display_off(c);
  12068. + if (status)
  12069. + ssam_err(c, "pm: display-off notification failed: %d\n", status);
  12070. +
  12071. + return status;
  12072. +}
  12073. +
  12074. +static void ssam_serial_hub_pm_complete(struct device *dev)
  12075. +{
  12076. + struct ssam_controller *c = dev_get_drvdata(dev);
  12077. + int status;
  12078. +
  12079. + /*
  12080. + * Try to signal display-on. This will restore events.
  12081. + *
  12082. + * Note: Signaling display-off/display-on should normally be done from
  12083. + * some sort of display state notifier. As that is not available,
  12084. + * signal it here.
  12085. + */
  12086. +
  12087. + status = ssam_ctrl_notif_display_on(c);
  12088. + if (status)
  12089. + ssam_err(c, "pm: display-on notification failed: %d\n", status);
  12090. +}
  12091. +
  12092. +static int ssam_serial_hub_pm_suspend(struct device *dev)
  12093. +{
  12094. + struct ssam_controller *c = dev_get_drvdata(dev);
  12095. + int status;
  12096. +
  12097. + /*
  12098. + * Try to signal D0-exit, enable IRQ wakeup if specified. Abort on
  12099. + * error.
  12100. + */
  12101. +
  12102. + status = ssam_ctrl_notif_d0_exit(c);
  12103. + if (status) {
  12104. + ssam_err(c, "pm: D0-exit notification failed: %d\n", status);
  12105. + goto err_notif;
  12106. + }
  12107. +
  12108. + status = ssam_irq_arm_for_wakeup(c);
  12109. + if (status)
  12110. + goto err_irq;
  12111. +
  12112. + WARN_ON(ssam_controller_suspend(c));
  12113. + return 0;
  12114. +
  12115. +err_irq:
  12116. + ssam_ctrl_notif_d0_entry(c);
  12117. +err_notif:
  12118. + ssam_ctrl_notif_display_on(c);
  12119. + return status;
  12120. +}
  12121. +
  12122. +static int ssam_serial_hub_pm_resume(struct device *dev)
  12123. +{
  12124. + struct ssam_controller *c = dev_get_drvdata(dev);
  12125. + int status;
  12126. +
  12127. + WARN_ON(ssam_controller_resume(c));
  12128. +
  12129. + /*
  12130. + * Try to disable IRQ wakeup (if specified) and signal D0-entry. In
  12131. + * case of errors, log them and try to restore normal operation state
  12132. + * as far as possible.
  12133. + *
  12134. + * Note: Signaling display-off/display-on should normally be done from
  12135. + * some sort of display state notifier. As that is not available,
  12136. + * signal it here.
  12137. + */
  12138. +
  12139. + ssam_irq_disarm_wakeup(c);
  12140. +
  12141. + status = ssam_ctrl_notif_d0_entry(c);
  12142. + if (status)
  12143. + ssam_err(c, "pm: D0-entry notification failed: %d\n", status);
  12144. +
  12145. + return 0;
  12146. +}
  12147. +
  12148. +static int ssam_serial_hub_pm_freeze(struct device *dev)
  12149. +{
  12150. + struct ssam_controller *c = dev_get_drvdata(dev);
  12151. + int status;
  12152. +
  12153. + /*
  12154. + * During hibernation image creation, we only have to ensure that the
  12155. + * EC doesn't send us any events. This is done via the display-off
  12156. + * and D0-exit notifications. Note that this sets up the wakeup IRQ
  12157. + * on the EC side, however, we have disabled it by default on our side
  12158. + * and won't enable it here.
  12159. + *
  12160. + * See ssam_serial_hub_poweroff() for more details on the hibernation
  12161. + * process.
  12162. + */
  12163. +
  12164. + status = ssam_ctrl_notif_d0_exit(c);
  12165. + if (status) {
  12166. + ssam_err(c, "pm: D0-exit notification failed: %d\n", status);
  12167. + ssam_ctrl_notif_display_on(c);
  12168. + return status;
  12169. + }
  12170. +
  12171. + WARN_ON(ssam_controller_suspend(c));
  12172. + return 0;
  12173. +}
  12174. +
  12175. +static int ssam_serial_hub_pm_thaw(struct device *dev)
  12176. +{
  12177. + struct ssam_controller *c = dev_get_drvdata(dev);
  12178. + int status;
  12179. +
  12180. + WARN_ON(ssam_controller_resume(c));
  12181. +
  12182. + status = ssam_ctrl_notif_d0_entry(c);
  12183. + if (status)
  12184. + ssam_err(c, "pm: D0-exit notification failed: %d\n", status);
  12185. +
  12186. + return status;
  12187. +}
  12188. +
  12189. +static int ssam_serial_hub_pm_poweroff(struct device *dev)
  12190. +{
  12191. + struct ssam_controller *c = dev_get_drvdata(dev);
  12192. + int status;
  12193. +
  12194. + /*
  12195. + * When entering hibernation and powering off the system, the EC, at
  12196. + * least on some models, may disable events. Without us taking care of
  12197. + * that, this leads to events not being enabled/restored when the
  12198. + * system resumes from hibernation, resulting SAM-HID subsystem devices
  12199. + * (i.e. keyboard, touchpad) not working, AC-plug/AC-unplug events being
  12200. + * gone, etc.
  12201. + *
  12202. + * To avoid these issues, we disable all registered events here (this is
  12203. + * likely not actually required) and restore them during the drivers PM
  12204. + * restore callback.
  12205. + *
  12206. + * Wakeup from the EC interrupt is not supported during hibernation,
  12207. + * so don't arm the IRQ here.
  12208. + */
  12209. +
  12210. + status = ssam_notifier_disable_registered(c);
  12211. + if (status) {
  12212. + ssam_err(c, "pm: failed to disable notifiers for hibernation: %d\n",
  12213. + status);
  12214. + return status;
  12215. + }
  12216. +
  12217. + status = ssam_ctrl_notif_d0_exit(c);
  12218. + if (status) {
  12219. + ssam_err(c, "pm: D0-exit notification failed: %d\n", status);
  12220. + ssam_notifier_restore_registered(c);
  12221. + return status;
  12222. + }
  12223. +
  12224. + WARN_ON(ssam_controller_suspend(c));
  12225. + return 0;
  12226. +}
  12227. +
  12228. +static int ssam_serial_hub_pm_restore(struct device *dev)
  12229. +{
  12230. + struct ssam_controller *c = dev_get_drvdata(dev);
  12231. + int status;
  12232. +
  12233. + /*
  12234. + * Ignore but log errors, try to restore state as much as possible in
  12235. + * case of failures. See ssam_serial_hub_poweroff() for more details on
  12236. + * the hibernation process.
  12237. + */
  12238. +
  12239. + WARN_ON(ssam_controller_resume(c));
  12240. +
  12241. + status = ssam_ctrl_notif_d0_entry(c);
  12242. + if (status)
  12243. + ssam_err(c, "pm: D0-entry notification failed: %d\n", status);
  12244. +
  12245. + ssam_notifier_restore_registered(c);
  12246. + return 0;
  12247. +}
  12248. +
  12249. +static const struct dev_pm_ops ssam_serial_hub_pm_ops = {
  12250. + .prepare = ssam_serial_hub_pm_prepare,
  12251. + .complete = ssam_serial_hub_pm_complete,
  12252. + .suspend = ssam_serial_hub_pm_suspend,
  12253. + .resume = ssam_serial_hub_pm_resume,
  12254. + .freeze = ssam_serial_hub_pm_freeze,
  12255. + .thaw = ssam_serial_hub_pm_thaw,
  12256. + .poweroff = ssam_serial_hub_pm_poweroff,
  12257. + .restore = ssam_serial_hub_pm_restore,
  12258. +};
  12259. +
  12260. +#else /* CONFIG_PM_SLEEP */
  12261. +
  12262. +static const struct dev_pm_ops ssam_serial_hub_pm_ops = { };
  12263. +
  12264. +#endif /* CONFIG_PM_SLEEP */
  12265. +
  12266. +
  12267. +/* -- Device/driver setup. -------------------------------------------------- */
  12268. +
  12269. +static const struct acpi_gpio_params gpio_ssam_wakeup_int = { 0, 0, false };
  12270. +static const struct acpi_gpio_params gpio_ssam_wakeup = { 1, 0, false };
  12271. +
  12272. +static const struct acpi_gpio_mapping ssam_acpi_gpios[] = {
  12273. + { "ssam_wakeup-int-gpio", &gpio_ssam_wakeup_int, 1 },
  12274. + { "ssam_wakeup-gpio", &gpio_ssam_wakeup, 1 },
  12275. + { },
  12276. +};
  12277. +
  12278. +static int ssam_serial_hub_probe(struct serdev_device *serdev)
  12279. +{
  12280. + struct ssam_controller *ctrl;
  12281. + acpi_handle *ssh = ACPI_HANDLE(&serdev->dev);
  12282. + acpi_status astatus;
  12283. + int status;
  12284. +
  12285. + if (gpiod_count(&serdev->dev, NULL) < 0)
  12286. + return -ENODEV;
  12287. +
  12288. + status = devm_acpi_dev_add_driver_gpios(&serdev->dev, ssam_acpi_gpios);
  12289. + if (status)
  12290. + return status;
  12291. +
  12292. + /* Allocate controller. */
  12293. + ctrl = kzalloc(sizeof(*ctrl), GFP_KERNEL);
  12294. + if (!ctrl)
  12295. + return -ENOMEM;
  12296. +
  12297. + /* Initialize controller. */
  12298. + status = ssam_controller_init(ctrl, serdev);
  12299. + if (status)
  12300. + goto err_ctrl_init;
  12301. +
  12302. + ssam_controller_lock(ctrl);
  12303. +
  12304. + /* Set up serdev device. */
  12305. + serdev_device_set_drvdata(serdev, ctrl);
  12306. + serdev_device_set_client_ops(serdev, &ssam_serdev_ops);
  12307. + status = serdev_device_open(serdev);
  12308. + if (status)
  12309. + goto err_devopen;
  12310. +
  12311. + astatus = ssam_serdev_setup_via_acpi(ssh, serdev);
  12312. + if (ACPI_FAILURE(astatus)) {
  12313. + status = -ENXIO;
  12314. + goto err_devinit;
  12315. + }
  12316. +
  12317. + /* Start controller. */
  12318. + status = ssam_controller_start(ctrl);
  12319. + if (status)
  12320. + goto err_devinit;
  12321. +
  12322. + ssam_controller_unlock(ctrl);
  12323. +
  12324. + /*
  12325. + * Initial SAM requests: Log version and notify default/init power
  12326. + * states.
  12327. + */
  12328. + status = ssam_log_firmware_version(ctrl);
  12329. + if (status)
  12330. + goto err_initrq;
  12331. +
  12332. + status = ssam_ctrl_notif_d0_entry(ctrl);
  12333. + if (status)
  12334. + goto err_initrq;
  12335. +
  12336. + status = ssam_ctrl_notif_display_on(ctrl);
  12337. + if (status)
  12338. + goto err_initrq;
  12339. +
  12340. + status = sysfs_create_group(&serdev->dev.kobj, &ssam_sam_group);
  12341. + if (status)
  12342. + goto err_initrq;
  12343. +
  12344. + /* Set up IRQ. */
  12345. + status = ssam_irq_setup(ctrl);
  12346. + if (status)
  12347. + goto err_irq;
  12348. +
  12349. + /* Finally, set main controller reference. */
  12350. + status = ssam_try_set_controller(ctrl);
  12351. + if (WARN_ON(status)) /* Currently, we're the only provider. */
  12352. + goto err_mainref;
  12353. +
  12354. + /*
  12355. + * TODO: The EC can wake up the system via the associated GPIO interrupt
  12356. + * in multiple situations. One of which is the remaining battery
  12357. + * capacity falling below a certain threshold. Normally, we should
  12358. + * use the device_init_wakeup function, however, the EC also seems
  12359. + * to have other reasons for waking up the system and it seems
  12360. + * that Windows has additional checks whether the system should be
  12361. + * resumed. In short, this causes some spurious unwanted wake-ups.
  12362. + * For now let's thus default power/wakeup to false.
  12363. + */
  12364. + device_set_wakeup_capable(&serdev->dev, true);
  12365. + acpi_walk_dep_device_list(ssh);
  12366. +
  12367. + return 0;
  12368. +
  12369. +err_mainref:
  12370. + ssam_irq_free(ctrl);
  12371. +err_irq:
  12372. + sysfs_remove_group(&serdev->dev.kobj, &ssam_sam_group);
  12373. +err_initrq:
  12374. + ssam_controller_lock(ctrl);
  12375. + ssam_controller_shutdown(ctrl);
  12376. +err_devinit:
  12377. + serdev_device_close(serdev);
  12378. +err_devopen:
  12379. + ssam_controller_destroy(ctrl);
  12380. + ssam_controller_unlock(ctrl);
  12381. +err_ctrl_init:
  12382. + kfree(ctrl);
  12383. + return status;
  12384. +}
  12385. +
  12386. +static void ssam_serial_hub_remove(struct serdev_device *serdev)
  12387. +{
  12388. + struct ssam_controller *ctrl = serdev_device_get_drvdata(serdev);
  12389. + int status;
  12390. +
  12391. + /* Clear static reference so that no one else can get a new one. */
  12392. + ssam_clear_controller();
  12393. +
  12394. + /* Disable and free IRQ. */
  12395. + ssam_irq_free(ctrl);
  12396. +
  12397. + sysfs_remove_group(&serdev->dev.kobj, &ssam_sam_group);
  12398. + ssam_controller_lock(ctrl);
  12399. +
  12400. + /* Remove all client devices. */
  12401. + ssam_controller_remove_clients(ctrl);
  12402. +
  12403. + /* Act as if suspending to silence events. */
  12404. + status = ssam_ctrl_notif_display_off(ctrl);
  12405. + if (status) {
  12406. + dev_err(&serdev->dev, "display-off notification failed: %d\n",
  12407. + status);
  12408. + }
  12409. +
  12410. + status = ssam_ctrl_notif_d0_exit(ctrl);
  12411. + if (status) {
  12412. + dev_err(&serdev->dev, "D0-exit notification failed: %d\n",
  12413. + status);
  12414. + }
  12415. +
  12416. + /* Shut down controller and remove serdev device reference from it. */
  12417. + ssam_controller_shutdown(ctrl);
  12418. +
  12419. + /* Shut down actual transport. */
  12420. + serdev_device_wait_until_sent(serdev, 0);
  12421. + serdev_device_close(serdev);
  12422. +
  12423. + /* Drop our controller reference. */
  12424. + ssam_controller_unlock(ctrl);
  12425. + ssam_controller_put(ctrl);
  12426. +
  12427. + device_set_wakeup_capable(&serdev->dev, false);
  12428. +}
  12429. +
  12430. +static const struct acpi_device_id ssam_serial_hub_match[] = {
  12431. + { "MSHW0084", 0 },
  12432. + { },
  12433. +};
  12434. +MODULE_DEVICE_TABLE(acpi, ssam_serial_hub_match);
  12435. +
  12436. +static struct serdev_device_driver ssam_serial_hub = {
  12437. + .probe = ssam_serial_hub_probe,
  12438. + .remove = ssam_serial_hub_remove,
  12439. + .driver = {
  12440. + .name = "surface_serial_hub",
  12441. + .acpi_match_table = ssam_serial_hub_match,
  12442. + .pm = &ssam_serial_hub_pm_ops,
  12443. + .shutdown = ssam_serial_hub_shutdown,
  12444. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  12445. + },
  12446. +};
  12447. +
  12448. +
  12449. +/* -- Module setup. --------------------------------------------------------- */
  12450. +
  12451. +static int __init ssam_core_init(void)
  12452. +{
  12453. + int status;
  12454. +
  12455. + status = ssam_bus_register();
  12456. + if (status)
  12457. + goto err_bus;
  12458. +
  12459. + status = ssh_ctrl_packet_cache_init();
  12460. + if (status)
  12461. + goto err_cpkg;
  12462. +
  12463. + status = ssam_event_item_cache_init();
  12464. + if (status)
  12465. + goto err_evitem;
  12466. +
  12467. + status = serdev_device_driver_register(&ssam_serial_hub);
  12468. + if (status)
  12469. + goto err_register;
  12470. +
  12471. + return 0;
  12472. +
  12473. +err_register:
  12474. + ssam_event_item_cache_destroy();
  12475. +err_evitem:
  12476. + ssh_ctrl_packet_cache_destroy();
  12477. +err_cpkg:
  12478. + ssam_bus_unregister();
  12479. +err_bus:
  12480. + return status;
  12481. +}
  12482. +module_init(ssam_core_init);
  12483. +
  12484. +static void __exit ssam_core_exit(void)
  12485. +{
  12486. + serdev_device_driver_unregister(&ssam_serial_hub);
  12487. + ssam_event_item_cache_destroy();
  12488. + ssh_ctrl_packet_cache_destroy();
  12489. + ssam_bus_unregister();
  12490. +}
  12491. +module_exit(ssam_core_exit);
  12492. +
  12493. +MODULE_AUTHOR("Maximilian Luz <luzmaximilian@gmail.com>");
  12494. +MODULE_DESCRIPTION("Subsystem and Surface Serial Hub driver for Surface System Aggregator Module");
  12495. +MODULE_LICENSE("GPL");
  12496. diff --git a/drivers/misc/surface_aggregator/ssh_msgb.h b/drivers/misc/surface_aggregator/ssh_msgb.h
  12497. new file mode 100644
  12498. index 000000000000..1221f642dda1
  12499. --- /dev/null
  12500. +++ b/drivers/misc/surface_aggregator/ssh_msgb.h
  12501. @@ -0,0 +1,205 @@
  12502. +/* SPDX-License-Identifier: GPL-2.0+ */
  12503. +/*
  12504. + * SSH message builder functions.
  12505. + *
  12506. + * Copyright (C) 2019-2020 Maximilian Luz <luzmaximilian@gmail.com>
  12507. + */
  12508. +
  12509. +#ifndef _SURFACE_AGGREGATOR_SSH_MSGB_H
  12510. +#define _SURFACE_AGGREGATOR_SSH_MSGB_H
  12511. +
  12512. +#include <asm/unaligned.h>
  12513. +#include <linux/types.h>
  12514. +
  12515. +#include <linux/surface_aggregator/controller.h>
  12516. +#include <linux/surface_aggregator/serial_hub.h>
  12517. +
  12518. +/**
  12519. + * struct msgbuf - Buffer struct to construct SSH messages.
  12520. + * @begin: Pointer to the beginning of the allocated buffer space.
  12521. + * @end: Pointer to the end (one past last element) of the allocated buffer
  12522. + * space.
  12523. + * @ptr: Pointer to the first free element in the buffer.
  12524. + */
  12525. +struct msgbuf {
  12526. + u8 *begin;
  12527. + u8 *end;
  12528. + u8 *ptr;
  12529. +};
  12530. +
  12531. +/**
  12532. + * msgb_init() - Initialize the given message buffer struct.
  12533. + * @msgb: The buffer struct to initialize
  12534. + * @ptr: Pointer to the underlying memory by which the buffer will be backed.
  12535. + * @cap: Size of the underlying memory.
  12536. + *
  12537. + * Initialize the given message buffer struct using the provided memory as
  12538. + * backing.
  12539. + */
  12540. +static inline void msgb_init(struct msgbuf *msgb, u8 *ptr, size_t cap)
  12541. +{
  12542. + msgb->begin = ptr;
  12543. + msgb->end = ptr + cap;
  12544. + msgb->ptr = ptr;
  12545. +}
  12546. +
  12547. +/**
  12548. + * msgb_bytes_used() - Return the current number of bytes used in the buffer.
  12549. + * @msgb: The message buffer.
  12550. + */
  12551. +static inline size_t msgb_bytes_used(const struct msgbuf *msgb)
  12552. +{
  12553. + return msgb->ptr - msgb->begin;
  12554. +}
  12555. +
  12556. +static inline void __msgb_push_u8(struct msgbuf *msgb, u8 value)
  12557. +{
  12558. + *msgb->ptr = value;
  12559. + msgb->ptr += sizeof(u8);
  12560. +}
  12561. +
  12562. +static inline void __msgb_push_u16(struct msgbuf *msgb, u16 value)
  12563. +{
  12564. + put_unaligned_le16(value, msgb->ptr);
  12565. + msgb->ptr += sizeof(u16);
  12566. +}
  12567. +
  12568. +/**
  12569. + * msgb_push_u16() - Push a u16 value to the buffer.
  12570. + * @msgb: The message buffer.
  12571. + * @value: The value to push to the buffer.
  12572. + */
  12573. +static inline void msgb_push_u16(struct msgbuf *msgb, u16 value)
  12574. +{
  12575. + if (WARN_ON(msgb->ptr + sizeof(u16) > msgb->end))
  12576. + return;
  12577. +
  12578. + __msgb_push_u16(msgb, value);
  12579. +}
  12580. +
  12581. +/**
  12582. + * msgb_push_syn() - Push SSH SYN bytes to the buffer.
  12583. + * @msgb: The message buffer.
  12584. + */
  12585. +static inline void msgb_push_syn(struct msgbuf *msgb)
  12586. +{
  12587. + msgb_push_u16(msgb, SSH_MSG_SYN);
  12588. +}
  12589. +
  12590. +/**
  12591. + * msgb_push_buf() - Push raw data to the buffer.
  12592. + * @msgb: The message buffer.
  12593. + * @buf: The data to push to the buffer.
  12594. + * @len: The length of the data to push to the buffer.
  12595. + */
  12596. +static inline void msgb_push_buf(struct msgbuf *msgb, const u8 *buf, size_t len)
  12597. +{
  12598. + msgb->ptr = memcpy(msgb->ptr, buf, len) + len;
  12599. +}
  12600. +
  12601. +/**
  12602. + * msgb_push_crc() - Compute CRC and push it to the buffer.
  12603. + * @msgb: The message buffer.
  12604. + * @buf: The data for which the CRC should be computed.
  12605. + * @len: The length of the data for which the CRC should be computed.
  12606. + */
  12607. +static inline void msgb_push_crc(struct msgbuf *msgb, const u8 *buf, size_t len)
  12608. +{
  12609. + msgb_push_u16(msgb, ssh_crc(buf, len));
  12610. +}
  12611. +
  12612. +/**
  12613. + * msgb_push_frame() - Push a SSH message frame header to the buffer.
  12614. + * @msgb: The message buffer
  12615. + * @ty: The type of the frame.
  12616. + * @len: The length of the payload of the frame.
  12617. + * @seq: The sequence ID of the frame/packet.
  12618. + */
  12619. +static inline void msgb_push_frame(struct msgbuf *msgb, u8 ty, u16 len, u8 seq)
  12620. +{
  12621. + u8 *const begin = msgb->ptr;
  12622. +
  12623. + if (WARN_ON(msgb->ptr + sizeof(struct ssh_frame) > msgb->end))
  12624. + return;
  12625. +
  12626. + __msgb_push_u8(msgb, ty); /* Frame type. */
  12627. + __msgb_push_u16(msgb, len); /* Frame payload length. */
  12628. + __msgb_push_u8(msgb, seq); /* Frame sequence ID. */
  12629. +
  12630. + msgb_push_crc(msgb, begin, msgb->ptr - begin);
  12631. +}
  12632. +
  12633. +/**
  12634. + * msgb_push_ack() - Push a SSH ACK frame to the buffer.
  12635. + * @msgb: The message buffer
  12636. + * @seq: The sequence ID of the frame/packet to be ACKed.
  12637. + */
  12638. +static inline void msgb_push_ack(struct msgbuf *msgb, u8 seq)
  12639. +{
  12640. + /* SYN. */
  12641. + msgb_push_syn(msgb);
  12642. +
  12643. + /* ACK-type frame + CRC. */
  12644. + msgb_push_frame(msgb, SSH_FRAME_TYPE_ACK, 0x00, seq);
  12645. +
  12646. + /* Payload CRC (ACK-type frames do not have a payload). */
  12647. + msgb_push_crc(msgb, msgb->ptr, 0);
  12648. +}
  12649. +
  12650. +/**
  12651. + * msgb_push_nak() - Push a SSH NAK frame to the buffer.
  12652. + * @msgb: The message buffer
  12653. + */
  12654. +static inline void msgb_push_nak(struct msgbuf *msgb)
  12655. +{
  12656. + /* SYN. */
  12657. + msgb_push_syn(msgb);
  12658. +
  12659. + /* NAK-type frame + CRC. */
  12660. + msgb_push_frame(msgb, SSH_FRAME_TYPE_NAK, 0x00, 0x00);
  12661. +
  12662. + /* Payload CRC (ACK-type frames do not have a payload). */
  12663. + msgb_push_crc(msgb, msgb->ptr, 0);
  12664. +}
  12665. +
  12666. +/**
  12667. + * msgb_push_cmd() - Push a SSH command frame with payload to the buffer.
  12668. + * @msgb: The message buffer.
  12669. + * @seq: The sequence ID (SEQ) of the frame/packet.
  12670. + * @rqid: The request ID (RQID) of the request contained in the frame.
  12671. + * @rqst: The request to wrap in the frame.
  12672. + */
  12673. +static inline void msgb_push_cmd(struct msgbuf *msgb, u8 seq, u16 rqid,
  12674. + const struct ssam_request *rqst)
  12675. +{
  12676. + const u8 type = SSH_FRAME_TYPE_DATA_SEQ;
  12677. + u8 *cmd;
  12678. +
  12679. + /* SYN. */
  12680. + msgb_push_syn(msgb);
  12681. +
  12682. + /* Command frame + CRC. */
  12683. + msgb_push_frame(msgb, type, sizeof(struct ssh_command) + rqst->length, seq);
  12684. +
  12685. + /* Frame payload: Command struct + payload. */
  12686. + if (WARN_ON(msgb->ptr + sizeof(struct ssh_command) > msgb->end))
  12687. + return;
  12688. +
  12689. + cmd = msgb->ptr;
  12690. +
  12691. + __msgb_push_u8(msgb, SSH_PLD_TYPE_CMD); /* Payload type. */
  12692. + __msgb_push_u8(msgb, rqst->target_category); /* Target category. */
  12693. + __msgb_push_u8(msgb, rqst->target_id); /* Target ID (out). */
  12694. + __msgb_push_u8(msgb, 0x00); /* Target ID (in). */
  12695. + __msgb_push_u8(msgb, rqst->instance_id); /* Instance ID. */
  12696. + __msgb_push_u16(msgb, rqid); /* Request ID. */
  12697. + __msgb_push_u8(msgb, rqst->command_id); /* Command ID. */
  12698. +
  12699. + /* Command payload. */
  12700. + msgb_push_buf(msgb, rqst->payload, rqst->length);
  12701. +
  12702. + /* CRC for command struct + payload. */
  12703. + msgb_push_crc(msgb, cmd, msgb->ptr - cmd);
  12704. +}
  12705. +
  12706. +#endif /* _SURFACE_AGGREGATOR_SSH_MSGB_H */
  12707. diff --git a/drivers/misc/surface_aggregator/ssh_packet_layer.c b/drivers/misc/surface_aggregator/ssh_packet_layer.c
  12708. new file mode 100644
  12709. index 000000000000..74f0faaa2b27
  12710. --- /dev/null
  12711. +++ b/drivers/misc/surface_aggregator/ssh_packet_layer.c
  12712. @@ -0,0 +1,2057 @@
  12713. +// SPDX-License-Identifier: GPL-2.0+
  12714. +/*
  12715. + * SSH packet transport layer.
  12716. + *
  12717. + * Copyright (C) 2019-2020 Maximilian Luz <luzmaximilian@gmail.com>
  12718. + */
  12719. +
  12720. +#include <asm/unaligned.h>
  12721. +#include <linux/atomic.h>
  12722. +#include <linux/error-injection.h>
  12723. +#include <linux/jiffies.h>
  12724. +#include <linux/kfifo.h>
  12725. +#include <linux/kref.h>
  12726. +#include <linux/kthread.h>
  12727. +#include <linux/ktime.h>
  12728. +#include <linux/limits.h>
  12729. +#include <linux/list.h>
  12730. +#include <linux/lockdep.h>
  12731. +#include <linux/serdev.h>
  12732. +#include <linux/slab.h>
  12733. +#include <linux/spinlock.h>
  12734. +#include <linux/workqueue.h>
  12735. +
  12736. +#include <linux/surface_aggregator/serial_hub.h>
  12737. +
  12738. +#include "ssh_msgb.h"
  12739. +#include "ssh_packet_layer.h"
  12740. +#include "ssh_parser.h"
  12741. +
  12742. +#include "trace.h"
  12743. +
  12744. +/*
  12745. + * To simplify reasoning about the code below, we define a few concepts. The
  12746. + * system below is similar to a state-machine for packets, however, there are
  12747. + * too many states to explicitly write them down. To (somewhat) manage the
  12748. + * states and packets we rely on flags, reference counting, and some simple
  12749. + * concepts. State transitions are triggered by actions.
  12750. + *
  12751. + * >> Actions <<
  12752. + *
  12753. + * - submit
  12754. + * - transmission start (process next item in queue)
  12755. + * - transmission finished (guaranteed to never be parallel to transmission
  12756. + * start)
  12757. + * - ACK received
  12758. + * - NAK received (this is equivalent to issuing re-submit for all pending
  12759. + * packets)
  12760. + * - timeout (this is equivalent to re-issuing a submit or canceling)
  12761. + * - cancel (non-pending and pending)
  12762. + *
  12763. + * >> Data Structures, Packet Ownership, General Overview <<
  12764. + *
  12765. + * The code below employs two main data structures: The packet queue,
  12766. + * containing all packets scheduled for transmission, and the set of pending
  12767. + * packets, containing all packets awaiting an ACK.
  12768. + *
  12769. + * Shared ownership of a packet is controlled via reference counting. Inside
  12770. + * the transport system are a total of five packet owners:
  12771. + *
  12772. + * - the packet queue,
  12773. + * - the pending set,
  12774. + * - the transmitter thread,
  12775. + * - the receiver thread (via ACKing), and
  12776. + * - the timeout work item.
  12777. + *
  12778. + * Normal operation is as follows: The initial reference of the packet is
  12779. + * obtained by submitting the packet and queuing it. The receiver thread takes
  12780. + * packets from the queue. By doing this, it does not increment the refcount
  12781. + * but takes over the reference (removing it from the queue). If the packet is
  12782. + * sequenced (i.e. needs to be ACKed by the client), the transmitter thread
  12783. + * sets-up the timeout and adds the packet to the pending set before starting
  12784. + * to transmit it. As the timeout is handled by a reaper task, no additional
  12785. + * reference for it is needed. After the transmit is done, the reference held
  12786. + * by the transmitter thread is dropped. If the packet is unsequenced (i.e.
  12787. + * does not need an ACK), the packet is completed by the transmitter thread
  12788. + * before dropping that reference.
  12789. + *
  12790. + * On receival of an ACK, the receiver thread removes and obtains the
  12791. + * reference to the packet from the pending set. The receiver thread will then
  12792. + * complete the packet and drop its reference.
  12793. + *
  12794. + * On receival of a NAK, the receiver thread re-submits all currently pending
  12795. + * packets.
  12796. + *
  12797. + * Packet timeouts are detected by the timeout reaper. This is a task,
  12798. + * scheduled depending on the earliest packet timeout expiration date,
  12799. + * checking all currently pending packets if their timeout has expired. If the
  12800. + * timeout of a packet has expired, it is re-submitted and the number of tries
  12801. + * of this packet is incremented. If this number reaches its limit, the packet
  12802. + * will be completed with a failure.
  12803. + *
  12804. + * On transmission failure (such as repeated packet timeouts), the completion
  12805. + * callback is immediately run by on thread on which the error was detected.
  12806. + *
  12807. + * To ensure that a packet eventually leaves the system it is marked as
  12808. + * "locked" directly before it is going to be completed or when it is
  12809. + * canceled. Marking a packet as "locked" has the effect that passing and
  12810. + * creating new references of the packet is disallowed. This means that the
  12811. + * packet cannot be added to the queue, the pending set, and the timeout, or
  12812. + * be picked up by the transmitter thread or receiver thread. To remove a
  12813. + * packet from the system it has to be marked as locked and subsequently all
  12814. + * references from the data structures (queue, pending) have to be removed.
  12815. + * References held by threads will eventually be dropped automatically as
  12816. + * their execution progresses.
  12817. + *
  12818. + * Note that the packet completion callback is, in case of success and for a
  12819. + * sequenced packet, guaranteed to run on the receiver thread, thus providing
  12820. + * a way to reliably identify responses to the packet. The packet completion
  12821. + * callback is only run once and it does not indicate that the packet has
  12822. + * fully left the system (for this, one should rely on the release method,
  12823. + * triggered when the reference count of the packet reaches zero). In case of
  12824. + * re-submission (and with somewhat unlikely timing), it may be possible that
  12825. + * the packet is being re-transmitted while the completion callback runs.
  12826. + * Completion will occur both on success and internal error, as well as when
  12827. + * the packet is canceled.
  12828. + *
  12829. + * >> Flags <<
  12830. + *
  12831. + * Flags are used to indicate the state and progression of a packet. Some flags
  12832. + * have stricter guarantees than other:
  12833. + *
  12834. + * - locked
  12835. + * Indicates if the packet is locked. If the packet is locked, passing and/or
  12836. + * creating additional references to the packet is forbidden. The packet thus
  12837. + * may not be queued, dequeued, or removed or added to the pending set. Note
  12838. + * that the packet state flags may still change (e.g. it may be marked as
  12839. + * ACKed, transmitted, ...).
  12840. + *
  12841. + * - completed
  12842. + * Indicates if the packet completion callback has been executed or is about
  12843. + * to be executed. This flag is used to ensure that the packet completion
  12844. + * callback is only run once.
  12845. + *
  12846. + * - queued
  12847. + * Indicates if a packet is present in the submission queue or not. This flag
  12848. + * must only be modified with the queue lock held, and must be coherent to the
  12849. + * presence of the packet in the queue.
  12850. + *
  12851. + * - pending
  12852. + * Indicates if a packet is present in the set of pending packets or not.
  12853. + * This flag must only be modified with the pending lock held, and must be
  12854. + * coherent to the presence of the packet in the pending set.
  12855. + *
  12856. + * - transmitting
  12857. + * Indicates if the packet is currently transmitting. In case of
  12858. + * re-transmissions, it is only safe to wait on the "transmitted" completion
  12859. + * after this flag has been set. The completion will be set both in success
  12860. + * and error case.
  12861. + *
  12862. + * - transmitted
  12863. + * Indicates if the packet has been transmitted. This flag is not cleared by
  12864. + * the system, thus it indicates the first transmission only.
  12865. + *
  12866. + * - acked
  12867. + * Indicates if the packet has been acknowledged by the client. There are no
  12868. + * other guarantees given. For example, the packet may still be canceled
  12869. + * and/or the completion may be triggered an error even though this bit is
  12870. + * set. Rely on the status provided to the completion callback instead.
  12871. + *
  12872. + * - canceled
  12873. + * Indicates if the packet has been canceled from the outside. There are no
  12874. + * other guarantees given. Specifically, the packet may be completed by
  12875. + * another part of the system before the cancellation attempts to complete it.
  12876. + *
  12877. + * >> General Notes <<
  12878. + *
  12879. + * - To avoid deadlocks, if both queue and pending locks are required, the
  12880. + * pending lock must be acquired before the queue lock.
  12881. + *
  12882. + * - The packet priority must be accessed only while holding the queue lock.
  12883. + *
  12884. + * - The packet timestamp must be accessed only while holding the pending
  12885. + * lock.
  12886. + */
  12887. +
  12888. +/*
  12889. + * SSH_PTL_MAX_PACKET_TRIES - Maximum transmission attempts for packet.
  12890. + *
  12891. + * Maximum number of transmission attempts per sequenced packet in case of
  12892. + * time-outs. Must be smaller than 16. If the packet times out after this
  12893. + * amount of tries, the packet will be completed with %-ETIMEDOUT as status
  12894. + * code.
  12895. + */
  12896. +#define SSH_PTL_MAX_PACKET_TRIES 3
  12897. +
  12898. +/*
  12899. + * SSH_PTL_TX_TIMEOUT - Packet transmission timeout.
  12900. + *
  12901. + * Timeout in jiffies for packet transmission via the underlying serial
  12902. + * device. If transmitting the packet takes longer than this timeout, the
  12903. + * packet will be completed with -ETIMEDOUT. It will not be re-submitted.
  12904. + */
  12905. +#define SSH_PTL_TX_TIMEOUT HZ
  12906. +
  12907. +/*
  12908. + * SSH_PTL_PACKET_TIMEOUT - Packet response timeout.
  12909. + *
  12910. + * Timeout as ktime_t delta for ACKs. If we have not received an ACK in this
  12911. + * time-frame after starting transmission, the packet will be re-submitted.
  12912. + */
  12913. +#define SSH_PTL_PACKET_TIMEOUT ms_to_ktime(1000)
  12914. +
  12915. +/*
  12916. + * SSH_PTL_PACKET_TIMEOUT_RESOLUTION - Packet timeout granularity.
  12917. + *
  12918. + * Time-resolution for timeouts. Should be larger than one jiffy to avoid
  12919. + * direct re-scheduling of reaper work_struct.
  12920. + */
  12921. +#define SSH_PTL_PACKET_TIMEOUT_RESOLUTION ms_to_ktime(max(2000 / HZ, 50))
  12922. +
  12923. +/*
  12924. + * SSH_PTL_MAX_PENDING - Maximum number of pending packets.
  12925. + *
  12926. + * Maximum number of sequenced packets concurrently waiting for an ACK.
  12927. + * Packets marked as blocking will not be transmitted while this limit is
  12928. + * reached.
  12929. + */
  12930. +#define SSH_PTL_MAX_PENDING 1
  12931. +
  12932. +/*
  12933. + * SSH_PTL_RX_BUF_LEN - Evaluation-buffer size in bytes.
  12934. + */
  12935. +#define SSH_PTL_RX_BUF_LEN 4096
  12936. +
  12937. +/*
  12938. + * SSH_PTL_RX_FIFO_LEN - Fifo input-buffer size in bytes.
  12939. + */
  12940. +#define SSH_PTL_RX_FIFO_LEN 4096
  12941. +
  12942. +#ifdef CONFIG_SURFACE_AGGREGATOR_ERROR_INJECTION
  12943. +
  12944. +/**
  12945. + * ssh_ptl_should_drop_ack_packet() - Error injection hook to drop ACK packets.
  12946. + *
  12947. + * Useful to test detection and handling of automated re-transmits by the EC.
  12948. + * Specifically of packets that the EC considers not-ACKed but the driver
  12949. + * already considers ACKed (due to dropped ACK). In this case, the EC
  12950. + * re-transmits the packet-to-be-ACKed and the driver should detect it as
  12951. + * duplicate/already handled. Note that the driver should still send an ACK
  12952. + * for the re-transmitted packet.
  12953. + */
  12954. +static noinline bool ssh_ptl_should_drop_ack_packet(void)
  12955. +{
  12956. + return false;
  12957. +}
  12958. +ALLOW_ERROR_INJECTION(ssh_ptl_should_drop_ack_packet, TRUE);
  12959. +
  12960. +/**
  12961. + * ssh_ptl_should_drop_nak_packet() - Error injection hook to drop NAK packets.
  12962. + *
  12963. + * Useful to test/force automated (timeout-based) re-transmit by the EC.
  12964. + * Specifically, packets that have not reached the driver completely/with valid
  12965. + * checksums. Only useful in combination with receival of (injected) bad data.
  12966. + */
  12967. +static noinline bool ssh_ptl_should_drop_nak_packet(void)
  12968. +{
  12969. + return false;
  12970. +}
  12971. +ALLOW_ERROR_INJECTION(ssh_ptl_should_drop_nak_packet, TRUE);
  12972. +
  12973. +/**
  12974. + * ssh_ptl_should_drop_dsq_packet() - Error injection hook to drop sequenced
  12975. + * data packet.
  12976. + *
  12977. + * Useful to test re-transmit timeout of the driver. If the data packet has not
  12978. + * been ACKed after a certain time, the driver should re-transmit the packet up
  12979. + * to limited number of times defined in SSH_PTL_MAX_PACKET_TRIES.
  12980. + */
  12981. +static noinline bool ssh_ptl_should_drop_dsq_packet(void)
  12982. +{
  12983. + return false;
  12984. +}
  12985. +ALLOW_ERROR_INJECTION(ssh_ptl_should_drop_dsq_packet, TRUE);
  12986. +
  12987. +/**
  12988. + * ssh_ptl_should_fail_write() - Error injection hook to make
  12989. + * serdev_device_write() fail.
  12990. + *
  12991. + * Hook to simulate errors in serdev_device_write when transmitting packets.
  12992. + */
  12993. +static noinline int ssh_ptl_should_fail_write(void)
  12994. +{
  12995. + return 0;
  12996. +}
  12997. +ALLOW_ERROR_INJECTION(ssh_ptl_should_fail_write, ERRNO);
  12998. +
  12999. +/**
  13000. + * ssh_ptl_should_corrupt_tx_data() - Error injection hook to simulate invalid
  13001. + * data being sent to the EC.
  13002. + *
  13003. + * Hook to simulate corrupt/invalid data being sent from host (driver) to EC.
  13004. + * Causes the packet data to be actively corrupted by overwriting it with
  13005. + * pre-defined values, such that it becomes invalid, causing the EC to respond
  13006. + * with a NAK packet. Useful to test handling of NAK packets received by the
  13007. + * driver.
  13008. + */
  13009. +static noinline bool ssh_ptl_should_corrupt_tx_data(void)
  13010. +{
  13011. + return false;
  13012. +}
  13013. +ALLOW_ERROR_INJECTION(ssh_ptl_should_corrupt_tx_data, TRUE);
  13014. +
  13015. +/**
  13016. + * ssh_ptl_should_corrupt_rx_syn() - Error injection hook to simulate invalid
  13017. + * data being sent by the EC.
  13018. + *
  13019. + * Hook to simulate invalid SYN bytes, i.e. an invalid start of messages and
  13020. + * test handling thereof in the driver.
  13021. + */
  13022. +static noinline bool ssh_ptl_should_corrupt_rx_syn(void)
  13023. +{
  13024. + return false;
  13025. +}
  13026. +ALLOW_ERROR_INJECTION(ssh_ptl_should_corrupt_rx_syn, TRUE);
  13027. +
  13028. +/**
  13029. + * ssh_ptl_should_corrupt_rx_data() - Error injection hook to simulate invalid
  13030. + * data being sent by the EC.
  13031. + *
  13032. + * Hook to simulate invalid data/checksum of the message frame and test handling
  13033. + * thereof in the driver.
  13034. + */
  13035. +static noinline bool ssh_ptl_should_corrupt_rx_data(void)
  13036. +{
  13037. + return false;
  13038. +}
  13039. +ALLOW_ERROR_INJECTION(ssh_ptl_should_corrupt_rx_data, TRUE);
  13040. +
  13041. +static bool __ssh_ptl_should_drop_ack_packet(struct ssh_packet *packet)
  13042. +{
  13043. + if (likely(!ssh_ptl_should_drop_ack_packet()))
  13044. + return false;
  13045. +
  13046. + trace_ssam_ei_tx_drop_ack_packet(packet);
  13047. + ptl_info(packet->ptl, "packet error injection: dropping ACK packet %p\n",
  13048. + packet);
  13049. +
  13050. + return true;
  13051. +}
  13052. +
  13053. +static bool __ssh_ptl_should_drop_nak_packet(struct ssh_packet *packet)
  13054. +{
  13055. + if (likely(!ssh_ptl_should_drop_nak_packet()))
  13056. + return false;
  13057. +
  13058. + trace_ssam_ei_tx_drop_nak_packet(packet);
  13059. + ptl_info(packet->ptl, "packet error injection: dropping NAK packet %p\n",
  13060. + packet);
  13061. +
  13062. + return true;
  13063. +}
  13064. +
  13065. +static bool __ssh_ptl_should_drop_dsq_packet(struct ssh_packet *packet)
  13066. +{
  13067. + if (likely(!ssh_ptl_should_drop_dsq_packet()))
  13068. + return false;
  13069. +
  13070. + trace_ssam_ei_tx_drop_dsq_packet(packet);
  13071. + ptl_info(packet->ptl,
  13072. + "packet error injection: dropping sequenced data packet %p\n",
  13073. + packet);
  13074. +
  13075. + return true;
  13076. +}
  13077. +
  13078. +static bool ssh_ptl_should_drop_packet(struct ssh_packet *packet)
  13079. +{
  13080. + /* Ignore packets that don't carry any data (i.e. flush). */
  13081. + if (!packet->data.ptr || !packet->data.len)
  13082. + return false;
  13083. +
  13084. + switch (packet->data.ptr[SSH_MSGOFFSET_FRAME(type)]) {
  13085. + case SSH_FRAME_TYPE_ACK:
  13086. + return __ssh_ptl_should_drop_ack_packet(packet);
  13087. +
  13088. + case SSH_FRAME_TYPE_NAK:
  13089. + return __ssh_ptl_should_drop_nak_packet(packet);
  13090. +
  13091. + case SSH_FRAME_TYPE_DATA_SEQ:
  13092. + return __ssh_ptl_should_drop_dsq_packet(packet);
  13093. +
  13094. + default:
  13095. + return false;
  13096. + }
  13097. +}
  13098. +
  13099. +static int ssh_ptl_write_buf(struct ssh_ptl *ptl, struct ssh_packet *packet,
  13100. + const unsigned char *buf, size_t count)
  13101. +{
  13102. + int status;
  13103. +
  13104. + status = ssh_ptl_should_fail_write();
  13105. + if (unlikely(status)) {
  13106. + trace_ssam_ei_tx_fail_write(packet, status);
  13107. + ptl_info(packet->ptl,
  13108. + "packet error injection: simulating transmit error %d, packet %p\n",
  13109. + status, packet);
  13110. +
  13111. + return status;
  13112. + }
  13113. +
  13114. + return serdev_device_write_buf(ptl->serdev, buf, count);
  13115. +}
  13116. +
  13117. +static void ssh_ptl_tx_inject_invalid_data(struct ssh_packet *packet)
  13118. +{
  13119. + /* Ignore packets that don't carry any data (i.e. flush). */
  13120. + if (!packet->data.ptr || !packet->data.len)
  13121. + return;
  13122. +
  13123. + /* Only allow sequenced data packets to be modified. */
  13124. + if (packet->data.ptr[SSH_MSGOFFSET_FRAME(type)] != SSH_FRAME_TYPE_DATA_SEQ)
  13125. + return;
  13126. +
  13127. + if (likely(!ssh_ptl_should_corrupt_tx_data()))
  13128. + return;
  13129. +
  13130. + trace_ssam_ei_tx_corrupt_data(packet);
  13131. + ptl_info(packet->ptl,
  13132. + "packet error injection: simulating invalid transmit data on packet %p\n",
  13133. + packet);
  13134. +
  13135. + /*
  13136. + * NB: The value 0xb3 has been chosen more or less randomly so that it
  13137. + * doesn't have any (major) overlap with the SYN bytes (aa 55) and is
  13138. + * non-trivial (i.e. non-zero, non-0xff).
  13139. + */
  13140. + memset(packet->data.ptr, 0xb3, packet->data.len);
  13141. +}
  13142. +
  13143. +static void ssh_ptl_rx_inject_invalid_syn(struct ssh_ptl *ptl,
  13144. + struct ssam_span *data)
  13145. +{
  13146. + struct ssam_span frame;
  13147. +
  13148. + /* Check if there actually is something to corrupt. */
  13149. + if (!sshp_find_syn(data, &frame))
  13150. + return;
  13151. +
  13152. + if (likely(!ssh_ptl_should_corrupt_rx_syn()))
  13153. + return;
  13154. +
  13155. + trace_ssam_ei_rx_corrupt_syn(data->len);
  13156. +
  13157. + data->ptr[1] = 0xb3; /* Set second byte of SYN to "random" value. */
  13158. +}
  13159. +
  13160. +static void ssh_ptl_rx_inject_invalid_data(struct ssh_ptl *ptl,
  13161. + struct ssam_span *frame)
  13162. +{
  13163. + size_t payload_len, message_len;
  13164. + struct ssh_frame *sshf;
  13165. +
  13166. + /* Ignore incomplete messages, will get handled once it's complete. */
  13167. + if (frame->len < SSH_MESSAGE_LENGTH(0))
  13168. + return;
  13169. +
  13170. + /* Ignore incomplete messages, part 2. */
  13171. + payload_len = get_unaligned_le16(&frame->ptr[SSH_MSGOFFSET_FRAME(len)]);
  13172. + message_len = SSH_MESSAGE_LENGTH(payload_len);
  13173. + if (frame->len < message_len)
  13174. + return;
  13175. +
  13176. + if (likely(!ssh_ptl_should_corrupt_rx_data()))
  13177. + return;
  13178. +
  13179. + sshf = (struct ssh_frame *)&frame->ptr[SSH_MSGOFFSET_FRAME(type)];
  13180. + trace_ssam_ei_rx_corrupt_data(sshf);
  13181. +
  13182. + /*
  13183. + * Flip bits in first byte of payload checksum. This is basically
  13184. + * equivalent to a payload/frame data error without us having to worry
  13185. + * about (the, arguably pretty small, probability of) accidental
  13186. + * checksum collisions.
  13187. + */
  13188. + frame->ptr[frame->len - 2] = ~frame->ptr[frame->len - 2];
  13189. +}
  13190. +
  13191. +#else /* CONFIG_SURFACE_AGGREGATOR_ERROR_INJECTION */
  13192. +
  13193. +static inline bool ssh_ptl_should_drop_packet(struct ssh_packet *packet)
  13194. +{
  13195. + return false;
  13196. +}
  13197. +
  13198. +static inline int ssh_ptl_write_buf(struct ssh_ptl *ptl,
  13199. + struct ssh_packet *packet,
  13200. + const unsigned char *buf,
  13201. + size_t count)
  13202. +{
  13203. + return serdev_device_write_buf(ptl->serdev, buf, count);
  13204. +}
  13205. +
  13206. +static inline void ssh_ptl_tx_inject_invalid_data(struct ssh_packet *packet)
  13207. +{
  13208. +}
  13209. +
  13210. +static inline void ssh_ptl_rx_inject_invalid_syn(struct ssh_ptl *ptl,
  13211. + struct ssam_span *data)
  13212. +{
  13213. +}
  13214. +
  13215. +static inline void ssh_ptl_rx_inject_invalid_data(struct ssh_ptl *ptl,
  13216. + struct ssam_span *frame)
  13217. +{
  13218. +}
  13219. +
  13220. +#endif /* CONFIG_SURFACE_AGGREGATOR_ERROR_INJECTION */
  13221. +
  13222. +static void __ssh_ptl_packet_release(struct kref *kref)
  13223. +{
  13224. + struct ssh_packet *p = container_of(kref, struct ssh_packet, refcnt);
  13225. +
  13226. + trace_ssam_packet_release(p);
  13227. +
  13228. + ptl_dbg_cond(p->ptl, "ptl: releasing packet %p\n", p);
  13229. + p->ops->release(p);
  13230. +}
  13231. +
  13232. +/**
  13233. + * ssh_packet_get() - Increment reference count of packet.
  13234. + * @packet: The packet to increment the reference count of.
  13235. + *
  13236. + * Increments the reference count of the given packet. See ssh_packet_put()
  13237. + * for the counter-part of this function.
  13238. + *
  13239. + * Return: Returns the packet provided as input.
  13240. + */
  13241. +struct ssh_packet *ssh_packet_get(struct ssh_packet *packet)
  13242. +{
  13243. + if (packet)
  13244. + kref_get(&packet->refcnt);
  13245. + return packet;
  13246. +}
  13247. +EXPORT_SYMBOL_GPL(ssh_packet_get);
  13248. +
  13249. +/**
  13250. + * ssh_packet_put() - Decrement reference count of packet.
  13251. + * @packet: The packet to decrement the reference count of.
  13252. + *
  13253. + * If the reference count reaches zero, the ``release`` callback specified in
  13254. + * the packet's &struct ssh_packet_ops, i.e. ``packet->ops->release``, will be
  13255. + * called.
  13256. + *
  13257. + * See ssh_packet_get() for the counter-part of this function.
  13258. + */
  13259. +void ssh_packet_put(struct ssh_packet *packet)
  13260. +{
  13261. + if (packet)
  13262. + kref_put(&packet->refcnt, __ssh_ptl_packet_release);
  13263. +}
  13264. +EXPORT_SYMBOL_GPL(ssh_packet_put);
  13265. +
  13266. +static u8 ssh_packet_get_seq(struct ssh_packet *packet)
  13267. +{
  13268. + return packet->data.ptr[SSH_MSGOFFSET_FRAME(seq)];
  13269. +}
  13270. +
  13271. +/**
  13272. + * ssh_packet_init() - Initialize SSH packet.
  13273. + * @packet: The packet to initialize.
  13274. + * @type: Type-flags of the packet.
  13275. + * @priority: Priority of the packet. See SSH_PACKET_PRIORITY() for details.
  13276. + * @ops: Packet operations.
  13277. + *
  13278. + * Initializes the given SSH packet. Sets the transmission buffer pointer to
  13279. + * %NULL and the transmission buffer length to zero. For data-type packets,
  13280. + * this buffer has to be set separately via ssh_packet_set_data() before
  13281. + * submission, and must contain a valid SSH message, i.e. frame with optional
  13282. + * payload of any type.
  13283. + */
  13284. +void ssh_packet_init(struct ssh_packet *packet, unsigned long type,
  13285. + u8 priority, const struct ssh_packet_ops *ops)
  13286. +{
  13287. + kref_init(&packet->refcnt);
  13288. +
  13289. + packet->ptl = NULL;
  13290. + INIT_LIST_HEAD(&packet->queue_node);
  13291. + INIT_LIST_HEAD(&packet->pending_node);
  13292. +
  13293. + packet->state = type & SSH_PACKET_FLAGS_TY_MASK;
  13294. + packet->priority = priority;
  13295. + packet->timestamp = KTIME_MAX;
  13296. +
  13297. + packet->data.ptr = NULL;
  13298. + packet->data.len = 0;
  13299. +
  13300. + packet->ops = ops;
  13301. +}
  13302. +
  13303. +static struct kmem_cache *ssh_ctrl_packet_cache;
  13304. +
  13305. +/**
  13306. + * ssh_ctrl_packet_cache_init() - Initialize the control packet cache.
  13307. + */
  13308. +int ssh_ctrl_packet_cache_init(void)
  13309. +{
  13310. + const unsigned int size = sizeof(struct ssh_packet) + SSH_MSG_LEN_CTRL;
  13311. + const unsigned int align = __alignof__(struct ssh_packet);
  13312. + struct kmem_cache *cache;
  13313. +
  13314. + cache = kmem_cache_create("ssam_ctrl_packet", size, align, 0, NULL);
  13315. + if (!cache)
  13316. + return -ENOMEM;
  13317. +
  13318. + ssh_ctrl_packet_cache = cache;
  13319. + return 0;
  13320. +}
  13321. +
  13322. +/**
  13323. + * ssh_ctrl_packet_cache_destroy() - Deinitialize the control packet cache.
  13324. + */
  13325. +void ssh_ctrl_packet_cache_destroy(void)
  13326. +{
  13327. + kmem_cache_destroy(ssh_ctrl_packet_cache);
  13328. + ssh_ctrl_packet_cache = NULL;
  13329. +}
  13330. +
  13331. +/**
  13332. + * ssh_ctrl_packet_alloc() - Allocate packet from control packet cache.
  13333. + * @packet: Where the pointer to the newly allocated packet should be stored.
  13334. + * @buffer: The buffer corresponding to this packet.
  13335. + * @flags: Flags used for allocation.
  13336. + *
  13337. + * Allocates a packet and corresponding transport buffer from the control
  13338. + * packet cache. Sets the packet's buffer reference to the allocated buffer.
  13339. + * The packet must be freed via ssh_ctrl_packet_free(), which will also free
  13340. + * the corresponding buffer. The corresponding buffer must not be freed
  13341. + * separately. Intended to be used with %ssh_ptl_ctrl_packet_ops as packet
  13342. + * operations.
  13343. + *
  13344. + * Return: Returns zero on success, %-ENOMEM if the allocation failed.
  13345. + */
  13346. +static int ssh_ctrl_packet_alloc(struct ssh_packet **packet,
  13347. + struct ssam_span *buffer, gfp_t flags)
  13348. +{
  13349. + *packet = kmem_cache_alloc(ssh_ctrl_packet_cache, flags);
  13350. + if (!*packet)
  13351. + return -ENOMEM;
  13352. +
  13353. + buffer->ptr = (u8 *)(*packet + 1);
  13354. + buffer->len = SSH_MSG_LEN_CTRL;
  13355. +
  13356. + trace_ssam_ctrl_packet_alloc(*packet, buffer->len);
  13357. + return 0;
  13358. +}
  13359. +
  13360. +/**
  13361. + * ssh_ctrl_packet_free() - Free packet allocated from control packet cache.
  13362. + * @p: The packet to free.
  13363. + */
  13364. +static void ssh_ctrl_packet_free(struct ssh_packet *p)
  13365. +{
  13366. + trace_ssam_ctrl_packet_free(p);
  13367. + kmem_cache_free(ssh_ctrl_packet_cache, p);
  13368. +}
  13369. +
  13370. +static const struct ssh_packet_ops ssh_ptl_ctrl_packet_ops = {
  13371. + .complete = NULL,
  13372. + .release = ssh_ctrl_packet_free,
  13373. +};
  13374. +
  13375. +static void ssh_ptl_timeout_reaper_mod(struct ssh_ptl *ptl, ktime_t now,
  13376. + ktime_t expires)
  13377. +{
  13378. + unsigned long delta = msecs_to_jiffies(ktime_ms_delta(expires, now));
  13379. + ktime_t aexp = ktime_add(expires, SSH_PTL_PACKET_TIMEOUT_RESOLUTION);
  13380. +
  13381. + spin_lock(&ptl->rtx_timeout.lock);
  13382. +
  13383. + /* Re-adjust / schedule reaper only if it is above resolution delta. */
  13384. + if (ktime_before(aexp, ptl->rtx_timeout.expires)) {
  13385. + ptl->rtx_timeout.expires = expires;
  13386. + mod_delayed_work(system_wq, &ptl->rtx_timeout.reaper, delta);
  13387. + }
  13388. +
  13389. + spin_unlock(&ptl->rtx_timeout.lock);
  13390. +}
  13391. +
  13392. +/* Must be called with queue lock held. */
  13393. +static void ssh_packet_next_try(struct ssh_packet *p)
  13394. +{
  13395. + u8 base = ssh_packet_priority_get_base(p->priority);
  13396. + u8 try = ssh_packet_priority_get_try(p->priority);
  13397. +
  13398. + lockdep_assert_held(&p->ptl->queue.lock);
  13399. +
  13400. + /*
  13401. + * Ensure that we write the priority in one go via WRITE_ONCE() so we
  13402. + * can access it via READ_ONCE() for tracing. Note that other access
  13403. + * is guarded by the queue lock, so no need to use READ_ONCE() there.
  13404. + */
  13405. + WRITE_ONCE(p->priority, __SSH_PACKET_PRIORITY(base, try + 1));
  13406. +}
  13407. +
  13408. +/* Must be called with queue lock held. */
  13409. +static struct list_head *__ssh_ptl_queue_find_entrypoint(struct ssh_packet *p)
  13410. +{
  13411. + struct list_head *head;
  13412. + struct ssh_packet *q;
  13413. +
  13414. + lockdep_assert_held(&p->ptl->queue.lock);
  13415. +
  13416. + /*
  13417. + * We generally assume that there are less control (ACK/NAK) packets
  13418. + * and re-submitted data packets as there are normal data packets (at
  13419. + * least in situations in which many packets are queued; if there
  13420. + * aren't many packets queued the decision on how to iterate should be
  13421. + * basically irrelevant; the number of control/data packets is more or
  13422. + * less limited via the maximum number of pending packets). Thus, when
  13423. + * inserting a control or re-submitted data packet, (determined by
  13424. + * their priority), we search from front to back. Normal data packets
  13425. + * are, usually queued directly at the tail of the queue, so for those
  13426. + * search from back to front.
  13427. + */
  13428. +
  13429. + if (p->priority > SSH_PACKET_PRIORITY(DATA, 0)) {
  13430. + list_for_each(head, &p->ptl->queue.head) {
  13431. + q = list_entry(head, struct ssh_packet, queue_node);
  13432. +
  13433. + if (q->priority < p->priority)
  13434. + break;
  13435. + }
  13436. + } else {
  13437. + list_for_each_prev(head, &p->ptl->queue.head) {
  13438. + q = list_entry(head, struct ssh_packet, queue_node);
  13439. +
  13440. + if (q->priority >= p->priority) {
  13441. + head = head->next;
  13442. + break;
  13443. + }
  13444. + }
  13445. + }
  13446. +
  13447. + return head;
  13448. +}
  13449. +
  13450. +/* Must be called with queue lock held. */
  13451. +static int __ssh_ptl_queue_push(struct ssh_packet *packet)
  13452. +{
  13453. + struct ssh_ptl *ptl = packet->ptl;
  13454. + struct list_head *head;
  13455. +
  13456. + lockdep_assert_held(&ptl->queue.lock);
  13457. +
  13458. + if (test_bit(SSH_PTL_SF_SHUTDOWN_BIT, &ptl->state))
  13459. + return -ESHUTDOWN;
  13460. +
  13461. + /* Avoid further transitions when canceling/completing. */
  13462. + if (test_bit(SSH_PACKET_SF_LOCKED_BIT, &packet->state))
  13463. + return -EINVAL;
  13464. +
  13465. + /* If this packet has already been queued, do not add it. */
  13466. + if (test_and_set_bit(SSH_PACKET_SF_QUEUED_BIT, &packet->state))
  13467. + return -EALREADY;
  13468. +
  13469. + head = __ssh_ptl_queue_find_entrypoint(packet);
  13470. +
  13471. + list_add_tail(&ssh_packet_get(packet)->queue_node, head);
  13472. + return 0;
  13473. +}
  13474. +
  13475. +static int ssh_ptl_queue_push(struct ssh_packet *packet)
  13476. +{
  13477. + int status;
  13478. +
  13479. + spin_lock(&packet->ptl->queue.lock);
  13480. + status = __ssh_ptl_queue_push(packet);
  13481. + spin_unlock(&packet->ptl->queue.lock);
  13482. +
  13483. + return status;
  13484. +}
  13485. +
  13486. +static void ssh_ptl_queue_remove(struct ssh_packet *packet)
  13487. +{
  13488. + struct ssh_ptl *ptl = packet->ptl;
  13489. +
  13490. + spin_lock(&ptl->queue.lock);
  13491. +
  13492. + if (!test_and_clear_bit(SSH_PACKET_SF_QUEUED_BIT, &packet->state)) {
  13493. + spin_unlock(&ptl->queue.lock);
  13494. + return;
  13495. + }
  13496. +
  13497. + list_del(&packet->queue_node);
  13498. +
  13499. + spin_unlock(&ptl->queue.lock);
  13500. + ssh_packet_put(packet);
  13501. +}
  13502. +
  13503. +static void ssh_ptl_pending_push(struct ssh_packet *p)
  13504. +{
  13505. + struct ssh_ptl *ptl = p->ptl;
  13506. + const ktime_t timestamp = ktime_get_coarse_boottime();
  13507. + const ktime_t timeout = ptl->rtx_timeout.timeout;
  13508. +
  13509. + /*
  13510. + * Note: We can get the time for the timestamp before acquiring the
  13511. + * lock as this is the only place we're setting it and this function
  13512. + * is called only from the transmitter thread. Thus it is not possible
  13513. + * to overwrite the timestamp with an outdated value below.
  13514. + */
  13515. +
  13516. + spin_lock(&ptl->pending.lock);
  13517. +
  13518. + /* If we are canceling/completing this packet, do not add it. */
  13519. + if (test_bit(SSH_PACKET_SF_LOCKED_BIT, &p->state)) {
  13520. + spin_unlock(&ptl->pending.lock);
  13521. + return;
  13522. + }
  13523. +
  13524. + /*
  13525. + * On re-submission, the packet has already been added the pending
  13526. + * set. We still need to update the timestamp as the packet timeout is
  13527. + * reset for each (re-)submission.
  13528. + */
  13529. + p->timestamp = timestamp;
  13530. +
  13531. + /* In case it is already pending (e.g. re-submission), do not add it. */
  13532. + if (!test_and_set_bit(SSH_PACKET_SF_PENDING_BIT, &p->state)) {
  13533. + atomic_inc(&ptl->pending.count);
  13534. + list_add_tail(&ssh_packet_get(p)->pending_node, &ptl->pending.head);
  13535. + }
  13536. +
  13537. + spin_unlock(&ptl->pending.lock);
  13538. +
  13539. + /* Arm/update timeout reaper. */
  13540. + ssh_ptl_timeout_reaper_mod(ptl, timestamp, timestamp + timeout);
  13541. +}
  13542. +
  13543. +static void ssh_ptl_pending_remove(struct ssh_packet *packet)
  13544. +{
  13545. + struct ssh_ptl *ptl = packet->ptl;
  13546. +
  13547. + spin_lock(&ptl->pending.lock);
  13548. +
  13549. + if (!test_and_clear_bit(SSH_PACKET_SF_PENDING_BIT, &packet->state)) {
  13550. + spin_unlock(&ptl->pending.lock);
  13551. + return;
  13552. + }
  13553. +
  13554. + list_del(&packet->pending_node);
  13555. + atomic_dec(&ptl->pending.count);
  13556. +
  13557. + spin_unlock(&ptl->pending.lock);
  13558. +
  13559. + ssh_packet_put(packet);
  13560. +}
  13561. +
  13562. +/* Warning: Does not check/set "completed" bit. */
  13563. +static void __ssh_ptl_complete(struct ssh_packet *p, int status)
  13564. +{
  13565. + struct ssh_ptl *ptl = READ_ONCE(p->ptl);
  13566. +
  13567. + trace_ssam_packet_complete(p, status);
  13568. + ptl_dbg_cond(ptl, "ptl: completing packet %p (status: %d)\n", p, status);
  13569. +
  13570. + if (p->ops->complete)
  13571. + p->ops->complete(p, status);
  13572. +}
  13573. +
  13574. +static void ssh_ptl_remove_and_complete(struct ssh_packet *p, int status)
  13575. +{
  13576. + /*
  13577. + * A call to this function should in general be preceded by
  13578. + * set_bit(SSH_PACKET_SF_LOCKED_BIT, &p->flags) to avoid re-adding the
  13579. + * packet to the structures it's going to be removed from.
  13580. + *
  13581. + * The set_bit call does not need explicit memory barriers as the
  13582. + * implicit barrier of the test_and_set_bit() call below ensure that the
  13583. + * flag is visible before we actually attempt to remove the packet.
  13584. + */
  13585. +
  13586. + if (test_and_set_bit(SSH_PACKET_SF_COMPLETED_BIT, &p->state))
  13587. + return;
  13588. +
  13589. + ssh_ptl_queue_remove(p);
  13590. + ssh_ptl_pending_remove(p);
  13591. +
  13592. + __ssh_ptl_complete(p, status);
  13593. +}
  13594. +
  13595. +static bool ssh_ptl_tx_can_process(struct ssh_packet *packet)
  13596. +{
  13597. + struct ssh_ptl *ptl = packet->ptl;
  13598. +
  13599. + if (test_bit(SSH_PACKET_TY_FLUSH_BIT, &packet->state))
  13600. + return !atomic_read(&ptl->pending.count);
  13601. +
  13602. + /* We can always process non-blocking packets. */
  13603. + if (!test_bit(SSH_PACKET_TY_BLOCKING_BIT, &packet->state))
  13604. + return true;
  13605. +
  13606. + /* If we are already waiting for this packet, send it again. */
  13607. + if (test_bit(SSH_PACKET_SF_PENDING_BIT, &packet->state))
  13608. + return true;
  13609. +
  13610. + /* Otherwise: Check if we have the capacity to send. */
  13611. + return atomic_read(&ptl->pending.count) < SSH_PTL_MAX_PENDING;
  13612. +}
  13613. +
  13614. +static struct ssh_packet *ssh_ptl_tx_pop(struct ssh_ptl *ptl)
  13615. +{
  13616. + struct ssh_packet *packet = ERR_PTR(-ENOENT);
  13617. + struct ssh_packet *p, *n;
  13618. +
  13619. + spin_lock(&ptl->queue.lock);
  13620. + list_for_each_entry_safe(p, n, &ptl->queue.head, queue_node) {
  13621. + /*
  13622. + * If we are canceling or completing this packet, ignore it.
  13623. + * It's going to be removed from this queue shortly.
  13624. + */
  13625. + if (test_bit(SSH_PACKET_SF_LOCKED_BIT, &p->state))
  13626. + continue;
  13627. +
  13628. + /*
  13629. + * Packets should be ordered non-blocking/to-be-resent first.
  13630. + * If we cannot process this packet, assume that we can't
  13631. + * process any following packet either and abort.
  13632. + */
  13633. + if (!ssh_ptl_tx_can_process(p)) {
  13634. + packet = ERR_PTR(-EBUSY);
  13635. + break;
  13636. + }
  13637. +
  13638. + /*
  13639. + * We are allowed to change the state now. Remove it from the
  13640. + * queue and mark it as being transmitted.
  13641. + */
  13642. +
  13643. + list_del(&p->queue_node);
  13644. +
  13645. + set_bit(SSH_PACKET_SF_TRANSMITTING_BIT, &p->state);
  13646. + /* Ensure that state never gets zero. */
  13647. + smp_mb__before_atomic();
  13648. + clear_bit(SSH_PACKET_SF_QUEUED_BIT, &p->state);
  13649. +
  13650. + /*
  13651. + * Update number of tries. This directly influences the
  13652. + * priority in case the packet is re-submitted (e.g. via
  13653. + * timeout/NAK). Note that all reads and writes to the
  13654. + * priority after the first submission are guarded by the
  13655. + * queue lock.
  13656. + */
  13657. + ssh_packet_next_try(p);
  13658. +
  13659. + packet = p;
  13660. + break;
  13661. + }
  13662. + spin_unlock(&ptl->queue.lock);
  13663. +
  13664. + return packet;
  13665. +}
  13666. +
  13667. +static struct ssh_packet *ssh_ptl_tx_next(struct ssh_ptl *ptl)
  13668. +{
  13669. + struct ssh_packet *p;
  13670. +
  13671. + p = ssh_ptl_tx_pop(ptl);
  13672. + if (IS_ERR(p))
  13673. + return p;
  13674. +
  13675. + if (test_bit(SSH_PACKET_TY_SEQUENCED_BIT, &p->state)) {
  13676. + ptl_dbg(ptl, "ptl: transmitting sequenced packet %p\n", p);
  13677. + ssh_ptl_pending_push(p);
  13678. + } else {
  13679. + ptl_dbg(ptl, "ptl: transmitting non-sequenced packet %p\n", p);
  13680. + }
  13681. +
  13682. + return p;
  13683. +}
  13684. +
  13685. +static void ssh_ptl_tx_compl_success(struct ssh_packet *packet)
  13686. +{
  13687. + struct ssh_ptl *ptl = packet->ptl;
  13688. +
  13689. + ptl_dbg(ptl, "ptl: successfully transmitted packet %p\n", packet);
  13690. +
  13691. + /* Transition state to "transmitted". */
  13692. + set_bit(SSH_PACKET_SF_TRANSMITTED_BIT, &packet->state);
  13693. + /* Ensure that state never gets zero. */
  13694. + smp_mb__before_atomic();
  13695. + clear_bit(SSH_PACKET_SF_TRANSMITTING_BIT, &packet->state);
  13696. +
  13697. + /* If the packet is unsequenced, we're done: Lock and complete. */
  13698. + if (!test_bit(SSH_PACKET_TY_SEQUENCED_BIT, &packet->state)) {
  13699. + set_bit(SSH_PACKET_SF_LOCKED_BIT, &packet->state);
  13700. + ssh_ptl_remove_and_complete(packet, 0);
  13701. + }
  13702. +
  13703. + /*
  13704. + * Notify that a packet transmission has finished. In general we're only
  13705. + * waiting for one packet (if any), so wake_up_all should be fine.
  13706. + */
  13707. + wake_up_all(&ptl->tx.packet_wq);
  13708. +}
  13709. +
  13710. +static void ssh_ptl_tx_compl_error(struct ssh_packet *packet, int status)
  13711. +{
  13712. + /* Transmission failure: Lock the packet and try to complete it. */
  13713. + set_bit(SSH_PACKET_SF_LOCKED_BIT, &packet->state);
  13714. + /* Ensure that state never gets zero. */
  13715. + smp_mb__before_atomic();
  13716. + clear_bit(SSH_PACKET_SF_TRANSMITTING_BIT, &packet->state);
  13717. +
  13718. + ptl_err(packet->ptl, "ptl: transmission error: %d\n", status);
  13719. + ptl_dbg(packet->ptl, "ptl: failed to transmit packet: %p\n", packet);
  13720. +
  13721. + ssh_ptl_remove_and_complete(packet, status);
  13722. +
  13723. + /*
  13724. + * Notify that a packet transmission has finished. In general we're only
  13725. + * waiting for one packet (if any), so wake_up_all should be fine.
  13726. + */
  13727. + wake_up_all(&packet->ptl->tx.packet_wq);
  13728. +}
  13729. +
  13730. +static long ssh_ptl_tx_wait_packet(struct ssh_ptl *ptl)
  13731. +{
  13732. + int status;
  13733. +
  13734. + status = wait_for_completion_interruptible(&ptl->tx.thread_cplt_pkt);
  13735. + reinit_completion(&ptl->tx.thread_cplt_pkt);
  13736. +
  13737. + /*
  13738. + * Ensure completion is cleared before continuing to avoid lost update
  13739. + * problems.
  13740. + */
  13741. + smp_mb__after_atomic();
  13742. +
  13743. + return status;
  13744. +}
  13745. +
  13746. +static long ssh_ptl_tx_wait_transfer(struct ssh_ptl *ptl, long timeout)
  13747. +{
  13748. + long status;
  13749. +
  13750. + status = wait_for_completion_interruptible_timeout(&ptl->tx.thread_cplt_tx,
  13751. + timeout);
  13752. + reinit_completion(&ptl->tx.thread_cplt_tx);
  13753. +
  13754. + /*
  13755. + * Ensure completion is cleared before continuing to avoid lost update
  13756. + * problems.
  13757. + */
  13758. + smp_mb__after_atomic();
  13759. +
  13760. + return status;
  13761. +}
  13762. +
  13763. +static int ssh_ptl_tx_packet(struct ssh_ptl *ptl, struct ssh_packet *packet)
  13764. +{
  13765. + long timeout = SSH_PTL_TX_TIMEOUT;
  13766. + size_t offset = 0;
  13767. +
  13768. + /* Note: Flush-packets don't have any data. */
  13769. + if (unlikely(!packet->data.ptr))
  13770. + return 0;
  13771. +
  13772. + /* Error injection: drop packet to simulate transmission problem. */
  13773. + if (ssh_ptl_should_drop_packet(packet))
  13774. + return 0;
  13775. +
  13776. + /* Error injection: simulate invalid packet data. */
  13777. + ssh_ptl_tx_inject_invalid_data(packet);
  13778. +
  13779. + ptl_dbg(ptl, "tx: sending data (length: %zu)\n", packet->data.len);
  13780. + print_hex_dump_debug("tx: ", DUMP_PREFIX_OFFSET, 16, 1,
  13781. + packet->data.ptr, packet->data.len, false);
  13782. +
  13783. + do {
  13784. + ssize_t status, len;
  13785. + u8 *buf;
  13786. +
  13787. + buf = packet->data.ptr + offset;
  13788. + len = packet->data.len - offset;
  13789. +
  13790. + status = ssh_ptl_write_buf(ptl, packet, buf, len);
  13791. + if (status < 0)
  13792. + return status;
  13793. +
  13794. + if (status == len)
  13795. + return 0;
  13796. +
  13797. + offset += status;
  13798. +
  13799. + timeout = ssh_ptl_tx_wait_transfer(ptl, timeout);
  13800. + if (kthread_should_stop() || !atomic_read(&ptl->tx.running))
  13801. + return -ESHUTDOWN;
  13802. +
  13803. + if (timeout < 0)
  13804. + return -EINTR;
  13805. +
  13806. + if (timeout == 0)
  13807. + return -ETIMEDOUT;
  13808. + } while (true);
  13809. +}
  13810. +
  13811. +static int ssh_ptl_tx_threadfn(void *data)
  13812. +{
  13813. + struct ssh_ptl *ptl = data;
  13814. +
  13815. + while (!kthread_should_stop() && atomic_read(&ptl->tx.running)) {
  13816. + struct ssh_packet *packet;
  13817. + int status;
  13818. +
  13819. + /* Try to get the next packet. */
  13820. + packet = ssh_ptl_tx_next(ptl);
  13821. +
  13822. + /* If no packet can be processed, we are done. */
  13823. + if (IS_ERR(packet)) {
  13824. + ssh_ptl_tx_wait_packet(ptl);
  13825. + continue;
  13826. + }
  13827. +
  13828. + /* Transfer and complete packet. */
  13829. + status = ssh_ptl_tx_packet(ptl, packet);
  13830. + if (status)
  13831. + ssh_ptl_tx_compl_error(packet, status);
  13832. + else
  13833. + ssh_ptl_tx_compl_success(packet);
  13834. +
  13835. + ssh_packet_put(packet);
  13836. + }
  13837. +
  13838. + return 0;
  13839. +}
  13840. +
  13841. +/**
  13842. + * ssh_ptl_tx_wakeup_packet() - Wake up packet transmitter thread for new
  13843. + * packet.
  13844. + * @ptl: The packet transport layer.
  13845. + *
  13846. + * Wakes up the packet transmitter thread, notifying it that a new packet has
  13847. + * arrived and is ready for transfer. If the packet transport layer has been
  13848. + * shut down, calls to this function will be ignored.
  13849. + */
  13850. +static void ssh_ptl_tx_wakeup_packet(struct ssh_ptl *ptl)
  13851. +{
  13852. + if (test_bit(SSH_PTL_SF_SHUTDOWN_BIT, &ptl->state))
  13853. + return;
  13854. +
  13855. + complete(&ptl->tx.thread_cplt_pkt);
  13856. +}
  13857. +
  13858. +/**
  13859. + * ssh_ptl_tx_start() - Start packet transmitter thread.
  13860. + * @ptl: The packet transport layer.
  13861. + *
  13862. + * Return: Returns zero on success, a negative error code on failure.
  13863. + */
  13864. +int ssh_ptl_tx_start(struct ssh_ptl *ptl)
  13865. +{
  13866. + atomic_set_release(&ptl->tx.running, 1);
  13867. +
  13868. + ptl->tx.thread = kthread_run(ssh_ptl_tx_threadfn, ptl, "ssam_serial_hub-tx");
  13869. + if (IS_ERR(ptl->tx.thread))
  13870. + return PTR_ERR(ptl->tx.thread);
  13871. +
  13872. + return 0;
  13873. +}
  13874. +
  13875. +/**
  13876. + * ssh_ptl_tx_stop() - Stop packet transmitter thread.
  13877. + * @ptl: The packet transport layer.
  13878. + *
  13879. + * Return: Returns zero on success, a negative error code on failure.
  13880. + */
  13881. +int ssh_ptl_tx_stop(struct ssh_ptl *ptl)
  13882. +{
  13883. + int status = 0;
  13884. +
  13885. + if (!IS_ERR_OR_NULL(ptl->tx.thread)) {
  13886. + /* Tell thread to stop. */
  13887. + atomic_set_release(&ptl->tx.running, 0);
  13888. +
  13889. + /*
  13890. + * Wake up thread in case it is paused. Do not use wakeup
  13891. + * helpers as this may be called when the shutdown bit has
  13892. + * already been set.
  13893. + */
  13894. + complete(&ptl->tx.thread_cplt_pkt);
  13895. + complete(&ptl->tx.thread_cplt_tx);
  13896. +
  13897. + /* Finally, wait for thread to stop. */
  13898. + status = kthread_stop(ptl->tx.thread);
  13899. + ptl->tx.thread = NULL;
  13900. + }
  13901. +
  13902. + return status;
  13903. +}
  13904. +
  13905. +static struct ssh_packet *ssh_ptl_ack_pop(struct ssh_ptl *ptl, u8 seq_id)
  13906. +{
  13907. + struct ssh_packet *packet = ERR_PTR(-ENOENT);
  13908. + struct ssh_packet *p, *n;
  13909. +
  13910. + spin_lock(&ptl->pending.lock);
  13911. + list_for_each_entry_safe(p, n, &ptl->pending.head, pending_node) {
  13912. + /*
  13913. + * We generally expect packets to be in order, so first packet
  13914. + * to be added to pending is first to be sent, is first to be
  13915. + * ACKed.
  13916. + */
  13917. + if (unlikely(ssh_packet_get_seq(p) != seq_id))
  13918. + continue;
  13919. +
  13920. + /*
  13921. + * In case we receive an ACK while handling a transmission
  13922. + * error completion. The packet will be removed shortly.
  13923. + */
  13924. + if (unlikely(test_bit(SSH_PACKET_SF_LOCKED_BIT, &p->state))) {
  13925. + packet = ERR_PTR(-EPERM);
  13926. + break;
  13927. + }
  13928. +
  13929. + /*
  13930. + * Mark the packet as ACKed and remove it from pending by
  13931. + * removing its node and decrementing the pending counter.
  13932. + */
  13933. + set_bit(SSH_PACKET_SF_ACKED_BIT, &p->state);
  13934. + /* Ensure that state never gets zero. */
  13935. + smp_mb__before_atomic();
  13936. + clear_bit(SSH_PACKET_SF_PENDING_BIT, &p->state);
  13937. +
  13938. + atomic_dec(&ptl->pending.count);
  13939. + list_del(&p->pending_node);
  13940. + packet = p;
  13941. +
  13942. + break;
  13943. + }
  13944. + spin_unlock(&ptl->pending.lock);
  13945. +
  13946. + return packet;
  13947. +}
  13948. +
  13949. +static void ssh_ptl_wait_until_transmitted(struct ssh_packet *packet)
  13950. +{
  13951. + wait_event(packet->ptl->tx.packet_wq,
  13952. + test_bit(SSH_PACKET_SF_TRANSMITTED_BIT, &packet->state) ||
  13953. + test_bit(SSH_PACKET_SF_LOCKED_BIT, &packet->state));
  13954. +}
  13955. +
  13956. +static void ssh_ptl_acknowledge(struct ssh_ptl *ptl, u8 seq)
  13957. +{
  13958. + struct ssh_packet *p;
  13959. +
  13960. + p = ssh_ptl_ack_pop(ptl, seq);
  13961. + if (IS_ERR(p)) {
  13962. + if (PTR_ERR(p) == -ENOENT) {
  13963. + /*
  13964. + * The packet has not been found in the set of pending
  13965. + * packets.
  13966. + */
  13967. + ptl_warn(ptl, "ptl: received ACK for non-pending packet\n");
  13968. + } else {
  13969. + /*
  13970. + * The packet is pending, but we are not allowed to take
  13971. + * it because it has been locked.
  13972. + */
  13973. + WARN_ON(PTR_ERR(p) != -EPERM);
  13974. + }
  13975. + return;
  13976. + }
  13977. +
  13978. + ptl_dbg(ptl, "ptl: received ACK for packet %p\n", p);
  13979. +
  13980. + /*
  13981. + * It is possible that the packet has been transmitted, but the state
  13982. + * has not been updated from "transmitting" to "transmitted" yet.
  13983. + * In that case, we need to wait for this transition to occur in order
  13984. + * to determine between success or failure.
  13985. + *
  13986. + * On transmission failure, the packet will be locked after this call.
  13987. + * On success, the transmitted bit will be set.
  13988. + */
  13989. + ssh_ptl_wait_until_transmitted(p);
  13990. +
  13991. + /*
  13992. + * The packet will already be locked in case of a transmission error or
  13993. + * cancellation. Let the transmitter or cancellation issuer complete the
  13994. + * packet.
  13995. + */
  13996. + if (unlikely(test_and_set_bit(SSH_PACKET_SF_LOCKED_BIT, &p->state))) {
  13997. + if (unlikely(!test_bit(SSH_PACKET_SF_TRANSMITTED_BIT, &p->state)))
  13998. + ptl_err(ptl, "ptl: received ACK before packet had been fully transmitted\n");
  13999. +
  14000. + ssh_packet_put(p);
  14001. + return;
  14002. + }
  14003. +
  14004. + ssh_ptl_remove_and_complete(p, 0);
  14005. + ssh_packet_put(p);
  14006. +
  14007. + if (atomic_read(&ptl->pending.count) < SSH_PTL_MAX_PENDING)
  14008. + ssh_ptl_tx_wakeup_packet(ptl);
  14009. +}
  14010. +
  14011. +/**
  14012. + * ssh_ptl_submit() - Submit a packet to the transport layer.
  14013. + * @ptl: The packet transport layer to submit the packet to.
  14014. + * @p: The packet to submit.
  14015. + *
  14016. + * Submits a new packet to the transport layer, queuing it to be sent. This
  14017. + * function should not be used for re-submission.
  14018. + *
  14019. + * Return: Returns zero on success, %-EINVAL if a packet field is invalid or
  14020. + * the packet has been canceled prior to submission, %-EALREADY if the packet
  14021. + * has already been submitted, or %-ESHUTDOWN if the packet transport layer
  14022. + * has been shut down.
  14023. + */
  14024. +int ssh_ptl_submit(struct ssh_ptl *ptl, struct ssh_packet *p)
  14025. +{
  14026. + struct ssh_ptl *ptl_old;
  14027. + int status;
  14028. +
  14029. + trace_ssam_packet_submit(p);
  14030. +
  14031. + /* Validate packet fields. */
  14032. + if (test_bit(SSH_PACKET_TY_FLUSH_BIT, &p->state)) {
  14033. + if (p->data.ptr || test_bit(SSH_PACKET_TY_SEQUENCED_BIT, &p->state))
  14034. + return -EINVAL;
  14035. + } else if (!p->data.ptr) {
  14036. + return -EINVAL;
  14037. + }
  14038. +
  14039. + /*
  14040. + * The ptl reference only gets set on or before the first submission.
  14041. + * After the first submission, it has to be read-only.
  14042. + *
  14043. + * Note that ptl may already be set from upper-layer request
  14044. + * submission, thus we cannot expect it to be NULL.
  14045. + */
  14046. + ptl_old = READ_ONCE(p->ptl);
  14047. + if (!ptl_old)
  14048. + WRITE_ONCE(p->ptl, ptl);
  14049. + else if (WARN_ON(ptl_old != ptl))
  14050. + return -EALREADY; /* Submitted on different PTL. */
  14051. +
  14052. + status = ssh_ptl_queue_push(p);
  14053. + if (status)
  14054. + return status;
  14055. +
  14056. + if (!test_bit(SSH_PACKET_TY_BLOCKING_BIT, &p->state) ||
  14057. + (atomic_read(&ptl->pending.count) < SSH_PTL_MAX_PENDING))
  14058. + ssh_ptl_tx_wakeup_packet(ptl);
  14059. +
  14060. + return 0;
  14061. +}
  14062. +
  14063. +/*
  14064. + * __ssh_ptl_resubmit() - Re-submit a packet to the transport layer.
  14065. + * @packet: The packet to re-submit.
  14066. + *
  14067. + * Re-submits the given packet: Checks if it can be re-submitted and queues it
  14068. + * if it can, resetting the packet timestamp in the process. Must be called
  14069. + * with the pending lock held.
  14070. + *
  14071. + * Return: Returns %-ECANCELED if the packet has exceeded its number of tries,
  14072. + * %-EINVAL if the packet has been locked, %-EALREADY if the packet is already
  14073. + * on the queue, and %-ESHUTDOWN if the transmission layer has been shut down.
  14074. + */
  14075. +static int __ssh_ptl_resubmit(struct ssh_packet *packet)
  14076. +{
  14077. + int status;
  14078. + u8 try;
  14079. +
  14080. + lockdep_assert_held(&packet->ptl->pending.lock);
  14081. +
  14082. + trace_ssam_packet_resubmit(packet);
  14083. +
  14084. + spin_lock(&packet->ptl->queue.lock);
  14085. +
  14086. + /* Check if the packet is out of tries. */
  14087. + try = ssh_packet_priority_get_try(packet->priority);
  14088. + if (try >= SSH_PTL_MAX_PACKET_TRIES) {
  14089. + spin_unlock(&packet->ptl->queue.lock);
  14090. + return -ECANCELED;
  14091. + }
  14092. +
  14093. + status = __ssh_ptl_queue_push(packet);
  14094. + if (status) {
  14095. + /*
  14096. + * An error here indicates that the packet has either already
  14097. + * been queued, been locked, or the transport layer is being
  14098. + * shut down. In all cases: Ignore the error.
  14099. + */
  14100. + spin_unlock(&packet->ptl->queue.lock);
  14101. + return status;
  14102. + }
  14103. +
  14104. + packet->timestamp = KTIME_MAX;
  14105. +
  14106. + spin_unlock(&packet->ptl->queue.lock);
  14107. + return 0;
  14108. +}
  14109. +
  14110. +static void ssh_ptl_resubmit_pending(struct ssh_ptl *ptl)
  14111. +{
  14112. + struct ssh_packet *p;
  14113. + bool resub = false;
  14114. +
  14115. + /*
  14116. + * Note: We deliberately do not remove/attempt to cancel and complete
  14117. + * packets that are out of tires in this function. The packet will be
  14118. + * eventually canceled and completed by the timeout. Removing the packet
  14119. + * here could lead to overly eager cancellation if the packet has not
  14120. + * been re-transmitted yet but the tries-counter already updated (i.e
  14121. + * ssh_ptl_tx_next() removed the packet from the queue and updated the
  14122. + * counter, but re-transmission for the last try has not actually
  14123. + * started yet).
  14124. + */
  14125. +
  14126. + spin_lock(&ptl->pending.lock);
  14127. +
  14128. + /* Re-queue all pending packets. */
  14129. + list_for_each_entry(p, &ptl->pending.head, pending_node) {
  14130. + /*
  14131. + * Re-submission fails if the packet is out of tries, has been
  14132. + * locked, is already queued, or the layer is being shut down.
  14133. + * No need to re-schedule tx-thread in those cases.
  14134. + */
  14135. + if (!__ssh_ptl_resubmit(p))
  14136. + resub = true;
  14137. + }
  14138. +
  14139. + spin_unlock(&ptl->pending.lock);
  14140. +
  14141. + if (resub)
  14142. + ssh_ptl_tx_wakeup_packet(ptl);
  14143. +}
  14144. +
  14145. +/**
  14146. + * ssh_ptl_cancel() - Cancel a packet.
  14147. + * @p: The packet to cancel.
  14148. + *
  14149. + * Cancels a packet. There are no guarantees on when completion and release
  14150. + * callbacks will be called. This may occur during execution of this function
  14151. + * or may occur at any point later.
  14152. + *
  14153. + * Note that it is not guaranteed that the packet will actually be canceled if
  14154. + * the packet is concurrently completed by another process. The only guarantee
  14155. + * of this function is that the packet will be completed (with success,
  14156. + * failure, or cancellation) and released from the transport layer in a
  14157. + * reasonable time-frame.
  14158. + *
  14159. + * May be called before the packet has been submitted, in which case any later
  14160. + * packet submission fails.
  14161. + */
  14162. +void ssh_ptl_cancel(struct ssh_packet *p)
  14163. +{
  14164. + if (test_and_set_bit(SSH_PACKET_SF_CANCELED_BIT, &p->state))
  14165. + return;
  14166. +
  14167. + trace_ssam_packet_cancel(p);
  14168. +
  14169. + /*
  14170. + * Lock packet and commit with memory barrier. If this packet has
  14171. + * already been locked, it's going to be removed and completed by
  14172. + * another party, which should have precedence.
  14173. + */
  14174. + if (test_and_set_bit(SSH_PACKET_SF_LOCKED_BIT, &p->state))
  14175. + return;
  14176. +
  14177. + /*
  14178. + * By marking the packet as locked and employing the implicit memory
  14179. + * barrier of test_and_set_bit, we have guaranteed that, at this point,
  14180. + * the packet cannot be added to the queue any more.
  14181. + *
  14182. + * In case the packet has never been submitted, packet->ptl is NULL. If
  14183. + * the packet is currently being submitted, packet->ptl may be NULL or
  14184. + * non-NULL. Due marking the packet as locked above and committing with
  14185. + * the memory barrier, we have guaranteed that, if packet->ptl is NULL,
  14186. + * the packet will never be added to the queue. If packet->ptl is
  14187. + * non-NULL, we don't have any guarantees.
  14188. + */
  14189. +
  14190. + if (READ_ONCE(p->ptl)) {
  14191. + ssh_ptl_remove_and_complete(p, -ECANCELED);
  14192. +
  14193. + if (atomic_read(&p->ptl->pending.count) < SSH_PTL_MAX_PENDING)
  14194. + ssh_ptl_tx_wakeup_packet(p->ptl);
  14195. +
  14196. + } else if (!test_and_set_bit(SSH_PACKET_SF_COMPLETED_BIT, &p->state)) {
  14197. + __ssh_ptl_complete(p, -ECANCELED);
  14198. + }
  14199. +}
  14200. +
  14201. +/* Must be called with pending lock held */
  14202. +static ktime_t ssh_packet_get_expiration(struct ssh_packet *p, ktime_t timeout)
  14203. +{
  14204. + lockdep_assert_held(&p->ptl->pending.lock);
  14205. +
  14206. + if (p->timestamp != KTIME_MAX)
  14207. + return ktime_add(p->timestamp, timeout);
  14208. + else
  14209. + return KTIME_MAX;
  14210. +}
  14211. +
  14212. +static void ssh_ptl_timeout_reap(struct work_struct *work)
  14213. +{
  14214. + struct ssh_ptl *ptl = to_ssh_ptl(work, rtx_timeout.reaper.work);
  14215. + struct ssh_packet *p, *n;
  14216. + LIST_HEAD(claimed);
  14217. + ktime_t now = ktime_get_coarse_boottime();
  14218. + ktime_t timeout = ptl->rtx_timeout.timeout;
  14219. + ktime_t next = KTIME_MAX;
  14220. + bool resub = false;
  14221. + int status;
  14222. +
  14223. + trace_ssam_ptl_timeout_reap(atomic_read(&ptl->pending.count));
  14224. +
  14225. + /*
  14226. + * Mark reaper as "not pending". This is done before checking any
  14227. + * packets to avoid lost-update type problems.
  14228. + */
  14229. + spin_lock(&ptl->rtx_timeout.lock);
  14230. + ptl->rtx_timeout.expires = KTIME_MAX;
  14231. + spin_unlock(&ptl->rtx_timeout.lock);
  14232. +
  14233. + spin_lock(&ptl->pending.lock);
  14234. +
  14235. + list_for_each_entry_safe(p, n, &ptl->pending.head, pending_node) {
  14236. + ktime_t expires = ssh_packet_get_expiration(p, timeout);
  14237. +
  14238. + /*
  14239. + * Check if the timeout hasn't expired yet. Find out next
  14240. + * expiration date to be handled after this run.
  14241. + */
  14242. + if (ktime_after(expires, now)) {
  14243. + next = ktime_before(expires, next) ? expires : next;
  14244. + continue;
  14245. + }
  14246. +
  14247. + trace_ssam_packet_timeout(p);
  14248. +
  14249. + status = __ssh_ptl_resubmit(p);
  14250. +
  14251. + /*
  14252. + * Re-submission fails if the packet is out of tries, has been
  14253. + * locked, is already queued, or the layer is being shut down.
  14254. + * No need to re-schedule tx-thread in those cases.
  14255. + */
  14256. + if (!status)
  14257. + resub = true;
  14258. +
  14259. + /* Go to next packet if this packet is not out of tries. */
  14260. + if (status != -ECANCELED)
  14261. + continue;
  14262. +
  14263. + /* No more tries left: Cancel the packet. */
  14264. +
  14265. + /*
  14266. + * If someone else has locked the packet already, don't use it
  14267. + * and let the other party complete it.
  14268. + */
  14269. + if (test_and_set_bit(SSH_PACKET_SF_LOCKED_BIT, &p->state))
  14270. + continue;
  14271. +
  14272. + /*
  14273. + * We have now marked the packet as locked. Thus it cannot be
  14274. + * added to the pending list again after we've removed it here.
  14275. + * We can therefore re-use the pending_node of this packet
  14276. + * temporarily.
  14277. + */
  14278. +
  14279. + clear_bit(SSH_PACKET_SF_PENDING_BIT, &p->state);
  14280. +
  14281. + atomic_dec(&ptl->pending.count);
  14282. + list_del(&p->pending_node);
  14283. +
  14284. + list_add_tail(&p->pending_node, &claimed);
  14285. + }
  14286. +
  14287. + spin_unlock(&ptl->pending.lock);
  14288. +
  14289. + /* Cancel and complete the packet. */
  14290. + list_for_each_entry_safe(p, n, &claimed, pending_node) {
  14291. + if (!test_and_set_bit(SSH_PACKET_SF_COMPLETED_BIT, &p->state)) {
  14292. + ssh_ptl_queue_remove(p);
  14293. + __ssh_ptl_complete(p, -ETIMEDOUT);
  14294. + }
  14295. +
  14296. + /*
  14297. + * Drop the reference we've obtained by removing it from
  14298. + * the pending set.
  14299. + */
  14300. + list_del(&p->pending_node);
  14301. + ssh_packet_put(p);
  14302. + }
  14303. +
  14304. + /* Ensure that reaper doesn't run again immediately. */
  14305. + next = max(next, ktime_add(now, SSH_PTL_PACKET_TIMEOUT_RESOLUTION));
  14306. + if (next != KTIME_MAX)
  14307. + ssh_ptl_timeout_reaper_mod(ptl, now, next);
  14308. +
  14309. + if (resub)
  14310. + ssh_ptl_tx_wakeup_packet(ptl);
  14311. +}
  14312. +
  14313. +static bool ssh_ptl_rx_retransmit_check(struct ssh_ptl *ptl, u8 seq)
  14314. +{
  14315. + int i;
  14316. +
  14317. + /*
  14318. + * Check if SEQ has been seen recently (i.e. packet was
  14319. + * re-transmitted and we should ignore it).
  14320. + */
  14321. + for (i = 0; i < ARRAY_SIZE(ptl->rx.blocked.seqs); i++) {
  14322. + if (likely(ptl->rx.blocked.seqs[i] != seq))
  14323. + continue;
  14324. +
  14325. + ptl_dbg(ptl, "ptl: ignoring repeated data packet\n");
  14326. + return true;
  14327. + }
  14328. +
  14329. + /* Update list of blocked sequence IDs. */
  14330. + ptl->rx.blocked.seqs[ptl->rx.blocked.offset] = seq;
  14331. + ptl->rx.blocked.offset = (ptl->rx.blocked.offset + 1)
  14332. + % ARRAY_SIZE(ptl->rx.blocked.seqs);
  14333. +
  14334. + return false;
  14335. +}
  14336. +
  14337. +static void ssh_ptl_rx_dataframe(struct ssh_ptl *ptl,
  14338. + const struct ssh_frame *frame,
  14339. + const struct ssam_span *payload)
  14340. +{
  14341. + if (ssh_ptl_rx_retransmit_check(ptl, frame->seq))
  14342. + return;
  14343. +
  14344. + ptl->ops.data_received(ptl, payload);
  14345. +}
  14346. +
  14347. +static void ssh_ptl_send_ack(struct ssh_ptl *ptl, u8 seq)
  14348. +{
  14349. + struct ssh_packet *packet;
  14350. + struct ssam_span buf;
  14351. + struct msgbuf msgb;
  14352. + int status;
  14353. +
  14354. + status = ssh_ctrl_packet_alloc(&packet, &buf, GFP_KERNEL);
  14355. + if (status) {
  14356. + ptl_err(ptl, "ptl: failed to allocate ACK packet\n");
  14357. + return;
  14358. + }
  14359. +
  14360. + ssh_packet_init(packet, 0, SSH_PACKET_PRIORITY(ACK, 0),
  14361. + &ssh_ptl_ctrl_packet_ops);
  14362. +
  14363. + msgb_init(&msgb, buf.ptr, buf.len);
  14364. + msgb_push_ack(&msgb, seq);
  14365. + ssh_packet_set_data(packet, msgb.begin, msgb_bytes_used(&msgb));
  14366. +
  14367. + ssh_ptl_submit(ptl, packet);
  14368. + ssh_packet_put(packet);
  14369. +}
  14370. +
  14371. +static void ssh_ptl_send_nak(struct ssh_ptl *ptl)
  14372. +{
  14373. + struct ssh_packet *packet;
  14374. + struct ssam_span buf;
  14375. + struct msgbuf msgb;
  14376. + int status;
  14377. +
  14378. + status = ssh_ctrl_packet_alloc(&packet, &buf, GFP_KERNEL);
  14379. + if (status) {
  14380. + ptl_err(ptl, "ptl: failed to allocate NAK packet\n");
  14381. + return;
  14382. + }
  14383. +
  14384. + ssh_packet_init(packet, 0, SSH_PACKET_PRIORITY(NAK, 0),
  14385. + &ssh_ptl_ctrl_packet_ops);
  14386. +
  14387. + msgb_init(&msgb, buf.ptr, buf.len);
  14388. + msgb_push_nak(&msgb);
  14389. + ssh_packet_set_data(packet, msgb.begin, msgb_bytes_used(&msgb));
  14390. +
  14391. + ssh_ptl_submit(ptl, packet);
  14392. + ssh_packet_put(packet);
  14393. +}
  14394. +
  14395. +static size_t ssh_ptl_rx_eval(struct ssh_ptl *ptl, struct ssam_span *source)
  14396. +{
  14397. + struct ssh_frame *frame;
  14398. + struct ssam_span payload;
  14399. + struct ssam_span aligned;
  14400. + bool syn_found;
  14401. + int status;
  14402. +
  14403. + /* Error injection: Modify data to simulate corrupt SYN bytes. */
  14404. + ssh_ptl_rx_inject_invalid_syn(ptl, source);
  14405. +
  14406. + /* Find SYN. */
  14407. + syn_found = sshp_find_syn(source, &aligned);
  14408. +
  14409. + if (unlikely(aligned.ptr - source->ptr) > 0) {
  14410. + ptl_warn(ptl, "rx: parser: invalid start of frame, skipping\n");
  14411. +
  14412. + /*
  14413. + * Notes:
  14414. + * - This might send multiple NAKs in case the communication
  14415. + * starts with an invalid SYN and is broken down into multiple
  14416. + * pieces. This should generally be handled fine, we just
  14417. + * might receive duplicate data in this case, which is
  14418. + * detected when handling data frames.
  14419. + * - This path will also be executed on invalid CRCs: When an
  14420. + * invalid CRC is encountered, the code below will skip data
  14421. + * until directly after the SYN. This causes the search for
  14422. + * the next SYN, which is generally not placed directly after
  14423. + * the last one.
  14424. + *
  14425. + * Open question: Should we send this in case of invalid
  14426. + * payload CRCs if the frame-type is non-sequential (current
  14427. + * implementation) or should we drop that frame without
  14428. + * telling the EC?
  14429. + */
  14430. + ssh_ptl_send_nak(ptl);
  14431. + }
  14432. +
  14433. + if (unlikely(!syn_found))
  14434. + return aligned.ptr - source->ptr;
  14435. +
  14436. + /* Error injection: Modify data to simulate corruption. */
  14437. + ssh_ptl_rx_inject_invalid_data(ptl, &aligned);
  14438. +
  14439. + /* Parse and validate frame. */
  14440. + status = sshp_parse_frame(&ptl->serdev->dev, &aligned, &frame, &payload,
  14441. + SSH_PTL_RX_BUF_LEN);
  14442. + if (status) /* Invalid frame: skip to next SYN. */
  14443. + return aligned.ptr - source->ptr + sizeof(u16);
  14444. + if (!frame) /* Not enough data. */
  14445. + return aligned.ptr - source->ptr;
  14446. +
  14447. + trace_ssam_rx_frame_received(frame);
  14448. +
  14449. + switch (frame->type) {
  14450. + case SSH_FRAME_TYPE_ACK:
  14451. + ssh_ptl_acknowledge(ptl, frame->seq);
  14452. + break;
  14453. +
  14454. + case SSH_FRAME_TYPE_NAK:
  14455. + ssh_ptl_resubmit_pending(ptl);
  14456. + break;
  14457. +
  14458. + case SSH_FRAME_TYPE_DATA_SEQ:
  14459. + ssh_ptl_send_ack(ptl, frame->seq);
  14460. + fallthrough;
  14461. +
  14462. + case SSH_FRAME_TYPE_DATA_NSQ:
  14463. + ssh_ptl_rx_dataframe(ptl, frame, &payload);
  14464. + break;
  14465. +
  14466. + default:
  14467. + ptl_warn(ptl, "ptl: received frame with unknown type %#04x\n",
  14468. + frame->type);
  14469. + break;
  14470. + }
  14471. +
  14472. + return aligned.ptr - source->ptr + SSH_MESSAGE_LENGTH(frame->len);
  14473. +}
  14474. +
  14475. +static int ssh_ptl_rx_threadfn(void *data)
  14476. +{
  14477. + struct ssh_ptl *ptl = data;
  14478. +
  14479. + while (true) {
  14480. + struct ssam_span span;
  14481. + size_t offs = 0;
  14482. + size_t n;
  14483. +
  14484. + wait_event_interruptible(ptl->rx.wq,
  14485. + !kfifo_is_empty(&ptl->rx.fifo) ||
  14486. + kthread_should_stop());
  14487. + if (kthread_should_stop())
  14488. + break;
  14489. +
  14490. + /* Copy from fifo to evaluation buffer. */
  14491. + n = sshp_buf_read_from_fifo(&ptl->rx.buf, &ptl->rx.fifo);
  14492. +
  14493. + ptl_dbg(ptl, "rx: received data (size: %zu)\n", n);
  14494. + print_hex_dump_debug("rx: ", DUMP_PREFIX_OFFSET, 16, 1,
  14495. + ptl->rx.buf.ptr + ptl->rx.buf.len - n,
  14496. + n, false);
  14497. +
  14498. + /* Parse until we need more bytes or buffer is empty. */
  14499. + while (offs < ptl->rx.buf.len) {
  14500. + sshp_buf_span_from(&ptl->rx.buf, offs, &span);
  14501. + n = ssh_ptl_rx_eval(ptl, &span);
  14502. + if (n == 0)
  14503. + break; /* Need more bytes. */
  14504. +
  14505. + offs += n;
  14506. + }
  14507. +
  14508. + /* Throw away the evaluated parts. */
  14509. + sshp_buf_drop(&ptl->rx.buf, offs);
  14510. + }
  14511. +
  14512. + return 0;
  14513. +}
  14514. +
  14515. +static void ssh_ptl_rx_wakeup(struct ssh_ptl *ptl)
  14516. +{
  14517. + wake_up(&ptl->rx.wq);
  14518. +}
  14519. +
  14520. +/**
  14521. + * ssh_ptl_rx_start() - Start packet transport layer receiver thread.
  14522. + * @ptl: The packet transport layer.
  14523. + *
  14524. + * Return: Returns zero on success, a negative error code on failure.
  14525. + */
  14526. +int ssh_ptl_rx_start(struct ssh_ptl *ptl)
  14527. +{
  14528. + if (ptl->rx.thread)
  14529. + return 0;
  14530. +
  14531. + ptl->rx.thread = kthread_run(ssh_ptl_rx_threadfn, ptl,
  14532. + "ssam_serial_hub-rx");
  14533. + if (IS_ERR(ptl->rx.thread))
  14534. + return PTR_ERR(ptl->rx.thread);
  14535. +
  14536. + return 0;
  14537. +}
  14538. +
  14539. +/**
  14540. + * ssh_ptl_rx_stop() - Stop packet transport layer receiver thread.
  14541. + * @ptl: The packet transport layer.
  14542. + *
  14543. + * Return: Returns zero on success, a negative error code on failure.
  14544. + */
  14545. +int ssh_ptl_rx_stop(struct ssh_ptl *ptl)
  14546. +{
  14547. + int status = 0;
  14548. +
  14549. + if (ptl->rx.thread) {
  14550. + status = kthread_stop(ptl->rx.thread);
  14551. + ptl->rx.thread = NULL;
  14552. + }
  14553. +
  14554. + return status;
  14555. +}
  14556. +
  14557. +/**
  14558. + * ssh_ptl_rx_rcvbuf() - Push data from lower-layer transport to the packet
  14559. + * layer.
  14560. + * @ptl: The packet transport layer.
  14561. + * @buf: Pointer to the data to push to the layer.
  14562. + * @n: Size of the data to push to the layer, in bytes.
  14563. + *
  14564. + * Pushes data from a lower-layer transport to the receiver fifo buffer of the
  14565. + * packet layer and notifies the receiver thread. Calls to this function are
  14566. + * ignored once the packet layer has been shut down.
  14567. + *
  14568. + * Return: Returns the number of bytes transferred (positive or zero) on
  14569. + * success. Returns %-ESHUTDOWN if the packet layer has been shut down.
  14570. + */
  14571. +int ssh_ptl_rx_rcvbuf(struct ssh_ptl *ptl, const u8 *buf, size_t n)
  14572. +{
  14573. + int used;
  14574. +
  14575. + if (test_bit(SSH_PTL_SF_SHUTDOWN_BIT, &ptl->state))
  14576. + return -ESHUTDOWN;
  14577. +
  14578. + used = kfifo_in(&ptl->rx.fifo, buf, n);
  14579. + if (used)
  14580. + ssh_ptl_rx_wakeup(ptl);
  14581. +
  14582. + return used;
  14583. +}
  14584. +
  14585. +/**
  14586. + * ssh_ptl_shutdown() - Shut down the packet transport layer.
  14587. + * @ptl: The packet transport layer.
  14588. + *
  14589. + * Shuts down the packet transport layer, removing and canceling all queued
  14590. + * and pending packets. Packets canceled by this operation will be completed
  14591. + * with %-ESHUTDOWN as status. Receiver and transmitter threads will be
  14592. + * stopped.
  14593. + *
  14594. + * As a result of this function, the transport layer will be marked as shut
  14595. + * down. Submission of packets after the transport layer has been shut down
  14596. + * will fail with %-ESHUTDOWN.
  14597. + */
  14598. +void ssh_ptl_shutdown(struct ssh_ptl *ptl)
  14599. +{
  14600. + LIST_HEAD(complete_q);
  14601. + LIST_HEAD(complete_p);
  14602. + struct ssh_packet *p, *n;
  14603. + int status;
  14604. +
  14605. + /* Ensure that no new packets (including ACK/NAK) can be submitted. */
  14606. + set_bit(SSH_PTL_SF_SHUTDOWN_BIT, &ptl->state);
  14607. + /*
  14608. + * Ensure that the layer gets marked as shut-down before actually
  14609. + * stopping it. In combination with the check in ssh_ptl_queue_push(),
  14610. + * this guarantees that no new packets can be added and all already
  14611. + * queued packets are properly canceled. In combination with the check
  14612. + * in ssh_ptl_rx_rcvbuf(), this guarantees that received data is
  14613. + * properly cut off.
  14614. + */
  14615. + smp_mb__after_atomic();
  14616. +
  14617. + status = ssh_ptl_rx_stop(ptl);
  14618. + if (status)
  14619. + ptl_err(ptl, "ptl: failed to stop receiver thread\n");
  14620. +
  14621. + status = ssh_ptl_tx_stop(ptl);
  14622. + if (status)
  14623. + ptl_err(ptl, "ptl: failed to stop transmitter thread\n");
  14624. +
  14625. + cancel_delayed_work_sync(&ptl->rtx_timeout.reaper);
  14626. +
  14627. + /*
  14628. + * At this point, all threads have been stopped. This means that the
  14629. + * only references to packets from inside the system are in the queue
  14630. + * and pending set.
  14631. + *
  14632. + * Note: We still need locks here because someone could still be
  14633. + * canceling packets.
  14634. + *
  14635. + * Note 2: We can re-use queue_node (or pending_node) if we mark the
  14636. + * packet as locked an then remove it from the queue (or pending set
  14637. + * respectively). Marking the packet as locked avoids re-queuing
  14638. + * (which should already be prevented by having stopped the treads...)
  14639. + * and not setting QUEUED_BIT (or PENDING_BIT) prevents removal from a
  14640. + * new list via other threads (e.g. cancellation).
  14641. + *
  14642. + * Note 3: There may be overlap between complete_p and complete_q.
  14643. + * This is handled via test_and_set_bit() on the "completed" flag
  14644. + * (also handles cancellation).
  14645. + */
  14646. +
  14647. + /* Mark queued packets as locked and move them to complete_q. */
  14648. + spin_lock(&ptl->queue.lock);
  14649. + list_for_each_entry_safe(p, n, &ptl->queue.head, queue_node) {
  14650. + set_bit(SSH_PACKET_SF_LOCKED_BIT, &p->state);
  14651. + /* Ensure that state does not get zero. */
  14652. + smp_mb__before_atomic();
  14653. + clear_bit(SSH_PACKET_SF_QUEUED_BIT, &p->state);
  14654. +
  14655. + list_del(&p->queue_node);
  14656. + list_add_tail(&p->queue_node, &complete_q);
  14657. + }
  14658. + spin_unlock(&ptl->queue.lock);
  14659. +
  14660. + /* Mark pending packets as locked and move them to complete_p. */
  14661. + spin_lock(&ptl->pending.lock);
  14662. + list_for_each_entry_safe(p, n, &ptl->pending.head, pending_node) {
  14663. + set_bit(SSH_PACKET_SF_LOCKED_BIT, &p->state);
  14664. + /* Ensure that state does not get zero. */
  14665. + smp_mb__before_atomic();
  14666. + clear_bit(SSH_PACKET_SF_PENDING_BIT, &p->state);
  14667. +
  14668. + list_del(&p->pending_node);
  14669. + list_add_tail(&p->pending_node, &complete_q);
  14670. + }
  14671. + atomic_set(&ptl->pending.count, 0);
  14672. + spin_unlock(&ptl->pending.lock);
  14673. +
  14674. + /* Complete and drop packets on complete_q. */
  14675. + list_for_each_entry(p, &complete_q, queue_node) {
  14676. + if (!test_and_set_bit(SSH_PACKET_SF_COMPLETED_BIT, &p->state))
  14677. + __ssh_ptl_complete(p, -ESHUTDOWN);
  14678. +
  14679. + ssh_packet_put(p);
  14680. + }
  14681. +
  14682. + /* Complete and drop packets on complete_p. */
  14683. + list_for_each_entry(p, &complete_p, pending_node) {
  14684. + if (!test_and_set_bit(SSH_PACKET_SF_COMPLETED_BIT, &p->state))
  14685. + __ssh_ptl_complete(p, -ESHUTDOWN);
  14686. +
  14687. + ssh_packet_put(p);
  14688. + }
  14689. +
  14690. + /*
  14691. + * At this point we have guaranteed that the system doesn't reference
  14692. + * any packets any more.
  14693. + */
  14694. +}
  14695. +
  14696. +/**
  14697. + * ssh_ptl_init() - Initialize packet transport layer.
  14698. + * @ptl: The packet transport layer to initialize.
  14699. + * @serdev: The underlying serial device, i.e. the lower-level transport.
  14700. + * @ops: Packet layer operations.
  14701. + *
  14702. + * Initializes the given packet transport layer. Transmitter and receiver
  14703. + * threads must be started separately via ssh_ptl_tx_start() and
  14704. + * ssh_ptl_rx_start(), after the packet-layer has been initialized and the
  14705. + * lower-level transport layer has been set up.
  14706. + *
  14707. + * Return: Returns zero on success and a nonzero error code on failure.
  14708. + */
  14709. +int ssh_ptl_init(struct ssh_ptl *ptl, struct serdev_device *serdev,
  14710. + struct ssh_ptl_ops *ops)
  14711. +{
  14712. + int i, status;
  14713. +
  14714. + ptl->serdev = serdev;
  14715. + ptl->state = 0;
  14716. +
  14717. + spin_lock_init(&ptl->queue.lock);
  14718. + INIT_LIST_HEAD(&ptl->queue.head);
  14719. +
  14720. + spin_lock_init(&ptl->pending.lock);
  14721. + INIT_LIST_HEAD(&ptl->pending.head);
  14722. + atomic_set_release(&ptl->pending.count, 0);
  14723. +
  14724. + ptl->tx.thread = NULL;
  14725. + atomic_set(&ptl->tx.running, 0);
  14726. + init_completion(&ptl->tx.thread_cplt_pkt);
  14727. + init_completion(&ptl->tx.thread_cplt_tx);
  14728. + init_waitqueue_head(&ptl->tx.packet_wq);
  14729. +
  14730. + ptl->rx.thread = NULL;
  14731. + init_waitqueue_head(&ptl->rx.wq);
  14732. +
  14733. + spin_lock_init(&ptl->rtx_timeout.lock);
  14734. + ptl->rtx_timeout.timeout = SSH_PTL_PACKET_TIMEOUT;
  14735. + ptl->rtx_timeout.expires = KTIME_MAX;
  14736. + INIT_DELAYED_WORK(&ptl->rtx_timeout.reaper, ssh_ptl_timeout_reap);
  14737. +
  14738. + ptl->ops = *ops;
  14739. +
  14740. + /* Initialize list of recent/blocked SEQs with invalid sequence IDs. */
  14741. + for (i = 0; i < ARRAY_SIZE(ptl->rx.blocked.seqs); i++)
  14742. + ptl->rx.blocked.seqs[i] = U16_MAX;
  14743. + ptl->rx.blocked.offset = 0;
  14744. +
  14745. + status = kfifo_alloc(&ptl->rx.fifo, SSH_PTL_RX_FIFO_LEN, GFP_KERNEL);
  14746. + if (status)
  14747. + return status;
  14748. +
  14749. + status = sshp_buf_alloc(&ptl->rx.buf, SSH_PTL_RX_BUF_LEN, GFP_KERNEL);
  14750. + if (status)
  14751. + kfifo_free(&ptl->rx.fifo);
  14752. +
  14753. + return status;
  14754. +}
  14755. +
  14756. +/**
  14757. + * ssh_ptl_destroy() - Deinitialize packet transport layer.
  14758. + * @ptl: The packet transport layer to deinitialize.
  14759. + *
  14760. + * Deinitializes the given packet transport layer and frees resources
  14761. + * associated with it. If receiver and/or transmitter threads have been
  14762. + * started, the layer must first be shut down via ssh_ptl_shutdown() before
  14763. + * this function can be called.
  14764. + */
  14765. +void ssh_ptl_destroy(struct ssh_ptl *ptl)
  14766. +{
  14767. + kfifo_free(&ptl->rx.fifo);
  14768. + sshp_buf_free(&ptl->rx.buf);
  14769. +}
  14770. diff --git a/drivers/misc/surface_aggregator/ssh_packet_layer.h b/drivers/misc/surface_aggregator/ssh_packet_layer.h
  14771. new file mode 100644
  14772. index 000000000000..e8757d03f279
  14773. --- /dev/null
  14774. +++ b/drivers/misc/surface_aggregator/ssh_packet_layer.h
  14775. @@ -0,0 +1,190 @@
  14776. +/* SPDX-License-Identifier: GPL-2.0+ */
  14777. +/*
  14778. + * SSH packet transport layer.
  14779. + *
  14780. + * Copyright (C) 2019-2020 Maximilian Luz <luzmaximilian@gmail.com>
  14781. + */
  14782. +
  14783. +#ifndef _SURFACE_AGGREGATOR_SSH_PACKET_LAYER_H
  14784. +#define _SURFACE_AGGREGATOR_SSH_PACKET_LAYER_H
  14785. +
  14786. +#include <linux/atomic.h>
  14787. +#include <linux/kfifo.h>
  14788. +#include <linux/ktime.h>
  14789. +#include <linux/list.h>
  14790. +#include <linux/serdev.h>
  14791. +#include <linux/spinlock.h>
  14792. +#include <linux/types.h>
  14793. +#include <linux/wait.h>
  14794. +#include <linux/workqueue.h>
  14795. +
  14796. +#include <linux/surface_aggregator/serial_hub.h>
  14797. +#include "ssh_parser.h"
  14798. +
  14799. +/**
  14800. + * enum ssh_ptl_state_flags - State-flags for &struct ssh_ptl.
  14801. + *
  14802. + * @SSH_PTL_SF_SHUTDOWN_BIT:
  14803. + * Indicates that the packet transport layer has been shut down or is
  14804. + * being shut down and should not accept any new packets/data.
  14805. + */
  14806. +enum ssh_ptl_state_flags {
  14807. + SSH_PTL_SF_SHUTDOWN_BIT,
  14808. +};
  14809. +
  14810. +/**
  14811. + * struct ssh_ptl_ops - Callback operations for packet transport layer.
  14812. + * @data_received: Function called when a data-packet has been received. Both,
  14813. + * the packet layer on which the packet has been received and
  14814. + * the packet's payload data are provided to this function.
  14815. + */
  14816. +struct ssh_ptl_ops {
  14817. + void (*data_received)(struct ssh_ptl *p, const struct ssam_span *data);
  14818. +};
  14819. +
  14820. +/**
  14821. + * struct ssh_ptl - SSH packet transport layer.
  14822. + * @serdev: Serial device providing the underlying data transport.
  14823. + * @state: State(-flags) of the transport layer.
  14824. + * @queue: Packet submission queue.
  14825. + * @queue.lock: Lock for modifying the packet submission queue.
  14826. + * @queue.head: List-head of the packet submission queue.
  14827. + * @pending: Set/list of pending packets.
  14828. + * @pending.lock: Lock for modifying the pending set.
  14829. + * @pending.head: List-head of the pending set/list.
  14830. + * @pending.count: Number of currently pending packets.
  14831. + * @tx: Transmitter subsystem.
  14832. + * @tx.running: Flag indicating (desired) transmitter thread state.
  14833. + * @tx.thread: Transmitter thread.
  14834. + * @tx.thread_cplt_tx: Completion for transmitter thread waiting on transfer.
  14835. + * @tx.thread_cplt_pkt: Completion for transmitter thread waiting on packets.
  14836. + * @tx.packet_wq: Waitqueue-head for packet transmit completion.
  14837. + * @rx: Receiver subsystem.
  14838. + * @rx.thread: Receiver thread.
  14839. + * @rx.wq: Waitqueue-head for receiver thread.
  14840. + * @rx.fifo: Buffer for receiving data/pushing data to receiver thread.
  14841. + * @rx.buf: Buffer for evaluating data on receiver thread.
  14842. + * @rx.blocked: List of recent/blocked sequence IDs to detect retransmission.
  14843. + * @rx.blocked.seqs: Array of blocked sequence IDs.
  14844. + * @rx.blocked.offset: Offset indicating where a new ID should be inserted.
  14845. + * @rtx_timeout: Retransmission timeout subsystem.
  14846. + * @rtx_timeout.lock: Lock for modifying the retransmission timeout reaper.
  14847. + * @rtx_timeout.timeout: Timeout interval for retransmission.
  14848. + * @rtx_timeout.expires: Time specifying when the reaper work is next scheduled.
  14849. + * @rtx_timeout.reaper: Work performing timeout checks and subsequent actions.
  14850. + * @ops: Packet layer operations.
  14851. + */
  14852. +struct ssh_ptl {
  14853. + struct serdev_device *serdev;
  14854. + unsigned long state;
  14855. +
  14856. + struct {
  14857. + spinlock_t lock;
  14858. + struct list_head head;
  14859. + } queue;
  14860. +
  14861. + struct {
  14862. + spinlock_t lock;
  14863. + struct list_head head;
  14864. + atomic_t count;
  14865. + } pending;
  14866. +
  14867. + struct {
  14868. + atomic_t running;
  14869. + struct task_struct *thread;
  14870. + struct completion thread_cplt_tx;
  14871. + struct completion thread_cplt_pkt;
  14872. + struct wait_queue_head packet_wq;
  14873. + } tx;
  14874. +
  14875. + struct {
  14876. + struct task_struct *thread;
  14877. + struct wait_queue_head wq;
  14878. + struct kfifo fifo;
  14879. + struct sshp_buf buf;
  14880. +
  14881. + struct {
  14882. + u16 seqs[8];
  14883. + u16 offset;
  14884. + } blocked;
  14885. + } rx;
  14886. +
  14887. + struct {
  14888. + spinlock_t lock;
  14889. + ktime_t timeout;
  14890. + ktime_t expires;
  14891. + struct delayed_work reaper;
  14892. + } rtx_timeout;
  14893. +
  14894. + struct ssh_ptl_ops ops;
  14895. +};
  14896. +
  14897. +#define __ssam_prcond(func, p, fmt, ...) \
  14898. + do { \
  14899. + typeof(p) __p = (p); \
  14900. + \
  14901. + if (__p) \
  14902. + func(__p, fmt, ##__VA_ARGS__); \
  14903. + } while (0)
  14904. +
  14905. +#define ptl_dbg(p, fmt, ...) dev_dbg(&(p)->serdev->dev, fmt, ##__VA_ARGS__)
  14906. +#define ptl_info(p, fmt, ...) dev_info(&(p)->serdev->dev, fmt, ##__VA_ARGS__)
  14907. +#define ptl_warn(p, fmt, ...) dev_warn(&(p)->serdev->dev, fmt, ##__VA_ARGS__)
  14908. +#define ptl_err(p, fmt, ...) dev_err(&(p)->serdev->dev, fmt, ##__VA_ARGS__)
  14909. +#define ptl_dbg_cond(p, fmt, ...) __ssam_prcond(ptl_dbg, p, fmt, ##__VA_ARGS__)
  14910. +
  14911. +#define to_ssh_ptl(ptr, member) \
  14912. + container_of(ptr, struct ssh_ptl, member)
  14913. +
  14914. +int ssh_ptl_init(struct ssh_ptl *ptl, struct serdev_device *serdev,
  14915. + struct ssh_ptl_ops *ops);
  14916. +
  14917. +void ssh_ptl_destroy(struct ssh_ptl *ptl);
  14918. +
  14919. +/**
  14920. + * ssh_ptl_get_device() - Get device associated with packet transport layer.
  14921. + * @ptl: The packet transport layer.
  14922. + *
  14923. + * Return: Returns the device on which the given packet transport layer builds
  14924. + * upon.
  14925. + */
  14926. +static inline struct device *ssh_ptl_get_device(struct ssh_ptl *ptl)
  14927. +{
  14928. + return ptl->serdev ? &ptl->serdev->dev : NULL;
  14929. +}
  14930. +
  14931. +int ssh_ptl_tx_start(struct ssh_ptl *ptl);
  14932. +int ssh_ptl_tx_stop(struct ssh_ptl *ptl);
  14933. +int ssh_ptl_rx_start(struct ssh_ptl *ptl);
  14934. +int ssh_ptl_rx_stop(struct ssh_ptl *ptl);
  14935. +void ssh_ptl_shutdown(struct ssh_ptl *ptl);
  14936. +
  14937. +int ssh_ptl_submit(struct ssh_ptl *ptl, struct ssh_packet *p);
  14938. +void ssh_ptl_cancel(struct ssh_packet *p);
  14939. +
  14940. +int ssh_ptl_rx_rcvbuf(struct ssh_ptl *ptl, const u8 *buf, size_t n);
  14941. +
  14942. +/**
  14943. + * ssh_ptl_tx_wakeup_transfer() - Wake up packet transmitter thread for
  14944. + * transfer.
  14945. + * @ptl: The packet transport layer.
  14946. + *
  14947. + * Wakes up the packet transmitter thread, notifying it that the underlying
  14948. + * transport has more space for data to be transmitted. If the packet
  14949. + * transport layer has been shut down, calls to this function will be ignored.
  14950. + */
  14951. +static inline void ssh_ptl_tx_wakeup_transfer(struct ssh_ptl *ptl)
  14952. +{
  14953. + if (test_bit(SSH_PTL_SF_SHUTDOWN_BIT, &ptl->state))
  14954. + return;
  14955. +
  14956. + complete(&ptl->tx.thread_cplt_tx);
  14957. +}
  14958. +
  14959. +void ssh_packet_init(struct ssh_packet *packet, unsigned long type,
  14960. + u8 priority, const struct ssh_packet_ops *ops);
  14961. +
  14962. +int ssh_ctrl_packet_cache_init(void);
  14963. +void ssh_ctrl_packet_cache_destroy(void);
  14964. +
  14965. +#endif /* _SURFACE_AGGREGATOR_SSH_PACKET_LAYER_H */
  14966. diff --git a/drivers/misc/surface_aggregator/ssh_parser.c b/drivers/misc/surface_aggregator/ssh_parser.c
  14967. new file mode 100644
  14968. index 000000000000..e2dead8de94a
  14969. --- /dev/null
  14970. +++ b/drivers/misc/surface_aggregator/ssh_parser.c
  14971. @@ -0,0 +1,228 @@
  14972. +// SPDX-License-Identifier: GPL-2.0+
  14973. +/*
  14974. + * SSH message parser.
  14975. + *
  14976. + * Copyright (C) 2019-2020 Maximilian Luz <luzmaximilian@gmail.com>
  14977. + */
  14978. +
  14979. +#include <asm/unaligned.h>
  14980. +#include <linux/compiler.h>
  14981. +#include <linux/device.h>
  14982. +#include <linux/types.h>
  14983. +
  14984. +#include <linux/surface_aggregator/serial_hub.h>
  14985. +#include "ssh_parser.h"
  14986. +
  14987. +/**
  14988. + * sshp_validate_crc() - Validate a CRC in raw message data.
  14989. + * @src: The span of data over which the CRC should be computed.
  14990. + * @crc: The pointer to the expected u16 CRC value.
  14991. + *
  14992. + * Computes the CRC of the provided data span (@src), compares it to the CRC
  14993. + * stored at the given address (@crc), and returns the result of this
  14994. + * comparison, i.e. %true if equal. This function is intended to run on raw
  14995. + * input/message data.
  14996. + *
  14997. + * Return: Returns %true if the computed CRC matches the stored CRC, %false
  14998. + * otherwise.
  14999. + */
  15000. +static bool sshp_validate_crc(const struct ssam_span *src, const u8 *crc)
  15001. +{
  15002. + u16 actual = ssh_crc(src->ptr, src->len);
  15003. + u16 expected = get_unaligned_le16(crc);
  15004. +
  15005. + return actual == expected;
  15006. +}
  15007. +
  15008. +/**
  15009. + * sshp_starts_with_syn() - Check if the given data starts with SSH SYN bytes.
  15010. + * @src: The data span to check the start of.
  15011. + */
  15012. +static bool sshp_starts_with_syn(const struct ssam_span *src)
  15013. +{
  15014. + return src->len >= 2 && get_unaligned_le16(src->ptr) == SSH_MSG_SYN;
  15015. +}
  15016. +
  15017. +/**
  15018. + * sshp_find_syn() - Find SSH SYN bytes in the given data span.
  15019. + * @src: The data span to search in.
  15020. + * @rem: The span (output) indicating the remaining data, starting with SSH
  15021. + * SYN bytes, if found.
  15022. + *
  15023. + * Search for SSH SYN bytes in the given source span. If found, set the @rem
  15024. + * span to the remaining data, starting with the first SYN bytes and capped by
  15025. + * the source span length, and return %true. This function does not copy any
  15026. + * data, but rather only sets pointers to the respective start addresses and
  15027. + * length values.
  15028. + *
  15029. + * If no SSH SYN bytes could be found, set the @rem span to the zero-length
  15030. + * span at the end of the source span and return %false.
  15031. + *
  15032. + * If partial SSH SYN bytes could be found at the end of the source span, set
  15033. + * the @rem span to cover these partial SYN bytes, capped by the end of the
  15034. + * source span, and return %false. This function should then be re-run once
  15035. + * more data is available.
  15036. + *
  15037. + * Return: Returns %true if a complete SSH SYN sequence could be found,
  15038. + * %false otherwise.
  15039. + */
  15040. +bool sshp_find_syn(const struct ssam_span *src, struct ssam_span *rem)
  15041. +{
  15042. + size_t i;
  15043. +
  15044. + for (i = 0; i < src->len - 1; i++) {
  15045. + if (likely(get_unaligned_le16(src->ptr + i) == SSH_MSG_SYN)) {
  15046. + rem->ptr = src->ptr + i;
  15047. + rem->len = src->len - i;
  15048. + return true;
  15049. + }
  15050. + }
  15051. +
  15052. + if (unlikely(src->ptr[src->len - 1] == (SSH_MSG_SYN & 0xff))) {
  15053. + rem->ptr = src->ptr + src->len - 1;
  15054. + rem->len = 1;
  15055. + return false;
  15056. + }
  15057. +
  15058. + rem->ptr = src->ptr + src->len;
  15059. + rem->len = 0;
  15060. + return false;
  15061. +}
  15062. +
  15063. +/**
  15064. + * sshp_parse_frame() - Parse SSH frame.
  15065. + * @dev: The device used for logging.
  15066. + * @source: The source to parse from.
  15067. + * @frame: The parsed frame (output).
  15068. + * @payload: The parsed payload (output).
  15069. + * @maxlen: The maximum supported message length.
  15070. + *
  15071. + * Parses and validates a SSH frame, including its payload, from the given
  15072. + * source. Sets the provided @frame pointer to the start of the frame and
  15073. + * writes the limits of the frame payload to the provided @payload span
  15074. + * pointer.
  15075. + *
  15076. + * This function does not copy any data, but rather only validates the message
  15077. + * data and sets pointers (and length values) to indicate the respective parts.
  15078. + *
  15079. + * If no complete SSH frame could be found, the frame pointer will be set to
  15080. + * the %NULL pointer and the payload span will be set to the null span (start
  15081. + * pointer %NULL, size zero).
  15082. + *
  15083. + * Return: Returns zero on success or if the frame is incomplete, %-ENOMSG if
  15084. + * the start of the message is invalid, %-EBADMSG if any (frame-header or
  15085. + * payload) CRC is invalid, or %-EMSGSIZE if the SSH message is bigger than
  15086. + * the maximum message length specified in the @maxlen parameter.
  15087. + */
  15088. +int sshp_parse_frame(const struct device *dev, const struct ssam_span *source,
  15089. + struct ssh_frame **frame, struct ssam_span *payload,
  15090. + size_t maxlen)
  15091. +{
  15092. + struct ssam_span sf;
  15093. + struct ssam_span sp;
  15094. +
  15095. + /* Initialize output. */
  15096. + *frame = NULL;
  15097. + payload->ptr = NULL;
  15098. + payload->len = 0;
  15099. +
  15100. + if (!sshp_starts_with_syn(source)) {
  15101. + dev_warn(dev, "rx: parser: invalid start of frame\n");
  15102. + return -ENOMSG;
  15103. + }
  15104. +
  15105. + /* Check for minimum packet length. */
  15106. + if (unlikely(source->len < SSH_MESSAGE_LENGTH(0))) {
  15107. + dev_dbg(dev, "rx: parser: not enough data for frame\n");
  15108. + return 0;
  15109. + }
  15110. +
  15111. + /* Pin down frame. */
  15112. + sf.ptr = source->ptr + sizeof(u16);
  15113. + sf.len = sizeof(struct ssh_frame);
  15114. +
  15115. + /* Validate frame CRC. */
  15116. + if (unlikely(!sshp_validate_crc(&sf, sf.ptr + sf.len))) {
  15117. + dev_warn(dev, "rx: parser: invalid frame CRC\n");
  15118. + return -EBADMSG;
  15119. + }
  15120. +
  15121. + /* Ensure packet does not exceed maximum length. */
  15122. + sp.len = get_unaligned_le16(&((struct ssh_frame *)sf.ptr)->len);
  15123. + if (unlikely(SSH_MESSAGE_LENGTH(sp.len) > maxlen)) {
  15124. + dev_warn(dev, "rx: parser: frame too large: %llu bytes\n",
  15125. + SSH_MESSAGE_LENGTH(sp.len));
  15126. + return -EMSGSIZE;
  15127. + }
  15128. +
  15129. + /* Pin down payload. */
  15130. + sp.ptr = sf.ptr + sf.len + sizeof(u16);
  15131. +
  15132. + /* Check for frame + payload length. */
  15133. + if (source->len < SSH_MESSAGE_LENGTH(sp.len)) {
  15134. + dev_dbg(dev, "rx: parser: not enough data for payload\n");
  15135. + return 0;
  15136. + }
  15137. +
  15138. + /* Validate payload CRC. */
  15139. + if (unlikely(!sshp_validate_crc(&sp, sp.ptr + sp.len))) {
  15140. + dev_warn(dev, "rx: parser: invalid payload CRC\n");
  15141. + return -EBADMSG;
  15142. + }
  15143. +
  15144. + *frame = (struct ssh_frame *)sf.ptr;
  15145. + *payload = sp;
  15146. +
  15147. + dev_dbg(dev, "rx: parser: valid frame found (type: %#04x, len: %u)\n",
  15148. + (*frame)->type, (*frame)->len);
  15149. +
  15150. + return 0;
  15151. +}
  15152. +
  15153. +/**
  15154. + * sshp_parse_command() - Parse SSH command frame payload.
  15155. + * @dev: The device used for logging.
  15156. + * @source: The source to parse from.
  15157. + * @command: The parsed command (output).
  15158. + * @command_data: The parsed command data/payload (output).
  15159. + *
  15160. + * Parses and validates a SSH command frame payload. Sets the @command pointer
  15161. + * to the command header and the @command_data span to the command data (i.e.
  15162. + * payload of the command). This will result in a zero-length span if the
  15163. + * command does not have any associated data/payload. This function does not
  15164. + * check the frame-payload-type field, which should be checked by the caller
  15165. + * before calling this function.
  15166. + *
  15167. + * The @source parameter should be the complete frame payload, e.g. returned
  15168. + * by the sshp_parse_frame() command.
  15169. + *
  15170. + * This function does not copy any data, but rather only validates the frame
  15171. + * payload data and sets pointers (and length values) to indicate the
  15172. + * respective parts.
  15173. + *
  15174. + * Return: Returns zero on success or %-ENOMSG if @source does not represent a
  15175. + * valid command-type frame payload, i.e. is too short.
  15176. + */
  15177. +int sshp_parse_command(const struct device *dev, const struct ssam_span *source,
  15178. + struct ssh_command **command,
  15179. + struct ssam_span *command_data)
  15180. +{
  15181. + /* Check for minimum length. */
  15182. + if (unlikely(source->len < sizeof(struct ssh_command))) {
  15183. + *command = NULL;
  15184. + command_data->ptr = NULL;
  15185. + command_data->len = 0;
  15186. +
  15187. + dev_err(dev, "rx: parser: command payload is too short\n");
  15188. + return -ENOMSG;
  15189. + }
  15190. +
  15191. + *command = (struct ssh_command *)source->ptr;
  15192. + command_data->ptr = source->ptr + sizeof(struct ssh_command);
  15193. + command_data->len = source->len - sizeof(struct ssh_command);
  15194. +
  15195. + dev_dbg(dev, "rx: parser: valid command found (tc: %#04x, cid: %#04x)\n",
  15196. + (*command)->tc, (*command)->cid);
  15197. +
  15198. + return 0;
  15199. +}
  15200. diff --git a/drivers/misc/surface_aggregator/ssh_parser.h b/drivers/misc/surface_aggregator/ssh_parser.h
  15201. new file mode 100644
  15202. index 000000000000..395c61ef890b
  15203. --- /dev/null
  15204. +++ b/drivers/misc/surface_aggregator/ssh_parser.h
  15205. @@ -0,0 +1,155 @@
  15206. +/* SPDX-License-Identifier: GPL-2.0+ */
  15207. +/*
  15208. + * SSH message parser.
  15209. + *
  15210. + * Copyright (C) 2019-2020 Maximilian Luz <luzmaximilian@gmail.com>
  15211. + */
  15212. +
  15213. +#ifndef _SURFACE_AGGREGATOR_SSH_PARSER_H
  15214. +#define _SURFACE_AGGREGATOR_SSH_PARSER_H
  15215. +
  15216. +#include <linux/device.h>
  15217. +#include <linux/kfifo.h>
  15218. +#include <linux/slab.h>
  15219. +#include <linux/types.h>
  15220. +
  15221. +#include <linux/surface_aggregator/serial_hub.h>
  15222. +
  15223. +
  15224. +/**
  15225. + * struct sshp_buf - Parser buffer for SSH messages.
  15226. + * @ptr: Pointer to the beginning of the buffer.
  15227. + * @len: Number of bytes used in the buffer.
  15228. + * @cap: Maximum capacity of the buffer.
  15229. + */
  15230. +struct sshp_buf {
  15231. + u8 *ptr;
  15232. + size_t len;
  15233. + size_t cap;
  15234. +};
  15235. +
  15236. +/**
  15237. + * sshp_buf_init() - Initialize a SSH parser buffer.
  15238. + * @buf: The buffer to initialize.
  15239. + * @ptr: The memory backing the buffer.
  15240. + * @cap: The length of the memory backing the buffer, i.e. its capacity.
  15241. + *
  15242. + * Initializes the buffer with the given memory as backing and set its used
  15243. + * length to zero.
  15244. + */
  15245. +static inline void sshp_buf_init(struct sshp_buf *buf, u8 *ptr, size_t cap)
  15246. +{
  15247. + buf->ptr = ptr;
  15248. + buf->len = 0;
  15249. + buf->cap = cap;
  15250. +}
  15251. +
  15252. +/**
  15253. + * sshp_buf_alloc() - Allocate and initialize a SSH parser buffer.
  15254. + * @buf: The buffer to initialize/allocate to.
  15255. + * @cap: The desired capacity of the buffer.
  15256. + * @flags: The flags used for allocating the memory.
  15257. + *
  15258. + * Allocates @cap bytes and initializes the provided buffer struct with the
  15259. + * allocated memory.
  15260. + *
  15261. + * Return: Returns zero on success and %-ENOMEM if allocation failed.
  15262. + */
  15263. +static inline int sshp_buf_alloc(struct sshp_buf *buf, size_t cap, gfp_t flags)
  15264. +{
  15265. + u8 *ptr;
  15266. +
  15267. + ptr = kzalloc(cap, flags);
  15268. + if (!ptr)
  15269. + return -ENOMEM;
  15270. +
  15271. + sshp_buf_init(buf, ptr, cap);
  15272. + return 0;
  15273. +}
  15274. +
  15275. +/**
  15276. + * sshp_buf_free() - Free a SSH parser buffer.
  15277. + * @buf: The buffer to free.
  15278. + *
  15279. + * Frees a SSH parser buffer by freeing the memory backing it and then
  15280. + * resetting its pointer to %NULL and length and capacity to zero. Intended to
  15281. + * free a buffer previously allocated with sshp_buf_alloc().
  15282. + */
  15283. +static inline void sshp_buf_free(struct sshp_buf *buf)
  15284. +{
  15285. + kfree(buf->ptr);
  15286. + buf->ptr = NULL;
  15287. + buf->len = 0;
  15288. + buf->cap = 0;
  15289. +}
  15290. +
  15291. +/**
  15292. + * sshp_buf_drop() - Drop data from the beginning of the buffer.
  15293. + * @buf: The buffer to drop data from.
  15294. + * @n: The number of bytes to drop.
  15295. + *
  15296. + * Drops the first @n bytes from the buffer. Re-aligns any remaining data to
  15297. + * the beginning of the buffer.
  15298. + */
  15299. +static inline void sshp_buf_drop(struct sshp_buf *buf, size_t n)
  15300. +{
  15301. + memmove(buf->ptr, buf->ptr + n, buf->len - n);
  15302. + buf->len -= n;
  15303. +}
  15304. +
  15305. +/**
  15306. + * sshp_buf_read_from_fifo() - Transfer data from a fifo to the buffer.
  15307. + * @buf: The buffer to write the data into.
  15308. + * @fifo: The fifo to read the data from.
  15309. + *
  15310. + * Transfers the data contained in the fifo to the buffer, removing it from
  15311. + * the fifo. This function will try to transfer as much data as possible,
  15312. + * limited either by the remaining space in the buffer or by the number of
  15313. + * bytes available in the fifo.
  15314. + *
  15315. + * Return: Returns the number of bytes transferred.
  15316. + */
  15317. +static inline size_t sshp_buf_read_from_fifo(struct sshp_buf *buf,
  15318. + struct kfifo *fifo)
  15319. +{
  15320. + size_t n;
  15321. +
  15322. + n = kfifo_out(fifo, buf->ptr + buf->len, buf->cap - buf->len);
  15323. + buf->len += n;
  15324. +
  15325. + return n;
  15326. +}
  15327. +
  15328. +/**
  15329. + * sshp_buf_span_from() - Initialize a span from the given buffer and offset.
  15330. + * @buf: The buffer to create the span from.
  15331. + * @offset: The offset in the buffer at which the span should start.
  15332. + * @span: The span to initialize (output).
  15333. + *
  15334. + * Initializes the provided span to point to the memory at the given offset in
  15335. + * the buffer, with the length of the span being capped by the number of bytes
  15336. + * used in the buffer after the offset (i.e. bytes remaining after the
  15337. + * offset).
  15338. + *
  15339. + * Warning: This function does not validate that @offset is less than or equal
  15340. + * to the number of bytes used in the buffer or the buffer capacity. This must
  15341. + * be guaranteed by the caller.
  15342. + */
  15343. +static inline void sshp_buf_span_from(struct sshp_buf *buf, size_t offset,
  15344. + struct ssam_span *span)
  15345. +{
  15346. + span->ptr = buf->ptr + offset;
  15347. + span->len = buf->len - offset;
  15348. +}
  15349. +
  15350. +bool sshp_find_syn(const struct ssam_span *src, struct ssam_span *rem);
  15351. +
  15352. +int sshp_parse_frame(const struct device *dev, const struct ssam_span *source,
  15353. + struct ssh_frame **frame, struct ssam_span *payload,
  15354. + size_t maxlen);
  15355. +
  15356. +int sshp_parse_command(const struct device *dev, const struct ssam_span *source,
  15357. + struct ssh_command **command,
  15358. + struct ssam_span *command_data);
  15359. +
  15360. +#endif /* _SURFACE_AGGREGATOR_SSH_PARSER_h */
  15361. diff --git a/drivers/misc/surface_aggregator/ssh_request_layer.c b/drivers/misc/surface_aggregator/ssh_request_layer.c
  15362. new file mode 100644
  15363. index 000000000000..bb1c862411a2
  15364. --- /dev/null
  15365. +++ b/drivers/misc/surface_aggregator/ssh_request_layer.c
  15366. @@ -0,0 +1,1264 @@
  15367. +// SPDX-License-Identifier: GPL-2.0+
  15368. +/*
  15369. + * SSH request transport layer.
  15370. + *
  15371. + * Copyright (C) 2019-2020 Maximilian Luz <luzmaximilian@gmail.com>
  15372. + */
  15373. +
  15374. +#include <asm/unaligned.h>
  15375. +#include <linux/atomic.h>
  15376. +#include <linux/completion.h>
  15377. +#include <linux/error-injection.h>
  15378. +#include <linux/ktime.h>
  15379. +#include <linux/limits.h>
  15380. +#include <linux/list.h>
  15381. +#include <linux/slab.h>
  15382. +#include <linux/spinlock.h>
  15383. +#include <linux/types.h>
  15384. +#include <linux/workqueue.h>
  15385. +
  15386. +#include <linux/surface_aggregator/serial_hub.h>
  15387. +#include <linux/surface_aggregator/controller.h>
  15388. +
  15389. +#include "ssh_packet_layer.h"
  15390. +#include "ssh_request_layer.h"
  15391. +
  15392. +#include "trace.h"
  15393. +
  15394. +/*
  15395. + * SSH_RTL_REQUEST_TIMEOUT - Request timeout.
  15396. + *
  15397. + * Timeout as ktime_t delta for request responses. If we have not received a
  15398. + * response in this time-frame after finishing the underlying packet
  15399. + * transmission, the request will be completed with %-ETIMEDOUT as status
  15400. + * code.
  15401. + */
  15402. +#define SSH_RTL_REQUEST_TIMEOUT ms_to_ktime(3000)
  15403. +
  15404. +/*
  15405. + * SSH_RTL_REQUEST_TIMEOUT_RESOLUTION - Request timeout granularity.
  15406. + *
  15407. + * Time-resolution for timeouts. Should be larger than one jiffy to avoid
  15408. + * direct re-scheduling of reaper work_struct.
  15409. + */
  15410. +#define SSH_RTL_REQUEST_TIMEOUT_RESOLUTION ms_to_ktime(max(2000 / HZ, 50))
  15411. +
  15412. +/*
  15413. + * SSH_RTL_MAX_PENDING - Maximum number of pending requests.
  15414. + *
  15415. + * Maximum number of requests concurrently waiting to be completed (i.e.
  15416. + * waiting for the corresponding packet transmission to finish if they don't
  15417. + * have a response or waiting for a response if they have one).
  15418. + */
  15419. +#define SSH_RTL_MAX_PENDING 3
  15420. +
  15421. +/*
  15422. + * SSH_RTL_TX_BATCH - Maximum number of requests processed per work execution.
  15423. + * Used to prevent livelocking of the workqueue. Value chosen via educated
  15424. + * guess, may be adjusted.
  15425. + */
  15426. +#define SSH_RTL_TX_BATCH 10
  15427. +
  15428. +#ifdef CONFIG_SURFACE_AGGREGATOR_ERROR_INJECTION
  15429. +
  15430. +/**
  15431. + * ssh_rtl_should_drop_response() - Error injection hook to drop request
  15432. + * responses.
  15433. + *
  15434. + * Useful to cause request transmission timeouts in the driver by dropping the
  15435. + * response to a request.
  15436. + */
  15437. +static noinline bool ssh_rtl_should_drop_response(void)
  15438. +{
  15439. + return false;
  15440. +}
  15441. +ALLOW_ERROR_INJECTION(ssh_rtl_should_drop_response, TRUE);
  15442. +
  15443. +#else
  15444. +
  15445. +static inline bool ssh_rtl_should_drop_response(void)
  15446. +{
  15447. + return false;
  15448. +}
  15449. +
  15450. +#endif
  15451. +
  15452. +static u16 ssh_request_get_rqid(struct ssh_request *rqst)
  15453. +{
  15454. + return get_unaligned_le16(rqst->packet.data.ptr
  15455. + + SSH_MSGOFFSET_COMMAND(rqid));
  15456. +}
  15457. +
  15458. +static u32 ssh_request_get_rqid_safe(struct ssh_request *rqst)
  15459. +{
  15460. + if (!rqst->packet.data.ptr)
  15461. + return U32_MAX;
  15462. +
  15463. + return ssh_request_get_rqid(rqst);
  15464. +}
  15465. +
  15466. +static void ssh_rtl_queue_remove(struct ssh_request *rqst)
  15467. +{
  15468. + struct ssh_rtl *rtl = ssh_request_rtl(rqst);
  15469. +
  15470. + spin_lock(&rtl->queue.lock);
  15471. +
  15472. + if (!test_and_clear_bit(SSH_REQUEST_SF_QUEUED_BIT, &rqst->state)) {
  15473. + spin_unlock(&rtl->queue.lock);
  15474. + return;
  15475. + }
  15476. +
  15477. + list_del(&rqst->node);
  15478. +
  15479. + spin_unlock(&rtl->queue.lock);
  15480. + ssh_request_put(rqst);
  15481. +}
  15482. +
  15483. +static bool ssh_rtl_queue_empty(struct ssh_rtl *rtl)
  15484. +{
  15485. + bool empty;
  15486. +
  15487. + spin_lock(&rtl->queue.lock);
  15488. + empty = list_empty(&rtl->queue.head);
  15489. + spin_unlock(&rtl->queue.lock);
  15490. +
  15491. + return empty;
  15492. +}
  15493. +
  15494. +static void ssh_rtl_pending_remove(struct ssh_request *rqst)
  15495. +{
  15496. + struct ssh_rtl *rtl = ssh_request_rtl(rqst);
  15497. +
  15498. + spin_lock(&rtl->pending.lock);
  15499. +
  15500. + if (!test_and_clear_bit(SSH_REQUEST_SF_PENDING_BIT, &rqst->state)) {
  15501. + spin_unlock(&rtl->pending.lock);
  15502. + return;
  15503. + }
  15504. +
  15505. + atomic_dec(&rtl->pending.count);
  15506. + list_del(&rqst->node);
  15507. +
  15508. + spin_unlock(&rtl->pending.lock);
  15509. +
  15510. + ssh_request_put(rqst);
  15511. +}
  15512. +
  15513. +static int ssh_rtl_tx_pending_push(struct ssh_request *rqst)
  15514. +{
  15515. + struct ssh_rtl *rtl = ssh_request_rtl(rqst);
  15516. +
  15517. + spin_lock(&rtl->pending.lock);
  15518. +
  15519. + if (test_bit(SSH_REQUEST_SF_LOCKED_BIT, &rqst->state)) {
  15520. + spin_unlock(&rtl->pending.lock);
  15521. + return -EINVAL;
  15522. + }
  15523. +
  15524. + if (test_and_set_bit(SSH_REQUEST_SF_PENDING_BIT, &rqst->state)) {
  15525. + spin_unlock(&rtl->pending.lock);
  15526. + return -EALREADY;
  15527. + }
  15528. +
  15529. + atomic_inc(&rtl->pending.count);
  15530. + list_add_tail(&ssh_request_get(rqst)->node, &rtl->pending.head);
  15531. +
  15532. + spin_unlock(&rtl->pending.lock);
  15533. + return 0;
  15534. +}
  15535. +
  15536. +static void ssh_rtl_complete_with_status(struct ssh_request *rqst, int status)
  15537. +{
  15538. + struct ssh_rtl *rtl = ssh_request_rtl(rqst);
  15539. +
  15540. + trace_ssam_request_complete(rqst, status);
  15541. +
  15542. + /* rtl/ptl may not be set if we're canceling before submitting. */
  15543. + rtl_dbg_cond(rtl, "rtl: completing request (rqid: %#06x, status: %d)\n",
  15544. + ssh_request_get_rqid_safe(rqst), status);
  15545. +
  15546. + rqst->ops->complete(rqst, NULL, NULL, status);
  15547. +}
  15548. +
  15549. +static void ssh_rtl_complete_with_rsp(struct ssh_request *rqst,
  15550. + const struct ssh_command *cmd,
  15551. + const struct ssam_span *data)
  15552. +{
  15553. + struct ssh_rtl *rtl = ssh_request_rtl(rqst);
  15554. +
  15555. + trace_ssam_request_complete(rqst, 0);
  15556. +
  15557. + rtl_dbg(rtl, "rtl: completing request with response (rqid: %#06x)\n",
  15558. + ssh_request_get_rqid(rqst));
  15559. +
  15560. + rqst->ops->complete(rqst, cmd, data, 0);
  15561. +}
  15562. +
  15563. +static bool ssh_rtl_tx_can_process(struct ssh_request *rqst)
  15564. +{
  15565. + struct ssh_rtl *rtl = ssh_request_rtl(rqst);
  15566. +
  15567. + if (test_bit(SSH_REQUEST_TY_FLUSH_BIT, &rqst->state))
  15568. + return !atomic_read(&rtl->pending.count);
  15569. +
  15570. + return atomic_read(&rtl->pending.count) < SSH_RTL_MAX_PENDING;
  15571. +}
  15572. +
  15573. +static struct ssh_request *ssh_rtl_tx_next(struct ssh_rtl *rtl)
  15574. +{
  15575. + struct ssh_request *rqst = ERR_PTR(-ENOENT);
  15576. + struct ssh_request *p, *n;
  15577. +
  15578. + spin_lock(&rtl->queue.lock);
  15579. +
  15580. + /* Find first non-locked request and remove it. */
  15581. + list_for_each_entry_safe(p, n, &rtl->queue.head, node) {
  15582. + if (unlikely(test_bit(SSH_REQUEST_SF_LOCKED_BIT, &p->state)))
  15583. + continue;
  15584. +
  15585. + if (!ssh_rtl_tx_can_process(p)) {
  15586. + rqst = ERR_PTR(-EBUSY);
  15587. + break;
  15588. + }
  15589. +
  15590. + /* Remove from queue and mark as transmitting. */
  15591. + set_bit(SSH_REQUEST_SF_TRANSMITTING_BIT, &p->state);
  15592. + /* Ensure state never gets zero. */
  15593. + smp_mb__before_atomic();
  15594. + clear_bit(SSH_REQUEST_SF_QUEUED_BIT, &p->state);
  15595. +
  15596. + list_del(&p->node);
  15597. +
  15598. + rqst = p;
  15599. + break;
  15600. + }
  15601. +
  15602. + spin_unlock(&rtl->queue.lock);
  15603. + return rqst;
  15604. +}
  15605. +
  15606. +static int ssh_rtl_tx_try_process_one(struct ssh_rtl *rtl)
  15607. +{
  15608. + struct ssh_request *rqst;
  15609. + int status;
  15610. +
  15611. + /* Get and prepare next request for transmit. */
  15612. + rqst = ssh_rtl_tx_next(rtl);
  15613. + if (IS_ERR(rqst))
  15614. + return PTR_ERR(rqst);
  15615. +
  15616. + /* Add it to/mark it as pending. */
  15617. + status = ssh_rtl_tx_pending_push(rqst);
  15618. + if (status) {
  15619. + ssh_request_put(rqst);
  15620. + return -EAGAIN;
  15621. + }
  15622. +
  15623. + /* Submit packet. */
  15624. + status = ssh_ptl_submit(&rtl->ptl, &rqst->packet);
  15625. + if (status == -ESHUTDOWN) {
  15626. + /*
  15627. + * Packet has been refused due to the packet layer shutting
  15628. + * down. Complete it here.
  15629. + */
  15630. + set_bit(SSH_REQUEST_SF_LOCKED_BIT, &rqst->state);
  15631. + /*
  15632. + * Note: A barrier is not required here, as there are only two
  15633. + * references in the system at this point: The one that we have,
  15634. + * and the other one that belongs to the pending set. Due to the
  15635. + * request being marked as "transmitting", our process is the
  15636. + * only one allowed to remove the pending node and change the
  15637. + * state. Normally, the task would fall to the packet callback,
  15638. + * but as this is a path where submission failed, this callback
  15639. + * will never be executed.
  15640. + */
  15641. +
  15642. + ssh_rtl_pending_remove(rqst);
  15643. + ssh_rtl_complete_with_status(rqst, -ESHUTDOWN);
  15644. +
  15645. + ssh_request_put(rqst);
  15646. + return -ESHUTDOWN;
  15647. +
  15648. + } else if (status) {
  15649. + /*
  15650. + * If submitting the packet failed and the packet layer isn't
  15651. + * shutting down, the packet has either been submitted/queued
  15652. + * before (-EALREADY, which cannot happen as we have
  15653. + * guaranteed that requests cannot be re-submitted), or the
  15654. + * packet was marked as locked (-EINVAL). To mark the packet
  15655. + * locked at this stage, the request, and thus the packets
  15656. + * itself, had to have been canceled. Simply drop the
  15657. + * reference. Cancellation itself will remove it from the set
  15658. + * of pending requests.
  15659. + */
  15660. +
  15661. + WARN_ON(status != -EINVAL);
  15662. +
  15663. + ssh_request_put(rqst);
  15664. + return -EAGAIN;
  15665. + }
  15666. +
  15667. + ssh_request_put(rqst);
  15668. + return 0;
  15669. +}
  15670. +
  15671. +static bool ssh_rtl_tx_schedule(struct ssh_rtl *rtl)
  15672. +{
  15673. + if (atomic_read(&rtl->pending.count) >= SSH_RTL_MAX_PENDING)
  15674. + return false;
  15675. +
  15676. + if (ssh_rtl_queue_empty(rtl))
  15677. + return false;
  15678. +
  15679. + return schedule_work(&rtl->tx.work);
  15680. +}
  15681. +
  15682. +static void ssh_rtl_tx_work_fn(struct work_struct *work)
  15683. +{
  15684. + struct ssh_rtl *rtl = to_ssh_rtl(work, tx.work);
  15685. + unsigned int iterations = SSH_RTL_TX_BATCH;
  15686. + int status;
  15687. +
  15688. + /*
  15689. + * Try to be nice and not block/live-lock the workqueue: Run a maximum
  15690. + * of 10 tries, then re-submit if necessary. This should not be
  15691. + * necessary for normal execution, but guarantee it anyway.
  15692. + */
  15693. + do {
  15694. + status = ssh_rtl_tx_try_process_one(rtl);
  15695. + if (status == -ENOENT || status == -EBUSY)
  15696. + return; /* No more requests to process. */
  15697. +
  15698. + if (status == -ESHUTDOWN) {
  15699. + /*
  15700. + * Packet system shutting down. No new packets can be
  15701. + * transmitted. Return silently, the party initiating
  15702. + * the shutdown should handle the rest.
  15703. + */
  15704. + return;
  15705. + }
  15706. +
  15707. + WARN_ON(status != 0 && status != -EAGAIN);
  15708. + } while (--iterations);
  15709. +
  15710. + /* Out of tries, reschedule. */
  15711. + ssh_rtl_tx_schedule(rtl);
  15712. +}
  15713. +
  15714. +/**
  15715. + * ssh_rtl_submit() - Submit a request to the transport layer.
  15716. + * @rtl: The request transport layer.
  15717. + * @rqst: The request to submit.
  15718. + *
  15719. + * Submits a request to the transport layer. A single request may not be
  15720. + * submitted multiple times without reinitializing it.
  15721. + *
  15722. + * Return: Returns zero on success, %-EINVAL if the request type is invalid or
  15723. + * the request has been canceled prior to submission, %-EALREADY if the
  15724. + * request has already been submitted, or %-ESHUTDOWN in case the request
  15725. + * transport layer has been shut down.
  15726. + */
  15727. +int ssh_rtl_submit(struct ssh_rtl *rtl, struct ssh_request *rqst)
  15728. +{
  15729. + trace_ssam_request_submit(rqst);
  15730. +
  15731. + /*
  15732. + * Ensure that requests expecting a response are sequenced. If this
  15733. + * invariant ever changes, see the comment in ssh_rtl_complete() on what
  15734. + * is required to be changed in the code.
  15735. + */
  15736. + if (test_bit(SSH_REQUEST_TY_HAS_RESPONSE_BIT, &rqst->state))
  15737. + if (!test_bit(SSH_PACKET_TY_SEQUENCED_BIT, &rqst->packet.state))
  15738. + return -EINVAL;
  15739. +
  15740. + spin_lock(&rtl->queue.lock);
  15741. +
  15742. + /*
  15743. + * Try to set ptl and check if this request has already been submitted.
  15744. + *
  15745. + * Must be inside lock as we might run into a lost update problem
  15746. + * otherwise: If this were outside of the lock, cancellation in
  15747. + * ssh_rtl_cancel_nonpending() may run after we've set the ptl
  15748. + * reference but before we enter the lock. In that case, we'd detect
  15749. + * that the request is being added to the queue and would try to remove
  15750. + * it from that, but removal might fail because it hasn't actually been
  15751. + * added yet. By putting this cmpxchg in the critical section, we
  15752. + * ensure that the queuing detection only triggers when we are already
  15753. + * in the critical section and the remove process will wait until the
  15754. + * push operation has been completed (via lock) due to that. Only then,
  15755. + * we can safely try to remove it.
  15756. + */
  15757. + if (cmpxchg(&rqst->packet.ptl, NULL, &rtl->ptl)) {
  15758. + spin_unlock(&rtl->queue.lock);
  15759. + return -EALREADY;
  15760. + }
  15761. +
  15762. + /*
  15763. + * Ensure that we set ptl reference before we continue modifying state.
  15764. + * This is required for non-pending cancellation. This barrier is paired
  15765. + * with the one in ssh_rtl_cancel_nonpending().
  15766. + *
  15767. + * By setting the ptl reference before we test for "locked", we can
  15768. + * check if the "locked" test may have already run. See comments in
  15769. + * ssh_rtl_cancel_nonpending() for more detail.
  15770. + */
  15771. + smp_mb__after_atomic();
  15772. +
  15773. + if (test_bit(SSH_RTL_SF_SHUTDOWN_BIT, &rtl->state)) {
  15774. + spin_unlock(&rtl->queue.lock);
  15775. + return -ESHUTDOWN;
  15776. + }
  15777. +
  15778. + if (test_bit(SSH_REQUEST_SF_LOCKED_BIT, &rqst->state)) {
  15779. + spin_unlock(&rtl->queue.lock);
  15780. + return -EINVAL;
  15781. + }
  15782. +
  15783. + set_bit(SSH_REQUEST_SF_QUEUED_BIT, &rqst->state);
  15784. + list_add_tail(&ssh_request_get(rqst)->node, &rtl->queue.head);
  15785. +
  15786. + spin_unlock(&rtl->queue.lock);
  15787. +
  15788. + ssh_rtl_tx_schedule(rtl);
  15789. + return 0;
  15790. +}
  15791. +
  15792. +static void ssh_rtl_timeout_reaper_mod(struct ssh_rtl *rtl, ktime_t now,
  15793. + ktime_t expires)
  15794. +{
  15795. + unsigned long delta = msecs_to_jiffies(ktime_ms_delta(expires, now));
  15796. + ktime_t aexp = ktime_add(expires, SSH_RTL_REQUEST_TIMEOUT_RESOLUTION);
  15797. +
  15798. + spin_lock(&rtl->rtx_timeout.lock);
  15799. +
  15800. + /* Re-adjust / schedule reaper only if it is above resolution delta. */
  15801. + if (ktime_before(aexp, rtl->rtx_timeout.expires)) {
  15802. + rtl->rtx_timeout.expires = expires;
  15803. + mod_delayed_work(system_wq, &rtl->rtx_timeout.reaper, delta);
  15804. + }
  15805. +
  15806. + spin_unlock(&rtl->rtx_timeout.lock);
  15807. +}
  15808. +
  15809. +static void ssh_rtl_timeout_start(struct ssh_request *rqst)
  15810. +{
  15811. + struct ssh_rtl *rtl = ssh_request_rtl(rqst);
  15812. + ktime_t timestamp = ktime_get_coarse_boottime();
  15813. + ktime_t timeout = rtl->rtx_timeout.timeout;
  15814. +
  15815. + if (test_bit(SSH_REQUEST_SF_LOCKED_BIT, &rqst->state))
  15816. + return;
  15817. +
  15818. + /*
  15819. + * Note: The timestamp gets set only once. This happens on the packet
  15820. + * callback. All other access to it is read-only.
  15821. + */
  15822. + WRITE_ONCE(rqst->timestamp, timestamp);
  15823. + /*
  15824. + * Ensure timestamp is set before starting the reaper. Paired with
  15825. + * implicit barrier following check on ssh_request_get_expiration() in
  15826. + * ssh_rtl_timeout_reap.
  15827. + */
  15828. + smp_mb__after_atomic();
  15829. +
  15830. + ssh_rtl_timeout_reaper_mod(rtl, timestamp, timestamp + timeout);
  15831. +}
  15832. +
  15833. +static void ssh_rtl_complete(struct ssh_rtl *rtl,
  15834. + const struct ssh_command *command,
  15835. + const struct ssam_span *command_data)
  15836. +{
  15837. + struct ssh_request *r = NULL;
  15838. + struct ssh_request *p, *n;
  15839. + u16 rqid = get_unaligned_le16(&command->rqid);
  15840. +
  15841. + trace_ssam_rx_response_received(command, command_data->len);
  15842. +
  15843. + /*
  15844. + * Get request from pending based on request ID and mark it as response
  15845. + * received and locked.
  15846. + */
  15847. + spin_lock(&rtl->pending.lock);
  15848. + list_for_each_entry_safe(p, n, &rtl->pending.head, node) {
  15849. + /* We generally expect requests to be processed in order. */
  15850. + if (unlikely(ssh_request_get_rqid(p) != rqid))
  15851. + continue;
  15852. +
  15853. + /* Simulate response timeout. */
  15854. + if (ssh_rtl_should_drop_response()) {
  15855. + spin_unlock(&rtl->pending.lock);
  15856. +
  15857. + trace_ssam_ei_rx_drop_response(p);
  15858. + rtl_info(rtl, "request error injection: dropping response for request %p\n",
  15859. + &p->packet);
  15860. + return;
  15861. + }
  15862. +
  15863. + /*
  15864. + * Mark as "response received" and "locked" as we're going to
  15865. + * complete it.
  15866. + */
  15867. + set_bit(SSH_REQUEST_SF_LOCKED_BIT, &p->state);
  15868. + set_bit(SSH_REQUEST_SF_RSPRCVD_BIT, &p->state);
  15869. + /* Ensure state never gets zero. */
  15870. + smp_mb__before_atomic();
  15871. + clear_bit(SSH_REQUEST_SF_PENDING_BIT, &p->state);
  15872. +
  15873. + atomic_dec(&rtl->pending.count);
  15874. + list_del(&p->node);
  15875. +
  15876. + r = p;
  15877. + break;
  15878. + }
  15879. + spin_unlock(&rtl->pending.lock);
  15880. +
  15881. + if (!r) {
  15882. + rtl_warn(rtl, "rtl: dropping unexpected command message (rqid = %#06x)\n",
  15883. + rqid);
  15884. + return;
  15885. + }
  15886. +
  15887. + /* If the request hasn't been completed yet, we will do this now. */
  15888. + if (test_and_set_bit(SSH_REQUEST_SF_COMPLETED_BIT, &r->state)) {
  15889. + ssh_request_put(r);
  15890. + ssh_rtl_tx_schedule(rtl);
  15891. + return;
  15892. + }
  15893. +
  15894. + /*
  15895. + * Make sure the request has been transmitted. In case of a sequenced
  15896. + * request, we are guaranteed that the completion callback will run on
  15897. + * the receiver thread directly when the ACK for the packet has been
  15898. + * received. Similarly, this function is guaranteed to run on the
  15899. + * receiver thread. Thus we are guaranteed that if the packet has been
  15900. + * successfully transmitted and received an ACK, the transmitted flag
  15901. + * has been set and is visible here.
  15902. + *
  15903. + * We are currently not handling unsequenced packets here, as those
  15904. + * should never expect a response as ensured in ssh_rtl_submit. If this
  15905. + * ever changes, one would have to test for
  15906. + *
  15907. + * (r->state & (transmitting | transmitted))
  15908. + *
  15909. + * on unsequenced packets to determine if they could have been
  15910. + * transmitted. There are no synchronization guarantees as in the
  15911. + * sequenced case, since, in this case, the callback function will not
  15912. + * run on the same thread. Thus an exact determination is impossible.
  15913. + */
  15914. + if (!test_bit(SSH_REQUEST_SF_TRANSMITTED_BIT, &r->state)) {
  15915. + rtl_err(rtl, "rtl: received response before ACK for request (rqid = %#06x)\n",
  15916. + rqid);
  15917. +
  15918. + /*
  15919. + * NB: Timeout has already been canceled, request already been
  15920. + * removed from pending and marked as locked and completed. As
  15921. + * we receive a "false" response, the packet might still be
  15922. + * queued though.
  15923. + */
  15924. + ssh_rtl_queue_remove(r);
  15925. +
  15926. + ssh_rtl_complete_with_status(r, -EREMOTEIO);
  15927. + ssh_request_put(r);
  15928. +
  15929. + ssh_rtl_tx_schedule(rtl);
  15930. + return;
  15931. + }
  15932. +
  15933. + /*
  15934. + * NB: Timeout has already been canceled, request already been
  15935. + * removed from pending and marked as locked and completed. The request
  15936. + * can also not be queued any more, as it has been marked as
  15937. + * transmitting and later transmitted. Thus no need to remove it from
  15938. + * anywhere.
  15939. + */
  15940. +
  15941. + ssh_rtl_complete_with_rsp(r, command, command_data);
  15942. + ssh_request_put(r);
  15943. +
  15944. + ssh_rtl_tx_schedule(rtl);
  15945. +}
  15946. +
  15947. +static bool ssh_rtl_cancel_nonpending(struct ssh_request *r)
  15948. +{
  15949. + struct ssh_rtl *rtl;
  15950. + unsigned long flags, fixed;
  15951. + bool remove;
  15952. +
  15953. + /*
  15954. + * Handle unsubmitted request: Try to mark the packet as locked,
  15955. + * expecting the state to be zero (i.e. unsubmitted). Note that, if
  15956. + * setting the state worked, we might still be adding the packet to the
  15957. + * queue in a currently executing submit call. In that case, however,
  15958. + * ptl reference must have been set previously, as locked is checked
  15959. + * after setting ptl. Furthermore, when the ptl reference is set, the
  15960. + * submission process is guaranteed to have entered the critical
  15961. + * section. Thus only if we successfully locked this request and ptl is
  15962. + * NULL, we have successfully removed the request, i.e. we are
  15963. + * guaranteed that, due to the "locked" check in ssh_rtl_submit(), the
  15964. + * packet will never be added. Otherwise, we need to try and grab it
  15965. + * from the queue, where we are now guaranteed that the packet is or has
  15966. + * been due to the critical section.
  15967. + *
  15968. + * Note that if the cmpxchg() fails, we are guaranteed that ptl has
  15969. + * been set and is non-NULL, as states can only be nonzero after this
  15970. + * has been set. Also note that we need to fetch the static (type)
  15971. + * flags to ensure that they don't cause the cmpxchg() to fail.
  15972. + */
  15973. + fixed = READ_ONCE(r->state) & SSH_REQUEST_FLAGS_TY_MASK;
  15974. + flags = cmpxchg(&r->state, fixed, SSH_REQUEST_SF_LOCKED_BIT);
  15975. +
  15976. + /*
  15977. + * Force correct ordering with regards to state and ptl reference access
  15978. + * to safe-guard cancellation to concurrent submission against a
  15979. + * lost-update problem. First try to exchange state, then also check
  15980. + * ptl if that worked. This barrier is paired with the
  15981. + * one in ssh_rtl_submit().
  15982. + */
  15983. + smp_mb__after_atomic();
  15984. +
  15985. + if (flags == fixed && !READ_ONCE(r->packet.ptl)) {
  15986. + if (test_and_set_bit(SSH_REQUEST_SF_COMPLETED_BIT, &r->state))
  15987. + return true;
  15988. +
  15989. + ssh_rtl_complete_with_status(r, -ECANCELED);
  15990. + return true;
  15991. + }
  15992. +
  15993. + rtl = ssh_request_rtl(r);
  15994. + spin_lock(&rtl->queue.lock);
  15995. +
  15996. + /*
  15997. + * Note: 1) Requests cannot be re-submitted. 2) If a request is
  15998. + * queued, it cannot be "transmitting"/"pending" yet. Thus, if we
  15999. + * successfully remove the request here, we have removed all its
  16000. + * occurrences in the system.
  16001. + */
  16002. +
  16003. + remove = test_and_clear_bit(SSH_REQUEST_SF_QUEUED_BIT, &r->state);
  16004. + if (!remove) {
  16005. + spin_unlock(&rtl->queue.lock);
  16006. + return false;
  16007. + }
  16008. +
  16009. + set_bit(SSH_REQUEST_SF_LOCKED_BIT, &r->state);
  16010. + list_del(&r->node);
  16011. +
  16012. + spin_unlock(&rtl->queue.lock);
  16013. +
  16014. + ssh_request_put(r); /* Drop reference obtained from queue. */
  16015. +
  16016. + if (test_and_set_bit(SSH_REQUEST_SF_COMPLETED_BIT, &r->state))
  16017. + return true;
  16018. +
  16019. + ssh_rtl_complete_with_status(r, -ECANCELED);
  16020. + return true;
  16021. +}
  16022. +
  16023. +static bool ssh_rtl_cancel_pending(struct ssh_request *r)
  16024. +{
  16025. + /* If the packet is already locked, it's going to be removed shortly. */
  16026. + if (test_and_set_bit(SSH_REQUEST_SF_LOCKED_BIT, &r->state))
  16027. + return true;
  16028. +
  16029. + /*
  16030. + * Now that we have locked the packet, we have guaranteed that it can't
  16031. + * be added to the system any more. If ptl is NULL, the locked
  16032. + * check in ssh_rtl_submit() has not been run and any submission,
  16033. + * currently in progress or called later, won't add the packet. Thus we
  16034. + * can directly complete it.
  16035. + *
  16036. + * The implicit memory barrier of test_and_set_bit() should be enough
  16037. + * to ensure that the correct order (first lock, then check ptl) is
  16038. + * ensured. This is paired with the barrier in ssh_rtl_submit().
  16039. + */
  16040. + if (!READ_ONCE(r->packet.ptl)) {
  16041. + if (test_and_set_bit(SSH_REQUEST_SF_COMPLETED_BIT, &r->state))
  16042. + return true;
  16043. +
  16044. + ssh_rtl_complete_with_status(r, -ECANCELED);
  16045. + return true;
  16046. + }
  16047. +
  16048. + /*
  16049. + * Try to cancel the packet. If the packet has not been completed yet,
  16050. + * this will subsequently (and synchronously) call the completion
  16051. + * callback of the packet, which will complete the request.
  16052. + */
  16053. + ssh_ptl_cancel(&r->packet);
  16054. +
  16055. + /*
  16056. + * If the packet has been completed with success, i.e. has not been
  16057. + * canceled by the above call, the request may not have been completed
  16058. + * yet (may be waiting for a response). Check if we need to do this
  16059. + * here.
  16060. + */
  16061. + if (test_and_set_bit(SSH_REQUEST_SF_COMPLETED_BIT, &r->state))
  16062. + return true;
  16063. +
  16064. + ssh_rtl_queue_remove(r);
  16065. + ssh_rtl_pending_remove(r);
  16066. + ssh_rtl_complete_with_status(r, -ECANCELED);
  16067. +
  16068. + return true;
  16069. +}
  16070. +
  16071. +/**
  16072. + * ssh_rtl_cancel() - Cancel request.
  16073. + * @rqst: The request to cancel.
  16074. + * @pending: Whether to also cancel pending requests.
  16075. + *
  16076. + * Cancels the given request. If @pending is %false, this will not cancel
  16077. + * pending requests, i.e. requests that have already been submitted to the
  16078. + * packet layer but not been completed yet. If @pending is %true, this will
  16079. + * cancel the given request regardless of the state it is in.
  16080. + *
  16081. + * If the request has been canceled by calling this function, both completion
  16082. + * and release callbacks of the request will be executed in a reasonable
  16083. + * time-frame. This may happen during execution of this function, however,
  16084. + * there is no guarantee for this. For example, a request currently
  16085. + * transmitting will be canceled/completed only after transmission has
  16086. + * completed, and the respective callbacks will be executed on the transmitter
  16087. + * thread, which may happen during, but also some time after execution of the
  16088. + * cancel function.
  16089. + *
  16090. + * Return: Returns %true if the given request has been canceled or completed,
  16091. + * either by this function or prior to calling this function, %false
  16092. + * otherwise. If @pending is %true, this function will always return %true.
  16093. + */
  16094. +bool ssh_rtl_cancel(struct ssh_request *rqst, bool pending)
  16095. +{
  16096. + struct ssh_rtl *rtl;
  16097. + bool canceled;
  16098. +
  16099. + if (test_and_set_bit(SSH_REQUEST_SF_CANCELED_BIT, &rqst->state))
  16100. + return true;
  16101. +
  16102. + trace_ssam_request_cancel(rqst);
  16103. +
  16104. + if (pending)
  16105. + canceled = ssh_rtl_cancel_pending(rqst);
  16106. + else
  16107. + canceled = ssh_rtl_cancel_nonpending(rqst);
  16108. +
  16109. + /* Note: rtl may be NULL if request has not been submitted yet. */
  16110. + rtl = ssh_request_rtl(rqst);
  16111. + if (canceled && rtl)
  16112. + ssh_rtl_tx_schedule(rtl);
  16113. +
  16114. + return canceled;
  16115. +}
  16116. +
  16117. +static void ssh_rtl_packet_callback(struct ssh_packet *p, int status)
  16118. +{
  16119. + struct ssh_request *r = to_ssh_request(p);
  16120. +
  16121. + if (unlikely(status)) {
  16122. + set_bit(SSH_REQUEST_SF_LOCKED_BIT, &r->state);
  16123. +
  16124. + if (test_and_set_bit(SSH_REQUEST_SF_COMPLETED_BIT, &r->state))
  16125. + return;
  16126. +
  16127. + /*
  16128. + * The packet may get canceled even though it has not been
  16129. + * submitted yet. The request may still be queued. Check the
  16130. + * queue and remove it if necessary. As the timeout would have
  16131. + * been started in this function on success, there's no need
  16132. + * to cancel it here.
  16133. + */
  16134. + ssh_rtl_queue_remove(r);
  16135. + ssh_rtl_pending_remove(r);
  16136. + ssh_rtl_complete_with_status(r, status);
  16137. +
  16138. + ssh_rtl_tx_schedule(ssh_request_rtl(r));
  16139. + return;
  16140. + }
  16141. +
  16142. + /* Update state: Mark as transmitted and clear transmitting. */
  16143. + set_bit(SSH_REQUEST_SF_TRANSMITTED_BIT, &r->state);
  16144. + /* Ensure state never gets zero. */
  16145. + smp_mb__before_atomic();
  16146. + clear_bit(SSH_REQUEST_SF_TRANSMITTING_BIT, &r->state);
  16147. +
  16148. + /* If we expect a response, we just need to start the timeout. */
  16149. + if (test_bit(SSH_REQUEST_TY_HAS_RESPONSE_BIT, &r->state)) {
  16150. + /*
  16151. + * Note: This is the only place where the timestamp gets set,
  16152. + * all other access to it is read-only.
  16153. + */
  16154. + ssh_rtl_timeout_start(r);
  16155. + return;
  16156. + }
  16157. +
  16158. + /*
  16159. + * If we don't expect a response, lock, remove, and complete the
  16160. + * request. Note that, at this point, the request is guaranteed to have
  16161. + * left the queue and no timeout has been started. Thus we only need to
  16162. + * remove it from pending. If the request has already been completed (it
  16163. + * may have been canceled) return.
  16164. + */
  16165. +
  16166. + set_bit(SSH_REQUEST_SF_LOCKED_BIT, &r->state);
  16167. + if (test_and_set_bit(SSH_REQUEST_SF_COMPLETED_BIT, &r->state))
  16168. + return;
  16169. +
  16170. + ssh_rtl_pending_remove(r);
  16171. + ssh_rtl_complete_with_status(r, 0);
  16172. +
  16173. + ssh_rtl_tx_schedule(ssh_request_rtl(r));
  16174. +}
  16175. +
  16176. +static ktime_t ssh_request_get_expiration(struct ssh_request *r, ktime_t timeout)
  16177. +{
  16178. + ktime_t timestamp = READ_ONCE(r->timestamp);
  16179. +
  16180. + if (timestamp != KTIME_MAX)
  16181. + return ktime_add(timestamp, timeout);
  16182. + else
  16183. + return KTIME_MAX;
  16184. +}
  16185. +
  16186. +static void ssh_rtl_timeout_reap(struct work_struct *work)
  16187. +{
  16188. + struct ssh_rtl *rtl = to_ssh_rtl(work, rtx_timeout.reaper.work);
  16189. + struct ssh_request *r, *n;
  16190. + LIST_HEAD(claimed);
  16191. + ktime_t now = ktime_get_coarse_boottime();
  16192. + ktime_t timeout = rtl->rtx_timeout.timeout;
  16193. + ktime_t next = KTIME_MAX;
  16194. +
  16195. + trace_ssam_rtl_timeout_reap(atomic_read(&rtl->pending.count));
  16196. +
  16197. + /*
  16198. + * Mark reaper as "not pending". This is done before checking any
  16199. + * requests to avoid lost-update type problems.
  16200. + */
  16201. + spin_lock(&rtl->rtx_timeout.lock);
  16202. + rtl->rtx_timeout.expires = KTIME_MAX;
  16203. + spin_unlock(&rtl->rtx_timeout.lock);
  16204. +
  16205. + spin_lock(&rtl->pending.lock);
  16206. + list_for_each_entry_safe(r, n, &rtl->pending.head, node) {
  16207. + ktime_t expires = ssh_request_get_expiration(r, timeout);
  16208. +
  16209. + /*
  16210. + * Check if the timeout hasn't expired yet. Find out next
  16211. + * expiration date to be handled after this run.
  16212. + */
  16213. + if (ktime_after(expires, now)) {
  16214. + next = ktime_before(expires, next) ? expires : next;
  16215. + continue;
  16216. + }
  16217. +
  16218. + /* Avoid further transitions if locked. */
  16219. + if (test_and_set_bit(SSH_REQUEST_SF_LOCKED_BIT, &r->state))
  16220. + continue;
  16221. +
  16222. + /*
  16223. + * We have now marked the packet as locked. Thus it cannot be
  16224. + * added to the pending or queued lists again after we've
  16225. + * removed it here. We can therefore re-use the node of this
  16226. + * packet temporarily.
  16227. + */
  16228. +
  16229. + clear_bit(SSH_REQUEST_SF_PENDING_BIT, &r->state);
  16230. +
  16231. + atomic_dec(&rtl->pending.count);
  16232. + list_del(&r->node);
  16233. +
  16234. + list_add_tail(&r->node, &claimed);
  16235. + }
  16236. + spin_unlock(&rtl->pending.lock);
  16237. +
  16238. + /* Cancel and complete the request. */
  16239. + list_for_each_entry_safe(r, n, &claimed, node) {
  16240. + trace_ssam_request_timeout(r);
  16241. +
  16242. + /*
  16243. + * At this point we've removed the packet from pending. This
  16244. + * means that we've obtained the last (only) reference of the
  16245. + * system to it. Thus we can just complete it.
  16246. + */
  16247. + if (!test_and_set_bit(SSH_REQUEST_SF_COMPLETED_BIT, &r->state))
  16248. + ssh_rtl_complete_with_status(r, -ETIMEDOUT);
  16249. +
  16250. + /*
  16251. + * Drop the reference we've obtained by removing it from the
  16252. + * pending set.
  16253. + */
  16254. + list_del(&r->node);
  16255. + ssh_request_put(r);
  16256. + }
  16257. +
  16258. + /* Ensure that the reaper doesn't run again immediately. */
  16259. + next = max(next, ktime_add(now, SSH_RTL_REQUEST_TIMEOUT_RESOLUTION));
  16260. + if (next != KTIME_MAX)
  16261. + ssh_rtl_timeout_reaper_mod(rtl, now, next);
  16262. +
  16263. + ssh_rtl_tx_schedule(rtl);
  16264. +}
  16265. +
  16266. +static void ssh_rtl_rx_event(struct ssh_rtl *rtl, const struct ssh_command *cmd,
  16267. + const struct ssam_span *data)
  16268. +{
  16269. + trace_ssam_rx_event_received(cmd, data->len);
  16270. +
  16271. + rtl_dbg(rtl, "rtl: handling event (rqid: %#06x)\n",
  16272. + get_unaligned_le16(&cmd->rqid));
  16273. +
  16274. + rtl->ops.handle_event(rtl, cmd, data);
  16275. +}
  16276. +
  16277. +static void ssh_rtl_rx_command(struct ssh_ptl *p, const struct ssam_span *data)
  16278. +{
  16279. + struct ssh_rtl *rtl = to_ssh_rtl(p, ptl);
  16280. + struct device *dev = &p->serdev->dev;
  16281. + struct ssh_command *command;
  16282. + struct ssam_span command_data;
  16283. +
  16284. + if (sshp_parse_command(dev, data, &command, &command_data))
  16285. + return;
  16286. +
  16287. + if (ssh_rqid_is_event(get_unaligned_le16(&command->rqid)))
  16288. + ssh_rtl_rx_event(rtl, command, &command_data);
  16289. + else
  16290. + ssh_rtl_complete(rtl, command, &command_data);
  16291. +}
  16292. +
  16293. +static void ssh_rtl_rx_data(struct ssh_ptl *p, const struct ssam_span *data)
  16294. +{
  16295. + if (!data->len) {
  16296. + ptl_err(p, "rtl: rx: no data frame payload\n");
  16297. + return;
  16298. + }
  16299. +
  16300. + switch (data->ptr[0]) {
  16301. + case SSH_PLD_TYPE_CMD:
  16302. + ssh_rtl_rx_command(p, data);
  16303. + break;
  16304. +
  16305. + default:
  16306. + ptl_err(p, "rtl: rx: unknown frame payload type (type: %#04x)\n",
  16307. + data->ptr[0]);
  16308. + break;
  16309. + }
  16310. +}
  16311. +
  16312. +static void ssh_rtl_packet_release(struct ssh_packet *p)
  16313. +{
  16314. + struct ssh_request *rqst;
  16315. +
  16316. + rqst = to_ssh_request(p);
  16317. + rqst->ops->release(rqst);
  16318. +}
  16319. +
  16320. +static const struct ssh_packet_ops ssh_rtl_packet_ops = {
  16321. + .complete = ssh_rtl_packet_callback,
  16322. + .release = ssh_rtl_packet_release,
  16323. +};
  16324. +
  16325. +/**
  16326. + * ssh_request_init() - Initialize SSH request.
  16327. + * @rqst: The request to initialize.
  16328. + * @flags: Request flags, determining the type of the request.
  16329. + * @ops: Request operations.
  16330. + *
  16331. + * Initializes the given SSH request and underlying packet. Sets the message
  16332. + * buffer pointer to %NULL and the message buffer length to zero. This buffer
  16333. + * has to be set separately via ssh_request_set_data() before submission and
  16334. + * must contain a valid SSH request message.
  16335. + *
  16336. + * Return: Returns zero on success or %-EINVAL if the given flags are invalid.
  16337. + */
  16338. +int ssh_request_init(struct ssh_request *rqst, enum ssam_request_flags flags,
  16339. + const struct ssh_request_ops *ops)
  16340. +{
  16341. + unsigned long type = BIT(SSH_PACKET_TY_BLOCKING_BIT);
  16342. +
  16343. + /* Unsequenced requests cannot have a response. */
  16344. + if (flags & SSAM_REQUEST_UNSEQUENCED && flags & SSAM_REQUEST_HAS_RESPONSE)
  16345. + return -EINVAL;
  16346. +
  16347. + if (!(flags & SSAM_REQUEST_UNSEQUENCED))
  16348. + type |= BIT(SSH_PACKET_TY_SEQUENCED_BIT);
  16349. +
  16350. + ssh_packet_init(&rqst->packet, type, SSH_PACKET_PRIORITY(DATA, 0),
  16351. + &ssh_rtl_packet_ops);
  16352. +
  16353. + INIT_LIST_HEAD(&rqst->node);
  16354. +
  16355. + rqst->state = 0;
  16356. + if (flags & SSAM_REQUEST_HAS_RESPONSE)
  16357. + rqst->state |= BIT(SSH_REQUEST_TY_HAS_RESPONSE_BIT);
  16358. +
  16359. + rqst->timestamp = KTIME_MAX;
  16360. + rqst->ops = ops;
  16361. +
  16362. + return 0;
  16363. +}
  16364. +
  16365. +/**
  16366. + * ssh_rtl_init() - Initialize request transport layer.
  16367. + * @rtl: The request transport layer to initialize.
  16368. + * @serdev: The underlying serial device, i.e. the lower-level transport.
  16369. + * @ops: Request transport layer operations.
  16370. + *
  16371. + * Initializes the given request transport layer and associated packet
  16372. + * transport layer. Transmitter and receiver threads must be started
  16373. + * separately via ssh_rtl_tx_start() and ssh_rtl_rx_start(), after the
  16374. + * request-layer has been initialized and the lower-level serial device layer
  16375. + * has been set up.
  16376. + *
  16377. + * Return: Returns zero on success and a nonzero error code on failure.
  16378. + */
  16379. +int ssh_rtl_init(struct ssh_rtl *rtl, struct serdev_device *serdev,
  16380. + const struct ssh_rtl_ops *ops)
  16381. +{
  16382. + struct ssh_ptl_ops ptl_ops;
  16383. + int status;
  16384. +
  16385. + ptl_ops.data_received = ssh_rtl_rx_data;
  16386. +
  16387. + status = ssh_ptl_init(&rtl->ptl, serdev, &ptl_ops);
  16388. + if (status)
  16389. + return status;
  16390. +
  16391. + spin_lock_init(&rtl->queue.lock);
  16392. + INIT_LIST_HEAD(&rtl->queue.head);
  16393. +
  16394. + spin_lock_init(&rtl->pending.lock);
  16395. + INIT_LIST_HEAD(&rtl->pending.head);
  16396. + atomic_set_release(&rtl->pending.count, 0);
  16397. +
  16398. + INIT_WORK(&rtl->tx.work, ssh_rtl_tx_work_fn);
  16399. +
  16400. + spin_lock_init(&rtl->rtx_timeout.lock);
  16401. + rtl->rtx_timeout.timeout = SSH_RTL_REQUEST_TIMEOUT;
  16402. + rtl->rtx_timeout.expires = KTIME_MAX;
  16403. + INIT_DELAYED_WORK(&rtl->rtx_timeout.reaper, ssh_rtl_timeout_reap);
  16404. +
  16405. + rtl->ops = *ops;
  16406. +
  16407. + return 0;
  16408. +}
  16409. +
  16410. +/**
  16411. + * ssh_rtl_destroy() - Deinitialize request transport layer.
  16412. + * @rtl: The request transport layer to deinitialize.
  16413. + *
  16414. + * Deinitializes the given request transport layer and frees resources
  16415. + * associated with it. If receiver and/or transmitter threads have been
  16416. + * started, the layer must first be shut down via ssh_rtl_shutdown() before
  16417. + * this function can be called.
  16418. + */
  16419. +void ssh_rtl_destroy(struct ssh_rtl *rtl)
  16420. +{
  16421. + ssh_ptl_destroy(&rtl->ptl);
  16422. +}
  16423. +
  16424. +/**
  16425. + * ssh_rtl_tx_start() - Start request transmitter and receiver.
  16426. + * @rtl: The request transport layer.
  16427. + *
  16428. + * Return: Returns zero on success, a negative error code on failure.
  16429. + */
  16430. +int ssh_rtl_start(struct ssh_rtl *rtl)
  16431. +{
  16432. + int status;
  16433. +
  16434. + status = ssh_ptl_tx_start(&rtl->ptl);
  16435. + if (status)
  16436. + return status;
  16437. +
  16438. + ssh_rtl_tx_schedule(rtl);
  16439. +
  16440. + status = ssh_ptl_rx_start(&rtl->ptl);
  16441. + if (status) {
  16442. + ssh_rtl_flush(rtl, msecs_to_jiffies(5000));
  16443. + ssh_ptl_tx_stop(&rtl->ptl);
  16444. + return status;
  16445. + }
  16446. +
  16447. + return 0;
  16448. +}
  16449. +
  16450. +struct ssh_flush_request {
  16451. + struct ssh_request base;
  16452. + struct completion completion;
  16453. + int status;
  16454. +};
  16455. +
  16456. +static void ssh_rtl_flush_request_complete(struct ssh_request *r,
  16457. + const struct ssh_command *cmd,
  16458. + const struct ssam_span *data,
  16459. + int status)
  16460. +{
  16461. + struct ssh_flush_request *rqst;
  16462. +
  16463. + rqst = container_of(r, struct ssh_flush_request, base);
  16464. + rqst->status = status;
  16465. +}
  16466. +
  16467. +static void ssh_rtl_flush_request_release(struct ssh_request *r)
  16468. +{
  16469. + struct ssh_flush_request *rqst;
  16470. +
  16471. + rqst = container_of(r, struct ssh_flush_request, base);
  16472. + complete_all(&rqst->completion);
  16473. +}
  16474. +
  16475. +static const struct ssh_request_ops ssh_rtl_flush_request_ops = {
  16476. + .complete = ssh_rtl_flush_request_complete,
  16477. + .release = ssh_rtl_flush_request_release,
  16478. +};
  16479. +
  16480. +/**
  16481. + * ssh_rtl_flush() - Flush the request transport layer.
  16482. + * @rtl: request transport layer
  16483. + * @timeout: timeout for the flush operation in jiffies
  16484. + *
  16485. + * Queue a special flush request and wait for its completion. This request
  16486. + * will be completed after all other currently queued and pending requests
  16487. + * have been completed. Instead of a normal data packet, this request submits
  16488. + * a special flush packet, meaning that upon completion, also the underlying
  16489. + * packet transport layer has been flushed.
  16490. + *
  16491. + * Flushing the request layer guarantees that all previously submitted
  16492. + * requests have been fully completed before this call returns. Additionally,
  16493. + * flushing blocks execution of all later submitted requests until the flush
  16494. + * has been completed.
  16495. + *
  16496. + * If the caller ensures that no new requests are submitted after a call to
  16497. + * this function, the request transport layer is guaranteed to have no
  16498. + * remaining requests when this call returns. The same guarantee does not hold
  16499. + * for the packet layer, on which control packets may still be queued after
  16500. + * this call.
  16501. + *
  16502. + * Return: Returns zero on success, %-ETIMEDOUT if the flush timed out and has
  16503. + * been canceled as a result of the timeout, or %-ESHUTDOWN if the packet
  16504. + * and/or request transport layer has been shut down before this call. May
  16505. + * also return %-EINTR if the underlying packet transmission has been
  16506. + * interrupted.
  16507. + */
  16508. +int ssh_rtl_flush(struct ssh_rtl *rtl, unsigned long timeout)
  16509. +{
  16510. + const unsigned int init_flags = SSAM_REQUEST_UNSEQUENCED;
  16511. + struct ssh_flush_request rqst;
  16512. + int status;
  16513. +
  16514. + ssh_request_init(&rqst.base, init_flags, &ssh_rtl_flush_request_ops);
  16515. + rqst.base.packet.state |= BIT(SSH_PACKET_TY_FLUSH_BIT);
  16516. + rqst.base.packet.priority = SSH_PACKET_PRIORITY(FLUSH, 0);
  16517. + rqst.base.state |= BIT(SSH_REQUEST_TY_FLUSH_BIT);
  16518. +
  16519. + init_completion(&rqst.completion);
  16520. +
  16521. + status = ssh_rtl_submit(rtl, &rqst.base);
  16522. + if (status)
  16523. + return status;
  16524. +
  16525. + ssh_request_put(&rqst.base);
  16526. +
  16527. + if (!wait_for_completion_timeout(&rqst.completion, timeout)) {
  16528. + ssh_rtl_cancel(&rqst.base, true);
  16529. + wait_for_completion(&rqst.completion);
  16530. + }
  16531. +
  16532. + WARN_ON(rqst.status != 0 && rqst.status != -ECANCELED &&
  16533. + rqst.status != -ESHUTDOWN && rqst.status != -EINTR);
  16534. +
  16535. + return rqst.status == -ECANCELED ? -ETIMEDOUT : rqst.status;
  16536. +}
  16537. +
  16538. +/**
  16539. + * ssh_rtl_shutdown() - Shut down request transport layer.
  16540. + * @rtl: The request transport layer.
  16541. + *
  16542. + * Shuts down the request transport layer, removing and canceling all queued
  16543. + * and pending requests. Requests canceled by this operation will be completed
  16544. + * with %-ESHUTDOWN as status. Receiver and transmitter threads will be
  16545. + * stopped, the lower-level packet layer will be shutdown.
  16546. + *
  16547. + * As a result of this function, the transport layer will be marked as shut
  16548. + * down. Submission of requests after the transport layer has been shut down
  16549. + * will fail with %-ESHUTDOWN.
  16550. + */
  16551. +void ssh_rtl_shutdown(struct ssh_rtl *rtl)
  16552. +{
  16553. + struct ssh_request *r, *n;
  16554. + LIST_HEAD(claimed);
  16555. + int pending;
  16556. +
  16557. + set_bit(SSH_RTL_SF_SHUTDOWN_BIT, &rtl->state);
  16558. + /*
  16559. + * Ensure that the layer gets marked as shut-down before actually
  16560. + * stopping it. In combination with the check in ssh_rtl_submit(),
  16561. + * this guarantees that no new requests can be added and all already
  16562. + * queued requests are properly canceled.
  16563. + */
  16564. + smp_mb__after_atomic();
  16565. +
  16566. + /* Remove requests from queue. */
  16567. + spin_lock(&rtl->queue.lock);
  16568. + list_for_each_entry_safe(r, n, &rtl->queue.head, node) {
  16569. + set_bit(SSH_REQUEST_SF_LOCKED_BIT, &r->state);
  16570. + /* Ensure state never gets zero. */
  16571. + smp_mb__before_atomic();
  16572. + clear_bit(SSH_REQUEST_SF_QUEUED_BIT, &r->state);
  16573. +
  16574. + list_del(&r->node);
  16575. + list_add_tail(&r->node, &claimed);
  16576. + }
  16577. + spin_unlock(&rtl->queue.lock);
  16578. +
  16579. + /*
  16580. + * We have now guaranteed that the queue is empty and no more new
  16581. + * requests can be submitted (i.e. it will stay empty). This means that
  16582. + * calling ssh_rtl_tx_schedule() will not schedule tx.work any more. So
  16583. + * we can simply call cancel_work_sync() on tx.work here and when that
  16584. + * returns, we've locked it down. This also means that after this call,
  16585. + * we don't submit any more packets to the underlying packet layer, so
  16586. + * we can also shut that down.
  16587. + */
  16588. +
  16589. + cancel_work_sync(&rtl->tx.work);
  16590. + ssh_ptl_shutdown(&rtl->ptl);
  16591. + cancel_delayed_work_sync(&rtl->rtx_timeout.reaper);
  16592. +
  16593. + /*
  16594. + * Shutting down the packet layer should also have canceled all
  16595. + * requests. Thus the pending set should be empty. Attempt to handle
  16596. + * this gracefully anyways, even though this should be dead code.
  16597. + */
  16598. +
  16599. + pending = atomic_read(&rtl->pending.count);
  16600. + if (WARN_ON(pending)) {
  16601. + spin_lock(&rtl->pending.lock);
  16602. + list_for_each_entry_safe(r, n, &rtl->pending.head, node) {
  16603. + set_bit(SSH_REQUEST_SF_LOCKED_BIT, &r->state);
  16604. + /* Ensure state never gets zero. */
  16605. + smp_mb__before_atomic();
  16606. + clear_bit(SSH_REQUEST_SF_PENDING_BIT, &r->state);
  16607. +
  16608. + list_del(&r->node);
  16609. + list_add_tail(&r->node, &claimed);
  16610. + }
  16611. + spin_unlock(&rtl->pending.lock);
  16612. + }
  16613. +
  16614. + /* Finally, cancel and complete the requests we claimed before. */
  16615. + list_for_each_entry_safe(r, n, &claimed, node) {
  16616. + /*
  16617. + * We need test_and_set() because we still might compete with
  16618. + * cancellation.
  16619. + */
  16620. + if (!test_and_set_bit(SSH_REQUEST_SF_COMPLETED_BIT, &r->state))
  16621. + ssh_rtl_complete_with_status(r, -ESHUTDOWN);
  16622. +
  16623. + /*
  16624. + * Drop the reference we've obtained by removing it from the
  16625. + * lists.
  16626. + */
  16627. + list_del(&r->node);
  16628. + ssh_request_put(r);
  16629. + }
  16630. +}
  16631. diff --git a/drivers/misc/surface_aggregator/ssh_request_layer.h b/drivers/misc/surface_aggregator/ssh_request_layer.h
  16632. new file mode 100644
  16633. index 000000000000..cb35815858d1
  16634. --- /dev/null
  16635. +++ b/drivers/misc/surface_aggregator/ssh_request_layer.h
  16636. @@ -0,0 +1,143 @@
  16637. +/* SPDX-License-Identifier: GPL-2.0+ */
  16638. +/*
  16639. + * SSH request transport layer.
  16640. + *
  16641. + * Copyright (C) 2019-2020 Maximilian Luz <luzmaximilian@gmail.com>
  16642. + */
  16643. +
  16644. +#ifndef _SURFACE_AGGREGATOR_SSH_REQUEST_LAYER_H
  16645. +#define _SURFACE_AGGREGATOR_SSH_REQUEST_LAYER_H
  16646. +
  16647. +#include <linux/atomic.h>
  16648. +#include <linux/ktime.h>
  16649. +#include <linux/list.h>
  16650. +#include <linux/spinlock.h>
  16651. +#include <linux/workqueue.h>
  16652. +
  16653. +#include <linux/surface_aggregator/serial_hub.h>
  16654. +#include <linux/surface_aggregator/controller.h>
  16655. +
  16656. +#include "ssh_packet_layer.h"
  16657. +
  16658. +/**
  16659. + * enum ssh_rtl_state_flags - State-flags for &struct ssh_rtl.
  16660. + *
  16661. + * @SSH_RTL_SF_SHUTDOWN_BIT:
  16662. + * Indicates that the request transport layer has been shut down or is
  16663. + * being shut down and should not accept any new requests.
  16664. + */
  16665. +enum ssh_rtl_state_flags {
  16666. + SSH_RTL_SF_SHUTDOWN_BIT,
  16667. +};
  16668. +
  16669. +/**
  16670. + * struct ssh_rtl_ops - Callback operations for request transport layer.
  16671. + * @handle_event: Function called when a SSH event has been received. The
  16672. + * specified function takes the request layer, received command
  16673. + * struct, and corresponding payload as arguments. If the event
  16674. + * has no payload, the payload span is empty (not %NULL).
  16675. + */
  16676. +struct ssh_rtl_ops {
  16677. + void (*handle_event)(struct ssh_rtl *rtl, const struct ssh_command *cmd,
  16678. + const struct ssam_span *data);
  16679. +};
  16680. +
  16681. +/**
  16682. + * struct ssh_rtl - SSH request transport layer.
  16683. + * @ptl: Underlying packet transport layer.
  16684. + * @state: State(-flags) of the transport layer.
  16685. + * @queue: Request submission queue.
  16686. + * @queue.lock: Lock for modifying the request submission queue.
  16687. + * @queue.head: List-head of the request submission queue.
  16688. + * @pending: Set/list of pending requests.
  16689. + * @pending.lock: Lock for modifying the request set.
  16690. + * @pending.head: List-head of the pending set/list.
  16691. + * @pending.count: Number of currently pending requests.
  16692. + * @tx: Transmitter subsystem.
  16693. + * @tx.work: Transmitter work item.
  16694. + * @rtx_timeout: Retransmission timeout subsystem.
  16695. + * @rtx_timeout.lock: Lock for modifying the retransmission timeout reaper.
  16696. + * @rtx_timeout.timeout: Timeout interval for retransmission.
  16697. + * @rtx_timeout.expires: Time specifying when the reaper work is next scheduled.
  16698. + * @rtx_timeout.reaper: Work performing timeout checks and subsequent actions.
  16699. + * @ops: Request layer operations.
  16700. + */
  16701. +struct ssh_rtl {
  16702. + struct ssh_ptl ptl;
  16703. + unsigned long state;
  16704. +
  16705. + struct {
  16706. + spinlock_t lock;
  16707. + struct list_head head;
  16708. + } queue;
  16709. +
  16710. + struct {
  16711. + spinlock_t lock;
  16712. + struct list_head head;
  16713. + atomic_t count;
  16714. + } pending;
  16715. +
  16716. + struct {
  16717. + struct work_struct work;
  16718. + } tx;
  16719. +
  16720. + struct {
  16721. + spinlock_t lock;
  16722. + ktime_t timeout;
  16723. + ktime_t expires;
  16724. + struct delayed_work reaper;
  16725. + } rtx_timeout;
  16726. +
  16727. + struct ssh_rtl_ops ops;
  16728. +};
  16729. +
  16730. +#define rtl_dbg(r, fmt, ...) ptl_dbg(&(r)->ptl, fmt, ##__VA_ARGS__)
  16731. +#define rtl_info(p, fmt, ...) ptl_info(&(p)->ptl, fmt, ##__VA_ARGS__)
  16732. +#define rtl_warn(r, fmt, ...) ptl_warn(&(r)->ptl, fmt, ##__VA_ARGS__)
  16733. +#define rtl_err(r, fmt, ...) ptl_err(&(r)->ptl, fmt, ##__VA_ARGS__)
  16734. +#define rtl_dbg_cond(r, fmt, ...) __ssam_prcond(rtl_dbg, r, fmt, ##__VA_ARGS__)
  16735. +
  16736. +#define to_ssh_rtl(ptr, member) \
  16737. + container_of(ptr, struct ssh_rtl, member)
  16738. +
  16739. +/**
  16740. + * ssh_rtl_get_device() - Get device associated with request transport layer.
  16741. + * @rtl: The request transport layer.
  16742. + *
  16743. + * Return: Returns the device on which the given request transport layer
  16744. + * builds upon.
  16745. + */
  16746. +static inline struct device *ssh_rtl_get_device(struct ssh_rtl *rtl)
  16747. +{
  16748. + return ssh_ptl_get_device(&rtl->ptl);
  16749. +}
  16750. +
  16751. +/**
  16752. + * ssh_request_rtl() - Get request transport layer associated with request.
  16753. + * @rqst: The request to get the request transport layer reference for.
  16754. + *
  16755. + * Return: Returns the &struct ssh_rtl associated with the given SSH request.
  16756. + */
  16757. +static inline struct ssh_rtl *ssh_request_rtl(struct ssh_request *rqst)
  16758. +{
  16759. + struct ssh_ptl *ptl;
  16760. +
  16761. + ptl = READ_ONCE(rqst->packet.ptl);
  16762. + return likely(ptl) ? to_ssh_rtl(ptl, ptl) : NULL;
  16763. +}
  16764. +
  16765. +int ssh_rtl_submit(struct ssh_rtl *rtl, struct ssh_request *rqst);
  16766. +bool ssh_rtl_cancel(struct ssh_request *rqst, bool pending);
  16767. +
  16768. +int ssh_rtl_init(struct ssh_rtl *rtl, struct serdev_device *serdev,
  16769. + const struct ssh_rtl_ops *ops);
  16770. +
  16771. +int ssh_rtl_start(struct ssh_rtl *rtl);
  16772. +int ssh_rtl_flush(struct ssh_rtl *rtl, unsigned long timeout);
  16773. +void ssh_rtl_shutdown(struct ssh_rtl *rtl);
  16774. +void ssh_rtl_destroy(struct ssh_rtl *rtl);
  16775. +
  16776. +int ssh_request_init(struct ssh_request *rqst, enum ssam_request_flags flags,
  16777. + const struct ssh_request_ops *ops);
  16778. +
  16779. +#endif /* _SURFACE_AGGREGATOR_SSH_REQUEST_LAYER_H */
  16780. diff --git a/drivers/misc/surface_aggregator/trace.h b/drivers/misc/surface_aggregator/trace.h
  16781. new file mode 100644
  16782. index 000000000000..eb332bb53ae4
  16783. --- /dev/null
  16784. +++ b/drivers/misc/surface_aggregator/trace.h
  16785. @@ -0,0 +1,632 @@
  16786. +/* SPDX-License-Identifier: GPL-2.0+ */
  16787. +/*
  16788. + * Trace points for SSAM/SSH.
  16789. + *
  16790. + * Copyright (C) 2020 Maximilian Luz <luzmaximilian@gmail.com>
  16791. + */
  16792. +
  16793. +#undef TRACE_SYSTEM
  16794. +#define TRACE_SYSTEM surface_aggregator
  16795. +
  16796. +#if !defined(_SURFACE_AGGREGATOR_TRACE_H) || defined(TRACE_HEADER_MULTI_READ)
  16797. +#define _SURFACE_AGGREGATOR_TRACE_H
  16798. +
  16799. +#include <linux/surface_aggregator/serial_hub.h>
  16800. +
  16801. +#include <asm/unaligned.h>
  16802. +#include <linux/tracepoint.h>
  16803. +
  16804. +TRACE_DEFINE_ENUM(SSH_FRAME_TYPE_DATA_SEQ);
  16805. +TRACE_DEFINE_ENUM(SSH_FRAME_TYPE_DATA_NSQ);
  16806. +TRACE_DEFINE_ENUM(SSH_FRAME_TYPE_ACK);
  16807. +TRACE_DEFINE_ENUM(SSH_FRAME_TYPE_NAK);
  16808. +
  16809. +TRACE_DEFINE_ENUM(SSH_PACKET_SF_LOCKED_BIT);
  16810. +TRACE_DEFINE_ENUM(SSH_PACKET_SF_QUEUED_BIT);
  16811. +TRACE_DEFINE_ENUM(SSH_PACKET_SF_PENDING_BIT);
  16812. +TRACE_DEFINE_ENUM(SSH_PACKET_SF_TRANSMITTING_BIT);
  16813. +TRACE_DEFINE_ENUM(SSH_PACKET_SF_TRANSMITTED_BIT);
  16814. +TRACE_DEFINE_ENUM(SSH_PACKET_SF_ACKED_BIT);
  16815. +TRACE_DEFINE_ENUM(SSH_PACKET_SF_CANCELED_BIT);
  16816. +TRACE_DEFINE_ENUM(SSH_PACKET_SF_COMPLETED_BIT);
  16817. +
  16818. +TRACE_DEFINE_ENUM(SSH_PACKET_TY_FLUSH_BIT);
  16819. +TRACE_DEFINE_ENUM(SSH_PACKET_TY_SEQUENCED_BIT);
  16820. +TRACE_DEFINE_ENUM(SSH_PACKET_TY_BLOCKING_BIT);
  16821. +
  16822. +TRACE_DEFINE_ENUM(SSH_PACKET_FLAGS_SF_MASK);
  16823. +TRACE_DEFINE_ENUM(SSH_PACKET_FLAGS_TY_MASK);
  16824. +
  16825. +TRACE_DEFINE_ENUM(SSH_REQUEST_SF_LOCKED_BIT);
  16826. +TRACE_DEFINE_ENUM(SSH_REQUEST_SF_QUEUED_BIT);
  16827. +TRACE_DEFINE_ENUM(SSH_REQUEST_SF_PENDING_BIT);
  16828. +TRACE_DEFINE_ENUM(SSH_REQUEST_SF_TRANSMITTING_BIT);
  16829. +TRACE_DEFINE_ENUM(SSH_REQUEST_SF_TRANSMITTED_BIT);
  16830. +TRACE_DEFINE_ENUM(SSH_REQUEST_SF_RSPRCVD_BIT);
  16831. +TRACE_DEFINE_ENUM(SSH_REQUEST_SF_CANCELED_BIT);
  16832. +TRACE_DEFINE_ENUM(SSH_REQUEST_SF_COMPLETED_BIT);
  16833. +
  16834. +TRACE_DEFINE_ENUM(SSH_REQUEST_TY_FLUSH_BIT);
  16835. +TRACE_DEFINE_ENUM(SSH_REQUEST_TY_HAS_RESPONSE_BIT);
  16836. +
  16837. +TRACE_DEFINE_ENUM(SSH_REQUEST_FLAGS_SF_MASK);
  16838. +TRACE_DEFINE_ENUM(SSH_REQUEST_FLAGS_TY_MASK);
  16839. +
  16840. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_SAM);
  16841. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_BAT);
  16842. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_TMP);
  16843. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_PMC);
  16844. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_FAN);
  16845. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_PoM);
  16846. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_DBG);
  16847. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_KBD);
  16848. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_FWU);
  16849. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_UNI);
  16850. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_LPC);
  16851. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_TCL);
  16852. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_SFL);
  16853. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_KIP);
  16854. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_EXT);
  16855. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_BLD);
  16856. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_BAS);
  16857. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_SEN);
  16858. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_SRQ);
  16859. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_MCU);
  16860. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_HID);
  16861. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_TCH);
  16862. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_BKL);
  16863. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_TAM);
  16864. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_ACC);
  16865. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_UFI);
  16866. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_USC);
  16867. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_PEN);
  16868. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_VID);
  16869. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_AUD);
  16870. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_SMC);
  16871. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_KPD);
  16872. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_REG);
  16873. +
  16874. +#define SSAM_PTR_UID_LEN 9
  16875. +#define SSAM_U8_FIELD_NOT_APPLICABLE ((u16)-1)
  16876. +#define SSAM_SEQ_NOT_APPLICABLE ((u16)-1)
  16877. +#define SSAM_RQID_NOT_APPLICABLE ((u32)-1)
  16878. +#define SSAM_SSH_TC_NOT_APPLICABLE 0
  16879. +
  16880. +#ifndef _SURFACE_AGGREGATOR_TRACE_HELPERS
  16881. +#define _SURFACE_AGGREGATOR_TRACE_HELPERS
  16882. +
  16883. +/**
  16884. + * ssam_trace_ptr_uid() - Convert the pointer to a non-pointer UID string.
  16885. + * @ptr: The pointer to convert.
  16886. + * @uid_str: A buffer of length SSAM_PTR_UID_LEN where the UID will be stored.
  16887. + *
  16888. + * Converts the given pointer into a UID string that is safe to be shared
  16889. + * with userspace and logs, i.e. doesn't give away the real memory location.
  16890. + */
  16891. +static inline void ssam_trace_ptr_uid(const void *ptr, char *uid_str)
  16892. +{
  16893. + char buf[2 * sizeof(void *) + 1];
  16894. +
  16895. + BUILD_BUG_ON(ARRAY_SIZE(buf) < SSAM_PTR_UID_LEN);
  16896. +
  16897. + snprintf(buf, ARRAY_SIZE(buf), "%p", ptr);
  16898. + memcpy(uid_str, &buf[ARRAY_SIZE(buf) - SSAM_PTR_UID_LEN],
  16899. + SSAM_PTR_UID_LEN);
  16900. +}
  16901. +
  16902. +/**
  16903. + * ssam_trace_get_packet_seq() - Read the packet's sequence ID.
  16904. + * @p: The packet.
  16905. + *
  16906. + * Return: Returns the packet's sequence ID (SEQ) field if present, or
  16907. + * %SSAM_SEQ_NOT_APPLICABLE if not (e.g. flush packet).
  16908. + */
  16909. +static inline u16 ssam_trace_get_packet_seq(const struct ssh_packet *p)
  16910. +{
  16911. + if (!p->data.ptr || p->data.len < SSH_MESSAGE_LENGTH(0))
  16912. + return SSAM_SEQ_NOT_APPLICABLE;
  16913. +
  16914. + return p->data.ptr[SSH_MSGOFFSET_FRAME(seq)];
  16915. +}
  16916. +
  16917. +/**
  16918. + * ssam_trace_get_request_id() - Read the packet's request ID.
  16919. + * @p: The packet.
  16920. + *
  16921. + * Return: Returns the packet's request ID (RQID) field if the packet
  16922. + * represents a request with command data, or %SSAM_RQID_NOT_APPLICABLE if not
  16923. + * (e.g. flush request, control packet).
  16924. + */
  16925. +static inline u32 ssam_trace_get_request_id(const struct ssh_packet *p)
  16926. +{
  16927. + if (!p->data.ptr || p->data.len < SSH_COMMAND_MESSAGE_LENGTH(0))
  16928. + return SSAM_RQID_NOT_APPLICABLE;
  16929. +
  16930. + return get_unaligned_le16(&p->data.ptr[SSH_MSGOFFSET_COMMAND(rqid)]);
  16931. +}
  16932. +
  16933. +/**
  16934. + * ssam_trace_get_request_tc() - Read the packet's request target category.
  16935. + * @p: The packet.
  16936. + *
  16937. + * Return: Returns the packet's request target category (TC) field if the
  16938. + * packet represents a request with command data, or %SSAM_TC_NOT_APPLICABLE
  16939. + * if not (e.g. flush request, control packet).
  16940. + */
  16941. +static inline u32 ssam_trace_get_request_tc(const struct ssh_packet *p)
  16942. +{
  16943. + if (!p->data.ptr || p->data.len < SSH_COMMAND_MESSAGE_LENGTH(0))
  16944. + return SSAM_SSH_TC_NOT_APPLICABLE;
  16945. +
  16946. + return get_unaligned_le16(&p->data.ptr[SSH_MSGOFFSET_COMMAND(tc)]);
  16947. +}
  16948. +
  16949. +#endif /* _SURFACE_AGGREGATOR_TRACE_HELPERS */
  16950. +
  16951. +#define ssam_trace_get_command_field_u8(packet, field) \
  16952. + ((!(packet) || (packet)->data.len < SSH_COMMAND_MESSAGE_LENGTH(0)) \
  16953. + ? 0 : (packet)->data.ptr[SSH_MSGOFFSET_COMMAND(field)])
  16954. +
  16955. +#define ssam_show_generic_u8_field(value) \
  16956. + __print_symbolic(value, \
  16957. + { SSAM_U8_FIELD_NOT_APPLICABLE, "N/A" } \
  16958. + )
  16959. +
  16960. +#define ssam_show_frame_type(ty) \
  16961. + __print_symbolic(ty, \
  16962. + { SSH_FRAME_TYPE_DATA_SEQ, "DSEQ" }, \
  16963. + { SSH_FRAME_TYPE_DATA_NSQ, "DNSQ" }, \
  16964. + { SSH_FRAME_TYPE_ACK, "ACK" }, \
  16965. + { SSH_FRAME_TYPE_NAK, "NAK" } \
  16966. + )
  16967. +
  16968. +#define ssam_show_packet_type(type) \
  16969. + __print_flags(flags & SSH_PACKET_FLAGS_TY_MASK, "", \
  16970. + { BIT(SSH_PACKET_TY_FLUSH_BIT), "F" }, \
  16971. + { BIT(SSH_PACKET_TY_SEQUENCED_BIT), "S" }, \
  16972. + { BIT(SSH_PACKET_TY_BLOCKING_BIT), "B" } \
  16973. + )
  16974. +
  16975. +#define ssam_show_packet_state(state) \
  16976. + __print_flags(flags & SSH_PACKET_FLAGS_SF_MASK, "", \
  16977. + { BIT(SSH_PACKET_SF_LOCKED_BIT), "L" }, \
  16978. + { BIT(SSH_PACKET_SF_QUEUED_BIT), "Q" }, \
  16979. + { BIT(SSH_PACKET_SF_PENDING_BIT), "P" }, \
  16980. + { BIT(SSH_PACKET_SF_TRANSMITTING_BIT), "S" }, \
  16981. + { BIT(SSH_PACKET_SF_TRANSMITTED_BIT), "T" }, \
  16982. + { BIT(SSH_PACKET_SF_ACKED_BIT), "A" }, \
  16983. + { BIT(SSH_PACKET_SF_CANCELED_BIT), "C" }, \
  16984. + { BIT(SSH_PACKET_SF_COMPLETED_BIT), "F" } \
  16985. + )
  16986. +
  16987. +#define ssam_show_packet_seq(seq) \
  16988. + __print_symbolic(seq, \
  16989. + { SSAM_SEQ_NOT_APPLICABLE, "N/A" } \
  16990. + )
  16991. +
  16992. +#define ssam_show_request_type(flags) \
  16993. + __print_flags((flags) & SSH_REQUEST_FLAGS_TY_MASK, "", \
  16994. + { BIT(SSH_REQUEST_TY_FLUSH_BIT), "F" }, \
  16995. + { BIT(SSH_REQUEST_TY_HAS_RESPONSE_BIT), "R" } \
  16996. + )
  16997. +
  16998. +#define ssam_show_request_state(flags) \
  16999. + __print_flags((flags) & SSH_REQUEST_FLAGS_SF_MASK, "", \
  17000. + { BIT(SSH_REQUEST_SF_LOCKED_BIT), "L" }, \
  17001. + { BIT(SSH_REQUEST_SF_QUEUED_BIT), "Q" }, \
  17002. + { BIT(SSH_REQUEST_SF_PENDING_BIT), "P" }, \
  17003. + { BIT(SSH_REQUEST_SF_TRANSMITTING_BIT), "S" }, \
  17004. + { BIT(SSH_REQUEST_SF_TRANSMITTED_BIT), "T" }, \
  17005. + { BIT(SSH_REQUEST_SF_RSPRCVD_BIT), "A" }, \
  17006. + { BIT(SSH_REQUEST_SF_CANCELED_BIT), "C" }, \
  17007. + { BIT(SSH_REQUEST_SF_COMPLETED_BIT), "F" } \
  17008. + )
  17009. +
  17010. +#define ssam_show_request_id(rqid) \
  17011. + __print_symbolic(rqid, \
  17012. + { SSAM_RQID_NOT_APPLICABLE, "N/A" } \
  17013. + )
  17014. +
  17015. +#define ssam_show_ssh_tc(rqid) \
  17016. + __print_symbolic(rqid, \
  17017. + { SSAM_SSH_TC_NOT_APPLICABLE, "N/A" }, \
  17018. + { SSAM_SSH_TC_SAM, "SAM" }, \
  17019. + { SSAM_SSH_TC_BAT, "BAT" }, \
  17020. + { SSAM_SSH_TC_TMP, "TMP" }, \
  17021. + { SSAM_SSH_TC_PMC, "PMC" }, \
  17022. + { SSAM_SSH_TC_FAN, "FAN" }, \
  17023. + { SSAM_SSH_TC_PoM, "PoM" }, \
  17024. + { SSAM_SSH_TC_DBG, "DBG" }, \
  17025. + { SSAM_SSH_TC_KBD, "KBD" }, \
  17026. + { SSAM_SSH_TC_FWU, "FWU" }, \
  17027. + { SSAM_SSH_TC_UNI, "UNI" }, \
  17028. + { SSAM_SSH_TC_LPC, "LPC" }, \
  17029. + { SSAM_SSH_TC_TCL, "TCL" }, \
  17030. + { SSAM_SSH_TC_SFL, "SFL" }, \
  17031. + { SSAM_SSH_TC_KIP, "KIP" }, \
  17032. + { SSAM_SSH_TC_EXT, "EXT" }, \
  17033. + { SSAM_SSH_TC_BLD, "BLD" }, \
  17034. + { SSAM_SSH_TC_BAS, "BAS" }, \
  17035. + { SSAM_SSH_TC_SEN, "SEN" }, \
  17036. + { SSAM_SSH_TC_SRQ, "SRQ" }, \
  17037. + { SSAM_SSH_TC_MCU, "MCU" }, \
  17038. + { SSAM_SSH_TC_HID, "HID" }, \
  17039. + { SSAM_SSH_TC_TCH, "TCH" }, \
  17040. + { SSAM_SSH_TC_BKL, "BKL" }, \
  17041. + { SSAM_SSH_TC_TAM, "TAM" }, \
  17042. + { SSAM_SSH_TC_ACC, "ACC" }, \
  17043. + { SSAM_SSH_TC_UFI, "UFI" }, \
  17044. + { SSAM_SSH_TC_USC, "USC" }, \
  17045. + { SSAM_SSH_TC_PEN, "PEN" }, \
  17046. + { SSAM_SSH_TC_VID, "VID" }, \
  17047. + { SSAM_SSH_TC_AUD, "AUD" }, \
  17048. + { SSAM_SSH_TC_SMC, "SMC" }, \
  17049. + { SSAM_SSH_TC_KPD, "KPD" }, \
  17050. + { SSAM_SSH_TC_REG, "REG" } \
  17051. + )
  17052. +
  17053. +DECLARE_EVENT_CLASS(ssam_frame_class,
  17054. + TP_PROTO(const struct ssh_frame *frame),
  17055. +
  17056. + TP_ARGS(frame),
  17057. +
  17058. + TP_STRUCT__entry(
  17059. + __field(u8, type)
  17060. + __field(u8, seq)
  17061. + __field(u16, len)
  17062. + ),
  17063. +
  17064. + TP_fast_assign(
  17065. + __entry->type = frame->type;
  17066. + __entry->seq = frame->seq;
  17067. + __entry->len = get_unaligned_le16(&frame->len);
  17068. + ),
  17069. +
  17070. + TP_printk("ty=%s, seq=%#04x, len=%u",
  17071. + ssam_show_frame_type(__entry->type),
  17072. + __entry->seq,
  17073. + __entry->len
  17074. + )
  17075. +);
  17076. +
  17077. +#define DEFINE_SSAM_FRAME_EVENT(name) \
  17078. + DEFINE_EVENT(ssam_frame_class, ssam_##name, \
  17079. + TP_PROTO(const struct ssh_frame *frame), \
  17080. + TP_ARGS(frame) \
  17081. + )
  17082. +
  17083. +DECLARE_EVENT_CLASS(ssam_command_class,
  17084. + TP_PROTO(const struct ssh_command *cmd, u16 len),
  17085. +
  17086. + TP_ARGS(cmd, len),
  17087. +
  17088. + TP_STRUCT__entry(
  17089. + __field(u16, rqid)
  17090. + __field(u16, len)
  17091. + __field(u8, tc)
  17092. + __field(u8, cid)
  17093. + __field(u8, iid)
  17094. + ),
  17095. +
  17096. + TP_fast_assign(
  17097. + __entry->rqid = get_unaligned_le16(&cmd->rqid);
  17098. + __entry->tc = cmd->tc;
  17099. + __entry->cid = cmd->cid;
  17100. + __entry->iid = cmd->iid;
  17101. + __entry->len = len;
  17102. + ),
  17103. +
  17104. + TP_printk("rqid=%#06x, tc=%s, cid=%#04x, iid=%#04x, len=%u",
  17105. + __entry->rqid,
  17106. + ssam_show_ssh_tc(__entry->tc),
  17107. + __entry->cid,
  17108. + __entry->iid,
  17109. + __entry->len
  17110. + )
  17111. +);
  17112. +
  17113. +#define DEFINE_SSAM_COMMAND_EVENT(name) \
  17114. + DEFINE_EVENT(ssam_command_class, ssam_##name, \
  17115. + TP_PROTO(const struct ssh_command *cmd, u16 len), \
  17116. + TP_ARGS(cmd, len) \
  17117. + )
  17118. +
  17119. +DECLARE_EVENT_CLASS(ssam_packet_class,
  17120. + TP_PROTO(const struct ssh_packet *packet),
  17121. +
  17122. + TP_ARGS(packet),
  17123. +
  17124. + TP_STRUCT__entry(
  17125. + __field(unsigned long, state)
  17126. + __array(char, uid, SSAM_PTR_UID_LEN)
  17127. + __field(u8, priority)
  17128. + __field(u16, length)
  17129. + __field(u16, seq)
  17130. + ),
  17131. +
  17132. + TP_fast_assign(
  17133. + __entry->state = READ_ONCE(packet->state);
  17134. + ssam_trace_ptr_uid(packet, __entry->uid);
  17135. + __entry->priority = READ_ONCE(packet->priority);
  17136. + __entry->length = packet->data.len;
  17137. + __entry->seq = ssam_trace_get_packet_seq(packet);
  17138. + ),
  17139. +
  17140. + TP_printk("uid=%s, seq=%s, ty=%s, pri=%#04x, len=%u, sta=%s",
  17141. + __entry->uid,
  17142. + ssam_show_packet_seq(__entry->seq),
  17143. + ssam_show_packet_type(__entry->state),
  17144. + __entry->priority,
  17145. + __entry->length,
  17146. + ssam_show_packet_state(__entry->state)
  17147. + )
  17148. +);
  17149. +
  17150. +#define DEFINE_SSAM_PACKET_EVENT(name) \
  17151. + DEFINE_EVENT(ssam_packet_class, ssam_##name, \
  17152. + TP_PROTO(const struct ssh_packet *packet), \
  17153. + TP_ARGS(packet) \
  17154. + )
  17155. +
  17156. +DECLARE_EVENT_CLASS(ssam_packet_status_class,
  17157. + TP_PROTO(const struct ssh_packet *packet, int status),
  17158. +
  17159. + TP_ARGS(packet, status),
  17160. +
  17161. + TP_STRUCT__entry(
  17162. + __field(unsigned long, state)
  17163. + __field(int, status)
  17164. + __array(char, uid, SSAM_PTR_UID_LEN)
  17165. + __field(u8, priority)
  17166. + __field(u16, length)
  17167. + __field(u16, seq)
  17168. + ),
  17169. +
  17170. + TP_fast_assign(
  17171. + __entry->state = READ_ONCE(packet->state);
  17172. + __entry->status = status;
  17173. + ssam_trace_ptr_uid(packet, __entry->uid);
  17174. + __entry->priority = READ_ONCE(packet->priority);
  17175. + __entry->length = packet->data.len;
  17176. + __entry->seq = ssam_trace_get_packet_seq(packet);
  17177. + ),
  17178. +
  17179. + TP_printk("uid=%s, seq=%s, ty=%s, pri=%#04x, len=%u, sta=%s, status=%d",
  17180. + __entry->uid,
  17181. + ssam_show_packet_seq(__entry->seq),
  17182. + ssam_show_packet_type(__entry->state),
  17183. + __entry->priority,
  17184. + __entry->length,
  17185. + ssam_show_packet_state(__entry->state),
  17186. + __entry->status
  17187. + )
  17188. +);
  17189. +
  17190. +#define DEFINE_SSAM_PACKET_STATUS_EVENT(name) \
  17191. + DEFINE_EVENT(ssam_packet_status_class, ssam_##name, \
  17192. + TP_PROTO(const struct ssh_packet *packet, int status), \
  17193. + TP_ARGS(packet, status) \
  17194. + )
  17195. +
  17196. +DECLARE_EVENT_CLASS(ssam_request_class,
  17197. + TP_PROTO(const struct ssh_request *request),
  17198. +
  17199. + TP_ARGS(request),
  17200. +
  17201. + TP_STRUCT__entry(
  17202. + __field(unsigned long, state)
  17203. + __field(u32, rqid)
  17204. + __array(char, uid, SSAM_PTR_UID_LEN)
  17205. + __field(u8, tc)
  17206. + __field(u16, cid)
  17207. + __field(u16, iid)
  17208. + ),
  17209. +
  17210. + TP_fast_assign(
  17211. + const struct ssh_packet *p = &request->packet;
  17212. +
  17213. + /* Use packet for UID so we can match requests to packets. */
  17214. + __entry->state = READ_ONCE(request->state);
  17215. + __entry->rqid = ssam_trace_get_request_id(p);
  17216. + ssam_trace_ptr_uid(p, __entry->uid);
  17217. + __entry->tc = ssam_trace_get_request_tc(p);
  17218. + __entry->cid = ssam_trace_get_command_field_u8(p, cid);
  17219. + __entry->iid = ssam_trace_get_command_field_u8(p, iid);
  17220. + ),
  17221. +
  17222. + TP_printk("uid=%s, rqid=%s, ty=%s, sta=%s, tc=%s, cid=%s, iid=%s",
  17223. + __entry->uid,
  17224. + ssam_show_request_id(__entry->rqid),
  17225. + ssam_show_request_type(__entry->state),
  17226. + ssam_show_request_state(__entry->state),
  17227. + ssam_show_ssh_tc(__entry->tc),
  17228. + ssam_show_generic_u8_field(__entry->cid),
  17229. + ssam_show_generic_u8_field(__entry->iid)
  17230. + )
  17231. +);
  17232. +
  17233. +#define DEFINE_SSAM_REQUEST_EVENT(name) \
  17234. + DEFINE_EVENT(ssam_request_class, ssam_##name, \
  17235. + TP_PROTO(const struct ssh_request *request), \
  17236. + TP_ARGS(request) \
  17237. + )
  17238. +
  17239. +DECLARE_EVENT_CLASS(ssam_request_status_class,
  17240. + TP_PROTO(const struct ssh_request *request, int status),
  17241. +
  17242. + TP_ARGS(request, status),
  17243. +
  17244. + TP_STRUCT__entry(
  17245. + __field(unsigned long, state)
  17246. + __field(u32, rqid)
  17247. + __field(int, status)
  17248. + __array(char, uid, SSAM_PTR_UID_LEN)
  17249. + __field(u8, tc)
  17250. + __field(u16, cid)
  17251. + __field(u16, iid)
  17252. + ),
  17253. +
  17254. + TP_fast_assign(
  17255. + const struct ssh_packet *p = &request->packet;
  17256. +
  17257. + /* Use packet for UID so we can match requests to packets. */
  17258. + __entry->state = READ_ONCE(request->state);
  17259. + __entry->rqid = ssam_trace_get_request_id(p);
  17260. + __entry->status = status;
  17261. + ssam_trace_ptr_uid(p, __entry->uid);
  17262. + __entry->tc = ssam_trace_get_request_tc(p);
  17263. + __entry->cid = ssam_trace_get_command_field_u8(p, cid);
  17264. + __entry->iid = ssam_trace_get_command_field_u8(p, iid);
  17265. + ),
  17266. +
  17267. + TP_printk("uid=%s, rqid=%s, ty=%s, sta=%s, tc=%s, cid=%s, iid=%s, status=%d",
  17268. + __entry->uid,
  17269. + ssam_show_request_id(__entry->rqid),
  17270. + ssam_show_request_type(__entry->state),
  17271. + ssam_show_request_state(__entry->state),
  17272. + ssam_show_ssh_tc(__entry->tc),
  17273. + ssam_show_generic_u8_field(__entry->cid),
  17274. + ssam_show_generic_u8_field(__entry->iid),
  17275. + __entry->status
  17276. + )
  17277. +);
  17278. +
  17279. +#define DEFINE_SSAM_REQUEST_STATUS_EVENT(name) \
  17280. + DEFINE_EVENT(ssam_request_status_class, ssam_##name, \
  17281. + TP_PROTO(const struct ssh_request *request, int status),\
  17282. + TP_ARGS(request, status) \
  17283. + )
  17284. +
  17285. +DECLARE_EVENT_CLASS(ssam_alloc_class,
  17286. + TP_PROTO(void *ptr, size_t len),
  17287. +
  17288. + TP_ARGS(ptr, len),
  17289. +
  17290. + TP_STRUCT__entry(
  17291. + __field(size_t, len)
  17292. + __array(char, uid, SSAM_PTR_UID_LEN)
  17293. + ),
  17294. +
  17295. + TP_fast_assign(
  17296. + __entry->len = len;
  17297. + ssam_trace_ptr_uid(ptr, __entry->uid);
  17298. + ),
  17299. +
  17300. + TP_printk("uid=%s, len=%zu", __entry->uid, __entry->len)
  17301. +);
  17302. +
  17303. +#define DEFINE_SSAM_ALLOC_EVENT(name) \
  17304. + DEFINE_EVENT(ssam_alloc_class, ssam_##name, \
  17305. + TP_PROTO(void *ptr, size_t len), \
  17306. + TP_ARGS(ptr, len) \
  17307. + )
  17308. +
  17309. +DECLARE_EVENT_CLASS(ssam_free_class,
  17310. + TP_PROTO(void *ptr),
  17311. +
  17312. + TP_ARGS(ptr),
  17313. +
  17314. + TP_STRUCT__entry(
  17315. + __array(char, uid, SSAM_PTR_UID_LEN)
  17316. + ),
  17317. +
  17318. + TP_fast_assign(
  17319. + ssam_trace_ptr_uid(ptr, __entry->uid);
  17320. + ),
  17321. +
  17322. + TP_printk("uid=%s", __entry->uid)
  17323. +);
  17324. +
  17325. +#define DEFINE_SSAM_FREE_EVENT(name) \
  17326. + DEFINE_EVENT(ssam_free_class, ssam_##name, \
  17327. + TP_PROTO(void *ptr), \
  17328. + TP_ARGS(ptr) \
  17329. + )
  17330. +
  17331. +DECLARE_EVENT_CLASS(ssam_pending_class,
  17332. + TP_PROTO(unsigned int pending),
  17333. +
  17334. + TP_ARGS(pending),
  17335. +
  17336. + TP_STRUCT__entry(
  17337. + __field(unsigned int, pending)
  17338. + ),
  17339. +
  17340. + TP_fast_assign(
  17341. + __entry->pending = pending;
  17342. + ),
  17343. +
  17344. + TP_printk("pending=%u", __entry->pending)
  17345. +);
  17346. +
  17347. +#define DEFINE_SSAM_PENDING_EVENT(name) \
  17348. + DEFINE_EVENT(ssam_pending_class, ssam_##name, \
  17349. + TP_PROTO(unsigned int pending), \
  17350. + TP_ARGS(pending) \
  17351. + )
  17352. +
  17353. +DECLARE_EVENT_CLASS(ssam_data_class,
  17354. + TP_PROTO(size_t length),
  17355. +
  17356. + TP_ARGS(length),
  17357. +
  17358. + TP_STRUCT__entry(
  17359. + __field(size_t, length)
  17360. + ),
  17361. +
  17362. + TP_fast_assign(
  17363. + __entry->length = length;
  17364. + ),
  17365. +
  17366. + TP_printk("length=%zu", __entry->length)
  17367. +);
  17368. +
  17369. +#define DEFINE_SSAM_DATA_EVENT(name) \
  17370. + DEFINE_EVENT(ssam_data_class, ssam_##name, \
  17371. + TP_PROTO(size_t length), \
  17372. + TP_ARGS(length) \
  17373. + )
  17374. +
  17375. +DEFINE_SSAM_FRAME_EVENT(rx_frame_received);
  17376. +DEFINE_SSAM_COMMAND_EVENT(rx_response_received);
  17377. +DEFINE_SSAM_COMMAND_EVENT(rx_event_received);
  17378. +
  17379. +DEFINE_SSAM_PACKET_EVENT(packet_release);
  17380. +DEFINE_SSAM_PACKET_EVENT(packet_submit);
  17381. +DEFINE_SSAM_PACKET_EVENT(packet_resubmit);
  17382. +DEFINE_SSAM_PACKET_EVENT(packet_timeout);
  17383. +DEFINE_SSAM_PACKET_EVENT(packet_cancel);
  17384. +DEFINE_SSAM_PACKET_STATUS_EVENT(packet_complete);
  17385. +DEFINE_SSAM_PENDING_EVENT(ptl_timeout_reap);
  17386. +
  17387. +DEFINE_SSAM_REQUEST_EVENT(request_submit);
  17388. +DEFINE_SSAM_REQUEST_EVENT(request_timeout);
  17389. +DEFINE_SSAM_REQUEST_EVENT(request_cancel);
  17390. +DEFINE_SSAM_REQUEST_STATUS_EVENT(request_complete);
  17391. +DEFINE_SSAM_PENDING_EVENT(rtl_timeout_reap);
  17392. +
  17393. +DEFINE_SSAM_PACKET_EVENT(ei_tx_drop_ack_packet);
  17394. +DEFINE_SSAM_PACKET_EVENT(ei_tx_drop_nak_packet);
  17395. +DEFINE_SSAM_PACKET_EVENT(ei_tx_drop_dsq_packet);
  17396. +DEFINE_SSAM_PACKET_STATUS_EVENT(ei_tx_fail_write);
  17397. +DEFINE_SSAM_PACKET_EVENT(ei_tx_corrupt_data);
  17398. +DEFINE_SSAM_DATA_EVENT(ei_rx_corrupt_syn);
  17399. +DEFINE_SSAM_FRAME_EVENT(ei_rx_corrupt_data);
  17400. +DEFINE_SSAM_REQUEST_EVENT(ei_rx_drop_response);
  17401. +
  17402. +DEFINE_SSAM_ALLOC_EVENT(ctrl_packet_alloc);
  17403. +DEFINE_SSAM_FREE_EVENT(ctrl_packet_free);
  17404. +
  17405. +DEFINE_SSAM_ALLOC_EVENT(event_item_alloc);
  17406. +DEFINE_SSAM_FREE_EVENT(event_item_free);
  17407. +
  17408. +#endif /* _SURFACE_AGGREGATOR_TRACE_H */
  17409. +
  17410. +/* This part must be outside protection */
  17411. +#undef TRACE_INCLUDE_PATH
  17412. +#undef TRACE_INCLUDE_FILE
  17413. +
  17414. +#define TRACE_INCLUDE_PATH .
  17415. +#define TRACE_INCLUDE_FILE trace
  17416. +
  17417. +#include <trace/define_trace.h>
  17418. diff --git a/include/linux/mod_devicetable.h b/include/linux/mod_devicetable.h
  17419. index ef64063fac30..0b8f1feefe0e 100644
  17420. --- a/include/linux/mod_devicetable.h
  17421. +++ b/include/linux/mod_devicetable.h
  17422. @@ -840,15 +840,16 @@ struct mhi_device_id {
  17423. /* Surface System Aggregator Module */
  17424. -#define SSAM_MATCH_CHANNEL 0x1
  17425. +#define SSAM_MATCH_TARGET 0x1
  17426. #define SSAM_MATCH_INSTANCE 0x2
  17427. #define SSAM_MATCH_FUNCTION 0x4
  17428. struct ssam_device_id {
  17429. __u8 match_flags;
  17430. + __u8 domain;
  17431. __u8 category;
  17432. - __u8 channel;
  17433. + __u8 target;
  17434. __u8 instance;
  17435. __u8 function;
  17436. diff --git a/include/linux/surface_acpi_notify.h b/include/linux/surface_acpi_notify.h
  17437. new file mode 100644
  17438. index 000000000000..8e3e86c7d78c
  17439. --- /dev/null
  17440. +++ b/include/linux/surface_acpi_notify.h
  17441. @@ -0,0 +1,39 @@
  17442. +/* SPDX-License-Identifier: GPL-2.0+ */
  17443. +/*
  17444. + * Interface for Surface ACPI Notify (SAN) driver.
  17445. + *
  17446. + * Provides access to discrete GPU notifications sent from ACPI via the SAN
  17447. + * driver, which are not handled by this driver directly.
  17448. + *
  17449. + * Copyright (C) 2019-2020 Maximilian Luz <luzmaximilian@gmail.com>
  17450. + */
  17451. +
  17452. +#ifndef _LINUX_SURFACE_ACPI_NOTIFY_H
  17453. +#define _LINUX_SURFACE_ACPI_NOTIFY_H
  17454. +
  17455. +#include <linux/notifier.h>
  17456. +#include <linux/types.h>
  17457. +
  17458. +/**
  17459. + * struct san_dgpu_event - Discrete GPU ACPI event.
  17460. + * @category: Category of the event.
  17461. + * @target: Target ID of the event source.
  17462. + * @command: Command ID of the event.
  17463. + * @instance: Instance ID of the event source.
  17464. + * @length: Length of the event's payload data (in bytes).
  17465. + * @payload: Pointer to the event's payload data.
  17466. + */
  17467. +struct san_dgpu_event {
  17468. + u8 category;
  17469. + u8 target;
  17470. + u8 command;
  17471. + u8 instance;
  17472. + u16 length;
  17473. + u8 *payload;
  17474. +};
  17475. +
  17476. +int san_client_link(struct device *client);
  17477. +int san_dgpu_notifier_register(struct notifier_block *nb);
  17478. +int san_dgpu_notifier_unregister(struct notifier_block *nb);
  17479. +
  17480. +#endif /* _LINUX_SURFACE_ACPI_NOTIFY_H */
  17481. diff --git a/include/linux/surface_aggregator/controller.h b/include/linux/surface_aggregator/controller.h
  17482. new file mode 100644
  17483. index 000000000000..f4b1ba887384
  17484. --- /dev/null
  17485. +++ b/include/linux/surface_aggregator/controller.h
  17486. @@ -0,0 +1,824 @@
  17487. +/* SPDX-License-Identifier: GPL-2.0+ */
  17488. +/*
  17489. + * Surface System Aggregator Module (SSAM) controller interface.
  17490. + *
  17491. + * Main communication interface for the SSAM EC. Provides a controller
  17492. + * managing access and communication to and from the SSAM EC, as well as main
  17493. + * communication structures and definitions.
  17494. + *
  17495. + * Copyright (C) 2019-2020 Maximilian Luz <luzmaximilian@gmail.com>
  17496. + */
  17497. +
  17498. +#ifndef _LINUX_SURFACE_AGGREGATOR_CONTROLLER_H
  17499. +#define _LINUX_SURFACE_AGGREGATOR_CONTROLLER_H
  17500. +
  17501. +#include <linux/completion.h>
  17502. +#include <linux/device.h>
  17503. +#include <linux/types.h>
  17504. +
  17505. +#include <linux/surface_aggregator/serial_hub.h>
  17506. +
  17507. +
  17508. +/* -- Main data types and definitions --------------------------------------- */
  17509. +
  17510. +/**
  17511. + * enum ssam_event_flags - Flags for enabling/disabling SAM events
  17512. + * @SSAM_EVENT_SEQUENCED: The event will be sent via a sequenced data frame.
  17513. + */
  17514. +enum ssam_event_flags {
  17515. + SSAM_EVENT_SEQUENCED = BIT(0),
  17516. +};
  17517. +
  17518. +/**
  17519. + * struct ssam_event - SAM event sent from the EC to the host.
  17520. + * @target_category: Target category of the event source. See &enum ssam_ssh_tc.
  17521. + * @target_id: Target ID of the event source.
  17522. + * @command_id: Command ID of the event.
  17523. + * @instance_id: Instance ID of the event source.
  17524. + * @length: Length of the event payload in bytes.
  17525. + * @data: Event payload data.
  17526. + */
  17527. +struct ssam_event {
  17528. + u8 target_category;
  17529. + u8 target_id;
  17530. + u8 command_id;
  17531. + u8 instance_id;
  17532. + u16 length;
  17533. + u8 data[];
  17534. +};
  17535. +
  17536. +/**
  17537. + * enum ssam_request_flags - Flags for SAM requests.
  17538. + *
  17539. + * @SSAM_REQUEST_HAS_RESPONSE:
  17540. + * Specifies that the request expects a response. If not set, the request
  17541. + * will be directly completed after its underlying packet has been
  17542. + * transmitted. If set, the request transport system waits for a response
  17543. + * of the request.
  17544. + *
  17545. + * @SSAM_REQUEST_UNSEQUENCED:
  17546. + * Specifies that the request should be transmitted via an unsequenced
  17547. + * packet. If set, the request must not have a response, meaning that this
  17548. + * flag and the %SSAM_REQUEST_HAS_RESPONSE flag are mutually exclusive.
  17549. + */
  17550. +enum ssam_request_flags {
  17551. + SSAM_REQUEST_HAS_RESPONSE = BIT(0),
  17552. + SSAM_REQUEST_UNSEQUENCED = BIT(1),
  17553. +};
  17554. +
  17555. +/**
  17556. + * struct ssam_request - SAM request description.
  17557. + * @target_category: Category of the request's target. See &enum ssam_ssh_tc.
  17558. + * @target_id: ID of the request's target.
  17559. + * @command_id: Command ID of the request.
  17560. + * @instance_id: Instance ID of the request's target.
  17561. + * @flags: Flags for the request. See &enum ssam_request_flags.
  17562. + * @length: Length of the request payload in bytes.
  17563. + * @payload: Request payload data.
  17564. + *
  17565. + * This struct fully describes a SAM request with payload. It is intended to
  17566. + * help set up the actual transport struct, e.g. &struct ssam_request_sync,
  17567. + * and specifically its raw message data via ssam_request_write_data().
  17568. + */
  17569. +struct ssam_request {
  17570. + u8 target_category;
  17571. + u8 target_id;
  17572. + u8 command_id;
  17573. + u8 instance_id;
  17574. + u16 flags;
  17575. + u16 length;
  17576. + const u8 *payload;
  17577. +};
  17578. +
  17579. +/**
  17580. + * struct ssam_response - Response buffer for SAM request.
  17581. + * @capacity: Capacity of the buffer, in bytes.
  17582. + * @length: Length of the actual data stored in the memory pointed to by
  17583. + * @pointer, in bytes. Set by the transport system.
  17584. + * @pointer: Pointer to the buffer's memory, storing the response payload data.
  17585. + */
  17586. +struct ssam_response {
  17587. + size_t capacity;
  17588. + size_t length;
  17589. + u8 *pointer;
  17590. +};
  17591. +
  17592. +struct ssam_controller;
  17593. +
  17594. +struct ssam_controller *ssam_get_controller(void);
  17595. +struct ssam_controller *ssam_client_bind(struct device *client);
  17596. +int ssam_client_link(struct ssam_controller *ctrl, struct device *client);
  17597. +
  17598. +struct device *ssam_controller_device(struct ssam_controller *c);
  17599. +
  17600. +struct ssam_controller *ssam_controller_get(struct ssam_controller *c);
  17601. +void ssam_controller_put(struct ssam_controller *c);
  17602. +
  17603. +void ssam_controller_statelock(struct ssam_controller *c);
  17604. +void ssam_controller_stateunlock(struct ssam_controller *c);
  17605. +
  17606. +ssize_t ssam_request_write_data(struct ssam_span *buf,
  17607. + struct ssam_controller *ctrl,
  17608. + const struct ssam_request *spec);
  17609. +
  17610. +
  17611. +/* -- Synchronous request interface. ---------------------------------------- */
  17612. +
  17613. +/**
  17614. + * struct ssam_request_sync - Synchronous SAM request struct.
  17615. + * @base: Underlying SSH request.
  17616. + * @comp: Completion used to signal full completion of the request. After the
  17617. + * request has been submitted, this struct may only be modified or
  17618. + * deallocated after the completion has been signaled.
  17619. + * request has been submitted,
  17620. + * @resp: Buffer to store the response.
  17621. + * @status: Status of the request, set after the base request has been
  17622. + * completed or has failed.
  17623. + */
  17624. +struct ssam_request_sync {
  17625. + struct ssh_request base;
  17626. + struct completion comp;
  17627. + struct ssam_response *resp;
  17628. + int status;
  17629. +};
  17630. +
  17631. +int ssam_request_sync_alloc(size_t payload_len, gfp_t flags,
  17632. + struct ssam_request_sync **rqst,
  17633. + struct ssam_span *buffer);
  17634. +
  17635. +void ssam_request_sync_free(struct ssam_request_sync *rqst);
  17636. +
  17637. +int ssam_request_sync_init(struct ssam_request_sync *rqst,
  17638. + enum ssam_request_flags flags);
  17639. +
  17640. +/**
  17641. + * ssam_request_sync_set_data - Set message data of a synchronous request.
  17642. + * @rqst: The request.
  17643. + * @ptr: Pointer to the request message data.
  17644. + * @len: Length of the request message data.
  17645. + *
  17646. + * Set the request message data of a synchronous request. The provided buffer
  17647. + * needs to live until the request has been completed.
  17648. + */
  17649. +static inline void ssam_request_sync_set_data(struct ssam_request_sync *rqst,
  17650. + u8 *ptr, size_t len)
  17651. +{
  17652. + ssh_request_set_data(&rqst->base, ptr, len);
  17653. +}
  17654. +
  17655. +/**
  17656. + * ssam_request_sync_set_resp - Set response buffer of a synchronous request.
  17657. + * @rqst: The request.
  17658. + * @resp: The response buffer.
  17659. + *
  17660. + * Sets the response buffer of a synchronous request. This buffer will store
  17661. + * the response of the request after it has been completed. May be %NULL if no
  17662. + * response is expected.
  17663. + */
  17664. +static inline void ssam_request_sync_set_resp(struct ssam_request_sync *rqst,
  17665. + struct ssam_response *resp)
  17666. +{
  17667. + rqst->resp = resp;
  17668. +}
  17669. +
  17670. +int ssam_request_sync_submit(struct ssam_controller *ctrl,
  17671. + struct ssam_request_sync *rqst);
  17672. +
  17673. +/**
  17674. + * ssam_request_sync_wait - Wait for completion of a synchronous request.
  17675. + * @rqst: The request to wait for.
  17676. + *
  17677. + * Wait for completion and release of a synchronous request. After this
  17678. + * function terminates, the request is guaranteed to have left the transport
  17679. + * system. After successful submission of a request, this function must be
  17680. + * called before accessing the response of the request, freeing the request,
  17681. + * or freeing any of the buffers associated with the request.
  17682. + *
  17683. + * This function must not be called if the request has not been submitted yet
  17684. + * and may lead to a deadlock/infinite wait if a subsequent request submission
  17685. + * fails in that case, due to the completion never triggering.
  17686. + *
  17687. + * Return: Returns the status of the given request, which is set on completion
  17688. + * of the packet. This value is zero on success and negative on failure.
  17689. + */
  17690. +static inline int ssam_request_sync_wait(struct ssam_request_sync *rqst)
  17691. +{
  17692. + wait_for_completion(&rqst->comp);
  17693. + return rqst->status;
  17694. +}
  17695. +
  17696. +int ssam_request_sync(struct ssam_controller *ctrl,
  17697. + const struct ssam_request *spec,
  17698. + struct ssam_response *rsp);
  17699. +
  17700. +int ssam_request_sync_with_buffer(struct ssam_controller *ctrl,
  17701. + const struct ssam_request *spec,
  17702. + struct ssam_response *rsp,
  17703. + struct ssam_span *buf);
  17704. +
  17705. +/**
  17706. + * ssam_request_sync_onstack - Execute a synchronous request on the stack.
  17707. + * @ctrl: The controller via which the request is submitted.
  17708. + * @rqst: The request specification.
  17709. + * @rsp: The response buffer.
  17710. + * @payload_len: The (maximum) request payload length.
  17711. + *
  17712. + * Allocates a synchronous request with specified payload length on the stack,
  17713. + * fully initializes it via the provided request specification, submits it,
  17714. + * and finally waits for its completion before returning its status. This
  17715. + * helper macro essentially allocates the request message buffer on the stack
  17716. + * and then calls ssam_request_sync_with_buffer().
  17717. + *
  17718. + * Note: The @payload_len parameter specifies the maximum payload length, used
  17719. + * for buffer allocation. The actual payload length may be smaller.
  17720. + *
  17721. + * Return: Returns the status of the request or any failure during setup, i.e.
  17722. + * zero on success and a negative value on failure.
  17723. + */
  17724. +#define ssam_request_sync_onstack(ctrl, rqst, rsp, payload_len) \
  17725. + ({ \
  17726. + u8 __data[SSH_COMMAND_MESSAGE_LENGTH(payload_len)]; \
  17727. + struct ssam_span __buf = { &__data[0], ARRAY_SIZE(__data) }; \
  17728. + \
  17729. + ssam_request_sync_with_buffer(ctrl, rqst, rsp, &__buf); \
  17730. + })
  17731. +
  17732. +/**
  17733. + * __ssam_retry - Retry request in case of I/O errors or timeouts.
  17734. + * @request: The request function to execute. Must return an integer.
  17735. + * @n: Number of tries.
  17736. + * @args: Arguments for the request function.
  17737. + *
  17738. + * Executes the given request function, i.e. calls @request. In case the
  17739. + * request returns %-EREMOTEIO (indicates I/O error) or %-ETIMEDOUT (request
  17740. + * or underlying packet timed out), @request will be re-executed again, up to
  17741. + * @n times in total.
  17742. + *
  17743. + * Return: Returns the return value of the last execution of @request.
  17744. + */
  17745. +#define __ssam_retry(request, n, args...) \
  17746. + ({ \
  17747. + int __i, __s = 0; \
  17748. + \
  17749. + for (__i = (n); __i > 0; __i--) { \
  17750. + __s = request(args); \
  17751. + if (__s != -ETIMEDOUT && __s != -EREMOTEIO) \
  17752. + break; \
  17753. + } \
  17754. + __s; \
  17755. + })
  17756. +
  17757. +/**
  17758. + * ssam_retry - Retry request in case of I/O errors or timeouts up to three
  17759. + * times in total.
  17760. + * @request: The request function to execute. Must return an integer.
  17761. + * @args: Arguments for the request function.
  17762. + *
  17763. + * Executes the given request function, i.e. calls @request. In case the
  17764. + * request returns %-EREMOTEIO (indicates I/O error) or -%ETIMEDOUT (request
  17765. + * or underlying packet timed out), @request will be re-executed again, up to
  17766. + * three times in total.
  17767. + *
  17768. + * See __ssam_retry() for a more generic macro for this purpose.
  17769. + *
  17770. + * Return: Returns the return value of the last execution of @request.
  17771. + */
  17772. +#define ssam_retry(request, args...) \
  17773. + __ssam_retry(request, 3, args)
  17774. +
  17775. +/**
  17776. + * struct ssam_request_spec - Blue-print specification of SAM request.
  17777. + * @target_category: Category of the request's target. See &enum ssam_ssh_tc.
  17778. + * @target_id: ID of the request's target.
  17779. + * @command_id: Command ID of the request.
  17780. + * @instance_id: Instance ID of the request's target.
  17781. + * @flags: Flags for the request. See &enum ssam_request_flags.
  17782. + *
  17783. + * Blue-print specification for a SAM request. This struct describes the
  17784. + * unique static parameters of a request (i.e. type) without specifying any of
  17785. + * its instance-specific data (e.g. payload). It is intended to be used as base
  17786. + * for defining simple request functions via the
  17787. + * ``SSAM_DEFINE_SYNC_REQUEST_x()`` family of macros.
  17788. + */
  17789. +struct ssam_request_spec {
  17790. + u8 target_category;
  17791. + u8 target_id;
  17792. + u8 command_id;
  17793. + u8 instance_id;
  17794. + u8 flags;
  17795. +};
  17796. +
  17797. +/**
  17798. + * struct ssam_request_spec_md - Blue-print specification for multi-device SAM
  17799. + * request.
  17800. + * @target_category: Category of the request's target. See &enum ssam_ssh_tc.
  17801. + * @command_id: Command ID of the request.
  17802. + * @flags: Flags for the request. See &enum ssam_request_flags.
  17803. + *
  17804. + * Blue-print specification for a multi-device SAM request, i.e. a request
  17805. + * that is applicable to multiple device instances, described by their
  17806. + * individual target and instance IDs. This struct describes the unique static
  17807. + * parameters of a request (i.e. type) without specifying any of its
  17808. + * instance-specific data (e.g. payload) and without specifying any of its
  17809. + * device specific IDs (i.e. target and instance ID). It is intended to be
  17810. + * used as base for defining simple multi-device request functions via the
  17811. + * ``SSAM_DEFINE_SYNC_REQUEST_MD_x()`` and ``SSAM_DEFINE_SYNC_REQUEST_CL_x()``
  17812. + * families of macros.
  17813. + */
  17814. +struct ssam_request_spec_md {
  17815. + u8 target_category;
  17816. + u8 command_id;
  17817. + u8 flags;
  17818. +};
  17819. +
  17820. +/**
  17821. + * SSAM_DEFINE_SYNC_REQUEST_N() - Define synchronous SAM request function
  17822. + * with neither argument nor return value.
  17823. + * @name: Name of the generated function.
  17824. + * @spec: Specification (&struct ssam_request_spec) defining the request.
  17825. + *
  17826. + * Defines a function executing the synchronous SAM request specified by
  17827. + * @spec, with the request having neither argument nor return value. The
  17828. + * generated function takes care of setting up the request struct and buffer
  17829. + * allocation, as well as execution of the request itself, returning once the
  17830. + * request has been fully completed. The required transport buffer will be
  17831. + * allocated on the stack.
  17832. + *
  17833. + * The generated function is defined as ``int name(struct ssam_controller
  17834. + * *ctrl)``, returning the status of the request, which is zero on success and
  17835. + * negative on failure. The ``ctrl`` parameter is the controller via which the
  17836. + * request is being sent.
  17837. + *
  17838. + * Refer to ssam_request_sync_onstack() for more details on the behavior of
  17839. + * the generated function.
  17840. + */
  17841. +#define SSAM_DEFINE_SYNC_REQUEST_N(name, spec...) \
  17842. + int name(struct ssam_controller *ctrl) \
  17843. + { \
  17844. + struct ssam_request_spec s = (struct ssam_request_spec)spec; \
  17845. + struct ssam_request rqst; \
  17846. + \
  17847. + rqst.target_category = s.target_category; \
  17848. + rqst.target_id = s.target_id; \
  17849. + rqst.command_id = s.command_id; \
  17850. + rqst.instance_id = s.instance_id; \
  17851. + rqst.flags = s.flags; \
  17852. + rqst.length = 0; \
  17853. + rqst.payload = NULL; \
  17854. + \
  17855. + return ssam_request_sync_onstack(ctrl, &rqst, NULL, 0); \
  17856. + }
  17857. +
  17858. +/**
  17859. + * SSAM_DEFINE_SYNC_REQUEST_W() - Define synchronous SAM request function with
  17860. + * argument.
  17861. + * @name: Name of the generated function.
  17862. + * @atype: Type of the request's argument.
  17863. + * @spec: Specification (&struct ssam_request_spec) defining the request.
  17864. + *
  17865. + * Defines a function executing the synchronous SAM request specified by
  17866. + * @spec, with the request taking an argument of type @atype and having no
  17867. + * return value. The generated function takes care of setting up the request
  17868. + * struct, buffer allocation, as well as execution of the request itself,
  17869. + * returning once the request has been fully completed. The required transport
  17870. + * buffer will be allocated on the stack.
  17871. + *
  17872. + * The generated function is defined as ``int name(struct ssam_controller
  17873. + * *ctrl, const atype *arg)``, returning the status of the request, which is
  17874. + * zero on success and negative on failure. The ``ctrl`` parameter is the
  17875. + * controller via which the request is sent. The request argument is specified
  17876. + * via the ``arg`` pointer.
  17877. + *
  17878. + * Refer to ssam_request_sync_onstack() for more details on the behavior of
  17879. + * the generated function.
  17880. + */
  17881. +#define SSAM_DEFINE_SYNC_REQUEST_W(name, atype, spec...) \
  17882. + int name(struct ssam_controller *ctrl, const atype *arg) \
  17883. + { \
  17884. + struct ssam_request_spec s = (struct ssam_request_spec)spec; \
  17885. + struct ssam_request rqst; \
  17886. + \
  17887. + rqst.target_category = s.target_category; \
  17888. + rqst.target_id = s.target_id; \
  17889. + rqst.command_id = s.command_id; \
  17890. + rqst.instance_id = s.instance_id; \
  17891. + rqst.flags = s.flags; \
  17892. + rqst.length = sizeof(atype); \
  17893. + rqst.payload = (u8 *)arg; \
  17894. + \
  17895. + return ssam_request_sync_onstack(ctrl, &rqst, NULL, \
  17896. + sizeof(atype)); \
  17897. + }
  17898. +
  17899. +/**
  17900. + * SSAM_DEFINE_SYNC_REQUEST_R() - Define synchronous SAM request function with
  17901. + * return value.
  17902. + * @name: Name of the generated function.
  17903. + * @rtype: Type of the request's return value.
  17904. + * @spec: Specification (&struct ssam_request_spec) defining the request.
  17905. + *
  17906. + * Defines a function executing the synchronous SAM request specified by
  17907. + * @spec, with the request taking no argument but having a return value of
  17908. + * type @rtype. The generated function takes care of setting up the request
  17909. + * and response structs, buffer allocation, as well as execution of the
  17910. + * request itself, returning once the request has been fully completed. The
  17911. + * required transport buffer will be allocated on the stack.
  17912. + *
  17913. + * The generated function is defined as ``int name(struct ssam_controller
  17914. + * *ctrl, rtype *ret)``, returning the status of the request, which is zero on
  17915. + * success and negative on failure. The ``ctrl`` parameter is the controller
  17916. + * via which the request is sent. The request's return value is written to the
  17917. + * memory pointed to by the ``ret`` parameter.
  17918. + *
  17919. + * Refer to ssam_request_sync_onstack() for more details on the behavior of
  17920. + * the generated function.
  17921. + */
  17922. +#define SSAM_DEFINE_SYNC_REQUEST_R(name, rtype, spec...) \
  17923. + int name(struct ssam_controller *ctrl, rtype *ret) \
  17924. + { \
  17925. + struct ssam_request_spec s = (struct ssam_request_spec)spec; \
  17926. + struct ssam_request rqst; \
  17927. + struct ssam_response rsp; \
  17928. + int status; \
  17929. + \
  17930. + rqst.target_category = s.target_category; \
  17931. + rqst.target_id = s.target_id; \
  17932. + rqst.command_id = s.command_id; \
  17933. + rqst.instance_id = s.instance_id; \
  17934. + rqst.flags = s.flags | SSAM_REQUEST_HAS_RESPONSE; \
  17935. + rqst.length = 0; \
  17936. + rqst.payload = NULL; \
  17937. + \
  17938. + rsp.capacity = sizeof(rtype); \
  17939. + rsp.length = 0; \
  17940. + rsp.pointer = (u8 *)ret; \
  17941. + \
  17942. + status = ssam_request_sync_onstack(ctrl, &rqst, &rsp, 0); \
  17943. + if (status) \
  17944. + return status; \
  17945. + \
  17946. + if (rsp.length != sizeof(rtype)) { \
  17947. + struct device *dev = ssam_controller_device(ctrl); \
  17948. + dev_err(dev, \
  17949. + "rqst: invalid response length, expected %zu, got %zu (tc: %#04x, cid: %#04x)", \
  17950. + sizeof(rtype), rsp.length, rqst.target_category,\
  17951. + rqst.command_id); \
  17952. + return -EIO; \
  17953. + } \
  17954. + \
  17955. + return 0; \
  17956. + }
  17957. +
  17958. +/**
  17959. + * SSAM_DEFINE_SYNC_REQUEST_MD_N() - Define synchronous multi-device SAM
  17960. + * request function with neither argument nor return value.
  17961. + * @name: Name of the generated function.
  17962. + * @spec: Specification (&struct ssam_request_spec_md) defining the request.
  17963. + *
  17964. + * Defines a function executing the synchronous SAM request specified by
  17965. + * @spec, with the request having neither argument nor return value. Device
  17966. + * specifying parameters are not hard-coded, but instead must be provided to
  17967. + * the function. The generated function takes care of setting up the request
  17968. + * struct, buffer allocation, as well as execution of the request itself,
  17969. + * returning once the request has been fully completed. The required transport
  17970. + * buffer will be allocated on the stack.
  17971. + *
  17972. + * The generated function is defined as ``int name(struct ssam_controller
  17973. + * *ctrl, u8 tid, u8 iid)``, returning the status of the request, which is
  17974. + * zero on success and negative on failure. The ``ctrl`` parameter is the
  17975. + * controller via which the request is sent, ``tid`` the target ID for the
  17976. + * request, and ``iid`` the instance ID.
  17977. + *
  17978. + * Refer to ssam_request_sync_onstack() for more details on the behavior of
  17979. + * the generated function.
  17980. + */
  17981. +#define SSAM_DEFINE_SYNC_REQUEST_MD_N(name, spec...) \
  17982. + int name(struct ssam_controller *ctrl, u8 tid, u8 iid) \
  17983. + { \
  17984. + struct ssam_request_spec_md s = (struct ssam_request_spec_md)spec; \
  17985. + struct ssam_request rqst; \
  17986. + \
  17987. + rqst.target_category = s.target_category; \
  17988. + rqst.target_id = tid; \
  17989. + rqst.command_id = s.command_id; \
  17990. + rqst.instance_id = iid; \
  17991. + rqst.flags = s.flags; \
  17992. + rqst.length = 0; \
  17993. + rqst.payload = NULL; \
  17994. + \
  17995. + return ssam_request_sync_onstack(ctrl, &rqst, NULL, 0); \
  17996. + }
  17997. +
  17998. +/**
  17999. + * SSAM_DEFINE_SYNC_REQUEST_MD_W() - Define synchronous multi-device SAM
  18000. + * request function with argument.
  18001. + * @name: Name of the generated function.
  18002. + * @atype: Type of the request's argument.
  18003. + * @spec: Specification (&struct ssam_request_spec_md) defining the request.
  18004. + *
  18005. + * Defines a function executing the synchronous SAM request specified by
  18006. + * @spec, with the request taking an argument of type @atype and having no
  18007. + * return value. Device specifying parameters are not hard-coded, but instead
  18008. + * must be provided to the function. The generated function takes care of
  18009. + * setting up the request struct, buffer allocation, as well as execution of
  18010. + * the request itself, returning once the request has been fully completed.
  18011. + * The required transport buffer will be allocated on the stack.
  18012. + *
  18013. + * The generated function is defined as ``int name(struct ssam_controller
  18014. + * *ctrl, u8 tid, u8 iid, const atype *arg)``, returning the status of the
  18015. + * request, which is zero on success and negative on failure. The ``ctrl``
  18016. + * parameter is the controller via which the request is sent, ``tid`` the
  18017. + * target ID for the request, and ``iid`` the instance ID. The request argument
  18018. + * is specified via the ``arg`` pointer.
  18019. + *
  18020. + * Refer to ssam_request_sync_onstack() for more details on the behavior of
  18021. + * the generated function.
  18022. + */
  18023. +#define SSAM_DEFINE_SYNC_REQUEST_MD_W(name, atype, spec...) \
  18024. + int name(struct ssam_controller *ctrl, u8 tid, u8 iid, const atype *arg)\
  18025. + { \
  18026. + struct ssam_request_spec_md s = (struct ssam_request_spec_md)spec; \
  18027. + struct ssam_request rqst; \
  18028. + \
  18029. + rqst.target_category = s.target_category; \
  18030. + rqst.target_id = tid; \
  18031. + rqst.command_id = s.command_id; \
  18032. + rqst.instance_id = iid; \
  18033. + rqst.flags = s.flags; \
  18034. + rqst.length = sizeof(atype); \
  18035. + rqst.payload = (u8 *)arg; \
  18036. + \
  18037. + return ssam_request_sync_onstack(ctrl, &rqst, NULL, \
  18038. + sizeof(atype)); \
  18039. + }
  18040. +
  18041. +/**
  18042. + * SSAM_DEFINE_SYNC_REQUEST_MD_R() - Define synchronous multi-device SAM
  18043. + * request function with return value.
  18044. + * @name: Name of the generated function.
  18045. + * @rtype: Type of the request's return value.
  18046. + * @spec: Specification (&struct ssam_request_spec_md) defining the request.
  18047. + *
  18048. + * Defines a function executing the synchronous SAM request specified by
  18049. + * @spec, with the request taking no argument but having a return value of
  18050. + * type @rtype. Device specifying parameters are not hard-coded, but instead
  18051. + * must be provided to the function. The generated function takes care of
  18052. + * setting up the request and response structs, buffer allocation, as well as
  18053. + * execution of the request itself, returning once the request has been fully
  18054. + * completed. The required transport buffer will be allocated on the stack.
  18055. + *
  18056. + * The generated function is defined as ``int name(struct ssam_controller
  18057. + * *ctrl, u8 tid, u8 iid, rtype *ret)``, returning the status of the request,
  18058. + * which is zero on success and negative on failure. The ``ctrl`` parameter is
  18059. + * the controller via which the request is sent, ``tid`` the target ID for the
  18060. + * request, and ``iid`` the instance ID. The request's return value is written
  18061. + * to the memory pointed to by the ``ret`` parameter.
  18062. + *
  18063. + * Refer to ssam_request_sync_onstack() for more details on the behavior of
  18064. + * the generated function.
  18065. + */
  18066. +#define SSAM_DEFINE_SYNC_REQUEST_MD_R(name, rtype, spec...) \
  18067. + int name(struct ssam_controller *ctrl, u8 tid, u8 iid, rtype *ret) \
  18068. + { \
  18069. + struct ssam_request_spec_md s = (struct ssam_request_spec_md)spec; \
  18070. + struct ssam_request rqst; \
  18071. + struct ssam_response rsp; \
  18072. + int status; \
  18073. + \
  18074. + rqst.target_category = s.target_category; \
  18075. + rqst.target_id = tid; \
  18076. + rqst.command_id = s.command_id; \
  18077. + rqst.instance_id = iid; \
  18078. + rqst.flags = s.flags | SSAM_REQUEST_HAS_RESPONSE; \
  18079. + rqst.length = 0; \
  18080. + rqst.payload = NULL; \
  18081. + \
  18082. + rsp.capacity = sizeof(rtype); \
  18083. + rsp.length = 0; \
  18084. + rsp.pointer = (u8 *)ret; \
  18085. + \
  18086. + status = ssam_request_sync_onstack(ctrl, &rqst, &rsp, 0); \
  18087. + if (status) \
  18088. + return status; \
  18089. + \
  18090. + if (rsp.length != sizeof(rtype)) { \
  18091. + struct device *dev = ssam_controller_device(ctrl); \
  18092. + dev_err(dev, \
  18093. + "rqst: invalid response length, expected %zu, got %zu (tc: %#04x, cid: %#04x)", \
  18094. + sizeof(rtype), rsp.length, rqst.target_category,\
  18095. + rqst.command_id); \
  18096. + return -EIO; \
  18097. + } \
  18098. + \
  18099. + return 0; \
  18100. + }
  18101. +
  18102. +
  18103. +/* -- Event notifier/callbacks. --------------------------------------------- */
  18104. +
  18105. +#define SSAM_NOTIF_STATE_SHIFT 2
  18106. +#define SSAM_NOTIF_STATE_MASK ((1 << SSAM_NOTIF_STATE_SHIFT) - 1)
  18107. +
  18108. +/**
  18109. + * enum ssam_notif_flags - Flags used in return values from SSAM notifier
  18110. + * callback functions.
  18111. + *
  18112. + * @SSAM_NOTIF_HANDLED:
  18113. + * Indicates that the notification has been handled. This flag should be
  18114. + * set by the handler if the handler can act/has acted upon the event
  18115. + * provided to it. This flag should not be set if the handler is not a
  18116. + * primary handler intended for the provided event.
  18117. + *
  18118. + * If this flag has not been set by any handler after the notifier chain
  18119. + * has been traversed, a warning will be emitted, stating that the event
  18120. + * has not been handled.
  18121. + *
  18122. + * @SSAM_NOTIF_STOP:
  18123. + * Indicates that the notifier traversal should stop. If this flag is
  18124. + * returned from a notifier callback, notifier chain traversal will
  18125. + * immediately stop and any remaining notifiers will not be called. This
  18126. + * flag is automatically set when ssam_notifier_from_errno() is called
  18127. + * with a negative error value.
  18128. + */
  18129. +enum ssam_notif_flags {
  18130. + SSAM_NOTIF_HANDLED = BIT(0),
  18131. + SSAM_NOTIF_STOP = BIT(1),
  18132. +};
  18133. +
  18134. +struct ssam_event_notifier;
  18135. +
  18136. +typedef u32 (*ssam_notifier_fn_t)(struct ssam_event_notifier *nf,
  18137. + const struct ssam_event *event);
  18138. +
  18139. +/**
  18140. + * struct ssam_notifier_block - Base notifier block for SSAM event
  18141. + * notifications.
  18142. + * @node: The node for the list of notifiers.
  18143. + * @fn: The callback function of this notifier. This function takes the
  18144. + * respective notifier block and event as input and should return
  18145. + * a notifier value, which can either be obtained from the flags
  18146. + * provided in &enum ssam_notif_flags, converted from a standard
  18147. + * error value via ssam_notifier_from_errno(), or a combination of
  18148. + * both (e.g. ``ssam_notifier_from_errno(e) | SSAM_NOTIF_HANDLED``).
  18149. + * @priority: Priority value determining the order in which notifier callbacks
  18150. + * will be called. A higher value means higher priority, i.e. the
  18151. + * associated callback will be executed earlier than other (lower
  18152. + * priority) callbacks.
  18153. + */
  18154. +struct ssam_notifier_block {
  18155. + struct list_head node;
  18156. + ssam_notifier_fn_t fn;
  18157. + int priority;
  18158. +};
  18159. +
  18160. +/**
  18161. + * ssam_notifier_from_errno() - Convert standard error value to notifier
  18162. + * return code.
  18163. + * @err: The error code to convert, must be negative (in case of failure) or
  18164. + * zero (in case of success).
  18165. + *
  18166. + * Return: Returns the notifier return value obtained by converting the
  18167. + * specified @err value. In case @err is negative, the %SSAM_NOTIF_STOP flag
  18168. + * will be set, causing notifier call chain traversal to abort.
  18169. + */
  18170. +static inline u32 ssam_notifier_from_errno(int err)
  18171. +{
  18172. + if (WARN_ON(err > 0) || err == 0)
  18173. + return 0;
  18174. + else
  18175. + return ((-err) << SSAM_NOTIF_STATE_SHIFT) | SSAM_NOTIF_STOP;
  18176. +}
  18177. +
  18178. +/**
  18179. + * ssam_notifier_to_errno() - Convert notifier return code to standard error
  18180. + * value.
  18181. + * @ret: The notifier return value to convert.
  18182. + *
  18183. + * Return: Returns the negative error value encoded in @ret or zero if @ret
  18184. + * indicates success.
  18185. + */
  18186. +static inline int ssam_notifier_to_errno(u32 ret)
  18187. +{
  18188. + return -(ret >> SSAM_NOTIF_STATE_SHIFT);
  18189. +}
  18190. +
  18191. +
  18192. +/* -- Event/notification registry. ------------------------------------------ */
  18193. +
  18194. +/**
  18195. + * struct ssam_event_registry - Registry specification used for enabling events.
  18196. + * @target_category: Target category for the event registry requests.
  18197. + * @target_id: Target ID for the event registry requests.
  18198. + * @cid_enable: Command ID for the event-enable request.
  18199. + * @cid_disable: Command ID for the event-disable request.
  18200. + *
  18201. + * This struct describes a SAM event registry via the minimal collection of
  18202. + * SAM IDs specifying the requests to use for enabling and disabling an event.
  18203. + * The individual event to be enabled/disabled itself is specified via &struct
  18204. + * ssam_event_id.
  18205. + */
  18206. +struct ssam_event_registry {
  18207. + u8 target_category;
  18208. + u8 target_id;
  18209. + u8 cid_enable;
  18210. + u8 cid_disable;
  18211. +};
  18212. +
  18213. +/**
  18214. + * struct ssam_event_id - Unique event ID used for enabling events.
  18215. + * @target_category: Target category of the event source.
  18216. + * @instance: Instance ID of the event source.
  18217. + *
  18218. + * This struct specifies the event to be enabled/disabled via an externally
  18219. + * provided registry. It does not specify the registry to be used itself, this
  18220. + * is done via &struct ssam_event_registry.
  18221. + */
  18222. +struct ssam_event_id {
  18223. + u8 target_category;
  18224. + u8 instance;
  18225. +};
  18226. +
  18227. +/**
  18228. + * enum ssam_event_mask - Flags specifying how events are matched to notifiers.
  18229. + *
  18230. + * @SSAM_EVENT_MASK_NONE:
  18231. + * Run the callback for any event with matching target category. Do not
  18232. + * do any additional filtering.
  18233. + *
  18234. + * @SSAM_EVENT_MASK_TARGET:
  18235. + * In addition to filtering by target category, only execute the notifier
  18236. + * callback for events with a target ID matching to the one of the
  18237. + * registry used for enabling/disabling the event.
  18238. + *
  18239. + * @SSAM_EVENT_MASK_INSTANCE:
  18240. + * In addition to filtering by target category, only execute the notifier
  18241. + * callback for events with an instance ID matching to the instance ID
  18242. + * used when enabling the event.
  18243. + *
  18244. + * @SSAM_EVENT_MASK_STRICT:
  18245. + * Do all the filtering above.
  18246. + */
  18247. +enum ssam_event_mask {
  18248. + SSAM_EVENT_MASK_TARGET = BIT(0),
  18249. + SSAM_EVENT_MASK_INSTANCE = BIT(1),
  18250. +
  18251. + SSAM_EVENT_MASK_NONE = 0,
  18252. + SSAM_EVENT_MASK_STRICT =
  18253. + SSAM_EVENT_MASK_TARGET
  18254. + | SSAM_EVENT_MASK_INSTANCE,
  18255. +};
  18256. +
  18257. +/**
  18258. + * SSAM_EVENT_REGISTRY() - Define a new event registry.
  18259. + * @tc: Target category for the event registry requests.
  18260. + * @tid: Target ID for the event registry requests.
  18261. + * @cid_en: Command ID for the event-enable request.
  18262. + * @cid_dis: Command ID for the event-disable request.
  18263. + *
  18264. + * Return: Returns the &struct ssam_event_registry specified by the given
  18265. + * parameters.
  18266. + */
  18267. +#define SSAM_EVENT_REGISTRY(tc, tid, cid_en, cid_dis) \
  18268. + ((struct ssam_event_registry) { \
  18269. + .target_category = (tc), \
  18270. + .target_id = (tid), \
  18271. + .cid_enable = (cid_en), \
  18272. + .cid_disable = (cid_dis), \
  18273. + })
  18274. +
  18275. +#define SSAM_EVENT_REGISTRY_SAM \
  18276. + SSAM_EVENT_REGISTRY(SSAM_SSH_TC_SAM, 0x01, 0x0b, 0x0c)
  18277. +
  18278. +#define SSAM_EVENT_REGISTRY_KIP \
  18279. + SSAM_EVENT_REGISTRY(SSAM_SSH_TC_KIP, 0x02, 0x27, 0x28)
  18280. +
  18281. +#define SSAM_EVENT_REGISTRY_REG \
  18282. + SSAM_EVENT_REGISTRY(SSAM_SSH_TC_REG, 0x02, 0x01, 0x02)
  18283. +
  18284. +/**
  18285. + * struct ssam_event_notifier - Notifier block for SSAM events.
  18286. + * @base: The base notifier block with callback function and priority.
  18287. + * @event: The event for which this block will receive notifications.
  18288. + * @event.reg: Registry via which the event will be enabled/disabled.
  18289. + * @event.id: ID specifying the event.
  18290. + * @event.mask: Flags determining how events are matched to the notifier.
  18291. + * @event.flags: Flags used for enabling the event.
  18292. + */
  18293. +struct ssam_event_notifier {
  18294. + struct ssam_notifier_block base;
  18295. +
  18296. + struct {
  18297. + struct ssam_event_registry reg;
  18298. + struct ssam_event_id id;
  18299. + enum ssam_event_mask mask;
  18300. + u8 flags;
  18301. + } event;
  18302. +};
  18303. +
  18304. +int ssam_notifier_register(struct ssam_controller *ctrl,
  18305. + struct ssam_event_notifier *n);
  18306. +
  18307. +int ssam_notifier_unregister(struct ssam_controller *ctrl,
  18308. + struct ssam_event_notifier *n);
  18309. +
  18310. +#endif /* _LINUX_SURFACE_AGGREGATOR_CONTROLLER_H */
  18311. diff --git a/include/linux/surface_aggregator/device.h b/include/linux/surface_aggregator/device.h
  18312. new file mode 100644
  18313. index 000000000000..02f3e06c0a60
  18314. --- /dev/null
  18315. +++ b/include/linux/surface_aggregator/device.h
  18316. @@ -0,0 +1,423 @@
  18317. +/* SPDX-License-Identifier: GPL-2.0+ */
  18318. +/*
  18319. + * Surface System Aggregator Module (SSAM) bus and client-device subsystem.
  18320. + *
  18321. + * Main interface for the surface-aggregator bus, surface-aggregator client
  18322. + * devices, and respective drivers building on top of the SSAM controller.
  18323. + * Provides support for non-platform/non-ACPI SSAM clients via dedicated
  18324. + * subsystem.
  18325. + *
  18326. + * Copyright (C) 2019-2020 Maximilian Luz <luzmaximilian@gmail.com>
  18327. + */
  18328. +
  18329. +#ifndef _LINUX_SURFACE_AGGREGATOR_DEVICE_H
  18330. +#define _LINUX_SURFACE_AGGREGATOR_DEVICE_H
  18331. +
  18332. +#include <linux/device.h>
  18333. +#include <linux/mod_devicetable.h>
  18334. +#include <linux/types.h>
  18335. +
  18336. +#include <linux/surface_aggregator/controller.h>
  18337. +
  18338. +
  18339. +/* -- Surface System Aggregator Module bus. --------------------------------- */
  18340. +
  18341. +/**
  18342. + * enum ssam_device_domain - SAM device domain.
  18343. + * @SSAM_DOMAIN_VIRTUAL: Virtual device.
  18344. + * @SSAM_DOMAIN_SERIALHUB: Physical device connected via Surface Serial Hub.
  18345. + */
  18346. +enum ssam_device_domain {
  18347. + SSAM_DOMAIN_VIRTUAL = 0x00,
  18348. + SSAM_DOMAIN_SERIALHUB = 0x01,
  18349. +};
  18350. +
  18351. +/**
  18352. + * enum ssam_virtual_tc - Target categories for the virtual SAM domain.
  18353. + * @SSAM_VIRTUAL_TC_HUB: Device hub category.
  18354. + */
  18355. +enum ssam_virtual_tc {
  18356. + SSAM_VIRTUAL_TC_HUB = 0x00,
  18357. +};
  18358. +
  18359. +/**
  18360. + * struct ssam_device_uid - Unique identifier for SSAM device.
  18361. + * @domain: Domain of the device.
  18362. + * @category: Target category of the device.
  18363. + * @target: Target ID of the device.
  18364. + * @instance: Instance ID of the device.
  18365. + * @function: Sub-function of the device. This field can be used to split a
  18366. + * single SAM device into multiple virtual subdevices to separate
  18367. + * different functionality of that device and allow one driver per
  18368. + * such functionality.
  18369. + */
  18370. +struct ssam_device_uid {
  18371. + u8 domain;
  18372. + u8 category;
  18373. + u8 target;
  18374. + u8 instance;
  18375. + u8 function;
  18376. +};
  18377. +
  18378. +/*
  18379. + * Special values for device matching.
  18380. + *
  18381. + * These values are intended to be used with SSAM_DEVICE(), SSAM_VDEV(), and
  18382. + * SSAM_SDEV() exclusively. Specifically, they are used to initialize the
  18383. + * match_flags member of the device ID structure. Do not use them directly
  18384. + * with struct ssam_device_id or struct ssam_device_uid.
  18385. + */
  18386. +#define SSAM_ANY_TID 0xffff
  18387. +#define SSAM_ANY_IID 0xffff
  18388. +#define SSAM_ANY_FUN 0xffff
  18389. +
  18390. +/**
  18391. + * SSAM_DEVICE() - Initialize a &struct ssam_device_id with the given
  18392. + * parameters.
  18393. + * @d: Domain of the device.
  18394. + * @cat: Target category of the device.
  18395. + * @tid: Target ID of the device.
  18396. + * @iid: Instance ID of the device.
  18397. + * @fun: Sub-function of the device.
  18398. + *
  18399. + * Initializes a &struct ssam_device_id with the given parameters. See &struct
  18400. + * ssam_device_uid for details regarding the parameters. The special values
  18401. + * %SSAM_ANY_TID, %SSAM_ANY_IID, and %SSAM_ANY_FUN can be used to specify that
  18402. + * matching should ignore target ID, instance ID, and/or sub-function,
  18403. + * respectively. This macro initializes the ``match_flags`` field based on the
  18404. + * given parameters.
  18405. + *
  18406. + * Note: The parameters @d and @cat must be valid &u8 values, the parameters
  18407. + * @tid, @iid, and @fun must be either valid &u8 values or %SSAM_ANY_TID,
  18408. + * %SSAM_ANY_IID, or %SSAM_ANY_FUN, respectively. Other non-&u8 values are not
  18409. + * allowed.
  18410. + */
  18411. +#define SSAM_DEVICE(d, cat, tid, iid, fun) \
  18412. + .match_flags = (((tid) != SSAM_ANY_TID) ? SSAM_MATCH_TARGET : 0) \
  18413. + | (((iid) != SSAM_ANY_IID) ? SSAM_MATCH_INSTANCE : 0) \
  18414. + | (((fun) != SSAM_ANY_FUN) ? SSAM_MATCH_FUNCTION : 0), \
  18415. + .domain = d, \
  18416. + .category = cat, \
  18417. + .target = ((tid) != SSAM_ANY_TID) ? (tid) : 0, \
  18418. + .instance = ((iid) != SSAM_ANY_IID) ? (iid) : 0, \
  18419. + .function = ((fun) != SSAM_ANY_FUN) ? (fun) : 0 \
  18420. +
  18421. +/**
  18422. + * SSAM_VDEV() - Initialize a &struct ssam_device_id as virtual device with
  18423. + * the given parameters.
  18424. + * @cat: Target category of the device.
  18425. + * @tid: Target ID of the device.
  18426. + * @iid: Instance ID of the device.
  18427. + * @fun: Sub-function of the device.
  18428. + *
  18429. + * Initializes a &struct ssam_device_id with the given parameters in the
  18430. + * virtual domain. See &struct ssam_device_uid for details regarding the
  18431. + * parameters. The special values %SSAM_ANY_TID, %SSAM_ANY_IID, and
  18432. + * %SSAM_ANY_FUN can be used to specify that matching should ignore target ID,
  18433. + * instance ID, and/or sub-function, respectively. This macro initializes the
  18434. + * ``match_flags`` field based on the given parameters.
  18435. + *
  18436. + * Note: The parameter @cat must be a valid &u8 value, the parameters @tid,
  18437. + * @iid, and @fun must be either valid &u8 values or %SSAM_ANY_TID,
  18438. + * %SSAM_ANY_IID, or %SSAM_ANY_FUN, respectively. Other non-&u8 values are not
  18439. + * allowed.
  18440. + */
  18441. +#define SSAM_VDEV(cat, tid, iid, fun) \
  18442. + SSAM_DEVICE(SSAM_DOMAIN_VIRTUAL, SSAM_VIRTUAL_TC_##cat, tid, iid, fun)
  18443. +
  18444. +/**
  18445. + * SSAM_SDEV() - Initialize a &struct ssam_device_id as physical SSH device
  18446. + * with the given parameters.
  18447. + * @cat: Target category of the device.
  18448. + * @tid: Target ID of the device.
  18449. + * @iid: Instance ID of the device.
  18450. + * @fun: Sub-function of the device.
  18451. + *
  18452. + * Initializes a &struct ssam_device_id with the given parameters in the SSH
  18453. + * domain. See &struct ssam_device_uid for details regarding the parameters.
  18454. + * The special values %SSAM_ANY_TID, %SSAM_ANY_IID, and %SSAM_ANY_FUN can be
  18455. + * used to specify that matching should ignore target ID, instance ID, and/or
  18456. + * sub-function, respectively. This macro initializes the ``match_flags``
  18457. + * field based on the given parameters.
  18458. + *
  18459. + * Note: The parameter @cat must be a valid &u8 value, the parameters @tid,
  18460. + * @iid, and @fun must be either valid &u8 values or %SSAM_ANY_TID,
  18461. + * %SSAM_ANY_IID, or %SSAM_ANY_FUN, respectively. Other non-&u8 values are not
  18462. + * allowed.
  18463. + */
  18464. +#define SSAM_SDEV(cat, tid, iid, fun) \
  18465. + SSAM_DEVICE(SSAM_DOMAIN_SERIALHUB, SSAM_SSH_TC_##cat, tid, iid, fun)
  18466. +
  18467. +/**
  18468. + * struct ssam_device - SSAM client device.
  18469. + * @dev: Driver model representation of the device.
  18470. + * @ctrl: SSAM controller managing this device.
  18471. + * @uid: UID identifying the device.
  18472. + */
  18473. +struct ssam_device {
  18474. + struct device dev;
  18475. + struct ssam_controller *ctrl;
  18476. +
  18477. + struct ssam_device_uid uid;
  18478. +};
  18479. +
  18480. +/**
  18481. + * struct ssam_device_driver - SSAM client device driver.
  18482. + * @driver: Base driver model structure.
  18483. + * @match_table: Match table specifying which devices the driver should bind to.
  18484. + * @probe: Called when the driver is being bound to a device.
  18485. + * @remove: Called when the driver is being unbound from the device.
  18486. + */
  18487. +struct ssam_device_driver {
  18488. + struct device_driver driver;
  18489. +
  18490. + const struct ssam_device_id *match_table;
  18491. +
  18492. + int (*probe)(struct ssam_device *sdev);
  18493. + void (*remove)(struct ssam_device *sdev);
  18494. +};
  18495. +
  18496. +extern struct bus_type ssam_bus_type;
  18497. +extern const struct device_type ssam_device_type;
  18498. +
  18499. +/**
  18500. + * is_ssam_device() - Check if the given device is a SSAM client device.
  18501. + * @d: The device to test the type of.
  18502. + *
  18503. + * Return: Returns %true if the specified device is of type &struct
  18504. + * ssam_device, i.e. the device type points to %ssam_device_type, and %false
  18505. + * otherwise.
  18506. + */
  18507. +static inline bool is_ssam_device(struct device *d)
  18508. +{
  18509. + return d->type == &ssam_device_type;
  18510. +}
  18511. +
  18512. +/**
  18513. + * to_ssam_device() - Casts the given device to a SSAM client device.
  18514. + * @d: The device to cast.
  18515. + *
  18516. + * Casts the given &struct device to a &struct ssam_device. The caller has to
  18517. + * ensure that the given device is actually enclosed in a &struct ssam_device,
  18518. + * e.g. by calling is_ssam_device().
  18519. + *
  18520. + * Return: Returns a pointer to the &struct ssam_device wrapping the given
  18521. + * device @d.
  18522. + */
  18523. +static inline struct ssam_device *to_ssam_device(struct device *d)
  18524. +{
  18525. + return container_of(d, struct ssam_device, dev);
  18526. +}
  18527. +
  18528. +/**
  18529. + * to_ssam_device_driver() - Casts the given device driver to a SSAM client
  18530. + * device driver.
  18531. + * @d: The driver to cast.
  18532. + *
  18533. + * Casts the given &struct device_driver to a &struct ssam_device_driver. The
  18534. + * caller has to ensure that the given driver is actually enclosed in a
  18535. + * &struct ssam_device_driver.
  18536. + *
  18537. + * Return: Returns the pointer to the &struct ssam_device_driver wrapping the
  18538. + * given device driver @d.
  18539. + */
  18540. +static inline
  18541. +struct ssam_device_driver *to_ssam_device_driver(struct device_driver *d)
  18542. +{
  18543. + return container_of(d, struct ssam_device_driver, driver);
  18544. +}
  18545. +
  18546. +const struct ssam_device_id *ssam_device_id_match(const struct ssam_device_id *table,
  18547. + const struct ssam_device_uid uid);
  18548. +
  18549. +const struct ssam_device_id *ssam_device_get_match(const struct ssam_device *dev);
  18550. +
  18551. +const void *ssam_device_get_match_data(const struct ssam_device *dev);
  18552. +
  18553. +struct ssam_device *ssam_device_alloc(struct ssam_controller *ctrl,
  18554. + struct ssam_device_uid uid);
  18555. +
  18556. +int ssam_device_add(struct ssam_device *sdev);
  18557. +void ssam_device_remove(struct ssam_device *sdev);
  18558. +
  18559. +/**
  18560. + * ssam_device_get() - Increment reference count of SSAM client device.
  18561. + * @sdev: The device to increment the reference count of.
  18562. + *
  18563. + * Increments the reference count of the given SSAM client device by
  18564. + * incrementing the reference count of the enclosed &struct device via
  18565. + * get_device().
  18566. + *
  18567. + * See ssam_device_put() for the counter-part of this function.
  18568. + *
  18569. + * Return: Returns the device provided as input.
  18570. + */
  18571. +static inline struct ssam_device *ssam_device_get(struct ssam_device *sdev)
  18572. +{
  18573. + return sdev ? to_ssam_device(get_device(&sdev->dev)) : NULL;
  18574. +}
  18575. +
  18576. +/**
  18577. + * ssam_device_put() - Decrement reference count of SSAM client device.
  18578. + * @sdev: The device to decrement the reference count of.
  18579. + *
  18580. + * Decrements the reference count of the given SSAM client device by
  18581. + * decrementing the reference count of the enclosed &struct device via
  18582. + * put_device().
  18583. + *
  18584. + * See ssam_device_get() for the counter-part of this function.
  18585. + */
  18586. +static inline void ssam_device_put(struct ssam_device *sdev)
  18587. +{
  18588. + if (sdev)
  18589. + put_device(&sdev->dev);
  18590. +}
  18591. +
  18592. +/**
  18593. + * ssam_device_get_drvdata() - Get driver-data of SSAM client device.
  18594. + * @sdev: The device to get the driver-data from.
  18595. + *
  18596. + * Return: Returns the driver-data of the given device, previously set via
  18597. + * ssam_device_set_drvdata().
  18598. + */
  18599. +static inline void *ssam_device_get_drvdata(struct ssam_device *sdev)
  18600. +{
  18601. + return dev_get_drvdata(&sdev->dev);
  18602. +}
  18603. +
  18604. +/**
  18605. + * ssam_device_set_drvdata() - Set driver-data of SSAM client device.
  18606. + * @sdev: The device to set the driver-data of.
  18607. + * @data: The data to set the device's driver-data pointer to.
  18608. + */
  18609. +static inline void ssam_device_set_drvdata(struct ssam_device *sdev, void *data)
  18610. +{
  18611. + dev_set_drvdata(&sdev->dev, data);
  18612. +}
  18613. +
  18614. +int __ssam_device_driver_register(struct ssam_device_driver *d, struct module *o);
  18615. +void ssam_device_driver_unregister(struct ssam_device_driver *d);
  18616. +
  18617. +/**
  18618. + * ssam_device_driver_register() - Register a SSAM client device driver.
  18619. + * @drv: The driver to register.
  18620. + */
  18621. +#define ssam_device_driver_register(drv) \
  18622. + __ssam_device_driver_register(drv, THIS_MODULE)
  18623. +
  18624. +/**
  18625. + * module_ssam_device_driver() - Helper macro for SSAM device driver
  18626. + * registration.
  18627. + * @drv: The driver managed by this module.
  18628. + *
  18629. + * Helper macro to register a SSAM device driver via module_init() and
  18630. + * module_exit(). This macro may only be used once per module and replaces the
  18631. + * aforementioned definitions.
  18632. + */
  18633. +#define module_ssam_device_driver(drv) \
  18634. + module_driver(drv, ssam_device_driver_register, \
  18635. + ssam_device_driver_unregister)
  18636. +
  18637. +
  18638. +/* -- Helpers for client-device requests. ----------------------------------- */
  18639. +
  18640. +/**
  18641. + * SSAM_DEFINE_SYNC_REQUEST_CL_N() - Define synchronous client-device SAM
  18642. + * request function with neither argument nor return value.
  18643. + * @name: Name of the generated function.
  18644. + * @spec: Specification (&struct ssam_request_spec_md) defining the request.
  18645. + *
  18646. + * Defines a function executing the synchronous SAM request specified by
  18647. + * @spec, with the request having neither argument nor return value. Device
  18648. + * specifying parameters are not hard-coded, but instead are provided via the
  18649. + * client device, specifically its UID, supplied when calling this function.
  18650. + * The generated function takes care of setting up the request struct, buffer
  18651. + * allocation, as well as execution of the request itself, returning once the
  18652. + * request has been fully completed. The required transport buffer will be
  18653. + * allocated on the stack.
  18654. + *
  18655. + * The generated function is defined as ``int name(struct ssam_device *sdev)``,
  18656. + * returning the status of the request, which is zero on success and negative
  18657. + * on failure. The ``sdev`` parameter specifies both the target device of the
  18658. + * request and by association the controller via which the request is sent.
  18659. + *
  18660. + * Refer to ssam_request_sync_onstack() for more details on the behavior of
  18661. + * the generated function.
  18662. + */
  18663. +#define SSAM_DEFINE_SYNC_REQUEST_CL_N(name, spec...) \
  18664. + SSAM_DEFINE_SYNC_REQUEST_MD_N(__raw_##name, spec) \
  18665. + int name(struct ssam_device *sdev) \
  18666. + { \
  18667. + return __raw_##name(sdev->ctrl, sdev->uid.target, \
  18668. + sdev->uid.instance); \
  18669. + }
  18670. +
  18671. +/**
  18672. + * SSAM_DEFINE_SYNC_REQUEST_CL_W() - Define synchronous client-device SAM
  18673. + * request function with argument.
  18674. + * @name: Name of the generated function.
  18675. + * @atype: Type of the request's argument.
  18676. + * @spec: Specification (&struct ssam_request_spec_md) defining the request.
  18677. + *
  18678. + * Defines a function executing the synchronous SAM request specified by
  18679. + * @spec, with the request taking an argument of type @atype and having no
  18680. + * return value. Device specifying parameters are not hard-coded, but instead
  18681. + * are provided via the client device, specifically its UID, supplied when
  18682. + * calling this function. The generated function takes care of setting up the
  18683. + * request struct, buffer allocation, as well as execution of the request
  18684. + * itself, returning once the request has been fully completed. The required
  18685. + * transport buffer will be allocated on the stack.
  18686. + *
  18687. + * The generated function is defined as ``int name(struct ssam_device *sdev,
  18688. + * const atype *arg)``, returning the status of the request, which is zero on
  18689. + * success and negative on failure. The ``sdev`` parameter specifies both the
  18690. + * target device of the request and by association the controller via which
  18691. + * the request is sent. The request's argument is specified via the ``arg``
  18692. + * pointer.
  18693. + *
  18694. + * Refer to ssam_request_sync_onstack() for more details on the behavior of
  18695. + * the generated function.
  18696. + */
  18697. +#define SSAM_DEFINE_SYNC_REQUEST_CL_W(name, atype, spec...) \
  18698. + SSAM_DEFINE_SYNC_REQUEST_MD_W(__raw_##name, atype, spec) \
  18699. + int name(struct ssam_device *sdev, const atype *arg) \
  18700. + { \
  18701. + return __raw_##name(sdev->ctrl, sdev->uid.target, \
  18702. + sdev->uid.instance, arg); \
  18703. + }
  18704. +
  18705. +/**
  18706. + * SSAM_DEFINE_SYNC_REQUEST_CL_R() - Define synchronous client-device SAM
  18707. + * request function with return value.
  18708. + * @name: Name of the generated function.
  18709. + * @rtype: Type of the request's return value.
  18710. + * @spec: Specification (&struct ssam_request_spec_md) defining the request.
  18711. + *
  18712. + * Defines a function executing the synchronous SAM request specified by
  18713. + * @spec, with the request taking no argument but having a return value of
  18714. + * type @rtype. Device specifying parameters are not hard-coded, but instead
  18715. + * are provided via the client device, specifically its UID, supplied when
  18716. + * calling this function. The generated function takes care of setting up the
  18717. + * request struct, buffer allocation, as well as execution of the request
  18718. + * itself, returning once the request has been fully completed. The required
  18719. + * transport buffer will be allocated on the stack.
  18720. + *
  18721. + * The generated function is defined as ``int name(struct ssam_device *sdev,
  18722. + * rtype *ret)``, returning the status of the request, which is zero on
  18723. + * success and negative on failure. The ``sdev`` parameter specifies both the
  18724. + * target device of the request and by association the controller via which
  18725. + * the request is sent. The request's return value is written to the memory
  18726. + * pointed to by the ``ret`` parameter.
  18727. + *
  18728. + * Refer to ssam_request_sync_onstack() for more details on the behavior of
  18729. + * the generated function.
  18730. + */
  18731. +#define SSAM_DEFINE_SYNC_REQUEST_CL_R(name, rtype, spec...) \
  18732. + SSAM_DEFINE_SYNC_REQUEST_MD_R(__raw_##name, rtype, spec) \
  18733. + int name(struct ssam_device *sdev, rtype *ret) \
  18734. + { \
  18735. + return __raw_##name(sdev->ctrl, sdev->uid.target, \
  18736. + sdev->uid.instance, ret); \
  18737. + }
  18738. +
  18739. +#endif /* _LINUX_SURFACE_AGGREGATOR_DEVICE_H */
  18740. diff --git a/include/linux/surface_aggregator/serial_hub.h b/include/linux/surface_aggregator/serial_hub.h
  18741. new file mode 100644
  18742. index 000000000000..64276fbfa1d5
  18743. --- /dev/null
  18744. +++ b/include/linux/surface_aggregator/serial_hub.h
  18745. @@ -0,0 +1,672 @@
  18746. +/* SPDX-License-Identifier: GPL-2.0+ */
  18747. +/*
  18748. + * Surface Serial Hub (SSH) protocol and communication interface.
  18749. + *
  18750. + * Lower-level communication layers and SSH protocol definitions for the
  18751. + * Surface System Aggregator Module (SSAM). Provides the interface for basic
  18752. + * packet- and request-based communication with the SSAM EC via SSH.
  18753. + *
  18754. + * Copyright (C) 2019-2020 Maximilian Luz <luzmaximilian@gmail.com>
  18755. + */
  18756. +
  18757. +#ifndef _LINUX_SURFACE_AGGREGATOR_SERIAL_HUB_H
  18758. +#define _LINUX_SURFACE_AGGREGATOR_SERIAL_HUB_H
  18759. +
  18760. +#include <linux/crc-ccitt.h>
  18761. +#include <linux/kref.h>
  18762. +#include <linux/ktime.h>
  18763. +#include <linux/list.h>
  18764. +#include <linux/types.h>
  18765. +
  18766. +
  18767. +/* -- Data structures for SAM-over-SSH communication. ----------------------- */
  18768. +
  18769. +/**
  18770. + * enum ssh_frame_type - Frame types for SSH frames.
  18771. + *
  18772. + * @SSH_FRAME_TYPE_DATA_SEQ:
  18773. + * Indicates a data frame, followed by a payload with the length specified
  18774. + * in the ``struct ssh_frame.len`` field. This frame is sequenced, meaning
  18775. + * that an ACK is required.
  18776. + *
  18777. + * @SSH_FRAME_TYPE_DATA_NSQ:
  18778. + * Same as %SSH_FRAME_TYPE_DATA_SEQ, but unsequenced, meaning that the
  18779. + * message does not have to be ACKed.
  18780. + *
  18781. + * @SSH_FRAME_TYPE_ACK:
  18782. + * Indicates an ACK message.
  18783. + *
  18784. + * @SSH_FRAME_TYPE_NAK:
  18785. + * Indicates an error response for previously sent frame. In general, this
  18786. + * means that the frame and/or payload is malformed, e.g. a CRC is wrong.
  18787. + * For command-type payloads, this can also mean that the command is
  18788. + * invalid.
  18789. + */
  18790. +enum ssh_frame_type {
  18791. + SSH_FRAME_TYPE_DATA_SEQ = 0x80,
  18792. + SSH_FRAME_TYPE_DATA_NSQ = 0x00,
  18793. + SSH_FRAME_TYPE_ACK = 0x40,
  18794. + SSH_FRAME_TYPE_NAK = 0x04,
  18795. +};
  18796. +
  18797. +/**
  18798. + * struct ssh_frame - SSH communication frame.
  18799. + * @type: The type of the frame. See &enum ssh_frame_type.
  18800. + * @len: The length of the frame payload directly following the CRC for this
  18801. + * frame. Does not include the final CRC for that payload.
  18802. + * @seq: The sequence number for this message/exchange.
  18803. + */
  18804. +struct ssh_frame {
  18805. + u8 type;
  18806. + __le16 len;
  18807. + u8 seq;
  18808. +} __packed;
  18809. +
  18810. +static_assert(sizeof(struct ssh_frame) == 4);
  18811. +
  18812. +/*
  18813. + * SSH_FRAME_MAX_PAYLOAD_SIZE - Maximum SSH frame payload length in bytes.
  18814. + *
  18815. + * This is the physical maximum length of the protocol. Implementations may
  18816. + * set a more constrained limit.
  18817. + */
  18818. +#define SSH_FRAME_MAX_PAYLOAD_SIZE U16_MAX
  18819. +
  18820. +/**
  18821. + * enum ssh_payload_type - Type indicator for the SSH payload.
  18822. + * @SSH_PLD_TYPE_CMD: The payload is a command structure with optional command
  18823. + * payload.
  18824. + */
  18825. +enum ssh_payload_type {
  18826. + SSH_PLD_TYPE_CMD = 0x80,
  18827. +};
  18828. +
  18829. +/**
  18830. + * struct ssh_command - Payload of a command-type frame.
  18831. + * @type: The type of the payload. See &enum ssh_payload_type. Should be
  18832. + * SSH_PLD_TYPE_CMD for this struct.
  18833. + * @tc: Command target category.
  18834. + * @tid_out: Output target ID. Should be zero if this an incoming (EC to host)
  18835. + * message.
  18836. + * @tid_in: Input target ID. Should be zero if this is an outgoing (host to
  18837. + * EC) message.
  18838. + * @iid: Instance ID.
  18839. + * @rqid: Request ID. Used to match requests with responses and differentiate
  18840. + * between responses and events.
  18841. + * @cid: Command ID.
  18842. + */
  18843. +struct ssh_command {
  18844. + u8 type;
  18845. + u8 tc;
  18846. + u8 tid_out;
  18847. + u8 tid_in;
  18848. + u8 iid;
  18849. + __le16 rqid;
  18850. + u8 cid;
  18851. +} __packed;
  18852. +
  18853. +static_assert(sizeof(struct ssh_command) == 8);
  18854. +
  18855. +/*
  18856. + * SSH_COMMAND_MAX_PAYLOAD_SIZE - Maximum SSH command payload length in bytes.
  18857. + *
  18858. + * This is the physical maximum length of the protocol. Implementations may
  18859. + * set a more constrained limit.
  18860. + */
  18861. +#define SSH_COMMAND_MAX_PAYLOAD_SIZE \
  18862. + (SSH_FRAME_MAX_PAYLOAD_SIZE - sizeof(struct ssh_command))
  18863. +
  18864. +/*
  18865. + * SSH_MSG_LEN_BASE - Base-length of a SSH message.
  18866. + *
  18867. + * This is the minimum number of bytes required to form a message. The actual
  18868. + * message length is SSH_MSG_LEN_BASE plus the length of the frame payload.
  18869. + */
  18870. +#define SSH_MSG_LEN_BASE (sizeof(struct ssh_frame) + 3ull * sizeof(u16))
  18871. +
  18872. +/*
  18873. + * SSH_MSG_LEN_CTRL - Length of a SSH control message.
  18874. + *
  18875. + * This is the length of a SSH control message, which is equal to a SSH
  18876. + * message without any payload.
  18877. + */
  18878. +#define SSH_MSG_LEN_CTRL SSH_MSG_LEN_BASE
  18879. +
  18880. +/**
  18881. + * SSH_MESSAGE_LENGTH() - Compute length of SSH message.
  18882. + * @payload_size: Length of the payload inside the SSH frame.
  18883. + *
  18884. + * Return: Returns the length of a SSH message with payload of specified size.
  18885. + */
  18886. +#define SSH_MESSAGE_LENGTH(payload_size) (SSH_MSG_LEN_BASE + (payload_size))
  18887. +
  18888. +/**
  18889. + * SSH_COMMAND_MESSAGE_LENGTH() - Compute length of SSH command message.
  18890. + * @payload_size: Length of the command payload.
  18891. + *
  18892. + * Return: Returns the length of a SSH command message with command payload of
  18893. + * specified size.
  18894. + */
  18895. +#define SSH_COMMAND_MESSAGE_LENGTH(payload_size) \
  18896. + SSH_MESSAGE_LENGTH(sizeof(struct ssh_command) + (payload_size))
  18897. +
  18898. +/**
  18899. + * SSH_MSGOFFSET_FRAME() - Compute offset in SSH message to specified field in
  18900. + * frame.
  18901. + * @field: The field for which the offset should be computed.
  18902. + *
  18903. + * Return: Returns the offset of the specified &struct ssh_frame field in the
  18904. + * raw SSH message data as. Takes SYN bytes (u16) preceding the frame into
  18905. + * account.
  18906. + */
  18907. +#define SSH_MSGOFFSET_FRAME(field) \
  18908. + (sizeof(u16) + offsetof(struct ssh_frame, field))
  18909. +
  18910. +/**
  18911. + * SSH_MSGOFFSET_COMMAND() - Compute offset in SSH message to specified field
  18912. + * in command.
  18913. + * @field: The field for which the offset should be computed.
  18914. + *
  18915. + * Return: Returns the offset of the specified &struct ssh_command field in
  18916. + * the raw SSH message data. Takes SYN bytes (u16) preceding the frame and the
  18917. + * frame CRC (u16) between frame and command into account.
  18918. + */
  18919. +#define SSH_MSGOFFSET_COMMAND(field) \
  18920. + (2ull * sizeof(u16) + sizeof(struct ssh_frame) \
  18921. + + offsetof(struct ssh_command, field))
  18922. +
  18923. +/*
  18924. + * SSH_MSG_SYN - SSH message synchronization (SYN) bytes as u16.
  18925. + */
  18926. +#define SSH_MSG_SYN ((u16)0x55aa)
  18927. +
  18928. +/**
  18929. + * ssh_crc() - Compute CRC for SSH messages.
  18930. + * @buf: The pointer pointing to the data for which the CRC should be computed.
  18931. + * @len: The length of the data for which the CRC should be computed.
  18932. + *
  18933. + * Return: Returns the CRC computed on the provided data, as used for SSH
  18934. + * messages.
  18935. + */
  18936. +static inline u16 ssh_crc(const u8 *buf, size_t len)
  18937. +{
  18938. + return crc_ccitt_false(0xffff, buf, len);
  18939. +}
  18940. +
  18941. +/*
  18942. + * SSH_NUM_EVENTS - The number of reserved event IDs.
  18943. + *
  18944. + * The number of reserved event IDs, used for registering an SSH event
  18945. + * handler. Valid event IDs are numbers below or equal to this value, with
  18946. + * exception of zero, which is not an event ID. Thus, this is also the
  18947. + * absolute maximum number of event handlers that can be registered.
  18948. + */
  18949. +#define SSH_NUM_EVENTS 34
  18950. +
  18951. +/*
  18952. + * SSH_NUM_TARGETS - The number of communication targets used in the protocol.
  18953. + */
  18954. +#define SSH_NUM_TARGETS 2
  18955. +
  18956. +/**
  18957. + * ssh_rqid_next_valid() - Return the next valid request ID.
  18958. + * @rqid: The current request ID.
  18959. + *
  18960. + * Return: Returns the next valid request ID, following the current request ID
  18961. + * provided to this function. This function skips any request IDs reserved for
  18962. + * events.
  18963. + */
  18964. +static inline u16 ssh_rqid_next_valid(u16 rqid)
  18965. +{
  18966. + return rqid > 0 ? rqid + 1u : rqid + SSH_NUM_EVENTS + 1u;
  18967. +}
  18968. +
  18969. +/**
  18970. + * ssh_rqid_to_event() - Convert request ID to its corresponding event ID.
  18971. + * @rqid: The request ID to convert.
  18972. + */
  18973. +static inline u16 ssh_rqid_to_event(u16 rqid)
  18974. +{
  18975. + return rqid - 1u;
  18976. +}
  18977. +
  18978. +/**
  18979. + * ssh_rqid_is_event() - Check if given request ID is a valid event ID.
  18980. + * @rqid: The request ID to check.
  18981. + */
  18982. +static inline bool ssh_rqid_is_event(u16 rqid)
  18983. +{
  18984. + return ssh_rqid_to_event(rqid) < SSH_NUM_EVENTS;
  18985. +}
  18986. +
  18987. +/**
  18988. + * ssh_tc_to_rqid() - Convert target category to its corresponding request ID.
  18989. + * @tc: The target category to convert.
  18990. + */
  18991. +static inline u16 ssh_tc_to_rqid(u8 tc)
  18992. +{
  18993. + return tc;
  18994. +}
  18995. +
  18996. +/**
  18997. + * ssh_tid_to_index() - Convert target ID to its corresponding target index.
  18998. + * @tid: The target ID to convert.
  18999. + */
  19000. +static inline u8 ssh_tid_to_index(u8 tid)
  19001. +{
  19002. + return tid - 1u;
  19003. +}
  19004. +
  19005. +/**
  19006. + * ssh_tid_is_valid() - Check if target ID is valid/supported.
  19007. + * @tid: The target ID to check.
  19008. + */
  19009. +static inline bool ssh_tid_is_valid(u8 tid)
  19010. +{
  19011. + return ssh_tid_to_index(tid) < SSH_NUM_TARGETS;
  19012. +}
  19013. +
  19014. +/**
  19015. + * struct ssam_span - Reference to a buffer region.
  19016. + * @ptr: Pointer to the buffer region.
  19017. + * @len: Length of the buffer region.
  19018. + *
  19019. + * A reference to a (non-owned) buffer segment, consisting of pointer and
  19020. + * length. Use of this struct indicates non-owned data, i.e. data of which the
  19021. + * life-time is managed (i.e. it is allocated/freed) via another pointer.
  19022. + */
  19023. +struct ssam_span {
  19024. + u8 *ptr;
  19025. + size_t len;
  19026. +};
  19027. +
  19028. +/*
  19029. + * Known SSH/EC target categories.
  19030. + *
  19031. + * List of currently known target category values; "Known" as in we know they
  19032. + * exist and are valid on at least some device/model. Detailed functionality
  19033. + * or the full category name is only known for some of these categories and
  19034. + * is detailed in the respective comment below.
  19035. + *
  19036. + * These values and abbreviations have been extracted from strings inside the
  19037. + * Windows driver.
  19038. + */
  19039. +enum ssam_ssh_tc {
  19040. + /* Category 0x00 is invalid for EC use. */
  19041. + SSAM_SSH_TC_SAM = 0x01, /* Generic system functionality, real-time clock. */
  19042. + SSAM_SSH_TC_BAT = 0x02, /* Battery/power subsystem. */
  19043. + SSAM_SSH_TC_TMP = 0x03, /* Thermal subsystem. */
  19044. + SSAM_SSH_TC_PMC = 0x04,
  19045. + SSAM_SSH_TC_FAN = 0x05,
  19046. + SSAM_SSH_TC_PoM = 0x06,
  19047. + SSAM_SSH_TC_DBG = 0x07,
  19048. + SSAM_SSH_TC_KBD = 0x08, /* Legacy keyboard (Laptop 1/2). */
  19049. + SSAM_SSH_TC_FWU = 0x09,
  19050. + SSAM_SSH_TC_UNI = 0x0a,
  19051. + SSAM_SSH_TC_LPC = 0x0b,
  19052. + SSAM_SSH_TC_TCL = 0x0c,
  19053. + SSAM_SSH_TC_SFL = 0x0d,
  19054. + SSAM_SSH_TC_KIP = 0x0e,
  19055. + SSAM_SSH_TC_EXT = 0x0f,
  19056. + SSAM_SSH_TC_BLD = 0x10,
  19057. + SSAM_SSH_TC_BAS = 0x11, /* Detachment system (Surface Book 2/3). */
  19058. + SSAM_SSH_TC_SEN = 0x12,
  19059. + SSAM_SSH_TC_SRQ = 0x13,
  19060. + SSAM_SSH_TC_MCU = 0x14,
  19061. + SSAM_SSH_TC_HID = 0x15, /* Generic HID input subsystem. */
  19062. + SSAM_SSH_TC_TCH = 0x16,
  19063. + SSAM_SSH_TC_BKL = 0x17,
  19064. + SSAM_SSH_TC_TAM = 0x18,
  19065. + SSAM_SSH_TC_ACC = 0x19,
  19066. + SSAM_SSH_TC_UFI = 0x1a,
  19067. + SSAM_SSH_TC_USC = 0x1b,
  19068. + SSAM_SSH_TC_PEN = 0x1c,
  19069. + SSAM_SSH_TC_VID = 0x1d,
  19070. + SSAM_SSH_TC_AUD = 0x1e,
  19071. + SSAM_SSH_TC_SMC = 0x1f,
  19072. + SSAM_SSH_TC_KPD = 0x20,
  19073. + SSAM_SSH_TC_REG = 0x21, /* Extended event registry. */
  19074. +};
  19075. +
  19076. +
  19077. +/* -- Packet transport layer (ptl). ----------------------------------------- */
  19078. +
  19079. +/**
  19080. + * enum ssh_packet_base_priority - Base priorities for &struct ssh_packet.
  19081. + * @SSH_PACKET_PRIORITY_FLUSH: Base priority for flush packets.
  19082. + * @SSH_PACKET_PRIORITY_DATA: Base priority for normal data packets.
  19083. + * @SSH_PACKET_PRIORITY_NAK: Base priority for NAK packets.
  19084. + * @SSH_PACKET_PRIORITY_ACK: Base priority for ACK packets.
  19085. + */
  19086. +enum ssh_packet_base_priority {
  19087. + SSH_PACKET_PRIORITY_FLUSH = 0, /* same as DATA to sequence flush */
  19088. + SSH_PACKET_PRIORITY_DATA = 0,
  19089. + SSH_PACKET_PRIORITY_NAK = 1,
  19090. + SSH_PACKET_PRIORITY_ACK = 2,
  19091. +};
  19092. +
  19093. +/*
  19094. + * Same as SSH_PACKET_PRIORITY() below, only with actual values.
  19095. + */
  19096. +#define __SSH_PACKET_PRIORITY(base, try) \
  19097. + (((base) << 4) | ((try) & 0x0f))
  19098. +
  19099. +/**
  19100. + * SSH_PACKET_PRIORITY() - Compute packet priority from base priority and
  19101. + * number of tries.
  19102. + * @base: The base priority as suffix of &enum ssh_packet_base_priority, e.g.
  19103. + * ``FLUSH``, ``DATA``, ``ACK``, or ``NAK``.
  19104. + * @try: The number of tries (must be less than 16).
  19105. + *
  19106. + * Compute the combined packet priority. The combined priority is dominated by
  19107. + * the base priority, whereas the number of (re-)tries decides the precedence
  19108. + * of packets with the same base priority, giving higher priority to packets
  19109. + * that already have more tries.
  19110. + *
  19111. + * Return: Returns the computed priority as value fitting inside a &u8. A
  19112. + * higher number means a higher priority.
  19113. + */
  19114. +#define SSH_PACKET_PRIORITY(base, try) \
  19115. + __SSH_PACKET_PRIORITY(SSH_PACKET_PRIORITY_##base, (try))
  19116. +
  19117. +/**
  19118. + * ssh_packet_priority_get_try() - Get number of tries from packet priority.
  19119. + * @priority: The packet priority.
  19120. + *
  19121. + * Return: Returns the number of tries encoded in the specified packet
  19122. + * priority.
  19123. + */
  19124. +static inline u8 ssh_packet_priority_get_try(u8 priority)
  19125. +{
  19126. + return priority & 0x0f;
  19127. +}
  19128. +
  19129. +/**
  19130. + * ssh_packet_priority_get_base - Get base priority from packet priority.
  19131. + * @priority: The packet priority.
  19132. + *
  19133. + * Return: Returns the base priority encoded in the given packet priority.
  19134. + */
  19135. +static inline u8 ssh_packet_priority_get_base(u8 priority)
  19136. +{
  19137. + return (priority & 0xf0) >> 4;
  19138. +}
  19139. +
  19140. +enum ssh_packet_flags {
  19141. + /* state flags */
  19142. + SSH_PACKET_SF_LOCKED_BIT,
  19143. + SSH_PACKET_SF_QUEUED_BIT,
  19144. + SSH_PACKET_SF_PENDING_BIT,
  19145. + SSH_PACKET_SF_TRANSMITTING_BIT,
  19146. + SSH_PACKET_SF_TRANSMITTED_BIT,
  19147. + SSH_PACKET_SF_ACKED_BIT,
  19148. + SSH_PACKET_SF_CANCELED_BIT,
  19149. + SSH_PACKET_SF_COMPLETED_BIT,
  19150. +
  19151. + /* type flags */
  19152. + SSH_PACKET_TY_FLUSH_BIT,
  19153. + SSH_PACKET_TY_SEQUENCED_BIT,
  19154. + SSH_PACKET_TY_BLOCKING_BIT,
  19155. +
  19156. + /* mask for state flags */
  19157. + SSH_PACKET_FLAGS_SF_MASK =
  19158. + BIT(SSH_PACKET_SF_LOCKED_BIT)
  19159. + | BIT(SSH_PACKET_SF_QUEUED_BIT)
  19160. + | BIT(SSH_PACKET_SF_PENDING_BIT)
  19161. + | BIT(SSH_PACKET_SF_TRANSMITTING_BIT)
  19162. + | BIT(SSH_PACKET_SF_TRANSMITTED_BIT)
  19163. + | BIT(SSH_PACKET_SF_ACKED_BIT)
  19164. + | BIT(SSH_PACKET_SF_CANCELED_BIT)
  19165. + | BIT(SSH_PACKET_SF_COMPLETED_BIT),
  19166. +
  19167. + /* mask for type flags */
  19168. + SSH_PACKET_FLAGS_TY_MASK =
  19169. + BIT(SSH_PACKET_TY_FLUSH_BIT)
  19170. + | BIT(SSH_PACKET_TY_SEQUENCED_BIT)
  19171. + | BIT(SSH_PACKET_TY_BLOCKING_BIT),
  19172. +};
  19173. +
  19174. +struct ssh_ptl;
  19175. +struct ssh_packet;
  19176. +
  19177. +/**
  19178. + * struct ssh_packet_ops - Callback operations for a SSH packet.
  19179. + * @release: Function called when the packet reference count reaches zero.
  19180. + * This callback must be relied upon to ensure that the packet has
  19181. + * left the transport system(s).
  19182. + * @complete: Function called when the packet is completed, either with
  19183. + * success or failure. In case of failure, the reason for the
  19184. + * failure is indicated by the value of the provided status code
  19185. + * argument. This value will be zero in case of success. Note that
  19186. + * a call to this callback does not guarantee that the packet is
  19187. + * not in use by the transport system any more.
  19188. + */
  19189. +struct ssh_packet_ops {
  19190. + void (*release)(struct ssh_packet *p);
  19191. + void (*complete)(struct ssh_packet *p, int status);
  19192. +};
  19193. +
  19194. +/**
  19195. + * struct ssh_packet - SSH transport packet.
  19196. + * @ptl: Pointer to the packet transport layer. May be %NULL if the packet
  19197. + * (or enclosing request) has not been submitted yet.
  19198. + * @refcnt: Reference count of the packet.
  19199. + * @priority: Priority of the packet. Must be computed via
  19200. + * SSH_PACKET_PRIORITY(). Must only be accessed while holding the
  19201. + * queue lock after first submission.
  19202. + * @data: Raw message data.
  19203. + * @data.len: Length of the raw message data.
  19204. + * @data.ptr: Pointer to the raw message data buffer.
  19205. + * @state: State and type flags describing current packet state (dynamic)
  19206. + * and type (static). See &enum ssh_packet_flags for possible
  19207. + * options.
  19208. + * @timestamp: Timestamp specifying when the latest transmission of a
  19209. + * currently pending packet has been started. May be %KTIME_MAX
  19210. + * before or in-between transmission attempts. Used for the packet
  19211. + * timeout implementation. Must only be accessed while holding the
  19212. + * pending lock after first submission.
  19213. + * @queue_node: The list node for the packet queue.
  19214. + * @pending_node: The list node for the set of pending packets.
  19215. + * @ops: Packet operations.
  19216. + */
  19217. +struct ssh_packet {
  19218. + struct ssh_ptl *ptl;
  19219. + struct kref refcnt;
  19220. +
  19221. + u8 priority;
  19222. +
  19223. + struct {
  19224. + size_t len;
  19225. + u8 *ptr;
  19226. + } data;
  19227. +
  19228. + unsigned long state;
  19229. + ktime_t timestamp;
  19230. +
  19231. + struct list_head queue_node;
  19232. + struct list_head pending_node;
  19233. +
  19234. + const struct ssh_packet_ops *ops;
  19235. +};
  19236. +
  19237. +struct ssh_packet *ssh_packet_get(struct ssh_packet *p);
  19238. +void ssh_packet_put(struct ssh_packet *p);
  19239. +
  19240. +/**
  19241. + * ssh_packet_set_data() - Set raw message data of packet.
  19242. + * @p: The packet for which the message data should be set.
  19243. + * @ptr: Pointer to the memory holding the message data.
  19244. + * @len: Length of the message data.
  19245. + *
  19246. + * Sets the raw message data buffer of the packet to the provided memory. The
  19247. + * memory is not copied. Instead, the caller is responsible for management
  19248. + * (i.e. allocation and deallocation) of the memory. The caller must ensure
  19249. + * that the provided memory is valid and contains a valid SSH message,
  19250. + * starting from the time of submission of the packet until the ``release``
  19251. + * callback has been called. During this time, the memory may not be altered
  19252. + * in any way.
  19253. + */
  19254. +static inline void ssh_packet_set_data(struct ssh_packet *p, u8 *ptr, size_t len)
  19255. +{
  19256. + p->data.ptr = ptr;
  19257. + p->data.len = len;
  19258. +}
  19259. +
  19260. +
  19261. +/* -- Request transport layer (rtl). ---------------------------------------- */
  19262. +
  19263. +enum ssh_request_flags {
  19264. + /* state flags */
  19265. + SSH_REQUEST_SF_LOCKED_BIT,
  19266. + SSH_REQUEST_SF_QUEUED_BIT,
  19267. + SSH_REQUEST_SF_PENDING_BIT,
  19268. + SSH_REQUEST_SF_TRANSMITTING_BIT,
  19269. + SSH_REQUEST_SF_TRANSMITTED_BIT,
  19270. + SSH_REQUEST_SF_RSPRCVD_BIT,
  19271. + SSH_REQUEST_SF_CANCELED_BIT,
  19272. + SSH_REQUEST_SF_COMPLETED_BIT,
  19273. +
  19274. + /* type flags */
  19275. + SSH_REQUEST_TY_FLUSH_BIT,
  19276. + SSH_REQUEST_TY_HAS_RESPONSE_BIT,
  19277. +
  19278. + /* mask for state flags */
  19279. + SSH_REQUEST_FLAGS_SF_MASK =
  19280. + BIT(SSH_REQUEST_SF_LOCKED_BIT)
  19281. + | BIT(SSH_REQUEST_SF_QUEUED_BIT)
  19282. + | BIT(SSH_REQUEST_SF_PENDING_BIT)
  19283. + | BIT(SSH_REQUEST_SF_TRANSMITTING_BIT)
  19284. + | BIT(SSH_REQUEST_SF_TRANSMITTED_BIT)
  19285. + | BIT(SSH_REQUEST_SF_RSPRCVD_BIT)
  19286. + | BIT(SSH_REQUEST_SF_CANCELED_BIT)
  19287. + | BIT(SSH_REQUEST_SF_COMPLETED_BIT),
  19288. +
  19289. + /* mask for type flags */
  19290. + SSH_REQUEST_FLAGS_TY_MASK =
  19291. + BIT(SSH_REQUEST_TY_FLUSH_BIT)
  19292. + | BIT(SSH_REQUEST_TY_HAS_RESPONSE_BIT),
  19293. +};
  19294. +
  19295. +struct ssh_rtl;
  19296. +struct ssh_request;
  19297. +
  19298. +/**
  19299. + * struct ssh_request_ops - Callback operations for a SSH request.
  19300. + * @release: Function called when the request's reference count reaches zero.
  19301. + * This callback must be relied upon to ensure that the request has
  19302. + * left the transport systems (both, packet an request systems).
  19303. + * @complete: Function called when the request is completed, either with
  19304. + * success or failure. The command data for the request response
  19305. + * is provided via the &struct ssh_command parameter (``cmd``),
  19306. + * the command payload of the request response via the &struct
  19307. + * ssh_span parameter (``data``).
  19308. + *
  19309. + * If the request does not have any response or has not been
  19310. + * completed with success, both ``cmd`` and ``data`` parameters will
  19311. + * be NULL. If the request response does not have any command
  19312. + * payload, the ``data`` span will be an empty (zero-length) span.
  19313. + *
  19314. + * In case of failure, the reason for the failure is indicated by
  19315. + * the value of the provided status code argument (``status``). This
  19316. + * value will be zero in case of success and a regular errno
  19317. + * otherwise.
  19318. + *
  19319. + * Note that a call to this callback does not guarantee that the
  19320. + * request is not in use by the transport systems any more.
  19321. + */
  19322. +struct ssh_request_ops {
  19323. + void (*release)(struct ssh_request *rqst);
  19324. + void (*complete)(struct ssh_request *rqst,
  19325. + const struct ssh_command *cmd,
  19326. + const struct ssam_span *data, int status);
  19327. +};
  19328. +
  19329. +/**
  19330. + * struct ssh_request - SSH transport request.
  19331. + * @packet: The underlying SSH transport packet.
  19332. + * @node: List node for the request queue and pending set.
  19333. + * @state: State and type flags describing current request state (dynamic)
  19334. + * and type (static). See &enum ssh_request_flags for possible
  19335. + * options.
  19336. + * @timestamp: Timestamp specifying when we start waiting on the response of
  19337. + * the request. This is set once the underlying packet has been
  19338. + * completed and may be %KTIME_MAX before that, or when the request
  19339. + * does not expect a response. Used for the request timeout
  19340. + * implementation.
  19341. + * @ops: Request Operations.
  19342. + */
  19343. +struct ssh_request {
  19344. + struct ssh_packet packet;
  19345. + struct list_head node;
  19346. +
  19347. + unsigned long state;
  19348. + ktime_t timestamp;
  19349. +
  19350. + const struct ssh_request_ops *ops;
  19351. +};
  19352. +
  19353. +/**
  19354. + * to_ssh_request() - Cast a SSH packet to its enclosing SSH request.
  19355. + * @p: The packet to cast.
  19356. + *
  19357. + * Casts the given &struct ssh_packet to its enclosing &struct ssh_request.
  19358. + * The caller is responsible for making sure that the packet is actually
  19359. + * wrapped in a &struct ssh_request.
  19360. + *
  19361. + * Return: Returns the &struct ssh_request wrapping the provided packet.
  19362. + */
  19363. +static inline struct ssh_request *to_ssh_request(struct ssh_packet *p)
  19364. +{
  19365. + return container_of(p, struct ssh_request, packet);
  19366. +}
  19367. +
  19368. +/**
  19369. + * ssh_request_get() - Increment reference count of request.
  19370. + * @r: The request to increment the reference count of.
  19371. + *
  19372. + * Increments the reference count of the given request by incrementing the
  19373. + * reference count of the underlying &struct ssh_packet, enclosed in it.
  19374. + *
  19375. + * See also ssh_request_put(), ssh_packet_get().
  19376. + *
  19377. + * Return: Returns the request provided as input.
  19378. + */
  19379. +static inline struct ssh_request *ssh_request_get(struct ssh_request *r)
  19380. +{
  19381. + return r ? to_ssh_request(ssh_packet_get(&r->packet)) : NULL;
  19382. +}
  19383. +
  19384. +/**
  19385. + * ssh_request_put() - Decrement reference count of request.
  19386. + * @r: The request to decrement the reference count of.
  19387. + *
  19388. + * Decrements the reference count of the given request by decrementing the
  19389. + * reference count of the underlying &struct ssh_packet, enclosed in it. If
  19390. + * the reference count reaches zero, the ``release`` callback specified in the
  19391. + * request's &struct ssh_request_ops, i.e. ``r->ops->release``, will be
  19392. + * called.
  19393. + *
  19394. + * See also ssh_request_get(), ssh_packet_put().
  19395. + */
  19396. +static inline void ssh_request_put(struct ssh_request *r)
  19397. +{
  19398. + if (r)
  19399. + ssh_packet_put(&r->packet);
  19400. +}
  19401. +
  19402. +/**
  19403. + * ssh_request_set_data() - Set raw message data of request.
  19404. + * @r: The request for which the message data should be set.
  19405. + * @ptr: Pointer to the memory holding the message data.
  19406. + * @len: Length of the message data.
  19407. + *
  19408. + * Sets the raw message data buffer of the underlying packet to the specified
  19409. + * buffer. Does not copy the actual message data, just sets the buffer pointer
  19410. + * and length. Refer to ssh_packet_set_data() for more details.
  19411. + */
  19412. +static inline void ssh_request_set_data(struct ssh_request *r, u8 *ptr, size_t len)
  19413. +{
  19414. + ssh_packet_set_data(&r->packet, ptr, len);
  19415. +}
  19416. +
  19417. +#endif /* _LINUX_SURFACE_AGGREGATOR_SERIAL_HUB_H */
  19418. diff --git a/include/uapi/linux/surface_aggregator/cdev.h b/include/uapi/linux/surface_aggregator/cdev.h
  19419. new file mode 100644
  19420. index 000000000000..fbcce04abfe9
  19421. --- /dev/null
  19422. +++ b/include/uapi/linux/surface_aggregator/cdev.h
  19423. @@ -0,0 +1,78 @@
  19424. +/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */
  19425. +/*
  19426. + * Surface System Aggregator Module (SSAM) user-space EC interface.
  19427. + *
  19428. + * Definitions, structs, and IOCTLs for the /dev/surface/aggregator misc
  19429. + * device. This device provides direct user-space access to the SSAM EC.
  19430. + * Intended for debugging and development.
  19431. + *
  19432. + * Copyright (C) 2020 Maximilian Luz <luzmaximilian@gmail.com>
  19433. + */
  19434. +
  19435. +#ifndef _UAPI_LINUX_SURFACE_AGGREGATOR_CDEV_H
  19436. +#define _UAPI_LINUX_SURFACE_AGGREGATOR_CDEV_H
  19437. +
  19438. +#include <linux/ioctl.h>
  19439. +#include <linux/types.h>
  19440. +
  19441. +/**
  19442. + * enum ssam_cdev_request_flags - Request flags for SSAM cdev request IOCTL.
  19443. + *
  19444. + * @SSAM_CDEV_REQUEST_HAS_RESPONSE:
  19445. + * Specifies that the request expects a response. If not set, the request
  19446. + * will be directly completed after its underlying packet has been
  19447. + * transmitted. If set, the request transport system waits for a response
  19448. + * of the request.
  19449. + *
  19450. + * @SSAM_CDEV_REQUEST_UNSEQUENCED:
  19451. + * Specifies that the request should be transmitted via an unsequenced
  19452. + * packet. If set, the request must not have a response, meaning that this
  19453. + * flag and the %SSAM_CDEV_REQUEST_HAS_RESPONSE flag are mutually
  19454. + * exclusive.
  19455. + */
  19456. +enum ssam_cdev_request_flags {
  19457. + SSAM_CDEV_REQUEST_HAS_RESPONSE = 0x01,
  19458. + SSAM_CDEV_REQUEST_UNSEQUENCED = 0x02,
  19459. +};
  19460. +
  19461. +/**
  19462. + * struct ssam_cdev_request - Controller request IOCTL argument.
  19463. + * @target_category: Target category of the SAM request.
  19464. + * @target_id: Target ID of the SAM request.
  19465. + * @command_id: Command ID of the SAM request.
  19466. + * @instance_id: Instance ID of the SAM request.
  19467. + * @flags: Request flags (see &enum ssam_cdev_request_flags).
  19468. + * @status: Request status (output).
  19469. + * @payload: Request payload (input data).
  19470. + * @payload.data: Pointer to request payload data.
  19471. + * @payload.length: Length of request payload data (in bytes).
  19472. + * @response: Request response (output data).
  19473. + * @response.data: Pointer to response buffer.
  19474. + * @response.length: On input: Capacity of response buffer (in bytes).
  19475. + * On output: Length of request response (number of bytes
  19476. + * in the buffer that are actually used).
  19477. + */
  19478. +struct ssam_cdev_request {
  19479. + __u8 target_category;
  19480. + __u8 target_id;
  19481. + __u8 command_id;
  19482. + __u8 instance_id;
  19483. + __u16 flags;
  19484. + __s16 status;
  19485. +
  19486. + struct {
  19487. + __u64 data;
  19488. + __u16 length;
  19489. + __u8 __pad[6];
  19490. + } payload;
  19491. +
  19492. + struct {
  19493. + __u64 data;
  19494. + __u16 length;
  19495. + __u8 __pad[6];
  19496. + } response;
  19497. +} __attribute__((__packed__));
  19498. +
  19499. +#define SSAM_CDEV_REQUEST _IOWR(0xA5, 1, struct ssam_cdev_request)
  19500. +
  19501. +#endif /* _UAPI_LINUX_SURFACE_AGGREGATOR_CDEV_H */
  19502. diff --git a/include/uapi/linux/surface_aggregator/dtx.h b/include/uapi/linux/surface_aggregator/dtx.h
  19503. new file mode 100644
  19504. index 000000000000..fc0ba6cbe3e8
  19505. --- /dev/null
  19506. +++ b/include/uapi/linux/surface_aggregator/dtx.h
  19507. @@ -0,0 +1,146 @@
  19508. +/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */
  19509. +/*
  19510. + * Surface DTX (clipboard detachment system driver) user-space interface.
  19511. + *
  19512. + * Definitions, structs, and IOCTLs for the /dev/surface/dtx misc device. This
  19513. + * device allows user-space to control the clipboard detachment process on
  19514. + * Surface Book series devices.
  19515. + *
  19516. + * Copyright (C) 2020 Maximilian Luz <luzmaximilian@gmail.com>
  19517. + */
  19518. +
  19519. +#ifndef _UAPI_LINUX_SURFACE_AGGREGATOR_DTX_H
  19520. +#define _UAPI_LINUX_SURFACE_AGGREGATOR_DTX_H
  19521. +
  19522. +#include <linux/ioctl.h>
  19523. +#include <linux/types.h>
  19524. +
  19525. +/* Status/error categories */
  19526. +#define SDTX_CATEGORY_STATUS 0x0000
  19527. +#define SDTX_CATEGORY_RUNTIME_ERROR 0x1000
  19528. +#define SDTX_CATEGORY_HARDWARE_ERROR 0x2000
  19529. +#define SDTX_CATEGORY_UNKNOWN 0xf000
  19530. +
  19531. +#define SDTX_CATEGORY_MASK 0xf000
  19532. +#define SDTX_CATEGORY(value) ((value) & SDTX_CATEGORY_MASK)
  19533. +
  19534. +#define SDTX_STATUS(code) ((code) | SDTX_CATEGORY_STATUS)
  19535. +#define SDTX_ERR_RT(code) ((code) | SDTX_CATEGORY_RUNTIME_ERROR)
  19536. +#define SDTX_ERR_HW(code) ((code) | SDTX_CATEGORY_HARDWARE_ERROR)
  19537. +#define SDTX_UNKNOWN(code) ((code) | SDTX_CATEGORY_UNKNOWN)
  19538. +
  19539. +#define SDTX_SUCCESS(value) (SDTX_CATEGORY(value) == SDTX_CATEGORY_STATUS)
  19540. +
  19541. +/* Latch status values */
  19542. +#define SDTX_LATCH_CLOSED SDTX_STATUS(0x00)
  19543. +#define SDTX_LATCH_OPENED SDTX_STATUS(0x01)
  19544. +
  19545. +/* Base state values */
  19546. +#define SDTX_BASE_DETACHED SDTX_STATUS(0x00)
  19547. +#define SDTX_BASE_ATTACHED SDTX_STATUS(0x01)
  19548. +
  19549. +/* Runtime errors (non-critical) */
  19550. +#define SDTX_DETACH_NOT_FEASIBLE SDTX_ERR_RT(0x01)
  19551. +#define SDTX_DETACH_TIMEDOUT SDTX_ERR_RT(0x02)
  19552. +
  19553. +/* Hardware errors (critical) */
  19554. +#define SDTX_ERR_FAILED_TO_OPEN SDTX_ERR_HW(0x01)
  19555. +#define SDTX_ERR_FAILED_TO_REMAIN_OPEN SDTX_ERR_HW(0x02)
  19556. +#define SDTX_ERR_FAILED_TO_CLOSE SDTX_ERR_HW(0x03)
  19557. +
  19558. +/* Base types */
  19559. +#define SDTX_DEVICE_TYPE_HID 0x0100
  19560. +#define SDTX_DEVICE_TYPE_SSH 0x0200
  19561. +
  19562. +#define SDTX_DEVICE_TYPE_MASK 0x0f00
  19563. +#define SDTX_DEVICE_TYPE(value) ((value) & SDTX_DEVICE_TYPE_MASK)
  19564. +
  19565. +#define SDTX_BASE_TYPE_HID(id) ((id) | SDTX_DEVICE_TYPE_HID)
  19566. +#define SDTX_BASE_TYPE_SSH(id) ((id) | SDTX_DEVICE_TYPE_SSH)
  19567. +
  19568. +/**
  19569. + * enum sdtx_device_mode - Mode describing how (and if) the clipboard is
  19570. + * attached to the base of the device.
  19571. + * @SDTX_DEVICE_MODE_TABLET: The clipboard is detached from the base and the
  19572. + * device operates as tablet.
  19573. + * @SDTX_DEVICE_MODE_LAPTOP: The clipboard is attached normally to the base
  19574. + * and the device operates as laptop.
  19575. + * @SDTX_DEVICE_MODE_STUDIO: The clipboard is attached to the base in reverse.
  19576. + * The device operates as tablet with keyboard and
  19577. + * touchpad deactivated, however, the base battery
  19578. + * and, if present in the specific device model, dGPU
  19579. + * are available to the system.
  19580. + */
  19581. +enum sdtx_device_mode {
  19582. + SDTX_DEVICE_MODE_TABLET = 0x00,
  19583. + SDTX_DEVICE_MODE_LAPTOP = 0x01,
  19584. + SDTX_DEVICE_MODE_STUDIO = 0x02,
  19585. +};
  19586. +
  19587. +/**
  19588. + * struct sdtx_event - Event provided by reading from the DTX device file.
  19589. + * @length: Length of the event payload, in bytes.
  19590. + * @code: Event code, detailing what type of event this is.
  19591. + * @data: Payload of the event, containing @length bytes.
  19592. + *
  19593. + * See &enum sdtx_event_code for currently valid event codes.
  19594. + */
  19595. +struct sdtx_event {
  19596. + __u16 length;
  19597. + __u16 code;
  19598. + __u8 data[];
  19599. +} __attribute__((__packed__));
  19600. +
  19601. +/**
  19602. + * enum sdtx_event_code - Code describing the type of an event.
  19603. + * @SDTX_EVENT_REQUEST: Detachment request event type.
  19604. + * @SDTX_EVENT_CANCEL: Cancel detachment process event type.
  19605. + * @SDTX_EVENT_BASE_CONNECTION: Base/clipboard connection change event type.
  19606. + * @SDTX_EVENT_LATCH_STATUS: Latch status change event type.
  19607. + * @SDTX_EVENT_DEVICE_MODE: Device mode change event type.
  19608. + *
  19609. + * Used in @struct sdtx_event to describe the type of the event. Further event
  19610. + * codes are reserved for future use. Any event parser should be able to
  19611. + * gracefully handle unknown events, i.e. by simply skipping them.
  19612. + *
  19613. + * Consult the DTX user-space interface documentation for details regarding
  19614. + * the individual event types.
  19615. + */
  19616. +enum sdtx_event_code {
  19617. + SDTX_EVENT_REQUEST = 1,
  19618. + SDTX_EVENT_CANCEL = 2,
  19619. + SDTX_EVENT_BASE_CONNECTION = 3,
  19620. + SDTX_EVENT_LATCH_STATUS = 4,
  19621. + SDTX_EVENT_DEVICE_MODE = 5,
  19622. +};
  19623. +
  19624. +/**
  19625. + * struct sdtx_base_info - Describes if and what type of base is connected.
  19626. + * @state: The state of the connection. Valid values are %SDTX_BASE_DETACHED,
  19627. + * %SDTX_BASE_ATTACHED, and %SDTX_DETACH_NOT_FEASIBLE (in case a base
  19628. + * is attached but low clipboard battery prevents detachment). Other
  19629. + * values are currently reserved.
  19630. + * @base_id: The type of base connected. Zero if no base is connected.
  19631. + */
  19632. +struct sdtx_base_info {
  19633. + __u16 state;
  19634. + __u16 base_id;
  19635. +} __attribute__((__packed__));
  19636. +
  19637. +/* IOCTLs */
  19638. +#define SDTX_IOCTL_EVENTS_ENABLE _IO(0xa5, 0x21)
  19639. +#define SDTX_IOCTL_EVENTS_DISABLE _IO(0xa5, 0x22)
  19640. +
  19641. +#define SDTX_IOCTL_LATCH_LOCK _IO(0xa5, 0x23)
  19642. +#define SDTX_IOCTL_LATCH_UNLOCK _IO(0xa5, 0x24)
  19643. +
  19644. +#define SDTX_IOCTL_LATCH_REQUEST _IO(0xa5, 0x25)
  19645. +#define SDTX_IOCTL_LATCH_CONFIRM _IO(0xa5, 0x26)
  19646. +#define SDTX_IOCTL_LATCH_HEARTBEAT _IO(0xa5, 0x27)
  19647. +#define SDTX_IOCTL_LATCH_CANCEL _IO(0xa5, 0x28)
  19648. +
  19649. +#define SDTX_IOCTL_GET_BASE_INFO _IOR(0xa5, 0x29, struct sdtx_base_info)
  19650. +#define SDTX_IOCTL_GET_DEVICE_MODE _IOR(0xa5, 0x2a, __u16)
  19651. +#define SDTX_IOCTL_GET_LATCH_STATUS _IOR(0xa5, 0x2b, __u16)
  19652. +
  19653. +#endif /* _UAPI_LINUX_SURFACE_AGGREGATOR_DTX_H */
  19654. diff --git a/scripts/mod/devicetable-offsets.c b/scripts/mod/devicetable-offsets.c
  19655. index bcff122d0dc8..4339377ad929 100644
  19656. --- a/scripts/mod/devicetable-offsets.c
  19657. +++ b/scripts/mod/devicetable-offsets.c
  19658. @@ -245,8 +245,9 @@ int main(void)
  19659. DEVID(ssam_device_id);
  19660. DEVID_FIELD(ssam_device_id, match_flags);
  19661. + DEVID_FIELD(ssam_device_id, domain);
  19662. DEVID_FIELD(ssam_device_id, category);
  19663. - DEVID_FIELD(ssam_device_id, channel);
  19664. + DEVID_FIELD(ssam_device_id, target);
  19665. DEVID_FIELD(ssam_device_id, instance);
  19666. DEVID_FIELD(ssam_device_id, function);
  19667. diff --git a/scripts/mod/file2alias.c b/scripts/mod/file2alias.c
  19668. index a6c583362b92..5b79fdc42641 100644
  19669. --- a/scripts/mod/file2alias.c
  19670. +++ b/scripts/mod/file2alias.c
  19671. @@ -1368,20 +1368,22 @@ static int do_mhi_entry(const char *filename, void *symval, char *alias)
  19672. return 1;
  19673. }
  19674. -/* Looks like: ssam:cNtNiNfN
  19675. +/*
  19676. + * Looks like: ssam:dNcNtNiNfN
  19677. *
  19678. * N is exactly 2 digits, where each is an upper-case hex digit.
  19679. */
  19680. static int do_ssam_entry(const char *filename, void *symval, char *alias)
  19681. {
  19682. DEF_FIELD(symval, ssam_device_id, match_flags);
  19683. + DEF_FIELD(symval, ssam_device_id, domain);
  19684. DEF_FIELD(symval, ssam_device_id, category);
  19685. - DEF_FIELD(symval, ssam_device_id, channel);
  19686. + DEF_FIELD(symval, ssam_device_id, target);
  19687. DEF_FIELD(symval, ssam_device_id, instance);
  19688. DEF_FIELD(symval, ssam_device_id, function);
  19689. - sprintf(alias, "ssam:c%02X", category);
  19690. - ADD(alias, "t", match_flags & SSAM_MATCH_CHANNEL, channel);
  19691. + sprintf(alias, "ssam:d%02Xc%02X", domain, category);
  19692. + ADD(alias, "t", match_flags & SSAM_MATCH_TARGET, target);
  19693. ADD(alias, "i", match_flags & SSAM_MATCH_INSTANCE, instance);
  19694. ADD(alias, "f", match_flags & SSAM_MATCH_FUNCTION, function);
  19695. --
  19696. 2.29.2