0002-surface-sam.patch 319 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931
  1. From 095746ff0ecad3ef1ff67e444ef10d4ac36cf8f8 Mon Sep 17 00:00:00 2001
  2. From: Maximilian Luz <luzmaximilian@gmail.com>
  3. Date: Fri, 6 Dec 2019 11:56:12 +0100
  4. Subject: [PATCH 2/4] surface-sam
  5. ---
  6. drivers/platform/x86/Kconfig | 2 +
  7. drivers/platform/x86/Makefile | 1 +
  8. drivers/platform/x86/surface_sam/Kconfig | 176 +
  9. drivers/platform/x86/surface_sam/Makefile | 15 +
  10. .../x86/surface_sam/surface_sam_dtx.c | 590 ++
  11. .../x86/surface_sam/surface_sam_hps.c | 1297 +++++
  12. .../x86/surface_sam/surface_sam_san.c | 913 +++
  13. .../x86/surface_sam/surface_sam_san.h | 30 +
  14. .../x86/surface_sam/surface_sam_sid.c | 281 +
  15. .../x86/surface_sam/surface_sam_sid_gpelid.c | 232 +
  16. .../surface_sam/surface_sam_sid_perfmode.c | 216 +
  17. .../x86/surface_sam/surface_sam_sid_power.c | 1154 ++++
  18. .../x86/surface_sam/surface_sam_sid_power.h | 15 +
  19. .../x86/surface_sam/surface_sam_sid_vhf.c | 432 ++
  20. .../x86/surface_sam/surface_sam_sid_vhf.h | 13 +
  21. .../x86/surface_sam/surface_sam_ssh.c | 5111 +++++++++++++++++
  22. .../x86/surface_sam/surface_sam_ssh.h | 488 ++
  23. .../x86/surface_sam/surface_sam_ssh_trace.h | 536 ++
  24. .../x86/surface_sam/surface_sam_vhf.c | 261 +
  25. 19 files changed, 11763 insertions(+)
  26. create mode 100644 drivers/platform/x86/surface_sam/Kconfig
  27. create mode 100644 drivers/platform/x86/surface_sam/Makefile
  28. create mode 100644 drivers/platform/x86/surface_sam/surface_sam_dtx.c
  29. create mode 100644 drivers/platform/x86/surface_sam/surface_sam_hps.c
  30. create mode 100644 drivers/platform/x86/surface_sam/surface_sam_san.c
  31. create mode 100644 drivers/platform/x86/surface_sam/surface_sam_san.h
  32. create mode 100644 drivers/platform/x86/surface_sam/surface_sam_sid.c
  33. create mode 100644 drivers/platform/x86/surface_sam/surface_sam_sid_gpelid.c
  34. create mode 100644 drivers/platform/x86/surface_sam/surface_sam_sid_perfmode.c
  35. create mode 100644 drivers/platform/x86/surface_sam/surface_sam_sid_power.c
  36. create mode 100644 drivers/platform/x86/surface_sam/surface_sam_sid_power.h
  37. create mode 100644 drivers/platform/x86/surface_sam/surface_sam_sid_vhf.c
  38. create mode 100644 drivers/platform/x86/surface_sam/surface_sam_sid_vhf.h
  39. create mode 100644 drivers/platform/x86/surface_sam/surface_sam_ssh.c
  40. create mode 100644 drivers/platform/x86/surface_sam/surface_sam_ssh.h
  41. create mode 100644 drivers/platform/x86/surface_sam/surface_sam_ssh_trace.h
  42. create mode 100644 drivers/platform/x86/surface_sam/surface_sam_vhf.c
  43. diff --git a/drivers/platform/x86/Kconfig b/drivers/platform/x86/Kconfig
  44. index 0ad7ad8cf8e1..5d1766294eca 100644
  45. --- a/drivers/platform/x86/Kconfig
  46. +++ b/drivers/platform/x86/Kconfig
  47. @@ -1350,6 +1350,8 @@ config INTEL_SCU_IPC
  48. some embedded Intel x86 platforms. This is not needed for PC-type
  49. machines.
  50. +source "drivers/platform/x86/surface_sam/Kconfig"
  51. +
  52. config INTEL_SCU_IPC_UTIL
  53. tristate "Intel SCU IPC utility driver"
  54. depends on INTEL_SCU_IPC
  55. diff --git a/drivers/platform/x86/Makefile b/drivers/platform/x86/Makefile
  56. index 53408d965874..b3f4305f73c5 100644
  57. --- a/drivers/platform/x86/Makefile
  58. +++ b/drivers/platform/x86/Makefile
  59. @@ -146,3 +146,4 @@ obj-$(CONFIG_INTEL_TELEMETRY) += intel_telemetry_core.o \
  60. intel_telemetry_pltdrv.o \
  61. intel_telemetry_debugfs.o
  62. obj-$(CONFIG_PMC_ATOM) += pmc_atom.o
  63. +obj-$(CONFIG_SURFACE_SAM) += surface_sam/
  64. diff --git a/drivers/platform/x86/surface_sam/Kconfig b/drivers/platform/x86/surface_sam/Kconfig
  65. new file mode 100644
  66. index 000000000000..7781c5cd932c
  67. --- /dev/null
  68. +++ b/drivers/platform/x86/surface_sam/Kconfig
  69. @@ -0,0 +1,176 @@
  70. +menuconfig SURFACE_SAM
  71. + depends on ACPI
  72. + tristate "Microsoft Surface/System Aggregator Module and Platform Drivers"
  73. + help
  74. + Drivers for the Surface/System Aggregator Module (SAM) of Microsoft
  75. + Surface devices.
  76. +
  77. + SAM is an embedded controller that provides access to various
  78. + functionalities on these devices, including battery status, keyboard
  79. + events (on the Laptops) and many more.
  80. +
  81. + Say M/Y here if you have a Microsoft Surface device with a SAM device
  82. + (i.e. 5th generation or later).
  83. +
  84. +config SURFACE_SAM_SSH
  85. + tristate "Surface Serial Hub Driver"
  86. + depends on SURFACE_SAM
  87. + depends on SERIAL_DEV_CTRL_TTYPORT
  88. + select CRC_CCITT
  89. + default m
  90. + help
  91. + Surface Serial Hub driver for 5th generation (or later) Microsoft
  92. + Surface devices.
  93. +
  94. + This is the base driver for the embedded serial controller found on
  95. + 5th generation (and later) Microsoft Surface devices (e.g. Book 2,
  96. + Laptop, Laptop 2, Pro 2017, Pro 6, ...). This driver itself only
  97. + provides access to the embedded controller (SAM) and subsequent
  98. + drivers are required for the respective functionalities.
  99. +
  100. + If you have a 5th generation (or later) Microsoft Surface device, say
  101. + Y or M here.
  102. +
  103. +config SURFACE_SAM_SSH_DEBUG_DEVICE
  104. + bool "Surface Serial Hub Debug Device"
  105. + depends on SURFACE_SAM_SSH
  106. + depends on SYSFS
  107. + default n
  108. + help
  109. + Debug device for direct communication with the embedded controller
  110. + found on 5th generation (and later) Microsoft Surface devices (e.g.
  111. + Book 2, Laptop, Laptop 2, Pro 2017, Pro 6, ...) via sysfs.
  112. +
  113. + If you are not sure, say N here.
  114. +
  115. +config SURFACE_SAM_SSH_ERROR_INJECTION
  116. + bool "Surface Serial Hub Error Injection Capabilities"
  117. + depends on SURFACE_SAM_SSH
  118. + depends on FUNCTION_ERROR_INJECTION
  119. + default n
  120. + help
  121. + Enable error injection capabilities for the Surface Serial Hub.
  122. + This is used to debug the driver, specifically the communication
  123. + interface. It is not required for normal use.
  124. +
  125. + If you are not sure, say N here.
  126. +
  127. +config SURFACE_SAM_SAN
  128. + tristate "Surface ACPI Notify Driver"
  129. + depends on SURFACE_SAM_SSH
  130. + default m
  131. + help
  132. + Surface ACPI Notify driver for 5th generation (or later) Microsoft
  133. + Surface devices.
  134. +
  135. + This driver enables basic ACPI events and requests, such as battery
  136. + status requests/events, thermal events, lid status, and possibly more,
  137. + which would otherwise not work on these devices.
  138. +
  139. + If you are not sure, say M here.
  140. +
  141. +config SURFACE_SAM_VHF
  142. + tristate "Surface Virtual HID Framework Driver"
  143. + depends on SURFACE_SAM_SSH
  144. + depends on HID
  145. + default m
  146. + help
  147. + Surface Virtual HID Framework driver for 5th generation (or later)
  148. + Microsoft Surface devices.
  149. +
  150. + This driver provides support for the Microsoft Virtual HID framework,
  151. + which is required for keyboard support on the Surface Laptop 1 and 2.
  152. +
  153. + If you are not sure, say M here.
  154. +
  155. +config SURFACE_SAM_DTX
  156. + tristate "Surface Detachment System (DTX) Driver"
  157. + depends on SURFACE_SAM_SSH
  158. + depends on INPUT
  159. + default m
  160. + help
  161. + Surface Detachment System (DTX) driver for the Microsoft Surface Book
  162. + 2. This driver provides support for proper detachment handling in
  163. + user-space, status-events relating to the base and support for
  164. + the safe-guard keeping the base attached when the discrete GPU
  165. + contained in it is running via the special /dev/surface-dtx device.
  166. +
  167. + Also provides a standard input device to provide SW_TABLET_MODE events
  168. + upon device mode change.
  169. +
  170. + If you are not sure, say M here.
  171. +
  172. +config SURFACE_SAM_HPS
  173. + tristate "Surface dGPU Hot-Plug System (dGPU-HPS) Driver"
  174. + depends on SURFACE_SAM_SSH
  175. + depends on SURFACE_SAM_SAN
  176. + depends on GPIO_SYSFS
  177. + default m
  178. + help
  179. + Driver to properly handle hot-plugging and explicit power-on/power-off
  180. + of the discrete GPU (dGPU) on the Surface Book 2 and 3.
  181. +
  182. + If you are not sure, say M here.
  183. +
  184. +config SURFACE_SAM_SID
  185. + tristate "Surface Platform Integration Driver"
  186. + depends on SURFACE_SAM_SSH
  187. + default m
  188. + help
  189. + Surface Platform Integration Driver for the Microsoft Surface Devices.
  190. + This driver loads various model-specific sub-drivers, including
  191. + battery and keyboard support on 7th generation Surface devices, proper
  192. + lid setup to enable device wakeup when the lid is opened on multiple
  193. + models, as well as performance mode setting support on the Surface
  194. + Book 2.
  195. +
  196. + If you are not sure, say M here.
  197. +
  198. +config SURFACE_SAM_SID_GPELID
  199. + tristate "Surface Lid Wakeup Driver"
  200. + depends on SURFACE_SAM_SID
  201. + default m
  202. + help
  203. + Driver to set up device wake-up via lid on Intel-based Microsoft
  204. + Surface devices. These devices do not wake up from sleep as their GPE
  205. + interrupt is not configured automatically. This driver solves that
  206. + problem.
  207. +
  208. + If you are not sure, say M here.
  209. +
  210. +config SURFACE_SAM_SID_PERFMODE
  211. + tristate "Surface Performance Mode Driver"
  212. + depends on SURFACE_SAM_SID
  213. + depends on SYSFS
  214. + default m
  215. + help
  216. + This driver provides support for setting performance-modes on Surface
  217. + devices via the perf_mode sysfs attribute. Currently only supports the
  218. + Surface Book 2. Performance-modes directly influence the fan-profile
  219. + of the device, allowing to choose between higher performance or
  220. + quieter operation.
  221. +
  222. + If you are not sure, say M here.
  223. +
  224. +config SURFACE_SAM_SID_VHF
  225. + tristate "Surface SAM HID Driver"
  226. + depends on SURFACE_SAM_SID
  227. + depends on HID
  228. + default m
  229. + help
  230. + This driver provides support for HID devices connected via the Surface
  231. + SAM embedded controller. It provides support for keyboard and touchpad
  232. + on the Surface Laptop 3 models.
  233. +
  234. + If you are not sure, say M here.
  235. +
  236. +config SURFACE_SAM_SID_POWER
  237. + tristate "Surface SAM Battery/AC Driver"
  238. + depends on SURFACE_SAM_SID
  239. + select POWER_SUPPLY
  240. + default m
  241. + help
  242. + This driver provides support for the battery and AC on 7th generation
  243. + Surface devices.
  244. +
  245. + If you are not sure, say M here.
  246. diff --git a/drivers/platform/x86/surface_sam/Makefile b/drivers/platform/x86/surface_sam/Makefile
  247. new file mode 100644
  248. index 000000000000..1a5c1260639d
  249. --- /dev/null
  250. +++ b/drivers/platform/x86/surface_sam/Makefile
  251. @@ -0,0 +1,15 @@
  252. +# SPDX-License-Identifier: GPL-2.0-or-later
  253. +
  254. +# For include/trace/define_trace.h to include surface_sam_ssh_trace.h
  255. +CFLAGS_surface_sam_ssh.o = -I$(src)
  256. +
  257. +obj-$(CONFIG_SURFACE_SAM_SSH) += surface_sam_ssh.o
  258. +obj-$(CONFIG_SURFACE_SAM_SAN) += surface_sam_san.o
  259. +obj-$(CONFIG_SURFACE_SAM_DTX) += surface_sam_dtx.o
  260. +obj-$(CONFIG_SURFACE_SAM_HPS) += surface_sam_hps.o
  261. +obj-$(CONFIG_SURFACE_SAM_VHF) += surface_sam_vhf.o
  262. +obj-$(CONFIG_SURFACE_SAM_SID) += surface_sam_sid.o
  263. +obj-$(CONFIG_SURFACE_SAM_SID_GPELID) += surface_sam_sid_gpelid.o
  264. +obj-$(CONFIG_SURFACE_SAM_SID_PERFMODE) += surface_sam_sid_perfmode.o
  265. +obj-$(CONFIG_SURFACE_SAM_SID_POWER) += surface_sam_sid_power.o
  266. +obj-$(CONFIG_SURFACE_SAM_SID_VHF) += surface_sam_sid_vhf.o
  267. diff --git a/drivers/platform/x86/surface_sam/surface_sam_dtx.c b/drivers/platform/x86/surface_sam/surface_sam_dtx.c
  268. new file mode 100644
  269. index 000000000000..88dba7bced3a
  270. --- /dev/null
  271. +++ b/drivers/platform/x86/surface_sam/surface_sam_dtx.c
  272. @@ -0,0 +1,590 @@
  273. +// SPDX-License-Identifier: GPL-2.0-or-later
  274. +/*
  275. + * Detachment system (DTX) driver for Microsoft Surface Book 2.
  276. + */
  277. +
  278. +#include <linux/acpi.h>
  279. +#include <linux/delay.h>
  280. +#include <linux/fs.h>
  281. +#include <linux/input.h>
  282. +#include <linux/ioctl.h>
  283. +#include <linux/kernel.h>
  284. +#include <linux/miscdevice.h>
  285. +#include <linux/module.h>
  286. +#include <linux/poll.h>
  287. +#include <linux/rculist.h>
  288. +#include <linux/slab.h>
  289. +#include <linux/spinlock.h>
  290. +#include <linux/platform_device.h>
  291. +
  292. +#include "surface_sam_ssh.h"
  293. +
  294. +
  295. +#define USB_VENDOR_ID_MICROSOFT 0x045e
  296. +#define USB_DEVICE_ID_MS_SURFACE_BASE_2_INTEGRATION 0x0922
  297. +
  298. +// name copied from MS device manager
  299. +#define DTX_INPUT_NAME "Microsoft Surface Base 2 Integration Device"
  300. +
  301. +
  302. +#define DTX_CMD_LATCH_LOCK _IO(0x11, 0x01)
  303. +#define DTX_CMD_LATCH_UNLOCK _IO(0x11, 0x02)
  304. +#define DTX_CMD_LATCH_REQUEST _IO(0x11, 0x03)
  305. +#define DTX_CMD_LATCH_OPEN _IO(0x11, 0x04)
  306. +#define DTX_CMD_GET_OPMODE _IOR(0x11, 0x05, int)
  307. +
  308. +#define SAM_RQST_DTX_TC 0x11
  309. +#define SAM_RQST_DTX_CID_LATCH_LOCK 0x06
  310. +#define SAM_RQST_DTX_CID_LATCH_UNLOCK 0x07
  311. +#define SAM_RQST_DTX_CID_LATCH_REQUEST 0x08
  312. +#define SAM_RQST_DTX_CID_LATCH_OPEN 0x09
  313. +#define SAM_RQST_DTX_CID_GET_OPMODE 0x0D
  314. +
  315. +#define SAM_EVENT_DTX_CID_CONNECTION 0x0c
  316. +#define SAM_EVENT_DTX_CID_BUTTON 0x0e
  317. +#define SAM_EVENT_DTX_CID_ERROR 0x0f
  318. +#define SAM_EVENT_DTX_CID_LATCH_STATUS 0x11
  319. +
  320. +#define DTX_OPMODE_TABLET 0x00
  321. +#define DTX_OPMODE_LAPTOP 0x01
  322. +#define DTX_OPMODE_STUDIO 0x02
  323. +
  324. +#define DTX_LATCH_CLOSED 0x00
  325. +#define DTX_LATCH_OPENED 0x01
  326. +
  327. +
  328. +// Warning: This must always be a power of 2!
  329. +#define DTX_CLIENT_BUF_SIZE 16
  330. +
  331. +#define DTX_CONNECT_OPMODE_DELAY 1000
  332. +
  333. +#define DTX_ERR KERN_ERR "surface_sam_dtx: "
  334. +#define DTX_WARN KERN_WARNING "surface_sam_dtx: "
  335. +
  336. +
  337. +struct surface_dtx_event {
  338. + u8 type;
  339. + u8 code;
  340. + u8 arg0;
  341. + u8 arg1;
  342. +} __packed;
  343. +
  344. +struct surface_dtx_dev {
  345. + struct ssam_event_notifier notif;
  346. + struct delayed_work opmode_work;
  347. + wait_queue_head_t waitq;
  348. + struct miscdevice mdev;
  349. + spinlock_t client_lock;
  350. + struct list_head client_list;
  351. + struct mutex mutex;
  352. + bool active;
  353. + spinlock_t input_lock;
  354. + struct input_dev *input_dev;
  355. +};
  356. +
  357. +struct surface_dtx_client {
  358. + struct list_head node;
  359. + struct surface_dtx_dev *ddev;
  360. + struct fasync_struct *fasync;
  361. + spinlock_t buffer_lock;
  362. + unsigned int buffer_head;
  363. + unsigned int buffer_tail;
  364. + struct surface_dtx_event buffer[DTX_CLIENT_BUF_SIZE];
  365. +};
  366. +
  367. +
  368. +static struct surface_dtx_dev surface_dtx_dev;
  369. +
  370. +
  371. +static int surface_sam_query_opmpde(void)
  372. +{
  373. + u8 result_buf[1];
  374. + int status;
  375. +
  376. + struct surface_sam_ssh_rqst rqst = {
  377. + .tc = SAM_RQST_DTX_TC,
  378. + .cid = SAM_RQST_DTX_CID_GET_OPMODE,
  379. + .iid = 0x00,
  380. + .chn = 0x01,
  381. + .snc = 0x01,
  382. + .cdl = 0x00,
  383. + .pld = NULL,
  384. + };
  385. +
  386. + struct surface_sam_ssh_buf result = {
  387. + .cap = 1,
  388. + .len = 0,
  389. + .data = result_buf,
  390. + };
  391. +
  392. + status = surface_sam_ssh_rqst(&rqst, &result);
  393. + if (status)
  394. + return status;
  395. +
  396. + if (result.len != 1)
  397. + return -EFAULT;
  398. +
  399. + return result.data[0];
  400. +}
  401. +
  402. +
  403. +static int dtx_cmd_simple(u8 cid)
  404. +{
  405. + struct surface_sam_ssh_rqst rqst = {
  406. + .tc = SAM_RQST_DTX_TC,
  407. + .cid = cid,
  408. + .iid = 0x00,
  409. + .chn = 0x01,
  410. + .snc = 0x00,
  411. + .cdl = 0x00,
  412. + .pld = NULL,
  413. + };
  414. +
  415. + return surface_sam_ssh_rqst(&rqst, NULL);
  416. +}
  417. +
  418. +static int dtx_cmd_get_opmode(int __user *buf)
  419. +{
  420. + int opmode;
  421. +
  422. + opmode = surface_sam_query_opmpde();
  423. + if (opmode < 0)
  424. + return opmode;
  425. +
  426. + if (put_user(opmode, buf))
  427. + return -EACCES;
  428. +
  429. + return 0;
  430. +}
  431. +
  432. +
  433. +static int surface_dtx_open(struct inode *inode, struct file *file)
  434. +{
  435. + struct surface_dtx_dev *ddev = container_of(file->private_data, struct surface_dtx_dev, mdev);
  436. + struct surface_dtx_client *client;
  437. +
  438. + // initialize client
  439. + client = kzalloc(sizeof(struct surface_dtx_client), GFP_KERNEL);
  440. + if (!client)
  441. + return -ENOMEM;
  442. +
  443. + spin_lock_init(&client->buffer_lock);
  444. + client->buffer_head = 0;
  445. + client->buffer_tail = 0;
  446. + client->ddev = ddev;
  447. +
  448. + // attach client
  449. + spin_lock(&ddev->client_lock);
  450. + list_add_tail_rcu(&client->node, &ddev->client_list);
  451. + spin_unlock(&ddev->client_lock);
  452. +
  453. + file->private_data = client;
  454. + nonseekable_open(inode, file);
  455. +
  456. + return 0;
  457. +}
  458. +
  459. +static int surface_dtx_release(struct inode *inode, struct file *file)
  460. +{
  461. + struct surface_dtx_client *client = file->private_data;
  462. +
  463. + // detach client
  464. + spin_lock(&client->ddev->client_lock);
  465. + list_del_rcu(&client->node);
  466. + spin_unlock(&client->ddev->client_lock);
  467. + synchronize_rcu();
  468. +
  469. + kfree(client);
  470. + file->private_data = NULL;
  471. +
  472. + return 0;
  473. +}
  474. +
  475. +static ssize_t surface_dtx_read(struct file *file, char __user *buf, size_t count, loff_t *offs)
  476. +{
  477. + struct surface_dtx_client *client = file->private_data;
  478. + struct surface_dtx_dev *ddev = client->ddev;
  479. + struct surface_dtx_event event;
  480. + size_t read = 0;
  481. + int status = 0;
  482. +
  483. + if (count != 0 && count < sizeof(struct surface_dtx_event))
  484. + return -EINVAL;
  485. +
  486. + if (!ddev->active)
  487. + return -ENODEV;
  488. +
  489. + // check availability
  490. + if (client->buffer_head == client->buffer_tail) {
  491. + if (file->f_flags & O_NONBLOCK)
  492. + return -EAGAIN;
  493. +
  494. + status = wait_event_interruptible(ddev->waitq,
  495. + client->buffer_head != client->buffer_tail ||
  496. + !ddev->active);
  497. + if (status)
  498. + return status;
  499. +
  500. + if (!ddev->active)
  501. + return -ENODEV;
  502. + }
  503. +
  504. + // copy events one by one
  505. + while (read + sizeof(struct surface_dtx_event) <= count) {
  506. + spin_lock_irq(&client->buffer_lock);
  507. +
  508. + if (client->buffer_head == client->buffer_tail) {
  509. + spin_unlock_irq(&client->buffer_lock);
  510. + break;
  511. + }
  512. +
  513. + // get one event
  514. + event = client->buffer[client->buffer_tail];
  515. + client->buffer_tail = (client->buffer_tail + 1) & (DTX_CLIENT_BUF_SIZE - 1);
  516. + spin_unlock_irq(&client->buffer_lock);
  517. +
  518. + // copy to userspace
  519. + if (copy_to_user(buf, &event, sizeof(struct surface_dtx_event)))
  520. + return -EFAULT;
  521. +
  522. + read += sizeof(struct surface_dtx_event);
  523. + }
  524. +
  525. + return read;
  526. +}
  527. +
  528. +static __poll_t surface_dtx_poll(struct file *file, struct poll_table_struct *pt)
  529. +{
  530. + struct surface_dtx_client *client = file->private_data;
  531. + int mask;
  532. +
  533. + poll_wait(file, &client->ddev->waitq, pt);
  534. +
  535. + if (client->ddev->active)
  536. + mask = EPOLLOUT | EPOLLWRNORM;
  537. + else
  538. + mask = EPOLLHUP | EPOLLERR;
  539. +
  540. + if (client->buffer_head != client->buffer_tail)
  541. + mask |= EPOLLIN | EPOLLRDNORM;
  542. +
  543. + return mask;
  544. +}
  545. +
  546. +static int surface_dtx_fasync(int fd, struct file *file, int on)
  547. +{
  548. + struct surface_dtx_client *client = file->private_data;
  549. +
  550. + return fasync_helper(fd, file, on, &client->fasync);
  551. +}
  552. +
  553. +static long surface_dtx_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
  554. +{
  555. + struct surface_dtx_client *client = file->private_data;
  556. + struct surface_dtx_dev *ddev = client->ddev;
  557. + int status;
  558. +
  559. + status = mutex_lock_interruptible(&ddev->mutex);
  560. + if (status)
  561. + return status;
  562. +
  563. + if (!ddev->active) {
  564. + mutex_unlock(&ddev->mutex);
  565. + return -ENODEV;
  566. + }
  567. +
  568. + switch (cmd) {
  569. + case DTX_CMD_LATCH_LOCK:
  570. + status = dtx_cmd_simple(SAM_RQST_DTX_CID_LATCH_LOCK);
  571. + break;
  572. +
  573. + case DTX_CMD_LATCH_UNLOCK:
  574. + status = dtx_cmd_simple(SAM_RQST_DTX_CID_LATCH_UNLOCK);
  575. + break;
  576. +
  577. + case DTX_CMD_LATCH_REQUEST:
  578. + status = dtx_cmd_simple(SAM_RQST_DTX_CID_LATCH_REQUEST);
  579. + break;
  580. +
  581. + case DTX_CMD_LATCH_OPEN:
  582. + status = dtx_cmd_simple(SAM_RQST_DTX_CID_LATCH_OPEN);
  583. + break;
  584. +
  585. + case DTX_CMD_GET_OPMODE:
  586. + status = dtx_cmd_get_opmode((int __user *)arg);
  587. + break;
  588. +
  589. + default:
  590. + status = -EINVAL;
  591. + break;
  592. + }
  593. +
  594. + mutex_unlock(&ddev->mutex);
  595. + return status;
  596. +}
  597. +
  598. +static const struct file_operations surface_dtx_fops = {
  599. + .owner = THIS_MODULE,
  600. + .open = surface_dtx_open,
  601. + .release = surface_dtx_release,
  602. + .read = surface_dtx_read,
  603. + .poll = surface_dtx_poll,
  604. + .fasync = surface_dtx_fasync,
  605. + .unlocked_ioctl = surface_dtx_ioctl,
  606. + .llseek = no_llseek,
  607. +};
  608. +
  609. +static struct surface_dtx_dev surface_dtx_dev = {
  610. + .mdev = {
  611. + .minor = MISC_DYNAMIC_MINOR,
  612. + .name = "surface_dtx",
  613. + .fops = &surface_dtx_fops,
  614. + },
  615. + .client_lock = __SPIN_LOCK_UNLOCKED(),
  616. + .input_lock = __SPIN_LOCK_UNLOCKED(),
  617. + .mutex = __MUTEX_INITIALIZER(surface_dtx_dev.mutex),
  618. + .active = false,
  619. +};
  620. +
  621. +
  622. +static void surface_dtx_push_event(struct surface_dtx_dev *ddev, struct surface_dtx_event *event)
  623. +{
  624. + struct surface_dtx_client *client;
  625. +
  626. + rcu_read_lock();
  627. + list_for_each_entry_rcu(client, &ddev->client_list, node) {
  628. + spin_lock(&client->buffer_lock);
  629. +
  630. + client->buffer[client->buffer_head++] = *event;
  631. + client->buffer_head &= DTX_CLIENT_BUF_SIZE - 1;
  632. +
  633. + if (unlikely(client->buffer_head == client->buffer_tail)) {
  634. + printk(DTX_WARN "event buffer overrun\n");
  635. + client->buffer_tail = (client->buffer_tail + 1) & (DTX_CLIENT_BUF_SIZE - 1);
  636. + }
  637. +
  638. + spin_unlock(&client->buffer_lock);
  639. +
  640. + kill_fasync(&client->fasync, SIGIO, POLL_IN);
  641. + }
  642. + rcu_read_unlock();
  643. +
  644. + wake_up_interruptible(&ddev->waitq);
  645. +}
  646. +
  647. +
  648. +static void surface_dtx_update_opmpde(struct surface_dtx_dev *ddev)
  649. +{
  650. + struct surface_dtx_event event;
  651. + int opmode;
  652. +
  653. + // get operation mode
  654. + opmode = surface_sam_query_opmpde();
  655. + if (opmode < 0)
  656. + printk(DTX_ERR "EC request failed with error %d\n", opmode);
  657. +
  658. + // send DTX event
  659. + event.type = 0x11;
  660. + event.code = 0x0D;
  661. + event.arg0 = opmode;
  662. + event.arg1 = 0x00;
  663. +
  664. + surface_dtx_push_event(ddev, &event);
  665. +
  666. + // send SW_TABLET_MODE event
  667. + spin_lock(&ddev->input_lock);
  668. + input_report_switch(ddev->input_dev, SW_TABLET_MODE, opmode != DTX_OPMODE_LAPTOP);
  669. + input_sync(ddev->input_dev);
  670. + spin_unlock(&ddev->input_lock);
  671. +}
  672. +
  673. +static void surface_dtx_opmode_workfn(struct work_struct *work)
  674. +{
  675. + struct surface_dtx_dev *ddev = container_of(work, struct surface_dtx_dev, opmode_work.work);
  676. +
  677. + surface_dtx_update_opmpde(ddev);
  678. +}
  679. +
  680. +static u32 surface_dtx_notification(struct ssam_notifier_block *nb, const struct ssam_event *in_event)
  681. +{
  682. + struct surface_dtx_dev *ddev = container_of(nb, struct surface_dtx_dev, notif.base);
  683. + struct surface_dtx_event event;
  684. + unsigned long delay;
  685. +
  686. + switch (in_event->command_id) {
  687. + case SAM_EVENT_DTX_CID_CONNECTION:
  688. + case SAM_EVENT_DTX_CID_BUTTON:
  689. + case SAM_EVENT_DTX_CID_ERROR:
  690. + case SAM_EVENT_DTX_CID_LATCH_STATUS:
  691. + if (in_event->length > 2) {
  692. + printk(DTX_ERR "unexpected payload size (cid: %x, len: %u)\n",
  693. + in_event->command_id, in_event->length);
  694. + return SSAM_NOTIF_HANDLED;
  695. + }
  696. +
  697. + event.type = in_event->target_category;
  698. + event.code = in_event->command_id;
  699. + event.arg0 = in_event->length >= 1 ? in_event->data[0] : 0x00;
  700. + event.arg1 = in_event->length >= 2 ? in_event->data[1] : 0x00;
  701. + surface_dtx_push_event(ddev, &event);
  702. + break;
  703. +
  704. + default:
  705. + return 0;
  706. + }
  707. +
  708. + // update device mode
  709. + if (in_event->command_id == SAM_EVENT_DTX_CID_CONNECTION) {
  710. + delay = event.arg0 ? DTX_CONNECT_OPMODE_DELAY : 0;
  711. + schedule_delayed_work(&ddev->opmode_work, delay);
  712. + }
  713. +
  714. + return SSAM_NOTIF_HANDLED;
  715. +}
  716. +
  717. +
  718. +static struct input_dev *surface_dtx_register_inputdev(struct platform_device *pdev)
  719. +{
  720. + struct input_dev *input_dev;
  721. + int status;
  722. +
  723. + input_dev = input_allocate_device();
  724. + if (!input_dev)
  725. + return ERR_PTR(-ENOMEM);
  726. +
  727. + input_dev->name = DTX_INPUT_NAME;
  728. + input_dev->dev.parent = &pdev->dev;
  729. + input_dev->id.bustype = BUS_VIRTUAL;
  730. + input_dev->id.vendor = USB_VENDOR_ID_MICROSOFT;
  731. + input_dev->id.product = USB_DEVICE_ID_MS_SURFACE_BASE_2_INTEGRATION;
  732. +
  733. + input_set_capability(input_dev, EV_SW, SW_TABLET_MODE);
  734. +
  735. + status = surface_sam_query_opmpde();
  736. + if (status < 0) {
  737. + input_free_device(input_dev);
  738. + return ERR_PTR(status);
  739. + }
  740. +
  741. + input_report_switch(input_dev, SW_TABLET_MODE, status != DTX_OPMODE_LAPTOP);
  742. +
  743. + status = input_register_device(input_dev);
  744. + if (status) {
  745. + input_unregister_device(input_dev);
  746. + return ERR_PTR(status);
  747. + }
  748. +
  749. + return input_dev;
  750. +}
  751. +
  752. +
  753. +static int surface_sam_dtx_probe(struct platform_device *pdev)
  754. +{
  755. + struct surface_dtx_dev *ddev = &surface_dtx_dev;
  756. + struct input_dev *input_dev;
  757. + int status;
  758. +
  759. + // link to ec
  760. + status = surface_sam_ssh_consumer_register(&pdev->dev);
  761. + if (status)
  762. + return status == -ENXIO ? -EPROBE_DEFER : status;
  763. +
  764. + input_dev = surface_dtx_register_inputdev(pdev);
  765. + if (IS_ERR(input_dev))
  766. + return PTR_ERR(input_dev);
  767. +
  768. + // initialize device
  769. + mutex_lock(&ddev->mutex);
  770. + if (ddev->active) {
  771. + mutex_unlock(&ddev->mutex);
  772. + status = -ENODEV;
  773. + goto err_register;
  774. + }
  775. +
  776. + INIT_DELAYED_WORK(&ddev->opmode_work, surface_dtx_opmode_workfn);
  777. + INIT_LIST_HEAD(&ddev->client_list);
  778. + init_waitqueue_head(&ddev->waitq);
  779. + ddev->active = true;
  780. + ddev->input_dev = input_dev;
  781. + mutex_unlock(&ddev->mutex);
  782. +
  783. + status = misc_register(&ddev->mdev);
  784. + if (status)
  785. + goto err_register;
  786. +
  787. + // set up events
  788. + ddev->notif.base.priority = 1;
  789. + ddev->notif.base.fn = surface_dtx_notification;
  790. + ddev->notif.event.reg = SSAM_EVENT_REGISTRY_SAM;
  791. + ddev->notif.event.id.target_category = SSAM_SSH_TC_BAS;
  792. + ddev->notif.event.id.instance = 0;
  793. + ddev->notif.event.flags = SSAM_EVENT_SEQUENCED;
  794. +
  795. + status = surface_sam_ssh_notifier_register(&ddev->notif);
  796. + if (status)
  797. + goto err_events_setup;
  798. +
  799. + return 0;
  800. +
  801. +err_events_setup:
  802. + misc_deregister(&ddev->mdev);
  803. +err_register:
  804. + input_unregister_device(ddev->input_dev);
  805. + return status;
  806. +}
  807. +
  808. +static int surface_sam_dtx_remove(struct platform_device *pdev)
  809. +{
  810. + struct surface_dtx_dev *ddev = &surface_dtx_dev;
  811. + struct surface_dtx_client *client;
  812. +
  813. + mutex_lock(&ddev->mutex);
  814. + if (!ddev->active) {
  815. + mutex_unlock(&ddev->mutex);
  816. + return 0;
  817. + }
  818. +
  819. + // mark as inactive
  820. + ddev->active = false;
  821. + mutex_unlock(&ddev->mutex);
  822. +
  823. + // After this call we're guaranteed that no more input events will arive
  824. + surface_sam_ssh_notifier_unregister(&ddev->notif);
  825. +
  826. + // wake up clients
  827. + spin_lock(&ddev->client_lock);
  828. + list_for_each_entry(client, &ddev->client_list, node) {
  829. + kill_fasync(&client->fasync, SIGIO, POLL_HUP);
  830. + }
  831. + spin_unlock(&ddev->client_lock);
  832. +
  833. + wake_up_interruptible(&ddev->waitq);
  834. +
  835. + // unregister user-space devices
  836. + input_unregister_device(ddev->input_dev);
  837. + misc_deregister(&ddev->mdev);
  838. +
  839. + return 0;
  840. +}
  841. +
  842. +
  843. +static const struct acpi_device_id surface_sam_dtx_match[] = {
  844. + { "MSHW0133", 0 },
  845. + { },
  846. +};
  847. +MODULE_DEVICE_TABLE(acpi, surface_sam_dtx_match);
  848. +
  849. +static struct platform_driver surface_sam_dtx = {
  850. + .probe = surface_sam_dtx_probe,
  851. + .remove = surface_sam_dtx_remove,
  852. + .driver = {
  853. + .name = "surface_sam_dtx",
  854. + .acpi_match_table = surface_sam_dtx_match,
  855. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  856. + },
  857. +};
  858. +module_platform_driver(surface_sam_dtx);
  859. +
  860. +MODULE_AUTHOR("Maximilian Luz <luzmaximilian@gmail.com>");
  861. +MODULE_DESCRIPTION("Surface Detachment System (DTX) Driver for 5th Generation Surface Devices");
  862. +MODULE_LICENSE("GPL");
  863. diff --git a/drivers/platform/x86/surface_sam/surface_sam_hps.c b/drivers/platform/x86/surface_sam/surface_sam_hps.c
  864. new file mode 100644
  865. index 000000000000..40f39f29113c
  866. --- /dev/null
  867. +++ b/drivers/platform/x86/surface_sam/surface_sam_hps.c
  868. @@ -0,0 +1,1297 @@
  869. +// SPDX-License-Identifier: GPL-2.0-or-later
  870. +/*
  871. + * Surface dGPU hot-plug system driver.
  872. + * Supports explicit setting of the dGPU power-state on the Surface Book 2 and
  873. + * properly handles hot-plugging by detaching the base.
  874. + */
  875. +
  876. +#include <linux/acpi.h>
  877. +#include <linux/delay.h>
  878. +#include <linux/gpio.h>
  879. +#include <linux/kernel.h>
  880. +#include <linux/module.h>
  881. +#include <linux/mutex.h>
  882. +#include <linux/pci.h>
  883. +#include <linux/platform_device.h>
  884. +#include <linux/sysfs.h>
  885. +
  886. +#include "surface_sam_ssh.h"
  887. +#include "surface_sam_san.h"
  888. +
  889. +
  890. +// TODO: vgaswitcheroo integration
  891. +
  892. +
  893. +static void dbg_dump_drvsta(struct platform_device *pdev, const char *prefix);
  894. +
  895. +
  896. +#define SHPS_DSM_REVISION 1
  897. +#define SHPS_DSM_GPU_ADDRS 0x02
  898. +#define SHPS_DSM_GPU_POWER 0x05
  899. +static const guid_t SHPS_DSM_UUID =
  900. + GUID_INIT(0x5515a847, 0xed55, 0x4b27, 0x83, 0x52, 0xcd,
  901. + 0x32, 0x0e, 0x10, 0x36, 0x0a);
  902. +
  903. +
  904. +#define SAM_DGPU_TC 0x13
  905. +#define SAM_DGPU_CID_POWERON 0x02
  906. +
  907. +#define SAM_DTX_TC 0x11
  908. +#define SAM_DTX_CID_LATCH_LOCK 0x06
  909. +#define SAM_DTX_CID_LATCH_UNLOCK 0x07
  910. +#define ACPI_SGCP_NOTIFY_POWER_ON 0x81
  911. +
  912. +#define SHPS_DSM_GPU_ADDRS_RP "RP5_PCIE"
  913. +#define SHPS_DSM_GPU_ADDRS_DGPU "DGPU_PCIE"
  914. +#define SHPS_PCI_GPU_ADDR_RP "\\_SB.PCI0.RP13._ADR"
  915. +
  916. +static const struct acpi_gpio_params gpio_base_presence_int = { 0, 0, false };
  917. +static const struct acpi_gpio_params gpio_base_presence = { 1, 0, false };
  918. +static const struct acpi_gpio_params gpio_dgpu_power_int = { 2, 0, false };
  919. +static const struct acpi_gpio_params gpio_dgpu_power = { 3, 0, false };
  920. +static const struct acpi_gpio_params gpio_dgpu_presence_int = { 4, 0, false };
  921. +static const struct acpi_gpio_params gpio_dgpu_presence = { 5, 0, false };
  922. +
  923. +static const struct acpi_gpio_mapping shps_acpi_gpios[] = {
  924. + { "base_presence-int-gpio", &gpio_base_presence_int, 1 },
  925. + { "base_presence-gpio", &gpio_base_presence, 1 },
  926. + { "dgpu_power-int-gpio", &gpio_dgpu_power_int, 1 },
  927. + { "dgpu_power-gpio", &gpio_dgpu_power, 1 },
  928. + { "dgpu_presence-int-gpio", &gpio_dgpu_presence_int, 1 },
  929. + { "dgpu_presence-gpio", &gpio_dgpu_presence, 1 },
  930. + { },
  931. +};
  932. +
  933. +
  934. +enum shps_dgpu_power {
  935. + SHPS_DGPU_POWER_OFF = 0,
  936. + SHPS_DGPU_POWER_ON = 1,
  937. + SHPS_DGPU_POWER_UNKNOWN = 2,
  938. +};
  939. +
  940. +static const char *shps_dgpu_power_str(enum shps_dgpu_power power)
  941. +{
  942. + if (power == SHPS_DGPU_POWER_OFF)
  943. + return "off";
  944. + else if (power == SHPS_DGPU_POWER_ON)
  945. + return "on";
  946. + else if (power == SHPS_DGPU_POWER_UNKNOWN)
  947. + return "unknown";
  948. + else
  949. + return "<invalid>";
  950. +}
  951. +
  952. +enum shps_notification_method {
  953. + SHPS_NOTIFICATION_METHOD_SAN = 1,
  954. + SHPS_NOTIFICATION_METHOD_SGCP = 2
  955. +};
  956. +
  957. +struct shps_hardware_traits {
  958. + enum shps_notification_method notification_method;
  959. + const char *dgpu_rp_pci_address;
  960. +};
  961. +
  962. +struct shps_driver_data {
  963. + struct mutex lock;
  964. + struct pci_dev *dgpu_root_port;
  965. + struct pci_saved_state *dgpu_root_port_state;
  966. + struct gpio_desc *gpio_dgpu_power;
  967. + struct gpio_desc *gpio_dgpu_presence;
  968. + struct gpio_desc *gpio_base_presence;
  969. + unsigned int irq_dgpu_presence;
  970. + unsigned int irq_base_presence;
  971. + unsigned long state;
  972. + acpi_handle sgpc_handle;
  973. + struct shps_hardware_traits hardware_traits;
  974. +};
  975. +
  976. +struct shps_hardware_probe {
  977. + const char *hardware_id;
  978. + int generation;
  979. + struct shps_hardware_traits *hardware_traits;
  980. +};
  981. +
  982. +static struct shps_hardware_traits shps_gen1_hwtraits = {
  983. + .notification_method = SHPS_NOTIFICATION_METHOD_SAN
  984. +};
  985. +
  986. +static struct shps_hardware_traits shps_gen2_hwtraits = {
  987. + .notification_method = SHPS_NOTIFICATION_METHOD_SGCP,
  988. + .dgpu_rp_pci_address = SHPS_PCI_GPU_ADDR_RP
  989. +};
  990. +
  991. +static const struct shps_hardware_probe shps_hardware_probe_match[] = {
  992. + /* Surface Book 3 */
  993. + { "MSHW0117", 2, &shps_gen2_hwtraits },
  994. +
  995. + /* Surface Book 2 (default, must be last entry) */
  996. + { NULL, 1, &shps_gen1_hwtraits }
  997. +};
  998. +
  999. +#define SHPS_STATE_BIT_PWRTGT 0 /* desired power state: 1 for on, 0 for off */
  1000. +#define SHPS_STATE_BIT_RPPWRON_SYNC 1 /* synchronous/requested power-up in progress */
  1001. +#define SHPS_STATE_BIT_WAKE_ENABLED 2 /* wakeup via base-presence GPIO enabled */
  1002. +
  1003. +
  1004. +#define SHPS_DGPU_PARAM_PERM 0644
  1005. +
  1006. +enum shps_dgpu_power_mp {
  1007. + SHPS_DGPU_MP_POWER_OFF = SHPS_DGPU_POWER_OFF,
  1008. + SHPS_DGPU_MP_POWER_ON = SHPS_DGPU_POWER_ON,
  1009. + SHPS_DGPU_MP_POWER_ASIS = -1,
  1010. +
  1011. + __SHPS_DGPU_MP_POWER_START = -1,
  1012. + __SHPS_DGPU_MP_POWER_END = 1,
  1013. +};
  1014. +
  1015. +static int param_dgpu_power_set(const char *val, const struct kernel_param *kp)
  1016. +{
  1017. + int power = SHPS_DGPU_MP_POWER_OFF;
  1018. + int status;
  1019. +
  1020. + status = kstrtoint(val, 0, &power);
  1021. + if (status)
  1022. + return status;
  1023. +
  1024. + if (power < __SHPS_DGPU_MP_POWER_START || power > __SHPS_DGPU_MP_POWER_END)
  1025. + return -EINVAL;
  1026. +
  1027. + return param_set_int(val, kp);
  1028. +}
  1029. +
  1030. +static const struct kernel_param_ops param_dgpu_power_ops = {
  1031. + .set = param_dgpu_power_set,
  1032. + .get = param_get_int,
  1033. +};
  1034. +
  1035. +static int param_dgpu_power_init = SHPS_DGPU_MP_POWER_OFF;
  1036. +static int param_dgpu_power_exit = SHPS_DGPU_MP_POWER_ON;
  1037. +static int param_dgpu_power_susp = SHPS_DGPU_MP_POWER_ASIS;
  1038. +static bool param_dtx_latch = true;
  1039. +
  1040. +module_param_cb(dgpu_power_init, &param_dgpu_power_ops, &param_dgpu_power_init, SHPS_DGPU_PARAM_PERM);
  1041. +module_param_cb(dgpu_power_exit, &param_dgpu_power_ops, &param_dgpu_power_exit, SHPS_DGPU_PARAM_PERM);
  1042. +module_param_cb(dgpu_power_susp, &param_dgpu_power_ops, &param_dgpu_power_susp, SHPS_DGPU_PARAM_PERM);
  1043. +module_param_named(dtx_latch, param_dtx_latch, bool, SHPS_DGPU_PARAM_PERM);
  1044. +
  1045. +MODULE_PARM_DESC(dgpu_power_init, "dGPU power state to be set on init (0: off / 1: on / 2: as-is, default: off)");
  1046. +MODULE_PARM_DESC(dgpu_power_exit, "dGPU power state to be set on exit (0: off / 1: on / 2: as-is, default: on)");
  1047. +MODULE_PARM_DESC(dgpu_power_susp, "dGPU power state to be set on exit (0: off / 1: on / 2: as-is, default: as-is)");
  1048. +MODULE_PARM_DESC(dtx_latch, "lock/unlock DTX base latch in accordance to power-state (Y/n)");
  1049. +
  1050. +static int dtx_cmd_simple(u8 cid)
  1051. +{
  1052. + struct surface_sam_ssh_rqst rqst = {
  1053. + .tc = SAM_DTX_TC,
  1054. + .cid = cid,
  1055. + .iid = 0x00,
  1056. + .chn = 0x01,
  1057. + .snc = 0x00,
  1058. + .cdl = 0x00,
  1059. + .pld = NULL,
  1060. + };
  1061. +
  1062. + return surface_sam_ssh_rqst(&rqst, NULL);
  1063. +}
  1064. +
  1065. +static inline int shps_dtx_latch_lock(void)
  1066. +{
  1067. + return dtx_cmd_simple(SAM_DTX_CID_LATCH_LOCK);
  1068. +}
  1069. +
  1070. +static inline int shps_dtx_latch_unlock(void)
  1071. +{
  1072. + return dtx_cmd_simple(SAM_DTX_CID_LATCH_UNLOCK);
  1073. +}
  1074. +
  1075. +static int shps_dgpu_dsm_get_pci_addr_from_adr(struct platform_device *pdev, const char *entry) {
  1076. + acpi_handle handle = ACPI_HANDLE(&pdev->dev);
  1077. + int status;
  1078. + struct acpi_object_list input;
  1079. + union acpi_object input_args[0];
  1080. + u64 device_addr;
  1081. + u8 bus, dev, fun;
  1082. +
  1083. + input.count = 0;
  1084. + input.pointer = input_args;
  1085. +
  1086. +
  1087. + status = acpi_evaluate_integer(handle, (acpi_string)entry, &input, &device_addr);
  1088. + if (status) {
  1089. + return -ENODEV;
  1090. + }
  1091. +
  1092. + bus = 0;
  1093. + dev = (device_addr & 0xFF0000) >> 16;
  1094. + fun = device_addr & 0xFF;
  1095. +
  1096. + dev_info(&pdev->dev, "found pci device at bus = %d, dev = %x, fun = %x\n",
  1097. + (u32)bus, (u32)dev, (u32)fun);
  1098. +
  1099. + return bus << 8 | PCI_DEVFN(dev, fun);
  1100. +}
  1101. +
  1102. +static int shps_dgpu_dsm_get_pci_addr_from_dsm(struct platform_device *pdev, const char *entry)
  1103. +{
  1104. + acpi_handle handle = ACPI_HANDLE(&pdev->dev);
  1105. + union acpi_object *result;
  1106. + union acpi_object *e0;
  1107. + union acpi_object *e1;
  1108. + union acpi_object *e2;
  1109. + u64 device_addr = 0;
  1110. + u8 bus, dev, fun;
  1111. + int i;
  1112. +
  1113. +
  1114. + result = acpi_evaluate_dsm_typed(handle, &SHPS_DSM_UUID, SHPS_DSM_REVISION,
  1115. + SHPS_DSM_GPU_ADDRS, NULL, ACPI_TYPE_PACKAGE);
  1116. +
  1117. + if (IS_ERR_OR_NULL(result))
  1118. + return result ? PTR_ERR(result) : -EIO;
  1119. +
  1120. + // three entries per device: name, address, <integer>
  1121. + for (i = 0; i + 2 < result->package.count; i += 3) {
  1122. + e0 = &result->package.elements[i];
  1123. + e1 = &result->package.elements[i + 1];
  1124. + e2 = &result->package.elements[i + 2];
  1125. +
  1126. + if (e0->type != ACPI_TYPE_STRING) {
  1127. + ACPI_FREE(result);
  1128. + return -EIO;
  1129. + }
  1130. +
  1131. + if (e1->type != ACPI_TYPE_INTEGER) {
  1132. + ACPI_FREE(result);
  1133. + return -EIO;
  1134. + }
  1135. +
  1136. + if (e2->type != ACPI_TYPE_INTEGER) {
  1137. + ACPI_FREE(result);
  1138. + return -EIO;
  1139. + }
  1140. +
  1141. + if (strncmp(e0->string.pointer, entry, 64) == 0)
  1142. + device_addr = e1->integer.value;
  1143. + }
  1144. +
  1145. + ACPI_FREE(result);
  1146. + if (device_addr == 0)
  1147. + return -ENODEV;
  1148. +
  1149. +
  1150. + // convert address
  1151. + bus = (device_addr & 0x0FF00000) >> 20;
  1152. + dev = (device_addr & 0x000F8000) >> 15;
  1153. + fun = (device_addr & 0x00007000) >> 12;
  1154. +
  1155. + return bus << 8 | PCI_DEVFN(dev, fun);
  1156. +}
  1157. +
  1158. +static struct pci_dev *shps_dgpu_dsm_get_pci_dev(struct platform_device *pdev)
  1159. +{
  1160. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1161. + struct pci_dev *dev;
  1162. + int addr;
  1163. +
  1164. +
  1165. + if (drvdata->hardware_traits.dgpu_rp_pci_address) {
  1166. + addr = shps_dgpu_dsm_get_pci_addr_from_adr(pdev, drvdata->hardware_traits.dgpu_rp_pci_address);
  1167. + } else {
  1168. + addr = shps_dgpu_dsm_get_pci_addr_from_dsm(pdev, SHPS_DSM_GPU_ADDRS_RP);
  1169. + }
  1170. +
  1171. + if (addr < 0)
  1172. + return ERR_PTR(addr);
  1173. +
  1174. + dev = pci_get_domain_bus_and_slot(0, (addr & 0xFF00) >> 8, addr & 0xFF);
  1175. + return dev ? dev : ERR_PTR(-ENODEV);
  1176. +}
  1177. +
  1178. +
  1179. +static int shps_dgpu_dsm_get_power_unlocked(struct platform_device *pdev)
  1180. +{
  1181. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1182. + struct gpio_desc *gpio = drvdata->gpio_dgpu_power;
  1183. + int status;
  1184. +
  1185. + status = gpiod_get_value_cansleep(gpio);
  1186. + if (status < 0)
  1187. + return status;
  1188. +
  1189. + return status == 0 ? SHPS_DGPU_POWER_OFF : SHPS_DGPU_POWER_ON;
  1190. +}
  1191. +
  1192. +static int shps_dgpu_dsm_get_power(struct platform_device *pdev)
  1193. +{
  1194. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1195. + int status;
  1196. +
  1197. + mutex_lock(&drvdata->lock);
  1198. + status = shps_dgpu_dsm_get_power_unlocked(pdev);
  1199. + mutex_unlock(&drvdata->lock);
  1200. +
  1201. + return status;
  1202. +}
  1203. +
  1204. +static int __shps_dgpu_dsm_set_power_unlocked(struct platform_device *pdev, enum shps_dgpu_power power)
  1205. +{
  1206. + acpi_handle handle = ACPI_HANDLE(&pdev->dev);
  1207. + union acpi_object *result;
  1208. + union acpi_object param;
  1209. +
  1210. + dev_info(&pdev->dev, "setting dGPU direct power to \'%s\'\n", shps_dgpu_power_str(power));
  1211. +
  1212. + param.type = ACPI_TYPE_INTEGER;
  1213. + param.integer.value = power == SHPS_DGPU_POWER_ON;
  1214. +
  1215. + result = acpi_evaluate_dsm_typed(handle, &SHPS_DSM_UUID, SHPS_DSM_REVISION,
  1216. + SHPS_DSM_GPU_POWER, &param, ACPI_TYPE_BUFFER);
  1217. +
  1218. + if (IS_ERR_OR_NULL(result))
  1219. + return result ? PTR_ERR(result) : -EIO;
  1220. +
  1221. + // check for the expected result
  1222. + if (result->buffer.length != 1 || result->buffer.pointer[0] != 0) {
  1223. + ACPI_FREE(result);
  1224. + return -EIO;
  1225. + }
  1226. +
  1227. + ACPI_FREE(result);
  1228. + return 0;
  1229. +}
  1230. +
  1231. +static int shps_dgpu_dsm_set_power_unlocked(struct platform_device *pdev, enum shps_dgpu_power power)
  1232. +{
  1233. + int status;
  1234. +
  1235. + if (power != SHPS_DGPU_POWER_ON && power != SHPS_DGPU_POWER_OFF)
  1236. + return -EINVAL;
  1237. +
  1238. + status = shps_dgpu_dsm_get_power_unlocked(pdev);
  1239. + if (status < 0)
  1240. + return status;
  1241. + if (status == power)
  1242. + return 0;
  1243. +
  1244. + return __shps_dgpu_dsm_set_power_unlocked(pdev, power);
  1245. +}
  1246. +
  1247. +static int shps_dgpu_dsm_set_power(struct platform_device *pdev, enum shps_dgpu_power power)
  1248. +{
  1249. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1250. + int status;
  1251. +
  1252. + mutex_lock(&drvdata->lock);
  1253. + status = shps_dgpu_dsm_set_power_unlocked(pdev, power);
  1254. + mutex_unlock(&drvdata->lock);
  1255. +
  1256. + return status;
  1257. +}
  1258. +
  1259. +
  1260. +static bool shps_rp_link_up(struct pci_dev *rp)
  1261. +{
  1262. + u16 lnksta = 0, sltsta = 0;
  1263. +
  1264. + pcie_capability_read_word(rp, PCI_EXP_LNKSTA, &lnksta);
  1265. + pcie_capability_read_word(rp, PCI_EXP_SLTSTA, &sltsta);
  1266. +
  1267. + return (lnksta & PCI_EXP_LNKSTA_DLLLA) || (sltsta & PCI_EXP_SLTSTA_PDS);
  1268. +}
  1269. +
  1270. +
  1271. +static int shps_dgpu_rp_get_power_unlocked(struct platform_device *pdev)
  1272. +{
  1273. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1274. + struct pci_dev *rp = drvdata->dgpu_root_port;
  1275. +
  1276. + if (rp->current_state == PCI_D3hot || rp->current_state == PCI_D3cold)
  1277. + return SHPS_DGPU_POWER_OFF;
  1278. + else if (rp->current_state == PCI_UNKNOWN || rp->current_state == PCI_POWER_ERROR)
  1279. + return SHPS_DGPU_POWER_UNKNOWN;
  1280. + else
  1281. + return SHPS_DGPU_POWER_ON;
  1282. +}
  1283. +
  1284. +static int shps_dgpu_rp_get_power(struct platform_device *pdev)
  1285. +{
  1286. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1287. + int status;
  1288. +
  1289. + mutex_lock(&drvdata->lock);
  1290. + status = shps_dgpu_rp_get_power_unlocked(pdev);
  1291. + mutex_unlock(&drvdata->lock);
  1292. +
  1293. + return status;
  1294. +}
  1295. +
  1296. +static int __shps_dgpu_rp_set_power_unlocked(struct platform_device *pdev, enum shps_dgpu_power power)
  1297. +{
  1298. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1299. + struct pci_dev *rp = drvdata->dgpu_root_port;
  1300. + int status, i;
  1301. +
  1302. + dev_info(&pdev->dev, "setting dGPU power state to \'%s\'\n", shps_dgpu_power_str(power));
  1303. +
  1304. + dbg_dump_drvsta(pdev, "__shps_dgpu_rp_set_power_unlocked.1");
  1305. + if (power == SHPS_DGPU_POWER_ON) {
  1306. + set_bit(SHPS_STATE_BIT_RPPWRON_SYNC, &drvdata->state);
  1307. + pci_set_power_state(rp, PCI_D0);
  1308. +
  1309. + if (drvdata->dgpu_root_port_state)
  1310. + pci_load_and_free_saved_state(rp, &drvdata->dgpu_root_port_state);
  1311. +
  1312. + pci_restore_state(rp);
  1313. +
  1314. + if (!pci_is_enabled(rp))
  1315. + pci_enable_device(rp);
  1316. +
  1317. + pci_set_master(rp);
  1318. + clear_bit(SHPS_STATE_BIT_RPPWRON_SYNC, &drvdata->state);
  1319. +
  1320. + set_bit(SHPS_STATE_BIT_PWRTGT, &drvdata->state);
  1321. + } else {
  1322. + if (!drvdata->dgpu_root_port_state) {
  1323. + pci_save_state(rp);
  1324. + drvdata->dgpu_root_port_state = pci_store_saved_state(rp);
  1325. + }
  1326. +
  1327. + /*
  1328. + * To properly update the hot-plug system we need to "remove" the dGPU
  1329. + * before disabling it and sending it to D3cold. Following this, we
  1330. + * need to wait for the link and slot status to actually change.
  1331. + */
  1332. + status = shps_dgpu_dsm_set_power_unlocked(pdev, SHPS_DGPU_POWER_OFF);
  1333. + if (status)
  1334. + return status;
  1335. +
  1336. + for (i = 0; i < 20 && shps_rp_link_up(rp); i++)
  1337. + msleep(50);
  1338. +
  1339. + if (shps_rp_link_up(rp))
  1340. + dev_err(&pdev->dev, "dGPU removal via DSM timed out\n");
  1341. +
  1342. + pci_clear_master(rp);
  1343. +
  1344. + if (pci_is_enabled(rp))
  1345. + pci_disable_device(rp);
  1346. +
  1347. + pci_set_power_state(rp, PCI_D3cold);
  1348. +
  1349. + clear_bit(SHPS_STATE_BIT_PWRTGT, &drvdata->state);
  1350. + }
  1351. + dbg_dump_drvsta(pdev, "__shps_dgpu_rp_set_power_unlocked.2");
  1352. +
  1353. + return 0;
  1354. +}
  1355. +
  1356. +static int shps_dgpu_rp_set_power_unlocked(struct platform_device *pdev, enum shps_dgpu_power power)
  1357. +{
  1358. + int status;
  1359. +
  1360. + if (power != SHPS_DGPU_POWER_ON && power != SHPS_DGPU_POWER_OFF)
  1361. + return -EINVAL;
  1362. +
  1363. + status = shps_dgpu_rp_get_power_unlocked(pdev);
  1364. + if (status < 0)
  1365. + return status;
  1366. + if (status == power)
  1367. + return 0;
  1368. +
  1369. + return __shps_dgpu_rp_set_power_unlocked(pdev, power);
  1370. +}
  1371. +
  1372. +static int shps_dgpu_rp_set_power(struct platform_device *pdev, enum shps_dgpu_power power)
  1373. +{
  1374. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1375. + int status;
  1376. +
  1377. + mutex_lock(&drvdata->lock);
  1378. + status = shps_dgpu_rp_set_power_unlocked(pdev, power);
  1379. + mutex_unlock(&drvdata->lock);
  1380. +
  1381. + return status;
  1382. +}
  1383. +
  1384. +
  1385. +static int shps_dgpu_set_power(struct platform_device *pdev, enum shps_dgpu_power power)
  1386. +{
  1387. + int status;
  1388. +
  1389. + if (!param_dtx_latch)
  1390. + return shps_dgpu_rp_set_power(pdev, power);
  1391. +
  1392. + if (power == SHPS_DGPU_POWER_ON) {
  1393. + status = shps_dtx_latch_lock();
  1394. + if (status)
  1395. + return status;
  1396. +
  1397. + status = shps_dgpu_rp_set_power(pdev, power);
  1398. + if (status)
  1399. + shps_dtx_latch_unlock();
  1400. +
  1401. + } else {
  1402. + status = shps_dgpu_rp_set_power(pdev, power);
  1403. + if (status)
  1404. + return status;
  1405. +
  1406. + status = shps_dtx_latch_unlock();
  1407. + }
  1408. +
  1409. + return status;
  1410. +}
  1411. +
  1412. +
  1413. +static int shps_dgpu_is_present(struct platform_device *pdev)
  1414. +{
  1415. + struct shps_driver_data *drvdata;
  1416. +
  1417. + drvdata = platform_get_drvdata(pdev);
  1418. + return gpiod_get_value_cansleep(drvdata->gpio_dgpu_presence);
  1419. +}
  1420. +
  1421. +
  1422. +static ssize_t dgpu_power_show(struct device *dev, struct device_attribute *attr, char *data)
  1423. +{
  1424. + struct platform_device *pdev = to_platform_device(dev);
  1425. + int power = shps_dgpu_rp_get_power(pdev);
  1426. +
  1427. + if (power < 0)
  1428. + return power;
  1429. +
  1430. + return sprintf(data, "%s\n", shps_dgpu_power_str(power));
  1431. +}
  1432. +
  1433. +static ssize_t dgpu_power_store(struct device *dev, struct device_attribute *attr,
  1434. + const char *data, size_t count)
  1435. +{
  1436. + struct platform_device *pdev = to_platform_device(dev);
  1437. + enum shps_dgpu_power power;
  1438. + bool b = false;
  1439. + int status;
  1440. +
  1441. + status = kstrtobool(data, &b);
  1442. + if (status)
  1443. + return status;
  1444. +
  1445. + status = shps_dgpu_is_present(pdev);
  1446. + if (status <= 0)
  1447. + return status < 0 ? status : -EPERM;
  1448. +
  1449. + power = b ? SHPS_DGPU_POWER_ON : SHPS_DGPU_POWER_OFF;
  1450. + status = shps_dgpu_set_power(pdev, power);
  1451. +
  1452. + return status < 0 ? status : count;
  1453. +}
  1454. +
  1455. +static ssize_t dgpu_power_dsm_show(struct device *dev, struct device_attribute *attr, char *data)
  1456. +{
  1457. + struct platform_device *pdev = to_platform_device(dev);
  1458. + int power = shps_dgpu_dsm_get_power(pdev);
  1459. +
  1460. + if (power < 0)
  1461. + return power;
  1462. +
  1463. + return sprintf(data, "%s\n", shps_dgpu_power_str(power));
  1464. +}
  1465. +
  1466. +static ssize_t dgpu_power_dsm_store(struct device *dev, struct device_attribute *attr,
  1467. + const char *data, size_t count)
  1468. +{
  1469. + struct platform_device *pdev = to_platform_device(dev);
  1470. + enum shps_dgpu_power power;
  1471. + bool b = false;
  1472. + int status;
  1473. +
  1474. + status = kstrtobool(data, &b);
  1475. + if (status)
  1476. + return status;
  1477. +
  1478. + status = shps_dgpu_is_present(pdev);
  1479. + if (status <= 0)
  1480. + return status < 0 ? status : -EPERM;
  1481. +
  1482. + power = b ? SHPS_DGPU_POWER_ON : SHPS_DGPU_POWER_OFF;
  1483. + status = shps_dgpu_dsm_set_power(pdev, power);
  1484. +
  1485. + return status < 0 ? status : count;
  1486. +}
  1487. +
  1488. +static DEVICE_ATTR_RW(dgpu_power);
  1489. +static DEVICE_ATTR_RW(dgpu_power_dsm);
  1490. +
  1491. +static struct attribute *shps_power_attrs[] = {
  1492. + &dev_attr_dgpu_power.attr,
  1493. + &dev_attr_dgpu_power_dsm.attr,
  1494. + NULL,
  1495. +};
  1496. +ATTRIBUTE_GROUPS(shps_power);
  1497. +
  1498. +
  1499. +static void dbg_dump_power_states(struct platform_device *pdev, const char *prefix)
  1500. +{
  1501. + enum shps_dgpu_power power_dsm;
  1502. + enum shps_dgpu_power power_rp;
  1503. + int status;
  1504. +
  1505. + status = shps_dgpu_rp_get_power_unlocked(pdev);
  1506. + if (status < 0)
  1507. + dev_err(&pdev->dev, "%s: failed to get root-port power state: %d\n", prefix, status);
  1508. + power_rp = status;
  1509. +
  1510. + status = shps_dgpu_rp_get_power_unlocked(pdev);
  1511. + if (status < 0)
  1512. + dev_err(&pdev->dev, "%s: failed to get direct power state: %d\n", prefix, status);
  1513. + power_dsm = status;
  1514. +
  1515. + dev_dbg(&pdev->dev, "%s: root-port power state: %d\n", prefix, power_rp);
  1516. + dev_dbg(&pdev->dev, "%s: direct power state: %d\n", prefix, power_dsm);
  1517. +}
  1518. +
  1519. +static void dbg_dump_pciesta(struct platform_device *pdev, const char *prefix)
  1520. +{
  1521. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1522. + struct pci_dev *rp = drvdata->dgpu_root_port;
  1523. + u16 lnksta, lnksta2, sltsta, sltsta2;
  1524. +
  1525. + pcie_capability_read_word(rp, PCI_EXP_LNKSTA, &lnksta);
  1526. + pcie_capability_read_word(rp, PCI_EXP_LNKSTA2, &lnksta2);
  1527. + pcie_capability_read_word(rp, PCI_EXP_SLTSTA, &sltsta);
  1528. + pcie_capability_read_word(rp, PCI_EXP_SLTSTA2, &sltsta2);
  1529. +
  1530. + dev_dbg(&pdev->dev, "%s: LNKSTA: 0x%04x\n", prefix, lnksta);
  1531. + dev_dbg(&pdev->dev, "%s: LNKSTA2: 0x%04x\n", prefix, lnksta2);
  1532. + dev_dbg(&pdev->dev, "%s: SLTSTA: 0x%04x\n", prefix, sltsta);
  1533. + dev_dbg(&pdev->dev, "%s: SLTSTA2: 0x%04x\n", prefix, sltsta2);
  1534. +}
  1535. +
  1536. +static void dbg_dump_drvsta(struct platform_device *pdev, const char *prefix)
  1537. +{
  1538. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1539. + struct pci_dev *rp = drvdata->dgpu_root_port;
  1540. +
  1541. + dev_dbg(&pdev->dev, "%s: RP power: %d\n", prefix, rp->current_state);
  1542. + dev_dbg(&pdev->dev, "%s: RP state saved: %d\n", prefix, rp->state_saved);
  1543. + dev_dbg(&pdev->dev, "%s: RP state stored: %d\n", prefix, !!drvdata->dgpu_root_port_state);
  1544. + dev_dbg(&pdev->dev, "%s: RP enabled: %d\n", prefix, atomic_read(&rp->enable_cnt));
  1545. + dev_dbg(&pdev->dev, "%s: RP mastered: %d\n", prefix, rp->is_busmaster);
  1546. +}
  1547. +
  1548. +static int shps_pm_prepare(struct device *dev)
  1549. +{
  1550. + struct platform_device *pdev = to_platform_device(dev);
  1551. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1552. + bool pwrtgt;
  1553. + int status = 0;
  1554. +
  1555. + dbg_dump_power_states(pdev, "shps_pm_prepare");
  1556. +
  1557. + if (param_dgpu_power_susp != SHPS_DGPU_MP_POWER_ASIS) {
  1558. + pwrtgt = test_bit(SHPS_STATE_BIT_PWRTGT, &drvdata->state);
  1559. +
  1560. + status = shps_dgpu_set_power(pdev, param_dgpu_power_susp);
  1561. + if (status) {
  1562. + dev_err(&pdev->dev, "failed to power %s dGPU: %d\n",
  1563. + param_dgpu_power_susp == SHPS_DGPU_MP_POWER_OFF ? "off" : "on",
  1564. + status);
  1565. + return status;
  1566. + }
  1567. +
  1568. + if (pwrtgt)
  1569. + set_bit(SHPS_STATE_BIT_PWRTGT, &drvdata->state);
  1570. + else
  1571. + clear_bit(SHPS_STATE_BIT_PWRTGT, &drvdata->state);
  1572. + }
  1573. +
  1574. + return 0;
  1575. +}
  1576. +
  1577. +static void shps_pm_complete(struct device *dev)
  1578. +{
  1579. + struct platform_device *pdev = to_platform_device(dev);
  1580. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1581. + int status;
  1582. +
  1583. + dbg_dump_power_states(pdev, "shps_pm_complete");
  1584. + dbg_dump_pciesta(pdev, "shps_pm_complete");
  1585. + dbg_dump_drvsta(pdev, "shps_pm_complete.1");
  1586. +
  1587. + // update power target, dGPU may have been detached while suspended
  1588. + status = shps_dgpu_is_present(pdev);
  1589. + if (status < 0) {
  1590. + dev_err(&pdev->dev, "failed to get dGPU presence: %d\n", status);
  1591. + return;
  1592. + } else if (status == 0) {
  1593. + clear_bit(SHPS_STATE_BIT_PWRTGT, &drvdata->state);
  1594. + }
  1595. +
  1596. + /*
  1597. + * During resume, the PCIe core will power on the root-port, which in turn
  1598. + * will power on the dGPU. Most of the state synchronization is already
  1599. + * handled via the SAN RQSG handler, so it is in a fully consistent
  1600. + * on-state here. If requested, turn it off here.
  1601. + *
  1602. + * As there seem to be some synchronization issues turning off the dGPU
  1603. + * directly after the power-on SAN RQSG notification during the resume
  1604. + * process, let's do this here.
  1605. + *
  1606. + * TODO/FIXME:
  1607. + * This does not combat unhandled power-ons when the device is not fully
  1608. + * resumed, i.e. re-suspended before shps_pm_complete is called. Those
  1609. + * should normally not be an issue, but the dGPU does get hot even though
  1610. + * it is suspended, so ideally we want to keep it off.
  1611. + */
  1612. + if (!test_bit(SHPS_STATE_BIT_PWRTGT, &drvdata->state)) {
  1613. + status = shps_dgpu_set_power(pdev, SHPS_DGPU_POWER_OFF);
  1614. + if (status)
  1615. + dev_err(&pdev->dev, "failed to power-off dGPU: %d\n", status);
  1616. + }
  1617. +
  1618. + dbg_dump_drvsta(pdev, "shps_pm_complete.2");
  1619. +}
  1620. +
  1621. +static int shps_pm_suspend(struct device *dev)
  1622. +{
  1623. + struct platform_device *pdev = to_platform_device(dev);
  1624. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1625. + int status;
  1626. +
  1627. + if (device_may_wakeup(dev)) {
  1628. + status = enable_irq_wake(drvdata->irq_base_presence);
  1629. + if (status)
  1630. + return status;
  1631. +
  1632. + set_bit(SHPS_STATE_BIT_WAKE_ENABLED, &drvdata->state);
  1633. + }
  1634. +
  1635. + return 0;
  1636. +}
  1637. +
  1638. +static int shps_pm_resume(struct device *dev)
  1639. +{
  1640. + struct platform_device *pdev = to_platform_device(dev);
  1641. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1642. + int status = 0;
  1643. +
  1644. + if (test_and_clear_bit(SHPS_STATE_BIT_WAKE_ENABLED, &drvdata->state))
  1645. + status = disable_irq_wake(drvdata->irq_base_presence);
  1646. +
  1647. + return status;
  1648. +}
  1649. +
  1650. +static void shps_shutdown(struct platform_device *pdev)
  1651. +{
  1652. + int status;
  1653. +
  1654. + /*
  1655. + * Turn on dGPU before shutting down. This allows the core drivers to
  1656. + * properly shut down the device. If we don't do this, the pcieport driver
  1657. + * will complain that the device has already been disabled.
  1658. + */
  1659. + status = shps_dgpu_set_power(pdev, SHPS_DGPU_POWER_ON);
  1660. + if (status)
  1661. + dev_err(&pdev->dev, "failed to turn on dGPU: %d\n", status);
  1662. +}
  1663. +
  1664. +static int shps_dgpu_detached(struct platform_device *pdev)
  1665. +{
  1666. + dbg_dump_power_states(pdev, "shps_dgpu_detached");
  1667. + return shps_dgpu_set_power(pdev, SHPS_DGPU_POWER_OFF);
  1668. +}
  1669. +
  1670. +static int shps_dgpu_attached(struct platform_device *pdev)
  1671. +{
  1672. + dbg_dump_power_states(pdev, "shps_dgpu_attached");
  1673. + return 0;
  1674. +}
  1675. +
  1676. +static int shps_dgpu_powered_on(struct platform_device *pdev)
  1677. +{
  1678. + /*
  1679. + * This function gets called directly after a power-state transition of
  1680. + * the dGPU root port out of D3cold state, indicating a power-on of the
  1681. + * dGPU. Specifically, this function is called from the RQSG handler of
  1682. + * SAN, invoked by the ACPI _ON method of the dGPU root port. This means
  1683. + * that this function is run inside `pci_set_power_state(rp, ...)`
  1684. + * syncrhonously and thus returns before the `pci_set_power_state` call
  1685. + * does.
  1686. + *
  1687. + * `pci_set_power_state` may either be called by us or when the PCI
  1688. + * subsystem decides to power up the root port (e.g. during resume). Thus
  1689. + * we should use this function to ensure that the dGPU and root port
  1690. + * states are consistent when an unexpected power-up is encountered.
  1691. + */
  1692. +
  1693. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1694. + struct pci_dev *rp = drvdata->dgpu_root_port;
  1695. + int status;
  1696. +
  1697. + dbg_dump_drvsta(pdev, "shps_dgpu_powered_on.1");
  1698. +
  1699. + // if we caused the root port to power-on, return
  1700. + if (test_bit(SHPS_STATE_BIT_RPPWRON_SYNC, &drvdata->state))
  1701. + return 0;
  1702. +
  1703. + // if dGPU is not present, force power-target to off and return
  1704. + status = shps_dgpu_is_present(pdev);
  1705. + if (status == 0)
  1706. + clear_bit(SHPS_STATE_BIT_PWRTGT, &drvdata->state);
  1707. + if (status <= 0)
  1708. + return status;
  1709. +
  1710. + mutex_lock(&drvdata->lock);
  1711. +
  1712. + dbg_dump_power_states(pdev, "shps_dgpu_powered_on.1");
  1713. + dbg_dump_pciesta(pdev, "shps_dgpu_powered_on.1");
  1714. + if (drvdata->dgpu_root_port_state)
  1715. + pci_load_and_free_saved_state(rp, &drvdata->dgpu_root_port_state);
  1716. + pci_restore_state(rp);
  1717. + if (!pci_is_enabled(rp))
  1718. + pci_enable_device(rp);
  1719. + pci_set_master(rp);
  1720. + dbg_dump_drvsta(pdev, "shps_dgpu_powered_on.2");
  1721. + dbg_dump_power_states(pdev, "shps_dgpu_powered_on.2");
  1722. + dbg_dump_pciesta(pdev, "shps_dgpu_powered_on.2");
  1723. +
  1724. + mutex_unlock(&drvdata->lock);
  1725. +
  1726. + if (!test_bit(SHPS_STATE_BIT_PWRTGT, &drvdata->state)) {
  1727. + dev_warn(&pdev->dev, "unexpected dGPU power-on detected\n");
  1728. + // TODO: schedule state re-check and update
  1729. + }
  1730. +
  1731. + return 0;
  1732. +}
  1733. +
  1734. +static int shps_dgpu_handle_rqsg(struct surface_sam_san_rqsg *rqsg, void *data)
  1735. +{
  1736. + struct platform_device *pdev = data;
  1737. +
  1738. + if (rqsg->tc == SAM_DGPU_TC && rqsg->cid == SAM_DGPU_CID_POWERON)
  1739. + return shps_dgpu_powered_on(pdev);
  1740. +
  1741. + dev_warn(&pdev->dev, "unimplemented dGPU request: RQSG(0x%02x, 0x%02x, 0x%02x)\n",
  1742. + rqsg->tc, rqsg->cid, rqsg->iid);
  1743. + return 0;
  1744. +}
  1745. +
  1746. +static irqreturn_t shps_dgpu_presence_irq(int irq, void *data)
  1747. +{
  1748. + struct platform_device *pdev = data;
  1749. + bool dgpu_present;
  1750. + int status;
  1751. +
  1752. + status = shps_dgpu_is_present(pdev);
  1753. + if (status < 0) {
  1754. + dev_err(&pdev->dev, "failed to check physical dGPU presence: %d\n", status);
  1755. + return IRQ_HANDLED;
  1756. + }
  1757. +
  1758. + dgpu_present = status != 0;
  1759. + dev_info(&pdev->dev, "dGPU physically %s\n", dgpu_present ? "attached" : "detached");
  1760. +
  1761. + if (dgpu_present)
  1762. + status = shps_dgpu_attached(pdev);
  1763. + else
  1764. + status = shps_dgpu_detached(pdev);
  1765. +
  1766. + if (status)
  1767. + dev_err(&pdev->dev, "error handling dGPU interrupt: %d\n", status);
  1768. +
  1769. + return IRQ_HANDLED;
  1770. +}
  1771. +
  1772. +static irqreturn_t shps_base_presence_irq(int irq, void *data)
  1773. +{
  1774. + return IRQ_HANDLED; // nothing to do, just wake
  1775. +}
  1776. +
  1777. +
  1778. +static int shps_gpios_setup(struct platform_device *pdev)
  1779. +{
  1780. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1781. + struct gpio_desc *gpio_dgpu_power;
  1782. + struct gpio_desc *gpio_dgpu_presence;
  1783. + struct gpio_desc *gpio_base_presence;
  1784. + int status;
  1785. +
  1786. + // get GPIOs
  1787. + gpio_dgpu_power = devm_gpiod_get(&pdev->dev, "dgpu_power", GPIOD_IN);
  1788. + if (IS_ERR(gpio_dgpu_power)) {
  1789. + status = PTR_ERR(gpio_dgpu_power);
  1790. + goto err_out;
  1791. + }
  1792. +
  1793. + gpio_dgpu_presence = devm_gpiod_get(&pdev->dev, "dgpu_presence", GPIOD_IN);
  1794. + if (IS_ERR(gpio_dgpu_presence)) {
  1795. + status = PTR_ERR(gpio_dgpu_presence);
  1796. + goto err_out;
  1797. + }
  1798. +
  1799. + gpio_base_presence = devm_gpiod_get(&pdev->dev, "base_presence", GPIOD_IN);
  1800. + if (IS_ERR(gpio_base_presence)) {
  1801. + status = PTR_ERR(gpio_base_presence);
  1802. + goto err_out;
  1803. + }
  1804. +
  1805. + // export GPIOs
  1806. + status = gpiod_export(gpio_dgpu_power, false);
  1807. + if (status)
  1808. + goto err_out;
  1809. +
  1810. + status = gpiod_export(gpio_dgpu_presence, false);
  1811. + if (status)
  1812. + goto err_export_dgpu_presence;
  1813. +
  1814. + status = gpiod_export(gpio_base_presence, false);
  1815. + if (status)
  1816. + goto err_export_base_presence;
  1817. +
  1818. + // create sysfs links
  1819. + status = gpiod_export_link(&pdev->dev, "gpio-dgpu_power", gpio_dgpu_power);
  1820. + if (status)
  1821. + goto err_link_dgpu_power;
  1822. +
  1823. + status = gpiod_export_link(&pdev->dev, "gpio-dgpu_presence", gpio_dgpu_presence);
  1824. + if (status)
  1825. + goto err_link_dgpu_presence;
  1826. +
  1827. + status = gpiod_export_link(&pdev->dev, "gpio-base_presence", gpio_base_presence);
  1828. + if (status)
  1829. + goto err_link_base_presence;
  1830. +
  1831. + drvdata->gpio_dgpu_power = gpio_dgpu_power;
  1832. + drvdata->gpio_dgpu_presence = gpio_dgpu_presence;
  1833. + drvdata->gpio_base_presence = gpio_base_presence;
  1834. + return 0;
  1835. +
  1836. +err_link_base_presence:
  1837. + sysfs_remove_link(&pdev->dev.kobj, "gpio-dgpu_presence");
  1838. +err_link_dgpu_presence:
  1839. + sysfs_remove_link(&pdev->dev.kobj, "gpio-dgpu_power");
  1840. +err_link_dgpu_power:
  1841. + gpiod_unexport(gpio_base_presence);
  1842. +err_export_base_presence:
  1843. + gpiod_unexport(gpio_dgpu_presence);
  1844. +err_export_dgpu_presence:
  1845. + gpiod_unexport(gpio_dgpu_power);
  1846. +err_out:
  1847. + return status;
  1848. +}
  1849. +
  1850. +static void shps_gpios_remove(struct platform_device *pdev)
  1851. +{
  1852. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1853. +
  1854. + sysfs_remove_link(&pdev->dev.kobj, "gpio-base_presence");
  1855. + sysfs_remove_link(&pdev->dev.kobj, "gpio-dgpu_presence");
  1856. + sysfs_remove_link(&pdev->dev.kobj, "gpio-dgpu_power");
  1857. + gpiod_unexport(drvdata->gpio_base_presence);
  1858. + gpiod_unexport(drvdata->gpio_dgpu_presence);
  1859. + gpiod_unexport(drvdata->gpio_dgpu_power);
  1860. +}
  1861. +
  1862. +static int shps_gpios_setup_irq(struct platform_device *pdev)
  1863. +{
  1864. + const int irqf_dgpu = IRQF_SHARED | IRQF_ONESHOT | IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING;
  1865. + const int irqf_base = IRQF_SHARED;
  1866. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1867. + int status;
  1868. +
  1869. + status = gpiod_to_irq(drvdata->gpio_base_presence);
  1870. + if (status < 0)
  1871. + return status;
  1872. + drvdata->irq_base_presence = status;
  1873. +
  1874. + status = gpiod_to_irq(drvdata->gpio_dgpu_presence);
  1875. + if (status < 0)
  1876. + return status;
  1877. + drvdata->irq_dgpu_presence = status;
  1878. +
  1879. + status = request_irq(drvdata->irq_base_presence,
  1880. + shps_base_presence_irq, irqf_base,
  1881. + "shps_base_presence_irq", pdev);
  1882. + if (status) {
  1883. + dev_err(&pdev->dev, "base irq failed: %d\n", status);
  1884. + return status;
  1885. + }
  1886. +
  1887. + status = request_threaded_irq(drvdata->irq_dgpu_presence,
  1888. + NULL, shps_dgpu_presence_irq, irqf_dgpu,
  1889. + "shps_dgpu_presence_irq", pdev);
  1890. + if (status) {
  1891. + free_irq(drvdata->irq_base_presence, pdev);
  1892. + return status;
  1893. + }
  1894. +
  1895. + return 0;
  1896. +}
  1897. +
  1898. +static void shps_gpios_remove_irq(struct platform_device *pdev)
  1899. +{
  1900. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1901. +
  1902. + free_irq(drvdata->irq_base_presence, pdev);
  1903. + free_irq(drvdata->irq_dgpu_presence, pdev);
  1904. +}
  1905. +
  1906. +static void shps_sgcp_notify(acpi_handle device, u32 value, void *context) {
  1907. + struct platform_device *pdev = context;
  1908. + switch (value) {
  1909. + case ACPI_SGCP_NOTIFY_POWER_ON:
  1910. + shps_dgpu_powered_on(pdev);
  1911. + }
  1912. +}
  1913. +
  1914. +static int shps_start_sgcp_notification(struct platform_device *pdev, acpi_handle *sgpc_handle) {
  1915. + acpi_handle handle;
  1916. + int status;
  1917. +
  1918. + status = acpi_get_handle(NULL, "\\_SB.SGPC", &handle);
  1919. + if (status) {
  1920. + dev_err(&pdev->dev, "error in get_handle %d\n", status);
  1921. + return status;
  1922. + }
  1923. +
  1924. + status = acpi_install_notify_handler(handle, ACPI_DEVICE_NOTIFY, shps_sgcp_notify, pdev);
  1925. + if (status) {
  1926. + dev_err(&pdev->dev, "error in install notify %d\n", status);
  1927. + *sgpc_handle = NULL;
  1928. + return status;
  1929. + }
  1930. +
  1931. + *sgpc_handle = handle;
  1932. + return 0;
  1933. +}
  1934. +
  1935. +static void shps_remove_sgcp_notification(struct platform_device *pdev) {
  1936. + int status;
  1937. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1938. +
  1939. + if (drvdata->sgpc_handle) {
  1940. + status = acpi_remove_notify_handler(drvdata->sgpc_handle, ACPI_DEVICE_NOTIFY, shps_sgcp_notify);
  1941. + if (status) {
  1942. + dev_err(&pdev->dev, "failed to remove notify handler: %d\n", status);
  1943. + }
  1944. + }
  1945. +}
  1946. +
  1947. +static struct shps_hardware_traits shps_detect_hardware_traits(struct platform_device *pdev) {
  1948. + const struct shps_hardware_probe *p;
  1949. +
  1950. + for (p = shps_hardware_probe_match; p->hardware_id; ++p) {
  1951. + if (acpi_dev_present(p->hardware_id, NULL, -1)) {
  1952. + break;
  1953. + }
  1954. + }
  1955. +
  1956. + dev_info(&pdev->dev,
  1957. + "shps_detect_hardware_traits found device %s, generation %d\n",
  1958. + p->hardware_id ? p->hardware_id : "SAN (default)",
  1959. + p->generation);
  1960. +
  1961. + return *p->hardware_traits;
  1962. +}
  1963. +
  1964. +static int shps_probe(struct platform_device *pdev)
  1965. +{
  1966. + struct acpi_device *shps_dev = ACPI_COMPANION(&pdev->dev);
  1967. + struct shps_driver_data *drvdata;
  1968. + struct device_link *link;
  1969. + int power, status;
  1970. + struct shps_hardware_traits detected_traits;
  1971. +
  1972. + if (gpiod_count(&pdev->dev, NULL) < 0) {
  1973. + dev_err(&pdev->dev, "gpiod_count returned < 0\n");
  1974. + return -ENODEV;
  1975. + }
  1976. +
  1977. + // link to SSH
  1978. + status = surface_sam_ssh_consumer_register(&pdev->dev);
  1979. + if (status) {
  1980. + return status == -ENXIO ? -EPROBE_DEFER : status;
  1981. + }
  1982. +
  1983. + // detect what kind of hardware we're running
  1984. + detected_traits = shps_detect_hardware_traits(pdev);
  1985. +
  1986. + if (detected_traits.notification_method == SHPS_NOTIFICATION_METHOD_SAN) {
  1987. + // link to SAN
  1988. + status = surface_sam_san_consumer_register(&pdev->dev, 0);
  1989. + if (status) {
  1990. + dev_err(&pdev->dev, "failed to register with san consumer: %d\n", status);
  1991. + return status == -ENXIO ? -EPROBE_DEFER : status;
  1992. + }
  1993. + }
  1994. +
  1995. + status = acpi_dev_add_driver_gpios(shps_dev, shps_acpi_gpios);
  1996. + if (status) {
  1997. + dev_err(&pdev->dev, "failed to add gpios: %d\n", status);
  1998. + return status;
  1999. + }
  2000. +
  2001. + drvdata = kzalloc(sizeof(struct shps_driver_data), GFP_KERNEL);
  2002. + if (!drvdata) {
  2003. + status = -ENOMEM;
  2004. + goto err_drvdata;
  2005. + }
  2006. + mutex_init(&drvdata->lock);
  2007. + platform_set_drvdata(pdev, drvdata);
  2008. +
  2009. + drvdata->hardware_traits = detected_traits;
  2010. +
  2011. + drvdata->dgpu_root_port = shps_dgpu_dsm_get_pci_dev(pdev);
  2012. + if (IS_ERR(drvdata->dgpu_root_port)) {
  2013. + status = PTR_ERR(drvdata->dgpu_root_port);
  2014. + dev_err(&pdev->dev, "failed to get pci dev: %d\n", status);
  2015. + goto err_rp_lookup;
  2016. + }
  2017. +
  2018. + status = shps_gpios_setup(pdev);
  2019. + if (status) {
  2020. + dev_err(&pdev->dev, "unable to set up gpios, %d\n", status);
  2021. + goto err_gpio;
  2022. + }
  2023. +
  2024. + status = shps_gpios_setup_irq(pdev);
  2025. + if (status) {
  2026. + dev_err(&pdev->dev, "unable to set up irqs %d\n", status);
  2027. + goto err_gpio_irqs;
  2028. + }
  2029. +
  2030. + status = device_add_groups(&pdev->dev, shps_power_groups);
  2031. + if (status)
  2032. + goto err_devattr;
  2033. +
  2034. + link = device_link_add(&pdev->dev, &drvdata->dgpu_root_port->dev,
  2035. + DL_FLAG_PM_RUNTIME | DL_FLAG_AUTOREMOVE_CONSUMER);
  2036. + if (!link)
  2037. + goto err_devlink;
  2038. +
  2039. + if (detected_traits.notification_method == SHPS_NOTIFICATION_METHOD_SAN) {
  2040. + status = surface_sam_san_set_rqsg_handler(shps_dgpu_handle_rqsg, pdev);
  2041. + if (status) {
  2042. + dev_err(&pdev->dev, "unable to set SAN notification handler (%d)\n", status);
  2043. + goto err_devlink;
  2044. + }
  2045. + } else if (detected_traits.notification_method == SHPS_NOTIFICATION_METHOD_SGCP) {
  2046. + status = shps_start_sgcp_notification(pdev, &drvdata->sgpc_handle);
  2047. + if (status) {
  2048. + dev_err(&pdev->dev, "unable to install SGCP notification handler (%d)\n", status);
  2049. + goto err_devlink;
  2050. + }
  2051. + }
  2052. +
  2053. + // if dGPU is not present turn-off root-port, else obey module param
  2054. + status = shps_dgpu_is_present(pdev);
  2055. + if (status < 0)
  2056. + goto err_post_notification;
  2057. +
  2058. + power = status == 0 ? SHPS_DGPU_POWER_OFF : param_dgpu_power_init;
  2059. + if (power != SHPS_DGPU_MP_POWER_ASIS) {
  2060. + status = shps_dgpu_set_power(pdev, power);
  2061. + if (status)
  2062. + goto err_post_notification;
  2063. + }
  2064. +
  2065. + // initialize power target
  2066. + status = shps_dgpu_rp_get_power(pdev);
  2067. + if (status < 0)
  2068. + goto err_pwrtgt;
  2069. +
  2070. + if (status)
  2071. + set_bit(SHPS_STATE_BIT_PWRTGT, &drvdata->state);
  2072. + else
  2073. + clear_bit(SHPS_STATE_BIT_PWRTGT, &drvdata->state);
  2074. +
  2075. + device_init_wakeup(&pdev->dev, true);
  2076. + return 0;
  2077. +
  2078. +err_pwrtgt:
  2079. + if (param_dgpu_power_exit != SHPS_DGPU_MP_POWER_ASIS) {
  2080. + status = shps_dgpu_set_power(pdev, param_dgpu_power_exit);
  2081. + if (status)
  2082. + dev_err(&pdev->dev, "failed to set dGPU power state: %d\n", status);
  2083. + }
  2084. +err_post_notification:
  2085. + if (detected_traits.notification_method == SHPS_NOTIFICATION_METHOD_SGCP) {
  2086. + shps_remove_sgcp_notification(pdev);
  2087. + } else if (detected_traits.notification_method == SHPS_NOTIFICATION_METHOD_SAN) {
  2088. + surface_sam_san_set_rqsg_handler(NULL, NULL);
  2089. + }
  2090. +err_devlink:
  2091. + device_remove_groups(&pdev->dev, shps_power_groups);
  2092. +err_devattr:
  2093. + shps_gpios_remove_irq(pdev);
  2094. +err_gpio_irqs:
  2095. + shps_gpios_remove(pdev);
  2096. +err_gpio:
  2097. + pci_dev_put(drvdata->dgpu_root_port);
  2098. +err_rp_lookup:
  2099. + platform_set_drvdata(pdev, NULL);
  2100. + kfree(drvdata);
  2101. +err_drvdata:
  2102. + acpi_dev_remove_driver_gpios(shps_dev);
  2103. + return status;
  2104. +}
  2105. +
  2106. +static int shps_remove(struct platform_device *pdev)
  2107. +{
  2108. + struct acpi_device *shps_dev = ACPI_COMPANION(&pdev->dev);
  2109. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  2110. + int status;
  2111. +
  2112. + if (param_dgpu_power_exit != SHPS_DGPU_MP_POWER_ASIS) {
  2113. + status = shps_dgpu_set_power(pdev, param_dgpu_power_exit);
  2114. + if (status)
  2115. + dev_err(&pdev->dev, "failed to set dGPU power state: %d\n", status);
  2116. + }
  2117. +
  2118. + device_set_wakeup_capable(&pdev->dev, false);
  2119. +
  2120. + if (drvdata->hardware_traits.notification_method == SHPS_NOTIFICATION_METHOD_SGCP) {
  2121. + shps_remove_sgcp_notification(pdev);
  2122. + } else if (drvdata->hardware_traits.notification_method == SHPS_NOTIFICATION_METHOD_SAN) {
  2123. + surface_sam_san_set_rqsg_handler(NULL, NULL);
  2124. + }
  2125. + device_remove_groups(&pdev->dev, shps_power_groups);
  2126. + shps_gpios_remove_irq(pdev);
  2127. + shps_gpios_remove(pdev);
  2128. + pci_dev_put(drvdata->dgpu_root_port);
  2129. + platform_set_drvdata(pdev, NULL);
  2130. + kfree(drvdata);
  2131. +
  2132. + acpi_dev_remove_driver_gpios(shps_dev);
  2133. + return 0;
  2134. +}
  2135. +
  2136. +
  2137. +static const struct dev_pm_ops shps_pm_ops = {
  2138. + .prepare = shps_pm_prepare,
  2139. + .complete = shps_pm_complete,
  2140. + .suspend = shps_pm_suspend,
  2141. + .resume = shps_pm_resume,
  2142. +};
  2143. +
  2144. +static const struct acpi_device_id shps_acpi_match[] = {
  2145. + { "MSHW0153", 0 },
  2146. + { },
  2147. +};
  2148. +MODULE_DEVICE_TABLE(acpi, shps_acpi_match);
  2149. +
  2150. +static struct platform_driver surface_sam_hps = {
  2151. + .probe = shps_probe,
  2152. + .remove = shps_remove,
  2153. + .shutdown = shps_shutdown,
  2154. + .driver = {
  2155. + .name = "surface_dgpu_hps",
  2156. + .acpi_match_table = shps_acpi_match,
  2157. + .pm = &shps_pm_ops,
  2158. + },
  2159. +};
  2160. +
  2161. +module_platform_driver(surface_sam_hps);
  2162. +
  2163. +MODULE_AUTHOR("Maximilian Luz <luzmaximilian@gmail.com>");
  2164. +MODULE_DESCRIPTION("Surface Hot-Plug System (HPS) and dGPU power-state Driver for Surface Book 2");
  2165. +MODULE_LICENSE("GPL");
  2166. diff --git a/drivers/platform/x86/surface_sam/surface_sam_san.c b/drivers/platform/x86/surface_sam/surface_sam_san.c
  2167. new file mode 100644
  2168. index 000000000000..11dd6daedc3d
  2169. --- /dev/null
  2170. +++ b/drivers/platform/x86/surface_sam/surface_sam_san.c
  2171. @@ -0,0 +1,913 @@
  2172. +// SPDX-License-Identifier: GPL-2.0-or-later
  2173. +/*
  2174. + * Surface ACPI Notify (SAN) and ACPI integration driver for SAM.
  2175. + * Translates communication from ACPI to SSH and back.
  2176. + */
  2177. +
  2178. +#include <linux/acpi.h>
  2179. +#include <linux/delay.h>
  2180. +#include <linux/jiffies.h>
  2181. +#include <linux/kernel.h>
  2182. +#include <linux/platform_device.h>
  2183. +
  2184. +#include "surface_sam_ssh.h"
  2185. +#include "surface_sam_san.h"
  2186. +
  2187. +
  2188. +#define SAN_RQST_RETRY 5
  2189. +
  2190. +#define SAN_DSM_REVISION 0
  2191. +#define SAN_DSM_FN_NOTIFY_SENSOR_TRIP_POINT 0x09
  2192. +
  2193. +static const guid_t SAN_DSM_UUID =
  2194. + GUID_INIT(0x93b666c5, 0x70c6, 0x469f, 0xa2, 0x15, 0x3d,
  2195. + 0x48, 0x7c, 0x91, 0xab, 0x3c);
  2196. +
  2197. +#define SAM_EVENT_DELAY_PWR_ADAPTER msecs_to_jiffies(5000)
  2198. +#define SAM_EVENT_DELAY_PWR_BST msecs_to_jiffies(2500)
  2199. +
  2200. +#define SAM_EVENT_PWR_CID_BIX 0x15
  2201. +#define SAM_EVENT_PWR_CID_BST 0x16
  2202. +#define SAM_EVENT_PWR_CID_ADAPTER 0x17
  2203. +#define SAM_EVENT_PWR_CID_DPTF 0x4f
  2204. +
  2205. +#define SAM_EVENT_TEMP_CID_NOTIFY_SENSOR_TRIP_POINT 0x0b
  2206. +
  2207. +#define SAN_RQST_TAG "surface_sam_san: rqst: "
  2208. +#define SAN_RQSG_TAG "surface_sam_san: rqsg: "
  2209. +
  2210. +#define SAN_QUIRK_BASE_STATE_DELAY 1000
  2211. +
  2212. +
  2213. +struct san_acpi_consumer {
  2214. + char *path;
  2215. + bool required;
  2216. + u32 flags;
  2217. +};
  2218. +
  2219. +struct san_opreg_context {
  2220. + struct acpi_connection_info connection;
  2221. + struct device *dev;
  2222. +};
  2223. +
  2224. +struct san_consumer_link {
  2225. + const struct san_acpi_consumer *properties;
  2226. + struct device_link *link;
  2227. +};
  2228. +
  2229. +struct san_consumers {
  2230. + u32 num;
  2231. + struct san_consumer_link *links;
  2232. +};
  2233. +
  2234. +struct san_drvdata {
  2235. + struct san_opreg_context opreg_ctx;
  2236. + struct san_consumers consumers;
  2237. +
  2238. + struct platform_device *dev;
  2239. + struct ssam_event_notifier nf_bat;
  2240. + struct ssam_event_notifier nf_tmp;
  2241. +};
  2242. +
  2243. +struct san_event_work {
  2244. + struct delayed_work work;
  2245. + struct platform_device *dev;
  2246. + struct ssam_event event; // must be last
  2247. +};
  2248. +
  2249. +struct gsb_data_in {
  2250. + u8 cv;
  2251. +} __packed;
  2252. +
  2253. +struct gsb_data_rqsx {
  2254. + u8 cv; // command value (should be 0x01 or 0x03)
  2255. + u8 tc; // target controller
  2256. + u8 tid; // transport channnel ID?
  2257. + u8 iid; // target sub-controller (e.g. primary vs. secondary battery)
  2258. + u8 snc; // expect-response-flag
  2259. + u8 cid; // command ID
  2260. + u8 cdl; // payload length
  2261. + u8 _pad; // padding
  2262. + u8 pld[0]; // payload
  2263. +} __packed;
  2264. +
  2265. +struct gsb_data_etwl {
  2266. + u8 cv; // command value (should be 0x02)
  2267. + u8 etw3; // ?
  2268. + u8 etw4; // ?
  2269. + u8 msg[0]; // error message (ASCIIZ)
  2270. +} __packed;
  2271. +
  2272. +struct gsb_data_out {
  2273. + u8 status; // _SSH communication status
  2274. + u8 len; // _SSH payload length
  2275. + u8 pld[0]; // _SSH payload
  2276. +} __packed;
  2277. +
  2278. +union gsb_buffer_data {
  2279. + struct gsb_data_in in; // common input
  2280. + struct gsb_data_rqsx rqsx; // RQSX input
  2281. + struct gsb_data_etwl etwl; // ETWL input
  2282. + struct gsb_data_out out; // output
  2283. +};
  2284. +
  2285. +struct gsb_buffer {
  2286. + u8 status; // GSB AttribRawProcess status
  2287. + u8 len; // GSB AttribRawProcess length
  2288. + union gsb_buffer_data data;
  2289. +} __packed;
  2290. +
  2291. +
  2292. +enum san_pwr_event {
  2293. + SAN_PWR_EVENT_BAT1_STAT = 0x03,
  2294. + SAN_PWR_EVENT_BAT1_INFO = 0x04,
  2295. + SAN_PWR_EVENT_ADP1_STAT = 0x05,
  2296. + SAN_PWR_EVENT_ADP1_INFO = 0x06,
  2297. + SAN_PWR_EVENT_BAT2_STAT = 0x07,
  2298. + SAN_PWR_EVENT_BAT2_INFO = 0x08,
  2299. + SAN_PWR_EVENT_DPTF = 0x0A,
  2300. +};
  2301. +
  2302. +
  2303. +static int sam_san_default_rqsg_handler(struct surface_sam_san_rqsg *rqsg, void *data);
  2304. +
  2305. +struct sam_san_rqsg_if {
  2306. + struct mutex lock;
  2307. + struct device *san_dev;
  2308. + surface_sam_san_rqsg_handler_fn handler;
  2309. + void *handler_data;
  2310. +};
  2311. +
  2312. +static struct sam_san_rqsg_if rqsg_if = {
  2313. + .lock = __MUTEX_INITIALIZER(rqsg_if.lock),
  2314. + .san_dev = NULL,
  2315. + .handler = sam_san_default_rqsg_handler,
  2316. + .handler_data = NULL,
  2317. +};
  2318. +
  2319. +int surface_sam_san_consumer_register(struct device *consumer, u32 flags)
  2320. +{
  2321. + const u32 valid = DL_FLAG_PM_RUNTIME | DL_FLAG_RPM_ACTIVE;
  2322. + int status;
  2323. +
  2324. + if ((flags | valid) != valid)
  2325. + return -EINVAL;
  2326. +
  2327. + flags |= DL_FLAG_AUTOREMOVE_CONSUMER;
  2328. +
  2329. + mutex_lock(&rqsg_if.lock);
  2330. + if (rqsg_if.san_dev)
  2331. + status = device_link_add(consumer, rqsg_if.san_dev, flags) ? 0 : -EINVAL;
  2332. + else
  2333. + status = -ENXIO;
  2334. + mutex_unlock(&rqsg_if.lock);
  2335. + return status;
  2336. +}
  2337. +EXPORT_SYMBOL_GPL(surface_sam_san_consumer_register);
  2338. +
  2339. +int surface_sam_san_set_rqsg_handler(surface_sam_san_rqsg_handler_fn fn, void *data)
  2340. +{
  2341. + int status = -EBUSY;
  2342. +
  2343. + mutex_lock(&rqsg_if.lock);
  2344. +
  2345. + if (rqsg_if.handler == sam_san_default_rqsg_handler || !fn) {
  2346. + rqsg_if.handler = fn ? fn : sam_san_default_rqsg_handler;
  2347. + rqsg_if.handler_data = data;
  2348. + status = 0;
  2349. + }
  2350. +
  2351. + mutex_unlock(&rqsg_if.lock);
  2352. + return status;
  2353. +}
  2354. +EXPORT_SYMBOL_GPL(surface_sam_san_set_rqsg_handler);
  2355. +
  2356. +int san_call_rqsg_handler(struct surface_sam_san_rqsg *rqsg)
  2357. +{
  2358. + int status;
  2359. +
  2360. + mutex_lock(&rqsg_if.lock);
  2361. + status = rqsg_if.handler(rqsg, rqsg_if.handler_data);
  2362. + mutex_unlock(&rqsg_if.lock);
  2363. +
  2364. + return status;
  2365. +}
  2366. +
  2367. +static int sam_san_default_rqsg_handler(struct surface_sam_san_rqsg *rqsg, void *data)
  2368. +{
  2369. + pr_warn(SAN_RQSG_TAG "unhandled request: RQSG(0x%02x, 0x%02x, 0x%02x)\n",
  2370. + rqsg->tc, rqsg->cid, rqsg->iid);
  2371. +
  2372. + return 0;
  2373. +}
  2374. +
  2375. +
  2376. +static bool san_acpi_can_notify(struct device *dev, u64 func)
  2377. +{
  2378. + acpi_handle san = ACPI_HANDLE(dev);
  2379. + return acpi_check_dsm(san, &SAN_DSM_UUID, SAN_DSM_REVISION, 1 << func);
  2380. +}
  2381. +
  2382. +static int san_acpi_notify_power_event(struct device *dev, enum san_pwr_event event)
  2383. +{
  2384. + acpi_handle san = ACPI_HANDLE(dev);
  2385. + union acpi_object *obj;
  2386. +
  2387. + if (!san_acpi_can_notify(dev, event))
  2388. + return 0;
  2389. +
  2390. + dev_dbg(dev, "notify power event 0x%02x\n", event);
  2391. + obj = acpi_evaluate_dsm_typed(san, &SAN_DSM_UUID, SAN_DSM_REVISION,
  2392. + event, NULL, ACPI_TYPE_BUFFER);
  2393. +
  2394. + if (IS_ERR_OR_NULL(obj))
  2395. + return obj ? PTR_ERR(obj) : -ENXIO;
  2396. +
  2397. + if (obj->buffer.length != 1 || obj->buffer.pointer[0] != 0) {
  2398. + dev_err(dev, "got unexpected result from _DSM\n");
  2399. + return -EFAULT;
  2400. + }
  2401. +
  2402. + ACPI_FREE(obj);
  2403. + return 0;
  2404. +}
  2405. +
  2406. +static int san_acpi_notify_sensor_trip_point(struct device *dev, u8 iid)
  2407. +{
  2408. + acpi_handle san = ACPI_HANDLE(dev);
  2409. + union acpi_object *obj;
  2410. + union acpi_object param;
  2411. +
  2412. + if (!san_acpi_can_notify(dev, SAN_DSM_FN_NOTIFY_SENSOR_TRIP_POINT))
  2413. + return 0;
  2414. +
  2415. + param.type = ACPI_TYPE_INTEGER;
  2416. + param.integer.value = iid;
  2417. +
  2418. + obj = acpi_evaluate_dsm_typed(san, &SAN_DSM_UUID, SAN_DSM_REVISION,
  2419. + SAN_DSM_FN_NOTIFY_SENSOR_TRIP_POINT,
  2420. + &param, ACPI_TYPE_BUFFER);
  2421. +
  2422. + if (IS_ERR_OR_NULL(obj))
  2423. + return obj ? PTR_ERR(obj) : -ENXIO;
  2424. +
  2425. + if (obj->buffer.length != 1 || obj->buffer.pointer[0] != 0) {
  2426. + dev_err(dev, "got unexpected result from _DSM\n");
  2427. + return -EFAULT;
  2428. + }
  2429. +
  2430. + ACPI_FREE(obj);
  2431. + return 0;
  2432. +}
  2433. +
  2434. +
  2435. +static inline int san_evt_power_adapter(struct device *dev, const struct ssam_event *event)
  2436. +{
  2437. + int status;
  2438. +
  2439. + status = san_acpi_notify_power_event(dev, SAN_PWR_EVENT_ADP1_STAT);
  2440. + if (status)
  2441. + return status;
  2442. +
  2443. + /*
  2444. + * Enusre that the battery states get updated correctly.
  2445. + * When the battery is fully charged and an adapter is plugged in, it
  2446. + * sometimes is not updated correctly, instead showing it as charging.
  2447. + * Explicitly trigger battery updates to fix this.
  2448. + */
  2449. +
  2450. + status = san_acpi_notify_power_event(dev, SAN_PWR_EVENT_BAT1_STAT);
  2451. + if (status)
  2452. + return status;
  2453. +
  2454. + return san_acpi_notify_power_event(dev, SAN_PWR_EVENT_BAT2_STAT);
  2455. +}
  2456. +
  2457. +static inline int san_evt_power_bix(struct device *dev, const struct ssam_event *event)
  2458. +{
  2459. + enum san_pwr_event evcode;
  2460. +
  2461. + if (event->instance_id == 0x02)
  2462. + evcode = SAN_PWR_EVENT_BAT2_INFO;
  2463. + else
  2464. + evcode = SAN_PWR_EVENT_BAT1_INFO;
  2465. +
  2466. + return san_acpi_notify_power_event(dev, evcode);
  2467. +}
  2468. +
  2469. +static inline int san_evt_power_bst(struct device *dev, const struct ssam_event *event)
  2470. +{
  2471. + enum san_pwr_event evcode;
  2472. +
  2473. + if (event->instance_id == 0x02)
  2474. + evcode = SAN_PWR_EVENT_BAT2_STAT;
  2475. + else
  2476. + evcode = SAN_PWR_EVENT_BAT1_STAT;
  2477. +
  2478. + return san_acpi_notify_power_event(dev, evcode);
  2479. +}
  2480. +
  2481. +static inline int san_evt_power_dptf(struct device *dev, const struct ssam_event *event)
  2482. +{
  2483. + union acpi_object payload;
  2484. + acpi_handle san = ACPI_HANDLE(dev);
  2485. + union acpi_object *obj;
  2486. +
  2487. + if (!san_acpi_can_notify(dev, SAN_PWR_EVENT_DPTF))
  2488. + return 0;
  2489. +
  2490. + /*
  2491. + * The Surface ACPI expects a buffer and not a package. It specifically
  2492. + * checks for ObjectType (Arg3) == 0x03. This will cause a warning in
  2493. + * acpica/nsarguments.c, but this can safely be ignored.
  2494. + */
  2495. + payload.type = ACPI_TYPE_BUFFER;
  2496. + payload.buffer.length = event->length;
  2497. + payload.buffer.pointer = (u8 *)&event->data[0];
  2498. +
  2499. + dev_dbg(dev, "notify power event 0x%02x\n", event->command_id);
  2500. + obj = acpi_evaluate_dsm_typed(san, &SAN_DSM_UUID, SAN_DSM_REVISION,
  2501. + SAN_PWR_EVENT_DPTF, &payload,
  2502. + ACPI_TYPE_BUFFER);
  2503. +
  2504. + if (IS_ERR_OR_NULL(obj))
  2505. + return obj ? PTR_ERR(obj) : -ENXIO;
  2506. +
  2507. + if (obj->buffer.length != 1 || obj->buffer.pointer[0] != 0) {
  2508. + dev_err(dev, "got unexpected result from _DSM\n");
  2509. + return -EFAULT;
  2510. + }
  2511. +
  2512. + ACPI_FREE(obj);
  2513. + return 0;
  2514. +}
  2515. +
  2516. +static unsigned long san_evt_power_delay(u8 cid)
  2517. +{
  2518. + switch (cid) {
  2519. + case SAM_EVENT_PWR_CID_ADAPTER:
  2520. + /*
  2521. + * Wait for battery state to update before signalling adapter change.
  2522. + */
  2523. + return SAM_EVENT_DELAY_PWR_ADAPTER;
  2524. +
  2525. + case SAM_EVENT_PWR_CID_BST:
  2526. + /*
  2527. + * Ensure we do not miss anything important due to caching.
  2528. + */
  2529. + return SAM_EVENT_DELAY_PWR_BST;
  2530. +
  2531. + case SAM_EVENT_PWR_CID_BIX:
  2532. + case SAM_EVENT_PWR_CID_DPTF:
  2533. + default:
  2534. + return 0;
  2535. + }
  2536. +}
  2537. +
  2538. +static bool san_evt_power(const struct ssam_event *event, struct device *dev)
  2539. +{
  2540. + int status;
  2541. +
  2542. + switch (event->command_id) {
  2543. + case SAM_EVENT_PWR_CID_BIX:
  2544. + status = san_evt_power_bix(dev, event);
  2545. + break;
  2546. +
  2547. + case SAM_EVENT_PWR_CID_BST:
  2548. + status = san_evt_power_bst(dev, event);
  2549. + break;
  2550. +
  2551. + case SAM_EVENT_PWR_CID_ADAPTER:
  2552. + status = san_evt_power_adapter(dev, event);
  2553. + break;
  2554. +
  2555. + case SAM_EVENT_PWR_CID_DPTF:
  2556. + status = san_evt_power_dptf(dev, event);
  2557. + break;
  2558. +
  2559. + default:
  2560. + return false;
  2561. + }
  2562. +
  2563. + if (status)
  2564. + dev_err(dev, "error handling power event (cid = %x)\n",
  2565. + event->command_id);
  2566. +
  2567. + return true;
  2568. +}
  2569. +
  2570. +static void san_evt_power_workfn(struct work_struct *work)
  2571. +{
  2572. + struct san_event_work *ev = container_of(work, struct san_event_work, work.work);
  2573. +
  2574. + san_evt_power(&ev->event, &ev->dev->dev);
  2575. + kfree(ev);
  2576. +}
  2577. +
  2578. +
  2579. +static u32 san_evt_power_nb(struct ssam_notifier_block *nb, const struct ssam_event *event)
  2580. +{
  2581. + struct san_drvdata *drvdata = container_of(nb, struct san_drvdata, nf_bat.base);
  2582. + struct san_event_work *work;
  2583. + unsigned long delay = san_evt_power_delay(event->command_id);
  2584. +
  2585. + if (delay == 0) {
  2586. + if (san_evt_power(event, &drvdata->dev->dev))
  2587. + return SSAM_NOTIF_HANDLED;
  2588. + else
  2589. + return 0;
  2590. + }
  2591. +
  2592. + work = kzalloc(sizeof(struct san_event_work) + event->length, GFP_KERNEL);
  2593. + if (!work)
  2594. + return ssam_notifier_from_errno(-ENOMEM);
  2595. +
  2596. + INIT_DELAYED_WORK(&work->work, san_evt_power_workfn);
  2597. + work->dev = drvdata->dev;
  2598. +
  2599. + memcpy(&work->event, event, sizeof(struct ssam_event) + event->length);
  2600. +
  2601. + schedule_delayed_work(&work->work, delay);
  2602. + return SSAM_NOTIF_HANDLED;
  2603. +}
  2604. +
  2605. +
  2606. +static inline int san_evt_thermal_notify(struct device *dev, const struct ssam_event *event)
  2607. +{
  2608. + return san_acpi_notify_sensor_trip_point(dev, event->instance_id);
  2609. +}
  2610. +
  2611. +static bool san_evt_thermal(const struct ssam_event *event, struct device *dev)
  2612. +{
  2613. + int status;
  2614. +
  2615. + switch (event->command_id) {
  2616. + case SAM_EVENT_TEMP_CID_NOTIFY_SENSOR_TRIP_POINT:
  2617. + status = san_evt_thermal_notify(dev, event);
  2618. + break;
  2619. +
  2620. + default:
  2621. + return false;
  2622. + }
  2623. +
  2624. + if (status) {
  2625. + dev_err(dev, "error handling thermal event (cid = %x)\n",
  2626. + event->command_id);
  2627. + }
  2628. +
  2629. + return true;
  2630. +}
  2631. +
  2632. +static u32 san_evt_thermal_nb(struct ssam_notifier_block *nb, const struct ssam_event *event)
  2633. +{
  2634. + struct san_drvdata *drvdata = container_of(nb, struct san_drvdata, nf_tmp.base);
  2635. + struct platform_device *pdev = drvdata->dev;
  2636. +
  2637. + if (san_evt_thermal(event, &pdev->dev))
  2638. + return SSAM_NOTIF_HANDLED;
  2639. + else
  2640. + return 0;
  2641. +}
  2642. +
  2643. +
  2644. +static struct gsb_data_rqsx
  2645. +*san_validate_rqsx(struct device *dev, const char *type, struct gsb_buffer *buffer)
  2646. +{
  2647. + struct gsb_data_rqsx *rqsx = &buffer->data.rqsx;
  2648. +
  2649. + if (buffer->len < 8) {
  2650. + dev_err(dev, "invalid %s package (len = %d)\n",
  2651. + type, buffer->len);
  2652. + return NULL;
  2653. + }
  2654. +
  2655. + if (rqsx->cdl != buffer->len - 8) {
  2656. + dev_err(dev, "bogus %s package (len = %d, cdl = %d)\n",
  2657. + type, buffer->len, rqsx->cdl);
  2658. + return NULL;
  2659. + }
  2660. +
  2661. + if (rqsx->tid != 0x01) {
  2662. + dev_warn(dev, "unsupported %s package (tid = 0x%02x)\n",
  2663. + type, rqsx->tid);
  2664. + return NULL;
  2665. + }
  2666. +
  2667. + return rqsx;
  2668. +}
  2669. +
  2670. +static acpi_status
  2671. +san_etwl(struct san_opreg_context *ctx, struct gsb_buffer *buffer)
  2672. +{
  2673. + struct gsb_data_etwl *etwl = &buffer->data.etwl;
  2674. +
  2675. + if (buffer->len < 3) {
  2676. + dev_err(ctx->dev, "invalid ETWL package (len = %d)\n", buffer->len);
  2677. + return AE_OK;
  2678. + }
  2679. +
  2680. + dev_err(ctx->dev, "ETWL(0x%02x, 0x%02x): %.*s\n",
  2681. + etwl->etw3, etwl->etw4,
  2682. + buffer->len - 3, (char *)etwl->msg);
  2683. +
  2684. + // indicate success
  2685. + buffer->status = 0x00;
  2686. + buffer->len = 0x00;
  2687. +
  2688. + return AE_OK;
  2689. +}
  2690. +
  2691. +static acpi_status
  2692. +san_rqst(struct san_opreg_context *ctx, struct gsb_buffer *buffer)
  2693. +{
  2694. + struct gsb_data_rqsx *gsb_rqst = san_validate_rqsx(ctx->dev, "RQST", buffer);
  2695. + struct surface_sam_ssh_rqst rqst = {};
  2696. + struct surface_sam_ssh_buf result = {};
  2697. + int status = 0;
  2698. + int try;
  2699. +
  2700. + if (!gsb_rqst)
  2701. + return AE_OK;
  2702. +
  2703. + rqst.tc = gsb_rqst->tc;
  2704. + rqst.cid = gsb_rqst->cid;
  2705. + rqst.iid = gsb_rqst->iid;
  2706. + rqst.chn = gsb_rqst->tid;
  2707. + rqst.snc = gsb_rqst->snc;
  2708. + rqst.cdl = gsb_rqst->cdl;
  2709. + rqst.pld = &gsb_rqst->pld[0];
  2710. +
  2711. + result.cap = SURFACE_SAM_SSH_MAX_RQST_RESPONSE;
  2712. + result.len = 0;
  2713. + result.data = kzalloc(result.cap, GFP_KERNEL);
  2714. +
  2715. + if (!result.data)
  2716. + return AE_NO_MEMORY;
  2717. +
  2718. + for (try = 0; try < SAN_RQST_RETRY; try++) {
  2719. + if (try)
  2720. + dev_warn(ctx->dev, SAN_RQST_TAG "IO error occurred, trying again\n");
  2721. +
  2722. + status = surface_sam_ssh_rqst(&rqst, &result);
  2723. + if (status != -EIO)
  2724. + break;
  2725. + }
  2726. +
  2727. + if (rqst.tc == 0x11 && rqst.cid == 0x0D && status == -EPERM) {
  2728. + /* Base state quirk:
  2729. + * The base state may be queried from ACPI when the EC is still
  2730. + * suspended. In this case it will return '-EPERM'. This query
  2731. + * will only be triggered from the ACPI lid GPE interrupt, thus
  2732. + * we are either in laptop or studio mode (base status 0x01 or
  2733. + * 0x02). Furthermore, we will only get here if the device (and
  2734. + * EC) have been suspended.
  2735. + *
  2736. + * We now assume that the device is in laptop mode (0x01). This
  2737. + * has the drawback that it will wake the device when unfolding
  2738. + * it in studio mode, but it also allows us to avoid actively
  2739. + * waiting for the EC to wake up, which may incur a notable
  2740. + * delay.
  2741. + */
  2742. +
  2743. + buffer->status = 0x00;
  2744. + buffer->len = 0x03;
  2745. + buffer->data.out.status = 0x00;
  2746. + buffer->data.out.len = 0x01;
  2747. + buffer->data.out.pld[0] = 0x01;
  2748. +
  2749. + } else if (!status) { // success
  2750. + buffer->status = 0x00;
  2751. + buffer->len = result.len + 2;
  2752. + buffer->data.out.status = 0x00;
  2753. + buffer->data.out.len = result.len;
  2754. + memcpy(&buffer->data.out.pld[0], result.data, result.len);
  2755. +
  2756. + } else { // failure
  2757. + dev_err(ctx->dev, SAN_RQST_TAG "failed with error %d\n", status);
  2758. + buffer->status = 0x00;
  2759. + buffer->len = 0x02;
  2760. + buffer->data.out.status = 0x01; // indicate _SSH error
  2761. + buffer->data.out.len = 0x00;
  2762. + }
  2763. +
  2764. + kfree(result.data);
  2765. +
  2766. + return AE_OK;
  2767. +}
  2768. +
  2769. +static acpi_status
  2770. +san_rqsg(struct san_opreg_context *ctx, struct gsb_buffer *buffer)
  2771. +{
  2772. + struct gsb_data_rqsx *gsb_rqsg = san_validate_rqsx(ctx->dev, "RQSG", buffer);
  2773. + struct surface_sam_san_rqsg rqsg = {};
  2774. + int status;
  2775. +
  2776. + if (!gsb_rqsg)
  2777. + return AE_OK;
  2778. +
  2779. + rqsg.tc = gsb_rqsg->tc;
  2780. + rqsg.cid = gsb_rqsg->cid;
  2781. + rqsg.iid = gsb_rqsg->iid;
  2782. + rqsg.cdl = gsb_rqsg->cdl;
  2783. + rqsg.pld = &gsb_rqsg->pld[0];
  2784. +
  2785. + status = san_call_rqsg_handler(&rqsg);
  2786. + if (!status) {
  2787. + buffer->status = 0x00;
  2788. + buffer->len = 0x02;
  2789. + buffer->data.out.status = 0x00;
  2790. + buffer->data.out.len = 0x00;
  2791. + } else {
  2792. + dev_err(ctx->dev, SAN_RQSG_TAG "failed with error %d\n", status);
  2793. + buffer->status = 0x00;
  2794. + buffer->len = 0x02;
  2795. + buffer->data.out.status = 0x01; // indicate _SSH error
  2796. + buffer->data.out.len = 0x00;
  2797. + }
  2798. +
  2799. + return AE_OK;
  2800. +}
  2801. +
  2802. +
  2803. +static acpi_status
  2804. +san_opreg_handler(u32 function, acpi_physical_address command,
  2805. + u32 bits, u64 *value64,
  2806. + void *opreg_context, void *region_context)
  2807. +{
  2808. + struct san_opreg_context *context = opreg_context;
  2809. + struct gsb_buffer *buffer = (struct gsb_buffer *)value64;
  2810. + int accessor_type = (0xFFFF0000 & function) >> 16;
  2811. +
  2812. + if (command != 0) {
  2813. + dev_warn(context->dev, "unsupported command: 0x%02llx\n", command);
  2814. + return AE_OK;
  2815. + }
  2816. +
  2817. + if (accessor_type != ACPI_GSB_ACCESS_ATTRIB_RAW_PROCESS) {
  2818. + dev_err(context->dev, "invalid access type: 0x%02x\n", accessor_type);
  2819. + return AE_OK;
  2820. + }
  2821. +
  2822. + // buffer must have at least contain the command-value
  2823. + if (buffer->len == 0) {
  2824. + dev_err(context->dev, "request-package too small\n");
  2825. + return AE_OK;
  2826. + }
  2827. +
  2828. + switch (buffer->data.in.cv) {
  2829. + case 0x01: return san_rqst(context, buffer);
  2830. + case 0x02: return san_etwl(context, buffer);
  2831. + case 0x03: return san_rqsg(context, buffer);
  2832. + }
  2833. +
  2834. + dev_warn(context->dev, "unsupported SAN0 request (cv: 0x%02x)\n", buffer->data.in.cv);
  2835. + return AE_OK;
  2836. +}
  2837. +
  2838. +static int san_events_register(struct platform_device *pdev)
  2839. +{
  2840. + struct san_drvdata *drvdata = platform_get_drvdata(pdev);
  2841. + int status;
  2842. +
  2843. + drvdata->nf_bat.base.priority = 1;
  2844. + drvdata->nf_bat.base.fn = san_evt_power_nb;
  2845. + drvdata->nf_bat.event.reg = SSAM_EVENT_REGISTRY_SAM;
  2846. + drvdata->nf_bat.event.id.target_category = SSAM_SSH_TC_BAT;
  2847. + drvdata->nf_bat.event.id.instance = 0;
  2848. + drvdata->nf_bat.event.flags = SSAM_EVENT_SEQUENCED;
  2849. +
  2850. + drvdata->nf_tmp.base.priority = 1;
  2851. + drvdata->nf_tmp.base.fn = san_evt_thermal_nb;
  2852. + drvdata->nf_tmp.event.reg = SSAM_EVENT_REGISTRY_SAM;
  2853. + drvdata->nf_tmp.event.id.target_category = SSAM_SSH_TC_TMP;
  2854. + drvdata->nf_tmp.event.id.instance = 0;
  2855. + drvdata->nf_tmp.event.flags = SSAM_EVENT_SEQUENCED;
  2856. +
  2857. + status = surface_sam_ssh_notifier_register(&drvdata->nf_bat);
  2858. + if (status)
  2859. + return status;
  2860. +
  2861. + status = surface_sam_ssh_notifier_register(&drvdata->nf_tmp);
  2862. + if (status)
  2863. + surface_sam_ssh_notifier_unregister(&drvdata->nf_bat);
  2864. +
  2865. + return status;
  2866. +}
  2867. +
  2868. +static void san_events_unregister(struct platform_device *pdev)
  2869. +{
  2870. + struct san_drvdata *drvdata = platform_get_drvdata(pdev);
  2871. +
  2872. + surface_sam_ssh_notifier_unregister(&drvdata->nf_bat);
  2873. + surface_sam_ssh_notifier_unregister(&drvdata->nf_tmp);
  2874. +}
  2875. +
  2876. +
  2877. +static int san_consumers_link(struct platform_device *pdev,
  2878. + const struct san_acpi_consumer *cons,
  2879. + struct san_consumers *out)
  2880. +{
  2881. + const struct san_acpi_consumer *con;
  2882. + struct san_consumer_link *links, *link;
  2883. + struct acpi_device *adev;
  2884. + acpi_handle handle;
  2885. + u32 max_links = 0;
  2886. + int status;
  2887. +
  2888. + if (!cons)
  2889. + return 0;
  2890. +
  2891. + // count links
  2892. + for (con = cons; con->path; ++con)
  2893. + max_links += 1;
  2894. +
  2895. + // allocate
  2896. + links = kcalloc(max_links, sizeof(struct san_consumer_link), GFP_KERNEL);
  2897. + link = &links[0];
  2898. +
  2899. + if (!links)
  2900. + return -ENOMEM;
  2901. +
  2902. + // create links
  2903. + for (con = cons; con->path; ++con) {
  2904. + status = acpi_get_handle(NULL, con->path, &handle);
  2905. + if (status) {
  2906. + if (con->required || status != AE_NOT_FOUND) {
  2907. + status = -ENXIO;
  2908. + goto cleanup;
  2909. + } else {
  2910. + continue;
  2911. + }
  2912. + }
  2913. +
  2914. + status = acpi_bus_get_device(handle, &adev);
  2915. + if (status)
  2916. + goto cleanup;
  2917. +
  2918. + link->link = device_link_add(&adev->dev, &pdev->dev, con->flags);
  2919. + if (!(link->link)) {
  2920. + status = -EFAULT;
  2921. + goto cleanup;
  2922. + }
  2923. + link->properties = con;
  2924. +
  2925. + link += 1;
  2926. + }
  2927. +
  2928. + out->num = link - links;
  2929. + out->links = links;
  2930. +
  2931. + return 0;
  2932. +
  2933. +cleanup:
  2934. + for (link = link - 1; link >= links; --link) {
  2935. + if (link->properties->flags & DL_FLAG_STATELESS)
  2936. + device_link_del(link->link);
  2937. + }
  2938. +
  2939. + return status;
  2940. +}
  2941. +
  2942. +static void san_consumers_unlink(struct san_consumers *consumers)
  2943. +{
  2944. + u32 i;
  2945. +
  2946. + if (!consumers)
  2947. + return;
  2948. +
  2949. + for (i = 0; i < consumers->num; ++i) {
  2950. + if (consumers->links[i].properties->flags & DL_FLAG_STATELESS)
  2951. + device_link_del(consumers->links[i].link);
  2952. + }
  2953. +
  2954. + kfree(consumers->links);
  2955. +
  2956. + consumers->num = 0;
  2957. + consumers->links = NULL;
  2958. +}
  2959. +
  2960. +static int surface_sam_san_probe(struct platform_device *pdev)
  2961. +{
  2962. + const struct san_acpi_consumer *cons;
  2963. + struct san_drvdata *drvdata;
  2964. + acpi_handle san = ACPI_HANDLE(&pdev->dev); // _SAN device node
  2965. + int status;
  2966. +
  2967. + /*
  2968. + * Defer probe if the _SSH driver has not set up the controller yet. This
  2969. + * makes sure we do not fail any initial requests (e.g. _STA request without
  2970. + * which the battery does not get set up correctly). Otherwise register as
  2971. + * consumer to set up a device_link.
  2972. + */
  2973. + status = surface_sam_ssh_consumer_register(&pdev->dev);
  2974. + if (status)
  2975. + return status == -ENXIO ? -EPROBE_DEFER : status;
  2976. +
  2977. + drvdata = kzalloc(sizeof(struct san_drvdata), GFP_KERNEL);
  2978. + if (!drvdata)
  2979. + return -ENOMEM;
  2980. +
  2981. + drvdata->dev = pdev;
  2982. + drvdata->opreg_ctx.dev = &pdev->dev;
  2983. +
  2984. + cons = acpi_device_get_match_data(&pdev->dev);
  2985. + status = san_consumers_link(pdev, cons, &drvdata->consumers);
  2986. + if (status)
  2987. + goto err_consumers;
  2988. +
  2989. + platform_set_drvdata(pdev, drvdata);
  2990. +
  2991. + status = acpi_install_address_space_handler(san,
  2992. + ACPI_ADR_SPACE_GSBUS,
  2993. + &san_opreg_handler,
  2994. + NULL, &drvdata->opreg_ctx);
  2995. +
  2996. + if (ACPI_FAILURE(status)) {
  2997. + status = -ENODEV;
  2998. + goto err_install_handler;
  2999. + }
  3000. +
  3001. + status = san_events_register(pdev);
  3002. + if (status)
  3003. + goto err_enable_events;
  3004. +
  3005. + mutex_lock(&rqsg_if.lock);
  3006. + if (!rqsg_if.san_dev)
  3007. + rqsg_if.san_dev = &pdev->dev;
  3008. + else
  3009. + status = -EBUSY;
  3010. + mutex_unlock(&rqsg_if.lock);
  3011. +
  3012. + if (status)
  3013. + goto err_install_dev;
  3014. +
  3015. + acpi_walk_dep_device_list(san);
  3016. + return 0;
  3017. +
  3018. +err_install_dev:
  3019. + san_events_unregister(pdev);
  3020. +err_enable_events:
  3021. + acpi_remove_address_space_handler(san, ACPI_ADR_SPACE_GSBUS, &san_opreg_handler);
  3022. +err_install_handler:
  3023. + platform_set_drvdata(san, NULL);
  3024. + san_consumers_unlink(&drvdata->consumers);
  3025. +err_consumers:
  3026. + kfree(drvdata);
  3027. + return status;
  3028. +}
  3029. +
  3030. +static int surface_sam_san_remove(struct platform_device *pdev)
  3031. +{
  3032. + struct san_drvdata *drvdata = platform_get_drvdata(pdev);
  3033. + acpi_handle san = ACPI_HANDLE(&pdev->dev); // _SAN device node
  3034. + acpi_status status = AE_OK;
  3035. +
  3036. + mutex_lock(&rqsg_if.lock);
  3037. + rqsg_if.san_dev = NULL;
  3038. + mutex_unlock(&rqsg_if.lock);
  3039. +
  3040. + acpi_remove_address_space_handler(san, ACPI_ADR_SPACE_GSBUS, &san_opreg_handler);
  3041. + san_events_unregister(pdev);
  3042. +
  3043. + /*
  3044. + * We have unregistered our event sources. Now we need to ensure that
  3045. + * all delayed works they may have spawned are run to completion.
  3046. + */
  3047. + flush_scheduled_work();
  3048. +
  3049. + san_consumers_unlink(&drvdata->consumers);
  3050. + kfree(drvdata);
  3051. +
  3052. + platform_set_drvdata(pdev, NULL);
  3053. + return status;
  3054. +}
  3055. +
  3056. +
  3057. +static const struct san_acpi_consumer san_mshw0091_consumers[] = {
  3058. + { "\\_SB.SRTC", true, DL_FLAG_PM_RUNTIME | DL_FLAG_STATELESS },
  3059. + { "\\ADP1", true, DL_FLAG_PM_RUNTIME | DL_FLAG_STATELESS },
  3060. + { "\\_SB.BAT1", true, DL_FLAG_PM_RUNTIME | DL_FLAG_STATELESS },
  3061. + { "\\_SB.BAT2", false, DL_FLAG_PM_RUNTIME | DL_FLAG_STATELESS },
  3062. + { },
  3063. +};
  3064. +
  3065. +static const struct acpi_device_id surface_sam_san_match[] = {
  3066. + { "MSHW0091", (unsigned long) san_mshw0091_consumers },
  3067. + { },
  3068. +};
  3069. +MODULE_DEVICE_TABLE(acpi, surface_sam_san_match);
  3070. +
  3071. +static struct platform_driver surface_sam_san = {
  3072. + .probe = surface_sam_san_probe,
  3073. + .remove = surface_sam_san_remove,
  3074. + .driver = {
  3075. + .name = "surface_sam_san",
  3076. + .acpi_match_table = surface_sam_san_match,
  3077. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  3078. + },
  3079. +};
  3080. +module_platform_driver(surface_sam_san);
  3081. +
  3082. +MODULE_AUTHOR("Maximilian Luz <luzmaximilian@gmail.com>");
  3083. +MODULE_DESCRIPTION("Surface ACPI Notify Driver for 5th Generation Surface Devices");
  3084. +MODULE_LICENSE("GPL");
  3085. diff --git a/drivers/platform/x86/surface_sam/surface_sam_san.h b/drivers/platform/x86/surface_sam/surface_sam_san.h
  3086. new file mode 100644
  3087. index 000000000000..2b9dee159bbb
  3088. --- /dev/null
  3089. +++ b/drivers/platform/x86/surface_sam/surface_sam_san.h
  3090. @@ -0,0 +1,30 @@
  3091. +/* SPDX-License-Identifier: GPL-2.0-or-later */
  3092. +/*
  3093. + * Interface for Surface ACPI/Notify (SAN).
  3094. + *
  3095. + * The SAN is the main interface between the Surface Serial Hub (SSH) and the
  3096. + * Surface/System Aggregator Module (SAM). It allows requests to be translated
  3097. + * from ACPI to SSH/SAM. It also interfaces with the discrete GPU hot-plug
  3098. + * driver.
  3099. + */
  3100. +
  3101. +#ifndef _SURFACE_SAM_SAN_H
  3102. +#define _SURFACE_SAM_SAN_H
  3103. +
  3104. +#include <linux/types.h>
  3105. +
  3106. +
  3107. +struct surface_sam_san_rqsg {
  3108. + u8 tc; // target category
  3109. + u8 cid; // command ID
  3110. + u8 iid; // instance ID
  3111. + u8 cdl; // command data length (length of payload)
  3112. + u8 *pld; // pointer to payload of length cdl
  3113. +};
  3114. +
  3115. +typedef int (*surface_sam_san_rqsg_handler_fn)(struct surface_sam_san_rqsg *rqsg, void *data);
  3116. +
  3117. +int surface_sam_san_consumer_register(struct device *consumer, u32 flags);
  3118. +int surface_sam_san_set_rqsg_handler(surface_sam_san_rqsg_handler_fn fn, void *data);
  3119. +
  3120. +#endif /* _SURFACE_SAM_SAN_H */
  3121. diff --git a/drivers/platform/x86/surface_sam/surface_sam_sid.c b/drivers/platform/x86/surface_sam/surface_sam_sid.c
  3122. new file mode 100644
  3123. index 000000000000..caa2e6446b5f
  3124. --- /dev/null
  3125. +++ b/drivers/platform/x86/surface_sam/surface_sam_sid.c
  3126. @@ -0,0 +1,281 @@
  3127. +// SPDX-License-Identifier: GPL-2.0-or-later
  3128. +/*
  3129. + * Surface Integration Driver.
  3130. + * MFD driver to provide device/model dependent functionality.
  3131. + */
  3132. +
  3133. +#include <linux/acpi.h>
  3134. +#include <linux/kernel.h>
  3135. +#include <linux/module.h>
  3136. +#include <linux/platform_device.h>
  3137. +#include <linux/mfd/core.h>
  3138. +
  3139. +#include "surface_sam_sid_power.h"
  3140. +#include "surface_sam_sid_vhf.h"
  3141. +
  3142. +
  3143. +struct ssam_battery_properties ssam_battery_props_bat1 = {
  3144. + .registry = SSAM_EVENT_REGISTRY_SAM,
  3145. + .num = 0,
  3146. + .channel = 1,
  3147. + .instance = 1,
  3148. +};
  3149. +
  3150. +struct ssam_battery_properties ssam_battery_props_bat2_sb3 = {
  3151. + .registry = SSAM_EVENT_REGISTRY_KIP,
  3152. + .num = 1,
  3153. + .channel = 2,
  3154. + .instance = 1,
  3155. +};
  3156. +
  3157. +
  3158. +static const struct ssam_hid_properties ssam_hid_props_keyboard = {
  3159. + .registry = SSAM_EVENT_REGISTRY_REG,
  3160. + .instance = 1,
  3161. +};
  3162. +
  3163. +static const struct ssam_hid_properties ssam_hid_props_touchpad = {
  3164. + .registry = SSAM_EVENT_REGISTRY_REG,
  3165. + .instance = 3,
  3166. +};
  3167. +
  3168. +static const struct ssam_hid_properties ssam_hid_props_iid5 = {
  3169. + .registry = SSAM_EVENT_REGISTRY_REG,
  3170. + .instance = 5,
  3171. +};
  3172. +
  3173. +static const struct ssam_hid_properties ssam_hid_props_iid6 = {
  3174. + .registry = SSAM_EVENT_REGISTRY_REG,
  3175. + .instance = 6,
  3176. +};
  3177. +
  3178. +
  3179. +static const struct mfd_cell sid_devs_sp4[] = {
  3180. + { .name = "surface_sam_sid_gpelid", .id = -1 },
  3181. + { .name = "surface_sam_sid_perfmode", .id = -1 },
  3182. + { },
  3183. +};
  3184. +
  3185. +static const struct mfd_cell sid_devs_sp6[] = {
  3186. + { .name = "surface_sam_sid_gpelid", .id = -1 },
  3187. + { .name = "surface_sam_sid_perfmode", .id = -1 },
  3188. + { },
  3189. +};
  3190. +
  3191. +static const struct mfd_cell sid_devs_sp7[] = {
  3192. + { .name = "surface_sam_sid_gpelid", .id = -1 },
  3193. + { .name = "surface_sam_sid_perfmode", .id = -1 },
  3194. + { .name = "surface_sam_sid_ac", .id = -1 },
  3195. + {
  3196. + .name = "surface_sam_sid_battery",
  3197. + .id = -1,
  3198. + .platform_data = &ssam_battery_props_bat1,
  3199. + .pdata_size = sizeof(struct ssam_battery_properties),
  3200. + },
  3201. + { },
  3202. +};
  3203. +
  3204. +static const struct mfd_cell sid_devs_sb1[] = {
  3205. + { .name = "surface_sam_sid_gpelid", .id = -1 },
  3206. + { },
  3207. +};
  3208. +
  3209. +static const struct mfd_cell sid_devs_sb2[] = {
  3210. + { .name = "surface_sam_sid_gpelid", .id = -1 },
  3211. + { .name = "surface_sam_sid_perfmode", .id = -1 },
  3212. + { },
  3213. +};
  3214. +
  3215. +static const struct mfd_cell sid_devs_sb3[] = {
  3216. + { .name = "surface_sam_sid_gpelid", .id = -1 },
  3217. + { .name = "surface_sam_sid_perfmode", .id = -1 },
  3218. + { .name = "surface_sam_sid_ac", .id = -1 },
  3219. + {
  3220. + .name = "surface_sam_sid_battery",
  3221. + .id = 1,
  3222. + .platform_data = &ssam_battery_props_bat1,
  3223. + .pdata_size = sizeof(struct ssam_battery_properties),
  3224. + },
  3225. + {
  3226. + .name = "surface_sam_sid_battery",
  3227. + .id = 2,
  3228. + .platform_data = &ssam_battery_props_bat2_sb3,
  3229. + .pdata_size = sizeof(struct ssam_battery_properties),
  3230. + },
  3231. + {
  3232. + .name = "surface_sam_sid_vhf",
  3233. + .id = 1,
  3234. + .platform_data = (void *)&ssam_hid_props_keyboard,
  3235. + .pdata_size = sizeof(struct ssam_hid_properties),
  3236. + },
  3237. + {
  3238. + .name = "surface_sam_sid_vhf",
  3239. + .id = 3,
  3240. + .platform_data = (void *)&ssam_hid_props_touchpad,
  3241. + .pdata_size = sizeof(struct ssam_hid_properties),
  3242. + },
  3243. + {
  3244. + .name = "surface_sam_sid_vhf",
  3245. + .id = 5,
  3246. + .platform_data = (void *)&ssam_hid_props_iid5,
  3247. + .pdata_size = sizeof(struct ssam_hid_properties),
  3248. + },
  3249. + {
  3250. + .name = "surface_sam_sid_vhf",
  3251. + .id = 6,
  3252. + .platform_data = (void *)&ssam_hid_props_iid6,
  3253. + .pdata_size = sizeof(struct ssam_hid_properties),
  3254. + },
  3255. + { },
  3256. +};
  3257. +
  3258. +static const struct mfd_cell sid_devs_sl1[] = {
  3259. + { .name = "surface_sam_sid_gpelid", .id = -1 },
  3260. + { },
  3261. +};
  3262. +
  3263. +static const struct mfd_cell sid_devs_sl2[] = {
  3264. + { .name = "surface_sam_sid_gpelid", .id = -1 },
  3265. + { },
  3266. +};
  3267. +
  3268. +static const struct mfd_cell sid_devs_sl3_13[] = {
  3269. + { .name = "surface_sam_sid_gpelid", .id = -1 },
  3270. + { .name = "surface_sam_sid_perfmode", .id = -1 },
  3271. + { .name = "surface_sam_sid_ac", .id = -1 },
  3272. + {
  3273. + .name = "surface_sam_sid_battery",
  3274. + .id = -1,
  3275. + .platform_data = &ssam_battery_props_bat1,
  3276. + .pdata_size = sizeof(struct ssam_battery_properties),
  3277. + },
  3278. + {
  3279. + .name = "surface_sam_sid_vhf",
  3280. + .id = 1,
  3281. + .platform_data = (void *)&ssam_hid_props_keyboard,
  3282. + .pdata_size = sizeof(struct ssam_hid_properties),
  3283. + },
  3284. + {
  3285. + .name = "surface_sam_sid_vhf",
  3286. + .id = 3,
  3287. + .platform_data = (void *)&ssam_hid_props_touchpad,
  3288. + .pdata_size = sizeof(struct ssam_hid_properties),
  3289. + },
  3290. + {
  3291. + .name = "surface_sam_sid_vhf",
  3292. + .id = 5,
  3293. + .platform_data = (void *)&ssam_hid_props_iid5,
  3294. + .pdata_size = sizeof(struct ssam_hid_properties),
  3295. + },
  3296. + { },
  3297. +};
  3298. +
  3299. +static const struct mfd_cell sid_devs_sl3_15[] = {
  3300. + { .name = "surface_sam_sid_perfmode", .id = -1 },
  3301. + { .name = "surface_sam_sid_ac", .id = -1 },
  3302. + {
  3303. + .name = "surface_sam_sid_battery",
  3304. + .id = -1,
  3305. + .platform_data = &ssam_battery_props_bat1,
  3306. + .pdata_size = sizeof(struct ssam_battery_properties),
  3307. + },
  3308. + {
  3309. + .name = "surface_sam_sid_vhf",
  3310. + .id = 1,
  3311. + .platform_data = (void *)&ssam_hid_props_keyboard,
  3312. + .pdata_size = sizeof(struct ssam_hid_properties),
  3313. + },
  3314. + {
  3315. + .name = "surface_sam_sid_vhf",
  3316. + .id = 3,
  3317. + .platform_data = (void *)&ssam_hid_props_touchpad,
  3318. + .pdata_size = sizeof(struct ssam_hid_properties),
  3319. + },
  3320. + {
  3321. + .name = "surface_sam_sid_vhf",
  3322. + .id = 5,
  3323. + .platform_data = (void *)&ssam_hid_props_iid5,
  3324. + .pdata_size = sizeof(struct ssam_hid_properties),
  3325. + },
  3326. + { },
  3327. +};
  3328. +
  3329. +static const struct acpi_device_id surface_sam_sid_match[] = {
  3330. + /* Surface Pro 4, 5, and 6 */
  3331. + { "MSHW0081", (unsigned long)sid_devs_sp4 },
  3332. +
  3333. + /* Surface Pro 6 (OMBR >= 0x10) */
  3334. + { "MSHW0111", (unsigned long)sid_devs_sp6 },
  3335. +
  3336. + /* Surface Pro 7 */
  3337. + { "MSHW0116", (unsigned long)sid_devs_sp7 },
  3338. +
  3339. + /* Surface Book 1 */
  3340. + { "MSHW0080", (unsigned long)sid_devs_sb1 },
  3341. +
  3342. + /* Surface Book 2 */
  3343. + { "MSHW0107", (unsigned long)sid_devs_sb2 },
  3344. +
  3345. + /* Surface Book 3 */
  3346. + { "MSHW0117", (unsigned long)sid_devs_sb3 },
  3347. +
  3348. + /* Surface Laptop 1 */
  3349. + { "MSHW0086", (unsigned long)sid_devs_sl1 },
  3350. +
  3351. + /* Surface Laptop 2 */
  3352. + { "MSHW0112", (unsigned long)sid_devs_sl2 },
  3353. +
  3354. + /* Surface Laptop 3 (13") */
  3355. + { "MSHW0114", (unsigned long)sid_devs_sl3_13 },
  3356. +
  3357. + /* Surface Laptop 3 (15") */
  3358. + { "MSHW0110", (unsigned long)sid_devs_sl3_15 },
  3359. +
  3360. + { },
  3361. +};
  3362. +MODULE_DEVICE_TABLE(acpi, surface_sam_sid_match);
  3363. +
  3364. +
  3365. +static int surface_sam_sid_probe(struct platform_device *pdev)
  3366. +{
  3367. + const struct acpi_device_id *match;
  3368. + const struct mfd_cell *cells, *p;
  3369. +
  3370. + match = acpi_match_device(surface_sam_sid_match, &pdev->dev);
  3371. + if (!match)
  3372. + return -ENODEV;
  3373. +
  3374. + cells = (struct mfd_cell *)match->driver_data;
  3375. + if (!cells)
  3376. + return -ENODEV;
  3377. +
  3378. + for (p = cells; p->name; ++p) {
  3379. + /* just count */
  3380. + }
  3381. +
  3382. + if (p == cells)
  3383. + return -ENODEV;
  3384. +
  3385. + return mfd_add_devices(&pdev->dev, 0, cells, p - cells, NULL, 0, NULL);
  3386. +}
  3387. +
  3388. +static int surface_sam_sid_remove(struct platform_device *pdev)
  3389. +{
  3390. + mfd_remove_devices(&pdev->dev);
  3391. + return 0;
  3392. +}
  3393. +
  3394. +static struct platform_driver surface_sam_sid = {
  3395. + .probe = surface_sam_sid_probe,
  3396. + .remove = surface_sam_sid_remove,
  3397. + .driver = {
  3398. + .name = "surface_sam_sid",
  3399. + .acpi_match_table = surface_sam_sid_match,
  3400. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  3401. + },
  3402. +};
  3403. +module_platform_driver(surface_sam_sid);
  3404. +
  3405. +MODULE_AUTHOR("Maximilian Luz <luzmaximilian@gmail.com>");
  3406. +MODULE_DESCRIPTION("Surface Integration Driver for 5th Generation Surface Devices");
  3407. +MODULE_LICENSE("GPL");
  3408. diff --git a/drivers/platform/x86/surface_sam/surface_sam_sid_gpelid.c b/drivers/platform/x86/surface_sam/surface_sam_sid_gpelid.c
  3409. new file mode 100644
  3410. index 000000000000..f0cee43c859b
  3411. --- /dev/null
  3412. +++ b/drivers/platform/x86/surface_sam/surface_sam_sid_gpelid.c
  3413. @@ -0,0 +1,232 @@
  3414. +// SPDX-License-Identifier: GPL-2.0-or-later
  3415. +/*
  3416. + * Surface Lid driver to enable wakeup from suspend via the lid.
  3417. + */
  3418. +
  3419. +#include <linux/acpi.h>
  3420. +#include <linux/dmi.h>
  3421. +#include <linux/kernel.h>
  3422. +#include <linux/module.h>
  3423. +#include <linux/platform_device.h>
  3424. +
  3425. +
  3426. +struct sid_lid_device {
  3427. + const char *acpi_path;
  3428. + const u32 gpe_number;
  3429. +};
  3430. +
  3431. +
  3432. +static const struct sid_lid_device lid_device_l17 = {
  3433. + .acpi_path = "\\_SB.LID0",
  3434. + .gpe_number = 0x17,
  3435. +};
  3436. +
  3437. +static const struct sid_lid_device lid_device_l4D = {
  3438. + .acpi_path = "\\_SB.LID0",
  3439. + .gpe_number = 0x4D,
  3440. +};
  3441. +
  3442. +static const struct sid_lid_device lid_device_l4F = {
  3443. + .acpi_path = "\\_SB.LID0",
  3444. + .gpe_number = 0x4F,
  3445. +};
  3446. +
  3447. +static const struct sid_lid_device lid_device_l57 = {
  3448. + .acpi_path = "\\_SB.LID0",
  3449. + .gpe_number = 0x57,
  3450. +};
  3451. +
  3452. +
  3453. +static const struct dmi_system_id dmi_lid_device_table[] = {
  3454. + {
  3455. + .ident = "Surface Pro 4",
  3456. + .matches = {
  3457. + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"),
  3458. + DMI_EXACT_MATCH(DMI_PRODUCT_NAME, "Surface Pro 4"),
  3459. + },
  3460. + .driver_data = (void *)&lid_device_l17,
  3461. + },
  3462. + {
  3463. + .ident = "Surface Pro 5",
  3464. + .matches = {
  3465. + /* match for SKU here due to generic product name "Surface Pro" */
  3466. + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"),
  3467. + DMI_EXACT_MATCH(DMI_PRODUCT_SKU, "Surface_Pro_1796"),
  3468. + },
  3469. + .driver_data = (void *)&lid_device_l4F,
  3470. + },
  3471. + {
  3472. + .ident = "Surface Pro 5 (LTE)",
  3473. + .matches = {
  3474. + /* match for SKU here due to generic product name "Surface Pro" */
  3475. + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"),
  3476. + DMI_EXACT_MATCH(DMI_PRODUCT_SKU, "Surface_Pro_1807"),
  3477. + },
  3478. + .driver_data = (void *)&lid_device_l4F,
  3479. + },
  3480. + {
  3481. + .ident = "Surface Pro 6",
  3482. + .matches = {
  3483. + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"),
  3484. + DMI_EXACT_MATCH(DMI_PRODUCT_NAME, "Surface Pro 6"),
  3485. + },
  3486. + .driver_data = (void *)&lid_device_l4F,
  3487. + },
  3488. + {
  3489. + .ident = "Surface Pro 7",
  3490. + .matches = {
  3491. + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"),
  3492. + DMI_EXACT_MATCH(DMI_PRODUCT_NAME, "Surface Pro 7"),
  3493. + },
  3494. + .driver_data = (void *)&lid_device_l4D,
  3495. + },
  3496. + {
  3497. + .ident = "Surface Book 1",
  3498. + .matches = {
  3499. + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"),
  3500. + DMI_EXACT_MATCH(DMI_PRODUCT_NAME, "Surface Book"),
  3501. + },
  3502. + .driver_data = (void *)&lid_device_l17,
  3503. + },
  3504. + {
  3505. + .ident = "Surface Book 2",
  3506. + .matches = {
  3507. + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"),
  3508. + DMI_EXACT_MATCH(DMI_PRODUCT_NAME, "Surface Book 2"),
  3509. + },
  3510. + .driver_data = (void *)&lid_device_l17,
  3511. + },
  3512. + {
  3513. + .ident = "Surface Book 3",
  3514. + .matches = {
  3515. + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"),
  3516. + DMI_EXACT_MATCH(DMI_PRODUCT_NAME, "Surface Book 3"),
  3517. + },
  3518. + .driver_data = (void *)&lid_device_l4D,
  3519. + },
  3520. + {
  3521. + .ident = "Surface Laptop 1",
  3522. + .matches = {
  3523. + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"),
  3524. + DMI_EXACT_MATCH(DMI_PRODUCT_NAME, "Surface Laptop"),
  3525. + },
  3526. + .driver_data = (void *)&lid_device_l57,
  3527. + },
  3528. + {
  3529. + .ident = "Surface Laptop 2",
  3530. + .matches = {
  3531. + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"),
  3532. + DMI_EXACT_MATCH(DMI_PRODUCT_NAME, "Surface Laptop 2"),
  3533. + },
  3534. + .driver_data = (void *)&lid_device_l57,
  3535. + },
  3536. + {
  3537. + .ident = "Surface Laptop 3 (13\")",
  3538. + .matches = {
  3539. + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"),
  3540. + DMI_EXACT_MATCH(DMI_PRODUCT_SKU, "Surface_Laptop_3_1867:1868"),
  3541. + },
  3542. + .driver_data = (void *)&lid_device_l4D,
  3543. + },
  3544. + { }
  3545. +};
  3546. +
  3547. +
  3548. +static int sid_lid_enable_wakeup(const struct sid_lid_device *dev, bool enable)
  3549. +{
  3550. + int action = enable ? ACPI_GPE_ENABLE : ACPI_GPE_DISABLE;
  3551. + int status;
  3552. +
  3553. + status = acpi_set_gpe_wake_mask(NULL, dev->gpe_number, action);
  3554. + if (status)
  3555. + return -EFAULT;
  3556. +
  3557. + return 0;
  3558. +}
  3559. +
  3560. +
  3561. +static int surface_sam_sid_gpelid_suspend(struct device *dev)
  3562. +{
  3563. + const struct sid_lid_device *ldev;
  3564. +
  3565. + ldev = dev_get_drvdata(dev);
  3566. + return sid_lid_enable_wakeup(ldev, true);
  3567. +}
  3568. +
  3569. +static int surface_sam_sid_gpelid_resume(struct device *dev)
  3570. +{
  3571. + const struct sid_lid_device *ldev;
  3572. +
  3573. + ldev = dev_get_drvdata(dev);
  3574. + return sid_lid_enable_wakeup(ldev, false);
  3575. +}
  3576. +
  3577. +static SIMPLE_DEV_PM_OPS(surface_sam_sid_gpelid_pm,
  3578. + surface_sam_sid_gpelid_suspend,
  3579. + surface_sam_sid_gpelid_resume);
  3580. +
  3581. +
  3582. +static int surface_sam_sid_gpelid_probe(struct platform_device *pdev)
  3583. +{
  3584. + const struct dmi_system_id *match;
  3585. + struct sid_lid_device *dev;
  3586. + acpi_handle lid_handle;
  3587. + int status;
  3588. +
  3589. + match = dmi_first_match(dmi_lid_device_table);
  3590. + if (!match)
  3591. + return -ENODEV;
  3592. +
  3593. + dev = match->driver_data;
  3594. + if (!dev)
  3595. + return -ENODEV;
  3596. +
  3597. + status = acpi_get_handle(NULL, (acpi_string)dev->acpi_path, &lid_handle);
  3598. + if (status)
  3599. + return -EFAULT;
  3600. +
  3601. + status = acpi_setup_gpe_for_wake(lid_handle, NULL, dev->gpe_number);
  3602. + if (status)
  3603. + return -EFAULT;
  3604. +
  3605. + status = acpi_enable_gpe(NULL, dev->gpe_number);
  3606. + if (status)
  3607. + return -EFAULT;
  3608. +
  3609. + status = sid_lid_enable_wakeup(dev, false);
  3610. + if (status) {
  3611. + acpi_disable_gpe(NULL, dev->gpe_number);
  3612. + return status;
  3613. + }
  3614. +
  3615. + platform_set_drvdata(pdev, dev);
  3616. + return 0;
  3617. +}
  3618. +
  3619. +static int surface_sam_sid_gpelid_remove(struct platform_device *pdev)
  3620. +{
  3621. + struct sid_lid_device *dev = platform_get_drvdata(pdev);
  3622. +
  3623. + /* restore default behavior without this module */
  3624. + sid_lid_enable_wakeup(dev, false);
  3625. + acpi_disable_gpe(NULL, dev->gpe_number);
  3626. +
  3627. + platform_set_drvdata(pdev, NULL);
  3628. + return 0;
  3629. +}
  3630. +
  3631. +static struct platform_driver surface_sam_sid_gpelid = {
  3632. + .probe = surface_sam_sid_gpelid_probe,
  3633. + .remove = surface_sam_sid_gpelid_remove,
  3634. + .driver = {
  3635. + .name = "surface_sam_sid_gpelid",
  3636. + .pm = &surface_sam_sid_gpelid_pm,
  3637. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  3638. + },
  3639. +};
  3640. +module_platform_driver(surface_sam_sid_gpelid);
  3641. +
  3642. +MODULE_AUTHOR("Maximilian Luz <luzmaximilian@gmail.com>");
  3643. +MODULE_DESCRIPTION("Surface Lid Driver for 5th Generation Surface Devices");
  3644. +MODULE_LICENSE("GPL");
  3645. +MODULE_ALIAS("platform:surface_sam_sid_gpelid");
  3646. diff --git a/drivers/platform/x86/surface_sam/surface_sam_sid_perfmode.c b/drivers/platform/x86/surface_sam/surface_sam_sid_perfmode.c
  3647. new file mode 100644
  3648. index 000000000000..2e11efb166f2
  3649. --- /dev/null
  3650. +++ b/drivers/platform/x86/surface_sam/surface_sam_sid_perfmode.c
  3651. @@ -0,0 +1,216 @@
  3652. +// SPDX-License-Identifier: GPL-2.0-or-later
  3653. +/*
  3654. + * Surface Performance Mode Driver.
  3655. + * Allows to change cooling capabilities based on user preference.
  3656. + */
  3657. +
  3658. +#include <asm/unaligned.h>
  3659. +#include <linux/kernel.h>
  3660. +#include <linux/module.h>
  3661. +#include <linux/platform_device.h>
  3662. +
  3663. +#include "surface_sam_ssh.h"
  3664. +
  3665. +
  3666. +#define SID_PARAM_PERM 0644
  3667. +
  3668. +enum sam_perf_mode {
  3669. + SAM_PERF_MODE_NORMAL = 1,
  3670. + SAM_PERF_MODE_BATTERY = 2,
  3671. + SAM_PERF_MODE_PERF1 = 3,
  3672. + SAM_PERF_MODE_PERF2 = 4,
  3673. +
  3674. + __SAM_PERF_MODE__START = 1,
  3675. + __SAM_PERF_MODE__END = 4,
  3676. +};
  3677. +
  3678. +enum sid_param_perf_mode {
  3679. + SID_PARAM_PERF_MODE_AS_IS = 0,
  3680. + SID_PARAM_PERF_MODE_NORMAL = SAM_PERF_MODE_NORMAL,
  3681. + SID_PARAM_PERF_MODE_BATTERY = SAM_PERF_MODE_BATTERY,
  3682. + SID_PARAM_PERF_MODE_PERF1 = SAM_PERF_MODE_PERF1,
  3683. + SID_PARAM_PERF_MODE_PERF2 = SAM_PERF_MODE_PERF2,
  3684. +
  3685. + __SID_PARAM_PERF_MODE__START = 0,
  3686. + __SID_PARAM_PERF_MODE__END = 4,
  3687. +};
  3688. +
  3689. +
  3690. +static int surface_sam_perf_mode_get(void)
  3691. +{
  3692. + u8 result_buf[8] = { 0 };
  3693. + int status;
  3694. +
  3695. + struct surface_sam_ssh_rqst rqst = {
  3696. + .tc = 0x03,
  3697. + .cid = 0x02,
  3698. + .iid = 0x00,
  3699. + .chn = 0x01,
  3700. + .snc = 0x01,
  3701. + .cdl = 0x00,
  3702. + .pld = NULL,
  3703. + };
  3704. +
  3705. + struct surface_sam_ssh_buf result = {
  3706. + .cap = ARRAY_SIZE(result_buf),
  3707. + .len = 0,
  3708. + .data = result_buf,
  3709. + };
  3710. +
  3711. + status = surface_sam_ssh_rqst(&rqst, &result);
  3712. + if (status)
  3713. + return status;
  3714. +
  3715. + if (result.len != 8)
  3716. + return -EFAULT;
  3717. +
  3718. + return get_unaligned_le32(&result.data[0]);
  3719. +}
  3720. +
  3721. +static int surface_sam_perf_mode_set(int perf_mode)
  3722. +{
  3723. + u8 payload[4] = { 0 };
  3724. +
  3725. + struct surface_sam_ssh_rqst rqst = {
  3726. + .tc = 0x03,
  3727. + .cid = 0x03,
  3728. + .iid = 0x00,
  3729. + .chn = 0x01,
  3730. + .snc = 0x00,
  3731. + .cdl = ARRAY_SIZE(payload),
  3732. + .pld = payload,
  3733. + };
  3734. +
  3735. + if (perf_mode < __SAM_PERF_MODE__START || perf_mode > __SAM_PERF_MODE__END)
  3736. + return -EINVAL;
  3737. +
  3738. + put_unaligned_le32(perf_mode, &rqst.pld[0]);
  3739. + return surface_sam_ssh_rqst(&rqst, NULL);
  3740. +}
  3741. +
  3742. +
  3743. +static int param_perf_mode_set(const char *val, const struct kernel_param *kp)
  3744. +{
  3745. + int perf_mode;
  3746. + int status;
  3747. +
  3748. + status = kstrtoint(val, 0, &perf_mode);
  3749. + if (status)
  3750. + return status;
  3751. +
  3752. + if (perf_mode < __SID_PARAM_PERF_MODE__START || perf_mode > __SID_PARAM_PERF_MODE__END)
  3753. + return -EINVAL;
  3754. +
  3755. + return param_set_int(val, kp);
  3756. +}
  3757. +
  3758. +static const struct kernel_param_ops param_perf_mode_ops = {
  3759. + .set = param_perf_mode_set,
  3760. + .get = param_get_int,
  3761. +};
  3762. +
  3763. +static int param_perf_mode_init = SID_PARAM_PERF_MODE_AS_IS;
  3764. +static int param_perf_mode_exit = SID_PARAM_PERF_MODE_AS_IS;
  3765. +
  3766. +module_param_cb(perf_mode_init, &param_perf_mode_ops, &param_perf_mode_init, SID_PARAM_PERM);
  3767. +module_param_cb(perf_mode_exit, &param_perf_mode_ops, &param_perf_mode_exit, SID_PARAM_PERM);
  3768. +
  3769. +MODULE_PARM_DESC(perf_mode_init, "Performance-mode to be set on module initialization");
  3770. +MODULE_PARM_DESC(perf_mode_exit, "Performance-mode to be set on module exit");
  3771. +
  3772. +
  3773. +static ssize_t perf_mode_show(struct device *dev, struct device_attribute *attr, char *data)
  3774. +{
  3775. + int perf_mode;
  3776. +
  3777. + perf_mode = surface_sam_perf_mode_get();
  3778. + if (perf_mode < 0) {
  3779. + dev_err(dev, "failed to get current performance mode: %d\n", perf_mode);
  3780. + return -EIO;
  3781. + }
  3782. +
  3783. + return sprintf(data, "%d\n", perf_mode);
  3784. +}
  3785. +
  3786. +static ssize_t perf_mode_store(struct device *dev, struct device_attribute *attr,
  3787. + const char *data, size_t count)
  3788. +{
  3789. + int perf_mode;
  3790. + int status;
  3791. +
  3792. + status = kstrtoint(data, 0, &perf_mode);
  3793. + if (status)
  3794. + return status;
  3795. +
  3796. + status = surface_sam_perf_mode_set(perf_mode);
  3797. + if (status)
  3798. + return status;
  3799. +
  3800. + // TODO: Should we notify ACPI here?
  3801. + //
  3802. + // There is a _DSM call described as
  3803. + // WSID._DSM: Notify DPTF on Slider State change
  3804. + // which calls
  3805. + // ODV3 = ToInteger (Arg3)
  3806. + // Notify(IETM, 0x88)
  3807. + // IETM is an INT3400 Intel Dynamic Power Performance Management
  3808. + // device, part of the DPTF framework. From the corresponding
  3809. + // kernel driver, it looks like event 0x88 is being ignored. Also
  3810. + // it is currently unknown what the consequecnes of setting ODV3
  3811. + // are.
  3812. +
  3813. + return count;
  3814. +}
  3815. +
  3816. +static const DEVICE_ATTR_RW(perf_mode);
  3817. +
  3818. +
  3819. +static int surface_sam_sid_perfmode_probe(struct platform_device *pdev)
  3820. +{
  3821. + int status;
  3822. +
  3823. + // link to ec
  3824. + status = surface_sam_ssh_consumer_register(&pdev->dev);
  3825. + if (status)
  3826. + return status == -ENXIO ? -EPROBE_DEFER : status;
  3827. +
  3828. + // set initial perf_mode
  3829. + if (param_perf_mode_init != SID_PARAM_PERF_MODE_AS_IS) {
  3830. + status = surface_sam_perf_mode_set(param_perf_mode_init);
  3831. + if (status)
  3832. + return status;
  3833. + }
  3834. +
  3835. + // register perf_mode attribute
  3836. + status = sysfs_create_file(&pdev->dev.kobj, &dev_attr_perf_mode.attr);
  3837. + if (status)
  3838. + goto err_sysfs;
  3839. +
  3840. + return 0;
  3841. +
  3842. +err_sysfs:
  3843. + surface_sam_perf_mode_set(param_perf_mode_exit);
  3844. + return status;
  3845. +}
  3846. +
  3847. +static int surface_sam_sid_perfmode_remove(struct platform_device *pdev)
  3848. +{
  3849. + sysfs_remove_file(&pdev->dev.kobj, &dev_attr_perf_mode.attr);
  3850. + surface_sam_perf_mode_set(param_perf_mode_exit);
  3851. + return 0;
  3852. +}
  3853. +
  3854. +static struct platform_driver surface_sam_sid_perfmode = {
  3855. + .probe = surface_sam_sid_perfmode_probe,
  3856. + .remove = surface_sam_sid_perfmode_remove,
  3857. + .driver = {
  3858. + .name = "surface_sam_sid_perfmode",
  3859. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  3860. + },
  3861. +};
  3862. +module_platform_driver(surface_sam_sid_perfmode);
  3863. +
  3864. +MODULE_AUTHOR("Maximilian Luz <luzmaximilian@gmail.com>");
  3865. +MODULE_DESCRIPTION("Surface Performance Mode Driver for 5th Generation Surface Devices");
  3866. +MODULE_LICENSE("GPL");
  3867. +MODULE_ALIAS("platform:surface_sam_sid_perfmode");
  3868. diff --git a/drivers/platform/x86/surface_sam/surface_sam_sid_power.c b/drivers/platform/x86/surface_sam/surface_sam_sid_power.c
  3869. new file mode 100644
  3870. index 000000000000..1d945c0a911a
  3871. --- /dev/null
  3872. +++ b/drivers/platform/x86/surface_sam/surface_sam_sid_power.c
  3873. @@ -0,0 +1,1154 @@
  3874. +// SPDX-License-Identifier: GPL-2.0-or-later
  3875. +/*
  3876. + * Surface SID Battery/AC Driver.
  3877. + * Provides support for the battery and AC on 7th generation Surface devices.
  3878. + */
  3879. +
  3880. +#include <linux/kernel.h>
  3881. +#include <linux/delay.h>
  3882. +#include <linux/jiffies.h>
  3883. +#include <linux/module.h>
  3884. +#include <linux/platform_device.h>
  3885. +#include <linux/power_supply.h>
  3886. +#include <linux/workqueue.h>
  3887. +
  3888. +#include "surface_sam_ssh.h"
  3889. +#include "surface_sam_sid_power.h"
  3890. +
  3891. +#define SPWR_WARN KERN_WARNING KBUILD_MODNAME ": "
  3892. +#define SPWR_DEBUG KERN_DEBUG KBUILD_MODNAME ": "
  3893. +
  3894. +
  3895. +// TODO: check BIX/BST for unknown/unsupported 0xffffffff entries
  3896. +// TODO: DPTF (/SAN notifications)?
  3897. +// TODO: other properties?
  3898. +
  3899. +
  3900. +static unsigned int cache_time = 1000;
  3901. +module_param(cache_time, uint, 0644);
  3902. +MODULE_PARM_DESC(cache_time, "battery state chaching time in milliseconds [default: 1000]");
  3903. +
  3904. +#define SPWR_AC_BAT_UPDATE_DELAY msecs_to_jiffies(5000)
  3905. +
  3906. +
  3907. +/*
  3908. + * SAM Interface.
  3909. + */
  3910. +
  3911. +#define SAM_PWR_TC 0x02
  3912. +
  3913. +#define SAM_RQST_PWR_CID_STA 0x01
  3914. +#define SAM_RQST_PWR_CID_BIX 0x02
  3915. +#define SAM_RQST_PWR_CID_BST 0x03
  3916. +#define SAM_RQST_PWR_CID_BTP 0x04
  3917. +
  3918. +#define SAM_RQST_PWR_CID_PMAX 0x0b
  3919. +#define SAM_RQST_PWR_CID_PSOC 0x0c
  3920. +#define SAM_RQST_PWR_CID_PSRC 0x0d
  3921. +#define SAM_RQST_PWR_CID_CHGI 0x0e
  3922. +#define SAM_RQST_PWR_CID_ARTG 0x0f
  3923. +
  3924. +#define SAM_EVENT_PWR_CID_BIX 0x15
  3925. +#define SAM_EVENT_PWR_CID_BST 0x16
  3926. +#define SAM_EVENT_PWR_CID_ADAPTER 0x17
  3927. +
  3928. +#define SAM_BATTERY_STA_OK 0x0f
  3929. +#define SAM_BATTERY_STA_PRESENT 0x10
  3930. +
  3931. +#define SAM_BATTERY_STATE_DISCHARGING 0x01
  3932. +#define SAM_BATTERY_STATE_CHARGING 0x02
  3933. +#define SAM_BATTERY_STATE_CRITICAL 0x04
  3934. +
  3935. +#define SAM_BATTERY_POWER_UNIT_MA 1
  3936. +
  3937. +
  3938. +/* Equivalent to data returned in ACPI _BIX method */
  3939. +struct spwr_bix {
  3940. + u8 revision;
  3941. + u32 power_unit;
  3942. + u32 design_cap;
  3943. + u32 last_full_charge_cap;
  3944. + u32 technology;
  3945. + u32 design_voltage;
  3946. + u32 design_cap_warn;
  3947. + u32 design_cap_low;
  3948. + u32 cycle_count;
  3949. + u32 measurement_accuracy;
  3950. + u32 max_sampling_time;
  3951. + u32 min_sampling_time;
  3952. + u32 max_avg_interval;
  3953. + u32 min_avg_interval;
  3954. + u32 bat_cap_granularity_1;
  3955. + u32 bat_cap_granularity_2;
  3956. + u8 model[21];
  3957. + u8 serial[11];
  3958. + u8 type[5];
  3959. + u8 oem_info[21];
  3960. +} __packed;
  3961. +
  3962. +/* Equivalent to data returned in ACPI _BST method */
  3963. +struct spwr_bst {
  3964. + u32 state;
  3965. + u32 present_rate;
  3966. + u32 remaining_cap;
  3967. + u32 present_voltage;
  3968. +} __packed;
  3969. +
  3970. +/* DPTF event payload */
  3971. +struct spwr_event_dptf {
  3972. + u32 pmax;
  3973. + u32 _1; /* currently unknown */
  3974. + u32 _2; /* currently unknown */
  3975. +} __packed;
  3976. +
  3977. +
  3978. +/* Get battery status (_STA) */
  3979. +static int sam_psy_get_sta(u8 channel, u8 instance, u32 *sta)
  3980. +{
  3981. + struct surface_sam_ssh_rqst rqst;
  3982. + struct surface_sam_ssh_buf result;
  3983. +
  3984. + rqst.tc = SAM_PWR_TC;
  3985. + rqst.cid = SAM_RQST_PWR_CID_STA;
  3986. + rqst.iid = instance;
  3987. + rqst.chn = channel;
  3988. + rqst.snc = 0x01;
  3989. + rqst.cdl = 0x00;
  3990. + rqst.pld = NULL;
  3991. +
  3992. + result.cap = sizeof(u32);
  3993. + result.len = 0;
  3994. + result.data = (u8 *)sta;
  3995. +
  3996. + return surface_sam_ssh_rqst(&rqst, &result);
  3997. +}
  3998. +
  3999. +/* Get battery static information (_BIX) */
  4000. +static int sam_psy_get_bix(u8 channel, u8 instance, struct spwr_bix *bix)
  4001. +{
  4002. + struct surface_sam_ssh_rqst rqst;
  4003. + struct surface_sam_ssh_buf result;
  4004. +
  4005. + rqst.tc = SAM_PWR_TC;
  4006. + rqst.cid = SAM_RQST_PWR_CID_BIX;
  4007. + rqst.iid = instance;
  4008. + rqst.chn = channel;
  4009. + rqst.snc = 0x01;
  4010. + rqst.cdl = 0x00;
  4011. + rqst.pld = NULL;
  4012. +
  4013. + result.cap = sizeof(struct spwr_bix);
  4014. + result.len = 0;
  4015. + result.data = (u8 *)bix;
  4016. +
  4017. + return surface_sam_ssh_rqst(&rqst, &result);
  4018. +}
  4019. +
  4020. +/* Get battery dynamic information (_BST) */
  4021. +static int sam_psy_get_bst(u8 channel, u8 instance, struct spwr_bst *bst)
  4022. +{
  4023. + struct surface_sam_ssh_rqst rqst;
  4024. + struct surface_sam_ssh_buf result;
  4025. +
  4026. + rqst.tc = SAM_PWR_TC;
  4027. + rqst.cid = SAM_RQST_PWR_CID_BST;
  4028. + rqst.iid = instance;
  4029. + rqst.chn = channel;
  4030. + rqst.snc = 0x01;
  4031. + rqst.cdl = 0x00;
  4032. + rqst.pld = NULL;
  4033. +
  4034. + result.cap = sizeof(struct spwr_bst);
  4035. + result.len = 0;
  4036. + result.data = (u8 *)bst;
  4037. +
  4038. + return surface_sam_ssh_rqst(&rqst, &result);
  4039. +}
  4040. +
  4041. +/* Set battery trip point (_BTP) */
  4042. +static int sam_psy_set_btp(u8 channel, u8 instance, u32 btp)
  4043. +{
  4044. + struct surface_sam_ssh_rqst rqst;
  4045. +
  4046. + rqst.tc = SAM_PWR_TC;
  4047. + rqst.cid = SAM_RQST_PWR_CID_BTP;
  4048. + rqst.iid = instance;
  4049. + rqst.chn = channel;
  4050. + rqst.snc = 0x00;
  4051. + rqst.cdl = sizeof(u32);
  4052. + rqst.pld = (u8 *)&btp;
  4053. +
  4054. + return surface_sam_ssh_rqst(&rqst, NULL);
  4055. +}
  4056. +
  4057. +/* Get platform power soruce for battery (DPTF PSRC) */
  4058. +static int sam_psy_get_psrc(u8 channel, u8 instance, u32 *psrc)
  4059. +{
  4060. + struct surface_sam_ssh_rqst rqst;
  4061. + struct surface_sam_ssh_buf result;
  4062. +
  4063. + rqst.tc = SAM_PWR_TC;
  4064. + rqst.cid = SAM_RQST_PWR_CID_PSRC;
  4065. + rqst.iid = instance;
  4066. + rqst.chn = channel;
  4067. + rqst.snc = 0x01;
  4068. + rqst.cdl = 0x00;
  4069. + rqst.pld = NULL;
  4070. +
  4071. + result.cap = sizeof(u32);
  4072. + result.len = 0;
  4073. + result.data = (u8 *)psrc;
  4074. +
  4075. + return surface_sam_ssh_rqst(&rqst, &result);
  4076. +}
  4077. +
  4078. +/* Get maximum platform power for battery (DPTF PMAX) */
  4079. +__always_unused
  4080. +static int sam_psy_get_pmax(u8 channel, u8 instance, u32 *pmax)
  4081. +{
  4082. + struct surface_sam_ssh_rqst rqst;
  4083. + struct surface_sam_ssh_buf result;
  4084. +
  4085. + rqst.tc = SAM_PWR_TC;
  4086. + rqst.cid = SAM_RQST_PWR_CID_PMAX;
  4087. + rqst.iid = instance;
  4088. + rqst.chn = channel;
  4089. + rqst.snc = 0x01;
  4090. + rqst.cdl = 0x00;
  4091. + rqst.pld = NULL;
  4092. +
  4093. + result.cap = sizeof(u32);
  4094. + result.len = 0;
  4095. + result.data = (u8 *)pmax;
  4096. +
  4097. + return surface_sam_ssh_rqst(&rqst, &result);
  4098. +}
  4099. +
  4100. +/* Get adapter rating (DPTF ARTG) */
  4101. +__always_unused
  4102. +static int sam_psy_get_artg(u8 channel, u8 instance, u32 *artg)
  4103. +{
  4104. + struct surface_sam_ssh_rqst rqst;
  4105. + struct surface_sam_ssh_buf result;
  4106. +
  4107. + rqst.tc = SAM_PWR_TC;
  4108. + rqst.cid = SAM_RQST_PWR_CID_ARTG;
  4109. + rqst.iid = instance;
  4110. + rqst.chn = channel;
  4111. + rqst.snc = 0x01;
  4112. + rqst.cdl = 0x00;
  4113. + rqst.pld = NULL;
  4114. +
  4115. + result.cap = sizeof(u32);
  4116. + result.len = 0;
  4117. + result.data = (u8 *)artg;
  4118. +
  4119. + return surface_sam_ssh_rqst(&rqst, &result);
  4120. +}
  4121. +
  4122. +/* Unknown (DPTF PSOC) */
  4123. +__always_unused
  4124. +static int sam_psy_get_psoc(u8 channel, u8 instance, u32 *psoc)
  4125. +{
  4126. + struct surface_sam_ssh_rqst rqst;
  4127. + struct surface_sam_ssh_buf result;
  4128. +
  4129. + rqst.tc = SAM_PWR_TC;
  4130. + rqst.cid = SAM_RQST_PWR_CID_PSOC;
  4131. + rqst.iid = instance;
  4132. + rqst.chn = channel;
  4133. + rqst.snc = 0x01;
  4134. + rqst.cdl = 0x00;
  4135. + rqst.pld = NULL;
  4136. +
  4137. + result.cap = sizeof(u32);
  4138. + result.len = 0;
  4139. + result.data = (u8 *)psoc;
  4140. +
  4141. + return surface_sam_ssh_rqst(&rqst, &result);
  4142. +}
  4143. +
  4144. +/* Unknown (DPTF CHGI/ INT3403 SPPC) */
  4145. +__always_unused
  4146. +static int sam_psy_set_chgi(u8 channel, u8 instance, u32 chgi)
  4147. +{
  4148. + struct surface_sam_ssh_rqst rqst;
  4149. +
  4150. + rqst.tc = SAM_PWR_TC;
  4151. + rqst.cid = SAM_RQST_PWR_CID_CHGI;
  4152. + rqst.iid = instance;
  4153. + rqst.chn = channel;
  4154. + rqst.snc = 0x00;
  4155. + rqst.cdl = sizeof(u32);
  4156. + rqst.pld = (u8 *)&chgi;
  4157. +
  4158. + return surface_sam_ssh_rqst(&rqst, NULL);
  4159. +}
  4160. +
  4161. +
  4162. +/*
  4163. + * Common Power-Subsystem Interface.
  4164. + */
  4165. +
  4166. +struct spwr_battery_device {
  4167. + struct platform_device *pdev;
  4168. + const struct ssam_battery_properties *p;
  4169. +
  4170. + char name[32];
  4171. + struct power_supply *psy;
  4172. + struct power_supply_desc psy_desc;
  4173. +
  4174. + struct delayed_work update_work;
  4175. +
  4176. + struct ssam_event_notifier notif;
  4177. +
  4178. + struct mutex lock;
  4179. + unsigned long timestamp;
  4180. +
  4181. + u32 sta;
  4182. + struct spwr_bix bix;
  4183. + struct spwr_bst bst;
  4184. + u32 alarm;
  4185. +};
  4186. +
  4187. +struct spwr_ac_device {
  4188. + struct platform_device *pdev;
  4189. +
  4190. + char name[32];
  4191. + struct power_supply *psy;
  4192. + struct power_supply_desc psy_desc;
  4193. +
  4194. + struct ssam_event_notifier notif;
  4195. +
  4196. + struct mutex lock;
  4197. +
  4198. + u32 state;
  4199. +};
  4200. +
  4201. +static enum power_supply_property spwr_ac_props[] = {
  4202. + POWER_SUPPLY_PROP_ONLINE,
  4203. +};
  4204. +
  4205. +static enum power_supply_property spwr_battery_props_chg[] = {
  4206. + POWER_SUPPLY_PROP_STATUS,
  4207. + POWER_SUPPLY_PROP_PRESENT,
  4208. + POWER_SUPPLY_PROP_TECHNOLOGY,
  4209. + POWER_SUPPLY_PROP_CYCLE_COUNT,
  4210. + POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN,
  4211. + POWER_SUPPLY_PROP_VOLTAGE_NOW,
  4212. + POWER_SUPPLY_PROP_CURRENT_NOW,
  4213. + POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN,
  4214. + POWER_SUPPLY_PROP_CHARGE_FULL,
  4215. + POWER_SUPPLY_PROP_CHARGE_NOW,
  4216. + POWER_SUPPLY_PROP_CAPACITY,
  4217. + POWER_SUPPLY_PROP_CAPACITY_LEVEL,
  4218. + POWER_SUPPLY_PROP_MODEL_NAME,
  4219. + POWER_SUPPLY_PROP_MANUFACTURER,
  4220. + POWER_SUPPLY_PROP_SERIAL_NUMBER,
  4221. +};
  4222. +
  4223. +static enum power_supply_property spwr_battery_props_eng[] = {
  4224. + POWER_SUPPLY_PROP_STATUS,
  4225. + POWER_SUPPLY_PROP_PRESENT,
  4226. + POWER_SUPPLY_PROP_TECHNOLOGY,
  4227. + POWER_SUPPLY_PROP_CYCLE_COUNT,
  4228. + POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN,
  4229. + POWER_SUPPLY_PROP_VOLTAGE_NOW,
  4230. + POWER_SUPPLY_PROP_POWER_NOW,
  4231. + POWER_SUPPLY_PROP_ENERGY_FULL_DESIGN,
  4232. + POWER_SUPPLY_PROP_ENERGY_FULL,
  4233. + POWER_SUPPLY_PROP_ENERGY_NOW,
  4234. + POWER_SUPPLY_PROP_CAPACITY,
  4235. + POWER_SUPPLY_PROP_CAPACITY_LEVEL,
  4236. + POWER_SUPPLY_PROP_MODEL_NAME,
  4237. + POWER_SUPPLY_PROP_MANUFACTURER,
  4238. + POWER_SUPPLY_PROP_SERIAL_NUMBER,
  4239. +};
  4240. +
  4241. +
  4242. +static int spwr_battery_register(struct spwr_battery_device *bat,
  4243. + struct platform_device *pdev,
  4244. + const struct ssam_battery_properties *p);
  4245. +
  4246. +static void spwr_battery_unregister(struct spwr_battery_device *bat);
  4247. +
  4248. +
  4249. +static inline bool spwr_battery_present(struct spwr_battery_device *bat)
  4250. +{
  4251. + return bat->sta & SAM_BATTERY_STA_PRESENT;
  4252. +}
  4253. +
  4254. +
  4255. +static inline int spwr_battery_load_sta(struct spwr_battery_device *bat)
  4256. +{
  4257. + return sam_psy_get_sta(bat->p->channel, bat->p->instance, &bat->sta);
  4258. +}
  4259. +
  4260. +static inline int spwr_battery_load_bix(struct spwr_battery_device *bat)
  4261. +{
  4262. + if (!spwr_battery_present(bat))
  4263. + return 0;
  4264. +
  4265. + return sam_psy_get_bix(bat->p->channel, bat->p->instance, &bat->bix);
  4266. +}
  4267. +
  4268. +static inline int spwr_battery_load_bst(struct spwr_battery_device *bat)
  4269. +{
  4270. + if (!spwr_battery_present(bat))
  4271. + return 0;
  4272. +
  4273. + return sam_psy_get_bst(bat->p->channel, bat->p->instance, &bat->bst);
  4274. +}
  4275. +
  4276. +
  4277. +static inline int spwr_battery_set_alarm_unlocked(struct spwr_battery_device *bat, u32 value)
  4278. +{
  4279. + bat->alarm = value;
  4280. + return sam_psy_set_btp(bat->p->channel, bat->p->instance, bat->alarm);
  4281. +}
  4282. +
  4283. +static inline int spwr_battery_set_alarm(struct spwr_battery_device *bat, u32 value)
  4284. +{
  4285. + int status;
  4286. +
  4287. + mutex_lock(&bat->lock);
  4288. + status = spwr_battery_set_alarm_unlocked(bat, value);
  4289. + mutex_unlock(&bat->lock);
  4290. +
  4291. + return status;
  4292. +}
  4293. +
  4294. +static inline int spwr_battery_update_bst_unlocked(struct spwr_battery_device *bat, bool cached)
  4295. +{
  4296. + unsigned long cache_deadline = bat->timestamp + msecs_to_jiffies(cache_time);
  4297. + int status;
  4298. +
  4299. + if (cached && bat->timestamp && time_is_after_jiffies(cache_deadline))
  4300. + return 0;
  4301. +
  4302. + status = spwr_battery_load_sta(bat);
  4303. + if (status)
  4304. + return status;
  4305. +
  4306. + status = spwr_battery_load_bst(bat);
  4307. + if (status)
  4308. + return status;
  4309. +
  4310. + bat->timestamp = jiffies;
  4311. + return 0;
  4312. +}
  4313. +
  4314. +static int spwr_battery_update_bst(struct spwr_battery_device *bat, bool cached)
  4315. +{
  4316. + int status;
  4317. +
  4318. + mutex_lock(&bat->lock);
  4319. + status = spwr_battery_update_bst_unlocked(bat, cached);
  4320. + mutex_unlock(&bat->lock);
  4321. +
  4322. + return status;
  4323. +}
  4324. +
  4325. +static inline int spwr_battery_update_bix_unlocked(struct spwr_battery_device *bat)
  4326. +{
  4327. + int status;
  4328. +
  4329. + status = spwr_battery_load_sta(bat);
  4330. + if (status)
  4331. + return status;
  4332. +
  4333. + status = spwr_battery_load_bix(bat);
  4334. + if (status)
  4335. + return status;
  4336. +
  4337. + status = spwr_battery_load_bst(bat);
  4338. + if (status)
  4339. + return status;
  4340. +
  4341. + bat->timestamp = jiffies;
  4342. + return 0;
  4343. +}
  4344. +
  4345. +static int spwr_battery_update_bix(struct spwr_battery_device *bat)
  4346. +{
  4347. + int status;
  4348. +
  4349. + mutex_lock(&bat->lock);
  4350. + status = spwr_battery_update_bix_unlocked(bat);
  4351. + mutex_unlock(&bat->lock);
  4352. +
  4353. + return status;
  4354. +}
  4355. +
  4356. +static inline int spwr_ac_update_unlocked(struct spwr_ac_device *ac)
  4357. +{
  4358. + return sam_psy_get_psrc(0x01, 0x01, &ac->state);
  4359. +}
  4360. +
  4361. +static int spwr_ac_update(struct spwr_ac_device *ac)
  4362. +{
  4363. + int status;
  4364. +
  4365. + mutex_lock(&ac->lock);
  4366. + status = spwr_ac_update_unlocked(ac);
  4367. + mutex_unlock(&ac->lock);
  4368. +
  4369. + return status;
  4370. +}
  4371. +
  4372. +
  4373. +static int spwr_battery_recheck(struct spwr_battery_device *bat)
  4374. +{
  4375. + bool present = spwr_battery_present(bat);
  4376. + u32 unit = bat->bix.power_unit;
  4377. + int status;
  4378. +
  4379. + status = spwr_battery_update_bix(bat);
  4380. + if (status)
  4381. + return status;
  4382. +
  4383. + // if battery has been attached, (re-)initialize alarm
  4384. + if (!present && spwr_battery_present(bat)) {
  4385. + status = spwr_battery_set_alarm(bat, bat->bix.design_cap_warn);
  4386. + if (status)
  4387. + return status;
  4388. + }
  4389. +
  4390. + // if the unit has changed, re-add the battery
  4391. + if (unit != bat->bix.power_unit) {
  4392. + spwr_battery_unregister(bat);
  4393. + status = spwr_battery_register(bat, bat->pdev, bat->p);
  4394. + }
  4395. +
  4396. + return status;
  4397. +}
  4398. +
  4399. +
  4400. +static inline int spwr_notify_bix(struct spwr_battery_device *bat)
  4401. +{
  4402. + int status;
  4403. +
  4404. + status = spwr_battery_recheck(bat);
  4405. + if (!status)
  4406. + power_supply_changed(bat->psy);
  4407. +
  4408. + return status;
  4409. +}
  4410. +
  4411. +static inline int spwr_notify_bst(struct spwr_battery_device *bat)
  4412. +{
  4413. + int status;
  4414. +
  4415. + status = spwr_battery_update_bst(bat, false);
  4416. + if (!status)
  4417. + power_supply_changed(bat->psy);
  4418. +
  4419. + return status;
  4420. +}
  4421. +
  4422. +static inline int spwr_notify_adapter_bat(struct spwr_battery_device *bat)
  4423. +{
  4424. + /*
  4425. + * Handle battery update quirk:
  4426. + * When the battery is fully charged and the adapter is plugged in or
  4427. + * removed, the EC does not send a separate event for the state
  4428. + * (charging/discharging) change. Furthermore it may take some time until
  4429. + * the state is updated on the battery. Schedule an update to solve this.
  4430. + */
  4431. +
  4432. + if (bat->bst.remaining_cap >= bat->bix.last_full_charge_cap)
  4433. + schedule_delayed_work(&bat->update_work, SPWR_AC_BAT_UPDATE_DELAY);
  4434. +
  4435. + return 0;
  4436. +}
  4437. +
  4438. +static inline int spwr_notify_adapter_ac(struct spwr_ac_device *ac)
  4439. +{
  4440. + int status;
  4441. +
  4442. + status = spwr_ac_update(ac);
  4443. + if (!status)
  4444. + power_supply_changed(ac->psy);
  4445. +
  4446. + return status;
  4447. +}
  4448. +
  4449. +static u32 spwr_notify_bat(struct ssam_notifier_block *nb, const struct ssam_event *event)
  4450. +{
  4451. + struct spwr_battery_device *bat = container_of(nb, struct spwr_battery_device, notif.base);
  4452. + int status;
  4453. +
  4454. + dev_dbg(&bat->pdev->dev, "power event (cid = 0x%02x, iid = %d, chn = %d)\n",
  4455. + event->command_id, event->instance_id, event->channel);
  4456. +
  4457. + // handled here, needs to be handled for all channels/instances
  4458. + if (event->command_id == SAM_EVENT_PWR_CID_ADAPTER) {
  4459. + status = spwr_notify_adapter_bat(bat);
  4460. + return ssam_notifier_from_errno(status) | SSAM_NOTIF_HANDLED;
  4461. + }
  4462. +
  4463. + // check for the correct channel and instance ID
  4464. + if (event->channel != bat->p->channel)
  4465. + return 0;
  4466. +
  4467. + if (event->instance_id != bat->p->instance)
  4468. + return 0;
  4469. +
  4470. + switch (event->command_id) {
  4471. + case SAM_EVENT_PWR_CID_BIX:
  4472. + status = spwr_notify_bix(bat);
  4473. + break;
  4474. +
  4475. + case SAM_EVENT_PWR_CID_BST:
  4476. + status = spwr_notify_bst(bat);
  4477. + break;
  4478. +
  4479. + default:
  4480. + return 0;
  4481. + }
  4482. +
  4483. + return ssam_notifier_from_errno(status) | SSAM_NOTIF_HANDLED;
  4484. +}
  4485. +
  4486. +static u32 spwr_notify_ac(struct ssam_notifier_block *nb, const struct ssam_event *event)
  4487. +{
  4488. + struct spwr_ac_device *ac = container_of(nb, struct spwr_ac_device, notif.base);
  4489. + int status;
  4490. +
  4491. + dev_dbg(&ac->pdev->dev, "power event (cid = 0x%02x, iid = %d, chn = %d)\n",
  4492. + event->command_id, event->instance_id, event->channel);
  4493. +
  4494. + // AC has IID = 0
  4495. + if (event->instance_id != 0)
  4496. + return 0;
  4497. +
  4498. + switch (event->command_id) {
  4499. + case SAM_EVENT_PWR_CID_ADAPTER:
  4500. + status = spwr_notify_adapter_ac(ac);
  4501. + return ssam_notifier_from_errno(status) | SSAM_NOTIF_HANDLED;
  4502. +
  4503. + default:
  4504. + return 0;
  4505. + }
  4506. +}
  4507. +
  4508. +static void spwr_battery_update_bst_workfn(struct work_struct *work)
  4509. +{
  4510. + struct delayed_work *dwork = to_delayed_work(work);
  4511. + struct spwr_battery_device *bat = container_of(dwork, struct spwr_battery_device, update_work);
  4512. + int status;
  4513. +
  4514. + status = spwr_battery_update_bst(bat, false);
  4515. + if (!status)
  4516. + power_supply_changed(bat->psy);
  4517. +
  4518. + if (status)
  4519. + dev_err(&bat->pdev->dev, "failed to update battery state: %d\n", status);
  4520. +}
  4521. +
  4522. +
  4523. +static inline int spwr_battery_prop_status(struct spwr_battery_device *bat)
  4524. +{
  4525. + if (bat->bst.state & SAM_BATTERY_STATE_DISCHARGING)
  4526. + return POWER_SUPPLY_STATUS_DISCHARGING;
  4527. +
  4528. + if (bat->bst.state & SAM_BATTERY_STATE_CHARGING)
  4529. + return POWER_SUPPLY_STATUS_CHARGING;
  4530. +
  4531. + if (bat->bix.last_full_charge_cap == bat->bst.remaining_cap)
  4532. + return POWER_SUPPLY_STATUS_FULL;
  4533. +
  4534. + if (bat->bst.present_rate == 0)
  4535. + return POWER_SUPPLY_STATUS_NOT_CHARGING;
  4536. +
  4537. + return POWER_SUPPLY_STATUS_UNKNOWN;
  4538. +}
  4539. +
  4540. +static inline int spwr_battery_prop_technology(struct spwr_battery_device *bat)
  4541. +{
  4542. + if (!strcasecmp("NiCd", bat->bix.type))
  4543. + return POWER_SUPPLY_TECHNOLOGY_NiCd;
  4544. +
  4545. + if (!strcasecmp("NiMH", bat->bix.type))
  4546. + return POWER_SUPPLY_TECHNOLOGY_NiMH;
  4547. +
  4548. + if (!strcasecmp("LION", bat->bix.type))
  4549. + return POWER_SUPPLY_TECHNOLOGY_LION;
  4550. +
  4551. + if (!strncasecmp("LI-ION", bat->bix.type, 6))
  4552. + return POWER_SUPPLY_TECHNOLOGY_LION;
  4553. +
  4554. + if (!strcasecmp("LiP", bat->bix.type))
  4555. + return POWER_SUPPLY_TECHNOLOGY_LIPO;
  4556. +
  4557. + return POWER_SUPPLY_TECHNOLOGY_UNKNOWN;
  4558. +}
  4559. +
  4560. +static inline int spwr_battery_prop_capacity(struct spwr_battery_device *bat)
  4561. +{
  4562. + if (bat->bst.remaining_cap && bat->bix.last_full_charge_cap)
  4563. + return bat->bst.remaining_cap * 100 / bat->bix.last_full_charge_cap;
  4564. + else
  4565. + return 0;
  4566. +}
  4567. +
  4568. +static inline int spwr_battery_prop_capacity_level(struct spwr_battery_device *bat)
  4569. +{
  4570. + if (bat->bst.state & SAM_BATTERY_STATE_CRITICAL)
  4571. + return POWER_SUPPLY_CAPACITY_LEVEL_CRITICAL;
  4572. +
  4573. + if (bat->bst.remaining_cap >= bat->bix.last_full_charge_cap)
  4574. + return POWER_SUPPLY_CAPACITY_LEVEL_FULL;
  4575. +
  4576. + if (bat->bst.remaining_cap <= bat->alarm)
  4577. + return POWER_SUPPLY_CAPACITY_LEVEL_LOW;
  4578. +
  4579. + return POWER_SUPPLY_CAPACITY_LEVEL_NORMAL;
  4580. +}
  4581. +
  4582. +static int spwr_ac_get_property(struct power_supply *psy,
  4583. + enum power_supply_property psp,
  4584. + union power_supply_propval *val)
  4585. +{
  4586. + struct spwr_ac_device *ac = power_supply_get_drvdata(psy);
  4587. + int status;
  4588. +
  4589. + mutex_lock(&ac->lock);
  4590. +
  4591. + status = spwr_ac_update_unlocked(ac);
  4592. + if (status)
  4593. + goto out;
  4594. +
  4595. + switch (psp) {
  4596. + case POWER_SUPPLY_PROP_ONLINE:
  4597. + val->intval = ac->state == 1;
  4598. + break;
  4599. +
  4600. + default:
  4601. + status = -EINVAL;
  4602. + goto out;
  4603. + }
  4604. +
  4605. +out:
  4606. + mutex_unlock(&ac->lock);
  4607. + return status;
  4608. +}
  4609. +
  4610. +static int spwr_battery_get_property(struct power_supply *psy,
  4611. + enum power_supply_property psp,
  4612. + union power_supply_propval *val)
  4613. +{
  4614. + struct spwr_battery_device *bat = power_supply_get_drvdata(psy);
  4615. + int status;
  4616. +
  4617. + mutex_lock(&bat->lock);
  4618. +
  4619. + status = spwr_battery_update_bst_unlocked(bat, true);
  4620. + if (status)
  4621. + goto out;
  4622. +
  4623. + // abort if battery is not present
  4624. + if (!spwr_battery_present(bat) && psp != POWER_SUPPLY_PROP_PRESENT) {
  4625. + status = -ENODEV;
  4626. + goto out;
  4627. + }
  4628. +
  4629. + switch (psp) {
  4630. + case POWER_SUPPLY_PROP_STATUS:
  4631. + val->intval = spwr_battery_prop_status(bat);
  4632. + break;
  4633. +
  4634. + case POWER_SUPPLY_PROP_PRESENT:
  4635. + val->intval = spwr_battery_present(bat);
  4636. + break;
  4637. +
  4638. + case POWER_SUPPLY_PROP_TECHNOLOGY:
  4639. + val->intval = spwr_battery_prop_technology(bat);
  4640. + break;
  4641. +
  4642. + case POWER_SUPPLY_PROP_CYCLE_COUNT:
  4643. + val->intval = bat->bix.cycle_count;
  4644. + break;
  4645. +
  4646. + case POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN:
  4647. + val->intval = bat->bix.design_voltage * 1000;
  4648. + break;
  4649. +
  4650. + case POWER_SUPPLY_PROP_VOLTAGE_NOW:
  4651. + val->intval = bat->bst.present_voltage * 1000;
  4652. + break;
  4653. +
  4654. + case POWER_SUPPLY_PROP_CURRENT_NOW:
  4655. + case POWER_SUPPLY_PROP_POWER_NOW:
  4656. + val->intval = bat->bst.present_rate * 1000;
  4657. + break;
  4658. +
  4659. + case POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN:
  4660. + case POWER_SUPPLY_PROP_ENERGY_FULL_DESIGN:
  4661. + val->intval = bat->bix.design_cap * 1000;
  4662. + break;
  4663. +
  4664. + case POWER_SUPPLY_PROP_CHARGE_FULL:
  4665. + case POWER_SUPPLY_PROP_ENERGY_FULL:
  4666. + val->intval = bat->bix.last_full_charge_cap * 1000;
  4667. + break;
  4668. +
  4669. + case POWER_SUPPLY_PROP_CHARGE_NOW:
  4670. + case POWER_SUPPLY_PROP_ENERGY_NOW:
  4671. + val->intval = bat->bst.remaining_cap * 1000;
  4672. + break;
  4673. +
  4674. + case POWER_SUPPLY_PROP_CAPACITY:
  4675. + val->intval = spwr_battery_prop_capacity(bat);
  4676. + break;
  4677. +
  4678. + case POWER_SUPPLY_PROP_CAPACITY_LEVEL:
  4679. + val->intval = spwr_battery_prop_capacity_level(bat);
  4680. + break;
  4681. +
  4682. + case POWER_SUPPLY_PROP_MODEL_NAME:
  4683. + val->strval = bat->bix.model;
  4684. + break;
  4685. +
  4686. + case POWER_SUPPLY_PROP_MANUFACTURER:
  4687. + val->strval = bat->bix.oem_info;
  4688. + break;
  4689. +
  4690. + case POWER_SUPPLY_PROP_SERIAL_NUMBER:
  4691. + val->strval = bat->bix.serial;
  4692. + break;
  4693. +
  4694. + default:
  4695. + status = -EINVAL;
  4696. + goto out;
  4697. + }
  4698. +
  4699. +out:
  4700. + mutex_unlock(&bat->lock);
  4701. + return status;
  4702. +}
  4703. +
  4704. +
  4705. +static ssize_t spwr_battery_alarm_show(struct device *dev,
  4706. + struct device_attribute *attr,
  4707. + char *buf)
  4708. +{
  4709. + struct power_supply *psy = dev_get_drvdata(dev);
  4710. + struct spwr_battery_device *bat = power_supply_get_drvdata(psy);
  4711. +
  4712. + return sprintf(buf, "%d\n", bat->alarm * 1000);
  4713. +}
  4714. +
  4715. +static ssize_t spwr_battery_alarm_store(struct device *dev,
  4716. + struct device_attribute *attr,
  4717. + const char *buf, size_t count)
  4718. +{
  4719. + struct power_supply *psy = dev_get_drvdata(dev);
  4720. + struct spwr_battery_device *bat = power_supply_get_drvdata(psy);
  4721. + unsigned long value;
  4722. + int status;
  4723. +
  4724. + status = kstrtoul(buf, 0, &value);
  4725. + if (status)
  4726. + return status;
  4727. +
  4728. + if (!spwr_battery_present(bat))
  4729. + return -ENODEV;
  4730. +
  4731. + status = spwr_battery_set_alarm(bat, value / 1000);
  4732. + if (status)
  4733. + return status;
  4734. +
  4735. + return count;
  4736. +}
  4737. +
  4738. +static const struct device_attribute alarm_attr = {
  4739. + .attr = {.name = "alarm", .mode = 0644},
  4740. + .show = spwr_battery_alarm_show,
  4741. + .store = spwr_battery_alarm_store,
  4742. +};
  4743. +
  4744. +
  4745. +static int spwr_ac_register(struct spwr_ac_device *ac, struct platform_device *pdev)
  4746. +{
  4747. + struct power_supply_config psy_cfg = {};
  4748. + u32 sta;
  4749. + int status;
  4750. +
  4751. + // make sure the device is there and functioning properly
  4752. + status = sam_psy_get_sta(0x01, 0x01, &sta);
  4753. + if (status)
  4754. + return status;
  4755. +
  4756. + if ((sta & SAM_BATTERY_STA_OK) != SAM_BATTERY_STA_OK)
  4757. + return -ENODEV;
  4758. +
  4759. + psy_cfg.drv_data = ac;
  4760. +
  4761. + ac->pdev = pdev;
  4762. + mutex_init(&ac->lock);
  4763. +
  4764. + snprintf(ac->name, ARRAY_SIZE(ac->name), "ADP0");
  4765. +
  4766. + ac->psy_desc.name = ac->name;
  4767. + ac->psy_desc.type = POWER_SUPPLY_TYPE_MAINS;
  4768. + ac->psy_desc.properties = spwr_ac_props;
  4769. + ac->psy_desc.num_properties = ARRAY_SIZE(spwr_ac_props);
  4770. + ac->psy_desc.get_property = spwr_ac_get_property;
  4771. +
  4772. + ac->psy = power_supply_register(&ac->pdev->dev, &ac->psy_desc, &psy_cfg);
  4773. + if (IS_ERR(ac->psy)) {
  4774. + status = PTR_ERR(ac->psy);
  4775. + goto err_psy;
  4776. + }
  4777. +
  4778. + ac->notif.base.priority = 1;
  4779. + ac->notif.base.fn = spwr_notify_ac;
  4780. + ac->notif.event.reg = SSAM_EVENT_REGISTRY_SAM;
  4781. + ac->notif.event.id.target_category = SSAM_SSH_TC_BAT;
  4782. + ac->notif.event.id.instance = 0;
  4783. + ac->notif.event.flags = SSAM_EVENT_SEQUENCED;
  4784. +
  4785. + status = surface_sam_ssh_notifier_register(&ac->notif);
  4786. + if (status)
  4787. + goto err_notif;
  4788. +
  4789. + return 0;
  4790. +
  4791. +err_notif:
  4792. + power_supply_unregister(ac->psy);
  4793. +err_psy:
  4794. + mutex_destroy(&ac->lock);
  4795. + return status;
  4796. +}
  4797. +
  4798. +static int spwr_ac_unregister(struct spwr_ac_device *ac)
  4799. +{
  4800. + surface_sam_ssh_notifier_unregister(&ac->notif);
  4801. + power_supply_unregister(ac->psy);
  4802. + mutex_destroy(&ac->lock);
  4803. + return 0;
  4804. +}
  4805. +
  4806. +static int spwr_battery_register(struct spwr_battery_device *bat,
  4807. + struct platform_device *pdev,
  4808. + const struct ssam_battery_properties *p)
  4809. +{
  4810. + struct power_supply_config psy_cfg = {};
  4811. + u32 sta;
  4812. + int status;
  4813. +
  4814. + bat->pdev = pdev;
  4815. + bat->p = p;
  4816. +
  4817. + // make sure the device is there and functioning properly
  4818. + status = sam_psy_get_sta(bat->p->channel, bat->p->instance, &sta);
  4819. + if (status)
  4820. + return status;
  4821. +
  4822. + if ((sta & SAM_BATTERY_STA_OK) != SAM_BATTERY_STA_OK)
  4823. + return -ENODEV;
  4824. +
  4825. + status = spwr_battery_update_bix_unlocked(bat);
  4826. + if (status)
  4827. + return status;
  4828. +
  4829. + if (spwr_battery_present(bat)) {
  4830. + status = spwr_battery_set_alarm_unlocked(bat, bat->bix.design_cap_warn);
  4831. + if (status)
  4832. + return status;
  4833. + }
  4834. +
  4835. + snprintf(bat->name, ARRAY_SIZE(bat->name), "BAT%d", bat->p->num);
  4836. + bat->psy_desc.name = bat->name;
  4837. + bat->psy_desc.type = POWER_SUPPLY_TYPE_BATTERY;
  4838. +
  4839. + if (bat->bix.power_unit == SAM_BATTERY_POWER_UNIT_MA) {
  4840. + bat->psy_desc.properties = spwr_battery_props_chg;
  4841. + bat->psy_desc.num_properties = ARRAY_SIZE(spwr_battery_props_chg);
  4842. + } else {
  4843. + bat->psy_desc.properties = spwr_battery_props_eng;
  4844. + bat->psy_desc.num_properties = ARRAY_SIZE(spwr_battery_props_eng);
  4845. + }
  4846. +
  4847. + bat->psy_desc.get_property = spwr_battery_get_property;
  4848. +
  4849. + mutex_init(&bat->lock);
  4850. + psy_cfg.drv_data = bat;
  4851. +
  4852. + INIT_DELAYED_WORK(&bat->update_work, spwr_battery_update_bst_workfn);
  4853. +
  4854. + bat->psy = power_supply_register(&bat->pdev->dev, &bat->psy_desc, &psy_cfg);
  4855. + if (IS_ERR(bat->psy)) {
  4856. + status = PTR_ERR(bat->psy);
  4857. + goto err_psy;
  4858. + }
  4859. +
  4860. + bat->notif.base.priority = 1;
  4861. + bat->notif.base.fn = spwr_notify_bat;
  4862. + bat->notif.event.reg = p->registry;
  4863. + bat->notif.event.id.target_category = SSAM_SSH_TC_BAT;
  4864. + bat->notif.event.id.instance = 0;
  4865. + bat->notif.event.flags = SSAM_EVENT_SEQUENCED;
  4866. +
  4867. + status = surface_sam_ssh_notifier_register(&bat->notif);
  4868. + if (status)
  4869. + goto err_notif;
  4870. +
  4871. + status = device_create_file(&bat->psy->dev, &alarm_attr);
  4872. + if (status)
  4873. + goto err_file;
  4874. +
  4875. + return 0;
  4876. +
  4877. +err_file:
  4878. + surface_sam_ssh_notifier_unregister(&bat->notif);
  4879. +err_notif:
  4880. + power_supply_unregister(bat->psy);
  4881. +err_psy:
  4882. + mutex_destroy(&bat->lock);
  4883. + return status;
  4884. +}
  4885. +
  4886. +static void spwr_battery_unregister(struct spwr_battery_device *bat)
  4887. +{
  4888. + surface_sam_ssh_notifier_unregister(&bat->notif);
  4889. + cancel_delayed_work_sync(&bat->update_work);
  4890. + device_remove_file(&bat->psy->dev, &alarm_attr);
  4891. + power_supply_unregister(bat->psy);
  4892. + mutex_destroy(&bat->lock);
  4893. +}
  4894. +
  4895. +
  4896. +/*
  4897. + * Battery Driver.
  4898. + */
  4899. +
  4900. +#ifdef CONFIG_PM_SLEEP
  4901. +static int surface_sam_sid_battery_resume(struct device *dev)
  4902. +{
  4903. + struct spwr_battery_device *bat;
  4904. +
  4905. + bat = dev_get_drvdata(dev);
  4906. + return spwr_battery_recheck(bat);
  4907. +}
  4908. +#else
  4909. +#define surface_sam_sid_battery_resume NULL
  4910. +#endif
  4911. +
  4912. +SIMPLE_DEV_PM_OPS(surface_sam_sid_battery_pm, NULL, surface_sam_sid_battery_resume);
  4913. +
  4914. +static int surface_sam_sid_battery_probe(struct platform_device *pdev)
  4915. +{
  4916. + struct spwr_battery_device *bat;
  4917. + int status;
  4918. +
  4919. + // link to ec
  4920. + status = surface_sam_ssh_consumer_register(&pdev->dev);
  4921. + if (status)
  4922. + return status == -ENXIO ? -EPROBE_DEFER : status;
  4923. +
  4924. + bat = devm_kzalloc(&pdev->dev, sizeof(struct spwr_battery_device), GFP_KERNEL);
  4925. + if (!bat)
  4926. + return -ENOMEM;
  4927. +
  4928. + platform_set_drvdata(pdev, bat);
  4929. + return spwr_battery_register(bat, pdev, pdev->dev.platform_data);
  4930. +}
  4931. +
  4932. +static int surface_sam_sid_battery_remove(struct platform_device *pdev)
  4933. +{
  4934. + struct spwr_battery_device *bat;
  4935. +
  4936. + bat = platform_get_drvdata(pdev);
  4937. + spwr_battery_unregister(bat);
  4938. +
  4939. + return 0;
  4940. +}
  4941. +
  4942. +static struct platform_driver surface_sam_sid_battery = {
  4943. + .probe = surface_sam_sid_battery_probe,
  4944. + .remove = surface_sam_sid_battery_remove,
  4945. + .driver = {
  4946. + .name = "surface_sam_sid_battery",
  4947. + .pm = &surface_sam_sid_battery_pm,
  4948. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  4949. + },
  4950. +};
  4951. +
  4952. +
  4953. +/*
  4954. + * AC Driver.
  4955. + */
  4956. +
  4957. +static int surface_sam_sid_ac_probe(struct platform_device *pdev)
  4958. +{
  4959. + int status;
  4960. + struct spwr_ac_device *ac;
  4961. +
  4962. + // link to ec
  4963. + status = surface_sam_ssh_consumer_register(&pdev->dev);
  4964. + if (status)
  4965. + return status == -ENXIO ? -EPROBE_DEFER : status;
  4966. +
  4967. + ac = devm_kzalloc(&pdev->dev, sizeof(struct spwr_ac_device), GFP_KERNEL);
  4968. + if (!ac)
  4969. + return -ENOMEM;
  4970. +
  4971. + status = spwr_ac_register(ac, pdev);
  4972. + if (status)
  4973. + return status;
  4974. +
  4975. + platform_set_drvdata(pdev, ac);
  4976. + return 0;
  4977. +}
  4978. +
  4979. +static int surface_sam_sid_ac_remove(struct platform_device *pdev)
  4980. +{
  4981. + struct spwr_ac_device *ac;
  4982. +
  4983. + ac = platform_get_drvdata(pdev);
  4984. + return spwr_ac_unregister(ac);
  4985. +}
  4986. +
  4987. +static struct platform_driver surface_sam_sid_ac = {
  4988. + .probe = surface_sam_sid_ac_probe,
  4989. + .remove = surface_sam_sid_ac_remove,
  4990. + .driver = {
  4991. + .name = "surface_sam_sid_ac",
  4992. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  4993. + },
  4994. +};
  4995. +
  4996. +
  4997. +static int __init surface_sam_sid_power_init(void)
  4998. +{
  4999. + int status;
  5000. +
  5001. + status = platform_driver_register(&surface_sam_sid_battery);
  5002. + if (status)
  5003. + return status;
  5004. +
  5005. + status = platform_driver_register(&surface_sam_sid_ac);
  5006. + if (status) {
  5007. + platform_driver_unregister(&surface_sam_sid_battery);
  5008. + return status;
  5009. + }
  5010. +
  5011. + return 0;
  5012. +}
  5013. +
  5014. +static void __exit surface_sam_sid_power_exit(void)
  5015. +{
  5016. + platform_driver_unregister(&surface_sam_sid_battery);
  5017. + platform_driver_unregister(&surface_sam_sid_ac);
  5018. +}
  5019. +
  5020. +module_init(surface_sam_sid_power_init);
  5021. +module_exit(surface_sam_sid_power_exit);
  5022. +
  5023. +MODULE_AUTHOR("Maximilian Luz <luzmaximilian@gmail.com>");
  5024. +MODULE_DESCRIPTION("Surface Battery/AC Driver for 7th Generation Surface Devices");
  5025. +MODULE_LICENSE("GPL");
  5026. +MODULE_ALIAS("platform:surface_sam_sid_ac");
  5027. +MODULE_ALIAS("platform:surface_sam_sid_battery");
  5028. diff --git a/drivers/platform/x86/surface_sam/surface_sam_sid_power.h b/drivers/platform/x86/surface_sam/surface_sam_sid_power.h
  5029. new file mode 100644
  5030. index 000000000000..2e8f212086e1
  5031. --- /dev/null
  5032. +++ b/drivers/platform/x86/surface_sam/surface_sam_sid_power.h
  5033. @@ -0,0 +1,15 @@
  5034. +#ifndef _SURFACE_SAM_SID_POWER_H
  5035. +#define _SURFACE_SAM_SID_POWER_H
  5036. +
  5037. +#include <linux/types.h>
  5038. +#include "surface_sam_ssh.h"
  5039. +
  5040. +
  5041. +struct ssam_battery_properties {
  5042. + struct ssam_event_registry registry;
  5043. + u8 num;
  5044. + u8 channel;
  5045. + u8 instance;
  5046. +};
  5047. +
  5048. +#endif /* _SURFACE_SAM_SID_POWER_H */
  5049. diff --git a/drivers/platform/x86/surface_sam/surface_sam_sid_vhf.c b/drivers/platform/x86/surface_sam/surface_sam_sid_vhf.c
  5050. new file mode 100644
  5051. index 000000000000..474221097eaf
  5052. --- /dev/null
  5053. +++ b/drivers/platform/x86/surface_sam/surface_sam_sid_vhf.c
  5054. @@ -0,0 +1,432 @@
  5055. +// SPDX-License-Identifier: GPL-2.0-or-later
  5056. +/*
  5057. + * Microsofs Surface HID (VHF) driver for HID input events via SAM.
  5058. + * Used for keyboard input events on the 7th generation Surface Laptops.
  5059. + */
  5060. +
  5061. +#include <linux/acpi.h>
  5062. +#include <linux/hid.h>
  5063. +#include <linux/input.h>
  5064. +#include <linux/platform_device.h>
  5065. +#include <linux/types.h>
  5066. +
  5067. +#include "surface_sam_ssh.h"
  5068. +#include "surface_sam_sid_vhf.h"
  5069. +
  5070. +#define SID_VHF_INPUT_NAME "Microsoft Surface HID"
  5071. +
  5072. +#define SAM_EVENT_SID_VHF_TC 0x15
  5073. +
  5074. +#define VHF_HID_STARTED 0
  5075. +
  5076. +struct sid_vhf {
  5077. + const struct ssam_hid_properties *p;
  5078. + struct platform_device *dev;
  5079. + struct hid_device *hid;
  5080. + struct ssam_event_notifier notif;
  5081. + unsigned long state;
  5082. +};
  5083. +
  5084. +
  5085. +static int sid_vhf_hid_start(struct hid_device *hid)
  5086. +{
  5087. + hid_dbg(hid, "%s\n", __func__);
  5088. + return 0;
  5089. +}
  5090. +
  5091. +static void sid_vhf_hid_stop(struct hid_device *hid)
  5092. +{
  5093. + hid_dbg(hid, "%s\n", __func__);
  5094. +}
  5095. +
  5096. +static int sid_vhf_hid_open(struct hid_device *hid)
  5097. +{
  5098. + struct sid_vhf *vhf = dev_get_drvdata(hid->dev.parent);
  5099. +
  5100. + hid_dbg(hid, "%s\n", __func__);
  5101. +
  5102. + set_bit(VHF_HID_STARTED, &vhf->state);
  5103. + return 0;
  5104. +}
  5105. +
  5106. +static void sid_vhf_hid_close(struct hid_device *hid)
  5107. +{
  5108. +
  5109. + struct sid_vhf *vhf = dev_get_drvdata(hid->dev.parent);
  5110. +
  5111. + hid_dbg(hid, "%s\n", __func__);
  5112. +
  5113. + clear_bit(VHF_HID_STARTED, &vhf->state);
  5114. +}
  5115. +
  5116. +struct surface_sam_sid_vhf_meta_rqst {
  5117. + u8 id;
  5118. + u32 offset;
  5119. + u32 length; // buffer limit on send, length of data received on receive
  5120. + u8 end; // 0x01 if end was reached
  5121. +} __packed;
  5122. +
  5123. +struct vhf_device_metadata_info {
  5124. + u8 len;
  5125. + u8 _2;
  5126. + u8 _3;
  5127. + u8 _4;
  5128. + u8 _5;
  5129. + u8 _6;
  5130. + u8 _7;
  5131. + u16 hid_len; // hid descriptor length
  5132. +} __packed;
  5133. +
  5134. +struct vhf_device_metadata {
  5135. + u32 len;
  5136. + u16 vendor_id;
  5137. + u16 product_id;
  5138. + u8 _1[24];
  5139. +} __packed;
  5140. +
  5141. +union vhf_buffer_data {
  5142. + struct vhf_device_metadata_info info;
  5143. + u8 pld[0x76];
  5144. + struct vhf_device_metadata meta;
  5145. +};
  5146. +
  5147. +struct surface_sam_sid_vhf_meta_resp {
  5148. + struct surface_sam_sid_vhf_meta_rqst rqst;
  5149. + union vhf_buffer_data data;
  5150. +} __packed;
  5151. +
  5152. +
  5153. +static int vhf_get_metadata(u8 iid, struct vhf_device_metadata *meta)
  5154. +{
  5155. + int status;
  5156. +
  5157. + struct surface_sam_sid_vhf_meta_resp resp = {
  5158. + .rqst = {
  5159. + .id = 2,
  5160. + .offset = 0,
  5161. + .length = 0x76,
  5162. + .end = 0
  5163. + }
  5164. + };
  5165. +
  5166. + struct surface_sam_ssh_rqst rqst = {
  5167. + .tc = 0x15,
  5168. + .cid = 0x04,
  5169. + .iid = iid,
  5170. + .chn = 0x02,
  5171. + .snc = 0x01,
  5172. + .cdl = sizeof(struct surface_sam_sid_vhf_meta_rqst),
  5173. + .pld = (u8 *)&resp.rqst,
  5174. + };
  5175. +
  5176. + struct surface_sam_ssh_buf result = {
  5177. + .cap = sizeof(struct surface_sam_sid_vhf_meta_resp),
  5178. + .len = 0,
  5179. + .data = (u8 *)&resp,
  5180. + };
  5181. +
  5182. + status = surface_sam_ssh_rqst(&rqst, &result);
  5183. + if (status)
  5184. + return status;
  5185. +
  5186. + *meta = resp.data.meta;
  5187. +
  5188. + return 0;
  5189. +}
  5190. +
  5191. +static int vhf_get_hid_descriptor(struct hid_device *hid, u8 iid, u8 **desc, int *size)
  5192. +{
  5193. + int status, len;
  5194. + u8 *buf;
  5195. +
  5196. + struct surface_sam_sid_vhf_meta_resp resp = {
  5197. + .rqst = {
  5198. + .id = 0,
  5199. + .offset = 0,
  5200. + .length = 0x76,
  5201. + .end = 0,
  5202. + }
  5203. + };
  5204. +
  5205. + struct surface_sam_ssh_rqst rqst = {
  5206. + .tc = 0x15,
  5207. + .cid = 0x04,
  5208. + .iid = iid,
  5209. + .chn = 0x02,
  5210. + .snc = 0x01,
  5211. + .cdl = sizeof(struct surface_sam_sid_vhf_meta_rqst),
  5212. + .pld = (u8 *)&resp.rqst,
  5213. + };
  5214. +
  5215. + struct surface_sam_ssh_buf result = {
  5216. + .cap = sizeof(struct surface_sam_sid_vhf_meta_resp),
  5217. + .len = 0,
  5218. + .data = (u8 *)&resp,
  5219. + };
  5220. +
  5221. + // first fetch 00 to get the total length
  5222. + status = surface_sam_ssh_rqst(&rqst, &result);
  5223. + if (status)
  5224. + return status;
  5225. +
  5226. + len = resp.data.info.hid_len;
  5227. +
  5228. + // allocate a buffer for the descriptor
  5229. + buf = kzalloc(len, GFP_KERNEL);
  5230. +
  5231. + // then, iterate and write into buffer, copying out bytes
  5232. + resp.rqst.id = 1;
  5233. + resp.rqst.offset = 0;
  5234. + resp.rqst.length = 0x76;
  5235. + resp.rqst.end = 0;
  5236. +
  5237. + while (!resp.rqst.end && resp.rqst.offset < len) {
  5238. + status = surface_sam_ssh_rqst(&rqst, &result);
  5239. + if (status) {
  5240. + kfree(buf);
  5241. + return status;
  5242. + }
  5243. + memcpy(buf + resp.rqst.offset, resp.data.pld, resp.rqst.length);
  5244. +
  5245. + resp.rqst.offset += resp.rqst.length;
  5246. + }
  5247. +
  5248. + *desc = buf;
  5249. + *size = len;
  5250. +
  5251. + return 0;
  5252. +}
  5253. +
  5254. +static int sid_vhf_hid_parse(struct hid_device *hid)
  5255. +{
  5256. + struct sid_vhf *vhf = dev_get_drvdata(hid->dev.parent);
  5257. + int ret = 0, size;
  5258. + u8 *buf;
  5259. +
  5260. + ret = vhf_get_hid_descriptor(hid, vhf->p->instance, &buf, &size);
  5261. + if (ret != 0) {
  5262. + hid_err(hid, "Failed to read HID descriptor from device: %d\n", ret);
  5263. + return -EIO;
  5264. + }
  5265. + hid_dbg(hid, "HID descriptor of device:");
  5266. + print_hex_dump_debug("descriptor:", DUMP_PREFIX_OFFSET, 16, 1, buf, size, false);
  5267. +
  5268. + ret = hid_parse_report(hid, buf, size);
  5269. + kfree(buf);
  5270. + return ret;
  5271. +
  5272. +}
  5273. +
  5274. +static int sid_vhf_hid_raw_request(struct hid_device *hid, unsigned char
  5275. + reportnum, u8 *buf, size_t len, unsigned char rtype, int
  5276. + reqtype)
  5277. +{
  5278. + struct sid_vhf *vhf = dev_get_drvdata(hid->dev.parent);
  5279. + int status;
  5280. + u8 cid;
  5281. + struct surface_sam_ssh_rqst rqst = {};
  5282. + struct surface_sam_ssh_buf result = {};
  5283. +
  5284. + hid_dbg(hid, "%s: reportnum=%#04x rtype=%i reqtype=%i\n", __func__, reportnum, rtype, reqtype);
  5285. + print_hex_dump_debug("report:", DUMP_PREFIX_OFFSET, 16, 1, buf, len, false);
  5286. +
  5287. + // Byte 0 is the report number. Report data starts at byte 1.
  5288. + buf[0] = reportnum;
  5289. +
  5290. + switch (rtype) {
  5291. + case HID_OUTPUT_REPORT:
  5292. + cid = 0x01;
  5293. + break;
  5294. + case HID_FEATURE_REPORT:
  5295. + switch (reqtype) {
  5296. + case HID_REQ_GET_REPORT:
  5297. + // The EC doesn't respond to GET FEATURE for these touchpad reports
  5298. + // we immediately discard to avoid waiting for a timeout.
  5299. + if (reportnum == 6 || reportnum == 7 || reportnum == 8 || reportnum == 9 || reportnum == 0x0b) {
  5300. + hid_dbg(hid, "%s: skipping get feature report for 0x%02x\n", __func__, reportnum);
  5301. + return 0;
  5302. + }
  5303. +
  5304. + cid = 0x02;
  5305. + break;
  5306. + case HID_REQ_SET_REPORT:
  5307. + cid = 0x03;
  5308. + break;
  5309. + default:
  5310. + hid_err(hid, "%s: unknown req type 0x%02x\n", __func__, rtype);
  5311. + return -EIO;
  5312. + }
  5313. + break;
  5314. + default:
  5315. + hid_err(hid, "%s: unknown report type 0x%02x\n", __func__, reportnum);
  5316. + return -EIO;
  5317. + }
  5318. +
  5319. + rqst.tc = SAM_EVENT_SID_VHF_TC;
  5320. + rqst.chn = 0x02;
  5321. + rqst.iid = vhf->p->instance;
  5322. + rqst.cid = cid;
  5323. + rqst.snc = reqtype == HID_REQ_GET_REPORT ? 0x01 : 0x00;
  5324. + rqst.cdl = reqtype == HID_REQ_GET_REPORT ? 0x01 : len;
  5325. + rqst.pld = buf;
  5326. +
  5327. + result.cap = len;
  5328. + result.len = 0;
  5329. + result.data = buf;
  5330. +
  5331. + hid_dbg(hid, "%s: sending to cid=%#04x snc=%#04x\n", __func__, cid, HID_REQ_GET_REPORT == reqtype);
  5332. +
  5333. + status = surface_sam_ssh_rqst(&rqst, &result);
  5334. + hid_dbg(hid, "%s: status %i\n", __func__, status);
  5335. +
  5336. + if (status)
  5337. + return status;
  5338. +
  5339. + if (result.len > 0)
  5340. + print_hex_dump_debug("response:", DUMP_PREFIX_OFFSET, 16, 1, result.data, result.len, false);
  5341. +
  5342. + return result.len;
  5343. +}
  5344. +
  5345. +static struct hid_ll_driver sid_vhf_hid_ll_driver = {
  5346. + .start = sid_vhf_hid_start,
  5347. + .stop = sid_vhf_hid_stop,
  5348. + .open = sid_vhf_hid_open,
  5349. + .close = sid_vhf_hid_close,
  5350. + .parse = sid_vhf_hid_parse,
  5351. + .raw_request = sid_vhf_hid_raw_request,
  5352. +};
  5353. +
  5354. +
  5355. +static struct hid_device *sid_vhf_create_hid_device(struct platform_device *pdev, struct vhf_device_metadata *meta)
  5356. +{
  5357. + struct hid_device *hid;
  5358. +
  5359. + hid = hid_allocate_device();
  5360. + if (IS_ERR(hid))
  5361. + return hid;
  5362. +
  5363. + hid->dev.parent = &pdev->dev;
  5364. +
  5365. + hid->bus = BUS_VIRTUAL;
  5366. + hid->vendor = meta->vendor_id;
  5367. + hid->product = meta->product_id;
  5368. +
  5369. + hid->ll_driver = &sid_vhf_hid_ll_driver;
  5370. +
  5371. + sprintf(hid->name, "%s", SID_VHF_INPUT_NAME);
  5372. +
  5373. + return hid;
  5374. +}
  5375. +
  5376. +static u32 sid_vhf_event_handler(struct ssam_notifier_block *nb, const struct ssam_event *event)
  5377. +{
  5378. + struct sid_vhf *vhf = container_of(nb, struct sid_vhf, notif.base);
  5379. + int status;
  5380. +
  5381. + if (event->target_category != SSAM_SSH_TC_HID)
  5382. + return 0;
  5383. +
  5384. + if (event->channel != 0x02)
  5385. + return 0;
  5386. +
  5387. + if (event->instance_id != vhf->p->instance)
  5388. + return 0;
  5389. +
  5390. + if (event->command_id != 0x00 && event->command_id != 0x03 && event->command_id != 0x04)
  5391. + return 0;
  5392. +
  5393. + // skip if HID hasn't started yet
  5394. + if (!test_bit(VHF_HID_STARTED, &vhf->state))
  5395. + return SSAM_NOTIF_HANDLED;
  5396. +
  5397. + status = hid_input_report(vhf->hid, HID_INPUT_REPORT, (u8 *)&event->data[0], event->length, 0);
  5398. + return ssam_notifier_from_errno(status) | SSAM_NOTIF_HANDLED;
  5399. +}
  5400. +
  5401. +static int surface_sam_sid_vhf_probe(struct platform_device *pdev)
  5402. +{
  5403. + const struct ssam_hid_properties *p = pdev->dev.platform_data;
  5404. + struct sid_vhf *vhf;
  5405. + struct vhf_device_metadata meta = {};
  5406. + struct hid_device *hid;
  5407. + int status;
  5408. +
  5409. + // add device link to EC
  5410. + status = surface_sam_ssh_consumer_register(&pdev->dev);
  5411. + if (status)
  5412. + return status == -ENXIO ? -EPROBE_DEFER : status;
  5413. +
  5414. + vhf = kzalloc(sizeof(struct sid_vhf), GFP_KERNEL);
  5415. + if (!vhf)
  5416. + return -ENOMEM;
  5417. +
  5418. + status = vhf_get_metadata(p->instance, &meta);
  5419. + if (status)
  5420. + goto err_create_hid;
  5421. +
  5422. + hid = sid_vhf_create_hid_device(pdev, &meta);
  5423. + if (IS_ERR(hid)) {
  5424. + status = PTR_ERR(hid);
  5425. + goto err_create_hid;
  5426. + }
  5427. +
  5428. + vhf->p = pdev->dev.platform_data;
  5429. + vhf->dev = pdev;
  5430. + vhf->hid = hid;
  5431. +
  5432. + vhf->notif.base.priority = 1;
  5433. + vhf->notif.base.fn = sid_vhf_event_handler;
  5434. + vhf->notif.event.reg = p->registry;
  5435. + vhf->notif.event.id.target_category = SSAM_SSH_TC_HID;
  5436. + vhf->notif.event.id.instance = p->instance;
  5437. + vhf->notif.event.flags = 0;
  5438. +
  5439. + platform_set_drvdata(pdev, vhf);
  5440. +
  5441. + status = surface_sam_ssh_notifier_register(&vhf->notif);
  5442. + if (status)
  5443. + goto err_notif;
  5444. +
  5445. + status = hid_add_device(hid);
  5446. + if (status)
  5447. + goto err_add_hid;
  5448. +
  5449. + return 0;
  5450. +
  5451. +err_add_hid:
  5452. + surface_sam_ssh_notifier_unregister(&vhf->notif);
  5453. +err_notif:
  5454. + hid_destroy_device(hid);
  5455. + platform_set_drvdata(pdev, NULL);
  5456. +err_create_hid:
  5457. + kfree(vhf);
  5458. + return status;
  5459. +}
  5460. +
  5461. +static int surface_sam_sid_vhf_remove(struct platform_device *pdev)
  5462. +{
  5463. + struct sid_vhf *vhf = platform_get_drvdata(pdev);
  5464. +
  5465. + surface_sam_ssh_notifier_unregister(&vhf->notif);
  5466. + hid_destroy_device(vhf->hid);
  5467. + kfree(vhf);
  5468. +
  5469. + platform_set_drvdata(pdev, NULL);
  5470. + return 0;
  5471. +}
  5472. +
  5473. +static struct platform_driver surface_sam_sid_vhf = {
  5474. + .probe = surface_sam_sid_vhf_probe,
  5475. + .remove = surface_sam_sid_vhf_remove,
  5476. + .driver = {
  5477. + .name = "surface_sam_sid_vhf",
  5478. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  5479. + },
  5480. +};
  5481. +module_platform_driver(surface_sam_sid_vhf);
  5482. +
  5483. +MODULE_AUTHOR("Blaž Hrastnik <blaz@mxxn.io>");
  5484. +MODULE_DESCRIPTION("Driver for HID devices connected via Surface SAM");
  5485. +MODULE_LICENSE("GPL");
  5486. +MODULE_ALIAS("platform:surface_sam_sid_vhf");
  5487. diff --git a/drivers/platform/x86/surface_sam/surface_sam_sid_vhf.h b/drivers/platform/x86/surface_sam/surface_sam_sid_vhf.h
  5488. new file mode 100644
  5489. index 000000000000..eb55485ccb11
  5490. --- /dev/null
  5491. +++ b/drivers/platform/x86/surface_sam/surface_sam_sid_vhf.h
  5492. @@ -0,0 +1,13 @@
  5493. +#ifndef _SURFACE_SAM_SID_VHF_H
  5494. +#define _SURFACE_SAM_SID_VHF_H
  5495. +
  5496. +#include <linux/types.h>
  5497. +#include "surface_sam_ssh.h"
  5498. +
  5499. +
  5500. +struct ssam_hid_properties {
  5501. + struct ssam_event_registry registry;
  5502. + u8 instance;
  5503. +};
  5504. +
  5505. +#endif /* _SURFACE_SAM_SID_VHF_H */
  5506. diff --git a/drivers/platform/x86/surface_sam/surface_sam_ssh.c b/drivers/platform/x86/surface_sam/surface_sam_ssh.c
  5507. new file mode 100644
  5508. index 000000000000..9f44bdfbc4fd
  5509. --- /dev/null
  5510. +++ b/drivers/platform/x86/surface_sam/surface_sam_ssh.c
  5511. @@ -0,0 +1,5111 @@
  5512. +// SPDX-License-Identifier: GPL-2.0-or-later
  5513. +/*
  5514. + * Surface Serial Hub (SSH) driver for communication with the Surface/System
  5515. + * Aggregator Module.
  5516. + */
  5517. +
  5518. +#include <asm/unaligned.h>
  5519. +#include <linux/acpi.h>
  5520. +#include <linux/atomic.h>
  5521. +#include <linux/completion.h>
  5522. +#include <linux/crc-ccitt.h>
  5523. +#include <linux/dmaengine.h>
  5524. +#include <linux/gpio/consumer.h>
  5525. +#include <linux/interrupt.h>
  5526. +#include <linux/jiffies.h>
  5527. +#include <linux/kernel.h>
  5528. +#include <linux/kfifo.h>
  5529. +#include <linux/kref.h>
  5530. +#include <linux/kthread.h>
  5531. +#include <linux/ktime.h>
  5532. +#include <linux/list.h>
  5533. +#include <linux/mutex.h>
  5534. +#include <linux/pm.h>
  5535. +#include <linux/refcount.h>
  5536. +#include <linux/serdev.h>
  5537. +#include <linux/spinlock.h>
  5538. +#include <linux/sysfs.h>
  5539. +#include <linux/workqueue.h>
  5540. +
  5541. +#include "surface_sam_ssh.h"
  5542. +
  5543. +#define CREATE_TRACE_POINTS
  5544. +#include "surface_sam_ssh_trace.h"
  5545. +
  5546. +
  5547. +/* -- TODO. ----------------------------------------------------------------- */
  5548. +
  5549. +#define SSH_RQST_TAG_FULL "surface_sam_ssh_rqst: "
  5550. +#define SSH_RQST_TAG "rqst: "
  5551. +
  5552. +#define SSH_SUPPORTED_FLOW_CONTROL_MASK (~((u8) ACPI_UART_FLOW_CONTROL_HW))
  5553. +
  5554. +
  5555. +/* -- Error injection helpers. ---------------------------------------------- */
  5556. +
  5557. +#ifdef CONFIG_SURFACE_SAM_SSH_ERROR_INJECTION
  5558. +#define noinline_if_inject noinline
  5559. +#else /* CONFIG_SURFACE_SAM_SSH_ERROR_INJECTION */
  5560. +#define noinline_if_inject inline
  5561. +#endif /* CONFIG_SURFACE_SAM_SSH_ERROR_INJECTION */
  5562. +
  5563. +
  5564. +/* -- Public interface. ----------------------------------------------------- */
  5565. +
  5566. +enum ssam_request_flags {
  5567. + SSAM_REQUEST_HAS_RESPONSE = BIT(0),
  5568. + SSAM_REQUEST_UNSEQUENCED = BIT(1),
  5569. +};
  5570. +
  5571. +struct ssam_request {
  5572. + u8 target_category;
  5573. + u8 command_id;
  5574. + u8 instance_id;
  5575. + u8 channel;
  5576. + u16 flags;
  5577. + u16 length;
  5578. + u8 *payload;
  5579. +};
  5580. +
  5581. +
  5582. +/* -- Common/utility functions. --------------------------------------------- */
  5583. +
  5584. +static inline u16 ssh_crc(const u8 *buf, size_t len)
  5585. +{
  5586. + return crc_ccitt_false(0xffff, buf, len);
  5587. +}
  5588. +
  5589. +static inline u16 __ssh_rqid_next(u16 rqid)
  5590. +{
  5591. + return rqid > 0 ? rqid + 1u : rqid + SURFACE_SAM_SSH_NUM_EVENTS + 1u;
  5592. +}
  5593. +
  5594. +static inline u16 ssh_event_to_rqid(u16 event)
  5595. +{
  5596. + return event + 1u;
  5597. +}
  5598. +
  5599. +static inline u16 ssh_rqid_to_event(u16 rqid)
  5600. +{
  5601. + return rqid - 1u;
  5602. +}
  5603. +
  5604. +static inline bool ssh_rqid_is_event(u16 rqid)
  5605. +{
  5606. + return ssh_rqid_to_event(rqid) < SURFACE_SAM_SSH_NUM_EVENTS;
  5607. +}
  5608. +
  5609. +static inline int ssh_tc_to_rqid(u8 tc)
  5610. +{
  5611. +#if 0 // TODO: check if it works without this
  5612. + /*
  5613. + * TC=0x08 represents the input subsystem on Surface Laptop 1 and 2.
  5614. + * This is mapped on Windows to RQID=0x0001. As input events seem to be
  5615. + * somewhat special with regards to enabling/disabling (they seem to be
  5616. + * enabled by default with a fixed RQID), let's do the same here.
  5617. + */
  5618. + if (tc == 0x08)
  5619. + return 0x0001;
  5620. +
  5621. + /* Default path: Set RQID = TC. */
  5622. +#endif
  5623. + return tc;
  5624. +}
  5625. +
  5626. +static inline int ssh_tc_to_event(u8 tc)
  5627. +{
  5628. + return ssh_rqid_to_event(ssh_tc_to_rqid(tc));
  5629. +}
  5630. +
  5631. +static inline u8 ssh_channel_to_index(u8 channel)
  5632. +{
  5633. + return channel - 1u;
  5634. +}
  5635. +
  5636. +static inline bool ssh_channel_is_valid(u8 channel)
  5637. +{
  5638. + return ssh_channel_to_index(channel) < SURFACE_SAM_SSH_NUM_CHANNELS;
  5639. +}
  5640. +
  5641. +
  5642. +/* -- Safe counters. -------------------------------------------------------- */
  5643. +
  5644. +struct ssh_seq_counter {
  5645. + u8 value;
  5646. +};
  5647. +
  5648. +struct ssh_rqid_counter {
  5649. + u16 value;
  5650. +};
  5651. +
  5652. +static inline void ssh_seq_reset(struct ssh_seq_counter *c)
  5653. +{
  5654. + WRITE_ONCE(c->value, 0);
  5655. +}
  5656. +
  5657. +static inline u8 ssh_seq_next(struct ssh_seq_counter *c)
  5658. +{
  5659. + u8 old = READ_ONCE(c->value);
  5660. + u8 new = old + 1;
  5661. + u8 ret;
  5662. +
  5663. + while (unlikely((ret = cmpxchg(&c->value, old, new)) != old)) {
  5664. + old = ret;
  5665. + new = old + 1;
  5666. + }
  5667. +
  5668. + return old;
  5669. +}
  5670. +
  5671. +static inline void ssh_rqid_reset(struct ssh_rqid_counter *c)
  5672. +{
  5673. + WRITE_ONCE(c->value, 0);
  5674. +}
  5675. +
  5676. +static inline u16 ssh_rqid_next(struct ssh_rqid_counter *c)
  5677. +{
  5678. + u16 old = READ_ONCE(c->value);
  5679. + u16 new = __ssh_rqid_next(old);
  5680. + u16 ret;
  5681. +
  5682. + while (unlikely((ret = cmpxchg(&c->value, old, new)) != old)) {
  5683. + old = ret;
  5684. + new = __ssh_rqid_next(old);
  5685. + }
  5686. +
  5687. + return old;
  5688. +}
  5689. +
  5690. +
  5691. +/* -- Builder functions for SAM-over-SSH messages. -------------------------- */
  5692. +
  5693. +struct msgbuf {
  5694. + u8 *buffer;
  5695. + u8 *end;
  5696. + u8 *ptr;
  5697. +};
  5698. +
  5699. +static inline void msgb_init(struct msgbuf *msgb, u8 *buffer, size_t cap)
  5700. +{
  5701. + msgb->buffer = buffer;
  5702. + msgb->end = buffer + cap;
  5703. + msgb->ptr = buffer;
  5704. +}
  5705. +
  5706. +static inline int msgb_alloc(struct msgbuf *msgb, size_t cap, gfp_t flags)
  5707. +{
  5708. + u8 *buf;
  5709. +
  5710. + buf = kzalloc(cap, flags);
  5711. + if (!buf)
  5712. + return -ENOMEM;
  5713. +
  5714. + msgb_init(msgb, buf, cap);
  5715. + return 0;
  5716. +}
  5717. +
  5718. +static inline void msgb_free(struct msgbuf *msgb)
  5719. +{
  5720. + kfree(msgb->buffer);
  5721. + msgb->buffer = NULL;
  5722. + msgb->end = NULL;
  5723. + msgb->ptr = NULL;
  5724. +}
  5725. +
  5726. +static inline void msgb_reset(struct msgbuf *msgb)
  5727. +{
  5728. + msgb->ptr = msgb->buffer;
  5729. +}
  5730. +
  5731. +static inline size_t msgb_bytes_used(const struct msgbuf *msgb)
  5732. +{
  5733. + return msgb->ptr - msgb->buffer;
  5734. +}
  5735. +
  5736. +static inline void msgb_push_u16(struct msgbuf *msgb, u16 value)
  5737. +{
  5738. + WARN_ON(msgb->ptr + sizeof(u16) > msgb->end);
  5739. + if (msgb->ptr + sizeof(u16) > msgb->end)
  5740. + return;
  5741. +
  5742. + put_unaligned_le16(value, msgb->ptr);
  5743. + msgb->ptr += sizeof(u16);
  5744. +}
  5745. +
  5746. +static inline void msgb_push_syn(struct msgbuf *msgb)
  5747. +{
  5748. + msgb_push_u16(msgb, SSH_MSG_SYN);
  5749. +}
  5750. +
  5751. +static inline void msgb_push_buf(struct msgbuf *msgb, const u8 *buf, size_t len)
  5752. +{
  5753. + msgb->ptr = memcpy(msgb->ptr, buf, len) + len;
  5754. +}
  5755. +
  5756. +static inline void msgb_push_crc(struct msgbuf *msgb, const u8 *buf, size_t len)
  5757. +{
  5758. + msgb_push_u16(msgb, ssh_crc(buf, len));
  5759. +}
  5760. +
  5761. +static inline void msgb_push_frame(struct msgbuf *msgb, u8 ty, u16 len, u8 seq)
  5762. +{
  5763. + struct ssh_frame *frame = (struct ssh_frame *)msgb->ptr;
  5764. + const u8 *const begin = msgb->ptr;
  5765. +
  5766. + WARN_ON(msgb->ptr + sizeof(*frame) > msgb->end);
  5767. + if (msgb->ptr + sizeof(*frame) > msgb->end)
  5768. + return;
  5769. +
  5770. + frame->type = ty;
  5771. + put_unaligned_le16(len, &frame->len);
  5772. + frame->seq = seq;
  5773. +
  5774. + msgb->ptr += sizeof(*frame);
  5775. + msgb_push_crc(msgb, begin, msgb->ptr - begin);
  5776. +}
  5777. +
  5778. +static inline void msgb_push_ack(struct msgbuf *msgb, u8 seq)
  5779. +{
  5780. + // SYN
  5781. + msgb_push_syn(msgb);
  5782. +
  5783. + // ACK-type frame + CRC
  5784. + msgb_push_frame(msgb, SSH_FRAME_TYPE_ACK, 0x00, seq);
  5785. +
  5786. + // payload CRC (ACK-type frames do not have a payload)
  5787. + msgb_push_crc(msgb, msgb->ptr, 0);
  5788. +}
  5789. +
  5790. +static inline void msgb_push_nak(struct msgbuf *msgb)
  5791. +{
  5792. + // SYN
  5793. + msgb_push_syn(msgb);
  5794. +
  5795. + // NAK-type frame + CRC
  5796. + msgb_push_frame(msgb, SSH_FRAME_TYPE_NAK, 0x00, 0x00);
  5797. +
  5798. + // payload CRC (ACK-type frames do not have a payload)
  5799. + msgb_push_crc(msgb, msgb->ptr, 0);
  5800. +}
  5801. +
  5802. +static inline void msgb_push_cmd(struct msgbuf *msgb, u8 seq,
  5803. + const struct surface_sam_ssh_rqst *rqst,
  5804. + u16 rqid)
  5805. +{
  5806. + struct ssh_command *cmd;
  5807. + const u8 *cmd_begin;
  5808. + const u8 type = SSH_FRAME_TYPE_DATA_SEQ;
  5809. +
  5810. + // SYN
  5811. + msgb_push_syn(msgb);
  5812. +
  5813. + // command frame + crc
  5814. + msgb_push_frame(msgb, type, sizeof(*cmd) + rqst->cdl, seq);
  5815. +
  5816. + // frame payload: command struct + payload
  5817. + WARN_ON(msgb->ptr + sizeof(*cmd) > msgb->end);
  5818. + if (msgb->ptr + sizeof(*cmd) > msgb->end)
  5819. + return;
  5820. +
  5821. + cmd_begin = msgb->ptr;
  5822. + cmd = (struct ssh_command *)msgb->ptr;
  5823. +
  5824. + cmd->type = SSH_PLD_TYPE_CMD;
  5825. + cmd->tc = rqst->tc;
  5826. + cmd->chn_out = rqst->chn;
  5827. + cmd->chn_in = 0x00;
  5828. + cmd->iid = rqst->iid;
  5829. + put_unaligned_le16(rqid, &cmd->rqid);
  5830. + cmd->cid = rqst->cid;
  5831. +
  5832. + msgb->ptr += sizeof(*cmd);
  5833. +
  5834. + // command payload
  5835. + msgb_push_buf(msgb, rqst->pld, rqst->cdl);
  5836. +
  5837. + // crc for command struct + payload
  5838. + msgb_push_crc(msgb, cmd_begin, msgb->ptr - cmd_begin);
  5839. +}
  5840. +
  5841. +
  5842. +/* -- Parser functions and utilities for SAM-over-SSH messages. ------------- */
  5843. +
  5844. +struct sshp_buf {
  5845. + u8 *ptr;
  5846. + size_t len;
  5847. + size_t cap;
  5848. +};
  5849. +
  5850. +
  5851. +static inline bool sshp_validate_crc(const struct sshp_span *src, const u8 *crc)
  5852. +{
  5853. + u16 actual = ssh_crc(src->ptr, src->len);
  5854. + u16 expected = get_unaligned_le16(crc);
  5855. +
  5856. + return actual == expected;
  5857. +}
  5858. +
  5859. +static bool sshp_find_syn(const struct sshp_span *src, struct sshp_span *rem)
  5860. +{
  5861. + size_t i;
  5862. +
  5863. + for (i = 0; i < src->len - 1; i++) {
  5864. + if (likely(get_unaligned_le16(src->ptr + i) == SSH_MSG_SYN)) {
  5865. + rem->ptr = src->ptr + i;
  5866. + rem->len = src->len - i;
  5867. + return true;
  5868. + }
  5869. + }
  5870. +
  5871. + if (unlikely(src->ptr[src->len - 1] == (SSH_MSG_SYN & 0xff))) {
  5872. + rem->ptr = src->ptr + src->len - 1;
  5873. + rem->len = 1;
  5874. + return false;
  5875. + } else {
  5876. + rem->ptr = src->ptr + src->len;
  5877. + rem->len = 0;
  5878. + return false;
  5879. + }
  5880. +}
  5881. +
  5882. +static bool sshp_starts_with_syn(const struct sshp_span *src)
  5883. +{
  5884. + return src->len >= 2 && get_unaligned_le16(src->ptr) == SSH_MSG_SYN;
  5885. +}
  5886. +
  5887. +static int sshp_parse_frame(const struct device *dev,
  5888. + const struct sshp_span *source,
  5889. + struct ssh_frame **frame,
  5890. + struct sshp_span *payload,
  5891. + size_t maxlen)
  5892. +{
  5893. + struct sshp_span sf;
  5894. + struct sshp_span sp;
  5895. +
  5896. + // initialize output
  5897. + *frame = NULL;
  5898. + payload->ptr = NULL;
  5899. + payload->len = 0;
  5900. +
  5901. + if (!sshp_starts_with_syn(source)) {
  5902. + dev_warn(dev, "rx: parser: invalid start of frame\n");
  5903. + return -ENOMSG;
  5904. + }
  5905. +
  5906. + // check for minumum packet length
  5907. + if (unlikely(source->len < SSH_MESSAGE_LENGTH(0))) {
  5908. + dev_dbg(dev, "rx: parser: not enough data for frame\n");
  5909. + return 0;
  5910. + }
  5911. +
  5912. + // pin down frame
  5913. + sf.ptr = source->ptr + sizeof(u16);
  5914. + sf.len = sizeof(struct ssh_frame);
  5915. +
  5916. + // validate frame CRC
  5917. + if (unlikely(!sshp_validate_crc(&sf, sf.ptr + sf.len))) {
  5918. + dev_warn(dev, "rx: parser: invalid frame CRC\n");
  5919. + return -EBADMSG;
  5920. + }
  5921. +
  5922. + // ensure packet does not exceed maximum length
  5923. + if (unlikely(((struct ssh_frame *)sf.ptr)->len > maxlen)) {
  5924. + dev_warn(dev, "rx: parser: frame too large: %u bytes\n",
  5925. + ((struct ssh_frame *)sf.ptr)->len);
  5926. + return -EMSGSIZE;
  5927. + }
  5928. +
  5929. + // pin down payload
  5930. + sp.ptr = sf.ptr + sf.len + sizeof(u16);
  5931. + sp.len = get_unaligned_le16(&((struct ssh_frame *)sf.ptr)->len);
  5932. +
  5933. + // check for frame + payload length
  5934. + if (source->len < SSH_MESSAGE_LENGTH(sp.len)) {
  5935. + dev_dbg(dev, "rx: parser: not enough data for payload\n");
  5936. + return 0;
  5937. + }
  5938. +
  5939. + // validate payload crc
  5940. + if (unlikely(!sshp_validate_crc(&sp, sp.ptr + sp.len))) {
  5941. + dev_warn(dev, "rx: parser: invalid payload CRC\n");
  5942. + return -EBADMSG;
  5943. + }
  5944. +
  5945. + *frame = (struct ssh_frame *)sf.ptr;
  5946. + *payload = sp;
  5947. +
  5948. + dev_dbg(dev, "rx: parser: valid frame found (type: 0x%02x, len: %u)\n",
  5949. + (*frame)->type, (*frame)->len);
  5950. +
  5951. + return 0;
  5952. +}
  5953. +
  5954. +static int sshp_parse_command(const struct device *dev,
  5955. + const struct sshp_span *source,
  5956. + struct ssh_command **command,
  5957. + struct sshp_span *command_data)
  5958. +{
  5959. + // check for minimum length
  5960. + if (unlikely(source->len < sizeof(struct ssh_command))) {
  5961. + *command = NULL;
  5962. + command_data->ptr = NULL;
  5963. + command_data->len = 0;
  5964. +
  5965. + dev_err(dev, "rx: parser: command payload is too short\n");
  5966. + return -ENOMSG;
  5967. + }
  5968. +
  5969. + *command = (struct ssh_command *)source->ptr;
  5970. + command_data->ptr = source->ptr + sizeof(struct ssh_command);
  5971. + command_data->len = source->len - sizeof(struct ssh_command);
  5972. +
  5973. + dev_dbg(dev, "rx: parser: valid command found (tc: 0x%02x,"
  5974. + " cid: 0x%02x)\n", (*command)->tc, (*command)->cid);
  5975. +
  5976. + return 0;
  5977. +}
  5978. +
  5979. +
  5980. +static inline void sshp_buf_init(struct sshp_buf *buf, u8 *ptr, size_t cap)
  5981. +{
  5982. + buf->ptr = ptr;
  5983. + buf->len = 0;
  5984. + buf->cap = cap;
  5985. +}
  5986. +
  5987. +static inline int sshp_buf_alloc(struct sshp_buf *buf, size_t cap, gfp_t flags)
  5988. +{
  5989. + u8 *ptr;
  5990. +
  5991. + ptr = kzalloc(cap, flags);
  5992. + if (!ptr)
  5993. + return -ENOMEM;
  5994. +
  5995. + sshp_buf_init(buf, ptr, cap);
  5996. + return 0;
  5997. +
  5998. +}
  5999. +
  6000. +static inline void sshp_buf_free(struct sshp_buf *buf)
  6001. +{
  6002. + kfree(buf->ptr);
  6003. + buf->ptr = NULL;
  6004. + buf->len = 0;
  6005. + buf->cap = 0;
  6006. +}
  6007. +
  6008. +static inline void sshp_buf_reset(struct sshp_buf *buf)
  6009. +{
  6010. + buf->len = 0;
  6011. +}
  6012. +
  6013. +static inline void sshp_buf_drop(struct sshp_buf *buf, size_t n)
  6014. +{
  6015. + memmove(buf->ptr, buf->ptr + n, buf->len - n);
  6016. + buf->len -= n;
  6017. +}
  6018. +
  6019. +static inline size_t sshp_buf_read_from_fifo(struct sshp_buf *buf,
  6020. + struct kfifo *fifo)
  6021. +{
  6022. + size_t n;
  6023. +
  6024. + n = kfifo_out(fifo, buf->ptr + buf->len, buf->cap - buf->len);
  6025. + buf->len += n;
  6026. +
  6027. + return n;
  6028. +}
  6029. +
  6030. +static inline void sshp_buf_span_from(struct sshp_buf *buf, size_t offset,
  6031. + struct sshp_span *span)
  6032. +{
  6033. + span->ptr = buf->ptr + offset;
  6034. + span->len = buf->len - offset;
  6035. +}
  6036. +
  6037. +
  6038. +/* -- Packet transport layer (ptl). ----------------------------------------- */
  6039. +/*
  6040. + * To simplify reasoning about the code below, we define a few concepts. The
  6041. + * system below is similar to a state-machine for packets, however, there are
  6042. + * too many states to explicitly write them down. To (somewhat) manage the
  6043. + * states and packets we rely on flags, reference counting, and some simple
  6044. + * concepts. State transitions are triggered by actions.
  6045. + *
  6046. + * >> Actions <<
  6047. + *
  6048. + * - submit
  6049. + * - transmission start (process next item in queue)
  6050. + * - transmission finished (guaranteed to never be parallel to transmission
  6051. + * start)
  6052. + * - ACK received
  6053. + * - NAK received (this is equivalent to issuing re-submit for all pending
  6054. + * packets)
  6055. + * - timeout (this is equivalent to re-issuing a submit or canceling)
  6056. + * - cancel (non-pending and pending)
  6057. + *
  6058. + * >> Data Structures, Packet Ownership, General Overview <<
  6059. + *
  6060. + * The code below employs two main data structures: The packet queue, containing
  6061. + * all packets scheduled for transmission, and the set of pending packets,
  6062. + * containing all packets awaiting an ACK.
  6063. + *
  6064. + * Shared ownership of a packet is controlled via reference counting. Inside the
  6065. + * transmission system are a total of five packet owners:
  6066. + *
  6067. + * - the packet queue,
  6068. + * - the pending set,
  6069. + * - the transmitter thread,
  6070. + * - the receiver thread (via ACKing), and
  6071. + * - the timeout work item.
  6072. + *
  6073. + * Normal operation is as follows: The initial reference of the packet is
  6074. + * obtained by submitting the packet and queueing it. The receiver thread
  6075. + * takes packets from the queue. By doing this, it does not increment the
  6076. + * refcount but takes over the reference (removing it from the queue).
  6077. + * If the packet is sequenced (i.e. needs to be ACKed by the client), the
  6078. + * transmitter thread sets-up the timeout and adds the packet to the pending set
  6079. + * before starting to transmit it. As the timeout is handled by a reaper task,
  6080. + * no additional reference for it is needed. After the transmit is done, the
  6081. + * reference hold by the transmitter thread is dropped. If the packet is
  6082. + * unsequenced (i.e. does not need an ACK), the packet is completed by the
  6083. + * transmitter thread before dropping that reference.
  6084. + *
  6085. + * On receial of an ACK, the receiver thread removes and obtains the refernce to
  6086. + * the packet from the pending set. On succes, the receiver thread will then
  6087. + * complete the packet and drop its reference.
  6088. + *
  6089. + * On error, the completion callback is immediately run by on thread on which
  6090. + * the error was detected.
  6091. + *
  6092. + * To ensure that a packet eventually leaves the system it is marked as "locked"
  6093. + * directly before it is going to be completed or when it is canceled. Marking a
  6094. + * packet as "locked" has the effect that passing and creating new references
  6095. + * of the packet will be blocked. This means that the packet cannot be added
  6096. + * to the queue, the pending set, and the timeout, or be picked up by the
  6097. + * transmitter thread or receiver thread. To remove a packet from the system it
  6098. + * has to be marked as locked and subsequently all references from the data
  6099. + * structures (queue, pending) have to be removed. References held by threads
  6100. + * will eventually be dropped automatically as their execution progresses.
  6101. + *
  6102. + * Note that the packet completion callback is, in case of success and for a
  6103. + * sequenced packet, guaranteed to run on the receiver thread, thus providing a
  6104. + * way to reliably identify responses to the packet. The packet completion
  6105. + * callback is only run once and it does not indicate that the packet has fully
  6106. + * left the system. In case of re-submission (and with somewhat unlikely
  6107. + * timing), it may be possible that the packet is being re-transmitted while the
  6108. + * completion callback runs. Completion will occur both on success and internal
  6109. + * error, as well as when the packet is canceled.
  6110. + *
  6111. + * >> Flags <<
  6112. + *
  6113. + * Flags are used to indicate the state and progression of a packet. Some flags
  6114. + * have stricter guarantees than other:
  6115. + *
  6116. + * - locked
  6117. + * Indicates if the packet is locked. If the packet is locked, passing and/or
  6118. + * creating additional references to the packet is forbidden. The packet thus
  6119. + * may not be queued, dequeued, or removed or added to the pending set. Note
  6120. + * that the packet state flags may still change (e.g. it may be marked as
  6121. + * ACKed, transmitted, ...).
  6122. + *
  6123. + * - completed
  6124. + * Indicates if the packet completion has been run or is about to be run. This
  6125. + * flag is used to ensure that the packet completion callback is only run
  6126. + * once.
  6127. + *
  6128. + * - queued
  6129. + * Indicates if a packet is present in the submission queue or not. This flag
  6130. + * must only be modified with the queue lock held, and must be coherent
  6131. + * presence of the packet in the queue.
  6132. + *
  6133. + * - pending
  6134. + * Indicates if a packet is present in the set of pending packets or not.
  6135. + * This flag must only be modified with the pending lock held, and must be
  6136. + * coherent presence of the packet in the pending set.
  6137. + *
  6138. + * - transmitting
  6139. + * Indicates if the packet is currently transmitting. In case of
  6140. + * re-transmissions, it is only safe to wait on the "transmitted" completion
  6141. + * after this flag has been set. The completion will be set both in success
  6142. + * and error case.
  6143. + *
  6144. + * - transmitted
  6145. + * Indicates if the packet has been transmitted. This flag is not cleared by
  6146. + * the system, thus it indicates the first transmission only.
  6147. + *
  6148. + * - acked
  6149. + * Indicates if the packet has been acknowledged by the client. There are no
  6150. + * other guarantees given. For example, the packet may still be canceled
  6151. + * and/or the completion may be triggered an error even though this bit is
  6152. + * set. Rely on the status provided by completion instead.
  6153. + *
  6154. + * - canceled
  6155. + * Indicates if the packet has been canceled from the outside. There are no
  6156. + * other guarantees given. Specifically, the packet may be completed by
  6157. + * another part of the system before the cancellation attempts to complete it.
  6158. + *
  6159. + * >> General Notes <<
  6160. + *
  6161. + * To avoid deadlocks, if both queue and pending locks are required, the pending
  6162. + * lock must be acquired before the queue lock.
  6163. + */
  6164. +
  6165. +/**
  6166. + * Maximum number transmission attempts per sequenced packet in case of
  6167. + * time-outs. Must be smaller than 16.
  6168. + */
  6169. +#define SSH_PTL_MAX_PACKET_TRIES 3
  6170. +
  6171. +/**
  6172. + * Timeout as ktime_t delta for ACKs. If we have not received an ACK in this
  6173. + * time-frame after starting transmission, the packet will be re-submitted.
  6174. + */
  6175. +#define SSH_PTL_PACKET_TIMEOUT ms_to_ktime(1000)
  6176. +
  6177. +/**
  6178. + * Maximum time resolution for timeouts. Currently set to max(2 jiffies, 50ms).
  6179. + * Should be larger than one jiffy to avoid direct re-scheduling of reaper
  6180. + * work_struct.
  6181. + */
  6182. +#define SSH_PTL_PACKET_TIMEOUT_RESOLUTION ms_to_ktime(max(2000 / HZ, 50))
  6183. +
  6184. +/**
  6185. + * Maximum number of sequenced packets concurrently waiting for an ACK.
  6186. + * Packets marked as blocking will not be transmitted while this limit is
  6187. + * reached.
  6188. + */
  6189. +#define SSH_PTL_MAX_PENDING 1
  6190. +
  6191. +#define SSH_PTL_RX_BUF_LEN 4096
  6192. +
  6193. +#define SSH_PTL_RX_FIFO_LEN 4096
  6194. +
  6195. +
  6196. +enum ssh_ptl_state_flags {
  6197. + SSH_PTL_SF_SHUTDOWN_BIT,
  6198. +};
  6199. +
  6200. +struct ssh_ptl_ops {
  6201. + void (*data_received)(struct ssh_ptl *p, const struct sshp_span *data);
  6202. +};
  6203. +
  6204. +struct ssh_ptl {
  6205. + struct serdev_device *serdev;
  6206. + unsigned long state;
  6207. +
  6208. + struct {
  6209. + spinlock_t lock;
  6210. + struct list_head head;
  6211. + } queue;
  6212. +
  6213. + struct {
  6214. + spinlock_t lock;
  6215. + struct list_head head;
  6216. + atomic_t count;
  6217. + } pending;
  6218. +
  6219. + struct {
  6220. + bool thread_signal;
  6221. + struct task_struct *thread;
  6222. + struct wait_queue_head thread_wq;
  6223. + struct wait_queue_head packet_wq;
  6224. + struct ssh_packet *packet;
  6225. + size_t offset;
  6226. + } tx;
  6227. +
  6228. + struct {
  6229. + struct task_struct *thread;
  6230. + struct wait_queue_head wq;
  6231. + struct kfifo fifo;
  6232. + struct sshp_buf buf;
  6233. +
  6234. + struct {
  6235. + u16 seqs[8];
  6236. + u16 offset;
  6237. + } blacklist;
  6238. + } rx;
  6239. +
  6240. + struct {
  6241. + ktime_t timeout;
  6242. + ktime_t expires;
  6243. + struct delayed_work reaper;
  6244. + } rtx_timeout;
  6245. +
  6246. + struct ssh_ptl_ops ops;
  6247. +};
  6248. +
  6249. +
  6250. +#define __ssam_prcond(func, p, fmt, ...) \
  6251. + do { \
  6252. + if ((p)) \
  6253. + func((p), fmt, ##__VA_ARGS__); \
  6254. + } while (0);
  6255. +
  6256. +#define ptl_dbg(p, fmt, ...) dev_dbg(&(p)->serdev->dev, fmt, ##__VA_ARGS__)
  6257. +#define ptl_info(p, fmt, ...) dev_info(&(p)->serdev->dev, fmt, ##__VA_ARGS__)
  6258. +#define ptl_warn(p, fmt, ...) dev_warn(&(p)->serdev->dev, fmt, ##__VA_ARGS__)
  6259. +#define ptl_err(p, fmt, ...) dev_err(&(p)->serdev->dev, fmt, ##__VA_ARGS__)
  6260. +#define ptl_dbg_cond(p, fmt, ...) __ssam_prcond(ptl_dbg, p, fmt, ##__VA_ARGS__)
  6261. +
  6262. +#define to_ssh_packet(ptr, member) \
  6263. + container_of(ptr, struct ssh_packet, member)
  6264. +
  6265. +#define to_ssh_ptl(ptr, member) \
  6266. + container_of(ptr, struct ssh_ptl, member)
  6267. +
  6268. +
  6269. +#ifdef CONFIG_SURFACE_SAM_SSH_ERROR_INJECTION
  6270. +
  6271. +/**
  6272. + * ssh_ptl_should_drop_ack_packet - error injection hook to drop ACK packets
  6273. + *
  6274. + * Useful to test detection and handling of automated re-transmits by the EC.
  6275. + * Specifically of packets that the EC consideres not-ACKed but the driver
  6276. + * already consideres ACKed (due to dropped ACK). In this case, the EC
  6277. + * re-transmits the packet-to-be-ACKed and the driver should detect it as
  6278. + * duplicate/already handled. Note that the driver should still send an ACK
  6279. + * for the re-transmitted packet.
  6280. + */
  6281. +static noinline bool ssh_ptl_should_drop_ack_packet(void)
  6282. +{
  6283. + return false;
  6284. +}
  6285. +ALLOW_ERROR_INJECTION(ssh_ptl_should_drop_ack_packet, TRUE);
  6286. +
  6287. +/**
  6288. + * ssh_ptl_should_drop_nak_packet - error injection hook to drop NAK packets
  6289. + *
  6290. + * Useful to test/force automated (timeout-based) re-transmit by the EC.
  6291. + * Specifically, packets that have not reached the driver completely/with valid
  6292. + * checksums. Only useful in combination with receival of (injected) bad data.
  6293. + */
  6294. +static noinline bool ssh_ptl_should_drop_nak_packet(void)
  6295. +{
  6296. + return false;
  6297. +}
  6298. +ALLOW_ERROR_INJECTION(ssh_ptl_should_drop_nak_packet, TRUE);
  6299. +
  6300. +/**
  6301. + * ssh_ptl_should_drop_dsq_packet - error injection hook to drop sequenced data
  6302. + * packet
  6303. + *
  6304. + * Useful to test re-transmit timeout of the driver. If the data packet has not
  6305. + * been ACKed after a certain time, the driver should re-transmit the packet up
  6306. + * to limited number of times defined in SSH_PTL_MAX_PACKET_TRIES.
  6307. + */
  6308. +static noinline bool ssh_ptl_should_drop_dsq_packet(void)
  6309. +{
  6310. + return false;
  6311. +}
  6312. +ALLOW_ERROR_INJECTION(ssh_ptl_should_drop_dsq_packet, TRUE);
  6313. +
  6314. +/**
  6315. + * ssh_ptl_should_fail_write - error injection hook to make serdev_device_write
  6316. + * fail
  6317. + *
  6318. + * Hook to simulate errors in serdev_device_write when transmitting packets.
  6319. + */
  6320. +static noinline int ssh_ptl_should_fail_write(void)
  6321. +{
  6322. + return 0;
  6323. +}
  6324. +ALLOW_ERROR_INJECTION(ssh_ptl_should_fail_write, ERRNO);
  6325. +
  6326. +/**
  6327. + * ssh_ptl_should_corrupt_tx_data - error injection hook to simualte invalid
  6328. + * data being sent to the EC
  6329. + *
  6330. + * Hook to simulate corrupt/invalid data being sent from host (driver) to EC.
  6331. + * Causes the package data to be actively corrupted by overwriting it with
  6332. + * pre-defined values, such that it becomes invalid, causing the EC to respond
  6333. + * with a NAK packet. Useful to test handling of NAK packets received by the
  6334. + * driver.
  6335. + */
  6336. +static noinline bool ssh_ptl_should_corrupt_tx_data(void)
  6337. +{
  6338. + return false;
  6339. +}
  6340. +ALLOW_ERROR_INJECTION(ssh_ptl_should_corrupt_tx_data, TRUE);
  6341. +
  6342. +/**
  6343. + * ssh_ptl_should_corrupt_rx_syn - error injection hook to simulate invalid
  6344. + * data being sent by the EC
  6345. + *
  6346. + * Hook to simulate invalid SYN bytes, i.e. an invalid start of messages and
  6347. + * test handling thereof in the driver.
  6348. + */
  6349. +static noinline bool ssh_ptl_should_corrupt_rx_syn(void)
  6350. +{
  6351. + return false;
  6352. +}
  6353. +ALLOW_ERROR_INJECTION(ssh_ptl_should_corrupt_rx_syn, TRUE);
  6354. +
  6355. +/**
  6356. + * ssh_ptl_should_corrupt_rx_data - error injection hook to simulate invalid
  6357. + * data being sent by the EC
  6358. + *
  6359. + * Hook to simulate invalid data/checksum of the message frame and test handling
  6360. + * thereof in the driver.
  6361. + */
  6362. +static noinline bool ssh_ptl_should_corrupt_rx_data(void)
  6363. +{
  6364. + return false;
  6365. +}
  6366. +ALLOW_ERROR_INJECTION(ssh_ptl_should_corrupt_rx_data, TRUE);
  6367. +
  6368. +
  6369. +static inline bool __ssh_ptl_should_drop_ack_packet(struct ssh_packet *packet)
  6370. +{
  6371. + if (likely(!ssh_ptl_should_drop_ack_packet()))
  6372. + return false;
  6373. +
  6374. + trace_ssam_ei_tx_drop_ack_packet(packet);
  6375. + ptl_info(packet->ptl, "packet error injection: dropping ACK packet %p\n",
  6376. + packet);
  6377. +
  6378. + return true;
  6379. +}
  6380. +
  6381. +static inline bool __ssh_ptl_should_drop_nak_packet(struct ssh_packet *packet)
  6382. +{
  6383. + if (likely(!ssh_ptl_should_drop_nak_packet()))
  6384. + return false;
  6385. +
  6386. + trace_ssam_ei_tx_drop_nak_packet(packet);
  6387. + ptl_info(packet->ptl, "packet error injection: dropping NAK packet %p\n",
  6388. + packet);
  6389. +
  6390. + return true;
  6391. +}
  6392. +
  6393. +static inline bool __ssh_ptl_should_drop_dsq_packet(struct ssh_packet *packet)
  6394. +{
  6395. + if (likely(!ssh_ptl_should_drop_dsq_packet()))
  6396. + return false;
  6397. +
  6398. + trace_ssam_ei_tx_drop_dsq_packet(packet);
  6399. + ptl_info(packet->ptl,
  6400. + "packet error injection: dropping sequenced data packet %p\n",
  6401. + packet);
  6402. +
  6403. + return true;
  6404. +}
  6405. +
  6406. +static bool ssh_ptl_should_drop_packet(struct ssh_packet *packet)
  6407. +{
  6408. + // ignore packets that don't carry any data (i.e. flush)
  6409. + if (!packet->data || !packet->data_length)
  6410. + return false;
  6411. +
  6412. + switch (packet->data[SSH_MSGOFFSET_FRAME(type)]) {
  6413. + case SSH_FRAME_TYPE_ACK:
  6414. + return __ssh_ptl_should_drop_ack_packet(packet);
  6415. +
  6416. + case SSH_FRAME_TYPE_NAK:
  6417. + return __ssh_ptl_should_drop_nak_packet(packet);
  6418. +
  6419. + case SSH_FRAME_TYPE_DATA_SEQ:
  6420. + return __ssh_ptl_should_drop_dsq_packet(packet);
  6421. +
  6422. + default:
  6423. + return false;
  6424. + }
  6425. +}
  6426. +
  6427. +static inline int ssh_ptl_write_buf(struct ssh_ptl *ptl,
  6428. + struct ssh_packet *packet,
  6429. + const unsigned char *buf,
  6430. + size_t count)
  6431. +{
  6432. + int status;
  6433. +
  6434. + status = ssh_ptl_should_fail_write();
  6435. + if (unlikely(status)) {
  6436. + trace_ssam_ei_tx_fail_write(packet, status);
  6437. + ptl_info(packet->ptl,
  6438. + "packet error injection: simulating transmit error %d, packet %p\n",
  6439. + status, packet);
  6440. +
  6441. + return status;
  6442. + }
  6443. +
  6444. + return serdev_device_write_buf(ptl->serdev, buf, count);
  6445. +}
  6446. +
  6447. +static inline void ssh_ptl_tx_inject_invalid_data(struct ssh_packet *packet)
  6448. +{
  6449. + // ignore packets that don't carry any data (i.e. flush)
  6450. + if (!packet->data || !packet->data_length)
  6451. + return;
  6452. +
  6453. + // only allow sequenced data packets to be modified
  6454. + if (packet->data[SSH_MSGOFFSET_FRAME(type)] != SSH_FRAME_TYPE_DATA_SEQ)
  6455. + return;
  6456. +
  6457. + if (likely(!ssh_ptl_should_corrupt_tx_data()))
  6458. + return;
  6459. +
  6460. + trace_ssam_ei_tx_corrupt_data(packet);
  6461. + ptl_info(packet->ptl,
  6462. + "packet error injection: simulating invalid transmit data on packet %p\n",
  6463. + packet);
  6464. +
  6465. + /*
  6466. + * NB: The value 0xb3 has been chosen more or less randomly so that it
  6467. + * doesn't have any (major) overlap with the SYN bytes (aa 55) and is
  6468. + * non-trivial (i.e. non-zero, non-0xff).
  6469. + */
  6470. + memset(packet->data, 0xb3, packet->data_length);
  6471. +}
  6472. +
  6473. +static inline void ssh_ptl_rx_inject_invalid_syn(struct ssh_ptl *ptl,
  6474. + struct sshp_span *data)
  6475. +{
  6476. + struct sshp_span frame;
  6477. +
  6478. + // check if there actually is something to corrupt
  6479. + if (!sshp_find_syn(data, &frame))
  6480. + return;
  6481. +
  6482. + if (likely(!ssh_ptl_should_corrupt_rx_syn()))
  6483. + return;
  6484. +
  6485. + trace_ssam_ei_rx_corrupt_syn("data_length", data->len);
  6486. +
  6487. + data->ptr[1] = 0xb3; // set second byte of SYN to "random" value
  6488. +}
  6489. +
  6490. +static inline void ssh_ptl_rx_inject_invalid_data(struct ssh_ptl *ptl,
  6491. + struct sshp_span *frame)
  6492. +{
  6493. + size_t payload_len, message_len;
  6494. + struct ssh_frame *sshf;
  6495. +
  6496. + // ignore incomplete messages, will get handled once it's complete
  6497. + if (frame->len < SSH_MESSAGE_LENGTH(0))
  6498. + return;
  6499. +
  6500. + // ignore incomplete messages, part 2
  6501. + payload_len = get_unaligned_le16(&frame->ptr[SSH_MSGOFFSET_FRAME(len)]);
  6502. + message_len = SSH_MESSAGE_LENGTH(payload_len);
  6503. + if (frame->len < message_len)
  6504. + return;
  6505. +
  6506. + if (likely(!ssh_ptl_should_corrupt_rx_data()))
  6507. + return;
  6508. +
  6509. + sshf = (struct ssh_frame *)&frame->ptr[SSH_MSGOFFSET_FRAME(type)];
  6510. + trace_ssam_ei_rx_corrupt_data(sshf);
  6511. +
  6512. + /*
  6513. + * Flip bits in first byte of payload checksum. This is basically
  6514. + * equivalent to a payload/frame data error without us having to worry
  6515. + * about (the, arguably pretty small, probability of) accidental
  6516. + * checksum collisions.
  6517. + */
  6518. + frame->ptr[frame->len - 2] = ~frame->ptr[frame->len - 2];
  6519. +}
  6520. +
  6521. +#else /* CONFIG_SURFACE_SAM_SSH_ERROR_INJECTION */
  6522. +
  6523. +static inline bool ssh_ptl_should_drop_packet(struct ssh_packet *packet)
  6524. +{
  6525. + return false;
  6526. +}
  6527. +
  6528. +static inline int ssh_ptl_write_buf(struct ssh_ptl *ptl,
  6529. + struct ssh_packet *packet,
  6530. + const unsigned char *buf,
  6531. + size_t count)
  6532. +{
  6533. + return serdev_device_write_buf(ptl->serdev, buf, count);
  6534. +}
  6535. +
  6536. +static inline void ssh_ptl_tx_inject_invalid_data(struct ssh_packet *packet)
  6537. +{
  6538. +}
  6539. +
  6540. +static inline void ssh_ptl_rx_inject_invalid_syn(struct ssh_ptl *ptl,
  6541. + struct sshp_span *data)
  6542. +{
  6543. +}
  6544. +
  6545. +static inline void ssh_ptl_rx_inject_invalid_data(struct ssh_ptl *ptl,
  6546. + struct sshp_span *frame)
  6547. +{
  6548. +}
  6549. +
  6550. +#endif /* CONFIG_SURFACE_SAM_SSH_ERROR_INJECTION */
  6551. +
  6552. +
  6553. +static void __ssh_ptl_packet_release(struct kref *kref)
  6554. +{
  6555. + struct ssh_packet *p = to_ssh_packet(kref, refcnt);
  6556. +
  6557. + trace_ssam_packet_release(p);
  6558. +
  6559. + ptl_dbg_cond(p->ptl, "ptl: releasing packet %p\n", p);
  6560. + p->ops->release(p);
  6561. +}
  6562. +
  6563. +static inline void ssh_packet_get(struct ssh_packet *packet)
  6564. +{
  6565. + kref_get(&packet->refcnt);
  6566. +}
  6567. +
  6568. +static inline void ssh_packet_put(struct ssh_packet *packet)
  6569. +{
  6570. + kref_put(&packet->refcnt, __ssh_ptl_packet_release);
  6571. +}
  6572. +
  6573. +
  6574. +static inline u8 ssh_packet_get_seq(struct ssh_packet *packet)
  6575. +{
  6576. + return packet->data[SSH_MSGOFFSET_FRAME(seq)];
  6577. +}
  6578. +
  6579. +
  6580. +struct ssh_packet_args {
  6581. + u8 type;
  6582. + u8 priority;
  6583. + const struct ssh_packet_ops *ops;
  6584. +};
  6585. +
  6586. +static void ssh_packet_init(struct ssh_packet *packet,
  6587. + const struct ssh_packet_args *args)
  6588. +{
  6589. + kref_init(&packet->refcnt);
  6590. +
  6591. + packet->ptl = NULL;
  6592. + INIT_LIST_HEAD(&packet->queue_node);
  6593. + INIT_LIST_HEAD(&packet->pending_node);
  6594. +
  6595. + packet->type = args->type;
  6596. + packet->priority = args->priority;
  6597. + packet->state = 0;
  6598. + packet->timestamp = KTIME_MAX;
  6599. +
  6600. + packet->data_length = 0;
  6601. + packet->data = NULL;
  6602. +
  6603. + packet->ops = args->ops;
  6604. +}
  6605. +
  6606. +
  6607. +static struct ssh_packet *ptl_alloc_ctrl_packet(
  6608. + struct ssh_ptl *ptl, const struct ssh_packet_args *args,
  6609. + gfp_t flags)
  6610. +{
  6611. + struct ssh_packet *packet;
  6612. +
  6613. + // TODO: chache packets
  6614. +
  6615. + packet = kzalloc(sizeof(struct ssh_packet) + SSH_MSG_LEN_CTRL, flags);
  6616. + if (!packet)
  6617. + return NULL;
  6618. +
  6619. + ssh_packet_init(packet, args);
  6620. + packet->data_length = SSH_MSG_LEN_CTRL;
  6621. + packet->data = ((u8 *) packet) + sizeof(struct ssh_packet);
  6622. +
  6623. + return packet;
  6624. +}
  6625. +
  6626. +static void ptl_free_ctrl_packet(struct ssh_packet *p)
  6627. +{
  6628. + // TODO: chache packets
  6629. +
  6630. + kfree(p);
  6631. +}
  6632. +
  6633. +static const struct ssh_packet_ops ssh_ptl_ctrl_packet_ops = {
  6634. + .complete = NULL,
  6635. + .release = ptl_free_ctrl_packet,
  6636. +};
  6637. +
  6638. +
  6639. +static void ssh_ptl_timeout_reaper_mod(struct ssh_ptl *ptl, ktime_t now,
  6640. + ktime_t expires)
  6641. +{
  6642. + unsigned long delta = msecs_to_jiffies(ktime_ms_delta(expires, now));
  6643. + ktime_t aexp = ktime_add(expires, SSH_PTL_PACKET_TIMEOUT_RESOLUTION);
  6644. + ktime_t old;
  6645. +
  6646. + // re-adjust / schedule reaper if it is above resolution delta
  6647. + old = READ_ONCE(ptl->rtx_timeout.expires);
  6648. + while (ktime_before(aexp, old))
  6649. + old = cmpxchg64(&ptl->rtx_timeout.expires, old, expires);
  6650. +
  6651. + // if we updated the reaper expiration, modify work timeout
  6652. + if (old == expires)
  6653. + mod_delayed_work(system_wq, &ptl->rtx_timeout.reaper, delta);
  6654. +}
  6655. +
  6656. +static void ssh_ptl_timeout_start(struct ssh_packet *packet)
  6657. +{
  6658. + struct ssh_ptl *ptl = packet->ptl;
  6659. + ktime_t timestamp = ktime_get_coarse_boottime();
  6660. + ktime_t timeout = ptl->rtx_timeout.timeout;
  6661. +
  6662. + if (test_bit(SSH_PACKET_SF_LOCKED_BIT, &packet->state))
  6663. + return;
  6664. +
  6665. + WRITE_ONCE(packet->timestamp, timestamp);
  6666. + smp_mb__after_atomic();
  6667. +
  6668. + ssh_ptl_timeout_reaper_mod(packet->ptl, timestamp, timestamp + timeout);
  6669. +}
  6670. +
  6671. +
  6672. +static struct list_head *__ssh_ptl_queue_find_entrypoint(struct ssh_packet *p)
  6673. +{
  6674. + struct list_head *head;
  6675. + u8 priority = READ_ONCE(p->priority);
  6676. +
  6677. + /*
  6678. + * We generally assume that there are less control (ACK/NAK) packets and
  6679. + * re-submitted data packets as there are normal data packets (at least
  6680. + * in situations in which many packets are queued; if there aren't many
  6681. + * packets queued the decision on how to iterate should be basically
  6682. + * irrellevant; the number of control/data packets is more or less
  6683. + * limited via the maximum number of pending packets). Thus, when
  6684. + * inserting a control or re-submitted data packet, (determined by their
  6685. + * priority), we search from front to back. Normal data packets are,
  6686. + * usually queued directly at the tail of the queue, so for those search
  6687. + * from back to front.
  6688. + */
  6689. +
  6690. + if (priority > SSH_PACKET_PRIORITY_DATA) {
  6691. + list_for_each(head, &p->ptl->queue.head) {
  6692. + p = list_entry(head, struct ssh_packet, queue_node);
  6693. +
  6694. + if (READ_ONCE(p->priority) < priority)
  6695. + break;
  6696. + }
  6697. + } else {
  6698. + list_for_each_prev(head, &p->ptl->queue.head) {
  6699. + p = list_entry(head, struct ssh_packet, queue_node);
  6700. +
  6701. + if (READ_ONCE(p->priority) >= priority) {
  6702. + head = head->next;
  6703. + break;
  6704. + }
  6705. + }
  6706. + }
  6707. +
  6708. +
  6709. + return head;
  6710. +}
  6711. +
  6712. +static int ssh_ptl_queue_push(struct ssh_packet *packet)
  6713. +{
  6714. + struct ssh_ptl *ptl = packet->ptl;
  6715. + struct list_head *head;
  6716. +
  6717. + spin_lock(&ptl->queue.lock);
  6718. +
  6719. + if (test_bit(SSH_PTL_SF_SHUTDOWN_BIT, &ptl->state)) {
  6720. + spin_unlock(&ptl->queue.lock);
  6721. + return -ESHUTDOWN;
  6722. + }
  6723. +
  6724. + // avoid further transitions when cancelling/completing
  6725. + if (test_bit(SSH_PACKET_SF_LOCKED_BIT, &packet->state)) {
  6726. + spin_unlock(&ptl->queue.lock);
  6727. + return -EINVAL;
  6728. + }
  6729. +
  6730. + // if this packet has already been queued, do not add it
  6731. + if (test_and_set_bit(SSH_PACKET_SF_QUEUED_BIT, &packet->state)) {
  6732. + spin_unlock(&ptl->queue.lock);
  6733. + return -EALREADY;
  6734. + }
  6735. +
  6736. + head = __ssh_ptl_queue_find_entrypoint(packet);
  6737. +
  6738. + ssh_packet_get(packet);
  6739. + list_add_tail(&packet->queue_node, &ptl->queue.head);
  6740. +
  6741. + spin_unlock(&ptl->queue.lock);
  6742. + return 0;
  6743. +}
  6744. +
  6745. +static void ssh_ptl_queue_remove(struct ssh_packet *packet)
  6746. +{
  6747. + struct ssh_ptl *ptl = packet->ptl;
  6748. + bool remove;
  6749. +
  6750. + spin_lock(&ptl->queue.lock);
  6751. +
  6752. + remove = test_and_clear_bit(SSH_PACKET_SF_QUEUED_BIT, &packet->state);
  6753. + if (remove)
  6754. + list_del(&packet->queue_node);
  6755. +
  6756. + spin_unlock(&ptl->queue.lock);
  6757. +
  6758. + if (remove)
  6759. + ssh_packet_put(packet);
  6760. +}
  6761. +
  6762. +
  6763. +static void ssh_ptl_pending_push(struct ssh_packet *packet)
  6764. +{
  6765. + struct ssh_ptl *ptl = packet->ptl;
  6766. +
  6767. + spin_lock(&ptl->pending.lock);
  6768. +
  6769. + // if we are cancelling/completing this packet, do not add it
  6770. + if (test_bit(SSH_PACKET_SF_LOCKED_BIT, &packet->state)) {
  6771. + spin_unlock(&ptl->pending.lock);
  6772. + return;
  6773. + }
  6774. +
  6775. + // in case it is already pending (e.g. re-submission), do not add it
  6776. + if (test_and_set_bit(SSH_PACKET_SF_PENDING_BIT, &packet->state)) {
  6777. + spin_unlock(&ptl->pending.lock);
  6778. + return;
  6779. + }
  6780. +
  6781. + atomic_inc(&ptl->pending.count);
  6782. + ssh_packet_get(packet);
  6783. + list_add_tail(&packet->pending_node, &ptl->pending.head);
  6784. +
  6785. + spin_unlock(&ptl->pending.lock);
  6786. +}
  6787. +
  6788. +static void ssh_ptl_pending_remove(struct ssh_packet *packet)
  6789. +{
  6790. + struct ssh_ptl *ptl = packet->ptl;
  6791. + bool remove;
  6792. +
  6793. + spin_lock(&ptl->pending.lock);
  6794. +
  6795. + remove = test_and_clear_bit(SSH_PACKET_SF_PENDING_BIT, &packet->state);
  6796. + if (remove) {
  6797. + list_del(&packet->pending_node);
  6798. + atomic_dec(&ptl->pending.count);
  6799. + }
  6800. +
  6801. + spin_unlock(&ptl->pending.lock);
  6802. +
  6803. + if (remove)
  6804. + ssh_packet_put(packet);
  6805. +}
  6806. +
  6807. +
  6808. +static void __ssh_ptl_complete(struct ssh_packet *p, int status)
  6809. +{
  6810. + struct ssh_ptl *ptl = READ_ONCE(p->ptl);
  6811. +
  6812. + trace_ssam_packet_complete(p, status);
  6813. +
  6814. + ptl_dbg_cond(ptl, "ptl: completing packet %p\n", p);
  6815. + if (p->ops->complete)
  6816. + p->ops->complete(p, status);
  6817. +}
  6818. +
  6819. +static void ssh_ptl_remove_and_complete(struct ssh_packet *p, int status)
  6820. +{
  6821. + /*
  6822. + * A call to this function should in general be preceeded by
  6823. + * set_bit(SSH_PACKET_SF_LOCKED_BIT, &p->flags) to avoid re-adding the
  6824. + * packet to the structures it's going to be removed from.
  6825. + *
  6826. + * The set_bit call does not need explicit memory barriers as the
  6827. + * implicit barrier of the test_and_set_bit call below ensure that the
  6828. + * flag is visible before we actually attempt to remove the packet.
  6829. + */
  6830. +
  6831. + if (test_and_set_bit(SSH_PACKET_SF_COMPLETED_BIT, &p->state))
  6832. + return;
  6833. +
  6834. + ssh_ptl_queue_remove(p);
  6835. + ssh_ptl_pending_remove(p);
  6836. +
  6837. + __ssh_ptl_complete(p, status);
  6838. +}
  6839. +
  6840. +
  6841. +static bool ssh_ptl_tx_can_process(struct ssh_packet *packet)
  6842. +{
  6843. + struct ssh_ptl *ptl = packet->ptl;
  6844. +
  6845. + if (packet->type & SSH_PACKET_TY_FLUSH)
  6846. + return !atomic_read(&ptl->pending.count);
  6847. +
  6848. + // we can alwas process non-blocking packets
  6849. + if (!(packet->type & SSH_PACKET_TY_BLOCKING))
  6850. + return true;
  6851. +
  6852. + // if we are already waiting for this packet, send it again
  6853. + if (test_bit(SSH_PACKET_SF_PENDING_BIT, &packet->state))
  6854. + return true;
  6855. +
  6856. + // otherwise: check if we have the capacity to send
  6857. + return atomic_read(&ptl->pending.count) < SSH_PTL_MAX_PENDING;
  6858. +}
  6859. +
  6860. +static struct ssh_packet *ssh_ptl_tx_pop(struct ssh_ptl *ptl)
  6861. +{
  6862. + struct ssh_packet *packet = ERR_PTR(-ENOENT);
  6863. + struct ssh_packet *p, *n;
  6864. +
  6865. + spin_lock(&ptl->queue.lock);
  6866. + list_for_each_entry_safe(p, n, &ptl->queue.head, queue_node) {
  6867. + /*
  6868. + * If we are cancelling or completing this packet, ignore it.
  6869. + * It's going to be removed from this queue shortly.
  6870. + */
  6871. + if (test_bit(SSH_PACKET_SF_LOCKED_BIT, &p->state))
  6872. + continue;
  6873. +
  6874. + /*
  6875. + * Packets should be ordered non-blocking/to-be-resent first.
  6876. + * If we cannot process this packet, assume that we can't
  6877. + * process any following packet either and abort.
  6878. + */
  6879. + if (!ssh_ptl_tx_can_process(p)) {
  6880. + packet = ERR_PTR(-EBUSY);
  6881. + break;
  6882. + }
  6883. +
  6884. + /*
  6885. + * We are allowed to change the state now. Remove it from the
  6886. + * queue and mark it as being transmitted. Note that we cannot
  6887. + * add it to the set of pending packets yet, as queue locks must
  6888. + * always be acquired before packet locks (otherwise we might
  6889. + * run into a deadlock).
  6890. + */
  6891. +
  6892. + list_del(&p->queue_node);
  6893. +
  6894. + /*
  6895. + * Ensure that the "queued" bit gets cleared after setting the
  6896. + * "transmitting" bit to guaranteee non-zero flags.
  6897. + */
  6898. + set_bit(SSH_PACKET_SF_TRANSMITTING_BIT, &p->state);
  6899. + smp_mb__before_atomic();
  6900. + clear_bit(SSH_PACKET_SF_QUEUED_BIT, &p->state);
  6901. +
  6902. + packet = p;
  6903. + break;
  6904. + }
  6905. + spin_unlock(&ptl->queue.lock);
  6906. +
  6907. + return packet;
  6908. +}
  6909. +
  6910. +static struct ssh_packet *ssh_ptl_tx_next(struct ssh_ptl *ptl)
  6911. +{
  6912. + struct ssh_packet *p;
  6913. +
  6914. + p = ssh_ptl_tx_pop(ptl);
  6915. + if (IS_ERR(p))
  6916. + return p;
  6917. +
  6918. + if (p->type & SSH_PACKET_TY_SEQUENCED) {
  6919. + ptl_dbg(ptl, "ptl: transmitting sequenced packet %p\n", p);
  6920. + ssh_ptl_pending_push(p);
  6921. + ssh_ptl_timeout_start(p);
  6922. + } else {
  6923. + ptl_dbg(ptl, "ptl: transmitting non-sequenced packet %p\n", p);
  6924. + }
  6925. +
  6926. + /*
  6927. + * Update number of tries. This directly influences the priority in case
  6928. + * the packet is re-submitted (e.g. via timeout/NAK). Note that this is
  6929. + * the only place where we update the priority in-flight. As this runs
  6930. + * only on the tx-thread, this read-modify-write procedure is safe.
  6931. + */
  6932. + WRITE_ONCE(p->priority, READ_ONCE(p->priority) + 1);
  6933. +
  6934. + return p;
  6935. +}
  6936. +
  6937. +static void ssh_ptl_tx_compl_success(struct ssh_packet *packet)
  6938. +{
  6939. + struct ssh_ptl *ptl = packet->ptl;
  6940. +
  6941. + ptl_dbg(ptl, "ptl: successfully transmitted packet %p\n", packet);
  6942. +
  6943. + /*
  6944. + * Transition to state to "transmitted". Ensure that the flags never get
  6945. + * zero with barrier.
  6946. + */
  6947. + set_bit(SSH_PACKET_SF_TRANSMITTED_BIT, &packet->state);
  6948. + smp_mb__before_atomic();
  6949. + clear_bit(SSH_PACKET_SF_TRANSMITTING_BIT, &packet->state);
  6950. +
  6951. + // if the packet is unsequenced, we're done: lock and complete
  6952. + if (!(packet->type & SSH_PACKET_TY_SEQUENCED)) {
  6953. + set_bit(SSH_PACKET_SF_LOCKED_BIT, &packet->state);
  6954. + ssh_ptl_remove_and_complete(packet, 0);
  6955. + }
  6956. +
  6957. + /*
  6958. + * Notify that a packet transmission has finished. In general we're only
  6959. + * waiting for one packet (if any), so wake_up_all should be fine.
  6960. + */
  6961. + wake_up_all(&ptl->tx.packet_wq);
  6962. +}
  6963. +
  6964. +static void ssh_ptl_tx_compl_error(struct ssh_packet *packet, int status)
  6965. +{
  6966. + /*
  6967. + * Transmission failure: Lock the packet and try to complete it. Ensure
  6968. + * that the flags never get zero with barrier.
  6969. + */
  6970. + set_bit(SSH_PACKET_SF_LOCKED_BIT, &packet->state);
  6971. + smp_mb__before_atomic();
  6972. + clear_bit(SSH_PACKET_SF_TRANSMITTING_BIT, &packet->state);
  6973. +
  6974. + ptl_err(packet->ptl, "ptl: transmission error: %d\n", status);
  6975. + ptl_dbg(packet->ptl, "ptl: failed to transmit packet: %p\n", packet);
  6976. +
  6977. + ssh_ptl_remove_and_complete(packet, status);
  6978. +
  6979. + /*
  6980. + * Notify that a packet transmission has finished. In general we're only
  6981. + * waiting for one packet (if any), so wake_up_all should be fine.
  6982. + */
  6983. + wake_up_all(&packet->ptl->tx.packet_wq);
  6984. +}
  6985. +
  6986. +static void ssh_ptl_tx_threadfn_wait(struct ssh_ptl *ptl)
  6987. +{
  6988. + wait_event_interruptible(ptl->tx.thread_wq,
  6989. + READ_ONCE(ptl->tx.thread_signal) || kthread_should_stop());
  6990. + WRITE_ONCE(ptl->tx.thread_signal, false);
  6991. +}
  6992. +
  6993. +static int ssh_ptl_tx_threadfn(void *data)
  6994. +{
  6995. + struct ssh_ptl *ptl = data;
  6996. +
  6997. + while (!kthread_should_stop()) {
  6998. + unsigned char *buf;
  6999. + bool drop = false;
  7000. + size_t len = 0;
  7001. + int status = 0;
  7002. +
  7003. + // if we don't have a packet, get the next and add it to pending
  7004. + if (IS_ERR_OR_NULL(ptl->tx.packet)) {
  7005. + ptl->tx.packet = ssh_ptl_tx_next(ptl);
  7006. + ptl->tx.offset = 0;
  7007. +
  7008. + // if no packet is available, we are done
  7009. + if (IS_ERR(ptl->tx.packet)) {
  7010. + ssh_ptl_tx_threadfn_wait(ptl);
  7011. + continue;
  7012. + }
  7013. + }
  7014. +
  7015. + // error injection: drop packet to simulate transmission problem
  7016. + if (ptl->tx.offset == 0)
  7017. + drop = ssh_ptl_should_drop_packet(ptl->tx.packet);
  7018. +
  7019. + // error injection: simulate invalid packet data
  7020. + if (ptl->tx.offset == 0 && !drop)
  7021. + ssh_ptl_tx_inject_invalid_data(ptl->tx.packet);
  7022. +
  7023. + // flush-packets don't have any data
  7024. + if (likely(ptl->tx.packet->data && !drop)) {
  7025. + buf = ptl->tx.packet->data + ptl->tx.offset;
  7026. + len = ptl->tx.packet->data_length - ptl->tx.offset;
  7027. +
  7028. + ptl_dbg(ptl, "tx: sending data (length: %zu)\n", len);
  7029. + print_hex_dump_debug("tx: ", DUMP_PREFIX_OFFSET, 16, 1,
  7030. + buf, len, false);
  7031. +
  7032. + status = ssh_ptl_write_buf(ptl, ptl->tx.packet, buf, len);
  7033. + }
  7034. +
  7035. + if (status < 0) {
  7036. + // complete packet with error
  7037. + ssh_ptl_tx_compl_error(ptl->tx.packet, status);
  7038. + ssh_packet_put(ptl->tx.packet);
  7039. + ptl->tx.packet = NULL;
  7040. +
  7041. + } else if (status == len) {
  7042. + // complete packet and/or mark as transmitted
  7043. + ssh_ptl_tx_compl_success(ptl->tx.packet);
  7044. + ssh_packet_put(ptl->tx.packet);
  7045. + ptl->tx.packet = NULL;
  7046. +
  7047. + } else { // need more buffer space
  7048. + ptl->tx.offset += status;
  7049. + ssh_ptl_tx_threadfn_wait(ptl);
  7050. + }
  7051. + }
  7052. +
  7053. + // cancel active packet before we actually stop
  7054. + if (!IS_ERR_OR_NULL(ptl->tx.packet)) {
  7055. + ssh_ptl_tx_compl_error(ptl->tx.packet, -ESHUTDOWN);
  7056. + ssh_packet_put(ptl->tx.packet);
  7057. + ptl->tx.packet = NULL;
  7058. + }
  7059. +
  7060. + return 0;
  7061. +}
  7062. +
  7063. +static inline void ssh_ptl_tx_wakeup(struct ssh_ptl *ptl, bool force)
  7064. +{
  7065. + if (test_bit(SSH_PTL_SF_SHUTDOWN_BIT, &ptl->state))
  7066. + return;
  7067. +
  7068. + if (force || atomic_read(&ptl->pending.count) < SSH_PTL_MAX_PENDING) {
  7069. + WRITE_ONCE(ptl->tx.thread_signal, true);
  7070. + smp_mb__after_atomic();
  7071. + wake_up(&ptl->tx.thread_wq);
  7072. + }
  7073. +}
  7074. +
  7075. +static int ssh_ptl_tx_start(struct ssh_ptl *ptl)
  7076. +{
  7077. + ptl->tx.thread = kthread_run(ssh_ptl_tx_threadfn, ptl, "surface-sh-tx");
  7078. + if (IS_ERR(ptl->tx.thread))
  7079. + return PTR_ERR(ptl->tx.thread);
  7080. +
  7081. + return 0;
  7082. +}
  7083. +
  7084. +static int ssh_ptl_tx_stop(struct ssh_ptl *ptl)
  7085. +{
  7086. + int status = 0;
  7087. +
  7088. + if (ptl->tx.thread) {
  7089. + status = kthread_stop(ptl->tx.thread);
  7090. + ptl->tx.thread = NULL;
  7091. + }
  7092. +
  7093. + return status;
  7094. +}
  7095. +
  7096. +
  7097. +static struct ssh_packet *ssh_ptl_ack_pop(struct ssh_ptl *ptl, u8 seq_id)
  7098. +{
  7099. + struct ssh_packet *packet = ERR_PTR(-ENOENT);
  7100. + struct ssh_packet *p, *n;
  7101. +
  7102. + spin_lock(&ptl->pending.lock);
  7103. + list_for_each_entry_safe(p, n, &ptl->pending.head, pending_node) {
  7104. + /*
  7105. + * We generally expect packets to be in order, so first packet
  7106. + * to be added to pending is first to be sent, is first to be
  7107. + * ACKed.
  7108. + */
  7109. + if (unlikely(ssh_packet_get_seq(p) != seq_id))
  7110. + continue;
  7111. +
  7112. + /*
  7113. + * In case we receive an ACK while handling a transmission error
  7114. + * completion. The packet will be removed shortly.
  7115. + */
  7116. + if (unlikely(test_bit(SSH_PACKET_SF_LOCKED_BIT, &p->state))) {
  7117. + packet = ERR_PTR(-EPERM);
  7118. + break;
  7119. + }
  7120. +
  7121. + /*
  7122. + * Mark packet as ACKed and remove it from pending. Ensure that
  7123. + * the flags never get zero with barrier.
  7124. + */
  7125. + set_bit(SSH_PACKET_SF_ACKED_BIT, &p->state);
  7126. + smp_mb__before_atomic();
  7127. + clear_bit(SSH_PACKET_SF_PENDING_BIT, &p->state);
  7128. +
  7129. + atomic_dec(&ptl->pending.count);
  7130. + list_del(&p->pending_node);
  7131. + packet = p;
  7132. +
  7133. + break;
  7134. + }
  7135. + spin_unlock(&ptl->pending.lock);
  7136. +
  7137. + return packet;
  7138. +}
  7139. +
  7140. +static void ssh_ptl_wait_until_transmitted(struct ssh_packet *packet)
  7141. +{
  7142. + wait_event(packet->ptl->tx.packet_wq,
  7143. + test_bit(SSH_PACKET_SF_TRANSMITTED_BIT, &packet->state)
  7144. + || test_bit(SSH_PACKET_SF_LOCKED_BIT, &packet->state));
  7145. +}
  7146. +
  7147. +static void ssh_ptl_acknowledge(struct ssh_ptl *ptl, u8 seq)
  7148. +{
  7149. + struct ssh_packet *p;
  7150. + int status = 0;
  7151. +
  7152. + p = ssh_ptl_ack_pop(ptl, seq);
  7153. + if (IS_ERR(p)) {
  7154. + if (PTR_ERR(p) == -ENOENT) {
  7155. + /*
  7156. + * The packet has not been found in the set of pending
  7157. + * packets.
  7158. + */
  7159. + ptl_warn(ptl, "ptl: received ACK for non-pending"
  7160. + " packet\n");
  7161. + } else {
  7162. + /*
  7163. + * The packet is pending, but we are not allowed to take
  7164. + * it because it has been locked.
  7165. + */
  7166. + }
  7167. + return;
  7168. + }
  7169. +
  7170. + ptl_dbg(ptl, "ptl: received ACK for packet %p\n", p);
  7171. +
  7172. + /*
  7173. + * It is possible that the packet has been transmitted, but the state
  7174. + * has not been updated from "transmitting" to "transmitted" yet.
  7175. + * In that case, we need to wait for this transition to occur in order
  7176. + * to determine between success or failure.
  7177. + */
  7178. + if (test_bit(SSH_PACKET_SF_TRANSMITTING_BIT, &p->state))
  7179. + ssh_ptl_wait_until_transmitted(p);
  7180. +
  7181. + /*
  7182. + * The packet will already be locked in case of a transmission error or
  7183. + * cancellation. Let the transmitter or cancellation issuer complete the
  7184. + * packet.
  7185. + */
  7186. + if (unlikely(test_and_set_bit(SSH_PACKET_SF_LOCKED_BIT, &p->state))) {
  7187. + ssh_packet_put(p);
  7188. + return;
  7189. + }
  7190. +
  7191. + if (unlikely(!test_bit(SSH_PACKET_SF_TRANSMITTED_BIT, &p->state))) {
  7192. + ptl_err(ptl, "ptl: received ACK before packet had been fully"
  7193. + " transmitted\n");
  7194. + status = -EREMOTEIO;
  7195. + }
  7196. +
  7197. + ssh_ptl_remove_and_complete(p, status);
  7198. + ssh_packet_put(p);
  7199. +
  7200. + ssh_ptl_tx_wakeup(ptl, false);
  7201. +}
  7202. +
  7203. +
  7204. +static int ssh_ptl_submit(struct ssh_ptl *ptl, struct ssh_packet *packet)
  7205. +{
  7206. + int status;
  7207. +
  7208. + trace_ssam_packet_submit(packet);
  7209. +
  7210. + // validate packet fields
  7211. + if (packet->type & SSH_PACKET_TY_FLUSH) {
  7212. + if (packet->data || (packet->type & SSH_PACKET_TY_SEQUENCED))
  7213. + return -EINVAL;
  7214. + } else if (!packet->data) {
  7215. + return -EINVAL;
  7216. + }
  7217. +
  7218. + /*
  7219. + * This function is currently not intended for re-submission. The ptl
  7220. + * reference only gets set on the first submission. After the first
  7221. + * submission, it has to be read-only.
  7222. + *
  7223. + * Use cmpxchg to ensure safety with regards to ssh_ptl_cancel and
  7224. + * re-entry, where we can't guarantee that the packet has been submitted
  7225. + * yet.
  7226. + *
  7227. + * The implicit barrier of cmpxchg is paired with barrier in
  7228. + * ssh_ptl_cancel to guarantee cancelation in case the packet has never
  7229. + * been submitted or is currently being submitted.
  7230. + */
  7231. + if (cmpxchg(&packet->ptl, NULL, ptl) != NULL)
  7232. + return -EALREADY;
  7233. +
  7234. + status = ssh_ptl_queue_push(packet);
  7235. + if (status)
  7236. + return status;
  7237. +
  7238. + ssh_ptl_tx_wakeup(ptl, !(packet->type & SSH_PACKET_TY_BLOCKING));
  7239. + return 0;
  7240. +}
  7241. +
  7242. +static void __ssh_ptl_resubmit(struct ssh_packet *packet)
  7243. +{
  7244. + struct list_head *head;
  7245. +
  7246. + trace_ssam_packet_resubmit(packet);
  7247. +
  7248. + spin_lock(&packet->ptl->queue.lock);
  7249. +
  7250. + // if this packet has already been queued, do not add it
  7251. + if (test_and_set_bit(SSH_PACKET_SF_QUEUED_BIT, &packet->state)) {
  7252. + spin_unlock(&packet->ptl->queue.lock);
  7253. + return;
  7254. + }
  7255. +
  7256. + // find first node with lower priority
  7257. + head = __ssh_ptl_queue_find_entrypoint(packet);
  7258. +
  7259. + WRITE_ONCE(packet->timestamp, KTIME_MAX);
  7260. + smp_mb__after_atomic();
  7261. +
  7262. + // add packet
  7263. + ssh_packet_get(packet);
  7264. + list_add_tail(&packet->queue_node, head);
  7265. +
  7266. + spin_unlock(&packet->ptl->queue.lock);
  7267. +}
  7268. +
  7269. +static void ssh_ptl_resubmit_pending(struct ssh_ptl *ptl)
  7270. +{
  7271. + struct ssh_packet *p;
  7272. + bool resub = false;
  7273. + u8 try;
  7274. +
  7275. + /*
  7276. + * Note: We deliberately do not remove/attempt to cancel and complete
  7277. + * packets that are out of tires in this function. The packet will be
  7278. + * eventually canceled and completed by the timeout. Removing the packet
  7279. + * here could lead to overly eager cancelation if the packet has not
  7280. + * been re-transmitted yet but the tries-counter already updated (i.e
  7281. + * ssh_ptl_tx_next removed the packet from the queue and updated the
  7282. + * counter, but re-transmission for the last try has not actually
  7283. + * started yet).
  7284. + */
  7285. +
  7286. + spin_lock(&ptl->pending.lock);
  7287. +
  7288. + // re-queue all pending packets
  7289. + list_for_each_entry(p, &ptl->pending.head, pending_node) {
  7290. + // avoid further transitions if locked
  7291. + if (test_bit(SSH_PACKET_SF_LOCKED_BIT, &p->state))
  7292. + continue;
  7293. +
  7294. + // do not re-schedule if packet is out of tries
  7295. + try = ssh_packet_priority_get_try(READ_ONCE(p->priority));
  7296. + if (try >= SSH_PTL_MAX_PACKET_TRIES)
  7297. + continue;
  7298. +
  7299. + resub = true;
  7300. + __ssh_ptl_resubmit(p);
  7301. + }
  7302. +
  7303. + spin_unlock(&ptl->pending.lock);
  7304. +
  7305. + ssh_ptl_tx_wakeup(ptl, resub);
  7306. +}
  7307. +
  7308. +static void ssh_ptl_cancel(struct ssh_packet *p)
  7309. +{
  7310. + if (test_and_set_bit(SSH_PACKET_SF_CANCELED_BIT, &p->state))
  7311. + return;
  7312. +
  7313. + trace_ssam_packet_cancel(p);
  7314. +
  7315. + /*
  7316. + * Lock packet and commit with memory barrier. If this packet has
  7317. + * already been locked, it's going to be removed and completed by
  7318. + * another party, which should have precedence.
  7319. + */
  7320. + if (test_and_set_bit(SSH_PACKET_SF_LOCKED_BIT, &p->state))
  7321. + return;
  7322. +
  7323. + /*
  7324. + * By marking the packet as locked and employing the implicit memory
  7325. + * barrier of test_and_set_bit, we have guaranteed that, at this point,
  7326. + * the packet cannot be added to the queue any more.
  7327. + *
  7328. + * In case the packet has never been submitted, packet->ptl is NULL. If
  7329. + * the packet is currently being submitted, packet->ptl may be NULL or
  7330. + * non-NULL. Due marking the packet as locked above and committing with
  7331. + * the memory barrier, we have guaranteed that, if packet->ptl is NULL,
  7332. + * the packet will never be added to the queue. If packet->ptl is
  7333. + * non-NULL, we don't have any guarantees.
  7334. + */
  7335. +
  7336. + if (READ_ONCE(p->ptl)) {
  7337. + ssh_ptl_remove_and_complete(p, -ECANCELED);
  7338. + ssh_ptl_tx_wakeup(p->ptl, false);
  7339. + } else if (!test_and_set_bit(SSH_PACKET_SF_COMPLETED_BIT, &p->state)) {
  7340. + __ssh_ptl_complete(p, -ECANCELED);
  7341. + }
  7342. +}
  7343. +
  7344. +
  7345. +static ktime_t ssh_packet_get_expiration(struct ssh_packet *p, ktime_t timeout)
  7346. +{
  7347. + ktime_t timestamp = READ_ONCE(p->timestamp);
  7348. +
  7349. + if (timestamp != KTIME_MAX)
  7350. + return ktime_add(timestamp, timeout);
  7351. + else
  7352. + return KTIME_MAX;
  7353. +}
  7354. +
  7355. +static void ssh_ptl_timeout_reap(struct work_struct *work)
  7356. +{
  7357. + struct ssh_ptl *ptl = to_ssh_ptl(work, rtx_timeout.reaper.work);
  7358. + struct ssh_packet *p, *n;
  7359. + LIST_HEAD(claimed);
  7360. + ktime_t now = ktime_get_coarse_boottime();
  7361. + ktime_t timeout = ptl->rtx_timeout.timeout;
  7362. + ktime_t next = KTIME_MAX;
  7363. + bool resub = false;
  7364. +
  7365. + trace_ssam_ptl_timeout_reap("pending", atomic_read(&ptl->pending.count));
  7366. +
  7367. + /*
  7368. + * Mark reaper as "not pending". This is done before checking any
  7369. + * packets to avoid lost-update type problems.
  7370. + */
  7371. + WRITE_ONCE(ptl->rtx_timeout.expires, KTIME_MAX);
  7372. + smp_mb__after_atomic();
  7373. +
  7374. + spin_lock(&ptl->pending.lock);
  7375. +
  7376. + list_for_each_entry_safe(p, n, &ptl->pending.head, pending_node) {
  7377. + ktime_t expires = ssh_packet_get_expiration(p, timeout);
  7378. + u8 try;
  7379. +
  7380. + /*
  7381. + * Check if the timeout hasn't expired yet. Find out next
  7382. + * expiration date to be handled after this run.
  7383. + */
  7384. + if (ktime_after(expires, now)) {
  7385. + next = ktime_before(expires, next) ? expires : next;
  7386. + continue;
  7387. + }
  7388. +
  7389. + // avoid further transitions if locked
  7390. + if (test_bit(SSH_PACKET_SF_LOCKED_BIT, &p->state))
  7391. + continue;
  7392. +
  7393. + trace_ssam_packet_timeout(p);
  7394. +
  7395. + // check if we still have some tries left
  7396. + try = ssh_packet_priority_get_try(READ_ONCE(p->priority));
  7397. + if (likely(try < SSH_PTL_MAX_PACKET_TRIES)) {
  7398. + resub = true;
  7399. + __ssh_ptl_resubmit(p);
  7400. + continue;
  7401. + }
  7402. +
  7403. + // no more tries left: cancel the packet
  7404. +
  7405. + // if someone else has locked the packet already, don't use it
  7406. + if (test_and_set_bit(SSH_PACKET_SF_LOCKED_BIT, &p->state))
  7407. + continue;
  7408. +
  7409. + /*
  7410. + * We have now marked the packet as locked. Thus it cannot be
  7411. + * added to the pending list again after we've removed it here.
  7412. + * We can therefore re-use the pending_node of this packet
  7413. + * temporarily.
  7414. + */
  7415. +
  7416. + clear_bit(SSH_PACKET_SF_PENDING_BIT, &p->state);
  7417. +
  7418. + atomic_dec(&ptl->pending.count);
  7419. + list_del(&p->pending_node);
  7420. +
  7421. + list_add_tail(&p->pending_node, &claimed);
  7422. + }
  7423. +
  7424. + spin_unlock(&ptl->pending.lock);
  7425. +
  7426. + // cancel and complete the packet
  7427. + list_for_each_entry_safe(p, n, &claimed, pending_node) {
  7428. + if (!test_and_set_bit(SSH_PACKET_SF_COMPLETED_BIT, &p->state)) {
  7429. + ssh_ptl_queue_remove(p);
  7430. + __ssh_ptl_complete(p, -ETIMEDOUT);
  7431. + }
  7432. +
  7433. + // drop the reference we've obtained by removing it from pending
  7434. + list_del(&p->pending_node);
  7435. + ssh_packet_put(p);
  7436. + }
  7437. +
  7438. + // ensure that reaper doesn't run again immediately
  7439. + next = max(next, ktime_add(now, SSH_PTL_PACKET_TIMEOUT_RESOLUTION));
  7440. + if (next != KTIME_MAX)
  7441. + ssh_ptl_timeout_reaper_mod(ptl, now, next);
  7442. +
  7443. + // force-wakeup to properly handle re-transmits if we've re-submitted
  7444. + ssh_ptl_tx_wakeup(ptl, resub);
  7445. +}
  7446. +
  7447. +
  7448. +static bool ssh_ptl_rx_blacklist_check(struct ssh_ptl *ptl, u8 seq)
  7449. +{
  7450. + int i;
  7451. +
  7452. + // check if SEQ is blacklisted
  7453. + for (i = 0; i < ARRAY_SIZE(ptl->rx.blacklist.seqs); i++) {
  7454. + if (likely(ptl->rx.blacklist.seqs[i] != seq))
  7455. + continue;
  7456. +
  7457. + ptl_dbg(ptl, "ptl: ignoring repeated data packet\n");
  7458. + return true;
  7459. + }
  7460. +
  7461. + // update blacklist
  7462. + ptl->rx.blacklist.seqs[ptl->rx.blacklist.offset] = seq;
  7463. + ptl->rx.blacklist.offset = (ptl->rx.blacklist.offset + 1)
  7464. + % ARRAY_SIZE(ptl->rx.blacklist.seqs);
  7465. +
  7466. + return false;
  7467. +}
  7468. +
  7469. +static void ssh_ptl_rx_dataframe(struct ssh_ptl *ptl,
  7470. + const struct ssh_frame *frame,
  7471. + const struct sshp_span *payload)
  7472. +{
  7473. + if (ssh_ptl_rx_blacklist_check(ptl, frame->seq))
  7474. + return;
  7475. +
  7476. + ptl->ops.data_received(ptl, payload);
  7477. +}
  7478. +
  7479. +static void ssh_ptl_send_ack(struct ssh_ptl *ptl, u8 seq)
  7480. +{
  7481. + struct ssh_packet_args args;
  7482. + struct ssh_packet *packet;
  7483. + struct msgbuf msgb;
  7484. +
  7485. + args.type = 0;
  7486. + args.priority = SSH_PACKET_PRIORITY(ACK, 0);
  7487. + args.ops = &ssh_ptl_ctrl_packet_ops;
  7488. +
  7489. + packet = ptl_alloc_ctrl_packet(ptl, &args, GFP_KERNEL);
  7490. + if (!packet) {
  7491. + ptl_err(ptl, "ptl: failed to allocate ACK packet\n");
  7492. + return;
  7493. + }
  7494. +
  7495. + msgb_init(&msgb, packet->data, packet->data_length);
  7496. + msgb_push_ack(&msgb, seq);
  7497. + packet->data_length = msgb_bytes_used(&msgb);
  7498. +
  7499. + ssh_ptl_submit(ptl, packet);
  7500. + ssh_packet_put(packet);
  7501. +}
  7502. +
  7503. +static void ssh_ptl_send_nak(struct ssh_ptl *ptl)
  7504. +{
  7505. + struct ssh_packet_args args;
  7506. + struct ssh_packet *packet;
  7507. + struct msgbuf msgb;
  7508. +
  7509. + args.type = 0;
  7510. + args.priority = SSH_PACKET_PRIORITY(NAK, 0);
  7511. + args.ops = &ssh_ptl_ctrl_packet_ops;
  7512. +
  7513. + packet = ptl_alloc_ctrl_packet(ptl, &args, GFP_KERNEL);
  7514. + if (!packet) {
  7515. + ptl_err(ptl, "ptl: failed to allocate NAK packet\n");
  7516. + return;
  7517. + }
  7518. +
  7519. + msgb_init(&msgb, packet->data, packet->data_length);
  7520. + msgb_push_nak(&msgb);
  7521. + packet->data_length = msgb_bytes_used(&msgb);
  7522. +
  7523. + ssh_ptl_submit(ptl, packet);
  7524. + ssh_packet_put(packet);
  7525. +}
  7526. +
  7527. +static size_t ssh_ptl_rx_eval(struct ssh_ptl *ptl, struct sshp_span *source)
  7528. +{
  7529. + struct ssh_frame *frame;
  7530. + struct sshp_span payload;
  7531. + struct sshp_span aligned;
  7532. + bool syn_found;
  7533. + int status;
  7534. +
  7535. + // error injection: modify data to simulate corrupt SYN bytes
  7536. + ssh_ptl_rx_inject_invalid_syn(ptl, source);
  7537. +
  7538. + // find SYN
  7539. + syn_found = sshp_find_syn(source, &aligned);
  7540. +
  7541. + if (unlikely(aligned.ptr - source->ptr) > 0) {
  7542. + ptl_warn(ptl, "rx: parser: invalid start of frame, skipping\n");
  7543. +
  7544. + /*
  7545. + * Notes:
  7546. + * - This might send multiple NAKs in case the communication
  7547. + * starts with an invalid SYN and is broken down into multiple
  7548. + * pieces. This should generally be handled fine, we just
  7549. + * might receive duplicate data in this case, which is
  7550. + * detected when handling data frames.
  7551. + * - This path will also be executed on invalid CRCs: When an
  7552. + * invalid CRC is encountered, the code below will skip data
  7553. + * until direclty after the SYN. This causes the search for
  7554. + * the next SYN, which is generally not placed directly after
  7555. + * the last one.
  7556. + */
  7557. + ssh_ptl_send_nak(ptl);
  7558. + }
  7559. +
  7560. + if (unlikely(!syn_found))
  7561. + return aligned.ptr - source->ptr;
  7562. +
  7563. + // error injection: modify data to simulate corruption
  7564. + ssh_ptl_rx_inject_invalid_data(ptl, &aligned);
  7565. +
  7566. + // parse and validate frame
  7567. + status = sshp_parse_frame(&ptl->serdev->dev, &aligned, &frame, &payload,
  7568. + SSH_PTL_RX_BUF_LEN);
  7569. + if (status) // invalid frame: skip to next syn
  7570. + return aligned.ptr - source->ptr + sizeof(u16);
  7571. + if (!frame) // not enough data
  7572. + return aligned.ptr - source->ptr;
  7573. +
  7574. + trace_ssam_rx_frame_received(frame);
  7575. +
  7576. + switch (frame->type) {
  7577. + case SSH_FRAME_TYPE_ACK:
  7578. + ssh_ptl_acknowledge(ptl, frame->seq);
  7579. + break;
  7580. +
  7581. + case SSH_FRAME_TYPE_NAK:
  7582. + ssh_ptl_resubmit_pending(ptl);
  7583. + break;
  7584. +
  7585. + case SSH_FRAME_TYPE_DATA_SEQ:
  7586. + ssh_ptl_send_ack(ptl, frame->seq);
  7587. + /* fallthrough */
  7588. +
  7589. + case SSH_FRAME_TYPE_DATA_NSQ:
  7590. + ssh_ptl_rx_dataframe(ptl, frame, &payload);
  7591. + break;
  7592. +
  7593. + default:
  7594. + ptl_warn(ptl, "ptl: received frame with unknown type 0x%02x\n",
  7595. + frame->type);
  7596. + break;
  7597. + }
  7598. +
  7599. + return aligned.ptr - source->ptr + SSH_MESSAGE_LENGTH(frame->len);
  7600. +}
  7601. +
  7602. +static int ssh_ptl_rx_threadfn(void *data)
  7603. +{
  7604. + struct ssh_ptl *ptl = data;
  7605. +
  7606. + while (true) {
  7607. + struct sshp_span span;
  7608. + size_t offs = 0;
  7609. + size_t n;
  7610. +
  7611. + wait_event_interruptible(ptl->rx.wq,
  7612. + !kfifo_is_empty(&ptl->rx.fifo)
  7613. + || kthread_should_stop());
  7614. + if (kthread_should_stop())
  7615. + break;
  7616. +
  7617. + // copy from fifo to evaluation buffer
  7618. + n = sshp_buf_read_from_fifo(&ptl->rx.buf, &ptl->rx.fifo);
  7619. +
  7620. + ptl_dbg(ptl, "rx: received data (size: %zu)\n", n);
  7621. + print_hex_dump_debug("rx: ", DUMP_PREFIX_OFFSET, 16, 1,
  7622. + ptl->rx.buf.ptr + ptl->rx.buf.len - n,
  7623. + n, false);
  7624. +
  7625. + // parse until we need more bytes or buffer is empty
  7626. + while (offs < ptl->rx.buf.len) {
  7627. + sshp_buf_span_from(&ptl->rx.buf, offs, &span);
  7628. + n = ssh_ptl_rx_eval(ptl, &span);
  7629. + if (n == 0)
  7630. + break; // need more bytes
  7631. +
  7632. + offs += n;
  7633. + }
  7634. +
  7635. + // throw away the evaluated parts
  7636. + sshp_buf_drop(&ptl->rx.buf, offs);
  7637. + }
  7638. +
  7639. + return 0;
  7640. +}
  7641. +
  7642. +static inline void ssh_ptl_rx_wakeup(struct ssh_ptl *ptl)
  7643. +{
  7644. + wake_up(&ptl->rx.wq);
  7645. +}
  7646. +
  7647. +static int ssh_ptl_rx_start(struct ssh_ptl *ptl)
  7648. +{
  7649. + if (ptl->rx.thread)
  7650. + return 0;
  7651. +
  7652. + ptl->rx.thread = kthread_run(ssh_ptl_rx_threadfn, ptl, "surface-sh-rx");
  7653. + if (IS_ERR(ptl->rx.thread))
  7654. + return PTR_ERR(ptl->rx.thread);
  7655. +
  7656. + return 0;
  7657. +}
  7658. +
  7659. +static int ssh_ptl_rx_stop(struct ssh_ptl *ptl)
  7660. +{
  7661. + int status = 0;
  7662. +
  7663. + if (ptl->rx.thread) {
  7664. + status = kthread_stop(ptl->rx.thread);
  7665. + ptl->rx.thread = NULL;
  7666. + }
  7667. +
  7668. + return status;
  7669. +}
  7670. +
  7671. +static int ssh_ptl_rx_rcvbuf(struct ssh_ptl *ptl, const u8 *buf, size_t n)
  7672. +{
  7673. + int used;
  7674. +
  7675. + if (test_bit(SSH_PTL_SF_SHUTDOWN_BIT, &ptl->state))
  7676. + return used;
  7677. +
  7678. + used = kfifo_in(&ptl->rx.fifo, buf, n);
  7679. + if (used)
  7680. + ssh_ptl_rx_wakeup(ptl);
  7681. +
  7682. + return used;
  7683. +}
  7684. +
  7685. +
  7686. +struct ssh_flush_packet {
  7687. + struct ssh_packet base;
  7688. + struct completion completion;
  7689. + int status;
  7690. +};
  7691. +
  7692. +static void ssh_ptl_flush_complete(struct ssh_packet *p, int status)
  7693. +{
  7694. + struct ssh_flush_packet *packet;
  7695. +
  7696. + packet = container_of(p, struct ssh_flush_packet, base);
  7697. + packet->status = status;
  7698. +}
  7699. +
  7700. +static void ssh_ptl_flush_release(struct ssh_packet *p)
  7701. +{
  7702. + struct ssh_flush_packet *packet;
  7703. +
  7704. + packet = container_of(p, struct ssh_flush_packet, base);
  7705. + complete_all(&packet->completion);
  7706. +}
  7707. +
  7708. +static const struct ssh_packet_ops ssh_flush_packet_ops = {
  7709. + .complete = ssh_ptl_flush_complete,
  7710. + .release = ssh_ptl_flush_release,
  7711. +};
  7712. +
  7713. +/**
  7714. + * ssh_ptl_flush - flush the packet transmission layer
  7715. + * @ptl: packet transmission layer
  7716. + * @timeout: timeout for the flush operation in jiffies
  7717. + *
  7718. + * Queue a special flush-packet and wait for its completion. This packet will
  7719. + * be completed after all other currently queued and pending packets have been
  7720. + * completed. Flushing guarantees that all previously submitted data packets
  7721. + * have been fully completed before this call returns. Additionally, flushing
  7722. + * blocks execution of all later submitted data packets until the flush has been
  7723. + * completed.
  7724. + *
  7725. + * Control (i.e. ACK/NAK) packets that have been submitted after this call will
  7726. + * be placed before the flush packet in the queue, as long as the flush-packet
  7727. + * has not been chosen for processing yet.
  7728. + *
  7729. + * Flushing, even when no new data packets are submitted after this call, does
  7730. + * not guarantee that no more packets are scheduled. For example, incoming
  7731. + * messages can promt automated submission of ACK or NAK type packets. If this
  7732. + * happens while the flush-packet is being processed (i.e. after it has been
  7733. + * taken from the queue), such packets may still be queued after this function
  7734. + * returns.
  7735. + *
  7736. + * Return: Zero on success, -ETIMEDOUT if the flush timed out and has been
  7737. + * canceled as a result of the timeout, or -ESHUTDOWN if the packet transmission
  7738. + * layer has been shut down before this call. May also return -EINTR if the
  7739. + * packet transmission has been interrupted.
  7740. + */
  7741. +static int ssh_ptl_flush(struct ssh_ptl *ptl, unsigned long timeout)
  7742. +{
  7743. + struct ssh_flush_packet packet;
  7744. + struct ssh_packet_args args;
  7745. + int status;
  7746. +
  7747. + args.type = SSH_PACKET_TY_FLUSH | SSH_PACKET_TY_BLOCKING;
  7748. + args.priority = SSH_PACKET_PRIORITY(FLUSH, 0);
  7749. + args.ops = &ssh_flush_packet_ops;
  7750. +
  7751. + ssh_packet_init(&packet.base, &args);
  7752. + init_completion(&packet.completion);
  7753. +
  7754. + status = ssh_ptl_submit(ptl, &packet.base);
  7755. + if (status)
  7756. + return status;
  7757. +
  7758. + ssh_packet_put(&packet.base);
  7759. +
  7760. + if (wait_for_completion_timeout(&packet.completion, timeout))
  7761. + return 0;
  7762. +
  7763. + ssh_ptl_cancel(&packet.base);
  7764. + wait_for_completion(&packet.completion);
  7765. +
  7766. + WARN_ON(packet.status != 0 && packet.status != -ECANCELED
  7767. + && packet.status != -ESHUTDOWN && packet.status != -EINTR);
  7768. +
  7769. + return packet.status == -ECANCELED ? -ETIMEDOUT : status;
  7770. +}
  7771. +
  7772. +/**
  7773. + * ssh_ptl_shutdown - shut down the packet transmission layer
  7774. + * @ptl: packet transmission layer
  7775. + *
  7776. + * Shuts down the packet transmission layer, removing and canceling all queued
  7777. + * and pending packets. Packets canceled by this operation will be completed
  7778. + * with -ESHUTDOWN as status.
  7779. + *
  7780. + * As a result of this function, the transmission layer will be marked as shut
  7781. + * down. Submission of packets after the transmission layer has been shut down
  7782. + * will fail with -ESHUTDOWN.
  7783. + */
  7784. +static void ssh_ptl_shutdown(struct ssh_ptl *ptl)
  7785. +{
  7786. + LIST_HEAD(complete_q);
  7787. + LIST_HEAD(complete_p);
  7788. + struct ssh_packet *p, *n;
  7789. + int status;
  7790. +
  7791. + // ensure that no new packets (including ACK/NAK) can be submitted
  7792. + set_bit(SSH_PTL_SF_SHUTDOWN_BIT, &ptl->state);
  7793. + smp_mb__after_atomic();
  7794. +
  7795. + status = ssh_ptl_rx_stop(ptl);
  7796. + if (status)
  7797. + ptl_err(ptl, "ptl: failed to stop receiver thread\n");
  7798. +
  7799. + status = ssh_ptl_tx_stop(ptl);
  7800. + if (status)
  7801. + ptl_err(ptl, "ptl: failed to stop transmitter thread\n");
  7802. +
  7803. + cancel_delayed_work_sync(&ptl->rtx_timeout.reaper);
  7804. +
  7805. + /*
  7806. + * At this point, all threads have been stopped. This means that the
  7807. + * only references to packets from inside the system are in the queue
  7808. + * and pending set.
  7809. + *
  7810. + * Note: We still need locks here because someone could still be
  7811. + * cancelling packets.
  7812. + *
  7813. + * Note 2: We can re-use queue_node (or pending_node) if we mark the
  7814. + * packet as locked an then remove it from the queue (or pending set
  7815. + * respecitvely). Marking the packet as locked avoids re-queueing
  7816. + * (which should already be prevented by having stopped the treads...)
  7817. + * and not setting QUEUED_BIT (or PENDING_BIT) prevents removal from a
  7818. + * new list via other threads (e.g. canellation).
  7819. + *
  7820. + * Note 3: There may be overlap between complete_p and complete_q.
  7821. + * This is handled via test_and_set_bit on the "completed" flag
  7822. + * (also handles cancelation).
  7823. + */
  7824. +
  7825. + // mark queued packets as locked and move them to complete_q
  7826. + spin_lock(&ptl->queue.lock);
  7827. + list_for_each_entry_safe(p, n, &ptl->queue.head, queue_node) {
  7828. + set_bit(SSH_PACKET_SF_LOCKED_BIT, &p->state);
  7829. + smp_mb__before_atomic();
  7830. + clear_bit(SSH_PACKET_SF_QUEUED_BIT, &p->state);
  7831. +
  7832. + list_del(&p->queue_node);
  7833. + list_add_tail(&p->queue_node, &complete_q);
  7834. + }
  7835. + spin_unlock(&ptl->queue.lock);
  7836. +
  7837. + // mark pending packets as locked and move them to complete_p
  7838. + spin_lock(&ptl->pending.lock);
  7839. + list_for_each_entry_safe(p, n, &ptl->pending.head, pending_node) {
  7840. + set_bit(SSH_PACKET_SF_LOCKED_BIT, &p->state);
  7841. + smp_mb__before_atomic();
  7842. + clear_bit(SSH_PACKET_SF_PENDING_BIT, &p->state);
  7843. +
  7844. + list_del(&p->pending_node);
  7845. + list_add_tail(&p->pending_node, &complete_q);
  7846. + }
  7847. + atomic_set(&ptl->pending.count, 0);
  7848. + spin_unlock(&ptl->pending.lock);
  7849. +
  7850. + // complete and drop packets on complete_q
  7851. + list_for_each_entry(p, &complete_q, queue_node) {
  7852. + if (!test_and_set_bit(SSH_PACKET_SF_COMPLETED_BIT, &p->state))
  7853. + __ssh_ptl_complete(p, -ESHUTDOWN);
  7854. +
  7855. + ssh_packet_put(p);
  7856. + }
  7857. +
  7858. + // complete and drop packets on complete_p
  7859. + list_for_each_entry(p, &complete_p, pending_node) {
  7860. + if (!test_and_set_bit(SSH_PACKET_SF_COMPLETED_BIT, &p->state))
  7861. + __ssh_ptl_complete(p, -ESHUTDOWN);
  7862. +
  7863. + ssh_packet_put(p);
  7864. + }
  7865. +
  7866. + /*
  7867. + * At this point we have guaranteed that the system doesn't reference
  7868. + * any packets any more.
  7869. + */
  7870. +}
  7871. +
  7872. +static inline struct device *ssh_ptl_get_device(struct ssh_ptl *ptl)
  7873. +{
  7874. + return &ptl->serdev->dev;
  7875. +}
  7876. +
  7877. +static int ssh_ptl_init(struct ssh_ptl *ptl, struct serdev_device *serdev,
  7878. + struct ssh_ptl_ops *ops)
  7879. +{
  7880. + int i, status;
  7881. +
  7882. + ptl->serdev = serdev;
  7883. + ptl->state = 0;
  7884. +
  7885. + spin_lock_init(&ptl->queue.lock);
  7886. + INIT_LIST_HEAD(&ptl->queue.head);
  7887. +
  7888. + spin_lock_init(&ptl->pending.lock);
  7889. + INIT_LIST_HEAD(&ptl->pending.head);
  7890. + atomic_set_release(&ptl->pending.count, 0);
  7891. +
  7892. + ptl->tx.thread = NULL;
  7893. + ptl->tx.thread_signal = false;
  7894. + ptl->tx.packet = NULL;
  7895. + ptl->tx.offset = 0;
  7896. + init_waitqueue_head(&ptl->tx.thread_wq);
  7897. + init_waitqueue_head(&ptl->tx.packet_wq);
  7898. +
  7899. + ptl->rx.thread = NULL;
  7900. + init_waitqueue_head(&ptl->rx.wq);
  7901. +
  7902. + ptl->rtx_timeout.timeout = SSH_PTL_PACKET_TIMEOUT;
  7903. + ptl->rtx_timeout.expires = KTIME_MAX;
  7904. + INIT_DELAYED_WORK(&ptl->rtx_timeout.reaper, ssh_ptl_timeout_reap);
  7905. +
  7906. + ptl->ops = *ops;
  7907. +
  7908. + // initialize SEQ blacklist with invalid sequence IDs
  7909. + for (i = 0; i < ARRAY_SIZE(ptl->rx.blacklist.seqs); i++)
  7910. + ptl->rx.blacklist.seqs[i] = 0xFFFF;
  7911. + ptl->rx.blacklist.offset = 0;
  7912. +
  7913. + status = kfifo_alloc(&ptl->rx.fifo, SSH_PTL_RX_FIFO_LEN, GFP_KERNEL);
  7914. + if (status)
  7915. + return status;
  7916. +
  7917. + status = sshp_buf_alloc(&ptl->rx.buf, SSH_PTL_RX_BUF_LEN, GFP_KERNEL);
  7918. + if (status)
  7919. + kfifo_free(&ptl->rx.fifo);
  7920. +
  7921. + return status;
  7922. +}
  7923. +
  7924. +static void ssh_ptl_destroy(struct ssh_ptl *ptl)
  7925. +{
  7926. + kfifo_free(&ptl->rx.fifo);
  7927. + sshp_buf_free(&ptl->rx.buf);
  7928. +}
  7929. +
  7930. +
  7931. +/* -- Request transport layer (rtl). ---------------------------------------- */
  7932. +
  7933. +#define SSH_RTL_REQUEST_TIMEOUT ms_to_ktime(1000)
  7934. +#define SSH_RTL_REQUEST_TIMEOUT_RESOLUTION ms_to_ktime(max(2000 / HZ, 50))
  7935. +
  7936. +#define SSH_RTL_MAX_PENDING 3
  7937. +
  7938. +
  7939. +enum ssh_rtl_state_flags {
  7940. + SSH_RTL_SF_SHUTDOWN_BIT,
  7941. +};
  7942. +
  7943. +struct ssh_rtl_ops {
  7944. + void (*handle_event)(struct ssh_rtl *rtl, const struct ssh_command *cmd,
  7945. + const struct sshp_span *data);
  7946. +};
  7947. +
  7948. +struct ssh_rtl {
  7949. + struct ssh_ptl ptl;
  7950. + unsigned long state;
  7951. +
  7952. + struct {
  7953. + spinlock_t lock;
  7954. + struct list_head head;
  7955. + } queue;
  7956. +
  7957. + struct {
  7958. + spinlock_t lock;
  7959. + struct list_head head;
  7960. + atomic_t count;
  7961. + } pending;
  7962. +
  7963. + struct {
  7964. + struct work_struct work;
  7965. + } tx;
  7966. +
  7967. + struct {
  7968. + ktime_t timeout;
  7969. + ktime_t expires;
  7970. + struct delayed_work reaper;
  7971. + } rtx_timeout;
  7972. +
  7973. + struct ssh_rtl_ops ops;
  7974. +};
  7975. +
  7976. +
  7977. +#define rtl_dbg(r, fmt, ...) ptl_dbg(&(r)->ptl, fmt, ##__VA_ARGS__)
  7978. +#define rtl_info(p, fmt, ...) ptl_info(&(p)->ptl, fmt, ##__VA_ARGS__)
  7979. +#define rtl_warn(r, fmt, ...) ptl_warn(&(r)->ptl, fmt, ##__VA_ARGS__)
  7980. +#define rtl_err(r, fmt, ...) ptl_err(&(r)->ptl, fmt, ##__VA_ARGS__)
  7981. +#define rtl_dbg_cond(r, fmt, ...) __ssam_prcond(rtl_dbg, r, fmt, ##__VA_ARGS__)
  7982. +
  7983. +#define to_ssh_rtl(ptr, member) \
  7984. + container_of(ptr, struct ssh_rtl, member)
  7985. +
  7986. +#define to_ssh_request(ptr, member) \
  7987. + container_of(ptr, struct ssh_request, member)
  7988. +
  7989. +
  7990. +/**
  7991. + * ssh_rtl_should_drop_response - error injection hook to drop request responses
  7992. + *
  7993. + * Useful to cause request transmission timeouts in the driver by dropping the
  7994. + * response to a request.
  7995. + */
  7996. +static noinline_if_inject bool ssh_rtl_should_drop_response(void)
  7997. +{
  7998. + return false;
  7999. +}
  8000. +ALLOW_ERROR_INJECTION(ssh_rtl_should_drop_response, TRUE);
  8001. +
  8002. +
  8003. +static inline void ssh_request_get(struct ssh_request *rqst)
  8004. +{
  8005. + ssh_packet_get(&rqst->packet);
  8006. +}
  8007. +
  8008. +static inline void ssh_request_put(struct ssh_request *rqst)
  8009. +{
  8010. + ssh_packet_put(&rqst->packet);
  8011. +}
  8012. +
  8013. +
  8014. +static inline u16 ssh_request_get_rqid(struct ssh_request *rqst)
  8015. +{
  8016. + return get_unaligned_le16(rqst->packet.data
  8017. + + SSH_MSGOFFSET_COMMAND(rqid));
  8018. +}
  8019. +
  8020. +static inline u32 ssh_request_get_rqid_safe(struct ssh_request *rqst)
  8021. +{
  8022. + if (!rqst->packet.data)
  8023. + return -1;
  8024. +
  8025. + return ssh_request_get_rqid(rqst);
  8026. +}
  8027. +
  8028. +
  8029. +static void ssh_rtl_queue_remove(struct ssh_request *rqst)
  8030. +{
  8031. + bool remove;
  8032. +
  8033. + spin_lock(&rqst->rtl->queue.lock);
  8034. +
  8035. + remove = test_and_clear_bit(SSH_REQUEST_SF_QUEUED_BIT, &rqst->state);
  8036. + if (remove)
  8037. + list_del(&rqst->node);
  8038. +
  8039. + spin_unlock(&rqst->rtl->queue.lock);
  8040. +
  8041. + if (remove)
  8042. + ssh_request_put(rqst);
  8043. +}
  8044. +
  8045. +static void ssh_rtl_pending_remove(struct ssh_request *rqst)
  8046. +{
  8047. + bool remove;
  8048. +
  8049. + spin_lock(&rqst->rtl->pending.lock);
  8050. +
  8051. + remove = test_and_clear_bit(SSH_REQUEST_SF_PENDING_BIT, &rqst->state);
  8052. + if (remove) {
  8053. + atomic_dec(&rqst->rtl->pending.count);
  8054. + list_del(&rqst->node);
  8055. + }
  8056. +
  8057. + spin_unlock(&rqst->rtl->pending.lock);
  8058. +
  8059. + if (remove)
  8060. + ssh_request_put(rqst);
  8061. +}
  8062. +
  8063. +
  8064. +static void ssh_rtl_complete_with_status(struct ssh_request *rqst, int status)
  8065. +{
  8066. + struct ssh_rtl *rtl = READ_ONCE(rqst->rtl);
  8067. +
  8068. + trace_ssam_request_complete(rqst, status);
  8069. +
  8070. + // rqst->rtl may not be set if we're cancelling before submitting
  8071. + rtl_dbg_cond(rtl, "rtl: completing request (rqid: 0x%04x,"
  8072. + " status: %d)\n", ssh_request_get_rqid_safe(rqst), status);
  8073. +
  8074. + rqst->ops->complete(rqst, NULL, NULL, status);
  8075. +}
  8076. +
  8077. +static void ssh_rtl_complete_with_rsp(struct ssh_request *rqst,
  8078. + const struct ssh_command *cmd,
  8079. + const struct sshp_span *data)
  8080. +{
  8081. + trace_ssam_request_complete(rqst, 0);
  8082. +
  8083. + rtl_dbg(rqst->rtl, "rtl: completing request with response"
  8084. + " (rqid: 0x%04x)\n", ssh_request_get_rqid(rqst));
  8085. +
  8086. + rqst->ops->complete(rqst, cmd, data, 0);
  8087. +}
  8088. +
  8089. +
  8090. +static bool ssh_rtl_tx_can_process(struct ssh_request *rqst)
  8091. +{
  8092. + if (test_bit(SSH_REQUEST_TY_FLUSH_BIT, &rqst->state))
  8093. + return !atomic_read(&rqst->rtl->pending.count);
  8094. +
  8095. + return atomic_read(&rqst->rtl->pending.count) < SSH_RTL_MAX_PENDING;
  8096. +}
  8097. +
  8098. +static struct ssh_request *ssh_rtl_tx_next(struct ssh_rtl *rtl)
  8099. +{
  8100. + struct ssh_request *rqst = ERR_PTR(-ENOENT);
  8101. + struct ssh_request *p, *n;
  8102. +
  8103. + spin_lock(&rtl->queue.lock);
  8104. +
  8105. + // find first non-locked request and remove it
  8106. + list_for_each_entry_safe(p, n, &rtl->queue.head, node) {
  8107. + if (unlikely(test_bit(SSH_REQUEST_SF_LOCKED_BIT, &p->state)))
  8108. + continue;
  8109. +
  8110. + if (!ssh_rtl_tx_can_process(p)) {
  8111. + rqst = ERR_PTR(-EBUSY);
  8112. + break;
  8113. + }
  8114. +
  8115. + /*
  8116. + * Remove from queue and mark as transmitting. Ensure that the
  8117. + * state does not get zero via memory barrier.
  8118. + */
  8119. + set_bit(SSH_REQUEST_SF_TRANSMITTING_BIT, &p->state);
  8120. + smp_mb__before_atomic();
  8121. + clear_bit(SSH_REQUEST_SF_QUEUED_BIT, &p->state);
  8122. +
  8123. + list_del(&p->node);
  8124. +
  8125. + rqst = p;
  8126. + break;
  8127. + }
  8128. +
  8129. + spin_unlock(&rtl->queue.lock);
  8130. + return rqst;
  8131. +}
  8132. +
  8133. +static int ssh_rtl_tx_pending_push(struct ssh_request *rqst)
  8134. +{
  8135. + struct ssh_rtl *rtl = rqst->rtl;
  8136. +
  8137. + spin_lock(&rtl->pending.lock);
  8138. +
  8139. + if (test_bit(SSH_REQUEST_SF_LOCKED_BIT, &rqst->state)) {
  8140. + spin_unlock(&rtl->pending.lock);
  8141. + return -EINVAL;
  8142. + }
  8143. +
  8144. + if (test_and_set_bit(SSH_REQUEST_SF_PENDING_BIT, &rqst->state)) {
  8145. + spin_unlock(&rtl->pending.lock);
  8146. + return -EALREADY;
  8147. + }
  8148. +
  8149. + atomic_inc(&rtl->pending.count);
  8150. + ssh_request_get(rqst);
  8151. + list_add_tail(&rqst->node, &rtl->pending.head);
  8152. +
  8153. + spin_unlock(&rtl->pending.lock);
  8154. + return 0;
  8155. +}
  8156. +
  8157. +static int ssh_rtl_tx_try_process_one(struct ssh_rtl *rtl)
  8158. +{
  8159. + struct ssh_request *rqst;
  8160. + int status;
  8161. +
  8162. + // get and prepare next request for transmit
  8163. + rqst = ssh_rtl_tx_next(rtl);
  8164. + if (IS_ERR(rqst))
  8165. + return PTR_ERR(rqst);
  8166. +
  8167. + // add to/mark as pending
  8168. + status = ssh_rtl_tx_pending_push(rqst);
  8169. + if (status) {
  8170. + ssh_request_put(rqst);
  8171. + return -EAGAIN;
  8172. + }
  8173. +
  8174. + // submit packet
  8175. + status = ssh_ptl_submit(&rtl->ptl, &rqst->packet);
  8176. + if (status == -ESHUTDOWN) {
  8177. + /*
  8178. + * Packet has been refused due to the packet layer shutting
  8179. + * down. Complete it here.
  8180. + */
  8181. + set_bit(SSH_REQUEST_SF_LOCKED_BIT, &rqst->state);
  8182. + smp_mb__after_atomic();
  8183. +
  8184. + ssh_rtl_pending_remove(rqst);
  8185. + ssh_rtl_complete_with_status(rqst, -ESHUTDOWN);
  8186. +
  8187. + ssh_request_put(rqst);
  8188. + return -ESHUTDOWN;
  8189. +
  8190. + } else if (status) {
  8191. + /*
  8192. + * If submitting the packet failed and the packet layer isn't
  8193. + * shutting down, the packet has either been submmitted/queued
  8194. + * before (-EALREADY, which cannot happen as we have guaranteed
  8195. + * that requests cannot be re-submitted), or the packet was
  8196. + * marked as locked (-EINVAL). To mark the packet locked at this
  8197. + * stage, the request, and thus the packets itself, had to have
  8198. + * been canceled. Simply drop the reference. Cancellation itself
  8199. + * will remove it from the set of pending requests.
  8200. + */
  8201. +
  8202. + WARN_ON(status != -EINVAL);
  8203. +
  8204. + ssh_request_put(rqst);
  8205. + return -EAGAIN;
  8206. + }
  8207. +
  8208. + ssh_request_put(rqst);
  8209. + return 0;
  8210. +}
  8211. +
  8212. +static bool ssh_rtl_queue_empty(struct ssh_rtl *rtl)
  8213. +{
  8214. + bool empty;
  8215. +
  8216. + spin_lock(&rtl->queue.lock);
  8217. + empty = list_empty(&rtl->queue.head);
  8218. + spin_unlock(&rtl->queue.lock);
  8219. +
  8220. + return empty;
  8221. +}
  8222. +
  8223. +static bool ssh_rtl_tx_schedule(struct ssh_rtl *rtl)
  8224. +{
  8225. + if (atomic_read(&rtl->pending.count) >= SSH_RTL_MAX_PENDING)
  8226. + return false;
  8227. +
  8228. + if (ssh_rtl_queue_empty(rtl))
  8229. + return false;
  8230. +
  8231. + return schedule_work(&rtl->tx.work);
  8232. +}
  8233. +
  8234. +static void ssh_rtl_tx_work_fn(struct work_struct *work)
  8235. +{
  8236. + struct ssh_rtl *rtl = to_ssh_rtl(work, tx.work);
  8237. + int i, status;
  8238. +
  8239. + /*
  8240. + * Try to be nice and not block the workqueue: Run a maximum of 10
  8241. + * tries, then re-submit if necessary. This should not be neccesary,
  8242. + * for normal execution, but guarantee it anyway.
  8243. + */
  8244. + for (i = 0; i < 10; i++) {
  8245. + status = ssh_rtl_tx_try_process_one(rtl);
  8246. + if (status == -ENOENT || status == -EBUSY)
  8247. + return; // no more requests to process
  8248. +
  8249. + if (status == -ESHUTDOWN) {
  8250. + /*
  8251. + * Packet system shutting down. No new packets can be
  8252. + * transmitted. Return silently, the party initiating
  8253. + * the shutdown should handle the rest.
  8254. + */
  8255. + return;
  8256. + }
  8257. +
  8258. + WARN_ON(status != 0 && status != -EAGAIN);
  8259. + }
  8260. +
  8261. + // out of tries, reschedule
  8262. + ssh_rtl_tx_schedule(rtl);
  8263. +}
  8264. +
  8265. +
  8266. +static int ssh_rtl_submit(struct ssh_rtl *rtl, struct ssh_request *rqst)
  8267. +{
  8268. + trace_ssam_request_submit(rqst);
  8269. +
  8270. + /*
  8271. + * Ensure that requests expecting a response are sequenced. If this
  8272. + * invariant ever changes, see the comment in ssh_rtl_complete on what
  8273. + * is required to be changed in the code.
  8274. + */
  8275. + if (test_bit(SSH_REQUEST_TY_HAS_RESPONSE_BIT, &rqst->state))
  8276. + if (!(rqst->packet.type & SSH_PACKET_TY_SEQUENCED))
  8277. + return -EINVAL;
  8278. +
  8279. + // try to set rtl and check if this request has already been submitted
  8280. + if (cmpxchg(&rqst->rtl, NULL, rtl) != NULL)
  8281. + return -EALREADY;
  8282. +
  8283. + spin_lock(&rtl->queue.lock);
  8284. +
  8285. + if (test_bit(SSH_RTL_SF_SHUTDOWN_BIT, &rtl->state)) {
  8286. + spin_unlock(&rtl->queue.lock);
  8287. + return -ESHUTDOWN;
  8288. + }
  8289. +
  8290. + if (test_bit(SSH_REQUEST_SF_LOCKED_BIT, &rqst->state)) {
  8291. + spin_unlock(&rtl->queue.lock);
  8292. + return -EINVAL;
  8293. + }
  8294. +
  8295. + ssh_request_get(rqst);
  8296. + set_bit(SSH_REQUEST_SF_QUEUED_BIT, &rqst->state);
  8297. + list_add_tail(&rqst->node, &rtl->queue.head);
  8298. +
  8299. + spin_unlock(&rtl->queue.lock);
  8300. +
  8301. + ssh_rtl_tx_schedule(rtl);
  8302. + return 0;
  8303. +}
  8304. +
  8305. +
  8306. +static void ssh_rtl_timeout_reaper_mod(struct ssh_rtl *rtl, ktime_t now,
  8307. + ktime_t expires)
  8308. +{
  8309. + unsigned long delta = msecs_to_jiffies(ktime_ms_delta(expires, now));
  8310. + ktime_t aexp = ktime_add(expires, SSH_RTL_REQUEST_TIMEOUT_RESOLUTION);
  8311. + ktime_t old;
  8312. +
  8313. + // re-adjust / schedule reaper if it is above resolution delta
  8314. + old = READ_ONCE(rtl->rtx_timeout.expires);
  8315. + while (ktime_before(aexp, old))
  8316. + old = cmpxchg64(&rtl->rtx_timeout.expires, old, expires);
  8317. +
  8318. + // if we updated the reaper expiration, modify work timeout
  8319. + if (old == expires)
  8320. + mod_delayed_work(system_wq, &rtl->rtx_timeout.reaper, delta);
  8321. +}
  8322. +
  8323. +static void ssh_rtl_timeout_start(struct ssh_request *rqst)
  8324. +{
  8325. + struct ssh_rtl *rtl = rqst->rtl;
  8326. + ktime_t timestamp = ktime_get_coarse_boottime();
  8327. + ktime_t timeout = rtl->rtx_timeout.timeout;
  8328. +
  8329. + if (test_bit(SSH_REQUEST_SF_LOCKED_BIT, &rqst->state))
  8330. + return;
  8331. +
  8332. + WRITE_ONCE(rqst->timestamp, timestamp);
  8333. + smp_mb__after_atomic();
  8334. +
  8335. + ssh_rtl_timeout_reaper_mod(rqst->rtl, timestamp, timestamp + timeout);
  8336. +}
  8337. +
  8338. +
  8339. +static void ssh_rtl_complete(struct ssh_rtl *rtl,
  8340. + const struct ssh_command *command,
  8341. + const struct sshp_span *command_data)
  8342. +{
  8343. + struct ssh_request *r = NULL;
  8344. + struct ssh_request *p, *n;
  8345. + u16 rqid = get_unaligned_le16(&command->rqid);
  8346. +
  8347. + trace_ssam_rx_response_received(command, command_data->len);
  8348. +
  8349. + /*
  8350. + * Get request from pending based on request ID and mark it as response
  8351. + * received and locked.
  8352. + */
  8353. + spin_lock(&rtl->pending.lock);
  8354. + list_for_each_entry_safe(p, n, &rtl->pending.head, node) {
  8355. + // we generally expect requests to be processed in order
  8356. + if (unlikely(ssh_request_get_rqid(p) != rqid))
  8357. + continue;
  8358. +
  8359. + // simulate response timeout
  8360. + if (ssh_rtl_should_drop_response()) {
  8361. + spin_unlock(&rtl->pending.lock);
  8362. +
  8363. + trace_ssam_ei_rx_drop_response(p);
  8364. + rtl_info(rtl, "request error injection: "
  8365. + "dropping response for request %p\n",
  8366. + &p->packet);
  8367. + return;
  8368. + }
  8369. +
  8370. + /*
  8371. + * Mark as "response received" and "locked" as we're going to
  8372. + * complete it. Ensure that the state doesn't get zero by
  8373. + * employing a memory barrier.
  8374. + */
  8375. + set_bit(SSH_REQUEST_SF_LOCKED_BIT, &p->state);
  8376. + set_bit(SSH_REQUEST_SF_RSPRCVD_BIT, &p->state);
  8377. + smp_mb__before_atomic();
  8378. + clear_bit(SSH_REQUEST_SF_PENDING_BIT, &p->state);
  8379. +
  8380. + atomic_dec(&rtl->pending.count);
  8381. + list_del(&p->node);
  8382. +
  8383. + r = p;
  8384. + break;
  8385. + }
  8386. + spin_unlock(&rtl->pending.lock);
  8387. +
  8388. + if (!r) {
  8389. + rtl_warn(rtl, "rtl: dropping unexpected command message"
  8390. + " (rqid = 0x%04x)\n", rqid);
  8391. + return;
  8392. + }
  8393. +
  8394. + // if the request hasn't been completed yet, we will do this now
  8395. + if (test_and_set_bit(SSH_REQUEST_SF_COMPLETED_BIT, &r->state)) {
  8396. + ssh_request_put(r);
  8397. + ssh_rtl_tx_schedule(rtl);
  8398. + return;
  8399. + }
  8400. +
  8401. + /*
  8402. + * Make sure the request has been transmitted. In case of a sequenced
  8403. + * request, we are guaranteed that the completion callback will run on
  8404. + * the receiver thread directly when the ACK for the packet has been
  8405. + * received. Similarly, this function is guaranteed to run on the
  8406. + * receiver thread. Thus we are guaranteed that if the packet has been
  8407. + * successfully transmitted and received an ACK, the transmitted flag
  8408. + * has been set and is visible here.
  8409. + *
  8410. + * We are currently not handling unsequenced packets here, as those
  8411. + * should never expect a response as ensured in ssh_rtl_submit. If this
  8412. + * ever changes, one would have to test for
  8413. + *
  8414. + * (r->state & (transmitting | transmitted))
  8415. + *
  8416. + * on unsequenced packets to determine if they could have been
  8417. + * transmitted. There are no synchronization guarantees as in the
  8418. + * sequenced case, since, in this case, the callback function will not
  8419. + * run on the same thread. Thus an exact determination is impossible.
  8420. + */
  8421. + if (!test_bit(SSH_REQUEST_SF_TRANSMITTED_BIT, &r->state)) {
  8422. + rtl_err(rtl, "rtl: received response before ACK for request"
  8423. + " (rqid = 0x%04x)\n", rqid);
  8424. +
  8425. + /*
  8426. + * NB: Timeout has already been canceled, request already been
  8427. + * removed from pending and marked as locked and completed. As
  8428. + * we receive a "false" response, the packet might still be
  8429. + * queued though.
  8430. + */
  8431. + ssh_rtl_queue_remove(r);
  8432. +
  8433. + ssh_rtl_complete_with_status(r, -EREMOTEIO);
  8434. + ssh_request_put(r);
  8435. +
  8436. + ssh_rtl_tx_schedule(rtl);
  8437. + return;
  8438. + }
  8439. +
  8440. + /*
  8441. + * NB: Timeout has already been canceled, request already been
  8442. + * removed from pending and marked as locked and completed. The request
  8443. + * can also not be queued any more, as it has been marked as
  8444. + * transmitting and later transmitted. Thus no need to remove it from
  8445. + * anywhere.
  8446. + */
  8447. +
  8448. + ssh_rtl_complete_with_rsp(r, command, command_data);
  8449. + ssh_request_put(r);
  8450. +
  8451. + ssh_rtl_tx_schedule(rtl);
  8452. +}
  8453. +
  8454. +
  8455. +static bool ssh_rtl_cancel_nonpending(struct ssh_request *r)
  8456. +{
  8457. + unsigned long state, fixed;
  8458. + bool remove;
  8459. +
  8460. + /*
  8461. + * Handle unsubmitted request: Try to mark the packet as locked,
  8462. + * expecting the state to be zero (i.e. unsubmitted). Note that, if
  8463. + * setting the state worked, we might still be adding the packet to the
  8464. + * queue in a currently executing submit call. In that case, however,
  8465. + * rqst->rtl must have been set previously, as locked is checked after
  8466. + * setting rqst->rtl. Thus only if we successfully lock this request and
  8467. + * rqst->rtl is NULL, we have successfully removed the request.
  8468. + * Otherwise we need to try and grab it from the queue.
  8469. + *
  8470. + * Note that if the CMPXCHG fails, we are guaranteed that rqst->rtl has
  8471. + * been set and is non-NULL, as states can only be nonzero after this
  8472. + * has been set. Also note that we need to fetch the static (type) flags
  8473. + * to ensure that they don't cause the cmpxchg to fail.
  8474. + */
  8475. + fixed = READ_ONCE(r->state) & SSH_REQUEST_FLAGS_TY_MASK;
  8476. + state = cmpxchg(&r->state, fixed, SSH_REQUEST_SF_LOCKED_BIT);
  8477. + if (!state && !READ_ONCE(r->rtl)) {
  8478. + if (test_and_set_bit(SSH_REQUEST_SF_COMPLETED_BIT, &r->state))
  8479. + return true;
  8480. +
  8481. + ssh_rtl_complete_with_status(r, -ECANCELED);
  8482. + return true;
  8483. + }
  8484. +
  8485. + spin_lock(&r->rtl->queue.lock);
  8486. +
  8487. + /*
  8488. + * Note: 1) Requests cannot be re-submitted. 2) If a request is queued,
  8489. + * it cannot be "transmitting"/"pending" yet. Thus, if we successfully
  8490. + * remove the the request here, we have removed all its occurences in
  8491. + * the system.
  8492. + */
  8493. +
  8494. + remove = test_and_clear_bit(SSH_REQUEST_SF_QUEUED_BIT, &r->state);
  8495. + if (!remove) {
  8496. + spin_unlock(&r->rtl->queue.lock);
  8497. + return false;
  8498. + }
  8499. +
  8500. + set_bit(SSH_REQUEST_SF_LOCKED_BIT, &r->state);
  8501. + list_del(&r->node);
  8502. +
  8503. + spin_unlock(&r->rtl->queue.lock);
  8504. +
  8505. + ssh_request_put(r); // drop reference obtained from queue
  8506. +
  8507. + if (test_and_set_bit(SSH_REQUEST_SF_COMPLETED_BIT, &r->state))
  8508. + return true;
  8509. +
  8510. + ssh_rtl_complete_with_status(r, -ECANCELED);
  8511. + return true;
  8512. +}
  8513. +
  8514. +static bool ssh_rtl_cancel_pending(struct ssh_request *r)
  8515. +{
  8516. + // if the packet is already locked, it's going to be removed shortly
  8517. + if (test_and_set_bit(SSH_REQUEST_SF_LOCKED_BIT, &r->state))
  8518. + return true;
  8519. +
  8520. + /*
  8521. + * Now that we have locked the packet, we have guaranteed that it can't
  8522. + * be added to the system any more. If rqst->rtl is zero, the locked
  8523. + * check in ssh_rtl_submit has not been run and any submission,
  8524. + * currently in progress or called later, won't add the packet. Thus we
  8525. + * can directly complete it.
  8526. + */
  8527. + if (!READ_ONCE(r->rtl)) {
  8528. + if (test_and_set_bit(SSH_REQUEST_SF_COMPLETED_BIT, &r->state))
  8529. + return true;
  8530. +
  8531. + ssh_rtl_complete_with_status(r, -ECANCELED);
  8532. + return true;
  8533. + }
  8534. +
  8535. + /*
  8536. + * Try to cancel the packet. If the packet has not been completed yet,
  8537. + * this will subsequently (and synchronously) call the completion
  8538. + * callback of the packet, which will complete the request.
  8539. + */
  8540. + ssh_ptl_cancel(&r->packet);
  8541. +
  8542. + /*
  8543. + * If the packet has been completed with success, i.e. has not been
  8544. + * canceled by the above call, the request may not have been completed
  8545. + * yet (may be waiting for a response). Check if we need to do this
  8546. + * here.
  8547. + */
  8548. + if (test_and_set_bit(SSH_REQUEST_SF_COMPLETED_BIT, &r->state))
  8549. + return true;
  8550. +
  8551. + ssh_rtl_queue_remove(r);
  8552. + ssh_rtl_pending_remove(r);
  8553. + ssh_rtl_complete_with_status(r, -ECANCELED);
  8554. +
  8555. + return true;
  8556. +}
  8557. +
  8558. +static bool ssh_rtl_cancel(struct ssh_request *rqst, bool pending)
  8559. +{
  8560. + struct ssh_rtl *rtl;
  8561. + bool canceled;
  8562. +
  8563. + if (test_and_set_bit(SSH_REQUEST_SF_CANCELED_BIT, &rqst->state))
  8564. + return true;
  8565. +
  8566. + trace_ssam_request_cancel(rqst);
  8567. +
  8568. + if (pending)
  8569. + canceled = ssh_rtl_cancel_pending(rqst);
  8570. + else
  8571. + canceled = ssh_rtl_cancel_nonpending(rqst);
  8572. +
  8573. + // note: rqst->rtl may be NULL if request has not been submitted yet
  8574. + rtl = READ_ONCE(rqst->rtl);
  8575. + if (canceled && rtl)
  8576. + ssh_rtl_tx_schedule(rtl);
  8577. +
  8578. + return canceled;
  8579. +}
  8580. +
  8581. +
  8582. +static void ssh_rtl_packet_callback(struct ssh_packet *p, int status)
  8583. +{
  8584. + struct ssh_request *r = to_ssh_request(p, packet);
  8585. +
  8586. + if (unlikely(status)) {
  8587. + set_bit(SSH_REQUEST_SF_LOCKED_BIT, &r->state);
  8588. +
  8589. + if (test_and_set_bit(SSH_REQUEST_SF_COMPLETED_BIT, &r->state))
  8590. + return;
  8591. +
  8592. + /*
  8593. + * The packet may get cancelled even though it has not been
  8594. + * submitted yet. The request may still be queued. Check the
  8595. + * queue and remove it if necessary. As the timeout would have
  8596. + * been started in this function on success, there's no need to
  8597. + * cancel it here.
  8598. + */
  8599. + ssh_rtl_queue_remove(r);
  8600. + ssh_rtl_pending_remove(r);
  8601. + ssh_rtl_complete_with_status(r, status);
  8602. +
  8603. + ssh_rtl_tx_schedule(r->rtl);
  8604. + return;
  8605. + }
  8606. +
  8607. + /*
  8608. + * Mark as transmitted, ensure that state doesn't get zero by inserting
  8609. + * a memory barrier.
  8610. + */
  8611. + set_bit(SSH_REQUEST_SF_TRANSMITTED_BIT, &r->state);
  8612. + smp_mb__before_atomic();
  8613. + clear_bit(SSH_REQUEST_SF_TRANSMITTING_BIT, &r->state);
  8614. +
  8615. + // if we expect a response, we just need to start the timeout
  8616. + if (test_bit(SSH_REQUEST_TY_HAS_RESPONSE_BIT, &r->state)) {
  8617. + ssh_rtl_timeout_start(r);
  8618. + return;
  8619. + }
  8620. +
  8621. + /*
  8622. + * If we don't expect a response, lock, remove, and complete the
  8623. + * request. Note that, at this point, the request is guaranteed to have
  8624. + * left the queue and no timeout has been started. Thus we only need to
  8625. + * remove it from pending. If the request has already been completed (it
  8626. + * may have been canceled) return.
  8627. + */
  8628. +
  8629. + set_bit(SSH_REQUEST_SF_LOCKED_BIT, &r->state);
  8630. + if (test_and_set_bit(SSH_REQUEST_SF_COMPLETED_BIT, &r->state))
  8631. + return;
  8632. +
  8633. + ssh_rtl_pending_remove(r);
  8634. + ssh_rtl_complete_with_status(r, 0);
  8635. +
  8636. + ssh_rtl_tx_schedule(r->rtl);
  8637. +}
  8638. +
  8639. +
  8640. +static ktime_t ssh_request_get_expiration(struct ssh_request *r, ktime_t timeo)
  8641. +{
  8642. + ktime_t timestamp = READ_ONCE(r->timestamp);
  8643. +
  8644. + if (timestamp != KTIME_MAX)
  8645. + return ktime_add(timestamp, timeo);
  8646. + else
  8647. + return KTIME_MAX;
  8648. +}
  8649. +
  8650. +static void ssh_rtl_timeout_reap(struct work_struct *work)
  8651. +{
  8652. + struct ssh_rtl *rtl = to_ssh_rtl(work, rtx_timeout.reaper.work);
  8653. + struct ssh_request *r, *n;
  8654. + LIST_HEAD(claimed);
  8655. + ktime_t now = ktime_get_coarse_boottime();
  8656. + ktime_t timeout = rtl->rtx_timeout.timeout;
  8657. + ktime_t next = KTIME_MAX;
  8658. +
  8659. + trace_ssam_rtl_timeout_reap("pending", atomic_read(&rtl->pending.count));
  8660. +
  8661. + /*
  8662. + * Mark reaper as "not pending". This is done before checking any
  8663. + * requests to avoid lost-update type problems.
  8664. + */
  8665. + WRITE_ONCE(rtl->rtx_timeout.expires, KTIME_MAX);
  8666. + smp_mb__after_atomic();
  8667. +
  8668. + spin_lock(&rtl->pending.lock);
  8669. + list_for_each_entry_safe(r, n, &rtl->pending.head, node) {
  8670. + ktime_t expires = ssh_request_get_expiration(r, timeout);
  8671. +
  8672. + /*
  8673. + * Check if the timeout hasn't expired yet. Find out next
  8674. + * expiration date to be handled after this run.
  8675. + */
  8676. + if (ktime_after(expires, now)) {
  8677. + next = ktime_before(expires, next) ? expires : next;
  8678. + continue;
  8679. + }
  8680. +
  8681. + // avoid further transitions if locked
  8682. + if (test_and_set_bit(SSH_REQUEST_SF_LOCKED_BIT, &r->state))
  8683. + continue;
  8684. +
  8685. + /*
  8686. + * We have now marked the packet as locked. Thus it cannot be
  8687. + * added to the pending or queued lists again after we've
  8688. + * removed it here. We can therefore re-use the node of this
  8689. + * packet temporarily.
  8690. + */
  8691. +
  8692. + clear_bit(SSH_REQUEST_SF_PENDING_BIT, &r->state);
  8693. +
  8694. + atomic_dec(&rtl->pending.count);
  8695. + list_del(&r->node);
  8696. +
  8697. + list_add_tail(&r->node, &claimed);
  8698. + }
  8699. + spin_unlock(&rtl->pending.lock);
  8700. +
  8701. + // cancel and complete the request
  8702. + list_for_each_entry_safe(r, n, &claimed, node) {
  8703. + trace_ssam_request_timeout(r);
  8704. +
  8705. + /*
  8706. + * At this point we've removed the packet from pending. This
  8707. + * means that we've obtained the last (only) reference of the
  8708. + * system to it. Thus we can just complete it.
  8709. + */
  8710. + if (!test_and_set_bit(SSH_REQUEST_SF_COMPLETED_BIT, &r->state))
  8711. + ssh_rtl_complete_with_status(r, -ETIMEDOUT);
  8712. +
  8713. + // drop the reference we've obtained by removing it from pending
  8714. + list_del(&r->node);
  8715. + ssh_request_put(r);
  8716. + }
  8717. +
  8718. + // ensure that reaper doesn't run again immediately
  8719. + next = max(next, ktime_add(now, SSH_RTL_REQUEST_TIMEOUT_RESOLUTION));
  8720. + if (next != KTIME_MAX)
  8721. + ssh_rtl_timeout_reaper_mod(rtl, now, next);
  8722. +
  8723. + ssh_rtl_tx_schedule(rtl);
  8724. +}
  8725. +
  8726. +
  8727. +static void ssh_rtl_rx_event(struct ssh_rtl *rtl, const struct ssh_command *cmd,
  8728. + const struct sshp_span *data)
  8729. +{
  8730. + trace_ssam_rx_event_received(cmd, data->len);
  8731. +
  8732. + rtl_dbg(rtl, "rtl: handling event (rqid: 0x%04x)\n",
  8733. + get_unaligned_le16(&cmd->rqid));
  8734. +
  8735. + rtl->ops.handle_event(rtl, cmd, data);
  8736. +}
  8737. +
  8738. +static void ssh_rtl_rx_command(struct ssh_ptl *p, const struct sshp_span *data)
  8739. +{
  8740. + struct ssh_rtl *rtl = to_ssh_rtl(p, ptl);
  8741. + struct device *dev = &p->serdev->dev;
  8742. + struct ssh_command *command;
  8743. + struct sshp_span command_data;
  8744. +
  8745. + if (sshp_parse_command(dev, data, &command, &command_data))
  8746. + return;
  8747. +
  8748. + if (ssh_rqid_is_event(get_unaligned_le16(&command->rqid)))
  8749. + ssh_rtl_rx_event(rtl, command, &command_data);
  8750. + else
  8751. + ssh_rtl_complete(rtl, command, &command_data);
  8752. +}
  8753. +
  8754. +static void ssh_rtl_rx_data(struct ssh_ptl *p, const struct sshp_span *data)
  8755. +{
  8756. + switch (data->ptr[0]) {
  8757. + case SSH_PLD_TYPE_CMD:
  8758. + ssh_rtl_rx_command(p, data);
  8759. + break;
  8760. +
  8761. + default:
  8762. + ptl_err(p, "rtl: rx: unknown frame payload type"
  8763. + " (type: 0x%02x)\n", data->ptr[0]);
  8764. + break;
  8765. + }
  8766. +}
  8767. +
  8768. +
  8769. +static inline struct device *ssh_rtl_get_device(struct ssh_rtl *rtl)
  8770. +{
  8771. + return ssh_ptl_get_device(&rtl->ptl);
  8772. +}
  8773. +
  8774. +static inline bool ssh_rtl_tx_flush(struct ssh_rtl *rtl)
  8775. +{
  8776. + return flush_work(&rtl->tx.work);
  8777. +}
  8778. +
  8779. +static inline int ssh_rtl_tx_start(struct ssh_rtl *rtl)
  8780. +{
  8781. + int status;
  8782. + bool sched;
  8783. +
  8784. + status = ssh_ptl_tx_start(&rtl->ptl);
  8785. + if (status)
  8786. + return status;
  8787. +
  8788. + /*
  8789. + * If the packet layer has been shut down and restarted without shutting
  8790. + * down the request layer, there may still be requests queued and not
  8791. + * handled.
  8792. + */
  8793. + spin_lock(&rtl->queue.lock);
  8794. + sched = !list_empty(&rtl->queue.head);
  8795. + spin_unlock(&rtl->queue.lock);
  8796. +
  8797. + if (sched)
  8798. + ssh_rtl_tx_schedule(rtl);
  8799. +
  8800. + return 0;
  8801. +}
  8802. +
  8803. +static inline int ssh_rtl_rx_start(struct ssh_rtl *rtl)
  8804. +{
  8805. + return ssh_ptl_rx_start(&rtl->ptl);
  8806. +}
  8807. +
  8808. +static int ssh_rtl_init(struct ssh_rtl *rtl, struct serdev_device *serdev,
  8809. + struct ssh_rtl_ops *ops)
  8810. +{
  8811. + struct ssh_ptl_ops ptl_ops;
  8812. + int status;
  8813. +
  8814. + ptl_ops.data_received = ssh_rtl_rx_data;
  8815. +
  8816. + status = ssh_ptl_init(&rtl->ptl, serdev, &ptl_ops);
  8817. + if (status)
  8818. + return status;
  8819. +
  8820. + spin_lock_init(&rtl->queue.lock);
  8821. + INIT_LIST_HEAD(&rtl->queue.head);
  8822. +
  8823. + spin_lock_init(&rtl->pending.lock);
  8824. + INIT_LIST_HEAD(&rtl->pending.head);
  8825. + atomic_set_release(&rtl->pending.count, 0);
  8826. +
  8827. + INIT_WORK(&rtl->tx.work, ssh_rtl_tx_work_fn);
  8828. +
  8829. + rtl->rtx_timeout.timeout = SSH_RTL_REQUEST_TIMEOUT;
  8830. + rtl->rtx_timeout.expires = KTIME_MAX;
  8831. + INIT_DELAYED_WORK(&rtl->rtx_timeout.reaper, ssh_rtl_timeout_reap);
  8832. +
  8833. + rtl->ops = *ops;
  8834. +
  8835. + return 0;
  8836. +}
  8837. +
  8838. +static void ssh_rtl_destroy(struct ssh_rtl *rtl)
  8839. +{
  8840. + ssh_ptl_destroy(&rtl->ptl);
  8841. +}
  8842. +
  8843. +
  8844. +static void ssh_rtl_packet_release(struct ssh_packet *p)
  8845. +{
  8846. + struct ssh_request *rqst = to_ssh_request(p, packet);
  8847. + rqst->ops->release(rqst);
  8848. +}
  8849. +
  8850. +static const struct ssh_packet_ops ssh_rtl_packet_ops = {
  8851. + .complete = ssh_rtl_packet_callback,
  8852. + .release = ssh_rtl_packet_release,
  8853. +};
  8854. +
  8855. +static void ssh_request_init(struct ssh_request *rqst,
  8856. + enum ssam_request_flags flags,
  8857. + const struct ssh_request_ops *ops)
  8858. +{
  8859. + struct ssh_packet_args packet_args;
  8860. +
  8861. + packet_args.type = SSH_PACKET_TY_BLOCKING;
  8862. + if (!(flags & SSAM_REQUEST_UNSEQUENCED))
  8863. + packet_args.type |= SSH_PACKET_TY_SEQUENCED;
  8864. +
  8865. + packet_args.priority = SSH_PACKET_PRIORITY(DATA, 0);
  8866. + packet_args.ops = &ssh_rtl_packet_ops;
  8867. +
  8868. + ssh_packet_init(&rqst->packet, &packet_args);
  8869. +
  8870. + rqst->rtl = NULL;
  8871. + INIT_LIST_HEAD(&rqst->node);
  8872. +
  8873. + rqst->state = 0;
  8874. + if (flags & SSAM_REQUEST_HAS_RESPONSE)
  8875. + rqst->state |= BIT(SSH_REQUEST_TY_HAS_RESPONSE_BIT);
  8876. +
  8877. + rqst->timestamp = KTIME_MAX;
  8878. + rqst->ops = ops;
  8879. +}
  8880. +
  8881. +
  8882. +struct ssh_flush_request {
  8883. + struct ssh_request base;
  8884. + struct completion completion;
  8885. + int status;
  8886. +};
  8887. +
  8888. +static void ssh_rtl_flush_request_complete(struct ssh_request *r,
  8889. + const struct ssh_command *cmd,
  8890. + const struct sshp_span *data,
  8891. + int status)
  8892. +{
  8893. + struct ssh_flush_request *rqst;
  8894. +
  8895. + rqst = container_of(r, struct ssh_flush_request, base);
  8896. + rqst->status = status;
  8897. +}
  8898. +
  8899. +static void ssh_rtl_flush_request_release(struct ssh_request *r)
  8900. +{
  8901. + struct ssh_flush_request *rqst;
  8902. +
  8903. + rqst = container_of(r, struct ssh_flush_request, base);
  8904. + complete_all(&rqst->completion);
  8905. +}
  8906. +
  8907. +static const struct ssh_request_ops ssh_rtl_flush_request_ops = {
  8908. + .complete = ssh_rtl_flush_request_complete,
  8909. + .release = ssh_rtl_flush_request_release,
  8910. +};
  8911. +
  8912. +/**
  8913. + * ssh_rtl_flush - flush the request transmission layer
  8914. + * @rtl: request transmission layer
  8915. + * @timeout: timeout for the flush operation in jiffies
  8916. + *
  8917. + * Queue a special flush request and wait for its completion. This request
  8918. + * will be completed after all other currently queued and pending requests
  8919. + * have been completed. Instead of a normal data packet, this request submits
  8920. + * a special flush packet, meaning that upon completion, also the underlying
  8921. + * packet transmission layer has been flushed.
  8922. + *
  8923. + * Flushing the request layer gurarantees that all previously submitted
  8924. + * requests have been fully completed before this call returns. Additinally,
  8925. + * flushing blocks execution of all later submitted requests until the flush
  8926. + * has been completed.
  8927. + *
  8928. + * If the caller ensures that no new requests are submitted after a call to
  8929. + * this function, the request transmission layer is guaranteed to have no
  8930. + * remaining requests when this call returns. The same guarantee does not hold
  8931. + * for the packet layer, on which control packets may still be queued after
  8932. + * this call. See the documentation of ssh_ptl_flush for more details on
  8933. + * packet layer flushing.
  8934. + *
  8935. + * Return: Zero on success, -ETIMEDOUT if the flush timed out and has been
  8936. + * canceled as a result of the timeout, or -ESHUTDOWN if the packet and/or
  8937. + * request transmission layer has been shut down before this call. May also
  8938. + * return -EINTR if the underlying packet transmission has been interrupted.
  8939. + */
  8940. +static int ssh_rtl_flush(struct ssh_rtl *rtl, unsigned long timeout)
  8941. +{
  8942. + const unsigned init_flags = SSAM_REQUEST_UNSEQUENCED;
  8943. + struct ssh_flush_request rqst;
  8944. + int status;
  8945. +
  8946. + ssh_request_init(&rqst.base, init_flags, &ssh_rtl_flush_request_ops);
  8947. + rqst.base.packet.type |= SSH_PACKET_TY_FLUSH;
  8948. + rqst.base.packet.priority = SSH_PACKET_PRIORITY(FLUSH, 0);
  8949. + rqst.base.state |= BIT(SSH_REQUEST_TY_FLUSH_BIT);
  8950. +
  8951. + init_completion(&rqst.completion);
  8952. +
  8953. + status = ssh_rtl_submit(rtl, &rqst.base);
  8954. + if (status)
  8955. + return status;
  8956. +
  8957. + ssh_request_put(&rqst.base);
  8958. +
  8959. + if (wait_for_completion_timeout(&rqst.completion, timeout))
  8960. + return 0;
  8961. +
  8962. + ssh_rtl_cancel(&rqst.base, true);
  8963. + wait_for_completion(&rqst.completion);
  8964. +
  8965. + WARN_ON(rqst.status != 0 && rqst.status != -ECANCELED
  8966. + && rqst.status != -ESHUTDOWN && rqst.status != -EINTR);
  8967. +
  8968. + return rqst.status == -ECANCELED ? -ETIMEDOUT : status;
  8969. +}
  8970. +
  8971. +
  8972. +static void ssh_rtl_shutdown(struct ssh_rtl *rtl)
  8973. +{
  8974. + struct ssh_request *r, *n;
  8975. + LIST_HEAD(claimed);
  8976. + int pending;
  8977. +
  8978. + set_bit(SSH_RTL_SF_SHUTDOWN_BIT, &rtl->state);
  8979. + smp_mb__after_atomic();
  8980. +
  8981. + // remove requests from queue
  8982. + spin_lock(&rtl->queue.lock);
  8983. + list_for_each_entry_safe(r, n, &rtl->queue.head, node) {
  8984. + set_bit(SSH_REQUEST_SF_LOCKED_BIT, &r->state);
  8985. + smp_mb__before_atomic();
  8986. + clear_bit(SSH_REQUEST_SF_QUEUED_BIT, &r->state);
  8987. +
  8988. + list_del(&r->node);
  8989. + list_add_tail(&r->node, &claimed);
  8990. + }
  8991. + spin_unlock(&rtl->queue.lock);
  8992. +
  8993. + /*
  8994. + * We have now guaranteed that the queue is empty and no more new
  8995. + * requests can be submitted (i.e. it will stay empty). This means that
  8996. + * calling ssh_rtl_tx_schedule will not schedule tx.work any more. So we
  8997. + * can simply call cancel_work_sync on tx.work here and when that
  8998. + * returns, we've locked it down. This also means that after this call,
  8999. + * we don't submit any more packets to the underlying packet layer, so
  9000. + * we can also shut that down.
  9001. + */
  9002. +
  9003. + cancel_work_sync(&rtl->tx.work);
  9004. + ssh_ptl_shutdown(&rtl->ptl);
  9005. + cancel_delayed_work_sync(&rtl->rtx_timeout.reaper);
  9006. +
  9007. + /*
  9008. + * Shutting down the packet layer should also have caneled all requests.
  9009. + * Thus the pending set should be empty. Attempt to handle this
  9010. + * gracefully anyways, even though this should be dead code.
  9011. + */
  9012. +
  9013. + pending = atomic_read(&rtl->pending.count);
  9014. + WARN_ON(pending);
  9015. +
  9016. + if (pending) {
  9017. + spin_lock(&rtl->pending.lock);
  9018. + list_for_each_entry_safe(r, n, &rtl->pending.head, node) {
  9019. + set_bit(SSH_REQUEST_SF_LOCKED_BIT, &r->state);
  9020. + smp_mb__before_atomic();
  9021. + clear_bit(SSH_REQUEST_SF_PENDING_BIT, &r->state);
  9022. +
  9023. + list_del(&r->node);
  9024. + list_add_tail(&r->node, &claimed);
  9025. + }
  9026. + spin_unlock(&rtl->pending.lock);
  9027. + }
  9028. +
  9029. + // finally cancel and complete requests
  9030. + list_for_each_entry_safe(r, n, &claimed, node) {
  9031. + // test_and_set because we still might compete with cancellation
  9032. + if (!test_and_set_bit(SSH_REQUEST_SF_COMPLETED_BIT, &r->state))
  9033. + ssh_rtl_complete_with_status(r, -ESHUTDOWN);
  9034. +
  9035. + // drop the reference we've obtained by removing it from list
  9036. + list_del(&r->node);
  9037. + ssh_request_put(r);
  9038. + }
  9039. +}
  9040. +
  9041. +
  9042. +/* -- Event notifier/callbacks. --------------------------------------------- */
  9043. +/*
  9044. + * The notifier system is based on linux/notifier.h, specifically the SRCU
  9045. + * implementation. The difference to that is, that some bits of the notifier
  9046. + * call return value can be tracked accross multiple calls. This is done so that
  9047. + * handling of events can be tracked and a warning can be issued in case an
  9048. + * event goes unhandled. The idea of that waring is that it should help discover
  9049. + * and identify new/currently unimplemented features.
  9050. + */
  9051. +
  9052. +struct ssam_nf_head {
  9053. + struct srcu_struct srcu;
  9054. + struct ssam_notifier_block __rcu *head;
  9055. +};
  9056. +
  9057. +
  9058. +int ssam_nfblk_call_chain(struct ssam_nf_head *nh, struct ssam_event *event)
  9059. +{
  9060. + struct ssam_notifier_block *nb, *next_nb;
  9061. + int ret = 0, idx;
  9062. +
  9063. + idx = srcu_read_lock(&nh->srcu);
  9064. +
  9065. + nb = rcu_dereference_raw(nh->head);
  9066. + while (nb) {
  9067. + next_nb = rcu_dereference_raw(nb->next);
  9068. +
  9069. + ret = (ret & SSAM_NOTIF_STATE_MASK) | nb->fn(nb, event);
  9070. + if (ret & SSAM_NOTIF_STOP)
  9071. + break;
  9072. +
  9073. + nb = next_nb;
  9074. + }
  9075. +
  9076. + srcu_read_unlock(&nh->srcu, idx);
  9077. + return ret;
  9078. +}
  9079. +
  9080. +/*
  9081. + * Note: This function must be synchronized by the caller with respect to other
  9082. + * insert and/or remove calls.
  9083. + */
  9084. +int __ssam_nfblk_insert(struct ssam_nf_head *nh, struct ssam_notifier_block *nb)
  9085. +{
  9086. + struct ssam_notifier_block **link = &nh->head;
  9087. +
  9088. + while ((*link) != NULL) {
  9089. + if (unlikely((*link) == nb)) {
  9090. + WARN(1, "double register detected");
  9091. + return -EINVAL;
  9092. + }
  9093. +
  9094. + if (nb->priority > (*link)->priority)
  9095. + break;
  9096. +
  9097. + link = &((*link)->next);
  9098. + }
  9099. +
  9100. + nb->next = *link;
  9101. + rcu_assign_pointer(*link, nb);
  9102. +
  9103. + return 0;
  9104. +}
  9105. +
  9106. +/*
  9107. + * Note: This function must be synchronized by the caller with respect to other
  9108. + * insert and/or remove calls. On success, the caller _must_ ensure SRCU
  9109. + * synchronization by calling `synchronize_srcu(&nh->srcu)` after leaving the
  9110. + * critical section, to ensure that the removed notifier block is not in use any
  9111. + * more.
  9112. + */
  9113. +int __ssam_nfblk_remove(struct ssam_nf_head *nh, struct ssam_notifier_block *nb)
  9114. +{
  9115. + struct ssam_notifier_block **link = &nh->head;
  9116. +
  9117. + while ((*link) != NULL) {
  9118. + if ((*link) == nb) {
  9119. + rcu_assign_pointer(*link, nb->next);
  9120. + return 0;
  9121. + }
  9122. +
  9123. + link = &((*link)->next);
  9124. + }
  9125. +
  9126. + return -ENOENT;
  9127. +}
  9128. +
  9129. +static int ssam_nf_head_init(struct ssam_nf_head *nh)
  9130. +{
  9131. + int status;
  9132. +
  9133. + status = init_srcu_struct(&nh->srcu);
  9134. + if (status)
  9135. + return status;
  9136. +
  9137. + nh->head = NULL;
  9138. + return 0;
  9139. +}
  9140. +
  9141. +static void ssam_nf_head_destroy(struct ssam_nf_head *nh)
  9142. +{
  9143. + cleanup_srcu_struct(&nh->srcu);
  9144. +}
  9145. +
  9146. +
  9147. +/* -- Event/notification registry. ------------------------------------------ */
  9148. +
  9149. +struct ssam_nf_refcount_key {
  9150. + struct ssam_event_registry reg;
  9151. + struct ssam_event_id id;
  9152. +};
  9153. +
  9154. +struct ssam_nf_refcount_entry {
  9155. + struct rb_node node;
  9156. + struct ssam_nf_refcount_key key;
  9157. + int refcount;
  9158. +};
  9159. +
  9160. +struct ssam_nf {
  9161. + struct mutex lock;
  9162. + struct rb_root refcount;
  9163. + struct ssam_nf_head head[SURFACE_SAM_SSH_NUM_EVENTS];
  9164. +};
  9165. +
  9166. +
  9167. +static int ssam_nf_refcount_inc(struct ssam_nf *nf,
  9168. + struct ssam_event_registry reg,
  9169. + struct ssam_event_id id)
  9170. +{
  9171. + struct ssam_nf_refcount_entry *entry;
  9172. + struct ssam_nf_refcount_key key;
  9173. + struct rb_node **link = &nf->refcount.rb_node;
  9174. + struct rb_node *parent;
  9175. + int cmp;
  9176. +
  9177. + key.reg = reg;
  9178. + key.id = id;
  9179. +
  9180. + while (*link) {
  9181. + entry = rb_entry(*link, struct ssam_nf_refcount_entry, node);
  9182. + parent = *link;
  9183. +
  9184. + cmp = memcmp(&key, &entry->key, sizeof(key));
  9185. + if (cmp < 0) {
  9186. + link = &(*link)->rb_left;
  9187. + } else if (cmp > 0) {
  9188. + link = &(*link)->rb_right;
  9189. + } else if (entry->refcount < INT_MAX) {
  9190. + return ++entry->refcount;
  9191. + } else {
  9192. + return -ENOSPC;
  9193. + }
  9194. + }
  9195. +
  9196. + entry = kzalloc(sizeof(*entry), GFP_KERNEL);
  9197. + if (!entry)
  9198. + return -ENOMEM;
  9199. +
  9200. + entry->key = key;
  9201. + entry->refcount = 1;
  9202. +
  9203. + rb_link_node(&entry->node, parent, link);
  9204. + rb_insert_color(&entry->node, &nf->refcount);
  9205. +
  9206. + return entry->refcount;
  9207. +}
  9208. +
  9209. +static int ssam_nf_refcount_dec(struct ssam_nf *nf,
  9210. + struct ssam_event_registry reg,
  9211. + struct ssam_event_id id)
  9212. +{
  9213. + struct ssam_nf_refcount_entry *entry;
  9214. + struct ssam_nf_refcount_key key;
  9215. + struct rb_node *node = nf->refcount.rb_node;
  9216. + int cmp, rc;
  9217. +
  9218. + key.reg = reg;
  9219. + key.id = id;
  9220. +
  9221. + while (node) {
  9222. + entry = rb_entry(node, struct ssam_nf_refcount_entry, node);
  9223. +
  9224. + cmp = memcmp(&key, &entry->key, sizeof(key));
  9225. + if (cmp < 0) {
  9226. + node = node->rb_left;
  9227. + } else if (cmp > 0) {
  9228. + node = node->rb_right;
  9229. + } else {
  9230. + rc = --entry->refcount;
  9231. +
  9232. + if (rc == 0) {
  9233. + rb_erase(&entry->node, &nf->refcount);
  9234. + kfree(entry);
  9235. + }
  9236. +
  9237. + return rc;
  9238. + }
  9239. + }
  9240. +
  9241. + return -ENOENT;
  9242. +}
  9243. +
  9244. +static void ssam_nf_call(struct ssam_nf *nf, struct device *dev, u16 rqid,
  9245. + struct ssam_event *event)
  9246. +{
  9247. + struct ssam_nf_head *nf_head;
  9248. + int status, nf_ret;
  9249. +
  9250. + if (!ssh_rqid_is_event(rqid)) {
  9251. + dev_warn(dev, "event: unsupported rqid: 0x%04x\n", rqid);
  9252. + return;
  9253. + }
  9254. +
  9255. + nf_head = &nf->head[ssh_rqid_to_event(rqid)];
  9256. + nf_ret = ssam_nfblk_call_chain(nf_head, event);
  9257. + status = ssam_notifier_to_errno(nf_ret);
  9258. +
  9259. + if (status < 0) {
  9260. + dev_err(dev, "event: error handling event: %d "
  9261. + "(tc: 0x%02x, cid: 0x%02x, iid: 0x%02x, chn: 0x%02x)\n",
  9262. + status, event->target_category, event->command_id,
  9263. + event->instance_id, event->channel);
  9264. + }
  9265. +
  9266. + if (!(nf_ret & SSAM_NOTIF_HANDLED)) {
  9267. + dev_warn(dev, "event: unhandled event (rqid: 0x%02x, "
  9268. + "tc: 0x%02x, cid: 0x%02x, iid: 0x%02x, chn: 0x%02x)\n",
  9269. + rqid, event->target_category, event->command_id,
  9270. + event->instance_id, event->channel);
  9271. + }
  9272. +}
  9273. +
  9274. +static int ssam_nf_register(struct ssam_nf *nf, struct ssam_event_notifier *n)
  9275. +{
  9276. + u16 rqid = ssh_tc_to_rqid(n->event.id.target_category);
  9277. + struct ssam_nf_head *nf_head;
  9278. + int rc, status;
  9279. +
  9280. + if (!ssh_rqid_is_event(rqid))
  9281. + return -EINVAL;
  9282. +
  9283. + nf_head = &nf->head[ssh_rqid_to_event(rqid)];
  9284. +
  9285. + mutex_lock(&nf->lock);
  9286. +
  9287. + rc = ssam_nf_refcount_inc(nf, n->event.reg, n->event.id);
  9288. + if (rc < 0) {
  9289. + mutex_lock(&nf->lock);
  9290. + return rc;
  9291. + }
  9292. +
  9293. + status = __ssam_nfblk_insert(nf_head, &n->base);
  9294. + if (status)
  9295. + ssam_nf_refcount_dec(nf, n->event.reg, n->event.id);
  9296. +
  9297. + mutex_unlock(&nf->lock);
  9298. + return status;
  9299. +}
  9300. +
  9301. +static int ssam_nf_unregister(struct ssam_nf *nf, struct ssam_event_notifier *n)
  9302. +{
  9303. + u16 rqid = ssh_tc_to_rqid(n->event.id.target_category);
  9304. + struct ssam_nf_head *nf_head;
  9305. + int status;
  9306. +
  9307. + if (!ssh_rqid_is_event(rqid))
  9308. + return -EINVAL;
  9309. +
  9310. + nf_head = &nf->head[ssh_rqid_to_event(rqid)];
  9311. +
  9312. + mutex_lock(&nf->lock);
  9313. +
  9314. + status = __ssam_nfblk_remove(nf_head, &n->base);
  9315. + if (status) {
  9316. + mutex_unlock(&nf->lock);
  9317. + return status;
  9318. + }
  9319. +
  9320. + ssam_nf_refcount_dec(nf, n->event.reg, n->event.id);
  9321. +
  9322. + mutex_unlock(&nf->lock);
  9323. + synchronize_srcu(&nf_head->srcu);
  9324. +
  9325. + return 0;
  9326. +}
  9327. +
  9328. +static int ssam_nf_init(struct ssam_nf *nf)
  9329. +{
  9330. + int i, status;
  9331. +
  9332. + for (i = 0; i < SURFACE_SAM_SSH_NUM_EVENTS; i++) {
  9333. + status = ssam_nf_head_init(&nf->head[i]);
  9334. + if (status)
  9335. + break;
  9336. + }
  9337. +
  9338. + if (status) {
  9339. + for (i = i - 1; i >= 0; i--)
  9340. + ssam_nf_head_destroy(&nf->head[i]);
  9341. +
  9342. + return status;
  9343. + }
  9344. +
  9345. + mutex_init(&nf->lock);
  9346. + return 0;
  9347. +}
  9348. +
  9349. +static void ssam_nf_destroy(struct ssam_nf *nf)
  9350. +{
  9351. + int i;
  9352. +
  9353. + for (i = 0; i < SURFACE_SAM_SSH_NUM_EVENTS; i++)
  9354. + ssam_nf_head_destroy(&nf->head[i]);
  9355. +
  9356. + mutex_destroy(&nf->lock);
  9357. +}
  9358. +
  9359. +
  9360. +/* -- Event/async request completion system. -------------------------------- */
  9361. +
  9362. +#define SSAM_CPLT_WQ_NAME "ssam_cpltq"
  9363. +
  9364. +
  9365. +struct ssam_cplt;
  9366. +
  9367. +struct ssam_event_item {
  9368. + struct list_head node;
  9369. + u16 rqid;
  9370. + struct ssam_event event; // must be last
  9371. +};
  9372. +
  9373. +struct ssam_event_queue {
  9374. + struct ssam_cplt *cplt;
  9375. +
  9376. + spinlock_t lock;
  9377. + struct list_head head;
  9378. + struct work_struct work;
  9379. +};
  9380. +
  9381. +struct ssam_event_channel {
  9382. + struct ssam_event_queue queue[SURFACE_SAM_SSH_NUM_EVENTS];
  9383. +};
  9384. +
  9385. +struct ssam_cplt {
  9386. + struct device *dev;
  9387. + struct workqueue_struct *wq;
  9388. +
  9389. + struct {
  9390. + struct ssam_event_channel channel[SURFACE_SAM_SSH_NUM_CHANNELS];
  9391. + struct ssam_nf notif;
  9392. + } event;
  9393. +};
  9394. +
  9395. +
  9396. +static void ssam_event_queue_push(struct ssam_event_queue *q,
  9397. + struct ssam_event_item *item)
  9398. +{
  9399. + spin_lock(&q->lock);
  9400. + list_add_tail(&item->node, &q->head);
  9401. + spin_unlock(&q->lock);
  9402. +}
  9403. +
  9404. +static struct ssam_event_item *ssam_event_queue_pop(struct ssam_event_queue *q)
  9405. +{
  9406. + struct ssam_event_item *item;
  9407. +
  9408. + spin_lock(&q->lock);
  9409. + item = list_first_entry_or_null(&q->head, struct ssam_event_item, node);
  9410. + if (item)
  9411. + list_del(&item->node);
  9412. + spin_unlock(&q->lock);
  9413. +
  9414. + return item;
  9415. +}
  9416. +
  9417. +static bool ssam_event_queue_is_empty(struct ssam_event_queue *q)
  9418. +{
  9419. + bool empty;
  9420. +
  9421. + spin_lock(&q->lock);
  9422. + empty = list_empty(&q->head);
  9423. + spin_unlock(&q->lock);
  9424. +
  9425. + return empty;
  9426. +}
  9427. +
  9428. +static struct ssam_event_queue *ssam_cplt_get_event_queue(
  9429. + struct ssam_cplt *cplt, u8 channel, u16 rqid)
  9430. +{
  9431. + u16 event = ssh_rqid_to_event(rqid);
  9432. + u16 chidx = ssh_channel_to_index(channel);
  9433. +
  9434. + if (!ssh_rqid_is_event(rqid)) {
  9435. + dev_err(cplt->dev, "event: unsupported rqid: 0x%04x\n", rqid);
  9436. + return NULL;
  9437. + }
  9438. +
  9439. + if (!ssh_channel_is_valid(channel)) {
  9440. + dev_warn(cplt->dev, "event: unsupported channel: %u\n",
  9441. + channel);
  9442. + chidx = 0;
  9443. + }
  9444. +
  9445. + return &cplt->event.channel[chidx].queue[event];
  9446. +}
  9447. +
  9448. +static inline bool ssam_cplt_submit(struct ssam_cplt *cplt,
  9449. + struct work_struct *work)
  9450. +{
  9451. + return queue_work(cplt->wq, work);
  9452. +}
  9453. +
  9454. +static int ssam_cplt_submit_event(struct ssam_cplt *cplt,
  9455. + struct ssam_event_item *item)
  9456. +{
  9457. + struct ssam_event_queue *evq;
  9458. +
  9459. + evq = ssam_cplt_get_event_queue(cplt, item->event.channel, item->rqid);
  9460. + if (!evq)
  9461. + return -EINVAL;
  9462. +
  9463. + ssam_event_queue_push(evq, item);
  9464. + ssam_cplt_submit(cplt, &evq->work);
  9465. + return 0;
  9466. +}
  9467. +
  9468. +static void ssam_cplt_flush(struct ssam_cplt *cplt)
  9469. +{
  9470. + flush_workqueue(cplt->wq);
  9471. +}
  9472. +
  9473. +static void ssam_event_queue_work_fn(struct work_struct *work)
  9474. +{
  9475. + struct ssam_event_queue *queue;
  9476. + struct ssam_event_item *item;
  9477. + struct ssam_nf *nf;
  9478. + struct device *dev;
  9479. + int i;
  9480. +
  9481. + queue = container_of(work, struct ssam_event_queue, work);
  9482. + nf = &queue->cplt->event.notif;
  9483. + dev = queue->cplt->dev;
  9484. +
  9485. + for (i = 0; i < 10; i++) {
  9486. + item = ssam_event_queue_pop(queue);
  9487. + if (item == NULL)
  9488. + return;
  9489. +
  9490. + ssam_nf_call(nf, dev, item->rqid, &item->event);
  9491. + kfree(item);
  9492. + }
  9493. +
  9494. + if (!ssam_event_queue_is_empty(queue))
  9495. + ssam_cplt_submit(queue->cplt, &queue->work);
  9496. +}
  9497. +
  9498. +static void ssam_event_queue_init(struct ssam_cplt *cplt,
  9499. + struct ssam_event_queue *evq)
  9500. +{
  9501. + evq->cplt = cplt;
  9502. + spin_lock_init(&evq->lock);
  9503. + INIT_LIST_HEAD(&evq->head);
  9504. + INIT_WORK(&evq->work, ssam_event_queue_work_fn);
  9505. +}
  9506. +
  9507. +static int ssam_cplt_init(struct ssam_cplt *cplt, struct device *dev)
  9508. +{
  9509. + struct ssam_event_channel *channel;
  9510. + int status, c, i;
  9511. +
  9512. + cplt->dev = dev;
  9513. +
  9514. + cplt->wq = create_workqueue(SSAM_CPLT_WQ_NAME);
  9515. + if (!cplt->wq)
  9516. + return -ENOMEM;
  9517. +
  9518. + for (c = 0; c < ARRAY_SIZE(cplt->event.channel); c++) {
  9519. + channel = &cplt->event.channel[c];
  9520. +
  9521. + for (i = 0; i < ARRAY_SIZE(channel->queue); i++)
  9522. + ssam_event_queue_init(cplt, &channel->queue[i]);
  9523. + }
  9524. +
  9525. + status = ssam_nf_init(&cplt->event.notif);
  9526. + if (status)
  9527. + destroy_workqueue(cplt->wq);
  9528. +
  9529. + return status;
  9530. +}
  9531. +
  9532. +static void ssam_cplt_destroy(struct ssam_cplt *cplt)
  9533. +{
  9534. + destroy_workqueue(cplt->wq);
  9535. + ssam_nf_destroy(&cplt->event.notif);
  9536. +}
  9537. +
  9538. +
  9539. +/* -- Top-Level Request Interface ------------------------------------------- */
  9540. +
  9541. +struct ssam_response {
  9542. + int status;
  9543. + u16 capacity;
  9544. + u16 length;
  9545. + u8 *pointer;
  9546. +};
  9547. +
  9548. +struct ssam_request_sync {
  9549. + struct ssh_request base;
  9550. + struct completion comp;
  9551. + struct ssam_response resp;
  9552. +};
  9553. +
  9554. +
  9555. +static void ssam_request_sync_complete(struct ssh_request *rqst,
  9556. + const struct ssh_command *cmd,
  9557. + const struct sshp_span *data, int status)
  9558. +{
  9559. + struct ssam_request_sync *r;
  9560. + struct ssh_rtl *rtl = READ_ONCE(rqst->rtl);
  9561. +
  9562. + r = container_of(rqst, struct ssam_request_sync, base);
  9563. + r->resp.status = status;
  9564. + r->resp.length = 0;
  9565. +
  9566. + if (status) {
  9567. + rtl_dbg_cond(rtl, "rsp: request failed: %d\n", status);
  9568. + return;
  9569. + }
  9570. +
  9571. + if (!data) // handle requests without a response
  9572. + return;
  9573. +
  9574. + if (!r->resp.pointer && data->len) {
  9575. + rtl_warn(rtl, "rsp: no response buffer provided, dropping data\n");
  9576. + return;
  9577. + }
  9578. +
  9579. + if (data->len > r->resp.capacity) {
  9580. + rtl_err(rtl, "rsp: response buffer too small,"
  9581. + " capacity: %u bytes, got: %zu bytes\n",
  9582. + r->resp.capacity, data->len);
  9583. + r->resp.status = -ENOSPC;
  9584. + return;
  9585. + }
  9586. +
  9587. + r->resp.length = data->len;
  9588. + memcpy(r->resp.pointer, data->ptr, data->len);
  9589. +}
  9590. +
  9591. +static void ssam_request_sync_release(struct ssh_request *rqst)
  9592. +{
  9593. + complete_all(&container_of(rqst, struct ssam_request_sync, base)->comp);
  9594. +}
  9595. +
  9596. +static const struct ssh_request_ops ssam_request_sync_ops = {
  9597. + .release = ssam_request_sync_release,
  9598. + .complete = ssam_request_sync_complete,
  9599. +};
  9600. +
  9601. +static void ssam_request_sync_wait_complete(struct ssam_request_sync *rqst)
  9602. +{
  9603. + wait_for_completion(&rqst->comp);
  9604. +}
  9605. +
  9606. +
  9607. +/* -- TODO ------------------------------------------------------------------ */
  9608. +
  9609. +enum ssh_ec_state {
  9610. + SSH_EC_UNINITIALIZED,
  9611. + SSH_EC_INITIALIZED,
  9612. + SSH_EC_SUSPENDED,
  9613. +};
  9614. +
  9615. +struct sam_ssh_ec {
  9616. + struct serdev_device *serdev;
  9617. +
  9618. + struct ssh_rtl rtl;
  9619. + struct ssam_cplt cplt;
  9620. +
  9621. + struct {
  9622. + struct ssh_seq_counter seq;
  9623. + struct ssh_rqid_counter rqid;
  9624. + } counter;
  9625. +
  9626. + enum ssh_ec_state state;
  9627. +
  9628. + int irq;
  9629. + bool irq_wakeup_enabled;
  9630. +};
  9631. +
  9632. +static struct sam_ssh_ec ssh_ec = {
  9633. + .state = SSH_EC_UNINITIALIZED,
  9634. + .serdev = NULL,
  9635. +};
  9636. +
  9637. +
  9638. +/* -- TODO ------------------------------------------------------------------ */
  9639. +
  9640. +#define ssh_dbg(ec, fmt, ...) dev_dbg(&(ec)->serdev->dev, fmt, ##__VA_ARGS__)
  9641. +#define ssh_warn(ec, fmt, ...) dev_warn(&(ec)->serdev->dev, fmt, ##__VA_ARGS__)
  9642. +#define ssh_err(ec, fmt, ...) dev_err(&(ec)->serdev->dev, fmt, ##__VA_ARGS__)
  9643. +
  9644. +
  9645. +static inline struct sam_ssh_ec *surface_sam_ssh_acquire(void)
  9646. +{
  9647. + return &ssh_ec;
  9648. +}
  9649. +
  9650. +static inline struct sam_ssh_ec *surface_sam_ssh_acquire_init(void)
  9651. +{
  9652. + struct sam_ssh_ec *ec = surface_sam_ssh_acquire();
  9653. +
  9654. + if (smp_load_acquire(&ec->state) == SSH_EC_UNINITIALIZED)
  9655. + return NULL;
  9656. +
  9657. + return ec;
  9658. +}
  9659. +
  9660. +int surface_sam_ssh_consumer_register(struct device *consumer)
  9661. +{
  9662. + u32 flags = DL_FLAG_PM_RUNTIME | DL_FLAG_AUTOREMOVE_CONSUMER;
  9663. + struct sam_ssh_ec *ec;
  9664. + struct device_link *link;
  9665. +
  9666. + ec = surface_sam_ssh_acquire_init();
  9667. + if (!ec)
  9668. + return -ENXIO;
  9669. +
  9670. + link = device_link_add(consumer, &ec->serdev->dev, flags);
  9671. + if (!link)
  9672. + return -EFAULT;
  9673. +
  9674. + return 0;
  9675. +}
  9676. +EXPORT_SYMBOL_GPL(surface_sam_ssh_consumer_register);
  9677. +
  9678. +
  9679. +static int __surface_sam_ssh_rqst(struct sam_ssh_ec *ec,
  9680. + const struct surface_sam_ssh_rqst *rqst,
  9681. + struct surface_sam_ssh_buf *result);
  9682. +
  9683. +static int surface_sam_ssh_event_enable(struct sam_ssh_ec *ec,
  9684. + struct ssam_event_registry reg,
  9685. + struct ssam_event_id id,
  9686. + u8 flags)
  9687. +{
  9688. + struct ssh_notification_params params;
  9689. + struct surface_sam_ssh_rqst rqst;
  9690. + struct surface_sam_ssh_buf result;
  9691. +
  9692. + u16 rqid = ssh_tc_to_rqid(id.target_category);
  9693. + u8 buf[1] = { 0x00 };
  9694. + int status;
  9695. +
  9696. + // only allow RQIDs that lie within event spectrum
  9697. + if (!ssh_rqid_is_event(rqid))
  9698. + return -EINVAL;
  9699. +
  9700. + params.target_category = id.target_category;
  9701. + params.instance_id = id.instance;
  9702. + params.flags = flags;
  9703. + put_unaligned_le16(rqid, &params.request_id);
  9704. +
  9705. + rqst.tc = reg.target_category;
  9706. + rqst.cid = reg.cid_enable;
  9707. + rqst.iid = 0x00;
  9708. + rqst.chn = reg.channel;
  9709. + rqst.snc = 0x01;
  9710. + rqst.cdl = sizeof(params);
  9711. + rqst.pld = (u8 *)&params;
  9712. +
  9713. + result.cap = ARRAY_SIZE(buf);
  9714. + result.len = 0;
  9715. + result.data = buf;
  9716. +
  9717. + status = __surface_sam_ssh_rqst(ec, &rqst, &result);
  9718. +
  9719. + if (status) {
  9720. + dev_err(&ec->serdev->dev, "failed to enable event source"
  9721. + " (tc: 0x%02x, rqid: 0x%04x)\n",
  9722. + id.target_category, rqid);
  9723. + }
  9724. +
  9725. + if (buf[0] != 0x00) {
  9726. + pr_warn(SSH_RQST_TAG_FULL
  9727. + "unexpected result while enabling event source: "
  9728. + "0x%02x\n", buf[0]);
  9729. + }
  9730. +
  9731. + return status;
  9732. +
  9733. +}
  9734. +
  9735. +static int surface_sam_ssh_event_disable(struct sam_ssh_ec *ec,
  9736. + struct ssam_event_registry reg,
  9737. + struct ssam_event_id id,
  9738. + u8 flags)
  9739. +{
  9740. + struct ssh_notification_params params;
  9741. + struct surface_sam_ssh_rqst rqst;
  9742. + struct surface_sam_ssh_buf result;
  9743. +
  9744. + u16 rqid = ssh_tc_to_rqid(id.target_category);
  9745. + u8 buf[1] = { 0x00 };
  9746. + int status;
  9747. +
  9748. + // only allow RQIDs that lie within event spectrum
  9749. + if (!ssh_rqid_is_event(rqid))
  9750. + return -EINVAL;
  9751. +
  9752. + params.target_category = id.target_category;
  9753. + params.instance_id = id.instance;
  9754. + params.flags = flags;
  9755. + put_unaligned_le16(rqid, &params.request_id);
  9756. +
  9757. + rqst.tc = reg.target_category;
  9758. + rqst.cid = reg.cid_disable;
  9759. + rqst.iid = 0x00;
  9760. + rqst.chn = reg.channel;
  9761. + rqst.snc = 0x01;
  9762. + rqst.cdl = sizeof(params);
  9763. + rqst.pld = (u8 *)&params;
  9764. +
  9765. + result.cap = ARRAY_SIZE(buf);
  9766. + result.len = 0;
  9767. + result.data = buf;
  9768. +
  9769. + status = __surface_sam_ssh_rqst(ec, &rqst, &result);
  9770. +
  9771. + if (status) {
  9772. + dev_err(&ec->serdev->dev, "failed to disable event source"
  9773. + " (tc: 0x%02x, rqid: 0x%04x)\n",
  9774. + id.target_category, rqid);
  9775. + }
  9776. +
  9777. + if (buf[0] != 0x00) {
  9778. + dev_warn(&ec->serdev->dev,
  9779. + "unexpected result while disabling event source: "
  9780. + "0x%02x\n", buf[0]);
  9781. + }
  9782. +
  9783. + return status;
  9784. +}
  9785. +
  9786. +
  9787. +int surface_sam_ssh_notifier_register(struct ssam_event_notifier *n)
  9788. +{
  9789. + struct ssam_nf_head *nf_head;
  9790. + struct sam_ssh_ec *ec;
  9791. + struct ssam_nf *nf;
  9792. + u16 event = ssh_tc_to_event(n->event.id.target_category);
  9793. + u16 rqid = ssh_event_to_rqid(event);
  9794. + int rc, status;
  9795. +
  9796. + if (!ssh_rqid_is_event(rqid))
  9797. + return -EINVAL;
  9798. +
  9799. + ec = surface_sam_ssh_acquire_init();
  9800. + if (!ec)
  9801. + return -ENXIO;
  9802. +
  9803. + nf = &ec->cplt.event.notif;
  9804. + nf_head = &nf->head[event];
  9805. +
  9806. + mutex_lock(&nf->lock);
  9807. +
  9808. + rc = ssam_nf_refcount_inc(nf, n->event.reg, n->event.id);
  9809. + if (rc < 0) {
  9810. + mutex_unlock(&nf->lock);
  9811. + return rc;
  9812. + }
  9813. +
  9814. + ssh_dbg(ec, "enabling event (tc: 0x%02x, rc: %d)\n", rqid, rc);
  9815. +
  9816. + status = __ssam_nfblk_insert(nf_head, &n->base);
  9817. + if (status) {
  9818. + ssam_nf_refcount_dec(nf, n->event.reg, n->event.id);
  9819. + mutex_unlock(&nf->lock);
  9820. + return status;
  9821. + }
  9822. +
  9823. + if (rc == 1) {
  9824. + status = surface_sam_ssh_event_enable(ec, n->event.reg, n->event.id, n->event.flags);
  9825. + if (status) {
  9826. + __ssam_nfblk_remove(nf_head, &n->base);
  9827. + ssam_nf_refcount_dec(nf, n->event.reg, n->event.id);
  9828. + mutex_unlock(&nf->lock);
  9829. + return status;
  9830. + }
  9831. + }
  9832. +
  9833. + mutex_unlock(&nf->lock);
  9834. + return 0;
  9835. +}
  9836. +EXPORT_SYMBOL_GPL(surface_sam_ssh_notifier_register);
  9837. +
  9838. +int surface_sam_ssh_notifier_unregister(struct ssam_event_notifier *n)
  9839. +{
  9840. + struct ssam_nf_head *nf_head;
  9841. + struct sam_ssh_ec *ec;
  9842. + struct ssam_nf *nf;
  9843. + u16 event = ssh_tc_to_event(n->event.id.target_category);
  9844. + u16 rqid = ssh_event_to_rqid(event);
  9845. + int rc, status = 0;
  9846. +
  9847. + if (!ssh_rqid_is_event(rqid))
  9848. + return -EINVAL;
  9849. +
  9850. + ec = surface_sam_ssh_acquire_init();
  9851. + if (!ec)
  9852. + return -ENXIO;
  9853. +
  9854. + nf = &ec->cplt.event.notif;
  9855. + nf_head = &nf->head[event];
  9856. +
  9857. + mutex_lock(&nf->lock);
  9858. +
  9859. + rc = ssam_nf_refcount_dec(nf, n->event.reg, n->event.id);
  9860. + if (rc < 0) {
  9861. + mutex_unlock(&nf->lock);
  9862. + return rc;
  9863. + }
  9864. +
  9865. + ssh_dbg(ec, "disabling event (tc: 0x%02x, rc: %d)\n", rqid, rc);
  9866. +
  9867. + if (rc == 0)
  9868. + status = surface_sam_ssh_event_disable(ec, n->event.reg, n->event.id, n->event.flags);
  9869. +
  9870. + __ssam_nfblk_remove(nf_head, &n->base);
  9871. + mutex_unlock(&nf->lock);
  9872. + synchronize_srcu(&nf_head->srcu);
  9873. +
  9874. + return status;
  9875. +}
  9876. +EXPORT_SYMBOL_GPL(surface_sam_ssh_notifier_unregister);
  9877. +
  9878. +
  9879. +static int __surface_sam_ssh_rqst(struct sam_ssh_ec *ec,
  9880. + const struct surface_sam_ssh_rqst *rqst,
  9881. + struct surface_sam_ssh_buf *result)
  9882. +{
  9883. + struct ssam_request_sync actual;
  9884. + struct msgbuf msgb;
  9885. + size_t msglen = SSH_COMMAND_MESSAGE_LENGTH(rqst->cdl);
  9886. + unsigned flags = 0;
  9887. + u16 rqid;
  9888. + u8 seq;
  9889. + int status;
  9890. +
  9891. + // prevent overflow
  9892. + if (rqst->cdl > SSH_COMMAND_MAX_PAYLOAD_SIZE) {
  9893. + ssh_err(ec, SSH_RQST_TAG "request payload too large\n");
  9894. + return -EINVAL;
  9895. + }
  9896. +
  9897. + if (result && result->data && rqst->snc)
  9898. + flags |= SSAM_REQUEST_HAS_RESPONSE;
  9899. +
  9900. + ssh_request_init(&actual.base, flags, &ssam_request_sync_ops);
  9901. + init_completion(&actual.comp);
  9902. +
  9903. + actual.resp.pointer = NULL;
  9904. + actual.resp.capacity = 0;
  9905. + actual.resp.length = 0;
  9906. + actual.resp.status = 0;
  9907. +
  9908. + if (result) {
  9909. + actual.resp.pointer = result->data;
  9910. + actual.resp.capacity = result->cap;
  9911. + }
  9912. +
  9913. + // alloc and create message
  9914. + status = msgb_alloc(&msgb, msglen, GFP_KERNEL);
  9915. + if (status)
  9916. + return status;
  9917. +
  9918. + seq = ssh_seq_next(&ec->counter.seq);
  9919. + rqid = ssh_rqid_next(&ec->counter.rqid);
  9920. + msgb_push_cmd(&msgb, seq, rqst, rqid);
  9921. +
  9922. + actual.base.packet.data = msgb.buffer;
  9923. + actual.base.packet.data_length = msgb.ptr - msgb.buffer;
  9924. +
  9925. + status = ssh_rtl_submit(&ec->rtl, &actual.base);
  9926. + if (status) {
  9927. + msgb_free(&msgb);
  9928. + return status;
  9929. + }
  9930. +
  9931. + ssh_request_put(&actual.base);
  9932. + ssam_request_sync_wait_complete(&actual);
  9933. + msgb_free(&msgb);
  9934. +
  9935. + if (result)
  9936. + result->len = actual.resp.length;
  9937. +
  9938. + return actual.resp.status;
  9939. +}
  9940. +
  9941. +int surface_sam_ssh_rqst(const struct surface_sam_ssh_rqst *rqst, struct surface_sam_ssh_buf *result)
  9942. +{
  9943. + struct sam_ssh_ec *ec;
  9944. +
  9945. + ec = surface_sam_ssh_acquire_init();
  9946. + if (!ec) {
  9947. + pr_warn(SSH_RQST_TAG_FULL "embedded controller is uninitialized\n");
  9948. + return -ENXIO;
  9949. + }
  9950. +
  9951. + if (smp_load_acquire(&ec->state) == SSH_EC_SUSPENDED) {
  9952. + ssh_warn(ec, SSH_RQST_TAG "embedded controller is suspended\n");
  9953. + return -EPERM;
  9954. + }
  9955. +
  9956. + return __surface_sam_ssh_rqst(ec, rqst, result);
  9957. +}
  9958. +EXPORT_SYMBOL_GPL(surface_sam_ssh_rqst);
  9959. +
  9960. +
  9961. +/**
  9962. + * surface_sam_ssh_ec_resume - Resume the EC if it is in a suspended mode.
  9963. + * @ec: the EC to resume
  9964. + *
  9965. + * Moves the EC from a suspended state to a normal state. See the
  9966. + * `surface_sam_ssh_ec_suspend` function what the specific differences of
  9967. + * these states are. Multiple repeated calls to this function seem to be
  9968. + * handled fine by the EC, after the first call, the state will remain
  9969. + * "normal".
  9970. + *
  9971. + * Must be called with the EC initialized and its lock held.
  9972. + */
  9973. +static int surface_sam_ssh_ec_resume(struct sam_ssh_ec *ec)
  9974. +{
  9975. + u8 buf[1] = { 0x00 };
  9976. + int status;
  9977. +
  9978. + struct surface_sam_ssh_rqst rqst = {
  9979. + .tc = 0x01,
  9980. + .cid = 0x16,
  9981. + .iid = 0x00,
  9982. + .chn = 0x01,
  9983. + .snc = 0x01,
  9984. + .cdl = 0x00,
  9985. + .pld = NULL,
  9986. + };
  9987. +
  9988. + struct surface_sam_ssh_buf result = {
  9989. + result.cap = ARRAY_SIZE(buf),
  9990. + result.len = 0,
  9991. + result.data = buf,
  9992. + };
  9993. +
  9994. + ssh_dbg(ec, "pm: resuming system aggregator module\n");
  9995. + status = __surface_sam_ssh_rqst(ec, &rqst, &result);
  9996. + if (status)
  9997. + return status;
  9998. +
  9999. + /*
  10000. + * The purpose of the return value of this request is unknown. Based on
  10001. + * logging and experience, we expect it to be zero. No other value has
  10002. + * been observed so far.
  10003. + */
  10004. + if (buf[0] != 0x00) {
  10005. + ssh_warn(ec, "unexpected result while trying to resume EC: "
  10006. + "0x%02x\n", buf[0]);
  10007. + }
  10008. +
  10009. + return 0;
  10010. +}
  10011. +
  10012. +/**
  10013. + * surface_sam_ssh_ec_suspend - Put the EC in a suspended mode:
  10014. + * @ec: the EC to suspend
  10015. + *
  10016. + * Tells the EC to enter a suspended mode. In this mode, events are quiesced
  10017. + * and the wake IRQ is armed (note that the wake IRQ does not fire if the EC
  10018. + * has not been suspended via this request). On some devices, the keyboard
  10019. + * backlight is turned off. Apart from this, the EC seems to continue to work
  10020. + * as normal, meaning requests sent to it are acknowledged and seem to be
  10021. + * correctly handled, including potential responses. Multiple repeated calls
  10022. + * to this function seem to be handled fine by the EC, after the first call,
  10023. + * the state will remain "suspended".
  10024. + *
  10025. + * Must be called with the EC initialized and its lock held.
  10026. + */
  10027. +static int surface_sam_ssh_ec_suspend(struct sam_ssh_ec *ec)
  10028. +{
  10029. + u8 buf[1] = { 0x00 };
  10030. + int status;
  10031. +
  10032. + struct surface_sam_ssh_rqst rqst = {
  10033. + .tc = 0x01,
  10034. + .cid = 0x15,
  10035. + .iid = 0x00,
  10036. + .chn = 0x01,
  10037. + .snc = 0x01,
  10038. + .cdl = 0x00,
  10039. + .pld = NULL,
  10040. + };
  10041. +
  10042. + struct surface_sam_ssh_buf result = {
  10043. + result.cap = ARRAY_SIZE(buf),
  10044. + result.len = 0,
  10045. + result.data = buf,
  10046. + };
  10047. +
  10048. + ssh_dbg(ec, "pm: suspending system aggregator module\n");
  10049. + status = __surface_sam_ssh_rqst(ec, &rqst, &result);
  10050. + if (status)
  10051. + return status;
  10052. +
  10053. + /*
  10054. + * The purpose of the return value of this request is unknown. Based on
  10055. + * logging and experience, we expect it to be zero. No other value has
  10056. + * been observed so far.
  10057. + */
  10058. + if (buf[0] != 0x00) {
  10059. + ssh_warn(ec, "unexpected result while trying to suspend EC: "
  10060. + "0x%02x\n", buf[0]);
  10061. + }
  10062. +
  10063. + return 0;
  10064. +}
  10065. +
  10066. +
  10067. +static int surface_sam_ssh_get_controller_version(struct sam_ssh_ec *ec, u32 *version)
  10068. +{
  10069. + struct surface_sam_ssh_rqst rqst = {
  10070. + .tc = 0x01,
  10071. + .cid = 0x13,
  10072. + .iid = 0x00,
  10073. + .chn = 0x01,
  10074. + .snc = 0x01,
  10075. + .cdl = 0x00,
  10076. + .pld = NULL,
  10077. + };
  10078. +
  10079. + struct surface_sam_ssh_buf result = {
  10080. + result.cap = sizeof(*version),
  10081. + result.len = 0,
  10082. + result.data = (u8 *)version,
  10083. + };
  10084. +
  10085. + *version = 0;
  10086. + return __surface_sam_ssh_rqst(ec, &rqst, &result);
  10087. +}
  10088. +
  10089. +static int surface_sam_ssh_log_controller_version(struct sam_ssh_ec *ec)
  10090. +{
  10091. + u32 version, a, b, c;
  10092. + int status;
  10093. +
  10094. + status = surface_sam_ssh_get_controller_version(ec, &version);
  10095. + if (status)
  10096. + return status;
  10097. +
  10098. + a = (version >> 24) & 0xff;
  10099. + b = le16_to_cpu((version >> 8) & 0xffff);
  10100. + c = version & 0xff;
  10101. +
  10102. + dev_info(&ec->serdev->dev, "SAM controller version: %u.%u.%u\n",
  10103. + a, b, c);
  10104. + return 0;
  10105. +}
  10106. +
  10107. +
  10108. +static const struct acpi_gpio_params gpio_ssh_wakeup_int = { 0, 0, false };
  10109. +static const struct acpi_gpio_params gpio_ssh_wakeup = { 1, 0, false };
  10110. +
  10111. +static const struct acpi_gpio_mapping ssh_acpi_gpios[] = {
  10112. + { "ssh_wakeup-int-gpio", &gpio_ssh_wakeup_int, 1 },
  10113. + { "ssh_wakeup-gpio", &gpio_ssh_wakeup, 1 },
  10114. + { },
  10115. +};
  10116. +
  10117. +static irqreturn_t ssh_wake_irq_handler(int irq, void *dev_id)
  10118. +{
  10119. + struct serdev_device *serdev = dev_id;
  10120. +
  10121. + dev_dbg(&serdev->dev, "pm: wake irq triggered\n");
  10122. +
  10123. + // TODO: Send GPIO callback command repeatedly to EC until callback
  10124. + // returns 0x00. Return flag of callback is "has more events".
  10125. + // Each time the command is sent, one event is "released". Once
  10126. + // all events have been released (return = 0x00), the GPIO is
  10127. + // re-armed.
  10128. +
  10129. + return IRQ_HANDLED;
  10130. +}
  10131. +
  10132. +static int ssh_setup_irq(struct serdev_device *serdev)
  10133. +{
  10134. + const int irqf = IRQF_SHARED | IRQF_ONESHOT | IRQF_TRIGGER_RISING;
  10135. + struct gpio_desc *gpiod;
  10136. + int irq;
  10137. + int status;
  10138. +
  10139. + gpiod = gpiod_get(&serdev->dev, "ssh_wakeup-int", GPIOD_ASIS);
  10140. + if (IS_ERR(gpiod))
  10141. + return PTR_ERR(gpiod);
  10142. +
  10143. + irq = gpiod_to_irq(gpiod);
  10144. + gpiod_put(gpiod);
  10145. +
  10146. + if (irq < 0)
  10147. + return irq;
  10148. +
  10149. + status = request_threaded_irq(irq, NULL, ssh_wake_irq_handler,
  10150. + irqf, "surface_sam_sh_wakeup", serdev);
  10151. + if (status)
  10152. + return status;
  10153. +
  10154. + return irq;
  10155. +}
  10156. +
  10157. +
  10158. +static acpi_status ssh_setup_from_resource(struct acpi_resource *rsc, void *ctx)
  10159. +{
  10160. + struct serdev_device *serdev = ctx;
  10161. + struct acpi_resource_common_serialbus *serial;
  10162. + struct acpi_resource_uart_serialbus *uart;
  10163. + bool flow_control;
  10164. + int status = 0;
  10165. +
  10166. + if (rsc->type != ACPI_RESOURCE_TYPE_SERIAL_BUS)
  10167. + return AE_OK;
  10168. +
  10169. + serial = &rsc->data.common_serial_bus;
  10170. + if (serial->type != ACPI_RESOURCE_SERIAL_TYPE_UART)
  10171. + return AE_OK;
  10172. +
  10173. + uart = &rsc->data.uart_serial_bus;
  10174. +
  10175. + // set up serdev device
  10176. + serdev_device_set_baudrate(serdev, uart->default_baud_rate);
  10177. +
  10178. + // serdev currently only supports RTSCTS flow control
  10179. + if (uart->flow_control & SSH_SUPPORTED_FLOW_CONTROL_MASK) {
  10180. + dev_warn(&serdev->dev, "setup: unsupported flow control"
  10181. + " (value: 0x%02x)\n", uart->flow_control);
  10182. + }
  10183. +
  10184. + // set RTSCTS flow control
  10185. + flow_control = uart->flow_control & ACPI_UART_FLOW_CONTROL_HW;
  10186. + serdev_device_set_flow_control(serdev, flow_control);
  10187. +
  10188. + // serdev currently only supports EVEN/ODD parity
  10189. + switch (uart->parity) {
  10190. + case ACPI_UART_PARITY_NONE:
  10191. + status = serdev_device_set_parity(serdev, SERDEV_PARITY_NONE);
  10192. + break;
  10193. + case ACPI_UART_PARITY_EVEN:
  10194. + status = serdev_device_set_parity(serdev, SERDEV_PARITY_EVEN);
  10195. + break;
  10196. + case ACPI_UART_PARITY_ODD:
  10197. + status = serdev_device_set_parity(serdev, SERDEV_PARITY_ODD);
  10198. + break;
  10199. + default:
  10200. + dev_warn(&serdev->dev, "setup: unsupported parity"
  10201. + " (value: 0x%02x)\n", uart->parity);
  10202. + break;
  10203. + }
  10204. +
  10205. + if (status) {
  10206. + dev_err(&serdev->dev, "setup: failed to set parity"
  10207. + " (value: 0x%02x)\n", uart->parity);
  10208. + return status;
  10209. + }
  10210. +
  10211. + return AE_CTRL_TERMINATE; // we've found the resource and are done
  10212. +}
  10213. +
  10214. +
  10215. +static int surface_sam_ssh_suspend(struct device *dev)
  10216. +{
  10217. + struct sam_ssh_ec *ec;
  10218. + int status;
  10219. +
  10220. + dev_dbg(dev, "pm: suspending\n");
  10221. +
  10222. + ec = surface_sam_ssh_acquire_init();
  10223. + if (ec) {
  10224. + status = surface_sam_ssh_ec_suspend(ec);
  10225. + if (status)
  10226. + return status;
  10227. +
  10228. + if (device_may_wakeup(dev)) {
  10229. + status = enable_irq_wake(ec->irq);
  10230. + if (status)
  10231. + return status;
  10232. +
  10233. + ec->irq_wakeup_enabled = true;
  10234. + } else {
  10235. + ec->irq_wakeup_enabled = false;
  10236. + }
  10237. +
  10238. + smp_store_release(&ec->state, SSH_EC_SUSPENDED);
  10239. + }
  10240. +
  10241. + return 0;
  10242. +}
  10243. +
  10244. +static int surface_sam_ssh_resume(struct device *dev)
  10245. +{
  10246. + struct sam_ssh_ec *ec;
  10247. + int status;
  10248. +
  10249. + dev_dbg(dev, "pm: resuming\n");
  10250. +
  10251. + ec = surface_sam_ssh_acquire_init();
  10252. + if (ec) {
  10253. + smp_store_release(&ec->state, SSH_EC_INITIALIZED);
  10254. +
  10255. + if (ec->irq_wakeup_enabled) {
  10256. + status = disable_irq_wake(ec->irq);
  10257. + if (status)
  10258. + return status;
  10259. +
  10260. + ec->irq_wakeup_enabled = false;
  10261. + }
  10262. +
  10263. + status = surface_sam_ssh_ec_resume(ec);
  10264. + if (status)
  10265. + return status;
  10266. + }
  10267. +
  10268. + return 0;
  10269. +}
  10270. +
  10271. +static SIMPLE_DEV_PM_OPS(surface_sam_ssh_pm_ops, surface_sam_ssh_suspend,
  10272. + surface_sam_ssh_resume);
  10273. +
  10274. +
  10275. +static void ssam_handle_event(struct ssh_rtl *rtl,
  10276. + const struct ssh_command *cmd,
  10277. + const struct sshp_span *data)
  10278. +{
  10279. + struct sam_ssh_ec *ec = container_of(rtl, struct sam_ssh_ec, rtl);
  10280. + struct ssam_event_item *item;
  10281. +
  10282. + item = kzalloc(sizeof(struct ssam_event_item) + data->len, GFP_KERNEL);
  10283. + if (!item)
  10284. + return;
  10285. +
  10286. + item->rqid = get_unaligned_le16(&cmd->rqid);
  10287. + item->event.target_category = cmd->tc;
  10288. + item->event.command_id = cmd->cid;
  10289. + item->event.instance_id = cmd->iid;
  10290. + item->event.channel = cmd->chn_in;
  10291. + item->event.length = data->len;
  10292. + memcpy(&item->event.data[0], data->ptr, data->len);
  10293. +
  10294. + ssam_cplt_submit_event(&ec->cplt, item);
  10295. +}
  10296. +
  10297. +static struct ssh_rtl_ops ssam_rtl_ops = {
  10298. + .handle_event = ssam_handle_event,
  10299. +};
  10300. +
  10301. +
  10302. +static int ssam_receive_buf(struct serdev_device *dev, const unsigned char *buf, size_t n)
  10303. +{
  10304. + struct sam_ssh_ec *ec = serdev_device_get_drvdata(dev);
  10305. + return ssh_ptl_rx_rcvbuf(&ec->rtl.ptl, buf, n);
  10306. +}
  10307. +
  10308. +static void ssam_write_wakeup(struct serdev_device *dev)
  10309. +{
  10310. + struct sam_ssh_ec *ec = serdev_device_get_drvdata(dev);
  10311. + ssh_ptl_tx_wakeup(&ec->rtl.ptl, true);
  10312. +}
  10313. +
  10314. +struct serdev_device_ops ssam_serdev_ops = {
  10315. + .receive_buf = ssam_receive_buf,
  10316. + .write_wakeup = ssam_write_wakeup,
  10317. +};
  10318. +
  10319. +
  10320. +#ifdef CONFIG_SURFACE_SAM_SSH_DEBUG_DEVICE
  10321. +
  10322. +static char sam_ssh_debug_rqst_buf_sysfs[256] = { 0 };
  10323. +static char sam_ssh_debug_rqst_buf_pld[255] = { 0 };
  10324. +static char sam_ssh_debug_rqst_buf_res[255] = { 0 };
  10325. +
  10326. +struct sysfs_rqst {
  10327. + u8 tc;
  10328. + u8 cid;
  10329. + u8 iid;
  10330. + u8 chn;
  10331. + u8 snc;
  10332. + u8 cdl;
  10333. + u8 pld[0];
  10334. +} __packed;
  10335. +
  10336. +static ssize_t rqst_read(struct file *f, struct kobject *kobj, struct bin_attribute *attr,
  10337. + char *buf, loff_t offs, size_t count)
  10338. +{
  10339. + if (offs < 0 || count + offs > ARRAY_SIZE(sam_ssh_debug_rqst_buf_sysfs))
  10340. + return -EINVAL;
  10341. +
  10342. + memcpy(buf, sam_ssh_debug_rqst_buf_sysfs + offs, count);
  10343. + return count;
  10344. +}
  10345. +
  10346. +static ssize_t rqst_write(struct file *f, struct kobject *kobj, struct bin_attribute *attr,
  10347. + char *buf, loff_t offs, size_t count)
  10348. +{
  10349. + struct sysfs_rqst *input;
  10350. + struct surface_sam_ssh_rqst rqst = {};
  10351. + struct surface_sam_ssh_buf result = {};
  10352. + int status;
  10353. +
  10354. + // check basic write constriants
  10355. + if (offs != 0 || count - sizeof(struct sysfs_rqst) > ARRAY_SIZE(sam_ssh_debug_rqst_buf_pld))
  10356. + return -EINVAL;
  10357. +
  10358. + if (count < sizeof(struct sysfs_rqst))
  10359. + return -EINVAL;
  10360. +
  10361. + input = (struct sysfs_rqst *)buf;
  10362. +
  10363. + // payload length should be consistent with data provided
  10364. + if (input->cdl + sizeof(struct sysfs_rqst) != count)
  10365. + return -EINVAL;
  10366. +
  10367. + rqst.tc = input->tc;
  10368. + rqst.cid = input->cid;
  10369. + rqst.iid = input->iid;
  10370. + rqst.chn = input->chn;
  10371. + rqst.snc = input->snc;
  10372. + rqst.cdl = input->cdl;
  10373. + rqst.pld = sam_ssh_debug_rqst_buf_pld;
  10374. + memcpy(sam_ssh_debug_rqst_buf_pld, &input->pld[0], input->cdl);
  10375. +
  10376. + result.cap = ARRAY_SIZE(sam_ssh_debug_rqst_buf_res);
  10377. + result.len = 0;
  10378. + result.data = sam_ssh_debug_rqst_buf_res;
  10379. +
  10380. + status = surface_sam_ssh_rqst(&rqst, &result);
  10381. + if (status)
  10382. + return status;
  10383. +
  10384. + sam_ssh_debug_rqst_buf_sysfs[0] = result.len;
  10385. + memcpy(sam_ssh_debug_rqst_buf_sysfs + 1, result.data, result.len);
  10386. + memset(sam_ssh_debug_rqst_buf_sysfs + result.len + 1, 0,
  10387. + ARRAY_SIZE(sam_ssh_debug_rqst_buf_sysfs) + 1 - result.len);
  10388. +
  10389. + return count;
  10390. +}
  10391. +
  10392. +static const BIN_ATTR_RW(rqst, ARRAY_SIZE(sam_ssh_debug_rqst_buf_sysfs));
  10393. +
  10394. +static int surface_sam_ssh_sysfs_register(struct device *dev)
  10395. +{
  10396. + return sysfs_create_bin_file(&dev->kobj, &bin_attr_rqst);
  10397. +}
  10398. +
  10399. +static void surface_sam_ssh_sysfs_unregister(struct device *dev)
  10400. +{
  10401. + sysfs_remove_bin_file(&dev->kobj, &bin_attr_rqst);
  10402. +}
  10403. +
  10404. +#else /* CONFIG_SURFACE_SAM_SSH_DEBUG_DEVICE */
  10405. +
  10406. +static int surface_sam_ssh_sysfs_register(struct device *dev)
  10407. +{
  10408. + return 0;
  10409. +}
  10410. +
  10411. +static void surface_sam_ssh_sysfs_unregister(struct device *dev)
  10412. +{
  10413. +}
  10414. +
  10415. +#endif /* CONFIG_SURFACE_SAM_SSH_DEBUG_DEVICE */
  10416. +
  10417. +
  10418. +static int surface_sam_ssh_probe(struct serdev_device *serdev)
  10419. +{
  10420. + struct sam_ssh_ec *ec;
  10421. + acpi_handle *ssh = ACPI_HANDLE(&serdev->dev);
  10422. + int status, irq;
  10423. +
  10424. + if (gpiod_count(&serdev->dev, NULL) < 0)
  10425. + return -ENODEV;
  10426. +
  10427. + status = devm_acpi_dev_add_driver_gpios(&serdev->dev, ssh_acpi_gpios);
  10428. + if (status)
  10429. + return status;
  10430. +
  10431. + // setup IRQ
  10432. + irq = ssh_setup_irq(serdev);
  10433. + if (irq < 0)
  10434. + return irq;
  10435. +
  10436. + // set up EC
  10437. + ec = surface_sam_ssh_acquire();
  10438. + if (smp_load_acquire(&ec->state) != SSH_EC_UNINITIALIZED) {
  10439. + dev_err(&serdev->dev, "embedded controller already initialized\n");
  10440. +
  10441. + status = -EBUSY;
  10442. + goto err_ecinit;
  10443. + }
  10444. +
  10445. + ec->serdev = serdev;
  10446. + ec->irq = irq;
  10447. + ssh_seq_reset(&ec->counter.seq);
  10448. + ssh_rqid_reset(&ec->counter.rqid);
  10449. +
  10450. + // initialize event/request completion system
  10451. + status = ssam_cplt_init(&ec->cplt, &serdev->dev);
  10452. + if (status)
  10453. + goto err_ecinit;
  10454. +
  10455. + // initialize request and packet transmission layers
  10456. + status = ssh_rtl_init(&ec->rtl, serdev, &ssam_rtl_ops);
  10457. + if (status)
  10458. + goto err_rtl;
  10459. +
  10460. + serdev_device_set_drvdata(serdev, ec);
  10461. +
  10462. + serdev_device_set_client_ops(serdev, &ssam_serdev_ops);
  10463. + status = serdev_device_open(serdev);
  10464. + if (status)
  10465. + goto err_open;
  10466. +
  10467. + status = acpi_walk_resources(ssh, METHOD_NAME__CRS,
  10468. + ssh_setup_from_resource, serdev);
  10469. + if (ACPI_FAILURE(status))
  10470. + goto err_devinit;
  10471. +
  10472. + status = ssh_rtl_tx_start(&ec->rtl);
  10473. + if (status)
  10474. + goto err_devinit;
  10475. +
  10476. + status = ssh_rtl_rx_start(&ec->rtl);
  10477. + if (status)
  10478. + goto err_devinit;
  10479. +
  10480. + smp_store_release(&ec->state, SSH_EC_INITIALIZED);
  10481. +
  10482. + status = surface_sam_ssh_log_controller_version(ec);
  10483. + if (status)
  10484. + goto err_finalize;
  10485. +
  10486. + status = surface_sam_ssh_ec_resume(ec);
  10487. + if (status)
  10488. + goto err_finalize;
  10489. +
  10490. + status = surface_sam_ssh_sysfs_register(&serdev->dev);
  10491. + if (status)
  10492. + goto err_finalize;
  10493. +
  10494. + // TODO: The EC can wake up the system via the associated GPIO interrupt in
  10495. + // multiple situations. One of which is the remaining battery capacity
  10496. + // falling below a certain threshold. Normally, we should use the
  10497. + // device_init_wakeup function, however, the EC also seems to have other
  10498. + // reasons for waking up the system and it seems that Windows has
  10499. + // additional checks whether the system should be resumed. In short, this
  10500. + // causes some spourious unwanted wake-ups. For now let's thus default
  10501. + // power/wakeup to false.
  10502. + device_set_wakeup_capable(&serdev->dev, true);
  10503. + acpi_walk_dep_device_list(ssh);
  10504. +
  10505. + return 0;
  10506. +
  10507. +err_finalize:
  10508. + smp_store_release(&ec->state, SSH_EC_UNINITIALIZED);
  10509. + ssh_rtl_flush(&ec->rtl, msecs_to_jiffies(5000));
  10510. +err_devinit:
  10511. + serdev_device_close(serdev);
  10512. +err_open:
  10513. + ssh_rtl_shutdown(&ec->rtl);
  10514. + ssh_rtl_destroy(&ec->rtl);
  10515. +err_rtl:
  10516. + ssam_cplt_flush(&ec->cplt);
  10517. + ssam_cplt_destroy(&ec->cplt);
  10518. +err_ecinit:
  10519. + free_irq(irq, serdev);
  10520. + serdev_device_set_drvdata(serdev, NULL);
  10521. + return status;
  10522. +}
  10523. +
  10524. +static void surface_sam_ssh_remove(struct serdev_device *serdev)
  10525. +{
  10526. + struct sam_ssh_ec *ec;
  10527. + int status;
  10528. +
  10529. + ec = surface_sam_ssh_acquire_init();
  10530. + if (!ec)
  10531. + return;
  10532. +
  10533. + free_irq(ec->irq, serdev);
  10534. + surface_sam_ssh_sysfs_unregister(&serdev->dev);
  10535. +
  10536. + // suspend EC and disable events
  10537. + status = surface_sam_ssh_ec_suspend(ec);
  10538. + if (status)
  10539. + dev_err(&serdev->dev, "failed to suspend EC: %d\n", status);
  10540. +
  10541. + // flush pending events and requests while everything still works
  10542. + status = ssh_rtl_flush(&ec->rtl, msecs_to_jiffies(5000));
  10543. + if (status)
  10544. + dev_err(&serdev->dev, "failed to flush request transmission layer: %d\n", status);
  10545. +
  10546. + ssam_cplt_flush(&ec->cplt);
  10547. +
  10548. + // mark device as uninitialized
  10549. + smp_store_release(&ec->state, SSH_EC_UNINITIALIZED);
  10550. +
  10551. + // cancel rem. requests, ensure no new ones can be queued, stop threads
  10552. + ssh_rtl_tx_flush(&ec->rtl);
  10553. + ssh_rtl_shutdown(&ec->rtl);
  10554. +
  10555. + // shut down actual transport
  10556. + serdev_device_wait_until_sent(ec->serdev, 0);
  10557. + serdev_device_close(ec->serdev);
  10558. +
  10559. + /*
  10560. + * Ensure _all_ events are completed. New ones could still have been
  10561. + * received after the last flush, before the request transport layer
  10562. + * has been shut down. At this point we can be sure that no requests
  10563. + * will remain after this call.
  10564. + */
  10565. + ssam_cplt_flush(&ec->cplt);
  10566. +
  10567. + // actually free resources
  10568. + ssam_cplt_destroy(&ec->cplt);
  10569. + ssh_rtl_destroy(&ec->rtl);
  10570. +
  10571. + ec->serdev = NULL;
  10572. + ec->irq = -1;
  10573. +
  10574. + device_set_wakeup_capable(&serdev->dev, false);
  10575. + serdev_device_set_drvdata(serdev, NULL);
  10576. +}
  10577. +
  10578. +
  10579. +static const struct acpi_device_id surface_sam_ssh_match[] = {
  10580. + { "MSHW0084", 0 },
  10581. + { },
  10582. +};
  10583. +MODULE_DEVICE_TABLE(acpi, surface_sam_ssh_match);
  10584. +
  10585. +static struct serdev_device_driver surface_sam_ssh = {
  10586. + .probe = surface_sam_ssh_probe,
  10587. + .remove = surface_sam_ssh_remove,
  10588. + .driver = {
  10589. + .name = "surface_sam_ssh",
  10590. + .acpi_match_table = surface_sam_ssh_match,
  10591. + .pm = &surface_sam_ssh_pm_ops,
  10592. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  10593. + },
  10594. +};
  10595. +
  10596. +
  10597. +static int __init surface_sam_ssh_init(void)
  10598. +{
  10599. + return serdev_device_driver_register(&surface_sam_ssh);
  10600. +}
  10601. +
  10602. +static void __exit surface_sam_ssh_exit(void)
  10603. +{
  10604. + serdev_device_driver_unregister(&surface_sam_ssh);
  10605. +}
  10606. +
  10607. +/*
  10608. + * Ensure that the driver is loaded late due to some issues with the UART
  10609. + * communication. Specifically, we want to ensure that DMA is ready and being
  10610. + * used. Not using DMA can result in spurious communication failures,
  10611. + * especially during boot, which among other things will result in wrong
  10612. + * battery information (via ACPI _BIX) being displayed. Using a late init_call
  10613. + * instead of the normal module_init gives the DMA subsystem time to
  10614. + * initialize and via that results in a more stable communication, avoiding
  10615. + * such failures.
  10616. + */
  10617. +late_initcall(surface_sam_ssh_init);
  10618. +module_exit(surface_sam_ssh_exit);
  10619. +
  10620. +MODULE_AUTHOR("Maximilian Luz <luzmaximilian@gmail.com>");
  10621. +MODULE_DESCRIPTION("Surface Serial Hub Driver for 5th Generation Surface Devices");
  10622. +MODULE_LICENSE("GPL");
  10623. diff --git a/drivers/platform/x86/surface_sam/surface_sam_ssh.h b/drivers/platform/x86/surface_sam/surface_sam_ssh.h
  10624. new file mode 100644
  10625. index 000000000000..25a3ae85fee7
  10626. --- /dev/null
  10627. +++ b/drivers/platform/x86/surface_sam/surface_sam_ssh.h
  10628. @@ -0,0 +1,488 @@
  10629. +/* SPDX-License-Identifier: GPL-2.0-or-later */
  10630. +/*
  10631. + * Interface for Surface Serial Hub (SSH).
  10632. + *
  10633. + * The SSH is the main communication hub for communication between host and
  10634. + * the Surface/System Aggregator Module (SAM) on newer Microsoft Surface
  10635. + * devices (Book 2, Pro 5, Laptops, ...). Also referred to as SAM-over-SSH.
  10636. + * Older devices (Book 1, Pro 4) use SAM-over-HID (via I2C).
  10637. + */
  10638. +
  10639. +#ifndef _SURFACE_SAM_SSH_H
  10640. +#define _SURFACE_SAM_SSH_H
  10641. +
  10642. +#include <linux/types.h>
  10643. +#include <linux/device.h>
  10644. +
  10645. +
  10646. +/* -- Data structures for SAM-over-SSH communication. ----------------------- */
  10647. +
  10648. +/**
  10649. + * enum ssh_frame_type - Frame types for SSH frames.
  10650. + * @SSH_FRAME_TYPE_DATA_SEQ: Indicates a data frame, followed by a payload with
  10651. + * the length specified in the ssh_frame.len field. This
  10652. + * frame is sequenced, meaning that an ACK is required.
  10653. + * @SSH_FRAME_TYPE_DATA_NSQ: Same as SSH_FRAME_TYPE_DATA_SEQ, but unsequenced,
  10654. + * meaning that the message does not have to be ACKed.
  10655. + * @SSH_FRAME_TYPE_ACK: Indicates an ACK message.
  10656. + * @SSH_FRAME_TYPE_NAK: Indicates an error response for previously sent
  10657. + * frame. In general, this means that the frame and/or
  10658. + * payload is malformed, e.g. a CRC is wrong. For command-
  10659. + * type payloads, this can also mean that the command is
  10660. + * invalid.
  10661. + */
  10662. +enum ssh_frame_type {
  10663. + SSH_FRAME_TYPE_DATA_SEQ = 0x80,
  10664. + SSH_FRAME_TYPE_DATA_NSQ = 0x00,
  10665. + SSH_FRAME_TYPE_ACK = 0x40,
  10666. + SSH_FRAME_TYPE_NAK = 0x04,
  10667. +};
  10668. +
  10669. +/**
  10670. + * struct ssh_frame - SSH communication frame.
  10671. + * @type: The type of the frame. See &enum ssh_frame_type.
  10672. + * @len: The length of the frame payload directly following the CRC for this
  10673. + * frame. Does not include the final CRC for that payload.
  10674. + * @seq: The sequence number for this message/exchange.
  10675. + */
  10676. +struct ssh_frame {
  10677. + u8 type;
  10678. + __le16 len;
  10679. + u8 seq;
  10680. +} __packed;
  10681. +
  10682. +static_assert(sizeof(struct ssh_frame) == 4);
  10683. +
  10684. +/*
  10685. + * Maximum SSH frame payload length in bytes. This is the physical maximum
  10686. + * length of the protocol. Implementations may set a more constrained limit.
  10687. + */
  10688. +#define SSH_FRAME_MAX_PAYLOAD_SIZE U16_MAX
  10689. +
  10690. +/**
  10691. + * enum ssh_payload_type - Type indicator for the SSH payload.
  10692. + * @SSH_PLD_TYPE_CMD: The payload is a command structure with optional command
  10693. + * payload.
  10694. + */
  10695. +enum ssh_payload_type {
  10696. + SSH_PLD_TYPE_CMD = 0x80,
  10697. +};
  10698. +
  10699. +/**
  10700. + * struct ssh_command - Payload of a command-type frame.
  10701. + * @type: The type of the payload. See &enum ssh_payload_type. Should be
  10702. + * SSH_PLD_TYPE_CMD for this struct.
  10703. + * @tc: Command target category.
  10704. + * @chn_out: Output channel. Should be zero if this an incoming (EC to host)
  10705. + * message.
  10706. + * @chn_in: Input channel. Should be zero if this is an outgoing (hos to EC)
  10707. + * message.
  10708. + * @iid: Instance ID.
  10709. + * @rqid: Request ID. Used to match requests with responses and differentiate
  10710. + * between responses and events.
  10711. + * @cid: Command ID.
  10712. + */
  10713. +struct ssh_command {
  10714. + u8 type;
  10715. + u8 tc;
  10716. + u8 chn_out;
  10717. + u8 chn_in;
  10718. + u8 iid;
  10719. + __le16 rqid;
  10720. + u8 cid;
  10721. +} __packed;
  10722. +
  10723. +static_assert(sizeof(struct ssh_command) == 8);
  10724. +
  10725. +/*
  10726. + * Maximum SSH command payload length in bytes. This is the physical maximum
  10727. + * length of the protocol. Implementations may set a more constrained limit.
  10728. + */
  10729. +#define SSH_COMMAND_MAX_PAYLOAD_SIZE \
  10730. + (SSH_FRAME_MAX_PAYLOAD_SIZE - sizeof(struct ssh_command))
  10731. +
  10732. +/**
  10733. + * struct ssh_notification_params - Command payload to enable/disable SSH
  10734. + * notifications.
  10735. + * @target_category: The target category for which notifications should be
  10736. + * enabled/disabled.
  10737. + * @flags: Flags determining how notifications are being sent.
  10738. + * @request_id: The request ID that is used to send these notifications.
  10739. + * @instance_id: The specific instance in the given target category for
  10740. + * which notifications should be enabled.
  10741. + */
  10742. +struct ssh_notification_params {
  10743. + u8 target_category;
  10744. + u8 flags;
  10745. + __le16 request_id;
  10746. + u8 instance_id;
  10747. +} __packed;
  10748. +
  10749. +static_assert(sizeof(struct ssh_notification_params) == 5);
  10750. +
  10751. +/**
  10752. + * SSH message syncrhonization (SYN) bytes.
  10753. + */
  10754. +#define SSH_MSG_SYN ((u16)0x55aa)
  10755. +
  10756. +/**
  10757. + * Base-length of a SSH message. This is the minimum number of bytes required
  10758. + * to form a message. The actual message length is SSH_MSG_LEN_BASE plus the
  10759. + * length of the frame payload.
  10760. + */
  10761. +#define SSH_MSG_LEN_BASE (sizeof(struct ssh_frame) + 3ull * sizeof(u16))
  10762. +
  10763. +/**
  10764. + * Length of a SSH control message.
  10765. + */
  10766. +#define SSH_MSG_LEN_CTRL SSH_MSG_LEN_BASE
  10767. +
  10768. +/**
  10769. + * Length of a SSH message with payload of specified size.
  10770. + */
  10771. +#define SSH_MESSAGE_LENGTH(payload_size) (SSH_MSG_LEN_BASE + payload_size)
  10772. +
  10773. +/**
  10774. + * Length of a SSH command message with command payload of specified size.
  10775. + */
  10776. +#define SSH_COMMAND_MESSAGE_LENGTH(payload_size) \
  10777. + SSH_MESSAGE_LENGTH(sizeof(struct ssh_command) + payload_size)
  10778. +
  10779. +/**
  10780. + * Offset of the specified struct ssh_frame field in the raw SSH message data.
  10781. + */
  10782. +#define SSH_MSGOFFSET_FRAME(field) \
  10783. + (sizeof(u16) + offsetof(struct ssh_frame, field))
  10784. +
  10785. +/**
  10786. + * Offset of the specified struct ssh_command field in the raw SSH message data.
  10787. + */
  10788. +#define SSH_MSGOFFSET_COMMAND(field) \
  10789. + (2ull * sizeof(u16) + sizeof(struct ssh_frame) \
  10790. + + offsetof(struct ssh_command, field))
  10791. +
  10792. +struct sshp_span {
  10793. + u8 *ptr;
  10794. + size_t len;
  10795. +};
  10796. +
  10797. +
  10798. +/* -- Packet transport layer (ptl). ----------------------------------------- */
  10799. +
  10800. +enum ssh_packet_priority {
  10801. + SSH_PACKET_PRIORITY_FLUSH = 0,
  10802. + SSH_PACKET_PRIORITY_DATA = 0,
  10803. + SSH_PACKET_PRIORITY_NAK = 1 << 4,
  10804. + SSH_PACKET_PRIORITY_ACK = 2 << 4,
  10805. +};
  10806. +
  10807. +#define SSH_PACKET_PRIORITY(base, try) \
  10808. + ((SSH_PACKET_PRIORITY_##base) | ((try) & 0x0f))
  10809. +
  10810. +#define ssh_packet_priority_get_try(p) ((p) & 0x0f)
  10811. +
  10812. +
  10813. +enum ssh_packet_type_flags {
  10814. + SSH_PACKET_TY_FLUSH_BIT,
  10815. + SSH_PACKET_TY_SEQUENCED_BIT,
  10816. + SSH_PACKET_TY_BLOCKING_BIT,
  10817. +
  10818. + SSH_PACKET_TY_FLUSH = BIT(SSH_PACKET_TY_FLUSH_BIT),
  10819. + SSH_PACKET_TY_SEQUENCED = BIT(SSH_PACKET_TY_SEQUENCED_BIT),
  10820. + SSH_PACKET_TY_BLOCKING = BIT(SSH_PACKET_TY_BLOCKING_BIT),
  10821. +};
  10822. +
  10823. +enum ssh_packet_state_flags {
  10824. + SSH_PACKET_SF_LOCKED_BIT,
  10825. + SSH_PACKET_SF_QUEUED_BIT,
  10826. + SSH_PACKET_SF_PENDING_BIT,
  10827. + SSH_PACKET_SF_TRANSMITTING_BIT,
  10828. + SSH_PACKET_SF_TRANSMITTED_BIT,
  10829. + SSH_PACKET_SF_ACKED_BIT,
  10830. + SSH_PACKET_SF_CANCELED_BIT,
  10831. + SSH_PACKET_SF_COMPLETED_BIT,
  10832. +};
  10833. +
  10834. +
  10835. +struct ssh_ptl;
  10836. +struct ssh_packet;
  10837. +
  10838. +struct ssh_packet_ops {
  10839. + void (*release)(struct ssh_packet *packet);
  10840. + void (*complete)(struct ssh_packet *packet, int status);
  10841. +};
  10842. +
  10843. +struct ssh_packet {
  10844. + struct ssh_ptl *ptl;
  10845. + struct kref refcnt;
  10846. +
  10847. + u8 type;
  10848. + u8 priority;
  10849. + u16 data_length;
  10850. + u8 *data;
  10851. +
  10852. + unsigned long state;
  10853. + ktime_t timestamp;
  10854. +
  10855. + struct list_head queue_node;
  10856. + struct list_head pending_node;
  10857. +
  10858. + const struct ssh_packet_ops *ops;
  10859. +};
  10860. +
  10861. +
  10862. +/* -- Request transport layer (rtl). ---------------------------------------- */
  10863. +
  10864. +enum ssh_request_flags {
  10865. + SSH_REQUEST_SF_LOCKED_BIT,
  10866. + SSH_REQUEST_SF_QUEUED_BIT,
  10867. + SSH_REQUEST_SF_PENDING_BIT,
  10868. + SSH_REQUEST_SF_TRANSMITTING_BIT,
  10869. + SSH_REQUEST_SF_TRANSMITTED_BIT,
  10870. + SSH_REQUEST_SF_RSPRCVD_BIT,
  10871. + SSH_REQUEST_SF_CANCELED_BIT,
  10872. + SSH_REQUEST_SF_COMPLETED_BIT,
  10873. +
  10874. + SSH_REQUEST_TY_FLUSH_BIT,
  10875. + SSH_REQUEST_TY_HAS_RESPONSE_BIT,
  10876. +
  10877. + SSH_REQUEST_FLAGS_SF_MASK =
  10878. + BIT(SSH_REQUEST_SF_LOCKED_BIT)
  10879. + | BIT(SSH_REQUEST_SF_QUEUED_BIT)
  10880. + | BIT(SSH_REQUEST_SF_PENDING_BIT)
  10881. + | BIT(SSH_REQUEST_SF_TRANSMITTING_BIT)
  10882. + | BIT(SSH_REQUEST_SF_TRANSMITTED_BIT)
  10883. + | BIT(SSH_REQUEST_SF_RSPRCVD_BIT)
  10884. + | BIT(SSH_REQUEST_SF_CANCELED_BIT)
  10885. + | BIT(SSH_REQUEST_SF_COMPLETED_BIT),
  10886. +
  10887. + SSH_REQUEST_FLAGS_TY_MASK =
  10888. + BIT(SSH_REQUEST_TY_FLUSH_BIT)
  10889. + | BIT(SSH_REQUEST_TY_HAS_RESPONSE_BIT),
  10890. +};
  10891. +
  10892. +
  10893. +struct ssh_rtl;
  10894. +struct ssh_request;
  10895. +
  10896. +struct ssh_request_ops {
  10897. + void (*release)(struct ssh_request *rqst);
  10898. + void (*complete)(struct ssh_request *rqst,
  10899. + const struct ssh_command *cmd,
  10900. + const struct sshp_span *data, int status);
  10901. +};
  10902. +
  10903. +struct ssh_request {
  10904. + struct ssh_rtl *rtl;
  10905. + struct ssh_packet packet;
  10906. + struct list_head node;
  10907. +
  10908. + unsigned long state;
  10909. + ktime_t timestamp;
  10910. +
  10911. + const struct ssh_request_ops *ops;
  10912. +};
  10913. +
  10914. +
  10915. +/* -- Main data types and definitions --------------------------------------- */
  10916. +
  10917. +enum ssam_ssh_tc {
  10918. + SSAM_SSH_TC_SAM = 0x01, // generic system functionality, real-time clock
  10919. + SSAM_SSH_TC_BAT = 0x02, // battery/power subsystem
  10920. + SSAM_SSH_TC_TMP = 0x03, // thermal subsystem
  10921. + SSAM_SSH_TC_PMC = 0x04,
  10922. + SSAM_SSH_TC_FAN = 0x05,
  10923. + SSAM_SSH_TC_PoM = 0x06,
  10924. + SSAM_SSH_TC_DBG = 0x07,
  10925. + SSAM_SSH_TC_KBD = 0x08, // legacy keyboard (Laptop 1/2)
  10926. + SSAM_SSH_TC_FWU = 0x09,
  10927. + SSAM_SSH_TC_UNI = 0x0a,
  10928. + SSAM_SSH_TC_LPC = 0x0b,
  10929. + SSAM_SSH_TC_TCL = 0x0c,
  10930. + SSAM_SSH_TC_SFL = 0x0d,
  10931. + SSAM_SSH_TC_KIP = 0x0e,
  10932. + SSAM_SSH_TC_EXT = 0x0f,
  10933. + SSAM_SSH_TC_BLD = 0x10,
  10934. + SSAM_SSH_TC_BAS = 0x11, // detachment system (Surface Book 2/3)
  10935. + SSAM_SSH_TC_SEN = 0x12,
  10936. + SSAM_SSH_TC_SRQ = 0x13,
  10937. + SSAM_SSH_TC_MCU = 0x14,
  10938. + SSAM_SSH_TC_HID = 0x15, // generic HID input subsystem
  10939. + SSAM_SSH_TC_TCH = 0x16,
  10940. + SSAM_SSH_TC_BKL = 0x17,
  10941. + SSAM_SSH_TC_TAM = 0x18,
  10942. + SSAM_SSH_TC_ACC = 0x19,
  10943. + SSAM_SSH_TC_UFI = 0x1a,
  10944. + SSAM_SSH_TC_USC = 0x1b,
  10945. + SSAM_SSH_TC_PEN = 0x1c,
  10946. + SSAM_SSH_TC_VID = 0x1d,
  10947. + SSAM_SSH_TC_AUD = 0x1e,
  10948. + SSAM_SSH_TC_SMC = 0x1f,
  10949. + SSAM_SSH_TC_KPD = 0x20,
  10950. + SSAM_SSH_TC_REG = 0x21,
  10951. +};
  10952. +
  10953. +/**
  10954. + * struct ssam_event_flags - Flags for enabling/disabling SAM-over-SSH events
  10955. + * @SSAM_EVENT_SEQUENCED: The event will be sent via a sequenced data frame.
  10956. + */
  10957. +enum ssam_event_flags {
  10958. + SSAM_EVENT_SEQUENCED = BIT(0),
  10959. +};
  10960. +
  10961. +struct ssam_event {
  10962. + u8 target_category;
  10963. + u8 command_id;
  10964. + u8 instance_id;
  10965. + u8 channel;
  10966. + u16 length;
  10967. + u8 data[0];
  10968. +};
  10969. +
  10970. +
  10971. +/* -- Event notifier/callbacks. --------------------------------------------- */
  10972. +
  10973. +#define SSAM_NOTIF_STATE_SHIFT 2
  10974. +#define SSAM_NOTIF_STATE_MASK ((1 << SSAM_NOTIF_STATE_SHIFT) - 1)
  10975. +
  10976. +#define SSAM_NOTIF_HANDLED BIT(0)
  10977. +#define SSAM_NOTIF_STOP BIT(1)
  10978. +
  10979. +
  10980. +struct ssam_notifier_block;
  10981. +
  10982. +typedef u32 (*ssam_notifier_fn_t)(struct ssam_notifier_block *nb,
  10983. + const struct ssam_event *event);
  10984. +
  10985. +struct ssam_notifier_block {
  10986. + struct ssam_notifier_block __rcu *next;
  10987. + ssam_notifier_fn_t fn;
  10988. + int priority;
  10989. +};
  10990. +
  10991. +
  10992. +static inline u32 ssam_notifier_from_errno(int err)
  10993. +{
  10994. + WARN_ON(err > 0);
  10995. +
  10996. + if (err >= 0)
  10997. + return 0;
  10998. + else
  10999. + return ((-err) << SSAM_NOTIF_STATE_SHIFT) | SSAM_NOTIF_STOP;
  11000. +}
  11001. +
  11002. +static inline int ssam_notifier_to_errno(u32 ret)
  11003. +{
  11004. + return -(ret >> SSAM_NOTIF_STATE_SHIFT);
  11005. +}
  11006. +
  11007. +
  11008. +/* -- Event/notification registry. ------------------------------------------ */
  11009. +
  11010. +struct ssam_event_registry {
  11011. + u8 target_category;
  11012. + u8 channel;
  11013. + u8 cid_enable;
  11014. + u8 cid_disable;
  11015. +};
  11016. +
  11017. +struct ssam_event_id {
  11018. + u8 target_category;
  11019. + u8 instance;
  11020. +};
  11021. +
  11022. +
  11023. +#define SSAM_EVENT_REGISTRY(tc, chn, cid_en, cid_dis) \
  11024. + ((struct ssam_event_registry) { \
  11025. + .target_category = (tc), \
  11026. + .channel = (chn), \
  11027. + .cid_enable = (cid_en), \
  11028. + .cid_disable = (cid_dis), \
  11029. + })
  11030. +
  11031. +#define SSAM_EVENT_ID(tc, iid) \
  11032. + ((struct ssam_event_id) { \
  11033. + .target_category = tc, \
  11034. + .instance = iid, \
  11035. + })
  11036. +
  11037. +
  11038. +#define SSAM_EVENT_REGISTRY_SAM \
  11039. + SSAM_EVENT_REGISTRY(SSAM_SSH_TC_SAM, 0x01, 0x0b, 0x0c)
  11040. +
  11041. +#define SSAM_EVENT_REGISTRY_KIP \
  11042. + SSAM_EVENT_REGISTRY(SSAM_SSH_TC_KIP, 0x02, 0x27, 0x28)
  11043. +
  11044. +#define SSAM_EVENT_REGISTRY_REG \
  11045. + SSAM_EVENT_REGISTRY(SSAM_SSH_TC_REG, 0x02, 0x01, 0x02)
  11046. +
  11047. +
  11048. +struct ssam_event_notifier {
  11049. + struct ssam_notifier_block base;
  11050. +
  11051. + struct {
  11052. + struct ssam_event_registry reg;
  11053. + struct ssam_event_id id;
  11054. + u8 flags;
  11055. + } event;
  11056. +};
  11057. +
  11058. +
  11059. +/* -- TODO -------------------------------------------------------------------*/
  11060. +
  11061. +/*
  11062. + * Maximum response payload size in bytes.
  11063. + * Value based on ACPI (255 bytes minus header/status bytes).
  11064. + */
  11065. +#define SURFACE_SAM_SSH_MAX_RQST_RESPONSE (255 - 4)
  11066. +
  11067. +/*
  11068. + * The number of reserved event IDs, used for registering an SSH event
  11069. + * handler. Valid event IDs are numbers below or equal to this value, with
  11070. + * exception of zero, which is not an event ID. Thus, this is also the
  11071. + * absolute maximum number of event handlers that can be registered.
  11072. + */
  11073. +#define SURFACE_SAM_SSH_NUM_EVENTS 0x22
  11074. +
  11075. +/*
  11076. + * The number of communication channels used in the protocol.
  11077. + */
  11078. +#define SURFACE_SAM_SSH_NUM_CHANNELS 2
  11079. +
  11080. +
  11081. +struct surface_sam_ssh_buf {
  11082. + u8 cap;
  11083. + u8 len;
  11084. + u8 *data;
  11085. +};
  11086. +
  11087. +struct surface_sam_ssh_rqst {
  11088. + u8 tc; // target category
  11089. + u8 cid; // command ID
  11090. + u8 iid; // instance ID
  11091. + u8 chn; // channel
  11092. + u8 snc; // expect response flag (bool: 0/1)
  11093. + u16 cdl; // command data length (length of payload)
  11094. + u8 *pld; // pointer to payload of length cdl
  11095. +};
  11096. +
  11097. +// TODO: remove rqid on external api
  11098. +struct surface_sam_ssh_event {
  11099. + u16 rqid; // event type/source ID
  11100. + u8 tc; // target category
  11101. + u8 cid; // command ID
  11102. + u8 iid; // instance ID
  11103. + u8 chn; // channel
  11104. + u8 len; // length of payload
  11105. + u8 *pld; // payload of length len
  11106. +};
  11107. +
  11108. +
  11109. +int surface_sam_ssh_consumer_register(struct device *consumer);
  11110. +
  11111. +int surface_sam_ssh_notifier_register(struct ssam_event_notifier *n);
  11112. +int surface_sam_ssh_notifier_unregister(struct ssam_event_notifier *n);
  11113. +
  11114. +int surface_sam_ssh_rqst(const struct surface_sam_ssh_rqst *rqst, struct surface_sam_ssh_buf *result);
  11115. +
  11116. +#endif /* _SURFACE_SAM_SSH_H */
  11117. diff --git a/drivers/platform/x86/surface_sam/surface_sam_ssh_trace.h b/drivers/platform/x86/surface_sam/surface_sam_ssh_trace.h
  11118. new file mode 100644
  11119. index 000000000000..801c60205128
  11120. --- /dev/null
  11121. +++ b/drivers/platform/x86/surface_sam/surface_sam_ssh_trace.h
  11122. @@ -0,0 +1,536 @@
  11123. +#undef TRACE_SYSTEM
  11124. +#define TRACE_SYSTEM surface_sam_ssh
  11125. +
  11126. +#if !defined(_SURFACE_SAM_SSH_TRACE_H) || defined(TRACE_HEADER_MULTI_READ)
  11127. +#define _SURFACE_SAM_SSH_TRACE_H
  11128. +
  11129. +#include <linux/tracepoint.h>
  11130. +
  11131. +#include "surface_sam_ssh.h"
  11132. +
  11133. +
  11134. +TRACE_DEFINE_ENUM(SSH_FRAME_TYPE_DATA_SEQ);
  11135. +TRACE_DEFINE_ENUM(SSH_FRAME_TYPE_DATA_NSQ);
  11136. +TRACE_DEFINE_ENUM(SSH_FRAME_TYPE_ACK);
  11137. +TRACE_DEFINE_ENUM(SSH_FRAME_TYPE_NAK);
  11138. +
  11139. +TRACE_DEFINE_ENUM(SSH_PACKET_TY_FLUSH_BIT);
  11140. +TRACE_DEFINE_ENUM(SSH_PACKET_TY_SEQUENCED_BIT);
  11141. +TRACE_DEFINE_ENUM(SSH_PACKET_TY_BLOCKING_BIT);
  11142. +
  11143. +TRACE_DEFINE_ENUM(SSH_PACKET_TY_FLUSH);
  11144. +TRACE_DEFINE_ENUM(SSH_PACKET_TY_SEQUENCED);
  11145. +TRACE_DEFINE_ENUM(SSH_PACKET_TY_BLOCKING);
  11146. +
  11147. +TRACE_DEFINE_ENUM(SSH_PACKET_SF_LOCKED_BIT);
  11148. +TRACE_DEFINE_ENUM(SSH_PACKET_SF_QUEUED_BIT);
  11149. +TRACE_DEFINE_ENUM(SSH_PACKET_SF_PENDING_BIT);
  11150. +TRACE_DEFINE_ENUM(SSH_PACKET_SF_TRANSMITTING_BIT);
  11151. +TRACE_DEFINE_ENUM(SSH_PACKET_SF_TRANSMITTED_BIT);
  11152. +TRACE_DEFINE_ENUM(SSH_PACKET_SF_ACKED_BIT);
  11153. +TRACE_DEFINE_ENUM(SSH_PACKET_SF_CANCELED_BIT);
  11154. +TRACE_DEFINE_ENUM(SSH_PACKET_SF_COMPLETED_BIT);
  11155. +
  11156. +TRACE_DEFINE_ENUM(SSH_REQUEST_SF_LOCKED_BIT);
  11157. +TRACE_DEFINE_ENUM(SSH_REQUEST_SF_QUEUED_BIT);
  11158. +TRACE_DEFINE_ENUM(SSH_REQUEST_SF_PENDING_BIT);
  11159. +TRACE_DEFINE_ENUM(SSH_REQUEST_SF_TRANSMITTING_BIT);
  11160. +TRACE_DEFINE_ENUM(SSH_REQUEST_SF_TRANSMITTED_BIT);
  11161. +TRACE_DEFINE_ENUM(SSH_REQUEST_SF_RSPRCVD_BIT);
  11162. +TRACE_DEFINE_ENUM(SSH_REQUEST_SF_CANCELED_BIT);
  11163. +TRACE_DEFINE_ENUM(SSH_REQUEST_SF_COMPLETED_BIT);
  11164. +TRACE_DEFINE_ENUM(SSH_REQUEST_TY_FLUSH_BIT);
  11165. +TRACE_DEFINE_ENUM(SSH_REQUEST_TY_HAS_RESPONSE_BIT);
  11166. +
  11167. +TRACE_DEFINE_ENUM(SSH_REQUEST_FLAGS_SF_MASK);
  11168. +TRACE_DEFINE_ENUM(SSH_REQUEST_FLAGS_TY_MASK);
  11169. +
  11170. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_SAM);
  11171. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_BAT);
  11172. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_TMP);
  11173. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_PMC);
  11174. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_FAN);
  11175. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_PoM);
  11176. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_DBG);
  11177. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_KBD);
  11178. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_FWU);
  11179. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_UNI);
  11180. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_LPC);
  11181. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_TCL);
  11182. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_SFL);
  11183. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_KIP);
  11184. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_EXT);
  11185. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_BLD);
  11186. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_BAS);
  11187. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_SEN);
  11188. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_SRQ);
  11189. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_MCU);
  11190. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_HID);
  11191. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_TCH);
  11192. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_BKL);
  11193. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_TAM);
  11194. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_ACC);
  11195. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_UFI);
  11196. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_USC);
  11197. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_PEN);
  11198. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_VID);
  11199. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_AUD);
  11200. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_SMC);
  11201. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_KPD);
  11202. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_REG);
  11203. +
  11204. +
  11205. +#define SSAM_PTR_UID_LEN 9
  11206. +#define SSAM_U8_FIELD_NOT_APPLICABLE ((u16)-1)
  11207. +#define SSAM_SEQ_NOT_APPLICABLE ((u16)-1)
  11208. +#define SSAM_RQID_NOT_APPLICABLE ((u32)-1)
  11209. +#define SSAM_SSH_TC_NOT_APPLICABLE 0
  11210. +
  11211. +
  11212. +#ifndef _SURFACE_SAM_SSH_TRACE_HELPERS
  11213. +#define _SURFACE_SAM_SSH_TRACE_HELPERS
  11214. +
  11215. +static inline void ssam_trace_ptr_uid(const void *ptr, char* uid_str)
  11216. +{
  11217. + char buf[2 * sizeof(void*) + 1];
  11218. +
  11219. + snprintf(buf, ARRAY_SIZE(buf), "%p", ptr);
  11220. + memcpy(uid_str, &buf[ARRAY_SIZE(buf) - SSAM_PTR_UID_LEN],
  11221. + SSAM_PTR_UID_LEN);
  11222. +}
  11223. +
  11224. +static inline u16 ssam_trace_get_packet_seq(const struct ssh_packet *p)
  11225. +{
  11226. + if (!p->data || p->data_length < SSH_MESSAGE_LENGTH(0))
  11227. + return SSAM_SEQ_NOT_APPLICABLE;
  11228. +
  11229. + return p->data[SSH_MSGOFFSET_FRAME(seq)];
  11230. +}
  11231. +
  11232. +static inline u32 ssam_trace_get_request_id(const struct ssh_packet *p)
  11233. +{
  11234. + if (!p->data || p->data_length < SSH_COMMAND_MESSAGE_LENGTH(0))
  11235. + return SSAM_RQID_NOT_APPLICABLE;
  11236. +
  11237. + return get_unaligned_le16(&p->data[SSH_MSGOFFSET_COMMAND(rqid)]);
  11238. +}
  11239. +
  11240. +static inline u32 ssam_trace_get_request_tc(const struct ssh_packet *p)
  11241. +{
  11242. + if (!p->data || p->data_length < SSH_COMMAND_MESSAGE_LENGTH(0))
  11243. + return SSAM_SSH_TC_NOT_APPLICABLE;
  11244. +
  11245. + return get_unaligned_le16(&p->data[SSH_MSGOFFSET_COMMAND(tc)]);
  11246. +}
  11247. +
  11248. +#endif /* _SURFACE_SAM_SSH_TRACE_HELPERS */
  11249. +
  11250. +#define ssam_trace_get_command_field_u8(packet, field) \
  11251. + ((!packet || packet->data_length < SSH_COMMAND_MESSAGE_LENGTH(0)) \
  11252. + ? 0 : p->data[SSH_MSGOFFSET_COMMAND(field)])
  11253. +
  11254. +#define ssam_show_generic_u8_field(value) \
  11255. + __print_symbolic(value, \
  11256. + { SSAM_U8_FIELD_NOT_APPLICABLE, "N/A" } \
  11257. + )
  11258. +
  11259. +
  11260. +#define ssam_show_frame_type(ty) \
  11261. + __print_symbolic(ty, \
  11262. + { SSH_FRAME_TYPE_DATA_SEQ, "DSEQ" }, \
  11263. + { SSH_FRAME_TYPE_DATA_NSQ, "DNSQ" }, \
  11264. + { SSH_FRAME_TYPE_ACK, "ACK" }, \
  11265. + { SSH_FRAME_TYPE_NAK, "NAK" } \
  11266. + )
  11267. +
  11268. +#define ssam_show_packet_type(type) \
  11269. + __print_flags(type, "", \
  11270. + { SSH_PACKET_TY_FLUSH, "F" }, \
  11271. + { SSH_PACKET_TY_SEQUENCED, "S" }, \
  11272. + { SSH_PACKET_TY_BLOCKING, "B" } \
  11273. + )
  11274. +
  11275. +#define ssam_show_packet_state(state) \
  11276. + __print_flags(state, "", \
  11277. + { BIT(SSH_PACKET_SF_LOCKED_BIT), "L" }, \
  11278. + { BIT(SSH_PACKET_SF_QUEUED_BIT), "Q" }, \
  11279. + { BIT(SSH_PACKET_SF_PENDING_BIT), "P" }, \
  11280. + { BIT(SSH_PACKET_SF_TRANSMITTING_BIT), "S" }, \
  11281. + { BIT(SSH_PACKET_SF_TRANSMITTED_BIT), "T" }, \
  11282. + { BIT(SSH_PACKET_SF_ACKED_BIT), "A" }, \
  11283. + { BIT(SSH_PACKET_SF_CANCELED_BIT), "C" }, \
  11284. + { BIT(SSH_PACKET_SF_COMPLETED_BIT), "F" } \
  11285. + )
  11286. +
  11287. +#define ssam_show_packet_seq(seq) \
  11288. + __print_symbolic(seq, \
  11289. + { SSAM_SEQ_NOT_APPLICABLE, "N/A" } \
  11290. + )
  11291. +
  11292. +
  11293. +#define ssam_show_request_type(flags) \
  11294. + __print_flags(flags & SSH_REQUEST_FLAGS_TY_MASK, "", \
  11295. + { BIT(SSH_REQUEST_TY_FLUSH_BIT), "F" }, \
  11296. + { BIT(SSH_REQUEST_TY_HAS_RESPONSE_BIT), "R" } \
  11297. + )
  11298. +
  11299. +#define ssam_show_request_state(flags) \
  11300. + __print_flags(flags & SSH_REQUEST_FLAGS_SF_MASK, "", \
  11301. + { BIT(SSH_REQUEST_SF_LOCKED_BIT), "L" }, \
  11302. + { BIT(SSH_REQUEST_SF_QUEUED_BIT), "Q" }, \
  11303. + { BIT(SSH_REQUEST_SF_PENDING_BIT), "P" }, \
  11304. + { BIT(SSH_REQUEST_SF_TRANSMITTING_BIT), "S" }, \
  11305. + { BIT(SSH_REQUEST_SF_TRANSMITTED_BIT), "T" }, \
  11306. + { BIT(SSH_REQUEST_SF_RSPRCVD_BIT), "A" }, \
  11307. + { BIT(SSH_REQUEST_SF_CANCELED_BIT), "C" }, \
  11308. + { BIT(SSH_REQUEST_SF_COMPLETED_BIT), "F" } \
  11309. + )
  11310. +
  11311. +#define ssam_show_request_id(rqid) \
  11312. + __print_symbolic(rqid, \
  11313. + { SSAM_RQID_NOT_APPLICABLE, "N/A" } \
  11314. + )
  11315. +
  11316. +#define ssam_show_ssh_tc(rqid) \
  11317. + __print_symbolic(rqid, \
  11318. + { SSAM_SSH_TC_NOT_APPLICABLE, "N/A" }, \
  11319. + { SSAM_SSH_TC_SAM, "SAM" }, \
  11320. + { SSAM_SSH_TC_BAT, "BAT" }, \
  11321. + { SSAM_SSH_TC_TMP, "TMP" }, \
  11322. + { SSAM_SSH_TC_PMC, "PMC" }, \
  11323. + { SSAM_SSH_TC_FAN, "FAN" }, \
  11324. + { SSAM_SSH_TC_PoM, "PoM" }, \
  11325. + { SSAM_SSH_TC_DBG, "DBG" }, \
  11326. + { SSAM_SSH_TC_KBD, "KBD" }, \
  11327. + { SSAM_SSH_TC_FWU, "FWU" }, \
  11328. + { SSAM_SSH_TC_UNI, "UNI" }, \
  11329. + { SSAM_SSH_TC_LPC, "LPC" }, \
  11330. + { SSAM_SSH_TC_TCL, "TCL" }, \
  11331. + { SSAM_SSH_TC_SFL, "SFL" }, \
  11332. + { SSAM_SSH_TC_KIP, "KIP" }, \
  11333. + { SSAM_SSH_TC_EXT, "EXT" }, \
  11334. + { SSAM_SSH_TC_BLD, "BLD" }, \
  11335. + { SSAM_SSH_TC_BAS, "BAS" }, \
  11336. + { SSAM_SSH_TC_SEN, "SEN" }, \
  11337. + { SSAM_SSH_TC_SRQ, "SRQ" }, \
  11338. + { SSAM_SSH_TC_MCU, "MCU" }, \
  11339. + { SSAM_SSH_TC_HID, "HID" }, \
  11340. + { SSAM_SSH_TC_TCH, "TCH" }, \
  11341. + { SSAM_SSH_TC_BKL, "BKL" }, \
  11342. + { SSAM_SSH_TC_TAM, "TAM" }, \
  11343. + { SSAM_SSH_TC_ACC, "ACC" }, \
  11344. + { SSAM_SSH_TC_UFI, "UFI" }, \
  11345. + { SSAM_SSH_TC_USC, "USC" }, \
  11346. + { SSAM_SSH_TC_PEN, "PEN" }, \
  11347. + { SSAM_SSH_TC_VID, "VID" }, \
  11348. + { SSAM_SSH_TC_AUD, "AUD" }, \
  11349. + { SSAM_SSH_TC_SMC, "SMC" }, \
  11350. + { SSAM_SSH_TC_KPD, "KPD" }, \
  11351. + { SSAM_SSH_TC_REG, "REG" } \
  11352. + )
  11353. +
  11354. +
  11355. +DECLARE_EVENT_CLASS(ssam_frame_class,
  11356. + TP_PROTO(const struct ssh_frame *frame),
  11357. +
  11358. + TP_ARGS(frame),
  11359. +
  11360. + TP_STRUCT__entry(
  11361. + __field(u8, type)
  11362. + __field(u8, seq)
  11363. + __field(u16, len)
  11364. + ),
  11365. +
  11366. + TP_fast_assign(
  11367. + __entry->type = frame->type;
  11368. + __entry->seq = frame->seq;
  11369. + __entry->len = get_unaligned_le16(&frame->len);
  11370. + ),
  11371. +
  11372. + TP_printk("ty=%s, seq=0x%02x, len=%u",
  11373. + ssam_show_frame_type(__entry->type),
  11374. + __entry->seq,
  11375. + __entry->len
  11376. + )
  11377. +);
  11378. +
  11379. +#define DEFINE_SSAM_FRAME_EVENT(name) \
  11380. + DEFINE_EVENT(ssam_frame_class, ssam_##name, \
  11381. + TP_PROTO(const struct ssh_frame *frame), \
  11382. + TP_ARGS(frame) \
  11383. + )
  11384. +
  11385. +
  11386. +DECLARE_EVENT_CLASS(ssam_command_class,
  11387. + TP_PROTO(const struct ssh_command *cmd, u16 len),
  11388. +
  11389. + TP_ARGS(cmd, len),
  11390. +
  11391. + TP_STRUCT__entry(
  11392. + __field(u16, rqid)
  11393. + __field(u16, len)
  11394. + __field(u8, tc)
  11395. + __field(u8, cid)
  11396. + __field(u8, iid)
  11397. + ),
  11398. +
  11399. + TP_fast_assign(
  11400. + __entry->rqid = get_unaligned_le16(&cmd->rqid);
  11401. + __entry->tc = cmd->tc;
  11402. + __entry->cid = cmd->cid;
  11403. + __entry->iid = cmd->iid;
  11404. + __entry->len = len;
  11405. + ),
  11406. +
  11407. + TP_printk("rqid=0x%04x, tc=%s, cid=0x%02x, iid=0x%02x, len=%u",
  11408. + __entry->rqid,
  11409. + ssam_show_ssh_tc(__entry->tc),
  11410. + __entry->cid,
  11411. + __entry->iid,
  11412. + __entry->len
  11413. + )
  11414. +);
  11415. +
  11416. +#define DEFINE_SSAM_COMMAND_EVENT(name) \
  11417. + DEFINE_EVENT(ssam_command_class, ssam_##name, \
  11418. + TP_PROTO(const struct ssh_command *cmd, u16 len), \
  11419. + TP_ARGS(cmd, len) \
  11420. + )
  11421. +
  11422. +
  11423. +DECLARE_EVENT_CLASS(ssam_packet_class,
  11424. + TP_PROTO(const struct ssh_packet *packet),
  11425. +
  11426. + TP_ARGS(packet),
  11427. +
  11428. + TP_STRUCT__entry(
  11429. + __array(char, uid, SSAM_PTR_UID_LEN)
  11430. + __field(u8, type)
  11431. + __field(u8, priority)
  11432. + __field(u16, length)
  11433. + __field(unsigned long, state)
  11434. + __field(u16, seq)
  11435. + ),
  11436. +
  11437. + TP_fast_assign(
  11438. + ssam_trace_ptr_uid(packet, __entry->uid);
  11439. + __entry->type = packet->type;
  11440. + __entry->priority = READ_ONCE(packet->priority);
  11441. + __entry->length = packet->data_length;
  11442. + __entry->state = READ_ONCE(packet->state);
  11443. + __entry->seq = ssam_trace_get_packet_seq(packet);
  11444. + ),
  11445. +
  11446. + TP_printk("uid=%s, seq=%s, ty=%s, pri=0x%02x, len=%u, sta=%s",
  11447. + __entry->uid,
  11448. + ssam_show_packet_seq(__entry->seq),
  11449. + ssam_show_packet_type(__entry->type),
  11450. + __entry->priority,
  11451. + __entry->length,
  11452. + ssam_show_packet_state(__entry->state)
  11453. + )
  11454. +);
  11455. +
  11456. +#define DEFINE_SSAM_PACKET_EVENT(name) \
  11457. + DEFINE_EVENT(ssam_packet_class, ssam_##name, \
  11458. + TP_PROTO(const struct ssh_packet *packet), \
  11459. + TP_ARGS(packet) \
  11460. + )
  11461. +
  11462. +
  11463. +DECLARE_EVENT_CLASS(ssam_packet_status_class,
  11464. + TP_PROTO(const struct ssh_packet *packet, int status),
  11465. +
  11466. + TP_ARGS(packet, status),
  11467. +
  11468. + TP_STRUCT__entry(
  11469. + __array(char, uid, SSAM_PTR_UID_LEN)
  11470. + __field(u8, type)
  11471. + __field(u8, priority)
  11472. + __field(u16, length)
  11473. + __field(unsigned long, state)
  11474. + __field(u16, seq)
  11475. + __field(int, status)
  11476. + ),
  11477. +
  11478. + TP_fast_assign(
  11479. + ssam_trace_ptr_uid(packet, __entry->uid);
  11480. + __entry->type = packet->type;
  11481. + __entry->priority = READ_ONCE(packet->priority);
  11482. + __entry->length = packet->data_length;
  11483. + __entry->state = READ_ONCE(packet->state);
  11484. + __entry->seq = ssam_trace_get_packet_seq(packet);
  11485. + __entry->status = status;
  11486. + ),
  11487. +
  11488. + TP_printk("uid=%s, seq=%s, ty=%s, pri=0x%02x, len=%u, sta=%s, status=%d",
  11489. + __entry->uid,
  11490. + ssam_show_packet_seq(__entry->seq),
  11491. + ssam_show_packet_type(__entry->type),
  11492. + __entry->priority,
  11493. + __entry->length,
  11494. + ssam_show_packet_state(__entry->state),
  11495. + __entry->status
  11496. + )
  11497. +);
  11498. +
  11499. +#define DEFINE_SSAM_PACKET_STATUS_EVENT(name) \
  11500. + DEFINE_EVENT(ssam_packet_status_class, ssam_##name, \
  11501. + TP_PROTO(const struct ssh_packet *packet, int status), \
  11502. + TP_ARGS(packet, status) \
  11503. + )
  11504. +
  11505. +
  11506. +DECLARE_EVENT_CLASS(ssam_request_class,
  11507. + TP_PROTO(const struct ssh_request *request),
  11508. +
  11509. + TP_ARGS(request),
  11510. +
  11511. + TP_STRUCT__entry(
  11512. + __array(char, uid, SSAM_PTR_UID_LEN)
  11513. + __field(unsigned long, state)
  11514. + __field(u32, rqid)
  11515. + __field(u8, tc)
  11516. + __field(u16, cid)
  11517. + __field(u16, iid)
  11518. + ),
  11519. +
  11520. + TP_fast_assign(
  11521. + const struct ssh_packet *p = &request->packet;
  11522. +
  11523. + // use packet for UID so we can match requests to packets
  11524. + ssam_trace_ptr_uid(p, __entry->uid);
  11525. + __entry->state = READ_ONCE(request->state);
  11526. + __entry->rqid = ssam_trace_get_request_id(p);
  11527. + __entry->tc = ssam_trace_get_request_tc(p);
  11528. + __entry->cid = ssam_trace_get_command_field_u8(p, cid);
  11529. + __entry->iid = ssam_trace_get_command_field_u8(p, iid);
  11530. + ),
  11531. +
  11532. + TP_printk("uid=%s, rqid=%s, ty=%s, sta=%s, tc=%s, cid=%s, iid=%s",
  11533. + __entry->uid,
  11534. + ssam_show_request_id(__entry->rqid),
  11535. + ssam_show_request_type(__entry->state),
  11536. + ssam_show_request_state(__entry->state),
  11537. + ssam_show_ssh_tc(__entry->tc),
  11538. + ssam_show_generic_u8_field(__entry->cid),
  11539. + ssam_show_generic_u8_field(__entry->iid)
  11540. + )
  11541. +);
  11542. +
  11543. +#define DEFINE_SSAM_REQUEST_EVENT(name) \
  11544. + DEFINE_EVENT(ssam_request_class, ssam_##name, \
  11545. + TP_PROTO(const struct ssh_request *request), \
  11546. + TP_ARGS(request) \
  11547. + )
  11548. +
  11549. +
  11550. +DECLARE_EVENT_CLASS(ssam_request_status_class,
  11551. + TP_PROTO(const struct ssh_request *request, int status),
  11552. +
  11553. + TP_ARGS(request, status),
  11554. +
  11555. + TP_STRUCT__entry(
  11556. + __array(char, uid, SSAM_PTR_UID_LEN)
  11557. + __field(unsigned long, state)
  11558. + __field(u32, rqid)
  11559. + __field(u8, tc)
  11560. + __field(u16, cid)
  11561. + __field(u16, iid)
  11562. + __field(int, status)
  11563. + ),
  11564. +
  11565. + TP_fast_assign(
  11566. + const struct ssh_packet *p = &request->packet;
  11567. +
  11568. + // use packet for UID so we can match requests to packets
  11569. + ssam_trace_ptr_uid(p, __entry->uid);
  11570. + __entry->state = READ_ONCE(request->state);
  11571. + __entry->rqid = ssam_trace_get_request_id(p);
  11572. + __entry->tc = ssam_trace_get_request_tc(p);
  11573. + __entry->cid = ssam_trace_get_command_field_u8(p, cid);
  11574. + __entry->iid = ssam_trace_get_command_field_u8(p, iid);
  11575. + __entry->status = status;
  11576. + ),
  11577. +
  11578. + TP_printk("uid=%s, rqid=%s, ty=%s, sta=%s, tc=%s, cid=%s, iid=%s, status=%d",
  11579. + __entry->uid,
  11580. + ssam_show_request_id(__entry->rqid),
  11581. + ssam_show_request_type(__entry->state),
  11582. + ssam_show_request_state(__entry->state),
  11583. + ssam_show_ssh_tc(__entry->tc),
  11584. + ssam_show_generic_u8_field(__entry->cid),
  11585. + ssam_show_generic_u8_field(__entry->iid),
  11586. + __entry->status
  11587. + )
  11588. +);
  11589. +
  11590. +#define DEFINE_SSAM_REQUEST_STATUS_EVENT(name) \
  11591. + DEFINE_EVENT(ssam_request_status_class, ssam_##name, \
  11592. + TP_PROTO(const struct ssh_request *request, int status),\
  11593. + TP_ARGS(request, status) \
  11594. + )
  11595. +
  11596. +
  11597. +DECLARE_EVENT_CLASS(ssam_generic_uint_class,
  11598. + TP_PROTO(const char* property, unsigned int value),
  11599. +
  11600. + TP_ARGS(property, value),
  11601. +
  11602. + TP_STRUCT__entry(
  11603. + __string(property, property)
  11604. + __field(unsigned int, value)
  11605. + ),
  11606. +
  11607. + TP_fast_assign(
  11608. + __assign_str(property, property);
  11609. + __entry->value = value;
  11610. + ),
  11611. +
  11612. + TP_printk("%s=%u", __get_str(property), __entry->value)
  11613. +);
  11614. +
  11615. +#define DEFINE_SSAM_GENERIC_UINT_EVENT(name) \
  11616. + DEFINE_EVENT(ssam_generic_uint_class, ssam_##name, \
  11617. + TP_PROTO(const char* property, unsigned int value), \
  11618. + TP_ARGS(property, value) \
  11619. + )
  11620. +
  11621. +
  11622. +DEFINE_SSAM_FRAME_EVENT(rx_frame_received);
  11623. +DEFINE_SSAM_COMMAND_EVENT(rx_response_received);
  11624. +DEFINE_SSAM_COMMAND_EVENT(rx_event_received);
  11625. +
  11626. +DEFINE_SSAM_PACKET_EVENT(packet_release);
  11627. +DEFINE_SSAM_PACKET_EVENT(packet_submit);
  11628. +DEFINE_SSAM_PACKET_EVENT(packet_resubmit);
  11629. +DEFINE_SSAM_PACKET_EVENT(packet_timeout);
  11630. +DEFINE_SSAM_PACKET_EVENT(packet_cancel);
  11631. +DEFINE_SSAM_PACKET_STATUS_EVENT(packet_complete);
  11632. +DEFINE_SSAM_GENERIC_UINT_EVENT(ptl_timeout_reap);
  11633. +
  11634. +DEFINE_SSAM_REQUEST_EVENT(request_submit);
  11635. +DEFINE_SSAM_REQUEST_EVENT(request_timeout);
  11636. +DEFINE_SSAM_REQUEST_EVENT(request_cancel);
  11637. +DEFINE_SSAM_REQUEST_STATUS_EVENT(request_complete);
  11638. +DEFINE_SSAM_GENERIC_UINT_EVENT(rtl_timeout_reap);
  11639. +
  11640. +DEFINE_SSAM_PACKET_EVENT(ei_tx_drop_ack_packet);
  11641. +DEFINE_SSAM_PACKET_EVENT(ei_tx_drop_nak_packet);
  11642. +DEFINE_SSAM_PACKET_EVENT(ei_tx_drop_dsq_packet);
  11643. +DEFINE_SSAM_PACKET_STATUS_EVENT(ei_tx_fail_write);
  11644. +DEFINE_SSAM_PACKET_EVENT(ei_tx_corrupt_data);
  11645. +DEFINE_SSAM_GENERIC_UINT_EVENT(ei_rx_corrupt_syn);
  11646. +DEFINE_SSAM_FRAME_EVENT(ei_rx_corrupt_data);
  11647. +DEFINE_SSAM_REQUEST_EVENT(ei_rx_drop_response);
  11648. +
  11649. +#endif /* _SURFACE_SAM_SSH_TRACE_H */
  11650. +
  11651. +/* This part must be outside protection */
  11652. +#undef TRACE_INCLUDE_PATH
  11653. +#undef TRACE_INCLUDE_FILE
  11654. +
  11655. +#define TRACE_INCLUDE_PATH .
  11656. +#define TRACE_INCLUDE_FILE surface_sam_ssh_trace
  11657. +
  11658. +#include <trace/define_trace.h>
  11659. diff --git a/drivers/platform/x86/surface_sam/surface_sam_vhf.c b/drivers/platform/x86/surface_sam/surface_sam_vhf.c
  11660. new file mode 100644
  11661. index 000000000000..984035c55d63
  11662. --- /dev/null
  11663. +++ b/drivers/platform/x86/surface_sam/surface_sam_vhf.c
  11664. @@ -0,0 +1,261 @@
  11665. +// SPDX-License-Identifier: GPL-2.0-or-later
  11666. +/*
  11667. + * Virtual HID Framework (VHF) driver for input events via SAM.
  11668. + * Used for keyboard input events on the Surface Laptops.
  11669. + */
  11670. +
  11671. +#include <linux/acpi.h>
  11672. +#include <linux/hid.h>
  11673. +#include <linux/input.h>
  11674. +#include <linux/platform_device.h>
  11675. +#include <linux/types.h>
  11676. +
  11677. +#include "surface_sam_ssh.h"
  11678. +
  11679. +
  11680. +#define USB_VENDOR_ID_MICROSOFT 0x045e
  11681. +#define USB_DEVICE_ID_MS_VHF 0xf001
  11682. +
  11683. +#define VHF_INPUT_NAME "Microsoft Virtual HID Framework Device"
  11684. +
  11685. +
  11686. +struct vhf_drvdata {
  11687. + struct platform_device *dev;
  11688. + struct hid_device *hid;
  11689. + struct ssam_event_notifier notif;
  11690. +};
  11691. +
  11692. +
  11693. +/*
  11694. + * These report descriptors have been extracted from a Surface Book 2.
  11695. + * They seems to be similar enough to be usable on the Surface Laptop.
  11696. + */
  11697. +static const u8 vhf_hid_desc[] = {
  11698. + // keyboard descriptor (event command ID 0x03)
  11699. + 0x05, 0x01, /* Usage Page (Desktop), */
  11700. + 0x09, 0x06, /* Usage (Keyboard), */
  11701. + 0xA1, 0x01, /* Collection (Application), */
  11702. + 0x85, 0x01, /* Report ID (1), */
  11703. + 0x15, 0x00, /* Logical Minimum (0), */
  11704. + 0x25, 0x01, /* Logical Maximum (1), */
  11705. + 0x75, 0x01, /* Report Size (1), */
  11706. + 0x95, 0x08, /* Report Count (8), */
  11707. + 0x05, 0x07, /* Usage Page (Keyboard), */
  11708. + 0x19, 0xE0, /* Usage Minimum (KB Leftcontrol), */
  11709. + 0x29, 0xE7, /* Usage Maximum (KB Right GUI), */
  11710. + 0x81, 0x02, /* Input (Variable), */
  11711. + 0x75, 0x08, /* Report Size (8), */
  11712. + 0x95, 0x0A, /* Report Count (10), */
  11713. + 0x19, 0x00, /* Usage Minimum (None), */
  11714. + 0x29, 0x91, /* Usage Maximum (KB LANG2), */
  11715. + 0x26, 0xFF, 0x00, /* Logical Maximum (255), */
  11716. + 0x81, 0x00, /* Input, */
  11717. + 0x05, 0x0C, /* Usage Page (Consumer), */
  11718. + 0x0A, 0xC0, 0x02, /* Usage (02C0h), */
  11719. + 0xA1, 0x02, /* Collection (Logical), */
  11720. + 0x1A, 0xC1, 0x02, /* Usage Minimum (02C1h), */
  11721. + 0x2A, 0xC6, 0x02, /* Usage Maximum (02C6h), */
  11722. + 0x95, 0x06, /* Report Count (6), */
  11723. + 0xB1, 0x03, /* Feature (Constant, Variable), */
  11724. + 0xC0, /* End Collection, */
  11725. + 0x05, 0x08, /* Usage Page (LED), */
  11726. + 0x19, 0x01, /* Usage Minimum (01h), */
  11727. + 0x29, 0x03, /* Usage Maximum (03h), */
  11728. + 0x75, 0x01, /* Report Size (1), */
  11729. + 0x95, 0x03, /* Report Count (3), */
  11730. + 0x25, 0x01, /* Logical Maximum (1), */
  11731. + 0x91, 0x02, /* Output (Variable), */
  11732. + 0x95, 0x05, /* Report Count (5), */
  11733. + 0x91, 0x01, /* Output (Constant), */
  11734. + 0xC0, /* End Collection, */
  11735. +
  11736. + // media key descriptor (event command ID 0x04)
  11737. + 0x05, 0x0C, /* Usage Page (Consumer), */
  11738. + 0x09, 0x01, /* Usage (Consumer Control), */
  11739. + 0xA1, 0x01, /* Collection (Application), */
  11740. + 0x85, 0x03, /* Report ID (3), */
  11741. + 0x75, 0x10, /* Report Size (16), */
  11742. + 0x15, 0x00, /* Logical Minimum (0), */
  11743. + 0x26, 0xFF, 0x03, /* Logical Maximum (1023), */
  11744. + 0x19, 0x00, /* Usage Minimum (00h), */
  11745. + 0x2A, 0xFF, 0x03, /* Usage Maximum (03FFh), */
  11746. + 0x81, 0x00, /* Input, */
  11747. + 0xC0, /* End Collection, */
  11748. +};
  11749. +
  11750. +
  11751. +static int vhf_hid_start(struct hid_device *hid)
  11752. +{
  11753. + hid_dbg(hid, "%s\n", __func__);
  11754. + return 0;
  11755. +}
  11756. +
  11757. +static void vhf_hid_stop(struct hid_device *hid)
  11758. +{
  11759. + hid_dbg(hid, "%s\n", __func__);
  11760. +}
  11761. +
  11762. +static int vhf_hid_open(struct hid_device *hid)
  11763. +{
  11764. + hid_dbg(hid, "%s\n", __func__);
  11765. + return 0;
  11766. +}
  11767. +
  11768. +static void vhf_hid_close(struct hid_device *hid)
  11769. +{
  11770. + hid_dbg(hid, "%s\n", __func__);
  11771. +}
  11772. +
  11773. +static int vhf_hid_parse(struct hid_device *hid)
  11774. +{
  11775. + return hid_parse_report(hid, (u8 *)vhf_hid_desc, ARRAY_SIZE(vhf_hid_desc));
  11776. +}
  11777. +
  11778. +static int vhf_hid_raw_request(struct hid_device *hid, unsigned char reportnum,
  11779. + u8 *buf, size_t len, unsigned char rtype,
  11780. + int reqtype)
  11781. +{
  11782. + hid_dbg(hid, "%s\n", __func__);
  11783. + return 0;
  11784. +}
  11785. +
  11786. +static int vhf_hid_output_report(struct hid_device *hid, u8 *buf, size_t len)
  11787. +{
  11788. + hid_dbg(hid, "%s\n", __func__);
  11789. + print_hex_dump_debug("report:", DUMP_PREFIX_OFFSET, 16, 1, buf, len, false);
  11790. +
  11791. + return len;
  11792. +}
  11793. +
  11794. +static struct hid_ll_driver vhf_hid_ll_driver = {
  11795. + .start = vhf_hid_start,
  11796. + .stop = vhf_hid_stop,
  11797. + .open = vhf_hid_open,
  11798. + .close = vhf_hid_close,
  11799. + .parse = vhf_hid_parse,
  11800. + .raw_request = vhf_hid_raw_request,
  11801. + .output_report = vhf_hid_output_report,
  11802. +};
  11803. +
  11804. +
  11805. +static struct hid_device *vhf_create_hid_device(struct platform_device *pdev)
  11806. +{
  11807. + struct hid_device *hid;
  11808. +
  11809. + hid = hid_allocate_device();
  11810. + if (IS_ERR(hid))
  11811. + return hid;
  11812. +
  11813. + hid->dev.parent = &pdev->dev;
  11814. +
  11815. + hid->bus = BUS_VIRTUAL;
  11816. + hid->vendor = USB_VENDOR_ID_MICROSOFT;
  11817. + hid->product = USB_DEVICE_ID_MS_VHF;
  11818. +
  11819. + hid->ll_driver = &vhf_hid_ll_driver;
  11820. +
  11821. + sprintf(hid->name, "%s", VHF_INPUT_NAME);
  11822. +
  11823. + return hid;
  11824. +}
  11825. +
  11826. +static u32 vhf_event_handler(struct ssam_notifier_block *nb, const struct ssam_event *event)
  11827. +{
  11828. + struct vhf_drvdata *drvdata = container_of(nb, struct vhf_drvdata, notif.base);
  11829. + int status;
  11830. +
  11831. + if (event->target_category != 0x08)
  11832. + return 0;
  11833. +
  11834. + if (event->command_id == 0x03 || event->command_id == 0x04) {
  11835. + status = hid_input_report(drvdata->hid, HID_INPUT_REPORT, (u8 *)&event->data[0], event->length, 1);
  11836. + return ssam_notifier_from_errno(status) | SSAM_NOTIF_HANDLED;
  11837. + }
  11838. +
  11839. + return 0;
  11840. +}
  11841. +
  11842. +static int surface_sam_vhf_probe(struct platform_device *pdev)
  11843. +{
  11844. + struct vhf_drvdata *drvdata;
  11845. + struct hid_device *hid;
  11846. + int status;
  11847. +
  11848. + // add device link to EC
  11849. + status = surface_sam_ssh_consumer_register(&pdev->dev);
  11850. + if (status)
  11851. + return status == -ENXIO ? -EPROBE_DEFER : status;
  11852. +
  11853. + drvdata = kzalloc(sizeof(struct vhf_drvdata), GFP_KERNEL);
  11854. + if (!drvdata)
  11855. + return -ENOMEM;
  11856. +
  11857. + hid = vhf_create_hid_device(pdev);
  11858. + if (IS_ERR(hid)) {
  11859. + status = PTR_ERR(hid);
  11860. + goto err_probe_hid;
  11861. + }
  11862. +
  11863. + status = hid_add_device(hid);
  11864. + if (status)
  11865. + goto err_add_hid;
  11866. +
  11867. + drvdata->dev = pdev;
  11868. + drvdata->hid = hid;
  11869. +
  11870. + drvdata->notif.base.priority = 1;
  11871. + drvdata->notif.base.fn = vhf_event_handler;
  11872. + drvdata->notif.event.reg = SSAM_EVENT_REGISTRY_SAM;
  11873. + drvdata->notif.event.id.target_category = SSAM_SSH_TC_KBD;
  11874. + drvdata->notif.event.id.instance = 0;
  11875. + drvdata->notif.event.flags = 0;
  11876. +
  11877. + platform_set_drvdata(pdev, drvdata);
  11878. +
  11879. + status = surface_sam_ssh_notifier_register(&drvdata->notif);
  11880. + if (status)
  11881. + goto err_add_hid;
  11882. +
  11883. + return 0;
  11884. +
  11885. +err_add_hid:
  11886. + hid_destroy_device(hid);
  11887. + platform_set_drvdata(pdev, NULL);
  11888. +err_probe_hid:
  11889. + kfree(drvdata);
  11890. + return status;
  11891. +}
  11892. +
  11893. +static int surface_sam_vhf_remove(struct platform_device *pdev)
  11894. +{
  11895. + struct vhf_drvdata *drvdata = platform_get_drvdata(pdev);
  11896. +
  11897. + surface_sam_ssh_notifier_unregister(&drvdata->notif);
  11898. + hid_destroy_device(drvdata->hid);
  11899. + kfree(drvdata);
  11900. +
  11901. + platform_set_drvdata(pdev, NULL);
  11902. + return 0;
  11903. +}
  11904. +
  11905. +
  11906. +static const struct acpi_device_id surface_sam_vhf_match[] = {
  11907. + { "MSHW0096" },
  11908. + { },
  11909. +};
  11910. +MODULE_DEVICE_TABLE(acpi, surface_sam_vhf_match);
  11911. +
  11912. +static struct platform_driver surface_sam_vhf = {
  11913. + .probe = surface_sam_vhf_probe,
  11914. + .remove = surface_sam_vhf_remove,
  11915. + .driver = {
  11916. + .name = "surface_sam_vhf",
  11917. + .acpi_match_table = surface_sam_vhf_match,
  11918. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  11919. + },
  11920. +};
  11921. +module_platform_driver(surface_sam_vhf);
  11922. +
  11923. +MODULE_AUTHOR("Maximilian Luz <luzmaximilian@gmail.com>");
  11924. +MODULE_DESCRIPTION("Virtual HID Framework Driver for 5th Generation Surface Devices");
  11925. +MODULE_LICENSE("GPL");
  11926. --
  11927. 2.27.0