0006-surface-sam.patch 598 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594
  1. From ef00777fa69ff655ce11b70ccb321774ec82659d Mon Sep 17 00:00:00 2001
  2. From: Maximilian Luz <luzmaximilian@gmail.com>
  3. Date: Thu, 29 Oct 2020 22:04:38 +0100
  4. Subject: [PATCH] PCI: Allow D3cold for hot-plug ports on Surface Books
  5. The Microsoft Surface Book series of devices have a tablet part (so
  6. called clipboard) that can be detached from the base of the device.
  7. While the clipboard contains the CPU, the base can contain a discrete
  8. GPU (dGPU). This dGPU is connected via a PCIe hot-plug port.
  9. Currently D3cold is disallowed for all hot-plug ports. On the Surface
  10. Book 2 and 3, this leads to increased power consumption during suspend
  11. and when the dGPU is not used (i.e. runtime suspended). This can be
  12. observed not only in battery drain, but also by the dGPU getting notably
  13. warm while suspended and not in D3cold.
  14. Testing shows that the Surface Books behave well with D3cold enabled for
  15. hot-plug ports, alleviating the aforementioned issues. Thus white-list
  16. D3cold for hot-plug ports on those devices.
  17. Note: PCIe hot-plug signalling while the device is in D3cold is handled
  18. via ACPI, out-of-band interrupts, and the surface_hotplug driver
  19. (combined). The device will work without the surface_hotplug driver,
  20. however, device removal/addition will only be detected on device resume.
  21. Signed-off-by: Maximilian Luz <luzmaximilian@gmail.com>
  22. Patchset: surface-sam
  23. ---
  24. drivers/pci/pci.c | 31 +++++++++++++++++++++++++++++--
  25. 1 file changed, 29 insertions(+), 2 deletions(-)
  26. diff --git a/drivers/pci/pci.c b/drivers/pci/pci.c
  27. index c9338f914a0e..94371684783e 100644
  28. --- a/drivers/pci/pci.c
  29. +++ b/drivers/pci/pci.c
  30. @@ -2679,6 +2679,32 @@ static const struct dmi_system_id bridge_d3_blacklist[] = {
  31. { }
  32. };
  33. +static const struct dmi_system_id bridge_d3_hotplug_whitelist[] = {
  34. +#ifdef CONFIG_X86
  35. + {
  36. + /*
  37. + * Microsoft Surface Books have a hot-plug root port for the
  38. + * discrete GPU (the device containing it can be detached form
  39. + * the top-part, containing the cpu).
  40. + *
  41. + * If this discrete GPU is not transitioned into D3cold for
  42. + * suspend, the device will become notably warm and also
  43. + * consume a lot more power than desirable.
  44. + *
  45. + * We assume that since those devices have been confirmed
  46. + * working with D3, future Surface devices will too. So let's
  47. + * keep this match generic.
  48. + */
  49. + .ident = "Microsoft Surface",
  50. + .matches = {
  51. + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"),
  52. + DMI_MATCH(DMI_PRODUCT_NAME, "Surface"),
  53. + },
  54. + },
  55. +#endif
  56. + { }
  57. +};
  58. +
  59. /**
  60. * pci_bridge_d3_possible - Is it possible to put the bridge into D3
  61. * @bridge: Bridge to check
  62. @@ -2719,10 +2745,11 @@ bool pci_bridge_d3_possible(struct pci_dev *bridge)
  63. /*
  64. * Hotplug ports handled natively by the OS were not validated
  65. * by vendors for runtime D3 at least until 2018 because there
  66. - * was no OS support.
  67. + * was no OS support. Explicitly whitelist systems that have
  68. + * been confirmed working.
  69. */
  70. if (bridge->is_hotplug_bridge)
  71. - return false;
  72. + return dmi_check_system(bridge_d3_hotplug_whitelist);
  73. if (dmi_check_system(bridge_d3_blacklist))
  74. return false;
  75. --
  76. 2.29.2
  77. From 901ceb17f1b911bb545fa41285344bb7573fb326 Mon Sep 17 00:00:00 2001
  78. From: Maximilian Luz <luzmaximilian@gmail.com>
  79. Date: Mon, 9 Nov 2020 14:23:00 +0100
  80. Subject: [PATCH] PCI: Run platform power transition on initial D0 entry
  81. On some devices and platforms, the initial platform power state is not
  82. in sync with the power state of the PCI device.
  83. pci_enable_device_flags() updates the state of a PCI device by reading
  84. from the the PCI_PM_CTRL register. This may change the stored power
  85. state of the device without running the appropriate platform power
  86. transition.
  87. Due to the stored power-state being changed, the later call to
  88. pci_set_power_state(..., PCI_D0) in do_pci_enable_device() can evaluate
  89. to a no-op if the stored state has been changed to D0 via that. This
  90. will then prevent the appropriate platform power transition to be run,
  91. which can on some devices and platforms lead to platform and PCI power
  92. state being entirely different, i.e. out-of-sync. On ACPI platforms,
  93. this can lead to power resources not being turned on, even though they
  94. are marked as required for D0.
  95. Specifically, on the Microsoft Surface Book 2 and 3, some ACPI power
  96. regions that should be "on" for the D0 state (and others) are
  97. initialized as "off" in ACPI, whereas the PCI device is in D0. As the
  98. state is updated in pci_enable_device_flags() without ensuring that the
  99. platform state is also updated, the power resource will never be
  100. properly turned on. Instead, it lives in a sort of on-but-marked-as-off
  101. zombie-state, which confuses things down the line when attempting to
  102. transition the device into D3cold: As the resource is already marked as
  103. off, it won't be turned off and the device does not fully enter D3cold,
  104. causing increased power consumption during (runtime-)suspend.
  105. By replacing pci_set_power_state() in do_pci_enable_device() with
  106. pci_power_up(), we can force pci_platform_power_transition() to be
  107. called, which will then check if the platform power state needs updating
  108. and appropriate actions need to be taken.
  109. Signed-off-by: Maximilian Luz <luzmaximilian@gmail.com>
  110. Patchset: surface-sam
  111. ---
  112. drivers/pci/pci.c | 2 +-
  113. 1 file changed, 1 insertion(+), 1 deletion(-)
  114. diff --git a/drivers/pci/pci.c b/drivers/pci/pci.c
  115. index 94371684783e..56c564c698bd 100644
  116. --- a/drivers/pci/pci.c
  117. +++ b/drivers/pci/pci.c
  118. @@ -1664,7 +1664,7 @@ static int do_pci_enable_device(struct pci_dev *dev, int bars)
  119. u16 cmd;
  120. u8 pin;
  121. - err = pci_set_power_state(dev, PCI_D0);
  122. + err = pci_power_up(dev);
  123. if (err < 0 && err != -EIO)
  124. return err;
  125. --
  126. 2.29.2
  127. From e025027564ad4c665df448213db6041640b0eb5e Mon Sep 17 00:00:00 2001
  128. From: Maximilian Luz <luzmaximilian@gmail.com>
  129. Date: Sat, 31 Oct 2020 20:46:33 +0100
  130. Subject: [PATCH] PCI: Add sysfs attribute for PCI device power state
  131. While most PCI power-states can be queried from user-space via lspci,
  132. this has some limits. Specifically, lspci fails to provide an accurate
  133. value when the device is in D3cold as it has to resume the device before
  134. it can access its power state via the configuration space, leading to it
  135. reporting D0 or another on-state. Thus lspci can, for example, not be
  136. used to diagnose power-consumption issues for devices that can enter
  137. D3cold or to ensure that devices properly enter D3cold at all.
  138. To alleviate this issue, introduce a new sysfs device attribute for the
  139. PCI power state, showing the current power state as seen by the kernel.
  140. Signed-off-by: Maximilian Luz <luzmaximilian@gmail.com>
  141. Patchset: surface-sam
  142. ---
  143. Documentation/ABI/testing/sysfs-bus-pci | 9 +++++++++
  144. drivers/pci/pci-sysfs.c | 12 ++++++++++++
  145. 2 files changed, 21 insertions(+)
  146. diff --git a/Documentation/ABI/testing/sysfs-bus-pci b/Documentation/ABI/testing/sysfs-bus-pci
  147. index 450296cc7948..881040af2611 100644
  148. --- a/Documentation/ABI/testing/sysfs-bus-pci
  149. +++ b/Documentation/ABI/testing/sysfs-bus-pci
  150. @@ -360,3 +360,12 @@ Contact: Heiner Kallweit <hkallweit1@gmail.com>
  151. Description: If ASPM is supported for an endpoint, these files can be
  152. used to disable or enable the individual power management
  153. states. Write y/1/on to enable, n/0/off to disable.
  154. +
  155. +What: /sys/bus/pci/devices/.../power_state
  156. +Date: November 2020
  157. +Contact: Linux PCI developers <linux-pci@vger.kernel.org>
  158. +Description:
  159. + This file contains the current PCI power state of the device.
  160. + The value comes from the PCI kernel device state and can be one
  161. + of: "unknown", "error", "D0", D1", "D2", "D3hot", "D3cold".
  162. + The file is read only.
  163. diff --git a/drivers/pci/pci-sysfs.c b/drivers/pci/pci-sysfs.c
  164. index 6d78df981d41..17f186ce8e87 100644
  165. --- a/drivers/pci/pci-sysfs.c
  166. +++ b/drivers/pci/pci-sysfs.c
  167. @@ -124,6 +124,17 @@ static ssize_t cpulistaffinity_show(struct device *dev,
  168. }
  169. static DEVICE_ATTR_RO(cpulistaffinity);
  170. +/* PCI power state */
  171. +static ssize_t power_state_show(struct device *dev,
  172. + struct device_attribute *attr, char *buf)
  173. +{
  174. + struct pci_dev *pci_dev = to_pci_dev(dev);
  175. + pci_power_t state = READ_ONCE(pci_dev->current_state);
  176. +
  177. + return sprintf(buf, "%s\n", pci_power_name(state));
  178. +}
  179. +static DEVICE_ATTR_RO(power_state);
  180. +
  181. /* show resources */
  182. static ssize_t resource_show(struct device *dev, struct device_attribute *attr,
  183. char *buf)
  184. @@ -581,6 +592,7 @@ static ssize_t driver_override_show(struct device *dev,
  185. static DEVICE_ATTR_RW(driver_override);
  186. static struct attribute *pci_dev_attrs[] = {
  187. + &dev_attr_power_state.attr,
  188. &dev_attr_resource.attr,
  189. &dev_attr_vendor.attr,
  190. &dev_attr_device.attr,
  191. --
  192. 2.29.2
  193. From f87195e108325927ad44baf3ed464d3c878c85c0 Mon Sep 17 00:00:00 2001
  194. From: Maximilian Luz <luzmaximilian@gmail.com>
  195. Date: Mon, 17 Aug 2020 01:23:20 +0200
  196. Subject: [PATCH] misc: surface_sam: Add file2alias support for Surface SAM
  197. devices
  198. Implement file2alias support for Surface System Aggregator Module (SSAM)
  199. devices. This allows modules to be auto-loaded for specific devices via
  200. their respective module alias.
  201. Patchset: surface-sam
  202. ---
  203. include/linux/mod_devicetable.h | 17 +++++++++++++++++
  204. scripts/mod/devicetable-offsets.c | 7 +++++++
  205. scripts/mod/file2alias.c | 21 +++++++++++++++++++++
  206. 3 files changed, 45 insertions(+)
  207. diff --git a/include/linux/mod_devicetable.h b/include/linux/mod_devicetable.h
  208. index e14cbe444afc..a35f82fb36da 100644
  209. --- a/include/linux/mod_devicetable.h
  210. +++ b/include/linux/mod_devicetable.h
  211. @@ -836,4 +836,21 @@ struct mhi_device_id {
  212. kernel_ulong_t driver_data;
  213. };
  214. +/* Surface System Aggregator Module */
  215. +
  216. +#define SSAM_MATCH_CHANNEL 0x1
  217. +#define SSAM_MATCH_INSTANCE 0x2
  218. +#define SSAM_MATCH_FUNCTION 0x4
  219. +
  220. +struct ssam_device_id {
  221. + __u8 match_flags;
  222. +
  223. + __u8 category;
  224. + __u8 channel;
  225. + __u8 instance;
  226. + __u8 function;
  227. +
  228. + kernel_ulong_t driver_data;
  229. +};
  230. +
  231. #endif /* LINUX_MOD_DEVICETABLE_H */
  232. diff --git a/scripts/mod/devicetable-offsets.c b/scripts/mod/devicetable-offsets.c
  233. index 010be8ba2116..35b9899b0b0f 100644
  234. --- a/scripts/mod/devicetable-offsets.c
  235. +++ b/scripts/mod/devicetable-offsets.c
  236. @@ -241,5 +241,12 @@ int main(void)
  237. DEVID(mhi_device_id);
  238. DEVID_FIELD(mhi_device_id, chan);
  239. + DEVID(ssam_device_id);
  240. + DEVID_FIELD(ssam_device_id, match_flags);
  241. + DEVID_FIELD(ssam_device_id, category);
  242. + DEVID_FIELD(ssam_device_id, channel);
  243. + DEVID_FIELD(ssam_device_id, instance);
  244. + DEVID_FIELD(ssam_device_id, function);
  245. +
  246. return 0;
  247. }
  248. diff --git a/scripts/mod/file2alias.c b/scripts/mod/file2alias.c
  249. index 9599e2a3f1e6..079672e0747a 100644
  250. --- a/scripts/mod/file2alias.c
  251. +++ b/scripts/mod/file2alias.c
  252. @@ -1364,6 +1364,26 @@ static int do_mhi_entry(const char *filename, void *symval, char *alias)
  253. return 1;
  254. }
  255. +/* Looks like: ssam:cNtNiNfN
  256. + *
  257. + * N is exactly 2 digits, where each is an upper-case hex digit.
  258. + */
  259. +static int do_ssam_entry(const char *filename, void *symval, char *alias)
  260. +{
  261. + DEF_FIELD(symval, ssam_device_id, match_flags);
  262. + DEF_FIELD(symval, ssam_device_id, category);
  263. + DEF_FIELD(symval, ssam_device_id, channel);
  264. + DEF_FIELD(symval, ssam_device_id, instance);
  265. + DEF_FIELD(symval, ssam_device_id, function);
  266. +
  267. + sprintf(alias, "ssam:c%02X", category);
  268. + ADD(alias, "t", match_flags & SSAM_MATCH_CHANNEL, channel);
  269. + ADD(alias, "i", match_flags & SSAM_MATCH_INSTANCE, instance);
  270. + ADD(alias, "f", match_flags & SSAM_MATCH_FUNCTION, function);
  271. +
  272. + return 1;
  273. +}
  274. +
  275. /* Does namelen bytes of name exactly match the symbol? */
  276. static bool sym_is(const char *name, unsigned namelen, const char *symbol)
  277. {
  278. @@ -1438,6 +1458,7 @@ static const struct devtable devtable[] = {
  279. {"tee", SIZE_tee_client_device_id, do_tee_entry},
  280. {"wmi", SIZE_wmi_device_id, do_wmi_entry},
  281. {"mhi", SIZE_mhi_device_id, do_mhi_entry},
  282. + {"ssam", SIZE_ssam_device_id, do_ssam_entry},
  283. };
  284. /* Create MODULE_ALIAS() statements.
  285. --
  286. 2.29.2
  287. From 7debd8e51563a4742e06c56857891a13227211b5 Mon Sep 17 00:00:00 2001
  288. From: Maximilian Luz <luzmaximilian@gmail.com>
  289. Date: Mon, 17 Aug 2020 01:44:30 +0200
  290. Subject: [PATCH] misc: Add support for Surface System Aggregator Module
  291. Add support for the Surface System Aggregator Module (SSAM), an embedded
  292. controller that can be found on 5th and later generation Microsoft
  293. Surface devices. The responsibilities of this EC vary from device to
  294. device. It provides battery information on all 5th and later generation
  295. devices, temperature sensor and cooling capability access, functionality
  296. for clipboard detaching on the Surface Books (2 and 3), as well as
  297. HID-over-SSAM input devices, including keyboard on the Surface Laptop 1
  298. and 2, and keyboard as well as touchpad input on the Surface Laptop 3
  299. and Surface Book 3.
  300. Patchset: surface-sam
  301. ---
  302. Documentation/driver-api/index.rst | 1 +
  303. .../surface_aggregator/client-api.rst | 38 +
  304. .../driver-api/surface_aggregator/client.rst | 394 +++
  305. .../surface_aggregator/clients/cdev.rst | 85 +
  306. .../surface_aggregator/clients/dtx.rst | 712 +++++
  307. .../surface_aggregator/clients/index.rst | 22 +
  308. .../surface_aggregator/clients/san.rst | 44 +
  309. .../driver-api/surface_aggregator/index.rst | 21 +
  310. .../surface_aggregator/internal-api.rst | 67 +
  311. .../surface_aggregator/internal.rst | 50 +
  312. .../surface_aggregator/overview.rst | 76 +
  313. .../driver-api/surface_aggregator/ssh.rst | 343 +++
  314. drivers/misc/Kconfig | 1 +
  315. drivers/misc/Makefile | 1 +
  316. drivers/misc/surface_aggregator/Kconfig | 67 +
  317. drivers/misc/surface_aggregator/Makefile | 18 +
  318. drivers/misc/surface_aggregator/bus.c | 424 +++
  319. drivers/misc/surface_aggregator/bus.h | 27 +
  320. .../misc/surface_aggregator/clients/Kconfig | 151 +
  321. .../misc/surface_aggregator/clients/Makefile | 11 +
  322. .../clients/surface_acpi_notify.c | 884 ++++++
  323. .../clients/surface_aggregator_cdev.c | 299 ++
  324. .../clients/surface_aggregator_registry.c | 656 +++++
  325. .../clients/surface_battery.c | 1192 ++++++++
  326. .../surface_aggregator/clients/surface_dtx.c | 1279 +++++++++
  327. .../surface_aggregator/clients/surface_hid.c | 922 ++++++
  328. .../clients/surface_hotplug.c | 269 ++
  329. .../clients/surface_perfmode.c | 122 +
  330. drivers/misc/surface_aggregator/controller.c | 2557 +++++++++++++++++
  331. drivers/misc/surface_aggregator/controller.h | 288 ++
  332. drivers/misc/surface_aggregator/core.c | 831 ++++++
  333. drivers/misc/surface_aggregator/ssh_msgb.h | 201 ++
  334. .../surface_aggregator/ssh_packet_layer.c | 2009 +++++++++++++
  335. .../surface_aggregator/ssh_packet_layer.h | 175 ++
  336. drivers/misc/surface_aggregator/ssh_parser.c | 229 ++
  337. drivers/misc/surface_aggregator/ssh_parser.h | 157 +
  338. .../surface_aggregator/ssh_request_layer.c | 1254 ++++++++
  339. .../surface_aggregator/ssh_request_layer.h | 142 +
  340. drivers/misc/surface_aggregator/trace.h | 625 ++++
  341. include/linux/mod_devicetable.h | 5 +-
  342. include/linux/surface_acpi_notify.h | 39 +
  343. include/linux/surface_aggregator/controller.h | 832 ++++++
  344. include/linux/surface_aggregator/device.h | 430 +++
  345. include/linux/surface_aggregator/serial_hub.h | 659 +++++
  346. include/uapi/linux/surface_aggregator/cdev.h | 58 +
  347. include/uapi/linux/surface_aggregator/dtx.h | 150 +
  348. scripts/mod/devicetable-offsets.c | 3 +-
  349. scripts/mod/file2alias.c | 10 +-
  350. 48 files changed, 18823 insertions(+), 7 deletions(-)
  351. create mode 100644 Documentation/driver-api/surface_aggregator/client-api.rst
  352. create mode 100644 Documentation/driver-api/surface_aggregator/client.rst
  353. create mode 100644 Documentation/driver-api/surface_aggregator/clients/cdev.rst
  354. create mode 100644 Documentation/driver-api/surface_aggregator/clients/dtx.rst
  355. create mode 100644 Documentation/driver-api/surface_aggregator/clients/index.rst
  356. create mode 100644 Documentation/driver-api/surface_aggregator/clients/san.rst
  357. create mode 100644 Documentation/driver-api/surface_aggregator/index.rst
  358. create mode 100644 Documentation/driver-api/surface_aggregator/internal-api.rst
  359. create mode 100644 Documentation/driver-api/surface_aggregator/internal.rst
  360. create mode 100644 Documentation/driver-api/surface_aggregator/overview.rst
  361. create mode 100644 Documentation/driver-api/surface_aggregator/ssh.rst
  362. create mode 100644 drivers/misc/surface_aggregator/Kconfig
  363. create mode 100644 drivers/misc/surface_aggregator/Makefile
  364. create mode 100644 drivers/misc/surface_aggregator/bus.c
  365. create mode 100644 drivers/misc/surface_aggregator/bus.h
  366. create mode 100644 drivers/misc/surface_aggregator/clients/Kconfig
  367. create mode 100644 drivers/misc/surface_aggregator/clients/Makefile
  368. create mode 100644 drivers/misc/surface_aggregator/clients/surface_acpi_notify.c
  369. create mode 100644 drivers/misc/surface_aggregator/clients/surface_aggregator_cdev.c
  370. create mode 100644 drivers/misc/surface_aggregator/clients/surface_aggregator_registry.c
  371. create mode 100644 drivers/misc/surface_aggregator/clients/surface_battery.c
  372. create mode 100644 drivers/misc/surface_aggregator/clients/surface_dtx.c
  373. create mode 100644 drivers/misc/surface_aggregator/clients/surface_hid.c
  374. create mode 100644 drivers/misc/surface_aggregator/clients/surface_hotplug.c
  375. create mode 100644 drivers/misc/surface_aggregator/clients/surface_perfmode.c
  376. create mode 100644 drivers/misc/surface_aggregator/controller.c
  377. create mode 100644 drivers/misc/surface_aggregator/controller.h
  378. create mode 100644 drivers/misc/surface_aggregator/core.c
  379. create mode 100644 drivers/misc/surface_aggregator/ssh_msgb.h
  380. create mode 100644 drivers/misc/surface_aggregator/ssh_packet_layer.c
  381. create mode 100644 drivers/misc/surface_aggregator/ssh_packet_layer.h
  382. create mode 100644 drivers/misc/surface_aggregator/ssh_parser.c
  383. create mode 100644 drivers/misc/surface_aggregator/ssh_parser.h
  384. create mode 100644 drivers/misc/surface_aggregator/ssh_request_layer.c
  385. create mode 100644 drivers/misc/surface_aggregator/ssh_request_layer.h
  386. create mode 100644 drivers/misc/surface_aggregator/trace.h
  387. create mode 100644 include/linux/surface_acpi_notify.h
  388. create mode 100644 include/linux/surface_aggregator/controller.h
  389. create mode 100644 include/linux/surface_aggregator/device.h
  390. create mode 100644 include/linux/surface_aggregator/serial_hub.h
  391. create mode 100644 include/uapi/linux/surface_aggregator/cdev.h
  392. create mode 100644 include/uapi/linux/surface_aggregator/dtx.h
  393. diff --git a/Documentation/driver-api/index.rst b/Documentation/driver-api/index.rst
  394. index 6567187e7687..e36363f0972b 100644
  395. --- a/Documentation/driver-api/index.rst
  396. +++ b/Documentation/driver-api/index.rst
  397. @@ -99,6 +99,7 @@ available subsections can be seen below.
  398. serial/index
  399. sm501
  400. smsc_ece1099
  401. + surface_aggregator/index
  402. switchtec
  403. sync_file
  404. vfio-mediated-device
  405. diff --git a/Documentation/driver-api/surface_aggregator/client-api.rst b/Documentation/driver-api/surface_aggregator/client-api.rst
  406. new file mode 100644
  407. index 000000000000..a1117d57036a
  408. --- /dev/null
  409. +++ b/Documentation/driver-api/surface_aggregator/client-api.rst
  410. @@ -0,0 +1,38 @@
  411. +.. SPDX-License-Identifier: GPL-2.0+
  412. +
  413. +===============================
  414. +Client Driver API Documentation
  415. +===============================
  416. +
  417. +.. contents::
  418. + :depth: 2
  419. +
  420. +
  421. +Serial Hub Communication
  422. +========================
  423. +
  424. +.. kernel-doc:: include/linux/surface_aggregator/serial_hub.h
  425. +
  426. +.. kernel-doc:: drivers/misc/surface_aggregator/ssh_packet_layer.c
  427. + :export:
  428. +
  429. +
  430. +Controller and Core Interface
  431. +=============================
  432. +
  433. +.. kernel-doc:: include/linux/surface_aggregator/controller.h
  434. +
  435. +.. kernel-doc:: drivers/misc/surface_aggregator/controller.c
  436. + :export:
  437. +
  438. +.. kernel-doc:: drivers/misc/surface_aggregator/core.c
  439. + :export:
  440. +
  441. +
  442. +Client Bus and Client Device API
  443. +================================
  444. +
  445. +.. kernel-doc:: include/linux/surface_aggregator/device.h
  446. +
  447. +.. kernel-doc:: drivers/misc/surface_aggregator/bus.c
  448. + :export:
  449. diff --git a/Documentation/driver-api/surface_aggregator/client.rst b/Documentation/driver-api/surface_aggregator/client.rst
  450. new file mode 100644
  451. index 000000000000..f1275bf53837
  452. --- /dev/null
  453. +++ b/Documentation/driver-api/surface_aggregator/client.rst
  454. @@ -0,0 +1,394 @@
  455. +.. SPDX-License-Identifier: GPL-2.0+
  456. +
  457. +.. |ssam_controller| replace:: :c:type:`struct ssam_controller <ssam_controller>`
  458. +.. |ssam_device| replace:: :c:type:`struct ssam_device <ssam_device>`
  459. +.. |ssam_device_driver| replace:: :c:type:`struct ssam_device_driver <ssam_device_driver>`
  460. +.. |ssam_client_bind| replace:: :c:func:`ssam_client_bind`
  461. +.. |ssam_client_link| replace:: :c:func:`ssam_client_link`
  462. +.. |ssam_get_controller| replace:: :c:func:`ssam_get_controller`
  463. +.. |ssam_controller_get| replace:: :c:func:`ssam_controller_get`
  464. +.. |ssam_controller_put| replace:: :c:func:`ssam_controller_put`
  465. +.. |ssam_device_alloc| replace:: :c:func:`ssam_device_alloc`
  466. +.. |ssam_device_add| replace:: :c:func:`ssam_device_add`
  467. +.. |ssam_device_remove| replace:: :c:func:`ssam_device_remove`
  468. +.. |ssam_device_driver_register| replace:: :c:func:`ssam_device_driver_register`
  469. +.. |ssam_device_driver_unregister| replace:: :c:func:`ssam_device_driver_unregister`
  470. +.. |module_ssam_device_driver| replace:: :c:func:`module_ssam_device_driver`
  471. +.. |SSAM_DEVICE| replace:: :c:func:`SSAM_DEVICE`
  472. +.. |ssam_notifier_register| replace:: :c:func:`ssam_notifier_register`
  473. +.. |ssam_notifier_unregister| replace:: :c:func:`ssam_notifier_unregister`
  474. +.. |ssam_request_sync| replace:: :c:func:`ssam_request_sync`
  475. +.. |ssam_event_mask| replace:: :c:type:`enum ssam_event_mask <ssam_event_mask>`
  476. +
  477. +
  478. +======================
  479. +Writing Client Drivers
  480. +======================
  481. +
  482. +For the API documentation, refer to:
  483. +
  484. +.. toctree::
  485. + :maxdepth: 2
  486. +
  487. + client-api
  488. +
  489. +
  490. +Overview
  491. +========
  492. +
  493. +Client drivers can be set up in two main ways, depending on how the
  494. +corresponding device is made available to the system. We specifically
  495. +differentiate between devices that are presented to the system via one of
  496. +the conventional ways, e.g. as platform devices via ACPI, and devices that
  497. +are non-discoverable and instead need to be explicitly provided by some
  498. +other mechanism, as discussed further below.
  499. +
  500. +
  501. +Non-SSAM Client Drivers
  502. +=======================
  503. +
  504. +All communication with the SAM EC is handled via the |ssam_controller|
  505. +representing that EC to the kernel. Drivers targetting a non-SSAM device
  506. +(and thus not being a |ssam_device_driver|) need to explicitly establish a
  507. +connection/relation to that controller. This can be done via the
  508. +|ssam_client_bind| function. Said function returns a reference to the SSAM
  509. +controller, but, more importantly, also establishes a device link between
  510. +client device and controller (this can also be done separate via
  511. +|ssam_client_link|). It is important to do this, as it, first, guarantees
  512. +that the returned controller is valid for use in the client driver for as
  513. +long as this driver is bound to its device, i.e. that the driver gets
  514. +unbound before the controller ever becomes invalid, and, second, as it
  515. +ensures correct suspend/resume ordering. This setup should be done in the
  516. +driver's probe function, and may be used to defer probing in case the SSAM
  517. +subsystem is not ready yet, for example:
  518. +
  519. +.. code-block:: c
  520. +
  521. + static int client_driver_probe(struct platform_device *pdev)
  522. + {
  523. + struct ssam_controller *ctrl;
  524. + int status;
  525. +
  526. + status = ssam_client_bind(&pdev->dev, &ctrl);
  527. + if (status)
  528. + return status == -ENXIO ? -EPROBE_DEFER : status;
  529. +
  530. + // ...
  531. +
  532. + return 0;
  533. + }
  534. +
  535. +The controller may be separately obtained via |ssam_get_controller| and its
  536. +lifetime be guaranteed via |ssam_controller_get| and |ssam_controller_put|.
  537. +Note that none of these functions, however, guarantee that the controller
  538. +will not be shut down or suspended. These functions essentially only operate
  539. +on the reference, i.e. only guarantee a bare minimum of accessibility
  540. +without any guarantees at all on practical operability.
  541. +
  542. +
  543. +Adding SSAM Devices
  544. +===================
  545. +
  546. +If a device does not already exist/is not already provided via conventional
  547. +means, it should be provided as |ssam_device| via the SSAM client device
  548. +hub. New devices can be added to this hub by entering their UID into the
  549. +corresponding registry. SSAM devices can also be manually allocated via
  550. +|ssam_device_alloc|, subsequently to which they have to be added via
  551. +|ssam_device_add| and eventually removed via |ssam_device_remove|. By
  552. +default, the parent of the device is set to the controller device provided
  553. +for allocation, however this may be changed before the device is added. Note
  554. +that, when changing the parent device, care must be taken to ensure that the
  555. +controller lifetime and suspend/resume ordering guarantees, in the default
  556. +setup provided through the parent-child relation, are preserved. If
  557. +necessary, by use of |ssam_client_link| as is done for non-SSAM client
  558. +drivers and described in more detail above.
  559. +
  560. +A client device must always be removed by the party which added the
  561. +respective device before the controller shuts down. Such removal can be
  562. +guaranteed by linking the driver providing the SSAM device to the controller
  563. +via |ssam_client_link|, causing it to unbind before the controller driver
  564. +unbinds. Client devices registered with the controller as parent are
  565. +automatically removed when the controller shuts down, but this should not be
  566. +relied upon, especially as this does not extend to client devices with a
  567. +different parent.
  568. +
  569. +
  570. +SSAM Client Drivers
  571. +===================
  572. +
  573. +SSAM client device drivers are, in essence, no different than other device
  574. +driver types. They are represented via |ssam_device_driver| and bind to a
  575. +|ssam_device| via its UID (:c:type:`struct ssam_device.uid <ssam_device>`)
  576. +member and the match table
  577. +(:c:type:`struct ssam_device_driver.match_table <ssam_device_driver>`),
  578. +which should be set when declaring the driver struct instance. Refer to the
  579. +|SSAM_DEVICE| macro documentation for more details on how to define members
  580. +of the driver's match table.
  581. +
  582. +The UID for SSAM client devices consists of a ``domain``, a ``category``,
  583. +a ``target``, an ``instance``, and a ``function``. The ``domain`` is used
  584. +differentiate between physical SAM devices
  585. +(:c:type:`SSAM_DOMAIN_SERIALHUB <ssam_device_domain>`), i.e. devices that can
  586. +be accessed via the Surface Serial Hub, and virtual ones
  587. +(:c:type:`SSAM_DOMAIN_VIRTUAL <ssam_device_domain>`), such as client-device
  588. +hubs, that have no real representation on the SAM EC and are solely used on
  589. +the kernel/driver-side. For physical devices, ``category`` represents the
  590. +target category, ``target`` the target ID, and ``instace`` the instance ID
  591. +used to access the physical SAM device. In addition, ``function`` references
  592. +a specific device functionality, but has no meaning to the SAM EC. The
  593. +(default) name of a client device is generated based on its UID.
  594. +
  595. +A driver instance can be registered via |ssam_device_driver_register| and
  596. +unregistered via |ssam_device_driver_unregister|. For convenience, the
  597. +|module_ssam_device_driver| macro may be used to define module init- and
  598. +exit-functions registering the driver.
  599. +
  600. +The controller associated with a SSAM client device can be found in its
  601. +:c:type:`struct ssam_device.ctrl <ssam_device>` member. This reference is
  602. +guaranteed to be valid for at least as long as the client driver is bound,
  603. +but should also be valid for as long as the client device exists. Note,
  604. +however, that access outside of the bound client driver must ensure that the
  605. +controller device is not suspended while making any requests or
  606. +(un)registering event notifiers (and thus should generally be avoided). This
  607. +is guaranteed when the controller is accessed from inside the bound client
  608. +driver.
  609. +
  610. +
  611. +Making Synchronous Requests
  612. +===========================
  613. +
  614. +Synchronous requests are (currently) the main form of host-initiated
  615. +communication with the EC. There are a couple of ways to define and execute
  616. +such requests, however, most of them boil down to something similar as shown
  617. +in the example below. This example defines a write-read request, meaning
  618. +that the caller provides an argument to the SAM EC and receives a response.
  619. +The caller needs to know the (maximum) length of the response payload and
  620. +provide a buffer for it.
  621. +
  622. +Care must be taken to ensure that any command payload data passed to the SAM
  623. +EC is provided in little-endian format and, similarly, any response payload
  624. +data received from it is converted from little-endian to host endianness.
  625. +
  626. +.. code-block:: c
  627. +
  628. + int perform_request(struct ssam_controller *ctrl, u32 arg, u32 *ret)
  629. + {
  630. + struct ssam_request rqst;
  631. + struct ssam_response resp;
  632. + int status;
  633. +
  634. + /* Convert request argument to little-endian. */
  635. + __le32 arg_le = cpu_to_le32(arg);
  636. + __le32 ret_le = cpu_to_le32(0);
  637. +
  638. + /*
  639. + * Initialize request specification. Replace this with your values.
  640. + * The rqst.payload field may be NULL if rqst.length is zero,
  641. + * indicating that the request does not have any argument.
  642. + *
  643. + * Note: The request parameters used here are not valid, i.e.
  644. + * they do not correspond to an actual SAM/EC request.
  645. + */
  646. + rqst.target_category = SSAM_SSH_TC_SAM;
  647. + rqst.target_id = 0x01;
  648. + rqst.command_id = 0x02;
  649. + rqst.instance_id = 0x03;
  650. + rqst.flags = SSAM_REQUEST_HAS_RESPONSE;
  651. + rqst.length = sizeof(arg_le);
  652. + rqst.payload = (u8 *)&arg_le;
  653. +
  654. + /* Initialize request response. */
  655. + resp.capacity = sizeof(ret_le);
  656. + resp.length = 0;
  657. + resp.pointer = (u8 *)&ret_le;
  658. +
  659. + /*
  660. + * Perform actual request. The response pointer may be null in case
  661. + * the request does not have any response. This must be consistent
  662. + * with the SSAM_REQUEST_HAS_RESPONSE flag set in the specification
  663. + * above.
  664. + */
  665. + status = ssam_request_sync(ctrl, &rqst, &resp);
  666. + if (status)
  667. + return status;
  668. +
  669. + /*
  670. + * Alternatively use
  671. + *
  672. + * ssam_request_sync_onstack(ctrl, &rqst, &resp, sizeof(arg_le));
  673. + *
  674. + * to perform the request, allocating the message buffer directly
  675. + * on the stack as opposed to via kzalloc().
  676. + */
  677. +
  678. + /*
  679. + * Convert request response back to native format. Note that in the
  680. + * error case, this value is not touched.
  681. + */
  682. + *ret = le32_to_cpu(ret_le);
  683. +
  684. + return status;
  685. + }
  686. +
  687. +Note that |ssam_request_sync| in its essence is a wrapper over lower-level
  688. +request primitives, which may also be used to perform requests. Refer to its
  689. +implementation and documentation for more details.
  690. +
  691. +An arguably more user-friendly way of defining such functions is by using
  692. +one of the generator macros, for example via:
  693. +
  694. +.. code-block:: c
  695. +
  696. + SSAM_DEFINE_SYNC_REQUEST_W(__ssam_tmp_perf_mode_set, __le32, {
  697. + .target_category = SSAM_SSH_TC_TMP,
  698. + .target_id = 0x01,
  699. + .command_id = 0x03,
  700. + .instance_id = 0x00,
  701. + });
  702. +
  703. +This example defines a function
  704. +
  705. +.. code-block:: c
  706. +
  707. + int __ssam_tmp_perf_mode_set(struct ssam_controller *ctrl, const __le32 *arg);
  708. +
  709. +executing the specified request, with the controller passed in when calling
  710. +said function. In this example, the argument is provided via the ``arg``
  711. +pointer. Note that the generated function allocates the message buffer on
  712. +the stack. Thus, if the argument provided via the request is large, these
  713. +kinds of macros should be avoided. Also note that, in contrast to the
  714. +previous non-macro example, this function does not do any endianness
  715. +conversion, which has to be handled by the caller. Apart from those
  716. +differences the function generated by the macro is similar to the one
  717. +provided in the non-macro example above.
  718. +
  719. +The full list of such function-generating macros is
  720. +
  721. +- :c:func:`SSAM_DEFINE_SYNC_REQUEST_N` for requests without return value and
  722. + without argument.
  723. +- :c:func:`SSAM_DEFINE_SYNC_REQUEST_R` for requests with return value but no
  724. + argument.
  725. +- :c:func:`SSAM_DEFINE_SYNC_REQUEST_W` for requests without return value but
  726. + with argument.
  727. +
  728. +Refer to their respective documentation for more details. For each one of
  729. +these macros, a special variant is provided, which targets request types
  730. +applicable to multiple instances of the same device type:
  731. +
  732. +- :c:func:`SSAM_DEFINE_SYNC_REQUEST_MD_N`
  733. +- :c:func:`SSAM_DEFINE_SYNC_REQUEST_MD_R`
  734. +- :c:func:`SSAM_DEFINE_SYNC_REQUEST_MD_W`
  735. +
  736. +The difference of those macros to the previously mentioned versions is, that
  737. +the device target and instance IDs are not fixed for the generated function,
  738. +but instead have to be provided by the caller of said function.
  739. +
  740. +Additionally, variants for direct use with client devices, i.e.
  741. +|ssam_device|, are also provided. These can, for example, be used as
  742. +follows:
  743. +
  744. +.. code-block:: c
  745. +
  746. + SSAM_DEFINE_SYNC_REQUEST_CL_R(ssam_bat_get_sta, __le32, {
  747. + .target_category = SSAM_SSH_TC_BAT,
  748. + .command_id = 0x01,
  749. + });
  750. +
  751. +This invocation of the macro defines a function
  752. +
  753. +.. code-block:: c
  754. +
  755. + int ssam_bat_get_sta(struct ssam_device *sdev, __le32 *ret);
  756. +
  757. +executing the specified request, using the device IDs and controller given
  758. +in the client device. The full list of such macros for client devices is:
  759. +
  760. +- :c:func:`SSAM_DEFINE_SYNC_REQUEST_CL_N`
  761. +- :c:func:`SSAM_DEFINE_SYNC_REQUEST_CL_R`
  762. +- :c:func:`SSAM_DEFINE_SYNC_REQUEST_CL_W`
  763. +
  764. +
  765. +Handling Events
  766. +===============
  767. +
  768. +To receive events from the SAM EC, an event notifier must be registered for
  769. +the desired event via |ssam_notifier_register|. The notifier must be
  770. +unregistered via |ssam_notifier_unregister| once it is not required any
  771. +more.
  772. +
  773. +Event notifiers are registered by providing (at minimum) a callback to call
  774. +in case an event has been received, the registry specifying how the event
  775. +should be enabled, an event ID specifying for which target category and,
  776. +optionally and depending on the registry used, for which instance ID events
  777. +should be enabled, and finally, flags describing how the EC will send these
  778. +events. Additionally, a priority for the respective notifier may be
  779. +specified, which determines its order in relation to any other notifier
  780. +registered for the same target category.
  781. +
  782. +By default, event notifiers will receive all events for the specific target
  783. +category, regardless of the instance ID specified when registering the
  784. +notifier. The core may be instructed to only call a notifier if the target
  785. +ID or instance ID (or both) of the event match the ones implied by the
  786. +notifier IDs (in case of target ID, the target ID of the registry), by
  787. +providing an event mask (see |ssam_event_mask|).
  788. +
  789. +In general, the target ID of the registry is also the target ID of the
  790. +enabled event (with the notable exception being keyboard input events on the
  791. +Surface Laptop 1 and 2, which are enabled via a registry with target ID 1,
  792. +but provide events with target ID 2).
  793. +
  794. +A full example for registering an event notifier and handling received
  795. +events is provided below:
  796. +
  797. +.. code-block:: c
  798. +
  799. + u32 notifier_callback(struct ssam_event_notifier *nf,
  800. + const struct ssam_event *event)
  801. + {
  802. + int status = ...
  803. +
  804. + /* Handle the event here ... */
  805. +
  806. + /* Convert return value and indicate that we handled the event. */
  807. + return ssam_notifier_from_errno(status) | SSAM_NOTIF_HANDLED;
  808. + }
  809. +
  810. + int setup_notifier(struct ssam_device *sdev,
  811. + struct ssam_event_notifier *nf)
  812. + {
  813. + /* Set priority wrt. other handlers of same target category. */
  814. + nf->base.priority = 1;
  815. +
  816. + /* Set event/notifier callback. */
  817. + nf->base.fn = notifier_callback;
  818. +
  819. + /* Specify event registry, i.e. how events get enabled/disabled. */
  820. + nf->event.reg = SSAM_EVENT_REGISTRY_KIP;
  821. +
  822. + /* Specify which event to enable/disable */
  823. + nf->event.id.target_category = sdev->uid.category;
  824. + nf->event.id.instance = sdev->uid.instance;
  825. +
  826. + /*
  827. + * Specify for which events the notifier callback gets executed.
  828. + * This essentially tells the core if it can skip notifiers that
  829. + * don't have target or instance IDs matching those of the event.
  830. + */
  831. + nf->event.mask = SSAM_EVENT_MASK_STRICT;
  832. +
  833. + /* Specify event flags. */
  834. + nf->event.flags = SSAM_EVENT_SEQUENCED;
  835. +
  836. + return ssam_notifier_register(sdev->ctrl, nf);
  837. + }
  838. +
  839. +Multiple event notifiers can be registered for the same event. The event
  840. +handler core takes care of enabling and disabling events when notifiers are
  841. +registered and unregistered, by keeping track of how many notifiers for a
  842. +specific event (combination of registry, event target category, and event
  843. +instance ID) are currently registered. This means that a specific event will
  844. +be enabled when the first notifier for it is being registered and disabled
  845. +when the last notifier for it is being unregistered. Note that the event
  846. +flags are therefore only used on the first registered notifier, however, one
  847. +should take care that notifiers for a specific event are always registered
  848. +with the same flag and it is considered a bug to do otherwise.
  849. diff --git a/Documentation/driver-api/surface_aggregator/clients/cdev.rst b/Documentation/driver-api/surface_aggregator/clients/cdev.rst
  850. new file mode 100644
  851. index 000000000000..720c9c03aa0e
  852. --- /dev/null
  853. +++ b/Documentation/driver-api/surface_aggregator/clients/cdev.rst
  854. @@ -0,0 +1,85 @@
  855. +.. SPDX-License-Identifier: GPL-2.0+
  856. +
  857. +.. |u8| replace:: :c:type:`u8 <u8>`
  858. +.. |u16| replace:: :c:type:`u16 <u16>`
  859. +.. |ssam_cdev_request| replace:: :c:type:`struct ssam_cdev_request <ssam_cdev_request>`
  860. +.. |ssam_request_flags| replace:: :c:type:`enum ssam_request_flags <ssam_request_flags>`
  861. +
  862. +==============================
  863. +User-Space EC Interface (cdev)
  864. +==============================
  865. +
  866. +The ``surface_aggregator_cdev`` module provides a misc-device for the SSAM
  867. +controller to allow for a (more or less) direct connection from user-space to
  868. +the SAM EC. It is intended to be used for development and debugging, and
  869. +therefore should not be used or relied upon in any other way. Note that this
  870. +module is not loaded automatically, but instead must be loaded manually.
  871. +
  872. +The provided interface is accessible through the ``/dev/surface/aggregator``
  873. +device-file. All functionality of this interface is provided via IOCTLs.
  874. +These IOCTLs and their respective input/output parameter structs are defined in
  875. +``include/uapi/linux/surface_aggregator/cdev.h``.
  876. +
  877. +
  878. +Controller IOCTLs
  879. +=================
  880. +
  881. +The following IOCTLs are provided:
  882. +
  883. +.. flat-table:: Controller IOCTLs
  884. + :widths: 1 1 1 1 4
  885. + :header-rows: 1
  886. +
  887. + * - Type
  888. + - Number
  889. + - Direction
  890. + - Name
  891. + - Description
  892. +
  893. + * - ``0xA5``
  894. + - ``1``
  895. + - ``WR``
  896. + - ``REQUEST``
  897. + - Perform synchronous SAM request.
  898. +
  899. +
  900. +``REQUEST``
  901. +-----------
  902. +
  903. +Defined as ``_IOWR(0xA5, 1, struct ssam_cdev_request)``.
  904. +
  905. +Executes a synchronous SAM request. The request specification is passed in
  906. +as argument of type |ssam_cdev_request|, which is then written to/modified
  907. +by the IOCTL to return status and result of the request.
  908. +
  909. +Request payload data must be allocated separately and is passed in via the
  910. +``payload.data`` and ``payload.length`` members. If a response is required,
  911. +the response buffer must be allocated by the caller and passed in via the
  912. +``response.data`` member. The ``response.length`` member must be set to the
  913. +capacity of this buffer, or if no response is required, zero. Upon
  914. +completion of the request, the call will write the response to the response
  915. +buffer (if its capacity allows it) and overwrite the length field with the
  916. +actual size of the response, in bytes.
  917. +
  918. +Additionally, if the request has a response, this should be indicated via
  919. +the request flags, as is done with in-kernel requests. Request flags can be
  920. +set via the ``flags`` member and the values correspond to the values found
  921. +in |ssam_request_flags|.
  922. +
  923. +Finally, the status of the request itself is returned in the ``status``
  924. +member (a negative value indicating failure). Note that failure indication
  925. +of the IOCTL is separated from failure indication of the request: The IOCTL
  926. +returns a negative status code if anything failed during setup of the
  927. +request (``-EFAULT``) or if the provided argument or any of its fields are
  928. +invalid (``-EINVAL``). In this case, the status value of the request
  929. +argument may be set, providing more detail on what went wrong (e.g.
  930. +``-ENOMEM`` for out-of-memory), but this value may also be zero. The IOCTL
  931. +will return with a zero status code in case the request has been set up,
  932. +submitted, and completed (i.e. handed back to user-space) successfully from
  933. +inside the IOCTL, but the request ``status`` member may still be negative in
  934. +case the actual execution of the request failed after it has been submitted.
  935. +
  936. +A full definition of the argument struct is provided below:
  937. +
  938. +.. kernel-doc:: include/uapi/linux/surface_aggregator/cdev.h
  939. + :functions: ssam_cdev_request
  940. diff --git a/Documentation/driver-api/surface_aggregator/clients/dtx.rst b/Documentation/driver-api/surface_aggregator/clients/dtx.rst
  941. new file mode 100644
  942. index 000000000000..e974c2b04e9f
  943. --- /dev/null
  944. +++ b/Documentation/driver-api/surface_aggregator/clients/dtx.rst
  945. @@ -0,0 +1,712 @@
  946. +.. SPDX-License-Identifier: GPL-2.0+
  947. +
  948. +.. |__u16| replace:: :c:type:`__u16 <__u16>`
  949. +.. |sdtx_event| replace:: :c:type:`struct sdtx_event <sdtx_event>`
  950. +.. |sdtx_event_code| replace:: :c:type:`enum sdtx_event_code <sdtx_event_code>`
  951. +.. |sdtx_base_info| replace:: :c:type:`struct sdtx_base_info <sdtx_base_info>`
  952. +.. |sdtx_device_mode| replace:: :c:type:`struct sdtx_device_mode <sdtx_device_mode>`
  953. +
  954. +======================================================
  955. +User-Space DTX (Clipboard Detachment System) Interface
  956. +======================================================
  957. +
  958. +The ``surface_dtx`` driver is responsible for proper clipboard detachment
  959. +and re-attachment handling. To this end, it provides the ``/dev/surface/dtx``
  960. +device file, through which it can interface with a user-space daemon. This
  961. +daemon is then ultimately responsible for determining and taking necessary
  962. +actions, such as unmounting devices attached to the base,
  963. +unloading/reloading the graphics-driver, user-notifications, etc.
  964. +
  965. +There are two basic communication principles used in this driver: Commands
  966. +(in other parts of the documentation also referred to as requests) and
  967. +events. Commands are sent to the EC and may have a different implications in
  968. +different contexts. Events are sent by the EC upon some internal state
  969. +change. Commands are always driver-initiated, whereas events are always
  970. +initiated by the EC.
  971. +
  972. +.. contents::
  973. +
  974. +Nomenclature
  975. +============
  976. +
  977. +* **Clipboard:**
  978. + The detachable upper part of the Surface Book, housing the screen and CPU.
  979. +
  980. +* **Base:**
  981. + The lower part of the Surface Book from which the clipboard can be
  982. + detached, optionally (model dependent) housing the discrete GPU (dGPU).
  983. +
  984. +* **Latch:**
  985. + The mechanism keeping the clipboard attached to the base in normal
  986. + operation and allowing it to be detached when requested.
  987. +
  988. +* **Silently ignored commands:**
  989. + The command is accepted by the EC as a valid command and acknowledged
  990. + (following the standard communication protocol), but the EC does not act
  991. + upon it, i.e. ignores it.e upper part of the
  992. +
  993. +
  994. +Detachment Process
  995. +==================
  996. +
  997. +Warning: This part of the documentation is based on reverse engineering and
  998. +testing and thus may contain errors or be incomplete.
  999. +
  1000. +Latch States
  1001. +------------
  1002. +
  1003. +The latch mechanism has two major states: *open* and *closed*. In the
  1004. +*closed* state (default), the clipboard is secured to the base, whereas in
  1005. +the *open* state, the clipboard can be removed by a user.
  1006. +
  1007. +The latch can additionally be locked and, correspondingly, unlocked, which
  1008. +can influence the detachment procedure. Specifically, this locking mechanism
  1009. +is intended to prevent the the dGPU, positioned in the base of the device,
  1010. +from being hot-unplugged while in use. More details can be found in the
  1011. +documentation for the detachment procedure below. By default, the latch is
  1012. +unlocked.
  1013. +
  1014. +Detachment Procedure
  1015. +--------------------
  1016. +
  1017. +Note that the detachment process is governed fully by the EC. The
  1018. +``surface_dtx`` driver only relays events from the EC to user-space and
  1019. +commands from user-space to the EC, i.e. it does not influence this process.
  1020. +
  1021. +The detachment process is started with the user pressing the *detach* button
  1022. +on the base of the device or executing the ``SDTX_IOCTL_LATCH_REQUEST`` IOCTL.
  1023. +Following that:
  1024. +
  1025. +1. The EC turns on the indicator led on the detach-button, sends a
  1026. + *detach-request* event (``SDTX_EVENT_REQUEST``), and awaits further
  1027. + instructions/commands. In case the latch is unlocked, the led will flash
  1028. + green. If the latch has been locked, the led will be solid red
  1029. +
  1030. +2. The event is, via the ``surface_dtx`` driver, relayed to user-space, where
  1031. + an appropriate user-space daemon can handle it and send instructions back
  1032. + to the EC via IOCTLs provided by this driver.
  1033. +
  1034. +3. The EC waits for instructions from user-space and acts according to them.
  1035. + If the EC does not receive any instructions in a given period, it will
  1036. + time out and continue as follows:
  1037. +
  1038. + - If the latch is unlocked, the EC will open the latch and the clipboard
  1039. + can be detached from the base. This is the exact behavior as without
  1040. + this driver or any user-space daemon. See the ``SDTX_IOCTL_LATCH_CONFIRM``
  1041. + description below for more details on the follow-up behavior of the EC.
  1042. +
  1043. + - If the latch is locked, the EC will *not* open the latch, meaning the
  1044. + clipboard cannot be detached from the base. Furthermore, the EC sends
  1045. + an cancel event (``SDTX_EVENT_CANCEL``) detailing this with the cancel
  1046. + reason ``SDTX_DETACH_TIMEDOUT`` (see :ref:`events` for details).
  1047. +
  1048. +Valid responses by a user-space daemon to a detachment request event are:
  1049. +
  1050. +- Execute ``SDTX_IOCTL_LATCH_REQUEST``. This will immediately abort the
  1051. + detachment process. Furthermore, the EC will send a detach-request event,
  1052. + similar to the user pressing the detach-button to cancel said process (see
  1053. + below).
  1054. +
  1055. +- Execute ``SDTX_IOCTL_LATCH_CONFIRM``. This will cause the EC to open the
  1056. + latch, after which the user can separate clipboard and base.
  1057. +
  1058. + As this changes the latch state, a *latch-status* event
  1059. + (``SDTX_EVENT_LATCH_STATUS``) will be sent once the latch has been opened
  1060. + successfully. If the EC fails to open the latch, e.g. due to hardware
  1061. + error or low battery, a latch-cancel event (``SDTX_EVENT_CANCEL``) will be
  1062. + sent with the cancel reason indicating the specific failure.
  1063. +
  1064. + If the latch is currently locked, the latch will automatically be
  1065. + unlocked before it is opened.
  1066. +
  1067. +- Execute ``SDTX_IOCTL_LATCH_HEARTBEAT``. This will reset the internal timeout.
  1068. + No other actions will be performed, i.e. the detachment process will neither
  1069. + be completed nor canceled, and the EC will still be waiting for further
  1070. + responses.
  1071. +
  1072. +- Execute ``SDTX_IOCTL_LATCH_CANCEL``. This will abort the detachment process,
  1073. + similar to ``SDTX_IOCTL_LATCH_REQUEST``, described above, or the button
  1074. + press, described below. A *generic request* event (``SDTX_EVENT_REQUEST``)
  1075. + is send in response to this. In contrast to those, however, this command
  1076. + does not trigger a new detachment process if none is currently in
  1077. + progress.
  1078. +
  1079. +- Do nothing. The detachment process eventually times out as described in
  1080. + point 3.
  1081. +
  1082. +See :ref:`ioctls` for more details on these responses.
  1083. +
  1084. +It is important to note that, if the user presses the detach button at any
  1085. +point when a detachment operation is in progress (i.e. after the the EC has
  1086. +sent the initial *detach-request* event (``SDTX_EVENT_REQUEST``) and before
  1087. +it received the corresponding response concluding the process), the
  1088. +detachment process is canceled on the EC-level and an identical event is
  1089. +being sent. Thus a *detach-request* event, by itself, does not signal the
  1090. +start of the detachment process.
  1091. +
  1092. +The detachment process may further be canceled by the EC due to hardware
  1093. +failures or a low clipboard battery. This is done via a cancel event
  1094. +(``SDTX_EVENT_CANCEL``) with the corresponding cancel reason.
  1095. +
  1096. +
  1097. +User-Space Interface Documentation
  1098. +==================================
  1099. +
  1100. +Error Codes and Status Values
  1101. +-----------------------------
  1102. +
  1103. +Error and status codes are divided into different categories, which can be
  1104. +used to determine if the status code is an error, and, if it is, the
  1105. +severity and type of that error. The current categories are:
  1106. +
  1107. +.. flat-table:: Overview of Status/Error Categories.
  1108. + :widths: 2 1 3
  1109. + :header-rows: 1
  1110. +
  1111. + * - Name
  1112. + - Value
  1113. + - Short Description
  1114. +
  1115. + * - ``STATUS``
  1116. + - ``0x0000``
  1117. + - Non-error status codes.
  1118. +
  1119. + * - ``RUNTIME_ERROR``
  1120. + - ``0x1000``
  1121. + - Non-critical runtime errors.
  1122. +
  1123. + * - ``HARDWARE_ERROR``
  1124. + - ``0x2000``
  1125. + - Critical hardware failures.
  1126. +
  1127. + * - ``UNKNOWN``
  1128. + - ``0xF000``
  1129. + - Unknown error codes.
  1130. +
  1131. +Other categories are reserved for future use. The ``SDTX_CATEGORY()`` macro
  1132. +can be used to determine the category of any status value. The
  1133. +``SDTX_SUCCESS()`` macro can be used to check if the status value is a
  1134. +success value (``SDTX_CATEGORY_STATUS``) or if it indicates a failure.
  1135. +
  1136. +Unknown status or error codes sent by the EC are assigned to the ``UNKNOWN``
  1137. +category by the driver and may be implemented via their own code in the
  1138. +future.
  1139. +
  1140. +Currently used error codes are:
  1141. +
  1142. +.. flat-table:: Overview of Error Codes.
  1143. + :widths: 2 1 1 3
  1144. + :header-rows: 1
  1145. +
  1146. + * - Name
  1147. + - Category
  1148. + - Value
  1149. + - Short Description
  1150. +
  1151. + * - ``SDTX_DETACH_NOT_FEASIBLE``
  1152. + - ``RUNTIME``
  1153. + - ``0x1001``
  1154. + - Detachment not feasible due to low clipboard battery.
  1155. +
  1156. + * - ``SDTX_DETACH_TIMEDOUT``
  1157. + - ``RUNTIME``
  1158. + - ``0x1002``
  1159. + - Detachment process timed out while the latch was locked.
  1160. +
  1161. + * - ``SDTX_ERR_FAILED_TO_OPEN``
  1162. + - ``HARDWARE``
  1163. + - ``0x2001``
  1164. + - Failed to open latch.
  1165. +
  1166. + * - ``SDTX_ERR_FAILED_TO_REMAIN_OPEN``
  1167. + - ``HARDWARE``
  1168. + - ``0x2002``
  1169. + - Failed to keep latch open.
  1170. +
  1171. + * - ``SDTX_ERR_FAILED_TO_CLOSE``
  1172. + - ``HARDWARE``
  1173. + - ``0x2003``
  1174. + - Failed to close latch.
  1175. +
  1176. +Other error codes are reserved for future use. Non-error status codes may
  1177. +overlap and are generally only unique within their use-case:
  1178. +
  1179. +.. flat-table:: Latch Status Codes.
  1180. + :widths: 2 1 1 3
  1181. + :header-rows: 1
  1182. +
  1183. + * - Name
  1184. + - Category
  1185. + - Value
  1186. + - Short Description
  1187. +
  1188. + * - ``SDTX_LATCH_CLOSED``
  1189. + - ``STATUS``
  1190. + - ``0x0000``
  1191. + - Latch is closed/has been closed.
  1192. +
  1193. + * - ``SDTX_LATCH_OPENED``
  1194. + - ``STATUS``
  1195. + - ``0x0001``
  1196. + - Latch is open/has been opened.
  1197. +
  1198. +.. flat-table:: Base State Codes.
  1199. + :widths: 2 1 1 3
  1200. + :header-rows: 1
  1201. +
  1202. + * - Name
  1203. + - Category
  1204. + - Value
  1205. + - Short Description
  1206. +
  1207. + * - ``SDTX_BASE_DETACHED``
  1208. + - ``STATUS``
  1209. + - ``0x0000``
  1210. + - Base has been detached/is not present.
  1211. +
  1212. + * - ``SDTX_BASE_ATTACHED``
  1213. + - ``STATUS``
  1214. + - ``0x0001``
  1215. + - Base has been attached/is present.
  1216. +
  1217. +Again, other codes are reserved for future use.
  1218. +
  1219. +.. _events:
  1220. +
  1221. +Events
  1222. +------
  1223. +
  1224. +Events can be received by reading from the device file. They are disabled by
  1225. +default and have to be enabled by executing ``SDTX_IOCTL_EVENTS_ENABLE``
  1226. +first. All events follow the layout prescribed by |sdtx_event|. Specific
  1227. +event types can be identified by their event code, described in
  1228. +|sdtx_event_code|. Note that other event codes are reserved for future use,
  1229. +thus an event parser must be able to handle any unknown/unsupported event
  1230. +types gracefully, by relying on the payload length given in the event header.
  1231. +
  1232. +Currently provided event types are:
  1233. +
  1234. +.. flat-table:: Overview of DTX events.
  1235. + :widths: 2 1 1 3
  1236. + :header-rows: 1
  1237. +
  1238. + * - Name
  1239. + - Code
  1240. + - Payload
  1241. + - Short Description
  1242. +
  1243. + * - ``SDTX_EVENT_REQUEST``
  1244. + - ``1``
  1245. + - ``0`` bytes
  1246. + - Detachment process initiated/aborted.
  1247. +
  1248. + * - ``SDTX_EVENT_CANCEL``
  1249. + - ``2``
  1250. + - ``2`` bytes
  1251. + - EC canceled detachment process.
  1252. +
  1253. + * - ``SDTX_EVENT_BASE_CONNECTION``
  1254. + - ``3``
  1255. + - ``4`` bytes
  1256. + - Base connection state changed.
  1257. +
  1258. + * - ``SDTX_EVENT_LATCH_STATUS``
  1259. + - ``4``
  1260. + - ``2`` bytes
  1261. + - Latch status changed.
  1262. +
  1263. + * - ``SDTX_EVENT_DEVICE_MODE``
  1264. + - ``5``
  1265. + - ``2`` bytes
  1266. + - Device mode changed.
  1267. +
  1268. +Individual events in more detail:
  1269. +
  1270. +``SDTX_EVENT_REQUEST``
  1271. +^^^^^^^^^^^^^^^^^^^^^^
  1272. +
  1273. +Sent when a detachment process is started or, if in progress, aborted by the
  1274. +user, either via a detach button press or a detach request
  1275. +(``SDTX_IOCTL_LATCH_REQUEST``) being sent from user-space.
  1276. +
  1277. +Does not have any payload.
  1278. +
  1279. +``SDTX_EVENT_CANCEL``
  1280. +^^^^^^^^^^^^^^^^^^^^^
  1281. +
  1282. +Sent when a detachment process is canceled by the EC due to unfulfilled
  1283. +preconditions (e.g. clipboard battery too low to detach) or hardware
  1284. +failure. The reason for cancellation is given in the event payload detailed
  1285. +below and can be one of
  1286. +
  1287. +* ``SDTX_DETACH_TIMEDOUT``: Detachment timed out while the latch was locked.
  1288. + The latch has neither been opened nor unlocked.
  1289. +
  1290. +* ``SDTX_DETACH_NOT_FEASIBLE``: Detachment not feasible due to low clipboard
  1291. + battery.
  1292. +
  1293. +* ``SDTX_ERR_FAILED_TO_OPEN``: Could not open the latch (hardware failure).
  1294. +
  1295. +* ``SDTX_ERR_FAILED_TO_REMAIN_OPEN``: Could not keep the latch open (hardware
  1296. + failure).
  1297. +
  1298. +* ``SDTX_ERR_FAILED_TO_CLOSE``: Could not close the latch (hardware failure).
  1299. +
  1300. +Other error codes in this context are reserved for future use.
  1301. +
  1302. +These codes can be classified via the ``SDTX_CATEGORY()`` macro to discern
  1303. +between critical hardware errors (``SDTX_CATEGORY_HARDWARE_ERROR``) or
  1304. +runtime errors (``SDTX_CATEGORY_RUNTIME_ERROR``), the latter of which may
  1305. +happen during normal operation if certain preconditions for detachment are
  1306. +not given.
  1307. +
  1308. +.. flat-table:: Detachment Cancel Event Payload
  1309. + :widths: 1 1 4
  1310. + :header-rows: 1
  1311. +
  1312. + * - Field
  1313. + - Type
  1314. + - Description
  1315. +
  1316. + * - ``reason``
  1317. + - |__u16|
  1318. + - Reason for cancellation.
  1319. +
  1320. +``SDTX_EVENT_BASE_CONNECTION``
  1321. +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1322. +
  1323. +Sent when the base connection state has changed, i.e. when the base has been
  1324. +attached, detached, or detachment has become infeasible due to low clipboard
  1325. +battery. The new state and, if a base is connected, ID of the base is
  1326. +provided as payload of type |sdtx_base_info| with its layout presented
  1327. +below:
  1328. +
  1329. +.. flat-table:: Base-Connection-Change Event Payload
  1330. + :widths: 1 1 4
  1331. + :header-rows: 1
  1332. +
  1333. + * - Field
  1334. + - Type
  1335. + - Description
  1336. +
  1337. + * - ``state``
  1338. + - |__u16|
  1339. + - Base connection state.
  1340. +
  1341. + * - ``base_id``
  1342. + - |__u16|
  1343. + - Type of base connected (zero if none).
  1344. +
  1345. +Possible values for ``state`` are:
  1346. +
  1347. +* ``SDTX_BASE_DETACHED``,
  1348. +* ``SDTX_BASE_ATTACHED``, and
  1349. +* ``SDTX_DETACH_NOT_FEASIBLE``.
  1350. +
  1351. +Other values are reserved for future use.
  1352. +
  1353. +``SDTX_EVENT_LATCH_STATUS``
  1354. +^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1355. +
  1356. +Sent when the latch status has changed, i.e. when the latch has been opened,
  1357. +closed, or an error occurred. The current status is provided as payload:
  1358. +
  1359. +.. flat-table:: Latch-Status-Change Event Payload
  1360. + :widths: 1 1 4
  1361. + :header-rows: 1
  1362. +
  1363. + * - Field
  1364. + - Type
  1365. + - Description
  1366. +
  1367. + * - ``status``
  1368. + - |__u16|
  1369. + - Latch status.
  1370. +
  1371. +Possible values for ``status`` are:
  1372. +
  1373. +* ``SDTX_LATCH_CLOSED``,
  1374. +* ``SDTX_LATCH_OPENED``,
  1375. +* ``SDTX_ERR_FAILED_TO_OPEN``,
  1376. +* ``SDTX_ERR_FAILED_TO_REMAIN_OPEN``, and
  1377. +* ``SDTX_ERR_FAILED_TO_CLOSE``.
  1378. +
  1379. +Other values are reserved for future use.
  1380. +
  1381. +``SDTX_EVENT_DEVICE_MODE``
  1382. +^^^^^^^^^^^^^^^^^^^^^^^^^^
  1383. +
  1384. +Sent when the device mode has changed. The new device mode is provided as
  1385. +payload:
  1386. +
  1387. +.. flat-table:: Device-Mode-Change Event Payload
  1388. + :widths: 1 1 4
  1389. + :header-rows: 1
  1390. +
  1391. + * - Field
  1392. + - Type
  1393. + - Description
  1394. +
  1395. + * - ``mode``
  1396. + - |__u16|
  1397. + - Device operation mode.
  1398. +
  1399. +Possible values for ``mode`` are:
  1400. +
  1401. +* ``SDTX_DEVICE_MODE_TABLET``,
  1402. +* ``SDTX_DEVICE_MODE_LAPTOP``, and
  1403. +* ``SDTX_DEVICE_MODE_STUDIO``.
  1404. +
  1405. +Other values are reserved for future use.
  1406. +
  1407. +.. _ioctls:
  1408. +
  1409. +IOCTLs
  1410. +------
  1411. +
  1412. +The following IOCTLs are provided:
  1413. +
  1414. +.. flat-table:: Overview of DTX IOCTLs
  1415. + :widths: 1 1 1 1 4
  1416. + :header-rows: 1
  1417. +
  1418. + * - Type
  1419. + - Number
  1420. + - Direction
  1421. + - Name
  1422. + - Description
  1423. +
  1424. + * - ``0xA5``
  1425. + - ``0x21``
  1426. + - ``-``
  1427. + - ``EVENTS_ENABLE``
  1428. + - Enable events for the current file descriptor.
  1429. +
  1430. + * - ``0xA5``
  1431. + - ``0x22``
  1432. + - ``-``
  1433. + - ``EVENTS_DISABLE``
  1434. + - Disable events for the current file descriptor.
  1435. +
  1436. + * - ``0xA5``
  1437. + - ``0x23``
  1438. + - ``-``
  1439. + - ``LATCH_LOCK``
  1440. + - Lock the latch.
  1441. +
  1442. + * - ``0xA5``
  1443. + - ``0x24``
  1444. + - ``-``
  1445. + - ``LATCH_UNLOCK``
  1446. + - Unlock the latch.
  1447. +
  1448. + * - ``0xA5``
  1449. + - ``0x25``
  1450. + - ``-``
  1451. + - ``LATCH_REQUEST``
  1452. + - Request clipboard detachment.
  1453. +
  1454. + * - ``0xA5``
  1455. + - ``0x26``
  1456. + - ``-``
  1457. + - ``LATCH_CONFIRM``
  1458. + - Confirm clipboard detachment request.
  1459. +
  1460. + * - ``0xA5``
  1461. + - ``0x27``
  1462. + - ``-``
  1463. + - ``LATCH_HEARTBEAT``
  1464. + - Send heartbeat signal to EC.
  1465. +
  1466. + * - ``0xA5``
  1467. + - ``0x28``
  1468. + - ``-``
  1469. + - ``LATCH_CANCEL``
  1470. + - Cancel detachment process.
  1471. +
  1472. + * - ``0xA5``
  1473. + - ``0x29``
  1474. + - ``R``
  1475. + - ``GET_BASE_INFO``
  1476. + - Get current base/connection information.
  1477. +
  1478. + * - ``0xA5``
  1479. + - ``0x2A``
  1480. + - ``R``
  1481. + - ``GET_DEVICE_MODE``
  1482. + - Get current device operation mode.
  1483. +
  1484. + * - ``0xA5``
  1485. + - ``0x2B``
  1486. + - ``R``
  1487. + - ``GET_LATCH_STATUS``
  1488. + - Get current device latch status.
  1489. +
  1490. +``SDTX_IOCTL_EVENTS_ENABLE``
  1491. +^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1492. +
  1493. +Defined as ``_IO(0xA5, 0x22)``.
  1494. +
  1495. +Enable events for the current file descriptor. Events can be obtained by
  1496. +reading from the device, if enabled. Events are disabled by default.
  1497. +
  1498. +``SDTX_IOCTL_EVENTS_DISABLE``
  1499. +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1500. +
  1501. +Defined as ``_IO(0xA5, 0x22)``.
  1502. +
  1503. +Disable events for the current file descriptor. Events can be obtained by
  1504. +reading from the device, if enabled. Events are disabled by default.
  1505. +
  1506. +``SDTX_IOCTL_LATCH_LOCK``
  1507. +^^^^^^^^^^^^^^^^^^^^^^^^^
  1508. +
  1509. +Defined as ``_IO(0xA5, 0x23)``.
  1510. +
  1511. +Locks the latch, causing the detachment procedure to abort without opening
  1512. +the latch on timeout. The latch is unlocked by default. This command will be
  1513. +silently ignored if the latch is already locked.
  1514. +
  1515. +``SDTX_IOCTL_LATCH_UNLOCK``
  1516. +^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1517. +
  1518. +Defined as ``_IO(0xA5, 0x24)``.
  1519. +
  1520. +Unlocks the latch, causing the detachment procedure to open the latch on
  1521. +timeout. The latch is unlocked by default. This command will not open the
  1522. +latch when sent during an ongoing detachment process. It will be silently
  1523. +ignored if the latch is already unlocked.
  1524. +
  1525. +``SDTX_IOCTL_LATCH_REQUEST``
  1526. +^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1527. +
  1528. +Defined as ``_IO(0xA5, 0x25)``.
  1529. +
  1530. +Generic latch request. Behavior depends on the context: If no
  1531. +detachment-process is active, detachment is requested. Otherwise the
  1532. +currently active detachment-process will be aborted.
  1533. +
  1534. +If a detachment process is canceled by this operation, a generic detachment
  1535. +request event (``SDTX_EVENT_REQUEST``) will be sent.
  1536. +
  1537. +This essentially behaves the same as a detachment button press.
  1538. +
  1539. +``SDTX_IOCTL_LATCH_CONFIRM``
  1540. +^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1541. +
  1542. +Defined as ``_IO(0xA5, 0x26)``.
  1543. +
  1544. +Acknowledges and confirms a latch request. If sent during an ongoing
  1545. +detachment process, this command causes the latch to be opened immediately.
  1546. +The latch will also be opened if it has been locked. In this case, the latch
  1547. +lock is reset to the unlocked state.
  1548. +
  1549. +This command will be silently ignored if there is currently no detachment
  1550. +procedure in progress.
  1551. +
  1552. +``SDTX_IOCTL_LATCH_HEARTBEAT``
  1553. +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1554. +
  1555. +Defined as ``_IO(0xA5, 0x27)``.
  1556. +
  1557. +Sends a heartbeat, essentially resetting the detachment timeout. This
  1558. +command can be used to keep the detachment process alive while work required
  1559. +for the detachment to succeed is still in progress.
  1560. +
  1561. +This command will be silently ignored if there is currently no detachment
  1562. +procedure in progress.
  1563. +
  1564. +``SDTX_IOCTL_LATCH_CANCEL``
  1565. +^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1566. +
  1567. +Defined as ``_IO(0xA5, 0x28)``.
  1568. +
  1569. +Cancels detachment in progress (if any). If a detachment process is canceled
  1570. +by this operation, a generic detachment request event
  1571. +(``SDTX_EVENT_REQUEST``) will be sent.
  1572. +
  1573. +This command will be silently ignored if there is currently no detachment
  1574. +procedure in progress.
  1575. +
  1576. +``SDTX_IOCTL_GET_BASE_INFO``
  1577. +^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1578. +
  1579. +Defined as ``_IOR(0xA5, 0x29, struct sdtx_base_info)``.
  1580. +
  1581. +Get the current base connection state (i.e. attached/detached) and the type
  1582. +of the base connected to the clipboard. This is command essentially provides
  1583. +a way to query the information provided by the base connection change event
  1584. +(``SDTX_EVENT_BASE_CONNECTION``).
  1585. +
  1586. +Possible values for ``struct sdtx_base_info.state`` are:
  1587. +
  1588. +* ``SDTX_BASE_DETACHED``,
  1589. +* ``SDTX_BASE_ATTACHED``, and
  1590. +* ``SDTX_DETACH_NOT_FEASIBLE``.
  1591. +
  1592. +Other values are reserved for future use.
  1593. +
  1594. +``SDTX_IOCTL_GET_DEVICE_MODE``
  1595. +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1596. +
  1597. +Defined as ``_IOR(0xA5, 0x2A, __u16)``.
  1598. +
  1599. +Returns the device operation mode, indicating if and how the base is
  1600. +attached to the clipboard. This is command essentially provides a way to
  1601. +query the information provided by the device mode change event
  1602. +(``SDTX_EVENT_DEVICE_MODE``).
  1603. +
  1604. +Returned values are:
  1605. +
  1606. +* ``SDTX_DEVICE_MODE_LAPTOP``
  1607. +* ``SDTX_DEVICE_MODE_TABLET``
  1608. +* ``SDTX_DEVICE_MODE_STUDIO``
  1609. +
  1610. +See |sdtx_device_mode| for details. Other values are reserved for future
  1611. +use.
  1612. +
  1613. +
  1614. +``SDTX_IOCTL_GET_LATCH_STATUS``
  1615. +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  1616. +
  1617. +Defined as ``_IOR(0xA5, 0x2B, __u16)``.
  1618. +
  1619. +Get the current latch status or (presumably) the last error encountered when
  1620. +trying to open/close the latch. This is command essentially provides a way
  1621. +to query the information provided by the latch status change event
  1622. +(``SDTX_EVENT_LATCH_STATUS``).
  1623. +
  1624. +Returned values are:
  1625. +
  1626. +* ``SDTX_LATCH_CLOSED``,
  1627. +* ``SDTX_LATCH_OPENED``,
  1628. +* ``SDTX_ERR_FAILED_TO_OPEN``,
  1629. +* ``SDTX_ERR_FAILED_TO_REMAIN_OPEN``, and
  1630. +* ``SDTX_ERR_FAILED_TO_CLOSE``.
  1631. +
  1632. +Other values are reserved for future use.
  1633. +
  1634. +A Note on Base IDs
  1635. +------------------
  1636. +
  1637. +Base types/IDs provided via ``SDTX_EVENT_BASE_CONNECTION`` or
  1638. +``SDTX_IOCTL_GET_BASE_INFO`` are directly forwarded from from the EC in the
  1639. +lower byte of the combined |__u16| value, with the driver storing the EC
  1640. +type from which this ID comes in the high byte (without this, base IDs over
  1641. +different types of ECs may be overlapping).
  1642. +
  1643. +The ``SDTX_DEVICE_TYPE()`` macro can be used to determine the EC device
  1644. +type. This can be one of
  1645. +
  1646. +* ``SDTX_DEVICE_TYPE_HID``, for Surface Aggregator Module over HID, and
  1647. +
  1648. +* ``SDTX_DEVICE_TYPE_SSH``, for Surface Aggregator Module over Surface Serial
  1649. + Hub.
  1650. +
  1651. +Note that currently only the ``SSH`` type EC is supported, however ``HID``
  1652. +type is reserved for future use.
  1653. +
  1654. +Structures and Enums
  1655. +--------------------
  1656. +
  1657. +.. kernel-doc:: include/uapi/linux/surface_aggregator/dtx.h
  1658. diff --git a/Documentation/driver-api/surface_aggregator/clients/index.rst b/Documentation/driver-api/surface_aggregator/clients/index.rst
  1659. new file mode 100644
  1660. index 000000000000..98ea9946b8a2
  1661. --- /dev/null
  1662. +++ b/Documentation/driver-api/surface_aggregator/clients/index.rst
  1663. @@ -0,0 +1,22 @@
  1664. +.. SPDX-License-Identifier: GPL-2.0+
  1665. +
  1666. +===========================
  1667. +Client Driver Documentation
  1668. +===========================
  1669. +
  1670. +This is the documentation for client drivers themselves. Refer to
  1671. +:doc:`../client` for documentation on how to write client drivers.
  1672. +
  1673. +.. toctree::
  1674. + :maxdepth: 1
  1675. +
  1676. + cdev
  1677. + dtx
  1678. + san
  1679. +
  1680. +.. only:: subproject and html
  1681. +
  1682. + Indices
  1683. + =======
  1684. +
  1685. + * :ref:`genindex`
  1686. diff --git a/Documentation/driver-api/surface_aggregator/clients/san.rst b/Documentation/driver-api/surface_aggregator/clients/san.rst
  1687. new file mode 100644
  1688. index 000000000000..1bf830ad367d
  1689. --- /dev/null
  1690. +++ b/Documentation/driver-api/surface_aggregator/clients/san.rst
  1691. @@ -0,0 +1,44 @@
  1692. +.. SPDX-License-Identifier: GPL-2.0+
  1693. +
  1694. +.. |san_client_link| replace:: :c:func:`san_client_link`
  1695. +.. |san_dgpu_notifier_register| replace:: :c:func:`san_dgpu_notifier_register`
  1696. +.. |san_dgpu_notifier_unregister| replace:: :c:func:`san_dgpu_notifier_unregister`
  1697. +
  1698. +===================
  1699. +Surface ACPI Notify
  1700. +===================
  1701. +
  1702. +The Surface ACPI Notify (SAN) device provides the bridge between ACPI and
  1703. +SAM controller. Specifically, ACPI code can execute requests and handle
  1704. +battery and thermal events via this interface. In addition to this, events
  1705. +relating to the discrete GPU (dGPU) of the Surface Book 2 can be sent from
  1706. +ACPI code (note: the Surface Book 3 uses a different method for this). The
  1707. +only currently known event sent via this interface is a dGPU power-on
  1708. +notification. While this driver handles the former part internally, it only
  1709. +relays the dGPU events to any other driver interested via its public API and
  1710. +does not handle them.
  1711. +
  1712. +The public interface of this driver is split into two parts: Client
  1713. +registration and notifier-block registration.
  1714. +
  1715. +A client to the SAN interface can be linked as consumer to the SAN device
  1716. +via |san_client_link|. This can be used to ensure that the a client
  1717. +receiving dGPU events does not miss any events due to the SAN interface not
  1718. +being set up as this forces the client driver to unbind once the SAN driver
  1719. +is unbound.
  1720. +
  1721. +Notifier-blocks can be registered by any device for as long as the module is
  1722. +loaded, regardless of being linked as client or not. Registration is done
  1723. +with |san_dgpu_notifier_register|. If the notifier is not needed any more, it
  1724. +should be unregistered via |san_dgpu_notifier_unregister|.
  1725. +
  1726. +Consult the API documentation below for more details.
  1727. +
  1728. +
  1729. +API Documentation
  1730. +=================
  1731. +
  1732. +.. kernel-doc:: include/linux/surface_acpi_notify.h
  1733. +
  1734. +.. kernel-doc:: drivers/misc/surface_aggregator/clients/surface_acpi_notify.c
  1735. + :export:
  1736. diff --git a/Documentation/driver-api/surface_aggregator/index.rst b/Documentation/driver-api/surface_aggregator/index.rst
  1737. new file mode 100644
  1738. index 000000000000..9fa70eedca59
  1739. --- /dev/null
  1740. +++ b/Documentation/driver-api/surface_aggregator/index.rst
  1741. @@ -0,0 +1,21 @@
  1742. +.. SPDX-License-Identifier: GPL-2.0+
  1743. +
  1744. +=======================================
  1745. +Surface System Aggregator Module (SSAM)
  1746. +=======================================
  1747. +
  1748. +.. toctree::
  1749. + :maxdepth: 2
  1750. +
  1751. + overview
  1752. + ssh
  1753. + client
  1754. + internal
  1755. + clients/index
  1756. +
  1757. +.. only:: subproject and html
  1758. +
  1759. + Indices
  1760. + =======
  1761. +
  1762. + * :ref:`genindex`
  1763. diff --git a/Documentation/driver-api/surface_aggregator/internal-api.rst b/Documentation/driver-api/surface_aggregator/internal-api.rst
  1764. new file mode 100644
  1765. index 000000000000..db6a70119f49
  1766. --- /dev/null
  1767. +++ b/Documentation/driver-api/surface_aggregator/internal-api.rst
  1768. @@ -0,0 +1,67 @@
  1769. +.. SPDX-License-Identifier: GPL-2.0+
  1770. +
  1771. +==========================
  1772. +Internal API Documentation
  1773. +==========================
  1774. +
  1775. +.. contents::
  1776. + :depth: 2
  1777. +
  1778. +
  1779. +Packet Transport Layer
  1780. +======================
  1781. +
  1782. +.. kernel-doc:: drivers/misc/surface_aggregator/ssh_parser.h
  1783. + :internal:
  1784. +
  1785. +.. kernel-doc:: drivers/misc/surface_aggregator/ssh_parser.c
  1786. + :internal:
  1787. +
  1788. +.. kernel-doc:: drivers/misc/surface_aggregator/ssh_msgb.h
  1789. + :internal:
  1790. +
  1791. +.. kernel-doc:: drivers/misc/surface_aggregator/ssh_packet_layer.h
  1792. + :internal:
  1793. +
  1794. +.. kernel-doc:: drivers/misc/surface_aggregator/ssh_packet_layer.c
  1795. + :internal:
  1796. +
  1797. +
  1798. +Request Transport Layer
  1799. +=======================
  1800. +
  1801. +.. kernel-doc:: drivers/misc/surface_aggregator/ssh_request_layer.h
  1802. + :internal:
  1803. +
  1804. +.. kernel-doc:: drivers/misc/surface_aggregator/ssh_request_layer.c
  1805. + :internal:
  1806. +
  1807. +
  1808. +Controller
  1809. +==========
  1810. +
  1811. +.. kernel-doc:: drivers/misc/surface_aggregator/controller.h
  1812. + :internal:
  1813. +
  1814. +.. kernel-doc:: drivers/misc/surface_aggregator/controller.c
  1815. + :internal:
  1816. +
  1817. +
  1818. +Client Device Bus
  1819. +=================
  1820. +
  1821. +.. kernel-doc:: drivers/misc/surface_aggregator/bus.c
  1822. + :internal:
  1823. +
  1824. +
  1825. +Core
  1826. +====
  1827. +
  1828. +.. kernel-doc:: drivers/misc/surface_aggregator/core.c
  1829. + :internal:
  1830. +
  1831. +
  1832. +Trace Helpers
  1833. +=============
  1834. +
  1835. +.. kernel-doc:: drivers/misc/surface_aggregator/trace.h
  1836. diff --git a/Documentation/driver-api/surface_aggregator/internal.rst b/Documentation/driver-api/surface_aggregator/internal.rst
  1837. new file mode 100644
  1838. index 000000000000..6c020b87ad62
  1839. --- /dev/null
  1840. +++ b/Documentation/driver-api/surface_aggregator/internal.rst
  1841. @@ -0,0 +1,50 @@
  1842. +.. SPDX-License-Identifier: GPL-2.0+
  1843. +
  1844. +=====================
  1845. +Core Driver Internals
  1846. +=====================
  1847. +
  1848. +For the API documentation, refer to:
  1849. +
  1850. +.. toctree::
  1851. + :maxdepth: 2
  1852. +
  1853. + internal-api
  1854. +
  1855. +
  1856. +Overview
  1857. +========
  1858. +
  1859. +The SSAM core implementation is structured in layers, somewhat following the
  1860. +SSH protocol structure:
  1861. +
  1862. +Lower-level packet transport is implemented in the *packet transport layer
  1863. +(PTL)*, directly building on top of the serial device (serdev)
  1864. +infrastructure of the kernel. As the name indicates, this layer deals with
  1865. +the packet transport logic and handles things like packet validation, packet
  1866. +acknowledgement (ACKing), packet (retransmission) timeouts, and relaying
  1867. +packet payloads to higher-level layers.
  1868. +
  1869. +Above this sits the *request transport layer (RTL)*. This layer is centered
  1870. +around command-type packet payloads, i.e. requests (sent from host to EC),
  1871. +responses of the EC to those requests, and events (sent from EC to host).
  1872. +It, specifically, distinguishes events from request responses, matches
  1873. +responses to their corresponding requests, and implements request timeouts.
  1874. +
  1875. +The *controller* layer is building on top of this and essentially decides
  1876. +how request responses and, especially, events are dealt with. It provides an
  1877. +event notifier system, handles event activation/deactivation, provides a
  1878. +workqueue for event and asynchronous request completion, and also manages
  1879. +the message counters required for building command messages (``SEQ``,
  1880. +``RQID``). This layer basically provides a fundamental interface to the SAM
  1881. +EC for use in other kernel drivers.
  1882. +
  1883. +While the controller layer already provides an interface for other kernel
  1884. +drivers, the client *bus* extends this interface to provide support for
  1885. +native SSAM devices, i.e. devices that are not defined in ACPI and not
  1886. +implemented as platform devices, via :c:type:`struct ssam_device <ssam_device>`
  1887. +and :c:type:`struct ssam_device_driver <ssam_device_driver>`. This aims to
  1888. +simplify management of client devices and client drivers.
  1889. +
  1890. +Refer to :doc:`client` for documentation regarding the client device/driver
  1891. +API and interface options for other kernel drivers.
  1892. diff --git a/Documentation/driver-api/surface_aggregator/overview.rst b/Documentation/driver-api/surface_aggregator/overview.rst
  1893. new file mode 100644
  1894. index 000000000000..b4ef7e25748c
  1895. --- /dev/null
  1896. +++ b/Documentation/driver-api/surface_aggregator/overview.rst
  1897. @@ -0,0 +1,76 @@
  1898. +.. SPDX-License-Identifier: GPL-2.0+
  1899. +
  1900. +========
  1901. +Overview
  1902. +========
  1903. +
  1904. +The Surface/System Aggregator Module (SAM, SSAM) is an (arguably *the*)
  1905. +embedded controller (EC) on Microsoft Surface devices. It has been originally
  1906. +introduced on 4th generation devices (Surface Pro 4, Surface Book 1), but
  1907. +its responsibilities and feature-set have since been expanded significantly
  1908. +with the following generations.
  1909. +
  1910. +
  1911. +Features and Integration
  1912. +========================
  1913. +
  1914. +Not much is currently known about SAM on 4th generation devices (Surface Pro
  1915. +4, Surface Book 1), due to the use of a different communication interface
  1916. +between host and EC (as detailed below). On 5th (Surface Pro 2017, Surface
  1917. +Book 2, Surface Laptop 1) and later generation devices, SAM is responsible
  1918. +for providing battery information (both current status and static values,
  1919. +such as maximum capacity etc.), as well as an assortment of temperature
  1920. +sensors (e.g. skin temperature) and cooling/performance-mode setting to the
  1921. +host. On the Surface Book 2, specifically, it additionally provides an
  1922. +interface for properly handling clipboard detachment (i.e. separating the
  1923. +display part from the keyboard part of the device), on the Surface Laptop 1
  1924. +and 2 it is required for keyboard HID input. This HID subsystem has been
  1925. +restructured for 7th generation devices and on those, specifically Surface
  1926. +Laptop 3 and Surface Book 3, is responsible for all major HID input (i.e.
  1927. +keyboard and touchpad).
  1928. +
  1929. +While the features have not changed much on a coarse level since the 5th
  1930. +generation, internal interfaces have undergone some rather large changes. On
  1931. +5th and 6th generation devices, both battery and temperature information is
  1932. +exposed to ACPI via a shim driver (referred to as Surface ACPI Notify, or
  1933. +SAN), translating ACPI generic serial bus write-/read-accesses to SAM
  1934. +requests. On 7th generation devices, this additional layer is gone and these
  1935. +devices require a driver hooking directly into the SAM interface. Equally,
  1936. +on newer generations, less devices are declared in ACPI, making them a bit
  1937. +harder to discover and requiring us to hard-code a sort of device registry.
  1938. +Due to this, a SSAM bus and subsystem with client devices
  1939. +(:c:type:`struct ssam_device <ssam_device>`) has been implemented.
  1940. +
  1941. +
  1942. +Communication
  1943. +=============
  1944. +
  1945. +The type of communication interface between host and EC depends on the
  1946. +generation of the Surface device. On 4th generation devices, host and EC
  1947. +communicate via HID, specifically using a HID-over-I2C device, whereas on
  1948. +5th and later generations, communication takes place via a USART serial
  1949. +device. In accordance to the drivers found on other operating systems, we
  1950. +refer to the serial device and its driver as Surface Serial Hub (SSH) and
  1951. +when needed to differentiate between both types of SAM as SAM-over-SSH, in
  1952. +contrast to SAM-over-HID for the former variant.
  1953. +
  1954. +Currently, this subsystem only supports SAM-over-SSH. The SSH communication
  1955. +interface is described in more detail below. The HID interface has not been
  1956. +reverse engineered yet and it is, at the moment, unclear how many (and
  1957. +which) concepts of the SSH interface detailed below can be transferred to
  1958. +it.
  1959. +
  1960. +Surface Serial Hub
  1961. +------------------
  1962. +
  1963. +As already elaborated above, the Surface Serial Hub (SSH) is the
  1964. +communication interface for SAM on 5th- and all later-generation Surface
  1965. +devices. On the highest level, communication can be separated into two main
  1966. +types: Requests, messages sent from host to EC that may trigger a direct
  1967. +response from the EC (explicitly associated with the request), and events
  1968. +(sometimes also referred to as notifications), sent from EC to host without
  1969. +being a direct response to a previous request. We may also refer to requests
  1970. +without response as commands. In general, events need to be enabled via one
  1971. +of multiple dedicated commands before they are sent by the EC.
  1972. +
  1973. +See :doc:`ssh` for a more technical protocol documentation.
  1974. diff --git a/Documentation/driver-api/surface_aggregator/ssh.rst b/Documentation/driver-api/surface_aggregator/ssh.rst
  1975. new file mode 100644
  1976. index 000000000000..0b68228010e9
  1977. --- /dev/null
  1978. +++ b/Documentation/driver-api/surface_aggregator/ssh.rst
  1979. @@ -0,0 +1,343 @@
  1980. +.. SPDX-License-Identifier: GPL-2.0+
  1981. +
  1982. +.. |u8| replace:: :c:type:`u8 <u8>`
  1983. +.. |u16| replace:: :c:type:`u16 <u16>`
  1984. +.. |TYPE| replace:: ``TYPE``
  1985. +.. |LEN| replace:: ``LEN``
  1986. +.. |SEQ| replace:: ``SEQ``
  1987. +.. |SYN| replace:: ``SYN``
  1988. +.. |NAK| replace:: ``NAK``
  1989. +.. |ACK| replace:: ``ACK``
  1990. +.. |DATA| replace:: ``DATA``
  1991. +.. |DATA_SEQ| replace:: ``DATA_SEQ``
  1992. +.. |DATA_NSQ| replace:: ``DATA_NSQ``
  1993. +.. |TC| replace:: ``TC``
  1994. +.. |TID| replace:: ``TID``
  1995. +.. |IID| replace:: ``IID``
  1996. +.. |RQID| replace:: ``RQID``
  1997. +.. |CID| replace:: ``CID``
  1998. +
  1999. +===========================
  2000. +Surface Serial Hub Protocol
  2001. +===========================
  2002. +
  2003. +The Surface Serial Hub (SSH) is the central communication interface for the
  2004. +embedded Surface Aggregator Module controller (SAM or EC) on newer Surface
  2005. +generations. We will refer to this protocol and interface as SAM-over-SSH,
  2006. +as opposed to SAM-over-HID for the older generations.
  2007. +
  2008. +On Surface devices with SAM-over-SSH, SAM is connected to the host via UART
  2009. +and defined in ACPI as device with ID ``MSHW0084``. On these devices,
  2010. +significant functionality is provided via SAM, including access to battery
  2011. +and power information and events, thermal read-outs and events, and many
  2012. +more. For Surface Laptops, keyboard input is handled via HID directed
  2013. +through SAM, on the Surface Laptop 3 and Surface Book 3 this also includes
  2014. +touchpad input.
  2015. +
  2016. +Note that the standard disclaimer for this subsystem also applies to this
  2017. +document: All of this has been reverse-engineered and may thus be erroneous
  2018. +and/or incomplete.
  2019. +
  2020. +All CRCs used in the following are two-byte ``crc_ccitt_false(0xffff, ...)``.
  2021. +All multi-byte values are little-endian, there is no implicit padding between
  2022. +values.
  2023. +
  2024. +
  2025. +SSH Packet Protocol: Definitions
  2026. +================================
  2027. +
  2028. +The fundamental communication unit of the SSH protocol is a frame
  2029. +(:c:type:`struct ssh_frame <ssh_frame>`). A frame consists of the following
  2030. +fields, packed together and in order:
  2031. +
  2032. +.. flat-table:: SSH Frame
  2033. + :widths: 1 1 4
  2034. + :header-rows: 1
  2035. +
  2036. + * - Field
  2037. + - Type
  2038. + - Description
  2039. +
  2040. + * - |TYPE|
  2041. + - |u8|
  2042. + - Type identifier of the frame.
  2043. +
  2044. + * - |LEN|
  2045. + - |u16|
  2046. + - Length of the payload associated with the frame.
  2047. +
  2048. + * - |SEQ|
  2049. + - |u8|
  2050. + - Sequence ID (see explanation below).
  2051. +
  2052. +Each frame structure is followed by a CRC over this structure. The CRC over
  2053. +the frame structure (|TYPE|, |LEN|, and |SEQ| fields) is placed directly
  2054. +after the frame structure and before the payload. The payload is followed by
  2055. +its own CRC (over all payload bytes). If the payload is not present (i.e.
  2056. +the frame has ``LEN=0``), the CRC of the payload is still present and will
  2057. +evaluate to ``0xffff``. The |LEN| field does not include any of the CRCs, it
  2058. +equals the number of bytes inbetween the CRC of the frame and the CRC of the
  2059. +payload.
  2060. +
  2061. +Additionally, the following fixed two-byte sequences are used:
  2062. +
  2063. +.. flat-table:: SSH Byte Sequences
  2064. + :widths: 1 1 4
  2065. + :header-rows: 1
  2066. +
  2067. + * - Name
  2068. + - Value
  2069. + - Description
  2070. +
  2071. + * - |SYN|
  2072. + - ``[0xAA, 0x55]``
  2073. + - Synchronization bytes.
  2074. +
  2075. +A message consists of |SYN|, followed by the frame (|TYPE|, |LEN|, |SEQ| and
  2076. +CRC) and, if specified in the frame (i.e. ``LEN > 0``), payload bytes,
  2077. +followed finally, regardless if the payload is present, the payload CRC. The
  2078. +messages corresponding to an exchange are, in part, identified by having the
  2079. +same sequence ID (|SEQ|), stored inside the frame (more on this in the next
  2080. +section). The sequence ID is a wrapping counter.
  2081. +
  2082. +A frame can have the following types
  2083. +(:c:type:`enum ssh_frame_type <ssh_frame_type>`):
  2084. +
  2085. +.. flat-table:: SSH Frame Types
  2086. + :widths: 1 1 4
  2087. + :header-rows: 1
  2088. +
  2089. + * - Name
  2090. + - Value
  2091. + - Short Description
  2092. +
  2093. + * - |NAK|
  2094. + - ``0x04``
  2095. + - Sent on error in previously received message.
  2096. +
  2097. + * - |ACK|
  2098. + - ``0x40``
  2099. + - Sent to acknowledge receival of |DATA| frame.
  2100. +
  2101. + * - |DATA_SEQ|
  2102. + - ``0x80``
  2103. + - Sent to transfer data. Sequenced.
  2104. +
  2105. + * - |DATA_NSQ|
  2106. + - ``0x00``
  2107. + - Same as |DATA_SEQ|, but does not need to be ACKed.
  2108. +
  2109. +Both |NAK|- and |ACK|-type frames are used to control flow of messages and
  2110. +thus do not carry a payload. |DATA_SEQ|- and |DATA_NSQ|-type frames on the
  2111. +other hand must carry a payload. The flow sequence and interaction of
  2112. +different frame types will be described in more depth in the next section.
  2113. +
  2114. +
  2115. +SSH Packet Protocol: Flow Sequence
  2116. +==================================
  2117. +
  2118. +Each exchange begins with |SYN|, followed by a |DATA_SEQ|- or
  2119. +|DATA_NSQ|-type frame, followed by its CRC, payload, and payload CRC. In
  2120. +case of a |DATA_NSQ|-type frame, the exchange is then finished. In case of a
  2121. +|DATA_SEQ|-type frame, the receiving party has to acknowledge receival of
  2122. +the frame by responding with a message containing an |ACK|-type frame with
  2123. +the same sequence ID of the |DATA| frame. In other words, the sequence ID of
  2124. +the |ACK| frame specifies the |DATA| frame to be acknowledged. In case of an
  2125. +error, e.g. an invalid CRC, the receiving party responds with a message
  2126. +containing an |NAK|-type frame. As the sequence ID of the previous data
  2127. +frame, for which an error is indicated via the |NAK| frame, cannot be relied
  2128. +upon, the sequence ID of the |NAK| frame should not be used and is set to
  2129. +zero. After receival of an |NAK| frame, the sending party should re-send all
  2130. +outstanding (non-ACKed) messages.
  2131. +
  2132. +Sequence IDs are not synchronized between the two parties, meaning that they
  2133. +are managed independently for each party. Identifying the messages
  2134. +corresponding to a single exchange thus relies on the sequence ID as well as
  2135. +the type of the message, and the context. Specifically, the sequence ID is
  2136. +used to associate an ``ACK`` with its ``DATA_SEQ``-type frame, but not
  2137. +``DATA_SEQ``- or ``DATA_NSQ``-type frames with other ``DATA``- type frames.
  2138. +
  2139. +An example exchange might look like this:
  2140. +
  2141. +::
  2142. +
  2143. + tx: -- SYN FRAME(D) CRC(F) PAYLOAD CRC(P) -----------------------------
  2144. + rx: ------------------------------------- SYN FRAME(A) CRC(F) CRC(P) --
  2145. +
  2146. +where both frames have the same sequence ID (``SEQ``). Here, ``FRAME(D)``
  2147. +indicates a |DATA_SEQ|-type frame, ``FRAME(A)`` an ``ACK``-type frame,
  2148. +``CRC(F)`` the CRC over the previous frame, ``CRC(P)`` the CRC over the
  2149. +previous payload. In case of an error, the exchange would look like this:
  2150. +
  2151. +::
  2152. +
  2153. + tx: -- SYN FRAME(D) CRC(F) PAYLOAD CRC(P) -----------------------------
  2154. + rx: ------------------------------------- SYN FRAME(N) CRC(F) CRC(P) --
  2155. +
  2156. +upon which the sender should re-send the message. ``FRAME(N)`` indicates an
  2157. +|NAK|-type frame. Note that the sequence ID of the |NAK|-type frame is fixed
  2158. +to zero. For |DATA_NSQ|-type frames, both exchanges are the same:
  2159. +
  2160. +::
  2161. +
  2162. + tx: -- SYN FRAME(DATA_NSQ) CRC(F) PAYLOAD CRC(P) ----------------------
  2163. + rx: -------------------------------------------------------------------
  2164. +
  2165. +Here, an error can be detected, but not corrected or indicated to the
  2166. +sending party. These exchanges are symmetric, i.e. switching rx and tx
  2167. +results again in a valid exchange. Currently, no longer exchanges are known.
  2168. +
  2169. +
  2170. +Commands: Requests, Responses, and Events
  2171. +=========================================
  2172. +
  2173. +Commands are sent as payload inside a data frame. Currently, this is the
  2174. +only known payload type of |DATA| frames, with a payload-type value of
  2175. +``0x80`` (:c:type:`SSH_PLD_TYPE_CMD <ssh_payload_type>`).
  2176. +
  2177. +The command-type payload (:c:type:`struct ssh_command <ssh_command>`)
  2178. +consists of an eight-byte command structure, followed by optional and
  2179. +variable length command data. The length of this optional data is derived
  2180. +from the frame payload length given in the corresponding frame, i.e. it is
  2181. +``frame.len - sizeof(struct ssh_command)``. The command struct contains the
  2182. +following fields, packed together and in order:
  2183. +
  2184. +.. flat-table:: SSH Command
  2185. + :widths: 1 1 4
  2186. + :header-rows: 1
  2187. +
  2188. + * - Field
  2189. + - Type
  2190. + - Description
  2191. +
  2192. + * - |TYPE|
  2193. + - |u8|
  2194. + - Type of the payload. For commands always ``0x80``.
  2195. +
  2196. + * - |TC|
  2197. + - |u8|
  2198. + - Target category.
  2199. +
  2200. + * - |TID| (out)
  2201. + - |u8|
  2202. + - Target ID for outgoing (host to EC) commands.
  2203. +
  2204. + * - |TID| (in)
  2205. + - |u8|
  2206. + - Target ID for incoming (EC to host) commands.
  2207. +
  2208. + * - |IID|
  2209. + - |u8|
  2210. + - Instance ID.
  2211. +
  2212. + * - |RQID|
  2213. + - |u16|
  2214. + - Request ID.
  2215. +
  2216. + * - |CID|
  2217. + - |u8|
  2218. + - Command ID.
  2219. +
  2220. +The command struct and data, in general, does not contain any failure
  2221. +detection mechanism (e.g. CRCs), this is solely done on the frame level.
  2222. +
  2223. +Command-type payloads are used by the host to send commands and requests to
  2224. +the EC as well as by the EC to send responses and events back to the host.
  2225. +We differentiate between requests (sent by the host), responses (sent by the
  2226. +EC in response to a request), and events (sent by the EC without a
  2227. +preceeding request).
  2228. +
  2229. +Commands and events are uniquely identified by their target category
  2230. +(``TC``) and command ID (``CID``). The target category specifies a general
  2231. +category for the command (e.g. system in general, vs. battery and ac, vs.
  2232. +temperature, and so on), while the command ID specifies the command inside
  2233. +that category. Only the combination of |TC| + |CID| is unique. Additionally,
  2234. +commands have an instance ID (``IID``), which is used to differentiate
  2235. +between different sub-devices. For example ``TC=3`` ``CID=1`` is a
  2236. +request to get the temperature on a thermal sensor, where |IID| specifies
  2237. +the respective sensor. If the instance ID is not used, it should be set to
  2238. +zero. If instance IDs are used, they, in general, start with a value of one,
  2239. +whereas zero may be used for instance independent queries, if applicable. A
  2240. +response to a request should have the same target category, command ID, and
  2241. +instance ID as the corresponding request.
  2242. +
  2243. +Responses are matched to their corresponding request via the request ID
  2244. +(``RQID``) field. This is a 16 bit wrapping counter similar to the sequence
  2245. +ID on the frames. Note that the sequence ID of the frames for a
  2246. +request-response pair does not match. Only the request ID has to match.
  2247. +Frame-protocol wise these are two separate exchanges, and may even be
  2248. +separated, e.g. by an event being sent after the request but before the
  2249. +response. Not all commands produce a response, and this is not detectable by
  2250. +|TC| + |CID|. It is the responsibility of the issuing party to wait for a
  2251. +response (or signal this to the communication framework, as is done in
  2252. +SAN/ACPI via the ``SNC`` flag).
  2253. +
  2254. +Events are identified by unique and reserved request IDs. These IDs should
  2255. +not be used by the host when sending a new request. They are used on the
  2256. +host to, first, detect events and, second, match them with a registered
  2257. +event handler. Request IDs for events are chosen by the host and directed to
  2258. +the EC when setting up and enabling an event source (via the
  2259. +enable-event-source request). The EC then uses the specified request ID for
  2260. +events sent from the respective source. Note that an event should still be
  2261. +identified by its target category, command ID, and, if applicable, instance
  2262. +ID, as a single event source can send multiple different event types. In
  2263. +general, however, a single target category should map to a single reserved
  2264. +event request ID.
  2265. +
  2266. +Furthermore, requests, responses, and events have an associated target ID
  2267. +(``TID``). This target ID is split into output (host to EC) and input (EC to
  2268. +host) fields, with the respecting other field (e.g. output field on incoming
  2269. +messages) set to zero. Two ``TID`` values are known: Primary (``0x01``) and
  2270. +secondary (``0x02``). In general, the response to a request should have the
  2271. +same ``TID`` value, however, the field (output vs. input) should be used in
  2272. +accordance to the direction in which the response is sent (i.e. on the input
  2273. +field, as responses are generally sent from the EC to the host).
  2274. +
  2275. +Note that, even though requests and events should be uniquely identifiable
  2276. +by target category and command ID alone, the EC may require specific
  2277. +priority and instance ID values to accept a command. A command that is
  2278. +accepted for ``TID=1``, for example, may not be accepted for ``TID=2``
  2279. +and vice versa.
  2280. +
  2281. +
  2282. +Limitations and Observations
  2283. +============================
  2284. +
  2285. +The protocol can, in theory, handle up to ``U8_MAX`` frames in parallel,
  2286. +with up to ``U16_MAX`` pending requests (neglecting request IDs reserved for
  2287. +events). In practice, however, this is more limited. From our testing
  2288. +(altough via a python and thus a user-space program), it seems that the EC
  2289. +can handle up to four requests (mostly) reliably in parallel at a certain
  2290. +time. With five or more requests in parallel, consistent discarding of
  2291. +commands (ACKed frame but no command response) has been observed. For five
  2292. +simultaneous commands, this reproducibly resulted in one command being
  2293. +dropped and four commands being handled.
  2294. +
  2295. +However, it has also been noted that, even with three requests in parallel,
  2296. +occasional frame drops happen. Apart from this, with a limit of three
  2297. +pending requests, no dropped commands (i.e. command being dropped but frame
  2298. +carrying command being ACKed) have been observed. In any case, frames (and
  2299. +possibly also commands) should be re-sent by the host if a certain timeout
  2300. +is exceeded. This is done by the EC for frames with a timeout of one second,
  2301. +up to two re-tries (i.e. three transmissions in total). The limit of
  2302. +re-tries also applies to received NAKs, and, in a worst case scenario, can
  2303. +lead to entire messages being dropped.
  2304. +
  2305. +While this also seems to work fine for pending data frames as long as no
  2306. +transmission failures occur, implementation and handling of these seems to
  2307. +depend on the assumption that there is only one non-acknowledged data frame.
  2308. +In particular, the detection of repeated frames relies on the last sequence
  2309. +number. This means that, if a frame that has been successfully received by
  2310. +the EC is sent again, e.g. due to the host not receiving an |ACK|, the EC
  2311. +will only detect this if it has the sequence ID of the last frame received
  2312. +by the EC. As an example: Sending two frames with ``SEQ=0`` and ``SEQ=1``
  2313. +followed by a repetition of ``SEQ=0`` will not detect the second ``SEQ=0``
  2314. +frame as such, and thus execute the command in this frame each time it has
  2315. +been received, i.e. twice in this example. Sending ``SEQ=0``, ``SEQ=1`` and
  2316. +then repeating ``SEQ=1`` will detect the second ``SEQ=1`` as repetition of
  2317. +the first one and ignore it, thus executing the contained command only once.
  2318. +
  2319. +In conclusion, this suggests a limit of at most one pending un-ACKed frame
  2320. +(per party, effectively leading to synchronous communication regarding
  2321. +frames) and at most three pending commands. The limit to synchronous frame
  2322. +transfers seems to be consistent with behavior observed on Windows.
  2323. diff --git a/drivers/misc/Kconfig b/drivers/misc/Kconfig
  2324. index be901ffc66fe..88f4231d0ed1 100644
  2325. --- a/drivers/misc/Kconfig
  2326. +++ b/drivers/misc/Kconfig
  2327. @@ -472,5 +472,6 @@ source "drivers/misc/ocxl/Kconfig"
  2328. source "drivers/misc/cardreader/Kconfig"
  2329. source "drivers/misc/habanalabs/Kconfig"
  2330. source "drivers/misc/uacce/Kconfig"
  2331. +source "drivers/misc/surface_aggregator/Kconfig"
  2332. source "drivers/misc/ipts/Kconfig"
  2333. endmenu
  2334. diff --git a/drivers/misc/Makefile b/drivers/misc/Makefile
  2335. index f97938d777e1..b0caee1dd3b7 100644
  2336. --- a/drivers/misc/Makefile
  2337. +++ b/drivers/misc/Makefile
  2338. @@ -58,3 +58,4 @@ obj-$(CONFIG_HABANA_AI) += habanalabs/
  2339. obj-$(CONFIG_UACCE) += uacce/
  2340. obj-$(CONFIG_XILINX_SDFEC) += xilinx_sdfec.o
  2341. obj-$(CONFIG_MISC_IPTS) += ipts/
  2342. +obj-$(CONFIG_SURFACE_AGGREGATOR) += surface_aggregator/
  2343. diff --git a/drivers/misc/surface_aggregator/Kconfig b/drivers/misc/surface_aggregator/Kconfig
  2344. new file mode 100644
  2345. index 000000000000..47dd8fdffac3
  2346. --- /dev/null
  2347. +++ b/drivers/misc/surface_aggregator/Kconfig
  2348. @@ -0,0 +1,67 @@
  2349. +# SPDX-License-Identifier: GPL-2.0+
  2350. +# Copyright (C) 2019-2020 Maximilian Luz <luzmaximilian@gmail.com>
  2351. +
  2352. +menuconfig SURFACE_AGGREGATOR
  2353. + tristate "Microsoft Surface System Aggregator Module Subsystem and Drivers"
  2354. + depends on SERIAL_DEV_BUS
  2355. + depends on ACPI
  2356. + select CRC_CCITT
  2357. + help
  2358. + The Surface System Aggregator Module (Surface SAM or SSAM) is an
  2359. + embedded controller (EC) found on 5th- and later-generation Microsoft
  2360. + Surface devices (i.e. Surface Pro 5, Surface Book 2, Surface Laptop,
  2361. + and newer, with exception of Surface Go series devices).
  2362. +
  2363. + Depending on the device in question, this EC provides varying
  2364. + functionality, including:
  2365. + - EC access from ACPI via Surface ACPI Notify (5th- and 6th-generation)
  2366. + - battery status information (all devices)
  2367. + - thermal sensor access (all devices)
  2368. + - performance mode / cooling mode control (all devices)
  2369. + - clipboard detachment system control (Surface Book 2 and 3)
  2370. + - HID / keyboard input (Surface Laptops, Surface Book 3)
  2371. +
  2372. + This option controls whether the Surface SAM subsystem core will be
  2373. + built. This includes a driver for the Surface Serial Hub (SSH), which
  2374. + is the device responsible for the communication with the EC, and a
  2375. + basic kernel interface exposing the EC functionality to other client
  2376. + drivers, i.e. allowing them to make requests to the EC and receive
  2377. + events from it. Selecting this option alone will not provide any
  2378. + client drivers and therefore no functionality beyond the in-kernel
  2379. + interface. Said functionality is the repsonsibility of the respective
  2380. + client drivers.
  2381. +
  2382. + Note: While 4th-generation Surface devices also make use of a SAM EC,
  2383. + due to a difference in the communication interface of the controller,
  2384. + only 5th and later generations are currently supported. Specifically,
  2385. + devices using SAM-over-SSH are supported, whereas devices using
  2386. + SAM-over-HID, which is used on the 4th generation, are currently not
  2387. + supported.
  2388. +
  2389. +config SURFACE_AGGREGATOR_BUS
  2390. + bool "Surface System Aggregator Module Bus"
  2391. + depends on SURFACE_AGGREGATOR
  2392. + default y
  2393. + help
  2394. + Expands the Surface System Aggregator Module (SSAM) core driver by
  2395. + providing a dedicated bus and client-device type.
  2396. +
  2397. + This bus and device type are intended to provide and simplify support
  2398. + for non-platform and non-ACPI SSAM devices, i.e. SSAM devices that are
  2399. + not auto-detectable via the conventional means (e.g. ACPI).
  2400. +
  2401. +config SURFACE_AGGREGATOR_ERROR_INJECTION
  2402. + bool "Surface System Aggregator Module Error Injection Capabilities"
  2403. + depends on SURFACE_AGGREGATOR
  2404. + depends on FUNCTION_ERROR_INJECTION
  2405. + help
  2406. + Provides error-injection capabilities for the Surface System
  2407. + Aggregator Module subsystem and Surface Serial Hub driver.
  2408. +
  2409. + Specifically, exports error injection hooks to be used with the
  2410. + kernel's function error injection capabilities to simulate underlying
  2411. + transport and communication problems, such as invalid data sent to or
  2412. + received from the EC, dropped data, and communication timeouts.
  2413. + Intended for development and debugging.
  2414. +
  2415. +source "drivers/misc/surface_aggregator/clients/Kconfig"
  2416. diff --git a/drivers/misc/surface_aggregator/Makefile b/drivers/misc/surface_aggregator/Makefile
  2417. new file mode 100644
  2418. index 000000000000..b48ffc37ab52
  2419. --- /dev/null
  2420. +++ b/drivers/misc/surface_aggregator/Makefile
  2421. @@ -0,0 +1,18 @@
  2422. +# SPDX-License-Identifier: GPL-2.0+
  2423. +# Copyright (C) 2019-2020 Maximilian Luz <luzmaximilian@gmail.com>
  2424. +
  2425. +# For include/trace/define_trace.h to include trace.h
  2426. +CFLAGS_core.o = -I$(src)
  2427. +
  2428. +obj-$(CONFIG_SURFACE_AGGREGATOR) += surface_aggregator.o
  2429. +obj-$(CONFIG_SURFACE_AGGREGATOR) += clients/
  2430. +
  2431. +surface_aggregator-objs := core.o
  2432. +surface_aggregator-objs += ssh_parser.o
  2433. +surface_aggregator-objs += ssh_packet_layer.o
  2434. +surface_aggregator-objs += ssh_request_layer.o
  2435. +surface_aggregator-objs += controller.o
  2436. +
  2437. +ifeq ($(CONFIG_SURFACE_AGGREGATOR_BUS),y)
  2438. +surface_aggregator-objs += bus.o
  2439. +endif
  2440. diff --git a/drivers/misc/surface_aggregator/bus.c b/drivers/misc/surface_aggregator/bus.c
  2441. new file mode 100644
  2442. index 000000000000..5e734bbd18cd
  2443. --- /dev/null
  2444. +++ b/drivers/misc/surface_aggregator/bus.c
  2445. @@ -0,0 +1,424 @@
  2446. +// SPDX-License-Identifier: GPL-2.0+
  2447. +/*
  2448. + * Surface System Aggregator Module bus and device integration.
  2449. + *
  2450. + * Copyright (C) 2019-2020 Maximilian Luz <luzmaximilian@gmail.com>
  2451. + */
  2452. +
  2453. +#include <linux/device.h>
  2454. +#include <linux/slab.h>
  2455. +
  2456. +#include <linux/surface_aggregator/controller.h>
  2457. +#include <linux/surface_aggregator/device.h>
  2458. +
  2459. +#include "bus.h"
  2460. +#include "controller.h"
  2461. +
  2462. +
  2463. +static ssize_t modalias_show(struct device *dev, struct device_attribute *attr,
  2464. + char *buf)
  2465. +{
  2466. + struct ssam_device *sdev = to_ssam_device(dev);
  2467. +
  2468. + return snprintf(buf, PAGE_SIZE - 1, "ssam:d%02Xc%02Xt%02Xi%02xf%02X\n",
  2469. + sdev->uid.domain, sdev->uid.category, sdev->uid.target,
  2470. + sdev->uid.instance, sdev->uid.function);
  2471. +}
  2472. +static DEVICE_ATTR_RO(modalias);
  2473. +
  2474. +static struct attribute *ssam_device_attrs[] = {
  2475. + &dev_attr_modalias.attr,
  2476. + NULL,
  2477. +};
  2478. +ATTRIBUTE_GROUPS(ssam_device);
  2479. +
  2480. +static int ssam_device_uevent(struct device *dev, struct kobj_uevent_env *env)
  2481. +{
  2482. + struct ssam_device *sdev = to_ssam_device(dev);
  2483. +
  2484. + return add_uevent_var(env, "MODALIAS=ssam:d%02Xc%02Xt%02Xi%02xf%02X",
  2485. + sdev->uid.domain, sdev->uid.category,
  2486. + sdev->uid.target, sdev->uid.instance,
  2487. + sdev->uid.function);
  2488. +}
  2489. +
  2490. +static void ssam_device_release(struct device *dev)
  2491. +{
  2492. + struct ssam_device *sdev = to_ssam_device(dev);
  2493. +
  2494. + ssam_controller_put(sdev->ctrl);
  2495. + kfree(sdev);
  2496. +}
  2497. +
  2498. +const struct device_type ssam_device_type = {
  2499. + .name = "surface_aggregator_device",
  2500. + .groups = ssam_device_groups,
  2501. + .uevent = ssam_device_uevent,
  2502. + .release = ssam_device_release,
  2503. +};
  2504. +EXPORT_SYMBOL_GPL(ssam_device_type);
  2505. +
  2506. +
  2507. +/**
  2508. + * ssam_device_alloc() - Allocate and initialize a SSAM client device.
  2509. + * @ctrl: The controller under which the device should be added.
  2510. + * @uid: The UID of the device to be added.
  2511. + *
  2512. + * Allocates and initializes a new client device. The parent of the device
  2513. + * will be set to the controller device and the name will be set based on the
  2514. + * UID. Note that the device still has to be added via ssam_device_add().
  2515. + * Refer to that function for more details.
  2516. + *
  2517. + * Return: Returns the newly allocated and initialized SSAM client device, or
  2518. + * %NULL if it could not be allocated.
  2519. + */
  2520. +struct ssam_device *ssam_device_alloc(struct ssam_controller *ctrl,
  2521. + struct ssam_device_uid uid)
  2522. +{
  2523. + struct ssam_device *sdev;
  2524. +
  2525. + sdev = kzalloc(sizeof(*sdev), GFP_KERNEL);
  2526. + if (!sdev)
  2527. + return NULL;
  2528. +
  2529. + device_initialize(&sdev->dev);
  2530. + sdev->dev.bus = &ssam_bus_type;
  2531. + sdev->dev.type = &ssam_device_type;
  2532. + sdev->dev.parent = ssam_controller_device(ctrl);
  2533. + sdev->ctrl = ssam_controller_get(ctrl);
  2534. + sdev->uid = uid;
  2535. +
  2536. + dev_set_name(&sdev->dev, "%02x:%02x:%02x:%02x:%02x",
  2537. + sdev->uid.domain, sdev->uid.category, sdev->uid.target,
  2538. + sdev->uid.instance, sdev->uid.function);
  2539. +
  2540. + return sdev;
  2541. +}
  2542. +EXPORT_SYMBOL_GPL(ssam_device_alloc);
  2543. +
  2544. +/**
  2545. + * ssam_device_add() - Add a SSAM client device.
  2546. + * @sdev: The SSAM client device to be added.
  2547. + *
  2548. + * Added client devices must be guaranteed to always have a valid and active
  2549. + * controller. Thus, this function will fail with %-ENXIO if the controller of
  2550. + * the device has not been initialized yet, has been suspended, or has been
  2551. + * shut down.
  2552. + *
  2553. + * The caller of this function should ensure that the corresponding call to
  2554. + * ssam_device_remove() is issued before the controller is shut down. If the
  2555. + * added device is a direct child of the controller device (default), it will
  2556. + * be automatically removed when the controller is shut down.
  2557. + *
  2558. + * By default, the controller device will become the parent of the newly
  2559. + * created client device. The parent may be changed before ssam_device_add is
  2560. + * called, but care must be taken that a) the correct suspend/resume ordering
  2561. + * is guaranteed and b) the client device does not oultive the controller,
  2562. + * i.e. that the device is removed before the controller is being shut down.
  2563. + * In case these guarantees have to be manually enforced, please refer to the
  2564. + * ssam_client_link() and ssam_client_bind() functions, which are intended to
  2565. + * set up device-links for this purpose.
  2566. + *
  2567. + * Return: Returns zero on success, a negative error code on failure.
  2568. + */
  2569. +int ssam_device_add(struct ssam_device *sdev)
  2570. +{
  2571. + int status;
  2572. +
  2573. + /*
  2574. + * Ensure that we can only add new devices to a controller if it has
  2575. + * been started and is not going away soon. This works in combination
  2576. + * with ssam_controller_remove_clients to ensure driver presence for the
  2577. + * controller device, i.e. it ensures that the controller (sdev->ctrl)
  2578. + * is always valid and can be used for requests as long as the client
  2579. + * device we add here is registered as child under it. This essentially
  2580. + * guarantees that the client driver can always expect the preconditions
  2581. + * for functions like ssam_request_sync (controller has to be started
  2582. + * and is not suspended) to hold and thus does not have to check for
  2583. + * them.
  2584. + *
  2585. + * Note that for this to work, the controller has to be a parent device.
  2586. + * If it is not a direct parent, care has to be taken that the device is
  2587. + * removed via ssam_device_remove(), as device_unregister does not
  2588. + * remove child devices recursively.
  2589. + */
  2590. + ssam_controller_statelock(sdev->ctrl);
  2591. +
  2592. + if (sdev->ctrl->state != SSAM_CONTROLLER_STARTED) {
  2593. + ssam_controller_stateunlock(sdev->ctrl);
  2594. + return -ENXIO;
  2595. + }
  2596. +
  2597. + status = device_add(&sdev->dev);
  2598. +
  2599. + ssam_controller_stateunlock(sdev->ctrl);
  2600. + return status;
  2601. +}
  2602. +EXPORT_SYMBOL_GPL(ssam_device_add);
  2603. +
  2604. +/**
  2605. + * ssam_device_remove() - Remove a SSAM client device.
  2606. + * @sdev: The device to remove.
  2607. + *
  2608. + * Removes and unregisters the provided SSAM client device.
  2609. + */
  2610. +void ssam_device_remove(struct ssam_device *sdev)
  2611. +{
  2612. + device_unregister(&sdev->dev);
  2613. +}
  2614. +EXPORT_SYMBOL_GPL(ssam_device_remove);
  2615. +
  2616. +
  2617. +/**
  2618. + * ssam_device_id_compatible() - Check if a device ID matches a UID.
  2619. + * @id: The device ID as potential match.
  2620. + * @uid: The device UID matching against.
  2621. + *
  2622. + * Check if the given ID is a match for the given UID, i.e. if a device with
  2623. + * the provided UID is compatible to the given ID following the match rules
  2624. + * described in its &ssam_device_id.match_flags member.
  2625. + *
  2626. + * Return: Returns %true iff the given UID is compatible to the match rule
  2627. + * described by the given ID, %false otherwise.
  2628. + */
  2629. +static bool ssam_device_id_compatible(const struct ssam_device_id *id,
  2630. + struct ssam_device_uid uid)
  2631. +{
  2632. + if (id->domain != uid.domain || id->category != uid.category)
  2633. + return false;
  2634. +
  2635. + if ((id->match_flags & SSAM_MATCH_TARGET) && id->target != uid.target)
  2636. + return false;
  2637. +
  2638. + if ((id->match_flags & SSAM_MATCH_INSTANCE) && id->instance != uid.instance)
  2639. + return false;
  2640. +
  2641. + if ((id->match_flags & SSAM_MATCH_FUNCTION) && id->function != uid.function)
  2642. + return false;
  2643. +
  2644. + return true;
  2645. +}
  2646. +
  2647. +/**
  2648. + * ssam_device_id_is_null() - Check if a device ID is null.
  2649. + * @id: The device ID to check.
  2650. + *
  2651. + * Check if a given device ID is null, i.e. all zeros. Used to check for the
  2652. + * end of ``MODULE_DEVICE_TABLE(ssam, ...)`` or similar lists.
  2653. + *
  2654. + * Return: Returns %true if the given ID represents a null ID, %false
  2655. + * otherwise.
  2656. + */
  2657. +static bool ssam_device_id_is_null(const struct ssam_device_id *id)
  2658. +{
  2659. + return id->match_flags == 0
  2660. + && id->domain == 0
  2661. + && id->category == 0
  2662. + && id->target == 0
  2663. + && id->instance == 0
  2664. + && id->function == 0
  2665. + && id->driver_data == 0;
  2666. +}
  2667. +
  2668. +/**
  2669. + * ssam_device_id_match() - Find the matching ID table entry for the given UID.
  2670. + * @table: The table to search in.
  2671. + * @uid: The UID to matched against the individual table entries.
  2672. + *
  2673. + * Find the first match for the provided device UID in the provided ID table
  2674. + * and return it. Returns %NULL if no match could be found.
  2675. + */
  2676. +const struct ssam_device_id *ssam_device_id_match(
  2677. + const struct ssam_device_id *table,
  2678. + const struct ssam_device_uid uid)
  2679. +{
  2680. + const struct ssam_device_id *id;
  2681. +
  2682. + for (id = table; !ssam_device_id_is_null(id); ++id)
  2683. + if (ssam_device_id_compatible(id, uid))
  2684. + return id;
  2685. +
  2686. + return NULL;
  2687. +}
  2688. +EXPORT_SYMBOL_GPL(ssam_device_id_match);
  2689. +
  2690. +/**
  2691. + * ssam_device_get_match() - Find and return the ID matching the device in the
  2692. + * ID table of the bound driver.
  2693. + * @dev: The device for which to get the matching ID table entry.
  2694. + *
  2695. + * Find the fist match for the UID of the device in the ID table of the
  2696. + * currently bound driver and return it. Returns %NULL if the device does not
  2697. + * have a driver bound to it, the driver does not have match_table (i.e. it is
  2698. + * %NULL), or there is no match in the driver's match_table.
  2699. + *
  2700. + * This function essentially calls ssam_device_id_match() with the ID table of
  2701. + * the bound device driver and the UID of the device.
  2702. + *
  2703. + * Return: Returns the first match for the UID of the device in the device
  2704. + * driver's match table, or %NULL if no such match could be found.
  2705. + */
  2706. +const struct ssam_device_id *ssam_device_get_match(
  2707. + const struct ssam_device *dev)
  2708. +{
  2709. + const struct ssam_device_driver *sdrv;
  2710. +
  2711. + sdrv = to_ssam_device_driver(dev->dev.driver);
  2712. + if (!sdrv)
  2713. + return NULL;
  2714. +
  2715. + if (!sdrv->match_table)
  2716. + return NULL;
  2717. +
  2718. + return ssam_device_id_match(sdrv->match_table, dev->uid);
  2719. +}
  2720. +EXPORT_SYMBOL_GPL(ssam_device_get_match);
  2721. +
  2722. +/**
  2723. + * ssam_device_get_match_data() - Find the ID matching the device in hte
  2724. + * ID table of the bound driver and return its ``driver_data`` member.
  2725. + * @dev: The device for which to get the match data.
  2726. + *
  2727. + * Find the fist match for the UID of the device in the ID table of the
  2728. + * corresponding driver and return its driver_data. Returns %NULL if the
  2729. + * device does not have a driver bound to it, the driver does not have
  2730. + * match_table (i.e. it is %NULL), there is no match in the driver's
  2731. + * match_table, or the match does not have any driver_data.
  2732. + *
  2733. + * This function essentially calls ssam_device_get_match() and, if any match
  2734. + * could be found, returns its ``struct ssam_device_id.driver_data`` member.
  2735. + *
  2736. + * Return: Returns the driver data associated with the first match for the UID
  2737. + * of the device in the device driver's match table, or %NULL if no such match
  2738. + * could be found.
  2739. + */
  2740. +const void *ssam_device_get_match_data(const struct ssam_device *dev)
  2741. +{
  2742. + const struct ssam_device_id *id;
  2743. +
  2744. + id = ssam_device_get_match(dev);
  2745. + if (!id)
  2746. + return NULL;
  2747. +
  2748. + return (const void *)id->driver_data;
  2749. +}
  2750. +EXPORT_SYMBOL_GPL(ssam_device_get_match_data);
  2751. +
  2752. +
  2753. +static int ssam_bus_match(struct device *dev, struct device_driver *drv)
  2754. +{
  2755. + struct ssam_device_driver *sdrv = to_ssam_device_driver(drv);
  2756. + struct ssam_device *sdev = to_ssam_device(dev);
  2757. +
  2758. + if (!is_ssam_device(dev))
  2759. + return 0;
  2760. +
  2761. + return !!ssam_device_id_match(sdrv->match_table, sdev->uid);
  2762. +}
  2763. +
  2764. +static int ssam_bus_probe(struct device *dev)
  2765. +{
  2766. + return to_ssam_device_driver(dev->driver)
  2767. + ->probe(to_ssam_device(dev));
  2768. +}
  2769. +
  2770. +static int ssam_bus_remove(struct device *dev)
  2771. +{
  2772. + struct ssam_device_driver *sdrv = to_ssam_device_driver(dev->driver);
  2773. +
  2774. + if (sdrv->remove)
  2775. + sdrv->remove(to_ssam_device(dev));
  2776. +
  2777. + return 0;
  2778. +}
  2779. +
  2780. +struct bus_type ssam_bus_type = {
  2781. + .name = "surface_aggregator",
  2782. + .match = ssam_bus_match,
  2783. + .probe = ssam_bus_probe,
  2784. + .remove = ssam_bus_remove,
  2785. +};
  2786. +EXPORT_SYMBOL_GPL(ssam_bus_type);
  2787. +
  2788. +
  2789. +/**
  2790. + * __ssam_device_driver_register() - Register a SSAM client device driver.
  2791. + * @sdrv: The driver to register.
  2792. + * @owner: The module owning the provided driver.
  2793. + *
  2794. + * Please refer to the ssam_device_driver_register() macro for the normal way
  2795. + * to register a driver from inside its owning module.
  2796. + */
  2797. +int __ssam_device_driver_register(struct ssam_device_driver *sdrv,
  2798. + struct module *owner)
  2799. +{
  2800. + sdrv->driver.owner = owner;
  2801. + sdrv->driver.bus = &ssam_bus_type;
  2802. +
  2803. + /* force drivers to async probe so I/O is possible in probe */
  2804. + sdrv->driver.probe_type = PROBE_PREFER_ASYNCHRONOUS;
  2805. +
  2806. + return driver_register(&sdrv->driver);
  2807. +}
  2808. +EXPORT_SYMBOL_GPL(__ssam_device_driver_register);
  2809. +
  2810. +/**
  2811. + * ssam_device_driver_unregister - Unregister a SSAM device driver.
  2812. + * @sdrv: The driver to unregister.
  2813. + */
  2814. +void ssam_device_driver_unregister(struct ssam_device_driver *sdrv)
  2815. +{
  2816. + driver_unregister(&sdrv->driver);
  2817. +}
  2818. +EXPORT_SYMBOL_GPL(ssam_device_driver_unregister);
  2819. +
  2820. +
  2821. +static int ssam_remove_device(struct device *dev, void *_data)
  2822. +{
  2823. + struct ssam_device *sdev = to_ssam_device(dev);
  2824. +
  2825. + if (is_ssam_device(dev))
  2826. + ssam_device_remove(sdev);
  2827. +
  2828. + return 0;
  2829. +}
  2830. +
  2831. +/**
  2832. + * ssam_controller_remove_clients() - Remove SSAM client devices registered as
  2833. + * direct children under the given controller.
  2834. + * @ctrl: The controller to remove all direct clients for.
  2835. + *
  2836. + * Remove all SSAM client devices registered as direct children under the
  2837. + * given controller. Note that this only accounts for direct children ot the
  2838. + * controller device. This does not take care of any client devices where the
  2839. + * parent device has been manually set before calling ssam_device_add. Refer
  2840. + * to ssam_device_add()/ssam_device_remove() for more details on those cases.
  2841. + *
  2842. + * To avoid new devices being added in parallel to this call, the main
  2843. + * controller lock (not statelock) must be held during this (and if
  2844. + * necessary, any subsequent deinitialization) call.
  2845. + */
  2846. +void ssam_controller_remove_clients(struct ssam_controller *ctrl)
  2847. +{
  2848. + struct device *dev;
  2849. +
  2850. + dev = ssam_controller_device(ctrl);
  2851. + device_for_each_child_reverse(dev, NULL, ssam_remove_device);
  2852. +}
  2853. +
  2854. +
  2855. +/**
  2856. + * ssam_bus_register() - Register and set-up the SSAM client device bus.
  2857. + */
  2858. +int ssam_bus_register(void)
  2859. +{
  2860. + return bus_register(&ssam_bus_type);
  2861. +}
  2862. +
  2863. +/**
  2864. + * ssam_bus_unregister() - Unregister the SSAM client device bus.
  2865. + */
  2866. +void ssam_bus_unregister(void)
  2867. +{
  2868. + return bus_unregister(&ssam_bus_type);
  2869. +}
  2870. diff --git a/drivers/misc/surface_aggregator/bus.h b/drivers/misc/surface_aggregator/bus.h
  2871. new file mode 100644
  2872. index 000000000000..7712baaed6a5
  2873. --- /dev/null
  2874. +++ b/drivers/misc/surface_aggregator/bus.h
  2875. @@ -0,0 +1,27 @@
  2876. +/* SPDX-License-Identifier: GPL-2.0+ */
  2877. +/*
  2878. + * Surface System Aggregator Module bus and device integration.
  2879. + *
  2880. + * Copyright (C) 2019-2020 Maximilian Luz <luzmaximilian@gmail.com>
  2881. + */
  2882. +
  2883. +#ifndef _SURFACE_AGGREGATOR_BUS_H
  2884. +#define _SURFACE_AGGREGATOR_BUS_H
  2885. +
  2886. +#include <linux/surface_aggregator/controller.h>
  2887. +
  2888. +#ifdef CONFIG_SURFACE_AGGREGATOR_BUS
  2889. +
  2890. +void ssam_controller_remove_clients(struct ssam_controller *ctrl);
  2891. +
  2892. +int ssam_bus_register(void);
  2893. +void ssam_bus_unregister(void);
  2894. +
  2895. +#else /* CONFIG_SURFACE_AGGREGATOR_BUS */
  2896. +
  2897. +static inline void ssam_controller_remove_clients(struct ssam_controller *ctrl) {}
  2898. +static inline int ssam_bus_register(void) { return 0; }
  2899. +static inline void ssam_bus_unregister(void) {}
  2900. +
  2901. +#endif /* CONFIG_SURFACE_AGGREGATOR_BUS */
  2902. +#endif /* _SURFACE_AGGREGATOR_BUS_H */
  2903. diff --git a/drivers/misc/surface_aggregator/clients/Kconfig b/drivers/misc/surface_aggregator/clients/Kconfig
  2904. new file mode 100644
  2905. index 000000000000..3c438cb3f0ca
  2906. --- /dev/null
  2907. +++ b/drivers/misc/surface_aggregator/clients/Kconfig
  2908. @@ -0,0 +1,151 @@
  2909. +# SPDX-License-Identifier: GPL-2.0+
  2910. +# Copyright (C) 2019-2020 Maximilian Luz <luzmaximilian@gmail.com>
  2911. +
  2912. +config SURFACE_AGGREGATOR_CDEV
  2913. + tristate "Surface System Aggregator Module User-Space Interface"
  2914. + depends on SURFACE_AGGREGATOR
  2915. + help
  2916. + Provides a misc-device interface to the Surface System Aggregator
  2917. + Module (SSAM) controller.
  2918. +
  2919. + This option provides a module (called surface_aggregator_cdev), that,
  2920. + when loaded, will add a client device (and its respective driver) to
  2921. + the SSAM controller. Said client device manages a misc-device
  2922. + interface (/dev/surface/aggregator), which can be used by user-space
  2923. + tools to directly communicate with the SSAM EC by sending requests and
  2924. + receiving the correspondign responses.
  2925. +
  2926. + The provided interface is intended for debugging and development only,
  2927. + and should not be used otherwise.
  2928. +
  2929. +config SURFACE_AGGREGATOR_REGISTRY
  2930. + tristate "Surface System Aggregator Module Device Registry"
  2931. + depends on SURFACE_AGGREGATOR_BUS
  2932. + default m
  2933. + help
  2934. + Device-registry and device-hubs for Surface System Aggregator Module
  2935. + (SSAM) devices.
  2936. +
  2937. + Provides a module and driver which act as device-registry for SSAM
  2938. + client devices that cannot be detected automatically, e.g. via ACPI.
  2939. + Such devices are instead provided via this registry and attached via
  2940. + device hubs, also provided in this module.
  2941. +
  2942. + Devices provided via this registry are:
  2943. + - performance / cooling mode device (all generations)
  2944. + - battery/AC devices (7th generation)
  2945. + - HID input devices (7th generation)
  2946. +
  2947. + Note that this module only provides the respective client devices.
  2948. + Drivers for these devices still need to be selected via the other
  2949. + options.
  2950. +
  2951. +config SURFACE_ACPI_NOTIFY
  2952. + tristate "Surface ACPI Notify Driver"
  2953. + depends on SURFACE_AGGREGATOR
  2954. + default m
  2955. + help
  2956. + Surface ACPI Notify (SAN) driver for Microsoft Surface devices.
  2957. +
  2958. + This driver provides support for the ACPI interface (called SAN) of
  2959. + the Surface System Aggregator Module (SSAM) EC. This interface is used
  2960. + on 5th- and 6th-generation Microsoft Surface devices (including
  2961. + Surface Pro 5 and 6, Surface Book 2, Surface Laptops 1 and 2, and in
  2962. + reduced functionality on the Surface Laptop 3) to execute SSAM
  2963. + requests directly from ACPI code, as well as receive SSAM events and
  2964. + turn them into ACPI notifications. It essentially acts as a
  2965. + translation layer between the SSAM controller and ACPI.
  2966. +
  2967. + Specifically, this driver may be needed for battery status reporting,
  2968. + thermal sensor access, and real-time clock information, depending on
  2969. + the Surface device in question.
  2970. +
  2971. +config SURFACE_BATTERY
  2972. + tristate "Surface Battery Driver"
  2973. + depends on SURFACE_AGGREGATOR_BUS
  2974. + select POWER_SUPPLY
  2975. + default m
  2976. + help
  2977. + Driver for battery and AC-adapter devices connected/managed via the
  2978. + Surface System Aggregator Module (SSAM) EC.
  2979. +
  2980. + This driver provides battery-/AC-information and -status support for
  2981. + Surface devices where said data is not exposed via the standard ACPI
  2982. + devices. On those models (7th-generation, i.e. Surface pro 7, Surface
  2983. + Laptop 3, and Surface Book 3), battery-/AC-status and -information is
  2984. + instead handled directly via SSAM client devices.
  2985. +
  2986. +config SURFACE_DTX
  2987. + tristate "Surface Detachment System Driver"
  2988. + depends on SURFACE_AGGREGATOR
  2989. + depends on INPUT
  2990. + default m
  2991. + help
  2992. + Driver for the Surface Book clipboard detachment system (DTX).
  2993. +
  2994. + On the Surface Book series devices, the display part containing the
  2995. + CPU (called the clipboard) can be detached from the base (containing a
  2996. + battery, the keyboard, and, optionally, a discrete GPU) by (if
  2997. + necessary) unlocking and opening the latch connecting both parts.
  2998. +
  2999. + This driver provides a user-space interface that can influence the
  3000. + behavior of this process, which includes the option to abort it in
  3001. + case the base is still in use or speed it up in case it is not.
  3002. +
  3003. + Note that this module can be built without support for the Surface
  3004. + Aggregator Bus (i.e. CONFIG_SURFACE_AGGREGATOR_BUS=n). In that case,
  3005. + some devices, specifically the Surface Book 3, will not be supported.
  3006. +
  3007. +config SURFACE_HID
  3008. + tristate "Surface HID Transport Driver"
  3009. + depends on SURFACE_AGGREGATOR_BUS
  3010. + depends on HID
  3011. + default m
  3012. + help
  3013. + Transport driver for HID devices connected via the Surface System
  3014. + Aggregator Module (SSAM).
  3015. +
  3016. + This driver provides support for HID input devices (e.g. touchpad and
  3017. + keyboard) connected via SSAM. It is required for keyboard input on the
  3018. + Surface Laptop 1 and 2, as well as keyboard and touchpad input on the
  3019. + Surface Laptop 3 and Surface Book 3.
  3020. +
  3021. + Note that this module can be built without support for the Surface
  3022. + Aggregator Bus (i.e. CONFIG_SURFACE_AGGREGATOR_BUS=n). In that case,
  3023. + some devices, specifically the Surface Book 3 and Surface Laptop 3,
  3024. + will not be supported.
  3025. +
  3026. +config SURFACE_HOTPLUG
  3027. + tristate "Surface Hot-Plug System Driver"
  3028. + depends on SURFACE_AGGREGATOR
  3029. + depends on SURFACE_ACPI_NOTIFY
  3030. + depends on GPIO_SYSFS
  3031. + default m
  3032. + help
  3033. + Driver for the Surface discrete GPU (dGPU) hot-plug system.
  3034. +
  3035. + This driver manages the dGPU power on the Surface Books, including
  3036. + when hot-plugging it by detaching the clipboard (display part
  3037. + containing the CPU) from the base (containing the keyboard and dGPU)
  3038. + of the device when it is running. This driver also provides a
  3039. + user-space interface via which the dGPU power-state (on/off) can be
  3040. + set, allowing users to turn off the dGPU in order to reduce power
  3041. + consumption.
  3042. +
  3043. +config SURFACE_PERFMODE
  3044. + tristate "Surface Performance-Mode Driver"
  3045. + depends on SURFACE_AGGREGATOR_BUS
  3046. + depends on SYSFS
  3047. + default m
  3048. + help
  3049. + Driver for the performance-/cooling-mode interface of Microsoft
  3050. + Surface devices.
  3051. +
  3052. + Microsoft Surface devices using the Surface System Aggregator Module
  3053. + (SSAM) can be switched between different performance modes. This,
  3054. + depending on the device, can influence their cooling behavior and may
  3055. + influence power limits, allowing users to choose between performance
  3056. + and higher power-draw, or lower power-draw and more silent operation.
  3057. +
  3058. + This driver provides a user-space interface (via sysfs) for
  3059. + controlling said mode via the corresponding client device.
  3060. diff --git a/drivers/misc/surface_aggregator/clients/Makefile b/drivers/misc/surface_aggregator/clients/Makefile
  3061. new file mode 100644
  3062. index 000000000000..7320922ba755
  3063. --- /dev/null
  3064. +++ b/drivers/misc/surface_aggregator/clients/Makefile
  3065. @@ -0,0 +1,11 @@
  3066. +# SPDX-License-Identifier: GPL-2.0+
  3067. +# Copyright (C) 2019-2020 Maximilian Luz <luzmaximilian@gmail.com>
  3068. +
  3069. +obj-$(CONFIG_SURFACE_AGGREGATOR_CDEV) += surface_aggregator_cdev.o
  3070. +obj-$(CONFIG_SURFACE_AGGREGATOR_REGISTRY) += surface_aggregator_registry.o
  3071. +obj-$(CONFIG_SURFACE_ACPI_NOTIFY) += surface_acpi_notify.o
  3072. +obj-$(CONFIG_SURFACE_BATTERY) += surface_battery.o
  3073. +obj-$(CONFIG_SURFACE_DTX) += surface_dtx.o
  3074. +obj-$(CONFIG_SURFACE_HID) += surface_hid.o
  3075. +obj-$(CONFIG_SURFACE_HOTPLUG) += surface_hotplug.o
  3076. +obj-$(CONFIG_SURFACE_PERFMODE) += surface_perfmode.o
  3077. diff --git a/drivers/misc/surface_aggregator/clients/surface_acpi_notify.c b/drivers/misc/surface_aggregator/clients/surface_acpi_notify.c
  3078. new file mode 100644
  3079. index 000000000000..7a5b8f280036
  3080. --- /dev/null
  3081. +++ b/drivers/misc/surface_aggregator/clients/surface_acpi_notify.c
  3082. @@ -0,0 +1,884 @@
  3083. +// SPDX-License-Identifier: GPL-2.0+
  3084. +/*
  3085. + * Driver for the Surface ACPI Notify (SAN) interface/shim.
  3086. + *
  3087. + * Translates communication from ACPI to Surface System Aggregator Module
  3088. + * (SSAM/SAM) requests and back, specifically SAM-over-SSH. Translates SSAM
  3089. + * events back to ACPI notifications. Allows handling of discrete GPU
  3090. + * notifications sent from ACPI via the SAN interface by providing them to any
  3091. + * registered external driver.
  3092. + *
  3093. + * Copyright (C) 2019-2020 Maximilian Luz <luzmaximilian@gmail.com>
  3094. + */
  3095. +
  3096. +#include <asm/unaligned.h>
  3097. +#include <linux/acpi.h>
  3098. +#include <linux/delay.h>
  3099. +#include <linux/jiffies.h>
  3100. +#include <linux/kernel.h>
  3101. +#include <linux/module.h>
  3102. +#include <linux/notifier.h>
  3103. +#include <linux/platform_device.h>
  3104. +#include <linux/rwsem.h>
  3105. +
  3106. +#include <linux/surface_aggregator/controller.h>
  3107. +#include <linux/surface_acpi_notify.h>
  3108. +
  3109. +
  3110. +struct san_data {
  3111. + struct device *dev;
  3112. + struct ssam_controller *ctrl;
  3113. +
  3114. + struct acpi_connection_info info;
  3115. +
  3116. + struct ssam_event_notifier nf_bat;
  3117. + struct ssam_event_notifier nf_tmp;
  3118. +};
  3119. +
  3120. +#define to_san_data(ptr, member) \
  3121. + container_of(ptr, struct san_data, member)
  3122. +
  3123. +
  3124. +/* -- dGPU notifier interface. ---------------------------------------------- */
  3125. +
  3126. +struct san_rqsg_if {
  3127. + struct rw_semaphore lock;
  3128. + struct device *dev;
  3129. + struct blocking_notifier_head nh;
  3130. +};
  3131. +
  3132. +static struct san_rqsg_if san_rqsg_if = {
  3133. + .lock = __RWSEM_INITIALIZER(san_rqsg_if.lock),
  3134. + .dev = NULL,
  3135. + .nh = BLOCKING_NOTIFIER_INIT(san_rqsg_if.nh),
  3136. +};
  3137. +
  3138. +static int san_set_rqsg_interface_device(struct device *dev)
  3139. +{
  3140. + int status = 0;
  3141. +
  3142. + down_write(&san_rqsg_if.lock);
  3143. + if (!san_rqsg_if.dev && dev)
  3144. + san_rqsg_if.dev = dev;
  3145. + else
  3146. + status = -EBUSY;
  3147. + up_write(&san_rqsg_if.lock);
  3148. +
  3149. + return status;
  3150. +}
  3151. +
  3152. +/**
  3153. + * san_client_link() - Link client as consumer to SAN device.
  3154. + * @client: The client to link.
  3155. + *
  3156. + * Sets up a device link between the provided client device as consumer and
  3157. + * the SAN device as provider. This function can be used to ensure that the
  3158. + * SAN interface has been set up and will be set up for as long as the driver
  3159. + * of the client device is bound. This guarantees that, during that time, all
  3160. + * dGPU events will be received by any registered notifier.
  3161. + *
  3162. + * The link will be automatically removed once the client device's driver is
  3163. + * unbound.
  3164. + *
  3165. + * Return: Returns zero on succes, %-ENXIO if the SAN interface has not been
  3166. + * set up yet, and %-ENOMEM if device link creation failed.
  3167. + */
  3168. +int san_client_link(struct device *client)
  3169. +{
  3170. + const u32 flags = DL_FLAG_PM_RUNTIME | DL_FLAG_AUTOREMOVE_CONSUMER;
  3171. + struct device_link *link;
  3172. +
  3173. + down_read(&san_rqsg_if.lock);
  3174. +
  3175. + if (!san_rqsg_if.dev) {
  3176. + up_read(&san_rqsg_if.lock);
  3177. + return -ENXIO;
  3178. + }
  3179. +
  3180. + link = device_link_add(client, san_rqsg_if.dev, flags);
  3181. + if (!link) {
  3182. + up_read(&san_rqsg_if.lock);
  3183. + return -ENOMEM;
  3184. + }
  3185. +
  3186. + if (READ_ONCE(link->status) == DL_STATE_SUPPLIER_UNBIND) {
  3187. + up_read(&san_rqsg_if.lock);
  3188. + return -ENXIO;
  3189. + }
  3190. +
  3191. + up_read(&san_rqsg_if.lock);
  3192. + return 0;
  3193. +}
  3194. +EXPORT_SYMBOL_GPL(san_client_link);
  3195. +
  3196. +/**
  3197. + * san_dgpu_notifier_register() - Register a SAN dGPU notifier.
  3198. + * @nb: The notifier-block to register.
  3199. + *
  3200. + * Registers a SAN dGPU notifier, receiving any new SAN dGPU events sent from
  3201. + * ACPI. The registered notifier will be called with &struct san_dgpu_event
  3202. + * as notifier data and the command ID of that event as notifier action.
  3203. + */
  3204. +int san_dgpu_notifier_register(struct notifier_block *nb)
  3205. +{
  3206. + return blocking_notifier_chain_register(&san_rqsg_if.nh, nb);
  3207. +}
  3208. +EXPORT_SYMBOL_GPL(san_dgpu_notifier_register);
  3209. +
  3210. +/**
  3211. + * san_dgpu_notifier_unregister() - Unregister a SAN dGPU notifier.
  3212. + * @nb: The notifier-block to unregister.
  3213. + */
  3214. +int san_dgpu_notifier_unregister(struct notifier_block *nb)
  3215. +{
  3216. + return blocking_notifier_chain_unregister(&san_rqsg_if.nh, nb);
  3217. +}
  3218. +EXPORT_SYMBOL_GPL(san_dgpu_notifier_unregister);
  3219. +
  3220. +static int san_dgpu_notifier_call(struct san_dgpu_event *evt)
  3221. +{
  3222. + int ret;
  3223. +
  3224. + ret = blocking_notifier_call_chain(&san_rqsg_if.nh, evt->command, evt);
  3225. + return notifier_to_errno(ret);
  3226. +}
  3227. +
  3228. +
  3229. +/* -- ACPI _DSM event relay. ------------------------------------------------ */
  3230. +
  3231. +#define SAN_DSM_REVISION 0
  3232. +
  3233. +static const guid_t SAN_DSM_UUID =
  3234. + GUID_INIT(0x93b666c5, 0x70c6, 0x469f, 0xa2, 0x15, 0x3d,
  3235. + 0x48, 0x7c, 0x91, 0xab, 0x3c);
  3236. +
  3237. +enum san_dsm_event_fn {
  3238. + SAN_DSM_EVENT_FN_BAT1_STAT = 0x03,
  3239. + SAN_DSM_EVENT_FN_BAT1_INFO = 0x04,
  3240. + SAN_DSM_EVENT_FN_ADP1_STAT = 0x05,
  3241. + SAN_DSM_EVENT_FN_ADP1_INFO = 0x06,
  3242. + SAN_DSM_EVENT_FN_BAT2_STAT = 0x07,
  3243. + SAN_DSM_EVENT_FN_BAT2_INFO = 0x08,
  3244. + SAN_DSM_EVENT_FN_THERMAL = 0x09,
  3245. + SAN_DSM_EVENT_FN_DPTF = 0x0a,
  3246. +};
  3247. +
  3248. +enum sam_event_cid_bat {
  3249. + SAM_EVENT_CID_BAT_BIX = 0x15,
  3250. + SAM_EVENT_CID_BAT_BST = 0x16,
  3251. + SAM_EVENT_CID_BAT_ADP = 0x17,
  3252. + SAM_EVENT_CID_BAT_PROT = 0x18,
  3253. + SAM_EVENT_CID_BAT_DPTF = 0x4f,
  3254. +};
  3255. +
  3256. +enum sam_event_cid_tmp {
  3257. + SAM_EVENT_CID_TMP_TRIP = 0x0b,
  3258. +};
  3259. +
  3260. +struct san_event_work {
  3261. + struct delayed_work work;
  3262. + struct device *dev;
  3263. + struct ssam_event event; // must be last
  3264. +};
  3265. +
  3266. +static int san_acpi_notify_event(struct device *dev, u64 func,
  3267. + union acpi_object *param)
  3268. +{
  3269. + acpi_handle san = ACPI_HANDLE(dev);
  3270. + union acpi_object *obj;
  3271. + int status = 0;
  3272. +
  3273. + if (!acpi_check_dsm(san, &SAN_DSM_UUID, SAN_DSM_REVISION, 1 << func))
  3274. + return 0;
  3275. +
  3276. + dev_dbg(dev, "notify event 0x%02llx\n", func);
  3277. +
  3278. + obj = acpi_evaluate_dsm_typed(san, &SAN_DSM_UUID, SAN_DSM_REVISION,
  3279. + func, param, ACPI_TYPE_BUFFER);
  3280. + if (!obj)
  3281. + return -EFAULT;
  3282. +
  3283. + if (obj->buffer.length != 1 || obj->buffer.pointer[0] != 0) {
  3284. + dev_err(dev, "got unexpected result from _DSM\n");
  3285. + status = -EPROTO;
  3286. + }
  3287. +
  3288. + ACPI_FREE(obj);
  3289. + return status;
  3290. +}
  3291. +
  3292. +static int san_evt_bat_adp(struct device *dev, const struct ssam_event *event)
  3293. +{
  3294. + int status;
  3295. +
  3296. + status = san_acpi_notify_event(dev, SAN_DSM_EVENT_FN_ADP1_STAT, NULL);
  3297. + if (status)
  3298. + return status;
  3299. +
  3300. + /*
  3301. + * Enusre that the battery states get updated correctly.
  3302. + * When the battery is fully charged and an adapter is plugged in, it
  3303. + * sometimes is not updated correctly, instead showing it as charging.
  3304. + * Explicitly trigger battery updates to fix this.
  3305. + */
  3306. +
  3307. + status = san_acpi_notify_event(dev, SAN_DSM_EVENT_FN_BAT1_STAT, NULL);
  3308. + if (status)
  3309. + return status;
  3310. +
  3311. + return san_acpi_notify_event(dev, SAN_DSM_EVENT_FN_BAT2_STAT, NULL);
  3312. +}
  3313. +
  3314. +static int san_evt_bat_bix(struct device *dev, const struct ssam_event *event)
  3315. +{
  3316. + enum san_dsm_event_fn fn;
  3317. +
  3318. + if (event->instance_id == 0x02)
  3319. + fn = SAN_DSM_EVENT_FN_BAT2_INFO;
  3320. + else
  3321. + fn = SAN_DSM_EVENT_FN_BAT1_INFO;
  3322. +
  3323. + return san_acpi_notify_event(dev, fn, NULL);
  3324. +}
  3325. +
  3326. +static int san_evt_bat_bst(struct device *dev, const struct ssam_event *event)
  3327. +{
  3328. + enum san_dsm_event_fn fn;
  3329. +
  3330. + if (event->instance_id == 0x02)
  3331. + fn = SAN_DSM_EVENT_FN_BAT2_STAT;
  3332. + else
  3333. + fn = SAN_DSM_EVENT_FN_BAT1_STAT;
  3334. +
  3335. + return san_acpi_notify_event(dev, fn, NULL);
  3336. +}
  3337. +
  3338. +static int san_evt_bat_dptf(struct device *dev, const struct ssam_event *event)
  3339. +{
  3340. + union acpi_object payload;
  3341. +
  3342. + /*
  3343. + * The Surface ACPI expects a buffer and not a package. It specifically
  3344. + * checks for ObjectType (Arg3) == 0x03. This will cause a warning in
  3345. + * acpica/nsarguments.c, but that warning can be safely ignored.
  3346. + */
  3347. + payload.type = ACPI_TYPE_BUFFER;
  3348. + payload.buffer.length = event->length;
  3349. + payload.buffer.pointer = (u8 *)&event->data[0];
  3350. +
  3351. + return san_acpi_notify_event(dev, SAN_DSM_EVENT_FN_DPTF, &payload);
  3352. +}
  3353. +
  3354. +static unsigned long san_evt_bat_delay(u8 cid)
  3355. +{
  3356. + switch (cid) {
  3357. + case SAM_EVENT_CID_BAT_ADP:
  3358. + /*
  3359. + * Wait for battery state to update before signalling adapter
  3360. + * change.
  3361. + */
  3362. + return msecs_to_jiffies(5000);
  3363. +
  3364. + case SAM_EVENT_CID_BAT_BST:
  3365. + /* Ensure we do not miss anything important due to caching. */
  3366. + return msecs_to_jiffies(2000);
  3367. +
  3368. + default:
  3369. + return 0;
  3370. + }
  3371. +}
  3372. +
  3373. +static bool san_evt_bat(const struct ssam_event *event, struct device *dev)
  3374. +{
  3375. + int status;
  3376. +
  3377. + switch (event->command_id) {
  3378. + case SAM_EVENT_CID_BAT_BIX:
  3379. + status = san_evt_bat_bix(dev, event);
  3380. + break;
  3381. +
  3382. + case SAM_EVENT_CID_BAT_BST:
  3383. + status = san_evt_bat_bst(dev, event);
  3384. + break;
  3385. +
  3386. + case SAM_EVENT_CID_BAT_ADP:
  3387. + status = san_evt_bat_adp(dev, event);
  3388. + break;
  3389. +
  3390. + case SAM_EVENT_CID_BAT_PROT:
  3391. + /*
  3392. + * TODO: Implement support for battery protection status change
  3393. + * event.
  3394. + */
  3395. + return true;
  3396. +
  3397. + case SAM_EVENT_CID_BAT_DPTF:
  3398. + status = san_evt_bat_dptf(dev, event);
  3399. + break;
  3400. +
  3401. + default:
  3402. + return false;
  3403. + }
  3404. +
  3405. + if (status)
  3406. + dev_err(dev, "error handling power event (cid = %x)\n",
  3407. + event->command_id);
  3408. +
  3409. + return true;
  3410. +}
  3411. +
  3412. +static void san_evt_bat_workfn(struct work_struct *work)
  3413. +{
  3414. + struct san_event_work *ev;
  3415. +
  3416. + ev = container_of(work, struct san_event_work, work.work);
  3417. + san_evt_bat(&ev->event, ev->dev);
  3418. + kfree(ev);
  3419. +}
  3420. +
  3421. +static u32 san_evt_bat_nf(struct ssam_event_notifier *nf,
  3422. + const struct ssam_event *event)
  3423. +{
  3424. + struct san_data *d = to_san_data(nf, nf_bat);
  3425. + struct san_event_work *work;
  3426. + unsigned long delay = san_evt_bat_delay(event->command_id);
  3427. +
  3428. + if (delay == 0)
  3429. + return san_evt_bat(event, d->dev) ? SSAM_NOTIF_HANDLED : 0;
  3430. +
  3431. + work = kzalloc(sizeof(*work) + event->length, GFP_KERNEL);
  3432. + if (!work)
  3433. + return ssam_notifier_from_errno(-ENOMEM);
  3434. +
  3435. + INIT_DELAYED_WORK(&work->work, san_evt_bat_workfn);
  3436. + work->dev = d->dev;
  3437. +
  3438. + memcpy(&work->event, event, sizeof(struct ssam_event) + event->length);
  3439. +
  3440. + schedule_delayed_work(&work->work, delay);
  3441. + return SSAM_NOTIF_HANDLED;
  3442. +}
  3443. +
  3444. +static int san_evt_tmp_trip(struct device *dev, const struct ssam_event *event)
  3445. +{
  3446. + union acpi_object param;
  3447. +
  3448. + /*
  3449. + * The Surface ACPI expects an integer and not a package. This will
  3450. + * cause a warning in acpica/nsarguments.c, but that warning can be
  3451. + * safely ignored.
  3452. + */
  3453. + param.type = ACPI_TYPE_INTEGER;
  3454. + param.integer.value = event->instance_id;
  3455. +
  3456. + return san_acpi_notify_event(dev, SAN_DSM_EVENT_FN_THERMAL, &param);
  3457. +}
  3458. +
  3459. +static bool san_evt_tmp(const struct ssam_event *event, struct device *dev)
  3460. +{
  3461. + int status;
  3462. +
  3463. + switch (event->command_id) {
  3464. + case SAM_EVENT_CID_TMP_TRIP:
  3465. + status = san_evt_tmp_trip(dev, event);
  3466. + break;
  3467. +
  3468. + default:
  3469. + return false;
  3470. + }
  3471. +
  3472. + if (status) {
  3473. + dev_err(dev, "error handling thermal event (cid = %x)\n",
  3474. + event->command_id);
  3475. + }
  3476. +
  3477. + return true;
  3478. +}
  3479. +
  3480. +static u32 san_evt_tmp_nf(struct ssam_event_notifier *nf,
  3481. + const struct ssam_event *event)
  3482. +{
  3483. + struct san_data *d = to_san_data(nf, nf_tmp);
  3484. +
  3485. + return san_evt_tmp(event, d->dev) ? SSAM_NOTIF_HANDLED : 0;
  3486. +}
  3487. +
  3488. +
  3489. +/* -- ACPI GSB OperationRegion handler -------------------------------------- */
  3490. +
  3491. +struct gsb_data_in {
  3492. + u8 cv;
  3493. +} __packed;
  3494. +
  3495. +struct gsb_data_rqsx {
  3496. + u8 cv; // command value (san_gsb_request_cv)
  3497. + u8 tc; // target category
  3498. + u8 tid; // target ID
  3499. + u8 iid; // instance ID
  3500. + u8 snc; // expect-response-flag?
  3501. + u8 cid; // command ID
  3502. + u16 cdl; // payload length
  3503. + u8 pld[]; // payload
  3504. +} __packed;
  3505. +
  3506. +struct gsb_data_etwl {
  3507. + u8 cv; // command value (should be 0x02)
  3508. + u8 etw3; // unknown
  3509. + u8 etw4; // unknown
  3510. + u8 msg[]; // error message (ASCIIZ)
  3511. +} __packed;
  3512. +
  3513. +struct gsb_data_out {
  3514. + u8 status; // _SSH communication status
  3515. + u8 len; // _SSH payload length
  3516. + u8 pld[]; // _SSH payload
  3517. +} __packed;
  3518. +
  3519. +union gsb_buffer_data {
  3520. + struct gsb_data_in in; // common input
  3521. + struct gsb_data_rqsx rqsx; // RQSX input
  3522. + struct gsb_data_etwl etwl; // ETWL input
  3523. + struct gsb_data_out out; // output
  3524. +};
  3525. +
  3526. +struct gsb_buffer {
  3527. + u8 status; // GSB AttribRawProcess status
  3528. + u8 len; // GSB AttribRawProcess length
  3529. + union gsb_buffer_data data;
  3530. +} __packed;
  3531. +
  3532. +#define SAN_GSB_MAX_RQSX_PAYLOAD (U8_MAX - 2 - sizeof(struct gsb_data_rqsx))
  3533. +#define SAN_GSB_MAX_RESPONSE (U8_MAX - 2 - sizeof(struct gsb_data_out))
  3534. +
  3535. +#define SAN_GSB_COMMAND 0
  3536. +
  3537. +enum san_gsb_request_cv {
  3538. + SAN_GSB_REQUEST_CV_RQST = 0x01,
  3539. + SAN_GSB_REQUEST_CV_ETWL = 0x02,
  3540. + SAN_GSB_REQUEST_CV_RQSG = 0x03,
  3541. +};
  3542. +
  3543. +#define SAN_REQUEST_NUM_TRIES 5
  3544. +
  3545. +static acpi_status san_etwl(struct san_data *d, struct gsb_buffer *b)
  3546. +{
  3547. + struct gsb_data_etwl *etwl = &b->data.etwl;
  3548. +
  3549. + if (b->len < sizeof(struct gsb_data_etwl)) {
  3550. + dev_err(d->dev, "invalid ETWL package (len = %d)\n", b->len);
  3551. + return AE_OK;
  3552. + }
  3553. +
  3554. + dev_err(d->dev, "ETWL(0x%02x, 0x%02x): %.*s\n", etwl->etw3, etwl->etw4,
  3555. + (unsigned int)(b->len - sizeof(struct gsb_data_etwl)),
  3556. + (char *)etwl->msg);
  3557. +
  3558. + // indicate success
  3559. + b->status = 0x00;
  3560. + b->len = 0x00;
  3561. +
  3562. + return AE_OK;
  3563. +}
  3564. +
  3565. +static struct gsb_data_rqsx *san_validate_rqsx(struct device *dev,
  3566. + const char *type, struct gsb_buffer *b)
  3567. +{
  3568. + struct gsb_data_rqsx *rqsx = &b->data.rqsx;
  3569. +
  3570. + if (b->len < sizeof(struct gsb_data_rqsx)) {
  3571. + dev_err(dev, "invalid %s package (len = %d)\n", type, b->len);
  3572. + return NULL;
  3573. + }
  3574. +
  3575. + if (get_unaligned(&rqsx->cdl) != b->len - sizeof(struct gsb_data_rqsx)) {
  3576. + dev_err(dev, "bogus %s package (len = %d, cdl = %d)\n",
  3577. + type, b->len, get_unaligned(&rqsx->cdl));
  3578. + return NULL;
  3579. + }
  3580. +
  3581. + if (get_unaligned(&rqsx->cdl) > SAN_GSB_MAX_RQSX_PAYLOAD) {
  3582. + dev_err(dev, "payload for %s package too large (cdl = %d)\n",
  3583. + type, get_unaligned(&rqsx->cdl));
  3584. + return NULL;
  3585. + }
  3586. +
  3587. + return rqsx;
  3588. +}
  3589. +
  3590. +static void gsb_rqsx_response_error(struct gsb_buffer *gsb, int status)
  3591. +{
  3592. + gsb->status = 0x00;
  3593. + gsb->len = 0x02;
  3594. + gsb->data.out.status = (u8)(-status);
  3595. + gsb->data.out.len = 0x00;
  3596. +}
  3597. +
  3598. +static void gsb_rqsx_response_success(struct gsb_buffer *gsb, u8 *ptr, size_t len)
  3599. +{
  3600. + gsb->status = 0x00;
  3601. + gsb->len = len + 2;
  3602. + gsb->data.out.status = 0x00;
  3603. + gsb->data.out.len = len;
  3604. +
  3605. + if (len)
  3606. + memcpy(&gsb->data.out.pld[0], ptr, len);
  3607. +}
  3608. +
  3609. +static acpi_status san_rqst_fixup_suspended(struct san_data *d,
  3610. + struct ssam_request *rqst,
  3611. + struct gsb_buffer *gsb)
  3612. +{
  3613. + if (rqst->target_category == SSAM_SSH_TC_BAS && rqst->command_id == 0x0D) {
  3614. + u8 base_state = 1;
  3615. +
  3616. + /* Base state quirk:
  3617. + * The base state may be queried from ACPI when the EC is still
  3618. + * suspended. In this case it will return '-EPERM'. This query
  3619. + * will only be triggered from the ACPI lid GPE interrupt, thus
  3620. + * we are either in laptop or studio mode (base status 0x01 or
  3621. + * 0x02). Furthermore, we will only get here if the device (and
  3622. + * EC) have been suspended.
  3623. + *
  3624. + * We now assume that the device is in laptop mode (0x01). This
  3625. + * has the drawback that it will wake the device when unfolding
  3626. + * it in studio mode, but it also allows us to avoid actively
  3627. + * waiting for the EC to wake up, which may incur a notable
  3628. + * delay.
  3629. + */
  3630. +
  3631. + dev_dbg(d->dev, "rqst: fixup: base-state quirk\n");
  3632. +
  3633. + gsb_rqsx_response_success(gsb, &base_state, sizeof(base_state));
  3634. + return AE_OK;
  3635. + }
  3636. +
  3637. + gsb_rqsx_response_error(gsb, -ENXIO);
  3638. + return AE_OK;
  3639. +}
  3640. +
  3641. +static acpi_status san_rqst(struct san_data *d, struct gsb_buffer *buffer)
  3642. +{
  3643. + u8 rspbuf[SAN_GSB_MAX_RESPONSE];
  3644. + struct gsb_data_rqsx *gsb_rqst;
  3645. + struct ssam_request rqst;
  3646. + struct ssam_response rsp;
  3647. + int status = 0;
  3648. +
  3649. + gsb_rqst = san_validate_rqsx(d->dev, "RQST", buffer);
  3650. + if (!gsb_rqst)
  3651. + return AE_OK;
  3652. +
  3653. + rqst.target_category = gsb_rqst->tc;
  3654. + rqst.target_id = gsb_rqst->tid;
  3655. + rqst.command_id = gsb_rqst->cid;
  3656. + rqst.instance_id = gsb_rqst->iid;
  3657. + rqst.flags = gsb_rqst->snc ? SSAM_REQUEST_HAS_RESPONSE : 0;
  3658. + rqst.length = get_unaligned(&gsb_rqst->cdl);
  3659. + rqst.payload = &gsb_rqst->pld[0];
  3660. +
  3661. + rsp.capacity = ARRAY_SIZE(rspbuf);
  3662. + rsp.length = 0;
  3663. + rsp.pointer = &rspbuf[0];
  3664. +
  3665. + // handle suspended device
  3666. + if (d->dev->power.is_suspended) {
  3667. + dev_warn(d->dev, "rqst: device is suspended, not executing\n");
  3668. + return san_rqst_fixup_suspended(d, &rqst, buffer);
  3669. + }
  3670. +
  3671. + status = __ssam_retry(ssam_request_sync_onstack, SAN_REQUEST_NUM_TRIES,
  3672. + d->ctrl, &rqst, &rsp, SAN_GSB_MAX_RQSX_PAYLOAD);
  3673. +
  3674. + if (!status) {
  3675. + gsb_rqsx_response_success(buffer, rsp.pointer, rsp.length);
  3676. + } else {
  3677. + dev_err(d->dev, "rqst: failed with error %d\n", status);
  3678. + gsb_rqsx_response_error(buffer, status);
  3679. + }
  3680. +
  3681. + return AE_OK;
  3682. +}
  3683. +
  3684. +static acpi_status san_rqsg(struct san_data *d, struct gsb_buffer *buffer)
  3685. +{
  3686. + struct gsb_data_rqsx *gsb_rqsg;
  3687. + struct san_dgpu_event evt;
  3688. + int status;
  3689. +
  3690. + gsb_rqsg = san_validate_rqsx(d->dev, "RQSG", buffer);
  3691. + if (!gsb_rqsg)
  3692. + return AE_OK;
  3693. +
  3694. + evt.category = gsb_rqsg->tc;
  3695. + evt.target = gsb_rqsg->tid;
  3696. + evt.command = gsb_rqsg->cid;
  3697. + evt.instance = gsb_rqsg->iid;
  3698. + evt.length = get_unaligned(&gsb_rqsg->cdl);
  3699. + evt.payload = &gsb_rqsg->pld[0];
  3700. +
  3701. + status = san_dgpu_notifier_call(&evt);
  3702. + if (!status) {
  3703. + gsb_rqsx_response_success(buffer, NULL, 0);
  3704. + } else {
  3705. + dev_err(d->dev, "rqsg: failed with error %d\n", status);
  3706. + gsb_rqsx_response_error(buffer, status);
  3707. + }
  3708. +
  3709. + return AE_OK;
  3710. +}
  3711. +
  3712. +static acpi_status san_opreg_handler(u32 function,
  3713. + acpi_physical_address command, u32 bits, u64 *value64,
  3714. + void *opreg_context, void *region_context)
  3715. +{
  3716. + struct san_data *d = to_san_data(opreg_context, info);
  3717. + struct gsb_buffer *buffer = (struct gsb_buffer *)value64;
  3718. + int accessor_type = (function & 0xFFFF0000) >> 16;
  3719. +
  3720. + if (command != SAN_GSB_COMMAND) {
  3721. + dev_warn(d->dev, "unsupported command: 0x%02llx\n", command);
  3722. + return AE_OK;
  3723. + }
  3724. +
  3725. + if (accessor_type != ACPI_GSB_ACCESS_ATTRIB_RAW_PROCESS) {
  3726. + dev_err(d->dev, "invalid access type: 0x%02x\n", accessor_type);
  3727. + return AE_OK;
  3728. + }
  3729. +
  3730. + // buffer must have at least contain the command-value
  3731. + if (buffer->len == 0) {
  3732. + dev_err(d->dev, "request-package too small\n");
  3733. + return AE_OK;
  3734. + }
  3735. +
  3736. + switch (buffer->data.in.cv) {
  3737. + case SAN_GSB_REQUEST_CV_RQST:
  3738. + return san_rqst(d, buffer);
  3739. +
  3740. + case SAN_GSB_REQUEST_CV_ETWL:
  3741. + return san_etwl(d, buffer);
  3742. +
  3743. + case SAN_GSB_REQUEST_CV_RQSG:
  3744. + return san_rqsg(d, buffer);
  3745. +
  3746. + default:
  3747. + dev_warn(d->dev, "unsupported SAN0 request (cv: 0x%02x)\n",
  3748. + buffer->data.in.cv);
  3749. + return AE_OK;
  3750. + }
  3751. +}
  3752. +
  3753. +
  3754. +/* -- Driver setup. --------------------------------------------------------- */
  3755. +
  3756. +static int san_events_register(struct platform_device *pdev)
  3757. +{
  3758. + struct san_data *d = platform_get_drvdata(pdev);
  3759. + int status;
  3760. +
  3761. + d->nf_bat.base.priority = 1;
  3762. + d->nf_bat.base.fn = san_evt_bat_nf;
  3763. + d->nf_bat.event.reg = SSAM_EVENT_REGISTRY_SAM;
  3764. + d->nf_bat.event.id.target_category = SSAM_SSH_TC_BAT;
  3765. + d->nf_bat.event.id.instance = 0;
  3766. + d->nf_bat.event.mask = SSAM_EVENT_MASK_TARGET;
  3767. + d->nf_bat.event.flags = SSAM_EVENT_SEQUENCED;
  3768. +
  3769. + d->nf_tmp.base.priority = 1;
  3770. + d->nf_tmp.base.fn = san_evt_tmp_nf;
  3771. + d->nf_tmp.event.reg = SSAM_EVENT_REGISTRY_SAM;
  3772. + d->nf_tmp.event.id.target_category = SSAM_SSH_TC_TMP;
  3773. + d->nf_tmp.event.id.instance = 0;
  3774. + d->nf_tmp.event.mask = SSAM_EVENT_MASK_TARGET;
  3775. + d->nf_tmp.event.flags = SSAM_EVENT_SEQUENCED;
  3776. +
  3777. + status = ssam_notifier_register(d->ctrl, &d->nf_bat);
  3778. + if (status)
  3779. + return status;
  3780. +
  3781. + status = ssam_notifier_register(d->ctrl, &d->nf_tmp);
  3782. + if (status)
  3783. + ssam_notifier_unregister(d->ctrl, &d->nf_bat);
  3784. +
  3785. + return status;
  3786. +}
  3787. +
  3788. +static void san_events_unregister(struct platform_device *pdev)
  3789. +{
  3790. + struct san_data *d = platform_get_drvdata(pdev);
  3791. +
  3792. + ssam_notifier_unregister(d->ctrl, &d->nf_bat);
  3793. + ssam_notifier_unregister(d->ctrl, &d->nf_tmp);
  3794. +}
  3795. +
  3796. +#define san_consumer_printk(level, dev, handle, fmt, ...) \
  3797. +do { \
  3798. + char *path = "<error getting consumer path>"; \
  3799. + struct acpi_buffer buffer = { \
  3800. + .length = ACPI_ALLOCATE_BUFFER, \
  3801. + .pointer = NULL, \
  3802. + }; \
  3803. + \
  3804. + if (ACPI_SUCCESS(acpi_get_name(handle, ACPI_FULL_PATHNAME, &buffer))) \
  3805. + path = buffer.pointer; \
  3806. + \
  3807. + dev_##level(dev, "[%s]: " fmt, path, ##__VA_ARGS__); \
  3808. + kfree(buffer.pointer); \
  3809. +} while (0)
  3810. +
  3811. +#define san_consumer_dbg(dev, handle, fmt, ...) \
  3812. + san_consumer_printk(dbg, dev, handle, fmt, ##__VA_ARGS__)
  3813. +
  3814. +#define san_consumer_warn(dev, handle, fmt, ...) \
  3815. + san_consumer_printk(warn, dev, handle, fmt, ##__VA_ARGS__)
  3816. +
  3817. +static bool is_san_consumer(struct platform_device *pdev, acpi_handle handle)
  3818. +{
  3819. + struct acpi_handle_list dep_devices;
  3820. + acpi_handle supplier = ACPI_HANDLE(&pdev->dev);
  3821. + acpi_status status;
  3822. + int i;
  3823. +
  3824. + if (!acpi_has_method(handle, "_DEP"))
  3825. + return false;
  3826. +
  3827. + status = acpi_evaluate_reference(handle, "_DEP", NULL, &dep_devices);
  3828. + if (ACPI_FAILURE(status)) {
  3829. + san_consumer_dbg(&pdev->dev, handle, "failed to evaluate _DEP\n");
  3830. + return false;
  3831. + }
  3832. +
  3833. + for (i = 0; i < dep_devices.count; i++) {
  3834. + if (dep_devices.handles[i] == supplier)
  3835. + return true;
  3836. + }
  3837. +
  3838. + return false;
  3839. +}
  3840. +
  3841. +static acpi_status san_consumer_setup(acpi_handle handle, u32 lvl,
  3842. + void *context, void **rv)
  3843. +{
  3844. + const u32 flags = DL_FLAG_PM_RUNTIME | DL_FLAG_AUTOREMOVE_SUPPLIER;
  3845. + struct platform_device *pdev = context;
  3846. + struct acpi_device *adev;
  3847. + struct device_link *link;
  3848. +
  3849. + if (!is_san_consumer(pdev, handle))
  3850. + return AE_OK;
  3851. +
  3852. + // ignore ACPI devices that are not present
  3853. + if (acpi_bus_get_device(handle, &adev) != 0)
  3854. + return AE_OK;
  3855. +
  3856. + san_consumer_dbg(&pdev->dev, handle, "creating device link\n");
  3857. +
  3858. + // try to set up device links, ignore but log errors
  3859. + link = device_link_add(&adev->dev, &pdev->dev, flags);
  3860. + if (!link) {
  3861. + san_consumer_warn(&pdev->dev, handle,
  3862. + "failed to create device link\n");
  3863. + return AE_OK;
  3864. + }
  3865. +
  3866. + return AE_OK;
  3867. +}
  3868. +
  3869. +static int san_consumer_links_setup(struct platform_device *pdev)
  3870. +{
  3871. + acpi_status status;
  3872. +
  3873. + status = acpi_walk_namespace(ACPI_TYPE_DEVICE, ACPI_ROOT_OBJECT,
  3874. + ACPI_UINT32_MAX, san_consumer_setup, NULL,
  3875. + pdev, NULL);
  3876. +
  3877. + return status ? -EFAULT : 0;
  3878. +}
  3879. +
  3880. +static int san_probe(struct platform_device *pdev)
  3881. +{
  3882. + acpi_handle san = ACPI_HANDLE(&pdev->dev);
  3883. + struct ssam_controller *ctrl;
  3884. + struct san_data *data;
  3885. + acpi_status astatus;
  3886. + int status;
  3887. +
  3888. + status = ssam_client_bind(&pdev->dev, &ctrl);
  3889. + if (status)
  3890. + return status == -ENXIO ? -EPROBE_DEFER : status;
  3891. +
  3892. + status = san_consumer_links_setup(pdev);
  3893. + if (status)
  3894. + return status;
  3895. +
  3896. + data = devm_kzalloc(&pdev->dev, sizeof(*data), GFP_KERNEL);
  3897. + if (!data)
  3898. + return -ENOMEM;
  3899. +
  3900. + data->dev = &pdev->dev;
  3901. + data->ctrl = ctrl;
  3902. +
  3903. + platform_set_drvdata(pdev, data);
  3904. +
  3905. + astatus = acpi_install_address_space_handler(san, ACPI_ADR_SPACE_GSBUS,
  3906. + &san_opreg_handler, NULL, &data->info);
  3907. + if (ACPI_FAILURE(astatus))
  3908. + return -ENXIO;
  3909. +
  3910. + status = san_events_register(pdev);
  3911. + if (status)
  3912. + goto err_enable_events;
  3913. +
  3914. + status = san_set_rqsg_interface_device(&pdev->dev);
  3915. + if (status)
  3916. + goto err_install_dev;
  3917. +
  3918. + acpi_walk_dep_device_list(san);
  3919. + return 0;
  3920. +
  3921. +err_install_dev:
  3922. + san_events_unregister(pdev);
  3923. +err_enable_events:
  3924. + acpi_remove_address_space_handler(san, ACPI_ADR_SPACE_GSBUS,
  3925. + &san_opreg_handler);
  3926. + return status;
  3927. +}
  3928. +
  3929. +static int san_remove(struct platform_device *pdev)
  3930. +{
  3931. + acpi_handle san = ACPI_HANDLE(&pdev->dev);
  3932. +
  3933. + san_set_rqsg_interface_device(NULL);
  3934. + acpi_remove_address_space_handler(san, ACPI_ADR_SPACE_GSBUS,
  3935. + &san_opreg_handler);
  3936. + san_events_unregister(pdev);
  3937. +
  3938. + /*
  3939. + * We have unregistered our event sources. Now we need to ensure that
  3940. + * all delayed works they may have spawned are run to completion.
  3941. + */
  3942. + flush_scheduled_work();
  3943. +
  3944. + return 0;
  3945. +}
  3946. +
  3947. +static const struct acpi_device_id san_match[] = {
  3948. + { "MSHW0091" },
  3949. + { },
  3950. +};
  3951. +MODULE_DEVICE_TABLE(acpi, san_match);
  3952. +
  3953. +static struct platform_driver surface_acpi_notify = {
  3954. + .probe = san_probe,
  3955. + .remove = san_remove,
  3956. + .driver = {
  3957. + .name = "surface_acpi_notify",
  3958. + .acpi_match_table = san_match,
  3959. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  3960. + },
  3961. +};
  3962. +module_platform_driver(surface_acpi_notify);
  3963. +
  3964. +MODULE_AUTHOR("Maximilian Luz <luzmaximilian@gmail.com>");
  3965. +MODULE_DESCRIPTION("Surface ACPI Notify driver for Surface System Aggregator Module");
  3966. +MODULE_LICENSE("GPL");
  3967. diff --git a/drivers/misc/surface_aggregator/clients/surface_aggregator_cdev.c b/drivers/misc/surface_aggregator/clients/surface_aggregator_cdev.c
  3968. new file mode 100644
  3969. index 000000000000..f5e81cd67357
  3970. --- /dev/null
  3971. +++ b/drivers/misc/surface_aggregator/clients/surface_aggregator_cdev.c
  3972. @@ -0,0 +1,299 @@
  3973. +// SPDX-License-Identifier: GPL-2.0+
  3974. +/*
  3975. + * Provides user-space access to the SSAM EC via the /dev/surface/aggregator
  3976. + * misc device. Intended for debugging and development.
  3977. + *
  3978. + * Copyright (C) 2020 Maximilian Luz <luzmaximilian@gmail.com>
  3979. + */
  3980. +
  3981. +#include <linux/fs.h>
  3982. +#include <linux/kernel.h>
  3983. +#include <linux/kref.h>
  3984. +#include <linux/miscdevice.h>
  3985. +#include <linux/module.h>
  3986. +#include <linux/platform_device.h>
  3987. +#include <linux/rwsem.h>
  3988. +#include <linux/slab.h>
  3989. +#include <linux/uaccess.h>
  3990. +
  3991. +#include <linux/surface_aggregator/cdev.h>
  3992. +#include <linux/surface_aggregator/controller.h>
  3993. +
  3994. +#define SSAM_CDEV_DEVICE_NAME "surface_aggregator_cdev"
  3995. +
  3996. +struct ssam_cdev {
  3997. + struct kref kref;
  3998. + struct rw_semaphore lock;
  3999. + struct ssam_controller *ctrl;
  4000. + struct miscdevice mdev;
  4001. +};
  4002. +
  4003. +static void __ssam_cdev_release(struct kref *kref)
  4004. +{
  4005. + kfree(container_of(kref, struct ssam_cdev, kref));
  4006. +}
  4007. +
  4008. +static struct ssam_cdev *ssam_cdev_get(struct ssam_cdev *cdev)
  4009. +{
  4010. + if (cdev)
  4011. + kref_get(&cdev->kref);
  4012. +
  4013. + return cdev;
  4014. +}
  4015. +
  4016. +static void ssam_cdev_put(struct ssam_cdev *cdev)
  4017. +{
  4018. + if (cdev)
  4019. + kref_put(&cdev->kref, __ssam_cdev_release);
  4020. +}
  4021. +
  4022. +static int ssam_cdev_device_open(struct inode *inode, struct file *filp)
  4023. +{
  4024. + struct miscdevice *mdev = filp->private_data;
  4025. + struct ssam_cdev *cdev = container_of(mdev, struct ssam_cdev, mdev);
  4026. +
  4027. + filp->private_data = ssam_cdev_get(cdev);
  4028. + return stream_open(inode, filp);
  4029. +}
  4030. +
  4031. +static int ssam_cdev_device_release(struct inode *inode, struct file *filp)
  4032. +{
  4033. + ssam_cdev_put(filp->private_data);
  4034. + return 0;
  4035. +}
  4036. +
  4037. +static long ssam_cdev_request(struct ssam_cdev *cdev, unsigned long arg)
  4038. +{
  4039. + struct ssam_cdev_request __user *r;
  4040. + struct ssam_cdev_request rqst;
  4041. + struct ssam_request spec;
  4042. + struct ssam_response rsp;
  4043. + const void __user *plddata;
  4044. + void __user *rspdata;
  4045. + int status = 0, ret = 0, tmp;
  4046. +
  4047. + r = (struct ssam_cdev_request __user *)arg;
  4048. + ret = copy_struct_from_user(&rqst, sizeof(rqst), r, sizeof(*r));
  4049. + if (ret)
  4050. + goto out;
  4051. +
  4052. + plddata = u64_to_user_ptr(rqst.payload.data);
  4053. + rspdata = u64_to_user_ptr(rqst.response.data);
  4054. +
  4055. + // setup basic request fields
  4056. + spec.target_category = rqst.target_category;
  4057. + spec.target_id = rqst.target_id;
  4058. + spec.command_id = rqst.command_id;
  4059. + spec.instance_id = rqst.instance_id;
  4060. + spec.flags = rqst.flags;
  4061. + spec.length = rqst.payload.length;
  4062. + spec.payload = NULL;
  4063. +
  4064. + rsp.capacity = rqst.response.length;
  4065. + rsp.length = 0;
  4066. + rsp.pointer = NULL;
  4067. +
  4068. + // get request payload from user-space
  4069. + if (spec.length) {
  4070. + if (!plddata) {
  4071. + ret = -EINVAL;
  4072. + goto out;
  4073. + }
  4074. +
  4075. + spec.payload = kzalloc(spec.length, GFP_KERNEL);
  4076. + if (!spec.payload) {
  4077. + status = -ENOMEM;
  4078. + ret = -EFAULT;
  4079. + goto out;
  4080. + }
  4081. +
  4082. + if (copy_from_user((void *)spec.payload, plddata, spec.length)) {
  4083. + ret = -EFAULT;
  4084. + goto out;
  4085. + }
  4086. + }
  4087. +
  4088. + // allocate response buffer
  4089. + if (rsp.capacity) {
  4090. + if (!rspdata) {
  4091. + ret = -EINVAL;
  4092. + goto out;
  4093. + }
  4094. +
  4095. + rsp.pointer = kzalloc(rsp.capacity, GFP_KERNEL);
  4096. + if (!rsp.pointer) {
  4097. + status = -ENOMEM;
  4098. + ret = -EFAULT;
  4099. + goto out;
  4100. + }
  4101. + }
  4102. +
  4103. + // perform request
  4104. + status = ssam_request_sync(cdev->ctrl, &spec, &rsp);
  4105. + if (status)
  4106. + goto out;
  4107. +
  4108. + // copy response to user-space
  4109. + if (rsp.length && copy_to_user(rspdata, rsp.pointer, rsp.length))
  4110. + ret = -EFAULT;
  4111. +
  4112. +out:
  4113. + // always try to set response-length and status
  4114. + tmp = put_user(rsp.length, &r->response.length);
  4115. + if (tmp)
  4116. + ret = tmp;
  4117. +
  4118. + tmp = put_user(status, &r->status);
  4119. + if (tmp)
  4120. + ret = tmp;
  4121. +
  4122. + // cleanup
  4123. + kfree(spec.payload);
  4124. + kfree(rsp.pointer);
  4125. +
  4126. + return ret;
  4127. +}
  4128. +
  4129. +static long __ssam_cdev_device_ioctl(struct ssam_cdev *cdev, unsigned int cmd,
  4130. + unsigned long arg)
  4131. +{
  4132. + switch (cmd) {
  4133. + case SSAM_CDEV_REQUEST:
  4134. + return ssam_cdev_request(cdev, arg);
  4135. +
  4136. + default:
  4137. + return -ENOTTY;
  4138. + }
  4139. +}
  4140. +
  4141. +static long ssam_cdev_device_ioctl(struct file *file, unsigned int cmd,
  4142. + unsigned long arg)
  4143. +{
  4144. + struct ssam_cdev *cdev = file->private_data;
  4145. + long status;
  4146. +
  4147. + // ensure that controller is valid for as long as we need it
  4148. + if (down_read_killable(&cdev->lock))
  4149. + return -ERESTARTSYS;
  4150. +
  4151. + if (!cdev->ctrl) {
  4152. + up_read(&cdev->lock);
  4153. + return -ENODEV;
  4154. + }
  4155. +
  4156. + status = __ssam_cdev_device_ioctl(cdev, cmd, arg);
  4157. +
  4158. + up_read(&cdev->lock);
  4159. + return status;
  4160. +}
  4161. +
  4162. +static const struct file_operations ssam_controller_fops = {
  4163. + .owner = THIS_MODULE,
  4164. + .open = ssam_cdev_device_open,
  4165. + .release = ssam_cdev_device_release,
  4166. + .unlocked_ioctl = ssam_cdev_device_ioctl,
  4167. + .compat_ioctl = ssam_cdev_device_ioctl,
  4168. + .llseek = noop_llseek,
  4169. +};
  4170. +
  4171. +static int ssam_dbg_device_probe(struct platform_device *pdev)
  4172. +{
  4173. + struct ssam_controller *ctrl;
  4174. + struct ssam_cdev *cdev;
  4175. + int status;
  4176. +
  4177. + status = ssam_client_bind(&pdev->dev, &ctrl);
  4178. + if (status)
  4179. + return status == -ENXIO ? -EPROBE_DEFER : status;
  4180. +
  4181. + cdev = kzalloc(sizeof(*cdev), GFP_KERNEL);
  4182. + if (!cdev)
  4183. + return -ENOMEM;
  4184. +
  4185. + kref_init(&cdev->kref);
  4186. + init_rwsem(&cdev->lock);
  4187. + cdev->ctrl = ctrl;
  4188. +
  4189. + cdev->mdev.parent = &pdev->dev;
  4190. + cdev->mdev.minor = MISC_DYNAMIC_MINOR;
  4191. + cdev->mdev.name = "surface_aggregator";
  4192. + cdev->mdev.nodename = "surface/aggregator";
  4193. + cdev->mdev.fops = &ssam_controller_fops;
  4194. +
  4195. + status = misc_register(&cdev->mdev);
  4196. + if (status) {
  4197. + kfree(cdev);
  4198. + return status;
  4199. + }
  4200. +
  4201. + platform_set_drvdata(pdev, cdev);
  4202. + return 0;
  4203. +}
  4204. +
  4205. +static int ssam_dbg_device_remove(struct platform_device *pdev)
  4206. +{
  4207. + struct ssam_cdev *cdev = platform_get_drvdata(pdev);
  4208. +
  4209. + misc_deregister(&cdev->mdev);
  4210. +
  4211. + /*
  4212. + * The controller is only guaranteed to be valid for as long as the
  4213. + * driver is bound. Remove controller so that any lingering open files
  4214. + * cannot access it any more after we're gone.
  4215. + */
  4216. + down_write(&cdev->lock);
  4217. + cdev->ctrl = NULL;
  4218. + up_write(&cdev->lock);
  4219. +
  4220. + ssam_cdev_put(cdev);
  4221. + return 0;
  4222. +}
  4223. +
  4224. +static struct platform_device *ssam_cdev_device;
  4225. +
  4226. +static struct platform_driver ssam_cdev_driver = {
  4227. + .probe = ssam_dbg_device_probe,
  4228. + .remove = ssam_dbg_device_remove,
  4229. + .driver = {
  4230. + .name = SSAM_CDEV_DEVICE_NAME,
  4231. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  4232. + },
  4233. +};
  4234. +
  4235. +static int __init ssam_debug_init(void)
  4236. +{
  4237. + int status;
  4238. +
  4239. + ssam_cdev_device = platform_device_alloc(SSAM_CDEV_DEVICE_NAME,
  4240. + PLATFORM_DEVID_NONE);
  4241. + if (!ssam_cdev_device)
  4242. + return -ENOMEM;
  4243. +
  4244. + status = platform_device_add(ssam_cdev_device);
  4245. + if (status)
  4246. + goto err_device;
  4247. +
  4248. + status = platform_driver_register(&ssam_cdev_driver);
  4249. + if (status)
  4250. + goto err_driver;
  4251. +
  4252. + return 0;
  4253. +
  4254. +err_driver:
  4255. + platform_device_del(ssam_cdev_device);
  4256. +err_device:
  4257. + platform_device_put(ssam_cdev_device);
  4258. + return status;
  4259. +}
  4260. +module_init(ssam_debug_init);
  4261. +
  4262. +static void __exit ssam_debug_exit(void)
  4263. +{
  4264. + platform_driver_unregister(&ssam_cdev_driver);
  4265. + platform_device_unregister(ssam_cdev_device);
  4266. +}
  4267. +module_exit(ssam_debug_exit);
  4268. +
  4269. +MODULE_AUTHOR("Maximilian Luz <luzmaximilian@gmail.com>");
  4270. +MODULE_DESCRIPTION("User-space interface for Surface System Aggregator Module");
  4271. +MODULE_LICENSE("GPL");
  4272. diff --git a/drivers/misc/surface_aggregator/clients/surface_aggregator_registry.c b/drivers/misc/surface_aggregator/clients/surface_aggregator_registry.c
  4273. new file mode 100644
  4274. index 000000000000..77ef266b88f3
  4275. --- /dev/null
  4276. +++ b/drivers/misc/surface_aggregator/clients/surface_aggregator_registry.c
  4277. @@ -0,0 +1,656 @@
  4278. +// SPDX-License-Identifier: GPL-2.0+
  4279. +/*
  4280. + * Surface System Aggregator Module (SSAM) client device registry.
  4281. + *
  4282. + * Registry for non-platform/non-ACPI SSAM client devices, i.e. devices that
  4283. + * cannot be auto-detected. Provides device-hubs for these devices.
  4284. + *
  4285. + * Copyright (C) 2020 Maximilian Luz <luzmaximilian@gmail.com>
  4286. + */
  4287. +
  4288. +#include <linux/acpi.h>
  4289. +#include <linux/kernel.h>
  4290. +#include <linux/module.h>
  4291. +#include <linux/mutex.h>
  4292. +#include <linux/notifier.h>
  4293. +#include <linux/platform_device.h>
  4294. +#include <linux/types.h>
  4295. +
  4296. +#include <linux/surface_aggregator/controller.h>
  4297. +#include <linux/surface_aggregator/device.h>
  4298. +
  4299. +
  4300. +/* -- Device registry. ------------------------------------------------------ */
  4301. +
  4302. +static const struct software_node ssam_node_root = {
  4303. + .name = "ssam_platform_hub",
  4304. +};
  4305. +
  4306. +static const struct software_node ssam_node_hub_main = {
  4307. + .name = "ssam:00:00:01:00:00",
  4308. + .parent = &ssam_node_root,
  4309. +};
  4310. +
  4311. +static const struct software_node ssam_node_hub_base = {
  4312. + .name = "ssam:00:00:02:00:00",
  4313. + .parent = &ssam_node_root,
  4314. +};
  4315. +
  4316. +static const struct software_node ssam_node_bat_ac = {
  4317. + .name = "ssam:01:02:01:01:01",
  4318. + .parent = &ssam_node_hub_main,
  4319. +};
  4320. +
  4321. +static const struct software_node ssam_node_bat_main = {
  4322. + .name = "ssam:01:02:01:01:00",
  4323. + .parent = &ssam_node_hub_main,
  4324. +};
  4325. +
  4326. +static const struct software_node ssam_node_bat_sb3base = {
  4327. + .name = "ssam:01:02:02:01:00",
  4328. + .parent = &ssam_node_hub_base,
  4329. +};
  4330. +
  4331. +static const struct software_node ssam_node_tmp_perf = {
  4332. + .name = "ssam:01:03:01:00:01",
  4333. + .parent = &ssam_node_hub_main,
  4334. +};
  4335. +
  4336. +static const struct software_node ssam_node_bas_dtx = {
  4337. + .name = "ssam:01:11:01:00:00",
  4338. + .parent = &ssam_node_hub_main,
  4339. +};
  4340. +
  4341. +static const struct software_node ssam_node_hid_main_keyboard = {
  4342. + .name = "ssam:01:15:02:01:00",
  4343. + .parent = &ssam_node_hub_main,
  4344. +};
  4345. +
  4346. +static const struct software_node ssam_node_hid_main_touchpad = {
  4347. + .name = "ssam:01:15:02:03:00",
  4348. + .parent = &ssam_node_hub_main,
  4349. +};
  4350. +
  4351. +static const struct software_node ssam_node_hid_main_iid5 = {
  4352. + .name = "ssam:01:15:02:05:00",
  4353. + .parent = &ssam_node_hub_main,
  4354. +};
  4355. +
  4356. +static const struct software_node ssam_node_hid_base_keyboard = {
  4357. + .name = "ssam:01:15:02:01:00",
  4358. + .parent = &ssam_node_hub_base,
  4359. +};
  4360. +
  4361. +static const struct software_node ssam_node_hid_base_touchpad = {
  4362. + .name = "ssam:01:15:02:03:00",
  4363. + .parent = &ssam_node_hub_base,
  4364. +};
  4365. +
  4366. +static const struct software_node ssam_node_hid_base_iid5 = {
  4367. + .name = "ssam:01:15:02:05:00",
  4368. + .parent = &ssam_node_hub_base,
  4369. +};
  4370. +
  4371. +static const struct software_node ssam_node_hid_base_iid6 = {
  4372. + .name = "ssam:01:15:02:06:00",
  4373. + .parent = &ssam_node_hub_base,
  4374. +};
  4375. +
  4376. +
  4377. +static const struct software_node *ssam_node_group_sb2[] = {
  4378. + &ssam_node_root,
  4379. + &ssam_node_hub_main,
  4380. + &ssam_node_tmp_perf,
  4381. + NULL,
  4382. +};
  4383. +
  4384. +static const struct software_node *ssam_node_group_sb3[] = {
  4385. + &ssam_node_root,
  4386. + &ssam_node_hub_main,
  4387. + &ssam_node_hub_base,
  4388. + &ssam_node_tmp_perf,
  4389. + &ssam_node_bat_ac,
  4390. + &ssam_node_bat_main,
  4391. + &ssam_node_bat_sb3base,
  4392. + &ssam_node_hid_base_keyboard,
  4393. + &ssam_node_hid_base_touchpad,
  4394. + &ssam_node_hid_base_iid5,
  4395. + &ssam_node_hid_base_iid6,
  4396. + &ssam_node_bas_dtx,
  4397. + NULL,
  4398. +};
  4399. +
  4400. +static const struct software_node *ssam_node_group_sl1[] = {
  4401. + &ssam_node_root,
  4402. + &ssam_node_hub_main,
  4403. + &ssam_node_tmp_perf,
  4404. + NULL,
  4405. +};
  4406. +
  4407. +static const struct software_node *ssam_node_group_sl2[] = {
  4408. + &ssam_node_root,
  4409. + &ssam_node_hub_main,
  4410. + &ssam_node_tmp_perf,
  4411. + NULL,
  4412. +};
  4413. +
  4414. +static const struct software_node *ssam_node_group_sl3[] = {
  4415. + &ssam_node_root,
  4416. + &ssam_node_hub_main,
  4417. + &ssam_node_tmp_perf,
  4418. + &ssam_node_bat_ac,
  4419. + &ssam_node_bat_main,
  4420. + &ssam_node_hid_main_keyboard,
  4421. + &ssam_node_hid_main_touchpad,
  4422. + &ssam_node_hid_main_iid5,
  4423. + NULL,
  4424. +};
  4425. +
  4426. +static const struct software_node *ssam_node_group_sp5[] = {
  4427. + &ssam_node_root,
  4428. + &ssam_node_hub_main,
  4429. + &ssam_node_tmp_perf,
  4430. + NULL,
  4431. +};
  4432. +
  4433. +static const struct software_node *ssam_node_group_sp6[] = {
  4434. + &ssam_node_root,
  4435. + &ssam_node_hub_main,
  4436. + &ssam_node_tmp_perf,
  4437. + NULL,
  4438. +};
  4439. +
  4440. +static const struct software_node *ssam_node_group_sp7[] = {
  4441. + &ssam_node_root,
  4442. + &ssam_node_hub_main,
  4443. + &ssam_node_tmp_perf,
  4444. + &ssam_node_bat_ac,
  4445. + &ssam_node_bat_main,
  4446. + NULL,
  4447. +};
  4448. +
  4449. +
  4450. +/* -- Device registry helper functions. ------------------------------------- */
  4451. +
  4452. +static int ssam_uid_from_string(const char *str, struct ssam_device_uid *uid)
  4453. +{
  4454. + u8 d, tc, tid, iid, fn;
  4455. + int n;
  4456. +
  4457. + n = sscanf(str, "ssam:%hhx:%hhx:%hhx:%hhx:%hhx", &d, &tc, &tid, &iid, &fn);
  4458. + if (n != 5)
  4459. + return -EINVAL;
  4460. +
  4461. + uid->domain = d;
  4462. + uid->category = tc;
  4463. + uid->target = tid;
  4464. + uid->instance = iid;
  4465. + uid->function = fn;
  4466. +
  4467. + return 0;
  4468. +}
  4469. +
  4470. +static int ssam_hub_remove_devices_fn(struct device *dev, void *data)
  4471. +{
  4472. + if (!is_ssam_device(dev))
  4473. + return 0;
  4474. +
  4475. + ssam_device_remove(to_ssam_device(dev));
  4476. + return 0;
  4477. +}
  4478. +
  4479. +static void ssam_hub_remove_devices(struct device *parent)
  4480. +{
  4481. + device_for_each_child_reverse(parent, NULL, ssam_hub_remove_devices_fn);
  4482. +}
  4483. +
  4484. +static int ssam_hub_add_device(struct device *parent,
  4485. + struct ssam_controller *ctrl,
  4486. + struct fwnode_handle *node)
  4487. +{
  4488. + struct ssam_device_uid uid;
  4489. + struct ssam_device *sdev;
  4490. + int status;
  4491. +
  4492. + status = ssam_uid_from_string(fwnode_get_name(node), &uid);
  4493. + if (status)
  4494. + return -ENODEV;
  4495. +
  4496. + sdev = ssam_device_alloc(ctrl, uid);
  4497. + if (!sdev)
  4498. + return -ENOMEM;
  4499. +
  4500. + sdev->dev.parent = parent;
  4501. + sdev->dev.fwnode = node;
  4502. +
  4503. + status = ssam_device_add(sdev);
  4504. + if (status)
  4505. + ssam_device_put(sdev);
  4506. +
  4507. + return status;
  4508. +}
  4509. +
  4510. +static int ssam_hub_add_devices(struct device *parent,
  4511. + struct ssam_controller *ctrl,
  4512. + struct fwnode_handle *node)
  4513. +{
  4514. + struct fwnode_handle *child;
  4515. + int status;
  4516. +
  4517. + fwnode_for_each_child_node(node, child) {
  4518. + status = ssam_hub_add_device(parent, ctrl, child);
  4519. + if (status && status != -ENODEV)
  4520. + goto err;
  4521. + }
  4522. +
  4523. + return 0;
  4524. +err:
  4525. + ssam_hub_remove_devices(parent);
  4526. + return status;
  4527. +}
  4528. +
  4529. +
  4530. +/* -- SSAM main-hub driver. ------------------------------------------------- */
  4531. +
  4532. +static int ssam_hub_probe(struct ssam_device *sdev)
  4533. +{
  4534. + struct fwnode_handle *node = dev_fwnode(&sdev->dev);
  4535. +
  4536. + if (!node)
  4537. + return -ENODEV;
  4538. +
  4539. + return ssam_hub_add_devices(&sdev->dev, sdev->ctrl, node);
  4540. +}
  4541. +
  4542. +static void ssam_hub_remove(struct ssam_device *sdev)
  4543. +{
  4544. + ssam_hub_remove_devices(&sdev->dev);
  4545. +}
  4546. +
  4547. +static const struct ssam_device_id ssam_hub_match[] = {
  4548. + { SSAM_VDEV(HUB, 0x01, 0x00, 0x00) },
  4549. + { },
  4550. +};
  4551. +
  4552. +static struct ssam_device_driver ssam_hub_driver = {
  4553. + .probe = ssam_hub_probe,
  4554. + .remove = ssam_hub_remove,
  4555. + .match_table = ssam_hub_match,
  4556. + .driver = {
  4557. + .name = "surface_aggregator_device_hub",
  4558. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  4559. + },
  4560. +};
  4561. +
  4562. +
  4563. +/* -- SSAM base-hub driver. ------------------------------------------------- */
  4564. +
  4565. +enum ssam_base_hub_state {
  4566. + SSAM_BASE_HUB_UNINITIALIZED,
  4567. + SSAM_BASE_HUB_CONNECTED,
  4568. + SSAM_BASE_HUB_DISCONNECTED,
  4569. +};
  4570. +
  4571. +struct ssam_base_hub {
  4572. + struct ssam_device *sdev;
  4573. +
  4574. + struct mutex lock;
  4575. + enum ssam_base_hub_state state;
  4576. +
  4577. + struct ssam_event_notifier notif;
  4578. +};
  4579. +
  4580. +
  4581. +static SSAM_DEFINE_SYNC_REQUEST_R(ssam_bas_query_opmode, u8, {
  4582. + .target_category = SSAM_SSH_TC_BAS,
  4583. + .target_id = 0x01,
  4584. + .command_id = 0x0d,
  4585. + .instance_id = 0x00,
  4586. +});
  4587. +
  4588. +#define SSAM_BAS_OPMODE_TABLET 0x00
  4589. +#define SSAM_EVENT_BAS_CID_CONNECTION 0x0c
  4590. +
  4591. +static int ssam_base_hub_query_state(struct ssam_device *sdev,
  4592. + enum ssam_base_hub_state *state)
  4593. +{
  4594. + u8 opmode;
  4595. + int status;
  4596. +
  4597. + status = ssam_retry(ssam_bas_query_opmode, sdev->ctrl, &opmode);
  4598. + if (status < 0) {
  4599. + dev_err(&sdev->dev, "failed to query base state: %d\n", status);
  4600. + return status;
  4601. + }
  4602. +
  4603. + if (opmode != SSAM_BAS_OPMODE_TABLET)
  4604. + *state = SSAM_BASE_HUB_CONNECTED;
  4605. + else
  4606. + *state = SSAM_BASE_HUB_DISCONNECTED;
  4607. +
  4608. + return 0;
  4609. +}
  4610. +
  4611. +
  4612. +static ssize_t ssam_base_hub_state_show(struct device *dev,
  4613. + struct device_attribute *attr,
  4614. + char *buf)
  4615. +{
  4616. + struct ssam_device *sdev = to_ssam_device(dev);
  4617. + struct ssam_base_hub *hub = ssam_device_get_drvdata(sdev);
  4618. + bool connected;
  4619. +
  4620. + mutex_lock(&hub->lock);
  4621. + connected = hub->state == SSAM_BASE_HUB_CONNECTED;
  4622. + mutex_unlock(&hub->lock);
  4623. +
  4624. + return snprintf(buf, PAGE_SIZE - 1, "%d\n", connected);
  4625. +}
  4626. +
  4627. +static struct device_attribute ssam_base_hub_attr_state =
  4628. + __ATTR(state, 0444, ssam_base_hub_state_show, NULL);
  4629. +
  4630. +static struct attribute *ssam_base_hub_attrs[] = {
  4631. + &ssam_base_hub_attr_state.attr,
  4632. + NULL,
  4633. +};
  4634. +
  4635. +const struct attribute_group ssam_base_hub_group = {
  4636. + .attrs = ssam_base_hub_attrs,
  4637. +};
  4638. +
  4639. +
  4640. +static int ssam_base_hub_update(struct ssam_device *sdev,
  4641. + enum ssam_base_hub_state new)
  4642. +{
  4643. + struct ssam_base_hub *hub = ssam_device_get_drvdata(sdev);
  4644. + struct fwnode_handle *node = dev_fwnode(&sdev->dev);
  4645. + int status = 0;
  4646. +
  4647. + mutex_lock(&hub->lock);
  4648. + if (hub->state == new) {
  4649. + mutex_unlock(&hub->lock);
  4650. + return 0;
  4651. + }
  4652. + hub->state = new;
  4653. +
  4654. + if (hub->state == SSAM_BASE_HUB_CONNECTED)
  4655. + status = ssam_hub_add_devices(&sdev->dev, sdev->ctrl, node);
  4656. +
  4657. + if (hub->state != SSAM_BASE_HUB_CONNECTED || status)
  4658. + ssam_hub_remove_devices(&sdev->dev);
  4659. +
  4660. + mutex_unlock(&hub->lock);
  4661. +
  4662. + if (status) {
  4663. + dev_err(&sdev->dev, "failed to update base-hub devices: %d\n",
  4664. + status);
  4665. + }
  4666. +
  4667. + return status;
  4668. +}
  4669. +
  4670. +static u32 ssam_base_hub_notif(struct ssam_event_notifier *nf,
  4671. + const struct ssam_event *event)
  4672. +{
  4673. + struct ssam_base_hub *hub;
  4674. + struct ssam_device *sdev;
  4675. + enum ssam_base_hub_state new;
  4676. +
  4677. + hub = container_of(nf, struct ssam_base_hub, notif);
  4678. + sdev = hub->sdev;
  4679. +
  4680. + if (event->command_id != SSAM_EVENT_BAS_CID_CONNECTION)
  4681. + return 0;
  4682. +
  4683. + if (event->length < 1) {
  4684. + dev_err(&sdev->dev, "unexpected payload size: %u\n",
  4685. + event->length);
  4686. + return 0;
  4687. + }
  4688. +
  4689. + if (event->data[0])
  4690. + new = SSAM_BASE_HUB_CONNECTED;
  4691. + else
  4692. + new = SSAM_BASE_HUB_DISCONNECTED;
  4693. +
  4694. + ssam_base_hub_update(sdev, new);
  4695. +
  4696. + /*
  4697. + * Do not return SSAM_NOTIF_HANDLED: The event should be picked up and
  4698. + * consumed by the detachment system driver. We're just a (more or less)
  4699. + * silent observer.
  4700. + */
  4701. + return 0;
  4702. +}
  4703. +
  4704. +static int __maybe_unused ssam_base_hub_resume(struct device *dev)
  4705. +{
  4706. + struct ssam_device *sdev = to_ssam_device(dev);
  4707. + enum ssam_base_hub_state state;
  4708. + int status;
  4709. +
  4710. + status = ssam_base_hub_query_state(sdev, &state);
  4711. + if (status)
  4712. + return status;
  4713. +
  4714. + return ssam_base_hub_update(sdev, state);
  4715. +}
  4716. +static SIMPLE_DEV_PM_OPS(ssam_base_hub_pm_ops, NULL, ssam_base_hub_resume);
  4717. +
  4718. +static int ssam_base_hub_probe(struct ssam_device *sdev)
  4719. +{
  4720. + enum ssam_base_hub_state state;
  4721. + struct ssam_base_hub *hub;
  4722. + int status;
  4723. +
  4724. + hub = devm_kzalloc(&sdev->dev, sizeof(*hub), GFP_KERNEL);
  4725. + if (!hub)
  4726. + return -ENOMEM;
  4727. +
  4728. + mutex_init(&hub->lock);
  4729. +
  4730. + hub->sdev = sdev;
  4731. + hub->state = SSAM_BASE_HUB_UNINITIALIZED;
  4732. +
  4733. + hub->notif.base.priority = 1000; // this notifier should run first
  4734. + hub->notif.base.fn = ssam_base_hub_notif;
  4735. + hub->notif.event.reg = SSAM_EVENT_REGISTRY_SAM;
  4736. + hub->notif.event.id.target_category = SSAM_SSH_TC_BAS,
  4737. + hub->notif.event.id.instance = 0,
  4738. + hub->notif.event.mask = SSAM_EVENT_MASK_NONE;
  4739. + hub->notif.event.flags = SSAM_EVENT_SEQUENCED;
  4740. +
  4741. + status = ssam_notifier_register(sdev->ctrl, &hub->notif);
  4742. + if (status)
  4743. + return status;
  4744. +
  4745. + ssam_device_set_drvdata(sdev, hub);
  4746. +
  4747. + status = ssam_base_hub_query_state(sdev, &state);
  4748. + if (status) {
  4749. + ssam_notifier_unregister(sdev->ctrl, &hub->notif);
  4750. + return status;
  4751. + }
  4752. +
  4753. + status = ssam_base_hub_update(sdev, state);
  4754. + if (status) {
  4755. + ssam_notifier_unregister(sdev->ctrl, &hub->notif);
  4756. + return status;
  4757. + }
  4758. +
  4759. + status = sysfs_create_group(&sdev->dev.kobj, &ssam_base_hub_group);
  4760. + if (status) {
  4761. + ssam_notifier_unregister(sdev->ctrl, &hub->notif);
  4762. + ssam_hub_remove_devices(&sdev->dev);
  4763. + }
  4764. +
  4765. + return status;
  4766. +}
  4767. +
  4768. +static void ssam_base_hub_remove(struct ssam_device *sdev)
  4769. +{
  4770. + struct ssam_base_hub *hub = ssam_device_get_drvdata(sdev);
  4771. +
  4772. + sysfs_remove_group(&sdev->dev.kobj, &ssam_base_hub_group);
  4773. +
  4774. + ssam_notifier_unregister(sdev->ctrl, &hub->notif);
  4775. + ssam_hub_remove_devices(&sdev->dev);
  4776. +
  4777. + mutex_destroy(&hub->lock);
  4778. +}
  4779. +
  4780. +static const struct ssam_device_id ssam_base_hub_match[] = {
  4781. + { SSAM_VDEV(HUB, 0x02, 0x00, 0x00) },
  4782. + { },
  4783. +};
  4784. +
  4785. +static struct ssam_device_driver ssam_base_hub_driver = {
  4786. + .probe = ssam_base_hub_probe,
  4787. + .remove = ssam_base_hub_remove,
  4788. + .match_table = ssam_base_hub_match,
  4789. + .driver = {
  4790. + .name = "surface_aggregator_base_hub",
  4791. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  4792. + .pm = &ssam_base_hub_pm_ops,
  4793. + },
  4794. +};
  4795. +
  4796. +
  4797. +/* -- SSAM platform/meta-hub driver. ---------------------------------------- */
  4798. +
  4799. +static const struct acpi_device_id ssam_platform_hub_match[] = {
  4800. + /* Surface Pro 4, 5, and 6 */
  4801. + { "MSHW0081", (unsigned long)ssam_node_group_sp5 },
  4802. +
  4803. + /* Surface Pro 6 (OMBR >= 0x10) */
  4804. + { "MSHW0111", (unsigned long)ssam_node_group_sp6 },
  4805. +
  4806. + /* Surface Pro 7 */
  4807. + { "MSHW0116", (unsigned long)ssam_node_group_sp7 },
  4808. +
  4809. + /* Surface Book 2 */
  4810. + { "MSHW0107", (unsigned long)ssam_node_group_sb2 },
  4811. +
  4812. + /* Surface Book 3 */
  4813. + { "MSHW0117", (unsigned long)ssam_node_group_sb3 },
  4814. +
  4815. + /* Surface Laptop 1 */
  4816. + { "MSHW0086", (unsigned long)ssam_node_group_sl1 },
  4817. +
  4818. + /* Surface Laptop 2 */
  4819. + { "MSHW0112", (unsigned long)ssam_node_group_sl2 },
  4820. +
  4821. + /* Surface Laptop 3 (13", Intel) */
  4822. + { "MSHW0114", (unsigned long)ssam_node_group_sl3 },
  4823. +
  4824. + /* Surface Laptop 3 (15", AMD) */
  4825. + { "MSHW0110", (unsigned long)ssam_node_group_sl3 },
  4826. +
  4827. + { },
  4828. +};
  4829. +MODULE_DEVICE_TABLE(acpi, ssam_platform_hub_match);
  4830. +
  4831. +static int ssam_platform_hub_probe(struct platform_device *pdev)
  4832. +{
  4833. + const struct software_node **nodes;
  4834. + struct ssam_controller *ctrl;
  4835. + struct fwnode_handle *root;
  4836. + int status;
  4837. +
  4838. + nodes = (const struct software_node **)acpi_device_get_match_data(&pdev->dev);
  4839. + if (!nodes)
  4840. + return -ENODEV;
  4841. +
  4842. + /*
  4843. + * As we're adding the SSAM client devices as children under this device
  4844. + * and not the SSAM controller, we need to add a device link to the
  4845. + * controller to ensure that we remove all of our devices before the
  4846. + * controller is removed. This also guarantees proper ordering for
  4847. + * suspend/resume of the devices on this hub.
  4848. + */
  4849. + status = ssam_client_bind(&pdev->dev, &ctrl);
  4850. + if (status)
  4851. + return status == -ENXIO ? -EPROBE_DEFER : status;
  4852. +
  4853. + status = software_node_register_node_group(nodes);
  4854. + if (status)
  4855. + return status;
  4856. +
  4857. + root = software_node_fwnode(&ssam_node_root);
  4858. + if (!root)
  4859. + return -ENOENT;
  4860. +
  4861. + set_secondary_fwnode(&pdev->dev, root);
  4862. +
  4863. + status = ssam_hub_add_devices(&pdev->dev, ctrl, root);
  4864. + if (status) {
  4865. + software_node_unregister_node_group(nodes);
  4866. + return status;
  4867. + }
  4868. +
  4869. + platform_set_drvdata(pdev, nodes);
  4870. + return 0;
  4871. +}
  4872. +
  4873. +static int ssam_platform_hub_remove(struct platform_device *pdev)
  4874. +{
  4875. + const struct software_node **nodes = platform_get_drvdata(pdev);
  4876. +
  4877. + ssam_hub_remove_devices(&pdev->dev);
  4878. + set_secondary_fwnode(&pdev->dev, NULL);
  4879. + software_node_unregister_node_group(nodes);
  4880. + return 0;
  4881. +}
  4882. +
  4883. +static struct platform_driver ssam_platform_hub_driver = {
  4884. + .probe = ssam_platform_hub_probe,
  4885. + .remove = ssam_platform_hub_remove,
  4886. + .driver = {
  4887. + .name = "surface_aggregator_platform_hub",
  4888. + .acpi_match_table = ssam_platform_hub_match,
  4889. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  4890. + },
  4891. +};
  4892. +
  4893. +
  4894. +/* -- Module initialization. ------------------------------------------------ */
  4895. +
  4896. +static int __init ssam_device_hub_init(void)
  4897. +{
  4898. + int status;
  4899. +
  4900. + status = platform_driver_register(&ssam_platform_hub_driver);
  4901. + if (status)
  4902. + goto err_platform;
  4903. +
  4904. + status = ssam_device_driver_register(&ssam_hub_driver);
  4905. + if (status)
  4906. + goto err_main;
  4907. +
  4908. + status = ssam_device_driver_register(&ssam_base_hub_driver);
  4909. + if (status)
  4910. + goto err_base;
  4911. +
  4912. + return 0;
  4913. +
  4914. +err_base:
  4915. + ssam_device_driver_unregister(&ssam_hub_driver);
  4916. +err_main:
  4917. + platform_driver_unregister(&ssam_platform_hub_driver);
  4918. +err_platform:
  4919. + return status;
  4920. +}
  4921. +module_init(ssam_device_hub_init);
  4922. +
  4923. +static void __exit ssam_device_hub_exit(void)
  4924. +{
  4925. + ssam_device_driver_unregister(&ssam_base_hub_driver);
  4926. + ssam_device_driver_unregister(&ssam_hub_driver);
  4927. + platform_driver_unregister(&ssam_platform_hub_driver);
  4928. +}
  4929. +module_exit(ssam_device_hub_exit);
  4930. +
  4931. +MODULE_AUTHOR("Maximilian Luz <luzmaximilian@gmail.com>");
  4932. +MODULE_DESCRIPTION("Device-registry for Surface System Aggregator Module");
  4933. +MODULE_LICENSE("GPL");
  4934. diff --git a/drivers/misc/surface_aggregator/clients/surface_battery.c b/drivers/misc/surface_aggregator/clients/surface_battery.c
  4935. new file mode 100644
  4936. index 000000000000..7ed9ba3f98d7
  4937. --- /dev/null
  4938. +++ b/drivers/misc/surface_aggregator/clients/surface_battery.c
  4939. @@ -0,0 +1,1192 @@
  4940. +// SPDX-License-Identifier: GPL-2.0+
  4941. +/*
  4942. + * Surface battery and AC device driver.
  4943. + *
  4944. + * Provides support for battery and AC devices connected via the Surface
  4945. + * System Aggregator Module.
  4946. + *
  4947. + * Copyright (C) 2019-2020 Maximilian Luz <luzmaximilian@gmail.com>
  4948. + */
  4949. +
  4950. +#include <asm/unaligned.h>
  4951. +#include <linux/delay.h>
  4952. +#include <linux/jiffies.h>
  4953. +#include <linux/kernel.h>
  4954. +#include <linux/module.h>
  4955. +#include <linux/power_supply.h>
  4956. +#include <linux/types.h>
  4957. +#include <linux/workqueue.h>
  4958. +
  4959. +#include <linux/surface_aggregator/device.h>
  4960. +
  4961. +#define SPWR_AC_BAT_UPDATE_DELAY msecs_to_jiffies(5000)
  4962. +
  4963. +
  4964. +/* -- Module parameters. ---------------------------------------------------- */
  4965. +
  4966. +static unsigned int cache_time = 1000;
  4967. +module_param(cache_time, uint, 0644);
  4968. +MODULE_PARM_DESC(cache_time, "battery state chaching time in milliseconds [default: 1000]");
  4969. +
  4970. +
  4971. +/* -- SAM Interface. -------------------------------------------------------- */
  4972. +
  4973. +enum sam_event_cid_bat {
  4974. + SAM_EVENT_CID_BAT_BIX = 0x15,
  4975. + SAM_EVENT_CID_BAT_BST = 0x16,
  4976. + SAM_EVENT_CID_BAT_ADP = 0x17,
  4977. + SAM_EVENT_CID_BAT_PROT = 0x18,
  4978. + SAM_EVENT_CID_BAT_DPTF = 0x53,
  4979. +};
  4980. +
  4981. +enum sam_battery_sta {
  4982. + SAM_BATTERY_STA_OK = 0x0f,
  4983. + SAM_BATTERY_STA_PRESENT = 0x10,
  4984. +};
  4985. +
  4986. +enum sam_battery_state {
  4987. + SAM_BATTERY_STATE_DISCHARGING = BIT(0),
  4988. + SAM_BATTERY_STATE_CHARGING = BIT(1),
  4989. + SAM_BATTERY_STATE_CRITICAL = BIT(2),
  4990. +};
  4991. +
  4992. +enum sam_battery_power_unit {
  4993. + SAM_BATTERY_POWER_UNIT_mW = 0,
  4994. + SAM_BATTERY_POWER_UNIT_mA = 1,
  4995. +};
  4996. +
  4997. +/* Equivalent to data returned in ACPI _BIX method, revision 0 */
  4998. +struct spwr_bix {
  4999. + u8 revision;
  5000. + __le32 power_unit;
  5001. + __le32 design_cap;
  5002. + __le32 last_full_charge_cap;
  5003. + __le32 technology;
  5004. + __le32 design_voltage;
  5005. + __le32 design_cap_warn;
  5006. + __le32 design_cap_low;
  5007. + __le32 cycle_count;
  5008. + __le32 measurement_accuracy;
  5009. + __le32 max_sampling_time;
  5010. + __le32 min_sampling_time;
  5011. + __le32 max_avg_interval;
  5012. + __le32 min_avg_interval;
  5013. + __le32 bat_cap_granularity_1;
  5014. + __le32 bat_cap_granularity_2;
  5015. + __u8 model[21];
  5016. + __u8 serial[11];
  5017. + __u8 type[5];
  5018. + __u8 oem_info[21];
  5019. +} __packed;
  5020. +
  5021. +static_assert(sizeof(struct spwr_bix) == 119);
  5022. +
  5023. +#define SPWR_BIX_REVISION 0
  5024. +
  5025. +/* Equivalent to data returned in ACPI _BST method */
  5026. +struct spwr_bst {
  5027. + __le32 state;
  5028. + __le32 present_rate;
  5029. + __le32 remaining_cap;
  5030. + __le32 present_voltage;
  5031. +} __packed;
  5032. +
  5033. +static_assert(sizeof(struct spwr_bst) == 16);
  5034. +
  5035. +#define SPWR_BATTERY_VALUE_UNKNOWN 0xffffffff
  5036. +
  5037. +/* Get battery status (_STA) */
  5038. +static SSAM_DEFINE_SYNC_REQUEST_CL_R(ssam_bat_get_sta, __le32, {
  5039. + .target_category = SSAM_SSH_TC_BAT,
  5040. + .command_id = 0x01,
  5041. +});
  5042. +
  5043. +/* Get battery static information (_BIX) */
  5044. +static SSAM_DEFINE_SYNC_REQUEST_CL_R(ssam_bat_get_bix, struct spwr_bix, {
  5045. + .target_category = SSAM_SSH_TC_BAT,
  5046. + .command_id = 0x02,
  5047. +});
  5048. +
  5049. +/* Get battery dynamic information (_BST) */
  5050. +static SSAM_DEFINE_SYNC_REQUEST_CL_R(ssam_bat_get_bst, struct spwr_bst, {
  5051. + .target_category = SSAM_SSH_TC_BAT,
  5052. + .command_id = 0x03,
  5053. +});
  5054. +
  5055. +/* Set battery trip point (_BTP) */
  5056. +static SSAM_DEFINE_SYNC_REQUEST_CL_W(ssam_bat_set_btp, __le32, {
  5057. + .target_category = SSAM_SSH_TC_BAT,
  5058. + .command_id = 0x04,
  5059. +});
  5060. +
  5061. +/* Get platform power soruce for battery (DPTF PSRC) */
  5062. +static SSAM_DEFINE_SYNC_REQUEST_CL_R(ssam_bat_get_psrc, __le32, {
  5063. + .target_category = SSAM_SSH_TC_BAT,
  5064. + .command_id = 0x0d,
  5065. +});
  5066. +
  5067. +/*
  5068. + * The following requests are currently unused. They are nevertheless included
  5069. + * for documentation of the SAM interface.
  5070. + */
  5071. +
  5072. +/* Get maximum platform power for battery (DPTF PMAX) */
  5073. +__always_unused
  5074. +static SSAM_DEFINE_SYNC_REQUEST_CL_R(ssam_bat_get_pmax, __le32, {
  5075. + .target_category = SSAM_SSH_TC_BAT,
  5076. + .command_id = 0x0b,
  5077. +});
  5078. +
  5079. +/* Get adapter rating (DPTF ARTG) */
  5080. +__always_unused
  5081. +static SSAM_DEFINE_SYNC_REQUEST_CL_R(ssam_bat_get_artg, __le32, {
  5082. + .target_category = SSAM_SSH_TC_BAT,
  5083. + .command_id = 0x0f,
  5084. +});
  5085. +
  5086. +/* Unknown (DPTF PSOC) */
  5087. +__always_unused
  5088. +static SSAM_DEFINE_SYNC_REQUEST_CL_R(ssam_bat_get_psoc, __le32, {
  5089. + .target_category = SSAM_SSH_TC_BAT,
  5090. + .command_id = 0x0c,
  5091. +});
  5092. +
  5093. +/* Unknown (DPTF CHGI/ INT3403 SPPC) */
  5094. +__always_unused
  5095. +static SSAM_DEFINE_SYNC_REQUEST_CL_W(ssam_bat_set_chgi, __le32, {
  5096. + .target_category = SSAM_SSH_TC_BAT,
  5097. + .command_id = 0x0e,
  5098. +});
  5099. +
  5100. +
  5101. +/* -- Common power-subsystem interface. ------------------------------------- */
  5102. +
  5103. +struct spwr_psy_properties {
  5104. + const char *name;
  5105. + struct ssam_event_registry registry;
  5106. +};
  5107. +
  5108. +struct spwr_battery_device {
  5109. + struct ssam_device *sdev;
  5110. +
  5111. + char name[32];
  5112. + struct power_supply *psy;
  5113. + struct power_supply_desc psy_desc;
  5114. +
  5115. + struct delayed_work update_work;
  5116. +
  5117. + struct ssam_event_notifier notif;
  5118. +
  5119. + struct mutex lock;
  5120. + unsigned long timestamp;
  5121. +
  5122. + __le32 sta;
  5123. + struct spwr_bix bix;
  5124. + struct spwr_bst bst;
  5125. + u32 alarm;
  5126. +};
  5127. +
  5128. +struct spwr_ac_device {
  5129. + struct ssam_device *sdev;
  5130. +
  5131. + char name[32];
  5132. + struct power_supply *psy;
  5133. + struct power_supply_desc psy_desc;
  5134. +
  5135. + struct ssam_event_notifier notif;
  5136. +
  5137. + struct mutex lock;
  5138. +
  5139. + __le32 state;
  5140. +};
  5141. +
  5142. +static enum power_supply_property spwr_ac_props[] = {
  5143. + POWER_SUPPLY_PROP_ONLINE,
  5144. +};
  5145. +
  5146. +static enum power_supply_property spwr_battery_props_chg[] = {
  5147. + POWER_SUPPLY_PROP_STATUS,
  5148. + POWER_SUPPLY_PROP_PRESENT,
  5149. + POWER_SUPPLY_PROP_TECHNOLOGY,
  5150. + POWER_SUPPLY_PROP_CYCLE_COUNT,
  5151. + POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN,
  5152. + POWER_SUPPLY_PROP_VOLTAGE_NOW,
  5153. + POWER_SUPPLY_PROP_CURRENT_NOW,
  5154. + POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN,
  5155. + POWER_SUPPLY_PROP_CHARGE_FULL,
  5156. + POWER_SUPPLY_PROP_CHARGE_NOW,
  5157. + POWER_SUPPLY_PROP_CAPACITY,
  5158. + POWER_SUPPLY_PROP_CAPACITY_LEVEL,
  5159. + POWER_SUPPLY_PROP_MODEL_NAME,
  5160. + POWER_SUPPLY_PROP_MANUFACTURER,
  5161. + POWER_SUPPLY_PROP_SERIAL_NUMBER,
  5162. +};
  5163. +
  5164. +static enum power_supply_property spwr_battery_props_eng[] = {
  5165. + POWER_SUPPLY_PROP_STATUS,
  5166. + POWER_SUPPLY_PROP_PRESENT,
  5167. + POWER_SUPPLY_PROP_TECHNOLOGY,
  5168. + POWER_SUPPLY_PROP_CYCLE_COUNT,
  5169. + POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN,
  5170. + POWER_SUPPLY_PROP_VOLTAGE_NOW,
  5171. + POWER_SUPPLY_PROP_POWER_NOW,
  5172. + POWER_SUPPLY_PROP_ENERGY_FULL_DESIGN,
  5173. + POWER_SUPPLY_PROP_ENERGY_FULL,
  5174. + POWER_SUPPLY_PROP_ENERGY_NOW,
  5175. + POWER_SUPPLY_PROP_CAPACITY,
  5176. + POWER_SUPPLY_PROP_CAPACITY_LEVEL,
  5177. + POWER_SUPPLY_PROP_MODEL_NAME,
  5178. + POWER_SUPPLY_PROP_MANUFACTURER,
  5179. + POWER_SUPPLY_PROP_SERIAL_NUMBER,
  5180. +};
  5181. +
  5182. +static bool spwr_battery_present(struct spwr_battery_device *bat)
  5183. +{
  5184. + return le32_to_cpu(bat->sta) & SAM_BATTERY_STA_PRESENT;
  5185. +}
  5186. +
  5187. +static int spwr_battery_load_sta(struct spwr_battery_device *bat)
  5188. +{
  5189. + return ssam_retry(ssam_bat_get_sta, bat->sdev, &bat->sta);
  5190. +}
  5191. +
  5192. +static int spwr_battery_load_bix(struct spwr_battery_device *bat)
  5193. +{
  5194. + int status;
  5195. +
  5196. + if (!spwr_battery_present(bat))
  5197. + return 0;
  5198. +
  5199. + status = ssam_retry(ssam_bat_get_bix, bat->sdev, &bat->bix);
  5200. +
  5201. + // enforce NULL terminated strings in case anything goes wrong...
  5202. + bat->bix.model[ARRAY_SIZE(bat->bix.model) - 1] = 0;
  5203. + bat->bix.serial[ARRAY_SIZE(bat->bix.serial) - 1] = 0;
  5204. + bat->bix.type[ARRAY_SIZE(bat->bix.type) - 1] = 0;
  5205. + bat->bix.oem_info[ARRAY_SIZE(bat->bix.oem_info) - 1] = 0;
  5206. +
  5207. + return status;
  5208. +}
  5209. +
  5210. +static int spwr_battery_load_bst(struct spwr_battery_device *bat)
  5211. +{
  5212. + if (!spwr_battery_present(bat))
  5213. + return 0;
  5214. +
  5215. + return ssam_retry(ssam_bat_get_bst, bat->sdev, &bat->bst);
  5216. +}
  5217. +
  5218. +static int spwr_battery_set_alarm_unlocked(struct spwr_battery_device *bat,
  5219. + u32 value)
  5220. +{
  5221. + __le32 value_le = cpu_to_le32(value);
  5222. +
  5223. + bat->alarm = value;
  5224. + return ssam_retry(ssam_bat_set_btp, bat->sdev, &value_le);
  5225. +}
  5226. +
  5227. +static int spwr_battery_set_alarm(struct spwr_battery_device *bat, u32 value)
  5228. +{
  5229. + int status;
  5230. +
  5231. + mutex_lock(&bat->lock);
  5232. + status = spwr_battery_set_alarm_unlocked(bat, value);
  5233. + mutex_unlock(&bat->lock);
  5234. +
  5235. + return status;
  5236. +}
  5237. +
  5238. +static int spwr_battery_update_bst_unlocked(struct spwr_battery_device *bat,
  5239. + bool cached)
  5240. +{
  5241. + unsigned long cache_deadline;
  5242. + int status;
  5243. +
  5244. + cache_deadline = bat->timestamp + msecs_to_jiffies(cache_time);
  5245. + if (cached && bat->timestamp && time_is_after_jiffies(cache_deadline))
  5246. + return 0;
  5247. +
  5248. + status = spwr_battery_load_sta(bat);
  5249. + if (status)
  5250. + return status;
  5251. +
  5252. + status = spwr_battery_load_bst(bat);
  5253. + if (status)
  5254. + return status;
  5255. +
  5256. + bat->timestamp = jiffies;
  5257. + return 0;
  5258. +}
  5259. +
  5260. +static int spwr_battery_update_bst(struct spwr_battery_device *bat, bool cached)
  5261. +{
  5262. + int status;
  5263. +
  5264. + mutex_lock(&bat->lock);
  5265. + status = spwr_battery_update_bst_unlocked(bat, cached);
  5266. + mutex_unlock(&bat->lock);
  5267. +
  5268. + return status;
  5269. +}
  5270. +
  5271. +static int spwr_battery_update_bix_unlocked(struct spwr_battery_device *bat)
  5272. +{
  5273. + int status;
  5274. +
  5275. + status = spwr_battery_load_sta(bat);
  5276. + if (status)
  5277. + return status;
  5278. +
  5279. + status = spwr_battery_load_bix(bat);
  5280. + if (status)
  5281. + return status;
  5282. +
  5283. + status = spwr_battery_load_bst(bat);
  5284. + if (status)
  5285. + return status;
  5286. +
  5287. + if (bat->bix.revision != SPWR_BIX_REVISION) {
  5288. + dev_warn(&bat->sdev->dev, "unsupported battery revision: %u\n",
  5289. + bat->bix.revision);
  5290. + }
  5291. +
  5292. + bat->timestamp = jiffies;
  5293. + return 0;
  5294. +}
  5295. +
  5296. +static int spwr_ac_update_unlocked(struct spwr_ac_device *ac)
  5297. +{
  5298. + int status;
  5299. + u32 old = ac->state;
  5300. +
  5301. + status = ssam_retry(ssam_bat_get_psrc, ac->sdev, &ac->state);
  5302. + if (status < 0)
  5303. + return status;
  5304. +
  5305. + return old != ac->state;
  5306. +}
  5307. +
  5308. +static int spwr_ac_update(struct spwr_ac_device *ac)
  5309. +{
  5310. + int status;
  5311. +
  5312. + mutex_lock(&ac->lock);
  5313. + status = spwr_ac_update_unlocked(ac);
  5314. + mutex_unlock(&ac->lock);
  5315. +
  5316. + return status;
  5317. +}
  5318. +
  5319. +static u32 sprw_battery_get_full_cap_safe(struct spwr_battery_device *bat)
  5320. +{
  5321. + u32 full_cap = get_unaligned_le32(&bat->bix.last_full_charge_cap);
  5322. +
  5323. + if (full_cap == 0 || full_cap == SPWR_BATTERY_VALUE_UNKNOWN)
  5324. + full_cap = get_unaligned_le32(&bat->bix.design_cap);
  5325. +
  5326. + return full_cap;
  5327. +}
  5328. +
  5329. +static bool spwr_battery_is_full(struct spwr_battery_device *bat)
  5330. +{
  5331. + u32 state = get_unaligned_le32(&bat->bst.state);
  5332. + u32 full_cap = sprw_battery_get_full_cap_safe(bat);
  5333. + u32 remaining_cap = get_unaligned_le32(&bat->bst.remaining_cap);
  5334. +
  5335. + return full_cap != SPWR_BATTERY_VALUE_UNKNOWN && full_cap != 0
  5336. + && remaining_cap != SPWR_BATTERY_VALUE_UNKNOWN
  5337. + && remaining_cap >= full_cap
  5338. + && state == 0;
  5339. +}
  5340. +
  5341. +static int spwr_battery_recheck_full(struct spwr_battery_device *bat)
  5342. +{
  5343. + bool present;
  5344. + u32 unit;
  5345. + int status;
  5346. +
  5347. + mutex_lock(&bat->lock);
  5348. + unit = get_unaligned_le32(&bat->bix.power_unit);
  5349. + present = spwr_battery_present(bat);
  5350. +
  5351. + status = spwr_battery_update_bix_unlocked(bat);
  5352. + if (status)
  5353. + goto out;
  5354. +
  5355. + // if battery has been attached, (re-)initialize alarm
  5356. + if (!present && spwr_battery_present(bat)) {
  5357. + u32 cap_warn = get_unaligned_le32(&bat->bix.design_cap_warn);
  5358. +
  5359. + status = spwr_battery_set_alarm_unlocked(bat, cap_warn);
  5360. + if (status)
  5361. + goto out;
  5362. + }
  5363. +
  5364. + /*
  5365. + * Warn if the unit has changed. This is something we genuinely don't
  5366. + * expect to happen, so make this a big warning. If it does, we'll
  5367. + * need to add support for it.
  5368. + */
  5369. + WARN_ON(unit != get_unaligned_le32(&bat->bix.power_unit));
  5370. +
  5371. +out:
  5372. + mutex_unlock(&bat->lock);
  5373. +
  5374. + if (!status)
  5375. + power_supply_changed(bat->psy);
  5376. +
  5377. + return status;
  5378. +}
  5379. +
  5380. +static int spwr_battery_recheck_status(struct spwr_battery_device *bat)
  5381. +{
  5382. + int status;
  5383. +
  5384. + status = spwr_battery_update_bst(bat, false);
  5385. + if (!status)
  5386. + power_supply_changed(bat->psy);
  5387. +
  5388. + return status;
  5389. +}
  5390. +
  5391. +static int spwr_battery_recheck_adapter(struct spwr_battery_device *bat)
  5392. +{
  5393. + u32 full_cap = sprw_battery_get_full_cap_safe(bat);
  5394. + u32 remaining_cap = get_unaligned_le32(&bat->bst.remaining_cap);
  5395. +
  5396. + if (full_cap == 0 || full_cap == SPWR_BATTERY_VALUE_UNKNOWN)
  5397. + return 0;
  5398. +
  5399. + if (remaining_cap == SPWR_BATTERY_VALUE_UNKNOWN)
  5400. + return 0;
  5401. +
  5402. + /*
  5403. + * Handle battery update quirk:
  5404. + * When the battery is fully charged and the adapter is plugged in or
  5405. + * removed, the EC does not send a separate event for the state
  5406. + * (charging/discharging) change. Furthermore it may take some time until
  5407. + * the state is updated on the battery. Schedule an update to solve this.
  5408. + */
  5409. +
  5410. + if (remaining_cap >= full_cap)
  5411. + schedule_delayed_work(&bat->update_work, SPWR_AC_BAT_UPDATE_DELAY);
  5412. +
  5413. + return 0;
  5414. +}
  5415. +
  5416. +static int spwr_ac_recheck(struct spwr_ac_device *ac)
  5417. +{
  5418. + int status;
  5419. +
  5420. + status = spwr_ac_update(ac);
  5421. + if (status > 0)
  5422. + power_supply_changed(ac->psy);
  5423. +
  5424. + return status >= 0 ? 0 : status;
  5425. +}
  5426. +
  5427. +static u32 spwr_notify_bat(struct ssam_event_notifier *nf,
  5428. + const struct ssam_event *event)
  5429. +{
  5430. + struct spwr_battery_device *bat;
  5431. + int status;
  5432. +
  5433. + bat = container_of(nf, struct spwr_battery_device, notif);
  5434. +
  5435. + dev_dbg(&bat->sdev->dev, "power event (cid = 0x%02x, iid = %d, tid = %d)\n",
  5436. + event->command_id, event->instance_id, event->target_id);
  5437. +
  5438. + // handled here, needs to be handled for all targets/instances
  5439. + if (event->command_id == SAM_EVENT_CID_BAT_ADP) {
  5440. + status = spwr_battery_recheck_adapter(bat);
  5441. + return ssam_notifier_from_errno(status) | SSAM_NOTIF_HANDLED;
  5442. + }
  5443. +
  5444. + if (bat->sdev->uid.target != event->target_id)
  5445. + return 0;
  5446. +
  5447. + if (bat->sdev->uid.instance != event->instance_id)
  5448. + return 0;
  5449. +
  5450. + switch (event->command_id) {
  5451. + case SAM_EVENT_CID_BAT_BIX:
  5452. + status = spwr_battery_recheck_full(bat);
  5453. + break;
  5454. +
  5455. + case SAM_EVENT_CID_BAT_BST:
  5456. + status = spwr_battery_recheck_status(bat);
  5457. + break;
  5458. +
  5459. + case SAM_EVENT_CID_BAT_PROT:
  5460. + /*
  5461. + * TODO: Implement support for battery protection status change
  5462. + * event.
  5463. + */
  5464. + status = 0;
  5465. + break;
  5466. +
  5467. + case SAM_EVENT_CID_BAT_DPTF:
  5468. + /*
  5469. + * TODO: Implement support for DPTF event.
  5470. + */
  5471. + status = 0;
  5472. + break;
  5473. +
  5474. + default:
  5475. + return 0;
  5476. + }
  5477. +
  5478. + return ssam_notifier_from_errno(status) | SSAM_NOTIF_HANDLED;
  5479. +}
  5480. +
  5481. +static u32 spwr_notify_ac(struct ssam_event_notifier *nf,
  5482. + const struct ssam_event *event)
  5483. +{
  5484. + struct spwr_ac_device *ac;
  5485. + int status;
  5486. +
  5487. + ac = container_of(nf, struct spwr_ac_device, notif);
  5488. +
  5489. + dev_dbg(&ac->sdev->dev, "power event (cid = 0x%02x, iid = %d, tid = %d)\n",
  5490. + event->command_id, event->instance_id, event->target_id);
  5491. +
  5492. + /*
  5493. + * Allow events of all targets/instances here. Global adapter status
  5494. + * seems to be handled via target=1 and instance=1, but events are
  5495. + * reported on all targets/instances in use.
  5496. + *
  5497. + * While it should be enough to just listen on 1/1, listen everywhere to
  5498. + * make sure we don't miss anything.
  5499. + */
  5500. +
  5501. + switch (event->command_id) {
  5502. + case SAM_EVENT_CID_BAT_ADP:
  5503. + status = spwr_ac_recheck(ac);
  5504. + return ssam_notifier_from_errno(status) | SSAM_NOTIF_HANDLED;
  5505. +
  5506. + default:
  5507. + return 0;
  5508. + }
  5509. +}
  5510. +
  5511. +static void spwr_battery_update_bst_workfn(struct work_struct *work)
  5512. +{
  5513. + struct delayed_work *dwork = to_delayed_work(work);
  5514. + struct spwr_battery_device *bat;
  5515. + int status;
  5516. +
  5517. + bat = container_of(dwork, struct spwr_battery_device, update_work);
  5518. +
  5519. + status = spwr_battery_update_bst(bat, false);
  5520. + if (!status)
  5521. + power_supply_changed(bat->psy);
  5522. +
  5523. + if (status) {
  5524. + dev_err(&bat->sdev->dev, "failed to update battery state: %d\n",
  5525. + status);
  5526. + }
  5527. +}
  5528. +
  5529. +static int spwr_battery_prop_status(struct spwr_battery_device *bat)
  5530. +{
  5531. + u32 state = get_unaligned_le32(&bat->bst.state);
  5532. + u32 present_rate = get_unaligned_le32(&bat->bst.present_rate);
  5533. +
  5534. + if (state & SAM_BATTERY_STATE_DISCHARGING)
  5535. + return POWER_SUPPLY_STATUS_DISCHARGING;
  5536. +
  5537. + if (state & SAM_BATTERY_STATE_CHARGING)
  5538. + return POWER_SUPPLY_STATUS_CHARGING;
  5539. +
  5540. + if (spwr_battery_is_full(bat))
  5541. + return POWER_SUPPLY_STATUS_FULL;
  5542. +
  5543. + if (present_rate == 0)
  5544. + return POWER_SUPPLY_STATUS_NOT_CHARGING;
  5545. +
  5546. + return POWER_SUPPLY_STATUS_UNKNOWN;
  5547. +}
  5548. +
  5549. +static int spwr_battery_prop_technology(struct spwr_battery_device *bat)
  5550. +{
  5551. + if (!strcasecmp("NiCd", bat->bix.type))
  5552. + return POWER_SUPPLY_TECHNOLOGY_NiCd;
  5553. +
  5554. + if (!strcasecmp("NiMH", bat->bix.type))
  5555. + return POWER_SUPPLY_TECHNOLOGY_NiMH;
  5556. +
  5557. + if (!strcasecmp("LION", bat->bix.type))
  5558. + return POWER_SUPPLY_TECHNOLOGY_LION;
  5559. +
  5560. + if (!strncasecmp("LI-ION", bat->bix.type, 6))
  5561. + return POWER_SUPPLY_TECHNOLOGY_LION;
  5562. +
  5563. + if (!strcasecmp("LiP", bat->bix.type))
  5564. + return POWER_SUPPLY_TECHNOLOGY_LIPO;
  5565. +
  5566. + return POWER_SUPPLY_TECHNOLOGY_UNKNOWN;
  5567. +}
  5568. +
  5569. +static int spwr_battery_prop_capacity(struct spwr_battery_device *bat)
  5570. +{
  5571. + u32 full_cap = sprw_battery_get_full_cap_safe(bat);
  5572. + u32 remaining_cap = get_unaligned_le32(&bat->bst.remaining_cap);
  5573. +
  5574. + if (full_cap == 0 || full_cap == SPWR_BATTERY_VALUE_UNKNOWN)
  5575. + return -ENODEV;
  5576. +
  5577. + if (remaining_cap == SPWR_BATTERY_VALUE_UNKNOWN)
  5578. + return -ENODEV;
  5579. +
  5580. + return remaining_cap * 100 / full_cap;
  5581. +}
  5582. +
  5583. +static int spwr_battery_prop_capacity_level(struct spwr_battery_device *bat)
  5584. +{
  5585. + u32 state = get_unaligned_le32(&bat->bst.state);
  5586. + u32 remaining_cap = get_unaligned_le32(&bat->bst.remaining_cap);
  5587. +
  5588. + if (state & SAM_BATTERY_STATE_CRITICAL)
  5589. + return POWER_SUPPLY_CAPACITY_LEVEL_CRITICAL;
  5590. +
  5591. + if (spwr_battery_is_full(bat))
  5592. + return POWER_SUPPLY_CAPACITY_LEVEL_FULL;
  5593. +
  5594. + if (remaining_cap <= bat->alarm)
  5595. + return POWER_SUPPLY_CAPACITY_LEVEL_LOW;
  5596. +
  5597. + return POWER_SUPPLY_CAPACITY_LEVEL_NORMAL;
  5598. +}
  5599. +
  5600. +static int spwr_ac_get_property(struct power_supply *psy,
  5601. + enum power_supply_property psp,
  5602. + union power_supply_propval *val)
  5603. +{
  5604. + struct spwr_ac_device *ac = power_supply_get_drvdata(psy);
  5605. + int status;
  5606. +
  5607. + mutex_lock(&ac->lock);
  5608. +
  5609. + status = spwr_ac_update_unlocked(ac);
  5610. + if (status)
  5611. + goto out;
  5612. +
  5613. + switch (psp) {
  5614. + case POWER_SUPPLY_PROP_ONLINE:
  5615. + val->intval = !!le32_to_cpu(ac->state);
  5616. + break;
  5617. +
  5618. + default:
  5619. + status = -EINVAL;
  5620. + goto out;
  5621. + }
  5622. +
  5623. +out:
  5624. + mutex_unlock(&ac->lock);
  5625. + return status;
  5626. +}
  5627. +
  5628. +static int spwr_battery_get_property(struct power_supply *psy,
  5629. + enum power_supply_property psp,
  5630. + union power_supply_propval *val)
  5631. +{
  5632. + struct spwr_battery_device *bat = power_supply_get_drvdata(psy);
  5633. + u32 value;
  5634. + int status;
  5635. +
  5636. + mutex_lock(&bat->lock);
  5637. +
  5638. + status = spwr_battery_update_bst_unlocked(bat, true);
  5639. + if (status)
  5640. + goto out;
  5641. +
  5642. + // abort if battery is not present
  5643. + if (!spwr_battery_present(bat) && psp != POWER_SUPPLY_PROP_PRESENT) {
  5644. + status = -ENODEV;
  5645. + goto out;
  5646. + }
  5647. +
  5648. + switch (psp) {
  5649. + case POWER_SUPPLY_PROP_STATUS:
  5650. + val->intval = spwr_battery_prop_status(bat);
  5651. + break;
  5652. +
  5653. + case POWER_SUPPLY_PROP_PRESENT:
  5654. + val->intval = spwr_battery_present(bat);
  5655. + break;
  5656. +
  5657. + case POWER_SUPPLY_PROP_TECHNOLOGY:
  5658. + val->intval = spwr_battery_prop_technology(bat);
  5659. + break;
  5660. +
  5661. + case POWER_SUPPLY_PROP_CYCLE_COUNT:
  5662. + value = get_unaligned_le32(&bat->bix.cycle_count);
  5663. + if (value != SPWR_BATTERY_VALUE_UNKNOWN)
  5664. + val->intval = value;
  5665. + else
  5666. + status = -ENODEV;
  5667. + break;
  5668. +
  5669. + case POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN:
  5670. + value = get_unaligned_le32(&bat->bix.design_voltage);
  5671. + if (value != SPWR_BATTERY_VALUE_UNKNOWN)
  5672. + val->intval = value * 1000;
  5673. + else
  5674. + status = -ENODEV;
  5675. + break;
  5676. +
  5677. + case POWER_SUPPLY_PROP_VOLTAGE_NOW:
  5678. + value = get_unaligned_le32(&bat->bst.present_voltage);
  5679. + if (value != SPWR_BATTERY_VALUE_UNKNOWN)
  5680. + val->intval = value * 1000;
  5681. + else
  5682. + status = -ENODEV;
  5683. + break;
  5684. +
  5685. + case POWER_SUPPLY_PROP_CURRENT_NOW:
  5686. + case POWER_SUPPLY_PROP_POWER_NOW:
  5687. + value = get_unaligned_le32(&bat->bst.present_rate);
  5688. + if (value != SPWR_BATTERY_VALUE_UNKNOWN)
  5689. + val->intval = value * 1000;
  5690. + else
  5691. + status = -ENODEV;
  5692. + break;
  5693. +
  5694. + case POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN:
  5695. + case POWER_SUPPLY_PROP_ENERGY_FULL_DESIGN:
  5696. + value = get_unaligned_le32(&bat->bix.design_cap);
  5697. + if (value != SPWR_BATTERY_VALUE_UNKNOWN)
  5698. + val->intval = value * 1000;
  5699. + else
  5700. + status = -ENODEV;
  5701. + break;
  5702. +
  5703. + case POWER_SUPPLY_PROP_CHARGE_FULL:
  5704. + case POWER_SUPPLY_PROP_ENERGY_FULL:
  5705. + value = get_unaligned_le32(&bat->bix.last_full_charge_cap);
  5706. + if (value != SPWR_BATTERY_VALUE_UNKNOWN)
  5707. + val->intval = value * 1000;
  5708. + else
  5709. + status = -ENODEV;
  5710. + break;
  5711. +
  5712. + case POWER_SUPPLY_PROP_CHARGE_NOW:
  5713. + case POWER_SUPPLY_PROP_ENERGY_NOW:
  5714. + value = get_unaligned_le32(&bat->bst.remaining_cap);
  5715. + if (value != SPWR_BATTERY_VALUE_UNKNOWN)
  5716. + val->intval = value * 1000;
  5717. + else
  5718. + status = -ENODEV;
  5719. + break;
  5720. +
  5721. + case POWER_SUPPLY_PROP_CAPACITY:
  5722. + val->intval = spwr_battery_prop_capacity(bat);
  5723. + break;
  5724. +
  5725. + case POWER_SUPPLY_PROP_CAPACITY_LEVEL:
  5726. + val->intval = spwr_battery_prop_capacity_level(bat);
  5727. + break;
  5728. +
  5729. + case POWER_SUPPLY_PROP_MODEL_NAME:
  5730. + val->strval = bat->bix.model;
  5731. + break;
  5732. +
  5733. + case POWER_SUPPLY_PROP_MANUFACTURER:
  5734. + val->strval = bat->bix.oem_info;
  5735. + break;
  5736. +
  5737. + case POWER_SUPPLY_PROP_SERIAL_NUMBER:
  5738. + val->strval = bat->bix.serial;
  5739. + break;
  5740. +
  5741. + default:
  5742. + status = -EINVAL;
  5743. + break;
  5744. + }
  5745. +
  5746. +out:
  5747. + mutex_unlock(&bat->lock);
  5748. + return status;
  5749. +}
  5750. +
  5751. +
  5752. +static ssize_t spwr_battery_alarm_show(struct device *dev,
  5753. + struct device_attribute *attr,
  5754. + char *buf)
  5755. +{
  5756. + struct power_supply *psy = dev_get_drvdata(dev);
  5757. + struct spwr_battery_device *bat = power_supply_get_drvdata(psy);
  5758. +
  5759. + return sprintf(buf, "%d\n", bat->alarm * 1000);
  5760. +}
  5761. +
  5762. +static ssize_t spwr_battery_alarm_store(struct device *dev,
  5763. + struct device_attribute *attr,
  5764. + const char *buf, size_t count)
  5765. +{
  5766. + struct power_supply *psy = dev_get_drvdata(dev);
  5767. + struct spwr_battery_device *bat = power_supply_get_drvdata(psy);
  5768. + unsigned long value;
  5769. + int status;
  5770. +
  5771. + status = kstrtoul(buf, 0, &value);
  5772. + if (status)
  5773. + return status;
  5774. +
  5775. + if (!spwr_battery_present(bat))
  5776. + return -ENODEV;
  5777. +
  5778. + status = spwr_battery_set_alarm(bat, value / 1000);
  5779. + if (status)
  5780. + return status;
  5781. +
  5782. + return count;
  5783. +}
  5784. +
  5785. +static const struct device_attribute alarm_attr = {
  5786. + .attr = {.name = "alarm", .mode = 0644},
  5787. + .show = spwr_battery_alarm_show,
  5788. + .store = spwr_battery_alarm_store,
  5789. +};
  5790. +
  5791. +
  5792. +static void spwr_ac_init(struct spwr_ac_device *ac,
  5793. + struct ssam_device *sdev,
  5794. + struct ssam_event_registry registry,
  5795. + const char *name)
  5796. +{
  5797. + mutex_init(&ac->lock);
  5798. + strncpy(ac->name, name, ARRAY_SIZE(ac->name) - 1);
  5799. +
  5800. + ac->sdev = sdev;
  5801. +
  5802. + ac->notif.base.priority = 1;
  5803. + ac->notif.base.fn = spwr_notify_ac;
  5804. + ac->notif.event.reg = registry;
  5805. + ac->notif.event.id.target_category = sdev->uid.category;
  5806. + ac->notif.event.id.instance = 0;
  5807. + ac->notif.event.mask = SSAM_EVENT_MASK_NONE;
  5808. + ac->notif.event.flags = SSAM_EVENT_SEQUENCED;
  5809. +
  5810. + ac->psy_desc.name = ac->name;
  5811. + ac->psy_desc.type = POWER_SUPPLY_TYPE_MAINS;
  5812. + ac->psy_desc.properties = spwr_ac_props;
  5813. + ac->psy_desc.num_properties = ARRAY_SIZE(spwr_ac_props);
  5814. + ac->psy_desc.get_property = spwr_ac_get_property;
  5815. +}
  5816. +
  5817. +static void spwr_ac_destroy(struct spwr_ac_device *ac)
  5818. +{
  5819. + mutex_destroy(&ac->lock);
  5820. +}
  5821. +
  5822. +static int spwr_ac_register(struct spwr_ac_device *ac)
  5823. +{
  5824. + struct power_supply_config psy_cfg = {};
  5825. + __le32 sta;
  5826. + int status;
  5827. +
  5828. + // make sure the device is there and functioning properly
  5829. + status = ssam_retry(ssam_bat_get_sta, ac->sdev, &sta);
  5830. + if (status)
  5831. + return status;
  5832. +
  5833. + if ((le32_to_cpu(sta) & SAM_BATTERY_STA_OK) != SAM_BATTERY_STA_OK)
  5834. + return -ENODEV;
  5835. +
  5836. + psy_cfg.drv_data = ac;
  5837. + ac->psy = power_supply_register(&ac->sdev->dev, &ac->psy_desc, &psy_cfg);
  5838. + if (IS_ERR(ac->psy))
  5839. + return PTR_ERR(ac->psy);
  5840. +
  5841. + status = ssam_notifier_register(ac->sdev->ctrl, &ac->notif);
  5842. + if (status)
  5843. + power_supply_unregister(ac->psy);
  5844. +
  5845. + return status;
  5846. +}
  5847. +
  5848. +static int spwr_ac_unregister(struct spwr_ac_device *ac)
  5849. +{
  5850. + ssam_notifier_unregister(ac->sdev->ctrl, &ac->notif);
  5851. + power_supply_unregister(ac->psy);
  5852. + return 0;
  5853. +}
  5854. +
  5855. +static void spwr_battery_init(struct spwr_battery_device *bat,
  5856. + struct ssam_device *sdev,
  5857. + struct ssam_event_registry registry,
  5858. + const char *name)
  5859. +{
  5860. + mutex_init(&bat->lock);
  5861. + strncpy(bat->name, name, ARRAY_SIZE(bat->name) - 1);
  5862. +
  5863. + bat->sdev = sdev;
  5864. +
  5865. + bat->notif.base.priority = 1;
  5866. + bat->notif.base.fn = spwr_notify_bat;
  5867. + bat->notif.event.reg = registry;
  5868. + bat->notif.event.id.target_category = sdev->uid.category;
  5869. + bat->notif.event.id.instance = 0;
  5870. + bat->notif.event.mask = SSAM_EVENT_MASK_NONE;
  5871. + bat->notif.event.flags = SSAM_EVENT_SEQUENCED;
  5872. +
  5873. + bat->psy_desc.name = bat->name;
  5874. + bat->psy_desc.type = POWER_SUPPLY_TYPE_BATTERY;
  5875. + bat->psy_desc.get_property = spwr_battery_get_property;
  5876. +
  5877. + INIT_DELAYED_WORK(&bat->update_work, spwr_battery_update_bst_workfn);
  5878. +}
  5879. +
  5880. +static void spwr_battery_destroy(struct spwr_battery_device *bat)
  5881. +{
  5882. + mutex_destroy(&bat->lock);
  5883. +}
  5884. +
  5885. +static int spwr_battery_register(struct spwr_battery_device *bat)
  5886. +{
  5887. + struct power_supply_config psy_cfg = {};
  5888. + __le32 sta;
  5889. + int status;
  5890. +
  5891. + // make sure the device is there and functioning properly
  5892. + status = ssam_retry(ssam_bat_get_sta, bat->sdev, &sta);
  5893. + if (status)
  5894. + return status;
  5895. +
  5896. + if ((le32_to_cpu(sta) & SAM_BATTERY_STA_OK) != SAM_BATTERY_STA_OK)
  5897. + return -ENODEV;
  5898. +
  5899. + status = spwr_battery_update_bix_unlocked(bat);
  5900. + if (status)
  5901. + return status;
  5902. +
  5903. + if (spwr_battery_present(bat)) {
  5904. + u32 cap_warn = get_unaligned_le32(&bat->bix.design_cap_warn);
  5905. +
  5906. + status = spwr_battery_set_alarm_unlocked(bat, cap_warn);
  5907. + if (status)
  5908. + return status;
  5909. + }
  5910. +
  5911. + switch (get_unaligned_le32(&bat->bix.power_unit)) {
  5912. + case SAM_BATTERY_POWER_UNIT_mW:
  5913. + bat->psy_desc.properties = spwr_battery_props_eng;
  5914. + bat->psy_desc.num_properties = ARRAY_SIZE(spwr_battery_props_eng);
  5915. + break;
  5916. +
  5917. + case SAM_BATTERY_POWER_UNIT_mA:
  5918. + bat->psy_desc.properties = spwr_battery_props_chg;
  5919. + bat->psy_desc.num_properties = ARRAY_SIZE(spwr_battery_props_chg);
  5920. + break;
  5921. +
  5922. + default:
  5923. + dev_err(&bat->sdev->dev, "unsupported battery power unit: %u\n",
  5924. + get_unaligned_le32(&bat->bix.power_unit));
  5925. + return -ENOTSUPP;
  5926. + }
  5927. +
  5928. + psy_cfg.drv_data = bat;
  5929. + bat->psy = power_supply_register(&bat->sdev->dev, &bat->psy_desc, &psy_cfg);
  5930. + if (IS_ERR(bat->psy))
  5931. + return PTR_ERR(bat->psy);
  5932. +
  5933. + status = ssam_notifier_register(bat->sdev->ctrl, &bat->notif);
  5934. + if (status)
  5935. + goto err_notif;
  5936. +
  5937. + status = device_create_file(&bat->psy->dev, &alarm_attr);
  5938. + if (status)
  5939. + goto err_file;
  5940. +
  5941. + return 0;
  5942. +
  5943. +err_file:
  5944. + ssam_notifier_unregister(bat->sdev->ctrl, &bat->notif);
  5945. +err_notif:
  5946. + power_supply_unregister(bat->psy);
  5947. + return status;
  5948. +}
  5949. +
  5950. +static void spwr_battery_unregister(struct spwr_battery_device *bat)
  5951. +{
  5952. + ssam_notifier_unregister(bat->sdev->ctrl, &bat->notif);
  5953. + cancel_delayed_work_sync(&bat->update_work);
  5954. + device_remove_file(&bat->psy->dev, &alarm_attr);
  5955. + power_supply_unregister(bat->psy);
  5956. +}
  5957. +
  5958. +
  5959. +/* -- Power management. ----------------------------------------------------- */
  5960. +
  5961. +#ifdef CONFIG_PM_SLEEP
  5962. +
  5963. +static int surface_battery_resume(struct device *dev)
  5964. +{
  5965. + return spwr_battery_recheck_full(dev_get_drvdata(dev));
  5966. +}
  5967. +
  5968. +static int surface_ac_resume(struct device *dev)
  5969. +{
  5970. + return spwr_ac_recheck(dev_get_drvdata(dev));
  5971. +}
  5972. +
  5973. +#else /* CONFIG_PM_SLEEP */
  5974. +
  5975. +#define surface_battery_resume NULL
  5976. +#define surface_ac_resume NULL
  5977. +
  5978. +#endif /* CONFIG_PM_SLEEP */
  5979. +
  5980. +SIMPLE_DEV_PM_OPS(surface_battery_pm_ops, NULL, surface_battery_resume);
  5981. +SIMPLE_DEV_PM_OPS(surface_ac_pm_ops, NULL, surface_ac_resume);
  5982. +
  5983. +
  5984. +/* -- Battery driver. ------------------------------------------------------- */
  5985. +
  5986. +static int surface_battery_probe(struct ssam_device *sdev)
  5987. +{
  5988. + const struct spwr_psy_properties *p;
  5989. + struct spwr_battery_device *bat;
  5990. + int status;
  5991. +
  5992. + p = ssam_device_get_match_data(sdev);
  5993. + if (!p)
  5994. + return -ENODEV;
  5995. +
  5996. + bat = devm_kzalloc(&sdev->dev, sizeof(*bat), GFP_KERNEL);
  5997. + if (!bat)
  5998. + return -ENOMEM;
  5999. +
  6000. + spwr_battery_init(bat, sdev, p->registry, p->name);
  6001. + ssam_device_set_drvdata(sdev, bat);
  6002. +
  6003. + status = spwr_battery_register(bat);
  6004. + if (status)
  6005. + spwr_battery_destroy(bat);
  6006. +
  6007. + return status;
  6008. +}
  6009. +
  6010. +static void surface_battery_remove(struct ssam_device *sdev)
  6011. +{
  6012. + struct spwr_battery_device *bat = ssam_device_get_drvdata(sdev);
  6013. +
  6014. + spwr_battery_unregister(bat);
  6015. + spwr_battery_destroy(bat);
  6016. +}
  6017. +
  6018. +static const struct spwr_psy_properties spwr_psy_props_bat1 = {
  6019. + .name = "BAT1",
  6020. + .registry = SSAM_EVENT_REGISTRY_SAM,
  6021. +};
  6022. +
  6023. +static const struct spwr_psy_properties spwr_psy_props_bat2_sb3 = {
  6024. + .name = "BAT2",
  6025. + .registry = SSAM_EVENT_REGISTRY_KIP,
  6026. +};
  6027. +
  6028. +static const struct ssam_device_id surface_battery_match[] = {
  6029. + { SSAM_SDEV(BAT, 0x01, 0x01, 0x00), (unsigned long)&spwr_psy_props_bat1 },
  6030. + { SSAM_SDEV(BAT, 0x02, 0x01, 0x00), (unsigned long)&spwr_psy_props_bat2_sb3 },
  6031. + { },
  6032. +};
  6033. +MODULE_DEVICE_TABLE(ssam, surface_battery_match);
  6034. +
  6035. +static struct ssam_device_driver surface_battery_driver = {
  6036. + .probe = surface_battery_probe,
  6037. + .remove = surface_battery_remove,
  6038. + .match_table = surface_battery_match,
  6039. + .driver = {
  6040. + .name = "surface_battery",
  6041. + .pm = &surface_battery_pm_ops,
  6042. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  6043. + },
  6044. +};
  6045. +
  6046. +
  6047. +/* -- AC driver. ------------------------------------------------------------ */
  6048. +
  6049. +static int surface_ac_probe(struct ssam_device *sdev)
  6050. +{
  6051. + const struct spwr_psy_properties *p;
  6052. + struct spwr_ac_device *ac;
  6053. + int status;
  6054. +
  6055. + p = ssam_device_get_match_data(sdev);
  6056. + if (!p)
  6057. + return -ENODEV;
  6058. +
  6059. + ac = devm_kzalloc(&sdev->dev, sizeof(*ac), GFP_KERNEL);
  6060. + if (!ac)
  6061. + return -ENOMEM;
  6062. +
  6063. + spwr_ac_init(ac, sdev, p->registry, p->name);
  6064. + ssam_device_set_drvdata(sdev, ac);
  6065. +
  6066. + status = spwr_ac_register(ac);
  6067. + if (status)
  6068. + spwr_ac_destroy(ac);
  6069. +
  6070. + return status;
  6071. +}
  6072. +
  6073. +static void surface_ac_remove(struct ssam_device *sdev)
  6074. +{
  6075. + struct spwr_ac_device *ac = ssam_device_get_drvdata(sdev);
  6076. +
  6077. + spwr_ac_unregister(ac);
  6078. + spwr_ac_destroy(ac);
  6079. +}
  6080. +
  6081. +static const struct spwr_psy_properties spwr_psy_props_adp1 = {
  6082. + .name = "ADP1",
  6083. + .registry = SSAM_EVENT_REGISTRY_SAM,
  6084. +};
  6085. +
  6086. +static const struct ssam_device_id surface_ac_match[] = {
  6087. + { SSAM_SDEV(BAT, 0x01, 0x01, 0x01), (unsigned long)&spwr_psy_props_adp1 },
  6088. + { },
  6089. +};
  6090. +MODULE_DEVICE_TABLE(ssam, surface_ac_match);
  6091. +
  6092. +static struct ssam_device_driver surface_ac_driver = {
  6093. + .probe = surface_ac_probe,
  6094. + .remove = surface_ac_remove,
  6095. + .match_table = surface_ac_match,
  6096. + .driver = {
  6097. + .name = "surface_ac",
  6098. + .pm = &surface_ac_pm_ops,
  6099. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  6100. + },
  6101. +};
  6102. +
  6103. +
  6104. +/* -- Module setup. --------------------------------------------------------- */
  6105. +
  6106. +static int __init surface_battery_init(void)
  6107. +{
  6108. + int status;
  6109. +
  6110. + status = ssam_device_driver_register(&surface_battery_driver);
  6111. + if (status)
  6112. + return status;
  6113. +
  6114. + status = ssam_device_driver_register(&surface_ac_driver);
  6115. + if (status)
  6116. + ssam_device_driver_unregister(&surface_battery_driver);
  6117. +
  6118. + return status;
  6119. +}
  6120. +module_init(surface_battery_init);
  6121. +
  6122. +static void __exit surface_battery_exit(void)
  6123. +{
  6124. + ssam_device_driver_unregister(&surface_battery_driver);
  6125. + ssam_device_driver_unregister(&surface_ac_driver);
  6126. +}
  6127. +module_exit(surface_battery_exit);
  6128. +
  6129. +MODULE_AUTHOR("Maximilian Luz <luzmaximilian@gmail.com>");
  6130. +MODULE_DESCRIPTION("Battery/AC driver for Surface System Aggregator Module");
  6131. +MODULE_LICENSE("GPL");
  6132. diff --git a/drivers/misc/surface_aggregator/clients/surface_dtx.c b/drivers/misc/surface_aggregator/clients/surface_dtx.c
  6133. new file mode 100644
  6134. index 000000000000..346b54848b8f
  6135. --- /dev/null
  6136. +++ b/drivers/misc/surface_aggregator/clients/surface_dtx.c
  6137. @@ -0,0 +1,1279 @@
  6138. +// SPDX-License-Identifier: GPL-2.0+
  6139. +/*
  6140. + * Surface Book (gen. 2 and later) detachment system (DTX) driver.
  6141. + *
  6142. + * Provides a user-space interface to properly handle clipboard/tablet
  6143. + * (containing screen and processor) detachment from the base of the device
  6144. + * (containing the keyboard and optionally a discrete GPU). Allows to
  6145. + * acknowledge (to speed things up), abort (e.g. in case the dGPU is stil in
  6146. + * use), or request detachment via user-space.
  6147. + *
  6148. + * Copyright (C) 2019-2020 Maximilian Luz <luzmaximilian@gmail.com>
  6149. + */
  6150. +
  6151. +#include <linux/acpi.h>
  6152. +#include <linux/delay.h>
  6153. +#include <linux/fs.h>
  6154. +#include <linux/input.h>
  6155. +#include <linux/ioctl.h>
  6156. +#include <linux/kernel.h>
  6157. +#include <linux/kfifo.h>
  6158. +#include <linux/kref.h>
  6159. +#include <linux/miscdevice.h>
  6160. +#include <linux/module.h>
  6161. +#include <linux/platform_device.h>
  6162. +#include <linux/poll.h>
  6163. +#include <linux/rwsem.h>
  6164. +#include <linux/slab.h>
  6165. +#include <linux/spinlock.h>
  6166. +
  6167. +#include <linux/surface_aggregator/controller.h>
  6168. +#include <linux/surface_aggregator/device.h>
  6169. +#include <linux/surface_aggregator/dtx.h>
  6170. +
  6171. +
  6172. +/* -- SSAM interface. ------------------------------------------------------- */
  6173. +
  6174. +enum sam_event_cid_bas {
  6175. + SAM_EVENT_CID_DTX_CONNECTION = 0x0c,
  6176. + SAM_EVENT_CID_DTX_REQUEST = 0x0e,
  6177. + SAM_EVENT_CID_DTX_CANCEL = 0x0f,
  6178. + SAM_EVENT_CID_DTX_LATCH_STATUS = 0x11,
  6179. +};
  6180. +
  6181. +enum ssam_bas_base_state {
  6182. + SSAM_BAS_BASE_STATE_DETACH_SUCCESS = 0x00,
  6183. + SSAM_BAS_BASE_STATE_ATTACHED = 0x01,
  6184. + SSAM_BAS_BASE_STATE_NOT_FEASIBLE = 0x02,
  6185. +};
  6186. +
  6187. +enum ssam_bas_latch_status {
  6188. + SSAM_BAS_LATCH_STATUS_CLOSED = 0x00,
  6189. + SSAM_BAS_LATCH_STATUS_OPENED = 0x01,
  6190. + SSAM_BAS_LATCH_STATUS_FAILED_TO_OPEN = 0x02,
  6191. + SSAM_BAS_LATCH_STATUS_FAILED_TO_REMAIN_OPEN = 0x03,
  6192. + SSAM_BAS_LATCH_STATUS_FAILED_TO_CLOSE = 0x04,
  6193. +};
  6194. +
  6195. +enum ssam_bas_cancel_reason {
  6196. + SSAM_BAS_CANCEL_REASON_NOT_FEASIBLE = 0x00, // low battery
  6197. + SSAM_BAS_CANCEL_REASON_TIMEOUT = 0x02,
  6198. + SSAM_BAS_CANCEL_REASON_FAILED_TO_OPEN = 0x03,
  6199. + SSAM_BAS_CANCEL_REASON_FAILED_TO_REMAIN_OPEN = 0x04,
  6200. + SSAM_BAS_CANCEL_REASON_FAILED_TO_CLOSE = 0x05,
  6201. +};
  6202. +
  6203. +struct ssam_bas_base_info {
  6204. + u8 state;
  6205. + u8 base_id;
  6206. +} __packed;
  6207. +
  6208. +static_assert(sizeof(struct ssam_bas_base_info) == 2);
  6209. +
  6210. +static SSAM_DEFINE_SYNC_REQUEST_N(ssam_bas_latch_lock, {
  6211. + .target_category = SSAM_SSH_TC_BAS,
  6212. + .target_id = 0x01,
  6213. + .command_id = 0x06,
  6214. + .instance_id = 0x00,
  6215. +});
  6216. +
  6217. +static SSAM_DEFINE_SYNC_REQUEST_N(ssam_bas_latch_unlock, {
  6218. + .target_category = SSAM_SSH_TC_BAS,
  6219. + .target_id = 0x01,
  6220. + .command_id = 0x07,
  6221. + .instance_id = 0x00,
  6222. +});
  6223. +
  6224. +static SSAM_DEFINE_SYNC_REQUEST_N(ssam_bas_latch_request, {
  6225. + .target_category = SSAM_SSH_TC_BAS,
  6226. + .target_id = 0x01,
  6227. + .command_id = 0x08,
  6228. + .instance_id = 0x00,
  6229. +});
  6230. +
  6231. +static SSAM_DEFINE_SYNC_REQUEST_N(ssam_bas_latch_confirm, {
  6232. + .target_category = SSAM_SSH_TC_BAS,
  6233. + .target_id = 0x01,
  6234. + .command_id = 0x09,
  6235. + .instance_id = 0x00,
  6236. +});
  6237. +
  6238. +static SSAM_DEFINE_SYNC_REQUEST_N(ssam_bas_latch_heartbeat, {
  6239. + .target_category = SSAM_SSH_TC_BAS,
  6240. + .target_id = 0x01,
  6241. + .command_id = 0x0a,
  6242. + .instance_id = 0x00,
  6243. +});
  6244. +
  6245. +static SSAM_DEFINE_SYNC_REQUEST_N(ssam_bas_latch_cancel, {
  6246. + .target_category = SSAM_SSH_TC_BAS,
  6247. + .target_id = 0x01,
  6248. + .command_id = 0x0b,
  6249. + .instance_id = 0x00,
  6250. +});
  6251. +
  6252. +static SSAM_DEFINE_SYNC_REQUEST_R(ssam_bas_get_base, struct ssam_bas_base_info, {
  6253. + .target_category = SSAM_SSH_TC_BAS,
  6254. + .target_id = 0x01,
  6255. + .command_id = 0x0c,
  6256. + .instance_id = 0x00,
  6257. +});
  6258. +
  6259. +static SSAM_DEFINE_SYNC_REQUEST_R(ssam_bas_get_device_mode, u8, {
  6260. + .target_category = SSAM_SSH_TC_BAS,
  6261. + .target_id = 0x01,
  6262. + .command_id = 0x0d,
  6263. + .instance_id = 0x00,
  6264. +});
  6265. +
  6266. +static SSAM_DEFINE_SYNC_REQUEST_R(ssam_bas_get_latch_status, u8, {
  6267. + .target_category = SSAM_SSH_TC_BAS,
  6268. + .target_id = 0x01,
  6269. + .command_id = 0x11,
  6270. + .instance_id = 0x00,
  6271. +});
  6272. +
  6273. +
  6274. +/* -- Main structures. ------------------------------------------------------ */
  6275. +
  6276. +enum sdtx_device_state {
  6277. + SDTX_DEVICE_SHUTDOWN_BIT = BIT(0),
  6278. + SDTX_DEVICE_DIRTY_BASE_BIT = BIT(1),
  6279. + SDTX_DEVICE_DIRTY_MODE_BIT = BIT(2),
  6280. + SDTX_DEVICE_DIRTY_LATCH_BIT = BIT(3),
  6281. +};
  6282. +
  6283. +struct sdtx_device {
  6284. + struct kref kref;
  6285. + struct rw_semaphore lock;
  6286. +
  6287. + struct device *dev;
  6288. + struct ssam_controller *ctrl;
  6289. + unsigned long flags;
  6290. +
  6291. + struct miscdevice mdev;
  6292. + wait_queue_head_t waitq;
  6293. + struct mutex write_lock;
  6294. + struct rw_semaphore client_lock;
  6295. + struct list_head client_list;
  6296. +
  6297. + struct delayed_work state_work;
  6298. + struct {
  6299. + struct ssam_bas_base_info base;
  6300. + u8 device_mode;
  6301. + u8 latch_status;
  6302. + } state;
  6303. +
  6304. + struct delayed_work mode_work;
  6305. + struct input_dev *mode_switch;
  6306. +
  6307. + struct ssam_event_notifier notif;
  6308. +};
  6309. +
  6310. +enum sdtx_client_state {
  6311. + SDTX_CLIENT_EVENTS_ENABLED_BIT = BIT(0),
  6312. +};
  6313. +
  6314. +struct sdtx_client {
  6315. + struct sdtx_device *ddev;
  6316. + struct list_head node;
  6317. + unsigned long flags;
  6318. +
  6319. + struct fasync_struct *fasync;
  6320. +
  6321. + struct mutex read_lock;
  6322. + DECLARE_KFIFO(buffer, u8, 512);
  6323. +};
  6324. +
  6325. +static void __sdtx_device_release(struct kref *kref)
  6326. +{
  6327. + struct sdtx_device *ddev = container_of(kref, struct sdtx_device, kref);
  6328. +
  6329. + mutex_destroy(&ddev->write_lock);
  6330. + kfree(ddev);
  6331. +}
  6332. +
  6333. +static struct sdtx_device *sdtx_device_get(struct sdtx_device *ddev)
  6334. +{
  6335. + if (ddev)
  6336. + kref_get(&ddev->kref);
  6337. +
  6338. + return ddev;
  6339. +}
  6340. +
  6341. +static void sdtx_device_put(struct sdtx_device *ddev)
  6342. +{
  6343. + if (ddev)
  6344. + kref_put(&ddev->kref, __sdtx_device_release);
  6345. +}
  6346. +
  6347. +
  6348. +/* -- Firmware value translations. ------------------------------------------ */
  6349. +
  6350. +static u16 sdtx_translate_base_state(struct sdtx_device *ddev, u8 state)
  6351. +{
  6352. + switch (state) {
  6353. + case SSAM_BAS_BASE_STATE_ATTACHED:
  6354. + return SDTX_BASE_ATTACHED;
  6355. +
  6356. + case SSAM_BAS_BASE_STATE_DETACH_SUCCESS:
  6357. + return SDTX_BASE_DETACHED;
  6358. +
  6359. + case SSAM_BAS_BASE_STATE_NOT_FEASIBLE:
  6360. + return SDTX_DETACH_NOT_FEASIBLE;
  6361. +
  6362. + default:
  6363. + dev_err(ddev->dev, "unknown base state: 0x%02x\n", state);
  6364. + return SDTX_UNKNOWN(state);
  6365. + }
  6366. +}
  6367. +
  6368. +static u16 sdtx_translate_latch_status(struct sdtx_device *ddev, u8 status)
  6369. +{
  6370. + switch (status) {
  6371. + case SSAM_BAS_LATCH_STATUS_CLOSED:
  6372. + return SDTX_LATCH_CLOSED;
  6373. +
  6374. + case SSAM_BAS_LATCH_STATUS_OPENED:
  6375. + return SDTX_LATCH_OPENED;
  6376. +
  6377. + case SSAM_BAS_LATCH_STATUS_FAILED_TO_OPEN:
  6378. + return SDTX_ERR_FAILED_TO_OPEN;
  6379. +
  6380. + case SSAM_BAS_LATCH_STATUS_FAILED_TO_REMAIN_OPEN:
  6381. + return SDTX_ERR_FAILED_TO_REMAIN_OPEN;
  6382. +
  6383. + case SSAM_BAS_LATCH_STATUS_FAILED_TO_CLOSE:
  6384. + return SDTX_ERR_FAILED_TO_CLOSE;
  6385. +
  6386. + default:
  6387. + dev_err(ddev->dev, "unknown latch status: 0x%02x\n", status);
  6388. + return SDTX_UNKNOWN(status);
  6389. + }
  6390. +}
  6391. +
  6392. +static u16 sdtx_translate_cancel_reason(struct sdtx_device *ddev, u8 reason)
  6393. +{
  6394. + switch (reason) {
  6395. + case SSAM_BAS_CANCEL_REASON_NOT_FEASIBLE:
  6396. + return SDTX_DETACH_NOT_FEASIBLE;
  6397. +
  6398. + case SSAM_BAS_CANCEL_REASON_TIMEOUT:
  6399. + return SDTX_DETACH_TIMEDOUT;
  6400. +
  6401. + case SSAM_BAS_CANCEL_REASON_FAILED_TO_OPEN:
  6402. + return SDTX_ERR_FAILED_TO_OPEN;
  6403. +
  6404. + case SSAM_BAS_CANCEL_REASON_FAILED_TO_REMAIN_OPEN:
  6405. + return SDTX_ERR_FAILED_TO_REMAIN_OPEN;
  6406. +
  6407. + case SSAM_BAS_CANCEL_REASON_FAILED_TO_CLOSE:
  6408. + return SDTX_ERR_FAILED_TO_CLOSE;
  6409. +
  6410. + default:
  6411. + dev_err(ddev->dev, "unknown cancel reason: 0x%02x\n", reason);
  6412. + return SDTX_UNKNOWN(reason);
  6413. + }
  6414. +}
  6415. +
  6416. +
  6417. +/* -- IOCTLs. --------------------------------------------------------------- */
  6418. +
  6419. +static int sdtx_ioctl_get_base_info(struct sdtx_device *ddev,
  6420. + struct sdtx_base_info __user *buf)
  6421. +{
  6422. + struct ssam_bas_base_info raw;
  6423. + struct sdtx_base_info info;
  6424. + int status;
  6425. +
  6426. + status = ssam_retry(ssam_bas_get_base, ddev->ctrl, &raw);
  6427. + if (status < 0)
  6428. + return status;
  6429. +
  6430. + info.state = sdtx_translate_base_state(ddev, raw.state);
  6431. + info.base_id = SDTX_BASE_TYPE_SSH(raw.base_id);
  6432. +
  6433. + if (copy_to_user(buf, &info, sizeof(info)))
  6434. + return -EFAULT;
  6435. +
  6436. + return 0;
  6437. +}
  6438. +
  6439. +static int sdtx_ioctl_get_device_mode(struct sdtx_device *ddev, u16 __user *buf)
  6440. +{
  6441. + u8 mode;
  6442. + int status;
  6443. +
  6444. + status = ssam_retry(ssam_bas_get_device_mode, ddev->ctrl, &mode);
  6445. + if (status < 0)
  6446. + return status;
  6447. +
  6448. + return put_user(mode, buf);
  6449. +}
  6450. +
  6451. +static int sdtx_ioctl_get_latch_status(struct sdtx_device *ddev, u16 __user *buf)
  6452. +{
  6453. + u8 latch;
  6454. + int status;
  6455. +
  6456. + status = ssam_retry(ssam_bas_get_latch_status, ddev->ctrl, &latch);
  6457. + if (status < 0)
  6458. + return status;
  6459. +
  6460. + return put_user(sdtx_translate_latch_status(ddev, latch), buf);
  6461. +}
  6462. +
  6463. +static long __surface_dtx_ioctl(struct sdtx_client *client, unsigned int cmd,
  6464. + unsigned long arg)
  6465. +{
  6466. + struct sdtx_device *ddev = client->ddev;
  6467. +
  6468. + switch (cmd) {
  6469. + case SDTX_IOCTL_EVENTS_ENABLE:
  6470. + set_bit(SDTX_CLIENT_EVENTS_ENABLED_BIT, &client->flags);
  6471. + return 0;
  6472. +
  6473. + case SDTX_IOCTL_EVENTS_DISABLE:
  6474. + clear_bit(SDTX_CLIENT_EVENTS_ENABLED_BIT, &client->flags);
  6475. + return 0;
  6476. +
  6477. + case SDTX_IOCTL_LATCH_LOCK:
  6478. + return ssam_retry(ssam_bas_latch_lock, ddev->ctrl);
  6479. +
  6480. + case SDTX_IOCTL_LATCH_UNLOCK:
  6481. + return ssam_retry(ssam_bas_latch_unlock, ddev->ctrl);
  6482. +
  6483. + case SDTX_IOCTL_LATCH_REQUEST:
  6484. + return ssam_retry(ssam_bas_latch_request, ddev->ctrl);
  6485. +
  6486. + case SDTX_IOCTL_LATCH_CONFIRM:
  6487. + return ssam_retry(ssam_bas_latch_confirm, ddev->ctrl);
  6488. +
  6489. + case SDTX_IOCTL_LATCH_HEARTBEAT:
  6490. + return ssam_retry(ssam_bas_latch_heartbeat, ddev->ctrl);
  6491. +
  6492. + case SDTX_IOCTL_LATCH_CANCEL:
  6493. + return ssam_retry(ssam_bas_latch_cancel, ddev->ctrl);
  6494. +
  6495. + case SDTX_IOCTL_GET_BASE_INFO:
  6496. + return sdtx_ioctl_get_base_info(ddev,
  6497. + (struct sdtx_base_info __user *)arg);
  6498. +
  6499. + case SDTX_IOCTL_GET_DEVICE_MODE:
  6500. + return sdtx_ioctl_get_device_mode(ddev, (u16 __user *)arg);
  6501. +
  6502. + case SDTX_IOCTL_GET_LATCH_STATUS:
  6503. + return sdtx_ioctl_get_latch_status(ddev, (u16 __user *)arg);
  6504. +
  6505. + default:
  6506. + return -EINVAL;
  6507. + }
  6508. +}
  6509. +
  6510. +static long surface_dtx_ioctl(struct file *file, unsigned int cmd,
  6511. + unsigned long arg)
  6512. +{
  6513. + struct sdtx_client *client = file->private_data;
  6514. + long status;
  6515. +
  6516. + if (down_read_killable(&client->ddev->lock))
  6517. + return -ERESTARTSYS;
  6518. +
  6519. + if (test_bit(SDTX_DEVICE_SHUTDOWN_BIT, &client->ddev->flags)) {
  6520. + up_read(&client->ddev->lock);
  6521. + return -ENODEV;
  6522. + }
  6523. +
  6524. + status = __surface_dtx_ioctl(client, cmd, arg);
  6525. +
  6526. + up_read(&client->ddev->lock);
  6527. + return status;
  6528. +}
  6529. +
  6530. +
  6531. +/* -- File operations. ------------------------------------------------------ */
  6532. +
  6533. +static int surface_dtx_open(struct inode *inode, struct file *file)
  6534. +{
  6535. + struct sdtx_device *ddev;
  6536. + struct sdtx_client *client;
  6537. +
  6538. + ddev = container_of(file->private_data, struct sdtx_device, mdev);
  6539. +
  6540. + // initialize client
  6541. + client = kzalloc(sizeof(*client), GFP_KERNEL);
  6542. + if (!client)
  6543. + return -ENOMEM;
  6544. +
  6545. + client->ddev = sdtx_device_get(ddev);
  6546. +
  6547. + INIT_LIST_HEAD(&client->node);
  6548. +
  6549. + mutex_init(&client->read_lock);
  6550. + INIT_KFIFO(client->buffer);
  6551. +
  6552. + file->private_data = client;
  6553. +
  6554. + // attach client
  6555. + down_write(&ddev->client_lock);
  6556. +
  6557. + // do not add a new client if the device has been shut down
  6558. + if (test_bit(SDTX_DEVICE_SHUTDOWN_BIT, &ddev->flags)) {
  6559. + up_write(&ddev->client_lock);
  6560. + sdtx_device_put(client->ddev);
  6561. + kfree(client);
  6562. + return -ENODEV;
  6563. + }
  6564. +
  6565. + list_add_tail(&client->node, &ddev->client_list);
  6566. + up_write(&ddev->client_lock);
  6567. +
  6568. + stream_open(inode, file);
  6569. + return 0;
  6570. +}
  6571. +
  6572. +static int surface_dtx_release(struct inode *inode, struct file *file)
  6573. +{
  6574. + struct sdtx_client *client = file->private_data;
  6575. +
  6576. + // detach client
  6577. + down_write(&client->ddev->client_lock);
  6578. + list_del(&client->node);
  6579. + up_write(&client->ddev->client_lock);
  6580. +
  6581. + sdtx_device_put(client->ddev);
  6582. + mutex_destroy(&client->read_lock);
  6583. + kfree(client);
  6584. +
  6585. + return 0;
  6586. +}
  6587. +
  6588. +static ssize_t surface_dtx_read(struct file *file, char __user *buf,
  6589. + size_t count, loff_t *offs)
  6590. +{
  6591. + struct sdtx_client *client = file->private_data;
  6592. + struct sdtx_device *ddev = client->ddev;
  6593. + unsigned int copied;
  6594. + int status = 0;
  6595. +
  6596. + if (down_read_killable(&ddev->lock))
  6597. + return -ERESTARTSYS;
  6598. +
  6599. + // make sure we're not shut down
  6600. + if (test_bit(SDTX_DEVICE_SHUTDOWN_BIT, &ddev->flags)) {
  6601. + up_read(&ddev->lock);
  6602. + return -ENODEV;
  6603. + }
  6604. +
  6605. + do {
  6606. + // check availability, wait if necessary
  6607. + if (kfifo_is_empty(&client->buffer)) {
  6608. + up_read(&ddev->lock);
  6609. +
  6610. + if (file->f_flags & O_NONBLOCK)
  6611. + return -EAGAIN;
  6612. +
  6613. + status = wait_event_interruptible(ddev->waitq,
  6614. + !kfifo_is_empty(&client->buffer)
  6615. + || test_bit(SDTX_DEVICE_SHUTDOWN_BIT,
  6616. + &ddev->flags));
  6617. + if (status < 0)
  6618. + return status;
  6619. +
  6620. + if (down_read_killable(&client->ddev->lock))
  6621. + return -ERESTARTSYS;
  6622. +
  6623. + // need to check that we're not shut down again
  6624. + if (test_bit(SDTX_DEVICE_SHUTDOWN_BIT, &ddev->flags)) {
  6625. + up_read(&ddev->lock);
  6626. + return -ENODEV;
  6627. + }
  6628. + }
  6629. +
  6630. + // try to read from fifo
  6631. + if (mutex_lock_interruptible(&client->read_lock)) {
  6632. + up_read(&ddev->lock);
  6633. + return -ERESTARTSYS;
  6634. + }
  6635. +
  6636. + status = kfifo_to_user(&client->buffer, buf, count, &copied);
  6637. + mutex_unlock(&client->read_lock);
  6638. +
  6639. + if (status < 0) {
  6640. + up_read(&ddev->lock);
  6641. + return status;
  6642. + }
  6643. +
  6644. + // we might not have gotten anything, check this here
  6645. + if (copied == 0 && (file->f_flags & O_NONBLOCK)) {
  6646. + up_read(&ddev->lock);
  6647. + return -EAGAIN;
  6648. + }
  6649. + } while (copied == 0);
  6650. +
  6651. + up_read(&ddev->lock);
  6652. + return copied;
  6653. +}
  6654. +
  6655. +static __poll_t surface_dtx_poll(struct file *file, struct poll_table_struct *pt)
  6656. +{
  6657. + struct sdtx_client *client = file->private_data;
  6658. + __poll_t events = 0;
  6659. +
  6660. + if (down_read_killable(&client->ddev->lock))
  6661. + return -ERESTARTSYS;
  6662. +
  6663. + if (test_bit(SDTX_DEVICE_SHUTDOWN_BIT, &client->ddev->flags)) {
  6664. + up_read(&client->ddev->lock);
  6665. + return EPOLLHUP | EPOLLERR;
  6666. + }
  6667. +
  6668. + poll_wait(file, &client->ddev->waitq, pt);
  6669. +
  6670. + if (!kfifo_is_empty(&client->buffer))
  6671. + events |= EPOLLIN | EPOLLRDNORM;
  6672. +
  6673. + up_read(&client->ddev->lock);
  6674. + return events;
  6675. +}
  6676. +
  6677. +static int surface_dtx_fasync(int fd, struct file *file, int on)
  6678. +{
  6679. + struct sdtx_client *client = file->private_data;
  6680. +
  6681. + return fasync_helper(fd, file, on, &client->fasync);
  6682. +}
  6683. +
  6684. +static const struct file_operations surface_dtx_fops = {
  6685. + .owner = THIS_MODULE,
  6686. + .open = surface_dtx_open,
  6687. + .release = surface_dtx_release,
  6688. + .read = surface_dtx_read,
  6689. + .poll = surface_dtx_poll,
  6690. + .fasync = surface_dtx_fasync,
  6691. + .unlocked_ioctl = surface_dtx_ioctl,
  6692. + .compat_ioctl = surface_dtx_ioctl,
  6693. + .llseek = no_llseek,
  6694. +};
  6695. +
  6696. +
  6697. +/* -- Event handling/forwarding. -------------------------------------------- */
  6698. +
  6699. +/*
  6700. + * The device operation mode is not immediately updated on the EC when the
  6701. + * base has been connected, i.e. querying the device mode inside the
  6702. + * connection event callback yields an outdated value. Thus, we can only
  6703. + * determine the new tablet-mode switch and device mode values after some
  6704. + * time.
  6705. + *
  6706. + * These delays have been chosen by experimenting. We first delay on connect
  6707. + * events, then check and validate the device mode against the base state and
  6708. + * if invalid delay again by the "recheck" delay.
  6709. + */
  6710. +#define SDTX_DEVICE_MODE_DELAY_CONNECT msecs_to_jiffies(100)
  6711. +#define SDTX_DEVICE_MODE_DELAY_RECHECK msecs_to_jiffies(100)
  6712. +
  6713. +static void sdtx_update_device_mode(struct sdtx_device *ddev, unsigned long delay);
  6714. +
  6715. +
  6716. +struct sdtx_status_event {
  6717. + struct sdtx_event e;
  6718. + __u16 v;
  6719. +} __packed;
  6720. +
  6721. +struct sdtx_base_info_event {
  6722. + struct sdtx_event e;
  6723. + struct sdtx_base_info v;
  6724. +} __packed;
  6725. +
  6726. +union sdtx_generic_event {
  6727. + struct sdtx_event common;
  6728. + struct sdtx_status_event status;
  6729. + struct sdtx_base_info_event base;
  6730. +};
  6731. +
  6732. +/* Must be executed with ddev->write_lock held. */
  6733. +static void sdtx_push_event(struct sdtx_device *ddev, struct sdtx_event *evt)
  6734. +{
  6735. + const size_t len = sizeof(struct sdtx_event) + evt->length;
  6736. + struct sdtx_client *client;
  6737. +
  6738. + down_read(&ddev->client_lock);
  6739. + list_for_each_entry(client, &ddev->client_list, node) {
  6740. + if (!test_bit(SDTX_CLIENT_EVENTS_ENABLED_BIT, &client->flags))
  6741. + continue;
  6742. +
  6743. + if (likely(kfifo_avail(&client->buffer) >= len))
  6744. + kfifo_in(&client->buffer, (const u8 *)evt, len);
  6745. + else
  6746. + dev_warn(ddev->dev, "event buffer overrun\n");
  6747. +
  6748. + kill_fasync(&client->fasync, SIGIO, POLL_IN);
  6749. + }
  6750. + up_read(&ddev->client_lock);
  6751. +
  6752. + wake_up_interruptible(&ddev->waitq);
  6753. +}
  6754. +
  6755. +static u32 sdtx_notifier(struct ssam_event_notifier *nf,
  6756. + const struct ssam_event *in)
  6757. +{
  6758. + struct sdtx_device *ddev = container_of(nf, struct sdtx_device, notif);
  6759. + union sdtx_generic_event event;
  6760. + size_t len;
  6761. +
  6762. + // validate event payload length
  6763. + switch (in->command_id) {
  6764. + case SAM_EVENT_CID_DTX_CONNECTION:
  6765. + len = 2;
  6766. + break;
  6767. +
  6768. + case SAM_EVENT_CID_DTX_REQUEST:
  6769. + len = 0;
  6770. + break;
  6771. +
  6772. + case SAM_EVENT_CID_DTX_CANCEL:
  6773. + len = 1;
  6774. + break;
  6775. +
  6776. + case SAM_EVENT_CID_DTX_LATCH_STATUS:
  6777. + len = 1;
  6778. + break;
  6779. +
  6780. + default:
  6781. + return 0;
  6782. + };
  6783. +
  6784. + if (in->length != len) {
  6785. + dev_err(ddev->dev, "unexpected payload size for event 0x%02x: "
  6786. + "got %u, expected %zu", in->command_id, in->length, len);
  6787. + return 0;
  6788. + }
  6789. +
  6790. + mutex_lock(&ddev->write_lock);
  6791. +
  6792. + // translate event
  6793. + switch (in->command_id) {
  6794. + case SAM_EVENT_CID_DTX_CONNECTION:
  6795. + clear_bit(SDTX_DEVICE_DIRTY_BASE_BIT, &ddev->flags);
  6796. +
  6797. + // if state has not changed: do not send new event
  6798. + if (ddev->state.base.state == in->data[0]
  6799. + && ddev->state.base.base_id == in->data[1])
  6800. + goto out;
  6801. +
  6802. + ddev->state.base.state = in->data[0];
  6803. + ddev->state.base.base_id = in->data[1];
  6804. +
  6805. + event.base.e.length = sizeof(struct sdtx_base_info);
  6806. + event.base.e.code = SDTX_EVENT_BASE_CONNECTION;
  6807. + event.base.v.state = sdtx_translate_base_state(ddev, in->data[0]);
  6808. + event.base.v.base_id = SDTX_BASE_TYPE_SSH(in->data[1]);
  6809. + break;
  6810. +
  6811. + case SAM_EVENT_CID_DTX_REQUEST:
  6812. + event.common.code = SDTX_EVENT_REQUEST;
  6813. + event.common.length = 0;
  6814. + break;
  6815. +
  6816. + case SAM_EVENT_CID_DTX_CANCEL:
  6817. + event.status.e.length = sizeof(u16);
  6818. + event.status.e.code = SDTX_EVENT_CANCEL;
  6819. + event.status.v = sdtx_translate_cancel_reason(ddev, in->data[0]);
  6820. + break;
  6821. +
  6822. + case SAM_EVENT_CID_DTX_LATCH_STATUS:
  6823. + clear_bit(SDTX_DEVICE_DIRTY_LATCH_BIT, &ddev->flags);
  6824. +
  6825. + // if state has not changed: do not send new event
  6826. + if (ddev->state.latch_status == in->data[0])
  6827. + goto out;
  6828. +
  6829. + ddev->state.latch_status = in->data[0];
  6830. +
  6831. + event.status.e.length = sizeof(u16);
  6832. + event.status.e.code = SDTX_EVENT_LATCH_STATUS;
  6833. + event.status.v = sdtx_translate_latch_status(ddev, in->data[0]);
  6834. + break;
  6835. + }
  6836. +
  6837. + sdtx_push_event(ddev, &event.common);
  6838. +
  6839. + // update device mode on base connection change
  6840. + if (in->command_id == SAM_EVENT_CID_DTX_CONNECTION) {
  6841. + unsigned long delay;
  6842. +
  6843. + delay = in->data[0] ? SDTX_DEVICE_MODE_DELAY_CONNECT : 0;
  6844. + sdtx_update_device_mode(ddev, delay);
  6845. + }
  6846. +
  6847. +out:
  6848. + mutex_unlock(&ddev->write_lock);
  6849. + return SSAM_NOTIF_HANDLED;
  6850. +}
  6851. +
  6852. +
  6853. +/* -- State update functions. ----------------------------------------------- */
  6854. +
  6855. +static bool sdtx_device_mode_invalid(u8 mode, u8 base_state)
  6856. +{
  6857. + return ((base_state == SSAM_BAS_BASE_STATE_ATTACHED)
  6858. + && (mode == SDTX_DEVICE_MODE_TABLET))
  6859. + || ((base_state == SSAM_BAS_BASE_STATE_DETACH_SUCCESS)
  6860. + && (mode != SDTX_DEVICE_MODE_TABLET));
  6861. +}
  6862. +
  6863. +static void sdtx_device_mode_workfn(struct work_struct *work)
  6864. +{
  6865. + struct sdtx_device *ddev;
  6866. + struct sdtx_status_event event;
  6867. + struct ssam_bas_base_info base;
  6868. + int status, tablet;
  6869. + u8 mode;
  6870. +
  6871. + ddev = container_of(work, struct sdtx_device, mode_work.work);
  6872. +
  6873. + // get operation mode
  6874. + status = ssam_retry(ssam_bas_get_device_mode, ddev->ctrl, &mode);
  6875. + if (status) {
  6876. + dev_err(ddev->dev, "failed to get device mode: %d\n", status);
  6877. + return;
  6878. + }
  6879. +
  6880. + // get base info
  6881. + status = ssam_retry(ssam_bas_get_base, ddev->ctrl, &base);
  6882. + if (status) {
  6883. + dev_err(ddev->dev, "failed to get base info: %d\n", status);
  6884. + return;
  6885. + }
  6886. +
  6887. + /*
  6888. + * In some cases (specifically when attaching the base), the device
  6889. + * mode isn't updated right away. Thus we check if the device mode
  6890. + * makes sense for the given base state and try again later if it
  6891. + * doesn't.
  6892. + */
  6893. + if (sdtx_device_mode_invalid(mode, base.state)) {
  6894. + dev_dbg(ddev->dev, "device mode is invalid, trying again\n");
  6895. + sdtx_update_device_mode(ddev, SDTX_DEVICE_MODE_DELAY_RECHECK);
  6896. + return;
  6897. + }
  6898. +
  6899. + mutex_lock(&ddev->write_lock);
  6900. + clear_bit(SDTX_DEVICE_DIRTY_MODE_BIT, &ddev->flags);
  6901. +
  6902. + // avoid sending duplicate device-mode events
  6903. + if (ddev->state.device_mode == mode) {
  6904. + mutex_unlock(&ddev->write_lock);
  6905. + return;
  6906. + }
  6907. +
  6908. + ddev->state.device_mode = mode;
  6909. +
  6910. + event.e.length = sizeof(u16);
  6911. + event.e.code = SDTX_EVENT_DEVICE_MODE;
  6912. + event.v = mode;
  6913. +
  6914. + sdtx_push_event(ddev, &event.e);
  6915. +
  6916. + // send SW_TABLET_MODE event
  6917. + tablet = mode != SDTX_DEVICE_MODE_LAPTOP;
  6918. + input_report_switch(ddev->mode_switch, SW_TABLET_MODE, tablet);
  6919. + input_sync(ddev->mode_switch);
  6920. +
  6921. + mutex_unlock(&ddev->write_lock);
  6922. +}
  6923. +
  6924. +static void sdtx_update_device_mode(struct sdtx_device *ddev, unsigned long delay)
  6925. +{
  6926. + schedule_delayed_work(&ddev->mode_work, delay);
  6927. +}
  6928. +
  6929. +
  6930. +static void __sdtx_device_state_update_base(struct sdtx_device *ddev,
  6931. + struct ssam_bas_base_info info)
  6932. +{
  6933. + struct sdtx_base_info_event event;
  6934. +
  6935. + // prevent duplicate events
  6936. + if (ddev->state.base.state == info.state
  6937. + && ddev->state.base.base_id == info.base_id)
  6938. + return;
  6939. +
  6940. + ddev->state.base = info;
  6941. +
  6942. + event.e.length = sizeof(struct sdtx_base_info);
  6943. + event.e.code = SDTX_EVENT_BASE_CONNECTION;
  6944. + event.v.state = sdtx_translate_base_state(ddev, info.state);
  6945. + event.v.base_id = SDTX_BASE_TYPE_SSH(info.base_id);
  6946. +
  6947. + sdtx_push_event(ddev, &event.e);
  6948. +}
  6949. +
  6950. +static void __sdtx_device_state_update_mode(struct sdtx_device *ddev, u8 mode)
  6951. +{
  6952. + struct sdtx_status_event event;
  6953. + int tablet;
  6954. +
  6955. + /*
  6956. + * Note: This function must be called after updating the base state
  6957. + * via __sdtx_device_state_update_base(), as we rely on the updated
  6958. + * base state value in the validity check below.
  6959. + */
  6960. +
  6961. + if (sdtx_device_mode_invalid(mode, ddev->state.base.state)) {
  6962. + dev_dbg(ddev->dev, "device mode is invalid, trying again\n");
  6963. + sdtx_update_device_mode(ddev, SDTX_DEVICE_MODE_DELAY_RECHECK);
  6964. + return;
  6965. + }
  6966. +
  6967. + // prevent duplicate events
  6968. + if (ddev->state.device_mode == mode)
  6969. + return;
  6970. +
  6971. + ddev->state.device_mode = mode;
  6972. +
  6973. + // send event
  6974. + event.e.length = sizeof(u16);
  6975. + event.e.code = SDTX_EVENT_DEVICE_MODE;
  6976. + event.v = mode;
  6977. +
  6978. + sdtx_push_event(ddev, &event.e);
  6979. +
  6980. + // send SW_TABLET_MODE event
  6981. + tablet = mode != SDTX_DEVICE_MODE_LAPTOP;
  6982. + input_report_switch(ddev->mode_switch, SW_TABLET_MODE, tablet);
  6983. + input_sync(ddev->mode_switch);
  6984. +}
  6985. +
  6986. +static void __sdtx_device_state_update_latch(struct sdtx_device *ddev, u8 status)
  6987. +{
  6988. + struct sdtx_status_event event;
  6989. +
  6990. + // prevent duplicate events
  6991. + if (ddev->state.latch_status == status)
  6992. + return;
  6993. +
  6994. + ddev->state.latch_status = status;
  6995. +
  6996. + event.e.length = sizeof(struct sdtx_base_info);
  6997. + event.e.code = SDTX_EVENT_BASE_CONNECTION;
  6998. + event.v = sdtx_translate_latch_status(ddev, status);
  6999. +
  7000. + sdtx_push_event(ddev, &event.e);
  7001. +}
  7002. +
  7003. +static void sdtx_device_state_workfn(struct work_struct *work)
  7004. +{
  7005. + struct sdtx_device *ddev;
  7006. + struct ssam_bas_base_info base;
  7007. + u8 mode, latch;
  7008. + int status;
  7009. +
  7010. + ddev = container_of(work, struct sdtx_device, state_work.work);
  7011. +
  7012. + // mark everyting as dirty
  7013. + set_bit(SDTX_DEVICE_DIRTY_BASE_BIT, &ddev->flags);
  7014. + set_bit(SDTX_DEVICE_DIRTY_MODE_BIT, &ddev->flags);
  7015. + set_bit(SDTX_DEVICE_DIRTY_LATCH_BIT, &ddev->flags);
  7016. +
  7017. + /*
  7018. + * Ensure that the state gets marked as dirty before continuing to
  7019. + * query it. Necessary to ensure that clear_bit() calls in
  7020. + * sdtx_notifier() and sdtx_device_mode_workfn() actually clear these
  7021. + * bits if an event is received while updating the state here.
  7022. + */
  7023. + smp_mb__after_atomic();
  7024. +
  7025. + status = ssam_retry(ssam_bas_get_base, ddev->ctrl, &base);
  7026. + if (status) {
  7027. + dev_err(ddev->dev, "failed to get base state: %d\n", status);
  7028. + return;
  7029. + }
  7030. +
  7031. + status = ssam_retry(ssam_bas_get_device_mode, ddev->ctrl, &mode);
  7032. + if (status) {
  7033. + dev_err(ddev->dev, "failed to get device mode: %d\n", status);
  7034. + return;
  7035. + }
  7036. +
  7037. + status = ssam_retry(ssam_bas_get_latch_status, ddev->ctrl, &latch);
  7038. + if (status) {
  7039. + dev_err(ddev->dev, "failed to get latch status: %d\n", status);
  7040. + return;
  7041. + }
  7042. +
  7043. + mutex_lock(&ddev->write_lock);
  7044. +
  7045. + /*
  7046. + * If the respective dirty-bit has been cleared, an event has been
  7047. + * received, updating this state. The queried state may thus be out of
  7048. + * date. At this point, we can safely assume that the state provided
  7049. + * by the event is either up to date, or we're about to receive
  7050. + * another event updating it.
  7051. + */
  7052. +
  7053. + if (test_and_clear_bit(SDTX_DEVICE_DIRTY_BASE_BIT, &ddev->flags))
  7054. + __sdtx_device_state_update_base(ddev, base);
  7055. +
  7056. + if (test_and_clear_bit(SDTX_DEVICE_DIRTY_MODE_BIT, &ddev->flags))
  7057. + __sdtx_device_state_update_mode(ddev, mode);
  7058. +
  7059. + if (test_and_clear_bit(SDTX_DEVICE_DIRTY_LATCH_BIT, &ddev->flags))
  7060. + __sdtx_device_state_update_latch(ddev, latch);
  7061. +
  7062. + mutex_unlock(&ddev->write_lock);
  7063. +}
  7064. +
  7065. +static void sdtx_update_device_state(struct sdtx_device *ddev, unsigned long delay)
  7066. +{
  7067. + schedule_delayed_work(&ddev->state_work, delay);
  7068. +}
  7069. +
  7070. +
  7071. +/* -- Common device initialization. ----------------------------------------- */
  7072. +
  7073. +static int sdtx_device_init(struct sdtx_device *ddev, struct device *dev,
  7074. + struct ssam_controller *ctrl)
  7075. +{
  7076. + int status, tablet_mode;
  7077. +
  7078. + // basic initialization
  7079. + kref_init(&ddev->kref);
  7080. + ddev->dev = dev;
  7081. + ddev->ctrl = ctrl;
  7082. +
  7083. + ddev->mdev.minor = MISC_DYNAMIC_MINOR;
  7084. + ddev->mdev.name = "surface_dtx";
  7085. + ddev->mdev.nodename = "surface/dtx";
  7086. + ddev->mdev.fops = &surface_dtx_fops;
  7087. +
  7088. + ddev->notif.base.priority = 1;
  7089. + ddev->notif.base.fn = sdtx_notifier;
  7090. + ddev->notif.event.reg = SSAM_EVENT_REGISTRY_SAM;
  7091. + ddev->notif.event.id.target_category = SSAM_SSH_TC_BAS;
  7092. + ddev->notif.event.id.instance = 0;
  7093. + ddev->notif.event.mask = SSAM_EVENT_MASK_NONE;
  7094. + ddev->notif.event.flags = SSAM_EVENT_SEQUENCED;
  7095. +
  7096. + init_waitqueue_head(&ddev->waitq);
  7097. + mutex_init(&ddev->write_lock);
  7098. + init_rwsem(&ddev->client_lock);
  7099. + INIT_LIST_HEAD(&ddev->client_list);
  7100. +
  7101. + INIT_DELAYED_WORK(&ddev->mode_work, sdtx_device_mode_workfn);
  7102. + INIT_DELAYED_WORK(&ddev->state_work, sdtx_device_state_workfn);
  7103. +
  7104. + /*
  7105. + * Get current device state. We want to guarantee that events are only
  7106. + * sent when state actually changes. Thus we cannot use special
  7107. + * "uninitialized" values, as that would cause problems when manually
  7108. + * querying the state in surface_dtx_pm_complete(). I.e. we would not
  7109. + * be able to detect state changes there if no change event has been
  7110. + * received between driver initialization and first device suspension.
  7111. + *
  7112. + * Note that we also need to do this before registring the event
  7113. + * notifier, as that may access the state values.
  7114. + */
  7115. + status = ssam_retry(ssam_bas_get_base, ddev->ctrl, &ddev->state.base);
  7116. + if (status)
  7117. + return status;
  7118. +
  7119. + status = ssam_retry(ssam_bas_get_device_mode, ddev->ctrl,
  7120. + &ddev->state.device_mode);
  7121. + if (status)
  7122. + return status;
  7123. +
  7124. + status = ssam_retry(ssam_bas_get_latch_status, ddev->ctrl,
  7125. + &ddev->state.latch_status);
  7126. + if (status)
  7127. + return status;
  7128. +
  7129. + // set up tablet mode switch
  7130. + ddev->mode_switch = input_allocate_device();
  7131. + if (!ddev->mode_switch)
  7132. + return -ENOMEM;
  7133. +
  7134. + ddev->mode_switch->name = "Microsoft Surface DTX Device Mode Switch";
  7135. + ddev->mode_switch->phys = "ssam/01:11:01:00:00/input0";
  7136. + ddev->mode_switch->id.bustype = BUS_HOST;
  7137. + ddev->mode_switch->dev.parent = ddev->dev;
  7138. +
  7139. + tablet_mode = (ddev->state.device_mode != SDTX_DEVICE_MODE_LAPTOP);
  7140. + input_set_capability(ddev->mode_switch, EV_SW, SW_TABLET_MODE);
  7141. + input_report_switch(ddev->mode_switch, SW_TABLET_MODE, tablet_mode);
  7142. +
  7143. + status = input_register_device(ddev->mode_switch);
  7144. + if (status) {
  7145. + input_free_device(ddev->mode_switch);
  7146. + return status;
  7147. + }
  7148. +
  7149. + // set up event notifier
  7150. + status = ssam_notifier_register(ddev->ctrl, &ddev->notif);
  7151. + if (status)
  7152. + goto err_notif;
  7153. +
  7154. + // register miscdevice
  7155. + status = misc_register(&ddev->mdev);
  7156. + if (status)
  7157. + goto err_mdev;
  7158. +
  7159. + /*
  7160. + * Update device state in case it has changed between getting the
  7161. + * initial mode and registring the event notifier.
  7162. + */
  7163. + sdtx_update_device_state(ddev, 0);
  7164. + return 0;
  7165. +
  7166. +err_notif:
  7167. + ssam_notifier_unregister(ddev->ctrl, &ddev->notif);
  7168. + cancel_delayed_work_sync(&ddev->mode_work);
  7169. +err_mdev:
  7170. + input_unregister_device(ddev->mode_switch);
  7171. + return status;
  7172. +}
  7173. +
  7174. +static struct sdtx_device *sdtx_device_setup(struct device *dev,
  7175. + struct ssam_controller *ctrl)
  7176. +{
  7177. + struct sdtx_device *ddev;
  7178. + int status;
  7179. +
  7180. + ddev = kzalloc(sizeof(*ddev), GFP_KERNEL);
  7181. + if (!ddev)
  7182. + return ERR_PTR(-ENOMEM);
  7183. +
  7184. + status = sdtx_device_init(ddev, dev, ctrl);
  7185. + if (status) {
  7186. + kfree(ddev);
  7187. + return ERR_PTR(status);
  7188. + }
  7189. +
  7190. + return ddev;
  7191. +}
  7192. +
  7193. +static void sdtx_device_destroy(struct sdtx_device *ddev)
  7194. +{
  7195. + struct sdtx_client *client;
  7196. +
  7197. + // disable notifiers, prevent new events from arriving
  7198. + ssam_notifier_unregister(ddev->ctrl, &ddev->notif);
  7199. +
  7200. + // stop mode_work, prevent access to mode_switch
  7201. + cancel_delayed_work_sync(&ddev->mode_work);
  7202. +
  7203. + // stop state_work
  7204. + cancel_delayed_work_sync(&ddev->state_work);
  7205. +
  7206. + // with mode_work canceled, we can unregister the mode_switch
  7207. + input_unregister_device(ddev->mode_switch);
  7208. +
  7209. + /*
  7210. + * Mark device as shut-down. Prevent new clients from being added and
  7211. + * new operations from being executed.
  7212. + */
  7213. + set_bit(SDTX_DEVICE_SHUTDOWN_BIT, &ddev->flags);
  7214. +
  7215. + // wake up async clients
  7216. + down_write(&ddev->client_lock);
  7217. + list_for_each_entry(client, &ddev->client_list, node) {
  7218. + kill_fasync(&client->fasync, SIGIO, POLL_HUP);
  7219. + }
  7220. + up_write(&ddev->client_lock);
  7221. +
  7222. + // wake up blocking clients
  7223. + wake_up_interruptible(&ddev->waitq);
  7224. +
  7225. + /*
  7226. + * Wait for clients to finish their current operation. After this, the
  7227. + * controller and device references are guaranteed to be no longer in
  7228. + * use.
  7229. + */
  7230. + down_write(&ddev->lock);
  7231. + ddev->dev = NULL;
  7232. + ddev->ctrl = NULL;
  7233. + up_write(&ddev->lock);
  7234. +
  7235. + // finally remove the misc-device
  7236. + misc_deregister(&ddev->mdev);
  7237. +
  7238. + /*
  7239. + * We're now guaranteed that sdtx_device_open() won't be called any
  7240. + * more, so we can now drop out reference.
  7241. + */
  7242. + sdtx_device_put(ddev);
  7243. +}
  7244. +
  7245. +
  7246. +/* -- PM ops. --------------------------------------------------------------- */
  7247. +
  7248. +#ifdef CONFIG_PM_SLEEP
  7249. +
  7250. +static void surface_dtx_pm_complete(struct device *dev)
  7251. +{
  7252. + struct sdtx_device *ddev = dev_get_drvdata(dev);
  7253. +
  7254. + /*
  7255. + * Normally, the EC will store events while suspended (i.e. in
  7256. + * display-off state) and release them when resumed (i.e. transitioned
  7257. + * to display-on state). During hibernation, however, the EC will be
  7258. + * shut down and does not store events. Furthermore, events might be
  7259. + * dropped during prolonged suspension (it is scurrently unknown how
  7260. + * big this event buffer is and how it behaves on overruns).
  7261. + *
  7262. + * To prevent any problems, we update the device state here. We do
  7263. + * this delayed to ensure that any events sent by the EC directly
  7264. + * after resuming will be handled first. The delay below has been
  7265. + * chosen (experimentally), so that there should be ample time for
  7266. + * these events to be handled, before we check and, if necessary,
  7267. + * update the state.
  7268. + */
  7269. + sdtx_update_device_state(ddev, msecs_to_jiffies(1000));
  7270. +}
  7271. +
  7272. +static const struct dev_pm_ops surface_dtx_pm_ops = {
  7273. + .complete = surface_dtx_pm_complete,
  7274. +};
  7275. +
  7276. +#else /* CONFIG_PM_SLEEP */
  7277. +
  7278. +static const struct dev_pm_ops surface_dtx_pm_ops = {};
  7279. +
  7280. +#endif /* CONFIG_PM_SLEEP */
  7281. +
  7282. +
  7283. +/* -- Platform driver. ------------------------------------------------------ */
  7284. +
  7285. +static int surface_dtx_platform_probe(struct platform_device *pdev)
  7286. +{
  7287. + struct ssam_controller *ctrl;
  7288. + struct sdtx_device *ddev;
  7289. + int status;
  7290. +
  7291. + // link to EC
  7292. + status = ssam_client_bind(&pdev->dev, &ctrl);
  7293. + if (status)
  7294. + return status == -ENXIO ? -EPROBE_DEFER : status;
  7295. +
  7296. + ddev = sdtx_device_setup(&pdev->dev, ctrl);
  7297. + if (IS_ERR(ddev))
  7298. + return PTR_ERR(ddev);
  7299. +
  7300. + platform_set_drvdata(pdev, ddev);
  7301. + return 0;
  7302. +}
  7303. +
  7304. +static int surface_dtx_platform_remove(struct platform_device *pdev)
  7305. +{
  7306. + sdtx_device_destroy(platform_get_drvdata(pdev));
  7307. + return 0;
  7308. +}
  7309. +
  7310. +static const struct acpi_device_id surface_dtx_acpi_match[] = {
  7311. + { "MSHW0133", 0 },
  7312. + { },
  7313. +};
  7314. +MODULE_DEVICE_TABLE(acpi, surface_dtx_acpi_match);
  7315. +
  7316. +static struct platform_driver surface_dtx_platform_driver = {
  7317. + .probe = surface_dtx_platform_probe,
  7318. + .remove = surface_dtx_platform_remove,
  7319. + .driver = {
  7320. + .name = "surface_dtx_pltf",
  7321. + .acpi_match_table = surface_dtx_acpi_match,
  7322. + .pm = &surface_dtx_pm_ops,
  7323. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  7324. + },
  7325. +};
  7326. +
  7327. +
  7328. +/* -- SSAM device driver. --------------------------------------------------- */
  7329. +
  7330. +#ifdef CONFIG_SURFACE_AGGREGATOR_BUS
  7331. +
  7332. +static int surface_dtx_ssam_probe(struct ssam_device *sdev)
  7333. +{
  7334. + struct sdtx_device *ddev;
  7335. +
  7336. + ddev = sdtx_device_setup(&sdev->dev, sdev->ctrl);
  7337. + if (IS_ERR(ddev))
  7338. + return PTR_ERR(ddev);
  7339. +
  7340. + ssam_device_set_drvdata(sdev, ddev);
  7341. + return 0;
  7342. +}
  7343. +
  7344. +static void surface_dtx_ssam_remove(struct ssam_device *sdev)
  7345. +{
  7346. + sdtx_device_destroy(ssam_device_get_drvdata(sdev));
  7347. +}
  7348. +
  7349. +static const struct ssam_device_id surface_dtx_ssam_match[] = {
  7350. + { SSAM_SDEV(BAS, 0x01, 0x00, 0x00) },
  7351. + { },
  7352. +};
  7353. +MODULE_DEVICE_TABLE(ssam, surface_dtx_ssam_match);
  7354. +
  7355. +static struct ssam_device_driver surface_dtx_ssam_driver = {
  7356. + .probe = surface_dtx_ssam_probe,
  7357. + .remove = surface_dtx_ssam_remove,
  7358. + .match_table = surface_dtx_ssam_match,
  7359. + .driver = {
  7360. + .name = "surface_dtx",
  7361. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  7362. + },
  7363. +};
  7364. +
  7365. +static int ssam_dtx_driver_register(void)
  7366. +{
  7367. + return ssam_device_driver_register(&surface_dtx_ssam_driver);
  7368. +}
  7369. +
  7370. +static void ssam_dtx_driver_unregister(void)
  7371. +{
  7372. + ssam_device_driver_unregister(&surface_dtx_ssam_driver);
  7373. +}
  7374. +
  7375. +#else /* CONFIG_SURFACE_AGGREGATOR_BUS */
  7376. +
  7377. +static int ssam_dtx_driver_register(void)
  7378. +{
  7379. + return 0;
  7380. +}
  7381. +
  7382. +static void ssam_dtx_driver_unregister(void)
  7383. +{
  7384. +}
  7385. +
  7386. +#endif /* CONFIG_SURFACE_AGGREGATOR_BUS */
  7387. +
  7388. +
  7389. +/* -- Module setup. --------------------------------------------------------- */
  7390. +
  7391. +static int __init surface_dtx_init(void)
  7392. +{
  7393. + int status;
  7394. +
  7395. + status = ssam_dtx_driver_register();
  7396. + if (status)
  7397. + return status;
  7398. +
  7399. + status = platform_driver_register(&surface_dtx_platform_driver);
  7400. + if (status)
  7401. + ssam_dtx_driver_unregister();
  7402. +
  7403. + return status;
  7404. +}
  7405. +module_init(surface_dtx_init);
  7406. +
  7407. +static void __exit surface_dtx_exit(void)
  7408. +{
  7409. + platform_driver_unregister(&surface_dtx_platform_driver);
  7410. + ssam_dtx_driver_unregister();
  7411. +}
  7412. +module_exit(surface_dtx_exit);
  7413. +
  7414. +MODULE_AUTHOR("Maximilian Luz <luzmaximilian@gmail.com>");
  7415. +MODULE_DESCRIPTION("Detachment-system driver for Surface System Aggregator Module");
  7416. +MODULE_LICENSE("GPL");
  7417. diff --git a/drivers/misc/surface_aggregator/clients/surface_hid.c b/drivers/misc/surface_aggregator/clients/surface_hid.c
  7418. new file mode 100644
  7419. index 000000000000..033abc9aa95e
  7420. --- /dev/null
  7421. +++ b/drivers/misc/surface_aggregator/clients/surface_hid.c
  7422. @@ -0,0 +1,922 @@
  7423. +// SPDX-License-Identifier: GPL-2.0+
  7424. +/*
  7425. + * Surface System Aggregator Module (SSAM) HID device driver.
  7426. + *
  7427. + * Provides support for HID input devices connected via the Surface System
  7428. + * Aggregator Module.
  7429. + *
  7430. + * Copyright (C) 2019-2020 Blaž Hrastnik <blaz@mxxn.io>,
  7431. + * Maximilian Luz <luzmaximilian@gmail.com>
  7432. + */
  7433. +
  7434. +#include <asm/unaligned.h>
  7435. +#include <linux/acpi.h>
  7436. +#include <linux/hid.h>
  7437. +#include <linux/input.h>
  7438. +#include <linux/kernel.h>
  7439. +#include <linux/module.h>
  7440. +#include <linux/platform_device.h>
  7441. +#include <linux/types.h>
  7442. +#include <linux/usb/ch9.h>
  7443. +
  7444. +#include <linux/surface_aggregator/controller.h>
  7445. +#include <linux/surface_aggregator/device.h>
  7446. +
  7447. +
  7448. +enum surface_hid_descriptor_entry {
  7449. + SURFACE_HID_DESC_HID = 0,
  7450. + SURFACE_HID_DESC_REPORT = 1,
  7451. + SURFACE_HID_DESC_ATTRS = 2,
  7452. +};
  7453. +
  7454. +struct surface_hid_descriptor {
  7455. + __u8 desc_len; // = 9
  7456. + __u8 desc_type; // = HID_DT_HID
  7457. + __le16 hid_version;
  7458. + __u8 country_code;
  7459. + __u8 num_descriptors; // = 1
  7460. +
  7461. + __u8 report_desc_type; // = HID_DT_REPORT
  7462. + __le16 report_desc_len;
  7463. +} __packed;
  7464. +
  7465. +static_assert(sizeof(struct surface_hid_descriptor) == 9);
  7466. +
  7467. +struct surface_hid_attributes {
  7468. + __le32 length;
  7469. + __le16 vendor;
  7470. + __le16 product;
  7471. + __le16 version;
  7472. + __u8 _unknown[22];
  7473. +} __packed;
  7474. +
  7475. +static_assert(sizeof(struct surface_hid_attributes) == 32);
  7476. +
  7477. +struct surface_hid_device;
  7478. +
  7479. +struct surface_hid_device_ops {
  7480. + int (*get_descriptor)(struct surface_hid_device *shid, u8 entry,
  7481. + u8 *buf, size_t len);
  7482. + int (*output_report)(struct surface_hid_device *shid, u8 report_id,
  7483. + u8 *data, size_t len);
  7484. + int (*get_feature_report)(struct surface_hid_device *shid, u8 report_id,
  7485. + u8 *data, size_t len);
  7486. + int (*set_feature_report)(struct surface_hid_device *shid, u8 report_id,
  7487. + u8 *data, size_t len);
  7488. +};
  7489. +
  7490. +struct surface_hid_device {
  7491. + struct device *dev;
  7492. + struct ssam_controller *ctrl;
  7493. + struct ssam_device_uid uid;
  7494. +
  7495. + struct surface_hid_descriptor hid_desc;
  7496. + struct surface_hid_attributes attrs;
  7497. +
  7498. + struct ssam_event_notifier notif;
  7499. + struct hid_device *hid;
  7500. +
  7501. + struct surface_hid_device_ops ops;
  7502. +};
  7503. +
  7504. +
  7505. +/* -- SAM interface (HID). -------------------------------------------------- */
  7506. +
  7507. +#ifdef CONFIG_SURFACE_AGGREGATOR_BUS
  7508. +
  7509. +struct surface_hid_buffer_slice {
  7510. + __u8 entry;
  7511. + __le32 offset;
  7512. + __le32 length;
  7513. + __u8 end;
  7514. + __u8 data[];
  7515. +} __packed;
  7516. +
  7517. +static_assert(sizeof(struct surface_hid_buffer_slice) == 10);
  7518. +
  7519. +enum surface_hid_cid {
  7520. + SURFACE_HID_CID_OUTPUT_REPORT = 0x01,
  7521. + SURFACE_HID_CID_GET_FEATURE_REPORT = 0x02,
  7522. + SURFACE_HID_CID_SET_FEATURE_REPORT = 0x03,
  7523. + SURFACE_HID_CID_GET_DESCRIPTOR = 0x04,
  7524. +};
  7525. +
  7526. +static int ssam_hid_get_descriptor(struct surface_hid_device *shid, u8 entry,
  7527. + u8 *buf, size_t len)
  7528. +{
  7529. + u8 buffer[sizeof(struct surface_hid_buffer_slice) + 0x76];
  7530. + struct surface_hid_buffer_slice *slice;
  7531. + struct ssam_request rqst;
  7532. + struct ssam_response rsp;
  7533. + u32 buffer_len, offset, length;
  7534. + int status;
  7535. +
  7536. + /*
  7537. + * Note: The 0x76 above has been chosen because that's what's used by
  7538. + * the Windows driver. Together with the header, this leads to a 128
  7539. + * byte payload in total.
  7540. + */
  7541. +
  7542. + buffer_len = ARRAY_SIZE(buffer) - sizeof(struct surface_hid_buffer_slice);
  7543. +
  7544. + rqst.target_category = shid->uid.category;
  7545. + rqst.target_id = shid->uid.target;
  7546. + rqst.command_id = SURFACE_HID_CID_GET_DESCRIPTOR;
  7547. + rqst.instance_id = shid->uid.instance;
  7548. + rqst.flags = SSAM_REQUEST_HAS_RESPONSE;
  7549. + rqst.length = sizeof(struct surface_hid_buffer_slice);
  7550. + rqst.payload = buffer;
  7551. +
  7552. + rsp.capacity = ARRAY_SIZE(buffer);
  7553. + rsp.pointer = buffer;
  7554. +
  7555. + slice = (struct surface_hid_buffer_slice *)buffer;
  7556. + slice->entry = entry;
  7557. + slice->end = 0;
  7558. +
  7559. + offset = 0;
  7560. + length = buffer_len;
  7561. +
  7562. + while (!slice->end && offset < len) {
  7563. + put_unaligned_le32(offset, &slice->offset);
  7564. + put_unaligned_le32(length, &slice->length);
  7565. +
  7566. + rsp.length = 0;
  7567. +
  7568. + status = ssam_retry(ssam_request_sync_onstack, shid->ctrl,
  7569. + &rqst, &rsp, sizeof(*slice));
  7570. + if (status)
  7571. + return status;
  7572. +
  7573. + offset = get_unaligned_le32(&slice->offset);
  7574. + length = get_unaligned_le32(&slice->length);
  7575. +
  7576. + // don't mess stuff up in case we receive garbage
  7577. + if (length > buffer_len || offset > len)
  7578. + return -EPROTO;
  7579. +
  7580. + if (offset + length > len)
  7581. + length = len - offset;
  7582. +
  7583. + memcpy(buf + offset, &slice->data[0], length);
  7584. +
  7585. + offset += length;
  7586. + length = buffer_len;
  7587. + }
  7588. +
  7589. + if (offset != len) {
  7590. + dev_err(shid->dev, "unexpected descriptor length: got %u, "
  7591. + "expected %zu\n", offset, len);
  7592. + return -EPROTO;
  7593. + }
  7594. +
  7595. + return 0;
  7596. +}
  7597. +
  7598. +static int ssam_hid_set_raw_report(struct surface_hid_device *shid,
  7599. + u8 report_id, bool feature, u8 *buf,
  7600. + size_t len)
  7601. +{
  7602. + struct ssam_request rqst;
  7603. + u8 cid;
  7604. +
  7605. + if (feature)
  7606. + cid = SURFACE_HID_CID_SET_FEATURE_REPORT;
  7607. + else
  7608. + cid = SURFACE_HID_CID_OUTPUT_REPORT;
  7609. +
  7610. + rqst.target_category = shid->uid.category;
  7611. + rqst.target_id = shid->uid.target;
  7612. + rqst.instance_id = shid->uid.instance;
  7613. + rqst.command_id = cid;
  7614. + rqst.flags = 0;
  7615. + rqst.length = len;
  7616. + rqst.payload = buf;
  7617. +
  7618. + buf[0] = report_id;
  7619. +
  7620. + return ssam_retry(ssam_request_sync, shid->ctrl, &rqst, NULL);
  7621. +}
  7622. +
  7623. +static int ssam_hid_get_raw_report(struct surface_hid_device *shid,
  7624. + u8 report_id, u8 *buf, size_t len)
  7625. +{
  7626. + struct ssam_request rqst;
  7627. + struct ssam_response rsp;
  7628. +
  7629. + rqst.target_category = shid->uid.category;
  7630. + rqst.target_id = shid->uid.target;
  7631. + rqst.instance_id = shid->uid.instance;
  7632. + rqst.command_id = SURFACE_HID_CID_GET_FEATURE_REPORT;
  7633. + rqst.flags = 0;
  7634. + rqst.length = sizeof(report_id);
  7635. + rqst.payload = &report_id;
  7636. +
  7637. + rsp.capacity = len;
  7638. + rsp.length = 0;
  7639. + rsp.pointer = buf;
  7640. +
  7641. + return ssam_retry(ssam_request_sync_onstack, shid->ctrl, &rqst, &rsp,
  7642. + sizeof(report_id));
  7643. +}
  7644. +
  7645. +static u32 ssam_hid_event_fn(struct ssam_event_notifier *nf,
  7646. + const struct ssam_event *event)
  7647. +{
  7648. + struct surface_hid_device *shid;
  7649. + int status;
  7650. +
  7651. + shid = container_of(nf, struct surface_hid_device, notif);
  7652. +
  7653. + if (event->command_id != 0x00)
  7654. + return 0;
  7655. +
  7656. + status = hid_input_report(shid->hid, HID_INPUT_REPORT,
  7657. + (u8 *)&event->data[0], event->length, 0);
  7658. +
  7659. + return ssam_notifier_from_errno(status) | SSAM_NOTIF_HANDLED;
  7660. +}
  7661. +
  7662. +
  7663. +/* -- Transport driver (HID). ----------------------------------------------- */
  7664. +
  7665. +static int shid_output_report(struct surface_hid_device *shid, u8 report_id,
  7666. + u8 *data, size_t len)
  7667. +{
  7668. + int status;
  7669. +
  7670. + status = ssam_hid_set_raw_report(shid, report_id, false, data, len);
  7671. + return status >= 0 ? len : status;
  7672. +}
  7673. +
  7674. +static int shid_get_feature_report(struct surface_hid_device *shid,
  7675. + u8 report_id, u8 *data, size_t len)
  7676. +{
  7677. + int status;
  7678. +
  7679. + status = ssam_hid_get_raw_report(shid, report_id, data, len);
  7680. + return status >= 0 ? len : status;
  7681. +}
  7682. +
  7683. +static int shid_set_feature_report(struct surface_hid_device *shid,
  7684. + u8 report_id, u8 *data, size_t len)
  7685. +{
  7686. + int status;
  7687. +
  7688. + status = ssam_hid_set_raw_report(shid, report_id, true, data, len);
  7689. + return status >= 0 ? len : status;
  7690. +}
  7691. +
  7692. +#endif /* CONFIG_SURFACE_AGGREGATOR_BUS */
  7693. +
  7694. +
  7695. +/* -- SAM interface (KBD). -------------------------------------------------- */
  7696. +
  7697. +#define KBD_FEATURE_REPORT_SIZE 7 // 6 + report ID
  7698. +
  7699. +enum surface_kbd_cid {
  7700. + SURFACE_KBD_CID_GET_DESCRIPTOR = 0x00,
  7701. + SURFACE_KBD_CID_SET_CAPSLOCK_LED = 0x01,
  7702. + SURFACE_KBD_CID_EVT_INPUT_GENERIC = 0x03,
  7703. + SURFACE_KBD_CID_EVT_INPUT_HOTKEYS = 0x04,
  7704. + SURFACE_KBD_CID_GET_FEATURE_REPORT = 0x0b,
  7705. +};
  7706. +
  7707. +static int ssam_kbd_get_descriptor(struct surface_hid_device *shid, u8 entry,
  7708. + u8 *buf, size_t len)
  7709. +{
  7710. + struct ssam_request rqst;
  7711. + struct ssam_response rsp;
  7712. + int status;
  7713. +
  7714. + rqst.target_category = shid->uid.category;
  7715. + rqst.target_id = shid->uid.target;
  7716. + rqst.command_id = SURFACE_KBD_CID_GET_DESCRIPTOR;
  7717. + rqst.instance_id = shid->uid.instance;
  7718. + rqst.flags = SSAM_REQUEST_HAS_RESPONSE;
  7719. + rqst.length = sizeof(entry);
  7720. + rqst.payload = &entry;
  7721. +
  7722. + rsp.capacity = len;
  7723. + rsp.length = 0;
  7724. + rsp.pointer = buf;
  7725. +
  7726. + status = ssam_retry(ssam_request_sync_onstack, shid->ctrl, &rqst, &rsp,
  7727. + sizeof(entry));
  7728. + if (status)
  7729. + return status;
  7730. +
  7731. + if (rsp.length != len) {
  7732. + dev_err(shid->dev, "invalid descriptor length: got %zu, "
  7733. + "expected, %zu\n", rsp.length, len);
  7734. + return -EPROTO;
  7735. + }
  7736. +
  7737. + return 0;
  7738. +}
  7739. +
  7740. +static int ssam_kbd_set_caps_led(struct surface_hid_device *shid, bool value)
  7741. +{
  7742. + struct ssam_request rqst;
  7743. + u8 value_u8 = value;
  7744. +
  7745. + rqst.target_category = shid->uid.category;
  7746. + rqst.target_id = shid->uid.target;
  7747. + rqst.command_id = SURFACE_KBD_CID_SET_CAPSLOCK_LED;
  7748. + rqst.instance_id = shid->uid.instance;
  7749. + rqst.flags = 0;
  7750. + rqst.length = sizeof(value_u8);
  7751. + rqst.payload = &value_u8;
  7752. +
  7753. + return ssam_retry(ssam_request_sync_onstack, shid->ctrl, &rqst, NULL,
  7754. + sizeof(value_u8));
  7755. +}
  7756. +
  7757. +static int ssam_kbd_get_feature_report(struct surface_hid_device *shid, u8 *buf,
  7758. + size_t len)
  7759. +{
  7760. + struct ssam_request rqst;
  7761. + struct ssam_response rsp;
  7762. + u8 payload = 0;
  7763. + int status;
  7764. +
  7765. + rqst.target_category = shid->uid.category;
  7766. + rqst.target_id = shid->uid.target;
  7767. + rqst.command_id = SURFACE_KBD_CID_GET_FEATURE_REPORT;
  7768. + rqst.instance_id = shid->uid.instance;
  7769. + rqst.flags = SSAM_REQUEST_HAS_RESPONSE;
  7770. + rqst.length = sizeof(payload);
  7771. + rqst.payload = &payload;
  7772. +
  7773. + rsp.capacity = len;
  7774. + rsp.length = 0;
  7775. + rsp.pointer = buf;
  7776. +
  7777. + status = ssam_retry(ssam_request_sync_onstack, shid->ctrl, &rqst, &rsp,
  7778. + sizeof(payload));
  7779. + if (status)
  7780. + return status;
  7781. +
  7782. + if (rsp.length != len) {
  7783. + dev_err(shid->dev, "invalid feature report length: got %zu, "
  7784. + "expected, %zu\n", rsp.length, len);
  7785. + return -EPROTO;
  7786. + }
  7787. +
  7788. + return 0;
  7789. +}
  7790. +
  7791. +static bool ssam_kbd_is_input_event(const struct ssam_event *event)
  7792. +{
  7793. + if (event->command_id == SURFACE_KBD_CID_EVT_INPUT_GENERIC)
  7794. + return true;
  7795. +
  7796. + if (event->command_id == SURFACE_KBD_CID_EVT_INPUT_HOTKEYS)
  7797. + return true;
  7798. +
  7799. + return false;
  7800. +}
  7801. +
  7802. +static u32 ssam_kbd_event_fn(struct ssam_event_notifier *nf,
  7803. + const struct ssam_event *event)
  7804. +{
  7805. + struct surface_hid_device *shid;
  7806. + int status;
  7807. +
  7808. + shid = container_of(nf, struct surface_hid_device, notif);
  7809. +
  7810. + /*
  7811. + * Check against device UID manually, as registry and device target
  7812. + * category doesn't line up.
  7813. + */
  7814. +
  7815. + if (shid->uid.category != event->target_category)
  7816. + return 0;
  7817. +
  7818. + if (shid->uid.target != event->target_id)
  7819. + return 0;
  7820. +
  7821. + if (shid->uid.instance != event->instance_id)
  7822. + return 0;
  7823. +
  7824. + if (!ssam_kbd_is_input_event(event))
  7825. + return 0;
  7826. +
  7827. + status = hid_input_report(shid->hid, HID_INPUT_REPORT,
  7828. + (u8 *)&event->data[0], event->length, 0);
  7829. +
  7830. + return ssam_notifier_from_errno(status) | SSAM_NOTIF_HANDLED;
  7831. +}
  7832. +
  7833. +
  7834. +/* -- Transport driver (KBD). ----------------------------------------------- */
  7835. +
  7836. +static int skbd_get_caps_led_value(struct hid_device *hid, u8 report_id,
  7837. + u8 *data, size_t len)
  7838. +{
  7839. + struct hid_field *field;
  7840. + unsigned int offset, size;
  7841. + int i;
  7842. +
  7843. + // get led field
  7844. + field = hidinput_get_led_field(hid);
  7845. + if (!field)
  7846. + return -ENOENT;
  7847. +
  7848. + // check if we got the correct report
  7849. + if (len != hid_report_len(field->report))
  7850. + return -ENOENT;
  7851. +
  7852. + if (report_id != field->report->id)
  7853. + return -ENOENT;
  7854. +
  7855. + // get caps lock led index
  7856. + for (i = 0; i < field->report_count; i++)
  7857. + if ((field->usage[i].hid & 0xffff) == 0x02)
  7858. + break;
  7859. +
  7860. + if (i == field->report_count)
  7861. + return -ENOENT;
  7862. +
  7863. + // extract value
  7864. + size = field->report_size;
  7865. + offset = field->report_offset + i * size;
  7866. + return !!hid_field_extract(hid, data + 1, size, offset);
  7867. +}
  7868. +
  7869. +static int skbd_output_report(struct surface_hid_device *shid, u8 report_id,
  7870. + u8 *data, size_t len)
  7871. +{
  7872. + int caps_led;
  7873. + int status;
  7874. +
  7875. + caps_led = skbd_get_caps_led_value(shid->hid, report_id, data, len);
  7876. + if (caps_led < 0)
  7877. + return -EIO; // only caps output reports are supported
  7878. +
  7879. + status = ssam_kbd_set_caps_led(shid, caps_led);
  7880. + if (status < 0)
  7881. + return status;
  7882. +
  7883. + return len;
  7884. +}
  7885. +
  7886. +static int skbd_get_feature_report(struct surface_hid_device *shid,
  7887. + u8 report_id, u8 *data, size_t len)
  7888. +{
  7889. + u8 report[KBD_FEATURE_REPORT_SIZE];
  7890. + int status;
  7891. +
  7892. + /*
  7893. + * The keyboard only has a single hard-coded read-only feature report
  7894. + * of size KBD_FEATURE_REPORT_SIZE. Try to load it and compare its
  7895. + * report ID against the requested one.
  7896. + */
  7897. +
  7898. + if (len < ARRAY_SIZE(report))
  7899. + return -ENOSPC;
  7900. +
  7901. + status = ssam_kbd_get_feature_report(shid, report, ARRAY_SIZE(report));
  7902. + if (status < 0)
  7903. + return status;
  7904. +
  7905. + if (report_id != report[0])
  7906. + return -ENOENT;
  7907. +
  7908. + memcpy(data, report, ARRAY_SIZE(report));
  7909. + return len;
  7910. +}
  7911. +
  7912. +static int skbd_set_feature_report(struct surface_hid_device *shid,
  7913. + u8 report_id, u8 *data, size_t len)
  7914. +{
  7915. + return -EIO;
  7916. +}
  7917. +
  7918. +
  7919. +/* -- Device descriptor access. --------------------------------------------- */
  7920. +
  7921. +static int surface_hid_load_hid_descriptor(struct surface_hid_device *shid)
  7922. +{
  7923. + int status;
  7924. +
  7925. + status = shid->ops.get_descriptor(shid, SURFACE_HID_DESC_HID,
  7926. + (u8 *)&shid->hid_desc, sizeof(shid->hid_desc));
  7927. + if (status)
  7928. + return status;
  7929. +
  7930. + if (shid->hid_desc.desc_len != sizeof(shid->hid_desc)) {
  7931. + dev_err(shid->dev, "unexpected HID descriptor length: got %u, "
  7932. + "expected %zu\n", shid->hid_desc.desc_len,
  7933. + sizeof(shid->hid_desc));
  7934. + return -EPROTO;
  7935. + }
  7936. +
  7937. + if (shid->hid_desc.desc_type != HID_DT_HID) {
  7938. + dev_err(shid->dev, "unexpected HID descriptor type: got 0x%x, "
  7939. + "expected 0x%x\n", shid->hid_desc.desc_type,
  7940. + HID_DT_HID);
  7941. + return -EPROTO;
  7942. + }
  7943. +
  7944. + if (shid->hid_desc.num_descriptors != 1) {
  7945. + dev_err(shid->dev, "unexpected number of descriptors: got %u, "
  7946. + "expected 1\n", shid->hid_desc.num_descriptors);
  7947. + return -EPROTO;
  7948. + }
  7949. +
  7950. + if (shid->hid_desc.report_desc_type != HID_DT_REPORT) {
  7951. + dev_err(shid->dev, "unexpected report descriptor type: got 0x%x, "
  7952. + "expected 0x%x\n", shid->hid_desc.report_desc_type,
  7953. + HID_DT_REPORT);
  7954. + return -EPROTO;
  7955. + }
  7956. +
  7957. + return 0;
  7958. +}
  7959. +
  7960. +static int surface_hid_load_device_attributes(struct surface_hid_device *shid)
  7961. +{
  7962. + int status;
  7963. +
  7964. + status = shid->ops.get_descriptor(shid, SURFACE_HID_DESC_ATTRS,
  7965. + (u8 *)&shid->attrs, sizeof(shid->attrs));
  7966. + if (status)
  7967. + return status;
  7968. +
  7969. + if (get_unaligned_le32(&shid->attrs.length) != sizeof(shid->attrs)) {
  7970. + dev_err(shid->dev, "unexpected attribute length: got %u, "
  7971. + "expected %zu\n", get_unaligned_le32(&shid->attrs.length),
  7972. + sizeof(shid->attrs));
  7973. + return -EPROTO;
  7974. + }
  7975. +
  7976. + return 0;
  7977. +}
  7978. +
  7979. +
  7980. +/* -- Transport driver (common). -------------------------------------------- */
  7981. +
  7982. +static int surface_hid_start(struct hid_device *hid)
  7983. +{
  7984. + struct surface_hid_device *shid = hid->driver_data;
  7985. +
  7986. + return ssam_notifier_register(shid->ctrl, &shid->notif);
  7987. +}
  7988. +
  7989. +static void surface_hid_stop(struct hid_device *hid)
  7990. +{
  7991. + struct surface_hid_device *shid = hid->driver_data;
  7992. +
  7993. + // Note: This call will log errors for us, so ignore them here.
  7994. + ssam_notifier_unregister(shid->ctrl, &shid->notif);
  7995. +}
  7996. +
  7997. +static int surface_hid_open(struct hid_device *hid)
  7998. +{
  7999. + return 0;
  8000. +}
  8001. +
  8002. +static void surface_hid_close(struct hid_device *hid)
  8003. +{
  8004. +}
  8005. +
  8006. +static int surface_hid_parse(struct hid_device *hid)
  8007. +{
  8008. + struct surface_hid_device *shid = hid->driver_data;
  8009. + size_t len = get_unaligned_le16(&shid->hid_desc.report_desc_len);
  8010. + u8 *buf;
  8011. + int status;
  8012. +
  8013. + buf = kzalloc(len, GFP_KERNEL);
  8014. + if (!buf)
  8015. + return -ENOMEM;
  8016. +
  8017. + status = shid->ops.get_descriptor(shid, SURFACE_HID_DESC_REPORT, buf, len);
  8018. + if (!status)
  8019. + status = hid_parse_report(hid, buf, len);
  8020. +
  8021. + kfree(buf);
  8022. + return status;
  8023. +}
  8024. +
  8025. +static int surface_hid_raw_request(struct hid_device *hid,
  8026. + unsigned char reportnum, u8 *buf, size_t len,
  8027. + unsigned char rtype, int reqtype)
  8028. +{
  8029. + struct surface_hid_device *shid = hid->driver_data;
  8030. +
  8031. + if (rtype == HID_OUTPUT_REPORT && reqtype == HID_REQ_SET_REPORT)
  8032. + return shid->ops.output_report(shid, reportnum, buf, len);
  8033. +
  8034. + else if (rtype == HID_FEATURE_REPORT && reqtype == HID_REQ_GET_REPORT)
  8035. + return shid->ops.get_feature_report(shid, reportnum, buf, len);
  8036. +
  8037. + else if (rtype == HID_FEATURE_REPORT && reqtype == HID_REQ_SET_REPORT)
  8038. + return shid->ops.set_feature_report(shid, reportnum, buf, len);
  8039. +
  8040. + return -EIO;
  8041. +}
  8042. +
  8043. +static struct hid_ll_driver surface_hid_ll_driver = {
  8044. + .start = surface_hid_start,
  8045. + .stop = surface_hid_stop,
  8046. + .open = surface_hid_open,
  8047. + .close = surface_hid_close,
  8048. + .parse = surface_hid_parse,
  8049. + .raw_request = surface_hid_raw_request,
  8050. +};
  8051. +
  8052. +
  8053. +/* -- Common device setup. -------------------------------------------------- */
  8054. +
  8055. +static int surface_hid_device_add(struct surface_hid_device *shid)
  8056. +{
  8057. + int status;
  8058. +
  8059. + status = surface_hid_load_hid_descriptor(shid);
  8060. + if (status)
  8061. + return status;
  8062. +
  8063. + status = surface_hid_load_device_attributes(shid);
  8064. + if (status)
  8065. + return status;
  8066. +
  8067. + shid->hid = hid_allocate_device();
  8068. + if (IS_ERR(shid->hid))
  8069. + return PTR_ERR(shid->hid);
  8070. +
  8071. + shid->hid->dev.parent = shid->dev;
  8072. + shid->hid->bus = BUS_HOST; // TODO: BUS_SURFACE
  8073. + shid->hid->vendor = cpu_to_le16(shid->attrs.vendor);
  8074. + shid->hid->product = cpu_to_le16(shid->attrs.product);
  8075. + shid->hid->version = cpu_to_le16(shid->hid_desc.hid_version);
  8076. + shid->hid->country = shid->hid_desc.country_code;
  8077. +
  8078. + snprintf(shid->hid->name, sizeof(shid->hid->name),
  8079. + "Microsoft Surface %04X:%04X",
  8080. + shid->hid->vendor, shid->hid->product);
  8081. +
  8082. + strlcpy(shid->hid->phys, dev_name(shid->dev), sizeof(shid->hid->phys));
  8083. +
  8084. + shid->hid->driver_data = shid;
  8085. + shid->hid->ll_driver = &surface_hid_ll_driver;
  8086. +
  8087. + status = hid_add_device(shid->hid);
  8088. + if (status)
  8089. + hid_destroy_device(shid->hid);
  8090. +
  8091. + return status;
  8092. +}
  8093. +
  8094. +static void surface_hid_device_destroy(struct surface_hid_device *shid)
  8095. +{
  8096. + hid_destroy_device(shid->hid);
  8097. +}
  8098. +
  8099. +
  8100. +/* -- PM ops. --------------------------------------------------------------- */
  8101. +
  8102. +#ifdef CONFIG_PM_SLEEP
  8103. +
  8104. +static int surface_hid_suspend(struct device *dev)
  8105. +{
  8106. + struct surface_hid_device *d = dev_get_drvdata(dev);
  8107. +
  8108. + if (d->hid->driver && d->hid->driver->suspend)
  8109. + return d->hid->driver->suspend(d->hid, PMSG_SUSPEND);
  8110. +
  8111. + return 0;
  8112. +}
  8113. +
  8114. +static int surface_hid_resume(struct device *dev)
  8115. +{
  8116. + struct surface_hid_device *d = dev_get_drvdata(dev);
  8117. +
  8118. + if (d->hid->driver && d->hid->driver->resume)
  8119. + return d->hid->driver->resume(d->hid);
  8120. +
  8121. + return 0;
  8122. +}
  8123. +
  8124. +static int surface_hid_freeze(struct device *dev)
  8125. +{
  8126. + struct surface_hid_device *d = dev_get_drvdata(dev);
  8127. +
  8128. + if (d->hid->driver && d->hid->driver->suspend)
  8129. + return d->hid->driver->suspend(d->hid, PMSG_FREEZE);
  8130. +
  8131. + return 0;
  8132. +}
  8133. +
  8134. +static int surface_hid_poweroff(struct device *dev)
  8135. +{
  8136. + struct surface_hid_device *d = dev_get_drvdata(dev);
  8137. +
  8138. + if (d->hid->driver && d->hid->driver->suspend)
  8139. + return d->hid->driver->suspend(d->hid, PMSG_HIBERNATE);
  8140. +
  8141. + return 0;
  8142. +}
  8143. +
  8144. +static int surface_hid_restore(struct device *dev)
  8145. +{
  8146. + struct surface_hid_device *d = dev_get_drvdata(dev);
  8147. +
  8148. + if (d->hid->driver && d->hid->driver->reset_resume)
  8149. + return d->hid->driver->reset_resume(d->hid);
  8150. +
  8151. + return 0;
  8152. +}
  8153. +
  8154. +const struct dev_pm_ops surface_hid_pm_ops = {
  8155. + .freeze = surface_hid_freeze,
  8156. + .thaw = surface_hid_resume,
  8157. + .suspend = surface_hid_suspend,
  8158. + .resume = surface_hid_resume,
  8159. + .poweroff = surface_hid_poweroff,
  8160. + .restore = surface_hid_restore,
  8161. +};
  8162. +
  8163. +#else /* CONFIG_PM_SLEEP */
  8164. +
  8165. +const struct dev_pm_ops surface_hid_pm_ops = { };
  8166. +
  8167. +#endif /* CONFIG_PM_SLEEP */
  8168. +
  8169. +
  8170. +/* -- Driver setup (HID). --------------------------------------------------- */
  8171. +
  8172. +#ifdef CONFIG_SURFACE_AGGREGATOR_BUS
  8173. +
  8174. +static int surface_hid_probe(struct ssam_device *sdev)
  8175. +{
  8176. + struct surface_hid_device *shid;
  8177. +
  8178. + shid = devm_kzalloc(&sdev->dev, sizeof(*shid), GFP_KERNEL);
  8179. + if (!shid)
  8180. + return -ENOMEM;
  8181. +
  8182. + shid->dev = &sdev->dev;
  8183. + shid->ctrl = sdev->ctrl;
  8184. + shid->uid = sdev->uid;
  8185. +
  8186. + shid->notif.base.priority = 1;
  8187. + shid->notif.base.fn = ssam_hid_event_fn;
  8188. + shid->notif.event.reg = SSAM_EVENT_REGISTRY_REG,
  8189. + shid->notif.event.id.target_category = sdev->uid.category;
  8190. + shid->notif.event.id.instance = sdev->uid.instance;
  8191. + shid->notif.event.mask = SSAM_EVENT_MASK_STRICT;
  8192. + shid->notif.event.flags = 0;
  8193. +
  8194. + shid->ops.get_descriptor = ssam_hid_get_descriptor;
  8195. + shid->ops.output_report = shid_output_report;
  8196. + shid->ops.get_feature_report = shid_get_feature_report;
  8197. + shid->ops.set_feature_report = shid_set_feature_report;
  8198. +
  8199. + ssam_device_set_drvdata(sdev, shid);
  8200. + return surface_hid_device_add(shid);
  8201. +}
  8202. +
  8203. +static void surface_hid_remove(struct ssam_device *sdev)
  8204. +{
  8205. + surface_hid_device_destroy(ssam_device_get_drvdata(sdev));
  8206. +}
  8207. +
  8208. +static const struct ssam_device_id surface_hid_match[] = {
  8209. + { SSAM_SDEV(HID, 0x02, SSAM_ANY_IID, 0x00) },
  8210. + { },
  8211. +};
  8212. +MODULE_DEVICE_TABLE(ssam, surface_hid_match);
  8213. +
  8214. +static struct ssam_device_driver surface_hid_driver = {
  8215. + .probe = surface_hid_probe,
  8216. + .remove = surface_hid_remove,
  8217. + .match_table = surface_hid_match,
  8218. + .driver = {
  8219. + .name = "surface_hid",
  8220. + .pm = &surface_hid_pm_ops,
  8221. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  8222. + },
  8223. +};
  8224. +
  8225. +static int surface_hid_driver_register(void)
  8226. +{
  8227. + return ssam_device_driver_register(&surface_hid_driver);
  8228. +}
  8229. +
  8230. +static void surface_hid_driver_unregister(void)
  8231. +{
  8232. + ssam_device_driver_unregister(&surface_hid_driver);
  8233. +}
  8234. +
  8235. +#else /* CONFIG_SURFACE_AGGREGATOR_BUS */
  8236. +
  8237. +static int surface_hid_driver_register(void)
  8238. +{
  8239. + return 0;
  8240. +}
  8241. +
  8242. +static void surface_hid_driver_unregister(void)
  8243. +{
  8244. +}
  8245. +
  8246. +#endif /* CONFIG_SURFACE_AGGREGATOR_BUS */
  8247. +
  8248. +
  8249. +/* -- Driver setup (KBD). --------------------------------------------------- */
  8250. +
  8251. +static int surface_kbd_probe(struct platform_device *pdev)
  8252. +{
  8253. + struct ssam_controller *ctrl;
  8254. + struct surface_hid_device *shid;
  8255. + int status;
  8256. +
  8257. + // add device link to EC
  8258. + status = ssam_client_bind(&pdev->dev, &ctrl);
  8259. + if (status)
  8260. + return status == -ENXIO ? -EPROBE_DEFER : status;
  8261. +
  8262. + shid = devm_kzalloc(&pdev->dev, sizeof(*shid), GFP_KERNEL);
  8263. + if (!shid)
  8264. + return -ENOMEM;
  8265. +
  8266. + shid->dev = &pdev->dev;
  8267. + shid->ctrl = ctrl;
  8268. +
  8269. + shid->uid.domain = SSAM_DOMAIN_SERIALHUB;
  8270. + shid->uid.category = SSAM_SSH_TC_KBD;
  8271. + shid->uid.target = 2;
  8272. + shid->uid.instance = 0;
  8273. + shid->uid.function = 0;
  8274. +
  8275. + shid->notif.base.priority = 1;
  8276. + shid->notif.base.fn = ssam_kbd_event_fn;
  8277. + shid->notif.event.reg = SSAM_EVENT_REGISTRY_SAM;
  8278. + shid->notif.event.id.target_category = shid->uid.category;
  8279. + shid->notif.event.id.instance = shid->uid.instance;
  8280. + shid->notif.event.mask = SSAM_EVENT_MASK_NONE;
  8281. + shid->notif.event.flags = 0;
  8282. +
  8283. + shid->ops.get_descriptor = ssam_kbd_get_descriptor;
  8284. + shid->ops.output_report = skbd_output_report;
  8285. + shid->ops.get_feature_report = skbd_get_feature_report;
  8286. + shid->ops.set_feature_report = skbd_set_feature_report;
  8287. +
  8288. + platform_set_drvdata(pdev, shid);
  8289. + return surface_hid_device_add(shid);
  8290. +}
  8291. +
  8292. +static int surface_kbd_remove(struct platform_device *pdev)
  8293. +{
  8294. + surface_hid_device_destroy(platform_get_drvdata(pdev));
  8295. + return 0;
  8296. +}
  8297. +
  8298. +static const struct acpi_device_id surface_kbd_match[] = {
  8299. + { "MSHW0096" },
  8300. + { },
  8301. +};
  8302. +MODULE_DEVICE_TABLE(acpi, surface_kbd_match);
  8303. +
  8304. +static struct platform_driver surface_kbd_driver = {
  8305. + .probe = surface_kbd_probe,
  8306. + .remove = surface_kbd_remove,
  8307. + .driver = {
  8308. + .name = "surface_keyboard",
  8309. + .acpi_match_table = surface_kbd_match,
  8310. + .pm = &surface_hid_pm_ops,
  8311. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  8312. + },
  8313. +};
  8314. +
  8315. +
  8316. +/* -- Module setup. --------------------------------------------------------- */
  8317. +
  8318. +static int __init surface_hid_init(void)
  8319. +{
  8320. + int status;
  8321. +
  8322. + status = surface_hid_driver_register();
  8323. + if (status)
  8324. + return status;
  8325. +
  8326. + status = platform_driver_register(&surface_kbd_driver);
  8327. + if (status)
  8328. + surface_hid_driver_unregister();
  8329. +
  8330. + return status;
  8331. +}
  8332. +module_init(surface_hid_init);
  8333. +
  8334. +static void __exit surface_hid_exit(void)
  8335. +{
  8336. + platform_driver_unregister(&surface_kbd_driver);
  8337. + surface_hid_driver_unregister();
  8338. +}
  8339. +module_exit(surface_hid_exit);
  8340. +
  8341. +MODULE_AUTHOR("Blaž Hrastnik <blaz@mxxn.io>");
  8342. +MODULE_AUTHOR("Maximilian Luz <luzmaximilian@gmail.com>");
  8343. +MODULE_DESCRIPTION("HID transport-/device-driver for Surface System Aggregator Module");
  8344. +MODULE_LICENSE("GPL");
  8345. diff --git a/drivers/misc/surface_aggregator/clients/surface_hotplug.c b/drivers/misc/surface_aggregator/clients/surface_hotplug.c
  8346. new file mode 100644
  8347. index 000000000000..9afddfc6a358
  8348. --- /dev/null
  8349. +++ b/drivers/misc/surface_aggregator/clients/surface_hotplug.c
  8350. @@ -0,0 +1,269 @@
  8351. +// SPDX-License-Identifier: GPL-2.0+
  8352. +/*
  8353. + * Surface Book (gen. 2 and later) hot-plug driver.
  8354. + *
  8355. + * Surface Book devices (can) have a hot-pluggable discrete GPU (dGPU). This
  8356. + * driver is responsible for out-of-band hot-plug event signalling on these
  8357. + * devices. It is specifically required when the hot-plug device is in D3cold
  8358. + * and can thus not generate PCIe hot-plug events itself.
  8359. + *
  8360. + * Event signalling is handled via ACPI, which will generate the appropriate
  8361. + * device-check notifications to be picked up by the PCIe hot-plug driver.
  8362. + *
  8363. + * Copyright (C) 2019-2020 Maximilian Luz <luzmaximilian@gmail.com>
  8364. + */
  8365. +
  8366. +#include <linux/acpi.h>
  8367. +#include <linux/gpio.h>
  8368. +#include <linux/interrupt.h>
  8369. +#include <linux/kernel.h>
  8370. +#include <linux/module.h>
  8371. +#include <linux/mutex.h>
  8372. +#include <linux/platform_device.h>
  8373. +
  8374. +static const struct acpi_gpio_params shps_base_presence_int = { 0, 0, false };
  8375. +static const struct acpi_gpio_params shps_base_presence = { 1, 0, false };
  8376. +static const struct acpi_gpio_params shps_device_power_int = { 2, 0, false };
  8377. +static const struct acpi_gpio_params shps_device_power = { 3, 0, false };
  8378. +static const struct acpi_gpio_params shps_device_presence_int = { 4, 0, false };
  8379. +static const struct acpi_gpio_params shps_device_presence = { 5, 0, false };
  8380. +
  8381. +static const struct acpi_gpio_mapping shps_acpi_gpios[] = {
  8382. + { "base_presence-int-gpio", &shps_base_presence_int, 1 },
  8383. + { "base_presence-gpio", &shps_base_presence, 1 },
  8384. + { "device_power-int-gpio", &shps_device_power_int, 1 },
  8385. + { "device_power-gpio", &shps_device_power, 1 },
  8386. + { "device_presence-int-gpio", &shps_device_presence_int, 1 },
  8387. + { "device_presence-gpio", &shps_device_presence, 1 },
  8388. + { },
  8389. +};
  8390. +
  8391. +static const guid_t shps_dsm_guid =
  8392. + GUID_INIT(0x5515a847, 0xed55, 0x4b27, 0x83, 0x52, 0xcd,
  8393. + 0x32, 0x0e, 0x10, 0x36, 0x0a);
  8394. +
  8395. +#define SHPS_DSM_REVISION 1
  8396. +
  8397. +enum shps_dsm_fn {
  8398. + SHPS_DSM_FN_PCI_NUM_ENTRIES = 0x01,
  8399. + SHPS_DSM_FN_PCI_GET_ENTRIES = 0x02,
  8400. + SHPS_DSM_FN_IRQ_BASE_PRESENCE = 0x03,
  8401. + SHPS_DSM_FN_IRQ_DEVICE_POWER = 0x04,
  8402. + SHPS_DSM_FN_IRQ_DEVICE_PRESENCE = 0x05,
  8403. +};
  8404. +
  8405. +enum shps_irq_type {
  8406. + /* NOTE: Must be in order of DSM function */
  8407. + SHPS_IRQ_TYPE_BASE_PRESENCE = 0,
  8408. + SHPS_IRQ_TYPE_DEVICE_POWER = 1,
  8409. + SHPS_IRQ_TYPE_DEVICE_PRESENCE = 2,
  8410. +
  8411. + SHPS_NUM_IRQS,
  8412. +};
  8413. +
  8414. +static const char *const shps_gpio_names[] = {
  8415. + [SHPS_IRQ_TYPE_BASE_PRESENCE] = "base_presence",
  8416. + [SHPS_IRQ_TYPE_DEVICE_POWER] = "device_power",
  8417. + [SHPS_IRQ_TYPE_DEVICE_PRESENCE] = "device_presence",
  8418. +};
  8419. +
  8420. +struct shps_device {
  8421. + struct mutex lock[SHPS_NUM_IRQS];
  8422. + struct gpio_desc *gpio[SHPS_NUM_IRQS];
  8423. + unsigned int irq[SHPS_NUM_IRQS];
  8424. +};
  8425. +
  8426. +#define SHPS_IRQ_NOT_PRESENT ((unsigned int)-1)
  8427. +
  8428. +static void shps_dsm_notify_irq(struct platform_device *pdev,
  8429. + enum shps_irq_type type)
  8430. +{
  8431. + struct shps_device *sdev = platform_get_drvdata(pdev);
  8432. + acpi_handle handle = ACPI_HANDLE(&pdev->dev);
  8433. + union acpi_object *result;
  8434. + union acpi_object param;
  8435. + int value;
  8436. +
  8437. + mutex_lock(&sdev->lock[type]);
  8438. +
  8439. + value = gpiod_get_value_cansleep(sdev->gpio[type]);
  8440. + if (value < 0) {
  8441. + mutex_unlock(&sdev->lock[type]);
  8442. + dev_err(&pdev->dev, "failed to get gpio: %d (irq=%d)\n",
  8443. + type, value);
  8444. + return;
  8445. + }
  8446. +
  8447. + dev_dbg(&pdev->dev, "IRQ notification via DSM (irq=%d, value=%d)\n",
  8448. + type, value);
  8449. +
  8450. + param.type = ACPI_TYPE_INTEGER;
  8451. + param.integer.value = value;
  8452. +
  8453. + result = acpi_evaluate_dsm(handle, &shps_dsm_guid, SHPS_DSM_REVISION,
  8454. + SHPS_DSM_FN_IRQ_BASE_PRESENCE + type, &param);
  8455. +
  8456. + if (!result) {
  8457. + mutex_unlock(&sdev->lock[type]);
  8458. + dev_err(&pdev->dev, "IRQ notification via DSM failed"
  8459. + " (irq=%d, gpio=%d)\n", type, value);
  8460. + return;
  8461. + }
  8462. +
  8463. + if (result->type != ACPI_TYPE_BUFFER) {
  8464. + dev_err(&pdev->dev, "IRQ notification via DSM failed:"
  8465. + " unexpected result type (irq=%d, gpio=%d)\n",
  8466. + type, value);
  8467. + }
  8468. +
  8469. + if (result->buffer.length != 1 || result->buffer.pointer[0] != 0) {
  8470. + dev_err(&pdev->dev, "IRQ notification via DSM failed:"
  8471. + "unexpected result value (irq=%d, gpio=%d)\n",
  8472. + type, value);
  8473. + }
  8474. +
  8475. + mutex_unlock(&sdev->lock[type]);
  8476. + ACPI_FREE(result);
  8477. +}
  8478. +
  8479. +static irqreturn_t shps_handle_irq(int irq, void *data)
  8480. +{
  8481. + struct platform_device *pdev = data;
  8482. + struct shps_device *sdev = platform_get_drvdata(pdev);
  8483. + int type;
  8484. +
  8485. + // figure out which IRQ we're handling
  8486. + for (type = 0; type < SHPS_NUM_IRQS; type++)
  8487. + if (irq == sdev->irq[type])
  8488. + break;
  8489. +
  8490. + // we should have found our interrupt, if not: this is a bug
  8491. + if (WARN(type >= SHPS_NUM_IRQS, "invalid IRQ number: %d\n", irq))
  8492. + return IRQ_HANDLED;
  8493. +
  8494. + // forward interrupt to ACPI via DSM
  8495. + shps_dsm_notify_irq(pdev, type);
  8496. + return IRQ_HANDLED;
  8497. +}
  8498. +
  8499. +static int shps_setup_irq(struct platform_device *pdev, enum shps_irq_type type)
  8500. +{
  8501. + struct shps_device *sdev = platform_get_drvdata(pdev);
  8502. + struct gpio_desc *gpiod;
  8503. + acpi_handle handle = ACPI_HANDLE(&pdev->dev);
  8504. + const char *irq_name;
  8505. + const int dsm = SHPS_DSM_FN_IRQ_BASE_PRESENCE + type;
  8506. + int status, irq;
  8507. +
  8508. + // initialize as "not present"
  8509. + sdev->gpio[type] = NULL;
  8510. + sdev->irq[type] = SHPS_IRQ_NOT_PRESENT;
  8511. +
  8512. + // only set up interrupts that we actually need
  8513. + if (!acpi_check_dsm(handle, &shps_dsm_guid, SHPS_DSM_REVISION, BIT(dsm))) {
  8514. + dev_dbg(&pdev->dev, "IRQ notification via DSM not present (irq=%d)\n",
  8515. + type);
  8516. + return 0;
  8517. + }
  8518. +
  8519. + gpiod = devm_gpiod_get(&pdev->dev, shps_gpio_names[type], GPIOD_ASIS);
  8520. + if (IS_ERR(gpiod))
  8521. + return PTR_ERR(gpiod);
  8522. +
  8523. + irq = gpiod_to_irq(gpiod);
  8524. + if (irq < 0)
  8525. + return irq;
  8526. +
  8527. + irq_name = devm_kasprintf(&pdev->dev, GFP_KERNEL, "shps-irq-%d", type);
  8528. + if (!irq_name)
  8529. + return -ENOMEM;
  8530. +
  8531. + status = devm_request_threaded_irq(&pdev->dev, irq, NULL, shps_handle_irq,
  8532. + IRQF_ONESHOT | IRQF_TRIGGER_FALLING | IRQF_TRIGGER_RISING,
  8533. + irq_name, pdev);
  8534. + if (status)
  8535. + return status;
  8536. +
  8537. + dev_dbg(&pdev->dev, "set up irq %d as type %d\n", irq, type);
  8538. +
  8539. + sdev->gpio[type] = gpiod;
  8540. + sdev->irq[type] = irq;
  8541. +
  8542. + return 0;
  8543. +}
  8544. +
  8545. +static int surface_hotplug_probe(struct platform_device *pdev)
  8546. +{
  8547. + struct shps_device *sdev;
  8548. + int status, i;
  8549. +
  8550. + if (gpiod_count(&pdev->dev, NULL) < 0) {
  8551. + dev_err(&pdev->dev, "gpiod_count returned < 0\n");
  8552. + return -ENODEV;
  8553. + }
  8554. +
  8555. + status = devm_acpi_dev_add_driver_gpios(&pdev->dev, shps_acpi_gpios);
  8556. + if (status) {
  8557. + dev_err(&pdev->dev, "failed to add gpios: %d\n", status);
  8558. + return status;
  8559. + }
  8560. +
  8561. + sdev = devm_kzalloc(&pdev->dev, sizeof(*sdev), GFP_KERNEL);
  8562. + if (!sdev)
  8563. + return -ENOMEM;
  8564. +
  8565. + platform_set_drvdata(pdev, sdev);
  8566. +
  8567. + // set up IRQs
  8568. + for (i = 0; i < SHPS_NUM_IRQS; i++) {
  8569. + mutex_init(&sdev->lock[i]);
  8570. +
  8571. + status = shps_setup_irq(pdev, i);
  8572. + if (status) {
  8573. + dev_err(&pdev->dev, "failed to set up IRQ %d: %d\n",
  8574. + i, status);
  8575. + return status;
  8576. + }
  8577. + }
  8578. +
  8579. + // ensure everything is up-to-date
  8580. + for (i = 0; i < SHPS_NUM_IRQS; i++)
  8581. + if (sdev->irq[i] != SHPS_IRQ_NOT_PRESENT)
  8582. + shps_dsm_notify_irq(pdev, i);
  8583. +
  8584. + return 0;
  8585. +}
  8586. +
  8587. +static int surface_hotplug_remove(struct platform_device *pdev)
  8588. +{
  8589. + struct shps_device *sdev = platform_get_drvdata(pdev);
  8590. + int i;
  8591. +
  8592. + // ensure that IRQs have been fully handled and won't trigger any more
  8593. + for (i = 0; i < SHPS_NUM_IRQS; i++)
  8594. + if (sdev->irq[i] != SHPS_IRQ_NOT_PRESENT)
  8595. + disable_irq(sdev->irq[i]);
  8596. +
  8597. + return 0;
  8598. +}
  8599. +
  8600. +static const struct acpi_device_id surface_hotplug_acpi_match[] = {
  8601. + { "MSHW0153", 0 },
  8602. + { },
  8603. +};
  8604. +MODULE_DEVICE_TABLE(acpi, surface_hotplug_acpi_match);
  8605. +
  8606. +static struct platform_driver surface_hotplug_driver = {
  8607. + .probe = surface_hotplug_probe,
  8608. + .remove = surface_hotplug_remove,
  8609. + .driver = {
  8610. + .name = "surface_hotplug",
  8611. + .acpi_match_table = surface_hotplug_acpi_match,
  8612. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  8613. + },
  8614. +};
  8615. +module_platform_driver(surface_hotplug_driver);
  8616. +
  8617. +MODULE_AUTHOR("Maximilian Luz <luzmaximilian@gmail.com>");
  8618. +MODULE_DESCRIPTION("Surface Hot-Plug Signalling Driver for Surface Book Devices");
  8619. +MODULE_LICENSE("GPL");
  8620. diff --git a/drivers/misc/surface_aggregator/clients/surface_perfmode.c b/drivers/misc/surface_aggregator/clients/surface_perfmode.c
  8621. new file mode 100644
  8622. index 000000000000..e13f4995b28b
  8623. --- /dev/null
  8624. +++ b/drivers/misc/surface_aggregator/clients/surface_perfmode.c
  8625. @@ -0,0 +1,122 @@
  8626. +// SPDX-License-Identifier: GPL-2.0+
  8627. +/*
  8628. + * Surface performance-mode driver.
  8629. + *
  8630. + * Proides a user-space interface for the performance mode control provided by
  8631. + * the Surface System Aggregator Module (SSAM), influencing cooling behavior
  8632. + * of the device and potentially managing power limits.
  8633. + *
  8634. + * Copyright (C) 2019-2020 Maximilian Luz <luzmaximilian@gmail.com>
  8635. + */
  8636. +
  8637. +#include <asm/unaligned.h>
  8638. +#include <linux/kernel.h>
  8639. +#include <linux/module.h>
  8640. +#include <linux/sysfs.h>
  8641. +#include <linux/types.h>
  8642. +
  8643. +#include <linux/surface_aggregator/device.h>
  8644. +
  8645. +enum sam_perf_mode {
  8646. + SAM_PERF_MODE_NORMAL = 1,
  8647. + SAM_PERF_MODE_BATTERY = 2,
  8648. + SAM_PERF_MODE_PERF1 = 3,
  8649. + SAM_PERF_MODE_PERF2 = 4,
  8650. +
  8651. + __SAM_PERF_MODE__MIN = 1,
  8652. + __SAM_PERF_MODE__MAX = 4,
  8653. +};
  8654. +
  8655. +struct ssam_perf_info {
  8656. + __le32 mode;
  8657. + __le16 unknown1;
  8658. + __le16 unknown2;
  8659. +} __packed;
  8660. +
  8661. +static SSAM_DEFINE_SYNC_REQUEST_CL_R(ssam_tmp_perf_mode_get, struct ssam_perf_info, {
  8662. + .target_category = SSAM_SSH_TC_TMP,
  8663. + .command_id = 0x02,
  8664. +});
  8665. +
  8666. +static SSAM_DEFINE_SYNC_REQUEST_CL_W(__ssam_tmp_perf_mode_set, __le32, {
  8667. + .target_category = SSAM_SSH_TC_TMP,
  8668. + .command_id = 0x03,
  8669. +});
  8670. +
  8671. +static int ssam_tmp_perf_mode_set(struct ssam_device *sdev, u32 mode)
  8672. +{
  8673. + __le32 mode_le = cpu_to_le32(mode);
  8674. +
  8675. + if (mode < __SAM_PERF_MODE__MIN || mode > __SAM_PERF_MODE__MAX)
  8676. + return -EINVAL;
  8677. +
  8678. + return ssam_retry(__ssam_tmp_perf_mode_set, sdev, &mode_le);
  8679. +}
  8680. +
  8681. +static ssize_t perf_mode_show(struct device *dev, struct device_attribute *attr,
  8682. + char *data)
  8683. +{
  8684. + struct ssam_device *sdev = to_ssam_device(dev);
  8685. + struct ssam_perf_info info;
  8686. + int status;
  8687. +
  8688. + status = ssam_retry(ssam_tmp_perf_mode_get, sdev, &info);
  8689. + if (status) {
  8690. + dev_err(dev, "failed to get current performance mode: %d\n",
  8691. + status);
  8692. + return -EIO;
  8693. + }
  8694. +
  8695. + return sprintf(data, "%d\n", le32_to_cpu(info.mode));
  8696. +}
  8697. +
  8698. +static ssize_t perf_mode_store(struct device *dev, struct device_attribute *attr,
  8699. + const char *data, size_t count)
  8700. +{
  8701. + struct ssam_device *sdev = to_ssam_device(dev);
  8702. + int perf_mode;
  8703. + int status;
  8704. +
  8705. + status = kstrtoint(data, 0, &perf_mode);
  8706. + if (status < 0)
  8707. + return status;
  8708. +
  8709. + status = ssam_tmp_perf_mode_set(sdev, perf_mode);
  8710. + if (status < 0)
  8711. + return status;
  8712. +
  8713. + return count;
  8714. +}
  8715. +
  8716. +static const DEVICE_ATTR_RW(perf_mode);
  8717. +
  8718. +static int surface_sam_sid_perfmode_probe(struct ssam_device *sdev)
  8719. +{
  8720. + return sysfs_create_file(&sdev->dev.kobj, &dev_attr_perf_mode.attr);
  8721. +}
  8722. +
  8723. +static void surface_sam_sid_perfmode_remove(struct ssam_device *sdev)
  8724. +{
  8725. + sysfs_remove_file(&sdev->dev.kobj, &dev_attr_perf_mode.attr);
  8726. +}
  8727. +
  8728. +static const struct ssam_device_id ssam_perfmode_match[] = {
  8729. + { SSAM_SDEV(TMP, 0x01, 0x00, 0x01) },
  8730. + { },
  8731. +};
  8732. +MODULE_DEVICE_TABLE(ssam, ssam_perfmode_match);
  8733. +
  8734. +static struct ssam_device_driver surface_sam_sid_perfmode = {
  8735. + .probe = surface_sam_sid_perfmode_probe,
  8736. + .remove = surface_sam_sid_perfmode_remove,
  8737. + .match_table = ssam_perfmode_match,
  8738. + .driver = {
  8739. + .name = "surface_performance_mode",
  8740. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  8741. + },
  8742. +};
  8743. +module_ssam_device_driver(surface_sam_sid_perfmode);
  8744. +
  8745. +MODULE_AUTHOR("Maximilian Luz <luzmaximilian@gmail.com>");
  8746. +MODULE_DESCRIPTION("Performance mode interface for Surface System Aggregator Module");
  8747. +MODULE_LICENSE("GPL");
  8748. diff --git a/drivers/misc/surface_aggregator/controller.c b/drivers/misc/surface_aggregator/controller.c
  8749. new file mode 100644
  8750. index 000000000000..feee7c7c5945
  8751. --- /dev/null
  8752. +++ b/drivers/misc/surface_aggregator/controller.c
  8753. @@ -0,0 +1,2557 @@
  8754. +// SPDX-License-Identifier: GPL-2.0+
  8755. +/*
  8756. + * Main SSAM/SSH controller structure and functionality.
  8757. + *
  8758. + * Copyright (C) 2019-2020 Maximilian Luz <luzmaximilian@gmail.com>
  8759. + */
  8760. +
  8761. +#include <linux/acpi.h>
  8762. +#include <linux/atomic.h>
  8763. +#include <linux/completion.h>
  8764. +#include <linux/gpio/consumer.h>
  8765. +#include <linux/interrupt.h>
  8766. +#include <linux/kref.h>
  8767. +#include <linux/list.h>
  8768. +#include <linux/mutex.h>
  8769. +#include <linux/rbtree.h>
  8770. +#include <linux/rwsem.h>
  8771. +#include <linux/serdev.h>
  8772. +#include <linux/slab.h>
  8773. +#include <linux/spinlock.h>
  8774. +#include <linux/srcu.h>
  8775. +#include <linux/types.h>
  8776. +#include <linux/workqueue.h>
  8777. +
  8778. +#include <linux/surface_aggregator/controller.h>
  8779. +#include <linux/surface_aggregator/serial_hub.h>
  8780. +
  8781. +#include "controller.h"
  8782. +#include "ssh_msgb.h"
  8783. +#include "ssh_request_layer.h"
  8784. +
  8785. +#include "trace.h"
  8786. +
  8787. +
  8788. +/* -- Safe counters. -------------------------------------------------------- */
  8789. +
  8790. +/**
  8791. + * ssh_seq_reset() - Reset/initialize sequence ID counter.
  8792. + * @c: The counter to reset.
  8793. + */
  8794. +static void ssh_seq_reset(struct ssh_seq_counter *c)
  8795. +{
  8796. + WRITE_ONCE(c->value, 0);
  8797. +}
  8798. +
  8799. +/**
  8800. + * ssh_seq_next() - Get next sequence ID.
  8801. + * @c: The counter providing the sequence IDs.
  8802. + *
  8803. + * Return: Retunrs the next sequence ID of the counter.
  8804. + */
  8805. +static u8 ssh_seq_next(struct ssh_seq_counter *c)
  8806. +{
  8807. + u8 old = READ_ONCE(c->value);
  8808. + u8 new = old + 1;
  8809. + u8 ret;
  8810. +
  8811. + while (unlikely((ret = cmpxchg(&c->value, old, new)) != old)) {
  8812. + old = ret;
  8813. + new = old + 1;
  8814. + }
  8815. +
  8816. + return old;
  8817. +}
  8818. +
  8819. +/**
  8820. + * ssh_rqid_reset() - Reset/initialize request ID counter.
  8821. + * @c: The counter to reset.
  8822. + */
  8823. +static void ssh_rqid_reset(struct ssh_rqid_counter *c)
  8824. +{
  8825. + WRITE_ONCE(c->value, 0);
  8826. +}
  8827. +
  8828. +/**
  8829. + * ssh_rqid_next() - Get next request ID.
  8830. + * @c: The counter providing the request IDs.
  8831. + *
  8832. + * Return: Returns the next request ID of the counter, skipping any reserved
  8833. + * request IDs.
  8834. + */
  8835. +static u16 ssh_rqid_next(struct ssh_rqid_counter *c)
  8836. +{
  8837. + u16 old = READ_ONCE(c->value);
  8838. + u16 new = ssh_rqid_next_valid(old);
  8839. + u16 ret;
  8840. +
  8841. + while (unlikely((ret = cmpxchg(&c->value, old, new)) != old)) {
  8842. + old = ret;
  8843. + new = ssh_rqid_next_valid(old);
  8844. + }
  8845. +
  8846. + return old;
  8847. +}
  8848. +
  8849. +
  8850. +/* -- Event notifier/callbacks. --------------------------------------------- */
  8851. +/*
  8852. + * The notifier system is based on linux/notifier.h, specifically the SRCU
  8853. + * implementation. The difference to that is, that some bits of the notifier
  8854. + * call return value can be tracked across multiple calls. This is done so that
  8855. + * handling of events can be tracked and a warning can be issued in case an
  8856. + * event goes unhandled. The idea of that waring is that it should help discover
  8857. + * and identify new/currently unimplemented features.
  8858. + */
  8859. +
  8860. +
  8861. +/**
  8862. + * ssam_event_matches_notifier() - Test if an event matches a notifier;
  8863. + * @notif: The event notifier to test against.
  8864. + * @event: The event to test.
  8865. + *
  8866. + * Return: Returns %true iff the given event matches the given notifier
  8867. + * according to the rules set in the notifier's event mask, %false otherwise.
  8868. + */
  8869. +static bool ssam_event_matches_notifier(
  8870. + const struct ssam_event_notifier *notif,
  8871. + const struct ssam_event *event)
  8872. +{
  8873. + bool match = notif->event.id.target_category == event->target_category;
  8874. +
  8875. + if (notif->event.mask & SSAM_EVENT_MASK_TARGET)
  8876. + match &= notif->event.reg.target_id == event->target_id;
  8877. +
  8878. + if (notif->event.mask & SSAM_EVENT_MASK_INSTANCE)
  8879. + match &= notif->event.id.instance == event->instance_id;
  8880. +
  8881. + return match;
  8882. +}
  8883. +
  8884. +/**
  8885. + * ssam_nfblk_call_chain() - Call event notifier callbacks of the given chain.
  8886. + * @nh: The notifier head for which the notifier callbacks should be called.
  8887. + * @event: The event data provided to the callbacks.
  8888. + *
  8889. + * Call all registered notifier callbacks in order of their priority until
  8890. + * either no notifier is left or a notifier returns a value with the
  8891. + * %SSAM_NOTIF_STOP bit set. Note that this bit is automatically set via
  8892. + * ssam_notifier_from_errno() on any non-zero error value.
  8893. + *
  8894. + * Return: Returns the notifier status value, which contains the notifier
  8895. + * status bits (%SSAM_NOTIF_HANDLED and %SSAM_NOTIF_STOP) as well as a
  8896. + * potential error value returned from the last executed notifier callback.
  8897. + * Use ssam_notifier_to_errno() to convert this value to the original error
  8898. + * value.
  8899. + */
  8900. +static int ssam_nfblk_call_chain(struct ssam_nf_head *nh, struct ssam_event *event)
  8901. +{
  8902. + struct ssam_notifier_block *nb, *next_nb;
  8903. + struct ssam_event_notifier *nf;
  8904. + int ret = 0, idx;
  8905. +
  8906. + idx = srcu_read_lock(&nh->srcu);
  8907. +
  8908. + nb = rcu_dereference_raw(nh->head);
  8909. + while (nb) {
  8910. + nf = container_of(nb, struct ssam_event_notifier, base);
  8911. + next_nb = rcu_dereference_raw(nb->next);
  8912. +
  8913. + if (ssam_event_matches_notifier(nf, event)) {
  8914. + ret = (ret & SSAM_NOTIF_STATE_MASK) | nb->fn(nf, event);
  8915. + if (ret & SSAM_NOTIF_STOP)
  8916. + break;
  8917. + }
  8918. +
  8919. + nb = next_nb;
  8920. + }
  8921. +
  8922. + srcu_read_unlock(&nh->srcu, idx);
  8923. + return ret;
  8924. +}
  8925. +
  8926. +/**
  8927. + * __ssam_nfblk_insert() - Insert a new notifier block into the given notifier
  8928. + * list.
  8929. + * @nh: The notifier head into which the block should be inserted.
  8930. + * @nb: The notifier block to add.
  8931. + *
  8932. + * Note: This function must be synchronized by the caller with respect to other
  8933. + * insert and/or remove calls.
  8934. + *
  8935. + * Return: Returns zero on success, %-EINVAL if the notifier block has already
  8936. + * been registered.
  8937. + */
  8938. +static int __ssam_nfblk_insert(struct ssam_nf_head *nh, struct ssam_notifier_block *nb)
  8939. +{
  8940. + struct ssam_notifier_block **link = &nh->head;
  8941. +
  8942. + while ((*link) != NULL) {
  8943. + if (unlikely((*link) == nb)) {
  8944. + WARN(1, "double register detected");
  8945. + return -EINVAL;
  8946. + }
  8947. +
  8948. + if (nb->priority > (*link)->priority)
  8949. + break;
  8950. +
  8951. + link = &((*link)->next);
  8952. + }
  8953. +
  8954. + nb->next = *link;
  8955. + rcu_assign_pointer(*link, nb);
  8956. +
  8957. + return 0;
  8958. +}
  8959. +
  8960. +/**
  8961. + * __ssam_nfblk_find_link() - Find a notifier block link on the given list.
  8962. + * @nh: The notifier head on wich the search should be conducted.
  8963. + * @nb: The notifier block to search for.
  8964. + *
  8965. + * Note: This function must be synchronized by the caller with respect to
  8966. + * insert and/or remove calls.
  8967. + *
  8968. + * Return: Returns a pointer to the link (i.e. pointer pointing) to the given
  8969. + * notifier block, from the previous node in the list, or %NULL if the given
  8970. + * notifier block is not contained in the notifier list.
  8971. + */
  8972. +static struct ssam_notifier_block **__ssam_nfblk_find_link(
  8973. + struct ssam_nf_head *nh, struct ssam_notifier_block *nb)
  8974. +{
  8975. + struct ssam_notifier_block **link = &nh->head;
  8976. +
  8977. + while ((*link) != NULL) {
  8978. + if ((*link) == nb)
  8979. + return link;
  8980. +
  8981. + link = &((*link)->next);
  8982. + }
  8983. +
  8984. + return NULL;
  8985. +}
  8986. +
  8987. +/**
  8988. + * __ssam_nfblk_erase() - Erase a notifier block link in the given notifier
  8989. + * list.
  8990. + * @link: The link to be erased.
  8991. + *
  8992. + * Note: This function must be synchronized by the caller with respect to
  8993. + * other insert and/or remove/erase/find calls. The caller _must_ ensure SRCU
  8994. + * synchronization by calling synchronize_srcu() with ``nh->srcu`` after
  8995. + * leaving the critical section, to ensure that the removed notifier block is
  8996. + * not in use any more.
  8997. + */
  8998. +static void __ssam_nfblk_erase(struct ssam_notifier_block **link)
  8999. +{
  9000. + rcu_assign_pointer(*link, (*link)->next);
  9001. +}
  9002. +
  9003. +
  9004. +/**
  9005. + * __ssam_nfblk_remove() - Remove a notifier block from the given notifier list.
  9006. + * @nh: The notifier head from which the block should be removed.
  9007. + * @nb: The notifier block to remove.
  9008. + *
  9009. + * Note: This function must be synchronized by the caller with respect to
  9010. + * other insert and/or remove calls. On success, the caller *must* ensure SRCU
  9011. + * synchronization by calling synchronize_srcu() with ``nh->srcu`` after
  9012. + * leaving the critical section, to ensure that the removed notifier block is
  9013. + * not in use any more.
  9014. + *
  9015. + * Return: Returns zero on success, %-ENOENT if the specified notifier block
  9016. + * could not be found on the notifier list.
  9017. + */
  9018. +static int __ssam_nfblk_remove(struct ssam_nf_head *nh,
  9019. + struct ssam_notifier_block *nb)
  9020. +{
  9021. + struct ssam_notifier_block **link;
  9022. +
  9023. + link = __ssam_nfblk_find_link(nh, nb);
  9024. + if (!link)
  9025. + return -ENOENT;
  9026. +
  9027. + __ssam_nfblk_erase(link);
  9028. + return 0;
  9029. +}
  9030. +
  9031. +/**
  9032. + * ssam_nf_head_init() - Initialize the given notifier head.
  9033. + * @nh: The notifier head to initialize.
  9034. + */
  9035. +static int ssam_nf_head_init(struct ssam_nf_head *nh)
  9036. +{
  9037. + int status;
  9038. +
  9039. + status = init_srcu_struct(&nh->srcu);
  9040. + if (status)
  9041. + return status;
  9042. +
  9043. + nh->head = NULL;
  9044. + return 0;
  9045. +}
  9046. +
  9047. +/**
  9048. + * ssam_nf_head_destroy() - Deinitialize the given notifier head.
  9049. + * @nh: The notifier head to deinitialize.
  9050. + */
  9051. +static void ssam_nf_head_destroy(struct ssam_nf_head *nh)
  9052. +{
  9053. + cleanup_srcu_struct(&nh->srcu);
  9054. +}
  9055. +
  9056. +
  9057. +/* -- Event/notification registry. ------------------------------------------ */
  9058. +
  9059. +/**
  9060. + * struct ssam_nf_refcount_key - Key used for event activation reference
  9061. + * counting.
  9062. + * @reg: The registry via which the event is enabled/disabled.
  9063. + * @id: The ID uniquely describing the event.
  9064. + */
  9065. +struct ssam_nf_refcount_key {
  9066. + struct ssam_event_registry reg;
  9067. + struct ssam_event_id id;
  9068. +};
  9069. +
  9070. +/**
  9071. + * struct ssam_nf_refcount_entry - RB-tree entry for referecnce counting event
  9072. + * activations.
  9073. + * @node: The node of this entry in the rb-tree.
  9074. + * @key: The key of the event.
  9075. + * @refcount: The reference-count of the event.
  9076. + * @flags: The flags used when enabling the event.
  9077. + */
  9078. +struct ssam_nf_refcount_entry {
  9079. + struct rb_node node;
  9080. + struct ssam_nf_refcount_key key;
  9081. + int refcount;
  9082. + u8 flags;
  9083. +};
  9084. +
  9085. +
  9086. +/**
  9087. + * ssam_nf_refcount_inc() - Increment reference-/activation-count of the given
  9088. + * event.
  9089. + * @nf: The notifier system reference.
  9090. + * @reg: The registry used to enable/disable the event.
  9091. + * @id: The event ID.
  9092. + *
  9093. + * Increments the reference-/activation-count associated with the specified
  9094. + * event type/ID, allocating a new entry for this event ID if necessary. A
  9095. + * newly allocated entry will have a refcount of one.
  9096. + *
  9097. + * Return: Returns the refcount entry on success. Returns ``ERR_PTR(-ENOSPC)``
  9098. + * if there have already been %INT_MAX events of the specified ID and type
  9099. + * registered, or ``ERR_PTR(-ENOMEM)`` if the entry could not be allocated.
  9100. + */
  9101. +static struct ssam_nf_refcount_entry *ssam_nf_refcount_inc(
  9102. + struct ssam_nf *nf, struct ssam_event_registry reg,
  9103. + struct ssam_event_id id)
  9104. +{
  9105. + struct ssam_nf_refcount_entry *entry;
  9106. + struct ssam_nf_refcount_key key;
  9107. + struct rb_node **link = &nf->refcount.rb_node;
  9108. + struct rb_node *parent = NULL;
  9109. + int cmp;
  9110. +
  9111. + key.reg = reg;
  9112. + key.id = id;
  9113. +
  9114. + while (*link) {
  9115. + entry = rb_entry(*link, struct ssam_nf_refcount_entry, node);
  9116. + parent = *link;
  9117. +
  9118. + cmp = memcmp(&key, &entry->key, sizeof(key));
  9119. + if (cmp < 0) {
  9120. + link = &(*link)->rb_left;
  9121. + } else if (cmp > 0) {
  9122. + link = &(*link)->rb_right;
  9123. + } else if (entry->refcount < INT_MAX) {
  9124. + entry->refcount++;
  9125. + return entry;
  9126. + } else {
  9127. + return ERR_PTR(-ENOSPC);
  9128. + }
  9129. + }
  9130. +
  9131. + entry = kzalloc(sizeof(*entry), GFP_KERNEL);
  9132. + if (!entry)
  9133. + return ERR_PTR(-ENOMEM);
  9134. +
  9135. + entry->key = key;
  9136. + entry->refcount = 1;
  9137. +
  9138. + rb_link_node(&entry->node, parent, link);
  9139. + rb_insert_color(&entry->node, &nf->refcount);
  9140. +
  9141. + return entry;
  9142. +}
  9143. +
  9144. +/**
  9145. + * ssam_nf_refcount_dec() - Decrement reference-/activation-count of the given
  9146. + * event.
  9147. + * @nf: The notifier system reference.
  9148. + * @reg: The registry used to enable/disable the event.
  9149. + * @id: The event ID.
  9150. + *
  9151. + * Decrements the reference-/activation-count of the specified event,
  9152. + * returning its entry. If the returned entry has a refcount of zero, the
  9153. + * caller is responsible for freeing it using kfree().
  9154. + *
  9155. + * Return: Returns the refcount entry on success or %NULL if the entry has not
  9156. + * been found.
  9157. + */
  9158. +static struct ssam_nf_refcount_entry *ssam_nf_refcount_dec(
  9159. + struct ssam_nf *nf, struct ssam_event_registry reg,
  9160. + struct ssam_event_id id)
  9161. +{
  9162. + struct ssam_nf_refcount_entry *entry;
  9163. + struct ssam_nf_refcount_key key;
  9164. + struct rb_node *node = nf->refcount.rb_node;
  9165. + int cmp;
  9166. +
  9167. + key.reg = reg;
  9168. + key.id = id;
  9169. +
  9170. + while (node) {
  9171. + entry = rb_entry(node, struct ssam_nf_refcount_entry, node);
  9172. +
  9173. + cmp = memcmp(&key, &entry->key, sizeof(key));
  9174. + if (cmp < 0) {
  9175. + node = node->rb_left;
  9176. + } else if (cmp > 0) {
  9177. + node = node->rb_right;
  9178. + } else {
  9179. + entry->refcount--;
  9180. + if (entry->refcount == 0)
  9181. + rb_erase(&entry->node, &nf->refcount);
  9182. +
  9183. + return entry;
  9184. + }
  9185. + }
  9186. +
  9187. + return NULL;
  9188. +}
  9189. +
  9190. +/**
  9191. + * ssam_nf_refcount_empty() - Test if the notification system has any
  9192. + * enabled/active events.
  9193. + * @nf: The notification system.
  9194. + */
  9195. +static bool ssam_nf_refcount_empty(struct ssam_nf *nf)
  9196. +{
  9197. + return RB_EMPTY_ROOT(&nf->refcount);
  9198. +}
  9199. +
  9200. +/**
  9201. + * ssam_nf_call() - Call notification callbacks for the provided event.
  9202. + * @nf: The notifier system
  9203. + * @dev: The associated device, only used for logging.
  9204. + * @rqid: The request ID of the event.
  9205. + * @event: The event provided to the callbacks.
  9206. + *
  9207. + * Executa registered callbacks in order of their priority until either no
  9208. + * callback is left or a callback returned a value with the %SSAM_NOTIF_STOP
  9209. + * bit set. Note that this bit is set automatically when converting non.zero
  9210. + * error values via ssam_notifier_from_errno() to notifier values.
  9211. + *
  9212. + * Also note that any callback that could handle an event should return a value
  9213. + * with bit %SSAM_NOTIF_HANDLED set, indicating that the event does not go
  9214. + * unhandled/ignored. In case no registered callback could handle an event,
  9215. + * this function will emit a warning.
  9216. + *
  9217. + * In case a callback failed, this function will emit an error message.
  9218. + */
  9219. +static void ssam_nf_call(struct ssam_nf *nf, struct device *dev, u16 rqid,
  9220. + struct ssam_event *event)
  9221. +{
  9222. + struct ssam_nf_head *nf_head;
  9223. + int status, nf_ret;
  9224. +
  9225. + if (!ssh_rqid_is_event(rqid)) {
  9226. + dev_warn(dev, "event: unsupported rqid: 0x%04x\n", rqid);
  9227. + return;
  9228. + }
  9229. +
  9230. + nf_head = &nf->head[ssh_rqid_to_event(rqid)];
  9231. + nf_ret = ssam_nfblk_call_chain(nf_head, event);
  9232. + status = ssam_notifier_to_errno(nf_ret);
  9233. +
  9234. + if (status < 0) {
  9235. + dev_err(dev, "event: error handling event: %d "
  9236. + "(tc: 0x%02x, tid: 0x%02x, cid: 0x%02x, iid: 0x%02x)\n",
  9237. + status, event->target_category, event->target_id,
  9238. + event->command_id, event->instance_id);
  9239. + }
  9240. +
  9241. + if (!(nf_ret & SSAM_NOTIF_HANDLED)) {
  9242. + dev_warn(dev, "event: unhandled event (rqid: 0x%02x, "
  9243. + "tc: 0x%02x, tid: 0x%02x, cid: 0x%02x, iid: 0x%02x)\n",
  9244. + rqid, event->target_category, event->target_id,
  9245. + event->command_id, event->instance_id);
  9246. + }
  9247. +}
  9248. +
  9249. +/**
  9250. + * ssam_nf_init() - Initialize the notifier system.
  9251. + * @nf: The notifier system to initialize.
  9252. + */
  9253. +static int ssam_nf_init(struct ssam_nf *nf)
  9254. +{
  9255. + int i, status;
  9256. +
  9257. + for (i = 0; i < SSH_NUM_EVENTS; i++) {
  9258. + status = ssam_nf_head_init(&nf->head[i]);
  9259. + if (status)
  9260. + break;
  9261. + }
  9262. +
  9263. + if (status) {
  9264. + for (i = i - 1; i >= 0; i--)
  9265. + ssam_nf_head_destroy(&nf->head[i]);
  9266. +
  9267. + return status;
  9268. + }
  9269. +
  9270. + mutex_init(&nf->lock);
  9271. + return 0;
  9272. +}
  9273. +
  9274. +/**
  9275. + * ssam_nf_destroy() - Deinitialize the notifier system.
  9276. + * @nf: The notifier system to deinitialize.
  9277. + */
  9278. +static void ssam_nf_destroy(struct ssam_nf *nf)
  9279. +{
  9280. + int i;
  9281. +
  9282. + for (i = 0; i < SSH_NUM_EVENTS; i++)
  9283. + ssam_nf_head_destroy(&nf->head[i]);
  9284. +
  9285. + mutex_destroy(&nf->lock);
  9286. +}
  9287. +
  9288. +
  9289. +/* -- Event/async request completion system. -------------------------------- */
  9290. +
  9291. +#define SSAM_CPLT_WQ_NAME "ssam_cpltq"
  9292. +
  9293. +/*
  9294. + * SSAM_EVENT_ITEM_CACHE_PAYLOAD_LEN - Maximum payload length for a cached
  9295. + * &struct ssam_event_item.
  9296. + *
  9297. + * This length has been chosen to be accommodate standard touchpad and
  9298. + * keyboard input events. Events with larger payloads will be allocated
  9299. + * separately.
  9300. + */
  9301. +#define SSAM_EVENT_ITEM_CACHE_PAYLOAD_LEN 32
  9302. +
  9303. +static struct kmem_cache *ssam_event_item_cache;
  9304. +
  9305. +/**
  9306. + * ssam_event_item_cache_init() - Initialize the event item cache.
  9307. + */
  9308. +int ssam_event_item_cache_init(void)
  9309. +{
  9310. + const unsigned int size = sizeof(struct ssam_event_item)
  9311. + + SSAM_EVENT_ITEM_CACHE_PAYLOAD_LEN;
  9312. + const unsigned int align = __alignof__(struct ssam_event_item);
  9313. + struct kmem_cache *cache;
  9314. +
  9315. + cache = kmem_cache_create("ssam_event_item", size, align, 0, NULL);
  9316. + if (!cache)
  9317. + return -ENOMEM;
  9318. +
  9319. + ssam_event_item_cache = cache;
  9320. + return 0;
  9321. +}
  9322. +
  9323. +/**
  9324. + * ssam_event_item_cache_destroy() - Deinitialize the event item cache.
  9325. + */
  9326. +void ssam_event_item_cache_destroy(void)
  9327. +{
  9328. + kmem_cache_destroy(ssam_event_item_cache);
  9329. + ssam_event_item_cache = NULL;
  9330. +}
  9331. +
  9332. +static void __ssam_event_item_free_cached(struct ssam_event_item *item)
  9333. +{
  9334. + kmem_cache_free(ssam_event_item_cache, item);
  9335. +}
  9336. +
  9337. +static void __ssam_event_item_free_generic(struct ssam_event_item *item)
  9338. +{
  9339. + kfree(item);
  9340. +}
  9341. +
  9342. +/**
  9343. + * ssam_event_item_free() - Free the provided event item.
  9344. + * @item: The event item to free.
  9345. + */
  9346. +static void ssam_event_item_free(struct ssam_event_item *item)
  9347. +{
  9348. + trace_ssam_event_item_free(item);
  9349. + item->ops.free(item);
  9350. +}
  9351. +
  9352. +/**
  9353. + * ssam_event_item_alloc() - Allocate an event item with the given payload size.
  9354. + * @len: The event payload length.
  9355. + * @flags: The flags used for allocation.
  9356. + *
  9357. + * Allocate an event item with the given payload size, preferring allocation
  9358. + * from the event item cache if the payload is small enough (i.e. smaller than
  9359. + * %SSAM_EVENT_ITEM_CACHE_PAYLOAD_LEN). Sets the item operations and payload
  9360. + * length values. The item free callback (``ops.free``) should not be
  9361. + * overwritten after this call.
  9362. + *
  9363. + * Return: Returns the newly allocated event item.
  9364. + */
  9365. +static struct ssam_event_item *ssam_event_item_alloc(size_t len, gfp_t flags)
  9366. +{
  9367. + struct ssam_event_item *item;
  9368. +
  9369. + if (len <= SSAM_EVENT_ITEM_CACHE_PAYLOAD_LEN) {
  9370. + item = kmem_cache_alloc(ssam_event_item_cache, GFP_KERNEL);
  9371. + if (!item)
  9372. + return NULL;
  9373. +
  9374. + item->ops.free = __ssam_event_item_free_cached;
  9375. + } else {
  9376. + item = kzalloc(sizeof(*item) + len, GFP_KERNEL);
  9377. + if (!item)
  9378. + return NULL;
  9379. +
  9380. + item->ops.free = __ssam_event_item_free_generic;
  9381. + }
  9382. +
  9383. + item->event.length = len;
  9384. +
  9385. + trace_ssam_event_item_alloc(item, len);
  9386. + return item;
  9387. +}
  9388. +
  9389. +
  9390. +/**
  9391. + * ssam_event_queue_push() - Push an event item to the event queue.
  9392. + * @q: The event queue.
  9393. + * @item: The item to add.
  9394. + */
  9395. +static void ssam_event_queue_push(struct ssam_event_queue *q,
  9396. + struct ssam_event_item *item)
  9397. +{
  9398. + spin_lock(&q->lock);
  9399. + list_add_tail(&item->node, &q->head);
  9400. + spin_unlock(&q->lock);
  9401. +}
  9402. +
  9403. +/**
  9404. + * ssam_event_queue_pop() - Pop the next event item from the event queue.
  9405. + * @q: The event queue.
  9406. + *
  9407. + * Returns and removes the next event item from the queue. Returns %NULL If
  9408. + * there is no event item left.
  9409. + */
  9410. +static struct ssam_event_item *ssam_event_queue_pop(struct ssam_event_queue *q)
  9411. +{
  9412. + struct ssam_event_item *item;
  9413. +
  9414. + spin_lock(&q->lock);
  9415. + item = list_first_entry_or_null(&q->head, struct ssam_event_item, node);
  9416. + if (item)
  9417. + list_del(&item->node);
  9418. + spin_unlock(&q->lock);
  9419. +
  9420. + return item;
  9421. +}
  9422. +
  9423. +/**
  9424. + * ssam_event_queue_is_empty() - Check if the event queue is empty.
  9425. + * @q: The event queue.
  9426. + */
  9427. +static bool ssam_event_queue_is_empty(struct ssam_event_queue *q)
  9428. +{
  9429. + bool empty;
  9430. +
  9431. + spin_lock(&q->lock);
  9432. + empty = list_empty(&q->head);
  9433. + spin_unlock(&q->lock);
  9434. +
  9435. + return empty;
  9436. +}
  9437. +
  9438. +/**
  9439. + * ssam_cplt_get_event_queue() - Get the event queue for the given parameters.
  9440. + * @cplt: The completion system on which to look for the queue.
  9441. + * @tid: The target ID of the queue.
  9442. + * @rqid: The request ID representing the event ID for which to get the queue.
  9443. + *
  9444. + * Return: Returns the event queue corresponding to the event type described
  9445. + * by the given parameters. If the request ID does not represent an event,
  9446. + * this function returns %NULL. If the target ID is not supported, this
  9447. + * function will fall back to the default target ID (``tid = 1``).
  9448. + */
  9449. +static struct ssam_event_queue *ssam_cplt_get_event_queue(
  9450. + struct ssam_cplt *cplt, u8 tid, u16 rqid)
  9451. +{
  9452. + u16 event = ssh_rqid_to_event(rqid);
  9453. + u16 tidx = ssh_tid_to_index(tid);
  9454. +
  9455. + if (!ssh_rqid_is_event(rqid)) {
  9456. + dev_err(cplt->dev, "event: unsupported request ID: 0x%04x\n", rqid);
  9457. + return NULL;
  9458. + }
  9459. +
  9460. + if (!ssh_tid_is_valid(tid)) {
  9461. + dev_warn(cplt->dev, "event: unsupported target ID: %u\n", tid);
  9462. + tidx = 0;
  9463. + }
  9464. +
  9465. + return &cplt->event.target[tidx].queue[event];
  9466. +}
  9467. +
  9468. +/**
  9469. + * ssam_cplt_submit() - Submit a work item to the compeltion system workqueue.
  9470. + * @cplt: The completion system.
  9471. + * @work: The work item to submit.
  9472. + */
  9473. +static bool ssam_cplt_submit(struct ssam_cplt *cplt, struct work_struct *work)
  9474. +{
  9475. + return queue_work(cplt->wq, work);
  9476. +}
  9477. +
  9478. +/**
  9479. + * ssam_cplt_submit_event() - Submit an event to the completion system.
  9480. + * @cplt: The completion system.
  9481. + * @item: The event item to submit.
  9482. + *
  9483. + * Submits the event to the completion system by queuing it on the event item
  9484. + * queue and queuing the respective event queue work item on the completion
  9485. + * workqueue, which will eventually complete the event.
  9486. + *
  9487. + * Return: Returns zero on success, %-EINVAL if there is no event queue that
  9488. + * can handle the given event item.
  9489. + */
  9490. +static int ssam_cplt_submit_event(struct ssam_cplt *cplt,
  9491. + struct ssam_event_item *item)
  9492. +{
  9493. + struct ssam_event_queue *evq;
  9494. +
  9495. + evq = ssam_cplt_get_event_queue(cplt, item->event.target_id, item->rqid);
  9496. + if (!evq)
  9497. + return -EINVAL;
  9498. +
  9499. + ssam_event_queue_push(evq, item);
  9500. + ssam_cplt_submit(cplt, &evq->work);
  9501. + return 0;
  9502. +}
  9503. +
  9504. +/**
  9505. + * ssam_cplt_flush() - Flush the completion system.
  9506. + * @cplt: The completion system.
  9507. + *
  9508. + * Flush the completion system by waiting until all currently submitted work
  9509. + * items have been completed.
  9510. + *
  9511. + * Note: This function does not guarantee that all events will have been
  9512. + * handled once this call terminates. In case of a larger number of
  9513. + * to-be-completed events, the event queue work function may re-schedule its
  9514. + * work item, which this flush operation will ignore.
  9515. + *
  9516. + * This operation is only intended to, during normal operation prior to
  9517. + * shutdown, try to complete most events and requests to get them out of the
  9518. + * system while the system is still fully operational. It does not aim to
  9519. + * provide any guraantee that all of them have been handled.
  9520. + */
  9521. +static void ssam_cplt_flush(struct ssam_cplt *cplt)
  9522. +{
  9523. + flush_workqueue(cplt->wq);
  9524. +}
  9525. +
  9526. +static void ssam_event_queue_work_fn(struct work_struct *work)
  9527. +{
  9528. + struct ssam_event_queue *queue;
  9529. + struct ssam_event_item *item;
  9530. + struct ssam_nf *nf;
  9531. + struct device *dev;
  9532. + int i;
  9533. +
  9534. + queue = container_of(work, struct ssam_event_queue, work);
  9535. + nf = &queue->cplt->event.notif;
  9536. + dev = queue->cplt->dev;
  9537. +
  9538. + // limit number of processed events to avoid livelocking
  9539. + for (i = 0; i < 10; i++) {
  9540. + item = ssam_event_queue_pop(queue);
  9541. + if (item == NULL)
  9542. + return;
  9543. +
  9544. + ssam_nf_call(nf, dev, item->rqid, &item->event);
  9545. + ssam_event_item_free(item);
  9546. + }
  9547. +
  9548. + if (!ssam_event_queue_is_empty(queue))
  9549. + ssam_cplt_submit(queue->cplt, &queue->work);
  9550. +}
  9551. +
  9552. +/**
  9553. + * ssam_event_queue_init() - Initialize an event queue.
  9554. + * @cplt: The completion system on which the queue resides.
  9555. + * @evq: The event queue to initialize.
  9556. + */
  9557. +static void ssam_event_queue_init(struct ssam_cplt *cplt,
  9558. + struct ssam_event_queue *evq)
  9559. +{
  9560. + evq->cplt = cplt;
  9561. + spin_lock_init(&evq->lock);
  9562. + INIT_LIST_HEAD(&evq->head);
  9563. + INIT_WORK(&evq->work, ssam_event_queue_work_fn);
  9564. +}
  9565. +
  9566. +/**
  9567. + * ssam_cplt_init() - Initialize completion system.
  9568. + * @cplt: The completion system to initialize.
  9569. + * @dev: The device used for logging.
  9570. + */
  9571. +static int ssam_cplt_init(struct ssam_cplt *cplt, struct device *dev)
  9572. +{
  9573. + struct ssam_event_target *target;
  9574. + int status, c, i;
  9575. +
  9576. + cplt->dev = dev;
  9577. +
  9578. + cplt->wq = create_workqueue(SSAM_CPLT_WQ_NAME);
  9579. + if (!cplt->wq)
  9580. + return -ENOMEM;
  9581. +
  9582. + for (c = 0; c < ARRAY_SIZE(cplt->event.target); c++) {
  9583. + target = &cplt->event.target[c];
  9584. +
  9585. + for (i = 0; i < ARRAY_SIZE(target->queue); i++)
  9586. + ssam_event_queue_init(cplt, &target->queue[i]);
  9587. + }
  9588. +
  9589. + status = ssam_nf_init(&cplt->event.notif);
  9590. + if (status)
  9591. + destroy_workqueue(cplt->wq);
  9592. +
  9593. + return status;
  9594. +}
  9595. +
  9596. +/**
  9597. + * ssam_cplt_destroy() - Deinitialize the completion system.
  9598. + * @cplt: The completion system to deinitialize.
  9599. + *
  9600. + * Deinitialize the given completion system and ensure that all pending, i.e.
  9601. + * yet-to-be-completed, event items and requests have been handled.
  9602. + */
  9603. +static void ssam_cplt_destroy(struct ssam_cplt *cplt)
  9604. +{
  9605. + /*
  9606. + * Note: destroy_workqueue ensures that all currently queued work will
  9607. + * be fully completed and the workqueue drained. This means that this
  9608. + * call will inherently also free any queued ssam_event_items, thus we
  9609. + * don't have to take care of that here explicitly.
  9610. + */
  9611. + destroy_workqueue(cplt->wq);
  9612. + ssam_nf_destroy(&cplt->event.notif);
  9613. +}
  9614. +
  9615. +
  9616. +/* -- Main SSAM device structures. ------------------------------------------ */
  9617. +
  9618. +/**
  9619. + * ssam_controller_device() - Get the &struct device associated with this
  9620. + * controller.
  9621. + * @c: The controller for which to get the device.
  9622. + *
  9623. + * Return: Returns the &struct device associated with this controller,
  9624. + * providing its lower-level transport.
  9625. + */
  9626. +struct device *ssam_controller_device(struct ssam_controller *c)
  9627. +{
  9628. + return ssh_rtl_get_device(&c->rtl);
  9629. +}
  9630. +EXPORT_SYMBOL_GPL(ssam_controller_device);
  9631. +
  9632. +static void __ssam_controller_release(struct kref *kref)
  9633. +{
  9634. + struct ssam_controller *ctrl = to_ssam_controller(kref, kref);
  9635. +
  9636. + ssam_controller_destroy(ctrl);
  9637. + kfree(ctrl);
  9638. +}
  9639. +
  9640. +/**
  9641. + * ssam_controller_get() - Increment reference count of controller.
  9642. + * @c: The controller.
  9643. + *
  9644. + * Return: Returns the controller provided as input.
  9645. + */
  9646. +struct ssam_controller *ssam_controller_get(struct ssam_controller *c)
  9647. +{
  9648. + if (c)
  9649. + kref_get(&c->kref);
  9650. + return c;
  9651. +}
  9652. +EXPORT_SYMBOL_GPL(ssam_controller_get);
  9653. +
  9654. +/**
  9655. + * ssam_controller_put() - Decrement reference count of controller.
  9656. + * @c: The controller.
  9657. + */
  9658. +void ssam_controller_put(struct ssam_controller *c)
  9659. +{
  9660. + if (c)
  9661. + kref_put(&c->kref, __ssam_controller_release);
  9662. +}
  9663. +EXPORT_SYMBOL_GPL(ssam_controller_put);
  9664. +
  9665. +
  9666. +/**
  9667. + * ssam_controller_statelock() - Lock the controller against state transitions.
  9668. + * @c: The controller to lock.
  9669. + *
  9670. + * Lock the controller against state transitions. Holding this lock guarantees
  9671. + * that the controller will not transition between states, i.e. if the
  9672. + * controller is in state "started", when this lock has been acquired, it will
  9673. + * remain in this state at least until the lock has been released.
  9674. + *
  9675. + * Multiple clients may concurrently hold this lock. In other words: The
  9676. + * ``statelock`` functions represent the read-lock part of a r/w-semaphore.
  9677. + * Actions causing state transitions of the controller must be executed while
  9678. + * holding the write-part of this r/w-semaphore (see ssam_controller_lock()
  9679. + * and ssam_controller_unlock() for that).
  9680. + *
  9681. + * See ssam_controller_stateunlock() for the corresponding unlock function.
  9682. + */
  9683. +void ssam_controller_statelock(struct ssam_controller *c)
  9684. +{
  9685. + down_read(&c->lock);
  9686. +}
  9687. +EXPORT_SYMBOL_GPL(ssam_controller_statelock);
  9688. +
  9689. +/**
  9690. + * ssam_controller_stateunlock() - Unlock controller state transitions.
  9691. + * @c: The controller to unlock.
  9692. + *
  9693. + * See ssam_controller_statelock() for the corresponding lock function.
  9694. + */
  9695. +void ssam_controller_stateunlock(struct ssam_controller *c)
  9696. +{
  9697. + up_read(&c->lock);
  9698. +}
  9699. +EXPORT_SYMBOL_GPL(ssam_controller_stateunlock);
  9700. +
  9701. +/**
  9702. + * ssam_controller_lock() - Acquire the main controller lock.
  9703. + * @c: The controller to lock.
  9704. + *
  9705. + * This lock must be held for any state transitions, including transition to
  9706. + * suspend/resumed states and during shutdown. See ssam_controller_statelock()
  9707. + * for more details on controller locking.
  9708. + *
  9709. + * See ssam_controller_unlock() for the corresponding unlock function.
  9710. + */
  9711. +void ssam_controller_lock(struct ssam_controller *c)
  9712. +{
  9713. + down_write(&c->lock);
  9714. +}
  9715. +
  9716. +/*
  9717. + * ssam_controller_unlock() - Release the main controller lock.
  9718. + * @c: The controller to unlock.
  9719. + *
  9720. + * See ssam_controller_lock() for the corresponding lock function.
  9721. + */
  9722. +void ssam_controller_unlock(struct ssam_controller *c)
  9723. +{
  9724. + up_write(&c->lock);
  9725. +}
  9726. +
  9727. +
  9728. +static void ssam_handle_event(struct ssh_rtl *rtl,
  9729. + const struct ssh_command *cmd,
  9730. + const struct ssam_span *data)
  9731. +{
  9732. + struct ssam_controller *ctrl = to_ssam_controller(rtl, rtl);
  9733. + struct ssam_event_item *item;
  9734. +
  9735. + item = ssam_event_item_alloc(data->len, GFP_KERNEL);
  9736. + if (!item)
  9737. + return;
  9738. +
  9739. + item->rqid = get_unaligned_le16(&cmd->rqid);
  9740. + item->event.target_category = cmd->tc;
  9741. + item->event.target_id = cmd->tid_in;
  9742. + item->event.command_id = cmd->cid;
  9743. + item->event.instance_id = cmd->iid;
  9744. + memcpy(&item->event.data[0], data->ptr, data->len);
  9745. +
  9746. + WARN_ON(ssam_cplt_submit_event(&ctrl->cplt, item));
  9747. +}
  9748. +
  9749. +static const struct ssh_rtl_ops ssam_rtl_ops = {
  9750. + .handle_event = ssam_handle_event,
  9751. +};
  9752. +
  9753. +
  9754. +static bool ssam_notifier_empty(struct ssam_controller *ctrl);
  9755. +static void ssam_notifier_unregister_all(struct ssam_controller *ctrl);
  9756. +
  9757. +
  9758. +#define SSAM_SSH_DSM_REVISION 0
  9759. +static const guid_t SSAM_SSH_DSM_GUID = GUID_INIT(0xd5e383e1, 0xd892, 0x4a76,
  9760. + 0x89, 0xfc, 0xf6, 0xaa, 0xae, 0x7e, 0xd5, 0xb5);
  9761. +
  9762. +enum ssh_dsm_fn {
  9763. + SSH_DSM_FN_SSH_POWER_PROFILE = 0x05,
  9764. + SSH_DSM_FN_SCREEN_ON_SLEEP_IDLE_TIMEOUT = 0x06,
  9765. + SSH_DSM_FN_SCREEN_OFF_SLEEP_IDLE_TIMEOUT = 0x07,
  9766. + SSH_DSM_FN_D3_CLOSES_HANDLE = 0x08,
  9767. + SSH_DSM_FN_SSH_BUFFER_SIZE = 0x09,
  9768. +};
  9769. +
  9770. +static int ssam_dsm_get_functions(acpi_handle handle, u64 *funcs)
  9771. +{
  9772. + union acpi_object *obj;
  9773. + u64 mask = 0;
  9774. + int i;
  9775. +
  9776. + *funcs = 0;
  9777. +
  9778. + if (!acpi_has_method(handle, "_DSM"))
  9779. + return 0;
  9780. +
  9781. + obj = acpi_evaluate_dsm_typed(handle, &SSAM_SSH_DSM_GUID,
  9782. + SSAM_SSH_DSM_REVISION, 0, NULL,
  9783. + ACPI_TYPE_BUFFER);
  9784. + if (!obj)
  9785. + return -EFAULT;
  9786. +
  9787. + for (i = 0; i < obj->buffer.length && i < 8; i++)
  9788. + mask |= (((u64)obj->buffer.pointer[i]) << (i * 8));
  9789. +
  9790. + if (mask & 0x01)
  9791. + *funcs = mask;
  9792. +
  9793. + ACPI_FREE(obj);
  9794. + return 0;
  9795. +}
  9796. +
  9797. +static int ssam_dsm_load_u32(acpi_handle handle, u64 funcs, u64 func, u32 *ret)
  9798. +{
  9799. + union acpi_object *obj;
  9800. + u64 val;
  9801. +
  9802. + if (!(funcs & BIT(func)))
  9803. + return 0;
  9804. +
  9805. + obj = acpi_evaluate_dsm_typed(handle, &SSAM_SSH_DSM_GUID,
  9806. + SSAM_SSH_DSM_REVISION, func, NULL,
  9807. + ACPI_TYPE_INTEGER);
  9808. + if (!obj)
  9809. + return -EFAULT;
  9810. +
  9811. + val = obj->integer.value;
  9812. + ACPI_FREE(obj);
  9813. +
  9814. + if (val > U32_MAX)
  9815. + return -ERANGE;
  9816. +
  9817. + *ret = val;
  9818. + return 0;
  9819. +}
  9820. +
  9821. +/**
  9822. + * ssam_controller_caps_load_from_acpi() - Load controller capabilities from
  9823. + * ACPI _DSM.
  9824. + * @handle: The handle of the ACPI controller/SSH device.
  9825. + * @caps: Where to store the capabilities in.
  9826. + *
  9827. + * Initializes the given controller capabilities with default values, then
  9828. + * checks and, if the respective _DSM functions are available, loads the
  9829. + * actual capabilities from the _DSM.
  9830. + *
  9831. + * Return: Returns zero on success, a negative error code on failure.
  9832. + */
  9833. +static int ssam_controller_caps_load_from_acpi(
  9834. + acpi_handle handle, struct ssam_controller_caps *caps)
  9835. +{
  9836. + u32 d3_closes_handle = false;
  9837. + u64 funcs;
  9838. + int status;
  9839. +
  9840. + // set defaults
  9841. + caps->ssh_power_profile = (u32)-1;
  9842. + caps->screen_on_sleep_idle_timeout = (u32)-1;
  9843. + caps->screen_off_sleep_idle_timeout = (u32)-1;
  9844. + caps->d3_closes_handle = false;
  9845. + caps->ssh_buffer_size = (u32)-1;
  9846. +
  9847. + status = ssam_dsm_get_functions(handle, &funcs);
  9848. + if (status)
  9849. + return status;
  9850. +
  9851. + status = ssam_dsm_load_u32(handle, funcs, SSH_DSM_FN_SSH_POWER_PROFILE,
  9852. + &caps->ssh_power_profile);
  9853. + if (status)
  9854. + return status;
  9855. +
  9856. + status = ssam_dsm_load_u32(handle, funcs,
  9857. + SSH_DSM_FN_SCREEN_ON_SLEEP_IDLE_TIMEOUT,
  9858. + &caps->screen_on_sleep_idle_timeout);
  9859. + if (status)
  9860. + return status;
  9861. +
  9862. + status = ssam_dsm_load_u32(handle, funcs,
  9863. + SSH_DSM_FN_SCREEN_OFF_SLEEP_IDLE_TIMEOUT,
  9864. + &caps->screen_off_sleep_idle_timeout);
  9865. + if (status)
  9866. + return status;
  9867. +
  9868. + status = ssam_dsm_load_u32(handle, funcs, SSH_DSM_FN_D3_CLOSES_HANDLE,
  9869. + &d3_closes_handle);
  9870. + if (status)
  9871. + return status;
  9872. +
  9873. + caps->d3_closes_handle = !!d3_closes_handle;
  9874. +
  9875. + status = ssam_dsm_load_u32(handle, funcs, SSH_DSM_FN_SSH_BUFFER_SIZE,
  9876. + &caps->ssh_buffer_size);
  9877. + if (status)
  9878. + return status;
  9879. +
  9880. + return 0;
  9881. +}
  9882. +
  9883. +/**
  9884. + * ssam_controller_init() - Initialize SSAM controller.
  9885. + * @ctrl: The controller to initialize.
  9886. + * @serdev: The serial device representing the underlying data transport.
  9887. + *
  9888. + * Initializes the given controller. Does neither start receiver nor
  9889. + * transmitter threads. After this call, the controller has to be hooked up to
  9890. + * the serdev core separately via &struct serdev_device_ops, relaying calls to
  9891. + * ssam_controller_receive_buf() and ssam_controller_write_wakeup(). Once the
  9892. + * controller has been hooked up, transmitter and receiver threads may be
  9893. + * started via ssam_controller_start(). These setup steps need to be completed
  9894. + * before controller can be used for requests.
  9895. + */
  9896. +int ssam_controller_init(struct ssam_controller *ctrl,
  9897. + struct serdev_device *serdev)
  9898. +{
  9899. + acpi_handle handle = ACPI_HANDLE(&serdev->dev);
  9900. + int status;
  9901. +
  9902. + init_rwsem(&ctrl->lock);
  9903. + kref_init(&ctrl->kref);
  9904. +
  9905. + status = ssam_controller_caps_load_from_acpi(handle, &ctrl->caps);
  9906. + if (status)
  9907. + return status;
  9908. +
  9909. + dev_dbg(&serdev->dev,
  9910. + "device capabilities:\n"
  9911. + " ssh_power_profile: %u\n"
  9912. + " ssh_buffer_size: %u\n"
  9913. + " screen_on_sleep_idle_timeout: %u\n"
  9914. + " screen_off_sleep_idle_timeout: %u\n"
  9915. + " d3_closes_handle: %u\n",
  9916. + ctrl->caps.ssh_power_profile,
  9917. + ctrl->caps.ssh_buffer_size,
  9918. + ctrl->caps.screen_on_sleep_idle_timeout,
  9919. + ctrl->caps.screen_off_sleep_idle_timeout,
  9920. + ctrl->caps.d3_closes_handle);
  9921. +
  9922. + ssh_seq_reset(&ctrl->counter.seq);
  9923. + ssh_rqid_reset(&ctrl->counter.rqid);
  9924. +
  9925. + // initialize event/request completion system
  9926. + status = ssam_cplt_init(&ctrl->cplt, &serdev->dev);
  9927. + if (status)
  9928. + return status;
  9929. +
  9930. + // initialize request and packet transport layers
  9931. + status = ssh_rtl_init(&ctrl->rtl, serdev, &ssam_rtl_ops);
  9932. + if (status) {
  9933. + ssam_cplt_destroy(&ctrl->cplt);
  9934. + return status;
  9935. + }
  9936. +
  9937. + /*
  9938. + * Set state via write_once even though we expect to be in an
  9939. + * exclusive context, due to smoke-testing in
  9940. + * ssam_request_sync_submit().
  9941. + */
  9942. + WRITE_ONCE(ctrl->state, SSAM_CONTROLLER_INITIALIZED);
  9943. + return 0;
  9944. +}
  9945. +
  9946. +/**
  9947. + * ssam_controller_start() - Start the receiver and transmitter threads of the
  9948. + * controller.
  9949. + * @ctrl: The controller.
  9950. + *
  9951. + * Note: When this function is called, the controller shouldbe properly hooked
  9952. + * up to the serdev core via &struct serdev_device_ops. Please refert to
  9953. + * ssam_controller_init() for more details on controller initialization.
  9954. + *
  9955. + * This function must be called from an exclusive context with regards to the
  9956. + * state, if necessary, by locking the controller via ssam_controller_lock().
  9957. + */
  9958. +int ssam_controller_start(struct ssam_controller *ctrl)
  9959. +{
  9960. + int status;
  9961. +
  9962. + if (ctrl->state != SSAM_CONTROLLER_INITIALIZED)
  9963. + return -EINVAL;
  9964. +
  9965. + status = ssh_rtl_start(&ctrl->rtl);
  9966. + if (status)
  9967. + return status;
  9968. +
  9969. + /*
  9970. + * Set state via write_once even though we expect to be locked/in an
  9971. + * exclusive context, due to smoke-testing in
  9972. + * ssam_request_sync_submit().
  9973. + */
  9974. + WRITE_ONCE(ctrl->state, SSAM_CONTROLLER_STARTED);
  9975. + return 0;
  9976. +}
  9977. +
  9978. +/**
  9979. + * ssam_controller_shutdown() - Shut down the controller.
  9980. + * @ctrl: The controller.
  9981. + *
  9982. + * Shuts down the controller by flushing all pending requests and stopping the
  9983. + * transmitter and receiver threads. All requests submitted after this call
  9984. + * will fail with %-ESHUTDOWN. While it is discouraged to do so, this function
  9985. + * is safe to use in parallel with ongoing request submission.
  9986. + *
  9987. + * In the course of this shutdown procedure, all currently registered
  9988. + * notifiers will be unregistered. It is, however, strongly recommended to not
  9989. + * rely on this behavior, and instead the party registring the notifier should
  9990. + * unregister it before the controller gets shut down, e.g. via the SSAM bus
  9991. + * which guarantees client devices to be removed before a shutdown.
  9992. + *
  9993. + * Note that events may still be pending after this call, but due to the
  9994. + * notifiers being unregistered, the will be dropped when the controller is
  9995. + * subsequently being destroyed via ssam_controller_destroy().
  9996. + *
  9997. + * This function must be called from an exclusive context with regards to the
  9998. + * state, if necessary, by locking the controller via ssam_controller_lock().
  9999. + */
  10000. +void ssam_controller_shutdown(struct ssam_controller *ctrl)
  10001. +{
  10002. + enum ssam_controller_state s = ctrl->state;
  10003. + int status;
  10004. +
  10005. + if (s == SSAM_CONTROLLER_UNINITIALIZED || s == SSAM_CONTROLLER_STOPPED)
  10006. + return;
  10007. +
  10008. + // try to flush pending events and requests while everything still works
  10009. + status = ssh_rtl_flush(&ctrl->rtl, msecs_to_jiffies(5000));
  10010. + if (status) {
  10011. + ssam_err(ctrl, "failed to flush request transport layer: %d\n",
  10012. + status);
  10013. + }
  10014. +
  10015. + // try to flush out all currently completing requests and events
  10016. + ssam_cplt_flush(&ctrl->cplt);
  10017. +
  10018. + /*
  10019. + * We expect all notifiers to have been removed by the respective client
  10020. + * driver that set them up at this point. If this warning occurs, some
  10021. + * client driver has not done that...
  10022. + */
  10023. + WARN_ON(!ssam_notifier_empty(ctrl));
  10024. +
  10025. + /*
  10026. + * Nevertheless, we should still take care of drivers that don't behave
  10027. + * well. Thus disable all enabled events, unregister all notifiers.
  10028. + */
  10029. + ssam_notifier_unregister_all(ctrl);
  10030. +
  10031. + // cancel rem. requests, ensure no new ones can be queued, stop threads
  10032. + ssh_rtl_shutdown(&ctrl->rtl);
  10033. +
  10034. + /*
  10035. + * Set state via write_once even though we expect to be locked/in an
  10036. + * exclusive context, due to smoke-testing in
  10037. + * ssam_request_sync_submit().
  10038. + */
  10039. + WRITE_ONCE(ctrl->state, SSAM_CONTROLLER_STOPPED);
  10040. + ctrl->rtl.ptl.serdev = NULL;
  10041. +}
  10042. +
  10043. +/**
  10044. + * ssam_controller_destroy() - Destroy the controller and free its resources.
  10045. + * @ctrl: The controller.
  10046. + *
  10047. + * Ensures that all resources associated with the controller get freed. This
  10048. + * function should only be called after the controller has been stopped via
  10049. + * ssam_controller_shutdown(). In general, this function should not be called
  10050. + * directly. The only valid place to call this function direclty is during
  10051. + * initialization, before the controller has been fully initialized and passed
  10052. + * to other processes. This function is called automatically when the
  10053. + * reference count of the controller reaches zero.
  10054. + *
  10055. + * Must be called from an exclusive context with regards to the controller
  10056. + * state.
  10057. + */
  10058. +void ssam_controller_destroy(struct ssam_controller *ctrl)
  10059. +{
  10060. + if (ctrl->state == SSAM_CONTROLLER_UNINITIALIZED)
  10061. + return;
  10062. +
  10063. + WARN_ON(ctrl->state != SSAM_CONTROLLER_STOPPED);
  10064. +
  10065. + /*
  10066. + * Note: New events could still have been received after the previous
  10067. + * flush in ssam_controller_shutdown, before the request transport layer
  10068. + * has been shut down. At this point, after the shutdown, we can be sure
  10069. + * that no new events will be queued. The call to ssam_cplt_destroy will
  10070. + * ensure that those remaining are being completed and freed.
  10071. + */
  10072. +
  10073. + // actually free resources
  10074. + ssam_cplt_destroy(&ctrl->cplt);
  10075. + ssh_rtl_destroy(&ctrl->rtl);
  10076. +
  10077. + /*
  10078. + * Set state via write_once even though we expect to be locked/in an
  10079. + * exclusive context, due to smoke-testing in
  10080. + * ssam_request_sync_submit().
  10081. + */
  10082. + WRITE_ONCE(ctrl->state, SSAM_CONTROLLER_UNINITIALIZED);
  10083. +}
  10084. +
  10085. +/**
  10086. + * ssam_controller_suspend() - Suspend the controller.
  10087. + * @ctrl: The controller to suspend.
  10088. + *
  10089. + * Marks the controller as suspended. Note that display-off and D0-exit
  10090. + * notifications have to be sent manually before transitioning the controller
  10091. + * into the suspended state via this function.
  10092. + *
  10093. + * See ssam_controller_resume() for the corresponding resume function.
  10094. + *
  10095. + * Return: Returns %-EINVAL if the controller is currently not in the
  10096. + * "started" state.
  10097. + */
  10098. +int ssam_controller_suspend(struct ssam_controller *ctrl)
  10099. +{
  10100. + ssam_controller_lock(ctrl);
  10101. +
  10102. + if (ctrl->state != SSAM_CONTROLLER_STARTED) {
  10103. + ssam_controller_unlock(ctrl);
  10104. + return -EINVAL;
  10105. + }
  10106. +
  10107. + ssam_dbg(ctrl, "pm: suspending controller\n");
  10108. +
  10109. + /*
  10110. + * Set state via write_once even though we're locked, due to
  10111. + * smoke-testing in ssam_request_sync_submit().
  10112. + */
  10113. + WRITE_ONCE(ctrl->state, SSAM_CONTROLLER_SUSPENDED);
  10114. +
  10115. + ssam_controller_unlock(ctrl);
  10116. + return 0;
  10117. +}
  10118. +
  10119. +/**
  10120. + * ssam_controller_resume() - Resume the controller from suspend.
  10121. + * @ctrl: The controller to resume.
  10122. + *
  10123. + * Resume the controller from the suspended state it was put into via
  10124. + * ssam_controller_suspend(). This function does not issue display-on and
  10125. + * D0-entry notifications. If required, those have to be sent manually after
  10126. + * this call.
  10127. + *
  10128. + * Return: Returns %-EINVAL if the controller is currently not suspended.
  10129. + */
  10130. +int ssam_controller_resume(struct ssam_controller *ctrl)
  10131. +{
  10132. + ssam_controller_lock(ctrl);
  10133. +
  10134. + if (ctrl->state != SSAM_CONTROLLER_SUSPENDED) {
  10135. + ssam_controller_unlock(ctrl);
  10136. + return -EINVAL;
  10137. + }
  10138. +
  10139. + ssam_dbg(ctrl, "pm: resuming controller\n");
  10140. +
  10141. + /*
  10142. + * Set state via write_once even though we're locked, due to
  10143. + * smoke-testing in ssam_request_sync_submit().
  10144. + */
  10145. + WRITE_ONCE(ctrl->state, SSAM_CONTROLLER_STARTED);
  10146. +
  10147. + ssam_controller_unlock(ctrl);
  10148. + return 0;
  10149. +}
  10150. +
  10151. +
  10152. +/* -- Top-level request interface ------------------------------------------- */
  10153. +
  10154. +/**
  10155. + * ssam_request_write_data() - Construct and write SAM request message to
  10156. + * buffer.
  10157. + * @buf: The buffer to write the data to.
  10158. + * @ctrl: The controller via which the request will be sent.
  10159. + * @spec: The request data and specification.
  10160. + *
  10161. + * Constructs a SAM/SSH request message and writes it to the provided buffer.
  10162. + * The request and transport counters, specifically RQID and SEQ, will be set
  10163. + * in this call. These counters are obtained from the controller. It is thus
  10164. + * only valid to send the resulting message via the controller specified here.
  10165. + *
  10166. + * For calculation of the required buffer size, refer to the
  10167. + * SSH_COMMAND_MESSAGE_LENGTH() macro.
  10168. + *
  10169. + * Return: Returns the number of bytes used in the buffer on success. Returns
  10170. + * %-EINVAL if the payload length provided in the request specification is too
  10171. + * large (larger than %SSH_COMMAND_MAX_PAYLOAD_SIZE) or if the provided buffer
  10172. + * is too small.
  10173. + */
  10174. +ssize_t ssam_request_write_data(struct ssam_span *buf,
  10175. + struct ssam_controller *ctrl,
  10176. + const struct ssam_request *spec)
  10177. +{
  10178. + struct msgbuf msgb;
  10179. + u16 rqid;
  10180. + u8 seq;
  10181. +
  10182. + if (spec->length > SSH_COMMAND_MAX_PAYLOAD_SIZE)
  10183. + return -EINVAL;
  10184. +
  10185. + if (SSH_COMMAND_MESSAGE_LENGTH(spec->length) > buf->len)
  10186. + return -EINVAL;
  10187. +
  10188. + msgb_init(&msgb, buf->ptr, buf->len);
  10189. + seq = ssh_seq_next(&ctrl->counter.seq);
  10190. + rqid = ssh_rqid_next(&ctrl->counter.rqid);
  10191. + msgb_push_cmd(&msgb, seq, rqid, spec);
  10192. +
  10193. + return msgb_bytes_used(&msgb);
  10194. +}
  10195. +EXPORT_SYMBOL_GPL(ssam_request_write_data);
  10196. +
  10197. +
  10198. +static void ssam_request_sync_complete(struct ssh_request *rqst,
  10199. + const struct ssh_command *cmd,
  10200. + const struct ssam_span *data, int status)
  10201. +{
  10202. + struct ssh_rtl *rtl = ssh_request_rtl(rqst);
  10203. + struct ssam_request_sync *r;
  10204. +
  10205. + r = container_of(rqst, struct ssam_request_sync, base);
  10206. + r->status = status;
  10207. +
  10208. + if (r->resp)
  10209. + r->resp->length = 0;
  10210. +
  10211. + if (status) {
  10212. + rtl_dbg_cond(rtl, "rsp: request failed: %d\n", status);
  10213. + return;
  10214. + }
  10215. +
  10216. + if (!data) // handle requests without a response
  10217. + return;
  10218. +
  10219. + if (!r->resp || !r->resp->pointer) {
  10220. + if (data->len)
  10221. + rtl_warn(rtl, "rsp: no response buffer provided, dropping data\n");
  10222. + return;
  10223. + }
  10224. +
  10225. + if (data->len > r->resp->capacity) {
  10226. + rtl_err(rtl, "rsp: response buffer too small, capacity: %zu bytes,"
  10227. + " got: %zu bytes\n", r->resp->capacity, data->len);
  10228. + r->status = -ENOSPC;
  10229. + return;
  10230. + }
  10231. +
  10232. + r->resp->length = data->len;
  10233. + memcpy(r->resp->pointer, data->ptr, data->len);
  10234. +}
  10235. +
  10236. +static void ssam_request_sync_release(struct ssh_request *rqst)
  10237. +{
  10238. + complete_all(&container_of(rqst, struct ssam_request_sync, base)->comp);
  10239. +}
  10240. +
  10241. +static const struct ssh_request_ops ssam_request_sync_ops = {
  10242. + .release = ssam_request_sync_release,
  10243. + .complete = ssam_request_sync_complete,
  10244. +};
  10245. +
  10246. +
  10247. +/**
  10248. + * ssam_request_sync_alloc() - Allocate a synchronous request.
  10249. + * @payload_len: The length of the request payload.
  10250. + * @flags: Flags used for allocation.
  10251. + * @rqst: Where to store the pointer to the allocated request.
  10252. + * @buffer: Where to store the buffer descriptor for the message buffer of
  10253. + * the request.
  10254. + *
  10255. + * Allocates a synchronous request with corresponding message buffer. The
  10256. + * request still needs to be initialized ssam_request_sync_init() before
  10257. + * it can be submitted, and the message buffer data must still be set to the
  10258. + * returned buffer via ssam_request_sync_set_data() after it has been filled,
  10259. + * if need be with adjusted message length.
  10260. + *
  10261. + * After use, the request and its corresponding message buffer should be freed
  10262. + * via ssam_request_sync_free(). The buffer must not be freed separately.
  10263. + *
  10264. + * Return: Returns zero on success, %-ENOMEM if the request could not be
  10265. + * allocated.
  10266. + */
  10267. +int ssam_request_sync_alloc(size_t payload_len, gfp_t flags,
  10268. + struct ssam_request_sync **rqst,
  10269. + struct ssam_span *buffer)
  10270. +{
  10271. + size_t msglen = SSH_COMMAND_MESSAGE_LENGTH(payload_len);
  10272. +
  10273. + *rqst = kzalloc(sizeof(**rqst) + msglen, flags);
  10274. + if (!*rqst)
  10275. + return -ENOMEM;
  10276. +
  10277. + buffer->ptr = (u8 *)(*rqst + 1);
  10278. + buffer->len = msglen;
  10279. +
  10280. + return 0;
  10281. +}
  10282. +EXPORT_SYMBOL_GPL(ssam_request_sync_alloc);
  10283. +
  10284. +/**
  10285. + * ssam_request_sync_free() - Free a synchronous request.
  10286. + * @rqst: The request to free.
  10287. + *
  10288. + * Free a synchronous request and its corresponding buffer allocated with
  10289. + * ssam_request_sync_alloc(). Do not use for requests allocated on the stack
  10290. + * or via any other function.
  10291. + *
  10292. + * Warning: The caller must ensure that the request is not in use any more.
  10293. + * I.e. the caller must ensure that it has the only reference to the request
  10294. + * and the request is not currently pending. This means that the caller has
  10295. + * either never submitted the request, request submission has failed, or the
  10296. + * caller has waited until the submitted request has been completed via
  10297. + * ssam_request_sync_wait().
  10298. + */
  10299. +void ssam_request_sync_free(struct ssam_request_sync *rqst)
  10300. +{
  10301. + kfree(rqst);
  10302. +}
  10303. +EXPORT_SYMBOL_GPL(ssam_request_sync_free);
  10304. +
  10305. +/**
  10306. + * ssam_request_sync_init() - Initialize a synchronous request struct.
  10307. + * @rqst: The request to initialize.
  10308. + * @flags: The request flags.
  10309. + *
  10310. + * Initializes the given request struct. Does not initialize the request
  10311. + * message data. This has to be done explicitly after this call via
  10312. + * ssam_request_sync_set_data() and the actual message data has to be written
  10313. + * via ssam_request_write_data().
  10314. + */
  10315. +void ssam_request_sync_init(struct ssam_request_sync *rqst,
  10316. + enum ssam_request_flags flags)
  10317. +{
  10318. + ssh_request_init(&rqst->base, flags, &ssam_request_sync_ops);
  10319. + init_completion(&rqst->comp);
  10320. + rqst->resp = NULL;
  10321. + rqst->status = 0;
  10322. +}
  10323. +EXPORT_SYMBOL_GPL(ssam_request_sync_init);
  10324. +
  10325. +/**
  10326. + * ssam_request_sync_submit() - Submit a synchronous request.
  10327. + * @ctrl: The controller with which to submit the request.
  10328. + * @rqst: The request to submit.
  10329. + *
  10330. + * Submit a synchronous request. The request has to be initialized and
  10331. + * properly set up, including response buffer (may be %NULL if no response is
  10332. + * expected) and command message data. This function does not wait for the
  10333. + * request to be completed.
  10334. + *
  10335. + * If this function succeeds, ssam_request_sync_wait() must be used to ensure
  10336. + * that the request has been completed before the response data can be
  10337. + * accessed and/or the request can be freed. On failure, the request may
  10338. + * immediately be freed.
  10339. + *
  10340. + * This function may only be used if the controller is active, i.e. has been
  10341. + * initialized and not suspended.
  10342. + */
  10343. +int ssam_request_sync_submit(struct ssam_controller *ctrl,
  10344. + struct ssam_request_sync *rqst)
  10345. +{
  10346. + int status;
  10347. +
  10348. + /*
  10349. + * This is only a superficial check. In general, the caller needs to
  10350. + * ensure that the controller is initialized and is not (and does not
  10351. + * get) suspended during use, i.e. until the request has been completed
  10352. + * (if _absolutely_ necessary, by use of ssam_controller_statelock/
  10353. + * ssam_controller_stateunlock, but something like ssam_client_link
  10354. + * should be preferred as this needs to last until the request has been
  10355. + * completed).
  10356. + *
  10357. + * Note that it is actually safe to use this function while the
  10358. + * controller is in the process of being shut down (as ssh_rtl_submit
  10359. + * is safe with regards to this), but it is generally discouraged to do
  10360. + * so.
  10361. + */
  10362. + if (WARN_ON(READ_ONCE(ctrl->state) != SSAM_CONTROLLER_STARTED)) {
  10363. + ssh_request_put(&rqst->base);
  10364. + return -ENXIO;
  10365. + }
  10366. +
  10367. + status = ssh_rtl_submit(&ctrl->rtl, &rqst->base);
  10368. + ssh_request_put(&rqst->base);
  10369. +
  10370. + return status;
  10371. +}
  10372. +EXPORT_SYMBOL_GPL(ssam_request_sync_submit);
  10373. +
  10374. +/**
  10375. + * ssam_request_sync() - Execute a synchronous request.
  10376. + * @ctrl: The controller via which the request will be submitted.
  10377. + * @spec: The request specification and payload.
  10378. + * @rsp: The response buffer.
  10379. + *
  10380. + * Allocates a synchronous request with its message data buffer on the heap
  10381. + * via ssam_request_sync_alloc(), fully intializes it via the provided request
  10382. + * specification, submits it, and finally waits for its completion before
  10383. + * freeing it and returning its status.
  10384. + *
  10385. + * Return: Returns the status of the request or any failure during setup.
  10386. + */
  10387. +int ssam_request_sync(struct ssam_controller *ctrl,
  10388. + const struct ssam_request *spec,
  10389. + struct ssam_response *rsp)
  10390. +{
  10391. + struct ssam_request_sync *rqst;
  10392. + struct ssam_span buf;
  10393. + ssize_t len;
  10394. + int status;
  10395. +
  10396. + status = ssam_request_sync_alloc(spec->length, GFP_KERNEL, &rqst, &buf);
  10397. + if (status)
  10398. + return status;
  10399. +
  10400. + ssam_request_sync_init(rqst, spec->flags);
  10401. + ssam_request_sync_set_resp(rqst, rsp);
  10402. +
  10403. + len = ssam_request_write_data(&buf, ctrl, spec);
  10404. + if (len < 0) {
  10405. + ssam_request_sync_free(rqst);
  10406. + return len;
  10407. + }
  10408. +
  10409. + ssam_request_sync_set_data(rqst, buf.ptr, len);
  10410. +
  10411. + status = ssam_request_sync_submit(ctrl, rqst);
  10412. + if (!status)
  10413. + status = ssam_request_sync_wait(rqst);
  10414. +
  10415. + ssam_request_sync_free(rqst);
  10416. + return status;
  10417. +}
  10418. +EXPORT_SYMBOL_GPL(ssam_request_sync);
  10419. +
  10420. +/**
  10421. + * ssam_request_sync_with_buffer() - Execute a synchronous request with the
  10422. + * provided buffer as backend for the message buffer.
  10423. + * @ctrl: The controller via which the request will be submitted.
  10424. + * @spec: The request specification and payload.
  10425. + * @rsp: The response buffer.
  10426. + * @buf: The buffer for the request message data.
  10427. + *
  10428. + * Allocates a synchronous request struct on the stack, fully initializes it
  10429. + * using the provided buffer as message data buffer, submits it, and then
  10430. + * waits for its completion before returning its staus. The
  10431. + * SSH_COMMAND_MESSAGE_LENGTH() macro can be used to compute the required
  10432. + * message buffer size.
  10433. + *
  10434. + * This function does essentially the same as ssam_request_sync(), but instead
  10435. + * of dynamically allocating the request and message data buffer, it uses the
  10436. + * provided message data buffer and stores the (small) request struct on the
  10437. + * heap.
  10438. + *
  10439. + * Return: Returns the status of the request or any failure during setup.
  10440. + */
  10441. +int ssam_request_sync_with_buffer(struct ssam_controller *ctrl,
  10442. + const struct ssam_request *spec,
  10443. + struct ssam_response *rsp,
  10444. + struct ssam_span *buf)
  10445. +{
  10446. + struct ssam_request_sync rqst;
  10447. + ssize_t len;
  10448. + int status;
  10449. +
  10450. + ssam_request_sync_init(&rqst, spec->flags);
  10451. + ssam_request_sync_set_resp(&rqst, rsp);
  10452. +
  10453. + len = ssam_request_write_data(buf, ctrl, spec);
  10454. + if (len < 0)
  10455. + return len;
  10456. +
  10457. + ssam_request_sync_set_data(&rqst, buf->ptr, len);
  10458. +
  10459. + status = ssam_request_sync_submit(ctrl, &rqst);
  10460. + if (!status)
  10461. + status = ssam_request_sync_wait(&rqst);
  10462. +
  10463. + return status;
  10464. +}
  10465. +EXPORT_SYMBOL_GPL(ssam_request_sync_with_buffer);
  10466. +
  10467. +
  10468. +/* -- Internal SAM requests. ------------------------------------------------ */
  10469. +
  10470. +static SSAM_DEFINE_SYNC_REQUEST_R(ssam_ssh_get_firmware_version, __le32, {
  10471. + .target_category = SSAM_SSH_TC_SAM,
  10472. + .target_id = 0x01,
  10473. + .command_id = 0x13,
  10474. + .instance_id = 0x00,
  10475. +});
  10476. +
  10477. +static SSAM_DEFINE_SYNC_REQUEST_R(ssam_ssh_notif_display_off, u8, {
  10478. + .target_category = SSAM_SSH_TC_SAM,
  10479. + .target_id = 0x01,
  10480. + .command_id = 0x15,
  10481. + .instance_id = 0x00,
  10482. +});
  10483. +
  10484. +static SSAM_DEFINE_SYNC_REQUEST_R(ssam_ssh_notif_display_on, u8, {
  10485. + .target_category = SSAM_SSH_TC_SAM,
  10486. + .target_id = 0x01,
  10487. + .command_id = 0x16,
  10488. + .instance_id = 0x00,
  10489. +});
  10490. +
  10491. +static SSAM_DEFINE_SYNC_REQUEST_R(ssam_ssh_notif_d0_exit, u8, {
  10492. + .target_category = SSAM_SSH_TC_SAM,
  10493. + .target_id = 0x01,
  10494. + .command_id = 0x33,
  10495. + .instance_id = 0x00,
  10496. +});
  10497. +
  10498. +static SSAM_DEFINE_SYNC_REQUEST_R(ssam_ssh_notif_d0_entry, u8, {
  10499. + .target_category = SSAM_SSH_TC_SAM,
  10500. + .target_id = 0x01,
  10501. + .command_id = 0x34,
  10502. + .instance_id = 0x00,
  10503. +});
  10504. +
  10505. +/**
  10506. + * struct ssh_notification_params - Command payload to enable/disable SSH
  10507. + * notifications.
  10508. + * @target_category: The target category for which notifications should be
  10509. + * enabled/disabled.
  10510. + * @flags: Flags determining how notifications are being sent.
  10511. + * @request_id: The request ID that is used to send these notifications.
  10512. + * @instance_id: The specific instance in the given target category for
  10513. + * which notifications should be enabled.
  10514. + */
  10515. +struct ssh_notification_params {
  10516. + u8 target_category;
  10517. + u8 flags;
  10518. + __le16 request_id;
  10519. + u8 instance_id;
  10520. +} __packed;
  10521. +
  10522. +static_assert(sizeof(struct ssh_notification_params) == 5);
  10523. +
  10524. +/**
  10525. + * ssam_ssh_event_enable() - Enable SSH event.
  10526. + * @ctrl: The controller for which to enable the event.
  10527. + * @reg: The event registry describing what request to use for enabling and
  10528. + * disabling the event.
  10529. + * @id: The event identifier.
  10530. + * @flags: The event flags.
  10531. + *
  10532. + * This is a wrapper for the raw SAM request to enable an event, thus it does
  10533. + * not handle referecnce counting for enable/disable of events. If an event
  10534. + * has already been enabled, the EC will ignore this request.
  10535. + *
  10536. + * Return: Returns the status of the executed SAM request (zero on success and
  10537. + * negative on direct failure) or %-EPROTO if the request response indicates a
  10538. + * failure.
  10539. + */
  10540. +static int ssam_ssh_event_enable(struct ssam_controller *ctrl,
  10541. + struct ssam_event_registry reg,
  10542. + struct ssam_event_id id, u8 flags)
  10543. +{
  10544. + struct ssh_notification_params params;
  10545. + struct ssam_request rqst;
  10546. + struct ssam_response result;
  10547. + int status;
  10548. +
  10549. + u16 rqid = ssh_tc_to_rqid(id.target_category);
  10550. + u8 buf[1] = { 0x00 };
  10551. +
  10552. + // only allow RQIDs that lie within event spectrum
  10553. + if (!ssh_rqid_is_event(rqid))
  10554. + return -EINVAL;
  10555. +
  10556. + params.target_category = id.target_category;
  10557. + params.instance_id = id.instance;
  10558. + params.flags = flags;
  10559. + put_unaligned_le16(rqid, &params.request_id);
  10560. +
  10561. + rqst.target_category = reg.target_category;
  10562. + rqst.target_id = reg.target_id;
  10563. + rqst.command_id = reg.cid_enable;
  10564. + rqst.instance_id = 0x00;
  10565. + rqst.flags = SSAM_REQUEST_HAS_RESPONSE;
  10566. + rqst.length = sizeof(params);
  10567. + rqst.payload = (u8 *)&params;
  10568. +
  10569. + result.capacity = ARRAY_SIZE(buf);
  10570. + result.length = 0;
  10571. + result.pointer = buf;
  10572. +
  10573. + status = ssam_retry(ssam_request_sync_onstack, ctrl, &rqst, &result,
  10574. + sizeof(params));
  10575. + if (status) {
  10576. + ssam_err(ctrl, "failed to enable event source (tc: 0x%02x, "
  10577. + "iid: 0x%02x, reg: 0x%02x)\n", id.target_category,
  10578. + id.instance, reg.target_category);
  10579. + }
  10580. +
  10581. + if (buf[0] != 0x00) {
  10582. + ssam_err(ctrl, "unexpected result while enabling event source: "
  10583. + "0x%02x (tc: 0x%02x, iid: 0x%02x, reg: 0x%02x)\n",
  10584. + buf[0], id.target_category, id.instance,
  10585. + reg.target_category);
  10586. + return -EPROTO;
  10587. + }
  10588. +
  10589. + return status;
  10590. +
  10591. +}
  10592. +
  10593. +/**
  10594. + * ssam_ssh_event_disable() - Disable SSH event.
  10595. + * @ctrl: The controller for which to disable the event.
  10596. + * @reg: The event registry describing what request to use for enabling and
  10597. + * disabling the event (must be same as used when enabling the event).
  10598. + * @id: The event identifier.
  10599. + * @flags: The event flags (likely ignored for disabling of events).
  10600. + *
  10601. + * This is a wrapper for the raw SAM request to disable an event, thus it does
  10602. + * not handle reference counting for enable/disable of events. If an event has
  10603. + * already been disabled, the EC will ignore this request.
  10604. + *
  10605. + * Return: Returns the status of the executed SAM request (zero on success and
  10606. + * negative on direct failure) or %-EPROTO if the request response indicates a
  10607. + * failure.
  10608. + */
  10609. +static int ssam_ssh_event_disable(struct ssam_controller *ctrl,
  10610. + struct ssam_event_registry reg,
  10611. + struct ssam_event_id id, u8 flags)
  10612. +{
  10613. + struct ssh_notification_params params;
  10614. + struct ssam_request rqst;
  10615. + struct ssam_response result;
  10616. + int status;
  10617. +
  10618. + u16 rqid = ssh_tc_to_rqid(id.target_category);
  10619. + u8 buf[1] = { 0x00 };
  10620. +
  10621. + // only allow RQIDs that lie within event spectrum
  10622. + if (!ssh_rqid_is_event(rqid))
  10623. + return -EINVAL;
  10624. +
  10625. + params.target_category = id.target_category;
  10626. + params.instance_id = id.instance;
  10627. + params.flags = flags;
  10628. + put_unaligned_le16(rqid, &params.request_id);
  10629. +
  10630. + rqst.target_category = reg.target_category;
  10631. + rqst.target_id = reg.target_id;
  10632. + rqst.command_id = reg.cid_disable;
  10633. + rqst.instance_id = 0x00;
  10634. + rqst.flags = SSAM_REQUEST_HAS_RESPONSE;
  10635. + rqst.length = sizeof(params);
  10636. + rqst.payload = (u8 *)&params;
  10637. +
  10638. + result.capacity = ARRAY_SIZE(buf);
  10639. + result.length = 0;
  10640. + result.pointer = buf;
  10641. +
  10642. + status = ssam_retry(ssam_request_sync_onstack, ctrl, &rqst, &result,
  10643. + sizeof(params));
  10644. + if (status) {
  10645. + ssam_err(ctrl, "failed to disable event source (tc: 0x%02x, "
  10646. + "iid: 0x%02x, reg: 0x%02x)\n", id.target_category,
  10647. + id.instance, reg.target_category);
  10648. + }
  10649. +
  10650. + if (buf[0] != 0x00) {
  10651. + ssam_err(ctrl, "unexpected result while disabling event source: "
  10652. + "0x%02x (tc: 0x%02x, iid: 0x%02x, reg: 0x%02x)\n",
  10653. + buf[0], id.target_category, id.instance,
  10654. + reg.target_category);
  10655. + return -EPROTO;
  10656. + }
  10657. +
  10658. + return status;
  10659. +}
  10660. +
  10661. +
  10662. +/* -- Wrappers for internal SAM requests. ----------------------------------- */
  10663. +
  10664. +/**
  10665. + * ssam_get_firmware_version() - Get the SAM/EC firmware version.
  10666. + * @ctrl: The controller.
  10667. + * @version: Where to store the version number.
  10668. + *
  10669. + * Return: Returns zero on success or the status of the executed SAM request
  10670. + * if that request failed.
  10671. + */
  10672. +int ssam_get_firmware_version(struct ssam_controller *ctrl, u32 *version)
  10673. +{
  10674. + __le32 __version;
  10675. + int status;
  10676. +
  10677. + status = ssam_retry(ssam_ssh_get_firmware_version, ctrl, &__version);
  10678. + if (status)
  10679. + return status;
  10680. +
  10681. + *version = le32_to_cpu(__version);
  10682. + return 0;
  10683. +}
  10684. +
  10685. +/**
  10686. + * ssam_ctrl_notif_display_off() - Notify EC that the display has been turned
  10687. + * off.
  10688. + * @ctrl: The controller.
  10689. + *
  10690. + * Notify the EC that the display has been turned off and the driver may enter
  10691. + * a lower-power state. This will prevent events from being sent directly.
  10692. + * Rather, the EC signals an event by pulling the wakeup GPIO high for as long
  10693. + * as there are pending events. The events then need to be manually released,
  10694. + * one by one, via the GPIO callback request. All pending events accumulated
  10695. + * during this state can also be released by issuing the display-on
  10696. + * notification, e.g. via ssam_ctrl_notif_display_on(), which will also reset
  10697. + * the GPIO.
  10698. + *
  10699. + * On some devices, specifically ones with an integrated keyboard, the keyboard
  10700. + * backlight will be turned off by this call.
  10701. + *
  10702. + * This function will only send the display-off notification command if
  10703. + * display noticications are supported by the EC. Currently all known devices
  10704. + * support these notification.
  10705. + *
  10706. + * Use ssam_ctrl_notif_display_on() to reverse the effects of this function.
  10707. + *
  10708. + * Return: Returns zero on success or if no request has been executed, the
  10709. + * status of the executed SAM request if that request failed, or %-EPROTO if
  10710. + * an unexpected response has been received.
  10711. + */
  10712. +int ssam_ctrl_notif_display_off(struct ssam_controller *ctrl)
  10713. +{
  10714. + int status;
  10715. + u8 response;
  10716. +
  10717. + ssam_dbg(ctrl, "pm: notifying display off\n");
  10718. +
  10719. + status = ssam_retry(ssam_ssh_notif_display_off, ctrl, &response);
  10720. + if (status)
  10721. + return status;
  10722. +
  10723. + if (response != 0) {
  10724. + ssam_err(ctrl, "unexpected response from display-off notification: 0x%02x\n",
  10725. + response);
  10726. + return -EPROTO;
  10727. + }
  10728. +
  10729. + return 0;
  10730. +}
  10731. +
  10732. +/**
  10733. + * ssam_ctrl_notif_display_on() - Notify EC that the display has been turned on.
  10734. + * @ctrl: The controller.
  10735. + *
  10736. + * Notify the EC that the display has been turned back on and the driver has
  10737. + * exited its lower-power state. This notification is the counterpart to the
  10738. + * display-off notification sent via ssam_ctrl_notif_display_off() and will
  10739. + * reverse its effects, including resetting events to their default behavior.
  10740. + *
  10741. + * This function will only send the display-on notification command if display
  10742. + * noticications are supported by the EC. Currently all known devices support
  10743. + * these notification.
  10744. + *
  10745. + * See ssam_ctrl_notif_display_off() for more details.
  10746. + *
  10747. + * Return: Returns zero on success or if no request has been executed, the
  10748. + * status of the executed SAM request if that request failed, or %-EPROTO if
  10749. + * an unexpected response has been received.
  10750. + */
  10751. +int ssam_ctrl_notif_display_on(struct ssam_controller *ctrl)
  10752. +{
  10753. + int status;
  10754. + u8 response;
  10755. +
  10756. + ssam_dbg(ctrl, "pm: notifying display on\n");
  10757. +
  10758. + status = ssam_retry(ssam_ssh_notif_display_on, ctrl, &response);
  10759. + if (status)
  10760. + return status;
  10761. +
  10762. + if (response != 0) {
  10763. + ssam_err(ctrl, "unexpected response from display-on notification: 0x%02x\n",
  10764. + response);
  10765. + return -EPROTO;
  10766. + }
  10767. +
  10768. + return 0;
  10769. +}
  10770. +
  10771. +/**
  10772. + * ssam_ctrl_notif_d0_exit() - Notify EC that the driver/device exits the D0
  10773. + * power state.
  10774. + * @ctrl: The controller
  10775. + *
  10776. + * Notifies the EC that the driver prepares to exit the D0 power state in
  10777. + * favor of a lower-power state. Exact effects of this function related to the
  10778. + * EC are currently unknown.
  10779. + *
  10780. + * This function will only send the D0-exit notification command if D0-state
  10781. + * noticications are supported by the EC. Only newer Surface generations
  10782. + * support these notifications.
  10783. + *
  10784. + * Use ssam_ctrl_notif_d0_entry() to reverse the effects of this function.
  10785. + *
  10786. + * Return: Returns zero on success or if no request has been executed, the
  10787. + * status of the executed SAM request if that request failed, or %-EPROTO if
  10788. + * an unexpected response has been received.
  10789. + */
  10790. +int ssam_ctrl_notif_d0_exit(struct ssam_controller *ctrl)
  10791. +{
  10792. + int status;
  10793. + u8 response;
  10794. +
  10795. + if (!ctrl->caps.d3_closes_handle)
  10796. + return 0;
  10797. +
  10798. + ssam_dbg(ctrl, "pm: notifying D0 exit\n");
  10799. +
  10800. + status = ssam_retry(ssam_ssh_notif_d0_exit, ctrl, &response);
  10801. + if (status)
  10802. + return status;
  10803. +
  10804. + if (response != 0) {
  10805. + ssam_err(ctrl, "unexpected response from D0-exit notification:"
  10806. + " 0x%02x\n", response);
  10807. + return -EPROTO;
  10808. + }
  10809. +
  10810. + return 0;
  10811. +}
  10812. +
  10813. +/**
  10814. + * ssam_ctrl_notif_d0_entry() - Notify EC that the driver/device enters the D0
  10815. + * power state.
  10816. + * @ctrl: The controller
  10817. + *
  10818. + * Notifies the EC that the driver has exited a lower-power state and entered
  10819. + * the D0 power state. Exact effects of this function related to the EC are
  10820. + * currently unknown.
  10821. + *
  10822. + * This function will only send the D0-entry notification command if D0-state
  10823. + * noticications are supported by the EC. Only newer Surface generations
  10824. + * support these notifications.
  10825. + *
  10826. + * See ssam_ctrl_notif_d0_exit() for more details.
  10827. + *
  10828. + * Return: Returns zero on success or if no request has been executed, the
  10829. + * status of the executed SAM request if that request failed, or %-EPROTO if
  10830. + * an unexpected response has been received.
  10831. + */
  10832. +int ssam_ctrl_notif_d0_entry(struct ssam_controller *ctrl)
  10833. +{
  10834. + int status;
  10835. + u8 response;
  10836. +
  10837. + if (!ctrl->caps.d3_closes_handle)
  10838. + return 0;
  10839. +
  10840. + ssam_dbg(ctrl, "pm: notifying D0 entry\n");
  10841. +
  10842. + status = ssam_retry(ssam_ssh_notif_d0_entry, ctrl, &response);
  10843. + if (status)
  10844. + return status;
  10845. +
  10846. + if (response != 0) {
  10847. + ssam_err(ctrl, "unexpected response from D0-entry notification:"
  10848. + " 0x%02x\n", response);
  10849. + return -EPROTO;
  10850. + }
  10851. +
  10852. + return 0;
  10853. +}
  10854. +
  10855. +
  10856. +/* -- Top-level event registry interface. ----------------------------------- */
  10857. +
  10858. +/**
  10859. + * ssam_notifier_register() - Register an event notifier.
  10860. + * @ctrl: The controller to register the notifier on.
  10861. + * @n: The event notifier to register.
  10862. + *
  10863. + * Register an event notifier and increment the usage counter of the
  10864. + * associated SAM event. If the event was previously not enabled, it will be
  10865. + * enabled during this call.
  10866. + *
  10867. + * Return: Returns zero on success, %-ENOSPC if there have already been
  10868. + * %INT_MAX notifiers for the event ID/type associated with the notifier block
  10869. + * registered, %-ENOMEM if the corresponding event entry could not be
  10870. + * allocated. If this is the first time that a notifier block is registered
  10871. + * for the specific associated event, returns the status of the event-enable
  10872. + * EC-command.
  10873. + */
  10874. +int ssam_notifier_register(struct ssam_controller *ctrl,
  10875. + struct ssam_event_notifier *n)
  10876. +{
  10877. + u16 rqid = ssh_tc_to_rqid(n->event.id.target_category);
  10878. + struct ssam_nf_refcount_entry *entry;
  10879. + struct ssam_nf_head *nf_head;
  10880. + struct ssam_nf *nf;
  10881. + int status;
  10882. +
  10883. + if (!ssh_rqid_is_event(rqid))
  10884. + return -EINVAL;
  10885. +
  10886. + nf = &ctrl->cplt.event.notif;
  10887. + nf_head = &nf->head[ssh_rqid_to_event(rqid)];
  10888. +
  10889. + mutex_lock(&nf->lock);
  10890. +
  10891. + entry = ssam_nf_refcount_inc(nf, n->event.reg, n->event.id);
  10892. + if (IS_ERR(entry)) {
  10893. + mutex_unlock(&nf->lock);
  10894. + return PTR_ERR(entry);
  10895. + }
  10896. +
  10897. + ssam_dbg(ctrl, "enabling event (reg: 0x%02x, tc: 0x%02x, iid: 0x%02x,"
  10898. + " rc: %d)\n", n->event.reg.target_category,
  10899. + n->event.id.target_category, n->event.id.instance,
  10900. + entry->refcount);
  10901. +
  10902. + status = __ssam_nfblk_insert(nf_head, &n->base);
  10903. + if (status) {
  10904. + entry = ssam_nf_refcount_dec(nf, n->event.reg, n->event.id);
  10905. + if (entry->refcount == 0)
  10906. + kfree(entry);
  10907. +
  10908. + mutex_unlock(&nf->lock);
  10909. + return status;
  10910. + }
  10911. +
  10912. + if (entry->refcount == 1) {
  10913. + status = ssam_ssh_event_enable(ctrl, n->event.reg, n->event.id,
  10914. + n->event.flags);
  10915. + if (status) {
  10916. + __ssam_nfblk_remove(nf_head, &n->base);
  10917. + kfree(ssam_nf_refcount_dec(nf, n->event.reg, n->event.id));
  10918. + mutex_unlock(&nf->lock);
  10919. + synchronize_srcu(&nf_head->srcu);
  10920. + return status;
  10921. + }
  10922. +
  10923. + entry->flags = n->event.flags;
  10924. +
  10925. + } else if (entry->flags != n->event.flags) {
  10926. + ssam_warn(ctrl, "inconsistent flags when enabling event: got 0x%02x,"
  10927. + " expected 0x%02x (reg: 0x%02x, tc: 0x%02x, iid: 0x%02x)",
  10928. + n->event.flags, entry->flags, n->event.reg.target_category,
  10929. + n->event.id.target_category, n->event.id.instance);
  10930. + }
  10931. +
  10932. + mutex_unlock(&nf->lock);
  10933. + return 0;
  10934. +
  10935. +}
  10936. +EXPORT_SYMBOL_GPL(ssam_notifier_register);
  10937. +
  10938. +/**
  10939. + * ssam_notifier_unregister() - Unregister an event notifier.
  10940. + * @ctrl: The controller the notifier has been registered on.
  10941. + * @n: The event notifier to unregister.
  10942. + *
  10943. + * Unregister an event notifier and decrement the usage counter of the
  10944. + * associated SAM event. If the usage counter reaches zero, the event will be
  10945. + * disabled.
  10946. + *
  10947. + * Return: Returns zero on success, %-ENOENT if the given notifier block has
  10948. + * not been registered on the controller. If the given notifier block was the
  10949. + * last one associated with its specific event, returns the status of the
  10950. + * event-disable EC-command.
  10951. + */
  10952. +int ssam_notifier_unregister(struct ssam_controller *ctrl,
  10953. + struct ssam_event_notifier *n)
  10954. +{
  10955. + u16 rqid = ssh_tc_to_rqid(n->event.id.target_category);
  10956. + struct ssam_notifier_block **link;
  10957. + struct ssam_nf_refcount_entry *entry;
  10958. + struct ssam_nf_head *nf_head;
  10959. + struct ssam_nf *nf;
  10960. + int status = 0;
  10961. +
  10962. + if (!ssh_rqid_is_event(rqid))
  10963. + return -EINVAL;
  10964. +
  10965. + nf = &ctrl->cplt.event.notif;
  10966. + nf_head = &nf->head[ssh_rqid_to_event(rqid)];
  10967. +
  10968. + mutex_lock(&nf->lock);
  10969. +
  10970. + link = __ssam_nfblk_find_link(nf_head, &n->base);
  10971. + if (!link) {
  10972. + mutex_unlock(&nf->lock);
  10973. + return -ENOENT;
  10974. + }
  10975. +
  10976. + entry = ssam_nf_refcount_dec(nf, n->event.reg, n->event.id);
  10977. + if (WARN_ON(!entry)) {
  10978. + mutex_unlock(&nf->lock);
  10979. + return -ENOENT;
  10980. + }
  10981. +
  10982. + ssam_dbg(ctrl, "disabling event (reg: 0x%02x, tc: 0x%02x, iid: 0x%02x,"
  10983. + " rc: %d)\n", n->event.reg.target_category,
  10984. + n->event.id.target_category, n->event.id.instance,
  10985. + entry->refcount);
  10986. +
  10987. + if (entry->flags != n->event.flags) {
  10988. + ssam_warn(ctrl, "inconsistent flags when enabling event: got 0x%02x,"
  10989. + " expected 0x%02x (reg: 0x%02x, tc: 0x%02x, iid: 0x%02x)",
  10990. + n->event.flags, entry->flags, n->event.reg.target_category,
  10991. + n->event.id.target_category, n->event.id.instance);
  10992. + }
  10993. +
  10994. + if (entry->refcount == 0) {
  10995. + status = ssam_ssh_event_disable(ctrl, n->event.reg, n->event.id,
  10996. + n->event.flags);
  10997. + kfree(entry);
  10998. + }
  10999. +
  11000. + __ssam_nfblk_erase(link);
  11001. + mutex_unlock(&nf->lock);
  11002. + synchronize_srcu(&nf_head->srcu);
  11003. +
  11004. + return status;
  11005. +}
  11006. +EXPORT_SYMBOL_GPL(ssam_notifier_unregister);
  11007. +
  11008. +/**
  11009. + * ssam_notifier_disable_registered() - Disable events for all registered
  11010. + * notifiers.
  11011. + * @ctrl: The controller for which to disable the notifiers/events.
  11012. + *
  11013. + * Disables events for all currently registered notifiers. In case of an error
  11014. + * (EC command failing), all previously disabled events will be restored and
  11015. + * the error code returned.
  11016. + *
  11017. + * This function is intended to disable all events prior to hibenration entry.
  11018. + * See ssam_notifier_restore_registered() to restore/re-enable all events
  11019. + * disabled with this function.
  11020. + *
  11021. + * Note that this function will not disable events for notifiers registered
  11022. + * after calling this function. It should thus be made sure that no new
  11023. + * notifiers are going to be added after this call and before the corresponding
  11024. + * call to ssam_notifier_restore_registered().
  11025. + *
  11026. + * Return: Returns zero on success. In case of failure returns the error code
  11027. + * returned by the failed EC command to disable an event.
  11028. + */
  11029. +int ssam_notifier_disable_registered(struct ssam_controller *ctrl)
  11030. +{
  11031. + struct ssam_nf *nf = &ctrl->cplt.event.notif;
  11032. + struct rb_node *n;
  11033. + int status;
  11034. +
  11035. + mutex_lock(&nf->lock);
  11036. + for (n = rb_first(&nf->refcount); n != NULL; n = rb_next(n)) {
  11037. + struct ssam_nf_refcount_entry *e;
  11038. +
  11039. + e = rb_entry(n, struct ssam_nf_refcount_entry, node);
  11040. + status = ssam_ssh_event_disable(ctrl, e->key.reg,
  11041. + e->key.id, e->flags);
  11042. + if (status)
  11043. + goto err;
  11044. + }
  11045. + mutex_unlock(&nf->lock);
  11046. +
  11047. + return 0;
  11048. +
  11049. +err:
  11050. + for (n = rb_prev(n); n != NULL; n = rb_prev(n)) {
  11051. + struct ssam_nf_refcount_entry *e;
  11052. +
  11053. + e = rb_entry(n, struct ssam_nf_refcount_entry, node);
  11054. + ssam_ssh_event_enable(ctrl, e->key.reg, e->key.id, e->flags);
  11055. + }
  11056. + mutex_unlock(&nf->lock);
  11057. +
  11058. + return status;
  11059. +}
  11060. +
  11061. +/**
  11062. + * ssam_notifier_restore_registered() - Restore/re-enable events for all
  11063. + * registered notifiers.
  11064. + * @ctrl: The controller for which to restore the notifiers/events.
  11065. + *
  11066. + * Restores/re-enables all events for which notifiers have been registered on
  11067. + * the given controller. In case of a failure, the error is logged and the
  11068. + * function continues to try and enable the remaining events.
  11069. + *
  11070. + * This function is intended to restore/re-enable all registered events after
  11071. + * hibernation. See ssam_notifier_disable_registered() for the counter part
  11072. + * disabling the events and more details.
  11073. + */
  11074. +void ssam_notifier_restore_registered(struct ssam_controller *ctrl)
  11075. +{
  11076. + struct ssam_nf *nf = &ctrl->cplt.event.notif;
  11077. + struct rb_node *n;
  11078. +
  11079. + mutex_lock(&nf->lock);
  11080. + for (n = rb_first(&nf->refcount); n != NULL; n = rb_next(n)) {
  11081. + struct ssam_nf_refcount_entry *e;
  11082. +
  11083. + e = rb_entry(n, struct ssam_nf_refcount_entry, node);
  11084. +
  11085. + // ignore errors, will get logged in call
  11086. + ssam_ssh_event_enable(ctrl, e->key.reg, e->key.id, e->flags);
  11087. + }
  11088. + mutex_unlock(&nf->lock);
  11089. +}
  11090. +
  11091. +/**
  11092. + * ssam_notifier_empty() - Check if there are any registered notifiers.
  11093. + * @ctrl: The controller to check on.
  11094. + *
  11095. + * Return: Returns %true if there are currently no notifiers registered on the
  11096. + * controller, %false otherwise.
  11097. + */
  11098. +static bool ssam_notifier_empty(struct ssam_controller *ctrl)
  11099. +{
  11100. + struct ssam_nf *nf = &ctrl->cplt.event.notif;
  11101. + bool result;
  11102. +
  11103. + mutex_lock(&nf->lock);
  11104. + result = ssam_nf_refcount_empty(nf);
  11105. + mutex_unlock(&nf->lock);
  11106. +
  11107. + return result;
  11108. +}
  11109. +
  11110. +/**
  11111. + * ssam_notifier_unregister_all() - Unregister all currently registered
  11112. + * notifiers.
  11113. + * @ctrl: The controller to unregister the notifiers on.
  11114. + *
  11115. + * Unregisters all currently registered notifiers. This function is used to
  11116. + * ensure that all notifiers will be unregistered and assocaited
  11117. + * entries/resources freed when the controller is being shut down.
  11118. + */
  11119. +static void ssam_notifier_unregister_all(struct ssam_controller *ctrl)
  11120. +{
  11121. + struct ssam_nf *nf = &ctrl->cplt.event.notif;
  11122. + struct ssam_nf_refcount_entry *e, *n;
  11123. +
  11124. + mutex_lock(&nf->lock);
  11125. + rbtree_postorder_for_each_entry_safe(e, n, &nf->refcount, node) {
  11126. + // ignore errors, will get logged in call
  11127. + ssam_ssh_event_disable(ctrl, e->key.reg, e->key.id, e->flags);
  11128. + kfree(e);
  11129. + }
  11130. + nf->refcount = RB_ROOT;
  11131. + mutex_unlock(&nf->lock);
  11132. +}
  11133. +
  11134. +
  11135. +/* -- Wakeup IRQ. ----------------------------------------------------------- */
  11136. +
  11137. +static irqreturn_t ssam_irq_handle(int irq, void *dev_id)
  11138. +{
  11139. + struct ssam_controller *ctrl = dev_id;
  11140. +
  11141. + ssam_dbg(ctrl, "pm: wake irq triggered\n");
  11142. +
  11143. + /*
  11144. + * Note: Proper wakeup detection is currently unimplemented.
  11145. + * When the EC is in display-off or any other non-D0 state, it
  11146. + * does not send events/notifications to the host. Instead it
  11147. + * signals that there are events available via the wakeup IRQ.
  11148. + * This driver is responsible for calling back to the EC to
  11149. + * release these events one-by-one.
  11150. + *
  11151. + * This IRQ should not cause a full system resume by its own.
  11152. + * Instead, events should be handled by their respective subsystem
  11153. + * drivers, which in turn should signal whether a full system
  11154. + * resume should be performed.
  11155. + *
  11156. + * TODO: Send GPIO callback command repeatedly to EC until callback
  11157. + * returns 0x00. Return flag of callback is "has more events".
  11158. + * Each time the command is sent, one event is "released". Once
  11159. + * all events have been released (return = 0x00), the GPIO is
  11160. + * re-armed. Detect wakeup events during this process, go back to
  11161. + * sleep if no wakeup event has been received.
  11162. + */
  11163. +
  11164. + return IRQ_HANDLED;
  11165. +}
  11166. +
  11167. +/**
  11168. + * ssam_irq_setup() - Set up SAM EC wakeup-GPIO interrupt.
  11169. + * @ctrl: The controller for which the IRQ should be set up.
  11170. + *
  11171. + * Set up an IRQ for the wakeup-GPIO pin of the SAM EC. This IRQ can be used
  11172. + * to wake the device from a low power state.
  11173. + *
  11174. + * Note that this IRQ can only be triggered while the EC is in the display-off
  11175. + * state. In this state, events are not sent to the host in the usual way.
  11176. + * Instead the wakeup-GPIO gets pulled to "high" as long as there are pending
  11177. + * events and these events need to be released one-by-one via the GPIO
  11178. + * callback request, either until there are no events left and the GPIO is
  11179. + * reset, or all at once by transitioning the EC out of the display-off state,
  11180. + * which will also clear the GPIO.
  11181. + *
  11182. + * Not all events, however, should trigger a full system wakeup. Instead the
  11183. + * driver should, if necessary, inspect and forward each event to the
  11184. + * corresponding subsystem, which in turn should decide if the system needs to
  11185. + * be woken up. This logic has not been implemented yet, thus wakeup by this
  11186. + * IRQ should be disabled by default to avoid spurious wake-ups, caused, for
  11187. + * example, by the remaining battery percentage changing. Refer to comments in
  11188. + * this function and comments in the corresponding IRQ handler for more
  11189. + * details on how this should be implemented.
  11190. + *
  11191. + * See also ssam_ctrl_notif_display_off() and ssam_ctrl_notif_display_off()
  11192. + * for functions to transition the EC into and out of the display-off state as
  11193. + * well as more details on it.
  11194. + *
  11195. + * The IRQ is disabled by default and has to be enabled before it can wake up
  11196. + * the device from suspend via ssam_irq_arm_for_wakeup(). On teardown, the IRQ
  11197. + * should be freed via ssam_irq_free().
  11198. + */
  11199. +int ssam_irq_setup(struct ssam_controller *ctrl)
  11200. +{
  11201. + struct device *dev = ssam_controller_device(ctrl);
  11202. + struct gpio_desc *gpiod;
  11203. + int irq;
  11204. + int status;
  11205. +
  11206. + /*
  11207. + * The actual GPIO interrupt is declared in ACPI as TRIGGER_HIGH.
  11208. + * However, the GPIO line only gets reset by sending the GPIO callback
  11209. + * command to SAM (or alternatively the display-on notification). As
  11210. + * proper handling for this interrupt is not implemented yet, leaving
  11211. + * the IRQ at TRIGGER_HIGH would cause an IRQ storm (as the callback
  11212. + * never gets sent and thus the line never gets reset). To avoid this,
  11213. + * mark the IRQ as TRIGGER_RISING for now, only creating a single
  11214. + * interrupt, and let the SAM resume callback during the controller
  11215. + * resume process clear it.
  11216. + */
  11217. + const int irqf = IRQF_SHARED | IRQF_ONESHOT | IRQF_TRIGGER_RISING;
  11218. +
  11219. + gpiod = gpiod_get(dev, "ssam_wakeup-int", GPIOD_ASIS);
  11220. + if (IS_ERR(gpiod))
  11221. + return PTR_ERR(gpiod);
  11222. +
  11223. + irq = gpiod_to_irq(gpiod);
  11224. + gpiod_put(gpiod);
  11225. +
  11226. + if (irq < 0)
  11227. + return irq;
  11228. +
  11229. + status = request_threaded_irq(irq, NULL, ssam_irq_handle, irqf,
  11230. + "ssam_wakeup", ctrl);
  11231. + if (status)
  11232. + return status;
  11233. +
  11234. + ctrl->irq.num = irq;
  11235. + disable_irq(ctrl->irq.num);
  11236. + return 0;
  11237. +}
  11238. +
  11239. +/**
  11240. + * ssam_irq_free() - Free SAM EC wakeup-GPIO interrupt.
  11241. + * @ctrl: The controller for which the IRQ should be freed.
  11242. + *
  11243. + * Free the wakeup-GPIO IRQ previously set-up via ssam_irq_setup().
  11244. + */
  11245. +void ssam_irq_free(struct ssam_controller *ctrl)
  11246. +{
  11247. + free_irq(ctrl->irq.num, ctrl);
  11248. + ctrl->irq.num = -1;
  11249. +}
  11250. +
  11251. +/**
  11252. + * ssam_irq_arm_for_wakeup() - Arm the EC IRQ for wakeup, if enabled.
  11253. + * @ctrl: The controller for which the IRQ should be armed.
  11254. + *
  11255. + * Sets up the IRQ so that it can be used to wake the device. Specifically,
  11256. + * this function enables the irq and then, if the device is allowed to wake up
  11257. + * the system, calls enable_irq_wake(). See ssam_irq_disarm_wakeup() for the
  11258. + * corresponding function to disable the IRQ.
  11259. + *
  11260. + * This function is intended to arm the IRQ before entering S2idle suspend.
  11261. + *
  11262. + * Note: calls to ssam_irq_arm_for_wakeup() and ssam_irq_disarm_wakeup() must
  11263. + * be balanced.
  11264. + */
  11265. +int ssam_irq_arm_for_wakeup(struct ssam_controller *ctrl)
  11266. +{
  11267. + struct device *dev = ssam_controller_device(ctrl);
  11268. + int status;
  11269. +
  11270. + enable_irq(ctrl->irq.num);
  11271. + if (device_may_wakeup(dev)) {
  11272. + status = enable_irq_wake(ctrl->irq.num);
  11273. + if (status) {
  11274. + ssam_err(ctrl, "failed to enable wake IRQ: %d\n", status);
  11275. + disable_irq(ctrl->irq.num);
  11276. + return status;
  11277. + }
  11278. +
  11279. + ctrl->irq.wakeup_enabled = true;
  11280. + } else {
  11281. + ctrl->irq.wakeup_enabled = false;
  11282. + }
  11283. +
  11284. + return 0;
  11285. +}
  11286. +
  11287. +/**
  11288. + * ssam_irq_disarm_wakeup() - Disarm the wakeup IRQ.
  11289. + * @ctrl: The controller for which the IRQ should be disarmed.
  11290. + *
  11291. + * Disarm the IRQ previously set up for wake via ssam_irq_arm_for_wakeup().
  11292. + *
  11293. + * This function is intended to disarm the IRQ after exiting S2idle suspend.
  11294. + *
  11295. + * Note: calls to ssam_irq_arm_for_wakeup() and ssam_irq_disarm_wakeup() must
  11296. + * be balanced.
  11297. + */
  11298. +void ssam_irq_disarm_wakeup(struct ssam_controller *ctrl)
  11299. +{
  11300. + int status;
  11301. +
  11302. + if (ctrl->irq.wakeup_enabled) {
  11303. + status = disable_irq_wake(ctrl->irq.num);
  11304. + if (status)
  11305. + ssam_err(ctrl, "failed to disable wake IRQ: %d\n", status);
  11306. +
  11307. + ctrl->irq.wakeup_enabled = false;
  11308. + }
  11309. + disable_irq(ctrl->irq.num);
  11310. +}
  11311. diff --git a/drivers/misc/surface_aggregator/controller.h b/drivers/misc/surface_aggregator/controller.h
  11312. new file mode 100644
  11313. index 000000000000..96e2b87a25d9
  11314. --- /dev/null
  11315. +++ b/drivers/misc/surface_aggregator/controller.h
  11316. @@ -0,0 +1,288 @@
  11317. +/* SPDX-License-Identifier: GPL-2.0+ */
  11318. +/*
  11319. + * Main SSAM/SSH controller structure and functionality.
  11320. + *
  11321. + * Copyright (C) 2019-2020 Maximilian Luz <luzmaximilian@gmail.com>
  11322. + */
  11323. +
  11324. +#ifndef _SURFACE_AGGREGATOR_CONTROLLER_H
  11325. +#define _SURFACE_AGGREGATOR_CONTROLLER_H
  11326. +
  11327. +#include <linux/kref.h>
  11328. +#include <linux/list.h>
  11329. +#include <linux/mutex.h>
  11330. +#include <linux/rbtree.h>
  11331. +#include <linux/rwsem.h>
  11332. +#include <linux/serdev.h>
  11333. +#include <linux/spinlock.h>
  11334. +#include <linux/srcu.h>
  11335. +#include <linux/types.h>
  11336. +#include <linux/workqueue.h>
  11337. +
  11338. +#include <linux/surface_aggregator/controller.h>
  11339. +#include <linux/surface_aggregator/serial_hub.h>
  11340. +
  11341. +#include "ssh_request_layer.h"
  11342. +
  11343. +
  11344. +/* -- Safe counters. -------------------------------------------------------- */
  11345. +
  11346. +/**
  11347. + * struct ssh_seq_counter - Safe counter for SSH sequence IDs.
  11348. + * @value: The current counter value.
  11349. + */
  11350. +struct ssh_seq_counter {
  11351. + u8 value;
  11352. +};
  11353. +
  11354. +/**
  11355. + * struct ssh_rqid_counter - Safe counter for SSH request IDs.
  11356. + * @value: The current counter value.
  11357. + */
  11358. +struct ssh_rqid_counter {
  11359. + u16 value;
  11360. +};
  11361. +
  11362. +
  11363. +/* -- Event/notification system. -------------------------------------------- */
  11364. +
  11365. +/**
  11366. + * struct ssam_nf_head - Notifier head for SSAM events.
  11367. + * @srcu: The SRCU struct for synchronization.
  11368. + * @head: Head-pointer for the single-linked list of notifier blocks registered
  11369. + * under this head.
  11370. + */
  11371. +struct ssam_nf_head {
  11372. + struct srcu_struct srcu;
  11373. + struct ssam_notifier_block __rcu *head;
  11374. +};
  11375. +
  11376. +/**
  11377. + * struct ssam_nf - Notifier callback- and activation-registry for SSAM events.
  11378. + * @lock: Lock guarding (de-)registration of notifier blocks. Note: This
  11379. + * lock does not need to be held for notifier calls, only
  11380. + * registration and deregistration.
  11381. + * @refcount: The root of the RB-tree used for reference-counting enabled
  11382. + * events/notifications.
  11383. + * @head: The list of notifier heads for event/notifiaction callbacks.
  11384. + */
  11385. +struct ssam_nf {
  11386. + struct mutex lock;
  11387. + struct rb_root refcount;
  11388. + struct ssam_nf_head head[SSH_NUM_EVENTS];
  11389. +};
  11390. +
  11391. +
  11392. +/* -- Event/async request completion system. -------------------------------- */
  11393. +
  11394. +struct ssam_cplt;
  11395. +
  11396. +/**
  11397. + * struct ssam_event_item - Struct for event queuing and completion.
  11398. + * @node: The node in the queue.
  11399. + * @rqid: The request ID of the event.
  11400. + * @ops: Instance specific functions.
  11401. + * @ops.free: Callback for freeing this event item.
  11402. + * @event: Actual event data.
  11403. + */
  11404. +struct ssam_event_item {
  11405. + struct list_head node;
  11406. + u16 rqid;
  11407. +
  11408. + struct {
  11409. + void (*free)(struct ssam_event_item *event);
  11410. + } ops;
  11411. +
  11412. + struct ssam_event event; // must be last
  11413. +};
  11414. +
  11415. +/**
  11416. + * struct ssam_event_queue - Queue for completing received events.
  11417. + * @cplt: Reference to the completion system on which this queue is active.
  11418. + * @lock: The lock for any operation on the queue.
  11419. + * @head: The list-head of the queue.
  11420. + * @work: The &struct work_struct performing completion work for this queue.
  11421. + */
  11422. +struct ssam_event_queue {
  11423. + struct ssam_cplt *cplt;
  11424. +
  11425. + spinlock_t lock;
  11426. + struct list_head head;
  11427. + struct work_struct work;
  11428. +};
  11429. +
  11430. +/**
  11431. + * struct ssam_event_target - Set of queues for a single SSH target ID.
  11432. + * @queue: The array of queues, one queue per event ID.
  11433. + */
  11434. +struct ssam_event_target {
  11435. + struct ssam_event_queue queue[SSH_NUM_EVENTS];
  11436. +};
  11437. +
  11438. +/**
  11439. + * struct ssam_cplt - SSAM event/async request completion system.
  11440. + * @dev: The device with which this system is associated. Only used
  11441. + * for logging.
  11442. + * @wq: The &struct workqueue_struct on which all completion work
  11443. + * items are queued.
  11444. + * @event: Event completion management.
  11445. + * @event.target: Array of &struct ssam_event_target, one for each target.
  11446. + * @event.notif: Notifier callbacks and event activation reference counting.
  11447. + */
  11448. +struct ssam_cplt {
  11449. + struct device *dev;
  11450. + struct workqueue_struct *wq;
  11451. +
  11452. + struct {
  11453. + struct ssam_event_target target[SSH_NUM_TARGETS];
  11454. + struct ssam_nf notif;
  11455. + } event;
  11456. +};
  11457. +
  11458. +
  11459. +/* -- Main SSAM device structures. ------------------------------------------ */
  11460. +
  11461. +/**
  11462. + * enum ssam_controller_state - State values for &struct ssam_controller.
  11463. + * @SSAM_CONTROLLER_UNINITIALIZED:
  11464. + * The controller has not been initialized yet or has been deinitialized.
  11465. + * @SSAM_CONTROLLER_INITIALIZED:
  11466. + * The controller is initialized, but has not been started yet.
  11467. + * @SSAM_CONTROLLER_STARTED:
  11468. + * The controller has been started and is ready to use.
  11469. + * @SSAM_CONTROLLER_STOPPED:
  11470. + * The controller has been stopped.
  11471. + * @SSAM_CONTROLLER_SUSPENDED:
  11472. + * The controller has been suspended.
  11473. + */
  11474. +enum ssam_controller_state {
  11475. + SSAM_CONTROLLER_UNINITIALIZED,
  11476. + SSAM_CONTROLLER_INITIALIZED,
  11477. + SSAM_CONTROLLER_STARTED,
  11478. + SSAM_CONTROLLER_STOPPED,
  11479. + SSAM_CONTROLLER_SUSPENDED,
  11480. +};
  11481. +
  11482. +/**
  11483. + * struct ssam_controller_caps - Controller device capabilities.
  11484. + * @ssh_power_profile: SSH power profile.
  11485. + * @ssh_buffer_size: SSH driver UART buffer size.
  11486. + * @screen_on_sleep_idle_timeout: SAM UART screen-on sleep idle timeout.
  11487. + * @screen_off_sleep_idle_timeout: SAM UART screen-off sleep idle timeout.
  11488. + * @d3_closes_handle: SAM closes UART handle in D3.
  11489. + *
  11490. + * Controller and SSH device capabilities found in ACPI.
  11491. + */
  11492. +struct ssam_controller_caps {
  11493. + u32 ssh_power_profile;
  11494. + u32 ssh_buffer_size;
  11495. + u32 screen_on_sleep_idle_timeout;
  11496. + u32 screen_off_sleep_idle_timeout;
  11497. + u32 d3_closes_handle:1;
  11498. +};
  11499. +
  11500. +/**
  11501. + * struct ssam_controller - SSAM controller device.
  11502. + * @kref: Reference count of the controller.
  11503. + * @lock: Main lock for the controller, used to guard state changes.
  11504. + * @state: Controller state.
  11505. + * @rtl: Request transport layer for SSH I/O.
  11506. + * @cplt: Completion system for SSH/SSAM events and asynchronous requests.
  11507. + * @counter: Safe SSH message ID counters.
  11508. + * @counter.seq: Sequence ID counter.
  11509. + * @counter.rqid: Request ID counter.
  11510. + * @irq: Wakeup IRQ resources.
  11511. + * @irq.num: The wakeup IRQ number.
  11512. + * @irq.wakeup_enabled: Whether wakeup by IRQ is enabled during suspend.
  11513. + * @caps: The controller device capabilities.
  11514. + */
  11515. +struct ssam_controller {
  11516. + struct kref kref;
  11517. +
  11518. + struct rw_semaphore lock;
  11519. + enum ssam_controller_state state;
  11520. +
  11521. + struct ssh_rtl rtl;
  11522. + struct ssam_cplt cplt;
  11523. +
  11524. + struct {
  11525. + struct ssh_seq_counter seq;
  11526. + struct ssh_rqid_counter rqid;
  11527. + } counter;
  11528. +
  11529. + struct {
  11530. + int num;
  11531. + bool wakeup_enabled;
  11532. + } irq;
  11533. +
  11534. + struct ssam_controller_caps caps;
  11535. +};
  11536. +
  11537. +#define to_ssam_controller(ptr, member) \
  11538. + container_of(ptr, struct ssam_controller, member)
  11539. +
  11540. +#define ssam_dbg(ctrl, fmt, ...) rtl_dbg(&(ctrl)->rtl, fmt, ##__VA_ARGS__)
  11541. +#define ssam_info(ctrl, fmt, ...) rtl_info(&(ctrl)->rtl, fmt, ##__VA_ARGS__)
  11542. +#define ssam_warn(ctrl, fmt, ...) rtl_warn(&(ctrl)->rtl, fmt, ##__VA_ARGS__)
  11543. +#define ssam_err(ctrl, fmt, ...) rtl_err(&(ctrl)->rtl, fmt, ##__VA_ARGS__)
  11544. +
  11545. +
  11546. +/**
  11547. + * ssam_controller_receive_buf() - Provide input-data to the controller.
  11548. + * @ctrl: The controller.
  11549. + * @buf: The input buffer.
  11550. + * @n: The number of bytes in the input buffer.
  11551. + *
  11552. + * Provide input data to be evaluated by the controller, which has been
  11553. + * received via the lower-level transport.
  11554. + *
  11555. + * Return: Returns the number of bytes consumed, or, if the packet transport
  11556. + * layer of the controller has been shut down, %-ESHUTDOWN.
  11557. + */
  11558. +static inline
  11559. +int ssam_controller_receive_buf(struct ssam_controller *ctrl,
  11560. + const unsigned char *buf, size_t n)
  11561. +{
  11562. + return ssh_ptl_rx_rcvbuf(&ctrl->rtl.ptl, buf, n);
  11563. +}
  11564. +
  11565. +/**
  11566. + * ssam_controller_write_wakeup() - Notify the controller that the underlying
  11567. + * device has space available for data to be written.
  11568. + * @ctrl: The controller.
  11569. + */
  11570. +static inline void ssam_controller_write_wakeup(struct ssam_controller *ctrl)
  11571. +{
  11572. + ssh_ptl_tx_wakeup(&ctrl->rtl.ptl);
  11573. +}
  11574. +
  11575. +
  11576. +int ssam_controller_init(struct ssam_controller *ctrl, struct serdev_device *s);
  11577. +int ssam_controller_start(struct ssam_controller *ctrl);
  11578. +void ssam_controller_shutdown(struct ssam_controller *ctrl);
  11579. +void ssam_controller_destroy(struct ssam_controller *ctrl);
  11580. +
  11581. +int ssam_notifier_disable_registered(struct ssam_controller *ctrl);
  11582. +void ssam_notifier_restore_registered(struct ssam_controller *ctrl);
  11583. +
  11584. +int ssam_irq_setup(struct ssam_controller *ctrl);
  11585. +void ssam_irq_free(struct ssam_controller *ctrl);
  11586. +int ssam_irq_arm_for_wakeup(struct ssam_controller *ctrl);
  11587. +void ssam_irq_disarm_wakeup(struct ssam_controller *ctrl);
  11588. +
  11589. +void ssam_controller_lock(struct ssam_controller *c);
  11590. +void ssam_controller_unlock(struct ssam_controller *c);
  11591. +
  11592. +int ssam_get_firmware_version(struct ssam_controller *ctrl, u32 *version);
  11593. +int ssam_ctrl_notif_display_off(struct ssam_controller *ctrl);
  11594. +int ssam_ctrl_notif_display_on(struct ssam_controller *ctrl);
  11595. +int ssam_ctrl_notif_d0_exit(struct ssam_controller *ctrl);
  11596. +int ssam_ctrl_notif_d0_entry(struct ssam_controller *ctrl);
  11597. +
  11598. +int ssam_controller_suspend(struct ssam_controller *ctrl);
  11599. +int ssam_controller_resume(struct ssam_controller *ctrl);
  11600. +
  11601. +int ssam_event_item_cache_init(void);
  11602. +void ssam_event_item_cache_destroy(void);
  11603. +
  11604. +#endif /* _SURFACE_AGGREGATOR_CONTROLLER_H */
  11605. diff --git a/drivers/misc/surface_aggregator/core.c b/drivers/misc/surface_aggregator/core.c
  11606. new file mode 100644
  11607. index 000000000000..6aaac82b9091
  11608. --- /dev/null
  11609. +++ b/drivers/misc/surface_aggregator/core.c
  11610. @@ -0,0 +1,831 @@
  11611. +// SPDX-License-Identifier: GPL-2.0+
  11612. +/*
  11613. + * Surface Serial Hub (SSH) driver for communication with the Surface/System
  11614. + * Aggregator Module (SSAM/SAM).
  11615. + *
  11616. + * Provides access to a SAM-over-SSH connected EC via a controller device.
  11617. + * Handles communication via requests as well as enabling, disabling, and
  11618. + * relaying of events.
  11619. + *
  11620. + * Copyright (C) 2019-2020 Maximilian Luz <luzmaximilian@gmail.com>
  11621. + */
  11622. +
  11623. +#include <linux/acpi.h>
  11624. +#include <linux/atomic.h>
  11625. +#include <linux/completion.h>
  11626. +#include <linux/gpio/consumer.h>
  11627. +#include <linux/kernel.h>
  11628. +#include <linux/kref.h>
  11629. +#include <linux/module.h>
  11630. +#include <linux/pm.h>
  11631. +#include <linux/serdev.h>
  11632. +#include <linux/sysfs.h>
  11633. +
  11634. +#include <linux/surface_aggregator/controller.h>
  11635. +
  11636. +#include "bus.h"
  11637. +#include "controller.h"
  11638. +
  11639. +#define CREATE_TRACE_POINTS
  11640. +#include "trace.h"
  11641. +
  11642. +
  11643. +/* -- Static controller reference. ------------------------------------------ */
  11644. +
  11645. +/*
  11646. + * Main controller reference. The corresponding lock must be held while
  11647. + * accessing (reading/writing) the reference.
  11648. + */
  11649. +static struct ssam_controller *__ssam_controller;
  11650. +static DEFINE_SPINLOCK(__ssam_controller_lock);
  11651. +
  11652. +/**
  11653. + * ssam_get_controller() - Get reference to SSAM controller.
  11654. + *
  11655. + * Returns a reference to the SSAM controller of the system or %NULL if there
  11656. + * is none, it hasn't been set up yet, or it has already been unregistered.
  11657. + * This function automatically increments the reference count of the
  11658. + * controller, thus the calling party must ensure that ssam_controller_put()
  11659. + * is called when it doesn't need the controller any more.
  11660. + */
  11661. +struct ssam_controller *ssam_get_controller(void)
  11662. +{
  11663. + struct ssam_controller *ctrl;
  11664. +
  11665. + spin_lock(&__ssam_controller_lock);
  11666. +
  11667. + ctrl = __ssam_controller;
  11668. + if (!ctrl)
  11669. + goto out;
  11670. +
  11671. + if (WARN_ON(!kref_get_unless_zero(&ctrl->kref)))
  11672. + ctrl = NULL;
  11673. +
  11674. +out:
  11675. + spin_unlock(&__ssam_controller_lock);
  11676. + return ctrl;
  11677. +}
  11678. +EXPORT_SYMBOL_GPL(ssam_get_controller);
  11679. +
  11680. +/**
  11681. + * ssam_try_set_controller() - Try to set the main controller reference.
  11682. + * @ctrl: The controller to which the reference should point.
  11683. + *
  11684. + * Set the main controller reference to the given pointer if the reference
  11685. + * hasn't been set already.
  11686. + *
  11687. + * Return: Returns zero on success or %-EBUSY if the reference has already
  11688. + * been set.
  11689. + */
  11690. +static int ssam_try_set_controller(struct ssam_controller *ctrl)
  11691. +{
  11692. + int status = 0;
  11693. +
  11694. + spin_lock(&__ssam_controller_lock);
  11695. + if (!__ssam_controller)
  11696. + __ssam_controller = ctrl;
  11697. + else
  11698. + status = -EBUSY;
  11699. + spin_unlock(&__ssam_controller_lock);
  11700. +
  11701. + return status;
  11702. +}
  11703. +
  11704. +/**
  11705. + * ssam_clear_controller() - Remove/clear the main controller reference.
  11706. + *
  11707. + * Clears the main controller reference, i.e. sets it to %NULL. This function
  11708. + * should be called before the controller is shut down.
  11709. + */
  11710. +static void ssam_clear_controller(void)
  11711. +{
  11712. + spin_lock(&__ssam_controller_lock);
  11713. + __ssam_controller = NULL;
  11714. + spin_unlock(&__ssam_controller_lock);
  11715. +}
  11716. +
  11717. +
  11718. +/**
  11719. + * ssam_client_link() - Link an arbitrary client device to the controller.
  11720. + * @c: The controller to link to.
  11721. + * @client: The client device.
  11722. + *
  11723. + * Link an arbitrary client device to the controller by creating a device link
  11724. + * between it as consumer and the controller device as provider. This function
  11725. + * can be used for non-SSAM devices (or SSAM devices not registered as child
  11726. + * under the controller) to guarantee that the controller is valid for as long
  11727. + * as the driver of the client device is bound, and that proper suspend and
  11728. + * resume ordering is guaranteed.
  11729. + *
  11730. + * The device link does not have to be destructed manually. It is removed
  11731. + * automatically once the driver of the client device unbinds.
  11732. + *
  11733. + * Return: Returns zero on success, %-ENXIO if the controller is not ready or
  11734. + * going to be removed soon, or %-ENOMEM if the device link could not be
  11735. + * created for other reasons.
  11736. + */
  11737. +int ssam_client_link(struct ssam_controller *c, struct device *client)
  11738. +{
  11739. + const u32 flags = DL_FLAG_PM_RUNTIME | DL_FLAG_AUTOREMOVE_CONSUMER;
  11740. + struct device_link *link;
  11741. + struct device *ctrldev;
  11742. +
  11743. + ssam_controller_statelock(c);
  11744. +
  11745. + if (c->state != SSAM_CONTROLLER_STARTED) {
  11746. + ssam_controller_stateunlock(c);
  11747. + return -ENXIO;
  11748. + }
  11749. +
  11750. + ctrldev = ssam_controller_device(c);
  11751. + if (!ctrldev) {
  11752. + ssam_controller_stateunlock(c);
  11753. + return -ENXIO;
  11754. + }
  11755. +
  11756. + link = device_link_add(client, ctrldev, flags);
  11757. + if (!link) {
  11758. + ssam_controller_stateunlock(c);
  11759. + return -ENOMEM;
  11760. + }
  11761. +
  11762. + /*
  11763. + * Return -ENXIO if supplier driver is on its way to be removed. In this
  11764. + * case, the controller won't be around for much longer and the device
  11765. + * link is not going to save us any more, as unbinding is already in
  11766. + * progress.
  11767. + */
  11768. + if (READ_ONCE(link->status) == DL_STATE_SUPPLIER_UNBIND) {
  11769. + ssam_controller_stateunlock(c);
  11770. + return -ENXIO;
  11771. + }
  11772. +
  11773. + ssam_controller_stateunlock(c);
  11774. + return 0;
  11775. +}
  11776. +EXPORT_SYMBOL_GPL(ssam_client_link);
  11777. +
  11778. +/**
  11779. + * ssam_client_bind() - Bind an arbitrary client device to the controller.
  11780. + * @client: The client device.
  11781. + * @ctrl: A pointer to where the controller reference should be returned.
  11782. + *
  11783. + * Link an arbitrary client device to the controller by creating a device link
  11784. + * between it as consumer and the main controller device as provider. This
  11785. + * function can be used for non-SSAM devices to guarantee that the controller
  11786. + * returned by this function is valid for as long as the driver of the client
  11787. + * device is bound, and that proper suspend and resume ordering is guaranteed.
  11788. + *
  11789. + * This function does essentially the same as ssam_client_link(), except that
  11790. + * it first fetches the main controller reference, then creates the link, and
  11791. + * finally returns this reference in the @ctrl parameter. Note that this
  11792. + * function does not increment the reference counter of the controller, as,
  11793. + * due to the link, the controller lifetime is assured as long as the driver
  11794. + * of the client device is bound.
  11795. + *
  11796. + * It is not valid to use the controller reference obtained by this method
  11797. + * outside of the driver bound to the client device at the time of calling
  11798. + * this function, without first incrementing the reference count of the
  11799. + * controller via ssam_controller_get(). Even after doing this, care must be
  11800. + * taken that requests are only submitted and notifiers are only
  11801. + * (un-)registered when the controller is active and not suspended. In other
  11802. + * words: The device link only lives as long as the client driver is bound and
  11803. + * any guarantees enforced by this link (e.g. active controller state) can
  11804. + * only be relied upon as long as this link exists and may need to be enforced
  11805. + * in other ways afterwards.
  11806. + *
  11807. + * The created device link does not have to be destructed manually. It is
  11808. + * removed automatically once the driver of the client device unbinds.
  11809. + *
  11810. + * Return: Returns zero on success, %-ENXIO if the controller is not present,
  11811. + * not ready or going to be removed soon, or %-ENOMEM if the device link could
  11812. + * not be created for other reasons.
  11813. + */
  11814. +int ssam_client_bind(struct device *client, struct ssam_controller **ctrl)
  11815. +{
  11816. + struct ssam_controller *c;
  11817. + int status;
  11818. +
  11819. + c = ssam_get_controller();
  11820. + if (!c)
  11821. + return -ENXIO;
  11822. +
  11823. + status = ssam_client_link(c, client);
  11824. +
  11825. + /*
  11826. + * Note that we can drop our controller reference in both success and
  11827. + * failure cases: On success, we have bound the controller lifetime
  11828. + * inherently to the client driver lifetime, i.e. it the controller is
  11829. + * now guaranteed to outlive the client driver. On failure, we're not
  11830. + * going to use the controller any more.
  11831. + */
  11832. + ssam_controller_put(c);
  11833. +
  11834. + *ctrl = status == 0 ? c : NULL;
  11835. + return status;
  11836. +}
  11837. +EXPORT_SYMBOL_GPL(ssam_client_bind);
  11838. +
  11839. +
  11840. +/* -- Glue layer (serdev_device -> ssam_controller). ------------------------ */
  11841. +
  11842. +static int ssam_receive_buf(struct serdev_device *dev, const unsigned char *buf,
  11843. + size_t n)
  11844. +{
  11845. + struct ssam_controller *ctrl;
  11846. +
  11847. + ctrl = serdev_device_get_drvdata(dev);
  11848. + return ssam_controller_receive_buf(ctrl, buf, n);
  11849. +}
  11850. +
  11851. +static void ssam_write_wakeup(struct serdev_device *dev)
  11852. +{
  11853. + ssam_controller_write_wakeup(serdev_device_get_drvdata(dev));
  11854. +}
  11855. +
  11856. +static const struct serdev_device_ops ssam_serdev_ops = {
  11857. + .receive_buf = ssam_receive_buf,
  11858. + .write_wakeup = ssam_write_wakeup,
  11859. +};
  11860. +
  11861. +
  11862. +/* -- SysFS and misc. ------------------------------------------------------- */
  11863. +
  11864. +static int ssam_log_firmware_version(struct ssam_controller *ctrl)
  11865. +{
  11866. + u32 version, a, b, c;
  11867. + int status;
  11868. +
  11869. + status = ssam_get_firmware_version(ctrl, &version);
  11870. + if (status)
  11871. + return status;
  11872. +
  11873. + a = (version >> 24) & 0xff;
  11874. + b = ((version >> 8) & 0xffff);
  11875. + c = version & 0xff;
  11876. +
  11877. + ssam_info(ctrl, "SAM firmware version: %u.%u.%u\n", a, b, c);
  11878. + return 0;
  11879. +}
  11880. +
  11881. +static ssize_t firmware_version_show(struct device *dev,
  11882. + struct device_attribute *attr, char *buf)
  11883. +{
  11884. + struct ssam_controller *ctrl = dev_get_drvdata(dev);
  11885. + u32 version, a, b, c;
  11886. + int status;
  11887. +
  11888. + status = ssam_get_firmware_version(ctrl, &version);
  11889. + if (status < 0)
  11890. + return status;
  11891. +
  11892. + a = (version >> 24) & 0xff;
  11893. + b = ((version >> 8) & 0xffff);
  11894. + c = version & 0xff;
  11895. +
  11896. + return snprintf(buf, PAGE_SIZE - 1, "%u.%u.%u\n", a, b, c);
  11897. +}
  11898. +static DEVICE_ATTR_RO(firmware_version);
  11899. +
  11900. +static struct attribute *ssam_sam_attrs[] = {
  11901. + &dev_attr_firmware_version.attr,
  11902. + NULL,
  11903. +};
  11904. +
  11905. +static const struct attribute_group ssam_sam_group = {
  11906. + .name = "sam",
  11907. + .attrs = ssam_sam_attrs,
  11908. +};
  11909. +
  11910. +
  11911. +/* -- ACPI based device setup. ---------------------------------------------- */
  11912. +
  11913. +static acpi_status ssam_serdev_setup_via_acpi_crs(struct acpi_resource *rsc,
  11914. + void *ctx)
  11915. +{
  11916. + struct serdev_device *serdev = ctx;
  11917. + struct acpi_resource_common_serialbus *serial;
  11918. + struct acpi_resource_uart_serialbus *uart;
  11919. + bool flow_control;
  11920. + int status = 0;
  11921. +
  11922. + if (rsc->type != ACPI_RESOURCE_TYPE_SERIAL_BUS)
  11923. + return AE_OK;
  11924. +
  11925. + serial = &rsc->data.common_serial_bus;
  11926. + if (serial->type != ACPI_RESOURCE_SERIAL_TYPE_UART)
  11927. + return AE_OK;
  11928. +
  11929. + uart = &rsc->data.uart_serial_bus;
  11930. +
  11931. + // set up serdev device
  11932. + serdev_device_set_baudrate(serdev, uart->default_baud_rate);
  11933. +
  11934. + // serdev currently only supports RTSCTS flow control
  11935. + if (uart->flow_control & (~((u8) ACPI_UART_FLOW_CONTROL_HW))) {
  11936. + dev_warn(&serdev->dev, "setup: unsupported flow control (value: 0x%02x)\n",
  11937. + uart->flow_control);
  11938. + }
  11939. +
  11940. + // set RTSCTS flow control
  11941. + flow_control = uart->flow_control & ACPI_UART_FLOW_CONTROL_HW;
  11942. + serdev_device_set_flow_control(serdev, flow_control);
  11943. +
  11944. + // serdev currently only supports EVEN/ODD parity
  11945. + switch (uart->parity) {
  11946. + case ACPI_UART_PARITY_NONE:
  11947. + status = serdev_device_set_parity(serdev, SERDEV_PARITY_NONE);
  11948. + break;
  11949. + case ACPI_UART_PARITY_EVEN:
  11950. + status = serdev_device_set_parity(serdev, SERDEV_PARITY_EVEN);
  11951. + break;
  11952. + case ACPI_UART_PARITY_ODD:
  11953. + status = serdev_device_set_parity(serdev, SERDEV_PARITY_ODD);
  11954. + break;
  11955. + default:
  11956. + dev_warn(&serdev->dev, "setup: unsupported parity (value: 0x%02x)\n",
  11957. + uart->parity);
  11958. + break;
  11959. + }
  11960. +
  11961. + if (status) {
  11962. + dev_err(&serdev->dev, "setup: failed to set parity (value: 0x%02x,"
  11963. + " error: %d)\n", uart->parity, status);
  11964. + return AE_ERROR;
  11965. + }
  11966. +
  11967. + return AE_CTRL_TERMINATE; // we've found the resource and are done
  11968. +}
  11969. +
  11970. +static acpi_status ssam_serdev_setup_via_acpi(acpi_handle handle,
  11971. + struct serdev_device *serdev)
  11972. +{
  11973. + return acpi_walk_resources(handle, METHOD_NAME__CRS,
  11974. + ssam_serdev_setup_via_acpi_crs, serdev);
  11975. +}
  11976. +
  11977. +
  11978. +/* -- Power management. ----------------------------------------------------- */
  11979. +
  11980. +static void ssam_serial_hub_shutdown(struct device *dev)
  11981. +{
  11982. + struct ssam_controller *c = dev_get_drvdata(dev);
  11983. + int status;
  11984. +
  11985. + /*
  11986. + * Try to disable notifiers, signal display-off and D0-exit, ignore any
  11987. + * errors.
  11988. + *
  11989. + * Note: It has not been established yet if this is actually
  11990. + * necessary/useful for shutdown.
  11991. + */
  11992. +
  11993. + status = ssam_notifier_disable_registered(c);
  11994. + if (status) {
  11995. + ssam_err(c, "pm: failed to disable notifiers for shutdown: %d\n",
  11996. + status);
  11997. + }
  11998. +
  11999. + status = ssam_ctrl_notif_display_off(c);
  12000. + if (status)
  12001. + ssam_err(c, "pm: display-off notification failed: %d\n", status);
  12002. +
  12003. + status = ssam_ctrl_notif_d0_exit(c);
  12004. + if (status)
  12005. + ssam_err(c, "pm: D0-exit notification failed: %d\n", status);
  12006. +}
  12007. +
  12008. +#ifdef CONFIG_PM_SLEEP
  12009. +
  12010. +static int ssam_serial_hub_pm_prepare(struct device *dev)
  12011. +{
  12012. + struct ssam_controller *c = dev_get_drvdata(dev);
  12013. + int status;
  12014. +
  12015. + /*
  12016. + * Try to signal display-off, This will quiesce events.
  12017. + *
  12018. + * Note: Signalling display-off/display-on should normally be done from
  12019. + * some sort of display state notifier. As that is not available, signal
  12020. + * it here.
  12021. + */
  12022. +
  12023. + status = ssam_ctrl_notif_display_off(c);
  12024. + if (status)
  12025. + ssam_err(c, "pm: display-off notification failed: %d\n", status);
  12026. +
  12027. + return status;
  12028. +}
  12029. +
  12030. +static void ssam_serial_hub_pm_complete(struct device *dev)
  12031. +{
  12032. + struct ssam_controller *c = dev_get_drvdata(dev);
  12033. + int status;
  12034. +
  12035. + /*
  12036. + * Try to signal display-on. This will restore events.
  12037. + *
  12038. + * Note: Signalling display-off/display-on should normally be done from
  12039. + * some sort of display state notifier. As that is not available, signal
  12040. + * it here.
  12041. + */
  12042. +
  12043. + status = ssam_ctrl_notif_display_on(c);
  12044. + if (status)
  12045. + ssam_err(c, "pm: display-on notification failed: %d\n", status);
  12046. +}
  12047. +
  12048. +static int ssam_serial_hub_pm_suspend(struct device *dev)
  12049. +{
  12050. + struct ssam_controller *c = dev_get_drvdata(dev);
  12051. + int status;
  12052. +
  12053. + /*
  12054. + * Try to signal D0-exit, enable IRQ wakeup if specified. Abort on
  12055. + * error.
  12056. + */
  12057. +
  12058. + status = ssam_ctrl_notif_d0_exit(c);
  12059. + if (status) {
  12060. + ssam_err(c, "pm: D0-exit notification failed: %d\n", status);
  12061. + goto err_notif;
  12062. + }
  12063. +
  12064. + status = ssam_irq_arm_for_wakeup(c);
  12065. + if (status)
  12066. + goto err_irq;
  12067. +
  12068. + WARN_ON(ssam_controller_suspend(c));
  12069. + return 0;
  12070. +
  12071. +err_irq:
  12072. + ssam_ctrl_notif_d0_entry(c);
  12073. +err_notif:
  12074. + ssam_ctrl_notif_display_on(c);
  12075. + return status;
  12076. +}
  12077. +
  12078. +static int ssam_serial_hub_pm_resume(struct device *dev)
  12079. +{
  12080. + struct ssam_controller *c = dev_get_drvdata(dev);
  12081. + int status;
  12082. +
  12083. + WARN_ON(ssam_controller_resume(c));
  12084. +
  12085. + /*
  12086. + * Try to disable IRQ wakeup (if specified) and signal D0-entry. In
  12087. + * case of errors, log them and try to restore normal operation state
  12088. + * as far as possible.
  12089. + *
  12090. + * Note: Signalling display-off/display-on should normally be done from
  12091. + * some sort of display state notifier. As that is not available, signal
  12092. + * it here.
  12093. + */
  12094. +
  12095. + ssam_irq_disarm_wakeup(c);
  12096. +
  12097. + status = ssam_ctrl_notif_d0_entry(c);
  12098. + if (status)
  12099. + ssam_err(c, "pm: D0-entry notification failed: %d\n", status);
  12100. +
  12101. + return 0;
  12102. +}
  12103. +
  12104. +static int ssam_serial_hub_pm_freeze(struct device *dev)
  12105. +{
  12106. + struct ssam_controller *c = dev_get_drvdata(dev);
  12107. + int status;
  12108. +
  12109. + /*
  12110. + * During hibernation image creation, we only have to ensure that the
  12111. + * EC doesn't send us any events. This is done via the display-off
  12112. + * and D0-exit notifications. Note that this sets up the wakeup IRQ
  12113. + * on the EC side, however, we have disabled it by default on our side
  12114. + * and won't enable it here.
  12115. + *
  12116. + * See ssam_serial_hub_poweroff() for more details on the hibernation
  12117. + * process.
  12118. + */
  12119. +
  12120. + status = ssam_ctrl_notif_d0_exit(c);
  12121. + if (status) {
  12122. + ssam_err(c, "pm: D0-exit notification failed: %d\n", status);
  12123. + ssam_ctrl_notif_display_on(c);
  12124. + return status;
  12125. + }
  12126. +
  12127. + WARN_ON(ssam_controller_suspend(c));
  12128. + return 0;
  12129. +}
  12130. +
  12131. +static int ssam_serial_hub_pm_thaw(struct device *dev)
  12132. +{
  12133. + struct ssam_controller *c = dev_get_drvdata(dev);
  12134. + int status;
  12135. +
  12136. + WARN_ON(ssam_controller_resume(c));
  12137. +
  12138. + status = ssam_ctrl_notif_d0_entry(c);
  12139. + if (status)
  12140. + ssam_err(c, "pm: D0-exit notification failed: %d\n", status);
  12141. +
  12142. + return status;
  12143. +}
  12144. +
  12145. +static int ssam_serial_hub_pm_poweroff(struct device *dev)
  12146. +{
  12147. + struct ssam_controller *c = dev_get_drvdata(dev);
  12148. + int status;
  12149. +
  12150. + /*
  12151. + * When entering hibernation and powering off the system, the EC, at
  12152. + * least on some models, may disable events. Without us taking care of
  12153. + * that, this leads to events not being enabled/restored when the
  12154. + * system resumes from hibernation, resulting SAM-HID subsystem devices
  12155. + * (i.e. keyboard, touchpad) not working, AC-plug/AC-unplug events being
  12156. + * gone, etc.
  12157. + *
  12158. + * To avoid these issues, we disable all registered events here (this is
  12159. + * likely not actually required) and restore them during the drivers PM
  12160. + * restore callback.
  12161. + *
  12162. + * Wakeup from the EC interrupt is not supported during hibernation,
  12163. + * so don't arm the IRQ here.
  12164. + */
  12165. +
  12166. + status = ssam_notifier_disable_registered(c);
  12167. + if (status) {
  12168. + ssam_err(c, "pm: failed to disable notifiers for hibernation: %d\n",
  12169. + status);
  12170. + return status;
  12171. + }
  12172. +
  12173. + status = ssam_ctrl_notif_d0_exit(c);
  12174. + if (status) {
  12175. + ssam_err(c, "pm: D0-exit notification failed: %d\n", status);
  12176. + ssam_notifier_restore_registered(c);
  12177. + return status;
  12178. + }
  12179. +
  12180. + WARN_ON(ssam_controller_suspend(c));
  12181. + return 0;
  12182. +}
  12183. +
  12184. +static int ssam_serial_hub_pm_restore(struct device *dev)
  12185. +{
  12186. + struct ssam_controller *c = dev_get_drvdata(dev);
  12187. + int status;
  12188. +
  12189. + /*
  12190. + * Ignore but log errors, try to restore state as much as possible in
  12191. + * case of failures. See ssam_serial_hub_poweroff() for more details on
  12192. + * the hibernation process.
  12193. + */
  12194. +
  12195. + WARN_ON(ssam_controller_resume(c));
  12196. +
  12197. + status = ssam_ctrl_notif_d0_entry(c);
  12198. + if (status)
  12199. + ssam_err(c, "pm: D0-entry notification failed: %d\n", status);
  12200. +
  12201. + ssam_notifier_restore_registered(c);
  12202. + return 0;
  12203. +}
  12204. +
  12205. +static const struct dev_pm_ops ssam_serial_hub_pm_ops = {
  12206. + .prepare = ssam_serial_hub_pm_prepare,
  12207. + .complete = ssam_serial_hub_pm_complete,
  12208. + .suspend = ssam_serial_hub_pm_suspend,
  12209. + .resume = ssam_serial_hub_pm_resume,
  12210. + .freeze = ssam_serial_hub_pm_freeze,
  12211. + .thaw = ssam_serial_hub_pm_thaw,
  12212. + .poweroff = ssam_serial_hub_pm_poweroff,
  12213. + .restore = ssam_serial_hub_pm_restore,
  12214. +};
  12215. +
  12216. +#else /* CONFIG_PM_SLEEP */
  12217. +
  12218. +static const struct dev_pm_ops ssam_serial_hub_pm_ops = { };
  12219. +
  12220. +#endif /* CONFIG_PM_SLEEP */
  12221. +
  12222. +
  12223. +/* -- Device/driver setup. -------------------------------------------------- */
  12224. +
  12225. +static const struct acpi_gpio_params gpio_ssam_wakeup_int = { 0, 0, false };
  12226. +static const struct acpi_gpio_params gpio_ssam_wakeup = { 1, 0, false };
  12227. +
  12228. +static const struct acpi_gpio_mapping ssam_acpi_gpios[] = {
  12229. + { "ssam_wakeup-int-gpio", &gpio_ssam_wakeup_int, 1 },
  12230. + { "ssam_wakeup-gpio", &gpio_ssam_wakeup, 1 },
  12231. + { },
  12232. +};
  12233. +
  12234. +static int ssam_serial_hub_probe(struct serdev_device *serdev)
  12235. +{
  12236. + struct ssam_controller *ctrl;
  12237. + acpi_handle *ssh = ACPI_HANDLE(&serdev->dev);
  12238. + acpi_status astatus;
  12239. + int status;
  12240. +
  12241. + if (gpiod_count(&serdev->dev, NULL) < 0)
  12242. + return -ENODEV;
  12243. +
  12244. + status = devm_acpi_dev_add_driver_gpios(&serdev->dev, ssam_acpi_gpios);
  12245. + if (status)
  12246. + return status;
  12247. +
  12248. + // allocate controller
  12249. + ctrl = kzalloc(sizeof(*ctrl), GFP_KERNEL);
  12250. + if (!ctrl)
  12251. + return -ENOMEM;
  12252. +
  12253. + // initialize controller
  12254. + status = ssam_controller_init(ctrl, serdev);
  12255. + if (status)
  12256. + goto err_ctrl_init;
  12257. +
  12258. + // set up serdev device
  12259. + serdev_device_set_drvdata(serdev, ctrl);
  12260. + serdev_device_set_client_ops(serdev, &ssam_serdev_ops);
  12261. + status = serdev_device_open(serdev);
  12262. + if (status)
  12263. + goto err_devopen;
  12264. +
  12265. + astatus = ssam_serdev_setup_via_acpi(ssh, serdev);
  12266. + if (ACPI_FAILURE(astatus)) {
  12267. + status = -ENXIO;
  12268. + goto err_devinit;
  12269. + }
  12270. +
  12271. + // start controller
  12272. + status = ssam_controller_start(ctrl);
  12273. + if (status)
  12274. + goto err_devinit;
  12275. +
  12276. + // initial SAM requests: log version, notify default/init power states
  12277. + status = ssam_log_firmware_version(ctrl);
  12278. + if (status)
  12279. + goto err_initrq;
  12280. +
  12281. + status = ssam_ctrl_notif_d0_entry(ctrl);
  12282. + if (status)
  12283. + goto err_initrq;
  12284. +
  12285. + status = ssam_ctrl_notif_display_on(ctrl);
  12286. + if (status)
  12287. + goto err_initrq;
  12288. +
  12289. + status = sysfs_create_group(&serdev->dev.kobj, &ssam_sam_group);
  12290. + if (status)
  12291. + goto err_initrq;
  12292. +
  12293. + // setup IRQ
  12294. + status = ssam_irq_setup(ctrl);
  12295. + if (status)
  12296. + goto err_irq;
  12297. +
  12298. + // finally, set main controller reference
  12299. + status = ssam_try_set_controller(ctrl);
  12300. + if (WARN_ON(status)) // currently, we're the only provider
  12301. + goto err_mainref;
  12302. +
  12303. + /*
  12304. + * TODO: The EC can wake up the system via the associated GPIO interrupt
  12305. + * in multiple situations. One of which is the remaining battery
  12306. + * capacity falling below a certain threshold. Normally, we should
  12307. + * use the device_init_wakeup function, however, the EC also seems
  12308. + * to have other reasons for waking up the system and it seems
  12309. + * that Windows has additional checks whether the system should be
  12310. + * resumed. In short, this causes some spurious unwanted wake-ups.
  12311. + * For now let's thus default power/wakeup to false.
  12312. + */
  12313. + device_set_wakeup_capable(&serdev->dev, true);
  12314. + acpi_walk_dep_device_list(ssh);
  12315. +
  12316. + return 0;
  12317. +
  12318. +err_mainref:
  12319. + ssam_irq_free(ctrl);
  12320. +err_irq:
  12321. + sysfs_remove_group(&serdev->dev.kobj, &ssam_sam_group);
  12322. +err_initrq:
  12323. + ssam_controller_shutdown(ctrl);
  12324. +err_devinit:
  12325. + serdev_device_close(serdev);
  12326. +err_devopen:
  12327. + ssam_controller_destroy(ctrl);
  12328. +err_ctrl_init:
  12329. + kfree(ctrl);
  12330. + return status;
  12331. +}
  12332. +
  12333. +static void ssam_serial_hub_remove(struct serdev_device *serdev)
  12334. +{
  12335. + struct ssam_controller *ctrl = serdev_device_get_drvdata(serdev);
  12336. + int status;
  12337. +
  12338. + // clear static reference, so that no one else can get a new one
  12339. + ssam_clear_controller();
  12340. +
  12341. + ssam_irq_free(ctrl);
  12342. + sysfs_remove_group(&serdev->dev.kobj, &ssam_sam_group);
  12343. + ssam_controller_lock(ctrl);
  12344. +
  12345. + // remove all client devices
  12346. + ssam_controller_remove_clients(ctrl);
  12347. +
  12348. + // act as if suspending to disable events
  12349. + status = ssam_ctrl_notif_display_off(ctrl);
  12350. + if (status) {
  12351. + dev_err(&serdev->dev, "display-off notification failed: %d\n",
  12352. + status);
  12353. + }
  12354. +
  12355. + status = ssam_ctrl_notif_d0_exit(ctrl);
  12356. + if (status) {
  12357. + dev_err(&serdev->dev, "D0-exit notification failed: %d\n",
  12358. + status);
  12359. + }
  12360. +
  12361. + // shut down controller and remove serdev device reference from it
  12362. + ssam_controller_shutdown(ctrl);
  12363. +
  12364. + // shut down actual transport
  12365. + serdev_device_wait_until_sent(serdev, 0);
  12366. + serdev_device_close(serdev);
  12367. +
  12368. + // drop our controller reference
  12369. + ssam_controller_unlock(ctrl);
  12370. + ssam_controller_put(ctrl);
  12371. +
  12372. + device_set_wakeup_capable(&serdev->dev, false);
  12373. +}
  12374. +
  12375. +
  12376. +static const struct acpi_device_id ssam_serial_hub_match[] = {
  12377. + { "MSHW0084", 0 },
  12378. + { },
  12379. +};
  12380. +MODULE_DEVICE_TABLE(acpi, ssam_serial_hub_match);
  12381. +
  12382. +static struct serdev_device_driver ssam_serial_hub = {
  12383. + .probe = ssam_serial_hub_probe,
  12384. + .remove = ssam_serial_hub_remove,
  12385. + .driver = {
  12386. + .name = "surface_serial_hub",
  12387. + .acpi_match_table = ssam_serial_hub_match,
  12388. + .pm = &ssam_serial_hub_pm_ops,
  12389. + .shutdown = ssam_serial_hub_shutdown,
  12390. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  12391. + },
  12392. +};
  12393. +
  12394. +
  12395. +/* -- Module setup. --------------------------------------------------------- */
  12396. +
  12397. +static int __init ssam_core_init(void)
  12398. +{
  12399. + int status;
  12400. +
  12401. + status = ssam_bus_register();
  12402. + if (status)
  12403. + goto err_bus;
  12404. +
  12405. + status = ssh_ctrl_packet_cache_init();
  12406. + if (status)
  12407. + goto err_cpkg;
  12408. +
  12409. + status = ssam_event_item_cache_init();
  12410. + if (status)
  12411. + goto err_evitem;
  12412. +
  12413. + status = serdev_device_driver_register(&ssam_serial_hub);
  12414. + if (status)
  12415. + goto err_register;
  12416. +
  12417. + return 0;
  12418. +
  12419. +err_register:
  12420. + ssam_event_item_cache_destroy();
  12421. +err_evitem:
  12422. + ssh_ctrl_packet_cache_destroy();
  12423. +err_cpkg:
  12424. + ssam_bus_unregister();
  12425. +err_bus:
  12426. + return status;
  12427. +}
  12428. +module_init(ssam_core_init);
  12429. +
  12430. +static void __exit ssam_core_exit(void)
  12431. +{
  12432. + serdev_device_driver_unregister(&ssam_serial_hub);
  12433. + ssam_event_item_cache_destroy();
  12434. + ssh_ctrl_packet_cache_destroy();
  12435. + ssam_bus_unregister();
  12436. +}
  12437. +module_exit(ssam_core_exit);
  12438. +
  12439. +MODULE_AUTHOR("Maximilian Luz <luzmaximilian@gmail.com>");
  12440. +MODULE_DESCRIPTION("Subsystem and Surface Serial Hub driver for Surface System Aggregator Module");
  12441. +MODULE_LICENSE("GPL");
  12442. diff --git a/drivers/misc/surface_aggregator/ssh_msgb.h b/drivers/misc/surface_aggregator/ssh_msgb.h
  12443. new file mode 100644
  12444. index 000000000000..7c29e7d7028a
  12445. --- /dev/null
  12446. +++ b/drivers/misc/surface_aggregator/ssh_msgb.h
  12447. @@ -0,0 +1,201 @@
  12448. +/* SPDX-License-Identifier: GPL-2.0+ */
  12449. +/*
  12450. + * SSH message builder functions.
  12451. + *
  12452. + * Copyright (C) 2019-2020 Maximilian Luz <luzmaximilian@gmail.com>
  12453. + */
  12454. +
  12455. +#ifndef _SURFACE_AGGREGATOR_SSH_MSGB_H
  12456. +#define _SURFACE_AGGREGATOR_SSH_MSGB_H
  12457. +
  12458. +#include <asm/unaligned.h>
  12459. +#include <linux/types.h>
  12460. +
  12461. +#include <linux/surface_aggregator/controller.h>
  12462. +#include <linux/surface_aggregator/serial_hub.h>
  12463. +
  12464. +
  12465. +/**
  12466. + * struct msgbuf - Buffer struct to construct SSH messages.
  12467. + * @begin: Pointer to the beginning of the allocated buffer space.
  12468. + * @end: Pointer to the end (one past last element) of the allocated buffer
  12469. + * space.
  12470. + * @ptr: Pointer to the first free element in the buffer.
  12471. + */
  12472. +struct msgbuf {
  12473. + u8 *begin;
  12474. + u8 *end;
  12475. + u8 *ptr;
  12476. +};
  12477. +
  12478. +/**
  12479. + * msgb_init() - Initialize the given message buffer struct.
  12480. + * @msgb: The buffer struct to initialize
  12481. + * @ptr: Pointer to the underlying memory by which the buffer will be backed.
  12482. + * @cap: Size of the underlying memory.
  12483. + *
  12484. + * Initialize the given message buffer struct using the provided memory as
  12485. + * backing.
  12486. + */
  12487. +static inline void msgb_init(struct msgbuf *msgb, u8 *ptr, size_t cap)
  12488. +{
  12489. + msgb->begin = ptr;
  12490. + msgb->end = ptr + cap;
  12491. + msgb->ptr = ptr;
  12492. +}
  12493. +
  12494. +/**
  12495. + * msgb_bytes_used() - Return the current number of bytes used in the buffer.
  12496. + * @msgb: The message buffer.
  12497. + */
  12498. +static inline size_t msgb_bytes_used(const struct msgbuf *msgb)
  12499. +{
  12500. + return msgb->ptr - msgb->begin;
  12501. +}
  12502. +
  12503. +/**
  12504. + * msgb_push_u16() - Push a u16 value to the buffer.
  12505. + * @msgb: The message buffer.
  12506. + * @value: The value to push to the buffer.
  12507. + */
  12508. +static inline void msgb_push_u16(struct msgbuf *msgb, u16 value)
  12509. +{
  12510. + if (WARN_ON(msgb->ptr + sizeof(u16) > msgb->end))
  12511. + return;
  12512. +
  12513. + put_unaligned_le16(value, msgb->ptr);
  12514. + msgb->ptr += sizeof(u16);
  12515. +}
  12516. +
  12517. +/**
  12518. + * msgb_push_syn() - Push SSH SYN bytes to the buffer.
  12519. + * @msgb: The message buffer.
  12520. + */
  12521. +static inline void msgb_push_syn(struct msgbuf *msgb)
  12522. +{
  12523. + msgb_push_u16(msgb, SSH_MSG_SYN);
  12524. +}
  12525. +
  12526. +/**
  12527. + * msgb_push_buf() - Push raw data to the buffer.
  12528. + * @msgb: The message buffer.
  12529. + * @buf: The data to push to the buffer.
  12530. + * @len: The length of the data to push to the buffer.
  12531. + */
  12532. +static inline void msgb_push_buf(struct msgbuf *msgb, const u8 *buf, size_t len)
  12533. +{
  12534. + msgb->ptr = memcpy(msgb->ptr, buf, len) + len;
  12535. +}
  12536. +
  12537. +/**
  12538. + * msgb_push_crc() - Compute CRC and push it to the buffer.
  12539. + * @msgb: The message buffer.
  12540. + * @buf: The data for which the CRC should be computed.
  12541. + * @len: The length of the data for which the CRC should be computed.
  12542. + */
  12543. +static inline void msgb_push_crc(struct msgbuf *msgb, const u8 *buf, size_t len)
  12544. +{
  12545. + msgb_push_u16(msgb, ssh_crc(buf, len));
  12546. +}
  12547. +
  12548. +/**
  12549. + * msgb_push_frame() - Push a SSH message frame header to the buffer.
  12550. + * @msgb: The message buffer
  12551. + * @ty: The type of the frame.
  12552. + * @len: The length of the payload of the frame.
  12553. + * @seq: The sequence ID of the frame/packet.
  12554. + */
  12555. +static inline void msgb_push_frame(struct msgbuf *msgb, u8 ty, u16 len, u8 seq)
  12556. +{
  12557. + struct ssh_frame *frame = (struct ssh_frame *)msgb->ptr;
  12558. + const u8 *const begin = msgb->ptr;
  12559. +
  12560. + if (WARN_ON(msgb->ptr + sizeof(*frame) > msgb->end))
  12561. + return;
  12562. +
  12563. + frame->type = ty;
  12564. + put_unaligned_le16(len, &frame->len);
  12565. + frame->seq = seq;
  12566. +
  12567. + msgb->ptr += sizeof(*frame);
  12568. + msgb_push_crc(msgb, begin, msgb->ptr - begin);
  12569. +}
  12570. +
  12571. +/**
  12572. + * msgb_push_ack() - Push a SSH ACK frame to the buffer.
  12573. + * @msgb: The message buffer
  12574. + * @seq: The sequence ID of the frame/packet to be ACKed.
  12575. + */
  12576. +static inline void msgb_push_ack(struct msgbuf *msgb, u8 seq)
  12577. +{
  12578. + // SYN
  12579. + msgb_push_syn(msgb);
  12580. +
  12581. + // ACK-type frame + CRC
  12582. + msgb_push_frame(msgb, SSH_FRAME_TYPE_ACK, 0x00, seq);
  12583. +
  12584. + // payload CRC (ACK-type frames do not have a payload)
  12585. + msgb_push_crc(msgb, msgb->ptr, 0);
  12586. +}
  12587. +
  12588. +/**
  12589. + * msgb_push_nak() - Push a SSH NAK frame to the buffer.
  12590. + * @msgb: The message buffer
  12591. + */
  12592. +static inline void msgb_push_nak(struct msgbuf *msgb)
  12593. +{
  12594. + // SYN
  12595. + msgb_push_syn(msgb);
  12596. +
  12597. + // NAK-type frame + CRC
  12598. + msgb_push_frame(msgb, SSH_FRAME_TYPE_NAK, 0x00, 0x00);
  12599. +
  12600. + // payload CRC (ACK-type frames do not have a payload)
  12601. + msgb_push_crc(msgb, msgb->ptr, 0);
  12602. +}
  12603. +
  12604. +/**
  12605. + * msgb_push_cmd() - Push a SSH command frame with payload to the buffer.
  12606. + * @msgb: The message buffer.
  12607. + * @seq: The sequence ID (SEQ) of the frame/packet.
  12608. + * @rqid: The request ID (RQID) of the request contained in the frame.
  12609. + * @rqst: The request to wrap in the frame.
  12610. + */
  12611. +static inline void msgb_push_cmd(struct msgbuf *msgb, u8 seq, u16 rqid,
  12612. + const struct ssam_request *rqst)
  12613. +{
  12614. + struct ssh_command *cmd;
  12615. + const u8 *cmd_begin;
  12616. + const u8 type = SSH_FRAME_TYPE_DATA_SEQ;
  12617. +
  12618. + // SYN
  12619. + msgb_push_syn(msgb);
  12620. +
  12621. + // command frame + crc
  12622. + msgb_push_frame(msgb, type, sizeof(*cmd) + rqst->length, seq);
  12623. +
  12624. + // frame payload: command struct + payload
  12625. + if (WARN_ON(msgb->ptr + sizeof(*cmd) > msgb->end))
  12626. + return;
  12627. +
  12628. + cmd_begin = msgb->ptr;
  12629. + cmd = (struct ssh_command *)msgb->ptr;
  12630. +
  12631. + cmd->type = SSH_PLD_TYPE_CMD;
  12632. + cmd->tc = rqst->target_category;
  12633. + cmd->tid_out = rqst->target_id;
  12634. + cmd->tid_in = 0x00;
  12635. + cmd->iid = rqst->instance_id;
  12636. + put_unaligned_le16(rqid, &cmd->rqid);
  12637. + cmd->cid = rqst->command_id;
  12638. +
  12639. + msgb->ptr += sizeof(*cmd);
  12640. +
  12641. + // command payload
  12642. + msgb_push_buf(msgb, rqst->payload, rqst->length);
  12643. +
  12644. + // crc for command struct + payload
  12645. + msgb_push_crc(msgb, cmd_begin, msgb->ptr - cmd_begin);
  12646. +}
  12647. +
  12648. +#endif /* _SURFACE_AGGREGATOR_SSH_MSGB_H */
  12649. diff --git a/drivers/misc/surface_aggregator/ssh_packet_layer.c b/drivers/misc/surface_aggregator/ssh_packet_layer.c
  12650. new file mode 100644
  12651. index 000000000000..2d72e8c02842
  12652. --- /dev/null
  12653. +++ b/drivers/misc/surface_aggregator/ssh_packet_layer.c
  12654. @@ -0,0 +1,2009 @@
  12655. +// SPDX-License-Identifier: GPL-2.0+
  12656. +/*
  12657. + * SSH packet transport layer.
  12658. + *
  12659. + * Copyright (C) 2019-2020 Maximilian Luz <luzmaximilian@gmail.com>
  12660. + */
  12661. +
  12662. +#include <asm/unaligned.h>
  12663. +#include <linux/atomic.h>
  12664. +#include <linux/error-injection.h>
  12665. +#include <linux/jiffies.h>
  12666. +#include <linux/kfifo.h>
  12667. +#include <linux/kref.h>
  12668. +#include <linux/kthread.h>
  12669. +#include <linux/ktime.h>
  12670. +#include <linux/list.h>
  12671. +#include <linux/serdev.h>
  12672. +#include <linux/slab.h>
  12673. +#include <linux/spinlock.h>
  12674. +#include <linux/workqueue.h>
  12675. +
  12676. +#include <linux/surface_aggregator/serial_hub.h>
  12677. +
  12678. +#include "ssh_msgb.h"
  12679. +#include "ssh_packet_layer.h"
  12680. +#include "ssh_parser.h"
  12681. +
  12682. +#include "trace.h"
  12683. +
  12684. +
  12685. +/*
  12686. + * To simplify reasoning about the code below, we define a few concepts. The
  12687. + * system below is similar to a state-machine for packets, however, there are
  12688. + * too many states to explicitly write them down. To (somewhat) manage the
  12689. + * states and packets we rely on flags, reference counting, and some simple
  12690. + * concepts. State transitions are triggered by actions.
  12691. + *
  12692. + * >> Actions <<
  12693. + *
  12694. + * - submit
  12695. + * - transmission start (process next item in queue)
  12696. + * - transmission finished (guaranteed to never be parallel to transmission
  12697. + * start)
  12698. + * - ACK received
  12699. + * - NAK received (this is equivalent to issuing re-submit for all pending
  12700. + * packets)
  12701. + * - timeout (this is equivalent to re-issuing a submit or canceling)
  12702. + * - cancel (non-pending and pending)
  12703. + *
  12704. + * >> Data Structures, Packet Ownership, General Overview <<
  12705. + *
  12706. + * The code below employs two main data structures: The packet queue,
  12707. + * containing all packets scheduled for transmission, and the set of pending
  12708. + * packets, containing all packets awaiting an ACK.
  12709. + *
  12710. + * Shared ownership of a packet is controlled via reference counting. Inside
  12711. + * the transport system are a total of five packet owners:
  12712. + *
  12713. + * - the packet queue,
  12714. + * - the pending set,
  12715. + * - the transmitter thread,
  12716. + * - the receiver thread (via ACKing), and
  12717. + * - the timeout work item.
  12718. + *
  12719. + * Normal operation is as follows: The initial reference of the packet is
  12720. + * obtained by submitting the packet and queueing it. The receiver thread
  12721. + * takes packets from the queue. By doing this, it does not increment the
  12722. + * refcount but takes over the reference (removing it from the queue). If the
  12723. + * packet is sequenced (i.e. needs to be ACKed by the client), the transmitter
  12724. + * thread sets-up the timeout and adds the packet to the pending set before
  12725. + * starting to transmit it. As the timeout is handled by a reaper task, no
  12726. + * additional reference for it is needed. After the transmit is done, the
  12727. + * reference held by the transmitter thread is dropped. If the packet is
  12728. + * unsequenced (i.e. does not need an ACK), the packet is completed by the
  12729. + * transmitter thread before dropping that reference.
  12730. + *
  12731. + * On receival of an ACK, the receiver thread removes and obtains the
  12732. + * reference to the packet from the pending set. The receiver thread will then
  12733. + * complete the packet and drop its reference.
  12734. + *
  12735. + * On receival of a NAK, the receiver thread re-submits all currently pending
  12736. + * packets.
  12737. + *
  12738. + * Packet timeouts are detected by the timeout reaper. This is a task,
  12739. + * scheduled depending on the earliest packet timeout expiration date,
  12740. + * checking all currently pending packets if their timeout has expired. If the
  12741. + * timeout of a packet has expired, it is re-submitted and the number of tries
  12742. + * of this packet is incremented. If this number reaches its limit, the packet
  12743. + * will be completed with a failure.
  12744. + *
  12745. + * On transmission failure (such as repeated packet timeouts), the completion
  12746. + * callback is immediately run by on thread on which the error was detected.
  12747. + *
  12748. + * To ensure that a packet eventually leaves the system it is marked as
  12749. + * "locked" directly before it is going to be completed or when it is
  12750. + * canceled. Marking a packet as "locked" has the effect that passing and
  12751. + * creating new references of the packet is disallowed. This means that the
  12752. + * packet cannot be added to the queue, the pending set, and the timeout, or
  12753. + * be picked up by the transmitter thread or receiver thread. To remove a
  12754. + * packet from the system it has to be marked as locked and subsequently all
  12755. + * references from the data structures (queue, pending) have to be removed.
  12756. + * References held by threads will eventually be dropped automatically as
  12757. + * their execution progresses.
  12758. + *
  12759. + * Note that the packet completion callback is, in case of success and for a
  12760. + * sequenced packet, guaranteed to run on the receiver thread, thus providing
  12761. + * a way to reliably identify responses to the packet. The packet completion
  12762. + * callback is only run once and it does not indicate that the packet has
  12763. + * fully left the system (for this, one should rely on the release method,
  12764. + * triggered when the reference count of the packet reaches zero). In case of
  12765. + * re-submission (and with somewhat unlikely timing), it may be possible that
  12766. + * the packet is being re-transmitted while the completion callback runs.
  12767. + * Completion will occur both on success and internal error, as well as when
  12768. + * the packet is canceled.
  12769. + *
  12770. + * >> Flags <<
  12771. + *
  12772. + * Flags are used to indicate the state and progression of a packet. Some flags
  12773. + * have stricter guarantees than other:
  12774. + *
  12775. + * - locked
  12776. + * Indicates if the packet is locked. If the packet is locked, passing and/or
  12777. + * creating additional references to the packet is forbidden. The packet thus
  12778. + * may not be queued, dequeued, or removed or added to the pending set. Note
  12779. + * that the packet state flags may still change (e.g. it may be marked as
  12780. + * ACKed, transmitted, ...).
  12781. + *
  12782. + * - completed
  12783. + * Indicates if the packet completion callback has been executed or is about
  12784. + * to be executed. This flag is used to ensure that the packet completion
  12785. + * callback is only run once.
  12786. + *
  12787. + * - queued
  12788. + * Indicates if a packet is present in the submission queue or not. This flag
  12789. + * must only be modified with the queue lock held, and must be coherent to the
  12790. + * presence of the packet in the queue.
  12791. + *
  12792. + * - pending
  12793. + * Indicates if a packet is present in the set of pending packets or not.
  12794. + * This flag must only be modified with the pending lock held, and must be
  12795. + * coherent to the presence of the packet in the pending set.
  12796. + *
  12797. + * - transmitting
  12798. + * Indicates if the packet is currently transmitting. In case of
  12799. + * re-transmissions, it is only safe to wait on the "transmitted" completion
  12800. + * after this flag has been set. The completion will be set both in success
  12801. + * and error case.
  12802. + *
  12803. + * - transmitted
  12804. + * Indicates if the packet has been transmitted. This flag is not cleared by
  12805. + * the system, thus it indicates the first transmission only.
  12806. + *
  12807. + * - acked
  12808. + * Indicates if the packet has been acknowledged by the client. There are no
  12809. + * other guarantees given. For example, the packet may still be canceled
  12810. + * and/or the completion may be triggered an error even though this bit is
  12811. + * set. Rely on the status provided to the completion callback instead.
  12812. + *
  12813. + * - canceled
  12814. + * Indicates if the packet has been canceled from the outside. There are no
  12815. + * other guarantees given. Specifically, the packet may be completed by
  12816. + * another part of the system before the cancellation attempts to complete it.
  12817. + *
  12818. + * >> General Notes <<
  12819. + *
  12820. + * To avoid deadlocks, if both queue and pending locks are required, the
  12821. + * pending lock must be acquired before the queue lock.
  12822. + */
  12823. +
  12824. +/*
  12825. + * SSH_PTL_MAX_PACKET_TRIES - Maximum transmission attempts for packet.
  12826. + *
  12827. + * Maximum number of transmission attempts per sequenced packet in case of
  12828. + * time-outs. Must be smaller than 16. If the packet times out after this
  12829. + * amount of tries, the packet will be completed with %-ETIMEDOUT as status
  12830. + * code.
  12831. + */
  12832. +#define SSH_PTL_MAX_PACKET_TRIES 3
  12833. +
  12834. +/*
  12835. + * SSH_PTL_PACKET_TIMEOUT - Packet timeout.
  12836. + *
  12837. + * Timeout as ktime_t delta for ACKs. If we have not received an ACK in this
  12838. + * time-frame after starting transmission, the packet will be re-submitted.
  12839. + */
  12840. +#define SSH_PTL_PACKET_TIMEOUT ms_to_ktime(1000)
  12841. +
  12842. +/*
  12843. + * SSH_PTL_PACKET_TIMEOUT_RESOLUTION - Packet timeout granularity.
  12844. + *
  12845. + * Time-resolution for timeouts. Should be larger than one jiffy to avoid
  12846. + * direct re-scheduling of reaper work_struct.
  12847. + */
  12848. +#define SSH_PTL_PACKET_TIMEOUT_RESOLUTION ms_to_ktime(max(2000 / HZ, 50))
  12849. +
  12850. +/*
  12851. + * SSH_PTL_MAX_PENDING - Maximum number of pending packets.
  12852. + *
  12853. + * Maximum number of sequenced packets concurrently waiting for an ACK.
  12854. + * Packets marked as blocking will not be transmitted while this limit is
  12855. + * reached.
  12856. + */
  12857. +#define SSH_PTL_MAX_PENDING 1
  12858. +
  12859. +/*
  12860. + * SSH_PTL_RX_BUF_LEN - Evaluation-buffer size in bytes.
  12861. + */
  12862. +#define SSH_PTL_RX_BUF_LEN 4096
  12863. +
  12864. +/*
  12865. + * SSH_PTL_RX_FIFO_LEN - Fifo input-buffer size in bytes.
  12866. + */
  12867. +#define SSH_PTL_RX_FIFO_LEN 4096
  12868. +
  12869. +
  12870. +#ifdef CONFIG_SURFACE_AGGREGATOR_ERROR_INJECTION
  12871. +
  12872. +/**
  12873. + * ssh_ptl_should_drop_ack_packet() - Error injection hook to drop ACK packets.
  12874. + *
  12875. + * Useful to test detection and handling of automated re-transmits by the EC.
  12876. + * Specifically of packets that the EC consideres not-ACKed but the driver
  12877. + * already consideres ACKed (due to dropped ACK). In this case, the EC
  12878. + * re-transmits the packet-to-be-ACKed and the driver should detect it as
  12879. + * duplicate/already handled. Note that the driver should still send an ACK
  12880. + * for the re-transmitted packet.
  12881. + */
  12882. +static noinline bool ssh_ptl_should_drop_ack_packet(void)
  12883. +{
  12884. + return false;
  12885. +}
  12886. +ALLOW_ERROR_INJECTION(ssh_ptl_should_drop_ack_packet, TRUE);
  12887. +
  12888. +/**
  12889. + * ssh_ptl_should_drop_nak_packet() - Error injection hook to drop NAK packets.
  12890. + *
  12891. + * Useful to test/force automated (timeout-based) re-transmit by the EC.
  12892. + * Specifically, packets that have not reached the driver completely/with valid
  12893. + * checksums. Only useful in combination with receival of (injected) bad data.
  12894. + */
  12895. +static noinline bool ssh_ptl_should_drop_nak_packet(void)
  12896. +{
  12897. + return false;
  12898. +}
  12899. +ALLOW_ERROR_INJECTION(ssh_ptl_should_drop_nak_packet, TRUE);
  12900. +
  12901. +/**
  12902. + * ssh_ptl_should_drop_dsq_packet() - Error injection hook to drop sequenced
  12903. + * data packet.
  12904. + *
  12905. + * Useful to test re-transmit timeout of the driver. If the data packet has not
  12906. + * been ACKed after a certain time, the driver should re-transmit the packet up
  12907. + * to limited number of times defined in SSH_PTL_MAX_PACKET_TRIES.
  12908. + */
  12909. +static noinline bool ssh_ptl_should_drop_dsq_packet(void)
  12910. +{
  12911. + return false;
  12912. +}
  12913. +ALLOW_ERROR_INJECTION(ssh_ptl_should_drop_dsq_packet, TRUE);
  12914. +
  12915. +/**
  12916. + * ssh_ptl_should_fail_write() - Error injection hook to make
  12917. + * serdev_device_write() fail.
  12918. + *
  12919. + * Hook to simulate errors in serdev_device_write when transmitting packets.
  12920. + */
  12921. +static noinline int ssh_ptl_should_fail_write(void)
  12922. +{
  12923. + return 0;
  12924. +}
  12925. +ALLOW_ERROR_INJECTION(ssh_ptl_should_fail_write, ERRNO);
  12926. +
  12927. +/**
  12928. + * ssh_ptl_should_corrupt_tx_data() - Error injection hook to simualte invalid
  12929. + * data being sent to the EC.
  12930. + *
  12931. + * Hook to simulate corrupt/invalid data being sent from host (driver) to EC.
  12932. + * Causes the packet data to be actively corrupted by overwriting it with
  12933. + * pre-defined values, such that it becomes invalid, causing the EC to respond
  12934. + * with a NAK packet. Useful to test handling of NAK packets received by the
  12935. + * driver.
  12936. + */
  12937. +static noinline bool ssh_ptl_should_corrupt_tx_data(void)
  12938. +{
  12939. + return false;
  12940. +}
  12941. +ALLOW_ERROR_INJECTION(ssh_ptl_should_corrupt_tx_data, TRUE);
  12942. +
  12943. +/**
  12944. + * ssh_ptl_should_corrupt_rx_syn() - Error injection hook to simulate invalid
  12945. + * data being sent by the EC.
  12946. + *
  12947. + * Hook to simulate invalid SYN bytes, i.e. an invalid start of messages and
  12948. + * test handling thereof in the driver.
  12949. + */
  12950. +static noinline bool ssh_ptl_should_corrupt_rx_syn(void)
  12951. +{
  12952. + return false;
  12953. +}
  12954. +ALLOW_ERROR_INJECTION(ssh_ptl_should_corrupt_rx_syn, TRUE);
  12955. +
  12956. +/**
  12957. + * ssh_ptl_should_corrupt_rx_data() - Error injection hook to simulate invalid
  12958. + * data being sent by the EC.
  12959. + *
  12960. + * Hook to simulate invalid data/checksum of the message frame and test handling
  12961. + * thereof in the driver.
  12962. + */
  12963. +static noinline bool ssh_ptl_should_corrupt_rx_data(void)
  12964. +{
  12965. + return false;
  12966. +}
  12967. +ALLOW_ERROR_INJECTION(ssh_ptl_should_corrupt_rx_data, TRUE);
  12968. +
  12969. +
  12970. +static bool __ssh_ptl_should_drop_ack_packet(struct ssh_packet *packet)
  12971. +{
  12972. + if (likely(!ssh_ptl_should_drop_ack_packet()))
  12973. + return false;
  12974. +
  12975. + trace_ssam_ei_tx_drop_ack_packet(packet);
  12976. + ptl_info(packet->ptl, "packet error injection: dropping ACK packet %p\n",
  12977. + packet);
  12978. +
  12979. + return true;
  12980. +}
  12981. +
  12982. +static bool __ssh_ptl_should_drop_nak_packet(struct ssh_packet *packet)
  12983. +{
  12984. + if (likely(!ssh_ptl_should_drop_nak_packet()))
  12985. + return false;
  12986. +
  12987. + trace_ssam_ei_tx_drop_nak_packet(packet);
  12988. + ptl_info(packet->ptl, "packet error injection: dropping NAK packet %p\n",
  12989. + packet);
  12990. +
  12991. + return true;
  12992. +}
  12993. +
  12994. +static bool __ssh_ptl_should_drop_dsq_packet(struct ssh_packet *packet)
  12995. +{
  12996. + if (likely(!ssh_ptl_should_drop_dsq_packet()))
  12997. + return false;
  12998. +
  12999. + trace_ssam_ei_tx_drop_dsq_packet(packet);
  13000. + ptl_info(packet->ptl,
  13001. + "packet error injection: dropping sequenced data packet %p\n",
  13002. + packet);
  13003. +
  13004. + return true;
  13005. +}
  13006. +
  13007. +static bool ssh_ptl_should_drop_packet(struct ssh_packet *packet)
  13008. +{
  13009. + // ignore packets that don't carry any data (i.e. flush)
  13010. + if (!packet->data.ptr || !packet->data.len)
  13011. + return false;
  13012. +
  13013. + switch (packet->data.ptr[SSH_MSGOFFSET_FRAME(type)]) {
  13014. + case SSH_FRAME_TYPE_ACK:
  13015. + return __ssh_ptl_should_drop_ack_packet(packet);
  13016. +
  13017. + case SSH_FRAME_TYPE_NAK:
  13018. + return __ssh_ptl_should_drop_nak_packet(packet);
  13019. +
  13020. + case SSH_FRAME_TYPE_DATA_SEQ:
  13021. + return __ssh_ptl_should_drop_dsq_packet(packet);
  13022. +
  13023. + default:
  13024. + return false;
  13025. + }
  13026. +}
  13027. +
  13028. +static int ssh_ptl_write_buf(struct ssh_ptl *ptl, struct ssh_packet *packet,
  13029. + const unsigned char *buf, size_t count)
  13030. +{
  13031. + int status;
  13032. +
  13033. + status = ssh_ptl_should_fail_write();
  13034. + if (unlikely(status)) {
  13035. + trace_ssam_ei_tx_fail_write(packet, status);
  13036. + ptl_info(packet->ptl,
  13037. + "packet error injection: simulating transmit error %d,"
  13038. + " packet %p\n", status, packet);
  13039. +
  13040. + return status;
  13041. + }
  13042. +
  13043. + return serdev_device_write_buf(ptl->serdev, buf, count);
  13044. +}
  13045. +
  13046. +static void ssh_ptl_tx_inject_invalid_data(struct ssh_packet *packet)
  13047. +{
  13048. + // ignore packets that don't carry any data (i.e. flush)
  13049. + if (!packet->data.ptr || !packet->data.len)
  13050. + return;
  13051. +
  13052. + // only allow sequenced data packets to be modified
  13053. + if (packet->data.ptr[SSH_MSGOFFSET_FRAME(type)] != SSH_FRAME_TYPE_DATA_SEQ)
  13054. + return;
  13055. +
  13056. + if (likely(!ssh_ptl_should_corrupt_tx_data()))
  13057. + return;
  13058. +
  13059. + trace_ssam_ei_tx_corrupt_data(packet);
  13060. + ptl_info(packet->ptl,
  13061. + "packet error injection: simulating invalid transmit data on packet %p\n",
  13062. + packet);
  13063. +
  13064. + /*
  13065. + * NB: The value 0xb3 has been chosen more or less randomly so that it
  13066. + * doesn't have any (major) overlap with the SYN bytes (aa 55) and is
  13067. + * non-trivial (i.e. non-zero, non-0xff).
  13068. + */
  13069. + memset(packet->data.ptr, 0xb3, packet->data.len);
  13070. +}
  13071. +
  13072. +static void ssh_ptl_rx_inject_invalid_syn(struct ssh_ptl *ptl,
  13073. + struct ssam_span *data)
  13074. +{
  13075. + struct ssam_span frame;
  13076. +
  13077. + // check if there actually is something to corrupt
  13078. + if (!sshp_find_syn(data, &frame))
  13079. + return;
  13080. +
  13081. + if (likely(!ssh_ptl_should_corrupt_rx_syn()))
  13082. + return;
  13083. +
  13084. + trace_ssam_ei_rx_corrupt_syn("data_length", data->len);
  13085. +
  13086. + data->ptr[1] = 0xb3; // set second byte of SYN to "random" value
  13087. +}
  13088. +
  13089. +static void ssh_ptl_rx_inject_invalid_data(struct ssh_ptl *ptl,
  13090. + struct ssam_span *frame)
  13091. +{
  13092. + size_t payload_len, message_len;
  13093. + struct ssh_frame *sshf;
  13094. +
  13095. + // ignore incomplete messages, will get handled once it's complete
  13096. + if (frame->len < SSH_MESSAGE_LENGTH(0))
  13097. + return;
  13098. +
  13099. + // ignore incomplete messages, part 2
  13100. + payload_len = get_unaligned_le16(&frame->ptr[SSH_MSGOFFSET_FRAME(len)]);
  13101. + message_len = SSH_MESSAGE_LENGTH(payload_len);
  13102. + if (frame->len < message_len)
  13103. + return;
  13104. +
  13105. + if (likely(!ssh_ptl_should_corrupt_rx_data()))
  13106. + return;
  13107. +
  13108. + sshf = (struct ssh_frame *)&frame->ptr[SSH_MSGOFFSET_FRAME(type)];
  13109. + trace_ssam_ei_rx_corrupt_data(sshf);
  13110. +
  13111. + /*
  13112. + * Flip bits in first byte of payload checksum. This is basically
  13113. + * equivalent to a payload/frame data error without us having to worry
  13114. + * about (the, arguably pretty small, probability of) accidental
  13115. + * checksum collisions.
  13116. + */
  13117. + frame->ptr[frame->len - 2] = ~frame->ptr[frame->len - 2];
  13118. +}
  13119. +
  13120. +#else /* CONFIG_SURFACE_AGGREGATOR_ERROR_INJECTION */
  13121. +
  13122. +static inline bool ssh_ptl_should_drop_packet(struct ssh_packet *packet)
  13123. +{
  13124. + return false;
  13125. +}
  13126. +
  13127. +static inline int ssh_ptl_write_buf(struct ssh_ptl *ptl,
  13128. + struct ssh_packet *packet,
  13129. + const unsigned char *buf,
  13130. + size_t count)
  13131. +{
  13132. + return serdev_device_write_buf(ptl->serdev, buf, count);
  13133. +}
  13134. +
  13135. +static inline void ssh_ptl_tx_inject_invalid_data(struct ssh_packet *packet)
  13136. +{
  13137. +}
  13138. +
  13139. +static inline void ssh_ptl_rx_inject_invalid_syn(struct ssh_ptl *ptl,
  13140. + struct ssam_span *data)
  13141. +{
  13142. +}
  13143. +
  13144. +static inline void ssh_ptl_rx_inject_invalid_data(struct ssh_ptl *ptl,
  13145. + struct ssam_span *frame)
  13146. +{
  13147. +}
  13148. +
  13149. +#endif /* CONFIG_SURFACE_AGGREGATOR_ERROR_INJECTION */
  13150. +
  13151. +
  13152. +static void __ssh_ptl_packet_release(struct kref *kref)
  13153. +{
  13154. + struct ssh_packet *p = container_of(kref, struct ssh_packet, refcnt);
  13155. +
  13156. + trace_ssam_packet_release(p);
  13157. +
  13158. + ptl_dbg_cond(p->ptl, "ptl: releasing packet %p\n", p);
  13159. + p->ops->release(p);
  13160. +}
  13161. +
  13162. +/**
  13163. + * ssh_packet_get() - Increment reference count of packet.
  13164. + * @packet: The packet to increment the reference count of.
  13165. + *
  13166. + * Increments the reference count of the given packet. See ssh_packet_put()
  13167. + * for the counter-part of this function.
  13168. + *
  13169. + * Return: Returns the packet provided as input.
  13170. + */
  13171. +struct ssh_packet *ssh_packet_get(struct ssh_packet *packet)
  13172. +{
  13173. + if (packet)
  13174. + kref_get(&packet->refcnt);
  13175. + return packet;
  13176. +}
  13177. +EXPORT_SYMBOL_GPL(ssh_packet_get);
  13178. +
  13179. +/**
  13180. + * ssh_packet_put() - Decrement reference count of packet.
  13181. + * @packet: The packet to decrement the reference count of.
  13182. + *
  13183. + * If the reference count reaches zero, the ``release`` callback specified in
  13184. + * the packet's &struct ssh_packet_ops, i.e. ``packet->ops->release``, will be
  13185. + * called.
  13186. + *
  13187. + * See ssh_packet_get() for the counter-part of this function.
  13188. + */
  13189. +void ssh_packet_put(struct ssh_packet *packet)
  13190. +{
  13191. + if (packet)
  13192. + kref_put(&packet->refcnt, __ssh_ptl_packet_release);
  13193. +}
  13194. +EXPORT_SYMBOL_GPL(ssh_packet_put);
  13195. +
  13196. +static u8 ssh_packet_get_seq(struct ssh_packet *packet)
  13197. +{
  13198. + return packet->data.ptr[SSH_MSGOFFSET_FRAME(seq)];
  13199. +}
  13200. +
  13201. +
  13202. +/**
  13203. + * ssh_packet_init() - Initialize SSH packet.
  13204. + * @packet: The packet to initialize.
  13205. + * @type: Type-flags of the packet.
  13206. + * @priority: Priority of the packet. See SSH_PACKET_PRIORITY() for details.
  13207. + * @ops: Packet operations.
  13208. + *
  13209. + * Initializes the given SSH packet. Sets the transmission buffer pointer to
  13210. + * %NULL and the transmission buffer length to zero. For data-type packets,
  13211. + * this buffer has to be set separately via ssh_packet_set_data() before
  13212. + * submission, and must contain a valid SSH message, i.e. frame with optional
  13213. + * payload of any type.
  13214. + */
  13215. +void ssh_packet_init(struct ssh_packet *packet, unsigned long type,
  13216. + u8 priority, const struct ssh_packet_ops *ops)
  13217. +{
  13218. + kref_init(&packet->refcnt);
  13219. +
  13220. + packet->ptl = NULL;
  13221. + INIT_LIST_HEAD(&packet->queue_node);
  13222. + INIT_LIST_HEAD(&packet->pending_node);
  13223. +
  13224. + packet->state = type & SSH_PACKET_FLAGS_TY_MASK;
  13225. + packet->priority = priority;
  13226. + packet->timestamp = KTIME_MAX;
  13227. +
  13228. + packet->data.ptr = NULL;
  13229. + packet->data.len = 0;
  13230. +
  13231. + packet->ops = ops;
  13232. +}
  13233. +
  13234. +
  13235. +static struct kmem_cache *ssh_ctrl_packet_cache;
  13236. +
  13237. +/**
  13238. + * ssh_ctrl_packet_cache_init() - Initialize the control packet cache.
  13239. + */
  13240. +int ssh_ctrl_packet_cache_init(void)
  13241. +{
  13242. + const unsigned int size = sizeof(struct ssh_packet) + SSH_MSG_LEN_CTRL;
  13243. + const unsigned int align = __alignof__(struct ssh_packet);
  13244. + struct kmem_cache *cache;
  13245. +
  13246. + cache = kmem_cache_create("ssam_ctrl_packet", size, align, 0, NULL);
  13247. + if (!cache)
  13248. + return -ENOMEM;
  13249. +
  13250. + ssh_ctrl_packet_cache = cache;
  13251. + return 0;
  13252. +}
  13253. +
  13254. +/**
  13255. + * ssh_ctrl_packet_cache_destroy() - Deinitialize the control packet cache.
  13256. + */
  13257. +void ssh_ctrl_packet_cache_destroy(void)
  13258. +{
  13259. + kmem_cache_destroy(ssh_ctrl_packet_cache);
  13260. + ssh_ctrl_packet_cache = NULL;
  13261. +}
  13262. +
  13263. +/**
  13264. + * ssh_ctrl_packet_alloc() - Allocate packet from control packet cache.
  13265. + * @packet: Where the pointer to the newly allocated packet should be stored.
  13266. + * @buffer: The buffer corresponding to this packet.
  13267. + * @flags: Flags used for allocation.
  13268. + *
  13269. + * Allocates a packet and corresponding transport buffer from the control
  13270. + * packet cache. Sets the packet's buffer reference to the allocated buffer.
  13271. + * The packet must be freed via ssh_ctrl_packet_free(), which will also free
  13272. + * the corresponding buffer. The corresponding buffer must not be freed
  13273. + * separately. Intended to be used with %ssh_ptl_ctrl_packet_ops as packet
  13274. + * operations.
  13275. + *
  13276. + * Return: Returns zero on success, %-ENOMEM if the allocation failed.
  13277. + */
  13278. +static int ssh_ctrl_packet_alloc(struct ssh_packet **packet,
  13279. + struct ssam_span *buffer, gfp_t flags)
  13280. +{
  13281. + *packet = kmem_cache_alloc(ssh_ctrl_packet_cache, flags);
  13282. + if (!*packet)
  13283. + return -ENOMEM;
  13284. +
  13285. + buffer->ptr = (u8 *)(*packet + 1);
  13286. + buffer->len = SSH_MSG_LEN_CTRL;
  13287. +
  13288. + trace_ssam_ctrl_packet_alloc(*packet, buffer->len);
  13289. + return 0;
  13290. +}
  13291. +
  13292. +/**
  13293. + * ssh_ctrl_packet_free() - Free packet allocated from control packet cache.
  13294. + * @p: The packet to free.
  13295. + */
  13296. +static void ssh_ctrl_packet_free(struct ssh_packet *p)
  13297. +{
  13298. + trace_ssam_ctrl_packet_free(p);
  13299. + kmem_cache_free(ssh_ctrl_packet_cache, p);
  13300. +}
  13301. +
  13302. +static const struct ssh_packet_ops ssh_ptl_ctrl_packet_ops = {
  13303. + .complete = NULL,
  13304. + .release = ssh_ctrl_packet_free,
  13305. +};
  13306. +
  13307. +
  13308. +static void ssh_ptl_timeout_reaper_mod(struct ssh_ptl *ptl, ktime_t now,
  13309. + ktime_t expires)
  13310. +{
  13311. + unsigned long delta = msecs_to_jiffies(ktime_ms_delta(expires, now));
  13312. + ktime_t aexp = ktime_add(expires, SSH_PTL_PACKET_TIMEOUT_RESOLUTION);
  13313. + ktime_t old_exp, old_act;
  13314. +
  13315. + // re-adjust / schedule reaper if it is above resolution delta
  13316. + old_act = READ_ONCE(ptl->rtx_timeout.expires);
  13317. + if (ktime_after(aexp, old_act))
  13318. + return;
  13319. +
  13320. + do {
  13321. + old_exp = old_act;
  13322. + old_act = cmpxchg64(&ptl->rtx_timeout.expires, old_exp, expires);
  13323. + } while (old_exp != old_act && ktime_before(aexp, old_act));
  13324. +
  13325. + // if we updated the reaper expiration, modify work timeout
  13326. + if (old_exp == old_act && old_act != expires)
  13327. + mod_delayed_work(system_wq, &ptl->rtx_timeout.reaper, delta);
  13328. +}
  13329. +
  13330. +static void ssh_ptl_timeout_start(struct ssh_packet *packet)
  13331. +{
  13332. + struct ssh_ptl *ptl = packet->ptl;
  13333. + ktime_t timestamp = ktime_get_coarse_boottime();
  13334. + ktime_t timeout = ptl->rtx_timeout.timeout;
  13335. +
  13336. + if (test_bit(SSH_PACKET_SF_LOCKED_BIT, &packet->state))
  13337. + return;
  13338. +
  13339. + WRITE_ONCE(packet->timestamp, timestamp);
  13340. + /*
  13341. + * Ensure timestamp is set before starting the reaper. Paired with
  13342. + * implicit barrier following check on ssh_packet_get_expiration() in
  13343. + * ssh_ptl_timeout_reap().
  13344. + */
  13345. + smp_mb__after_atomic();
  13346. +
  13347. + ssh_ptl_timeout_reaper_mod(packet->ptl, timestamp, timestamp + timeout);
  13348. +}
  13349. +
  13350. +
  13351. +static void ssh_packet_next_try(struct ssh_packet *p)
  13352. +{
  13353. + u8 priority = READ_ONCE(p->priority);
  13354. + u8 base = ssh_packet_priority_get_base(priority);
  13355. + u8 try = ssh_packet_priority_get_try(priority);
  13356. +
  13357. + WRITE_ONCE(p->priority, __SSH_PACKET_PRIORITY(base, try + 1));
  13358. +}
  13359. +
  13360. +/* must be called with queue lock held */
  13361. +static struct list_head *__ssh_ptl_queue_find_entrypoint(struct ssh_packet *p)
  13362. +{
  13363. + struct list_head *head;
  13364. + u8 priority = READ_ONCE(p->priority);
  13365. +
  13366. + /*
  13367. + * We generally assume that there are less control (ACK/NAK) packets and
  13368. + * re-submitted data packets as there are normal data packets (at least
  13369. + * in situations in which many packets are queued; if there aren't many
  13370. + * packets queued the decision on how to iterate should be basically
  13371. + * irrellevant; the number of control/data packets is more or less
  13372. + * limited via the maximum number of pending packets). Thus, when
  13373. + * inserting a control or re-submitted data packet, (determined by their
  13374. + * priority), we search from front to back. Normal data packets are,
  13375. + * usually queued directly at the tail of the queue, so for those search
  13376. + * from back to front.
  13377. + */
  13378. +
  13379. + if (priority > SSH_PACKET_PRIORITY(DATA, 0)) {
  13380. + list_for_each(head, &p->ptl->queue.head) {
  13381. + p = list_entry(head, struct ssh_packet, queue_node);
  13382. +
  13383. + if (READ_ONCE(p->priority) < priority)
  13384. + break;
  13385. + }
  13386. + } else {
  13387. + list_for_each_prev(head, &p->ptl->queue.head) {
  13388. + p = list_entry(head, struct ssh_packet, queue_node);
  13389. +
  13390. + if (READ_ONCE(p->priority) >= priority) {
  13391. + head = head->next;
  13392. + break;
  13393. + }
  13394. + }
  13395. + }
  13396. +
  13397. +
  13398. + return head;
  13399. +}
  13400. +
  13401. +/* must be called with queue lock held */
  13402. +static int __ssh_ptl_queue_push(struct ssh_packet *packet)
  13403. +{
  13404. + struct ssh_ptl *ptl = packet->ptl;
  13405. + struct list_head *head;
  13406. +
  13407. +
  13408. + if (test_bit(SSH_PTL_SF_SHUTDOWN_BIT, &ptl->state))
  13409. + return -ESHUTDOWN;
  13410. +
  13411. + // avoid further transitions when cancelling/completing
  13412. + if (test_bit(SSH_PACKET_SF_LOCKED_BIT, &packet->state))
  13413. + return -EINVAL;
  13414. +
  13415. + // if this packet has already been queued, do not add it
  13416. + if (test_and_set_bit(SSH_PACKET_SF_QUEUED_BIT, &packet->state))
  13417. + return -EALREADY;
  13418. +
  13419. + head = __ssh_ptl_queue_find_entrypoint(packet);
  13420. +
  13421. + list_add_tail(&ssh_packet_get(packet)->queue_node, head);
  13422. + return 0;
  13423. +}
  13424. +
  13425. +static int ssh_ptl_queue_push(struct ssh_packet *packet)
  13426. +{
  13427. + int status;
  13428. +
  13429. + spin_lock(&packet->ptl->queue.lock);
  13430. + status = __ssh_ptl_queue_push(packet);
  13431. + spin_unlock(&packet->ptl->queue.lock);
  13432. +
  13433. + return status;
  13434. +}
  13435. +
  13436. +static void ssh_ptl_queue_remove(struct ssh_packet *packet)
  13437. +{
  13438. + struct ssh_ptl *ptl = packet->ptl;
  13439. +
  13440. + spin_lock(&ptl->queue.lock);
  13441. +
  13442. + if (!test_and_clear_bit(SSH_PACKET_SF_QUEUED_BIT, &packet->state)) {
  13443. + spin_unlock(&ptl->queue.lock);
  13444. + return;
  13445. + }
  13446. +
  13447. + list_del(&packet->queue_node);
  13448. +
  13449. + spin_unlock(&ptl->queue.lock);
  13450. + ssh_packet_put(packet);
  13451. +}
  13452. +
  13453. +
  13454. +static void ssh_ptl_pending_push(struct ssh_packet *packet)
  13455. +{
  13456. + struct ssh_ptl *ptl = packet->ptl;
  13457. +
  13458. + spin_lock(&ptl->pending.lock);
  13459. +
  13460. + // if we are cancelling/completing this packet, do not add it
  13461. + if (test_bit(SSH_PACKET_SF_LOCKED_BIT, &packet->state)) {
  13462. + spin_unlock(&ptl->pending.lock);
  13463. + return;
  13464. + }
  13465. +
  13466. + // in case it is already pending (e.g. re-submission), do not add it
  13467. + if (test_and_set_bit(SSH_PACKET_SF_PENDING_BIT, &packet->state)) {
  13468. + spin_unlock(&ptl->pending.lock);
  13469. + return;
  13470. + }
  13471. +
  13472. + atomic_inc(&ptl->pending.count);
  13473. + list_add_tail(&ssh_packet_get(packet)->pending_node, &ptl->pending.head);
  13474. +
  13475. + spin_unlock(&ptl->pending.lock);
  13476. +}
  13477. +
  13478. +static void ssh_ptl_pending_remove(struct ssh_packet *packet)
  13479. +{
  13480. + struct ssh_ptl *ptl = packet->ptl;
  13481. +
  13482. + spin_lock(&ptl->pending.lock);
  13483. +
  13484. + if (!test_and_clear_bit(SSH_PACKET_SF_PENDING_BIT, &packet->state)) {
  13485. + spin_unlock(&ptl->pending.lock);
  13486. + return;
  13487. + }
  13488. +
  13489. + list_del(&packet->pending_node);
  13490. + atomic_dec(&ptl->pending.count);
  13491. +
  13492. + spin_unlock(&ptl->pending.lock);
  13493. +
  13494. + ssh_packet_put(packet);
  13495. +}
  13496. +
  13497. +
  13498. +/* warning: does not check/set "completed" bit */
  13499. +static void __ssh_ptl_complete(struct ssh_packet *p, int status)
  13500. +{
  13501. + struct ssh_ptl *ptl = READ_ONCE(p->ptl);
  13502. +
  13503. + trace_ssam_packet_complete(p, status);
  13504. + ptl_dbg_cond(ptl, "ptl: completing packet %p (status: %d)\n", p, status);
  13505. +
  13506. + if (p->ops->complete)
  13507. + p->ops->complete(p, status);
  13508. +}
  13509. +
  13510. +static void ssh_ptl_remove_and_complete(struct ssh_packet *p, int status)
  13511. +{
  13512. + /*
  13513. + * A call to this function should in general be preceded by
  13514. + * set_bit(SSH_PACKET_SF_LOCKED_BIT, &p->flags) to avoid re-adding the
  13515. + * packet to the structures it's going to be removed from.
  13516. + *
  13517. + * The set_bit call does not need explicit memory barriers as the
  13518. + * implicit barrier of the test_and_set_bit() call below ensure that the
  13519. + * flag is visible before we actually attempt to remove the packet.
  13520. + */
  13521. +
  13522. + if (test_and_set_bit(SSH_PACKET_SF_COMPLETED_BIT, &p->state))
  13523. + return;
  13524. +
  13525. + ssh_ptl_queue_remove(p);
  13526. + ssh_ptl_pending_remove(p);
  13527. +
  13528. + __ssh_ptl_complete(p, status);
  13529. +}
  13530. +
  13531. +
  13532. +static bool ssh_ptl_tx_can_process(struct ssh_packet *packet)
  13533. +{
  13534. + struct ssh_ptl *ptl = packet->ptl;
  13535. +
  13536. + if (test_bit(SSH_PACKET_TY_FLUSH_BIT, &packet->state))
  13537. + return !atomic_read(&ptl->pending.count);
  13538. +
  13539. + // we can alwas process non-blocking packets
  13540. + if (!test_bit(SSH_PACKET_TY_BLOCKING_BIT, &packet->state))
  13541. + return true;
  13542. +
  13543. + // if we are already waiting for this packet, send it again
  13544. + if (test_bit(SSH_PACKET_SF_PENDING_BIT, &packet->state))
  13545. + return true;
  13546. +
  13547. + // otherwise: check if we have the capacity to send
  13548. + return atomic_read(&ptl->pending.count) < SSH_PTL_MAX_PENDING;
  13549. +}
  13550. +
  13551. +static struct ssh_packet *ssh_ptl_tx_pop(struct ssh_ptl *ptl)
  13552. +{
  13553. + struct ssh_packet *packet = ERR_PTR(-ENOENT);
  13554. + struct ssh_packet *p, *n;
  13555. +
  13556. + spin_lock(&ptl->queue.lock);
  13557. + list_for_each_entry_safe(p, n, &ptl->queue.head, queue_node) {
  13558. + /*
  13559. + * If we are cancelling or completing this packet, ignore it.
  13560. + * It's going to be removed from this queue shortly.
  13561. + */
  13562. + if (test_bit(SSH_PACKET_SF_LOCKED_BIT, &p->state))
  13563. + continue;
  13564. +
  13565. + /*
  13566. + * Packets should be ordered non-blocking/to-be-resent first.
  13567. + * If we cannot process this packet, assume that we can't
  13568. + * process any following packet either and abort.
  13569. + */
  13570. + if (!ssh_ptl_tx_can_process(p)) {
  13571. + packet = ERR_PTR(-EBUSY);
  13572. + break;
  13573. + }
  13574. +
  13575. + /*
  13576. + * We are allowed to change the state now. Remove it from the
  13577. + * queue and mark it as being transmitted. Note that we cannot
  13578. + * add it to the set of pending packets yet, as queue locks must
  13579. + * always be acquired before packet locks (otherwise we might
  13580. + * run into a deadlock).
  13581. + */
  13582. +
  13583. + list_del(&p->queue_node);
  13584. +
  13585. + set_bit(SSH_PACKET_SF_TRANSMITTING_BIT, &p->state);
  13586. + // ensure that state never gets zero
  13587. + smp_mb__before_atomic();
  13588. + clear_bit(SSH_PACKET_SF_QUEUED_BIT, &p->state);
  13589. +
  13590. + packet = p;
  13591. + break;
  13592. + }
  13593. + spin_unlock(&ptl->queue.lock);
  13594. +
  13595. + return packet;
  13596. +}
  13597. +
  13598. +static struct ssh_packet *ssh_ptl_tx_next(struct ssh_ptl *ptl)
  13599. +{
  13600. + struct ssh_packet *p;
  13601. +
  13602. + p = ssh_ptl_tx_pop(ptl);
  13603. + if (IS_ERR(p))
  13604. + return p;
  13605. +
  13606. + if (test_bit(SSH_PACKET_TY_SEQUENCED_BIT, &p->state)) {
  13607. + ptl_dbg(ptl, "ptl: transmitting sequenced packet %p\n", p);
  13608. + ssh_ptl_pending_push(p);
  13609. + ssh_ptl_timeout_start(p);
  13610. + } else {
  13611. + ptl_dbg(ptl, "ptl: transmitting non-sequenced packet %p\n", p);
  13612. + }
  13613. +
  13614. + /*
  13615. + * Update number of tries. This directly influences the priority in case
  13616. + * the packet is re-submitted (e.g. via timeout/NAK). Note that this is
  13617. + * the only place where we update the priority in-flight. As this runs
  13618. + * only on the tx-thread, this read-modify-write procedure is safe.
  13619. + */
  13620. + ssh_packet_next_try(p);
  13621. +
  13622. + return p;
  13623. +}
  13624. +
  13625. +static void ssh_ptl_tx_compl_success(struct ssh_packet *packet)
  13626. +{
  13627. + struct ssh_ptl *ptl = packet->ptl;
  13628. +
  13629. + ptl_dbg(ptl, "ptl: successfully transmitted packet %p\n", packet);
  13630. +
  13631. + // transition state to "transmitted"
  13632. + set_bit(SSH_PACKET_SF_TRANSMITTED_BIT, &packet->state);
  13633. + // ensure that state never gets zero
  13634. + smp_mb__before_atomic();
  13635. + clear_bit(SSH_PACKET_SF_TRANSMITTING_BIT, &packet->state);
  13636. +
  13637. + // if the packet is unsequenced, we're done: lock and complete
  13638. + if (!test_bit(SSH_PACKET_TY_SEQUENCED_BIT, &packet->state)) {
  13639. + set_bit(SSH_PACKET_SF_LOCKED_BIT, &packet->state);
  13640. + ssh_ptl_remove_and_complete(packet, 0);
  13641. + }
  13642. +
  13643. + /*
  13644. + * Notify that a packet transmission has finished. In general we're only
  13645. + * waiting for one packet (if any), so wake_up_all should be fine.
  13646. + */
  13647. + wake_up_all(&ptl->tx.packet_wq);
  13648. +}
  13649. +
  13650. +static void ssh_ptl_tx_compl_error(struct ssh_packet *packet, int status)
  13651. +{
  13652. + // transmission failure: lock the packet and try to complete it
  13653. + set_bit(SSH_PACKET_SF_LOCKED_BIT, &packet->state);
  13654. + // ensure that state never gets zero
  13655. + smp_mb__before_atomic();
  13656. + clear_bit(SSH_PACKET_SF_TRANSMITTING_BIT, &packet->state);
  13657. +
  13658. + ptl_err(packet->ptl, "ptl: transmission error: %d\n", status);
  13659. + ptl_dbg(packet->ptl, "ptl: failed to transmit packet: %p\n", packet);
  13660. +
  13661. + ssh_ptl_remove_and_complete(packet, status);
  13662. +
  13663. + /*
  13664. + * Notify that a packet transmission has finished. In general we're only
  13665. + * waiting for one packet (if any), so wake_up_all should be fine.
  13666. + */
  13667. + wake_up_all(&packet->ptl->tx.packet_wq);
  13668. +}
  13669. +
  13670. +static void ssh_ptl_tx_threadfn_wait(struct ssh_ptl *ptl)
  13671. +{
  13672. + wait_event_interruptible(ptl->tx.thread_wq,
  13673. + READ_ONCE(ptl->tx.thread_signal) || kthread_should_stop());
  13674. + WRITE_ONCE(ptl->tx.thread_signal, false);
  13675. +}
  13676. +
  13677. +static int ssh_ptl_tx_threadfn(void *data)
  13678. +{
  13679. + struct ssh_ptl *ptl = data;
  13680. +
  13681. + while (!kthread_should_stop()) {
  13682. + unsigned char *buf;
  13683. + bool drop = false;
  13684. + size_t len = 0;
  13685. + int status = 0;
  13686. +
  13687. + // if we don't have a packet, get the next and add it to pending
  13688. + if (IS_ERR_OR_NULL(ptl->tx.packet)) {
  13689. + ptl->tx.packet = ssh_ptl_tx_next(ptl);
  13690. + ptl->tx.offset = 0;
  13691. +
  13692. + // if no packet can be processed, we are done
  13693. + if (IS_ERR(ptl->tx.packet)) {
  13694. + ssh_ptl_tx_threadfn_wait(ptl);
  13695. + continue;
  13696. + }
  13697. + }
  13698. +
  13699. + // error injection: drop packet to simulate transmission problem
  13700. + if (ptl->tx.offset == 0)
  13701. + drop = ssh_ptl_should_drop_packet(ptl->tx.packet);
  13702. +
  13703. + // error injection: simulate invalid packet data
  13704. + if (ptl->tx.offset == 0 && !drop)
  13705. + ssh_ptl_tx_inject_invalid_data(ptl->tx.packet);
  13706. +
  13707. + // note: flush-packets don't have any data
  13708. + if (likely(ptl->tx.packet->data.ptr && !drop)) {
  13709. + buf = ptl->tx.packet->data.ptr + ptl->tx.offset;
  13710. + len = ptl->tx.packet->data.len - ptl->tx.offset;
  13711. +
  13712. + ptl_dbg(ptl, "tx: sending data (length: %zu)\n", len);
  13713. + print_hex_dump_debug("tx: ", DUMP_PREFIX_OFFSET, 16, 1,
  13714. + buf, len, false);
  13715. +
  13716. + status = ssh_ptl_write_buf(ptl, ptl->tx.packet, buf, len);
  13717. + }
  13718. +
  13719. + if (status < 0) {
  13720. + // complete packet with error
  13721. + ssh_ptl_tx_compl_error(ptl->tx.packet, status);
  13722. + ssh_packet_put(ptl->tx.packet);
  13723. + ptl->tx.packet = NULL;
  13724. +
  13725. + } else if (status == len) {
  13726. + // complete packet and/or mark as transmitted
  13727. + ssh_ptl_tx_compl_success(ptl->tx.packet);
  13728. + ssh_packet_put(ptl->tx.packet);
  13729. + ptl->tx.packet = NULL;
  13730. +
  13731. + } else { // need more buffer space
  13732. + ptl->tx.offset += status;
  13733. + ssh_ptl_tx_threadfn_wait(ptl);
  13734. + }
  13735. + }
  13736. +
  13737. + // cancel active packet before we actually stop
  13738. + if (!IS_ERR_OR_NULL(ptl->tx.packet)) {
  13739. + ssh_ptl_tx_compl_error(ptl->tx.packet, -ESHUTDOWN);
  13740. + ssh_packet_put(ptl->tx.packet);
  13741. + ptl->tx.packet = NULL;
  13742. + }
  13743. +
  13744. + return 0;
  13745. +}
  13746. +
  13747. +/**
  13748. + * ssh_ptl_tx_wakeup() - Wake up packet transmitter thread.
  13749. + * @ptl: The packet transport layer.
  13750. + *
  13751. + * Wakes up the packet transmitter thread. If the packet transport layer has
  13752. + * been shut down, calls to this function will be ignored.
  13753. + */
  13754. +void ssh_ptl_tx_wakeup(struct ssh_ptl *ptl)
  13755. +{
  13756. + if (test_bit(SSH_PTL_SF_SHUTDOWN_BIT, &ptl->state))
  13757. + return;
  13758. +
  13759. + WRITE_ONCE(ptl->tx.thread_signal, true);
  13760. + /*
  13761. + * Ensure that the signal is set before we wake the transmitter
  13762. + * thread to prevent lost updates: If the signal is not set,
  13763. + * when the thread checks it in ssh_ptl_tx_threadfn_wait(), it
  13764. + * may go back to sleep.
  13765. + */
  13766. + smp_mb__after_atomic();
  13767. + wake_up(&ptl->tx.thread_wq);
  13768. +}
  13769. +
  13770. +/**
  13771. + * ssh_ptl_tx_start() - Start packet transmitter thread.
  13772. + * @ptl: The packet transport layer.
  13773. + *
  13774. + * Return: Returns zero on success, a negative error code on failure.
  13775. + */
  13776. +int ssh_ptl_tx_start(struct ssh_ptl *ptl)
  13777. +{
  13778. + ptl->tx.thread = kthread_run(ssh_ptl_tx_threadfn, ptl,
  13779. + "ssam_serial_hub-tx");
  13780. + if (IS_ERR(ptl->tx.thread))
  13781. + return PTR_ERR(ptl->tx.thread);
  13782. +
  13783. + return 0;
  13784. +}
  13785. +
  13786. +/**
  13787. + * ssh_ptl_tx_stop() - Stop packet transmitter thread.
  13788. + * @ptl: The packet transport layer.
  13789. + *
  13790. + * Return: Returns zero on success, a negative error code on failure.
  13791. + */
  13792. +int ssh_ptl_tx_stop(struct ssh_ptl *ptl)
  13793. +{
  13794. + int status = 0;
  13795. +
  13796. + if (ptl->tx.thread) {
  13797. + status = kthread_stop(ptl->tx.thread);
  13798. + ptl->tx.thread = NULL;
  13799. + }
  13800. +
  13801. + return status;
  13802. +}
  13803. +
  13804. +
  13805. +static struct ssh_packet *ssh_ptl_ack_pop(struct ssh_ptl *ptl, u8 seq_id)
  13806. +{
  13807. + struct ssh_packet *packet = ERR_PTR(-ENOENT);
  13808. + struct ssh_packet *p, *n;
  13809. +
  13810. + spin_lock(&ptl->pending.lock);
  13811. + list_for_each_entry_safe(p, n, &ptl->pending.head, pending_node) {
  13812. + /*
  13813. + * We generally expect packets to be in order, so first packet
  13814. + * to be added to pending is first to be sent, is first to be
  13815. + * ACKed.
  13816. + */
  13817. + if (unlikely(ssh_packet_get_seq(p) != seq_id))
  13818. + continue;
  13819. +
  13820. + /*
  13821. + * In case we receive an ACK while handling a transmission
  13822. + * error completion. The packet will be removed shortly.
  13823. + */
  13824. + if (unlikely(test_bit(SSH_PACKET_SF_LOCKED_BIT, &p->state))) {
  13825. + packet = ERR_PTR(-EPERM);
  13826. + break;
  13827. + }
  13828. +
  13829. + /*
  13830. + * Mark the packet as ACKed and remove it from pending by
  13831. + * removing its node and decrementing the pending counter.
  13832. + */
  13833. + set_bit(SSH_PACKET_SF_ACKED_BIT, &p->state);
  13834. + // ensure that state never gets zero
  13835. + smp_mb__before_atomic();
  13836. + clear_bit(SSH_PACKET_SF_PENDING_BIT, &p->state);
  13837. +
  13838. + atomic_dec(&ptl->pending.count);
  13839. + list_del(&p->pending_node);
  13840. + packet = p;
  13841. +
  13842. + break;
  13843. + }
  13844. + spin_unlock(&ptl->pending.lock);
  13845. +
  13846. + return packet;
  13847. +}
  13848. +
  13849. +static void ssh_ptl_wait_until_transmitted(struct ssh_packet *packet)
  13850. +{
  13851. + wait_event(packet->ptl->tx.packet_wq,
  13852. + test_bit(SSH_PACKET_SF_TRANSMITTED_BIT, &packet->state)
  13853. + || test_bit(SSH_PACKET_SF_LOCKED_BIT, &packet->state));
  13854. +}
  13855. +
  13856. +static void ssh_ptl_acknowledge(struct ssh_ptl *ptl, u8 seq)
  13857. +{
  13858. + struct ssh_packet *p;
  13859. + int status = 0;
  13860. +
  13861. + p = ssh_ptl_ack_pop(ptl, seq);
  13862. + if (IS_ERR(p)) {
  13863. + if (PTR_ERR(p) == -ENOENT) {
  13864. + /*
  13865. + * The packet has not been found in the set of pending
  13866. + * packets.
  13867. + */
  13868. + ptl_warn(ptl, "ptl: received ACK for non-pending packet\n");
  13869. + } else {
  13870. + /*
  13871. + * The packet is pending, but we are not allowed to take
  13872. + * it because it has been locked.
  13873. + */
  13874. + WARN_ON(PTR_ERR(p) != -EPERM);
  13875. + }
  13876. + return;
  13877. + }
  13878. +
  13879. + ptl_dbg(ptl, "ptl: received ACK for packet %p\n", p);
  13880. +
  13881. + /*
  13882. + * It is possible that the packet has been transmitted, but the state
  13883. + * has not been updated from "transmitting" to "transmitted" yet.
  13884. + * In that case, we need to wait for this transition to occur in order
  13885. + * to determine between success or failure.
  13886. + */
  13887. + if (test_bit(SSH_PACKET_SF_TRANSMITTING_BIT, &p->state))
  13888. + ssh_ptl_wait_until_transmitted(p);
  13889. +
  13890. + /*
  13891. + * The packet will already be locked in case of a transmission error or
  13892. + * cancellation. Let the transmitter or cancellation issuer complete the
  13893. + * packet.
  13894. + */
  13895. + if (unlikely(test_and_set_bit(SSH_PACKET_SF_LOCKED_BIT, &p->state))) {
  13896. + ssh_packet_put(p);
  13897. + return;
  13898. + }
  13899. +
  13900. + if (unlikely(!test_bit(SSH_PACKET_SF_TRANSMITTED_BIT, &p->state))) {
  13901. + ptl_err(ptl, "ptl: received ACK before packet had been fully transmitted\n");
  13902. + status = -EREMOTEIO;
  13903. + }
  13904. +
  13905. + ssh_ptl_remove_and_complete(p, status);
  13906. + ssh_packet_put(p);
  13907. +
  13908. + if (atomic_read(&ptl->pending.count) < SSH_PTL_MAX_PENDING)
  13909. + ssh_ptl_tx_wakeup(ptl);
  13910. +}
  13911. +
  13912. +
  13913. +/**
  13914. + * ssh_ptl_submit() - Submit a packet to the transport layer.
  13915. + * @ptl: The packet transport layer to submit the packet to.
  13916. + * @p: The packet to submit.
  13917. + *
  13918. + * Submits a new packet to the transport layer, queuing it to be sent. This
  13919. + * function should not be used for re-submission.
  13920. + *
  13921. + * Return: Returns zero on success, %-EINVAL if a packet field is invalid or
  13922. + * the packet has been canceled prior to submission, %-EALREADY if the packet
  13923. + * has already been submitted, or %-ESHUTDOWN if the packet transport layer
  13924. + * has been shut down.
  13925. + */
  13926. +int ssh_ptl_submit(struct ssh_ptl *ptl, struct ssh_packet *p)
  13927. +{
  13928. + struct ssh_ptl *ptl_old;
  13929. + int status;
  13930. +
  13931. + trace_ssam_packet_submit(p);
  13932. +
  13933. + // validate packet fields
  13934. + if (test_bit(SSH_PACKET_TY_FLUSH_BIT, &p->state)) {
  13935. + if (p->data.ptr || test_bit(SSH_PACKET_TY_SEQUENCED_BIT, &p->state))
  13936. + return -EINVAL;
  13937. + } else if (!p->data.ptr) {
  13938. + return -EINVAL;
  13939. + }
  13940. +
  13941. + /*
  13942. + * The ptl reference only gets set on or before the first submission.
  13943. + * After the first submission, it has to be read-only.
  13944. + */
  13945. + ptl_old = READ_ONCE(p->ptl);
  13946. + if (ptl_old == NULL)
  13947. + WRITE_ONCE(p->ptl, ptl);
  13948. + else if (WARN_ON(ptl_old != ptl))
  13949. + return -EALREADY; // submitted on different PTL
  13950. +
  13951. + status = ssh_ptl_queue_push(p);
  13952. + if (status)
  13953. + return status;
  13954. +
  13955. + if (!test_bit(SSH_PACKET_TY_BLOCKING_BIT, &p->state)
  13956. + || (atomic_read(&ptl->pending.count) < SSH_PTL_MAX_PENDING))
  13957. + ssh_ptl_tx_wakeup(ptl);
  13958. +
  13959. + return 0;
  13960. +}
  13961. +
  13962. +/* must be called with pending lock held */
  13963. +static int __ssh_ptl_resubmit(struct ssh_packet *packet)
  13964. +{
  13965. + int status;
  13966. +
  13967. + trace_ssam_packet_resubmit(packet);
  13968. +
  13969. + spin_lock(&packet->ptl->queue.lock);
  13970. +
  13971. + status = __ssh_ptl_queue_push(packet);
  13972. + if (status) {
  13973. + /*
  13974. + * An error here indicates that the packet has either already
  13975. + * been queued, been locked, or the transport layer is being
  13976. + * shut down. In all cases: Ignore the error.
  13977. + */
  13978. + spin_unlock(&packet->ptl->queue.lock);
  13979. + return status;
  13980. + }
  13981. +
  13982. + /*
  13983. + * Reset the timestamp. This must be called and executed before the
  13984. + * pending lock is released. The lock release should be a sufficient
  13985. + * barrier for this operation, thus there is no need to manually add
  13986. + * one here.
  13987. + */
  13988. + WRITE_ONCE(packet->timestamp, KTIME_MAX);
  13989. +
  13990. + spin_unlock(&packet->ptl->queue.lock);
  13991. + return 0;
  13992. +}
  13993. +
  13994. +static void ssh_ptl_resubmit_pending(struct ssh_ptl *ptl)
  13995. +{
  13996. + struct ssh_packet *p;
  13997. + bool resub = false;
  13998. + u8 try;
  13999. +
  14000. + /*
  14001. + * Note: We deliberately do not remove/attempt to cancel and complete
  14002. + * packets that are out of tires in this function. The packet will be
  14003. + * eventually canceled and completed by the timeout. Removing the packet
  14004. + * here could lead to overly eager cancellation if the packet has not
  14005. + * been re-transmitted yet but the tries-counter already updated (i.e
  14006. + * ssh_ptl_tx_next() removed the packet from the queue and updated the
  14007. + * counter, but re-transmission for the last try has not actually
  14008. + * started yet).
  14009. + */
  14010. +
  14011. + spin_lock(&ptl->pending.lock);
  14012. +
  14013. + // re-queue all pending packets
  14014. + list_for_each_entry(p, &ptl->pending.head, pending_node) {
  14015. + // avoid further transitions if locked
  14016. + if (test_bit(SSH_PACKET_SF_LOCKED_BIT, &p->state))
  14017. + continue;
  14018. +
  14019. + // do not re-schedule if packet is out of tries
  14020. + try = ssh_packet_priority_get_try(READ_ONCE(p->priority));
  14021. + if (try >= SSH_PTL_MAX_PACKET_TRIES)
  14022. + continue;
  14023. +
  14024. + /*
  14025. + * Submission fails if the packet has been locked, is already
  14026. + * queued, or the layer is being shut down. No need to
  14027. + * re-schedule tx-thread in those cases.
  14028. + */
  14029. + if (!__ssh_ptl_resubmit(p))
  14030. + resub = true;
  14031. + }
  14032. +
  14033. + spin_unlock(&ptl->pending.lock);
  14034. +
  14035. + if (resub)
  14036. + ssh_ptl_tx_wakeup(ptl);
  14037. +}
  14038. +
  14039. +/**
  14040. + * ssh_ptl_cancel() - Cancel a packet.
  14041. + * @p: The packet to cancel.
  14042. + *
  14043. + * Cancels a packet. There are no guarantees on when completion and release
  14044. + * callbacks will be called. This may occur during execution of this function
  14045. + * or may occur at any point later.
  14046. + *
  14047. + * Note that it is not guaranteed that the packet will actually be cancelled
  14048. + * if the packet is concurrently completed by another process. The only
  14049. + * guarantee of this function is that the packet will be completed (with
  14050. + * success, failure, or cancellation) and released from the transport layer in
  14051. + * a reasonable time-frame.
  14052. + *
  14053. + * May be called before the packet has been submitted, in which case any later
  14054. + * packet submission fails.
  14055. + */
  14056. +void ssh_ptl_cancel(struct ssh_packet *p)
  14057. +{
  14058. + if (test_and_set_bit(SSH_PACKET_SF_CANCELED_BIT, &p->state))
  14059. + return;
  14060. +
  14061. + trace_ssam_packet_cancel(p);
  14062. +
  14063. + /*
  14064. + * Lock packet and commit with memory barrier. If this packet has
  14065. + * already been locked, it's going to be removed and completed by
  14066. + * another party, which should have precedence.
  14067. + */
  14068. + if (test_and_set_bit(SSH_PACKET_SF_LOCKED_BIT, &p->state))
  14069. + return;
  14070. +
  14071. + /*
  14072. + * By marking the packet as locked and employing the implicit memory
  14073. + * barrier of test_and_set_bit, we have guaranteed that, at this point,
  14074. + * the packet cannot be added to the queue any more.
  14075. + *
  14076. + * In case the packet has never been submitted, packet->ptl is NULL. If
  14077. + * the packet is currently being submitted, packet->ptl may be NULL or
  14078. + * non-NULL. Due marking the packet as locked above and committing with
  14079. + * the memory barrier, we have guaranteed that, if packet->ptl is NULL,
  14080. + * the packet will never be added to the queue. If packet->ptl is
  14081. + * non-NULL, we don't have any guarantees.
  14082. + */
  14083. +
  14084. + if (READ_ONCE(p->ptl)) {
  14085. + ssh_ptl_remove_and_complete(p, -ECANCELED);
  14086. +
  14087. + if (atomic_read(&p->ptl->pending.count) < SSH_PTL_MAX_PENDING)
  14088. + ssh_ptl_tx_wakeup(p->ptl);
  14089. +
  14090. + } else if (!test_and_set_bit(SSH_PACKET_SF_COMPLETED_BIT, &p->state)) {
  14091. + __ssh_ptl_complete(p, -ECANCELED);
  14092. + }
  14093. +}
  14094. +
  14095. +
  14096. +static ktime_t ssh_packet_get_expiration(struct ssh_packet *p, ktime_t timeout)
  14097. +{
  14098. + ktime_t timestamp = READ_ONCE(p->timestamp);
  14099. +
  14100. + if (timestamp != KTIME_MAX)
  14101. + return ktime_add(timestamp, timeout);
  14102. + else
  14103. + return KTIME_MAX;
  14104. +}
  14105. +
  14106. +static void ssh_ptl_timeout_reap(struct work_struct *work)
  14107. +{
  14108. + struct ssh_ptl *ptl = to_ssh_ptl(work, rtx_timeout.reaper.work);
  14109. + struct ssh_packet *p, *n;
  14110. + LIST_HEAD(claimed);
  14111. + ktime_t now = ktime_get_coarse_boottime();
  14112. + ktime_t timeout = ptl->rtx_timeout.timeout;
  14113. + ktime_t next = KTIME_MAX;
  14114. + bool resub = false;
  14115. +
  14116. + trace_ssam_ptl_timeout_reap("pending", atomic_read(&ptl->pending.count));
  14117. +
  14118. + /*
  14119. + * Mark reaper as "not pending". This is done before checking any
  14120. + * packets to avoid lost-update type problems.
  14121. + */
  14122. + WRITE_ONCE(ptl->rtx_timeout.expires, KTIME_MAX);
  14123. + /*
  14124. + * Ensure that the reaper is marked as deactivated before we continue
  14125. + * checking packets to prevent lost-update problems when a packet is
  14126. + * added to the pending set and ssh_ptl_timeout_reaper_mod is called
  14127. + * during execution of the part below.
  14128. + */
  14129. + smp_mb__after_atomic();
  14130. +
  14131. + spin_lock(&ptl->pending.lock);
  14132. +
  14133. + list_for_each_entry_safe(p, n, &ptl->pending.head, pending_node) {
  14134. + ktime_t expires = ssh_packet_get_expiration(p, timeout);
  14135. + u8 try;
  14136. +
  14137. + /*
  14138. + * Check if the timeout hasn't expired yet. Find out next
  14139. + * expiration date to be handled after this run.
  14140. + */
  14141. + if (ktime_after(expires, now)) {
  14142. + next = ktime_before(expires, next) ? expires : next;
  14143. + continue;
  14144. + }
  14145. +
  14146. + // check if we still have some tries left
  14147. + try = ssh_packet_priority_get_try(READ_ONCE(p->priority));
  14148. + if (likely(try < SSH_PTL_MAX_PACKET_TRIES)) {
  14149. + trace_ssam_packet_timeout(p);
  14150. +
  14151. + /*
  14152. + * Submission fails if the packet has been locked, is
  14153. + * already queued, or the layer is being shut down.
  14154. + * No need to re-schedule tx-thread in those cases.
  14155. + */
  14156. + if (!__ssh_ptl_resubmit(p))
  14157. + resub = true;
  14158. +
  14159. + continue;
  14160. + }
  14161. +
  14162. + // no more tries left: cancel the packet
  14163. +
  14164. + // if someone else has locked the packet already, don't use it
  14165. + if (test_and_set_bit(SSH_PACKET_SF_LOCKED_BIT, &p->state))
  14166. + continue;
  14167. +
  14168. + trace_ssam_packet_timeout(p);
  14169. +
  14170. + /*
  14171. + * We have now marked the packet as locked. Thus it cannot be
  14172. + * added to the pending list again after we've removed it here.
  14173. + * We can therefore re-use the pending_node of this packet
  14174. + * temporarily.
  14175. + */
  14176. +
  14177. + clear_bit(SSH_PACKET_SF_PENDING_BIT, &p->state);
  14178. +
  14179. + atomic_dec(&ptl->pending.count);
  14180. + list_del(&p->pending_node);
  14181. +
  14182. + list_add_tail(&p->pending_node, &claimed);
  14183. + }
  14184. +
  14185. + spin_unlock(&ptl->pending.lock);
  14186. +
  14187. + // cancel and complete the packet
  14188. + list_for_each_entry_safe(p, n, &claimed, pending_node) {
  14189. + if (!test_and_set_bit(SSH_PACKET_SF_COMPLETED_BIT, &p->state)) {
  14190. + ssh_ptl_queue_remove(p);
  14191. + __ssh_ptl_complete(p, -ETIMEDOUT);
  14192. + }
  14193. +
  14194. + // drop the reference we've obtained by removing it from pending
  14195. + list_del(&p->pending_node);
  14196. + ssh_packet_put(p);
  14197. + }
  14198. +
  14199. + // ensure that reaper doesn't run again immediately
  14200. + next = max(next, ktime_add(now, SSH_PTL_PACKET_TIMEOUT_RESOLUTION));
  14201. + if (next != KTIME_MAX)
  14202. + ssh_ptl_timeout_reaper_mod(ptl, now, next);
  14203. +
  14204. + if (resub)
  14205. + ssh_ptl_tx_wakeup(ptl);
  14206. +}
  14207. +
  14208. +
  14209. +static bool ssh_ptl_rx_retransmit_check(struct ssh_ptl *ptl, u8 seq)
  14210. +{
  14211. + int i;
  14212. +
  14213. + // check if SEQ has been seen recently (i.e. packet was re-transmitted)
  14214. + for (i = 0; i < ARRAY_SIZE(ptl->rx.blocked.seqs); i++) {
  14215. + if (likely(ptl->rx.blocked.seqs[i] != seq))
  14216. + continue;
  14217. +
  14218. + ptl_dbg(ptl, "ptl: ignoring repeated data packet\n");
  14219. + return true;
  14220. + }
  14221. +
  14222. + // update list of blocked seuence IDs
  14223. + ptl->rx.blocked.seqs[ptl->rx.blocked.offset] = seq;
  14224. + ptl->rx.blocked.offset = (ptl->rx.blocked.offset + 1)
  14225. + % ARRAY_SIZE(ptl->rx.blocked.seqs);
  14226. +
  14227. + return false;
  14228. +}
  14229. +
  14230. +static void ssh_ptl_rx_dataframe(struct ssh_ptl *ptl,
  14231. + const struct ssh_frame *frame,
  14232. + const struct ssam_span *payload)
  14233. +{
  14234. + if (ssh_ptl_rx_retransmit_check(ptl, frame->seq))
  14235. + return;
  14236. +
  14237. + ptl->ops.data_received(ptl, payload);
  14238. +}
  14239. +
  14240. +static void ssh_ptl_send_ack(struct ssh_ptl *ptl, u8 seq)
  14241. +{
  14242. + struct ssh_packet *packet;
  14243. + struct ssam_span buf;
  14244. + struct msgbuf msgb;
  14245. + int status;
  14246. +
  14247. + status = ssh_ctrl_packet_alloc(&packet, &buf, GFP_KERNEL);
  14248. + if (status) {
  14249. + ptl_err(ptl, "ptl: failed to allocate ACK packet\n");
  14250. + return;
  14251. + }
  14252. +
  14253. + ssh_packet_init(packet, 0, SSH_PACKET_PRIORITY(ACK, 0),
  14254. + &ssh_ptl_ctrl_packet_ops);
  14255. +
  14256. + msgb_init(&msgb, buf.ptr, buf.len);
  14257. + msgb_push_ack(&msgb, seq);
  14258. + ssh_packet_set_data(packet, msgb.begin, msgb_bytes_used(&msgb));
  14259. +
  14260. + ssh_ptl_submit(ptl, packet);
  14261. + ssh_packet_put(packet);
  14262. +}
  14263. +
  14264. +static void ssh_ptl_send_nak(struct ssh_ptl *ptl)
  14265. +{
  14266. + struct ssh_packet *packet;
  14267. + struct ssam_span buf;
  14268. + struct msgbuf msgb;
  14269. + int status;
  14270. +
  14271. + status = ssh_ctrl_packet_alloc(&packet, &buf, GFP_KERNEL);
  14272. + if (status) {
  14273. + ptl_err(ptl, "ptl: failed to allocate NAK packet\n");
  14274. + return;
  14275. + }
  14276. +
  14277. + ssh_packet_init(packet, 0, SSH_PACKET_PRIORITY(NAK, 0),
  14278. + &ssh_ptl_ctrl_packet_ops);
  14279. +
  14280. + msgb_init(&msgb, buf.ptr, buf.len);
  14281. + msgb_push_nak(&msgb);
  14282. + ssh_packet_set_data(packet, msgb.begin, msgb_bytes_used(&msgb));
  14283. +
  14284. + ssh_ptl_submit(ptl, packet);
  14285. + ssh_packet_put(packet);
  14286. +}
  14287. +
  14288. +static size_t ssh_ptl_rx_eval(struct ssh_ptl *ptl, struct ssam_span *source)
  14289. +{
  14290. + struct ssh_frame *frame;
  14291. + struct ssam_span payload;
  14292. + struct ssam_span aligned;
  14293. + bool syn_found;
  14294. + int status;
  14295. +
  14296. + // error injection: modify data to simulate corrupt SYN bytes
  14297. + ssh_ptl_rx_inject_invalid_syn(ptl, source);
  14298. +
  14299. + // find SYN
  14300. + syn_found = sshp_find_syn(source, &aligned);
  14301. +
  14302. + if (unlikely(aligned.ptr - source->ptr) > 0) {
  14303. + ptl_warn(ptl, "rx: parser: invalid start of frame, skipping\n");
  14304. +
  14305. + /*
  14306. + * Notes:
  14307. + * - This might send multiple NAKs in case the communication
  14308. + * starts with an invalid SYN and is broken down into multiple
  14309. + * pieces. This should generally be handled fine, we just
  14310. + * might receive duplicate data in this case, which is
  14311. + * detected when handling data frames.
  14312. + * - This path will also be executed on invalid CRCs: When an
  14313. + * invalid CRC is encountered, the code below will skip data
  14314. + * until direclty after the SYN. This causes the search for
  14315. + * the next SYN, which is generally not placed directly after
  14316. + * the last one.
  14317. + *
  14318. + * Open question: Should we send this in case of invalid
  14319. + * payload CRCs if the frame-type is nonsequential (current
  14320. + * implementation) or should we drop that frame without
  14321. + * telling the EC?
  14322. + */
  14323. + ssh_ptl_send_nak(ptl);
  14324. + }
  14325. +
  14326. + if (unlikely(!syn_found))
  14327. + return aligned.ptr - source->ptr;
  14328. +
  14329. + // error injection: modify data to simulate corruption
  14330. + ssh_ptl_rx_inject_invalid_data(ptl, &aligned);
  14331. +
  14332. + // parse and validate frame
  14333. + status = sshp_parse_frame(&ptl->serdev->dev, &aligned, &frame, &payload,
  14334. + SSH_PTL_RX_BUF_LEN);
  14335. + if (status) // invalid frame: skip to next syn
  14336. + return aligned.ptr - source->ptr + sizeof(u16);
  14337. + if (!frame) // not enough data
  14338. + return aligned.ptr - source->ptr;
  14339. +
  14340. + trace_ssam_rx_frame_received(frame);
  14341. +
  14342. + switch (frame->type) {
  14343. + case SSH_FRAME_TYPE_ACK:
  14344. + ssh_ptl_acknowledge(ptl, frame->seq);
  14345. + break;
  14346. +
  14347. + case SSH_FRAME_TYPE_NAK:
  14348. + ssh_ptl_resubmit_pending(ptl);
  14349. + break;
  14350. +
  14351. + case SSH_FRAME_TYPE_DATA_SEQ:
  14352. + ssh_ptl_send_ack(ptl, frame->seq);
  14353. + fallthrough;
  14354. +
  14355. + case SSH_FRAME_TYPE_DATA_NSQ:
  14356. + ssh_ptl_rx_dataframe(ptl, frame, &payload);
  14357. + break;
  14358. +
  14359. + default:
  14360. + ptl_warn(ptl, "ptl: received frame with unknown type 0x%02x\n",
  14361. + frame->type);
  14362. + break;
  14363. + }
  14364. +
  14365. + return aligned.ptr - source->ptr + SSH_MESSAGE_LENGTH(frame->len);
  14366. +}
  14367. +
  14368. +static int ssh_ptl_rx_threadfn(void *data)
  14369. +{
  14370. + struct ssh_ptl *ptl = data;
  14371. +
  14372. + while (true) {
  14373. + struct ssam_span span;
  14374. + size_t offs = 0;
  14375. + size_t n;
  14376. +
  14377. + wait_event_interruptible(ptl->rx.wq,
  14378. + !kfifo_is_empty(&ptl->rx.fifo)
  14379. + || kthread_should_stop());
  14380. + if (kthread_should_stop())
  14381. + break;
  14382. +
  14383. + // copy from fifo to evaluation buffer
  14384. + n = sshp_buf_read_from_fifo(&ptl->rx.buf, &ptl->rx.fifo);
  14385. +
  14386. + ptl_dbg(ptl, "rx: received data (size: %zu)\n", n);
  14387. + print_hex_dump_debug("rx: ", DUMP_PREFIX_OFFSET, 16, 1,
  14388. + ptl->rx.buf.ptr + ptl->rx.buf.len - n,
  14389. + n, false);
  14390. +
  14391. + // parse until we need more bytes or buffer is empty
  14392. + while (offs < ptl->rx.buf.len) {
  14393. + sshp_buf_span_from(&ptl->rx.buf, offs, &span);
  14394. + n = ssh_ptl_rx_eval(ptl, &span);
  14395. + if (n == 0)
  14396. + break; // need more bytes
  14397. +
  14398. + offs += n;
  14399. + }
  14400. +
  14401. + // throw away the evaluated parts
  14402. + sshp_buf_drop(&ptl->rx.buf, offs);
  14403. + }
  14404. +
  14405. + return 0;
  14406. +}
  14407. +
  14408. +static void ssh_ptl_rx_wakeup(struct ssh_ptl *ptl)
  14409. +{
  14410. + wake_up(&ptl->rx.wq);
  14411. +}
  14412. +
  14413. +/**
  14414. + * ssh_ptl_rx_start() - Start packet transport layer receiver thread.
  14415. + * @ptl: The packet transport layer.
  14416. + *
  14417. + * Return: Returns zero on success, a negative error code on failure.
  14418. + */
  14419. +int ssh_ptl_rx_start(struct ssh_ptl *ptl)
  14420. +{
  14421. + if (ptl->rx.thread)
  14422. + return 0;
  14423. +
  14424. + ptl->rx.thread = kthread_run(ssh_ptl_rx_threadfn, ptl,
  14425. + "ssam_serial_hub-rx");
  14426. + if (IS_ERR(ptl->rx.thread))
  14427. + return PTR_ERR(ptl->rx.thread);
  14428. +
  14429. + return 0;
  14430. +}
  14431. +
  14432. +/**
  14433. + * ssh_ptl_rx_stop() - Stop packet transport layer receiver thread.
  14434. + * @ptl: The packet transport layer.
  14435. + *
  14436. + * Return: Returns zero on success, a negative error code on failure.
  14437. + */
  14438. +int ssh_ptl_rx_stop(struct ssh_ptl *ptl)
  14439. +{
  14440. + int status = 0;
  14441. +
  14442. + if (ptl->rx.thread) {
  14443. + status = kthread_stop(ptl->rx.thread);
  14444. + ptl->rx.thread = NULL;
  14445. + }
  14446. +
  14447. + return status;
  14448. +}
  14449. +
  14450. +/**
  14451. + * ssh_ptl_rx_rcvbuf() - Push data from lower-layer transport to the packet
  14452. + * layer.
  14453. + * @ptl: The packet transport layer.
  14454. + * @buf: Pointer to the data to push to the layer.
  14455. + * @n: Size of the data to push to the layer, in bytes.
  14456. + *
  14457. + * Pushes data from a lower-layer transport to the receiver fifo buffer of the
  14458. + * packet layer and notifies the reveiver thread. Calls to this function are
  14459. + * ignored once the packet layer has been shut down.
  14460. + *
  14461. + * Return: Returns the number of bytes transferred (positive or zero) on
  14462. + * success. Returns %-ESHUTDOWN if the packet layer has been shut down.
  14463. + */
  14464. +int ssh_ptl_rx_rcvbuf(struct ssh_ptl *ptl, const u8 *buf, size_t n)
  14465. +{
  14466. + int used;
  14467. +
  14468. + if (test_bit(SSH_PTL_SF_SHUTDOWN_BIT, &ptl->state))
  14469. + return -ESHUTDOWN;
  14470. +
  14471. + used = kfifo_in(&ptl->rx.fifo, buf, n);
  14472. + if (used)
  14473. + ssh_ptl_rx_wakeup(ptl);
  14474. +
  14475. + return used;
  14476. +}
  14477. +
  14478. +
  14479. +/**
  14480. + * ssh_ptl_shutdown() - Shut down the packet transport layer.
  14481. + * @ptl: The packet transport layer.
  14482. + *
  14483. + * Shuts down the packet transport layer, removing and canceling all queued
  14484. + * and pending packets. Packets canceled by this operation will be completed
  14485. + * with %-ESHUTDOWN as status. Receiver and transmitter threads will be
  14486. + * stopped.
  14487. + *
  14488. + * As a result of this function, the transport layer will be marked as shut
  14489. + * down. Submission of packets after the transport layer has been shut down
  14490. + * will fail with %-ESHUTDOWN.
  14491. + */
  14492. +void ssh_ptl_shutdown(struct ssh_ptl *ptl)
  14493. +{
  14494. + LIST_HEAD(complete_q);
  14495. + LIST_HEAD(complete_p);
  14496. + struct ssh_packet *p, *n;
  14497. + int status;
  14498. +
  14499. + // ensure that no new packets (including ACK/NAK) can be submitted
  14500. + set_bit(SSH_PTL_SF_SHUTDOWN_BIT, &ptl->state);
  14501. + /*
  14502. + * Ensure that the layer gets marked as shut-down before actually
  14503. + * stopping it. In combination with the check in ssh_ptl_queue_push(),
  14504. + * this guarantees that no new packets can be added and all already
  14505. + * queued packets are properly cancelled. In combination with the check
  14506. + * in ssh_ptl_rx_rcvbuf(), this guarantees that received data is
  14507. + * properly cut off.
  14508. + */
  14509. + smp_mb__after_atomic();
  14510. +
  14511. + status = ssh_ptl_rx_stop(ptl);
  14512. + if (status)
  14513. + ptl_err(ptl, "ptl: failed to stop receiver thread\n");
  14514. +
  14515. + status = ssh_ptl_tx_stop(ptl);
  14516. + if (status)
  14517. + ptl_err(ptl, "ptl: failed to stop transmitter thread\n");
  14518. +
  14519. + cancel_delayed_work_sync(&ptl->rtx_timeout.reaper);
  14520. +
  14521. + /*
  14522. + * At this point, all threads have been stopped. This means that the
  14523. + * only references to packets from inside the system are in the queue
  14524. + * and pending set.
  14525. + *
  14526. + * Note: We still need locks here because someone could still be
  14527. + * cancelling packets.
  14528. + *
  14529. + * Note 2: We can re-use queue_node (or pending_node) if we mark the
  14530. + * packet as locked an then remove it from the queue (or pending set
  14531. + * respecitvely). Marking the packet as locked avoids re-queueing
  14532. + * (which should already be prevented by having stopped the treads...)
  14533. + * and not setting QUEUED_BIT (or PENDING_BIT) prevents removal from a
  14534. + * new list via other threads (e.g. canellation).
  14535. + *
  14536. + * Note 3: There may be overlap between complete_p and complete_q.
  14537. + * This is handled via test_and_set_bit() on the "completed" flag
  14538. + * (also handles cancellation).
  14539. + */
  14540. +
  14541. + // mark queued packets as locked and move them to complete_q
  14542. + spin_lock(&ptl->queue.lock);
  14543. + list_for_each_entry_safe(p, n, &ptl->queue.head, queue_node) {
  14544. + set_bit(SSH_PACKET_SF_LOCKED_BIT, &p->state);
  14545. + // ensure that state does not get zero
  14546. + smp_mb__before_atomic();
  14547. + clear_bit(SSH_PACKET_SF_QUEUED_BIT, &p->state);
  14548. +
  14549. + list_del(&p->queue_node);
  14550. + list_add_tail(&p->queue_node, &complete_q);
  14551. + }
  14552. + spin_unlock(&ptl->queue.lock);
  14553. +
  14554. + // mark pending packets as locked and move them to complete_p
  14555. + spin_lock(&ptl->pending.lock);
  14556. + list_for_each_entry_safe(p, n, &ptl->pending.head, pending_node) {
  14557. + set_bit(SSH_PACKET_SF_LOCKED_BIT, &p->state);
  14558. + // ensure that state does not get zero
  14559. + smp_mb__before_atomic();
  14560. + clear_bit(SSH_PACKET_SF_PENDING_BIT, &p->state);
  14561. +
  14562. + list_del(&p->pending_node);
  14563. + list_add_tail(&p->pending_node, &complete_q);
  14564. + }
  14565. + atomic_set(&ptl->pending.count, 0);
  14566. + spin_unlock(&ptl->pending.lock);
  14567. +
  14568. + // complete and drop packets on complete_q
  14569. + list_for_each_entry(p, &complete_q, queue_node) {
  14570. + if (!test_and_set_bit(SSH_PACKET_SF_COMPLETED_BIT, &p->state))
  14571. + __ssh_ptl_complete(p, -ESHUTDOWN);
  14572. +
  14573. + ssh_packet_put(p);
  14574. + }
  14575. +
  14576. + // complete and drop packets on complete_p
  14577. + list_for_each_entry(p, &complete_p, pending_node) {
  14578. + if (!test_and_set_bit(SSH_PACKET_SF_COMPLETED_BIT, &p->state))
  14579. + __ssh_ptl_complete(p, -ESHUTDOWN);
  14580. +
  14581. + ssh_packet_put(p);
  14582. + }
  14583. +
  14584. + /*
  14585. + * At this point we have guaranteed that the system doesn't reference
  14586. + * any packets any more.
  14587. + */
  14588. +}
  14589. +
  14590. +/**
  14591. + * ssh_ptl_init() - Initialize packet transport layer.
  14592. + * @ptl: The packet transport layer to initialize.
  14593. + * @serdev: The underlying serial device, i.e. the lower-level transport.
  14594. + * @ops: Packet layer operations.
  14595. + *
  14596. + * Initializes the given packet transport layer. Transmitter and receiver
  14597. + * threads must be started separately via ssh_ptl_tx_start() and
  14598. + * ssh_ptl_rx_start(), after the packet-layer has been initialized and the
  14599. + * lower-level transport layer has been set up.
  14600. + *
  14601. + * Return: Returns zero on success and a nonzero error code on failure.
  14602. + */
  14603. +int ssh_ptl_init(struct ssh_ptl *ptl, struct serdev_device *serdev,
  14604. + struct ssh_ptl_ops *ops)
  14605. +{
  14606. + int i, status;
  14607. +
  14608. + ptl->serdev = serdev;
  14609. + ptl->state = 0;
  14610. +
  14611. + spin_lock_init(&ptl->queue.lock);
  14612. + INIT_LIST_HEAD(&ptl->queue.head);
  14613. +
  14614. + spin_lock_init(&ptl->pending.lock);
  14615. + INIT_LIST_HEAD(&ptl->pending.head);
  14616. + atomic_set_release(&ptl->pending.count, 0);
  14617. +
  14618. + ptl->tx.thread = NULL;
  14619. + ptl->tx.thread_signal = false;
  14620. + ptl->tx.packet = NULL;
  14621. + ptl->tx.offset = 0;
  14622. + init_waitqueue_head(&ptl->tx.thread_wq);
  14623. + init_waitqueue_head(&ptl->tx.packet_wq);
  14624. +
  14625. + ptl->rx.thread = NULL;
  14626. + init_waitqueue_head(&ptl->rx.wq);
  14627. +
  14628. + ptl->rtx_timeout.timeout = SSH_PTL_PACKET_TIMEOUT;
  14629. + ptl->rtx_timeout.expires = KTIME_MAX;
  14630. + INIT_DELAYED_WORK(&ptl->rtx_timeout.reaper, ssh_ptl_timeout_reap);
  14631. +
  14632. + ptl->ops = *ops;
  14633. +
  14634. + // initialize list of recent/blocked SEQs with invalid sequence IDs
  14635. + for (i = 0; i < ARRAY_SIZE(ptl->rx.blocked.seqs); i++)
  14636. + ptl->rx.blocked.seqs[i] = 0xFFFF;
  14637. + ptl->rx.blocked.offset = 0;
  14638. +
  14639. + status = kfifo_alloc(&ptl->rx.fifo, SSH_PTL_RX_FIFO_LEN, GFP_KERNEL);
  14640. + if (status)
  14641. + return status;
  14642. +
  14643. + status = sshp_buf_alloc(&ptl->rx.buf, SSH_PTL_RX_BUF_LEN, GFP_KERNEL);
  14644. + if (status)
  14645. + kfifo_free(&ptl->rx.fifo);
  14646. +
  14647. + return status;
  14648. +}
  14649. +
  14650. +/**
  14651. + * ssh_ptl_destroy() - Deinitialize packet transport layer.
  14652. + * @ptl: The packet transport layer to deinitialize.
  14653. + *
  14654. + * Deinitializes the given packet transport layer and frees resources
  14655. + * associated with it. If receiver and/or transmitter threads have been
  14656. + * started, the layer must first be shut down via ssh_ptl_shutdown() before
  14657. + * this function can be called.
  14658. + */
  14659. +void ssh_ptl_destroy(struct ssh_ptl *ptl)
  14660. +{
  14661. + kfifo_free(&ptl->rx.fifo);
  14662. + sshp_buf_free(&ptl->rx.buf);
  14663. +}
  14664. diff --git a/drivers/misc/surface_aggregator/ssh_packet_layer.h b/drivers/misc/surface_aggregator/ssh_packet_layer.h
  14665. new file mode 100644
  14666. index 000000000000..f3d8a85389d5
  14667. --- /dev/null
  14668. +++ b/drivers/misc/surface_aggregator/ssh_packet_layer.h
  14669. @@ -0,0 +1,175 @@
  14670. +/* SPDX-License-Identifier: GPL-2.0+ */
  14671. +/*
  14672. + * SSH packet transport layer.
  14673. + *
  14674. + * Copyright (C) 2019-2020 Maximilian Luz <luzmaximilian@gmail.com>
  14675. + */
  14676. +
  14677. +#ifndef _SURFACE_AGGREGATOR_SSH_PACKET_LAYER_H
  14678. +#define _SURFACE_AGGREGATOR_SSH_PACKET_LAYER_H
  14679. +
  14680. +#include <linux/atomic.h>
  14681. +#include <linux/kfifo.h>
  14682. +#include <linux/ktime.h>
  14683. +#include <linux/list.h>
  14684. +#include <linux/serdev.h>
  14685. +#include <linux/spinlock.h>
  14686. +#include <linux/types.h>
  14687. +#include <linux/wait.h>
  14688. +#include <linux/workqueue.h>
  14689. +
  14690. +#include <linux/surface_aggregator/serial_hub.h>
  14691. +#include "ssh_parser.h"
  14692. +
  14693. +
  14694. +/**
  14695. + * enum ssh_ptl_state_flags - State-flags for &struct ssh_ptl.
  14696. + *
  14697. + * @SSH_PTL_SF_SHUTDOWN_BIT:
  14698. + * Indicates that the packet transport layer has been shut down or is
  14699. + * being shut down and should not accept any new packets/data.
  14700. + */
  14701. +enum ssh_ptl_state_flags {
  14702. + SSH_PTL_SF_SHUTDOWN_BIT,
  14703. +};
  14704. +
  14705. +/**
  14706. + * struct ssh_ptl_ops - Callback operations for packet transport layer.
  14707. + * @data_received: Function called when a data-packet has been received. Both,
  14708. + * the packet layer on which the packet has been received and
  14709. + * the packet's payload data are provided to this function.
  14710. + */
  14711. +struct ssh_ptl_ops {
  14712. + void (*data_received)(struct ssh_ptl *p, const struct ssam_span *data);
  14713. +};
  14714. +
  14715. +/**
  14716. + * struct ssh_ptl - SSH packet transport layer.
  14717. + * @serdev: Serial device providing the underlying data transport.
  14718. + * @state: State(-flags) of the transport layer.
  14719. + * @queue: Packet submission queue.
  14720. + * @queue.lock: Lock for modifying the packet submission queue.
  14721. + * @queue.head: List-head of the packet submission queue.
  14722. + * @pending: Set/list of pending packets.
  14723. + * @pending.lock: Lock for modifying the pending set.
  14724. + * @pending.head: List-head of the pending set/list.
  14725. + * @pending.count: Number of currently pending packets.
  14726. + * @tx: Transmitter subsystem.
  14727. + * @tx.thread_signal: Signal notifying transmitter thread of data to be sent.
  14728. + * @tx.thread: Transmitter thread.
  14729. + * @tx.thread_wq: Waitqueue-head for transmitter thread.
  14730. + * @tx.packet_wq: Waitqueue-head for packet transmit completion.
  14731. + * @tx.packet: Currently sent packet.
  14732. + * @tx.offset: Data-offset into the packet currently being transmitted.
  14733. + * @rx: Receiver subsystem.
  14734. + * @rx.thread: Receiver thread.
  14735. + * @rx.wq: Waitqueue-head for receiver thread.
  14736. + * @rx.fifo: Buffer for receiving data/pushing data to receiver thread.
  14737. + * @rx.buf: Buffer for evaluating data on receiver thread.
  14738. + * @rx.blocked: List of recent/blocked sequence IDs to detect retransmission.
  14739. + * @rx.blocked.seqs: Array of blocked sequence IDs.
  14740. + * @rx.blocked.offset: Offset indicating where a new ID should be inserted.
  14741. + * @rtx_timeout: Retransmission timeout subsystem.
  14742. + * @rtx_timeout.timeout: Timeout inverval for retransmission.
  14743. + * @rtx_timeout.expires: Time specifying when the reaper work is next scheduled.
  14744. + * @rtx_timeout.reaper: Work performing timeout checks and subsequent actions.
  14745. + * @ops: Packet layer operations.
  14746. + */
  14747. +struct ssh_ptl {
  14748. + struct serdev_device *serdev;
  14749. + unsigned long state;
  14750. +
  14751. + struct {
  14752. + spinlock_t lock;
  14753. + struct list_head head;
  14754. + } queue;
  14755. +
  14756. + struct {
  14757. + spinlock_t lock;
  14758. + struct list_head head;
  14759. + atomic_t count;
  14760. + } pending;
  14761. +
  14762. + struct {
  14763. + bool thread_signal;
  14764. + struct task_struct *thread;
  14765. + struct wait_queue_head thread_wq;
  14766. + struct wait_queue_head packet_wq;
  14767. + struct ssh_packet *packet;
  14768. + size_t offset;
  14769. + } tx;
  14770. +
  14771. + struct {
  14772. + struct task_struct *thread;
  14773. + struct wait_queue_head wq;
  14774. + struct kfifo fifo;
  14775. + struct sshp_buf buf;
  14776. +
  14777. + struct {
  14778. + u16 seqs[8];
  14779. + u16 offset;
  14780. + } blocked;
  14781. + } rx;
  14782. +
  14783. + struct {
  14784. + ktime_t timeout;
  14785. + ktime_t expires;
  14786. + struct delayed_work reaper;
  14787. + } rtx_timeout;
  14788. +
  14789. + struct ssh_ptl_ops ops;
  14790. +};
  14791. +
  14792. +
  14793. +#define __ssam_prcond(func, p, fmt, ...) \
  14794. + do { \
  14795. + if ((p)) \
  14796. + func((p), fmt, ##__VA_ARGS__); \
  14797. + } while (0)
  14798. +
  14799. +#define ptl_dbg(p, fmt, ...) dev_dbg(&(p)->serdev->dev, fmt, ##__VA_ARGS__)
  14800. +#define ptl_info(p, fmt, ...) dev_info(&(p)->serdev->dev, fmt, ##__VA_ARGS__)
  14801. +#define ptl_warn(p, fmt, ...) dev_warn(&(p)->serdev->dev, fmt, ##__VA_ARGS__)
  14802. +#define ptl_err(p, fmt, ...) dev_err(&(p)->serdev->dev, fmt, ##__VA_ARGS__)
  14803. +#define ptl_dbg_cond(p, fmt, ...) __ssam_prcond(ptl_dbg, p, fmt, ##__VA_ARGS__)
  14804. +
  14805. +#define to_ssh_ptl(ptr, member) \
  14806. + container_of(ptr, struct ssh_ptl, member)
  14807. +
  14808. +
  14809. +int ssh_ptl_init(struct ssh_ptl *ptl, struct serdev_device *serdev,
  14810. + struct ssh_ptl_ops *ops);
  14811. +
  14812. +void ssh_ptl_destroy(struct ssh_ptl *ptl);
  14813. +
  14814. +/**
  14815. + * ssh_ptl_get_device() - Get device associated with packet transport layer.
  14816. + * @ptl: The packet transport layer.
  14817. + *
  14818. + * Return: Returns the device on which the given packet transport layer builds
  14819. + * upon.
  14820. + */
  14821. +static inline struct device *ssh_ptl_get_device(struct ssh_ptl *ptl)
  14822. +{
  14823. + return ptl->serdev ? &ptl->serdev->dev : NULL;
  14824. +}
  14825. +
  14826. +int ssh_ptl_tx_start(struct ssh_ptl *ptl);
  14827. +int ssh_ptl_tx_stop(struct ssh_ptl *ptl);
  14828. +int ssh_ptl_rx_start(struct ssh_ptl *ptl);
  14829. +int ssh_ptl_rx_stop(struct ssh_ptl *ptl);
  14830. +void ssh_ptl_shutdown(struct ssh_ptl *ptl);
  14831. +
  14832. +int ssh_ptl_submit(struct ssh_ptl *ptl, struct ssh_packet *p);
  14833. +void ssh_ptl_cancel(struct ssh_packet *p);
  14834. +
  14835. +int ssh_ptl_rx_rcvbuf(struct ssh_ptl *ptl, const u8 *buf, size_t n);
  14836. +void ssh_ptl_tx_wakeup(struct ssh_ptl *ptl);
  14837. +
  14838. +void ssh_packet_init(struct ssh_packet *packet, unsigned long type,
  14839. + u8 priority, const struct ssh_packet_ops *ops);
  14840. +
  14841. +int ssh_ctrl_packet_cache_init(void);
  14842. +void ssh_ctrl_packet_cache_destroy(void);
  14843. +
  14844. +#endif /* _SURFACE_AGGREGATOR_SSH_PACKET_LAYER_H */
  14845. diff --git a/drivers/misc/surface_aggregator/ssh_parser.c b/drivers/misc/surface_aggregator/ssh_parser.c
  14846. new file mode 100644
  14847. index 000000000000..575cbc039ad7
  14848. --- /dev/null
  14849. +++ b/drivers/misc/surface_aggregator/ssh_parser.c
  14850. @@ -0,0 +1,229 @@
  14851. +// SPDX-License-Identifier: GPL-2.0+
  14852. +/*
  14853. + * SSH message parser.
  14854. + *
  14855. + * Copyright (C) 2019-2020 Maximilian Luz <luzmaximilian@gmail.com>
  14856. + */
  14857. +
  14858. +#include <asm/unaligned.h>
  14859. +#include <linux/compiler.h>
  14860. +#include <linux/device.h>
  14861. +#include <linux/types.h>
  14862. +
  14863. +#include <linux/surface_aggregator/serial_hub.h>
  14864. +#include "ssh_parser.h"
  14865. +
  14866. +
  14867. +/**
  14868. + * sshp_validate_crc() - Validate a CRC in raw message data.
  14869. + * @src: The span of data over which the CRC should be computed.
  14870. + * @crc: The pointer to the expected u16 CRC value.
  14871. + *
  14872. + * Computes the CRC of the provided data span (@src), compares it to the CRC
  14873. + * stored at the given address (@crc), and returns the result of this
  14874. + * comparison, i.e. %true iff equal. This function is intended to run on raw
  14875. + * input/message data.
  14876. + *
  14877. + * Return: Returns %true iff the computed CRC matches the stored CRC, %false
  14878. + * otherwise.
  14879. + */
  14880. +static bool sshp_validate_crc(const struct ssam_span *src, const u8 *crc)
  14881. +{
  14882. + u16 actual = ssh_crc(src->ptr, src->len);
  14883. + u16 expected = get_unaligned_le16(crc);
  14884. +
  14885. + return actual == expected;
  14886. +}
  14887. +
  14888. +/**
  14889. + * sshp_starts_with_syn() - Check if the given data starts with SSH SYN bytes.
  14890. + * @src: The data span to check the start of.
  14891. + */
  14892. +static bool sshp_starts_with_syn(const struct ssam_span *src)
  14893. +{
  14894. + return src->len >= 2 && get_unaligned_le16(src->ptr) == SSH_MSG_SYN;
  14895. +}
  14896. +
  14897. +/**
  14898. + * sshp_find_syn() - Find SSH SYN bytes in the given data span.
  14899. + * @src: The data span to search in.
  14900. + * @rem: The span (output) indicating the remaining data, starting with SSH
  14901. + * SYN bytes, if found.
  14902. + *
  14903. + * Search for SSH SYN bytes in the given source span. If found, set the @rem
  14904. + * span to the remaining data, starting with the first SYN bytes and capped by
  14905. + * the source span length, and return %true. This function does not copy
  14906. + * any data, but rather only sets pointers to the respecitve start addresses
  14907. + * and length values.
  14908. + *
  14909. + * If no SSH SYN bytes could be found, set the @rem span to the zero-length
  14910. + * span at the end of the source span and return %false.
  14911. + *
  14912. + * If partial SSH SYN bytes could be found at the end of the source span, set
  14913. + * the @rem span to cover these partial SYN bytes, capped by the end of the
  14914. + * source span, and return %false. This function should then be re-run once
  14915. + * more data is available.
  14916. + *
  14917. + * Return: Returns %true iff a complete SSG SYN sequence could be found,
  14918. + * %false otherwise.
  14919. + */
  14920. +bool sshp_find_syn(const struct ssam_span *src, struct ssam_span *rem)
  14921. +{
  14922. + size_t i;
  14923. +
  14924. + for (i = 0; i < src->len - 1; i++) {
  14925. + if (likely(get_unaligned_le16(src->ptr + i) == SSH_MSG_SYN)) {
  14926. + rem->ptr = src->ptr + i;
  14927. + rem->len = src->len - i;
  14928. + return true;
  14929. + }
  14930. + }
  14931. +
  14932. + if (unlikely(src->ptr[src->len - 1] == (SSH_MSG_SYN & 0xff))) {
  14933. + rem->ptr = src->ptr + src->len - 1;
  14934. + rem->len = 1;
  14935. + return false;
  14936. + }
  14937. +
  14938. + rem->ptr = src->ptr + src->len;
  14939. + rem->len = 0;
  14940. + return false;
  14941. +}
  14942. +
  14943. +/**
  14944. + * sshp_parse_frame() - Parse SSH frame.
  14945. + * @dev: The device used for logging.
  14946. + * @source: The source to parse from.
  14947. + * @frame: The parsed frame (output).
  14948. + * @payload: The parsed payload (output).
  14949. + * @maxlen: The maximum supported message length.
  14950. + *
  14951. + * Parses and validates a SSH frame, including its payload, from the given
  14952. + * source. Sets the provided @frame pointer to the start of the frame and
  14953. + * writes the limits of the frame payload to the provided @payload span
  14954. + * pointer.
  14955. + *
  14956. + * This function does not copy any data, but rather only validates the message
  14957. + * data and sets pointers (and length values) to indicate the respective parts.
  14958. + *
  14959. + * If no complete SSH frame could be found, the frame pointer will be set to
  14960. + * the %NULL pointer and the payload span will be set to the null span (start
  14961. + * pointer %NULL, size zero).
  14962. + *
  14963. + * Return: Returns zero on success or if the frame is incomplete, %-ENOMSG if
  14964. + * the start of the message is invalid, %-EBADMSG if any (frame-header or
  14965. + * payload) CRC is ivnalid, or %-EMSGSIZE if the SSH message is bigger than
  14966. + * the maximum message length specified in the @maxlen parameter.
  14967. + */
  14968. +int sshp_parse_frame(const struct device *dev, const struct ssam_span *source,
  14969. + struct ssh_frame **frame, struct ssam_span *payload,
  14970. + size_t maxlen)
  14971. +{
  14972. + struct ssam_span sf;
  14973. + struct ssam_span sp;
  14974. +
  14975. + // initialize output
  14976. + *frame = NULL;
  14977. + payload->ptr = NULL;
  14978. + payload->len = 0;
  14979. +
  14980. + if (!sshp_starts_with_syn(source)) {
  14981. + dev_warn(dev, "rx: parser: invalid start of frame\n");
  14982. + return -ENOMSG;
  14983. + }
  14984. +
  14985. + // check for minimum packet length
  14986. + if (unlikely(source->len < SSH_MESSAGE_LENGTH(0))) {
  14987. + dev_dbg(dev, "rx: parser: not enough data for frame\n");
  14988. + return 0;
  14989. + }
  14990. +
  14991. + // pin down frame
  14992. + sf.ptr = source->ptr + sizeof(u16);
  14993. + sf.len = sizeof(struct ssh_frame);
  14994. +
  14995. + // validate frame CRC
  14996. + if (unlikely(!sshp_validate_crc(&sf, sf.ptr + sf.len))) {
  14997. + dev_warn(dev, "rx: parser: invalid frame CRC\n");
  14998. + return -EBADMSG;
  14999. + }
  15000. +
  15001. + // ensure packet does not exceed maximum length
  15002. + sp.len = get_unaligned_le16(&((struct ssh_frame *)sf.ptr)->len);
  15003. + if (unlikely(sp.len + SSH_MESSAGE_LENGTH(0) > maxlen)) {
  15004. + dev_warn(dev, "rx: parser: frame too large: %u bytes\n",
  15005. + ((struct ssh_frame *)sf.ptr)->len);
  15006. + return -EMSGSIZE;
  15007. + }
  15008. +
  15009. + // pin down payload
  15010. + sp.ptr = sf.ptr + sf.len + sizeof(u16);
  15011. +
  15012. + // check for frame + payload length
  15013. + if (source->len < SSH_MESSAGE_LENGTH(sp.len)) {
  15014. + dev_dbg(dev, "rx: parser: not enough data for payload\n");
  15015. + return 0;
  15016. + }
  15017. +
  15018. + // validate payload crc
  15019. + if (unlikely(!sshp_validate_crc(&sp, sp.ptr + sp.len))) {
  15020. + dev_warn(dev, "rx: parser: invalid payload CRC\n");
  15021. + return -EBADMSG;
  15022. + }
  15023. +
  15024. + *frame = (struct ssh_frame *)sf.ptr;
  15025. + *payload = sp;
  15026. +
  15027. + dev_dbg(dev, "rx: parser: valid frame found (type: 0x%02x, len: %u)\n",
  15028. + (*frame)->type, (*frame)->len);
  15029. +
  15030. + return 0;
  15031. +}
  15032. +
  15033. +/**
  15034. + * sshp_parse_command() - Parse SSH command frame payload.
  15035. + * @dev: The device used for logging.
  15036. + * @source: The source to parse from.
  15037. + * @command: The parsed command (output).
  15038. + * @command_data: The parsed command data/payload (output).
  15039. + *
  15040. + * Parses and validates a SSH command frame payload. Sets the @command pointer
  15041. + * to the command header and the @command_data span to the command data (i.e.
  15042. + * payload of the command). This will result in a zero-length span if the
  15043. + * command does not have any associated data/payload. This function does not
  15044. + * check the frame-payload-type field, which should be checked by the caller
  15045. + * before calling this function.
  15046. + *
  15047. + * The @source parameter should be the complete frame payload, e.g. returned
  15048. + * by the sshp_parse_frame() command.
  15049. + *
  15050. + * This function does not copy any data, but rather only validates the frame
  15051. + * payload data and sets pointers (and length values) to indicate the
  15052. + * respective parts.
  15053. + *
  15054. + * Return: Returns zero on success or %-ENOMSG if @source does not represent a
  15055. + * valid command-type frame payload, i.e. is too short.
  15056. + */
  15057. +int sshp_parse_command(const struct device *dev, const struct ssam_span *source,
  15058. + struct ssh_command **command,
  15059. + struct ssam_span *command_data)
  15060. +{
  15061. + // check for minimum length
  15062. + if (unlikely(source->len < sizeof(struct ssh_command))) {
  15063. + *command = NULL;
  15064. + command_data->ptr = NULL;
  15065. + command_data->len = 0;
  15066. +
  15067. + dev_err(dev, "rx: parser: command payload is too short\n");
  15068. + return -ENOMSG;
  15069. + }
  15070. +
  15071. + *command = (struct ssh_command *)source->ptr;
  15072. + command_data->ptr = source->ptr + sizeof(struct ssh_command);
  15073. + command_data->len = source->len - sizeof(struct ssh_command);
  15074. +
  15075. + dev_dbg(dev, "rx: parser: valid command found (tc: 0x%02x, cid: 0x%02x)\n",
  15076. + (*command)->tc, (*command)->cid);
  15077. +
  15078. + return 0;
  15079. +}
  15080. diff --git a/drivers/misc/surface_aggregator/ssh_parser.h b/drivers/misc/surface_aggregator/ssh_parser.h
  15081. new file mode 100644
  15082. index 000000000000..71c43ab07bf6
  15083. --- /dev/null
  15084. +++ b/drivers/misc/surface_aggregator/ssh_parser.h
  15085. @@ -0,0 +1,157 @@
  15086. +/* SPDX-License-Identifier: GPL-2.0+ */
  15087. +/*
  15088. + * SSH message parser.
  15089. + *
  15090. + * Copyright (C) 2019-2020 Maximilian Luz <luzmaximilian@gmail.com>
  15091. + */
  15092. +
  15093. +#ifndef _SURFACE_AGGREGATOR_SSH_PARSER_H
  15094. +#define _SURFACE_AGGREGATOR_SSH_PARSER_H
  15095. +
  15096. +#include <linux/device.h>
  15097. +#include <linux/kfifo.h>
  15098. +#include <linux/slab.h>
  15099. +#include <linux/types.h>
  15100. +
  15101. +#include <linux/surface_aggregator/serial_hub.h>
  15102. +
  15103. +
  15104. +/**
  15105. + * struct sshp_buf - Parser buffer for SSH messages.
  15106. + * @ptr: Pointer to the beginning of the buffer.
  15107. + * @len: Number of bytes used in the buffer.
  15108. + * @cap: Maximum capacity of the buffer.
  15109. + */
  15110. +struct sshp_buf {
  15111. + u8 *ptr;
  15112. + size_t len;
  15113. + size_t cap;
  15114. +};
  15115. +
  15116. +/**
  15117. + * sshp_buf_init() - Initialize a SSH parser buffer.
  15118. + * @buf: The buffer to initialize.
  15119. + * @ptr: The memory backing the buffer.
  15120. + * @cap: The length of the memory backing the buffer, i.e. its capacity.
  15121. + *
  15122. + * Initializes the buffer with the given memory as backing and set its used
  15123. + * length to zero.
  15124. + */
  15125. +static inline void sshp_buf_init(struct sshp_buf *buf, u8 *ptr, size_t cap)
  15126. +{
  15127. + buf->ptr = ptr;
  15128. + buf->len = 0;
  15129. + buf->cap = cap;
  15130. +}
  15131. +
  15132. +/**
  15133. + * sshp_buf_alloc() - Allocate and initialize a SSH parser buffer.
  15134. + * @buf: The buffer to initialize/allocate to.
  15135. + * @cap: The desired capacity of the buffer.
  15136. + * @flags: The flags used for allocating the memory.
  15137. + *
  15138. + * Allocates @cap bytes and initializes the provided buffer struct with the
  15139. + * allocated memory.
  15140. + *
  15141. + * Return: Returns zero on success and %-ENOMEM if allocation failed.
  15142. + */
  15143. +static inline int sshp_buf_alloc(struct sshp_buf *buf, size_t cap, gfp_t flags)
  15144. +{
  15145. + u8 *ptr;
  15146. +
  15147. + ptr = kzalloc(cap, flags);
  15148. + if (!ptr)
  15149. + return -ENOMEM;
  15150. +
  15151. + sshp_buf_init(buf, ptr, cap);
  15152. + return 0;
  15153. +
  15154. +}
  15155. +
  15156. +/**
  15157. + * sshp_buf_free() - Free a SSH parser buffer.
  15158. + * @buf: The buffer to free.
  15159. + *
  15160. + * Frees a SSH parser buffer by freeing the memory backing it and then
  15161. + * resetting its pointer to %NULL and length and capacity to zero. Intended to
  15162. + * free a buffer previously allocated with sshp_buf_alloc().
  15163. + */
  15164. +static inline void sshp_buf_free(struct sshp_buf *buf)
  15165. +{
  15166. + kfree(buf->ptr);
  15167. + buf->ptr = NULL;
  15168. + buf->len = 0;
  15169. + buf->cap = 0;
  15170. +}
  15171. +
  15172. +/**
  15173. + * sshp_buf_drop() - Drop data from the beginning of the buffer.
  15174. + * @buf: The buffer to drop data from.
  15175. + * @n: The number of bytes to drop.
  15176. + *
  15177. + * Drops the first @n bytes from the buffer. Re-aligns any remaining data to
  15178. + * the beginning of the buffer.
  15179. + */
  15180. +static inline void sshp_buf_drop(struct sshp_buf *buf, size_t n)
  15181. +{
  15182. + memmove(buf->ptr, buf->ptr + n, buf->len - n);
  15183. + buf->len -= n;
  15184. +}
  15185. +
  15186. +/**
  15187. + * sshp_buf_read_from_fifo() - Transfer data from a fifo to the buffer.
  15188. + * @buf: The buffer to write the data into.
  15189. + * @fifo: The fifo to read the data from.
  15190. + *
  15191. + * Transfers the data contained in the fifo to the buffer, removing it from
  15192. + * the fifo. This function will try to transfer as much data as possible,
  15193. + * limited either by the remaining space in the buffer or by the number of
  15194. + * bytes available in the fifo.
  15195. + *
  15196. + * Return: Returns the number of bytes transferred.
  15197. + */
  15198. +static inline size_t sshp_buf_read_from_fifo(struct sshp_buf *buf,
  15199. + struct kfifo *fifo)
  15200. +{
  15201. + size_t n;
  15202. +
  15203. + n = kfifo_out(fifo, buf->ptr + buf->len, buf->cap - buf->len);
  15204. + buf->len += n;
  15205. +
  15206. + return n;
  15207. +}
  15208. +
  15209. +/**
  15210. + * sshp_buf_span_from() - Initialize a span from the given buffer and offset.
  15211. + * @buf: The buffer to create the span from.
  15212. + * @offset: The offset in the buffer at which the span should start.
  15213. + * @span: The span to initialize (output).
  15214. + *
  15215. + * Initializes the provided span to point to the memory at the given offset in
  15216. + * the buffer, with the length of the span being capped by the number of bytes
  15217. + * used in the buffer after the offset (i.e. bytes remaining after the
  15218. + * offset).
  15219. + *
  15220. + * Warning: This function does not validate that @offset is less than or equal
  15221. + * to the number of bytes used in the buffer or the buffer capacity. This must
  15222. + * be guaranteed by the caller.
  15223. + */
  15224. +static inline void sshp_buf_span_from(struct sshp_buf *buf, size_t offset,
  15225. + struct ssam_span *span)
  15226. +{
  15227. + span->ptr = buf->ptr + offset;
  15228. + span->len = buf->len - offset;
  15229. +}
  15230. +
  15231. +
  15232. +bool sshp_find_syn(const struct ssam_span *src, struct ssam_span *rem);
  15233. +
  15234. +int sshp_parse_frame(const struct device *dev, const struct ssam_span *source,
  15235. + struct ssh_frame **frame, struct ssam_span *payload,
  15236. + size_t maxlen);
  15237. +
  15238. +int sshp_parse_command(const struct device *dev, const struct ssam_span *source,
  15239. + struct ssh_command **command,
  15240. + struct ssam_span *command_data);
  15241. +
  15242. +#endif /* _SURFACE_AGGREGATOR_SSH_PARSER_h */
  15243. diff --git a/drivers/misc/surface_aggregator/ssh_request_layer.c b/drivers/misc/surface_aggregator/ssh_request_layer.c
  15244. new file mode 100644
  15245. index 000000000000..f47bd949b6c3
  15246. --- /dev/null
  15247. +++ b/drivers/misc/surface_aggregator/ssh_request_layer.c
  15248. @@ -0,0 +1,1254 @@
  15249. +// SPDX-License-Identifier: GPL-2.0+
  15250. +/*
  15251. + * SSH request transport layer.
  15252. + *
  15253. + * Copyright (C) 2019-2020 Maximilian Luz <luzmaximilian@gmail.com>
  15254. + */
  15255. +
  15256. +#include <asm/unaligned.h>
  15257. +#include <linux/atomic.h>
  15258. +#include <linux/completion.h>
  15259. +#include <linux/error-injection.h>
  15260. +#include <linux/ktime.h>
  15261. +#include <linux/list.h>
  15262. +#include <linux/slab.h>
  15263. +#include <linux/spinlock.h>
  15264. +#include <linux/types.h>
  15265. +#include <linux/workqueue.h>
  15266. +
  15267. +#include <linux/surface_aggregator/serial_hub.h>
  15268. +#include <linux/surface_aggregator/controller.h>
  15269. +
  15270. +#include "ssh_packet_layer.h"
  15271. +#include "ssh_request_layer.h"
  15272. +
  15273. +#include "trace.h"
  15274. +
  15275. +
  15276. +/*
  15277. + * SSH_RTL_REQUEST_TIMEOUT - Request timeout.
  15278. + *
  15279. + * Timeout as ktime_t delta for request responses. If we have not received a
  15280. + * response in this time-frame after finishing the underlying packet
  15281. + * transmission, the request will be completed with %-ETIMEDOUT as status
  15282. + * code.
  15283. + */
  15284. +#define SSH_RTL_REQUEST_TIMEOUT ms_to_ktime(3000)
  15285. +
  15286. +/*
  15287. + * SSH_RTL_REQUEST_TIMEOUT_RESOLUTION - Request timeout granularity.
  15288. + *
  15289. + * Time-resolution for timeouts. Should be larger than one jiffy to avoid
  15290. + * direct re-scheduling of reaper work_struct.
  15291. + */
  15292. +#define SSH_RTL_REQUEST_TIMEOUT_RESOLUTION ms_to_ktime(max(2000 / HZ, 50))
  15293. +
  15294. +/*
  15295. + * SSH_RTL_MAX_PENDING - Maximum number of pending requests.
  15296. + *
  15297. + * Maximum number of requests concurrently waiting to be completed (i.e.
  15298. + * waiting for the corresponding packet transmission to finish if they don't
  15299. + * have a response or waiting for a response if they have one).
  15300. + */
  15301. +#define SSH_RTL_MAX_PENDING 3
  15302. +
  15303. +
  15304. +#ifdef CONFIG_SURFACE_AGGREGATOR_ERROR_INJECTION
  15305. +
  15306. +/**
  15307. + * ssh_rtl_should_drop_response() - Error injection hook to drop request
  15308. + * responses.
  15309. + *
  15310. + * Useful to cause request transmission timeouts in the driver by dropping the
  15311. + * response to a request.
  15312. + */
  15313. +static noinline bool ssh_rtl_should_drop_response(void)
  15314. +{
  15315. + return false;
  15316. +}
  15317. +ALLOW_ERROR_INJECTION(ssh_rtl_should_drop_response, TRUE);
  15318. +
  15319. +#else
  15320. +
  15321. +static inline bool ssh_rtl_should_drop_response(void)
  15322. +{
  15323. + return false;
  15324. +}
  15325. +
  15326. +#endif
  15327. +
  15328. +
  15329. +static u16 ssh_request_get_rqid(struct ssh_request *rqst)
  15330. +{
  15331. + return get_unaligned_le16(rqst->packet.data.ptr
  15332. + + SSH_MSGOFFSET_COMMAND(rqid));
  15333. +}
  15334. +
  15335. +static u32 ssh_request_get_rqid_safe(struct ssh_request *rqst)
  15336. +{
  15337. + if (!rqst->packet.data.ptr)
  15338. + return (u32)-1;
  15339. +
  15340. + return ssh_request_get_rqid(rqst);
  15341. +}
  15342. +
  15343. +
  15344. +static void ssh_rtl_queue_remove(struct ssh_request *rqst)
  15345. +{
  15346. + struct ssh_rtl *rtl = ssh_request_rtl(rqst);
  15347. +
  15348. + spin_lock(&rtl->queue.lock);
  15349. +
  15350. + if (!test_and_clear_bit(SSH_REQUEST_SF_QUEUED_BIT, &rqst->state)) {
  15351. + spin_unlock(&rtl->queue.lock);
  15352. + return;
  15353. + }
  15354. +
  15355. + list_del(&rqst->node);
  15356. +
  15357. + spin_unlock(&rtl->queue.lock);
  15358. + ssh_request_put(rqst);
  15359. +}
  15360. +
  15361. +static bool ssh_rtl_queue_empty(struct ssh_rtl *rtl)
  15362. +{
  15363. + bool empty;
  15364. +
  15365. + spin_lock(&rtl->queue.lock);
  15366. + empty = list_empty(&rtl->queue.head);
  15367. + spin_unlock(&rtl->queue.lock);
  15368. +
  15369. + return empty;
  15370. +}
  15371. +
  15372. +
  15373. +static void ssh_rtl_pending_remove(struct ssh_request *rqst)
  15374. +{
  15375. + struct ssh_rtl *rtl = ssh_request_rtl(rqst);
  15376. +
  15377. + spin_lock(&rtl->pending.lock);
  15378. +
  15379. + if (!test_and_clear_bit(SSH_REQUEST_SF_PENDING_BIT, &rqst->state)) {
  15380. + spin_unlock(&rtl->pending.lock);
  15381. + return;
  15382. + }
  15383. +
  15384. + atomic_dec(&rtl->pending.count);
  15385. + list_del(&rqst->node);
  15386. +
  15387. + spin_unlock(&rtl->pending.lock);
  15388. +
  15389. + ssh_request_put(rqst);
  15390. +}
  15391. +
  15392. +static int ssh_rtl_tx_pending_push(struct ssh_request *rqst)
  15393. +{
  15394. + struct ssh_rtl *rtl = ssh_request_rtl(rqst);
  15395. +
  15396. + spin_lock(&rtl->pending.lock);
  15397. +
  15398. + if (test_bit(SSH_REQUEST_SF_LOCKED_BIT, &rqst->state)) {
  15399. + spin_unlock(&rtl->pending.lock);
  15400. + return -EINVAL;
  15401. + }
  15402. +
  15403. + if (test_and_set_bit(SSH_REQUEST_SF_PENDING_BIT, &rqst->state)) {
  15404. + spin_unlock(&rtl->pending.lock);
  15405. + return -EALREADY;
  15406. + }
  15407. +
  15408. + atomic_inc(&rtl->pending.count);
  15409. + list_add_tail(&ssh_request_get(rqst)->node, &rtl->pending.head);
  15410. +
  15411. + spin_unlock(&rtl->pending.lock);
  15412. + return 0;
  15413. +}
  15414. +
  15415. +
  15416. +static void ssh_rtl_complete_with_status(struct ssh_request *rqst, int status)
  15417. +{
  15418. + struct ssh_rtl *rtl = ssh_request_rtl(rqst);
  15419. +
  15420. + trace_ssam_request_complete(rqst, status);
  15421. +
  15422. + // rtl/ptl may not be set if we're cancelling before submitting
  15423. + rtl_dbg_cond(rtl, "rtl: completing request (rqid: 0x%04x, status: %d)\n",
  15424. + ssh_request_get_rqid_safe(rqst), status);
  15425. +
  15426. + rqst->ops->complete(rqst, NULL, NULL, status);
  15427. +}
  15428. +
  15429. +static void ssh_rtl_complete_with_rsp(struct ssh_request *rqst,
  15430. + const struct ssh_command *cmd,
  15431. + const struct ssam_span *data)
  15432. +{
  15433. + struct ssh_rtl *rtl = ssh_request_rtl(rqst);
  15434. +
  15435. + trace_ssam_request_complete(rqst, 0);
  15436. +
  15437. + rtl_dbg(rtl, "rtl: completing request with response (rqid: 0x%04x)\n",
  15438. + ssh_request_get_rqid(rqst));
  15439. +
  15440. + rqst->ops->complete(rqst, cmd, data, 0);
  15441. +}
  15442. +
  15443. +
  15444. +static bool ssh_rtl_tx_can_process(struct ssh_request *rqst)
  15445. +{
  15446. + struct ssh_rtl *rtl = ssh_request_rtl(rqst);
  15447. +
  15448. + if (test_bit(SSH_REQUEST_TY_FLUSH_BIT, &rqst->state))
  15449. + return !atomic_read(&rtl->pending.count);
  15450. +
  15451. + return atomic_read(&rtl->pending.count) < SSH_RTL_MAX_PENDING;
  15452. +}
  15453. +
  15454. +static struct ssh_request *ssh_rtl_tx_next(struct ssh_rtl *rtl)
  15455. +{
  15456. + struct ssh_request *rqst = ERR_PTR(-ENOENT);
  15457. + struct ssh_request *p, *n;
  15458. +
  15459. + spin_lock(&rtl->queue.lock);
  15460. +
  15461. + // find first non-locked request and remove it
  15462. + list_for_each_entry_safe(p, n, &rtl->queue.head, node) {
  15463. + if (unlikely(test_bit(SSH_REQUEST_SF_LOCKED_BIT, &p->state)))
  15464. + continue;
  15465. +
  15466. + if (!ssh_rtl_tx_can_process(p)) {
  15467. + rqst = ERR_PTR(-EBUSY);
  15468. + break;
  15469. + }
  15470. +
  15471. + // remove from queue and mark as transmitting
  15472. + set_bit(SSH_REQUEST_SF_TRANSMITTING_BIT, &p->state);
  15473. + // ensure state never gets zero
  15474. + smp_mb__before_atomic();
  15475. + clear_bit(SSH_REQUEST_SF_QUEUED_BIT, &p->state);
  15476. +
  15477. + list_del(&p->node);
  15478. +
  15479. + rqst = p;
  15480. + break;
  15481. + }
  15482. +
  15483. + spin_unlock(&rtl->queue.lock);
  15484. + return rqst;
  15485. +}
  15486. +
  15487. +static int ssh_rtl_tx_try_process_one(struct ssh_rtl *rtl)
  15488. +{
  15489. + struct ssh_request *rqst;
  15490. + int status;
  15491. +
  15492. + // get and prepare next request for transmit
  15493. + rqst = ssh_rtl_tx_next(rtl);
  15494. + if (IS_ERR(rqst))
  15495. + return PTR_ERR(rqst);
  15496. +
  15497. + // add to/mark as pending
  15498. + status = ssh_rtl_tx_pending_push(rqst);
  15499. + if (status) {
  15500. + ssh_request_put(rqst);
  15501. + return -EAGAIN;
  15502. + }
  15503. +
  15504. + // submit packet
  15505. + status = ssh_ptl_submit(&rtl->ptl, &rqst->packet);
  15506. + if (status == -ESHUTDOWN) {
  15507. + /*
  15508. + * Packet has been refused due to the packet layer shutting
  15509. + * down. Complete it here.
  15510. + */
  15511. + set_bit(SSH_REQUEST_SF_LOCKED_BIT, &rqst->state);
  15512. + /*
  15513. + * Note: A barrier is not required here, as there are only two
  15514. + * references in the system at this point: The one that we have,
  15515. + * and the other one that belongs to the pending set. Due to the
  15516. + * request being marked as "transmitting", our process is the
  15517. + * only one allowed to remove the pending node and change the
  15518. + * state. Normally, the task would fall to the packet callback,
  15519. + * but as this is a path where submission failed, this callback
  15520. + * will never be executed.
  15521. + */
  15522. +
  15523. + ssh_rtl_pending_remove(rqst);
  15524. + ssh_rtl_complete_with_status(rqst, -ESHUTDOWN);
  15525. +
  15526. + ssh_request_put(rqst);
  15527. + return -ESHUTDOWN;
  15528. +
  15529. + } else if (status) {
  15530. + /*
  15531. + * If submitting the packet failed and the packet layer isn't
  15532. + * shutting down, the packet has either been submmitted/queued
  15533. + * before (-EALREADY, which cannot happen as we have guaranteed
  15534. + * that requests cannot be re-submitted), or the packet was
  15535. + * marked as locked (-EINVAL). To mark the packet locked at this
  15536. + * stage, the request, and thus the packets itself, had to have
  15537. + * been canceled. Simply drop the reference. Cancellation itself
  15538. + * will remove it from the set of pending requests.
  15539. + */
  15540. +
  15541. + WARN_ON(status != -EINVAL);
  15542. +
  15543. + ssh_request_put(rqst);
  15544. + return -EAGAIN;
  15545. + }
  15546. +
  15547. + ssh_request_put(rqst);
  15548. + return 0;
  15549. +}
  15550. +
  15551. +static bool ssh_rtl_tx_schedule(struct ssh_rtl *rtl)
  15552. +{
  15553. + if (atomic_read(&rtl->pending.count) >= SSH_RTL_MAX_PENDING)
  15554. + return false;
  15555. +
  15556. + if (ssh_rtl_queue_empty(rtl))
  15557. + return false;
  15558. +
  15559. + return schedule_work(&rtl->tx.work);
  15560. +}
  15561. +
  15562. +static void ssh_rtl_tx_work_fn(struct work_struct *work)
  15563. +{
  15564. + struct ssh_rtl *rtl = to_ssh_rtl(work, tx.work);
  15565. + int i, status;
  15566. +
  15567. + /*
  15568. + * Try to be nice and not block/live-lock the workqueue: Run a maximum
  15569. + * of 10 tries, then re-submit if necessary. This should not be
  15570. + * necessary for normal execution, but guarantee it anyway.
  15571. + */
  15572. + for (i = 0; i < 10; i++) {
  15573. + status = ssh_rtl_tx_try_process_one(rtl);
  15574. + if (status == -ENOENT || status == -EBUSY)
  15575. + return; // no more requests to process
  15576. +
  15577. + if (status == -ESHUTDOWN) {
  15578. + /*
  15579. + * Packet system shutting down. No new packets can be
  15580. + * transmitted. Return silently, the party initiating
  15581. + * the shutdown should handle the rest.
  15582. + */
  15583. + return;
  15584. + }
  15585. +
  15586. + WARN_ON(status != 0 && status != -EAGAIN);
  15587. + }
  15588. +
  15589. + // out of tries, reschedule
  15590. + ssh_rtl_tx_schedule(rtl);
  15591. +}
  15592. +
  15593. +
  15594. +/**
  15595. + * ssh_rtl_submit() - Submit a request to the transport layer.
  15596. + * @rtl: The request transport layer.
  15597. + * @rqst: The request to submit.
  15598. + *
  15599. + * Submits a request to the transport layer. A single request may not be
  15600. + * submitted multiple times without reinitializing it.
  15601. + *
  15602. + * Return: Returns zero on success, %-EINVAL if the request type is invalid or
  15603. + * the request has been canceled prior to submission, %-EALREADY if the
  15604. + * request has already been submitted, or %-ESHUTDOWN in case the request
  15605. + * transport layer has been shut down.
  15606. + */
  15607. +int ssh_rtl_submit(struct ssh_rtl *rtl, struct ssh_request *rqst)
  15608. +{
  15609. + trace_ssam_request_submit(rqst);
  15610. +
  15611. + /*
  15612. + * Ensure that requests expecting a response are sequenced. If this
  15613. + * invariant ever changes, see the comment in ssh_rtl_complete() on what
  15614. + * is required to be changed in the code.
  15615. + */
  15616. + if (test_bit(SSH_REQUEST_TY_HAS_RESPONSE_BIT, &rqst->state))
  15617. + if (!test_bit(SSH_PACKET_TY_SEQUENCED_BIT, &rqst->packet.state))
  15618. + return -EINVAL;
  15619. +
  15620. + spin_lock(&rtl->queue.lock);
  15621. +
  15622. + /*
  15623. + * Try to set ptl and check if this request has already been submitted.
  15624. + *
  15625. + * Must be inside lock as we might run into a lost update problem
  15626. + * otherwise: If this were outside of the lock, cancellation in
  15627. + * ssh_rtl_cancel_nonpending() may run after we've set the ptl
  15628. + * reference but before we enter the lock. In that case, we'd detect
  15629. + * that the request is being added to the queue and would try to remove
  15630. + * it from that, but removal might fail because it hasn't actually been
  15631. + * added yet. By putting this cmpxchg in the critical section, we
  15632. + * ensure that the queuing detection only triggers when we are already
  15633. + * in the critical section and the remove process will wait until the
  15634. + * push operation has been completed (via lock) due to that. Only then,
  15635. + * we can safely try to remove it.
  15636. + */
  15637. + if (cmpxchg(&rqst->packet.ptl, NULL, &rtl->ptl) != NULL) {
  15638. + spin_unlock(&rtl->queue.lock);
  15639. + return -EALREADY;
  15640. + }
  15641. +
  15642. + /*
  15643. + * Ensure that we set ptl reference before we continue modifying state.
  15644. + * This is required for non-pending cancellation. This barrier is paired
  15645. + * with the one in ssh_rtl_cancel_nonpending().
  15646. + *
  15647. + * By setting the ptl reference before we test for "locked", we can
  15648. + * check if the "locked" test may have already run. See comments in
  15649. + * ssh_rtl_cancel_nonpending() for more detail.
  15650. + */
  15651. + smp_mb__after_atomic();
  15652. +
  15653. + if (test_bit(SSH_RTL_SF_SHUTDOWN_BIT, &rtl->state)) {
  15654. + spin_unlock(&rtl->queue.lock);
  15655. + return -ESHUTDOWN;
  15656. + }
  15657. +
  15658. + if (test_bit(SSH_REQUEST_SF_LOCKED_BIT, &rqst->state)) {
  15659. + spin_unlock(&rtl->queue.lock);
  15660. + return -EINVAL;
  15661. + }
  15662. +
  15663. + set_bit(SSH_REQUEST_SF_QUEUED_BIT, &rqst->state);
  15664. + list_add_tail(&ssh_request_get(rqst)->node, &rtl->queue.head);
  15665. +
  15666. + spin_unlock(&rtl->queue.lock);
  15667. +
  15668. + ssh_rtl_tx_schedule(rtl);
  15669. + return 0;
  15670. +}
  15671. +
  15672. +static void ssh_rtl_timeout_reaper_mod(struct ssh_rtl *rtl, ktime_t now,
  15673. + ktime_t expires)
  15674. +{
  15675. + unsigned long delta = msecs_to_jiffies(ktime_ms_delta(expires, now));
  15676. + ktime_t aexp = ktime_add(expires, SSH_RTL_REQUEST_TIMEOUT_RESOLUTION);
  15677. + ktime_t old_exp, old_act;
  15678. +
  15679. + // re-adjust / schedule reaper if it is above resolution delta
  15680. + old_act = READ_ONCE(rtl->rtx_timeout.expires);
  15681. + if (ktime_after(aexp, old_act))
  15682. + return;
  15683. +
  15684. + do {
  15685. + old_exp = old_act;
  15686. + old_act = cmpxchg64(&rtl->rtx_timeout.expires, old_exp, expires);
  15687. + } while (old_exp != old_act && ktime_before(aexp, old_act));
  15688. +
  15689. + // if we updated the reaper expiration, modify work timeout
  15690. + if (old_exp == old_act && old_act != expires)
  15691. + mod_delayed_work(system_wq, &rtl->rtx_timeout.reaper, delta);
  15692. +}
  15693. +
  15694. +static void ssh_rtl_timeout_start(struct ssh_request *rqst)
  15695. +{
  15696. + struct ssh_rtl *rtl = ssh_request_rtl(rqst);
  15697. + ktime_t timestamp = ktime_get_coarse_boottime();
  15698. + ktime_t timeout = rtl->rtx_timeout.timeout;
  15699. +
  15700. + if (test_bit(SSH_REQUEST_SF_LOCKED_BIT, &rqst->state))
  15701. + return;
  15702. +
  15703. + WRITE_ONCE(rqst->timestamp, timestamp);
  15704. + /*
  15705. + * Ensure timestamp is set before starting the reaper. Paired with
  15706. + * implicit barrier following check on ssh_request_get_expiration() in
  15707. + * ssh_rtl_timeout_reap.
  15708. + */
  15709. + smp_mb__after_atomic();
  15710. +
  15711. + ssh_rtl_timeout_reaper_mod(rtl, timestamp, timestamp + timeout);
  15712. +}
  15713. +
  15714. +
  15715. +static void ssh_rtl_complete(struct ssh_rtl *rtl,
  15716. + const struct ssh_command *command,
  15717. + const struct ssam_span *command_data)
  15718. +{
  15719. + struct ssh_request *r = NULL;
  15720. + struct ssh_request *p, *n;
  15721. + u16 rqid = get_unaligned_le16(&command->rqid);
  15722. +
  15723. + trace_ssam_rx_response_received(command, command_data->len);
  15724. +
  15725. + /*
  15726. + * Get request from pending based on request ID and mark it as response
  15727. + * received and locked.
  15728. + */
  15729. + spin_lock(&rtl->pending.lock);
  15730. + list_for_each_entry_safe(p, n, &rtl->pending.head, node) {
  15731. + // we generally expect requests to be processed in order
  15732. + if (unlikely(ssh_request_get_rqid(p) != rqid))
  15733. + continue;
  15734. +
  15735. + // simulate response timeout
  15736. + if (ssh_rtl_should_drop_response()) {
  15737. + spin_unlock(&rtl->pending.lock);
  15738. +
  15739. + trace_ssam_ei_rx_drop_response(p);
  15740. + rtl_info(rtl, "request error injection: dropping response for request %p\n",
  15741. + &p->packet);
  15742. + return;
  15743. + }
  15744. +
  15745. + /*
  15746. + * Mark as "response received" and "locked" as we're going to
  15747. + * complete it.
  15748. + */
  15749. + set_bit(SSH_REQUEST_SF_LOCKED_BIT, &p->state);
  15750. + set_bit(SSH_REQUEST_SF_RSPRCVD_BIT, &p->state);
  15751. + // ensure state never gets zero
  15752. + smp_mb__before_atomic();
  15753. + clear_bit(SSH_REQUEST_SF_PENDING_BIT, &p->state);
  15754. +
  15755. + atomic_dec(&rtl->pending.count);
  15756. + list_del(&p->node);
  15757. +
  15758. + r = p;
  15759. + break;
  15760. + }
  15761. + spin_unlock(&rtl->pending.lock);
  15762. +
  15763. + if (!r) {
  15764. + rtl_warn(rtl, "rtl: dropping unexpected command message (rqid = 0x%04x)\n",
  15765. + rqid);
  15766. + return;
  15767. + }
  15768. +
  15769. + // if the request hasn't been completed yet, we will do this now
  15770. + if (test_and_set_bit(SSH_REQUEST_SF_COMPLETED_BIT, &r->state)) {
  15771. + ssh_request_put(r);
  15772. + ssh_rtl_tx_schedule(rtl);
  15773. + return;
  15774. + }
  15775. +
  15776. + /*
  15777. + * Make sure the request has been transmitted. In case of a sequenced
  15778. + * request, we are guaranteed that the completion callback will run on
  15779. + * the receiver thread directly when the ACK for the packet has been
  15780. + * received. Similarly, this function is guaranteed to run on the
  15781. + * receiver thread. Thus we are guaranteed that if the packet has been
  15782. + * successfully transmitted and received an ACK, the transmitted flag
  15783. + * has been set and is visible here.
  15784. + *
  15785. + * We are currently not handling unsequenced packets here, as those
  15786. + * should never expect a response as ensured in ssh_rtl_submit. If this
  15787. + * ever changes, one would have to test for
  15788. + *
  15789. + * (r->state & (transmitting | transmitted))
  15790. + *
  15791. + * on unsequenced packets to determine if they could have been
  15792. + * transmitted. There are no synchronization guarantees as in the
  15793. + * sequenced case, since, in this case, the callback function will not
  15794. + * run on the same thread. Thus an exact determination is impossible.
  15795. + */
  15796. + if (!test_bit(SSH_REQUEST_SF_TRANSMITTED_BIT, &r->state)) {
  15797. + rtl_err(rtl, "rtl: received response before ACK for request (rqid = 0x%04x)\n",
  15798. + rqid);
  15799. +
  15800. + /*
  15801. + * NB: Timeout has already been canceled, request already been
  15802. + * removed from pending and marked as locked and completed. As
  15803. + * we receive a "false" response, the packet might still be
  15804. + * queued though.
  15805. + */
  15806. + ssh_rtl_queue_remove(r);
  15807. +
  15808. + ssh_rtl_complete_with_status(r, -EREMOTEIO);
  15809. + ssh_request_put(r);
  15810. +
  15811. + ssh_rtl_tx_schedule(rtl);
  15812. + return;
  15813. + }
  15814. +
  15815. + /*
  15816. + * NB: Timeout has already been canceled, request already been
  15817. + * removed from pending and marked as locked and completed. The request
  15818. + * can also not be queued any more, as it has been marked as
  15819. + * transmitting and later transmitted. Thus no need to remove it from
  15820. + * anywhere.
  15821. + */
  15822. +
  15823. + ssh_rtl_complete_with_rsp(r, command, command_data);
  15824. + ssh_request_put(r);
  15825. +
  15826. + ssh_rtl_tx_schedule(rtl);
  15827. +}
  15828. +
  15829. +
  15830. +static bool ssh_rtl_cancel_nonpending(struct ssh_request *r)
  15831. +{
  15832. + struct ssh_rtl *rtl;
  15833. + unsigned long flags, fixed;
  15834. + bool remove;
  15835. +
  15836. + /*
  15837. + * Handle unsubmitted request: Try to mark the packet as locked,
  15838. + * expecting the state to be zero (i.e. unsubmitted). Note that, if
  15839. + * setting the state worked, we might still be adding the packet to the
  15840. + * queue in a currently executing submit call. In that case, however,
  15841. + * ptl reference must have been set previously, as locked is checked
  15842. + * after setting ptl. Furthermore, when the ptl reference is set, the
  15843. + * submission process is guaranteed to have entered the critical
  15844. + * section. Thus only if we successfully locked this request and ptl is
  15845. + * NULL, we have successfully removed the request, i.e. we are
  15846. + * guaranteed that, due to the "locked" check in ssh_rtl_submit(), the
  15847. + * packet will never be added. Otherwise, we need to try and grab it
  15848. + * from the queue, where we are now guaranteed that the packet is or has
  15849. + * been due to the critical section.
  15850. + *
  15851. + * Note that if the CMPXCHG fails, we are guaranteed that ptl has
  15852. + * been set and is non-NULL, as states can only be nonzero after this
  15853. + * has been set. Also note that we need to fetch the static (type) flags
  15854. + * to ensure that they don't cause the cmpxchg to fail.
  15855. + */
  15856. + fixed = READ_ONCE(r->state) & SSH_REQUEST_FLAGS_TY_MASK;
  15857. + flags = cmpxchg(&r->state, fixed, SSH_REQUEST_SF_LOCKED_BIT);
  15858. +
  15859. + /*
  15860. + * Force correct ordering with regards to state and ptl reference access
  15861. + * to safe-guard cancellation to concurrent submission against a
  15862. + * lost-update problem. First try to exchange state, then also check
  15863. + * ptl if that worked. This barrier is paired with the
  15864. + * one in ssh_rtl_submit().
  15865. + */
  15866. + smp_mb__after_atomic();
  15867. +
  15868. + if (flags == fixed && !READ_ONCE(r->packet.ptl)) {
  15869. + if (test_and_set_bit(SSH_REQUEST_SF_COMPLETED_BIT, &r->state))
  15870. + return true;
  15871. +
  15872. + ssh_rtl_complete_with_status(r, -ECANCELED);
  15873. + return true;
  15874. + }
  15875. +
  15876. + rtl = ssh_request_rtl(r);
  15877. + spin_lock(&rtl->queue.lock);
  15878. +
  15879. + /*
  15880. + * Note: 1) Requests cannot be re-submitted. 2) If a request is queued,
  15881. + * it cannot be "transmitting"/"pending" yet. Thus, if we successfully
  15882. + * remove the request here, we have removed all its occurences in the
  15883. + * system.
  15884. + */
  15885. +
  15886. + remove = test_and_clear_bit(SSH_REQUEST_SF_QUEUED_BIT, &r->state);
  15887. + if (!remove) {
  15888. + spin_unlock(&rtl->queue.lock);
  15889. + return false;
  15890. + }
  15891. +
  15892. + set_bit(SSH_REQUEST_SF_LOCKED_BIT, &r->state);
  15893. + list_del(&r->node);
  15894. +
  15895. + spin_unlock(&rtl->queue.lock);
  15896. +
  15897. + ssh_request_put(r); // drop reference obtained from queue
  15898. +
  15899. + if (test_and_set_bit(SSH_REQUEST_SF_COMPLETED_BIT, &r->state))
  15900. + return true;
  15901. +
  15902. + ssh_rtl_complete_with_status(r, -ECANCELED);
  15903. + return true;
  15904. +}
  15905. +
  15906. +static bool ssh_rtl_cancel_pending(struct ssh_request *r)
  15907. +{
  15908. + // if the packet is already locked, it's going to be removed shortly
  15909. + if (test_and_set_bit(SSH_REQUEST_SF_LOCKED_BIT, &r->state))
  15910. + return true;
  15911. +
  15912. + /*
  15913. + * Now that we have locked the packet, we have guaranteed that it can't
  15914. + * be added to the system any more. If ptl is zero, the locked
  15915. + * check in ssh_rtl_submit() has not been run and any submission,
  15916. + * currently in progress or called later, won't add the packet. Thus we
  15917. + * can directly complete it.
  15918. + *
  15919. + * The implicit memory barrier of test_and_set_bit() should be enough
  15920. + * to ensure that the correct order (first lock, then check ptl) is
  15921. + * ensured. This is paired with the barrier in ssh_rtl_submit().
  15922. + */
  15923. + if (!READ_ONCE(r->packet.ptl)) {
  15924. + if (test_and_set_bit(SSH_REQUEST_SF_COMPLETED_BIT, &r->state))
  15925. + return true;
  15926. +
  15927. + ssh_rtl_complete_with_status(r, -ECANCELED);
  15928. + return true;
  15929. + }
  15930. +
  15931. + /*
  15932. + * Try to cancel the packet. If the packet has not been completed yet,
  15933. + * this will subsequently (and synchronously) call the completion
  15934. + * callback of the packet, which will complete the request.
  15935. + */
  15936. + ssh_ptl_cancel(&r->packet);
  15937. +
  15938. + /*
  15939. + * If the packet has been completed with success, i.e. has not been
  15940. + * canceled by the above call, the request may not have been completed
  15941. + * yet (may be waiting for a response). Check if we need to do this
  15942. + * here.
  15943. + */
  15944. + if (test_and_set_bit(SSH_REQUEST_SF_COMPLETED_BIT, &r->state))
  15945. + return true;
  15946. +
  15947. + ssh_rtl_queue_remove(r);
  15948. + ssh_rtl_pending_remove(r);
  15949. + ssh_rtl_complete_with_status(r, -ECANCELED);
  15950. +
  15951. + return true;
  15952. +}
  15953. +
  15954. +/**
  15955. + * ssh_rtl_cancel() - Cancel request.
  15956. + * @rqst: The request to cancel.
  15957. + * @pending: Whether to also cancel pending requests.
  15958. + *
  15959. + * Cancels the given request. If @pending is %false, this will not cancel
  15960. + * pending requests, i.e. requests that have already been submitted to the
  15961. + * packet layer but not been completed yet. If @pending is %true, this will
  15962. + * cancel the given request regardless of the state it is in.
  15963. + *
  15964. + * If the request has been canceled by calling this function, both completion
  15965. + * and release callbacks of the request will be executed in a reasonable
  15966. + * time-frame. This may happen during execution of this function, however,
  15967. + * there is no guarantee for this. For example, a request currently
  15968. + * transmitting will be canceled/completed only after transmission has
  15969. + * completed, and the respective callbacks will be executed on the transmitter
  15970. + * thread, which may happen during, but also some time after execution of the
  15971. + * cancel function.
  15972. + *
  15973. + * Return: Returns %true iff the given request has been canceled or completed,
  15974. + * either by this function or prior to calling this function, %false
  15975. + * otherwise. If @pending is %true, this function will always return %true.
  15976. + */
  15977. +bool ssh_rtl_cancel(struct ssh_request *rqst, bool pending)
  15978. +{
  15979. + struct ssh_rtl *rtl;
  15980. + bool canceled;
  15981. +
  15982. + if (test_and_set_bit(SSH_REQUEST_SF_CANCELED_BIT, &rqst->state))
  15983. + return true;
  15984. +
  15985. + trace_ssam_request_cancel(rqst);
  15986. +
  15987. + if (pending)
  15988. + canceled = ssh_rtl_cancel_pending(rqst);
  15989. + else
  15990. + canceled = ssh_rtl_cancel_nonpending(rqst);
  15991. +
  15992. + // note: rtl may be NULL if request has not been submitted yet
  15993. + rtl = ssh_request_rtl(rqst);
  15994. + if (canceled && rtl)
  15995. + ssh_rtl_tx_schedule(rtl);
  15996. +
  15997. + return canceled;
  15998. +}
  15999. +
  16000. +
  16001. +static void ssh_rtl_packet_callback(struct ssh_packet *p, int status)
  16002. +{
  16003. + struct ssh_request *r = to_ssh_request(p);
  16004. +
  16005. + if (unlikely(status)) {
  16006. + set_bit(SSH_REQUEST_SF_LOCKED_BIT, &r->state);
  16007. +
  16008. + if (test_and_set_bit(SSH_REQUEST_SF_COMPLETED_BIT, &r->state))
  16009. + return;
  16010. +
  16011. + /*
  16012. + * The packet may get cancelled even though it has not been
  16013. + * submitted yet. The request may still be queued. Check the
  16014. + * queue and remove it if necessary. As the timeout would have
  16015. + * been started in this function on success, there's no need to
  16016. + * cancel it here.
  16017. + */
  16018. + ssh_rtl_queue_remove(r);
  16019. + ssh_rtl_pending_remove(r);
  16020. + ssh_rtl_complete_with_status(r, status);
  16021. +
  16022. + ssh_rtl_tx_schedule(ssh_request_rtl(r));
  16023. + return;
  16024. + }
  16025. +
  16026. + // update state: mark as transmitted and clear transmitting
  16027. + set_bit(SSH_REQUEST_SF_TRANSMITTED_BIT, &r->state);
  16028. + // ensure state never gets zero
  16029. + smp_mb__before_atomic();
  16030. + clear_bit(SSH_REQUEST_SF_TRANSMITTING_BIT, &r->state);
  16031. +
  16032. + // if we expect a response, we just need to start the timeout
  16033. + if (test_bit(SSH_REQUEST_TY_HAS_RESPONSE_BIT, &r->state)) {
  16034. + ssh_rtl_timeout_start(r);
  16035. + return;
  16036. + }
  16037. +
  16038. + /*
  16039. + * If we don't expect a response, lock, remove, and complete the
  16040. + * request. Note that, at this point, the request is guaranteed to have
  16041. + * left the queue and no timeout has been started. Thus we only need to
  16042. + * remove it from pending. If the request has already been completed (it
  16043. + * may have been canceled) return.
  16044. + */
  16045. +
  16046. + set_bit(SSH_REQUEST_SF_LOCKED_BIT, &r->state);
  16047. + if (test_and_set_bit(SSH_REQUEST_SF_COMPLETED_BIT, &r->state))
  16048. + return;
  16049. +
  16050. + ssh_rtl_pending_remove(r);
  16051. + ssh_rtl_complete_with_status(r, 0);
  16052. +
  16053. + ssh_rtl_tx_schedule(ssh_request_rtl(r));
  16054. +}
  16055. +
  16056. +
  16057. +static ktime_t ssh_request_get_expiration(struct ssh_request *r, ktime_t timeout)
  16058. +{
  16059. + ktime_t timestamp = READ_ONCE(r->timestamp);
  16060. +
  16061. + if (timestamp != KTIME_MAX)
  16062. + return ktime_add(timestamp, timeout);
  16063. + else
  16064. + return KTIME_MAX;
  16065. +}
  16066. +
  16067. +static void ssh_rtl_timeout_reap(struct work_struct *work)
  16068. +{
  16069. + struct ssh_rtl *rtl = to_ssh_rtl(work, rtx_timeout.reaper.work);
  16070. + struct ssh_request *r, *n;
  16071. + LIST_HEAD(claimed);
  16072. + ktime_t now = ktime_get_coarse_boottime();
  16073. + ktime_t timeout = rtl->rtx_timeout.timeout;
  16074. + ktime_t next = KTIME_MAX;
  16075. +
  16076. + trace_ssam_rtl_timeout_reap("pending", atomic_read(&rtl->pending.count));
  16077. +
  16078. + /*
  16079. + * Mark reaper as "not pending". This is done before checking any
  16080. + * requests to avoid lost-update type problems.
  16081. + */
  16082. + WRITE_ONCE(rtl->rtx_timeout.expires, KTIME_MAX);
  16083. + /*
  16084. + * Ensure that the reaper is marked as deactivated before we continue
  16085. + * checking requests to prevent lost-update problems when a request is
  16086. + * added to the pending set and ssh_rtl_timeout_reaper_mod is called
  16087. + * during execution of the part below.
  16088. + */
  16089. + smp_mb__after_atomic();
  16090. +
  16091. + spin_lock(&rtl->pending.lock);
  16092. + list_for_each_entry_safe(r, n, &rtl->pending.head, node) {
  16093. + ktime_t expires = ssh_request_get_expiration(r, timeout);
  16094. +
  16095. + /*
  16096. + * Check if the timeout hasn't expired yet. Find out next
  16097. + * expiration date to be handled after this run.
  16098. + */
  16099. + if (ktime_after(expires, now)) {
  16100. + next = ktime_before(expires, next) ? expires : next;
  16101. + continue;
  16102. + }
  16103. +
  16104. + // avoid further transitions if locked
  16105. + if (test_and_set_bit(SSH_REQUEST_SF_LOCKED_BIT, &r->state))
  16106. + continue;
  16107. +
  16108. + /*
  16109. + * We have now marked the packet as locked. Thus it cannot be
  16110. + * added to the pending or queued lists again after we've
  16111. + * removed it here. We can therefore re-use the node of this
  16112. + * packet temporarily.
  16113. + */
  16114. +
  16115. + clear_bit(SSH_REQUEST_SF_PENDING_BIT, &r->state);
  16116. +
  16117. + atomic_dec(&rtl->pending.count);
  16118. + list_del(&r->node);
  16119. +
  16120. + list_add_tail(&r->node, &claimed);
  16121. + }
  16122. + spin_unlock(&rtl->pending.lock);
  16123. +
  16124. + // cancel and complete the request
  16125. + list_for_each_entry_safe(r, n, &claimed, node) {
  16126. + trace_ssam_request_timeout(r);
  16127. +
  16128. + /*
  16129. + * At this point we've removed the packet from pending. This
  16130. + * means that we've obtained the last (only) reference of the
  16131. + * system to it. Thus we can just complete it.
  16132. + */
  16133. + if (!test_and_set_bit(SSH_REQUEST_SF_COMPLETED_BIT, &r->state))
  16134. + ssh_rtl_complete_with_status(r, -ETIMEDOUT);
  16135. +
  16136. + // drop the reference we've obtained by removing it from pending
  16137. + list_del(&r->node);
  16138. + ssh_request_put(r);
  16139. + }
  16140. +
  16141. + // ensure that reaper doesn't run again immediately
  16142. + next = max(next, ktime_add(now, SSH_RTL_REQUEST_TIMEOUT_RESOLUTION));
  16143. + if (next != KTIME_MAX)
  16144. + ssh_rtl_timeout_reaper_mod(rtl, now, next);
  16145. +
  16146. + ssh_rtl_tx_schedule(rtl);
  16147. +}
  16148. +
  16149. +
  16150. +static void ssh_rtl_rx_event(struct ssh_rtl *rtl, const struct ssh_command *cmd,
  16151. + const struct ssam_span *data)
  16152. +{
  16153. + trace_ssam_rx_event_received(cmd, data->len);
  16154. +
  16155. + rtl_dbg(rtl, "rtl: handling event (rqid: 0x%04x)\n",
  16156. + get_unaligned_le16(&cmd->rqid));
  16157. +
  16158. + rtl->ops.handle_event(rtl, cmd, data);
  16159. +}
  16160. +
  16161. +static void ssh_rtl_rx_command(struct ssh_ptl *p, const struct ssam_span *data)
  16162. +{
  16163. + struct ssh_rtl *rtl = to_ssh_rtl(p, ptl);
  16164. + struct device *dev = &p->serdev->dev;
  16165. + struct ssh_command *command;
  16166. + struct ssam_span command_data;
  16167. +
  16168. + if (sshp_parse_command(dev, data, &command, &command_data))
  16169. + return;
  16170. +
  16171. + if (ssh_rqid_is_event(get_unaligned_le16(&command->rqid)))
  16172. + ssh_rtl_rx_event(rtl, command, &command_data);
  16173. + else
  16174. + ssh_rtl_complete(rtl, command, &command_data);
  16175. +}
  16176. +
  16177. +static void ssh_rtl_rx_data(struct ssh_ptl *p, const struct ssam_span *data)
  16178. +{
  16179. + if (!data->len) {
  16180. + ptl_err(p, "rtl: rx: no data frame payload\n");
  16181. + return;
  16182. + }
  16183. +
  16184. + switch (data->ptr[0]) {
  16185. + case SSH_PLD_TYPE_CMD:
  16186. + ssh_rtl_rx_command(p, data);
  16187. + break;
  16188. +
  16189. + default:
  16190. + ptl_err(p, "rtl: rx: unknown frame payload type (type: 0x%02x)\n",
  16191. + data->ptr[0]);
  16192. + break;
  16193. + }
  16194. +}
  16195. +
  16196. +
  16197. +static void ssh_rtl_packet_release(struct ssh_packet *p)
  16198. +{
  16199. + struct ssh_request *rqst;
  16200. +
  16201. + rqst = to_ssh_request(p);
  16202. + rqst->ops->release(rqst);
  16203. +}
  16204. +
  16205. +static const struct ssh_packet_ops ssh_rtl_packet_ops = {
  16206. + .complete = ssh_rtl_packet_callback,
  16207. + .release = ssh_rtl_packet_release,
  16208. +};
  16209. +
  16210. +/**
  16211. + * ssh_request_init() - Initialize SSH request.
  16212. + * @rqst: The request to initialize.
  16213. + * @flags: Request flags, determining the type of the request.
  16214. + * @ops: Request operations.
  16215. + *
  16216. + * Initializes the given SSH request and underlying packet. Sets the message
  16217. + * buffer pointer to %NULL and the message buffer length to zero. This buffer
  16218. + * has to be set separately via ssh_request_set_data() before submission and
  16219. + * must contain a valid SSH request message.
  16220. + */
  16221. +void ssh_request_init(struct ssh_request *rqst, enum ssam_request_flags flags,
  16222. + const struct ssh_request_ops *ops)
  16223. +{
  16224. + unsigned long type = BIT(SSH_PACKET_TY_BLOCKING_BIT);
  16225. +
  16226. + if (!(flags & SSAM_REQUEST_UNSEQUENCED))
  16227. + type |= BIT(SSH_PACKET_TY_SEQUENCED_BIT);
  16228. +
  16229. + ssh_packet_init(&rqst->packet, type, SSH_PACKET_PRIORITY(DATA, 0),
  16230. + &ssh_rtl_packet_ops);
  16231. +
  16232. + INIT_LIST_HEAD(&rqst->node);
  16233. +
  16234. + rqst->state = 0;
  16235. + if (flags & SSAM_REQUEST_HAS_RESPONSE)
  16236. + rqst->state |= BIT(SSH_REQUEST_TY_HAS_RESPONSE_BIT);
  16237. +
  16238. + rqst->timestamp = KTIME_MAX;
  16239. + rqst->ops = ops;
  16240. +}
  16241. +
  16242. +
  16243. +/**
  16244. + * ssh_rtl_init() - Initialize request transport layer.
  16245. + * @rtl: The request transport layer to initialize.
  16246. + * @serdev: The underlying serial device, i.e. the lower-level transport.
  16247. + * @ops: Request transport layer operations.
  16248. + *
  16249. + * Initializes the given request transport layer and associated packet
  16250. + * transport layer. Transmitter and receiver threads must be started
  16251. + * separately via ssh_rtl_tx_start() and ssh_rtl_rx_start(), after the
  16252. + * request-layer has been initialized and the lower-level serial device layer
  16253. + * has been set up.
  16254. + *
  16255. + * Return: Returns zero on success and a nonzero error code on failure.
  16256. + */
  16257. +int ssh_rtl_init(struct ssh_rtl *rtl, struct serdev_device *serdev,
  16258. + const struct ssh_rtl_ops *ops)
  16259. +{
  16260. + struct ssh_ptl_ops ptl_ops;
  16261. + int status;
  16262. +
  16263. + ptl_ops.data_received = ssh_rtl_rx_data;
  16264. +
  16265. + status = ssh_ptl_init(&rtl->ptl, serdev, &ptl_ops);
  16266. + if (status)
  16267. + return status;
  16268. +
  16269. + spin_lock_init(&rtl->queue.lock);
  16270. + INIT_LIST_HEAD(&rtl->queue.head);
  16271. +
  16272. + spin_lock_init(&rtl->pending.lock);
  16273. + INIT_LIST_HEAD(&rtl->pending.head);
  16274. + atomic_set_release(&rtl->pending.count, 0);
  16275. +
  16276. + INIT_WORK(&rtl->tx.work, ssh_rtl_tx_work_fn);
  16277. +
  16278. + rtl->rtx_timeout.timeout = SSH_RTL_REQUEST_TIMEOUT;
  16279. + rtl->rtx_timeout.expires = KTIME_MAX;
  16280. + INIT_DELAYED_WORK(&rtl->rtx_timeout.reaper, ssh_rtl_timeout_reap);
  16281. +
  16282. + rtl->ops = *ops;
  16283. +
  16284. + return 0;
  16285. +}
  16286. +
  16287. +/**
  16288. + * ssh_rtl_destroy() - Deinitialize request transport layer.
  16289. + * @rtl: The request transport layer to deinitialize.
  16290. + *
  16291. + * Deinitializes the given request transport layer and frees resources
  16292. + * associated with it. If receiver and/or transmitter threads have been
  16293. + * started, the layer must first be shut down via ssh_rtl_shutdown() before
  16294. + * this function can be called.
  16295. + */
  16296. +void ssh_rtl_destroy(struct ssh_rtl *rtl)
  16297. +{
  16298. + ssh_ptl_destroy(&rtl->ptl);
  16299. +}
  16300. +
  16301. +/**
  16302. + * ssh_rtl_tx_start() - Start request transmitter and receiver.
  16303. + * @rtl: The request transport layer.
  16304. + *
  16305. + * Return: Returns zero on success, a negative error code on failure.
  16306. + */
  16307. +int ssh_rtl_start(struct ssh_rtl *rtl)
  16308. +{
  16309. + int status;
  16310. +
  16311. + status = ssh_ptl_tx_start(&rtl->ptl);
  16312. + if (status)
  16313. + return status;
  16314. +
  16315. + ssh_rtl_tx_schedule(rtl);
  16316. +
  16317. + status = ssh_ptl_rx_start(&rtl->ptl);
  16318. + if (status) {
  16319. + ssh_rtl_flush(rtl, msecs_to_jiffies(5000));
  16320. + ssh_ptl_tx_stop(&rtl->ptl);
  16321. + return status;
  16322. + }
  16323. +
  16324. + return 0;
  16325. +}
  16326. +
  16327. +struct ssh_flush_request {
  16328. + struct ssh_request base;
  16329. + struct completion completion;
  16330. + int status;
  16331. +};
  16332. +
  16333. +static void ssh_rtl_flush_request_complete(struct ssh_request *r,
  16334. + const struct ssh_command *cmd,
  16335. + const struct ssam_span *data,
  16336. + int status)
  16337. +{
  16338. + struct ssh_flush_request *rqst;
  16339. +
  16340. + rqst = container_of(r, struct ssh_flush_request, base);
  16341. + rqst->status = status;
  16342. +}
  16343. +
  16344. +static void ssh_rtl_flush_request_release(struct ssh_request *r)
  16345. +{
  16346. + struct ssh_flush_request *rqst;
  16347. +
  16348. + rqst = container_of(r, struct ssh_flush_request, base);
  16349. + complete_all(&rqst->completion);
  16350. +}
  16351. +
  16352. +static const struct ssh_request_ops ssh_rtl_flush_request_ops = {
  16353. + .complete = ssh_rtl_flush_request_complete,
  16354. + .release = ssh_rtl_flush_request_release,
  16355. +};
  16356. +
  16357. +/**
  16358. + * ssh_rtl_flush() - Flush the request transport layer.
  16359. + * @rtl: request transport layer
  16360. + * @timeout: timeout for the flush operation in jiffies
  16361. + *
  16362. + * Queue a special flush request and wait for its completion. This request
  16363. + * will be completed after all other currently queued and pending requests
  16364. + * have been completed. Instead of a normal data packet, this request submits
  16365. + * a special flush packet, meaning that upon completion, also the underlying
  16366. + * packet transport layer has been flushed.
  16367. + *
  16368. + * Flushing the request layer gurarantees that all previously submitted
  16369. + * requests have been fully completed before this call returns. Additinally,
  16370. + * flushing blocks execution of all later submitted requests until the flush
  16371. + * has been completed.
  16372. + *
  16373. + * If the caller ensures that no new requests are submitted after a call to
  16374. + * this function, the request transport layer is guaranteed to have no
  16375. + * remaining requests when this call returns. The same guarantee does not hold
  16376. + * for the packet layer, on which control packets may still be queued after
  16377. + * this call.
  16378. + *
  16379. + * Return: Returns zero on success, %-ETIMEDOUT if the flush timed out and has
  16380. + * been canceled as a result of the timeout, or %-ESHUTDOWN if the packet
  16381. + * and/or request transport layer has been shut down before this call. May
  16382. + * also return %-EINTR if the underlying packet transmission has been
  16383. + * interrupted.
  16384. + */
  16385. +int ssh_rtl_flush(struct ssh_rtl *rtl, unsigned long timeout)
  16386. +{
  16387. + const unsigned int init_flags = SSAM_REQUEST_UNSEQUENCED;
  16388. + struct ssh_flush_request rqst;
  16389. + int status;
  16390. +
  16391. + ssh_request_init(&rqst.base, init_flags, &ssh_rtl_flush_request_ops);
  16392. + rqst.base.packet.state |= BIT(SSH_PACKET_TY_FLUSH_BIT);
  16393. + rqst.base.packet.priority = SSH_PACKET_PRIORITY(FLUSH, 0);
  16394. + rqst.base.state |= BIT(SSH_REQUEST_TY_FLUSH_BIT);
  16395. +
  16396. + init_completion(&rqst.completion);
  16397. +
  16398. + status = ssh_rtl_submit(rtl, &rqst.base);
  16399. + if (status)
  16400. + return status;
  16401. +
  16402. + ssh_request_put(&rqst.base);
  16403. +
  16404. + if (!wait_for_completion_timeout(&rqst.completion, timeout)) {
  16405. + ssh_rtl_cancel(&rqst.base, true);
  16406. + wait_for_completion(&rqst.completion);
  16407. + }
  16408. +
  16409. + WARN_ON(rqst.status != 0 && rqst.status != -ECANCELED
  16410. + && rqst.status != -ESHUTDOWN && rqst.status != -EINTR);
  16411. +
  16412. + return rqst.status == -ECANCELED ? -ETIMEDOUT : rqst.status;
  16413. +}
  16414. +
  16415. +
  16416. +/**
  16417. + * ssh_rtl_shutdown() - Shut down request transport layer.
  16418. + * @rtl: The request transport layer.
  16419. + *
  16420. + * Shuts down the request transport layer, removing and canceling all queued
  16421. + * and pending requests. Requests canceled by this operation will be completed
  16422. + * with %-ESHUTDOWN as status. Receiver and transmitter threads will be
  16423. + * stopped, the lower-level packet layer will be shutdown.
  16424. + *
  16425. + * As a result of this function, the transport layer will be marked as shut
  16426. + * down. Submission of requests after the transport layer has been shut down
  16427. + * will fail with %-ESHUTDOWN.
  16428. + */
  16429. +void ssh_rtl_shutdown(struct ssh_rtl *rtl)
  16430. +{
  16431. + struct ssh_request *r, *n;
  16432. + LIST_HEAD(claimed);
  16433. + int pending;
  16434. +
  16435. + set_bit(SSH_RTL_SF_SHUTDOWN_BIT, &rtl->state);
  16436. + /*
  16437. + * Ensure that the layer gets marked as shut-down before actually
  16438. + * stopping it. In combination with the check in ssh_rtl_sunmit(), this
  16439. + * guarantees that no new requests can be added and all already queued
  16440. + * requests are properly cancelled.
  16441. + */
  16442. + smp_mb__after_atomic();
  16443. +
  16444. + // remove requests from queue
  16445. + spin_lock(&rtl->queue.lock);
  16446. + list_for_each_entry_safe(r, n, &rtl->queue.head, node) {
  16447. + set_bit(SSH_REQUEST_SF_LOCKED_BIT, &r->state);
  16448. + // ensure state never gets zero
  16449. + smp_mb__before_atomic();
  16450. + clear_bit(SSH_REQUEST_SF_QUEUED_BIT, &r->state);
  16451. +
  16452. + list_del(&r->node);
  16453. + list_add_tail(&r->node, &claimed);
  16454. + }
  16455. + spin_unlock(&rtl->queue.lock);
  16456. +
  16457. + /*
  16458. + * We have now guaranteed that the queue is empty and no more new
  16459. + * requests can be submitted (i.e. it will stay empty). This means that
  16460. + * calling ssh_rtl_tx_schedule() will not schedule tx.work any more. So
  16461. + * we can simply call cancel_work_sync() on tx.work here and when that
  16462. + * returns, we've locked it down. This also means that after this call,
  16463. + * we don't submit any more packets to the underlying packet layer, so
  16464. + * we can also shut that down.
  16465. + */
  16466. +
  16467. + cancel_work_sync(&rtl->tx.work);
  16468. + ssh_ptl_shutdown(&rtl->ptl);
  16469. + cancel_delayed_work_sync(&rtl->rtx_timeout.reaper);
  16470. +
  16471. + /*
  16472. + * Shutting down the packet layer should also have caneled all requests.
  16473. + * Thus the pending set should be empty. Attempt to handle this
  16474. + * gracefully anyways, even though this should be dead code.
  16475. + */
  16476. +
  16477. + pending = atomic_read(&rtl->pending.count);
  16478. + if (WARN_ON(pending)) {
  16479. + spin_lock(&rtl->pending.lock);
  16480. + list_for_each_entry_safe(r, n, &rtl->pending.head, node) {
  16481. + set_bit(SSH_REQUEST_SF_LOCKED_BIT, &r->state);
  16482. + // ensure state never gets zero
  16483. + smp_mb__before_atomic();
  16484. + clear_bit(SSH_REQUEST_SF_PENDING_BIT, &r->state);
  16485. +
  16486. + list_del(&r->node);
  16487. + list_add_tail(&r->node, &claimed);
  16488. + }
  16489. + spin_unlock(&rtl->pending.lock);
  16490. + }
  16491. +
  16492. + // finally, cancel and complete the requests we claimed before
  16493. + list_for_each_entry_safe(r, n, &claimed, node) {
  16494. + // test_and_set because we still might compete with cancellation
  16495. + if (!test_and_set_bit(SSH_REQUEST_SF_COMPLETED_BIT, &r->state))
  16496. + ssh_rtl_complete_with_status(r, -ESHUTDOWN);
  16497. +
  16498. + // drop reference we've obtained by removing it from the lists
  16499. + list_del(&r->node);
  16500. + ssh_request_put(r);
  16501. + }
  16502. +}
  16503. diff --git a/drivers/misc/surface_aggregator/ssh_request_layer.h b/drivers/misc/surface_aggregator/ssh_request_layer.h
  16504. new file mode 100644
  16505. index 000000000000..e945e0532628
  16506. --- /dev/null
  16507. +++ b/drivers/misc/surface_aggregator/ssh_request_layer.h
  16508. @@ -0,0 +1,142 @@
  16509. +/* SPDX-License-Identifier: GPL-2.0+ */
  16510. +/*
  16511. + * SSH request transport layer.
  16512. + *
  16513. + * Copyright (C) 2019-2020 Maximilian Luz <luzmaximilian@gmail.com>
  16514. + */
  16515. +
  16516. +#ifndef _SURFACE_AGGREGATOR_SSH_REQUEST_LAYER_H
  16517. +#define _SURFACE_AGGREGATOR_SSH_REQUEST_LAYER_H
  16518. +
  16519. +#include <linux/atomic.h>
  16520. +#include <linux/ktime.h>
  16521. +#include <linux/list.h>
  16522. +#include <linux/spinlock.h>
  16523. +#include <linux/workqueue.h>
  16524. +
  16525. +#include <linux/surface_aggregator/serial_hub.h>
  16526. +#include <linux/surface_aggregator/controller.h>
  16527. +
  16528. +#include "ssh_packet_layer.h"
  16529. +
  16530. +
  16531. +/**
  16532. + * enum ssh_rtl_state_flags - State-flags for &struct ssh_rtl.
  16533. + *
  16534. + * @SSH_RTL_SF_SHUTDOWN_BIT:
  16535. + * Indicates that the request transport layer has been shut down or is
  16536. + * being shut down and should not accept any new requests.
  16537. + */
  16538. +enum ssh_rtl_state_flags {
  16539. + SSH_RTL_SF_SHUTDOWN_BIT,
  16540. +};
  16541. +
  16542. +/**
  16543. + * struct ssh_rtl_ops - Callback operations for request transport layer.
  16544. + * @handle_event: Function called when a SSH event has been received. The
  16545. + * specified function takes the request layer, received command
  16546. + * struct, and corresponding payload as arguments. If the event
  16547. + * has no payload, the payload span is empty (not %NULL).
  16548. + */
  16549. +struct ssh_rtl_ops {
  16550. + void (*handle_event)(struct ssh_rtl *rtl, const struct ssh_command *cmd,
  16551. + const struct ssam_span *data);
  16552. +};
  16553. +
  16554. +/**
  16555. + * struct ssh_rtl - SSH request transport layer.
  16556. + * @ptl: Underlying packet transport layer.
  16557. + * @state: State(-flags) of the transport layer.
  16558. + * @queue: Request submission queue.
  16559. + * @queue.lock: Lock for modifying the request submission queue.
  16560. + * @queue.head: List-head of the request submission queue.
  16561. + * @pending: Set/list of pending requests.
  16562. + * @pending.lock: Lock for modifying the request set.
  16563. + * @pending.head: List-head of the pending set/list.
  16564. + * @pending.count: Number of currently pending requests.
  16565. + * @tx: Transmitter subsystem.
  16566. + * @tx.work: Transmitter work item.
  16567. + * @rtx_timeout: Retransmission timeout subsystem.
  16568. + * @rtx_timeout.timeout: Timeout inverval for retransmission.
  16569. + * @rtx_timeout.expires: Time specifying when the reaper work is next scheduled.
  16570. + * @rtx_timeout.reaper: Work performing timeout checks and subsequent actions.
  16571. + * @ops: Request layer operations.
  16572. + */
  16573. +struct ssh_rtl {
  16574. + struct ssh_ptl ptl;
  16575. + unsigned long state;
  16576. +
  16577. + struct {
  16578. + spinlock_t lock;
  16579. + struct list_head head;
  16580. + } queue;
  16581. +
  16582. + struct {
  16583. + spinlock_t lock;
  16584. + struct list_head head;
  16585. + atomic_t count;
  16586. + } pending;
  16587. +
  16588. + struct {
  16589. + struct work_struct work;
  16590. + } tx;
  16591. +
  16592. + struct {
  16593. + ktime_t timeout;
  16594. + ktime_t expires;
  16595. + struct delayed_work reaper;
  16596. + } rtx_timeout;
  16597. +
  16598. + struct ssh_rtl_ops ops;
  16599. +};
  16600. +
  16601. +#define rtl_dbg(r, fmt, ...) ptl_dbg(&(r)->ptl, fmt, ##__VA_ARGS__)
  16602. +#define rtl_info(p, fmt, ...) ptl_info(&(p)->ptl, fmt, ##__VA_ARGS__)
  16603. +#define rtl_warn(r, fmt, ...) ptl_warn(&(r)->ptl, fmt, ##__VA_ARGS__)
  16604. +#define rtl_err(r, fmt, ...) ptl_err(&(r)->ptl, fmt, ##__VA_ARGS__)
  16605. +#define rtl_dbg_cond(r, fmt, ...) __ssam_prcond(rtl_dbg, r, fmt, ##__VA_ARGS__)
  16606. +
  16607. +#define to_ssh_rtl(ptr, member) \
  16608. + container_of(ptr, struct ssh_rtl, member)
  16609. +
  16610. +/**
  16611. + * ssh_rtl_get_device() - Get device associated with request transport layer.
  16612. + * @rtl: The request transport layer.
  16613. + *
  16614. + * Return: Returns the device on which the given request transport layer
  16615. + * builds upon.
  16616. + */
  16617. +static inline struct device *ssh_rtl_get_device(struct ssh_rtl *rtl)
  16618. +{
  16619. + return ssh_ptl_get_device(&rtl->ptl);
  16620. +}
  16621. +
  16622. +/**
  16623. + * ssh_request_rtl() - Get request transport layer associated with request.
  16624. + * @rqst: The request to get the request transport layer reference for.
  16625. + *
  16626. + * Return: Returns the &struct ssh_rtl associated with the given SSH request.
  16627. + */
  16628. +static inline struct ssh_rtl *ssh_request_rtl(struct ssh_request *rqst)
  16629. +{
  16630. + struct ssh_ptl *ptl;
  16631. +
  16632. + ptl = READ_ONCE(rqst->packet.ptl);
  16633. + return likely(ptl) ? to_ssh_rtl(ptl, ptl) : NULL;
  16634. +}
  16635. +
  16636. +int ssh_rtl_submit(struct ssh_rtl *rtl, struct ssh_request *rqst);
  16637. +bool ssh_rtl_cancel(struct ssh_request *rqst, bool pending);
  16638. +
  16639. +int ssh_rtl_init(struct ssh_rtl *rtl, struct serdev_device *serdev,
  16640. + const struct ssh_rtl_ops *ops);
  16641. +
  16642. +int ssh_rtl_start(struct ssh_rtl *rtl);
  16643. +int ssh_rtl_flush(struct ssh_rtl *rtl, unsigned long timeout);
  16644. +void ssh_rtl_shutdown(struct ssh_rtl *rtl);
  16645. +void ssh_rtl_destroy(struct ssh_rtl *rtl);
  16646. +
  16647. +void ssh_request_init(struct ssh_request *rqst, enum ssam_request_flags flags,
  16648. + const struct ssh_request_ops *ops);
  16649. +
  16650. +#endif /* _SURFACE_AGGREGATOR_SSH_REQUEST_LAYER_H */
  16651. diff --git a/drivers/misc/surface_aggregator/trace.h b/drivers/misc/surface_aggregator/trace.h
  16652. new file mode 100644
  16653. index 000000000000..232bf1142aae
  16654. --- /dev/null
  16655. +++ b/drivers/misc/surface_aggregator/trace.h
  16656. @@ -0,0 +1,625 @@
  16657. +/* SPDX-License-Identifier: GPL-2.0+ */
  16658. +/*
  16659. + * Trace points for SSAM/SSH.
  16660. + *
  16661. + * Copyright (C) 2020 Maximilian Luz <luzmaximilian@gmail.com>
  16662. + */
  16663. +
  16664. +#undef TRACE_SYSTEM
  16665. +#define TRACE_SYSTEM surface_aggregator
  16666. +
  16667. +#if !defined(_SURFACE_AGGREGATOR_TRACE_H) || defined(TRACE_HEADER_MULTI_READ)
  16668. +#define _SURFACE_AGGREGATOR_TRACE_H
  16669. +
  16670. +#include <linux/surface_aggregator/serial_hub.h>
  16671. +
  16672. +#include <asm/unaligned.h>
  16673. +#include <linux/tracepoint.h>
  16674. +
  16675. +
  16676. +TRACE_DEFINE_ENUM(SSH_FRAME_TYPE_DATA_SEQ);
  16677. +TRACE_DEFINE_ENUM(SSH_FRAME_TYPE_DATA_NSQ);
  16678. +TRACE_DEFINE_ENUM(SSH_FRAME_TYPE_ACK);
  16679. +TRACE_DEFINE_ENUM(SSH_FRAME_TYPE_NAK);
  16680. +
  16681. +TRACE_DEFINE_ENUM(SSH_PACKET_SF_LOCKED_BIT);
  16682. +TRACE_DEFINE_ENUM(SSH_PACKET_SF_QUEUED_BIT);
  16683. +TRACE_DEFINE_ENUM(SSH_PACKET_SF_PENDING_BIT);
  16684. +TRACE_DEFINE_ENUM(SSH_PACKET_SF_TRANSMITTING_BIT);
  16685. +TRACE_DEFINE_ENUM(SSH_PACKET_SF_TRANSMITTED_BIT);
  16686. +TRACE_DEFINE_ENUM(SSH_PACKET_SF_ACKED_BIT);
  16687. +TRACE_DEFINE_ENUM(SSH_PACKET_SF_CANCELED_BIT);
  16688. +TRACE_DEFINE_ENUM(SSH_PACKET_SF_COMPLETED_BIT);
  16689. +
  16690. +TRACE_DEFINE_ENUM(SSH_PACKET_TY_FLUSH_BIT);
  16691. +TRACE_DEFINE_ENUM(SSH_PACKET_TY_SEQUENCED_BIT);
  16692. +TRACE_DEFINE_ENUM(SSH_PACKET_TY_BLOCKING_BIT);
  16693. +
  16694. +TRACE_DEFINE_ENUM(SSH_PACKET_FLAGS_SF_MASK);
  16695. +TRACE_DEFINE_ENUM(SSH_PACKET_FLAGS_TY_MASK);
  16696. +
  16697. +TRACE_DEFINE_ENUM(SSH_REQUEST_SF_LOCKED_BIT);
  16698. +TRACE_DEFINE_ENUM(SSH_REQUEST_SF_QUEUED_BIT);
  16699. +TRACE_DEFINE_ENUM(SSH_REQUEST_SF_PENDING_BIT);
  16700. +TRACE_DEFINE_ENUM(SSH_REQUEST_SF_TRANSMITTING_BIT);
  16701. +TRACE_DEFINE_ENUM(SSH_REQUEST_SF_TRANSMITTED_BIT);
  16702. +TRACE_DEFINE_ENUM(SSH_REQUEST_SF_RSPRCVD_BIT);
  16703. +TRACE_DEFINE_ENUM(SSH_REQUEST_SF_CANCELED_BIT);
  16704. +TRACE_DEFINE_ENUM(SSH_REQUEST_SF_COMPLETED_BIT);
  16705. +
  16706. +TRACE_DEFINE_ENUM(SSH_REQUEST_TY_FLUSH_BIT);
  16707. +TRACE_DEFINE_ENUM(SSH_REQUEST_TY_HAS_RESPONSE_BIT);
  16708. +
  16709. +TRACE_DEFINE_ENUM(SSH_REQUEST_FLAGS_SF_MASK);
  16710. +TRACE_DEFINE_ENUM(SSH_REQUEST_FLAGS_TY_MASK);
  16711. +
  16712. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_SAM);
  16713. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_BAT);
  16714. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_TMP);
  16715. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_PMC);
  16716. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_FAN);
  16717. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_PoM);
  16718. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_DBG);
  16719. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_KBD);
  16720. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_FWU);
  16721. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_UNI);
  16722. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_LPC);
  16723. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_TCL);
  16724. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_SFL);
  16725. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_KIP);
  16726. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_EXT);
  16727. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_BLD);
  16728. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_BAS);
  16729. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_SEN);
  16730. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_SRQ);
  16731. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_MCU);
  16732. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_HID);
  16733. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_TCH);
  16734. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_BKL);
  16735. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_TAM);
  16736. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_ACC);
  16737. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_UFI);
  16738. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_USC);
  16739. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_PEN);
  16740. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_VID);
  16741. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_AUD);
  16742. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_SMC);
  16743. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_KPD);
  16744. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_REG);
  16745. +
  16746. +
  16747. +#define SSAM_PTR_UID_LEN 9
  16748. +#define SSAM_U8_FIELD_NOT_APPLICABLE ((u16)-1)
  16749. +#define SSAM_SEQ_NOT_APPLICABLE ((u16)-1)
  16750. +#define SSAM_RQID_NOT_APPLICABLE ((u32)-1)
  16751. +#define SSAM_SSH_TC_NOT_APPLICABLE 0
  16752. +
  16753. +
  16754. +#ifndef _SURFACE_AGGREGATOR_TRACE_HELPERS
  16755. +#define _SURFACE_AGGREGATOR_TRACE_HELPERS
  16756. +
  16757. +/**
  16758. + * ssam_trace_ptr_uid() - Convert the pointer to a non-pointer UID string.
  16759. + * @ptr: The pointer to convert.
  16760. + * @uid_str: A buffer of length SSAM_PTR_UID_LEN where the UID will be stored.
  16761. + *
  16762. + * Converts the given pointer into a UID string that is safe to be shared
  16763. + * with userspace and logs, i.e. doesn't give away the real memory location.
  16764. + */
  16765. +static inline void ssam_trace_ptr_uid(const void *ptr, char *uid_str)
  16766. +{
  16767. + char buf[2 * sizeof(void *) + 1];
  16768. +
  16769. + snprintf(buf, ARRAY_SIZE(buf), "%p", ptr);
  16770. + memcpy(uid_str, &buf[ARRAY_SIZE(buf) - SSAM_PTR_UID_LEN],
  16771. + SSAM_PTR_UID_LEN);
  16772. +}
  16773. +
  16774. +/**
  16775. + * ssam_trace_get_packet_seq() - Read the packet's sequence ID.
  16776. + * @p: The packet.
  16777. + *
  16778. + * Return: Returns the packet's sequence ID (SEQ) field if present, or
  16779. + * %SSAM_SEQ_NOT_APPLICABLE if not (e.g. flush packet).
  16780. + */
  16781. +static inline u16 ssam_trace_get_packet_seq(const struct ssh_packet *p)
  16782. +{
  16783. + if (!p->data.ptr || p->data.len < SSH_MESSAGE_LENGTH(0))
  16784. + return SSAM_SEQ_NOT_APPLICABLE;
  16785. +
  16786. + return p->data.ptr[SSH_MSGOFFSET_FRAME(seq)];
  16787. +}
  16788. +
  16789. +/**
  16790. + * ssam_trace_get_request_id() - Read the packet's request ID.
  16791. + * @p: The packet.
  16792. + *
  16793. + * Return: Returns the packet's request ID (RQID) field if the packet
  16794. + * represents a request with command data, or %SSAM_RQID_NOT_APPLICABLE if not
  16795. + * (e.g. flush request, control packet).
  16796. + */
  16797. +static inline u32 ssam_trace_get_request_id(const struct ssh_packet *p)
  16798. +{
  16799. + if (!p->data.ptr || p->data.len < SSH_COMMAND_MESSAGE_LENGTH(0))
  16800. + return SSAM_RQID_NOT_APPLICABLE;
  16801. +
  16802. + return get_unaligned_le16(&p->data.ptr[SSH_MSGOFFSET_COMMAND(rqid)]);
  16803. +}
  16804. +
  16805. +/**
  16806. + * ssam_trace_get_request_tc() - Read the packet's request target category.
  16807. + * @p: The packet.
  16808. + *
  16809. + * Return: Returns the packet's request target category (TC) field if the
  16810. + * packet represents a request with command data, or %SSAM_TC_NOT_APPLICABLE
  16811. + * if not (e.g. flush request, control packet).
  16812. + */
  16813. +static inline u32 ssam_trace_get_request_tc(const struct ssh_packet *p)
  16814. +{
  16815. + if (!p->data.ptr || p->data.len < SSH_COMMAND_MESSAGE_LENGTH(0))
  16816. + return SSAM_SSH_TC_NOT_APPLICABLE;
  16817. +
  16818. + return get_unaligned_le16(&p->data.ptr[SSH_MSGOFFSET_COMMAND(tc)]);
  16819. +}
  16820. +
  16821. +#endif /* _SURFACE_AGGREGATOR_TRACE_HELPERS */
  16822. +
  16823. +#define ssam_trace_get_command_field_u8(packet, field) \
  16824. + ((!packet || packet->data.len < SSH_COMMAND_MESSAGE_LENGTH(0)) \
  16825. + ? 0 : p->data.ptr[SSH_MSGOFFSET_COMMAND(field)])
  16826. +
  16827. +#define ssam_show_generic_u8_field(value) \
  16828. + __print_symbolic(value, \
  16829. + { SSAM_U8_FIELD_NOT_APPLICABLE, "N/A" } \
  16830. + )
  16831. +
  16832. +
  16833. +#define ssam_show_frame_type(ty) \
  16834. + __print_symbolic(ty, \
  16835. + { SSH_FRAME_TYPE_DATA_SEQ, "DSEQ" }, \
  16836. + { SSH_FRAME_TYPE_DATA_NSQ, "DNSQ" }, \
  16837. + { SSH_FRAME_TYPE_ACK, "ACK" }, \
  16838. + { SSH_FRAME_TYPE_NAK, "NAK" } \
  16839. + )
  16840. +
  16841. +#define ssam_show_packet_type(type) \
  16842. + __print_flags(flags & SSH_PACKET_FLAGS_TY_MASK, "", \
  16843. + { BIT(SSH_PACKET_TY_FLUSH_BIT), "F" }, \
  16844. + { BIT(SSH_PACKET_TY_SEQUENCED_BIT), "S" }, \
  16845. + { BIT(SSH_PACKET_TY_BLOCKING_BIT), "B" } \
  16846. + )
  16847. +
  16848. +#define ssam_show_packet_state(state) \
  16849. + __print_flags(flags & SSH_PACKET_FLAGS_SF_MASK, "", \
  16850. + { BIT(SSH_PACKET_SF_LOCKED_BIT), "L" }, \
  16851. + { BIT(SSH_PACKET_SF_QUEUED_BIT), "Q" }, \
  16852. + { BIT(SSH_PACKET_SF_PENDING_BIT), "P" }, \
  16853. + { BIT(SSH_PACKET_SF_TRANSMITTING_BIT), "S" }, \
  16854. + { BIT(SSH_PACKET_SF_TRANSMITTED_BIT), "T" }, \
  16855. + { BIT(SSH_PACKET_SF_ACKED_BIT), "A" }, \
  16856. + { BIT(SSH_PACKET_SF_CANCELED_BIT), "C" }, \
  16857. + { BIT(SSH_PACKET_SF_COMPLETED_BIT), "F" } \
  16858. + )
  16859. +
  16860. +#define ssam_show_packet_seq(seq) \
  16861. + __print_symbolic(seq, \
  16862. + { SSAM_SEQ_NOT_APPLICABLE, "N/A" } \
  16863. + )
  16864. +
  16865. +
  16866. +#define ssam_show_request_type(flags) \
  16867. + __print_flags(flags & SSH_REQUEST_FLAGS_TY_MASK, "", \
  16868. + { BIT(SSH_REQUEST_TY_FLUSH_BIT), "F" }, \
  16869. + { BIT(SSH_REQUEST_TY_HAS_RESPONSE_BIT), "R" } \
  16870. + )
  16871. +
  16872. +#define ssam_show_request_state(flags) \
  16873. + __print_flags(flags & SSH_REQUEST_FLAGS_SF_MASK, "", \
  16874. + { BIT(SSH_REQUEST_SF_LOCKED_BIT), "L" }, \
  16875. + { BIT(SSH_REQUEST_SF_QUEUED_BIT), "Q" }, \
  16876. + { BIT(SSH_REQUEST_SF_PENDING_BIT), "P" }, \
  16877. + { BIT(SSH_REQUEST_SF_TRANSMITTING_BIT), "S" }, \
  16878. + { BIT(SSH_REQUEST_SF_TRANSMITTED_BIT), "T" }, \
  16879. + { BIT(SSH_REQUEST_SF_RSPRCVD_BIT), "A" }, \
  16880. + { BIT(SSH_REQUEST_SF_CANCELED_BIT), "C" }, \
  16881. + { BIT(SSH_REQUEST_SF_COMPLETED_BIT), "F" } \
  16882. + )
  16883. +
  16884. +#define ssam_show_request_id(rqid) \
  16885. + __print_symbolic(rqid, \
  16886. + { SSAM_RQID_NOT_APPLICABLE, "N/A" } \
  16887. + )
  16888. +
  16889. +#define ssam_show_ssh_tc(rqid) \
  16890. + __print_symbolic(rqid, \
  16891. + { SSAM_SSH_TC_NOT_APPLICABLE, "N/A" }, \
  16892. + { SSAM_SSH_TC_SAM, "SAM" }, \
  16893. + { SSAM_SSH_TC_BAT, "BAT" }, \
  16894. + { SSAM_SSH_TC_TMP, "TMP" }, \
  16895. + { SSAM_SSH_TC_PMC, "PMC" }, \
  16896. + { SSAM_SSH_TC_FAN, "FAN" }, \
  16897. + { SSAM_SSH_TC_PoM, "PoM" }, \
  16898. + { SSAM_SSH_TC_DBG, "DBG" }, \
  16899. + { SSAM_SSH_TC_KBD, "KBD" }, \
  16900. + { SSAM_SSH_TC_FWU, "FWU" }, \
  16901. + { SSAM_SSH_TC_UNI, "UNI" }, \
  16902. + { SSAM_SSH_TC_LPC, "LPC" }, \
  16903. + { SSAM_SSH_TC_TCL, "TCL" }, \
  16904. + { SSAM_SSH_TC_SFL, "SFL" }, \
  16905. + { SSAM_SSH_TC_KIP, "KIP" }, \
  16906. + { SSAM_SSH_TC_EXT, "EXT" }, \
  16907. + { SSAM_SSH_TC_BLD, "BLD" }, \
  16908. + { SSAM_SSH_TC_BAS, "BAS" }, \
  16909. + { SSAM_SSH_TC_SEN, "SEN" }, \
  16910. + { SSAM_SSH_TC_SRQ, "SRQ" }, \
  16911. + { SSAM_SSH_TC_MCU, "MCU" }, \
  16912. + { SSAM_SSH_TC_HID, "HID" }, \
  16913. + { SSAM_SSH_TC_TCH, "TCH" }, \
  16914. + { SSAM_SSH_TC_BKL, "BKL" }, \
  16915. + { SSAM_SSH_TC_TAM, "TAM" }, \
  16916. + { SSAM_SSH_TC_ACC, "ACC" }, \
  16917. + { SSAM_SSH_TC_UFI, "UFI" }, \
  16918. + { SSAM_SSH_TC_USC, "USC" }, \
  16919. + { SSAM_SSH_TC_PEN, "PEN" }, \
  16920. + { SSAM_SSH_TC_VID, "VID" }, \
  16921. + { SSAM_SSH_TC_AUD, "AUD" }, \
  16922. + { SSAM_SSH_TC_SMC, "SMC" }, \
  16923. + { SSAM_SSH_TC_KPD, "KPD" }, \
  16924. + { SSAM_SSH_TC_REG, "REG" } \
  16925. + )
  16926. +
  16927. +
  16928. +DECLARE_EVENT_CLASS(ssam_frame_class,
  16929. + TP_PROTO(const struct ssh_frame *frame),
  16930. +
  16931. + TP_ARGS(frame),
  16932. +
  16933. + TP_STRUCT__entry(
  16934. + __field(u8, type)
  16935. + __field(u8, seq)
  16936. + __field(u16, len)
  16937. + ),
  16938. +
  16939. + TP_fast_assign(
  16940. + __entry->type = frame->type;
  16941. + __entry->seq = frame->seq;
  16942. + __entry->len = get_unaligned_le16(&frame->len);
  16943. + ),
  16944. +
  16945. + TP_printk("ty=%s, seq=0x%02x, len=%u",
  16946. + ssam_show_frame_type(__entry->type),
  16947. + __entry->seq,
  16948. + __entry->len
  16949. + )
  16950. +);
  16951. +
  16952. +#define DEFINE_SSAM_FRAME_EVENT(name) \
  16953. + DEFINE_EVENT(ssam_frame_class, ssam_##name, \
  16954. + TP_PROTO(const struct ssh_frame *frame), \
  16955. + TP_ARGS(frame) \
  16956. + )
  16957. +
  16958. +
  16959. +DECLARE_EVENT_CLASS(ssam_command_class,
  16960. + TP_PROTO(const struct ssh_command *cmd, u16 len),
  16961. +
  16962. + TP_ARGS(cmd, len),
  16963. +
  16964. + TP_STRUCT__entry(
  16965. + __field(u16, rqid)
  16966. + __field(u16, len)
  16967. + __field(u8, tc)
  16968. + __field(u8, cid)
  16969. + __field(u8, iid)
  16970. + ),
  16971. +
  16972. + TP_fast_assign(
  16973. + __entry->rqid = get_unaligned_le16(&cmd->rqid);
  16974. + __entry->tc = cmd->tc;
  16975. + __entry->cid = cmd->cid;
  16976. + __entry->iid = cmd->iid;
  16977. + __entry->len = len;
  16978. + ),
  16979. +
  16980. + TP_printk("rqid=0x%04x, tc=%s, cid=0x%02x, iid=0x%02x, len=%u",
  16981. + __entry->rqid,
  16982. + ssam_show_ssh_tc(__entry->tc),
  16983. + __entry->cid,
  16984. + __entry->iid,
  16985. + __entry->len
  16986. + )
  16987. +);
  16988. +
  16989. +#define DEFINE_SSAM_COMMAND_EVENT(name) \
  16990. + DEFINE_EVENT(ssam_command_class, ssam_##name, \
  16991. + TP_PROTO(const struct ssh_command *cmd, u16 len), \
  16992. + TP_ARGS(cmd, len) \
  16993. + )
  16994. +
  16995. +
  16996. +DECLARE_EVENT_CLASS(ssam_packet_class,
  16997. + TP_PROTO(const struct ssh_packet *packet),
  16998. +
  16999. + TP_ARGS(packet),
  17000. +
  17001. + TP_STRUCT__entry(
  17002. + __field(unsigned long, state)
  17003. + __array(char, uid, SSAM_PTR_UID_LEN)
  17004. + __field(u8, priority)
  17005. + __field(u16, length)
  17006. + __field(u16, seq)
  17007. + ),
  17008. +
  17009. + TP_fast_assign(
  17010. + __entry->state = READ_ONCE(packet->state);
  17011. + ssam_trace_ptr_uid(packet, __entry->uid);
  17012. + __entry->priority = READ_ONCE(packet->priority);
  17013. + __entry->length = packet->data.len;
  17014. + __entry->seq = ssam_trace_get_packet_seq(packet);
  17015. + ),
  17016. +
  17017. + TP_printk("uid=%s, seq=%s, ty=%s, pri=0x%02x, len=%u, sta=%s",
  17018. + __entry->uid,
  17019. + ssam_show_packet_seq(__entry->seq),
  17020. + ssam_show_packet_type(__entry->state),
  17021. + __entry->priority,
  17022. + __entry->length,
  17023. + ssam_show_packet_state(__entry->state)
  17024. + )
  17025. +);
  17026. +
  17027. +#define DEFINE_SSAM_PACKET_EVENT(name) \
  17028. + DEFINE_EVENT(ssam_packet_class, ssam_##name, \
  17029. + TP_PROTO(const struct ssh_packet *packet), \
  17030. + TP_ARGS(packet) \
  17031. + )
  17032. +
  17033. +
  17034. +DECLARE_EVENT_CLASS(ssam_packet_status_class,
  17035. + TP_PROTO(const struct ssh_packet *packet, int status),
  17036. +
  17037. + TP_ARGS(packet, status),
  17038. +
  17039. + TP_STRUCT__entry(
  17040. + __field(unsigned long, state)
  17041. + __field(int, status)
  17042. + __array(char, uid, SSAM_PTR_UID_LEN)
  17043. + __field(u8, priority)
  17044. + __field(u16, length)
  17045. + __field(u16, seq)
  17046. + ),
  17047. +
  17048. + TP_fast_assign(
  17049. + __entry->state = READ_ONCE(packet->state);
  17050. + __entry->status = status;
  17051. + ssam_trace_ptr_uid(packet, __entry->uid);
  17052. + __entry->priority = READ_ONCE(packet->priority);
  17053. + __entry->length = packet->data.len;
  17054. + __entry->seq = ssam_trace_get_packet_seq(packet);
  17055. + ),
  17056. +
  17057. + TP_printk("uid=%s, seq=%s, ty=%s, pri=0x%02x, len=%u, sta=%s, status=%d",
  17058. + __entry->uid,
  17059. + ssam_show_packet_seq(__entry->seq),
  17060. + ssam_show_packet_type(__entry->state),
  17061. + __entry->priority,
  17062. + __entry->length,
  17063. + ssam_show_packet_state(__entry->state),
  17064. + __entry->status
  17065. + )
  17066. +);
  17067. +
  17068. +#define DEFINE_SSAM_PACKET_STATUS_EVENT(name) \
  17069. + DEFINE_EVENT(ssam_packet_status_class, ssam_##name, \
  17070. + TP_PROTO(const struct ssh_packet *packet, int status), \
  17071. + TP_ARGS(packet, status) \
  17072. + )
  17073. +
  17074. +
  17075. +DECLARE_EVENT_CLASS(ssam_request_class,
  17076. + TP_PROTO(const struct ssh_request *request),
  17077. +
  17078. + TP_ARGS(request),
  17079. +
  17080. + TP_STRUCT__entry(
  17081. + __field(unsigned long, state)
  17082. + __field(u32, rqid)
  17083. + __array(char, uid, SSAM_PTR_UID_LEN)
  17084. + __field(u8, tc)
  17085. + __field(u16, cid)
  17086. + __field(u16, iid)
  17087. + ),
  17088. +
  17089. + TP_fast_assign(
  17090. + const struct ssh_packet *p = &request->packet;
  17091. +
  17092. + // use packet for UID so we can match requests to packets
  17093. + __entry->state = READ_ONCE(request->state);
  17094. + __entry->rqid = ssam_trace_get_request_id(p);
  17095. + ssam_trace_ptr_uid(p, __entry->uid);
  17096. + __entry->tc = ssam_trace_get_request_tc(p);
  17097. + __entry->cid = ssam_trace_get_command_field_u8(p, cid);
  17098. + __entry->iid = ssam_trace_get_command_field_u8(p, iid);
  17099. + ),
  17100. +
  17101. + TP_printk("uid=%s, rqid=%s, ty=%s, sta=%s, tc=%s, cid=%s, iid=%s",
  17102. + __entry->uid,
  17103. + ssam_show_request_id(__entry->rqid),
  17104. + ssam_show_request_type(__entry->state),
  17105. + ssam_show_request_state(__entry->state),
  17106. + ssam_show_ssh_tc(__entry->tc),
  17107. + ssam_show_generic_u8_field(__entry->cid),
  17108. + ssam_show_generic_u8_field(__entry->iid)
  17109. + )
  17110. +);
  17111. +
  17112. +#define DEFINE_SSAM_REQUEST_EVENT(name) \
  17113. + DEFINE_EVENT(ssam_request_class, ssam_##name, \
  17114. + TP_PROTO(const struct ssh_request *request), \
  17115. + TP_ARGS(request) \
  17116. + )
  17117. +
  17118. +
  17119. +DECLARE_EVENT_CLASS(ssam_request_status_class,
  17120. + TP_PROTO(const struct ssh_request *request, int status),
  17121. +
  17122. + TP_ARGS(request, status),
  17123. +
  17124. + TP_STRUCT__entry(
  17125. + __field(unsigned long, state)
  17126. + __field(u32, rqid)
  17127. + __field(int, status)
  17128. + __array(char, uid, SSAM_PTR_UID_LEN)
  17129. + __field(u8, tc)
  17130. + __field(u16, cid)
  17131. + __field(u16, iid)
  17132. + ),
  17133. +
  17134. + TP_fast_assign(
  17135. + const struct ssh_packet *p = &request->packet;
  17136. +
  17137. + // use packet for UID so we can match requests to packets
  17138. + __entry->state = READ_ONCE(request->state);
  17139. + __entry->rqid = ssam_trace_get_request_id(p);
  17140. + __entry->status = status;
  17141. + ssam_trace_ptr_uid(p, __entry->uid);
  17142. + __entry->tc = ssam_trace_get_request_tc(p);
  17143. + __entry->cid = ssam_trace_get_command_field_u8(p, cid);
  17144. + __entry->iid = ssam_trace_get_command_field_u8(p, iid);
  17145. + ),
  17146. +
  17147. + TP_printk("uid=%s, rqid=%s, ty=%s, sta=%s, tc=%s, cid=%s, iid=%s, status=%d",
  17148. + __entry->uid,
  17149. + ssam_show_request_id(__entry->rqid),
  17150. + ssam_show_request_type(__entry->state),
  17151. + ssam_show_request_state(__entry->state),
  17152. + ssam_show_ssh_tc(__entry->tc),
  17153. + ssam_show_generic_u8_field(__entry->cid),
  17154. + ssam_show_generic_u8_field(__entry->iid),
  17155. + __entry->status
  17156. + )
  17157. +);
  17158. +
  17159. +#define DEFINE_SSAM_REQUEST_STATUS_EVENT(name) \
  17160. + DEFINE_EVENT(ssam_request_status_class, ssam_##name, \
  17161. + TP_PROTO(const struct ssh_request *request, int status),\
  17162. + TP_ARGS(request, status) \
  17163. + )
  17164. +
  17165. +
  17166. +DECLARE_EVENT_CLASS(ssam_alloc_class,
  17167. + TP_PROTO(void *ptr, size_t len),
  17168. +
  17169. + TP_ARGS(ptr, len),
  17170. +
  17171. + TP_STRUCT__entry(
  17172. + __field(size_t, len)
  17173. + __array(char, uid, SSAM_PTR_UID_LEN)
  17174. + ),
  17175. +
  17176. + TP_fast_assign(
  17177. + __entry->len = len;
  17178. + ssam_trace_ptr_uid(ptr, __entry->uid);
  17179. + ),
  17180. +
  17181. + TP_printk("uid=%s, len=%zu", __entry->uid, __entry->len)
  17182. +);
  17183. +
  17184. +#define DEFINE_SSAM_ALLOC_EVENT(name) \
  17185. + DEFINE_EVENT(ssam_alloc_class, ssam_##name, \
  17186. + TP_PROTO(void *ptr, size_t len), \
  17187. + TP_ARGS(ptr, len) \
  17188. + )
  17189. +
  17190. +
  17191. +DECLARE_EVENT_CLASS(ssam_free_class,
  17192. + TP_PROTO(void *ptr),
  17193. +
  17194. + TP_ARGS(ptr),
  17195. +
  17196. + TP_STRUCT__entry(
  17197. + __array(char, uid, SSAM_PTR_UID_LEN)
  17198. + ),
  17199. +
  17200. + TP_fast_assign(
  17201. + ssam_trace_ptr_uid(ptr, __entry->uid);
  17202. + ),
  17203. +
  17204. + TP_printk("uid=%s", __entry->uid)
  17205. +);
  17206. +
  17207. +#define DEFINE_SSAM_FREE_EVENT(name) \
  17208. + DEFINE_EVENT(ssam_free_class, ssam_##name, \
  17209. + TP_PROTO(void *ptr), \
  17210. + TP_ARGS(ptr) \
  17211. + )
  17212. +
  17213. +
  17214. +DECLARE_EVENT_CLASS(ssam_generic_uint_class,
  17215. + TP_PROTO(const char *property, unsigned int value),
  17216. +
  17217. + TP_ARGS(property, value),
  17218. +
  17219. + TP_STRUCT__entry(
  17220. + __field(unsigned int, value)
  17221. + __string(property, property)
  17222. + ),
  17223. +
  17224. + TP_fast_assign(
  17225. + __entry->value = value;
  17226. + __assign_str(property, property);
  17227. + ),
  17228. +
  17229. + TP_printk("%s=%u", __get_str(property), __entry->value)
  17230. +);
  17231. +
  17232. +#define DEFINE_SSAM_GENERIC_UINT_EVENT(name) \
  17233. + DEFINE_EVENT(ssam_generic_uint_class, ssam_##name, \
  17234. + TP_PROTO(const char *property, unsigned int value), \
  17235. + TP_ARGS(property, value) \
  17236. + )
  17237. +
  17238. +
  17239. +DEFINE_SSAM_FRAME_EVENT(rx_frame_received);
  17240. +DEFINE_SSAM_COMMAND_EVENT(rx_response_received);
  17241. +DEFINE_SSAM_COMMAND_EVENT(rx_event_received);
  17242. +
  17243. +DEFINE_SSAM_PACKET_EVENT(packet_release);
  17244. +DEFINE_SSAM_PACKET_EVENT(packet_submit);
  17245. +DEFINE_SSAM_PACKET_EVENT(packet_resubmit);
  17246. +DEFINE_SSAM_PACKET_EVENT(packet_timeout);
  17247. +DEFINE_SSAM_PACKET_EVENT(packet_cancel);
  17248. +DEFINE_SSAM_PACKET_STATUS_EVENT(packet_complete);
  17249. +DEFINE_SSAM_GENERIC_UINT_EVENT(ptl_timeout_reap);
  17250. +
  17251. +DEFINE_SSAM_REQUEST_EVENT(request_submit);
  17252. +DEFINE_SSAM_REQUEST_EVENT(request_timeout);
  17253. +DEFINE_SSAM_REQUEST_EVENT(request_cancel);
  17254. +DEFINE_SSAM_REQUEST_STATUS_EVENT(request_complete);
  17255. +DEFINE_SSAM_GENERIC_UINT_EVENT(rtl_timeout_reap);
  17256. +
  17257. +DEFINE_SSAM_PACKET_EVENT(ei_tx_drop_ack_packet);
  17258. +DEFINE_SSAM_PACKET_EVENT(ei_tx_drop_nak_packet);
  17259. +DEFINE_SSAM_PACKET_EVENT(ei_tx_drop_dsq_packet);
  17260. +DEFINE_SSAM_PACKET_STATUS_EVENT(ei_tx_fail_write);
  17261. +DEFINE_SSAM_PACKET_EVENT(ei_tx_corrupt_data);
  17262. +DEFINE_SSAM_GENERIC_UINT_EVENT(ei_rx_corrupt_syn);
  17263. +DEFINE_SSAM_FRAME_EVENT(ei_rx_corrupt_data);
  17264. +DEFINE_SSAM_REQUEST_EVENT(ei_rx_drop_response);
  17265. +
  17266. +DEFINE_SSAM_ALLOC_EVENT(ctrl_packet_alloc);
  17267. +DEFINE_SSAM_FREE_EVENT(ctrl_packet_free);
  17268. +
  17269. +DEFINE_SSAM_ALLOC_EVENT(event_item_alloc);
  17270. +DEFINE_SSAM_FREE_EVENT(event_item_free);
  17271. +
  17272. +#endif /* _SURFACE_AGGREGATOR_TRACE_H */
  17273. +
  17274. +/* This part must be outside protection */
  17275. +#undef TRACE_INCLUDE_PATH
  17276. +#undef TRACE_INCLUDE_FILE
  17277. +
  17278. +#define TRACE_INCLUDE_PATH .
  17279. +#define TRACE_INCLUDE_FILE trace
  17280. +
  17281. +#include <trace/define_trace.h>
  17282. diff --git a/include/linux/mod_devicetable.h b/include/linux/mod_devicetable.h
  17283. index a35f82fb36da..9932a610bda0 100644
  17284. --- a/include/linux/mod_devicetable.h
  17285. +++ b/include/linux/mod_devicetable.h
  17286. @@ -838,15 +838,16 @@ struct mhi_device_id {
  17287. /* Surface System Aggregator Module */
  17288. -#define SSAM_MATCH_CHANNEL 0x1
  17289. +#define SSAM_MATCH_TARGET 0x1
  17290. #define SSAM_MATCH_INSTANCE 0x2
  17291. #define SSAM_MATCH_FUNCTION 0x4
  17292. struct ssam_device_id {
  17293. __u8 match_flags;
  17294. + __u8 domain;
  17295. __u8 category;
  17296. - __u8 channel;
  17297. + __u8 target;
  17298. __u8 instance;
  17299. __u8 function;
  17300. diff --git a/include/linux/surface_acpi_notify.h b/include/linux/surface_acpi_notify.h
  17301. new file mode 100644
  17302. index 000000000000..8e3e86c7d78c
  17303. --- /dev/null
  17304. +++ b/include/linux/surface_acpi_notify.h
  17305. @@ -0,0 +1,39 @@
  17306. +/* SPDX-License-Identifier: GPL-2.0+ */
  17307. +/*
  17308. + * Interface for Surface ACPI Notify (SAN) driver.
  17309. + *
  17310. + * Provides access to discrete GPU notifications sent from ACPI via the SAN
  17311. + * driver, which are not handled by this driver directly.
  17312. + *
  17313. + * Copyright (C) 2019-2020 Maximilian Luz <luzmaximilian@gmail.com>
  17314. + */
  17315. +
  17316. +#ifndef _LINUX_SURFACE_ACPI_NOTIFY_H
  17317. +#define _LINUX_SURFACE_ACPI_NOTIFY_H
  17318. +
  17319. +#include <linux/notifier.h>
  17320. +#include <linux/types.h>
  17321. +
  17322. +/**
  17323. + * struct san_dgpu_event - Discrete GPU ACPI event.
  17324. + * @category: Category of the event.
  17325. + * @target: Target ID of the event source.
  17326. + * @command: Command ID of the event.
  17327. + * @instance: Instance ID of the event source.
  17328. + * @length: Length of the event's payload data (in bytes).
  17329. + * @payload: Pointer to the event's payload data.
  17330. + */
  17331. +struct san_dgpu_event {
  17332. + u8 category;
  17333. + u8 target;
  17334. + u8 command;
  17335. + u8 instance;
  17336. + u16 length;
  17337. + u8 *payload;
  17338. +};
  17339. +
  17340. +int san_client_link(struct device *client);
  17341. +int san_dgpu_notifier_register(struct notifier_block *nb);
  17342. +int san_dgpu_notifier_unregister(struct notifier_block *nb);
  17343. +
  17344. +#endif /* _LINUX_SURFACE_ACPI_NOTIFY_H */
  17345. diff --git a/include/linux/surface_aggregator/controller.h b/include/linux/surface_aggregator/controller.h
  17346. new file mode 100644
  17347. index 000000000000..d128c68c04e0
  17348. --- /dev/null
  17349. +++ b/include/linux/surface_aggregator/controller.h
  17350. @@ -0,0 +1,832 @@
  17351. +/* SPDX-License-Identifier: GPL-2.0+ */
  17352. +/*
  17353. + * Surface System Aggregator Module (SSAM) controller interface.
  17354. + *
  17355. + * Main communication interface for the SSAM EC. Provides a controller
  17356. + * managing access and communication to and from the SSAM EC, as well as main
  17357. + * communication structures and definitions.
  17358. + *
  17359. + * Copyright (C) 2019-2020 Maximilian Luz <luzmaximilian@gmail.com>
  17360. + */
  17361. +
  17362. +#ifndef _LINUX_SURFACE_AGGREGATOR_CONTROLLER_H
  17363. +#define _LINUX_SURFACE_AGGREGATOR_CONTROLLER_H
  17364. +
  17365. +#include <linux/completion.h>
  17366. +#include <linux/device.h>
  17367. +#include <linux/types.h>
  17368. +
  17369. +#include <linux/surface_aggregator/serial_hub.h>
  17370. +
  17371. +
  17372. +/* -- Main data types and definitions --------------------------------------- */
  17373. +
  17374. +/**
  17375. + * enum ssam_event_flags - Flags for enabling/disabling SAM events
  17376. + * @SSAM_EVENT_SEQUENCED: The event will be sent via a sequenced data frame.
  17377. + */
  17378. +enum ssam_event_flags {
  17379. + SSAM_EVENT_SEQUENCED = BIT(0),
  17380. +};
  17381. +
  17382. +/**
  17383. + * struct ssam_event - SAM event sent from the EC to the host.
  17384. + * @target_category: Target category of the event source. See &enum ssam_ssh_tc.
  17385. + * @target_id: Target ID of the event source.
  17386. + * @command_id: Command ID of the event.
  17387. + * @instance_id: Instance ID of the event source.
  17388. + * @length: Length of the event payload in bytes.
  17389. + * @data: Event payload data.
  17390. + */
  17391. +struct ssam_event {
  17392. + u8 target_category;
  17393. + u8 target_id;
  17394. + u8 command_id;
  17395. + u8 instance_id;
  17396. + u16 length;
  17397. + u8 data[];
  17398. +};
  17399. +
  17400. +/**
  17401. + * enum ssam_request_flags - Flags for SAM requests.
  17402. + *
  17403. + * @SSAM_REQUEST_HAS_RESPONSE:
  17404. + * Specifies that the request expects a response. If not set, the request
  17405. + * will be directly completed after its underlying packet has been
  17406. + * transmitted. If set, the request transport system waits for a response
  17407. + * of the request.
  17408. + *
  17409. + * @SSAM_REQUEST_UNSEQUENCED:
  17410. + * Specifies that the request should be transmitted via an unsequenced
  17411. + * packet. If set, the request must not have a response, meaning that this
  17412. + * flag and the %SSAM_REQUEST_HAS_RESPONSE flag are mutually exclusive.
  17413. + */
  17414. +enum ssam_request_flags {
  17415. + SSAM_REQUEST_HAS_RESPONSE = BIT(0),
  17416. + SSAM_REQUEST_UNSEQUENCED = BIT(1),
  17417. +};
  17418. +
  17419. +/**
  17420. + * struct ssam_request - SAM request description.
  17421. + * @target_category: Category of the request's target. See &enum ssam_ssh_tc.
  17422. + * @target_id: ID of the request's target.
  17423. + * @command_id: Command ID of the request.
  17424. + * @instance_id: Instance ID of the request's target.
  17425. + * @flags: Flags for the request. See &enum ssam_request_flags.
  17426. + * @length: Length of the request payload in bytes.
  17427. + * @payload: Request payload data.
  17428. + *
  17429. + * This struct fully describes a SAM request with payload. It is intended to
  17430. + * help set up the actual transport struct, e.g. &struct ssam_request_sync,
  17431. + * and specifically its raw message data via ssam_request_write_data().
  17432. + */
  17433. +struct ssam_request {
  17434. + u8 target_category;
  17435. + u8 target_id;
  17436. + u8 command_id;
  17437. + u8 instance_id;
  17438. + u16 flags;
  17439. + u16 length;
  17440. + const u8 *payload;
  17441. +};
  17442. +
  17443. +/**
  17444. + * struct ssam_response - Response buffer for SAM request.
  17445. + * @capacity: Capacity of the buffer, in bytes.
  17446. + * @length: Length of the actual data stored in the memory pointed to by
  17447. + * @pointer, in bytes. Set by the transport system.
  17448. + * @pointer: Pointer to the buffer's memory, storing the response payload data.
  17449. + */
  17450. +struct ssam_response {
  17451. + size_t capacity;
  17452. + size_t length;
  17453. + u8 *pointer;
  17454. +};
  17455. +
  17456. +struct ssam_controller;
  17457. +
  17458. +
  17459. +struct ssam_controller *ssam_get_controller(void);
  17460. +int ssam_client_link(struct ssam_controller *ctrl, struct device *client);
  17461. +int ssam_client_bind(struct device *client, struct ssam_controller **ctrl);
  17462. +
  17463. +struct device *ssam_controller_device(struct ssam_controller *c);
  17464. +
  17465. +struct ssam_controller *ssam_controller_get(struct ssam_controller *c);
  17466. +void ssam_controller_put(struct ssam_controller *c);
  17467. +
  17468. +void ssam_controller_statelock(struct ssam_controller *c);
  17469. +void ssam_controller_stateunlock(struct ssam_controller *c);
  17470. +
  17471. +ssize_t ssam_request_write_data(struct ssam_span *buf,
  17472. + struct ssam_controller *ctrl,
  17473. + const struct ssam_request *spec);
  17474. +
  17475. +
  17476. +/* -- Synchronous request interface. ---------------------------------------- */
  17477. +
  17478. +/**
  17479. + * struct ssam_request_sync - Synchronous SAM request struct.
  17480. + * @base: Underlying SSH request.
  17481. + * @comp: Completion used to signal full completion of the request. After the
  17482. + * request has been submitted, this struct may only be modified or
  17483. + * deallocated after the completion has been signaled.
  17484. + * request has been submitted,
  17485. + * @resp: Buffer to store the response.
  17486. + * @status: Status of the request, set after the base request has been
  17487. + * completed or has failed.
  17488. + */
  17489. +struct ssam_request_sync {
  17490. + struct ssh_request base;
  17491. + struct completion comp;
  17492. + struct ssam_response *resp;
  17493. + int status;
  17494. +};
  17495. +
  17496. +int ssam_request_sync_alloc(size_t payload_len, gfp_t flags,
  17497. + struct ssam_request_sync **rqst,
  17498. + struct ssam_span *buffer);
  17499. +
  17500. +void ssam_request_sync_free(struct ssam_request_sync *rqst);
  17501. +
  17502. +void ssam_request_sync_init(struct ssam_request_sync *rqst,
  17503. + enum ssam_request_flags flags);
  17504. +
  17505. +/**
  17506. + * ssam_request_sync_set_data - Set message data of a synchronous request.
  17507. + * @rqst: The request.
  17508. + * @ptr: Pointer to the request message data.
  17509. + * @len: Length of the request message data.
  17510. + *
  17511. + * Set the request message data of a synchronous request. The provided buffer
  17512. + * needs to live until the request has been completed.
  17513. + */
  17514. +static inline void ssam_request_sync_set_data(struct ssam_request_sync *rqst,
  17515. + u8 *ptr, size_t len)
  17516. +{
  17517. + ssh_request_set_data(&rqst->base, ptr, len);
  17518. +}
  17519. +
  17520. +/**
  17521. + * ssam_request_sync_set_resp - Set response buffer of a synchronous request.
  17522. + * @rqst: The request.
  17523. + * @resp: The response buffer.
  17524. + *
  17525. + * Sets the response buffer ot a synchronous request. This buffer will store
  17526. + * the response of the request after it has been completed. May be %NULL if
  17527. + * no response is expected.
  17528. + */
  17529. +static inline void ssam_request_sync_set_resp(struct ssam_request_sync *rqst,
  17530. + struct ssam_response *resp)
  17531. +{
  17532. + rqst->resp = resp;
  17533. +}
  17534. +
  17535. +int ssam_request_sync_submit(struct ssam_controller *ctrl,
  17536. + struct ssam_request_sync *rqst);
  17537. +
  17538. +/**
  17539. + * ssam_request_sync_wait - Wait for completion of a synchronous request.
  17540. + * @rqst: The request to wait for.
  17541. + *
  17542. + * Wait for completion and release of a synchronous request. After this
  17543. + * function terminates, the request is guaranteed to have left the transport
  17544. + * system. After successful submission of a request, this function must be
  17545. + * called before accessing the response of the request, freeing the request,
  17546. + * or freeing any of the buffers associated with the request.
  17547. + *
  17548. + * This function must not be called if the request has not been submitted yet
  17549. + * and may lead to a deadlock/infinite wait if a subsequent request submission
  17550. + * fails in that case, due to the completion never triggering.
  17551. + *
  17552. + * Return: Returns the status of the given request, which is set on completion
  17553. + * of the packet. This value is zero on success and negative on failure.
  17554. + */
  17555. +static inline int ssam_request_sync_wait(struct ssam_request_sync *rqst)
  17556. +{
  17557. + wait_for_completion(&rqst->comp);
  17558. + return rqst->status;
  17559. +}
  17560. +
  17561. +int ssam_request_sync(struct ssam_controller *ctrl,
  17562. + const struct ssam_request *spec,
  17563. + struct ssam_response *rsp);
  17564. +
  17565. +int ssam_request_sync_with_buffer(struct ssam_controller *ctrl,
  17566. + const struct ssam_request *spec,
  17567. + struct ssam_response *rsp,
  17568. + struct ssam_span *buf);
  17569. +
  17570. +
  17571. +/**
  17572. + * ssam_request_sync_onstack - Execute a synchronous request on the stack.
  17573. + * @ctrl: The controller via which the request is submitted.
  17574. + * @rqst: The request specification.
  17575. + * @rsp: The response buffer.
  17576. + * @payload_len: The (maximum) request payload length.
  17577. + *
  17578. + * Allocates a synchronous request with specified payload length on the stack,
  17579. + * fully intializes it via the provided request specification, submits it, and
  17580. + * finally waits for its completion before returning its status. This helper
  17581. + * macro essentially allocates the request message buffer on the stack and
  17582. + * then calls ssam_request_sync_with_buffer().
  17583. + *
  17584. + * Note: The @payload_len parameter specifies the maximum payload length, used
  17585. + * for buffer allocation. The actual payload length may be smaller.
  17586. + *
  17587. + * Return: Returns the status of the request or any failure during setup, i.e.
  17588. + * zero on success and a negative value on failure.
  17589. + */
  17590. +#define ssam_request_sync_onstack(ctrl, rqst, rsp, payload_len) \
  17591. + ({ \
  17592. + u8 __data[SSH_COMMAND_MESSAGE_LENGTH(payload_len)]; \
  17593. + struct ssam_span __buf = { &__data[0], ARRAY_SIZE(__data) }; \
  17594. + \
  17595. + ssam_request_sync_with_buffer(ctrl, rqst, rsp, &__buf); \
  17596. + })
  17597. +
  17598. +/**
  17599. + * __ssam_retry - Retry request in case of I/O errors or timeouts.
  17600. + * @request: The request function to execute. Must return an integer.
  17601. + * @n: Number of tries.
  17602. + * @args: Arguments for the request function.
  17603. + *
  17604. + * Executes the given request function, i.e. calls @request. In case the
  17605. + * request returns %-EREMOTEIO (indicates I/O error) or -%ETIMEDOUT (request
  17606. + * or underlying packet timed out), @request will be re-executed again, up to
  17607. + * @n times in total.
  17608. + *
  17609. + * Return: Returns the return value of the last execution of @request.
  17610. + */
  17611. +#define __ssam_retry(request, n, args...) \
  17612. + ({ \
  17613. + int __i, __s = 0; \
  17614. + \
  17615. + for (__i = (n); __i > 0; __i--) { \
  17616. + __s = request(args); \
  17617. + if (__s != -ETIMEDOUT && __s != -EREMOTEIO) \
  17618. + break; \
  17619. + } \
  17620. + __s; \
  17621. + })
  17622. +
  17623. +/**
  17624. + * ssam_retry - Retry request in case of I/O errors or timeouts up to three
  17625. + * times in total.
  17626. + * @request: The request function to execute. Must return an integer.
  17627. + * @args: Arguments for the request function.
  17628. + *
  17629. + * Executes the given request function, i.e. calls @request. In case the
  17630. + * request returns %-EREMOTEIO (indicates I/O error) or -%ETIMEDOUT (request
  17631. + * or underlying packet timed out), @request will be re-executed again, up to
  17632. + * three times in total.
  17633. + *
  17634. + * See __ssam_retry() for a more generic macro for this purpose.
  17635. + *
  17636. + * Return: Returns the return value of the last execution of @request.
  17637. + */
  17638. +#define ssam_retry(request, args...) \
  17639. + __ssam_retry(request, 3, args)
  17640. +
  17641. +/**
  17642. + * struct ssam_request_spec - Blue-print specification of SAM request.
  17643. + * @target_category: Category of the request's target. See &enum ssam_ssh_tc.
  17644. + * @target_id: ID of the request's target.
  17645. + * @command_id: Command ID of the request.
  17646. + * @instance_id: Instance ID of the request's target.
  17647. + * @flags: Flags for the request. See &enum ssam_request_flags.
  17648. + *
  17649. + * Blue-print specification for a SAM request. This struct describes the
  17650. + * unique static parameters of a request (i.e. type) without specifying any of
  17651. + * its instance-specific data (e.g. payload). It is intended to be used as base
  17652. + * for defining simple request functions via the
  17653. + * ``SSAM_DEFINE_SYNC_REQUEST_x()`` family of macros.
  17654. + */
  17655. +struct ssam_request_spec {
  17656. + u8 target_category;
  17657. + u8 target_id;
  17658. + u8 command_id;
  17659. + u8 instance_id;
  17660. + u8 flags;
  17661. +};
  17662. +
  17663. +/**
  17664. + * struct ssam_request_spec_md - Blue-print specification for multi-device SAM
  17665. + * request.
  17666. + * @target_category: Category of the request's target. See &enum ssam_ssh_tc.
  17667. + * @command_id: Command ID of the request.
  17668. + * @flags: Flags for the request. See &enum ssam_request_flags.
  17669. + *
  17670. + * Blue-print specification for a multi-device SAM request, i.e. a request
  17671. + * that is applicable to multiple device instances, described by their
  17672. + * individual target and instance IDs. This struct describes the unique static
  17673. + * parameters of a request (i.e. type) without specifying any of its
  17674. + * instance-specific data (e.g. payload) and without specifying any of its
  17675. + * device specific IDs (i.e. target and instance ID). It is intended to be
  17676. + * used as base for defining simple multi-device request functions via the
  17677. + * ``SSAM_DEFINE_SYNC_REQUEST_MD_x()`` and ``SSAM_DEFINE_SYNC_REQUEST_CL_x()``
  17678. + * families of macros.
  17679. + */
  17680. +struct ssam_request_spec_md {
  17681. + u8 target_category;
  17682. + u8 command_id;
  17683. + u8 flags;
  17684. +};
  17685. +
  17686. +/**
  17687. + * SSAM_DEFINE_SYNC_REQUEST_N() - Define synchronous SAM request function
  17688. + * with neither argument nor return value.
  17689. + * @name: Name of the generated function.
  17690. + * @spec: Specification (&struct ssam_request_spec) defining the request.
  17691. + *
  17692. + * Defines a function executing the synchronous SAM request specified by
  17693. + * @spec, with the request having neither argument nor return value. The
  17694. + * generated function takes care of setting up the request struct and buffer
  17695. + * allocation, as well as execution of the request itself, returning once the
  17696. + * request has been fully completed. The required transport buffer will be
  17697. + * allocated on the stack.
  17698. + *
  17699. + * The generated function is defined as ``int name(struct ssam_controller
  17700. + * *ctrl)``, returning the status of the request, which is zero on success and
  17701. + * negative on failure. The ``ctrl`` parameter is the controller via which the
  17702. + * request is being sent.
  17703. + *
  17704. + * Refer to ssam_request_sync_onstack() for more details on the behavior of
  17705. + * the generated function.
  17706. + */
  17707. +#define SSAM_DEFINE_SYNC_REQUEST_N(name, spec...) \
  17708. + int name(struct ssam_controller *ctrl) \
  17709. + { \
  17710. + struct ssam_request_spec s = (struct ssam_request_spec)spec; \
  17711. + struct ssam_request rqst; \
  17712. + \
  17713. + rqst.target_category = s.target_category; \
  17714. + rqst.target_id = s.target_id; \
  17715. + rqst.command_id = s.command_id; \
  17716. + rqst.instance_id = s.instance_id; \
  17717. + rqst.flags = s.flags; \
  17718. + rqst.length = 0; \
  17719. + rqst.payload = NULL; \
  17720. + \
  17721. + return ssam_request_sync_onstack(ctrl, &rqst, NULL, 0); \
  17722. + }
  17723. +
  17724. +/**
  17725. + * SSAM_DEFINE_SYNC_REQUEST_W() - Define synchronous SAM request function with
  17726. + * argument.
  17727. + * @name: Name of the generated function.
  17728. + * @atype: Type of the request's argument.
  17729. + * @spec: Specification (&struct ssam_request_spec) defining the request.
  17730. + *
  17731. + * Defines a function executing the synchronous SAM request specified by
  17732. + * @spec, with the request taking an argument of type @atype and having no
  17733. + * return value. The generated function takes care of setting up the request
  17734. + * struct, buffer allocation, as well as execution of the request itself,
  17735. + * returning once the request has been fully completed. The required transport
  17736. + * buffer will be allocated on the stack.
  17737. + *
  17738. + * The generated function is defined as ``int name(struct ssam_controller
  17739. + * *ctrl, const atype *arg)``, returning the status of the request, which is
  17740. + * zero on success and negative on failure. The ``ctrl`` parameter is the
  17741. + * controller via which the request is sent. The request argument is specified
  17742. + * via the ``arg`` pointer.
  17743. + *
  17744. + * Refer to ssam_request_sync_onstack() for more details on the behavior of
  17745. + * the generated function.
  17746. + */
  17747. +#define SSAM_DEFINE_SYNC_REQUEST_W(name, atype, spec...) \
  17748. + int name(struct ssam_controller *ctrl, const atype *arg) \
  17749. + { \
  17750. + struct ssam_request_spec s = (struct ssam_request_spec)spec; \
  17751. + struct ssam_request rqst; \
  17752. + \
  17753. + rqst.target_category = s.target_category; \
  17754. + rqst.target_id = s.target_id; \
  17755. + rqst.command_id = s.command_id; \
  17756. + rqst.instance_id = s.instance_id; \
  17757. + rqst.flags = s.flags; \
  17758. + rqst.length = sizeof(atype); \
  17759. + rqst.payload = (u8 *)arg; \
  17760. + \
  17761. + return ssam_request_sync_onstack(ctrl, &rqst, NULL, \
  17762. + sizeof(atype)); \
  17763. + }
  17764. +
  17765. +/**
  17766. + * SSAM_DEFINE_SYNC_REQUEST_R() - Define synchronous SAM request function with
  17767. + * return value.
  17768. + * @name: Name of the generated function.
  17769. + * @rtype: Type of the request's return value.
  17770. + * @spec: Specification (&struct ssam_request_spec) defining the request.
  17771. + *
  17772. + * Defines a function executing the synchronous SAM request specified by
  17773. + * @spec, with the request taking no argument but having a return value of
  17774. + * type @rtype. The generated function takes care of setting up the request
  17775. + * and response structs, buffer allocation, as well as execution of the
  17776. + * request itself, returning once the request has been fully completed. The
  17777. + * required transport buffer will be allocated on the stack.
  17778. + *
  17779. + * The generated function is defined as ``int name(struct ssam_controller
  17780. + * *ctrl, rtype *ret)``, returning the status of the request, which is zero on
  17781. + * success and negative on failure. The ``ctrl`` parameter is the controller
  17782. + * via which the request is sent. The request's return value is written to the
  17783. + * memory pointed to by the ``ret`` parameter.
  17784. + *
  17785. + * Refer to ssam_request_sync_onstack() for more details on the behavior of
  17786. + * the generated function.
  17787. + */
  17788. +#define SSAM_DEFINE_SYNC_REQUEST_R(name, rtype, spec...) \
  17789. + int name(struct ssam_controller *ctrl, rtype *ret) \
  17790. + { \
  17791. + struct ssam_request_spec s = (struct ssam_request_spec)spec; \
  17792. + struct ssam_request rqst; \
  17793. + struct ssam_response rsp; \
  17794. + int status; \
  17795. + \
  17796. + rqst.target_category = s.target_category; \
  17797. + rqst.target_id = s.target_id; \
  17798. + rqst.command_id = s.command_id; \
  17799. + rqst.instance_id = s.instance_id; \
  17800. + rqst.flags = s.flags | SSAM_REQUEST_HAS_RESPONSE; \
  17801. + rqst.length = 0; \
  17802. + rqst.payload = NULL; \
  17803. + \
  17804. + rsp.capacity = sizeof(rtype); \
  17805. + rsp.length = 0; \
  17806. + rsp.pointer = (u8 *)ret; \
  17807. + \
  17808. + status = ssam_request_sync_onstack(ctrl, &rqst, &rsp, 0); \
  17809. + if (status) \
  17810. + return status; \
  17811. + \
  17812. + if (rsp.length != sizeof(rtype)) { \
  17813. + struct device *dev = ssam_controller_device(ctrl); \
  17814. + dev_err(dev, "rqst: invalid response length, expected " \
  17815. + "%zu, got %zu (tc: 0x%02x, cid: 0x%02x)", \
  17816. + sizeof(rtype), rsp.length, rqst.target_category,\
  17817. + rqst.command_id); \
  17818. + return -EIO; \
  17819. + } \
  17820. + \
  17821. + return 0; \
  17822. + }
  17823. +
  17824. +/**
  17825. + * SSAM_DEFINE_SYNC_REQUEST_MD_N() - Define synchronous multi-device SAM
  17826. + * request function with neither argument nor return value.
  17827. + * @name: Name of the generated function.
  17828. + * @spec: Specification (&struct ssam_request_spec_md) defining the request.
  17829. + *
  17830. + * Defines a function executing the synchronous SAM request specified by
  17831. + * @spec, with the request having neither argument nor return value. Device
  17832. + * specifying parameters are not hard-coded, but instead must be provided to
  17833. + * the function. The generated function takes care of setting up the request
  17834. + * struct, buffer allocation, as well as execution of the request itself,
  17835. + * returning once the request has been fully completed. The required transport
  17836. + * buffer will be allocated on the stack.
  17837. + *
  17838. + * The generated function is defined as ``int name(struct ssam_controller
  17839. + * *ctrl, u8 tid, u8 iid)``, returning the status of the request, which is
  17840. + * zero on success and negative on failure. The ``ctrl`` parameter is the
  17841. + * controller via which the request is sent, ``tid`` the target ID for the
  17842. + * request, and ``iid`` the instance ID.
  17843. + *
  17844. + * Refer to ssam_request_sync_onstack() for more details on the behavior of
  17845. + * the generated function.
  17846. + */
  17847. +#define SSAM_DEFINE_SYNC_REQUEST_MD_N(name, spec...) \
  17848. + int name(struct ssam_controller *ctrl, u8 tid, u8 iid) \
  17849. + { \
  17850. + struct ssam_request_spec_md s \
  17851. + = (struct ssam_request_spec_md)spec; \
  17852. + struct ssam_request rqst; \
  17853. + \
  17854. + rqst.target_category = s.target_category; \
  17855. + rqst.target_id = tid; \
  17856. + rqst.command_id = s.command_id; \
  17857. + rqst.instance_id = iid; \
  17858. + rqst.flags = s.flags; \
  17859. + rqst.length = 0; \
  17860. + rqst.payload = NULL; \
  17861. + \
  17862. + return ssam_request_sync_onstack(ctrl, &rqst, NULL, 0); \
  17863. + }
  17864. +
  17865. +/**
  17866. + * SSAM_DEFINE_SYNC_REQUEST_MD_W() - Define synchronous multi-device SAM
  17867. + * request function with argument.
  17868. + * @name: Name of the generated function.
  17869. + * @atype: Type of the request's argument.
  17870. + * @spec: Specification (&struct ssam_request_spec_md) defining the request.
  17871. + *
  17872. + * Defines a function executing the synchronous SAM request specified by
  17873. + * @spec, with the request taking an argument of type @atype and having no
  17874. + * return value. Device specifying parameters are not hard-coded, but instead
  17875. + * must be provided to the function. The generated function takes care of
  17876. + * setting up the request struct, buffer allocation, as well as execution of
  17877. + * the request itself, returning once the request has been fully completed.
  17878. + * The required transport buffer will be allocated on the stack.
  17879. + *
  17880. + * The generated function is defined as ``int name(struct ssam_controller
  17881. + * *ctrl, u8 tid, u8 iid, const atype *arg)``, returning the status of the
  17882. + * request, which is zero on success and negative on failure. The ``ctrl``
  17883. + * parameter is the controller via which the request is sent, ``tid`` the
  17884. + * target ID for the request, and ``iid`` the instance ID. The request argument
  17885. + * is specified via the ``arg`` pointer.
  17886. + *
  17887. + * Refer to ssam_request_sync_onstack() for more details on the behavior of
  17888. + * the generated function.
  17889. + */
  17890. +#define SSAM_DEFINE_SYNC_REQUEST_MD_W(name, atype, spec...) \
  17891. + int name(struct ssam_controller *ctrl, u8 tid, u8 iid, const atype *arg)\
  17892. + { \
  17893. + struct ssam_request_spec_md s \
  17894. + = (struct ssam_request_spec_md)spec; \
  17895. + struct ssam_request rqst; \
  17896. + \
  17897. + rqst.target_category = s.target_category; \
  17898. + rqst.target_id = tid; \
  17899. + rqst.command_id = s.command_id; \
  17900. + rqst.instance_id = iid; \
  17901. + rqst.flags = s.flags; \
  17902. + rqst.length = sizeof(atype); \
  17903. + rqst.payload = (u8 *)arg; \
  17904. + \
  17905. + return ssam_request_sync_onstack(ctrl, &rqst, NULL, \
  17906. + sizeof(atype)); \
  17907. + }
  17908. +
  17909. +/**
  17910. + * SSAM_DEFINE_SYNC_REQUEST_MD_R() - Define synchronous multi-device SAM
  17911. + * request function with return value.
  17912. + * @name: Name of the generated function.
  17913. + * @rtype: Type of the request's return value.
  17914. + * @spec: Specification (&struct ssam_request_spec_md) defining the request.
  17915. + *
  17916. + * Defines a function executing the synchronous SAM request specified by
  17917. + * @spec, with the request taking no argument but having a return value of
  17918. + * type @rtype. Device specifying parameters are not hard-coded, but instead
  17919. + * must be provided to the function. The generated function takes care of
  17920. + * setting up the request and response structs, buffer allocation, as well as
  17921. + * execution of the request itself, returning once the request has been fully
  17922. + * completed. The required transport buffer will be allocated on the stack.
  17923. + *
  17924. + * The generated function is defined as ``int name(struct ssam_controller
  17925. + * *ctrl, u8 tid, u8 iid, rtype *ret)``, returning the status of the request,
  17926. + * which is zero on success and negative on failure. The ``ctrl`` parameter is
  17927. + * the controller via which the request is sent, ``tid`` the target ID for the
  17928. + * request, and ``iid`` the instance ID. The request's return value is written
  17929. + * to the memory pointed to by the ``ret`` parameter.
  17930. + *
  17931. + * Refer to ssam_request_sync_onstack() for more details on the behavior of
  17932. + * the generated function.
  17933. + */
  17934. +#define SSAM_DEFINE_SYNC_REQUEST_MD_R(name, rtype, spec...) \
  17935. + int name(struct ssam_controller *ctrl, u8 tid, u8 iid, rtype *ret) \
  17936. + { \
  17937. + struct ssam_request_spec_md s \
  17938. + = (struct ssam_request_spec_md)spec; \
  17939. + struct ssam_request rqst; \
  17940. + struct ssam_response rsp; \
  17941. + int status; \
  17942. + \
  17943. + rqst.target_category = s.target_category; \
  17944. + rqst.target_id = tid; \
  17945. + rqst.command_id = s.command_id; \
  17946. + rqst.instance_id = iid; \
  17947. + rqst.flags = s.flags | SSAM_REQUEST_HAS_RESPONSE; \
  17948. + rqst.length = 0; \
  17949. + rqst.payload = NULL; \
  17950. + \
  17951. + rsp.capacity = sizeof(rtype); \
  17952. + rsp.length = 0; \
  17953. + rsp.pointer = (u8 *)ret; \
  17954. + \
  17955. + status = ssam_request_sync_onstack(ctrl, &rqst, &rsp, 0); \
  17956. + if (status) \
  17957. + return status; \
  17958. + \
  17959. + if (rsp.length != sizeof(rtype)) { \
  17960. + struct device *dev = ssam_controller_device(ctrl); \
  17961. + dev_err(dev, "rqst: invalid response length, expected " \
  17962. + "%zu, got %zu (tc: 0x%02x, cid: 0x%02x)", \
  17963. + sizeof(rtype), rsp.length, rqst.target_category,\
  17964. + rqst.command_id); \
  17965. + return -EIO; \
  17966. + } \
  17967. + \
  17968. + return 0; \
  17969. + }
  17970. +
  17971. +
  17972. +/* -- Event notifier/callbacks. --------------------------------------------- */
  17973. +
  17974. +#define SSAM_NOTIF_STATE_SHIFT 2
  17975. +#define SSAM_NOTIF_STATE_MASK ((1 << SSAM_NOTIF_STATE_SHIFT) - 1)
  17976. +
  17977. +/**
  17978. + * enum ssam_notif_flags - Flags used in return values from SSAM notifier
  17979. + * callback functions.
  17980. + *
  17981. + * @SSAM_NOTIF_HANDLED:
  17982. + * Indicates that the notification has been handled. This flag should be
  17983. + * set by the handler if the handler can act/has acted upon the event
  17984. + * provided to it. This flag should not be set if the handler is not a
  17985. + * primary handler intended for the provided event.
  17986. + *
  17987. + * If this flag has not been set by any handler after the notifier chain
  17988. + * has been traversed, a warning will be emitted, stating that the event
  17989. + * has not been handled.
  17990. + *
  17991. + * @SSAM_NOTIF_STOP:
  17992. + * Indicates that the notifier traversal should stop. If this flag is
  17993. + * returned from a notifier callback, notifier chain traversal will
  17994. + * immediately stop and any remaining notifiers will not be called. This
  17995. + * flag is automatically set when ssam_notifier_from_errno() is called
  17996. + * with a negative error value.
  17997. + */
  17998. +enum ssam_notif_flags {
  17999. + SSAM_NOTIF_HANDLED = BIT(0),
  18000. + SSAM_NOTIF_STOP = BIT(1),
  18001. +};
  18002. +
  18003. +
  18004. +struct ssam_event_notifier;
  18005. +
  18006. +typedef u32 (*ssam_notifier_fn_t)(struct ssam_event_notifier *nf,
  18007. + const struct ssam_event *event);
  18008. +
  18009. +/**
  18010. + * struct ssam_notifier_block - Base notifier block for SSAM event
  18011. + * notifications.
  18012. + * @next: The next notifier block in order of priority.
  18013. + * @fn: The callback function of this notifier. This function takes the
  18014. + * respective notifier block and event as input and should return
  18015. + * a notifier value, which can either be obtained from the flags
  18016. + * provided in &enum ssam_notif_flags, converted from a standard
  18017. + * error value via ssam_notifier_from_errno(), or a combination of
  18018. + * both (e.g. ``ssam_notifier_from_errno(e) | SSAM_NOTIF_HANDLED``).
  18019. + * @priority: Priority value determining the order in which notifier callbacks
  18020. + * will be called. A higher value means higher priority, i.e. the
  18021. + * associated callback will be executed earlier than other (lower
  18022. + * priority) callbacks.
  18023. + */
  18024. +struct ssam_notifier_block {
  18025. + struct ssam_notifier_block __rcu *next;
  18026. + ssam_notifier_fn_t fn;
  18027. + int priority;
  18028. +};
  18029. +
  18030. +/**
  18031. + * ssam_notifier_from_errno() - Convert standard error value to notifier
  18032. + * return code.
  18033. + * @err: The error code to convert, must be negative (in case of failure) or
  18034. + * zero (in case of success).
  18035. + *
  18036. + * Return: Returns the notifier return value obtained by converting the
  18037. + * specified @err value. In case @err is negative, the %SSAM_NOTIF_STOP flag
  18038. + * will be set, causing notifier call chain traversal to abort.
  18039. + */
  18040. +static inline u32 ssam_notifier_from_errno(int err)
  18041. +{
  18042. + if (WARN_ON(err > 0) || err == 0)
  18043. + return 0;
  18044. + else
  18045. + return ((-err) << SSAM_NOTIF_STATE_SHIFT) | SSAM_NOTIF_STOP;
  18046. +}
  18047. +
  18048. +/**
  18049. + * ssam_notifier_to_errno() - Convert notifier return code to standard error
  18050. + * value.
  18051. + * @ret: The notifier return value to convert.
  18052. + *
  18053. + * Return: Returns the negative error value encoded in @ret or zero if @ret
  18054. + * indicates success.
  18055. + */
  18056. +static inline int ssam_notifier_to_errno(u32 ret)
  18057. +{
  18058. + return -(ret >> SSAM_NOTIF_STATE_SHIFT);
  18059. +}
  18060. +
  18061. +
  18062. +/* -- Event/notification registry. ------------------------------------------ */
  18063. +
  18064. +/**
  18065. + * struct ssam_event_registry - Registry specification used for enabling events.
  18066. + * @target_category: Target category for the event registry requests.
  18067. + * @target_id: Target ID for the event registry requests.
  18068. + * @cid_enable: Command ID for the event-enable request.
  18069. + * @cid_disable: Command ID for the event-disable request.
  18070. + *
  18071. + * This struct describes a SAM event registry via the minimal collection of
  18072. + * SAM IDs specifying the requests to use for enabling and disabling an event.
  18073. + * The individual event to be enabled/disabled itself is specified via &struct
  18074. + * ssam_event_id.
  18075. + */
  18076. +struct ssam_event_registry {
  18077. + u8 target_category;
  18078. + u8 target_id;
  18079. + u8 cid_enable;
  18080. + u8 cid_disable;
  18081. +};
  18082. +
  18083. +/**
  18084. + * struct ssam_event_id - Unique event ID used for enabling events.
  18085. + * @target_category: Target category of the event source.
  18086. + * @instance: Instance ID of the event source.
  18087. + *
  18088. + * This struct specifies the event to be enabled/disabled via an externally
  18089. + * provided registry. It does not specify the registry to be used itself, this
  18090. + * is done via &struct ssam_event_registry.
  18091. + */
  18092. +struct ssam_event_id {
  18093. + u8 target_category;
  18094. + u8 instance;
  18095. +};
  18096. +
  18097. +/**
  18098. + * enum ssam_event_mask - Flags specifying how events are matched to notifiers.
  18099. + *
  18100. + * @SSAM_EVENT_MASK_NONE:
  18101. + * Run the callback for any event with matching target category. Do not
  18102. + * do any additional filtering.
  18103. + *
  18104. + * @SSAM_EVENT_MASK_TARGET:
  18105. + * In addition to filtering by target category, only execute the notifier
  18106. + * callback for events with a target ID matching to the one of the
  18107. + * registry used for enabling/disabling the event.
  18108. + *
  18109. + * @SSAM_EVENT_MASK_INSTANCE:
  18110. + * In addition to filtering by target category, only execute the notifier
  18111. + * callback for events with an instance ID matching to the instance ID
  18112. + * used when enabling the event.
  18113. + *
  18114. + * @SSAM_EVENT_MASK_STRICT:
  18115. + * Do all the filtering above.
  18116. + */
  18117. +enum ssam_event_mask {
  18118. + SSAM_EVENT_MASK_TARGET = BIT(0),
  18119. + SSAM_EVENT_MASK_INSTANCE = BIT(1),
  18120. +
  18121. + SSAM_EVENT_MASK_NONE = 0,
  18122. + SSAM_EVENT_MASK_STRICT
  18123. + = SSAM_EVENT_MASK_TARGET
  18124. + | SSAM_EVENT_MASK_INSTANCE,
  18125. +};
  18126. +
  18127. +
  18128. +/**
  18129. + * SSAM_EVENT_REGISTRY() - Define a new event registry.
  18130. + * @tc: Target category for the event registry requests.
  18131. + * @tid: Target ID for the event registry requests.
  18132. + * @cid_en: Command ID for the event-enable request.
  18133. + * @cid_dis: Command ID for the event-disable request.
  18134. + *
  18135. + * Return: Returns the &struct ssam_event_registry specified by the given
  18136. + * parameters.
  18137. + */
  18138. +#define SSAM_EVENT_REGISTRY(tc, tid, cid_en, cid_dis) \
  18139. + ((struct ssam_event_registry) { \
  18140. + .target_category = (tc), \
  18141. + .target_id = (tid), \
  18142. + .cid_enable = (cid_en), \
  18143. + .cid_disable = (cid_dis), \
  18144. + })
  18145. +
  18146. +#define SSAM_EVENT_REGISTRY_SAM \
  18147. + SSAM_EVENT_REGISTRY(SSAM_SSH_TC_SAM, 0x01, 0x0b, 0x0c)
  18148. +
  18149. +#define SSAM_EVENT_REGISTRY_KIP \
  18150. + SSAM_EVENT_REGISTRY(SSAM_SSH_TC_KIP, 0x02, 0x27, 0x28)
  18151. +
  18152. +#define SSAM_EVENT_REGISTRY_REG \
  18153. + SSAM_EVENT_REGISTRY(SSAM_SSH_TC_REG, 0x02, 0x01, 0x02)
  18154. +
  18155. +
  18156. +/**
  18157. + * struct ssam_event_notifier - Notifier block for SSAM events.
  18158. + * @base: The base notifier block with callback function and priority.
  18159. + * @event: The event for which this block will receive notifications.
  18160. + * @event.reg: Registry via which the event will be enabled/disabled.
  18161. + * @event.id: ID specifying the event.
  18162. + * @event.mask: Flags determining how events are matched to the notifier.
  18163. + * @event.flags: Flags used for enabling the event.
  18164. + */
  18165. +struct ssam_event_notifier {
  18166. + struct ssam_notifier_block base;
  18167. +
  18168. + struct {
  18169. + struct ssam_event_registry reg;
  18170. + struct ssam_event_id id;
  18171. + enum ssam_event_mask mask;
  18172. + u8 flags;
  18173. + } event;
  18174. +};
  18175. +
  18176. +int ssam_notifier_register(struct ssam_controller *ctrl,
  18177. + struct ssam_event_notifier *n);
  18178. +
  18179. +int ssam_notifier_unregister(struct ssam_controller *ctrl,
  18180. + struct ssam_event_notifier *n);
  18181. +
  18182. +#endif /* _LINUX_SURFACE_AGGREGATOR_CONTROLLER_H */
  18183. diff --git a/include/linux/surface_aggregator/device.h b/include/linux/surface_aggregator/device.h
  18184. new file mode 100644
  18185. index 000000000000..64b1299d7bd8
  18186. --- /dev/null
  18187. +++ b/include/linux/surface_aggregator/device.h
  18188. @@ -0,0 +1,430 @@
  18189. +/* SPDX-License-Identifier: GPL-2.0+ */
  18190. +/*
  18191. + * Surface System Aggregator Module (SSAM) bus and client-device subsystem.
  18192. + *
  18193. + * Main interface for the surface-aggregator bus, surface-aggregator client
  18194. + * devices, and respective drivers building on top of the SSAM controller.
  18195. + * Provides support for non-platform/non-ACPI SSAM clients via dedicated
  18196. + * subsystem.
  18197. + *
  18198. + * Copyright (C) 2019-2020 Maximilian Luz <luzmaximilian@gmail.com>
  18199. + */
  18200. +
  18201. +#ifndef _LINUX_SURFACE_AGGREGATOR_DEVICE_H
  18202. +#define _LINUX_SURFACE_AGGREGATOR_DEVICE_H
  18203. +
  18204. +#include <linux/device.h>
  18205. +#include <linux/mod_devicetable.h>
  18206. +#include <linux/types.h>
  18207. +
  18208. +#include <linux/surface_aggregator/controller.h>
  18209. +
  18210. +
  18211. +/* -- Surface System Aggregator Module bus. --------------------------------- */
  18212. +
  18213. +/**
  18214. + * enum ssam_device_domain - SAM device domain.
  18215. + * @SSAM_DOMAIN_VIRTUAL: Virtual device.
  18216. + * @SSAM_DOMAIN_SERIALHUB: Physical dovice connected via Surface Serial Hub.
  18217. + */
  18218. +enum ssam_device_domain {
  18219. + SSAM_DOMAIN_VIRTUAL = 0x00,
  18220. + SSAM_DOMAIN_SERIALHUB = 0x01,
  18221. +};
  18222. +
  18223. +/**
  18224. + * enum ssam_virtual_tc - Target categories for the virtual SAM domain.
  18225. + * @SSAM_VIRTUAL_TC_HUB: Device hub category.
  18226. + */
  18227. +enum ssam_virtual_tc {
  18228. + SSAM_VIRTUAL_TC_HUB = 0x00,
  18229. +};
  18230. +
  18231. +/**
  18232. + * struct ssam_device_uid - Unique identifier for SSAM device.
  18233. + * @domain: Domain of the device.
  18234. + * @category: Target category of the device.
  18235. + * @target: Target ID of the device.
  18236. + * @instance: Instance ID of the device.
  18237. + * @function: Sub-function of the device. This field can be used to split a
  18238. + * single SAM device into multiple virtual subdevices to separate
  18239. + * different functionality of that device and allow one driver per
  18240. + * such functionality.
  18241. + */
  18242. +struct ssam_device_uid {
  18243. + u8 domain;
  18244. + u8 category;
  18245. + u8 target;
  18246. + u8 instance;
  18247. + u8 function;
  18248. +};
  18249. +
  18250. +/*
  18251. + * Special values for device matching.
  18252. + *
  18253. + * These values are intended to be used with SSAM_DEVICE(), SSAM_VDEV(), and
  18254. + * SSAM_SDEV() exclusively. Specifically, they are used to initialize the
  18255. + * match_flags member of the device ID structure. Do not use them directly
  18256. + * with struct ssam_device_id or struct ssam_device_uid.
  18257. + */
  18258. +#define SSAM_ANY_TID 0xffff
  18259. +#define SSAM_ANY_IID 0xffff
  18260. +#define SSAM_ANY_FUN 0xffff
  18261. +
  18262. +/**
  18263. + * SSAM_DEVICE() - Initialize a &struct ssam_device_id with the given
  18264. + * parameters.
  18265. + * @d: Domain of the device.
  18266. + * @cat: Target category of the device.
  18267. + * @tid: Target ID of the device.
  18268. + * @iid: Instance ID of the device.
  18269. + * @fun: Sub-function of the device.
  18270. + *
  18271. + * Initializes a &struct ssam_device_id with the given parameters. See &struct
  18272. + * ssam_device_uid for details regarding the parameters. The special values
  18273. + * %SSAM_ANY_TID, %SSAM_ANY_IID, and %SSAM_ANY_FUN can be used to specify that
  18274. + * matching should ignore target ID, instance ID, and/or sub-function,
  18275. + * respectively. This macro initializes the ``match_flags`` field based on the
  18276. + * given parameters.
  18277. + *
  18278. + * Note: The parameters @d and @cat must be valid &u8 values, the parameters
  18279. + * @tid, @iid, and @fun must be either valid &u8 values or %SSAM_ANY_TID,
  18280. + * %SSAM_ANY_IID, or %SSAM_ANY_FUN, respectively. Other non-&u8 values are not
  18281. + * allowed.
  18282. + */
  18283. +#define SSAM_DEVICE(d, cat, tid, iid, fun) \
  18284. + .match_flags = (((tid) != SSAM_ANY_TID) ? SSAM_MATCH_TARGET : 0) \
  18285. + | (((iid) != SSAM_ANY_IID) ? SSAM_MATCH_INSTANCE : 0) \
  18286. + | (((fun) != SSAM_ANY_FUN) ? SSAM_MATCH_FUNCTION : 0), \
  18287. + .domain = d, \
  18288. + .category = cat, \
  18289. + .target = ((tid) != SSAM_ANY_TID) ? (tid) : 0, \
  18290. + .instance = ((iid) != SSAM_ANY_IID) ? (iid) : 0, \
  18291. + .function = ((fun) != SSAM_ANY_FUN) ? (fun) : 0 \
  18292. +
  18293. +/**
  18294. + * SSAM_VDEV() - Initialize a &struct ssam_device_id as virtual device with
  18295. + * the given parameters.
  18296. + * @cat: Target category of the device.
  18297. + * @tid: Target ID of the device.
  18298. + * @iid: Instance ID of the device.
  18299. + * @fun: Sub-function of the device.
  18300. + *
  18301. + * Initializes a &struct ssam_device_id with the given parameters in the
  18302. + * virtual domain. See &struct ssam_device_uid for details regarding the
  18303. + * parameters. The special values %SSAM_ANY_TID, %SSAM_ANY_IID, and
  18304. + * %SSAM_ANY_FUN can be used to specify that matching should ignore target ID,
  18305. + * instance ID, and/or sub-function, respectively. This macro initializes the
  18306. + * ``match_flags`` field based on the given parameters.
  18307. + *
  18308. + * Note: The parameter @cat must be a valid &u8 value, the parameters @tid,
  18309. + * @iid, and @fun must be either valid &u8 values or %SSAM_ANY_TID,
  18310. + * %SSAM_ANY_IID, or %SSAM_ANY_FUN, respectively. Other non-&u8 values are not
  18311. + * allowed.
  18312. + */
  18313. +#define SSAM_VDEV(cat, tid, iid, fun) \
  18314. + SSAM_DEVICE(SSAM_DOMAIN_VIRTUAL, SSAM_VIRTUAL_TC_##cat, tid, iid, fun)
  18315. +
  18316. +
  18317. +/**
  18318. + * SSAM_SDEV() - Initialize a &struct ssam_device_id as physical SSH device
  18319. + * with the given parameters.
  18320. + * @cat: Target category of the device.
  18321. + * @tid: Target ID of the device.
  18322. + * @iid: Instance ID of the device.
  18323. + * @fun: Sub-function of the device.
  18324. + *
  18325. + * Initializes a &struct ssam_device_id with the given parameters in the SSH
  18326. + * domain. See &struct ssam_device_uid for details regarding the parameters.
  18327. + * The special values %SSAM_ANY_TID, %SSAM_ANY_IID, and %SSAM_ANY_FUN can be
  18328. + * used to specify that matching should ignore target ID, instance ID, and/or
  18329. + * sub-function, respectively. This macro initializes the ``match_flags``
  18330. + * field based on the given parameters.
  18331. + *
  18332. + * Note: The parameter @cat must be a valid &u8 value, the parameters @tid,
  18333. + * @iid, and @fun must be either valid &u8 values or %SSAM_ANY_TID,
  18334. + * %SSAM_ANY_IID, or %SSAM_ANY_FUN, respectively. Other non-&u8 values are not
  18335. + * allowed.
  18336. + */
  18337. +#define SSAM_SDEV(cat, tid, iid, fun) \
  18338. + SSAM_DEVICE(SSAM_DOMAIN_SERIALHUB, SSAM_SSH_TC_##cat, tid, iid, fun)
  18339. +
  18340. +
  18341. +/**
  18342. + * struct ssam_device - SSAM client device.
  18343. + * @dev: Driver model representation of the device.
  18344. + * @ctrl: SSAM controller managing this device.
  18345. + * @uid: UID identifying the device.
  18346. + */
  18347. +struct ssam_device {
  18348. + struct device dev;
  18349. + struct ssam_controller *ctrl;
  18350. +
  18351. + struct ssam_device_uid uid;
  18352. +};
  18353. +
  18354. +/**
  18355. + * struct ssam_device_driver - SSAM client device driver.
  18356. + * @driver: Base driver model structure.
  18357. + * @match_table: Match table specifying which devices the driver should bind to.
  18358. + * @probe: Called when the driver is being bound to a device.
  18359. + * @remove: Called when the driver is being unbound from the device.
  18360. + */
  18361. +struct ssam_device_driver {
  18362. + struct device_driver driver;
  18363. +
  18364. + const struct ssam_device_id *match_table;
  18365. +
  18366. + int (*probe)(struct ssam_device *sdev);
  18367. + void (*remove)(struct ssam_device *sdev);
  18368. +};
  18369. +
  18370. +extern struct bus_type ssam_bus_type;
  18371. +extern const struct device_type ssam_device_type;
  18372. +
  18373. +
  18374. +/**
  18375. + * is_ssam_device() - Check if the given device is a SSAM client device.
  18376. + * @d: The device to test the type of.
  18377. + *
  18378. + * Return: Returns %true iff the specified device is of type &struct
  18379. + * ssam_device, i.e. the device type points to %ssam_device_type, and %false
  18380. + * otherwise.
  18381. + */
  18382. +static inline bool is_ssam_device(struct device *d)
  18383. +{
  18384. + return d->type == &ssam_device_type;
  18385. +}
  18386. +
  18387. +/**
  18388. + * to_ssam_device() - Casts the given device to a SSAM client device.
  18389. + * @d: The device to cast.
  18390. + *
  18391. + * Casts the given &struct device to a &struct ssam_device. The caller has to
  18392. + * ensure that the given device is actually enclosed in a &struct ssam_device,
  18393. + * e.g. by calling is_ssam_device().
  18394. + *
  18395. + * Return: Returns a pointer to the &struct ssam_device wrapping the given
  18396. + * device @d.
  18397. + */
  18398. +static inline struct ssam_device *to_ssam_device(struct device *d)
  18399. +{
  18400. + return container_of(d, struct ssam_device, dev);
  18401. +}
  18402. +
  18403. +/**
  18404. + * to_ssam_device_driver() - Casts the given device driver to a SSAM client
  18405. + * device driver.
  18406. + * @d: The driver to cast.
  18407. + *
  18408. + * Casts the given &struct device_driver to a &struct ssam_device_driver. The
  18409. + * caller has to ensure that the given driver is actually enclosed in a
  18410. + * &struct ssam_device_driver.
  18411. + *
  18412. + * Return: Returns the pointer to the &struct ssam_device_driver wrapping the
  18413. + * given device driver @d.
  18414. + */
  18415. +static inline
  18416. +struct ssam_device_driver *to_ssam_device_driver(struct device_driver *d)
  18417. +{
  18418. + return container_of(d, struct ssam_device_driver, driver);
  18419. +}
  18420. +
  18421. +
  18422. +const struct ssam_device_id *ssam_device_id_match(
  18423. + const struct ssam_device_id *table,
  18424. + const struct ssam_device_uid uid);
  18425. +
  18426. +const struct ssam_device_id *ssam_device_get_match(
  18427. + const struct ssam_device *dev);
  18428. +
  18429. +const void *ssam_device_get_match_data(const struct ssam_device *dev);
  18430. +
  18431. +struct ssam_device *ssam_device_alloc(struct ssam_controller *ctrl,
  18432. + struct ssam_device_uid uid);
  18433. +
  18434. +int ssam_device_add(struct ssam_device *sdev);
  18435. +void ssam_device_remove(struct ssam_device *sdev);
  18436. +
  18437. +/**
  18438. + * ssam_device_get() - Increment reference count of SSAM client device.
  18439. + * @sdev: The device to increment the reference count of.
  18440. + *
  18441. + * Increments the reference count of the given SSAM client device by
  18442. + * incrementing the reference count of the enclosed &struct device via
  18443. + * get_device().
  18444. + *
  18445. + * See ssam_device_put() for the counter-part of this function.
  18446. + *
  18447. + * Return: Returns the device provided as input.
  18448. + */
  18449. +static inline struct ssam_device *ssam_device_get(struct ssam_device *sdev)
  18450. +{
  18451. + return sdev ? to_ssam_device(get_device(&sdev->dev)) : NULL;
  18452. +}
  18453. +
  18454. +/**
  18455. + * ssam_device_put() - Decrement reference count of SSAM client device.
  18456. + * @sdev: The device to decrement the reference count of.
  18457. + *
  18458. + * Decrements the reference count of the given SSAM client device by
  18459. + * decrementing the reference count of the enclosed &struct device via
  18460. + * put_device().
  18461. + *
  18462. + * See ssam_device_get() for the counter-part of this function.
  18463. + */
  18464. +static inline void ssam_device_put(struct ssam_device *sdev)
  18465. +{
  18466. + if (sdev)
  18467. + put_device(&sdev->dev);
  18468. +}
  18469. +
  18470. +/**
  18471. + * ssam_device_get_drvdata() - Get driver-data of SSAM client device.
  18472. + * @sdev: The device to get the driver-data from.
  18473. + *
  18474. + * Return: Returns the driver-data of the given device, previously set via
  18475. + * ssam_device_set_drvdata().
  18476. + */
  18477. +static inline void *ssam_device_get_drvdata(struct ssam_device *sdev)
  18478. +{
  18479. + return dev_get_drvdata(&sdev->dev);
  18480. +}
  18481. +
  18482. +/**
  18483. + * ssam_device_set_drvdata() - Set driver-data of SSAM client device.
  18484. + * @sdev: The device to set the driver-data of.
  18485. + * @data: The data to set the device's driver-data pointer to.
  18486. + */
  18487. +static inline void ssam_device_set_drvdata(struct ssam_device *sdev, void *data)
  18488. +{
  18489. + dev_set_drvdata(&sdev->dev, data);
  18490. +}
  18491. +
  18492. +
  18493. +int __ssam_device_driver_register(struct ssam_device_driver *d, struct module *o);
  18494. +void ssam_device_driver_unregister(struct ssam_device_driver *d);
  18495. +
  18496. +/**
  18497. + * ssam_device_driver_register() - Register a SSAM client device driver.
  18498. + * @drv: The driver to register.
  18499. + */
  18500. +#define ssam_device_driver_register(drv) \
  18501. + __ssam_device_driver_register(drv, THIS_MODULE)
  18502. +
  18503. +/**
  18504. + * module_ssam_device_driver() - Helper macro for SSAM device driver
  18505. + * registration.
  18506. + * @drv: The driver managed by this module.
  18507. + *
  18508. + * Helper macro to register a SSAM device driver via module_init() and
  18509. + * module_exit(). This macro may only be used once per module and replaces
  18510. + * the afforementioned definitions.
  18511. + */
  18512. +#define module_ssam_device_driver(drv) \
  18513. + module_driver(drv, ssam_device_driver_register, \
  18514. + ssam_device_driver_unregister)
  18515. +
  18516. +
  18517. +/* -- Helpers for client-device requests. ----------------------------------- */
  18518. +
  18519. +/**
  18520. + * SSAM_DEFINE_SYNC_REQUEST_CL_N() - Define synchronous client-device SAM
  18521. + * request function with neither argument nor return value.
  18522. + * @name: Name of the generated function.
  18523. + * @spec: Specification (&struct ssam_request_spec_md) defining the request.
  18524. + *
  18525. + * Defines a function executing the synchronous SAM request specified by
  18526. + * @spec, with the request having neither argument nor return value. Device
  18527. + * specifying parameters are not hard-coded, but instead are provided via the
  18528. + * client device, specifically its UID, supplied when calling this function.
  18529. + * The generated function takes care of setting up the request struct, buffer
  18530. + * allocation, as well as execution of the request itself, returning once the
  18531. + * request has been fully completed. The required transport buffer will be
  18532. + * allocated on the stack.
  18533. + *
  18534. + * The generated function is defined as ``int name(struct ssam_device *sdev)``,
  18535. + * returning the status of the request, which is zero on success and negative
  18536. + * on failure. The ``sdev`` parameter specifies both the target device of the
  18537. + * request and by association the controller via which the request is sent.
  18538. + *
  18539. + * Refer to ssam_request_sync_onstack() for more details on the behavior of
  18540. + * the generated function.
  18541. + */
  18542. +#define SSAM_DEFINE_SYNC_REQUEST_CL_N(name, spec...) \
  18543. + SSAM_DEFINE_SYNC_REQUEST_MD_N(__raw_##name, spec) \
  18544. + int name(struct ssam_device *sdev) \
  18545. + { \
  18546. + return __raw_##name(sdev->ctrl, sdev->uid.target, \
  18547. + sdev->uid.instance); \
  18548. + }
  18549. +
  18550. +/**
  18551. + * SSAM_DEFINE_SYNC_REQUEST_CL_W() - Define synchronous client-device SAM
  18552. + * request function with argument.
  18553. + * @name: Name of the generated function.
  18554. + * @atype: Type of the request's argument.
  18555. + * @spec: Specification (&struct ssam_request_spec_md) defining the request.
  18556. + *
  18557. + * Defines a function executing the synchronous SAM request specified by
  18558. + * @spec, with the request taking an argument of type @atype and having no
  18559. + * return value. Device specifying parameters are not hard-coded, but instead
  18560. + * are provided via the client device, specifically its UID, supplied when
  18561. + * calling this function. The generated function takes care of setting up the
  18562. + * request struct, buffer allocation, as well as execution of the request
  18563. + * itself, returning once the request has been fully completed. The required
  18564. + * transport buffer will be allocated on the stack.
  18565. + *
  18566. + * The generated function is defined as ``int name(struct ssam_device *sdev,
  18567. + * const atype *arg)``, returning the status of the request, which is zero on
  18568. + * success and negative on failure. The ``sdev`` parameter specifies both the
  18569. + * target device of the request and by association the controller via which
  18570. + * the request is sent. The request's argument is specified via the ``arg``
  18571. + * pointer.
  18572. + *
  18573. + * Refer to ssam_request_sync_onstack() for more details on the behavior of
  18574. + * the generated function.
  18575. + */
  18576. +#define SSAM_DEFINE_SYNC_REQUEST_CL_W(name, atype, spec...) \
  18577. + SSAM_DEFINE_SYNC_REQUEST_MD_W(__raw_##name, atype, spec) \
  18578. + int name(struct ssam_device *sdev, const atype *arg) \
  18579. + { \
  18580. + return __raw_##name(sdev->ctrl, sdev->uid.target, \
  18581. + sdev->uid.instance, arg); \
  18582. + }
  18583. +
  18584. +/**
  18585. + * SSAM_DEFINE_SYNC_REQUEST_CL_R() - Define synchronous client-device SAM
  18586. + * request function with return value.
  18587. + * @name: Name of the generated function.
  18588. + * @rtype: Type of the request's return value.
  18589. + * @spec: Specification (&struct ssam_request_spec_md) defining the request.
  18590. + *
  18591. + * Defines a function executing the synchronous SAM request specified by
  18592. + * @spec, with the request taking no argument but having a return value of
  18593. + * type @rtype. Device specifying parameters are not hard-coded, but instead
  18594. + * are provided via the client device, specifically its UID, supplied when
  18595. + * calling this function. The generated function takes care of setting up the
  18596. + * request struct, buffer allocation, as well as execution of the request
  18597. + * itself, returning once the request has been fully completed. The required
  18598. + * transport buffer will be allocated on the stack.
  18599. + *
  18600. + * The generated function is defined as ``int name(struct ssam_device *sdev,
  18601. + * rtype *ret)``, returning the status of the request, which is zero on
  18602. + * success and negative on failure. The ``sdev`` parameter specifies both the
  18603. + * target device of the request and by association the controller via which
  18604. + * the request is sent. The request's return value is written to the memory
  18605. + * pointed to by the ``ret`` parameter.
  18606. + *
  18607. + * Refer to ssam_request_sync_onstack() for more details on the behavior of
  18608. + * the generated function.
  18609. + */
  18610. +#define SSAM_DEFINE_SYNC_REQUEST_CL_R(name, rtype, spec...) \
  18611. + SSAM_DEFINE_SYNC_REQUEST_MD_R(__raw_##name, rtype, spec) \
  18612. + int name(struct ssam_device *sdev, rtype *ret) \
  18613. + { \
  18614. + return __raw_##name(sdev->ctrl, sdev->uid.target, \
  18615. + sdev->uid.instance, ret); \
  18616. + }
  18617. +
  18618. +#endif /* _LINUX_SURFACE_AGGREGATOR_DEVICE_H */
  18619. diff --git a/include/linux/surface_aggregator/serial_hub.h b/include/linux/surface_aggregator/serial_hub.h
  18620. new file mode 100644
  18621. index 000000000000..376313f402b2
  18622. --- /dev/null
  18623. +++ b/include/linux/surface_aggregator/serial_hub.h
  18624. @@ -0,0 +1,659 @@
  18625. +/* SPDX-License-Identifier: GPL-2.0+ */
  18626. +/*
  18627. + * Surface Serial Hub (SSH) protocol and communication interface.
  18628. + *
  18629. + * Lower-level communication layers and SSH protocol definitions for the
  18630. + * Surface System Aggregator Module (SSAM). Provides the interface for basic
  18631. + * packet- and request-based communication with the SSAM EC via SSH.
  18632. + *
  18633. + * Copyright (C) 2019-2020 Maximilian Luz <luzmaximilian@gmail.com>
  18634. + */
  18635. +
  18636. +#ifndef _LINUX_SURFACE_AGGREGATOR_SERIAL_HUB_H
  18637. +#define _LINUX_SURFACE_AGGREGATOR_SERIAL_HUB_H
  18638. +
  18639. +#include <linux/crc-ccitt.h>
  18640. +#include <linux/kref.h>
  18641. +#include <linux/ktime.h>
  18642. +#include <linux/list.h>
  18643. +#include <linux/types.h>
  18644. +
  18645. +
  18646. +/* -- Data structures for SAM-over-SSH communication. ----------------------- */
  18647. +
  18648. +/**
  18649. + * enum ssh_frame_type - Frame types for SSH frames.
  18650. + *
  18651. + * @SSH_FRAME_TYPE_DATA_SEQ:
  18652. + * Indicates a data frame, followed by a payload with the length specified
  18653. + * in the ``struct ssh_frame.len`` field. This frame is sequenced, meaning
  18654. + * that an ACK is required.
  18655. + *
  18656. + * @SSH_FRAME_TYPE_DATA_NSQ:
  18657. + * Same as %SSH_FRAME_TYPE_DATA_SEQ, but unsequenced, meaning that the
  18658. + * message does not have to be ACKed.
  18659. + *
  18660. + * @SSH_FRAME_TYPE_ACK:
  18661. + * Indicates an ACK message.
  18662. + *
  18663. + * @SSH_FRAME_TYPE_NAK:
  18664. + * Indicates an error response for previously sent frame. In general, this
  18665. + * means that the frame and/or payload is malformed, e.g. a CRC is wrong.
  18666. + * For command-type payloads, this can also mean that the command is
  18667. + * invalid.
  18668. + */
  18669. +enum ssh_frame_type {
  18670. + SSH_FRAME_TYPE_DATA_SEQ = 0x80,
  18671. + SSH_FRAME_TYPE_DATA_NSQ = 0x00,
  18672. + SSH_FRAME_TYPE_ACK = 0x40,
  18673. + SSH_FRAME_TYPE_NAK = 0x04,
  18674. +};
  18675. +
  18676. +/**
  18677. + * struct ssh_frame - SSH communication frame.
  18678. + * @type: The type of the frame. See &enum ssh_frame_type.
  18679. + * @len: The length of the frame payload directly following the CRC for this
  18680. + * frame. Does not include the final CRC for that payload.
  18681. + * @seq: The sequence number for this message/exchange.
  18682. + */
  18683. +struct ssh_frame {
  18684. + u8 type;
  18685. + __le16 len;
  18686. + u8 seq;
  18687. +} __packed;
  18688. +
  18689. +static_assert(sizeof(struct ssh_frame) == 4);
  18690. +
  18691. +/*
  18692. + * SSH_FRAME_MAX_PAYLOAD_SIZE - Maximum SSH frame payload length in bytes.
  18693. + *
  18694. + * This is the physical maximum length of the protocol. Implementations may
  18695. + * set a more constrained limit.
  18696. + */
  18697. +#define SSH_FRAME_MAX_PAYLOAD_SIZE U16_MAX
  18698. +
  18699. +/**
  18700. + * enum ssh_payload_type - Type indicator for the SSH payload.
  18701. + * @SSH_PLD_TYPE_CMD: The payload is a command structure with optional command
  18702. + * payload.
  18703. + */
  18704. +enum ssh_payload_type {
  18705. + SSH_PLD_TYPE_CMD = 0x80,
  18706. +};
  18707. +
  18708. +/**
  18709. + * struct ssh_command - Payload of a command-type frame.
  18710. + * @type: The type of the payload. See &enum ssh_payload_type. Should be
  18711. + * SSH_PLD_TYPE_CMD for this struct.
  18712. + * @tc: Command target category.
  18713. + * @tid_out: Output target ID. Should be zero if this an incoming (EC to host)
  18714. + * message.
  18715. + * @tid_in: Input target ID. Should be zero if this is an outgoing (host to
  18716. + * EC) message.
  18717. + * @iid: Instance ID.
  18718. + * @rqid: Request ID. Used to match requests with responses and differentiate
  18719. + * between responses and events.
  18720. + * @cid: Command ID.
  18721. + */
  18722. +struct ssh_command {
  18723. + u8 type;
  18724. + u8 tc;
  18725. + u8 tid_out;
  18726. + u8 tid_in;
  18727. + u8 iid;
  18728. + __le16 rqid;
  18729. + u8 cid;
  18730. +} __packed;
  18731. +
  18732. +static_assert(sizeof(struct ssh_command) == 8);
  18733. +
  18734. +/*
  18735. + * SSH_COMMAND_MAX_PAYLOAD_SIZE - Maximum SSH command payload length in bytes.
  18736. + *
  18737. + * This is the physical maximum length of the protocol. Implementations may
  18738. + * set a more constrained limit.
  18739. + */
  18740. +#define SSH_COMMAND_MAX_PAYLOAD_SIZE \
  18741. + (SSH_FRAME_MAX_PAYLOAD_SIZE - sizeof(struct ssh_command))
  18742. +
  18743. +/*
  18744. + * SSH_MSG_LEN_BASE - Base-length of a SSH message.
  18745. + *
  18746. + * This is the minimum number of bytes required to form a message. The actual
  18747. + * message length is SSH_MSG_LEN_BASE plus the length of the frame payload.
  18748. + */
  18749. +#define SSH_MSG_LEN_BASE (sizeof(struct ssh_frame) + 3ull * sizeof(u16))
  18750. +
  18751. +/*
  18752. + * SSH_MSG_LEN_CTRL - Length of a SSH control message.
  18753. + *
  18754. + * This is the length of a SSH control message, which is equal to a SSH
  18755. + * message without any payload.
  18756. + */
  18757. +#define SSH_MSG_LEN_CTRL SSH_MSG_LEN_BASE
  18758. +
  18759. +/**
  18760. + * SSH_MESSAGE_LENGTH() - Comute length of SSH message.
  18761. + * @payload_size: Length of the payload inside the SSH frame.
  18762. + *
  18763. + * Return: Returns the length of a SSH message with payload of specified size.
  18764. + */
  18765. +#define SSH_MESSAGE_LENGTH(payload_size) (SSH_MSG_LEN_BASE + payload_size)
  18766. +
  18767. +/**
  18768. + * SSH_COMMAND_MESSAGE_LENGTH() - Compute length of SSH command message.
  18769. + * @payload_size: Length of the command payload.
  18770. + *
  18771. + * Return: Returns the length of a SSH command message with command payload of
  18772. + * specified size.
  18773. + */
  18774. +#define SSH_COMMAND_MESSAGE_LENGTH(payload_size) \
  18775. + SSH_MESSAGE_LENGTH(sizeof(struct ssh_command) + payload_size)
  18776. +
  18777. +/**
  18778. + * SSH_MSGOFFSET_FRAME() - Compute offset in SSH message to specified field in
  18779. + * frame.
  18780. + * @field: The field for which the offset should be computed.
  18781. + *
  18782. + * Return: Returns the offset of the specified &struct ssh_frame field in the
  18783. + * raw SSH message data as.
  18784. + */
  18785. +#define SSH_MSGOFFSET_FRAME(field) \
  18786. + (sizeof(u16) + offsetof(struct ssh_frame, field))
  18787. +
  18788. +/**
  18789. + * SSH_MSGOFFSET_COMMAND() - Compute offset in SSH message to specified field
  18790. + * in command.
  18791. + * @field: The field for which the offset should be computed.
  18792. + *
  18793. + * Return: Returns the offset of the specified &struct ssh_command field in
  18794. + * the raw SSH message data.
  18795. + */
  18796. +#define SSH_MSGOFFSET_COMMAND(field) \
  18797. + (2ull * sizeof(u16) + sizeof(struct ssh_frame) \
  18798. + + offsetof(struct ssh_command, field))
  18799. +
  18800. +/*
  18801. + * SSH_MSG_SYN - SSH message synchronization (SYN) bytes as u16.
  18802. + */
  18803. +#define SSH_MSG_SYN ((u16)0x55aa)
  18804. +
  18805. +/**
  18806. + * ssh_crc() - Compute CRC for SSH messages.
  18807. + * @buf: The pointer pointing to the data for which the CRC should be computed.
  18808. + * @len: The length of the data for which the CRC should be computed.
  18809. + *
  18810. + * Return: Returns the CRC computed on the provided data, as used for SSH
  18811. + * messages.
  18812. + */
  18813. +static inline u16 ssh_crc(const u8 *buf, size_t len)
  18814. +{
  18815. + return crc_ccitt_false(0xffff, buf, len);
  18816. +}
  18817. +
  18818. +/*
  18819. + * SSH_NUM_EVENTS - The number of reserved event IDs.
  18820. + *
  18821. + * The number of reserved event IDs, used for registering an SSH event
  18822. + * handler. Valid event IDs are numbers below or equal to this value, with
  18823. + * exception of zero, which is not an event ID. Thus, this is also the
  18824. + * absolute maximum number of event handlers that can be registered.
  18825. + */
  18826. +#define SSH_NUM_EVENTS 34
  18827. +
  18828. +/*
  18829. + * SSH_NUM_TARGETS - The number of communication targets used in the protocol.
  18830. + */
  18831. +#define SSH_NUM_TARGETS 2
  18832. +
  18833. +/**
  18834. + * ssh_rqid_next_valid() - Return the next valid request ID.
  18835. + * @rqid: The current request ID.
  18836. + *
  18837. + * Return: Returns the next valid request ID, following the current request ID
  18838. + * provided to this function. This function skips any request IDs reserved for
  18839. + * events.
  18840. + */
  18841. +static inline u16 ssh_rqid_next_valid(u16 rqid)
  18842. +{
  18843. + return rqid > 0 ? rqid + 1u : rqid + SSH_NUM_EVENTS + 1u;
  18844. +}
  18845. +
  18846. +/**
  18847. + * ssh_rqid_to_event() - Convert request ID to its corresponding event ID.
  18848. + * @rqid: The request ID to convert.
  18849. + */
  18850. +static inline u16 ssh_rqid_to_event(u16 rqid)
  18851. +{
  18852. + return rqid - 1u;
  18853. +}
  18854. +
  18855. +/**
  18856. + * ssh_rqid_is_event() - Check if given request ID is a valid event ID.
  18857. + * @rqid: The request ID to check.
  18858. + */
  18859. +static inline bool ssh_rqid_is_event(u16 rqid)
  18860. +{
  18861. + return ssh_rqid_to_event(rqid) < SSH_NUM_EVENTS;
  18862. +}
  18863. +
  18864. +/**
  18865. + * ssh_tc_to_rqid() - Convert target category to its corresponding request ID.
  18866. + * @tc: The target category to convert.
  18867. + */
  18868. +static inline u16 ssh_tc_to_rqid(u8 tc)
  18869. +{
  18870. + return tc;
  18871. +}
  18872. +
  18873. +/**
  18874. + * ssh_tid_to_index() - Convert target ID to its corresponding target index.
  18875. + * @tid: The target ID to convert.
  18876. + */
  18877. +static inline u8 ssh_tid_to_index(u8 tid)
  18878. +{
  18879. + return tid - 1u;
  18880. +}
  18881. +
  18882. +/**
  18883. + * ssh_tid_is_valid() - Check if target ID is valid/supported.
  18884. + * @tid: The target ID to check.
  18885. + */
  18886. +static inline bool ssh_tid_is_valid(u8 tid)
  18887. +{
  18888. + return ssh_tid_to_index(tid) < SSH_NUM_TARGETS;
  18889. +}
  18890. +
  18891. +/**
  18892. + * struct ssam_span - Reference to a buffer region.
  18893. + * @ptr: Pointer to the buffer region.
  18894. + * @len: Length of the buffer region.
  18895. + *
  18896. + * A reference to a (non-owned) buffer segment, consisting of pointer and
  18897. + * length. Use of this struct indicates non-owned data, i.e. data of which the
  18898. + * life-time is managed (i.e. it is allocated/freed) via another pointer.
  18899. + */
  18900. +struct ssam_span {
  18901. + u8 *ptr;
  18902. + size_t len;
  18903. +};
  18904. +
  18905. +enum ssam_ssh_tc {
  18906. + /* Known SSH/EC target categories. */
  18907. + // category 0x00 is invalid for EC use
  18908. + SSAM_SSH_TC_SAM = 0x01, // generic system functionality, real-time clock
  18909. + SSAM_SSH_TC_BAT = 0x02, // battery/power subsystem
  18910. + SSAM_SSH_TC_TMP = 0x03, // thermal subsystem
  18911. + SSAM_SSH_TC_PMC = 0x04,
  18912. + SSAM_SSH_TC_FAN = 0x05,
  18913. + SSAM_SSH_TC_PoM = 0x06,
  18914. + SSAM_SSH_TC_DBG = 0x07,
  18915. + SSAM_SSH_TC_KBD = 0x08, // legacy keyboard (Laptop 1/2)
  18916. + SSAM_SSH_TC_FWU = 0x09,
  18917. + SSAM_SSH_TC_UNI = 0x0a,
  18918. + SSAM_SSH_TC_LPC = 0x0b,
  18919. + SSAM_SSH_TC_TCL = 0x0c,
  18920. + SSAM_SSH_TC_SFL = 0x0d,
  18921. + SSAM_SSH_TC_KIP = 0x0e,
  18922. + SSAM_SSH_TC_EXT = 0x0f,
  18923. + SSAM_SSH_TC_BLD = 0x10,
  18924. + SSAM_SSH_TC_BAS = 0x11, // detachment system (Surface Book 2/3)
  18925. + SSAM_SSH_TC_SEN = 0x12,
  18926. + SSAM_SSH_TC_SRQ = 0x13,
  18927. + SSAM_SSH_TC_MCU = 0x14,
  18928. + SSAM_SSH_TC_HID = 0x15, // generic HID input subsystem
  18929. + SSAM_SSH_TC_TCH = 0x16,
  18930. + SSAM_SSH_TC_BKL = 0x17,
  18931. + SSAM_SSH_TC_TAM = 0x18,
  18932. + SSAM_SSH_TC_ACC = 0x19,
  18933. + SSAM_SSH_TC_UFI = 0x1a,
  18934. + SSAM_SSH_TC_USC = 0x1b,
  18935. + SSAM_SSH_TC_PEN = 0x1c,
  18936. + SSAM_SSH_TC_VID = 0x1d,
  18937. + SSAM_SSH_TC_AUD = 0x1e,
  18938. + SSAM_SSH_TC_SMC = 0x1f,
  18939. + SSAM_SSH_TC_KPD = 0x20,
  18940. + SSAM_SSH_TC_REG = 0x21,
  18941. +};
  18942. +
  18943. +
  18944. +/* -- Packet transport layer (ptl). ----------------------------------------- */
  18945. +
  18946. +/**
  18947. + * enum ssh_packet_base_priority - Base priorities for &struct ssh_packet.
  18948. + * @SSH_PACKET_PRIORITY_FLUSH: Base priority for flush packets.
  18949. + * @SSH_PACKET_PRIORITY_DATA: Base priority for normal data paackets.
  18950. + * @SSH_PACKET_PRIORITY_NAK: Base priority for NAK packets.
  18951. + * @SSH_PACKET_PRIORITY_ACK: Base priority for ACK packets.
  18952. + */
  18953. +enum ssh_packet_base_priority {
  18954. + SSH_PACKET_PRIORITY_FLUSH = 0, /* same as DATA to sequence flush */
  18955. + SSH_PACKET_PRIORITY_DATA = 0,
  18956. + SSH_PACKET_PRIORITY_NAK = 1,
  18957. + SSH_PACKET_PRIORITY_ACK = 2,
  18958. +};
  18959. +
  18960. +/*
  18961. + * Same as SSH_PACKET_PRIORITY() below, only with actual values.
  18962. + */
  18963. +#define __SSH_PACKET_PRIORITY(base, try) \
  18964. + (((base) << 4) | ((try) & 0x0f))
  18965. +
  18966. +/**
  18967. + * SSH_PACKET_PRIORITY() - Compute packet priority from base priority and
  18968. + * number of tries.
  18969. + * @base: The base priority as suffix of &enum ssh_packet_base_priority, e.g.
  18970. + * ``FLUSH``, ``DATA``, ``ACK``, or ``NAK``.
  18971. + * @try: The number of tries (must be less than 16).
  18972. + *
  18973. + * Compute the combined packet priority. The combined priority is dominated by
  18974. + * the base priority, whereas the number of (re-)tries decides the precedence
  18975. + * of packets with the same base priority, giving higher priority to packets
  18976. + * that already have more tries.
  18977. + *
  18978. + * Return: Returns the computed priority as value fitting inside a &u8. A
  18979. + * higher number means a higher priority.
  18980. + */
  18981. +#define SSH_PACKET_PRIORITY(base, try) \
  18982. + __SSH_PACKET_PRIORITY(SSH_PACKET_PRIORITY_##base, (try))
  18983. +
  18984. +/**
  18985. + * ssh_packet_priority_get_try() - Get number of tries from packet priority.
  18986. + * @priority: The packet priority.
  18987. + *
  18988. + * Return: Returns the number of tries encoded in the specified packet
  18989. + * priority.
  18990. + */
  18991. +static inline u8 ssh_packet_priority_get_try(u8 priority)
  18992. +{
  18993. + return priority & 0x0f;
  18994. +}
  18995. +
  18996. +/**
  18997. + * ssh_packet_priority_get_base - Get base priority from packet priority.
  18998. + * @priority: The packet priority.
  18999. + *
  19000. + * Return: Returns the base priority encoded in the given packet priority.
  19001. + */
  19002. +static inline u8 ssh_packet_priority_get_base(u8 priority)
  19003. +{
  19004. + return (priority & 0xf0) >> 4;
  19005. +}
  19006. +
  19007. +
  19008. +enum ssh_packet_flags {
  19009. + /* state flags */
  19010. + SSH_PACKET_SF_LOCKED_BIT,
  19011. + SSH_PACKET_SF_QUEUED_BIT,
  19012. + SSH_PACKET_SF_PENDING_BIT,
  19013. + SSH_PACKET_SF_TRANSMITTING_BIT,
  19014. + SSH_PACKET_SF_TRANSMITTED_BIT,
  19015. + SSH_PACKET_SF_ACKED_BIT,
  19016. + SSH_PACKET_SF_CANCELED_BIT,
  19017. + SSH_PACKET_SF_COMPLETED_BIT,
  19018. +
  19019. + /* type flags */
  19020. + SSH_PACKET_TY_FLUSH_BIT,
  19021. + SSH_PACKET_TY_SEQUENCED_BIT,
  19022. + SSH_PACKET_TY_BLOCKING_BIT,
  19023. +
  19024. + /* mask for state flags */
  19025. + SSH_PACKET_FLAGS_SF_MASK =
  19026. + BIT(SSH_PACKET_SF_LOCKED_BIT)
  19027. + | BIT(SSH_PACKET_SF_QUEUED_BIT)
  19028. + | BIT(SSH_PACKET_SF_PENDING_BIT)
  19029. + | BIT(SSH_PACKET_SF_TRANSMITTING_BIT)
  19030. + | BIT(SSH_PACKET_SF_TRANSMITTED_BIT)
  19031. + | BIT(SSH_PACKET_SF_ACKED_BIT)
  19032. + | BIT(SSH_PACKET_SF_CANCELED_BIT)
  19033. + | BIT(SSH_PACKET_SF_COMPLETED_BIT),
  19034. +
  19035. + /* mask for type flags */
  19036. + SSH_PACKET_FLAGS_TY_MASK =
  19037. + BIT(SSH_PACKET_TY_FLUSH_BIT)
  19038. + | BIT(SSH_PACKET_TY_SEQUENCED_BIT)
  19039. + | BIT(SSH_PACKET_TY_BLOCKING_BIT),
  19040. +};
  19041. +
  19042. +
  19043. +struct ssh_ptl;
  19044. +struct ssh_packet;
  19045. +
  19046. +/**
  19047. + * struct ssh_packet_ops - Callback operations for a SSH packet.
  19048. + * @release: Function called when the packet reference count reaches zero.
  19049. + * This callback must be relied upon to ensure that the packet has
  19050. + * left the transport system(s).
  19051. + * @complete: Function called when the packet is completed, either with
  19052. + * success or failure. In case of failure, the reason for the
  19053. + * failure is indicated by the value of the provided status code
  19054. + * argument. This value will be zero in case of success. Note that
  19055. + * a call to this callback does not guarantee that the packet is
  19056. + * not in use by the transport system any more.
  19057. + */
  19058. +struct ssh_packet_ops {
  19059. + void (*release)(struct ssh_packet *p);
  19060. + void (*complete)(struct ssh_packet *p, int status);
  19061. +};
  19062. +
  19063. +/**
  19064. + * struct ssh_packet - SSH transport packet.
  19065. + * @ptl: Pointer to the packet transport layer. May be %NULL if the packet
  19066. + * (or enclosing request) has not been submitted yet.
  19067. + * @refcnt: Reference count of the packet.
  19068. + * @priority: Priority of the packet. Must be computed via
  19069. + * SSH_PACKET_PRIORITY().
  19070. + * @data: Raw message data.
  19071. + * @data.len: Length of the raw message data.
  19072. + * @data.ptr: Pointer to the raw message data buffer.
  19073. + * @state: State and type flags describing current packet state (dynamic)
  19074. + * and type (static). See &enum ssh_packet_flags for possible
  19075. + * options.
  19076. + * @timestamp: Timestamp specifying when the latest transmission of a
  19077. + * currently pending packet has been started. May be %KTIME_MAX
  19078. + * before or in-between transmission attempts. Used for the packet
  19079. + * timeout implementation.
  19080. + * @queue_node: The list node for the packet queue.
  19081. + * @pending_node: The list node for the set of pending packets.
  19082. + * @ops: Packet operations.
  19083. + */
  19084. +struct ssh_packet {
  19085. + struct ssh_ptl *ptl;
  19086. + struct kref refcnt;
  19087. +
  19088. + u8 priority;
  19089. +
  19090. + struct {
  19091. + size_t len;
  19092. + u8 *ptr;
  19093. + } data;
  19094. +
  19095. + unsigned long state;
  19096. + ktime_t timestamp;
  19097. +
  19098. + struct list_head queue_node;
  19099. + struct list_head pending_node;
  19100. +
  19101. + const struct ssh_packet_ops *ops;
  19102. +};
  19103. +
  19104. +struct ssh_packet *ssh_packet_get(struct ssh_packet *p);
  19105. +void ssh_packet_put(struct ssh_packet *p);
  19106. +
  19107. +/**
  19108. + * ssh_packet_set_data() - Set raw message data of packet.
  19109. + * @p: The packet for which the message data should be set.
  19110. + * @ptr: Pointer to the memory holding the message data.
  19111. + * @len: Length of the message data.
  19112. + *
  19113. + * Sets the raw message data buffer of the packet to the provided memory. The
  19114. + * memory is not copied. Instead, the caller is responsible for management
  19115. + * (i.e. allocation and deallocation) of the memory. The caller must ensure
  19116. + * that the provided memory is valid and contains a valid SSH message,
  19117. + * starting from the time of submission of the packet until the ``release``
  19118. + * callback has been called. During this time, the memory may not be altered
  19119. + * in any way.
  19120. + */
  19121. +static inline void ssh_packet_set_data(struct ssh_packet *p, u8 *ptr, size_t len)
  19122. +{
  19123. + p->data.ptr = ptr;
  19124. + p->data.len = len;
  19125. +}
  19126. +
  19127. +
  19128. +/* -- Request transport layer (rtl). ---------------------------------------- */
  19129. +
  19130. +enum ssh_request_flags {
  19131. + /* state flags */
  19132. + SSH_REQUEST_SF_LOCKED_BIT,
  19133. + SSH_REQUEST_SF_QUEUED_BIT,
  19134. + SSH_REQUEST_SF_PENDING_BIT,
  19135. + SSH_REQUEST_SF_TRANSMITTING_BIT,
  19136. + SSH_REQUEST_SF_TRANSMITTED_BIT,
  19137. + SSH_REQUEST_SF_RSPRCVD_BIT,
  19138. + SSH_REQUEST_SF_CANCELED_BIT,
  19139. + SSH_REQUEST_SF_COMPLETED_BIT,
  19140. +
  19141. + /* type flags */
  19142. + SSH_REQUEST_TY_FLUSH_BIT,
  19143. + SSH_REQUEST_TY_HAS_RESPONSE_BIT,
  19144. +
  19145. + /* mask for state flags */
  19146. + SSH_REQUEST_FLAGS_SF_MASK =
  19147. + BIT(SSH_REQUEST_SF_LOCKED_BIT)
  19148. + | BIT(SSH_REQUEST_SF_QUEUED_BIT)
  19149. + | BIT(SSH_REQUEST_SF_PENDING_BIT)
  19150. + | BIT(SSH_REQUEST_SF_TRANSMITTING_BIT)
  19151. + | BIT(SSH_REQUEST_SF_TRANSMITTED_BIT)
  19152. + | BIT(SSH_REQUEST_SF_RSPRCVD_BIT)
  19153. + | BIT(SSH_REQUEST_SF_CANCELED_BIT)
  19154. + | BIT(SSH_REQUEST_SF_COMPLETED_BIT),
  19155. +
  19156. + /* mask for type flags */
  19157. + SSH_REQUEST_FLAGS_TY_MASK =
  19158. + BIT(SSH_REQUEST_TY_FLUSH_BIT)
  19159. + | BIT(SSH_REQUEST_TY_HAS_RESPONSE_BIT),
  19160. +};
  19161. +
  19162. +
  19163. +struct ssh_rtl;
  19164. +struct ssh_request;
  19165. +
  19166. +/**
  19167. + * struct ssh_request_ops - Callback operations for a SSH request.
  19168. + * @release: Function called when the request's reference count reaches zero.
  19169. + * This callback must be relied upon to ensure that the request has
  19170. + * left the transport systems (both, packet an request systems).
  19171. + * @complete: Function called when the request is completed, either with
  19172. + * success or failure. The command data for the request response
  19173. + * is provided via the &struct ssh_command parameter (``cmd``),
  19174. + * the command payload of the request response via the &struct
  19175. + * ssh_span parameter (``data``).
  19176. + *
  19177. + * If the request does not have any response or has not been
  19178. + * completed with success, both ``cmd`` and ``data`` parameters will
  19179. + * be NULL. If the request response does not have any command
  19180. + * payload, the ``data`` span will be an empty (zero-length) span.
  19181. + *
  19182. + * In case of failure, the reason for the failure is indicated by
  19183. + * the value of the provided status code argument (``status``). This
  19184. + * value will be zero in case of success.
  19185. + *
  19186. + * Note that a call to this callback does not guarantee that the
  19187. + * request is not in use by the transport systems any more.
  19188. + */
  19189. +struct ssh_request_ops {
  19190. + void (*release)(struct ssh_request *rqst);
  19191. + void (*complete)(struct ssh_request *rqst,
  19192. + const struct ssh_command *cmd,
  19193. + const struct ssam_span *data, int status);
  19194. +};
  19195. +
  19196. +/**
  19197. + * struct ssh_request - SSH transport request.
  19198. + * @packet: The underlying SSH transport packet.
  19199. + * @node: List node for the request queue and pending set.
  19200. + * @state: State and type flags describing current request state (dynamic)
  19201. + * and type (static). See &enum ssh_request_flags for possible
  19202. + * options.
  19203. + * @timestamp: Timestamp specifying when we start waiting on the respnse of the
  19204. + * request. This is set once the underlying packet has been completed
  19205. + * and may be %KTIME_MAX before that, or when the request does not
  19206. + * expect a response. Used for the request timeout implementation.
  19207. + * @ops: Request Operations.
  19208. + */
  19209. +struct ssh_request {
  19210. + struct ssh_packet packet;
  19211. + struct list_head node;
  19212. +
  19213. + unsigned long state;
  19214. + ktime_t timestamp;
  19215. +
  19216. + const struct ssh_request_ops *ops;
  19217. +};
  19218. +
  19219. +/**
  19220. + * to_ssh_request() - Cast a SSH packet to its enclosing SSH request.
  19221. + * @p: The packet to cast.
  19222. + *
  19223. + * Casts the given &struct ssh_packet to its enclosing &struct ssh_request.
  19224. + * The caller is responsible for making sure that the packet is actually
  19225. + * wrapped in a &struct ssh_request.
  19226. + *
  19227. + * Return: Returns the &struct ssh_request wrapping the provided packet.
  19228. + */
  19229. +static inline struct ssh_request *to_ssh_request(struct ssh_packet *p)
  19230. +{
  19231. + return container_of(p, struct ssh_request, packet);
  19232. +}
  19233. +
  19234. +/**
  19235. + * ssh_request_get() - Increment reference count of request.
  19236. + * @r: The request to increment the reference count of.
  19237. + *
  19238. + * Increments the reference count of the given request by incrementing the
  19239. + * reference count of the underlying &struct ssh_packet, enclosed in it.
  19240. + *
  19241. + * See also ssh_request_put(), ssh_packet_get().
  19242. + *
  19243. + * Return: Returns the request provided as input.
  19244. + */
  19245. +static inline struct ssh_request *ssh_request_get(struct ssh_request *r)
  19246. +{
  19247. + return r ? to_ssh_request(ssh_packet_get(&r->packet)) : NULL;
  19248. +}
  19249. +
  19250. +/**
  19251. + * ssh_request_put() - Decrement reference count of request.
  19252. + * @r: The request to decrement the reference count of.
  19253. + *
  19254. + * Decrements the reference count of the given request by decrementing the
  19255. + * reference count of the underlying &struct ssh_packet, enclosed in it. If
  19256. + * the reference count reaches zero, the ``release`` callback specified in the
  19257. + * request's &struct ssh_request_ops, i.e. ``r->ops->release``, will be
  19258. + * called.
  19259. + *
  19260. + * See also ssh_request_get(), ssh_packet_put().
  19261. + */
  19262. +static inline void ssh_request_put(struct ssh_request *r)
  19263. +{
  19264. + if (r)
  19265. + ssh_packet_put(&r->packet);
  19266. +}
  19267. +
  19268. +/**
  19269. + * ssh_request_set_data() - Set raw message data of request.
  19270. + * @r: The request for which the message data should be set.
  19271. + * @ptr: Pointer to the memory holding the message data.
  19272. + * @len: Length of the message data.
  19273. + *
  19274. + * Sets the raw message data buffer of the underlying packet to the specified
  19275. + * buffer. Does not copy the actual message data, just sets the buffer pointer
  19276. + * and length. Refer to ssh_packet_set_data() for more details.
  19277. + */
  19278. +static inline void ssh_request_set_data(struct ssh_request *r, u8 *ptr, size_t len)
  19279. +{
  19280. + ssh_packet_set_data(&r->packet, ptr, len);
  19281. +}
  19282. +
  19283. +#endif /* _LINUX_SURFACE_AGGREGATOR_SERIAL_HUB_H */
  19284. diff --git a/include/uapi/linux/surface_aggregator/cdev.h b/include/uapi/linux/surface_aggregator/cdev.h
  19285. new file mode 100644
  19286. index 000000000000..1a8bc0249f8e
  19287. --- /dev/null
  19288. +++ b/include/uapi/linux/surface_aggregator/cdev.h
  19289. @@ -0,0 +1,58 @@
  19290. +/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */
  19291. +/*
  19292. + * Surface System Aggregator Module (SSAM) user-space EC interface.
  19293. + *
  19294. + * Definitions, structs, and IOCTLs for the /dev/surface/aggregator misc
  19295. + * device. This device provides direct user-space access to the SSAM EC.
  19296. + * Intended for debugging and development.
  19297. + *
  19298. + * Copyright (C) 2020 Maximilian Luz <luzmaximilian@gmail.com>
  19299. + */
  19300. +
  19301. +#ifndef _UAPI_LINUX_SURFACE_AGGREGATOR_CDEV_H
  19302. +#define _UAPI_LINUX_SURFACE_AGGREGATOR_CDEV_H
  19303. +
  19304. +#include <linux/ioctl.h>
  19305. +#include <linux/types.h>
  19306. +
  19307. +/**
  19308. + * struct ssam_cdev_request - Controller request IOCTL argument.
  19309. + * @target_category: Target category of the SAM request.
  19310. + * @target_id: Target ID of the SAM request.
  19311. + * @command_id: Command ID of the SAM request.
  19312. + * @instance_id: Instance ID of the SAM request.
  19313. + * @flags: SAM Request flags.
  19314. + * @status: Request status (output).
  19315. + * @payload: Request payload (input data).
  19316. + * @payload.data: Pointer to request payload data.
  19317. + * @payload.length: Length of request payload data (in bytes).
  19318. + * @response: Request response (output data).
  19319. + * @response.data: Pointer to response buffer.
  19320. + * @response.length: On input: Capacity of response buffer (in bytes).
  19321. + * On output: Length of request response (number of bytes
  19322. + * in the buffer that are actually used).
  19323. + */
  19324. +struct ssam_cdev_request {
  19325. + __u8 target_category;
  19326. + __u8 target_id;
  19327. + __u8 command_id;
  19328. + __u8 instance_id;
  19329. + __u16 flags;
  19330. + __s16 status;
  19331. +
  19332. + struct {
  19333. + __u64 data;
  19334. + __u16 length;
  19335. + __u8 __pad[6];
  19336. + } payload;
  19337. +
  19338. + struct {
  19339. + __u64 data;
  19340. + __u16 length;
  19341. + __u8 __pad[6];
  19342. + } response;
  19343. +} __attribute__((__packed__));
  19344. +
  19345. +#define SSAM_CDEV_REQUEST _IOWR(0xA5, 1, struct ssam_cdev_request)
  19346. +
  19347. +#endif /* _UAPI_LINUX_SURFACE_AGGREGATOR_CDEV_H */
  19348. diff --git a/include/uapi/linux/surface_aggregator/dtx.h b/include/uapi/linux/surface_aggregator/dtx.h
  19349. new file mode 100644
  19350. index 000000000000..fb6c49e254af
  19351. --- /dev/null
  19352. +++ b/include/uapi/linux/surface_aggregator/dtx.h
  19353. @@ -0,0 +1,150 @@
  19354. +/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */
  19355. +/*
  19356. + * Surface DTX (clipboard detachment system driver) user-space interface.
  19357. + *
  19358. + * Definitions, structs, and IOCTLs for the /dev/surface/dtx misc device. This
  19359. + * device allows user-space to control the clipboard detachment process on
  19360. + * Surface Book series devices.
  19361. + *
  19362. + * Copyright (C) 2020 Maximilian Luz <luzmaximilian@gmail.com>
  19363. + */
  19364. +
  19365. +#ifndef _UAPI_LINUX_SURFACE_AGGREGATOR_DTX_H
  19366. +#define _UAPI_LINUX_SURFACE_AGGREGATOR_DTX_H
  19367. +
  19368. +#include <linux/ioctl.h>
  19369. +#include <linux/types.h>
  19370. +
  19371. +
  19372. +/* Status/error categories */
  19373. +#define SDTX_CATEGORY_STATUS 0x0000
  19374. +#define SDTX_CATEGORY_RUNTIME_ERROR 0x1000
  19375. +#define SDTX_CATEGORY_HARDWARE_ERROR 0x2000
  19376. +#define SDTX_CATEGORY_UNKNOWN 0xf000
  19377. +
  19378. +#define SDTX_CATEGORY_MASK 0xf000
  19379. +#define SDTX_CATEGORY(value) ((value) & SDTX_CATEGORY_MASK)
  19380. +
  19381. +#define SDTX_STATUS(code) ((code) | SDTX_CATEGORY_STATUS)
  19382. +#define SDTX_ERR_RT(code) ((code) | SDTX_CATEGORY_RUNTIME_ERROR)
  19383. +#define SDTX_ERR_HW(code) ((code) | SDTX_CATEGORY_HARDWARE_ERROR)
  19384. +#define SDTX_UNKNOWN(code) ((code) | SDTX_CATEGORY_UNKNOWN)
  19385. +
  19386. +#define SDTX_SUCCESS(value) (SDTX_CATEGORY(value) == SDTX_CATEGORY_STATUS)
  19387. +
  19388. +/* Latch status values */
  19389. +#define SDTX_LATCH_CLOSED SDTX_STATUS(0x00)
  19390. +#define SDTX_LATCH_OPENED SDTX_STATUS(0x01)
  19391. +
  19392. +/* Base state values */
  19393. +#define SDTX_BASE_DETACHED SDTX_STATUS(0x00)
  19394. +#define SDTX_BASE_ATTACHED SDTX_STATUS(0x01)
  19395. +
  19396. +/* Runtime errors (non-critical) */
  19397. +#define SDTX_DETACH_NOT_FEASIBLE SDTX_ERR_RT(0x01)
  19398. +#define SDTX_DETACH_TIMEDOUT SDTX_ERR_RT(0x02)
  19399. +
  19400. +/* Hardware errors (critical) */
  19401. +#define SDTX_ERR_FAILED_TO_OPEN SDTX_ERR_HW(0x01)
  19402. +#define SDTX_ERR_FAILED_TO_REMAIN_OPEN SDTX_ERR_HW(0x02)
  19403. +#define SDTX_ERR_FAILED_TO_CLOSE SDTX_ERR_HW(0x03)
  19404. +
  19405. +
  19406. +/* Base types */
  19407. +#define SDTX_DEVICE_TYPE_HID 0x0100
  19408. +#define SDTX_DEVICE_TYPE_SSH 0x0200
  19409. +
  19410. +#define SDTX_DEVICE_TYPE_MASK 0x0f00
  19411. +#define SDTX_DEVICE_TYPE(value) ((value) & SDTX_DEVICE_TYPE_MASK)
  19412. +
  19413. +#define SDTX_BASE_TYPE_HID(id) ((id) | SDTX_DEVICE_TYPE_HID)
  19414. +#define SDTX_BASE_TYPE_SSH(id) ((id) | SDTX_DEVICE_TYPE_SSH)
  19415. +
  19416. +
  19417. +/**
  19418. + * enum sdtx_device_mode - Mode describing how (and if) the clipboard is
  19419. + * attached to the base of the device.
  19420. + * @SDTX_DEVICE_MODE_TABLET: The clipboard is detached from the base and the
  19421. + * device operates as tablet.
  19422. + * @SDTX_DEVICE_MODE_LAPTOP: The clipboard is attached normally to the base
  19423. + * and the device operates as laptop.
  19424. + * @SDTX_DEVICE_MODE_STUDIO: The clipboard is attached to the base in reverse.
  19425. + * The device operates as tablet with keyboard and
  19426. + * touchpad deactivated, however, the base battery
  19427. + * and, if present in the specific device model, dGPU
  19428. + * are available to the system.
  19429. + */
  19430. +enum sdtx_device_mode {
  19431. + SDTX_DEVICE_MODE_TABLET = 0x00,
  19432. + SDTX_DEVICE_MODE_LAPTOP = 0x01,
  19433. + SDTX_DEVICE_MODE_STUDIO = 0x02,
  19434. +};
  19435. +
  19436. +/**
  19437. + * struct sdtx_event - Event provided by reading from the DTX device file.
  19438. + * @length: Length of the event payload, in bytes.
  19439. + * @code: Event code, detailing what type of event this is.
  19440. + * @data: Payload of the event, containing @length bytes.
  19441. + *
  19442. + * See &enum sdtx_event_code for currently valid event codes.
  19443. + */
  19444. +struct sdtx_event {
  19445. + __u16 length;
  19446. + __u16 code;
  19447. + __u8 data[];
  19448. +} __attribute__((__packed__));
  19449. +
  19450. +/**
  19451. + * enum sdtx_event_code - Code describing the type of an event.
  19452. + * @SDTX_EVENT_REQUEST: Detachment request event type.
  19453. + * @SDTX_EVENT_CANCEL: Cancel detachment process event type.
  19454. + * @SDTX_EVENT_BASE_CONNECTION: Base/clipboard connection change event type.
  19455. + * @SDTX_EVENT_LATCH_STATUS: Latch status change event type.
  19456. + * @SDTX_EVENT_DEVICE_MODE: Device mode change event type.
  19457. + *
  19458. + * Used in @struct sdtx_event to describe the type of the event. Further event
  19459. + * codes are reserved for future use. Any event parser should be able to
  19460. + * gracefully handle unknown events, i.e. by simply skipping them.
  19461. + *
  19462. + * Consult the DTX user-space interface documentation for details regarding
  19463. + * the individual event types.
  19464. + */
  19465. +enum sdtx_event_code {
  19466. + SDTX_EVENT_REQUEST = 1,
  19467. + SDTX_EVENT_CANCEL = 2,
  19468. + SDTX_EVENT_BASE_CONNECTION = 3,
  19469. + SDTX_EVENT_LATCH_STATUS = 4,
  19470. + SDTX_EVENT_DEVICE_MODE = 5,
  19471. +};
  19472. +
  19473. +/**
  19474. + * struct sdtx_base_info - Describes if and what type of base is connected.
  19475. + * @state: The state of the connection. Valid values are %SDTX_BASE_DETACHED,
  19476. + * %SDTX_BASE_ATTACHED, and %SDTX_DETACH_NOT_FEASIBLE (in case a base
  19477. + * is attached but low clipboard battery prevents detachment). Other
  19478. + * values are currently reserved.
  19479. + * @base_id: The type of base connected. Zero if no base is connected.
  19480. + */
  19481. +struct sdtx_base_info {
  19482. + __u16 state;
  19483. + __u16 base_id;
  19484. +} __attribute__((__packed__));
  19485. +
  19486. +
  19487. +/* IOCTLs */
  19488. +#define SDTX_IOCTL_EVENTS_ENABLE _IO(0xa5, 0x21)
  19489. +#define SDTX_IOCTL_EVENTS_DISABLE _IO(0xa5, 0x22)
  19490. +
  19491. +#define SDTX_IOCTL_LATCH_LOCK _IO(0xa5, 0x23)
  19492. +#define SDTX_IOCTL_LATCH_UNLOCK _IO(0xa5, 0x24)
  19493. +
  19494. +#define SDTX_IOCTL_LATCH_REQUEST _IO(0xa5, 0x25)
  19495. +#define SDTX_IOCTL_LATCH_CONFIRM _IO(0xa5, 0x26)
  19496. +#define SDTX_IOCTL_LATCH_HEARTBEAT _IO(0xa5, 0x27)
  19497. +#define SDTX_IOCTL_LATCH_CANCEL _IO(0xa5, 0x28)
  19498. +
  19499. +#define SDTX_IOCTL_GET_BASE_INFO _IOR(0xa5, 0x29, struct sdtx_base_info)
  19500. +#define SDTX_IOCTL_GET_DEVICE_MODE _IOR(0xa5, 0x2a, __u16)
  19501. +#define SDTX_IOCTL_GET_LATCH_STATUS _IOR(0xa5, 0x2b, __u16)
  19502. +
  19503. +#endif /* _UAPI_LINUX_SURFACE_AGGREGATOR_DTX_H */
  19504. diff --git a/scripts/mod/devicetable-offsets.c b/scripts/mod/devicetable-offsets.c
  19505. index 35b9899b0b0f..6b761c5b3ddd 100644
  19506. --- a/scripts/mod/devicetable-offsets.c
  19507. +++ b/scripts/mod/devicetable-offsets.c
  19508. @@ -243,8 +243,9 @@ int main(void)
  19509. DEVID(ssam_device_id);
  19510. DEVID_FIELD(ssam_device_id, match_flags);
  19511. + DEVID_FIELD(ssam_device_id, domain);
  19512. DEVID_FIELD(ssam_device_id, category);
  19513. - DEVID_FIELD(ssam_device_id, channel);
  19514. + DEVID_FIELD(ssam_device_id, target);
  19515. DEVID_FIELD(ssam_device_id, instance);
  19516. DEVID_FIELD(ssam_device_id, function);
  19517. diff --git a/scripts/mod/file2alias.c b/scripts/mod/file2alias.c
  19518. index 079672e0747a..23d9d368fde9 100644
  19519. --- a/scripts/mod/file2alias.c
  19520. +++ b/scripts/mod/file2alias.c
  19521. @@ -1364,20 +1364,22 @@ static int do_mhi_entry(const char *filename, void *symval, char *alias)
  19522. return 1;
  19523. }
  19524. -/* Looks like: ssam:cNtNiNfN
  19525. +/*
  19526. + * Looks like: ssam:dNcNtNiNfN
  19527. *
  19528. * N is exactly 2 digits, where each is an upper-case hex digit.
  19529. */
  19530. static int do_ssam_entry(const char *filename, void *symval, char *alias)
  19531. {
  19532. DEF_FIELD(symval, ssam_device_id, match_flags);
  19533. + DEF_FIELD(symval, ssam_device_id, domain);
  19534. DEF_FIELD(symval, ssam_device_id, category);
  19535. - DEF_FIELD(symval, ssam_device_id, channel);
  19536. + DEF_FIELD(symval, ssam_device_id, target);
  19537. DEF_FIELD(symval, ssam_device_id, instance);
  19538. DEF_FIELD(symval, ssam_device_id, function);
  19539. - sprintf(alias, "ssam:c%02X", category);
  19540. - ADD(alias, "t", match_flags & SSAM_MATCH_CHANNEL, channel);
  19541. + sprintf(alias, "ssam:d%02Xc%02X", domain, category);
  19542. + ADD(alias, "t", match_flags & SSAM_MATCH_TARGET, target);
  19543. ADD(alias, "i", match_flags & SSAM_MATCH_INSTANCE, instance);
  19544. ADD(alias, "f", match_flags & SSAM_MATCH_FUNCTION, function);
  19545. --
  19546. 2.29.2