0003-surface-sam.patch 318 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915
  1. From abe232973324da458501e918a62ccf15c437e54a Mon Sep 17 00:00:00 2001
  2. From: Maximilian Luz <luzmaximilian@gmail.com>
  3. Date: Fri, 6 Dec 2019 11:56:12 +0100
  4. Subject: [PATCH 3/5] surface-sam
  5. ---
  6. drivers/platform/x86/Kconfig | 2 +
  7. drivers/platform/x86/Makefile | 1 +
  8. drivers/platform/x86/surface_sam/Kconfig | 176 +
  9. drivers/platform/x86/surface_sam/Makefile | 15 +
  10. .../x86/surface_sam/surface_sam_dtx.c | 590 ++
  11. .../x86/surface_sam/surface_sam_hps.c | 1297 +++++
  12. .../x86/surface_sam/surface_sam_san.c | 913 +++
  13. .../x86/surface_sam/surface_sam_san.h | 30 +
  14. .../x86/surface_sam/surface_sam_sid.c | 262 +
  15. .../x86/surface_sam/surface_sam_sid_gpelid.c | 232 +
  16. .../surface_sam/surface_sam_sid_perfmode.c | 216 +
  17. .../x86/surface_sam/surface_sam_sid_power.c | 1154 ++++
  18. .../x86/surface_sam/surface_sam_sid_power.h | 15 +
  19. .../x86/surface_sam/surface_sam_sid_vhf.c | 432 ++
  20. .../x86/surface_sam/surface_sam_sid_vhf.h | 13 +
  21. .../x86/surface_sam/surface_sam_ssh.c | 5114 +++++++++++++++++
  22. .../x86/surface_sam/surface_sam_ssh.h | 488 ++
  23. .../x86/surface_sam/surface_sam_ssh_trace.h | 536 ++
  24. .../x86/surface_sam/surface_sam_vhf.c | 261 +
  25. 19 files changed, 11747 insertions(+)
  26. create mode 100644 drivers/platform/x86/surface_sam/Kconfig
  27. create mode 100644 drivers/platform/x86/surface_sam/Makefile
  28. create mode 100644 drivers/platform/x86/surface_sam/surface_sam_dtx.c
  29. create mode 100644 drivers/platform/x86/surface_sam/surface_sam_hps.c
  30. create mode 100644 drivers/platform/x86/surface_sam/surface_sam_san.c
  31. create mode 100644 drivers/platform/x86/surface_sam/surface_sam_san.h
  32. create mode 100644 drivers/platform/x86/surface_sam/surface_sam_sid.c
  33. create mode 100644 drivers/platform/x86/surface_sam/surface_sam_sid_gpelid.c
  34. create mode 100644 drivers/platform/x86/surface_sam/surface_sam_sid_perfmode.c
  35. create mode 100644 drivers/platform/x86/surface_sam/surface_sam_sid_power.c
  36. create mode 100644 drivers/platform/x86/surface_sam/surface_sam_sid_power.h
  37. create mode 100644 drivers/platform/x86/surface_sam/surface_sam_sid_vhf.c
  38. create mode 100644 drivers/platform/x86/surface_sam/surface_sam_sid_vhf.h
  39. create mode 100644 drivers/platform/x86/surface_sam/surface_sam_ssh.c
  40. create mode 100644 drivers/platform/x86/surface_sam/surface_sam_ssh.h
  41. create mode 100644 drivers/platform/x86/surface_sam/surface_sam_ssh_trace.h
  42. create mode 100644 drivers/platform/x86/surface_sam/surface_sam_vhf.c
  43. diff --git a/drivers/platform/x86/Kconfig b/drivers/platform/x86/Kconfig
  44. index 0ad7ad8cf8e17..5d1766294eca9 100644
  45. --- a/drivers/platform/x86/Kconfig
  46. +++ b/drivers/platform/x86/Kconfig
  47. @@ -1350,6 +1350,8 @@ config INTEL_SCU_IPC
  48. some embedded Intel x86 platforms. This is not needed for PC-type
  49. machines.
  50. +source "drivers/platform/x86/surface_sam/Kconfig"
  51. +
  52. config INTEL_SCU_IPC_UTIL
  53. tristate "Intel SCU IPC utility driver"
  54. depends on INTEL_SCU_IPC
  55. diff --git a/drivers/platform/x86/Makefile b/drivers/platform/x86/Makefile
  56. index 53408d9658740..b3f4305f73c56 100644
  57. --- a/drivers/platform/x86/Makefile
  58. +++ b/drivers/platform/x86/Makefile
  59. @@ -146,3 +146,4 @@ obj-$(CONFIG_INTEL_TELEMETRY) += intel_telemetry_core.o \
  60. intel_telemetry_pltdrv.o \
  61. intel_telemetry_debugfs.o
  62. obj-$(CONFIG_PMC_ATOM) += pmc_atom.o
  63. +obj-$(CONFIG_SURFACE_SAM) += surface_sam/
  64. diff --git a/drivers/platform/x86/surface_sam/Kconfig b/drivers/platform/x86/surface_sam/Kconfig
  65. new file mode 100644
  66. index 0000000000000..7781c5cd932c0
  67. --- /dev/null
  68. +++ b/drivers/platform/x86/surface_sam/Kconfig
  69. @@ -0,0 +1,176 @@
  70. +menuconfig SURFACE_SAM
  71. + depends on ACPI
  72. + tristate "Microsoft Surface/System Aggregator Module and Platform Drivers"
  73. + help
  74. + Drivers for the Surface/System Aggregator Module (SAM) of Microsoft
  75. + Surface devices.
  76. +
  77. + SAM is an embedded controller that provides access to various
  78. + functionalities on these devices, including battery status, keyboard
  79. + events (on the Laptops) and many more.
  80. +
  81. + Say M/Y here if you have a Microsoft Surface device with a SAM device
  82. + (i.e. 5th generation or later).
  83. +
  84. +config SURFACE_SAM_SSH
  85. + tristate "Surface Serial Hub Driver"
  86. + depends on SURFACE_SAM
  87. + depends on SERIAL_DEV_CTRL_TTYPORT
  88. + select CRC_CCITT
  89. + default m
  90. + help
  91. + Surface Serial Hub driver for 5th generation (or later) Microsoft
  92. + Surface devices.
  93. +
  94. + This is the base driver for the embedded serial controller found on
  95. + 5th generation (and later) Microsoft Surface devices (e.g. Book 2,
  96. + Laptop, Laptop 2, Pro 2017, Pro 6, ...). This driver itself only
  97. + provides access to the embedded controller (SAM) and subsequent
  98. + drivers are required for the respective functionalities.
  99. +
  100. + If you have a 5th generation (or later) Microsoft Surface device, say
  101. + Y or M here.
  102. +
  103. +config SURFACE_SAM_SSH_DEBUG_DEVICE
  104. + bool "Surface Serial Hub Debug Device"
  105. + depends on SURFACE_SAM_SSH
  106. + depends on SYSFS
  107. + default n
  108. + help
  109. + Debug device for direct communication with the embedded controller
  110. + found on 5th generation (and later) Microsoft Surface devices (e.g.
  111. + Book 2, Laptop, Laptop 2, Pro 2017, Pro 6, ...) via sysfs.
  112. +
  113. + If you are not sure, say N here.
  114. +
  115. +config SURFACE_SAM_SSH_ERROR_INJECTION
  116. + bool "Surface Serial Hub Error Injection Capabilities"
  117. + depends on SURFACE_SAM_SSH
  118. + depends on FUNCTION_ERROR_INJECTION
  119. + default n
  120. + help
  121. + Enable error injection capabilities for the Surface Serial Hub.
  122. + This is used to debug the driver, specifically the communication
  123. + interface. It is not required for normal use.
  124. +
  125. + If you are not sure, say N here.
  126. +
  127. +config SURFACE_SAM_SAN
  128. + tristate "Surface ACPI Notify Driver"
  129. + depends on SURFACE_SAM_SSH
  130. + default m
  131. + help
  132. + Surface ACPI Notify driver for 5th generation (or later) Microsoft
  133. + Surface devices.
  134. +
  135. + This driver enables basic ACPI events and requests, such as battery
  136. + status requests/events, thermal events, lid status, and possibly more,
  137. + which would otherwise not work on these devices.
  138. +
  139. + If you are not sure, say M here.
  140. +
  141. +config SURFACE_SAM_VHF
  142. + tristate "Surface Virtual HID Framework Driver"
  143. + depends on SURFACE_SAM_SSH
  144. + depends on HID
  145. + default m
  146. + help
  147. + Surface Virtual HID Framework driver for 5th generation (or later)
  148. + Microsoft Surface devices.
  149. +
  150. + This driver provides support for the Microsoft Virtual HID framework,
  151. + which is required for keyboard support on the Surface Laptop 1 and 2.
  152. +
  153. + If you are not sure, say M here.
  154. +
  155. +config SURFACE_SAM_DTX
  156. + tristate "Surface Detachment System (DTX) Driver"
  157. + depends on SURFACE_SAM_SSH
  158. + depends on INPUT
  159. + default m
  160. + help
  161. + Surface Detachment System (DTX) driver for the Microsoft Surface Book
  162. + 2. This driver provides support for proper detachment handling in
  163. + user-space, status-events relating to the base and support for
  164. + the safe-guard keeping the base attached when the discrete GPU
  165. + contained in it is running via the special /dev/surface-dtx device.
  166. +
  167. + Also provides a standard input device to provide SW_TABLET_MODE events
  168. + upon device mode change.
  169. +
  170. + If you are not sure, say M here.
  171. +
  172. +config SURFACE_SAM_HPS
  173. + tristate "Surface dGPU Hot-Plug System (dGPU-HPS) Driver"
  174. + depends on SURFACE_SAM_SSH
  175. + depends on SURFACE_SAM_SAN
  176. + depends on GPIO_SYSFS
  177. + default m
  178. + help
  179. + Driver to properly handle hot-plugging and explicit power-on/power-off
  180. + of the discrete GPU (dGPU) on the Surface Book 2 and 3.
  181. +
  182. + If you are not sure, say M here.
  183. +
  184. +config SURFACE_SAM_SID
  185. + tristate "Surface Platform Integration Driver"
  186. + depends on SURFACE_SAM_SSH
  187. + default m
  188. + help
  189. + Surface Platform Integration Driver for the Microsoft Surface Devices.
  190. + This driver loads various model-specific sub-drivers, including
  191. + battery and keyboard support on 7th generation Surface devices, proper
  192. + lid setup to enable device wakeup when the lid is opened on multiple
  193. + models, as well as performance mode setting support on the Surface
  194. + Book 2.
  195. +
  196. + If you are not sure, say M here.
  197. +
  198. +config SURFACE_SAM_SID_GPELID
  199. + tristate "Surface Lid Wakeup Driver"
  200. + depends on SURFACE_SAM_SID
  201. + default m
  202. + help
  203. + Driver to set up device wake-up via lid on Intel-based Microsoft
  204. + Surface devices. These devices do not wake up from sleep as their GPE
  205. + interrupt is not configured automatically. This driver solves that
  206. + problem.
  207. +
  208. + If you are not sure, say M here.
  209. +
  210. +config SURFACE_SAM_SID_PERFMODE
  211. + tristate "Surface Performance Mode Driver"
  212. + depends on SURFACE_SAM_SID
  213. + depends on SYSFS
  214. + default m
  215. + help
  216. + This driver provides support for setting performance-modes on Surface
  217. + devices via the perf_mode sysfs attribute. Currently only supports the
  218. + Surface Book 2. Performance-modes directly influence the fan-profile
  219. + of the device, allowing to choose between higher performance or
  220. + quieter operation.
  221. +
  222. + If you are not sure, say M here.
  223. +
  224. +config SURFACE_SAM_SID_VHF
  225. + tristate "Surface SAM HID Driver"
  226. + depends on SURFACE_SAM_SID
  227. + depends on HID
  228. + default m
  229. + help
  230. + This driver provides support for HID devices connected via the Surface
  231. + SAM embedded controller. It provides support for keyboard and touchpad
  232. + on the Surface Laptop 3 models.
  233. +
  234. + If you are not sure, say M here.
  235. +
  236. +config SURFACE_SAM_SID_POWER
  237. + tristate "Surface SAM Battery/AC Driver"
  238. + depends on SURFACE_SAM_SID
  239. + select POWER_SUPPLY
  240. + default m
  241. + help
  242. + This driver provides support for the battery and AC on 7th generation
  243. + Surface devices.
  244. +
  245. + If you are not sure, say M here.
  246. diff --git a/drivers/platform/x86/surface_sam/Makefile b/drivers/platform/x86/surface_sam/Makefile
  247. new file mode 100644
  248. index 0000000000000..1a5c1260639dc
  249. --- /dev/null
  250. +++ b/drivers/platform/x86/surface_sam/Makefile
  251. @@ -0,0 +1,15 @@
  252. +# SPDX-License-Identifier: GPL-2.0-or-later
  253. +
  254. +# For include/trace/define_trace.h to include surface_sam_ssh_trace.h
  255. +CFLAGS_surface_sam_ssh.o = -I$(src)
  256. +
  257. +obj-$(CONFIG_SURFACE_SAM_SSH) += surface_sam_ssh.o
  258. +obj-$(CONFIG_SURFACE_SAM_SAN) += surface_sam_san.o
  259. +obj-$(CONFIG_SURFACE_SAM_DTX) += surface_sam_dtx.o
  260. +obj-$(CONFIG_SURFACE_SAM_HPS) += surface_sam_hps.o
  261. +obj-$(CONFIG_SURFACE_SAM_VHF) += surface_sam_vhf.o
  262. +obj-$(CONFIG_SURFACE_SAM_SID) += surface_sam_sid.o
  263. +obj-$(CONFIG_SURFACE_SAM_SID_GPELID) += surface_sam_sid_gpelid.o
  264. +obj-$(CONFIG_SURFACE_SAM_SID_PERFMODE) += surface_sam_sid_perfmode.o
  265. +obj-$(CONFIG_SURFACE_SAM_SID_POWER) += surface_sam_sid_power.o
  266. +obj-$(CONFIG_SURFACE_SAM_SID_VHF) += surface_sam_sid_vhf.o
  267. diff --git a/drivers/platform/x86/surface_sam/surface_sam_dtx.c b/drivers/platform/x86/surface_sam/surface_sam_dtx.c
  268. new file mode 100644
  269. index 0000000000000..88dba7bced3a4
  270. --- /dev/null
  271. +++ b/drivers/platform/x86/surface_sam/surface_sam_dtx.c
  272. @@ -0,0 +1,590 @@
  273. +// SPDX-License-Identifier: GPL-2.0-or-later
  274. +/*
  275. + * Detachment system (DTX) driver for Microsoft Surface Book 2.
  276. + */
  277. +
  278. +#include <linux/acpi.h>
  279. +#include <linux/delay.h>
  280. +#include <linux/fs.h>
  281. +#include <linux/input.h>
  282. +#include <linux/ioctl.h>
  283. +#include <linux/kernel.h>
  284. +#include <linux/miscdevice.h>
  285. +#include <linux/module.h>
  286. +#include <linux/poll.h>
  287. +#include <linux/rculist.h>
  288. +#include <linux/slab.h>
  289. +#include <linux/spinlock.h>
  290. +#include <linux/platform_device.h>
  291. +
  292. +#include "surface_sam_ssh.h"
  293. +
  294. +
  295. +#define USB_VENDOR_ID_MICROSOFT 0x045e
  296. +#define USB_DEVICE_ID_MS_SURFACE_BASE_2_INTEGRATION 0x0922
  297. +
  298. +// name copied from MS device manager
  299. +#define DTX_INPUT_NAME "Microsoft Surface Base 2 Integration Device"
  300. +
  301. +
  302. +#define DTX_CMD_LATCH_LOCK _IO(0x11, 0x01)
  303. +#define DTX_CMD_LATCH_UNLOCK _IO(0x11, 0x02)
  304. +#define DTX_CMD_LATCH_REQUEST _IO(0x11, 0x03)
  305. +#define DTX_CMD_LATCH_OPEN _IO(0x11, 0x04)
  306. +#define DTX_CMD_GET_OPMODE _IOR(0x11, 0x05, int)
  307. +
  308. +#define SAM_RQST_DTX_TC 0x11
  309. +#define SAM_RQST_DTX_CID_LATCH_LOCK 0x06
  310. +#define SAM_RQST_DTX_CID_LATCH_UNLOCK 0x07
  311. +#define SAM_RQST_DTX_CID_LATCH_REQUEST 0x08
  312. +#define SAM_RQST_DTX_CID_LATCH_OPEN 0x09
  313. +#define SAM_RQST_DTX_CID_GET_OPMODE 0x0D
  314. +
  315. +#define SAM_EVENT_DTX_CID_CONNECTION 0x0c
  316. +#define SAM_EVENT_DTX_CID_BUTTON 0x0e
  317. +#define SAM_EVENT_DTX_CID_ERROR 0x0f
  318. +#define SAM_EVENT_DTX_CID_LATCH_STATUS 0x11
  319. +
  320. +#define DTX_OPMODE_TABLET 0x00
  321. +#define DTX_OPMODE_LAPTOP 0x01
  322. +#define DTX_OPMODE_STUDIO 0x02
  323. +
  324. +#define DTX_LATCH_CLOSED 0x00
  325. +#define DTX_LATCH_OPENED 0x01
  326. +
  327. +
  328. +// Warning: This must always be a power of 2!
  329. +#define DTX_CLIENT_BUF_SIZE 16
  330. +
  331. +#define DTX_CONNECT_OPMODE_DELAY 1000
  332. +
  333. +#define DTX_ERR KERN_ERR "surface_sam_dtx: "
  334. +#define DTX_WARN KERN_WARNING "surface_sam_dtx: "
  335. +
  336. +
  337. +struct surface_dtx_event {
  338. + u8 type;
  339. + u8 code;
  340. + u8 arg0;
  341. + u8 arg1;
  342. +} __packed;
  343. +
  344. +struct surface_dtx_dev {
  345. + struct ssam_event_notifier notif;
  346. + struct delayed_work opmode_work;
  347. + wait_queue_head_t waitq;
  348. + struct miscdevice mdev;
  349. + spinlock_t client_lock;
  350. + struct list_head client_list;
  351. + struct mutex mutex;
  352. + bool active;
  353. + spinlock_t input_lock;
  354. + struct input_dev *input_dev;
  355. +};
  356. +
  357. +struct surface_dtx_client {
  358. + struct list_head node;
  359. + struct surface_dtx_dev *ddev;
  360. + struct fasync_struct *fasync;
  361. + spinlock_t buffer_lock;
  362. + unsigned int buffer_head;
  363. + unsigned int buffer_tail;
  364. + struct surface_dtx_event buffer[DTX_CLIENT_BUF_SIZE];
  365. +};
  366. +
  367. +
  368. +static struct surface_dtx_dev surface_dtx_dev;
  369. +
  370. +
  371. +static int surface_sam_query_opmpde(void)
  372. +{
  373. + u8 result_buf[1];
  374. + int status;
  375. +
  376. + struct surface_sam_ssh_rqst rqst = {
  377. + .tc = SAM_RQST_DTX_TC,
  378. + .cid = SAM_RQST_DTX_CID_GET_OPMODE,
  379. + .iid = 0x00,
  380. + .chn = 0x01,
  381. + .snc = 0x01,
  382. + .cdl = 0x00,
  383. + .pld = NULL,
  384. + };
  385. +
  386. + struct surface_sam_ssh_buf result = {
  387. + .cap = 1,
  388. + .len = 0,
  389. + .data = result_buf,
  390. + };
  391. +
  392. + status = surface_sam_ssh_rqst(&rqst, &result);
  393. + if (status)
  394. + return status;
  395. +
  396. + if (result.len != 1)
  397. + return -EFAULT;
  398. +
  399. + return result.data[0];
  400. +}
  401. +
  402. +
  403. +static int dtx_cmd_simple(u8 cid)
  404. +{
  405. + struct surface_sam_ssh_rqst rqst = {
  406. + .tc = SAM_RQST_DTX_TC,
  407. + .cid = cid,
  408. + .iid = 0x00,
  409. + .chn = 0x01,
  410. + .snc = 0x00,
  411. + .cdl = 0x00,
  412. + .pld = NULL,
  413. + };
  414. +
  415. + return surface_sam_ssh_rqst(&rqst, NULL);
  416. +}
  417. +
  418. +static int dtx_cmd_get_opmode(int __user *buf)
  419. +{
  420. + int opmode;
  421. +
  422. + opmode = surface_sam_query_opmpde();
  423. + if (opmode < 0)
  424. + return opmode;
  425. +
  426. + if (put_user(opmode, buf))
  427. + return -EACCES;
  428. +
  429. + return 0;
  430. +}
  431. +
  432. +
  433. +static int surface_dtx_open(struct inode *inode, struct file *file)
  434. +{
  435. + struct surface_dtx_dev *ddev = container_of(file->private_data, struct surface_dtx_dev, mdev);
  436. + struct surface_dtx_client *client;
  437. +
  438. + // initialize client
  439. + client = kzalloc(sizeof(struct surface_dtx_client), GFP_KERNEL);
  440. + if (!client)
  441. + return -ENOMEM;
  442. +
  443. + spin_lock_init(&client->buffer_lock);
  444. + client->buffer_head = 0;
  445. + client->buffer_tail = 0;
  446. + client->ddev = ddev;
  447. +
  448. + // attach client
  449. + spin_lock(&ddev->client_lock);
  450. + list_add_tail_rcu(&client->node, &ddev->client_list);
  451. + spin_unlock(&ddev->client_lock);
  452. +
  453. + file->private_data = client;
  454. + nonseekable_open(inode, file);
  455. +
  456. + return 0;
  457. +}
  458. +
  459. +static int surface_dtx_release(struct inode *inode, struct file *file)
  460. +{
  461. + struct surface_dtx_client *client = file->private_data;
  462. +
  463. + // detach client
  464. + spin_lock(&client->ddev->client_lock);
  465. + list_del_rcu(&client->node);
  466. + spin_unlock(&client->ddev->client_lock);
  467. + synchronize_rcu();
  468. +
  469. + kfree(client);
  470. + file->private_data = NULL;
  471. +
  472. + return 0;
  473. +}
  474. +
  475. +static ssize_t surface_dtx_read(struct file *file, char __user *buf, size_t count, loff_t *offs)
  476. +{
  477. + struct surface_dtx_client *client = file->private_data;
  478. + struct surface_dtx_dev *ddev = client->ddev;
  479. + struct surface_dtx_event event;
  480. + size_t read = 0;
  481. + int status = 0;
  482. +
  483. + if (count != 0 && count < sizeof(struct surface_dtx_event))
  484. + return -EINVAL;
  485. +
  486. + if (!ddev->active)
  487. + return -ENODEV;
  488. +
  489. + // check availability
  490. + if (client->buffer_head == client->buffer_tail) {
  491. + if (file->f_flags & O_NONBLOCK)
  492. + return -EAGAIN;
  493. +
  494. + status = wait_event_interruptible(ddev->waitq,
  495. + client->buffer_head != client->buffer_tail ||
  496. + !ddev->active);
  497. + if (status)
  498. + return status;
  499. +
  500. + if (!ddev->active)
  501. + return -ENODEV;
  502. + }
  503. +
  504. + // copy events one by one
  505. + while (read + sizeof(struct surface_dtx_event) <= count) {
  506. + spin_lock_irq(&client->buffer_lock);
  507. +
  508. + if (client->buffer_head == client->buffer_tail) {
  509. + spin_unlock_irq(&client->buffer_lock);
  510. + break;
  511. + }
  512. +
  513. + // get one event
  514. + event = client->buffer[client->buffer_tail];
  515. + client->buffer_tail = (client->buffer_tail + 1) & (DTX_CLIENT_BUF_SIZE - 1);
  516. + spin_unlock_irq(&client->buffer_lock);
  517. +
  518. + // copy to userspace
  519. + if (copy_to_user(buf, &event, sizeof(struct surface_dtx_event)))
  520. + return -EFAULT;
  521. +
  522. + read += sizeof(struct surface_dtx_event);
  523. + }
  524. +
  525. + return read;
  526. +}
  527. +
  528. +static __poll_t surface_dtx_poll(struct file *file, struct poll_table_struct *pt)
  529. +{
  530. + struct surface_dtx_client *client = file->private_data;
  531. + int mask;
  532. +
  533. + poll_wait(file, &client->ddev->waitq, pt);
  534. +
  535. + if (client->ddev->active)
  536. + mask = EPOLLOUT | EPOLLWRNORM;
  537. + else
  538. + mask = EPOLLHUP | EPOLLERR;
  539. +
  540. + if (client->buffer_head != client->buffer_tail)
  541. + mask |= EPOLLIN | EPOLLRDNORM;
  542. +
  543. + return mask;
  544. +}
  545. +
  546. +static int surface_dtx_fasync(int fd, struct file *file, int on)
  547. +{
  548. + struct surface_dtx_client *client = file->private_data;
  549. +
  550. + return fasync_helper(fd, file, on, &client->fasync);
  551. +}
  552. +
  553. +static long surface_dtx_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
  554. +{
  555. + struct surface_dtx_client *client = file->private_data;
  556. + struct surface_dtx_dev *ddev = client->ddev;
  557. + int status;
  558. +
  559. + status = mutex_lock_interruptible(&ddev->mutex);
  560. + if (status)
  561. + return status;
  562. +
  563. + if (!ddev->active) {
  564. + mutex_unlock(&ddev->mutex);
  565. + return -ENODEV;
  566. + }
  567. +
  568. + switch (cmd) {
  569. + case DTX_CMD_LATCH_LOCK:
  570. + status = dtx_cmd_simple(SAM_RQST_DTX_CID_LATCH_LOCK);
  571. + break;
  572. +
  573. + case DTX_CMD_LATCH_UNLOCK:
  574. + status = dtx_cmd_simple(SAM_RQST_DTX_CID_LATCH_UNLOCK);
  575. + break;
  576. +
  577. + case DTX_CMD_LATCH_REQUEST:
  578. + status = dtx_cmd_simple(SAM_RQST_DTX_CID_LATCH_REQUEST);
  579. + break;
  580. +
  581. + case DTX_CMD_LATCH_OPEN:
  582. + status = dtx_cmd_simple(SAM_RQST_DTX_CID_LATCH_OPEN);
  583. + break;
  584. +
  585. + case DTX_CMD_GET_OPMODE:
  586. + status = dtx_cmd_get_opmode((int __user *)arg);
  587. + break;
  588. +
  589. + default:
  590. + status = -EINVAL;
  591. + break;
  592. + }
  593. +
  594. + mutex_unlock(&ddev->mutex);
  595. + return status;
  596. +}
  597. +
  598. +static const struct file_operations surface_dtx_fops = {
  599. + .owner = THIS_MODULE,
  600. + .open = surface_dtx_open,
  601. + .release = surface_dtx_release,
  602. + .read = surface_dtx_read,
  603. + .poll = surface_dtx_poll,
  604. + .fasync = surface_dtx_fasync,
  605. + .unlocked_ioctl = surface_dtx_ioctl,
  606. + .llseek = no_llseek,
  607. +};
  608. +
  609. +static struct surface_dtx_dev surface_dtx_dev = {
  610. + .mdev = {
  611. + .minor = MISC_DYNAMIC_MINOR,
  612. + .name = "surface_dtx",
  613. + .fops = &surface_dtx_fops,
  614. + },
  615. + .client_lock = __SPIN_LOCK_UNLOCKED(),
  616. + .input_lock = __SPIN_LOCK_UNLOCKED(),
  617. + .mutex = __MUTEX_INITIALIZER(surface_dtx_dev.mutex),
  618. + .active = false,
  619. +};
  620. +
  621. +
  622. +static void surface_dtx_push_event(struct surface_dtx_dev *ddev, struct surface_dtx_event *event)
  623. +{
  624. + struct surface_dtx_client *client;
  625. +
  626. + rcu_read_lock();
  627. + list_for_each_entry_rcu(client, &ddev->client_list, node) {
  628. + spin_lock(&client->buffer_lock);
  629. +
  630. + client->buffer[client->buffer_head++] = *event;
  631. + client->buffer_head &= DTX_CLIENT_BUF_SIZE - 1;
  632. +
  633. + if (unlikely(client->buffer_head == client->buffer_tail)) {
  634. + printk(DTX_WARN "event buffer overrun\n");
  635. + client->buffer_tail = (client->buffer_tail + 1) & (DTX_CLIENT_BUF_SIZE - 1);
  636. + }
  637. +
  638. + spin_unlock(&client->buffer_lock);
  639. +
  640. + kill_fasync(&client->fasync, SIGIO, POLL_IN);
  641. + }
  642. + rcu_read_unlock();
  643. +
  644. + wake_up_interruptible(&ddev->waitq);
  645. +}
  646. +
  647. +
  648. +static void surface_dtx_update_opmpde(struct surface_dtx_dev *ddev)
  649. +{
  650. + struct surface_dtx_event event;
  651. + int opmode;
  652. +
  653. + // get operation mode
  654. + opmode = surface_sam_query_opmpde();
  655. + if (opmode < 0)
  656. + printk(DTX_ERR "EC request failed with error %d\n", opmode);
  657. +
  658. + // send DTX event
  659. + event.type = 0x11;
  660. + event.code = 0x0D;
  661. + event.arg0 = opmode;
  662. + event.arg1 = 0x00;
  663. +
  664. + surface_dtx_push_event(ddev, &event);
  665. +
  666. + // send SW_TABLET_MODE event
  667. + spin_lock(&ddev->input_lock);
  668. + input_report_switch(ddev->input_dev, SW_TABLET_MODE, opmode != DTX_OPMODE_LAPTOP);
  669. + input_sync(ddev->input_dev);
  670. + spin_unlock(&ddev->input_lock);
  671. +}
  672. +
  673. +static void surface_dtx_opmode_workfn(struct work_struct *work)
  674. +{
  675. + struct surface_dtx_dev *ddev = container_of(work, struct surface_dtx_dev, opmode_work.work);
  676. +
  677. + surface_dtx_update_opmpde(ddev);
  678. +}
  679. +
  680. +static u32 surface_dtx_notification(struct ssam_notifier_block *nb, const struct ssam_event *in_event)
  681. +{
  682. + struct surface_dtx_dev *ddev = container_of(nb, struct surface_dtx_dev, notif.base);
  683. + struct surface_dtx_event event;
  684. + unsigned long delay;
  685. +
  686. + switch (in_event->command_id) {
  687. + case SAM_EVENT_DTX_CID_CONNECTION:
  688. + case SAM_EVENT_DTX_CID_BUTTON:
  689. + case SAM_EVENT_DTX_CID_ERROR:
  690. + case SAM_EVENT_DTX_CID_LATCH_STATUS:
  691. + if (in_event->length > 2) {
  692. + printk(DTX_ERR "unexpected payload size (cid: %x, len: %u)\n",
  693. + in_event->command_id, in_event->length);
  694. + return SSAM_NOTIF_HANDLED;
  695. + }
  696. +
  697. + event.type = in_event->target_category;
  698. + event.code = in_event->command_id;
  699. + event.arg0 = in_event->length >= 1 ? in_event->data[0] : 0x00;
  700. + event.arg1 = in_event->length >= 2 ? in_event->data[1] : 0x00;
  701. + surface_dtx_push_event(ddev, &event);
  702. + break;
  703. +
  704. + default:
  705. + return 0;
  706. + }
  707. +
  708. + // update device mode
  709. + if (in_event->command_id == SAM_EVENT_DTX_CID_CONNECTION) {
  710. + delay = event.arg0 ? DTX_CONNECT_OPMODE_DELAY : 0;
  711. + schedule_delayed_work(&ddev->opmode_work, delay);
  712. + }
  713. +
  714. + return SSAM_NOTIF_HANDLED;
  715. +}
  716. +
  717. +
  718. +static struct input_dev *surface_dtx_register_inputdev(struct platform_device *pdev)
  719. +{
  720. + struct input_dev *input_dev;
  721. + int status;
  722. +
  723. + input_dev = input_allocate_device();
  724. + if (!input_dev)
  725. + return ERR_PTR(-ENOMEM);
  726. +
  727. + input_dev->name = DTX_INPUT_NAME;
  728. + input_dev->dev.parent = &pdev->dev;
  729. + input_dev->id.bustype = BUS_VIRTUAL;
  730. + input_dev->id.vendor = USB_VENDOR_ID_MICROSOFT;
  731. + input_dev->id.product = USB_DEVICE_ID_MS_SURFACE_BASE_2_INTEGRATION;
  732. +
  733. + input_set_capability(input_dev, EV_SW, SW_TABLET_MODE);
  734. +
  735. + status = surface_sam_query_opmpde();
  736. + if (status < 0) {
  737. + input_free_device(input_dev);
  738. + return ERR_PTR(status);
  739. + }
  740. +
  741. + input_report_switch(input_dev, SW_TABLET_MODE, status != DTX_OPMODE_LAPTOP);
  742. +
  743. + status = input_register_device(input_dev);
  744. + if (status) {
  745. + input_unregister_device(input_dev);
  746. + return ERR_PTR(status);
  747. + }
  748. +
  749. + return input_dev;
  750. +}
  751. +
  752. +
  753. +static int surface_sam_dtx_probe(struct platform_device *pdev)
  754. +{
  755. + struct surface_dtx_dev *ddev = &surface_dtx_dev;
  756. + struct input_dev *input_dev;
  757. + int status;
  758. +
  759. + // link to ec
  760. + status = surface_sam_ssh_consumer_register(&pdev->dev);
  761. + if (status)
  762. + return status == -ENXIO ? -EPROBE_DEFER : status;
  763. +
  764. + input_dev = surface_dtx_register_inputdev(pdev);
  765. + if (IS_ERR(input_dev))
  766. + return PTR_ERR(input_dev);
  767. +
  768. + // initialize device
  769. + mutex_lock(&ddev->mutex);
  770. + if (ddev->active) {
  771. + mutex_unlock(&ddev->mutex);
  772. + status = -ENODEV;
  773. + goto err_register;
  774. + }
  775. +
  776. + INIT_DELAYED_WORK(&ddev->opmode_work, surface_dtx_opmode_workfn);
  777. + INIT_LIST_HEAD(&ddev->client_list);
  778. + init_waitqueue_head(&ddev->waitq);
  779. + ddev->active = true;
  780. + ddev->input_dev = input_dev;
  781. + mutex_unlock(&ddev->mutex);
  782. +
  783. + status = misc_register(&ddev->mdev);
  784. + if (status)
  785. + goto err_register;
  786. +
  787. + // set up events
  788. + ddev->notif.base.priority = 1;
  789. + ddev->notif.base.fn = surface_dtx_notification;
  790. + ddev->notif.event.reg = SSAM_EVENT_REGISTRY_SAM;
  791. + ddev->notif.event.id.target_category = SSAM_SSH_TC_BAS;
  792. + ddev->notif.event.id.instance = 0;
  793. + ddev->notif.event.flags = SSAM_EVENT_SEQUENCED;
  794. +
  795. + status = surface_sam_ssh_notifier_register(&ddev->notif);
  796. + if (status)
  797. + goto err_events_setup;
  798. +
  799. + return 0;
  800. +
  801. +err_events_setup:
  802. + misc_deregister(&ddev->mdev);
  803. +err_register:
  804. + input_unregister_device(ddev->input_dev);
  805. + return status;
  806. +}
  807. +
  808. +static int surface_sam_dtx_remove(struct platform_device *pdev)
  809. +{
  810. + struct surface_dtx_dev *ddev = &surface_dtx_dev;
  811. + struct surface_dtx_client *client;
  812. +
  813. + mutex_lock(&ddev->mutex);
  814. + if (!ddev->active) {
  815. + mutex_unlock(&ddev->mutex);
  816. + return 0;
  817. + }
  818. +
  819. + // mark as inactive
  820. + ddev->active = false;
  821. + mutex_unlock(&ddev->mutex);
  822. +
  823. + // After this call we're guaranteed that no more input events will arive
  824. + surface_sam_ssh_notifier_unregister(&ddev->notif);
  825. +
  826. + // wake up clients
  827. + spin_lock(&ddev->client_lock);
  828. + list_for_each_entry(client, &ddev->client_list, node) {
  829. + kill_fasync(&client->fasync, SIGIO, POLL_HUP);
  830. + }
  831. + spin_unlock(&ddev->client_lock);
  832. +
  833. + wake_up_interruptible(&ddev->waitq);
  834. +
  835. + // unregister user-space devices
  836. + input_unregister_device(ddev->input_dev);
  837. + misc_deregister(&ddev->mdev);
  838. +
  839. + return 0;
  840. +}
  841. +
  842. +
  843. +static const struct acpi_device_id surface_sam_dtx_match[] = {
  844. + { "MSHW0133", 0 },
  845. + { },
  846. +};
  847. +MODULE_DEVICE_TABLE(acpi, surface_sam_dtx_match);
  848. +
  849. +static struct platform_driver surface_sam_dtx = {
  850. + .probe = surface_sam_dtx_probe,
  851. + .remove = surface_sam_dtx_remove,
  852. + .driver = {
  853. + .name = "surface_sam_dtx",
  854. + .acpi_match_table = surface_sam_dtx_match,
  855. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  856. + },
  857. +};
  858. +module_platform_driver(surface_sam_dtx);
  859. +
  860. +MODULE_AUTHOR("Maximilian Luz <luzmaximilian@gmail.com>");
  861. +MODULE_DESCRIPTION("Surface Detachment System (DTX) Driver for 5th Generation Surface Devices");
  862. +MODULE_LICENSE("GPL");
  863. diff --git a/drivers/platform/x86/surface_sam/surface_sam_hps.c b/drivers/platform/x86/surface_sam/surface_sam_hps.c
  864. new file mode 100644
  865. index 0000000000000..40f39f29113c5
  866. --- /dev/null
  867. +++ b/drivers/platform/x86/surface_sam/surface_sam_hps.c
  868. @@ -0,0 +1,1297 @@
  869. +// SPDX-License-Identifier: GPL-2.0-or-later
  870. +/*
  871. + * Surface dGPU hot-plug system driver.
  872. + * Supports explicit setting of the dGPU power-state on the Surface Book 2 and
  873. + * properly handles hot-plugging by detaching the base.
  874. + */
  875. +
  876. +#include <linux/acpi.h>
  877. +#include <linux/delay.h>
  878. +#include <linux/gpio.h>
  879. +#include <linux/kernel.h>
  880. +#include <linux/module.h>
  881. +#include <linux/mutex.h>
  882. +#include <linux/pci.h>
  883. +#include <linux/platform_device.h>
  884. +#include <linux/sysfs.h>
  885. +
  886. +#include "surface_sam_ssh.h"
  887. +#include "surface_sam_san.h"
  888. +
  889. +
  890. +// TODO: vgaswitcheroo integration
  891. +
  892. +
  893. +static void dbg_dump_drvsta(struct platform_device *pdev, const char *prefix);
  894. +
  895. +
  896. +#define SHPS_DSM_REVISION 1
  897. +#define SHPS_DSM_GPU_ADDRS 0x02
  898. +#define SHPS_DSM_GPU_POWER 0x05
  899. +static const guid_t SHPS_DSM_UUID =
  900. + GUID_INIT(0x5515a847, 0xed55, 0x4b27, 0x83, 0x52, 0xcd,
  901. + 0x32, 0x0e, 0x10, 0x36, 0x0a);
  902. +
  903. +
  904. +#define SAM_DGPU_TC 0x13
  905. +#define SAM_DGPU_CID_POWERON 0x02
  906. +
  907. +#define SAM_DTX_TC 0x11
  908. +#define SAM_DTX_CID_LATCH_LOCK 0x06
  909. +#define SAM_DTX_CID_LATCH_UNLOCK 0x07
  910. +#define ACPI_SGCP_NOTIFY_POWER_ON 0x81
  911. +
  912. +#define SHPS_DSM_GPU_ADDRS_RP "RP5_PCIE"
  913. +#define SHPS_DSM_GPU_ADDRS_DGPU "DGPU_PCIE"
  914. +#define SHPS_PCI_GPU_ADDR_RP "\\_SB.PCI0.RP13._ADR"
  915. +
  916. +static const struct acpi_gpio_params gpio_base_presence_int = { 0, 0, false };
  917. +static const struct acpi_gpio_params gpio_base_presence = { 1, 0, false };
  918. +static const struct acpi_gpio_params gpio_dgpu_power_int = { 2, 0, false };
  919. +static const struct acpi_gpio_params gpio_dgpu_power = { 3, 0, false };
  920. +static const struct acpi_gpio_params gpio_dgpu_presence_int = { 4, 0, false };
  921. +static const struct acpi_gpio_params gpio_dgpu_presence = { 5, 0, false };
  922. +
  923. +static const struct acpi_gpio_mapping shps_acpi_gpios[] = {
  924. + { "base_presence-int-gpio", &gpio_base_presence_int, 1 },
  925. + { "base_presence-gpio", &gpio_base_presence, 1 },
  926. + { "dgpu_power-int-gpio", &gpio_dgpu_power_int, 1 },
  927. + { "dgpu_power-gpio", &gpio_dgpu_power, 1 },
  928. + { "dgpu_presence-int-gpio", &gpio_dgpu_presence_int, 1 },
  929. + { "dgpu_presence-gpio", &gpio_dgpu_presence, 1 },
  930. + { },
  931. +};
  932. +
  933. +
  934. +enum shps_dgpu_power {
  935. + SHPS_DGPU_POWER_OFF = 0,
  936. + SHPS_DGPU_POWER_ON = 1,
  937. + SHPS_DGPU_POWER_UNKNOWN = 2,
  938. +};
  939. +
  940. +static const char *shps_dgpu_power_str(enum shps_dgpu_power power)
  941. +{
  942. + if (power == SHPS_DGPU_POWER_OFF)
  943. + return "off";
  944. + else if (power == SHPS_DGPU_POWER_ON)
  945. + return "on";
  946. + else if (power == SHPS_DGPU_POWER_UNKNOWN)
  947. + return "unknown";
  948. + else
  949. + return "<invalid>";
  950. +}
  951. +
  952. +enum shps_notification_method {
  953. + SHPS_NOTIFICATION_METHOD_SAN = 1,
  954. + SHPS_NOTIFICATION_METHOD_SGCP = 2
  955. +};
  956. +
  957. +struct shps_hardware_traits {
  958. + enum shps_notification_method notification_method;
  959. + const char *dgpu_rp_pci_address;
  960. +};
  961. +
  962. +struct shps_driver_data {
  963. + struct mutex lock;
  964. + struct pci_dev *dgpu_root_port;
  965. + struct pci_saved_state *dgpu_root_port_state;
  966. + struct gpio_desc *gpio_dgpu_power;
  967. + struct gpio_desc *gpio_dgpu_presence;
  968. + struct gpio_desc *gpio_base_presence;
  969. + unsigned int irq_dgpu_presence;
  970. + unsigned int irq_base_presence;
  971. + unsigned long state;
  972. + acpi_handle sgpc_handle;
  973. + struct shps_hardware_traits hardware_traits;
  974. +};
  975. +
  976. +struct shps_hardware_probe {
  977. + const char *hardware_id;
  978. + int generation;
  979. + struct shps_hardware_traits *hardware_traits;
  980. +};
  981. +
  982. +static struct shps_hardware_traits shps_gen1_hwtraits = {
  983. + .notification_method = SHPS_NOTIFICATION_METHOD_SAN
  984. +};
  985. +
  986. +static struct shps_hardware_traits shps_gen2_hwtraits = {
  987. + .notification_method = SHPS_NOTIFICATION_METHOD_SGCP,
  988. + .dgpu_rp_pci_address = SHPS_PCI_GPU_ADDR_RP
  989. +};
  990. +
  991. +static const struct shps_hardware_probe shps_hardware_probe_match[] = {
  992. + /* Surface Book 3 */
  993. + { "MSHW0117", 2, &shps_gen2_hwtraits },
  994. +
  995. + /* Surface Book 2 (default, must be last entry) */
  996. + { NULL, 1, &shps_gen1_hwtraits }
  997. +};
  998. +
  999. +#define SHPS_STATE_BIT_PWRTGT 0 /* desired power state: 1 for on, 0 for off */
  1000. +#define SHPS_STATE_BIT_RPPWRON_SYNC 1 /* synchronous/requested power-up in progress */
  1001. +#define SHPS_STATE_BIT_WAKE_ENABLED 2 /* wakeup via base-presence GPIO enabled */
  1002. +
  1003. +
  1004. +#define SHPS_DGPU_PARAM_PERM 0644
  1005. +
  1006. +enum shps_dgpu_power_mp {
  1007. + SHPS_DGPU_MP_POWER_OFF = SHPS_DGPU_POWER_OFF,
  1008. + SHPS_DGPU_MP_POWER_ON = SHPS_DGPU_POWER_ON,
  1009. + SHPS_DGPU_MP_POWER_ASIS = -1,
  1010. +
  1011. + __SHPS_DGPU_MP_POWER_START = -1,
  1012. + __SHPS_DGPU_MP_POWER_END = 1,
  1013. +};
  1014. +
  1015. +static int param_dgpu_power_set(const char *val, const struct kernel_param *kp)
  1016. +{
  1017. + int power = SHPS_DGPU_MP_POWER_OFF;
  1018. + int status;
  1019. +
  1020. + status = kstrtoint(val, 0, &power);
  1021. + if (status)
  1022. + return status;
  1023. +
  1024. + if (power < __SHPS_DGPU_MP_POWER_START || power > __SHPS_DGPU_MP_POWER_END)
  1025. + return -EINVAL;
  1026. +
  1027. + return param_set_int(val, kp);
  1028. +}
  1029. +
  1030. +static const struct kernel_param_ops param_dgpu_power_ops = {
  1031. + .set = param_dgpu_power_set,
  1032. + .get = param_get_int,
  1033. +};
  1034. +
  1035. +static int param_dgpu_power_init = SHPS_DGPU_MP_POWER_OFF;
  1036. +static int param_dgpu_power_exit = SHPS_DGPU_MP_POWER_ON;
  1037. +static int param_dgpu_power_susp = SHPS_DGPU_MP_POWER_ASIS;
  1038. +static bool param_dtx_latch = true;
  1039. +
  1040. +module_param_cb(dgpu_power_init, &param_dgpu_power_ops, &param_dgpu_power_init, SHPS_DGPU_PARAM_PERM);
  1041. +module_param_cb(dgpu_power_exit, &param_dgpu_power_ops, &param_dgpu_power_exit, SHPS_DGPU_PARAM_PERM);
  1042. +module_param_cb(dgpu_power_susp, &param_dgpu_power_ops, &param_dgpu_power_susp, SHPS_DGPU_PARAM_PERM);
  1043. +module_param_named(dtx_latch, param_dtx_latch, bool, SHPS_DGPU_PARAM_PERM);
  1044. +
  1045. +MODULE_PARM_DESC(dgpu_power_init, "dGPU power state to be set on init (0: off / 1: on / 2: as-is, default: off)");
  1046. +MODULE_PARM_DESC(dgpu_power_exit, "dGPU power state to be set on exit (0: off / 1: on / 2: as-is, default: on)");
  1047. +MODULE_PARM_DESC(dgpu_power_susp, "dGPU power state to be set on exit (0: off / 1: on / 2: as-is, default: as-is)");
  1048. +MODULE_PARM_DESC(dtx_latch, "lock/unlock DTX base latch in accordance to power-state (Y/n)");
  1049. +
  1050. +static int dtx_cmd_simple(u8 cid)
  1051. +{
  1052. + struct surface_sam_ssh_rqst rqst = {
  1053. + .tc = SAM_DTX_TC,
  1054. + .cid = cid,
  1055. + .iid = 0x00,
  1056. + .chn = 0x01,
  1057. + .snc = 0x00,
  1058. + .cdl = 0x00,
  1059. + .pld = NULL,
  1060. + };
  1061. +
  1062. + return surface_sam_ssh_rqst(&rqst, NULL);
  1063. +}
  1064. +
  1065. +static inline int shps_dtx_latch_lock(void)
  1066. +{
  1067. + return dtx_cmd_simple(SAM_DTX_CID_LATCH_LOCK);
  1068. +}
  1069. +
  1070. +static inline int shps_dtx_latch_unlock(void)
  1071. +{
  1072. + return dtx_cmd_simple(SAM_DTX_CID_LATCH_UNLOCK);
  1073. +}
  1074. +
  1075. +static int shps_dgpu_dsm_get_pci_addr_from_adr(struct platform_device *pdev, const char *entry) {
  1076. + acpi_handle handle = ACPI_HANDLE(&pdev->dev);
  1077. + int status;
  1078. + struct acpi_object_list input;
  1079. + union acpi_object input_args[0];
  1080. + u64 device_addr;
  1081. + u8 bus, dev, fun;
  1082. +
  1083. + input.count = 0;
  1084. + input.pointer = input_args;
  1085. +
  1086. +
  1087. + status = acpi_evaluate_integer(handle, (acpi_string)entry, &input, &device_addr);
  1088. + if (status) {
  1089. + return -ENODEV;
  1090. + }
  1091. +
  1092. + bus = 0;
  1093. + dev = (device_addr & 0xFF0000) >> 16;
  1094. + fun = device_addr & 0xFF;
  1095. +
  1096. + dev_info(&pdev->dev, "found pci device at bus = %d, dev = %x, fun = %x\n",
  1097. + (u32)bus, (u32)dev, (u32)fun);
  1098. +
  1099. + return bus << 8 | PCI_DEVFN(dev, fun);
  1100. +}
  1101. +
  1102. +static int shps_dgpu_dsm_get_pci_addr_from_dsm(struct platform_device *pdev, const char *entry)
  1103. +{
  1104. + acpi_handle handle = ACPI_HANDLE(&pdev->dev);
  1105. + union acpi_object *result;
  1106. + union acpi_object *e0;
  1107. + union acpi_object *e1;
  1108. + union acpi_object *e2;
  1109. + u64 device_addr = 0;
  1110. + u8 bus, dev, fun;
  1111. + int i;
  1112. +
  1113. +
  1114. + result = acpi_evaluate_dsm_typed(handle, &SHPS_DSM_UUID, SHPS_DSM_REVISION,
  1115. + SHPS_DSM_GPU_ADDRS, NULL, ACPI_TYPE_PACKAGE);
  1116. +
  1117. + if (IS_ERR_OR_NULL(result))
  1118. + return result ? PTR_ERR(result) : -EIO;
  1119. +
  1120. + // three entries per device: name, address, <integer>
  1121. + for (i = 0; i + 2 < result->package.count; i += 3) {
  1122. + e0 = &result->package.elements[i];
  1123. + e1 = &result->package.elements[i + 1];
  1124. + e2 = &result->package.elements[i + 2];
  1125. +
  1126. + if (e0->type != ACPI_TYPE_STRING) {
  1127. + ACPI_FREE(result);
  1128. + return -EIO;
  1129. + }
  1130. +
  1131. + if (e1->type != ACPI_TYPE_INTEGER) {
  1132. + ACPI_FREE(result);
  1133. + return -EIO;
  1134. + }
  1135. +
  1136. + if (e2->type != ACPI_TYPE_INTEGER) {
  1137. + ACPI_FREE(result);
  1138. + return -EIO;
  1139. + }
  1140. +
  1141. + if (strncmp(e0->string.pointer, entry, 64) == 0)
  1142. + device_addr = e1->integer.value;
  1143. + }
  1144. +
  1145. + ACPI_FREE(result);
  1146. + if (device_addr == 0)
  1147. + return -ENODEV;
  1148. +
  1149. +
  1150. + // convert address
  1151. + bus = (device_addr & 0x0FF00000) >> 20;
  1152. + dev = (device_addr & 0x000F8000) >> 15;
  1153. + fun = (device_addr & 0x00007000) >> 12;
  1154. +
  1155. + return bus << 8 | PCI_DEVFN(dev, fun);
  1156. +}
  1157. +
  1158. +static struct pci_dev *shps_dgpu_dsm_get_pci_dev(struct platform_device *pdev)
  1159. +{
  1160. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1161. + struct pci_dev *dev;
  1162. + int addr;
  1163. +
  1164. +
  1165. + if (drvdata->hardware_traits.dgpu_rp_pci_address) {
  1166. + addr = shps_dgpu_dsm_get_pci_addr_from_adr(pdev, drvdata->hardware_traits.dgpu_rp_pci_address);
  1167. + } else {
  1168. + addr = shps_dgpu_dsm_get_pci_addr_from_dsm(pdev, SHPS_DSM_GPU_ADDRS_RP);
  1169. + }
  1170. +
  1171. + if (addr < 0)
  1172. + return ERR_PTR(addr);
  1173. +
  1174. + dev = pci_get_domain_bus_and_slot(0, (addr & 0xFF00) >> 8, addr & 0xFF);
  1175. + return dev ? dev : ERR_PTR(-ENODEV);
  1176. +}
  1177. +
  1178. +
  1179. +static int shps_dgpu_dsm_get_power_unlocked(struct platform_device *pdev)
  1180. +{
  1181. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1182. + struct gpio_desc *gpio = drvdata->gpio_dgpu_power;
  1183. + int status;
  1184. +
  1185. + status = gpiod_get_value_cansleep(gpio);
  1186. + if (status < 0)
  1187. + return status;
  1188. +
  1189. + return status == 0 ? SHPS_DGPU_POWER_OFF : SHPS_DGPU_POWER_ON;
  1190. +}
  1191. +
  1192. +static int shps_dgpu_dsm_get_power(struct platform_device *pdev)
  1193. +{
  1194. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1195. + int status;
  1196. +
  1197. + mutex_lock(&drvdata->lock);
  1198. + status = shps_dgpu_dsm_get_power_unlocked(pdev);
  1199. + mutex_unlock(&drvdata->lock);
  1200. +
  1201. + return status;
  1202. +}
  1203. +
  1204. +static int __shps_dgpu_dsm_set_power_unlocked(struct platform_device *pdev, enum shps_dgpu_power power)
  1205. +{
  1206. + acpi_handle handle = ACPI_HANDLE(&pdev->dev);
  1207. + union acpi_object *result;
  1208. + union acpi_object param;
  1209. +
  1210. + dev_info(&pdev->dev, "setting dGPU direct power to \'%s\'\n", shps_dgpu_power_str(power));
  1211. +
  1212. + param.type = ACPI_TYPE_INTEGER;
  1213. + param.integer.value = power == SHPS_DGPU_POWER_ON;
  1214. +
  1215. + result = acpi_evaluate_dsm_typed(handle, &SHPS_DSM_UUID, SHPS_DSM_REVISION,
  1216. + SHPS_DSM_GPU_POWER, &param, ACPI_TYPE_BUFFER);
  1217. +
  1218. + if (IS_ERR_OR_NULL(result))
  1219. + return result ? PTR_ERR(result) : -EIO;
  1220. +
  1221. + // check for the expected result
  1222. + if (result->buffer.length != 1 || result->buffer.pointer[0] != 0) {
  1223. + ACPI_FREE(result);
  1224. + return -EIO;
  1225. + }
  1226. +
  1227. + ACPI_FREE(result);
  1228. + return 0;
  1229. +}
  1230. +
  1231. +static int shps_dgpu_dsm_set_power_unlocked(struct platform_device *pdev, enum shps_dgpu_power power)
  1232. +{
  1233. + int status;
  1234. +
  1235. + if (power != SHPS_DGPU_POWER_ON && power != SHPS_DGPU_POWER_OFF)
  1236. + return -EINVAL;
  1237. +
  1238. + status = shps_dgpu_dsm_get_power_unlocked(pdev);
  1239. + if (status < 0)
  1240. + return status;
  1241. + if (status == power)
  1242. + return 0;
  1243. +
  1244. + return __shps_dgpu_dsm_set_power_unlocked(pdev, power);
  1245. +}
  1246. +
  1247. +static int shps_dgpu_dsm_set_power(struct platform_device *pdev, enum shps_dgpu_power power)
  1248. +{
  1249. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1250. + int status;
  1251. +
  1252. + mutex_lock(&drvdata->lock);
  1253. + status = shps_dgpu_dsm_set_power_unlocked(pdev, power);
  1254. + mutex_unlock(&drvdata->lock);
  1255. +
  1256. + return status;
  1257. +}
  1258. +
  1259. +
  1260. +static bool shps_rp_link_up(struct pci_dev *rp)
  1261. +{
  1262. + u16 lnksta = 0, sltsta = 0;
  1263. +
  1264. + pcie_capability_read_word(rp, PCI_EXP_LNKSTA, &lnksta);
  1265. + pcie_capability_read_word(rp, PCI_EXP_SLTSTA, &sltsta);
  1266. +
  1267. + return (lnksta & PCI_EXP_LNKSTA_DLLLA) || (sltsta & PCI_EXP_SLTSTA_PDS);
  1268. +}
  1269. +
  1270. +
  1271. +static int shps_dgpu_rp_get_power_unlocked(struct platform_device *pdev)
  1272. +{
  1273. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1274. + struct pci_dev *rp = drvdata->dgpu_root_port;
  1275. +
  1276. + if (rp->current_state == PCI_D3hot || rp->current_state == PCI_D3cold)
  1277. + return SHPS_DGPU_POWER_OFF;
  1278. + else if (rp->current_state == PCI_UNKNOWN || rp->current_state == PCI_POWER_ERROR)
  1279. + return SHPS_DGPU_POWER_UNKNOWN;
  1280. + else
  1281. + return SHPS_DGPU_POWER_ON;
  1282. +}
  1283. +
  1284. +static int shps_dgpu_rp_get_power(struct platform_device *pdev)
  1285. +{
  1286. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1287. + int status;
  1288. +
  1289. + mutex_lock(&drvdata->lock);
  1290. + status = shps_dgpu_rp_get_power_unlocked(pdev);
  1291. + mutex_unlock(&drvdata->lock);
  1292. +
  1293. + return status;
  1294. +}
  1295. +
  1296. +static int __shps_dgpu_rp_set_power_unlocked(struct platform_device *pdev, enum shps_dgpu_power power)
  1297. +{
  1298. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1299. + struct pci_dev *rp = drvdata->dgpu_root_port;
  1300. + int status, i;
  1301. +
  1302. + dev_info(&pdev->dev, "setting dGPU power state to \'%s\'\n", shps_dgpu_power_str(power));
  1303. +
  1304. + dbg_dump_drvsta(pdev, "__shps_dgpu_rp_set_power_unlocked.1");
  1305. + if (power == SHPS_DGPU_POWER_ON) {
  1306. + set_bit(SHPS_STATE_BIT_RPPWRON_SYNC, &drvdata->state);
  1307. + pci_set_power_state(rp, PCI_D0);
  1308. +
  1309. + if (drvdata->dgpu_root_port_state)
  1310. + pci_load_and_free_saved_state(rp, &drvdata->dgpu_root_port_state);
  1311. +
  1312. + pci_restore_state(rp);
  1313. +
  1314. + if (!pci_is_enabled(rp))
  1315. + pci_enable_device(rp);
  1316. +
  1317. + pci_set_master(rp);
  1318. + clear_bit(SHPS_STATE_BIT_RPPWRON_SYNC, &drvdata->state);
  1319. +
  1320. + set_bit(SHPS_STATE_BIT_PWRTGT, &drvdata->state);
  1321. + } else {
  1322. + if (!drvdata->dgpu_root_port_state) {
  1323. + pci_save_state(rp);
  1324. + drvdata->dgpu_root_port_state = pci_store_saved_state(rp);
  1325. + }
  1326. +
  1327. + /*
  1328. + * To properly update the hot-plug system we need to "remove" the dGPU
  1329. + * before disabling it and sending it to D3cold. Following this, we
  1330. + * need to wait for the link and slot status to actually change.
  1331. + */
  1332. + status = shps_dgpu_dsm_set_power_unlocked(pdev, SHPS_DGPU_POWER_OFF);
  1333. + if (status)
  1334. + return status;
  1335. +
  1336. + for (i = 0; i < 20 && shps_rp_link_up(rp); i++)
  1337. + msleep(50);
  1338. +
  1339. + if (shps_rp_link_up(rp))
  1340. + dev_err(&pdev->dev, "dGPU removal via DSM timed out\n");
  1341. +
  1342. + pci_clear_master(rp);
  1343. +
  1344. + if (pci_is_enabled(rp))
  1345. + pci_disable_device(rp);
  1346. +
  1347. + pci_set_power_state(rp, PCI_D3cold);
  1348. +
  1349. + clear_bit(SHPS_STATE_BIT_PWRTGT, &drvdata->state);
  1350. + }
  1351. + dbg_dump_drvsta(pdev, "__shps_dgpu_rp_set_power_unlocked.2");
  1352. +
  1353. + return 0;
  1354. +}
  1355. +
  1356. +static int shps_dgpu_rp_set_power_unlocked(struct platform_device *pdev, enum shps_dgpu_power power)
  1357. +{
  1358. + int status;
  1359. +
  1360. + if (power != SHPS_DGPU_POWER_ON && power != SHPS_DGPU_POWER_OFF)
  1361. + return -EINVAL;
  1362. +
  1363. + status = shps_dgpu_rp_get_power_unlocked(pdev);
  1364. + if (status < 0)
  1365. + return status;
  1366. + if (status == power)
  1367. + return 0;
  1368. +
  1369. + return __shps_dgpu_rp_set_power_unlocked(pdev, power);
  1370. +}
  1371. +
  1372. +static int shps_dgpu_rp_set_power(struct platform_device *pdev, enum shps_dgpu_power power)
  1373. +{
  1374. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1375. + int status;
  1376. +
  1377. + mutex_lock(&drvdata->lock);
  1378. + status = shps_dgpu_rp_set_power_unlocked(pdev, power);
  1379. + mutex_unlock(&drvdata->lock);
  1380. +
  1381. + return status;
  1382. +}
  1383. +
  1384. +
  1385. +static int shps_dgpu_set_power(struct platform_device *pdev, enum shps_dgpu_power power)
  1386. +{
  1387. + int status;
  1388. +
  1389. + if (!param_dtx_latch)
  1390. + return shps_dgpu_rp_set_power(pdev, power);
  1391. +
  1392. + if (power == SHPS_DGPU_POWER_ON) {
  1393. + status = shps_dtx_latch_lock();
  1394. + if (status)
  1395. + return status;
  1396. +
  1397. + status = shps_dgpu_rp_set_power(pdev, power);
  1398. + if (status)
  1399. + shps_dtx_latch_unlock();
  1400. +
  1401. + } else {
  1402. + status = shps_dgpu_rp_set_power(pdev, power);
  1403. + if (status)
  1404. + return status;
  1405. +
  1406. + status = shps_dtx_latch_unlock();
  1407. + }
  1408. +
  1409. + return status;
  1410. +}
  1411. +
  1412. +
  1413. +static int shps_dgpu_is_present(struct platform_device *pdev)
  1414. +{
  1415. + struct shps_driver_data *drvdata;
  1416. +
  1417. + drvdata = platform_get_drvdata(pdev);
  1418. + return gpiod_get_value_cansleep(drvdata->gpio_dgpu_presence);
  1419. +}
  1420. +
  1421. +
  1422. +static ssize_t dgpu_power_show(struct device *dev, struct device_attribute *attr, char *data)
  1423. +{
  1424. + struct platform_device *pdev = to_platform_device(dev);
  1425. + int power = shps_dgpu_rp_get_power(pdev);
  1426. +
  1427. + if (power < 0)
  1428. + return power;
  1429. +
  1430. + return sprintf(data, "%s\n", shps_dgpu_power_str(power));
  1431. +}
  1432. +
  1433. +static ssize_t dgpu_power_store(struct device *dev, struct device_attribute *attr,
  1434. + const char *data, size_t count)
  1435. +{
  1436. + struct platform_device *pdev = to_platform_device(dev);
  1437. + enum shps_dgpu_power power;
  1438. + bool b = false;
  1439. + int status;
  1440. +
  1441. + status = kstrtobool(data, &b);
  1442. + if (status)
  1443. + return status;
  1444. +
  1445. + status = shps_dgpu_is_present(pdev);
  1446. + if (status <= 0)
  1447. + return status < 0 ? status : -EPERM;
  1448. +
  1449. + power = b ? SHPS_DGPU_POWER_ON : SHPS_DGPU_POWER_OFF;
  1450. + status = shps_dgpu_set_power(pdev, power);
  1451. +
  1452. + return status < 0 ? status : count;
  1453. +}
  1454. +
  1455. +static ssize_t dgpu_power_dsm_show(struct device *dev, struct device_attribute *attr, char *data)
  1456. +{
  1457. + struct platform_device *pdev = to_platform_device(dev);
  1458. + int power = shps_dgpu_dsm_get_power(pdev);
  1459. +
  1460. + if (power < 0)
  1461. + return power;
  1462. +
  1463. + return sprintf(data, "%s\n", shps_dgpu_power_str(power));
  1464. +}
  1465. +
  1466. +static ssize_t dgpu_power_dsm_store(struct device *dev, struct device_attribute *attr,
  1467. + const char *data, size_t count)
  1468. +{
  1469. + struct platform_device *pdev = to_platform_device(dev);
  1470. + enum shps_dgpu_power power;
  1471. + bool b = false;
  1472. + int status;
  1473. +
  1474. + status = kstrtobool(data, &b);
  1475. + if (status)
  1476. + return status;
  1477. +
  1478. + status = shps_dgpu_is_present(pdev);
  1479. + if (status <= 0)
  1480. + return status < 0 ? status : -EPERM;
  1481. +
  1482. + power = b ? SHPS_DGPU_POWER_ON : SHPS_DGPU_POWER_OFF;
  1483. + status = shps_dgpu_dsm_set_power(pdev, power);
  1484. +
  1485. + return status < 0 ? status : count;
  1486. +}
  1487. +
  1488. +static DEVICE_ATTR_RW(dgpu_power);
  1489. +static DEVICE_ATTR_RW(dgpu_power_dsm);
  1490. +
  1491. +static struct attribute *shps_power_attrs[] = {
  1492. + &dev_attr_dgpu_power.attr,
  1493. + &dev_attr_dgpu_power_dsm.attr,
  1494. + NULL,
  1495. +};
  1496. +ATTRIBUTE_GROUPS(shps_power);
  1497. +
  1498. +
  1499. +static void dbg_dump_power_states(struct platform_device *pdev, const char *prefix)
  1500. +{
  1501. + enum shps_dgpu_power power_dsm;
  1502. + enum shps_dgpu_power power_rp;
  1503. + int status;
  1504. +
  1505. + status = shps_dgpu_rp_get_power_unlocked(pdev);
  1506. + if (status < 0)
  1507. + dev_err(&pdev->dev, "%s: failed to get root-port power state: %d\n", prefix, status);
  1508. + power_rp = status;
  1509. +
  1510. + status = shps_dgpu_rp_get_power_unlocked(pdev);
  1511. + if (status < 0)
  1512. + dev_err(&pdev->dev, "%s: failed to get direct power state: %d\n", prefix, status);
  1513. + power_dsm = status;
  1514. +
  1515. + dev_dbg(&pdev->dev, "%s: root-port power state: %d\n", prefix, power_rp);
  1516. + dev_dbg(&pdev->dev, "%s: direct power state: %d\n", prefix, power_dsm);
  1517. +}
  1518. +
  1519. +static void dbg_dump_pciesta(struct platform_device *pdev, const char *prefix)
  1520. +{
  1521. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1522. + struct pci_dev *rp = drvdata->dgpu_root_port;
  1523. + u16 lnksta, lnksta2, sltsta, sltsta2;
  1524. +
  1525. + pcie_capability_read_word(rp, PCI_EXP_LNKSTA, &lnksta);
  1526. + pcie_capability_read_word(rp, PCI_EXP_LNKSTA2, &lnksta2);
  1527. + pcie_capability_read_word(rp, PCI_EXP_SLTSTA, &sltsta);
  1528. + pcie_capability_read_word(rp, PCI_EXP_SLTSTA2, &sltsta2);
  1529. +
  1530. + dev_dbg(&pdev->dev, "%s: LNKSTA: 0x%04x\n", prefix, lnksta);
  1531. + dev_dbg(&pdev->dev, "%s: LNKSTA2: 0x%04x\n", prefix, lnksta2);
  1532. + dev_dbg(&pdev->dev, "%s: SLTSTA: 0x%04x\n", prefix, sltsta);
  1533. + dev_dbg(&pdev->dev, "%s: SLTSTA2: 0x%04x\n", prefix, sltsta2);
  1534. +}
  1535. +
  1536. +static void dbg_dump_drvsta(struct platform_device *pdev, const char *prefix)
  1537. +{
  1538. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1539. + struct pci_dev *rp = drvdata->dgpu_root_port;
  1540. +
  1541. + dev_dbg(&pdev->dev, "%s: RP power: %d\n", prefix, rp->current_state);
  1542. + dev_dbg(&pdev->dev, "%s: RP state saved: %d\n", prefix, rp->state_saved);
  1543. + dev_dbg(&pdev->dev, "%s: RP state stored: %d\n", prefix, !!drvdata->dgpu_root_port_state);
  1544. + dev_dbg(&pdev->dev, "%s: RP enabled: %d\n", prefix, atomic_read(&rp->enable_cnt));
  1545. + dev_dbg(&pdev->dev, "%s: RP mastered: %d\n", prefix, rp->is_busmaster);
  1546. +}
  1547. +
  1548. +static int shps_pm_prepare(struct device *dev)
  1549. +{
  1550. + struct platform_device *pdev = to_platform_device(dev);
  1551. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1552. + bool pwrtgt;
  1553. + int status = 0;
  1554. +
  1555. + dbg_dump_power_states(pdev, "shps_pm_prepare");
  1556. +
  1557. + if (param_dgpu_power_susp != SHPS_DGPU_MP_POWER_ASIS) {
  1558. + pwrtgt = test_bit(SHPS_STATE_BIT_PWRTGT, &drvdata->state);
  1559. +
  1560. + status = shps_dgpu_set_power(pdev, param_dgpu_power_susp);
  1561. + if (status) {
  1562. + dev_err(&pdev->dev, "failed to power %s dGPU: %d\n",
  1563. + param_dgpu_power_susp == SHPS_DGPU_MP_POWER_OFF ? "off" : "on",
  1564. + status);
  1565. + return status;
  1566. + }
  1567. +
  1568. + if (pwrtgt)
  1569. + set_bit(SHPS_STATE_BIT_PWRTGT, &drvdata->state);
  1570. + else
  1571. + clear_bit(SHPS_STATE_BIT_PWRTGT, &drvdata->state);
  1572. + }
  1573. +
  1574. + return 0;
  1575. +}
  1576. +
  1577. +static void shps_pm_complete(struct device *dev)
  1578. +{
  1579. + struct platform_device *pdev = to_platform_device(dev);
  1580. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1581. + int status;
  1582. +
  1583. + dbg_dump_power_states(pdev, "shps_pm_complete");
  1584. + dbg_dump_pciesta(pdev, "shps_pm_complete");
  1585. + dbg_dump_drvsta(pdev, "shps_pm_complete.1");
  1586. +
  1587. + // update power target, dGPU may have been detached while suspended
  1588. + status = shps_dgpu_is_present(pdev);
  1589. + if (status < 0) {
  1590. + dev_err(&pdev->dev, "failed to get dGPU presence: %d\n", status);
  1591. + return;
  1592. + } else if (status == 0) {
  1593. + clear_bit(SHPS_STATE_BIT_PWRTGT, &drvdata->state);
  1594. + }
  1595. +
  1596. + /*
  1597. + * During resume, the PCIe core will power on the root-port, which in turn
  1598. + * will power on the dGPU. Most of the state synchronization is already
  1599. + * handled via the SAN RQSG handler, so it is in a fully consistent
  1600. + * on-state here. If requested, turn it off here.
  1601. + *
  1602. + * As there seem to be some synchronization issues turning off the dGPU
  1603. + * directly after the power-on SAN RQSG notification during the resume
  1604. + * process, let's do this here.
  1605. + *
  1606. + * TODO/FIXME:
  1607. + * This does not combat unhandled power-ons when the device is not fully
  1608. + * resumed, i.e. re-suspended before shps_pm_complete is called. Those
  1609. + * should normally not be an issue, but the dGPU does get hot even though
  1610. + * it is suspended, so ideally we want to keep it off.
  1611. + */
  1612. + if (!test_bit(SHPS_STATE_BIT_PWRTGT, &drvdata->state)) {
  1613. + status = shps_dgpu_set_power(pdev, SHPS_DGPU_POWER_OFF);
  1614. + if (status)
  1615. + dev_err(&pdev->dev, "failed to power-off dGPU: %d\n", status);
  1616. + }
  1617. +
  1618. + dbg_dump_drvsta(pdev, "shps_pm_complete.2");
  1619. +}
  1620. +
  1621. +static int shps_pm_suspend(struct device *dev)
  1622. +{
  1623. + struct platform_device *pdev = to_platform_device(dev);
  1624. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1625. + int status;
  1626. +
  1627. + if (device_may_wakeup(dev)) {
  1628. + status = enable_irq_wake(drvdata->irq_base_presence);
  1629. + if (status)
  1630. + return status;
  1631. +
  1632. + set_bit(SHPS_STATE_BIT_WAKE_ENABLED, &drvdata->state);
  1633. + }
  1634. +
  1635. + return 0;
  1636. +}
  1637. +
  1638. +static int shps_pm_resume(struct device *dev)
  1639. +{
  1640. + struct platform_device *pdev = to_platform_device(dev);
  1641. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1642. + int status = 0;
  1643. +
  1644. + if (test_and_clear_bit(SHPS_STATE_BIT_WAKE_ENABLED, &drvdata->state))
  1645. + status = disable_irq_wake(drvdata->irq_base_presence);
  1646. +
  1647. + return status;
  1648. +}
  1649. +
  1650. +static void shps_shutdown(struct platform_device *pdev)
  1651. +{
  1652. + int status;
  1653. +
  1654. + /*
  1655. + * Turn on dGPU before shutting down. This allows the core drivers to
  1656. + * properly shut down the device. If we don't do this, the pcieport driver
  1657. + * will complain that the device has already been disabled.
  1658. + */
  1659. + status = shps_dgpu_set_power(pdev, SHPS_DGPU_POWER_ON);
  1660. + if (status)
  1661. + dev_err(&pdev->dev, "failed to turn on dGPU: %d\n", status);
  1662. +}
  1663. +
  1664. +static int shps_dgpu_detached(struct platform_device *pdev)
  1665. +{
  1666. + dbg_dump_power_states(pdev, "shps_dgpu_detached");
  1667. + return shps_dgpu_set_power(pdev, SHPS_DGPU_POWER_OFF);
  1668. +}
  1669. +
  1670. +static int shps_dgpu_attached(struct platform_device *pdev)
  1671. +{
  1672. + dbg_dump_power_states(pdev, "shps_dgpu_attached");
  1673. + return 0;
  1674. +}
  1675. +
  1676. +static int shps_dgpu_powered_on(struct platform_device *pdev)
  1677. +{
  1678. + /*
  1679. + * This function gets called directly after a power-state transition of
  1680. + * the dGPU root port out of D3cold state, indicating a power-on of the
  1681. + * dGPU. Specifically, this function is called from the RQSG handler of
  1682. + * SAN, invoked by the ACPI _ON method of the dGPU root port. This means
  1683. + * that this function is run inside `pci_set_power_state(rp, ...)`
  1684. + * syncrhonously and thus returns before the `pci_set_power_state` call
  1685. + * does.
  1686. + *
  1687. + * `pci_set_power_state` may either be called by us or when the PCI
  1688. + * subsystem decides to power up the root port (e.g. during resume). Thus
  1689. + * we should use this function to ensure that the dGPU and root port
  1690. + * states are consistent when an unexpected power-up is encountered.
  1691. + */
  1692. +
  1693. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1694. + struct pci_dev *rp = drvdata->dgpu_root_port;
  1695. + int status;
  1696. +
  1697. + dbg_dump_drvsta(pdev, "shps_dgpu_powered_on.1");
  1698. +
  1699. + // if we caused the root port to power-on, return
  1700. + if (test_bit(SHPS_STATE_BIT_RPPWRON_SYNC, &drvdata->state))
  1701. + return 0;
  1702. +
  1703. + // if dGPU is not present, force power-target to off and return
  1704. + status = shps_dgpu_is_present(pdev);
  1705. + if (status == 0)
  1706. + clear_bit(SHPS_STATE_BIT_PWRTGT, &drvdata->state);
  1707. + if (status <= 0)
  1708. + return status;
  1709. +
  1710. + mutex_lock(&drvdata->lock);
  1711. +
  1712. + dbg_dump_power_states(pdev, "shps_dgpu_powered_on.1");
  1713. + dbg_dump_pciesta(pdev, "shps_dgpu_powered_on.1");
  1714. + if (drvdata->dgpu_root_port_state)
  1715. + pci_load_and_free_saved_state(rp, &drvdata->dgpu_root_port_state);
  1716. + pci_restore_state(rp);
  1717. + if (!pci_is_enabled(rp))
  1718. + pci_enable_device(rp);
  1719. + pci_set_master(rp);
  1720. + dbg_dump_drvsta(pdev, "shps_dgpu_powered_on.2");
  1721. + dbg_dump_power_states(pdev, "shps_dgpu_powered_on.2");
  1722. + dbg_dump_pciesta(pdev, "shps_dgpu_powered_on.2");
  1723. +
  1724. + mutex_unlock(&drvdata->lock);
  1725. +
  1726. + if (!test_bit(SHPS_STATE_BIT_PWRTGT, &drvdata->state)) {
  1727. + dev_warn(&pdev->dev, "unexpected dGPU power-on detected\n");
  1728. + // TODO: schedule state re-check and update
  1729. + }
  1730. +
  1731. + return 0;
  1732. +}
  1733. +
  1734. +static int shps_dgpu_handle_rqsg(struct surface_sam_san_rqsg *rqsg, void *data)
  1735. +{
  1736. + struct platform_device *pdev = data;
  1737. +
  1738. + if (rqsg->tc == SAM_DGPU_TC && rqsg->cid == SAM_DGPU_CID_POWERON)
  1739. + return shps_dgpu_powered_on(pdev);
  1740. +
  1741. + dev_warn(&pdev->dev, "unimplemented dGPU request: RQSG(0x%02x, 0x%02x, 0x%02x)\n",
  1742. + rqsg->tc, rqsg->cid, rqsg->iid);
  1743. + return 0;
  1744. +}
  1745. +
  1746. +static irqreturn_t shps_dgpu_presence_irq(int irq, void *data)
  1747. +{
  1748. + struct platform_device *pdev = data;
  1749. + bool dgpu_present;
  1750. + int status;
  1751. +
  1752. + status = shps_dgpu_is_present(pdev);
  1753. + if (status < 0) {
  1754. + dev_err(&pdev->dev, "failed to check physical dGPU presence: %d\n", status);
  1755. + return IRQ_HANDLED;
  1756. + }
  1757. +
  1758. + dgpu_present = status != 0;
  1759. + dev_info(&pdev->dev, "dGPU physically %s\n", dgpu_present ? "attached" : "detached");
  1760. +
  1761. + if (dgpu_present)
  1762. + status = shps_dgpu_attached(pdev);
  1763. + else
  1764. + status = shps_dgpu_detached(pdev);
  1765. +
  1766. + if (status)
  1767. + dev_err(&pdev->dev, "error handling dGPU interrupt: %d\n", status);
  1768. +
  1769. + return IRQ_HANDLED;
  1770. +}
  1771. +
  1772. +static irqreturn_t shps_base_presence_irq(int irq, void *data)
  1773. +{
  1774. + return IRQ_HANDLED; // nothing to do, just wake
  1775. +}
  1776. +
  1777. +
  1778. +static int shps_gpios_setup(struct platform_device *pdev)
  1779. +{
  1780. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1781. + struct gpio_desc *gpio_dgpu_power;
  1782. + struct gpio_desc *gpio_dgpu_presence;
  1783. + struct gpio_desc *gpio_base_presence;
  1784. + int status;
  1785. +
  1786. + // get GPIOs
  1787. + gpio_dgpu_power = devm_gpiod_get(&pdev->dev, "dgpu_power", GPIOD_IN);
  1788. + if (IS_ERR(gpio_dgpu_power)) {
  1789. + status = PTR_ERR(gpio_dgpu_power);
  1790. + goto err_out;
  1791. + }
  1792. +
  1793. + gpio_dgpu_presence = devm_gpiod_get(&pdev->dev, "dgpu_presence", GPIOD_IN);
  1794. + if (IS_ERR(gpio_dgpu_presence)) {
  1795. + status = PTR_ERR(gpio_dgpu_presence);
  1796. + goto err_out;
  1797. + }
  1798. +
  1799. + gpio_base_presence = devm_gpiod_get(&pdev->dev, "base_presence", GPIOD_IN);
  1800. + if (IS_ERR(gpio_base_presence)) {
  1801. + status = PTR_ERR(gpio_base_presence);
  1802. + goto err_out;
  1803. + }
  1804. +
  1805. + // export GPIOs
  1806. + status = gpiod_export(gpio_dgpu_power, false);
  1807. + if (status)
  1808. + goto err_out;
  1809. +
  1810. + status = gpiod_export(gpio_dgpu_presence, false);
  1811. + if (status)
  1812. + goto err_export_dgpu_presence;
  1813. +
  1814. + status = gpiod_export(gpio_base_presence, false);
  1815. + if (status)
  1816. + goto err_export_base_presence;
  1817. +
  1818. + // create sysfs links
  1819. + status = gpiod_export_link(&pdev->dev, "gpio-dgpu_power", gpio_dgpu_power);
  1820. + if (status)
  1821. + goto err_link_dgpu_power;
  1822. +
  1823. + status = gpiod_export_link(&pdev->dev, "gpio-dgpu_presence", gpio_dgpu_presence);
  1824. + if (status)
  1825. + goto err_link_dgpu_presence;
  1826. +
  1827. + status = gpiod_export_link(&pdev->dev, "gpio-base_presence", gpio_base_presence);
  1828. + if (status)
  1829. + goto err_link_base_presence;
  1830. +
  1831. + drvdata->gpio_dgpu_power = gpio_dgpu_power;
  1832. + drvdata->gpio_dgpu_presence = gpio_dgpu_presence;
  1833. + drvdata->gpio_base_presence = gpio_base_presence;
  1834. + return 0;
  1835. +
  1836. +err_link_base_presence:
  1837. + sysfs_remove_link(&pdev->dev.kobj, "gpio-dgpu_presence");
  1838. +err_link_dgpu_presence:
  1839. + sysfs_remove_link(&pdev->dev.kobj, "gpio-dgpu_power");
  1840. +err_link_dgpu_power:
  1841. + gpiod_unexport(gpio_base_presence);
  1842. +err_export_base_presence:
  1843. + gpiod_unexport(gpio_dgpu_presence);
  1844. +err_export_dgpu_presence:
  1845. + gpiod_unexport(gpio_dgpu_power);
  1846. +err_out:
  1847. + return status;
  1848. +}
  1849. +
  1850. +static void shps_gpios_remove(struct platform_device *pdev)
  1851. +{
  1852. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1853. +
  1854. + sysfs_remove_link(&pdev->dev.kobj, "gpio-base_presence");
  1855. + sysfs_remove_link(&pdev->dev.kobj, "gpio-dgpu_presence");
  1856. + sysfs_remove_link(&pdev->dev.kobj, "gpio-dgpu_power");
  1857. + gpiod_unexport(drvdata->gpio_base_presence);
  1858. + gpiod_unexport(drvdata->gpio_dgpu_presence);
  1859. + gpiod_unexport(drvdata->gpio_dgpu_power);
  1860. +}
  1861. +
  1862. +static int shps_gpios_setup_irq(struct platform_device *pdev)
  1863. +{
  1864. + const int irqf_dgpu = IRQF_SHARED | IRQF_ONESHOT | IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING;
  1865. + const int irqf_base = IRQF_SHARED;
  1866. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1867. + int status;
  1868. +
  1869. + status = gpiod_to_irq(drvdata->gpio_base_presence);
  1870. + if (status < 0)
  1871. + return status;
  1872. + drvdata->irq_base_presence = status;
  1873. +
  1874. + status = gpiod_to_irq(drvdata->gpio_dgpu_presence);
  1875. + if (status < 0)
  1876. + return status;
  1877. + drvdata->irq_dgpu_presence = status;
  1878. +
  1879. + status = request_irq(drvdata->irq_base_presence,
  1880. + shps_base_presence_irq, irqf_base,
  1881. + "shps_base_presence_irq", pdev);
  1882. + if (status) {
  1883. + dev_err(&pdev->dev, "base irq failed: %d\n", status);
  1884. + return status;
  1885. + }
  1886. +
  1887. + status = request_threaded_irq(drvdata->irq_dgpu_presence,
  1888. + NULL, shps_dgpu_presence_irq, irqf_dgpu,
  1889. + "shps_dgpu_presence_irq", pdev);
  1890. + if (status) {
  1891. + free_irq(drvdata->irq_base_presence, pdev);
  1892. + return status;
  1893. + }
  1894. +
  1895. + return 0;
  1896. +}
  1897. +
  1898. +static void shps_gpios_remove_irq(struct platform_device *pdev)
  1899. +{
  1900. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1901. +
  1902. + free_irq(drvdata->irq_base_presence, pdev);
  1903. + free_irq(drvdata->irq_dgpu_presence, pdev);
  1904. +}
  1905. +
  1906. +static void shps_sgcp_notify(acpi_handle device, u32 value, void *context) {
  1907. + struct platform_device *pdev = context;
  1908. + switch (value) {
  1909. + case ACPI_SGCP_NOTIFY_POWER_ON:
  1910. + shps_dgpu_powered_on(pdev);
  1911. + }
  1912. +}
  1913. +
  1914. +static int shps_start_sgcp_notification(struct platform_device *pdev, acpi_handle *sgpc_handle) {
  1915. + acpi_handle handle;
  1916. + int status;
  1917. +
  1918. + status = acpi_get_handle(NULL, "\\_SB.SGPC", &handle);
  1919. + if (status) {
  1920. + dev_err(&pdev->dev, "error in get_handle %d\n", status);
  1921. + return status;
  1922. + }
  1923. +
  1924. + status = acpi_install_notify_handler(handle, ACPI_DEVICE_NOTIFY, shps_sgcp_notify, pdev);
  1925. + if (status) {
  1926. + dev_err(&pdev->dev, "error in install notify %d\n", status);
  1927. + *sgpc_handle = NULL;
  1928. + return status;
  1929. + }
  1930. +
  1931. + *sgpc_handle = handle;
  1932. + return 0;
  1933. +}
  1934. +
  1935. +static void shps_remove_sgcp_notification(struct platform_device *pdev) {
  1936. + int status;
  1937. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1938. +
  1939. + if (drvdata->sgpc_handle) {
  1940. + status = acpi_remove_notify_handler(drvdata->sgpc_handle, ACPI_DEVICE_NOTIFY, shps_sgcp_notify);
  1941. + if (status) {
  1942. + dev_err(&pdev->dev, "failed to remove notify handler: %d\n", status);
  1943. + }
  1944. + }
  1945. +}
  1946. +
  1947. +static struct shps_hardware_traits shps_detect_hardware_traits(struct platform_device *pdev) {
  1948. + const struct shps_hardware_probe *p;
  1949. +
  1950. + for (p = shps_hardware_probe_match; p->hardware_id; ++p) {
  1951. + if (acpi_dev_present(p->hardware_id, NULL, -1)) {
  1952. + break;
  1953. + }
  1954. + }
  1955. +
  1956. + dev_info(&pdev->dev,
  1957. + "shps_detect_hardware_traits found device %s, generation %d\n",
  1958. + p->hardware_id ? p->hardware_id : "SAN (default)",
  1959. + p->generation);
  1960. +
  1961. + return *p->hardware_traits;
  1962. +}
  1963. +
  1964. +static int shps_probe(struct platform_device *pdev)
  1965. +{
  1966. + struct acpi_device *shps_dev = ACPI_COMPANION(&pdev->dev);
  1967. + struct shps_driver_data *drvdata;
  1968. + struct device_link *link;
  1969. + int power, status;
  1970. + struct shps_hardware_traits detected_traits;
  1971. +
  1972. + if (gpiod_count(&pdev->dev, NULL) < 0) {
  1973. + dev_err(&pdev->dev, "gpiod_count returned < 0\n");
  1974. + return -ENODEV;
  1975. + }
  1976. +
  1977. + // link to SSH
  1978. + status = surface_sam_ssh_consumer_register(&pdev->dev);
  1979. + if (status) {
  1980. + return status == -ENXIO ? -EPROBE_DEFER : status;
  1981. + }
  1982. +
  1983. + // detect what kind of hardware we're running
  1984. + detected_traits = shps_detect_hardware_traits(pdev);
  1985. +
  1986. + if (detected_traits.notification_method == SHPS_NOTIFICATION_METHOD_SAN) {
  1987. + // link to SAN
  1988. + status = surface_sam_san_consumer_register(&pdev->dev, 0);
  1989. + if (status) {
  1990. + dev_err(&pdev->dev, "failed to register with san consumer: %d\n", status);
  1991. + return status == -ENXIO ? -EPROBE_DEFER : status;
  1992. + }
  1993. + }
  1994. +
  1995. + status = acpi_dev_add_driver_gpios(shps_dev, shps_acpi_gpios);
  1996. + if (status) {
  1997. + dev_err(&pdev->dev, "failed to add gpios: %d\n", status);
  1998. + return status;
  1999. + }
  2000. +
  2001. + drvdata = kzalloc(sizeof(struct shps_driver_data), GFP_KERNEL);
  2002. + if (!drvdata) {
  2003. + status = -ENOMEM;
  2004. + goto err_drvdata;
  2005. + }
  2006. + mutex_init(&drvdata->lock);
  2007. + platform_set_drvdata(pdev, drvdata);
  2008. +
  2009. + drvdata->hardware_traits = detected_traits;
  2010. +
  2011. + drvdata->dgpu_root_port = shps_dgpu_dsm_get_pci_dev(pdev);
  2012. + if (IS_ERR(drvdata->dgpu_root_port)) {
  2013. + status = PTR_ERR(drvdata->dgpu_root_port);
  2014. + dev_err(&pdev->dev, "failed to get pci dev: %d\n", status);
  2015. + goto err_rp_lookup;
  2016. + }
  2017. +
  2018. + status = shps_gpios_setup(pdev);
  2019. + if (status) {
  2020. + dev_err(&pdev->dev, "unable to set up gpios, %d\n", status);
  2021. + goto err_gpio;
  2022. + }
  2023. +
  2024. + status = shps_gpios_setup_irq(pdev);
  2025. + if (status) {
  2026. + dev_err(&pdev->dev, "unable to set up irqs %d\n", status);
  2027. + goto err_gpio_irqs;
  2028. + }
  2029. +
  2030. + status = device_add_groups(&pdev->dev, shps_power_groups);
  2031. + if (status)
  2032. + goto err_devattr;
  2033. +
  2034. + link = device_link_add(&pdev->dev, &drvdata->dgpu_root_port->dev,
  2035. + DL_FLAG_PM_RUNTIME | DL_FLAG_AUTOREMOVE_CONSUMER);
  2036. + if (!link)
  2037. + goto err_devlink;
  2038. +
  2039. + if (detected_traits.notification_method == SHPS_NOTIFICATION_METHOD_SAN) {
  2040. + status = surface_sam_san_set_rqsg_handler(shps_dgpu_handle_rqsg, pdev);
  2041. + if (status) {
  2042. + dev_err(&pdev->dev, "unable to set SAN notification handler (%d)\n", status);
  2043. + goto err_devlink;
  2044. + }
  2045. + } else if (detected_traits.notification_method == SHPS_NOTIFICATION_METHOD_SGCP) {
  2046. + status = shps_start_sgcp_notification(pdev, &drvdata->sgpc_handle);
  2047. + if (status) {
  2048. + dev_err(&pdev->dev, "unable to install SGCP notification handler (%d)\n", status);
  2049. + goto err_devlink;
  2050. + }
  2051. + }
  2052. +
  2053. + // if dGPU is not present turn-off root-port, else obey module param
  2054. + status = shps_dgpu_is_present(pdev);
  2055. + if (status < 0)
  2056. + goto err_post_notification;
  2057. +
  2058. + power = status == 0 ? SHPS_DGPU_POWER_OFF : param_dgpu_power_init;
  2059. + if (power != SHPS_DGPU_MP_POWER_ASIS) {
  2060. + status = shps_dgpu_set_power(pdev, power);
  2061. + if (status)
  2062. + goto err_post_notification;
  2063. + }
  2064. +
  2065. + // initialize power target
  2066. + status = shps_dgpu_rp_get_power(pdev);
  2067. + if (status < 0)
  2068. + goto err_pwrtgt;
  2069. +
  2070. + if (status)
  2071. + set_bit(SHPS_STATE_BIT_PWRTGT, &drvdata->state);
  2072. + else
  2073. + clear_bit(SHPS_STATE_BIT_PWRTGT, &drvdata->state);
  2074. +
  2075. + device_init_wakeup(&pdev->dev, true);
  2076. + return 0;
  2077. +
  2078. +err_pwrtgt:
  2079. + if (param_dgpu_power_exit != SHPS_DGPU_MP_POWER_ASIS) {
  2080. + status = shps_dgpu_set_power(pdev, param_dgpu_power_exit);
  2081. + if (status)
  2082. + dev_err(&pdev->dev, "failed to set dGPU power state: %d\n", status);
  2083. + }
  2084. +err_post_notification:
  2085. + if (detected_traits.notification_method == SHPS_NOTIFICATION_METHOD_SGCP) {
  2086. + shps_remove_sgcp_notification(pdev);
  2087. + } else if (detected_traits.notification_method == SHPS_NOTIFICATION_METHOD_SAN) {
  2088. + surface_sam_san_set_rqsg_handler(NULL, NULL);
  2089. + }
  2090. +err_devlink:
  2091. + device_remove_groups(&pdev->dev, shps_power_groups);
  2092. +err_devattr:
  2093. + shps_gpios_remove_irq(pdev);
  2094. +err_gpio_irqs:
  2095. + shps_gpios_remove(pdev);
  2096. +err_gpio:
  2097. + pci_dev_put(drvdata->dgpu_root_port);
  2098. +err_rp_lookup:
  2099. + platform_set_drvdata(pdev, NULL);
  2100. + kfree(drvdata);
  2101. +err_drvdata:
  2102. + acpi_dev_remove_driver_gpios(shps_dev);
  2103. + return status;
  2104. +}
  2105. +
  2106. +static int shps_remove(struct platform_device *pdev)
  2107. +{
  2108. + struct acpi_device *shps_dev = ACPI_COMPANION(&pdev->dev);
  2109. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  2110. + int status;
  2111. +
  2112. + if (param_dgpu_power_exit != SHPS_DGPU_MP_POWER_ASIS) {
  2113. + status = shps_dgpu_set_power(pdev, param_dgpu_power_exit);
  2114. + if (status)
  2115. + dev_err(&pdev->dev, "failed to set dGPU power state: %d\n", status);
  2116. + }
  2117. +
  2118. + device_set_wakeup_capable(&pdev->dev, false);
  2119. +
  2120. + if (drvdata->hardware_traits.notification_method == SHPS_NOTIFICATION_METHOD_SGCP) {
  2121. + shps_remove_sgcp_notification(pdev);
  2122. + } else if (drvdata->hardware_traits.notification_method == SHPS_NOTIFICATION_METHOD_SAN) {
  2123. + surface_sam_san_set_rqsg_handler(NULL, NULL);
  2124. + }
  2125. + device_remove_groups(&pdev->dev, shps_power_groups);
  2126. + shps_gpios_remove_irq(pdev);
  2127. + shps_gpios_remove(pdev);
  2128. + pci_dev_put(drvdata->dgpu_root_port);
  2129. + platform_set_drvdata(pdev, NULL);
  2130. + kfree(drvdata);
  2131. +
  2132. + acpi_dev_remove_driver_gpios(shps_dev);
  2133. + return 0;
  2134. +}
  2135. +
  2136. +
  2137. +static const struct dev_pm_ops shps_pm_ops = {
  2138. + .prepare = shps_pm_prepare,
  2139. + .complete = shps_pm_complete,
  2140. + .suspend = shps_pm_suspend,
  2141. + .resume = shps_pm_resume,
  2142. +};
  2143. +
  2144. +static const struct acpi_device_id shps_acpi_match[] = {
  2145. + { "MSHW0153", 0 },
  2146. + { },
  2147. +};
  2148. +MODULE_DEVICE_TABLE(acpi, shps_acpi_match);
  2149. +
  2150. +static struct platform_driver surface_sam_hps = {
  2151. + .probe = shps_probe,
  2152. + .remove = shps_remove,
  2153. + .shutdown = shps_shutdown,
  2154. + .driver = {
  2155. + .name = "surface_dgpu_hps",
  2156. + .acpi_match_table = shps_acpi_match,
  2157. + .pm = &shps_pm_ops,
  2158. + },
  2159. +};
  2160. +
  2161. +module_platform_driver(surface_sam_hps);
  2162. +
  2163. +MODULE_AUTHOR("Maximilian Luz <luzmaximilian@gmail.com>");
  2164. +MODULE_DESCRIPTION("Surface Hot-Plug System (HPS) and dGPU power-state Driver for Surface Book 2");
  2165. +MODULE_LICENSE("GPL");
  2166. diff --git a/drivers/platform/x86/surface_sam/surface_sam_san.c b/drivers/platform/x86/surface_sam/surface_sam_san.c
  2167. new file mode 100644
  2168. index 0000000000000..11dd6daedc3dd
  2169. --- /dev/null
  2170. +++ b/drivers/platform/x86/surface_sam/surface_sam_san.c
  2171. @@ -0,0 +1,913 @@
  2172. +// SPDX-License-Identifier: GPL-2.0-or-later
  2173. +/*
  2174. + * Surface ACPI Notify (SAN) and ACPI integration driver for SAM.
  2175. + * Translates communication from ACPI to SSH and back.
  2176. + */
  2177. +
  2178. +#include <linux/acpi.h>
  2179. +#include <linux/delay.h>
  2180. +#include <linux/jiffies.h>
  2181. +#include <linux/kernel.h>
  2182. +#include <linux/platform_device.h>
  2183. +
  2184. +#include "surface_sam_ssh.h"
  2185. +#include "surface_sam_san.h"
  2186. +
  2187. +
  2188. +#define SAN_RQST_RETRY 5
  2189. +
  2190. +#define SAN_DSM_REVISION 0
  2191. +#define SAN_DSM_FN_NOTIFY_SENSOR_TRIP_POINT 0x09
  2192. +
  2193. +static const guid_t SAN_DSM_UUID =
  2194. + GUID_INIT(0x93b666c5, 0x70c6, 0x469f, 0xa2, 0x15, 0x3d,
  2195. + 0x48, 0x7c, 0x91, 0xab, 0x3c);
  2196. +
  2197. +#define SAM_EVENT_DELAY_PWR_ADAPTER msecs_to_jiffies(5000)
  2198. +#define SAM_EVENT_DELAY_PWR_BST msecs_to_jiffies(2500)
  2199. +
  2200. +#define SAM_EVENT_PWR_CID_BIX 0x15
  2201. +#define SAM_EVENT_PWR_CID_BST 0x16
  2202. +#define SAM_EVENT_PWR_CID_ADAPTER 0x17
  2203. +#define SAM_EVENT_PWR_CID_DPTF 0x4f
  2204. +
  2205. +#define SAM_EVENT_TEMP_CID_NOTIFY_SENSOR_TRIP_POINT 0x0b
  2206. +
  2207. +#define SAN_RQST_TAG "surface_sam_san: rqst: "
  2208. +#define SAN_RQSG_TAG "surface_sam_san: rqsg: "
  2209. +
  2210. +#define SAN_QUIRK_BASE_STATE_DELAY 1000
  2211. +
  2212. +
  2213. +struct san_acpi_consumer {
  2214. + char *path;
  2215. + bool required;
  2216. + u32 flags;
  2217. +};
  2218. +
  2219. +struct san_opreg_context {
  2220. + struct acpi_connection_info connection;
  2221. + struct device *dev;
  2222. +};
  2223. +
  2224. +struct san_consumer_link {
  2225. + const struct san_acpi_consumer *properties;
  2226. + struct device_link *link;
  2227. +};
  2228. +
  2229. +struct san_consumers {
  2230. + u32 num;
  2231. + struct san_consumer_link *links;
  2232. +};
  2233. +
  2234. +struct san_drvdata {
  2235. + struct san_opreg_context opreg_ctx;
  2236. + struct san_consumers consumers;
  2237. +
  2238. + struct platform_device *dev;
  2239. + struct ssam_event_notifier nf_bat;
  2240. + struct ssam_event_notifier nf_tmp;
  2241. +};
  2242. +
  2243. +struct san_event_work {
  2244. + struct delayed_work work;
  2245. + struct platform_device *dev;
  2246. + struct ssam_event event; // must be last
  2247. +};
  2248. +
  2249. +struct gsb_data_in {
  2250. + u8 cv;
  2251. +} __packed;
  2252. +
  2253. +struct gsb_data_rqsx {
  2254. + u8 cv; // command value (should be 0x01 or 0x03)
  2255. + u8 tc; // target controller
  2256. + u8 tid; // transport channnel ID?
  2257. + u8 iid; // target sub-controller (e.g. primary vs. secondary battery)
  2258. + u8 snc; // expect-response-flag
  2259. + u8 cid; // command ID
  2260. + u8 cdl; // payload length
  2261. + u8 _pad; // padding
  2262. + u8 pld[0]; // payload
  2263. +} __packed;
  2264. +
  2265. +struct gsb_data_etwl {
  2266. + u8 cv; // command value (should be 0x02)
  2267. + u8 etw3; // ?
  2268. + u8 etw4; // ?
  2269. + u8 msg[0]; // error message (ASCIIZ)
  2270. +} __packed;
  2271. +
  2272. +struct gsb_data_out {
  2273. + u8 status; // _SSH communication status
  2274. + u8 len; // _SSH payload length
  2275. + u8 pld[0]; // _SSH payload
  2276. +} __packed;
  2277. +
  2278. +union gsb_buffer_data {
  2279. + struct gsb_data_in in; // common input
  2280. + struct gsb_data_rqsx rqsx; // RQSX input
  2281. + struct gsb_data_etwl etwl; // ETWL input
  2282. + struct gsb_data_out out; // output
  2283. +};
  2284. +
  2285. +struct gsb_buffer {
  2286. + u8 status; // GSB AttribRawProcess status
  2287. + u8 len; // GSB AttribRawProcess length
  2288. + union gsb_buffer_data data;
  2289. +} __packed;
  2290. +
  2291. +
  2292. +enum san_pwr_event {
  2293. + SAN_PWR_EVENT_BAT1_STAT = 0x03,
  2294. + SAN_PWR_EVENT_BAT1_INFO = 0x04,
  2295. + SAN_PWR_EVENT_ADP1_STAT = 0x05,
  2296. + SAN_PWR_EVENT_ADP1_INFO = 0x06,
  2297. + SAN_PWR_EVENT_BAT2_STAT = 0x07,
  2298. + SAN_PWR_EVENT_BAT2_INFO = 0x08,
  2299. + SAN_PWR_EVENT_DPTF = 0x0A,
  2300. +};
  2301. +
  2302. +
  2303. +static int sam_san_default_rqsg_handler(struct surface_sam_san_rqsg *rqsg, void *data);
  2304. +
  2305. +struct sam_san_rqsg_if {
  2306. + struct mutex lock;
  2307. + struct device *san_dev;
  2308. + surface_sam_san_rqsg_handler_fn handler;
  2309. + void *handler_data;
  2310. +};
  2311. +
  2312. +static struct sam_san_rqsg_if rqsg_if = {
  2313. + .lock = __MUTEX_INITIALIZER(rqsg_if.lock),
  2314. + .san_dev = NULL,
  2315. + .handler = sam_san_default_rqsg_handler,
  2316. + .handler_data = NULL,
  2317. +};
  2318. +
  2319. +int surface_sam_san_consumer_register(struct device *consumer, u32 flags)
  2320. +{
  2321. + const u32 valid = DL_FLAG_PM_RUNTIME | DL_FLAG_RPM_ACTIVE;
  2322. + int status;
  2323. +
  2324. + if ((flags | valid) != valid)
  2325. + return -EINVAL;
  2326. +
  2327. + flags |= DL_FLAG_AUTOREMOVE_CONSUMER;
  2328. +
  2329. + mutex_lock(&rqsg_if.lock);
  2330. + if (rqsg_if.san_dev)
  2331. + status = device_link_add(consumer, rqsg_if.san_dev, flags) ? 0 : -EINVAL;
  2332. + else
  2333. + status = -ENXIO;
  2334. + mutex_unlock(&rqsg_if.lock);
  2335. + return status;
  2336. +}
  2337. +EXPORT_SYMBOL_GPL(surface_sam_san_consumer_register);
  2338. +
  2339. +int surface_sam_san_set_rqsg_handler(surface_sam_san_rqsg_handler_fn fn, void *data)
  2340. +{
  2341. + int status = -EBUSY;
  2342. +
  2343. + mutex_lock(&rqsg_if.lock);
  2344. +
  2345. + if (rqsg_if.handler == sam_san_default_rqsg_handler || !fn) {
  2346. + rqsg_if.handler = fn ? fn : sam_san_default_rqsg_handler;
  2347. + rqsg_if.handler_data = data;
  2348. + status = 0;
  2349. + }
  2350. +
  2351. + mutex_unlock(&rqsg_if.lock);
  2352. + return status;
  2353. +}
  2354. +EXPORT_SYMBOL_GPL(surface_sam_san_set_rqsg_handler);
  2355. +
  2356. +int san_call_rqsg_handler(struct surface_sam_san_rqsg *rqsg)
  2357. +{
  2358. + int status;
  2359. +
  2360. + mutex_lock(&rqsg_if.lock);
  2361. + status = rqsg_if.handler(rqsg, rqsg_if.handler_data);
  2362. + mutex_unlock(&rqsg_if.lock);
  2363. +
  2364. + return status;
  2365. +}
  2366. +
  2367. +static int sam_san_default_rqsg_handler(struct surface_sam_san_rqsg *rqsg, void *data)
  2368. +{
  2369. + pr_warn(SAN_RQSG_TAG "unhandled request: RQSG(0x%02x, 0x%02x, 0x%02x)\n",
  2370. + rqsg->tc, rqsg->cid, rqsg->iid);
  2371. +
  2372. + return 0;
  2373. +}
  2374. +
  2375. +
  2376. +static bool san_acpi_can_notify(struct device *dev, u64 func)
  2377. +{
  2378. + acpi_handle san = ACPI_HANDLE(dev);
  2379. + return acpi_check_dsm(san, &SAN_DSM_UUID, SAN_DSM_REVISION, 1 << func);
  2380. +}
  2381. +
  2382. +static int san_acpi_notify_power_event(struct device *dev, enum san_pwr_event event)
  2383. +{
  2384. + acpi_handle san = ACPI_HANDLE(dev);
  2385. + union acpi_object *obj;
  2386. +
  2387. + if (!san_acpi_can_notify(dev, event))
  2388. + return 0;
  2389. +
  2390. + dev_dbg(dev, "notify power event 0x%02x\n", event);
  2391. + obj = acpi_evaluate_dsm_typed(san, &SAN_DSM_UUID, SAN_DSM_REVISION,
  2392. + event, NULL, ACPI_TYPE_BUFFER);
  2393. +
  2394. + if (IS_ERR_OR_NULL(obj))
  2395. + return obj ? PTR_ERR(obj) : -ENXIO;
  2396. +
  2397. + if (obj->buffer.length != 1 || obj->buffer.pointer[0] != 0) {
  2398. + dev_err(dev, "got unexpected result from _DSM\n");
  2399. + return -EFAULT;
  2400. + }
  2401. +
  2402. + ACPI_FREE(obj);
  2403. + return 0;
  2404. +}
  2405. +
  2406. +static int san_acpi_notify_sensor_trip_point(struct device *dev, u8 iid)
  2407. +{
  2408. + acpi_handle san = ACPI_HANDLE(dev);
  2409. + union acpi_object *obj;
  2410. + union acpi_object param;
  2411. +
  2412. + if (!san_acpi_can_notify(dev, SAN_DSM_FN_NOTIFY_SENSOR_TRIP_POINT))
  2413. + return 0;
  2414. +
  2415. + param.type = ACPI_TYPE_INTEGER;
  2416. + param.integer.value = iid;
  2417. +
  2418. + obj = acpi_evaluate_dsm_typed(san, &SAN_DSM_UUID, SAN_DSM_REVISION,
  2419. + SAN_DSM_FN_NOTIFY_SENSOR_TRIP_POINT,
  2420. + &param, ACPI_TYPE_BUFFER);
  2421. +
  2422. + if (IS_ERR_OR_NULL(obj))
  2423. + return obj ? PTR_ERR(obj) : -ENXIO;
  2424. +
  2425. + if (obj->buffer.length != 1 || obj->buffer.pointer[0] != 0) {
  2426. + dev_err(dev, "got unexpected result from _DSM\n");
  2427. + return -EFAULT;
  2428. + }
  2429. +
  2430. + ACPI_FREE(obj);
  2431. + return 0;
  2432. +}
  2433. +
  2434. +
  2435. +static inline int san_evt_power_adapter(struct device *dev, const struct ssam_event *event)
  2436. +{
  2437. + int status;
  2438. +
  2439. + status = san_acpi_notify_power_event(dev, SAN_PWR_EVENT_ADP1_STAT);
  2440. + if (status)
  2441. + return status;
  2442. +
  2443. + /*
  2444. + * Enusre that the battery states get updated correctly.
  2445. + * When the battery is fully charged and an adapter is plugged in, it
  2446. + * sometimes is not updated correctly, instead showing it as charging.
  2447. + * Explicitly trigger battery updates to fix this.
  2448. + */
  2449. +
  2450. + status = san_acpi_notify_power_event(dev, SAN_PWR_EVENT_BAT1_STAT);
  2451. + if (status)
  2452. + return status;
  2453. +
  2454. + return san_acpi_notify_power_event(dev, SAN_PWR_EVENT_BAT2_STAT);
  2455. +}
  2456. +
  2457. +static inline int san_evt_power_bix(struct device *dev, const struct ssam_event *event)
  2458. +{
  2459. + enum san_pwr_event evcode;
  2460. +
  2461. + if (event->instance_id == 0x02)
  2462. + evcode = SAN_PWR_EVENT_BAT2_INFO;
  2463. + else
  2464. + evcode = SAN_PWR_EVENT_BAT1_INFO;
  2465. +
  2466. + return san_acpi_notify_power_event(dev, evcode);
  2467. +}
  2468. +
  2469. +static inline int san_evt_power_bst(struct device *dev, const struct ssam_event *event)
  2470. +{
  2471. + enum san_pwr_event evcode;
  2472. +
  2473. + if (event->instance_id == 0x02)
  2474. + evcode = SAN_PWR_EVENT_BAT2_STAT;
  2475. + else
  2476. + evcode = SAN_PWR_EVENT_BAT1_STAT;
  2477. +
  2478. + return san_acpi_notify_power_event(dev, evcode);
  2479. +}
  2480. +
  2481. +static inline int san_evt_power_dptf(struct device *dev, const struct ssam_event *event)
  2482. +{
  2483. + union acpi_object payload;
  2484. + acpi_handle san = ACPI_HANDLE(dev);
  2485. + union acpi_object *obj;
  2486. +
  2487. + if (!san_acpi_can_notify(dev, SAN_PWR_EVENT_DPTF))
  2488. + return 0;
  2489. +
  2490. + /*
  2491. + * The Surface ACPI expects a buffer and not a package. It specifically
  2492. + * checks for ObjectType (Arg3) == 0x03. This will cause a warning in
  2493. + * acpica/nsarguments.c, but this can safely be ignored.
  2494. + */
  2495. + payload.type = ACPI_TYPE_BUFFER;
  2496. + payload.buffer.length = event->length;
  2497. + payload.buffer.pointer = (u8 *)&event->data[0];
  2498. +
  2499. + dev_dbg(dev, "notify power event 0x%02x\n", event->command_id);
  2500. + obj = acpi_evaluate_dsm_typed(san, &SAN_DSM_UUID, SAN_DSM_REVISION,
  2501. + SAN_PWR_EVENT_DPTF, &payload,
  2502. + ACPI_TYPE_BUFFER);
  2503. +
  2504. + if (IS_ERR_OR_NULL(obj))
  2505. + return obj ? PTR_ERR(obj) : -ENXIO;
  2506. +
  2507. + if (obj->buffer.length != 1 || obj->buffer.pointer[0] != 0) {
  2508. + dev_err(dev, "got unexpected result from _DSM\n");
  2509. + return -EFAULT;
  2510. + }
  2511. +
  2512. + ACPI_FREE(obj);
  2513. + return 0;
  2514. +}
  2515. +
  2516. +static unsigned long san_evt_power_delay(u8 cid)
  2517. +{
  2518. + switch (cid) {
  2519. + case SAM_EVENT_PWR_CID_ADAPTER:
  2520. + /*
  2521. + * Wait for battery state to update before signalling adapter change.
  2522. + */
  2523. + return SAM_EVENT_DELAY_PWR_ADAPTER;
  2524. +
  2525. + case SAM_EVENT_PWR_CID_BST:
  2526. + /*
  2527. + * Ensure we do not miss anything important due to caching.
  2528. + */
  2529. + return SAM_EVENT_DELAY_PWR_BST;
  2530. +
  2531. + case SAM_EVENT_PWR_CID_BIX:
  2532. + case SAM_EVENT_PWR_CID_DPTF:
  2533. + default:
  2534. + return 0;
  2535. + }
  2536. +}
  2537. +
  2538. +static bool san_evt_power(const struct ssam_event *event, struct device *dev)
  2539. +{
  2540. + int status;
  2541. +
  2542. + switch (event->command_id) {
  2543. + case SAM_EVENT_PWR_CID_BIX:
  2544. + status = san_evt_power_bix(dev, event);
  2545. + break;
  2546. +
  2547. + case SAM_EVENT_PWR_CID_BST:
  2548. + status = san_evt_power_bst(dev, event);
  2549. + break;
  2550. +
  2551. + case SAM_EVENT_PWR_CID_ADAPTER:
  2552. + status = san_evt_power_adapter(dev, event);
  2553. + break;
  2554. +
  2555. + case SAM_EVENT_PWR_CID_DPTF:
  2556. + status = san_evt_power_dptf(dev, event);
  2557. + break;
  2558. +
  2559. + default:
  2560. + return false;
  2561. + }
  2562. +
  2563. + if (status)
  2564. + dev_err(dev, "error handling power event (cid = %x)\n",
  2565. + event->command_id);
  2566. +
  2567. + return true;
  2568. +}
  2569. +
  2570. +static void san_evt_power_workfn(struct work_struct *work)
  2571. +{
  2572. + struct san_event_work *ev = container_of(work, struct san_event_work, work.work);
  2573. +
  2574. + san_evt_power(&ev->event, &ev->dev->dev);
  2575. + kfree(ev);
  2576. +}
  2577. +
  2578. +
  2579. +static u32 san_evt_power_nb(struct ssam_notifier_block *nb, const struct ssam_event *event)
  2580. +{
  2581. + struct san_drvdata *drvdata = container_of(nb, struct san_drvdata, nf_bat.base);
  2582. + struct san_event_work *work;
  2583. + unsigned long delay = san_evt_power_delay(event->command_id);
  2584. +
  2585. + if (delay == 0) {
  2586. + if (san_evt_power(event, &drvdata->dev->dev))
  2587. + return SSAM_NOTIF_HANDLED;
  2588. + else
  2589. + return 0;
  2590. + }
  2591. +
  2592. + work = kzalloc(sizeof(struct san_event_work) + event->length, GFP_KERNEL);
  2593. + if (!work)
  2594. + return ssam_notifier_from_errno(-ENOMEM);
  2595. +
  2596. + INIT_DELAYED_WORK(&work->work, san_evt_power_workfn);
  2597. + work->dev = drvdata->dev;
  2598. +
  2599. + memcpy(&work->event, event, sizeof(struct ssam_event) + event->length);
  2600. +
  2601. + schedule_delayed_work(&work->work, delay);
  2602. + return SSAM_NOTIF_HANDLED;
  2603. +}
  2604. +
  2605. +
  2606. +static inline int san_evt_thermal_notify(struct device *dev, const struct ssam_event *event)
  2607. +{
  2608. + return san_acpi_notify_sensor_trip_point(dev, event->instance_id);
  2609. +}
  2610. +
  2611. +static bool san_evt_thermal(const struct ssam_event *event, struct device *dev)
  2612. +{
  2613. + int status;
  2614. +
  2615. + switch (event->command_id) {
  2616. + case SAM_EVENT_TEMP_CID_NOTIFY_SENSOR_TRIP_POINT:
  2617. + status = san_evt_thermal_notify(dev, event);
  2618. + break;
  2619. +
  2620. + default:
  2621. + return false;
  2622. + }
  2623. +
  2624. + if (status) {
  2625. + dev_err(dev, "error handling thermal event (cid = %x)\n",
  2626. + event->command_id);
  2627. + }
  2628. +
  2629. + return true;
  2630. +}
  2631. +
  2632. +static u32 san_evt_thermal_nb(struct ssam_notifier_block *nb, const struct ssam_event *event)
  2633. +{
  2634. + struct san_drvdata *drvdata = container_of(nb, struct san_drvdata, nf_tmp.base);
  2635. + struct platform_device *pdev = drvdata->dev;
  2636. +
  2637. + if (san_evt_thermal(event, &pdev->dev))
  2638. + return SSAM_NOTIF_HANDLED;
  2639. + else
  2640. + return 0;
  2641. +}
  2642. +
  2643. +
  2644. +static struct gsb_data_rqsx
  2645. +*san_validate_rqsx(struct device *dev, const char *type, struct gsb_buffer *buffer)
  2646. +{
  2647. + struct gsb_data_rqsx *rqsx = &buffer->data.rqsx;
  2648. +
  2649. + if (buffer->len < 8) {
  2650. + dev_err(dev, "invalid %s package (len = %d)\n",
  2651. + type, buffer->len);
  2652. + return NULL;
  2653. + }
  2654. +
  2655. + if (rqsx->cdl != buffer->len - 8) {
  2656. + dev_err(dev, "bogus %s package (len = %d, cdl = %d)\n",
  2657. + type, buffer->len, rqsx->cdl);
  2658. + return NULL;
  2659. + }
  2660. +
  2661. + if (rqsx->tid != 0x01) {
  2662. + dev_warn(dev, "unsupported %s package (tid = 0x%02x)\n",
  2663. + type, rqsx->tid);
  2664. + return NULL;
  2665. + }
  2666. +
  2667. + return rqsx;
  2668. +}
  2669. +
  2670. +static acpi_status
  2671. +san_etwl(struct san_opreg_context *ctx, struct gsb_buffer *buffer)
  2672. +{
  2673. + struct gsb_data_etwl *etwl = &buffer->data.etwl;
  2674. +
  2675. + if (buffer->len < 3) {
  2676. + dev_err(ctx->dev, "invalid ETWL package (len = %d)\n", buffer->len);
  2677. + return AE_OK;
  2678. + }
  2679. +
  2680. + dev_err(ctx->dev, "ETWL(0x%02x, 0x%02x): %.*s\n",
  2681. + etwl->etw3, etwl->etw4,
  2682. + buffer->len - 3, (char *)etwl->msg);
  2683. +
  2684. + // indicate success
  2685. + buffer->status = 0x00;
  2686. + buffer->len = 0x00;
  2687. +
  2688. + return AE_OK;
  2689. +}
  2690. +
  2691. +static acpi_status
  2692. +san_rqst(struct san_opreg_context *ctx, struct gsb_buffer *buffer)
  2693. +{
  2694. + struct gsb_data_rqsx *gsb_rqst = san_validate_rqsx(ctx->dev, "RQST", buffer);
  2695. + struct surface_sam_ssh_rqst rqst = {};
  2696. + struct surface_sam_ssh_buf result = {};
  2697. + int status = 0;
  2698. + int try;
  2699. +
  2700. + if (!gsb_rqst)
  2701. + return AE_OK;
  2702. +
  2703. + rqst.tc = gsb_rqst->tc;
  2704. + rqst.cid = gsb_rqst->cid;
  2705. + rqst.iid = gsb_rqst->iid;
  2706. + rqst.chn = gsb_rqst->tid;
  2707. + rqst.snc = gsb_rqst->snc;
  2708. + rqst.cdl = gsb_rqst->cdl;
  2709. + rqst.pld = &gsb_rqst->pld[0];
  2710. +
  2711. + result.cap = SURFACE_SAM_SSH_MAX_RQST_RESPONSE;
  2712. + result.len = 0;
  2713. + result.data = kzalloc(result.cap, GFP_KERNEL);
  2714. +
  2715. + if (!result.data)
  2716. + return AE_NO_MEMORY;
  2717. +
  2718. + for (try = 0; try < SAN_RQST_RETRY; try++) {
  2719. + if (try)
  2720. + dev_warn(ctx->dev, SAN_RQST_TAG "IO error occurred, trying again\n");
  2721. +
  2722. + status = surface_sam_ssh_rqst(&rqst, &result);
  2723. + if (status != -EIO)
  2724. + break;
  2725. + }
  2726. +
  2727. + if (rqst.tc == 0x11 && rqst.cid == 0x0D && status == -EPERM) {
  2728. + /* Base state quirk:
  2729. + * The base state may be queried from ACPI when the EC is still
  2730. + * suspended. In this case it will return '-EPERM'. This query
  2731. + * will only be triggered from the ACPI lid GPE interrupt, thus
  2732. + * we are either in laptop or studio mode (base status 0x01 or
  2733. + * 0x02). Furthermore, we will only get here if the device (and
  2734. + * EC) have been suspended.
  2735. + *
  2736. + * We now assume that the device is in laptop mode (0x01). This
  2737. + * has the drawback that it will wake the device when unfolding
  2738. + * it in studio mode, but it also allows us to avoid actively
  2739. + * waiting for the EC to wake up, which may incur a notable
  2740. + * delay.
  2741. + */
  2742. +
  2743. + buffer->status = 0x00;
  2744. + buffer->len = 0x03;
  2745. + buffer->data.out.status = 0x00;
  2746. + buffer->data.out.len = 0x01;
  2747. + buffer->data.out.pld[0] = 0x01;
  2748. +
  2749. + } else if (!status) { // success
  2750. + buffer->status = 0x00;
  2751. + buffer->len = result.len + 2;
  2752. + buffer->data.out.status = 0x00;
  2753. + buffer->data.out.len = result.len;
  2754. + memcpy(&buffer->data.out.pld[0], result.data, result.len);
  2755. +
  2756. + } else { // failure
  2757. + dev_err(ctx->dev, SAN_RQST_TAG "failed with error %d\n", status);
  2758. + buffer->status = 0x00;
  2759. + buffer->len = 0x02;
  2760. + buffer->data.out.status = 0x01; // indicate _SSH error
  2761. + buffer->data.out.len = 0x00;
  2762. + }
  2763. +
  2764. + kfree(result.data);
  2765. +
  2766. + return AE_OK;
  2767. +}
  2768. +
  2769. +static acpi_status
  2770. +san_rqsg(struct san_opreg_context *ctx, struct gsb_buffer *buffer)
  2771. +{
  2772. + struct gsb_data_rqsx *gsb_rqsg = san_validate_rqsx(ctx->dev, "RQSG", buffer);
  2773. + struct surface_sam_san_rqsg rqsg = {};
  2774. + int status;
  2775. +
  2776. + if (!gsb_rqsg)
  2777. + return AE_OK;
  2778. +
  2779. + rqsg.tc = gsb_rqsg->tc;
  2780. + rqsg.cid = gsb_rqsg->cid;
  2781. + rqsg.iid = gsb_rqsg->iid;
  2782. + rqsg.cdl = gsb_rqsg->cdl;
  2783. + rqsg.pld = &gsb_rqsg->pld[0];
  2784. +
  2785. + status = san_call_rqsg_handler(&rqsg);
  2786. + if (!status) {
  2787. + buffer->status = 0x00;
  2788. + buffer->len = 0x02;
  2789. + buffer->data.out.status = 0x00;
  2790. + buffer->data.out.len = 0x00;
  2791. + } else {
  2792. + dev_err(ctx->dev, SAN_RQSG_TAG "failed with error %d\n", status);
  2793. + buffer->status = 0x00;
  2794. + buffer->len = 0x02;
  2795. + buffer->data.out.status = 0x01; // indicate _SSH error
  2796. + buffer->data.out.len = 0x00;
  2797. + }
  2798. +
  2799. + return AE_OK;
  2800. +}
  2801. +
  2802. +
  2803. +static acpi_status
  2804. +san_opreg_handler(u32 function, acpi_physical_address command,
  2805. + u32 bits, u64 *value64,
  2806. + void *opreg_context, void *region_context)
  2807. +{
  2808. + struct san_opreg_context *context = opreg_context;
  2809. + struct gsb_buffer *buffer = (struct gsb_buffer *)value64;
  2810. + int accessor_type = (0xFFFF0000 & function) >> 16;
  2811. +
  2812. + if (command != 0) {
  2813. + dev_warn(context->dev, "unsupported command: 0x%02llx\n", command);
  2814. + return AE_OK;
  2815. + }
  2816. +
  2817. + if (accessor_type != ACPI_GSB_ACCESS_ATTRIB_RAW_PROCESS) {
  2818. + dev_err(context->dev, "invalid access type: 0x%02x\n", accessor_type);
  2819. + return AE_OK;
  2820. + }
  2821. +
  2822. + // buffer must have at least contain the command-value
  2823. + if (buffer->len == 0) {
  2824. + dev_err(context->dev, "request-package too small\n");
  2825. + return AE_OK;
  2826. + }
  2827. +
  2828. + switch (buffer->data.in.cv) {
  2829. + case 0x01: return san_rqst(context, buffer);
  2830. + case 0x02: return san_etwl(context, buffer);
  2831. + case 0x03: return san_rqsg(context, buffer);
  2832. + }
  2833. +
  2834. + dev_warn(context->dev, "unsupported SAN0 request (cv: 0x%02x)\n", buffer->data.in.cv);
  2835. + return AE_OK;
  2836. +}
  2837. +
  2838. +static int san_events_register(struct platform_device *pdev)
  2839. +{
  2840. + struct san_drvdata *drvdata = platform_get_drvdata(pdev);
  2841. + int status;
  2842. +
  2843. + drvdata->nf_bat.base.priority = 1;
  2844. + drvdata->nf_bat.base.fn = san_evt_power_nb;
  2845. + drvdata->nf_bat.event.reg = SSAM_EVENT_REGISTRY_SAM;
  2846. + drvdata->nf_bat.event.id.target_category = SSAM_SSH_TC_BAT;
  2847. + drvdata->nf_bat.event.id.instance = 0;
  2848. + drvdata->nf_bat.event.flags = SSAM_EVENT_SEQUENCED;
  2849. +
  2850. + drvdata->nf_tmp.base.priority = 1;
  2851. + drvdata->nf_tmp.base.fn = san_evt_thermal_nb;
  2852. + drvdata->nf_tmp.event.reg = SSAM_EVENT_REGISTRY_SAM;
  2853. + drvdata->nf_tmp.event.id.target_category = SSAM_SSH_TC_TMP;
  2854. + drvdata->nf_tmp.event.id.instance = 0;
  2855. + drvdata->nf_tmp.event.flags = SSAM_EVENT_SEQUENCED;
  2856. +
  2857. + status = surface_sam_ssh_notifier_register(&drvdata->nf_bat);
  2858. + if (status)
  2859. + return status;
  2860. +
  2861. + status = surface_sam_ssh_notifier_register(&drvdata->nf_tmp);
  2862. + if (status)
  2863. + surface_sam_ssh_notifier_unregister(&drvdata->nf_bat);
  2864. +
  2865. + return status;
  2866. +}
  2867. +
  2868. +static void san_events_unregister(struct platform_device *pdev)
  2869. +{
  2870. + struct san_drvdata *drvdata = platform_get_drvdata(pdev);
  2871. +
  2872. + surface_sam_ssh_notifier_unregister(&drvdata->nf_bat);
  2873. + surface_sam_ssh_notifier_unregister(&drvdata->nf_tmp);
  2874. +}
  2875. +
  2876. +
  2877. +static int san_consumers_link(struct platform_device *pdev,
  2878. + const struct san_acpi_consumer *cons,
  2879. + struct san_consumers *out)
  2880. +{
  2881. + const struct san_acpi_consumer *con;
  2882. + struct san_consumer_link *links, *link;
  2883. + struct acpi_device *adev;
  2884. + acpi_handle handle;
  2885. + u32 max_links = 0;
  2886. + int status;
  2887. +
  2888. + if (!cons)
  2889. + return 0;
  2890. +
  2891. + // count links
  2892. + for (con = cons; con->path; ++con)
  2893. + max_links += 1;
  2894. +
  2895. + // allocate
  2896. + links = kcalloc(max_links, sizeof(struct san_consumer_link), GFP_KERNEL);
  2897. + link = &links[0];
  2898. +
  2899. + if (!links)
  2900. + return -ENOMEM;
  2901. +
  2902. + // create links
  2903. + for (con = cons; con->path; ++con) {
  2904. + status = acpi_get_handle(NULL, con->path, &handle);
  2905. + if (status) {
  2906. + if (con->required || status != AE_NOT_FOUND) {
  2907. + status = -ENXIO;
  2908. + goto cleanup;
  2909. + } else {
  2910. + continue;
  2911. + }
  2912. + }
  2913. +
  2914. + status = acpi_bus_get_device(handle, &adev);
  2915. + if (status)
  2916. + goto cleanup;
  2917. +
  2918. + link->link = device_link_add(&adev->dev, &pdev->dev, con->flags);
  2919. + if (!(link->link)) {
  2920. + status = -EFAULT;
  2921. + goto cleanup;
  2922. + }
  2923. + link->properties = con;
  2924. +
  2925. + link += 1;
  2926. + }
  2927. +
  2928. + out->num = link - links;
  2929. + out->links = links;
  2930. +
  2931. + return 0;
  2932. +
  2933. +cleanup:
  2934. + for (link = link - 1; link >= links; --link) {
  2935. + if (link->properties->flags & DL_FLAG_STATELESS)
  2936. + device_link_del(link->link);
  2937. + }
  2938. +
  2939. + return status;
  2940. +}
  2941. +
  2942. +static void san_consumers_unlink(struct san_consumers *consumers)
  2943. +{
  2944. + u32 i;
  2945. +
  2946. + if (!consumers)
  2947. + return;
  2948. +
  2949. + for (i = 0; i < consumers->num; ++i) {
  2950. + if (consumers->links[i].properties->flags & DL_FLAG_STATELESS)
  2951. + device_link_del(consumers->links[i].link);
  2952. + }
  2953. +
  2954. + kfree(consumers->links);
  2955. +
  2956. + consumers->num = 0;
  2957. + consumers->links = NULL;
  2958. +}
  2959. +
  2960. +static int surface_sam_san_probe(struct platform_device *pdev)
  2961. +{
  2962. + const struct san_acpi_consumer *cons;
  2963. + struct san_drvdata *drvdata;
  2964. + acpi_handle san = ACPI_HANDLE(&pdev->dev); // _SAN device node
  2965. + int status;
  2966. +
  2967. + /*
  2968. + * Defer probe if the _SSH driver has not set up the controller yet. This
  2969. + * makes sure we do not fail any initial requests (e.g. _STA request without
  2970. + * which the battery does not get set up correctly). Otherwise register as
  2971. + * consumer to set up a device_link.
  2972. + */
  2973. + status = surface_sam_ssh_consumer_register(&pdev->dev);
  2974. + if (status)
  2975. + return status == -ENXIO ? -EPROBE_DEFER : status;
  2976. +
  2977. + drvdata = kzalloc(sizeof(struct san_drvdata), GFP_KERNEL);
  2978. + if (!drvdata)
  2979. + return -ENOMEM;
  2980. +
  2981. + drvdata->dev = pdev;
  2982. + drvdata->opreg_ctx.dev = &pdev->dev;
  2983. +
  2984. + cons = acpi_device_get_match_data(&pdev->dev);
  2985. + status = san_consumers_link(pdev, cons, &drvdata->consumers);
  2986. + if (status)
  2987. + goto err_consumers;
  2988. +
  2989. + platform_set_drvdata(pdev, drvdata);
  2990. +
  2991. + status = acpi_install_address_space_handler(san,
  2992. + ACPI_ADR_SPACE_GSBUS,
  2993. + &san_opreg_handler,
  2994. + NULL, &drvdata->opreg_ctx);
  2995. +
  2996. + if (ACPI_FAILURE(status)) {
  2997. + status = -ENODEV;
  2998. + goto err_install_handler;
  2999. + }
  3000. +
  3001. + status = san_events_register(pdev);
  3002. + if (status)
  3003. + goto err_enable_events;
  3004. +
  3005. + mutex_lock(&rqsg_if.lock);
  3006. + if (!rqsg_if.san_dev)
  3007. + rqsg_if.san_dev = &pdev->dev;
  3008. + else
  3009. + status = -EBUSY;
  3010. + mutex_unlock(&rqsg_if.lock);
  3011. +
  3012. + if (status)
  3013. + goto err_install_dev;
  3014. +
  3015. + acpi_walk_dep_device_list(san);
  3016. + return 0;
  3017. +
  3018. +err_install_dev:
  3019. + san_events_unregister(pdev);
  3020. +err_enable_events:
  3021. + acpi_remove_address_space_handler(san, ACPI_ADR_SPACE_GSBUS, &san_opreg_handler);
  3022. +err_install_handler:
  3023. + platform_set_drvdata(san, NULL);
  3024. + san_consumers_unlink(&drvdata->consumers);
  3025. +err_consumers:
  3026. + kfree(drvdata);
  3027. + return status;
  3028. +}
  3029. +
  3030. +static int surface_sam_san_remove(struct platform_device *pdev)
  3031. +{
  3032. + struct san_drvdata *drvdata = platform_get_drvdata(pdev);
  3033. + acpi_handle san = ACPI_HANDLE(&pdev->dev); // _SAN device node
  3034. + acpi_status status = AE_OK;
  3035. +
  3036. + mutex_lock(&rqsg_if.lock);
  3037. + rqsg_if.san_dev = NULL;
  3038. + mutex_unlock(&rqsg_if.lock);
  3039. +
  3040. + acpi_remove_address_space_handler(san, ACPI_ADR_SPACE_GSBUS, &san_opreg_handler);
  3041. + san_events_unregister(pdev);
  3042. +
  3043. + /*
  3044. + * We have unregistered our event sources. Now we need to ensure that
  3045. + * all delayed works they may have spawned are run to completion.
  3046. + */
  3047. + flush_scheduled_work();
  3048. +
  3049. + san_consumers_unlink(&drvdata->consumers);
  3050. + kfree(drvdata);
  3051. +
  3052. + platform_set_drvdata(pdev, NULL);
  3053. + return status;
  3054. +}
  3055. +
  3056. +
  3057. +static const struct san_acpi_consumer san_mshw0091_consumers[] = {
  3058. + { "\\_SB.SRTC", true, DL_FLAG_PM_RUNTIME | DL_FLAG_STATELESS },
  3059. + { "\\ADP1", true, DL_FLAG_PM_RUNTIME | DL_FLAG_STATELESS },
  3060. + { "\\_SB.BAT1", true, DL_FLAG_PM_RUNTIME | DL_FLAG_STATELESS },
  3061. + { "\\_SB.BAT2", false, DL_FLAG_PM_RUNTIME | DL_FLAG_STATELESS },
  3062. + { },
  3063. +};
  3064. +
  3065. +static const struct acpi_device_id surface_sam_san_match[] = {
  3066. + { "MSHW0091", (unsigned long) san_mshw0091_consumers },
  3067. + { },
  3068. +};
  3069. +MODULE_DEVICE_TABLE(acpi, surface_sam_san_match);
  3070. +
  3071. +static struct platform_driver surface_sam_san = {
  3072. + .probe = surface_sam_san_probe,
  3073. + .remove = surface_sam_san_remove,
  3074. + .driver = {
  3075. + .name = "surface_sam_san",
  3076. + .acpi_match_table = surface_sam_san_match,
  3077. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  3078. + },
  3079. +};
  3080. +module_platform_driver(surface_sam_san);
  3081. +
  3082. +MODULE_AUTHOR("Maximilian Luz <luzmaximilian@gmail.com>");
  3083. +MODULE_DESCRIPTION("Surface ACPI Notify Driver for 5th Generation Surface Devices");
  3084. +MODULE_LICENSE("GPL");
  3085. diff --git a/drivers/platform/x86/surface_sam/surface_sam_san.h b/drivers/platform/x86/surface_sam/surface_sam_san.h
  3086. new file mode 100644
  3087. index 0000000000000..2b9dee159bbbc
  3088. --- /dev/null
  3089. +++ b/drivers/platform/x86/surface_sam/surface_sam_san.h
  3090. @@ -0,0 +1,30 @@
  3091. +/* SPDX-License-Identifier: GPL-2.0-or-later */
  3092. +/*
  3093. + * Interface for Surface ACPI/Notify (SAN).
  3094. + *
  3095. + * The SAN is the main interface between the Surface Serial Hub (SSH) and the
  3096. + * Surface/System Aggregator Module (SAM). It allows requests to be translated
  3097. + * from ACPI to SSH/SAM. It also interfaces with the discrete GPU hot-plug
  3098. + * driver.
  3099. + */
  3100. +
  3101. +#ifndef _SURFACE_SAM_SAN_H
  3102. +#define _SURFACE_SAM_SAN_H
  3103. +
  3104. +#include <linux/types.h>
  3105. +
  3106. +
  3107. +struct surface_sam_san_rqsg {
  3108. + u8 tc; // target category
  3109. + u8 cid; // command ID
  3110. + u8 iid; // instance ID
  3111. + u8 cdl; // command data length (length of payload)
  3112. + u8 *pld; // pointer to payload of length cdl
  3113. +};
  3114. +
  3115. +typedef int (*surface_sam_san_rqsg_handler_fn)(struct surface_sam_san_rqsg *rqsg, void *data);
  3116. +
  3117. +int surface_sam_san_consumer_register(struct device *consumer, u32 flags);
  3118. +int surface_sam_san_set_rqsg_handler(surface_sam_san_rqsg_handler_fn fn, void *data);
  3119. +
  3120. +#endif /* _SURFACE_SAM_SAN_H */
  3121. diff --git a/drivers/platform/x86/surface_sam/surface_sam_sid.c b/drivers/platform/x86/surface_sam/surface_sam_sid.c
  3122. new file mode 100644
  3123. index 0000000000000..0dae6569b4265
  3124. --- /dev/null
  3125. +++ b/drivers/platform/x86/surface_sam/surface_sam_sid.c
  3126. @@ -0,0 +1,262 @@
  3127. +// SPDX-License-Identifier: GPL-2.0-or-later
  3128. +/*
  3129. + * Surface Integration Driver.
  3130. + * MFD driver to provide device/model dependent functionality.
  3131. + */
  3132. +
  3133. +#include <linux/acpi.h>
  3134. +#include <linux/kernel.h>
  3135. +#include <linux/module.h>
  3136. +#include <linux/platform_device.h>
  3137. +#include <linux/mfd/core.h>
  3138. +
  3139. +#include "surface_sam_sid_power.h"
  3140. +#include "surface_sam_sid_vhf.h"
  3141. +
  3142. +
  3143. +struct ssam_battery_properties ssam_battery_props_bat1 = {
  3144. + .registry = SSAM_EVENT_REGISTRY_SAM,
  3145. + .num = 0,
  3146. + .channel = 1,
  3147. + .instance = 1,
  3148. +};
  3149. +
  3150. +struct ssam_battery_properties ssam_battery_props_bat2_sb3 = {
  3151. + .registry = SSAM_EVENT_REGISTRY_KIP,
  3152. + .num = 1,
  3153. + .channel = 2,
  3154. + .instance = 1,
  3155. +};
  3156. +
  3157. +
  3158. +static const struct ssam_hid_properties ssam_hid_props_sl3 = {
  3159. + .registry = SSAM_EVENT_REGISTRY_REG, // TODO: needs confirmation
  3160. + .instance = 0,
  3161. +};
  3162. +
  3163. +static const struct ssam_hid_properties ssam_hid_props_sb3_keyboard = {
  3164. + .registry = SSAM_EVENT_REGISTRY_REG,
  3165. + .instance = 1,
  3166. +};
  3167. +
  3168. +static const struct ssam_hid_properties ssam_hid_props_sb3_touchpad = {
  3169. + .registry = SSAM_EVENT_REGISTRY_REG,
  3170. + .instance = 3,
  3171. +};
  3172. +
  3173. +static const struct ssam_hid_properties ssam_hid_props_sb3_iid5 = {
  3174. + .registry = SSAM_EVENT_REGISTRY_REG,
  3175. + .instance = 5,
  3176. +};
  3177. +
  3178. +static const struct ssam_hid_properties ssam_hid_props_sb3_iid6 = {
  3179. + .registry = SSAM_EVENT_REGISTRY_REG,
  3180. + .instance = 6,
  3181. +};
  3182. +
  3183. +
  3184. +static const struct mfd_cell sid_devs_sp4[] = {
  3185. + { .name = "surface_sam_sid_gpelid", .id = -1 },
  3186. + { .name = "surface_sam_sid_perfmode", .id = -1 },
  3187. + { },
  3188. +};
  3189. +
  3190. +static const struct mfd_cell sid_devs_sp6[] = {
  3191. + { .name = "surface_sam_sid_gpelid", .id = -1 },
  3192. + { .name = "surface_sam_sid_perfmode", .id = -1 },
  3193. + { },
  3194. +};
  3195. +
  3196. +static const struct mfd_cell sid_devs_sp7[] = {
  3197. + { .name = "surface_sam_sid_gpelid", .id = -1 },
  3198. + { .name = "surface_sam_sid_perfmode", .id = -1 },
  3199. + { .name = "surface_sam_sid_ac", .id = -1 },
  3200. + {
  3201. + .name = "surface_sam_sid_battery",
  3202. + .id = -1,
  3203. + .platform_data = &ssam_battery_props_bat1,
  3204. + .pdata_size = sizeof(struct ssam_battery_properties),
  3205. + },
  3206. + { },
  3207. +};
  3208. +
  3209. +static const struct mfd_cell sid_devs_sb1[] = {
  3210. + { .name = "surface_sam_sid_gpelid", .id = -1 },
  3211. + { },
  3212. +};
  3213. +
  3214. +static const struct mfd_cell sid_devs_sb2[] = {
  3215. + { .name = "surface_sam_sid_gpelid", .id = -1 },
  3216. + { .name = "surface_sam_sid_perfmode", .id = -1 },
  3217. + { },
  3218. +};
  3219. +
  3220. +static const struct mfd_cell sid_devs_sb3[] = {
  3221. + { .name = "surface_sam_sid_gpelid", .id = -1 },
  3222. + { .name = "surface_sam_sid_perfmode", .id = -1 },
  3223. + { .name = "surface_sam_sid_ac", .id = -1 },
  3224. + {
  3225. + .name = "surface_sam_sid_battery",
  3226. + .id = 1,
  3227. + .platform_data = &ssam_battery_props_bat1,
  3228. + .pdata_size = sizeof(struct ssam_battery_properties),
  3229. + },
  3230. + {
  3231. + .name = "surface_sam_sid_battery",
  3232. + .id = 2,
  3233. + .platform_data = &ssam_battery_props_bat2_sb3,
  3234. + .pdata_size = sizeof(struct ssam_battery_properties),
  3235. + },
  3236. + {
  3237. + .name = "surface_sam_sid_vhf",
  3238. + .id = 1,
  3239. + .platform_data = (void *)&ssam_hid_props_sb3_keyboard,
  3240. + .pdata_size = sizeof(struct ssam_hid_properties),
  3241. + },
  3242. + {
  3243. + .name = "surface_sam_sid_vhf",
  3244. + .id = 3,
  3245. + .platform_data = (void *)&ssam_hid_props_sb3_touchpad,
  3246. + .pdata_size = sizeof(struct ssam_hid_properties),
  3247. + },
  3248. + {
  3249. + .name = "surface_sam_sid_vhf",
  3250. + .id = 5,
  3251. + .platform_data = (void *)&ssam_hid_props_sb3_iid5,
  3252. + .pdata_size = sizeof(struct ssam_hid_properties),
  3253. + },
  3254. + {
  3255. + .name = "surface_sam_sid_vhf",
  3256. + .id = 6,
  3257. + .platform_data = (void *)&ssam_hid_props_sb3_iid6,
  3258. + .pdata_size = sizeof(struct ssam_hid_properties),
  3259. + },
  3260. + { },
  3261. +};
  3262. +
  3263. +static const struct mfd_cell sid_devs_sl1[] = {
  3264. + { .name = "surface_sam_sid_gpelid", .id = -1 },
  3265. + { },
  3266. +};
  3267. +
  3268. +static const struct mfd_cell sid_devs_sl2[] = {
  3269. + { .name = "surface_sam_sid_gpelid", .id = -1 },
  3270. + { },
  3271. +};
  3272. +
  3273. +static const struct mfd_cell sid_devs_sl3_13[] = {
  3274. + { .name = "surface_sam_sid_gpelid", .id = -1 },
  3275. + { .name = "surface_sam_sid_perfmode", .id = -1 },
  3276. + { .name = "surface_sam_sid_ac", .id = -1 },
  3277. + {
  3278. + .name = "surface_sam_sid_battery",
  3279. + .id = -1,
  3280. + .platform_data = &ssam_battery_props_bat1,
  3281. + .pdata_size = sizeof(struct ssam_battery_properties),
  3282. + },
  3283. + {
  3284. + .name = "surface_sam_sid_vhf",
  3285. + .id = -1,
  3286. + .platform_data = (void *)&ssam_hid_props_sl3,
  3287. + .pdata_size = sizeof(struct ssam_hid_properties),
  3288. + },
  3289. + { },
  3290. +};
  3291. +
  3292. +static const struct mfd_cell sid_devs_sl3_15[] = {
  3293. + { .name = "surface_sam_sid_perfmode", .id = -1 },
  3294. + { .name = "surface_sam_sid_ac", .id = -1 },
  3295. + {
  3296. + .name = "surface_sam_sid_battery",
  3297. + .id = -1,
  3298. + .platform_data = &ssam_battery_props_bat1,
  3299. + .pdata_size = sizeof(struct ssam_battery_properties),
  3300. + },
  3301. + {
  3302. + .name = "surface_sam_sid_vhf",
  3303. + .id = -1,
  3304. + .platform_data = (void *)&ssam_hid_props_sl3,
  3305. + .pdata_size = sizeof(struct ssam_hid_properties),
  3306. + },
  3307. + { },
  3308. +};
  3309. +
  3310. +static const struct acpi_device_id surface_sam_sid_match[] = {
  3311. + /* Surface Pro 4, 5, and 6 */
  3312. + { "MSHW0081", (unsigned long)sid_devs_sp4 },
  3313. +
  3314. + /* Surface Pro 6 (OMBR >= 0x10) */
  3315. + { "MSHW0111", (unsigned long)sid_devs_sp6 },
  3316. +
  3317. + /* Surface Pro 7 */
  3318. + { "MSHW0116", (unsigned long)sid_devs_sp7 },
  3319. +
  3320. + /* Surface Book 1 */
  3321. + { "MSHW0080", (unsigned long)sid_devs_sb1 },
  3322. +
  3323. + /* Surface Book 2 */
  3324. + { "MSHW0107", (unsigned long)sid_devs_sb2 },
  3325. +
  3326. + /* Surface Book 3 */
  3327. + { "MSHW0117", (unsigned long)sid_devs_sb3 },
  3328. +
  3329. + /* Surface Laptop 1 */
  3330. + { "MSHW0086", (unsigned long)sid_devs_sl1 },
  3331. +
  3332. + /* Surface Laptop 2 */
  3333. + { "MSHW0112", (unsigned long)sid_devs_sl2 },
  3334. +
  3335. + /* Surface Laptop 3 (13") */
  3336. + { "MSHW0114", (unsigned long)sid_devs_sl3_13 },
  3337. +
  3338. + /* Surface Laptop 3 (15") */
  3339. + { "MSHW0110", (unsigned long)sid_devs_sl3_15 },
  3340. +
  3341. + { },
  3342. +};
  3343. +MODULE_DEVICE_TABLE(acpi, surface_sam_sid_match);
  3344. +
  3345. +
  3346. +static int surface_sam_sid_probe(struct platform_device *pdev)
  3347. +{
  3348. + const struct acpi_device_id *match;
  3349. + const struct mfd_cell *cells, *p;
  3350. +
  3351. + match = acpi_match_device(surface_sam_sid_match, &pdev->dev);
  3352. + if (!match)
  3353. + return -ENODEV;
  3354. +
  3355. + cells = (struct mfd_cell *)match->driver_data;
  3356. + if (!cells)
  3357. + return -ENODEV;
  3358. +
  3359. + for (p = cells; p->name; ++p) {
  3360. + /* just count */
  3361. + }
  3362. +
  3363. + if (p == cells)
  3364. + return -ENODEV;
  3365. +
  3366. + return mfd_add_devices(&pdev->dev, 0, cells, p - cells, NULL, 0, NULL);
  3367. +}
  3368. +
  3369. +static int surface_sam_sid_remove(struct platform_device *pdev)
  3370. +{
  3371. + mfd_remove_devices(&pdev->dev);
  3372. + return 0;
  3373. +}
  3374. +
  3375. +static struct platform_driver surface_sam_sid = {
  3376. + .probe = surface_sam_sid_probe,
  3377. + .remove = surface_sam_sid_remove,
  3378. + .driver = {
  3379. + .name = "surface_sam_sid",
  3380. + .acpi_match_table = surface_sam_sid_match,
  3381. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  3382. + },
  3383. +};
  3384. +module_platform_driver(surface_sam_sid);
  3385. +
  3386. +MODULE_AUTHOR("Maximilian Luz <luzmaximilian@gmail.com>");
  3387. +MODULE_DESCRIPTION("Surface Integration Driver for 5th Generation Surface Devices");
  3388. +MODULE_LICENSE("GPL");
  3389. diff --git a/drivers/platform/x86/surface_sam/surface_sam_sid_gpelid.c b/drivers/platform/x86/surface_sam/surface_sam_sid_gpelid.c
  3390. new file mode 100644
  3391. index 0000000000000..f0cee43c859b4
  3392. --- /dev/null
  3393. +++ b/drivers/platform/x86/surface_sam/surface_sam_sid_gpelid.c
  3394. @@ -0,0 +1,232 @@
  3395. +// SPDX-License-Identifier: GPL-2.0-or-later
  3396. +/*
  3397. + * Surface Lid driver to enable wakeup from suspend via the lid.
  3398. + */
  3399. +
  3400. +#include <linux/acpi.h>
  3401. +#include <linux/dmi.h>
  3402. +#include <linux/kernel.h>
  3403. +#include <linux/module.h>
  3404. +#include <linux/platform_device.h>
  3405. +
  3406. +
  3407. +struct sid_lid_device {
  3408. + const char *acpi_path;
  3409. + const u32 gpe_number;
  3410. +};
  3411. +
  3412. +
  3413. +static const struct sid_lid_device lid_device_l17 = {
  3414. + .acpi_path = "\\_SB.LID0",
  3415. + .gpe_number = 0x17,
  3416. +};
  3417. +
  3418. +static const struct sid_lid_device lid_device_l4D = {
  3419. + .acpi_path = "\\_SB.LID0",
  3420. + .gpe_number = 0x4D,
  3421. +};
  3422. +
  3423. +static const struct sid_lid_device lid_device_l4F = {
  3424. + .acpi_path = "\\_SB.LID0",
  3425. + .gpe_number = 0x4F,
  3426. +};
  3427. +
  3428. +static const struct sid_lid_device lid_device_l57 = {
  3429. + .acpi_path = "\\_SB.LID0",
  3430. + .gpe_number = 0x57,
  3431. +};
  3432. +
  3433. +
  3434. +static const struct dmi_system_id dmi_lid_device_table[] = {
  3435. + {
  3436. + .ident = "Surface Pro 4",
  3437. + .matches = {
  3438. + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"),
  3439. + DMI_EXACT_MATCH(DMI_PRODUCT_NAME, "Surface Pro 4"),
  3440. + },
  3441. + .driver_data = (void *)&lid_device_l17,
  3442. + },
  3443. + {
  3444. + .ident = "Surface Pro 5",
  3445. + .matches = {
  3446. + /* match for SKU here due to generic product name "Surface Pro" */
  3447. + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"),
  3448. + DMI_EXACT_MATCH(DMI_PRODUCT_SKU, "Surface_Pro_1796"),
  3449. + },
  3450. + .driver_data = (void *)&lid_device_l4F,
  3451. + },
  3452. + {
  3453. + .ident = "Surface Pro 5 (LTE)",
  3454. + .matches = {
  3455. + /* match for SKU here due to generic product name "Surface Pro" */
  3456. + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"),
  3457. + DMI_EXACT_MATCH(DMI_PRODUCT_SKU, "Surface_Pro_1807"),
  3458. + },
  3459. + .driver_data = (void *)&lid_device_l4F,
  3460. + },
  3461. + {
  3462. + .ident = "Surface Pro 6",
  3463. + .matches = {
  3464. + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"),
  3465. + DMI_EXACT_MATCH(DMI_PRODUCT_NAME, "Surface Pro 6"),
  3466. + },
  3467. + .driver_data = (void *)&lid_device_l4F,
  3468. + },
  3469. + {
  3470. + .ident = "Surface Pro 7",
  3471. + .matches = {
  3472. + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"),
  3473. + DMI_EXACT_MATCH(DMI_PRODUCT_NAME, "Surface Pro 7"),
  3474. + },
  3475. + .driver_data = (void *)&lid_device_l4D,
  3476. + },
  3477. + {
  3478. + .ident = "Surface Book 1",
  3479. + .matches = {
  3480. + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"),
  3481. + DMI_EXACT_MATCH(DMI_PRODUCT_NAME, "Surface Book"),
  3482. + },
  3483. + .driver_data = (void *)&lid_device_l17,
  3484. + },
  3485. + {
  3486. + .ident = "Surface Book 2",
  3487. + .matches = {
  3488. + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"),
  3489. + DMI_EXACT_MATCH(DMI_PRODUCT_NAME, "Surface Book 2"),
  3490. + },
  3491. + .driver_data = (void *)&lid_device_l17,
  3492. + },
  3493. + {
  3494. + .ident = "Surface Book 3",
  3495. + .matches = {
  3496. + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"),
  3497. + DMI_EXACT_MATCH(DMI_PRODUCT_NAME, "Surface Book 3"),
  3498. + },
  3499. + .driver_data = (void *)&lid_device_l4D,
  3500. + },
  3501. + {
  3502. + .ident = "Surface Laptop 1",
  3503. + .matches = {
  3504. + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"),
  3505. + DMI_EXACT_MATCH(DMI_PRODUCT_NAME, "Surface Laptop"),
  3506. + },
  3507. + .driver_data = (void *)&lid_device_l57,
  3508. + },
  3509. + {
  3510. + .ident = "Surface Laptop 2",
  3511. + .matches = {
  3512. + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"),
  3513. + DMI_EXACT_MATCH(DMI_PRODUCT_NAME, "Surface Laptop 2"),
  3514. + },
  3515. + .driver_data = (void *)&lid_device_l57,
  3516. + },
  3517. + {
  3518. + .ident = "Surface Laptop 3 (13\")",
  3519. + .matches = {
  3520. + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"),
  3521. + DMI_EXACT_MATCH(DMI_PRODUCT_SKU, "Surface_Laptop_3_1867:1868"),
  3522. + },
  3523. + .driver_data = (void *)&lid_device_l4D,
  3524. + },
  3525. + { }
  3526. +};
  3527. +
  3528. +
  3529. +static int sid_lid_enable_wakeup(const struct sid_lid_device *dev, bool enable)
  3530. +{
  3531. + int action = enable ? ACPI_GPE_ENABLE : ACPI_GPE_DISABLE;
  3532. + int status;
  3533. +
  3534. + status = acpi_set_gpe_wake_mask(NULL, dev->gpe_number, action);
  3535. + if (status)
  3536. + return -EFAULT;
  3537. +
  3538. + return 0;
  3539. +}
  3540. +
  3541. +
  3542. +static int surface_sam_sid_gpelid_suspend(struct device *dev)
  3543. +{
  3544. + const struct sid_lid_device *ldev;
  3545. +
  3546. + ldev = dev_get_drvdata(dev);
  3547. + return sid_lid_enable_wakeup(ldev, true);
  3548. +}
  3549. +
  3550. +static int surface_sam_sid_gpelid_resume(struct device *dev)
  3551. +{
  3552. + const struct sid_lid_device *ldev;
  3553. +
  3554. + ldev = dev_get_drvdata(dev);
  3555. + return sid_lid_enable_wakeup(ldev, false);
  3556. +}
  3557. +
  3558. +static SIMPLE_DEV_PM_OPS(surface_sam_sid_gpelid_pm,
  3559. + surface_sam_sid_gpelid_suspend,
  3560. + surface_sam_sid_gpelid_resume);
  3561. +
  3562. +
  3563. +static int surface_sam_sid_gpelid_probe(struct platform_device *pdev)
  3564. +{
  3565. + const struct dmi_system_id *match;
  3566. + struct sid_lid_device *dev;
  3567. + acpi_handle lid_handle;
  3568. + int status;
  3569. +
  3570. + match = dmi_first_match(dmi_lid_device_table);
  3571. + if (!match)
  3572. + return -ENODEV;
  3573. +
  3574. + dev = match->driver_data;
  3575. + if (!dev)
  3576. + return -ENODEV;
  3577. +
  3578. + status = acpi_get_handle(NULL, (acpi_string)dev->acpi_path, &lid_handle);
  3579. + if (status)
  3580. + return -EFAULT;
  3581. +
  3582. + status = acpi_setup_gpe_for_wake(lid_handle, NULL, dev->gpe_number);
  3583. + if (status)
  3584. + return -EFAULT;
  3585. +
  3586. + status = acpi_enable_gpe(NULL, dev->gpe_number);
  3587. + if (status)
  3588. + return -EFAULT;
  3589. +
  3590. + status = sid_lid_enable_wakeup(dev, false);
  3591. + if (status) {
  3592. + acpi_disable_gpe(NULL, dev->gpe_number);
  3593. + return status;
  3594. + }
  3595. +
  3596. + platform_set_drvdata(pdev, dev);
  3597. + return 0;
  3598. +}
  3599. +
  3600. +static int surface_sam_sid_gpelid_remove(struct platform_device *pdev)
  3601. +{
  3602. + struct sid_lid_device *dev = platform_get_drvdata(pdev);
  3603. +
  3604. + /* restore default behavior without this module */
  3605. + sid_lid_enable_wakeup(dev, false);
  3606. + acpi_disable_gpe(NULL, dev->gpe_number);
  3607. +
  3608. + platform_set_drvdata(pdev, NULL);
  3609. + return 0;
  3610. +}
  3611. +
  3612. +static struct platform_driver surface_sam_sid_gpelid = {
  3613. + .probe = surface_sam_sid_gpelid_probe,
  3614. + .remove = surface_sam_sid_gpelid_remove,
  3615. + .driver = {
  3616. + .name = "surface_sam_sid_gpelid",
  3617. + .pm = &surface_sam_sid_gpelid_pm,
  3618. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  3619. + },
  3620. +};
  3621. +module_platform_driver(surface_sam_sid_gpelid);
  3622. +
  3623. +MODULE_AUTHOR("Maximilian Luz <luzmaximilian@gmail.com>");
  3624. +MODULE_DESCRIPTION("Surface Lid Driver for 5th Generation Surface Devices");
  3625. +MODULE_LICENSE("GPL");
  3626. +MODULE_ALIAS("platform:surface_sam_sid_gpelid");
  3627. diff --git a/drivers/platform/x86/surface_sam/surface_sam_sid_perfmode.c b/drivers/platform/x86/surface_sam/surface_sam_sid_perfmode.c
  3628. new file mode 100644
  3629. index 0000000000000..2e11efb166f2b
  3630. --- /dev/null
  3631. +++ b/drivers/platform/x86/surface_sam/surface_sam_sid_perfmode.c
  3632. @@ -0,0 +1,216 @@
  3633. +// SPDX-License-Identifier: GPL-2.0-or-later
  3634. +/*
  3635. + * Surface Performance Mode Driver.
  3636. + * Allows to change cooling capabilities based on user preference.
  3637. + */
  3638. +
  3639. +#include <asm/unaligned.h>
  3640. +#include <linux/kernel.h>
  3641. +#include <linux/module.h>
  3642. +#include <linux/platform_device.h>
  3643. +
  3644. +#include "surface_sam_ssh.h"
  3645. +
  3646. +
  3647. +#define SID_PARAM_PERM 0644
  3648. +
  3649. +enum sam_perf_mode {
  3650. + SAM_PERF_MODE_NORMAL = 1,
  3651. + SAM_PERF_MODE_BATTERY = 2,
  3652. + SAM_PERF_MODE_PERF1 = 3,
  3653. + SAM_PERF_MODE_PERF2 = 4,
  3654. +
  3655. + __SAM_PERF_MODE__START = 1,
  3656. + __SAM_PERF_MODE__END = 4,
  3657. +};
  3658. +
  3659. +enum sid_param_perf_mode {
  3660. + SID_PARAM_PERF_MODE_AS_IS = 0,
  3661. + SID_PARAM_PERF_MODE_NORMAL = SAM_PERF_MODE_NORMAL,
  3662. + SID_PARAM_PERF_MODE_BATTERY = SAM_PERF_MODE_BATTERY,
  3663. + SID_PARAM_PERF_MODE_PERF1 = SAM_PERF_MODE_PERF1,
  3664. + SID_PARAM_PERF_MODE_PERF2 = SAM_PERF_MODE_PERF2,
  3665. +
  3666. + __SID_PARAM_PERF_MODE__START = 0,
  3667. + __SID_PARAM_PERF_MODE__END = 4,
  3668. +};
  3669. +
  3670. +
  3671. +static int surface_sam_perf_mode_get(void)
  3672. +{
  3673. + u8 result_buf[8] = { 0 };
  3674. + int status;
  3675. +
  3676. + struct surface_sam_ssh_rqst rqst = {
  3677. + .tc = 0x03,
  3678. + .cid = 0x02,
  3679. + .iid = 0x00,
  3680. + .chn = 0x01,
  3681. + .snc = 0x01,
  3682. + .cdl = 0x00,
  3683. + .pld = NULL,
  3684. + };
  3685. +
  3686. + struct surface_sam_ssh_buf result = {
  3687. + .cap = ARRAY_SIZE(result_buf),
  3688. + .len = 0,
  3689. + .data = result_buf,
  3690. + };
  3691. +
  3692. + status = surface_sam_ssh_rqst(&rqst, &result);
  3693. + if (status)
  3694. + return status;
  3695. +
  3696. + if (result.len != 8)
  3697. + return -EFAULT;
  3698. +
  3699. + return get_unaligned_le32(&result.data[0]);
  3700. +}
  3701. +
  3702. +static int surface_sam_perf_mode_set(int perf_mode)
  3703. +{
  3704. + u8 payload[4] = { 0 };
  3705. +
  3706. + struct surface_sam_ssh_rqst rqst = {
  3707. + .tc = 0x03,
  3708. + .cid = 0x03,
  3709. + .iid = 0x00,
  3710. + .chn = 0x01,
  3711. + .snc = 0x00,
  3712. + .cdl = ARRAY_SIZE(payload),
  3713. + .pld = payload,
  3714. + };
  3715. +
  3716. + if (perf_mode < __SAM_PERF_MODE__START || perf_mode > __SAM_PERF_MODE__END)
  3717. + return -EINVAL;
  3718. +
  3719. + put_unaligned_le32(perf_mode, &rqst.pld[0]);
  3720. + return surface_sam_ssh_rqst(&rqst, NULL);
  3721. +}
  3722. +
  3723. +
  3724. +static int param_perf_mode_set(const char *val, const struct kernel_param *kp)
  3725. +{
  3726. + int perf_mode;
  3727. + int status;
  3728. +
  3729. + status = kstrtoint(val, 0, &perf_mode);
  3730. + if (status)
  3731. + return status;
  3732. +
  3733. + if (perf_mode < __SID_PARAM_PERF_MODE__START || perf_mode > __SID_PARAM_PERF_MODE__END)
  3734. + return -EINVAL;
  3735. +
  3736. + return param_set_int(val, kp);
  3737. +}
  3738. +
  3739. +static const struct kernel_param_ops param_perf_mode_ops = {
  3740. + .set = param_perf_mode_set,
  3741. + .get = param_get_int,
  3742. +};
  3743. +
  3744. +static int param_perf_mode_init = SID_PARAM_PERF_MODE_AS_IS;
  3745. +static int param_perf_mode_exit = SID_PARAM_PERF_MODE_AS_IS;
  3746. +
  3747. +module_param_cb(perf_mode_init, &param_perf_mode_ops, &param_perf_mode_init, SID_PARAM_PERM);
  3748. +module_param_cb(perf_mode_exit, &param_perf_mode_ops, &param_perf_mode_exit, SID_PARAM_PERM);
  3749. +
  3750. +MODULE_PARM_DESC(perf_mode_init, "Performance-mode to be set on module initialization");
  3751. +MODULE_PARM_DESC(perf_mode_exit, "Performance-mode to be set on module exit");
  3752. +
  3753. +
  3754. +static ssize_t perf_mode_show(struct device *dev, struct device_attribute *attr, char *data)
  3755. +{
  3756. + int perf_mode;
  3757. +
  3758. + perf_mode = surface_sam_perf_mode_get();
  3759. + if (perf_mode < 0) {
  3760. + dev_err(dev, "failed to get current performance mode: %d\n", perf_mode);
  3761. + return -EIO;
  3762. + }
  3763. +
  3764. + return sprintf(data, "%d\n", perf_mode);
  3765. +}
  3766. +
  3767. +static ssize_t perf_mode_store(struct device *dev, struct device_attribute *attr,
  3768. + const char *data, size_t count)
  3769. +{
  3770. + int perf_mode;
  3771. + int status;
  3772. +
  3773. + status = kstrtoint(data, 0, &perf_mode);
  3774. + if (status)
  3775. + return status;
  3776. +
  3777. + status = surface_sam_perf_mode_set(perf_mode);
  3778. + if (status)
  3779. + return status;
  3780. +
  3781. + // TODO: Should we notify ACPI here?
  3782. + //
  3783. + // There is a _DSM call described as
  3784. + // WSID._DSM: Notify DPTF on Slider State change
  3785. + // which calls
  3786. + // ODV3 = ToInteger (Arg3)
  3787. + // Notify(IETM, 0x88)
  3788. + // IETM is an INT3400 Intel Dynamic Power Performance Management
  3789. + // device, part of the DPTF framework. From the corresponding
  3790. + // kernel driver, it looks like event 0x88 is being ignored. Also
  3791. + // it is currently unknown what the consequecnes of setting ODV3
  3792. + // are.
  3793. +
  3794. + return count;
  3795. +}
  3796. +
  3797. +static const DEVICE_ATTR_RW(perf_mode);
  3798. +
  3799. +
  3800. +static int surface_sam_sid_perfmode_probe(struct platform_device *pdev)
  3801. +{
  3802. + int status;
  3803. +
  3804. + // link to ec
  3805. + status = surface_sam_ssh_consumer_register(&pdev->dev);
  3806. + if (status)
  3807. + return status == -ENXIO ? -EPROBE_DEFER : status;
  3808. +
  3809. + // set initial perf_mode
  3810. + if (param_perf_mode_init != SID_PARAM_PERF_MODE_AS_IS) {
  3811. + status = surface_sam_perf_mode_set(param_perf_mode_init);
  3812. + if (status)
  3813. + return status;
  3814. + }
  3815. +
  3816. + // register perf_mode attribute
  3817. + status = sysfs_create_file(&pdev->dev.kobj, &dev_attr_perf_mode.attr);
  3818. + if (status)
  3819. + goto err_sysfs;
  3820. +
  3821. + return 0;
  3822. +
  3823. +err_sysfs:
  3824. + surface_sam_perf_mode_set(param_perf_mode_exit);
  3825. + return status;
  3826. +}
  3827. +
  3828. +static int surface_sam_sid_perfmode_remove(struct platform_device *pdev)
  3829. +{
  3830. + sysfs_remove_file(&pdev->dev.kobj, &dev_attr_perf_mode.attr);
  3831. + surface_sam_perf_mode_set(param_perf_mode_exit);
  3832. + return 0;
  3833. +}
  3834. +
  3835. +static struct platform_driver surface_sam_sid_perfmode = {
  3836. + .probe = surface_sam_sid_perfmode_probe,
  3837. + .remove = surface_sam_sid_perfmode_remove,
  3838. + .driver = {
  3839. + .name = "surface_sam_sid_perfmode",
  3840. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  3841. + },
  3842. +};
  3843. +module_platform_driver(surface_sam_sid_perfmode);
  3844. +
  3845. +MODULE_AUTHOR("Maximilian Luz <luzmaximilian@gmail.com>");
  3846. +MODULE_DESCRIPTION("Surface Performance Mode Driver for 5th Generation Surface Devices");
  3847. +MODULE_LICENSE("GPL");
  3848. +MODULE_ALIAS("platform:surface_sam_sid_perfmode");
  3849. diff --git a/drivers/platform/x86/surface_sam/surface_sam_sid_power.c b/drivers/platform/x86/surface_sam/surface_sam_sid_power.c
  3850. new file mode 100644
  3851. index 0000000000000..1d945c0a911a4
  3852. --- /dev/null
  3853. +++ b/drivers/platform/x86/surface_sam/surface_sam_sid_power.c
  3854. @@ -0,0 +1,1154 @@
  3855. +// SPDX-License-Identifier: GPL-2.0-or-later
  3856. +/*
  3857. + * Surface SID Battery/AC Driver.
  3858. + * Provides support for the battery and AC on 7th generation Surface devices.
  3859. + */
  3860. +
  3861. +#include <linux/kernel.h>
  3862. +#include <linux/delay.h>
  3863. +#include <linux/jiffies.h>
  3864. +#include <linux/module.h>
  3865. +#include <linux/platform_device.h>
  3866. +#include <linux/power_supply.h>
  3867. +#include <linux/workqueue.h>
  3868. +
  3869. +#include "surface_sam_ssh.h"
  3870. +#include "surface_sam_sid_power.h"
  3871. +
  3872. +#define SPWR_WARN KERN_WARNING KBUILD_MODNAME ": "
  3873. +#define SPWR_DEBUG KERN_DEBUG KBUILD_MODNAME ": "
  3874. +
  3875. +
  3876. +// TODO: check BIX/BST for unknown/unsupported 0xffffffff entries
  3877. +// TODO: DPTF (/SAN notifications)?
  3878. +// TODO: other properties?
  3879. +
  3880. +
  3881. +static unsigned int cache_time = 1000;
  3882. +module_param(cache_time, uint, 0644);
  3883. +MODULE_PARM_DESC(cache_time, "battery state chaching time in milliseconds [default: 1000]");
  3884. +
  3885. +#define SPWR_AC_BAT_UPDATE_DELAY msecs_to_jiffies(5000)
  3886. +
  3887. +
  3888. +/*
  3889. + * SAM Interface.
  3890. + */
  3891. +
  3892. +#define SAM_PWR_TC 0x02
  3893. +
  3894. +#define SAM_RQST_PWR_CID_STA 0x01
  3895. +#define SAM_RQST_PWR_CID_BIX 0x02
  3896. +#define SAM_RQST_PWR_CID_BST 0x03
  3897. +#define SAM_RQST_PWR_CID_BTP 0x04
  3898. +
  3899. +#define SAM_RQST_PWR_CID_PMAX 0x0b
  3900. +#define SAM_RQST_PWR_CID_PSOC 0x0c
  3901. +#define SAM_RQST_PWR_CID_PSRC 0x0d
  3902. +#define SAM_RQST_PWR_CID_CHGI 0x0e
  3903. +#define SAM_RQST_PWR_CID_ARTG 0x0f
  3904. +
  3905. +#define SAM_EVENT_PWR_CID_BIX 0x15
  3906. +#define SAM_EVENT_PWR_CID_BST 0x16
  3907. +#define SAM_EVENT_PWR_CID_ADAPTER 0x17
  3908. +
  3909. +#define SAM_BATTERY_STA_OK 0x0f
  3910. +#define SAM_BATTERY_STA_PRESENT 0x10
  3911. +
  3912. +#define SAM_BATTERY_STATE_DISCHARGING 0x01
  3913. +#define SAM_BATTERY_STATE_CHARGING 0x02
  3914. +#define SAM_BATTERY_STATE_CRITICAL 0x04
  3915. +
  3916. +#define SAM_BATTERY_POWER_UNIT_MA 1
  3917. +
  3918. +
  3919. +/* Equivalent to data returned in ACPI _BIX method */
  3920. +struct spwr_bix {
  3921. + u8 revision;
  3922. + u32 power_unit;
  3923. + u32 design_cap;
  3924. + u32 last_full_charge_cap;
  3925. + u32 technology;
  3926. + u32 design_voltage;
  3927. + u32 design_cap_warn;
  3928. + u32 design_cap_low;
  3929. + u32 cycle_count;
  3930. + u32 measurement_accuracy;
  3931. + u32 max_sampling_time;
  3932. + u32 min_sampling_time;
  3933. + u32 max_avg_interval;
  3934. + u32 min_avg_interval;
  3935. + u32 bat_cap_granularity_1;
  3936. + u32 bat_cap_granularity_2;
  3937. + u8 model[21];
  3938. + u8 serial[11];
  3939. + u8 type[5];
  3940. + u8 oem_info[21];
  3941. +} __packed;
  3942. +
  3943. +/* Equivalent to data returned in ACPI _BST method */
  3944. +struct spwr_bst {
  3945. + u32 state;
  3946. + u32 present_rate;
  3947. + u32 remaining_cap;
  3948. + u32 present_voltage;
  3949. +} __packed;
  3950. +
  3951. +/* DPTF event payload */
  3952. +struct spwr_event_dptf {
  3953. + u32 pmax;
  3954. + u32 _1; /* currently unknown */
  3955. + u32 _2; /* currently unknown */
  3956. +} __packed;
  3957. +
  3958. +
  3959. +/* Get battery status (_STA) */
  3960. +static int sam_psy_get_sta(u8 channel, u8 instance, u32 *sta)
  3961. +{
  3962. + struct surface_sam_ssh_rqst rqst;
  3963. + struct surface_sam_ssh_buf result;
  3964. +
  3965. + rqst.tc = SAM_PWR_TC;
  3966. + rqst.cid = SAM_RQST_PWR_CID_STA;
  3967. + rqst.iid = instance;
  3968. + rqst.chn = channel;
  3969. + rqst.snc = 0x01;
  3970. + rqst.cdl = 0x00;
  3971. + rqst.pld = NULL;
  3972. +
  3973. + result.cap = sizeof(u32);
  3974. + result.len = 0;
  3975. + result.data = (u8 *)sta;
  3976. +
  3977. + return surface_sam_ssh_rqst(&rqst, &result);
  3978. +}
  3979. +
  3980. +/* Get battery static information (_BIX) */
  3981. +static int sam_psy_get_bix(u8 channel, u8 instance, struct spwr_bix *bix)
  3982. +{
  3983. + struct surface_sam_ssh_rqst rqst;
  3984. + struct surface_sam_ssh_buf result;
  3985. +
  3986. + rqst.tc = SAM_PWR_TC;
  3987. + rqst.cid = SAM_RQST_PWR_CID_BIX;
  3988. + rqst.iid = instance;
  3989. + rqst.chn = channel;
  3990. + rqst.snc = 0x01;
  3991. + rqst.cdl = 0x00;
  3992. + rqst.pld = NULL;
  3993. +
  3994. + result.cap = sizeof(struct spwr_bix);
  3995. + result.len = 0;
  3996. + result.data = (u8 *)bix;
  3997. +
  3998. + return surface_sam_ssh_rqst(&rqst, &result);
  3999. +}
  4000. +
  4001. +/* Get battery dynamic information (_BST) */
  4002. +static int sam_psy_get_bst(u8 channel, u8 instance, struct spwr_bst *bst)
  4003. +{
  4004. + struct surface_sam_ssh_rqst rqst;
  4005. + struct surface_sam_ssh_buf result;
  4006. +
  4007. + rqst.tc = SAM_PWR_TC;
  4008. + rqst.cid = SAM_RQST_PWR_CID_BST;
  4009. + rqst.iid = instance;
  4010. + rqst.chn = channel;
  4011. + rqst.snc = 0x01;
  4012. + rqst.cdl = 0x00;
  4013. + rqst.pld = NULL;
  4014. +
  4015. + result.cap = sizeof(struct spwr_bst);
  4016. + result.len = 0;
  4017. + result.data = (u8 *)bst;
  4018. +
  4019. + return surface_sam_ssh_rqst(&rqst, &result);
  4020. +}
  4021. +
  4022. +/* Set battery trip point (_BTP) */
  4023. +static int sam_psy_set_btp(u8 channel, u8 instance, u32 btp)
  4024. +{
  4025. + struct surface_sam_ssh_rqst rqst;
  4026. +
  4027. + rqst.tc = SAM_PWR_TC;
  4028. + rqst.cid = SAM_RQST_PWR_CID_BTP;
  4029. + rqst.iid = instance;
  4030. + rqst.chn = channel;
  4031. + rqst.snc = 0x00;
  4032. + rqst.cdl = sizeof(u32);
  4033. + rqst.pld = (u8 *)&btp;
  4034. +
  4035. + return surface_sam_ssh_rqst(&rqst, NULL);
  4036. +}
  4037. +
  4038. +/* Get platform power soruce for battery (DPTF PSRC) */
  4039. +static int sam_psy_get_psrc(u8 channel, u8 instance, u32 *psrc)
  4040. +{
  4041. + struct surface_sam_ssh_rqst rqst;
  4042. + struct surface_sam_ssh_buf result;
  4043. +
  4044. + rqst.tc = SAM_PWR_TC;
  4045. + rqst.cid = SAM_RQST_PWR_CID_PSRC;
  4046. + rqst.iid = instance;
  4047. + rqst.chn = channel;
  4048. + rqst.snc = 0x01;
  4049. + rqst.cdl = 0x00;
  4050. + rqst.pld = NULL;
  4051. +
  4052. + result.cap = sizeof(u32);
  4053. + result.len = 0;
  4054. + result.data = (u8 *)psrc;
  4055. +
  4056. + return surface_sam_ssh_rqst(&rqst, &result);
  4057. +}
  4058. +
  4059. +/* Get maximum platform power for battery (DPTF PMAX) */
  4060. +__always_unused
  4061. +static int sam_psy_get_pmax(u8 channel, u8 instance, u32 *pmax)
  4062. +{
  4063. + struct surface_sam_ssh_rqst rqst;
  4064. + struct surface_sam_ssh_buf result;
  4065. +
  4066. + rqst.tc = SAM_PWR_TC;
  4067. + rqst.cid = SAM_RQST_PWR_CID_PMAX;
  4068. + rqst.iid = instance;
  4069. + rqst.chn = channel;
  4070. + rqst.snc = 0x01;
  4071. + rqst.cdl = 0x00;
  4072. + rqst.pld = NULL;
  4073. +
  4074. + result.cap = sizeof(u32);
  4075. + result.len = 0;
  4076. + result.data = (u8 *)pmax;
  4077. +
  4078. + return surface_sam_ssh_rqst(&rqst, &result);
  4079. +}
  4080. +
  4081. +/* Get adapter rating (DPTF ARTG) */
  4082. +__always_unused
  4083. +static int sam_psy_get_artg(u8 channel, u8 instance, u32 *artg)
  4084. +{
  4085. + struct surface_sam_ssh_rqst rqst;
  4086. + struct surface_sam_ssh_buf result;
  4087. +
  4088. + rqst.tc = SAM_PWR_TC;
  4089. + rqst.cid = SAM_RQST_PWR_CID_ARTG;
  4090. + rqst.iid = instance;
  4091. + rqst.chn = channel;
  4092. + rqst.snc = 0x01;
  4093. + rqst.cdl = 0x00;
  4094. + rqst.pld = NULL;
  4095. +
  4096. + result.cap = sizeof(u32);
  4097. + result.len = 0;
  4098. + result.data = (u8 *)artg;
  4099. +
  4100. + return surface_sam_ssh_rqst(&rqst, &result);
  4101. +}
  4102. +
  4103. +/* Unknown (DPTF PSOC) */
  4104. +__always_unused
  4105. +static int sam_psy_get_psoc(u8 channel, u8 instance, u32 *psoc)
  4106. +{
  4107. + struct surface_sam_ssh_rqst rqst;
  4108. + struct surface_sam_ssh_buf result;
  4109. +
  4110. + rqst.tc = SAM_PWR_TC;
  4111. + rqst.cid = SAM_RQST_PWR_CID_PSOC;
  4112. + rqst.iid = instance;
  4113. + rqst.chn = channel;
  4114. + rqst.snc = 0x01;
  4115. + rqst.cdl = 0x00;
  4116. + rqst.pld = NULL;
  4117. +
  4118. + result.cap = sizeof(u32);
  4119. + result.len = 0;
  4120. + result.data = (u8 *)psoc;
  4121. +
  4122. + return surface_sam_ssh_rqst(&rqst, &result);
  4123. +}
  4124. +
  4125. +/* Unknown (DPTF CHGI/ INT3403 SPPC) */
  4126. +__always_unused
  4127. +static int sam_psy_set_chgi(u8 channel, u8 instance, u32 chgi)
  4128. +{
  4129. + struct surface_sam_ssh_rqst rqst;
  4130. +
  4131. + rqst.tc = SAM_PWR_TC;
  4132. + rqst.cid = SAM_RQST_PWR_CID_CHGI;
  4133. + rqst.iid = instance;
  4134. + rqst.chn = channel;
  4135. + rqst.snc = 0x00;
  4136. + rqst.cdl = sizeof(u32);
  4137. + rqst.pld = (u8 *)&chgi;
  4138. +
  4139. + return surface_sam_ssh_rqst(&rqst, NULL);
  4140. +}
  4141. +
  4142. +
  4143. +/*
  4144. + * Common Power-Subsystem Interface.
  4145. + */
  4146. +
  4147. +struct spwr_battery_device {
  4148. + struct platform_device *pdev;
  4149. + const struct ssam_battery_properties *p;
  4150. +
  4151. + char name[32];
  4152. + struct power_supply *psy;
  4153. + struct power_supply_desc psy_desc;
  4154. +
  4155. + struct delayed_work update_work;
  4156. +
  4157. + struct ssam_event_notifier notif;
  4158. +
  4159. + struct mutex lock;
  4160. + unsigned long timestamp;
  4161. +
  4162. + u32 sta;
  4163. + struct spwr_bix bix;
  4164. + struct spwr_bst bst;
  4165. + u32 alarm;
  4166. +};
  4167. +
  4168. +struct spwr_ac_device {
  4169. + struct platform_device *pdev;
  4170. +
  4171. + char name[32];
  4172. + struct power_supply *psy;
  4173. + struct power_supply_desc psy_desc;
  4174. +
  4175. + struct ssam_event_notifier notif;
  4176. +
  4177. + struct mutex lock;
  4178. +
  4179. + u32 state;
  4180. +};
  4181. +
  4182. +static enum power_supply_property spwr_ac_props[] = {
  4183. + POWER_SUPPLY_PROP_ONLINE,
  4184. +};
  4185. +
  4186. +static enum power_supply_property spwr_battery_props_chg[] = {
  4187. + POWER_SUPPLY_PROP_STATUS,
  4188. + POWER_SUPPLY_PROP_PRESENT,
  4189. + POWER_SUPPLY_PROP_TECHNOLOGY,
  4190. + POWER_SUPPLY_PROP_CYCLE_COUNT,
  4191. + POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN,
  4192. + POWER_SUPPLY_PROP_VOLTAGE_NOW,
  4193. + POWER_SUPPLY_PROP_CURRENT_NOW,
  4194. + POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN,
  4195. + POWER_SUPPLY_PROP_CHARGE_FULL,
  4196. + POWER_SUPPLY_PROP_CHARGE_NOW,
  4197. + POWER_SUPPLY_PROP_CAPACITY,
  4198. + POWER_SUPPLY_PROP_CAPACITY_LEVEL,
  4199. + POWER_SUPPLY_PROP_MODEL_NAME,
  4200. + POWER_SUPPLY_PROP_MANUFACTURER,
  4201. + POWER_SUPPLY_PROP_SERIAL_NUMBER,
  4202. +};
  4203. +
  4204. +static enum power_supply_property spwr_battery_props_eng[] = {
  4205. + POWER_SUPPLY_PROP_STATUS,
  4206. + POWER_SUPPLY_PROP_PRESENT,
  4207. + POWER_SUPPLY_PROP_TECHNOLOGY,
  4208. + POWER_SUPPLY_PROP_CYCLE_COUNT,
  4209. + POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN,
  4210. + POWER_SUPPLY_PROP_VOLTAGE_NOW,
  4211. + POWER_SUPPLY_PROP_POWER_NOW,
  4212. + POWER_SUPPLY_PROP_ENERGY_FULL_DESIGN,
  4213. + POWER_SUPPLY_PROP_ENERGY_FULL,
  4214. + POWER_SUPPLY_PROP_ENERGY_NOW,
  4215. + POWER_SUPPLY_PROP_CAPACITY,
  4216. + POWER_SUPPLY_PROP_CAPACITY_LEVEL,
  4217. + POWER_SUPPLY_PROP_MODEL_NAME,
  4218. + POWER_SUPPLY_PROP_MANUFACTURER,
  4219. + POWER_SUPPLY_PROP_SERIAL_NUMBER,
  4220. +};
  4221. +
  4222. +
  4223. +static int spwr_battery_register(struct spwr_battery_device *bat,
  4224. + struct platform_device *pdev,
  4225. + const struct ssam_battery_properties *p);
  4226. +
  4227. +static void spwr_battery_unregister(struct spwr_battery_device *bat);
  4228. +
  4229. +
  4230. +static inline bool spwr_battery_present(struct spwr_battery_device *bat)
  4231. +{
  4232. + return bat->sta & SAM_BATTERY_STA_PRESENT;
  4233. +}
  4234. +
  4235. +
  4236. +static inline int spwr_battery_load_sta(struct spwr_battery_device *bat)
  4237. +{
  4238. + return sam_psy_get_sta(bat->p->channel, bat->p->instance, &bat->sta);
  4239. +}
  4240. +
  4241. +static inline int spwr_battery_load_bix(struct spwr_battery_device *bat)
  4242. +{
  4243. + if (!spwr_battery_present(bat))
  4244. + return 0;
  4245. +
  4246. + return sam_psy_get_bix(bat->p->channel, bat->p->instance, &bat->bix);
  4247. +}
  4248. +
  4249. +static inline int spwr_battery_load_bst(struct spwr_battery_device *bat)
  4250. +{
  4251. + if (!spwr_battery_present(bat))
  4252. + return 0;
  4253. +
  4254. + return sam_psy_get_bst(bat->p->channel, bat->p->instance, &bat->bst);
  4255. +}
  4256. +
  4257. +
  4258. +static inline int spwr_battery_set_alarm_unlocked(struct spwr_battery_device *bat, u32 value)
  4259. +{
  4260. + bat->alarm = value;
  4261. + return sam_psy_set_btp(bat->p->channel, bat->p->instance, bat->alarm);
  4262. +}
  4263. +
  4264. +static inline int spwr_battery_set_alarm(struct spwr_battery_device *bat, u32 value)
  4265. +{
  4266. + int status;
  4267. +
  4268. + mutex_lock(&bat->lock);
  4269. + status = spwr_battery_set_alarm_unlocked(bat, value);
  4270. + mutex_unlock(&bat->lock);
  4271. +
  4272. + return status;
  4273. +}
  4274. +
  4275. +static inline int spwr_battery_update_bst_unlocked(struct spwr_battery_device *bat, bool cached)
  4276. +{
  4277. + unsigned long cache_deadline = bat->timestamp + msecs_to_jiffies(cache_time);
  4278. + int status;
  4279. +
  4280. + if (cached && bat->timestamp && time_is_after_jiffies(cache_deadline))
  4281. + return 0;
  4282. +
  4283. + status = spwr_battery_load_sta(bat);
  4284. + if (status)
  4285. + return status;
  4286. +
  4287. + status = spwr_battery_load_bst(bat);
  4288. + if (status)
  4289. + return status;
  4290. +
  4291. + bat->timestamp = jiffies;
  4292. + return 0;
  4293. +}
  4294. +
  4295. +static int spwr_battery_update_bst(struct spwr_battery_device *bat, bool cached)
  4296. +{
  4297. + int status;
  4298. +
  4299. + mutex_lock(&bat->lock);
  4300. + status = spwr_battery_update_bst_unlocked(bat, cached);
  4301. + mutex_unlock(&bat->lock);
  4302. +
  4303. + return status;
  4304. +}
  4305. +
  4306. +static inline int spwr_battery_update_bix_unlocked(struct spwr_battery_device *bat)
  4307. +{
  4308. + int status;
  4309. +
  4310. + status = spwr_battery_load_sta(bat);
  4311. + if (status)
  4312. + return status;
  4313. +
  4314. + status = spwr_battery_load_bix(bat);
  4315. + if (status)
  4316. + return status;
  4317. +
  4318. + status = spwr_battery_load_bst(bat);
  4319. + if (status)
  4320. + return status;
  4321. +
  4322. + bat->timestamp = jiffies;
  4323. + return 0;
  4324. +}
  4325. +
  4326. +static int spwr_battery_update_bix(struct spwr_battery_device *bat)
  4327. +{
  4328. + int status;
  4329. +
  4330. + mutex_lock(&bat->lock);
  4331. + status = spwr_battery_update_bix_unlocked(bat);
  4332. + mutex_unlock(&bat->lock);
  4333. +
  4334. + return status;
  4335. +}
  4336. +
  4337. +static inline int spwr_ac_update_unlocked(struct spwr_ac_device *ac)
  4338. +{
  4339. + return sam_psy_get_psrc(0x01, 0x01, &ac->state);
  4340. +}
  4341. +
  4342. +static int spwr_ac_update(struct spwr_ac_device *ac)
  4343. +{
  4344. + int status;
  4345. +
  4346. + mutex_lock(&ac->lock);
  4347. + status = spwr_ac_update_unlocked(ac);
  4348. + mutex_unlock(&ac->lock);
  4349. +
  4350. + return status;
  4351. +}
  4352. +
  4353. +
  4354. +static int spwr_battery_recheck(struct spwr_battery_device *bat)
  4355. +{
  4356. + bool present = spwr_battery_present(bat);
  4357. + u32 unit = bat->bix.power_unit;
  4358. + int status;
  4359. +
  4360. + status = spwr_battery_update_bix(bat);
  4361. + if (status)
  4362. + return status;
  4363. +
  4364. + // if battery has been attached, (re-)initialize alarm
  4365. + if (!present && spwr_battery_present(bat)) {
  4366. + status = spwr_battery_set_alarm(bat, bat->bix.design_cap_warn);
  4367. + if (status)
  4368. + return status;
  4369. + }
  4370. +
  4371. + // if the unit has changed, re-add the battery
  4372. + if (unit != bat->bix.power_unit) {
  4373. + spwr_battery_unregister(bat);
  4374. + status = spwr_battery_register(bat, bat->pdev, bat->p);
  4375. + }
  4376. +
  4377. + return status;
  4378. +}
  4379. +
  4380. +
  4381. +static inline int spwr_notify_bix(struct spwr_battery_device *bat)
  4382. +{
  4383. + int status;
  4384. +
  4385. + status = spwr_battery_recheck(bat);
  4386. + if (!status)
  4387. + power_supply_changed(bat->psy);
  4388. +
  4389. + return status;
  4390. +}
  4391. +
  4392. +static inline int spwr_notify_bst(struct spwr_battery_device *bat)
  4393. +{
  4394. + int status;
  4395. +
  4396. + status = spwr_battery_update_bst(bat, false);
  4397. + if (!status)
  4398. + power_supply_changed(bat->psy);
  4399. +
  4400. + return status;
  4401. +}
  4402. +
  4403. +static inline int spwr_notify_adapter_bat(struct spwr_battery_device *bat)
  4404. +{
  4405. + /*
  4406. + * Handle battery update quirk:
  4407. + * When the battery is fully charged and the adapter is plugged in or
  4408. + * removed, the EC does not send a separate event for the state
  4409. + * (charging/discharging) change. Furthermore it may take some time until
  4410. + * the state is updated on the battery. Schedule an update to solve this.
  4411. + */
  4412. +
  4413. + if (bat->bst.remaining_cap >= bat->bix.last_full_charge_cap)
  4414. + schedule_delayed_work(&bat->update_work, SPWR_AC_BAT_UPDATE_DELAY);
  4415. +
  4416. + return 0;
  4417. +}
  4418. +
  4419. +static inline int spwr_notify_adapter_ac(struct spwr_ac_device *ac)
  4420. +{
  4421. + int status;
  4422. +
  4423. + status = spwr_ac_update(ac);
  4424. + if (!status)
  4425. + power_supply_changed(ac->psy);
  4426. +
  4427. + return status;
  4428. +}
  4429. +
  4430. +static u32 spwr_notify_bat(struct ssam_notifier_block *nb, const struct ssam_event *event)
  4431. +{
  4432. + struct spwr_battery_device *bat = container_of(nb, struct spwr_battery_device, notif.base);
  4433. + int status;
  4434. +
  4435. + dev_dbg(&bat->pdev->dev, "power event (cid = 0x%02x, iid = %d, chn = %d)\n",
  4436. + event->command_id, event->instance_id, event->channel);
  4437. +
  4438. + // handled here, needs to be handled for all channels/instances
  4439. + if (event->command_id == SAM_EVENT_PWR_CID_ADAPTER) {
  4440. + status = spwr_notify_adapter_bat(bat);
  4441. + return ssam_notifier_from_errno(status) | SSAM_NOTIF_HANDLED;
  4442. + }
  4443. +
  4444. + // check for the correct channel and instance ID
  4445. + if (event->channel != bat->p->channel)
  4446. + return 0;
  4447. +
  4448. + if (event->instance_id != bat->p->instance)
  4449. + return 0;
  4450. +
  4451. + switch (event->command_id) {
  4452. + case SAM_EVENT_PWR_CID_BIX:
  4453. + status = spwr_notify_bix(bat);
  4454. + break;
  4455. +
  4456. + case SAM_EVENT_PWR_CID_BST:
  4457. + status = spwr_notify_bst(bat);
  4458. + break;
  4459. +
  4460. + default:
  4461. + return 0;
  4462. + }
  4463. +
  4464. + return ssam_notifier_from_errno(status) | SSAM_NOTIF_HANDLED;
  4465. +}
  4466. +
  4467. +static u32 spwr_notify_ac(struct ssam_notifier_block *nb, const struct ssam_event *event)
  4468. +{
  4469. + struct spwr_ac_device *ac = container_of(nb, struct spwr_ac_device, notif.base);
  4470. + int status;
  4471. +
  4472. + dev_dbg(&ac->pdev->dev, "power event (cid = 0x%02x, iid = %d, chn = %d)\n",
  4473. + event->command_id, event->instance_id, event->channel);
  4474. +
  4475. + // AC has IID = 0
  4476. + if (event->instance_id != 0)
  4477. + return 0;
  4478. +
  4479. + switch (event->command_id) {
  4480. + case SAM_EVENT_PWR_CID_ADAPTER:
  4481. + status = spwr_notify_adapter_ac(ac);
  4482. + return ssam_notifier_from_errno(status) | SSAM_NOTIF_HANDLED;
  4483. +
  4484. + default:
  4485. + return 0;
  4486. + }
  4487. +}
  4488. +
  4489. +static void spwr_battery_update_bst_workfn(struct work_struct *work)
  4490. +{
  4491. + struct delayed_work *dwork = to_delayed_work(work);
  4492. + struct spwr_battery_device *bat = container_of(dwork, struct spwr_battery_device, update_work);
  4493. + int status;
  4494. +
  4495. + status = spwr_battery_update_bst(bat, false);
  4496. + if (!status)
  4497. + power_supply_changed(bat->psy);
  4498. +
  4499. + if (status)
  4500. + dev_err(&bat->pdev->dev, "failed to update battery state: %d\n", status);
  4501. +}
  4502. +
  4503. +
  4504. +static inline int spwr_battery_prop_status(struct spwr_battery_device *bat)
  4505. +{
  4506. + if (bat->bst.state & SAM_BATTERY_STATE_DISCHARGING)
  4507. + return POWER_SUPPLY_STATUS_DISCHARGING;
  4508. +
  4509. + if (bat->bst.state & SAM_BATTERY_STATE_CHARGING)
  4510. + return POWER_SUPPLY_STATUS_CHARGING;
  4511. +
  4512. + if (bat->bix.last_full_charge_cap == bat->bst.remaining_cap)
  4513. + return POWER_SUPPLY_STATUS_FULL;
  4514. +
  4515. + if (bat->bst.present_rate == 0)
  4516. + return POWER_SUPPLY_STATUS_NOT_CHARGING;
  4517. +
  4518. + return POWER_SUPPLY_STATUS_UNKNOWN;
  4519. +}
  4520. +
  4521. +static inline int spwr_battery_prop_technology(struct spwr_battery_device *bat)
  4522. +{
  4523. + if (!strcasecmp("NiCd", bat->bix.type))
  4524. + return POWER_SUPPLY_TECHNOLOGY_NiCd;
  4525. +
  4526. + if (!strcasecmp("NiMH", bat->bix.type))
  4527. + return POWER_SUPPLY_TECHNOLOGY_NiMH;
  4528. +
  4529. + if (!strcasecmp("LION", bat->bix.type))
  4530. + return POWER_SUPPLY_TECHNOLOGY_LION;
  4531. +
  4532. + if (!strncasecmp("LI-ION", bat->bix.type, 6))
  4533. + return POWER_SUPPLY_TECHNOLOGY_LION;
  4534. +
  4535. + if (!strcasecmp("LiP", bat->bix.type))
  4536. + return POWER_SUPPLY_TECHNOLOGY_LIPO;
  4537. +
  4538. + return POWER_SUPPLY_TECHNOLOGY_UNKNOWN;
  4539. +}
  4540. +
  4541. +static inline int spwr_battery_prop_capacity(struct spwr_battery_device *bat)
  4542. +{
  4543. + if (bat->bst.remaining_cap && bat->bix.last_full_charge_cap)
  4544. + return bat->bst.remaining_cap * 100 / bat->bix.last_full_charge_cap;
  4545. + else
  4546. + return 0;
  4547. +}
  4548. +
  4549. +static inline int spwr_battery_prop_capacity_level(struct spwr_battery_device *bat)
  4550. +{
  4551. + if (bat->bst.state & SAM_BATTERY_STATE_CRITICAL)
  4552. + return POWER_SUPPLY_CAPACITY_LEVEL_CRITICAL;
  4553. +
  4554. + if (bat->bst.remaining_cap >= bat->bix.last_full_charge_cap)
  4555. + return POWER_SUPPLY_CAPACITY_LEVEL_FULL;
  4556. +
  4557. + if (bat->bst.remaining_cap <= bat->alarm)
  4558. + return POWER_SUPPLY_CAPACITY_LEVEL_LOW;
  4559. +
  4560. + return POWER_SUPPLY_CAPACITY_LEVEL_NORMAL;
  4561. +}
  4562. +
  4563. +static int spwr_ac_get_property(struct power_supply *psy,
  4564. + enum power_supply_property psp,
  4565. + union power_supply_propval *val)
  4566. +{
  4567. + struct spwr_ac_device *ac = power_supply_get_drvdata(psy);
  4568. + int status;
  4569. +
  4570. + mutex_lock(&ac->lock);
  4571. +
  4572. + status = spwr_ac_update_unlocked(ac);
  4573. + if (status)
  4574. + goto out;
  4575. +
  4576. + switch (psp) {
  4577. + case POWER_SUPPLY_PROP_ONLINE:
  4578. + val->intval = ac->state == 1;
  4579. + break;
  4580. +
  4581. + default:
  4582. + status = -EINVAL;
  4583. + goto out;
  4584. + }
  4585. +
  4586. +out:
  4587. + mutex_unlock(&ac->lock);
  4588. + return status;
  4589. +}
  4590. +
  4591. +static int spwr_battery_get_property(struct power_supply *psy,
  4592. + enum power_supply_property psp,
  4593. + union power_supply_propval *val)
  4594. +{
  4595. + struct spwr_battery_device *bat = power_supply_get_drvdata(psy);
  4596. + int status;
  4597. +
  4598. + mutex_lock(&bat->lock);
  4599. +
  4600. + status = spwr_battery_update_bst_unlocked(bat, true);
  4601. + if (status)
  4602. + goto out;
  4603. +
  4604. + // abort if battery is not present
  4605. + if (!spwr_battery_present(bat) && psp != POWER_SUPPLY_PROP_PRESENT) {
  4606. + status = -ENODEV;
  4607. + goto out;
  4608. + }
  4609. +
  4610. + switch (psp) {
  4611. + case POWER_SUPPLY_PROP_STATUS:
  4612. + val->intval = spwr_battery_prop_status(bat);
  4613. + break;
  4614. +
  4615. + case POWER_SUPPLY_PROP_PRESENT:
  4616. + val->intval = spwr_battery_present(bat);
  4617. + break;
  4618. +
  4619. + case POWER_SUPPLY_PROP_TECHNOLOGY:
  4620. + val->intval = spwr_battery_prop_technology(bat);
  4621. + break;
  4622. +
  4623. + case POWER_SUPPLY_PROP_CYCLE_COUNT:
  4624. + val->intval = bat->bix.cycle_count;
  4625. + break;
  4626. +
  4627. + case POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN:
  4628. + val->intval = bat->bix.design_voltage * 1000;
  4629. + break;
  4630. +
  4631. + case POWER_SUPPLY_PROP_VOLTAGE_NOW:
  4632. + val->intval = bat->bst.present_voltage * 1000;
  4633. + break;
  4634. +
  4635. + case POWER_SUPPLY_PROP_CURRENT_NOW:
  4636. + case POWER_SUPPLY_PROP_POWER_NOW:
  4637. + val->intval = bat->bst.present_rate * 1000;
  4638. + break;
  4639. +
  4640. + case POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN:
  4641. + case POWER_SUPPLY_PROP_ENERGY_FULL_DESIGN:
  4642. + val->intval = bat->bix.design_cap * 1000;
  4643. + break;
  4644. +
  4645. + case POWER_SUPPLY_PROP_CHARGE_FULL:
  4646. + case POWER_SUPPLY_PROP_ENERGY_FULL:
  4647. + val->intval = bat->bix.last_full_charge_cap * 1000;
  4648. + break;
  4649. +
  4650. + case POWER_SUPPLY_PROP_CHARGE_NOW:
  4651. + case POWER_SUPPLY_PROP_ENERGY_NOW:
  4652. + val->intval = bat->bst.remaining_cap * 1000;
  4653. + break;
  4654. +
  4655. + case POWER_SUPPLY_PROP_CAPACITY:
  4656. + val->intval = spwr_battery_prop_capacity(bat);
  4657. + break;
  4658. +
  4659. + case POWER_SUPPLY_PROP_CAPACITY_LEVEL:
  4660. + val->intval = spwr_battery_prop_capacity_level(bat);
  4661. + break;
  4662. +
  4663. + case POWER_SUPPLY_PROP_MODEL_NAME:
  4664. + val->strval = bat->bix.model;
  4665. + break;
  4666. +
  4667. + case POWER_SUPPLY_PROP_MANUFACTURER:
  4668. + val->strval = bat->bix.oem_info;
  4669. + break;
  4670. +
  4671. + case POWER_SUPPLY_PROP_SERIAL_NUMBER:
  4672. + val->strval = bat->bix.serial;
  4673. + break;
  4674. +
  4675. + default:
  4676. + status = -EINVAL;
  4677. + goto out;
  4678. + }
  4679. +
  4680. +out:
  4681. + mutex_unlock(&bat->lock);
  4682. + return status;
  4683. +}
  4684. +
  4685. +
  4686. +static ssize_t spwr_battery_alarm_show(struct device *dev,
  4687. + struct device_attribute *attr,
  4688. + char *buf)
  4689. +{
  4690. + struct power_supply *psy = dev_get_drvdata(dev);
  4691. + struct spwr_battery_device *bat = power_supply_get_drvdata(psy);
  4692. +
  4693. + return sprintf(buf, "%d\n", bat->alarm * 1000);
  4694. +}
  4695. +
  4696. +static ssize_t spwr_battery_alarm_store(struct device *dev,
  4697. + struct device_attribute *attr,
  4698. + const char *buf, size_t count)
  4699. +{
  4700. + struct power_supply *psy = dev_get_drvdata(dev);
  4701. + struct spwr_battery_device *bat = power_supply_get_drvdata(psy);
  4702. + unsigned long value;
  4703. + int status;
  4704. +
  4705. + status = kstrtoul(buf, 0, &value);
  4706. + if (status)
  4707. + return status;
  4708. +
  4709. + if (!spwr_battery_present(bat))
  4710. + return -ENODEV;
  4711. +
  4712. + status = spwr_battery_set_alarm(bat, value / 1000);
  4713. + if (status)
  4714. + return status;
  4715. +
  4716. + return count;
  4717. +}
  4718. +
  4719. +static const struct device_attribute alarm_attr = {
  4720. + .attr = {.name = "alarm", .mode = 0644},
  4721. + .show = spwr_battery_alarm_show,
  4722. + .store = spwr_battery_alarm_store,
  4723. +};
  4724. +
  4725. +
  4726. +static int spwr_ac_register(struct spwr_ac_device *ac, struct platform_device *pdev)
  4727. +{
  4728. + struct power_supply_config psy_cfg = {};
  4729. + u32 sta;
  4730. + int status;
  4731. +
  4732. + // make sure the device is there and functioning properly
  4733. + status = sam_psy_get_sta(0x01, 0x01, &sta);
  4734. + if (status)
  4735. + return status;
  4736. +
  4737. + if ((sta & SAM_BATTERY_STA_OK) != SAM_BATTERY_STA_OK)
  4738. + return -ENODEV;
  4739. +
  4740. + psy_cfg.drv_data = ac;
  4741. +
  4742. + ac->pdev = pdev;
  4743. + mutex_init(&ac->lock);
  4744. +
  4745. + snprintf(ac->name, ARRAY_SIZE(ac->name), "ADP0");
  4746. +
  4747. + ac->psy_desc.name = ac->name;
  4748. + ac->psy_desc.type = POWER_SUPPLY_TYPE_MAINS;
  4749. + ac->psy_desc.properties = spwr_ac_props;
  4750. + ac->psy_desc.num_properties = ARRAY_SIZE(spwr_ac_props);
  4751. + ac->psy_desc.get_property = spwr_ac_get_property;
  4752. +
  4753. + ac->psy = power_supply_register(&ac->pdev->dev, &ac->psy_desc, &psy_cfg);
  4754. + if (IS_ERR(ac->psy)) {
  4755. + status = PTR_ERR(ac->psy);
  4756. + goto err_psy;
  4757. + }
  4758. +
  4759. + ac->notif.base.priority = 1;
  4760. + ac->notif.base.fn = spwr_notify_ac;
  4761. + ac->notif.event.reg = SSAM_EVENT_REGISTRY_SAM;
  4762. + ac->notif.event.id.target_category = SSAM_SSH_TC_BAT;
  4763. + ac->notif.event.id.instance = 0;
  4764. + ac->notif.event.flags = SSAM_EVENT_SEQUENCED;
  4765. +
  4766. + status = surface_sam_ssh_notifier_register(&ac->notif);
  4767. + if (status)
  4768. + goto err_notif;
  4769. +
  4770. + return 0;
  4771. +
  4772. +err_notif:
  4773. + power_supply_unregister(ac->psy);
  4774. +err_psy:
  4775. + mutex_destroy(&ac->lock);
  4776. + return status;
  4777. +}
  4778. +
  4779. +static int spwr_ac_unregister(struct spwr_ac_device *ac)
  4780. +{
  4781. + surface_sam_ssh_notifier_unregister(&ac->notif);
  4782. + power_supply_unregister(ac->psy);
  4783. + mutex_destroy(&ac->lock);
  4784. + return 0;
  4785. +}
  4786. +
  4787. +static int spwr_battery_register(struct spwr_battery_device *bat,
  4788. + struct platform_device *pdev,
  4789. + const struct ssam_battery_properties *p)
  4790. +{
  4791. + struct power_supply_config psy_cfg = {};
  4792. + u32 sta;
  4793. + int status;
  4794. +
  4795. + bat->pdev = pdev;
  4796. + bat->p = p;
  4797. +
  4798. + // make sure the device is there and functioning properly
  4799. + status = sam_psy_get_sta(bat->p->channel, bat->p->instance, &sta);
  4800. + if (status)
  4801. + return status;
  4802. +
  4803. + if ((sta & SAM_BATTERY_STA_OK) != SAM_BATTERY_STA_OK)
  4804. + return -ENODEV;
  4805. +
  4806. + status = spwr_battery_update_bix_unlocked(bat);
  4807. + if (status)
  4808. + return status;
  4809. +
  4810. + if (spwr_battery_present(bat)) {
  4811. + status = spwr_battery_set_alarm_unlocked(bat, bat->bix.design_cap_warn);
  4812. + if (status)
  4813. + return status;
  4814. + }
  4815. +
  4816. + snprintf(bat->name, ARRAY_SIZE(bat->name), "BAT%d", bat->p->num);
  4817. + bat->psy_desc.name = bat->name;
  4818. + bat->psy_desc.type = POWER_SUPPLY_TYPE_BATTERY;
  4819. +
  4820. + if (bat->bix.power_unit == SAM_BATTERY_POWER_UNIT_MA) {
  4821. + bat->psy_desc.properties = spwr_battery_props_chg;
  4822. + bat->psy_desc.num_properties = ARRAY_SIZE(spwr_battery_props_chg);
  4823. + } else {
  4824. + bat->psy_desc.properties = spwr_battery_props_eng;
  4825. + bat->psy_desc.num_properties = ARRAY_SIZE(spwr_battery_props_eng);
  4826. + }
  4827. +
  4828. + bat->psy_desc.get_property = spwr_battery_get_property;
  4829. +
  4830. + mutex_init(&bat->lock);
  4831. + psy_cfg.drv_data = bat;
  4832. +
  4833. + INIT_DELAYED_WORK(&bat->update_work, spwr_battery_update_bst_workfn);
  4834. +
  4835. + bat->psy = power_supply_register(&bat->pdev->dev, &bat->psy_desc, &psy_cfg);
  4836. + if (IS_ERR(bat->psy)) {
  4837. + status = PTR_ERR(bat->psy);
  4838. + goto err_psy;
  4839. + }
  4840. +
  4841. + bat->notif.base.priority = 1;
  4842. + bat->notif.base.fn = spwr_notify_bat;
  4843. + bat->notif.event.reg = p->registry;
  4844. + bat->notif.event.id.target_category = SSAM_SSH_TC_BAT;
  4845. + bat->notif.event.id.instance = 0;
  4846. + bat->notif.event.flags = SSAM_EVENT_SEQUENCED;
  4847. +
  4848. + status = surface_sam_ssh_notifier_register(&bat->notif);
  4849. + if (status)
  4850. + goto err_notif;
  4851. +
  4852. + status = device_create_file(&bat->psy->dev, &alarm_attr);
  4853. + if (status)
  4854. + goto err_file;
  4855. +
  4856. + return 0;
  4857. +
  4858. +err_file:
  4859. + surface_sam_ssh_notifier_unregister(&bat->notif);
  4860. +err_notif:
  4861. + power_supply_unregister(bat->psy);
  4862. +err_psy:
  4863. + mutex_destroy(&bat->lock);
  4864. + return status;
  4865. +}
  4866. +
  4867. +static void spwr_battery_unregister(struct spwr_battery_device *bat)
  4868. +{
  4869. + surface_sam_ssh_notifier_unregister(&bat->notif);
  4870. + cancel_delayed_work_sync(&bat->update_work);
  4871. + device_remove_file(&bat->psy->dev, &alarm_attr);
  4872. + power_supply_unregister(bat->psy);
  4873. + mutex_destroy(&bat->lock);
  4874. +}
  4875. +
  4876. +
  4877. +/*
  4878. + * Battery Driver.
  4879. + */
  4880. +
  4881. +#ifdef CONFIG_PM_SLEEP
  4882. +static int surface_sam_sid_battery_resume(struct device *dev)
  4883. +{
  4884. + struct spwr_battery_device *bat;
  4885. +
  4886. + bat = dev_get_drvdata(dev);
  4887. + return spwr_battery_recheck(bat);
  4888. +}
  4889. +#else
  4890. +#define surface_sam_sid_battery_resume NULL
  4891. +#endif
  4892. +
  4893. +SIMPLE_DEV_PM_OPS(surface_sam_sid_battery_pm, NULL, surface_sam_sid_battery_resume);
  4894. +
  4895. +static int surface_sam_sid_battery_probe(struct platform_device *pdev)
  4896. +{
  4897. + struct spwr_battery_device *bat;
  4898. + int status;
  4899. +
  4900. + // link to ec
  4901. + status = surface_sam_ssh_consumer_register(&pdev->dev);
  4902. + if (status)
  4903. + return status == -ENXIO ? -EPROBE_DEFER : status;
  4904. +
  4905. + bat = devm_kzalloc(&pdev->dev, sizeof(struct spwr_battery_device), GFP_KERNEL);
  4906. + if (!bat)
  4907. + return -ENOMEM;
  4908. +
  4909. + platform_set_drvdata(pdev, bat);
  4910. + return spwr_battery_register(bat, pdev, pdev->dev.platform_data);
  4911. +}
  4912. +
  4913. +static int surface_sam_sid_battery_remove(struct platform_device *pdev)
  4914. +{
  4915. + struct spwr_battery_device *bat;
  4916. +
  4917. + bat = platform_get_drvdata(pdev);
  4918. + spwr_battery_unregister(bat);
  4919. +
  4920. + return 0;
  4921. +}
  4922. +
  4923. +static struct platform_driver surface_sam_sid_battery = {
  4924. + .probe = surface_sam_sid_battery_probe,
  4925. + .remove = surface_sam_sid_battery_remove,
  4926. + .driver = {
  4927. + .name = "surface_sam_sid_battery",
  4928. + .pm = &surface_sam_sid_battery_pm,
  4929. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  4930. + },
  4931. +};
  4932. +
  4933. +
  4934. +/*
  4935. + * AC Driver.
  4936. + */
  4937. +
  4938. +static int surface_sam_sid_ac_probe(struct platform_device *pdev)
  4939. +{
  4940. + int status;
  4941. + struct spwr_ac_device *ac;
  4942. +
  4943. + // link to ec
  4944. + status = surface_sam_ssh_consumer_register(&pdev->dev);
  4945. + if (status)
  4946. + return status == -ENXIO ? -EPROBE_DEFER : status;
  4947. +
  4948. + ac = devm_kzalloc(&pdev->dev, sizeof(struct spwr_ac_device), GFP_KERNEL);
  4949. + if (!ac)
  4950. + return -ENOMEM;
  4951. +
  4952. + status = spwr_ac_register(ac, pdev);
  4953. + if (status)
  4954. + return status;
  4955. +
  4956. + platform_set_drvdata(pdev, ac);
  4957. + return 0;
  4958. +}
  4959. +
  4960. +static int surface_sam_sid_ac_remove(struct platform_device *pdev)
  4961. +{
  4962. + struct spwr_ac_device *ac;
  4963. +
  4964. + ac = platform_get_drvdata(pdev);
  4965. + return spwr_ac_unregister(ac);
  4966. +}
  4967. +
  4968. +static struct platform_driver surface_sam_sid_ac = {
  4969. + .probe = surface_sam_sid_ac_probe,
  4970. + .remove = surface_sam_sid_ac_remove,
  4971. + .driver = {
  4972. + .name = "surface_sam_sid_ac",
  4973. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  4974. + },
  4975. +};
  4976. +
  4977. +
  4978. +static int __init surface_sam_sid_power_init(void)
  4979. +{
  4980. + int status;
  4981. +
  4982. + status = platform_driver_register(&surface_sam_sid_battery);
  4983. + if (status)
  4984. + return status;
  4985. +
  4986. + status = platform_driver_register(&surface_sam_sid_ac);
  4987. + if (status) {
  4988. + platform_driver_unregister(&surface_sam_sid_battery);
  4989. + return status;
  4990. + }
  4991. +
  4992. + return 0;
  4993. +}
  4994. +
  4995. +static void __exit surface_sam_sid_power_exit(void)
  4996. +{
  4997. + platform_driver_unregister(&surface_sam_sid_battery);
  4998. + platform_driver_unregister(&surface_sam_sid_ac);
  4999. +}
  5000. +
  5001. +module_init(surface_sam_sid_power_init);
  5002. +module_exit(surface_sam_sid_power_exit);
  5003. +
  5004. +MODULE_AUTHOR("Maximilian Luz <luzmaximilian@gmail.com>");
  5005. +MODULE_DESCRIPTION("Surface Battery/AC Driver for 7th Generation Surface Devices");
  5006. +MODULE_LICENSE("GPL");
  5007. +MODULE_ALIAS("platform:surface_sam_sid_ac");
  5008. +MODULE_ALIAS("platform:surface_sam_sid_battery");
  5009. diff --git a/drivers/platform/x86/surface_sam/surface_sam_sid_power.h b/drivers/platform/x86/surface_sam/surface_sam_sid_power.h
  5010. new file mode 100644
  5011. index 0000000000000..2e8f212086e12
  5012. --- /dev/null
  5013. +++ b/drivers/platform/x86/surface_sam/surface_sam_sid_power.h
  5014. @@ -0,0 +1,15 @@
  5015. +#ifndef _SURFACE_SAM_SID_POWER_H
  5016. +#define _SURFACE_SAM_SID_POWER_H
  5017. +
  5018. +#include <linux/types.h>
  5019. +#include "surface_sam_ssh.h"
  5020. +
  5021. +
  5022. +struct ssam_battery_properties {
  5023. + struct ssam_event_registry registry;
  5024. + u8 num;
  5025. + u8 channel;
  5026. + u8 instance;
  5027. +};
  5028. +
  5029. +#endif /* _SURFACE_SAM_SID_POWER_H */
  5030. diff --git a/drivers/platform/x86/surface_sam/surface_sam_sid_vhf.c b/drivers/platform/x86/surface_sam/surface_sam_sid_vhf.c
  5031. new file mode 100644
  5032. index 0000000000000..474221097eaf1
  5033. --- /dev/null
  5034. +++ b/drivers/platform/x86/surface_sam/surface_sam_sid_vhf.c
  5035. @@ -0,0 +1,432 @@
  5036. +// SPDX-License-Identifier: GPL-2.0-or-later
  5037. +/*
  5038. + * Microsofs Surface HID (VHF) driver for HID input events via SAM.
  5039. + * Used for keyboard input events on the 7th generation Surface Laptops.
  5040. + */
  5041. +
  5042. +#include <linux/acpi.h>
  5043. +#include <linux/hid.h>
  5044. +#include <linux/input.h>
  5045. +#include <linux/platform_device.h>
  5046. +#include <linux/types.h>
  5047. +
  5048. +#include "surface_sam_ssh.h"
  5049. +#include "surface_sam_sid_vhf.h"
  5050. +
  5051. +#define SID_VHF_INPUT_NAME "Microsoft Surface HID"
  5052. +
  5053. +#define SAM_EVENT_SID_VHF_TC 0x15
  5054. +
  5055. +#define VHF_HID_STARTED 0
  5056. +
  5057. +struct sid_vhf {
  5058. + const struct ssam_hid_properties *p;
  5059. + struct platform_device *dev;
  5060. + struct hid_device *hid;
  5061. + struct ssam_event_notifier notif;
  5062. + unsigned long state;
  5063. +};
  5064. +
  5065. +
  5066. +static int sid_vhf_hid_start(struct hid_device *hid)
  5067. +{
  5068. + hid_dbg(hid, "%s\n", __func__);
  5069. + return 0;
  5070. +}
  5071. +
  5072. +static void sid_vhf_hid_stop(struct hid_device *hid)
  5073. +{
  5074. + hid_dbg(hid, "%s\n", __func__);
  5075. +}
  5076. +
  5077. +static int sid_vhf_hid_open(struct hid_device *hid)
  5078. +{
  5079. + struct sid_vhf *vhf = dev_get_drvdata(hid->dev.parent);
  5080. +
  5081. + hid_dbg(hid, "%s\n", __func__);
  5082. +
  5083. + set_bit(VHF_HID_STARTED, &vhf->state);
  5084. + return 0;
  5085. +}
  5086. +
  5087. +static void sid_vhf_hid_close(struct hid_device *hid)
  5088. +{
  5089. +
  5090. + struct sid_vhf *vhf = dev_get_drvdata(hid->dev.parent);
  5091. +
  5092. + hid_dbg(hid, "%s\n", __func__);
  5093. +
  5094. + clear_bit(VHF_HID_STARTED, &vhf->state);
  5095. +}
  5096. +
  5097. +struct surface_sam_sid_vhf_meta_rqst {
  5098. + u8 id;
  5099. + u32 offset;
  5100. + u32 length; // buffer limit on send, length of data received on receive
  5101. + u8 end; // 0x01 if end was reached
  5102. +} __packed;
  5103. +
  5104. +struct vhf_device_metadata_info {
  5105. + u8 len;
  5106. + u8 _2;
  5107. + u8 _3;
  5108. + u8 _4;
  5109. + u8 _5;
  5110. + u8 _6;
  5111. + u8 _7;
  5112. + u16 hid_len; // hid descriptor length
  5113. +} __packed;
  5114. +
  5115. +struct vhf_device_metadata {
  5116. + u32 len;
  5117. + u16 vendor_id;
  5118. + u16 product_id;
  5119. + u8 _1[24];
  5120. +} __packed;
  5121. +
  5122. +union vhf_buffer_data {
  5123. + struct vhf_device_metadata_info info;
  5124. + u8 pld[0x76];
  5125. + struct vhf_device_metadata meta;
  5126. +};
  5127. +
  5128. +struct surface_sam_sid_vhf_meta_resp {
  5129. + struct surface_sam_sid_vhf_meta_rqst rqst;
  5130. + union vhf_buffer_data data;
  5131. +} __packed;
  5132. +
  5133. +
  5134. +static int vhf_get_metadata(u8 iid, struct vhf_device_metadata *meta)
  5135. +{
  5136. + int status;
  5137. +
  5138. + struct surface_sam_sid_vhf_meta_resp resp = {
  5139. + .rqst = {
  5140. + .id = 2,
  5141. + .offset = 0,
  5142. + .length = 0x76,
  5143. + .end = 0
  5144. + }
  5145. + };
  5146. +
  5147. + struct surface_sam_ssh_rqst rqst = {
  5148. + .tc = 0x15,
  5149. + .cid = 0x04,
  5150. + .iid = iid,
  5151. + .chn = 0x02,
  5152. + .snc = 0x01,
  5153. + .cdl = sizeof(struct surface_sam_sid_vhf_meta_rqst),
  5154. + .pld = (u8 *)&resp.rqst,
  5155. + };
  5156. +
  5157. + struct surface_sam_ssh_buf result = {
  5158. + .cap = sizeof(struct surface_sam_sid_vhf_meta_resp),
  5159. + .len = 0,
  5160. + .data = (u8 *)&resp,
  5161. + };
  5162. +
  5163. + status = surface_sam_ssh_rqst(&rqst, &result);
  5164. + if (status)
  5165. + return status;
  5166. +
  5167. + *meta = resp.data.meta;
  5168. +
  5169. + return 0;
  5170. +}
  5171. +
  5172. +static int vhf_get_hid_descriptor(struct hid_device *hid, u8 iid, u8 **desc, int *size)
  5173. +{
  5174. + int status, len;
  5175. + u8 *buf;
  5176. +
  5177. + struct surface_sam_sid_vhf_meta_resp resp = {
  5178. + .rqst = {
  5179. + .id = 0,
  5180. + .offset = 0,
  5181. + .length = 0x76,
  5182. + .end = 0,
  5183. + }
  5184. + };
  5185. +
  5186. + struct surface_sam_ssh_rqst rqst = {
  5187. + .tc = 0x15,
  5188. + .cid = 0x04,
  5189. + .iid = iid,
  5190. + .chn = 0x02,
  5191. + .snc = 0x01,
  5192. + .cdl = sizeof(struct surface_sam_sid_vhf_meta_rqst),
  5193. + .pld = (u8 *)&resp.rqst,
  5194. + };
  5195. +
  5196. + struct surface_sam_ssh_buf result = {
  5197. + .cap = sizeof(struct surface_sam_sid_vhf_meta_resp),
  5198. + .len = 0,
  5199. + .data = (u8 *)&resp,
  5200. + };
  5201. +
  5202. + // first fetch 00 to get the total length
  5203. + status = surface_sam_ssh_rqst(&rqst, &result);
  5204. + if (status)
  5205. + return status;
  5206. +
  5207. + len = resp.data.info.hid_len;
  5208. +
  5209. + // allocate a buffer for the descriptor
  5210. + buf = kzalloc(len, GFP_KERNEL);
  5211. +
  5212. + // then, iterate and write into buffer, copying out bytes
  5213. + resp.rqst.id = 1;
  5214. + resp.rqst.offset = 0;
  5215. + resp.rqst.length = 0x76;
  5216. + resp.rqst.end = 0;
  5217. +
  5218. + while (!resp.rqst.end && resp.rqst.offset < len) {
  5219. + status = surface_sam_ssh_rqst(&rqst, &result);
  5220. + if (status) {
  5221. + kfree(buf);
  5222. + return status;
  5223. + }
  5224. + memcpy(buf + resp.rqst.offset, resp.data.pld, resp.rqst.length);
  5225. +
  5226. + resp.rqst.offset += resp.rqst.length;
  5227. + }
  5228. +
  5229. + *desc = buf;
  5230. + *size = len;
  5231. +
  5232. + return 0;
  5233. +}
  5234. +
  5235. +static int sid_vhf_hid_parse(struct hid_device *hid)
  5236. +{
  5237. + struct sid_vhf *vhf = dev_get_drvdata(hid->dev.parent);
  5238. + int ret = 0, size;
  5239. + u8 *buf;
  5240. +
  5241. + ret = vhf_get_hid_descriptor(hid, vhf->p->instance, &buf, &size);
  5242. + if (ret != 0) {
  5243. + hid_err(hid, "Failed to read HID descriptor from device: %d\n", ret);
  5244. + return -EIO;
  5245. + }
  5246. + hid_dbg(hid, "HID descriptor of device:");
  5247. + print_hex_dump_debug("descriptor:", DUMP_PREFIX_OFFSET, 16, 1, buf, size, false);
  5248. +
  5249. + ret = hid_parse_report(hid, buf, size);
  5250. + kfree(buf);
  5251. + return ret;
  5252. +
  5253. +}
  5254. +
  5255. +static int sid_vhf_hid_raw_request(struct hid_device *hid, unsigned char
  5256. + reportnum, u8 *buf, size_t len, unsigned char rtype, int
  5257. + reqtype)
  5258. +{
  5259. + struct sid_vhf *vhf = dev_get_drvdata(hid->dev.parent);
  5260. + int status;
  5261. + u8 cid;
  5262. + struct surface_sam_ssh_rqst rqst = {};
  5263. + struct surface_sam_ssh_buf result = {};
  5264. +
  5265. + hid_dbg(hid, "%s: reportnum=%#04x rtype=%i reqtype=%i\n", __func__, reportnum, rtype, reqtype);
  5266. + print_hex_dump_debug("report:", DUMP_PREFIX_OFFSET, 16, 1, buf, len, false);
  5267. +
  5268. + // Byte 0 is the report number. Report data starts at byte 1.
  5269. + buf[0] = reportnum;
  5270. +
  5271. + switch (rtype) {
  5272. + case HID_OUTPUT_REPORT:
  5273. + cid = 0x01;
  5274. + break;
  5275. + case HID_FEATURE_REPORT:
  5276. + switch (reqtype) {
  5277. + case HID_REQ_GET_REPORT:
  5278. + // The EC doesn't respond to GET FEATURE for these touchpad reports
  5279. + // we immediately discard to avoid waiting for a timeout.
  5280. + if (reportnum == 6 || reportnum == 7 || reportnum == 8 || reportnum == 9 || reportnum == 0x0b) {
  5281. + hid_dbg(hid, "%s: skipping get feature report for 0x%02x\n", __func__, reportnum);
  5282. + return 0;
  5283. + }
  5284. +
  5285. + cid = 0x02;
  5286. + break;
  5287. + case HID_REQ_SET_REPORT:
  5288. + cid = 0x03;
  5289. + break;
  5290. + default:
  5291. + hid_err(hid, "%s: unknown req type 0x%02x\n", __func__, rtype);
  5292. + return -EIO;
  5293. + }
  5294. + break;
  5295. + default:
  5296. + hid_err(hid, "%s: unknown report type 0x%02x\n", __func__, reportnum);
  5297. + return -EIO;
  5298. + }
  5299. +
  5300. + rqst.tc = SAM_EVENT_SID_VHF_TC;
  5301. + rqst.chn = 0x02;
  5302. + rqst.iid = vhf->p->instance;
  5303. + rqst.cid = cid;
  5304. + rqst.snc = reqtype == HID_REQ_GET_REPORT ? 0x01 : 0x00;
  5305. + rqst.cdl = reqtype == HID_REQ_GET_REPORT ? 0x01 : len;
  5306. + rqst.pld = buf;
  5307. +
  5308. + result.cap = len;
  5309. + result.len = 0;
  5310. + result.data = buf;
  5311. +
  5312. + hid_dbg(hid, "%s: sending to cid=%#04x snc=%#04x\n", __func__, cid, HID_REQ_GET_REPORT == reqtype);
  5313. +
  5314. + status = surface_sam_ssh_rqst(&rqst, &result);
  5315. + hid_dbg(hid, "%s: status %i\n", __func__, status);
  5316. +
  5317. + if (status)
  5318. + return status;
  5319. +
  5320. + if (result.len > 0)
  5321. + print_hex_dump_debug("response:", DUMP_PREFIX_OFFSET, 16, 1, result.data, result.len, false);
  5322. +
  5323. + return result.len;
  5324. +}
  5325. +
  5326. +static struct hid_ll_driver sid_vhf_hid_ll_driver = {
  5327. + .start = sid_vhf_hid_start,
  5328. + .stop = sid_vhf_hid_stop,
  5329. + .open = sid_vhf_hid_open,
  5330. + .close = sid_vhf_hid_close,
  5331. + .parse = sid_vhf_hid_parse,
  5332. + .raw_request = sid_vhf_hid_raw_request,
  5333. +};
  5334. +
  5335. +
  5336. +static struct hid_device *sid_vhf_create_hid_device(struct platform_device *pdev, struct vhf_device_metadata *meta)
  5337. +{
  5338. + struct hid_device *hid;
  5339. +
  5340. + hid = hid_allocate_device();
  5341. + if (IS_ERR(hid))
  5342. + return hid;
  5343. +
  5344. + hid->dev.parent = &pdev->dev;
  5345. +
  5346. + hid->bus = BUS_VIRTUAL;
  5347. + hid->vendor = meta->vendor_id;
  5348. + hid->product = meta->product_id;
  5349. +
  5350. + hid->ll_driver = &sid_vhf_hid_ll_driver;
  5351. +
  5352. + sprintf(hid->name, "%s", SID_VHF_INPUT_NAME);
  5353. +
  5354. + return hid;
  5355. +}
  5356. +
  5357. +static u32 sid_vhf_event_handler(struct ssam_notifier_block *nb, const struct ssam_event *event)
  5358. +{
  5359. + struct sid_vhf *vhf = container_of(nb, struct sid_vhf, notif.base);
  5360. + int status;
  5361. +
  5362. + if (event->target_category != SSAM_SSH_TC_HID)
  5363. + return 0;
  5364. +
  5365. + if (event->channel != 0x02)
  5366. + return 0;
  5367. +
  5368. + if (event->instance_id != vhf->p->instance)
  5369. + return 0;
  5370. +
  5371. + if (event->command_id != 0x00 && event->command_id != 0x03 && event->command_id != 0x04)
  5372. + return 0;
  5373. +
  5374. + // skip if HID hasn't started yet
  5375. + if (!test_bit(VHF_HID_STARTED, &vhf->state))
  5376. + return SSAM_NOTIF_HANDLED;
  5377. +
  5378. + status = hid_input_report(vhf->hid, HID_INPUT_REPORT, (u8 *)&event->data[0], event->length, 0);
  5379. + return ssam_notifier_from_errno(status) | SSAM_NOTIF_HANDLED;
  5380. +}
  5381. +
  5382. +static int surface_sam_sid_vhf_probe(struct platform_device *pdev)
  5383. +{
  5384. + const struct ssam_hid_properties *p = pdev->dev.platform_data;
  5385. + struct sid_vhf *vhf;
  5386. + struct vhf_device_metadata meta = {};
  5387. + struct hid_device *hid;
  5388. + int status;
  5389. +
  5390. + // add device link to EC
  5391. + status = surface_sam_ssh_consumer_register(&pdev->dev);
  5392. + if (status)
  5393. + return status == -ENXIO ? -EPROBE_DEFER : status;
  5394. +
  5395. + vhf = kzalloc(sizeof(struct sid_vhf), GFP_KERNEL);
  5396. + if (!vhf)
  5397. + return -ENOMEM;
  5398. +
  5399. + status = vhf_get_metadata(p->instance, &meta);
  5400. + if (status)
  5401. + goto err_create_hid;
  5402. +
  5403. + hid = sid_vhf_create_hid_device(pdev, &meta);
  5404. + if (IS_ERR(hid)) {
  5405. + status = PTR_ERR(hid);
  5406. + goto err_create_hid;
  5407. + }
  5408. +
  5409. + vhf->p = pdev->dev.platform_data;
  5410. + vhf->dev = pdev;
  5411. + vhf->hid = hid;
  5412. +
  5413. + vhf->notif.base.priority = 1;
  5414. + vhf->notif.base.fn = sid_vhf_event_handler;
  5415. + vhf->notif.event.reg = p->registry;
  5416. + vhf->notif.event.id.target_category = SSAM_SSH_TC_HID;
  5417. + vhf->notif.event.id.instance = p->instance;
  5418. + vhf->notif.event.flags = 0;
  5419. +
  5420. + platform_set_drvdata(pdev, vhf);
  5421. +
  5422. + status = surface_sam_ssh_notifier_register(&vhf->notif);
  5423. + if (status)
  5424. + goto err_notif;
  5425. +
  5426. + status = hid_add_device(hid);
  5427. + if (status)
  5428. + goto err_add_hid;
  5429. +
  5430. + return 0;
  5431. +
  5432. +err_add_hid:
  5433. + surface_sam_ssh_notifier_unregister(&vhf->notif);
  5434. +err_notif:
  5435. + hid_destroy_device(hid);
  5436. + platform_set_drvdata(pdev, NULL);
  5437. +err_create_hid:
  5438. + kfree(vhf);
  5439. + return status;
  5440. +}
  5441. +
  5442. +static int surface_sam_sid_vhf_remove(struct platform_device *pdev)
  5443. +{
  5444. + struct sid_vhf *vhf = platform_get_drvdata(pdev);
  5445. +
  5446. + surface_sam_ssh_notifier_unregister(&vhf->notif);
  5447. + hid_destroy_device(vhf->hid);
  5448. + kfree(vhf);
  5449. +
  5450. + platform_set_drvdata(pdev, NULL);
  5451. + return 0;
  5452. +}
  5453. +
  5454. +static struct platform_driver surface_sam_sid_vhf = {
  5455. + .probe = surface_sam_sid_vhf_probe,
  5456. + .remove = surface_sam_sid_vhf_remove,
  5457. + .driver = {
  5458. + .name = "surface_sam_sid_vhf",
  5459. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  5460. + },
  5461. +};
  5462. +module_platform_driver(surface_sam_sid_vhf);
  5463. +
  5464. +MODULE_AUTHOR("Blaž Hrastnik <blaz@mxxn.io>");
  5465. +MODULE_DESCRIPTION("Driver for HID devices connected via Surface SAM");
  5466. +MODULE_LICENSE("GPL");
  5467. +MODULE_ALIAS("platform:surface_sam_sid_vhf");
  5468. diff --git a/drivers/platform/x86/surface_sam/surface_sam_sid_vhf.h b/drivers/platform/x86/surface_sam/surface_sam_sid_vhf.h
  5469. new file mode 100644
  5470. index 0000000000000..eb55485ccb119
  5471. --- /dev/null
  5472. +++ b/drivers/platform/x86/surface_sam/surface_sam_sid_vhf.h
  5473. @@ -0,0 +1,13 @@
  5474. +#ifndef _SURFACE_SAM_SID_VHF_H
  5475. +#define _SURFACE_SAM_SID_VHF_H
  5476. +
  5477. +#include <linux/types.h>
  5478. +#include "surface_sam_ssh.h"
  5479. +
  5480. +
  5481. +struct ssam_hid_properties {
  5482. + struct ssam_event_registry registry;
  5483. + u8 instance;
  5484. +};
  5485. +
  5486. +#endif /* _SURFACE_SAM_SID_VHF_H */
  5487. diff --git a/drivers/platform/x86/surface_sam/surface_sam_ssh.c b/drivers/platform/x86/surface_sam/surface_sam_ssh.c
  5488. new file mode 100644
  5489. index 0000000000000..8f2c9b2182dc0
  5490. --- /dev/null
  5491. +++ b/drivers/platform/x86/surface_sam/surface_sam_ssh.c
  5492. @@ -0,0 +1,5114 @@
  5493. +// SPDX-License-Identifier: GPL-2.0-or-later
  5494. +/*
  5495. + * Surface Serial Hub (SSH) driver for communication with the Surface/System
  5496. + * Aggregator Module.
  5497. + */
  5498. +
  5499. +#include <asm/unaligned.h>
  5500. +#include <linux/acpi.h>
  5501. +#include <linux/atomic.h>
  5502. +#include <linux/completion.h>
  5503. +#include <linux/crc-ccitt.h>
  5504. +#include <linux/dmaengine.h>
  5505. +#include <linux/gpio/consumer.h>
  5506. +#include <linux/interrupt.h>
  5507. +#include <linux/jiffies.h>
  5508. +#include <linux/kernel.h>
  5509. +#include <linux/kfifo.h>
  5510. +#include <linux/kref.h>
  5511. +#include <linux/kthread.h>
  5512. +#include <linux/ktime.h>
  5513. +#include <linux/list.h>
  5514. +#include <linux/mutex.h>
  5515. +#include <linux/pm.h>
  5516. +#include <linux/refcount.h>
  5517. +#include <linux/serdev.h>
  5518. +#include <linux/spinlock.h>
  5519. +#include <linux/sysfs.h>
  5520. +#include <linux/workqueue.h>
  5521. +
  5522. +#include "surface_sam_ssh.h"
  5523. +
  5524. +#define CREATE_TRACE_POINTS
  5525. +#include "surface_sam_ssh_trace.h"
  5526. +
  5527. +
  5528. +/* -- TODO. ----------------------------------------------------------------- */
  5529. +
  5530. +#define SSH_RQST_TAG_FULL "surface_sam_ssh_rqst: "
  5531. +#define SSH_RQST_TAG "rqst: "
  5532. +
  5533. +#define SSH_SUPPORTED_FLOW_CONTROL_MASK (~((u8) ACPI_UART_FLOW_CONTROL_HW))
  5534. +
  5535. +
  5536. +/* -- Error injection helpers. ---------------------------------------------- */
  5537. +
  5538. +#ifdef CONFIG_SURFACE_SAM_SSH_ERROR_INJECTION
  5539. +#define noinline_if_inject noinline
  5540. +#else /* CONFIG_SURFACE_SAM_SSH_ERROR_INJECTION */
  5541. +#define noinline_if_inject inline
  5542. +#endif /* CONFIG_SURFACE_SAM_SSH_ERROR_INJECTION */
  5543. +
  5544. +
  5545. +/* -- Public interface. ----------------------------------------------------- */
  5546. +
  5547. +enum ssam_request_flags {
  5548. + SSAM_REQUEST_HAS_RESPONSE = BIT(0),
  5549. + SSAM_REQUEST_UNSEQUENCED = BIT(1),
  5550. +};
  5551. +
  5552. +struct ssam_request {
  5553. + u8 target_category;
  5554. + u8 command_id;
  5555. + u8 instance_id;
  5556. + u8 channel;
  5557. + u16 flags;
  5558. + u16 length;
  5559. + u8 *payload;
  5560. +};
  5561. +
  5562. +
  5563. +/* -- Common/utility functions. --------------------------------------------- */
  5564. +
  5565. +static inline u16 ssh_crc(const u8 *buf, size_t len)
  5566. +{
  5567. + return crc_ccitt_false(0xffff, buf, len);
  5568. +}
  5569. +
  5570. +static inline u16 __ssh_rqid_next(u16 rqid)
  5571. +{
  5572. + return rqid > 0 ? rqid + 1u : rqid + SURFACE_SAM_SSH_NUM_EVENTS + 1u;
  5573. +}
  5574. +
  5575. +static inline u16 ssh_event_to_rqid(u16 event)
  5576. +{
  5577. + return event + 1u;
  5578. +}
  5579. +
  5580. +static inline u16 ssh_rqid_to_event(u16 rqid)
  5581. +{
  5582. + return rqid - 1u;
  5583. +}
  5584. +
  5585. +static inline bool ssh_rqid_is_event(u16 rqid)
  5586. +{
  5587. + return ssh_rqid_to_event(rqid) < SURFACE_SAM_SSH_NUM_EVENTS;
  5588. +}
  5589. +
  5590. +static inline int ssh_tc_to_rqid(u8 tc)
  5591. +{
  5592. +#if 0 // TODO: check if it works without this
  5593. + /*
  5594. + * TC=0x08 represents the input subsystem on Surface Laptop 1 and 2.
  5595. + * This is mapped on Windows to RQID=0x0001. As input events seem to be
  5596. + * somewhat special with regards to enabling/disabling (they seem to be
  5597. + * enabled by default with a fixed RQID), let's do the same here.
  5598. + */
  5599. + if (tc == 0x08)
  5600. + return 0x0001;
  5601. +
  5602. + /* Default path: Set RQID = TC. */
  5603. +#endif
  5604. + return tc;
  5605. +}
  5606. +
  5607. +static inline int ssh_tc_to_event(u8 tc)
  5608. +{
  5609. + return ssh_rqid_to_event(ssh_tc_to_rqid(tc));
  5610. +}
  5611. +
  5612. +static inline u8 ssh_channel_to_index(u8 channel)
  5613. +{
  5614. + return channel - 1u;
  5615. +}
  5616. +
  5617. +static inline bool ssh_channel_is_valid(u8 channel)
  5618. +{
  5619. + return ssh_channel_to_index(channel) < SURFACE_SAM_SSH_NUM_CHANNELS;
  5620. +}
  5621. +
  5622. +
  5623. +/* -- Safe counters. -------------------------------------------------------- */
  5624. +
  5625. +struct ssh_seq_counter {
  5626. + u8 value;
  5627. +};
  5628. +
  5629. +struct ssh_rqid_counter {
  5630. + u16 value;
  5631. +};
  5632. +
  5633. +static inline void ssh_seq_reset(struct ssh_seq_counter *c)
  5634. +{
  5635. + WRITE_ONCE(c->value, 0);
  5636. +}
  5637. +
  5638. +static inline u8 ssh_seq_next(struct ssh_seq_counter *c)
  5639. +{
  5640. + u8 old = READ_ONCE(c->value);
  5641. + u8 new = old + 1;
  5642. + u8 ret;
  5643. +
  5644. + while (unlikely((ret = cmpxchg(&c->value, old, new)) != old)) {
  5645. + old = ret;
  5646. + new = old + 1;
  5647. + }
  5648. +
  5649. + return old;
  5650. +}
  5651. +
  5652. +static inline void ssh_rqid_reset(struct ssh_rqid_counter *c)
  5653. +{
  5654. + WRITE_ONCE(c->value, 0);
  5655. +}
  5656. +
  5657. +static inline u16 ssh_rqid_next(struct ssh_rqid_counter *c)
  5658. +{
  5659. + u16 old = READ_ONCE(c->value);
  5660. + u16 new = __ssh_rqid_next(old);
  5661. + u16 ret;
  5662. +
  5663. + while (unlikely((ret = cmpxchg(&c->value, old, new)) != old)) {
  5664. + old = ret;
  5665. + new = __ssh_rqid_next(old);
  5666. + }
  5667. +
  5668. + return old;
  5669. +}
  5670. +
  5671. +
  5672. +/* -- Builder functions for SAM-over-SSH messages. -------------------------- */
  5673. +
  5674. +struct msgbuf {
  5675. + u8 *buffer;
  5676. + u8 *end;
  5677. + u8 *ptr;
  5678. +};
  5679. +
  5680. +static inline void msgb_init(struct msgbuf *msgb, u8 *buffer, size_t cap)
  5681. +{
  5682. + msgb->buffer = buffer;
  5683. + msgb->end = buffer + cap;
  5684. + msgb->ptr = buffer;
  5685. +}
  5686. +
  5687. +static inline int msgb_alloc(struct msgbuf *msgb, size_t cap, gfp_t flags)
  5688. +{
  5689. + u8 *buf;
  5690. +
  5691. + buf = kzalloc(cap, flags);
  5692. + if (!buf)
  5693. + return -ENOMEM;
  5694. +
  5695. + msgb_init(msgb, buf, cap);
  5696. + return 0;
  5697. +}
  5698. +
  5699. +static inline void msgb_free(struct msgbuf *msgb)
  5700. +{
  5701. + kfree(msgb->buffer);
  5702. + msgb->buffer = NULL;
  5703. + msgb->end = NULL;
  5704. + msgb->ptr = NULL;
  5705. +}
  5706. +
  5707. +static inline void msgb_reset(struct msgbuf *msgb)
  5708. +{
  5709. + msgb->ptr = msgb->buffer;
  5710. +}
  5711. +
  5712. +static inline size_t msgb_bytes_used(const struct msgbuf *msgb)
  5713. +{
  5714. + return msgb->ptr - msgb->buffer;
  5715. +}
  5716. +
  5717. +static inline void msgb_push_u16(struct msgbuf *msgb, u16 value)
  5718. +{
  5719. + WARN_ON(msgb->ptr + sizeof(u16) > msgb->end);
  5720. + if (msgb->ptr + sizeof(u16) > msgb->end)
  5721. + return;
  5722. +
  5723. + put_unaligned_le16(value, msgb->ptr);
  5724. + msgb->ptr += sizeof(u16);
  5725. +}
  5726. +
  5727. +static inline void msgb_push_syn(struct msgbuf *msgb)
  5728. +{
  5729. + msgb_push_u16(msgb, SSH_MSG_SYN);
  5730. +}
  5731. +
  5732. +static inline void msgb_push_buf(struct msgbuf *msgb, const u8 *buf, size_t len)
  5733. +{
  5734. + msgb->ptr = memcpy(msgb->ptr, buf, len) + len;
  5735. +}
  5736. +
  5737. +static inline void msgb_push_crc(struct msgbuf *msgb, const u8 *buf, size_t len)
  5738. +{
  5739. + msgb_push_u16(msgb, ssh_crc(buf, len));
  5740. +}
  5741. +
  5742. +static inline void msgb_push_frame(struct msgbuf *msgb, u8 ty, u16 len, u8 seq)
  5743. +{
  5744. + struct ssh_frame *frame = (struct ssh_frame *)msgb->ptr;
  5745. + const u8 *const begin = msgb->ptr;
  5746. +
  5747. + WARN_ON(msgb->ptr + sizeof(*frame) > msgb->end);
  5748. + if (msgb->ptr + sizeof(*frame) > msgb->end)
  5749. + return;
  5750. +
  5751. + frame->type = ty;
  5752. + put_unaligned_le16(len, &frame->len);
  5753. + frame->seq = seq;
  5754. +
  5755. + msgb->ptr += sizeof(*frame);
  5756. + msgb_push_crc(msgb, begin, msgb->ptr - begin);
  5757. +}
  5758. +
  5759. +static inline void msgb_push_ack(struct msgbuf *msgb, u8 seq)
  5760. +{
  5761. + // SYN
  5762. + msgb_push_syn(msgb);
  5763. +
  5764. + // ACK-type frame + CRC
  5765. + msgb_push_frame(msgb, SSH_FRAME_TYPE_ACK, 0x00, seq);
  5766. +
  5767. + // payload CRC (ACK-type frames do not have a payload)
  5768. + msgb_push_crc(msgb, msgb->ptr, 0);
  5769. +}
  5770. +
  5771. +static inline void msgb_push_nak(struct msgbuf *msgb)
  5772. +{
  5773. + // SYN
  5774. + msgb_push_syn(msgb);
  5775. +
  5776. + // NAK-type frame + CRC
  5777. + msgb_push_frame(msgb, SSH_FRAME_TYPE_NAK, 0x00, 0x00);
  5778. +
  5779. + // payload CRC (ACK-type frames do not have a payload)
  5780. + msgb_push_crc(msgb, msgb->ptr, 0);
  5781. +}
  5782. +
  5783. +static inline void msgb_push_cmd(struct msgbuf *msgb, u8 seq,
  5784. + const struct surface_sam_ssh_rqst *rqst,
  5785. + u16 rqid)
  5786. +{
  5787. + struct ssh_command *cmd;
  5788. + const u8 *cmd_begin;
  5789. + const u8 type = SSH_FRAME_TYPE_DATA_SEQ;
  5790. +
  5791. + // SYN
  5792. + msgb_push_syn(msgb);
  5793. +
  5794. + // command frame + crc
  5795. + msgb_push_frame(msgb, type, sizeof(*cmd) + rqst->cdl, seq);
  5796. +
  5797. + // frame payload: command struct + payload
  5798. + WARN_ON(msgb->ptr + sizeof(*cmd) > msgb->end);
  5799. + if (msgb->ptr + sizeof(*cmd) > msgb->end)
  5800. + return;
  5801. +
  5802. + cmd_begin = msgb->ptr;
  5803. + cmd = (struct ssh_command *)msgb->ptr;
  5804. +
  5805. + cmd->type = SSH_PLD_TYPE_CMD;
  5806. + cmd->tc = rqst->tc;
  5807. + cmd->chn_out = rqst->chn;
  5808. + cmd->chn_in = 0x00;
  5809. + cmd->iid = rqst->iid;
  5810. + put_unaligned_le16(rqid, &cmd->rqid);
  5811. + cmd->cid = rqst->cid;
  5812. +
  5813. + msgb->ptr += sizeof(*cmd);
  5814. +
  5815. + // command payload
  5816. + msgb_push_buf(msgb, rqst->pld, rqst->cdl);
  5817. +
  5818. + // crc for command struct + payload
  5819. + msgb_push_crc(msgb, cmd_begin, msgb->ptr - cmd_begin);
  5820. +}
  5821. +
  5822. +
  5823. +/* -- Parser functions and utilities for SAM-over-SSH messages. ------------- */
  5824. +
  5825. +struct sshp_buf {
  5826. + u8 *ptr;
  5827. + size_t len;
  5828. + size_t cap;
  5829. +};
  5830. +
  5831. +
  5832. +static inline bool sshp_validate_crc(const struct sshp_span *src, const u8 *crc)
  5833. +{
  5834. + u16 actual = ssh_crc(src->ptr, src->len);
  5835. + u16 expected = get_unaligned_le16(crc);
  5836. +
  5837. + return actual == expected;
  5838. +}
  5839. +
  5840. +static bool sshp_find_syn(const struct sshp_span *src, struct sshp_span *rem)
  5841. +{
  5842. + size_t i;
  5843. +
  5844. + for (i = 0; i < src->len - 1; i++) {
  5845. + if (likely(get_unaligned_le16(src->ptr + i) == SSH_MSG_SYN)) {
  5846. + rem->ptr = src->ptr + i;
  5847. + rem->len = src->len - i;
  5848. + return true;
  5849. + }
  5850. + }
  5851. +
  5852. + if (unlikely(src->ptr[src->len - 1] == (SSH_MSG_SYN & 0xff))) {
  5853. + rem->ptr = src->ptr + src->len - 1;
  5854. + rem->len = 1;
  5855. + return false;
  5856. + } else {
  5857. + rem->ptr = src->ptr + src->len;
  5858. + rem->len = 0;
  5859. + return false;
  5860. + }
  5861. +}
  5862. +
  5863. +static bool sshp_starts_with_syn(const struct sshp_span *src)
  5864. +{
  5865. + return src->len >= 2 && get_unaligned_le16(src->ptr) == SSH_MSG_SYN;
  5866. +}
  5867. +
  5868. +static int sshp_parse_frame(const struct device *dev,
  5869. + const struct sshp_span *source,
  5870. + struct ssh_frame **frame,
  5871. + struct sshp_span *payload,
  5872. + size_t maxlen)
  5873. +{
  5874. + struct sshp_span sf;
  5875. + struct sshp_span sp;
  5876. +
  5877. + // initialize output
  5878. + *frame = NULL;
  5879. + payload->ptr = NULL;
  5880. + payload->len = 0;
  5881. +
  5882. + if (!sshp_starts_with_syn(source)) {
  5883. + dev_warn(dev, "rx: parser: invalid start of frame\n");
  5884. + return -ENOMSG;
  5885. + }
  5886. +
  5887. + // check for minumum packet length
  5888. + if (unlikely(source->len < SSH_MESSAGE_LENGTH(0))) {
  5889. + dev_dbg(dev, "rx: parser: not enough data for frame\n");
  5890. + return 0;
  5891. + }
  5892. +
  5893. + // pin down frame
  5894. + sf.ptr = source->ptr + sizeof(u16);
  5895. + sf.len = sizeof(struct ssh_frame);
  5896. +
  5897. + // validate frame CRC
  5898. + if (unlikely(!sshp_validate_crc(&sf, sf.ptr + sf.len))) {
  5899. + dev_warn(dev, "rx: parser: invalid frame CRC\n");
  5900. + return -EBADMSG;
  5901. + }
  5902. +
  5903. + // ensure packet does not exceed maximum length
  5904. + if (unlikely(((struct ssh_frame *)sf.ptr)->len > maxlen)) {
  5905. + dev_warn(dev, "rx: parser: frame too large: %u bytes\n",
  5906. + ((struct ssh_frame *)sf.ptr)->len);
  5907. + return -EMSGSIZE;
  5908. + }
  5909. +
  5910. + // pin down payload
  5911. + sp.ptr = sf.ptr + sf.len + sizeof(u16);
  5912. + sp.len = get_unaligned_le16(&((struct ssh_frame *)sf.ptr)->len);
  5913. +
  5914. + // check for frame + payload length
  5915. + if (source->len < SSH_MESSAGE_LENGTH(sp.len)) {
  5916. + dev_dbg(dev, "rx: parser: not enough data for payload\n");
  5917. + return 0;
  5918. + }
  5919. +
  5920. + // validate payload crc
  5921. + if (unlikely(!sshp_validate_crc(&sp, sp.ptr + sp.len))) {
  5922. + dev_warn(dev, "rx: parser: invalid payload CRC\n");
  5923. + return -EBADMSG;
  5924. + }
  5925. +
  5926. + *frame = (struct ssh_frame *)sf.ptr;
  5927. + *payload = sp;
  5928. +
  5929. + dev_dbg(dev, "rx: parser: valid frame found (type: 0x%02x, len: %u)\n",
  5930. + (*frame)->type, (*frame)->len);
  5931. +
  5932. + return 0;
  5933. +}
  5934. +
  5935. +static int sshp_parse_command(const struct device *dev,
  5936. + const struct sshp_span *source,
  5937. + struct ssh_command **command,
  5938. + struct sshp_span *command_data)
  5939. +{
  5940. + // check for minimum length
  5941. + if (unlikely(source->len < sizeof(struct ssh_command))) {
  5942. + *command = NULL;
  5943. + command_data->ptr = NULL;
  5944. + command_data->len = 0;
  5945. +
  5946. + dev_err(dev, "rx: parser: command payload is too short\n");
  5947. + return -ENOMSG;
  5948. + }
  5949. +
  5950. + *command = (struct ssh_command *)source->ptr;
  5951. + command_data->ptr = source->ptr + sizeof(struct ssh_command);
  5952. + command_data->len = source->len - sizeof(struct ssh_command);
  5953. +
  5954. + dev_dbg(dev, "rx: parser: valid command found (tc: 0x%02x,"
  5955. + " cid: 0x%02x)\n", (*command)->tc, (*command)->cid);
  5956. +
  5957. + return 0;
  5958. +}
  5959. +
  5960. +
  5961. +static inline void sshp_buf_init(struct sshp_buf *buf, u8 *ptr, size_t cap)
  5962. +{
  5963. + buf->ptr = ptr;
  5964. + buf->len = 0;
  5965. + buf->cap = cap;
  5966. +}
  5967. +
  5968. +static inline int sshp_buf_alloc(struct sshp_buf *buf, size_t cap, gfp_t flags)
  5969. +{
  5970. + u8 *ptr;
  5971. +
  5972. + ptr = kzalloc(cap, flags);
  5973. + if (!ptr)
  5974. + return -ENOMEM;
  5975. +
  5976. + sshp_buf_init(buf, ptr, cap);
  5977. + return 0;
  5978. +
  5979. +}
  5980. +
  5981. +static inline void sshp_buf_free(struct sshp_buf *buf)
  5982. +{
  5983. + kfree(buf->ptr);
  5984. + buf->ptr = NULL;
  5985. + buf->len = 0;
  5986. + buf->cap = 0;
  5987. +}
  5988. +
  5989. +static inline void sshp_buf_reset(struct sshp_buf *buf)
  5990. +{
  5991. + buf->len = 0;
  5992. +}
  5993. +
  5994. +static inline void sshp_buf_drop(struct sshp_buf *buf, size_t n)
  5995. +{
  5996. + memmove(buf->ptr, buf->ptr + n, buf->len - n);
  5997. + buf->len -= n;
  5998. +}
  5999. +
  6000. +static inline size_t sshp_buf_read_from_fifo(struct sshp_buf *buf,
  6001. + struct kfifo *fifo)
  6002. +{
  6003. + size_t n;
  6004. +
  6005. + n = kfifo_out(fifo, buf->ptr + buf->len, buf->cap - buf->len);
  6006. + buf->len += n;
  6007. +
  6008. + return n;
  6009. +}
  6010. +
  6011. +static inline void sshp_buf_span_from(struct sshp_buf *buf, size_t offset,
  6012. + struct sshp_span *span)
  6013. +{
  6014. + span->ptr = buf->ptr + offset;
  6015. + span->len = buf->len - offset;
  6016. +}
  6017. +
  6018. +
  6019. +/* -- Packet transport layer (ptl). ----------------------------------------- */
  6020. +/*
  6021. + * To simplify reasoning about the code below, we define a few concepts. The
  6022. + * system below is similar to a state-machine for packets, however, there are
  6023. + * too many states to explicitly write them down. To (somewhat) manage the
  6024. + * states and packets we rely on flags, reference counting, and some simple
  6025. + * concepts. State transitions are triggered by actions.
  6026. + *
  6027. + * >> Actions <<
  6028. + *
  6029. + * - submit
  6030. + * - transmission start (process next item in queue)
  6031. + * - transmission finished (guaranteed to never be parallel to transmission
  6032. + * start)
  6033. + * - ACK received
  6034. + * - NAK received (this is equivalent to issuing re-submit for all pending
  6035. + * packets)
  6036. + * - timeout (this is equivalent to re-issuing a submit or canceling)
  6037. + * - cancel (non-pending and pending)
  6038. + *
  6039. + * >> Data Structures, Packet Ownership, General Overview <<
  6040. + *
  6041. + * The code below employs two main data structures: The packet queue, containing
  6042. + * all packets scheduled for transmission, and the set of pending packets,
  6043. + * containing all packets awaiting an ACK.
  6044. + *
  6045. + * Shared ownership of a packet is controlled via reference counting. Inside the
  6046. + * transmission system are a total of five packet owners:
  6047. + *
  6048. + * - the packet queue,
  6049. + * - the pending set,
  6050. + * - the transmitter thread,
  6051. + * - the receiver thread (via ACKing), and
  6052. + * - the timeout work item.
  6053. + *
  6054. + * Normal operation is as follows: The initial reference of the packet is
  6055. + * obtained by submitting the packet and queueing it. The receiver thread
  6056. + * takes packets from the queue. By doing this, it does not increment the
  6057. + * refcount but takes over the reference (removing it from the queue).
  6058. + * If the packet is sequenced (i.e. needs to be ACKed by the client), the
  6059. + * transmitter thread sets-up the timeout and adds the packet to the pending set
  6060. + * before starting to transmit it. As the timeout is handled by a reaper task,
  6061. + * no additional reference for it is needed. After the transmit is done, the
  6062. + * reference hold by the transmitter thread is dropped. If the packet is
  6063. + * unsequenced (i.e. does not need an ACK), the packet is completed by the
  6064. + * transmitter thread before dropping that reference.
  6065. + *
  6066. + * On receial of an ACK, the receiver thread removes and obtains the refernce to
  6067. + * the packet from the pending set. On succes, the receiver thread will then
  6068. + * complete the packet and drop its reference.
  6069. + *
  6070. + * On error, the completion callback is immediately run by on thread on which
  6071. + * the error was detected.
  6072. + *
  6073. + * To ensure that a packet eventually leaves the system it is marked as "locked"
  6074. + * directly before it is going to be completed or when it is canceled. Marking a
  6075. + * packet as "locked" has the effect that passing and creating new references
  6076. + * of the packet will be blocked. This means that the packet cannot be added
  6077. + * to the queue, the pending set, and the timeout, or be picked up by the
  6078. + * transmitter thread or receiver thread. To remove a packet from the system it
  6079. + * has to be marked as locked and subsequently all references from the data
  6080. + * structures (queue, pending) have to be removed. References held by threads
  6081. + * will eventually be dropped automatically as their execution progresses.
  6082. + *
  6083. + * Note that the packet completion callback is, in case of success and for a
  6084. + * sequenced packet, guaranteed to run on the receiver thread, thus providing a
  6085. + * way to reliably identify responses to the packet. The packet completion
  6086. + * callback is only run once and it does not indicate that the packet has fully
  6087. + * left the system. In case of re-submission (and with somewhat unlikely
  6088. + * timing), it may be possible that the packet is being re-transmitted while the
  6089. + * completion callback runs. Completion will occur both on success and internal
  6090. + * error, as well as when the packet is canceled.
  6091. + *
  6092. + * >> Flags <<
  6093. + *
  6094. + * Flags are used to indicate the state and progression of a packet. Some flags
  6095. + * have stricter guarantees than other:
  6096. + *
  6097. + * - locked
  6098. + * Indicates if the packet is locked. If the packet is locked, passing and/or
  6099. + * creating additional references to the packet is forbidden. The packet thus
  6100. + * may not be queued, dequeued, or removed or added to the pending set. Note
  6101. + * that the packet state flags may still change (e.g. it may be marked as
  6102. + * ACKed, transmitted, ...).
  6103. + *
  6104. + * - completed
  6105. + * Indicates if the packet completion has been run or is about to be run. This
  6106. + * flag is used to ensure that the packet completion callback is only run
  6107. + * once.
  6108. + *
  6109. + * - queued
  6110. + * Indicates if a packet is present in the submission queue or not. This flag
  6111. + * must only be modified with the queue lock held, and must be coherent
  6112. + * presence of the packet in the queue.
  6113. + *
  6114. + * - pending
  6115. + * Indicates if a packet is present in the set of pending packets or not.
  6116. + * This flag must only be modified with the pending lock held, and must be
  6117. + * coherent presence of the packet in the pending set.
  6118. + *
  6119. + * - transmitting
  6120. + * Indicates if the packet is currently transmitting. In case of
  6121. + * re-transmissions, it is only safe to wait on the "transmitted" completion
  6122. + * after this flag has been set. The completion will be set both in success
  6123. + * and error case.
  6124. + *
  6125. + * - transmitted
  6126. + * Indicates if the packet has been transmitted. This flag is not cleared by
  6127. + * the system, thus it indicates the first transmission only.
  6128. + *
  6129. + * - acked
  6130. + * Indicates if the packet has been acknowledged by the client. There are no
  6131. + * other guarantees given. For example, the packet may still be canceled
  6132. + * and/or the completion may be triggered an error even though this bit is
  6133. + * set. Rely on the status provided by completion instead.
  6134. + *
  6135. + * - canceled
  6136. + * Indicates if the packet has been canceled from the outside. There are no
  6137. + * other guarantees given. Specifically, the packet may be completed by
  6138. + * another part of the system before the cancellation attempts to complete it.
  6139. + *
  6140. + * >> General Notes <<
  6141. + *
  6142. + * To avoid deadlocks, if both queue and pending locks are required, the pending
  6143. + * lock must be acquired before the queue lock.
  6144. + */
  6145. +
  6146. +/**
  6147. + * Maximum number transmission attempts per sequenced packet in case of
  6148. + * time-outs. Must be smaller than 16.
  6149. + */
  6150. +#define SSH_PTL_MAX_PACKET_TRIES 3
  6151. +
  6152. +/**
  6153. + * Timeout as ktime_t delta for ACKs. If we have not received an ACK in this
  6154. + * time-frame after starting transmission, the packet will be re-submitted.
  6155. + */
  6156. +#define SSH_PTL_PACKET_TIMEOUT ms_to_ktime(1000)
  6157. +
  6158. +/**
  6159. + * Maximum time resolution for timeouts. Currently set to max(2 jiffies, 50ms).
  6160. + * Should be larger than one jiffy to avoid direct re-scheduling of reaper
  6161. + * work_struct.
  6162. + */
  6163. +#define SSH_PTL_PACKET_TIMEOUT_RESOLUTION ms_to_ktime(max(2000 / HZ, 50))
  6164. +
  6165. +/**
  6166. + * Maximum number of sequenced packets concurrently waiting for an ACK.
  6167. + * Packets marked as blocking will not be transmitted while this limit is
  6168. + * reached.
  6169. + */
  6170. +#define SSH_PTL_MAX_PENDING 1
  6171. +
  6172. +#define SSH_PTL_RX_BUF_LEN 4096
  6173. +
  6174. +#define SSH_PTL_RX_FIFO_LEN 4096
  6175. +
  6176. +
  6177. +enum ssh_ptl_state_flags {
  6178. + SSH_PTL_SF_SHUTDOWN_BIT,
  6179. +};
  6180. +
  6181. +struct ssh_ptl_ops {
  6182. + void (*data_received)(struct ssh_ptl *p, const struct sshp_span *data);
  6183. +};
  6184. +
  6185. +struct ssh_ptl {
  6186. + struct serdev_device *serdev;
  6187. + unsigned long state;
  6188. +
  6189. + struct {
  6190. + spinlock_t lock;
  6191. + struct list_head head;
  6192. + } queue;
  6193. +
  6194. + struct {
  6195. + spinlock_t lock;
  6196. + struct list_head head;
  6197. + atomic_t count;
  6198. + } pending;
  6199. +
  6200. + struct {
  6201. + bool thread_signal;
  6202. + struct task_struct *thread;
  6203. + struct wait_queue_head thread_wq;
  6204. + struct wait_queue_head packet_wq;
  6205. + struct ssh_packet *packet;
  6206. + size_t offset;
  6207. + } tx;
  6208. +
  6209. + struct {
  6210. + struct task_struct *thread;
  6211. + struct wait_queue_head wq;
  6212. + struct kfifo fifo;
  6213. + struct sshp_buf buf;
  6214. +
  6215. + struct {
  6216. + u16 seqs[8];
  6217. + u16 offset;
  6218. + } blacklist;
  6219. + } rx;
  6220. +
  6221. + struct {
  6222. + ktime_t timeout;
  6223. + ktime_t expires;
  6224. + struct delayed_work reaper;
  6225. + } rtx_timeout;
  6226. +
  6227. + struct ssh_ptl_ops ops;
  6228. +};
  6229. +
  6230. +
  6231. +#define __ssam_prcond(func, p, fmt, ...) \
  6232. + do { \
  6233. + if ((p)) \
  6234. + func((p), fmt, ##__VA_ARGS__); \
  6235. + } while (0);
  6236. +
  6237. +#define ptl_dbg(p, fmt, ...) dev_dbg(&(p)->serdev->dev, fmt, ##__VA_ARGS__)
  6238. +#define ptl_info(p, fmt, ...) dev_info(&(p)->serdev->dev, fmt, ##__VA_ARGS__)
  6239. +#define ptl_warn(p, fmt, ...) dev_warn(&(p)->serdev->dev, fmt, ##__VA_ARGS__)
  6240. +#define ptl_err(p, fmt, ...) dev_err(&(p)->serdev->dev, fmt, ##__VA_ARGS__)
  6241. +#define ptl_dbg_cond(p, fmt, ...) __ssam_prcond(ptl_dbg, p, fmt, ##__VA_ARGS__)
  6242. +
  6243. +#define to_ssh_packet(ptr, member) \
  6244. + container_of(ptr, struct ssh_packet, member)
  6245. +
  6246. +#define to_ssh_ptl(ptr, member) \
  6247. + container_of(ptr, struct ssh_ptl, member)
  6248. +
  6249. +
  6250. +#ifdef CONFIG_SURFACE_SAM_SSH_ERROR_INJECTION
  6251. +
  6252. +/**
  6253. + * ssh_ptl_should_drop_ack_packet - error injection hook to drop ACK packets
  6254. + *
  6255. + * Useful to test detection and handling of automated re-transmits by the EC.
  6256. + * Specifically of packets that the EC consideres not-ACKed but the driver
  6257. + * already consideres ACKed (due to dropped ACK). In this case, the EC
  6258. + * re-transmits the packet-to-be-ACKed and the driver should detect it as
  6259. + * duplicate/already handled. Note that the driver should still send an ACK
  6260. + * for the re-transmitted packet.
  6261. + */
  6262. +static noinline bool ssh_ptl_should_drop_ack_packet(void)
  6263. +{
  6264. + return false;
  6265. +}
  6266. +ALLOW_ERROR_INJECTION(ssh_ptl_should_drop_ack_packet, TRUE);
  6267. +
  6268. +/**
  6269. + * ssh_ptl_should_drop_nak_packet - error injection hook to drop NAK packets
  6270. + *
  6271. + * Useful to test/force automated (timeout-based) re-transmit by the EC.
  6272. + * Specifically, packets that have not reached the driver completely/with valid
  6273. + * checksums. Only useful in combination with receival of (injected) bad data.
  6274. + */
  6275. +static noinline bool ssh_ptl_should_drop_nak_packet(void)
  6276. +{
  6277. + return false;
  6278. +}
  6279. +ALLOW_ERROR_INJECTION(ssh_ptl_should_drop_nak_packet, TRUE);
  6280. +
  6281. +/**
  6282. + * ssh_ptl_should_drop_dsq_packet - error injection hook to drop sequenced data
  6283. + * packet
  6284. + *
  6285. + * Useful to test re-transmit timeout of the driver. If the data packet has not
  6286. + * been ACKed after a certain time, the driver should re-transmit the packet up
  6287. + * to limited number of times defined in SSH_PTL_MAX_PACKET_TRIES.
  6288. + */
  6289. +static noinline bool ssh_ptl_should_drop_dsq_packet(void)
  6290. +{
  6291. + return false;
  6292. +}
  6293. +ALLOW_ERROR_INJECTION(ssh_ptl_should_drop_dsq_packet, TRUE);
  6294. +
  6295. +/**
  6296. + * ssh_ptl_should_fail_write - error injection hook to make serdev_device_write
  6297. + * fail
  6298. + *
  6299. + * Hook to simulate errors in serdev_device_write when transmitting packets.
  6300. + */
  6301. +static noinline int ssh_ptl_should_fail_write(void)
  6302. +{
  6303. + return 0;
  6304. +}
  6305. +ALLOW_ERROR_INJECTION(ssh_ptl_should_fail_write, ERRNO);
  6306. +
  6307. +/**
  6308. + * ssh_ptl_should_corrupt_tx_data - error injection hook to simualte invalid
  6309. + * data being sent to the EC
  6310. + *
  6311. + * Hook to simulate corrupt/invalid data being sent from host (driver) to EC.
  6312. + * Causes the package data to be actively corrupted by overwriting it with
  6313. + * pre-defined values, such that it becomes invalid, causing the EC to respond
  6314. + * with a NAK packet. Useful to test handling of NAK packets received by the
  6315. + * driver.
  6316. + */
  6317. +static noinline bool ssh_ptl_should_corrupt_tx_data(void)
  6318. +{
  6319. + return false;
  6320. +}
  6321. +ALLOW_ERROR_INJECTION(ssh_ptl_should_corrupt_tx_data, TRUE);
  6322. +
  6323. +/**
  6324. + * ssh_ptl_should_corrupt_rx_syn - error injection hook to simulate invalid
  6325. + * data being sent by the EC
  6326. + *
  6327. + * Hook to simulate invalid SYN bytes, i.e. an invalid start of messages and
  6328. + * test handling thereof in the driver.
  6329. + */
  6330. +static noinline bool ssh_ptl_should_corrupt_rx_syn(void)
  6331. +{
  6332. + return false;
  6333. +}
  6334. +ALLOW_ERROR_INJECTION(ssh_ptl_should_corrupt_rx_syn, TRUE);
  6335. +
  6336. +/**
  6337. + * ssh_ptl_should_corrupt_rx_data - error injection hook to simulate invalid
  6338. + * data being sent by the EC
  6339. + *
  6340. + * Hook to simulate invalid data/checksum of the message frame and test handling
  6341. + * thereof in the driver.
  6342. + */
  6343. +static noinline bool ssh_ptl_should_corrupt_rx_data(void)
  6344. +{
  6345. + return false;
  6346. +}
  6347. +ALLOW_ERROR_INJECTION(ssh_ptl_should_corrupt_rx_data, TRUE);
  6348. +
  6349. +
  6350. +static inline bool __ssh_ptl_should_drop_ack_packet(struct ssh_packet *packet)
  6351. +{
  6352. + if (likely(!ssh_ptl_should_drop_ack_packet()))
  6353. + return false;
  6354. +
  6355. + trace_ssam_ei_tx_drop_ack_packet(packet);
  6356. + ptl_info(packet->ptl, "packet error injection: dropping ACK packet %p\n",
  6357. + packet);
  6358. +
  6359. + return true;
  6360. +}
  6361. +
  6362. +static inline bool __ssh_ptl_should_drop_nak_packet(struct ssh_packet *packet)
  6363. +{
  6364. + if (likely(!ssh_ptl_should_drop_nak_packet()))
  6365. + return false;
  6366. +
  6367. + trace_ssam_ei_tx_drop_nak_packet(packet);
  6368. + ptl_info(packet->ptl, "packet error injection: dropping NAK packet %p\n",
  6369. + packet);
  6370. +
  6371. + return true;
  6372. +}
  6373. +
  6374. +static inline bool __ssh_ptl_should_drop_dsq_packet(struct ssh_packet *packet)
  6375. +{
  6376. + if (likely(!ssh_ptl_should_drop_dsq_packet()))
  6377. + return false;
  6378. +
  6379. + trace_ssam_ei_tx_drop_dsq_packet(packet);
  6380. + ptl_info(packet->ptl,
  6381. + "packet error injection: dropping sequenced data packet %p\n",
  6382. + packet);
  6383. +
  6384. + return true;
  6385. +}
  6386. +
  6387. +static bool ssh_ptl_should_drop_packet(struct ssh_packet *packet)
  6388. +{
  6389. + // ignore packets that don't carry any data (i.e. flush)
  6390. + if (!packet->data || !packet->data_length)
  6391. + return false;
  6392. +
  6393. + switch (packet->data[SSH_MSGOFFSET_FRAME(type)]) {
  6394. + case SSH_FRAME_TYPE_ACK:
  6395. + return __ssh_ptl_should_drop_ack_packet(packet);
  6396. +
  6397. + case SSH_FRAME_TYPE_NAK:
  6398. + return __ssh_ptl_should_drop_nak_packet(packet);
  6399. +
  6400. + case SSH_FRAME_TYPE_DATA_SEQ:
  6401. + return __ssh_ptl_should_drop_dsq_packet(packet);
  6402. +
  6403. + default:
  6404. + return false;
  6405. + }
  6406. +}
  6407. +
  6408. +static inline int ssh_ptl_write_buf(struct ssh_ptl *ptl,
  6409. + struct ssh_packet *packet,
  6410. + const unsigned char *buf,
  6411. + size_t count)
  6412. +{
  6413. + int status;
  6414. +
  6415. + status = ssh_ptl_should_fail_write();
  6416. + if (unlikely(status)) {
  6417. + trace_ssam_ei_tx_fail_write(packet, status);
  6418. + ptl_info(packet->ptl,
  6419. + "packet error injection: simulating transmit error %d, packet %p\n",
  6420. + status, packet);
  6421. +
  6422. + return status;
  6423. + }
  6424. +
  6425. + return serdev_device_write_buf(ptl->serdev, buf, count);
  6426. +}
  6427. +
  6428. +static inline void ssh_ptl_tx_inject_invalid_data(struct ssh_packet *packet)
  6429. +{
  6430. + // ignore packets that don't carry any data (i.e. flush)
  6431. + if (!packet->data || !packet->data_length)
  6432. + return;
  6433. +
  6434. + // only allow sequenced data packets to be modified
  6435. + if (packet->data[SSH_MSGOFFSET_FRAME(type)] != SSH_FRAME_TYPE_DATA_SEQ)
  6436. + return;
  6437. +
  6438. + if (likely(!ssh_ptl_should_corrupt_tx_data()))
  6439. + return;
  6440. +
  6441. + trace_ssam_ei_tx_corrupt_data(packet);
  6442. + ptl_info(packet->ptl,
  6443. + "packet error injection: simulating invalid transmit data on packet %p\n",
  6444. + packet);
  6445. +
  6446. + /*
  6447. + * NB: The value 0xb3 has been chosen more or less randomly so that it
  6448. + * doesn't have any (major) overlap with the SYN bytes (aa 55) and is
  6449. + * non-trivial (i.e. non-zero, non-0xff).
  6450. + */
  6451. + memset(packet->data, 0xb3, packet->data_length);
  6452. +}
  6453. +
  6454. +static inline void ssh_ptl_rx_inject_invalid_syn(struct ssh_ptl *ptl,
  6455. + struct sshp_span *data)
  6456. +{
  6457. + struct sshp_span frame;
  6458. +
  6459. + // check if there actually is something to corrupt
  6460. + if (!sshp_find_syn(data, &frame))
  6461. + return;
  6462. +
  6463. + if (likely(!ssh_ptl_should_corrupt_rx_syn()))
  6464. + return;
  6465. +
  6466. + trace_ssam_ei_rx_corrupt_syn("data_length", data->len);
  6467. +
  6468. + data->ptr[1] = 0xb3; // set second byte of SYN to "random" value
  6469. +}
  6470. +
  6471. +static inline void ssh_ptl_rx_inject_invalid_data(struct ssh_ptl *ptl,
  6472. + struct sshp_span *frame)
  6473. +{
  6474. + size_t payload_len, message_len;
  6475. + struct ssh_frame *sshf;
  6476. +
  6477. + // ignore incomplete messages, will get handled once it's complete
  6478. + if (frame->len < SSH_MESSAGE_LENGTH(0))
  6479. + return;
  6480. +
  6481. + // ignore incomplete messages, part 2
  6482. + payload_len = get_unaligned_le16(&frame->ptr[SSH_MSGOFFSET_FRAME(len)]);
  6483. + message_len = SSH_MESSAGE_LENGTH(payload_len);
  6484. + if (frame->len < message_len)
  6485. + return;
  6486. +
  6487. + if (likely(!ssh_ptl_should_corrupt_rx_data()))
  6488. + return;
  6489. +
  6490. + sshf = (struct ssh_frame *)&frame->ptr[SSH_MSGOFFSET_FRAME(type)];
  6491. + trace_ssam_ei_rx_corrupt_data(sshf);
  6492. +
  6493. + /*
  6494. + * Flip bits in first byte of payload checksum. This is basically
  6495. + * equivalent to a payload/frame data error without us having to worry
  6496. + * about (the, arguably pretty small, probability of) accidental
  6497. + * checksum collisions.
  6498. + */
  6499. + frame->ptr[frame->len - 2] = ~frame->ptr[frame->len - 2];
  6500. +}
  6501. +
  6502. +#else /* CONFIG_SURFACE_SAM_SSH_ERROR_INJECTION */
  6503. +
  6504. +static inline bool ssh_ptl_should_drop_packet(struct ssh_packet *packet)
  6505. +{
  6506. + return false;
  6507. +}
  6508. +
  6509. +static inline int ssh_ptl_write_buf(struct ssh_ptl *ptl,
  6510. + struct ssh_packet *packet,
  6511. + const unsigned char *buf,
  6512. + size_t count)
  6513. +{
  6514. + return serdev_device_write_buf(ptl->serdev, buf, count);
  6515. +}
  6516. +
  6517. +static inline void ssh_ptl_tx_inject_invalid_data(struct ssh_packet *packet)
  6518. +{
  6519. +}
  6520. +
  6521. +static inline void ssh_ptl_rx_inject_invalid_syn(struct ssh_ptl *ptl,
  6522. + struct sshp_span *data)
  6523. +{
  6524. +}
  6525. +
  6526. +static inline void ssh_ptl_rx_inject_invalid_data(struct ssh_ptl *ptl,
  6527. + struct sshp_span *frame)
  6528. +{
  6529. +}
  6530. +
  6531. +#endif /* CONFIG_SURFACE_SAM_SSH_ERROR_INJECTION */
  6532. +
  6533. +
  6534. +static void __ssh_ptl_packet_release(struct kref *kref)
  6535. +{
  6536. + struct ssh_packet *p = to_ssh_packet(kref, refcnt);
  6537. +
  6538. + trace_ssam_packet_release(p);
  6539. +
  6540. + ptl_dbg_cond(p->ptl, "ptl: releasing packet %p\n", p);
  6541. + p->ops->release(p);
  6542. +}
  6543. +
  6544. +static inline void ssh_packet_get(struct ssh_packet *packet)
  6545. +{
  6546. + kref_get(&packet->refcnt);
  6547. +}
  6548. +
  6549. +static inline void ssh_packet_put(struct ssh_packet *packet)
  6550. +{
  6551. + kref_put(&packet->refcnt, __ssh_ptl_packet_release);
  6552. +}
  6553. +
  6554. +
  6555. +static inline u8 ssh_packet_get_seq(struct ssh_packet *packet)
  6556. +{
  6557. + return packet->data[SSH_MSGOFFSET_FRAME(seq)];
  6558. +}
  6559. +
  6560. +
  6561. +struct ssh_packet_args {
  6562. + u8 type;
  6563. + u8 priority;
  6564. + const struct ssh_packet_ops *ops;
  6565. +};
  6566. +
  6567. +static void ssh_packet_init(struct ssh_packet *packet,
  6568. + const struct ssh_packet_args *args)
  6569. +{
  6570. + kref_init(&packet->refcnt);
  6571. +
  6572. + packet->ptl = NULL;
  6573. + INIT_LIST_HEAD(&packet->queue_node);
  6574. + INIT_LIST_HEAD(&packet->pending_node);
  6575. +
  6576. + packet->type = args->type;
  6577. + packet->priority = args->priority;
  6578. + packet->state = 0;
  6579. + packet->timestamp = KTIME_MAX;
  6580. +
  6581. + packet->data_length = 0;
  6582. + packet->data = NULL;
  6583. +
  6584. + packet->ops = args->ops;
  6585. +}
  6586. +
  6587. +
  6588. +static struct ssh_packet *ptl_alloc_ctrl_packet(
  6589. + struct ssh_ptl *ptl, const struct ssh_packet_args *args,
  6590. + gfp_t flags)
  6591. +{
  6592. + struct ssh_packet *packet;
  6593. +
  6594. + // TODO: chache packets
  6595. +
  6596. + packet = kzalloc(sizeof(struct ssh_packet) + SSH_MSG_LEN_CTRL, flags);
  6597. + if (!packet)
  6598. + return NULL;
  6599. +
  6600. + ssh_packet_init(packet, args);
  6601. + packet->data_length = SSH_MSG_LEN_CTRL;
  6602. + packet->data = ((u8 *) packet) + sizeof(struct ssh_packet);
  6603. +
  6604. + return packet;
  6605. +}
  6606. +
  6607. +static void ptl_free_ctrl_packet(struct ssh_packet *p)
  6608. +{
  6609. + // TODO: chache packets
  6610. +
  6611. + kfree(p);
  6612. +}
  6613. +
  6614. +static const struct ssh_packet_ops ssh_ptl_ctrl_packet_ops = {
  6615. + .complete = NULL,
  6616. + .release = ptl_free_ctrl_packet,
  6617. +};
  6618. +
  6619. +
  6620. +static void ssh_ptl_timeout_reaper_mod(struct ssh_ptl *ptl, ktime_t now,
  6621. + ktime_t expires)
  6622. +{
  6623. + unsigned long delta = msecs_to_jiffies(ktime_ms_delta(expires, now));
  6624. + ktime_t aexp = ktime_add(expires, SSH_PTL_PACKET_TIMEOUT_RESOLUTION);
  6625. + ktime_t old;
  6626. +
  6627. + // re-adjust / schedule reaper if it is above resolution delta
  6628. + old = READ_ONCE(ptl->rtx_timeout.expires);
  6629. + while (ktime_before(aexp, old))
  6630. + old = cmpxchg64(&ptl->rtx_timeout.expires, old, expires);
  6631. +
  6632. + // if we updated the reaper expiration, modify work timeout
  6633. + if (old == expires)
  6634. + mod_delayed_work(system_wq, &ptl->rtx_timeout.reaper, delta);
  6635. +}
  6636. +
  6637. +static void ssh_ptl_timeout_start(struct ssh_packet *packet)
  6638. +{
  6639. + struct ssh_ptl *ptl = packet->ptl;
  6640. + ktime_t timestamp = ktime_get_coarse_boottime();
  6641. + ktime_t timeout = ptl->rtx_timeout.timeout;
  6642. +
  6643. + if (test_bit(SSH_PACKET_SF_LOCKED_BIT, &packet->state))
  6644. + return;
  6645. +
  6646. + WRITE_ONCE(packet->timestamp, timestamp);
  6647. + smp_mb__after_atomic();
  6648. +
  6649. + ssh_ptl_timeout_reaper_mod(packet->ptl, timestamp, timestamp + timeout);
  6650. +}
  6651. +
  6652. +
  6653. +static struct list_head *__ssh_ptl_queue_find_entrypoint(struct ssh_packet *p)
  6654. +{
  6655. + struct list_head *head;
  6656. + u8 priority = READ_ONCE(p->priority);
  6657. +
  6658. + /*
  6659. + * We generally assume that there are less control (ACK/NAK) packets and
  6660. + * re-submitted data packets as there are normal data packets (at least
  6661. + * in situations in which many packets are queued; if there aren't many
  6662. + * packets queued the decision on how to iterate should be basically
  6663. + * irrellevant; the number of control/data packets is more or less
  6664. + * limited via the maximum number of pending packets). Thus, when
  6665. + * inserting a control or re-submitted data packet, (determined by their
  6666. + * priority), we search from front to back. Normal data packets are,
  6667. + * usually queued directly at the tail of the queue, so for those search
  6668. + * from back to front.
  6669. + */
  6670. +
  6671. + if (priority > SSH_PACKET_PRIORITY_DATA) {
  6672. + list_for_each(head, &p->ptl->queue.head) {
  6673. + p = list_entry(head, struct ssh_packet, queue_node);
  6674. +
  6675. + if (READ_ONCE(p->priority) < priority)
  6676. + break;
  6677. + }
  6678. + } else {
  6679. + list_for_each_prev(head, &p->ptl->queue.head) {
  6680. + p = list_entry(head, struct ssh_packet, queue_node);
  6681. +
  6682. + if (READ_ONCE(p->priority) >= priority) {
  6683. + head = head->next;
  6684. + break;
  6685. + }
  6686. + }
  6687. + }
  6688. +
  6689. +
  6690. + return head;
  6691. +}
  6692. +
  6693. +static int ssh_ptl_queue_push(struct ssh_packet *packet)
  6694. +{
  6695. + struct ssh_ptl *ptl = packet->ptl;
  6696. + struct list_head *head;
  6697. +
  6698. + spin_lock(&ptl->queue.lock);
  6699. +
  6700. + if (test_bit(SSH_PTL_SF_SHUTDOWN_BIT, &ptl->state)) {
  6701. + spin_unlock(&ptl->queue.lock);
  6702. + return -ESHUTDOWN;
  6703. + }
  6704. +
  6705. + // avoid further transitions when cancelling/completing
  6706. + if (test_bit(SSH_PACKET_SF_LOCKED_BIT, &packet->state)) {
  6707. + spin_unlock(&ptl->queue.lock);
  6708. + return -EINVAL;
  6709. + }
  6710. +
  6711. + // if this packet has already been queued, do not add it
  6712. + if (test_and_set_bit(SSH_PACKET_SF_QUEUED_BIT, &packet->state)) {
  6713. + spin_unlock(&ptl->queue.lock);
  6714. + return -EALREADY;
  6715. + }
  6716. +
  6717. + head = __ssh_ptl_queue_find_entrypoint(packet);
  6718. +
  6719. + ssh_packet_get(packet);
  6720. + list_add_tail(&packet->queue_node, &ptl->queue.head);
  6721. +
  6722. + spin_unlock(&ptl->queue.lock);
  6723. + return 0;
  6724. +}
  6725. +
  6726. +static void ssh_ptl_queue_remove(struct ssh_packet *packet)
  6727. +{
  6728. + struct ssh_ptl *ptl = packet->ptl;
  6729. + bool remove;
  6730. +
  6731. + spin_lock(&ptl->queue.lock);
  6732. +
  6733. + remove = test_and_clear_bit(SSH_PACKET_SF_QUEUED_BIT, &packet->state);
  6734. + if (remove)
  6735. + list_del(&packet->queue_node);
  6736. +
  6737. + spin_unlock(&ptl->queue.lock);
  6738. +
  6739. + if (remove)
  6740. + ssh_packet_put(packet);
  6741. +}
  6742. +
  6743. +
  6744. +static void ssh_ptl_pending_push(struct ssh_packet *packet)
  6745. +{
  6746. + struct ssh_ptl *ptl = packet->ptl;
  6747. +
  6748. + spin_lock(&ptl->pending.lock);
  6749. +
  6750. + // if we are cancelling/completing this packet, do not add it
  6751. + if (test_bit(SSH_PACKET_SF_LOCKED_BIT, &packet->state)) {
  6752. + spin_unlock(&ptl->pending.lock);
  6753. + return;
  6754. + }
  6755. +
  6756. + // in case it is already pending (e.g. re-submission), do not add it
  6757. + if (test_and_set_bit(SSH_PACKET_SF_PENDING_BIT, &packet->state)) {
  6758. + spin_unlock(&ptl->pending.lock);
  6759. + return;
  6760. + }
  6761. +
  6762. + atomic_inc(&ptl->pending.count);
  6763. + ssh_packet_get(packet);
  6764. + list_add_tail(&packet->pending_node, &ptl->pending.head);
  6765. +
  6766. + spin_unlock(&ptl->pending.lock);
  6767. +}
  6768. +
  6769. +static void ssh_ptl_pending_remove(struct ssh_packet *packet)
  6770. +{
  6771. + struct ssh_ptl *ptl = packet->ptl;
  6772. + bool remove;
  6773. +
  6774. + spin_lock(&ptl->pending.lock);
  6775. +
  6776. + remove = test_and_clear_bit(SSH_PACKET_SF_PENDING_BIT, &packet->state);
  6777. + if (remove) {
  6778. + list_del(&packet->pending_node);
  6779. + atomic_dec(&ptl->pending.count);
  6780. + }
  6781. +
  6782. + spin_unlock(&ptl->pending.lock);
  6783. +
  6784. + if (remove)
  6785. + ssh_packet_put(packet);
  6786. +}
  6787. +
  6788. +
  6789. +static void __ssh_ptl_complete(struct ssh_packet *p, int status)
  6790. +{
  6791. + struct ssh_ptl *ptl = READ_ONCE(p->ptl);
  6792. +
  6793. + trace_ssam_packet_complete(p, status);
  6794. +
  6795. + ptl_dbg_cond(ptl, "ptl: completing packet %p\n", p);
  6796. + if (p->ops->complete)
  6797. + p->ops->complete(p, status);
  6798. +}
  6799. +
  6800. +static void ssh_ptl_remove_and_complete(struct ssh_packet *p, int status)
  6801. +{
  6802. + /*
  6803. + * A call to this function should in general be preceeded by
  6804. + * set_bit(SSH_PACKET_SF_LOCKED_BIT, &p->flags) to avoid re-adding the
  6805. + * packet to the structures it's going to be removed from.
  6806. + *
  6807. + * The set_bit call does not need explicit memory barriers as the
  6808. + * implicit barrier of the test_and_set_bit call below ensure that the
  6809. + * flag is visible before we actually attempt to remove the packet.
  6810. + */
  6811. +
  6812. + if (test_and_set_bit(SSH_PACKET_SF_COMPLETED_BIT, &p->state))
  6813. + return;
  6814. +
  6815. + ssh_ptl_queue_remove(p);
  6816. + ssh_ptl_pending_remove(p);
  6817. +
  6818. + __ssh_ptl_complete(p, status);
  6819. +}
  6820. +
  6821. +
  6822. +static bool ssh_ptl_tx_can_process(struct ssh_packet *packet)
  6823. +{
  6824. + struct ssh_ptl *ptl = packet->ptl;
  6825. +
  6826. + if (packet->type & SSH_PACKET_TY_FLUSH)
  6827. + return !atomic_read(&ptl->pending.count);
  6828. +
  6829. + // we can alwas process non-blocking packets
  6830. + if (!(packet->type & SSH_PACKET_TY_BLOCKING))
  6831. + return true;
  6832. +
  6833. + // if we are already waiting for this packet, send it again
  6834. + if (test_bit(SSH_PACKET_SF_PENDING_BIT, &packet->state))
  6835. + return true;
  6836. +
  6837. + // otherwise: check if we have the capacity to send
  6838. + return atomic_read(&ptl->pending.count) < SSH_PTL_MAX_PENDING;
  6839. +}
  6840. +
  6841. +static struct ssh_packet *ssh_ptl_tx_pop(struct ssh_ptl *ptl)
  6842. +{
  6843. + struct ssh_packet *packet = ERR_PTR(-ENOENT);
  6844. + struct ssh_packet *p, *n;
  6845. +
  6846. + spin_lock(&ptl->queue.lock);
  6847. + list_for_each_entry_safe(p, n, &ptl->queue.head, queue_node) {
  6848. + /*
  6849. + * If we are cancelling or completing this packet, ignore it.
  6850. + * It's going to be removed from this queue shortly.
  6851. + */
  6852. + if (test_bit(SSH_PACKET_SF_LOCKED_BIT, &p->state)) {
  6853. + spin_unlock(&ptl->queue.lock);
  6854. + continue;
  6855. + }
  6856. +
  6857. + /*
  6858. + * Packets should be ordered non-blocking/to-be-resent first.
  6859. + * If we cannot process this packet, assume that we can't
  6860. + * process any following packet either and abort.
  6861. + */
  6862. + if (!ssh_ptl_tx_can_process(p)) {
  6863. + spin_unlock(&ptl->queue.lock);
  6864. + packet = ERR_PTR(-EBUSY);
  6865. + break;
  6866. + }
  6867. +
  6868. + /*
  6869. + * We are allowed to change the state now. Remove it from the
  6870. + * queue and mark it as being transmitted. Note that we cannot
  6871. + * add it to the set of pending packets yet, as queue locks must
  6872. + * always be acquired before packet locks (otherwise we might
  6873. + * run into a deadlock).
  6874. + */
  6875. +
  6876. + list_del(&p->queue_node);
  6877. +
  6878. + /*
  6879. + * Ensure that the "queued" bit gets cleared after setting the
  6880. + * "transmitting" bit to guaranteee non-zero flags.
  6881. + */
  6882. + set_bit(SSH_PACKET_SF_TRANSMITTING_BIT, &p->state);
  6883. + smp_mb__before_atomic();
  6884. + clear_bit(SSH_PACKET_SF_QUEUED_BIT, &p->state);
  6885. +
  6886. + packet = p;
  6887. + break;
  6888. + }
  6889. + spin_unlock(&ptl->queue.lock);
  6890. +
  6891. + return packet;
  6892. +}
  6893. +
  6894. +static struct ssh_packet *ssh_ptl_tx_next(struct ssh_ptl *ptl)
  6895. +{
  6896. + struct ssh_packet *p;
  6897. +
  6898. + p = ssh_ptl_tx_pop(ptl);
  6899. + if (IS_ERR(p))
  6900. + return p;
  6901. +
  6902. + if (p->type & SSH_PACKET_TY_SEQUENCED) {
  6903. + ptl_dbg(ptl, "ptl: transmitting sequenced packet %p\n", p);
  6904. + ssh_ptl_pending_push(p);
  6905. + ssh_ptl_timeout_start(p);
  6906. + } else {
  6907. + ptl_dbg(ptl, "ptl: transmitting non-sequenced packet %p\n", p);
  6908. + }
  6909. +
  6910. + /*
  6911. + * Update number of tries. This directly influences the priority in case
  6912. + * the packet is re-submitted (e.g. via timeout/NAK). Note that this is
  6913. + * the only place where we update the priority in-flight. As this runs
  6914. + * only on the tx-thread, this read-modify-write procedure is safe.
  6915. + */
  6916. + WRITE_ONCE(p->priority, READ_ONCE(p->priority) + 1);
  6917. +
  6918. + return p;
  6919. +}
  6920. +
  6921. +static void ssh_ptl_tx_compl_success(struct ssh_packet *packet)
  6922. +{
  6923. + struct ssh_ptl *ptl = packet->ptl;
  6924. +
  6925. + ptl_dbg(ptl, "ptl: successfully transmitted packet %p\n", packet);
  6926. +
  6927. + /*
  6928. + * Transition to state to "transmitted". Ensure that the flags never get
  6929. + * zero with barrier.
  6930. + */
  6931. + set_bit(SSH_PACKET_SF_TRANSMITTED_BIT, &packet->state);
  6932. + smp_mb__before_atomic();
  6933. + clear_bit(SSH_PACKET_SF_TRANSMITTING_BIT, &packet->state);
  6934. +
  6935. + // if the packet is unsequenced, we're done: lock and complete
  6936. + if (!(packet->type & SSH_PACKET_TY_SEQUENCED)) {
  6937. + set_bit(SSH_PACKET_SF_LOCKED_BIT, &packet->state);
  6938. + ssh_ptl_remove_and_complete(packet, 0);
  6939. + }
  6940. +
  6941. + /*
  6942. + * Notify that a packet transmission has finished. In general we're only
  6943. + * waiting for one packet (if any), so wake_up_all should be fine.
  6944. + */
  6945. + wake_up_all(&ptl->tx.packet_wq);
  6946. +}
  6947. +
  6948. +static void ssh_ptl_tx_compl_error(struct ssh_packet *packet, int status)
  6949. +{
  6950. + /*
  6951. + * Transmission failure: Lock the packet and try to complete it. Ensure
  6952. + * that the flags never get zero with barrier.
  6953. + */
  6954. + set_bit(SSH_PACKET_SF_LOCKED_BIT, &packet->state);
  6955. + smp_mb__before_atomic();
  6956. + clear_bit(SSH_PACKET_SF_TRANSMITTING_BIT, &packet->state);
  6957. +
  6958. + ptl_err(packet->ptl, "ptl: transmission error: %d\n", status);
  6959. + ptl_dbg(packet->ptl, "ptl: failed to transmit packet: %p\n", packet);
  6960. +
  6961. + ssh_ptl_remove_and_complete(packet, status);
  6962. +
  6963. + /*
  6964. + * Notify that a packet transmission has finished. In general we're only
  6965. + * waiting for one packet (if any), so wake_up_all should be fine.
  6966. + */
  6967. + wake_up_all(&packet->ptl->tx.packet_wq);
  6968. +}
  6969. +
  6970. +static void ssh_ptl_tx_threadfn_wait(struct ssh_ptl *ptl)
  6971. +{
  6972. + wait_event_interruptible(ptl->tx.thread_wq,
  6973. + READ_ONCE(ptl->tx.thread_signal) || kthread_should_stop());
  6974. + WRITE_ONCE(ptl->tx.thread_signal, false);
  6975. +}
  6976. +
  6977. +static int ssh_ptl_tx_threadfn(void *data)
  6978. +{
  6979. + struct ssh_ptl *ptl = data;
  6980. +
  6981. + while (!kthread_should_stop()) {
  6982. + unsigned char *buf;
  6983. + bool drop = false;
  6984. + size_t len = 0;
  6985. + int status = 0;
  6986. +
  6987. + // if we don't have a packet, get the next and add it to pending
  6988. + if (IS_ERR_OR_NULL(ptl->tx.packet)) {
  6989. + ptl->tx.packet = ssh_ptl_tx_next(ptl);
  6990. + ptl->tx.offset = 0;
  6991. +
  6992. + // if no packet is available, we are done
  6993. + if (IS_ERR(ptl->tx.packet)) {
  6994. + ssh_ptl_tx_threadfn_wait(ptl);
  6995. + continue;
  6996. + }
  6997. + }
  6998. +
  6999. + // error injection: drop packet to simulate transmission problem
  7000. + if (ptl->tx.offset == 0)
  7001. + drop = ssh_ptl_should_drop_packet(ptl->tx.packet);
  7002. +
  7003. + // error injection: simulate invalid packet data
  7004. + if (ptl->tx.offset == 0 && !drop)
  7005. + ssh_ptl_tx_inject_invalid_data(ptl->tx.packet);
  7006. +
  7007. + // flush-packets don't have any data
  7008. + if (likely(ptl->tx.packet->data && !drop)) {
  7009. + buf = ptl->tx.packet->data + ptl->tx.offset;
  7010. + len = ptl->tx.packet->data_length - ptl->tx.offset;
  7011. +
  7012. + ptl_dbg(ptl, "tx: sending data (length: %zu)\n", len);
  7013. + print_hex_dump_debug("tx: ", DUMP_PREFIX_OFFSET, 16, 1,
  7014. + buf, len, false);
  7015. +
  7016. + status = ssh_ptl_write_buf(ptl, ptl->tx.packet, buf, len);
  7017. + }
  7018. +
  7019. + if (status < 0) {
  7020. + // complete packet with error
  7021. + ssh_ptl_tx_compl_error(ptl->tx.packet, status);
  7022. + ssh_packet_put(ptl->tx.packet);
  7023. + ptl->tx.packet = NULL;
  7024. +
  7025. + } else if (status == len) {
  7026. + // complete packet and/or mark as transmitted
  7027. + ssh_ptl_tx_compl_success(ptl->tx.packet);
  7028. + ssh_packet_put(ptl->tx.packet);
  7029. + ptl->tx.packet = NULL;
  7030. +
  7031. + } else { // need more buffer space
  7032. + ptl->tx.offset += status;
  7033. + ssh_ptl_tx_threadfn_wait(ptl);
  7034. + }
  7035. + }
  7036. +
  7037. + // cancel active packet before we actually stop
  7038. + if (!IS_ERR_OR_NULL(ptl->tx.packet)) {
  7039. + ssh_ptl_tx_compl_error(ptl->tx.packet, -ESHUTDOWN);
  7040. + ssh_packet_put(ptl->tx.packet);
  7041. + ptl->tx.packet = NULL;
  7042. + }
  7043. +
  7044. + return 0;
  7045. +}
  7046. +
  7047. +static inline void ssh_ptl_tx_wakeup(struct ssh_ptl *ptl, bool force)
  7048. +{
  7049. + if (test_bit(SSH_PTL_SF_SHUTDOWN_BIT, &ptl->state))
  7050. + return;
  7051. +
  7052. + if (force || atomic_read(&ptl->pending.count) < SSH_PTL_MAX_PENDING) {
  7053. + WRITE_ONCE(ptl->tx.thread_signal, true);
  7054. + smp_mb__after_atomic();
  7055. + wake_up(&ptl->tx.thread_wq);
  7056. + }
  7057. +}
  7058. +
  7059. +static int ssh_ptl_tx_start(struct ssh_ptl *ptl)
  7060. +{
  7061. + ptl->tx.thread = kthread_run(ssh_ptl_tx_threadfn, ptl, "surface-sh-tx");
  7062. + if (IS_ERR(ptl->tx.thread))
  7063. + return PTR_ERR(ptl->tx.thread);
  7064. +
  7065. + return 0;
  7066. +}
  7067. +
  7068. +static int ssh_ptl_tx_stop(struct ssh_ptl *ptl)
  7069. +{
  7070. + int status = 0;
  7071. +
  7072. + if (ptl->tx.thread) {
  7073. + status = kthread_stop(ptl->tx.thread);
  7074. + ptl->tx.thread = NULL;
  7075. + }
  7076. +
  7077. + return status;
  7078. +}
  7079. +
  7080. +
  7081. +static struct ssh_packet *ssh_ptl_ack_pop(struct ssh_ptl *ptl, u8 seq_id)
  7082. +{
  7083. + struct ssh_packet *packet = ERR_PTR(-ENOENT);
  7084. + struct ssh_packet *p, *n;
  7085. +
  7086. + spin_lock(&ptl->pending.lock);
  7087. + list_for_each_entry_safe(p, n, &ptl->pending.head, pending_node) {
  7088. + /*
  7089. + * We generally expect packets to be in order, so first packet
  7090. + * to be added to pending is first to be sent, is first to be
  7091. + * ACKed.
  7092. + */
  7093. + if (unlikely(ssh_packet_get_seq(p) != seq_id))
  7094. + continue;
  7095. +
  7096. + /*
  7097. + * In case we receive an ACK while handling a transmission error
  7098. + * completion. The packet will be removed shortly.
  7099. + */
  7100. + if (unlikely(test_bit(SSH_PACKET_SF_LOCKED_BIT, &p->state))) {
  7101. + packet = ERR_PTR(-EPERM);
  7102. + break;
  7103. + }
  7104. +
  7105. + /*
  7106. + * Mark packet as ACKed and remove it from pending. Ensure that
  7107. + * the flags never get zero with barrier.
  7108. + */
  7109. + set_bit(SSH_PACKET_SF_ACKED_BIT, &p->state);
  7110. + smp_mb__before_atomic();
  7111. + clear_bit(SSH_PACKET_SF_PENDING_BIT, &p->state);
  7112. +
  7113. + atomic_dec(&ptl->pending.count);
  7114. + list_del(&p->pending_node);
  7115. + packet = p;
  7116. +
  7117. + break;
  7118. + }
  7119. + spin_unlock(&ptl->pending.lock);
  7120. +
  7121. + return packet;
  7122. +}
  7123. +
  7124. +static void ssh_ptl_wait_until_transmitted(struct ssh_packet *packet)
  7125. +{
  7126. + wait_event(packet->ptl->tx.packet_wq,
  7127. + test_bit(SSH_PACKET_SF_TRANSMITTED_BIT, &packet->state)
  7128. + || test_bit(SSH_PACKET_SF_LOCKED_BIT, &packet->state));
  7129. +}
  7130. +
  7131. +static void ssh_ptl_acknowledge(struct ssh_ptl *ptl, u8 seq)
  7132. +{
  7133. + struct ssh_packet *p;
  7134. + int status = 0;
  7135. +
  7136. + p = ssh_ptl_ack_pop(ptl, seq);
  7137. + if (IS_ERR(p)) {
  7138. + if (PTR_ERR(p) == -ENOENT) {
  7139. + /*
  7140. + * The packet has not been found in the set of pending
  7141. + * packets.
  7142. + */
  7143. + ptl_warn(ptl, "ptl: received ACK for non-pending"
  7144. + " packet\n");
  7145. + } else {
  7146. + /*
  7147. + * The packet is pending, but we are not allowed to take
  7148. + * it because it has been locked.
  7149. + */
  7150. + }
  7151. + return;
  7152. + }
  7153. +
  7154. + ptl_dbg(ptl, "ptl: received ACK for packet %p\n", p);
  7155. +
  7156. + /*
  7157. + * It is possible that the packet has been transmitted, but the state
  7158. + * has not been updated from "transmitting" to "transmitted" yet.
  7159. + * In that case, we need to wait for this transition to occur in order
  7160. + * to determine between success or failure.
  7161. + */
  7162. + if (test_bit(SSH_PACKET_SF_TRANSMITTING_BIT, &p->state))
  7163. + ssh_ptl_wait_until_transmitted(p);
  7164. +
  7165. + /*
  7166. + * The packet will already be locked in case of a transmission error or
  7167. + * cancellation. Let the transmitter or cancellation issuer complete the
  7168. + * packet.
  7169. + */
  7170. + if (unlikely(test_and_set_bit(SSH_PACKET_SF_LOCKED_BIT, &p->state))) {
  7171. + ssh_packet_put(p);
  7172. + return;
  7173. + }
  7174. +
  7175. + if (unlikely(!test_bit(SSH_PACKET_SF_TRANSMITTED_BIT, &p->state))) {
  7176. + ptl_err(ptl, "ptl: received ACK before packet had been fully"
  7177. + " transmitted\n");
  7178. + status = -EREMOTEIO;
  7179. + }
  7180. +
  7181. + ssh_ptl_remove_and_complete(p, status);
  7182. + ssh_packet_put(p);
  7183. +
  7184. + ssh_ptl_tx_wakeup(ptl, false);
  7185. +}
  7186. +
  7187. +
  7188. +static int ssh_ptl_submit(struct ssh_ptl *ptl, struct ssh_packet *packet)
  7189. +{
  7190. + int status;
  7191. +
  7192. + trace_ssam_packet_submit(packet);
  7193. +
  7194. + // validate packet fields
  7195. + if (packet->type & SSH_PACKET_TY_FLUSH) {
  7196. + if (packet->data || (packet->type & SSH_PACKET_TY_SEQUENCED))
  7197. + return -EINVAL;
  7198. + } else if (!packet->data) {
  7199. + return -EINVAL;
  7200. + }
  7201. +
  7202. + /*
  7203. + * This function is currently not intended for re-submission. The ptl
  7204. + * reference only gets set on the first submission. After the first
  7205. + * submission, it has to be read-only.
  7206. + *
  7207. + * Use cmpxchg to ensure safety with regards to ssh_ptl_cancel and
  7208. + * re-entry, where we can't guarantee that the packet has been submitted
  7209. + * yet.
  7210. + *
  7211. + * The implicit barrier of cmpxchg is paired with barrier in
  7212. + * ssh_ptl_cancel to guarantee cancelation in case the packet has never
  7213. + * been submitted or is currently being submitted.
  7214. + */
  7215. + if (cmpxchg(&packet->ptl, NULL, ptl) != NULL)
  7216. + return -EALREADY;
  7217. +
  7218. + status = ssh_ptl_queue_push(packet);
  7219. + if (status)
  7220. + return status;
  7221. +
  7222. + ssh_ptl_tx_wakeup(ptl, !(packet->type & SSH_PACKET_TY_BLOCKING));
  7223. + return 0;
  7224. +}
  7225. +
  7226. +static void __ssh_ptl_resubmit(struct ssh_packet *packet)
  7227. +{
  7228. + struct list_head *head;
  7229. +
  7230. + trace_ssam_packet_resubmit(packet);
  7231. +
  7232. + spin_lock(&packet->ptl->queue.lock);
  7233. +
  7234. + // if this packet has already been queued, do not add it
  7235. + if (test_and_set_bit(SSH_PACKET_SF_QUEUED_BIT, &packet->state)) {
  7236. + spin_unlock(&packet->ptl->queue.lock);
  7237. + return;
  7238. + }
  7239. +
  7240. + // find first node with lower priority
  7241. + head = __ssh_ptl_queue_find_entrypoint(packet);
  7242. +
  7243. + WRITE_ONCE(packet->timestamp, KTIME_MAX);
  7244. + smp_mb__after_atomic();
  7245. +
  7246. + // add packet
  7247. + ssh_packet_get(packet);
  7248. + list_add_tail(&packet->queue_node, head);
  7249. +
  7250. + spin_unlock(&packet->ptl->queue.lock);
  7251. +}
  7252. +
  7253. +static void ssh_ptl_resubmit_pending(struct ssh_ptl *ptl)
  7254. +{
  7255. + struct ssh_packet *p;
  7256. + bool resub = false;
  7257. + u8 try;
  7258. +
  7259. + /*
  7260. + * Note: We deliberately do not remove/attempt to cancel and complete
  7261. + * packets that are out of tires in this function. The packet will be
  7262. + * eventually canceled and completed by the timeout. Removing the packet
  7263. + * here could lead to overly eager cancelation if the packet has not
  7264. + * been re-transmitted yet but the tries-counter already updated (i.e
  7265. + * ssh_ptl_tx_next removed the packet from the queue and updated the
  7266. + * counter, but re-transmission for the last try has not actually
  7267. + * started yet).
  7268. + */
  7269. +
  7270. + spin_lock(&ptl->pending.lock);
  7271. +
  7272. + // re-queue all pending packets
  7273. + list_for_each_entry(p, &ptl->pending.head, pending_node) {
  7274. + // avoid further transitions if locked
  7275. + if (test_bit(SSH_PACKET_SF_LOCKED_BIT, &p->state))
  7276. + continue;
  7277. +
  7278. + // do not re-schedule if packet is out of tries
  7279. + try = ssh_packet_priority_get_try(READ_ONCE(p->priority));
  7280. + if (try >= SSH_PTL_MAX_PACKET_TRIES)
  7281. + continue;
  7282. +
  7283. + resub = true;
  7284. + __ssh_ptl_resubmit(p);
  7285. + }
  7286. +
  7287. + spin_unlock(&ptl->pending.lock);
  7288. +
  7289. + ssh_ptl_tx_wakeup(ptl, resub);
  7290. +}
  7291. +
  7292. +static void ssh_ptl_cancel(struct ssh_packet *p)
  7293. +{
  7294. + if (test_and_set_bit(SSH_PACKET_SF_CANCELED_BIT, &p->state))
  7295. + return;
  7296. +
  7297. + trace_ssam_packet_cancel(p);
  7298. +
  7299. + /*
  7300. + * Lock packet and commit with memory barrier. If this packet has
  7301. + * already been locked, it's going to be removed and completed by
  7302. + * another party, which should have precedence.
  7303. + */
  7304. + if (test_and_set_bit(SSH_PACKET_SF_LOCKED_BIT, &p->state))
  7305. + return;
  7306. +
  7307. + /*
  7308. + * By marking the packet as locked and employing the implicit memory
  7309. + * barrier of test_and_set_bit, we have guaranteed that, at this point,
  7310. + * the packet cannot be added to the queue any more.
  7311. + *
  7312. + * In case the packet has never been submitted, packet->ptl is NULL. If
  7313. + * the packet is currently being submitted, packet->ptl may be NULL or
  7314. + * non-NULL. Due marking the packet as locked above and committing with
  7315. + * the memory barrier, we have guaranteed that, if packet->ptl is NULL,
  7316. + * the packet will never be added to the queue. If packet->ptl is
  7317. + * non-NULL, we don't have any guarantees.
  7318. + */
  7319. +
  7320. + if (READ_ONCE(p->ptl)) {
  7321. + ssh_ptl_remove_and_complete(p, -ECANCELED);
  7322. + ssh_ptl_tx_wakeup(p->ptl, false);
  7323. + } else if (!test_and_set_bit(SSH_PACKET_SF_COMPLETED_BIT, &p->state)) {
  7324. + __ssh_ptl_complete(p, -ECANCELED);
  7325. + }
  7326. +}
  7327. +
  7328. +
  7329. +static ktime_t ssh_packet_get_expiration(struct ssh_packet *p, ktime_t timeout)
  7330. +{
  7331. + ktime_t timestamp = READ_ONCE(p->timestamp);
  7332. +
  7333. + if (timestamp != KTIME_MAX)
  7334. + return ktime_add(timestamp, timeout);
  7335. + else
  7336. + return KTIME_MAX;
  7337. +}
  7338. +
  7339. +static void ssh_ptl_timeout_reap(struct work_struct *work)
  7340. +{
  7341. + struct ssh_ptl *ptl = to_ssh_ptl(work, rtx_timeout.reaper.work);
  7342. + struct ssh_packet *p, *n;
  7343. + LIST_HEAD(claimed);
  7344. + ktime_t now = ktime_get_coarse_boottime();
  7345. + ktime_t timeout = ptl->rtx_timeout.timeout;
  7346. + ktime_t next = KTIME_MAX;
  7347. + bool resub = false;
  7348. +
  7349. + trace_ssam_ptl_timeout_reap("pending", atomic_read(&ptl->pending.count));
  7350. +
  7351. + /*
  7352. + * Mark reaper as "not pending". This is done before checking any
  7353. + * packets to avoid lost-update type problems.
  7354. + */
  7355. + WRITE_ONCE(ptl->rtx_timeout.expires, KTIME_MAX);
  7356. + smp_mb__after_atomic();
  7357. +
  7358. + spin_lock(&ptl->pending.lock);
  7359. +
  7360. + list_for_each_entry_safe(p, n, &ptl->pending.head, pending_node) {
  7361. + ktime_t expires = ssh_packet_get_expiration(p, timeout);
  7362. + u8 try;
  7363. +
  7364. + /*
  7365. + * Check if the timeout hasn't expired yet. Find out next
  7366. + * expiration date to be handled after this run.
  7367. + */
  7368. + if (ktime_after(expires, now)) {
  7369. + next = ktime_before(expires, next) ? expires : next;
  7370. + continue;
  7371. + }
  7372. +
  7373. + // avoid further transitions if locked
  7374. + if (test_bit(SSH_PACKET_SF_LOCKED_BIT, &p->state))
  7375. + continue;
  7376. +
  7377. + trace_ssam_packet_timeout(p);
  7378. +
  7379. + // check if we still have some tries left
  7380. + try = ssh_packet_priority_get_try(READ_ONCE(p->priority));
  7381. + if (likely(try < SSH_PTL_MAX_PACKET_TRIES)) {
  7382. + resub = true;
  7383. + __ssh_ptl_resubmit(p);
  7384. + continue;
  7385. + }
  7386. +
  7387. + // no more tries left: cancel the packet
  7388. +
  7389. + // if someone else has locked the packet already, don't use it
  7390. + if (test_and_set_bit(SSH_PACKET_SF_LOCKED_BIT, &p->state))
  7391. + continue;
  7392. +
  7393. + /*
  7394. + * We have now marked the packet as locked. Thus it cannot be
  7395. + * added to the pending list again after we've removed it here.
  7396. + * We can therefore re-use the pending_node of this packet
  7397. + * temporarily.
  7398. + */
  7399. +
  7400. + clear_bit(SSH_PACKET_SF_PENDING_BIT, &p->state);
  7401. +
  7402. + atomic_dec(&ptl->pending.count);
  7403. + list_del(&p->pending_node);
  7404. +
  7405. + list_add_tail(&p->pending_node, &claimed);
  7406. + }
  7407. +
  7408. + spin_unlock(&ptl->pending.lock);
  7409. +
  7410. + // cancel and complete the packet
  7411. + list_for_each_entry_safe(p, n, &claimed, pending_node) {
  7412. + if (!test_and_set_bit(SSH_PACKET_SF_COMPLETED_BIT, &p->state)) {
  7413. + ssh_ptl_queue_remove(p);
  7414. + __ssh_ptl_complete(p, -ETIMEDOUT);
  7415. + }
  7416. +
  7417. + // drop the reference we've obtained by removing it from pending
  7418. + list_del(&p->pending_node);
  7419. + ssh_packet_put(p);
  7420. + }
  7421. +
  7422. + // ensure that reaper doesn't run again immediately
  7423. + next = max(next, ktime_add(now, SSH_PTL_PACKET_TIMEOUT_RESOLUTION));
  7424. + if (next != KTIME_MAX)
  7425. + ssh_ptl_timeout_reaper_mod(ptl, now, next);
  7426. +
  7427. + // force-wakeup to properly handle re-transmits if we've re-submitted
  7428. + ssh_ptl_tx_wakeup(ptl, resub);
  7429. +}
  7430. +
  7431. +
  7432. +static bool ssh_ptl_rx_blacklist_check(struct ssh_ptl *ptl, u8 seq)
  7433. +{
  7434. + int i;
  7435. +
  7436. + // check if SEQ is blacklisted
  7437. + for (i = 0; i < ARRAY_SIZE(ptl->rx.blacklist.seqs); i++) {
  7438. + if (likely(ptl->rx.blacklist.seqs[i] != seq))
  7439. + continue;
  7440. +
  7441. + ptl_dbg(ptl, "ptl: ignoring repeated data packet\n");
  7442. + return true;
  7443. + }
  7444. +
  7445. + // update blacklist
  7446. + ptl->rx.blacklist.seqs[ptl->rx.blacklist.offset] = seq;
  7447. + ptl->rx.blacklist.offset = (ptl->rx.blacklist.offset + 1)
  7448. + % ARRAY_SIZE(ptl->rx.blacklist.seqs);
  7449. +
  7450. + return false;
  7451. +}
  7452. +
  7453. +static void ssh_ptl_rx_dataframe(struct ssh_ptl *ptl,
  7454. + const struct ssh_frame *frame,
  7455. + const struct sshp_span *payload)
  7456. +{
  7457. + if (ssh_ptl_rx_blacklist_check(ptl, frame->seq))
  7458. + return;
  7459. +
  7460. + ptl->ops.data_received(ptl, payload);
  7461. +}
  7462. +
  7463. +static void ssh_ptl_send_ack(struct ssh_ptl *ptl, u8 seq)
  7464. +{
  7465. + struct ssh_packet_args args;
  7466. + struct ssh_packet *packet;
  7467. + struct msgbuf msgb;
  7468. +
  7469. + args.type = 0;
  7470. + args.priority = SSH_PACKET_PRIORITY(ACK, 0);
  7471. + args.ops = &ssh_ptl_ctrl_packet_ops;
  7472. +
  7473. + packet = ptl_alloc_ctrl_packet(ptl, &args, GFP_KERNEL);
  7474. + if (!packet) {
  7475. + ptl_err(ptl, "ptl: failed to allocate ACK packet\n");
  7476. + return;
  7477. + }
  7478. +
  7479. + msgb_init(&msgb, packet->data, packet->data_length);
  7480. + msgb_push_ack(&msgb, seq);
  7481. + packet->data_length = msgb_bytes_used(&msgb);
  7482. +
  7483. + ssh_ptl_submit(ptl, packet);
  7484. + ssh_packet_put(packet);
  7485. +}
  7486. +
  7487. +static void ssh_ptl_send_nak(struct ssh_ptl *ptl)
  7488. +{
  7489. + struct ssh_packet_args args;
  7490. + struct ssh_packet *packet;
  7491. + struct msgbuf msgb;
  7492. +
  7493. + args.type = 0;
  7494. + args.priority = SSH_PACKET_PRIORITY(NAK, 0);
  7495. + args.ops = &ssh_ptl_ctrl_packet_ops;
  7496. +
  7497. + packet = ptl_alloc_ctrl_packet(ptl, &args, GFP_KERNEL);
  7498. + if (!packet) {
  7499. + ptl_err(ptl, "ptl: failed to allocate NAK packet\n");
  7500. + return;
  7501. + }
  7502. +
  7503. + msgb_init(&msgb, packet->data, packet->data_length);
  7504. + msgb_push_nak(&msgb);
  7505. + packet->data_length = msgb_bytes_used(&msgb);
  7506. +
  7507. + ssh_ptl_submit(ptl, packet);
  7508. + ssh_packet_put(packet);
  7509. +}
  7510. +
  7511. +static size_t ssh_ptl_rx_eval(struct ssh_ptl *ptl, struct sshp_span *source)
  7512. +{
  7513. + struct ssh_frame *frame;
  7514. + struct sshp_span payload;
  7515. + struct sshp_span aligned;
  7516. + bool syn_found;
  7517. + int status;
  7518. +
  7519. + // error injection: modify data to simulate corrupt SYN bytes
  7520. + ssh_ptl_rx_inject_invalid_syn(ptl, source);
  7521. +
  7522. + // find SYN
  7523. + syn_found = sshp_find_syn(source, &aligned);
  7524. +
  7525. + if (unlikely(aligned.ptr - source->ptr) > 0) {
  7526. + ptl_warn(ptl, "rx: parser: invalid start of frame, skipping\n");
  7527. +
  7528. + /*
  7529. + * Notes:
  7530. + * - This might send multiple NAKs in case the communication
  7531. + * starts with an invalid SYN and is broken down into multiple
  7532. + * pieces. This should generally be handled fine, we just
  7533. + * might receive duplicate data in this case, which is
  7534. + * detected when handling data frames.
  7535. + * - This path will also be executed on invalid CRCs: When an
  7536. + * invalid CRC is encountered, the code below will skip data
  7537. + * until direclty after the SYN. This causes the search for
  7538. + * the next SYN, which is generally not placed directly after
  7539. + * the last one.
  7540. + */
  7541. + ssh_ptl_send_nak(ptl);
  7542. + }
  7543. +
  7544. + if (unlikely(!syn_found))
  7545. + return aligned.ptr - source->ptr;
  7546. +
  7547. + // error injection: modify data to simulate corruption
  7548. + ssh_ptl_rx_inject_invalid_data(ptl, &aligned);
  7549. +
  7550. + // parse and validate frame
  7551. + status = sshp_parse_frame(&ptl->serdev->dev, &aligned, &frame, &payload,
  7552. + SSH_PTL_RX_BUF_LEN);
  7553. + if (status) // invalid frame: skip to next syn
  7554. + return aligned.ptr - source->ptr + sizeof(u16);
  7555. + if (!frame) // not enough data
  7556. + return aligned.ptr - source->ptr;
  7557. +
  7558. + trace_ssam_rx_frame_received(frame);
  7559. +
  7560. + switch (frame->type) {
  7561. + case SSH_FRAME_TYPE_ACK:
  7562. + ssh_ptl_acknowledge(ptl, frame->seq);
  7563. + break;
  7564. +
  7565. + case SSH_FRAME_TYPE_NAK:
  7566. + ssh_ptl_resubmit_pending(ptl);
  7567. + break;
  7568. +
  7569. + case SSH_FRAME_TYPE_DATA_SEQ:
  7570. + ssh_ptl_send_ack(ptl, frame->seq);
  7571. + /* fallthrough */
  7572. +
  7573. + case SSH_FRAME_TYPE_DATA_NSQ:
  7574. + ssh_ptl_rx_dataframe(ptl, frame, &payload);
  7575. + break;
  7576. +
  7577. + default:
  7578. + ptl_warn(ptl, "ptl: received frame with unknown type 0x%02x\n",
  7579. + frame->type);
  7580. + break;
  7581. + }
  7582. +
  7583. + return aligned.ptr - source->ptr + SSH_MESSAGE_LENGTH(frame->len);
  7584. +}
  7585. +
  7586. +static int ssh_ptl_rx_threadfn(void *data)
  7587. +{
  7588. + struct ssh_ptl *ptl = data;
  7589. +
  7590. + while (true) {
  7591. + struct sshp_span span;
  7592. + size_t offs = 0;
  7593. + size_t n;
  7594. +
  7595. + wait_event_interruptible(ptl->rx.wq,
  7596. + !kfifo_is_empty(&ptl->rx.fifo)
  7597. + || kthread_should_stop());
  7598. + if (kthread_should_stop())
  7599. + break;
  7600. +
  7601. + // copy from fifo to evaluation buffer
  7602. + n = sshp_buf_read_from_fifo(&ptl->rx.buf, &ptl->rx.fifo);
  7603. +
  7604. + ptl_dbg(ptl, "rx: received data (size: %zu)\n", n);
  7605. + print_hex_dump_debug("rx: ", DUMP_PREFIX_OFFSET, 16, 1,
  7606. + ptl->rx.buf.ptr + ptl->rx.buf.len - n,
  7607. + n, false);
  7608. +
  7609. + // parse until we need more bytes or buffer is empty
  7610. + while (offs < ptl->rx.buf.len) {
  7611. + sshp_buf_span_from(&ptl->rx.buf, offs, &span);
  7612. + n = ssh_ptl_rx_eval(ptl, &span);
  7613. + if (n == 0)
  7614. + break; // need more bytes
  7615. +
  7616. + offs += n;
  7617. + }
  7618. +
  7619. + // throw away the evaluated parts
  7620. + sshp_buf_drop(&ptl->rx.buf, offs);
  7621. + }
  7622. +
  7623. + return 0;
  7624. +}
  7625. +
  7626. +static inline void ssh_ptl_rx_wakeup(struct ssh_ptl *ptl)
  7627. +{
  7628. + wake_up(&ptl->rx.wq);
  7629. +}
  7630. +
  7631. +static int ssh_ptl_rx_start(struct ssh_ptl *ptl)
  7632. +{
  7633. + if (ptl->rx.thread)
  7634. + return 0;
  7635. +
  7636. + ptl->rx.thread = kthread_run(ssh_ptl_rx_threadfn, ptl, "surface-sh-rx");
  7637. + if (IS_ERR(ptl->rx.thread))
  7638. + return PTR_ERR(ptl->rx.thread);
  7639. +
  7640. + return 0;
  7641. +}
  7642. +
  7643. +static int ssh_ptl_rx_stop(struct ssh_ptl *ptl)
  7644. +{
  7645. + int status = 0;
  7646. +
  7647. + if (ptl->rx.thread) {
  7648. + status = kthread_stop(ptl->rx.thread);
  7649. + ptl->rx.thread = NULL;
  7650. + }
  7651. +
  7652. + return status;
  7653. +}
  7654. +
  7655. +static int ssh_ptl_rx_rcvbuf(struct ssh_ptl *ptl, const u8 *buf, size_t n)
  7656. +{
  7657. + int used;
  7658. +
  7659. + if (test_bit(SSH_PTL_SF_SHUTDOWN_BIT, &ptl->state))
  7660. + return used;
  7661. +
  7662. + used = kfifo_in(&ptl->rx.fifo, buf, n);
  7663. + if (used)
  7664. + ssh_ptl_rx_wakeup(ptl);
  7665. +
  7666. + return used;
  7667. +}
  7668. +
  7669. +
  7670. +struct ssh_flush_packet {
  7671. + struct ssh_packet base;
  7672. + struct completion completion;
  7673. + int status;
  7674. +};
  7675. +
  7676. +static void ssh_ptl_flush_complete(struct ssh_packet *p, int status)
  7677. +{
  7678. + struct ssh_flush_packet *packet;
  7679. +
  7680. + packet = container_of(p, struct ssh_flush_packet, base);
  7681. + packet->status = status;
  7682. +}
  7683. +
  7684. +static void ssh_ptl_flush_release(struct ssh_packet *p)
  7685. +{
  7686. + struct ssh_flush_packet *packet;
  7687. +
  7688. + packet = container_of(p, struct ssh_flush_packet, base);
  7689. + complete_all(&packet->completion);
  7690. +}
  7691. +
  7692. +static const struct ssh_packet_ops ssh_flush_packet_ops = {
  7693. + .complete = ssh_ptl_flush_complete,
  7694. + .release = ssh_ptl_flush_release,
  7695. +};
  7696. +
  7697. +/**
  7698. + * ssh_ptl_flush - flush the packet transmission layer
  7699. + * @ptl: packet transmission layer
  7700. + * @timeout: timeout for the flush operation in jiffies
  7701. + *
  7702. + * Queue a special flush-packet and wait for its completion. This packet will
  7703. + * be completed after all other currently queued and pending packets have been
  7704. + * completed. Flushing guarantees that all previously submitted data packets
  7705. + * have been fully completed before this call returns. Additionally, flushing
  7706. + * blocks execution of all later submitted data packets until the flush has been
  7707. + * completed.
  7708. + *
  7709. + * Control (i.e. ACK/NAK) packets that have been submitted after this call will
  7710. + * be placed before the flush packet in the queue, as long as the flush-packet
  7711. + * has not been chosen for processing yet.
  7712. + *
  7713. + * Flushing, even when no new data packets are submitted after this call, does
  7714. + * not guarantee that no more packets are scheduled. For example, incoming
  7715. + * messages can promt automated submission of ACK or NAK type packets. If this
  7716. + * happens while the flush-packet is being processed (i.e. after it has been
  7717. + * taken from the queue), such packets may still be queued after this function
  7718. + * returns.
  7719. + *
  7720. + * Return: Zero on success, -ETIMEDOUT if the flush timed out and has been
  7721. + * canceled as a result of the timeout, or -ESHUTDOWN if the packet transmission
  7722. + * layer has been shut down before this call. May also return -EINTR if the
  7723. + * packet transmission has been interrupted.
  7724. + */
  7725. +static int ssh_ptl_flush(struct ssh_ptl *ptl, unsigned long timeout)
  7726. +{
  7727. + struct ssh_flush_packet packet;
  7728. + struct ssh_packet_args args;
  7729. + int status;
  7730. +
  7731. + args.type = SSH_PACKET_TY_FLUSH | SSH_PACKET_TY_BLOCKING;
  7732. + args.priority = SSH_PACKET_PRIORITY(FLUSH, 0);
  7733. + args.ops = &ssh_flush_packet_ops;
  7734. +
  7735. + ssh_packet_init(&packet.base, &args);
  7736. + init_completion(&packet.completion);
  7737. +
  7738. + status = ssh_ptl_submit(ptl, &packet.base);
  7739. + if (status)
  7740. + return status;
  7741. +
  7742. + ssh_packet_put(&packet.base);
  7743. +
  7744. + if (wait_for_completion_timeout(&packet.completion, timeout))
  7745. + return 0;
  7746. +
  7747. + ssh_ptl_cancel(&packet.base);
  7748. + wait_for_completion(&packet.completion);
  7749. +
  7750. + WARN_ON(packet.status != 0 && packet.status != -ECANCELED
  7751. + && packet.status != -ESHUTDOWN && packet.status != -EINTR);
  7752. +
  7753. + return packet.status == -ECANCELED ? -ETIMEDOUT : status;
  7754. +}
  7755. +
  7756. +/**
  7757. + * ssh_ptl_shutdown - shut down the packet transmission layer
  7758. + * @ptl: packet transmission layer
  7759. + *
  7760. + * Shuts down the packet transmission layer, removing and canceling all queued
  7761. + * and pending packets. Packets canceled by this operation will be completed
  7762. + * with -ESHUTDOWN as status.
  7763. + *
  7764. + * As a result of this function, the transmission layer will be marked as shut
  7765. + * down. Submission of packets after the transmission layer has been shut down
  7766. + * will fail with -ESHUTDOWN.
  7767. + */
  7768. +static void ssh_ptl_shutdown(struct ssh_ptl *ptl)
  7769. +{
  7770. + LIST_HEAD(complete_q);
  7771. + LIST_HEAD(complete_p);
  7772. + struct ssh_packet *p, *n;
  7773. + int status;
  7774. +
  7775. + // ensure that no new packets (including ACK/NAK) can be submitted
  7776. + set_bit(SSH_PTL_SF_SHUTDOWN_BIT, &ptl->state);
  7777. + smp_mb__after_atomic();
  7778. +
  7779. + status = ssh_ptl_rx_stop(ptl);
  7780. + if (status)
  7781. + ptl_err(ptl, "ptl: failed to stop receiver thread\n");
  7782. +
  7783. + status = ssh_ptl_tx_stop(ptl);
  7784. + if (status)
  7785. + ptl_err(ptl, "ptl: failed to stop transmitter thread\n");
  7786. +
  7787. + cancel_delayed_work_sync(&ptl->rtx_timeout.reaper);
  7788. +
  7789. + /*
  7790. + * At this point, all threads have been stopped. This means that the
  7791. + * only references to packets from inside the system are in the queue
  7792. + * and pending set.
  7793. + *
  7794. + * Note: We still need locks here because someone could still be
  7795. + * cancelling packets.
  7796. + *
  7797. + * Note 2: We can re-use queue_node (or pending_node) if we mark the
  7798. + * packet as locked an then remove it from the queue (or pending set
  7799. + * respecitvely). Marking the packet as locked avoids re-queueing
  7800. + * (which should already be prevented by having stopped the treads...)
  7801. + * and not setting QUEUED_BIT (or PENDING_BIT) prevents removal from a
  7802. + * new list via other threads (e.g. canellation).
  7803. + *
  7804. + * Note 3: There may be overlap between complete_p and complete_q.
  7805. + * This is handled via test_and_set_bit on the "completed" flag
  7806. + * (also handles cancelation).
  7807. + */
  7808. +
  7809. + // mark queued packets as locked and move them to complete_q
  7810. + spin_lock(&ptl->queue.lock);
  7811. + list_for_each_entry_safe(p, n, &ptl->queue.head, queue_node) {
  7812. + set_bit(SSH_PACKET_SF_LOCKED_BIT, &p->state);
  7813. + smp_mb__before_atomic();
  7814. + clear_bit(SSH_PACKET_SF_QUEUED_BIT, &p->state);
  7815. +
  7816. + list_del(&p->queue_node);
  7817. + list_add_tail(&p->queue_node, &complete_q);
  7818. + }
  7819. + spin_unlock(&ptl->queue.lock);
  7820. +
  7821. + // mark pending packets as locked and move them to complete_p
  7822. + spin_lock(&ptl->pending.lock);
  7823. + list_for_each_entry_safe(p, n, &ptl->pending.head, pending_node) {
  7824. + set_bit(SSH_PACKET_SF_LOCKED_BIT, &p->state);
  7825. + smp_mb__before_atomic();
  7826. + clear_bit(SSH_PACKET_SF_PENDING_BIT, &p->state);
  7827. +
  7828. + list_del(&p->pending_node);
  7829. + list_add_tail(&p->pending_node, &complete_q);
  7830. + }
  7831. + atomic_set(&ptl->pending.count, 0);
  7832. + spin_unlock(&ptl->pending.lock);
  7833. +
  7834. + // complete and drop packets on complete_q
  7835. + list_for_each_entry(p, &complete_q, queue_node) {
  7836. + if (!test_and_set_bit(SSH_PACKET_SF_COMPLETED_BIT, &p->state))
  7837. + __ssh_ptl_complete(p, -ESHUTDOWN);
  7838. +
  7839. + ssh_packet_put(p);
  7840. + }
  7841. +
  7842. + // complete and drop packets on complete_p
  7843. + list_for_each_entry(p, &complete_p, pending_node) {
  7844. + if (!test_and_set_bit(SSH_PACKET_SF_COMPLETED_BIT, &p->state))
  7845. + __ssh_ptl_complete(p, -ESHUTDOWN);
  7846. +
  7847. + ssh_packet_put(p);
  7848. + }
  7849. +
  7850. + /*
  7851. + * At this point we have guaranteed that the system doesn't reference
  7852. + * any packets any more.
  7853. + */
  7854. +}
  7855. +
  7856. +static inline struct device *ssh_ptl_get_device(struct ssh_ptl *ptl)
  7857. +{
  7858. + return &ptl->serdev->dev;
  7859. +}
  7860. +
  7861. +static int ssh_ptl_init(struct ssh_ptl *ptl, struct serdev_device *serdev,
  7862. + struct ssh_ptl_ops *ops)
  7863. +{
  7864. + int i, status;
  7865. +
  7866. + ptl->serdev = serdev;
  7867. + ptl->state = 0;
  7868. +
  7869. + spin_lock_init(&ptl->queue.lock);
  7870. + INIT_LIST_HEAD(&ptl->queue.head);
  7871. +
  7872. + spin_lock_init(&ptl->pending.lock);
  7873. + INIT_LIST_HEAD(&ptl->pending.head);
  7874. + atomic_set_release(&ptl->pending.count, 0);
  7875. +
  7876. + ptl->tx.thread = NULL;
  7877. + ptl->tx.thread_signal = false;
  7878. + ptl->tx.packet = NULL;
  7879. + ptl->tx.offset = 0;
  7880. + init_waitqueue_head(&ptl->tx.thread_wq);
  7881. + init_waitqueue_head(&ptl->tx.packet_wq);
  7882. +
  7883. + ptl->rx.thread = NULL;
  7884. + init_waitqueue_head(&ptl->rx.wq);
  7885. +
  7886. + ptl->rtx_timeout.timeout = SSH_PTL_PACKET_TIMEOUT;
  7887. + ptl->rtx_timeout.expires = KTIME_MAX;
  7888. + INIT_DELAYED_WORK(&ptl->rtx_timeout.reaper, ssh_ptl_timeout_reap);
  7889. +
  7890. + ptl->ops = *ops;
  7891. +
  7892. + // initialize SEQ blacklist with invalid sequence IDs
  7893. + for (i = 0; i < ARRAY_SIZE(ptl->rx.blacklist.seqs); i++)
  7894. + ptl->rx.blacklist.seqs[i] = 0xFFFF;
  7895. + ptl->rx.blacklist.offset = 0;
  7896. +
  7897. + status = kfifo_alloc(&ptl->rx.fifo, SSH_PTL_RX_FIFO_LEN, GFP_KERNEL);
  7898. + if (status)
  7899. + return status;
  7900. +
  7901. + status = sshp_buf_alloc(&ptl->rx.buf, SSH_PTL_RX_BUF_LEN, GFP_KERNEL);
  7902. + if (status)
  7903. + kfifo_free(&ptl->rx.fifo);
  7904. +
  7905. + return status;
  7906. +}
  7907. +
  7908. +static void ssh_ptl_destroy(struct ssh_ptl *ptl)
  7909. +{
  7910. + kfifo_free(&ptl->rx.fifo);
  7911. + sshp_buf_free(&ptl->rx.buf);
  7912. +}
  7913. +
  7914. +
  7915. +/* -- Request transport layer (rtl). ---------------------------------------- */
  7916. +
  7917. +#define SSH_RTL_REQUEST_TIMEOUT ms_to_ktime(1000)
  7918. +#define SSH_RTL_REQUEST_TIMEOUT_RESOLUTION ms_to_ktime(max(2000 / HZ, 50))
  7919. +
  7920. +#define SSH_RTL_MAX_PENDING 3
  7921. +
  7922. +
  7923. +enum ssh_rtl_state_flags {
  7924. + SSH_RTL_SF_SHUTDOWN_BIT,
  7925. +};
  7926. +
  7927. +struct ssh_rtl_ops {
  7928. + void (*handle_event)(struct ssh_rtl *rtl, const struct ssh_command *cmd,
  7929. + const struct sshp_span *data);
  7930. +};
  7931. +
  7932. +struct ssh_rtl {
  7933. + struct ssh_ptl ptl;
  7934. + unsigned long state;
  7935. +
  7936. + struct {
  7937. + spinlock_t lock;
  7938. + struct list_head head;
  7939. + } queue;
  7940. +
  7941. + struct {
  7942. + spinlock_t lock;
  7943. + struct list_head head;
  7944. + atomic_t count;
  7945. + } pending;
  7946. +
  7947. + struct {
  7948. + struct work_struct work;
  7949. + } tx;
  7950. +
  7951. + struct {
  7952. + ktime_t timeout;
  7953. + ktime_t expires;
  7954. + struct delayed_work reaper;
  7955. + } rtx_timeout;
  7956. +
  7957. + struct ssh_rtl_ops ops;
  7958. +};
  7959. +
  7960. +
  7961. +#define rtl_dbg(r, fmt, ...) ptl_dbg(&(r)->ptl, fmt, ##__VA_ARGS__)
  7962. +#define rtl_info(p, fmt, ...) ptl_info(&(p)->ptl, fmt, ##__VA_ARGS__)
  7963. +#define rtl_warn(r, fmt, ...) ptl_warn(&(r)->ptl, fmt, ##__VA_ARGS__)
  7964. +#define rtl_err(r, fmt, ...) ptl_err(&(r)->ptl, fmt, ##__VA_ARGS__)
  7965. +#define rtl_dbg_cond(r, fmt, ...) __ssam_prcond(rtl_dbg, r, fmt, ##__VA_ARGS__)
  7966. +
  7967. +#define to_ssh_rtl(ptr, member) \
  7968. + container_of(ptr, struct ssh_rtl, member)
  7969. +
  7970. +#define to_ssh_request(ptr, member) \
  7971. + container_of(ptr, struct ssh_request, member)
  7972. +
  7973. +
  7974. +/**
  7975. + * ssh_rtl_should_drop_response - error injection hook to drop request responses
  7976. + *
  7977. + * Useful to cause request transmission timeouts in the driver by dropping the
  7978. + * response to a request.
  7979. + */
  7980. +static noinline_if_inject bool ssh_rtl_should_drop_response(void)
  7981. +{
  7982. + return false;
  7983. +}
  7984. +ALLOW_ERROR_INJECTION(ssh_rtl_should_drop_response, TRUE);
  7985. +
  7986. +
  7987. +static inline void ssh_request_get(struct ssh_request *rqst)
  7988. +{
  7989. + ssh_packet_get(&rqst->packet);
  7990. +}
  7991. +
  7992. +static inline void ssh_request_put(struct ssh_request *rqst)
  7993. +{
  7994. + ssh_packet_put(&rqst->packet);
  7995. +}
  7996. +
  7997. +
  7998. +static inline u16 ssh_request_get_rqid(struct ssh_request *rqst)
  7999. +{
  8000. + return get_unaligned_le16(rqst->packet.data
  8001. + + SSH_MSGOFFSET_COMMAND(rqid));
  8002. +}
  8003. +
  8004. +static inline u32 ssh_request_get_rqid_safe(struct ssh_request *rqst)
  8005. +{
  8006. + if (!rqst->packet.data)
  8007. + return -1;
  8008. +
  8009. + return ssh_request_get_rqid(rqst);
  8010. +}
  8011. +
  8012. +
  8013. +static void ssh_rtl_queue_remove(struct ssh_request *rqst)
  8014. +{
  8015. + bool remove;
  8016. +
  8017. + spin_lock(&rqst->rtl->queue.lock);
  8018. +
  8019. + remove = test_and_clear_bit(SSH_REQUEST_SF_QUEUED_BIT, &rqst->state);
  8020. + if (remove)
  8021. + list_del(&rqst->node);
  8022. +
  8023. + spin_unlock(&rqst->rtl->queue.lock);
  8024. +
  8025. + if (remove)
  8026. + ssh_request_put(rqst);
  8027. +}
  8028. +
  8029. +static void ssh_rtl_pending_remove(struct ssh_request *rqst)
  8030. +{
  8031. + bool remove;
  8032. +
  8033. + spin_lock(&rqst->rtl->pending.lock);
  8034. +
  8035. + remove = test_and_clear_bit(SSH_REQUEST_SF_PENDING_BIT, &rqst->state);
  8036. + if (remove) {
  8037. + atomic_dec(&rqst->rtl->pending.count);
  8038. + list_del(&rqst->node);
  8039. + }
  8040. +
  8041. + spin_unlock(&rqst->rtl->pending.lock);
  8042. +
  8043. + if (remove)
  8044. + ssh_request_put(rqst);
  8045. +}
  8046. +
  8047. +
  8048. +static void ssh_rtl_complete_with_status(struct ssh_request *rqst, int status)
  8049. +{
  8050. + struct ssh_rtl *rtl = READ_ONCE(rqst->rtl);
  8051. +
  8052. + trace_ssam_request_complete(rqst, status);
  8053. +
  8054. + // rqst->rtl may not be set if we're cancelling before submitting
  8055. + rtl_dbg_cond(rtl, "rtl: completing request (rqid: 0x%04x,"
  8056. + " status: %d)\n", ssh_request_get_rqid_safe(rqst), status);
  8057. +
  8058. + rqst->ops->complete(rqst, NULL, NULL, status);
  8059. +}
  8060. +
  8061. +static void ssh_rtl_complete_with_rsp(struct ssh_request *rqst,
  8062. + const struct ssh_command *cmd,
  8063. + const struct sshp_span *data)
  8064. +{
  8065. + trace_ssam_request_complete(rqst, 0);
  8066. +
  8067. + rtl_dbg(rqst->rtl, "rtl: completing request with response"
  8068. + " (rqid: 0x%04x)\n", ssh_request_get_rqid(rqst));
  8069. +
  8070. + rqst->ops->complete(rqst, cmd, data, 0);
  8071. +}
  8072. +
  8073. +
  8074. +static bool ssh_rtl_tx_can_process(struct ssh_request *rqst)
  8075. +{
  8076. + if (test_bit(SSH_REQUEST_TY_FLUSH_BIT, &rqst->state))
  8077. + return !atomic_read(&rqst->rtl->pending.count);
  8078. +
  8079. + return atomic_read(&rqst->rtl->pending.count) < SSH_RTL_MAX_PENDING;
  8080. +}
  8081. +
  8082. +static struct ssh_request *ssh_rtl_tx_next(struct ssh_rtl *rtl)
  8083. +{
  8084. + struct ssh_request *rqst = ERR_PTR(-ENOENT);
  8085. + struct ssh_request *p, *n;
  8086. +
  8087. + spin_lock(&rtl->queue.lock);
  8088. +
  8089. + // find first non-locked request and remove it
  8090. + list_for_each_entry_safe(p, n, &rtl->queue.head, node) {
  8091. + if (unlikely(test_bit(SSH_REQUEST_SF_LOCKED_BIT, &p->state)))
  8092. + continue;
  8093. +
  8094. + if (!ssh_rtl_tx_can_process(p)) {
  8095. + rqst = ERR_PTR(-EBUSY);
  8096. + break;
  8097. + }
  8098. +
  8099. + /*
  8100. + * Remove from queue and mark as transmitting. Ensure that the
  8101. + * state does not get zero via memory barrier.
  8102. + */
  8103. + set_bit(SSH_REQUEST_SF_TRANSMITTING_BIT, &p->state);
  8104. + smp_mb__before_atomic();
  8105. + clear_bit(SSH_REQUEST_SF_QUEUED_BIT, &p->state);
  8106. +
  8107. + list_del(&p->node);
  8108. +
  8109. + rqst = p;
  8110. + break;
  8111. + }
  8112. +
  8113. + spin_unlock(&rtl->queue.lock);
  8114. + return rqst;
  8115. +}
  8116. +
  8117. +static int ssh_rtl_tx_pending_push(struct ssh_request *rqst)
  8118. +{
  8119. + struct ssh_rtl *rtl = rqst->rtl;
  8120. +
  8121. + spin_lock(&rtl->pending.lock);
  8122. +
  8123. + if (test_bit(SSH_REQUEST_SF_LOCKED_BIT, &rqst->state)) {
  8124. + spin_unlock(&rtl->pending.lock);
  8125. + return -EINVAL;
  8126. + }
  8127. +
  8128. + if (test_and_set_bit(SSH_REQUEST_SF_PENDING_BIT, &rqst->state)) {
  8129. + spin_unlock(&rtl->pending.lock);
  8130. + return -EALREADY;
  8131. + }
  8132. +
  8133. + atomic_inc(&rtl->pending.count);
  8134. + ssh_request_get(rqst);
  8135. + list_add_tail(&rqst->node, &rtl->pending.head);
  8136. +
  8137. + spin_unlock(&rtl->pending.lock);
  8138. + return 0;
  8139. +}
  8140. +
  8141. +static int ssh_rtl_tx_try_process_one(struct ssh_rtl *rtl)
  8142. +{
  8143. + struct ssh_request *rqst;
  8144. + int status;
  8145. +
  8146. + // get and prepare next request for transmit
  8147. + rqst = ssh_rtl_tx_next(rtl);
  8148. + if (IS_ERR(rqst))
  8149. + return PTR_ERR(rqst);
  8150. +
  8151. + // add to/mark as pending
  8152. + status = ssh_rtl_tx_pending_push(rqst);
  8153. + if (status) {
  8154. + ssh_request_put(rqst);
  8155. + return -EAGAIN;
  8156. + }
  8157. +
  8158. + // submit packet
  8159. + status = ssh_ptl_submit(&rtl->ptl, &rqst->packet);
  8160. + if (status == -ESHUTDOWN) {
  8161. + /*
  8162. + * Packet has been refused due to the packet layer shutting
  8163. + * down. Complete it here.
  8164. + */
  8165. + set_bit(SSH_REQUEST_SF_LOCKED_BIT, &rqst->state);
  8166. + smp_mb__after_atomic();
  8167. +
  8168. + ssh_rtl_pending_remove(rqst);
  8169. + ssh_rtl_complete_with_status(rqst, -ESHUTDOWN);
  8170. +
  8171. + ssh_request_put(rqst);
  8172. + return -ESHUTDOWN;
  8173. +
  8174. + } else if (status) {
  8175. + /*
  8176. + * If submitting the packet failed and the packet layer isn't
  8177. + * shutting down, the packet has either been submmitted/queued
  8178. + * before (-EALREADY, which cannot happen as we have guaranteed
  8179. + * that requests cannot be re-submitted), or the packet was
  8180. + * marked as locked (-EINVAL). To mark the packet locked at this
  8181. + * stage, the request, and thus the packets itself, had to have
  8182. + * been canceled. Simply drop the reference. Cancellation itself
  8183. + * will remove it from the set of pending requests.
  8184. + */
  8185. +
  8186. + WARN_ON(status != -EINVAL);
  8187. +
  8188. + ssh_request_put(rqst);
  8189. + return -EAGAIN;
  8190. + }
  8191. +
  8192. + ssh_request_put(rqst);
  8193. + return 0;
  8194. +}
  8195. +
  8196. +static bool ssh_rtl_queue_empty(struct ssh_rtl *rtl)
  8197. +{
  8198. + bool empty;
  8199. +
  8200. + spin_lock(&rtl->queue.lock);
  8201. + empty = list_empty(&rtl->queue.head);
  8202. + spin_unlock(&rtl->queue.lock);
  8203. +
  8204. + return empty;
  8205. +}
  8206. +
  8207. +static bool ssh_rtl_tx_schedule(struct ssh_rtl *rtl)
  8208. +{
  8209. + if (atomic_read(&rtl->pending.count) >= SSH_RTL_MAX_PENDING)
  8210. + return false;
  8211. +
  8212. + if (ssh_rtl_queue_empty(rtl))
  8213. + return false;
  8214. +
  8215. + return schedule_work(&rtl->tx.work);
  8216. +}
  8217. +
  8218. +static void ssh_rtl_tx_work_fn(struct work_struct *work)
  8219. +{
  8220. + struct ssh_rtl *rtl = to_ssh_rtl(work, tx.work);
  8221. + int i, status;
  8222. +
  8223. + /*
  8224. + * Try to be nice and not block the workqueue: Run a maximum of 10
  8225. + * tries, then re-submit if necessary. This should not be neccesary,
  8226. + * for normal execution, but guarantee it anyway.
  8227. + */
  8228. + for (i = 0; i < 10; i++) {
  8229. + status = ssh_rtl_tx_try_process_one(rtl);
  8230. + if (status == -ENOENT || status == -EBUSY)
  8231. + return; // no more requests to process
  8232. +
  8233. + if (status == -ESHUTDOWN) {
  8234. + /*
  8235. + * Packet system shutting down. No new packets can be
  8236. + * transmitted. Return silently, the party initiating
  8237. + * the shutdown should handle the rest.
  8238. + */
  8239. + return;
  8240. + }
  8241. +
  8242. + WARN_ON(status != 0 && status != -EAGAIN);
  8243. + }
  8244. +
  8245. + // out of tries, reschedule
  8246. + ssh_rtl_tx_schedule(rtl);
  8247. +}
  8248. +
  8249. +
  8250. +static int ssh_rtl_submit(struct ssh_rtl *rtl, struct ssh_request *rqst)
  8251. +{
  8252. + trace_ssam_request_submit(rqst);
  8253. +
  8254. + /*
  8255. + * Ensure that requests expecting a response are sequenced. If this
  8256. + * invariant ever changes, see the comment in ssh_rtl_complete on what
  8257. + * is required to be changed in the code.
  8258. + */
  8259. + if (test_bit(SSH_REQUEST_TY_HAS_RESPONSE_BIT, &rqst->state))
  8260. + if (!(rqst->packet.type & SSH_PACKET_TY_SEQUENCED))
  8261. + return -EINVAL;
  8262. +
  8263. + // try to set rtl and check if this request has already been submitted
  8264. + if (cmpxchg(&rqst->rtl, NULL, rtl) != NULL)
  8265. + return -EALREADY;
  8266. +
  8267. + spin_lock(&rtl->queue.lock);
  8268. +
  8269. + if (test_bit(SSH_RTL_SF_SHUTDOWN_BIT, &rtl->state)) {
  8270. + spin_unlock(&rtl->queue.lock);
  8271. + return -ESHUTDOWN;
  8272. + }
  8273. +
  8274. + if (test_bit(SSH_REQUEST_SF_LOCKED_BIT, &rqst->state)) {
  8275. + spin_unlock(&rtl->queue.lock);
  8276. + return -EINVAL;
  8277. + }
  8278. +
  8279. + ssh_request_get(rqst);
  8280. + set_bit(SSH_REQUEST_SF_QUEUED_BIT, &rqst->state);
  8281. + list_add_tail(&rqst->node, &rtl->queue.head);
  8282. +
  8283. + spin_unlock(&rtl->queue.lock);
  8284. +
  8285. + ssh_rtl_tx_schedule(rtl);
  8286. + return 0;
  8287. +}
  8288. +
  8289. +
  8290. +static void ssh_rtl_timeout_reaper_mod(struct ssh_rtl *rtl, ktime_t now,
  8291. + ktime_t expires)
  8292. +{
  8293. + unsigned long delta = msecs_to_jiffies(ktime_ms_delta(expires, now));
  8294. + ktime_t aexp = ktime_add(expires, SSH_RTL_REQUEST_TIMEOUT_RESOLUTION);
  8295. + ktime_t old;
  8296. +
  8297. + // re-adjust / schedule reaper if it is above resolution delta
  8298. + old = READ_ONCE(rtl->rtx_timeout.expires);
  8299. + while (ktime_before(aexp, old))
  8300. + old = cmpxchg64(&rtl->rtx_timeout.expires, old, expires);
  8301. +
  8302. + // if we updated the reaper expiration, modify work timeout
  8303. + if (old == expires)
  8304. + mod_delayed_work(system_wq, &rtl->rtx_timeout.reaper, delta);
  8305. +}
  8306. +
  8307. +static void ssh_rtl_timeout_start(struct ssh_request *rqst)
  8308. +{
  8309. + struct ssh_rtl *rtl = rqst->rtl;
  8310. + ktime_t timestamp = ktime_get_coarse_boottime();
  8311. + ktime_t timeout = rtl->rtx_timeout.timeout;
  8312. +
  8313. + if (test_bit(SSH_REQUEST_SF_LOCKED_BIT, &rqst->state))
  8314. + return;
  8315. +
  8316. + WRITE_ONCE(rqst->timestamp, timestamp);
  8317. + smp_mb__after_atomic();
  8318. +
  8319. + ssh_rtl_timeout_reaper_mod(rqst->rtl, timestamp, timestamp + timeout);
  8320. +}
  8321. +
  8322. +
  8323. +static void ssh_rtl_complete(struct ssh_rtl *rtl,
  8324. + const struct ssh_command *command,
  8325. + const struct sshp_span *command_data)
  8326. +{
  8327. + struct ssh_request *r = NULL;
  8328. + struct ssh_request *p, *n;
  8329. + u16 rqid = get_unaligned_le16(&command->rqid);
  8330. +
  8331. + trace_ssam_rx_response_received(command, command_data->len);
  8332. +
  8333. + /*
  8334. + * Get request from pending based on request ID and mark it as response
  8335. + * received and locked.
  8336. + */
  8337. + spin_lock(&rtl->pending.lock);
  8338. + list_for_each_entry_safe(p, n, &rtl->pending.head, node) {
  8339. + // we generally expect requests to be processed in order
  8340. + if (unlikely(ssh_request_get_rqid(p) != rqid))
  8341. + continue;
  8342. +
  8343. + // simulate response timeout
  8344. + if (ssh_rtl_should_drop_response()) {
  8345. + spin_unlock(&rtl->pending.lock);
  8346. +
  8347. + trace_ssam_ei_rx_drop_response(p);
  8348. + rtl_info(rtl, "request error injection: "
  8349. + "dropping response for request %p\n",
  8350. + &p->packet);
  8351. + return;
  8352. + }
  8353. +
  8354. + /*
  8355. + * Mark as "response received" and "locked" as we're going to
  8356. + * complete it. Ensure that the state doesn't get zero by
  8357. + * employing a memory barrier.
  8358. + */
  8359. + set_bit(SSH_REQUEST_SF_LOCKED_BIT, &p->state);
  8360. + set_bit(SSH_REQUEST_SF_RSPRCVD_BIT, &p->state);
  8361. + smp_mb__before_atomic();
  8362. + clear_bit(SSH_REQUEST_SF_PENDING_BIT, &p->state);
  8363. +
  8364. + atomic_dec(&rtl->pending.count);
  8365. + list_del(&p->node);
  8366. +
  8367. + r = p;
  8368. + break;
  8369. + }
  8370. + spin_unlock(&rtl->pending.lock);
  8371. +
  8372. + if (!r) {
  8373. + rtl_warn(rtl, "rtl: dropping unexpected command message"
  8374. + " (rqid = 0x%04x)\n", rqid);
  8375. + return;
  8376. + }
  8377. +
  8378. + // if the request hasn't been completed yet, we will do this now
  8379. + if (test_and_set_bit(SSH_REQUEST_SF_COMPLETED_BIT, &r->state)) {
  8380. + ssh_request_put(r);
  8381. + ssh_rtl_tx_schedule(rtl);
  8382. + return;
  8383. + }
  8384. +
  8385. + /*
  8386. + * Make sure the request has been transmitted. In case of a sequenced
  8387. + * request, we are guaranteed that the completion callback will run on
  8388. + * the receiver thread directly when the ACK for the packet has been
  8389. + * received. Similarly, this function is guaranteed to run on the
  8390. + * receiver thread. Thus we are guaranteed that if the packet has been
  8391. + * successfully transmitted and received an ACK, the transmitted flag
  8392. + * has been set and is visible here.
  8393. + *
  8394. + * We are currently not handling unsequenced packets here, as those
  8395. + * should never expect a response as ensured in ssh_rtl_submit. If this
  8396. + * ever changes, one would have to test for
  8397. + *
  8398. + * (r->state & (transmitting | transmitted))
  8399. + *
  8400. + * on unsequenced packets to determine if they could have been
  8401. + * transmitted. There are no synchronization guarantees as in the
  8402. + * sequenced case, since, in this case, the callback function will not
  8403. + * run on the same thread. Thus an exact determination is impossible.
  8404. + */
  8405. + if (!test_bit(SSH_REQUEST_SF_TRANSMITTED_BIT, &r->state)) {
  8406. + rtl_err(rtl, "rtl: received response before ACK for request"
  8407. + " (rqid = 0x%04x)\n", rqid);
  8408. +
  8409. + /*
  8410. + * NB: Timeout has already been canceled, request already been
  8411. + * removed from pending and marked as locked and completed. As
  8412. + * we receive a "false" response, the packet might still be
  8413. + * queued though.
  8414. + */
  8415. + ssh_rtl_queue_remove(r);
  8416. +
  8417. + ssh_rtl_complete_with_status(r, -EREMOTEIO);
  8418. + ssh_request_put(r);
  8419. +
  8420. + ssh_rtl_tx_schedule(rtl);
  8421. + return;
  8422. + }
  8423. +
  8424. + /*
  8425. + * NB: Timeout has already been canceled, request already been
  8426. + * removed from pending and marked as locked and completed. The request
  8427. + * can also not be queued any more, as it has been marked as
  8428. + * transmitting and later transmitted. Thus no need to remove it from
  8429. + * anywhere.
  8430. + */
  8431. +
  8432. + ssh_rtl_complete_with_rsp(r, command, command_data);
  8433. + ssh_request_put(r);
  8434. +
  8435. + ssh_rtl_tx_schedule(rtl);
  8436. +}
  8437. +
  8438. +
  8439. +static bool ssh_rtl_cancel_nonpending(struct ssh_request *r)
  8440. +{
  8441. + unsigned long state, fixed;
  8442. + bool remove;
  8443. +
  8444. + /*
  8445. + * Handle unsubmitted request: Try to mark the packet as locked,
  8446. + * expecting the state to be zero (i.e. unsubmitted). Note that, if
  8447. + * setting the state worked, we might still be adding the packet to the
  8448. + * queue in a currently executing submit call. In that case, however,
  8449. + * rqst->rtl must have been set previously, as locked is checked after
  8450. + * setting rqst->rtl. Thus only if we successfully lock this request and
  8451. + * rqst->rtl is NULL, we have successfully removed the request.
  8452. + * Otherwise we need to try and grab it from the queue.
  8453. + *
  8454. + * Note that if the CMPXCHG fails, we are guaranteed that rqst->rtl has
  8455. + * been set and is non-NULL, as states can only be nonzero after this
  8456. + * has been set. Also note that we need to fetch the static (type) flags
  8457. + * to ensure that they don't cause the cmpxchg to fail.
  8458. + */
  8459. + fixed = READ_ONCE(r->state) & SSH_REQUEST_FLAGS_TY_MASK;
  8460. + state = cmpxchg(&r->state, fixed, SSH_REQUEST_SF_LOCKED_BIT);
  8461. + if (!state && !READ_ONCE(r->rtl)) {
  8462. + if (test_and_set_bit(SSH_REQUEST_SF_COMPLETED_BIT, &r->state))
  8463. + return true;
  8464. +
  8465. + ssh_rtl_complete_with_status(r, -ECANCELED);
  8466. + return true;
  8467. + }
  8468. +
  8469. + spin_lock(&r->rtl->queue.lock);
  8470. +
  8471. + /*
  8472. + * Note: 1) Requests cannot be re-submitted. 2) If a request is queued,
  8473. + * it cannot be "transmitting"/"pending" yet. Thus, if we successfully
  8474. + * remove the the request here, we have removed all its occurences in
  8475. + * the system.
  8476. + */
  8477. +
  8478. + remove = test_and_clear_bit(SSH_REQUEST_SF_QUEUED_BIT, &r->state);
  8479. + if (!remove) {
  8480. + spin_unlock(&r->rtl->queue.lock);
  8481. + return false;
  8482. + }
  8483. +
  8484. + set_bit(SSH_REQUEST_SF_LOCKED_BIT, &r->state);
  8485. + list_del(&r->node);
  8486. +
  8487. + spin_unlock(&r->rtl->queue.lock);
  8488. +
  8489. + ssh_request_put(r); // drop reference obtained from queue
  8490. +
  8491. + if (test_and_set_bit(SSH_REQUEST_SF_COMPLETED_BIT, &r->state))
  8492. + return true;
  8493. +
  8494. + ssh_rtl_complete_with_status(r, -ECANCELED);
  8495. + return true;
  8496. +}
  8497. +
  8498. +static bool ssh_rtl_cancel_pending(struct ssh_request *r)
  8499. +{
  8500. + // if the packet is already locked, it's going to be removed shortly
  8501. + if (test_and_set_bit(SSH_REQUEST_SF_LOCKED_BIT, &r->state))
  8502. + return true;
  8503. +
  8504. + /*
  8505. + * Now that we have locked the packet, we have guaranteed that it can't
  8506. + * be added to the system any more. If rqst->rtl is zero, the locked
  8507. + * check in ssh_rtl_submit has not been run and any submission,
  8508. + * currently in progress or called later, won't add the packet. Thus we
  8509. + * can directly complete it.
  8510. + */
  8511. + if (!READ_ONCE(r->rtl)) {
  8512. + if (test_and_set_bit(SSH_REQUEST_SF_COMPLETED_BIT, &r->state))
  8513. + return true;
  8514. +
  8515. + ssh_rtl_complete_with_status(r, -ECANCELED);
  8516. + return true;
  8517. + }
  8518. +
  8519. + /*
  8520. + * Try to cancel the packet. If the packet has not been completed yet,
  8521. + * this will subsequently (and synchronously) call the completion
  8522. + * callback of the packet, which will complete the request.
  8523. + */
  8524. + ssh_ptl_cancel(&r->packet);
  8525. +
  8526. + /*
  8527. + * If the packet has been completed with success, i.e. has not been
  8528. + * canceled by the above call, the request may not have been completed
  8529. + * yet (may be waiting for a response). Check if we need to do this
  8530. + * here.
  8531. + */
  8532. + if (test_and_set_bit(SSH_REQUEST_SF_COMPLETED_BIT, &r->state))
  8533. + return true;
  8534. +
  8535. + ssh_rtl_queue_remove(r);
  8536. + ssh_rtl_pending_remove(r);
  8537. + ssh_rtl_complete_with_status(r, -ECANCELED);
  8538. +
  8539. + return true;
  8540. +}
  8541. +
  8542. +static bool ssh_rtl_cancel(struct ssh_request *rqst, bool pending)
  8543. +{
  8544. + struct ssh_rtl *rtl;
  8545. + bool canceled;
  8546. +
  8547. + if (test_and_set_bit(SSH_REQUEST_SF_CANCELED_BIT, &rqst->state))
  8548. + return true;
  8549. +
  8550. + trace_ssam_request_cancel(rqst);
  8551. +
  8552. + if (pending)
  8553. + canceled = ssh_rtl_cancel_pending(rqst);
  8554. + else
  8555. + canceled = ssh_rtl_cancel_nonpending(rqst);
  8556. +
  8557. + // note: rqst->rtl may be NULL if request has not been submitted yet
  8558. + rtl = READ_ONCE(rqst->rtl);
  8559. + if (canceled && rtl)
  8560. + ssh_rtl_tx_schedule(rtl);
  8561. +
  8562. + return canceled;
  8563. +}
  8564. +
  8565. +
  8566. +static void ssh_rtl_packet_callback(struct ssh_packet *p, int status)
  8567. +{
  8568. + struct ssh_request *r = to_ssh_request(p, packet);
  8569. +
  8570. + if (unlikely(status)) {
  8571. + set_bit(SSH_REQUEST_SF_LOCKED_BIT, &r->state);
  8572. +
  8573. + if (test_and_set_bit(SSH_REQUEST_SF_COMPLETED_BIT, &r->state))
  8574. + return;
  8575. +
  8576. + /*
  8577. + * The packet may get cancelled even though it has not been
  8578. + * submitted yet. The request may still be queued. Check the
  8579. + * queue and remove it if necessary. As the timeout would have
  8580. + * been started in this function on success, there's no need to
  8581. + * cancel it here.
  8582. + */
  8583. + ssh_rtl_queue_remove(r);
  8584. + ssh_rtl_pending_remove(r);
  8585. + ssh_rtl_complete_with_status(r, status);
  8586. +
  8587. + ssh_rtl_tx_schedule(r->rtl);
  8588. + return;
  8589. + }
  8590. +
  8591. + /*
  8592. + * Mark as transmitted, ensure that state doesn't get zero by inserting
  8593. + * a memory barrier.
  8594. + */
  8595. + set_bit(SSH_REQUEST_SF_TRANSMITTED_BIT, &r->state);
  8596. + smp_mb__before_atomic();
  8597. + clear_bit(SSH_REQUEST_SF_TRANSMITTING_BIT, &r->state);
  8598. +
  8599. + // if we expect a response, we just need to start the timeout
  8600. + if (test_bit(SSH_REQUEST_TY_HAS_RESPONSE_BIT, &r->state)) {
  8601. + ssh_rtl_timeout_start(r);
  8602. + return;
  8603. + }
  8604. +
  8605. + /*
  8606. + * If we don't expect a response, lock, remove, and complete the
  8607. + * request. Note that, at this point, the request is guaranteed to have
  8608. + * left the queue and no timeout has been started. Thus we only need to
  8609. + * remove it from pending. If the request has already been completed (it
  8610. + * may have been canceled) return.
  8611. + */
  8612. +
  8613. + set_bit(SSH_REQUEST_SF_LOCKED_BIT, &r->state);
  8614. + if (test_and_set_bit(SSH_REQUEST_SF_COMPLETED_BIT, &r->state))
  8615. + return;
  8616. +
  8617. + ssh_rtl_pending_remove(r);
  8618. + ssh_rtl_complete_with_status(r, 0);
  8619. +
  8620. + ssh_rtl_tx_schedule(r->rtl);
  8621. +}
  8622. +
  8623. +
  8624. +static ktime_t ssh_request_get_expiration(struct ssh_request *r, ktime_t timeo)
  8625. +{
  8626. + ktime_t timestamp = READ_ONCE(r->timestamp);
  8627. +
  8628. + if (timestamp != KTIME_MAX)
  8629. + return ktime_add(timestamp, timeo);
  8630. + else
  8631. + return KTIME_MAX;
  8632. +}
  8633. +
  8634. +static void ssh_rtl_timeout_reap(struct work_struct *work)
  8635. +{
  8636. + struct ssh_rtl *rtl = to_ssh_rtl(work, rtx_timeout.reaper.work);
  8637. + struct ssh_request *r, *n;
  8638. + LIST_HEAD(claimed);
  8639. + ktime_t now = ktime_get_coarse_boottime();
  8640. + ktime_t timeout = rtl->rtx_timeout.timeout;
  8641. + ktime_t next = KTIME_MAX;
  8642. +
  8643. + trace_ssam_rtl_timeout_reap("pending", atomic_read(&rtl->pending.count));
  8644. +
  8645. + /*
  8646. + * Mark reaper as "not pending". This is done before checking any
  8647. + * requests to avoid lost-update type problems.
  8648. + */
  8649. + WRITE_ONCE(rtl->rtx_timeout.expires, KTIME_MAX);
  8650. + smp_mb__after_atomic();
  8651. +
  8652. + spin_lock(&rtl->pending.lock);
  8653. + list_for_each_entry_safe(r, n, &rtl->pending.head, node) {
  8654. + ktime_t expires = ssh_request_get_expiration(r, timeout);
  8655. +
  8656. + /*
  8657. + * Check if the timeout hasn't expired yet. Find out next
  8658. + * expiration date to be handled after this run.
  8659. + */
  8660. + if (ktime_after(expires, now)) {
  8661. + next = ktime_before(expires, next) ? expires : next;
  8662. + continue;
  8663. + }
  8664. +
  8665. + // avoid further transitions if locked
  8666. + if (test_and_set_bit(SSH_REQUEST_SF_LOCKED_BIT, &r->state))
  8667. + continue;
  8668. +
  8669. + /*
  8670. + * We have now marked the packet as locked. Thus it cannot be
  8671. + * added to the pending or queued lists again after we've
  8672. + * removed it here. We can therefore re-use the node of this
  8673. + * packet temporarily.
  8674. + */
  8675. +
  8676. + clear_bit(SSH_REQUEST_SF_PENDING_BIT, &r->state);
  8677. +
  8678. + atomic_dec(&rtl->pending.count);
  8679. + list_del(&r->node);
  8680. +
  8681. + list_add_tail(&r->node, &claimed);
  8682. + }
  8683. + spin_unlock(&rtl->pending.lock);
  8684. +
  8685. + // cancel and complete the request
  8686. + list_for_each_entry_safe(r, n, &claimed, node) {
  8687. + trace_ssam_request_timeout(r);
  8688. +
  8689. + /*
  8690. + * At this point we've removed the packet from pending. This
  8691. + * means that we've obtained the last (only) reference of the
  8692. + * system to it. Thus we can just complete it.
  8693. + */
  8694. + if (!test_and_set_bit(SSH_REQUEST_SF_COMPLETED_BIT, &r->state))
  8695. + ssh_rtl_complete_with_status(r, -ETIMEDOUT);
  8696. +
  8697. + // drop the reference we've obtained by removing it from pending
  8698. + list_del(&r->node);
  8699. + ssh_request_put(r);
  8700. + }
  8701. +
  8702. + // ensure that reaper doesn't run again immediately
  8703. + next = max(next, ktime_add(now, SSH_RTL_REQUEST_TIMEOUT_RESOLUTION));
  8704. + if (next != KTIME_MAX)
  8705. + ssh_rtl_timeout_reaper_mod(rtl, now, next);
  8706. +
  8707. + ssh_rtl_tx_schedule(rtl);
  8708. +}
  8709. +
  8710. +
  8711. +static void ssh_rtl_rx_event(struct ssh_rtl *rtl, const struct ssh_command *cmd,
  8712. + const struct sshp_span *data)
  8713. +{
  8714. + trace_ssam_rx_event_received(cmd, data->len);
  8715. +
  8716. + rtl_dbg(rtl, "rtl: handling event (rqid: 0x%04x)\n",
  8717. + get_unaligned_le16(&cmd->rqid));
  8718. +
  8719. + rtl->ops.handle_event(rtl, cmd, data);
  8720. +}
  8721. +
  8722. +static void ssh_rtl_rx_command(struct ssh_ptl *p, const struct sshp_span *data)
  8723. +{
  8724. + struct ssh_rtl *rtl = to_ssh_rtl(p, ptl);
  8725. + struct device *dev = &p->serdev->dev;
  8726. + struct ssh_command *command;
  8727. + struct sshp_span command_data;
  8728. +
  8729. + if (sshp_parse_command(dev, data, &command, &command_data))
  8730. + return;
  8731. +
  8732. + if (ssh_rqid_is_event(get_unaligned_le16(&command->rqid)))
  8733. + ssh_rtl_rx_event(rtl, command, &command_data);
  8734. + else
  8735. + ssh_rtl_complete(rtl, command, &command_data);
  8736. +}
  8737. +
  8738. +static void ssh_rtl_rx_data(struct ssh_ptl *p, const struct sshp_span *data)
  8739. +{
  8740. + switch (data->ptr[0]) {
  8741. + case SSH_PLD_TYPE_CMD:
  8742. + ssh_rtl_rx_command(p, data);
  8743. + break;
  8744. +
  8745. + default:
  8746. + ptl_err(p, "rtl: rx: unknown frame payload type"
  8747. + " (type: 0x%02x)\n", data->ptr[0]);
  8748. + break;
  8749. + }
  8750. +}
  8751. +
  8752. +
  8753. +static inline struct device *ssh_rtl_get_device(struct ssh_rtl *rtl)
  8754. +{
  8755. + return ssh_ptl_get_device(&rtl->ptl);
  8756. +}
  8757. +
  8758. +static inline bool ssh_rtl_tx_flush(struct ssh_rtl *rtl)
  8759. +{
  8760. + return flush_work(&rtl->tx.work);
  8761. +}
  8762. +
  8763. +static inline int ssh_rtl_tx_start(struct ssh_rtl *rtl)
  8764. +{
  8765. + int status;
  8766. + bool sched;
  8767. +
  8768. + status = ssh_ptl_tx_start(&rtl->ptl);
  8769. + if (status)
  8770. + return status;
  8771. +
  8772. + /*
  8773. + * If the packet layer has been shut down and restarted without shutting
  8774. + * down the request layer, there may still be requests queued and not
  8775. + * handled.
  8776. + */
  8777. + spin_lock(&rtl->queue.lock);
  8778. + sched = !list_empty(&rtl->queue.head);
  8779. + spin_unlock(&rtl->queue.lock);
  8780. +
  8781. + if (sched)
  8782. + ssh_rtl_tx_schedule(rtl);
  8783. +
  8784. + return 0;
  8785. +}
  8786. +
  8787. +static inline int ssh_rtl_rx_start(struct ssh_rtl *rtl)
  8788. +{
  8789. + return ssh_ptl_rx_start(&rtl->ptl);
  8790. +}
  8791. +
  8792. +static int ssh_rtl_init(struct ssh_rtl *rtl, struct serdev_device *serdev,
  8793. + struct ssh_rtl_ops *ops)
  8794. +{
  8795. + struct ssh_ptl_ops ptl_ops;
  8796. + int status;
  8797. +
  8798. + ptl_ops.data_received = ssh_rtl_rx_data;
  8799. +
  8800. + status = ssh_ptl_init(&rtl->ptl, serdev, &ptl_ops);
  8801. + if (status)
  8802. + return status;
  8803. +
  8804. + spin_lock_init(&rtl->queue.lock);
  8805. + INIT_LIST_HEAD(&rtl->queue.head);
  8806. +
  8807. + spin_lock_init(&rtl->pending.lock);
  8808. + INIT_LIST_HEAD(&rtl->pending.head);
  8809. + atomic_set_release(&rtl->pending.count, 0);
  8810. +
  8811. + INIT_WORK(&rtl->tx.work, ssh_rtl_tx_work_fn);
  8812. +
  8813. + rtl->rtx_timeout.timeout = SSH_RTL_REQUEST_TIMEOUT;
  8814. + rtl->rtx_timeout.expires = KTIME_MAX;
  8815. + INIT_DELAYED_WORK(&rtl->rtx_timeout.reaper, ssh_rtl_timeout_reap);
  8816. +
  8817. + rtl->ops = *ops;
  8818. +
  8819. + return 0;
  8820. +}
  8821. +
  8822. +static void ssh_rtl_destroy(struct ssh_rtl *rtl)
  8823. +{
  8824. + ssh_ptl_destroy(&rtl->ptl);
  8825. +}
  8826. +
  8827. +
  8828. +static void ssh_rtl_packet_release(struct ssh_packet *p)
  8829. +{
  8830. + struct ssh_request *rqst = to_ssh_request(p, packet);
  8831. + rqst->ops->release(rqst);
  8832. +}
  8833. +
  8834. +static const struct ssh_packet_ops ssh_rtl_packet_ops = {
  8835. + .complete = ssh_rtl_packet_callback,
  8836. + .release = ssh_rtl_packet_release,
  8837. +};
  8838. +
  8839. +static void ssh_request_init(struct ssh_request *rqst,
  8840. + enum ssam_request_flags flags,
  8841. + const struct ssh_request_ops *ops)
  8842. +{
  8843. + struct ssh_packet_args packet_args;
  8844. +
  8845. + packet_args.type = SSH_PACKET_TY_BLOCKING;
  8846. + if (!(flags & SSAM_REQUEST_UNSEQUENCED))
  8847. + packet_args.type = SSH_PACKET_TY_SEQUENCED;
  8848. +
  8849. + packet_args.priority = SSH_PACKET_PRIORITY(DATA, 0);
  8850. + packet_args.ops = &ssh_rtl_packet_ops;
  8851. +
  8852. + ssh_packet_init(&rqst->packet, &packet_args);
  8853. +
  8854. + rqst->rtl = NULL;
  8855. + INIT_LIST_HEAD(&rqst->node);
  8856. +
  8857. + rqst->state = 0;
  8858. + if (flags & SSAM_REQUEST_HAS_RESPONSE)
  8859. + rqst->state |= BIT(SSH_REQUEST_TY_HAS_RESPONSE_BIT);
  8860. +
  8861. + rqst->timestamp = KTIME_MAX;
  8862. + rqst->ops = ops;
  8863. +}
  8864. +
  8865. +
  8866. +struct ssh_flush_request {
  8867. + struct ssh_request base;
  8868. + struct completion completion;
  8869. + int status;
  8870. +};
  8871. +
  8872. +static void ssh_rtl_flush_request_complete(struct ssh_request *r,
  8873. + const struct ssh_command *cmd,
  8874. + const struct sshp_span *data,
  8875. + int status)
  8876. +{
  8877. + struct ssh_flush_request *rqst;
  8878. +
  8879. + rqst = container_of(r, struct ssh_flush_request, base);
  8880. + rqst->status = status;
  8881. +}
  8882. +
  8883. +static void ssh_rtl_flush_request_release(struct ssh_request *r)
  8884. +{
  8885. + struct ssh_flush_request *rqst;
  8886. +
  8887. + rqst = container_of(r, struct ssh_flush_request, base);
  8888. + complete_all(&rqst->completion);
  8889. +}
  8890. +
  8891. +static const struct ssh_request_ops ssh_rtl_flush_request_ops = {
  8892. + .complete = ssh_rtl_flush_request_complete,
  8893. + .release = ssh_rtl_flush_request_release,
  8894. +};
  8895. +
  8896. +/**
  8897. + * ssh_rtl_flush - flush the request transmission layer
  8898. + * @rtl: request transmission layer
  8899. + * @timeout: timeout for the flush operation in jiffies
  8900. + *
  8901. + * Queue a special flush request and wait for its completion. This request
  8902. + * will be completed after all other currently queued and pending requests
  8903. + * have been completed. Instead of a normal data packet, this request submits
  8904. + * a special flush packet, meaning that upon completion, also the underlying
  8905. + * packet transmission layer has been flushed.
  8906. + *
  8907. + * Flushing the request layer gurarantees that all previously submitted
  8908. + * requests have been fully completed before this call returns. Additinally,
  8909. + * flushing blocks execution of all later submitted requests until the flush
  8910. + * has been completed.
  8911. + *
  8912. + * If the caller ensures that no new requests are submitted after a call to
  8913. + * this function, the request transmission layer is guaranteed to have no
  8914. + * remaining requests when this call returns. The same guarantee does not hold
  8915. + * for the packet layer, on which control packets may still be queued after
  8916. + * this call. See the documentation of ssh_ptl_flush for more details on
  8917. + * packet layer flushing.
  8918. + *
  8919. + * Return: Zero on success, -ETIMEDOUT if the flush timed out and has been
  8920. + * canceled as a result of the timeout, or -ESHUTDOWN if the packet and/or
  8921. + * request transmission layer has been shut down before this call. May also
  8922. + * return -EINTR if the underlying packet transmission has been interrupted.
  8923. + */
  8924. +static int ssh_rtl_flush(struct ssh_rtl *rtl, unsigned long timeout)
  8925. +{
  8926. + const unsigned init_flags = SSAM_REQUEST_UNSEQUENCED;
  8927. + struct ssh_flush_request rqst;
  8928. + int status;
  8929. +
  8930. + ssh_request_init(&rqst.base, init_flags, &ssh_rtl_flush_request_ops);
  8931. + rqst.base.packet.type |= SSH_PACKET_TY_FLUSH;
  8932. + rqst.base.packet.priority = SSH_PACKET_PRIORITY(FLUSH, 0);
  8933. + rqst.base.state |= BIT(SSH_REQUEST_TY_FLUSH_BIT);
  8934. +
  8935. + init_completion(&rqst.completion);
  8936. +
  8937. + status = ssh_rtl_submit(rtl, &rqst.base);
  8938. + if (status)
  8939. + return status;
  8940. +
  8941. + ssh_request_put(&rqst.base);
  8942. +
  8943. + if (wait_for_completion_timeout(&rqst.completion, timeout))
  8944. + return 0;
  8945. +
  8946. + ssh_rtl_cancel(&rqst.base, true);
  8947. + wait_for_completion(&rqst.completion);
  8948. +
  8949. + WARN_ON(rqst.status != 0 && rqst.status != -ECANCELED
  8950. + && rqst.status != -ESHUTDOWN && rqst.status != -EINTR);
  8951. +
  8952. + return rqst.status == -ECANCELED ? -ETIMEDOUT : status;
  8953. +}
  8954. +
  8955. +
  8956. +static void ssh_rtl_shutdown(struct ssh_rtl *rtl)
  8957. +{
  8958. + struct ssh_request *r, *n;
  8959. + LIST_HEAD(claimed);
  8960. + int pending;
  8961. +
  8962. + set_bit(SSH_RTL_SF_SHUTDOWN_BIT, &rtl->state);
  8963. + smp_mb__after_atomic();
  8964. +
  8965. + // remove requests from queue
  8966. + spin_lock(&rtl->queue.lock);
  8967. + list_for_each_entry_safe(r, n, &rtl->queue.head, node) {
  8968. + set_bit(SSH_REQUEST_SF_LOCKED_BIT, &r->state);
  8969. + smp_mb__before_atomic();
  8970. + clear_bit(SSH_REQUEST_SF_QUEUED_BIT, &r->state);
  8971. +
  8972. + list_del(&r->node);
  8973. + list_add_tail(&r->node, &claimed);
  8974. + }
  8975. + spin_unlock(&rtl->queue.lock);
  8976. +
  8977. + /*
  8978. + * We have now guaranteed that the queue is empty and no more new
  8979. + * requests can be submitted (i.e. it will stay empty). This means that
  8980. + * calling ssh_rtl_tx_schedule will not schedule tx.work any more. So we
  8981. + * can simply call cancel_work_sync on tx.work here and when that
  8982. + * returns, we've locked it down. This also means that after this call,
  8983. + * we don't submit any more packets to the underlying packet layer, so
  8984. + * we can also shut that down.
  8985. + */
  8986. +
  8987. + cancel_work_sync(&rtl->tx.work);
  8988. + ssh_ptl_shutdown(&rtl->ptl);
  8989. + cancel_delayed_work_sync(&rtl->rtx_timeout.reaper);
  8990. +
  8991. + /*
  8992. + * Shutting down the packet layer should also have caneled all requests.
  8993. + * Thus the pending set should be empty. Attempt to handle this
  8994. + * gracefully anyways, even though this should be dead code.
  8995. + */
  8996. +
  8997. + pending = atomic_read(&rtl->pending.count);
  8998. + WARN_ON(pending);
  8999. +
  9000. + if (pending) {
  9001. + spin_lock(&rtl->pending.lock);
  9002. + list_for_each_entry_safe(r, n, &rtl->pending.head, node) {
  9003. + set_bit(SSH_REQUEST_SF_LOCKED_BIT, &r->state);
  9004. + smp_mb__before_atomic();
  9005. + clear_bit(SSH_REQUEST_SF_PENDING_BIT, &r->state);
  9006. +
  9007. + list_del(&r->node);
  9008. + list_add_tail(&r->node, &claimed);
  9009. + }
  9010. + spin_unlock(&rtl->pending.lock);
  9011. + }
  9012. +
  9013. + // finally cancel and complete requests
  9014. + list_for_each_entry_safe(r, n, &claimed, node) {
  9015. + // test_and_set because we still might compete with cancellation
  9016. + if (!test_and_set_bit(SSH_REQUEST_SF_COMPLETED_BIT, &r->state))
  9017. + ssh_rtl_complete_with_status(r, -ESHUTDOWN);
  9018. +
  9019. + // drop the reference we've obtained by removing it from list
  9020. + list_del(&r->node);
  9021. + ssh_request_put(r);
  9022. + }
  9023. +}
  9024. +
  9025. +
  9026. +/* -- Event notifier/callbacks. --------------------------------------------- */
  9027. +/*
  9028. + * The notifier system is based on linux/notifier.h, specifically the SRCU
  9029. + * implementation. The difference to that is, that some bits of the notifier
  9030. + * call return value can be tracked accross multiple calls. This is done so that
  9031. + * handling of events can be tracked and a warning can be issued in case an
  9032. + * event goes unhandled. The idea of that waring is that it should help discover
  9033. + * and identify new/currently unimplemented features.
  9034. + */
  9035. +
  9036. +struct ssam_nf_head {
  9037. + struct srcu_struct srcu;
  9038. + struct ssam_notifier_block __rcu *head;
  9039. +};
  9040. +
  9041. +
  9042. +int ssam_nfblk_call_chain(struct ssam_nf_head *nh, struct ssam_event *event)
  9043. +{
  9044. + struct ssam_notifier_block *nb, *next_nb;
  9045. + int ret = 0, idx;
  9046. +
  9047. + idx = srcu_read_lock(&nh->srcu);
  9048. +
  9049. + nb = rcu_dereference_raw(nh->head);
  9050. + while (nb) {
  9051. + next_nb = rcu_dereference_raw(nb->next);
  9052. +
  9053. + ret = (ret & SSAM_NOTIF_STATE_MASK) | nb->fn(nb, event);
  9054. + if (ret & SSAM_NOTIF_STOP)
  9055. + break;
  9056. +
  9057. + nb = next_nb;
  9058. + }
  9059. +
  9060. + srcu_read_unlock(&nh->srcu, idx);
  9061. + return ret;
  9062. +}
  9063. +
  9064. +/*
  9065. + * Note: This function must be synchronized by the caller with respect to other
  9066. + * insert and/or remove calls.
  9067. + */
  9068. +int __ssam_nfblk_insert(struct ssam_nf_head *nh, struct ssam_notifier_block *nb)
  9069. +{
  9070. + struct ssam_notifier_block **link = &nh->head;
  9071. +
  9072. + while ((*link) != NULL) {
  9073. + if (unlikely((*link) == nb)) {
  9074. + WARN(1, "double register detected");
  9075. + return -EINVAL;
  9076. + }
  9077. +
  9078. + if (nb->priority > (*link)->priority)
  9079. + break;
  9080. +
  9081. + link = &((*link)->next);
  9082. + }
  9083. +
  9084. + nb->next = *link;
  9085. + rcu_assign_pointer(*link, nb);
  9086. +
  9087. + return 0;
  9088. +}
  9089. +
  9090. +/*
  9091. + * Note: This function must be synchronized by the caller with respect to other
  9092. + * insert and/or remove calls. On success, the caller _must_ ensure SRCU
  9093. + * synchronization by calling `synchronize_srcu(&nh->srcu)` after leaving the
  9094. + * critical section, to ensure that the removed notifier block is not in use any
  9095. + * more.
  9096. + */
  9097. +int __ssam_nfblk_remove(struct ssam_nf_head *nh, struct ssam_notifier_block *nb)
  9098. +{
  9099. + struct ssam_notifier_block **link = &nh->head;
  9100. +
  9101. + while ((*link) != NULL) {
  9102. + if ((*link) == nb) {
  9103. + rcu_assign_pointer(*link, nb->next);
  9104. + return 0;
  9105. + }
  9106. +
  9107. + link = &((*link)->next);
  9108. + }
  9109. +
  9110. + return -ENOENT;
  9111. +}
  9112. +
  9113. +static int ssam_nf_head_init(struct ssam_nf_head *nh)
  9114. +{
  9115. + int status;
  9116. +
  9117. + status = init_srcu_struct(&nh->srcu);
  9118. + if (status)
  9119. + return status;
  9120. +
  9121. + nh->head = NULL;
  9122. + return 0;
  9123. +}
  9124. +
  9125. +static void ssam_nf_head_destroy(struct ssam_nf_head *nh)
  9126. +{
  9127. + cleanup_srcu_struct(&nh->srcu);
  9128. +}
  9129. +
  9130. +
  9131. +/* -- Event/notification registry. ------------------------------------------ */
  9132. +
  9133. +struct ssam_nf_refcount_key {
  9134. + struct ssam_event_registry reg;
  9135. + struct ssam_event_id id;
  9136. +};
  9137. +
  9138. +struct ssam_nf_refcount_entry {
  9139. + struct rb_node node;
  9140. + struct ssam_nf_refcount_key key;
  9141. + int refcount;
  9142. +};
  9143. +
  9144. +struct ssam_nf {
  9145. + struct mutex lock;
  9146. + struct rb_root refcount;
  9147. + struct ssam_nf_head head[SURFACE_SAM_SSH_NUM_EVENTS];
  9148. +};
  9149. +
  9150. +
  9151. +static int ssam_nf_refcount_inc(struct ssam_nf *nf,
  9152. + struct ssam_event_registry reg,
  9153. + struct ssam_event_id id)
  9154. +{
  9155. + struct ssam_nf_refcount_entry *entry;
  9156. + struct ssam_nf_refcount_key key;
  9157. + struct rb_node **link = &nf->refcount.rb_node;
  9158. + struct rb_node *parent;
  9159. + int cmp;
  9160. +
  9161. + key.reg = reg;
  9162. + key.id = id;
  9163. +
  9164. + while (*link) {
  9165. + entry = rb_entry(*link, struct ssam_nf_refcount_entry, node);
  9166. + parent = *link;
  9167. +
  9168. + cmp = memcmp(&key, &entry->key, sizeof(key));
  9169. + if (cmp < 0) {
  9170. + link = &(*link)->rb_left;
  9171. + } else if (cmp > 0) {
  9172. + link = &(*link)->rb_right;
  9173. + } else if (entry->refcount < INT_MAX) {
  9174. + return ++entry->refcount;
  9175. + } else {
  9176. + return -ENOSPC;
  9177. + }
  9178. + }
  9179. +
  9180. + entry = kzalloc(sizeof(*entry), GFP_KERNEL);
  9181. + if (!entry)
  9182. + return -ENOMEM;
  9183. +
  9184. + entry->key = key;
  9185. + entry->refcount = 1;
  9186. +
  9187. + rb_link_node(&entry->node, parent, link);
  9188. + rb_insert_color(&entry->node, &nf->refcount);
  9189. +
  9190. + return entry->refcount;
  9191. +}
  9192. +
  9193. +static int ssam_nf_refcount_dec(struct ssam_nf *nf,
  9194. + struct ssam_event_registry reg,
  9195. + struct ssam_event_id id)
  9196. +{
  9197. + struct ssam_nf_refcount_entry *entry;
  9198. + struct ssam_nf_refcount_key key;
  9199. + struct rb_node *node = nf->refcount.rb_node;
  9200. + int cmp, rc;
  9201. +
  9202. + key.reg = reg;
  9203. + key.id = id;
  9204. +
  9205. + while (node) {
  9206. + entry = rb_entry(node, struct ssam_nf_refcount_entry, node);
  9207. +
  9208. + cmp = memcmp(&key, &entry->key, sizeof(key));
  9209. + if (cmp < 0) {
  9210. + node = node->rb_left;
  9211. + } else if (cmp > 0) {
  9212. + node = node->rb_right;
  9213. + } else {
  9214. + rc = --entry->refcount;
  9215. +
  9216. + if (rc == 0) {
  9217. + rb_erase(&entry->node, &nf->refcount);
  9218. + kfree(entry);
  9219. + }
  9220. +
  9221. + return rc;
  9222. + }
  9223. + }
  9224. +
  9225. + return -ENOENT;
  9226. +}
  9227. +
  9228. +static void ssam_nf_call(struct ssam_nf *nf, struct device *dev, u16 rqid,
  9229. + struct ssam_event *event)
  9230. +{
  9231. + struct ssam_nf_head *nf_head;
  9232. + int status, nf_ret;
  9233. +
  9234. + if (!ssh_rqid_is_event(rqid)) {
  9235. + dev_warn(dev, "event: unsupported rqid: 0x%04x\n", rqid);
  9236. + return;
  9237. + }
  9238. +
  9239. + nf_head = &nf->head[ssh_rqid_to_event(rqid)];
  9240. + nf_ret = ssam_nfblk_call_chain(nf_head, event);
  9241. + status = ssam_notifier_to_errno(nf_ret);
  9242. +
  9243. + if (status < 0) {
  9244. + dev_err(dev, "event: error handling event: %d "
  9245. + "(tc: 0x%02x, cid: 0x%02x, iid: 0x%02x, chn: 0x%02x)\n",
  9246. + status, event->target_category, event->command_id,
  9247. + event->instance_id, event->channel);
  9248. + }
  9249. +
  9250. + if (!(nf_ret & SSAM_NOTIF_HANDLED)) {
  9251. + dev_warn(dev, "event: unhandled event (rqid: 0x%02x, "
  9252. + "tc: 0x%02x, cid: 0x%02x, iid: 0x%02x, chn: 0x%02x)\n",
  9253. + rqid, event->target_category, event->command_id,
  9254. + event->instance_id, event->channel);
  9255. + }
  9256. +}
  9257. +
  9258. +static int ssam_nf_register(struct ssam_nf *nf, struct ssam_event_notifier *n)
  9259. +{
  9260. + u16 rqid = ssh_tc_to_rqid(n->event.id.target_category);
  9261. + struct ssam_nf_head *nf_head;
  9262. + int rc, status;
  9263. +
  9264. + if (!ssh_rqid_is_event(rqid))
  9265. + return -EINVAL;
  9266. +
  9267. + nf_head = &nf->head[ssh_rqid_to_event(rqid)];
  9268. +
  9269. + mutex_lock(&nf->lock);
  9270. +
  9271. + rc = ssam_nf_refcount_inc(nf, n->event.reg, n->event.id);
  9272. + if (rc < 0) {
  9273. + mutex_lock(&nf->lock);
  9274. + return rc;
  9275. + }
  9276. +
  9277. + status = __ssam_nfblk_insert(nf_head, &n->base);
  9278. + if (status)
  9279. + ssam_nf_refcount_dec(nf, n->event.reg, n->event.id);
  9280. +
  9281. + mutex_unlock(&nf->lock);
  9282. + return status;
  9283. +}
  9284. +
  9285. +static int ssam_nf_unregister(struct ssam_nf *nf, struct ssam_event_notifier *n)
  9286. +{
  9287. + u16 rqid = ssh_tc_to_rqid(n->event.id.target_category);
  9288. + struct ssam_nf_head *nf_head;
  9289. + int status;
  9290. +
  9291. + if (!ssh_rqid_is_event(rqid))
  9292. + return -EINVAL;
  9293. +
  9294. + nf_head = &nf->head[ssh_rqid_to_event(rqid)];
  9295. +
  9296. + mutex_lock(&nf->lock);
  9297. +
  9298. + status = __ssam_nfblk_remove(nf_head, &n->base);
  9299. + if (status) {
  9300. + mutex_unlock(&nf->lock);
  9301. + return status;
  9302. + }
  9303. +
  9304. + ssam_nf_refcount_dec(nf, n->event.reg, n->event.id);
  9305. +
  9306. + mutex_unlock(&nf->lock);
  9307. + synchronize_srcu(&nf_head->srcu);
  9308. +
  9309. + return 0;
  9310. +}
  9311. +
  9312. +static int ssam_nf_init(struct ssam_nf *nf)
  9313. +{
  9314. + int i, status;
  9315. +
  9316. + for (i = 0; i < SURFACE_SAM_SSH_NUM_EVENTS; i++) {
  9317. + status = ssam_nf_head_init(&nf->head[i]);
  9318. + if (status)
  9319. + break;
  9320. + }
  9321. +
  9322. + if (status) {
  9323. + for (i = i - 1; i >= 0; i--)
  9324. + ssam_nf_head_destroy(&nf->head[i]);
  9325. +
  9326. + return status;
  9327. + }
  9328. +
  9329. + mutex_init(&nf->lock);
  9330. + return 0;
  9331. +}
  9332. +
  9333. +static void ssam_nf_destroy(struct ssam_nf *nf)
  9334. +{
  9335. + int i;
  9336. +
  9337. + for (i = 0; i < SURFACE_SAM_SSH_NUM_EVENTS; i++)
  9338. + ssam_nf_head_destroy(&nf->head[i]);
  9339. +
  9340. + mutex_destroy(&nf->lock);
  9341. +}
  9342. +
  9343. +
  9344. +/* -- Event/async request completion system. -------------------------------- */
  9345. +
  9346. +#define SSAM_CPLT_WQ_NAME "ssam_cpltq"
  9347. +
  9348. +
  9349. +struct ssam_cplt;
  9350. +
  9351. +struct ssam_event_item {
  9352. + struct list_head node;
  9353. + u16 rqid;
  9354. + struct ssam_event event; // must be last
  9355. +};
  9356. +
  9357. +struct ssam_event_queue {
  9358. + struct ssam_cplt *cplt;
  9359. +
  9360. + spinlock_t lock;
  9361. + struct list_head head;
  9362. + struct work_struct work;
  9363. +};
  9364. +
  9365. +struct ssam_event_channel {
  9366. + struct ssam_event_queue queue[SURFACE_SAM_SSH_NUM_EVENTS];
  9367. +};
  9368. +
  9369. +struct ssam_cplt {
  9370. + struct device *dev;
  9371. + struct workqueue_struct *wq;
  9372. +
  9373. + struct {
  9374. + struct ssam_event_channel channel[SURFACE_SAM_SSH_NUM_CHANNELS];
  9375. + struct ssam_nf notif;
  9376. + } event;
  9377. +};
  9378. +
  9379. +
  9380. +static void ssam_event_queue_push(struct ssam_event_queue *q,
  9381. + struct ssam_event_item *item)
  9382. +{
  9383. + spin_lock(&q->lock);
  9384. + list_add_tail(&item->node, &q->head);
  9385. + spin_unlock(&q->lock);
  9386. +}
  9387. +
  9388. +static struct ssam_event_item *ssam_event_queue_pop(struct ssam_event_queue *q)
  9389. +{
  9390. + struct ssam_event_item *item;
  9391. +
  9392. + spin_lock(&q->lock);
  9393. + item = list_first_entry_or_null(&q->head, struct ssam_event_item, node);
  9394. + if (item)
  9395. + list_del(&item->node);
  9396. + spin_unlock(&q->lock);
  9397. +
  9398. + return item;
  9399. +}
  9400. +
  9401. +static bool ssam_event_queue_is_empty(struct ssam_event_queue *q)
  9402. +{
  9403. + bool empty;
  9404. +
  9405. + spin_lock(&q->lock);
  9406. + empty = list_empty(&q->head);
  9407. + spin_unlock(&q->lock);
  9408. +
  9409. + return empty;
  9410. +}
  9411. +
  9412. +static struct ssam_event_queue *ssam_cplt_get_event_queue(
  9413. + struct ssam_cplt *cplt, u8 channel, u16 rqid)
  9414. +{
  9415. + u16 event = ssh_rqid_to_event(rqid);
  9416. + u16 chidx = ssh_channel_to_index(channel);
  9417. +
  9418. + if (!ssh_rqid_is_event(rqid)) {
  9419. + dev_err(cplt->dev, "event: unsupported rqid: 0x%04x\n", rqid);
  9420. + return NULL;
  9421. + }
  9422. +
  9423. + if (!ssh_channel_is_valid(channel)) {
  9424. + dev_warn(cplt->dev, "event: unsupported channel: %u\n",
  9425. + channel);
  9426. + chidx = 0;
  9427. + }
  9428. +
  9429. + return &cplt->event.channel[chidx].queue[event];
  9430. +}
  9431. +
  9432. +static inline bool ssam_cplt_submit(struct ssam_cplt *cplt,
  9433. + struct work_struct *work)
  9434. +{
  9435. + return queue_work(cplt->wq, work);
  9436. +}
  9437. +
  9438. +static int ssam_cplt_submit_event(struct ssam_cplt *cplt,
  9439. + struct ssam_event_item *item)
  9440. +{
  9441. + struct ssam_event_queue *evq;
  9442. +
  9443. + evq = ssam_cplt_get_event_queue(cplt, item->event.channel, item->rqid);
  9444. + if (!evq)
  9445. + return -EINVAL;
  9446. +
  9447. + ssam_event_queue_push(evq, item);
  9448. + ssam_cplt_submit(cplt, &evq->work);
  9449. + return 0;
  9450. +}
  9451. +
  9452. +static void ssam_cplt_flush(struct ssam_cplt *cplt)
  9453. +{
  9454. + flush_workqueue(cplt->wq);
  9455. +}
  9456. +
  9457. +static void ssam_event_queue_work_fn(struct work_struct *work)
  9458. +{
  9459. + struct ssam_event_queue *queue;
  9460. + struct ssam_event_item *item;
  9461. + struct ssam_nf *nf;
  9462. + struct device *dev;
  9463. + int i;
  9464. +
  9465. + queue = container_of(work, struct ssam_event_queue, work);
  9466. + nf = &queue->cplt->event.notif;
  9467. + dev = queue->cplt->dev;
  9468. +
  9469. + for (i = 0; i < 10; i++) {
  9470. + item = ssam_event_queue_pop(queue);
  9471. + if (item == NULL)
  9472. + return;
  9473. +
  9474. + ssam_nf_call(nf, dev, item->rqid, &item->event);
  9475. + kfree(item);
  9476. + }
  9477. +
  9478. + if (!ssam_event_queue_is_empty(queue))
  9479. + ssam_cplt_submit(queue->cplt, &queue->work);
  9480. +}
  9481. +
  9482. +static void ssam_event_queue_init(struct ssam_cplt *cplt,
  9483. + struct ssam_event_queue *evq)
  9484. +{
  9485. + evq->cplt = cplt;
  9486. + spin_lock_init(&evq->lock);
  9487. + INIT_LIST_HEAD(&evq->head);
  9488. + INIT_WORK(&evq->work, ssam_event_queue_work_fn);
  9489. +}
  9490. +
  9491. +static int ssam_cplt_init(struct ssam_cplt *cplt, struct device *dev)
  9492. +{
  9493. + struct ssam_event_channel *channel;
  9494. + int status, c, i;
  9495. +
  9496. + cplt->dev = dev;
  9497. +
  9498. + cplt->wq = create_workqueue(SSAM_CPLT_WQ_NAME);
  9499. + if (!cplt->wq)
  9500. + return -ENOMEM;
  9501. +
  9502. + for (c = 0; c < ARRAY_SIZE(cplt->event.channel); c++) {
  9503. + channel = &cplt->event.channel[c];
  9504. +
  9505. + for (i = 0; i < ARRAY_SIZE(channel->queue); i++)
  9506. + ssam_event_queue_init(cplt, &channel->queue[i]);
  9507. + }
  9508. +
  9509. + status = ssam_nf_init(&cplt->event.notif);
  9510. + if (status)
  9511. + destroy_workqueue(cplt->wq);
  9512. +
  9513. + return status;
  9514. +}
  9515. +
  9516. +static void ssam_cplt_destroy(struct ssam_cplt *cplt)
  9517. +{
  9518. + destroy_workqueue(cplt->wq);
  9519. + ssam_nf_destroy(&cplt->event.notif);
  9520. +}
  9521. +
  9522. +
  9523. +/* -- Top-Level Request Interface ------------------------------------------- */
  9524. +
  9525. +struct ssam_response {
  9526. + int status;
  9527. + u16 capacity;
  9528. + u16 length;
  9529. + u8 *pointer;
  9530. +};
  9531. +
  9532. +struct ssam_request_sync {
  9533. + struct ssh_request base;
  9534. + struct completion comp;
  9535. + struct ssam_response resp;
  9536. +};
  9537. +
  9538. +
  9539. +static void ssam_request_sync_complete(struct ssh_request *rqst,
  9540. + const struct ssh_command *cmd,
  9541. + const struct sshp_span *data, int status)
  9542. +{
  9543. + struct ssam_request_sync *r;
  9544. + struct ssh_rtl *rtl = READ_ONCE(rqst->rtl);
  9545. +
  9546. + r = container_of(rqst, struct ssam_request_sync, base);
  9547. + r->resp.status = status;
  9548. + r->resp.length = 0;
  9549. +
  9550. + if (status) {
  9551. + rtl_dbg_cond(rtl, "rsp: request failed: %d\n", status);
  9552. + return;
  9553. + }
  9554. +
  9555. + if (!data) // handle requests without a response
  9556. + return;
  9557. +
  9558. + if (!r->resp.pointer && data->len) {
  9559. + rtl_warn(rtl, "rsp: no response buffer provided, dropping data\n");
  9560. + return;
  9561. + }
  9562. +
  9563. + if (data->len > r->resp.capacity) {
  9564. + rtl_err(rtl, "rsp: response buffer too small,"
  9565. + " capacity: %u bytes, got: %zu bytes\n",
  9566. + r->resp.capacity, data->len);
  9567. + r->resp.status = -ENOSPC;
  9568. + return;
  9569. + }
  9570. +
  9571. + r->resp.length = data->len;
  9572. + memcpy(r->resp.pointer, data->ptr, data->len);
  9573. +}
  9574. +
  9575. +static void ssam_request_sync_release(struct ssh_request *rqst)
  9576. +{
  9577. + complete_all(&container_of(rqst, struct ssam_request_sync, base)->comp);
  9578. +}
  9579. +
  9580. +static const struct ssh_request_ops ssam_request_sync_ops = {
  9581. + .release = ssam_request_sync_release,
  9582. + .complete = ssam_request_sync_complete,
  9583. +};
  9584. +
  9585. +static void ssam_request_sync_wait_complete(struct ssam_request_sync *rqst)
  9586. +{
  9587. + wait_for_completion(&rqst->comp);
  9588. +}
  9589. +
  9590. +
  9591. +/* -- TODO ------------------------------------------------------------------ */
  9592. +
  9593. +enum ssh_ec_state {
  9594. + SSH_EC_UNINITIALIZED,
  9595. + SSH_EC_INITIALIZED,
  9596. + SSH_EC_SUSPENDED,
  9597. +};
  9598. +
  9599. +struct sam_ssh_ec {
  9600. + struct serdev_device *serdev;
  9601. +
  9602. + struct ssh_rtl rtl;
  9603. + struct ssam_cplt cplt;
  9604. +
  9605. + struct {
  9606. + struct ssh_seq_counter seq;
  9607. + struct ssh_rqid_counter rqid;
  9608. + } counter;
  9609. +
  9610. + enum ssh_ec_state state;
  9611. +
  9612. + int irq;
  9613. + bool irq_wakeup_enabled;
  9614. +};
  9615. +
  9616. +static struct sam_ssh_ec ssh_ec = {
  9617. + .state = SSH_EC_UNINITIALIZED,
  9618. + .serdev = NULL,
  9619. +};
  9620. +
  9621. +
  9622. +/* -- TODO ------------------------------------------------------------------ */
  9623. +
  9624. +#define ssh_dbg(ec, fmt, ...) dev_dbg(&(ec)->serdev->dev, fmt, ##__VA_ARGS__)
  9625. +#define ssh_warn(ec, fmt, ...) dev_warn(&(ec)->serdev->dev, fmt, ##__VA_ARGS__)
  9626. +#define ssh_err(ec, fmt, ...) dev_err(&(ec)->serdev->dev, fmt, ##__VA_ARGS__)
  9627. +
  9628. +
  9629. +static inline struct sam_ssh_ec *surface_sam_ssh_acquire(void)
  9630. +{
  9631. + return &ssh_ec;
  9632. +}
  9633. +
  9634. +static inline struct sam_ssh_ec *surface_sam_ssh_acquire_init(void)
  9635. +{
  9636. + struct sam_ssh_ec *ec = surface_sam_ssh_acquire();
  9637. +
  9638. + if (smp_load_acquire(&ec->state) == SSH_EC_UNINITIALIZED)
  9639. + return NULL;
  9640. +
  9641. + return ec;
  9642. +}
  9643. +
  9644. +int surface_sam_ssh_consumer_register(struct device *consumer)
  9645. +{
  9646. + u32 flags = DL_FLAG_PM_RUNTIME | DL_FLAG_AUTOREMOVE_CONSUMER;
  9647. + struct sam_ssh_ec *ec;
  9648. + struct device_link *link;
  9649. +
  9650. + ec = surface_sam_ssh_acquire_init();
  9651. + if (!ec)
  9652. + return -ENXIO;
  9653. +
  9654. + link = device_link_add(consumer, &ec->serdev->dev, flags);
  9655. + if (!link)
  9656. + return -EFAULT;
  9657. +
  9658. + return 0;
  9659. +}
  9660. +EXPORT_SYMBOL_GPL(surface_sam_ssh_consumer_register);
  9661. +
  9662. +
  9663. +static int __surface_sam_ssh_rqst(struct sam_ssh_ec *ec,
  9664. + const struct surface_sam_ssh_rqst *rqst,
  9665. + struct surface_sam_ssh_buf *result);
  9666. +
  9667. +static int surface_sam_ssh_event_enable(struct sam_ssh_ec *ec,
  9668. + struct ssam_event_registry reg,
  9669. + struct ssam_event_id id,
  9670. + u8 flags)
  9671. +{
  9672. + struct ssh_notification_params params;
  9673. + struct surface_sam_ssh_rqst rqst;
  9674. + struct surface_sam_ssh_buf result;
  9675. +
  9676. + u16 rqid = ssh_tc_to_rqid(id.target_category);
  9677. + u8 buf[1] = { 0x00 };
  9678. + int status;
  9679. +
  9680. + // only allow RQIDs that lie within event spectrum
  9681. + if (!ssh_rqid_is_event(rqid))
  9682. + return -EINVAL;
  9683. +
  9684. + params.target_category = id.target_category;
  9685. + params.instance_id = id.instance;
  9686. + params.flags = flags;
  9687. + put_unaligned_le16(rqid, &params.request_id);
  9688. +
  9689. + rqst.tc = reg.target_category;
  9690. + rqst.cid = reg.cid_enable;
  9691. + rqst.iid = 0x00;
  9692. + rqst.chn = reg.channel;
  9693. + rqst.snc = 0x01;
  9694. + rqst.cdl = sizeof(params);
  9695. + rqst.pld = (u8 *)&params;
  9696. +
  9697. + result.cap = ARRAY_SIZE(buf);
  9698. + result.len = 0;
  9699. + result.data = buf;
  9700. +
  9701. + status = __surface_sam_ssh_rqst(ec, &rqst, &result);
  9702. +
  9703. + if (status) {
  9704. + dev_err(&ec->serdev->dev, "failed to enable event source"
  9705. + " (tc: 0x%02x, rqid: 0x%04x)\n",
  9706. + id.target_category, rqid);
  9707. + }
  9708. +
  9709. + if (buf[0] != 0x00) {
  9710. + pr_warn(SSH_RQST_TAG_FULL
  9711. + "unexpected result while enabling event source: "
  9712. + "0x%02x\n", buf[0]);
  9713. + }
  9714. +
  9715. + return status;
  9716. +
  9717. +}
  9718. +
  9719. +static int surface_sam_ssh_event_disable(struct sam_ssh_ec *ec,
  9720. + struct ssam_event_registry reg,
  9721. + struct ssam_event_id id,
  9722. + u8 flags)
  9723. +{
  9724. + struct ssh_notification_params params;
  9725. + struct surface_sam_ssh_rqst rqst;
  9726. + struct surface_sam_ssh_buf result;
  9727. +
  9728. + u16 rqid = ssh_tc_to_rqid(id.target_category);
  9729. + u8 buf[1] = { 0x00 };
  9730. + int status;
  9731. +
  9732. + // only allow RQIDs that lie within event spectrum
  9733. + if (!ssh_rqid_is_event(rqid))
  9734. + return -EINVAL;
  9735. +
  9736. + params.target_category = id.target_category;
  9737. + params.instance_id = id.instance;
  9738. + params.flags = flags;
  9739. + put_unaligned_le16(rqid, &params.request_id);
  9740. +
  9741. + rqst.tc = reg.target_category;
  9742. + rqst.cid = reg.cid_disable;
  9743. + rqst.iid = 0x00;
  9744. + rqst.chn = reg.channel;
  9745. + rqst.snc = 0x01;
  9746. + rqst.cdl = sizeof(params);
  9747. + rqst.pld = (u8 *)&params;
  9748. +
  9749. + result.cap = ARRAY_SIZE(buf);
  9750. + result.len = 0;
  9751. + result.data = buf;
  9752. +
  9753. + status = __surface_sam_ssh_rqst(ec, &rqst, &result);
  9754. +
  9755. + if (status) {
  9756. + dev_err(&ec->serdev->dev, "failed to disable event source"
  9757. + " (tc: 0x%02x, rqid: 0x%04x)\n",
  9758. + id.target_category, rqid);
  9759. + }
  9760. +
  9761. + if (buf[0] != 0x00) {
  9762. + dev_warn(&ec->serdev->dev,
  9763. + "unexpected result while disabling event source: "
  9764. + "0x%02x\n", buf[0]);
  9765. + }
  9766. +
  9767. + return status;
  9768. +}
  9769. +
  9770. +
  9771. +int surface_sam_ssh_notifier_register(struct ssam_event_notifier *n)
  9772. +{
  9773. + struct ssam_nf_head *nf_head;
  9774. + struct sam_ssh_ec *ec;
  9775. + struct ssam_nf *nf;
  9776. + u16 event = ssh_tc_to_event(n->event.id.target_category);
  9777. + u16 rqid = ssh_event_to_rqid(event);
  9778. + int rc, status;
  9779. +
  9780. + if (!ssh_rqid_is_event(rqid))
  9781. + return -EINVAL;
  9782. +
  9783. + ec = surface_sam_ssh_acquire_init();
  9784. + if (!ec)
  9785. + return -ENXIO;
  9786. +
  9787. + nf = &ec->cplt.event.notif;
  9788. + nf_head = &nf->head[event];
  9789. +
  9790. + mutex_lock(&nf->lock);
  9791. +
  9792. + rc = ssam_nf_refcount_inc(nf, n->event.reg, n->event.id);
  9793. + if (rc < 0) {
  9794. + mutex_unlock(&nf->lock);
  9795. + return rc;
  9796. + }
  9797. +
  9798. + ssh_dbg(ec, "enabling event (tc: 0x%02x, rc: %d)\n", rqid, rc);
  9799. +
  9800. + status = __ssam_nfblk_insert(nf_head, &n->base);
  9801. + if (status) {
  9802. + ssam_nf_refcount_dec(nf, n->event.reg, n->event.id);
  9803. + mutex_unlock(&nf->lock);
  9804. + return status;
  9805. + }
  9806. +
  9807. + if (rc == 1) {
  9808. + status = surface_sam_ssh_event_enable(ec, n->event.reg, n->event.id, n->event.flags);
  9809. + if (status) {
  9810. + __ssam_nfblk_remove(nf_head, &n->base);
  9811. + ssam_nf_refcount_dec(nf, n->event.reg, n->event.id);
  9812. + mutex_unlock(&nf->lock);
  9813. + return status;
  9814. + }
  9815. + }
  9816. +
  9817. + mutex_unlock(&nf->lock);
  9818. + return 0;
  9819. +}
  9820. +EXPORT_SYMBOL_GPL(surface_sam_ssh_notifier_register);
  9821. +
  9822. +int surface_sam_ssh_notifier_unregister(struct ssam_event_notifier *n)
  9823. +{
  9824. + struct ssam_nf_head *nf_head;
  9825. + struct sam_ssh_ec *ec;
  9826. + struct ssam_nf *nf;
  9827. + u16 event = ssh_tc_to_event(n->event.id.target_category);
  9828. + u16 rqid = ssh_event_to_rqid(event);
  9829. + int rc, status = 0;
  9830. +
  9831. + if (!ssh_rqid_is_event(rqid))
  9832. + return -EINVAL;
  9833. +
  9834. + ec = surface_sam_ssh_acquire_init();
  9835. + if (!ec)
  9836. + return -ENXIO;
  9837. +
  9838. + nf = &ec->cplt.event.notif;
  9839. + nf_head = &nf->head[event];
  9840. +
  9841. + mutex_lock(&nf->lock);
  9842. +
  9843. + rc = ssam_nf_refcount_dec(nf, n->event.reg, n->event.id);
  9844. + if (rc < 0) {
  9845. + mutex_unlock(&nf->lock);
  9846. + return rc;
  9847. + }
  9848. +
  9849. + ssh_dbg(ec, "disabling event (tc: 0x%02x, rc: %d)\n", rqid, rc);
  9850. +
  9851. + if (rc == 0)
  9852. + status = surface_sam_ssh_event_disable(ec, n->event.reg, n->event.id, n->event.flags);
  9853. +
  9854. + __ssam_nfblk_remove(nf_head, &n->base);
  9855. + mutex_unlock(&nf->lock);
  9856. + synchronize_srcu(&nf_head->srcu);
  9857. +
  9858. + return status;
  9859. +}
  9860. +EXPORT_SYMBOL_GPL(surface_sam_ssh_notifier_unregister);
  9861. +
  9862. +
  9863. +static int __surface_sam_ssh_rqst(struct sam_ssh_ec *ec,
  9864. + const struct surface_sam_ssh_rqst *rqst,
  9865. + struct surface_sam_ssh_buf *result)
  9866. +{
  9867. + struct ssam_request_sync actual;
  9868. + struct msgbuf msgb;
  9869. + size_t msglen = SSH_COMMAND_MESSAGE_LENGTH(rqst->cdl);
  9870. + unsigned flags = 0;
  9871. + u16 rqid;
  9872. + u8 seq;
  9873. + int status;
  9874. +
  9875. + // prevent overflow
  9876. + if (rqst->cdl > SSH_COMMAND_MAX_PAYLOAD_SIZE) {
  9877. + ssh_err(ec, SSH_RQST_TAG "request payload too large\n");
  9878. + return -EINVAL;
  9879. + }
  9880. +
  9881. + if (result && result->data && rqst->snc)
  9882. + flags |= SSAM_REQUEST_HAS_RESPONSE;
  9883. +
  9884. + ssh_request_init(&actual.base, flags, &ssam_request_sync_ops);
  9885. + init_completion(&actual.comp);
  9886. +
  9887. + actual.resp.pointer = NULL;
  9888. + actual.resp.capacity = 0;
  9889. + actual.resp.length = 0;
  9890. + actual.resp.status = 0;
  9891. +
  9892. + if (result) {
  9893. + actual.resp.pointer = result->data;
  9894. + actual.resp.capacity = result->cap;
  9895. + }
  9896. +
  9897. + // alloc and create message
  9898. + status = msgb_alloc(&msgb, msglen, GFP_KERNEL);
  9899. + if (status)
  9900. + return status;
  9901. +
  9902. + seq = ssh_seq_next(&ec->counter.seq);
  9903. + rqid = ssh_rqid_next(&ec->counter.rqid);
  9904. + msgb_push_cmd(&msgb, seq, rqst, rqid);
  9905. +
  9906. + actual.base.packet.data = msgb.buffer;
  9907. + actual.base.packet.data_length = msgb.ptr - msgb.buffer;
  9908. +
  9909. + status = ssh_rtl_submit(&ec->rtl, &actual.base);
  9910. + if (status) {
  9911. + msgb_free(&msgb);
  9912. + return status;
  9913. + }
  9914. +
  9915. + ssh_request_put(&actual.base);
  9916. + ssam_request_sync_wait_complete(&actual);
  9917. + msgb_free(&msgb);
  9918. +
  9919. + if (result)
  9920. + result->len = actual.resp.length;
  9921. +
  9922. + return actual.resp.status;
  9923. +}
  9924. +
  9925. +int surface_sam_ssh_rqst(const struct surface_sam_ssh_rqst *rqst, struct surface_sam_ssh_buf *result)
  9926. +{
  9927. + struct sam_ssh_ec *ec;
  9928. +
  9929. + ec = surface_sam_ssh_acquire_init();
  9930. + if (!ec) {
  9931. + pr_warn(SSH_RQST_TAG_FULL "embedded controller is uninitialized\n");
  9932. + return -ENXIO;
  9933. + }
  9934. +
  9935. + if (smp_load_acquire(&ec->state) == SSH_EC_SUSPENDED) {
  9936. + ssh_warn(ec, SSH_RQST_TAG "embedded controller is suspended\n");
  9937. + return -EPERM;
  9938. + }
  9939. +
  9940. + return __surface_sam_ssh_rqst(ec, rqst, result);
  9941. +}
  9942. +EXPORT_SYMBOL_GPL(surface_sam_ssh_rqst);
  9943. +
  9944. +
  9945. +/**
  9946. + * surface_sam_ssh_ec_resume - Resume the EC if it is in a suspended mode.
  9947. + * @ec: the EC to resume
  9948. + *
  9949. + * Moves the EC from a suspended state to a normal state. See the
  9950. + * `surface_sam_ssh_ec_suspend` function what the specific differences of
  9951. + * these states are. Multiple repeated calls to this function seem to be
  9952. + * handled fine by the EC, after the first call, the state will remain
  9953. + * "normal".
  9954. + *
  9955. + * Must be called with the EC initialized and its lock held.
  9956. + */
  9957. +static int surface_sam_ssh_ec_resume(struct sam_ssh_ec *ec)
  9958. +{
  9959. + u8 buf[1] = { 0x00 };
  9960. + int status;
  9961. +
  9962. + struct surface_sam_ssh_rqst rqst = {
  9963. + .tc = 0x01,
  9964. + .cid = 0x16,
  9965. + .iid = 0x00,
  9966. + .chn = 0x01,
  9967. + .snc = 0x01,
  9968. + .cdl = 0x00,
  9969. + .pld = NULL,
  9970. + };
  9971. +
  9972. + struct surface_sam_ssh_buf result = {
  9973. + result.cap = ARRAY_SIZE(buf),
  9974. + result.len = 0,
  9975. + result.data = buf,
  9976. + };
  9977. +
  9978. + ssh_dbg(ec, "pm: resuming system aggregator module\n");
  9979. + status = __surface_sam_ssh_rqst(ec, &rqst, &result);
  9980. + if (status)
  9981. + return status;
  9982. +
  9983. + /*
  9984. + * The purpose of the return value of this request is unknown. Based on
  9985. + * logging and experience, we expect it to be zero. No other value has
  9986. + * been observed so far.
  9987. + */
  9988. + if (buf[0] != 0x00) {
  9989. + ssh_warn(ec, "unexpected result while trying to resume EC: "
  9990. + "0x%02x\n", buf[0]);
  9991. + }
  9992. +
  9993. + return 0;
  9994. +}
  9995. +
  9996. +/**
  9997. + * surface_sam_ssh_ec_suspend - Put the EC in a suspended mode:
  9998. + * @ec: the EC to suspend
  9999. + *
  10000. + * Tells the EC to enter a suspended mode. In this mode, events are quiesced
  10001. + * and the wake IRQ is armed (note that the wake IRQ does not fire if the EC
  10002. + * has not been suspended via this request). On some devices, the keyboard
  10003. + * backlight is turned off. Apart from this, the EC seems to continue to work
  10004. + * as normal, meaning requests sent to it are acknowledged and seem to be
  10005. + * correctly handled, including potential responses. Multiple repeated calls
  10006. + * to this function seem to be handled fine by the EC, after the first call,
  10007. + * the state will remain "suspended".
  10008. + *
  10009. + * Must be called with the EC initialized and its lock held.
  10010. + */
  10011. +static int surface_sam_ssh_ec_suspend(struct sam_ssh_ec *ec)
  10012. +{
  10013. + u8 buf[1] = { 0x00 };
  10014. + int status;
  10015. +
  10016. + struct surface_sam_ssh_rqst rqst = {
  10017. + .tc = 0x01,
  10018. + .cid = 0x15,
  10019. + .iid = 0x00,
  10020. + .chn = 0x01,
  10021. + .snc = 0x01,
  10022. + .cdl = 0x00,
  10023. + .pld = NULL,
  10024. + };
  10025. +
  10026. + struct surface_sam_ssh_buf result = {
  10027. + result.cap = ARRAY_SIZE(buf),
  10028. + result.len = 0,
  10029. + result.data = buf,
  10030. + };
  10031. +
  10032. + ssh_dbg(ec, "pm: suspending system aggregator module\n");
  10033. + status = __surface_sam_ssh_rqst(ec, &rqst, &result);
  10034. + if (status)
  10035. + return status;
  10036. +
  10037. + /*
  10038. + * The purpose of the return value of this request is unknown. Based on
  10039. + * logging and experience, we expect it to be zero. No other value has
  10040. + * been observed so far.
  10041. + */
  10042. + if (buf[0] != 0x00) {
  10043. + ssh_warn(ec, "unexpected result while trying to suspend EC: "
  10044. + "0x%02x\n", buf[0]);
  10045. + }
  10046. +
  10047. + return 0;
  10048. +}
  10049. +
  10050. +
  10051. +static int surface_sam_ssh_get_controller_version(struct sam_ssh_ec *ec, u32 *version)
  10052. +{
  10053. + struct surface_sam_ssh_rqst rqst = {
  10054. + .tc = 0x01,
  10055. + .cid = 0x13,
  10056. + .iid = 0x00,
  10057. + .chn = 0x01,
  10058. + .snc = 0x01,
  10059. + .cdl = 0x00,
  10060. + .pld = NULL,
  10061. + };
  10062. +
  10063. + struct surface_sam_ssh_buf result = {
  10064. + result.cap = sizeof(*version),
  10065. + result.len = 0,
  10066. + result.data = (u8 *)version,
  10067. + };
  10068. +
  10069. + *version = 0;
  10070. + return __surface_sam_ssh_rqst(ec, &rqst, &result);
  10071. +}
  10072. +
  10073. +static int surface_sam_ssh_log_controller_version(struct sam_ssh_ec *ec)
  10074. +{
  10075. + u32 version, a, b, c;
  10076. + int status;
  10077. +
  10078. + status = surface_sam_ssh_get_controller_version(ec, &version);
  10079. + if (status)
  10080. + return status;
  10081. +
  10082. + a = (version >> 24) & 0xff;
  10083. + b = le16_to_cpu((version >> 8) & 0xffff);
  10084. + c = version & 0xff;
  10085. +
  10086. + dev_info(&ec->serdev->dev, "SAM controller version: %u.%u.%u\n",
  10087. + a, b, c);
  10088. + return 0;
  10089. +}
  10090. +
  10091. +
  10092. +static const struct acpi_gpio_params gpio_ssh_wakeup_int = { 0, 0, false };
  10093. +static const struct acpi_gpio_params gpio_ssh_wakeup = { 1, 0, false };
  10094. +
  10095. +static const struct acpi_gpio_mapping ssh_acpi_gpios[] = {
  10096. + { "ssh_wakeup-int-gpio", &gpio_ssh_wakeup_int, 1 },
  10097. + { "ssh_wakeup-gpio", &gpio_ssh_wakeup, 1 },
  10098. + { },
  10099. +};
  10100. +
  10101. +static irqreturn_t ssh_wake_irq_handler(int irq, void *dev_id)
  10102. +{
  10103. + struct serdev_device *serdev = dev_id;
  10104. +
  10105. + dev_dbg(&serdev->dev, "pm: wake irq triggered\n");
  10106. +
  10107. + // TODO: Send GPIO callback command repeatedly to EC until callback
  10108. + // returns 0x00. Return flag of callback is "has more events".
  10109. + // Each time the command is sent, one event is "released". Once
  10110. + // all events have been released (return = 0x00), the GPIO is
  10111. + // re-armed.
  10112. +
  10113. + return IRQ_HANDLED;
  10114. +}
  10115. +
  10116. +static int ssh_setup_irq(struct serdev_device *serdev)
  10117. +{
  10118. + const int irqf = IRQF_SHARED | IRQF_ONESHOT | IRQF_TRIGGER_RISING;
  10119. + struct gpio_desc *gpiod;
  10120. + int irq;
  10121. + int status;
  10122. +
  10123. + gpiod = gpiod_get(&serdev->dev, "ssh_wakeup-int", GPIOD_ASIS);
  10124. + if (IS_ERR(gpiod))
  10125. + return PTR_ERR(gpiod);
  10126. +
  10127. + irq = gpiod_to_irq(gpiod);
  10128. + gpiod_put(gpiod);
  10129. +
  10130. + if (irq < 0)
  10131. + return irq;
  10132. +
  10133. + status = request_threaded_irq(irq, NULL, ssh_wake_irq_handler,
  10134. + irqf, "surface_sam_sh_wakeup", serdev);
  10135. + if (status)
  10136. + return status;
  10137. +
  10138. + return irq;
  10139. +}
  10140. +
  10141. +
  10142. +static acpi_status ssh_setup_from_resource(struct acpi_resource *rsc, void *ctx)
  10143. +{
  10144. + struct serdev_device *serdev = ctx;
  10145. + struct acpi_resource_common_serialbus *serial;
  10146. + struct acpi_resource_uart_serialbus *uart;
  10147. + bool flow_control;
  10148. + int status = 0;
  10149. +
  10150. + if (rsc->type != ACPI_RESOURCE_TYPE_SERIAL_BUS)
  10151. + return AE_OK;
  10152. +
  10153. + serial = &rsc->data.common_serial_bus;
  10154. + if (serial->type != ACPI_RESOURCE_SERIAL_TYPE_UART)
  10155. + return AE_OK;
  10156. +
  10157. + uart = &rsc->data.uart_serial_bus;
  10158. +
  10159. + // set up serdev device
  10160. + serdev_device_set_baudrate(serdev, uart->default_baud_rate);
  10161. +
  10162. + // serdev currently only supports RTSCTS flow control
  10163. + if (uart->flow_control & SSH_SUPPORTED_FLOW_CONTROL_MASK) {
  10164. + dev_warn(&serdev->dev, "setup: unsupported flow control"
  10165. + " (value: 0x%02x)\n", uart->flow_control);
  10166. + }
  10167. +
  10168. + // set RTSCTS flow control
  10169. + flow_control = uart->flow_control & ACPI_UART_FLOW_CONTROL_HW;
  10170. + serdev_device_set_flow_control(serdev, flow_control);
  10171. +
  10172. + // serdev currently only supports EVEN/ODD parity
  10173. + switch (uart->parity) {
  10174. + case ACPI_UART_PARITY_NONE:
  10175. + status = serdev_device_set_parity(serdev, SERDEV_PARITY_NONE);
  10176. + break;
  10177. + case ACPI_UART_PARITY_EVEN:
  10178. + status = serdev_device_set_parity(serdev, SERDEV_PARITY_EVEN);
  10179. + break;
  10180. + case ACPI_UART_PARITY_ODD:
  10181. + status = serdev_device_set_parity(serdev, SERDEV_PARITY_ODD);
  10182. + break;
  10183. + default:
  10184. + dev_warn(&serdev->dev, "setup: unsupported parity"
  10185. + " (value: 0x%02x)\n", uart->parity);
  10186. + break;
  10187. + }
  10188. +
  10189. + if (status) {
  10190. + dev_err(&serdev->dev, "setup: failed to set parity"
  10191. + " (value: 0x%02x)\n", uart->parity);
  10192. + return status;
  10193. + }
  10194. +
  10195. + return AE_CTRL_TERMINATE; // we've found the resource and are done
  10196. +}
  10197. +
  10198. +
  10199. +static int surface_sam_ssh_suspend(struct device *dev)
  10200. +{
  10201. + struct sam_ssh_ec *ec;
  10202. + int status;
  10203. +
  10204. + dev_dbg(dev, "pm: suspending\n");
  10205. +
  10206. + ec = surface_sam_ssh_acquire_init();
  10207. + if (ec) {
  10208. + status = surface_sam_ssh_ec_suspend(ec);
  10209. + if (status)
  10210. + return status;
  10211. +
  10212. + if (device_may_wakeup(dev)) {
  10213. + status = enable_irq_wake(ec->irq);
  10214. + if (status)
  10215. + return status;
  10216. +
  10217. + ec->irq_wakeup_enabled = true;
  10218. + } else {
  10219. + ec->irq_wakeup_enabled = false;
  10220. + }
  10221. +
  10222. + smp_store_release(&ec->state, SSH_EC_SUSPENDED);
  10223. + }
  10224. +
  10225. + return 0;
  10226. +}
  10227. +
  10228. +static int surface_sam_ssh_resume(struct device *dev)
  10229. +{
  10230. + struct sam_ssh_ec *ec;
  10231. + int status;
  10232. +
  10233. + dev_dbg(dev, "pm: resuming\n");
  10234. +
  10235. + ec = surface_sam_ssh_acquire_init();
  10236. + if (ec) {
  10237. + smp_store_release(&ec->state, SSH_EC_INITIALIZED);
  10238. +
  10239. + if (ec->irq_wakeup_enabled) {
  10240. + status = disable_irq_wake(ec->irq);
  10241. + if (status)
  10242. + return status;
  10243. +
  10244. + ec->irq_wakeup_enabled = false;
  10245. + }
  10246. +
  10247. + status = surface_sam_ssh_ec_resume(ec);
  10248. + if (status)
  10249. + return status;
  10250. + }
  10251. +
  10252. + return 0;
  10253. +}
  10254. +
  10255. +static SIMPLE_DEV_PM_OPS(surface_sam_ssh_pm_ops, surface_sam_ssh_suspend,
  10256. + surface_sam_ssh_resume);
  10257. +
  10258. +
  10259. +static void ssam_handle_event(struct ssh_rtl *rtl,
  10260. + const struct ssh_command *cmd,
  10261. + const struct sshp_span *data)
  10262. +{
  10263. + struct sam_ssh_ec *ec = container_of(rtl, struct sam_ssh_ec, rtl);
  10264. + struct ssam_event_item *item;
  10265. +
  10266. + item = kzalloc(sizeof(struct ssam_event_item) + data->len, GFP_KERNEL);
  10267. + if (!item)
  10268. + return;
  10269. +
  10270. + item->rqid = get_unaligned_le16(&cmd->rqid);
  10271. + item->event.target_category = cmd->tc;
  10272. + item->event.command_id = cmd->cid;
  10273. + item->event.instance_id = cmd->iid;
  10274. + item->event.channel = cmd->chn_in;
  10275. + item->event.length = data->len;
  10276. + memcpy(&item->event.data[0], data->ptr, data->len);
  10277. +
  10278. + ssam_cplt_submit_event(&ec->cplt, item);
  10279. +}
  10280. +
  10281. +static struct ssh_rtl_ops ssam_rtl_ops = {
  10282. + .handle_event = ssam_handle_event,
  10283. +};
  10284. +
  10285. +
  10286. +static int ssam_receive_buf(struct serdev_device *dev, const unsigned char *buf, size_t n)
  10287. +{
  10288. + struct sam_ssh_ec *ec = serdev_device_get_drvdata(dev);
  10289. + return ssh_ptl_rx_rcvbuf(&ec->rtl.ptl, buf, n);
  10290. +}
  10291. +
  10292. +static void ssam_write_wakeup(struct serdev_device *dev)
  10293. +{
  10294. + struct sam_ssh_ec *ec = serdev_device_get_drvdata(dev);
  10295. + ssh_ptl_tx_wakeup(&ec->rtl.ptl, true);
  10296. +}
  10297. +
  10298. +struct serdev_device_ops ssam_serdev_ops = {
  10299. + .receive_buf = ssam_receive_buf,
  10300. + .write_wakeup = ssam_write_wakeup,
  10301. +};
  10302. +
  10303. +
  10304. +#ifdef CONFIG_SURFACE_SAM_SSH_DEBUG_DEVICE
  10305. +
  10306. +static char sam_ssh_debug_rqst_buf_sysfs[256] = { 0 };
  10307. +static char sam_ssh_debug_rqst_buf_pld[255] = { 0 };
  10308. +static char sam_ssh_debug_rqst_buf_res[255] = { 0 };
  10309. +
  10310. +struct sysfs_rqst {
  10311. + u8 tc;
  10312. + u8 cid;
  10313. + u8 iid;
  10314. + u8 chn;
  10315. + u8 snc;
  10316. + u8 cdl;
  10317. + u8 pld[0];
  10318. +} __packed;
  10319. +
  10320. +static ssize_t rqst_read(struct file *f, struct kobject *kobj, struct bin_attribute *attr,
  10321. + char *buf, loff_t offs, size_t count)
  10322. +{
  10323. + if (offs < 0 || count + offs > ARRAY_SIZE(sam_ssh_debug_rqst_buf_sysfs))
  10324. + return -EINVAL;
  10325. +
  10326. + memcpy(buf, sam_ssh_debug_rqst_buf_sysfs + offs, count);
  10327. + return count;
  10328. +}
  10329. +
  10330. +static ssize_t rqst_write(struct file *f, struct kobject *kobj, struct bin_attribute *attr,
  10331. + char *buf, loff_t offs, size_t count)
  10332. +{
  10333. + struct sysfs_rqst *input;
  10334. + struct surface_sam_ssh_rqst rqst = {};
  10335. + struct surface_sam_ssh_buf result = {};
  10336. + int status;
  10337. +
  10338. + // check basic write constriants
  10339. + if (offs != 0 || count - sizeof(struct sysfs_rqst) > ARRAY_SIZE(sam_ssh_debug_rqst_buf_pld))
  10340. + return -EINVAL;
  10341. +
  10342. + if (count < sizeof(struct sysfs_rqst))
  10343. + return -EINVAL;
  10344. +
  10345. + input = (struct sysfs_rqst *)buf;
  10346. +
  10347. + // payload length should be consistent with data provided
  10348. + if (input->cdl + sizeof(struct sysfs_rqst) != count)
  10349. + return -EINVAL;
  10350. +
  10351. + rqst.tc = input->tc;
  10352. + rqst.cid = input->cid;
  10353. + rqst.iid = input->iid;
  10354. + rqst.chn = input->chn;
  10355. + rqst.snc = input->snc;
  10356. + rqst.cdl = input->cdl;
  10357. + rqst.pld = sam_ssh_debug_rqst_buf_pld;
  10358. + memcpy(sam_ssh_debug_rqst_buf_pld, &input->pld[0], input->cdl);
  10359. +
  10360. + result.cap = ARRAY_SIZE(sam_ssh_debug_rqst_buf_res);
  10361. + result.len = 0;
  10362. + result.data = sam_ssh_debug_rqst_buf_res;
  10363. +
  10364. + status = surface_sam_ssh_rqst(&rqst, &result);
  10365. + if (status)
  10366. + return status;
  10367. +
  10368. + sam_ssh_debug_rqst_buf_sysfs[0] = result.len;
  10369. + memcpy(sam_ssh_debug_rqst_buf_sysfs + 1, result.data, result.len);
  10370. + memset(sam_ssh_debug_rqst_buf_sysfs + result.len + 1, 0,
  10371. + ARRAY_SIZE(sam_ssh_debug_rqst_buf_sysfs) + 1 - result.len);
  10372. +
  10373. + return count;
  10374. +}
  10375. +
  10376. +static const BIN_ATTR_RW(rqst, ARRAY_SIZE(sam_ssh_debug_rqst_buf_sysfs));
  10377. +
  10378. +static int surface_sam_ssh_sysfs_register(struct device *dev)
  10379. +{
  10380. + return sysfs_create_bin_file(&dev->kobj, &bin_attr_rqst);
  10381. +}
  10382. +
  10383. +static void surface_sam_ssh_sysfs_unregister(struct device *dev)
  10384. +{
  10385. + sysfs_remove_bin_file(&dev->kobj, &bin_attr_rqst);
  10386. +}
  10387. +
  10388. +#else /* CONFIG_SURFACE_SAM_SSH_DEBUG_DEVICE */
  10389. +
  10390. +static int surface_sam_ssh_sysfs_register(struct device *dev)
  10391. +{
  10392. + return 0;
  10393. +}
  10394. +
  10395. +static void surface_sam_ssh_sysfs_unregister(struct device *dev)
  10396. +{
  10397. +}
  10398. +
  10399. +#endif /* CONFIG_SURFACE_SAM_SSH_DEBUG_DEVICE */
  10400. +
  10401. +
  10402. +static int surface_sam_ssh_probe(struct serdev_device *serdev)
  10403. +{
  10404. + struct sam_ssh_ec *ec;
  10405. + acpi_handle *ssh = ACPI_HANDLE(&serdev->dev);
  10406. + int status, irq;
  10407. +
  10408. + if (gpiod_count(&serdev->dev, NULL) < 0)
  10409. + return -ENODEV;
  10410. +
  10411. + status = devm_acpi_dev_add_driver_gpios(&serdev->dev, ssh_acpi_gpios);
  10412. + if (status)
  10413. + return status;
  10414. +
  10415. + // setup IRQ
  10416. + irq = ssh_setup_irq(serdev);
  10417. + if (irq < 0)
  10418. + return irq;
  10419. +
  10420. + // set up EC
  10421. + ec = surface_sam_ssh_acquire();
  10422. + if (smp_load_acquire(&ec->state) != SSH_EC_UNINITIALIZED) {
  10423. + dev_err(&serdev->dev, "embedded controller already initialized\n");
  10424. +
  10425. + status = -EBUSY;
  10426. + goto err_ecinit;
  10427. + }
  10428. +
  10429. + ec->serdev = serdev;
  10430. + ec->irq = irq;
  10431. + ssh_seq_reset(&ec->counter.seq);
  10432. + ssh_rqid_reset(&ec->counter.rqid);
  10433. +
  10434. + // initialize event/request completion system
  10435. + status = ssam_cplt_init(&ec->cplt, &serdev->dev);
  10436. + if (status)
  10437. + goto err_ecinit;
  10438. +
  10439. + // initialize request and packet transmission layers
  10440. + status = ssh_rtl_init(&ec->rtl, serdev, &ssam_rtl_ops);
  10441. + if (status)
  10442. + goto err_rtl;
  10443. +
  10444. + serdev_device_set_drvdata(serdev, ec);
  10445. +
  10446. + serdev_device_set_client_ops(serdev, &ssam_serdev_ops);
  10447. + status = serdev_device_open(serdev);
  10448. + if (status)
  10449. + goto err_open;
  10450. +
  10451. + status = acpi_walk_resources(ssh, METHOD_NAME__CRS,
  10452. + ssh_setup_from_resource, serdev);
  10453. + if (ACPI_FAILURE(status))
  10454. + goto err_devinit;
  10455. +
  10456. + status = ssh_rtl_tx_start(&ec->rtl);
  10457. + if (status)
  10458. + goto err_devinit;
  10459. +
  10460. + status = ssh_rtl_rx_start(&ec->rtl);
  10461. + if (status)
  10462. + goto err_devinit;
  10463. +
  10464. + smp_store_release(&ec->state, SSH_EC_INITIALIZED);
  10465. +
  10466. + status = surface_sam_ssh_log_controller_version(ec);
  10467. + if (status)
  10468. + goto err_finalize;
  10469. +
  10470. + status = surface_sam_ssh_ec_resume(ec);
  10471. + if (status)
  10472. + goto err_finalize;
  10473. +
  10474. + status = surface_sam_ssh_sysfs_register(&serdev->dev);
  10475. + if (status)
  10476. + goto err_finalize;
  10477. +
  10478. + // TODO: The EC can wake up the system via the associated GPIO interrupt in
  10479. + // multiple situations. One of which is the remaining battery capacity
  10480. + // falling below a certain threshold. Normally, we should use the
  10481. + // device_init_wakeup function, however, the EC also seems to have other
  10482. + // reasons for waking up the system and it seems that Windows has
  10483. + // additional checks whether the system should be resumed. In short, this
  10484. + // causes some spourious unwanted wake-ups. For now let's thus default
  10485. + // power/wakeup to false.
  10486. + device_set_wakeup_capable(&serdev->dev, true);
  10487. + acpi_walk_dep_device_list(ssh);
  10488. +
  10489. + return 0;
  10490. +
  10491. +err_finalize:
  10492. + smp_store_release(&ec->state, SSH_EC_UNINITIALIZED);
  10493. + ssh_rtl_flush(&ec->rtl, msecs_to_jiffies(5000));
  10494. +err_devinit:
  10495. + serdev_device_close(serdev);
  10496. +err_open:
  10497. + ssh_rtl_shutdown(&ec->rtl);
  10498. + ssh_rtl_destroy(&ec->rtl);
  10499. +err_rtl:
  10500. + ssam_cplt_flush(&ec->cplt);
  10501. + ssam_cplt_destroy(&ec->cplt);
  10502. +err_ecinit:
  10503. + free_irq(irq, serdev);
  10504. + serdev_device_set_drvdata(serdev, NULL);
  10505. + return status;
  10506. +}
  10507. +
  10508. +static void surface_sam_ssh_remove(struct serdev_device *serdev)
  10509. +{
  10510. + struct sam_ssh_ec *ec;
  10511. + int status;
  10512. +
  10513. + ec = surface_sam_ssh_acquire_init();
  10514. + if (!ec)
  10515. + return;
  10516. +
  10517. + free_irq(ec->irq, serdev);
  10518. + surface_sam_ssh_sysfs_unregister(&serdev->dev);
  10519. +
  10520. + // suspend EC and disable events
  10521. + status = surface_sam_ssh_ec_suspend(ec);
  10522. + if (status)
  10523. + dev_err(&serdev->dev, "failed to suspend EC: %d\n", status);
  10524. +
  10525. + // flush pending events and requests while everything still works
  10526. + status = ssh_rtl_flush(&ec->rtl, msecs_to_jiffies(5000));
  10527. + if (status)
  10528. + dev_err(&serdev->dev, "failed to flush request transmission layer: %d\n", status);
  10529. +
  10530. + ssam_cplt_flush(&ec->cplt);
  10531. +
  10532. + // mark device as uninitialized
  10533. + smp_store_release(&ec->state, SSH_EC_UNINITIALIZED);
  10534. +
  10535. + // cancel rem. requests, ensure no new ones can be queued, stop threads
  10536. + ssh_rtl_tx_flush(&ec->rtl);
  10537. + ssh_rtl_shutdown(&ec->rtl);
  10538. +
  10539. + // shut down actual transport
  10540. + serdev_device_wait_until_sent(ec->serdev, 0);
  10541. + serdev_device_close(ec->serdev);
  10542. +
  10543. + /*
  10544. + * Ensure _all_ events are completed. New ones could still have been
  10545. + * received after the last flush, before the request transport layer
  10546. + * has been shut down. At this point we can be sure that no requests
  10547. + * will remain after this call.
  10548. + */
  10549. + ssam_cplt_flush(&ec->cplt);
  10550. +
  10551. + // actually free resources
  10552. + ssam_cplt_destroy(&ec->cplt);
  10553. + ssh_rtl_destroy(&ec->rtl);
  10554. +
  10555. + ec->serdev = NULL;
  10556. + ec->irq = -1;
  10557. +
  10558. + device_set_wakeup_capable(&serdev->dev, false);
  10559. + serdev_device_set_drvdata(serdev, NULL);
  10560. +}
  10561. +
  10562. +
  10563. +static const struct acpi_device_id surface_sam_ssh_match[] = {
  10564. + { "MSHW0084", 0 },
  10565. + { },
  10566. +};
  10567. +MODULE_DEVICE_TABLE(acpi, surface_sam_ssh_match);
  10568. +
  10569. +static struct serdev_device_driver surface_sam_ssh = {
  10570. + .probe = surface_sam_ssh_probe,
  10571. + .remove = surface_sam_ssh_remove,
  10572. + .driver = {
  10573. + .name = "surface_sam_ssh",
  10574. + .acpi_match_table = surface_sam_ssh_match,
  10575. + .pm = &surface_sam_ssh_pm_ops,
  10576. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  10577. + },
  10578. +};
  10579. +
  10580. +
  10581. +static int __init surface_sam_ssh_init(void)
  10582. +{
  10583. + return serdev_device_driver_register(&surface_sam_ssh);
  10584. +}
  10585. +
  10586. +static void __exit surface_sam_ssh_exit(void)
  10587. +{
  10588. + serdev_device_driver_unregister(&surface_sam_ssh);
  10589. +}
  10590. +
  10591. +/*
  10592. + * Ensure that the driver is loaded late due to some issues with the UART
  10593. + * communication. Specifically, we want to ensure that DMA is ready and being
  10594. + * used. Not using DMA can result in spurious communication failures,
  10595. + * especially during boot, which among other things will result in wrong
  10596. + * battery information (via ACPI _BIX) being displayed. Using a late init_call
  10597. + * instead of the normal module_init gives the DMA subsystem time to
  10598. + * initialize and via that results in a more stable communication, avoiding
  10599. + * such failures.
  10600. + */
  10601. +late_initcall(surface_sam_ssh_init);
  10602. +module_exit(surface_sam_ssh_exit);
  10603. +
  10604. +MODULE_AUTHOR("Maximilian Luz <luzmaximilian@gmail.com>");
  10605. +MODULE_DESCRIPTION("Surface Serial Hub Driver for 5th Generation Surface Devices");
  10606. +MODULE_LICENSE("GPL");
  10607. diff --git a/drivers/platform/x86/surface_sam/surface_sam_ssh.h b/drivers/platform/x86/surface_sam/surface_sam_ssh.h
  10608. new file mode 100644
  10609. index 0000000000000..25a3ae85fee7f
  10610. --- /dev/null
  10611. +++ b/drivers/platform/x86/surface_sam/surface_sam_ssh.h
  10612. @@ -0,0 +1,488 @@
  10613. +/* SPDX-License-Identifier: GPL-2.0-or-later */
  10614. +/*
  10615. + * Interface for Surface Serial Hub (SSH).
  10616. + *
  10617. + * The SSH is the main communication hub for communication between host and
  10618. + * the Surface/System Aggregator Module (SAM) on newer Microsoft Surface
  10619. + * devices (Book 2, Pro 5, Laptops, ...). Also referred to as SAM-over-SSH.
  10620. + * Older devices (Book 1, Pro 4) use SAM-over-HID (via I2C).
  10621. + */
  10622. +
  10623. +#ifndef _SURFACE_SAM_SSH_H
  10624. +#define _SURFACE_SAM_SSH_H
  10625. +
  10626. +#include <linux/types.h>
  10627. +#include <linux/device.h>
  10628. +
  10629. +
  10630. +/* -- Data structures for SAM-over-SSH communication. ----------------------- */
  10631. +
  10632. +/**
  10633. + * enum ssh_frame_type - Frame types for SSH frames.
  10634. + * @SSH_FRAME_TYPE_DATA_SEQ: Indicates a data frame, followed by a payload with
  10635. + * the length specified in the ssh_frame.len field. This
  10636. + * frame is sequenced, meaning that an ACK is required.
  10637. + * @SSH_FRAME_TYPE_DATA_NSQ: Same as SSH_FRAME_TYPE_DATA_SEQ, but unsequenced,
  10638. + * meaning that the message does not have to be ACKed.
  10639. + * @SSH_FRAME_TYPE_ACK: Indicates an ACK message.
  10640. + * @SSH_FRAME_TYPE_NAK: Indicates an error response for previously sent
  10641. + * frame. In general, this means that the frame and/or
  10642. + * payload is malformed, e.g. a CRC is wrong. For command-
  10643. + * type payloads, this can also mean that the command is
  10644. + * invalid.
  10645. + */
  10646. +enum ssh_frame_type {
  10647. + SSH_FRAME_TYPE_DATA_SEQ = 0x80,
  10648. + SSH_FRAME_TYPE_DATA_NSQ = 0x00,
  10649. + SSH_FRAME_TYPE_ACK = 0x40,
  10650. + SSH_FRAME_TYPE_NAK = 0x04,
  10651. +};
  10652. +
  10653. +/**
  10654. + * struct ssh_frame - SSH communication frame.
  10655. + * @type: The type of the frame. See &enum ssh_frame_type.
  10656. + * @len: The length of the frame payload directly following the CRC for this
  10657. + * frame. Does not include the final CRC for that payload.
  10658. + * @seq: The sequence number for this message/exchange.
  10659. + */
  10660. +struct ssh_frame {
  10661. + u8 type;
  10662. + __le16 len;
  10663. + u8 seq;
  10664. +} __packed;
  10665. +
  10666. +static_assert(sizeof(struct ssh_frame) == 4);
  10667. +
  10668. +/*
  10669. + * Maximum SSH frame payload length in bytes. This is the physical maximum
  10670. + * length of the protocol. Implementations may set a more constrained limit.
  10671. + */
  10672. +#define SSH_FRAME_MAX_PAYLOAD_SIZE U16_MAX
  10673. +
  10674. +/**
  10675. + * enum ssh_payload_type - Type indicator for the SSH payload.
  10676. + * @SSH_PLD_TYPE_CMD: The payload is a command structure with optional command
  10677. + * payload.
  10678. + */
  10679. +enum ssh_payload_type {
  10680. + SSH_PLD_TYPE_CMD = 0x80,
  10681. +};
  10682. +
  10683. +/**
  10684. + * struct ssh_command - Payload of a command-type frame.
  10685. + * @type: The type of the payload. See &enum ssh_payload_type. Should be
  10686. + * SSH_PLD_TYPE_CMD for this struct.
  10687. + * @tc: Command target category.
  10688. + * @chn_out: Output channel. Should be zero if this an incoming (EC to host)
  10689. + * message.
  10690. + * @chn_in: Input channel. Should be zero if this is an outgoing (hos to EC)
  10691. + * message.
  10692. + * @iid: Instance ID.
  10693. + * @rqid: Request ID. Used to match requests with responses and differentiate
  10694. + * between responses and events.
  10695. + * @cid: Command ID.
  10696. + */
  10697. +struct ssh_command {
  10698. + u8 type;
  10699. + u8 tc;
  10700. + u8 chn_out;
  10701. + u8 chn_in;
  10702. + u8 iid;
  10703. + __le16 rqid;
  10704. + u8 cid;
  10705. +} __packed;
  10706. +
  10707. +static_assert(sizeof(struct ssh_command) == 8);
  10708. +
  10709. +/*
  10710. + * Maximum SSH command payload length in bytes. This is the physical maximum
  10711. + * length of the protocol. Implementations may set a more constrained limit.
  10712. + */
  10713. +#define SSH_COMMAND_MAX_PAYLOAD_SIZE \
  10714. + (SSH_FRAME_MAX_PAYLOAD_SIZE - sizeof(struct ssh_command))
  10715. +
  10716. +/**
  10717. + * struct ssh_notification_params - Command payload to enable/disable SSH
  10718. + * notifications.
  10719. + * @target_category: The target category for which notifications should be
  10720. + * enabled/disabled.
  10721. + * @flags: Flags determining how notifications are being sent.
  10722. + * @request_id: The request ID that is used to send these notifications.
  10723. + * @instance_id: The specific instance in the given target category for
  10724. + * which notifications should be enabled.
  10725. + */
  10726. +struct ssh_notification_params {
  10727. + u8 target_category;
  10728. + u8 flags;
  10729. + __le16 request_id;
  10730. + u8 instance_id;
  10731. +} __packed;
  10732. +
  10733. +static_assert(sizeof(struct ssh_notification_params) == 5);
  10734. +
  10735. +/**
  10736. + * SSH message syncrhonization (SYN) bytes.
  10737. + */
  10738. +#define SSH_MSG_SYN ((u16)0x55aa)
  10739. +
  10740. +/**
  10741. + * Base-length of a SSH message. This is the minimum number of bytes required
  10742. + * to form a message. The actual message length is SSH_MSG_LEN_BASE plus the
  10743. + * length of the frame payload.
  10744. + */
  10745. +#define SSH_MSG_LEN_BASE (sizeof(struct ssh_frame) + 3ull * sizeof(u16))
  10746. +
  10747. +/**
  10748. + * Length of a SSH control message.
  10749. + */
  10750. +#define SSH_MSG_LEN_CTRL SSH_MSG_LEN_BASE
  10751. +
  10752. +/**
  10753. + * Length of a SSH message with payload of specified size.
  10754. + */
  10755. +#define SSH_MESSAGE_LENGTH(payload_size) (SSH_MSG_LEN_BASE + payload_size)
  10756. +
  10757. +/**
  10758. + * Length of a SSH command message with command payload of specified size.
  10759. + */
  10760. +#define SSH_COMMAND_MESSAGE_LENGTH(payload_size) \
  10761. + SSH_MESSAGE_LENGTH(sizeof(struct ssh_command) + payload_size)
  10762. +
  10763. +/**
  10764. + * Offset of the specified struct ssh_frame field in the raw SSH message data.
  10765. + */
  10766. +#define SSH_MSGOFFSET_FRAME(field) \
  10767. + (sizeof(u16) + offsetof(struct ssh_frame, field))
  10768. +
  10769. +/**
  10770. + * Offset of the specified struct ssh_command field in the raw SSH message data.
  10771. + */
  10772. +#define SSH_MSGOFFSET_COMMAND(field) \
  10773. + (2ull * sizeof(u16) + sizeof(struct ssh_frame) \
  10774. + + offsetof(struct ssh_command, field))
  10775. +
  10776. +struct sshp_span {
  10777. + u8 *ptr;
  10778. + size_t len;
  10779. +};
  10780. +
  10781. +
  10782. +/* -- Packet transport layer (ptl). ----------------------------------------- */
  10783. +
  10784. +enum ssh_packet_priority {
  10785. + SSH_PACKET_PRIORITY_FLUSH = 0,
  10786. + SSH_PACKET_PRIORITY_DATA = 0,
  10787. + SSH_PACKET_PRIORITY_NAK = 1 << 4,
  10788. + SSH_PACKET_PRIORITY_ACK = 2 << 4,
  10789. +};
  10790. +
  10791. +#define SSH_PACKET_PRIORITY(base, try) \
  10792. + ((SSH_PACKET_PRIORITY_##base) | ((try) & 0x0f))
  10793. +
  10794. +#define ssh_packet_priority_get_try(p) ((p) & 0x0f)
  10795. +
  10796. +
  10797. +enum ssh_packet_type_flags {
  10798. + SSH_PACKET_TY_FLUSH_BIT,
  10799. + SSH_PACKET_TY_SEQUENCED_BIT,
  10800. + SSH_PACKET_TY_BLOCKING_BIT,
  10801. +
  10802. + SSH_PACKET_TY_FLUSH = BIT(SSH_PACKET_TY_FLUSH_BIT),
  10803. + SSH_PACKET_TY_SEQUENCED = BIT(SSH_PACKET_TY_SEQUENCED_BIT),
  10804. + SSH_PACKET_TY_BLOCKING = BIT(SSH_PACKET_TY_BLOCKING_BIT),
  10805. +};
  10806. +
  10807. +enum ssh_packet_state_flags {
  10808. + SSH_PACKET_SF_LOCKED_BIT,
  10809. + SSH_PACKET_SF_QUEUED_BIT,
  10810. + SSH_PACKET_SF_PENDING_BIT,
  10811. + SSH_PACKET_SF_TRANSMITTING_BIT,
  10812. + SSH_PACKET_SF_TRANSMITTED_BIT,
  10813. + SSH_PACKET_SF_ACKED_BIT,
  10814. + SSH_PACKET_SF_CANCELED_BIT,
  10815. + SSH_PACKET_SF_COMPLETED_BIT,
  10816. +};
  10817. +
  10818. +
  10819. +struct ssh_ptl;
  10820. +struct ssh_packet;
  10821. +
  10822. +struct ssh_packet_ops {
  10823. + void (*release)(struct ssh_packet *packet);
  10824. + void (*complete)(struct ssh_packet *packet, int status);
  10825. +};
  10826. +
  10827. +struct ssh_packet {
  10828. + struct ssh_ptl *ptl;
  10829. + struct kref refcnt;
  10830. +
  10831. + u8 type;
  10832. + u8 priority;
  10833. + u16 data_length;
  10834. + u8 *data;
  10835. +
  10836. + unsigned long state;
  10837. + ktime_t timestamp;
  10838. +
  10839. + struct list_head queue_node;
  10840. + struct list_head pending_node;
  10841. +
  10842. + const struct ssh_packet_ops *ops;
  10843. +};
  10844. +
  10845. +
  10846. +/* -- Request transport layer (rtl). ---------------------------------------- */
  10847. +
  10848. +enum ssh_request_flags {
  10849. + SSH_REQUEST_SF_LOCKED_BIT,
  10850. + SSH_REQUEST_SF_QUEUED_BIT,
  10851. + SSH_REQUEST_SF_PENDING_BIT,
  10852. + SSH_REQUEST_SF_TRANSMITTING_BIT,
  10853. + SSH_REQUEST_SF_TRANSMITTED_BIT,
  10854. + SSH_REQUEST_SF_RSPRCVD_BIT,
  10855. + SSH_REQUEST_SF_CANCELED_BIT,
  10856. + SSH_REQUEST_SF_COMPLETED_BIT,
  10857. +
  10858. + SSH_REQUEST_TY_FLUSH_BIT,
  10859. + SSH_REQUEST_TY_HAS_RESPONSE_BIT,
  10860. +
  10861. + SSH_REQUEST_FLAGS_SF_MASK =
  10862. + BIT(SSH_REQUEST_SF_LOCKED_BIT)
  10863. + | BIT(SSH_REQUEST_SF_QUEUED_BIT)
  10864. + | BIT(SSH_REQUEST_SF_PENDING_BIT)
  10865. + | BIT(SSH_REQUEST_SF_TRANSMITTING_BIT)
  10866. + | BIT(SSH_REQUEST_SF_TRANSMITTED_BIT)
  10867. + | BIT(SSH_REQUEST_SF_RSPRCVD_BIT)
  10868. + | BIT(SSH_REQUEST_SF_CANCELED_BIT)
  10869. + | BIT(SSH_REQUEST_SF_COMPLETED_BIT),
  10870. +
  10871. + SSH_REQUEST_FLAGS_TY_MASK =
  10872. + BIT(SSH_REQUEST_TY_FLUSH_BIT)
  10873. + | BIT(SSH_REQUEST_TY_HAS_RESPONSE_BIT),
  10874. +};
  10875. +
  10876. +
  10877. +struct ssh_rtl;
  10878. +struct ssh_request;
  10879. +
  10880. +struct ssh_request_ops {
  10881. + void (*release)(struct ssh_request *rqst);
  10882. + void (*complete)(struct ssh_request *rqst,
  10883. + const struct ssh_command *cmd,
  10884. + const struct sshp_span *data, int status);
  10885. +};
  10886. +
  10887. +struct ssh_request {
  10888. + struct ssh_rtl *rtl;
  10889. + struct ssh_packet packet;
  10890. + struct list_head node;
  10891. +
  10892. + unsigned long state;
  10893. + ktime_t timestamp;
  10894. +
  10895. + const struct ssh_request_ops *ops;
  10896. +};
  10897. +
  10898. +
  10899. +/* -- Main data types and definitions --------------------------------------- */
  10900. +
  10901. +enum ssam_ssh_tc {
  10902. + SSAM_SSH_TC_SAM = 0x01, // generic system functionality, real-time clock
  10903. + SSAM_SSH_TC_BAT = 0x02, // battery/power subsystem
  10904. + SSAM_SSH_TC_TMP = 0x03, // thermal subsystem
  10905. + SSAM_SSH_TC_PMC = 0x04,
  10906. + SSAM_SSH_TC_FAN = 0x05,
  10907. + SSAM_SSH_TC_PoM = 0x06,
  10908. + SSAM_SSH_TC_DBG = 0x07,
  10909. + SSAM_SSH_TC_KBD = 0x08, // legacy keyboard (Laptop 1/2)
  10910. + SSAM_SSH_TC_FWU = 0x09,
  10911. + SSAM_SSH_TC_UNI = 0x0a,
  10912. + SSAM_SSH_TC_LPC = 0x0b,
  10913. + SSAM_SSH_TC_TCL = 0x0c,
  10914. + SSAM_SSH_TC_SFL = 0x0d,
  10915. + SSAM_SSH_TC_KIP = 0x0e,
  10916. + SSAM_SSH_TC_EXT = 0x0f,
  10917. + SSAM_SSH_TC_BLD = 0x10,
  10918. + SSAM_SSH_TC_BAS = 0x11, // detachment system (Surface Book 2/3)
  10919. + SSAM_SSH_TC_SEN = 0x12,
  10920. + SSAM_SSH_TC_SRQ = 0x13,
  10921. + SSAM_SSH_TC_MCU = 0x14,
  10922. + SSAM_SSH_TC_HID = 0x15, // generic HID input subsystem
  10923. + SSAM_SSH_TC_TCH = 0x16,
  10924. + SSAM_SSH_TC_BKL = 0x17,
  10925. + SSAM_SSH_TC_TAM = 0x18,
  10926. + SSAM_SSH_TC_ACC = 0x19,
  10927. + SSAM_SSH_TC_UFI = 0x1a,
  10928. + SSAM_SSH_TC_USC = 0x1b,
  10929. + SSAM_SSH_TC_PEN = 0x1c,
  10930. + SSAM_SSH_TC_VID = 0x1d,
  10931. + SSAM_SSH_TC_AUD = 0x1e,
  10932. + SSAM_SSH_TC_SMC = 0x1f,
  10933. + SSAM_SSH_TC_KPD = 0x20,
  10934. + SSAM_SSH_TC_REG = 0x21,
  10935. +};
  10936. +
  10937. +/**
  10938. + * struct ssam_event_flags - Flags for enabling/disabling SAM-over-SSH events
  10939. + * @SSAM_EVENT_SEQUENCED: The event will be sent via a sequenced data frame.
  10940. + */
  10941. +enum ssam_event_flags {
  10942. + SSAM_EVENT_SEQUENCED = BIT(0),
  10943. +};
  10944. +
  10945. +struct ssam_event {
  10946. + u8 target_category;
  10947. + u8 command_id;
  10948. + u8 instance_id;
  10949. + u8 channel;
  10950. + u16 length;
  10951. + u8 data[0];
  10952. +};
  10953. +
  10954. +
  10955. +/* -- Event notifier/callbacks. --------------------------------------------- */
  10956. +
  10957. +#define SSAM_NOTIF_STATE_SHIFT 2
  10958. +#define SSAM_NOTIF_STATE_MASK ((1 << SSAM_NOTIF_STATE_SHIFT) - 1)
  10959. +
  10960. +#define SSAM_NOTIF_HANDLED BIT(0)
  10961. +#define SSAM_NOTIF_STOP BIT(1)
  10962. +
  10963. +
  10964. +struct ssam_notifier_block;
  10965. +
  10966. +typedef u32 (*ssam_notifier_fn_t)(struct ssam_notifier_block *nb,
  10967. + const struct ssam_event *event);
  10968. +
  10969. +struct ssam_notifier_block {
  10970. + struct ssam_notifier_block __rcu *next;
  10971. + ssam_notifier_fn_t fn;
  10972. + int priority;
  10973. +};
  10974. +
  10975. +
  10976. +static inline u32 ssam_notifier_from_errno(int err)
  10977. +{
  10978. + WARN_ON(err > 0);
  10979. +
  10980. + if (err >= 0)
  10981. + return 0;
  10982. + else
  10983. + return ((-err) << SSAM_NOTIF_STATE_SHIFT) | SSAM_NOTIF_STOP;
  10984. +}
  10985. +
  10986. +static inline int ssam_notifier_to_errno(u32 ret)
  10987. +{
  10988. + return -(ret >> SSAM_NOTIF_STATE_SHIFT);
  10989. +}
  10990. +
  10991. +
  10992. +/* -- Event/notification registry. ------------------------------------------ */
  10993. +
  10994. +struct ssam_event_registry {
  10995. + u8 target_category;
  10996. + u8 channel;
  10997. + u8 cid_enable;
  10998. + u8 cid_disable;
  10999. +};
  11000. +
  11001. +struct ssam_event_id {
  11002. + u8 target_category;
  11003. + u8 instance;
  11004. +};
  11005. +
  11006. +
  11007. +#define SSAM_EVENT_REGISTRY(tc, chn, cid_en, cid_dis) \
  11008. + ((struct ssam_event_registry) { \
  11009. + .target_category = (tc), \
  11010. + .channel = (chn), \
  11011. + .cid_enable = (cid_en), \
  11012. + .cid_disable = (cid_dis), \
  11013. + })
  11014. +
  11015. +#define SSAM_EVENT_ID(tc, iid) \
  11016. + ((struct ssam_event_id) { \
  11017. + .target_category = tc, \
  11018. + .instance = iid, \
  11019. + })
  11020. +
  11021. +
  11022. +#define SSAM_EVENT_REGISTRY_SAM \
  11023. + SSAM_EVENT_REGISTRY(SSAM_SSH_TC_SAM, 0x01, 0x0b, 0x0c)
  11024. +
  11025. +#define SSAM_EVENT_REGISTRY_KIP \
  11026. + SSAM_EVENT_REGISTRY(SSAM_SSH_TC_KIP, 0x02, 0x27, 0x28)
  11027. +
  11028. +#define SSAM_EVENT_REGISTRY_REG \
  11029. + SSAM_EVENT_REGISTRY(SSAM_SSH_TC_REG, 0x02, 0x01, 0x02)
  11030. +
  11031. +
  11032. +struct ssam_event_notifier {
  11033. + struct ssam_notifier_block base;
  11034. +
  11035. + struct {
  11036. + struct ssam_event_registry reg;
  11037. + struct ssam_event_id id;
  11038. + u8 flags;
  11039. + } event;
  11040. +};
  11041. +
  11042. +
  11043. +/* -- TODO -------------------------------------------------------------------*/
  11044. +
  11045. +/*
  11046. + * Maximum response payload size in bytes.
  11047. + * Value based on ACPI (255 bytes minus header/status bytes).
  11048. + */
  11049. +#define SURFACE_SAM_SSH_MAX_RQST_RESPONSE (255 - 4)
  11050. +
  11051. +/*
  11052. + * The number of reserved event IDs, used for registering an SSH event
  11053. + * handler. Valid event IDs are numbers below or equal to this value, with
  11054. + * exception of zero, which is not an event ID. Thus, this is also the
  11055. + * absolute maximum number of event handlers that can be registered.
  11056. + */
  11057. +#define SURFACE_SAM_SSH_NUM_EVENTS 0x22
  11058. +
  11059. +/*
  11060. + * The number of communication channels used in the protocol.
  11061. + */
  11062. +#define SURFACE_SAM_SSH_NUM_CHANNELS 2
  11063. +
  11064. +
  11065. +struct surface_sam_ssh_buf {
  11066. + u8 cap;
  11067. + u8 len;
  11068. + u8 *data;
  11069. +};
  11070. +
  11071. +struct surface_sam_ssh_rqst {
  11072. + u8 tc; // target category
  11073. + u8 cid; // command ID
  11074. + u8 iid; // instance ID
  11075. + u8 chn; // channel
  11076. + u8 snc; // expect response flag (bool: 0/1)
  11077. + u16 cdl; // command data length (length of payload)
  11078. + u8 *pld; // pointer to payload of length cdl
  11079. +};
  11080. +
  11081. +// TODO: remove rqid on external api
  11082. +struct surface_sam_ssh_event {
  11083. + u16 rqid; // event type/source ID
  11084. + u8 tc; // target category
  11085. + u8 cid; // command ID
  11086. + u8 iid; // instance ID
  11087. + u8 chn; // channel
  11088. + u8 len; // length of payload
  11089. + u8 *pld; // payload of length len
  11090. +};
  11091. +
  11092. +
  11093. +int surface_sam_ssh_consumer_register(struct device *consumer);
  11094. +
  11095. +int surface_sam_ssh_notifier_register(struct ssam_event_notifier *n);
  11096. +int surface_sam_ssh_notifier_unregister(struct ssam_event_notifier *n);
  11097. +
  11098. +int surface_sam_ssh_rqst(const struct surface_sam_ssh_rqst *rqst, struct surface_sam_ssh_buf *result);
  11099. +
  11100. +#endif /* _SURFACE_SAM_SSH_H */
  11101. diff --git a/drivers/platform/x86/surface_sam/surface_sam_ssh_trace.h b/drivers/platform/x86/surface_sam/surface_sam_ssh_trace.h
  11102. new file mode 100644
  11103. index 0000000000000..801c60205128c
  11104. --- /dev/null
  11105. +++ b/drivers/platform/x86/surface_sam/surface_sam_ssh_trace.h
  11106. @@ -0,0 +1,536 @@
  11107. +#undef TRACE_SYSTEM
  11108. +#define TRACE_SYSTEM surface_sam_ssh
  11109. +
  11110. +#if !defined(_SURFACE_SAM_SSH_TRACE_H) || defined(TRACE_HEADER_MULTI_READ)
  11111. +#define _SURFACE_SAM_SSH_TRACE_H
  11112. +
  11113. +#include <linux/tracepoint.h>
  11114. +
  11115. +#include "surface_sam_ssh.h"
  11116. +
  11117. +
  11118. +TRACE_DEFINE_ENUM(SSH_FRAME_TYPE_DATA_SEQ);
  11119. +TRACE_DEFINE_ENUM(SSH_FRAME_TYPE_DATA_NSQ);
  11120. +TRACE_DEFINE_ENUM(SSH_FRAME_TYPE_ACK);
  11121. +TRACE_DEFINE_ENUM(SSH_FRAME_TYPE_NAK);
  11122. +
  11123. +TRACE_DEFINE_ENUM(SSH_PACKET_TY_FLUSH_BIT);
  11124. +TRACE_DEFINE_ENUM(SSH_PACKET_TY_SEQUENCED_BIT);
  11125. +TRACE_DEFINE_ENUM(SSH_PACKET_TY_BLOCKING_BIT);
  11126. +
  11127. +TRACE_DEFINE_ENUM(SSH_PACKET_TY_FLUSH);
  11128. +TRACE_DEFINE_ENUM(SSH_PACKET_TY_SEQUENCED);
  11129. +TRACE_DEFINE_ENUM(SSH_PACKET_TY_BLOCKING);
  11130. +
  11131. +TRACE_DEFINE_ENUM(SSH_PACKET_SF_LOCKED_BIT);
  11132. +TRACE_DEFINE_ENUM(SSH_PACKET_SF_QUEUED_BIT);
  11133. +TRACE_DEFINE_ENUM(SSH_PACKET_SF_PENDING_BIT);
  11134. +TRACE_DEFINE_ENUM(SSH_PACKET_SF_TRANSMITTING_BIT);
  11135. +TRACE_DEFINE_ENUM(SSH_PACKET_SF_TRANSMITTED_BIT);
  11136. +TRACE_DEFINE_ENUM(SSH_PACKET_SF_ACKED_BIT);
  11137. +TRACE_DEFINE_ENUM(SSH_PACKET_SF_CANCELED_BIT);
  11138. +TRACE_DEFINE_ENUM(SSH_PACKET_SF_COMPLETED_BIT);
  11139. +
  11140. +TRACE_DEFINE_ENUM(SSH_REQUEST_SF_LOCKED_BIT);
  11141. +TRACE_DEFINE_ENUM(SSH_REQUEST_SF_QUEUED_BIT);
  11142. +TRACE_DEFINE_ENUM(SSH_REQUEST_SF_PENDING_BIT);
  11143. +TRACE_DEFINE_ENUM(SSH_REQUEST_SF_TRANSMITTING_BIT);
  11144. +TRACE_DEFINE_ENUM(SSH_REQUEST_SF_TRANSMITTED_BIT);
  11145. +TRACE_DEFINE_ENUM(SSH_REQUEST_SF_RSPRCVD_BIT);
  11146. +TRACE_DEFINE_ENUM(SSH_REQUEST_SF_CANCELED_BIT);
  11147. +TRACE_DEFINE_ENUM(SSH_REQUEST_SF_COMPLETED_BIT);
  11148. +TRACE_DEFINE_ENUM(SSH_REQUEST_TY_FLUSH_BIT);
  11149. +TRACE_DEFINE_ENUM(SSH_REQUEST_TY_HAS_RESPONSE_BIT);
  11150. +
  11151. +TRACE_DEFINE_ENUM(SSH_REQUEST_FLAGS_SF_MASK);
  11152. +TRACE_DEFINE_ENUM(SSH_REQUEST_FLAGS_TY_MASK);
  11153. +
  11154. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_SAM);
  11155. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_BAT);
  11156. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_TMP);
  11157. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_PMC);
  11158. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_FAN);
  11159. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_PoM);
  11160. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_DBG);
  11161. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_KBD);
  11162. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_FWU);
  11163. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_UNI);
  11164. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_LPC);
  11165. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_TCL);
  11166. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_SFL);
  11167. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_KIP);
  11168. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_EXT);
  11169. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_BLD);
  11170. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_BAS);
  11171. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_SEN);
  11172. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_SRQ);
  11173. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_MCU);
  11174. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_HID);
  11175. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_TCH);
  11176. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_BKL);
  11177. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_TAM);
  11178. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_ACC);
  11179. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_UFI);
  11180. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_USC);
  11181. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_PEN);
  11182. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_VID);
  11183. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_AUD);
  11184. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_SMC);
  11185. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_KPD);
  11186. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_REG);
  11187. +
  11188. +
  11189. +#define SSAM_PTR_UID_LEN 9
  11190. +#define SSAM_U8_FIELD_NOT_APPLICABLE ((u16)-1)
  11191. +#define SSAM_SEQ_NOT_APPLICABLE ((u16)-1)
  11192. +#define SSAM_RQID_NOT_APPLICABLE ((u32)-1)
  11193. +#define SSAM_SSH_TC_NOT_APPLICABLE 0
  11194. +
  11195. +
  11196. +#ifndef _SURFACE_SAM_SSH_TRACE_HELPERS
  11197. +#define _SURFACE_SAM_SSH_TRACE_HELPERS
  11198. +
  11199. +static inline void ssam_trace_ptr_uid(const void *ptr, char* uid_str)
  11200. +{
  11201. + char buf[2 * sizeof(void*) + 1];
  11202. +
  11203. + snprintf(buf, ARRAY_SIZE(buf), "%p", ptr);
  11204. + memcpy(uid_str, &buf[ARRAY_SIZE(buf) - SSAM_PTR_UID_LEN],
  11205. + SSAM_PTR_UID_LEN);
  11206. +}
  11207. +
  11208. +static inline u16 ssam_trace_get_packet_seq(const struct ssh_packet *p)
  11209. +{
  11210. + if (!p->data || p->data_length < SSH_MESSAGE_LENGTH(0))
  11211. + return SSAM_SEQ_NOT_APPLICABLE;
  11212. +
  11213. + return p->data[SSH_MSGOFFSET_FRAME(seq)];
  11214. +}
  11215. +
  11216. +static inline u32 ssam_trace_get_request_id(const struct ssh_packet *p)
  11217. +{
  11218. + if (!p->data || p->data_length < SSH_COMMAND_MESSAGE_LENGTH(0))
  11219. + return SSAM_RQID_NOT_APPLICABLE;
  11220. +
  11221. + return get_unaligned_le16(&p->data[SSH_MSGOFFSET_COMMAND(rqid)]);
  11222. +}
  11223. +
  11224. +static inline u32 ssam_trace_get_request_tc(const struct ssh_packet *p)
  11225. +{
  11226. + if (!p->data || p->data_length < SSH_COMMAND_MESSAGE_LENGTH(0))
  11227. + return SSAM_SSH_TC_NOT_APPLICABLE;
  11228. +
  11229. + return get_unaligned_le16(&p->data[SSH_MSGOFFSET_COMMAND(tc)]);
  11230. +}
  11231. +
  11232. +#endif /* _SURFACE_SAM_SSH_TRACE_HELPERS */
  11233. +
  11234. +#define ssam_trace_get_command_field_u8(packet, field) \
  11235. + ((!packet || packet->data_length < SSH_COMMAND_MESSAGE_LENGTH(0)) \
  11236. + ? 0 : p->data[SSH_MSGOFFSET_COMMAND(field)])
  11237. +
  11238. +#define ssam_show_generic_u8_field(value) \
  11239. + __print_symbolic(value, \
  11240. + { SSAM_U8_FIELD_NOT_APPLICABLE, "N/A" } \
  11241. + )
  11242. +
  11243. +
  11244. +#define ssam_show_frame_type(ty) \
  11245. + __print_symbolic(ty, \
  11246. + { SSH_FRAME_TYPE_DATA_SEQ, "DSEQ" }, \
  11247. + { SSH_FRAME_TYPE_DATA_NSQ, "DNSQ" }, \
  11248. + { SSH_FRAME_TYPE_ACK, "ACK" }, \
  11249. + { SSH_FRAME_TYPE_NAK, "NAK" } \
  11250. + )
  11251. +
  11252. +#define ssam_show_packet_type(type) \
  11253. + __print_flags(type, "", \
  11254. + { SSH_PACKET_TY_FLUSH, "F" }, \
  11255. + { SSH_PACKET_TY_SEQUENCED, "S" }, \
  11256. + { SSH_PACKET_TY_BLOCKING, "B" } \
  11257. + )
  11258. +
  11259. +#define ssam_show_packet_state(state) \
  11260. + __print_flags(state, "", \
  11261. + { BIT(SSH_PACKET_SF_LOCKED_BIT), "L" }, \
  11262. + { BIT(SSH_PACKET_SF_QUEUED_BIT), "Q" }, \
  11263. + { BIT(SSH_PACKET_SF_PENDING_BIT), "P" }, \
  11264. + { BIT(SSH_PACKET_SF_TRANSMITTING_BIT), "S" }, \
  11265. + { BIT(SSH_PACKET_SF_TRANSMITTED_BIT), "T" }, \
  11266. + { BIT(SSH_PACKET_SF_ACKED_BIT), "A" }, \
  11267. + { BIT(SSH_PACKET_SF_CANCELED_BIT), "C" }, \
  11268. + { BIT(SSH_PACKET_SF_COMPLETED_BIT), "F" } \
  11269. + )
  11270. +
  11271. +#define ssam_show_packet_seq(seq) \
  11272. + __print_symbolic(seq, \
  11273. + { SSAM_SEQ_NOT_APPLICABLE, "N/A" } \
  11274. + )
  11275. +
  11276. +
  11277. +#define ssam_show_request_type(flags) \
  11278. + __print_flags(flags & SSH_REQUEST_FLAGS_TY_MASK, "", \
  11279. + { BIT(SSH_REQUEST_TY_FLUSH_BIT), "F" }, \
  11280. + { BIT(SSH_REQUEST_TY_HAS_RESPONSE_BIT), "R" } \
  11281. + )
  11282. +
  11283. +#define ssam_show_request_state(flags) \
  11284. + __print_flags(flags & SSH_REQUEST_FLAGS_SF_MASK, "", \
  11285. + { BIT(SSH_REQUEST_SF_LOCKED_BIT), "L" }, \
  11286. + { BIT(SSH_REQUEST_SF_QUEUED_BIT), "Q" }, \
  11287. + { BIT(SSH_REQUEST_SF_PENDING_BIT), "P" }, \
  11288. + { BIT(SSH_REQUEST_SF_TRANSMITTING_BIT), "S" }, \
  11289. + { BIT(SSH_REQUEST_SF_TRANSMITTED_BIT), "T" }, \
  11290. + { BIT(SSH_REQUEST_SF_RSPRCVD_BIT), "A" }, \
  11291. + { BIT(SSH_REQUEST_SF_CANCELED_BIT), "C" }, \
  11292. + { BIT(SSH_REQUEST_SF_COMPLETED_BIT), "F" } \
  11293. + )
  11294. +
  11295. +#define ssam_show_request_id(rqid) \
  11296. + __print_symbolic(rqid, \
  11297. + { SSAM_RQID_NOT_APPLICABLE, "N/A" } \
  11298. + )
  11299. +
  11300. +#define ssam_show_ssh_tc(rqid) \
  11301. + __print_symbolic(rqid, \
  11302. + { SSAM_SSH_TC_NOT_APPLICABLE, "N/A" }, \
  11303. + { SSAM_SSH_TC_SAM, "SAM" }, \
  11304. + { SSAM_SSH_TC_BAT, "BAT" }, \
  11305. + { SSAM_SSH_TC_TMP, "TMP" }, \
  11306. + { SSAM_SSH_TC_PMC, "PMC" }, \
  11307. + { SSAM_SSH_TC_FAN, "FAN" }, \
  11308. + { SSAM_SSH_TC_PoM, "PoM" }, \
  11309. + { SSAM_SSH_TC_DBG, "DBG" }, \
  11310. + { SSAM_SSH_TC_KBD, "KBD" }, \
  11311. + { SSAM_SSH_TC_FWU, "FWU" }, \
  11312. + { SSAM_SSH_TC_UNI, "UNI" }, \
  11313. + { SSAM_SSH_TC_LPC, "LPC" }, \
  11314. + { SSAM_SSH_TC_TCL, "TCL" }, \
  11315. + { SSAM_SSH_TC_SFL, "SFL" }, \
  11316. + { SSAM_SSH_TC_KIP, "KIP" }, \
  11317. + { SSAM_SSH_TC_EXT, "EXT" }, \
  11318. + { SSAM_SSH_TC_BLD, "BLD" }, \
  11319. + { SSAM_SSH_TC_BAS, "BAS" }, \
  11320. + { SSAM_SSH_TC_SEN, "SEN" }, \
  11321. + { SSAM_SSH_TC_SRQ, "SRQ" }, \
  11322. + { SSAM_SSH_TC_MCU, "MCU" }, \
  11323. + { SSAM_SSH_TC_HID, "HID" }, \
  11324. + { SSAM_SSH_TC_TCH, "TCH" }, \
  11325. + { SSAM_SSH_TC_BKL, "BKL" }, \
  11326. + { SSAM_SSH_TC_TAM, "TAM" }, \
  11327. + { SSAM_SSH_TC_ACC, "ACC" }, \
  11328. + { SSAM_SSH_TC_UFI, "UFI" }, \
  11329. + { SSAM_SSH_TC_USC, "USC" }, \
  11330. + { SSAM_SSH_TC_PEN, "PEN" }, \
  11331. + { SSAM_SSH_TC_VID, "VID" }, \
  11332. + { SSAM_SSH_TC_AUD, "AUD" }, \
  11333. + { SSAM_SSH_TC_SMC, "SMC" }, \
  11334. + { SSAM_SSH_TC_KPD, "KPD" }, \
  11335. + { SSAM_SSH_TC_REG, "REG" } \
  11336. + )
  11337. +
  11338. +
  11339. +DECLARE_EVENT_CLASS(ssam_frame_class,
  11340. + TP_PROTO(const struct ssh_frame *frame),
  11341. +
  11342. + TP_ARGS(frame),
  11343. +
  11344. + TP_STRUCT__entry(
  11345. + __field(u8, type)
  11346. + __field(u8, seq)
  11347. + __field(u16, len)
  11348. + ),
  11349. +
  11350. + TP_fast_assign(
  11351. + __entry->type = frame->type;
  11352. + __entry->seq = frame->seq;
  11353. + __entry->len = get_unaligned_le16(&frame->len);
  11354. + ),
  11355. +
  11356. + TP_printk("ty=%s, seq=0x%02x, len=%u",
  11357. + ssam_show_frame_type(__entry->type),
  11358. + __entry->seq,
  11359. + __entry->len
  11360. + )
  11361. +);
  11362. +
  11363. +#define DEFINE_SSAM_FRAME_EVENT(name) \
  11364. + DEFINE_EVENT(ssam_frame_class, ssam_##name, \
  11365. + TP_PROTO(const struct ssh_frame *frame), \
  11366. + TP_ARGS(frame) \
  11367. + )
  11368. +
  11369. +
  11370. +DECLARE_EVENT_CLASS(ssam_command_class,
  11371. + TP_PROTO(const struct ssh_command *cmd, u16 len),
  11372. +
  11373. + TP_ARGS(cmd, len),
  11374. +
  11375. + TP_STRUCT__entry(
  11376. + __field(u16, rqid)
  11377. + __field(u16, len)
  11378. + __field(u8, tc)
  11379. + __field(u8, cid)
  11380. + __field(u8, iid)
  11381. + ),
  11382. +
  11383. + TP_fast_assign(
  11384. + __entry->rqid = get_unaligned_le16(&cmd->rqid);
  11385. + __entry->tc = cmd->tc;
  11386. + __entry->cid = cmd->cid;
  11387. + __entry->iid = cmd->iid;
  11388. + __entry->len = len;
  11389. + ),
  11390. +
  11391. + TP_printk("rqid=0x%04x, tc=%s, cid=0x%02x, iid=0x%02x, len=%u",
  11392. + __entry->rqid,
  11393. + ssam_show_ssh_tc(__entry->tc),
  11394. + __entry->cid,
  11395. + __entry->iid,
  11396. + __entry->len
  11397. + )
  11398. +);
  11399. +
  11400. +#define DEFINE_SSAM_COMMAND_EVENT(name) \
  11401. + DEFINE_EVENT(ssam_command_class, ssam_##name, \
  11402. + TP_PROTO(const struct ssh_command *cmd, u16 len), \
  11403. + TP_ARGS(cmd, len) \
  11404. + )
  11405. +
  11406. +
  11407. +DECLARE_EVENT_CLASS(ssam_packet_class,
  11408. + TP_PROTO(const struct ssh_packet *packet),
  11409. +
  11410. + TP_ARGS(packet),
  11411. +
  11412. + TP_STRUCT__entry(
  11413. + __array(char, uid, SSAM_PTR_UID_LEN)
  11414. + __field(u8, type)
  11415. + __field(u8, priority)
  11416. + __field(u16, length)
  11417. + __field(unsigned long, state)
  11418. + __field(u16, seq)
  11419. + ),
  11420. +
  11421. + TP_fast_assign(
  11422. + ssam_trace_ptr_uid(packet, __entry->uid);
  11423. + __entry->type = packet->type;
  11424. + __entry->priority = READ_ONCE(packet->priority);
  11425. + __entry->length = packet->data_length;
  11426. + __entry->state = READ_ONCE(packet->state);
  11427. + __entry->seq = ssam_trace_get_packet_seq(packet);
  11428. + ),
  11429. +
  11430. + TP_printk("uid=%s, seq=%s, ty=%s, pri=0x%02x, len=%u, sta=%s",
  11431. + __entry->uid,
  11432. + ssam_show_packet_seq(__entry->seq),
  11433. + ssam_show_packet_type(__entry->type),
  11434. + __entry->priority,
  11435. + __entry->length,
  11436. + ssam_show_packet_state(__entry->state)
  11437. + )
  11438. +);
  11439. +
  11440. +#define DEFINE_SSAM_PACKET_EVENT(name) \
  11441. + DEFINE_EVENT(ssam_packet_class, ssam_##name, \
  11442. + TP_PROTO(const struct ssh_packet *packet), \
  11443. + TP_ARGS(packet) \
  11444. + )
  11445. +
  11446. +
  11447. +DECLARE_EVENT_CLASS(ssam_packet_status_class,
  11448. + TP_PROTO(const struct ssh_packet *packet, int status),
  11449. +
  11450. + TP_ARGS(packet, status),
  11451. +
  11452. + TP_STRUCT__entry(
  11453. + __array(char, uid, SSAM_PTR_UID_LEN)
  11454. + __field(u8, type)
  11455. + __field(u8, priority)
  11456. + __field(u16, length)
  11457. + __field(unsigned long, state)
  11458. + __field(u16, seq)
  11459. + __field(int, status)
  11460. + ),
  11461. +
  11462. + TP_fast_assign(
  11463. + ssam_trace_ptr_uid(packet, __entry->uid);
  11464. + __entry->type = packet->type;
  11465. + __entry->priority = READ_ONCE(packet->priority);
  11466. + __entry->length = packet->data_length;
  11467. + __entry->state = READ_ONCE(packet->state);
  11468. + __entry->seq = ssam_trace_get_packet_seq(packet);
  11469. + __entry->status = status;
  11470. + ),
  11471. +
  11472. + TP_printk("uid=%s, seq=%s, ty=%s, pri=0x%02x, len=%u, sta=%s, status=%d",
  11473. + __entry->uid,
  11474. + ssam_show_packet_seq(__entry->seq),
  11475. + ssam_show_packet_type(__entry->type),
  11476. + __entry->priority,
  11477. + __entry->length,
  11478. + ssam_show_packet_state(__entry->state),
  11479. + __entry->status
  11480. + )
  11481. +);
  11482. +
  11483. +#define DEFINE_SSAM_PACKET_STATUS_EVENT(name) \
  11484. + DEFINE_EVENT(ssam_packet_status_class, ssam_##name, \
  11485. + TP_PROTO(const struct ssh_packet *packet, int status), \
  11486. + TP_ARGS(packet, status) \
  11487. + )
  11488. +
  11489. +
  11490. +DECLARE_EVENT_CLASS(ssam_request_class,
  11491. + TP_PROTO(const struct ssh_request *request),
  11492. +
  11493. + TP_ARGS(request),
  11494. +
  11495. + TP_STRUCT__entry(
  11496. + __array(char, uid, SSAM_PTR_UID_LEN)
  11497. + __field(unsigned long, state)
  11498. + __field(u32, rqid)
  11499. + __field(u8, tc)
  11500. + __field(u16, cid)
  11501. + __field(u16, iid)
  11502. + ),
  11503. +
  11504. + TP_fast_assign(
  11505. + const struct ssh_packet *p = &request->packet;
  11506. +
  11507. + // use packet for UID so we can match requests to packets
  11508. + ssam_trace_ptr_uid(p, __entry->uid);
  11509. + __entry->state = READ_ONCE(request->state);
  11510. + __entry->rqid = ssam_trace_get_request_id(p);
  11511. + __entry->tc = ssam_trace_get_request_tc(p);
  11512. + __entry->cid = ssam_trace_get_command_field_u8(p, cid);
  11513. + __entry->iid = ssam_trace_get_command_field_u8(p, iid);
  11514. + ),
  11515. +
  11516. + TP_printk("uid=%s, rqid=%s, ty=%s, sta=%s, tc=%s, cid=%s, iid=%s",
  11517. + __entry->uid,
  11518. + ssam_show_request_id(__entry->rqid),
  11519. + ssam_show_request_type(__entry->state),
  11520. + ssam_show_request_state(__entry->state),
  11521. + ssam_show_ssh_tc(__entry->tc),
  11522. + ssam_show_generic_u8_field(__entry->cid),
  11523. + ssam_show_generic_u8_field(__entry->iid)
  11524. + )
  11525. +);
  11526. +
  11527. +#define DEFINE_SSAM_REQUEST_EVENT(name) \
  11528. + DEFINE_EVENT(ssam_request_class, ssam_##name, \
  11529. + TP_PROTO(const struct ssh_request *request), \
  11530. + TP_ARGS(request) \
  11531. + )
  11532. +
  11533. +
  11534. +DECLARE_EVENT_CLASS(ssam_request_status_class,
  11535. + TP_PROTO(const struct ssh_request *request, int status),
  11536. +
  11537. + TP_ARGS(request, status),
  11538. +
  11539. + TP_STRUCT__entry(
  11540. + __array(char, uid, SSAM_PTR_UID_LEN)
  11541. + __field(unsigned long, state)
  11542. + __field(u32, rqid)
  11543. + __field(u8, tc)
  11544. + __field(u16, cid)
  11545. + __field(u16, iid)
  11546. + __field(int, status)
  11547. + ),
  11548. +
  11549. + TP_fast_assign(
  11550. + const struct ssh_packet *p = &request->packet;
  11551. +
  11552. + // use packet for UID so we can match requests to packets
  11553. + ssam_trace_ptr_uid(p, __entry->uid);
  11554. + __entry->state = READ_ONCE(request->state);
  11555. + __entry->rqid = ssam_trace_get_request_id(p);
  11556. + __entry->tc = ssam_trace_get_request_tc(p);
  11557. + __entry->cid = ssam_trace_get_command_field_u8(p, cid);
  11558. + __entry->iid = ssam_trace_get_command_field_u8(p, iid);
  11559. + __entry->status = status;
  11560. + ),
  11561. +
  11562. + TP_printk("uid=%s, rqid=%s, ty=%s, sta=%s, tc=%s, cid=%s, iid=%s, status=%d",
  11563. + __entry->uid,
  11564. + ssam_show_request_id(__entry->rqid),
  11565. + ssam_show_request_type(__entry->state),
  11566. + ssam_show_request_state(__entry->state),
  11567. + ssam_show_ssh_tc(__entry->tc),
  11568. + ssam_show_generic_u8_field(__entry->cid),
  11569. + ssam_show_generic_u8_field(__entry->iid),
  11570. + __entry->status
  11571. + )
  11572. +);
  11573. +
  11574. +#define DEFINE_SSAM_REQUEST_STATUS_EVENT(name) \
  11575. + DEFINE_EVENT(ssam_request_status_class, ssam_##name, \
  11576. + TP_PROTO(const struct ssh_request *request, int status),\
  11577. + TP_ARGS(request, status) \
  11578. + )
  11579. +
  11580. +
  11581. +DECLARE_EVENT_CLASS(ssam_generic_uint_class,
  11582. + TP_PROTO(const char* property, unsigned int value),
  11583. +
  11584. + TP_ARGS(property, value),
  11585. +
  11586. + TP_STRUCT__entry(
  11587. + __string(property, property)
  11588. + __field(unsigned int, value)
  11589. + ),
  11590. +
  11591. + TP_fast_assign(
  11592. + __assign_str(property, property);
  11593. + __entry->value = value;
  11594. + ),
  11595. +
  11596. + TP_printk("%s=%u", __get_str(property), __entry->value)
  11597. +);
  11598. +
  11599. +#define DEFINE_SSAM_GENERIC_UINT_EVENT(name) \
  11600. + DEFINE_EVENT(ssam_generic_uint_class, ssam_##name, \
  11601. + TP_PROTO(const char* property, unsigned int value), \
  11602. + TP_ARGS(property, value) \
  11603. + )
  11604. +
  11605. +
  11606. +DEFINE_SSAM_FRAME_EVENT(rx_frame_received);
  11607. +DEFINE_SSAM_COMMAND_EVENT(rx_response_received);
  11608. +DEFINE_SSAM_COMMAND_EVENT(rx_event_received);
  11609. +
  11610. +DEFINE_SSAM_PACKET_EVENT(packet_release);
  11611. +DEFINE_SSAM_PACKET_EVENT(packet_submit);
  11612. +DEFINE_SSAM_PACKET_EVENT(packet_resubmit);
  11613. +DEFINE_SSAM_PACKET_EVENT(packet_timeout);
  11614. +DEFINE_SSAM_PACKET_EVENT(packet_cancel);
  11615. +DEFINE_SSAM_PACKET_STATUS_EVENT(packet_complete);
  11616. +DEFINE_SSAM_GENERIC_UINT_EVENT(ptl_timeout_reap);
  11617. +
  11618. +DEFINE_SSAM_REQUEST_EVENT(request_submit);
  11619. +DEFINE_SSAM_REQUEST_EVENT(request_timeout);
  11620. +DEFINE_SSAM_REQUEST_EVENT(request_cancel);
  11621. +DEFINE_SSAM_REQUEST_STATUS_EVENT(request_complete);
  11622. +DEFINE_SSAM_GENERIC_UINT_EVENT(rtl_timeout_reap);
  11623. +
  11624. +DEFINE_SSAM_PACKET_EVENT(ei_tx_drop_ack_packet);
  11625. +DEFINE_SSAM_PACKET_EVENT(ei_tx_drop_nak_packet);
  11626. +DEFINE_SSAM_PACKET_EVENT(ei_tx_drop_dsq_packet);
  11627. +DEFINE_SSAM_PACKET_STATUS_EVENT(ei_tx_fail_write);
  11628. +DEFINE_SSAM_PACKET_EVENT(ei_tx_corrupt_data);
  11629. +DEFINE_SSAM_GENERIC_UINT_EVENT(ei_rx_corrupt_syn);
  11630. +DEFINE_SSAM_FRAME_EVENT(ei_rx_corrupt_data);
  11631. +DEFINE_SSAM_REQUEST_EVENT(ei_rx_drop_response);
  11632. +
  11633. +#endif /* _SURFACE_SAM_SSH_TRACE_H */
  11634. +
  11635. +/* This part must be outside protection */
  11636. +#undef TRACE_INCLUDE_PATH
  11637. +#undef TRACE_INCLUDE_FILE
  11638. +
  11639. +#define TRACE_INCLUDE_PATH .
  11640. +#define TRACE_INCLUDE_FILE surface_sam_ssh_trace
  11641. +
  11642. +#include <trace/define_trace.h>
  11643. diff --git a/drivers/platform/x86/surface_sam/surface_sam_vhf.c b/drivers/platform/x86/surface_sam/surface_sam_vhf.c
  11644. new file mode 100644
  11645. index 0000000000000..984035c55d63a
  11646. --- /dev/null
  11647. +++ b/drivers/platform/x86/surface_sam/surface_sam_vhf.c
  11648. @@ -0,0 +1,261 @@
  11649. +// SPDX-License-Identifier: GPL-2.0-or-later
  11650. +/*
  11651. + * Virtual HID Framework (VHF) driver for input events via SAM.
  11652. + * Used for keyboard input events on the Surface Laptops.
  11653. + */
  11654. +
  11655. +#include <linux/acpi.h>
  11656. +#include <linux/hid.h>
  11657. +#include <linux/input.h>
  11658. +#include <linux/platform_device.h>
  11659. +#include <linux/types.h>
  11660. +
  11661. +#include "surface_sam_ssh.h"
  11662. +
  11663. +
  11664. +#define USB_VENDOR_ID_MICROSOFT 0x045e
  11665. +#define USB_DEVICE_ID_MS_VHF 0xf001
  11666. +
  11667. +#define VHF_INPUT_NAME "Microsoft Virtual HID Framework Device"
  11668. +
  11669. +
  11670. +struct vhf_drvdata {
  11671. + struct platform_device *dev;
  11672. + struct hid_device *hid;
  11673. + struct ssam_event_notifier notif;
  11674. +};
  11675. +
  11676. +
  11677. +/*
  11678. + * These report descriptors have been extracted from a Surface Book 2.
  11679. + * They seems to be similar enough to be usable on the Surface Laptop.
  11680. + */
  11681. +static const u8 vhf_hid_desc[] = {
  11682. + // keyboard descriptor (event command ID 0x03)
  11683. + 0x05, 0x01, /* Usage Page (Desktop), */
  11684. + 0x09, 0x06, /* Usage (Keyboard), */
  11685. + 0xA1, 0x01, /* Collection (Application), */
  11686. + 0x85, 0x01, /* Report ID (1), */
  11687. + 0x15, 0x00, /* Logical Minimum (0), */
  11688. + 0x25, 0x01, /* Logical Maximum (1), */
  11689. + 0x75, 0x01, /* Report Size (1), */
  11690. + 0x95, 0x08, /* Report Count (8), */
  11691. + 0x05, 0x07, /* Usage Page (Keyboard), */
  11692. + 0x19, 0xE0, /* Usage Minimum (KB Leftcontrol), */
  11693. + 0x29, 0xE7, /* Usage Maximum (KB Right GUI), */
  11694. + 0x81, 0x02, /* Input (Variable), */
  11695. + 0x75, 0x08, /* Report Size (8), */
  11696. + 0x95, 0x0A, /* Report Count (10), */
  11697. + 0x19, 0x00, /* Usage Minimum (None), */
  11698. + 0x29, 0x91, /* Usage Maximum (KB LANG2), */
  11699. + 0x26, 0xFF, 0x00, /* Logical Maximum (255), */
  11700. + 0x81, 0x00, /* Input, */
  11701. + 0x05, 0x0C, /* Usage Page (Consumer), */
  11702. + 0x0A, 0xC0, 0x02, /* Usage (02C0h), */
  11703. + 0xA1, 0x02, /* Collection (Logical), */
  11704. + 0x1A, 0xC1, 0x02, /* Usage Minimum (02C1h), */
  11705. + 0x2A, 0xC6, 0x02, /* Usage Maximum (02C6h), */
  11706. + 0x95, 0x06, /* Report Count (6), */
  11707. + 0xB1, 0x03, /* Feature (Constant, Variable), */
  11708. + 0xC0, /* End Collection, */
  11709. + 0x05, 0x08, /* Usage Page (LED), */
  11710. + 0x19, 0x01, /* Usage Minimum (01h), */
  11711. + 0x29, 0x03, /* Usage Maximum (03h), */
  11712. + 0x75, 0x01, /* Report Size (1), */
  11713. + 0x95, 0x03, /* Report Count (3), */
  11714. + 0x25, 0x01, /* Logical Maximum (1), */
  11715. + 0x91, 0x02, /* Output (Variable), */
  11716. + 0x95, 0x05, /* Report Count (5), */
  11717. + 0x91, 0x01, /* Output (Constant), */
  11718. + 0xC0, /* End Collection, */
  11719. +
  11720. + // media key descriptor (event command ID 0x04)
  11721. + 0x05, 0x0C, /* Usage Page (Consumer), */
  11722. + 0x09, 0x01, /* Usage (Consumer Control), */
  11723. + 0xA1, 0x01, /* Collection (Application), */
  11724. + 0x85, 0x03, /* Report ID (3), */
  11725. + 0x75, 0x10, /* Report Size (16), */
  11726. + 0x15, 0x00, /* Logical Minimum (0), */
  11727. + 0x26, 0xFF, 0x03, /* Logical Maximum (1023), */
  11728. + 0x19, 0x00, /* Usage Minimum (00h), */
  11729. + 0x2A, 0xFF, 0x03, /* Usage Maximum (03FFh), */
  11730. + 0x81, 0x00, /* Input, */
  11731. + 0xC0, /* End Collection, */
  11732. +};
  11733. +
  11734. +
  11735. +static int vhf_hid_start(struct hid_device *hid)
  11736. +{
  11737. + hid_dbg(hid, "%s\n", __func__);
  11738. + return 0;
  11739. +}
  11740. +
  11741. +static void vhf_hid_stop(struct hid_device *hid)
  11742. +{
  11743. + hid_dbg(hid, "%s\n", __func__);
  11744. +}
  11745. +
  11746. +static int vhf_hid_open(struct hid_device *hid)
  11747. +{
  11748. + hid_dbg(hid, "%s\n", __func__);
  11749. + return 0;
  11750. +}
  11751. +
  11752. +static void vhf_hid_close(struct hid_device *hid)
  11753. +{
  11754. + hid_dbg(hid, "%s\n", __func__);
  11755. +}
  11756. +
  11757. +static int vhf_hid_parse(struct hid_device *hid)
  11758. +{
  11759. + return hid_parse_report(hid, (u8 *)vhf_hid_desc, ARRAY_SIZE(vhf_hid_desc));
  11760. +}
  11761. +
  11762. +static int vhf_hid_raw_request(struct hid_device *hid, unsigned char reportnum,
  11763. + u8 *buf, size_t len, unsigned char rtype,
  11764. + int reqtype)
  11765. +{
  11766. + hid_dbg(hid, "%s\n", __func__);
  11767. + return 0;
  11768. +}
  11769. +
  11770. +static int vhf_hid_output_report(struct hid_device *hid, u8 *buf, size_t len)
  11771. +{
  11772. + hid_dbg(hid, "%s\n", __func__);
  11773. + print_hex_dump_debug("report:", DUMP_PREFIX_OFFSET, 16, 1, buf, len, false);
  11774. +
  11775. + return len;
  11776. +}
  11777. +
  11778. +static struct hid_ll_driver vhf_hid_ll_driver = {
  11779. + .start = vhf_hid_start,
  11780. + .stop = vhf_hid_stop,
  11781. + .open = vhf_hid_open,
  11782. + .close = vhf_hid_close,
  11783. + .parse = vhf_hid_parse,
  11784. + .raw_request = vhf_hid_raw_request,
  11785. + .output_report = vhf_hid_output_report,
  11786. +};
  11787. +
  11788. +
  11789. +static struct hid_device *vhf_create_hid_device(struct platform_device *pdev)
  11790. +{
  11791. + struct hid_device *hid;
  11792. +
  11793. + hid = hid_allocate_device();
  11794. + if (IS_ERR(hid))
  11795. + return hid;
  11796. +
  11797. + hid->dev.parent = &pdev->dev;
  11798. +
  11799. + hid->bus = BUS_VIRTUAL;
  11800. + hid->vendor = USB_VENDOR_ID_MICROSOFT;
  11801. + hid->product = USB_DEVICE_ID_MS_VHF;
  11802. +
  11803. + hid->ll_driver = &vhf_hid_ll_driver;
  11804. +
  11805. + sprintf(hid->name, "%s", VHF_INPUT_NAME);
  11806. +
  11807. + return hid;
  11808. +}
  11809. +
  11810. +static u32 vhf_event_handler(struct ssam_notifier_block *nb, const struct ssam_event *event)
  11811. +{
  11812. + struct vhf_drvdata *drvdata = container_of(nb, struct vhf_drvdata, notif.base);
  11813. + int status;
  11814. +
  11815. + if (event->target_category != 0x08)
  11816. + return 0;
  11817. +
  11818. + if (event->command_id == 0x03 || event->command_id == 0x04) {
  11819. + status = hid_input_report(drvdata->hid, HID_INPUT_REPORT, (u8 *)&event->data[0], event->length, 1);
  11820. + return ssam_notifier_from_errno(status) | SSAM_NOTIF_HANDLED;
  11821. + }
  11822. +
  11823. + return 0;
  11824. +}
  11825. +
  11826. +static int surface_sam_vhf_probe(struct platform_device *pdev)
  11827. +{
  11828. + struct vhf_drvdata *drvdata;
  11829. + struct hid_device *hid;
  11830. + int status;
  11831. +
  11832. + // add device link to EC
  11833. + status = surface_sam_ssh_consumer_register(&pdev->dev);
  11834. + if (status)
  11835. + return status == -ENXIO ? -EPROBE_DEFER : status;
  11836. +
  11837. + drvdata = kzalloc(sizeof(struct vhf_drvdata), GFP_KERNEL);
  11838. + if (!drvdata)
  11839. + return -ENOMEM;
  11840. +
  11841. + hid = vhf_create_hid_device(pdev);
  11842. + if (IS_ERR(hid)) {
  11843. + status = PTR_ERR(hid);
  11844. + goto err_probe_hid;
  11845. + }
  11846. +
  11847. + status = hid_add_device(hid);
  11848. + if (status)
  11849. + goto err_add_hid;
  11850. +
  11851. + drvdata->dev = pdev;
  11852. + drvdata->hid = hid;
  11853. +
  11854. + drvdata->notif.base.priority = 1;
  11855. + drvdata->notif.base.fn = vhf_event_handler;
  11856. + drvdata->notif.event.reg = SSAM_EVENT_REGISTRY_SAM;
  11857. + drvdata->notif.event.id.target_category = SSAM_SSH_TC_KBD;
  11858. + drvdata->notif.event.id.instance = 0;
  11859. + drvdata->notif.event.flags = 0;
  11860. +
  11861. + platform_set_drvdata(pdev, drvdata);
  11862. +
  11863. + status = surface_sam_ssh_notifier_register(&drvdata->notif);
  11864. + if (status)
  11865. + goto err_add_hid;
  11866. +
  11867. + return 0;
  11868. +
  11869. +err_add_hid:
  11870. + hid_destroy_device(hid);
  11871. + platform_set_drvdata(pdev, NULL);
  11872. +err_probe_hid:
  11873. + kfree(drvdata);
  11874. + return status;
  11875. +}
  11876. +
  11877. +static int surface_sam_vhf_remove(struct platform_device *pdev)
  11878. +{
  11879. + struct vhf_drvdata *drvdata = platform_get_drvdata(pdev);
  11880. +
  11881. + surface_sam_ssh_notifier_unregister(&drvdata->notif);
  11882. + hid_destroy_device(drvdata->hid);
  11883. + kfree(drvdata);
  11884. +
  11885. + platform_set_drvdata(pdev, NULL);
  11886. + return 0;
  11887. +}
  11888. +
  11889. +
  11890. +static const struct acpi_device_id surface_sam_vhf_match[] = {
  11891. + { "MSHW0096" },
  11892. + { },
  11893. +};
  11894. +MODULE_DEVICE_TABLE(acpi, surface_sam_vhf_match);
  11895. +
  11896. +static struct platform_driver surface_sam_vhf = {
  11897. + .probe = surface_sam_vhf_probe,
  11898. + .remove = surface_sam_vhf_remove,
  11899. + .driver = {
  11900. + .name = "surface_sam_vhf",
  11901. + .acpi_match_table = surface_sam_vhf_match,
  11902. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  11903. + },
  11904. +};
  11905. +module_platform_driver(surface_sam_vhf);
  11906. +
  11907. +MODULE_AUTHOR("Maximilian Luz <luzmaximilian@gmail.com>");
  11908. +MODULE_DESCRIPTION("Virtual HID Framework Driver for 5th Generation Surface Devices");
  11909. +MODULE_LICENSE("GPL");
  11910. --
  11911. 2.27.0