0004-surface-sam.patch 325 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133
  1. From 9fe067a9be3ad6e688acd4f4e1452a6c876e4401 Mon Sep 17 00:00:00 2001
  2. From: qzed <qzed@users.noreply.github.com>
  3. Date: Mon, 26 Aug 2019 01:11:08 +0200
  4. Subject: [PATCH 4/6] surface-sam
  5. ---
  6. drivers/acpi/acpica/dsopcode.c | 2 +-
  7. drivers/acpi/acpica/exfield.c | 12 +-
  8. drivers/platform/x86/Kconfig | 1 +
  9. drivers/platform/x86/Makefile | 1 +
  10. drivers/platform/x86/surface_sam/Kconfig | 176 +
  11. drivers/platform/x86/surface_sam/Makefile | 15 +
  12. .../x86/surface_sam/surface_sam_dtx.c | 590 ++
  13. .../x86/surface_sam/surface_sam_hps.c | 1297 +++++
  14. .../x86/surface_sam/surface_sam_san.c | 913 +++
  15. .../x86/surface_sam/surface_sam_san.h | 30 +
  16. .../x86/surface_sam/surface_sam_sid.c | 281 +
  17. .../x86/surface_sam/surface_sam_sid_gpelid.c | 232 +
  18. .../surface_sam/surface_sam_sid_perfmode.c | 216 +
  19. .../x86/surface_sam/surface_sam_sid_power.c | 1154 ++++
  20. .../x86/surface_sam/surface_sam_sid_power.h | 15 +
  21. .../x86/surface_sam/surface_sam_sid_vhf.c | 432 ++
  22. .../x86/surface_sam/surface_sam_sid_vhf.h | 13 +
  23. .../x86/surface_sam/surface_sam_ssh.c | 5111 +++++++++++++++++
  24. .../x86/surface_sam/surface_sam_ssh.h | 488 ++
  25. .../x86/surface_sam/surface_sam_ssh_trace.h | 536 ++
  26. .../x86/surface_sam/surface_sam_vhf.c | 261 +
  27. drivers/tty/serdev/core.c | 111 +-
  28. 22 files changed, 11871 insertions(+), 16 deletions(-)
  29. create mode 100644 drivers/platform/x86/surface_sam/Kconfig
  30. create mode 100644 drivers/platform/x86/surface_sam/Makefile
  31. create mode 100644 drivers/platform/x86/surface_sam/surface_sam_dtx.c
  32. create mode 100644 drivers/platform/x86/surface_sam/surface_sam_hps.c
  33. create mode 100644 drivers/platform/x86/surface_sam/surface_sam_san.c
  34. create mode 100644 drivers/platform/x86/surface_sam/surface_sam_san.h
  35. create mode 100644 drivers/platform/x86/surface_sam/surface_sam_sid.c
  36. create mode 100644 drivers/platform/x86/surface_sam/surface_sam_sid_gpelid.c
  37. create mode 100644 drivers/platform/x86/surface_sam/surface_sam_sid_perfmode.c
  38. create mode 100644 drivers/platform/x86/surface_sam/surface_sam_sid_power.c
  39. create mode 100644 drivers/platform/x86/surface_sam/surface_sam_sid_power.h
  40. create mode 100644 drivers/platform/x86/surface_sam/surface_sam_sid_vhf.c
  41. create mode 100644 drivers/platform/x86/surface_sam/surface_sam_sid_vhf.h
  42. create mode 100644 drivers/platform/x86/surface_sam/surface_sam_ssh.c
  43. create mode 100644 drivers/platform/x86/surface_sam/surface_sam_ssh.h
  44. create mode 100644 drivers/platform/x86/surface_sam/surface_sam_ssh_trace.h
  45. create mode 100644 drivers/platform/x86/surface_sam/surface_sam_vhf.c
  46. diff --git a/drivers/acpi/acpica/dsopcode.c b/drivers/acpi/acpica/dsopcode.c
  47. index 10f32b62608ee..7b2a4987f0507 100644
  48. --- a/drivers/acpi/acpica/dsopcode.c
  49. +++ b/drivers/acpi/acpica/dsopcode.c
  50. @@ -123,7 +123,7 @@ acpi_ds_init_buffer_field(u16 aml_opcode,
  51. /* Offset is in bits, count is in bits */
  52. - field_flags = AML_FIELD_ACCESS_BYTE;
  53. + field_flags = AML_FIELD_ACCESS_BUFFER;
  54. bit_offset = offset;
  55. bit_count = (u32) length_desc->integer.value;
  56. diff --git a/drivers/acpi/acpica/exfield.c b/drivers/acpi/acpica/exfield.c
  57. index d3d2dbfba680c..0b7f617a6e9b1 100644
  58. --- a/drivers/acpi/acpica/exfield.c
  59. +++ b/drivers/acpi/acpica/exfield.c
  60. @@ -109,6 +109,7 @@ acpi_ex_read_data_from_field(struct acpi_walk_state *walk_state,
  61. union acpi_operand_object *buffer_desc;
  62. void *buffer;
  63. u32 buffer_length;
  64. + u8 field_flags;
  65. ACPI_FUNCTION_TRACE_PTR(ex_read_data_from_field, obj_desc);
  66. @@ -157,11 +158,16 @@ acpi_ex_read_data_from_field(struct acpi_walk_state *walk_state,
  67. * Note: Field.length is in bits.
  68. */
  69. buffer_length =
  70. - (acpi_size)ACPI_ROUND_BITS_UP_TO_BYTES(obj_desc->field.bit_length);
  71. + (acpi_size)ACPI_ROUND_BITS_UP_TO_BYTES(obj_desc->common_field.bit_length);
  72. + field_flags = obj_desc->common_field.field_flags;
  73. - if (buffer_length > acpi_gbl_integer_byte_width) {
  74. + if (buffer_length > acpi_gbl_integer_byte_width ||
  75. + (field_flags & AML_FIELD_ACCESS_TYPE_MASK) == AML_FIELD_ACCESS_BUFFER) {
  76. - /* Field is too large for an Integer, create a Buffer instead */
  77. + /*
  78. + * Field is either too large for an Integer, or a actually of type
  79. + * buffer, so create a Buffer.
  80. + */
  81. buffer_desc = acpi_ut_create_buffer_object(buffer_length);
  82. if (!buffer_desc) {
  83. diff --git a/drivers/platform/x86/Kconfig b/drivers/platform/x86/Kconfig
  84. index 348c795019fa4..d25067a838a33 100644
  85. --- a/drivers/platform/x86/Kconfig
  86. +++ b/drivers/platform/x86/Kconfig
  87. @@ -1342,6 +1342,7 @@ config PCENGINES_APU2
  88. will be called pcengines-apuv2.
  89. source "drivers/platform/x86/intel_speed_select_if/Kconfig"
  90. +source "drivers/platform/x86/surface_sam/Kconfig"
  91. endif # X86_PLATFORM_DEVICES
  92. diff --git a/drivers/platform/x86/Makefile b/drivers/platform/x86/Makefile
  93. index 6dd955ad9bf18..19b56f2181eb9 100644
  94. --- a/drivers/platform/x86/Makefile
  95. +++ b/drivers/platform/x86/Makefile
  96. @@ -101,3 +101,4 @@ obj-$(CONFIG_I2C_MULTI_INSTANTIATE) += i2c-multi-instantiate.o
  97. obj-$(CONFIG_INTEL_ATOMISP2_PM) += intel_atomisp2_pm.o
  98. obj-$(CONFIG_PCENGINES_APU2) += pcengines-apuv2.o
  99. obj-$(CONFIG_INTEL_SPEED_SELECT_INTERFACE) += intel_speed_select_if/
  100. +obj-$(CONFIG_SURFACE_SAM) += surface_sam/
  101. diff --git a/drivers/platform/x86/surface_sam/Kconfig b/drivers/platform/x86/surface_sam/Kconfig
  102. new file mode 100644
  103. index 0000000000000..7781c5cd932c0
  104. --- /dev/null
  105. +++ b/drivers/platform/x86/surface_sam/Kconfig
  106. @@ -0,0 +1,176 @@
  107. +menuconfig SURFACE_SAM
  108. + depends on ACPI
  109. + tristate "Microsoft Surface/System Aggregator Module and Platform Drivers"
  110. + help
  111. + Drivers for the Surface/System Aggregator Module (SAM) of Microsoft
  112. + Surface devices.
  113. +
  114. + SAM is an embedded controller that provides access to various
  115. + functionalities on these devices, including battery status, keyboard
  116. + events (on the Laptops) and many more.
  117. +
  118. + Say M/Y here if you have a Microsoft Surface device with a SAM device
  119. + (i.e. 5th generation or later).
  120. +
  121. +config SURFACE_SAM_SSH
  122. + tristate "Surface Serial Hub Driver"
  123. + depends on SURFACE_SAM
  124. + depends on SERIAL_DEV_CTRL_TTYPORT
  125. + select CRC_CCITT
  126. + default m
  127. + help
  128. + Surface Serial Hub driver for 5th generation (or later) Microsoft
  129. + Surface devices.
  130. +
  131. + This is the base driver for the embedded serial controller found on
  132. + 5th generation (and later) Microsoft Surface devices (e.g. Book 2,
  133. + Laptop, Laptop 2, Pro 2017, Pro 6, ...). This driver itself only
  134. + provides access to the embedded controller (SAM) and subsequent
  135. + drivers are required for the respective functionalities.
  136. +
  137. + If you have a 5th generation (or later) Microsoft Surface device, say
  138. + Y or M here.
  139. +
  140. +config SURFACE_SAM_SSH_DEBUG_DEVICE
  141. + bool "Surface Serial Hub Debug Device"
  142. + depends on SURFACE_SAM_SSH
  143. + depends on SYSFS
  144. + default n
  145. + help
  146. + Debug device for direct communication with the embedded controller
  147. + found on 5th generation (and later) Microsoft Surface devices (e.g.
  148. + Book 2, Laptop, Laptop 2, Pro 2017, Pro 6, ...) via sysfs.
  149. +
  150. + If you are not sure, say N here.
  151. +
  152. +config SURFACE_SAM_SSH_ERROR_INJECTION
  153. + bool "Surface Serial Hub Error Injection Capabilities"
  154. + depends on SURFACE_SAM_SSH
  155. + depends on FUNCTION_ERROR_INJECTION
  156. + default n
  157. + help
  158. + Enable error injection capabilities for the Surface Serial Hub.
  159. + This is used to debug the driver, specifically the communication
  160. + interface. It is not required for normal use.
  161. +
  162. + If you are not sure, say N here.
  163. +
  164. +config SURFACE_SAM_SAN
  165. + tristate "Surface ACPI Notify Driver"
  166. + depends on SURFACE_SAM_SSH
  167. + default m
  168. + help
  169. + Surface ACPI Notify driver for 5th generation (or later) Microsoft
  170. + Surface devices.
  171. +
  172. + This driver enables basic ACPI events and requests, such as battery
  173. + status requests/events, thermal events, lid status, and possibly more,
  174. + which would otherwise not work on these devices.
  175. +
  176. + If you are not sure, say M here.
  177. +
  178. +config SURFACE_SAM_VHF
  179. + tristate "Surface Virtual HID Framework Driver"
  180. + depends on SURFACE_SAM_SSH
  181. + depends on HID
  182. + default m
  183. + help
  184. + Surface Virtual HID Framework driver for 5th generation (or later)
  185. + Microsoft Surface devices.
  186. +
  187. + This driver provides support for the Microsoft Virtual HID framework,
  188. + which is required for keyboard support on the Surface Laptop 1 and 2.
  189. +
  190. + If you are not sure, say M here.
  191. +
  192. +config SURFACE_SAM_DTX
  193. + tristate "Surface Detachment System (DTX) Driver"
  194. + depends on SURFACE_SAM_SSH
  195. + depends on INPUT
  196. + default m
  197. + help
  198. + Surface Detachment System (DTX) driver for the Microsoft Surface Book
  199. + 2. This driver provides support for proper detachment handling in
  200. + user-space, status-events relating to the base and support for
  201. + the safe-guard keeping the base attached when the discrete GPU
  202. + contained in it is running via the special /dev/surface-dtx device.
  203. +
  204. + Also provides a standard input device to provide SW_TABLET_MODE events
  205. + upon device mode change.
  206. +
  207. + If you are not sure, say M here.
  208. +
  209. +config SURFACE_SAM_HPS
  210. + tristate "Surface dGPU Hot-Plug System (dGPU-HPS) Driver"
  211. + depends on SURFACE_SAM_SSH
  212. + depends on SURFACE_SAM_SAN
  213. + depends on GPIO_SYSFS
  214. + default m
  215. + help
  216. + Driver to properly handle hot-plugging and explicit power-on/power-off
  217. + of the discrete GPU (dGPU) on the Surface Book 2 and 3.
  218. +
  219. + If you are not sure, say M here.
  220. +
  221. +config SURFACE_SAM_SID
  222. + tristate "Surface Platform Integration Driver"
  223. + depends on SURFACE_SAM_SSH
  224. + default m
  225. + help
  226. + Surface Platform Integration Driver for the Microsoft Surface Devices.
  227. + This driver loads various model-specific sub-drivers, including
  228. + battery and keyboard support on 7th generation Surface devices, proper
  229. + lid setup to enable device wakeup when the lid is opened on multiple
  230. + models, as well as performance mode setting support on the Surface
  231. + Book 2.
  232. +
  233. + If you are not sure, say M here.
  234. +
  235. +config SURFACE_SAM_SID_GPELID
  236. + tristate "Surface Lid Wakeup Driver"
  237. + depends on SURFACE_SAM_SID
  238. + default m
  239. + help
  240. + Driver to set up device wake-up via lid on Intel-based Microsoft
  241. + Surface devices. These devices do not wake up from sleep as their GPE
  242. + interrupt is not configured automatically. This driver solves that
  243. + problem.
  244. +
  245. + If you are not sure, say M here.
  246. +
  247. +config SURFACE_SAM_SID_PERFMODE
  248. + tristate "Surface Performance Mode Driver"
  249. + depends on SURFACE_SAM_SID
  250. + depends on SYSFS
  251. + default m
  252. + help
  253. + This driver provides support for setting performance-modes on Surface
  254. + devices via the perf_mode sysfs attribute. Currently only supports the
  255. + Surface Book 2. Performance-modes directly influence the fan-profile
  256. + of the device, allowing to choose between higher performance or
  257. + quieter operation.
  258. +
  259. + If you are not sure, say M here.
  260. +
  261. +config SURFACE_SAM_SID_VHF
  262. + tristate "Surface SAM HID Driver"
  263. + depends on SURFACE_SAM_SID
  264. + depends on HID
  265. + default m
  266. + help
  267. + This driver provides support for HID devices connected via the Surface
  268. + SAM embedded controller. It provides support for keyboard and touchpad
  269. + on the Surface Laptop 3 models.
  270. +
  271. + If you are not sure, say M here.
  272. +
  273. +config SURFACE_SAM_SID_POWER
  274. + tristate "Surface SAM Battery/AC Driver"
  275. + depends on SURFACE_SAM_SID
  276. + select POWER_SUPPLY
  277. + default m
  278. + help
  279. + This driver provides support for the battery and AC on 7th generation
  280. + Surface devices.
  281. +
  282. + If you are not sure, say M here.
  283. diff --git a/drivers/platform/x86/surface_sam/Makefile b/drivers/platform/x86/surface_sam/Makefile
  284. new file mode 100644
  285. index 0000000000000..1a5c1260639dc
  286. --- /dev/null
  287. +++ b/drivers/platform/x86/surface_sam/Makefile
  288. @@ -0,0 +1,15 @@
  289. +# SPDX-License-Identifier: GPL-2.0-or-later
  290. +
  291. +# For include/trace/define_trace.h to include surface_sam_ssh_trace.h
  292. +CFLAGS_surface_sam_ssh.o = -I$(src)
  293. +
  294. +obj-$(CONFIG_SURFACE_SAM_SSH) += surface_sam_ssh.o
  295. +obj-$(CONFIG_SURFACE_SAM_SAN) += surface_sam_san.o
  296. +obj-$(CONFIG_SURFACE_SAM_DTX) += surface_sam_dtx.o
  297. +obj-$(CONFIG_SURFACE_SAM_HPS) += surface_sam_hps.o
  298. +obj-$(CONFIG_SURFACE_SAM_VHF) += surface_sam_vhf.o
  299. +obj-$(CONFIG_SURFACE_SAM_SID) += surface_sam_sid.o
  300. +obj-$(CONFIG_SURFACE_SAM_SID_GPELID) += surface_sam_sid_gpelid.o
  301. +obj-$(CONFIG_SURFACE_SAM_SID_PERFMODE) += surface_sam_sid_perfmode.o
  302. +obj-$(CONFIG_SURFACE_SAM_SID_POWER) += surface_sam_sid_power.o
  303. +obj-$(CONFIG_SURFACE_SAM_SID_VHF) += surface_sam_sid_vhf.o
  304. diff --git a/drivers/platform/x86/surface_sam/surface_sam_dtx.c b/drivers/platform/x86/surface_sam/surface_sam_dtx.c
  305. new file mode 100644
  306. index 0000000000000..88dba7bced3a4
  307. --- /dev/null
  308. +++ b/drivers/platform/x86/surface_sam/surface_sam_dtx.c
  309. @@ -0,0 +1,590 @@
  310. +// SPDX-License-Identifier: GPL-2.0-or-later
  311. +/*
  312. + * Detachment system (DTX) driver for Microsoft Surface Book 2.
  313. + */
  314. +
  315. +#include <linux/acpi.h>
  316. +#include <linux/delay.h>
  317. +#include <linux/fs.h>
  318. +#include <linux/input.h>
  319. +#include <linux/ioctl.h>
  320. +#include <linux/kernel.h>
  321. +#include <linux/miscdevice.h>
  322. +#include <linux/module.h>
  323. +#include <linux/poll.h>
  324. +#include <linux/rculist.h>
  325. +#include <linux/slab.h>
  326. +#include <linux/spinlock.h>
  327. +#include <linux/platform_device.h>
  328. +
  329. +#include "surface_sam_ssh.h"
  330. +
  331. +
  332. +#define USB_VENDOR_ID_MICROSOFT 0x045e
  333. +#define USB_DEVICE_ID_MS_SURFACE_BASE_2_INTEGRATION 0x0922
  334. +
  335. +// name copied from MS device manager
  336. +#define DTX_INPUT_NAME "Microsoft Surface Base 2 Integration Device"
  337. +
  338. +
  339. +#define DTX_CMD_LATCH_LOCK _IO(0x11, 0x01)
  340. +#define DTX_CMD_LATCH_UNLOCK _IO(0x11, 0x02)
  341. +#define DTX_CMD_LATCH_REQUEST _IO(0x11, 0x03)
  342. +#define DTX_CMD_LATCH_OPEN _IO(0x11, 0x04)
  343. +#define DTX_CMD_GET_OPMODE _IOR(0x11, 0x05, int)
  344. +
  345. +#define SAM_RQST_DTX_TC 0x11
  346. +#define SAM_RQST_DTX_CID_LATCH_LOCK 0x06
  347. +#define SAM_RQST_DTX_CID_LATCH_UNLOCK 0x07
  348. +#define SAM_RQST_DTX_CID_LATCH_REQUEST 0x08
  349. +#define SAM_RQST_DTX_CID_LATCH_OPEN 0x09
  350. +#define SAM_RQST_DTX_CID_GET_OPMODE 0x0D
  351. +
  352. +#define SAM_EVENT_DTX_CID_CONNECTION 0x0c
  353. +#define SAM_EVENT_DTX_CID_BUTTON 0x0e
  354. +#define SAM_EVENT_DTX_CID_ERROR 0x0f
  355. +#define SAM_EVENT_DTX_CID_LATCH_STATUS 0x11
  356. +
  357. +#define DTX_OPMODE_TABLET 0x00
  358. +#define DTX_OPMODE_LAPTOP 0x01
  359. +#define DTX_OPMODE_STUDIO 0x02
  360. +
  361. +#define DTX_LATCH_CLOSED 0x00
  362. +#define DTX_LATCH_OPENED 0x01
  363. +
  364. +
  365. +// Warning: This must always be a power of 2!
  366. +#define DTX_CLIENT_BUF_SIZE 16
  367. +
  368. +#define DTX_CONNECT_OPMODE_DELAY 1000
  369. +
  370. +#define DTX_ERR KERN_ERR "surface_sam_dtx: "
  371. +#define DTX_WARN KERN_WARNING "surface_sam_dtx: "
  372. +
  373. +
  374. +struct surface_dtx_event {
  375. + u8 type;
  376. + u8 code;
  377. + u8 arg0;
  378. + u8 arg1;
  379. +} __packed;
  380. +
  381. +struct surface_dtx_dev {
  382. + struct ssam_event_notifier notif;
  383. + struct delayed_work opmode_work;
  384. + wait_queue_head_t waitq;
  385. + struct miscdevice mdev;
  386. + spinlock_t client_lock;
  387. + struct list_head client_list;
  388. + struct mutex mutex;
  389. + bool active;
  390. + spinlock_t input_lock;
  391. + struct input_dev *input_dev;
  392. +};
  393. +
  394. +struct surface_dtx_client {
  395. + struct list_head node;
  396. + struct surface_dtx_dev *ddev;
  397. + struct fasync_struct *fasync;
  398. + spinlock_t buffer_lock;
  399. + unsigned int buffer_head;
  400. + unsigned int buffer_tail;
  401. + struct surface_dtx_event buffer[DTX_CLIENT_BUF_SIZE];
  402. +};
  403. +
  404. +
  405. +static struct surface_dtx_dev surface_dtx_dev;
  406. +
  407. +
  408. +static int surface_sam_query_opmpde(void)
  409. +{
  410. + u8 result_buf[1];
  411. + int status;
  412. +
  413. + struct surface_sam_ssh_rqst rqst = {
  414. + .tc = SAM_RQST_DTX_TC,
  415. + .cid = SAM_RQST_DTX_CID_GET_OPMODE,
  416. + .iid = 0x00,
  417. + .chn = 0x01,
  418. + .snc = 0x01,
  419. + .cdl = 0x00,
  420. + .pld = NULL,
  421. + };
  422. +
  423. + struct surface_sam_ssh_buf result = {
  424. + .cap = 1,
  425. + .len = 0,
  426. + .data = result_buf,
  427. + };
  428. +
  429. + status = surface_sam_ssh_rqst(&rqst, &result);
  430. + if (status)
  431. + return status;
  432. +
  433. + if (result.len != 1)
  434. + return -EFAULT;
  435. +
  436. + return result.data[0];
  437. +}
  438. +
  439. +
  440. +static int dtx_cmd_simple(u8 cid)
  441. +{
  442. + struct surface_sam_ssh_rqst rqst = {
  443. + .tc = SAM_RQST_DTX_TC,
  444. + .cid = cid,
  445. + .iid = 0x00,
  446. + .chn = 0x01,
  447. + .snc = 0x00,
  448. + .cdl = 0x00,
  449. + .pld = NULL,
  450. + };
  451. +
  452. + return surface_sam_ssh_rqst(&rqst, NULL);
  453. +}
  454. +
  455. +static int dtx_cmd_get_opmode(int __user *buf)
  456. +{
  457. + int opmode;
  458. +
  459. + opmode = surface_sam_query_opmpde();
  460. + if (opmode < 0)
  461. + return opmode;
  462. +
  463. + if (put_user(opmode, buf))
  464. + return -EACCES;
  465. +
  466. + return 0;
  467. +}
  468. +
  469. +
  470. +static int surface_dtx_open(struct inode *inode, struct file *file)
  471. +{
  472. + struct surface_dtx_dev *ddev = container_of(file->private_data, struct surface_dtx_dev, mdev);
  473. + struct surface_dtx_client *client;
  474. +
  475. + // initialize client
  476. + client = kzalloc(sizeof(struct surface_dtx_client), GFP_KERNEL);
  477. + if (!client)
  478. + return -ENOMEM;
  479. +
  480. + spin_lock_init(&client->buffer_lock);
  481. + client->buffer_head = 0;
  482. + client->buffer_tail = 0;
  483. + client->ddev = ddev;
  484. +
  485. + // attach client
  486. + spin_lock(&ddev->client_lock);
  487. + list_add_tail_rcu(&client->node, &ddev->client_list);
  488. + spin_unlock(&ddev->client_lock);
  489. +
  490. + file->private_data = client;
  491. + nonseekable_open(inode, file);
  492. +
  493. + return 0;
  494. +}
  495. +
  496. +static int surface_dtx_release(struct inode *inode, struct file *file)
  497. +{
  498. + struct surface_dtx_client *client = file->private_data;
  499. +
  500. + // detach client
  501. + spin_lock(&client->ddev->client_lock);
  502. + list_del_rcu(&client->node);
  503. + spin_unlock(&client->ddev->client_lock);
  504. + synchronize_rcu();
  505. +
  506. + kfree(client);
  507. + file->private_data = NULL;
  508. +
  509. + return 0;
  510. +}
  511. +
  512. +static ssize_t surface_dtx_read(struct file *file, char __user *buf, size_t count, loff_t *offs)
  513. +{
  514. + struct surface_dtx_client *client = file->private_data;
  515. + struct surface_dtx_dev *ddev = client->ddev;
  516. + struct surface_dtx_event event;
  517. + size_t read = 0;
  518. + int status = 0;
  519. +
  520. + if (count != 0 && count < sizeof(struct surface_dtx_event))
  521. + return -EINVAL;
  522. +
  523. + if (!ddev->active)
  524. + return -ENODEV;
  525. +
  526. + // check availability
  527. + if (client->buffer_head == client->buffer_tail) {
  528. + if (file->f_flags & O_NONBLOCK)
  529. + return -EAGAIN;
  530. +
  531. + status = wait_event_interruptible(ddev->waitq,
  532. + client->buffer_head != client->buffer_tail ||
  533. + !ddev->active);
  534. + if (status)
  535. + return status;
  536. +
  537. + if (!ddev->active)
  538. + return -ENODEV;
  539. + }
  540. +
  541. + // copy events one by one
  542. + while (read + sizeof(struct surface_dtx_event) <= count) {
  543. + spin_lock_irq(&client->buffer_lock);
  544. +
  545. + if (client->buffer_head == client->buffer_tail) {
  546. + spin_unlock_irq(&client->buffer_lock);
  547. + break;
  548. + }
  549. +
  550. + // get one event
  551. + event = client->buffer[client->buffer_tail];
  552. + client->buffer_tail = (client->buffer_tail + 1) & (DTX_CLIENT_BUF_SIZE - 1);
  553. + spin_unlock_irq(&client->buffer_lock);
  554. +
  555. + // copy to userspace
  556. + if (copy_to_user(buf, &event, sizeof(struct surface_dtx_event)))
  557. + return -EFAULT;
  558. +
  559. + read += sizeof(struct surface_dtx_event);
  560. + }
  561. +
  562. + return read;
  563. +}
  564. +
  565. +static __poll_t surface_dtx_poll(struct file *file, struct poll_table_struct *pt)
  566. +{
  567. + struct surface_dtx_client *client = file->private_data;
  568. + int mask;
  569. +
  570. + poll_wait(file, &client->ddev->waitq, pt);
  571. +
  572. + if (client->ddev->active)
  573. + mask = EPOLLOUT | EPOLLWRNORM;
  574. + else
  575. + mask = EPOLLHUP | EPOLLERR;
  576. +
  577. + if (client->buffer_head != client->buffer_tail)
  578. + mask |= EPOLLIN | EPOLLRDNORM;
  579. +
  580. + return mask;
  581. +}
  582. +
  583. +static int surface_dtx_fasync(int fd, struct file *file, int on)
  584. +{
  585. + struct surface_dtx_client *client = file->private_data;
  586. +
  587. + return fasync_helper(fd, file, on, &client->fasync);
  588. +}
  589. +
  590. +static long surface_dtx_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
  591. +{
  592. + struct surface_dtx_client *client = file->private_data;
  593. + struct surface_dtx_dev *ddev = client->ddev;
  594. + int status;
  595. +
  596. + status = mutex_lock_interruptible(&ddev->mutex);
  597. + if (status)
  598. + return status;
  599. +
  600. + if (!ddev->active) {
  601. + mutex_unlock(&ddev->mutex);
  602. + return -ENODEV;
  603. + }
  604. +
  605. + switch (cmd) {
  606. + case DTX_CMD_LATCH_LOCK:
  607. + status = dtx_cmd_simple(SAM_RQST_DTX_CID_LATCH_LOCK);
  608. + break;
  609. +
  610. + case DTX_CMD_LATCH_UNLOCK:
  611. + status = dtx_cmd_simple(SAM_RQST_DTX_CID_LATCH_UNLOCK);
  612. + break;
  613. +
  614. + case DTX_CMD_LATCH_REQUEST:
  615. + status = dtx_cmd_simple(SAM_RQST_DTX_CID_LATCH_REQUEST);
  616. + break;
  617. +
  618. + case DTX_CMD_LATCH_OPEN:
  619. + status = dtx_cmd_simple(SAM_RQST_DTX_CID_LATCH_OPEN);
  620. + break;
  621. +
  622. + case DTX_CMD_GET_OPMODE:
  623. + status = dtx_cmd_get_opmode((int __user *)arg);
  624. + break;
  625. +
  626. + default:
  627. + status = -EINVAL;
  628. + break;
  629. + }
  630. +
  631. + mutex_unlock(&ddev->mutex);
  632. + return status;
  633. +}
  634. +
  635. +static const struct file_operations surface_dtx_fops = {
  636. + .owner = THIS_MODULE,
  637. + .open = surface_dtx_open,
  638. + .release = surface_dtx_release,
  639. + .read = surface_dtx_read,
  640. + .poll = surface_dtx_poll,
  641. + .fasync = surface_dtx_fasync,
  642. + .unlocked_ioctl = surface_dtx_ioctl,
  643. + .llseek = no_llseek,
  644. +};
  645. +
  646. +static struct surface_dtx_dev surface_dtx_dev = {
  647. + .mdev = {
  648. + .minor = MISC_DYNAMIC_MINOR,
  649. + .name = "surface_dtx",
  650. + .fops = &surface_dtx_fops,
  651. + },
  652. + .client_lock = __SPIN_LOCK_UNLOCKED(),
  653. + .input_lock = __SPIN_LOCK_UNLOCKED(),
  654. + .mutex = __MUTEX_INITIALIZER(surface_dtx_dev.mutex),
  655. + .active = false,
  656. +};
  657. +
  658. +
  659. +static void surface_dtx_push_event(struct surface_dtx_dev *ddev, struct surface_dtx_event *event)
  660. +{
  661. + struct surface_dtx_client *client;
  662. +
  663. + rcu_read_lock();
  664. + list_for_each_entry_rcu(client, &ddev->client_list, node) {
  665. + spin_lock(&client->buffer_lock);
  666. +
  667. + client->buffer[client->buffer_head++] = *event;
  668. + client->buffer_head &= DTX_CLIENT_BUF_SIZE - 1;
  669. +
  670. + if (unlikely(client->buffer_head == client->buffer_tail)) {
  671. + printk(DTX_WARN "event buffer overrun\n");
  672. + client->buffer_tail = (client->buffer_tail + 1) & (DTX_CLIENT_BUF_SIZE - 1);
  673. + }
  674. +
  675. + spin_unlock(&client->buffer_lock);
  676. +
  677. + kill_fasync(&client->fasync, SIGIO, POLL_IN);
  678. + }
  679. + rcu_read_unlock();
  680. +
  681. + wake_up_interruptible(&ddev->waitq);
  682. +}
  683. +
  684. +
  685. +static void surface_dtx_update_opmpde(struct surface_dtx_dev *ddev)
  686. +{
  687. + struct surface_dtx_event event;
  688. + int opmode;
  689. +
  690. + // get operation mode
  691. + opmode = surface_sam_query_opmpde();
  692. + if (opmode < 0)
  693. + printk(DTX_ERR "EC request failed with error %d\n", opmode);
  694. +
  695. + // send DTX event
  696. + event.type = 0x11;
  697. + event.code = 0x0D;
  698. + event.arg0 = opmode;
  699. + event.arg1 = 0x00;
  700. +
  701. + surface_dtx_push_event(ddev, &event);
  702. +
  703. + // send SW_TABLET_MODE event
  704. + spin_lock(&ddev->input_lock);
  705. + input_report_switch(ddev->input_dev, SW_TABLET_MODE, opmode != DTX_OPMODE_LAPTOP);
  706. + input_sync(ddev->input_dev);
  707. + spin_unlock(&ddev->input_lock);
  708. +}
  709. +
  710. +static void surface_dtx_opmode_workfn(struct work_struct *work)
  711. +{
  712. + struct surface_dtx_dev *ddev = container_of(work, struct surface_dtx_dev, opmode_work.work);
  713. +
  714. + surface_dtx_update_opmpde(ddev);
  715. +}
  716. +
  717. +static u32 surface_dtx_notification(struct ssam_notifier_block *nb, const struct ssam_event *in_event)
  718. +{
  719. + struct surface_dtx_dev *ddev = container_of(nb, struct surface_dtx_dev, notif.base);
  720. + struct surface_dtx_event event;
  721. + unsigned long delay;
  722. +
  723. + switch (in_event->command_id) {
  724. + case SAM_EVENT_DTX_CID_CONNECTION:
  725. + case SAM_EVENT_DTX_CID_BUTTON:
  726. + case SAM_EVENT_DTX_CID_ERROR:
  727. + case SAM_EVENT_DTX_CID_LATCH_STATUS:
  728. + if (in_event->length > 2) {
  729. + printk(DTX_ERR "unexpected payload size (cid: %x, len: %u)\n",
  730. + in_event->command_id, in_event->length);
  731. + return SSAM_NOTIF_HANDLED;
  732. + }
  733. +
  734. + event.type = in_event->target_category;
  735. + event.code = in_event->command_id;
  736. + event.arg0 = in_event->length >= 1 ? in_event->data[0] : 0x00;
  737. + event.arg1 = in_event->length >= 2 ? in_event->data[1] : 0x00;
  738. + surface_dtx_push_event(ddev, &event);
  739. + break;
  740. +
  741. + default:
  742. + return 0;
  743. + }
  744. +
  745. + // update device mode
  746. + if (in_event->command_id == SAM_EVENT_DTX_CID_CONNECTION) {
  747. + delay = event.arg0 ? DTX_CONNECT_OPMODE_DELAY : 0;
  748. + schedule_delayed_work(&ddev->opmode_work, delay);
  749. + }
  750. +
  751. + return SSAM_NOTIF_HANDLED;
  752. +}
  753. +
  754. +
  755. +static struct input_dev *surface_dtx_register_inputdev(struct platform_device *pdev)
  756. +{
  757. + struct input_dev *input_dev;
  758. + int status;
  759. +
  760. + input_dev = input_allocate_device();
  761. + if (!input_dev)
  762. + return ERR_PTR(-ENOMEM);
  763. +
  764. + input_dev->name = DTX_INPUT_NAME;
  765. + input_dev->dev.parent = &pdev->dev;
  766. + input_dev->id.bustype = BUS_VIRTUAL;
  767. + input_dev->id.vendor = USB_VENDOR_ID_MICROSOFT;
  768. + input_dev->id.product = USB_DEVICE_ID_MS_SURFACE_BASE_2_INTEGRATION;
  769. +
  770. + input_set_capability(input_dev, EV_SW, SW_TABLET_MODE);
  771. +
  772. + status = surface_sam_query_opmpde();
  773. + if (status < 0) {
  774. + input_free_device(input_dev);
  775. + return ERR_PTR(status);
  776. + }
  777. +
  778. + input_report_switch(input_dev, SW_TABLET_MODE, status != DTX_OPMODE_LAPTOP);
  779. +
  780. + status = input_register_device(input_dev);
  781. + if (status) {
  782. + input_unregister_device(input_dev);
  783. + return ERR_PTR(status);
  784. + }
  785. +
  786. + return input_dev;
  787. +}
  788. +
  789. +
  790. +static int surface_sam_dtx_probe(struct platform_device *pdev)
  791. +{
  792. + struct surface_dtx_dev *ddev = &surface_dtx_dev;
  793. + struct input_dev *input_dev;
  794. + int status;
  795. +
  796. + // link to ec
  797. + status = surface_sam_ssh_consumer_register(&pdev->dev);
  798. + if (status)
  799. + return status == -ENXIO ? -EPROBE_DEFER : status;
  800. +
  801. + input_dev = surface_dtx_register_inputdev(pdev);
  802. + if (IS_ERR(input_dev))
  803. + return PTR_ERR(input_dev);
  804. +
  805. + // initialize device
  806. + mutex_lock(&ddev->mutex);
  807. + if (ddev->active) {
  808. + mutex_unlock(&ddev->mutex);
  809. + status = -ENODEV;
  810. + goto err_register;
  811. + }
  812. +
  813. + INIT_DELAYED_WORK(&ddev->opmode_work, surface_dtx_opmode_workfn);
  814. + INIT_LIST_HEAD(&ddev->client_list);
  815. + init_waitqueue_head(&ddev->waitq);
  816. + ddev->active = true;
  817. + ddev->input_dev = input_dev;
  818. + mutex_unlock(&ddev->mutex);
  819. +
  820. + status = misc_register(&ddev->mdev);
  821. + if (status)
  822. + goto err_register;
  823. +
  824. + // set up events
  825. + ddev->notif.base.priority = 1;
  826. + ddev->notif.base.fn = surface_dtx_notification;
  827. + ddev->notif.event.reg = SSAM_EVENT_REGISTRY_SAM;
  828. + ddev->notif.event.id.target_category = SSAM_SSH_TC_BAS;
  829. + ddev->notif.event.id.instance = 0;
  830. + ddev->notif.event.flags = SSAM_EVENT_SEQUENCED;
  831. +
  832. + status = surface_sam_ssh_notifier_register(&ddev->notif);
  833. + if (status)
  834. + goto err_events_setup;
  835. +
  836. + return 0;
  837. +
  838. +err_events_setup:
  839. + misc_deregister(&ddev->mdev);
  840. +err_register:
  841. + input_unregister_device(ddev->input_dev);
  842. + return status;
  843. +}
  844. +
  845. +static int surface_sam_dtx_remove(struct platform_device *pdev)
  846. +{
  847. + struct surface_dtx_dev *ddev = &surface_dtx_dev;
  848. + struct surface_dtx_client *client;
  849. +
  850. + mutex_lock(&ddev->mutex);
  851. + if (!ddev->active) {
  852. + mutex_unlock(&ddev->mutex);
  853. + return 0;
  854. + }
  855. +
  856. + // mark as inactive
  857. + ddev->active = false;
  858. + mutex_unlock(&ddev->mutex);
  859. +
  860. + // After this call we're guaranteed that no more input events will arive
  861. + surface_sam_ssh_notifier_unregister(&ddev->notif);
  862. +
  863. + // wake up clients
  864. + spin_lock(&ddev->client_lock);
  865. + list_for_each_entry(client, &ddev->client_list, node) {
  866. + kill_fasync(&client->fasync, SIGIO, POLL_HUP);
  867. + }
  868. + spin_unlock(&ddev->client_lock);
  869. +
  870. + wake_up_interruptible(&ddev->waitq);
  871. +
  872. + // unregister user-space devices
  873. + input_unregister_device(ddev->input_dev);
  874. + misc_deregister(&ddev->mdev);
  875. +
  876. + return 0;
  877. +}
  878. +
  879. +
  880. +static const struct acpi_device_id surface_sam_dtx_match[] = {
  881. + { "MSHW0133", 0 },
  882. + { },
  883. +};
  884. +MODULE_DEVICE_TABLE(acpi, surface_sam_dtx_match);
  885. +
  886. +static struct platform_driver surface_sam_dtx = {
  887. + .probe = surface_sam_dtx_probe,
  888. + .remove = surface_sam_dtx_remove,
  889. + .driver = {
  890. + .name = "surface_sam_dtx",
  891. + .acpi_match_table = surface_sam_dtx_match,
  892. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  893. + },
  894. +};
  895. +module_platform_driver(surface_sam_dtx);
  896. +
  897. +MODULE_AUTHOR("Maximilian Luz <luzmaximilian@gmail.com>");
  898. +MODULE_DESCRIPTION("Surface Detachment System (DTX) Driver for 5th Generation Surface Devices");
  899. +MODULE_LICENSE("GPL");
  900. diff --git a/drivers/platform/x86/surface_sam/surface_sam_hps.c b/drivers/platform/x86/surface_sam/surface_sam_hps.c
  901. new file mode 100644
  902. index 0000000000000..40f39f29113c5
  903. --- /dev/null
  904. +++ b/drivers/platform/x86/surface_sam/surface_sam_hps.c
  905. @@ -0,0 +1,1297 @@
  906. +// SPDX-License-Identifier: GPL-2.0-or-later
  907. +/*
  908. + * Surface dGPU hot-plug system driver.
  909. + * Supports explicit setting of the dGPU power-state on the Surface Book 2 and
  910. + * properly handles hot-plugging by detaching the base.
  911. + */
  912. +
  913. +#include <linux/acpi.h>
  914. +#include <linux/delay.h>
  915. +#include <linux/gpio.h>
  916. +#include <linux/kernel.h>
  917. +#include <linux/module.h>
  918. +#include <linux/mutex.h>
  919. +#include <linux/pci.h>
  920. +#include <linux/platform_device.h>
  921. +#include <linux/sysfs.h>
  922. +
  923. +#include "surface_sam_ssh.h"
  924. +#include "surface_sam_san.h"
  925. +
  926. +
  927. +// TODO: vgaswitcheroo integration
  928. +
  929. +
  930. +static void dbg_dump_drvsta(struct platform_device *pdev, const char *prefix);
  931. +
  932. +
  933. +#define SHPS_DSM_REVISION 1
  934. +#define SHPS_DSM_GPU_ADDRS 0x02
  935. +#define SHPS_DSM_GPU_POWER 0x05
  936. +static const guid_t SHPS_DSM_UUID =
  937. + GUID_INIT(0x5515a847, 0xed55, 0x4b27, 0x83, 0x52, 0xcd,
  938. + 0x32, 0x0e, 0x10, 0x36, 0x0a);
  939. +
  940. +
  941. +#define SAM_DGPU_TC 0x13
  942. +#define SAM_DGPU_CID_POWERON 0x02
  943. +
  944. +#define SAM_DTX_TC 0x11
  945. +#define SAM_DTX_CID_LATCH_LOCK 0x06
  946. +#define SAM_DTX_CID_LATCH_UNLOCK 0x07
  947. +#define ACPI_SGCP_NOTIFY_POWER_ON 0x81
  948. +
  949. +#define SHPS_DSM_GPU_ADDRS_RP "RP5_PCIE"
  950. +#define SHPS_DSM_GPU_ADDRS_DGPU "DGPU_PCIE"
  951. +#define SHPS_PCI_GPU_ADDR_RP "\\_SB.PCI0.RP13._ADR"
  952. +
  953. +static const struct acpi_gpio_params gpio_base_presence_int = { 0, 0, false };
  954. +static const struct acpi_gpio_params gpio_base_presence = { 1, 0, false };
  955. +static const struct acpi_gpio_params gpio_dgpu_power_int = { 2, 0, false };
  956. +static const struct acpi_gpio_params gpio_dgpu_power = { 3, 0, false };
  957. +static const struct acpi_gpio_params gpio_dgpu_presence_int = { 4, 0, false };
  958. +static const struct acpi_gpio_params gpio_dgpu_presence = { 5, 0, false };
  959. +
  960. +static const struct acpi_gpio_mapping shps_acpi_gpios[] = {
  961. + { "base_presence-int-gpio", &gpio_base_presence_int, 1 },
  962. + { "base_presence-gpio", &gpio_base_presence, 1 },
  963. + { "dgpu_power-int-gpio", &gpio_dgpu_power_int, 1 },
  964. + { "dgpu_power-gpio", &gpio_dgpu_power, 1 },
  965. + { "dgpu_presence-int-gpio", &gpio_dgpu_presence_int, 1 },
  966. + { "dgpu_presence-gpio", &gpio_dgpu_presence, 1 },
  967. + { },
  968. +};
  969. +
  970. +
  971. +enum shps_dgpu_power {
  972. + SHPS_DGPU_POWER_OFF = 0,
  973. + SHPS_DGPU_POWER_ON = 1,
  974. + SHPS_DGPU_POWER_UNKNOWN = 2,
  975. +};
  976. +
  977. +static const char *shps_dgpu_power_str(enum shps_dgpu_power power)
  978. +{
  979. + if (power == SHPS_DGPU_POWER_OFF)
  980. + return "off";
  981. + else if (power == SHPS_DGPU_POWER_ON)
  982. + return "on";
  983. + else if (power == SHPS_DGPU_POWER_UNKNOWN)
  984. + return "unknown";
  985. + else
  986. + return "<invalid>";
  987. +}
  988. +
  989. +enum shps_notification_method {
  990. + SHPS_NOTIFICATION_METHOD_SAN = 1,
  991. + SHPS_NOTIFICATION_METHOD_SGCP = 2
  992. +};
  993. +
  994. +struct shps_hardware_traits {
  995. + enum shps_notification_method notification_method;
  996. + const char *dgpu_rp_pci_address;
  997. +};
  998. +
  999. +struct shps_driver_data {
  1000. + struct mutex lock;
  1001. + struct pci_dev *dgpu_root_port;
  1002. + struct pci_saved_state *dgpu_root_port_state;
  1003. + struct gpio_desc *gpio_dgpu_power;
  1004. + struct gpio_desc *gpio_dgpu_presence;
  1005. + struct gpio_desc *gpio_base_presence;
  1006. + unsigned int irq_dgpu_presence;
  1007. + unsigned int irq_base_presence;
  1008. + unsigned long state;
  1009. + acpi_handle sgpc_handle;
  1010. + struct shps_hardware_traits hardware_traits;
  1011. +};
  1012. +
  1013. +struct shps_hardware_probe {
  1014. + const char *hardware_id;
  1015. + int generation;
  1016. + struct shps_hardware_traits *hardware_traits;
  1017. +};
  1018. +
  1019. +static struct shps_hardware_traits shps_gen1_hwtraits = {
  1020. + .notification_method = SHPS_NOTIFICATION_METHOD_SAN
  1021. +};
  1022. +
  1023. +static struct shps_hardware_traits shps_gen2_hwtraits = {
  1024. + .notification_method = SHPS_NOTIFICATION_METHOD_SGCP,
  1025. + .dgpu_rp_pci_address = SHPS_PCI_GPU_ADDR_RP
  1026. +};
  1027. +
  1028. +static const struct shps_hardware_probe shps_hardware_probe_match[] = {
  1029. + /* Surface Book 3 */
  1030. + { "MSHW0117", 2, &shps_gen2_hwtraits },
  1031. +
  1032. + /* Surface Book 2 (default, must be last entry) */
  1033. + { NULL, 1, &shps_gen1_hwtraits }
  1034. +};
  1035. +
  1036. +#define SHPS_STATE_BIT_PWRTGT 0 /* desired power state: 1 for on, 0 for off */
  1037. +#define SHPS_STATE_BIT_RPPWRON_SYNC 1 /* synchronous/requested power-up in progress */
  1038. +#define SHPS_STATE_BIT_WAKE_ENABLED 2 /* wakeup via base-presence GPIO enabled */
  1039. +
  1040. +
  1041. +#define SHPS_DGPU_PARAM_PERM 0644
  1042. +
  1043. +enum shps_dgpu_power_mp {
  1044. + SHPS_DGPU_MP_POWER_OFF = SHPS_DGPU_POWER_OFF,
  1045. + SHPS_DGPU_MP_POWER_ON = SHPS_DGPU_POWER_ON,
  1046. + SHPS_DGPU_MP_POWER_ASIS = -1,
  1047. +
  1048. + __SHPS_DGPU_MP_POWER_START = -1,
  1049. + __SHPS_DGPU_MP_POWER_END = 1,
  1050. +};
  1051. +
  1052. +static int param_dgpu_power_set(const char *val, const struct kernel_param *kp)
  1053. +{
  1054. + int power = SHPS_DGPU_MP_POWER_OFF;
  1055. + int status;
  1056. +
  1057. + status = kstrtoint(val, 0, &power);
  1058. + if (status)
  1059. + return status;
  1060. +
  1061. + if (power < __SHPS_DGPU_MP_POWER_START || power > __SHPS_DGPU_MP_POWER_END)
  1062. + return -EINVAL;
  1063. +
  1064. + return param_set_int(val, kp);
  1065. +}
  1066. +
  1067. +static const struct kernel_param_ops param_dgpu_power_ops = {
  1068. + .set = param_dgpu_power_set,
  1069. + .get = param_get_int,
  1070. +};
  1071. +
  1072. +static int param_dgpu_power_init = SHPS_DGPU_MP_POWER_OFF;
  1073. +static int param_dgpu_power_exit = SHPS_DGPU_MP_POWER_ON;
  1074. +static int param_dgpu_power_susp = SHPS_DGPU_MP_POWER_ASIS;
  1075. +static bool param_dtx_latch = true;
  1076. +
  1077. +module_param_cb(dgpu_power_init, &param_dgpu_power_ops, &param_dgpu_power_init, SHPS_DGPU_PARAM_PERM);
  1078. +module_param_cb(dgpu_power_exit, &param_dgpu_power_ops, &param_dgpu_power_exit, SHPS_DGPU_PARAM_PERM);
  1079. +module_param_cb(dgpu_power_susp, &param_dgpu_power_ops, &param_dgpu_power_susp, SHPS_DGPU_PARAM_PERM);
  1080. +module_param_named(dtx_latch, param_dtx_latch, bool, SHPS_DGPU_PARAM_PERM);
  1081. +
  1082. +MODULE_PARM_DESC(dgpu_power_init, "dGPU power state to be set on init (0: off / 1: on / 2: as-is, default: off)");
  1083. +MODULE_PARM_DESC(dgpu_power_exit, "dGPU power state to be set on exit (0: off / 1: on / 2: as-is, default: on)");
  1084. +MODULE_PARM_DESC(dgpu_power_susp, "dGPU power state to be set on exit (0: off / 1: on / 2: as-is, default: as-is)");
  1085. +MODULE_PARM_DESC(dtx_latch, "lock/unlock DTX base latch in accordance to power-state (Y/n)");
  1086. +
  1087. +static int dtx_cmd_simple(u8 cid)
  1088. +{
  1089. + struct surface_sam_ssh_rqst rqst = {
  1090. + .tc = SAM_DTX_TC,
  1091. + .cid = cid,
  1092. + .iid = 0x00,
  1093. + .chn = 0x01,
  1094. + .snc = 0x00,
  1095. + .cdl = 0x00,
  1096. + .pld = NULL,
  1097. + };
  1098. +
  1099. + return surface_sam_ssh_rqst(&rqst, NULL);
  1100. +}
  1101. +
  1102. +static inline int shps_dtx_latch_lock(void)
  1103. +{
  1104. + return dtx_cmd_simple(SAM_DTX_CID_LATCH_LOCK);
  1105. +}
  1106. +
  1107. +static inline int shps_dtx_latch_unlock(void)
  1108. +{
  1109. + return dtx_cmd_simple(SAM_DTX_CID_LATCH_UNLOCK);
  1110. +}
  1111. +
  1112. +static int shps_dgpu_dsm_get_pci_addr_from_adr(struct platform_device *pdev, const char *entry) {
  1113. + acpi_handle handle = ACPI_HANDLE(&pdev->dev);
  1114. + int status;
  1115. + struct acpi_object_list input;
  1116. + union acpi_object input_args[0];
  1117. + u64 device_addr;
  1118. + u8 bus, dev, fun;
  1119. +
  1120. + input.count = 0;
  1121. + input.pointer = input_args;
  1122. +
  1123. +
  1124. + status = acpi_evaluate_integer(handle, (acpi_string)entry, &input, &device_addr);
  1125. + if (status) {
  1126. + return -ENODEV;
  1127. + }
  1128. +
  1129. + bus = 0;
  1130. + dev = (device_addr & 0xFF0000) >> 16;
  1131. + fun = device_addr & 0xFF;
  1132. +
  1133. + dev_info(&pdev->dev, "found pci device at bus = %d, dev = %x, fun = %x\n",
  1134. + (u32)bus, (u32)dev, (u32)fun);
  1135. +
  1136. + return bus << 8 | PCI_DEVFN(dev, fun);
  1137. +}
  1138. +
  1139. +static int shps_dgpu_dsm_get_pci_addr_from_dsm(struct platform_device *pdev, const char *entry)
  1140. +{
  1141. + acpi_handle handle = ACPI_HANDLE(&pdev->dev);
  1142. + union acpi_object *result;
  1143. + union acpi_object *e0;
  1144. + union acpi_object *e1;
  1145. + union acpi_object *e2;
  1146. + u64 device_addr = 0;
  1147. + u8 bus, dev, fun;
  1148. + int i;
  1149. +
  1150. +
  1151. + result = acpi_evaluate_dsm_typed(handle, &SHPS_DSM_UUID, SHPS_DSM_REVISION,
  1152. + SHPS_DSM_GPU_ADDRS, NULL, ACPI_TYPE_PACKAGE);
  1153. +
  1154. + if (IS_ERR_OR_NULL(result))
  1155. + return result ? PTR_ERR(result) : -EIO;
  1156. +
  1157. + // three entries per device: name, address, <integer>
  1158. + for (i = 0; i + 2 < result->package.count; i += 3) {
  1159. + e0 = &result->package.elements[i];
  1160. + e1 = &result->package.elements[i + 1];
  1161. + e2 = &result->package.elements[i + 2];
  1162. +
  1163. + if (e0->type != ACPI_TYPE_STRING) {
  1164. + ACPI_FREE(result);
  1165. + return -EIO;
  1166. + }
  1167. +
  1168. + if (e1->type != ACPI_TYPE_INTEGER) {
  1169. + ACPI_FREE(result);
  1170. + return -EIO;
  1171. + }
  1172. +
  1173. + if (e2->type != ACPI_TYPE_INTEGER) {
  1174. + ACPI_FREE(result);
  1175. + return -EIO;
  1176. + }
  1177. +
  1178. + if (strncmp(e0->string.pointer, entry, 64) == 0)
  1179. + device_addr = e1->integer.value;
  1180. + }
  1181. +
  1182. + ACPI_FREE(result);
  1183. + if (device_addr == 0)
  1184. + return -ENODEV;
  1185. +
  1186. +
  1187. + // convert address
  1188. + bus = (device_addr & 0x0FF00000) >> 20;
  1189. + dev = (device_addr & 0x000F8000) >> 15;
  1190. + fun = (device_addr & 0x00007000) >> 12;
  1191. +
  1192. + return bus << 8 | PCI_DEVFN(dev, fun);
  1193. +}
  1194. +
  1195. +static struct pci_dev *shps_dgpu_dsm_get_pci_dev(struct platform_device *pdev)
  1196. +{
  1197. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1198. + struct pci_dev *dev;
  1199. + int addr;
  1200. +
  1201. +
  1202. + if (drvdata->hardware_traits.dgpu_rp_pci_address) {
  1203. + addr = shps_dgpu_dsm_get_pci_addr_from_adr(pdev, drvdata->hardware_traits.dgpu_rp_pci_address);
  1204. + } else {
  1205. + addr = shps_dgpu_dsm_get_pci_addr_from_dsm(pdev, SHPS_DSM_GPU_ADDRS_RP);
  1206. + }
  1207. +
  1208. + if (addr < 0)
  1209. + return ERR_PTR(addr);
  1210. +
  1211. + dev = pci_get_domain_bus_and_slot(0, (addr & 0xFF00) >> 8, addr & 0xFF);
  1212. + return dev ? dev : ERR_PTR(-ENODEV);
  1213. +}
  1214. +
  1215. +
  1216. +static int shps_dgpu_dsm_get_power_unlocked(struct platform_device *pdev)
  1217. +{
  1218. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1219. + struct gpio_desc *gpio = drvdata->gpio_dgpu_power;
  1220. + int status;
  1221. +
  1222. + status = gpiod_get_value_cansleep(gpio);
  1223. + if (status < 0)
  1224. + return status;
  1225. +
  1226. + return status == 0 ? SHPS_DGPU_POWER_OFF : SHPS_DGPU_POWER_ON;
  1227. +}
  1228. +
  1229. +static int shps_dgpu_dsm_get_power(struct platform_device *pdev)
  1230. +{
  1231. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1232. + int status;
  1233. +
  1234. + mutex_lock(&drvdata->lock);
  1235. + status = shps_dgpu_dsm_get_power_unlocked(pdev);
  1236. + mutex_unlock(&drvdata->lock);
  1237. +
  1238. + return status;
  1239. +}
  1240. +
  1241. +static int __shps_dgpu_dsm_set_power_unlocked(struct platform_device *pdev, enum shps_dgpu_power power)
  1242. +{
  1243. + acpi_handle handle = ACPI_HANDLE(&pdev->dev);
  1244. + union acpi_object *result;
  1245. + union acpi_object param;
  1246. +
  1247. + dev_info(&pdev->dev, "setting dGPU direct power to \'%s\'\n", shps_dgpu_power_str(power));
  1248. +
  1249. + param.type = ACPI_TYPE_INTEGER;
  1250. + param.integer.value = power == SHPS_DGPU_POWER_ON;
  1251. +
  1252. + result = acpi_evaluate_dsm_typed(handle, &SHPS_DSM_UUID, SHPS_DSM_REVISION,
  1253. + SHPS_DSM_GPU_POWER, &param, ACPI_TYPE_BUFFER);
  1254. +
  1255. + if (IS_ERR_OR_NULL(result))
  1256. + return result ? PTR_ERR(result) : -EIO;
  1257. +
  1258. + // check for the expected result
  1259. + if (result->buffer.length != 1 || result->buffer.pointer[0] != 0) {
  1260. + ACPI_FREE(result);
  1261. + return -EIO;
  1262. + }
  1263. +
  1264. + ACPI_FREE(result);
  1265. + return 0;
  1266. +}
  1267. +
  1268. +static int shps_dgpu_dsm_set_power_unlocked(struct platform_device *pdev, enum shps_dgpu_power power)
  1269. +{
  1270. + int status;
  1271. +
  1272. + if (power != SHPS_DGPU_POWER_ON && power != SHPS_DGPU_POWER_OFF)
  1273. + return -EINVAL;
  1274. +
  1275. + status = shps_dgpu_dsm_get_power_unlocked(pdev);
  1276. + if (status < 0)
  1277. + return status;
  1278. + if (status == power)
  1279. + return 0;
  1280. +
  1281. + return __shps_dgpu_dsm_set_power_unlocked(pdev, power);
  1282. +}
  1283. +
  1284. +static int shps_dgpu_dsm_set_power(struct platform_device *pdev, enum shps_dgpu_power power)
  1285. +{
  1286. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1287. + int status;
  1288. +
  1289. + mutex_lock(&drvdata->lock);
  1290. + status = shps_dgpu_dsm_set_power_unlocked(pdev, power);
  1291. + mutex_unlock(&drvdata->lock);
  1292. +
  1293. + return status;
  1294. +}
  1295. +
  1296. +
  1297. +static bool shps_rp_link_up(struct pci_dev *rp)
  1298. +{
  1299. + u16 lnksta = 0, sltsta = 0;
  1300. +
  1301. + pcie_capability_read_word(rp, PCI_EXP_LNKSTA, &lnksta);
  1302. + pcie_capability_read_word(rp, PCI_EXP_SLTSTA, &sltsta);
  1303. +
  1304. + return (lnksta & PCI_EXP_LNKSTA_DLLLA) || (sltsta & PCI_EXP_SLTSTA_PDS);
  1305. +}
  1306. +
  1307. +
  1308. +static int shps_dgpu_rp_get_power_unlocked(struct platform_device *pdev)
  1309. +{
  1310. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1311. + struct pci_dev *rp = drvdata->dgpu_root_port;
  1312. +
  1313. + if (rp->current_state == PCI_D3hot || rp->current_state == PCI_D3cold)
  1314. + return SHPS_DGPU_POWER_OFF;
  1315. + else if (rp->current_state == PCI_UNKNOWN || rp->current_state == PCI_POWER_ERROR)
  1316. + return SHPS_DGPU_POWER_UNKNOWN;
  1317. + else
  1318. + return SHPS_DGPU_POWER_ON;
  1319. +}
  1320. +
  1321. +static int shps_dgpu_rp_get_power(struct platform_device *pdev)
  1322. +{
  1323. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1324. + int status;
  1325. +
  1326. + mutex_lock(&drvdata->lock);
  1327. + status = shps_dgpu_rp_get_power_unlocked(pdev);
  1328. + mutex_unlock(&drvdata->lock);
  1329. +
  1330. + return status;
  1331. +}
  1332. +
  1333. +static int __shps_dgpu_rp_set_power_unlocked(struct platform_device *pdev, enum shps_dgpu_power power)
  1334. +{
  1335. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1336. + struct pci_dev *rp = drvdata->dgpu_root_port;
  1337. + int status, i;
  1338. +
  1339. + dev_info(&pdev->dev, "setting dGPU power state to \'%s\'\n", shps_dgpu_power_str(power));
  1340. +
  1341. + dbg_dump_drvsta(pdev, "__shps_dgpu_rp_set_power_unlocked.1");
  1342. + if (power == SHPS_DGPU_POWER_ON) {
  1343. + set_bit(SHPS_STATE_BIT_RPPWRON_SYNC, &drvdata->state);
  1344. + pci_set_power_state(rp, PCI_D0);
  1345. +
  1346. + if (drvdata->dgpu_root_port_state)
  1347. + pci_load_and_free_saved_state(rp, &drvdata->dgpu_root_port_state);
  1348. +
  1349. + pci_restore_state(rp);
  1350. +
  1351. + if (!pci_is_enabled(rp))
  1352. + pci_enable_device(rp);
  1353. +
  1354. + pci_set_master(rp);
  1355. + clear_bit(SHPS_STATE_BIT_RPPWRON_SYNC, &drvdata->state);
  1356. +
  1357. + set_bit(SHPS_STATE_BIT_PWRTGT, &drvdata->state);
  1358. + } else {
  1359. + if (!drvdata->dgpu_root_port_state) {
  1360. + pci_save_state(rp);
  1361. + drvdata->dgpu_root_port_state = pci_store_saved_state(rp);
  1362. + }
  1363. +
  1364. + /*
  1365. + * To properly update the hot-plug system we need to "remove" the dGPU
  1366. + * before disabling it and sending it to D3cold. Following this, we
  1367. + * need to wait for the link and slot status to actually change.
  1368. + */
  1369. + status = shps_dgpu_dsm_set_power_unlocked(pdev, SHPS_DGPU_POWER_OFF);
  1370. + if (status)
  1371. + return status;
  1372. +
  1373. + for (i = 0; i < 20 && shps_rp_link_up(rp); i++)
  1374. + msleep(50);
  1375. +
  1376. + if (shps_rp_link_up(rp))
  1377. + dev_err(&pdev->dev, "dGPU removal via DSM timed out\n");
  1378. +
  1379. + pci_clear_master(rp);
  1380. +
  1381. + if (pci_is_enabled(rp))
  1382. + pci_disable_device(rp);
  1383. +
  1384. + pci_set_power_state(rp, PCI_D3cold);
  1385. +
  1386. + clear_bit(SHPS_STATE_BIT_PWRTGT, &drvdata->state);
  1387. + }
  1388. + dbg_dump_drvsta(pdev, "__shps_dgpu_rp_set_power_unlocked.2");
  1389. +
  1390. + return 0;
  1391. +}
  1392. +
  1393. +static int shps_dgpu_rp_set_power_unlocked(struct platform_device *pdev, enum shps_dgpu_power power)
  1394. +{
  1395. + int status;
  1396. +
  1397. + if (power != SHPS_DGPU_POWER_ON && power != SHPS_DGPU_POWER_OFF)
  1398. + return -EINVAL;
  1399. +
  1400. + status = shps_dgpu_rp_get_power_unlocked(pdev);
  1401. + if (status < 0)
  1402. + return status;
  1403. + if (status == power)
  1404. + return 0;
  1405. +
  1406. + return __shps_dgpu_rp_set_power_unlocked(pdev, power);
  1407. +}
  1408. +
  1409. +static int shps_dgpu_rp_set_power(struct platform_device *pdev, enum shps_dgpu_power power)
  1410. +{
  1411. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1412. + int status;
  1413. +
  1414. + mutex_lock(&drvdata->lock);
  1415. + status = shps_dgpu_rp_set_power_unlocked(pdev, power);
  1416. + mutex_unlock(&drvdata->lock);
  1417. +
  1418. + return status;
  1419. +}
  1420. +
  1421. +
  1422. +static int shps_dgpu_set_power(struct platform_device *pdev, enum shps_dgpu_power power)
  1423. +{
  1424. + int status;
  1425. +
  1426. + if (!param_dtx_latch)
  1427. + return shps_dgpu_rp_set_power(pdev, power);
  1428. +
  1429. + if (power == SHPS_DGPU_POWER_ON) {
  1430. + status = shps_dtx_latch_lock();
  1431. + if (status)
  1432. + return status;
  1433. +
  1434. + status = shps_dgpu_rp_set_power(pdev, power);
  1435. + if (status)
  1436. + shps_dtx_latch_unlock();
  1437. +
  1438. + } else {
  1439. + status = shps_dgpu_rp_set_power(pdev, power);
  1440. + if (status)
  1441. + return status;
  1442. +
  1443. + status = shps_dtx_latch_unlock();
  1444. + }
  1445. +
  1446. + return status;
  1447. +}
  1448. +
  1449. +
  1450. +static int shps_dgpu_is_present(struct platform_device *pdev)
  1451. +{
  1452. + struct shps_driver_data *drvdata;
  1453. +
  1454. + drvdata = platform_get_drvdata(pdev);
  1455. + return gpiod_get_value_cansleep(drvdata->gpio_dgpu_presence);
  1456. +}
  1457. +
  1458. +
  1459. +static ssize_t dgpu_power_show(struct device *dev, struct device_attribute *attr, char *data)
  1460. +{
  1461. + struct platform_device *pdev = to_platform_device(dev);
  1462. + int power = shps_dgpu_rp_get_power(pdev);
  1463. +
  1464. + if (power < 0)
  1465. + return power;
  1466. +
  1467. + return sprintf(data, "%s\n", shps_dgpu_power_str(power));
  1468. +}
  1469. +
  1470. +static ssize_t dgpu_power_store(struct device *dev, struct device_attribute *attr,
  1471. + const char *data, size_t count)
  1472. +{
  1473. + struct platform_device *pdev = to_platform_device(dev);
  1474. + enum shps_dgpu_power power;
  1475. + bool b = false;
  1476. + int status;
  1477. +
  1478. + status = kstrtobool(data, &b);
  1479. + if (status)
  1480. + return status;
  1481. +
  1482. + status = shps_dgpu_is_present(pdev);
  1483. + if (status <= 0)
  1484. + return status < 0 ? status : -EPERM;
  1485. +
  1486. + power = b ? SHPS_DGPU_POWER_ON : SHPS_DGPU_POWER_OFF;
  1487. + status = shps_dgpu_set_power(pdev, power);
  1488. +
  1489. + return status < 0 ? status : count;
  1490. +}
  1491. +
  1492. +static ssize_t dgpu_power_dsm_show(struct device *dev, struct device_attribute *attr, char *data)
  1493. +{
  1494. + struct platform_device *pdev = to_platform_device(dev);
  1495. + int power = shps_dgpu_dsm_get_power(pdev);
  1496. +
  1497. + if (power < 0)
  1498. + return power;
  1499. +
  1500. + return sprintf(data, "%s\n", shps_dgpu_power_str(power));
  1501. +}
  1502. +
  1503. +static ssize_t dgpu_power_dsm_store(struct device *dev, struct device_attribute *attr,
  1504. + const char *data, size_t count)
  1505. +{
  1506. + struct platform_device *pdev = to_platform_device(dev);
  1507. + enum shps_dgpu_power power;
  1508. + bool b = false;
  1509. + int status;
  1510. +
  1511. + status = kstrtobool(data, &b);
  1512. + if (status)
  1513. + return status;
  1514. +
  1515. + status = shps_dgpu_is_present(pdev);
  1516. + if (status <= 0)
  1517. + return status < 0 ? status : -EPERM;
  1518. +
  1519. + power = b ? SHPS_DGPU_POWER_ON : SHPS_DGPU_POWER_OFF;
  1520. + status = shps_dgpu_dsm_set_power(pdev, power);
  1521. +
  1522. + return status < 0 ? status : count;
  1523. +}
  1524. +
  1525. +static DEVICE_ATTR_RW(dgpu_power);
  1526. +static DEVICE_ATTR_RW(dgpu_power_dsm);
  1527. +
  1528. +static struct attribute *shps_power_attrs[] = {
  1529. + &dev_attr_dgpu_power.attr,
  1530. + &dev_attr_dgpu_power_dsm.attr,
  1531. + NULL,
  1532. +};
  1533. +ATTRIBUTE_GROUPS(shps_power);
  1534. +
  1535. +
  1536. +static void dbg_dump_power_states(struct platform_device *pdev, const char *prefix)
  1537. +{
  1538. + enum shps_dgpu_power power_dsm;
  1539. + enum shps_dgpu_power power_rp;
  1540. + int status;
  1541. +
  1542. + status = shps_dgpu_rp_get_power_unlocked(pdev);
  1543. + if (status < 0)
  1544. + dev_err(&pdev->dev, "%s: failed to get root-port power state: %d\n", prefix, status);
  1545. + power_rp = status;
  1546. +
  1547. + status = shps_dgpu_rp_get_power_unlocked(pdev);
  1548. + if (status < 0)
  1549. + dev_err(&pdev->dev, "%s: failed to get direct power state: %d\n", prefix, status);
  1550. + power_dsm = status;
  1551. +
  1552. + dev_dbg(&pdev->dev, "%s: root-port power state: %d\n", prefix, power_rp);
  1553. + dev_dbg(&pdev->dev, "%s: direct power state: %d\n", prefix, power_dsm);
  1554. +}
  1555. +
  1556. +static void dbg_dump_pciesta(struct platform_device *pdev, const char *prefix)
  1557. +{
  1558. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1559. + struct pci_dev *rp = drvdata->dgpu_root_port;
  1560. + u16 lnksta, lnksta2, sltsta, sltsta2;
  1561. +
  1562. + pcie_capability_read_word(rp, PCI_EXP_LNKSTA, &lnksta);
  1563. + pcie_capability_read_word(rp, PCI_EXP_LNKSTA2, &lnksta2);
  1564. + pcie_capability_read_word(rp, PCI_EXP_SLTSTA, &sltsta);
  1565. + pcie_capability_read_word(rp, PCI_EXP_SLTSTA2, &sltsta2);
  1566. +
  1567. + dev_dbg(&pdev->dev, "%s: LNKSTA: 0x%04x\n", prefix, lnksta);
  1568. + dev_dbg(&pdev->dev, "%s: LNKSTA2: 0x%04x\n", prefix, lnksta2);
  1569. + dev_dbg(&pdev->dev, "%s: SLTSTA: 0x%04x\n", prefix, sltsta);
  1570. + dev_dbg(&pdev->dev, "%s: SLTSTA2: 0x%04x\n", prefix, sltsta2);
  1571. +}
  1572. +
  1573. +static void dbg_dump_drvsta(struct platform_device *pdev, const char *prefix)
  1574. +{
  1575. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1576. + struct pci_dev *rp = drvdata->dgpu_root_port;
  1577. +
  1578. + dev_dbg(&pdev->dev, "%s: RP power: %d\n", prefix, rp->current_state);
  1579. + dev_dbg(&pdev->dev, "%s: RP state saved: %d\n", prefix, rp->state_saved);
  1580. + dev_dbg(&pdev->dev, "%s: RP state stored: %d\n", prefix, !!drvdata->dgpu_root_port_state);
  1581. + dev_dbg(&pdev->dev, "%s: RP enabled: %d\n", prefix, atomic_read(&rp->enable_cnt));
  1582. + dev_dbg(&pdev->dev, "%s: RP mastered: %d\n", prefix, rp->is_busmaster);
  1583. +}
  1584. +
  1585. +static int shps_pm_prepare(struct device *dev)
  1586. +{
  1587. + struct platform_device *pdev = to_platform_device(dev);
  1588. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1589. + bool pwrtgt;
  1590. + int status = 0;
  1591. +
  1592. + dbg_dump_power_states(pdev, "shps_pm_prepare");
  1593. +
  1594. + if (param_dgpu_power_susp != SHPS_DGPU_MP_POWER_ASIS) {
  1595. + pwrtgt = test_bit(SHPS_STATE_BIT_PWRTGT, &drvdata->state);
  1596. +
  1597. + status = shps_dgpu_set_power(pdev, param_dgpu_power_susp);
  1598. + if (status) {
  1599. + dev_err(&pdev->dev, "failed to power %s dGPU: %d\n",
  1600. + param_dgpu_power_susp == SHPS_DGPU_MP_POWER_OFF ? "off" : "on",
  1601. + status);
  1602. + return status;
  1603. + }
  1604. +
  1605. + if (pwrtgt)
  1606. + set_bit(SHPS_STATE_BIT_PWRTGT, &drvdata->state);
  1607. + else
  1608. + clear_bit(SHPS_STATE_BIT_PWRTGT, &drvdata->state);
  1609. + }
  1610. +
  1611. + return 0;
  1612. +}
  1613. +
  1614. +static void shps_pm_complete(struct device *dev)
  1615. +{
  1616. + struct platform_device *pdev = to_platform_device(dev);
  1617. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1618. + int status;
  1619. +
  1620. + dbg_dump_power_states(pdev, "shps_pm_complete");
  1621. + dbg_dump_pciesta(pdev, "shps_pm_complete");
  1622. + dbg_dump_drvsta(pdev, "shps_pm_complete.1");
  1623. +
  1624. + // update power target, dGPU may have been detached while suspended
  1625. + status = shps_dgpu_is_present(pdev);
  1626. + if (status < 0) {
  1627. + dev_err(&pdev->dev, "failed to get dGPU presence: %d\n", status);
  1628. + return;
  1629. + } else if (status == 0) {
  1630. + clear_bit(SHPS_STATE_BIT_PWRTGT, &drvdata->state);
  1631. + }
  1632. +
  1633. + /*
  1634. + * During resume, the PCIe core will power on the root-port, which in turn
  1635. + * will power on the dGPU. Most of the state synchronization is already
  1636. + * handled via the SAN RQSG handler, so it is in a fully consistent
  1637. + * on-state here. If requested, turn it off here.
  1638. + *
  1639. + * As there seem to be some synchronization issues turning off the dGPU
  1640. + * directly after the power-on SAN RQSG notification during the resume
  1641. + * process, let's do this here.
  1642. + *
  1643. + * TODO/FIXME:
  1644. + * This does not combat unhandled power-ons when the device is not fully
  1645. + * resumed, i.e. re-suspended before shps_pm_complete is called. Those
  1646. + * should normally not be an issue, but the dGPU does get hot even though
  1647. + * it is suspended, so ideally we want to keep it off.
  1648. + */
  1649. + if (!test_bit(SHPS_STATE_BIT_PWRTGT, &drvdata->state)) {
  1650. + status = shps_dgpu_set_power(pdev, SHPS_DGPU_POWER_OFF);
  1651. + if (status)
  1652. + dev_err(&pdev->dev, "failed to power-off dGPU: %d\n", status);
  1653. + }
  1654. +
  1655. + dbg_dump_drvsta(pdev, "shps_pm_complete.2");
  1656. +}
  1657. +
  1658. +static int shps_pm_suspend(struct device *dev)
  1659. +{
  1660. + struct platform_device *pdev = to_platform_device(dev);
  1661. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1662. + int status;
  1663. +
  1664. + if (device_may_wakeup(dev)) {
  1665. + status = enable_irq_wake(drvdata->irq_base_presence);
  1666. + if (status)
  1667. + return status;
  1668. +
  1669. + set_bit(SHPS_STATE_BIT_WAKE_ENABLED, &drvdata->state);
  1670. + }
  1671. +
  1672. + return 0;
  1673. +}
  1674. +
  1675. +static int shps_pm_resume(struct device *dev)
  1676. +{
  1677. + struct platform_device *pdev = to_platform_device(dev);
  1678. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1679. + int status = 0;
  1680. +
  1681. + if (test_and_clear_bit(SHPS_STATE_BIT_WAKE_ENABLED, &drvdata->state))
  1682. + status = disable_irq_wake(drvdata->irq_base_presence);
  1683. +
  1684. + return status;
  1685. +}
  1686. +
  1687. +static void shps_shutdown(struct platform_device *pdev)
  1688. +{
  1689. + int status;
  1690. +
  1691. + /*
  1692. + * Turn on dGPU before shutting down. This allows the core drivers to
  1693. + * properly shut down the device. If we don't do this, the pcieport driver
  1694. + * will complain that the device has already been disabled.
  1695. + */
  1696. + status = shps_dgpu_set_power(pdev, SHPS_DGPU_POWER_ON);
  1697. + if (status)
  1698. + dev_err(&pdev->dev, "failed to turn on dGPU: %d\n", status);
  1699. +}
  1700. +
  1701. +static int shps_dgpu_detached(struct platform_device *pdev)
  1702. +{
  1703. + dbg_dump_power_states(pdev, "shps_dgpu_detached");
  1704. + return shps_dgpu_set_power(pdev, SHPS_DGPU_POWER_OFF);
  1705. +}
  1706. +
  1707. +static int shps_dgpu_attached(struct platform_device *pdev)
  1708. +{
  1709. + dbg_dump_power_states(pdev, "shps_dgpu_attached");
  1710. + return 0;
  1711. +}
  1712. +
  1713. +static int shps_dgpu_powered_on(struct platform_device *pdev)
  1714. +{
  1715. + /*
  1716. + * This function gets called directly after a power-state transition of
  1717. + * the dGPU root port out of D3cold state, indicating a power-on of the
  1718. + * dGPU. Specifically, this function is called from the RQSG handler of
  1719. + * SAN, invoked by the ACPI _ON method of the dGPU root port. This means
  1720. + * that this function is run inside `pci_set_power_state(rp, ...)`
  1721. + * syncrhonously and thus returns before the `pci_set_power_state` call
  1722. + * does.
  1723. + *
  1724. + * `pci_set_power_state` may either be called by us or when the PCI
  1725. + * subsystem decides to power up the root port (e.g. during resume). Thus
  1726. + * we should use this function to ensure that the dGPU and root port
  1727. + * states are consistent when an unexpected power-up is encountered.
  1728. + */
  1729. +
  1730. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1731. + struct pci_dev *rp = drvdata->dgpu_root_port;
  1732. + int status;
  1733. +
  1734. + dbg_dump_drvsta(pdev, "shps_dgpu_powered_on.1");
  1735. +
  1736. + // if we caused the root port to power-on, return
  1737. + if (test_bit(SHPS_STATE_BIT_RPPWRON_SYNC, &drvdata->state))
  1738. + return 0;
  1739. +
  1740. + // if dGPU is not present, force power-target to off and return
  1741. + status = shps_dgpu_is_present(pdev);
  1742. + if (status == 0)
  1743. + clear_bit(SHPS_STATE_BIT_PWRTGT, &drvdata->state);
  1744. + if (status <= 0)
  1745. + return status;
  1746. +
  1747. + mutex_lock(&drvdata->lock);
  1748. +
  1749. + dbg_dump_power_states(pdev, "shps_dgpu_powered_on.1");
  1750. + dbg_dump_pciesta(pdev, "shps_dgpu_powered_on.1");
  1751. + if (drvdata->dgpu_root_port_state)
  1752. + pci_load_and_free_saved_state(rp, &drvdata->dgpu_root_port_state);
  1753. + pci_restore_state(rp);
  1754. + if (!pci_is_enabled(rp))
  1755. + pci_enable_device(rp);
  1756. + pci_set_master(rp);
  1757. + dbg_dump_drvsta(pdev, "shps_dgpu_powered_on.2");
  1758. + dbg_dump_power_states(pdev, "shps_dgpu_powered_on.2");
  1759. + dbg_dump_pciesta(pdev, "shps_dgpu_powered_on.2");
  1760. +
  1761. + mutex_unlock(&drvdata->lock);
  1762. +
  1763. + if (!test_bit(SHPS_STATE_BIT_PWRTGT, &drvdata->state)) {
  1764. + dev_warn(&pdev->dev, "unexpected dGPU power-on detected\n");
  1765. + // TODO: schedule state re-check and update
  1766. + }
  1767. +
  1768. + return 0;
  1769. +}
  1770. +
  1771. +static int shps_dgpu_handle_rqsg(struct surface_sam_san_rqsg *rqsg, void *data)
  1772. +{
  1773. + struct platform_device *pdev = data;
  1774. +
  1775. + if (rqsg->tc == SAM_DGPU_TC && rqsg->cid == SAM_DGPU_CID_POWERON)
  1776. + return shps_dgpu_powered_on(pdev);
  1777. +
  1778. + dev_warn(&pdev->dev, "unimplemented dGPU request: RQSG(0x%02x, 0x%02x, 0x%02x)\n",
  1779. + rqsg->tc, rqsg->cid, rqsg->iid);
  1780. + return 0;
  1781. +}
  1782. +
  1783. +static irqreturn_t shps_dgpu_presence_irq(int irq, void *data)
  1784. +{
  1785. + struct platform_device *pdev = data;
  1786. + bool dgpu_present;
  1787. + int status;
  1788. +
  1789. + status = shps_dgpu_is_present(pdev);
  1790. + if (status < 0) {
  1791. + dev_err(&pdev->dev, "failed to check physical dGPU presence: %d\n", status);
  1792. + return IRQ_HANDLED;
  1793. + }
  1794. +
  1795. + dgpu_present = status != 0;
  1796. + dev_info(&pdev->dev, "dGPU physically %s\n", dgpu_present ? "attached" : "detached");
  1797. +
  1798. + if (dgpu_present)
  1799. + status = shps_dgpu_attached(pdev);
  1800. + else
  1801. + status = shps_dgpu_detached(pdev);
  1802. +
  1803. + if (status)
  1804. + dev_err(&pdev->dev, "error handling dGPU interrupt: %d\n", status);
  1805. +
  1806. + return IRQ_HANDLED;
  1807. +}
  1808. +
  1809. +static irqreturn_t shps_base_presence_irq(int irq, void *data)
  1810. +{
  1811. + return IRQ_HANDLED; // nothing to do, just wake
  1812. +}
  1813. +
  1814. +
  1815. +static int shps_gpios_setup(struct platform_device *pdev)
  1816. +{
  1817. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1818. + struct gpio_desc *gpio_dgpu_power;
  1819. + struct gpio_desc *gpio_dgpu_presence;
  1820. + struct gpio_desc *gpio_base_presence;
  1821. + int status;
  1822. +
  1823. + // get GPIOs
  1824. + gpio_dgpu_power = devm_gpiod_get(&pdev->dev, "dgpu_power", GPIOD_IN);
  1825. + if (IS_ERR(gpio_dgpu_power)) {
  1826. + status = PTR_ERR(gpio_dgpu_power);
  1827. + goto err_out;
  1828. + }
  1829. +
  1830. + gpio_dgpu_presence = devm_gpiod_get(&pdev->dev, "dgpu_presence", GPIOD_IN);
  1831. + if (IS_ERR(gpio_dgpu_presence)) {
  1832. + status = PTR_ERR(gpio_dgpu_presence);
  1833. + goto err_out;
  1834. + }
  1835. +
  1836. + gpio_base_presence = devm_gpiod_get(&pdev->dev, "base_presence", GPIOD_IN);
  1837. + if (IS_ERR(gpio_base_presence)) {
  1838. + status = PTR_ERR(gpio_base_presence);
  1839. + goto err_out;
  1840. + }
  1841. +
  1842. + // export GPIOs
  1843. + status = gpiod_export(gpio_dgpu_power, false);
  1844. + if (status)
  1845. + goto err_out;
  1846. +
  1847. + status = gpiod_export(gpio_dgpu_presence, false);
  1848. + if (status)
  1849. + goto err_export_dgpu_presence;
  1850. +
  1851. + status = gpiod_export(gpio_base_presence, false);
  1852. + if (status)
  1853. + goto err_export_base_presence;
  1854. +
  1855. + // create sysfs links
  1856. + status = gpiod_export_link(&pdev->dev, "gpio-dgpu_power", gpio_dgpu_power);
  1857. + if (status)
  1858. + goto err_link_dgpu_power;
  1859. +
  1860. + status = gpiod_export_link(&pdev->dev, "gpio-dgpu_presence", gpio_dgpu_presence);
  1861. + if (status)
  1862. + goto err_link_dgpu_presence;
  1863. +
  1864. + status = gpiod_export_link(&pdev->dev, "gpio-base_presence", gpio_base_presence);
  1865. + if (status)
  1866. + goto err_link_base_presence;
  1867. +
  1868. + drvdata->gpio_dgpu_power = gpio_dgpu_power;
  1869. + drvdata->gpio_dgpu_presence = gpio_dgpu_presence;
  1870. + drvdata->gpio_base_presence = gpio_base_presence;
  1871. + return 0;
  1872. +
  1873. +err_link_base_presence:
  1874. + sysfs_remove_link(&pdev->dev.kobj, "gpio-dgpu_presence");
  1875. +err_link_dgpu_presence:
  1876. + sysfs_remove_link(&pdev->dev.kobj, "gpio-dgpu_power");
  1877. +err_link_dgpu_power:
  1878. + gpiod_unexport(gpio_base_presence);
  1879. +err_export_base_presence:
  1880. + gpiod_unexport(gpio_dgpu_presence);
  1881. +err_export_dgpu_presence:
  1882. + gpiod_unexport(gpio_dgpu_power);
  1883. +err_out:
  1884. + return status;
  1885. +}
  1886. +
  1887. +static void shps_gpios_remove(struct platform_device *pdev)
  1888. +{
  1889. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1890. +
  1891. + sysfs_remove_link(&pdev->dev.kobj, "gpio-base_presence");
  1892. + sysfs_remove_link(&pdev->dev.kobj, "gpio-dgpu_presence");
  1893. + sysfs_remove_link(&pdev->dev.kobj, "gpio-dgpu_power");
  1894. + gpiod_unexport(drvdata->gpio_base_presence);
  1895. + gpiod_unexport(drvdata->gpio_dgpu_presence);
  1896. + gpiod_unexport(drvdata->gpio_dgpu_power);
  1897. +}
  1898. +
  1899. +static int shps_gpios_setup_irq(struct platform_device *pdev)
  1900. +{
  1901. + const int irqf_dgpu = IRQF_SHARED | IRQF_ONESHOT | IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING;
  1902. + const int irqf_base = IRQF_SHARED;
  1903. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1904. + int status;
  1905. +
  1906. + status = gpiod_to_irq(drvdata->gpio_base_presence);
  1907. + if (status < 0)
  1908. + return status;
  1909. + drvdata->irq_base_presence = status;
  1910. +
  1911. + status = gpiod_to_irq(drvdata->gpio_dgpu_presence);
  1912. + if (status < 0)
  1913. + return status;
  1914. + drvdata->irq_dgpu_presence = status;
  1915. +
  1916. + status = request_irq(drvdata->irq_base_presence,
  1917. + shps_base_presence_irq, irqf_base,
  1918. + "shps_base_presence_irq", pdev);
  1919. + if (status) {
  1920. + dev_err(&pdev->dev, "base irq failed: %d\n", status);
  1921. + return status;
  1922. + }
  1923. +
  1924. + status = request_threaded_irq(drvdata->irq_dgpu_presence,
  1925. + NULL, shps_dgpu_presence_irq, irqf_dgpu,
  1926. + "shps_dgpu_presence_irq", pdev);
  1927. + if (status) {
  1928. + free_irq(drvdata->irq_base_presence, pdev);
  1929. + return status;
  1930. + }
  1931. +
  1932. + return 0;
  1933. +}
  1934. +
  1935. +static void shps_gpios_remove_irq(struct platform_device *pdev)
  1936. +{
  1937. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1938. +
  1939. + free_irq(drvdata->irq_base_presence, pdev);
  1940. + free_irq(drvdata->irq_dgpu_presence, pdev);
  1941. +}
  1942. +
  1943. +static void shps_sgcp_notify(acpi_handle device, u32 value, void *context) {
  1944. + struct platform_device *pdev = context;
  1945. + switch (value) {
  1946. + case ACPI_SGCP_NOTIFY_POWER_ON:
  1947. + shps_dgpu_powered_on(pdev);
  1948. + }
  1949. +}
  1950. +
  1951. +static int shps_start_sgcp_notification(struct platform_device *pdev, acpi_handle *sgpc_handle) {
  1952. + acpi_handle handle;
  1953. + int status;
  1954. +
  1955. + status = acpi_get_handle(NULL, "\\_SB.SGPC", &handle);
  1956. + if (status) {
  1957. + dev_err(&pdev->dev, "error in get_handle %d\n", status);
  1958. + return status;
  1959. + }
  1960. +
  1961. + status = acpi_install_notify_handler(handle, ACPI_DEVICE_NOTIFY, shps_sgcp_notify, pdev);
  1962. + if (status) {
  1963. + dev_err(&pdev->dev, "error in install notify %d\n", status);
  1964. + *sgpc_handle = NULL;
  1965. + return status;
  1966. + }
  1967. +
  1968. + *sgpc_handle = handle;
  1969. + return 0;
  1970. +}
  1971. +
  1972. +static void shps_remove_sgcp_notification(struct platform_device *pdev) {
  1973. + int status;
  1974. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1975. +
  1976. + if (drvdata->sgpc_handle) {
  1977. + status = acpi_remove_notify_handler(drvdata->sgpc_handle, ACPI_DEVICE_NOTIFY, shps_sgcp_notify);
  1978. + if (status) {
  1979. + dev_err(&pdev->dev, "failed to remove notify handler: %d\n", status);
  1980. + }
  1981. + }
  1982. +}
  1983. +
  1984. +static struct shps_hardware_traits shps_detect_hardware_traits(struct platform_device *pdev) {
  1985. + const struct shps_hardware_probe *p;
  1986. +
  1987. + for (p = shps_hardware_probe_match; p->hardware_id; ++p) {
  1988. + if (acpi_dev_present(p->hardware_id, NULL, -1)) {
  1989. + break;
  1990. + }
  1991. + }
  1992. +
  1993. + dev_info(&pdev->dev,
  1994. + "shps_detect_hardware_traits found device %s, generation %d\n",
  1995. + p->hardware_id ? p->hardware_id : "SAN (default)",
  1996. + p->generation);
  1997. +
  1998. + return *p->hardware_traits;
  1999. +}
  2000. +
  2001. +static int shps_probe(struct platform_device *pdev)
  2002. +{
  2003. + struct acpi_device *shps_dev = ACPI_COMPANION(&pdev->dev);
  2004. + struct shps_driver_data *drvdata;
  2005. + struct device_link *link;
  2006. + int power, status;
  2007. + struct shps_hardware_traits detected_traits;
  2008. +
  2009. + if (gpiod_count(&pdev->dev, NULL) < 0) {
  2010. + dev_err(&pdev->dev, "gpiod_count returned < 0\n");
  2011. + return -ENODEV;
  2012. + }
  2013. +
  2014. + // link to SSH
  2015. + status = surface_sam_ssh_consumer_register(&pdev->dev);
  2016. + if (status) {
  2017. + return status == -ENXIO ? -EPROBE_DEFER : status;
  2018. + }
  2019. +
  2020. + // detect what kind of hardware we're running
  2021. + detected_traits = shps_detect_hardware_traits(pdev);
  2022. +
  2023. + if (detected_traits.notification_method == SHPS_NOTIFICATION_METHOD_SAN) {
  2024. + // link to SAN
  2025. + status = surface_sam_san_consumer_register(&pdev->dev, 0);
  2026. + if (status) {
  2027. + dev_err(&pdev->dev, "failed to register with san consumer: %d\n", status);
  2028. + return status == -ENXIO ? -EPROBE_DEFER : status;
  2029. + }
  2030. + }
  2031. +
  2032. + status = acpi_dev_add_driver_gpios(shps_dev, shps_acpi_gpios);
  2033. + if (status) {
  2034. + dev_err(&pdev->dev, "failed to add gpios: %d\n", status);
  2035. + return status;
  2036. + }
  2037. +
  2038. + drvdata = kzalloc(sizeof(struct shps_driver_data), GFP_KERNEL);
  2039. + if (!drvdata) {
  2040. + status = -ENOMEM;
  2041. + goto err_drvdata;
  2042. + }
  2043. + mutex_init(&drvdata->lock);
  2044. + platform_set_drvdata(pdev, drvdata);
  2045. +
  2046. + drvdata->hardware_traits = detected_traits;
  2047. +
  2048. + drvdata->dgpu_root_port = shps_dgpu_dsm_get_pci_dev(pdev);
  2049. + if (IS_ERR(drvdata->dgpu_root_port)) {
  2050. + status = PTR_ERR(drvdata->dgpu_root_port);
  2051. + dev_err(&pdev->dev, "failed to get pci dev: %d\n", status);
  2052. + goto err_rp_lookup;
  2053. + }
  2054. +
  2055. + status = shps_gpios_setup(pdev);
  2056. + if (status) {
  2057. + dev_err(&pdev->dev, "unable to set up gpios, %d\n", status);
  2058. + goto err_gpio;
  2059. + }
  2060. +
  2061. + status = shps_gpios_setup_irq(pdev);
  2062. + if (status) {
  2063. + dev_err(&pdev->dev, "unable to set up irqs %d\n", status);
  2064. + goto err_gpio_irqs;
  2065. + }
  2066. +
  2067. + status = device_add_groups(&pdev->dev, shps_power_groups);
  2068. + if (status)
  2069. + goto err_devattr;
  2070. +
  2071. + link = device_link_add(&pdev->dev, &drvdata->dgpu_root_port->dev,
  2072. + DL_FLAG_PM_RUNTIME | DL_FLAG_AUTOREMOVE_CONSUMER);
  2073. + if (!link)
  2074. + goto err_devlink;
  2075. +
  2076. + if (detected_traits.notification_method == SHPS_NOTIFICATION_METHOD_SAN) {
  2077. + status = surface_sam_san_set_rqsg_handler(shps_dgpu_handle_rqsg, pdev);
  2078. + if (status) {
  2079. + dev_err(&pdev->dev, "unable to set SAN notification handler (%d)\n", status);
  2080. + goto err_devlink;
  2081. + }
  2082. + } else if (detected_traits.notification_method == SHPS_NOTIFICATION_METHOD_SGCP) {
  2083. + status = shps_start_sgcp_notification(pdev, &drvdata->sgpc_handle);
  2084. + if (status) {
  2085. + dev_err(&pdev->dev, "unable to install SGCP notification handler (%d)\n", status);
  2086. + goto err_devlink;
  2087. + }
  2088. + }
  2089. +
  2090. + // if dGPU is not present turn-off root-port, else obey module param
  2091. + status = shps_dgpu_is_present(pdev);
  2092. + if (status < 0)
  2093. + goto err_post_notification;
  2094. +
  2095. + power = status == 0 ? SHPS_DGPU_POWER_OFF : param_dgpu_power_init;
  2096. + if (power != SHPS_DGPU_MP_POWER_ASIS) {
  2097. + status = shps_dgpu_set_power(pdev, power);
  2098. + if (status)
  2099. + goto err_post_notification;
  2100. + }
  2101. +
  2102. + // initialize power target
  2103. + status = shps_dgpu_rp_get_power(pdev);
  2104. + if (status < 0)
  2105. + goto err_pwrtgt;
  2106. +
  2107. + if (status)
  2108. + set_bit(SHPS_STATE_BIT_PWRTGT, &drvdata->state);
  2109. + else
  2110. + clear_bit(SHPS_STATE_BIT_PWRTGT, &drvdata->state);
  2111. +
  2112. + device_init_wakeup(&pdev->dev, true);
  2113. + return 0;
  2114. +
  2115. +err_pwrtgt:
  2116. + if (param_dgpu_power_exit != SHPS_DGPU_MP_POWER_ASIS) {
  2117. + status = shps_dgpu_set_power(pdev, param_dgpu_power_exit);
  2118. + if (status)
  2119. + dev_err(&pdev->dev, "failed to set dGPU power state: %d\n", status);
  2120. + }
  2121. +err_post_notification:
  2122. + if (detected_traits.notification_method == SHPS_NOTIFICATION_METHOD_SGCP) {
  2123. + shps_remove_sgcp_notification(pdev);
  2124. + } else if (detected_traits.notification_method == SHPS_NOTIFICATION_METHOD_SAN) {
  2125. + surface_sam_san_set_rqsg_handler(NULL, NULL);
  2126. + }
  2127. +err_devlink:
  2128. + device_remove_groups(&pdev->dev, shps_power_groups);
  2129. +err_devattr:
  2130. + shps_gpios_remove_irq(pdev);
  2131. +err_gpio_irqs:
  2132. + shps_gpios_remove(pdev);
  2133. +err_gpio:
  2134. + pci_dev_put(drvdata->dgpu_root_port);
  2135. +err_rp_lookup:
  2136. + platform_set_drvdata(pdev, NULL);
  2137. + kfree(drvdata);
  2138. +err_drvdata:
  2139. + acpi_dev_remove_driver_gpios(shps_dev);
  2140. + return status;
  2141. +}
  2142. +
  2143. +static int shps_remove(struct platform_device *pdev)
  2144. +{
  2145. + struct acpi_device *shps_dev = ACPI_COMPANION(&pdev->dev);
  2146. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  2147. + int status;
  2148. +
  2149. + if (param_dgpu_power_exit != SHPS_DGPU_MP_POWER_ASIS) {
  2150. + status = shps_dgpu_set_power(pdev, param_dgpu_power_exit);
  2151. + if (status)
  2152. + dev_err(&pdev->dev, "failed to set dGPU power state: %d\n", status);
  2153. + }
  2154. +
  2155. + device_set_wakeup_capable(&pdev->dev, false);
  2156. +
  2157. + if (drvdata->hardware_traits.notification_method == SHPS_NOTIFICATION_METHOD_SGCP) {
  2158. + shps_remove_sgcp_notification(pdev);
  2159. + } else if (drvdata->hardware_traits.notification_method == SHPS_NOTIFICATION_METHOD_SAN) {
  2160. + surface_sam_san_set_rqsg_handler(NULL, NULL);
  2161. + }
  2162. + device_remove_groups(&pdev->dev, shps_power_groups);
  2163. + shps_gpios_remove_irq(pdev);
  2164. + shps_gpios_remove(pdev);
  2165. + pci_dev_put(drvdata->dgpu_root_port);
  2166. + platform_set_drvdata(pdev, NULL);
  2167. + kfree(drvdata);
  2168. +
  2169. + acpi_dev_remove_driver_gpios(shps_dev);
  2170. + return 0;
  2171. +}
  2172. +
  2173. +
  2174. +static const struct dev_pm_ops shps_pm_ops = {
  2175. + .prepare = shps_pm_prepare,
  2176. + .complete = shps_pm_complete,
  2177. + .suspend = shps_pm_suspend,
  2178. + .resume = shps_pm_resume,
  2179. +};
  2180. +
  2181. +static const struct acpi_device_id shps_acpi_match[] = {
  2182. + { "MSHW0153", 0 },
  2183. + { },
  2184. +};
  2185. +MODULE_DEVICE_TABLE(acpi, shps_acpi_match);
  2186. +
  2187. +static struct platform_driver surface_sam_hps = {
  2188. + .probe = shps_probe,
  2189. + .remove = shps_remove,
  2190. + .shutdown = shps_shutdown,
  2191. + .driver = {
  2192. + .name = "surface_dgpu_hps",
  2193. + .acpi_match_table = shps_acpi_match,
  2194. + .pm = &shps_pm_ops,
  2195. + },
  2196. +};
  2197. +
  2198. +module_platform_driver(surface_sam_hps);
  2199. +
  2200. +MODULE_AUTHOR("Maximilian Luz <luzmaximilian@gmail.com>");
  2201. +MODULE_DESCRIPTION("Surface Hot-Plug System (HPS) and dGPU power-state Driver for Surface Book 2");
  2202. +MODULE_LICENSE("GPL");
  2203. diff --git a/drivers/platform/x86/surface_sam/surface_sam_san.c b/drivers/platform/x86/surface_sam/surface_sam_san.c
  2204. new file mode 100644
  2205. index 0000000000000..11dd6daedc3dd
  2206. --- /dev/null
  2207. +++ b/drivers/platform/x86/surface_sam/surface_sam_san.c
  2208. @@ -0,0 +1,913 @@
  2209. +// SPDX-License-Identifier: GPL-2.0-or-later
  2210. +/*
  2211. + * Surface ACPI Notify (SAN) and ACPI integration driver for SAM.
  2212. + * Translates communication from ACPI to SSH and back.
  2213. + */
  2214. +
  2215. +#include <linux/acpi.h>
  2216. +#include <linux/delay.h>
  2217. +#include <linux/jiffies.h>
  2218. +#include <linux/kernel.h>
  2219. +#include <linux/platform_device.h>
  2220. +
  2221. +#include "surface_sam_ssh.h"
  2222. +#include "surface_sam_san.h"
  2223. +
  2224. +
  2225. +#define SAN_RQST_RETRY 5
  2226. +
  2227. +#define SAN_DSM_REVISION 0
  2228. +#define SAN_DSM_FN_NOTIFY_SENSOR_TRIP_POINT 0x09
  2229. +
  2230. +static const guid_t SAN_DSM_UUID =
  2231. + GUID_INIT(0x93b666c5, 0x70c6, 0x469f, 0xa2, 0x15, 0x3d,
  2232. + 0x48, 0x7c, 0x91, 0xab, 0x3c);
  2233. +
  2234. +#define SAM_EVENT_DELAY_PWR_ADAPTER msecs_to_jiffies(5000)
  2235. +#define SAM_EVENT_DELAY_PWR_BST msecs_to_jiffies(2500)
  2236. +
  2237. +#define SAM_EVENT_PWR_CID_BIX 0x15
  2238. +#define SAM_EVENT_PWR_CID_BST 0x16
  2239. +#define SAM_EVENT_PWR_CID_ADAPTER 0x17
  2240. +#define SAM_EVENT_PWR_CID_DPTF 0x4f
  2241. +
  2242. +#define SAM_EVENT_TEMP_CID_NOTIFY_SENSOR_TRIP_POINT 0x0b
  2243. +
  2244. +#define SAN_RQST_TAG "surface_sam_san: rqst: "
  2245. +#define SAN_RQSG_TAG "surface_sam_san: rqsg: "
  2246. +
  2247. +#define SAN_QUIRK_BASE_STATE_DELAY 1000
  2248. +
  2249. +
  2250. +struct san_acpi_consumer {
  2251. + char *path;
  2252. + bool required;
  2253. + u32 flags;
  2254. +};
  2255. +
  2256. +struct san_opreg_context {
  2257. + struct acpi_connection_info connection;
  2258. + struct device *dev;
  2259. +};
  2260. +
  2261. +struct san_consumer_link {
  2262. + const struct san_acpi_consumer *properties;
  2263. + struct device_link *link;
  2264. +};
  2265. +
  2266. +struct san_consumers {
  2267. + u32 num;
  2268. + struct san_consumer_link *links;
  2269. +};
  2270. +
  2271. +struct san_drvdata {
  2272. + struct san_opreg_context opreg_ctx;
  2273. + struct san_consumers consumers;
  2274. +
  2275. + struct platform_device *dev;
  2276. + struct ssam_event_notifier nf_bat;
  2277. + struct ssam_event_notifier nf_tmp;
  2278. +};
  2279. +
  2280. +struct san_event_work {
  2281. + struct delayed_work work;
  2282. + struct platform_device *dev;
  2283. + struct ssam_event event; // must be last
  2284. +};
  2285. +
  2286. +struct gsb_data_in {
  2287. + u8 cv;
  2288. +} __packed;
  2289. +
  2290. +struct gsb_data_rqsx {
  2291. + u8 cv; // command value (should be 0x01 or 0x03)
  2292. + u8 tc; // target controller
  2293. + u8 tid; // transport channnel ID?
  2294. + u8 iid; // target sub-controller (e.g. primary vs. secondary battery)
  2295. + u8 snc; // expect-response-flag
  2296. + u8 cid; // command ID
  2297. + u8 cdl; // payload length
  2298. + u8 _pad; // padding
  2299. + u8 pld[0]; // payload
  2300. +} __packed;
  2301. +
  2302. +struct gsb_data_etwl {
  2303. + u8 cv; // command value (should be 0x02)
  2304. + u8 etw3; // ?
  2305. + u8 etw4; // ?
  2306. + u8 msg[0]; // error message (ASCIIZ)
  2307. +} __packed;
  2308. +
  2309. +struct gsb_data_out {
  2310. + u8 status; // _SSH communication status
  2311. + u8 len; // _SSH payload length
  2312. + u8 pld[0]; // _SSH payload
  2313. +} __packed;
  2314. +
  2315. +union gsb_buffer_data {
  2316. + struct gsb_data_in in; // common input
  2317. + struct gsb_data_rqsx rqsx; // RQSX input
  2318. + struct gsb_data_etwl etwl; // ETWL input
  2319. + struct gsb_data_out out; // output
  2320. +};
  2321. +
  2322. +struct gsb_buffer {
  2323. + u8 status; // GSB AttribRawProcess status
  2324. + u8 len; // GSB AttribRawProcess length
  2325. + union gsb_buffer_data data;
  2326. +} __packed;
  2327. +
  2328. +
  2329. +enum san_pwr_event {
  2330. + SAN_PWR_EVENT_BAT1_STAT = 0x03,
  2331. + SAN_PWR_EVENT_BAT1_INFO = 0x04,
  2332. + SAN_PWR_EVENT_ADP1_STAT = 0x05,
  2333. + SAN_PWR_EVENT_ADP1_INFO = 0x06,
  2334. + SAN_PWR_EVENT_BAT2_STAT = 0x07,
  2335. + SAN_PWR_EVENT_BAT2_INFO = 0x08,
  2336. + SAN_PWR_EVENT_DPTF = 0x0A,
  2337. +};
  2338. +
  2339. +
  2340. +static int sam_san_default_rqsg_handler(struct surface_sam_san_rqsg *rqsg, void *data);
  2341. +
  2342. +struct sam_san_rqsg_if {
  2343. + struct mutex lock;
  2344. + struct device *san_dev;
  2345. + surface_sam_san_rqsg_handler_fn handler;
  2346. + void *handler_data;
  2347. +};
  2348. +
  2349. +static struct sam_san_rqsg_if rqsg_if = {
  2350. + .lock = __MUTEX_INITIALIZER(rqsg_if.lock),
  2351. + .san_dev = NULL,
  2352. + .handler = sam_san_default_rqsg_handler,
  2353. + .handler_data = NULL,
  2354. +};
  2355. +
  2356. +int surface_sam_san_consumer_register(struct device *consumer, u32 flags)
  2357. +{
  2358. + const u32 valid = DL_FLAG_PM_RUNTIME | DL_FLAG_RPM_ACTIVE;
  2359. + int status;
  2360. +
  2361. + if ((flags | valid) != valid)
  2362. + return -EINVAL;
  2363. +
  2364. + flags |= DL_FLAG_AUTOREMOVE_CONSUMER;
  2365. +
  2366. + mutex_lock(&rqsg_if.lock);
  2367. + if (rqsg_if.san_dev)
  2368. + status = device_link_add(consumer, rqsg_if.san_dev, flags) ? 0 : -EINVAL;
  2369. + else
  2370. + status = -ENXIO;
  2371. + mutex_unlock(&rqsg_if.lock);
  2372. + return status;
  2373. +}
  2374. +EXPORT_SYMBOL_GPL(surface_sam_san_consumer_register);
  2375. +
  2376. +int surface_sam_san_set_rqsg_handler(surface_sam_san_rqsg_handler_fn fn, void *data)
  2377. +{
  2378. + int status = -EBUSY;
  2379. +
  2380. + mutex_lock(&rqsg_if.lock);
  2381. +
  2382. + if (rqsg_if.handler == sam_san_default_rqsg_handler || !fn) {
  2383. + rqsg_if.handler = fn ? fn : sam_san_default_rqsg_handler;
  2384. + rqsg_if.handler_data = data;
  2385. + status = 0;
  2386. + }
  2387. +
  2388. + mutex_unlock(&rqsg_if.lock);
  2389. + return status;
  2390. +}
  2391. +EXPORT_SYMBOL_GPL(surface_sam_san_set_rqsg_handler);
  2392. +
  2393. +int san_call_rqsg_handler(struct surface_sam_san_rqsg *rqsg)
  2394. +{
  2395. + int status;
  2396. +
  2397. + mutex_lock(&rqsg_if.lock);
  2398. + status = rqsg_if.handler(rqsg, rqsg_if.handler_data);
  2399. + mutex_unlock(&rqsg_if.lock);
  2400. +
  2401. + return status;
  2402. +}
  2403. +
  2404. +static int sam_san_default_rqsg_handler(struct surface_sam_san_rqsg *rqsg, void *data)
  2405. +{
  2406. + pr_warn(SAN_RQSG_TAG "unhandled request: RQSG(0x%02x, 0x%02x, 0x%02x)\n",
  2407. + rqsg->tc, rqsg->cid, rqsg->iid);
  2408. +
  2409. + return 0;
  2410. +}
  2411. +
  2412. +
  2413. +static bool san_acpi_can_notify(struct device *dev, u64 func)
  2414. +{
  2415. + acpi_handle san = ACPI_HANDLE(dev);
  2416. + return acpi_check_dsm(san, &SAN_DSM_UUID, SAN_DSM_REVISION, 1 << func);
  2417. +}
  2418. +
  2419. +static int san_acpi_notify_power_event(struct device *dev, enum san_pwr_event event)
  2420. +{
  2421. + acpi_handle san = ACPI_HANDLE(dev);
  2422. + union acpi_object *obj;
  2423. +
  2424. + if (!san_acpi_can_notify(dev, event))
  2425. + return 0;
  2426. +
  2427. + dev_dbg(dev, "notify power event 0x%02x\n", event);
  2428. + obj = acpi_evaluate_dsm_typed(san, &SAN_DSM_UUID, SAN_DSM_REVISION,
  2429. + event, NULL, ACPI_TYPE_BUFFER);
  2430. +
  2431. + if (IS_ERR_OR_NULL(obj))
  2432. + return obj ? PTR_ERR(obj) : -ENXIO;
  2433. +
  2434. + if (obj->buffer.length != 1 || obj->buffer.pointer[0] != 0) {
  2435. + dev_err(dev, "got unexpected result from _DSM\n");
  2436. + return -EFAULT;
  2437. + }
  2438. +
  2439. + ACPI_FREE(obj);
  2440. + return 0;
  2441. +}
  2442. +
  2443. +static int san_acpi_notify_sensor_trip_point(struct device *dev, u8 iid)
  2444. +{
  2445. + acpi_handle san = ACPI_HANDLE(dev);
  2446. + union acpi_object *obj;
  2447. + union acpi_object param;
  2448. +
  2449. + if (!san_acpi_can_notify(dev, SAN_DSM_FN_NOTIFY_SENSOR_TRIP_POINT))
  2450. + return 0;
  2451. +
  2452. + param.type = ACPI_TYPE_INTEGER;
  2453. + param.integer.value = iid;
  2454. +
  2455. + obj = acpi_evaluate_dsm_typed(san, &SAN_DSM_UUID, SAN_DSM_REVISION,
  2456. + SAN_DSM_FN_NOTIFY_SENSOR_TRIP_POINT,
  2457. + &param, ACPI_TYPE_BUFFER);
  2458. +
  2459. + if (IS_ERR_OR_NULL(obj))
  2460. + return obj ? PTR_ERR(obj) : -ENXIO;
  2461. +
  2462. + if (obj->buffer.length != 1 || obj->buffer.pointer[0] != 0) {
  2463. + dev_err(dev, "got unexpected result from _DSM\n");
  2464. + return -EFAULT;
  2465. + }
  2466. +
  2467. + ACPI_FREE(obj);
  2468. + return 0;
  2469. +}
  2470. +
  2471. +
  2472. +static inline int san_evt_power_adapter(struct device *dev, const struct ssam_event *event)
  2473. +{
  2474. + int status;
  2475. +
  2476. + status = san_acpi_notify_power_event(dev, SAN_PWR_EVENT_ADP1_STAT);
  2477. + if (status)
  2478. + return status;
  2479. +
  2480. + /*
  2481. + * Enusre that the battery states get updated correctly.
  2482. + * When the battery is fully charged and an adapter is plugged in, it
  2483. + * sometimes is not updated correctly, instead showing it as charging.
  2484. + * Explicitly trigger battery updates to fix this.
  2485. + */
  2486. +
  2487. + status = san_acpi_notify_power_event(dev, SAN_PWR_EVENT_BAT1_STAT);
  2488. + if (status)
  2489. + return status;
  2490. +
  2491. + return san_acpi_notify_power_event(dev, SAN_PWR_EVENT_BAT2_STAT);
  2492. +}
  2493. +
  2494. +static inline int san_evt_power_bix(struct device *dev, const struct ssam_event *event)
  2495. +{
  2496. + enum san_pwr_event evcode;
  2497. +
  2498. + if (event->instance_id == 0x02)
  2499. + evcode = SAN_PWR_EVENT_BAT2_INFO;
  2500. + else
  2501. + evcode = SAN_PWR_EVENT_BAT1_INFO;
  2502. +
  2503. + return san_acpi_notify_power_event(dev, evcode);
  2504. +}
  2505. +
  2506. +static inline int san_evt_power_bst(struct device *dev, const struct ssam_event *event)
  2507. +{
  2508. + enum san_pwr_event evcode;
  2509. +
  2510. + if (event->instance_id == 0x02)
  2511. + evcode = SAN_PWR_EVENT_BAT2_STAT;
  2512. + else
  2513. + evcode = SAN_PWR_EVENT_BAT1_STAT;
  2514. +
  2515. + return san_acpi_notify_power_event(dev, evcode);
  2516. +}
  2517. +
  2518. +static inline int san_evt_power_dptf(struct device *dev, const struct ssam_event *event)
  2519. +{
  2520. + union acpi_object payload;
  2521. + acpi_handle san = ACPI_HANDLE(dev);
  2522. + union acpi_object *obj;
  2523. +
  2524. + if (!san_acpi_can_notify(dev, SAN_PWR_EVENT_DPTF))
  2525. + return 0;
  2526. +
  2527. + /*
  2528. + * The Surface ACPI expects a buffer and not a package. It specifically
  2529. + * checks for ObjectType (Arg3) == 0x03. This will cause a warning in
  2530. + * acpica/nsarguments.c, but this can safely be ignored.
  2531. + */
  2532. + payload.type = ACPI_TYPE_BUFFER;
  2533. + payload.buffer.length = event->length;
  2534. + payload.buffer.pointer = (u8 *)&event->data[0];
  2535. +
  2536. + dev_dbg(dev, "notify power event 0x%02x\n", event->command_id);
  2537. + obj = acpi_evaluate_dsm_typed(san, &SAN_DSM_UUID, SAN_DSM_REVISION,
  2538. + SAN_PWR_EVENT_DPTF, &payload,
  2539. + ACPI_TYPE_BUFFER);
  2540. +
  2541. + if (IS_ERR_OR_NULL(obj))
  2542. + return obj ? PTR_ERR(obj) : -ENXIO;
  2543. +
  2544. + if (obj->buffer.length != 1 || obj->buffer.pointer[0] != 0) {
  2545. + dev_err(dev, "got unexpected result from _DSM\n");
  2546. + return -EFAULT;
  2547. + }
  2548. +
  2549. + ACPI_FREE(obj);
  2550. + return 0;
  2551. +}
  2552. +
  2553. +static unsigned long san_evt_power_delay(u8 cid)
  2554. +{
  2555. + switch (cid) {
  2556. + case SAM_EVENT_PWR_CID_ADAPTER:
  2557. + /*
  2558. + * Wait for battery state to update before signalling adapter change.
  2559. + */
  2560. + return SAM_EVENT_DELAY_PWR_ADAPTER;
  2561. +
  2562. + case SAM_EVENT_PWR_CID_BST:
  2563. + /*
  2564. + * Ensure we do not miss anything important due to caching.
  2565. + */
  2566. + return SAM_EVENT_DELAY_PWR_BST;
  2567. +
  2568. + case SAM_EVENT_PWR_CID_BIX:
  2569. + case SAM_EVENT_PWR_CID_DPTF:
  2570. + default:
  2571. + return 0;
  2572. + }
  2573. +}
  2574. +
  2575. +static bool san_evt_power(const struct ssam_event *event, struct device *dev)
  2576. +{
  2577. + int status;
  2578. +
  2579. + switch (event->command_id) {
  2580. + case SAM_EVENT_PWR_CID_BIX:
  2581. + status = san_evt_power_bix(dev, event);
  2582. + break;
  2583. +
  2584. + case SAM_EVENT_PWR_CID_BST:
  2585. + status = san_evt_power_bst(dev, event);
  2586. + break;
  2587. +
  2588. + case SAM_EVENT_PWR_CID_ADAPTER:
  2589. + status = san_evt_power_adapter(dev, event);
  2590. + break;
  2591. +
  2592. + case SAM_EVENT_PWR_CID_DPTF:
  2593. + status = san_evt_power_dptf(dev, event);
  2594. + break;
  2595. +
  2596. + default:
  2597. + return false;
  2598. + }
  2599. +
  2600. + if (status)
  2601. + dev_err(dev, "error handling power event (cid = %x)\n",
  2602. + event->command_id);
  2603. +
  2604. + return true;
  2605. +}
  2606. +
  2607. +static void san_evt_power_workfn(struct work_struct *work)
  2608. +{
  2609. + struct san_event_work *ev = container_of(work, struct san_event_work, work.work);
  2610. +
  2611. + san_evt_power(&ev->event, &ev->dev->dev);
  2612. + kfree(ev);
  2613. +}
  2614. +
  2615. +
  2616. +static u32 san_evt_power_nb(struct ssam_notifier_block *nb, const struct ssam_event *event)
  2617. +{
  2618. + struct san_drvdata *drvdata = container_of(nb, struct san_drvdata, nf_bat.base);
  2619. + struct san_event_work *work;
  2620. + unsigned long delay = san_evt_power_delay(event->command_id);
  2621. +
  2622. + if (delay == 0) {
  2623. + if (san_evt_power(event, &drvdata->dev->dev))
  2624. + return SSAM_NOTIF_HANDLED;
  2625. + else
  2626. + return 0;
  2627. + }
  2628. +
  2629. + work = kzalloc(sizeof(struct san_event_work) + event->length, GFP_KERNEL);
  2630. + if (!work)
  2631. + return ssam_notifier_from_errno(-ENOMEM);
  2632. +
  2633. + INIT_DELAYED_WORK(&work->work, san_evt_power_workfn);
  2634. + work->dev = drvdata->dev;
  2635. +
  2636. + memcpy(&work->event, event, sizeof(struct ssam_event) + event->length);
  2637. +
  2638. + schedule_delayed_work(&work->work, delay);
  2639. + return SSAM_NOTIF_HANDLED;
  2640. +}
  2641. +
  2642. +
  2643. +static inline int san_evt_thermal_notify(struct device *dev, const struct ssam_event *event)
  2644. +{
  2645. + return san_acpi_notify_sensor_trip_point(dev, event->instance_id);
  2646. +}
  2647. +
  2648. +static bool san_evt_thermal(const struct ssam_event *event, struct device *dev)
  2649. +{
  2650. + int status;
  2651. +
  2652. + switch (event->command_id) {
  2653. + case SAM_EVENT_TEMP_CID_NOTIFY_SENSOR_TRIP_POINT:
  2654. + status = san_evt_thermal_notify(dev, event);
  2655. + break;
  2656. +
  2657. + default:
  2658. + return false;
  2659. + }
  2660. +
  2661. + if (status) {
  2662. + dev_err(dev, "error handling thermal event (cid = %x)\n",
  2663. + event->command_id);
  2664. + }
  2665. +
  2666. + return true;
  2667. +}
  2668. +
  2669. +static u32 san_evt_thermal_nb(struct ssam_notifier_block *nb, const struct ssam_event *event)
  2670. +{
  2671. + struct san_drvdata *drvdata = container_of(nb, struct san_drvdata, nf_tmp.base);
  2672. + struct platform_device *pdev = drvdata->dev;
  2673. +
  2674. + if (san_evt_thermal(event, &pdev->dev))
  2675. + return SSAM_NOTIF_HANDLED;
  2676. + else
  2677. + return 0;
  2678. +}
  2679. +
  2680. +
  2681. +static struct gsb_data_rqsx
  2682. +*san_validate_rqsx(struct device *dev, const char *type, struct gsb_buffer *buffer)
  2683. +{
  2684. + struct gsb_data_rqsx *rqsx = &buffer->data.rqsx;
  2685. +
  2686. + if (buffer->len < 8) {
  2687. + dev_err(dev, "invalid %s package (len = %d)\n",
  2688. + type, buffer->len);
  2689. + return NULL;
  2690. + }
  2691. +
  2692. + if (rqsx->cdl != buffer->len - 8) {
  2693. + dev_err(dev, "bogus %s package (len = %d, cdl = %d)\n",
  2694. + type, buffer->len, rqsx->cdl);
  2695. + return NULL;
  2696. + }
  2697. +
  2698. + if (rqsx->tid != 0x01) {
  2699. + dev_warn(dev, "unsupported %s package (tid = 0x%02x)\n",
  2700. + type, rqsx->tid);
  2701. + return NULL;
  2702. + }
  2703. +
  2704. + return rqsx;
  2705. +}
  2706. +
  2707. +static acpi_status
  2708. +san_etwl(struct san_opreg_context *ctx, struct gsb_buffer *buffer)
  2709. +{
  2710. + struct gsb_data_etwl *etwl = &buffer->data.etwl;
  2711. +
  2712. + if (buffer->len < 3) {
  2713. + dev_err(ctx->dev, "invalid ETWL package (len = %d)\n", buffer->len);
  2714. + return AE_OK;
  2715. + }
  2716. +
  2717. + dev_err(ctx->dev, "ETWL(0x%02x, 0x%02x): %.*s\n",
  2718. + etwl->etw3, etwl->etw4,
  2719. + buffer->len - 3, (char *)etwl->msg);
  2720. +
  2721. + // indicate success
  2722. + buffer->status = 0x00;
  2723. + buffer->len = 0x00;
  2724. +
  2725. + return AE_OK;
  2726. +}
  2727. +
  2728. +static acpi_status
  2729. +san_rqst(struct san_opreg_context *ctx, struct gsb_buffer *buffer)
  2730. +{
  2731. + struct gsb_data_rqsx *gsb_rqst = san_validate_rqsx(ctx->dev, "RQST", buffer);
  2732. + struct surface_sam_ssh_rqst rqst = {};
  2733. + struct surface_sam_ssh_buf result = {};
  2734. + int status = 0;
  2735. + int try;
  2736. +
  2737. + if (!gsb_rqst)
  2738. + return AE_OK;
  2739. +
  2740. + rqst.tc = gsb_rqst->tc;
  2741. + rqst.cid = gsb_rqst->cid;
  2742. + rqst.iid = gsb_rqst->iid;
  2743. + rqst.chn = gsb_rqst->tid;
  2744. + rqst.snc = gsb_rqst->snc;
  2745. + rqst.cdl = gsb_rqst->cdl;
  2746. + rqst.pld = &gsb_rqst->pld[0];
  2747. +
  2748. + result.cap = SURFACE_SAM_SSH_MAX_RQST_RESPONSE;
  2749. + result.len = 0;
  2750. + result.data = kzalloc(result.cap, GFP_KERNEL);
  2751. +
  2752. + if (!result.data)
  2753. + return AE_NO_MEMORY;
  2754. +
  2755. + for (try = 0; try < SAN_RQST_RETRY; try++) {
  2756. + if (try)
  2757. + dev_warn(ctx->dev, SAN_RQST_TAG "IO error occurred, trying again\n");
  2758. +
  2759. + status = surface_sam_ssh_rqst(&rqst, &result);
  2760. + if (status != -EIO)
  2761. + break;
  2762. + }
  2763. +
  2764. + if (rqst.tc == 0x11 && rqst.cid == 0x0D && status == -EPERM) {
  2765. + /* Base state quirk:
  2766. + * The base state may be queried from ACPI when the EC is still
  2767. + * suspended. In this case it will return '-EPERM'. This query
  2768. + * will only be triggered from the ACPI lid GPE interrupt, thus
  2769. + * we are either in laptop or studio mode (base status 0x01 or
  2770. + * 0x02). Furthermore, we will only get here if the device (and
  2771. + * EC) have been suspended.
  2772. + *
  2773. + * We now assume that the device is in laptop mode (0x01). This
  2774. + * has the drawback that it will wake the device when unfolding
  2775. + * it in studio mode, but it also allows us to avoid actively
  2776. + * waiting for the EC to wake up, which may incur a notable
  2777. + * delay.
  2778. + */
  2779. +
  2780. + buffer->status = 0x00;
  2781. + buffer->len = 0x03;
  2782. + buffer->data.out.status = 0x00;
  2783. + buffer->data.out.len = 0x01;
  2784. + buffer->data.out.pld[0] = 0x01;
  2785. +
  2786. + } else if (!status) { // success
  2787. + buffer->status = 0x00;
  2788. + buffer->len = result.len + 2;
  2789. + buffer->data.out.status = 0x00;
  2790. + buffer->data.out.len = result.len;
  2791. + memcpy(&buffer->data.out.pld[0], result.data, result.len);
  2792. +
  2793. + } else { // failure
  2794. + dev_err(ctx->dev, SAN_RQST_TAG "failed with error %d\n", status);
  2795. + buffer->status = 0x00;
  2796. + buffer->len = 0x02;
  2797. + buffer->data.out.status = 0x01; // indicate _SSH error
  2798. + buffer->data.out.len = 0x00;
  2799. + }
  2800. +
  2801. + kfree(result.data);
  2802. +
  2803. + return AE_OK;
  2804. +}
  2805. +
  2806. +static acpi_status
  2807. +san_rqsg(struct san_opreg_context *ctx, struct gsb_buffer *buffer)
  2808. +{
  2809. + struct gsb_data_rqsx *gsb_rqsg = san_validate_rqsx(ctx->dev, "RQSG", buffer);
  2810. + struct surface_sam_san_rqsg rqsg = {};
  2811. + int status;
  2812. +
  2813. + if (!gsb_rqsg)
  2814. + return AE_OK;
  2815. +
  2816. + rqsg.tc = gsb_rqsg->tc;
  2817. + rqsg.cid = gsb_rqsg->cid;
  2818. + rqsg.iid = gsb_rqsg->iid;
  2819. + rqsg.cdl = gsb_rqsg->cdl;
  2820. + rqsg.pld = &gsb_rqsg->pld[0];
  2821. +
  2822. + status = san_call_rqsg_handler(&rqsg);
  2823. + if (!status) {
  2824. + buffer->status = 0x00;
  2825. + buffer->len = 0x02;
  2826. + buffer->data.out.status = 0x00;
  2827. + buffer->data.out.len = 0x00;
  2828. + } else {
  2829. + dev_err(ctx->dev, SAN_RQSG_TAG "failed with error %d\n", status);
  2830. + buffer->status = 0x00;
  2831. + buffer->len = 0x02;
  2832. + buffer->data.out.status = 0x01; // indicate _SSH error
  2833. + buffer->data.out.len = 0x00;
  2834. + }
  2835. +
  2836. + return AE_OK;
  2837. +}
  2838. +
  2839. +
  2840. +static acpi_status
  2841. +san_opreg_handler(u32 function, acpi_physical_address command,
  2842. + u32 bits, u64 *value64,
  2843. + void *opreg_context, void *region_context)
  2844. +{
  2845. + struct san_opreg_context *context = opreg_context;
  2846. + struct gsb_buffer *buffer = (struct gsb_buffer *)value64;
  2847. + int accessor_type = (0xFFFF0000 & function) >> 16;
  2848. +
  2849. + if (command != 0) {
  2850. + dev_warn(context->dev, "unsupported command: 0x%02llx\n", command);
  2851. + return AE_OK;
  2852. + }
  2853. +
  2854. + if (accessor_type != ACPI_GSB_ACCESS_ATTRIB_RAW_PROCESS) {
  2855. + dev_err(context->dev, "invalid access type: 0x%02x\n", accessor_type);
  2856. + return AE_OK;
  2857. + }
  2858. +
  2859. + // buffer must have at least contain the command-value
  2860. + if (buffer->len == 0) {
  2861. + dev_err(context->dev, "request-package too small\n");
  2862. + return AE_OK;
  2863. + }
  2864. +
  2865. + switch (buffer->data.in.cv) {
  2866. + case 0x01: return san_rqst(context, buffer);
  2867. + case 0x02: return san_etwl(context, buffer);
  2868. + case 0x03: return san_rqsg(context, buffer);
  2869. + }
  2870. +
  2871. + dev_warn(context->dev, "unsupported SAN0 request (cv: 0x%02x)\n", buffer->data.in.cv);
  2872. + return AE_OK;
  2873. +}
  2874. +
  2875. +static int san_events_register(struct platform_device *pdev)
  2876. +{
  2877. + struct san_drvdata *drvdata = platform_get_drvdata(pdev);
  2878. + int status;
  2879. +
  2880. + drvdata->nf_bat.base.priority = 1;
  2881. + drvdata->nf_bat.base.fn = san_evt_power_nb;
  2882. + drvdata->nf_bat.event.reg = SSAM_EVENT_REGISTRY_SAM;
  2883. + drvdata->nf_bat.event.id.target_category = SSAM_SSH_TC_BAT;
  2884. + drvdata->nf_bat.event.id.instance = 0;
  2885. + drvdata->nf_bat.event.flags = SSAM_EVENT_SEQUENCED;
  2886. +
  2887. + drvdata->nf_tmp.base.priority = 1;
  2888. + drvdata->nf_tmp.base.fn = san_evt_thermal_nb;
  2889. + drvdata->nf_tmp.event.reg = SSAM_EVENT_REGISTRY_SAM;
  2890. + drvdata->nf_tmp.event.id.target_category = SSAM_SSH_TC_TMP;
  2891. + drvdata->nf_tmp.event.id.instance = 0;
  2892. + drvdata->nf_tmp.event.flags = SSAM_EVENT_SEQUENCED;
  2893. +
  2894. + status = surface_sam_ssh_notifier_register(&drvdata->nf_bat);
  2895. + if (status)
  2896. + return status;
  2897. +
  2898. + status = surface_sam_ssh_notifier_register(&drvdata->nf_tmp);
  2899. + if (status)
  2900. + surface_sam_ssh_notifier_unregister(&drvdata->nf_bat);
  2901. +
  2902. + return status;
  2903. +}
  2904. +
  2905. +static void san_events_unregister(struct platform_device *pdev)
  2906. +{
  2907. + struct san_drvdata *drvdata = platform_get_drvdata(pdev);
  2908. +
  2909. + surface_sam_ssh_notifier_unregister(&drvdata->nf_bat);
  2910. + surface_sam_ssh_notifier_unregister(&drvdata->nf_tmp);
  2911. +}
  2912. +
  2913. +
  2914. +static int san_consumers_link(struct platform_device *pdev,
  2915. + const struct san_acpi_consumer *cons,
  2916. + struct san_consumers *out)
  2917. +{
  2918. + const struct san_acpi_consumer *con;
  2919. + struct san_consumer_link *links, *link;
  2920. + struct acpi_device *adev;
  2921. + acpi_handle handle;
  2922. + u32 max_links = 0;
  2923. + int status;
  2924. +
  2925. + if (!cons)
  2926. + return 0;
  2927. +
  2928. + // count links
  2929. + for (con = cons; con->path; ++con)
  2930. + max_links += 1;
  2931. +
  2932. + // allocate
  2933. + links = kcalloc(max_links, sizeof(struct san_consumer_link), GFP_KERNEL);
  2934. + link = &links[0];
  2935. +
  2936. + if (!links)
  2937. + return -ENOMEM;
  2938. +
  2939. + // create links
  2940. + for (con = cons; con->path; ++con) {
  2941. + status = acpi_get_handle(NULL, con->path, &handle);
  2942. + if (status) {
  2943. + if (con->required || status != AE_NOT_FOUND) {
  2944. + status = -ENXIO;
  2945. + goto cleanup;
  2946. + } else {
  2947. + continue;
  2948. + }
  2949. + }
  2950. +
  2951. + status = acpi_bus_get_device(handle, &adev);
  2952. + if (status)
  2953. + goto cleanup;
  2954. +
  2955. + link->link = device_link_add(&adev->dev, &pdev->dev, con->flags);
  2956. + if (!(link->link)) {
  2957. + status = -EFAULT;
  2958. + goto cleanup;
  2959. + }
  2960. + link->properties = con;
  2961. +
  2962. + link += 1;
  2963. + }
  2964. +
  2965. + out->num = link - links;
  2966. + out->links = links;
  2967. +
  2968. + return 0;
  2969. +
  2970. +cleanup:
  2971. + for (link = link - 1; link >= links; --link) {
  2972. + if (link->properties->flags & DL_FLAG_STATELESS)
  2973. + device_link_del(link->link);
  2974. + }
  2975. +
  2976. + return status;
  2977. +}
  2978. +
  2979. +static void san_consumers_unlink(struct san_consumers *consumers)
  2980. +{
  2981. + u32 i;
  2982. +
  2983. + if (!consumers)
  2984. + return;
  2985. +
  2986. + for (i = 0; i < consumers->num; ++i) {
  2987. + if (consumers->links[i].properties->flags & DL_FLAG_STATELESS)
  2988. + device_link_del(consumers->links[i].link);
  2989. + }
  2990. +
  2991. + kfree(consumers->links);
  2992. +
  2993. + consumers->num = 0;
  2994. + consumers->links = NULL;
  2995. +}
  2996. +
  2997. +static int surface_sam_san_probe(struct platform_device *pdev)
  2998. +{
  2999. + const struct san_acpi_consumer *cons;
  3000. + struct san_drvdata *drvdata;
  3001. + acpi_handle san = ACPI_HANDLE(&pdev->dev); // _SAN device node
  3002. + int status;
  3003. +
  3004. + /*
  3005. + * Defer probe if the _SSH driver has not set up the controller yet. This
  3006. + * makes sure we do not fail any initial requests (e.g. _STA request without
  3007. + * which the battery does not get set up correctly). Otherwise register as
  3008. + * consumer to set up a device_link.
  3009. + */
  3010. + status = surface_sam_ssh_consumer_register(&pdev->dev);
  3011. + if (status)
  3012. + return status == -ENXIO ? -EPROBE_DEFER : status;
  3013. +
  3014. + drvdata = kzalloc(sizeof(struct san_drvdata), GFP_KERNEL);
  3015. + if (!drvdata)
  3016. + return -ENOMEM;
  3017. +
  3018. + drvdata->dev = pdev;
  3019. + drvdata->opreg_ctx.dev = &pdev->dev;
  3020. +
  3021. + cons = acpi_device_get_match_data(&pdev->dev);
  3022. + status = san_consumers_link(pdev, cons, &drvdata->consumers);
  3023. + if (status)
  3024. + goto err_consumers;
  3025. +
  3026. + platform_set_drvdata(pdev, drvdata);
  3027. +
  3028. + status = acpi_install_address_space_handler(san,
  3029. + ACPI_ADR_SPACE_GSBUS,
  3030. + &san_opreg_handler,
  3031. + NULL, &drvdata->opreg_ctx);
  3032. +
  3033. + if (ACPI_FAILURE(status)) {
  3034. + status = -ENODEV;
  3035. + goto err_install_handler;
  3036. + }
  3037. +
  3038. + status = san_events_register(pdev);
  3039. + if (status)
  3040. + goto err_enable_events;
  3041. +
  3042. + mutex_lock(&rqsg_if.lock);
  3043. + if (!rqsg_if.san_dev)
  3044. + rqsg_if.san_dev = &pdev->dev;
  3045. + else
  3046. + status = -EBUSY;
  3047. + mutex_unlock(&rqsg_if.lock);
  3048. +
  3049. + if (status)
  3050. + goto err_install_dev;
  3051. +
  3052. + acpi_walk_dep_device_list(san);
  3053. + return 0;
  3054. +
  3055. +err_install_dev:
  3056. + san_events_unregister(pdev);
  3057. +err_enable_events:
  3058. + acpi_remove_address_space_handler(san, ACPI_ADR_SPACE_GSBUS, &san_opreg_handler);
  3059. +err_install_handler:
  3060. + platform_set_drvdata(san, NULL);
  3061. + san_consumers_unlink(&drvdata->consumers);
  3062. +err_consumers:
  3063. + kfree(drvdata);
  3064. + return status;
  3065. +}
  3066. +
  3067. +static int surface_sam_san_remove(struct platform_device *pdev)
  3068. +{
  3069. + struct san_drvdata *drvdata = platform_get_drvdata(pdev);
  3070. + acpi_handle san = ACPI_HANDLE(&pdev->dev); // _SAN device node
  3071. + acpi_status status = AE_OK;
  3072. +
  3073. + mutex_lock(&rqsg_if.lock);
  3074. + rqsg_if.san_dev = NULL;
  3075. + mutex_unlock(&rqsg_if.lock);
  3076. +
  3077. + acpi_remove_address_space_handler(san, ACPI_ADR_SPACE_GSBUS, &san_opreg_handler);
  3078. + san_events_unregister(pdev);
  3079. +
  3080. + /*
  3081. + * We have unregistered our event sources. Now we need to ensure that
  3082. + * all delayed works they may have spawned are run to completion.
  3083. + */
  3084. + flush_scheduled_work();
  3085. +
  3086. + san_consumers_unlink(&drvdata->consumers);
  3087. + kfree(drvdata);
  3088. +
  3089. + platform_set_drvdata(pdev, NULL);
  3090. + return status;
  3091. +}
  3092. +
  3093. +
  3094. +static const struct san_acpi_consumer san_mshw0091_consumers[] = {
  3095. + { "\\_SB.SRTC", true, DL_FLAG_PM_RUNTIME | DL_FLAG_STATELESS },
  3096. + { "\\ADP1", true, DL_FLAG_PM_RUNTIME | DL_FLAG_STATELESS },
  3097. + { "\\_SB.BAT1", true, DL_FLAG_PM_RUNTIME | DL_FLAG_STATELESS },
  3098. + { "\\_SB.BAT2", false, DL_FLAG_PM_RUNTIME | DL_FLAG_STATELESS },
  3099. + { },
  3100. +};
  3101. +
  3102. +static const struct acpi_device_id surface_sam_san_match[] = {
  3103. + { "MSHW0091", (unsigned long) san_mshw0091_consumers },
  3104. + { },
  3105. +};
  3106. +MODULE_DEVICE_TABLE(acpi, surface_sam_san_match);
  3107. +
  3108. +static struct platform_driver surface_sam_san = {
  3109. + .probe = surface_sam_san_probe,
  3110. + .remove = surface_sam_san_remove,
  3111. + .driver = {
  3112. + .name = "surface_sam_san",
  3113. + .acpi_match_table = surface_sam_san_match,
  3114. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  3115. + },
  3116. +};
  3117. +module_platform_driver(surface_sam_san);
  3118. +
  3119. +MODULE_AUTHOR("Maximilian Luz <luzmaximilian@gmail.com>");
  3120. +MODULE_DESCRIPTION("Surface ACPI Notify Driver for 5th Generation Surface Devices");
  3121. +MODULE_LICENSE("GPL");
  3122. diff --git a/drivers/platform/x86/surface_sam/surface_sam_san.h b/drivers/platform/x86/surface_sam/surface_sam_san.h
  3123. new file mode 100644
  3124. index 0000000000000..2b9dee159bbbc
  3125. --- /dev/null
  3126. +++ b/drivers/platform/x86/surface_sam/surface_sam_san.h
  3127. @@ -0,0 +1,30 @@
  3128. +/* SPDX-License-Identifier: GPL-2.0-or-later */
  3129. +/*
  3130. + * Interface for Surface ACPI/Notify (SAN).
  3131. + *
  3132. + * The SAN is the main interface between the Surface Serial Hub (SSH) and the
  3133. + * Surface/System Aggregator Module (SAM). It allows requests to be translated
  3134. + * from ACPI to SSH/SAM. It also interfaces with the discrete GPU hot-plug
  3135. + * driver.
  3136. + */
  3137. +
  3138. +#ifndef _SURFACE_SAM_SAN_H
  3139. +#define _SURFACE_SAM_SAN_H
  3140. +
  3141. +#include <linux/types.h>
  3142. +
  3143. +
  3144. +struct surface_sam_san_rqsg {
  3145. + u8 tc; // target category
  3146. + u8 cid; // command ID
  3147. + u8 iid; // instance ID
  3148. + u8 cdl; // command data length (length of payload)
  3149. + u8 *pld; // pointer to payload of length cdl
  3150. +};
  3151. +
  3152. +typedef int (*surface_sam_san_rqsg_handler_fn)(struct surface_sam_san_rqsg *rqsg, void *data);
  3153. +
  3154. +int surface_sam_san_consumer_register(struct device *consumer, u32 flags);
  3155. +int surface_sam_san_set_rqsg_handler(surface_sam_san_rqsg_handler_fn fn, void *data);
  3156. +
  3157. +#endif /* _SURFACE_SAM_SAN_H */
  3158. diff --git a/drivers/platform/x86/surface_sam/surface_sam_sid.c b/drivers/platform/x86/surface_sam/surface_sam_sid.c
  3159. new file mode 100644
  3160. index 0000000000000..caa2e6446b5f4
  3161. --- /dev/null
  3162. +++ b/drivers/platform/x86/surface_sam/surface_sam_sid.c
  3163. @@ -0,0 +1,281 @@
  3164. +// SPDX-License-Identifier: GPL-2.0-or-later
  3165. +/*
  3166. + * Surface Integration Driver.
  3167. + * MFD driver to provide device/model dependent functionality.
  3168. + */
  3169. +
  3170. +#include <linux/acpi.h>
  3171. +#include <linux/kernel.h>
  3172. +#include <linux/module.h>
  3173. +#include <linux/platform_device.h>
  3174. +#include <linux/mfd/core.h>
  3175. +
  3176. +#include "surface_sam_sid_power.h"
  3177. +#include "surface_sam_sid_vhf.h"
  3178. +
  3179. +
  3180. +struct ssam_battery_properties ssam_battery_props_bat1 = {
  3181. + .registry = SSAM_EVENT_REGISTRY_SAM,
  3182. + .num = 0,
  3183. + .channel = 1,
  3184. + .instance = 1,
  3185. +};
  3186. +
  3187. +struct ssam_battery_properties ssam_battery_props_bat2_sb3 = {
  3188. + .registry = SSAM_EVENT_REGISTRY_KIP,
  3189. + .num = 1,
  3190. + .channel = 2,
  3191. + .instance = 1,
  3192. +};
  3193. +
  3194. +
  3195. +static const struct ssam_hid_properties ssam_hid_props_keyboard = {
  3196. + .registry = SSAM_EVENT_REGISTRY_REG,
  3197. + .instance = 1,
  3198. +};
  3199. +
  3200. +static const struct ssam_hid_properties ssam_hid_props_touchpad = {
  3201. + .registry = SSAM_EVENT_REGISTRY_REG,
  3202. + .instance = 3,
  3203. +};
  3204. +
  3205. +static const struct ssam_hid_properties ssam_hid_props_iid5 = {
  3206. + .registry = SSAM_EVENT_REGISTRY_REG,
  3207. + .instance = 5,
  3208. +};
  3209. +
  3210. +static const struct ssam_hid_properties ssam_hid_props_iid6 = {
  3211. + .registry = SSAM_EVENT_REGISTRY_REG,
  3212. + .instance = 6,
  3213. +};
  3214. +
  3215. +
  3216. +static const struct mfd_cell sid_devs_sp4[] = {
  3217. + { .name = "surface_sam_sid_gpelid", .id = -1 },
  3218. + { .name = "surface_sam_sid_perfmode", .id = -1 },
  3219. + { },
  3220. +};
  3221. +
  3222. +static const struct mfd_cell sid_devs_sp6[] = {
  3223. + { .name = "surface_sam_sid_gpelid", .id = -1 },
  3224. + { .name = "surface_sam_sid_perfmode", .id = -1 },
  3225. + { },
  3226. +};
  3227. +
  3228. +static const struct mfd_cell sid_devs_sp7[] = {
  3229. + { .name = "surface_sam_sid_gpelid", .id = -1 },
  3230. + { .name = "surface_sam_sid_perfmode", .id = -1 },
  3231. + { .name = "surface_sam_sid_ac", .id = -1 },
  3232. + {
  3233. + .name = "surface_sam_sid_battery",
  3234. + .id = -1,
  3235. + .platform_data = &ssam_battery_props_bat1,
  3236. + .pdata_size = sizeof(struct ssam_battery_properties),
  3237. + },
  3238. + { },
  3239. +};
  3240. +
  3241. +static const struct mfd_cell sid_devs_sb1[] = {
  3242. + { .name = "surface_sam_sid_gpelid", .id = -1 },
  3243. + { },
  3244. +};
  3245. +
  3246. +static const struct mfd_cell sid_devs_sb2[] = {
  3247. + { .name = "surface_sam_sid_gpelid", .id = -1 },
  3248. + { .name = "surface_sam_sid_perfmode", .id = -1 },
  3249. + { },
  3250. +};
  3251. +
  3252. +static const struct mfd_cell sid_devs_sb3[] = {
  3253. + { .name = "surface_sam_sid_gpelid", .id = -1 },
  3254. + { .name = "surface_sam_sid_perfmode", .id = -1 },
  3255. + { .name = "surface_sam_sid_ac", .id = -1 },
  3256. + {
  3257. + .name = "surface_sam_sid_battery",
  3258. + .id = 1,
  3259. + .platform_data = &ssam_battery_props_bat1,
  3260. + .pdata_size = sizeof(struct ssam_battery_properties),
  3261. + },
  3262. + {
  3263. + .name = "surface_sam_sid_battery",
  3264. + .id = 2,
  3265. + .platform_data = &ssam_battery_props_bat2_sb3,
  3266. + .pdata_size = sizeof(struct ssam_battery_properties),
  3267. + },
  3268. + {
  3269. + .name = "surface_sam_sid_vhf",
  3270. + .id = 1,
  3271. + .platform_data = (void *)&ssam_hid_props_keyboard,
  3272. + .pdata_size = sizeof(struct ssam_hid_properties),
  3273. + },
  3274. + {
  3275. + .name = "surface_sam_sid_vhf",
  3276. + .id = 3,
  3277. + .platform_data = (void *)&ssam_hid_props_touchpad,
  3278. + .pdata_size = sizeof(struct ssam_hid_properties),
  3279. + },
  3280. + {
  3281. + .name = "surface_sam_sid_vhf",
  3282. + .id = 5,
  3283. + .platform_data = (void *)&ssam_hid_props_iid5,
  3284. + .pdata_size = sizeof(struct ssam_hid_properties),
  3285. + },
  3286. + {
  3287. + .name = "surface_sam_sid_vhf",
  3288. + .id = 6,
  3289. + .platform_data = (void *)&ssam_hid_props_iid6,
  3290. + .pdata_size = sizeof(struct ssam_hid_properties),
  3291. + },
  3292. + { },
  3293. +};
  3294. +
  3295. +static const struct mfd_cell sid_devs_sl1[] = {
  3296. + { .name = "surface_sam_sid_gpelid", .id = -1 },
  3297. + { },
  3298. +};
  3299. +
  3300. +static const struct mfd_cell sid_devs_sl2[] = {
  3301. + { .name = "surface_sam_sid_gpelid", .id = -1 },
  3302. + { },
  3303. +};
  3304. +
  3305. +static const struct mfd_cell sid_devs_sl3_13[] = {
  3306. + { .name = "surface_sam_sid_gpelid", .id = -1 },
  3307. + { .name = "surface_sam_sid_perfmode", .id = -1 },
  3308. + { .name = "surface_sam_sid_ac", .id = -1 },
  3309. + {
  3310. + .name = "surface_sam_sid_battery",
  3311. + .id = -1,
  3312. + .platform_data = &ssam_battery_props_bat1,
  3313. + .pdata_size = sizeof(struct ssam_battery_properties),
  3314. + },
  3315. + {
  3316. + .name = "surface_sam_sid_vhf",
  3317. + .id = 1,
  3318. + .platform_data = (void *)&ssam_hid_props_keyboard,
  3319. + .pdata_size = sizeof(struct ssam_hid_properties),
  3320. + },
  3321. + {
  3322. + .name = "surface_sam_sid_vhf",
  3323. + .id = 3,
  3324. + .platform_data = (void *)&ssam_hid_props_touchpad,
  3325. + .pdata_size = sizeof(struct ssam_hid_properties),
  3326. + },
  3327. + {
  3328. + .name = "surface_sam_sid_vhf",
  3329. + .id = 5,
  3330. + .platform_data = (void *)&ssam_hid_props_iid5,
  3331. + .pdata_size = sizeof(struct ssam_hid_properties),
  3332. + },
  3333. + { },
  3334. +};
  3335. +
  3336. +static const struct mfd_cell sid_devs_sl3_15[] = {
  3337. + { .name = "surface_sam_sid_perfmode", .id = -1 },
  3338. + { .name = "surface_sam_sid_ac", .id = -1 },
  3339. + {
  3340. + .name = "surface_sam_sid_battery",
  3341. + .id = -1,
  3342. + .platform_data = &ssam_battery_props_bat1,
  3343. + .pdata_size = sizeof(struct ssam_battery_properties),
  3344. + },
  3345. + {
  3346. + .name = "surface_sam_sid_vhf",
  3347. + .id = 1,
  3348. + .platform_data = (void *)&ssam_hid_props_keyboard,
  3349. + .pdata_size = sizeof(struct ssam_hid_properties),
  3350. + },
  3351. + {
  3352. + .name = "surface_sam_sid_vhf",
  3353. + .id = 3,
  3354. + .platform_data = (void *)&ssam_hid_props_touchpad,
  3355. + .pdata_size = sizeof(struct ssam_hid_properties),
  3356. + },
  3357. + {
  3358. + .name = "surface_sam_sid_vhf",
  3359. + .id = 5,
  3360. + .platform_data = (void *)&ssam_hid_props_iid5,
  3361. + .pdata_size = sizeof(struct ssam_hid_properties),
  3362. + },
  3363. + { },
  3364. +};
  3365. +
  3366. +static const struct acpi_device_id surface_sam_sid_match[] = {
  3367. + /* Surface Pro 4, 5, and 6 */
  3368. + { "MSHW0081", (unsigned long)sid_devs_sp4 },
  3369. +
  3370. + /* Surface Pro 6 (OMBR >= 0x10) */
  3371. + { "MSHW0111", (unsigned long)sid_devs_sp6 },
  3372. +
  3373. + /* Surface Pro 7 */
  3374. + { "MSHW0116", (unsigned long)sid_devs_sp7 },
  3375. +
  3376. + /* Surface Book 1 */
  3377. + { "MSHW0080", (unsigned long)sid_devs_sb1 },
  3378. +
  3379. + /* Surface Book 2 */
  3380. + { "MSHW0107", (unsigned long)sid_devs_sb2 },
  3381. +
  3382. + /* Surface Book 3 */
  3383. + { "MSHW0117", (unsigned long)sid_devs_sb3 },
  3384. +
  3385. + /* Surface Laptop 1 */
  3386. + { "MSHW0086", (unsigned long)sid_devs_sl1 },
  3387. +
  3388. + /* Surface Laptop 2 */
  3389. + { "MSHW0112", (unsigned long)sid_devs_sl2 },
  3390. +
  3391. + /* Surface Laptop 3 (13") */
  3392. + { "MSHW0114", (unsigned long)sid_devs_sl3_13 },
  3393. +
  3394. + /* Surface Laptop 3 (15") */
  3395. + { "MSHW0110", (unsigned long)sid_devs_sl3_15 },
  3396. +
  3397. + { },
  3398. +};
  3399. +MODULE_DEVICE_TABLE(acpi, surface_sam_sid_match);
  3400. +
  3401. +
  3402. +static int surface_sam_sid_probe(struct platform_device *pdev)
  3403. +{
  3404. + const struct acpi_device_id *match;
  3405. + const struct mfd_cell *cells, *p;
  3406. +
  3407. + match = acpi_match_device(surface_sam_sid_match, &pdev->dev);
  3408. + if (!match)
  3409. + return -ENODEV;
  3410. +
  3411. + cells = (struct mfd_cell *)match->driver_data;
  3412. + if (!cells)
  3413. + return -ENODEV;
  3414. +
  3415. + for (p = cells; p->name; ++p) {
  3416. + /* just count */
  3417. + }
  3418. +
  3419. + if (p == cells)
  3420. + return -ENODEV;
  3421. +
  3422. + return mfd_add_devices(&pdev->dev, 0, cells, p - cells, NULL, 0, NULL);
  3423. +}
  3424. +
  3425. +static int surface_sam_sid_remove(struct platform_device *pdev)
  3426. +{
  3427. + mfd_remove_devices(&pdev->dev);
  3428. + return 0;
  3429. +}
  3430. +
  3431. +static struct platform_driver surface_sam_sid = {
  3432. + .probe = surface_sam_sid_probe,
  3433. + .remove = surface_sam_sid_remove,
  3434. + .driver = {
  3435. + .name = "surface_sam_sid",
  3436. + .acpi_match_table = surface_sam_sid_match,
  3437. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  3438. + },
  3439. +};
  3440. +module_platform_driver(surface_sam_sid);
  3441. +
  3442. +MODULE_AUTHOR("Maximilian Luz <luzmaximilian@gmail.com>");
  3443. +MODULE_DESCRIPTION("Surface Integration Driver for 5th Generation Surface Devices");
  3444. +MODULE_LICENSE("GPL");
  3445. diff --git a/drivers/platform/x86/surface_sam/surface_sam_sid_gpelid.c b/drivers/platform/x86/surface_sam/surface_sam_sid_gpelid.c
  3446. new file mode 100644
  3447. index 0000000000000..f0cee43c859b4
  3448. --- /dev/null
  3449. +++ b/drivers/platform/x86/surface_sam/surface_sam_sid_gpelid.c
  3450. @@ -0,0 +1,232 @@
  3451. +// SPDX-License-Identifier: GPL-2.0-or-later
  3452. +/*
  3453. + * Surface Lid driver to enable wakeup from suspend via the lid.
  3454. + */
  3455. +
  3456. +#include <linux/acpi.h>
  3457. +#include <linux/dmi.h>
  3458. +#include <linux/kernel.h>
  3459. +#include <linux/module.h>
  3460. +#include <linux/platform_device.h>
  3461. +
  3462. +
  3463. +struct sid_lid_device {
  3464. + const char *acpi_path;
  3465. + const u32 gpe_number;
  3466. +};
  3467. +
  3468. +
  3469. +static const struct sid_lid_device lid_device_l17 = {
  3470. + .acpi_path = "\\_SB.LID0",
  3471. + .gpe_number = 0x17,
  3472. +};
  3473. +
  3474. +static const struct sid_lid_device lid_device_l4D = {
  3475. + .acpi_path = "\\_SB.LID0",
  3476. + .gpe_number = 0x4D,
  3477. +};
  3478. +
  3479. +static const struct sid_lid_device lid_device_l4F = {
  3480. + .acpi_path = "\\_SB.LID0",
  3481. + .gpe_number = 0x4F,
  3482. +};
  3483. +
  3484. +static const struct sid_lid_device lid_device_l57 = {
  3485. + .acpi_path = "\\_SB.LID0",
  3486. + .gpe_number = 0x57,
  3487. +};
  3488. +
  3489. +
  3490. +static const struct dmi_system_id dmi_lid_device_table[] = {
  3491. + {
  3492. + .ident = "Surface Pro 4",
  3493. + .matches = {
  3494. + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"),
  3495. + DMI_EXACT_MATCH(DMI_PRODUCT_NAME, "Surface Pro 4"),
  3496. + },
  3497. + .driver_data = (void *)&lid_device_l17,
  3498. + },
  3499. + {
  3500. + .ident = "Surface Pro 5",
  3501. + .matches = {
  3502. + /* match for SKU here due to generic product name "Surface Pro" */
  3503. + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"),
  3504. + DMI_EXACT_MATCH(DMI_PRODUCT_SKU, "Surface_Pro_1796"),
  3505. + },
  3506. + .driver_data = (void *)&lid_device_l4F,
  3507. + },
  3508. + {
  3509. + .ident = "Surface Pro 5 (LTE)",
  3510. + .matches = {
  3511. + /* match for SKU here due to generic product name "Surface Pro" */
  3512. + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"),
  3513. + DMI_EXACT_MATCH(DMI_PRODUCT_SKU, "Surface_Pro_1807"),
  3514. + },
  3515. + .driver_data = (void *)&lid_device_l4F,
  3516. + },
  3517. + {
  3518. + .ident = "Surface Pro 6",
  3519. + .matches = {
  3520. + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"),
  3521. + DMI_EXACT_MATCH(DMI_PRODUCT_NAME, "Surface Pro 6"),
  3522. + },
  3523. + .driver_data = (void *)&lid_device_l4F,
  3524. + },
  3525. + {
  3526. + .ident = "Surface Pro 7",
  3527. + .matches = {
  3528. + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"),
  3529. + DMI_EXACT_MATCH(DMI_PRODUCT_NAME, "Surface Pro 7"),
  3530. + },
  3531. + .driver_data = (void *)&lid_device_l4D,
  3532. + },
  3533. + {
  3534. + .ident = "Surface Book 1",
  3535. + .matches = {
  3536. + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"),
  3537. + DMI_EXACT_MATCH(DMI_PRODUCT_NAME, "Surface Book"),
  3538. + },
  3539. + .driver_data = (void *)&lid_device_l17,
  3540. + },
  3541. + {
  3542. + .ident = "Surface Book 2",
  3543. + .matches = {
  3544. + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"),
  3545. + DMI_EXACT_MATCH(DMI_PRODUCT_NAME, "Surface Book 2"),
  3546. + },
  3547. + .driver_data = (void *)&lid_device_l17,
  3548. + },
  3549. + {
  3550. + .ident = "Surface Book 3",
  3551. + .matches = {
  3552. + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"),
  3553. + DMI_EXACT_MATCH(DMI_PRODUCT_NAME, "Surface Book 3"),
  3554. + },
  3555. + .driver_data = (void *)&lid_device_l4D,
  3556. + },
  3557. + {
  3558. + .ident = "Surface Laptop 1",
  3559. + .matches = {
  3560. + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"),
  3561. + DMI_EXACT_MATCH(DMI_PRODUCT_NAME, "Surface Laptop"),
  3562. + },
  3563. + .driver_data = (void *)&lid_device_l57,
  3564. + },
  3565. + {
  3566. + .ident = "Surface Laptop 2",
  3567. + .matches = {
  3568. + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"),
  3569. + DMI_EXACT_MATCH(DMI_PRODUCT_NAME, "Surface Laptop 2"),
  3570. + },
  3571. + .driver_data = (void *)&lid_device_l57,
  3572. + },
  3573. + {
  3574. + .ident = "Surface Laptop 3 (13\")",
  3575. + .matches = {
  3576. + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"),
  3577. + DMI_EXACT_MATCH(DMI_PRODUCT_SKU, "Surface_Laptop_3_1867:1868"),
  3578. + },
  3579. + .driver_data = (void *)&lid_device_l4D,
  3580. + },
  3581. + { }
  3582. +};
  3583. +
  3584. +
  3585. +static int sid_lid_enable_wakeup(const struct sid_lid_device *dev, bool enable)
  3586. +{
  3587. + int action = enable ? ACPI_GPE_ENABLE : ACPI_GPE_DISABLE;
  3588. + int status;
  3589. +
  3590. + status = acpi_set_gpe_wake_mask(NULL, dev->gpe_number, action);
  3591. + if (status)
  3592. + return -EFAULT;
  3593. +
  3594. + return 0;
  3595. +}
  3596. +
  3597. +
  3598. +static int surface_sam_sid_gpelid_suspend(struct device *dev)
  3599. +{
  3600. + const struct sid_lid_device *ldev;
  3601. +
  3602. + ldev = dev_get_drvdata(dev);
  3603. + return sid_lid_enable_wakeup(ldev, true);
  3604. +}
  3605. +
  3606. +static int surface_sam_sid_gpelid_resume(struct device *dev)
  3607. +{
  3608. + const struct sid_lid_device *ldev;
  3609. +
  3610. + ldev = dev_get_drvdata(dev);
  3611. + return sid_lid_enable_wakeup(ldev, false);
  3612. +}
  3613. +
  3614. +static SIMPLE_DEV_PM_OPS(surface_sam_sid_gpelid_pm,
  3615. + surface_sam_sid_gpelid_suspend,
  3616. + surface_sam_sid_gpelid_resume);
  3617. +
  3618. +
  3619. +static int surface_sam_sid_gpelid_probe(struct platform_device *pdev)
  3620. +{
  3621. + const struct dmi_system_id *match;
  3622. + struct sid_lid_device *dev;
  3623. + acpi_handle lid_handle;
  3624. + int status;
  3625. +
  3626. + match = dmi_first_match(dmi_lid_device_table);
  3627. + if (!match)
  3628. + return -ENODEV;
  3629. +
  3630. + dev = match->driver_data;
  3631. + if (!dev)
  3632. + return -ENODEV;
  3633. +
  3634. + status = acpi_get_handle(NULL, (acpi_string)dev->acpi_path, &lid_handle);
  3635. + if (status)
  3636. + return -EFAULT;
  3637. +
  3638. + status = acpi_setup_gpe_for_wake(lid_handle, NULL, dev->gpe_number);
  3639. + if (status)
  3640. + return -EFAULT;
  3641. +
  3642. + status = acpi_enable_gpe(NULL, dev->gpe_number);
  3643. + if (status)
  3644. + return -EFAULT;
  3645. +
  3646. + status = sid_lid_enable_wakeup(dev, false);
  3647. + if (status) {
  3648. + acpi_disable_gpe(NULL, dev->gpe_number);
  3649. + return status;
  3650. + }
  3651. +
  3652. + platform_set_drvdata(pdev, dev);
  3653. + return 0;
  3654. +}
  3655. +
  3656. +static int surface_sam_sid_gpelid_remove(struct platform_device *pdev)
  3657. +{
  3658. + struct sid_lid_device *dev = platform_get_drvdata(pdev);
  3659. +
  3660. + /* restore default behavior without this module */
  3661. + sid_lid_enable_wakeup(dev, false);
  3662. + acpi_disable_gpe(NULL, dev->gpe_number);
  3663. +
  3664. + platform_set_drvdata(pdev, NULL);
  3665. + return 0;
  3666. +}
  3667. +
  3668. +static struct platform_driver surface_sam_sid_gpelid = {
  3669. + .probe = surface_sam_sid_gpelid_probe,
  3670. + .remove = surface_sam_sid_gpelid_remove,
  3671. + .driver = {
  3672. + .name = "surface_sam_sid_gpelid",
  3673. + .pm = &surface_sam_sid_gpelid_pm,
  3674. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  3675. + },
  3676. +};
  3677. +module_platform_driver(surface_sam_sid_gpelid);
  3678. +
  3679. +MODULE_AUTHOR("Maximilian Luz <luzmaximilian@gmail.com>");
  3680. +MODULE_DESCRIPTION("Surface Lid Driver for 5th Generation Surface Devices");
  3681. +MODULE_LICENSE("GPL");
  3682. +MODULE_ALIAS("platform:surface_sam_sid_gpelid");
  3683. diff --git a/drivers/platform/x86/surface_sam/surface_sam_sid_perfmode.c b/drivers/platform/x86/surface_sam/surface_sam_sid_perfmode.c
  3684. new file mode 100644
  3685. index 0000000000000..2e11efb166f2b
  3686. --- /dev/null
  3687. +++ b/drivers/platform/x86/surface_sam/surface_sam_sid_perfmode.c
  3688. @@ -0,0 +1,216 @@
  3689. +// SPDX-License-Identifier: GPL-2.0-or-later
  3690. +/*
  3691. + * Surface Performance Mode Driver.
  3692. + * Allows to change cooling capabilities based on user preference.
  3693. + */
  3694. +
  3695. +#include <asm/unaligned.h>
  3696. +#include <linux/kernel.h>
  3697. +#include <linux/module.h>
  3698. +#include <linux/platform_device.h>
  3699. +
  3700. +#include "surface_sam_ssh.h"
  3701. +
  3702. +
  3703. +#define SID_PARAM_PERM 0644
  3704. +
  3705. +enum sam_perf_mode {
  3706. + SAM_PERF_MODE_NORMAL = 1,
  3707. + SAM_PERF_MODE_BATTERY = 2,
  3708. + SAM_PERF_MODE_PERF1 = 3,
  3709. + SAM_PERF_MODE_PERF2 = 4,
  3710. +
  3711. + __SAM_PERF_MODE__START = 1,
  3712. + __SAM_PERF_MODE__END = 4,
  3713. +};
  3714. +
  3715. +enum sid_param_perf_mode {
  3716. + SID_PARAM_PERF_MODE_AS_IS = 0,
  3717. + SID_PARAM_PERF_MODE_NORMAL = SAM_PERF_MODE_NORMAL,
  3718. + SID_PARAM_PERF_MODE_BATTERY = SAM_PERF_MODE_BATTERY,
  3719. + SID_PARAM_PERF_MODE_PERF1 = SAM_PERF_MODE_PERF1,
  3720. + SID_PARAM_PERF_MODE_PERF2 = SAM_PERF_MODE_PERF2,
  3721. +
  3722. + __SID_PARAM_PERF_MODE__START = 0,
  3723. + __SID_PARAM_PERF_MODE__END = 4,
  3724. +};
  3725. +
  3726. +
  3727. +static int surface_sam_perf_mode_get(void)
  3728. +{
  3729. + u8 result_buf[8] = { 0 };
  3730. + int status;
  3731. +
  3732. + struct surface_sam_ssh_rqst rqst = {
  3733. + .tc = 0x03,
  3734. + .cid = 0x02,
  3735. + .iid = 0x00,
  3736. + .chn = 0x01,
  3737. + .snc = 0x01,
  3738. + .cdl = 0x00,
  3739. + .pld = NULL,
  3740. + };
  3741. +
  3742. + struct surface_sam_ssh_buf result = {
  3743. + .cap = ARRAY_SIZE(result_buf),
  3744. + .len = 0,
  3745. + .data = result_buf,
  3746. + };
  3747. +
  3748. + status = surface_sam_ssh_rqst(&rqst, &result);
  3749. + if (status)
  3750. + return status;
  3751. +
  3752. + if (result.len != 8)
  3753. + return -EFAULT;
  3754. +
  3755. + return get_unaligned_le32(&result.data[0]);
  3756. +}
  3757. +
  3758. +static int surface_sam_perf_mode_set(int perf_mode)
  3759. +{
  3760. + u8 payload[4] = { 0 };
  3761. +
  3762. + struct surface_sam_ssh_rqst rqst = {
  3763. + .tc = 0x03,
  3764. + .cid = 0x03,
  3765. + .iid = 0x00,
  3766. + .chn = 0x01,
  3767. + .snc = 0x00,
  3768. + .cdl = ARRAY_SIZE(payload),
  3769. + .pld = payload,
  3770. + };
  3771. +
  3772. + if (perf_mode < __SAM_PERF_MODE__START || perf_mode > __SAM_PERF_MODE__END)
  3773. + return -EINVAL;
  3774. +
  3775. + put_unaligned_le32(perf_mode, &rqst.pld[0]);
  3776. + return surface_sam_ssh_rqst(&rqst, NULL);
  3777. +}
  3778. +
  3779. +
  3780. +static int param_perf_mode_set(const char *val, const struct kernel_param *kp)
  3781. +{
  3782. + int perf_mode;
  3783. + int status;
  3784. +
  3785. + status = kstrtoint(val, 0, &perf_mode);
  3786. + if (status)
  3787. + return status;
  3788. +
  3789. + if (perf_mode < __SID_PARAM_PERF_MODE__START || perf_mode > __SID_PARAM_PERF_MODE__END)
  3790. + return -EINVAL;
  3791. +
  3792. + return param_set_int(val, kp);
  3793. +}
  3794. +
  3795. +static const struct kernel_param_ops param_perf_mode_ops = {
  3796. + .set = param_perf_mode_set,
  3797. + .get = param_get_int,
  3798. +};
  3799. +
  3800. +static int param_perf_mode_init = SID_PARAM_PERF_MODE_AS_IS;
  3801. +static int param_perf_mode_exit = SID_PARAM_PERF_MODE_AS_IS;
  3802. +
  3803. +module_param_cb(perf_mode_init, &param_perf_mode_ops, &param_perf_mode_init, SID_PARAM_PERM);
  3804. +module_param_cb(perf_mode_exit, &param_perf_mode_ops, &param_perf_mode_exit, SID_PARAM_PERM);
  3805. +
  3806. +MODULE_PARM_DESC(perf_mode_init, "Performance-mode to be set on module initialization");
  3807. +MODULE_PARM_DESC(perf_mode_exit, "Performance-mode to be set on module exit");
  3808. +
  3809. +
  3810. +static ssize_t perf_mode_show(struct device *dev, struct device_attribute *attr, char *data)
  3811. +{
  3812. + int perf_mode;
  3813. +
  3814. + perf_mode = surface_sam_perf_mode_get();
  3815. + if (perf_mode < 0) {
  3816. + dev_err(dev, "failed to get current performance mode: %d\n", perf_mode);
  3817. + return -EIO;
  3818. + }
  3819. +
  3820. + return sprintf(data, "%d\n", perf_mode);
  3821. +}
  3822. +
  3823. +static ssize_t perf_mode_store(struct device *dev, struct device_attribute *attr,
  3824. + const char *data, size_t count)
  3825. +{
  3826. + int perf_mode;
  3827. + int status;
  3828. +
  3829. + status = kstrtoint(data, 0, &perf_mode);
  3830. + if (status)
  3831. + return status;
  3832. +
  3833. + status = surface_sam_perf_mode_set(perf_mode);
  3834. + if (status)
  3835. + return status;
  3836. +
  3837. + // TODO: Should we notify ACPI here?
  3838. + //
  3839. + // There is a _DSM call described as
  3840. + // WSID._DSM: Notify DPTF on Slider State change
  3841. + // which calls
  3842. + // ODV3 = ToInteger (Arg3)
  3843. + // Notify(IETM, 0x88)
  3844. + // IETM is an INT3400 Intel Dynamic Power Performance Management
  3845. + // device, part of the DPTF framework. From the corresponding
  3846. + // kernel driver, it looks like event 0x88 is being ignored. Also
  3847. + // it is currently unknown what the consequecnes of setting ODV3
  3848. + // are.
  3849. +
  3850. + return count;
  3851. +}
  3852. +
  3853. +static const DEVICE_ATTR_RW(perf_mode);
  3854. +
  3855. +
  3856. +static int surface_sam_sid_perfmode_probe(struct platform_device *pdev)
  3857. +{
  3858. + int status;
  3859. +
  3860. + // link to ec
  3861. + status = surface_sam_ssh_consumer_register(&pdev->dev);
  3862. + if (status)
  3863. + return status == -ENXIO ? -EPROBE_DEFER : status;
  3864. +
  3865. + // set initial perf_mode
  3866. + if (param_perf_mode_init != SID_PARAM_PERF_MODE_AS_IS) {
  3867. + status = surface_sam_perf_mode_set(param_perf_mode_init);
  3868. + if (status)
  3869. + return status;
  3870. + }
  3871. +
  3872. + // register perf_mode attribute
  3873. + status = sysfs_create_file(&pdev->dev.kobj, &dev_attr_perf_mode.attr);
  3874. + if (status)
  3875. + goto err_sysfs;
  3876. +
  3877. + return 0;
  3878. +
  3879. +err_sysfs:
  3880. + surface_sam_perf_mode_set(param_perf_mode_exit);
  3881. + return status;
  3882. +}
  3883. +
  3884. +static int surface_sam_sid_perfmode_remove(struct platform_device *pdev)
  3885. +{
  3886. + sysfs_remove_file(&pdev->dev.kobj, &dev_attr_perf_mode.attr);
  3887. + surface_sam_perf_mode_set(param_perf_mode_exit);
  3888. + return 0;
  3889. +}
  3890. +
  3891. +static struct platform_driver surface_sam_sid_perfmode = {
  3892. + .probe = surface_sam_sid_perfmode_probe,
  3893. + .remove = surface_sam_sid_perfmode_remove,
  3894. + .driver = {
  3895. + .name = "surface_sam_sid_perfmode",
  3896. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  3897. + },
  3898. +};
  3899. +module_platform_driver(surface_sam_sid_perfmode);
  3900. +
  3901. +MODULE_AUTHOR("Maximilian Luz <luzmaximilian@gmail.com>");
  3902. +MODULE_DESCRIPTION("Surface Performance Mode Driver for 5th Generation Surface Devices");
  3903. +MODULE_LICENSE("GPL");
  3904. +MODULE_ALIAS("platform:surface_sam_sid_perfmode");
  3905. diff --git a/drivers/platform/x86/surface_sam/surface_sam_sid_power.c b/drivers/platform/x86/surface_sam/surface_sam_sid_power.c
  3906. new file mode 100644
  3907. index 0000000000000..1d945c0a911a4
  3908. --- /dev/null
  3909. +++ b/drivers/platform/x86/surface_sam/surface_sam_sid_power.c
  3910. @@ -0,0 +1,1154 @@
  3911. +// SPDX-License-Identifier: GPL-2.0-or-later
  3912. +/*
  3913. + * Surface SID Battery/AC Driver.
  3914. + * Provides support for the battery and AC on 7th generation Surface devices.
  3915. + */
  3916. +
  3917. +#include <linux/kernel.h>
  3918. +#include <linux/delay.h>
  3919. +#include <linux/jiffies.h>
  3920. +#include <linux/module.h>
  3921. +#include <linux/platform_device.h>
  3922. +#include <linux/power_supply.h>
  3923. +#include <linux/workqueue.h>
  3924. +
  3925. +#include "surface_sam_ssh.h"
  3926. +#include "surface_sam_sid_power.h"
  3927. +
  3928. +#define SPWR_WARN KERN_WARNING KBUILD_MODNAME ": "
  3929. +#define SPWR_DEBUG KERN_DEBUG KBUILD_MODNAME ": "
  3930. +
  3931. +
  3932. +// TODO: check BIX/BST for unknown/unsupported 0xffffffff entries
  3933. +// TODO: DPTF (/SAN notifications)?
  3934. +// TODO: other properties?
  3935. +
  3936. +
  3937. +static unsigned int cache_time = 1000;
  3938. +module_param(cache_time, uint, 0644);
  3939. +MODULE_PARM_DESC(cache_time, "battery state chaching time in milliseconds [default: 1000]");
  3940. +
  3941. +#define SPWR_AC_BAT_UPDATE_DELAY msecs_to_jiffies(5000)
  3942. +
  3943. +
  3944. +/*
  3945. + * SAM Interface.
  3946. + */
  3947. +
  3948. +#define SAM_PWR_TC 0x02
  3949. +
  3950. +#define SAM_RQST_PWR_CID_STA 0x01
  3951. +#define SAM_RQST_PWR_CID_BIX 0x02
  3952. +#define SAM_RQST_PWR_CID_BST 0x03
  3953. +#define SAM_RQST_PWR_CID_BTP 0x04
  3954. +
  3955. +#define SAM_RQST_PWR_CID_PMAX 0x0b
  3956. +#define SAM_RQST_PWR_CID_PSOC 0x0c
  3957. +#define SAM_RQST_PWR_CID_PSRC 0x0d
  3958. +#define SAM_RQST_PWR_CID_CHGI 0x0e
  3959. +#define SAM_RQST_PWR_CID_ARTG 0x0f
  3960. +
  3961. +#define SAM_EVENT_PWR_CID_BIX 0x15
  3962. +#define SAM_EVENT_PWR_CID_BST 0x16
  3963. +#define SAM_EVENT_PWR_CID_ADAPTER 0x17
  3964. +
  3965. +#define SAM_BATTERY_STA_OK 0x0f
  3966. +#define SAM_BATTERY_STA_PRESENT 0x10
  3967. +
  3968. +#define SAM_BATTERY_STATE_DISCHARGING 0x01
  3969. +#define SAM_BATTERY_STATE_CHARGING 0x02
  3970. +#define SAM_BATTERY_STATE_CRITICAL 0x04
  3971. +
  3972. +#define SAM_BATTERY_POWER_UNIT_MA 1
  3973. +
  3974. +
  3975. +/* Equivalent to data returned in ACPI _BIX method */
  3976. +struct spwr_bix {
  3977. + u8 revision;
  3978. + u32 power_unit;
  3979. + u32 design_cap;
  3980. + u32 last_full_charge_cap;
  3981. + u32 technology;
  3982. + u32 design_voltage;
  3983. + u32 design_cap_warn;
  3984. + u32 design_cap_low;
  3985. + u32 cycle_count;
  3986. + u32 measurement_accuracy;
  3987. + u32 max_sampling_time;
  3988. + u32 min_sampling_time;
  3989. + u32 max_avg_interval;
  3990. + u32 min_avg_interval;
  3991. + u32 bat_cap_granularity_1;
  3992. + u32 bat_cap_granularity_2;
  3993. + u8 model[21];
  3994. + u8 serial[11];
  3995. + u8 type[5];
  3996. + u8 oem_info[21];
  3997. +} __packed;
  3998. +
  3999. +/* Equivalent to data returned in ACPI _BST method */
  4000. +struct spwr_bst {
  4001. + u32 state;
  4002. + u32 present_rate;
  4003. + u32 remaining_cap;
  4004. + u32 present_voltage;
  4005. +} __packed;
  4006. +
  4007. +/* DPTF event payload */
  4008. +struct spwr_event_dptf {
  4009. + u32 pmax;
  4010. + u32 _1; /* currently unknown */
  4011. + u32 _2; /* currently unknown */
  4012. +} __packed;
  4013. +
  4014. +
  4015. +/* Get battery status (_STA) */
  4016. +static int sam_psy_get_sta(u8 channel, u8 instance, u32 *sta)
  4017. +{
  4018. + struct surface_sam_ssh_rqst rqst;
  4019. + struct surface_sam_ssh_buf result;
  4020. +
  4021. + rqst.tc = SAM_PWR_TC;
  4022. + rqst.cid = SAM_RQST_PWR_CID_STA;
  4023. + rqst.iid = instance;
  4024. + rqst.chn = channel;
  4025. + rqst.snc = 0x01;
  4026. + rqst.cdl = 0x00;
  4027. + rqst.pld = NULL;
  4028. +
  4029. + result.cap = sizeof(u32);
  4030. + result.len = 0;
  4031. + result.data = (u8 *)sta;
  4032. +
  4033. + return surface_sam_ssh_rqst(&rqst, &result);
  4034. +}
  4035. +
  4036. +/* Get battery static information (_BIX) */
  4037. +static int sam_psy_get_bix(u8 channel, u8 instance, struct spwr_bix *bix)
  4038. +{
  4039. + struct surface_sam_ssh_rqst rqst;
  4040. + struct surface_sam_ssh_buf result;
  4041. +
  4042. + rqst.tc = SAM_PWR_TC;
  4043. + rqst.cid = SAM_RQST_PWR_CID_BIX;
  4044. + rqst.iid = instance;
  4045. + rqst.chn = channel;
  4046. + rqst.snc = 0x01;
  4047. + rqst.cdl = 0x00;
  4048. + rqst.pld = NULL;
  4049. +
  4050. + result.cap = sizeof(struct spwr_bix);
  4051. + result.len = 0;
  4052. + result.data = (u8 *)bix;
  4053. +
  4054. + return surface_sam_ssh_rqst(&rqst, &result);
  4055. +}
  4056. +
  4057. +/* Get battery dynamic information (_BST) */
  4058. +static int sam_psy_get_bst(u8 channel, u8 instance, struct spwr_bst *bst)
  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_BST;
  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(struct spwr_bst);
  4072. + result.len = 0;
  4073. + result.data = (u8 *)bst;
  4074. +
  4075. + return surface_sam_ssh_rqst(&rqst, &result);
  4076. +}
  4077. +
  4078. +/* Set battery trip point (_BTP) */
  4079. +static int sam_psy_set_btp(u8 channel, u8 instance, u32 btp)
  4080. +{
  4081. + struct surface_sam_ssh_rqst rqst;
  4082. +
  4083. + rqst.tc = SAM_PWR_TC;
  4084. + rqst.cid = SAM_RQST_PWR_CID_BTP;
  4085. + rqst.iid = instance;
  4086. + rqst.chn = channel;
  4087. + rqst.snc = 0x00;
  4088. + rqst.cdl = sizeof(u32);
  4089. + rqst.pld = (u8 *)&btp;
  4090. +
  4091. + return surface_sam_ssh_rqst(&rqst, NULL);
  4092. +}
  4093. +
  4094. +/* Get platform power soruce for battery (DPTF PSRC) */
  4095. +static int sam_psy_get_psrc(u8 channel, u8 instance, u32 *psrc)
  4096. +{
  4097. + struct surface_sam_ssh_rqst rqst;
  4098. + struct surface_sam_ssh_buf result;
  4099. +
  4100. + rqst.tc = SAM_PWR_TC;
  4101. + rqst.cid = SAM_RQST_PWR_CID_PSRC;
  4102. + rqst.iid = instance;
  4103. + rqst.chn = channel;
  4104. + rqst.snc = 0x01;
  4105. + rqst.cdl = 0x00;
  4106. + rqst.pld = NULL;
  4107. +
  4108. + result.cap = sizeof(u32);
  4109. + result.len = 0;
  4110. + result.data = (u8 *)psrc;
  4111. +
  4112. + return surface_sam_ssh_rqst(&rqst, &result);
  4113. +}
  4114. +
  4115. +/* Get maximum platform power for battery (DPTF PMAX) */
  4116. +__always_unused
  4117. +static int sam_psy_get_pmax(u8 channel, u8 instance, u32 *pmax)
  4118. +{
  4119. + struct surface_sam_ssh_rqst rqst;
  4120. + struct surface_sam_ssh_buf result;
  4121. +
  4122. + rqst.tc = SAM_PWR_TC;
  4123. + rqst.cid = SAM_RQST_PWR_CID_PMAX;
  4124. + rqst.iid = instance;
  4125. + rqst.chn = channel;
  4126. + rqst.snc = 0x01;
  4127. + rqst.cdl = 0x00;
  4128. + rqst.pld = NULL;
  4129. +
  4130. + result.cap = sizeof(u32);
  4131. + result.len = 0;
  4132. + result.data = (u8 *)pmax;
  4133. +
  4134. + return surface_sam_ssh_rqst(&rqst, &result);
  4135. +}
  4136. +
  4137. +/* Get adapter rating (DPTF ARTG) */
  4138. +__always_unused
  4139. +static int sam_psy_get_artg(u8 channel, u8 instance, u32 *artg)
  4140. +{
  4141. + struct surface_sam_ssh_rqst rqst;
  4142. + struct surface_sam_ssh_buf result;
  4143. +
  4144. + rqst.tc = SAM_PWR_TC;
  4145. + rqst.cid = SAM_RQST_PWR_CID_ARTG;
  4146. + rqst.iid = instance;
  4147. + rqst.chn = channel;
  4148. + rqst.snc = 0x01;
  4149. + rqst.cdl = 0x00;
  4150. + rqst.pld = NULL;
  4151. +
  4152. + result.cap = sizeof(u32);
  4153. + result.len = 0;
  4154. + result.data = (u8 *)artg;
  4155. +
  4156. + return surface_sam_ssh_rqst(&rqst, &result);
  4157. +}
  4158. +
  4159. +/* Unknown (DPTF PSOC) */
  4160. +__always_unused
  4161. +static int sam_psy_get_psoc(u8 channel, u8 instance, u32 *psoc)
  4162. +{
  4163. + struct surface_sam_ssh_rqst rqst;
  4164. + struct surface_sam_ssh_buf result;
  4165. +
  4166. + rqst.tc = SAM_PWR_TC;
  4167. + rqst.cid = SAM_RQST_PWR_CID_PSOC;
  4168. + rqst.iid = instance;
  4169. + rqst.chn = channel;
  4170. + rqst.snc = 0x01;
  4171. + rqst.cdl = 0x00;
  4172. + rqst.pld = NULL;
  4173. +
  4174. + result.cap = sizeof(u32);
  4175. + result.len = 0;
  4176. + result.data = (u8 *)psoc;
  4177. +
  4178. + return surface_sam_ssh_rqst(&rqst, &result);
  4179. +}
  4180. +
  4181. +/* Unknown (DPTF CHGI/ INT3403 SPPC) */
  4182. +__always_unused
  4183. +static int sam_psy_set_chgi(u8 channel, u8 instance, u32 chgi)
  4184. +{
  4185. + struct surface_sam_ssh_rqst rqst;
  4186. +
  4187. + rqst.tc = SAM_PWR_TC;
  4188. + rqst.cid = SAM_RQST_PWR_CID_CHGI;
  4189. + rqst.iid = instance;
  4190. + rqst.chn = channel;
  4191. + rqst.snc = 0x00;
  4192. + rqst.cdl = sizeof(u32);
  4193. + rqst.pld = (u8 *)&chgi;
  4194. +
  4195. + return surface_sam_ssh_rqst(&rqst, NULL);
  4196. +}
  4197. +
  4198. +
  4199. +/*
  4200. + * Common Power-Subsystem Interface.
  4201. + */
  4202. +
  4203. +struct spwr_battery_device {
  4204. + struct platform_device *pdev;
  4205. + const struct ssam_battery_properties *p;
  4206. +
  4207. + char name[32];
  4208. + struct power_supply *psy;
  4209. + struct power_supply_desc psy_desc;
  4210. +
  4211. + struct delayed_work update_work;
  4212. +
  4213. + struct ssam_event_notifier notif;
  4214. +
  4215. + struct mutex lock;
  4216. + unsigned long timestamp;
  4217. +
  4218. + u32 sta;
  4219. + struct spwr_bix bix;
  4220. + struct spwr_bst bst;
  4221. + u32 alarm;
  4222. +};
  4223. +
  4224. +struct spwr_ac_device {
  4225. + struct platform_device *pdev;
  4226. +
  4227. + char name[32];
  4228. + struct power_supply *psy;
  4229. + struct power_supply_desc psy_desc;
  4230. +
  4231. + struct ssam_event_notifier notif;
  4232. +
  4233. + struct mutex lock;
  4234. +
  4235. + u32 state;
  4236. +};
  4237. +
  4238. +static enum power_supply_property spwr_ac_props[] = {
  4239. + POWER_SUPPLY_PROP_ONLINE,
  4240. +};
  4241. +
  4242. +static enum power_supply_property spwr_battery_props_chg[] = {
  4243. + POWER_SUPPLY_PROP_STATUS,
  4244. + POWER_SUPPLY_PROP_PRESENT,
  4245. + POWER_SUPPLY_PROP_TECHNOLOGY,
  4246. + POWER_SUPPLY_PROP_CYCLE_COUNT,
  4247. + POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN,
  4248. + POWER_SUPPLY_PROP_VOLTAGE_NOW,
  4249. + POWER_SUPPLY_PROP_CURRENT_NOW,
  4250. + POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN,
  4251. + POWER_SUPPLY_PROP_CHARGE_FULL,
  4252. + POWER_SUPPLY_PROP_CHARGE_NOW,
  4253. + POWER_SUPPLY_PROP_CAPACITY,
  4254. + POWER_SUPPLY_PROP_CAPACITY_LEVEL,
  4255. + POWER_SUPPLY_PROP_MODEL_NAME,
  4256. + POWER_SUPPLY_PROP_MANUFACTURER,
  4257. + POWER_SUPPLY_PROP_SERIAL_NUMBER,
  4258. +};
  4259. +
  4260. +static enum power_supply_property spwr_battery_props_eng[] = {
  4261. + POWER_SUPPLY_PROP_STATUS,
  4262. + POWER_SUPPLY_PROP_PRESENT,
  4263. + POWER_SUPPLY_PROP_TECHNOLOGY,
  4264. + POWER_SUPPLY_PROP_CYCLE_COUNT,
  4265. + POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN,
  4266. + POWER_SUPPLY_PROP_VOLTAGE_NOW,
  4267. + POWER_SUPPLY_PROP_POWER_NOW,
  4268. + POWER_SUPPLY_PROP_ENERGY_FULL_DESIGN,
  4269. + POWER_SUPPLY_PROP_ENERGY_FULL,
  4270. + POWER_SUPPLY_PROP_ENERGY_NOW,
  4271. + POWER_SUPPLY_PROP_CAPACITY,
  4272. + POWER_SUPPLY_PROP_CAPACITY_LEVEL,
  4273. + POWER_SUPPLY_PROP_MODEL_NAME,
  4274. + POWER_SUPPLY_PROP_MANUFACTURER,
  4275. + POWER_SUPPLY_PROP_SERIAL_NUMBER,
  4276. +};
  4277. +
  4278. +
  4279. +static int spwr_battery_register(struct spwr_battery_device *bat,
  4280. + struct platform_device *pdev,
  4281. + const struct ssam_battery_properties *p);
  4282. +
  4283. +static void spwr_battery_unregister(struct spwr_battery_device *bat);
  4284. +
  4285. +
  4286. +static inline bool spwr_battery_present(struct spwr_battery_device *bat)
  4287. +{
  4288. + return bat->sta & SAM_BATTERY_STA_PRESENT;
  4289. +}
  4290. +
  4291. +
  4292. +static inline int spwr_battery_load_sta(struct spwr_battery_device *bat)
  4293. +{
  4294. + return sam_psy_get_sta(bat->p->channel, bat->p->instance, &bat->sta);
  4295. +}
  4296. +
  4297. +static inline int spwr_battery_load_bix(struct spwr_battery_device *bat)
  4298. +{
  4299. + if (!spwr_battery_present(bat))
  4300. + return 0;
  4301. +
  4302. + return sam_psy_get_bix(bat->p->channel, bat->p->instance, &bat->bix);
  4303. +}
  4304. +
  4305. +static inline int spwr_battery_load_bst(struct spwr_battery_device *bat)
  4306. +{
  4307. + if (!spwr_battery_present(bat))
  4308. + return 0;
  4309. +
  4310. + return sam_psy_get_bst(bat->p->channel, bat->p->instance, &bat->bst);
  4311. +}
  4312. +
  4313. +
  4314. +static inline int spwr_battery_set_alarm_unlocked(struct spwr_battery_device *bat, u32 value)
  4315. +{
  4316. + bat->alarm = value;
  4317. + return sam_psy_set_btp(bat->p->channel, bat->p->instance, bat->alarm);
  4318. +}
  4319. +
  4320. +static inline int spwr_battery_set_alarm(struct spwr_battery_device *bat, u32 value)
  4321. +{
  4322. + int status;
  4323. +
  4324. + mutex_lock(&bat->lock);
  4325. + status = spwr_battery_set_alarm_unlocked(bat, value);
  4326. + mutex_unlock(&bat->lock);
  4327. +
  4328. + return status;
  4329. +}
  4330. +
  4331. +static inline int spwr_battery_update_bst_unlocked(struct spwr_battery_device *bat, bool cached)
  4332. +{
  4333. + unsigned long cache_deadline = bat->timestamp + msecs_to_jiffies(cache_time);
  4334. + int status;
  4335. +
  4336. + if (cached && bat->timestamp && time_is_after_jiffies(cache_deadline))
  4337. + return 0;
  4338. +
  4339. + status = spwr_battery_load_sta(bat);
  4340. + if (status)
  4341. + return status;
  4342. +
  4343. + status = spwr_battery_load_bst(bat);
  4344. + if (status)
  4345. + return status;
  4346. +
  4347. + bat->timestamp = jiffies;
  4348. + return 0;
  4349. +}
  4350. +
  4351. +static int spwr_battery_update_bst(struct spwr_battery_device *bat, bool cached)
  4352. +{
  4353. + int status;
  4354. +
  4355. + mutex_lock(&bat->lock);
  4356. + status = spwr_battery_update_bst_unlocked(bat, cached);
  4357. + mutex_unlock(&bat->lock);
  4358. +
  4359. + return status;
  4360. +}
  4361. +
  4362. +static inline int spwr_battery_update_bix_unlocked(struct spwr_battery_device *bat)
  4363. +{
  4364. + int status;
  4365. +
  4366. + status = spwr_battery_load_sta(bat);
  4367. + if (status)
  4368. + return status;
  4369. +
  4370. + status = spwr_battery_load_bix(bat);
  4371. + if (status)
  4372. + return status;
  4373. +
  4374. + status = spwr_battery_load_bst(bat);
  4375. + if (status)
  4376. + return status;
  4377. +
  4378. + bat->timestamp = jiffies;
  4379. + return 0;
  4380. +}
  4381. +
  4382. +static int spwr_battery_update_bix(struct spwr_battery_device *bat)
  4383. +{
  4384. + int status;
  4385. +
  4386. + mutex_lock(&bat->lock);
  4387. + status = spwr_battery_update_bix_unlocked(bat);
  4388. + mutex_unlock(&bat->lock);
  4389. +
  4390. + return status;
  4391. +}
  4392. +
  4393. +static inline int spwr_ac_update_unlocked(struct spwr_ac_device *ac)
  4394. +{
  4395. + return sam_psy_get_psrc(0x01, 0x01, &ac->state);
  4396. +}
  4397. +
  4398. +static int spwr_ac_update(struct spwr_ac_device *ac)
  4399. +{
  4400. + int status;
  4401. +
  4402. + mutex_lock(&ac->lock);
  4403. + status = spwr_ac_update_unlocked(ac);
  4404. + mutex_unlock(&ac->lock);
  4405. +
  4406. + return status;
  4407. +}
  4408. +
  4409. +
  4410. +static int spwr_battery_recheck(struct spwr_battery_device *bat)
  4411. +{
  4412. + bool present = spwr_battery_present(bat);
  4413. + u32 unit = bat->bix.power_unit;
  4414. + int status;
  4415. +
  4416. + status = spwr_battery_update_bix(bat);
  4417. + if (status)
  4418. + return status;
  4419. +
  4420. + // if battery has been attached, (re-)initialize alarm
  4421. + if (!present && spwr_battery_present(bat)) {
  4422. + status = spwr_battery_set_alarm(bat, bat->bix.design_cap_warn);
  4423. + if (status)
  4424. + return status;
  4425. + }
  4426. +
  4427. + // if the unit has changed, re-add the battery
  4428. + if (unit != bat->bix.power_unit) {
  4429. + spwr_battery_unregister(bat);
  4430. + status = spwr_battery_register(bat, bat->pdev, bat->p);
  4431. + }
  4432. +
  4433. + return status;
  4434. +}
  4435. +
  4436. +
  4437. +static inline int spwr_notify_bix(struct spwr_battery_device *bat)
  4438. +{
  4439. + int status;
  4440. +
  4441. + status = spwr_battery_recheck(bat);
  4442. + if (!status)
  4443. + power_supply_changed(bat->psy);
  4444. +
  4445. + return status;
  4446. +}
  4447. +
  4448. +static inline int spwr_notify_bst(struct spwr_battery_device *bat)
  4449. +{
  4450. + int status;
  4451. +
  4452. + status = spwr_battery_update_bst(bat, false);
  4453. + if (!status)
  4454. + power_supply_changed(bat->psy);
  4455. +
  4456. + return status;
  4457. +}
  4458. +
  4459. +static inline int spwr_notify_adapter_bat(struct spwr_battery_device *bat)
  4460. +{
  4461. + /*
  4462. + * Handle battery update quirk:
  4463. + * When the battery is fully charged and the adapter is plugged in or
  4464. + * removed, the EC does not send a separate event for the state
  4465. + * (charging/discharging) change. Furthermore it may take some time until
  4466. + * the state is updated on the battery. Schedule an update to solve this.
  4467. + */
  4468. +
  4469. + if (bat->bst.remaining_cap >= bat->bix.last_full_charge_cap)
  4470. + schedule_delayed_work(&bat->update_work, SPWR_AC_BAT_UPDATE_DELAY);
  4471. +
  4472. + return 0;
  4473. +}
  4474. +
  4475. +static inline int spwr_notify_adapter_ac(struct spwr_ac_device *ac)
  4476. +{
  4477. + int status;
  4478. +
  4479. + status = spwr_ac_update(ac);
  4480. + if (!status)
  4481. + power_supply_changed(ac->psy);
  4482. +
  4483. + return status;
  4484. +}
  4485. +
  4486. +static u32 spwr_notify_bat(struct ssam_notifier_block *nb, const struct ssam_event *event)
  4487. +{
  4488. + struct spwr_battery_device *bat = container_of(nb, struct spwr_battery_device, notif.base);
  4489. + int status;
  4490. +
  4491. + dev_dbg(&bat->pdev->dev, "power event (cid = 0x%02x, iid = %d, chn = %d)\n",
  4492. + event->command_id, event->instance_id, event->channel);
  4493. +
  4494. + // handled here, needs to be handled for all channels/instances
  4495. + if (event->command_id == SAM_EVENT_PWR_CID_ADAPTER) {
  4496. + status = spwr_notify_adapter_bat(bat);
  4497. + return ssam_notifier_from_errno(status) | SSAM_NOTIF_HANDLED;
  4498. + }
  4499. +
  4500. + // check for the correct channel and instance ID
  4501. + if (event->channel != bat->p->channel)
  4502. + return 0;
  4503. +
  4504. + if (event->instance_id != bat->p->instance)
  4505. + return 0;
  4506. +
  4507. + switch (event->command_id) {
  4508. + case SAM_EVENT_PWR_CID_BIX:
  4509. + status = spwr_notify_bix(bat);
  4510. + break;
  4511. +
  4512. + case SAM_EVENT_PWR_CID_BST:
  4513. + status = spwr_notify_bst(bat);
  4514. + break;
  4515. +
  4516. + default:
  4517. + return 0;
  4518. + }
  4519. +
  4520. + return ssam_notifier_from_errno(status) | SSAM_NOTIF_HANDLED;
  4521. +}
  4522. +
  4523. +static u32 spwr_notify_ac(struct ssam_notifier_block *nb, const struct ssam_event *event)
  4524. +{
  4525. + struct spwr_ac_device *ac = container_of(nb, struct spwr_ac_device, notif.base);
  4526. + int status;
  4527. +
  4528. + dev_dbg(&ac->pdev->dev, "power event (cid = 0x%02x, iid = %d, chn = %d)\n",
  4529. + event->command_id, event->instance_id, event->channel);
  4530. +
  4531. + // AC has IID = 0
  4532. + if (event->instance_id != 0)
  4533. + return 0;
  4534. +
  4535. + switch (event->command_id) {
  4536. + case SAM_EVENT_PWR_CID_ADAPTER:
  4537. + status = spwr_notify_adapter_ac(ac);
  4538. + return ssam_notifier_from_errno(status) | SSAM_NOTIF_HANDLED;
  4539. +
  4540. + default:
  4541. + return 0;
  4542. + }
  4543. +}
  4544. +
  4545. +static void spwr_battery_update_bst_workfn(struct work_struct *work)
  4546. +{
  4547. + struct delayed_work *dwork = to_delayed_work(work);
  4548. + struct spwr_battery_device *bat = container_of(dwork, struct spwr_battery_device, update_work);
  4549. + int status;
  4550. +
  4551. + status = spwr_battery_update_bst(bat, false);
  4552. + if (!status)
  4553. + power_supply_changed(bat->psy);
  4554. +
  4555. + if (status)
  4556. + dev_err(&bat->pdev->dev, "failed to update battery state: %d\n", status);
  4557. +}
  4558. +
  4559. +
  4560. +static inline int spwr_battery_prop_status(struct spwr_battery_device *bat)
  4561. +{
  4562. + if (bat->bst.state & SAM_BATTERY_STATE_DISCHARGING)
  4563. + return POWER_SUPPLY_STATUS_DISCHARGING;
  4564. +
  4565. + if (bat->bst.state & SAM_BATTERY_STATE_CHARGING)
  4566. + return POWER_SUPPLY_STATUS_CHARGING;
  4567. +
  4568. + if (bat->bix.last_full_charge_cap == bat->bst.remaining_cap)
  4569. + return POWER_SUPPLY_STATUS_FULL;
  4570. +
  4571. + if (bat->bst.present_rate == 0)
  4572. + return POWER_SUPPLY_STATUS_NOT_CHARGING;
  4573. +
  4574. + return POWER_SUPPLY_STATUS_UNKNOWN;
  4575. +}
  4576. +
  4577. +static inline int spwr_battery_prop_technology(struct spwr_battery_device *bat)
  4578. +{
  4579. + if (!strcasecmp("NiCd", bat->bix.type))
  4580. + return POWER_SUPPLY_TECHNOLOGY_NiCd;
  4581. +
  4582. + if (!strcasecmp("NiMH", bat->bix.type))
  4583. + return POWER_SUPPLY_TECHNOLOGY_NiMH;
  4584. +
  4585. + if (!strcasecmp("LION", bat->bix.type))
  4586. + return POWER_SUPPLY_TECHNOLOGY_LION;
  4587. +
  4588. + if (!strncasecmp("LI-ION", bat->bix.type, 6))
  4589. + return POWER_SUPPLY_TECHNOLOGY_LION;
  4590. +
  4591. + if (!strcasecmp("LiP", bat->bix.type))
  4592. + return POWER_SUPPLY_TECHNOLOGY_LIPO;
  4593. +
  4594. + return POWER_SUPPLY_TECHNOLOGY_UNKNOWN;
  4595. +}
  4596. +
  4597. +static inline int spwr_battery_prop_capacity(struct spwr_battery_device *bat)
  4598. +{
  4599. + if (bat->bst.remaining_cap && bat->bix.last_full_charge_cap)
  4600. + return bat->bst.remaining_cap * 100 / bat->bix.last_full_charge_cap;
  4601. + else
  4602. + return 0;
  4603. +}
  4604. +
  4605. +static inline int spwr_battery_prop_capacity_level(struct spwr_battery_device *bat)
  4606. +{
  4607. + if (bat->bst.state & SAM_BATTERY_STATE_CRITICAL)
  4608. + return POWER_SUPPLY_CAPACITY_LEVEL_CRITICAL;
  4609. +
  4610. + if (bat->bst.remaining_cap >= bat->bix.last_full_charge_cap)
  4611. + return POWER_SUPPLY_CAPACITY_LEVEL_FULL;
  4612. +
  4613. + if (bat->bst.remaining_cap <= bat->alarm)
  4614. + return POWER_SUPPLY_CAPACITY_LEVEL_LOW;
  4615. +
  4616. + return POWER_SUPPLY_CAPACITY_LEVEL_NORMAL;
  4617. +}
  4618. +
  4619. +static int spwr_ac_get_property(struct power_supply *psy,
  4620. + enum power_supply_property psp,
  4621. + union power_supply_propval *val)
  4622. +{
  4623. + struct spwr_ac_device *ac = power_supply_get_drvdata(psy);
  4624. + int status;
  4625. +
  4626. + mutex_lock(&ac->lock);
  4627. +
  4628. + status = spwr_ac_update_unlocked(ac);
  4629. + if (status)
  4630. + goto out;
  4631. +
  4632. + switch (psp) {
  4633. + case POWER_SUPPLY_PROP_ONLINE:
  4634. + val->intval = ac->state == 1;
  4635. + break;
  4636. +
  4637. + default:
  4638. + status = -EINVAL;
  4639. + goto out;
  4640. + }
  4641. +
  4642. +out:
  4643. + mutex_unlock(&ac->lock);
  4644. + return status;
  4645. +}
  4646. +
  4647. +static int spwr_battery_get_property(struct power_supply *psy,
  4648. + enum power_supply_property psp,
  4649. + union power_supply_propval *val)
  4650. +{
  4651. + struct spwr_battery_device *bat = power_supply_get_drvdata(psy);
  4652. + int status;
  4653. +
  4654. + mutex_lock(&bat->lock);
  4655. +
  4656. + status = spwr_battery_update_bst_unlocked(bat, true);
  4657. + if (status)
  4658. + goto out;
  4659. +
  4660. + // abort if battery is not present
  4661. + if (!spwr_battery_present(bat) && psp != POWER_SUPPLY_PROP_PRESENT) {
  4662. + status = -ENODEV;
  4663. + goto out;
  4664. + }
  4665. +
  4666. + switch (psp) {
  4667. + case POWER_SUPPLY_PROP_STATUS:
  4668. + val->intval = spwr_battery_prop_status(bat);
  4669. + break;
  4670. +
  4671. + case POWER_SUPPLY_PROP_PRESENT:
  4672. + val->intval = spwr_battery_present(bat);
  4673. + break;
  4674. +
  4675. + case POWER_SUPPLY_PROP_TECHNOLOGY:
  4676. + val->intval = spwr_battery_prop_technology(bat);
  4677. + break;
  4678. +
  4679. + case POWER_SUPPLY_PROP_CYCLE_COUNT:
  4680. + val->intval = bat->bix.cycle_count;
  4681. + break;
  4682. +
  4683. + case POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN:
  4684. + val->intval = bat->bix.design_voltage * 1000;
  4685. + break;
  4686. +
  4687. + case POWER_SUPPLY_PROP_VOLTAGE_NOW:
  4688. + val->intval = bat->bst.present_voltage * 1000;
  4689. + break;
  4690. +
  4691. + case POWER_SUPPLY_PROP_CURRENT_NOW:
  4692. + case POWER_SUPPLY_PROP_POWER_NOW:
  4693. + val->intval = bat->bst.present_rate * 1000;
  4694. + break;
  4695. +
  4696. + case POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN:
  4697. + case POWER_SUPPLY_PROP_ENERGY_FULL_DESIGN:
  4698. + val->intval = bat->bix.design_cap * 1000;
  4699. + break;
  4700. +
  4701. + case POWER_SUPPLY_PROP_CHARGE_FULL:
  4702. + case POWER_SUPPLY_PROP_ENERGY_FULL:
  4703. + val->intval = bat->bix.last_full_charge_cap * 1000;
  4704. + break;
  4705. +
  4706. + case POWER_SUPPLY_PROP_CHARGE_NOW:
  4707. + case POWER_SUPPLY_PROP_ENERGY_NOW:
  4708. + val->intval = bat->bst.remaining_cap * 1000;
  4709. + break;
  4710. +
  4711. + case POWER_SUPPLY_PROP_CAPACITY:
  4712. + val->intval = spwr_battery_prop_capacity(bat);
  4713. + break;
  4714. +
  4715. + case POWER_SUPPLY_PROP_CAPACITY_LEVEL:
  4716. + val->intval = spwr_battery_prop_capacity_level(bat);
  4717. + break;
  4718. +
  4719. + case POWER_SUPPLY_PROP_MODEL_NAME:
  4720. + val->strval = bat->bix.model;
  4721. + break;
  4722. +
  4723. + case POWER_SUPPLY_PROP_MANUFACTURER:
  4724. + val->strval = bat->bix.oem_info;
  4725. + break;
  4726. +
  4727. + case POWER_SUPPLY_PROP_SERIAL_NUMBER:
  4728. + val->strval = bat->bix.serial;
  4729. + break;
  4730. +
  4731. + default:
  4732. + status = -EINVAL;
  4733. + goto out;
  4734. + }
  4735. +
  4736. +out:
  4737. + mutex_unlock(&bat->lock);
  4738. + return status;
  4739. +}
  4740. +
  4741. +
  4742. +static ssize_t spwr_battery_alarm_show(struct device *dev,
  4743. + struct device_attribute *attr,
  4744. + char *buf)
  4745. +{
  4746. + struct power_supply *psy = dev_get_drvdata(dev);
  4747. + struct spwr_battery_device *bat = power_supply_get_drvdata(psy);
  4748. +
  4749. + return sprintf(buf, "%d\n", bat->alarm * 1000);
  4750. +}
  4751. +
  4752. +static ssize_t spwr_battery_alarm_store(struct device *dev,
  4753. + struct device_attribute *attr,
  4754. + const char *buf, size_t count)
  4755. +{
  4756. + struct power_supply *psy = dev_get_drvdata(dev);
  4757. + struct spwr_battery_device *bat = power_supply_get_drvdata(psy);
  4758. + unsigned long value;
  4759. + int status;
  4760. +
  4761. + status = kstrtoul(buf, 0, &value);
  4762. + if (status)
  4763. + return status;
  4764. +
  4765. + if (!spwr_battery_present(bat))
  4766. + return -ENODEV;
  4767. +
  4768. + status = spwr_battery_set_alarm(bat, value / 1000);
  4769. + if (status)
  4770. + return status;
  4771. +
  4772. + return count;
  4773. +}
  4774. +
  4775. +static const struct device_attribute alarm_attr = {
  4776. + .attr = {.name = "alarm", .mode = 0644},
  4777. + .show = spwr_battery_alarm_show,
  4778. + .store = spwr_battery_alarm_store,
  4779. +};
  4780. +
  4781. +
  4782. +static int spwr_ac_register(struct spwr_ac_device *ac, struct platform_device *pdev)
  4783. +{
  4784. + struct power_supply_config psy_cfg = {};
  4785. + u32 sta;
  4786. + int status;
  4787. +
  4788. + // make sure the device is there and functioning properly
  4789. + status = sam_psy_get_sta(0x01, 0x01, &sta);
  4790. + if (status)
  4791. + return status;
  4792. +
  4793. + if ((sta & SAM_BATTERY_STA_OK) != SAM_BATTERY_STA_OK)
  4794. + return -ENODEV;
  4795. +
  4796. + psy_cfg.drv_data = ac;
  4797. +
  4798. + ac->pdev = pdev;
  4799. + mutex_init(&ac->lock);
  4800. +
  4801. + snprintf(ac->name, ARRAY_SIZE(ac->name), "ADP0");
  4802. +
  4803. + ac->psy_desc.name = ac->name;
  4804. + ac->psy_desc.type = POWER_SUPPLY_TYPE_MAINS;
  4805. + ac->psy_desc.properties = spwr_ac_props;
  4806. + ac->psy_desc.num_properties = ARRAY_SIZE(spwr_ac_props);
  4807. + ac->psy_desc.get_property = spwr_ac_get_property;
  4808. +
  4809. + ac->psy = power_supply_register(&ac->pdev->dev, &ac->psy_desc, &psy_cfg);
  4810. + if (IS_ERR(ac->psy)) {
  4811. + status = PTR_ERR(ac->psy);
  4812. + goto err_psy;
  4813. + }
  4814. +
  4815. + ac->notif.base.priority = 1;
  4816. + ac->notif.base.fn = spwr_notify_ac;
  4817. + ac->notif.event.reg = SSAM_EVENT_REGISTRY_SAM;
  4818. + ac->notif.event.id.target_category = SSAM_SSH_TC_BAT;
  4819. + ac->notif.event.id.instance = 0;
  4820. + ac->notif.event.flags = SSAM_EVENT_SEQUENCED;
  4821. +
  4822. + status = surface_sam_ssh_notifier_register(&ac->notif);
  4823. + if (status)
  4824. + goto err_notif;
  4825. +
  4826. + return 0;
  4827. +
  4828. +err_notif:
  4829. + power_supply_unregister(ac->psy);
  4830. +err_psy:
  4831. + mutex_destroy(&ac->lock);
  4832. + return status;
  4833. +}
  4834. +
  4835. +static int spwr_ac_unregister(struct spwr_ac_device *ac)
  4836. +{
  4837. + surface_sam_ssh_notifier_unregister(&ac->notif);
  4838. + power_supply_unregister(ac->psy);
  4839. + mutex_destroy(&ac->lock);
  4840. + return 0;
  4841. +}
  4842. +
  4843. +static int spwr_battery_register(struct spwr_battery_device *bat,
  4844. + struct platform_device *pdev,
  4845. + const struct ssam_battery_properties *p)
  4846. +{
  4847. + struct power_supply_config psy_cfg = {};
  4848. + u32 sta;
  4849. + int status;
  4850. +
  4851. + bat->pdev = pdev;
  4852. + bat->p = p;
  4853. +
  4854. + // make sure the device is there and functioning properly
  4855. + status = sam_psy_get_sta(bat->p->channel, bat->p->instance, &sta);
  4856. + if (status)
  4857. + return status;
  4858. +
  4859. + if ((sta & SAM_BATTERY_STA_OK) != SAM_BATTERY_STA_OK)
  4860. + return -ENODEV;
  4861. +
  4862. + status = spwr_battery_update_bix_unlocked(bat);
  4863. + if (status)
  4864. + return status;
  4865. +
  4866. + if (spwr_battery_present(bat)) {
  4867. + status = spwr_battery_set_alarm_unlocked(bat, bat->bix.design_cap_warn);
  4868. + if (status)
  4869. + return status;
  4870. + }
  4871. +
  4872. + snprintf(bat->name, ARRAY_SIZE(bat->name), "BAT%d", bat->p->num);
  4873. + bat->psy_desc.name = bat->name;
  4874. + bat->psy_desc.type = POWER_SUPPLY_TYPE_BATTERY;
  4875. +
  4876. + if (bat->bix.power_unit == SAM_BATTERY_POWER_UNIT_MA) {
  4877. + bat->psy_desc.properties = spwr_battery_props_chg;
  4878. + bat->psy_desc.num_properties = ARRAY_SIZE(spwr_battery_props_chg);
  4879. + } else {
  4880. + bat->psy_desc.properties = spwr_battery_props_eng;
  4881. + bat->psy_desc.num_properties = ARRAY_SIZE(spwr_battery_props_eng);
  4882. + }
  4883. +
  4884. + bat->psy_desc.get_property = spwr_battery_get_property;
  4885. +
  4886. + mutex_init(&bat->lock);
  4887. + psy_cfg.drv_data = bat;
  4888. +
  4889. + INIT_DELAYED_WORK(&bat->update_work, spwr_battery_update_bst_workfn);
  4890. +
  4891. + bat->psy = power_supply_register(&bat->pdev->dev, &bat->psy_desc, &psy_cfg);
  4892. + if (IS_ERR(bat->psy)) {
  4893. + status = PTR_ERR(bat->psy);
  4894. + goto err_psy;
  4895. + }
  4896. +
  4897. + bat->notif.base.priority = 1;
  4898. + bat->notif.base.fn = spwr_notify_bat;
  4899. + bat->notif.event.reg = p->registry;
  4900. + bat->notif.event.id.target_category = SSAM_SSH_TC_BAT;
  4901. + bat->notif.event.id.instance = 0;
  4902. + bat->notif.event.flags = SSAM_EVENT_SEQUENCED;
  4903. +
  4904. + status = surface_sam_ssh_notifier_register(&bat->notif);
  4905. + if (status)
  4906. + goto err_notif;
  4907. +
  4908. + status = device_create_file(&bat->psy->dev, &alarm_attr);
  4909. + if (status)
  4910. + goto err_file;
  4911. +
  4912. + return 0;
  4913. +
  4914. +err_file:
  4915. + surface_sam_ssh_notifier_unregister(&bat->notif);
  4916. +err_notif:
  4917. + power_supply_unregister(bat->psy);
  4918. +err_psy:
  4919. + mutex_destroy(&bat->lock);
  4920. + return status;
  4921. +}
  4922. +
  4923. +static void spwr_battery_unregister(struct spwr_battery_device *bat)
  4924. +{
  4925. + surface_sam_ssh_notifier_unregister(&bat->notif);
  4926. + cancel_delayed_work_sync(&bat->update_work);
  4927. + device_remove_file(&bat->psy->dev, &alarm_attr);
  4928. + power_supply_unregister(bat->psy);
  4929. + mutex_destroy(&bat->lock);
  4930. +}
  4931. +
  4932. +
  4933. +/*
  4934. + * Battery Driver.
  4935. + */
  4936. +
  4937. +#ifdef CONFIG_PM_SLEEP
  4938. +static int surface_sam_sid_battery_resume(struct device *dev)
  4939. +{
  4940. + struct spwr_battery_device *bat;
  4941. +
  4942. + bat = dev_get_drvdata(dev);
  4943. + return spwr_battery_recheck(bat);
  4944. +}
  4945. +#else
  4946. +#define surface_sam_sid_battery_resume NULL
  4947. +#endif
  4948. +
  4949. +SIMPLE_DEV_PM_OPS(surface_sam_sid_battery_pm, NULL, surface_sam_sid_battery_resume);
  4950. +
  4951. +static int surface_sam_sid_battery_probe(struct platform_device *pdev)
  4952. +{
  4953. + struct spwr_battery_device *bat;
  4954. + int status;
  4955. +
  4956. + // link to ec
  4957. + status = surface_sam_ssh_consumer_register(&pdev->dev);
  4958. + if (status)
  4959. + return status == -ENXIO ? -EPROBE_DEFER : status;
  4960. +
  4961. + bat = devm_kzalloc(&pdev->dev, sizeof(struct spwr_battery_device), GFP_KERNEL);
  4962. + if (!bat)
  4963. + return -ENOMEM;
  4964. +
  4965. + platform_set_drvdata(pdev, bat);
  4966. + return spwr_battery_register(bat, pdev, pdev->dev.platform_data);
  4967. +}
  4968. +
  4969. +static int surface_sam_sid_battery_remove(struct platform_device *pdev)
  4970. +{
  4971. + struct spwr_battery_device *bat;
  4972. +
  4973. + bat = platform_get_drvdata(pdev);
  4974. + spwr_battery_unregister(bat);
  4975. +
  4976. + return 0;
  4977. +}
  4978. +
  4979. +static struct platform_driver surface_sam_sid_battery = {
  4980. + .probe = surface_sam_sid_battery_probe,
  4981. + .remove = surface_sam_sid_battery_remove,
  4982. + .driver = {
  4983. + .name = "surface_sam_sid_battery",
  4984. + .pm = &surface_sam_sid_battery_pm,
  4985. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  4986. + },
  4987. +};
  4988. +
  4989. +
  4990. +/*
  4991. + * AC Driver.
  4992. + */
  4993. +
  4994. +static int surface_sam_sid_ac_probe(struct platform_device *pdev)
  4995. +{
  4996. + int status;
  4997. + struct spwr_ac_device *ac;
  4998. +
  4999. + // link to ec
  5000. + status = surface_sam_ssh_consumer_register(&pdev->dev);
  5001. + if (status)
  5002. + return status == -ENXIO ? -EPROBE_DEFER : status;
  5003. +
  5004. + ac = devm_kzalloc(&pdev->dev, sizeof(struct spwr_ac_device), GFP_KERNEL);
  5005. + if (!ac)
  5006. + return -ENOMEM;
  5007. +
  5008. + status = spwr_ac_register(ac, pdev);
  5009. + if (status)
  5010. + return status;
  5011. +
  5012. + platform_set_drvdata(pdev, ac);
  5013. + return 0;
  5014. +}
  5015. +
  5016. +static int surface_sam_sid_ac_remove(struct platform_device *pdev)
  5017. +{
  5018. + struct spwr_ac_device *ac;
  5019. +
  5020. + ac = platform_get_drvdata(pdev);
  5021. + return spwr_ac_unregister(ac);
  5022. +}
  5023. +
  5024. +static struct platform_driver surface_sam_sid_ac = {
  5025. + .probe = surface_sam_sid_ac_probe,
  5026. + .remove = surface_sam_sid_ac_remove,
  5027. + .driver = {
  5028. + .name = "surface_sam_sid_ac",
  5029. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  5030. + },
  5031. +};
  5032. +
  5033. +
  5034. +static int __init surface_sam_sid_power_init(void)
  5035. +{
  5036. + int status;
  5037. +
  5038. + status = platform_driver_register(&surface_sam_sid_battery);
  5039. + if (status)
  5040. + return status;
  5041. +
  5042. + status = platform_driver_register(&surface_sam_sid_ac);
  5043. + if (status) {
  5044. + platform_driver_unregister(&surface_sam_sid_battery);
  5045. + return status;
  5046. + }
  5047. +
  5048. + return 0;
  5049. +}
  5050. +
  5051. +static void __exit surface_sam_sid_power_exit(void)
  5052. +{
  5053. + platform_driver_unregister(&surface_sam_sid_battery);
  5054. + platform_driver_unregister(&surface_sam_sid_ac);
  5055. +}
  5056. +
  5057. +module_init(surface_sam_sid_power_init);
  5058. +module_exit(surface_sam_sid_power_exit);
  5059. +
  5060. +MODULE_AUTHOR("Maximilian Luz <luzmaximilian@gmail.com>");
  5061. +MODULE_DESCRIPTION("Surface Battery/AC Driver for 7th Generation Surface Devices");
  5062. +MODULE_LICENSE("GPL");
  5063. +MODULE_ALIAS("platform:surface_sam_sid_ac");
  5064. +MODULE_ALIAS("platform:surface_sam_sid_battery");
  5065. diff --git a/drivers/platform/x86/surface_sam/surface_sam_sid_power.h b/drivers/platform/x86/surface_sam/surface_sam_sid_power.h
  5066. new file mode 100644
  5067. index 0000000000000..2e8f212086e12
  5068. --- /dev/null
  5069. +++ b/drivers/platform/x86/surface_sam/surface_sam_sid_power.h
  5070. @@ -0,0 +1,15 @@
  5071. +#ifndef _SURFACE_SAM_SID_POWER_H
  5072. +#define _SURFACE_SAM_SID_POWER_H
  5073. +
  5074. +#include <linux/types.h>
  5075. +#include "surface_sam_ssh.h"
  5076. +
  5077. +
  5078. +struct ssam_battery_properties {
  5079. + struct ssam_event_registry registry;
  5080. + u8 num;
  5081. + u8 channel;
  5082. + u8 instance;
  5083. +};
  5084. +
  5085. +#endif /* _SURFACE_SAM_SID_POWER_H */
  5086. diff --git a/drivers/platform/x86/surface_sam/surface_sam_sid_vhf.c b/drivers/platform/x86/surface_sam/surface_sam_sid_vhf.c
  5087. new file mode 100644
  5088. index 0000000000000..474221097eaf1
  5089. --- /dev/null
  5090. +++ b/drivers/platform/x86/surface_sam/surface_sam_sid_vhf.c
  5091. @@ -0,0 +1,432 @@
  5092. +// SPDX-License-Identifier: GPL-2.0-or-later
  5093. +/*
  5094. + * Microsofs Surface HID (VHF) driver for HID input events via SAM.
  5095. + * Used for keyboard input events on the 7th generation Surface Laptops.
  5096. + */
  5097. +
  5098. +#include <linux/acpi.h>
  5099. +#include <linux/hid.h>
  5100. +#include <linux/input.h>
  5101. +#include <linux/platform_device.h>
  5102. +#include <linux/types.h>
  5103. +
  5104. +#include "surface_sam_ssh.h"
  5105. +#include "surface_sam_sid_vhf.h"
  5106. +
  5107. +#define SID_VHF_INPUT_NAME "Microsoft Surface HID"
  5108. +
  5109. +#define SAM_EVENT_SID_VHF_TC 0x15
  5110. +
  5111. +#define VHF_HID_STARTED 0
  5112. +
  5113. +struct sid_vhf {
  5114. + const struct ssam_hid_properties *p;
  5115. + struct platform_device *dev;
  5116. + struct hid_device *hid;
  5117. + struct ssam_event_notifier notif;
  5118. + unsigned long state;
  5119. +};
  5120. +
  5121. +
  5122. +static int sid_vhf_hid_start(struct hid_device *hid)
  5123. +{
  5124. + hid_dbg(hid, "%s\n", __func__);
  5125. + return 0;
  5126. +}
  5127. +
  5128. +static void sid_vhf_hid_stop(struct hid_device *hid)
  5129. +{
  5130. + hid_dbg(hid, "%s\n", __func__);
  5131. +}
  5132. +
  5133. +static int sid_vhf_hid_open(struct hid_device *hid)
  5134. +{
  5135. + struct sid_vhf *vhf = dev_get_drvdata(hid->dev.parent);
  5136. +
  5137. + hid_dbg(hid, "%s\n", __func__);
  5138. +
  5139. + set_bit(VHF_HID_STARTED, &vhf->state);
  5140. + return 0;
  5141. +}
  5142. +
  5143. +static void sid_vhf_hid_close(struct hid_device *hid)
  5144. +{
  5145. +
  5146. + struct sid_vhf *vhf = dev_get_drvdata(hid->dev.parent);
  5147. +
  5148. + hid_dbg(hid, "%s\n", __func__);
  5149. +
  5150. + clear_bit(VHF_HID_STARTED, &vhf->state);
  5151. +}
  5152. +
  5153. +struct surface_sam_sid_vhf_meta_rqst {
  5154. + u8 id;
  5155. + u32 offset;
  5156. + u32 length; // buffer limit on send, length of data received on receive
  5157. + u8 end; // 0x01 if end was reached
  5158. +} __packed;
  5159. +
  5160. +struct vhf_device_metadata_info {
  5161. + u8 len;
  5162. + u8 _2;
  5163. + u8 _3;
  5164. + u8 _4;
  5165. + u8 _5;
  5166. + u8 _6;
  5167. + u8 _7;
  5168. + u16 hid_len; // hid descriptor length
  5169. +} __packed;
  5170. +
  5171. +struct vhf_device_metadata {
  5172. + u32 len;
  5173. + u16 vendor_id;
  5174. + u16 product_id;
  5175. + u8 _1[24];
  5176. +} __packed;
  5177. +
  5178. +union vhf_buffer_data {
  5179. + struct vhf_device_metadata_info info;
  5180. + u8 pld[0x76];
  5181. + struct vhf_device_metadata meta;
  5182. +};
  5183. +
  5184. +struct surface_sam_sid_vhf_meta_resp {
  5185. + struct surface_sam_sid_vhf_meta_rqst rqst;
  5186. + union vhf_buffer_data data;
  5187. +} __packed;
  5188. +
  5189. +
  5190. +static int vhf_get_metadata(u8 iid, struct vhf_device_metadata *meta)
  5191. +{
  5192. + int status;
  5193. +
  5194. + struct surface_sam_sid_vhf_meta_resp resp = {
  5195. + .rqst = {
  5196. + .id = 2,
  5197. + .offset = 0,
  5198. + .length = 0x76,
  5199. + .end = 0
  5200. + }
  5201. + };
  5202. +
  5203. + struct surface_sam_ssh_rqst rqst = {
  5204. + .tc = 0x15,
  5205. + .cid = 0x04,
  5206. + .iid = iid,
  5207. + .chn = 0x02,
  5208. + .snc = 0x01,
  5209. + .cdl = sizeof(struct surface_sam_sid_vhf_meta_rqst),
  5210. + .pld = (u8 *)&resp.rqst,
  5211. + };
  5212. +
  5213. + struct surface_sam_ssh_buf result = {
  5214. + .cap = sizeof(struct surface_sam_sid_vhf_meta_resp),
  5215. + .len = 0,
  5216. + .data = (u8 *)&resp,
  5217. + };
  5218. +
  5219. + status = surface_sam_ssh_rqst(&rqst, &result);
  5220. + if (status)
  5221. + return status;
  5222. +
  5223. + *meta = resp.data.meta;
  5224. +
  5225. + return 0;
  5226. +}
  5227. +
  5228. +static int vhf_get_hid_descriptor(struct hid_device *hid, u8 iid, u8 **desc, int *size)
  5229. +{
  5230. + int status, len;
  5231. + u8 *buf;
  5232. +
  5233. + struct surface_sam_sid_vhf_meta_resp resp = {
  5234. + .rqst = {
  5235. + .id = 0,
  5236. + .offset = 0,
  5237. + .length = 0x76,
  5238. + .end = 0,
  5239. + }
  5240. + };
  5241. +
  5242. + struct surface_sam_ssh_rqst rqst = {
  5243. + .tc = 0x15,
  5244. + .cid = 0x04,
  5245. + .iid = iid,
  5246. + .chn = 0x02,
  5247. + .snc = 0x01,
  5248. + .cdl = sizeof(struct surface_sam_sid_vhf_meta_rqst),
  5249. + .pld = (u8 *)&resp.rqst,
  5250. + };
  5251. +
  5252. + struct surface_sam_ssh_buf result = {
  5253. + .cap = sizeof(struct surface_sam_sid_vhf_meta_resp),
  5254. + .len = 0,
  5255. + .data = (u8 *)&resp,
  5256. + };
  5257. +
  5258. + // first fetch 00 to get the total length
  5259. + status = surface_sam_ssh_rqst(&rqst, &result);
  5260. + if (status)
  5261. + return status;
  5262. +
  5263. + len = resp.data.info.hid_len;
  5264. +
  5265. + // allocate a buffer for the descriptor
  5266. + buf = kzalloc(len, GFP_KERNEL);
  5267. +
  5268. + // then, iterate and write into buffer, copying out bytes
  5269. + resp.rqst.id = 1;
  5270. + resp.rqst.offset = 0;
  5271. + resp.rqst.length = 0x76;
  5272. + resp.rqst.end = 0;
  5273. +
  5274. + while (!resp.rqst.end && resp.rqst.offset < len) {
  5275. + status = surface_sam_ssh_rqst(&rqst, &result);
  5276. + if (status) {
  5277. + kfree(buf);
  5278. + return status;
  5279. + }
  5280. + memcpy(buf + resp.rqst.offset, resp.data.pld, resp.rqst.length);
  5281. +
  5282. + resp.rqst.offset += resp.rqst.length;
  5283. + }
  5284. +
  5285. + *desc = buf;
  5286. + *size = len;
  5287. +
  5288. + return 0;
  5289. +}
  5290. +
  5291. +static int sid_vhf_hid_parse(struct hid_device *hid)
  5292. +{
  5293. + struct sid_vhf *vhf = dev_get_drvdata(hid->dev.parent);
  5294. + int ret = 0, size;
  5295. + u8 *buf;
  5296. +
  5297. + ret = vhf_get_hid_descriptor(hid, vhf->p->instance, &buf, &size);
  5298. + if (ret != 0) {
  5299. + hid_err(hid, "Failed to read HID descriptor from device: %d\n", ret);
  5300. + return -EIO;
  5301. + }
  5302. + hid_dbg(hid, "HID descriptor of device:");
  5303. + print_hex_dump_debug("descriptor:", DUMP_PREFIX_OFFSET, 16, 1, buf, size, false);
  5304. +
  5305. + ret = hid_parse_report(hid, buf, size);
  5306. + kfree(buf);
  5307. + return ret;
  5308. +
  5309. +}
  5310. +
  5311. +static int sid_vhf_hid_raw_request(struct hid_device *hid, unsigned char
  5312. + reportnum, u8 *buf, size_t len, unsigned char rtype, int
  5313. + reqtype)
  5314. +{
  5315. + struct sid_vhf *vhf = dev_get_drvdata(hid->dev.parent);
  5316. + int status;
  5317. + u8 cid;
  5318. + struct surface_sam_ssh_rqst rqst = {};
  5319. + struct surface_sam_ssh_buf result = {};
  5320. +
  5321. + hid_dbg(hid, "%s: reportnum=%#04x rtype=%i reqtype=%i\n", __func__, reportnum, rtype, reqtype);
  5322. + print_hex_dump_debug("report:", DUMP_PREFIX_OFFSET, 16, 1, buf, len, false);
  5323. +
  5324. + // Byte 0 is the report number. Report data starts at byte 1.
  5325. + buf[0] = reportnum;
  5326. +
  5327. + switch (rtype) {
  5328. + case HID_OUTPUT_REPORT:
  5329. + cid = 0x01;
  5330. + break;
  5331. + case HID_FEATURE_REPORT:
  5332. + switch (reqtype) {
  5333. + case HID_REQ_GET_REPORT:
  5334. + // The EC doesn't respond to GET FEATURE for these touchpad reports
  5335. + // we immediately discard to avoid waiting for a timeout.
  5336. + if (reportnum == 6 || reportnum == 7 || reportnum == 8 || reportnum == 9 || reportnum == 0x0b) {
  5337. + hid_dbg(hid, "%s: skipping get feature report for 0x%02x\n", __func__, reportnum);
  5338. + return 0;
  5339. + }
  5340. +
  5341. + cid = 0x02;
  5342. + break;
  5343. + case HID_REQ_SET_REPORT:
  5344. + cid = 0x03;
  5345. + break;
  5346. + default:
  5347. + hid_err(hid, "%s: unknown req type 0x%02x\n", __func__, rtype);
  5348. + return -EIO;
  5349. + }
  5350. + break;
  5351. + default:
  5352. + hid_err(hid, "%s: unknown report type 0x%02x\n", __func__, reportnum);
  5353. + return -EIO;
  5354. + }
  5355. +
  5356. + rqst.tc = SAM_EVENT_SID_VHF_TC;
  5357. + rqst.chn = 0x02;
  5358. + rqst.iid = vhf->p->instance;
  5359. + rqst.cid = cid;
  5360. + rqst.snc = reqtype == HID_REQ_GET_REPORT ? 0x01 : 0x00;
  5361. + rqst.cdl = reqtype == HID_REQ_GET_REPORT ? 0x01 : len;
  5362. + rqst.pld = buf;
  5363. +
  5364. + result.cap = len;
  5365. + result.len = 0;
  5366. + result.data = buf;
  5367. +
  5368. + hid_dbg(hid, "%s: sending to cid=%#04x snc=%#04x\n", __func__, cid, HID_REQ_GET_REPORT == reqtype);
  5369. +
  5370. + status = surface_sam_ssh_rqst(&rqst, &result);
  5371. + hid_dbg(hid, "%s: status %i\n", __func__, status);
  5372. +
  5373. + if (status)
  5374. + return status;
  5375. +
  5376. + if (result.len > 0)
  5377. + print_hex_dump_debug("response:", DUMP_PREFIX_OFFSET, 16, 1, result.data, result.len, false);
  5378. +
  5379. + return result.len;
  5380. +}
  5381. +
  5382. +static struct hid_ll_driver sid_vhf_hid_ll_driver = {
  5383. + .start = sid_vhf_hid_start,
  5384. + .stop = sid_vhf_hid_stop,
  5385. + .open = sid_vhf_hid_open,
  5386. + .close = sid_vhf_hid_close,
  5387. + .parse = sid_vhf_hid_parse,
  5388. + .raw_request = sid_vhf_hid_raw_request,
  5389. +};
  5390. +
  5391. +
  5392. +static struct hid_device *sid_vhf_create_hid_device(struct platform_device *pdev, struct vhf_device_metadata *meta)
  5393. +{
  5394. + struct hid_device *hid;
  5395. +
  5396. + hid = hid_allocate_device();
  5397. + if (IS_ERR(hid))
  5398. + return hid;
  5399. +
  5400. + hid->dev.parent = &pdev->dev;
  5401. +
  5402. + hid->bus = BUS_VIRTUAL;
  5403. + hid->vendor = meta->vendor_id;
  5404. + hid->product = meta->product_id;
  5405. +
  5406. + hid->ll_driver = &sid_vhf_hid_ll_driver;
  5407. +
  5408. + sprintf(hid->name, "%s", SID_VHF_INPUT_NAME);
  5409. +
  5410. + return hid;
  5411. +}
  5412. +
  5413. +static u32 sid_vhf_event_handler(struct ssam_notifier_block *nb, const struct ssam_event *event)
  5414. +{
  5415. + struct sid_vhf *vhf = container_of(nb, struct sid_vhf, notif.base);
  5416. + int status;
  5417. +
  5418. + if (event->target_category != SSAM_SSH_TC_HID)
  5419. + return 0;
  5420. +
  5421. + if (event->channel != 0x02)
  5422. + return 0;
  5423. +
  5424. + if (event->instance_id != vhf->p->instance)
  5425. + return 0;
  5426. +
  5427. + if (event->command_id != 0x00 && event->command_id != 0x03 && event->command_id != 0x04)
  5428. + return 0;
  5429. +
  5430. + // skip if HID hasn't started yet
  5431. + if (!test_bit(VHF_HID_STARTED, &vhf->state))
  5432. + return SSAM_NOTIF_HANDLED;
  5433. +
  5434. + status = hid_input_report(vhf->hid, HID_INPUT_REPORT, (u8 *)&event->data[0], event->length, 0);
  5435. + return ssam_notifier_from_errno(status) | SSAM_NOTIF_HANDLED;
  5436. +}
  5437. +
  5438. +static int surface_sam_sid_vhf_probe(struct platform_device *pdev)
  5439. +{
  5440. + const struct ssam_hid_properties *p = pdev->dev.platform_data;
  5441. + struct sid_vhf *vhf;
  5442. + struct vhf_device_metadata meta = {};
  5443. + struct hid_device *hid;
  5444. + int status;
  5445. +
  5446. + // add device link to EC
  5447. + status = surface_sam_ssh_consumer_register(&pdev->dev);
  5448. + if (status)
  5449. + return status == -ENXIO ? -EPROBE_DEFER : status;
  5450. +
  5451. + vhf = kzalloc(sizeof(struct sid_vhf), GFP_KERNEL);
  5452. + if (!vhf)
  5453. + return -ENOMEM;
  5454. +
  5455. + status = vhf_get_metadata(p->instance, &meta);
  5456. + if (status)
  5457. + goto err_create_hid;
  5458. +
  5459. + hid = sid_vhf_create_hid_device(pdev, &meta);
  5460. + if (IS_ERR(hid)) {
  5461. + status = PTR_ERR(hid);
  5462. + goto err_create_hid;
  5463. + }
  5464. +
  5465. + vhf->p = pdev->dev.platform_data;
  5466. + vhf->dev = pdev;
  5467. + vhf->hid = hid;
  5468. +
  5469. + vhf->notif.base.priority = 1;
  5470. + vhf->notif.base.fn = sid_vhf_event_handler;
  5471. + vhf->notif.event.reg = p->registry;
  5472. + vhf->notif.event.id.target_category = SSAM_SSH_TC_HID;
  5473. + vhf->notif.event.id.instance = p->instance;
  5474. + vhf->notif.event.flags = 0;
  5475. +
  5476. + platform_set_drvdata(pdev, vhf);
  5477. +
  5478. + status = surface_sam_ssh_notifier_register(&vhf->notif);
  5479. + if (status)
  5480. + goto err_notif;
  5481. +
  5482. + status = hid_add_device(hid);
  5483. + if (status)
  5484. + goto err_add_hid;
  5485. +
  5486. + return 0;
  5487. +
  5488. +err_add_hid:
  5489. + surface_sam_ssh_notifier_unregister(&vhf->notif);
  5490. +err_notif:
  5491. + hid_destroy_device(hid);
  5492. + platform_set_drvdata(pdev, NULL);
  5493. +err_create_hid:
  5494. + kfree(vhf);
  5495. + return status;
  5496. +}
  5497. +
  5498. +static int surface_sam_sid_vhf_remove(struct platform_device *pdev)
  5499. +{
  5500. + struct sid_vhf *vhf = platform_get_drvdata(pdev);
  5501. +
  5502. + surface_sam_ssh_notifier_unregister(&vhf->notif);
  5503. + hid_destroy_device(vhf->hid);
  5504. + kfree(vhf);
  5505. +
  5506. + platform_set_drvdata(pdev, NULL);
  5507. + return 0;
  5508. +}
  5509. +
  5510. +static struct platform_driver surface_sam_sid_vhf = {
  5511. + .probe = surface_sam_sid_vhf_probe,
  5512. + .remove = surface_sam_sid_vhf_remove,
  5513. + .driver = {
  5514. + .name = "surface_sam_sid_vhf",
  5515. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  5516. + },
  5517. +};
  5518. +module_platform_driver(surface_sam_sid_vhf);
  5519. +
  5520. +MODULE_AUTHOR("Blaž Hrastnik <blaz@mxxn.io>");
  5521. +MODULE_DESCRIPTION("Driver for HID devices connected via Surface SAM");
  5522. +MODULE_LICENSE("GPL");
  5523. +MODULE_ALIAS("platform:surface_sam_sid_vhf");
  5524. diff --git a/drivers/platform/x86/surface_sam/surface_sam_sid_vhf.h b/drivers/platform/x86/surface_sam/surface_sam_sid_vhf.h
  5525. new file mode 100644
  5526. index 0000000000000..eb55485ccb119
  5527. --- /dev/null
  5528. +++ b/drivers/platform/x86/surface_sam/surface_sam_sid_vhf.h
  5529. @@ -0,0 +1,13 @@
  5530. +#ifndef _SURFACE_SAM_SID_VHF_H
  5531. +#define _SURFACE_SAM_SID_VHF_H
  5532. +
  5533. +#include <linux/types.h>
  5534. +#include "surface_sam_ssh.h"
  5535. +
  5536. +
  5537. +struct ssam_hid_properties {
  5538. + struct ssam_event_registry registry;
  5539. + u8 instance;
  5540. +};
  5541. +
  5542. +#endif /* _SURFACE_SAM_SID_VHF_H */
  5543. diff --git a/drivers/platform/x86/surface_sam/surface_sam_ssh.c b/drivers/platform/x86/surface_sam/surface_sam_ssh.c
  5544. new file mode 100644
  5545. index 0000000000000..9f44bdfbc4fd7
  5546. --- /dev/null
  5547. +++ b/drivers/platform/x86/surface_sam/surface_sam_ssh.c
  5548. @@ -0,0 +1,5111 @@
  5549. +// SPDX-License-Identifier: GPL-2.0-or-later
  5550. +/*
  5551. + * Surface Serial Hub (SSH) driver for communication with the Surface/System
  5552. + * Aggregator Module.
  5553. + */
  5554. +
  5555. +#include <asm/unaligned.h>
  5556. +#include <linux/acpi.h>
  5557. +#include <linux/atomic.h>
  5558. +#include <linux/completion.h>
  5559. +#include <linux/crc-ccitt.h>
  5560. +#include <linux/dmaengine.h>
  5561. +#include <linux/gpio/consumer.h>
  5562. +#include <linux/interrupt.h>
  5563. +#include <linux/jiffies.h>
  5564. +#include <linux/kernel.h>
  5565. +#include <linux/kfifo.h>
  5566. +#include <linux/kref.h>
  5567. +#include <linux/kthread.h>
  5568. +#include <linux/ktime.h>
  5569. +#include <linux/list.h>
  5570. +#include <linux/mutex.h>
  5571. +#include <linux/pm.h>
  5572. +#include <linux/refcount.h>
  5573. +#include <linux/serdev.h>
  5574. +#include <linux/spinlock.h>
  5575. +#include <linux/sysfs.h>
  5576. +#include <linux/workqueue.h>
  5577. +
  5578. +#include "surface_sam_ssh.h"
  5579. +
  5580. +#define CREATE_TRACE_POINTS
  5581. +#include "surface_sam_ssh_trace.h"
  5582. +
  5583. +
  5584. +/* -- TODO. ----------------------------------------------------------------- */
  5585. +
  5586. +#define SSH_RQST_TAG_FULL "surface_sam_ssh_rqst: "
  5587. +#define SSH_RQST_TAG "rqst: "
  5588. +
  5589. +#define SSH_SUPPORTED_FLOW_CONTROL_MASK (~((u8) ACPI_UART_FLOW_CONTROL_HW))
  5590. +
  5591. +
  5592. +/* -- Error injection helpers. ---------------------------------------------- */
  5593. +
  5594. +#ifdef CONFIG_SURFACE_SAM_SSH_ERROR_INJECTION
  5595. +#define noinline_if_inject noinline
  5596. +#else /* CONFIG_SURFACE_SAM_SSH_ERROR_INJECTION */
  5597. +#define noinline_if_inject inline
  5598. +#endif /* CONFIG_SURFACE_SAM_SSH_ERROR_INJECTION */
  5599. +
  5600. +
  5601. +/* -- Public interface. ----------------------------------------------------- */
  5602. +
  5603. +enum ssam_request_flags {
  5604. + SSAM_REQUEST_HAS_RESPONSE = BIT(0),
  5605. + SSAM_REQUEST_UNSEQUENCED = BIT(1),
  5606. +};
  5607. +
  5608. +struct ssam_request {
  5609. + u8 target_category;
  5610. + u8 command_id;
  5611. + u8 instance_id;
  5612. + u8 channel;
  5613. + u16 flags;
  5614. + u16 length;
  5615. + u8 *payload;
  5616. +};
  5617. +
  5618. +
  5619. +/* -- Common/utility functions. --------------------------------------------- */
  5620. +
  5621. +static inline u16 ssh_crc(const u8 *buf, size_t len)
  5622. +{
  5623. + return crc_ccitt_false(0xffff, buf, len);
  5624. +}
  5625. +
  5626. +static inline u16 __ssh_rqid_next(u16 rqid)
  5627. +{
  5628. + return rqid > 0 ? rqid + 1u : rqid + SURFACE_SAM_SSH_NUM_EVENTS + 1u;
  5629. +}
  5630. +
  5631. +static inline u16 ssh_event_to_rqid(u16 event)
  5632. +{
  5633. + return event + 1u;
  5634. +}
  5635. +
  5636. +static inline u16 ssh_rqid_to_event(u16 rqid)
  5637. +{
  5638. + return rqid - 1u;
  5639. +}
  5640. +
  5641. +static inline bool ssh_rqid_is_event(u16 rqid)
  5642. +{
  5643. + return ssh_rqid_to_event(rqid) < SURFACE_SAM_SSH_NUM_EVENTS;
  5644. +}
  5645. +
  5646. +static inline int ssh_tc_to_rqid(u8 tc)
  5647. +{
  5648. +#if 0 // TODO: check if it works without this
  5649. + /*
  5650. + * TC=0x08 represents the input subsystem on Surface Laptop 1 and 2.
  5651. + * This is mapped on Windows to RQID=0x0001. As input events seem to be
  5652. + * somewhat special with regards to enabling/disabling (they seem to be
  5653. + * enabled by default with a fixed RQID), let's do the same here.
  5654. + */
  5655. + if (tc == 0x08)
  5656. + return 0x0001;
  5657. +
  5658. + /* Default path: Set RQID = TC. */
  5659. +#endif
  5660. + return tc;
  5661. +}
  5662. +
  5663. +static inline int ssh_tc_to_event(u8 tc)
  5664. +{
  5665. + return ssh_rqid_to_event(ssh_tc_to_rqid(tc));
  5666. +}
  5667. +
  5668. +static inline u8 ssh_channel_to_index(u8 channel)
  5669. +{
  5670. + return channel - 1u;
  5671. +}
  5672. +
  5673. +static inline bool ssh_channel_is_valid(u8 channel)
  5674. +{
  5675. + return ssh_channel_to_index(channel) < SURFACE_SAM_SSH_NUM_CHANNELS;
  5676. +}
  5677. +
  5678. +
  5679. +/* -- Safe counters. -------------------------------------------------------- */
  5680. +
  5681. +struct ssh_seq_counter {
  5682. + u8 value;
  5683. +};
  5684. +
  5685. +struct ssh_rqid_counter {
  5686. + u16 value;
  5687. +};
  5688. +
  5689. +static inline void ssh_seq_reset(struct ssh_seq_counter *c)
  5690. +{
  5691. + WRITE_ONCE(c->value, 0);
  5692. +}
  5693. +
  5694. +static inline u8 ssh_seq_next(struct ssh_seq_counter *c)
  5695. +{
  5696. + u8 old = READ_ONCE(c->value);
  5697. + u8 new = old + 1;
  5698. + u8 ret;
  5699. +
  5700. + while (unlikely((ret = cmpxchg(&c->value, old, new)) != old)) {
  5701. + old = ret;
  5702. + new = old + 1;
  5703. + }
  5704. +
  5705. + return old;
  5706. +}
  5707. +
  5708. +static inline void ssh_rqid_reset(struct ssh_rqid_counter *c)
  5709. +{
  5710. + WRITE_ONCE(c->value, 0);
  5711. +}
  5712. +
  5713. +static inline u16 ssh_rqid_next(struct ssh_rqid_counter *c)
  5714. +{
  5715. + u16 old = READ_ONCE(c->value);
  5716. + u16 new = __ssh_rqid_next(old);
  5717. + u16 ret;
  5718. +
  5719. + while (unlikely((ret = cmpxchg(&c->value, old, new)) != old)) {
  5720. + old = ret;
  5721. + new = __ssh_rqid_next(old);
  5722. + }
  5723. +
  5724. + return old;
  5725. +}
  5726. +
  5727. +
  5728. +/* -- Builder functions for SAM-over-SSH messages. -------------------------- */
  5729. +
  5730. +struct msgbuf {
  5731. + u8 *buffer;
  5732. + u8 *end;
  5733. + u8 *ptr;
  5734. +};
  5735. +
  5736. +static inline void msgb_init(struct msgbuf *msgb, u8 *buffer, size_t cap)
  5737. +{
  5738. + msgb->buffer = buffer;
  5739. + msgb->end = buffer + cap;
  5740. + msgb->ptr = buffer;
  5741. +}
  5742. +
  5743. +static inline int msgb_alloc(struct msgbuf *msgb, size_t cap, gfp_t flags)
  5744. +{
  5745. + u8 *buf;
  5746. +
  5747. + buf = kzalloc(cap, flags);
  5748. + if (!buf)
  5749. + return -ENOMEM;
  5750. +
  5751. + msgb_init(msgb, buf, cap);
  5752. + return 0;
  5753. +}
  5754. +
  5755. +static inline void msgb_free(struct msgbuf *msgb)
  5756. +{
  5757. + kfree(msgb->buffer);
  5758. + msgb->buffer = NULL;
  5759. + msgb->end = NULL;
  5760. + msgb->ptr = NULL;
  5761. +}
  5762. +
  5763. +static inline void msgb_reset(struct msgbuf *msgb)
  5764. +{
  5765. + msgb->ptr = msgb->buffer;
  5766. +}
  5767. +
  5768. +static inline size_t msgb_bytes_used(const struct msgbuf *msgb)
  5769. +{
  5770. + return msgb->ptr - msgb->buffer;
  5771. +}
  5772. +
  5773. +static inline void msgb_push_u16(struct msgbuf *msgb, u16 value)
  5774. +{
  5775. + WARN_ON(msgb->ptr + sizeof(u16) > msgb->end);
  5776. + if (msgb->ptr + sizeof(u16) > msgb->end)
  5777. + return;
  5778. +
  5779. + put_unaligned_le16(value, msgb->ptr);
  5780. + msgb->ptr += sizeof(u16);
  5781. +}
  5782. +
  5783. +static inline void msgb_push_syn(struct msgbuf *msgb)
  5784. +{
  5785. + msgb_push_u16(msgb, SSH_MSG_SYN);
  5786. +}
  5787. +
  5788. +static inline void msgb_push_buf(struct msgbuf *msgb, const u8 *buf, size_t len)
  5789. +{
  5790. + msgb->ptr = memcpy(msgb->ptr, buf, len) + len;
  5791. +}
  5792. +
  5793. +static inline void msgb_push_crc(struct msgbuf *msgb, const u8 *buf, size_t len)
  5794. +{
  5795. + msgb_push_u16(msgb, ssh_crc(buf, len));
  5796. +}
  5797. +
  5798. +static inline void msgb_push_frame(struct msgbuf *msgb, u8 ty, u16 len, u8 seq)
  5799. +{
  5800. + struct ssh_frame *frame = (struct ssh_frame *)msgb->ptr;
  5801. + const u8 *const begin = msgb->ptr;
  5802. +
  5803. + WARN_ON(msgb->ptr + sizeof(*frame) > msgb->end);
  5804. + if (msgb->ptr + sizeof(*frame) > msgb->end)
  5805. + return;
  5806. +
  5807. + frame->type = ty;
  5808. + put_unaligned_le16(len, &frame->len);
  5809. + frame->seq = seq;
  5810. +
  5811. + msgb->ptr += sizeof(*frame);
  5812. + msgb_push_crc(msgb, begin, msgb->ptr - begin);
  5813. +}
  5814. +
  5815. +static inline void msgb_push_ack(struct msgbuf *msgb, u8 seq)
  5816. +{
  5817. + // SYN
  5818. + msgb_push_syn(msgb);
  5819. +
  5820. + // ACK-type frame + CRC
  5821. + msgb_push_frame(msgb, SSH_FRAME_TYPE_ACK, 0x00, seq);
  5822. +
  5823. + // payload CRC (ACK-type frames do not have a payload)
  5824. + msgb_push_crc(msgb, msgb->ptr, 0);
  5825. +}
  5826. +
  5827. +static inline void msgb_push_nak(struct msgbuf *msgb)
  5828. +{
  5829. + // SYN
  5830. + msgb_push_syn(msgb);
  5831. +
  5832. + // NAK-type frame + CRC
  5833. + msgb_push_frame(msgb, SSH_FRAME_TYPE_NAK, 0x00, 0x00);
  5834. +
  5835. + // payload CRC (ACK-type frames do not have a payload)
  5836. + msgb_push_crc(msgb, msgb->ptr, 0);
  5837. +}
  5838. +
  5839. +static inline void msgb_push_cmd(struct msgbuf *msgb, u8 seq,
  5840. + const struct surface_sam_ssh_rqst *rqst,
  5841. + u16 rqid)
  5842. +{
  5843. + struct ssh_command *cmd;
  5844. + const u8 *cmd_begin;
  5845. + const u8 type = SSH_FRAME_TYPE_DATA_SEQ;
  5846. +
  5847. + // SYN
  5848. + msgb_push_syn(msgb);
  5849. +
  5850. + // command frame + crc
  5851. + msgb_push_frame(msgb, type, sizeof(*cmd) + rqst->cdl, seq);
  5852. +
  5853. + // frame payload: command struct + payload
  5854. + WARN_ON(msgb->ptr + sizeof(*cmd) > msgb->end);
  5855. + if (msgb->ptr + sizeof(*cmd) > msgb->end)
  5856. + return;
  5857. +
  5858. + cmd_begin = msgb->ptr;
  5859. + cmd = (struct ssh_command *)msgb->ptr;
  5860. +
  5861. + cmd->type = SSH_PLD_TYPE_CMD;
  5862. + cmd->tc = rqst->tc;
  5863. + cmd->chn_out = rqst->chn;
  5864. + cmd->chn_in = 0x00;
  5865. + cmd->iid = rqst->iid;
  5866. + put_unaligned_le16(rqid, &cmd->rqid);
  5867. + cmd->cid = rqst->cid;
  5868. +
  5869. + msgb->ptr += sizeof(*cmd);
  5870. +
  5871. + // command payload
  5872. + msgb_push_buf(msgb, rqst->pld, rqst->cdl);
  5873. +
  5874. + // crc for command struct + payload
  5875. + msgb_push_crc(msgb, cmd_begin, msgb->ptr - cmd_begin);
  5876. +}
  5877. +
  5878. +
  5879. +/* -- Parser functions and utilities for SAM-over-SSH messages. ------------- */
  5880. +
  5881. +struct sshp_buf {
  5882. + u8 *ptr;
  5883. + size_t len;
  5884. + size_t cap;
  5885. +};
  5886. +
  5887. +
  5888. +static inline bool sshp_validate_crc(const struct sshp_span *src, const u8 *crc)
  5889. +{
  5890. + u16 actual = ssh_crc(src->ptr, src->len);
  5891. + u16 expected = get_unaligned_le16(crc);
  5892. +
  5893. + return actual == expected;
  5894. +}
  5895. +
  5896. +static bool sshp_find_syn(const struct sshp_span *src, struct sshp_span *rem)
  5897. +{
  5898. + size_t i;
  5899. +
  5900. + for (i = 0; i < src->len - 1; i++) {
  5901. + if (likely(get_unaligned_le16(src->ptr + i) == SSH_MSG_SYN)) {
  5902. + rem->ptr = src->ptr + i;
  5903. + rem->len = src->len - i;
  5904. + return true;
  5905. + }
  5906. + }
  5907. +
  5908. + if (unlikely(src->ptr[src->len - 1] == (SSH_MSG_SYN & 0xff))) {
  5909. + rem->ptr = src->ptr + src->len - 1;
  5910. + rem->len = 1;
  5911. + return false;
  5912. + } else {
  5913. + rem->ptr = src->ptr + src->len;
  5914. + rem->len = 0;
  5915. + return false;
  5916. + }
  5917. +}
  5918. +
  5919. +static bool sshp_starts_with_syn(const struct sshp_span *src)
  5920. +{
  5921. + return src->len >= 2 && get_unaligned_le16(src->ptr) == SSH_MSG_SYN;
  5922. +}
  5923. +
  5924. +static int sshp_parse_frame(const struct device *dev,
  5925. + const struct sshp_span *source,
  5926. + struct ssh_frame **frame,
  5927. + struct sshp_span *payload,
  5928. + size_t maxlen)
  5929. +{
  5930. + struct sshp_span sf;
  5931. + struct sshp_span sp;
  5932. +
  5933. + // initialize output
  5934. + *frame = NULL;
  5935. + payload->ptr = NULL;
  5936. + payload->len = 0;
  5937. +
  5938. + if (!sshp_starts_with_syn(source)) {
  5939. + dev_warn(dev, "rx: parser: invalid start of frame\n");
  5940. + return -ENOMSG;
  5941. + }
  5942. +
  5943. + // check for minumum packet length
  5944. + if (unlikely(source->len < SSH_MESSAGE_LENGTH(0))) {
  5945. + dev_dbg(dev, "rx: parser: not enough data for frame\n");
  5946. + return 0;
  5947. + }
  5948. +
  5949. + // pin down frame
  5950. + sf.ptr = source->ptr + sizeof(u16);
  5951. + sf.len = sizeof(struct ssh_frame);
  5952. +
  5953. + // validate frame CRC
  5954. + if (unlikely(!sshp_validate_crc(&sf, sf.ptr + sf.len))) {
  5955. + dev_warn(dev, "rx: parser: invalid frame CRC\n");
  5956. + return -EBADMSG;
  5957. + }
  5958. +
  5959. + // ensure packet does not exceed maximum length
  5960. + if (unlikely(((struct ssh_frame *)sf.ptr)->len > maxlen)) {
  5961. + dev_warn(dev, "rx: parser: frame too large: %u bytes\n",
  5962. + ((struct ssh_frame *)sf.ptr)->len);
  5963. + return -EMSGSIZE;
  5964. + }
  5965. +
  5966. + // pin down payload
  5967. + sp.ptr = sf.ptr + sf.len + sizeof(u16);
  5968. + sp.len = get_unaligned_le16(&((struct ssh_frame *)sf.ptr)->len);
  5969. +
  5970. + // check for frame + payload length
  5971. + if (source->len < SSH_MESSAGE_LENGTH(sp.len)) {
  5972. + dev_dbg(dev, "rx: parser: not enough data for payload\n");
  5973. + return 0;
  5974. + }
  5975. +
  5976. + // validate payload crc
  5977. + if (unlikely(!sshp_validate_crc(&sp, sp.ptr + sp.len))) {
  5978. + dev_warn(dev, "rx: parser: invalid payload CRC\n");
  5979. + return -EBADMSG;
  5980. + }
  5981. +
  5982. + *frame = (struct ssh_frame *)sf.ptr;
  5983. + *payload = sp;
  5984. +
  5985. + dev_dbg(dev, "rx: parser: valid frame found (type: 0x%02x, len: %u)\n",
  5986. + (*frame)->type, (*frame)->len);
  5987. +
  5988. + return 0;
  5989. +}
  5990. +
  5991. +static int sshp_parse_command(const struct device *dev,
  5992. + const struct sshp_span *source,
  5993. + struct ssh_command **command,
  5994. + struct sshp_span *command_data)
  5995. +{
  5996. + // check for minimum length
  5997. + if (unlikely(source->len < sizeof(struct ssh_command))) {
  5998. + *command = NULL;
  5999. + command_data->ptr = NULL;
  6000. + command_data->len = 0;
  6001. +
  6002. + dev_err(dev, "rx: parser: command payload is too short\n");
  6003. + return -ENOMSG;
  6004. + }
  6005. +
  6006. + *command = (struct ssh_command *)source->ptr;
  6007. + command_data->ptr = source->ptr + sizeof(struct ssh_command);
  6008. + command_data->len = source->len - sizeof(struct ssh_command);
  6009. +
  6010. + dev_dbg(dev, "rx: parser: valid command found (tc: 0x%02x,"
  6011. + " cid: 0x%02x)\n", (*command)->tc, (*command)->cid);
  6012. +
  6013. + return 0;
  6014. +}
  6015. +
  6016. +
  6017. +static inline void sshp_buf_init(struct sshp_buf *buf, u8 *ptr, size_t cap)
  6018. +{
  6019. + buf->ptr = ptr;
  6020. + buf->len = 0;
  6021. + buf->cap = cap;
  6022. +}
  6023. +
  6024. +static inline int sshp_buf_alloc(struct sshp_buf *buf, size_t cap, gfp_t flags)
  6025. +{
  6026. + u8 *ptr;
  6027. +
  6028. + ptr = kzalloc(cap, flags);
  6029. + if (!ptr)
  6030. + return -ENOMEM;
  6031. +
  6032. + sshp_buf_init(buf, ptr, cap);
  6033. + return 0;
  6034. +
  6035. +}
  6036. +
  6037. +static inline void sshp_buf_free(struct sshp_buf *buf)
  6038. +{
  6039. + kfree(buf->ptr);
  6040. + buf->ptr = NULL;
  6041. + buf->len = 0;
  6042. + buf->cap = 0;
  6043. +}
  6044. +
  6045. +static inline void sshp_buf_reset(struct sshp_buf *buf)
  6046. +{
  6047. + buf->len = 0;
  6048. +}
  6049. +
  6050. +static inline void sshp_buf_drop(struct sshp_buf *buf, size_t n)
  6051. +{
  6052. + memmove(buf->ptr, buf->ptr + n, buf->len - n);
  6053. + buf->len -= n;
  6054. +}
  6055. +
  6056. +static inline size_t sshp_buf_read_from_fifo(struct sshp_buf *buf,
  6057. + struct kfifo *fifo)
  6058. +{
  6059. + size_t n;
  6060. +
  6061. + n = kfifo_out(fifo, buf->ptr + buf->len, buf->cap - buf->len);
  6062. + buf->len += n;
  6063. +
  6064. + return n;
  6065. +}
  6066. +
  6067. +static inline void sshp_buf_span_from(struct sshp_buf *buf, size_t offset,
  6068. + struct sshp_span *span)
  6069. +{
  6070. + span->ptr = buf->ptr + offset;
  6071. + span->len = buf->len - offset;
  6072. +}
  6073. +
  6074. +
  6075. +/* -- Packet transport layer (ptl). ----------------------------------------- */
  6076. +/*
  6077. + * To simplify reasoning about the code below, we define a few concepts. The
  6078. + * system below is similar to a state-machine for packets, however, there are
  6079. + * too many states to explicitly write them down. To (somewhat) manage the
  6080. + * states and packets we rely on flags, reference counting, and some simple
  6081. + * concepts. State transitions are triggered by actions.
  6082. + *
  6083. + * >> Actions <<
  6084. + *
  6085. + * - submit
  6086. + * - transmission start (process next item in queue)
  6087. + * - transmission finished (guaranteed to never be parallel to transmission
  6088. + * start)
  6089. + * - ACK received
  6090. + * - NAK received (this is equivalent to issuing re-submit for all pending
  6091. + * packets)
  6092. + * - timeout (this is equivalent to re-issuing a submit or canceling)
  6093. + * - cancel (non-pending and pending)
  6094. + *
  6095. + * >> Data Structures, Packet Ownership, General Overview <<
  6096. + *
  6097. + * The code below employs two main data structures: The packet queue, containing
  6098. + * all packets scheduled for transmission, and the set of pending packets,
  6099. + * containing all packets awaiting an ACK.
  6100. + *
  6101. + * Shared ownership of a packet is controlled via reference counting. Inside the
  6102. + * transmission system are a total of five packet owners:
  6103. + *
  6104. + * - the packet queue,
  6105. + * - the pending set,
  6106. + * - the transmitter thread,
  6107. + * - the receiver thread (via ACKing), and
  6108. + * - the timeout work item.
  6109. + *
  6110. + * Normal operation is as follows: The initial reference of the packet is
  6111. + * obtained by submitting the packet and queueing it. The receiver thread
  6112. + * takes packets from the queue. By doing this, it does not increment the
  6113. + * refcount but takes over the reference (removing it from the queue).
  6114. + * If the packet is sequenced (i.e. needs to be ACKed by the client), the
  6115. + * transmitter thread sets-up the timeout and adds the packet to the pending set
  6116. + * before starting to transmit it. As the timeout is handled by a reaper task,
  6117. + * no additional reference for it is needed. After the transmit is done, the
  6118. + * reference hold by the transmitter thread is dropped. If the packet is
  6119. + * unsequenced (i.e. does not need an ACK), the packet is completed by the
  6120. + * transmitter thread before dropping that reference.
  6121. + *
  6122. + * On receial of an ACK, the receiver thread removes and obtains the refernce to
  6123. + * the packet from the pending set. On succes, the receiver thread will then
  6124. + * complete the packet and drop its reference.
  6125. + *
  6126. + * On error, the completion callback is immediately run by on thread on which
  6127. + * the error was detected.
  6128. + *
  6129. + * To ensure that a packet eventually leaves the system it is marked as "locked"
  6130. + * directly before it is going to be completed or when it is canceled. Marking a
  6131. + * packet as "locked" has the effect that passing and creating new references
  6132. + * of the packet will be blocked. This means that the packet cannot be added
  6133. + * to the queue, the pending set, and the timeout, or be picked up by the
  6134. + * transmitter thread or receiver thread. To remove a packet from the system it
  6135. + * has to be marked as locked and subsequently all references from the data
  6136. + * structures (queue, pending) have to be removed. References held by threads
  6137. + * will eventually be dropped automatically as their execution progresses.
  6138. + *
  6139. + * Note that the packet completion callback is, in case of success and for a
  6140. + * sequenced packet, guaranteed to run on the receiver thread, thus providing a
  6141. + * way to reliably identify responses to the packet. The packet completion
  6142. + * callback is only run once and it does not indicate that the packet has fully
  6143. + * left the system. In case of re-submission (and with somewhat unlikely
  6144. + * timing), it may be possible that the packet is being re-transmitted while the
  6145. + * completion callback runs. Completion will occur both on success and internal
  6146. + * error, as well as when the packet is canceled.
  6147. + *
  6148. + * >> Flags <<
  6149. + *
  6150. + * Flags are used to indicate the state and progression of a packet. Some flags
  6151. + * have stricter guarantees than other:
  6152. + *
  6153. + * - locked
  6154. + * Indicates if the packet is locked. If the packet is locked, passing and/or
  6155. + * creating additional references to the packet is forbidden. The packet thus
  6156. + * may not be queued, dequeued, or removed or added to the pending set. Note
  6157. + * that the packet state flags may still change (e.g. it may be marked as
  6158. + * ACKed, transmitted, ...).
  6159. + *
  6160. + * - completed
  6161. + * Indicates if the packet completion has been run or is about to be run. This
  6162. + * flag is used to ensure that the packet completion callback is only run
  6163. + * once.
  6164. + *
  6165. + * - queued
  6166. + * Indicates if a packet is present in the submission queue or not. This flag
  6167. + * must only be modified with the queue lock held, and must be coherent
  6168. + * presence of the packet in the queue.
  6169. + *
  6170. + * - pending
  6171. + * Indicates if a packet is present in the set of pending packets or not.
  6172. + * This flag must only be modified with the pending lock held, and must be
  6173. + * coherent presence of the packet in the pending set.
  6174. + *
  6175. + * - transmitting
  6176. + * Indicates if the packet is currently transmitting. In case of
  6177. + * re-transmissions, it is only safe to wait on the "transmitted" completion
  6178. + * after this flag has been set. The completion will be set both in success
  6179. + * and error case.
  6180. + *
  6181. + * - transmitted
  6182. + * Indicates if the packet has been transmitted. This flag is not cleared by
  6183. + * the system, thus it indicates the first transmission only.
  6184. + *
  6185. + * - acked
  6186. + * Indicates if the packet has been acknowledged by the client. There are no
  6187. + * other guarantees given. For example, the packet may still be canceled
  6188. + * and/or the completion may be triggered an error even though this bit is
  6189. + * set. Rely on the status provided by completion instead.
  6190. + *
  6191. + * - canceled
  6192. + * Indicates if the packet has been canceled from the outside. There are no
  6193. + * other guarantees given. Specifically, the packet may be completed by
  6194. + * another part of the system before the cancellation attempts to complete it.
  6195. + *
  6196. + * >> General Notes <<
  6197. + *
  6198. + * To avoid deadlocks, if both queue and pending locks are required, the pending
  6199. + * lock must be acquired before the queue lock.
  6200. + */
  6201. +
  6202. +/**
  6203. + * Maximum number transmission attempts per sequenced packet in case of
  6204. + * time-outs. Must be smaller than 16.
  6205. + */
  6206. +#define SSH_PTL_MAX_PACKET_TRIES 3
  6207. +
  6208. +/**
  6209. + * Timeout as ktime_t delta for ACKs. If we have not received an ACK in this
  6210. + * time-frame after starting transmission, the packet will be re-submitted.
  6211. + */
  6212. +#define SSH_PTL_PACKET_TIMEOUT ms_to_ktime(1000)
  6213. +
  6214. +/**
  6215. + * Maximum time resolution for timeouts. Currently set to max(2 jiffies, 50ms).
  6216. + * Should be larger than one jiffy to avoid direct re-scheduling of reaper
  6217. + * work_struct.
  6218. + */
  6219. +#define SSH_PTL_PACKET_TIMEOUT_RESOLUTION ms_to_ktime(max(2000 / HZ, 50))
  6220. +
  6221. +/**
  6222. + * Maximum number of sequenced packets concurrently waiting for an ACK.
  6223. + * Packets marked as blocking will not be transmitted while this limit is
  6224. + * reached.
  6225. + */
  6226. +#define SSH_PTL_MAX_PENDING 1
  6227. +
  6228. +#define SSH_PTL_RX_BUF_LEN 4096
  6229. +
  6230. +#define SSH_PTL_RX_FIFO_LEN 4096
  6231. +
  6232. +
  6233. +enum ssh_ptl_state_flags {
  6234. + SSH_PTL_SF_SHUTDOWN_BIT,
  6235. +};
  6236. +
  6237. +struct ssh_ptl_ops {
  6238. + void (*data_received)(struct ssh_ptl *p, const struct sshp_span *data);
  6239. +};
  6240. +
  6241. +struct ssh_ptl {
  6242. + struct serdev_device *serdev;
  6243. + unsigned long state;
  6244. +
  6245. + struct {
  6246. + spinlock_t lock;
  6247. + struct list_head head;
  6248. + } queue;
  6249. +
  6250. + struct {
  6251. + spinlock_t lock;
  6252. + struct list_head head;
  6253. + atomic_t count;
  6254. + } pending;
  6255. +
  6256. + struct {
  6257. + bool thread_signal;
  6258. + struct task_struct *thread;
  6259. + struct wait_queue_head thread_wq;
  6260. + struct wait_queue_head packet_wq;
  6261. + struct ssh_packet *packet;
  6262. + size_t offset;
  6263. + } tx;
  6264. +
  6265. + struct {
  6266. + struct task_struct *thread;
  6267. + struct wait_queue_head wq;
  6268. + struct kfifo fifo;
  6269. + struct sshp_buf buf;
  6270. +
  6271. + struct {
  6272. + u16 seqs[8];
  6273. + u16 offset;
  6274. + } blacklist;
  6275. + } rx;
  6276. +
  6277. + struct {
  6278. + ktime_t timeout;
  6279. + ktime_t expires;
  6280. + struct delayed_work reaper;
  6281. + } rtx_timeout;
  6282. +
  6283. + struct ssh_ptl_ops ops;
  6284. +};
  6285. +
  6286. +
  6287. +#define __ssam_prcond(func, p, fmt, ...) \
  6288. + do { \
  6289. + if ((p)) \
  6290. + func((p), fmt, ##__VA_ARGS__); \
  6291. + } while (0);
  6292. +
  6293. +#define ptl_dbg(p, fmt, ...) dev_dbg(&(p)->serdev->dev, fmt, ##__VA_ARGS__)
  6294. +#define ptl_info(p, fmt, ...) dev_info(&(p)->serdev->dev, fmt, ##__VA_ARGS__)
  6295. +#define ptl_warn(p, fmt, ...) dev_warn(&(p)->serdev->dev, fmt, ##__VA_ARGS__)
  6296. +#define ptl_err(p, fmt, ...) dev_err(&(p)->serdev->dev, fmt, ##__VA_ARGS__)
  6297. +#define ptl_dbg_cond(p, fmt, ...) __ssam_prcond(ptl_dbg, p, fmt, ##__VA_ARGS__)
  6298. +
  6299. +#define to_ssh_packet(ptr, member) \
  6300. + container_of(ptr, struct ssh_packet, member)
  6301. +
  6302. +#define to_ssh_ptl(ptr, member) \
  6303. + container_of(ptr, struct ssh_ptl, member)
  6304. +
  6305. +
  6306. +#ifdef CONFIG_SURFACE_SAM_SSH_ERROR_INJECTION
  6307. +
  6308. +/**
  6309. + * ssh_ptl_should_drop_ack_packet - error injection hook to drop ACK packets
  6310. + *
  6311. + * Useful to test detection and handling of automated re-transmits by the EC.
  6312. + * Specifically of packets that the EC consideres not-ACKed but the driver
  6313. + * already consideres ACKed (due to dropped ACK). In this case, the EC
  6314. + * re-transmits the packet-to-be-ACKed and the driver should detect it as
  6315. + * duplicate/already handled. Note that the driver should still send an ACK
  6316. + * for the re-transmitted packet.
  6317. + */
  6318. +static noinline bool ssh_ptl_should_drop_ack_packet(void)
  6319. +{
  6320. + return false;
  6321. +}
  6322. +ALLOW_ERROR_INJECTION(ssh_ptl_should_drop_ack_packet, TRUE);
  6323. +
  6324. +/**
  6325. + * ssh_ptl_should_drop_nak_packet - error injection hook to drop NAK packets
  6326. + *
  6327. + * Useful to test/force automated (timeout-based) re-transmit by the EC.
  6328. + * Specifically, packets that have not reached the driver completely/with valid
  6329. + * checksums. Only useful in combination with receival of (injected) bad data.
  6330. + */
  6331. +static noinline bool ssh_ptl_should_drop_nak_packet(void)
  6332. +{
  6333. + return false;
  6334. +}
  6335. +ALLOW_ERROR_INJECTION(ssh_ptl_should_drop_nak_packet, TRUE);
  6336. +
  6337. +/**
  6338. + * ssh_ptl_should_drop_dsq_packet - error injection hook to drop sequenced data
  6339. + * packet
  6340. + *
  6341. + * Useful to test re-transmit timeout of the driver. If the data packet has not
  6342. + * been ACKed after a certain time, the driver should re-transmit the packet up
  6343. + * to limited number of times defined in SSH_PTL_MAX_PACKET_TRIES.
  6344. + */
  6345. +static noinline bool ssh_ptl_should_drop_dsq_packet(void)
  6346. +{
  6347. + return false;
  6348. +}
  6349. +ALLOW_ERROR_INJECTION(ssh_ptl_should_drop_dsq_packet, TRUE);
  6350. +
  6351. +/**
  6352. + * ssh_ptl_should_fail_write - error injection hook to make serdev_device_write
  6353. + * fail
  6354. + *
  6355. + * Hook to simulate errors in serdev_device_write when transmitting packets.
  6356. + */
  6357. +static noinline int ssh_ptl_should_fail_write(void)
  6358. +{
  6359. + return 0;
  6360. +}
  6361. +ALLOW_ERROR_INJECTION(ssh_ptl_should_fail_write, ERRNO);
  6362. +
  6363. +/**
  6364. + * ssh_ptl_should_corrupt_tx_data - error injection hook to simualte invalid
  6365. + * data being sent to the EC
  6366. + *
  6367. + * Hook to simulate corrupt/invalid data being sent from host (driver) to EC.
  6368. + * Causes the package data to be actively corrupted by overwriting it with
  6369. + * pre-defined values, such that it becomes invalid, causing the EC to respond
  6370. + * with a NAK packet. Useful to test handling of NAK packets received by the
  6371. + * driver.
  6372. + */
  6373. +static noinline bool ssh_ptl_should_corrupt_tx_data(void)
  6374. +{
  6375. + return false;
  6376. +}
  6377. +ALLOW_ERROR_INJECTION(ssh_ptl_should_corrupt_tx_data, TRUE);
  6378. +
  6379. +/**
  6380. + * ssh_ptl_should_corrupt_rx_syn - error injection hook to simulate invalid
  6381. + * data being sent by the EC
  6382. + *
  6383. + * Hook to simulate invalid SYN bytes, i.e. an invalid start of messages and
  6384. + * test handling thereof in the driver.
  6385. + */
  6386. +static noinline bool ssh_ptl_should_corrupt_rx_syn(void)
  6387. +{
  6388. + return false;
  6389. +}
  6390. +ALLOW_ERROR_INJECTION(ssh_ptl_should_corrupt_rx_syn, TRUE);
  6391. +
  6392. +/**
  6393. + * ssh_ptl_should_corrupt_rx_data - error injection hook to simulate invalid
  6394. + * data being sent by the EC
  6395. + *
  6396. + * Hook to simulate invalid data/checksum of the message frame and test handling
  6397. + * thereof in the driver.
  6398. + */
  6399. +static noinline bool ssh_ptl_should_corrupt_rx_data(void)
  6400. +{
  6401. + return false;
  6402. +}
  6403. +ALLOW_ERROR_INJECTION(ssh_ptl_should_corrupt_rx_data, TRUE);
  6404. +
  6405. +
  6406. +static inline bool __ssh_ptl_should_drop_ack_packet(struct ssh_packet *packet)
  6407. +{
  6408. + if (likely(!ssh_ptl_should_drop_ack_packet()))
  6409. + return false;
  6410. +
  6411. + trace_ssam_ei_tx_drop_ack_packet(packet);
  6412. + ptl_info(packet->ptl, "packet error injection: dropping ACK packet %p\n",
  6413. + packet);
  6414. +
  6415. + return true;
  6416. +}
  6417. +
  6418. +static inline bool __ssh_ptl_should_drop_nak_packet(struct ssh_packet *packet)
  6419. +{
  6420. + if (likely(!ssh_ptl_should_drop_nak_packet()))
  6421. + return false;
  6422. +
  6423. + trace_ssam_ei_tx_drop_nak_packet(packet);
  6424. + ptl_info(packet->ptl, "packet error injection: dropping NAK packet %p\n",
  6425. + packet);
  6426. +
  6427. + return true;
  6428. +}
  6429. +
  6430. +static inline bool __ssh_ptl_should_drop_dsq_packet(struct ssh_packet *packet)
  6431. +{
  6432. + if (likely(!ssh_ptl_should_drop_dsq_packet()))
  6433. + return false;
  6434. +
  6435. + trace_ssam_ei_tx_drop_dsq_packet(packet);
  6436. + ptl_info(packet->ptl,
  6437. + "packet error injection: dropping sequenced data packet %p\n",
  6438. + packet);
  6439. +
  6440. + return true;
  6441. +}
  6442. +
  6443. +static bool ssh_ptl_should_drop_packet(struct ssh_packet *packet)
  6444. +{
  6445. + // ignore packets that don't carry any data (i.e. flush)
  6446. + if (!packet->data || !packet->data_length)
  6447. + return false;
  6448. +
  6449. + switch (packet->data[SSH_MSGOFFSET_FRAME(type)]) {
  6450. + case SSH_FRAME_TYPE_ACK:
  6451. + return __ssh_ptl_should_drop_ack_packet(packet);
  6452. +
  6453. + case SSH_FRAME_TYPE_NAK:
  6454. + return __ssh_ptl_should_drop_nak_packet(packet);
  6455. +
  6456. + case SSH_FRAME_TYPE_DATA_SEQ:
  6457. + return __ssh_ptl_should_drop_dsq_packet(packet);
  6458. +
  6459. + default:
  6460. + return false;
  6461. + }
  6462. +}
  6463. +
  6464. +static inline int ssh_ptl_write_buf(struct ssh_ptl *ptl,
  6465. + struct ssh_packet *packet,
  6466. + const unsigned char *buf,
  6467. + size_t count)
  6468. +{
  6469. + int status;
  6470. +
  6471. + status = ssh_ptl_should_fail_write();
  6472. + if (unlikely(status)) {
  6473. + trace_ssam_ei_tx_fail_write(packet, status);
  6474. + ptl_info(packet->ptl,
  6475. + "packet error injection: simulating transmit error %d, packet %p\n",
  6476. + status, packet);
  6477. +
  6478. + return status;
  6479. + }
  6480. +
  6481. + return serdev_device_write_buf(ptl->serdev, buf, count);
  6482. +}
  6483. +
  6484. +static inline void ssh_ptl_tx_inject_invalid_data(struct ssh_packet *packet)
  6485. +{
  6486. + // ignore packets that don't carry any data (i.e. flush)
  6487. + if (!packet->data || !packet->data_length)
  6488. + return;
  6489. +
  6490. + // only allow sequenced data packets to be modified
  6491. + if (packet->data[SSH_MSGOFFSET_FRAME(type)] != SSH_FRAME_TYPE_DATA_SEQ)
  6492. + return;
  6493. +
  6494. + if (likely(!ssh_ptl_should_corrupt_tx_data()))
  6495. + return;
  6496. +
  6497. + trace_ssam_ei_tx_corrupt_data(packet);
  6498. + ptl_info(packet->ptl,
  6499. + "packet error injection: simulating invalid transmit data on packet %p\n",
  6500. + packet);
  6501. +
  6502. + /*
  6503. + * NB: The value 0xb3 has been chosen more or less randomly so that it
  6504. + * doesn't have any (major) overlap with the SYN bytes (aa 55) and is
  6505. + * non-trivial (i.e. non-zero, non-0xff).
  6506. + */
  6507. + memset(packet->data, 0xb3, packet->data_length);
  6508. +}
  6509. +
  6510. +static inline void ssh_ptl_rx_inject_invalid_syn(struct ssh_ptl *ptl,
  6511. + struct sshp_span *data)
  6512. +{
  6513. + struct sshp_span frame;
  6514. +
  6515. + // check if there actually is something to corrupt
  6516. + if (!sshp_find_syn(data, &frame))
  6517. + return;
  6518. +
  6519. + if (likely(!ssh_ptl_should_corrupt_rx_syn()))
  6520. + return;
  6521. +
  6522. + trace_ssam_ei_rx_corrupt_syn("data_length", data->len);
  6523. +
  6524. + data->ptr[1] = 0xb3; // set second byte of SYN to "random" value
  6525. +}
  6526. +
  6527. +static inline void ssh_ptl_rx_inject_invalid_data(struct ssh_ptl *ptl,
  6528. + struct sshp_span *frame)
  6529. +{
  6530. + size_t payload_len, message_len;
  6531. + struct ssh_frame *sshf;
  6532. +
  6533. + // ignore incomplete messages, will get handled once it's complete
  6534. + if (frame->len < SSH_MESSAGE_LENGTH(0))
  6535. + return;
  6536. +
  6537. + // ignore incomplete messages, part 2
  6538. + payload_len = get_unaligned_le16(&frame->ptr[SSH_MSGOFFSET_FRAME(len)]);
  6539. + message_len = SSH_MESSAGE_LENGTH(payload_len);
  6540. + if (frame->len < message_len)
  6541. + return;
  6542. +
  6543. + if (likely(!ssh_ptl_should_corrupt_rx_data()))
  6544. + return;
  6545. +
  6546. + sshf = (struct ssh_frame *)&frame->ptr[SSH_MSGOFFSET_FRAME(type)];
  6547. + trace_ssam_ei_rx_corrupt_data(sshf);
  6548. +
  6549. + /*
  6550. + * Flip bits in first byte of payload checksum. This is basically
  6551. + * equivalent to a payload/frame data error without us having to worry
  6552. + * about (the, arguably pretty small, probability of) accidental
  6553. + * checksum collisions.
  6554. + */
  6555. + frame->ptr[frame->len - 2] = ~frame->ptr[frame->len - 2];
  6556. +}
  6557. +
  6558. +#else /* CONFIG_SURFACE_SAM_SSH_ERROR_INJECTION */
  6559. +
  6560. +static inline bool ssh_ptl_should_drop_packet(struct ssh_packet *packet)
  6561. +{
  6562. + return false;
  6563. +}
  6564. +
  6565. +static inline int ssh_ptl_write_buf(struct ssh_ptl *ptl,
  6566. + struct ssh_packet *packet,
  6567. + const unsigned char *buf,
  6568. + size_t count)
  6569. +{
  6570. + return serdev_device_write_buf(ptl->serdev, buf, count);
  6571. +}
  6572. +
  6573. +static inline void ssh_ptl_tx_inject_invalid_data(struct ssh_packet *packet)
  6574. +{
  6575. +}
  6576. +
  6577. +static inline void ssh_ptl_rx_inject_invalid_syn(struct ssh_ptl *ptl,
  6578. + struct sshp_span *data)
  6579. +{
  6580. +}
  6581. +
  6582. +static inline void ssh_ptl_rx_inject_invalid_data(struct ssh_ptl *ptl,
  6583. + struct sshp_span *frame)
  6584. +{
  6585. +}
  6586. +
  6587. +#endif /* CONFIG_SURFACE_SAM_SSH_ERROR_INJECTION */
  6588. +
  6589. +
  6590. +static void __ssh_ptl_packet_release(struct kref *kref)
  6591. +{
  6592. + struct ssh_packet *p = to_ssh_packet(kref, refcnt);
  6593. +
  6594. + trace_ssam_packet_release(p);
  6595. +
  6596. + ptl_dbg_cond(p->ptl, "ptl: releasing packet %p\n", p);
  6597. + p->ops->release(p);
  6598. +}
  6599. +
  6600. +static inline void ssh_packet_get(struct ssh_packet *packet)
  6601. +{
  6602. + kref_get(&packet->refcnt);
  6603. +}
  6604. +
  6605. +static inline void ssh_packet_put(struct ssh_packet *packet)
  6606. +{
  6607. + kref_put(&packet->refcnt, __ssh_ptl_packet_release);
  6608. +}
  6609. +
  6610. +
  6611. +static inline u8 ssh_packet_get_seq(struct ssh_packet *packet)
  6612. +{
  6613. + return packet->data[SSH_MSGOFFSET_FRAME(seq)];
  6614. +}
  6615. +
  6616. +
  6617. +struct ssh_packet_args {
  6618. + u8 type;
  6619. + u8 priority;
  6620. + const struct ssh_packet_ops *ops;
  6621. +};
  6622. +
  6623. +static void ssh_packet_init(struct ssh_packet *packet,
  6624. + const struct ssh_packet_args *args)
  6625. +{
  6626. + kref_init(&packet->refcnt);
  6627. +
  6628. + packet->ptl = NULL;
  6629. + INIT_LIST_HEAD(&packet->queue_node);
  6630. + INIT_LIST_HEAD(&packet->pending_node);
  6631. +
  6632. + packet->type = args->type;
  6633. + packet->priority = args->priority;
  6634. + packet->state = 0;
  6635. + packet->timestamp = KTIME_MAX;
  6636. +
  6637. + packet->data_length = 0;
  6638. + packet->data = NULL;
  6639. +
  6640. + packet->ops = args->ops;
  6641. +}
  6642. +
  6643. +
  6644. +static struct ssh_packet *ptl_alloc_ctrl_packet(
  6645. + struct ssh_ptl *ptl, const struct ssh_packet_args *args,
  6646. + gfp_t flags)
  6647. +{
  6648. + struct ssh_packet *packet;
  6649. +
  6650. + // TODO: chache packets
  6651. +
  6652. + packet = kzalloc(sizeof(struct ssh_packet) + SSH_MSG_LEN_CTRL, flags);
  6653. + if (!packet)
  6654. + return NULL;
  6655. +
  6656. + ssh_packet_init(packet, args);
  6657. + packet->data_length = SSH_MSG_LEN_CTRL;
  6658. + packet->data = ((u8 *) packet) + sizeof(struct ssh_packet);
  6659. +
  6660. + return packet;
  6661. +}
  6662. +
  6663. +static void ptl_free_ctrl_packet(struct ssh_packet *p)
  6664. +{
  6665. + // TODO: chache packets
  6666. +
  6667. + kfree(p);
  6668. +}
  6669. +
  6670. +static const struct ssh_packet_ops ssh_ptl_ctrl_packet_ops = {
  6671. + .complete = NULL,
  6672. + .release = ptl_free_ctrl_packet,
  6673. +};
  6674. +
  6675. +
  6676. +static void ssh_ptl_timeout_reaper_mod(struct ssh_ptl *ptl, ktime_t now,
  6677. + ktime_t expires)
  6678. +{
  6679. + unsigned long delta = msecs_to_jiffies(ktime_ms_delta(expires, now));
  6680. + ktime_t aexp = ktime_add(expires, SSH_PTL_PACKET_TIMEOUT_RESOLUTION);
  6681. + ktime_t old;
  6682. +
  6683. + // re-adjust / schedule reaper if it is above resolution delta
  6684. + old = READ_ONCE(ptl->rtx_timeout.expires);
  6685. + while (ktime_before(aexp, old))
  6686. + old = cmpxchg64(&ptl->rtx_timeout.expires, old, expires);
  6687. +
  6688. + // if we updated the reaper expiration, modify work timeout
  6689. + if (old == expires)
  6690. + mod_delayed_work(system_wq, &ptl->rtx_timeout.reaper, delta);
  6691. +}
  6692. +
  6693. +static void ssh_ptl_timeout_start(struct ssh_packet *packet)
  6694. +{
  6695. + struct ssh_ptl *ptl = packet->ptl;
  6696. + ktime_t timestamp = ktime_get_coarse_boottime();
  6697. + ktime_t timeout = ptl->rtx_timeout.timeout;
  6698. +
  6699. + if (test_bit(SSH_PACKET_SF_LOCKED_BIT, &packet->state))
  6700. + return;
  6701. +
  6702. + WRITE_ONCE(packet->timestamp, timestamp);
  6703. + smp_mb__after_atomic();
  6704. +
  6705. + ssh_ptl_timeout_reaper_mod(packet->ptl, timestamp, timestamp + timeout);
  6706. +}
  6707. +
  6708. +
  6709. +static struct list_head *__ssh_ptl_queue_find_entrypoint(struct ssh_packet *p)
  6710. +{
  6711. + struct list_head *head;
  6712. + u8 priority = READ_ONCE(p->priority);
  6713. +
  6714. + /*
  6715. + * We generally assume that there are less control (ACK/NAK) packets and
  6716. + * re-submitted data packets as there are normal data packets (at least
  6717. + * in situations in which many packets are queued; if there aren't many
  6718. + * packets queued the decision on how to iterate should be basically
  6719. + * irrellevant; the number of control/data packets is more or less
  6720. + * limited via the maximum number of pending packets). Thus, when
  6721. + * inserting a control or re-submitted data packet, (determined by their
  6722. + * priority), we search from front to back. Normal data packets are,
  6723. + * usually queued directly at the tail of the queue, so for those search
  6724. + * from back to front.
  6725. + */
  6726. +
  6727. + if (priority > SSH_PACKET_PRIORITY_DATA) {
  6728. + list_for_each(head, &p->ptl->queue.head) {
  6729. + p = list_entry(head, struct ssh_packet, queue_node);
  6730. +
  6731. + if (READ_ONCE(p->priority) < priority)
  6732. + break;
  6733. + }
  6734. + } else {
  6735. + list_for_each_prev(head, &p->ptl->queue.head) {
  6736. + p = list_entry(head, struct ssh_packet, queue_node);
  6737. +
  6738. + if (READ_ONCE(p->priority) >= priority) {
  6739. + head = head->next;
  6740. + break;
  6741. + }
  6742. + }
  6743. + }
  6744. +
  6745. +
  6746. + return head;
  6747. +}
  6748. +
  6749. +static int ssh_ptl_queue_push(struct ssh_packet *packet)
  6750. +{
  6751. + struct ssh_ptl *ptl = packet->ptl;
  6752. + struct list_head *head;
  6753. +
  6754. + spin_lock(&ptl->queue.lock);
  6755. +
  6756. + if (test_bit(SSH_PTL_SF_SHUTDOWN_BIT, &ptl->state)) {
  6757. + spin_unlock(&ptl->queue.lock);
  6758. + return -ESHUTDOWN;
  6759. + }
  6760. +
  6761. + // avoid further transitions when cancelling/completing
  6762. + if (test_bit(SSH_PACKET_SF_LOCKED_BIT, &packet->state)) {
  6763. + spin_unlock(&ptl->queue.lock);
  6764. + return -EINVAL;
  6765. + }
  6766. +
  6767. + // if this packet has already been queued, do not add it
  6768. + if (test_and_set_bit(SSH_PACKET_SF_QUEUED_BIT, &packet->state)) {
  6769. + spin_unlock(&ptl->queue.lock);
  6770. + return -EALREADY;
  6771. + }
  6772. +
  6773. + head = __ssh_ptl_queue_find_entrypoint(packet);
  6774. +
  6775. + ssh_packet_get(packet);
  6776. + list_add_tail(&packet->queue_node, &ptl->queue.head);
  6777. +
  6778. + spin_unlock(&ptl->queue.lock);
  6779. + return 0;
  6780. +}
  6781. +
  6782. +static void ssh_ptl_queue_remove(struct ssh_packet *packet)
  6783. +{
  6784. + struct ssh_ptl *ptl = packet->ptl;
  6785. + bool remove;
  6786. +
  6787. + spin_lock(&ptl->queue.lock);
  6788. +
  6789. + remove = test_and_clear_bit(SSH_PACKET_SF_QUEUED_BIT, &packet->state);
  6790. + if (remove)
  6791. + list_del(&packet->queue_node);
  6792. +
  6793. + spin_unlock(&ptl->queue.lock);
  6794. +
  6795. + if (remove)
  6796. + ssh_packet_put(packet);
  6797. +}
  6798. +
  6799. +
  6800. +static void ssh_ptl_pending_push(struct ssh_packet *packet)
  6801. +{
  6802. + struct ssh_ptl *ptl = packet->ptl;
  6803. +
  6804. + spin_lock(&ptl->pending.lock);
  6805. +
  6806. + // if we are cancelling/completing this packet, do not add it
  6807. + if (test_bit(SSH_PACKET_SF_LOCKED_BIT, &packet->state)) {
  6808. + spin_unlock(&ptl->pending.lock);
  6809. + return;
  6810. + }
  6811. +
  6812. + // in case it is already pending (e.g. re-submission), do not add it
  6813. + if (test_and_set_bit(SSH_PACKET_SF_PENDING_BIT, &packet->state)) {
  6814. + spin_unlock(&ptl->pending.lock);
  6815. + return;
  6816. + }
  6817. +
  6818. + atomic_inc(&ptl->pending.count);
  6819. + ssh_packet_get(packet);
  6820. + list_add_tail(&packet->pending_node, &ptl->pending.head);
  6821. +
  6822. + spin_unlock(&ptl->pending.lock);
  6823. +}
  6824. +
  6825. +static void ssh_ptl_pending_remove(struct ssh_packet *packet)
  6826. +{
  6827. + struct ssh_ptl *ptl = packet->ptl;
  6828. + bool remove;
  6829. +
  6830. + spin_lock(&ptl->pending.lock);
  6831. +
  6832. + remove = test_and_clear_bit(SSH_PACKET_SF_PENDING_BIT, &packet->state);
  6833. + if (remove) {
  6834. + list_del(&packet->pending_node);
  6835. + atomic_dec(&ptl->pending.count);
  6836. + }
  6837. +
  6838. + spin_unlock(&ptl->pending.lock);
  6839. +
  6840. + if (remove)
  6841. + ssh_packet_put(packet);
  6842. +}
  6843. +
  6844. +
  6845. +static void __ssh_ptl_complete(struct ssh_packet *p, int status)
  6846. +{
  6847. + struct ssh_ptl *ptl = READ_ONCE(p->ptl);
  6848. +
  6849. + trace_ssam_packet_complete(p, status);
  6850. +
  6851. + ptl_dbg_cond(ptl, "ptl: completing packet %p\n", p);
  6852. + if (p->ops->complete)
  6853. + p->ops->complete(p, status);
  6854. +}
  6855. +
  6856. +static void ssh_ptl_remove_and_complete(struct ssh_packet *p, int status)
  6857. +{
  6858. + /*
  6859. + * A call to this function should in general be preceeded by
  6860. + * set_bit(SSH_PACKET_SF_LOCKED_BIT, &p->flags) to avoid re-adding the
  6861. + * packet to the structures it's going to be removed from.
  6862. + *
  6863. + * The set_bit call does not need explicit memory barriers as the
  6864. + * implicit barrier of the test_and_set_bit call below ensure that the
  6865. + * flag is visible before we actually attempt to remove the packet.
  6866. + */
  6867. +
  6868. + if (test_and_set_bit(SSH_PACKET_SF_COMPLETED_BIT, &p->state))
  6869. + return;
  6870. +
  6871. + ssh_ptl_queue_remove(p);
  6872. + ssh_ptl_pending_remove(p);
  6873. +
  6874. + __ssh_ptl_complete(p, status);
  6875. +}
  6876. +
  6877. +
  6878. +static bool ssh_ptl_tx_can_process(struct ssh_packet *packet)
  6879. +{
  6880. + struct ssh_ptl *ptl = packet->ptl;
  6881. +
  6882. + if (packet->type & SSH_PACKET_TY_FLUSH)
  6883. + return !atomic_read(&ptl->pending.count);
  6884. +
  6885. + // we can alwas process non-blocking packets
  6886. + if (!(packet->type & SSH_PACKET_TY_BLOCKING))
  6887. + return true;
  6888. +
  6889. + // if we are already waiting for this packet, send it again
  6890. + if (test_bit(SSH_PACKET_SF_PENDING_BIT, &packet->state))
  6891. + return true;
  6892. +
  6893. + // otherwise: check if we have the capacity to send
  6894. + return atomic_read(&ptl->pending.count) < SSH_PTL_MAX_PENDING;
  6895. +}
  6896. +
  6897. +static struct ssh_packet *ssh_ptl_tx_pop(struct ssh_ptl *ptl)
  6898. +{
  6899. + struct ssh_packet *packet = ERR_PTR(-ENOENT);
  6900. + struct ssh_packet *p, *n;
  6901. +
  6902. + spin_lock(&ptl->queue.lock);
  6903. + list_for_each_entry_safe(p, n, &ptl->queue.head, queue_node) {
  6904. + /*
  6905. + * If we are cancelling or completing this packet, ignore it.
  6906. + * It's going to be removed from this queue shortly.
  6907. + */
  6908. + if (test_bit(SSH_PACKET_SF_LOCKED_BIT, &p->state))
  6909. + continue;
  6910. +
  6911. + /*
  6912. + * Packets should be ordered non-blocking/to-be-resent first.
  6913. + * If we cannot process this packet, assume that we can't
  6914. + * process any following packet either and abort.
  6915. + */
  6916. + if (!ssh_ptl_tx_can_process(p)) {
  6917. + packet = ERR_PTR(-EBUSY);
  6918. + break;
  6919. + }
  6920. +
  6921. + /*
  6922. + * We are allowed to change the state now. Remove it from the
  6923. + * queue and mark it as being transmitted. Note that we cannot
  6924. + * add it to the set of pending packets yet, as queue locks must
  6925. + * always be acquired before packet locks (otherwise we might
  6926. + * run into a deadlock).
  6927. + */
  6928. +
  6929. + list_del(&p->queue_node);
  6930. +
  6931. + /*
  6932. + * Ensure that the "queued" bit gets cleared after setting the
  6933. + * "transmitting" bit to guaranteee non-zero flags.
  6934. + */
  6935. + set_bit(SSH_PACKET_SF_TRANSMITTING_BIT, &p->state);
  6936. + smp_mb__before_atomic();
  6937. + clear_bit(SSH_PACKET_SF_QUEUED_BIT, &p->state);
  6938. +
  6939. + packet = p;
  6940. + break;
  6941. + }
  6942. + spin_unlock(&ptl->queue.lock);
  6943. +
  6944. + return packet;
  6945. +}
  6946. +
  6947. +static struct ssh_packet *ssh_ptl_tx_next(struct ssh_ptl *ptl)
  6948. +{
  6949. + struct ssh_packet *p;
  6950. +
  6951. + p = ssh_ptl_tx_pop(ptl);
  6952. + if (IS_ERR(p))
  6953. + return p;
  6954. +
  6955. + if (p->type & SSH_PACKET_TY_SEQUENCED) {
  6956. + ptl_dbg(ptl, "ptl: transmitting sequenced packet %p\n", p);
  6957. + ssh_ptl_pending_push(p);
  6958. + ssh_ptl_timeout_start(p);
  6959. + } else {
  6960. + ptl_dbg(ptl, "ptl: transmitting non-sequenced packet %p\n", p);
  6961. + }
  6962. +
  6963. + /*
  6964. + * Update number of tries. This directly influences the priority in case
  6965. + * the packet is re-submitted (e.g. via timeout/NAK). Note that this is
  6966. + * the only place where we update the priority in-flight. As this runs
  6967. + * only on the tx-thread, this read-modify-write procedure is safe.
  6968. + */
  6969. + WRITE_ONCE(p->priority, READ_ONCE(p->priority) + 1);
  6970. +
  6971. + return p;
  6972. +}
  6973. +
  6974. +static void ssh_ptl_tx_compl_success(struct ssh_packet *packet)
  6975. +{
  6976. + struct ssh_ptl *ptl = packet->ptl;
  6977. +
  6978. + ptl_dbg(ptl, "ptl: successfully transmitted packet %p\n", packet);
  6979. +
  6980. + /*
  6981. + * Transition to state to "transmitted". Ensure that the flags never get
  6982. + * zero with barrier.
  6983. + */
  6984. + set_bit(SSH_PACKET_SF_TRANSMITTED_BIT, &packet->state);
  6985. + smp_mb__before_atomic();
  6986. + clear_bit(SSH_PACKET_SF_TRANSMITTING_BIT, &packet->state);
  6987. +
  6988. + // if the packet is unsequenced, we're done: lock and complete
  6989. + if (!(packet->type & SSH_PACKET_TY_SEQUENCED)) {
  6990. + set_bit(SSH_PACKET_SF_LOCKED_BIT, &packet->state);
  6991. + ssh_ptl_remove_and_complete(packet, 0);
  6992. + }
  6993. +
  6994. + /*
  6995. + * Notify that a packet transmission has finished. In general we're only
  6996. + * waiting for one packet (if any), so wake_up_all should be fine.
  6997. + */
  6998. + wake_up_all(&ptl->tx.packet_wq);
  6999. +}
  7000. +
  7001. +static void ssh_ptl_tx_compl_error(struct ssh_packet *packet, int status)
  7002. +{
  7003. + /*
  7004. + * Transmission failure: Lock the packet and try to complete it. Ensure
  7005. + * that the flags never get zero with barrier.
  7006. + */
  7007. + set_bit(SSH_PACKET_SF_LOCKED_BIT, &packet->state);
  7008. + smp_mb__before_atomic();
  7009. + clear_bit(SSH_PACKET_SF_TRANSMITTING_BIT, &packet->state);
  7010. +
  7011. + ptl_err(packet->ptl, "ptl: transmission error: %d\n", status);
  7012. + ptl_dbg(packet->ptl, "ptl: failed to transmit packet: %p\n", packet);
  7013. +
  7014. + ssh_ptl_remove_and_complete(packet, status);
  7015. +
  7016. + /*
  7017. + * Notify that a packet transmission has finished. In general we're only
  7018. + * waiting for one packet (if any), so wake_up_all should be fine.
  7019. + */
  7020. + wake_up_all(&packet->ptl->tx.packet_wq);
  7021. +}
  7022. +
  7023. +static void ssh_ptl_tx_threadfn_wait(struct ssh_ptl *ptl)
  7024. +{
  7025. + wait_event_interruptible(ptl->tx.thread_wq,
  7026. + READ_ONCE(ptl->tx.thread_signal) || kthread_should_stop());
  7027. + WRITE_ONCE(ptl->tx.thread_signal, false);
  7028. +}
  7029. +
  7030. +static int ssh_ptl_tx_threadfn(void *data)
  7031. +{
  7032. + struct ssh_ptl *ptl = data;
  7033. +
  7034. + while (!kthread_should_stop()) {
  7035. + unsigned char *buf;
  7036. + bool drop = false;
  7037. + size_t len = 0;
  7038. + int status = 0;
  7039. +
  7040. + // if we don't have a packet, get the next and add it to pending
  7041. + if (IS_ERR_OR_NULL(ptl->tx.packet)) {
  7042. + ptl->tx.packet = ssh_ptl_tx_next(ptl);
  7043. + ptl->tx.offset = 0;
  7044. +
  7045. + // if no packet is available, we are done
  7046. + if (IS_ERR(ptl->tx.packet)) {
  7047. + ssh_ptl_tx_threadfn_wait(ptl);
  7048. + continue;
  7049. + }
  7050. + }
  7051. +
  7052. + // error injection: drop packet to simulate transmission problem
  7053. + if (ptl->tx.offset == 0)
  7054. + drop = ssh_ptl_should_drop_packet(ptl->tx.packet);
  7055. +
  7056. + // error injection: simulate invalid packet data
  7057. + if (ptl->tx.offset == 0 && !drop)
  7058. + ssh_ptl_tx_inject_invalid_data(ptl->tx.packet);
  7059. +
  7060. + // flush-packets don't have any data
  7061. + if (likely(ptl->tx.packet->data && !drop)) {
  7062. + buf = ptl->tx.packet->data + ptl->tx.offset;
  7063. + len = ptl->tx.packet->data_length - ptl->tx.offset;
  7064. +
  7065. + ptl_dbg(ptl, "tx: sending data (length: %zu)\n", len);
  7066. + print_hex_dump_debug("tx: ", DUMP_PREFIX_OFFSET, 16, 1,
  7067. + buf, len, false);
  7068. +
  7069. + status = ssh_ptl_write_buf(ptl, ptl->tx.packet, buf, len);
  7070. + }
  7071. +
  7072. + if (status < 0) {
  7073. + // complete packet with error
  7074. + ssh_ptl_tx_compl_error(ptl->tx.packet, status);
  7075. + ssh_packet_put(ptl->tx.packet);
  7076. + ptl->tx.packet = NULL;
  7077. +
  7078. + } else if (status == len) {
  7079. + // complete packet and/or mark as transmitted
  7080. + ssh_ptl_tx_compl_success(ptl->tx.packet);
  7081. + ssh_packet_put(ptl->tx.packet);
  7082. + ptl->tx.packet = NULL;
  7083. +
  7084. + } else { // need more buffer space
  7085. + ptl->tx.offset += status;
  7086. + ssh_ptl_tx_threadfn_wait(ptl);
  7087. + }
  7088. + }
  7089. +
  7090. + // cancel active packet before we actually stop
  7091. + if (!IS_ERR_OR_NULL(ptl->tx.packet)) {
  7092. + ssh_ptl_tx_compl_error(ptl->tx.packet, -ESHUTDOWN);
  7093. + ssh_packet_put(ptl->tx.packet);
  7094. + ptl->tx.packet = NULL;
  7095. + }
  7096. +
  7097. + return 0;
  7098. +}
  7099. +
  7100. +static inline void ssh_ptl_tx_wakeup(struct ssh_ptl *ptl, bool force)
  7101. +{
  7102. + if (test_bit(SSH_PTL_SF_SHUTDOWN_BIT, &ptl->state))
  7103. + return;
  7104. +
  7105. + if (force || atomic_read(&ptl->pending.count) < SSH_PTL_MAX_PENDING) {
  7106. + WRITE_ONCE(ptl->tx.thread_signal, true);
  7107. + smp_mb__after_atomic();
  7108. + wake_up(&ptl->tx.thread_wq);
  7109. + }
  7110. +}
  7111. +
  7112. +static int ssh_ptl_tx_start(struct ssh_ptl *ptl)
  7113. +{
  7114. + ptl->tx.thread = kthread_run(ssh_ptl_tx_threadfn, ptl, "surface-sh-tx");
  7115. + if (IS_ERR(ptl->tx.thread))
  7116. + return PTR_ERR(ptl->tx.thread);
  7117. +
  7118. + return 0;
  7119. +}
  7120. +
  7121. +static int ssh_ptl_tx_stop(struct ssh_ptl *ptl)
  7122. +{
  7123. + int status = 0;
  7124. +
  7125. + if (ptl->tx.thread) {
  7126. + status = kthread_stop(ptl->tx.thread);
  7127. + ptl->tx.thread = NULL;
  7128. + }
  7129. +
  7130. + return status;
  7131. +}
  7132. +
  7133. +
  7134. +static struct ssh_packet *ssh_ptl_ack_pop(struct ssh_ptl *ptl, u8 seq_id)
  7135. +{
  7136. + struct ssh_packet *packet = ERR_PTR(-ENOENT);
  7137. + struct ssh_packet *p, *n;
  7138. +
  7139. + spin_lock(&ptl->pending.lock);
  7140. + list_for_each_entry_safe(p, n, &ptl->pending.head, pending_node) {
  7141. + /*
  7142. + * We generally expect packets to be in order, so first packet
  7143. + * to be added to pending is first to be sent, is first to be
  7144. + * ACKed.
  7145. + */
  7146. + if (unlikely(ssh_packet_get_seq(p) != seq_id))
  7147. + continue;
  7148. +
  7149. + /*
  7150. + * In case we receive an ACK while handling a transmission error
  7151. + * completion. The packet will be removed shortly.
  7152. + */
  7153. + if (unlikely(test_bit(SSH_PACKET_SF_LOCKED_BIT, &p->state))) {
  7154. + packet = ERR_PTR(-EPERM);
  7155. + break;
  7156. + }
  7157. +
  7158. + /*
  7159. + * Mark packet as ACKed and remove it from pending. Ensure that
  7160. + * the flags never get zero with barrier.
  7161. + */
  7162. + set_bit(SSH_PACKET_SF_ACKED_BIT, &p->state);
  7163. + smp_mb__before_atomic();
  7164. + clear_bit(SSH_PACKET_SF_PENDING_BIT, &p->state);
  7165. +
  7166. + atomic_dec(&ptl->pending.count);
  7167. + list_del(&p->pending_node);
  7168. + packet = p;
  7169. +
  7170. + break;
  7171. + }
  7172. + spin_unlock(&ptl->pending.lock);
  7173. +
  7174. + return packet;
  7175. +}
  7176. +
  7177. +static void ssh_ptl_wait_until_transmitted(struct ssh_packet *packet)
  7178. +{
  7179. + wait_event(packet->ptl->tx.packet_wq,
  7180. + test_bit(SSH_PACKET_SF_TRANSMITTED_BIT, &packet->state)
  7181. + || test_bit(SSH_PACKET_SF_LOCKED_BIT, &packet->state));
  7182. +}
  7183. +
  7184. +static void ssh_ptl_acknowledge(struct ssh_ptl *ptl, u8 seq)
  7185. +{
  7186. + struct ssh_packet *p;
  7187. + int status = 0;
  7188. +
  7189. + p = ssh_ptl_ack_pop(ptl, seq);
  7190. + if (IS_ERR(p)) {
  7191. + if (PTR_ERR(p) == -ENOENT) {
  7192. + /*
  7193. + * The packet has not been found in the set of pending
  7194. + * packets.
  7195. + */
  7196. + ptl_warn(ptl, "ptl: received ACK for non-pending"
  7197. + " packet\n");
  7198. + } else {
  7199. + /*
  7200. + * The packet is pending, but we are not allowed to take
  7201. + * it because it has been locked.
  7202. + */
  7203. + }
  7204. + return;
  7205. + }
  7206. +
  7207. + ptl_dbg(ptl, "ptl: received ACK for packet %p\n", p);
  7208. +
  7209. + /*
  7210. + * It is possible that the packet has been transmitted, but the state
  7211. + * has not been updated from "transmitting" to "transmitted" yet.
  7212. + * In that case, we need to wait for this transition to occur in order
  7213. + * to determine between success or failure.
  7214. + */
  7215. + if (test_bit(SSH_PACKET_SF_TRANSMITTING_BIT, &p->state))
  7216. + ssh_ptl_wait_until_transmitted(p);
  7217. +
  7218. + /*
  7219. + * The packet will already be locked in case of a transmission error or
  7220. + * cancellation. Let the transmitter or cancellation issuer complete the
  7221. + * packet.
  7222. + */
  7223. + if (unlikely(test_and_set_bit(SSH_PACKET_SF_LOCKED_BIT, &p->state))) {
  7224. + ssh_packet_put(p);
  7225. + return;
  7226. + }
  7227. +
  7228. + if (unlikely(!test_bit(SSH_PACKET_SF_TRANSMITTED_BIT, &p->state))) {
  7229. + ptl_err(ptl, "ptl: received ACK before packet had been fully"
  7230. + " transmitted\n");
  7231. + status = -EREMOTEIO;
  7232. + }
  7233. +
  7234. + ssh_ptl_remove_and_complete(p, status);
  7235. + ssh_packet_put(p);
  7236. +
  7237. + ssh_ptl_tx_wakeup(ptl, false);
  7238. +}
  7239. +
  7240. +
  7241. +static int ssh_ptl_submit(struct ssh_ptl *ptl, struct ssh_packet *packet)
  7242. +{
  7243. + int status;
  7244. +
  7245. + trace_ssam_packet_submit(packet);
  7246. +
  7247. + // validate packet fields
  7248. + if (packet->type & SSH_PACKET_TY_FLUSH) {
  7249. + if (packet->data || (packet->type & SSH_PACKET_TY_SEQUENCED))
  7250. + return -EINVAL;
  7251. + } else if (!packet->data) {
  7252. + return -EINVAL;
  7253. + }
  7254. +
  7255. + /*
  7256. + * This function is currently not intended for re-submission. The ptl
  7257. + * reference only gets set on the first submission. After the first
  7258. + * submission, it has to be read-only.
  7259. + *
  7260. + * Use cmpxchg to ensure safety with regards to ssh_ptl_cancel and
  7261. + * re-entry, where we can't guarantee that the packet has been submitted
  7262. + * yet.
  7263. + *
  7264. + * The implicit barrier of cmpxchg is paired with barrier in
  7265. + * ssh_ptl_cancel to guarantee cancelation in case the packet has never
  7266. + * been submitted or is currently being submitted.
  7267. + */
  7268. + if (cmpxchg(&packet->ptl, NULL, ptl) != NULL)
  7269. + return -EALREADY;
  7270. +
  7271. + status = ssh_ptl_queue_push(packet);
  7272. + if (status)
  7273. + return status;
  7274. +
  7275. + ssh_ptl_tx_wakeup(ptl, !(packet->type & SSH_PACKET_TY_BLOCKING));
  7276. + return 0;
  7277. +}
  7278. +
  7279. +static void __ssh_ptl_resubmit(struct ssh_packet *packet)
  7280. +{
  7281. + struct list_head *head;
  7282. +
  7283. + trace_ssam_packet_resubmit(packet);
  7284. +
  7285. + spin_lock(&packet->ptl->queue.lock);
  7286. +
  7287. + // if this packet has already been queued, do not add it
  7288. + if (test_and_set_bit(SSH_PACKET_SF_QUEUED_BIT, &packet->state)) {
  7289. + spin_unlock(&packet->ptl->queue.lock);
  7290. + return;
  7291. + }
  7292. +
  7293. + // find first node with lower priority
  7294. + head = __ssh_ptl_queue_find_entrypoint(packet);
  7295. +
  7296. + WRITE_ONCE(packet->timestamp, KTIME_MAX);
  7297. + smp_mb__after_atomic();
  7298. +
  7299. + // add packet
  7300. + ssh_packet_get(packet);
  7301. + list_add_tail(&packet->queue_node, head);
  7302. +
  7303. + spin_unlock(&packet->ptl->queue.lock);
  7304. +}
  7305. +
  7306. +static void ssh_ptl_resubmit_pending(struct ssh_ptl *ptl)
  7307. +{
  7308. + struct ssh_packet *p;
  7309. + bool resub = false;
  7310. + u8 try;
  7311. +
  7312. + /*
  7313. + * Note: We deliberately do not remove/attempt to cancel and complete
  7314. + * packets that are out of tires in this function. The packet will be
  7315. + * eventually canceled and completed by the timeout. Removing the packet
  7316. + * here could lead to overly eager cancelation if the packet has not
  7317. + * been re-transmitted yet but the tries-counter already updated (i.e
  7318. + * ssh_ptl_tx_next removed the packet from the queue and updated the
  7319. + * counter, but re-transmission for the last try has not actually
  7320. + * started yet).
  7321. + */
  7322. +
  7323. + spin_lock(&ptl->pending.lock);
  7324. +
  7325. + // re-queue all pending packets
  7326. + list_for_each_entry(p, &ptl->pending.head, pending_node) {
  7327. + // avoid further transitions if locked
  7328. + if (test_bit(SSH_PACKET_SF_LOCKED_BIT, &p->state))
  7329. + continue;
  7330. +
  7331. + // do not re-schedule if packet is out of tries
  7332. + try = ssh_packet_priority_get_try(READ_ONCE(p->priority));
  7333. + if (try >= SSH_PTL_MAX_PACKET_TRIES)
  7334. + continue;
  7335. +
  7336. + resub = true;
  7337. + __ssh_ptl_resubmit(p);
  7338. + }
  7339. +
  7340. + spin_unlock(&ptl->pending.lock);
  7341. +
  7342. + ssh_ptl_tx_wakeup(ptl, resub);
  7343. +}
  7344. +
  7345. +static void ssh_ptl_cancel(struct ssh_packet *p)
  7346. +{
  7347. + if (test_and_set_bit(SSH_PACKET_SF_CANCELED_BIT, &p->state))
  7348. + return;
  7349. +
  7350. + trace_ssam_packet_cancel(p);
  7351. +
  7352. + /*
  7353. + * Lock packet and commit with memory barrier. If this packet has
  7354. + * already been locked, it's going to be removed and completed by
  7355. + * another party, which should have precedence.
  7356. + */
  7357. + if (test_and_set_bit(SSH_PACKET_SF_LOCKED_BIT, &p->state))
  7358. + return;
  7359. +
  7360. + /*
  7361. + * By marking the packet as locked and employing the implicit memory
  7362. + * barrier of test_and_set_bit, we have guaranteed that, at this point,
  7363. + * the packet cannot be added to the queue any more.
  7364. + *
  7365. + * In case the packet has never been submitted, packet->ptl is NULL. If
  7366. + * the packet is currently being submitted, packet->ptl may be NULL or
  7367. + * non-NULL. Due marking the packet as locked above and committing with
  7368. + * the memory barrier, we have guaranteed that, if packet->ptl is NULL,
  7369. + * the packet will never be added to the queue. If packet->ptl is
  7370. + * non-NULL, we don't have any guarantees.
  7371. + */
  7372. +
  7373. + if (READ_ONCE(p->ptl)) {
  7374. + ssh_ptl_remove_and_complete(p, -ECANCELED);
  7375. + ssh_ptl_tx_wakeup(p->ptl, false);
  7376. + } else if (!test_and_set_bit(SSH_PACKET_SF_COMPLETED_BIT, &p->state)) {
  7377. + __ssh_ptl_complete(p, -ECANCELED);
  7378. + }
  7379. +}
  7380. +
  7381. +
  7382. +static ktime_t ssh_packet_get_expiration(struct ssh_packet *p, ktime_t timeout)
  7383. +{
  7384. + ktime_t timestamp = READ_ONCE(p->timestamp);
  7385. +
  7386. + if (timestamp != KTIME_MAX)
  7387. + return ktime_add(timestamp, timeout);
  7388. + else
  7389. + return KTIME_MAX;
  7390. +}
  7391. +
  7392. +static void ssh_ptl_timeout_reap(struct work_struct *work)
  7393. +{
  7394. + struct ssh_ptl *ptl = to_ssh_ptl(work, rtx_timeout.reaper.work);
  7395. + struct ssh_packet *p, *n;
  7396. + LIST_HEAD(claimed);
  7397. + ktime_t now = ktime_get_coarse_boottime();
  7398. + ktime_t timeout = ptl->rtx_timeout.timeout;
  7399. + ktime_t next = KTIME_MAX;
  7400. + bool resub = false;
  7401. +
  7402. + trace_ssam_ptl_timeout_reap("pending", atomic_read(&ptl->pending.count));
  7403. +
  7404. + /*
  7405. + * Mark reaper as "not pending". This is done before checking any
  7406. + * packets to avoid lost-update type problems.
  7407. + */
  7408. + WRITE_ONCE(ptl->rtx_timeout.expires, KTIME_MAX);
  7409. + smp_mb__after_atomic();
  7410. +
  7411. + spin_lock(&ptl->pending.lock);
  7412. +
  7413. + list_for_each_entry_safe(p, n, &ptl->pending.head, pending_node) {
  7414. + ktime_t expires = ssh_packet_get_expiration(p, timeout);
  7415. + u8 try;
  7416. +
  7417. + /*
  7418. + * Check if the timeout hasn't expired yet. Find out next
  7419. + * expiration date to be handled after this run.
  7420. + */
  7421. + if (ktime_after(expires, now)) {
  7422. + next = ktime_before(expires, next) ? expires : next;
  7423. + continue;
  7424. + }
  7425. +
  7426. + // avoid further transitions if locked
  7427. + if (test_bit(SSH_PACKET_SF_LOCKED_BIT, &p->state))
  7428. + continue;
  7429. +
  7430. + trace_ssam_packet_timeout(p);
  7431. +
  7432. + // check if we still have some tries left
  7433. + try = ssh_packet_priority_get_try(READ_ONCE(p->priority));
  7434. + if (likely(try < SSH_PTL_MAX_PACKET_TRIES)) {
  7435. + resub = true;
  7436. + __ssh_ptl_resubmit(p);
  7437. + continue;
  7438. + }
  7439. +
  7440. + // no more tries left: cancel the packet
  7441. +
  7442. + // if someone else has locked the packet already, don't use it
  7443. + if (test_and_set_bit(SSH_PACKET_SF_LOCKED_BIT, &p->state))
  7444. + continue;
  7445. +
  7446. + /*
  7447. + * We have now marked the packet as locked. Thus it cannot be
  7448. + * added to the pending list again after we've removed it here.
  7449. + * We can therefore re-use the pending_node of this packet
  7450. + * temporarily.
  7451. + */
  7452. +
  7453. + clear_bit(SSH_PACKET_SF_PENDING_BIT, &p->state);
  7454. +
  7455. + atomic_dec(&ptl->pending.count);
  7456. + list_del(&p->pending_node);
  7457. +
  7458. + list_add_tail(&p->pending_node, &claimed);
  7459. + }
  7460. +
  7461. + spin_unlock(&ptl->pending.lock);
  7462. +
  7463. + // cancel and complete the packet
  7464. + list_for_each_entry_safe(p, n, &claimed, pending_node) {
  7465. + if (!test_and_set_bit(SSH_PACKET_SF_COMPLETED_BIT, &p->state)) {
  7466. + ssh_ptl_queue_remove(p);
  7467. + __ssh_ptl_complete(p, -ETIMEDOUT);
  7468. + }
  7469. +
  7470. + // drop the reference we've obtained by removing it from pending
  7471. + list_del(&p->pending_node);
  7472. + ssh_packet_put(p);
  7473. + }
  7474. +
  7475. + // ensure that reaper doesn't run again immediately
  7476. + next = max(next, ktime_add(now, SSH_PTL_PACKET_TIMEOUT_RESOLUTION));
  7477. + if (next != KTIME_MAX)
  7478. + ssh_ptl_timeout_reaper_mod(ptl, now, next);
  7479. +
  7480. + // force-wakeup to properly handle re-transmits if we've re-submitted
  7481. + ssh_ptl_tx_wakeup(ptl, resub);
  7482. +}
  7483. +
  7484. +
  7485. +static bool ssh_ptl_rx_blacklist_check(struct ssh_ptl *ptl, u8 seq)
  7486. +{
  7487. + int i;
  7488. +
  7489. + // check if SEQ is blacklisted
  7490. + for (i = 0; i < ARRAY_SIZE(ptl->rx.blacklist.seqs); i++) {
  7491. + if (likely(ptl->rx.blacklist.seqs[i] != seq))
  7492. + continue;
  7493. +
  7494. + ptl_dbg(ptl, "ptl: ignoring repeated data packet\n");
  7495. + return true;
  7496. + }
  7497. +
  7498. + // update blacklist
  7499. + ptl->rx.blacklist.seqs[ptl->rx.blacklist.offset] = seq;
  7500. + ptl->rx.blacklist.offset = (ptl->rx.blacklist.offset + 1)
  7501. + % ARRAY_SIZE(ptl->rx.blacklist.seqs);
  7502. +
  7503. + return false;
  7504. +}
  7505. +
  7506. +static void ssh_ptl_rx_dataframe(struct ssh_ptl *ptl,
  7507. + const struct ssh_frame *frame,
  7508. + const struct sshp_span *payload)
  7509. +{
  7510. + if (ssh_ptl_rx_blacklist_check(ptl, frame->seq))
  7511. + return;
  7512. +
  7513. + ptl->ops.data_received(ptl, payload);
  7514. +}
  7515. +
  7516. +static void ssh_ptl_send_ack(struct ssh_ptl *ptl, u8 seq)
  7517. +{
  7518. + struct ssh_packet_args args;
  7519. + struct ssh_packet *packet;
  7520. + struct msgbuf msgb;
  7521. +
  7522. + args.type = 0;
  7523. + args.priority = SSH_PACKET_PRIORITY(ACK, 0);
  7524. + args.ops = &ssh_ptl_ctrl_packet_ops;
  7525. +
  7526. + packet = ptl_alloc_ctrl_packet(ptl, &args, GFP_KERNEL);
  7527. + if (!packet) {
  7528. + ptl_err(ptl, "ptl: failed to allocate ACK packet\n");
  7529. + return;
  7530. + }
  7531. +
  7532. + msgb_init(&msgb, packet->data, packet->data_length);
  7533. + msgb_push_ack(&msgb, seq);
  7534. + packet->data_length = msgb_bytes_used(&msgb);
  7535. +
  7536. + ssh_ptl_submit(ptl, packet);
  7537. + ssh_packet_put(packet);
  7538. +}
  7539. +
  7540. +static void ssh_ptl_send_nak(struct ssh_ptl *ptl)
  7541. +{
  7542. + struct ssh_packet_args args;
  7543. + struct ssh_packet *packet;
  7544. + struct msgbuf msgb;
  7545. +
  7546. + args.type = 0;
  7547. + args.priority = SSH_PACKET_PRIORITY(NAK, 0);
  7548. + args.ops = &ssh_ptl_ctrl_packet_ops;
  7549. +
  7550. + packet = ptl_alloc_ctrl_packet(ptl, &args, GFP_KERNEL);
  7551. + if (!packet) {
  7552. + ptl_err(ptl, "ptl: failed to allocate NAK packet\n");
  7553. + return;
  7554. + }
  7555. +
  7556. + msgb_init(&msgb, packet->data, packet->data_length);
  7557. + msgb_push_nak(&msgb);
  7558. + packet->data_length = msgb_bytes_used(&msgb);
  7559. +
  7560. + ssh_ptl_submit(ptl, packet);
  7561. + ssh_packet_put(packet);
  7562. +}
  7563. +
  7564. +static size_t ssh_ptl_rx_eval(struct ssh_ptl *ptl, struct sshp_span *source)
  7565. +{
  7566. + struct ssh_frame *frame;
  7567. + struct sshp_span payload;
  7568. + struct sshp_span aligned;
  7569. + bool syn_found;
  7570. + int status;
  7571. +
  7572. + // error injection: modify data to simulate corrupt SYN bytes
  7573. + ssh_ptl_rx_inject_invalid_syn(ptl, source);
  7574. +
  7575. + // find SYN
  7576. + syn_found = sshp_find_syn(source, &aligned);
  7577. +
  7578. + if (unlikely(aligned.ptr - source->ptr) > 0) {
  7579. + ptl_warn(ptl, "rx: parser: invalid start of frame, skipping\n");
  7580. +
  7581. + /*
  7582. + * Notes:
  7583. + * - This might send multiple NAKs in case the communication
  7584. + * starts with an invalid SYN and is broken down into multiple
  7585. + * pieces. This should generally be handled fine, we just
  7586. + * might receive duplicate data in this case, which is
  7587. + * detected when handling data frames.
  7588. + * - This path will also be executed on invalid CRCs: When an
  7589. + * invalid CRC is encountered, the code below will skip data
  7590. + * until direclty after the SYN. This causes the search for
  7591. + * the next SYN, which is generally not placed directly after
  7592. + * the last one.
  7593. + */
  7594. + ssh_ptl_send_nak(ptl);
  7595. + }
  7596. +
  7597. + if (unlikely(!syn_found))
  7598. + return aligned.ptr - source->ptr;
  7599. +
  7600. + // error injection: modify data to simulate corruption
  7601. + ssh_ptl_rx_inject_invalid_data(ptl, &aligned);
  7602. +
  7603. + // parse and validate frame
  7604. + status = sshp_parse_frame(&ptl->serdev->dev, &aligned, &frame, &payload,
  7605. + SSH_PTL_RX_BUF_LEN);
  7606. + if (status) // invalid frame: skip to next syn
  7607. + return aligned.ptr - source->ptr + sizeof(u16);
  7608. + if (!frame) // not enough data
  7609. + return aligned.ptr - source->ptr;
  7610. +
  7611. + trace_ssam_rx_frame_received(frame);
  7612. +
  7613. + switch (frame->type) {
  7614. + case SSH_FRAME_TYPE_ACK:
  7615. + ssh_ptl_acknowledge(ptl, frame->seq);
  7616. + break;
  7617. +
  7618. + case SSH_FRAME_TYPE_NAK:
  7619. + ssh_ptl_resubmit_pending(ptl);
  7620. + break;
  7621. +
  7622. + case SSH_FRAME_TYPE_DATA_SEQ:
  7623. + ssh_ptl_send_ack(ptl, frame->seq);
  7624. + /* fallthrough */
  7625. +
  7626. + case SSH_FRAME_TYPE_DATA_NSQ:
  7627. + ssh_ptl_rx_dataframe(ptl, frame, &payload);
  7628. + break;
  7629. +
  7630. + default:
  7631. + ptl_warn(ptl, "ptl: received frame with unknown type 0x%02x\n",
  7632. + frame->type);
  7633. + break;
  7634. + }
  7635. +
  7636. + return aligned.ptr - source->ptr + SSH_MESSAGE_LENGTH(frame->len);
  7637. +}
  7638. +
  7639. +static int ssh_ptl_rx_threadfn(void *data)
  7640. +{
  7641. + struct ssh_ptl *ptl = data;
  7642. +
  7643. + while (true) {
  7644. + struct sshp_span span;
  7645. + size_t offs = 0;
  7646. + size_t n;
  7647. +
  7648. + wait_event_interruptible(ptl->rx.wq,
  7649. + !kfifo_is_empty(&ptl->rx.fifo)
  7650. + || kthread_should_stop());
  7651. + if (kthread_should_stop())
  7652. + break;
  7653. +
  7654. + // copy from fifo to evaluation buffer
  7655. + n = sshp_buf_read_from_fifo(&ptl->rx.buf, &ptl->rx.fifo);
  7656. +
  7657. + ptl_dbg(ptl, "rx: received data (size: %zu)\n", n);
  7658. + print_hex_dump_debug("rx: ", DUMP_PREFIX_OFFSET, 16, 1,
  7659. + ptl->rx.buf.ptr + ptl->rx.buf.len - n,
  7660. + n, false);
  7661. +
  7662. + // parse until we need more bytes or buffer is empty
  7663. + while (offs < ptl->rx.buf.len) {
  7664. + sshp_buf_span_from(&ptl->rx.buf, offs, &span);
  7665. + n = ssh_ptl_rx_eval(ptl, &span);
  7666. + if (n == 0)
  7667. + break; // need more bytes
  7668. +
  7669. + offs += n;
  7670. + }
  7671. +
  7672. + // throw away the evaluated parts
  7673. + sshp_buf_drop(&ptl->rx.buf, offs);
  7674. + }
  7675. +
  7676. + return 0;
  7677. +}
  7678. +
  7679. +static inline void ssh_ptl_rx_wakeup(struct ssh_ptl *ptl)
  7680. +{
  7681. + wake_up(&ptl->rx.wq);
  7682. +}
  7683. +
  7684. +static int ssh_ptl_rx_start(struct ssh_ptl *ptl)
  7685. +{
  7686. + if (ptl->rx.thread)
  7687. + return 0;
  7688. +
  7689. + ptl->rx.thread = kthread_run(ssh_ptl_rx_threadfn, ptl, "surface-sh-rx");
  7690. + if (IS_ERR(ptl->rx.thread))
  7691. + return PTR_ERR(ptl->rx.thread);
  7692. +
  7693. + return 0;
  7694. +}
  7695. +
  7696. +static int ssh_ptl_rx_stop(struct ssh_ptl *ptl)
  7697. +{
  7698. + int status = 0;
  7699. +
  7700. + if (ptl->rx.thread) {
  7701. + status = kthread_stop(ptl->rx.thread);
  7702. + ptl->rx.thread = NULL;
  7703. + }
  7704. +
  7705. + return status;
  7706. +}
  7707. +
  7708. +static int ssh_ptl_rx_rcvbuf(struct ssh_ptl *ptl, const u8 *buf, size_t n)
  7709. +{
  7710. + int used;
  7711. +
  7712. + if (test_bit(SSH_PTL_SF_SHUTDOWN_BIT, &ptl->state))
  7713. + return used;
  7714. +
  7715. + used = kfifo_in(&ptl->rx.fifo, buf, n);
  7716. + if (used)
  7717. + ssh_ptl_rx_wakeup(ptl);
  7718. +
  7719. + return used;
  7720. +}
  7721. +
  7722. +
  7723. +struct ssh_flush_packet {
  7724. + struct ssh_packet base;
  7725. + struct completion completion;
  7726. + int status;
  7727. +};
  7728. +
  7729. +static void ssh_ptl_flush_complete(struct ssh_packet *p, int status)
  7730. +{
  7731. + struct ssh_flush_packet *packet;
  7732. +
  7733. + packet = container_of(p, struct ssh_flush_packet, base);
  7734. + packet->status = status;
  7735. +}
  7736. +
  7737. +static void ssh_ptl_flush_release(struct ssh_packet *p)
  7738. +{
  7739. + struct ssh_flush_packet *packet;
  7740. +
  7741. + packet = container_of(p, struct ssh_flush_packet, base);
  7742. + complete_all(&packet->completion);
  7743. +}
  7744. +
  7745. +static const struct ssh_packet_ops ssh_flush_packet_ops = {
  7746. + .complete = ssh_ptl_flush_complete,
  7747. + .release = ssh_ptl_flush_release,
  7748. +};
  7749. +
  7750. +/**
  7751. + * ssh_ptl_flush - flush the packet transmission layer
  7752. + * @ptl: packet transmission layer
  7753. + * @timeout: timeout for the flush operation in jiffies
  7754. + *
  7755. + * Queue a special flush-packet and wait for its completion. This packet will
  7756. + * be completed after all other currently queued and pending packets have been
  7757. + * completed. Flushing guarantees that all previously submitted data packets
  7758. + * have been fully completed before this call returns. Additionally, flushing
  7759. + * blocks execution of all later submitted data packets until the flush has been
  7760. + * completed.
  7761. + *
  7762. + * Control (i.e. ACK/NAK) packets that have been submitted after this call will
  7763. + * be placed before the flush packet in the queue, as long as the flush-packet
  7764. + * has not been chosen for processing yet.
  7765. + *
  7766. + * Flushing, even when no new data packets are submitted after this call, does
  7767. + * not guarantee that no more packets are scheduled. For example, incoming
  7768. + * messages can promt automated submission of ACK or NAK type packets. If this
  7769. + * happens while the flush-packet is being processed (i.e. after it has been
  7770. + * taken from the queue), such packets may still be queued after this function
  7771. + * returns.
  7772. + *
  7773. + * Return: Zero on success, -ETIMEDOUT if the flush timed out and has been
  7774. + * canceled as a result of the timeout, or -ESHUTDOWN if the packet transmission
  7775. + * layer has been shut down before this call. May also return -EINTR if the
  7776. + * packet transmission has been interrupted.
  7777. + */
  7778. +static int ssh_ptl_flush(struct ssh_ptl *ptl, unsigned long timeout)
  7779. +{
  7780. + struct ssh_flush_packet packet;
  7781. + struct ssh_packet_args args;
  7782. + int status;
  7783. +
  7784. + args.type = SSH_PACKET_TY_FLUSH | SSH_PACKET_TY_BLOCKING;
  7785. + args.priority = SSH_PACKET_PRIORITY(FLUSH, 0);
  7786. + args.ops = &ssh_flush_packet_ops;
  7787. +
  7788. + ssh_packet_init(&packet.base, &args);
  7789. + init_completion(&packet.completion);
  7790. +
  7791. + status = ssh_ptl_submit(ptl, &packet.base);
  7792. + if (status)
  7793. + return status;
  7794. +
  7795. + ssh_packet_put(&packet.base);
  7796. +
  7797. + if (wait_for_completion_timeout(&packet.completion, timeout))
  7798. + return 0;
  7799. +
  7800. + ssh_ptl_cancel(&packet.base);
  7801. + wait_for_completion(&packet.completion);
  7802. +
  7803. + WARN_ON(packet.status != 0 && packet.status != -ECANCELED
  7804. + && packet.status != -ESHUTDOWN && packet.status != -EINTR);
  7805. +
  7806. + return packet.status == -ECANCELED ? -ETIMEDOUT : status;
  7807. +}
  7808. +
  7809. +/**
  7810. + * ssh_ptl_shutdown - shut down the packet transmission layer
  7811. + * @ptl: packet transmission layer
  7812. + *
  7813. + * Shuts down the packet transmission layer, removing and canceling all queued
  7814. + * and pending packets. Packets canceled by this operation will be completed
  7815. + * with -ESHUTDOWN as status.
  7816. + *
  7817. + * As a result of this function, the transmission layer will be marked as shut
  7818. + * down. Submission of packets after the transmission layer has been shut down
  7819. + * will fail with -ESHUTDOWN.
  7820. + */
  7821. +static void ssh_ptl_shutdown(struct ssh_ptl *ptl)
  7822. +{
  7823. + LIST_HEAD(complete_q);
  7824. + LIST_HEAD(complete_p);
  7825. + struct ssh_packet *p, *n;
  7826. + int status;
  7827. +
  7828. + // ensure that no new packets (including ACK/NAK) can be submitted
  7829. + set_bit(SSH_PTL_SF_SHUTDOWN_BIT, &ptl->state);
  7830. + smp_mb__after_atomic();
  7831. +
  7832. + status = ssh_ptl_rx_stop(ptl);
  7833. + if (status)
  7834. + ptl_err(ptl, "ptl: failed to stop receiver thread\n");
  7835. +
  7836. + status = ssh_ptl_tx_stop(ptl);
  7837. + if (status)
  7838. + ptl_err(ptl, "ptl: failed to stop transmitter thread\n");
  7839. +
  7840. + cancel_delayed_work_sync(&ptl->rtx_timeout.reaper);
  7841. +
  7842. + /*
  7843. + * At this point, all threads have been stopped. This means that the
  7844. + * only references to packets from inside the system are in the queue
  7845. + * and pending set.
  7846. + *
  7847. + * Note: We still need locks here because someone could still be
  7848. + * cancelling packets.
  7849. + *
  7850. + * Note 2: We can re-use queue_node (or pending_node) if we mark the
  7851. + * packet as locked an then remove it from the queue (or pending set
  7852. + * respecitvely). Marking the packet as locked avoids re-queueing
  7853. + * (which should already be prevented by having stopped the treads...)
  7854. + * and not setting QUEUED_BIT (or PENDING_BIT) prevents removal from a
  7855. + * new list via other threads (e.g. canellation).
  7856. + *
  7857. + * Note 3: There may be overlap between complete_p and complete_q.
  7858. + * This is handled via test_and_set_bit on the "completed" flag
  7859. + * (also handles cancelation).
  7860. + */
  7861. +
  7862. + // mark queued packets as locked and move them to complete_q
  7863. + spin_lock(&ptl->queue.lock);
  7864. + list_for_each_entry_safe(p, n, &ptl->queue.head, queue_node) {
  7865. + set_bit(SSH_PACKET_SF_LOCKED_BIT, &p->state);
  7866. + smp_mb__before_atomic();
  7867. + clear_bit(SSH_PACKET_SF_QUEUED_BIT, &p->state);
  7868. +
  7869. + list_del(&p->queue_node);
  7870. + list_add_tail(&p->queue_node, &complete_q);
  7871. + }
  7872. + spin_unlock(&ptl->queue.lock);
  7873. +
  7874. + // mark pending packets as locked and move them to complete_p
  7875. + spin_lock(&ptl->pending.lock);
  7876. + list_for_each_entry_safe(p, n, &ptl->pending.head, pending_node) {
  7877. + set_bit(SSH_PACKET_SF_LOCKED_BIT, &p->state);
  7878. + smp_mb__before_atomic();
  7879. + clear_bit(SSH_PACKET_SF_PENDING_BIT, &p->state);
  7880. +
  7881. + list_del(&p->pending_node);
  7882. + list_add_tail(&p->pending_node, &complete_q);
  7883. + }
  7884. + atomic_set(&ptl->pending.count, 0);
  7885. + spin_unlock(&ptl->pending.lock);
  7886. +
  7887. + // complete and drop packets on complete_q
  7888. + list_for_each_entry(p, &complete_q, queue_node) {
  7889. + if (!test_and_set_bit(SSH_PACKET_SF_COMPLETED_BIT, &p->state))
  7890. + __ssh_ptl_complete(p, -ESHUTDOWN);
  7891. +
  7892. + ssh_packet_put(p);
  7893. + }
  7894. +
  7895. + // complete and drop packets on complete_p
  7896. + list_for_each_entry(p, &complete_p, pending_node) {
  7897. + if (!test_and_set_bit(SSH_PACKET_SF_COMPLETED_BIT, &p->state))
  7898. + __ssh_ptl_complete(p, -ESHUTDOWN);
  7899. +
  7900. + ssh_packet_put(p);
  7901. + }
  7902. +
  7903. + /*
  7904. + * At this point we have guaranteed that the system doesn't reference
  7905. + * any packets any more.
  7906. + */
  7907. +}
  7908. +
  7909. +static inline struct device *ssh_ptl_get_device(struct ssh_ptl *ptl)
  7910. +{
  7911. + return &ptl->serdev->dev;
  7912. +}
  7913. +
  7914. +static int ssh_ptl_init(struct ssh_ptl *ptl, struct serdev_device *serdev,
  7915. + struct ssh_ptl_ops *ops)
  7916. +{
  7917. + int i, status;
  7918. +
  7919. + ptl->serdev = serdev;
  7920. + ptl->state = 0;
  7921. +
  7922. + spin_lock_init(&ptl->queue.lock);
  7923. + INIT_LIST_HEAD(&ptl->queue.head);
  7924. +
  7925. + spin_lock_init(&ptl->pending.lock);
  7926. + INIT_LIST_HEAD(&ptl->pending.head);
  7927. + atomic_set_release(&ptl->pending.count, 0);
  7928. +
  7929. + ptl->tx.thread = NULL;
  7930. + ptl->tx.thread_signal = false;
  7931. + ptl->tx.packet = NULL;
  7932. + ptl->tx.offset = 0;
  7933. + init_waitqueue_head(&ptl->tx.thread_wq);
  7934. + init_waitqueue_head(&ptl->tx.packet_wq);
  7935. +
  7936. + ptl->rx.thread = NULL;
  7937. + init_waitqueue_head(&ptl->rx.wq);
  7938. +
  7939. + ptl->rtx_timeout.timeout = SSH_PTL_PACKET_TIMEOUT;
  7940. + ptl->rtx_timeout.expires = KTIME_MAX;
  7941. + INIT_DELAYED_WORK(&ptl->rtx_timeout.reaper, ssh_ptl_timeout_reap);
  7942. +
  7943. + ptl->ops = *ops;
  7944. +
  7945. + // initialize SEQ blacklist with invalid sequence IDs
  7946. + for (i = 0; i < ARRAY_SIZE(ptl->rx.blacklist.seqs); i++)
  7947. + ptl->rx.blacklist.seqs[i] = 0xFFFF;
  7948. + ptl->rx.blacklist.offset = 0;
  7949. +
  7950. + status = kfifo_alloc(&ptl->rx.fifo, SSH_PTL_RX_FIFO_LEN, GFP_KERNEL);
  7951. + if (status)
  7952. + return status;
  7953. +
  7954. + status = sshp_buf_alloc(&ptl->rx.buf, SSH_PTL_RX_BUF_LEN, GFP_KERNEL);
  7955. + if (status)
  7956. + kfifo_free(&ptl->rx.fifo);
  7957. +
  7958. + return status;
  7959. +}
  7960. +
  7961. +static void ssh_ptl_destroy(struct ssh_ptl *ptl)
  7962. +{
  7963. + kfifo_free(&ptl->rx.fifo);
  7964. + sshp_buf_free(&ptl->rx.buf);
  7965. +}
  7966. +
  7967. +
  7968. +/* -- Request transport layer (rtl). ---------------------------------------- */
  7969. +
  7970. +#define SSH_RTL_REQUEST_TIMEOUT ms_to_ktime(1000)
  7971. +#define SSH_RTL_REQUEST_TIMEOUT_RESOLUTION ms_to_ktime(max(2000 / HZ, 50))
  7972. +
  7973. +#define SSH_RTL_MAX_PENDING 3
  7974. +
  7975. +
  7976. +enum ssh_rtl_state_flags {
  7977. + SSH_RTL_SF_SHUTDOWN_BIT,
  7978. +};
  7979. +
  7980. +struct ssh_rtl_ops {
  7981. + void (*handle_event)(struct ssh_rtl *rtl, const struct ssh_command *cmd,
  7982. + const struct sshp_span *data);
  7983. +};
  7984. +
  7985. +struct ssh_rtl {
  7986. + struct ssh_ptl ptl;
  7987. + unsigned long state;
  7988. +
  7989. + struct {
  7990. + spinlock_t lock;
  7991. + struct list_head head;
  7992. + } queue;
  7993. +
  7994. + struct {
  7995. + spinlock_t lock;
  7996. + struct list_head head;
  7997. + atomic_t count;
  7998. + } pending;
  7999. +
  8000. + struct {
  8001. + struct work_struct work;
  8002. + } tx;
  8003. +
  8004. + struct {
  8005. + ktime_t timeout;
  8006. + ktime_t expires;
  8007. + struct delayed_work reaper;
  8008. + } rtx_timeout;
  8009. +
  8010. + struct ssh_rtl_ops ops;
  8011. +};
  8012. +
  8013. +
  8014. +#define rtl_dbg(r, fmt, ...) ptl_dbg(&(r)->ptl, fmt, ##__VA_ARGS__)
  8015. +#define rtl_info(p, fmt, ...) ptl_info(&(p)->ptl, fmt, ##__VA_ARGS__)
  8016. +#define rtl_warn(r, fmt, ...) ptl_warn(&(r)->ptl, fmt, ##__VA_ARGS__)
  8017. +#define rtl_err(r, fmt, ...) ptl_err(&(r)->ptl, fmt, ##__VA_ARGS__)
  8018. +#define rtl_dbg_cond(r, fmt, ...) __ssam_prcond(rtl_dbg, r, fmt, ##__VA_ARGS__)
  8019. +
  8020. +#define to_ssh_rtl(ptr, member) \
  8021. + container_of(ptr, struct ssh_rtl, member)
  8022. +
  8023. +#define to_ssh_request(ptr, member) \
  8024. + container_of(ptr, struct ssh_request, member)
  8025. +
  8026. +
  8027. +/**
  8028. + * ssh_rtl_should_drop_response - error injection hook to drop request responses
  8029. + *
  8030. + * Useful to cause request transmission timeouts in the driver by dropping the
  8031. + * response to a request.
  8032. + */
  8033. +static noinline_if_inject bool ssh_rtl_should_drop_response(void)
  8034. +{
  8035. + return false;
  8036. +}
  8037. +ALLOW_ERROR_INJECTION(ssh_rtl_should_drop_response, TRUE);
  8038. +
  8039. +
  8040. +static inline void ssh_request_get(struct ssh_request *rqst)
  8041. +{
  8042. + ssh_packet_get(&rqst->packet);
  8043. +}
  8044. +
  8045. +static inline void ssh_request_put(struct ssh_request *rqst)
  8046. +{
  8047. + ssh_packet_put(&rqst->packet);
  8048. +}
  8049. +
  8050. +
  8051. +static inline u16 ssh_request_get_rqid(struct ssh_request *rqst)
  8052. +{
  8053. + return get_unaligned_le16(rqst->packet.data
  8054. + + SSH_MSGOFFSET_COMMAND(rqid));
  8055. +}
  8056. +
  8057. +static inline u32 ssh_request_get_rqid_safe(struct ssh_request *rqst)
  8058. +{
  8059. + if (!rqst->packet.data)
  8060. + return -1;
  8061. +
  8062. + return ssh_request_get_rqid(rqst);
  8063. +}
  8064. +
  8065. +
  8066. +static void ssh_rtl_queue_remove(struct ssh_request *rqst)
  8067. +{
  8068. + bool remove;
  8069. +
  8070. + spin_lock(&rqst->rtl->queue.lock);
  8071. +
  8072. + remove = test_and_clear_bit(SSH_REQUEST_SF_QUEUED_BIT, &rqst->state);
  8073. + if (remove)
  8074. + list_del(&rqst->node);
  8075. +
  8076. + spin_unlock(&rqst->rtl->queue.lock);
  8077. +
  8078. + if (remove)
  8079. + ssh_request_put(rqst);
  8080. +}
  8081. +
  8082. +static void ssh_rtl_pending_remove(struct ssh_request *rqst)
  8083. +{
  8084. + bool remove;
  8085. +
  8086. + spin_lock(&rqst->rtl->pending.lock);
  8087. +
  8088. + remove = test_and_clear_bit(SSH_REQUEST_SF_PENDING_BIT, &rqst->state);
  8089. + if (remove) {
  8090. + atomic_dec(&rqst->rtl->pending.count);
  8091. + list_del(&rqst->node);
  8092. + }
  8093. +
  8094. + spin_unlock(&rqst->rtl->pending.lock);
  8095. +
  8096. + if (remove)
  8097. + ssh_request_put(rqst);
  8098. +}
  8099. +
  8100. +
  8101. +static void ssh_rtl_complete_with_status(struct ssh_request *rqst, int status)
  8102. +{
  8103. + struct ssh_rtl *rtl = READ_ONCE(rqst->rtl);
  8104. +
  8105. + trace_ssam_request_complete(rqst, status);
  8106. +
  8107. + // rqst->rtl may not be set if we're cancelling before submitting
  8108. + rtl_dbg_cond(rtl, "rtl: completing request (rqid: 0x%04x,"
  8109. + " status: %d)\n", ssh_request_get_rqid_safe(rqst), status);
  8110. +
  8111. + rqst->ops->complete(rqst, NULL, NULL, status);
  8112. +}
  8113. +
  8114. +static void ssh_rtl_complete_with_rsp(struct ssh_request *rqst,
  8115. + const struct ssh_command *cmd,
  8116. + const struct sshp_span *data)
  8117. +{
  8118. + trace_ssam_request_complete(rqst, 0);
  8119. +
  8120. + rtl_dbg(rqst->rtl, "rtl: completing request with response"
  8121. + " (rqid: 0x%04x)\n", ssh_request_get_rqid(rqst));
  8122. +
  8123. + rqst->ops->complete(rqst, cmd, data, 0);
  8124. +}
  8125. +
  8126. +
  8127. +static bool ssh_rtl_tx_can_process(struct ssh_request *rqst)
  8128. +{
  8129. + if (test_bit(SSH_REQUEST_TY_FLUSH_BIT, &rqst->state))
  8130. + return !atomic_read(&rqst->rtl->pending.count);
  8131. +
  8132. + return atomic_read(&rqst->rtl->pending.count) < SSH_RTL_MAX_PENDING;
  8133. +}
  8134. +
  8135. +static struct ssh_request *ssh_rtl_tx_next(struct ssh_rtl *rtl)
  8136. +{
  8137. + struct ssh_request *rqst = ERR_PTR(-ENOENT);
  8138. + struct ssh_request *p, *n;
  8139. +
  8140. + spin_lock(&rtl->queue.lock);
  8141. +
  8142. + // find first non-locked request and remove it
  8143. + list_for_each_entry_safe(p, n, &rtl->queue.head, node) {
  8144. + if (unlikely(test_bit(SSH_REQUEST_SF_LOCKED_BIT, &p->state)))
  8145. + continue;
  8146. +
  8147. + if (!ssh_rtl_tx_can_process(p)) {
  8148. + rqst = ERR_PTR(-EBUSY);
  8149. + break;
  8150. + }
  8151. +
  8152. + /*
  8153. + * Remove from queue and mark as transmitting. Ensure that the
  8154. + * state does not get zero via memory barrier.
  8155. + */
  8156. + set_bit(SSH_REQUEST_SF_TRANSMITTING_BIT, &p->state);
  8157. + smp_mb__before_atomic();
  8158. + clear_bit(SSH_REQUEST_SF_QUEUED_BIT, &p->state);
  8159. +
  8160. + list_del(&p->node);
  8161. +
  8162. + rqst = p;
  8163. + break;
  8164. + }
  8165. +
  8166. + spin_unlock(&rtl->queue.lock);
  8167. + return rqst;
  8168. +}
  8169. +
  8170. +static int ssh_rtl_tx_pending_push(struct ssh_request *rqst)
  8171. +{
  8172. + struct ssh_rtl *rtl = rqst->rtl;
  8173. +
  8174. + spin_lock(&rtl->pending.lock);
  8175. +
  8176. + if (test_bit(SSH_REQUEST_SF_LOCKED_BIT, &rqst->state)) {
  8177. + spin_unlock(&rtl->pending.lock);
  8178. + return -EINVAL;
  8179. + }
  8180. +
  8181. + if (test_and_set_bit(SSH_REQUEST_SF_PENDING_BIT, &rqst->state)) {
  8182. + spin_unlock(&rtl->pending.lock);
  8183. + return -EALREADY;
  8184. + }
  8185. +
  8186. + atomic_inc(&rtl->pending.count);
  8187. + ssh_request_get(rqst);
  8188. + list_add_tail(&rqst->node, &rtl->pending.head);
  8189. +
  8190. + spin_unlock(&rtl->pending.lock);
  8191. + return 0;
  8192. +}
  8193. +
  8194. +static int ssh_rtl_tx_try_process_one(struct ssh_rtl *rtl)
  8195. +{
  8196. + struct ssh_request *rqst;
  8197. + int status;
  8198. +
  8199. + // get and prepare next request for transmit
  8200. + rqst = ssh_rtl_tx_next(rtl);
  8201. + if (IS_ERR(rqst))
  8202. + return PTR_ERR(rqst);
  8203. +
  8204. + // add to/mark as pending
  8205. + status = ssh_rtl_tx_pending_push(rqst);
  8206. + if (status) {
  8207. + ssh_request_put(rqst);
  8208. + return -EAGAIN;
  8209. + }
  8210. +
  8211. + // submit packet
  8212. + status = ssh_ptl_submit(&rtl->ptl, &rqst->packet);
  8213. + if (status == -ESHUTDOWN) {
  8214. + /*
  8215. + * Packet has been refused due to the packet layer shutting
  8216. + * down. Complete it here.
  8217. + */
  8218. + set_bit(SSH_REQUEST_SF_LOCKED_BIT, &rqst->state);
  8219. + smp_mb__after_atomic();
  8220. +
  8221. + ssh_rtl_pending_remove(rqst);
  8222. + ssh_rtl_complete_with_status(rqst, -ESHUTDOWN);
  8223. +
  8224. + ssh_request_put(rqst);
  8225. + return -ESHUTDOWN;
  8226. +
  8227. + } else if (status) {
  8228. + /*
  8229. + * If submitting the packet failed and the packet layer isn't
  8230. + * shutting down, the packet has either been submmitted/queued
  8231. + * before (-EALREADY, which cannot happen as we have guaranteed
  8232. + * that requests cannot be re-submitted), or the packet was
  8233. + * marked as locked (-EINVAL). To mark the packet locked at this
  8234. + * stage, the request, and thus the packets itself, had to have
  8235. + * been canceled. Simply drop the reference. Cancellation itself
  8236. + * will remove it from the set of pending requests.
  8237. + */
  8238. +
  8239. + WARN_ON(status != -EINVAL);
  8240. +
  8241. + ssh_request_put(rqst);
  8242. + return -EAGAIN;
  8243. + }
  8244. +
  8245. + ssh_request_put(rqst);
  8246. + return 0;
  8247. +}
  8248. +
  8249. +static bool ssh_rtl_queue_empty(struct ssh_rtl *rtl)
  8250. +{
  8251. + bool empty;
  8252. +
  8253. + spin_lock(&rtl->queue.lock);
  8254. + empty = list_empty(&rtl->queue.head);
  8255. + spin_unlock(&rtl->queue.lock);
  8256. +
  8257. + return empty;
  8258. +}
  8259. +
  8260. +static bool ssh_rtl_tx_schedule(struct ssh_rtl *rtl)
  8261. +{
  8262. + if (atomic_read(&rtl->pending.count) >= SSH_RTL_MAX_PENDING)
  8263. + return false;
  8264. +
  8265. + if (ssh_rtl_queue_empty(rtl))
  8266. + return false;
  8267. +
  8268. + return schedule_work(&rtl->tx.work);
  8269. +}
  8270. +
  8271. +static void ssh_rtl_tx_work_fn(struct work_struct *work)
  8272. +{
  8273. + struct ssh_rtl *rtl = to_ssh_rtl(work, tx.work);
  8274. + int i, status;
  8275. +
  8276. + /*
  8277. + * Try to be nice and not block the workqueue: Run a maximum of 10
  8278. + * tries, then re-submit if necessary. This should not be neccesary,
  8279. + * for normal execution, but guarantee it anyway.
  8280. + */
  8281. + for (i = 0; i < 10; i++) {
  8282. + status = ssh_rtl_tx_try_process_one(rtl);
  8283. + if (status == -ENOENT || status == -EBUSY)
  8284. + return; // no more requests to process
  8285. +
  8286. + if (status == -ESHUTDOWN) {
  8287. + /*
  8288. + * Packet system shutting down. No new packets can be
  8289. + * transmitted. Return silently, the party initiating
  8290. + * the shutdown should handle the rest.
  8291. + */
  8292. + return;
  8293. + }
  8294. +
  8295. + WARN_ON(status != 0 && status != -EAGAIN);
  8296. + }
  8297. +
  8298. + // out of tries, reschedule
  8299. + ssh_rtl_tx_schedule(rtl);
  8300. +}
  8301. +
  8302. +
  8303. +static int ssh_rtl_submit(struct ssh_rtl *rtl, struct ssh_request *rqst)
  8304. +{
  8305. + trace_ssam_request_submit(rqst);
  8306. +
  8307. + /*
  8308. + * Ensure that requests expecting a response are sequenced. If this
  8309. + * invariant ever changes, see the comment in ssh_rtl_complete on what
  8310. + * is required to be changed in the code.
  8311. + */
  8312. + if (test_bit(SSH_REQUEST_TY_HAS_RESPONSE_BIT, &rqst->state))
  8313. + if (!(rqst->packet.type & SSH_PACKET_TY_SEQUENCED))
  8314. + return -EINVAL;
  8315. +
  8316. + // try to set rtl and check if this request has already been submitted
  8317. + if (cmpxchg(&rqst->rtl, NULL, rtl) != NULL)
  8318. + return -EALREADY;
  8319. +
  8320. + spin_lock(&rtl->queue.lock);
  8321. +
  8322. + if (test_bit(SSH_RTL_SF_SHUTDOWN_BIT, &rtl->state)) {
  8323. + spin_unlock(&rtl->queue.lock);
  8324. + return -ESHUTDOWN;
  8325. + }
  8326. +
  8327. + if (test_bit(SSH_REQUEST_SF_LOCKED_BIT, &rqst->state)) {
  8328. + spin_unlock(&rtl->queue.lock);
  8329. + return -EINVAL;
  8330. + }
  8331. +
  8332. + ssh_request_get(rqst);
  8333. + set_bit(SSH_REQUEST_SF_QUEUED_BIT, &rqst->state);
  8334. + list_add_tail(&rqst->node, &rtl->queue.head);
  8335. +
  8336. + spin_unlock(&rtl->queue.lock);
  8337. +
  8338. + ssh_rtl_tx_schedule(rtl);
  8339. + return 0;
  8340. +}
  8341. +
  8342. +
  8343. +static void ssh_rtl_timeout_reaper_mod(struct ssh_rtl *rtl, ktime_t now,
  8344. + ktime_t expires)
  8345. +{
  8346. + unsigned long delta = msecs_to_jiffies(ktime_ms_delta(expires, now));
  8347. + ktime_t aexp = ktime_add(expires, SSH_RTL_REQUEST_TIMEOUT_RESOLUTION);
  8348. + ktime_t old;
  8349. +
  8350. + // re-adjust / schedule reaper if it is above resolution delta
  8351. + old = READ_ONCE(rtl->rtx_timeout.expires);
  8352. + while (ktime_before(aexp, old))
  8353. + old = cmpxchg64(&rtl->rtx_timeout.expires, old, expires);
  8354. +
  8355. + // if we updated the reaper expiration, modify work timeout
  8356. + if (old == expires)
  8357. + mod_delayed_work(system_wq, &rtl->rtx_timeout.reaper, delta);
  8358. +}
  8359. +
  8360. +static void ssh_rtl_timeout_start(struct ssh_request *rqst)
  8361. +{
  8362. + struct ssh_rtl *rtl = rqst->rtl;
  8363. + ktime_t timestamp = ktime_get_coarse_boottime();
  8364. + ktime_t timeout = rtl->rtx_timeout.timeout;
  8365. +
  8366. + if (test_bit(SSH_REQUEST_SF_LOCKED_BIT, &rqst->state))
  8367. + return;
  8368. +
  8369. + WRITE_ONCE(rqst->timestamp, timestamp);
  8370. + smp_mb__after_atomic();
  8371. +
  8372. + ssh_rtl_timeout_reaper_mod(rqst->rtl, timestamp, timestamp + timeout);
  8373. +}
  8374. +
  8375. +
  8376. +static void ssh_rtl_complete(struct ssh_rtl *rtl,
  8377. + const struct ssh_command *command,
  8378. + const struct sshp_span *command_data)
  8379. +{
  8380. + struct ssh_request *r = NULL;
  8381. + struct ssh_request *p, *n;
  8382. + u16 rqid = get_unaligned_le16(&command->rqid);
  8383. +
  8384. + trace_ssam_rx_response_received(command, command_data->len);
  8385. +
  8386. + /*
  8387. + * Get request from pending based on request ID and mark it as response
  8388. + * received and locked.
  8389. + */
  8390. + spin_lock(&rtl->pending.lock);
  8391. + list_for_each_entry_safe(p, n, &rtl->pending.head, node) {
  8392. + // we generally expect requests to be processed in order
  8393. + if (unlikely(ssh_request_get_rqid(p) != rqid))
  8394. + continue;
  8395. +
  8396. + // simulate response timeout
  8397. + if (ssh_rtl_should_drop_response()) {
  8398. + spin_unlock(&rtl->pending.lock);
  8399. +
  8400. + trace_ssam_ei_rx_drop_response(p);
  8401. + rtl_info(rtl, "request error injection: "
  8402. + "dropping response for request %p\n",
  8403. + &p->packet);
  8404. + return;
  8405. + }
  8406. +
  8407. + /*
  8408. + * Mark as "response received" and "locked" as we're going to
  8409. + * complete it. Ensure that the state doesn't get zero by
  8410. + * employing a memory barrier.
  8411. + */
  8412. + set_bit(SSH_REQUEST_SF_LOCKED_BIT, &p->state);
  8413. + set_bit(SSH_REQUEST_SF_RSPRCVD_BIT, &p->state);
  8414. + smp_mb__before_atomic();
  8415. + clear_bit(SSH_REQUEST_SF_PENDING_BIT, &p->state);
  8416. +
  8417. + atomic_dec(&rtl->pending.count);
  8418. + list_del(&p->node);
  8419. +
  8420. + r = p;
  8421. + break;
  8422. + }
  8423. + spin_unlock(&rtl->pending.lock);
  8424. +
  8425. + if (!r) {
  8426. + rtl_warn(rtl, "rtl: dropping unexpected command message"
  8427. + " (rqid = 0x%04x)\n", rqid);
  8428. + return;
  8429. + }
  8430. +
  8431. + // if the request hasn't been completed yet, we will do this now
  8432. + if (test_and_set_bit(SSH_REQUEST_SF_COMPLETED_BIT, &r->state)) {
  8433. + ssh_request_put(r);
  8434. + ssh_rtl_tx_schedule(rtl);
  8435. + return;
  8436. + }
  8437. +
  8438. + /*
  8439. + * Make sure the request has been transmitted. In case of a sequenced
  8440. + * request, we are guaranteed that the completion callback will run on
  8441. + * the receiver thread directly when the ACK for the packet has been
  8442. + * received. Similarly, this function is guaranteed to run on the
  8443. + * receiver thread. Thus we are guaranteed that if the packet has been
  8444. + * successfully transmitted and received an ACK, the transmitted flag
  8445. + * has been set and is visible here.
  8446. + *
  8447. + * We are currently not handling unsequenced packets here, as those
  8448. + * should never expect a response as ensured in ssh_rtl_submit. If this
  8449. + * ever changes, one would have to test for
  8450. + *
  8451. + * (r->state & (transmitting | transmitted))
  8452. + *
  8453. + * on unsequenced packets to determine if they could have been
  8454. + * transmitted. There are no synchronization guarantees as in the
  8455. + * sequenced case, since, in this case, the callback function will not
  8456. + * run on the same thread. Thus an exact determination is impossible.
  8457. + */
  8458. + if (!test_bit(SSH_REQUEST_SF_TRANSMITTED_BIT, &r->state)) {
  8459. + rtl_err(rtl, "rtl: received response before ACK for request"
  8460. + " (rqid = 0x%04x)\n", rqid);
  8461. +
  8462. + /*
  8463. + * NB: Timeout has already been canceled, request already been
  8464. + * removed from pending and marked as locked and completed. As
  8465. + * we receive a "false" response, the packet might still be
  8466. + * queued though.
  8467. + */
  8468. + ssh_rtl_queue_remove(r);
  8469. +
  8470. + ssh_rtl_complete_with_status(r, -EREMOTEIO);
  8471. + ssh_request_put(r);
  8472. +
  8473. + ssh_rtl_tx_schedule(rtl);
  8474. + return;
  8475. + }
  8476. +
  8477. + /*
  8478. + * NB: Timeout has already been canceled, request already been
  8479. + * removed from pending and marked as locked and completed. The request
  8480. + * can also not be queued any more, as it has been marked as
  8481. + * transmitting and later transmitted. Thus no need to remove it from
  8482. + * anywhere.
  8483. + */
  8484. +
  8485. + ssh_rtl_complete_with_rsp(r, command, command_data);
  8486. + ssh_request_put(r);
  8487. +
  8488. + ssh_rtl_tx_schedule(rtl);
  8489. +}
  8490. +
  8491. +
  8492. +static bool ssh_rtl_cancel_nonpending(struct ssh_request *r)
  8493. +{
  8494. + unsigned long state, fixed;
  8495. + bool remove;
  8496. +
  8497. + /*
  8498. + * Handle unsubmitted request: Try to mark the packet as locked,
  8499. + * expecting the state to be zero (i.e. unsubmitted). Note that, if
  8500. + * setting the state worked, we might still be adding the packet to the
  8501. + * queue in a currently executing submit call. In that case, however,
  8502. + * rqst->rtl must have been set previously, as locked is checked after
  8503. + * setting rqst->rtl. Thus only if we successfully lock this request and
  8504. + * rqst->rtl is NULL, we have successfully removed the request.
  8505. + * Otherwise we need to try and grab it from the queue.
  8506. + *
  8507. + * Note that if the CMPXCHG fails, we are guaranteed that rqst->rtl has
  8508. + * been set and is non-NULL, as states can only be nonzero after this
  8509. + * has been set. Also note that we need to fetch the static (type) flags
  8510. + * to ensure that they don't cause the cmpxchg to fail.
  8511. + */
  8512. + fixed = READ_ONCE(r->state) & SSH_REQUEST_FLAGS_TY_MASK;
  8513. + state = cmpxchg(&r->state, fixed, SSH_REQUEST_SF_LOCKED_BIT);
  8514. + if (!state && !READ_ONCE(r->rtl)) {
  8515. + if (test_and_set_bit(SSH_REQUEST_SF_COMPLETED_BIT, &r->state))
  8516. + return true;
  8517. +
  8518. + ssh_rtl_complete_with_status(r, -ECANCELED);
  8519. + return true;
  8520. + }
  8521. +
  8522. + spin_lock(&r->rtl->queue.lock);
  8523. +
  8524. + /*
  8525. + * Note: 1) Requests cannot be re-submitted. 2) If a request is queued,
  8526. + * it cannot be "transmitting"/"pending" yet. Thus, if we successfully
  8527. + * remove the the request here, we have removed all its occurences in
  8528. + * the system.
  8529. + */
  8530. +
  8531. + remove = test_and_clear_bit(SSH_REQUEST_SF_QUEUED_BIT, &r->state);
  8532. + if (!remove) {
  8533. + spin_unlock(&r->rtl->queue.lock);
  8534. + return false;
  8535. + }
  8536. +
  8537. + set_bit(SSH_REQUEST_SF_LOCKED_BIT, &r->state);
  8538. + list_del(&r->node);
  8539. +
  8540. + spin_unlock(&r->rtl->queue.lock);
  8541. +
  8542. + ssh_request_put(r); // drop reference obtained from queue
  8543. +
  8544. + if (test_and_set_bit(SSH_REQUEST_SF_COMPLETED_BIT, &r->state))
  8545. + return true;
  8546. +
  8547. + ssh_rtl_complete_with_status(r, -ECANCELED);
  8548. + return true;
  8549. +}
  8550. +
  8551. +static bool ssh_rtl_cancel_pending(struct ssh_request *r)
  8552. +{
  8553. + // if the packet is already locked, it's going to be removed shortly
  8554. + if (test_and_set_bit(SSH_REQUEST_SF_LOCKED_BIT, &r->state))
  8555. + return true;
  8556. +
  8557. + /*
  8558. + * Now that we have locked the packet, we have guaranteed that it can't
  8559. + * be added to the system any more. If rqst->rtl is zero, the locked
  8560. + * check in ssh_rtl_submit has not been run and any submission,
  8561. + * currently in progress or called later, won't add the packet. Thus we
  8562. + * can directly complete it.
  8563. + */
  8564. + if (!READ_ONCE(r->rtl)) {
  8565. + if (test_and_set_bit(SSH_REQUEST_SF_COMPLETED_BIT, &r->state))
  8566. + return true;
  8567. +
  8568. + ssh_rtl_complete_with_status(r, -ECANCELED);
  8569. + return true;
  8570. + }
  8571. +
  8572. + /*
  8573. + * Try to cancel the packet. If the packet has not been completed yet,
  8574. + * this will subsequently (and synchronously) call the completion
  8575. + * callback of the packet, which will complete the request.
  8576. + */
  8577. + ssh_ptl_cancel(&r->packet);
  8578. +
  8579. + /*
  8580. + * If the packet has been completed with success, i.e. has not been
  8581. + * canceled by the above call, the request may not have been completed
  8582. + * yet (may be waiting for a response). Check if we need to do this
  8583. + * here.
  8584. + */
  8585. + if (test_and_set_bit(SSH_REQUEST_SF_COMPLETED_BIT, &r->state))
  8586. + return true;
  8587. +
  8588. + ssh_rtl_queue_remove(r);
  8589. + ssh_rtl_pending_remove(r);
  8590. + ssh_rtl_complete_with_status(r, -ECANCELED);
  8591. +
  8592. + return true;
  8593. +}
  8594. +
  8595. +static bool ssh_rtl_cancel(struct ssh_request *rqst, bool pending)
  8596. +{
  8597. + struct ssh_rtl *rtl;
  8598. + bool canceled;
  8599. +
  8600. + if (test_and_set_bit(SSH_REQUEST_SF_CANCELED_BIT, &rqst->state))
  8601. + return true;
  8602. +
  8603. + trace_ssam_request_cancel(rqst);
  8604. +
  8605. + if (pending)
  8606. + canceled = ssh_rtl_cancel_pending(rqst);
  8607. + else
  8608. + canceled = ssh_rtl_cancel_nonpending(rqst);
  8609. +
  8610. + // note: rqst->rtl may be NULL if request has not been submitted yet
  8611. + rtl = READ_ONCE(rqst->rtl);
  8612. + if (canceled && rtl)
  8613. + ssh_rtl_tx_schedule(rtl);
  8614. +
  8615. + return canceled;
  8616. +}
  8617. +
  8618. +
  8619. +static void ssh_rtl_packet_callback(struct ssh_packet *p, int status)
  8620. +{
  8621. + struct ssh_request *r = to_ssh_request(p, packet);
  8622. +
  8623. + if (unlikely(status)) {
  8624. + set_bit(SSH_REQUEST_SF_LOCKED_BIT, &r->state);
  8625. +
  8626. + if (test_and_set_bit(SSH_REQUEST_SF_COMPLETED_BIT, &r->state))
  8627. + return;
  8628. +
  8629. + /*
  8630. + * The packet may get cancelled even though it has not been
  8631. + * submitted yet. The request may still be queued. Check the
  8632. + * queue and remove it if necessary. As the timeout would have
  8633. + * been started in this function on success, there's no need to
  8634. + * cancel it here.
  8635. + */
  8636. + ssh_rtl_queue_remove(r);
  8637. + ssh_rtl_pending_remove(r);
  8638. + ssh_rtl_complete_with_status(r, status);
  8639. +
  8640. + ssh_rtl_tx_schedule(r->rtl);
  8641. + return;
  8642. + }
  8643. +
  8644. + /*
  8645. + * Mark as transmitted, ensure that state doesn't get zero by inserting
  8646. + * a memory barrier.
  8647. + */
  8648. + set_bit(SSH_REQUEST_SF_TRANSMITTED_BIT, &r->state);
  8649. + smp_mb__before_atomic();
  8650. + clear_bit(SSH_REQUEST_SF_TRANSMITTING_BIT, &r->state);
  8651. +
  8652. + // if we expect a response, we just need to start the timeout
  8653. + if (test_bit(SSH_REQUEST_TY_HAS_RESPONSE_BIT, &r->state)) {
  8654. + ssh_rtl_timeout_start(r);
  8655. + return;
  8656. + }
  8657. +
  8658. + /*
  8659. + * If we don't expect a response, lock, remove, and complete the
  8660. + * request. Note that, at this point, the request is guaranteed to have
  8661. + * left the queue and no timeout has been started. Thus we only need to
  8662. + * remove it from pending. If the request has already been completed (it
  8663. + * may have been canceled) return.
  8664. + */
  8665. +
  8666. + set_bit(SSH_REQUEST_SF_LOCKED_BIT, &r->state);
  8667. + if (test_and_set_bit(SSH_REQUEST_SF_COMPLETED_BIT, &r->state))
  8668. + return;
  8669. +
  8670. + ssh_rtl_pending_remove(r);
  8671. + ssh_rtl_complete_with_status(r, 0);
  8672. +
  8673. + ssh_rtl_tx_schedule(r->rtl);
  8674. +}
  8675. +
  8676. +
  8677. +static ktime_t ssh_request_get_expiration(struct ssh_request *r, ktime_t timeo)
  8678. +{
  8679. + ktime_t timestamp = READ_ONCE(r->timestamp);
  8680. +
  8681. + if (timestamp != KTIME_MAX)
  8682. + return ktime_add(timestamp, timeo);
  8683. + else
  8684. + return KTIME_MAX;
  8685. +}
  8686. +
  8687. +static void ssh_rtl_timeout_reap(struct work_struct *work)
  8688. +{
  8689. + struct ssh_rtl *rtl = to_ssh_rtl(work, rtx_timeout.reaper.work);
  8690. + struct ssh_request *r, *n;
  8691. + LIST_HEAD(claimed);
  8692. + ktime_t now = ktime_get_coarse_boottime();
  8693. + ktime_t timeout = rtl->rtx_timeout.timeout;
  8694. + ktime_t next = KTIME_MAX;
  8695. +
  8696. + trace_ssam_rtl_timeout_reap("pending", atomic_read(&rtl->pending.count));
  8697. +
  8698. + /*
  8699. + * Mark reaper as "not pending". This is done before checking any
  8700. + * requests to avoid lost-update type problems.
  8701. + */
  8702. + WRITE_ONCE(rtl->rtx_timeout.expires, KTIME_MAX);
  8703. + smp_mb__after_atomic();
  8704. +
  8705. + spin_lock(&rtl->pending.lock);
  8706. + list_for_each_entry_safe(r, n, &rtl->pending.head, node) {
  8707. + ktime_t expires = ssh_request_get_expiration(r, timeout);
  8708. +
  8709. + /*
  8710. + * Check if the timeout hasn't expired yet. Find out next
  8711. + * expiration date to be handled after this run.
  8712. + */
  8713. + if (ktime_after(expires, now)) {
  8714. + next = ktime_before(expires, next) ? expires : next;
  8715. + continue;
  8716. + }
  8717. +
  8718. + // avoid further transitions if locked
  8719. + if (test_and_set_bit(SSH_REQUEST_SF_LOCKED_BIT, &r->state))
  8720. + continue;
  8721. +
  8722. + /*
  8723. + * We have now marked the packet as locked. Thus it cannot be
  8724. + * added to the pending or queued lists again after we've
  8725. + * removed it here. We can therefore re-use the node of this
  8726. + * packet temporarily.
  8727. + */
  8728. +
  8729. + clear_bit(SSH_REQUEST_SF_PENDING_BIT, &r->state);
  8730. +
  8731. + atomic_dec(&rtl->pending.count);
  8732. + list_del(&r->node);
  8733. +
  8734. + list_add_tail(&r->node, &claimed);
  8735. + }
  8736. + spin_unlock(&rtl->pending.lock);
  8737. +
  8738. + // cancel and complete the request
  8739. + list_for_each_entry_safe(r, n, &claimed, node) {
  8740. + trace_ssam_request_timeout(r);
  8741. +
  8742. + /*
  8743. + * At this point we've removed the packet from pending. This
  8744. + * means that we've obtained the last (only) reference of the
  8745. + * system to it. Thus we can just complete it.
  8746. + */
  8747. + if (!test_and_set_bit(SSH_REQUEST_SF_COMPLETED_BIT, &r->state))
  8748. + ssh_rtl_complete_with_status(r, -ETIMEDOUT);
  8749. +
  8750. + // drop the reference we've obtained by removing it from pending
  8751. + list_del(&r->node);
  8752. + ssh_request_put(r);
  8753. + }
  8754. +
  8755. + // ensure that reaper doesn't run again immediately
  8756. + next = max(next, ktime_add(now, SSH_RTL_REQUEST_TIMEOUT_RESOLUTION));
  8757. + if (next != KTIME_MAX)
  8758. + ssh_rtl_timeout_reaper_mod(rtl, now, next);
  8759. +
  8760. + ssh_rtl_tx_schedule(rtl);
  8761. +}
  8762. +
  8763. +
  8764. +static void ssh_rtl_rx_event(struct ssh_rtl *rtl, const struct ssh_command *cmd,
  8765. + const struct sshp_span *data)
  8766. +{
  8767. + trace_ssam_rx_event_received(cmd, data->len);
  8768. +
  8769. + rtl_dbg(rtl, "rtl: handling event (rqid: 0x%04x)\n",
  8770. + get_unaligned_le16(&cmd->rqid));
  8771. +
  8772. + rtl->ops.handle_event(rtl, cmd, data);
  8773. +}
  8774. +
  8775. +static void ssh_rtl_rx_command(struct ssh_ptl *p, const struct sshp_span *data)
  8776. +{
  8777. + struct ssh_rtl *rtl = to_ssh_rtl(p, ptl);
  8778. + struct device *dev = &p->serdev->dev;
  8779. + struct ssh_command *command;
  8780. + struct sshp_span command_data;
  8781. +
  8782. + if (sshp_parse_command(dev, data, &command, &command_data))
  8783. + return;
  8784. +
  8785. + if (ssh_rqid_is_event(get_unaligned_le16(&command->rqid)))
  8786. + ssh_rtl_rx_event(rtl, command, &command_data);
  8787. + else
  8788. + ssh_rtl_complete(rtl, command, &command_data);
  8789. +}
  8790. +
  8791. +static void ssh_rtl_rx_data(struct ssh_ptl *p, const struct sshp_span *data)
  8792. +{
  8793. + switch (data->ptr[0]) {
  8794. + case SSH_PLD_TYPE_CMD:
  8795. + ssh_rtl_rx_command(p, data);
  8796. + break;
  8797. +
  8798. + default:
  8799. + ptl_err(p, "rtl: rx: unknown frame payload type"
  8800. + " (type: 0x%02x)\n", data->ptr[0]);
  8801. + break;
  8802. + }
  8803. +}
  8804. +
  8805. +
  8806. +static inline struct device *ssh_rtl_get_device(struct ssh_rtl *rtl)
  8807. +{
  8808. + return ssh_ptl_get_device(&rtl->ptl);
  8809. +}
  8810. +
  8811. +static inline bool ssh_rtl_tx_flush(struct ssh_rtl *rtl)
  8812. +{
  8813. + return flush_work(&rtl->tx.work);
  8814. +}
  8815. +
  8816. +static inline int ssh_rtl_tx_start(struct ssh_rtl *rtl)
  8817. +{
  8818. + int status;
  8819. + bool sched;
  8820. +
  8821. + status = ssh_ptl_tx_start(&rtl->ptl);
  8822. + if (status)
  8823. + return status;
  8824. +
  8825. + /*
  8826. + * If the packet layer has been shut down and restarted without shutting
  8827. + * down the request layer, there may still be requests queued and not
  8828. + * handled.
  8829. + */
  8830. + spin_lock(&rtl->queue.lock);
  8831. + sched = !list_empty(&rtl->queue.head);
  8832. + spin_unlock(&rtl->queue.lock);
  8833. +
  8834. + if (sched)
  8835. + ssh_rtl_tx_schedule(rtl);
  8836. +
  8837. + return 0;
  8838. +}
  8839. +
  8840. +static inline int ssh_rtl_rx_start(struct ssh_rtl *rtl)
  8841. +{
  8842. + return ssh_ptl_rx_start(&rtl->ptl);
  8843. +}
  8844. +
  8845. +static int ssh_rtl_init(struct ssh_rtl *rtl, struct serdev_device *serdev,
  8846. + struct ssh_rtl_ops *ops)
  8847. +{
  8848. + struct ssh_ptl_ops ptl_ops;
  8849. + int status;
  8850. +
  8851. + ptl_ops.data_received = ssh_rtl_rx_data;
  8852. +
  8853. + status = ssh_ptl_init(&rtl->ptl, serdev, &ptl_ops);
  8854. + if (status)
  8855. + return status;
  8856. +
  8857. + spin_lock_init(&rtl->queue.lock);
  8858. + INIT_LIST_HEAD(&rtl->queue.head);
  8859. +
  8860. + spin_lock_init(&rtl->pending.lock);
  8861. + INIT_LIST_HEAD(&rtl->pending.head);
  8862. + atomic_set_release(&rtl->pending.count, 0);
  8863. +
  8864. + INIT_WORK(&rtl->tx.work, ssh_rtl_tx_work_fn);
  8865. +
  8866. + rtl->rtx_timeout.timeout = SSH_RTL_REQUEST_TIMEOUT;
  8867. + rtl->rtx_timeout.expires = KTIME_MAX;
  8868. + INIT_DELAYED_WORK(&rtl->rtx_timeout.reaper, ssh_rtl_timeout_reap);
  8869. +
  8870. + rtl->ops = *ops;
  8871. +
  8872. + return 0;
  8873. +}
  8874. +
  8875. +static void ssh_rtl_destroy(struct ssh_rtl *rtl)
  8876. +{
  8877. + ssh_ptl_destroy(&rtl->ptl);
  8878. +}
  8879. +
  8880. +
  8881. +static void ssh_rtl_packet_release(struct ssh_packet *p)
  8882. +{
  8883. + struct ssh_request *rqst = to_ssh_request(p, packet);
  8884. + rqst->ops->release(rqst);
  8885. +}
  8886. +
  8887. +static const struct ssh_packet_ops ssh_rtl_packet_ops = {
  8888. + .complete = ssh_rtl_packet_callback,
  8889. + .release = ssh_rtl_packet_release,
  8890. +};
  8891. +
  8892. +static void ssh_request_init(struct ssh_request *rqst,
  8893. + enum ssam_request_flags flags,
  8894. + const struct ssh_request_ops *ops)
  8895. +{
  8896. + struct ssh_packet_args packet_args;
  8897. +
  8898. + packet_args.type = SSH_PACKET_TY_BLOCKING;
  8899. + if (!(flags & SSAM_REQUEST_UNSEQUENCED))
  8900. + packet_args.type |= SSH_PACKET_TY_SEQUENCED;
  8901. +
  8902. + packet_args.priority = SSH_PACKET_PRIORITY(DATA, 0);
  8903. + packet_args.ops = &ssh_rtl_packet_ops;
  8904. +
  8905. + ssh_packet_init(&rqst->packet, &packet_args);
  8906. +
  8907. + rqst->rtl = NULL;
  8908. + INIT_LIST_HEAD(&rqst->node);
  8909. +
  8910. + rqst->state = 0;
  8911. + if (flags & SSAM_REQUEST_HAS_RESPONSE)
  8912. + rqst->state |= BIT(SSH_REQUEST_TY_HAS_RESPONSE_BIT);
  8913. +
  8914. + rqst->timestamp = KTIME_MAX;
  8915. + rqst->ops = ops;
  8916. +}
  8917. +
  8918. +
  8919. +struct ssh_flush_request {
  8920. + struct ssh_request base;
  8921. + struct completion completion;
  8922. + int status;
  8923. +};
  8924. +
  8925. +static void ssh_rtl_flush_request_complete(struct ssh_request *r,
  8926. + const struct ssh_command *cmd,
  8927. + const struct sshp_span *data,
  8928. + int status)
  8929. +{
  8930. + struct ssh_flush_request *rqst;
  8931. +
  8932. + rqst = container_of(r, struct ssh_flush_request, base);
  8933. + rqst->status = status;
  8934. +}
  8935. +
  8936. +static void ssh_rtl_flush_request_release(struct ssh_request *r)
  8937. +{
  8938. + struct ssh_flush_request *rqst;
  8939. +
  8940. + rqst = container_of(r, struct ssh_flush_request, base);
  8941. + complete_all(&rqst->completion);
  8942. +}
  8943. +
  8944. +static const struct ssh_request_ops ssh_rtl_flush_request_ops = {
  8945. + .complete = ssh_rtl_flush_request_complete,
  8946. + .release = ssh_rtl_flush_request_release,
  8947. +};
  8948. +
  8949. +/**
  8950. + * ssh_rtl_flush - flush the request transmission layer
  8951. + * @rtl: request transmission layer
  8952. + * @timeout: timeout for the flush operation in jiffies
  8953. + *
  8954. + * Queue a special flush request and wait for its completion. This request
  8955. + * will be completed after all other currently queued and pending requests
  8956. + * have been completed. Instead of a normal data packet, this request submits
  8957. + * a special flush packet, meaning that upon completion, also the underlying
  8958. + * packet transmission layer has been flushed.
  8959. + *
  8960. + * Flushing the request layer gurarantees that all previously submitted
  8961. + * requests have been fully completed before this call returns. Additinally,
  8962. + * flushing blocks execution of all later submitted requests until the flush
  8963. + * has been completed.
  8964. + *
  8965. + * If the caller ensures that no new requests are submitted after a call to
  8966. + * this function, the request transmission layer is guaranteed to have no
  8967. + * remaining requests when this call returns. The same guarantee does not hold
  8968. + * for the packet layer, on which control packets may still be queued after
  8969. + * this call. See the documentation of ssh_ptl_flush for more details on
  8970. + * packet layer flushing.
  8971. + *
  8972. + * Return: Zero on success, -ETIMEDOUT if the flush timed out and has been
  8973. + * canceled as a result of the timeout, or -ESHUTDOWN if the packet and/or
  8974. + * request transmission layer has been shut down before this call. May also
  8975. + * return -EINTR if the underlying packet transmission has been interrupted.
  8976. + */
  8977. +static int ssh_rtl_flush(struct ssh_rtl *rtl, unsigned long timeout)
  8978. +{
  8979. + const unsigned init_flags = SSAM_REQUEST_UNSEQUENCED;
  8980. + struct ssh_flush_request rqst;
  8981. + int status;
  8982. +
  8983. + ssh_request_init(&rqst.base, init_flags, &ssh_rtl_flush_request_ops);
  8984. + rqst.base.packet.type |= SSH_PACKET_TY_FLUSH;
  8985. + rqst.base.packet.priority = SSH_PACKET_PRIORITY(FLUSH, 0);
  8986. + rqst.base.state |= BIT(SSH_REQUEST_TY_FLUSH_BIT);
  8987. +
  8988. + init_completion(&rqst.completion);
  8989. +
  8990. + status = ssh_rtl_submit(rtl, &rqst.base);
  8991. + if (status)
  8992. + return status;
  8993. +
  8994. + ssh_request_put(&rqst.base);
  8995. +
  8996. + if (wait_for_completion_timeout(&rqst.completion, timeout))
  8997. + return 0;
  8998. +
  8999. + ssh_rtl_cancel(&rqst.base, true);
  9000. + wait_for_completion(&rqst.completion);
  9001. +
  9002. + WARN_ON(rqst.status != 0 && rqst.status != -ECANCELED
  9003. + && rqst.status != -ESHUTDOWN && rqst.status != -EINTR);
  9004. +
  9005. + return rqst.status == -ECANCELED ? -ETIMEDOUT : status;
  9006. +}
  9007. +
  9008. +
  9009. +static void ssh_rtl_shutdown(struct ssh_rtl *rtl)
  9010. +{
  9011. + struct ssh_request *r, *n;
  9012. + LIST_HEAD(claimed);
  9013. + int pending;
  9014. +
  9015. + set_bit(SSH_RTL_SF_SHUTDOWN_BIT, &rtl->state);
  9016. + smp_mb__after_atomic();
  9017. +
  9018. + // remove requests from queue
  9019. + spin_lock(&rtl->queue.lock);
  9020. + list_for_each_entry_safe(r, n, &rtl->queue.head, node) {
  9021. + set_bit(SSH_REQUEST_SF_LOCKED_BIT, &r->state);
  9022. + smp_mb__before_atomic();
  9023. + clear_bit(SSH_REQUEST_SF_QUEUED_BIT, &r->state);
  9024. +
  9025. + list_del(&r->node);
  9026. + list_add_tail(&r->node, &claimed);
  9027. + }
  9028. + spin_unlock(&rtl->queue.lock);
  9029. +
  9030. + /*
  9031. + * We have now guaranteed that the queue is empty and no more new
  9032. + * requests can be submitted (i.e. it will stay empty). This means that
  9033. + * calling ssh_rtl_tx_schedule will not schedule tx.work any more. So we
  9034. + * can simply call cancel_work_sync on tx.work here and when that
  9035. + * returns, we've locked it down. This also means that after this call,
  9036. + * we don't submit any more packets to the underlying packet layer, so
  9037. + * we can also shut that down.
  9038. + */
  9039. +
  9040. + cancel_work_sync(&rtl->tx.work);
  9041. + ssh_ptl_shutdown(&rtl->ptl);
  9042. + cancel_delayed_work_sync(&rtl->rtx_timeout.reaper);
  9043. +
  9044. + /*
  9045. + * Shutting down the packet layer should also have caneled all requests.
  9046. + * Thus the pending set should be empty. Attempt to handle this
  9047. + * gracefully anyways, even though this should be dead code.
  9048. + */
  9049. +
  9050. + pending = atomic_read(&rtl->pending.count);
  9051. + WARN_ON(pending);
  9052. +
  9053. + if (pending) {
  9054. + spin_lock(&rtl->pending.lock);
  9055. + list_for_each_entry_safe(r, n, &rtl->pending.head, node) {
  9056. + set_bit(SSH_REQUEST_SF_LOCKED_BIT, &r->state);
  9057. + smp_mb__before_atomic();
  9058. + clear_bit(SSH_REQUEST_SF_PENDING_BIT, &r->state);
  9059. +
  9060. + list_del(&r->node);
  9061. + list_add_tail(&r->node, &claimed);
  9062. + }
  9063. + spin_unlock(&rtl->pending.lock);
  9064. + }
  9065. +
  9066. + // finally cancel and complete requests
  9067. + list_for_each_entry_safe(r, n, &claimed, node) {
  9068. + // test_and_set because we still might compete with cancellation
  9069. + if (!test_and_set_bit(SSH_REQUEST_SF_COMPLETED_BIT, &r->state))
  9070. + ssh_rtl_complete_with_status(r, -ESHUTDOWN);
  9071. +
  9072. + // drop the reference we've obtained by removing it from list
  9073. + list_del(&r->node);
  9074. + ssh_request_put(r);
  9075. + }
  9076. +}
  9077. +
  9078. +
  9079. +/* -- Event notifier/callbacks. --------------------------------------------- */
  9080. +/*
  9081. + * The notifier system is based on linux/notifier.h, specifically the SRCU
  9082. + * implementation. The difference to that is, that some bits of the notifier
  9083. + * call return value can be tracked accross multiple calls. This is done so that
  9084. + * handling of events can be tracked and a warning can be issued in case an
  9085. + * event goes unhandled. The idea of that waring is that it should help discover
  9086. + * and identify new/currently unimplemented features.
  9087. + */
  9088. +
  9089. +struct ssam_nf_head {
  9090. + struct srcu_struct srcu;
  9091. + struct ssam_notifier_block __rcu *head;
  9092. +};
  9093. +
  9094. +
  9095. +int ssam_nfblk_call_chain(struct ssam_nf_head *nh, struct ssam_event *event)
  9096. +{
  9097. + struct ssam_notifier_block *nb, *next_nb;
  9098. + int ret = 0, idx;
  9099. +
  9100. + idx = srcu_read_lock(&nh->srcu);
  9101. +
  9102. + nb = rcu_dereference_raw(nh->head);
  9103. + while (nb) {
  9104. + next_nb = rcu_dereference_raw(nb->next);
  9105. +
  9106. + ret = (ret & SSAM_NOTIF_STATE_MASK) | nb->fn(nb, event);
  9107. + if (ret & SSAM_NOTIF_STOP)
  9108. + break;
  9109. +
  9110. + nb = next_nb;
  9111. + }
  9112. +
  9113. + srcu_read_unlock(&nh->srcu, idx);
  9114. + return ret;
  9115. +}
  9116. +
  9117. +/*
  9118. + * Note: This function must be synchronized by the caller with respect to other
  9119. + * insert and/or remove calls.
  9120. + */
  9121. +int __ssam_nfblk_insert(struct ssam_nf_head *nh, struct ssam_notifier_block *nb)
  9122. +{
  9123. + struct ssam_notifier_block **link = &nh->head;
  9124. +
  9125. + while ((*link) != NULL) {
  9126. + if (unlikely((*link) == nb)) {
  9127. + WARN(1, "double register detected");
  9128. + return -EINVAL;
  9129. + }
  9130. +
  9131. + if (nb->priority > (*link)->priority)
  9132. + break;
  9133. +
  9134. + link = &((*link)->next);
  9135. + }
  9136. +
  9137. + nb->next = *link;
  9138. + rcu_assign_pointer(*link, nb);
  9139. +
  9140. + return 0;
  9141. +}
  9142. +
  9143. +/*
  9144. + * Note: This function must be synchronized by the caller with respect to other
  9145. + * insert and/or remove calls. On success, the caller _must_ ensure SRCU
  9146. + * synchronization by calling `synchronize_srcu(&nh->srcu)` after leaving the
  9147. + * critical section, to ensure that the removed notifier block is not in use any
  9148. + * more.
  9149. + */
  9150. +int __ssam_nfblk_remove(struct ssam_nf_head *nh, struct ssam_notifier_block *nb)
  9151. +{
  9152. + struct ssam_notifier_block **link = &nh->head;
  9153. +
  9154. + while ((*link) != NULL) {
  9155. + if ((*link) == nb) {
  9156. + rcu_assign_pointer(*link, nb->next);
  9157. + return 0;
  9158. + }
  9159. +
  9160. + link = &((*link)->next);
  9161. + }
  9162. +
  9163. + return -ENOENT;
  9164. +}
  9165. +
  9166. +static int ssam_nf_head_init(struct ssam_nf_head *nh)
  9167. +{
  9168. + int status;
  9169. +
  9170. + status = init_srcu_struct(&nh->srcu);
  9171. + if (status)
  9172. + return status;
  9173. +
  9174. + nh->head = NULL;
  9175. + return 0;
  9176. +}
  9177. +
  9178. +static void ssam_nf_head_destroy(struct ssam_nf_head *nh)
  9179. +{
  9180. + cleanup_srcu_struct(&nh->srcu);
  9181. +}
  9182. +
  9183. +
  9184. +/* -- Event/notification registry. ------------------------------------------ */
  9185. +
  9186. +struct ssam_nf_refcount_key {
  9187. + struct ssam_event_registry reg;
  9188. + struct ssam_event_id id;
  9189. +};
  9190. +
  9191. +struct ssam_nf_refcount_entry {
  9192. + struct rb_node node;
  9193. + struct ssam_nf_refcount_key key;
  9194. + int refcount;
  9195. +};
  9196. +
  9197. +struct ssam_nf {
  9198. + struct mutex lock;
  9199. + struct rb_root refcount;
  9200. + struct ssam_nf_head head[SURFACE_SAM_SSH_NUM_EVENTS];
  9201. +};
  9202. +
  9203. +
  9204. +static int ssam_nf_refcount_inc(struct ssam_nf *nf,
  9205. + struct ssam_event_registry reg,
  9206. + struct ssam_event_id id)
  9207. +{
  9208. + struct ssam_nf_refcount_entry *entry;
  9209. + struct ssam_nf_refcount_key key;
  9210. + struct rb_node **link = &nf->refcount.rb_node;
  9211. + struct rb_node *parent;
  9212. + int cmp;
  9213. +
  9214. + key.reg = reg;
  9215. + key.id = id;
  9216. +
  9217. + while (*link) {
  9218. + entry = rb_entry(*link, struct ssam_nf_refcount_entry, node);
  9219. + parent = *link;
  9220. +
  9221. + cmp = memcmp(&key, &entry->key, sizeof(key));
  9222. + if (cmp < 0) {
  9223. + link = &(*link)->rb_left;
  9224. + } else if (cmp > 0) {
  9225. + link = &(*link)->rb_right;
  9226. + } else if (entry->refcount < INT_MAX) {
  9227. + return ++entry->refcount;
  9228. + } else {
  9229. + return -ENOSPC;
  9230. + }
  9231. + }
  9232. +
  9233. + entry = kzalloc(sizeof(*entry), GFP_KERNEL);
  9234. + if (!entry)
  9235. + return -ENOMEM;
  9236. +
  9237. + entry->key = key;
  9238. + entry->refcount = 1;
  9239. +
  9240. + rb_link_node(&entry->node, parent, link);
  9241. + rb_insert_color(&entry->node, &nf->refcount);
  9242. +
  9243. + return entry->refcount;
  9244. +}
  9245. +
  9246. +static int ssam_nf_refcount_dec(struct ssam_nf *nf,
  9247. + struct ssam_event_registry reg,
  9248. + struct ssam_event_id id)
  9249. +{
  9250. + struct ssam_nf_refcount_entry *entry;
  9251. + struct ssam_nf_refcount_key key;
  9252. + struct rb_node *node = nf->refcount.rb_node;
  9253. + int cmp, rc;
  9254. +
  9255. + key.reg = reg;
  9256. + key.id = id;
  9257. +
  9258. + while (node) {
  9259. + entry = rb_entry(node, struct ssam_nf_refcount_entry, node);
  9260. +
  9261. + cmp = memcmp(&key, &entry->key, sizeof(key));
  9262. + if (cmp < 0) {
  9263. + node = node->rb_left;
  9264. + } else if (cmp > 0) {
  9265. + node = node->rb_right;
  9266. + } else {
  9267. + rc = --entry->refcount;
  9268. +
  9269. + if (rc == 0) {
  9270. + rb_erase(&entry->node, &nf->refcount);
  9271. + kfree(entry);
  9272. + }
  9273. +
  9274. + return rc;
  9275. + }
  9276. + }
  9277. +
  9278. + return -ENOENT;
  9279. +}
  9280. +
  9281. +static void ssam_nf_call(struct ssam_nf *nf, struct device *dev, u16 rqid,
  9282. + struct ssam_event *event)
  9283. +{
  9284. + struct ssam_nf_head *nf_head;
  9285. + int status, nf_ret;
  9286. +
  9287. + if (!ssh_rqid_is_event(rqid)) {
  9288. + dev_warn(dev, "event: unsupported rqid: 0x%04x\n", rqid);
  9289. + return;
  9290. + }
  9291. +
  9292. + nf_head = &nf->head[ssh_rqid_to_event(rqid)];
  9293. + nf_ret = ssam_nfblk_call_chain(nf_head, event);
  9294. + status = ssam_notifier_to_errno(nf_ret);
  9295. +
  9296. + if (status < 0) {
  9297. + dev_err(dev, "event: error handling event: %d "
  9298. + "(tc: 0x%02x, cid: 0x%02x, iid: 0x%02x, chn: 0x%02x)\n",
  9299. + status, event->target_category, event->command_id,
  9300. + event->instance_id, event->channel);
  9301. + }
  9302. +
  9303. + if (!(nf_ret & SSAM_NOTIF_HANDLED)) {
  9304. + dev_warn(dev, "event: unhandled event (rqid: 0x%02x, "
  9305. + "tc: 0x%02x, cid: 0x%02x, iid: 0x%02x, chn: 0x%02x)\n",
  9306. + rqid, event->target_category, event->command_id,
  9307. + event->instance_id, event->channel);
  9308. + }
  9309. +}
  9310. +
  9311. +static int ssam_nf_register(struct ssam_nf *nf, struct ssam_event_notifier *n)
  9312. +{
  9313. + u16 rqid = ssh_tc_to_rqid(n->event.id.target_category);
  9314. + struct ssam_nf_head *nf_head;
  9315. + int rc, status;
  9316. +
  9317. + if (!ssh_rqid_is_event(rqid))
  9318. + return -EINVAL;
  9319. +
  9320. + nf_head = &nf->head[ssh_rqid_to_event(rqid)];
  9321. +
  9322. + mutex_lock(&nf->lock);
  9323. +
  9324. + rc = ssam_nf_refcount_inc(nf, n->event.reg, n->event.id);
  9325. + if (rc < 0) {
  9326. + mutex_lock(&nf->lock);
  9327. + return rc;
  9328. + }
  9329. +
  9330. + status = __ssam_nfblk_insert(nf_head, &n->base);
  9331. + if (status)
  9332. + ssam_nf_refcount_dec(nf, n->event.reg, n->event.id);
  9333. +
  9334. + mutex_unlock(&nf->lock);
  9335. + return status;
  9336. +}
  9337. +
  9338. +static int ssam_nf_unregister(struct ssam_nf *nf, struct ssam_event_notifier *n)
  9339. +{
  9340. + u16 rqid = ssh_tc_to_rqid(n->event.id.target_category);
  9341. + struct ssam_nf_head *nf_head;
  9342. + int status;
  9343. +
  9344. + if (!ssh_rqid_is_event(rqid))
  9345. + return -EINVAL;
  9346. +
  9347. + nf_head = &nf->head[ssh_rqid_to_event(rqid)];
  9348. +
  9349. + mutex_lock(&nf->lock);
  9350. +
  9351. + status = __ssam_nfblk_remove(nf_head, &n->base);
  9352. + if (status) {
  9353. + mutex_unlock(&nf->lock);
  9354. + return status;
  9355. + }
  9356. +
  9357. + ssam_nf_refcount_dec(nf, n->event.reg, n->event.id);
  9358. +
  9359. + mutex_unlock(&nf->lock);
  9360. + synchronize_srcu(&nf_head->srcu);
  9361. +
  9362. + return 0;
  9363. +}
  9364. +
  9365. +static int ssam_nf_init(struct ssam_nf *nf)
  9366. +{
  9367. + int i, status;
  9368. +
  9369. + for (i = 0; i < SURFACE_SAM_SSH_NUM_EVENTS; i++) {
  9370. + status = ssam_nf_head_init(&nf->head[i]);
  9371. + if (status)
  9372. + break;
  9373. + }
  9374. +
  9375. + if (status) {
  9376. + for (i = i - 1; i >= 0; i--)
  9377. + ssam_nf_head_destroy(&nf->head[i]);
  9378. +
  9379. + return status;
  9380. + }
  9381. +
  9382. + mutex_init(&nf->lock);
  9383. + return 0;
  9384. +}
  9385. +
  9386. +static void ssam_nf_destroy(struct ssam_nf *nf)
  9387. +{
  9388. + int i;
  9389. +
  9390. + for (i = 0; i < SURFACE_SAM_SSH_NUM_EVENTS; i++)
  9391. + ssam_nf_head_destroy(&nf->head[i]);
  9392. +
  9393. + mutex_destroy(&nf->lock);
  9394. +}
  9395. +
  9396. +
  9397. +/* -- Event/async request completion system. -------------------------------- */
  9398. +
  9399. +#define SSAM_CPLT_WQ_NAME "ssam_cpltq"
  9400. +
  9401. +
  9402. +struct ssam_cplt;
  9403. +
  9404. +struct ssam_event_item {
  9405. + struct list_head node;
  9406. + u16 rqid;
  9407. + struct ssam_event event; // must be last
  9408. +};
  9409. +
  9410. +struct ssam_event_queue {
  9411. + struct ssam_cplt *cplt;
  9412. +
  9413. + spinlock_t lock;
  9414. + struct list_head head;
  9415. + struct work_struct work;
  9416. +};
  9417. +
  9418. +struct ssam_event_channel {
  9419. + struct ssam_event_queue queue[SURFACE_SAM_SSH_NUM_EVENTS];
  9420. +};
  9421. +
  9422. +struct ssam_cplt {
  9423. + struct device *dev;
  9424. + struct workqueue_struct *wq;
  9425. +
  9426. + struct {
  9427. + struct ssam_event_channel channel[SURFACE_SAM_SSH_NUM_CHANNELS];
  9428. + struct ssam_nf notif;
  9429. + } event;
  9430. +};
  9431. +
  9432. +
  9433. +static void ssam_event_queue_push(struct ssam_event_queue *q,
  9434. + struct ssam_event_item *item)
  9435. +{
  9436. + spin_lock(&q->lock);
  9437. + list_add_tail(&item->node, &q->head);
  9438. + spin_unlock(&q->lock);
  9439. +}
  9440. +
  9441. +static struct ssam_event_item *ssam_event_queue_pop(struct ssam_event_queue *q)
  9442. +{
  9443. + struct ssam_event_item *item;
  9444. +
  9445. + spin_lock(&q->lock);
  9446. + item = list_first_entry_or_null(&q->head, struct ssam_event_item, node);
  9447. + if (item)
  9448. + list_del(&item->node);
  9449. + spin_unlock(&q->lock);
  9450. +
  9451. + return item;
  9452. +}
  9453. +
  9454. +static bool ssam_event_queue_is_empty(struct ssam_event_queue *q)
  9455. +{
  9456. + bool empty;
  9457. +
  9458. + spin_lock(&q->lock);
  9459. + empty = list_empty(&q->head);
  9460. + spin_unlock(&q->lock);
  9461. +
  9462. + return empty;
  9463. +}
  9464. +
  9465. +static struct ssam_event_queue *ssam_cplt_get_event_queue(
  9466. + struct ssam_cplt *cplt, u8 channel, u16 rqid)
  9467. +{
  9468. + u16 event = ssh_rqid_to_event(rqid);
  9469. + u16 chidx = ssh_channel_to_index(channel);
  9470. +
  9471. + if (!ssh_rqid_is_event(rqid)) {
  9472. + dev_err(cplt->dev, "event: unsupported rqid: 0x%04x\n", rqid);
  9473. + return NULL;
  9474. + }
  9475. +
  9476. + if (!ssh_channel_is_valid(channel)) {
  9477. + dev_warn(cplt->dev, "event: unsupported channel: %u\n",
  9478. + channel);
  9479. + chidx = 0;
  9480. + }
  9481. +
  9482. + return &cplt->event.channel[chidx].queue[event];
  9483. +}
  9484. +
  9485. +static inline bool ssam_cplt_submit(struct ssam_cplt *cplt,
  9486. + struct work_struct *work)
  9487. +{
  9488. + return queue_work(cplt->wq, work);
  9489. +}
  9490. +
  9491. +static int ssam_cplt_submit_event(struct ssam_cplt *cplt,
  9492. + struct ssam_event_item *item)
  9493. +{
  9494. + struct ssam_event_queue *evq;
  9495. +
  9496. + evq = ssam_cplt_get_event_queue(cplt, item->event.channel, item->rqid);
  9497. + if (!evq)
  9498. + return -EINVAL;
  9499. +
  9500. + ssam_event_queue_push(evq, item);
  9501. + ssam_cplt_submit(cplt, &evq->work);
  9502. + return 0;
  9503. +}
  9504. +
  9505. +static void ssam_cplt_flush(struct ssam_cplt *cplt)
  9506. +{
  9507. + flush_workqueue(cplt->wq);
  9508. +}
  9509. +
  9510. +static void ssam_event_queue_work_fn(struct work_struct *work)
  9511. +{
  9512. + struct ssam_event_queue *queue;
  9513. + struct ssam_event_item *item;
  9514. + struct ssam_nf *nf;
  9515. + struct device *dev;
  9516. + int i;
  9517. +
  9518. + queue = container_of(work, struct ssam_event_queue, work);
  9519. + nf = &queue->cplt->event.notif;
  9520. + dev = queue->cplt->dev;
  9521. +
  9522. + for (i = 0; i < 10; i++) {
  9523. + item = ssam_event_queue_pop(queue);
  9524. + if (item == NULL)
  9525. + return;
  9526. +
  9527. + ssam_nf_call(nf, dev, item->rqid, &item->event);
  9528. + kfree(item);
  9529. + }
  9530. +
  9531. + if (!ssam_event_queue_is_empty(queue))
  9532. + ssam_cplt_submit(queue->cplt, &queue->work);
  9533. +}
  9534. +
  9535. +static void ssam_event_queue_init(struct ssam_cplt *cplt,
  9536. + struct ssam_event_queue *evq)
  9537. +{
  9538. + evq->cplt = cplt;
  9539. + spin_lock_init(&evq->lock);
  9540. + INIT_LIST_HEAD(&evq->head);
  9541. + INIT_WORK(&evq->work, ssam_event_queue_work_fn);
  9542. +}
  9543. +
  9544. +static int ssam_cplt_init(struct ssam_cplt *cplt, struct device *dev)
  9545. +{
  9546. + struct ssam_event_channel *channel;
  9547. + int status, c, i;
  9548. +
  9549. + cplt->dev = dev;
  9550. +
  9551. + cplt->wq = create_workqueue(SSAM_CPLT_WQ_NAME);
  9552. + if (!cplt->wq)
  9553. + return -ENOMEM;
  9554. +
  9555. + for (c = 0; c < ARRAY_SIZE(cplt->event.channel); c++) {
  9556. + channel = &cplt->event.channel[c];
  9557. +
  9558. + for (i = 0; i < ARRAY_SIZE(channel->queue); i++)
  9559. + ssam_event_queue_init(cplt, &channel->queue[i]);
  9560. + }
  9561. +
  9562. + status = ssam_nf_init(&cplt->event.notif);
  9563. + if (status)
  9564. + destroy_workqueue(cplt->wq);
  9565. +
  9566. + return status;
  9567. +}
  9568. +
  9569. +static void ssam_cplt_destroy(struct ssam_cplt *cplt)
  9570. +{
  9571. + destroy_workqueue(cplt->wq);
  9572. + ssam_nf_destroy(&cplt->event.notif);
  9573. +}
  9574. +
  9575. +
  9576. +/* -- Top-Level Request Interface ------------------------------------------- */
  9577. +
  9578. +struct ssam_response {
  9579. + int status;
  9580. + u16 capacity;
  9581. + u16 length;
  9582. + u8 *pointer;
  9583. +};
  9584. +
  9585. +struct ssam_request_sync {
  9586. + struct ssh_request base;
  9587. + struct completion comp;
  9588. + struct ssam_response resp;
  9589. +};
  9590. +
  9591. +
  9592. +static void ssam_request_sync_complete(struct ssh_request *rqst,
  9593. + const struct ssh_command *cmd,
  9594. + const struct sshp_span *data, int status)
  9595. +{
  9596. + struct ssam_request_sync *r;
  9597. + struct ssh_rtl *rtl = READ_ONCE(rqst->rtl);
  9598. +
  9599. + r = container_of(rqst, struct ssam_request_sync, base);
  9600. + r->resp.status = status;
  9601. + r->resp.length = 0;
  9602. +
  9603. + if (status) {
  9604. + rtl_dbg_cond(rtl, "rsp: request failed: %d\n", status);
  9605. + return;
  9606. + }
  9607. +
  9608. + if (!data) // handle requests without a response
  9609. + return;
  9610. +
  9611. + if (!r->resp.pointer && data->len) {
  9612. + rtl_warn(rtl, "rsp: no response buffer provided, dropping data\n");
  9613. + return;
  9614. + }
  9615. +
  9616. + if (data->len > r->resp.capacity) {
  9617. + rtl_err(rtl, "rsp: response buffer too small,"
  9618. + " capacity: %u bytes, got: %zu bytes\n",
  9619. + r->resp.capacity, data->len);
  9620. + r->resp.status = -ENOSPC;
  9621. + return;
  9622. + }
  9623. +
  9624. + r->resp.length = data->len;
  9625. + memcpy(r->resp.pointer, data->ptr, data->len);
  9626. +}
  9627. +
  9628. +static void ssam_request_sync_release(struct ssh_request *rqst)
  9629. +{
  9630. + complete_all(&container_of(rqst, struct ssam_request_sync, base)->comp);
  9631. +}
  9632. +
  9633. +static const struct ssh_request_ops ssam_request_sync_ops = {
  9634. + .release = ssam_request_sync_release,
  9635. + .complete = ssam_request_sync_complete,
  9636. +};
  9637. +
  9638. +static void ssam_request_sync_wait_complete(struct ssam_request_sync *rqst)
  9639. +{
  9640. + wait_for_completion(&rqst->comp);
  9641. +}
  9642. +
  9643. +
  9644. +/* -- TODO ------------------------------------------------------------------ */
  9645. +
  9646. +enum ssh_ec_state {
  9647. + SSH_EC_UNINITIALIZED,
  9648. + SSH_EC_INITIALIZED,
  9649. + SSH_EC_SUSPENDED,
  9650. +};
  9651. +
  9652. +struct sam_ssh_ec {
  9653. + struct serdev_device *serdev;
  9654. +
  9655. + struct ssh_rtl rtl;
  9656. + struct ssam_cplt cplt;
  9657. +
  9658. + struct {
  9659. + struct ssh_seq_counter seq;
  9660. + struct ssh_rqid_counter rqid;
  9661. + } counter;
  9662. +
  9663. + enum ssh_ec_state state;
  9664. +
  9665. + int irq;
  9666. + bool irq_wakeup_enabled;
  9667. +};
  9668. +
  9669. +static struct sam_ssh_ec ssh_ec = {
  9670. + .state = SSH_EC_UNINITIALIZED,
  9671. + .serdev = NULL,
  9672. +};
  9673. +
  9674. +
  9675. +/* -- TODO ------------------------------------------------------------------ */
  9676. +
  9677. +#define ssh_dbg(ec, fmt, ...) dev_dbg(&(ec)->serdev->dev, fmt, ##__VA_ARGS__)
  9678. +#define ssh_warn(ec, fmt, ...) dev_warn(&(ec)->serdev->dev, fmt, ##__VA_ARGS__)
  9679. +#define ssh_err(ec, fmt, ...) dev_err(&(ec)->serdev->dev, fmt, ##__VA_ARGS__)
  9680. +
  9681. +
  9682. +static inline struct sam_ssh_ec *surface_sam_ssh_acquire(void)
  9683. +{
  9684. + return &ssh_ec;
  9685. +}
  9686. +
  9687. +static inline struct sam_ssh_ec *surface_sam_ssh_acquire_init(void)
  9688. +{
  9689. + struct sam_ssh_ec *ec = surface_sam_ssh_acquire();
  9690. +
  9691. + if (smp_load_acquire(&ec->state) == SSH_EC_UNINITIALIZED)
  9692. + return NULL;
  9693. +
  9694. + return ec;
  9695. +}
  9696. +
  9697. +int surface_sam_ssh_consumer_register(struct device *consumer)
  9698. +{
  9699. + u32 flags = DL_FLAG_PM_RUNTIME | DL_FLAG_AUTOREMOVE_CONSUMER;
  9700. + struct sam_ssh_ec *ec;
  9701. + struct device_link *link;
  9702. +
  9703. + ec = surface_sam_ssh_acquire_init();
  9704. + if (!ec)
  9705. + return -ENXIO;
  9706. +
  9707. + link = device_link_add(consumer, &ec->serdev->dev, flags);
  9708. + if (!link)
  9709. + return -EFAULT;
  9710. +
  9711. + return 0;
  9712. +}
  9713. +EXPORT_SYMBOL_GPL(surface_sam_ssh_consumer_register);
  9714. +
  9715. +
  9716. +static int __surface_sam_ssh_rqst(struct sam_ssh_ec *ec,
  9717. + const struct surface_sam_ssh_rqst *rqst,
  9718. + struct surface_sam_ssh_buf *result);
  9719. +
  9720. +static int surface_sam_ssh_event_enable(struct sam_ssh_ec *ec,
  9721. + struct ssam_event_registry reg,
  9722. + struct ssam_event_id id,
  9723. + u8 flags)
  9724. +{
  9725. + struct ssh_notification_params params;
  9726. + struct surface_sam_ssh_rqst rqst;
  9727. + struct surface_sam_ssh_buf result;
  9728. +
  9729. + u16 rqid = ssh_tc_to_rqid(id.target_category);
  9730. + u8 buf[1] = { 0x00 };
  9731. + int status;
  9732. +
  9733. + // only allow RQIDs that lie within event spectrum
  9734. + if (!ssh_rqid_is_event(rqid))
  9735. + return -EINVAL;
  9736. +
  9737. + params.target_category = id.target_category;
  9738. + params.instance_id = id.instance;
  9739. + params.flags = flags;
  9740. + put_unaligned_le16(rqid, &params.request_id);
  9741. +
  9742. + rqst.tc = reg.target_category;
  9743. + rqst.cid = reg.cid_enable;
  9744. + rqst.iid = 0x00;
  9745. + rqst.chn = reg.channel;
  9746. + rqst.snc = 0x01;
  9747. + rqst.cdl = sizeof(params);
  9748. + rqst.pld = (u8 *)&params;
  9749. +
  9750. + result.cap = ARRAY_SIZE(buf);
  9751. + result.len = 0;
  9752. + result.data = buf;
  9753. +
  9754. + status = __surface_sam_ssh_rqst(ec, &rqst, &result);
  9755. +
  9756. + if (status) {
  9757. + dev_err(&ec->serdev->dev, "failed to enable event source"
  9758. + " (tc: 0x%02x, rqid: 0x%04x)\n",
  9759. + id.target_category, rqid);
  9760. + }
  9761. +
  9762. + if (buf[0] != 0x00) {
  9763. + pr_warn(SSH_RQST_TAG_FULL
  9764. + "unexpected result while enabling event source: "
  9765. + "0x%02x\n", buf[0]);
  9766. + }
  9767. +
  9768. + return status;
  9769. +
  9770. +}
  9771. +
  9772. +static int surface_sam_ssh_event_disable(struct sam_ssh_ec *ec,
  9773. + struct ssam_event_registry reg,
  9774. + struct ssam_event_id id,
  9775. + u8 flags)
  9776. +{
  9777. + struct ssh_notification_params params;
  9778. + struct surface_sam_ssh_rqst rqst;
  9779. + struct surface_sam_ssh_buf result;
  9780. +
  9781. + u16 rqid = ssh_tc_to_rqid(id.target_category);
  9782. + u8 buf[1] = { 0x00 };
  9783. + int status;
  9784. +
  9785. + // only allow RQIDs that lie within event spectrum
  9786. + if (!ssh_rqid_is_event(rqid))
  9787. + return -EINVAL;
  9788. +
  9789. + params.target_category = id.target_category;
  9790. + params.instance_id = id.instance;
  9791. + params.flags = flags;
  9792. + put_unaligned_le16(rqid, &params.request_id);
  9793. +
  9794. + rqst.tc = reg.target_category;
  9795. + rqst.cid = reg.cid_disable;
  9796. + rqst.iid = 0x00;
  9797. + rqst.chn = reg.channel;
  9798. + rqst.snc = 0x01;
  9799. + rqst.cdl = sizeof(params);
  9800. + rqst.pld = (u8 *)&params;
  9801. +
  9802. + result.cap = ARRAY_SIZE(buf);
  9803. + result.len = 0;
  9804. + result.data = buf;
  9805. +
  9806. + status = __surface_sam_ssh_rqst(ec, &rqst, &result);
  9807. +
  9808. + if (status) {
  9809. + dev_err(&ec->serdev->dev, "failed to disable event source"
  9810. + " (tc: 0x%02x, rqid: 0x%04x)\n",
  9811. + id.target_category, rqid);
  9812. + }
  9813. +
  9814. + if (buf[0] != 0x00) {
  9815. + dev_warn(&ec->serdev->dev,
  9816. + "unexpected result while disabling event source: "
  9817. + "0x%02x\n", buf[0]);
  9818. + }
  9819. +
  9820. + return status;
  9821. +}
  9822. +
  9823. +
  9824. +int surface_sam_ssh_notifier_register(struct ssam_event_notifier *n)
  9825. +{
  9826. + struct ssam_nf_head *nf_head;
  9827. + struct sam_ssh_ec *ec;
  9828. + struct ssam_nf *nf;
  9829. + u16 event = ssh_tc_to_event(n->event.id.target_category);
  9830. + u16 rqid = ssh_event_to_rqid(event);
  9831. + int rc, status;
  9832. +
  9833. + if (!ssh_rqid_is_event(rqid))
  9834. + return -EINVAL;
  9835. +
  9836. + ec = surface_sam_ssh_acquire_init();
  9837. + if (!ec)
  9838. + return -ENXIO;
  9839. +
  9840. + nf = &ec->cplt.event.notif;
  9841. + nf_head = &nf->head[event];
  9842. +
  9843. + mutex_lock(&nf->lock);
  9844. +
  9845. + rc = ssam_nf_refcount_inc(nf, n->event.reg, n->event.id);
  9846. + if (rc < 0) {
  9847. + mutex_unlock(&nf->lock);
  9848. + return rc;
  9849. + }
  9850. +
  9851. + ssh_dbg(ec, "enabling event (tc: 0x%02x, rc: %d)\n", rqid, rc);
  9852. +
  9853. + status = __ssam_nfblk_insert(nf_head, &n->base);
  9854. + if (status) {
  9855. + ssam_nf_refcount_dec(nf, n->event.reg, n->event.id);
  9856. + mutex_unlock(&nf->lock);
  9857. + return status;
  9858. + }
  9859. +
  9860. + if (rc == 1) {
  9861. + status = surface_sam_ssh_event_enable(ec, n->event.reg, n->event.id, n->event.flags);
  9862. + if (status) {
  9863. + __ssam_nfblk_remove(nf_head, &n->base);
  9864. + ssam_nf_refcount_dec(nf, n->event.reg, n->event.id);
  9865. + mutex_unlock(&nf->lock);
  9866. + return status;
  9867. + }
  9868. + }
  9869. +
  9870. + mutex_unlock(&nf->lock);
  9871. + return 0;
  9872. +}
  9873. +EXPORT_SYMBOL_GPL(surface_sam_ssh_notifier_register);
  9874. +
  9875. +int surface_sam_ssh_notifier_unregister(struct ssam_event_notifier *n)
  9876. +{
  9877. + struct ssam_nf_head *nf_head;
  9878. + struct sam_ssh_ec *ec;
  9879. + struct ssam_nf *nf;
  9880. + u16 event = ssh_tc_to_event(n->event.id.target_category);
  9881. + u16 rqid = ssh_event_to_rqid(event);
  9882. + int rc, status = 0;
  9883. +
  9884. + if (!ssh_rqid_is_event(rqid))
  9885. + return -EINVAL;
  9886. +
  9887. + ec = surface_sam_ssh_acquire_init();
  9888. + if (!ec)
  9889. + return -ENXIO;
  9890. +
  9891. + nf = &ec->cplt.event.notif;
  9892. + nf_head = &nf->head[event];
  9893. +
  9894. + mutex_lock(&nf->lock);
  9895. +
  9896. + rc = ssam_nf_refcount_dec(nf, n->event.reg, n->event.id);
  9897. + if (rc < 0) {
  9898. + mutex_unlock(&nf->lock);
  9899. + return rc;
  9900. + }
  9901. +
  9902. + ssh_dbg(ec, "disabling event (tc: 0x%02x, rc: %d)\n", rqid, rc);
  9903. +
  9904. + if (rc == 0)
  9905. + status = surface_sam_ssh_event_disable(ec, n->event.reg, n->event.id, n->event.flags);
  9906. +
  9907. + __ssam_nfblk_remove(nf_head, &n->base);
  9908. + mutex_unlock(&nf->lock);
  9909. + synchronize_srcu(&nf_head->srcu);
  9910. +
  9911. + return status;
  9912. +}
  9913. +EXPORT_SYMBOL_GPL(surface_sam_ssh_notifier_unregister);
  9914. +
  9915. +
  9916. +static int __surface_sam_ssh_rqst(struct sam_ssh_ec *ec,
  9917. + const struct surface_sam_ssh_rqst *rqst,
  9918. + struct surface_sam_ssh_buf *result)
  9919. +{
  9920. + struct ssam_request_sync actual;
  9921. + struct msgbuf msgb;
  9922. + size_t msglen = SSH_COMMAND_MESSAGE_LENGTH(rqst->cdl);
  9923. + unsigned flags = 0;
  9924. + u16 rqid;
  9925. + u8 seq;
  9926. + int status;
  9927. +
  9928. + // prevent overflow
  9929. + if (rqst->cdl > SSH_COMMAND_MAX_PAYLOAD_SIZE) {
  9930. + ssh_err(ec, SSH_RQST_TAG "request payload too large\n");
  9931. + return -EINVAL;
  9932. + }
  9933. +
  9934. + if (result && result->data && rqst->snc)
  9935. + flags |= SSAM_REQUEST_HAS_RESPONSE;
  9936. +
  9937. + ssh_request_init(&actual.base, flags, &ssam_request_sync_ops);
  9938. + init_completion(&actual.comp);
  9939. +
  9940. + actual.resp.pointer = NULL;
  9941. + actual.resp.capacity = 0;
  9942. + actual.resp.length = 0;
  9943. + actual.resp.status = 0;
  9944. +
  9945. + if (result) {
  9946. + actual.resp.pointer = result->data;
  9947. + actual.resp.capacity = result->cap;
  9948. + }
  9949. +
  9950. + // alloc and create message
  9951. + status = msgb_alloc(&msgb, msglen, GFP_KERNEL);
  9952. + if (status)
  9953. + return status;
  9954. +
  9955. + seq = ssh_seq_next(&ec->counter.seq);
  9956. + rqid = ssh_rqid_next(&ec->counter.rqid);
  9957. + msgb_push_cmd(&msgb, seq, rqst, rqid);
  9958. +
  9959. + actual.base.packet.data = msgb.buffer;
  9960. + actual.base.packet.data_length = msgb.ptr - msgb.buffer;
  9961. +
  9962. + status = ssh_rtl_submit(&ec->rtl, &actual.base);
  9963. + if (status) {
  9964. + msgb_free(&msgb);
  9965. + return status;
  9966. + }
  9967. +
  9968. + ssh_request_put(&actual.base);
  9969. + ssam_request_sync_wait_complete(&actual);
  9970. + msgb_free(&msgb);
  9971. +
  9972. + if (result)
  9973. + result->len = actual.resp.length;
  9974. +
  9975. + return actual.resp.status;
  9976. +}
  9977. +
  9978. +int surface_sam_ssh_rqst(const struct surface_sam_ssh_rqst *rqst, struct surface_sam_ssh_buf *result)
  9979. +{
  9980. + struct sam_ssh_ec *ec;
  9981. +
  9982. + ec = surface_sam_ssh_acquire_init();
  9983. + if (!ec) {
  9984. + pr_warn(SSH_RQST_TAG_FULL "embedded controller is uninitialized\n");
  9985. + return -ENXIO;
  9986. + }
  9987. +
  9988. + if (smp_load_acquire(&ec->state) == SSH_EC_SUSPENDED) {
  9989. + ssh_warn(ec, SSH_RQST_TAG "embedded controller is suspended\n");
  9990. + return -EPERM;
  9991. + }
  9992. +
  9993. + return __surface_sam_ssh_rqst(ec, rqst, result);
  9994. +}
  9995. +EXPORT_SYMBOL_GPL(surface_sam_ssh_rqst);
  9996. +
  9997. +
  9998. +/**
  9999. + * surface_sam_ssh_ec_resume - Resume the EC if it is in a suspended mode.
  10000. + * @ec: the EC to resume
  10001. + *
  10002. + * Moves the EC from a suspended state to a normal state. See the
  10003. + * `surface_sam_ssh_ec_suspend` function what the specific differences of
  10004. + * these states are. Multiple repeated calls to this function seem to be
  10005. + * handled fine by the EC, after the first call, the state will remain
  10006. + * "normal".
  10007. + *
  10008. + * Must be called with the EC initialized and its lock held.
  10009. + */
  10010. +static int surface_sam_ssh_ec_resume(struct sam_ssh_ec *ec)
  10011. +{
  10012. + u8 buf[1] = { 0x00 };
  10013. + int status;
  10014. +
  10015. + struct surface_sam_ssh_rqst rqst = {
  10016. + .tc = 0x01,
  10017. + .cid = 0x16,
  10018. + .iid = 0x00,
  10019. + .chn = 0x01,
  10020. + .snc = 0x01,
  10021. + .cdl = 0x00,
  10022. + .pld = NULL,
  10023. + };
  10024. +
  10025. + struct surface_sam_ssh_buf result = {
  10026. + result.cap = ARRAY_SIZE(buf),
  10027. + result.len = 0,
  10028. + result.data = buf,
  10029. + };
  10030. +
  10031. + ssh_dbg(ec, "pm: resuming system aggregator module\n");
  10032. + status = __surface_sam_ssh_rqst(ec, &rqst, &result);
  10033. + if (status)
  10034. + return status;
  10035. +
  10036. + /*
  10037. + * The purpose of the return value of this request is unknown. Based on
  10038. + * logging and experience, we expect it to be zero. No other value has
  10039. + * been observed so far.
  10040. + */
  10041. + if (buf[0] != 0x00) {
  10042. + ssh_warn(ec, "unexpected result while trying to resume EC: "
  10043. + "0x%02x\n", buf[0]);
  10044. + }
  10045. +
  10046. + return 0;
  10047. +}
  10048. +
  10049. +/**
  10050. + * surface_sam_ssh_ec_suspend - Put the EC in a suspended mode:
  10051. + * @ec: the EC to suspend
  10052. + *
  10053. + * Tells the EC to enter a suspended mode. In this mode, events are quiesced
  10054. + * and the wake IRQ is armed (note that the wake IRQ does not fire if the EC
  10055. + * has not been suspended via this request). On some devices, the keyboard
  10056. + * backlight is turned off. Apart from this, the EC seems to continue to work
  10057. + * as normal, meaning requests sent to it are acknowledged and seem to be
  10058. + * correctly handled, including potential responses. Multiple repeated calls
  10059. + * to this function seem to be handled fine by the EC, after the first call,
  10060. + * the state will remain "suspended".
  10061. + *
  10062. + * Must be called with the EC initialized and its lock held.
  10063. + */
  10064. +static int surface_sam_ssh_ec_suspend(struct sam_ssh_ec *ec)
  10065. +{
  10066. + u8 buf[1] = { 0x00 };
  10067. + int status;
  10068. +
  10069. + struct surface_sam_ssh_rqst rqst = {
  10070. + .tc = 0x01,
  10071. + .cid = 0x15,
  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 = ARRAY_SIZE(buf),
  10081. + result.len = 0,
  10082. + result.data = buf,
  10083. + };
  10084. +
  10085. + ssh_dbg(ec, "pm: suspending system aggregator module\n");
  10086. + status = __surface_sam_ssh_rqst(ec, &rqst, &result);
  10087. + if (status)
  10088. + return status;
  10089. +
  10090. + /*
  10091. + * The purpose of the return value of this request is unknown. Based on
  10092. + * logging and experience, we expect it to be zero. No other value has
  10093. + * been observed so far.
  10094. + */
  10095. + if (buf[0] != 0x00) {
  10096. + ssh_warn(ec, "unexpected result while trying to suspend EC: "
  10097. + "0x%02x\n", buf[0]);
  10098. + }
  10099. +
  10100. + return 0;
  10101. +}
  10102. +
  10103. +
  10104. +static int surface_sam_ssh_get_controller_version(struct sam_ssh_ec *ec, u32 *version)
  10105. +{
  10106. + struct surface_sam_ssh_rqst rqst = {
  10107. + .tc = 0x01,
  10108. + .cid = 0x13,
  10109. + .iid = 0x00,
  10110. + .chn = 0x01,
  10111. + .snc = 0x01,
  10112. + .cdl = 0x00,
  10113. + .pld = NULL,
  10114. + };
  10115. +
  10116. + struct surface_sam_ssh_buf result = {
  10117. + result.cap = sizeof(*version),
  10118. + result.len = 0,
  10119. + result.data = (u8 *)version,
  10120. + };
  10121. +
  10122. + *version = 0;
  10123. + return __surface_sam_ssh_rqst(ec, &rqst, &result);
  10124. +}
  10125. +
  10126. +static int surface_sam_ssh_log_controller_version(struct sam_ssh_ec *ec)
  10127. +{
  10128. + u32 version, a, b, c;
  10129. + int status;
  10130. +
  10131. + status = surface_sam_ssh_get_controller_version(ec, &version);
  10132. + if (status)
  10133. + return status;
  10134. +
  10135. + a = (version >> 24) & 0xff;
  10136. + b = le16_to_cpu((version >> 8) & 0xffff);
  10137. + c = version & 0xff;
  10138. +
  10139. + dev_info(&ec->serdev->dev, "SAM controller version: %u.%u.%u\n",
  10140. + a, b, c);
  10141. + return 0;
  10142. +}
  10143. +
  10144. +
  10145. +static const struct acpi_gpio_params gpio_ssh_wakeup_int = { 0, 0, false };
  10146. +static const struct acpi_gpio_params gpio_ssh_wakeup = { 1, 0, false };
  10147. +
  10148. +static const struct acpi_gpio_mapping ssh_acpi_gpios[] = {
  10149. + { "ssh_wakeup-int-gpio", &gpio_ssh_wakeup_int, 1 },
  10150. + { "ssh_wakeup-gpio", &gpio_ssh_wakeup, 1 },
  10151. + { },
  10152. +};
  10153. +
  10154. +static irqreturn_t ssh_wake_irq_handler(int irq, void *dev_id)
  10155. +{
  10156. + struct serdev_device *serdev = dev_id;
  10157. +
  10158. + dev_dbg(&serdev->dev, "pm: wake irq triggered\n");
  10159. +
  10160. + // TODO: Send GPIO callback command repeatedly to EC until callback
  10161. + // returns 0x00. Return flag of callback is "has more events".
  10162. + // Each time the command is sent, one event is "released". Once
  10163. + // all events have been released (return = 0x00), the GPIO is
  10164. + // re-armed.
  10165. +
  10166. + return IRQ_HANDLED;
  10167. +}
  10168. +
  10169. +static int ssh_setup_irq(struct serdev_device *serdev)
  10170. +{
  10171. + const int irqf = IRQF_SHARED | IRQF_ONESHOT | IRQF_TRIGGER_RISING;
  10172. + struct gpio_desc *gpiod;
  10173. + int irq;
  10174. + int status;
  10175. +
  10176. + gpiod = gpiod_get(&serdev->dev, "ssh_wakeup-int", GPIOD_ASIS);
  10177. + if (IS_ERR(gpiod))
  10178. + return PTR_ERR(gpiod);
  10179. +
  10180. + irq = gpiod_to_irq(gpiod);
  10181. + gpiod_put(gpiod);
  10182. +
  10183. + if (irq < 0)
  10184. + return irq;
  10185. +
  10186. + status = request_threaded_irq(irq, NULL, ssh_wake_irq_handler,
  10187. + irqf, "surface_sam_sh_wakeup", serdev);
  10188. + if (status)
  10189. + return status;
  10190. +
  10191. + return irq;
  10192. +}
  10193. +
  10194. +
  10195. +static acpi_status ssh_setup_from_resource(struct acpi_resource *rsc, void *ctx)
  10196. +{
  10197. + struct serdev_device *serdev = ctx;
  10198. + struct acpi_resource_common_serialbus *serial;
  10199. + struct acpi_resource_uart_serialbus *uart;
  10200. + bool flow_control;
  10201. + int status = 0;
  10202. +
  10203. + if (rsc->type != ACPI_RESOURCE_TYPE_SERIAL_BUS)
  10204. + return AE_OK;
  10205. +
  10206. + serial = &rsc->data.common_serial_bus;
  10207. + if (serial->type != ACPI_RESOURCE_SERIAL_TYPE_UART)
  10208. + return AE_OK;
  10209. +
  10210. + uart = &rsc->data.uart_serial_bus;
  10211. +
  10212. + // set up serdev device
  10213. + serdev_device_set_baudrate(serdev, uart->default_baud_rate);
  10214. +
  10215. + // serdev currently only supports RTSCTS flow control
  10216. + if (uart->flow_control & SSH_SUPPORTED_FLOW_CONTROL_MASK) {
  10217. + dev_warn(&serdev->dev, "setup: unsupported flow control"
  10218. + " (value: 0x%02x)\n", uart->flow_control);
  10219. + }
  10220. +
  10221. + // set RTSCTS flow control
  10222. + flow_control = uart->flow_control & ACPI_UART_FLOW_CONTROL_HW;
  10223. + serdev_device_set_flow_control(serdev, flow_control);
  10224. +
  10225. + // serdev currently only supports EVEN/ODD parity
  10226. + switch (uart->parity) {
  10227. + case ACPI_UART_PARITY_NONE:
  10228. + status = serdev_device_set_parity(serdev, SERDEV_PARITY_NONE);
  10229. + break;
  10230. + case ACPI_UART_PARITY_EVEN:
  10231. + status = serdev_device_set_parity(serdev, SERDEV_PARITY_EVEN);
  10232. + break;
  10233. + case ACPI_UART_PARITY_ODD:
  10234. + status = serdev_device_set_parity(serdev, SERDEV_PARITY_ODD);
  10235. + break;
  10236. + default:
  10237. + dev_warn(&serdev->dev, "setup: unsupported parity"
  10238. + " (value: 0x%02x)\n", uart->parity);
  10239. + break;
  10240. + }
  10241. +
  10242. + if (status) {
  10243. + dev_err(&serdev->dev, "setup: failed to set parity"
  10244. + " (value: 0x%02x)\n", uart->parity);
  10245. + return status;
  10246. + }
  10247. +
  10248. + return AE_CTRL_TERMINATE; // we've found the resource and are done
  10249. +}
  10250. +
  10251. +
  10252. +static int surface_sam_ssh_suspend(struct device *dev)
  10253. +{
  10254. + struct sam_ssh_ec *ec;
  10255. + int status;
  10256. +
  10257. + dev_dbg(dev, "pm: suspending\n");
  10258. +
  10259. + ec = surface_sam_ssh_acquire_init();
  10260. + if (ec) {
  10261. + status = surface_sam_ssh_ec_suspend(ec);
  10262. + if (status)
  10263. + return status;
  10264. +
  10265. + if (device_may_wakeup(dev)) {
  10266. + status = enable_irq_wake(ec->irq);
  10267. + if (status)
  10268. + return status;
  10269. +
  10270. + ec->irq_wakeup_enabled = true;
  10271. + } else {
  10272. + ec->irq_wakeup_enabled = false;
  10273. + }
  10274. +
  10275. + smp_store_release(&ec->state, SSH_EC_SUSPENDED);
  10276. + }
  10277. +
  10278. + return 0;
  10279. +}
  10280. +
  10281. +static int surface_sam_ssh_resume(struct device *dev)
  10282. +{
  10283. + struct sam_ssh_ec *ec;
  10284. + int status;
  10285. +
  10286. + dev_dbg(dev, "pm: resuming\n");
  10287. +
  10288. + ec = surface_sam_ssh_acquire_init();
  10289. + if (ec) {
  10290. + smp_store_release(&ec->state, SSH_EC_INITIALIZED);
  10291. +
  10292. + if (ec->irq_wakeup_enabled) {
  10293. + status = disable_irq_wake(ec->irq);
  10294. + if (status)
  10295. + return status;
  10296. +
  10297. + ec->irq_wakeup_enabled = false;
  10298. + }
  10299. +
  10300. + status = surface_sam_ssh_ec_resume(ec);
  10301. + if (status)
  10302. + return status;
  10303. + }
  10304. +
  10305. + return 0;
  10306. +}
  10307. +
  10308. +static SIMPLE_DEV_PM_OPS(surface_sam_ssh_pm_ops, surface_sam_ssh_suspend,
  10309. + surface_sam_ssh_resume);
  10310. +
  10311. +
  10312. +static void ssam_handle_event(struct ssh_rtl *rtl,
  10313. + const struct ssh_command *cmd,
  10314. + const struct sshp_span *data)
  10315. +{
  10316. + struct sam_ssh_ec *ec = container_of(rtl, struct sam_ssh_ec, rtl);
  10317. + struct ssam_event_item *item;
  10318. +
  10319. + item = kzalloc(sizeof(struct ssam_event_item) + data->len, GFP_KERNEL);
  10320. + if (!item)
  10321. + return;
  10322. +
  10323. + item->rqid = get_unaligned_le16(&cmd->rqid);
  10324. + item->event.target_category = cmd->tc;
  10325. + item->event.command_id = cmd->cid;
  10326. + item->event.instance_id = cmd->iid;
  10327. + item->event.channel = cmd->chn_in;
  10328. + item->event.length = data->len;
  10329. + memcpy(&item->event.data[0], data->ptr, data->len);
  10330. +
  10331. + ssam_cplt_submit_event(&ec->cplt, item);
  10332. +}
  10333. +
  10334. +static struct ssh_rtl_ops ssam_rtl_ops = {
  10335. + .handle_event = ssam_handle_event,
  10336. +};
  10337. +
  10338. +
  10339. +static int ssam_receive_buf(struct serdev_device *dev, const unsigned char *buf, size_t n)
  10340. +{
  10341. + struct sam_ssh_ec *ec = serdev_device_get_drvdata(dev);
  10342. + return ssh_ptl_rx_rcvbuf(&ec->rtl.ptl, buf, n);
  10343. +}
  10344. +
  10345. +static void ssam_write_wakeup(struct serdev_device *dev)
  10346. +{
  10347. + struct sam_ssh_ec *ec = serdev_device_get_drvdata(dev);
  10348. + ssh_ptl_tx_wakeup(&ec->rtl.ptl, true);
  10349. +}
  10350. +
  10351. +struct serdev_device_ops ssam_serdev_ops = {
  10352. + .receive_buf = ssam_receive_buf,
  10353. + .write_wakeup = ssam_write_wakeup,
  10354. +};
  10355. +
  10356. +
  10357. +#ifdef CONFIG_SURFACE_SAM_SSH_DEBUG_DEVICE
  10358. +
  10359. +static char sam_ssh_debug_rqst_buf_sysfs[256] = { 0 };
  10360. +static char sam_ssh_debug_rqst_buf_pld[255] = { 0 };
  10361. +static char sam_ssh_debug_rqst_buf_res[255] = { 0 };
  10362. +
  10363. +struct sysfs_rqst {
  10364. + u8 tc;
  10365. + u8 cid;
  10366. + u8 iid;
  10367. + u8 chn;
  10368. + u8 snc;
  10369. + u8 cdl;
  10370. + u8 pld[0];
  10371. +} __packed;
  10372. +
  10373. +static ssize_t rqst_read(struct file *f, struct kobject *kobj, struct bin_attribute *attr,
  10374. + char *buf, loff_t offs, size_t count)
  10375. +{
  10376. + if (offs < 0 || count + offs > ARRAY_SIZE(sam_ssh_debug_rqst_buf_sysfs))
  10377. + return -EINVAL;
  10378. +
  10379. + memcpy(buf, sam_ssh_debug_rqst_buf_sysfs + offs, count);
  10380. + return count;
  10381. +}
  10382. +
  10383. +static ssize_t rqst_write(struct file *f, struct kobject *kobj, struct bin_attribute *attr,
  10384. + char *buf, loff_t offs, size_t count)
  10385. +{
  10386. + struct sysfs_rqst *input;
  10387. + struct surface_sam_ssh_rqst rqst = {};
  10388. + struct surface_sam_ssh_buf result = {};
  10389. + int status;
  10390. +
  10391. + // check basic write constriants
  10392. + if (offs != 0 || count - sizeof(struct sysfs_rqst) > ARRAY_SIZE(sam_ssh_debug_rqst_buf_pld))
  10393. + return -EINVAL;
  10394. +
  10395. + if (count < sizeof(struct sysfs_rqst))
  10396. + return -EINVAL;
  10397. +
  10398. + input = (struct sysfs_rqst *)buf;
  10399. +
  10400. + // payload length should be consistent with data provided
  10401. + if (input->cdl + sizeof(struct sysfs_rqst) != count)
  10402. + return -EINVAL;
  10403. +
  10404. + rqst.tc = input->tc;
  10405. + rqst.cid = input->cid;
  10406. + rqst.iid = input->iid;
  10407. + rqst.chn = input->chn;
  10408. + rqst.snc = input->snc;
  10409. + rqst.cdl = input->cdl;
  10410. + rqst.pld = sam_ssh_debug_rqst_buf_pld;
  10411. + memcpy(sam_ssh_debug_rqst_buf_pld, &input->pld[0], input->cdl);
  10412. +
  10413. + result.cap = ARRAY_SIZE(sam_ssh_debug_rqst_buf_res);
  10414. + result.len = 0;
  10415. + result.data = sam_ssh_debug_rqst_buf_res;
  10416. +
  10417. + status = surface_sam_ssh_rqst(&rqst, &result);
  10418. + if (status)
  10419. + return status;
  10420. +
  10421. + sam_ssh_debug_rqst_buf_sysfs[0] = result.len;
  10422. + memcpy(sam_ssh_debug_rqst_buf_sysfs + 1, result.data, result.len);
  10423. + memset(sam_ssh_debug_rqst_buf_sysfs + result.len + 1, 0,
  10424. + ARRAY_SIZE(sam_ssh_debug_rqst_buf_sysfs) + 1 - result.len);
  10425. +
  10426. + return count;
  10427. +}
  10428. +
  10429. +static const BIN_ATTR_RW(rqst, ARRAY_SIZE(sam_ssh_debug_rqst_buf_sysfs));
  10430. +
  10431. +static int surface_sam_ssh_sysfs_register(struct device *dev)
  10432. +{
  10433. + return sysfs_create_bin_file(&dev->kobj, &bin_attr_rqst);
  10434. +}
  10435. +
  10436. +static void surface_sam_ssh_sysfs_unregister(struct device *dev)
  10437. +{
  10438. + sysfs_remove_bin_file(&dev->kobj, &bin_attr_rqst);
  10439. +}
  10440. +
  10441. +#else /* CONFIG_SURFACE_SAM_SSH_DEBUG_DEVICE */
  10442. +
  10443. +static int surface_sam_ssh_sysfs_register(struct device *dev)
  10444. +{
  10445. + return 0;
  10446. +}
  10447. +
  10448. +static void surface_sam_ssh_sysfs_unregister(struct device *dev)
  10449. +{
  10450. +}
  10451. +
  10452. +#endif /* CONFIG_SURFACE_SAM_SSH_DEBUG_DEVICE */
  10453. +
  10454. +
  10455. +static int surface_sam_ssh_probe(struct serdev_device *serdev)
  10456. +{
  10457. + struct sam_ssh_ec *ec;
  10458. + acpi_handle *ssh = ACPI_HANDLE(&serdev->dev);
  10459. + int status, irq;
  10460. +
  10461. + if (gpiod_count(&serdev->dev, NULL) < 0)
  10462. + return -ENODEV;
  10463. +
  10464. + status = devm_acpi_dev_add_driver_gpios(&serdev->dev, ssh_acpi_gpios);
  10465. + if (status)
  10466. + return status;
  10467. +
  10468. + // setup IRQ
  10469. + irq = ssh_setup_irq(serdev);
  10470. + if (irq < 0)
  10471. + return irq;
  10472. +
  10473. + // set up EC
  10474. + ec = surface_sam_ssh_acquire();
  10475. + if (smp_load_acquire(&ec->state) != SSH_EC_UNINITIALIZED) {
  10476. + dev_err(&serdev->dev, "embedded controller already initialized\n");
  10477. +
  10478. + status = -EBUSY;
  10479. + goto err_ecinit;
  10480. + }
  10481. +
  10482. + ec->serdev = serdev;
  10483. + ec->irq = irq;
  10484. + ssh_seq_reset(&ec->counter.seq);
  10485. + ssh_rqid_reset(&ec->counter.rqid);
  10486. +
  10487. + // initialize event/request completion system
  10488. + status = ssam_cplt_init(&ec->cplt, &serdev->dev);
  10489. + if (status)
  10490. + goto err_ecinit;
  10491. +
  10492. + // initialize request and packet transmission layers
  10493. + status = ssh_rtl_init(&ec->rtl, serdev, &ssam_rtl_ops);
  10494. + if (status)
  10495. + goto err_rtl;
  10496. +
  10497. + serdev_device_set_drvdata(serdev, ec);
  10498. +
  10499. + serdev_device_set_client_ops(serdev, &ssam_serdev_ops);
  10500. + status = serdev_device_open(serdev);
  10501. + if (status)
  10502. + goto err_open;
  10503. +
  10504. + status = acpi_walk_resources(ssh, METHOD_NAME__CRS,
  10505. + ssh_setup_from_resource, serdev);
  10506. + if (ACPI_FAILURE(status))
  10507. + goto err_devinit;
  10508. +
  10509. + status = ssh_rtl_tx_start(&ec->rtl);
  10510. + if (status)
  10511. + goto err_devinit;
  10512. +
  10513. + status = ssh_rtl_rx_start(&ec->rtl);
  10514. + if (status)
  10515. + goto err_devinit;
  10516. +
  10517. + smp_store_release(&ec->state, SSH_EC_INITIALIZED);
  10518. +
  10519. + status = surface_sam_ssh_log_controller_version(ec);
  10520. + if (status)
  10521. + goto err_finalize;
  10522. +
  10523. + status = surface_sam_ssh_ec_resume(ec);
  10524. + if (status)
  10525. + goto err_finalize;
  10526. +
  10527. + status = surface_sam_ssh_sysfs_register(&serdev->dev);
  10528. + if (status)
  10529. + goto err_finalize;
  10530. +
  10531. + // TODO: The EC can wake up the system via the associated GPIO interrupt in
  10532. + // multiple situations. One of which is the remaining battery capacity
  10533. + // falling below a certain threshold. Normally, we should use the
  10534. + // device_init_wakeup function, however, the EC also seems to have other
  10535. + // reasons for waking up the system and it seems that Windows has
  10536. + // additional checks whether the system should be resumed. In short, this
  10537. + // causes some spourious unwanted wake-ups. For now let's thus default
  10538. + // power/wakeup to false.
  10539. + device_set_wakeup_capable(&serdev->dev, true);
  10540. + acpi_walk_dep_device_list(ssh);
  10541. +
  10542. + return 0;
  10543. +
  10544. +err_finalize:
  10545. + smp_store_release(&ec->state, SSH_EC_UNINITIALIZED);
  10546. + ssh_rtl_flush(&ec->rtl, msecs_to_jiffies(5000));
  10547. +err_devinit:
  10548. + serdev_device_close(serdev);
  10549. +err_open:
  10550. + ssh_rtl_shutdown(&ec->rtl);
  10551. + ssh_rtl_destroy(&ec->rtl);
  10552. +err_rtl:
  10553. + ssam_cplt_flush(&ec->cplt);
  10554. + ssam_cplt_destroy(&ec->cplt);
  10555. +err_ecinit:
  10556. + free_irq(irq, serdev);
  10557. + serdev_device_set_drvdata(serdev, NULL);
  10558. + return status;
  10559. +}
  10560. +
  10561. +static void surface_sam_ssh_remove(struct serdev_device *serdev)
  10562. +{
  10563. + struct sam_ssh_ec *ec;
  10564. + int status;
  10565. +
  10566. + ec = surface_sam_ssh_acquire_init();
  10567. + if (!ec)
  10568. + return;
  10569. +
  10570. + free_irq(ec->irq, serdev);
  10571. + surface_sam_ssh_sysfs_unregister(&serdev->dev);
  10572. +
  10573. + // suspend EC and disable events
  10574. + status = surface_sam_ssh_ec_suspend(ec);
  10575. + if (status)
  10576. + dev_err(&serdev->dev, "failed to suspend EC: %d\n", status);
  10577. +
  10578. + // flush pending events and requests while everything still works
  10579. + status = ssh_rtl_flush(&ec->rtl, msecs_to_jiffies(5000));
  10580. + if (status)
  10581. + dev_err(&serdev->dev, "failed to flush request transmission layer: %d\n", status);
  10582. +
  10583. + ssam_cplt_flush(&ec->cplt);
  10584. +
  10585. + // mark device as uninitialized
  10586. + smp_store_release(&ec->state, SSH_EC_UNINITIALIZED);
  10587. +
  10588. + // cancel rem. requests, ensure no new ones can be queued, stop threads
  10589. + ssh_rtl_tx_flush(&ec->rtl);
  10590. + ssh_rtl_shutdown(&ec->rtl);
  10591. +
  10592. + // shut down actual transport
  10593. + serdev_device_wait_until_sent(ec->serdev, 0);
  10594. + serdev_device_close(ec->serdev);
  10595. +
  10596. + /*
  10597. + * Ensure _all_ events are completed. New ones could still have been
  10598. + * received after the last flush, before the request transport layer
  10599. + * has been shut down. At this point we can be sure that no requests
  10600. + * will remain after this call.
  10601. + */
  10602. + ssam_cplt_flush(&ec->cplt);
  10603. +
  10604. + // actually free resources
  10605. + ssam_cplt_destroy(&ec->cplt);
  10606. + ssh_rtl_destroy(&ec->rtl);
  10607. +
  10608. + ec->serdev = NULL;
  10609. + ec->irq = -1;
  10610. +
  10611. + device_set_wakeup_capable(&serdev->dev, false);
  10612. + serdev_device_set_drvdata(serdev, NULL);
  10613. +}
  10614. +
  10615. +
  10616. +static const struct acpi_device_id surface_sam_ssh_match[] = {
  10617. + { "MSHW0084", 0 },
  10618. + { },
  10619. +};
  10620. +MODULE_DEVICE_TABLE(acpi, surface_sam_ssh_match);
  10621. +
  10622. +static struct serdev_device_driver surface_sam_ssh = {
  10623. + .probe = surface_sam_ssh_probe,
  10624. + .remove = surface_sam_ssh_remove,
  10625. + .driver = {
  10626. + .name = "surface_sam_ssh",
  10627. + .acpi_match_table = surface_sam_ssh_match,
  10628. + .pm = &surface_sam_ssh_pm_ops,
  10629. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  10630. + },
  10631. +};
  10632. +
  10633. +
  10634. +static int __init surface_sam_ssh_init(void)
  10635. +{
  10636. + return serdev_device_driver_register(&surface_sam_ssh);
  10637. +}
  10638. +
  10639. +static void __exit surface_sam_ssh_exit(void)
  10640. +{
  10641. + serdev_device_driver_unregister(&surface_sam_ssh);
  10642. +}
  10643. +
  10644. +/*
  10645. + * Ensure that the driver is loaded late due to some issues with the UART
  10646. + * communication. Specifically, we want to ensure that DMA is ready and being
  10647. + * used. Not using DMA can result in spurious communication failures,
  10648. + * especially during boot, which among other things will result in wrong
  10649. + * battery information (via ACPI _BIX) being displayed. Using a late init_call
  10650. + * instead of the normal module_init gives the DMA subsystem time to
  10651. + * initialize and via that results in a more stable communication, avoiding
  10652. + * such failures.
  10653. + */
  10654. +late_initcall(surface_sam_ssh_init);
  10655. +module_exit(surface_sam_ssh_exit);
  10656. +
  10657. +MODULE_AUTHOR("Maximilian Luz <luzmaximilian@gmail.com>");
  10658. +MODULE_DESCRIPTION("Surface Serial Hub Driver for 5th Generation Surface Devices");
  10659. +MODULE_LICENSE("GPL");
  10660. diff --git a/drivers/platform/x86/surface_sam/surface_sam_ssh.h b/drivers/platform/x86/surface_sam/surface_sam_ssh.h
  10661. new file mode 100644
  10662. index 0000000000000..25a3ae85fee7f
  10663. --- /dev/null
  10664. +++ b/drivers/platform/x86/surface_sam/surface_sam_ssh.h
  10665. @@ -0,0 +1,488 @@
  10666. +/* SPDX-License-Identifier: GPL-2.0-or-later */
  10667. +/*
  10668. + * Interface for Surface Serial Hub (SSH).
  10669. + *
  10670. + * The SSH is the main communication hub for communication between host and
  10671. + * the Surface/System Aggregator Module (SAM) on newer Microsoft Surface
  10672. + * devices (Book 2, Pro 5, Laptops, ...). Also referred to as SAM-over-SSH.
  10673. + * Older devices (Book 1, Pro 4) use SAM-over-HID (via I2C).
  10674. + */
  10675. +
  10676. +#ifndef _SURFACE_SAM_SSH_H
  10677. +#define _SURFACE_SAM_SSH_H
  10678. +
  10679. +#include <linux/types.h>
  10680. +#include <linux/device.h>
  10681. +
  10682. +
  10683. +/* -- Data structures for SAM-over-SSH communication. ----------------------- */
  10684. +
  10685. +/**
  10686. + * enum ssh_frame_type - Frame types for SSH frames.
  10687. + * @SSH_FRAME_TYPE_DATA_SEQ: Indicates a data frame, followed by a payload with
  10688. + * the length specified in the ssh_frame.len field. This
  10689. + * frame is sequenced, meaning that an ACK is required.
  10690. + * @SSH_FRAME_TYPE_DATA_NSQ: Same as SSH_FRAME_TYPE_DATA_SEQ, but unsequenced,
  10691. + * meaning that the message does not have to be ACKed.
  10692. + * @SSH_FRAME_TYPE_ACK: Indicates an ACK message.
  10693. + * @SSH_FRAME_TYPE_NAK: Indicates an error response for previously sent
  10694. + * frame. In general, this means that the frame and/or
  10695. + * payload is malformed, e.g. a CRC is wrong. For command-
  10696. + * type payloads, this can also mean that the command is
  10697. + * invalid.
  10698. + */
  10699. +enum ssh_frame_type {
  10700. + SSH_FRAME_TYPE_DATA_SEQ = 0x80,
  10701. + SSH_FRAME_TYPE_DATA_NSQ = 0x00,
  10702. + SSH_FRAME_TYPE_ACK = 0x40,
  10703. + SSH_FRAME_TYPE_NAK = 0x04,
  10704. +};
  10705. +
  10706. +/**
  10707. + * struct ssh_frame - SSH communication frame.
  10708. + * @type: The type of the frame. See &enum ssh_frame_type.
  10709. + * @len: The length of the frame payload directly following the CRC for this
  10710. + * frame. Does not include the final CRC for that payload.
  10711. + * @seq: The sequence number for this message/exchange.
  10712. + */
  10713. +struct ssh_frame {
  10714. + u8 type;
  10715. + __le16 len;
  10716. + u8 seq;
  10717. +} __packed;
  10718. +
  10719. +static_assert(sizeof(struct ssh_frame) == 4);
  10720. +
  10721. +/*
  10722. + * Maximum SSH frame payload length in bytes. This is the physical maximum
  10723. + * length of the protocol. Implementations may set a more constrained limit.
  10724. + */
  10725. +#define SSH_FRAME_MAX_PAYLOAD_SIZE U16_MAX
  10726. +
  10727. +/**
  10728. + * enum ssh_payload_type - Type indicator for the SSH payload.
  10729. + * @SSH_PLD_TYPE_CMD: The payload is a command structure with optional command
  10730. + * payload.
  10731. + */
  10732. +enum ssh_payload_type {
  10733. + SSH_PLD_TYPE_CMD = 0x80,
  10734. +};
  10735. +
  10736. +/**
  10737. + * struct ssh_command - Payload of a command-type frame.
  10738. + * @type: The type of the payload. See &enum ssh_payload_type. Should be
  10739. + * SSH_PLD_TYPE_CMD for this struct.
  10740. + * @tc: Command target category.
  10741. + * @chn_out: Output channel. Should be zero if this an incoming (EC to host)
  10742. + * message.
  10743. + * @chn_in: Input channel. Should be zero if this is an outgoing (hos to EC)
  10744. + * message.
  10745. + * @iid: Instance ID.
  10746. + * @rqid: Request ID. Used to match requests with responses and differentiate
  10747. + * between responses and events.
  10748. + * @cid: Command ID.
  10749. + */
  10750. +struct ssh_command {
  10751. + u8 type;
  10752. + u8 tc;
  10753. + u8 chn_out;
  10754. + u8 chn_in;
  10755. + u8 iid;
  10756. + __le16 rqid;
  10757. + u8 cid;
  10758. +} __packed;
  10759. +
  10760. +static_assert(sizeof(struct ssh_command) == 8);
  10761. +
  10762. +/*
  10763. + * Maximum SSH command payload length in bytes. This is the physical maximum
  10764. + * length of the protocol. Implementations may set a more constrained limit.
  10765. + */
  10766. +#define SSH_COMMAND_MAX_PAYLOAD_SIZE \
  10767. + (SSH_FRAME_MAX_PAYLOAD_SIZE - sizeof(struct ssh_command))
  10768. +
  10769. +/**
  10770. + * struct ssh_notification_params - Command payload to enable/disable SSH
  10771. + * notifications.
  10772. + * @target_category: The target category for which notifications should be
  10773. + * enabled/disabled.
  10774. + * @flags: Flags determining how notifications are being sent.
  10775. + * @request_id: The request ID that is used to send these notifications.
  10776. + * @instance_id: The specific instance in the given target category for
  10777. + * which notifications should be enabled.
  10778. + */
  10779. +struct ssh_notification_params {
  10780. + u8 target_category;
  10781. + u8 flags;
  10782. + __le16 request_id;
  10783. + u8 instance_id;
  10784. +} __packed;
  10785. +
  10786. +static_assert(sizeof(struct ssh_notification_params) == 5);
  10787. +
  10788. +/**
  10789. + * SSH message syncrhonization (SYN) bytes.
  10790. + */
  10791. +#define SSH_MSG_SYN ((u16)0x55aa)
  10792. +
  10793. +/**
  10794. + * Base-length of a SSH message. This is the minimum number of bytes required
  10795. + * to form a message. The actual message length is SSH_MSG_LEN_BASE plus the
  10796. + * length of the frame payload.
  10797. + */
  10798. +#define SSH_MSG_LEN_BASE (sizeof(struct ssh_frame) + 3ull * sizeof(u16))
  10799. +
  10800. +/**
  10801. + * Length of a SSH control message.
  10802. + */
  10803. +#define SSH_MSG_LEN_CTRL SSH_MSG_LEN_BASE
  10804. +
  10805. +/**
  10806. + * Length of a SSH message with payload of specified size.
  10807. + */
  10808. +#define SSH_MESSAGE_LENGTH(payload_size) (SSH_MSG_LEN_BASE + payload_size)
  10809. +
  10810. +/**
  10811. + * Length of a SSH command message with command payload of specified size.
  10812. + */
  10813. +#define SSH_COMMAND_MESSAGE_LENGTH(payload_size) \
  10814. + SSH_MESSAGE_LENGTH(sizeof(struct ssh_command) + payload_size)
  10815. +
  10816. +/**
  10817. + * Offset of the specified struct ssh_frame field in the raw SSH message data.
  10818. + */
  10819. +#define SSH_MSGOFFSET_FRAME(field) \
  10820. + (sizeof(u16) + offsetof(struct ssh_frame, field))
  10821. +
  10822. +/**
  10823. + * Offset of the specified struct ssh_command field in the raw SSH message data.
  10824. + */
  10825. +#define SSH_MSGOFFSET_COMMAND(field) \
  10826. + (2ull * sizeof(u16) + sizeof(struct ssh_frame) \
  10827. + + offsetof(struct ssh_command, field))
  10828. +
  10829. +struct sshp_span {
  10830. + u8 *ptr;
  10831. + size_t len;
  10832. +};
  10833. +
  10834. +
  10835. +/* -- Packet transport layer (ptl). ----------------------------------------- */
  10836. +
  10837. +enum ssh_packet_priority {
  10838. + SSH_PACKET_PRIORITY_FLUSH = 0,
  10839. + SSH_PACKET_PRIORITY_DATA = 0,
  10840. + SSH_PACKET_PRIORITY_NAK = 1 << 4,
  10841. + SSH_PACKET_PRIORITY_ACK = 2 << 4,
  10842. +};
  10843. +
  10844. +#define SSH_PACKET_PRIORITY(base, try) \
  10845. + ((SSH_PACKET_PRIORITY_##base) | ((try) & 0x0f))
  10846. +
  10847. +#define ssh_packet_priority_get_try(p) ((p) & 0x0f)
  10848. +
  10849. +
  10850. +enum ssh_packet_type_flags {
  10851. + SSH_PACKET_TY_FLUSH_BIT,
  10852. + SSH_PACKET_TY_SEQUENCED_BIT,
  10853. + SSH_PACKET_TY_BLOCKING_BIT,
  10854. +
  10855. + SSH_PACKET_TY_FLUSH = BIT(SSH_PACKET_TY_FLUSH_BIT),
  10856. + SSH_PACKET_TY_SEQUENCED = BIT(SSH_PACKET_TY_SEQUENCED_BIT),
  10857. + SSH_PACKET_TY_BLOCKING = BIT(SSH_PACKET_TY_BLOCKING_BIT),
  10858. +};
  10859. +
  10860. +enum ssh_packet_state_flags {
  10861. + SSH_PACKET_SF_LOCKED_BIT,
  10862. + SSH_PACKET_SF_QUEUED_BIT,
  10863. + SSH_PACKET_SF_PENDING_BIT,
  10864. + SSH_PACKET_SF_TRANSMITTING_BIT,
  10865. + SSH_PACKET_SF_TRANSMITTED_BIT,
  10866. + SSH_PACKET_SF_ACKED_BIT,
  10867. + SSH_PACKET_SF_CANCELED_BIT,
  10868. + SSH_PACKET_SF_COMPLETED_BIT,
  10869. +};
  10870. +
  10871. +
  10872. +struct ssh_ptl;
  10873. +struct ssh_packet;
  10874. +
  10875. +struct ssh_packet_ops {
  10876. + void (*release)(struct ssh_packet *packet);
  10877. + void (*complete)(struct ssh_packet *packet, int status);
  10878. +};
  10879. +
  10880. +struct ssh_packet {
  10881. + struct ssh_ptl *ptl;
  10882. + struct kref refcnt;
  10883. +
  10884. + u8 type;
  10885. + u8 priority;
  10886. + u16 data_length;
  10887. + u8 *data;
  10888. +
  10889. + unsigned long state;
  10890. + ktime_t timestamp;
  10891. +
  10892. + struct list_head queue_node;
  10893. + struct list_head pending_node;
  10894. +
  10895. + const struct ssh_packet_ops *ops;
  10896. +};
  10897. +
  10898. +
  10899. +/* -- Request transport layer (rtl). ---------------------------------------- */
  10900. +
  10901. +enum ssh_request_flags {
  10902. + SSH_REQUEST_SF_LOCKED_BIT,
  10903. + SSH_REQUEST_SF_QUEUED_BIT,
  10904. + SSH_REQUEST_SF_PENDING_BIT,
  10905. + SSH_REQUEST_SF_TRANSMITTING_BIT,
  10906. + SSH_REQUEST_SF_TRANSMITTED_BIT,
  10907. + SSH_REQUEST_SF_RSPRCVD_BIT,
  10908. + SSH_REQUEST_SF_CANCELED_BIT,
  10909. + SSH_REQUEST_SF_COMPLETED_BIT,
  10910. +
  10911. + SSH_REQUEST_TY_FLUSH_BIT,
  10912. + SSH_REQUEST_TY_HAS_RESPONSE_BIT,
  10913. +
  10914. + SSH_REQUEST_FLAGS_SF_MASK =
  10915. + BIT(SSH_REQUEST_SF_LOCKED_BIT)
  10916. + | BIT(SSH_REQUEST_SF_QUEUED_BIT)
  10917. + | BIT(SSH_REQUEST_SF_PENDING_BIT)
  10918. + | BIT(SSH_REQUEST_SF_TRANSMITTING_BIT)
  10919. + | BIT(SSH_REQUEST_SF_TRANSMITTED_BIT)
  10920. + | BIT(SSH_REQUEST_SF_RSPRCVD_BIT)
  10921. + | BIT(SSH_REQUEST_SF_CANCELED_BIT)
  10922. + | BIT(SSH_REQUEST_SF_COMPLETED_BIT),
  10923. +
  10924. + SSH_REQUEST_FLAGS_TY_MASK =
  10925. + BIT(SSH_REQUEST_TY_FLUSH_BIT)
  10926. + | BIT(SSH_REQUEST_TY_HAS_RESPONSE_BIT),
  10927. +};
  10928. +
  10929. +
  10930. +struct ssh_rtl;
  10931. +struct ssh_request;
  10932. +
  10933. +struct ssh_request_ops {
  10934. + void (*release)(struct ssh_request *rqst);
  10935. + void (*complete)(struct ssh_request *rqst,
  10936. + const struct ssh_command *cmd,
  10937. + const struct sshp_span *data, int status);
  10938. +};
  10939. +
  10940. +struct ssh_request {
  10941. + struct ssh_rtl *rtl;
  10942. + struct ssh_packet packet;
  10943. + struct list_head node;
  10944. +
  10945. + unsigned long state;
  10946. + ktime_t timestamp;
  10947. +
  10948. + const struct ssh_request_ops *ops;
  10949. +};
  10950. +
  10951. +
  10952. +/* -- Main data types and definitions --------------------------------------- */
  10953. +
  10954. +enum ssam_ssh_tc {
  10955. + SSAM_SSH_TC_SAM = 0x01, // generic system functionality, real-time clock
  10956. + SSAM_SSH_TC_BAT = 0x02, // battery/power subsystem
  10957. + SSAM_SSH_TC_TMP = 0x03, // thermal subsystem
  10958. + SSAM_SSH_TC_PMC = 0x04,
  10959. + SSAM_SSH_TC_FAN = 0x05,
  10960. + SSAM_SSH_TC_PoM = 0x06,
  10961. + SSAM_SSH_TC_DBG = 0x07,
  10962. + SSAM_SSH_TC_KBD = 0x08, // legacy keyboard (Laptop 1/2)
  10963. + SSAM_SSH_TC_FWU = 0x09,
  10964. + SSAM_SSH_TC_UNI = 0x0a,
  10965. + SSAM_SSH_TC_LPC = 0x0b,
  10966. + SSAM_SSH_TC_TCL = 0x0c,
  10967. + SSAM_SSH_TC_SFL = 0x0d,
  10968. + SSAM_SSH_TC_KIP = 0x0e,
  10969. + SSAM_SSH_TC_EXT = 0x0f,
  10970. + SSAM_SSH_TC_BLD = 0x10,
  10971. + SSAM_SSH_TC_BAS = 0x11, // detachment system (Surface Book 2/3)
  10972. + SSAM_SSH_TC_SEN = 0x12,
  10973. + SSAM_SSH_TC_SRQ = 0x13,
  10974. + SSAM_SSH_TC_MCU = 0x14,
  10975. + SSAM_SSH_TC_HID = 0x15, // generic HID input subsystem
  10976. + SSAM_SSH_TC_TCH = 0x16,
  10977. + SSAM_SSH_TC_BKL = 0x17,
  10978. + SSAM_SSH_TC_TAM = 0x18,
  10979. + SSAM_SSH_TC_ACC = 0x19,
  10980. + SSAM_SSH_TC_UFI = 0x1a,
  10981. + SSAM_SSH_TC_USC = 0x1b,
  10982. + SSAM_SSH_TC_PEN = 0x1c,
  10983. + SSAM_SSH_TC_VID = 0x1d,
  10984. + SSAM_SSH_TC_AUD = 0x1e,
  10985. + SSAM_SSH_TC_SMC = 0x1f,
  10986. + SSAM_SSH_TC_KPD = 0x20,
  10987. + SSAM_SSH_TC_REG = 0x21,
  10988. +};
  10989. +
  10990. +/**
  10991. + * struct ssam_event_flags - Flags for enabling/disabling SAM-over-SSH events
  10992. + * @SSAM_EVENT_SEQUENCED: The event will be sent via a sequenced data frame.
  10993. + */
  10994. +enum ssam_event_flags {
  10995. + SSAM_EVENT_SEQUENCED = BIT(0),
  10996. +};
  10997. +
  10998. +struct ssam_event {
  10999. + u8 target_category;
  11000. + u8 command_id;
  11001. + u8 instance_id;
  11002. + u8 channel;
  11003. + u16 length;
  11004. + u8 data[0];
  11005. +};
  11006. +
  11007. +
  11008. +/* -- Event notifier/callbacks. --------------------------------------------- */
  11009. +
  11010. +#define SSAM_NOTIF_STATE_SHIFT 2
  11011. +#define SSAM_NOTIF_STATE_MASK ((1 << SSAM_NOTIF_STATE_SHIFT) - 1)
  11012. +
  11013. +#define SSAM_NOTIF_HANDLED BIT(0)
  11014. +#define SSAM_NOTIF_STOP BIT(1)
  11015. +
  11016. +
  11017. +struct ssam_notifier_block;
  11018. +
  11019. +typedef u32 (*ssam_notifier_fn_t)(struct ssam_notifier_block *nb,
  11020. + const struct ssam_event *event);
  11021. +
  11022. +struct ssam_notifier_block {
  11023. + struct ssam_notifier_block __rcu *next;
  11024. + ssam_notifier_fn_t fn;
  11025. + int priority;
  11026. +};
  11027. +
  11028. +
  11029. +static inline u32 ssam_notifier_from_errno(int err)
  11030. +{
  11031. + WARN_ON(err > 0);
  11032. +
  11033. + if (err >= 0)
  11034. + return 0;
  11035. + else
  11036. + return ((-err) << SSAM_NOTIF_STATE_SHIFT) | SSAM_NOTIF_STOP;
  11037. +}
  11038. +
  11039. +static inline int ssam_notifier_to_errno(u32 ret)
  11040. +{
  11041. + return -(ret >> SSAM_NOTIF_STATE_SHIFT);
  11042. +}
  11043. +
  11044. +
  11045. +/* -- Event/notification registry. ------------------------------------------ */
  11046. +
  11047. +struct ssam_event_registry {
  11048. + u8 target_category;
  11049. + u8 channel;
  11050. + u8 cid_enable;
  11051. + u8 cid_disable;
  11052. +};
  11053. +
  11054. +struct ssam_event_id {
  11055. + u8 target_category;
  11056. + u8 instance;
  11057. +};
  11058. +
  11059. +
  11060. +#define SSAM_EVENT_REGISTRY(tc, chn, cid_en, cid_dis) \
  11061. + ((struct ssam_event_registry) { \
  11062. + .target_category = (tc), \
  11063. + .channel = (chn), \
  11064. + .cid_enable = (cid_en), \
  11065. + .cid_disable = (cid_dis), \
  11066. + })
  11067. +
  11068. +#define SSAM_EVENT_ID(tc, iid) \
  11069. + ((struct ssam_event_id) { \
  11070. + .target_category = tc, \
  11071. + .instance = iid, \
  11072. + })
  11073. +
  11074. +
  11075. +#define SSAM_EVENT_REGISTRY_SAM \
  11076. + SSAM_EVENT_REGISTRY(SSAM_SSH_TC_SAM, 0x01, 0x0b, 0x0c)
  11077. +
  11078. +#define SSAM_EVENT_REGISTRY_KIP \
  11079. + SSAM_EVENT_REGISTRY(SSAM_SSH_TC_KIP, 0x02, 0x27, 0x28)
  11080. +
  11081. +#define SSAM_EVENT_REGISTRY_REG \
  11082. + SSAM_EVENT_REGISTRY(SSAM_SSH_TC_REG, 0x02, 0x01, 0x02)
  11083. +
  11084. +
  11085. +struct ssam_event_notifier {
  11086. + struct ssam_notifier_block base;
  11087. +
  11088. + struct {
  11089. + struct ssam_event_registry reg;
  11090. + struct ssam_event_id id;
  11091. + u8 flags;
  11092. + } event;
  11093. +};
  11094. +
  11095. +
  11096. +/* -- TODO -------------------------------------------------------------------*/
  11097. +
  11098. +/*
  11099. + * Maximum response payload size in bytes.
  11100. + * Value based on ACPI (255 bytes minus header/status bytes).
  11101. + */
  11102. +#define SURFACE_SAM_SSH_MAX_RQST_RESPONSE (255 - 4)
  11103. +
  11104. +/*
  11105. + * The number of reserved event IDs, used for registering an SSH event
  11106. + * handler. Valid event IDs are numbers below or equal to this value, with
  11107. + * exception of zero, which is not an event ID. Thus, this is also the
  11108. + * absolute maximum number of event handlers that can be registered.
  11109. + */
  11110. +#define SURFACE_SAM_SSH_NUM_EVENTS 0x22
  11111. +
  11112. +/*
  11113. + * The number of communication channels used in the protocol.
  11114. + */
  11115. +#define SURFACE_SAM_SSH_NUM_CHANNELS 2
  11116. +
  11117. +
  11118. +struct surface_sam_ssh_buf {
  11119. + u8 cap;
  11120. + u8 len;
  11121. + u8 *data;
  11122. +};
  11123. +
  11124. +struct surface_sam_ssh_rqst {
  11125. + u8 tc; // target category
  11126. + u8 cid; // command ID
  11127. + u8 iid; // instance ID
  11128. + u8 chn; // channel
  11129. + u8 snc; // expect response flag (bool: 0/1)
  11130. + u16 cdl; // command data length (length of payload)
  11131. + u8 *pld; // pointer to payload of length cdl
  11132. +};
  11133. +
  11134. +// TODO: remove rqid on external api
  11135. +struct surface_sam_ssh_event {
  11136. + u16 rqid; // event type/source ID
  11137. + u8 tc; // target category
  11138. + u8 cid; // command ID
  11139. + u8 iid; // instance ID
  11140. + u8 chn; // channel
  11141. + u8 len; // length of payload
  11142. + u8 *pld; // payload of length len
  11143. +};
  11144. +
  11145. +
  11146. +int surface_sam_ssh_consumer_register(struct device *consumer);
  11147. +
  11148. +int surface_sam_ssh_notifier_register(struct ssam_event_notifier *n);
  11149. +int surface_sam_ssh_notifier_unregister(struct ssam_event_notifier *n);
  11150. +
  11151. +int surface_sam_ssh_rqst(const struct surface_sam_ssh_rqst *rqst, struct surface_sam_ssh_buf *result);
  11152. +
  11153. +#endif /* _SURFACE_SAM_SSH_H */
  11154. diff --git a/drivers/platform/x86/surface_sam/surface_sam_ssh_trace.h b/drivers/platform/x86/surface_sam/surface_sam_ssh_trace.h
  11155. new file mode 100644
  11156. index 0000000000000..801c60205128c
  11157. --- /dev/null
  11158. +++ b/drivers/platform/x86/surface_sam/surface_sam_ssh_trace.h
  11159. @@ -0,0 +1,536 @@
  11160. +#undef TRACE_SYSTEM
  11161. +#define TRACE_SYSTEM surface_sam_ssh
  11162. +
  11163. +#if !defined(_SURFACE_SAM_SSH_TRACE_H) || defined(TRACE_HEADER_MULTI_READ)
  11164. +#define _SURFACE_SAM_SSH_TRACE_H
  11165. +
  11166. +#include <linux/tracepoint.h>
  11167. +
  11168. +#include "surface_sam_ssh.h"
  11169. +
  11170. +
  11171. +TRACE_DEFINE_ENUM(SSH_FRAME_TYPE_DATA_SEQ);
  11172. +TRACE_DEFINE_ENUM(SSH_FRAME_TYPE_DATA_NSQ);
  11173. +TRACE_DEFINE_ENUM(SSH_FRAME_TYPE_ACK);
  11174. +TRACE_DEFINE_ENUM(SSH_FRAME_TYPE_NAK);
  11175. +
  11176. +TRACE_DEFINE_ENUM(SSH_PACKET_TY_FLUSH_BIT);
  11177. +TRACE_DEFINE_ENUM(SSH_PACKET_TY_SEQUENCED_BIT);
  11178. +TRACE_DEFINE_ENUM(SSH_PACKET_TY_BLOCKING_BIT);
  11179. +
  11180. +TRACE_DEFINE_ENUM(SSH_PACKET_TY_FLUSH);
  11181. +TRACE_DEFINE_ENUM(SSH_PACKET_TY_SEQUENCED);
  11182. +TRACE_DEFINE_ENUM(SSH_PACKET_TY_BLOCKING);
  11183. +
  11184. +TRACE_DEFINE_ENUM(SSH_PACKET_SF_LOCKED_BIT);
  11185. +TRACE_DEFINE_ENUM(SSH_PACKET_SF_QUEUED_BIT);
  11186. +TRACE_DEFINE_ENUM(SSH_PACKET_SF_PENDING_BIT);
  11187. +TRACE_DEFINE_ENUM(SSH_PACKET_SF_TRANSMITTING_BIT);
  11188. +TRACE_DEFINE_ENUM(SSH_PACKET_SF_TRANSMITTED_BIT);
  11189. +TRACE_DEFINE_ENUM(SSH_PACKET_SF_ACKED_BIT);
  11190. +TRACE_DEFINE_ENUM(SSH_PACKET_SF_CANCELED_BIT);
  11191. +TRACE_DEFINE_ENUM(SSH_PACKET_SF_COMPLETED_BIT);
  11192. +
  11193. +TRACE_DEFINE_ENUM(SSH_REQUEST_SF_LOCKED_BIT);
  11194. +TRACE_DEFINE_ENUM(SSH_REQUEST_SF_QUEUED_BIT);
  11195. +TRACE_DEFINE_ENUM(SSH_REQUEST_SF_PENDING_BIT);
  11196. +TRACE_DEFINE_ENUM(SSH_REQUEST_SF_TRANSMITTING_BIT);
  11197. +TRACE_DEFINE_ENUM(SSH_REQUEST_SF_TRANSMITTED_BIT);
  11198. +TRACE_DEFINE_ENUM(SSH_REQUEST_SF_RSPRCVD_BIT);
  11199. +TRACE_DEFINE_ENUM(SSH_REQUEST_SF_CANCELED_BIT);
  11200. +TRACE_DEFINE_ENUM(SSH_REQUEST_SF_COMPLETED_BIT);
  11201. +TRACE_DEFINE_ENUM(SSH_REQUEST_TY_FLUSH_BIT);
  11202. +TRACE_DEFINE_ENUM(SSH_REQUEST_TY_HAS_RESPONSE_BIT);
  11203. +
  11204. +TRACE_DEFINE_ENUM(SSH_REQUEST_FLAGS_SF_MASK);
  11205. +TRACE_DEFINE_ENUM(SSH_REQUEST_FLAGS_TY_MASK);
  11206. +
  11207. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_SAM);
  11208. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_BAT);
  11209. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_TMP);
  11210. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_PMC);
  11211. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_FAN);
  11212. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_PoM);
  11213. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_DBG);
  11214. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_KBD);
  11215. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_FWU);
  11216. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_UNI);
  11217. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_LPC);
  11218. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_TCL);
  11219. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_SFL);
  11220. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_KIP);
  11221. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_EXT);
  11222. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_BLD);
  11223. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_BAS);
  11224. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_SEN);
  11225. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_SRQ);
  11226. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_MCU);
  11227. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_HID);
  11228. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_TCH);
  11229. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_BKL);
  11230. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_TAM);
  11231. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_ACC);
  11232. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_UFI);
  11233. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_USC);
  11234. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_PEN);
  11235. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_VID);
  11236. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_AUD);
  11237. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_SMC);
  11238. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_KPD);
  11239. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_REG);
  11240. +
  11241. +
  11242. +#define SSAM_PTR_UID_LEN 9
  11243. +#define SSAM_U8_FIELD_NOT_APPLICABLE ((u16)-1)
  11244. +#define SSAM_SEQ_NOT_APPLICABLE ((u16)-1)
  11245. +#define SSAM_RQID_NOT_APPLICABLE ((u32)-1)
  11246. +#define SSAM_SSH_TC_NOT_APPLICABLE 0
  11247. +
  11248. +
  11249. +#ifndef _SURFACE_SAM_SSH_TRACE_HELPERS
  11250. +#define _SURFACE_SAM_SSH_TRACE_HELPERS
  11251. +
  11252. +static inline void ssam_trace_ptr_uid(const void *ptr, char* uid_str)
  11253. +{
  11254. + char buf[2 * sizeof(void*) + 1];
  11255. +
  11256. + snprintf(buf, ARRAY_SIZE(buf), "%p", ptr);
  11257. + memcpy(uid_str, &buf[ARRAY_SIZE(buf) - SSAM_PTR_UID_LEN],
  11258. + SSAM_PTR_UID_LEN);
  11259. +}
  11260. +
  11261. +static inline u16 ssam_trace_get_packet_seq(const struct ssh_packet *p)
  11262. +{
  11263. + if (!p->data || p->data_length < SSH_MESSAGE_LENGTH(0))
  11264. + return SSAM_SEQ_NOT_APPLICABLE;
  11265. +
  11266. + return p->data[SSH_MSGOFFSET_FRAME(seq)];
  11267. +}
  11268. +
  11269. +static inline u32 ssam_trace_get_request_id(const struct ssh_packet *p)
  11270. +{
  11271. + if (!p->data || p->data_length < SSH_COMMAND_MESSAGE_LENGTH(0))
  11272. + return SSAM_RQID_NOT_APPLICABLE;
  11273. +
  11274. + return get_unaligned_le16(&p->data[SSH_MSGOFFSET_COMMAND(rqid)]);
  11275. +}
  11276. +
  11277. +static inline u32 ssam_trace_get_request_tc(const struct ssh_packet *p)
  11278. +{
  11279. + if (!p->data || p->data_length < SSH_COMMAND_MESSAGE_LENGTH(0))
  11280. + return SSAM_SSH_TC_NOT_APPLICABLE;
  11281. +
  11282. + return get_unaligned_le16(&p->data[SSH_MSGOFFSET_COMMAND(tc)]);
  11283. +}
  11284. +
  11285. +#endif /* _SURFACE_SAM_SSH_TRACE_HELPERS */
  11286. +
  11287. +#define ssam_trace_get_command_field_u8(packet, field) \
  11288. + ((!packet || packet->data_length < SSH_COMMAND_MESSAGE_LENGTH(0)) \
  11289. + ? 0 : p->data[SSH_MSGOFFSET_COMMAND(field)])
  11290. +
  11291. +#define ssam_show_generic_u8_field(value) \
  11292. + __print_symbolic(value, \
  11293. + { SSAM_U8_FIELD_NOT_APPLICABLE, "N/A" } \
  11294. + )
  11295. +
  11296. +
  11297. +#define ssam_show_frame_type(ty) \
  11298. + __print_symbolic(ty, \
  11299. + { SSH_FRAME_TYPE_DATA_SEQ, "DSEQ" }, \
  11300. + { SSH_FRAME_TYPE_DATA_NSQ, "DNSQ" }, \
  11301. + { SSH_FRAME_TYPE_ACK, "ACK" }, \
  11302. + { SSH_FRAME_TYPE_NAK, "NAK" } \
  11303. + )
  11304. +
  11305. +#define ssam_show_packet_type(type) \
  11306. + __print_flags(type, "", \
  11307. + { SSH_PACKET_TY_FLUSH, "F" }, \
  11308. + { SSH_PACKET_TY_SEQUENCED, "S" }, \
  11309. + { SSH_PACKET_TY_BLOCKING, "B" } \
  11310. + )
  11311. +
  11312. +#define ssam_show_packet_state(state) \
  11313. + __print_flags(state, "", \
  11314. + { BIT(SSH_PACKET_SF_LOCKED_BIT), "L" }, \
  11315. + { BIT(SSH_PACKET_SF_QUEUED_BIT), "Q" }, \
  11316. + { BIT(SSH_PACKET_SF_PENDING_BIT), "P" }, \
  11317. + { BIT(SSH_PACKET_SF_TRANSMITTING_BIT), "S" }, \
  11318. + { BIT(SSH_PACKET_SF_TRANSMITTED_BIT), "T" }, \
  11319. + { BIT(SSH_PACKET_SF_ACKED_BIT), "A" }, \
  11320. + { BIT(SSH_PACKET_SF_CANCELED_BIT), "C" }, \
  11321. + { BIT(SSH_PACKET_SF_COMPLETED_BIT), "F" } \
  11322. + )
  11323. +
  11324. +#define ssam_show_packet_seq(seq) \
  11325. + __print_symbolic(seq, \
  11326. + { SSAM_SEQ_NOT_APPLICABLE, "N/A" } \
  11327. + )
  11328. +
  11329. +
  11330. +#define ssam_show_request_type(flags) \
  11331. + __print_flags(flags & SSH_REQUEST_FLAGS_TY_MASK, "", \
  11332. + { BIT(SSH_REQUEST_TY_FLUSH_BIT), "F" }, \
  11333. + { BIT(SSH_REQUEST_TY_HAS_RESPONSE_BIT), "R" } \
  11334. + )
  11335. +
  11336. +#define ssam_show_request_state(flags) \
  11337. + __print_flags(flags & SSH_REQUEST_FLAGS_SF_MASK, "", \
  11338. + { BIT(SSH_REQUEST_SF_LOCKED_BIT), "L" }, \
  11339. + { BIT(SSH_REQUEST_SF_QUEUED_BIT), "Q" }, \
  11340. + { BIT(SSH_REQUEST_SF_PENDING_BIT), "P" }, \
  11341. + { BIT(SSH_REQUEST_SF_TRANSMITTING_BIT), "S" }, \
  11342. + { BIT(SSH_REQUEST_SF_TRANSMITTED_BIT), "T" }, \
  11343. + { BIT(SSH_REQUEST_SF_RSPRCVD_BIT), "A" }, \
  11344. + { BIT(SSH_REQUEST_SF_CANCELED_BIT), "C" }, \
  11345. + { BIT(SSH_REQUEST_SF_COMPLETED_BIT), "F" } \
  11346. + )
  11347. +
  11348. +#define ssam_show_request_id(rqid) \
  11349. + __print_symbolic(rqid, \
  11350. + { SSAM_RQID_NOT_APPLICABLE, "N/A" } \
  11351. + )
  11352. +
  11353. +#define ssam_show_ssh_tc(rqid) \
  11354. + __print_symbolic(rqid, \
  11355. + { SSAM_SSH_TC_NOT_APPLICABLE, "N/A" }, \
  11356. + { SSAM_SSH_TC_SAM, "SAM" }, \
  11357. + { SSAM_SSH_TC_BAT, "BAT" }, \
  11358. + { SSAM_SSH_TC_TMP, "TMP" }, \
  11359. + { SSAM_SSH_TC_PMC, "PMC" }, \
  11360. + { SSAM_SSH_TC_FAN, "FAN" }, \
  11361. + { SSAM_SSH_TC_PoM, "PoM" }, \
  11362. + { SSAM_SSH_TC_DBG, "DBG" }, \
  11363. + { SSAM_SSH_TC_KBD, "KBD" }, \
  11364. + { SSAM_SSH_TC_FWU, "FWU" }, \
  11365. + { SSAM_SSH_TC_UNI, "UNI" }, \
  11366. + { SSAM_SSH_TC_LPC, "LPC" }, \
  11367. + { SSAM_SSH_TC_TCL, "TCL" }, \
  11368. + { SSAM_SSH_TC_SFL, "SFL" }, \
  11369. + { SSAM_SSH_TC_KIP, "KIP" }, \
  11370. + { SSAM_SSH_TC_EXT, "EXT" }, \
  11371. + { SSAM_SSH_TC_BLD, "BLD" }, \
  11372. + { SSAM_SSH_TC_BAS, "BAS" }, \
  11373. + { SSAM_SSH_TC_SEN, "SEN" }, \
  11374. + { SSAM_SSH_TC_SRQ, "SRQ" }, \
  11375. + { SSAM_SSH_TC_MCU, "MCU" }, \
  11376. + { SSAM_SSH_TC_HID, "HID" }, \
  11377. + { SSAM_SSH_TC_TCH, "TCH" }, \
  11378. + { SSAM_SSH_TC_BKL, "BKL" }, \
  11379. + { SSAM_SSH_TC_TAM, "TAM" }, \
  11380. + { SSAM_SSH_TC_ACC, "ACC" }, \
  11381. + { SSAM_SSH_TC_UFI, "UFI" }, \
  11382. + { SSAM_SSH_TC_USC, "USC" }, \
  11383. + { SSAM_SSH_TC_PEN, "PEN" }, \
  11384. + { SSAM_SSH_TC_VID, "VID" }, \
  11385. + { SSAM_SSH_TC_AUD, "AUD" }, \
  11386. + { SSAM_SSH_TC_SMC, "SMC" }, \
  11387. + { SSAM_SSH_TC_KPD, "KPD" }, \
  11388. + { SSAM_SSH_TC_REG, "REG" } \
  11389. + )
  11390. +
  11391. +
  11392. +DECLARE_EVENT_CLASS(ssam_frame_class,
  11393. + TP_PROTO(const struct ssh_frame *frame),
  11394. +
  11395. + TP_ARGS(frame),
  11396. +
  11397. + TP_STRUCT__entry(
  11398. + __field(u8, type)
  11399. + __field(u8, seq)
  11400. + __field(u16, len)
  11401. + ),
  11402. +
  11403. + TP_fast_assign(
  11404. + __entry->type = frame->type;
  11405. + __entry->seq = frame->seq;
  11406. + __entry->len = get_unaligned_le16(&frame->len);
  11407. + ),
  11408. +
  11409. + TP_printk("ty=%s, seq=0x%02x, len=%u",
  11410. + ssam_show_frame_type(__entry->type),
  11411. + __entry->seq,
  11412. + __entry->len
  11413. + )
  11414. +);
  11415. +
  11416. +#define DEFINE_SSAM_FRAME_EVENT(name) \
  11417. + DEFINE_EVENT(ssam_frame_class, ssam_##name, \
  11418. + TP_PROTO(const struct ssh_frame *frame), \
  11419. + TP_ARGS(frame) \
  11420. + )
  11421. +
  11422. +
  11423. +DECLARE_EVENT_CLASS(ssam_command_class,
  11424. + TP_PROTO(const struct ssh_command *cmd, u16 len),
  11425. +
  11426. + TP_ARGS(cmd, len),
  11427. +
  11428. + TP_STRUCT__entry(
  11429. + __field(u16, rqid)
  11430. + __field(u16, len)
  11431. + __field(u8, tc)
  11432. + __field(u8, cid)
  11433. + __field(u8, iid)
  11434. + ),
  11435. +
  11436. + TP_fast_assign(
  11437. + __entry->rqid = get_unaligned_le16(&cmd->rqid);
  11438. + __entry->tc = cmd->tc;
  11439. + __entry->cid = cmd->cid;
  11440. + __entry->iid = cmd->iid;
  11441. + __entry->len = len;
  11442. + ),
  11443. +
  11444. + TP_printk("rqid=0x%04x, tc=%s, cid=0x%02x, iid=0x%02x, len=%u",
  11445. + __entry->rqid,
  11446. + ssam_show_ssh_tc(__entry->tc),
  11447. + __entry->cid,
  11448. + __entry->iid,
  11449. + __entry->len
  11450. + )
  11451. +);
  11452. +
  11453. +#define DEFINE_SSAM_COMMAND_EVENT(name) \
  11454. + DEFINE_EVENT(ssam_command_class, ssam_##name, \
  11455. + TP_PROTO(const struct ssh_command *cmd, u16 len), \
  11456. + TP_ARGS(cmd, len) \
  11457. + )
  11458. +
  11459. +
  11460. +DECLARE_EVENT_CLASS(ssam_packet_class,
  11461. + TP_PROTO(const struct ssh_packet *packet),
  11462. +
  11463. + TP_ARGS(packet),
  11464. +
  11465. + TP_STRUCT__entry(
  11466. + __array(char, uid, SSAM_PTR_UID_LEN)
  11467. + __field(u8, type)
  11468. + __field(u8, priority)
  11469. + __field(u16, length)
  11470. + __field(unsigned long, state)
  11471. + __field(u16, seq)
  11472. + ),
  11473. +
  11474. + TP_fast_assign(
  11475. + ssam_trace_ptr_uid(packet, __entry->uid);
  11476. + __entry->type = packet->type;
  11477. + __entry->priority = READ_ONCE(packet->priority);
  11478. + __entry->length = packet->data_length;
  11479. + __entry->state = READ_ONCE(packet->state);
  11480. + __entry->seq = ssam_trace_get_packet_seq(packet);
  11481. + ),
  11482. +
  11483. + TP_printk("uid=%s, seq=%s, ty=%s, pri=0x%02x, len=%u, sta=%s",
  11484. + __entry->uid,
  11485. + ssam_show_packet_seq(__entry->seq),
  11486. + ssam_show_packet_type(__entry->type),
  11487. + __entry->priority,
  11488. + __entry->length,
  11489. + ssam_show_packet_state(__entry->state)
  11490. + )
  11491. +);
  11492. +
  11493. +#define DEFINE_SSAM_PACKET_EVENT(name) \
  11494. + DEFINE_EVENT(ssam_packet_class, ssam_##name, \
  11495. + TP_PROTO(const struct ssh_packet *packet), \
  11496. + TP_ARGS(packet) \
  11497. + )
  11498. +
  11499. +
  11500. +DECLARE_EVENT_CLASS(ssam_packet_status_class,
  11501. + TP_PROTO(const struct ssh_packet *packet, int status),
  11502. +
  11503. + TP_ARGS(packet, status),
  11504. +
  11505. + TP_STRUCT__entry(
  11506. + __array(char, uid, SSAM_PTR_UID_LEN)
  11507. + __field(u8, type)
  11508. + __field(u8, priority)
  11509. + __field(u16, length)
  11510. + __field(unsigned long, state)
  11511. + __field(u16, seq)
  11512. + __field(int, status)
  11513. + ),
  11514. +
  11515. + TP_fast_assign(
  11516. + ssam_trace_ptr_uid(packet, __entry->uid);
  11517. + __entry->type = packet->type;
  11518. + __entry->priority = READ_ONCE(packet->priority);
  11519. + __entry->length = packet->data_length;
  11520. + __entry->state = READ_ONCE(packet->state);
  11521. + __entry->seq = ssam_trace_get_packet_seq(packet);
  11522. + __entry->status = status;
  11523. + ),
  11524. +
  11525. + TP_printk("uid=%s, seq=%s, ty=%s, pri=0x%02x, len=%u, sta=%s, status=%d",
  11526. + __entry->uid,
  11527. + ssam_show_packet_seq(__entry->seq),
  11528. + ssam_show_packet_type(__entry->type),
  11529. + __entry->priority,
  11530. + __entry->length,
  11531. + ssam_show_packet_state(__entry->state),
  11532. + __entry->status
  11533. + )
  11534. +);
  11535. +
  11536. +#define DEFINE_SSAM_PACKET_STATUS_EVENT(name) \
  11537. + DEFINE_EVENT(ssam_packet_status_class, ssam_##name, \
  11538. + TP_PROTO(const struct ssh_packet *packet, int status), \
  11539. + TP_ARGS(packet, status) \
  11540. + )
  11541. +
  11542. +
  11543. +DECLARE_EVENT_CLASS(ssam_request_class,
  11544. + TP_PROTO(const struct ssh_request *request),
  11545. +
  11546. + TP_ARGS(request),
  11547. +
  11548. + TP_STRUCT__entry(
  11549. + __array(char, uid, SSAM_PTR_UID_LEN)
  11550. + __field(unsigned long, state)
  11551. + __field(u32, rqid)
  11552. + __field(u8, tc)
  11553. + __field(u16, cid)
  11554. + __field(u16, iid)
  11555. + ),
  11556. +
  11557. + TP_fast_assign(
  11558. + const struct ssh_packet *p = &request->packet;
  11559. +
  11560. + // use packet for UID so we can match requests to packets
  11561. + ssam_trace_ptr_uid(p, __entry->uid);
  11562. + __entry->state = READ_ONCE(request->state);
  11563. + __entry->rqid = ssam_trace_get_request_id(p);
  11564. + __entry->tc = ssam_trace_get_request_tc(p);
  11565. + __entry->cid = ssam_trace_get_command_field_u8(p, cid);
  11566. + __entry->iid = ssam_trace_get_command_field_u8(p, iid);
  11567. + ),
  11568. +
  11569. + TP_printk("uid=%s, rqid=%s, ty=%s, sta=%s, tc=%s, cid=%s, iid=%s",
  11570. + __entry->uid,
  11571. + ssam_show_request_id(__entry->rqid),
  11572. + ssam_show_request_type(__entry->state),
  11573. + ssam_show_request_state(__entry->state),
  11574. + ssam_show_ssh_tc(__entry->tc),
  11575. + ssam_show_generic_u8_field(__entry->cid),
  11576. + ssam_show_generic_u8_field(__entry->iid)
  11577. + )
  11578. +);
  11579. +
  11580. +#define DEFINE_SSAM_REQUEST_EVENT(name) \
  11581. + DEFINE_EVENT(ssam_request_class, ssam_##name, \
  11582. + TP_PROTO(const struct ssh_request *request), \
  11583. + TP_ARGS(request) \
  11584. + )
  11585. +
  11586. +
  11587. +DECLARE_EVENT_CLASS(ssam_request_status_class,
  11588. + TP_PROTO(const struct ssh_request *request, int status),
  11589. +
  11590. + TP_ARGS(request, status),
  11591. +
  11592. + TP_STRUCT__entry(
  11593. + __array(char, uid, SSAM_PTR_UID_LEN)
  11594. + __field(unsigned long, state)
  11595. + __field(u32, rqid)
  11596. + __field(u8, tc)
  11597. + __field(u16, cid)
  11598. + __field(u16, iid)
  11599. + __field(int, status)
  11600. + ),
  11601. +
  11602. + TP_fast_assign(
  11603. + const struct ssh_packet *p = &request->packet;
  11604. +
  11605. + // use packet for UID so we can match requests to packets
  11606. + ssam_trace_ptr_uid(p, __entry->uid);
  11607. + __entry->state = READ_ONCE(request->state);
  11608. + __entry->rqid = ssam_trace_get_request_id(p);
  11609. + __entry->tc = ssam_trace_get_request_tc(p);
  11610. + __entry->cid = ssam_trace_get_command_field_u8(p, cid);
  11611. + __entry->iid = ssam_trace_get_command_field_u8(p, iid);
  11612. + __entry->status = status;
  11613. + ),
  11614. +
  11615. + TP_printk("uid=%s, rqid=%s, ty=%s, sta=%s, tc=%s, cid=%s, iid=%s, status=%d",
  11616. + __entry->uid,
  11617. + ssam_show_request_id(__entry->rqid),
  11618. + ssam_show_request_type(__entry->state),
  11619. + ssam_show_request_state(__entry->state),
  11620. + ssam_show_ssh_tc(__entry->tc),
  11621. + ssam_show_generic_u8_field(__entry->cid),
  11622. + ssam_show_generic_u8_field(__entry->iid),
  11623. + __entry->status
  11624. + )
  11625. +);
  11626. +
  11627. +#define DEFINE_SSAM_REQUEST_STATUS_EVENT(name) \
  11628. + DEFINE_EVENT(ssam_request_status_class, ssam_##name, \
  11629. + TP_PROTO(const struct ssh_request *request, int status),\
  11630. + TP_ARGS(request, status) \
  11631. + )
  11632. +
  11633. +
  11634. +DECLARE_EVENT_CLASS(ssam_generic_uint_class,
  11635. + TP_PROTO(const char* property, unsigned int value),
  11636. +
  11637. + TP_ARGS(property, value),
  11638. +
  11639. + TP_STRUCT__entry(
  11640. + __string(property, property)
  11641. + __field(unsigned int, value)
  11642. + ),
  11643. +
  11644. + TP_fast_assign(
  11645. + __assign_str(property, property);
  11646. + __entry->value = value;
  11647. + ),
  11648. +
  11649. + TP_printk("%s=%u", __get_str(property), __entry->value)
  11650. +);
  11651. +
  11652. +#define DEFINE_SSAM_GENERIC_UINT_EVENT(name) \
  11653. + DEFINE_EVENT(ssam_generic_uint_class, ssam_##name, \
  11654. + TP_PROTO(const char* property, unsigned int value), \
  11655. + TP_ARGS(property, value) \
  11656. + )
  11657. +
  11658. +
  11659. +DEFINE_SSAM_FRAME_EVENT(rx_frame_received);
  11660. +DEFINE_SSAM_COMMAND_EVENT(rx_response_received);
  11661. +DEFINE_SSAM_COMMAND_EVENT(rx_event_received);
  11662. +
  11663. +DEFINE_SSAM_PACKET_EVENT(packet_release);
  11664. +DEFINE_SSAM_PACKET_EVENT(packet_submit);
  11665. +DEFINE_SSAM_PACKET_EVENT(packet_resubmit);
  11666. +DEFINE_SSAM_PACKET_EVENT(packet_timeout);
  11667. +DEFINE_SSAM_PACKET_EVENT(packet_cancel);
  11668. +DEFINE_SSAM_PACKET_STATUS_EVENT(packet_complete);
  11669. +DEFINE_SSAM_GENERIC_UINT_EVENT(ptl_timeout_reap);
  11670. +
  11671. +DEFINE_SSAM_REQUEST_EVENT(request_submit);
  11672. +DEFINE_SSAM_REQUEST_EVENT(request_timeout);
  11673. +DEFINE_SSAM_REQUEST_EVENT(request_cancel);
  11674. +DEFINE_SSAM_REQUEST_STATUS_EVENT(request_complete);
  11675. +DEFINE_SSAM_GENERIC_UINT_EVENT(rtl_timeout_reap);
  11676. +
  11677. +DEFINE_SSAM_PACKET_EVENT(ei_tx_drop_ack_packet);
  11678. +DEFINE_SSAM_PACKET_EVENT(ei_tx_drop_nak_packet);
  11679. +DEFINE_SSAM_PACKET_EVENT(ei_tx_drop_dsq_packet);
  11680. +DEFINE_SSAM_PACKET_STATUS_EVENT(ei_tx_fail_write);
  11681. +DEFINE_SSAM_PACKET_EVENT(ei_tx_corrupt_data);
  11682. +DEFINE_SSAM_GENERIC_UINT_EVENT(ei_rx_corrupt_syn);
  11683. +DEFINE_SSAM_FRAME_EVENT(ei_rx_corrupt_data);
  11684. +DEFINE_SSAM_REQUEST_EVENT(ei_rx_drop_response);
  11685. +
  11686. +#endif /* _SURFACE_SAM_SSH_TRACE_H */
  11687. +
  11688. +/* This part must be outside protection */
  11689. +#undef TRACE_INCLUDE_PATH
  11690. +#undef TRACE_INCLUDE_FILE
  11691. +
  11692. +#define TRACE_INCLUDE_PATH .
  11693. +#define TRACE_INCLUDE_FILE surface_sam_ssh_trace
  11694. +
  11695. +#include <trace/define_trace.h>
  11696. diff --git a/drivers/platform/x86/surface_sam/surface_sam_vhf.c b/drivers/platform/x86/surface_sam/surface_sam_vhf.c
  11697. new file mode 100644
  11698. index 0000000000000..984035c55d63a
  11699. --- /dev/null
  11700. +++ b/drivers/platform/x86/surface_sam/surface_sam_vhf.c
  11701. @@ -0,0 +1,261 @@
  11702. +// SPDX-License-Identifier: GPL-2.0-or-later
  11703. +/*
  11704. + * Virtual HID Framework (VHF) driver for input events via SAM.
  11705. + * Used for keyboard input events on the Surface Laptops.
  11706. + */
  11707. +
  11708. +#include <linux/acpi.h>
  11709. +#include <linux/hid.h>
  11710. +#include <linux/input.h>
  11711. +#include <linux/platform_device.h>
  11712. +#include <linux/types.h>
  11713. +
  11714. +#include "surface_sam_ssh.h"
  11715. +
  11716. +
  11717. +#define USB_VENDOR_ID_MICROSOFT 0x045e
  11718. +#define USB_DEVICE_ID_MS_VHF 0xf001
  11719. +
  11720. +#define VHF_INPUT_NAME "Microsoft Virtual HID Framework Device"
  11721. +
  11722. +
  11723. +struct vhf_drvdata {
  11724. + struct platform_device *dev;
  11725. + struct hid_device *hid;
  11726. + struct ssam_event_notifier notif;
  11727. +};
  11728. +
  11729. +
  11730. +/*
  11731. + * These report descriptors have been extracted from a Surface Book 2.
  11732. + * They seems to be similar enough to be usable on the Surface Laptop.
  11733. + */
  11734. +static const u8 vhf_hid_desc[] = {
  11735. + // keyboard descriptor (event command ID 0x03)
  11736. + 0x05, 0x01, /* Usage Page (Desktop), */
  11737. + 0x09, 0x06, /* Usage (Keyboard), */
  11738. + 0xA1, 0x01, /* Collection (Application), */
  11739. + 0x85, 0x01, /* Report ID (1), */
  11740. + 0x15, 0x00, /* Logical Minimum (0), */
  11741. + 0x25, 0x01, /* Logical Maximum (1), */
  11742. + 0x75, 0x01, /* Report Size (1), */
  11743. + 0x95, 0x08, /* Report Count (8), */
  11744. + 0x05, 0x07, /* Usage Page (Keyboard), */
  11745. + 0x19, 0xE0, /* Usage Minimum (KB Leftcontrol), */
  11746. + 0x29, 0xE7, /* Usage Maximum (KB Right GUI), */
  11747. + 0x81, 0x02, /* Input (Variable), */
  11748. + 0x75, 0x08, /* Report Size (8), */
  11749. + 0x95, 0x0A, /* Report Count (10), */
  11750. + 0x19, 0x00, /* Usage Minimum (None), */
  11751. + 0x29, 0x91, /* Usage Maximum (KB LANG2), */
  11752. + 0x26, 0xFF, 0x00, /* Logical Maximum (255), */
  11753. + 0x81, 0x00, /* Input, */
  11754. + 0x05, 0x0C, /* Usage Page (Consumer), */
  11755. + 0x0A, 0xC0, 0x02, /* Usage (02C0h), */
  11756. + 0xA1, 0x02, /* Collection (Logical), */
  11757. + 0x1A, 0xC1, 0x02, /* Usage Minimum (02C1h), */
  11758. + 0x2A, 0xC6, 0x02, /* Usage Maximum (02C6h), */
  11759. + 0x95, 0x06, /* Report Count (6), */
  11760. + 0xB1, 0x03, /* Feature (Constant, Variable), */
  11761. + 0xC0, /* End Collection, */
  11762. + 0x05, 0x08, /* Usage Page (LED), */
  11763. + 0x19, 0x01, /* Usage Minimum (01h), */
  11764. + 0x29, 0x03, /* Usage Maximum (03h), */
  11765. + 0x75, 0x01, /* Report Size (1), */
  11766. + 0x95, 0x03, /* Report Count (3), */
  11767. + 0x25, 0x01, /* Logical Maximum (1), */
  11768. + 0x91, 0x02, /* Output (Variable), */
  11769. + 0x95, 0x05, /* Report Count (5), */
  11770. + 0x91, 0x01, /* Output (Constant), */
  11771. + 0xC0, /* End Collection, */
  11772. +
  11773. + // media key descriptor (event command ID 0x04)
  11774. + 0x05, 0x0C, /* Usage Page (Consumer), */
  11775. + 0x09, 0x01, /* Usage (Consumer Control), */
  11776. + 0xA1, 0x01, /* Collection (Application), */
  11777. + 0x85, 0x03, /* Report ID (3), */
  11778. + 0x75, 0x10, /* Report Size (16), */
  11779. + 0x15, 0x00, /* Logical Minimum (0), */
  11780. + 0x26, 0xFF, 0x03, /* Logical Maximum (1023), */
  11781. + 0x19, 0x00, /* Usage Minimum (00h), */
  11782. + 0x2A, 0xFF, 0x03, /* Usage Maximum (03FFh), */
  11783. + 0x81, 0x00, /* Input, */
  11784. + 0xC0, /* End Collection, */
  11785. +};
  11786. +
  11787. +
  11788. +static int vhf_hid_start(struct hid_device *hid)
  11789. +{
  11790. + hid_dbg(hid, "%s\n", __func__);
  11791. + return 0;
  11792. +}
  11793. +
  11794. +static void vhf_hid_stop(struct hid_device *hid)
  11795. +{
  11796. + hid_dbg(hid, "%s\n", __func__);
  11797. +}
  11798. +
  11799. +static int vhf_hid_open(struct hid_device *hid)
  11800. +{
  11801. + hid_dbg(hid, "%s\n", __func__);
  11802. + return 0;
  11803. +}
  11804. +
  11805. +static void vhf_hid_close(struct hid_device *hid)
  11806. +{
  11807. + hid_dbg(hid, "%s\n", __func__);
  11808. +}
  11809. +
  11810. +static int vhf_hid_parse(struct hid_device *hid)
  11811. +{
  11812. + return hid_parse_report(hid, (u8 *)vhf_hid_desc, ARRAY_SIZE(vhf_hid_desc));
  11813. +}
  11814. +
  11815. +static int vhf_hid_raw_request(struct hid_device *hid, unsigned char reportnum,
  11816. + u8 *buf, size_t len, unsigned char rtype,
  11817. + int reqtype)
  11818. +{
  11819. + hid_dbg(hid, "%s\n", __func__);
  11820. + return 0;
  11821. +}
  11822. +
  11823. +static int vhf_hid_output_report(struct hid_device *hid, u8 *buf, size_t len)
  11824. +{
  11825. + hid_dbg(hid, "%s\n", __func__);
  11826. + print_hex_dump_debug("report:", DUMP_PREFIX_OFFSET, 16, 1, buf, len, false);
  11827. +
  11828. + return len;
  11829. +}
  11830. +
  11831. +static struct hid_ll_driver vhf_hid_ll_driver = {
  11832. + .start = vhf_hid_start,
  11833. + .stop = vhf_hid_stop,
  11834. + .open = vhf_hid_open,
  11835. + .close = vhf_hid_close,
  11836. + .parse = vhf_hid_parse,
  11837. + .raw_request = vhf_hid_raw_request,
  11838. + .output_report = vhf_hid_output_report,
  11839. +};
  11840. +
  11841. +
  11842. +static struct hid_device *vhf_create_hid_device(struct platform_device *pdev)
  11843. +{
  11844. + struct hid_device *hid;
  11845. +
  11846. + hid = hid_allocate_device();
  11847. + if (IS_ERR(hid))
  11848. + return hid;
  11849. +
  11850. + hid->dev.parent = &pdev->dev;
  11851. +
  11852. + hid->bus = BUS_VIRTUAL;
  11853. + hid->vendor = USB_VENDOR_ID_MICROSOFT;
  11854. + hid->product = USB_DEVICE_ID_MS_VHF;
  11855. +
  11856. + hid->ll_driver = &vhf_hid_ll_driver;
  11857. +
  11858. + sprintf(hid->name, "%s", VHF_INPUT_NAME);
  11859. +
  11860. + return hid;
  11861. +}
  11862. +
  11863. +static u32 vhf_event_handler(struct ssam_notifier_block *nb, const struct ssam_event *event)
  11864. +{
  11865. + struct vhf_drvdata *drvdata = container_of(nb, struct vhf_drvdata, notif.base);
  11866. + int status;
  11867. +
  11868. + if (event->target_category != 0x08)
  11869. + return 0;
  11870. +
  11871. + if (event->command_id == 0x03 || event->command_id == 0x04) {
  11872. + status = hid_input_report(drvdata->hid, HID_INPUT_REPORT, (u8 *)&event->data[0], event->length, 1);
  11873. + return ssam_notifier_from_errno(status) | SSAM_NOTIF_HANDLED;
  11874. + }
  11875. +
  11876. + return 0;
  11877. +}
  11878. +
  11879. +static int surface_sam_vhf_probe(struct platform_device *pdev)
  11880. +{
  11881. + struct vhf_drvdata *drvdata;
  11882. + struct hid_device *hid;
  11883. + int status;
  11884. +
  11885. + // add device link to EC
  11886. + status = surface_sam_ssh_consumer_register(&pdev->dev);
  11887. + if (status)
  11888. + return status == -ENXIO ? -EPROBE_DEFER : status;
  11889. +
  11890. + drvdata = kzalloc(sizeof(struct vhf_drvdata), GFP_KERNEL);
  11891. + if (!drvdata)
  11892. + return -ENOMEM;
  11893. +
  11894. + hid = vhf_create_hid_device(pdev);
  11895. + if (IS_ERR(hid)) {
  11896. + status = PTR_ERR(hid);
  11897. + goto err_probe_hid;
  11898. + }
  11899. +
  11900. + status = hid_add_device(hid);
  11901. + if (status)
  11902. + goto err_add_hid;
  11903. +
  11904. + drvdata->dev = pdev;
  11905. + drvdata->hid = hid;
  11906. +
  11907. + drvdata->notif.base.priority = 1;
  11908. + drvdata->notif.base.fn = vhf_event_handler;
  11909. + drvdata->notif.event.reg = SSAM_EVENT_REGISTRY_SAM;
  11910. + drvdata->notif.event.id.target_category = SSAM_SSH_TC_KBD;
  11911. + drvdata->notif.event.id.instance = 0;
  11912. + drvdata->notif.event.flags = 0;
  11913. +
  11914. + platform_set_drvdata(pdev, drvdata);
  11915. +
  11916. + status = surface_sam_ssh_notifier_register(&drvdata->notif);
  11917. + if (status)
  11918. + goto err_add_hid;
  11919. +
  11920. + return 0;
  11921. +
  11922. +err_add_hid:
  11923. + hid_destroy_device(hid);
  11924. + platform_set_drvdata(pdev, NULL);
  11925. +err_probe_hid:
  11926. + kfree(drvdata);
  11927. + return status;
  11928. +}
  11929. +
  11930. +static int surface_sam_vhf_remove(struct platform_device *pdev)
  11931. +{
  11932. + struct vhf_drvdata *drvdata = platform_get_drvdata(pdev);
  11933. +
  11934. + surface_sam_ssh_notifier_unregister(&drvdata->notif);
  11935. + hid_destroy_device(drvdata->hid);
  11936. + kfree(drvdata);
  11937. +
  11938. + platform_set_drvdata(pdev, NULL);
  11939. + return 0;
  11940. +}
  11941. +
  11942. +
  11943. +static const struct acpi_device_id surface_sam_vhf_match[] = {
  11944. + { "MSHW0096" },
  11945. + { },
  11946. +};
  11947. +MODULE_DEVICE_TABLE(acpi, surface_sam_vhf_match);
  11948. +
  11949. +static struct platform_driver surface_sam_vhf = {
  11950. + .probe = surface_sam_vhf_probe,
  11951. + .remove = surface_sam_vhf_remove,
  11952. + .driver = {
  11953. + .name = "surface_sam_vhf",
  11954. + .acpi_match_table = surface_sam_vhf_match,
  11955. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  11956. + },
  11957. +};
  11958. +module_platform_driver(surface_sam_vhf);
  11959. +
  11960. +MODULE_AUTHOR("Maximilian Luz <luzmaximilian@gmail.com>");
  11961. +MODULE_DESCRIPTION("Virtual HID Framework Driver for 5th Generation Surface Devices");
  11962. +MODULE_LICENSE("GPL");
  11963. diff --git a/drivers/tty/serdev/core.c b/drivers/tty/serdev/core.c
  11964. index a9719858c950b..ce5309d002805 100644
  11965. --- a/drivers/tty/serdev/core.c
  11966. +++ b/drivers/tty/serdev/core.c
  11967. @@ -552,16 +552,97 @@ static int of_serdev_register_devices(struct serdev_controller *ctrl)
  11968. }
  11969. #ifdef CONFIG_ACPI
  11970. +
  11971. +#define SERDEV_ACPI_MAX_SCAN_DEPTH 32
  11972. +
  11973. +struct acpi_serdev_lookup {
  11974. + acpi_handle device_handle;
  11975. + acpi_handle controller_handle;
  11976. + int n;
  11977. + int index;
  11978. +};
  11979. +
  11980. +static int acpi_serdev_parse_resource(struct acpi_resource *ares, void *data)
  11981. +{
  11982. + struct acpi_serdev_lookup *lookup = data;
  11983. + struct acpi_resource_uart_serialbus *sb;
  11984. + acpi_status status;
  11985. +
  11986. + if (ares->type != ACPI_RESOURCE_TYPE_SERIAL_BUS)
  11987. + return 1;
  11988. +
  11989. + if (ares->data.common_serial_bus.type != ACPI_RESOURCE_SERIAL_TYPE_UART)
  11990. + return 1;
  11991. +
  11992. + if (lookup->index != -1 && lookup->n++ != lookup->index)
  11993. + return 1;
  11994. +
  11995. + sb = &ares->data.uart_serial_bus;
  11996. +
  11997. + status = acpi_get_handle(lookup->device_handle,
  11998. + sb->resource_source.string_ptr,
  11999. + &lookup->controller_handle);
  12000. + if (ACPI_FAILURE(status))
  12001. + return 1;
  12002. +
  12003. + /*
  12004. + * NOTE: Ideally, we would also want to retreive other properties here,
  12005. + * once setting them before opening the device is supported by serdev.
  12006. + */
  12007. +
  12008. + return 1;
  12009. +}
  12010. +
  12011. +static int acpi_serdev_do_lookup(struct acpi_device *adev,
  12012. + struct acpi_serdev_lookup *lookup)
  12013. +{
  12014. + struct list_head resource_list;
  12015. + int ret;
  12016. +
  12017. + lookup->device_handle = acpi_device_handle(adev);
  12018. + lookup->controller_handle = NULL;
  12019. + lookup->n = 0;
  12020. +
  12021. + INIT_LIST_HEAD(&resource_list);
  12022. + ret = acpi_dev_get_resources(adev, &resource_list,
  12023. + acpi_serdev_parse_resource, lookup);
  12024. + acpi_dev_free_resource_list(&resource_list);
  12025. +
  12026. + if (ret < 0)
  12027. + return -EINVAL;
  12028. +
  12029. + return 0;
  12030. +}
  12031. +
  12032. +static int acpi_serdev_check_resources(struct serdev_controller *ctrl,
  12033. + struct acpi_device *adev)
  12034. +{
  12035. + struct acpi_serdev_lookup lookup;
  12036. + int ret;
  12037. +
  12038. + if (acpi_bus_get_status(adev) || !adev->status.present)
  12039. + return -EINVAL;
  12040. +
  12041. + /* Look for UARTSerialBusV2 resource */
  12042. + lookup.index = -1; // we only care for the last device
  12043. +
  12044. + ret = acpi_serdev_do_lookup(adev, &lookup);
  12045. + if (ret)
  12046. + return ret;
  12047. +
  12048. + /* Make sure controller and ResourceSource handle match */
  12049. + if (ACPI_HANDLE(ctrl->dev.parent) != lookup.controller_handle)
  12050. + return -ENODEV;
  12051. +
  12052. + return 0;
  12053. +}
  12054. +
  12055. static acpi_status acpi_serdev_register_device(struct serdev_controller *ctrl,
  12056. - struct acpi_device *adev)
  12057. + struct acpi_device *adev)
  12058. {
  12059. - struct serdev_device *serdev = NULL;
  12060. + struct serdev_device *serdev;
  12061. int err;
  12062. - if (acpi_bus_get_status(adev) || !adev->status.present ||
  12063. - acpi_device_enumerated(adev))
  12064. - return AE_OK;
  12065. -
  12066. serdev = serdev_device_alloc(ctrl);
  12067. if (!serdev) {
  12068. dev_err(&ctrl->dev, "failed to allocate serdev device for %s\n",
  12069. @@ -589,7 +670,7 @@ static const struct acpi_device_id serdev_acpi_devices_blacklist[] = {
  12070. };
  12071. static acpi_status acpi_serdev_add_device(acpi_handle handle, u32 level,
  12072. - void *data, void **return_value)
  12073. + void *data, void **return_value)
  12074. {
  12075. struct serdev_controller *ctrl = data;
  12076. struct acpi_device *adev;
  12077. @@ -597,26 +678,32 @@ static acpi_status acpi_serdev_add_device(acpi_handle handle, u32 level,
  12078. if (acpi_bus_get_device(handle, &adev))
  12079. return AE_OK;
  12080. + if (acpi_device_enumerated(adev))
  12081. + return AE_OK;
  12082. +
  12083. /* Skip if black listed */
  12084. if (!acpi_match_device_ids(adev, serdev_acpi_devices_blacklist))
  12085. return AE_OK;
  12086. + if (acpi_serdev_check_resources(ctrl, adev))
  12087. + return AE_OK;
  12088. +
  12089. return acpi_serdev_register_device(ctrl, adev);
  12090. }
  12091. +
  12092. static int acpi_serdev_register_devices(struct serdev_controller *ctrl)
  12093. {
  12094. acpi_status status;
  12095. - acpi_handle handle;
  12096. - handle = ACPI_HANDLE(ctrl->dev.parent);
  12097. - if (!handle)
  12098. + if (!has_acpi_companion(ctrl->dev.parent))
  12099. return -ENODEV;
  12100. - status = acpi_walk_namespace(ACPI_TYPE_DEVICE, handle, 1,
  12101. + status = acpi_walk_namespace(ACPI_TYPE_DEVICE, ACPI_ROOT_OBJECT,
  12102. + SERDEV_ACPI_MAX_SCAN_DEPTH,
  12103. acpi_serdev_add_device, NULL, ctrl, NULL);
  12104. if (ACPI_FAILURE(status))
  12105. - dev_dbg(&ctrl->dev, "failed to enumerate serdev slaves\n");
  12106. + dev_warn(&ctrl->dev, "failed to enumerate serdev slaves\n");
  12107. if (!ctrl->serdev)
  12108. return -ENODEV;
  12109. --
  12110. 2.27.0