0005-surface-sam.patch 325 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137
  1. From 94e62231d05dc74e0e2cc76d8fbc752a84ff91b1 Mon Sep 17 00:00:00 2001
  2. From: qzed <qzed@users.noreply.github.com>
  3. Date: Mon, 26 Aug 2019 01:15:40 +0200
  4. Subject: [PATCH 5/8] surface-sam
  5. ---
  6. drivers/acpi/acpica/dsopcode.c | 2 +-
  7. drivers/acpi/acpica/exfield.c | 26 +-
  8. drivers/platform/x86/Kconfig | 2 +
  9. drivers/platform/x86/Makefile | 1 +
  10. drivers/platform/x86/surface_sam/Kconfig | 164 +
  11. drivers/platform/x86/surface_sam/Makefile | 15 +
  12. .../x86/surface_sam/surface_sam_dtx.c | 590 ++
  13. .../x86/surface_sam/surface_sam_hps.c | 1297 +++++
  14. .../x86/surface_sam/surface_sam_san.c | 913 +++
  15. .../x86/surface_sam/surface_sam_san.h | 30 +
  16. .../x86/surface_sam/surface_sam_sid.c | 281 +
  17. .../x86/surface_sam/surface_sam_sid_gpelid.c | 232 +
  18. .../surface_sam/surface_sam_sid_perfmode.c | 216 +
  19. .../x86/surface_sam/surface_sam_sid_power.c | 1154 ++++
  20. .../x86/surface_sam/surface_sam_sid_power.h | 15 +
  21. .../x86/surface_sam/surface_sam_sid_vhf.c | 432 ++
  22. .../x86/surface_sam/surface_sam_sid_vhf.h | 13 +
  23. .../x86/surface_sam/surface_sam_ssh.c | 5112 +++++++++++++++++
  24. .../x86/surface_sam/surface_sam_ssh.h | 482 ++
  25. .../x86/surface_sam/surface_sam_ssh_trace.h | 536 ++
  26. .../x86/surface_sam/surface_sam_vhf.c | 261 +
  27. drivers/tty/serdev/core.c | 110 +-
  28. 22 files changed, 11855 insertions(+), 29 deletions(-)
  29. create mode 100644 drivers/platform/x86/surface_sam/Kconfig
  30. create mode 100644 drivers/platform/x86/surface_sam/Makefile
  31. create mode 100644 drivers/platform/x86/surface_sam/surface_sam_dtx.c
  32. create mode 100644 drivers/platform/x86/surface_sam/surface_sam_hps.c
  33. create mode 100644 drivers/platform/x86/surface_sam/surface_sam_san.c
  34. create mode 100644 drivers/platform/x86/surface_sam/surface_sam_san.h
  35. create mode 100644 drivers/platform/x86/surface_sam/surface_sam_sid.c
  36. create mode 100644 drivers/platform/x86/surface_sam/surface_sam_sid_gpelid.c
  37. create mode 100644 drivers/platform/x86/surface_sam/surface_sam_sid_perfmode.c
  38. create mode 100644 drivers/platform/x86/surface_sam/surface_sam_sid_power.c
  39. create mode 100644 drivers/platform/x86/surface_sam/surface_sam_sid_power.h
  40. create mode 100644 drivers/platform/x86/surface_sam/surface_sam_sid_vhf.c
  41. create mode 100644 drivers/platform/x86/surface_sam/surface_sam_sid_vhf.h
  42. create mode 100644 drivers/platform/x86/surface_sam/surface_sam_ssh.c
  43. create mode 100644 drivers/platform/x86/surface_sam/surface_sam_ssh.h
  44. create mode 100644 drivers/platform/x86/surface_sam/surface_sam_ssh_trace.h
  45. create mode 100644 drivers/platform/x86/surface_sam/surface_sam_vhf.c
  46. diff --git a/drivers/acpi/acpica/dsopcode.c b/drivers/acpi/acpica/dsopcode.c
  47. index 2f4641e5ecde8..beb22d7e245e3 100644
  48. --- a/drivers/acpi/acpica/dsopcode.c
  49. +++ b/drivers/acpi/acpica/dsopcode.c
  50. @@ -123,7 +123,7 @@ acpi_ds_init_buffer_field(u16 aml_opcode,
  51. /* Offset is in bits, count is in bits */
  52. - field_flags = AML_FIELD_ACCESS_BYTE;
  53. + field_flags = AML_FIELD_ACCESS_BUFFER;
  54. bit_offset = offset;
  55. bit_count = (u32) length_desc->integer.value;
  56. diff --git a/drivers/acpi/acpica/exfield.c b/drivers/acpi/acpica/exfield.c
  57. index b272c329d45db..cf547883a9937 100644
  58. --- a/drivers/acpi/acpica/exfield.c
  59. +++ b/drivers/acpi/acpica/exfield.c
  60. @@ -102,6 +102,7 @@ acpi_ex_read_data_from_field(struct acpi_walk_state *walk_state,
  61. void *buffer;
  62. u32 function;
  63. u16 accessor_type;
  64. + u8 field_flags;
  65. ACPI_FUNCTION_TRACE_PTR(ex_read_data_from_field, obj_desc);
  66. @@ -199,11 +200,16 @@ acpi_ex_read_data_from_field(struct acpi_walk_state *walk_state,
  67. * Note: Field.length is in bits.
  68. */
  69. length =
  70. - (acpi_size)ACPI_ROUND_BITS_UP_TO_BYTES(obj_desc->field.bit_length);
  71. + (acpi_size)ACPI_ROUND_BITS_UP_TO_BYTES(obj_desc->common_field.bit_length);
  72. + field_flags = obj_desc->common_field.field_flags;
  73. - if (length > acpi_gbl_integer_byte_width) {
  74. + if (length > acpi_gbl_integer_byte_width ||
  75. + (field_flags & AML_FIELD_ACCESS_TYPE_MASK) == AML_FIELD_ACCESS_BUFFER) {
  76. - /* Field is too large for an Integer, create a Buffer instead */
  77. + /*
  78. + * Field is either too large for an Integer, or a actually of type
  79. + * buffer, so create a Buffer.
  80. + */
  81. buffer_desc = acpi_ut_create_buffer_object(length);
  82. if (!buffer_desc) {
  83. @@ -366,19 +372,7 @@ acpi_ex_write_data_to_field(union acpi_operand_object *source_desc,
  84. } else if (obj_desc->field.region_obj->region.space_id ==
  85. ACPI_ADR_SPACE_GSBUS) {
  86. accessor_type = obj_desc->field.attribute;
  87. - length =
  88. - acpi_ex_get_serial_access_length(accessor_type,
  89. - obj_desc->field.
  90. - access_length);
  91. -
  92. - /*
  93. - * Add additional 2 bytes for the generic_serial_bus data buffer:
  94. - *
  95. - * Status; (Byte 0 of the data buffer)
  96. - * Length; (Byte 1 of the data buffer)
  97. - * Data[x-1]: (Bytes 2-x of the arbitrary length data buffer)
  98. - */
  99. - length += 2;
  100. + length = source_desc->buffer.length;
  101. function = ACPI_WRITE | (accessor_type << 16);
  102. } else { /* IPMI */
  103. diff --git a/drivers/platform/x86/Kconfig b/drivers/platform/x86/Kconfig
  104. index 2ad19dc64a4af..7cee1015981d5 100644
  105. --- a/drivers/platform/x86/Kconfig
  106. +++ b/drivers/platform/x86/Kconfig
  107. @@ -1250,6 +1250,8 @@ config INTEL_ATOMISP2_PM
  108. To compile this driver as a module, choose M here: the module
  109. will be called intel_atomisp2_pm.
  110. +source "drivers/platform/x86/surface_sam/Kconfig"
  111. +
  112. endif # X86_PLATFORM_DEVICES
  113. config PMC_ATOM
  114. diff --git a/drivers/platform/x86/Makefile b/drivers/platform/x86/Makefile
  115. index 2ea90039a3e49..cbea9579c1d2f 100644
  116. --- a/drivers/platform/x86/Makefile
  117. +++ b/drivers/platform/x86/Makefile
  118. @@ -94,3 +94,4 @@ obj-$(CONFIG_INTEL_TURBO_MAX_3) += intel_turbo_max_3.o
  119. obj-$(CONFIG_INTEL_CHTDC_TI_PWRBTN) += intel_chtdc_ti_pwrbtn.o
  120. obj-$(CONFIG_I2C_MULTI_INSTANTIATE) += i2c-multi-instantiate.o
  121. obj-$(CONFIG_INTEL_ATOMISP2_PM) += intel_atomisp2_pm.o
  122. +obj-$(CONFIG_SURFACE_SAM) += surface_sam/
  123. diff --git a/drivers/platform/x86/surface_sam/Kconfig b/drivers/platform/x86/surface_sam/Kconfig
  124. new file mode 100644
  125. index 0000000000000..51278a80569aa
  126. --- /dev/null
  127. +++ b/drivers/platform/x86/surface_sam/Kconfig
  128. @@ -0,0 +1,164 @@
  129. +menuconfig SURFACE_SAM
  130. + depends on ACPI
  131. + tristate "Microsoft Surface/System Aggregator Module and Platform Drivers"
  132. + help
  133. + Drivers for the Surface/System Aggregator Module (SAM) of Microsoft
  134. + Surface devices.
  135. +
  136. + SAM is an embedded controller that provides access to various
  137. + functionalities on these devices, including battery status, keyboard
  138. + events (on the Laptops) and many more.
  139. +
  140. + Say M/Y here if you have a Microsoft Surface device with a SAM device
  141. + (i.e. 5th generation or later).
  142. +
  143. +config SURFACE_SAM_SSH
  144. + tristate "Surface Serial Hub Driver"
  145. + depends on SURFACE_SAM
  146. + depends on SERIAL_DEV_CTRL_TTYPORT
  147. + select CRC_CCITT
  148. + default m
  149. + help
  150. + Surface Serial Hub driver for 5th generation (or later) Microsoft
  151. + Surface devices.
  152. +
  153. + This is the base driver for the embedded serial controller found on
  154. + 5th generation (and later) Microsoft Surface devices (e.g. Book 2,
  155. + Laptop, Laptop 2, Pro 2017, Pro 6, ...). This driver itself only
  156. + provides access to the embedded controller (SAM) and subsequent
  157. + drivers are required for the respective functionalities.
  158. +
  159. + If you have a 5th generation (or later) Microsoft Surface device, say
  160. + Y or M here.
  161. +
  162. +config SURFACE_SAM_SSH_DEBUG_DEVICE
  163. + bool "Surface Serial Hub Debug Device"
  164. + depends on SURFACE_SAM_SSH
  165. + depends on SYSFS
  166. + default n
  167. + help
  168. + Debug device for direct communication with the embedded controller
  169. + found on 5th generation (and later) Microsoft Surface devices (e.g.
  170. + Book 2, Laptop, Laptop 2, Pro 2017, Pro 6, ...) via sysfs.
  171. +
  172. + If you are not sure, say N here.
  173. +
  174. +config SURFACE_SAM_SAN
  175. + tristate "Surface ACPI Notify Driver"
  176. + depends on SURFACE_SAM_SSH
  177. + default m
  178. + help
  179. + Surface ACPI Notify driver for 5th generation (or later) Microsoft
  180. + Surface devices.
  181. +
  182. + This driver enables basic ACPI events and requests, such as battery
  183. + status requests/events, thermal events, lid status, and possibly more,
  184. + which would otherwise not work on these devices.
  185. +
  186. + If you are not sure, say M here.
  187. +
  188. +config SURFACE_SAM_VHF
  189. + tristate "Surface Virtual HID Framework Driver"
  190. + depends on SURFACE_SAM_SSH
  191. + depends on HID
  192. + default m
  193. + help
  194. + Surface Virtual HID Framework driver for 5th generation (or later)
  195. + Microsoft Surface devices.
  196. +
  197. + This driver provides support for the Microsoft Virtual HID framework,
  198. + which is required for keyboard support on the Surface Laptop 1 and 2.
  199. +
  200. + If you are not sure, say M here.
  201. +
  202. +config SURFACE_SAM_DTX
  203. + tristate "Surface Detachment System (DTX) Driver"
  204. + depends on SURFACE_SAM_SSH
  205. + depends on INPUT
  206. + default m
  207. + help
  208. + Surface Detachment System (DTX) driver for the Microsoft Surface Book
  209. + 2. This driver provides support for proper detachment handling in
  210. + user-space, status-events relating to the base and support for
  211. + the safe-guard keeping the base attached when the discrete GPU
  212. + contained in it is running via the special /dev/surface-dtx device.
  213. +
  214. + Also provides a standard input device to provide SW_TABLET_MODE events
  215. + upon device mode change.
  216. +
  217. + If you are not sure, say M here.
  218. +
  219. +config SURFACE_SAM_HPS
  220. + tristate "Surface dGPU Hot-Plug System (dGPU-HPS) Driver"
  221. + depends on SURFACE_SAM_SSH
  222. + depends on SURFACE_SAM_SAN
  223. + depends on GPIO_SYSFS
  224. + default m
  225. + help
  226. + Driver to properly handle hot-plugging and explicit power-on/power-off
  227. + of the discrete GPU (dGPU) on the Surface Book 2 and 3.
  228. +
  229. + If you are not sure, say M here.
  230. +
  231. +config SURFACE_SAM_SID
  232. + tristate "Surface Platform Integration Driver"
  233. + depends on SURFACE_SAM_SSH
  234. + default m
  235. + help
  236. + Surface Platform Integration Driver for the Microsoft Surface Devices.
  237. + This driver loads various model-specific sub-drivers, including
  238. + battery and keyboard support on 7th generation Surface devices, proper
  239. + lid setup to enable device wakeup when the lid is opened on multiple
  240. + models, as well as performance mode setting support on the Surface
  241. + Book 2.
  242. +
  243. + If you are not sure, say M here.
  244. +
  245. +config SURFACE_SAM_SID_GPELID
  246. + tristate "Surface Lid Wakeup Driver"
  247. + depends on SURFACE_SAM_SID
  248. + default m
  249. + help
  250. + Driver to set up device wake-up via lid on Intel-based Microsoft
  251. + Surface devices. These devices do not wake up from sleep as their GPE
  252. + interrupt is not configured automatically. This driver solves that
  253. + problem.
  254. +
  255. + If you are not sure, say M here.
  256. +
  257. +config SURFACE_SAM_SID_PERFMODE
  258. + tristate "Surface Performance Mode Driver"
  259. + depends on SURFACE_SAM_SID
  260. + depends on SYSFS
  261. + default m
  262. + help
  263. + This driver provides support for setting performance-modes on Surface
  264. + devices via the perf_mode sysfs attribute. Currently only supports the
  265. + Surface Book 2. Performance-modes directly influence the fan-profile
  266. + of the device, allowing to choose between higher performance or
  267. + quieter operation.
  268. +
  269. + If you are not sure, say M here.
  270. +
  271. +config SURFACE_SAM_SID_VHF
  272. + tristate "Surface SAM HID Driver"
  273. + depends on SURFACE_SAM_SID
  274. + depends on HID
  275. + default m
  276. + help
  277. + This driver provides support for HID devices connected via the Surface
  278. + SAM embedded controller. It provides support for keyboard and touchpad
  279. + on the Surface Laptop 3 models.
  280. +
  281. + If you are not sure, say M here.
  282. +
  283. +config SURFACE_SAM_SID_POWER
  284. + tristate "Surface SAM Battery/AC Driver"
  285. + depends on SURFACE_SAM_SID
  286. + select POWER_SUPPLY
  287. + default m
  288. + help
  289. + This driver provides support for the battery and AC on 7th generation
  290. + Surface devices.
  291. +
  292. + If you are not sure, say M here.
  293. diff --git a/drivers/platform/x86/surface_sam/Makefile b/drivers/platform/x86/surface_sam/Makefile
  294. new file mode 100644
  295. index 0000000000000..1a5c1260639dc
  296. --- /dev/null
  297. +++ b/drivers/platform/x86/surface_sam/Makefile
  298. @@ -0,0 +1,15 @@
  299. +# SPDX-License-Identifier: GPL-2.0-or-later
  300. +
  301. +# For include/trace/define_trace.h to include surface_sam_ssh_trace.h
  302. +CFLAGS_surface_sam_ssh.o = -I$(src)
  303. +
  304. +obj-$(CONFIG_SURFACE_SAM_SSH) += surface_sam_ssh.o
  305. +obj-$(CONFIG_SURFACE_SAM_SAN) += surface_sam_san.o
  306. +obj-$(CONFIG_SURFACE_SAM_DTX) += surface_sam_dtx.o
  307. +obj-$(CONFIG_SURFACE_SAM_HPS) += surface_sam_hps.o
  308. +obj-$(CONFIG_SURFACE_SAM_VHF) += surface_sam_vhf.o
  309. +obj-$(CONFIG_SURFACE_SAM_SID) += surface_sam_sid.o
  310. +obj-$(CONFIG_SURFACE_SAM_SID_GPELID) += surface_sam_sid_gpelid.o
  311. +obj-$(CONFIG_SURFACE_SAM_SID_PERFMODE) += surface_sam_sid_perfmode.o
  312. +obj-$(CONFIG_SURFACE_SAM_SID_POWER) += surface_sam_sid_power.o
  313. +obj-$(CONFIG_SURFACE_SAM_SID_VHF) += surface_sam_sid_vhf.o
  314. diff --git a/drivers/platform/x86/surface_sam/surface_sam_dtx.c b/drivers/platform/x86/surface_sam/surface_sam_dtx.c
  315. new file mode 100644
  316. index 0000000000000..88dba7bced3a4
  317. --- /dev/null
  318. +++ b/drivers/platform/x86/surface_sam/surface_sam_dtx.c
  319. @@ -0,0 +1,590 @@
  320. +// SPDX-License-Identifier: GPL-2.0-or-later
  321. +/*
  322. + * Detachment system (DTX) driver for Microsoft Surface Book 2.
  323. + */
  324. +
  325. +#include <linux/acpi.h>
  326. +#include <linux/delay.h>
  327. +#include <linux/fs.h>
  328. +#include <linux/input.h>
  329. +#include <linux/ioctl.h>
  330. +#include <linux/kernel.h>
  331. +#include <linux/miscdevice.h>
  332. +#include <linux/module.h>
  333. +#include <linux/poll.h>
  334. +#include <linux/rculist.h>
  335. +#include <linux/slab.h>
  336. +#include <linux/spinlock.h>
  337. +#include <linux/platform_device.h>
  338. +
  339. +#include "surface_sam_ssh.h"
  340. +
  341. +
  342. +#define USB_VENDOR_ID_MICROSOFT 0x045e
  343. +#define USB_DEVICE_ID_MS_SURFACE_BASE_2_INTEGRATION 0x0922
  344. +
  345. +// name copied from MS device manager
  346. +#define DTX_INPUT_NAME "Microsoft Surface Base 2 Integration Device"
  347. +
  348. +
  349. +#define DTX_CMD_LATCH_LOCK _IO(0x11, 0x01)
  350. +#define DTX_CMD_LATCH_UNLOCK _IO(0x11, 0x02)
  351. +#define DTX_CMD_LATCH_REQUEST _IO(0x11, 0x03)
  352. +#define DTX_CMD_LATCH_OPEN _IO(0x11, 0x04)
  353. +#define DTX_CMD_GET_OPMODE _IOR(0x11, 0x05, int)
  354. +
  355. +#define SAM_RQST_DTX_TC 0x11
  356. +#define SAM_RQST_DTX_CID_LATCH_LOCK 0x06
  357. +#define SAM_RQST_DTX_CID_LATCH_UNLOCK 0x07
  358. +#define SAM_RQST_DTX_CID_LATCH_REQUEST 0x08
  359. +#define SAM_RQST_DTX_CID_LATCH_OPEN 0x09
  360. +#define SAM_RQST_DTX_CID_GET_OPMODE 0x0D
  361. +
  362. +#define SAM_EVENT_DTX_CID_CONNECTION 0x0c
  363. +#define SAM_EVENT_DTX_CID_BUTTON 0x0e
  364. +#define SAM_EVENT_DTX_CID_ERROR 0x0f
  365. +#define SAM_EVENT_DTX_CID_LATCH_STATUS 0x11
  366. +
  367. +#define DTX_OPMODE_TABLET 0x00
  368. +#define DTX_OPMODE_LAPTOP 0x01
  369. +#define DTX_OPMODE_STUDIO 0x02
  370. +
  371. +#define DTX_LATCH_CLOSED 0x00
  372. +#define DTX_LATCH_OPENED 0x01
  373. +
  374. +
  375. +// Warning: This must always be a power of 2!
  376. +#define DTX_CLIENT_BUF_SIZE 16
  377. +
  378. +#define DTX_CONNECT_OPMODE_DELAY 1000
  379. +
  380. +#define DTX_ERR KERN_ERR "surface_sam_dtx: "
  381. +#define DTX_WARN KERN_WARNING "surface_sam_dtx: "
  382. +
  383. +
  384. +struct surface_dtx_event {
  385. + u8 type;
  386. + u8 code;
  387. + u8 arg0;
  388. + u8 arg1;
  389. +} __packed;
  390. +
  391. +struct surface_dtx_dev {
  392. + struct ssam_event_notifier notif;
  393. + struct delayed_work opmode_work;
  394. + wait_queue_head_t waitq;
  395. + struct miscdevice mdev;
  396. + spinlock_t client_lock;
  397. + struct list_head client_list;
  398. + struct mutex mutex;
  399. + bool active;
  400. + spinlock_t input_lock;
  401. + struct input_dev *input_dev;
  402. +};
  403. +
  404. +struct surface_dtx_client {
  405. + struct list_head node;
  406. + struct surface_dtx_dev *ddev;
  407. + struct fasync_struct *fasync;
  408. + spinlock_t buffer_lock;
  409. + unsigned int buffer_head;
  410. + unsigned int buffer_tail;
  411. + struct surface_dtx_event buffer[DTX_CLIENT_BUF_SIZE];
  412. +};
  413. +
  414. +
  415. +static struct surface_dtx_dev surface_dtx_dev;
  416. +
  417. +
  418. +static int surface_sam_query_opmpde(void)
  419. +{
  420. + u8 result_buf[1];
  421. + int status;
  422. +
  423. + struct surface_sam_ssh_rqst rqst = {
  424. + .tc = SAM_RQST_DTX_TC,
  425. + .cid = SAM_RQST_DTX_CID_GET_OPMODE,
  426. + .iid = 0x00,
  427. + .chn = 0x01,
  428. + .snc = 0x01,
  429. + .cdl = 0x00,
  430. + .pld = NULL,
  431. + };
  432. +
  433. + struct surface_sam_ssh_buf result = {
  434. + .cap = 1,
  435. + .len = 0,
  436. + .data = result_buf,
  437. + };
  438. +
  439. + status = surface_sam_ssh_rqst(&rqst, &result);
  440. + if (status)
  441. + return status;
  442. +
  443. + if (result.len != 1)
  444. + return -EFAULT;
  445. +
  446. + return result.data[0];
  447. +}
  448. +
  449. +
  450. +static int dtx_cmd_simple(u8 cid)
  451. +{
  452. + struct surface_sam_ssh_rqst rqst = {
  453. + .tc = SAM_RQST_DTX_TC,
  454. + .cid = cid,
  455. + .iid = 0x00,
  456. + .chn = 0x01,
  457. + .snc = 0x00,
  458. + .cdl = 0x00,
  459. + .pld = NULL,
  460. + };
  461. +
  462. + return surface_sam_ssh_rqst(&rqst, NULL);
  463. +}
  464. +
  465. +static int dtx_cmd_get_opmode(int __user *buf)
  466. +{
  467. + int opmode;
  468. +
  469. + opmode = surface_sam_query_opmpde();
  470. + if (opmode < 0)
  471. + return opmode;
  472. +
  473. + if (put_user(opmode, buf))
  474. + return -EACCES;
  475. +
  476. + return 0;
  477. +}
  478. +
  479. +
  480. +static int surface_dtx_open(struct inode *inode, struct file *file)
  481. +{
  482. + struct surface_dtx_dev *ddev = container_of(file->private_data, struct surface_dtx_dev, mdev);
  483. + struct surface_dtx_client *client;
  484. +
  485. + // initialize client
  486. + client = kzalloc(sizeof(struct surface_dtx_client), GFP_KERNEL);
  487. + if (!client)
  488. + return -ENOMEM;
  489. +
  490. + spin_lock_init(&client->buffer_lock);
  491. + client->buffer_head = 0;
  492. + client->buffer_tail = 0;
  493. + client->ddev = ddev;
  494. +
  495. + // attach client
  496. + spin_lock(&ddev->client_lock);
  497. + list_add_tail_rcu(&client->node, &ddev->client_list);
  498. + spin_unlock(&ddev->client_lock);
  499. +
  500. + file->private_data = client;
  501. + nonseekable_open(inode, file);
  502. +
  503. + return 0;
  504. +}
  505. +
  506. +static int surface_dtx_release(struct inode *inode, struct file *file)
  507. +{
  508. + struct surface_dtx_client *client = file->private_data;
  509. +
  510. + // detach client
  511. + spin_lock(&client->ddev->client_lock);
  512. + list_del_rcu(&client->node);
  513. + spin_unlock(&client->ddev->client_lock);
  514. + synchronize_rcu();
  515. +
  516. + kfree(client);
  517. + file->private_data = NULL;
  518. +
  519. + return 0;
  520. +}
  521. +
  522. +static ssize_t surface_dtx_read(struct file *file, char __user *buf, size_t count, loff_t *offs)
  523. +{
  524. + struct surface_dtx_client *client = file->private_data;
  525. + struct surface_dtx_dev *ddev = client->ddev;
  526. + struct surface_dtx_event event;
  527. + size_t read = 0;
  528. + int status = 0;
  529. +
  530. + if (count != 0 && count < sizeof(struct surface_dtx_event))
  531. + return -EINVAL;
  532. +
  533. + if (!ddev->active)
  534. + return -ENODEV;
  535. +
  536. + // check availability
  537. + if (client->buffer_head == client->buffer_tail) {
  538. + if (file->f_flags & O_NONBLOCK)
  539. + return -EAGAIN;
  540. +
  541. + status = wait_event_interruptible(ddev->waitq,
  542. + client->buffer_head != client->buffer_tail ||
  543. + !ddev->active);
  544. + if (status)
  545. + return status;
  546. +
  547. + if (!ddev->active)
  548. + return -ENODEV;
  549. + }
  550. +
  551. + // copy events one by one
  552. + while (read + sizeof(struct surface_dtx_event) <= count) {
  553. + spin_lock_irq(&client->buffer_lock);
  554. +
  555. + if (client->buffer_head == client->buffer_tail) {
  556. + spin_unlock_irq(&client->buffer_lock);
  557. + break;
  558. + }
  559. +
  560. + // get one event
  561. + event = client->buffer[client->buffer_tail];
  562. + client->buffer_tail = (client->buffer_tail + 1) & (DTX_CLIENT_BUF_SIZE - 1);
  563. + spin_unlock_irq(&client->buffer_lock);
  564. +
  565. + // copy to userspace
  566. + if (copy_to_user(buf, &event, sizeof(struct surface_dtx_event)))
  567. + return -EFAULT;
  568. +
  569. + read += sizeof(struct surface_dtx_event);
  570. + }
  571. +
  572. + return read;
  573. +}
  574. +
  575. +static __poll_t surface_dtx_poll(struct file *file, struct poll_table_struct *pt)
  576. +{
  577. + struct surface_dtx_client *client = file->private_data;
  578. + int mask;
  579. +
  580. + poll_wait(file, &client->ddev->waitq, pt);
  581. +
  582. + if (client->ddev->active)
  583. + mask = EPOLLOUT | EPOLLWRNORM;
  584. + else
  585. + mask = EPOLLHUP | EPOLLERR;
  586. +
  587. + if (client->buffer_head != client->buffer_tail)
  588. + mask |= EPOLLIN | EPOLLRDNORM;
  589. +
  590. + return mask;
  591. +}
  592. +
  593. +static int surface_dtx_fasync(int fd, struct file *file, int on)
  594. +{
  595. + struct surface_dtx_client *client = file->private_data;
  596. +
  597. + return fasync_helper(fd, file, on, &client->fasync);
  598. +}
  599. +
  600. +static long surface_dtx_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
  601. +{
  602. + struct surface_dtx_client *client = file->private_data;
  603. + struct surface_dtx_dev *ddev = client->ddev;
  604. + int status;
  605. +
  606. + status = mutex_lock_interruptible(&ddev->mutex);
  607. + if (status)
  608. + return status;
  609. +
  610. + if (!ddev->active) {
  611. + mutex_unlock(&ddev->mutex);
  612. + return -ENODEV;
  613. + }
  614. +
  615. + switch (cmd) {
  616. + case DTX_CMD_LATCH_LOCK:
  617. + status = dtx_cmd_simple(SAM_RQST_DTX_CID_LATCH_LOCK);
  618. + break;
  619. +
  620. + case DTX_CMD_LATCH_UNLOCK:
  621. + status = dtx_cmd_simple(SAM_RQST_DTX_CID_LATCH_UNLOCK);
  622. + break;
  623. +
  624. + case DTX_CMD_LATCH_REQUEST:
  625. + status = dtx_cmd_simple(SAM_RQST_DTX_CID_LATCH_REQUEST);
  626. + break;
  627. +
  628. + case DTX_CMD_LATCH_OPEN:
  629. + status = dtx_cmd_simple(SAM_RQST_DTX_CID_LATCH_OPEN);
  630. + break;
  631. +
  632. + case DTX_CMD_GET_OPMODE:
  633. + status = dtx_cmd_get_opmode((int __user *)arg);
  634. + break;
  635. +
  636. + default:
  637. + status = -EINVAL;
  638. + break;
  639. + }
  640. +
  641. + mutex_unlock(&ddev->mutex);
  642. + return status;
  643. +}
  644. +
  645. +static const struct file_operations surface_dtx_fops = {
  646. + .owner = THIS_MODULE,
  647. + .open = surface_dtx_open,
  648. + .release = surface_dtx_release,
  649. + .read = surface_dtx_read,
  650. + .poll = surface_dtx_poll,
  651. + .fasync = surface_dtx_fasync,
  652. + .unlocked_ioctl = surface_dtx_ioctl,
  653. + .llseek = no_llseek,
  654. +};
  655. +
  656. +static struct surface_dtx_dev surface_dtx_dev = {
  657. + .mdev = {
  658. + .minor = MISC_DYNAMIC_MINOR,
  659. + .name = "surface_dtx",
  660. + .fops = &surface_dtx_fops,
  661. + },
  662. + .client_lock = __SPIN_LOCK_UNLOCKED(),
  663. + .input_lock = __SPIN_LOCK_UNLOCKED(),
  664. + .mutex = __MUTEX_INITIALIZER(surface_dtx_dev.mutex),
  665. + .active = false,
  666. +};
  667. +
  668. +
  669. +static void surface_dtx_push_event(struct surface_dtx_dev *ddev, struct surface_dtx_event *event)
  670. +{
  671. + struct surface_dtx_client *client;
  672. +
  673. + rcu_read_lock();
  674. + list_for_each_entry_rcu(client, &ddev->client_list, node) {
  675. + spin_lock(&client->buffer_lock);
  676. +
  677. + client->buffer[client->buffer_head++] = *event;
  678. + client->buffer_head &= DTX_CLIENT_BUF_SIZE - 1;
  679. +
  680. + if (unlikely(client->buffer_head == client->buffer_tail)) {
  681. + printk(DTX_WARN "event buffer overrun\n");
  682. + client->buffer_tail = (client->buffer_tail + 1) & (DTX_CLIENT_BUF_SIZE - 1);
  683. + }
  684. +
  685. + spin_unlock(&client->buffer_lock);
  686. +
  687. + kill_fasync(&client->fasync, SIGIO, POLL_IN);
  688. + }
  689. + rcu_read_unlock();
  690. +
  691. + wake_up_interruptible(&ddev->waitq);
  692. +}
  693. +
  694. +
  695. +static void surface_dtx_update_opmpde(struct surface_dtx_dev *ddev)
  696. +{
  697. + struct surface_dtx_event event;
  698. + int opmode;
  699. +
  700. + // get operation mode
  701. + opmode = surface_sam_query_opmpde();
  702. + if (opmode < 0)
  703. + printk(DTX_ERR "EC request failed with error %d\n", opmode);
  704. +
  705. + // send DTX event
  706. + event.type = 0x11;
  707. + event.code = 0x0D;
  708. + event.arg0 = opmode;
  709. + event.arg1 = 0x00;
  710. +
  711. + surface_dtx_push_event(ddev, &event);
  712. +
  713. + // send SW_TABLET_MODE event
  714. + spin_lock(&ddev->input_lock);
  715. + input_report_switch(ddev->input_dev, SW_TABLET_MODE, opmode != DTX_OPMODE_LAPTOP);
  716. + input_sync(ddev->input_dev);
  717. + spin_unlock(&ddev->input_lock);
  718. +}
  719. +
  720. +static void surface_dtx_opmode_workfn(struct work_struct *work)
  721. +{
  722. + struct surface_dtx_dev *ddev = container_of(work, struct surface_dtx_dev, opmode_work.work);
  723. +
  724. + surface_dtx_update_opmpde(ddev);
  725. +}
  726. +
  727. +static u32 surface_dtx_notification(struct ssam_notifier_block *nb, const struct ssam_event *in_event)
  728. +{
  729. + struct surface_dtx_dev *ddev = container_of(nb, struct surface_dtx_dev, notif.base);
  730. + struct surface_dtx_event event;
  731. + unsigned long delay;
  732. +
  733. + switch (in_event->command_id) {
  734. + case SAM_EVENT_DTX_CID_CONNECTION:
  735. + case SAM_EVENT_DTX_CID_BUTTON:
  736. + case SAM_EVENT_DTX_CID_ERROR:
  737. + case SAM_EVENT_DTX_CID_LATCH_STATUS:
  738. + if (in_event->length > 2) {
  739. + printk(DTX_ERR "unexpected payload size (cid: %x, len: %u)\n",
  740. + in_event->command_id, in_event->length);
  741. + return SSAM_NOTIF_HANDLED;
  742. + }
  743. +
  744. + event.type = in_event->target_category;
  745. + event.code = in_event->command_id;
  746. + event.arg0 = in_event->length >= 1 ? in_event->data[0] : 0x00;
  747. + event.arg1 = in_event->length >= 2 ? in_event->data[1] : 0x00;
  748. + surface_dtx_push_event(ddev, &event);
  749. + break;
  750. +
  751. + default:
  752. + return 0;
  753. + }
  754. +
  755. + // update device mode
  756. + if (in_event->command_id == SAM_EVENT_DTX_CID_CONNECTION) {
  757. + delay = event.arg0 ? DTX_CONNECT_OPMODE_DELAY : 0;
  758. + schedule_delayed_work(&ddev->opmode_work, delay);
  759. + }
  760. +
  761. + return SSAM_NOTIF_HANDLED;
  762. +}
  763. +
  764. +
  765. +static struct input_dev *surface_dtx_register_inputdev(struct platform_device *pdev)
  766. +{
  767. + struct input_dev *input_dev;
  768. + int status;
  769. +
  770. + input_dev = input_allocate_device();
  771. + if (!input_dev)
  772. + return ERR_PTR(-ENOMEM);
  773. +
  774. + input_dev->name = DTX_INPUT_NAME;
  775. + input_dev->dev.parent = &pdev->dev;
  776. + input_dev->id.bustype = BUS_VIRTUAL;
  777. + input_dev->id.vendor = USB_VENDOR_ID_MICROSOFT;
  778. + input_dev->id.product = USB_DEVICE_ID_MS_SURFACE_BASE_2_INTEGRATION;
  779. +
  780. + input_set_capability(input_dev, EV_SW, SW_TABLET_MODE);
  781. +
  782. + status = surface_sam_query_opmpde();
  783. + if (status < 0) {
  784. + input_free_device(input_dev);
  785. + return ERR_PTR(status);
  786. + }
  787. +
  788. + input_report_switch(input_dev, SW_TABLET_MODE, status != DTX_OPMODE_LAPTOP);
  789. +
  790. + status = input_register_device(input_dev);
  791. + if (status) {
  792. + input_unregister_device(input_dev);
  793. + return ERR_PTR(status);
  794. + }
  795. +
  796. + return input_dev;
  797. +}
  798. +
  799. +
  800. +static int surface_sam_dtx_probe(struct platform_device *pdev)
  801. +{
  802. + struct surface_dtx_dev *ddev = &surface_dtx_dev;
  803. + struct input_dev *input_dev;
  804. + int status;
  805. +
  806. + // link to ec
  807. + status = surface_sam_ssh_consumer_register(&pdev->dev);
  808. + if (status)
  809. + return status == -ENXIO ? -EPROBE_DEFER : status;
  810. +
  811. + input_dev = surface_dtx_register_inputdev(pdev);
  812. + if (IS_ERR(input_dev))
  813. + return PTR_ERR(input_dev);
  814. +
  815. + // initialize device
  816. + mutex_lock(&ddev->mutex);
  817. + if (ddev->active) {
  818. + mutex_unlock(&ddev->mutex);
  819. + status = -ENODEV;
  820. + goto err_register;
  821. + }
  822. +
  823. + INIT_DELAYED_WORK(&ddev->opmode_work, surface_dtx_opmode_workfn);
  824. + INIT_LIST_HEAD(&ddev->client_list);
  825. + init_waitqueue_head(&ddev->waitq);
  826. + ddev->active = true;
  827. + ddev->input_dev = input_dev;
  828. + mutex_unlock(&ddev->mutex);
  829. +
  830. + status = misc_register(&ddev->mdev);
  831. + if (status)
  832. + goto err_register;
  833. +
  834. + // set up events
  835. + ddev->notif.base.priority = 1;
  836. + ddev->notif.base.fn = surface_dtx_notification;
  837. + ddev->notif.event.reg = SSAM_EVENT_REGISTRY_SAM;
  838. + ddev->notif.event.id.target_category = SSAM_SSH_TC_BAS;
  839. + ddev->notif.event.id.instance = 0;
  840. + ddev->notif.event.flags = SSAM_EVENT_SEQUENCED;
  841. +
  842. + status = surface_sam_ssh_notifier_register(&ddev->notif);
  843. + if (status)
  844. + goto err_events_setup;
  845. +
  846. + return 0;
  847. +
  848. +err_events_setup:
  849. + misc_deregister(&ddev->mdev);
  850. +err_register:
  851. + input_unregister_device(ddev->input_dev);
  852. + return status;
  853. +}
  854. +
  855. +static int surface_sam_dtx_remove(struct platform_device *pdev)
  856. +{
  857. + struct surface_dtx_dev *ddev = &surface_dtx_dev;
  858. + struct surface_dtx_client *client;
  859. +
  860. + mutex_lock(&ddev->mutex);
  861. + if (!ddev->active) {
  862. + mutex_unlock(&ddev->mutex);
  863. + return 0;
  864. + }
  865. +
  866. + // mark as inactive
  867. + ddev->active = false;
  868. + mutex_unlock(&ddev->mutex);
  869. +
  870. + // After this call we're guaranteed that no more input events will arive
  871. + surface_sam_ssh_notifier_unregister(&ddev->notif);
  872. +
  873. + // wake up clients
  874. + spin_lock(&ddev->client_lock);
  875. + list_for_each_entry(client, &ddev->client_list, node) {
  876. + kill_fasync(&client->fasync, SIGIO, POLL_HUP);
  877. + }
  878. + spin_unlock(&ddev->client_lock);
  879. +
  880. + wake_up_interruptible(&ddev->waitq);
  881. +
  882. + // unregister user-space devices
  883. + input_unregister_device(ddev->input_dev);
  884. + misc_deregister(&ddev->mdev);
  885. +
  886. + return 0;
  887. +}
  888. +
  889. +
  890. +static const struct acpi_device_id surface_sam_dtx_match[] = {
  891. + { "MSHW0133", 0 },
  892. + { },
  893. +};
  894. +MODULE_DEVICE_TABLE(acpi, surface_sam_dtx_match);
  895. +
  896. +static struct platform_driver surface_sam_dtx = {
  897. + .probe = surface_sam_dtx_probe,
  898. + .remove = surface_sam_dtx_remove,
  899. + .driver = {
  900. + .name = "surface_sam_dtx",
  901. + .acpi_match_table = surface_sam_dtx_match,
  902. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  903. + },
  904. +};
  905. +module_platform_driver(surface_sam_dtx);
  906. +
  907. +MODULE_AUTHOR("Maximilian Luz <luzmaximilian@gmail.com>");
  908. +MODULE_DESCRIPTION("Surface Detachment System (DTX) Driver for 5th Generation Surface Devices");
  909. +MODULE_LICENSE("GPL");
  910. diff --git a/drivers/platform/x86/surface_sam/surface_sam_hps.c b/drivers/platform/x86/surface_sam/surface_sam_hps.c
  911. new file mode 100644
  912. index 0000000000000..40f39f29113c5
  913. --- /dev/null
  914. +++ b/drivers/platform/x86/surface_sam/surface_sam_hps.c
  915. @@ -0,0 +1,1297 @@
  916. +// SPDX-License-Identifier: GPL-2.0-or-later
  917. +/*
  918. + * Surface dGPU hot-plug system driver.
  919. + * Supports explicit setting of the dGPU power-state on the Surface Book 2 and
  920. + * properly handles hot-plugging by detaching the base.
  921. + */
  922. +
  923. +#include <linux/acpi.h>
  924. +#include <linux/delay.h>
  925. +#include <linux/gpio.h>
  926. +#include <linux/kernel.h>
  927. +#include <linux/module.h>
  928. +#include <linux/mutex.h>
  929. +#include <linux/pci.h>
  930. +#include <linux/platform_device.h>
  931. +#include <linux/sysfs.h>
  932. +
  933. +#include "surface_sam_ssh.h"
  934. +#include "surface_sam_san.h"
  935. +
  936. +
  937. +// TODO: vgaswitcheroo integration
  938. +
  939. +
  940. +static void dbg_dump_drvsta(struct platform_device *pdev, const char *prefix);
  941. +
  942. +
  943. +#define SHPS_DSM_REVISION 1
  944. +#define SHPS_DSM_GPU_ADDRS 0x02
  945. +#define SHPS_DSM_GPU_POWER 0x05
  946. +static const guid_t SHPS_DSM_UUID =
  947. + GUID_INIT(0x5515a847, 0xed55, 0x4b27, 0x83, 0x52, 0xcd,
  948. + 0x32, 0x0e, 0x10, 0x36, 0x0a);
  949. +
  950. +
  951. +#define SAM_DGPU_TC 0x13
  952. +#define SAM_DGPU_CID_POWERON 0x02
  953. +
  954. +#define SAM_DTX_TC 0x11
  955. +#define SAM_DTX_CID_LATCH_LOCK 0x06
  956. +#define SAM_DTX_CID_LATCH_UNLOCK 0x07
  957. +#define ACPI_SGCP_NOTIFY_POWER_ON 0x81
  958. +
  959. +#define SHPS_DSM_GPU_ADDRS_RP "RP5_PCIE"
  960. +#define SHPS_DSM_GPU_ADDRS_DGPU "DGPU_PCIE"
  961. +#define SHPS_PCI_GPU_ADDR_RP "\\_SB.PCI0.RP13._ADR"
  962. +
  963. +static const struct acpi_gpio_params gpio_base_presence_int = { 0, 0, false };
  964. +static const struct acpi_gpio_params gpio_base_presence = { 1, 0, false };
  965. +static const struct acpi_gpio_params gpio_dgpu_power_int = { 2, 0, false };
  966. +static const struct acpi_gpio_params gpio_dgpu_power = { 3, 0, false };
  967. +static const struct acpi_gpio_params gpio_dgpu_presence_int = { 4, 0, false };
  968. +static const struct acpi_gpio_params gpio_dgpu_presence = { 5, 0, false };
  969. +
  970. +static const struct acpi_gpio_mapping shps_acpi_gpios[] = {
  971. + { "base_presence-int-gpio", &gpio_base_presence_int, 1 },
  972. + { "base_presence-gpio", &gpio_base_presence, 1 },
  973. + { "dgpu_power-int-gpio", &gpio_dgpu_power_int, 1 },
  974. + { "dgpu_power-gpio", &gpio_dgpu_power, 1 },
  975. + { "dgpu_presence-int-gpio", &gpio_dgpu_presence_int, 1 },
  976. + { "dgpu_presence-gpio", &gpio_dgpu_presence, 1 },
  977. + { },
  978. +};
  979. +
  980. +
  981. +enum shps_dgpu_power {
  982. + SHPS_DGPU_POWER_OFF = 0,
  983. + SHPS_DGPU_POWER_ON = 1,
  984. + SHPS_DGPU_POWER_UNKNOWN = 2,
  985. +};
  986. +
  987. +static const char *shps_dgpu_power_str(enum shps_dgpu_power power)
  988. +{
  989. + if (power == SHPS_DGPU_POWER_OFF)
  990. + return "off";
  991. + else if (power == SHPS_DGPU_POWER_ON)
  992. + return "on";
  993. + else if (power == SHPS_DGPU_POWER_UNKNOWN)
  994. + return "unknown";
  995. + else
  996. + return "<invalid>";
  997. +}
  998. +
  999. +enum shps_notification_method {
  1000. + SHPS_NOTIFICATION_METHOD_SAN = 1,
  1001. + SHPS_NOTIFICATION_METHOD_SGCP = 2
  1002. +};
  1003. +
  1004. +struct shps_hardware_traits {
  1005. + enum shps_notification_method notification_method;
  1006. + const char *dgpu_rp_pci_address;
  1007. +};
  1008. +
  1009. +struct shps_driver_data {
  1010. + struct mutex lock;
  1011. + struct pci_dev *dgpu_root_port;
  1012. + struct pci_saved_state *dgpu_root_port_state;
  1013. + struct gpio_desc *gpio_dgpu_power;
  1014. + struct gpio_desc *gpio_dgpu_presence;
  1015. + struct gpio_desc *gpio_base_presence;
  1016. + unsigned int irq_dgpu_presence;
  1017. + unsigned int irq_base_presence;
  1018. + unsigned long state;
  1019. + acpi_handle sgpc_handle;
  1020. + struct shps_hardware_traits hardware_traits;
  1021. +};
  1022. +
  1023. +struct shps_hardware_probe {
  1024. + const char *hardware_id;
  1025. + int generation;
  1026. + struct shps_hardware_traits *hardware_traits;
  1027. +};
  1028. +
  1029. +static struct shps_hardware_traits shps_gen1_hwtraits = {
  1030. + .notification_method = SHPS_NOTIFICATION_METHOD_SAN
  1031. +};
  1032. +
  1033. +static struct shps_hardware_traits shps_gen2_hwtraits = {
  1034. + .notification_method = SHPS_NOTIFICATION_METHOD_SGCP,
  1035. + .dgpu_rp_pci_address = SHPS_PCI_GPU_ADDR_RP
  1036. +};
  1037. +
  1038. +static const struct shps_hardware_probe shps_hardware_probe_match[] = {
  1039. + /* Surface Book 3 */
  1040. + { "MSHW0117", 2, &shps_gen2_hwtraits },
  1041. +
  1042. + /* Surface Book 2 (default, must be last entry) */
  1043. + { NULL, 1, &shps_gen1_hwtraits }
  1044. +};
  1045. +
  1046. +#define SHPS_STATE_BIT_PWRTGT 0 /* desired power state: 1 for on, 0 for off */
  1047. +#define SHPS_STATE_BIT_RPPWRON_SYNC 1 /* synchronous/requested power-up in progress */
  1048. +#define SHPS_STATE_BIT_WAKE_ENABLED 2 /* wakeup via base-presence GPIO enabled */
  1049. +
  1050. +
  1051. +#define SHPS_DGPU_PARAM_PERM 0644
  1052. +
  1053. +enum shps_dgpu_power_mp {
  1054. + SHPS_DGPU_MP_POWER_OFF = SHPS_DGPU_POWER_OFF,
  1055. + SHPS_DGPU_MP_POWER_ON = SHPS_DGPU_POWER_ON,
  1056. + SHPS_DGPU_MP_POWER_ASIS = -1,
  1057. +
  1058. + __SHPS_DGPU_MP_POWER_START = -1,
  1059. + __SHPS_DGPU_MP_POWER_END = 1,
  1060. +};
  1061. +
  1062. +static int param_dgpu_power_set(const char *val, const struct kernel_param *kp)
  1063. +{
  1064. + int power = SHPS_DGPU_MP_POWER_OFF;
  1065. + int status;
  1066. +
  1067. + status = kstrtoint(val, 0, &power);
  1068. + if (status)
  1069. + return status;
  1070. +
  1071. + if (power < __SHPS_DGPU_MP_POWER_START || power > __SHPS_DGPU_MP_POWER_END)
  1072. + return -EINVAL;
  1073. +
  1074. + return param_set_int(val, kp);
  1075. +}
  1076. +
  1077. +static const struct kernel_param_ops param_dgpu_power_ops = {
  1078. + .set = param_dgpu_power_set,
  1079. + .get = param_get_int,
  1080. +};
  1081. +
  1082. +static int param_dgpu_power_init = SHPS_DGPU_MP_POWER_OFF;
  1083. +static int param_dgpu_power_exit = SHPS_DGPU_MP_POWER_ON;
  1084. +static int param_dgpu_power_susp = SHPS_DGPU_MP_POWER_ASIS;
  1085. +static bool param_dtx_latch = true;
  1086. +
  1087. +module_param_cb(dgpu_power_init, &param_dgpu_power_ops, &param_dgpu_power_init, SHPS_DGPU_PARAM_PERM);
  1088. +module_param_cb(dgpu_power_exit, &param_dgpu_power_ops, &param_dgpu_power_exit, SHPS_DGPU_PARAM_PERM);
  1089. +module_param_cb(dgpu_power_susp, &param_dgpu_power_ops, &param_dgpu_power_susp, SHPS_DGPU_PARAM_PERM);
  1090. +module_param_named(dtx_latch, param_dtx_latch, bool, SHPS_DGPU_PARAM_PERM);
  1091. +
  1092. +MODULE_PARM_DESC(dgpu_power_init, "dGPU power state to be set on init (0: off / 1: on / 2: as-is, default: off)");
  1093. +MODULE_PARM_DESC(dgpu_power_exit, "dGPU power state to be set on exit (0: off / 1: on / 2: as-is, default: on)");
  1094. +MODULE_PARM_DESC(dgpu_power_susp, "dGPU power state to be set on exit (0: off / 1: on / 2: as-is, default: as-is)");
  1095. +MODULE_PARM_DESC(dtx_latch, "lock/unlock DTX base latch in accordance to power-state (Y/n)");
  1096. +
  1097. +static int dtx_cmd_simple(u8 cid)
  1098. +{
  1099. + struct surface_sam_ssh_rqst rqst = {
  1100. + .tc = SAM_DTX_TC,
  1101. + .cid = cid,
  1102. + .iid = 0x00,
  1103. + .chn = 0x01,
  1104. + .snc = 0x00,
  1105. + .cdl = 0x00,
  1106. + .pld = NULL,
  1107. + };
  1108. +
  1109. + return surface_sam_ssh_rqst(&rqst, NULL);
  1110. +}
  1111. +
  1112. +static inline int shps_dtx_latch_lock(void)
  1113. +{
  1114. + return dtx_cmd_simple(SAM_DTX_CID_LATCH_LOCK);
  1115. +}
  1116. +
  1117. +static inline int shps_dtx_latch_unlock(void)
  1118. +{
  1119. + return dtx_cmd_simple(SAM_DTX_CID_LATCH_UNLOCK);
  1120. +}
  1121. +
  1122. +static int shps_dgpu_dsm_get_pci_addr_from_adr(struct platform_device *pdev, const char *entry) {
  1123. + acpi_handle handle = ACPI_HANDLE(&pdev->dev);
  1124. + int status;
  1125. + struct acpi_object_list input;
  1126. + union acpi_object input_args[0];
  1127. + u64 device_addr;
  1128. + u8 bus, dev, fun;
  1129. +
  1130. + input.count = 0;
  1131. + input.pointer = input_args;
  1132. +
  1133. +
  1134. + status = acpi_evaluate_integer(handle, (acpi_string)entry, &input, &device_addr);
  1135. + if (status) {
  1136. + return -ENODEV;
  1137. + }
  1138. +
  1139. + bus = 0;
  1140. + dev = (device_addr & 0xFF0000) >> 16;
  1141. + fun = device_addr & 0xFF;
  1142. +
  1143. + dev_info(&pdev->dev, "found pci device at bus = %d, dev = %x, fun = %x\n",
  1144. + (u32)bus, (u32)dev, (u32)fun);
  1145. +
  1146. + return bus << 8 | PCI_DEVFN(dev, fun);
  1147. +}
  1148. +
  1149. +static int shps_dgpu_dsm_get_pci_addr_from_dsm(struct platform_device *pdev, const char *entry)
  1150. +{
  1151. + acpi_handle handle = ACPI_HANDLE(&pdev->dev);
  1152. + union acpi_object *result;
  1153. + union acpi_object *e0;
  1154. + union acpi_object *e1;
  1155. + union acpi_object *e2;
  1156. + u64 device_addr = 0;
  1157. + u8 bus, dev, fun;
  1158. + int i;
  1159. +
  1160. +
  1161. + result = acpi_evaluate_dsm_typed(handle, &SHPS_DSM_UUID, SHPS_DSM_REVISION,
  1162. + SHPS_DSM_GPU_ADDRS, NULL, ACPI_TYPE_PACKAGE);
  1163. +
  1164. + if (IS_ERR_OR_NULL(result))
  1165. + return result ? PTR_ERR(result) : -EIO;
  1166. +
  1167. + // three entries per device: name, address, <integer>
  1168. + for (i = 0; i + 2 < result->package.count; i += 3) {
  1169. + e0 = &result->package.elements[i];
  1170. + e1 = &result->package.elements[i + 1];
  1171. + e2 = &result->package.elements[i + 2];
  1172. +
  1173. + if (e0->type != ACPI_TYPE_STRING) {
  1174. + ACPI_FREE(result);
  1175. + return -EIO;
  1176. + }
  1177. +
  1178. + if (e1->type != ACPI_TYPE_INTEGER) {
  1179. + ACPI_FREE(result);
  1180. + return -EIO;
  1181. + }
  1182. +
  1183. + if (e2->type != ACPI_TYPE_INTEGER) {
  1184. + ACPI_FREE(result);
  1185. + return -EIO;
  1186. + }
  1187. +
  1188. + if (strncmp(e0->string.pointer, entry, 64) == 0)
  1189. + device_addr = e1->integer.value;
  1190. + }
  1191. +
  1192. + ACPI_FREE(result);
  1193. + if (device_addr == 0)
  1194. + return -ENODEV;
  1195. +
  1196. +
  1197. + // convert address
  1198. + bus = (device_addr & 0x0FF00000) >> 20;
  1199. + dev = (device_addr & 0x000F8000) >> 15;
  1200. + fun = (device_addr & 0x00007000) >> 12;
  1201. +
  1202. + return bus << 8 | PCI_DEVFN(dev, fun);
  1203. +}
  1204. +
  1205. +static struct pci_dev *shps_dgpu_dsm_get_pci_dev(struct platform_device *pdev)
  1206. +{
  1207. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1208. + struct pci_dev *dev;
  1209. + int addr;
  1210. +
  1211. +
  1212. + if (drvdata->hardware_traits.dgpu_rp_pci_address) {
  1213. + addr = shps_dgpu_dsm_get_pci_addr_from_adr(pdev, drvdata->hardware_traits.dgpu_rp_pci_address);
  1214. + } else {
  1215. + addr = shps_dgpu_dsm_get_pci_addr_from_dsm(pdev, SHPS_DSM_GPU_ADDRS_RP);
  1216. + }
  1217. +
  1218. + if (addr < 0)
  1219. + return ERR_PTR(addr);
  1220. +
  1221. + dev = pci_get_domain_bus_and_slot(0, (addr & 0xFF00) >> 8, addr & 0xFF);
  1222. + return dev ? dev : ERR_PTR(-ENODEV);
  1223. +}
  1224. +
  1225. +
  1226. +static int shps_dgpu_dsm_get_power_unlocked(struct platform_device *pdev)
  1227. +{
  1228. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1229. + struct gpio_desc *gpio = drvdata->gpio_dgpu_power;
  1230. + int status;
  1231. +
  1232. + status = gpiod_get_value_cansleep(gpio);
  1233. + if (status < 0)
  1234. + return status;
  1235. +
  1236. + return status == 0 ? SHPS_DGPU_POWER_OFF : SHPS_DGPU_POWER_ON;
  1237. +}
  1238. +
  1239. +static int shps_dgpu_dsm_get_power(struct platform_device *pdev)
  1240. +{
  1241. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1242. + int status;
  1243. +
  1244. + mutex_lock(&drvdata->lock);
  1245. + status = shps_dgpu_dsm_get_power_unlocked(pdev);
  1246. + mutex_unlock(&drvdata->lock);
  1247. +
  1248. + return status;
  1249. +}
  1250. +
  1251. +static int __shps_dgpu_dsm_set_power_unlocked(struct platform_device *pdev, enum shps_dgpu_power power)
  1252. +{
  1253. + acpi_handle handle = ACPI_HANDLE(&pdev->dev);
  1254. + union acpi_object *result;
  1255. + union acpi_object param;
  1256. +
  1257. + dev_info(&pdev->dev, "setting dGPU direct power to \'%s\'\n", shps_dgpu_power_str(power));
  1258. +
  1259. + param.type = ACPI_TYPE_INTEGER;
  1260. + param.integer.value = power == SHPS_DGPU_POWER_ON;
  1261. +
  1262. + result = acpi_evaluate_dsm_typed(handle, &SHPS_DSM_UUID, SHPS_DSM_REVISION,
  1263. + SHPS_DSM_GPU_POWER, &param, ACPI_TYPE_BUFFER);
  1264. +
  1265. + if (IS_ERR_OR_NULL(result))
  1266. + return result ? PTR_ERR(result) : -EIO;
  1267. +
  1268. + // check for the expected result
  1269. + if (result->buffer.length != 1 || result->buffer.pointer[0] != 0) {
  1270. + ACPI_FREE(result);
  1271. + return -EIO;
  1272. + }
  1273. +
  1274. + ACPI_FREE(result);
  1275. + return 0;
  1276. +}
  1277. +
  1278. +static int shps_dgpu_dsm_set_power_unlocked(struct platform_device *pdev, enum shps_dgpu_power power)
  1279. +{
  1280. + int status;
  1281. +
  1282. + if (power != SHPS_DGPU_POWER_ON && power != SHPS_DGPU_POWER_OFF)
  1283. + return -EINVAL;
  1284. +
  1285. + status = shps_dgpu_dsm_get_power_unlocked(pdev);
  1286. + if (status < 0)
  1287. + return status;
  1288. + if (status == power)
  1289. + return 0;
  1290. +
  1291. + return __shps_dgpu_dsm_set_power_unlocked(pdev, power);
  1292. +}
  1293. +
  1294. +static int shps_dgpu_dsm_set_power(struct platform_device *pdev, enum shps_dgpu_power power)
  1295. +{
  1296. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1297. + int status;
  1298. +
  1299. + mutex_lock(&drvdata->lock);
  1300. + status = shps_dgpu_dsm_set_power_unlocked(pdev, power);
  1301. + mutex_unlock(&drvdata->lock);
  1302. +
  1303. + return status;
  1304. +}
  1305. +
  1306. +
  1307. +static bool shps_rp_link_up(struct pci_dev *rp)
  1308. +{
  1309. + u16 lnksta = 0, sltsta = 0;
  1310. +
  1311. + pcie_capability_read_word(rp, PCI_EXP_LNKSTA, &lnksta);
  1312. + pcie_capability_read_word(rp, PCI_EXP_SLTSTA, &sltsta);
  1313. +
  1314. + return (lnksta & PCI_EXP_LNKSTA_DLLLA) || (sltsta & PCI_EXP_SLTSTA_PDS);
  1315. +}
  1316. +
  1317. +
  1318. +static int shps_dgpu_rp_get_power_unlocked(struct platform_device *pdev)
  1319. +{
  1320. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1321. + struct pci_dev *rp = drvdata->dgpu_root_port;
  1322. +
  1323. + if (rp->current_state == PCI_D3hot || rp->current_state == PCI_D3cold)
  1324. + return SHPS_DGPU_POWER_OFF;
  1325. + else if (rp->current_state == PCI_UNKNOWN || rp->current_state == PCI_POWER_ERROR)
  1326. + return SHPS_DGPU_POWER_UNKNOWN;
  1327. + else
  1328. + return SHPS_DGPU_POWER_ON;
  1329. +}
  1330. +
  1331. +static int shps_dgpu_rp_get_power(struct platform_device *pdev)
  1332. +{
  1333. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1334. + int status;
  1335. +
  1336. + mutex_lock(&drvdata->lock);
  1337. + status = shps_dgpu_rp_get_power_unlocked(pdev);
  1338. + mutex_unlock(&drvdata->lock);
  1339. +
  1340. + return status;
  1341. +}
  1342. +
  1343. +static int __shps_dgpu_rp_set_power_unlocked(struct platform_device *pdev, enum shps_dgpu_power power)
  1344. +{
  1345. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1346. + struct pci_dev *rp = drvdata->dgpu_root_port;
  1347. + int status, i;
  1348. +
  1349. + dev_info(&pdev->dev, "setting dGPU power state to \'%s\'\n", shps_dgpu_power_str(power));
  1350. +
  1351. + dbg_dump_drvsta(pdev, "__shps_dgpu_rp_set_power_unlocked.1");
  1352. + if (power == SHPS_DGPU_POWER_ON) {
  1353. + set_bit(SHPS_STATE_BIT_RPPWRON_SYNC, &drvdata->state);
  1354. + pci_set_power_state(rp, PCI_D0);
  1355. +
  1356. + if (drvdata->dgpu_root_port_state)
  1357. + pci_load_and_free_saved_state(rp, &drvdata->dgpu_root_port_state);
  1358. +
  1359. + pci_restore_state(rp);
  1360. +
  1361. + if (!pci_is_enabled(rp))
  1362. + pci_enable_device(rp);
  1363. +
  1364. + pci_set_master(rp);
  1365. + clear_bit(SHPS_STATE_BIT_RPPWRON_SYNC, &drvdata->state);
  1366. +
  1367. + set_bit(SHPS_STATE_BIT_PWRTGT, &drvdata->state);
  1368. + } else {
  1369. + if (!drvdata->dgpu_root_port_state) {
  1370. + pci_save_state(rp);
  1371. + drvdata->dgpu_root_port_state = pci_store_saved_state(rp);
  1372. + }
  1373. +
  1374. + /*
  1375. + * To properly update the hot-plug system we need to "remove" the dGPU
  1376. + * before disabling it and sending it to D3cold. Following this, we
  1377. + * need to wait for the link and slot status to actually change.
  1378. + */
  1379. + status = shps_dgpu_dsm_set_power_unlocked(pdev, SHPS_DGPU_POWER_OFF);
  1380. + if (status)
  1381. + return status;
  1382. +
  1383. + for (i = 0; i < 20 && shps_rp_link_up(rp); i++)
  1384. + msleep(50);
  1385. +
  1386. + if (shps_rp_link_up(rp))
  1387. + dev_err(&pdev->dev, "dGPU removal via DSM timed out\n");
  1388. +
  1389. + pci_clear_master(rp);
  1390. +
  1391. + if (pci_is_enabled(rp))
  1392. + pci_disable_device(rp);
  1393. +
  1394. + pci_set_power_state(rp, PCI_D3cold);
  1395. +
  1396. + clear_bit(SHPS_STATE_BIT_PWRTGT, &drvdata->state);
  1397. + }
  1398. + dbg_dump_drvsta(pdev, "__shps_dgpu_rp_set_power_unlocked.2");
  1399. +
  1400. + return 0;
  1401. +}
  1402. +
  1403. +static int shps_dgpu_rp_set_power_unlocked(struct platform_device *pdev, enum shps_dgpu_power power)
  1404. +{
  1405. + int status;
  1406. +
  1407. + if (power != SHPS_DGPU_POWER_ON && power != SHPS_DGPU_POWER_OFF)
  1408. + return -EINVAL;
  1409. +
  1410. + status = shps_dgpu_rp_get_power_unlocked(pdev);
  1411. + if (status < 0)
  1412. + return status;
  1413. + if (status == power)
  1414. + return 0;
  1415. +
  1416. + return __shps_dgpu_rp_set_power_unlocked(pdev, power);
  1417. +}
  1418. +
  1419. +static int shps_dgpu_rp_set_power(struct platform_device *pdev, enum shps_dgpu_power power)
  1420. +{
  1421. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1422. + int status;
  1423. +
  1424. + mutex_lock(&drvdata->lock);
  1425. + status = shps_dgpu_rp_set_power_unlocked(pdev, power);
  1426. + mutex_unlock(&drvdata->lock);
  1427. +
  1428. + return status;
  1429. +}
  1430. +
  1431. +
  1432. +static int shps_dgpu_set_power(struct platform_device *pdev, enum shps_dgpu_power power)
  1433. +{
  1434. + int status;
  1435. +
  1436. + if (!param_dtx_latch)
  1437. + return shps_dgpu_rp_set_power(pdev, power);
  1438. +
  1439. + if (power == SHPS_DGPU_POWER_ON) {
  1440. + status = shps_dtx_latch_lock();
  1441. + if (status)
  1442. + return status;
  1443. +
  1444. + status = shps_dgpu_rp_set_power(pdev, power);
  1445. + if (status)
  1446. + shps_dtx_latch_unlock();
  1447. +
  1448. + } else {
  1449. + status = shps_dgpu_rp_set_power(pdev, power);
  1450. + if (status)
  1451. + return status;
  1452. +
  1453. + status = shps_dtx_latch_unlock();
  1454. + }
  1455. +
  1456. + return status;
  1457. +}
  1458. +
  1459. +
  1460. +static int shps_dgpu_is_present(struct platform_device *pdev)
  1461. +{
  1462. + struct shps_driver_data *drvdata;
  1463. +
  1464. + drvdata = platform_get_drvdata(pdev);
  1465. + return gpiod_get_value_cansleep(drvdata->gpio_dgpu_presence);
  1466. +}
  1467. +
  1468. +
  1469. +static ssize_t dgpu_power_show(struct device *dev, struct device_attribute *attr, char *data)
  1470. +{
  1471. + struct platform_device *pdev = to_platform_device(dev);
  1472. + int power = shps_dgpu_rp_get_power(pdev);
  1473. +
  1474. + if (power < 0)
  1475. + return power;
  1476. +
  1477. + return sprintf(data, "%s\n", shps_dgpu_power_str(power));
  1478. +}
  1479. +
  1480. +static ssize_t dgpu_power_store(struct device *dev, struct device_attribute *attr,
  1481. + const char *data, size_t count)
  1482. +{
  1483. + struct platform_device *pdev = to_platform_device(dev);
  1484. + enum shps_dgpu_power power;
  1485. + bool b = false;
  1486. + int status;
  1487. +
  1488. + status = kstrtobool(data, &b);
  1489. + if (status)
  1490. + return status;
  1491. +
  1492. + status = shps_dgpu_is_present(pdev);
  1493. + if (status <= 0)
  1494. + return status < 0 ? status : -EPERM;
  1495. +
  1496. + power = b ? SHPS_DGPU_POWER_ON : SHPS_DGPU_POWER_OFF;
  1497. + status = shps_dgpu_set_power(pdev, power);
  1498. +
  1499. + return status < 0 ? status : count;
  1500. +}
  1501. +
  1502. +static ssize_t dgpu_power_dsm_show(struct device *dev, struct device_attribute *attr, char *data)
  1503. +{
  1504. + struct platform_device *pdev = to_platform_device(dev);
  1505. + int power = shps_dgpu_dsm_get_power(pdev);
  1506. +
  1507. + if (power < 0)
  1508. + return power;
  1509. +
  1510. + return sprintf(data, "%s\n", shps_dgpu_power_str(power));
  1511. +}
  1512. +
  1513. +static ssize_t dgpu_power_dsm_store(struct device *dev, struct device_attribute *attr,
  1514. + const char *data, size_t count)
  1515. +{
  1516. + struct platform_device *pdev = to_platform_device(dev);
  1517. + enum shps_dgpu_power power;
  1518. + bool b = false;
  1519. + int status;
  1520. +
  1521. + status = kstrtobool(data, &b);
  1522. + if (status)
  1523. + return status;
  1524. +
  1525. + status = shps_dgpu_is_present(pdev);
  1526. + if (status <= 0)
  1527. + return status < 0 ? status : -EPERM;
  1528. +
  1529. + power = b ? SHPS_DGPU_POWER_ON : SHPS_DGPU_POWER_OFF;
  1530. + status = shps_dgpu_dsm_set_power(pdev, power);
  1531. +
  1532. + return status < 0 ? status : count;
  1533. +}
  1534. +
  1535. +static DEVICE_ATTR_RW(dgpu_power);
  1536. +static DEVICE_ATTR_RW(dgpu_power_dsm);
  1537. +
  1538. +static struct attribute *shps_power_attrs[] = {
  1539. + &dev_attr_dgpu_power.attr,
  1540. + &dev_attr_dgpu_power_dsm.attr,
  1541. + NULL,
  1542. +};
  1543. +ATTRIBUTE_GROUPS(shps_power);
  1544. +
  1545. +
  1546. +static void dbg_dump_power_states(struct platform_device *pdev, const char *prefix)
  1547. +{
  1548. + enum shps_dgpu_power power_dsm;
  1549. + enum shps_dgpu_power power_rp;
  1550. + int status;
  1551. +
  1552. + status = shps_dgpu_rp_get_power_unlocked(pdev);
  1553. + if (status < 0)
  1554. + dev_err(&pdev->dev, "%s: failed to get root-port power state: %d\n", prefix, status);
  1555. + power_rp = status;
  1556. +
  1557. + status = shps_dgpu_rp_get_power_unlocked(pdev);
  1558. + if (status < 0)
  1559. + dev_err(&pdev->dev, "%s: failed to get direct power state: %d\n", prefix, status);
  1560. + power_dsm = status;
  1561. +
  1562. + dev_dbg(&pdev->dev, "%s: root-port power state: %d\n", prefix, power_rp);
  1563. + dev_dbg(&pdev->dev, "%s: direct power state: %d\n", prefix, power_dsm);
  1564. +}
  1565. +
  1566. +static void dbg_dump_pciesta(struct platform_device *pdev, const char *prefix)
  1567. +{
  1568. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1569. + struct pci_dev *rp = drvdata->dgpu_root_port;
  1570. + u16 lnksta, lnksta2, sltsta, sltsta2;
  1571. +
  1572. + pcie_capability_read_word(rp, PCI_EXP_LNKSTA, &lnksta);
  1573. + pcie_capability_read_word(rp, PCI_EXP_LNKSTA2, &lnksta2);
  1574. + pcie_capability_read_word(rp, PCI_EXP_SLTSTA, &sltsta);
  1575. + pcie_capability_read_word(rp, PCI_EXP_SLTSTA2, &sltsta2);
  1576. +
  1577. + dev_dbg(&pdev->dev, "%s: LNKSTA: 0x%04x\n", prefix, lnksta);
  1578. + dev_dbg(&pdev->dev, "%s: LNKSTA2: 0x%04x\n", prefix, lnksta2);
  1579. + dev_dbg(&pdev->dev, "%s: SLTSTA: 0x%04x\n", prefix, sltsta);
  1580. + dev_dbg(&pdev->dev, "%s: SLTSTA2: 0x%04x\n", prefix, sltsta2);
  1581. +}
  1582. +
  1583. +static void dbg_dump_drvsta(struct platform_device *pdev, const char *prefix)
  1584. +{
  1585. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1586. + struct pci_dev *rp = drvdata->dgpu_root_port;
  1587. +
  1588. + dev_dbg(&pdev->dev, "%s: RP power: %d\n", prefix, rp->current_state);
  1589. + dev_dbg(&pdev->dev, "%s: RP state saved: %d\n", prefix, rp->state_saved);
  1590. + dev_dbg(&pdev->dev, "%s: RP state stored: %d\n", prefix, !!drvdata->dgpu_root_port_state);
  1591. + dev_dbg(&pdev->dev, "%s: RP enabled: %d\n", prefix, atomic_read(&rp->enable_cnt));
  1592. + dev_dbg(&pdev->dev, "%s: RP mastered: %d\n", prefix, rp->is_busmaster);
  1593. +}
  1594. +
  1595. +static int shps_pm_prepare(struct device *dev)
  1596. +{
  1597. + struct platform_device *pdev = to_platform_device(dev);
  1598. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1599. + bool pwrtgt;
  1600. + int status = 0;
  1601. +
  1602. + dbg_dump_power_states(pdev, "shps_pm_prepare");
  1603. +
  1604. + if (param_dgpu_power_susp != SHPS_DGPU_MP_POWER_ASIS) {
  1605. + pwrtgt = test_bit(SHPS_STATE_BIT_PWRTGT, &drvdata->state);
  1606. +
  1607. + status = shps_dgpu_set_power(pdev, param_dgpu_power_susp);
  1608. + if (status) {
  1609. + dev_err(&pdev->dev, "failed to power %s dGPU: %d\n",
  1610. + param_dgpu_power_susp == SHPS_DGPU_MP_POWER_OFF ? "off" : "on",
  1611. + status);
  1612. + return status;
  1613. + }
  1614. +
  1615. + if (pwrtgt)
  1616. + set_bit(SHPS_STATE_BIT_PWRTGT, &drvdata->state);
  1617. + else
  1618. + clear_bit(SHPS_STATE_BIT_PWRTGT, &drvdata->state);
  1619. + }
  1620. +
  1621. + return 0;
  1622. +}
  1623. +
  1624. +static void shps_pm_complete(struct device *dev)
  1625. +{
  1626. + struct platform_device *pdev = to_platform_device(dev);
  1627. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1628. + int status;
  1629. +
  1630. + dbg_dump_power_states(pdev, "shps_pm_complete");
  1631. + dbg_dump_pciesta(pdev, "shps_pm_complete");
  1632. + dbg_dump_drvsta(pdev, "shps_pm_complete.1");
  1633. +
  1634. + // update power target, dGPU may have been detached while suspended
  1635. + status = shps_dgpu_is_present(pdev);
  1636. + if (status < 0) {
  1637. + dev_err(&pdev->dev, "failed to get dGPU presence: %d\n", status);
  1638. + return;
  1639. + } else if (status == 0) {
  1640. + clear_bit(SHPS_STATE_BIT_PWRTGT, &drvdata->state);
  1641. + }
  1642. +
  1643. + /*
  1644. + * During resume, the PCIe core will power on the root-port, which in turn
  1645. + * will power on the dGPU. Most of the state synchronization is already
  1646. + * handled via the SAN RQSG handler, so it is in a fully consistent
  1647. + * on-state here. If requested, turn it off here.
  1648. + *
  1649. + * As there seem to be some synchronization issues turning off the dGPU
  1650. + * directly after the power-on SAN RQSG notification during the resume
  1651. + * process, let's do this here.
  1652. + *
  1653. + * TODO/FIXME:
  1654. + * This does not combat unhandled power-ons when the device is not fully
  1655. + * resumed, i.e. re-suspended before shps_pm_complete is called. Those
  1656. + * should normally not be an issue, but the dGPU does get hot even though
  1657. + * it is suspended, so ideally we want to keep it off.
  1658. + */
  1659. + if (!test_bit(SHPS_STATE_BIT_PWRTGT, &drvdata->state)) {
  1660. + status = shps_dgpu_set_power(pdev, SHPS_DGPU_POWER_OFF);
  1661. + if (status)
  1662. + dev_err(&pdev->dev, "failed to power-off dGPU: %d\n", status);
  1663. + }
  1664. +
  1665. + dbg_dump_drvsta(pdev, "shps_pm_complete.2");
  1666. +}
  1667. +
  1668. +static int shps_pm_suspend(struct device *dev)
  1669. +{
  1670. + struct platform_device *pdev = to_platform_device(dev);
  1671. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1672. + int status;
  1673. +
  1674. + if (device_may_wakeup(dev)) {
  1675. + status = enable_irq_wake(drvdata->irq_base_presence);
  1676. + if (status)
  1677. + return status;
  1678. +
  1679. + set_bit(SHPS_STATE_BIT_WAKE_ENABLED, &drvdata->state);
  1680. + }
  1681. +
  1682. + return 0;
  1683. +}
  1684. +
  1685. +static int shps_pm_resume(struct device *dev)
  1686. +{
  1687. + struct platform_device *pdev = to_platform_device(dev);
  1688. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1689. + int status = 0;
  1690. +
  1691. + if (test_and_clear_bit(SHPS_STATE_BIT_WAKE_ENABLED, &drvdata->state))
  1692. + status = disable_irq_wake(drvdata->irq_base_presence);
  1693. +
  1694. + return status;
  1695. +}
  1696. +
  1697. +static void shps_shutdown(struct platform_device *pdev)
  1698. +{
  1699. + int status;
  1700. +
  1701. + /*
  1702. + * Turn on dGPU before shutting down. This allows the core drivers to
  1703. + * properly shut down the device. If we don't do this, the pcieport driver
  1704. + * will complain that the device has already been disabled.
  1705. + */
  1706. + status = shps_dgpu_set_power(pdev, SHPS_DGPU_POWER_ON);
  1707. + if (status)
  1708. + dev_err(&pdev->dev, "failed to turn on dGPU: %d\n", status);
  1709. +}
  1710. +
  1711. +static int shps_dgpu_detached(struct platform_device *pdev)
  1712. +{
  1713. + dbg_dump_power_states(pdev, "shps_dgpu_detached");
  1714. + return shps_dgpu_set_power(pdev, SHPS_DGPU_POWER_OFF);
  1715. +}
  1716. +
  1717. +static int shps_dgpu_attached(struct platform_device *pdev)
  1718. +{
  1719. + dbg_dump_power_states(pdev, "shps_dgpu_attached");
  1720. + return 0;
  1721. +}
  1722. +
  1723. +static int shps_dgpu_powered_on(struct platform_device *pdev)
  1724. +{
  1725. + /*
  1726. + * This function gets called directly after a power-state transition of
  1727. + * the dGPU root port out of D3cold state, indicating a power-on of the
  1728. + * dGPU. Specifically, this function is called from the RQSG handler of
  1729. + * SAN, invoked by the ACPI _ON method of the dGPU root port. This means
  1730. + * that this function is run inside `pci_set_power_state(rp, ...)`
  1731. + * syncrhonously and thus returns before the `pci_set_power_state` call
  1732. + * does.
  1733. + *
  1734. + * `pci_set_power_state` may either be called by us or when the PCI
  1735. + * subsystem decides to power up the root port (e.g. during resume). Thus
  1736. + * we should use this function to ensure that the dGPU and root port
  1737. + * states are consistent when an unexpected power-up is encountered.
  1738. + */
  1739. +
  1740. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1741. + struct pci_dev *rp = drvdata->dgpu_root_port;
  1742. + int status;
  1743. +
  1744. + dbg_dump_drvsta(pdev, "shps_dgpu_powered_on.1");
  1745. +
  1746. + // if we caused the root port to power-on, return
  1747. + if (test_bit(SHPS_STATE_BIT_RPPWRON_SYNC, &drvdata->state))
  1748. + return 0;
  1749. +
  1750. + // if dGPU is not present, force power-target to off and return
  1751. + status = shps_dgpu_is_present(pdev);
  1752. + if (status == 0)
  1753. + clear_bit(SHPS_STATE_BIT_PWRTGT, &drvdata->state);
  1754. + if (status <= 0)
  1755. + return status;
  1756. +
  1757. + mutex_lock(&drvdata->lock);
  1758. +
  1759. + dbg_dump_power_states(pdev, "shps_dgpu_powered_on.1");
  1760. + dbg_dump_pciesta(pdev, "shps_dgpu_powered_on.1");
  1761. + if (drvdata->dgpu_root_port_state)
  1762. + pci_load_and_free_saved_state(rp, &drvdata->dgpu_root_port_state);
  1763. + pci_restore_state(rp);
  1764. + if (!pci_is_enabled(rp))
  1765. + pci_enable_device(rp);
  1766. + pci_set_master(rp);
  1767. + dbg_dump_drvsta(pdev, "shps_dgpu_powered_on.2");
  1768. + dbg_dump_power_states(pdev, "shps_dgpu_powered_on.2");
  1769. + dbg_dump_pciesta(pdev, "shps_dgpu_powered_on.2");
  1770. +
  1771. + mutex_unlock(&drvdata->lock);
  1772. +
  1773. + if (!test_bit(SHPS_STATE_BIT_PWRTGT, &drvdata->state)) {
  1774. + dev_warn(&pdev->dev, "unexpected dGPU power-on detected\n");
  1775. + // TODO: schedule state re-check and update
  1776. + }
  1777. +
  1778. + return 0;
  1779. +}
  1780. +
  1781. +static int shps_dgpu_handle_rqsg(struct surface_sam_san_rqsg *rqsg, void *data)
  1782. +{
  1783. + struct platform_device *pdev = data;
  1784. +
  1785. + if (rqsg->tc == SAM_DGPU_TC && rqsg->cid == SAM_DGPU_CID_POWERON)
  1786. + return shps_dgpu_powered_on(pdev);
  1787. +
  1788. + dev_warn(&pdev->dev, "unimplemented dGPU request: RQSG(0x%02x, 0x%02x, 0x%02x)\n",
  1789. + rqsg->tc, rqsg->cid, rqsg->iid);
  1790. + return 0;
  1791. +}
  1792. +
  1793. +static irqreturn_t shps_dgpu_presence_irq(int irq, void *data)
  1794. +{
  1795. + struct platform_device *pdev = data;
  1796. + bool dgpu_present;
  1797. + int status;
  1798. +
  1799. + status = shps_dgpu_is_present(pdev);
  1800. + if (status < 0) {
  1801. + dev_err(&pdev->dev, "failed to check physical dGPU presence: %d\n", status);
  1802. + return IRQ_HANDLED;
  1803. + }
  1804. +
  1805. + dgpu_present = status != 0;
  1806. + dev_info(&pdev->dev, "dGPU physically %s\n", dgpu_present ? "attached" : "detached");
  1807. +
  1808. + if (dgpu_present)
  1809. + status = shps_dgpu_attached(pdev);
  1810. + else
  1811. + status = shps_dgpu_detached(pdev);
  1812. +
  1813. + if (status)
  1814. + dev_err(&pdev->dev, "error handling dGPU interrupt: %d\n", status);
  1815. +
  1816. + return IRQ_HANDLED;
  1817. +}
  1818. +
  1819. +static irqreturn_t shps_base_presence_irq(int irq, void *data)
  1820. +{
  1821. + return IRQ_HANDLED; // nothing to do, just wake
  1822. +}
  1823. +
  1824. +
  1825. +static int shps_gpios_setup(struct platform_device *pdev)
  1826. +{
  1827. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1828. + struct gpio_desc *gpio_dgpu_power;
  1829. + struct gpio_desc *gpio_dgpu_presence;
  1830. + struct gpio_desc *gpio_base_presence;
  1831. + int status;
  1832. +
  1833. + // get GPIOs
  1834. + gpio_dgpu_power = devm_gpiod_get(&pdev->dev, "dgpu_power", GPIOD_IN);
  1835. + if (IS_ERR(gpio_dgpu_power)) {
  1836. + status = PTR_ERR(gpio_dgpu_power);
  1837. + goto err_out;
  1838. + }
  1839. +
  1840. + gpio_dgpu_presence = devm_gpiod_get(&pdev->dev, "dgpu_presence", GPIOD_IN);
  1841. + if (IS_ERR(gpio_dgpu_presence)) {
  1842. + status = PTR_ERR(gpio_dgpu_presence);
  1843. + goto err_out;
  1844. + }
  1845. +
  1846. + gpio_base_presence = devm_gpiod_get(&pdev->dev, "base_presence", GPIOD_IN);
  1847. + if (IS_ERR(gpio_base_presence)) {
  1848. + status = PTR_ERR(gpio_base_presence);
  1849. + goto err_out;
  1850. + }
  1851. +
  1852. + // export GPIOs
  1853. + status = gpiod_export(gpio_dgpu_power, false);
  1854. + if (status)
  1855. + goto err_out;
  1856. +
  1857. + status = gpiod_export(gpio_dgpu_presence, false);
  1858. + if (status)
  1859. + goto err_export_dgpu_presence;
  1860. +
  1861. + status = gpiod_export(gpio_base_presence, false);
  1862. + if (status)
  1863. + goto err_export_base_presence;
  1864. +
  1865. + // create sysfs links
  1866. + status = gpiod_export_link(&pdev->dev, "gpio-dgpu_power", gpio_dgpu_power);
  1867. + if (status)
  1868. + goto err_link_dgpu_power;
  1869. +
  1870. + status = gpiod_export_link(&pdev->dev, "gpio-dgpu_presence", gpio_dgpu_presence);
  1871. + if (status)
  1872. + goto err_link_dgpu_presence;
  1873. +
  1874. + status = gpiod_export_link(&pdev->dev, "gpio-base_presence", gpio_base_presence);
  1875. + if (status)
  1876. + goto err_link_base_presence;
  1877. +
  1878. + drvdata->gpio_dgpu_power = gpio_dgpu_power;
  1879. + drvdata->gpio_dgpu_presence = gpio_dgpu_presence;
  1880. + drvdata->gpio_base_presence = gpio_base_presence;
  1881. + return 0;
  1882. +
  1883. +err_link_base_presence:
  1884. + sysfs_remove_link(&pdev->dev.kobj, "gpio-dgpu_presence");
  1885. +err_link_dgpu_presence:
  1886. + sysfs_remove_link(&pdev->dev.kobj, "gpio-dgpu_power");
  1887. +err_link_dgpu_power:
  1888. + gpiod_unexport(gpio_base_presence);
  1889. +err_export_base_presence:
  1890. + gpiod_unexport(gpio_dgpu_presence);
  1891. +err_export_dgpu_presence:
  1892. + gpiod_unexport(gpio_dgpu_power);
  1893. +err_out:
  1894. + return status;
  1895. +}
  1896. +
  1897. +static void shps_gpios_remove(struct platform_device *pdev)
  1898. +{
  1899. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1900. +
  1901. + sysfs_remove_link(&pdev->dev.kobj, "gpio-base_presence");
  1902. + sysfs_remove_link(&pdev->dev.kobj, "gpio-dgpu_presence");
  1903. + sysfs_remove_link(&pdev->dev.kobj, "gpio-dgpu_power");
  1904. + gpiod_unexport(drvdata->gpio_base_presence);
  1905. + gpiod_unexport(drvdata->gpio_dgpu_presence);
  1906. + gpiod_unexport(drvdata->gpio_dgpu_power);
  1907. +}
  1908. +
  1909. +static int shps_gpios_setup_irq(struct platform_device *pdev)
  1910. +{
  1911. + const int irqf_dgpu = IRQF_SHARED | IRQF_ONESHOT | IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING;
  1912. + const int irqf_base = IRQF_SHARED;
  1913. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1914. + int status;
  1915. +
  1916. + status = gpiod_to_irq(drvdata->gpio_base_presence);
  1917. + if (status < 0)
  1918. + return status;
  1919. + drvdata->irq_base_presence = status;
  1920. +
  1921. + status = gpiod_to_irq(drvdata->gpio_dgpu_presence);
  1922. + if (status < 0)
  1923. + return status;
  1924. + drvdata->irq_dgpu_presence = status;
  1925. +
  1926. + status = request_irq(drvdata->irq_base_presence,
  1927. + shps_base_presence_irq, irqf_base,
  1928. + "shps_base_presence_irq", pdev);
  1929. + if (status) {
  1930. + dev_err(&pdev->dev, "base irq failed: %d\n", status);
  1931. + return status;
  1932. + }
  1933. +
  1934. + status = request_threaded_irq(drvdata->irq_dgpu_presence,
  1935. + NULL, shps_dgpu_presence_irq, irqf_dgpu,
  1936. + "shps_dgpu_presence_irq", pdev);
  1937. + if (status) {
  1938. + free_irq(drvdata->irq_base_presence, pdev);
  1939. + return status;
  1940. + }
  1941. +
  1942. + return 0;
  1943. +}
  1944. +
  1945. +static void shps_gpios_remove_irq(struct platform_device *pdev)
  1946. +{
  1947. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1948. +
  1949. + free_irq(drvdata->irq_base_presence, pdev);
  1950. + free_irq(drvdata->irq_dgpu_presence, pdev);
  1951. +}
  1952. +
  1953. +static void shps_sgcp_notify(acpi_handle device, u32 value, void *context) {
  1954. + struct platform_device *pdev = context;
  1955. + switch (value) {
  1956. + case ACPI_SGCP_NOTIFY_POWER_ON:
  1957. + shps_dgpu_powered_on(pdev);
  1958. + }
  1959. +}
  1960. +
  1961. +static int shps_start_sgcp_notification(struct platform_device *pdev, acpi_handle *sgpc_handle) {
  1962. + acpi_handle handle;
  1963. + int status;
  1964. +
  1965. + status = acpi_get_handle(NULL, "\\_SB.SGPC", &handle);
  1966. + if (status) {
  1967. + dev_err(&pdev->dev, "error in get_handle %d\n", status);
  1968. + return status;
  1969. + }
  1970. +
  1971. + status = acpi_install_notify_handler(handle, ACPI_DEVICE_NOTIFY, shps_sgcp_notify, pdev);
  1972. + if (status) {
  1973. + dev_err(&pdev->dev, "error in install notify %d\n", status);
  1974. + *sgpc_handle = NULL;
  1975. + return status;
  1976. + }
  1977. +
  1978. + *sgpc_handle = handle;
  1979. + return 0;
  1980. +}
  1981. +
  1982. +static void shps_remove_sgcp_notification(struct platform_device *pdev) {
  1983. + int status;
  1984. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  1985. +
  1986. + if (drvdata->sgpc_handle) {
  1987. + status = acpi_remove_notify_handler(drvdata->sgpc_handle, ACPI_DEVICE_NOTIFY, shps_sgcp_notify);
  1988. + if (status) {
  1989. + dev_err(&pdev->dev, "failed to remove notify handler: %d\n", status);
  1990. + }
  1991. + }
  1992. +}
  1993. +
  1994. +static struct shps_hardware_traits shps_detect_hardware_traits(struct platform_device *pdev) {
  1995. + const struct shps_hardware_probe *p;
  1996. +
  1997. + for (p = shps_hardware_probe_match; p->hardware_id; ++p) {
  1998. + if (acpi_dev_present(p->hardware_id, NULL, -1)) {
  1999. + break;
  2000. + }
  2001. + }
  2002. +
  2003. + dev_info(&pdev->dev,
  2004. + "shps_detect_hardware_traits found device %s, generation %d\n",
  2005. + p->hardware_id ? p->hardware_id : "SAN (default)",
  2006. + p->generation);
  2007. +
  2008. + return *p->hardware_traits;
  2009. +}
  2010. +
  2011. +static int shps_probe(struct platform_device *pdev)
  2012. +{
  2013. + struct acpi_device *shps_dev = ACPI_COMPANION(&pdev->dev);
  2014. + struct shps_driver_data *drvdata;
  2015. + struct device_link *link;
  2016. + int power, status;
  2017. + struct shps_hardware_traits detected_traits;
  2018. +
  2019. + if (gpiod_count(&pdev->dev, NULL) < 0) {
  2020. + dev_err(&pdev->dev, "gpiod_count returned < 0\n");
  2021. + return -ENODEV;
  2022. + }
  2023. +
  2024. + // link to SSH
  2025. + status = surface_sam_ssh_consumer_register(&pdev->dev);
  2026. + if (status) {
  2027. + return status == -ENXIO ? -EPROBE_DEFER : status;
  2028. + }
  2029. +
  2030. + // detect what kind of hardware we're running
  2031. + detected_traits = shps_detect_hardware_traits(pdev);
  2032. +
  2033. + if (detected_traits.notification_method == SHPS_NOTIFICATION_METHOD_SAN) {
  2034. + // link to SAN
  2035. + status = surface_sam_san_consumer_register(&pdev->dev, 0);
  2036. + if (status) {
  2037. + dev_err(&pdev->dev, "failed to register with san consumer: %d\n", status);
  2038. + return status == -ENXIO ? -EPROBE_DEFER : status;
  2039. + }
  2040. + }
  2041. +
  2042. + status = acpi_dev_add_driver_gpios(shps_dev, shps_acpi_gpios);
  2043. + if (status) {
  2044. + dev_err(&pdev->dev, "failed to add gpios: %d\n", status);
  2045. + return status;
  2046. + }
  2047. +
  2048. + drvdata = kzalloc(sizeof(struct shps_driver_data), GFP_KERNEL);
  2049. + if (!drvdata) {
  2050. + status = -ENOMEM;
  2051. + goto err_drvdata;
  2052. + }
  2053. + mutex_init(&drvdata->lock);
  2054. + platform_set_drvdata(pdev, drvdata);
  2055. +
  2056. + drvdata->hardware_traits = detected_traits;
  2057. +
  2058. + drvdata->dgpu_root_port = shps_dgpu_dsm_get_pci_dev(pdev);
  2059. + if (IS_ERR(drvdata->dgpu_root_port)) {
  2060. + status = PTR_ERR(drvdata->dgpu_root_port);
  2061. + dev_err(&pdev->dev, "failed to get pci dev: %d\n", status);
  2062. + goto err_rp_lookup;
  2063. + }
  2064. +
  2065. + status = shps_gpios_setup(pdev);
  2066. + if (status) {
  2067. + dev_err(&pdev->dev, "unable to set up gpios, %d\n", status);
  2068. + goto err_gpio;
  2069. + }
  2070. +
  2071. + status = shps_gpios_setup_irq(pdev);
  2072. + if (status) {
  2073. + dev_err(&pdev->dev, "unable to set up irqs %d\n", status);
  2074. + goto err_gpio_irqs;
  2075. + }
  2076. +
  2077. + status = device_add_groups(&pdev->dev, shps_power_groups);
  2078. + if (status)
  2079. + goto err_devattr;
  2080. +
  2081. + link = device_link_add(&pdev->dev, &drvdata->dgpu_root_port->dev,
  2082. + DL_FLAG_PM_RUNTIME | DL_FLAG_AUTOREMOVE_CONSUMER);
  2083. + if (!link)
  2084. + goto err_devlink;
  2085. +
  2086. + if (detected_traits.notification_method == SHPS_NOTIFICATION_METHOD_SAN) {
  2087. + status = surface_sam_san_set_rqsg_handler(shps_dgpu_handle_rqsg, pdev);
  2088. + if (status) {
  2089. + dev_err(&pdev->dev, "unable to set SAN notification handler (%d)\n", status);
  2090. + goto err_devlink;
  2091. + }
  2092. + } else if (detected_traits.notification_method == SHPS_NOTIFICATION_METHOD_SGCP) {
  2093. + status = shps_start_sgcp_notification(pdev, &drvdata->sgpc_handle);
  2094. + if (status) {
  2095. + dev_err(&pdev->dev, "unable to install SGCP notification handler (%d)\n", status);
  2096. + goto err_devlink;
  2097. + }
  2098. + }
  2099. +
  2100. + // if dGPU is not present turn-off root-port, else obey module param
  2101. + status = shps_dgpu_is_present(pdev);
  2102. + if (status < 0)
  2103. + goto err_post_notification;
  2104. +
  2105. + power = status == 0 ? SHPS_DGPU_POWER_OFF : param_dgpu_power_init;
  2106. + if (power != SHPS_DGPU_MP_POWER_ASIS) {
  2107. + status = shps_dgpu_set_power(pdev, power);
  2108. + if (status)
  2109. + goto err_post_notification;
  2110. + }
  2111. +
  2112. + // initialize power target
  2113. + status = shps_dgpu_rp_get_power(pdev);
  2114. + if (status < 0)
  2115. + goto err_pwrtgt;
  2116. +
  2117. + if (status)
  2118. + set_bit(SHPS_STATE_BIT_PWRTGT, &drvdata->state);
  2119. + else
  2120. + clear_bit(SHPS_STATE_BIT_PWRTGT, &drvdata->state);
  2121. +
  2122. + device_init_wakeup(&pdev->dev, true);
  2123. + return 0;
  2124. +
  2125. +err_pwrtgt:
  2126. + if (param_dgpu_power_exit != SHPS_DGPU_MP_POWER_ASIS) {
  2127. + status = shps_dgpu_set_power(pdev, param_dgpu_power_exit);
  2128. + if (status)
  2129. + dev_err(&pdev->dev, "failed to set dGPU power state: %d\n", status);
  2130. + }
  2131. +err_post_notification:
  2132. + if (detected_traits.notification_method == SHPS_NOTIFICATION_METHOD_SGCP) {
  2133. + shps_remove_sgcp_notification(pdev);
  2134. + } else if (detected_traits.notification_method == SHPS_NOTIFICATION_METHOD_SAN) {
  2135. + surface_sam_san_set_rqsg_handler(NULL, NULL);
  2136. + }
  2137. +err_devlink:
  2138. + device_remove_groups(&pdev->dev, shps_power_groups);
  2139. +err_devattr:
  2140. + shps_gpios_remove_irq(pdev);
  2141. +err_gpio_irqs:
  2142. + shps_gpios_remove(pdev);
  2143. +err_gpio:
  2144. + pci_dev_put(drvdata->dgpu_root_port);
  2145. +err_rp_lookup:
  2146. + platform_set_drvdata(pdev, NULL);
  2147. + kfree(drvdata);
  2148. +err_drvdata:
  2149. + acpi_dev_remove_driver_gpios(shps_dev);
  2150. + return status;
  2151. +}
  2152. +
  2153. +static int shps_remove(struct platform_device *pdev)
  2154. +{
  2155. + struct acpi_device *shps_dev = ACPI_COMPANION(&pdev->dev);
  2156. + struct shps_driver_data *drvdata = platform_get_drvdata(pdev);
  2157. + int status;
  2158. +
  2159. + if (param_dgpu_power_exit != SHPS_DGPU_MP_POWER_ASIS) {
  2160. + status = shps_dgpu_set_power(pdev, param_dgpu_power_exit);
  2161. + if (status)
  2162. + dev_err(&pdev->dev, "failed to set dGPU power state: %d\n", status);
  2163. + }
  2164. +
  2165. + device_set_wakeup_capable(&pdev->dev, false);
  2166. +
  2167. + if (drvdata->hardware_traits.notification_method == SHPS_NOTIFICATION_METHOD_SGCP) {
  2168. + shps_remove_sgcp_notification(pdev);
  2169. + } else if (drvdata->hardware_traits.notification_method == SHPS_NOTIFICATION_METHOD_SAN) {
  2170. + surface_sam_san_set_rqsg_handler(NULL, NULL);
  2171. + }
  2172. + device_remove_groups(&pdev->dev, shps_power_groups);
  2173. + shps_gpios_remove_irq(pdev);
  2174. + shps_gpios_remove(pdev);
  2175. + pci_dev_put(drvdata->dgpu_root_port);
  2176. + platform_set_drvdata(pdev, NULL);
  2177. + kfree(drvdata);
  2178. +
  2179. + acpi_dev_remove_driver_gpios(shps_dev);
  2180. + return 0;
  2181. +}
  2182. +
  2183. +
  2184. +static const struct dev_pm_ops shps_pm_ops = {
  2185. + .prepare = shps_pm_prepare,
  2186. + .complete = shps_pm_complete,
  2187. + .suspend = shps_pm_suspend,
  2188. + .resume = shps_pm_resume,
  2189. +};
  2190. +
  2191. +static const struct acpi_device_id shps_acpi_match[] = {
  2192. + { "MSHW0153", 0 },
  2193. + { },
  2194. +};
  2195. +MODULE_DEVICE_TABLE(acpi, shps_acpi_match);
  2196. +
  2197. +static struct platform_driver surface_sam_hps = {
  2198. + .probe = shps_probe,
  2199. + .remove = shps_remove,
  2200. + .shutdown = shps_shutdown,
  2201. + .driver = {
  2202. + .name = "surface_dgpu_hps",
  2203. + .acpi_match_table = shps_acpi_match,
  2204. + .pm = &shps_pm_ops,
  2205. + },
  2206. +};
  2207. +
  2208. +module_platform_driver(surface_sam_hps);
  2209. +
  2210. +MODULE_AUTHOR("Maximilian Luz <luzmaximilian@gmail.com>");
  2211. +MODULE_DESCRIPTION("Surface Hot-Plug System (HPS) and dGPU power-state Driver for Surface Book 2");
  2212. +MODULE_LICENSE("GPL");
  2213. diff --git a/drivers/platform/x86/surface_sam/surface_sam_san.c b/drivers/platform/x86/surface_sam/surface_sam_san.c
  2214. new file mode 100644
  2215. index 0000000000000..11dd6daedc3dd
  2216. --- /dev/null
  2217. +++ b/drivers/platform/x86/surface_sam/surface_sam_san.c
  2218. @@ -0,0 +1,913 @@
  2219. +// SPDX-License-Identifier: GPL-2.0-or-later
  2220. +/*
  2221. + * Surface ACPI Notify (SAN) and ACPI integration driver for SAM.
  2222. + * Translates communication from ACPI to SSH and back.
  2223. + */
  2224. +
  2225. +#include <linux/acpi.h>
  2226. +#include <linux/delay.h>
  2227. +#include <linux/jiffies.h>
  2228. +#include <linux/kernel.h>
  2229. +#include <linux/platform_device.h>
  2230. +
  2231. +#include "surface_sam_ssh.h"
  2232. +#include "surface_sam_san.h"
  2233. +
  2234. +
  2235. +#define SAN_RQST_RETRY 5
  2236. +
  2237. +#define SAN_DSM_REVISION 0
  2238. +#define SAN_DSM_FN_NOTIFY_SENSOR_TRIP_POINT 0x09
  2239. +
  2240. +static const guid_t SAN_DSM_UUID =
  2241. + GUID_INIT(0x93b666c5, 0x70c6, 0x469f, 0xa2, 0x15, 0x3d,
  2242. + 0x48, 0x7c, 0x91, 0xab, 0x3c);
  2243. +
  2244. +#define SAM_EVENT_DELAY_PWR_ADAPTER msecs_to_jiffies(5000)
  2245. +#define SAM_EVENT_DELAY_PWR_BST msecs_to_jiffies(2500)
  2246. +
  2247. +#define SAM_EVENT_PWR_CID_BIX 0x15
  2248. +#define SAM_EVENT_PWR_CID_BST 0x16
  2249. +#define SAM_EVENT_PWR_CID_ADAPTER 0x17
  2250. +#define SAM_EVENT_PWR_CID_DPTF 0x4f
  2251. +
  2252. +#define SAM_EVENT_TEMP_CID_NOTIFY_SENSOR_TRIP_POINT 0x0b
  2253. +
  2254. +#define SAN_RQST_TAG "surface_sam_san: rqst: "
  2255. +#define SAN_RQSG_TAG "surface_sam_san: rqsg: "
  2256. +
  2257. +#define SAN_QUIRK_BASE_STATE_DELAY 1000
  2258. +
  2259. +
  2260. +struct san_acpi_consumer {
  2261. + char *path;
  2262. + bool required;
  2263. + u32 flags;
  2264. +};
  2265. +
  2266. +struct san_opreg_context {
  2267. + struct acpi_connection_info connection;
  2268. + struct device *dev;
  2269. +};
  2270. +
  2271. +struct san_consumer_link {
  2272. + const struct san_acpi_consumer *properties;
  2273. + struct device_link *link;
  2274. +};
  2275. +
  2276. +struct san_consumers {
  2277. + u32 num;
  2278. + struct san_consumer_link *links;
  2279. +};
  2280. +
  2281. +struct san_drvdata {
  2282. + struct san_opreg_context opreg_ctx;
  2283. + struct san_consumers consumers;
  2284. +
  2285. + struct platform_device *dev;
  2286. + struct ssam_event_notifier nf_bat;
  2287. + struct ssam_event_notifier nf_tmp;
  2288. +};
  2289. +
  2290. +struct san_event_work {
  2291. + struct delayed_work work;
  2292. + struct platform_device *dev;
  2293. + struct ssam_event event; // must be last
  2294. +};
  2295. +
  2296. +struct gsb_data_in {
  2297. + u8 cv;
  2298. +} __packed;
  2299. +
  2300. +struct gsb_data_rqsx {
  2301. + u8 cv; // command value (should be 0x01 or 0x03)
  2302. + u8 tc; // target controller
  2303. + u8 tid; // transport channnel ID?
  2304. + u8 iid; // target sub-controller (e.g. primary vs. secondary battery)
  2305. + u8 snc; // expect-response-flag
  2306. + u8 cid; // command ID
  2307. + u8 cdl; // payload length
  2308. + u8 _pad; // padding
  2309. + u8 pld[0]; // payload
  2310. +} __packed;
  2311. +
  2312. +struct gsb_data_etwl {
  2313. + u8 cv; // command value (should be 0x02)
  2314. + u8 etw3; // ?
  2315. + u8 etw4; // ?
  2316. + u8 msg[0]; // error message (ASCIIZ)
  2317. +} __packed;
  2318. +
  2319. +struct gsb_data_out {
  2320. + u8 status; // _SSH communication status
  2321. + u8 len; // _SSH payload length
  2322. + u8 pld[0]; // _SSH payload
  2323. +} __packed;
  2324. +
  2325. +union gsb_buffer_data {
  2326. + struct gsb_data_in in; // common input
  2327. + struct gsb_data_rqsx rqsx; // RQSX input
  2328. + struct gsb_data_etwl etwl; // ETWL input
  2329. + struct gsb_data_out out; // output
  2330. +};
  2331. +
  2332. +struct gsb_buffer {
  2333. + u8 status; // GSB AttribRawProcess status
  2334. + u8 len; // GSB AttribRawProcess length
  2335. + union gsb_buffer_data data;
  2336. +} __packed;
  2337. +
  2338. +
  2339. +enum san_pwr_event {
  2340. + SAN_PWR_EVENT_BAT1_STAT = 0x03,
  2341. + SAN_PWR_EVENT_BAT1_INFO = 0x04,
  2342. + SAN_PWR_EVENT_ADP1_STAT = 0x05,
  2343. + SAN_PWR_EVENT_ADP1_INFO = 0x06,
  2344. + SAN_PWR_EVENT_BAT2_STAT = 0x07,
  2345. + SAN_PWR_EVENT_BAT2_INFO = 0x08,
  2346. + SAN_PWR_EVENT_DPTF = 0x0A,
  2347. +};
  2348. +
  2349. +
  2350. +static int sam_san_default_rqsg_handler(struct surface_sam_san_rqsg *rqsg, void *data);
  2351. +
  2352. +struct sam_san_rqsg_if {
  2353. + struct mutex lock;
  2354. + struct device *san_dev;
  2355. + surface_sam_san_rqsg_handler_fn handler;
  2356. + void *handler_data;
  2357. +};
  2358. +
  2359. +static struct sam_san_rqsg_if rqsg_if = {
  2360. + .lock = __MUTEX_INITIALIZER(rqsg_if.lock),
  2361. + .san_dev = NULL,
  2362. + .handler = sam_san_default_rqsg_handler,
  2363. + .handler_data = NULL,
  2364. +};
  2365. +
  2366. +int surface_sam_san_consumer_register(struct device *consumer, u32 flags)
  2367. +{
  2368. + const u32 valid = DL_FLAG_PM_RUNTIME | DL_FLAG_RPM_ACTIVE;
  2369. + int status;
  2370. +
  2371. + if ((flags | valid) != valid)
  2372. + return -EINVAL;
  2373. +
  2374. + flags |= DL_FLAG_AUTOREMOVE_CONSUMER;
  2375. +
  2376. + mutex_lock(&rqsg_if.lock);
  2377. + if (rqsg_if.san_dev)
  2378. + status = device_link_add(consumer, rqsg_if.san_dev, flags) ? 0 : -EINVAL;
  2379. + else
  2380. + status = -ENXIO;
  2381. + mutex_unlock(&rqsg_if.lock);
  2382. + return status;
  2383. +}
  2384. +EXPORT_SYMBOL_GPL(surface_sam_san_consumer_register);
  2385. +
  2386. +int surface_sam_san_set_rqsg_handler(surface_sam_san_rqsg_handler_fn fn, void *data)
  2387. +{
  2388. + int status = -EBUSY;
  2389. +
  2390. + mutex_lock(&rqsg_if.lock);
  2391. +
  2392. + if (rqsg_if.handler == sam_san_default_rqsg_handler || !fn) {
  2393. + rqsg_if.handler = fn ? fn : sam_san_default_rqsg_handler;
  2394. + rqsg_if.handler_data = data;
  2395. + status = 0;
  2396. + }
  2397. +
  2398. + mutex_unlock(&rqsg_if.lock);
  2399. + return status;
  2400. +}
  2401. +EXPORT_SYMBOL_GPL(surface_sam_san_set_rqsg_handler);
  2402. +
  2403. +int san_call_rqsg_handler(struct surface_sam_san_rqsg *rqsg)
  2404. +{
  2405. + int status;
  2406. +
  2407. + mutex_lock(&rqsg_if.lock);
  2408. + status = rqsg_if.handler(rqsg, rqsg_if.handler_data);
  2409. + mutex_unlock(&rqsg_if.lock);
  2410. +
  2411. + return status;
  2412. +}
  2413. +
  2414. +static int sam_san_default_rqsg_handler(struct surface_sam_san_rqsg *rqsg, void *data)
  2415. +{
  2416. + pr_warn(SAN_RQSG_TAG "unhandled request: RQSG(0x%02x, 0x%02x, 0x%02x)\n",
  2417. + rqsg->tc, rqsg->cid, rqsg->iid);
  2418. +
  2419. + return 0;
  2420. +}
  2421. +
  2422. +
  2423. +static bool san_acpi_can_notify(struct device *dev, u64 func)
  2424. +{
  2425. + acpi_handle san = ACPI_HANDLE(dev);
  2426. + return acpi_check_dsm(san, &SAN_DSM_UUID, SAN_DSM_REVISION, 1 << func);
  2427. +}
  2428. +
  2429. +static int san_acpi_notify_power_event(struct device *dev, enum san_pwr_event event)
  2430. +{
  2431. + acpi_handle san = ACPI_HANDLE(dev);
  2432. + union acpi_object *obj;
  2433. +
  2434. + if (!san_acpi_can_notify(dev, event))
  2435. + return 0;
  2436. +
  2437. + dev_dbg(dev, "notify power event 0x%02x\n", event);
  2438. + obj = acpi_evaluate_dsm_typed(san, &SAN_DSM_UUID, SAN_DSM_REVISION,
  2439. + event, NULL, ACPI_TYPE_BUFFER);
  2440. +
  2441. + if (IS_ERR_OR_NULL(obj))
  2442. + return obj ? PTR_ERR(obj) : -ENXIO;
  2443. +
  2444. + if (obj->buffer.length != 1 || obj->buffer.pointer[0] != 0) {
  2445. + dev_err(dev, "got unexpected result from _DSM\n");
  2446. + return -EFAULT;
  2447. + }
  2448. +
  2449. + ACPI_FREE(obj);
  2450. + return 0;
  2451. +}
  2452. +
  2453. +static int san_acpi_notify_sensor_trip_point(struct device *dev, u8 iid)
  2454. +{
  2455. + acpi_handle san = ACPI_HANDLE(dev);
  2456. + union acpi_object *obj;
  2457. + union acpi_object param;
  2458. +
  2459. + if (!san_acpi_can_notify(dev, SAN_DSM_FN_NOTIFY_SENSOR_TRIP_POINT))
  2460. + return 0;
  2461. +
  2462. + param.type = ACPI_TYPE_INTEGER;
  2463. + param.integer.value = iid;
  2464. +
  2465. + obj = acpi_evaluate_dsm_typed(san, &SAN_DSM_UUID, SAN_DSM_REVISION,
  2466. + SAN_DSM_FN_NOTIFY_SENSOR_TRIP_POINT,
  2467. + &param, ACPI_TYPE_BUFFER);
  2468. +
  2469. + if (IS_ERR_OR_NULL(obj))
  2470. + return obj ? PTR_ERR(obj) : -ENXIO;
  2471. +
  2472. + if (obj->buffer.length != 1 || obj->buffer.pointer[0] != 0) {
  2473. + dev_err(dev, "got unexpected result from _DSM\n");
  2474. + return -EFAULT;
  2475. + }
  2476. +
  2477. + ACPI_FREE(obj);
  2478. + return 0;
  2479. +}
  2480. +
  2481. +
  2482. +static inline int san_evt_power_adapter(struct device *dev, const struct ssam_event *event)
  2483. +{
  2484. + int status;
  2485. +
  2486. + status = san_acpi_notify_power_event(dev, SAN_PWR_EVENT_ADP1_STAT);
  2487. + if (status)
  2488. + return status;
  2489. +
  2490. + /*
  2491. + * Enusre that the battery states get updated correctly.
  2492. + * When the battery is fully charged and an adapter is plugged in, it
  2493. + * sometimes is not updated correctly, instead showing it as charging.
  2494. + * Explicitly trigger battery updates to fix this.
  2495. + */
  2496. +
  2497. + status = san_acpi_notify_power_event(dev, SAN_PWR_EVENT_BAT1_STAT);
  2498. + if (status)
  2499. + return status;
  2500. +
  2501. + return san_acpi_notify_power_event(dev, SAN_PWR_EVENT_BAT2_STAT);
  2502. +}
  2503. +
  2504. +static inline int san_evt_power_bix(struct device *dev, const struct ssam_event *event)
  2505. +{
  2506. + enum san_pwr_event evcode;
  2507. +
  2508. + if (event->instance_id == 0x02)
  2509. + evcode = SAN_PWR_EVENT_BAT2_INFO;
  2510. + else
  2511. + evcode = SAN_PWR_EVENT_BAT1_INFO;
  2512. +
  2513. + return san_acpi_notify_power_event(dev, evcode);
  2514. +}
  2515. +
  2516. +static inline int san_evt_power_bst(struct device *dev, const struct ssam_event *event)
  2517. +{
  2518. + enum san_pwr_event evcode;
  2519. +
  2520. + if (event->instance_id == 0x02)
  2521. + evcode = SAN_PWR_EVENT_BAT2_STAT;
  2522. + else
  2523. + evcode = SAN_PWR_EVENT_BAT1_STAT;
  2524. +
  2525. + return san_acpi_notify_power_event(dev, evcode);
  2526. +}
  2527. +
  2528. +static inline int san_evt_power_dptf(struct device *dev, const struct ssam_event *event)
  2529. +{
  2530. + union acpi_object payload;
  2531. + acpi_handle san = ACPI_HANDLE(dev);
  2532. + union acpi_object *obj;
  2533. +
  2534. + if (!san_acpi_can_notify(dev, SAN_PWR_EVENT_DPTF))
  2535. + return 0;
  2536. +
  2537. + /*
  2538. + * The Surface ACPI expects a buffer and not a package. It specifically
  2539. + * checks for ObjectType (Arg3) == 0x03. This will cause a warning in
  2540. + * acpica/nsarguments.c, but this can safely be ignored.
  2541. + */
  2542. + payload.type = ACPI_TYPE_BUFFER;
  2543. + payload.buffer.length = event->length;
  2544. + payload.buffer.pointer = (u8 *)&event->data[0];
  2545. +
  2546. + dev_dbg(dev, "notify power event 0x%02x\n", event->command_id);
  2547. + obj = acpi_evaluate_dsm_typed(san, &SAN_DSM_UUID, SAN_DSM_REVISION,
  2548. + SAN_PWR_EVENT_DPTF, &payload,
  2549. + ACPI_TYPE_BUFFER);
  2550. +
  2551. + if (IS_ERR_OR_NULL(obj))
  2552. + return obj ? PTR_ERR(obj) : -ENXIO;
  2553. +
  2554. + if (obj->buffer.length != 1 || obj->buffer.pointer[0] != 0) {
  2555. + dev_err(dev, "got unexpected result from _DSM\n");
  2556. + return -EFAULT;
  2557. + }
  2558. +
  2559. + ACPI_FREE(obj);
  2560. + return 0;
  2561. +}
  2562. +
  2563. +static unsigned long san_evt_power_delay(u8 cid)
  2564. +{
  2565. + switch (cid) {
  2566. + case SAM_EVENT_PWR_CID_ADAPTER:
  2567. + /*
  2568. + * Wait for battery state to update before signalling adapter change.
  2569. + */
  2570. + return SAM_EVENT_DELAY_PWR_ADAPTER;
  2571. +
  2572. + case SAM_EVENT_PWR_CID_BST:
  2573. + /*
  2574. + * Ensure we do not miss anything important due to caching.
  2575. + */
  2576. + return SAM_EVENT_DELAY_PWR_BST;
  2577. +
  2578. + case SAM_EVENT_PWR_CID_BIX:
  2579. + case SAM_EVENT_PWR_CID_DPTF:
  2580. + default:
  2581. + return 0;
  2582. + }
  2583. +}
  2584. +
  2585. +static bool san_evt_power(const struct ssam_event *event, struct device *dev)
  2586. +{
  2587. + int status;
  2588. +
  2589. + switch (event->command_id) {
  2590. + case SAM_EVENT_PWR_CID_BIX:
  2591. + status = san_evt_power_bix(dev, event);
  2592. + break;
  2593. +
  2594. + case SAM_EVENT_PWR_CID_BST:
  2595. + status = san_evt_power_bst(dev, event);
  2596. + break;
  2597. +
  2598. + case SAM_EVENT_PWR_CID_ADAPTER:
  2599. + status = san_evt_power_adapter(dev, event);
  2600. + break;
  2601. +
  2602. + case SAM_EVENT_PWR_CID_DPTF:
  2603. + status = san_evt_power_dptf(dev, event);
  2604. + break;
  2605. +
  2606. + default:
  2607. + return false;
  2608. + }
  2609. +
  2610. + if (status)
  2611. + dev_err(dev, "error handling power event (cid = %x)\n",
  2612. + event->command_id);
  2613. +
  2614. + return true;
  2615. +}
  2616. +
  2617. +static void san_evt_power_workfn(struct work_struct *work)
  2618. +{
  2619. + struct san_event_work *ev = container_of(work, struct san_event_work, work.work);
  2620. +
  2621. + san_evt_power(&ev->event, &ev->dev->dev);
  2622. + kfree(ev);
  2623. +}
  2624. +
  2625. +
  2626. +static u32 san_evt_power_nb(struct ssam_notifier_block *nb, const struct ssam_event *event)
  2627. +{
  2628. + struct san_drvdata *drvdata = container_of(nb, struct san_drvdata, nf_bat.base);
  2629. + struct san_event_work *work;
  2630. + unsigned long delay = san_evt_power_delay(event->command_id);
  2631. +
  2632. + if (delay == 0) {
  2633. + if (san_evt_power(event, &drvdata->dev->dev))
  2634. + return SSAM_NOTIF_HANDLED;
  2635. + else
  2636. + return 0;
  2637. + }
  2638. +
  2639. + work = kzalloc(sizeof(struct san_event_work) + event->length, GFP_KERNEL);
  2640. + if (!work)
  2641. + return ssam_notifier_from_errno(-ENOMEM);
  2642. +
  2643. + INIT_DELAYED_WORK(&work->work, san_evt_power_workfn);
  2644. + work->dev = drvdata->dev;
  2645. +
  2646. + memcpy(&work->event, event, sizeof(struct ssam_event) + event->length);
  2647. +
  2648. + schedule_delayed_work(&work->work, delay);
  2649. + return SSAM_NOTIF_HANDLED;
  2650. +}
  2651. +
  2652. +
  2653. +static inline int san_evt_thermal_notify(struct device *dev, const struct ssam_event *event)
  2654. +{
  2655. + return san_acpi_notify_sensor_trip_point(dev, event->instance_id);
  2656. +}
  2657. +
  2658. +static bool san_evt_thermal(const struct ssam_event *event, struct device *dev)
  2659. +{
  2660. + int status;
  2661. +
  2662. + switch (event->command_id) {
  2663. + case SAM_EVENT_TEMP_CID_NOTIFY_SENSOR_TRIP_POINT:
  2664. + status = san_evt_thermal_notify(dev, event);
  2665. + break;
  2666. +
  2667. + default:
  2668. + return false;
  2669. + }
  2670. +
  2671. + if (status) {
  2672. + dev_err(dev, "error handling thermal event (cid = %x)\n",
  2673. + event->command_id);
  2674. + }
  2675. +
  2676. + return true;
  2677. +}
  2678. +
  2679. +static u32 san_evt_thermal_nb(struct ssam_notifier_block *nb, const struct ssam_event *event)
  2680. +{
  2681. + struct san_drvdata *drvdata = container_of(nb, struct san_drvdata, nf_tmp.base);
  2682. + struct platform_device *pdev = drvdata->dev;
  2683. +
  2684. + if (san_evt_thermal(event, &pdev->dev))
  2685. + return SSAM_NOTIF_HANDLED;
  2686. + else
  2687. + return 0;
  2688. +}
  2689. +
  2690. +
  2691. +static struct gsb_data_rqsx
  2692. +*san_validate_rqsx(struct device *dev, const char *type, struct gsb_buffer *buffer)
  2693. +{
  2694. + struct gsb_data_rqsx *rqsx = &buffer->data.rqsx;
  2695. +
  2696. + if (buffer->len < 8) {
  2697. + dev_err(dev, "invalid %s package (len = %d)\n",
  2698. + type, buffer->len);
  2699. + return NULL;
  2700. + }
  2701. +
  2702. + if (rqsx->cdl != buffer->len - 8) {
  2703. + dev_err(dev, "bogus %s package (len = %d, cdl = %d)\n",
  2704. + type, buffer->len, rqsx->cdl);
  2705. + return NULL;
  2706. + }
  2707. +
  2708. + if (rqsx->tid != 0x01) {
  2709. + dev_warn(dev, "unsupported %s package (tid = 0x%02x)\n",
  2710. + type, rqsx->tid);
  2711. + return NULL;
  2712. + }
  2713. +
  2714. + return rqsx;
  2715. +}
  2716. +
  2717. +static acpi_status
  2718. +san_etwl(struct san_opreg_context *ctx, struct gsb_buffer *buffer)
  2719. +{
  2720. + struct gsb_data_etwl *etwl = &buffer->data.etwl;
  2721. +
  2722. + if (buffer->len < 3) {
  2723. + dev_err(ctx->dev, "invalid ETWL package (len = %d)\n", buffer->len);
  2724. + return AE_OK;
  2725. + }
  2726. +
  2727. + dev_err(ctx->dev, "ETWL(0x%02x, 0x%02x): %.*s\n",
  2728. + etwl->etw3, etwl->etw4,
  2729. + buffer->len - 3, (char *)etwl->msg);
  2730. +
  2731. + // indicate success
  2732. + buffer->status = 0x00;
  2733. + buffer->len = 0x00;
  2734. +
  2735. + return AE_OK;
  2736. +}
  2737. +
  2738. +static acpi_status
  2739. +san_rqst(struct san_opreg_context *ctx, struct gsb_buffer *buffer)
  2740. +{
  2741. + struct gsb_data_rqsx *gsb_rqst = san_validate_rqsx(ctx->dev, "RQST", buffer);
  2742. + struct surface_sam_ssh_rqst rqst = {};
  2743. + struct surface_sam_ssh_buf result = {};
  2744. + int status = 0;
  2745. + int try;
  2746. +
  2747. + if (!gsb_rqst)
  2748. + return AE_OK;
  2749. +
  2750. + rqst.tc = gsb_rqst->tc;
  2751. + rqst.cid = gsb_rqst->cid;
  2752. + rqst.iid = gsb_rqst->iid;
  2753. + rqst.chn = gsb_rqst->tid;
  2754. + rqst.snc = gsb_rqst->snc;
  2755. + rqst.cdl = gsb_rqst->cdl;
  2756. + rqst.pld = &gsb_rqst->pld[0];
  2757. +
  2758. + result.cap = SURFACE_SAM_SSH_MAX_RQST_RESPONSE;
  2759. + result.len = 0;
  2760. + result.data = kzalloc(result.cap, GFP_KERNEL);
  2761. +
  2762. + if (!result.data)
  2763. + return AE_NO_MEMORY;
  2764. +
  2765. + for (try = 0; try < SAN_RQST_RETRY; try++) {
  2766. + if (try)
  2767. + dev_warn(ctx->dev, SAN_RQST_TAG "IO error occurred, trying again\n");
  2768. +
  2769. + status = surface_sam_ssh_rqst(&rqst, &result);
  2770. + if (status != -EIO)
  2771. + break;
  2772. + }
  2773. +
  2774. + if (rqst.tc == 0x11 && rqst.cid == 0x0D && status == -EPERM) {
  2775. + /* Base state quirk:
  2776. + * The base state may be queried from ACPI when the EC is still
  2777. + * suspended. In this case it will return '-EPERM'. This query
  2778. + * will only be triggered from the ACPI lid GPE interrupt, thus
  2779. + * we are either in laptop or studio mode (base status 0x01 or
  2780. + * 0x02). Furthermore, we will only get here if the device (and
  2781. + * EC) have been suspended.
  2782. + *
  2783. + * We now assume that the device is in laptop mode (0x01). This
  2784. + * has the drawback that it will wake the device when unfolding
  2785. + * it in studio mode, but it also allows us to avoid actively
  2786. + * waiting for the EC to wake up, which may incur a notable
  2787. + * delay.
  2788. + */
  2789. +
  2790. + buffer->status = 0x00;
  2791. + buffer->len = 0x03;
  2792. + buffer->data.out.status = 0x00;
  2793. + buffer->data.out.len = 0x01;
  2794. + buffer->data.out.pld[0] = 0x01;
  2795. +
  2796. + } else if (!status) { // success
  2797. + buffer->status = 0x00;
  2798. + buffer->len = result.len + 2;
  2799. + buffer->data.out.status = 0x00;
  2800. + buffer->data.out.len = result.len;
  2801. + memcpy(&buffer->data.out.pld[0], result.data, result.len);
  2802. +
  2803. + } else { // failure
  2804. + dev_err(ctx->dev, SAN_RQST_TAG "failed with error %d\n", status);
  2805. + buffer->status = 0x00;
  2806. + buffer->len = 0x02;
  2807. + buffer->data.out.status = 0x01; // indicate _SSH error
  2808. + buffer->data.out.len = 0x00;
  2809. + }
  2810. +
  2811. + kfree(result.data);
  2812. +
  2813. + return AE_OK;
  2814. +}
  2815. +
  2816. +static acpi_status
  2817. +san_rqsg(struct san_opreg_context *ctx, struct gsb_buffer *buffer)
  2818. +{
  2819. + struct gsb_data_rqsx *gsb_rqsg = san_validate_rqsx(ctx->dev, "RQSG", buffer);
  2820. + struct surface_sam_san_rqsg rqsg = {};
  2821. + int status;
  2822. +
  2823. + if (!gsb_rqsg)
  2824. + return AE_OK;
  2825. +
  2826. + rqsg.tc = gsb_rqsg->tc;
  2827. + rqsg.cid = gsb_rqsg->cid;
  2828. + rqsg.iid = gsb_rqsg->iid;
  2829. + rqsg.cdl = gsb_rqsg->cdl;
  2830. + rqsg.pld = &gsb_rqsg->pld[0];
  2831. +
  2832. + status = san_call_rqsg_handler(&rqsg);
  2833. + if (!status) {
  2834. + buffer->status = 0x00;
  2835. + buffer->len = 0x02;
  2836. + buffer->data.out.status = 0x00;
  2837. + buffer->data.out.len = 0x00;
  2838. + } else {
  2839. + dev_err(ctx->dev, SAN_RQSG_TAG "failed with error %d\n", status);
  2840. + buffer->status = 0x00;
  2841. + buffer->len = 0x02;
  2842. + buffer->data.out.status = 0x01; // indicate _SSH error
  2843. + buffer->data.out.len = 0x00;
  2844. + }
  2845. +
  2846. + return AE_OK;
  2847. +}
  2848. +
  2849. +
  2850. +static acpi_status
  2851. +san_opreg_handler(u32 function, acpi_physical_address command,
  2852. + u32 bits, u64 *value64,
  2853. + void *opreg_context, void *region_context)
  2854. +{
  2855. + struct san_opreg_context *context = opreg_context;
  2856. + struct gsb_buffer *buffer = (struct gsb_buffer *)value64;
  2857. + int accessor_type = (0xFFFF0000 & function) >> 16;
  2858. +
  2859. + if (command != 0) {
  2860. + dev_warn(context->dev, "unsupported command: 0x%02llx\n", command);
  2861. + return AE_OK;
  2862. + }
  2863. +
  2864. + if (accessor_type != ACPI_GSB_ACCESS_ATTRIB_RAW_PROCESS) {
  2865. + dev_err(context->dev, "invalid access type: 0x%02x\n", accessor_type);
  2866. + return AE_OK;
  2867. + }
  2868. +
  2869. + // buffer must have at least contain the command-value
  2870. + if (buffer->len == 0) {
  2871. + dev_err(context->dev, "request-package too small\n");
  2872. + return AE_OK;
  2873. + }
  2874. +
  2875. + switch (buffer->data.in.cv) {
  2876. + case 0x01: return san_rqst(context, buffer);
  2877. + case 0x02: return san_etwl(context, buffer);
  2878. + case 0x03: return san_rqsg(context, buffer);
  2879. + }
  2880. +
  2881. + dev_warn(context->dev, "unsupported SAN0 request (cv: 0x%02x)\n", buffer->data.in.cv);
  2882. + return AE_OK;
  2883. +}
  2884. +
  2885. +static int san_events_register(struct platform_device *pdev)
  2886. +{
  2887. + struct san_drvdata *drvdata = platform_get_drvdata(pdev);
  2888. + int status;
  2889. +
  2890. + drvdata->nf_bat.base.priority = 1;
  2891. + drvdata->nf_bat.base.fn = san_evt_power_nb;
  2892. + drvdata->nf_bat.event.reg = SSAM_EVENT_REGISTRY_SAM;
  2893. + drvdata->nf_bat.event.id.target_category = SSAM_SSH_TC_BAT;
  2894. + drvdata->nf_bat.event.id.instance = 0;
  2895. + drvdata->nf_bat.event.flags = SSAM_EVENT_SEQUENCED;
  2896. +
  2897. + drvdata->nf_tmp.base.priority = 1;
  2898. + drvdata->nf_tmp.base.fn = san_evt_thermal_nb;
  2899. + drvdata->nf_tmp.event.reg = SSAM_EVENT_REGISTRY_SAM;
  2900. + drvdata->nf_tmp.event.id.target_category = SSAM_SSH_TC_TMP;
  2901. + drvdata->nf_tmp.event.id.instance = 0;
  2902. + drvdata->nf_tmp.event.flags = SSAM_EVENT_SEQUENCED;
  2903. +
  2904. + status = surface_sam_ssh_notifier_register(&drvdata->nf_bat);
  2905. + if (status)
  2906. + return status;
  2907. +
  2908. + status = surface_sam_ssh_notifier_register(&drvdata->nf_tmp);
  2909. + if (status)
  2910. + surface_sam_ssh_notifier_unregister(&drvdata->nf_bat);
  2911. +
  2912. + return status;
  2913. +}
  2914. +
  2915. +static void san_events_unregister(struct platform_device *pdev)
  2916. +{
  2917. + struct san_drvdata *drvdata = platform_get_drvdata(pdev);
  2918. +
  2919. + surface_sam_ssh_notifier_unregister(&drvdata->nf_bat);
  2920. + surface_sam_ssh_notifier_unregister(&drvdata->nf_tmp);
  2921. +}
  2922. +
  2923. +
  2924. +static int san_consumers_link(struct platform_device *pdev,
  2925. + const struct san_acpi_consumer *cons,
  2926. + struct san_consumers *out)
  2927. +{
  2928. + const struct san_acpi_consumer *con;
  2929. + struct san_consumer_link *links, *link;
  2930. + struct acpi_device *adev;
  2931. + acpi_handle handle;
  2932. + u32 max_links = 0;
  2933. + int status;
  2934. +
  2935. + if (!cons)
  2936. + return 0;
  2937. +
  2938. + // count links
  2939. + for (con = cons; con->path; ++con)
  2940. + max_links += 1;
  2941. +
  2942. + // allocate
  2943. + links = kcalloc(max_links, sizeof(struct san_consumer_link), GFP_KERNEL);
  2944. + link = &links[0];
  2945. +
  2946. + if (!links)
  2947. + return -ENOMEM;
  2948. +
  2949. + // create links
  2950. + for (con = cons; con->path; ++con) {
  2951. + status = acpi_get_handle(NULL, con->path, &handle);
  2952. + if (status) {
  2953. + if (con->required || status != AE_NOT_FOUND) {
  2954. + status = -ENXIO;
  2955. + goto cleanup;
  2956. + } else {
  2957. + continue;
  2958. + }
  2959. + }
  2960. +
  2961. + status = acpi_bus_get_device(handle, &adev);
  2962. + if (status)
  2963. + goto cleanup;
  2964. +
  2965. + link->link = device_link_add(&adev->dev, &pdev->dev, con->flags);
  2966. + if (!(link->link)) {
  2967. + status = -EFAULT;
  2968. + goto cleanup;
  2969. + }
  2970. + link->properties = con;
  2971. +
  2972. + link += 1;
  2973. + }
  2974. +
  2975. + out->num = link - links;
  2976. + out->links = links;
  2977. +
  2978. + return 0;
  2979. +
  2980. +cleanup:
  2981. + for (link = link - 1; link >= links; --link) {
  2982. + if (link->properties->flags & DL_FLAG_STATELESS)
  2983. + device_link_del(link->link);
  2984. + }
  2985. +
  2986. + return status;
  2987. +}
  2988. +
  2989. +static void san_consumers_unlink(struct san_consumers *consumers)
  2990. +{
  2991. + u32 i;
  2992. +
  2993. + if (!consumers)
  2994. + return;
  2995. +
  2996. + for (i = 0; i < consumers->num; ++i) {
  2997. + if (consumers->links[i].properties->flags & DL_FLAG_STATELESS)
  2998. + device_link_del(consumers->links[i].link);
  2999. + }
  3000. +
  3001. + kfree(consumers->links);
  3002. +
  3003. + consumers->num = 0;
  3004. + consumers->links = NULL;
  3005. +}
  3006. +
  3007. +static int surface_sam_san_probe(struct platform_device *pdev)
  3008. +{
  3009. + const struct san_acpi_consumer *cons;
  3010. + struct san_drvdata *drvdata;
  3011. + acpi_handle san = ACPI_HANDLE(&pdev->dev); // _SAN device node
  3012. + int status;
  3013. +
  3014. + /*
  3015. + * Defer probe if the _SSH driver has not set up the controller yet. This
  3016. + * makes sure we do not fail any initial requests (e.g. _STA request without
  3017. + * which the battery does not get set up correctly). Otherwise register as
  3018. + * consumer to set up a device_link.
  3019. + */
  3020. + status = surface_sam_ssh_consumer_register(&pdev->dev);
  3021. + if (status)
  3022. + return status == -ENXIO ? -EPROBE_DEFER : status;
  3023. +
  3024. + drvdata = kzalloc(sizeof(struct san_drvdata), GFP_KERNEL);
  3025. + if (!drvdata)
  3026. + return -ENOMEM;
  3027. +
  3028. + drvdata->dev = pdev;
  3029. + drvdata->opreg_ctx.dev = &pdev->dev;
  3030. +
  3031. + cons = acpi_device_get_match_data(&pdev->dev);
  3032. + status = san_consumers_link(pdev, cons, &drvdata->consumers);
  3033. + if (status)
  3034. + goto err_consumers;
  3035. +
  3036. + platform_set_drvdata(pdev, drvdata);
  3037. +
  3038. + status = acpi_install_address_space_handler(san,
  3039. + ACPI_ADR_SPACE_GSBUS,
  3040. + &san_opreg_handler,
  3041. + NULL, &drvdata->opreg_ctx);
  3042. +
  3043. + if (ACPI_FAILURE(status)) {
  3044. + status = -ENODEV;
  3045. + goto err_install_handler;
  3046. + }
  3047. +
  3048. + status = san_events_register(pdev);
  3049. + if (status)
  3050. + goto err_enable_events;
  3051. +
  3052. + mutex_lock(&rqsg_if.lock);
  3053. + if (!rqsg_if.san_dev)
  3054. + rqsg_if.san_dev = &pdev->dev;
  3055. + else
  3056. + status = -EBUSY;
  3057. + mutex_unlock(&rqsg_if.lock);
  3058. +
  3059. + if (status)
  3060. + goto err_install_dev;
  3061. +
  3062. + acpi_walk_dep_device_list(san);
  3063. + return 0;
  3064. +
  3065. +err_install_dev:
  3066. + san_events_unregister(pdev);
  3067. +err_enable_events:
  3068. + acpi_remove_address_space_handler(san, ACPI_ADR_SPACE_GSBUS, &san_opreg_handler);
  3069. +err_install_handler:
  3070. + platform_set_drvdata(san, NULL);
  3071. + san_consumers_unlink(&drvdata->consumers);
  3072. +err_consumers:
  3073. + kfree(drvdata);
  3074. + return status;
  3075. +}
  3076. +
  3077. +static int surface_sam_san_remove(struct platform_device *pdev)
  3078. +{
  3079. + struct san_drvdata *drvdata = platform_get_drvdata(pdev);
  3080. + acpi_handle san = ACPI_HANDLE(&pdev->dev); // _SAN device node
  3081. + acpi_status status = AE_OK;
  3082. +
  3083. + mutex_lock(&rqsg_if.lock);
  3084. + rqsg_if.san_dev = NULL;
  3085. + mutex_unlock(&rqsg_if.lock);
  3086. +
  3087. + acpi_remove_address_space_handler(san, ACPI_ADR_SPACE_GSBUS, &san_opreg_handler);
  3088. + san_events_unregister(pdev);
  3089. +
  3090. + /*
  3091. + * We have unregistered our event sources. Now we need to ensure that
  3092. + * all delayed works they may have spawned are run to completion.
  3093. + */
  3094. + flush_scheduled_work();
  3095. +
  3096. + san_consumers_unlink(&drvdata->consumers);
  3097. + kfree(drvdata);
  3098. +
  3099. + platform_set_drvdata(pdev, NULL);
  3100. + return status;
  3101. +}
  3102. +
  3103. +
  3104. +static const struct san_acpi_consumer san_mshw0091_consumers[] = {
  3105. + { "\\_SB.SRTC", true, DL_FLAG_PM_RUNTIME | DL_FLAG_STATELESS },
  3106. + { "\\ADP1", true, DL_FLAG_PM_RUNTIME | DL_FLAG_STATELESS },
  3107. + { "\\_SB.BAT1", true, DL_FLAG_PM_RUNTIME | DL_FLAG_STATELESS },
  3108. + { "\\_SB.BAT2", false, DL_FLAG_PM_RUNTIME | DL_FLAG_STATELESS },
  3109. + { },
  3110. +};
  3111. +
  3112. +static const struct acpi_device_id surface_sam_san_match[] = {
  3113. + { "MSHW0091", (unsigned long) san_mshw0091_consumers },
  3114. + { },
  3115. +};
  3116. +MODULE_DEVICE_TABLE(acpi, surface_sam_san_match);
  3117. +
  3118. +static struct platform_driver surface_sam_san = {
  3119. + .probe = surface_sam_san_probe,
  3120. + .remove = surface_sam_san_remove,
  3121. + .driver = {
  3122. + .name = "surface_sam_san",
  3123. + .acpi_match_table = surface_sam_san_match,
  3124. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  3125. + },
  3126. +};
  3127. +module_platform_driver(surface_sam_san);
  3128. +
  3129. +MODULE_AUTHOR("Maximilian Luz <luzmaximilian@gmail.com>");
  3130. +MODULE_DESCRIPTION("Surface ACPI Notify Driver for 5th Generation Surface Devices");
  3131. +MODULE_LICENSE("GPL");
  3132. diff --git a/drivers/platform/x86/surface_sam/surface_sam_san.h b/drivers/platform/x86/surface_sam/surface_sam_san.h
  3133. new file mode 100644
  3134. index 0000000000000..2b9dee159bbbc
  3135. --- /dev/null
  3136. +++ b/drivers/platform/x86/surface_sam/surface_sam_san.h
  3137. @@ -0,0 +1,30 @@
  3138. +/* SPDX-License-Identifier: GPL-2.0-or-later */
  3139. +/*
  3140. + * Interface for Surface ACPI/Notify (SAN).
  3141. + *
  3142. + * The SAN is the main interface between the Surface Serial Hub (SSH) and the
  3143. + * Surface/System Aggregator Module (SAM). It allows requests to be translated
  3144. + * from ACPI to SSH/SAM. It also interfaces with the discrete GPU hot-plug
  3145. + * driver.
  3146. + */
  3147. +
  3148. +#ifndef _SURFACE_SAM_SAN_H
  3149. +#define _SURFACE_SAM_SAN_H
  3150. +
  3151. +#include <linux/types.h>
  3152. +
  3153. +
  3154. +struct surface_sam_san_rqsg {
  3155. + u8 tc; // target category
  3156. + u8 cid; // command ID
  3157. + u8 iid; // instance ID
  3158. + u8 cdl; // command data length (length of payload)
  3159. + u8 *pld; // pointer to payload of length cdl
  3160. +};
  3161. +
  3162. +typedef int (*surface_sam_san_rqsg_handler_fn)(struct surface_sam_san_rqsg *rqsg, void *data);
  3163. +
  3164. +int surface_sam_san_consumer_register(struct device *consumer, u32 flags);
  3165. +int surface_sam_san_set_rqsg_handler(surface_sam_san_rqsg_handler_fn fn, void *data);
  3166. +
  3167. +#endif /* _SURFACE_SAM_SAN_H */
  3168. diff --git a/drivers/platform/x86/surface_sam/surface_sam_sid.c b/drivers/platform/x86/surface_sam/surface_sam_sid.c
  3169. new file mode 100644
  3170. index 0000000000000..caa2e6446b5f4
  3171. --- /dev/null
  3172. +++ b/drivers/platform/x86/surface_sam/surface_sam_sid.c
  3173. @@ -0,0 +1,281 @@
  3174. +// SPDX-License-Identifier: GPL-2.0-or-later
  3175. +/*
  3176. + * Surface Integration Driver.
  3177. + * MFD driver to provide device/model dependent functionality.
  3178. + */
  3179. +
  3180. +#include <linux/acpi.h>
  3181. +#include <linux/kernel.h>
  3182. +#include <linux/module.h>
  3183. +#include <linux/platform_device.h>
  3184. +#include <linux/mfd/core.h>
  3185. +
  3186. +#include "surface_sam_sid_power.h"
  3187. +#include "surface_sam_sid_vhf.h"
  3188. +
  3189. +
  3190. +struct ssam_battery_properties ssam_battery_props_bat1 = {
  3191. + .registry = SSAM_EVENT_REGISTRY_SAM,
  3192. + .num = 0,
  3193. + .channel = 1,
  3194. + .instance = 1,
  3195. +};
  3196. +
  3197. +struct ssam_battery_properties ssam_battery_props_bat2_sb3 = {
  3198. + .registry = SSAM_EVENT_REGISTRY_KIP,
  3199. + .num = 1,
  3200. + .channel = 2,
  3201. + .instance = 1,
  3202. +};
  3203. +
  3204. +
  3205. +static const struct ssam_hid_properties ssam_hid_props_keyboard = {
  3206. + .registry = SSAM_EVENT_REGISTRY_REG,
  3207. + .instance = 1,
  3208. +};
  3209. +
  3210. +static const struct ssam_hid_properties ssam_hid_props_touchpad = {
  3211. + .registry = SSAM_EVENT_REGISTRY_REG,
  3212. + .instance = 3,
  3213. +};
  3214. +
  3215. +static const struct ssam_hid_properties ssam_hid_props_iid5 = {
  3216. + .registry = SSAM_EVENT_REGISTRY_REG,
  3217. + .instance = 5,
  3218. +};
  3219. +
  3220. +static const struct ssam_hid_properties ssam_hid_props_iid6 = {
  3221. + .registry = SSAM_EVENT_REGISTRY_REG,
  3222. + .instance = 6,
  3223. +};
  3224. +
  3225. +
  3226. +static const struct mfd_cell sid_devs_sp4[] = {
  3227. + { .name = "surface_sam_sid_gpelid", .id = -1 },
  3228. + { .name = "surface_sam_sid_perfmode", .id = -1 },
  3229. + { },
  3230. +};
  3231. +
  3232. +static const struct mfd_cell sid_devs_sp6[] = {
  3233. + { .name = "surface_sam_sid_gpelid", .id = -1 },
  3234. + { .name = "surface_sam_sid_perfmode", .id = -1 },
  3235. + { },
  3236. +};
  3237. +
  3238. +static const struct mfd_cell sid_devs_sp7[] = {
  3239. + { .name = "surface_sam_sid_gpelid", .id = -1 },
  3240. + { .name = "surface_sam_sid_perfmode", .id = -1 },
  3241. + { .name = "surface_sam_sid_ac", .id = -1 },
  3242. + {
  3243. + .name = "surface_sam_sid_battery",
  3244. + .id = -1,
  3245. + .platform_data = &ssam_battery_props_bat1,
  3246. + .pdata_size = sizeof(struct ssam_battery_properties),
  3247. + },
  3248. + { },
  3249. +};
  3250. +
  3251. +static const struct mfd_cell sid_devs_sb1[] = {
  3252. + { .name = "surface_sam_sid_gpelid", .id = -1 },
  3253. + { },
  3254. +};
  3255. +
  3256. +static const struct mfd_cell sid_devs_sb2[] = {
  3257. + { .name = "surface_sam_sid_gpelid", .id = -1 },
  3258. + { .name = "surface_sam_sid_perfmode", .id = -1 },
  3259. + { },
  3260. +};
  3261. +
  3262. +static const struct mfd_cell sid_devs_sb3[] = {
  3263. + { .name = "surface_sam_sid_gpelid", .id = -1 },
  3264. + { .name = "surface_sam_sid_perfmode", .id = -1 },
  3265. + { .name = "surface_sam_sid_ac", .id = -1 },
  3266. + {
  3267. + .name = "surface_sam_sid_battery",
  3268. + .id = 1,
  3269. + .platform_data = &ssam_battery_props_bat1,
  3270. + .pdata_size = sizeof(struct ssam_battery_properties),
  3271. + },
  3272. + {
  3273. + .name = "surface_sam_sid_battery",
  3274. + .id = 2,
  3275. + .platform_data = &ssam_battery_props_bat2_sb3,
  3276. + .pdata_size = sizeof(struct ssam_battery_properties),
  3277. + },
  3278. + {
  3279. + .name = "surface_sam_sid_vhf",
  3280. + .id = 1,
  3281. + .platform_data = (void *)&ssam_hid_props_keyboard,
  3282. + .pdata_size = sizeof(struct ssam_hid_properties),
  3283. + },
  3284. + {
  3285. + .name = "surface_sam_sid_vhf",
  3286. + .id = 3,
  3287. + .platform_data = (void *)&ssam_hid_props_touchpad,
  3288. + .pdata_size = sizeof(struct ssam_hid_properties),
  3289. + },
  3290. + {
  3291. + .name = "surface_sam_sid_vhf",
  3292. + .id = 5,
  3293. + .platform_data = (void *)&ssam_hid_props_iid5,
  3294. + .pdata_size = sizeof(struct ssam_hid_properties),
  3295. + },
  3296. + {
  3297. + .name = "surface_sam_sid_vhf",
  3298. + .id = 6,
  3299. + .platform_data = (void *)&ssam_hid_props_iid6,
  3300. + .pdata_size = sizeof(struct ssam_hid_properties),
  3301. + },
  3302. + { },
  3303. +};
  3304. +
  3305. +static const struct mfd_cell sid_devs_sl1[] = {
  3306. + { .name = "surface_sam_sid_gpelid", .id = -1 },
  3307. + { },
  3308. +};
  3309. +
  3310. +static const struct mfd_cell sid_devs_sl2[] = {
  3311. + { .name = "surface_sam_sid_gpelid", .id = -1 },
  3312. + { },
  3313. +};
  3314. +
  3315. +static const struct mfd_cell sid_devs_sl3_13[] = {
  3316. + { .name = "surface_sam_sid_gpelid", .id = -1 },
  3317. + { .name = "surface_sam_sid_perfmode", .id = -1 },
  3318. + { .name = "surface_sam_sid_ac", .id = -1 },
  3319. + {
  3320. + .name = "surface_sam_sid_battery",
  3321. + .id = -1,
  3322. + .platform_data = &ssam_battery_props_bat1,
  3323. + .pdata_size = sizeof(struct ssam_battery_properties),
  3324. + },
  3325. + {
  3326. + .name = "surface_sam_sid_vhf",
  3327. + .id = 1,
  3328. + .platform_data = (void *)&ssam_hid_props_keyboard,
  3329. + .pdata_size = sizeof(struct ssam_hid_properties),
  3330. + },
  3331. + {
  3332. + .name = "surface_sam_sid_vhf",
  3333. + .id = 3,
  3334. + .platform_data = (void *)&ssam_hid_props_touchpad,
  3335. + .pdata_size = sizeof(struct ssam_hid_properties),
  3336. + },
  3337. + {
  3338. + .name = "surface_sam_sid_vhf",
  3339. + .id = 5,
  3340. + .platform_data = (void *)&ssam_hid_props_iid5,
  3341. + .pdata_size = sizeof(struct ssam_hid_properties),
  3342. + },
  3343. + { },
  3344. +};
  3345. +
  3346. +static const struct mfd_cell sid_devs_sl3_15[] = {
  3347. + { .name = "surface_sam_sid_perfmode", .id = -1 },
  3348. + { .name = "surface_sam_sid_ac", .id = -1 },
  3349. + {
  3350. + .name = "surface_sam_sid_battery",
  3351. + .id = -1,
  3352. + .platform_data = &ssam_battery_props_bat1,
  3353. + .pdata_size = sizeof(struct ssam_battery_properties),
  3354. + },
  3355. + {
  3356. + .name = "surface_sam_sid_vhf",
  3357. + .id = 1,
  3358. + .platform_data = (void *)&ssam_hid_props_keyboard,
  3359. + .pdata_size = sizeof(struct ssam_hid_properties),
  3360. + },
  3361. + {
  3362. + .name = "surface_sam_sid_vhf",
  3363. + .id = 3,
  3364. + .platform_data = (void *)&ssam_hid_props_touchpad,
  3365. + .pdata_size = sizeof(struct ssam_hid_properties),
  3366. + },
  3367. + {
  3368. + .name = "surface_sam_sid_vhf",
  3369. + .id = 5,
  3370. + .platform_data = (void *)&ssam_hid_props_iid5,
  3371. + .pdata_size = sizeof(struct ssam_hid_properties),
  3372. + },
  3373. + { },
  3374. +};
  3375. +
  3376. +static const struct acpi_device_id surface_sam_sid_match[] = {
  3377. + /* Surface Pro 4, 5, and 6 */
  3378. + { "MSHW0081", (unsigned long)sid_devs_sp4 },
  3379. +
  3380. + /* Surface Pro 6 (OMBR >= 0x10) */
  3381. + { "MSHW0111", (unsigned long)sid_devs_sp6 },
  3382. +
  3383. + /* Surface Pro 7 */
  3384. + { "MSHW0116", (unsigned long)sid_devs_sp7 },
  3385. +
  3386. + /* Surface Book 1 */
  3387. + { "MSHW0080", (unsigned long)sid_devs_sb1 },
  3388. +
  3389. + /* Surface Book 2 */
  3390. + { "MSHW0107", (unsigned long)sid_devs_sb2 },
  3391. +
  3392. + /* Surface Book 3 */
  3393. + { "MSHW0117", (unsigned long)sid_devs_sb3 },
  3394. +
  3395. + /* Surface Laptop 1 */
  3396. + { "MSHW0086", (unsigned long)sid_devs_sl1 },
  3397. +
  3398. + /* Surface Laptop 2 */
  3399. + { "MSHW0112", (unsigned long)sid_devs_sl2 },
  3400. +
  3401. + /* Surface Laptop 3 (13") */
  3402. + { "MSHW0114", (unsigned long)sid_devs_sl3_13 },
  3403. +
  3404. + /* Surface Laptop 3 (15") */
  3405. + { "MSHW0110", (unsigned long)sid_devs_sl3_15 },
  3406. +
  3407. + { },
  3408. +};
  3409. +MODULE_DEVICE_TABLE(acpi, surface_sam_sid_match);
  3410. +
  3411. +
  3412. +static int surface_sam_sid_probe(struct platform_device *pdev)
  3413. +{
  3414. + const struct acpi_device_id *match;
  3415. + const struct mfd_cell *cells, *p;
  3416. +
  3417. + match = acpi_match_device(surface_sam_sid_match, &pdev->dev);
  3418. + if (!match)
  3419. + return -ENODEV;
  3420. +
  3421. + cells = (struct mfd_cell *)match->driver_data;
  3422. + if (!cells)
  3423. + return -ENODEV;
  3424. +
  3425. + for (p = cells; p->name; ++p) {
  3426. + /* just count */
  3427. + }
  3428. +
  3429. + if (p == cells)
  3430. + return -ENODEV;
  3431. +
  3432. + return mfd_add_devices(&pdev->dev, 0, cells, p - cells, NULL, 0, NULL);
  3433. +}
  3434. +
  3435. +static int surface_sam_sid_remove(struct platform_device *pdev)
  3436. +{
  3437. + mfd_remove_devices(&pdev->dev);
  3438. + return 0;
  3439. +}
  3440. +
  3441. +static struct platform_driver surface_sam_sid = {
  3442. + .probe = surface_sam_sid_probe,
  3443. + .remove = surface_sam_sid_remove,
  3444. + .driver = {
  3445. + .name = "surface_sam_sid",
  3446. + .acpi_match_table = surface_sam_sid_match,
  3447. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  3448. + },
  3449. +};
  3450. +module_platform_driver(surface_sam_sid);
  3451. +
  3452. +MODULE_AUTHOR("Maximilian Luz <luzmaximilian@gmail.com>");
  3453. +MODULE_DESCRIPTION("Surface Integration Driver for 5th Generation Surface Devices");
  3454. +MODULE_LICENSE("GPL");
  3455. diff --git a/drivers/platform/x86/surface_sam/surface_sam_sid_gpelid.c b/drivers/platform/x86/surface_sam/surface_sam_sid_gpelid.c
  3456. new file mode 100644
  3457. index 0000000000000..f0cee43c859b4
  3458. --- /dev/null
  3459. +++ b/drivers/platform/x86/surface_sam/surface_sam_sid_gpelid.c
  3460. @@ -0,0 +1,232 @@
  3461. +// SPDX-License-Identifier: GPL-2.0-or-later
  3462. +/*
  3463. + * Surface Lid driver to enable wakeup from suspend via the lid.
  3464. + */
  3465. +
  3466. +#include <linux/acpi.h>
  3467. +#include <linux/dmi.h>
  3468. +#include <linux/kernel.h>
  3469. +#include <linux/module.h>
  3470. +#include <linux/platform_device.h>
  3471. +
  3472. +
  3473. +struct sid_lid_device {
  3474. + const char *acpi_path;
  3475. + const u32 gpe_number;
  3476. +};
  3477. +
  3478. +
  3479. +static const struct sid_lid_device lid_device_l17 = {
  3480. + .acpi_path = "\\_SB.LID0",
  3481. + .gpe_number = 0x17,
  3482. +};
  3483. +
  3484. +static const struct sid_lid_device lid_device_l4D = {
  3485. + .acpi_path = "\\_SB.LID0",
  3486. + .gpe_number = 0x4D,
  3487. +};
  3488. +
  3489. +static const struct sid_lid_device lid_device_l4F = {
  3490. + .acpi_path = "\\_SB.LID0",
  3491. + .gpe_number = 0x4F,
  3492. +};
  3493. +
  3494. +static const struct sid_lid_device lid_device_l57 = {
  3495. + .acpi_path = "\\_SB.LID0",
  3496. + .gpe_number = 0x57,
  3497. +};
  3498. +
  3499. +
  3500. +static const struct dmi_system_id dmi_lid_device_table[] = {
  3501. + {
  3502. + .ident = "Surface Pro 4",
  3503. + .matches = {
  3504. + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"),
  3505. + DMI_EXACT_MATCH(DMI_PRODUCT_NAME, "Surface Pro 4"),
  3506. + },
  3507. + .driver_data = (void *)&lid_device_l17,
  3508. + },
  3509. + {
  3510. + .ident = "Surface Pro 5",
  3511. + .matches = {
  3512. + /* match for SKU here due to generic product name "Surface Pro" */
  3513. + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"),
  3514. + DMI_EXACT_MATCH(DMI_PRODUCT_SKU, "Surface_Pro_1796"),
  3515. + },
  3516. + .driver_data = (void *)&lid_device_l4F,
  3517. + },
  3518. + {
  3519. + .ident = "Surface Pro 5 (LTE)",
  3520. + .matches = {
  3521. + /* match for SKU here due to generic product name "Surface Pro" */
  3522. + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"),
  3523. + DMI_EXACT_MATCH(DMI_PRODUCT_SKU, "Surface_Pro_1807"),
  3524. + },
  3525. + .driver_data = (void *)&lid_device_l4F,
  3526. + },
  3527. + {
  3528. + .ident = "Surface Pro 6",
  3529. + .matches = {
  3530. + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"),
  3531. + DMI_EXACT_MATCH(DMI_PRODUCT_NAME, "Surface Pro 6"),
  3532. + },
  3533. + .driver_data = (void *)&lid_device_l4F,
  3534. + },
  3535. + {
  3536. + .ident = "Surface Pro 7",
  3537. + .matches = {
  3538. + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"),
  3539. + DMI_EXACT_MATCH(DMI_PRODUCT_NAME, "Surface Pro 7"),
  3540. + },
  3541. + .driver_data = (void *)&lid_device_l4D,
  3542. + },
  3543. + {
  3544. + .ident = "Surface Book 1",
  3545. + .matches = {
  3546. + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"),
  3547. + DMI_EXACT_MATCH(DMI_PRODUCT_NAME, "Surface Book"),
  3548. + },
  3549. + .driver_data = (void *)&lid_device_l17,
  3550. + },
  3551. + {
  3552. + .ident = "Surface Book 2",
  3553. + .matches = {
  3554. + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"),
  3555. + DMI_EXACT_MATCH(DMI_PRODUCT_NAME, "Surface Book 2"),
  3556. + },
  3557. + .driver_data = (void *)&lid_device_l17,
  3558. + },
  3559. + {
  3560. + .ident = "Surface Book 3",
  3561. + .matches = {
  3562. + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"),
  3563. + DMI_EXACT_MATCH(DMI_PRODUCT_NAME, "Surface Book 3"),
  3564. + },
  3565. + .driver_data = (void *)&lid_device_l4D,
  3566. + },
  3567. + {
  3568. + .ident = "Surface Laptop 1",
  3569. + .matches = {
  3570. + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"),
  3571. + DMI_EXACT_MATCH(DMI_PRODUCT_NAME, "Surface Laptop"),
  3572. + },
  3573. + .driver_data = (void *)&lid_device_l57,
  3574. + },
  3575. + {
  3576. + .ident = "Surface Laptop 2",
  3577. + .matches = {
  3578. + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"),
  3579. + DMI_EXACT_MATCH(DMI_PRODUCT_NAME, "Surface Laptop 2"),
  3580. + },
  3581. + .driver_data = (void *)&lid_device_l57,
  3582. + },
  3583. + {
  3584. + .ident = "Surface Laptop 3 (13\")",
  3585. + .matches = {
  3586. + DMI_EXACT_MATCH(DMI_SYS_VENDOR, "Microsoft Corporation"),
  3587. + DMI_EXACT_MATCH(DMI_PRODUCT_SKU, "Surface_Laptop_3_1867:1868"),
  3588. + },
  3589. + .driver_data = (void *)&lid_device_l4D,
  3590. + },
  3591. + { }
  3592. +};
  3593. +
  3594. +
  3595. +static int sid_lid_enable_wakeup(const struct sid_lid_device *dev, bool enable)
  3596. +{
  3597. + int action = enable ? ACPI_GPE_ENABLE : ACPI_GPE_DISABLE;
  3598. + int status;
  3599. +
  3600. + status = acpi_set_gpe_wake_mask(NULL, dev->gpe_number, action);
  3601. + if (status)
  3602. + return -EFAULT;
  3603. +
  3604. + return 0;
  3605. +}
  3606. +
  3607. +
  3608. +static int surface_sam_sid_gpelid_suspend(struct device *dev)
  3609. +{
  3610. + const struct sid_lid_device *ldev;
  3611. +
  3612. + ldev = dev_get_drvdata(dev);
  3613. + return sid_lid_enable_wakeup(ldev, true);
  3614. +}
  3615. +
  3616. +static int surface_sam_sid_gpelid_resume(struct device *dev)
  3617. +{
  3618. + const struct sid_lid_device *ldev;
  3619. +
  3620. + ldev = dev_get_drvdata(dev);
  3621. + return sid_lid_enable_wakeup(ldev, false);
  3622. +}
  3623. +
  3624. +static SIMPLE_DEV_PM_OPS(surface_sam_sid_gpelid_pm,
  3625. + surface_sam_sid_gpelid_suspend,
  3626. + surface_sam_sid_gpelid_resume);
  3627. +
  3628. +
  3629. +static int surface_sam_sid_gpelid_probe(struct platform_device *pdev)
  3630. +{
  3631. + const struct dmi_system_id *match;
  3632. + struct sid_lid_device *dev;
  3633. + acpi_handle lid_handle;
  3634. + int status;
  3635. +
  3636. + match = dmi_first_match(dmi_lid_device_table);
  3637. + if (!match)
  3638. + return -ENODEV;
  3639. +
  3640. + dev = match->driver_data;
  3641. + if (!dev)
  3642. + return -ENODEV;
  3643. +
  3644. + status = acpi_get_handle(NULL, (acpi_string)dev->acpi_path, &lid_handle);
  3645. + if (status)
  3646. + return -EFAULT;
  3647. +
  3648. + status = acpi_setup_gpe_for_wake(lid_handle, NULL, dev->gpe_number);
  3649. + if (status)
  3650. + return -EFAULT;
  3651. +
  3652. + status = acpi_enable_gpe(NULL, dev->gpe_number);
  3653. + if (status)
  3654. + return -EFAULT;
  3655. +
  3656. + status = sid_lid_enable_wakeup(dev, false);
  3657. + if (status) {
  3658. + acpi_disable_gpe(NULL, dev->gpe_number);
  3659. + return status;
  3660. + }
  3661. +
  3662. + platform_set_drvdata(pdev, dev);
  3663. + return 0;
  3664. +}
  3665. +
  3666. +static int surface_sam_sid_gpelid_remove(struct platform_device *pdev)
  3667. +{
  3668. + struct sid_lid_device *dev = platform_get_drvdata(pdev);
  3669. +
  3670. + /* restore default behavior without this module */
  3671. + sid_lid_enable_wakeup(dev, false);
  3672. + acpi_disable_gpe(NULL, dev->gpe_number);
  3673. +
  3674. + platform_set_drvdata(pdev, NULL);
  3675. + return 0;
  3676. +}
  3677. +
  3678. +static struct platform_driver surface_sam_sid_gpelid = {
  3679. + .probe = surface_sam_sid_gpelid_probe,
  3680. + .remove = surface_sam_sid_gpelid_remove,
  3681. + .driver = {
  3682. + .name = "surface_sam_sid_gpelid",
  3683. + .pm = &surface_sam_sid_gpelid_pm,
  3684. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  3685. + },
  3686. +};
  3687. +module_platform_driver(surface_sam_sid_gpelid);
  3688. +
  3689. +MODULE_AUTHOR("Maximilian Luz <luzmaximilian@gmail.com>");
  3690. +MODULE_DESCRIPTION("Surface Lid Driver for 5th Generation Surface Devices");
  3691. +MODULE_LICENSE("GPL");
  3692. +MODULE_ALIAS("platform:surface_sam_sid_gpelid");
  3693. diff --git a/drivers/platform/x86/surface_sam/surface_sam_sid_perfmode.c b/drivers/platform/x86/surface_sam/surface_sam_sid_perfmode.c
  3694. new file mode 100644
  3695. index 0000000000000..2e11efb166f2b
  3696. --- /dev/null
  3697. +++ b/drivers/platform/x86/surface_sam/surface_sam_sid_perfmode.c
  3698. @@ -0,0 +1,216 @@
  3699. +// SPDX-License-Identifier: GPL-2.0-or-later
  3700. +/*
  3701. + * Surface Performance Mode Driver.
  3702. + * Allows to change cooling capabilities based on user preference.
  3703. + */
  3704. +
  3705. +#include <asm/unaligned.h>
  3706. +#include <linux/kernel.h>
  3707. +#include <linux/module.h>
  3708. +#include <linux/platform_device.h>
  3709. +
  3710. +#include "surface_sam_ssh.h"
  3711. +
  3712. +
  3713. +#define SID_PARAM_PERM 0644
  3714. +
  3715. +enum sam_perf_mode {
  3716. + SAM_PERF_MODE_NORMAL = 1,
  3717. + SAM_PERF_MODE_BATTERY = 2,
  3718. + SAM_PERF_MODE_PERF1 = 3,
  3719. + SAM_PERF_MODE_PERF2 = 4,
  3720. +
  3721. + __SAM_PERF_MODE__START = 1,
  3722. + __SAM_PERF_MODE__END = 4,
  3723. +};
  3724. +
  3725. +enum sid_param_perf_mode {
  3726. + SID_PARAM_PERF_MODE_AS_IS = 0,
  3727. + SID_PARAM_PERF_MODE_NORMAL = SAM_PERF_MODE_NORMAL,
  3728. + SID_PARAM_PERF_MODE_BATTERY = SAM_PERF_MODE_BATTERY,
  3729. + SID_PARAM_PERF_MODE_PERF1 = SAM_PERF_MODE_PERF1,
  3730. + SID_PARAM_PERF_MODE_PERF2 = SAM_PERF_MODE_PERF2,
  3731. +
  3732. + __SID_PARAM_PERF_MODE__START = 0,
  3733. + __SID_PARAM_PERF_MODE__END = 4,
  3734. +};
  3735. +
  3736. +
  3737. +static int surface_sam_perf_mode_get(void)
  3738. +{
  3739. + u8 result_buf[8] = { 0 };
  3740. + int status;
  3741. +
  3742. + struct surface_sam_ssh_rqst rqst = {
  3743. + .tc = 0x03,
  3744. + .cid = 0x02,
  3745. + .iid = 0x00,
  3746. + .chn = 0x01,
  3747. + .snc = 0x01,
  3748. + .cdl = 0x00,
  3749. + .pld = NULL,
  3750. + };
  3751. +
  3752. + struct surface_sam_ssh_buf result = {
  3753. + .cap = ARRAY_SIZE(result_buf),
  3754. + .len = 0,
  3755. + .data = result_buf,
  3756. + };
  3757. +
  3758. + status = surface_sam_ssh_rqst(&rqst, &result);
  3759. + if (status)
  3760. + return status;
  3761. +
  3762. + if (result.len != 8)
  3763. + return -EFAULT;
  3764. +
  3765. + return get_unaligned_le32(&result.data[0]);
  3766. +}
  3767. +
  3768. +static int surface_sam_perf_mode_set(int perf_mode)
  3769. +{
  3770. + u8 payload[4] = { 0 };
  3771. +
  3772. + struct surface_sam_ssh_rqst rqst = {
  3773. + .tc = 0x03,
  3774. + .cid = 0x03,
  3775. + .iid = 0x00,
  3776. + .chn = 0x01,
  3777. + .snc = 0x00,
  3778. + .cdl = ARRAY_SIZE(payload),
  3779. + .pld = payload,
  3780. + };
  3781. +
  3782. + if (perf_mode < __SAM_PERF_MODE__START || perf_mode > __SAM_PERF_MODE__END)
  3783. + return -EINVAL;
  3784. +
  3785. + put_unaligned_le32(perf_mode, &rqst.pld[0]);
  3786. + return surface_sam_ssh_rqst(&rqst, NULL);
  3787. +}
  3788. +
  3789. +
  3790. +static int param_perf_mode_set(const char *val, const struct kernel_param *kp)
  3791. +{
  3792. + int perf_mode;
  3793. + int status;
  3794. +
  3795. + status = kstrtoint(val, 0, &perf_mode);
  3796. + if (status)
  3797. + return status;
  3798. +
  3799. + if (perf_mode < __SID_PARAM_PERF_MODE__START || perf_mode > __SID_PARAM_PERF_MODE__END)
  3800. + return -EINVAL;
  3801. +
  3802. + return param_set_int(val, kp);
  3803. +}
  3804. +
  3805. +static const struct kernel_param_ops param_perf_mode_ops = {
  3806. + .set = param_perf_mode_set,
  3807. + .get = param_get_int,
  3808. +};
  3809. +
  3810. +static int param_perf_mode_init = SID_PARAM_PERF_MODE_AS_IS;
  3811. +static int param_perf_mode_exit = SID_PARAM_PERF_MODE_AS_IS;
  3812. +
  3813. +module_param_cb(perf_mode_init, &param_perf_mode_ops, &param_perf_mode_init, SID_PARAM_PERM);
  3814. +module_param_cb(perf_mode_exit, &param_perf_mode_ops, &param_perf_mode_exit, SID_PARAM_PERM);
  3815. +
  3816. +MODULE_PARM_DESC(perf_mode_init, "Performance-mode to be set on module initialization");
  3817. +MODULE_PARM_DESC(perf_mode_exit, "Performance-mode to be set on module exit");
  3818. +
  3819. +
  3820. +static ssize_t perf_mode_show(struct device *dev, struct device_attribute *attr, char *data)
  3821. +{
  3822. + int perf_mode;
  3823. +
  3824. + perf_mode = surface_sam_perf_mode_get();
  3825. + if (perf_mode < 0) {
  3826. + dev_err(dev, "failed to get current performance mode: %d\n", perf_mode);
  3827. + return -EIO;
  3828. + }
  3829. +
  3830. + return sprintf(data, "%d\n", perf_mode);
  3831. +}
  3832. +
  3833. +static ssize_t perf_mode_store(struct device *dev, struct device_attribute *attr,
  3834. + const char *data, size_t count)
  3835. +{
  3836. + int perf_mode;
  3837. + int status;
  3838. +
  3839. + status = kstrtoint(data, 0, &perf_mode);
  3840. + if (status)
  3841. + return status;
  3842. +
  3843. + status = surface_sam_perf_mode_set(perf_mode);
  3844. + if (status)
  3845. + return status;
  3846. +
  3847. + // TODO: Should we notify ACPI here?
  3848. + //
  3849. + // There is a _DSM call described as
  3850. + // WSID._DSM: Notify DPTF on Slider State change
  3851. + // which calls
  3852. + // ODV3 = ToInteger (Arg3)
  3853. + // Notify(IETM, 0x88)
  3854. + // IETM is an INT3400 Intel Dynamic Power Performance Management
  3855. + // device, part of the DPTF framework. From the corresponding
  3856. + // kernel driver, it looks like event 0x88 is being ignored. Also
  3857. + // it is currently unknown what the consequecnes of setting ODV3
  3858. + // are.
  3859. +
  3860. + return count;
  3861. +}
  3862. +
  3863. +static const DEVICE_ATTR_RW(perf_mode);
  3864. +
  3865. +
  3866. +static int surface_sam_sid_perfmode_probe(struct platform_device *pdev)
  3867. +{
  3868. + int status;
  3869. +
  3870. + // link to ec
  3871. + status = surface_sam_ssh_consumer_register(&pdev->dev);
  3872. + if (status)
  3873. + return status == -ENXIO ? -EPROBE_DEFER : status;
  3874. +
  3875. + // set initial perf_mode
  3876. + if (param_perf_mode_init != SID_PARAM_PERF_MODE_AS_IS) {
  3877. + status = surface_sam_perf_mode_set(param_perf_mode_init);
  3878. + if (status)
  3879. + return status;
  3880. + }
  3881. +
  3882. + // register perf_mode attribute
  3883. + status = sysfs_create_file(&pdev->dev.kobj, &dev_attr_perf_mode.attr);
  3884. + if (status)
  3885. + goto err_sysfs;
  3886. +
  3887. + return 0;
  3888. +
  3889. +err_sysfs:
  3890. + surface_sam_perf_mode_set(param_perf_mode_exit);
  3891. + return status;
  3892. +}
  3893. +
  3894. +static int surface_sam_sid_perfmode_remove(struct platform_device *pdev)
  3895. +{
  3896. + sysfs_remove_file(&pdev->dev.kobj, &dev_attr_perf_mode.attr);
  3897. + surface_sam_perf_mode_set(param_perf_mode_exit);
  3898. + return 0;
  3899. +}
  3900. +
  3901. +static struct platform_driver surface_sam_sid_perfmode = {
  3902. + .probe = surface_sam_sid_perfmode_probe,
  3903. + .remove = surface_sam_sid_perfmode_remove,
  3904. + .driver = {
  3905. + .name = "surface_sam_sid_perfmode",
  3906. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  3907. + },
  3908. +};
  3909. +module_platform_driver(surface_sam_sid_perfmode);
  3910. +
  3911. +MODULE_AUTHOR("Maximilian Luz <luzmaximilian@gmail.com>");
  3912. +MODULE_DESCRIPTION("Surface Performance Mode Driver for 5th Generation Surface Devices");
  3913. +MODULE_LICENSE("GPL");
  3914. +MODULE_ALIAS("platform:surface_sam_sid_perfmode");
  3915. diff --git a/drivers/platform/x86/surface_sam/surface_sam_sid_power.c b/drivers/platform/x86/surface_sam/surface_sam_sid_power.c
  3916. new file mode 100644
  3917. index 0000000000000..1d945c0a911a4
  3918. --- /dev/null
  3919. +++ b/drivers/platform/x86/surface_sam/surface_sam_sid_power.c
  3920. @@ -0,0 +1,1154 @@
  3921. +// SPDX-License-Identifier: GPL-2.0-or-later
  3922. +/*
  3923. + * Surface SID Battery/AC Driver.
  3924. + * Provides support for the battery and AC on 7th generation Surface devices.
  3925. + */
  3926. +
  3927. +#include <linux/kernel.h>
  3928. +#include <linux/delay.h>
  3929. +#include <linux/jiffies.h>
  3930. +#include <linux/module.h>
  3931. +#include <linux/platform_device.h>
  3932. +#include <linux/power_supply.h>
  3933. +#include <linux/workqueue.h>
  3934. +
  3935. +#include "surface_sam_ssh.h"
  3936. +#include "surface_sam_sid_power.h"
  3937. +
  3938. +#define SPWR_WARN KERN_WARNING KBUILD_MODNAME ": "
  3939. +#define SPWR_DEBUG KERN_DEBUG KBUILD_MODNAME ": "
  3940. +
  3941. +
  3942. +// TODO: check BIX/BST for unknown/unsupported 0xffffffff entries
  3943. +// TODO: DPTF (/SAN notifications)?
  3944. +// TODO: other properties?
  3945. +
  3946. +
  3947. +static unsigned int cache_time = 1000;
  3948. +module_param(cache_time, uint, 0644);
  3949. +MODULE_PARM_DESC(cache_time, "battery state chaching time in milliseconds [default: 1000]");
  3950. +
  3951. +#define SPWR_AC_BAT_UPDATE_DELAY msecs_to_jiffies(5000)
  3952. +
  3953. +
  3954. +/*
  3955. + * SAM Interface.
  3956. + */
  3957. +
  3958. +#define SAM_PWR_TC 0x02
  3959. +
  3960. +#define SAM_RQST_PWR_CID_STA 0x01
  3961. +#define SAM_RQST_PWR_CID_BIX 0x02
  3962. +#define SAM_RQST_PWR_CID_BST 0x03
  3963. +#define SAM_RQST_PWR_CID_BTP 0x04
  3964. +
  3965. +#define SAM_RQST_PWR_CID_PMAX 0x0b
  3966. +#define SAM_RQST_PWR_CID_PSOC 0x0c
  3967. +#define SAM_RQST_PWR_CID_PSRC 0x0d
  3968. +#define SAM_RQST_PWR_CID_CHGI 0x0e
  3969. +#define SAM_RQST_PWR_CID_ARTG 0x0f
  3970. +
  3971. +#define SAM_EVENT_PWR_CID_BIX 0x15
  3972. +#define SAM_EVENT_PWR_CID_BST 0x16
  3973. +#define SAM_EVENT_PWR_CID_ADAPTER 0x17
  3974. +
  3975. +#define SAM_BATTERY_STA_OK 0x0f
  3976. +#define SAM_BATTERY_STA_PRESENT 0x10
  3977. +
  3978. +#define SAM_BATTERY_STATE_DISCHARGING 0x01
  3979. +#define SAM_BATTERY_STATE_CHARGING 0x02
  3980. +#define SAM_BATTERY_STATE_CRITICAL 0x04
  3981. +
  3982. +#define SAM_BATTERY_POWER_UNIT_MA 1
  3983. +
  3984. +
  3985. +/* Equivalent to data returned in ACPI _BIX method */
  3986. +struct spwr_bix {
  3987. + u8 revision;
  3988. + u32 power_unit;
  3989. + u32 design_cap;
  3990. + u32 last_full_charge_cap;
  3991. + u32 technology;
  3992. + u32 design_voltage;
  3993. + u32 design_cap_warn;
  3994. + u32 design_cap_low;
  3995. + u32 cycle_count;
  3996. + u32 measurement_accuracy;
  3997. + u32 max_sampling_time;
  3998. + u32 min_sampling_time;
  3999. + u32 max_avg_interval;
  4000. + u32 min_avg_interval;
  4001. + u32 bat_cap_granularity_1;
  4002. + u32 bat_cap_granularity_2;
  4003. + u8 model[21];
  4004. + u8 serial[11];
  4005. + u8 type[5];
  4006. + u8 oem_info[21];
  4007. +} __packed;
  4008. +
  4009. +/* Equivalent to data returned in ACPI _BST method */
  4010. +struct spwr_bst {
  4011. + u32 state;
  4012. + u32 present_rate;
  4013. + u32 remaining_cap;
  4014. + u32 present_voltage;
  4015. +} __packed;
  4016. +
  4017. +/* DPTF event payload */
  4018. +struct spwr_event_dptf {
  4019. + u32 pmax;
  4020. + u32 _1; /* currently unknown */
  4021. + u32 _2; /* currently unknown */
  4022. +} __packed;
  4023. +
  4024. +
  4025. +/* Get battery status (_STA) */
  4026. +static int sam_psy_get_sta(u8 channel, u8 instance, u32 *sta)
  4027. +{
  4028. + struct surface_sam_ssh_rqst rqst;
  4029. + struct surface_sam_ssh_buf result;
  4030. +
  4031. + rqst.tc = SAM_PWR_TC;
  4032. + rqst.cid = SAM_RQST_PWR_CID_STA;
  4033. + rqst.iid = instance;
  4034. + rqst.chn = channel;
  4035. + rqst.snc = 0x01;
  4036. + rqst.cdl = 0x00;
  4037. + rqst.pld = NULL;
  4038. +
  4039. + result.cap = sizeof(u32);
  4040. + result.len = 0;
  4041. + result.data = (u8 *)sta;
  4042. +
  4043. + return surface_sam_ssh_rqst(&rqst, &result);
  4044. +}
  4045. +
  4046. +/* Get battery static information (_BIX) */
  4047. +static int sam_psy_get_bix(u8 channel, u8 instance, struct spwr_bix *bix)
  4048. +{
  4049. + struct surface_sam_ssh_rqst rqst;
  4050. + struct surface_sam_ssh_buf result;
  4051. +
  4052. + rqst.tc = SAM_PWR_TC;
  4053. + rqst.cid = SAM_RQST_PWR_CID_BIX;
  4054. + rqst.iid = instance;
  4055. + rqst.chn = channel;
  4056. + rqst.snc = 0x01;
  4057. + rqst.cdl = 0x00;
  4058. + rqst.pld = NULL;
  4059. +
  4060. + result.cap = sizeof(struct spwr_bix);
  4061. + result.len = 0;
  4062. + result.data = (u8 *)bix;
  4063. +
  4064. + return surface_sam_ssh_rqst(&rqst, &result);
  4065. +}
  4066. +
  4067. +/* Get battery dynamic information (_BST) */
  4068. +static int sam_psy_get_bst(u8 channel, u8 instance, struct spwr_bst *bst)
  4069. +{
  4070. + struct surface_sam_ssh_rqst rqst;
  4071. + struct surface_sam_ssh_buf result;
  4072. +
  4073. + rqst.tc = SAM_PWR_TC;
  4074. + rqst.cid = SAM_RQST_PWR_CID_BST;
  4075. + rqst.iid = instance;
  4076. + rqst.chn = channel;
  4077. + rqst.snc = 0x01;
  4078. + rqst.cdl = 0x00;
  4079. + rqst.pld = NULL;
  4080. +
  4081. + result.cap = sizeof(struct spwr_bst);
  4082. + result.len = 0;
  4083. + result.data = (u8 *)bst;
  4084. +
  4085. + return surface_sam_ssh_rqst(&rqst, &result);
  4086. +}
  4087. +
  4088. +/* Set battery trip point (_BTP) */
  4089. +static int sam_psy_set_btp(u8 channel, u8 instance, u32 btp)
  4090. +{
  4091. + struct surface_sam_ssh_rqst rqst;
  4092. +
  4093. + rqst.tc = SAM_PWR_TC;
  4094. + rqst.cid = SAM_RQST_PWR_CID_BTP;
  4095. + rqst.iid = instance;
  4096. + rqst.chn = channel;
  4097. + rqst.snc = 0x00;
  4098. + rqst.cdl = sizeof(u32);
  4099. + rqst.pld = (u8 *)&btp;
  4100. +
  4101. + return surface_sam_ssh_rqst(&rqst, NULL);
  4102. +}
  4103. +
  4104. +/* Get platform power soruce for battery (DPTF PSRC) */
  4105. +static int sam_psy_get_psrc(u8 channel, u8 instance, u32 *psrc)
  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_PSRC;
  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 *)psrc;
  4121. +
  4122. + return surface_sam_ssh_rqst(&rqst, &result);
  4123. +}
  4124. +
  4125. +/* Get maximum platform power for battery (DPTF PMAX) */
  4126. +__always_unused
  4127. +static int sam_psy_get_pmax(u8 channel, u8 instance, u32 *pmax)
  4128. +{
  4129. + struct surface_sam_ssh_rqst rqst;
  4130. + struct surface_sam_ssh_buf result;
  4131. +
  4132. + rqst.tc = SAM_PWR_TC;
  4133. + rqst.cid = SAM_RQST_PWR_CID_PMAX;
  4134. + rqst.iid = instance;
  4135. + rqst.chn = channel;
  4136. + rqst.snc = 0x01;
  4137. + rqst.cdl = 0x00;
  4138. + rqst.pld = NULL;
  4139. +
  4140. + result.cap = sizeof(u32);
  4141. + result.len = 0;
  4142. + result.data = (u8 *)pmax;
  4143. +
  4144. + return surface_sam_ssh_rqst(&rqst, &result);
  4145. +}
  4146. +
  4147. +/* Get adapter rating (DPTF ARTG) */
  4148. +__always_unused
  4149. +static int sam_psy_get_artg(u8 channel, u8 instance, u32 *artg)
  4150. +{
  4151. + struct surface_sam_ssh_rqst rqst;
  4152. + struct surface_sam_ssh_buf result;
  4153. +
  4154. + rqst.tc = SAM_PWR_TC;
  4155. + rqst.cid = SAM_RQST_PWR_CID_ARTG;
  4156. + rqst.iid = instance;
  4157. + rqst.chn = channel;
  4158. + rqst.snc = 0x01;
  4159. + rqst.cdl = 0x00;
  4160. + rqst.pld = NULL;
  4161. +
  4162. + result.cap = sizeof(u32);
  4163. + result.len = 0;
  4164. + result.data = (u8 *)artg;
  4165. +
  4166. + return surface_sam_ssh_rqst(&rqst, &result);
  4167. +}
  4168. +
  4169. +/* Unknown (DPTF PSOC) */
  4170. +__always_unused
  4171. +static int sam_psy_get_psoc(u8 channel, u8 instance, u32 *psoc)
  4172. +{
  4173. + struct surface_sam_ssh_rqst rqst;
  4174. + struct surface_sam_ssh_buf result;
  4175. +
  4176. + rqst.tc = SAM_PWR_TC;
  4177. + rqst.cid = SAM_RQST_PWR_CID_PSOC;
  4178. + rqst.iid = instance;
  4179. + rqst.chn = channel;
  4180. + rqst.snc = 0x01;
  4181. + rqst.cdl = 0x00;
  4182. + rqst.pld = NULL;
  4183. +
  4184. + result.cap = sizeof(u32);
  4185. + result.len = 0;
  4186. + result.data = (u8 *)psoc;
  4187. +
  4188. + return surface_sam_ssh_rqst(&rqst, &result);
  4189. +}
  4190. +
  4191. +/* Unknown (DPTF CHGI/ INT3403 SPPC) */
  4192. +__always_unused
  4193. +static int sam_psy_set_chgi(u8 channel, u8 instance, u32 chgi)
  4194. +{
  4195. + struct surface_sam_ssh_rqst rqst;
  4196. +
  4197. + rqst.tc = SAM_PWR_TC;
  4198. + rqst.cid = SAM_RQST_PWR_CID_CHGI;
  4199. + rqst.iid = instance;
  4200. + rqst.chn = channel;
  4201. + rqst.snc = 0x00;
  4202. + rqst.cdl = sizeof(u32);
  4203. + rqst.pld = (u8 *)&chgi;
  4204. +
  4205. + return surface_sam_ssh_rqst(&rqst, NULL);
  4206. +}
  4207. +
  4208. +
  4209. +/*
  4210. + * Common Power-Subsystem Interface.
  4211. + */
  4212. +
  4213. +struct spwr_battery_device {
  4214. + struct platform_device *pdev;
  4215. + const struct ssam_battery_properties *p;
  4216. +
  4217. + char name[32];
  4218. + struct power_supply *psy;
  4219. + struct power_supply_desc psy_desc;
  4220. +
  4221. + struct delayed_work update_work;
  4222. +
  4223. + struct ssam_event_notifier notif;
  4224. +
  4225. + struct mutex lock;
  4226. + unsigned long timestamp;
  4227. +
  4228. + u32 sta;
  4229. + struct spwr_bix bix;
  4230. + struct spwr_bst bst;
  4231. + u32 alarm;
  4232. +};
  4233. +
  4234. +struct spwr_ac_device {
  4235. + struct platform_device *pdev;
  4236. +
  4237. + char name[32];
  4238. + struct power_supply *psy;
  4239. + struct power_supply_desc psy_desc;
  4240. +
  4241. + struct ssam_event_notifier notif;
  4242. +
  4243. + struct mutex lock;
  4244. +
  4245. + u32 state;
  4246. +};
  4247. +
  4248. +static enum power_supply_property spwr_ac_props[] = {
  4249. + POWER_SUPPLY_PROP_ONLINE,
  4250. +};
  4251. +
  4252. +static enum power_supply_property spwr_battery_props_chg[] = {
  4253. + POWER_SUPPLY_PROP_STATUS,
  4254. + POWER_SUPPLY_PROP_PRESENT,
  4255. + POWER_SUPPLY_PROP_TECHNOLOGY,
  4256. + POWER_SUPPLY_PROP_CYCLE_COUNT,
  4257. + POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN,
  4258. + POWER_SUPPLY_PROP_VOLTAGE_NOW,
  4259. + POWER_SUPPLY_PROP_CURRENT_NOW,
  4260. + POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN,
  4261. + POWER_SUPPLY_PROP_CHARGE_FULL,
  4262. + POWER_SUPPLY_PROP_CHARGE_NOW,
  4263. + POWER_SUPPLY_PROP_CAPACITY,
  4264. + POWER_SUPPLY_PROP_CAPACITY_LEVEL,
  4265. + POWER_SUPPLY_PROP_MODEL_NAME,
  4266. + POWER_SUPPLY_PROP_MANUFACTURER,
  4267. + POWER_SUPPLY_PROP_SERIAL_NUMBER,
  4268. +};
  4269. +
  4270. +static enum power_supply_property spwr_battery_props_eng[] = {
  4271. + POWER_SUPPLY_PROP_STATUS,
  4272. + POWER_SUPPLY_PROP_PRESENT,
  4273. + POWER_SUPPLY_PROP_TECHNOLOGY,
  4274. + POWER_SUPPLY_PROP_CYCLE_COUNT,
  4275. + POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN,
  4276. + POWER_SUPPLY_PROP_VOLTAGE_NOW,
  4277. + POWER_SUPPLY_PROP_POWER_NOW,
  4278. + POWER_SUPPLY_PROP_ENERGY_FULL_DESIGN,
  4279. + POWER_SUPPLY_PROP_ENERGY_FULL,
  4280. + POWER_SUPPLY_PROP_ENERGY_NOW,
  4281. + POWER_SUPPLY_PROP_CAPACITY,
  4282. + POWER_SUPPLY_PROP_CAPACITY_LEVEL,
  4283. + POWER_SUPPLY_PROP_MODEL_NAME,
  4284. + POWER_SUPPLY_PROP_MANUFACTURER,
  4285. + POWER_SUPPLY_PROP_SERIAL_NUMBER,
  4286. +};
  4287. +
  4288. +
  4289. +static int spwr_battery_register(struct spwr_battery_device *bat,
  4290. + struct platform_device *pdev,
  4291. + const struct ssam_battery_properties *p);
  4292. +
  4293. +static void spwr_battery_unregister(struct spwr_battery_device *bat);
  4294. +
  4295. +
  4296. +static inline bool spwr_battery_present(struct spwr_battery_device *bat)
  4297. +{
  4298. + return bat->sta & SAM_BATTERY_STA_PRESENT;
  4299. +}
  4300. +
  4301. +
  4302. +static inline int spwr_battery_load_sta(struct spwr_battery_device *bat)
  4303. +{
  4304. + return sam_psy_get_sta(bat->p->channel, bat->p->instance, &bat->sta);
  4305. +}
  4306. +
  4307. +static inline int spwr_battery_load_bix(struct spwr_battery_device *bat)
  4308. +{
  4309. + if (!spwr_battery_present(bat))
  4310. + return 0;
  4311. +
  4312. + return sam_psy_get_bix(bat->p->channel, bat->p->instance, &bat->bix);
  4313. +}
  4314. +
  4315. +static inline int spwr_battery_load_bst(struct spwr_battery_device *bat)
  4316. +{
  4317. + if (!spwr_battery_present(bat))
  4318. + return 0;
  4319. +
  4320. + return sam_psy_get_bst(bat->p->channel, bat->p->instance, &bat->bst);
  4321. +}
  4322. +
  4323. +
  4324. +static inline int spwr_battery_set_alarm_unlocked(struct spwr_battery_device *bat, u32 value)
  4325. +{
  4326. + bat->alarm = value;
  4327. + return sam_psy_set_btp(bat->p->channel, bat->p->instance, bat->alarm);
  4328. +}
  4329. +
  4330. +static inline int spwr_battery_set_alarm(struct spwr_battery_device *bat, u32 value)
  4331. +{
  4332. + int status;
  4333. +
  4334. + mutex_lock(&bat->lock);
  4335. + status = spwr_battery_set_alarm_unlocked(bat, value);
  4336. + mutex_unlock(&bat->lock);
  4337. +
  4338. + return status;
  4339. +}
  4340. +
  4341. +static inline int spwr_battery_update_bst_unlocked(struct spwr_battery_device *bat, bool cached)
  4342. +{
  4343. + unsigned long cache_deadline = bat->timestamp + msecs_to_jiffies(cache_time);
  4344. + int status;
  4345. +
  4346. + if (cached && bat->timestamp && time_is_after_jiffies(cache_deadline))
  4347. + return 0;
  4348. +
  4349. + status = spwr_battery_load_sta(bat);
  4350. + if (status)
  4351. + return status;
  4352. +
  4353. + status = spwr_battery_load_bst(bat);
  4354. + if (status)
  4355. + return status;
  4356. +
  4357. + bat->timestamp = jiffies;
  4358. + return 0;
  4359. +}
  4360. +
  4361. +static int spwr_battery_update_bst(struct spwr_battery_device *bat, bool cached)
  4362. +{
  4363. + int status;
  4364. +
  4365. + mutex_lock(&bat->lock);
  4366. + status = spwr_battery_update_bst_unlocked(bat, cached);
  4367. + mutex_unlock(&bat->lock);
  4368. +
  4369. + return status;
  4370. +}
  4371. +
  4372. +static inline int spwr_battery_update_bix_unlocked(struct spwr_battery_device *bat)
  4373. +{
  4374. + int status;
  4375. +
  4376. + status = spwr_battery_load_sta(bat);
  4377. + if (status)
  4378. + return status;
  4379. +
  4380. + status = spwr_battery_load_bix(bat);
  4381. + if (status)
  4382. + return status;
  4383. +
  4384. + status = spwr_battery_load_bst(bat);
  4385. + if (status)
  4386. + return status;
  4387. +
  4388. + bat->timestamp = jiffies;
  4389. + return 0;
  4390. +}
  4391. +
  4392. +static int spwr_battery_update_bix(struct spwr_battery_device *bat)
  4393. +{
  4394. + int status;
  4395. +
  4396. + mutex_lock(&bat->lock);
  4397. + status = spwr_battery_update_bix_unlocked(bat);
  4398. + mutex_unlock(&bat->lock);
  4399. +
  4400. + return status;
  4401. +}
  4402. +
  4403. +static inline int spwr_ac_update_unlocked(struct spwr_ac_device *ac)
  4404. +{
  4405. + return sam_psy_get_psrc(0x01, 0x01, &ac->state);
  4406. +}
  4407. +
  4408. +static int spwr_ac_update(struct spwr_ac_device *ac)
  4409. +{
  4410. + int status;
  4411. +
  4412. + mutex_lock(&ac->lock);
  4413. + status = spwr_ac_update_unlocked(ac);
  4414. + mutex_unlock(&ac->lock);
  4415. +
  4416. + return status;
  4417. +}
  4418. +
  4419. +
  4420. +static int spwr_battery_recheck(struct spwr_battery_device *bat)
  4421. +{
  4422. + bool present = spwr_battery_present(bat);
  4423. + u32 unit = bat->bix.power_unit;
  4424. + int status;
  4425. +
  4426. + status = spwr_battery_update_bix(bat);
  4427. + if (status)
  4428. + return status;
  4429. +
  4430. + // if battery has been attached, (re-)initialize alarm
  4431. + if (!present && spwr_battery_present(bat)) {
  4432. + status = spwr_battery_set_alarm(bat, bat->bix.design_cap_warn);
  4433. + if (status)
  4434. + return status;
  4435. + }
  4436. +
  4437. + // if the unit has changed, re-add the battery
  4438. + if (unit != bat->bix.power_unit) {
  4439. + spwr_battery_unregister(bat);
  4440. + status = spwr_battery_register(bat, bat->pdev, bat->p);
  4441. + }
  4442. +
  4443. + return status;
  4444. +}
  4445. +
  4446. +
  4447. +static inline int spwr_notify_bix(struct spwr_battery_device *bat)
  4448. +{
  4449. + int status;
  4450. +
  4451. + status = spwr_battery_recheck(bat);
  4452. + if (!status)
  4453. + power_supply_changed(bat->psy);
  4454. +
  4455. + return status;
  4456. +}
  4457. +
  4458. +static inline int spwr_notify_bst(struct spwr_battery_device *bat)
  4459. +{
  4460. + int status;
  4461. +
  4462. + status = spwr_battery_update_bst(bat, false);
  4463. + if (!status)
  4464. + power_supply_changed(bat->psy);
  4465. +
  4466. + return status;
  4467. +}
  4468. +
  4469. +static inline int spwr_notify_adapter_bat(struct spwr_battery_device *bat)
  4470. +{
  4471. + /*
  4472. + * Handle battery update quirk:
  4473. + * When the battery is fully charged and the adapter is plugged in or
  4474. + * removed, the EC does not send a separate event for the state
  4475. + * (charging/discharging) change. Furthermore it may take some time until
  4476. + * the state is updated on the battery. Schedule an update to solve this.
  4477. + */
  4478. +
  4479. + if (bat->bst.remaining_cap >= bat->bix.last_full_charge_cap)
  4480. + schedule_delayed_work(&bat->update_work, SPWR_AC_BAT_UPDATE_DELAY);
  4481. +
  4482. + return 0;
  4483. +}
  4484. +
  4485. +static inline int spwr_notify_adapter_ac(struct spwr_ac_device *ac)
  4486. +{
  4487. + int status;
  4488. +
  4489. + status = spwr_ac_update(ac);
  4490. + if (!status)
  4491. + power_supply_changed(ac->psy);
  4492. +
  4493. + return status;
  4494. +}
  4495. +
  4496. +static u32 spwr_notify_bat(struct ssam_notifier_block *nb, const struct ssam_event *event)
  4497. +{
  4498. + struct spwr_battery_device *bat = container_of(nb, struct spwr_battery_device, notif.base);
  4499. + int status;
  4500. +
  4501. + dev_dbg(&bat->pdev->dev, "power event (cid = 0x%02x, iid = %d, chn = %d)\n",
  4502. + event->command_id, event->instance_id, event->channel);
  4503. +
  4504. + // handled here, needs to be handled for all channels/instances
  4505. + if (event->command_id == SAM_EVENT_PWR_CID_ADAPTER) {
  4506. + status = spwr_notify_adapter_bat(bat);
  4507. + return ssam_notifier_from_errno(status) | SSAM_NOTIF_HANDLED;
  4508. + }
  4509. +
  4510. + // check for the correct channel and instance ID
  4511. + if (event->channel != bat->p->channel)
  4512. + return 0;
  4513. +
  4514. + if (event->instance_id != bat->p->instance)
  4515. + return 0;
  4516. +
  4517. + switch (event->command_id) {
  4518. + case SAM_EVENT_PWR_CID_BIX:
  4519. + status = spwr_notify_bix(bat);
  4520. + break;
  4521. +
  4522. + case SAM_EVENT_PWR_CID_BST:
  4523. + status = spwr_notify_bst(bat);
  4524. + break;
  4525. +
  4526. + default:
  4527. + return 0;
  4528. + }
  4529. +
  4530. + return ssam_notifier_from_errno(status) | SSAM_NOTIF_HANDLED;
  4531. +}
  4532. +
  4533. +static u32 spwr_notify_ac(struct ssam_notifier_block *nb, const struct ssam_event *event)
  4534. +{
  4535. + struct spwr_ac_device *ac = container_of(nb, struct spwr_ac_device, notif.base);
  4536. + int status;
  4537. +
  4538. + dev_dbg(&ac->pdev->dev, "power event (cid = 0x%02x, iid = %d, chn = %d)\n",
  4539. + event->command_id, event->instance_id, event->channel);
  4540. +
  4541. + // AC has IID = 0
  4542. + if (event->instance_id != 0)
  4543. + return 0;
  4544. +
  4545. + switch (event->command_id) {
  4546. + case SAM_EVENT_PWR_CID_ADAPTER:
  4547. + status = spwr_notify_adapter_ac(ac);
  4548. + return ssam_notifier_from_errno(status) | SSAM_NOTIF_HANDLED;
  4549. +
  4550. + default:
  4551. + return 0;
  4552. + }
  4553. +}
  4554. +
  4555. +static void spwr_battery_update_bst_workfn(struct work_struct *work)
  4556. +{
  4557. + struct delayed_work *dwork = to_delayed_work(work);
  4558. + struct spwr_battery_device *bat = container_of(dwork, struct spwr_battery_device, update_work);
  4559. + int status;
  4560. +
  4561. + status = spwr_battery_update_bst(bat, false);
  4562. + if (!status)
  4563. + power_supply_changed(bat->psy);
  4564. +
  4565. + if (status)
  4566. + dev_err(&bat->pdev->dev, "failed to update battery state: %d\n", status);
  4567. +}
  4568. +
  4569. +
  4570. +static inline int spwr_battery_prop_status(struct spwr_battery_device *bat)
  4571. +{
  4572. + if (bat->bst.state & SAM_BATTERY_STATE_DISCHARGING)
  4573. + return POWER_SUPPLY_STATUS_DISCHARGING;
  4574. +
  4575. + if (bat->bst.state & SAM_BATTERY_STATE_CHARGING)
  4576. + return POWER_SUPPLY_STATUS_CHARGING;
  4577. +
  4578. + if (bat->bix.last_full_charge_cap == bat->bst.remaining_cap)
  4579. + return POWER_SUPPLY_STATUS_FULL;
  4580. +
  4581. + if (bat->bst.present_rate == 0)
  4582. + return POWER_SUPPLY_STATUS_NOT_CHARGING;
  4583. +
  4584. + return POWER_SUPPLY_STATUS_UNKNOWN;
  4585. +}
  4586. +
  4587. +static inline int spwr_battery_prop_technology(struct spwr_battery_device *bat)
  4588. +{
  4589. + if (!strcasecmp("NiCd", bat->bix.type))
  4590. + return POWER_SUPPLY_TECHNOLOGY_NiCd;
  4591. +
  4592. + if (!strcasecmp("NiMH", bat->bix.type))
  4593. + return POWER_SUPPLY_TECHNOLOGY_NiMH;
  4594. +
  4595. + if (!strcasecmp("LION", bat->bix.type))
  4596. + return POWER_SUPPLY_TECHNOLOGY_LION;
  4597. +
  4598. + if (!strncasecmp("LI-ION", bat->bix.type, 6))
  4599. + return POWER_SUPPLY_TECHNOLOGY_LION;
  4600. +
  4601. + if (!strcasecmp("LiP", bat->bix.type))
  4602. + return POWER_SUPPLY_TECHNOLOGY_LIPO;
  4603. +
  4604. + return POWER_SUPPLY_TECHNOLOGY_UNKNOWN;
  4605. +}
  4606. +
  4607. +static inline int spwr_battery_prop_capacity(struct spwr_battery_device *bat)
  4608. +{
  4609. + if (bat->bst.remaining_cap && bat->bix.last_full_charge_cap)
  4610. + return bat->bst.remaining_cap * 100 / bat->bix.last_full_charge_cap;
  4611. + else
  4612. + return 0;
  4613. +}
  4614. +
  4615. +static inline int spwr_battery_prop_capacity_level(struct spwr_battery_device *bat)
  4616. +{
  4617. + if (bat->bst.state & SAM_BATTERY_STATE_CRITICAL)
  4618. + return POWER_SUPPLY_CAPACITY_LEVEL_CRITICAL;
  4619. +
  4620. + if (bat->bst.remaining_cap >= bat->bix.last_full_charge_cap)
  4621. + return POWER_SUPPLY_CAPACITY_LEVEL_FULL;
  4622. +
  4623. + if (bat->bst.remaining_cap <= bat->alarm)
  4624. + return POWER_SUPPLY_CAPACITY_LEVEL_LOW;
  4625. +
  4626. + return POWER_SUPPLY_CAPACITY_LEVEL_NORMAL;
  4627. +}
  4628. +
  4629. +static int spwr_ac_get_property(struct power_supply *psy,
  4630. + enum power_supply_property psp,
  4631. + union power_supply_propval *val)
  4632. +{
  4633. + struct spwr_ac_device *ac = power_supply_get_drvdata(psy);
  4634. + int status;
  4635. +
  4636. + mutex_lock(&ac->lock);
  4637. +
  4638. + status = spwr_ac_update_unlocked(ac);
  4639. + if (status)
  4640. + goto out;
  4641. +
  4642. + switch (psp) {
  4643. + case POWER_SUPPLY_PROP_ONLINE:
  4644. + val->intval = ac->state == 1;
  4645. + break;
  4646. +
  4647. + default:
  4648. + status = -EINVAL;
  4649. + goto out;
  4650. + }
  4651. +
  4652. +out:
  4653. + mutex_unlock(&ac->lock);
  4654. + return status;
  4655. +}
  4656. +
  4657. +static int spwr_battery_get_property(struct power_supply *psy,
  4658. + enum power_supply_property psp,
  4659. + union power_supply_propval *val)
  4660. +{
  4661. + struct spwr_battery_device *bat = power_supply_get_drvdata(psy);
  4662. + int status;
  4663. +
  4664. + mutex_lock(&bat->lock);
  4665. +
  4666. + status = spwr_battery_update_bst_unlocked(bat, true);
  4667. + if (status)
  4668. + goto out;
  4669. +
  4670. + // abort if battery is not present
  4671. + if (!spwr_battery_present(bat) && psp != POWER_SUPPLY_PROP_PRESENT) {
  4672. + status = -ENODEV;
  4673. + goto out;
  4674. + }
  4675. +
  4676. + switch (psp) {
  4677. + case POWER_SUPPLY_PROP_STATUS:
  4678. + val->intval = spwr_battery_prop_status(bat);
  4679. + break;
  4680. +
  4681. + case POWER_SUPPLY_PROP_PRESENT:
  4682. + val->intval = spwr_battery_present(bat);
  4683. + break;
  4684. +
  4685. + case POWER_SUPPLY_PROP_TECHNOLOGY:
  4686. + val->intval = spwr_battery_prop_technology(bat);
  4687. + break;
  4688. +
  4689. + case POWER_SUPPLY_PROP_CYCLE_COUNT:
  4690. + val->intval = bat->bix.cycle_count;
  4691. + break;
  4692. +
  4693. + case POWER_SUPPLY_PROP_VOLTAGE_MIN_DESIGN:
  4694. + val->intval = bat->bix.design_voltage * 1000;
  4695. + break;
  4696. +
  4697. + case POWER_SUPPLY_PROP_VOLTAGE_NOW:
  4698. + val->intval = bat->bst.present_voltage * 1000;
  4699. + break;
  4700. +
  4701. + case POWER_SUPPLY_PROP_CURRENT_NOW:
  4702. + case POWER_SUPPLY_PROP_POWER_NOW:
  4703. + val->intval = bat->bst.present_rate * 1000;
  4704. + break;
  4705. +
  4706. + case POWER_SUPPLY_PROP_CHARGE_FULL_DESIGN:
  4707. + case POWER_SUPPLY_PROP_ENERGY_FULL_DESIGN:
  4708. + val->intval = bat->bix.design_cap * 1000;
  4709. + break;
  4710. +
  4711. + case POWER_SUPPLY_PROP_CHARGE_FULL:
  4712. + case POWER_SUPPLY_PROP_ENERGY_FULL:
  4713. + val->intval = bat->bix.last_full_charge_cap * 1000;
  4714. + break;
  4715. +
  4716. + case POWER_SUPPLY_PROP_CHARGE_NOW:
  4717. + case POWER_SUPPLY_PROP_ENERGY_NOW:
  4718. + val->intval = bat->bst.remaining_cap * 1000;
  4719. + break;
  4720. +
  4721. + case POWER_SUPPLY_PROP_CAPACITY:
  4722. + val->intval = spwr_battery_prop_capacity(bat);
  4723. + break;
  4724. +
  4725. + case POWER_SUPPLY_PROP_CAPACITY_LEVEL:
  4726. + val->intval = spwr_battery_prop_capacity_level(bat);
  4727. + break;
  4728. +
  4729. + case POWER_SUPPLY_PROP_MODEL_NAME:
  4730. + val->strval = bat->bix.model;
  4731. + break;
  4732. +
  4733. + case POWER_SUPPLY_PROP_MANUFACTURER:
  4734. + val->strval = bat->bix.oem_info;
  4735. + break;
  4736. +
  4737. + case POWER_SUPPLY_PROP_SERIAL_NUMBER:
  4738. + val->strval = bat->bix.serial;
  4739. + break;
  4740. +
  4741. + default:
  4742. + status = -EINVAL;
  4743. + goto out;
  4744. + }
  4745. +
  4746. +out:
  4747. + mutex_unlock(&bat->lock);
  4748. + return status;
  4749. +}
  4750. +
  4751. +
  4752. +static ssize_t spwr_battery_alarm_show(struct device *dev,
  4753. + struct device_attribute *attr,
  4754. + char *buf)
  4755. +{
  4756. + struct power_supply *psy = dev_get_drvdata(dev);
  4757. + struct spwr_battery_device *bat = power_supply_get_drvdata(psy);
  4758. +
  4759. + return sprintf(buf, "%d\n", bat->alarm * 1000);
  4760. +}
  4761. +
  4762. +static ssize_t spwr_battery_alarm_store(struct device *dev,
  4763. + struct device_attribute *attr,
  4764. + const char *buf, size_t count)
  4765. +{
  4766. + struct power_supply *psy = dev_get_drvdata(dev);
  4767. + struct spwr_battery_device *bat = power_supply_get_drvdata(psy);
  4768. + unsigned long value;
  4769. + int status;
  4770. +
  4771. + status = kstrtoul(buf, 0, &value);
  4772. + if (status)
  4773. + return status;
  4774. +
  4775. + if (!spwr_battery_present(bat))
  4776. + return -ENODEV;
  4777. +
  4778. + status = spwr_battery_set_alarm(bat, value / 1000);
  4779. + if (status)
  4780. + return status;
  4781. +
  4782. + return count;
  4783. +}
  4784. +
  4785. +static const struct device_attribute alarm_attr = {
  4786. + .attr = {.name = "alarm", .mode = 0644},
  4787. + .show = spwr_battery_alarm_show,
  4788. + .store = spwr_battery_alarm_store,
  4789. +};
  4790. +
  4791. +
  4792. +static int spwr_ac_register(struct spwr_ac_device *ac, struct platform_device *pdev)
  4793. +{
  4794. + struct power_supply_config psy_cfg = {};
  4795. + u32 sta;
  4796. + int status;
  4797. +
  4798. + // make sure the device is there and functioning properly
  4799. + status = sam_psy_get_sta(0x01, 0x01, &sta);
  4800. + if (status)
  4801. + return status;
  4802. +
  4803. + if ((sta & SAM_BATTERY_STA_OK) != SAM_BATTERY_STA_OK)
  4804. + return -ENODEV;
  4805. +
  4806. + psy_cfg.drv_data = ac;
  4807. +
  4808. + ac->pdev = pdev;
  4809. + mutex_init(&ac->lock);
  4810. +
  4811. + snprintf(ac->name, ARRAY_SIZE(ac->name), "ADP0");
  4812. +
  4813. + ac->psy_desc.name = ac->name;
  4814. + ac->psy_desc.type = POWER_SUPPLY_TYPE_MAINS;
  4815. + ac->psy_desc.properties = spwr_ac_props;
  4816. + ac->psy_desc.num_properties = ARRAY_SIZE(spwr_ac_props);
  4817. + ac->psy_desc.get_property = spwr_ac_get_property;
  4818. +
  4819. + ac->psy = power_supply_register(&ac->pdev->dev, &ac->psy_desc, &psy_cfg);
  4820. + if (IS_ERR(ac->psy)) {
  4821. + status = PTR_ERR(ac->psy);
  4822. + goto err_psy;
  4823. + }
  4824. +
  4825. + ac->notif.base.priority = 1;
  4826. + ac->notif.base.fn = spwr_notify_ac;
  4827. + ac->notif.event.reg = SSAM_EVENT_REGISTRY_SAM;
  4828. + ac->notif.event.id.target_category = SSAM_SSH_TC_BAT;
  4829. + ac->notif.event.id.instance = 0;
  4830. + ac->notif.event.flags = SSAM_EVENT_SEQUENCED;
  4831. +
  4832. + status = surface_sam_ssh_notifier_register(&ac->notif);
  4833. + if (status)
  4834. + goto err_notif;
  4835. +
  4836. + return 0;
  4837. +
  4838. +err_notif:
  4839. + power_supply_unregister(ac->psy);
  4840. +err_psy:
  4841. + mutex_destroy(&ac->lock);
  4842. + return status;
  4843. +}
  4844. +
  4845. +static int spwr_ac_unregister(struct spwr_ac_device *ac)
  4846. +{
  4847. + surface_sam_ssh_notifier_unregister(&ac->notif);
  4848. + power_supply_unregister(ac->psy);
  4849. + mutex_destroy(&ac->lock);
  4850. + return 0;
  4851. +}
  4852. +
  4853. +static int spwr_battery_register(struct spwr_battery_device *bat,
  4854. + struct platform_device *pdev,
  4855. + const struct ssam_battery_properties *p)
  4856. +{
  4857. + struct power_supply_config psy_cfg = {};
  4858. + u32 sta;
  4859. + int status;
  4860. +
  4861. + bat->pdev = pdev;
  4862. + bat->p = p;
  4863. +
  4864. + // make sure the device is there and functioning properly
  4865. + status = sam_psy_get_sta(bat->p->channel, bat->p->instance, &sta);
  4866. + if (status)
  4867. + return status;
  4868. +
  4869. + if ((sta & SAM_BATTERY_STA_OK) != SAM_BATTERY_STA_OK)
  4870. + return -ENODEV;
  4871. +
  4872. + status = spwr_battery_update_bix_unlocked(bat);
  4873. + if (status)
  4874. + return status;
  4875. +
  4876. + if (spwr_battery_present(bat)) {
  4877. + status = spwr_battery_set_alarm_unlocked(bat, bat->bix.design_cap_warn);
  4878. + if (status)
  4879. + return status;
  4880. + }
  4881. +
  4882. + snprintf(bat->name, ARRAY_SIZE(bat->name), "BAT%d", bat->p->num);
  4883. + bat->psy_desc.name = bat->name;
  4884. + bat->psy_desc.type = POWER_SUPPLY_TYPE_BATTERY;
  4885. +
  4886. + if (bat->bix.power_unit == SAM_BATTERY_POWER_UNIT_MA) {
  4887. + bat->psy_desc.properties = spwr_battery_props_chg;
  4888. + bat->psy_desc.num_properties = ARRAY_SIZE(spwr_battery_props_chg);
  4889. + } else {
  4890. + bat->psy_desc.properties = spwr_battery_props_eng;
  4891. + bat->psy_desc.num_properties = ARRAY_SIZE(spwr_battery_props_eng);
  4892. + }
  4893. +
  4894. + bat->psy_desc.get_property = spwr_battery_get_property;
  4895. +
  4896. + mutex_init(&bat->lock);
  4897. + psy_cfg.drv_data = bat;
  4898. +
  4899. + INIT_DELAYED_WORK(&bat->update_work, spwr_battery_update_bst_workfn);
  4900. +
  4901. + bat->psy = power_supply_register(&bat->pdev->dev, &bat->psy_desc, &psy_cfg);
  4902. + if (IS_ERR(bat->psy)) {
  4903. + status = PTR_ERR(bat->psy);
  4904. + goto err_psy;
  4905. + }
  4906. +
  4907. + bat->notif.base.priority = 1;
  4908. + bat->notif.base.fn = spwr_notify_bat;
  4909. + bat->notif.event.reg = p->registry;
  4910. + bat->notif.event.id.target_category = SSAM_SSH_TC_BAT;
  4911. + bat->notif.event.id.instance = 0;
  4912. + bat->notif.event.flags = SSAM_EVENT_SEQUENCED;
  4913. +
  4914. + status = surface_sam_ssh_notifier_register(&bat->notif);
  4915. + if (status)
  4916. + goto err_notif;
  4917. +
  4918. + status = device_create_file(&bat->psy->dev, &alarm_attr);
  4919. + if (status)
  4920. + goto err_file;
  4921. +
  4922. + return 0;
  4923. +
  4924. +err_file:
  4925. + surface_sam_ssh_notifier_unregister(&bat->notif);
  4926. +err_notif:
  4927. + power_supply_unregister(bat->psy);
  4928. +err_psy:
  4929. + mutex_destroy(&bat->lock);
  4930. + return status;
  4931. +}
  4932. +
  4933. +static void spwr_battery_unregister(struct spwr_battery_device *bat)
  4934. +{
  4935. + surface_sam_ssh_notifier_unregister(&bat->notif);
  4936. + cancel_delayed_work_sync(&bat->update_work);
  4937. + device_remove_file(&bat->psy->dev, &alarm_attr);
  4938. + power_supply_unregister(bat->psy);
  4939. + mutex_destroy(&bat->lock);
  4940. +}
  4941. +
  4942. +
  4943. +/*
  4944. + * Battery Driver.
  4945. + */
  4946. +
  4947. +#ifdef CONFIG_PM_SLEEP
  4948. +static int surface_sam_sid_battery_resume(struct device *dev)
  4949. +{
  4950. + struct spwr_battery_device *bat;
  4951. +
  4952. + bat = dev_get_drvdata(dev);
  4953. + return spwr_battery_recheck(bat);
  4954. +}
  4955. +#else
  4956. +#define surface_sam_sid_battery_resume NULL
  4957. +#endif
  4958. +
  4959. +SIMPLE_DEV_PM_OPS(surface_sam_sid_battery_pm, NULL, surface_sam_sid_battery_resume);
  4960. +
  4961. +static int surface_sam_sid_battery_probe(struct platform_device *pdev)
  4962. +{
  4963. + struct spwr_battery_device *bat;
  4964. + int status;
  4965. +
  4966. + // link to ec
  4967. + status = surface_sam_ssh_consumer_register(&pdev->dev);
  4968. + if (status)
  4969. + return status == -ENXIO ? -EPROBE_DEFER : status;
  4970. +
  4971. + bat = devm_kzalloc(&pdev->dev, sizeof(struct spwr_battery_device), GFP_KERNEL);
  4972. + if (!bat)
  4973. + return -ENOMEM;
  4974. +
  4975. + platform_set_drvdata(pdev, bat);
  4976. + return spwr_battery_register(bat, pdev, pdev->dev.platform_data);
  4977. +}
  4978. +
  4979. +static int surface_sam_sid_battery_remove(struct platform_device *pdev)
  4980. +{
  4981. + struct spwr_battery_device *bat;
  4982. +
  4983. + bat = platform_get_drvdata(pdev);
  4984. + spwr_battery_unregister(bat);
  4985. +
  4986. + return 0;
  4987. +}
  4988. +
  4989. +static struct platform_driver surface_sam_sid_battery = {
  4990. + .probe = surface_sam_sid_battery_probe,
  4991. + .remove = surface_sam_sid_battery_remove,
  4992. + .driver = {
  4993. + .name = "surface_sam_sid_battery",
  4994. + .pm = &surface_sam_sid_battery_pm,
  4995. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  4996. + },
  4997. +};
  4998. +
  4999. +
  5000. +/*
  5001. + * AC Driver.
  5002. + */
  5003. +
  5004. +static int surface_sam_sid_ac_probe(struct platform_device *pdev)
  5005. +{
  5006. + int status;
  5007. + struct spwr_ac_device *ac;
  5008. +
  5009. + // link to ec
  5010. + status = surface_sam_ssh_consumer_register(&pdev->dev);
  5011. + if (status)
  5012. + return status == -ENXIO ? -EPROBE_DEFER : status;
  5013. +
  5014. + ac = devm_kzalloc(&pdev->dev, sizeof(struct spwr_ac_device), GFP_KERNEL);
  5015. + if (!ac)
  5016. + return -ENOMEM;
  5017. +
  5018. + status = spwr_ac_register(ac, pdev);
  5019. + if (status)
  5020. + return status;
  5021. +
  5022. + platform_set_drvdata(pdev, ac);
  5023. + return 0;
  5024. +}
  5025. +
  5026. +static int surface_sam_sid_ac_remove(struct platform_device *pdev)
  5027. +{
  5028. + struct spwr_ac_device *ac;
  5029. +
  5030. + ac = platform_get_drvdata(pdev);
  5031. + return spwr_ac_unregister(ac);
  5032. +}
  5033. +
  5034. +static struct platform_driver surface_sam_sid_ac = {
  5035. + .probe = surface_sam_sid_ac_probe,
  5036. + .remove = surface_sam_sid_ac_remove,
  5037. + .driver = {
  5038. + .name = "surface_sam_sid_ac",
  5039. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  5040. + },
  5041. +};
  5042. +
  5043. +
  5044. +static int __init surface_sam_sid_power_init(void)
  5045. +{
  5046. + int status;
  5047. +
  5048. + status = platform_driver_register(&surface_sam_sid_battery);
  5049. + if (status)
  5050. + return status;
  5051. +
  5052. + status = platform_driver_register(&surface_sam_sid_ac);
  5053. + if (status) {
  5054. + platform_driver_unregister(&surface_sam_sid_battery);
  5055. + return status;
  5056. + }
  5057. +
  5058. + return 0;
  5059. +}
  5060. +
  5061. +static void __exit surface_sam_sid_power_exit(void)
  5062. +{
  5063. + platform_driver_unregister(&surface_sam_sid_battery);
  5064. + platform_driver_unregister(&surface_sam_sid_ac);
  5065. +}
  5066. +
  5067. +module_init(surface_sam_sid_power_init);
  5068. +module_exit(surface_sam_sid_power_exit);
  5069. +
  5070. +MODULE_AUTHOR("Maximilian Luz <luzmaximilian@gmail.com>");
  5071. +MODULE_DESCRIPTION("Surface Battery/AC Driver for 7th Generation Surface Devices");
  5072. +MODULE_LICENSE("GPL");
  5073. +MODULE_ALIAS("platform:surface_sam_sid_ac");
  5074. +MODULE_ALIAS("platform:surface_sam_sid_battery");
  5075. diff --git a/drivers/platform/x86/surface_sam/surface_sam_sid_power.h b/drivers/platform/x86/surface_sam/surface_sam_sid_power.h
  5076. new file mode 100644
  5077. index 0000000000000..2e8f212086e12
  5078. --- /dev/null
  5079. +++ b/drivers/platform/x86/surface_sam/surface_sam_sid_power.h
  5080. @@ -0,0 +1,15 @@
  5081. +#ifndef _SURFACE_SAM_SID_POWER_H
  5082. +#define _SURFACE_SAM_SID_POWER_H
  5083. +
  5084. +#include <linux/types.h>
  5085. +#include "surface_sam_ssh.h"
  5086. +
  5087. +
  5088. +struct ssam_battery_properties {
  5089. + struct ssam_event_registry registry;
  5090. + u8 num;
  5091. + u8 channel;
  5092. + u8 instance;
  5093. +};
  5094. +
  5095. +#endif /* _SURFACE_SAM_SID_POWER_H */
  5096. diff --git a/drivers/platform/x86/surface_sam/surface_sam_sid_vhf.c b/drivers/platform/x86/surface_sam/surface_sam_sid_vhf.c
  5097. new file mode 100644
  5098. index 0000000000000..474221097eaf1
  5099. --- /dev/null
  5100. +++ b/drivers/platform/x86/surface_sam/surface_sam_sid_vhf.c
  5101. @@ -0,0 +1,432 @@
  5102. +// SPDX-License-Identifier: GPL-2.0-or-later
  5103. +/*
  5104. + * Microsofs Surface HID (VHF) driver for HID input events via SAM.
  5105. + * Used for keyboard input events on the 7th generation Surface Laptops.
  5106. + */
  5107. +
  5108. +#include <linux/acpi.h>
  5109. +#include <linux/hid.h>
  5110. +#include <linux/input.h>
  5111. +#include <linux/platform_device.h>
  5112. +#include <linux/types.h>
  5113. +
  5114. +#include "surface_sam_ssh.h"
  5115. +#include "surface_sam_sid_vhf.h"
  5116. +
  5117. +#define SID_VHF_INPUT_NAME "Microsoft Surface HID"
  5118. +
  5119. +#define SAM_EVENT_SID_VHF_TC 0x15
  5120. +
  5121. +#define VHF_HID_STARTED 0
  5122. +
  5123. +struct sid_vhf {
  5124. + const struct ssam_hid_properties *p;
  5125. + struct platform_device *dev;
  5126. + struct hid_device *hid;
  5127. + struct ssam_event_notifier notif;
  5128. + unsigned long state;
  5129. +};
  5130. +
  5131. +
  5132. +static int sid_vhf_hid_start(struct hid_device *hid)
  5133. +{
  5134. + hid_dbg(hid, "%s\n", __func__);
  5135. + return 0;
  5136. +}
  5137. +
  5138. +static void sid_vhf_hid_stop(struct hid_device *hid)
  5139. +{
  5140. + hid_dbg(hid, "%s\n", __func__);
  5141. +}
  5142. +
  5143. +static int sid_vhf_hid_open(struct hid_device *hid)
  5144. +{
  5145. + struct sid_vhf *vhf = dev_get_drvdata(hid->dev.parent);
  5146. +
  5147. + hid_dbg(hid, "%s\n", __func__);
  5148. +
  5149. + set_bit(VHF_HID_STARTED, &vhf->state);
  5150. + return 0;
  5151. +}
  5152. +
  5153. +static void sid_vhf_hid_close(struct hid_device *hid)
  5154. +{
  5155. +
  5156. + struct sid_vhf *vhf = dev_get_drvdata(hid->dev.parent);
  5157. +
  5158. + hid_dbg(hid, "%s\n", __func__);
  5159. +
  5160. + clear_bit(VHF_HID_STARTED, &vhf->state);
  5161. +}
  5162. +
  5163. +struct surface_sam_sid_vhf_meta_rqst {
  5164. + u8 id;
  5165. + u32 offset;
  5166. + u32 length; // buffer limit on send, length of data received on receive
  5167. + u8 end; // 0x01 if end was reached
  5168. +} __packed;
  5169. +
  5170. +struct vhf_device_metadata_info {
  5171. + u8 len;
  5172. + u8 _2;
  5173. + u8 _3;
  5174. + u8 _4;
  5175. + u8 _5;
  5176. + u8 _6;
  5177. + u8 _7;
  5178. + u16 hid_len; // hid descriptor length
  5179. +} __packed;
  5180. +
  5181. +struct vhf_device_metadata {
  5182. + u32 len;
  5183. + u16 vendor_id;
  5184. + u16 product_id;
  5185. + u8 _1[24];
  5186. +} __packed;
  5187. +
  5188. +union vhf_buffer_data {
  5189. + struct vhf_device_metadata_info info;
  5190. + u8 pld[0x76];
  5191. + struct vhf_device_metadata meta;
  5192. +};
  5193. +
  5194. +struct surface_sam_sid_vhf_meta_resp {
  5195. + struct surface_sam_sid_vhf_meta_rqst rqst;
  5196. + union vhf_buffer_data data;
  5197. +} __packed;
  5198. +
  5199. +
  5200. +static int vhf_get_metadata(u8 iid, struct vhf_device_metadata *meta)
  5201. +{
  5202. + int status;
  5203. +
  5204. + struct surface_sam_sid_vhf_meta_resp resp = {
  5205. + .rqst = {
  5206. + .id = 2,
  5207. + .offset = 0,
  5208. + .length = 0x76,
  5209. + .end = 0
  5210. + }
  5211. + };
  5212. +
  5213. + struct surface_sam_ssh_rqst rqst = {
  5214. + .tc = 0x15,
  5215. + .cid = 0x04,
  5216. + .iid = iid,
  5217. + .chn = 0x02,
  5218. + .snc = 0x01,
  5219. + .cdl = sizeof(struct surface_sam_sid_vhf_meta_rqst),
  5220. + .pld = (u8 *)&resp.rqst,
  5221. + };
  5222. +
  5223. + struct surface_sam_ssh_buf result = {
  5224. + .cap = sizeof(struct surface_sam_sid_vhf_meta_resp),
  5225. + .len = 0,
  5226. + .data = (u8 *)&resp,
  5227. + };
  5228. +
  5229. + status = surface_sam_ssh_rqst(&rqst, &result);
  5230. + if (status)
  5231. + return status;
  5232. +
  5233. + *meta = resp.data.meta;
  5234. +
  5235. + return 0;
  5236. +}
  5237. +
  5238. +static int vhf_get_hid_descriptor(struct hid_device *hid, u8 iid, u8 **desc, int *size)
  5239. +{
  5240. + int status, len;
  5241. + u8 *buf;
  5242. +
  5243. + struct surface_sam_sid_vhf_meta_resp resp = {
  5244. + .rqst = {
  5245. + .id = 0,
  5246. + .offset = 0,
  5247. + .length = 0x76,
  5248. + .end = 0,
  5249. + }
  5250. + };
  5251. +
  5252. + struct surface_sam_ssh_rqst rqst = {
  5253. + .tc = 0x15,
  5254. + .cid = 0x04,
  5255. + .iid = iid,
  5256. + .chn = 0x02,
  5257. + .snc = 0x01,
  5258. + .cdl = sizeof(struct surface_sam_sid_vhf_meta_rqst),
  5259. + .pld = (u8 *)&resp.rqst,
  5260. + };
  5261. +
  5262. + struct surface_sam_ssh_buf result = {
  5263. + .cap = sizeof(struct surface_sam_sid_vhf_meta_resp),
  5264. + .len = 0,
  5265. + .data = (u8 *)&resp,
  5266. + };
  5267. +
  5268. + // first fetch 00 to get the total length
  5269. + status = surface_sam_ssh_rqst(&rqst, &result);
  5270. + if (status)
  5271. + return status;
  5272. +
  5273. + len = resp.data.info.hid_len;
  5274. +
  5275. + // allocate a buffer for the descriptor
  5276. + buf = kzalloc(len, GFP_KERNEL);
  5277. +
  5278. + // then, iterate and write into buffer, copying out bytes
  5279. + resp.rqst.id = 1;
  5280. + resp.rqst.offset = 0;
  5281. + resp.rqst.length = 0x76;
  5282. + resp.rqst.end = 0;
  5283. +
  5284. + while (!resp.rqst.end && resp.rqst.offset < len) {
  5285. + status = surface_sam_ssh_rqst(&rqst, &result);
  5286. + if (status) {
  5287. + kfree(buf);
  5288. + return status;
  5289. + }
  5290. + memcpy(buf + resp.rqst.offset, resp.data.pld, resp.rqst.length);
  5291. +
  5292. + resp.rqst.offset += resp.rqst.length;
  5293. + }
  5294. +
  5295. + *desc = buf;
  5296. + *size = len;
  5297. +
  5298. + return 0;
  5299. +}
  5300. +
  5301. +static int sid_vhf_hid_parse(struct hid_device *hid)
  5302. +{
  5303. + struct sid_vhf *vhf = dev_get_drvdata(hid->dev.parent);
  5304. + int ret = 0, size;
  5305. + u8 *buf;
  5306. +
  5307. + ret = vhf_get_hid_descriptor(hid, vhf->p->instance, &buf, &size);
  5308. + if (ret != 0) {
  5309. + hid_err(hid, "Failed to read HID descriptor from device: %d\n", ret);
  5310. + return -EIO;
  5311. + }
  5312. + hid_dbg(hid, "HID descriptor of device:");
  5313. + print_hex_dump_debug("descriptor:", DUMP_PREFIX_OFFSET, 16, 1, buf, size, false);
  5314. +
  5315. + ret = hid_parse_report(hid, buf, size);
  5316. + kfree(buf);
  5317. + return ret;
  5318. +
  5319. +}
  5320. +
  5321. +static int sid_vhf_hid_raw_request(struct hid_device *hid, unsigned char
  5322. + reportnum, u8 *buf, size_t len, unsigned char rtype, int
  5323. + reqtype)
  5324. +{
  5325. + struct sid_vhf *vhf = dev_get_drvdata(hid->dev.parent);
  5326. + int status;
  5327. + u8 cid;
  5328. + struct surface_sam_ssh_rqst rqst = {};
  5329. + struct surface_sam_ssh_buf result = {};
  5330. +
  5331. + hid_dbg(hid, "%s: reportnum=%#04x rtype=%i reqtype=%i\n", __func__, reportnum, rtype, reqtype);
  5332. + print_hex_dump_debug("report:", DUMP_PREFIX_OFFSET, 16, 1, buf, len, false);
  5333. +
  5334. + // Byte 0 is the report number. Report data starts at byte 1.
  5335. + buf[0] = reportnum;
  5336. +
  5337. + switch (rtype) {
  5338. + case HID_OUTPUT_REPORT:
  5339. + cid = 0x01;
  5340. + break;
  5341. + case HID_FEATURE_REPORT:
  5342. + switch (reqtype) {
  5343. + case HID_REQ_GET_REPORT:
  5344. + // The EC doesn't respond to GET FEATURE for these touchpad reports
  5345. + // we immediately discard to avoid waiting for a timeout.
  5346. + if (reportnum == 6 || reportnum == 7 || reportnum == 8 || reportnum == 9 || reportnum == 0x0b) {
  5347. + hid_dbg(hid, "%s: skipping get feature report for 0x%02x\n", __func__, reportnum);
  5348. + return 0;
  5349. + }
  5350. +
  5351. + cid = 0x02;
  5352. + break;
  5353. + case HID_REQ_SET_REPORT:
  5354. + cid = 0x03;
  5355. + break;
  5356. + default:
  5357. + hid_err(hid, "%s: unknown req type 0x%02x\n", __func__, rtype);
  5358. + return -EIO;
  5359. + }
  5360. + break;
  5361. + default:
  5362. + hid_err(hid, "%s: unknown report type 0x%02x\n", __func__, reportnum);
  5363. + return -EIO;
  5364. + }
  5365. +
  5366. + rqst.tc = SAM_EVENT_SID_VHF_TC;
  5367. + rqst.chn = 0x02;
  5368. + rqst.iid = vhf->p->instance;
  5369. + rqst.cid = cid;
  5370. + rqst.snc = reqtype == HID_REQ_GET_REPORT ? 0x01 : 0x00;
  5371. + rqst.cdl = reqtype == HID_REQ_GET_REPORT ? 0x01 : len;
  5372. + rqst.pld = buf;
  5373. +
  5374. + result.cap = len;
  5375. + result.len = 0;
  5376. + result.data = buf;
  5377. +
  5378. + hid_dbg(hid, "%s: sending to cid=%#04x snc=%#04x\n", __func__, cid, HID_REQ_GET_REPORT == reqtype);
  5379. +
  5380. + status = surface_sam_ssh_rqst(&rqst, &result);
  5381. + hid_dbg(hid, "%s: status %i\n", __func__, status);
  5382. +
  5383. + if (status)
  5384. + return status;
  5385. +
  5386. + if (result.len > 0)
  5387. + print_hex_dump_debug("response:", DUMP_PREFIX_OFFSET, 16, 1, result.data, result.len, false);
  5388. +
  5389. + return result.len;
  5390. +}
  5391. +
  5392. +static struct hid_ll_driver sid_vhf_hid_ll_driver = {
  5393. + .start = sid_vhf_hid_start,
  5394. + .stop = sid_vhf_hid_stop,
  5395. + .open = sid_vhf_hid_open,
  5396. + .close = sid_vhf_hid_close,
  5397. + .parse = sid_vhf_hid_parse,
  5398. + .raw_request = sid_vhf_hid_raw_request,
  5399. +};
  5400. +
  5401. +
  5402. +static struct hid_device *sid_vhf_create_hid_device(struct platform_device *pdev, struct vhf_device_metadata *meta)
  5403. +{
  5404. + struct hid_device *hid;
  5405. +
  5406. + hid = hid_allocate_device();
  5407. + if (IS_ERR(hid))
  5408. + return hid;
  5409. +
  5410. + hid->dev.parent = &pdev->dev;
  5411. +
  5412. + hid->bus = BUS_VIRTUAL;
  5413. + hid->vendor = meta->vendor_id;
  5414. + hid->product = meta->product_id;
  5415. +
  5416. + hid->ll_driver = &sid_vhf_hid_ll_driver;
  5417. +
  5418. + sprintf(hid->name, "%s", SID_VHF_INPUT_NAME);
  5419. +
  5420. + return hid;
  5421. +}
  5422. +
  5423. +static u32 sid_vhf_event_handler(struct ssam_notifier_block *nb, const struct ssam_event *event)
  5424. +{
  5425. + struct sid_vhf *vhf = container_of(nb, struct sid_vhf, notif.base);
  5426. + int status;
  5427. +
  5428. + if (event->target_category != SSAM_SSH_TC_HID)
  5429. + return 0;
  5430. +
  5431. + if (event->channel != 0x02)
  5432. + return 0;
  5433. +
  5434. + if (event->instance_id != vhf->p->instance)
  5435. + return 0;
  5436. +
  5437. + if (event->command_id != 0x00 && event->command_id != 0x03 && event->command_id != 0x04)
  5438. + return 0;
  5439. +
  5440. + // skip if HID hasn't started yet
  5441. + if (!test_bit(VHF_HID_STARTED, &vhf->state))
  5442. + return SSAM_NOTIF_HANDLED;
  5443. +
  5444. + status = hid_input_report(vhf->hid, HID_INPUT_REPORT, (u8 *)&event->data[0], event->length, 0);
  5445. + return ssam_notifier_from_errno(status) | SSAM_NOTIF_HANDLED;
  5446. +}
  5447. +
  5448. +static int surface_sam_sid_vhf_probe(struct platform_device *pdev)
  5449. +{
  5450. + const struct ssam_hid_properties *p = pdev->dev.platform_data;
  5451. + struct sid_vhf *vhf;
  5452. + struct vhf_device_metadata meta = {};
  5453. + struct hid_device *hid;
  5454. + int status;
  5455. +
  5456. + // add device link to EC
  5457. + status = surface_sam_ssh_consumer_register(&pdev->dev);
  5458. + if (status)
  5459. + return status == -ENXIO ? -EPROBE_DEFER : status;
  5460. +
  5461. + vhf = kzalloc(sizeof(struct sid_vhf), GFP_KERNEL);
  5462. + if (!vhf)
  5463. + return -ENOMEM;
  5464. +
  5465. + status = vhf_get_metadata(p->instance, &meta);
  5466. + if (status)
  5467. + goto err_create_hid;
  5468. +
  5469. + hid = sid_vhf_create_hid_device(pdev, &meta);
  5470. + if (IS_ERR(hid)) {
  5471. + status = PTR_ERR(hid);
  5472. + goto err_create_hid;
  5473. + }
  5474. +
  5475. + vhf->p = pdev->dev.platform_data;
  5476. + vhf->dev = pdev;
  5477. + vhf->hid = hid;
  5478. +
  5479. + vhf->notif.base.priority = 1;
  5480. + vhf->notif.base.fn = sid_vhf_event_handler;
  5481. + vhf->notif.event.reg = p->registry;
  5482. + vhf->notif.event.id.target_category = SSAM_SSH_TC_HID;
  5483. + vhf->notif.event.id.instance = p->instance;
  5484. + vhf->notif.event.flags = 0;
  5485. +
  5486. + platform_set_drvdata(pdev, vhf);
  5487. +
  5488. + status = surface_sam_ssh_notifier_register(&vhf->notif);
  5489. + if (status)
  5490. + goto err_notif;
  5491. +
  5492. + status = hid_add_device(hid);
  5493. + if (status)
  5494. + goto err_add_hid;
  5495. +
  5496. + return 0;
  5497. +
  5498. +err_add_hid:
  5499. + surface_sam_ssh_notifier_unregister(&vhf->notif);
  5500. +err_notif:
  5501. + hid_destroy_device(hid);
  5502. + platform_set_drvdata(pdev, NULL);
  5503. +err_create_hid:
  5504. + kfree(vhf);
  5505. + return status;
  5506. +}
  5507. +
  5508. +static int surface_sam_sid_vhf_remove(struct platform_device *pdev)
  5509. +{
  5510. + struct sid_vhf *vhf = platform_get_drvdata(pdev);
  5511. +
  5512. + surface_sam_ssh_notifier_unregister(&vhf->notif);
  5513. + hid_destroy_device(vhf->hid);
  5514. + kfree(vhf);
  5515. +
  5516. + platform_set_drvdata(pdev, NULL);
  5517. + return 0;
  5518. +}
  5519. +
  5520. +static struct platform_driver surface_sam_sid_vhf = {
  5521. + .probe = surface_sam_sid_vhf_probe,
  5522. + .remove = surface_sam_sid_vhf_remove,
  5523. + .driver = {
  5524. + .name = "surface_sam_sid_vhf",
  5525. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  5526. + },
  5527. +};
  5528. +module_platform_driver(surface_sam_sid_vhf);
  5529. +
  5530. +MODULE_AUTHOR("Blaž Hrastnik <blaz@mxxn.io>");
  5531. +MODULE_DESCRIPTION("Driver for HID devices connected via Surface SAM");
  5532. +MODULE_LICENSE("GPL");
  5533. +MODULE_ALIAS("platform:surface_sam_sid_vhf");
  5534. diff --git a/drivers/platform/x86/surface_sam/surface_sam_sid_vhf.h b/drivers/platform/x86/surface_sam/surface_sam_sid_vhf.h
  5535. new file mode 100644
  5536. index 0000000000000..eb55485ccb119
  5537. --- /dev/null
  5538. +++ b/drivers/platform/x86/surface_sam/surface_sam_sid_vhf.h
  5539. @@ -0,0 +1,13 @@
  5540. +#ifndef _SURFACE_SAM_SID_VHF_H
  5541. +#define _SURFACE_SAM_SID_VHF_H
  5542. +
  5543. +#include <linux/types.h>
  5544. +#include "surface_sam_ssh.h"
  5545. +
  5546. +
  5547. +struct ssam_hid_properties {
  5548. + struct ssam_event_registry registry;
  5549. + u8 instance;
  5550. +};
  5551. +
  5552. +#endif /* _SURFACE_SAM_SID_VHF_H */
  5553. diff --git a/drivers/platform/x86/surface_sam/surface_sam_ssh.c b/drivers/platform/x86/surface_sam/surface_sam_ssh.c
  5554. new file mode 100644
  5555. index 0000000000000..ef1ce8cd7d7f2
  5556. --- /dev/null
  5557. +++ b/drivers/platform/x86/surface_sam/surface_sam_ssh.c
  5558. @@ -0,0 +1,5112 @@
  5559. +// SPDX-License-Identifier: GPL-2.0-or-later
  5560. +/*
  5561. + * Surface Serial Hub (SSH) driver for communication with the Surface/System
  5562. + * Aggregator Module.
  5563. + */
  5564. +
  5565. +#include <asm/unaligned.h>
  5566. +#include <linux/acpi.h>
  5567. +#include <linux/atomic.h>
  5568. +#include <linux/completion.h>
  5569. +#include <linux/crc-ccitt.h>
  5570. +#include <linux/dmaengine.h>
  5571. +#include <linux/gpio/consumer.h>
  5572. +#include <linux/interrupt.h>
  5573. +#include <linux/jiffies.h>
  5574. +#include <linux/kernel.h>
  5575. +#include <linux/kfifo.h>
  5576. +#include <linux/kref.h>
  5577. +#include <linux/kthread.h>
  5578. +#include <linux/ktime.h>
  5579. +#include <linux/list.h>
  5580. +#include <linux/mutex.h>
  5581. +#include <linux/pm.h>
  5582. +#include <linux/refcount.h>
  5583. +#include <linux/serdev.h>
  5584. +#include <linux/spinlock.h>
  5585. +#include <linux/sysfs.h>
  5586. +#include <linux/workqueue.h>
  5587. +
  5588. +#include "surface_sam_ssh.h"
  5589. +
  5590. +#define CREATE_TRACE_POINTS
  5591. +#include "surface_sam_ssh_trace.h"
  5592. +
  5593. +
  5594. +/* -- TODO. ----------------------------------------------------------------- */
  5595. +
  5596. +#define SSH_RQST_TAG_FULL "surface_sam_ssh_rqst: "
  5597. +#define SSH_RQST_TAG "rqst: "
  5598. +
  5599. +#define SSH_SUPPORTED_FLOW_CONTROL_MASK (~((u8) ACPI_UART_FLOW_CONTROL_HW))
  5600. +
  5601. +
  5602. +/* -- Error injection helpers. ---------------------------------------------- */
  5603. +
  5604. +#if 0 // not supported on 4.19
  5605. +#define noinline_if_inject noinline
  5606. +#else /* CONFIG_SURFACE_SAM_SSH_ERROR_INJECTION */
  5607. +#define noinline_if_inject inline
  5608. +#endif /* CONFIG_SURFACE_SAM_SSH_ERROR_INJECTION */
  5609. +
  5610. +
  5611. +/* -- Public interface. ----------------------------------------------------- */
  5612. +
  5613. +enum ssam_request_flags {
  5614. + SSAM_REQUEST_HAS_RESPONSE = BIT(0),
  5615. + SSAM_REQUEST_UNSEQUENCED = BIT(1),
  5616. +};
  5617. +
  5618. +struct ssam_request {
  5619. + u8 target_category;
  5620. + u8 command_id;
  5621. + u8 instance_id;
  5622. + u8 channel;
  5623. + u16 flags;
  5624. + u16 length;
  5625. + u8 *payload;
  5626. +};
  5627. +
  5628. +
  5629. +/* -- Common/utility functions. --------------------------------------------- */
  5630. +
  5631. +static inline u16 ssh_crc(const u8 *buf, size_t len)
  5632. +{
  5633. + return crc_ccitt_false(0xffff, buf, len);
  5634. +}
  5635. +
  5636. +static inline u16 __ssh_rqid_next(u16 rqid)
  5637. +{
  5638. + return rqid > 0 ? rqid + 1u : rqid + SURFACE_SAM_SSH_NUM_EVENTS + 1u;
  5639. +}
  5640. +
  5641. +static inline u16 ssh_event_to_rqid(u16 event)
  5642. +{
  5643. + return event + 1u;
  5644. +}
  5645. +
  5646. +static inline u16 ssh_rqid_to_event(u16 rqid)
  5647. +{
  5648. + return rqid - 1u;
  5649. +}
  5650. +
  5651. +static inline bool ssh_rqid_is_event(u16 rqid)
  5652. +{
  5653. + return ssh_rqid_to_event(rqid) < SURFACE_SAM_SSH_NUM_EVENTS;
  5654. +}
  5655. +
  5656. +static inline int ssh_tc_to_rqid(u8 tc)
  5657. +{
  5658. +#if 0 // TODO: check if it works without this
  5659. + /*
  5660. + * TC=0x08 represents the input subsystem on Surface Laptop 1 and 2.
  5661. + * This is mapped on Windows to RQID=0x0001. As input events seem to be
  5662. + * somewhat special with regards to enabling/disabling (they seem to be
  5663. + * enabled by default with a fixed RQID), let's do the same here.
  5664. + */
  5665. + if (tc == 0x08)
  5666. + return 0x0001;
  5667. +
  5668. + /* Default path: Set RQID = TC. */
  5669. +#endif
  5670. + return tc;
  5671. +}
  5672. +
  5673. +static inline int ssh_tc_to_event(u8 tc)
  5674. +{
  5675. + return ssh_rqid_to_event(ssh_tc_to_rqid(tc));
  5676. +}
  5677. +
  5678. +static inline u8 ssh_channel_to_index(u8 channel)
  5679. +{
  5680. + return channel - 1u;
  5681. +}
  5682. +
  5683. +static inline bool ssh_channel_is_valid(u8 channel)
  5684. +{
  5685. + return ssh_channel_to_index(channel) < SURFACE_SAM_SSH_NUM_CHANNELS;
  5686. +}
  5687. +
  5688. +
  5689. +/* -- Safe counters. -------------------------------------------------------- */
  5690. +
  5691. +struct ssh_seq_counter {
  5692. + u8 value;
  5693. +};
  5694. +
  5695. +struct ssh_rqid_counter {
  5696. + u16 value;
  5697. +};
  5698. +
  5699. +static inline void ssh_seq_reset(struct ssh_seq_counter *c)
  5700. +{
  5701. + WRITE_ONCE(c->value, 0);
  5702. +}
  5703. +
  5704. +static inline u8 ssh_seq_next(struct ssh_seq_counter *c)
  5705. +{
  5706. + u8 old = READ_ONCE(c->value);
  5707. + u8 new = old + 1;
  5708. + u8 ret;
  5709. +
  5710. + while (unlikely((ret = cmpxchg(&c->value, old, new)) != old)) {
  5711. + old = ret;
  5712. + new = old + 1;
  5713. + }
  5714. +
  5715. + return old;
  5716. +}
  5717. +
  5718. +static inline void ssh_rqid_reset(struct ssh_rqid_counter *c)
  5719. +{
  5720. + WRITE_ONCE(c->value, 0);
  5721. +}
  5722. +
  5723. +static inline u16 ssh_rqid_next(struct ssh_rqid_counter *c)
  5724. +{
  5725. + u16 old = READ_ONCE(c->value);
  5726. + u16 new = __ssh_rqid_next(old);
  5727. + u16 ret;
  5728. +
  5729. + while (unlikely((ret = cmpxchg(&c->value, old, new)) != old)) {
  5730. + old = ret;
  5731. + new = __ssh_rqid_next(old);
  5732. + }
  5733. +
  5734. + return old;
  5735. +}
  5736. +
  5737. +
  5738. +/* -- Builder functions for SAM-over-SSH messages. -------------------------- */
  5739. +
  5740. +struct msgbuf {
  5741. + u8 *buffer;
  5742. + u8 *end;
  5743. + u8 *ptr;
  5744. +};
  5745. +
  5746. +static inline void msgb_init(struct msgbuf *msgb, u8 *buffer, size_t cap)
  5747. +{
  5748. + msgb->buffer = buffer;
  5749. + msgb->end = buffer + cap;
  5750. + msgb->ptr = buffer;
  5751. +}
  5752. +
  5753. +static inline int msgb_alloc(struct msgbuf *msgb, size_t cap, gfp_t flags)
  5754. +{
  5755. + u8 *buf;
  5756. +
  5757. + buf = kzalloc(cap, flags);
  5758. + if (!buf)
  5759. + return -ENOMEM;
  5760. +
  5761. + msgb_init(msgb, buf, cap);
  5762. + return 0;
  5763. +}
  5764. +
  5765. +static inline void msgb_free(struct msgbuf *msgb)
  5766. +{
  5767. + kfree(msgb->buffer);
  5768. + msgb->buffer = NULL;
  5769. + msgb->end = NULL;
  5770. + msgb->ptr = NULL;
  5771. +}
  5772. +
  5773. +static inline void msgb_reset(struct msgbuf *msgb)
  5774. +{
  5775. + msgb->ptr = msgb->buffer;
  5776. +}
  5777. +
  5778. +static inline size_t msgb_bytes_used(const struct msgbuf *msgb)
  5779. +{
  5780. + return msgb->ptr - msgb->buffer;
  5781. +}
  5782. +
  5783. +static inline void msgb_push_u16(struct msgbuf *msgb, u16 value)
  5784. +{
  5785. + WARN_ON(msgb->ptr + sizeof(u16) > msgb->end);
  5786. + if (msgb->ptr + sizeof(u16) > msgb->end)
  5787. + return;
  5788. +
  5789. + put_unaligned_le16(value, msgb->ptr);
  5790. + msgb->ptr += sizeof(u16);
  5791. +}
  5792. +
  5793. +static inline void msgb_push_syn(struct msgbuf *msgb)
  5794. +{
  5795. + msgb_push_u16(msgb, SSH_MSG_SYN);
  5796. +}
  5797. +
  5798. +static inline void msgb_push_buf(struct msgbuf *msgb, const u8 *buf, size_t len)
  5799. +{
  5800. + msgb->ptr = memcpy(msgb->ptr, buf, len) + len;
  5801. +}
  5802. +
  5803. +static inline void msgb_push_crc(struct msgbuf *msgb, const u8 *buf, size_t len)
  5804. +{
  5805. + msgb_push_u16(msgb, ssh_crc(buf, len));
  5806. +}
  5807. +
  5808. +static inline void msgb_push_frame(struct msgbuf *msgb, u8 ty, u16 len, u8 seq)
  5809. +{
  5810. + struct ssh_frame *frame = (struct ssh_frame *)msgb->ptr;
  5811. + const u8 *const begin = msgb->ptr;
  5812. +
  5813. + WARN_ON(msgb->ptr + sizeof(*frame) > msgb->end);
  5814. + if (msgb->ptr + sizeof(*frame) > msgb->end)
  5815. + return;
  5816. +
  5817. + frame->type = ty;
  5818. + put_unaligned_le16(len, &frame->len);
  5819. + frame->seq = seq;
  5820. +
  5821. + msgb->ptr += sizeof(*frame);
  5822. + msgb_push_crc(msgb, begin, msgb->ptr - begin);
  5823. +}
  5824. +
  5825. +static inline void msgb_push_ack(struct msgbuf *msgb, u8 seq)
  5826. +{
  5827. + // SYN
  5828. + msgb_push_syn(msgb);
  5829. +
  5830. + // ACK-type frame + CRC
  5831. + msgb_push_frame(msgb, SSH_FRAME_TYPE_ACK, 0x00, seq);
  5832. +
  5833. + // payload CRC (ACK-type frames do not have a payload)
  5834. + msgb_push_crc(msgb, msgb->ptr, 0);
  5835. +}
  5836. +
  5837. +static inline void msgb_push_nak(struct msgbuf *msgb)
  5838. +{
  5839. + // SYN
  5840. + msgb_push_syn(msgb);
  5841. +
  5842. + // NAK-type frame + CRC
  5843. + msgb_push_frame(msgb, SSH_FRAME_TYPE_NAK, 0x00, 0x00);
  5844. +
  5845. + // payload CRC (ACK-type frames do not have a payload)
  5846. + msgb_push_crc(msgb, msgb->ptr, 0);
  5847. +}
  5848. +
  5849. +static inline void msgb_push_cmd(struct msgbuf *msgb, u8 seq,
  5850. + const struct surface_sam_ssh_rqst *rqst,
  5851. + u16 rqid)
  5852. +{
  5853. + struct ssh_command *cmd;
  5854. + const u8 *cmd_begin;
  5855. + const u8 type = SSH_FRAME_TYPE_DATA_SEQ;
  5856. +
  5857. + // SYN
  5858. + msgb_push_syn(msgb);
  5859. +
  5860. + // command frame + crc
  5861. + msgb_push_frame(msgb, type, sizeof(*cmd) + rqst->cdl, seq);
  5862. +
  5863. + // frame payload: command struct + payload
  5864. + WARN_ON(msgb->ptr + sizeof(*cmd) > msgb->end);
  5865. + if (msgb->ptr + sizeof(*cmd) > msgb->end)
  5866. + return;
  5867. +
  5868. + cmd_begin = msgb->ptr;
  5869. + cmd = (struct ssh_command *)msgb->ptr;
  5870. +
  5871. + cmd->type = SSH_PLD_TYPE_CMD;
  5872. + cmd->tc = rqst->tc;
  5873. + cmd->chn_out = rqst->chn;
  5874. + cmd->chn_in = 0x00;
  5875. + cmd->iid = rqst->iid;
  5876. + put_unaligned_le16(rqid, &cmd->rqid);
  5877. + cmd->cid = rqst->cid;
  5878. +
  5879. + msgb->ptr += sizeof(*cmd);
  5880. +
  5881. + // command payload
  5882. + msgb_push_buf(msgb, rqst->pld, rqst->cdl);
  5883. +
  5884. + // crc for command struct + payload
  5885. + msgb_push_crc(msgb, cmd_begin, msgb->ptr - cmd_begin);
  5886. +}
  5887. +
  5888. +
  5889. +/* -- Parser functions and utilities for SAM-over-SSH messages. ------------- */
  5890. +
  5891. +struct sshp_buf {
  5892. + u8 *ptr;
  5893. + size_t len;
  5894. + size_t cap;
  5895. +};
  5896. +
  5897. +
  5898. +static inline bool sshp_validate_crc(const struct sshp_span *src, const u8 *crc)
  5899. +{
  5900. + u16 actual = ssh_crc(src->ptr, src->len);
  5901. + u16 expected = get_unaligned_le16(crc);
  5902. +
  5903. + return actual == expected;
  5904. +}
  5905. +
  5906. +static bool sshp_find_syn(const struct sshp_span *src, struct sshp_span *rem)
  5907. +{
  5908. + size_t i;
  5909. +
  5910. + for (i = 0; i < src->len - 1; i++) {
  5911. + if (likely(get_unaligned_le16(src->ptr + i) == SSH_MSG_SYN)) {
  5912. + rem->ptr = src->ptr + i;
  5913. + rem->len = src->len - i;
  5914. + return true;
  5915. + }
  5916. + }
  5917. +
  5918. + if (unlikely(src->ptr[src->len - 1] == (SSH_MSG_SYN & 0xff))) {
  5919. + rem->ptr = src->ptr + src->len - 1;
  5920. + rem->len = 1;
  5921. + return false;
  5922. + } else {
  5923. + rem->ptr = src->ptr + src->len;
  5924. + rem->len = 0;
  5925. + return false;
  5926. + }
  5927. +}
  5928. +
  5929. +static bool sshp_starts_with_syn(const struct sshp_span *src)
  5930. +{
  5931. + return src->len >= 2 && get_unaligned_le16(src->ptr) == SSH_MSG_SYN;
  5932. +}
  5933. +
  5934. +static int sshp_parse_frame(const struct device *dev,
  5935. + const struct sshp_span *source,
  5936. + struct ssh_frame **frame,
  5937. + struct sshp_span *payload,
  5938. + size_t maxlen)
  5939. +{
  5940. + struct sshp_span sf;
  5941. + struct sshp_span sp;
  5942. +
  5943. + // initialize output
  5944. + *frame = NULL;
  5945. + payload->ptr = NULL;
  5946. + payload->len = 0;
  5947. +
  5948. + if (!sshp_starts_with_syn(source)) {
  5949. + dev_warn(dev, "rx: parser: invalid start of frame\n");
  5950. + return -ENOMSG;
  5951. + }
  5952. +
  5953. + // check for minumum packet length
  5954. + if (unlikely(source->len < SSH_MESSAGE_LENGTH(0))) {
  5955. + dev_dbg(dev, "rx: parser: not enough data for frame\n");
  5956. + return 0;
  5957. + }
  5958. +
  5959. + // pin down frame
  5960. + sf.ptr = source->ptr + sizeof(u16);
  5961. + sf.len = sizeof(struct ssh_frame);
  5962. +
  5963. + // validate frame CRC
  5964. + if (unlikely(!sshp_validate_crc(&sf, sf.ptr + sf.len))) {
  5965. + dev_warn(dev, "rx: parser: invalid frame CRC\n");
  5966. + return -EBADMSG;
  5967. + }
  5968. +
  5969. + // ensure packet does not exceed maximum length
  5970. + if (unlikely(((struct ssh_frame *)sf.ptr)->len > maxlen)) {
  5971. + dev_warn(dev, "rx: parser: frame too large: %u bytes\n",
  5972. + ((struct ssh_frame *)sf.ptr)->len);
  5973. + return -EMSGSIZE;
  5974. + }
  5975. +
  5976. + // pin down payload
  5977. + sp.ptr = sf.ptr + sf.len + sizeof(u16);
  5978. + sp.len = get_unaligned_le16(&((struct ssh_frame *)sf.ptr)->len);
  5979. +
  5980. + // check for frame + payload length
  5981. + if (source->len < SSH_MESSAGE_LENGTH(sp.len)) {
  5982. + dev_dbg(dev, "rx: parser: not enough data for payload\n");
  5983. + return 0;
  5984. + }
  5985. +
  5986. + // validate payload crc
  5987. + if (unlikely(!sshp_validate_crc(&sp, sp.ptr + sp.len))) {
  5988. + dev_warn(dev, "rx: parser: invalid payload CRC\n");
  5989. + return -EBADMSG;
  5990. + }
  5991. +
  5992. + *frame = (struct ssh_frame *)sf.ptr;
  5993. + *payload = sp;
  5994. +
  5995. + dev_dbg(dev, "rx: parser: valid frame found (type: 0x%02x, len: %u)\n",
  5996. + (*frame)->type, (*frame)->len);
  5997. +
  5998. + return 0;
  5999. +}
  6000. +
  6001. +static int sshp_parse_command(const struct device *dev,
  6002. + const struct sshp_span *source,
  6003. + struct ssh_command **command,
  6004. + struct sshp_span *command_data)
  6005. +{
  6006. + // check for minimum length
  6007. + if (unlikely(source->len < sizeof(struct ssh_command))) {
  6008. + *command = NULL;
  6009. + command_data->ptr = NULL;
  6010. + command_data->len = 0;
  6011. +
  6012. + dev_err(dev, "rx: parser: command payload is too short\n");
  6013. + return -ENOMSG;
  6014. + }
  6015. +
  6016. + *command = (struct ssh_command *)source->ptr;
  6017. + command_data->ptr = source->ptr + sizeof(struct ssh_command);
  6018. + command_data->len = source->len - sizeof(struct ssh_command);
  6019. +
  6020. + dev_dbg(dev, "rx: parser: valid command found (tc: 0x%02x,"
  6021. + " cid: 0x%02x)\n", (*command)->tc, (*command)->cid);
  6022. +
  6023. + return 0;
  6024. +}
  6025. +
  6026. +
  6027. +static inline void sshp_buf_init(struct sshp_buf *buf, u8 *ptr, size_t cap)
  6028. +{
  6029. + buf->ptr = ptr;
  6030. + buf->len = 0;
  6031. + buf->cap = cap;
  6032. +}
  6033. +
  6034. +static inline int sshp_buf_alloc(struct sshp_buf *buf, size_t cap, gfp_t flags)
  6035. +{
  6036. + u8 *ptr;
  6037. +
  6038. + ptr = kzalloc(cap, flags);
  6039. + if (!ptr)
  6040. + return -ENOMEM;
  6041. +
  6042. + sshp_buf_init(buf, ptr, cap);
  6043. + return 0;
  6044. +
  6045. +}
  6046. +
  6047. +static inline void sshp_buf_free(struct sshp_buf *buf)
  6048. +{
  6049. + kfree(buf->ptr);
  6050. + buf->ptr = NULL;
  6051. + buf->len = 0;
  6052. + buf->cap = 0;
  6053. +}
  6054. +
  6055. +static inline void sshp_buf_reset(struct sshp_buf *buf)
  6056. +{
  6057. + buf->len = 0;
  6058. +}
  6059. +
  6060. +static inline void sshp_buf_drop(struct sshp_buf *buf, size_t n)
  6061. +{
  6062. + memmove(buf->ptr, buf->ptr + n, buf->len - n);
  6063. + buf->len -= n;
  6064. +}
  6065. +
  6066. +static inline size_t sshp_buf_read_from_fifo(struct sshp_buf *buf,
  6067. + struct kfifo *fifo)
  6068. +{
  6069. + size_t n;
  6070. +
  6071. + n = kfifo_out(fifo, buf->ptr + buf->len, buf->cap - buf->len);
  6072. + buf->len += n;
  6073. +
  6074. + return n;
  6075. +}
  6076. +
  6077. +static inline void sshp_buf_span_from(struct sshp_buf *buf, size_t offset,
  6078. + struct sshp_span *span)
  6079. +{
  6080. + span->ptr = buf->ptr + offset;
  6081. + span->len = buf->len - offset;
  6082. +}
  6083. +
  6084. +
  6085. +/* -- Packet transport layer (ptl). ----------------------------------------- */
  6086. +/*
  6087. + * To simplify reasoning about the code below, we define a few concepts. The
  6088. + * system below is similar to a state-machine for packets, however, there are
  6089. + * too many states to explicitly write them down. To (somewhat) manage the
  6090. + * states and packets we rely on flags, reference counting, and some simple
  6091. + * concepts. State transitions are triggered by actions.
  6092. + *
  6093. + * >> Actions <<
  6094. + *
  6095. + * - submit
  6096. + * - transmission start (process next item in queue)
  6097. + * - transmission finished (guaranteed to never be parallel to transmission
  6098. + * start)
  6099. + * - ACK received
  6100. + * - NAK received (this is equivalent to issuing re-submit for all pending
  6101. + * packets)
  6102. + * - timeout (this is equivalent to re-issuing a submit or canceling)
  6103. + * - cancel (non-pending and pending)
  6104. + *
  6105. + * >> Data Structures, Packet Ownership, General Overview <<
  6106. + *
  6107. + * The code below employs two main data structures: The packet queue, containing
  6108. + * all packets scheduled for transmission, and the set of pending packets,
  6109. + * containing all packets awaiting an ACK.
  6110. + *
  6111. + * Shared ownership of a packet is controlled via reference counting. Inside the
  6112. + * transmission system are a total of five packet owners:
  6113. + *
  6114. + * - the packet queue,
  6115. + * - the pending set,
  6116. + * - the transmitter thread,
  6117. + * - the receiver thread (via ACKing), and
  6118. + * - the timeout work item.
  6119. + *
  6120. + * Normal operation is as follows: The initial reference of the packet is
  6121. + * obtained by submitting the packet and queueing it. The receiver thread
  6122. + * takes packets from the queue. By doing this, it does not increment the
  6123. + * refcount but takes over the reference (removing it from the queue).
  6124. + * If the packet is sequenced (i.e. needs to be ACKed by the client), the
  6125. + * transmitter thread sets-up the timeout and adds the packet to the pending set
  6126. + * before starting to transmit it. As the timeout is handled by a reaper task,
  6127. + * no additional reference for it is needed. After the transmit is done, the
  6128. + * reference hold by the transmitter thread is dropped. If the packet is
  6129. + * unsequenced (i.e. does not need an ACK), the packet is completed by the
  6130. + * transmitter thread before dropping that reference.
  6131. + *
  6132. + * On receial of an ACK, the receiver thread removes and obtains the refernce to
  6133. + * the packet from the pending set. On succes, the receiver thread will then
  6134. + * complete the packet and drop its reference.
  6135. + *
  6136. + * On error, the completion callback is immediately run by on thread on which
  6137. + * the error was detected.
  6138. + *
  6139. + * To ensure that a packet eventually leaves the system it is marked as "locked"
  6140. + * directly before it is going to be completed or when it is canceled. Marking a
  6141. + * packet as "locked" has the effect that passing and creating new references
  6142. + * of the packet will be blocked. This means that the packet cannot be added
  6143. + * to the queue, the pending set, and the timeout, or be picked up by the
  6144. + * transmitter thread or receiver thread. To remove a packet from the system it
  6145. + * has to be marked as locked and subsequently all references from the data
  6146. + * structures (queue, pending) have to be removed. References held by threads
  6147. + * will eventually be dropped automatically as their execution progresses.
  6148. + *
  6149. + * Note that the packet completion callback is, in case of success and for a
  6150. + * sequenced packet, guaranteed to run on the receiver thread, thus providing a
  6151. + * way to reliably identify responses to the packet. The packet completion
  6152. + * callback is only run once and it does not indicate that the packet has fully
  6153. + * left the system. In case of re-submission (and with somewhat unlikely
  6154. + * timing), it may be possible that the packet is being re-transmitted while the
  6155. + * completion callback runs. Completion will occur both on success and internal
  6156. + * error, as well as when the packet is canceled.
  6157. + *
  6158. + * >> Flags <<
  6159. + *
  6160. + * Flags are used to indicate the state and progression of a packet. Some flags
  6161. + * have stricter guarantees than other:
  6162. + *
  6163. + * - locked
  6164. + * Indicates if the packet is locked. If the packet is locked, passing and/or
  6165. + * creating additional references to the packet is forbidden. The packet thus
  6166. + * may not be queued, dequeued, or removed or added to the pending set. Note
  6167. + * that the packet state flags may still change (e.g. it may be marked as
  6168. + * ACKed, transmitted, ...).
  6169. + *
  6170. + * - completed
  6171. + * Indicates if the packet completion has been run or is about to be run. This
  6172. + * flag is used to ensure that the packet completion callback is only run
  6173. + * once.
  6174. + *
  6175. + * - queued
  6176. + * Indicates if a packet is present in the submission queue or not. This flag
  6177. + * must only be modified with the queue lock held, and must be coherent
  6178. + * presence of the packet in the queue.
  6179. + *
  6180. + * - pending
  6181. + * Indicates if a packet is present in the set of pending packets or not.
  6182. + * This flag must only be modified with the pending lock held, and must be
  6183. + * coherent presence of the packet in the pending set.
  6184. + *
  6185. + * - transmitting
  6186. + * Indicates if the packet is currently transmitting. In case of
  6187. + * re-transmissions, it is only safe to wait on the "transmitted" completion
  6188. + * after this flag has been set. The completion will be set both in success
  6189. + * and error case.
  6190. + *
  6191. + * - transmitted
  6192. + * Indicates if the packet has been transmitted. This flag is not cleared by
  6193. + * the system, thus it indicates the first transmission only.
  6194. + *
  6195. + * - acked
  6196. + * Indicates if the packet has been acknowledged by the client. There are no
  6197. + * other guarantees given. For example, the packet may still be canceled
  6198. + * and/or the completion may be triggered an error even though this bit is
  6199. + * set. Rely on the status provided by completion instead.
  6200. + *
  6201. + * - canceled
  6202. + * Indicates if the packet has been canceled from the outside. There are no
  6203. + * other guarantees given. Specifically, the packet may be completed by
  6204. + * another part of the system before the cancellation attempts to complete it.
  6205. + *
  6206. + * >> General Notes <<
  6207. + *
  6208. + * To avoid deadlocks, if both queue and pending locks are required, the pending
  6209. + * lock must be acquired before the queue lock.
  6210. + */
  6211. +
  6212. +/**
  6213. + * Maximum number transmission attempts per sequenced packet in case of
  6214. + * time-outs. Must be smaller than 16.
  6215. + */
  6216. +#define SSH_PTL_MAX_PACKET_TRIES 3
  6217. +
  6218. +/**
  6219. + * Timeout as ktime_t delta for ACKs. If we have not received an ACK in this
  6220. + * time-frame after starting transmission, the packet will be re-submitted.
  6221. + */
  6222. +#define SSH_PTL_PACKET_TIMEOUT ms_to_ktime(1000)
  6223. +
  6224. +/**
  6225. + * Maximum time resolution for timeouts. Currently set to max(2 jiffies, 50ms).
  6226. + * Should be larger than one jiffy to avoid direct re-scheduling of reaper
  6227. + * work_struct.
  6228. + */
  6229. +#define SSH_PTL_PACKET_TIMEOUT_RESOLUTION ms_to_ktime(max(2000 / HZ, 50))
  6230. +
  6231. +/**
  6232. + * Maximum number of sequenced packets concurrently waiting for an ACK.
  6233. + * Packets marked as blocking will not be transmitted while this limit is
  6234. + * reached.
  6235. + */
  6236. +#define SSH_PTL_MAX_PENDING 1
  6237. +
  6238. +#define SSH_PTL_RX_BUF_LEN 4096
  6239. +
  6240. +#define SSH_PTL_RX_FIFO_LEN 4096
  6241. +
  6242. +
  6243. +enum ssh_ptl_state_flags {
  6244. + SSH_PTL_SF_SHUTDOWN_BIT,
  6245. +};
  6246. +
  6247. +struct ssh_ptl_ops {
  6248. + void (*data_received)(struct ssh_ptl *p, const struct sshp_span *data);
  6249. +};
  6250. +
  6251. +struct ssh_ptl {
  6252. + struct serdev_device *serdev;
  6253. + unsigned long state;
  6254. +
  6255. + struct {
  6256. + spinlock_t lock;
  6257. + struct list_head head;
  6258. + } queue;
  6259. +
  6260. + struct {
  6261. + spinlock_t lock;
  6262. + struct list_head head;
  6263. + atomic_t count;
  6264. + } pending;
  6265. +
  6266. + struct {
  6267. + bool thread_signal;
  6268. + struct task_struct *thread;
  6269. + struct wait_queue_head thread_wq;
  6270. + struct wait_queue_head packet_wq;
  6271. + struct ssh_packet *packet;
  6272. + size_t offset;
  6273. + } tx;
  6274. +
  6275. + struct {
  6276. + struct task_struct *thread;
  6277. + struct wait_queue_head wq;
  6278. + struct kfifo fifo;
  6279. + struct sshp_buf buf;
  6280. +
  6281. + struct {
  6282. + u16 seqs[8];
  6283. + u16 offset;
  6284. + } blacklist;
  6285. + } rx;
  6286. +
  6287. + struct {
  6288. + ktime_t timeout;
  6289. + ktime_t expires;
  6290. + struct delayed_work reaper;
  6291. + } rtx_timeout;
  6292. +
  6293. + struct ssh_ptl_ops ops;
  6294. +};
  6295. +
  6296. +
  6297. +#define __ssam_prcond(func, p, fmt, ...) \
  6298. + do { \
  6299. + if ((p)) \
  6300. + func((p), fmt, ##__VA_ARGS__); \
  6301. + } while (0);
  6302. +
  6303. +#define ptl_dbg(p, fmt, ...) dev_dbg(&(p)->serdev->dev, fmt, ##__VA_ARGS__)
  6304. +#define ptl_info(p, fmt, ...) dev_info(&(p)->serdev->dev, fmt, ##__VA_ARGS__)
  6305. +#define ptl_warn(p, fmt, ...) dev_warn(&(p)->serdev->dev, fmt, ##__VA_ARGS__)
  6306. +#define ptl_err(p, fmt, ...) dev_err(&(p)->serdev->dev, fmt, ##__VA_ARGS__)
  6307. +#define ptl_dbg_cond(p, fmt, ...) __ssam_prcond(ptl_dbg, p, fmt, ##__VA_ARGS__)
  6308. +
  6309. +#define to_ssh_packet(ptr, member) \
  6310. + container_of(ptr, struct ssh_packet, member)
  6311. +
  6312. +#define to_ssh_ptl(ptr, member) \
  6313. + container_of(ptr, struct ssh_ptl, member)
  6314. +
  6315. +
  6316. +#if 0 // not supported on 4.19
  6317. +
  6318. +/**
  6319. + * ssh_ptl_should_drop_ack_packet - error injection hook to drop ACK packets
  6320. + *
  6321. + * Useful to test detection and handling of automated re-transmits by the EC.
  6322. + * Specifically of packets that the EC consideres not-ACKed but the driver
  6323. + * already consideres ACKed (due to dropped ACK). In this case, the EC
  6324. + * re-transmits the packet-to-be-ACKed and the driver should detect it as
  6325. + * duplicate/already handled. Note that the driver should still send an ACK
  6326. + * for the re-transmitted packet.
  6327. + */
  6328. +static noinline bool ssh_ptl_should_drop_ack_packet(void)
  6329. +{
  6330. + return false;
  6331. +}
  6332. +ALLOW_ERROR_INJECTION(ssh_ptl_should_drop_ack_packet, TRUE);
  6333. +
  6334. +/**
  6335. + * ssh_ptl_should_drop_nak_packet - error injection hook to drop NAK packets
  6336. + *
  6337. + * Useful to test/force automated (timeout-based) re-transmit by the EC.
  6338. + * Specifically, packets that have not reached the driver completely/with valid
  6339. + * checksums. Only useful in combination with receival of (injected) bad data.
  6340. + */
  6341. +static noinline bool ssh_ptl_should_drop_nak_packet(void)
  6342. +{
  6343. + return false;
  6344. +}
  6345. +ALLOW_ERROR_INJECTION(ssh_ptl_should_drop_nak_packet, TRUE);
  6346. +
  6347. +/**
  6348. + * ssh_ptl_should_drop_dsq_packet - error injection hook to drop sequenced data
  6349. + * packet
  6350. + *
  6351. + * Useful to test re-transmit timeout of the driver. If the data packet has not
  6352. + * been ACKed after a certain time, the driver should re-transmit the packet up
  6353. + * to limited number of times defined in SSH_PTL_MAX_PACKET_TRIES.
  6354. + */
  6355. +static noinline bool ssh_ptl_should_drop_dsq_packet(void)
  6356. +{
  6357. + return false;
  6358. +}
  6359. +ALLOW_ERROR_INJECTION(ssh_ptl_should_drop_dsq_packet, TRUE);
  6360. +
  6361. +/**
  6362. + * ssh_ptl_should_fail_write - error injection hook to make serdev_device_write
  6363. + * fail
  6364. + *
  6365. + * Hook to simulate errors in serdev_device_write when transmitting packets.
  6366. + */
  6367. +static noinline int ssh_ptl_should_fail_write(void)
  6368. +{
  6369. + return 0;
  6370. +}
  6371. +ALLOW_ERROR_INJECTION(ssh_ptl_should_fail_write, ERRNO);
  6372. +
  6373. +/**
  6374. + * ssh_ptl_should_corrupt_tx_data - error injection hook to simualte invalid
  6375. + * data being sent to the EC
  6376. + *
  6377. + * Hook to simulate corrupt/invalid data being sent from host (driver) to EC.
  6378. + * Causes the package data to be actively corrupted by overwriting it with
  6379. + * pre-defined values, such that it becomes invalid, causing the EC to respond
  6380. + * with a NAK packet. Useful to test handling of NAK packets received by the
  6381. + * driver.
  6382. + */
  6383. +static noinline bool ssh_ptl_should_corrupt_tx_data(void)
  6384. +{
  6385. + return false;
  6386. +}
  6387. +ALLOW_ERROR_INJECTION(ssh_ptl_should_corrupt_tx_data, TRUE);
  6388. +
  6389. +/**
  6390. + * ssh_ptl_should_corrupt_rx_syn - error injection hook to simulate invalid
  6391. + * data being sent by the EC
  6392. + *
  6393. + * Hook to simulate invalid SYN bytes, i.e. an invalid start of messages and
  6394. + * test handling thereof in the driver.
  6395. + */
  6396. +static noinline bool ssh_ptl_should_corrupt_rx_syn(void)
  6397. +{
  6398. + return false;
  6399. +}
  6400. +ALLOW_ERROR_INJECTION(ssh_ptl_should_corrupt_rx_syn, TRUE);
  6401. +
  6402. +/**
  6403. + * ssh_ptl_should_corrupt_rx_data - error injection hook to simulate invalid
  6404. + * data being sent by the EC
  6405. + *
  6406. + * Hook to simulate invalid data/checksum of the message frame and test handling
  6407. + * thereof in the driver.
  6408. + */
  6409. +static noinline bool ssh_ptl_should_corrupt_rx_data(void)
  6410. +{
  6411. + return false;
  6412. +}
  6413. +ALLOW_ERROR_INJECTION(ssh_ptl_should_corrupt_rx_data, TRUE);
  6414. +
  6415. +
  6416. +static inline bool __ssh_ptl_should_drop_ack_packet(struct ssh_packet *packet)
  6417. +{
  6418. + if (likely(!ssh_ptl_should_drop_ack_packet()))
  6419. + return false;
  6420. +
  6421. + trace_ssam_ei_tx_drop_ack_packet(packet);
  6422. + ptl_info(packet->ptl, "packet error injection: dropping ACK packet %p\n",
  6423. + packet);
  6424. +
  6425. + return true;
  6426. +}
  6427. +
  6428. +static inline bool __ssh_ptl_should_drop_nak_packet(struct ssh_packet *packet)
  6429. +{
  6430. + if (likely(!ssh_ptl_should_drop_nak_packet()))
  6431. + return false;
  6432. +
  6433. + trace_ssam_ei_tx_drop_nak_packet(packet);
  6434. + ptl_info(packet->ptl, "packet error injection: dropping NAK packet %p\n",
  6435. + packet);
  6436. +
  6437. + return true;
  6438. +}
  6439. +
  6440. +static inline bool __ssh_ptl_should_drop_dsq_packet(struct ssh_packet *packet)
  6441. +{
  6442. + if (likely(!ssh_ptl_should_drop_dsq_packet()))
  6443. + return false;
  6444. +
  6445. + trace_ssam_ei_tx_drop_dsq_packet(packet);
  6446. + ptl_info(packet->ptl,
  6447. + "packet error injection: dropping sequenced data packet %p\n",
  6448. + packet);
  6449. +
  6450. + return true;
  6451. +}
  6452. +
  6453. +static bool ssh_ptl_should_drop_packet(struct ssh_packet *packet)
  6454. +{
  6455. + // ignore packets that don't carry any data (i.e. flush)
  6456. + if (!packet->data || !packet->data_length)
  6457. + return false;
  6458. +
  6459. + switch (packet->data[SSH_MSGOFFSET_FRAME(type)]) {
  6460. + case SSH_FRAME_TYPE_ACK:
  6461. + return __ssh_ptl_should_drop_ack_packet(packet);
  6462. +
  6463. + case SSH_FRAME_TYPE_NAK:
  6464. + return __ssh_ptl_should_drop_nak_packet(packet);
  6465. +
  6466. + case SSH_FRAME_TYPE_DATA_SEQ:
  6467. + return __ssh_ptl_should_drop_dsq_packet(packet);
  6468. +
  6469. + default:
  6470. + return false;
  6471. + }
  6472. +}
  6473. +
  6474. +static inline int ssh_ptl_write_buf(struct ssh_ptl *ptl,
  6475. + struct ssh_packet *packet,
  6476. + const unsigned char *buf,
  6477. + size_t count)
  6478. +{
  6479. + int status;
  6480. +
  6481. + status = ssh_ptl_should_fail_write();
  6482. + if (unlikely(status)) {
  6483. + trace_ssam_ei_tx_fail_write(packet, status);
  6484. + ptl_info(packet->ptl,
  6485. + "packet error injection: simulating transmit error %d, packet %p\n",
  6486. + status, packet);
  6487. +
  6488. + return status;
  6489. + }
  6490. +
  6491. + return serdev_device_write_buf(ptl->serdev, buf, count);
  6492. +}
  6493. +
  6494. +static inline void ssh_ptl_tx_inject_invalid_data(struct ssh_packet *packet)
  6495. +{
  6496. + // ignore packets that don't carry any data (i.e. flush)
  6497. + if (!packet->data || !packet->data_length)
  6498. + return;
  6499. +
  6500. + // only allow sequenced data packets to be modified
  6501. + if (packet->data[SSH_MSGOFFSET_FRAME(type)] != SSH_FRAME_TYPE_DATA_SEQ)
  6502. + return;
  6503. +
  6504. + if (likely(!ssh_ptl_should_corrupt_tx_data()))
  6505. + return;
  6506. +
  6507. + trace_ssam_ei_tx_corrupt_data(packet);
  6508. + ptl_info(packet->ptl,
  6509. + "packet error injection: simulating invalid transmit data on packet %p\n",
  6510. + packet);
  6511. +
  6512. + /*
  6513. + * NB: The value 0xb3 has been chosen more or less randomly so that it
  6514. + * doesn't have any (major) overlap with the SYN bytes (aa 55) and is
  6515. + * non-trivial (i.e. non-zero, non-0xff).
  6516. + */
  6517. + memset(packet->data, 0xb3, packet->data_length);
  6518. +}
  6519. +
  6520. +static inline void ssh_ptl_rx_inject_invalid_syn(struct ssh_ptl *ptl,
  6521. + struct sshp_span *data)
  6522. +{
  6523. + struct sshp_span frame;
  6524. +
  6525. + // check if there actually is something to corrupt
  6526. + if (!sshp_find_syn(data, &frame))
  6527. + return;
  6528. +
  6529. + if (likely(!ssh_ptl_should_corrupt_rx_syn()))
  6530. + return;
  6531. +
  6532. + trace_ssam_ei_rx_corrupt_syn("data_length", data->len);
  6533. +
  6534. + data->ptr[1] = 0xb3; // set second byte of SYN to "random" value
  6535. +}
  6536. +
  6537. +static inline void ssh_ptl_rx_inject_invalid_data(struct ssh_ptl *ptl,
  6538. + struct sshp_span *frame)
  6539. +{
  6540. + size_t payload_len, message_len;
  6541. + struct ssh_frame *sshf;
  6542. +
  6543. + // ignore incomplete messages, will get handled once it's complete
  6544. + if (frame->len < SSH_MESSAGE_LENGTH(0))
  6545. + return;
  6546. +
  6547. + // ignore incomplete messages, part 2
  6548. + payload_len = get_unaligned_le16(&frame->ptr[SSH_MSGOFFSET_FRAME(len)]);
  6549. + message_len = SSH_MESSAGE_LENGTH(payload_len);
  6550. + if (frame->len < message_len)
  6551. + return;
  6552. +
  6553. + if (likely(!ssh_ptl_should_corrupt_rx_data()))
  6554. + return;
  6555. +
  6556. + sshf = (struct ssh_frame *)&frame->ptr[SSH_MSGOFFSET_FRAME(type)];
  6557. + trace_ssam_ei_rx_corrupt_data(sshf);
  6558. +
  6559. + /*
  6560. + * Flip bits in first byte of payload checksum. This is basically
  6561. + * equivalent to a payload/frame data error without us having to worry
  6562. + * about (the, arguably pretty small, probability of) accidental
  6563. + * checksum collisions.
  6564. + */
  6565. + frame->ptr[frame->len - 2] = ~frame->ptr[frame->len - 2];
  6566. +}
  6567. +
  6568. +#else /* CONFIG_SURFACE_SAM_SSH_ERROR_INJECTION */
  6569. +
  6570. +static inline bool ssh_ptl_should_drop_packet(struct ssh_packet *packet)
  6571. +{
  6572. + return false;
  6573. +}
  6574. +
  6575. +static inline int ssh_ptl_write_buf(struct ssh_ptl *ptl,
  6576. + struct ssh_packet *packet,
  6577. + const unsigned char *buf,
  6578. + size_t count)
  6579. +{
  6580. + return serdev_device_write_buf(ptl->serdev, buf, count);
  6581. +}
  6582. +
  6583. +static inline void ssh_ptl_tx_inject_invalid_data(struct ssh_packet *packet)
  6584. +{
  6585. +}
  6586. +
  6587. +static inline void ssh_ptl_rx_inject_invalid_syn(struct ssh_ptl *ptl,
  6588. + struct sshp_span *data)
  6589. +{
  6590. +}
  6591. +
  6592. +static inline void ssh_ptl_rx_inject_invalid_data(struct ssh_ptl *ptl,
  6593. + struct sshp_span *frame)
  6594. +{
  6595. +}
  6596. +
  6597. +#endif /* CONFIG_SURFACE_SAM_SSH_ERROR_INJECTION */
  6598. +
  6599. +
  6600. +static void __ssh_ptl_packet_release(struct kref *kref)
  6601. +{
  6602. + struct ssh_packet *p = to_ssh_packet(kref, refcnt);
  6603. +
  6604. + trace_ssam_packet_release(p);
  6605. +
  6606. + ptl_dbg_cond(p->ptl, "ptl: releasing packet %p\n", p);
  6607. + p->ops->release(p);
  6608. +}
  6609. +
  6610. +static inline void ssh_packet_get(struct ssh_packet *packet)
  6611. +{
  6612. + kref_get(&packet->refcnt);
  6613. +}
  6614. +
  6615. +static inline void ssh_packet_put(struct ssh_packet *packet)
  6616. +{
  6617. + kref_put(&packet->refcnt, __ssh_ptl_packet_release);
  6618. +}
  6619. +
  6620. +
  6621. +static inline u8 ssh_packet_get_seq(struct ssh_packet *packet)
  6622. +{
  6623. + return packet->data[SSH_MSGOFFSET_FRAME(seq)];
  6624. +}
  6625. +
  6626. +
  6627. +struct ssh_packet_args {
  6628. + u8 type;
  6629. + u8 priority;
  6630. + const struct ssh_packet_ops *ops;
  6631. +};
  6632. +
  6633. +static void ssh_packet_init(struct ssh_packet *packet,
  6634. + const struct ssh_packet_args *args)
  6635. +{
  6636. + kref_init(&packet->refcnt);
  6637. +
  6638. + packet->ptl = NULL;
  6639. + INIT_LIST_HEAD(&packet->queue_node);
  6640. + INIT_LIST_HEAD(&packet->pending_node);
  6641. +
  6642. + packet->type = args->type;
  6643. + packet->priority = args->priority;
  6644. + packet->state = 0;
  6645. + packet->timestamp = KTIME_MAX;
  6646. +
  6647. + packet->data_length = 0;
  6648. + packet->data = NULL;
  6649. +
  6650. + packet->ops = args->ops;
  6651. +}
  6652. +
  6653. +
  6654. +static struct ssh_packet *ptl_alloc_ctrl_packet(
  6655. + struct ssh_ptl *ptl, const struct ssh_packet_args *args,
  6656. + gfp_t flags)
  6657. +{
  6658. + struct ssh_packet *packet;
  6659. +
  6660. + // TODO: chache packets
  6661. +
  6662. + packet = kzalloc(sizeof(struct ssh_packet) + SSH_MSG_LEN_CTRL, flags);
  6663. + if (!packet)
  6664. + return NULL;
  6665. +
  6666. + ssh_packet_init(packet, args);
  6667. + packet->data_length = SSH_MSG_LEN_CTRL;
  6668. + packet->data = ((u8 *) packet) + sizeof(struct ssh_packet);
  6669. +
  6670. + return packet;
  6671. +}
  6672. +
  6673. +static void ptl_free_ctrl_packet(struct ssh_packet *p)
  6674. +{
  6675. + // TODO: chache packets
  6676. +
  6677. + kfree(p);
  6678. +}
  6679. +
  6680. +static const struct ssh_packet_ops ssh_ptl_ctrl_packet_ops = {
  6681. + .complete = NULL,
  6682. + .release = ptl_free_ctrl_packet,
  6683. +};
  6684. +
  6685. +
  6686. +static void ssh_ptl_timeout_reaper_mod(struct ssh_ptl *ptl, ktime_t now,
  6687. + ktime_t expires)
  6688. +{
  6689. + unsigned long delta = msecs_to_jiffies(ktime_ms_delta(expires, now));
  6690. + ktime_t aexp = ktime_add(expires, SSH_PTL_PACKET_TIMEOUT_RESOLUTION);
  6691. + ktime_t old;
  6692. +
  6693. + // re-adjust / schedule reaper if it is above resolution delta
  6694. + old = READ_ONCE(ptl->rtx_timeout.expires);
  6695. + while (ktime_before(aexp, old))
  6696. + old = cmpxchg64(&ptl->rtx_timeout.expires, old, expires);
  6697. +
  6698. + // if we updated the reaper expiration, modify work timeout
  6699. + if (old == expires)
  6700. + mod_delayed_work(system_wq, &ptl->rtx_timeout.reaper, delta);
  6701. +}
  6702. +
  6703. +static void ssh_ptl_timeout_start(struct ssh_packet *packet)
  6704. +{
  6705. + struct ssh_ptl *ptl = packet->ptl;
  6706. + ktime_t timestamp = ktime_get_coarse_boottime();
  6707. + ktime_t timeout = ptl->rtx_timeout.timeout;
  6708. +
  6709. + if (test_bit(SSH_PACKET_SF_LOCKED_BIT, &packet->state))
  6710. + return;
  6711. +
  6712. + WRITE_ONCE(packet->timestamp, timestamp);
  6713. + smp_mb__after_atomic();
  6714. +
  6715. + ssh_ptl_timeout_reaper_mod(packet->ptl, timestamp, timestamp + timeout);
  6716. +}
  6717. +
  6718. +
  6719. +static struct list_head *__ssh_ptl_queue_find_entrypoint(struct ssh_packet *p)
  6720. +{
  6721. + struct list_head *head;
  6722. + u8 priority = READ_ONCE(p->priority);
  6723. +
  6724. + /*
  6725. + * We generally assume that there are less control (ACK/NAK) packets and
  6726. + * re-submitted data packets as there are normal data packets (at least
  6727. + * in situations in which many packets are queued; if there aren't many
  6728. + * packets queued the decision on how to iterate should be basically
  6729. + * irrellevant; the number of control/data packets is more or less
  6730. + * limited via the maximum number of pending packets). Thus, when
  6731. + * inserting a control or re-submitted data packet, (determined by their
  6732. + * priority), we search from front to back. Normal data packets are,
  6733. + * usually queued directly at the tail of the queue, so for those search
  6734. + * from back to front.
  6735. + */
  6736. +
  6737. + if (priority > SSH_PACKET_PRIORITY_DATA) {
  6738. + list_for_each(head, &p->ptl->queue.head) {
  6739. + p = list_entry(head, struct ssh_packet, queue_node);
  6740. +
  6741. + if (READ_ONCE(p->priority) < priority)
  6742. + break;
  6743. + }
  6744. + } else {
  6745. + list_for_each_prev(head, &p->ptl->queue.head) {
  6746. + p = list_entry(head, struct ssh_packet, queue_node);
  6747. +
  6748. + if (READ_ONCE(p->priority) >= priority) {
  6749. + head = head->next;
  6750. + break;
  6751. + }
  6752. + }
  6753. + }
  6754. +
  6755. +
  6756. + return head;
  6757. +}
  6758. +
  6759. +static int ssh_ptl_queue_push(struct ssh_packet *packet)
  6760. +{
  6761. + struct ssh_ptl *ptl = packet->ptl;
  6762. + struct list_head *head;
  6763. +
  6764. + spin_lock(&ptl->queue.lock);
  6765. +
  6766. + if (test_bit(SSH_PTL_SF_SHUTDOWN_BIT, &ptl->state)) {
  6767. + spin_unlock(&ptl->queue.lock);
  6768. + return -ESHUTDOWN;
  6769. + }
  6770. +
  6771. + // avoid further transitions when cancelling/completing
  6772. + if (test_bit(SSH_PACKET_SF_LOCKED_BIT, &packet->state)) {
  6773. + spin_unlock(&ptl->queue.lock);
  6774. + return -EINVAL;
  6775. + }
  6776. +
  6777. + // if this packet has already been queued, do not add it
  6778. + if (test_and_set_bit(SSH_PACKET_SF_QUEUED_BIT, &packet->state)) {
  6779. + spin_unlock(&ptl->queue.lock);
  6780. + return -EALREADY;
  6781. + }
  6782. +
  6783. + head = __ssh_ptl_queue_find_entrypoint(packet);
  6784. +
  6785. + ssh_packet_get(packet);
  6786. + list_add_tail(&packet->queue_node, &ptl->queue.head);
  6787. +
  6788. + spin_unlock(&ptl->queue.lock);
  6789. + return 0;
  6790. +}
  6791. +
  6792. +static void ssh_ptl_queue_remove(struct ssh_packet *packet)
  6793. +{
  6794. + struct ssh_ptl *ptl = packet->ptl;
  6795. + bool remove;
  6796. +
  6797. + spin_lock(&ptl->queue.lock);
  6798. +
  6799. + remove = test_and_clear_bit(SSH_PACKET_SF_QUEUED_BIT, &packet->state);
  6800. + if (remove)
  6801. + list_del(&packet->queue_node);
  6802. +
  6803. + spin_unlock(&ptl->queue.lock);
  6804. +
  6805. + if (remove)
  6806. + ssh_packet_put(packet);
  6807. +}
  6808. +
  6809. +
  6810. +static void ssh_ptl_pending_push(struct ssh_packet *packet)
  6811. +{
  6812. + struct ssh_ptl *ptl = packet->ptl;
  6813. +
  6814. + spin_lock(&ptl->pending.lock);
  6815. +
  6816. + // if we are cancelling/completing this packet, do not add it
  6817. + if (test_bit(SSH_PACKET_SF_LOCKED_BIT, &packet->state)) {
  6818. + spin_unlock(&ptl->pending.lock);
  6819. + return;
  6820. + }
  6821. +
  6822. + // in case it is already pending (e.g. re-submission), do not add it
  6823. + if (test_and_set_bit(SSH_PACKET_SF_PENDING_BIT, &packet->state)) {
  6824. + spin_unlock(&ptl->pending.lock);
  6825. + return;
  6826. + }
  6827. +
  6828. + atomic_inc(&ptl->pending.count);
  6829. + ssh_packet_get(packet);
  6830. + list_add_tail(&packet->pending_node, &ptl->pending.head);
  6831. +
  6832. + spin_unlock(&ptl->pending.lock);
  6833. +}
  6834. +
  6835. +static void ssh_ptl_pending_remove(struct ssh_packet *packet)
  6836. +{
  6837. + struct ssh_ptl *ptl = packet->ptl;
  6838. + bool remove;
  6839. +
  6840. + spin_lock(&ptl->pending.lock);
  6841. +
  6842. + remove = test_and_clear_bit(SSH_PACKET_SF_PENDING_BIT, &packet->state);
  6843. + if (remove) {
  6844. + list_del(&packet->pending_node);
  6845. + atomic_dec(&ptl->pending.count);
  6846. + }
  6847. +
  6848. + spin_unlock(&ptl->pending.lock);
  6849. +
  6850. + if (remove)
  6851. + ssh_packet_put(packet);
  6852. +}
  6853. +
  6854. +
  6855. +static void __ssh_ptl_complete(struct ssh_packet *p, int status)
  6856. +{
  6857. + struct ssh_ptl *ptl = READ_ONCE(p->ptl);
  6858. +
  6859. + trace_ssam_packet_complete(p, status);
  6860. +
  6861. + ptl_dbg_cond(ptl, "ptl: completing packet %p\n", p);
  6862. + if (p->ops->complete)
  6863. + p->ops->complete(p, status);
  6864. +}
  6865. +
  6866. +static void ssh_ptl_remove_and_complete(struct ssh_packet *p, int status)
  6867. +{
  6868. + /*
  6869. + * A call to this function should in general be preceeded by
  6870. + * set_bit(SSH_PACKET_SF_LOCKED_BIT, &p->flags) to avoid re-adding the
  6871. + * packet to the structures it's going to be removed from.
  6872. + *
  6873. + * The set_bit call does not need explicit memory barriers as the
  6874. + * implicit barrier of the test_and_set_bit call below ensure that the
  6875. + * flag is visible before we actually attempt to remove the packet.
  6876. + */
  6877. +
  6878. + if (test_and_set_bit(SSH_PACKET_SF_COMPLETED_BIT, &p->state))
  6879. + return;
  6880. +
  6881. + ssh_ptl_queue_remove(p);
  6882. + ssh_ptl_pending_remove(p);
  6883. +
  6884. + __ssh_ptl_complete(p, status);
  6885. +}
  6886. +
  6887. +
  6888. +static bool ssh_ptl_tx_can_process(struct ssh_packet *packet)
  6889. +{
  6890. + struct ssh_ptl *ptl = packet->ptl;
  6891. +
  6892. + if (packet->type & SSH_PACKET_TY_FLUSH)
  6893. + return !atomic_read(&ptl->pending.count);
  6894. +
  6895. + // we can alwas process non-blocking packets
  6896. + if (!(packet->type & SSH_PACKET_TY_BLOCKING))
  6897. + return true;
  6898. +
  6899. + // if we are already waiting for this packet, send it again
  6900. + if (test_bit(SSH_PACKET_SF_PENDING_BIT, &packet->state))
  6901. + return true;
  6902. +
  6903. + // otherwise: check if we have the capacity to send
  6904. + return atomic_read(&ptl->pending.count) < SSH_PTL_MAX_PENDING;
  6905. +}
  6906. +
  6907. +static struct ssh_packet *ssh_ptl_tx_pop(struct ssh_ptl *ptl)
  6908. +{
  6909. + struct ssh_packet *packet = ERR_PTR(-ENOENT);
  6910. + struct ssh_packet *p, *n;
  6911. +
  6912. + spin_lock(&ptl->queue.lock);
  6913. + list_for_each_entry_safe(p, n, &ptl->queue.head, queue_node) {
  6914. + /*
  6915. + * If we are cancelling or completing this packet, ignore it.
  6916. + * It's going to be removed from this queue shortly.
  6917. + */
  6918. + if (test_bit(SSH_PACKET_SF_LOCKED_BIT, &p->state))
  6919. + continue;
  6920. +
  6921. + /*
  6922. + * Packets should be ordered non-blocking/to-be-resent first.
  6923. + * If we cannot process this packet, assume that we can't
  6924. + * process any following packet either and abort.
  6925. + */
  6926. + if (!ssh_ptl_tx_can_process(p)) {
  6927. + packet = ERR_PTR(-EBUSY);
  6928. + break;
  6929. + }
  6930. +
  6931. + /*
  6932. + * We are allowed to change the state now. Remove it from the
  6933. + * queue and mark it as being transmitted. Note that we cannot
  6934. + * add it to the set of pending packets yet, as queue locks must
  6935. + * always be acquired before packet locks (otherwise we might
  6936. + * run into a deadlock).
  6937. + */
  6938. +
  6939. + list_del(&p->queue_node);
  6940. +
  6941. + /*
  6942. + * Ensure that the "queued" bit gets cleared after setting the
  6943. + * "transmitting" bit to guaranteee non-zero flags.
  6944. + */
  6945. + set_bit(SSH_PACKET_SF_TRANSMITTING_BIT, &p->state);
  6946. + smp_mb__before_atomic();
  6947. + clear_bit(SSH_PACKET_SF_QUEUED_BIT, &p->state);
  6948. +
  6949. + packet = p;
  6950. + break;
  6951. + }
  6952. + spin_unlock(&ptl->queue.lock);
  6953. +
  6954. + return packet;
  6955. +}
  6956. +
  6957. +static struct ssh_packet *ssh_ptl_tx_next(struct ssh_ptl *ptl)
  6958. +{
  6959. + struct ssh_packet *p;
  6960. +
  6961. + p = ssh_ptl_tx_pop(ptl);
  6962. + if (IS_ERR(p))
  6963. + return p;
  6964. +
  6965. + if (p->type & SSH_PACKET_TY_SEQUENCED) {
  6966. + ptl_dbg(ptl, "ptl: transmitting sequenced packet %p\n", p);
  6967. + ssh_ptl_pending_push(p);
  6968. + ssh_ptl_timeout_start(p);
  6969. + } else {
  6970. + ptl_dbg(ptl, "ptl: transmitting non-sequenced packet %p\n", p);
  6971. + }
  6972. +
  6973. + /*
  6974. + * Update number of tries. This directly influences the priority in case
  6975. + * the packet is re-submitted (e.g. via timeout/NAK). Note that this is
  6976. + * the only place where we update the priority in-flight. As this runs
  6977. + * only on the tx-thread, this read-modify-write procedure is safe.
  6978. + */
  6979. + WRITE_ONCE(p->priority, READ_ONCE(p->priority) + 1);
  6980. +
  6981. + return p;
  6982. +}
  6983. +
  6984. +static void ssh_ptl_tx_compl_success(struct ssh_packet *packet)
  6985. +{
  6986. + struct ssh_ptl *ptl = packet->ptl;
  6987. +
  6988. + ptl_dbg(ptl, "ptl: successfully transmitted packet %p\n", packet);
  6989. +
  6990. + /*
  6991. + * Transition to state to "transmitted". Ensure that the flags never get
  6992. + * zero with barrier.
  6993. + */
  6994. + set_bit(SSH_PACKET_SF_TRANSMITTED_BIT, &packet->state);
  6995. + smp_mb__before_atomic();
  6996. + clear_bit(SSH_PACKET_SF_TRANSMITTING_BIT, &packet->state);
  6997. +
  6998. + // if the packet is unsequenced, we're done: lock and complete
  6999. + if (!(packet->type & SSH_PACKET_TY_SEQUENCED)) {
  7000. + set_bit(SSH_PACKET_SF_LOCKED_BIT, &packet->state);
  7001. + ssh_ptl_remove_and_complete(packet, 0);
  7002. + }
  7003. +
  7004. + /*
  7005. + * Notify that a packet transmission has finished. In general we're only
  7006. + * waiting for one packet (if any), so wake_up_all should be fine.
  7007. + */
  7008. + wake_up_all(&ptl->tx.packet_wq);
  7009. +}
  7010. +
  7011. +static void ssh_ptl_tx_compl_error(struct ssh_packet *packet, int status)
  7012. +{
  7013. + /*
  7014. + * Transmission failure: Lock the packet and try to complete it. Ensure
  7015. + * that the flags never get zero with barrier.
  7016. + */
  7017. + set_bit(SSH_PACKET_SF_LOCKED_BIT, &packet->state);
  7018. + smp_mb__before_atomic();
  7019. + clear_bit(SSH_PACKET_SF_TRANSMITTING_BIT, &packet->state);
  7020. +
  7021. + ptl_err(packet->ptl, "ptl: transmission error: %d\n", status);
  7022. + ptl_dbg(packet->ptl, "ptl: failed to transmit packet: %p\n", packet);
  7023. +
  7024. + ssh_ptl_remove_and_complete(packet, status);
  7025. +
  7026. + /*
  7027. + * Notify that a packet transmission has finished. In general we're only
  7028. + * waiting for one packet (if any), so wake_up_all should be fine.
  7029. + */
  7030. + wake_up_all(&packet->ptl->tx.packet_wq);
  7031. +}
  7032. +
  7033. +static void ssh_ptl_tx_threadfn_wait(struct ssh_ptl *ptl)
  7034. +{
  7035. + wait_event_interruptible(ptl->tx.thread_wq,
  7036. + READ_ONCE(ptl->tx.thread_signal) || kthread_should_stop());
  7037. + WRITE_ONCE(ptl->tx.thread_signal, false);
  7038. +}
  7039. +
  7040. +static int ssh_ptl_tx_threadfn(void *data)
  7041. +{
  7042. + struct ssh_ptl *ptl = data;
  7043. +
  7044. + while (!kthread_should_stop()) {
  7045. + unsigned char *buf;
  7046. + bool drop = false;
  7047. + size_t len = 0;
  7048. + int status = 0;
  7049. +
  7050. + // if we don't have a packet, get the next and add it to pending
  7051. + if (IS_ERR_OR_NULL(ptl->tx.packet)) {
  7052. + ptl->tx.packet = ssh_ptl_tx_next(ptl);
  7053. + ptl->tx.offset = 0;
  7054. +
  7055. + // if no packet is available, we are done
  7056. + if (IS_ERR(ptl->tx.packet)) {
  7057. + ssh_ptl_tx_threadfn_wait(ptl);
  7058. + continue;
  7059. + }
  7060. + }
  7061. +
  7062. + // error injection: drop packet to simulate transmission problem
  7063. + if (ptl->tx.offset == 0)
  7064. + drop = ssh_ptl_should_drop_packet(ptl->tx.packet);
  7065. +
  7066. + // error injection: simulate invalid packet data
  7067. + if (ptl->tx.offset == 0 && !drop)
  7068. + ssh_ptl_tx_inject_invalid_data(ptl->tx.packet);
  7069. +
  7070. + // flush-packets don't have any data
  7071. + if (likely(ptl->tx.packet->data && !drop)) {
  7072. + buf = ptl->tx.packet->data + ptl->tx.offset;
  7073. + len = ptl->tx.packet->data_length - ptl->tx.offset;
  7074. +
  7075. + ptl_dbg(ptl, "tx: sending data (length: %zu)\n", len);
  7076. + print_hex_dump_debug("tx: ", DUMP_PREFIX_OFFSET, 16, 1,
  7077. + buf, len, false);
  7078. +
  7079. + status = ssh_ptl_write_buf(ptl, ptl->tx.packet, buf, len);
  7080. + }
  7081. +
  7082. + if (status < 0) {
  7083. + // complete packet with error
  7084. + ssh_ptl_tx_compl_error(ptl->tx.packet, status);
  7085. + ssh_packet_put(ptl->tx.packet);
  7086. + ptl->tx.packet = NULL;
  7087. +
  7088. + } else if (status == len) {
  7089. + // complete packet and/or mark as transmitted
  7090. + ssh_ptl_tx_compl_success(ptl->tx.packet);
  7091. + ssh_packet_put(ptl->tx.packet);
  7092. + ptl->tx.packet = NULL;
  7093. +
  7094. + } else { // need more buffer space
  7095. + ptl->tx.offset += status;
  7096. + ssh_ptl_tx_threadfn_wait(ptl);
  7097. + }
  7098. + }
  7099. +
  7100. + // cancel active packet before we actually stop
  7101. + if (!IS_ERR_OR_NULL(ptl->tx.packet)) {
  7102. + ssh_ptl_tx_compl_error(ptl->tx.packet, -ESHUTDOWN);
  7103. + ssh_packet_put(ptl->tx.packet);
  7104. + ptl->tx.packet = NULL;
  7105. + }
  7106. +
  7107. + return 0;
  7108. +}
  7109. +
  7110. +static inline void ssh_ptl_tx_wakeup(struct ssh_ptl *ptl, bool force)
  7111. +{
  7112. + if (test_bit(SSH_PTL_SF_SHUTDOWN_BIT, &ptl->state))
  7113. + return;
  7114. +
  7115. + if (force || atomic_read(&ptl->pending.count) < SSH_PTL_MAX_PENDING) {
  7116. + WRITE_ONCE(ptl->tx.thread_signal, true);
  7117. + smp_mb__after_atomic();
  7118. + wake_up(&ptl->tx.thread_wq);
  7119. + }
  7120. +}
  7121. +
  7122. +static int ssh_ptl_tx_start(struct ssh_ptl *ptl)
  7123. +{
  7124. + ptl->tx.thread = kthread_run(ssh_ptl_tx_threadfn, ptl, "surface-sh-tx");
  7125. + if (IS_ERR(ptl->tx.thread))
  7126. + return PTR_ERR(ptl->tx.thread);
  7127. +
  7128. + return 0;
  7129. +}
  7130. +
  7131. +static int ssh_ptl_tx_stop(struct ssh_ptl *ptl)
  7132. +{
  7133. + int status = 0;
  7134. +
  7135. + if (ptl->tx.thread) {
  7136. + status = kthread_stop(ptl->tx.thread);
  7137. + ptl->tx.thread = NULL;
  7138. + }
  7139. +
  7140. + return status;
  7141. +}
  7142. +
  7143. +
  7144. +static struct ssh_packet *ssh_ptl_ack_pop(struct ssh_ptl *ptl, u8 seq_id)
  7145. +{
  7146. + struct ssh_packet *packet = ERR_PTR(-ENOENT);
  7147. + struct ssh_packet *p, *n;
  7148. +
  7149. + spin_lock(&ptl->pending.lock);
  7150. + list_for_each_entry_safe(p, n, &ptl->pending.head, pending_node) {
  7151. + /*
  7152. + * We generally expect packets to be in order, so first packet
  7153. + * to be added to pending is first to be sent, is first to be
  7154. + * ACKed.
  7155. + */
  7156. + if (unlikely(ssh_packet_get_seq(p) != seq_id))
  7157. + continue;
  7158. +
  7159. + /*
  7160. + * In case we receive an ACK while handling a transmission error
  7161. + * completion. The packet will be removed shortly.
  7162. + */
  7163. + if (unlikely(test_bit(SSH_PACKET_SF_LOCKED_BIT, &p->state))) {
  7164. + packet = ERR_PTR(-EPERM);
  7165. + break;
  7166. + }
  7167. +
  7168. + /*
  7169. + * Mark packet as ACKed and remove it from pending. Ensure that
  7170. + * the flags never get zero with barrier.
  7171. + */
  7172. + set_bit(SSH_PACKET_SF_ACKED_BIT, &p->state);
  7173. + smp_mb__before_atomic();
  7174. + clear_bit(SSH_PACKET_SF_PENDING_BIT, &p->state);
  7175. +
  7176. + atomic_dec(&ptl->pending.count);
  7177. + list_del(&p->pending_node);
  7178. + packet = p;
  7179. +
  7180. + break;
  7181. + }
  7182. + spin_unlock(&ptl->pending.lock);
  7183. +
  7184. + return packet;
  7185. +}
  7186. +
  7187. +static void ssh_ptl_wait_until_transmitted(struct ssh_packet *packet)
  7188. +{
  7189. + wait_event(packet->ptl->tx.packet_wq,
  7190. + test_bit(SSH_PACKET_SF_TRANSMITTED_BIT, &packet->state)
  7191. + || test_bit(SSH_PACKET_SF_LOCKED_BIT, &packet->state));
  7192. +}
  7193. +
  7194. +static void ssh_ptl_acknowledge(struct ssh_ptl *ptl, u8 seq)
  7195. +{
  7196. + struct ssh_packet *p;
  7197. + int status = 0;
  7198. +
  7199. + p = ssh_ptl_ack_pop(ptl, seq);
  7200. + if (IS_ERR(p)) {
  7201. + if (PTR_ERR(p) == -ENOENT) {
  7202. + /*
  7203. + * The packet has not been found in the set of pending
  7204. + * packets.
  7205. + */
  7206. + ptl_warn(ptl, "ptl: received ACK for non-pending"
  7207. + " packet\n");
  7208. + } else {
  7209. + /*
  7210. + * The packet is pending, but we are not allowed to take
  7211. + * it because it has been locked.
  7212. + */
  7213. + }
  7214. + return;
  7215. + }
  7216. +
  7217. + ptl_dbg(ptl, "ptl: received ACK for packet %p\n", p);
  7218. +
  7219. + /*
  7220. + * It is possible that the packet has been transmitted, but the state
  7221. + * has not been updated from "transmitting" to "transmitted" yet.
  7222. + * In that case, we need to wait for this transition to occur in order
  7223. + * to determine between success or failure.
  7224. + */
  7225. + if (test_bit(SSH_PACKET_SF_TRANSMITTING_BIT, &p->state))
  7226. + ssh_ptl_wait_until_transmitted(p);
  7227. +
  7228. + /*
  7229. + * The packet will already be locked in case of a transmission error or
  7230. + * cancellation. Let the transmitter or cancellation issuer complete the
  7231. + * packet.
  7232. + */
  7233. + if (unlikely(test_and_set_bit(SSH_PACKET_SF_LOCKED_BIT, &p->state))) {
  7234. + ssh_packet_put(p);
  7235. + return;
  7236. + }
  7237. +
  7238. + if (unlikely(!test_bit(SSH_PACKET_SF_TRANSMITTED_BIT, &p->state))) {
  7239. + ptl_err(ptl, "ptl: received ACK before packet had been fully"
  7240. + " transmitted\n");
  7241. + status = -EREMOTEIO;
  7242. + }
  7243. +
  7244. + ssh_ptl_remove_and_complete(p, status);
  7245. + ssh_packet_put(p);
  7246. +
  7247. + ssh_ptl_tx_wakeup(ptl, false);
  7248. +}
  7249. +
  7250. +
  7251. +static int ssh_ptl_submit(struct ssh_ptl *ptl, struct ssh_packet *packet)
  7252. +{
  7253. + int status;
  7254. +
  7255. + trace_ssam_packet_submit(packet);
  7256. +
  7257. + // validate packet fields
  7258. + if (packet->type & SSH_PACKET_TY_FLUSH) {
  7259. + if (packet->data || (packet->type & SSH_PACKET_TY_SEQUENCED))
  7260. + return -EINVAL;
  7261. + } else if (!packet->data) {
  7262. + return -EINVAL;
  7263. + }
  7264. +
  7265. + /*
  7266. + * This function is currently not intended for re-submission. The ptl
  7267. + * reference only gets set on the first submission. After the first
  7268. + * submission, it has to be read-only.
  7269. + *
  7270. + * Use cmpxchg to ensure safety with regards to ssh_ptl_cancel and
  7271. + * re-entry, where we can't guarantee that the packet has been submitted
  7272. + * yet.
  7273. + *
  7274. + * The implicit barrier of cmpxchg is paired with barrier in
  7275. + * ssh_ptl_cancel to guarantee cancelation in case the packet has never
  7276. + * been submitted or is currently being submitted.
  7277. + */
  7278. + if (cmpxchg(&packet->ptl, NULL, ptl) != NULL)
  7279. + return -EALREADY;
  7280. +
  7281. + status = ssh_ptl_queue_push(packet);
  7282. + if (status)
  7283. + return status;
  7284. +
  7285. + ssh_ptl_tx_wakeup(ptl, !(packet->type & SSH_PACKET_TY_BLOCKING));
  7286. + return 0;
  7287. +}
  7288. +
  7289. +static void __ssh_ptl_resubmit(struct ssh_packet *packet)
  7290. +{
  7291. + struct list_head *head;
  7292. +
  7293. + trace_ssam_packet_resubmit(packet);
  7294. +
  7295. + spin_lock(&packet->ptl->queue.lock);
  7296. +
  7297. + // if this packet has already been queued, do not add it
  7298. + if (test_and_set_bit(SSH_PACKET_SF_QUEUED_BIT, &packet->state)) {
  7299. + spin_unlock(&packet->ptl->queue.lock);
  7300. + return;
  7301. + }
  7302. +
  7303. + // find first node with lower priority
  7304. + head = __ssh_ptl_queue_find_entrypoint(packet);
  7305. +
  7306. + WRITE_ONCE(packet->timestamp, KTIME_MAX);
  7307. + smp_mb__after_atomic();
  7308. +
  7309. + // add packet
  7310. + ssh_packet_get(packet);
  7311. + list_add_tail(&packet->queue_node, head);
  7312. +
  7313. + spin_unlock(&packet->ptl->queue.lock);
  7314. +}
  7315. +
  7316. +static void ssh_ptl_resubmit_pending(struct ssh_ptl *ptl)
  7317. +{
  7318. + struct ssh_packet *p;
  7319. + bool resub = false;
  7320. + u8 try;
  7321. +
  7322. + /*
  7323. + * Note: We deliberately do not remove/attempt to cancel and complete
  7324. + * packets that are out of tires in this function. The packet will be
  7325. + * eventually canceled and completed by the timeout. Removing the packet
  7326. + * here could lead to overly eager cancelation if the packet has not
  7327. + * been re-transmitted yet but the tries-counter already updated (i.e
  7328. + * ssh_ptl_tx_next removed the packet from the queue and updated the
  7329. + * counter, but re-transmission for the last try has not actually
  7330. + * started yet).
  7331. + */
  7332. +
  7333. + spin_lock(&ptl->pending.lock);
  7334. +
  7335. + // re-queue all pending packets
  7336. + list_for_each_entry(p, &ptl->pending.head, pending_node) {
  7337. + // avoid further transitions if locked
  7338. + if (test_bit(SSH_PACKET_SF_LOCKED_BIT, &p->state))
  7339. + continue;
  7340. +
  7341. + // do not re-schedule if packet is out of tries
  7342. + try = ssh_packet_priority_get_try(READ_ONCE(p->priority));
  7343. + if (try >= SSH_PTL_MAX_PACKET_TRIES)
  7344. + continue;
  7345. +
  7346. + resub = true;
  7347. + __ssh_ptl_resubmit(p);
  7348. + }
  7349. +
  7350. + spin_unlock(&ptl->pending.lock);
  7351. +
  7352. + ssh_ptl_tx_wakeup(ptl, resub);
  7353. +}
  7354. +
  7355. +static void ssh_ptl_cancel(struct ssh_packet *p)
  7356. +{
  7357. + if (test_and_set_bit(SSH_PACKET_SF_CANCELED_BIT, &p->state))
  7358. + return;
  7359. +
  7360. + trace_ssam_packet_cancel(p);
  7361. +
  7362. + /*
  7363. + * Lock packet and commit with memory barrier. If this packet has
  7364. + * already been locked, it's going to be removed and completed by
  7365. + * another party, which should have precedence.
  7366. + */
  7367. + if (test_and_set_bit(SSH_PACKET_SF_LOCKED_BIT, &p->state))
  7368. + return;
  7369. +
  7370. + /*
  7371. + * By marking the packet as locked and employing the implicit memory
  7372. + * barrier of test_and_set_bit, we have guaranteed that, at this point,
  7373. + * the packet cannot be added to the queue any more.
  7374. + *
  7375. + * In case the packet has never been submitted, packet->ptl is NULL. If
  7376. + * the packet is currently being submitted, packet->ptl may be NULL or
  7377. + * non-NULL. Due marking the packet as locked above and committing with
  7378. + * the memory barrier, we have guaranteed that, if packet->ptl is NULL,
  7379. + * the packet will never be added to the queue. If packet->ptl is
  7380. + * non-NULL, we don't have any guarantees.
  7381. + */
  7382. +
  7383. + if (READ_ONCE(p->ptl)) {
  7384. + ssh_ptl_remove_and_complete(p, -ECANCELED);
  7385. + ssh_ptl_tx_wakeup(p->ptl, false);
  7386. + } else if (!test_and_set_bit(SSH_PACKET_SF_COMPLETED_BIT, &p->state)) {
  7387. + __ssh_ptl_complete(p, -ECANCELED);
  7388. + }
  7389. +}
  7390. +
  7391. +
  7392. +static ktime_t ssh_packet_get_expiration(struct ssh_packet *p, ktime_t timeout)
  7393. +{
  7394. + ktime_t timestamp = READ_ONCE(p->timestamp);
  7395. +
  7396. + if (timestamp != KTIME_MAX)
  7397. + return ktime_add(timestamp, timeout);
  7398. + else
  7399. + return KTIME_MAX;
  7400. +}
  7401. +
  7402. +static void ssh_ptl_timeout_reap(struct work_struct *work)
  7403. +{
  7404. + struct ssh_ptl *ptl = to_ssh_ptl(work, rtx_timeout.reaper.work);
  7405. + struct ssh_packet *p, *n;
  7406. + LIST_HEAD(claimed);
  7407. + ktime_t now = ktime_get_coarse_boottime();
  7408. + ktime_t timeout = ptl->rtx_timeout.timeout;
  7409. + ktime_t next = KTIME_MAX;
  7410. + bool resub = false;
  7411. +
  7412. + trace_ssam_ptl_timeout_reap("pending", atomic_read(&ptl->pending.count));
  7413. +
  7414. + /*
  7415. + * Mark reaper as "not pending". This is done before checking any
  7416. + * packets to avoid lost-update type problems.
  7417. + */
  7418. + WRITE_ONCE(ptl->rtx_timeout.expires, KTIME_MAX);
  7419. + smp_mb__after_atomic();
  7420. +
  7421. + spin_lock(&ptl->pending.lock);
  7422. +
  7423. + list_for_each_entry_safe(p, n, &ptl->pending.head, pending_node) {
  7424. + ktime_t expires = ssh_packet_get_expiration(p, timeout);
  7425. + u8 try;
  7426. +
  7427. + /*
  7428. + * Check if the timeout hasn't expired yet. Find out next
  7429. + * expiration date to be handled after this run.
  7430. + */
  7431. + if (ktime_after(expires, now)) {
  7432. + next = ktime_before(expires, next) ? expires : next;
  7433. + continue;
  7434. + }
  7435. +
  7436. + // avoid further transitions if locked
  7437. + if (test_bit(SSH_PACKET_SF_LOCKED_BIT, &p->state))
  7438. + continue;
  7439. +
  7440. + trace_ssam_packet_timeout(p);
  7441. +
  7442. + // check if we still have some tries left
  7443. + try = ssh_packet_priority_get_try(READ_ONCE(p->priority));
  7444. + if (likely(try < SSH_PTL_MAX_PACKET_TRIES)) {
  7445. + resub = true;
  7446. + __ssh_ptl_resubmit(p);
  7447. + continue;
  7448. + }
  7449. +
  7450. + // no more tries left: cancel the packet
  7451. +
  7452. + // if someone else has locked the packet already, don't use it
  7453. + if (test_and_set_bit(SSH_PACKET_SF_LOCKED_BIT, &p->state))
  7454. + continue;
  7455. +
  7456. + /*
  7457. + * We have now marked the packet as locked. Thus it cannot be
  7458. + * added to the pending list again after we've removed it here.
  7459. + * We can therefore re-use the pending_node of this packet
  7460. + * temporarily.
  7461. + */
  7462. +
  7463. + clear_bit(SSH_PACKET_SF_PENDING_BIT, &p->state);
  7464. +
  7465. + atomic_dec(&ptl->pending.count);
  7466. + list_del(&p->pending_node);
  7467. +
  7468. + list_add_tail(&p->pending_node, &claimed);
  7469. + }
  7470. +
  7471. + spin_unlock(&ptl->pending.lock);
  7472. +
  7473. + // cancel and complete the packet
  7474. + list_for_each_entry_safe(p, n, &claimed, pending_node) {
  7475. + if (!test_and_set_bit(SSH_PACKET_SF_COMPLETED_BIT, &p->state)) {
  7476. + ssh_ptl_queue_remove(p);
  7477. + __ssh_ptl_complete(p, -ETIMEDOUT);
  7478. + }
  7479. +
  7480. + // drop the reference we've obtained by removing it from pending
  7481. + list_del(&p->pending_node);
  7482. + ssh_packet_put(p);
  7483. + }
  7484. +
  7485. + // ensure that reaper doesn't run again immediately
  7486. + next = max(next, ktime_add(now, SSH_PTL_PACKET_TIMEOUT_RESOLUTION));
  7487. + if (next != KTIME_MAX)
  7488. + ssh_ptl_timeout_reaper_mod(ptl, now, next);
  7489. +
  7490. + // force-wakeup to properly handle re-transmits if we've re-submitted
  7491. + ssh_ptl_tx_wakeup(ptl, resub);
  7492. +}
  7493. +
  7494. +
  7495. +static bool ssh_ptl_rx_blacklist_check(struct ssh_ptl *ptl, u8 seq)
  7496. +{
  7497. + int i;
  7498. +
  7499. + // check if SEQ is blacklisted
  7500. + for (i = 0; i < ARRAY_SIZE(ptl->rx.blacklist.seqs); i++) {
  7501. + if (likely(ptl->rx.blacklist.seqs[i] != seq))
  7502. + continue;
  7503. +
  7504. + ptl_dbg(ptl, "ptl: ignoring repeated data packet\n");
  7505. + return true;
  7506. + }
  7507. +
  7508. + // update blacklist
  7509. + ptl->rx.blacklist.seqs[ptl->rx.blacklist.offset] = seq;
  7510. + ptl->rx.blacklist.offset = (ptl->rx.blacklist.offset + 1)
  7511. + % ARRAY_SIZE(ptl->rx.blacklist.seqs);
  7512. +
  7513. + return false;
  7514. +}
  7515. +
  7516. +static void ssh_ptl_rx_dataframe(struct ssh_ptl *ptl,
  7517. + const struct ssh_frame *frame,
  7518. + const struct sshp_span *payload)
  7519. +{
  7520. + if (ssh_ptl_rx_blacklist_check(ptl, frame->seq))
  7521. + return;
  7522. +
  7523. + ptl->ops.data_received(ptl, payload);
  7524. +}
  7525. +
  7526. +static void ssh_ptl_send_ack(struct ssh_ptl *ptl, u8 seq)
  7527. +{
  7528. + struct ssh_packet_args args;
  7529. + struct ssh_packet *packet;
  7530. + struct msgbuf msgb;
  7531. +
  7532. + args.type = 0;
  7533. + args.priority = SSH_PACKET_PRIORITY(ACK, 0);
  7534. + args.ops = &ssh_ptl_ctrl_packet_ops;
  7535. +
  7536. + packet = ptl_alloc_ctrl_packet(ptl, &args, GFP_KERNEL);
  7537. + if (!packet) {
  7538. + ptl_err(ptl, "ptl: failed to allocate ACK packet\n");
  7539. + return;
  7540. + }
  7541. +
  7542. + msgb_init(&msgb, packet->data, packet->data_length);
  7543. + msgb_push_ack(&msgb, seq);
  7544. + packet->data_length = msgb_bytes_used(&msgb);
  7545. +
  7546. + ssh_ptl_submit(ptl, packet);
  7547. + ssh_packet_put(packet);
  7548. +}
  7549. +
  7550. +static void ssh_ptl_send_nak(struct ssh_ptl *ptl)
  7551. +{
  7552. + struct ssh_packet_args args;
  7553. + struct ssh_packet *packet;
  7554. + struct msgbuf msgb;
  7555. +
  7556. + args.type = 0;
  7557. + args.priority = SSH_PACKET_PRIORITY(NAK, 0);
  7558. + args.ops = &ssh_ptl_ctrl_packet_ops;
  7559. +
  7560. + packet = ptl_alloc_ctrl_packet(ptl, &args, GFP_KERNEL);
  7561. + if (!packet) {
  7562. + ptl_err(ptl, "ptl: failed to allocate NAK packet\n");
  7563. + return;
  7564. + }
  7565. +
  7566. + msgb_init(&msgb, packet->data, packet->data_length);
  7567. + msgb_push_nak(&msgb);
  7568. + packet->data_length = msgb_bytes_used(&msgb);
  7569. +
  7570. + ssh_ptl_submit(ptl, packet);
  7571. + ssh_packet_put(packet);
  7572. +}
  7573. +
  7574. +static size_t ssh_ptl_rx_eval(struct ssh_ptl *ptl, struct sshp_span *source)
  7575. +{
  7576. + struct ssh_frame *frame;
  7577. + struct sshp_span payload;
  7578. + struct sshp_span aligned;
  7579. + bool syn_found;
  7580. + int status;
  7581. +
  7582. + // error injection: modify data to simulate corrupt SYN bytes
  7583. + ssh_ptl_rx_inject_invalid_syn(ptl, source);
  7584. +
  7585. + // find SYN
  7586. + syn_found = sshp_find_syn(source, &aligned);
  7587. +
  7588. + if (unlikely(aligned.ptr - source->ptr) > 0) {
  7589. + ptl_warn(ptl, "rx: parser: invalid start of frame, skipping\n");
  7590. +
  7591. + /*
  7592. + * Notes:
  7593. + * - This might send multiple NAKs in case the communication
  7594. + * starts with an invalid SYN and is broken down into multiple
  7595. + * pieces. This should generally be handled fine, we just
  7596. + * might receive duplicate data in this case, which is
  7597. + * detected when handling data frames.
  7598. + * - This path will also be executed on invalid CRCs: When an
  7599. + * invalid CRC is encountered, the code below will skip data
  7600. + * until direclty after the SYN. This causes the search for
  7601. + * the next SYN, which is generally not placed directly after
  7602. + * the last one.
  7603. + */
  7604. + ssh_ptl_send_nak(ptl);
  7605. + }
  7606. +
  7607. + if (unlikely(!syn_found))
  7608. + return aligned.ptr - source->ptr;
  7609. +
  7610. + // error injection: modify data to simulate corruption
  7611. + ssh_ptl_rx_inject_invalid_data(ptl, &aligned);
  7612. +
  7613. + // parse and validate frame
  7614. + status = sshp_parse_frame(&ptl->serdev->dev, &aligned, &frame, &payload,
  7615. + SSH_PTL_RX_BUF_LEN);
  7616. + if (status) // invalid frame: skip to next syn
  7617. + return aligned.ptr - source->ptr + sizeof(u16);
  7618. + if (!frame) // not enough data
  7619. + return aligned.ptr - source->ptr;
  7620. +
  7621. + trace_ssam_rx_frame_received(frame);
  7622. +
  7623. + switch (frame->type) {
  7624. + case SSH_FRAME_TYPE_ACK:
  7625. + ssh_ptl_acknowledge(ptl, frame->seq);
  7626. + break;
  7627. +
  7628. + case SSH_FRAME_TYPE_NAK:
  7629. + ssh_ptl_resubmit_pending(ptl);
  7630. + break;
  7631. +
  7632. + case SSH_FRAME_TYPE_DATA_SEQ:
  7633. + ssh_ptl_send_ack(ptl, frame->seq);
  7634. + /* fallthrough */
  7635. +
  7636. + case SSH_FRAME_TYPE_DATA_NSQ:
  7637. + ssh_ptl_rx_dataframe(ptl, frame, &payload);
  7638. + break;
  7639. +
  7640. + default:
  7641. + ptl_warn(ptl, "ptl: received frame with unknown type 0x%02x\n",
  7642. + frame->type);
  7643. + break;
  7644. + }
  7645. +
  7646. + return aligned.ptr - source->ptr + SSH_MESSAGE_LENGTH(frame->len);
  7647. +}
  7648. +
  7649. +static int ssh_ptl_rx_threadfn(void *data)
  7650. +{
  7651. + struct ssh_ptl *ptl = data;
  7652. +
  7653. + while (true) {
  7654. + struct sshp_span span;
  7655. + size_t offs = 0;
  7656. + size_t n;
  7657. +
  7658. + wait_event_interruptible(ptl->rx.wq,
  7659. + !kfifo_is_empty(&ptl->rx.fifo)
  7660. + || kthread_should_stop());
  7661. + if (kthread_should_stop())
  7662. + break;
  7663. +
  7664. + // copy from fifo to evaluation buffer
  7665. + n = sshp_buf_read_from_fifo(&ptl->rx.buf, &ptl->rx.fifo);
  7666. +
  7667. + ptl_dbg(ptl, "rx: received data (size: %zu)\n", n);
  7668. + print_hex_dump_debug("rx: ", DUMP_PREFIX_OFFSET, 16, 1,
  7669. + ptl->rx.buf.ptr + ptl->rx.buf.len - n,
  7670. + n, false);
  7671. +
  7672. + // parse until we need more bytes or buffer is empty
  7673. + while (offs < ptl->rx.buf.len) {
  7674. + sshp_buf_span_from(&ptl->rx.buf, offs, &span);
  7675. + n = ssh_ptl_rx_eval(ptl, &span);
  7676. + if (n == 0)
  7677. + break; // need more bytes
  7678. +
  7679. + offs += n;
  7680. + }
  7681. +
  7682. + // throw away the evaluated parts
  7683. + sshp_buf_drop(&ptl->rx.buf, offs);
  7684. + }
  7685. +
  7686. + return 0;
  7687. +}
  7688. +
  7689. +static inline void ssh_ptl_rx_wakeup(struct ssh_ptl *ptl)
  7690. +{
  7691. + wake_up(&ptl->rx.wq);
  7692. +}
  7693. +
  7694. +static int ssh_ptl_rx_start(struct ssh_ptl *ptl)
  7695. +{
  7696. + if (ptl->rx.thread)
  7697. + return 0;
  7698. +
  7699. + ptl->rx.thread = kthread_run(ssh_ptl_rx_threadfn, ptl, "surface-sh-rx");
  7700. + if (IS_ERR(ptl->rx.thread))
  7701. + return PTR_ERR(ptl->rx.thread);
  7702. +
  7703. + return 0;
  7704. +}
  7705. +
  7706. +static int ssh_ptl_rx_stop(struct ssh_ptl *ptl)
  7707. +{
  7708. + int status = 0;
  7709. +
  7710. + if (ptl->rx.thread) {
  7711. + status = kthread_stop(ptl->rx.thread);
  7712. + ptl->rx.thread = NULL;
  7713. + }
  7714. +
  7715. + return status;
  7716. +}
  7717. +
  7718. +static int ssh_ptl_rx_rcvbuf(struct ssh_ptl *ptl, const u8 *buf, size_t n)
  7719. +{
  7720. + int used;
  7721. +
  7722. + if (test_bit(SSH_PTL_SF_SHUTDOWN_BIT, &ptl->state))
  7723. + return used;
  7724. +
  7725. + used = kfifo_in(&ptl->rx.fifo, buf, n);
  7726. + if (used)
  7727. + ssh_ptl_rx_wakeup(ptl);
  7728. +
  7729. + return used;
  7730. +}
  7731. +
  7732. +
  7733. +struct ssh_flush_packet {
  7734. + struct ssh_packet base;
  7735. + struct completion completion;
  7736. + int status;
  7737. +};
  7738. +
  7739. +static void ssh_ptl_flush_complete(struct ssh_packet *p, int status)
  7740. +{
  7741. + struct ssh_flush_packet *packet;
  7742. +
  7743. + packet = container_of(p, struct ssh_flush_packet, base);
  7744. + packet->status = status;
  7745. +}
  7746. +
  7747. +static void ssh_ptl_flush_release(struct ssh_packet *p)
  7748. +{
  7749. + struct ssh_flush_packet *packet;
  7750. +
  7751. + packet = container_of(p, struct ssh_flush_packet, base);
  7752. + complete_all(&packet->completion);
  7753. +}
  7754. +
  7755. +static const struct ssh_packet_ops ssh_flush_packet_ops = {
  7756. + .complete = ssh_ptl_flush_complete,
  7757. + .release = ssh_ptl_flush_release,
  7758. +};
  7759. +
  7760. +/**
  7761. + * ssh_ptl_flush - flush the packet transmission layer
  7762. + * @ptl: packet transmission layer
  7763. + * @timeout: timeout for the flush operation in jiffies
  7764. + *
  7765. + * Queue a special flush-packet and wait for its completion. This packet will
  7766. + * be completed after all other currently queued and pending packets have been
  7767. + * completed. Flushing guarantees that all previously submitted data packets
  7768. + * have been fully completed before this call returns. Additionally, flushing
  7769. + * blocks execution of all later submitted data packets until the flush has been
  7770. + * completed.
  7771. + *
  7772. + * Control (i.e. ACK/NAK) packets that have been submitted after this call will
  7773. + * be placed before the flush packet in the queue, as long as the flush-packet
  7774. + * has not been chosen for processing yet.
  7775. + *
  7776. + * Flushing, even when no new data packets are submitted after this call, does
  7777. + * not guarantee that no more packets are scheduled. For example, incoming
  7778. + * messages can promt automated submission of ACK or NAK type packets. If this
  7779. + * happens while the flush-packet is being processed (i.e. after it has been
  7780. + * taken from the queue), such packets may still be queued after this function
  7781. + * returns.
  7782. + *
  7783. + * Return: Zero on success, -ETIMEDOUT if the flush timed out and has been
  7784. + * canceled as a result of the timeout, or -ESHUTDOWN if the packet transmission
  7785. + * layer has been shut down before this call. May also return -EINTR if the
  7786. + * packet transmission has been interrupted.
  7787. + */
  7788. +static int ssh_ptl_flush(struct ssh_ptl *ptl, unsigned long timeout)
  7789. +{
  7790. + struct ssh_flush_packet packet;
  7791. + struct ssh_packet_args args;
  7792. + int status;
  7793. +
  7794. + args.type = SSH_PACKET_TY_FLUSH | SSH_PACKET_TY_BLOCKING;
  7795. + args.priority = SSH_PACKET_PRIORITY(FLUSH, 0);
  7796. + args.ops = &ssh_flush_packet_ops;
  7797. +
  7798. + ssh_packet_init(&packet.base, &args);
  7799. + init_completion(&packet.completion);
  7800. +
  7801. + status = ssh_ptl_submit(ptl, &packet.base);
  7802. + if (status)
  7803. + return status;
  7804. +
  7805. + ssh_packet_put(&packet.base);
  7806. +
  7807. + if (wait_for_completion_timeout(&packet.completion, timeout))
  7808. + return 0;
  7809. +
  7810. + ssh_ptl_cancel(&packet.base);
  7811. + wait_for_completion(&packet.completion);
  7812. +
  7813. + WARN_ON(packet.status != 0 && packet.status != -ECANCELED
  7814. + && packet.status != -ESHUTDOWN && packet.status != -EINTR);
  7815. +
  7816. + return packet.status == -ECANCELED ? -ETIMEDOUT : status;
  7817. +}
  7818. +
  7819. +/**
  7820. + * ssh_ptl_shutdown - shut down the packet transmission layer
  7821. + * @ptl: packet transmission layer
  7822. + *
  7823. + * Shuts down the packet transmission layer, removing and canceling all queued
  7824. + * and pending packets. Packets canceled by this operation will be completed
  7825. + * with -ESHUTDOWN as status.
  7826. + *
  7827. + * As a result of this function, the transmission layer will be marked as shut
  7828. + * down. Submission of packets after the transmission layer has been shut down
  7829. + * will fail with -ESHUTDOWN.
  7830. + */
  7831. +static void ssh_ptl_shutdown(struct ssh_ptl *ptl)
  7832. +{
  7833. + LIST_HEAD(complete_q);
  7834. + LIST_HEAD(complete_p);
  7835. + struct ssh_packet *p, *n;
  7836. + int status;
  7837. +
  7838. + // ensure that no new packets (including ACK/NAK) can be submitted
  7839. + set_bit(SSH_PTL_SF_SHUTDOWN_BIT, &ptl->state);
  7840. + smp_mb__after_atomic();
  7841. +
  7842. + status = ssh_ptl_rx_stop(ptl);
  7843. + if (status)
  7844. + ptl_err(ptl, "ptl: failed to stop receiver thread\n");
  7845. +
  7846. + status = ssh_ptl_tx_stop(ptl);
  7847. + if (status)
  7848. + ptl_err(ptl, "ptl: failed to stop transmitter thread\n");
  7849. +
  7850. + cancel_delayed_work_sync(&ptl->rtx_timeout.reaper);
  7851. +
  7852. + /*
  7853. + * At this point, all threads have been stopped. This means that the
  7854. + * only references to packets from inside the system are in the queue
  7855. + * and pending set.
  7856. + *
  7857. + * Note: We still need locks here because someone could still be
  7858. + * cancelling packets.
  7859. + *
  7860. + * Note 2: We can re-use queue_node (or pending_node) if we mark the
  7861. + * packet as locked an then remove it from the queue (or pending set
  7862. + * respecitvely). Marking the packet as locked avoids re-queueing
  7863. + * (which should already be prevented by having stopped the treads...)
  7864. + * and not setting QUEUED_BIT (or PENDING_BIT) prevents removal from a
  7865. + * new list via other threads (e.g. canellation).
  7866. + *
  7867. + * Note 3: There may be overlap between complete_p and complete_q.
  7868. + * This is handled via test_and_set_bit on the "completed" flag
  7869. + * (also handles cancelation).
  7870. + */
  7871. +
  7872. + // mark queued packets as locked and move them to complete_q
  7873. + spin_lock(&ptl->queue.lock);
  7874. + list_for_each_entry_safe(p, n, &ptl->queue.head, queue_node) {
  7875. + set_bit(SSH_PACKET_SF_LOCKED_BIT, &p->state);
  7876. + smp_mb__before_atomic();
  7877. + clear_bit(SSH_PACKET_SF_QUEUED_BIT, &p->state);
  7878. +
  7879. + list_del(&p->queue_node);
  7880. + list_add_tail(&p->queue_node, &complete_q);
  7881. + }
  7882. + spin_unlock(&ptl->queue.lock);
  7883. +
  7884. + // mark pending packets as locked and move them to complete_p
  7885. + spin_lock(&ptl->pending.lock);
  7886. + list_for_each_entry_safe(p, n, &ptl->pending.head, pending_node) {
  7887. + set_bit(SSH_PACKET_SF_LOCKED_BIT, &p->state);
  7888. + smp_mb__before_atomic();
  7889. + clear_bit(SSH_PACKET_SF_PENDING_BIT, &p->state);
  7890. +
  7891. + list_del(&p->pending_node);
  7892. + list_add_tail(&p->pending_node, &complete_q);
  7893. + }
  7894. + atomic_set(&ptl->pending.count, 0);
  7895. + spin_unlock(&ptl->pending.lock);
  7896. +
  7897. + // complete and drop packets on complete_q
  7898. + list_for_each_entry(p, &complete_q, queue_node) {
  7899. + if (!test_and_set_bit(SSH_PACKET_SF_COMPLETED_BIT, &p->state))
  7900. + __ssh_ptl_complete(p, -ESHUTDOWN);
  7901. +
  7902. + ssh_packet_put(p);
  7903. + }
  7904. +
  7905. + // complete and drop packets on complete_p
  7906. + list_for_each_entry(p, &complete_p, pending_node) {
  7907. + if (!test_and_set_bit(SSH_PACKET_SF_COMPLETED_BIT, &p->state))
  7908. + __ssh_ptl_complete(p, -ESHUTDOWN);
  7909. +
  7910. + ssh_packet_put(p);
  7911. + }
  7912. +
  7913. + /*
  7914. + * At this point we have guaranteed that the system doesn't reference
  7915. + * any packets any more.
  7916. + */
  7917. +}
  7918. +
  7919. +static inline struct device *ssh_ptl_get_device(struct ssh_ptl *ptl)
  7920. +{
  7921. + return &ptl->serdev->dev;
  7922. +}
  7923. +
  7924. +static int ssh_ptl_init(struct ssh_ptl *ptl, struct serdev_device *serdev,
  7925. + struct ssh_ptl_ops *ops)
  7926. +{
  7927. + int i, status;
  7928. +
  7929. + ptl->serdev = serdev;
  7930. + ptl->state = 0;
  7931. +
  7932. + spin_lock_init(&ptl->queue.lock);
  7933. + INIT_LIST_HEAD(&ptl->queue.head);
  7934. +
  7935. + spin_lock_init(&ptl->pending.lock);
  7936. + INIT_LIST_HEAD(&ptl->pending.head);
  7937. + atomic_set_release(&ptl->pending.count, 0);
  7938. +
  7939. + ptl->tx.thread = NULL;
  7940. + ptl->tx.thread_signal = false;
  7941. + ptl->tx.packet = NULL;
  7942. + ptl->tx.offset = 0;
  7943. + init_waitqueue_head(&ptl->tx.thread_wq);
  7944. + init_waitqueue_head(&ptl->tx.packet_wq);
  7945. +
  7946. + ptl->rx.thread = NULL;
  7947. + init_waitqueue_head(&ptl->rx.wq);
  7948. +
  7949. + ptl->rtx_timeout.timeout = SSH_PTL_PACKET_TIMEOUT;
  7950. + ptl->rtx_timeout.expires = KTIME_MAX;
  7951. + INIT_DELAYED_WORK(&ptl->rtx_timeout.reaper, ssh_ptl_timeout_reap);
  7952. +
  7953. + ptl->ops = *ops;
  7954. +
  7955. + // initialize SEQ blacklist with invalid sequence IDs
  7956. + for (i = 0; i < ARRAY_SIZE(ptl->rx.blacklist.seqs); i++)
  7957. + ptl->rx.blacklist.seqs[i] = 0xFFFF;
  7958. + ptl->rx.blacklist.offset = 0;
  7959. +
  7960. + status = kfifo_alloc(&ptl->rx.fifo, SSH_PTL_RX_FIFO_LEN, GFP_KERNEL);
  7961. + if (status)
  7962. + return status;
  7963. +
  7964. + status = sshp_buf_alloc(&ptl->rx.buf, SSH_PTL_RX_BUF_LEN, GFP_KERNEL);
  7965. + if (status)
  7966. + kfifo_free(&ptl->rx.fifo);
  7967. +
  7968. + return status;
  7969. +}
  7970. +
  7971. +static void ssh_ptl_destroy(struct ssh_ptl *ptl)
  7972. +{
  7973. + kfifo_free(&ptl->rx.fifo);
  7974. + sshp_buf_free(&ptl->rx.buf);
  7975. +}
  7976. +
  7977. +
  7978. +/* -- Request transport layer (rtl). ---------------------------------------- */
  7979. +
  7980. +#define SSH_RTL_REQUEST_TIMEOUT ms_to_ktime(1000)
  7981. +#define SSH_RTL_REQUEST_TIMEOUT_RESOLUTION ms_to_ktime(max(2000 / HZ, 50))
  7982. +
  7983. +#define SSH_RTL_MAX_PENDING 3
  7984. +
  7985. +
  7986. +enum ssh_rtl_state_flags {
  7987. + SSH_RTL_SF_SHUTDOWN_BIT,
  7988. +};
  7989. +
  7990. +struct ssh_rtl_ops {
  7991. + void (*handle_event)(struct ssh_rtl *rtl, const struct ssh_command *cmd,
  7992. + const struct sshp_span *data);
  7993. +};
  7994. +
  7995. +struct ssh_rtl {
  7996. + struct ssh_ptl ptl;
  7997. + unsigned long state;
  7998. +
  7999. + struct {
  8000. + spinlock_t lock;
  8001. + struct list_head head;
  8002. + } queue;
  8003. +
  8004. + struct {
  8005. + spinlock_t lock;
  8006. + struct list_head head;
  8007. + atomic_t count;
  8008. + } pending;
  8009. +
  8010. + struct {
  8011. + struct work_struct work;
  8012. + } tx;
  8013. +
  8014. + struct {
  8015. + ktime_t timeout;
  8016. + ktime_t expires;
  8017. + struct delayed_work reaper;
  8018. + } rtx_timeout;
  8019. +
  8020. + struct ssh_rtl_ops ops;
  8021. +};
  8022. +
  8023. +
  8024. +#define rtl_dbg(r, fmt, ...) ptl_dbg(&(r)->ptl, fmt, ##__VA_ARGS__)
  8025. +#define rtl_info(p, fmt, ...) ptl_info(&(p)->ptl, fmt, ##__VA_ARGS__)
  8026. +#define rtl_warn(r, fmt, ...) ptl_warn(&(r)->ptl, fmt, ##__VA_ARGS__)
  8027. +#define rtl_err(r, fmt, ...) ptl_err(&(r)->ptl, fmt, ##__VA_ARGS__)
  8028. +#define rtl_dbg_cond(r, fmt, ...) __ssam_prcond(rtl_dbg, r, fmt, ##__VA_ARGS__)
  8029. +
  8030. +#define to_ssh_rtl(ptr, member) \
  8031. + container_of(ptr, struct ssh_rtl, member)
  8032. +
  8033. +#define to_ssh_request(ptr, member) \
  8034. + container_of(ptr, struct ssh_request, member)
  8035. +
  8036. +
  8037. +/**
  8038. + * ssh_rtl_should_drop_response - error injection hook to drop request responses
  8039. + *
  8040. + * Useful to cause request transmission timeouts in the driver by dropping the
  8041. + * response to a request.
  8042. + */
  8043. +static noinline_if_inject bool ssh_rtl_should_drop_response(void)
  8044. +{
  8045. + return false;
  8046. +}
  8047. +// not supported on 4.19
  8048. +// ALLOW_ERROR_INJECTION(ssh_rtl_should_drop_response, TRUE);
  8049. +
  8050. +
  8051. +static inline void ssh_request_get(struct ssh_request *rqst)
  8052. +{
  8053. + ssh_packet_get(&rqst->packet);
  8054. +}
  8055. +
  8056. +static inline void ssh_request_put(struct ssh_request *rqst)
  8057. +{
  8058. + ssh_packet_put(&rqst->packet);
  8059. +}
  8060. +
  8061. +
  8062. +static inline u16 ssh_request_get_rqid(struct ssh_request *rqst)
  8063. +{
  8064. + return get_unaligned_le16(rqst->packet.data
  8065. + + SSH_MSGOFFSET_COMMAND(rqid));
  8066. +}
  8067. +
  8068. +static inline u32 ssh_request_get_rqid_safe(struct ssh_request *rqst)
  8069. +{
  8070. + if (!rqst->packet.data)
  8071. + return -1;
  8072. +
  8073. + return ssh_request_get_rqid(rqst);
  8074. +}
  8075. +
  8076. +
  8077. +static void ssh_rtl_queue_remove(struct ssh_request *rqst)
  8078. +{
  8079. + bool remove;
  8080. +
  8081. + spin_lock(&rqst->rtl->queue.lock);
  8082. +
  8083. + remove = test_and_clear_bit(SSH_REQUEST_SF_QUEUED_BIT, &rqst->state);
  8084. + if (remove)
  8085. + list_del(&rqst->node);
  8086. +
  8087. + spin_unlock(&rqst->rtl->queue.lock);
  8088. +
  8089. + if (remove)
  8090. + ssh_request_put(rqst);
  8091. +}
  8092. +
  8093. +static void ssh_rtl_pending_remove(struct ssh_request *rqst)
  8094. +{
  8095. + bool remove;
  8096. +
  8097. + spin_lock(&rqst->rtl->pending.lock);
  8098. +
  8099. + remove = test_and_clear_bit(SSH_REQUEST_SF_PENDING_BIT, &rqst->state);
  8100. + if (remove) {
  8101. + atomic_dec(&rqst->rtl->pending.count);
  8102. + list_del(&rqst->node);
  8103. + }
  8104. +
  8105. + spin_unlock(&rqst->rtl->pending.lock);
  8106. +
  8107. + if (remove)
  8108. + ssh_request_put(rqst);
  8109. +}
  8110. +
  8111. +
  8112. +static void ssh_rtl_complete_with_status(struct ssh_request *rqst, int status)
  8113. +{
  8114. + struct ssh_rtl *rtl = READ_ONCE(rqst->rtl);
  8115. +
  8116. + trace_ssam_request_complete(rqst, status);
  8117. +
  8118. + // rqst->rtl may not be set if we're cancelling before submitting
  8119. + rtl_dbg_cond(rtl, "rtl: completing request (rqid: 0x%04x,"
  8120. + " status: %d)\n", ssh_request_get_rqid_safe(rqst), status);
  8121. +
  8122. + rqst->ops->complete(rqst, NULL, NULL, status);
  8123. +}
  8124. +
  8125. +static void ssh_rtl_complete_with_rsp(struct ssh_request *rqst,
  8126. + const struct ssh_command *cmd,
  8127. + const struct sshp_span *data)
  8128. +{
  8129. + trace_ssam_request_complete(rqst, 0);
  8130. +
  8131. + rtl_dbg(rqst->rtl, "rtl: completing request with response"
  8132. + " (rqid: 0x%04x)\n", ssh_request_get_rqid(rqst));
  8133. +
  8134. + rqst->ops->complete(rqst, cmd, data, 0);
  8135. +}
  8136. +
  8137. +
  8138. +static bool ssh_rtl_tx_can_process(struct ssh_request *rqst)
  8139. +{
  8140. + if (test_bit(SSH_REQUEST_TY_FLUSH_BIT, &rqst->state))
  8141. + return !atomic_read(&rqst->rtl->pending.count);
  8142. +
  8143. + return atomic_read(&rqst->rtl->pending.count) < SSH_RTL_MAX_PENDING;
  8144. +}
  8145. +
  8146. +static struct ssh_request *ssh_rtl_tx_next(struct ssh_rtl *rtl)
  8147. +{
  8148. + struct ssh_request *rqst = ERR_PTR(-ENOENT);
  8149. + struct ssh_request *p, *n;
  8150. +
  8151. + spin_lock(&rtl->queue.lock);
  8152. +
  8153. + // find first non-locked request and remove it
  8154. + list_for_each_entry_safe(p, n, &rtl->queue.head, node) {
  8155. + if (unlikely(test_bit(SSH_REQUEST_SF_LOCKED_BIT, &p->state)))
  8156. + continue;
  8157. +
  8158. + if (!ssh_rtl_tx_can_process(p)) {
  8159. + rqst = ERR_PTR(-EBUSY);
  8160. + break;
  8161. + }
  8162. +
  8163. + /*
  8164. + * Remove from queue and mark as transmitting. Ensure that the
  8165. + * state does not get zero via memory barrier.
  8166. + */
  8167. + set_bit(SSH_REQUEST_SF_TRANSMITTING_BIT, &p->state);
  8168. + smp_mb__before_atomic();
  8169. + clear_bit(SSH_REQUEST_SF_QUEUED_BIT, &p->state);
  8170. +
  8171. + list_del(&p->node);
  8172. +
  8173. + rqst = p;
  8174. + break;
  8175. + }
  8176. +
  8177. + spin_unlock(&rtl->queue.lock);
  8178. + return rqst;
  8179. +}
  8180. +
  8181. +static int ssh_rtl_tx_pending_push(struct ssh_request *rqst)
  8182. +{
  8183. + struct ssh_rtl *rtl = rqst->rtl;
  8184. +
  8185. + spin_lock(&rtl->pending.lock);
  8186. +
  8187. + if (test_bit(SSH_REQUEST_SF_LOCKED_BIT, &rqst->state)) {
  8188. + spin_unlock(&rtl->pending.lock);
  8189. + return -EINVAL;
  8190. + }
  8191. +
  8192. + if (test_and_set_bit(SSH_REQUEST_SF_PENDING_BIT, &rqst->state)) {
  8193. + spin_unlock(&rtl->pending.lock);
  8194. + return -EALREADY;
  8195. + }
  8196. +
  8197. + atomic_inc(&rtl->pending.count);
  8198. + ssh_request_get(rqst);
  8199. + list_add_tail(&rqst->node, &rtl->pending.head);
  8200. +
  8201. + spin_unlock(&rtl->pending.lock);
  8202. + return 0;
  8203. +}
  8204. +
  8205. +static int ssh_rtl_tx_try_process_one(struct ssh_rtl *rtl)
  8206. +{
  8207. + struct ssh_request *rqst;
  8208. + int status;
  8209. +
  8210. + // get and prepare next request for transmit
  8211. + rqst = ssh_rtl_tx_next(rtl);
  8212. + if (IS_ERR(rqst))
  8213. + return PTR_ERR(rqst);
  8214. +
  8215. + // add to/mark as pending
  8216. + status = ssh_rtl_tx_pending_push(rqst);
  8217. + if (status) {
  8218. + ssh_request_put(rqst);
  8219. + return -EAGAIN;
  8220. + }
  8221. +
  8222. + // submit packet
  8223. + status = ssh_ptl_submit(&rtl->ptl, &rqst->packet);
  8224. + if (status == -ESHUTDOWN) {
  8225. + /*
  8226. + * Packet has been refused due to the packet layer shutting
  8227. + * down. Complete it here.
  8228. + */
  8229. + set_bit(SSH_REQUEST_SF_LOCKED_BIT, &rqst->state);
  8230. + smp_mb__after_atomic();
  8231. +
  8232. + ssh_rtl_pending_remove(rqst);
  8233. + ssh_rtl_complete_with_status(rqst, -ESHUTDOWN);
  8234. +
  8235. + ssh_request_put(rqst);
  8236. + return -ESHUTDOWN;
  8237. +
  8238. + } else if (status) {
  8239. + /*
  8240. + * If submitting the packet failed and the packet layer isn't
  8241. + * shutting down, the packet has either been submmitted/queued
  8242. + * before (-EALREADY, which cannot happen as we have guaranteed
  8243. + * that requests cannot be re-submitted), or the packet was
  8244. + * marked as locked (-EINVAL). To mark the packet locked at this
  8245. + * stage, the request, and thus the packets itself, had to have
  8246. + * been canceled. Simply drop the reference. Cancellation itself
  8247. + * will remove it from the set of pending requests.
  8248. + */
  8249. +
  8250. + WARN_ON(status != -EINVAL);
  8251. +
  8252. + ssh_request_put(rqst);
  8253. + return -EAGAIN;
  8254. + }
  8255. +
  8256. + ssh_request_put(rqst);
  8257. + return 0;
  8258. +}
  8259. +
  8260. +static bool ssh_rtl_queue_empty(struct ssh_rtl *rtl)
  8261. +{
  8262. + bool empty;
  8263. +
  8264. + spin_lock(&rtl->queue.lock);
  8265. + empty = list_empty(&rtl->queue.head);
  8266. + spin_unlock(&rtl->queue.lock);
  8267. +
  8268. + return empty;
  8269. +}
  8270. +
  8271. +static bool ssh_rtl_tx_schedule(struct ssh_rtl *rtl)
  8272. +{
  8273. + if (atomic_read(&rtl->pending.count) >= SSH_RTL_MAX_PENDING)
  8274. + return false;
  8275. +
  8276. + if (ssh_rtl_queue_empty(rtl))
  8277. + return false;
  8278. +
  8279. + return schedule_work(&rtl->tx.work);
  8280. +}
  8281. +
  8282. +static void ssh_rtl_tx_work_fn(struct work_struct *work)
  8283. +{
  8284. + struct ssh_rtl *rtl = to_ssh_rtl(work, tx.work);
  8285. + int i, status;
  8286. +
  8287. + /*
  8288. + * Try to be nice and not block the workqueue: Run a maximum of 10
  8289. + * tries, then re-submit if necessary. This should not be neccesary,
  8290. + * for normal execution, but guarantee it anyway.
  8291. + */
  8292. + for (i = 0; i < 10; i++) {
  8293. + status = ssh_rtl_tx_try_process_one(rtl);
  8294. + if (status == -ENOENT || status == -EBUSY)
  8295. + return; // no more requests to process
  8296. +
  8297. + if (status == -ESHUTDOWN) {
  8298. + /*
  8299. + * Packet system shutting down. No new packets can be
  8300. + * transmitted. Return silently, the party initiating
  8301. + * the shutdown should handle the rest.
  8302. + */
  8303. + return;
  8304. + }
  8305. +
  8306. + WARN_ON(status != 0 && status != -EAGAIN);
  8307. + }
  8308. +
  8309. + // out of tries, reschedule
  8310. + ssh_rtl_tx_schedule(rtl);
  8311. +}
  8312. +
  8313. +
  8314. +static int ssh_rtl_submit(struct ssh_rtl *rtl, struct ssh_request *rqst)
  8315. +{
  8316. + trace_ssam_request_submit(rqst);
  8317. +
  8318. + /*
  8319. + * Ensure that requests expecting a response are sequenced. If this
  8320. + * invariant ever changes, see the comment in ssh_rtl_complete on what
  8321. + * is required to be changed in the code.
  8322. + */
  8323. + if (test_bit(SSH_REQUEST_TY_HAS_RESPONSE_BIT, &rqst->state))
  8324. + if (!(rqst->packet.type & SSH_PACKET_TY_SEQUENCED))
  8325. + return -EINVAL;
  8326. +
  8327. + // try to set rtl and check if this request has already been submitted
  8328. + if (cmpxchg(&rqst->rtl, NULL, rtl) != NULL)
  8329. + return -EALREADY;
  8330. +
  8331. + spin_lock(&rtl->queue.lock);
  8332. +
  8333. + if (test_bit(SSH_RTL_SF_SHUTDOWN_BIT, &rtl->state)) {
  8334. + spin_unlock(&rtl->queue.lock);
  8335. + return -ESHUTDOWN;
  8336. + }
  8337. +
  8338. + if (test_bit(SSH_REQUEST_SF_LOCKED_BIT, &rqst->state)) {
  8339. + spin_unlock(&rtl->queue.lock);
  8340. + return -EINVAL;
  8341. + }
  8342. +
  8343. + ssh_request_get(rqst);
  8344. + set_bit(SSH_REQUEST_SF_QUEUED_BIT, &rqst->state);
  8345. + list_add_tail(&rqst->node, &rtl->queue.head);
  8346. +
  8347. + spin_unlock(&rtl->queue.lock);
  8348. +
  8349. + ssh_rtl_tx_schedule(rtl);
  8350. + return 0;
  8351. +}
  8352. +
  8353. +
  8354. +static void ssh_rtl_timeout_reaper_mod(struct ssh_rtl *rtl, ktime_t now,
  8355. + ktime_t expires)
  8356. +{
  8357. + unsigned long delta = msecs_to_jiffies(ktime_ms_delta(expires, now));
  8358. + ktime_t aexp = ktime_add(expires, SSH_RTL_REQUEST_TIMEOUT_RESOLUTION);
  8359. + ktime_t old;
  8360. +
  8361. + // re-adjust / schedule reaper if it is above resolution delta
  8362. + old = READ_ONCE(rtl->rtx_timeout.expires);
  8363. + while (ktime_before(aexp, old))
  8364. + old = cmpxchg64(&rtl->rtx_timeout.expires, old, expires);
  8365. +
  8366. + // if we updated the reaper expiration, modify work timeout
  8367. + if (old == expires)
  8368. + mod_delayed_work(system_wq, &rtl->rtx_timeout.reaper, delta);
  8369. +}
  8370. +
  8371. +static void ssh_rtl_timeout_start(struct ssh_request *rqst)
  8372. +{
  8373. + struct ssh_rtl *rtl = rqst->rtl;
  8374. + ktime_t timestamp = ktime_get_coarse_boottime();
  8375. + ktime_t timeout = rtl->rtx_timeout.timeout;
  8376. +
  8377. + if (test_bit(SSH_REQUEST_SF_LOCKED_BIT, &rqst->state))
  8378. + return;
  8379. +
  8380. + WRITE_ONCE(rqst->timestamp, timestamp);
  8381. + smp_mb__after_atomic();
  8382. +
  8383. + ssh_rtl_timeout_reaper_mod(rqst->rtl, timestamp, timestamp + timeout);
  8384. +}
  8385. +
  8386. +
  8387. +static void ssh_rtl_complete(struct ssh_rtl *rtl,
  8388. + const struct ssh_command *command,
  8389. + const struct sshp_span *command_data)
  8390. +{
  8391. + struct ssh_request *r = NULL;
  8392. + struct ssh_request *p, *n;
  8393. + u16 rqid = get_unaligned_le16(&command->rqid);
  8394. +
  8395. + trace_ssam_rx_response_received(command, command_data->len);
  8396. +
  8397. + /*
  8398. + * Get request from pending based on request ID and mark it as response
  8399. + * received and locked.
  8400. + */
  8401. + spin_lock(&rtl->pending.lock);
  8402. + list_for_each_entry_safe(p, n, &rtl->pending.head, node) {
  8403. + // we generally expect requests to be processed in order
  8404. + if (unlikely(ssh_request_get_rqid(p) != rqid))
  8405. + continue;
  8406. +
  8407. + // simulate response timeout
  8408. + if (ssh_rtl_should_drop_response()) {
  8409. + spin_unlock(&rtl->pending.lock);
  8410. +
  8411. + trace_ssam_ei_rx_drop_response(p);
  8412. + rtl_info(rtl, "request error injection: "
  8413. + "dropping response for request %p\n",
  8414. + &p->packet);
  8415. + return;
  8416. + }
  8417. +
  8418. + /*
  8419. + * Mark as "response received" and "locked" as we're going to
  8420. + * complete it. Ensure that the state doesn't get zero by
  8421. + * employing a memory barrier.
  8422. + */
  8423. + set_bit(SSH_REQUEST_SF_LOCKED_BIT, &p->state);
  8424. + set_bit(SSH_REQUEST_SF_RSPRCVD_BIT, &p->state);
  8425. + smp_mb__before_atomic();
  8426. + clear_bit(SSH_REQUEST_SF_PENDING_BIT, &p->state);
  8427. +
  8428. + atomic_dec(&rtl->pending.count);
  8429. + list_del(&p->node);
  8430. +
  8431. + r = p;
  8432. + break;
  8433. + }
  8434. + spin_unlock(&rtl->pending.lock);
  8435. +
  8436. + if (!r) {
  8437. + rtl_warn(rtl, "rtl: dropping unexpected command message"
  8438. + " (rqid = 0x%04x)\n", rqid);
  8439. + return;
  8440. + }
  8441. +
  8442. + // if the request hasn't been completed yet, we will do this now
  8443. + if (test_and_set_bit(SSH_REQUEST_SF_COMPLETED_BIT, &r->state)) {
  8444. + ssh_request_put(r);
  8445. + ssh_rtl_tx_schedule(rtl);
  8446. + return;
  8447. + }
  8448. +
  8449. + /*
  8450. + * Make sure the request has been transmitted. In case of a sequenced
  8451. + * request, we are guaranteed that the completion callback will run on
  8452. + * the receiver thread directly when the ACK for the packet has been
  8453. + * received. Similarly, this function is guaranteed to run on the
  8454. + * receiver thread. Thus we are guaranteed that if the packet has been
  8455. + * successfully transmitted and received an ACK, the transmitted flag
  8456. + * has been set and is visible here.
  8457. + *
  8458. + * We are currently not handling unsequenced packets here, as those
  8459. + * should never expect a response as ensured in ssh_rtl_submit. If this
  8460. + * ever changes, one would have to test for
  8461. + *
  8462. + * (r->state & (transmitting | transmitted))
  8463. + *
  8464. + * on unsequenced packets to determine if they could have been
  8465. + * transmitted. There are no synchronization guarantees as in the
  8466. + * sequenced case, since, in this case, the callback function will not
  8467. + * run on the same thread. Thus an exact determination is impossible.
  8468. + */
  8469. + if (!test_bit(SSH_REQUEST_SF_TRANSMITTED_BIT, &r->state)) {
  8470. + rtl_err(rtl, "rtl: received response before ACK for request"
  8471. + " (rqid = 0x%04x)\n", rqid);
  8472. +
  8473. + /*
  8474. + * NB: Timeout has already been canceled, request already been
  8475. + * removed from pending and marked as locked and completed. As
  8476. + * we receive a "false" response, the packet might still be
  8477. + * queued though.
  8478. + */
  8479. + ssh_rtl_queue_remove(r);
  8480. +
  8481. + ssh_rtl_complete_with_status(r, -EREMOTEIO);
  8482. + ssh_request_put(r);
  8483. +
  8484. + ssh_rtl_tx_schedule(rtl);
  8485. + return;
  8486. + }
  8487. +
  8488. + /*
  8489. + * NB: Timeout has already been canceled, request already been
  8490. + * removed from pending and marked as locked and completed. The request
  8491. + * can also not be queued any more, as it has been marked as
  8492. + * transmitting and later transmitted. Thus no need to remove it from
  8493. + * anywhere.
  8494. + */
  8495. +
  8496. + ssh_rtl_complete_with_rsp(r, command, command_data);
  8497. + ssh_request_put(r);
  8498. +
  8499. + ssh_rtl_tx_schedule(rtl);
  8500. +}
  8501. +
  8502. +
  8503. +static bool ssh_rtl_cancel_nonpending(struct ssh_request *r)
  8504. +{
  8505. + unsigned long state, fixed;
  8506. + bool remove;
  8507. +
  8508. + /*
  8509. + * Handle unsubmitted request: Try to mark the packet as locked,
  8510. + * expecting the state to be zero (i.e. unsubmitted). Note that, if
  8511. + * setting the state worked, we might still be adding the packet to the
  8512. + * queue in a currently executing submit call. In that case, however,
  8513. + * rqst->rtl must have been set previously, as locked is checked after
  8514. + * setting rqst->rtl. Thus only if we successfully lock this request and
  8515. + * rqst->rtl is NULL, we have successfully removed the request.
  8516. + * Otherwise we need to try and grab it from the queue.
  8517. + *
  8518. + * Note that if the CMPXCHG fails, we are guaranteed that rqst->rtl has
  8519. + * been set and is non-NULL, as states can only be nonzero after this
  8520. + * has been set. Also note that we need to fetch the static (type) flags
  8521. + * to ensure that they don't cause the cmpxchg to fail.
  8522. + */
  8523. + fixed = READ_ONCE(r->state) & SSH_REQUEST_FLAGS_TY_MASK;
  8524. + state = cmpxchg(&r->state, fixed, SSH_REQUEST_SF_LOCKED_BIT);
  8525. + if (!state && !READ_ONCE(r->rtl)) {
  8526. + if (test_and_set_bit(SSH_REQUEST_SF_COMPLETED_BIT, &r->state))
  8527. + return true;
  8528. +
  8529. + ssh_rtl_complete_with_status(r, -ECANCELED);
  8530. + return true;
  8531. + }
  8532. +
  8533. + spin_lock(&r->rtl->queue.lock);
  8534. +
  8535. + /*
  8536. + * Note: 1) Requests cannot be re-submitted. 2) If a request is queued,
  8537. + * it cannot be "transmitting"/"pending" yet. Thus, if we successfully
  8538. + * remove the the request here, we have removed all its occurences in
  8539. + * the system.
  8540. + */
  8541. +
  8542. + remove = test_and_clear_bit(SSH_REQUEST_SF_QUEUED_BIT, &r->state);
  8543. + if (!remove) {
  8544. + spin_unlock(&r->rtl->queue.lock);
  8545. + return false;
  8546. + }
  8547. +
  8548. + set_bit(SSH_REQUEST_SF_LOCKED_BIT, &r->state);
  8549. + list_del(&r->node);
  8550. +
  8551. + spin_unlock(&r->rtl->queue.lock);
  8552. +
  8553. + ssh_request_put(r); // drop reference obtained from queue
  8554. +
  8555. + if (test_and_set_bit(SSH_REQUEST_SF_COMPLETED_BIT, &r->state))
  8556. + return true;
  8557. +
  8558. + ssh_rtl_complete_with_status(r, -ECANCELED);
  8559. + return true;
  8560. +}
  8561. +
  8562. +static bool ssh_rtl_cancel_pending(struct ssh_request *r)
  8563. +{
  8564. + // if the packet is already locked, it's going to be removed shortly
  8565. + if (test_and_set_bit(SSH_REQUEST_SF_LOCKED_BIT, &r->state))
  8566. + return true;
  8567. +
  8568. + /*
  8569. + * Now that we have locked the packet, we have guaranteed that it can't
  8570. + * be added to the system any more. If rqst->rtl is zero, the locked
  8571. + * check in ssh_rtl_submit has not been run and any submission,
  8572. + * currently in progress or called later, won't add the packet. Thus we
  8573. + * can directly complete it.
  8574. + */
  8575. + if (!READ_ONCE(r->rtl)) {
  8576. + if (test_and_set_bit(SSH_REQUEST_SF_COMPLETED_BIT, &r->state))
  8577. + return true;
  8578. +
  8579. + ssh_rtl_complete_with_status(r, -ECANCELED);
  8580. + return true;
  8581. + }
  8582. +
  8583. + /*
  8584. + * Try to cancel the packet. If the packet has not been completed yet,
  8585. + * this will subsequently (and synchronously) call the completion
  8586. + * callback of the packet, which will complete the request.
  8587. + */
  8588. + ssh_ptl_cancel(&r->packet);
  8589. +
  8590. + /*
  8591. + * If the packet has been completed with success, i.e. has not been
  8592. + * canceled by the above call, the request may not have been completed
  8593. + * yet (may be waiting for a response). Check if we need to do this
  8594. + * here.
  8595. + */
  8596. + if (test_and_set_bit(SSH_REQUEST_SF_COMPLETED_BIT, &r->state))
  8597. + return true;
  8598. +
  8599. + ssh_rtl_queue_remove(r);
  8600. + ssh_rtl_pending_remove(r);
  8601. + ssh_rtl_complete_with_status(r, -ECANCELED);
  8602. +
  8603. + return true;
  8604. +}
  8605. +
  8606. +static bool ssh_rtl_cancel(struct ssh_request *rqst, bool pending)
  8607. +{
  8608. + struct ssh_rtl *rtl;
  8609. + bool canceled;
  8610. +
  8611. + if (test_and_set_bit(SSH_REQUEST_SF_CANCELED_BIT, &rqst->state))
  8612. + return true;
  8613. +
  8614. + trace_ssam_request_cancel(rqst);
  8615. +
  8616. + if (pending)
  8617. + canceled = ssh_rtl_cancel_pending(rqst);
  8618. + else
  8619. + canceled = ssh_rtl_cancel_nonpending(rqst);
  8620. +
  8621. + // note: rqst->rtl may be NULL if request has not been submitted yet
  8622. + rtl = READ_ONCE(rqst->rtl);
  8623. + if (canceled && rtl)
  8624. + ssh_rtl_tx_schedule(rtl);
  8625. +
  8626. + return canceled;
  8627. +}
  8628. +
  8629. +
  8630. +static void ssh_rtl_packet_callback(struct ssh_packet *p, int status)
  8631. +{
  8632. + struct ssh_request *r = to_ssh_request(p, packet);
  8633. +
  8634. + if (unlikely(status)) {
  8635. + set_bit(SSH_REQUEST_SF_LOCKED_BIT, &r->state);
  8636. +
  8637. + if (test_and_set_bit(SSH_REQUEST_SF_COMPLETED_BIT, &r->state))
  8638. + return;
  8639. +
  8640. + /*
  8641. + * The packet may get cancelled even though it has not been
  8642. + * submitted yet. The request may still be queued. Check the
  8643. + * queue and remove it if necessary. As the timeout would have
  8644. + * been started in this function on success, there's no need to
  8645. + * cancel it here.
  8646. + */
  8647. + ssh_rtl_queue_remove(r);
  8648. + ssh_rtl_pending_remove(r);
  8649. + ssh_rtl_complete_with_status(r, status);
  8650. +
  8651. + ssh_rtl_tx_schedule(r->rtl);
  8652. + return;
  8653. + }
  8654. +
  8655. + /*
  8656. + * Mark as transmitted, ensure that state doesn't get zero by inserting
  8657. + * a memory barrier.
  8658. + */
  8659. + set_bit(SSH_REQUEST_SF_TRANSMITTED_BIT, &r->state);
  8660. + smp_mb__before_atomic();
  8661. + clear_bit(SSH_REQUEST_SF_TRANSMITTING_BIT, &r->state);
  8662. +
  8663. + // if we expect a response, we just need to start the timeout
  8664. + if (test_bit(SSH_REQUEST_TY_HAS_RESPONSE_BIT, &r->state)) {
  8665. + ssh_rtl_timeout_start(r);
  8666. + return;
  8667. + }
  8668. +
  8669. + /*
  8670. + * If we don't expect a response, lock, remove, and complete the
  8671. + * request. Note that, at this point, the request is guaranteed to have
  8672. + * left the queue and no timeout has been started. Thus we only need to
  8673. + * remove it from pending. If the request has already been completed (it
  8674. + * may have been canceled) return.
  8675. + */
  8676. +
  8677. + set_bit(SSH_REQUEST_SF_LOCKED_BIT, &r->state);
  8678. + if (test_and_set_bit(SSH_REQUEST_SF_COMPLETED_BIT, &r->state))
  8679. + return;
  8680. +
  8681. + ssh_rtl_pending_remove(r);
  8682. + ssh_rtl_complete_with_status(r, 0);
  8683. +
  8684. + ssh_rtl_tx_schedule(r->rtl);
  8685. +}
  8686. +
  8687. +
  8688. +static ktime_t ssh_request_get_expiration(struct ssh_request *r, ktime_t timeo)
  8689. +{
  8690. + ktime_t timestamp = READ_ONCE(r->timestamp);
  8691. +
  8692. + if (timestamp != KTIME_MAX)
  8693. + return ktime_add(timestamp, timeo);
  8694. + else
  8695. + return KTIME_MAX;
  8696. +}
  8697. +
  8698. +static void ssh_rtl_timeout_reap(struct work_struct *work)
  8699. +{
  8700. + struct ssh_rtl *rtl = to_ssh_rtl(work, rtx_timeout.reaper.work);
  8701. + struct ssh_request *r, *n;
  8702. + LIST_HEAD(claimed);
  8703. + ktime_t now = ktime_get_coarse_boottime();
  8704. + ktime_t timeout = rtl->rtx_timeout.timeout;
  8705. + ktime_t next = KTIME_MAX;
  8706. +
  8707. + trace_ssam_rtl_timeout_reap("pending", atomic_read(&rtl->pending.count));
  8708. +
  8709. + /*
  8710. + * Mark reaper as "not pending". This is done before checking any
  8711. + * requests to avoid lost-update type problems.
  8712. + */
  8713. + WRITE_ONCE(rtl->rtx_timeout.expires, KTIME_MAX);
  8714. + smp_mb__after_atomic();
  8715. +
  8716. + spin_lock(&rtl->pending.lock);
  8717. + list_for_each_entry_safe(r, n, &rtl->pending.head, node) {
  8718. + ktime_t expires = ssh_request_get_expiration(r, timeout);
  8719. +
  8720. + /*
  8721. + * Check if the timeout hasn't expired yet. Find out next
  8722. + * expiration date to be handled after this run.
  8723. + */
  8724. + if (ktime_after(expires, now)) {
  8725. + next = ktime_before(expires, next) ? expires : next;
  8726. + continue;
  8727. + }
  8728. +
  8729. + // avoid further transitions if locked
  8730. + if (test_and_set_bit(SSH_REQUEST_SF_LOCKED_BIT, &r->state))
  8731. + continue;
  8732. +
  8733. + /*
  8734. + * We have now marked the packet as locked. Thus it cannot be
  8735. + * added to the pending or queued lists again after we've
  8736. + * removed it here. We can therefore re-use the node of this
  8737. + * packet temporarily.
  8738. + */
  8739. +
  8740. + clear_bit(SSH_REQUEST_SF_PENDING_BIT, &r->state);
  8741. +
  8742. + atomic_dec(&rtl->pending.count);
  8743. + list_del(&r->node);
  8744. +
  8745. + list_add_tail(&r->node, &claimed);
  8746. + }
  8747. + spin_unlock(&rtl->pending.lock);
  8748. +
  8749. + // cancel and complete the request
  8750. + list_for_each_entry_safe(r, n, &claimed, node) {
  8751. + trace_ssam_request_timeout(r);
  8752. +
  8753. + /*
  8754. + * At this point we've removed the packet from pending. This
  8755. + * means that we've obtained the last (only) reference of the
  8756. + * system to it. Thus we can just complete it.
  8757. + */
  8758. + if (!test_and_set_bit(SSH_REQUEST_SF_COMPLETED_BIT, &r->state))
  8759. + ssh_rtl_complete_with_status(r, -ETIMEDOUT);
  8760. +
  8761. + // drop the reference we've obtained by removing it from pending
  8762. + list_del(&r->node);
  8763. + ssh_request_put(r);
  8764. + }
  8765. +
  8766. + // ensure that reaper doesn't run again immediately
  8767. + next = max(next, ktime_add(now, SSH_RTL_REQUEST_TIMEOUT_RESOLUTION));
  8768. + if (next != KTIME_MAX)
  8769. + ssh_rtl_timeout_reaper_mod(rtl, now, next);
  8770. +
  8771. + ssh_rtl_tx_schedule(rtl);
  8772. +}
  8773. +
  8774. +
  8775. +static void ssh_rtl_rx_event(struct ssh_rtl *rtl, const struct ssh_command *cmd,
  8776. + const struct sshp_span *data)
  8777. +{
  8778. + trace_ssam_rx_event_received(cmd, data->len);
  8779. +
  8780. + rtl_dbg(rtl, "rtl: handling event (rqid: 0x%04x)\n",
  8781. + get_unaligned_le16(&cmd->rqid));
  8782. +
  8783. + rtl->ops.handle_event(rtl, cmd, data);
  8784. +}
  8785. +
  8786. +static void ssh_rtl_rx_command(struct ssh_ptl *p, const struct sshp_span *data)
  8787. +{
  8788. + struct ssh_rtl *rtl = to_ssh_rtl(p, ptl);
  8789. + struct device *dev = &p->serdev->dev;
  8790. + struct ssh_command *command;
  8791. + struct sshp_span command_data;
  8792. +
  8793. + if (sshp_parse_command(dev, data, &command, &command_data))
  8794. + return;
  8795. +
  8796. + if (ssh_rqid_is_event(get_unaligned_le16(&command->rqid)))
  8797. + ssh_rtl_rx_event(rtl, command, &command_data);
  8798. + else
  8799. + ssh_rtl_complete(rtl, command, &command_data);
  8800. +}
  8801. +
  8802. +static void ssh_rtl_rx_data(struct ssh_ptl *p, const struct sshp_span *data)
  8803. +{
  8804. + switch (data->ptr[0]) {
  8805. + case SSH_PLD_TYPE_CMD:
  8806. + ssh_rtl_rx_command(p, data);
  8807. + break;
  8808. +
  8809. + default:
  8810. + ptl_err(p, "rtl: rx: unknown frame payload type"
  8811. + " (type: 0x%02x)\n", data->ptr[0]);
  8812. + break;
  8813. + }
  8814. +}
  8815. +
  8816. +
  8817. +static inline struct device *ssh_rtl_get_device(struct ssh_rtl *rtl)
  8818. +{
  8819. + return ssh_ptl_get_device(&rtl->ptl);
  8820. +}
  8821. +
  8822. +static inline bool ssh_rtl_tx_flush(struct ssh_rtl *rtl)
  8823. +{
  8824. + return flush_work(&rtl->tx.work);
  8825. +}
  8826. +
  8827. +static inline int ssh_rtl_tx_start(struct ssh_rtl *rtl)
  8828. +{
  8829. + int status;
  8830. + bool sched;
  8831. +
  8832. + status = ssh_ptl_tx_start(&rtl->ptl);
  8833. + if (status)
  8834. + return status;
  8835. +
  8836. + /*
  8837. + * If the packet layer has been shut down and restarted without shutting
  8838. + * down the request layer, there may still be requests queued and not
  8839. + * handled.
  8840. + */
  8841. + spin_lock(&rtl->queue.lock);
  8842. + sched = !list_empty(&rtl->queue.head);
  8843. + spin_unlock(&rtl->queue.lock);
  8844. +
  8845. + if (sched)
  8846. + ssh_rtl_tx_schedule(rtl);
  8847. +
  8848. + return 0;
  8849. +}
  8850. +
  8851. +static inline int ssh_rtl_rx_start(struct ssh_rtl *rtl)
  8852. +{
  8853. + return ssh_ptl_rx_start(&rtl->ptl);
  8854. +}
  8855. +
  8856. +static int ssh_rtl_init(struct ssh_rtl *rtl, struct serdev_device *serdev,
  8857. + struct ssh_rtl_ops *ops)
  8858. +{
  8859. + struct ssh_ptl_ops ptl_ops;
  8860. + int status;
  8861. +
  8862. + ptl_ops.data_received = ssh_rtl_rx_data;
  8863. +
  8864. + status = ssh_ptl_init(&rtl->ptl, serdev, &ptl_ops);
  8865. + if (status)
  8866. + return status;
  8867. +
  8868. + spin_lock_init(&rtl->queue.lock);
  8869. + INIT_LIST_HEAD(&rtl->queue.head);
  8870. +
  8871. + spin_lock_init(&rtl->pending.lock);
  8872. + INIT_LIST_HEAD(&rtl->pending.head);
  8873. + atomic_set_release(&rtl->pending.count, 0);
  8874. +
  8875. + INIT_WORK(&rtl->tx.work, ssh_rtl_tx_work_fn);
  8876. +
  8877. + rtl->rtx_timeout.timeout = SSH_RTL_REQUEST_TIMEOUT;
  8878. + rtl->rtx_timeout.expires = KTIME_MAX;
  8879. + INIT_DELAYED_WORK(&rtl->rtx_timeout.reaper, ssh_rtl_timeout_reap);
  8880. +
  8881. + rtl->ops = *ops;
  8882. +
  8883. + return 0;
  8884. +}
  8885. +
  8886. +static void ssh_rtl_destroy(struct ssh_rtl *rtl)
  8887. +{
  8888. + ssh_ptl_destroy(&rtl->ptl);
  8889. +}
  8890. +
  8891. +
  8892. +static void ssh_rtl_packet_release(struct ssh_packet *p)
  8893. +{
  8894. + struct ssh_request *rqst = to_ssh_request(p, packet);
  8895. + rqst->ops->release(rqst);
  8896. +}
  8897. +
  8898. +static const struct ssh_packet_ops ssh_rtl_packet_ops = {
  8899. + .complete = ssh_rtl_packet_callback,
  8900. + .release = ssh_rtl_packet_release,
  8901. +};
  8902. +
  8903. +static void ssh_request_init(struct ssh_request *rqst,
  8904. + enum ssam_request_flags flags,
  8905. + const struct ssh_request_ops *ops)
  8906. +{
  8907. + struct ssh_packet_args packet_args;
  8908. +
  8909. + packet_args.type = SSH_PACKET_TY_BLOCKING;
  8910. + if (!(flags & SSAM_REQUEST_UNSEQUENCED))
  8911. + packet_args.type |= SSH_PACKET_TY_SEQUENCED;
  8912. +
  8913. + packet_args.priority = SSH_PACKET_PRIORITY(DATA, 0);
  8914. + packet_args.ops = &ssh_rtl_packet_ops;
  8915. +
  8916. + ssh_packet_init(&rqst->packet, &packet_args);
  8917. +
  8918. + rqst->rtl = NULL;
  8919. + INIT_LIST_HEAD(&rqst->node);
  8920. +
  8921. + rqst->state = 0;
  8922. + if (flags & SSAM_REQUEST_HAS_RESPONSE)
  8923. + rqst->state |= BIT(SSH_REQUEST_TY_HAS_RESPONSE_BIT);
  8924. +
  8925. + rqst->timestamp = KTIME_MAX;
  8926. + rqst->ops = ops;
  8927. +}
  8928. +
  8929. +
  8930. +struct ssh_flush_request {
  8931. + struct ssh_request base;
  8932. + struct completion completion;
  8933. + int status;
  8934. +};
  8935. +
  8936. +static void ssh_rtl_flush_request_complete(struct ssh_request *r,
  8937. + const struct ssh_command *cmd,
  8938. + const struct sshp_span *data,
  8939. + int status)
  8940. +{
  8941. + struct ssh_flush_request *rqst;
  8942. +
  8943. + rqst = container_of(r, struct ssh_flush_request, base);
  8944. + rqst->status = status;
  8945. +}
  8946. +
  8947. +static void ssh_rtl_flush_request_release(struct ssh_request *r)
  8948. +{
  8949. + struct ssh_flush_request *rqst;
  8950. +
  8951. + rqst = container_of(r, struct ssh_flush_request, base);
  8952. + complete_all(&rqst->completion);
  8953. +}
  8954. +
  8955. +static const struct ssh_request_ops ssh_rtl_flush_request_ops = {
  8956. + .complete = ssh_rtl_flush_request_complete,
  8957. + .release = ssh_rtl_flush_request_release,
  8958. +};
  8959. +
  8960. +/**
  8961. + * ssh_rtl_flush - flush the request transmission layer
  8962. + * @rtl: request transmission layer
  8963. + * @timeout: timeout for the flush operation in jiffies
  8964. + *
  8965. + * Queue a special flush request and wait for its completion. This request
  8966. + * will be completed after all other currently queued and pending requests
  8967. + * have been completed. Instead of a normal data packet, this request submits
  8968. + * a special flush packet, meaning that upon completion, also the underlying
  8969. + * packet transmission layer has been flushed.
  8970. + *
  8971. + * Flushing the request layer gurarantees that all previously submitted
  8972. + * requests have been fully completed before this call returns. Additinally,
  8973. + * flushing blocks execution of all later submitted requests until the flush
  8974. + * has been completed.
  8975. + *
  8976. + * If the caller ensures that no new requests are submitted after a call to
  8977. + * this function, the request transmission layer is guaranteed to have no
  8978. + * remaining requests when this call returns. The same guarantee does not hold
  8979. + * for the packet layer, on which control packets may still be queued after
  8980. + * this call. See the documentation of ssh_ptl_flush for more details on
  8981. + * packet layer flushing.
  8982. + *
  8983. + * Return: Zero on success, -ETIMEDOUT if the flush timed out and has been
  8984. + * canceled as a result of the timeout, or -ESHUTDOWN if the packet and/or
  8985. + * request transmission layer has been shut down before this call. May also
  8986. + * return -EINTR if the underlying packet transmission has been interrupted.
  8987. + */
  8988. +static int ssh_rtl_flush(struct ssh_rtl *rtl, unsigned long timeout)
  8989. +{
  8990. + const unsigned init_flags = SSAM_REQUEST_UNSEQUENCED;
  8991. + struct ssh_flush_request rqst;
  8992. + int status;
  8993. +
  8994. + ssh_request_init(&rqst.base, init_flags, &ssh_rtl_flush_request_ops);
  8995. + rqst.base.packet.type |= SSH_PACKET_TY_FLUSH;
  8996. + rqst.base.packet.priority = SSH_PACKET_PRIORITY(FLUSH, 0);
  8997. + rqst.base.state |= BIT(SSH_REQUEST_TY_FLUSH_BIT);
  8998. +
  8999. + init_completion(&rqst.completion);
  9000. +
  9001. + status = ssh_rtl_submit(rtl, &rqst.base);
  9002. + if (status)
  9003. + return status;
  9004. +
  9005. + ssh_request_put(&rqst.base);
  9006. +
  9007. + if (wait_for_completion_timeout(&rqst.completion, timeout))
  9008. + return 0;
  9009. +
  9010. + ssh_rtl_cancel(&rqst.base, true);
  9011. + wait_for_completion(&rqst.completion);
  9012. +
  9013. + WARN_ON(rqst.status != 0 && rqst.status != -ECANCELED
  9014. + && rqst.status != -ESHUTDOWN && rqst.status != -EINTR);
  9015. +
  9016. + return rqst.status == -ECANCELED ? -ETIMEDOUT : status;
  9017. +}
  9018. +
  9019. +
  9020. +static void ssh_rtl_shutdown(struct ssh_rtl *rtl)
  9021. +{
  9022. + struct ssh_request *r, *n;
  9023. + LIST_HEAD(claimed);
  9024. + int pending;
  9025. +
  9026. + set_bit(SSH_RTL_SF_SHUTDOWN_BIT, &rtl->state);
  9027. + smp_mb__after_atomic();
  9028. +
  9029. + // remove requests from queue
  9030. + spin_lock(&rtl->queue.lock);
  9031. + list_for_each_entry_safe(r, n, &rtl->queue.head, node) {
  9032. + set_bit(SSH_REQUEST_SF_LOCKED_BIT, &r->state);
  9033. + smp_mb__before_atomic();
  9034. + clear_bit(SSH_REQUEST_SF_QUEUED_BIT, &r->state);
  9035. +
  9036. + list_del(&r->node);
  9037. + list_add_tail(&r->node, &claimed);
  9038. + }
  9039. + spin_unlock(&rtl->queue.lock);
  9040. +
  9041. + /*
  9042. + * We have now guaranteed that the queue is empty and no more new
  9043. + * requests can be submitted (i.e. it will stay empty). This means that
  9044. + * calling ssh_rtl_tx_schedule will not schedule tx.work any more. So we
  9045. + * can simply call cancel_work_sync on tx.work here and when that
  9046. + * returns, we've locked it down. This also means that after this call,
  9047. + * we don't submit any more packets to the underlying packet layer, so
  9048. + * we can also shut that down.
  9049. + */
  9050. +
  9051. + cancel_work_sync(&rtl->tx.work);
  9052. + ssh_ptl_shutdown(&rtl->ptl);
  9053. + cancel_delayed_work_sync(&rtl->rtx_timeout.reaper);
  9054. +
  9055. + /*
  9056. + * Shutting down the packet layer should also have caneled all requests.
  9057. + * Thus the pending set should be empty. Attempt to handle this
  9058. + * gracefully anyways, even though this should be dead code.
  9059. + */
  9060. +
  9061. + pending = atomic_read(&rtl->pending.count);
  9062. + WARN_ON(pending);
  9063. +
  9064. + if (pending) {
  9065. + spin_lock(&rtl->pending.lock);
  9066. + list_for_each_entry_safe(r, n, &rtl->pending.head, node) {
  9067. + set_bit(SSH_REQUEST_SF_LOCKED_BIT, &r->state);
  9068. + smp_mb__before_atomic();
  9069. + clear_bit(SSH_REQUEST_SF_PENDING_BIT, &r->state);
  9070. +
  9071. + list_del(&r->node);
  9072. + list_add_tail(&r->node, &claimed);
  9073. + }
  9074. + spin_unlock(&rtl->pending.lock);
  9075. + }
  9076. +
  9077. + // finally cancel and complete requests
  9078. + list_for_each_entry_safe(r, n, &claimed, node) {
  9079. + // test_and_set because we still might compete with cancellation
  9080. + if (!test_and_set_bit(SSH_REQUEST_SF_COMPLETED_BIT, &r->state))
  9081. + ssh_rtl_complete_with_status(r, -ESHUTDOWN);
  9082. +
  9083. + // drop the reference we've obtained by removing it from list
  9084. + list_del(&r->node);
  9085. + ssh_request_put(r);
  9086. + }
  9087. +}
  9088. +
  9089. +
  9090. +/* -- Event notifier/callbacks. --------------------------------------------- */
  9091. +/*
  9092. + * The notifier system is based on linux/notifier.h, specifically the SRCU
  9093. + * implementation. The difference to that is, that some bits of the notifier
  9094. + * call return value can be tracked accross multiple calls. This is done so that
  9095. + * handling of events can be tracked and a warning can be issued in case an
  9096. + * event goes unhandled. The idea of that waring is that it should help discover
  9097. + * and identify new/currently unimplemented features.
  9098. + */
  9099. +
  9100. +struct ssam_nf_head {
  9101. + struct srcu_struct srcu;
  9102. + struct ssam_notifier_block __rcu *head;
  9103. +};
  9104. +
  9105. +
  9106. +int ssam_nfblk_call_chain(struct ssam_nf_head *nh, struct ssam_event *event)
  9107. +{
  9108. + struct ssam_notifier_block *nb, *next_nb;
  9109. + int ret = 0, idx;
  9110. +
  9111. + idx = srcu_read_lock(&nh->srcu);
  9112. +
  9113. + nb = rcu_dereference_raw(nh->head);
  9114. + while (nb) {
  9115. + next_nb = rcu_dereference_raw(nb->next);
  9116. +
  9117. + ret = (ret & SSAM_NOTIF_STATE_MASK) | nb->fn(nb, event);
  9118. + if (ret & SSAM_NOTIF_STOP)
  9119. + break;
  9120. +
  9121. + nb = next_nb;
  9122. + }
  9123. +
  9124. + srcu_read_unlock(&nh->srcu, idx);
  9125. + return ret;
  9126. +}
  9127. +
  9128. +/*
  9129. + * Note: This function must be synchronized by the caller with respect to other
  9130. + * insert and/or remove calls.
  9131. + */
  9132. +int __ssam_nfblk_insert(struct ssam_nf_head *nh, struct ssam_notifier_block *nb)
  9133. +{
  9134. + struct ssam_notifier_block **link = &nh->head;
  9135. +
  9136. + while ((*link) != NULL) {
  9137. + if (unlikely((*link) == nb)) {
  9138. + WARN(1, "double register detected");
  9139. + return -EINVAL;
  9140. + }
  9141. +
  9142. + if (nb->priority > (*link)->priority)
  9143. + break;
  9144. +
  9145. + link = &((*link)->next);
  9146. + }
  9147. +
  9148. + nb->next = *link;
  9149. + rcu_assign_pointer(*link, nb);
  9150. +
  9151. + return 0;
  9152. +}
  9153. +
  9154. +/*
  9155. + * Note: This function must be synchronized by the caller with respect to other
  9156. + * insert and/or remove calls. On success, the caller _must_ ensure SRCU
  9157. + * synchronization by calling `synchronize_srcu(&nh->srcu)` after leaving the
  9158. + * critical section, to ensure that the removed notifier block is not in use any
  9159. + * more.
  9160. + */
  9161. +int __ssam_nfblk_remove(struct ssam_nf_head *nh, struct ssam_notifier_block *nb)
  9162. +{
  9163. + struct ssam_notifier_block **link = &nh->head;
  9164. +
  9165. + while ((*link) != NULL) {
  9166. + if ((*link) == nb) {
  9167. + rcu_assign_pointer(*link, nb->next);
  9168. + return 0;
  9169. + }
  9170. +
  9171. + link = &((*link)->next);
  9172. + }
  9173. +
  9174. + return -ENOENT;
  9175. +}
  9176. +
  9177. +static int ssam_nf_head_init(struct ssam_nf_head *nh)
  9178. +{
  9179. + int status;
  9180. +
  9181. + status = init_srcu_struct(&nh->srcu);
  9182. + if (status)
  9183. + return status;
  9184. +
  9185. + nh->head = NULL;
  9186. + return 0;
  9187. +}
  9188. +
  9189. +static void ssam_nf_head_destroy(struct ssam_nf_head *nh)
  9190. +{
  9191. + cleanup_srcu_struct(&nh->srcu);
  9192. +}
  9193. +
  9194. +
  9195. +/* -- Event/notification registry. ------------------------------------------ */
  9196. +
  9197. +struct ssam_nf_refcount_key {
  9198. + struct ssam_event_registry reg;
  9199. + struct ssam_event_id id;
  9200. +};
  9201. +
  9202. +struct ssam_nf_refcount_entry {
  9203. + struct rb_node node;
  9204. + struct ssam_nf_refcount_key key;
  9205. + int refcount;
  9206. +};
  9207. +
  9208. +struct ssam_nf {
  9209. + struct mutex lock;
  9210. + struct rb_root refcount;
  9211. + struct ssam_nf_head head[SURFACE_SAM_SSH_NUM_EVENTS];
  9212. +};
  9213. +
  9214. +
  9215. +static int ssam_nf_refcount_inc(struct ssam_nf *nf,
  9216. + struct ssam_event_registry reg,
  9217. + struct ssam_event_id id)
  9218. +{
  9219. + struct ssam_nf_refcount_entry *entry;
  9220. + struct ssam_nf_refcount_key key;
  9221. + struct rb_node **link = &nf->refcount.rb_node;
  9222. + struct rb_node *parent;
  9223. + int cmp;
  9224. +
  9225. + key.reg = reg;
  9226. + key.id = id;
  9227. +
  9228. + while (*link) {
  9229. + entry = rb_entry(*link, struct ssam_nf_refcount_entry, node);
  9230. + parent = *link;
  9231. +
  9232. + cmp = memcmp(&key, &entry->key, sizeof(key));
  9233. + if (cmp < 0) {
  9234. + link = &(*link)->rb_left;
  9235. + } else if (cmp > 0) {
  9236. + link = &(*link)->rb_right;
  9237. + } else if (entry->refcount < INT_MAX) {
  9238. + return ++entry->refcount;
  9239. + } else {
  9240. + return -ENOSPC;
  9241. + }
  9242. + }
  9243. +
  9244. + entry = kzalloc(sizeof(*entry), GFP_KERNEL);
  9245. + if (!entry)
  9246. + return -ENOMEM;
  9247. +
  9248. + entry->key = key;
  9249. + entry->refcount = 1;
  9250. +
  9251. + rb_link_node(&entry->node, parent, link);
  9252. + rb_insert_color(&entry->node, &nf->refcount);
  9253. +
  9254. + return entry->refcount;
  9255. +}
  9256. +
  9257. +static int ssam_nf_refcount_dec(struct ssam_nf *nf,
  9258. + struct ssam_event_registry reg,
  9259. + struct ssam_event_id id)
  9260. +{
  9261. + struct ssam_nf_refcount_entry *entry;
  9262. + struct ssam_nf_refcount_key key;
  9263. + struct rb_node *node = nf->refcount.rb_node;
  9264. + int cmp, rc;
  9265. +
  9266. + key.reg = reg;
  9267. + key.id = id;
  9268. +
  9269. + while (node) {
  9270. + entry = rb_entry(node, struct ssam_nf_refcount_entry, node);
  9271. +
  9272. + cmp = memcmp(&key, &entry->key, sizeof(key));
  9273. + if (cmp < 0) {
  9274. + node = node->rb_left;
  9275. + } else if (cmp > 0) {
  9276. + node = node->rb_right;
  9277. + } else {
  9278. + rc = --entry->refcount;
  9279. +
  9280. + if (rc == 0) {
  9281. + rb_erase(&entry->node, &nf->refcount);
  9282. + kfree(entry);
  9283. + }
  9284. +
  9285. + return rc;
  9286. + }
  9287. + }
  9288. +
  9289. + return -ENOENT;
  9290. +}
  9291. +
  9292. +static void ssam_nf_call(struct ssam_nf *nf, struct device *dev, u16 rqid,
  9293. + struct ssam_event *event)
  9294. +{
  9295. + struct ssam_nf_head *nf_head;
  9296. + int status, nf_ret;
  9297. +
  9298. + if (!ssh_rqid_is_event(rqid)) {
  9299. + dev_warn(dev, "event: unsupported rqid: 0x%04x\n", rqid);
  9300. + return;
  9301. + }
  9302. +
  9303. + nf_head = &nf->head[ssh_rqid_to_event(rqid)];
  9304. + nf_ret = ssam_nfblk_call_chain(nf_head, event);
  9305. + status = ssam_notifier_to_errno(nf_ret);
  9306. +
  9307. + if (status < 0) {
  9308. + dev_err(dev, "event: error handling event: %d "
  9309. + "(tc: 0x%02x, cid: 0x%02x, iid: 0x%02x, chn: 0x%02x)\n",
  9310. + status, event->target_category, event->command_id,
  9311. + event->instance_id, event->channel);
  9312. + }
  9313. +
  9314. + if (!(nf_ret & SSAM_NOTIF_HANDLED)) {
  9315. + dev_warn(dev, "event: unhandled event (rqid: 0x%02x, "
  9316. + "tc: 0x%02x, cid: 0x%02x, iid: 0x%02x, chn: 0x%02x)\n",
  9317. + rqid, event->target_category, event->command_id,
  9318. + event->instance_id, event->channel);
  9319. + }
  9320. +}
  9321. +
  9322. +static int ssam_nf_register(struct ssam_nf *nf, struct ssam_event_notifier *n)
  9323. +{
  9324. + u16 rqid = ssh_tc_to_rqid(n->event.id.target_category);
  9325. + struct ssam_nf_head *nf_head;
  9326. + int rc, status;
  9327. +
  9328. + if (!ssh_rqid_is_event(rqid))
  9329. + return -EINVAL;
  9330. +
  9331. + nf_head = &nf->head[ssh_rqid_to_event(rqid)];
  9332. +
  9333. + mutex_lock(&nf->lock);
  9334. +
  9335. + rc = ssam_nf_refcount_inc(nf, n->event.reg, n->event.id);
  9336. + if (rc < 0) {
  9337. + mutex_lock(&nf->lock);
  9338. + return rc;
  9339. + }
  9340. +
  9341. + status = __ssam_nfblk_insert(nf_head, &n->base);
  9342. + if (status)
  9343. + ssam_nf_refcount_dec(nf, n->event.reg, n->event.id);
  9344. +
  9345. + mutex_unlock(&nf->lock);
  9346. + return status;
  9347. +}
  9348. +
  9349. +static int ssam_nf_unregister(struct ssam_nf *nf, struct ssam_event_notifier *n)
  9350. +{
  9351. + u16 rqid = ssh_tc_to_rqid(n->event.id.target_category);
  9352. + struct ssam_nf_head *nf_head;
  9353. + int status;
  9354. +
  9355. + if (!ssh_rqid_is_event(rqid))
  9356. + return -EINVAL;
  9357. +
  9358. + nf_head = &nf->head[ssh_rqid_to_event(rqid)];
  9359. +
  9360. + mutex_lock(&nf->lock);
  9361. +
  9362. + status = __ssam_nfblk_remove(nf_head, &n->base);
  9363. + if (status) {
  9364. + mutex_unlock(&nf->lock);
  9365. + return status;
  9366. + }
  9367. +
  9368. + ssam_nf_refcount_dec(nf, n->event.reg, n->event.id);
  9369. +
  9370. + mutex_unlock(&nf->lock);
  9371. + synchronize_srcu(&nf_head->srcu);
  9372. +
  9373. + return 0;
  9374. +}
  9375. +
  9376. +static int ssam_nf_init(struct ssam_nf *nf)
  9377. +{
  9378. + int i, status;
  9379. +
  9380. + for (i = 0; i < SURFACE_SAM_SSH_NUM_EVENTS; i++) {
  9381. + status = ssam_nf_head_init(&nf->head[i]);
  9382. + if (status)
  9383. + break;
  9384. + }
  9385. +
  9386. + if (status) {
  9387. + for (i = i - 1; i >= 0; i--)
  9388. + ssam_nf_head_destroy(&nf->head[i]);
  9389. +
  9390. + return status;
  9391. + }
  9392. +
  9393. + mutex_init(&nf->lock);
  9394. + return 0;
  9395. +}
  9396. +
  9397. +static void ssam_nf_destroy(struct ssam_nf *nf)
  9398. +{
  9399. + int i;
  9400. +
  9401. + for (i = 0; i < SURFACE_SAM_SSH_NUM_EVENTS; i++)
  9402. + ssam_nf_head_destroy(&nf->head[i]);
  9403. +
  9404. + mutex_destroy(&nf->lock);
  9405. +}
  9406. +
  9407. +
  9408. +/* -- Event/async request completion system. -------------------------------- */
  9409. +
  9410. +#define SSAM_CPLT_WQ_NAME "ssam_cpltq"
  9411. +
  9412. +
  9413. +struct ssam_cplt;
  9414. +
  9415. +struct ssam_event_item {
  9416. + struct list_head node;
  9417. + u16 rqid;
  9418. + struct ssam_event event; // must be last
  9419. +};
  9420. +
  9421. +struct ssam_event_queue {
  9422. + struct ssam_cplt *cplt;
  9423. +
  9424. + spinlock_t lock;
  9425. + struct list_head head;
  9426. + struct work_struct work;
  9427. +};
  9428. +
  9429. +struct ssam_event_channel {
  9430. + struct ssam_event_queue queue[SURFACE_SAM_SSH_NUM_EVENTS];
  9431. +};
  9432. +
  9433. +struct ssam_cplt {
  9434. + struct device *dev;
  9435. + struct workqueue_struct *wq;
  9436. +
  9437. + struct {
  9438. + struct ssam_event_channel channel[SURFACE_SAM_SSH_NUM_CHANNELS];
  9439. + struct ssam_nf notif;
  9440. + } event;
  9441. +};
  9442. +
  9443. +
  9444. +static void ssam_event_queue_push(struct ssam_event_queue *q,
  9445. + struct ssam_event_item *item)
  9446. +{
  9447. + spin_lock(&q->lock);
  9448. + list_add_tail(&item->node, &q->head);
  9449. + spin_unlock(&q->lock);
  9450. +}
  9451. +
  9452. +static struct ssam_event_item *ssam_event_queue_pop(struct ssam_event_queue *q)
  9453. +{
  9454. + struct ssam_event_item *item;
  9455. +
  9456. + spin_lock(&q->lock);
  9457. + item = list_first_entry_or_null(&q->head, struct ssam_event_item, node);
  9458. + if (item)
  9459. + list_del(&item->node);
  9460. + spin_unlock(&q->lock);
  9461. +
  9462. + return item;
  9463. +}
  9464. +
  9465. +static bool ssam_event_queue_is_empty(struct ssam_event_queue *q)
  9466. +{
  9467. + bool empty;
  9468. +
  9469. + spin_lock(&q->lock);
  9470. + empty = list_empty(&q->head);
  9471. + spin_unlock(&q->lock);
  9472. +
  9473. + return empty;
  9474. +}
  9475. +
  9476. +static struct ssam_event_queue *ssam_cplt_get_event_queue(
  9477. + struct ssam_cplt *cplt, u8 channel, u16 rqid)
  9478. +{
  9479. + u16 event = ssh_rqid_to_event(rqid);
  9480. + u16 chidx = ssh_channel_to_index(channel);
  9481. +
  9482. + if (!ssh_rqid_is_event(rqid)) {
  9483. + dev_err(cplt->dev, "event: unsupported rqid: 0x%04x\n", rqid);
  9484. + return NULL;
  9485. + }
  9486. +
  9487. + if (!ssh_channel_is_valid(channel)) {
  9488. + dev_warn(cplt->dev, "event: unsupported channel: %u\n",
  9489. + channel);
  9490. + chidx = 0;
  9491. + }
  9492. +
  9493. + return &cplt->event.channel[chidx].queue[event];
  9494. +}
  9495. +
  9496. +static inline bool ssam_cplt_submit(struct ssam_cplt *cplt,
  9497. + struct work_struct *work)
  9498. +{
  9499. + return queue_work(cplt->wq, work);
  9500. +}
  9501. +
  9502. +static int ssam_cplt_submit_event(struct ssam_cplt *cplt,
  9503. + struct ssam_event_item *item)
  9504. +{
  9505. + struct ssam_event_queue *evq;
  9506. +
  9507. + evq = ssam_cplt_get_event_queue(cplt, item->event.channel, item->rqid);
  9508. + if (!evq)
  9509. + return -EINVAL;
  9510. +
  9511. + ssam_event_queue_push(evq, item);
  9512. + ssam_cplt_submit(cplt, &evq->work);
  9513. + return 0;
  9514. +}
  9515. +
  9516. +static void ssam_cplt_flush(struct ssam_cplt *cplt)
  9517. +{
  9518. + flush_workqueue(cplt->wq);
  9519. +}
  9520. +
  9521. +static void ssam_event_queue_work_fn(struct work_struct *work)
  9522. +{
  9523. + struct ssam_event_queue *queue;
  9524. + struct ssam_event_item *item;
  9525. + struct ssam_nf *nf;
  9526. + struct device *dev;
  9527. + int i;
  9528. +
  9529. + queue = container_of(work, struct ssam_event_queue, work);
  9530. + nf = &queue->cplt->event.notif;
  9531. + dev = queue->cplt->dev;
  9532. +
  9533. + for (i = 0; i < 10; i++) {
  9534. + item = ssam_event_queue_pop(queue);
  9535. + if (item == NULL)
  9536. + return;
  9537. +
  9538. + ssam_nf_call(nf, dev, item->rqid, &item->event);
  9539. + kfree(item);
  9540. + }
  9541. +
  9542. + if (!ssam_event_queue_is_empty(queue))
  9543. + ssam_cplt_submit(queue->cplt, &queue->work);
  9544. +}
  9545. +
  9546. +static void ssam_event_queue_init(struct ssam_cplt *cplt,
  9547. + struct ssam_event_queue *evq)
  9548. +{
  9549. + evq->cplt = cplt;
  9550. + spin_lock_init(&evq->lock);
  9551. + INIT_LIST_HEAD(&evq->head);
  9552. + INIT_WORK(&evq->work, ssam_event_queue_work_fn);
  9553. +}
  9554. +
  9555. +static int ssam_cplt_init(struct ssam_cplt *cplt, struct device *dev)
  9556. +{
  9557. + struct ssam_event_channel *channel;
  9558. + int status, c, i;
  9559. +
  9560. + cplt->dev = dev;
  9561. +
  9562. + cplt->wq = create_workqueue(SSAM_CPLT_WQ_NAME);
  9563. + if (!cplt->wq)
  9564. + return -ENOMEM;
  9565. +
  9566. + for (c = 0; c < ARRAY_SIZE(cplt->event.channel); c++) {
  9567. + channel = &cplt->event.channel[c];
  9568. +
  9569. + for (i = 0; i < ARRAY_SIZE(channel->queue); i++)
  9570. + ssam_event_queue_init(cplt, &channel->queue[i]);
  9571. + }
  9572. +
  9573. + status = ssam_nf_init(&cplt->event.notif);
  9574. + if (status)
  9575. + destroy_workqueue(cplt->wq);
  9576. +
  9577. + return status;
  9578. +}
  9579. +
  9580. +static void ssam_cplt_destroy(struct ssam_cplt *cplt)
  9581. +{
  9582. + destroy_workqueue(cplt->wq);
  9583. + ssam_nf_destroy(&cplt->event.notif);
  9584. +}
  9585. +
  9586. +
  9587. +/* -- Top-Level Request Interface ------------------------------------------- */
  9588. +
  9589. +struct ssam_response {
  9590. + int status;
  9591. + u16 capacity;
  9592. + u16 length;
  9593. + u8 *pointer;
  9594. +};
  9595. +
  9596. +struct ssam_request_sync {
  9597. + struct ssh_request base;
  9598. + struct completion comp;
  9599. + struct ssam_response resp;
  9600. +};
  9601. +
  9602. +
  9603. +static void ssam_request_sync_complete(struct ssh_request *rqst,
  9604. + const struct ssh_command *cmd,
  9605. + const struct sshp_span *data, int status)
  9606. +{
  9607. + struct ssam_request_sync *r;
  9608. + struct ssh_rtl *rtl = READ_ONCE(rqst->rtl);
  9609. +
  9610. + r = container_of(rqst, struct ssam_request_sync, base);
  9611. + r->resp.status = status;
  9612. + r->resp.length = 0;
  9613. +
  9614. + if (status) {
  9615. + rtl_dbg_cond(rtl, "rsp: request failed: %d\n", status);
  9616. + return;
  9617. + }
  9618. +
  9619. + if (!data) // handle requests without a response
  9620. + return;
  9621. +
  9622. + if (!r->resp.pointer && data->len) {
  9623. + rtl_warn(rtl, "rsp: no response buffer provided, dropping data\n");
  9624. + return;
  9625. + }
  9626. +
  9627. + if (data->len > r->resp.capacity) {
  9628. + rtl_err(rtl, "rsp: response buffer too small,"
  9629. + " capacity: %u bytes, got: %zu bytes\n",
  9630. + r->resp.capacity, data->len);
  9631. + r->resp.status = -ENOSPC;
  9632. + return;
  9633. + }
  9634. +
  9635. + r->resp.length = data->len;
  9636. + memcpy(r->resp.pointer, data->ptr, data->len);
  9637. +}
  9638. +
  9639. +static void ssam_request_sync_release(struct ssh_request *rqst)
  9640. +{
  9641. + complete_all(&container_of(rqst, struct ssam_request_sync, base)->comp);
  9642. +}
  9643. +
  9644. +static const struct ssh_request_ops ssam_request_sync_ops = {
  9645. + .release = ssam_request_sync_release,
  9646. + .complete = ssam_request_sync_complete,
  9647. +};
  9648. +
  9649. +static void ssam_request_sync_wait_complete(struct ssam_request_sync *rqst)
  9650. +{
  9651. + wait_for_completion(&rqst->comp);
  9652. +}
  9653. +
  9654. +
  9655. +/* -- TODO ------------------------------------------------------------------ */
  9656. +
  9657. +enum ssh_ec_state {
  9658. + SSH_EC_UNINITIALIZED,
  9659. + SSH_EC_INITIALIZED,
  9660. + SSH_EC_SUSPENDED,
  9661. +};
  9662. +
  9663. +struct sam_ssh_ec {
  9664. + struct serdev_device *serdev;
  9665. +
  9666. + struct ssh_rtl rtl;
  9667. + struct ssam_cplt cplt;
  9668. +
  9669. + struct {
  9670. + struct ssh_seq_counter seq;
  9671. + struct ssh_rqid_counter rqid;
  9672. + } counter;
  9673. +
  9674. + enum ssh_ec_state state;
  9675. +
  9676. + int irq;
  9677. + bool irq_wakeup_enabled;
  9678. +};
  9679. +
  9680. +static struct sam_ssh_ec ssh_ec = {
  9681. + .state = SSH_EC_UNINITIALIZED,
  9682. + .serdev = NULL,
  9683. +};
  9684. +
  9685. +
  9686. +/* -- TODO ------------------------------------------------------------------ */
  9687. +
  9688. +#define ssh_dbg(ec, fmt, ...) dev_dbg(&(ec)->serdev->dev, fmt, ##__VA_ARGS__)
  9689. +#define ssh_warn(ec, fmt, ...) dev_warn(&(ec)->serdev->dev, fmt, ##__VA_ARGS__)
  9690. +#define ssh_err(ec, fmt, ...) dev_err(&(ec)->serdev->dev, fmt, ##__VA_ARGS__)
  9691. +
  9692. +
  9693. +static inline struct sam_ssh_ec *surface_sam_ssh_acquire(void)
  9694. +{
  9695. + return &ssh_ec;
  9696. +}
  9697. +
  9698. +static inline struct sam_ssh_ec *surface_sam_ssh_acquire_init(void)
  9699. +{
  9700. + struct sam_ssh_ec *ec = surface_sam_ssh_acquire();
  9701. +
  9702. + if (smp_load_acquire(&ec->state) == SSH_EC_UNINITIALIZED)
  9703. + return NULL;
  9704. +
  9705. + return ec;
  9706. +}
  9707. +
  9708. +int surface_sam_ssh_consumer_register(struct device *consumer)
  9709. +{
  9710. + u32 flags = DL_FLAG_PM_RUNTIME | DL_FLAG_AUTOREMOVE_CONSUMER;
  9711. + struct sam_ssh_ec *ec;
  9712. + struct device_link *link;
  9713. +
  9714. + ec = surface_sam_ssh_acquire_init();
  9715. + if (!ec)
  9716. + return -ENXIO;
  9717. +
  9718. + link = device_link_add(consumer, &ec->serdev->dev, flags);
  9719. + if (!link)
  9720. + return -EFAULT;
  9721. +
  9722. + return 0;
  9723. +}
  9724. +EXPORT_SYMBOL_GPL(surface_sam_ssh_consumer_register);
  9725. +
  9726. +
  9727. +static int __surface_sam_ssh_rqst(struct sam_ssh_ec *ec,
  9728. + const struct surface_sam_ssh_rqst *rqst,
  9729. + struct surface_sam_ssh_buf *result);
  9730. +
  9731. +static int surface_sam_ssh_event_enable(struct sam_ssh_ec *ec,
  9732. + struct ssam_event_registry reg,
  9733. + struct ssam_event_id id,
  9734. + u8 flags)
  9735. +{
  9736. + struct ssh_notification_params params;
  9737. + struct surface_sam_ssh_rqst rqst;
  9738. + struct surface_sam_ssh_buf result;
  9739. +
  9740. + u16 rqid = ssh_tc_to_rqid(id.target_category);
  9741. + u8 buf[1] = { 0x00 };
  9742. + int status;
  9743. +
  9744. + // only allow RQIDs that lie within event spectrum
  9745. + if (!ssh_rqid_is_event(rqid))
  9746. + return -EINVAL;
  9747. +
  9748. + params.target_category = id.target_category;
  9749. + params.instance_id = id.instance;
  9750. + params.flags = flags;
  9751. + put_unaligned_le16(rqid, &params.request_id);
  9752. +
  9753. + rqst.tc = reg.target_category;
  9754. + rqst.cid = reg.cid_enable;
  9755. + rqst.iid = 0x00;
  9756. + rqst.chn = reg.channel;
  9757. + rqst.snc = 0x01;
  9758. + rqst.cdl = sizeof(params);
  9759. + rqst.pld = (u8 *)&params;
  9760. +
  9761. + result.cap = ARRAY_SIZE(buf);
  9762. + result.len = 0;
  9763. + result.data = buf;
  9764. +
  9765. + status = __surface_sam_ssh_rqst(ec, &rqst, &result);
  9766. +
  9767. + if (status) {
  9768. + dev_err(&ec->serdev->dev, "failed to enable event source"
  9769. + " (tc: 0x%02x, rqid: 0x%04x)\n",
  9770. + id.target_category, rqid);
  9771. + }
  9772. +
  9773. + if (buf[0] != 0x00) {
  9774. + pr_warn(SSH_RQST_TAG_FULL
  9775. + "unexpected result while enabling event source: "
  9776. + "0x%02x\n", buf[0]);
  9777. + }
  9778. +
  9779. + return status;
  9780. +
  9781. +}
  9782. +
  9783. +static int surface_sam_ssh_event_disable(struct sam_ssh_ec *ec,
  9784. + struct ssam_event_registry reg,
  9785. + struct ssam_event_id id,
  9786. + u8 flags)
  9787. +{
  9788. + struct ssh_notification_params params;
  9789. + struct surface_sam_ssh_rqst rqst;
  9790. + struct surface_sam_ssh_buf result;
  9791. +
  9792. + u16 rqid = ssh_tc_to_rqid(id.target_category);
  9793. + u8 buf[1] = { 0x00 };
  9794. + int status;
  9795. +
  9796. + // only allow RQIDs that lie within event spectrum
  9797. + if (!ssh_rqid_is_event(rqid))
  9798. + return -EINVAL;
  9799. +
  9800. + params.target_category = id.target_category;
  9801. + params.instance_id = id.instance;
  9802. + params.flags = flags;
  9803. + put_unaligned_le16(rqid, &params.request_id);
  9804. +
  9805. + rqst.tc = reg.target_category;
  9806. + rqst.cid = reg.cid_disable;
  9807. + rqst.iid = 0x00;
  9808. + rqst.chn = reg.channel;
  9809. + rqst.snc = 0x01;
  9810. + rqst.cdl = sizeof(params);
  9811. + rqst.pld = (u8 *)&params;
  9812. +
  9813. + result.cap = ARRAY_SIZE(buf);
  9814. + result.len = 0;
  9815. + result.data = buf;
  9816. +
  9817. + status = __surface_sam_ssh_rqst(ec, &rqst, &result);
  9818. +
  9819. + if (status) {
  9820. + dev_err(&ec->serdev->dev, "failed to disable event source"
  9821. + " (tc: 0x%02x, rqid: 0x%04x)\n",
  9822. + id.target_category, rqid);
  9823. + }
  9824. +
  9825. + if (buf[0] != 0x00) {
  9826. + dev_warn(&ec->serdev->dev,
  9827. + "unexpected result while disabling event source: "
  9828. + "0x%02x\n", buf[0]);
  9829. + }
  9830. +
  9831. + return status;
  9832. +}
  9833. +
  9834. +
  9835. +int surface_sam_ssh_notifier_register(struct ssam_event_notifier *n)
  9836. +{
  9837. + struct ssam_nf_head *nf_head;
  9838. + struct sam_ssh_ec *ec;
  9839. + struct ssam_nf *nf;
  9840. + u16 event = ssh_tc_to_event(n->event.id.target_category);
  9841. + u16 rqid = ssh_event_to_rqid(event);
  9842. + int rc, status;
  9843. +
  9844. + if (!ssh_rqid_is_event(rqid))
  9845. + return -EINVAL;
  9846. +
  9847. + ec = surface_sam_ssh_acquire_init();
  9848. + if (!ec)
  9849. + return -ENXIO;
  9850. +
  9851. + nf = &ec->cplt.event.notif;
  9852. + nf_head = &nf->head[event];
  9853. +
  9854. + mutex_lock(&nf->lock);
  9855. +
  9856. + rc = ssam_nf_refcount_inc(nf, n->event.reg, n->event.id);
  9857. + if (rc < 0) {
  9858. + mutex_unlock(&nf->lock);
  9859. + return rc;
  9860. + }
  9861. +
  9862. + ssh_dbg(ec, "enabling event (tc: 0x%02x, rc: %d)\n", rqid, rc);
  9863. +
  9864. + status = __ssam_nfblk_insert(nf_head, &n->base);
  9865. + if (status) {
  9866. + ssam_nf_refcount_dec(nf, n->event.reg, n->event.id);
  9867. + mutex_unlock(&nf->lock);
  9868. + return status;
  9869. + }
  9870. +
  9871. + if (rc == 1) {
  9872. + status = surface_sam_ssh_event_enable(ec, n->event.reg, n->event.id, n->event.flags);
  9873. + if (status) {
  9874. + __ssam_nfblk_remove(nf_head, &n->base);
  9875. + ssam_nf_refcount_dec(nf, n->event.reg, n->event.id);
  9876. + mutex_unlock(&nf->lock);
  9877. + return status;
  9878. + }
  9879. + }
  9880. +
  9881. + mutex_unlock(&nf->lock);
  9882. + return 0;
  9883. +}
  9884. +EXPORT_SYMBOL_GPL(surface_sam_ssh_notifier_register);
  9885. +
  9886. +int surface_sam_ssh_notifier_unregister(struct ssam_event_notifier *n)
  9887. +{
  9888. + struct ssam_nf_head *nf_head;
  9889. + struct sam_ssh_ec *ec;
  9890. + struct ssam_nf *nf;
  9891. + u16 event = ssh_tc_to_event(n->event.id.target_category);
  9892. + u16 rqid = ssh_event_to_rqid(event);
  9893. + int rc, status = 0;
  9894. +
  9895. + if (!ssh_rqid_is_event(rqid))
  9896. + return -EINVAL;
  9897. +
  9898. + ec = surface_sam_ssh_acquire_init();
  9899. + if (!ec)
  9900. + return -ENXIO;
  9901. +
  9902. + nf = &ec->cplt.event.notif;
  9903. + nf_head = &nf->head[event];
  9904. +
  9905. + mutex_lock(&nf->lock);
  9906. +
  9907. + rc = ssam_nf_refcount_dec(nf, n->event.reg, n->event.id);
  9908. + if (rc < 0) {
  9909. + mutex_unlock(&nf->lock);
  9910. + return rc;
  9911. + }
  9912. +
  9913. + ssh_dbg(ec, "disabling event (tc: 0x%02x, rc: %d)\n", rqid, rc);
  9914. +
  9915. + if (rc == 0)
  9916. + status = surface_sam_ssh_event_disable(ec, n->event.reg, n->event.id, n->event.flags);
  9917. +
  9918. + __ssam_nfblk_remove(nf_head, &n->base);
  9919. + mutex_unlock(&nf->lock);
  9920. + synchronize_srcu(&nf_head->srcu);
  9921. +
  9922. + return status;
  9923. +}
  9924. +EXPORT_SYMBOL_GPL(surface_sam_ssh_notifier_unregister);
  9925. +
  9926. +
  9927. +static int __surface_sam_ssh_rqst(struct sam_ssh_ec *ec,
  9928. + const struct surface_sam_ssh_rqst *rqst,
  9929. + struct surface_sam_ssh_buf *result)
  9930. +{
  9931. + struct ssam_request_sync actual;
  9932. + struct msgbuf msgb;
  9933. + size_t msglen = SSH_COMMAND_MESSAGE_LENGTH(rqst->cdl);
  9934. + unsigned flags = 0;
  9935. + u16 rqid;
  9936. + u8 seq;
  9937. + int status;
  9938. +
  9939. + // prevent overflow
  9940. + if (rqst->cdl > SSH_COMMAND_MAX_PAYLOAD_SIZE) {
  9941. + ssh_err(ec, SSH_RQST_TAG "request payload too large\n");
  9942. + return -EINVAL;
  9943. + }
  9944. +
  9945. + if (result && result->data && rqst->snc)
  9946. + flags |= SSAM_REQUEST_HAS_RESPONSE;
  9947. +
  9948. + ssh_request_init(&actual.base, flags, &ssam_request_sync_ops);
  9949. + init_completion(&actual.comp);
  9950. +
  9951. + actual.resp.pointer = NULL;
  9952. + actual.resp.capacity = 0;
  9953. + actual.resp.length = 0;
  9954. + actual.resp.status = 0;
  9955. +
  9956. + if (result) {
  9957. + actual.resp.pointer = result->data;
  9958. + actual.resp.capacity = result->cap;
  9959. + }
  9960. +
  9961. + // alloc and create message
  9962. + status = msgb_alloc(&msgb, msglen, GFP_KERNEL);
  9963. + if (status)
  9964. + return status;
  9965. +
  9966. + seq = ssh_seq_next(&ec->counter.seq);
  9967. + rqid = ssh_rqid_next(&ec->counter.rqid);
  9968. + msgb_push_cmd(&msgb, seq, rqst, rqid);
  9969. +
  9970. + actual.base.packet.data = msgb.buffer;
  9971. + actual.base.packet.data_length = msgb.ptr - msgb.buffer;
  9972. +
  9973. + status = ssh_rtl_submit(&ec->rtl, &actual.base);
  9974. + if (status) {
  9975. + msgb_free(&msgb);
  9976. + return status;
  9977. + }
  9978. +
  9979. + ssh_request_put(&actual.base);
  9980. + ssam_request_sync_wait_complete(&actual);
  9981. + msgb_free(&msgb);
  9982. +
  9983. + if (result)
  9984. + result->len = actual.resp.length;
  9985. +
  9986. + return actual.resp.status;
  9987. +}
  9988. +
  9989. +int surface_sam_ssh_rqst(const struct surface_sam_ssh_rqst *rqst, struct surface_sam_ssh_buf *result)
  9990. +{
  9991. + struct sam_ssh_ec *ec;
  9992. +
  9993. + ec = surface_sam_ssh_acquire_init();
  9994. + if (!ec) {
  9995. + pr_warn(SSH_RQST_TAG_FULL "embedded controller is uninitialized\n");
  9996. + return -ENXIO;
  9997. + }
  9998. +
  9999. + if (smp_load_acquire(&ec->state) == SSH_EC_SUSPENDED) {
  10000. + ssh_warn(ec, SSH_RQST_TAG "embedded controller is suspended\n");
  10001. + return -EPERM;
  10002. + }
  10003. +
  10004. + return __surface_sam_ssh_rqst(ec, rqst, result);
  10005. +}
  10006. +EXPORT_SYMBOL_GPL(surface_sam_ssh_rqst);
  10007. +
  10008. +
  10009. +/**
  10010. + * surface_sam_ssh_ec_resume - Resume the EC if it is in a suspended mode.
  10011. + * @ec: the EC to resume
  10012. + *
  10013. + * Moves the EC from a suspended state to a normal state. See the
  10014. + * `surface_sam_ssh_ec_suspend` function what the specific differences of
  10015. + * these states are. Multiple repeated calls to this function seem to be
  10016. + * handled fine by the EC, after the first call, the state will remain
  10017. + * "normal".
  10018. + *
  10019. + * Must be called with the EC initialized and its lock held.
  10020. + */
  10021. +static int surface_sam_ssh_ec_resume(struct sam_ssh_ec *ec)
  10022. +{
  10023. + u8 buf[1] = { 0x00 };
  10024. + int status;
  10025. +
  10026. + struct surface_sam_ssh_rqst rqst = {
  10027. + .tc = 0x01,
  10028. + .cid = 0x16,
  10029. + .iid = 0x00,
  10030. + .chn = 0x01,
  10031. + .snc = 0x01,
  10032. + .cdl = 0x00,
  10033. + .pld = NULL,
  10034. + };
  10035. +
  10036. + struct surface_sam_ssh_buf result = {
  10037. + result.cap = ARRAY_SIZE(buf),
  10038. + result.len = 0,
  10039. + result.data = buf,
  10040. + };
  10041. +
  10042. + ssh_dbg(ec, "pm: resuming system aggregator module\n");
  10043. + status = __surface_sam_ssh_rqst(ec, &rqst, &result);
  10044. + if (status)
  10045. + return status;
  10046. +
  10047. + /*
  10048. + * The purpose of the return value of this request is unknown. Based on
  10049. + * logging and experience, we expect it to be zero. No other value has
  10050. + * been observed so far.
  10051. + */
  10052. + if (buf[0] != 0x00) {
  10053. + ssh_warn(ec, "unexpected result while trying to resume EC: "
  10054. + "0x%02x\n", buf[0]);
  10055. + }
  10056. +
  10057. + return 0;
  10058. +}
  10059. +
  10060. +/**
  10061. + * surface_sam_ssh_ec_suspend - Put the EC in a suspended mode:
  10062. + * @ec: the EC to suspend
  10063. + *
  10064. + * Tells the EC to enter a suspended mode. In this mode, events are quiesced
  10065. + * and the wake IRQ is armed (note that the wake IRQ does not fire if the EC
  10066. + * has not been suspended via this request). On some devices, the keyboard
  10067. + * backlight is turned off. Apart from this, the EC seems to continue to work
  10068. + * as normal, meaning requests sent to it are acknowledged and seem to be
  10069. + * correctly handled, including potential responses. Multiple repeated calls
  10070. + * to this function seem to be handled fine by the EC, after the first call,
  10071. + * the state will remain "suspended".
  10072. + *
  10073. + * Must be called with the EC initialized and its lock held.
  10074. + */
  10075. +static int surface_sam_ssh_ec_suspend(struct sam_ssh_ec *ec)
  10076. +{
  10077. + u8 buf[1] = { 0x00 };
  10078. + int status;
  10079. +
  10080. + struct surface_sam_ssh_rqst rqst = {
  10081. + .tc = 0x01,
  10082. + .cid = 0x15,
  10083. + .iid = 0x00,
  10084. + .chn = 0x01,
  10085. + .snc = 0x01,
  10086. + .cdl = 0x00,
  10087. + .pld = NULL,
  10088. + };
  10089. +
  10090. + struct surface_sam_ssh_buf result = {
  10091. + result.cap = ARRAY_SIZE(buf),
  10092. + result.len = 0,
  10093. + result.data = buf,
  10094. + };
  10095. +
  10096. + ssh_dbg(ec, "pm: suspending system aggregator module\n");
  10097. + status = __surface_sam_ssh_rqst(ec, &rqst, &result);
  10098. + if (status)
  10099. + return status;
  10100. +
  10101. + /*
  10102. + * The purpose of the return value of this request is unknown. Based on
  10103. + * logging and experience, we expect it to be zero. No other value has
  10104. + * been observed so far.
  10105. + */
  10106. + if (buf[0] != 0x00) {
  10107. + ssh_warn(ec, "unexpected result while trying to suspend EC: "
  10108. + "0x%02x\n", buf[0]);
  10109. + }
  10110. +
  10111. + return 0;
  10112. +}
  10113. +
  10114. +
  10115. +static int surface_sam_ssh_get_controller_version(struct sam_ssh_ec *ec, u32 *version)
  10116. +{
  10117. + struct surface_sam_ssh_rqst rqst = {
  10118. + .tc = 0x01,
  10119. + .cid = 0x13,
  10120. + .iid = 0x00,
  10121. + .chn = 0x01,
  10122. + .snc = 0x01,
  10123. + .cdl = 0x00,
  10124. + .pld = NULL,
  10125. + };
  10126. +
  10127. + struct surface_sam_ssh_buf result = {
  10128. + result.cap = sizeof(*version),
  10129. + result.len = 0,
  10130. + result.data = (u8 *)version,
  10131. + };
  10132. +
  10133. + *version = 0;
  10134. + return __surface_sam_ssh_rqst(ec, &rqst, &result);
  10135. +}
  10136. +
  10137. +static int surface_sam_ssh_log_controller_version(struct sam_ssh_ec *ec)
  10138. +{
  10139. + u32 version, a, b, c;
  10140. + int status;
  10141. +
  10142. + status = surface_sam_ssh_get_controller_version(ec, &version);
  10143. + if (status)
  10144. + return status;
  10145. +
  10146. + a = (version >> 24) & 0xff;
  10147. + b = le16_to_cpu((version >> 8) & 0xffff);
  10148. + c = version & 0xff;
  10149. +
  10150. + dev_info(&ec->serdev->dev, "SAM controller version: %u.%u.%u\n",
  10151. + a, b, c);
  10152. + return 0;
  10153. +}
  10154. +
  10155. +
  10156. +static const struct acpi_gpio_params gpio_ssh_wakeup_int = { 0, 0, false };
  10157. +static const struct acpi_gpio_params gpio_ssh_wakeup = { 1, 0, false };
  10158. +
  10159. +static const struct acpi_gpio_mapping ssh_acpi_gpios[] = {
  10160. + { "ssh_wakeup-int-gpio", &gpio_ssh_wakeup_int, 1 },
  10161. + { "ssh_wakeup-gpio", &gpio_ssh_wakeup, 1 },
  10162. + { },
  10163. +};
  10164. +
  10165. +static irqreturn_t ssh_wake_irq_handler(int irq, void *dev_id)
  10166. +{
  10167. + struct serdev_device *serdev = dev_id;
  10168. +
  10169. + dev_dbg(&serdev->dev, "pm: wake irq triggered\n");
  10170. +
  10171. + // TODO: Send GPIO callback command repeatedly to EC until callback
  10172. + // returns 0x00. Return flag of callback is "has more events".
  10173. + // Each time the command is sent, one event is "released". Once
  10174. + // all events have been released (return = 0x00), the GPIO is
  10175. + // re-armed.
  10176. +
  10177. + return IRQ_HANDLED;
  10178. +}
  10179. +
  10180. +static int ssh_setup_irq(struct serdev_device *serdev)
  10181. +{
  10182. + const int irqf = IRQF_SHARED | IRQF_ONESHOT | IRQF_TRIGGER_RISING;
  10183. + struct gpio_desc *gpiod;
  10184. + int irq;
  10185. + int status;
  10186. +
  10187. + gpiod = gpiod_get(&serdev->dev, "ssh_wakeup-int", GPIOD_ASIS);
  10188. + if (IS_ERR(gpiod))
  10189. + return PTR_ERR(gpiod);
  10190. +
  10191. + irq = gpiod_to_irq(gpiod);
  10192. + gpiod_put(gpiod);
  10193. +
  10194. + if (irq < 0)
  10195. + return irq;
  10196. +
  10197. + status = request_threaded_irq(irq, NULL, ssh_wake_irq_handler,
  10198. + irqf, "surface_sam_sh_wakeup", serdev);
  10199. + if (status)
  10200. + return status;
  10201. +
  10202. + return irq;
  10203. +}
  10204. +
  10205. +
  10206. +static acpi_status ssh_setup_from_resource(struct acpi_resource *rsc, void *ctx)
  10207. +{
  10208. + struct serdev_device *serdev = ctx;
  10209. + struct acpi_resource_common_serialbus *serial;
  10210. + struct acpi_resource_uart_serialbus *uart;
  10211. + bool flow_control;
  10212. + int status = 0;
  10213. +
  10214. + if (rsc->type != ACPI_RESOURCE_TYPE_SERIAL_BUS)
  10215. + return AE_OK;
  10216. +
  10217. + serial = &rsc->data.common_serial_bus;
  10218. + if (serial->type != ACPI_RESOURCE_SERIAL_TYPE_UART)
  10219. + return AE_OK;
  10220. +
  10221. + uart = &rsc->data.uart_serial_bus;
  10222. +
  10223. + // set up serdev device
  10224. + serdev_device_set_baudrate(serdev, uart->default_baud_rate);
  10225. +
  10226. + // serdev currently only supports RTSCTS flow control
  10227. + if (uart->flow_control & SSH_SUPPORTED_FLOW_CONTROL_MASK) {
  10228. + dev_warn(&serdev->dev, "setup: unsupported flow control"
  10229. + " (value: 0x%02x)\n", uart->flow_control);
  10230. + }
  10231. +
  10232. + // set RTSCTS flow control
  10233. + flow_control = uart->flow_control & ACPI_UART_FLOW_CONTROL_HW;
  10234. + serdev_device_set_flow_control(serdev, flow_control);
  10235. +
  10236. + // serdev currently only supports EVEN/ODD parity
  10237. + switch (uart->parity) {
  10238. + case ACPI_UART_PARITY_NONE:
  10239. + status = serdev_device_set_parity(serdev, SERDEV_PARITY_NONE);
  10240. + break;
  10241. + case ACPI_UART_PARITY_EVEN:
  10242. + status = serdev_device_set_parity(serdev, SERDEV_PARITY_EVEN);
  10243. + break;
  10244. + case ACPI_UART_PARITY_ODD:
  10245. + status = serdev_device_set_parity(serdev, SERDEV_PARITY_ODD);
  10246. + break;
  10247. + default:
  10248. + dev_warn(&serdev->dev, "setup: unsupported parity"
  10249. + " (value: 0x%02x)\n", uart->parity);
  10250. + break;
  10251. + }
  10252. +
  10253. + if (status) {
  10254. + dev_err(&serdev->dev, "setup: failed to set parity"
  10255. + " (value: 0x%02x)\n", uart->parity);
  10256. + return status;
  10257. + }
  10258. +
  10259. + return AE_CTRL_TERMINATE; // we've found the resource and are done
  10260. +}
  10261. +
  10262. +
  10263. +static int surface_sam_ssh_suspend(struct device *dev)
  10264. +{
  10265. + struct sam_ssh_ec *ec;
  10266. + int status;
  10267. +
  10268. + dev_dbg(dev, "pm: suspending\n");
  10269. +
  10270. + ec = surface_sam_ssh_acquire_init();
  10271. + if (ec) {
  10272. + status = surface_sam_ssh_ec_suspend(ec);
  10273. + if (status)
  10274. + return status;
  10275. +
  10276. + if (device_may_wakeup(dev)) {
  10277. + status = enable_irq_wake(ec->irq);
  10278. + if (status)
  10279. + return status;
  10280. +
  10281. + ec->irq_wakeup_enabled = true;
  10282. + } else {
  10283. + ec->irq_wakeup_enabled = false;
  10284. + }
  10285. +
  10286. + smp_store_release(&ec->state, SSH_EC_SUSPENDED);
  10287. + }
  10288. +
  10289. + return 0;
  10290. +}
  10291. +
  10292. +static int surface_sam_ssh_resume(struct device *dev)
  10293. +{
  10294. + struct sam_ssh_ec *ec;
  10295. + int status;
  10296. +
  10297. + dev_dbg(dev, "pm: resuming\n");
  10298. +
  10299. + ec = surface_sam_ssh_acquire_init();
  10300. + if (ec) {
  10301. + smp_store_release(&ec->state, SSH_EC_INITIALIZED);
  10302. +
  10303. + if (ec->irq_wakeup_enabled) {
  10304. + status = disable_irq_wake(ec->irq);
  10305. + if (status)
  10306. + return status;
  10307. +
  10308. + ec->irq_wakeup_enabled = false;
  10309. + }
  10310. +
  10311. + status = surface_sam_ssh_ec_resume(ec);
  10312. + if (status)
  10313. + return status;
  10314. + }
  10315. +
  10316. + return 0;
  10317. +}
  10318. +
  10319. +static SIMPLE_DEV_PM_OPS(surface_sam_ssh_pm_ops, surface_sam_ssh_suspend,
  10320. + surface_sam_ssh_resume);
  10321. +
  10322. +
  10323. +static void ssam_handle_event(struct ssh_rtl *rtl,
  10324. + const struct ssh_command *cmd,
  10325. + const struct sshp_span *data)
  10326. +{
  10327. + struct sam_ssh_ec *ec = container_of(rtl, struct sam_ssh_ec, rtl);
  10328. + struct ssam_event_item *item;
  10329. +
  10330. + item = kzalloc(sizeof(struct ssam_event_item) + data->len, GFP_KERNEL);
  10331. + if (!item)
  10332. + return;
  10333. +
  10334. + item->rqid = get_unaligned_le16(&cmd->rqid);
  10335. + item->event.target_category = cmd->tc;
  10336. + item->event.command_id = cmd->cid;
  10337. + item->event.instance_id = cmd->iid;
  10338. + item->event.channel = cmd->chn_in;
  10339. + item->event.length = data->len;
  10340. + memcpy(&item->event.data[0], data->ptr, data->len);
  10341. +
  10342. + ssam_cplt_submit_event(&ec->cplt, item);
  10343. +}
  10344. +
  10345. +static struct ssh_rtl_ops ssam_rtl_ops = {
  10346. + .handle_event = ssam_handle_event,
  10347. +};
  10348. +
  10349. +
  10350. +static int ssam_receive_buf(struct serdev_device *dev, const unsigned char *buf, size_t n)
  10351. +{
  10352. + struct sam_ssh_ec *ec = serdev_device_get_drvdata(dev);
  10353. + return ssh_ptl_rx_rcvbuf(&ec->rtl.ptl, buf, n);
  10354. +}
  10355. +
  10356. +static void ssam_write_wakeup(struct serdev_device *dev)
  10357. +{
  10358. + struct sam_ssh_ec *ec = serdev_device_get_drvdata(dev);
  10359. + ssh_ptl_tx_wakeup(&ec->rtl.ptl, true);
  10360. +}
  10361. +
  10362. +struct serdev_device_ops ssam_serdev_ops = {
  10363. + .receive_buf = ssam_receive_buf,
  10364. + .write_wakeup = ssam_write_wakeup,
  10365. +};
  10366. +
  10367. +
  10368. +#ifdef CONFIG_SURFACE_SAM_SSH_DEBUG_DEVICE
  10369. +
  10370. +static char sam_ssh_debug_rqst_buf_sysfs[256] = { 0 };
  10371. +static char sam_ssh_debug_rqst_buf_pld[255] = { 0 };
  10372. +static char sam_ssh_debug_rqst_buf_res[255] = { 0 };
  10373. +
  10374. +struct sysfs_rqst {
  10375. + u8 tc;
  10376. + u8 cid;
  10377. + u8 iid;
  10378. + u8 chn;
  10379. + u8 snc;
  10380. + u8 cdl;
  10381. + u8 pld[0];
  10382. +} __packed;
  10383. +
  10384. +static ssize_t rqst_read(struct file *f, struct kobject *kobj, struct bin_attribute *attr,
  10385. + char *buf, loff_t offs, size_t count)
  10386. +{
  10387. + if (offs < 0 || count + offs > ARRAY_SIZE(sam_ssh_debug_rqst_buf_sysfs))
  10388. + return -EINVAL;
  10389. +
  10390. + memcpy(buf, sam_ssh_debug_rqst_buf_sysfs + offs, count);
  10391. + return count;
  10392. +}
  10393. +
  10394. +static ssize_t rqst_write(struct file *f, struct kobject *kobj, struct bin_attribute *attr,
  10395. + char *buf, loff_t offs, size_t count)
  10396. +{
  10397. + struct sysfs_rqst *input;
  10398. + struct surface_sam_ssh_rqst rqst = {};
  10399. + struct surface_sam_ssh_buf result = {};
  10400. + int status;
  10401. +
  10402. + // check basic write constriants
  10403. + if (offs != 0 || count - sizeof(struct sysfs_rqst) > ARRAY_SIZE(sam_ssh_debug_rqst_buf_pld))
  10404. + return -EINVAL;
  10405. +
  10406. + if (count < sizeof(struct sysfs_rqst))
  10407. + return -EINVAL;
  10408. +
  10409. + input = (struct sysfs_rqst *)buf;
  10410. +
  10411. + // payload length should be consistent with data provided
  10412. + if (input->cdl + sizeof(struct sysfs_rqst) != count)
  10413. + return -EINVAL;
  10414. +
  10415. + rqst.tc = input->tc;
  10416. + rqst.cid = input->cid;
  10417. + rqst.iid = input->iid;
  10418. + rqst.chn = input->chn;
  10419. + rqst.snc = input->snc;
  10420. + rqst.cdl = input->cdl;
  10421. + rqst.pld = sam_ssh_debug_rqst_buf_pld;
  10422. + memcpy(sam_ssh_debug_rqst_buf_pld, &input->pld[0], input->cdl);
  10423. +
  10424. + result.cap = ARRAY_SIZE(sam_ssh_debug_rqst_buf_res);
  10425. + result.len = 0;
  10426. + result.data = sam_ssh_debug_rqst_buf_res;
  10427. +
  10428. + status = surface_sam_ssh_rqst(&rqst, &result);
  10429. + if (status)
  10430. + return status;
  10431. +
  10432. + sam_ssh_debug_rqst_buf_sysfs[0] = result.len;
  10433. + memcpy(sam_ssh_debug_rqst_buf_sysfs + 1, result.data, result.len);
  10434. + memset(sam_ssh_debug_rqst_buf_sysfs + result.len + 1, 0,
  10435. + ARRAY_SIZE(sam_ssh_debug_rqst_buf_sysfs) + 1 - result.len);
  10436. +
  10437. + return count;
  10438. +}
  10439. +
  10440. +static const BIN_ATTR_RW(rqst, ARRAY_SIZE(sam_ssh_debug_rqst_buf_sysfs));
  10441. +
  10442. +static int surface_sam_ssh_sysfs_register(struct device *dev)
  10443. +{
  10444. + return sysfs_create_bin_file(&dev->kobj, &bin_attr_rqst);
  10445. +}
  10446. +
  10447. +static void surface_sam_ssh_sysfs_unregister(struct device *dev)
  10448. +{
  10449. + sysfs_remove_bin_file(&dev->kobj, &bin_attr_rqst);
  10450. +}
  10451. +
  10452. +#else /* CONFIG_SURFACE_SAM_SSH_DEBUG_DEVICE */
  10453. +
  10454. +static int surface_sam_ssh_sysfs_register(struct device *dev)
  10455. +{
  10456. + return 0;
  10457. +}
  10458. +
  10459. +static void surface_sam_ssh_sysfs_unregister(struct device *dev)
  10460. +{
  10461. +}
  10462. +
  10463. +#endif /* CONFIG_SURFACE_SAM_SSH_DEBUG_DEVICE */
  10464. +
  10465. +
  10466. +static int surface_sam_ssh_probe(struct serdev_device *serdev)
  10467. +{
  10468. + struct sam_ssh_ec *ec;
  10469. + acpi_handle *ssh = ACPI_HANDLE(&serdev->dev);
  10470. + int status, irq;
  10471. +
  10472. + if (gpiod_count(&serdev->dev, NULL) < 0)
  10473. + return -ENODEV;
  10474. +
  10475. + status = devm_acpi_dev_add_driver_gpios(&serdev->dev, ssh_acpi_gpios);
  10476. + if (status)
  10477. + return status;
  10478. +
  10479. + // setup IRQ
  10480. + irq = ssh_setup_irq(serdev);
  10481. + if (irq < 0)
  10482. + return irq;
  10483. +
  10484. + // set up EC
  10485. + ec = surface_sam_ssh_acquire();
  10486. + if (smp_load_acquire(&ec->state) != SSH_EC_UNINITIALIZED) {
  10487. + dev_err(&serdev->dev, "embedded controller already initialized\n");
  10488. +
  10489. + status = -EBUSY;
  10490. + goto err_ecinit;
  10491. + }
  10492. +
  10493. + ec->serdev = serdev;
  10494. + ec->irq = irq;
  10495. + ssh_seq_reset(&ec->counter.seq);
  10496. + ssh_rqid_reset(&ec->counter.rqid);
  10497. +
  10498. + // initialize event/request completion system
  10499. + status = ssam_cplt_init(&ec->cplt, &serdev->dev);
  10500. + if (status)
  10501. + goto err_ecinit;
  10502. +
  10503. + // initialize request and packet transmission layers
  10504. + status = ssh_rtl_init(&ec->rtl, serdev, &ssam_rtl_ops);
  10505. + if (status)
  10506. + goto err_rtl;
  10507. +
  10508. + serdev_device_set_drvdata(serdev, ec);
  10509. +
  10510. + serdev_device_set_client_ops(serdev, &ssam_serdev_ops);
  10511. + status = serdev_device_open(serdev);
  10512. + if (status)
  10513. + goto err_open;
  10514. +
  10515. + status = acpi_walk_resources(ssh, METHOD_NAME__CRS,
  10516. + ssh_setup_from_resource, serdev);
  10517. + if (ACPI_FAILURE(status))
  10518. + goto err_devinit;
  10519. +
  10520. + status = ssh_rtl_tx_start(&ec->rtl);
  10521. + if (status)
  10522. + goto err_devinit;
  10523. +
  10524. + status = ssh_rtl_rx_start(&ec->rtl);
  10525. + if (status)
  10526. + goto err_devinit;
  10527. +
  10528. + smp_store_release(&ec->state, SSH_EC_INITIALIZED);
  10529. +
  10530. + status = surface_sam_ssh_log_controller_version(ec);
  10531. + if (status)
  10532. + goto err_finalize;
  10533. +
  10534. + status = surface_sam_ssh_ec_resume(ec);
  10535. + if (status)
  10536. + goto err_finalize;
  10537. +
  10538. + status = surface_sam_ssh_sysfs_register(&serdev->dev);
  10539. + if (status)
  10540. + goto err_finalize;
  10541. +
  10542. + // TODO: The EC can wake up the system via the associated GPIO interrupt in
  10543. + // multiple situations. One of which is the remaining battery capacity
  10544. + // falling below a certain threshold. Normally, we should use the
  10545. + // device_init_wakeup function, however, the EC also seems to have other
  10546. + // reasons for waking up the system and it seems that Windows has
  10547. + // additional checks whether the system should be resumed. In short, this
  10548. + // causes some spourious unwanted wake-ups. For now let's thus default
  10549. + // power/wakeup to false.
  10550. + device_set_wakeup_capable(&serdev->dev, true);
  10551. + acpi_walk_dep_device_list(ssh);
  10552. +
  10553. + return 0;
  10554. +
  10555. +err_finalize:
  10556. + smp_store_release(&ec->state, SSH_EC_UNINITIALIZED);
  10557. + ssh_rtl_flush(&ec->rtl, msecs_to_jiffies(5000));
  10558. +err_devinit:
  10559. + serdev_device_close(serdev);
  10560. +err_open:
  10561. + ssh_rtl_shutdown(&ec->rtl);
  10562. + ssh_rtl_destroy(&ec->rtl);
  10563. +err_rtl:
  10564. + ssam_cplt_flush(&ec->cplt);
  10565. + ssam_cplt_destroy(&ec->cplt);
  10566. +err_ecinit:
  10567. + free_irq(irq, serdev);
  10568. + serdev_device_set_drvdata(serdev, NULL);
  10569. + return status;
  10570. +}
  10571. +
  10572. +static void surface_sam_ssh_remove(struct serdev_device *serdev)
  10573. +{
  10574. + struct sam_ssh_ec *ec;
  10575. + int status;
  10576. +
  10577. + ec = surface_sam_ssh_acquire_init();
  10578. + if (!ec)
  10579. + return;
  10580. +
  10581. + free_irq(ec->irq, serdev);
  10582. + surface_sam_ssh_sysfs_unregister(&serdev->dev);
  10583. +
  10584. + // suspend EC and disable events
  10585. + status = surface_sam_ssh_ec_suspend(ec);
  10586. + if (status)
  10587. + dev_err(&serdev->dev, "failed to suspend EC: %d\n", status);
  10588. +
  10589. + // flush pending events and requests while everything still works
  10590. + status = ssh_rtl_flush(&ec->rtl, msecs_to_jiffies(5000));
  10591. + if (status)
  10592. + dev_err(&serdev->dev, "failed to flush request transmission layer: %d\n", status);
  10593. +
  10594. + ssam_cplt_flush(&ec->cplt);
  10595. +
  10596. + // mark device as uninitialized
  10597. + smp_store_release(&ec->state, SSH_EC_UNINITIALIZED);
  10598. +
  10599. + // cancel rem. requests, ensure no new ones can be queued, stop threads
  10600. + ssh_rtl_tx_flush(&ec->rtl);
  10601. + ssh_rtl_shutdown(&ec->rtl);
  10602. +
  10603. + // shut down actual transport
  10604. + serdev_device_wait_until_sent(ec->serdev, 0);
  10605. + serdev_device_close(ec->serdev);
  10606. +
  10607. + /*
  10608. + * Ensure _all_ events are completed. New ones could still have been
  10609. + * received after the last flush, before the request transport layer
  10610. + * has been shut down. At this point we can be sure that no requests
  10611. + * will remain after this call.
  10612. + */
  10613. + ssam_cplt_flush(&ec->cplt);
  10614. +
  10615. + // actually free resources
  10616. + ssam_cplt_destroy(&ec->cplt);
  10617. + ssh_rtl_destroy(&ec->rtl);
  10618. +
  10619. + ec->serdev = NULL;
  10620. + ec->irq = -1;
  10621. +
  10622. + device_set_wakeup_capable(&serdev->dev, false);
  10623. + serdev_device_set_drvdata(serdev, NULL);
  10624. +}
  10625. +
  10626. +
  10627. +static const struct acpi_device_id surface_sam_ssh_match[] = {
  10628. + { "MSHW0084", 0 },
  10629. + { },
  10630. +};
  10631. +MODULE_DEVICE_TABLE(acpi, surface_sam_ssh_match);
  10632. +
  10633. +static struct serdev_device_driver surface_sam_ssh = {
  10634. + .probe = surface_sam_ssh_probe,
  10635. + .remove = surface_sam_ssh_remove,
  10636. + .driver = {
  10637. + .name = "surface_sam_ssh",
  10638. + .acpi_match_table = surface_sam_ssh_match,
  10639. + .pm = &surface_sam_ssh_pm_ops,
  10640. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  10641. + },
  10642. +};
  10643. +
  10644. +
  10645. +static int __init surface_sam_ssh_init(void)
  10646. +{
  10647. + return serdev_device_driver_register(&surface_sam_ssh);
  10648. +}
  10649. +
  10650. +static void __exit surface_sam_ssh_exit(void)
  10651. +{
  10652. + serdev_device_driver_unregister(&surface_sam_ssh);
  10653. +}
  10654. +
  10655. +/*
  10656. + * Ensure that the driver is loaded late due to some issues with the UART
  10657. + * communication. Specifically, we want to ensure that DMA is ready and being
  10658. + * used. Not using DMA can result in spurious communication failures,
  10659. + * especially during boot, which among other things will result in wrong
  10660. + * battery information (via ACPI _BIX) being displayed. Using a late init_call
  10661. + * instead of the normal module_init gives the DMA subsystem time to
  10662. + * initialize and via that results in a more stable communication, avoiding
  10663. + * such failures.
  10664. + */
  10665. +late_initcall(surface_sam_ssh_init);
  10666. +module_exit(surface_sam_ssh_exit);
  10667. +
  10668. +MODULE_AUTHOR("Maximilian Luz <luzmaximilian@gmail.com>");
  10669. +MODULE_DESCRIPTION("Surface Serial Hub Driver for 5th Generation Surface Devices");
  10670. +MODULE_LICENSE("GPL");
  10671. diff --git a/drivers/platform/x86/surface_sam/surface_sam_ssh.h b/drivers/platform/x86/surface_sam/surface_sam_ssh.h
  10672. new file mode 100644
  10673. index 0000000000000..e4f0e343496c4
  10674. --- /dev/null
  10675. +++ b/drivers/platform/x86/surface_sam/surface_sam_ssh.h
  10676. @@ -0,0 +1,482 @@
  10677. +/* SPDX-License-Identifier: GPL-2.0-or-later */
  10678. +/*
  10679. + * Interface for Surface Serial Hub (SSH).
  10680. + *
  10681. + * The SSH is the main communication hub for communication between host and
  10682. + * the Surface/System Aggregator Module (SAM) on newer Microsoft Surface
  10683. + * devices (Book 2, Pro 5, Laptops, ...). Also referred to as SAM-over-SSH.
  10684. + * Older devices (Book 1, Pro 4) use SAM-over-HID (via I2C).
  10685. + */
  10686. +
  10687. +#ifndef _SURFACE_SAM_SSH_H
  10688. +#define _SURFACE_SAM_SSH_H
  10689. +
  10690. +#include <linux/types.h>
  10691. +#include <linux/device.h>
  10692. +
  10693. +
  10694. +/* -- Data structures for SAM-over-SSH communication. ----------------------- */
  10695. +
  10696. +/**
  10697. + * enum ssh_frame_type - Frame types for SSH frames.
  10698. + * @SSH_FRAME_TYPE_DATA_SEQ: Indicates a data frame, followed by a payload with
  10699. + * the length specified in the ssh_frame.len field. This
  10700. + * frame is sequenced, meaning that an ACK is required.
  10701. + * @SSH_FRAME_TYPE_DATA_NSQ: Same as SSH_FRAME_TYPE_DATA_SEQ, but unsequenced,
  10702. + * meaning that the message does not have to be ACKed.
  10703. + * @SSH_FRAME_TYPE_ACK: Indicates an ACK message.
  10704. + * @SSH_FRAME_TYPE_NAK: Indicates an error response for previously sent
  10705. + * frame. In general, this means that the frame and/or
  10706. + * payload is malformed, e.g. a CRC is wrong. For command-
  10707. + * type payloads, this can also mean that the command is
  10708. + * invalid.
  10709. + */
  10710. +enum ssh_frame_type {
  10711. + SSH_FRAME_TYPE_DATA_SEQ = 0x80,
  10712. + SSH_FRAME_TYPE_DATA_NSQ = 0x00,
  10713. + SSH_FRAME_TYPE_ACK = 0x40,
  10714. + SSH_FRAME_TYPE_NAK = 0x04,
  10715. +};
  10716. +
  10717. +/**
  10718. + * struct ssh_frame - SSH communication frame.
  10719. + * @type: The type of the frame. See &enum ssh_frame_type.
  10720. + * @len: The length of the frame payload directly following the CRC for this
  10721. + * frame. Does not include the final CRC for that payload.
  10722. + * @seq: The sequence number for this message/exchange.
  10723. + */
  10724. +struct ssh_frame {
  10725. + u8 type;
  10726. + __le16 len;
  10727. + u8 seq;
  10728. +} __packed;
  10729. +
  10730. +/*
  10731. + * Maximum SSH frame payload length in bytes. This is the physical maximum
  10732. + * length of the protocol. Implementations may set a more constrained limit.
  10733. + */
  10734. +#define SSH_FRAME_MAX_PAYLOAD_SIZE U16_MAX
  10735. +
  10736. +/**
  10737. + * enum ssh_payload_type - Type indicator for the SSH payload.
  10738. + * @SSH_PLD_TYPE_CMD: The payload is a command structure with optional command
  10739. + * payload.
  10740. + */
  10741. +enum ssh_payload_type {
  10742. + SSH_PLD_TYPE_CMD = 0x80,
  10743. +};
  10744. +
  10745. +/**
  10746. + * struct ssh_command - Payload of a command-type frame.
  10747. + * @type: The type of the payload. See &enum ssh_payload_type. Should be
  10748. + * SSH_PLD_TYPE_CMD for this struct.
  10749. + * @tc: Command target category.
  10750. + * @chn_out: Output channel. Should be zero if this an incoming (EC to host)
  10751. + * message.
  10752. + * @chn_in: Input channel. Should be zero if this is an outgoing (hos to EC)
  10753. + * message.
  10754. + * @iid: Instance ID.
  10755. + * @rqid: Request ID. Used to match requests with responses and differentiate
  10756. + * between responses and events.
  10757. + * @cid: Command ID.
  10758. + */
  10759. +struct ssh_command {
  10760. + u8 type;
  10761. + u8 tc;
  10762. + u8 chn_out;
  10763. + u8 chn_in;
  10764. + u8 iid;
  10765. + __le16 rqid;
  10766. + u8 cid;
  10767. +} __packed;
  10768. +
  10769. +/*
  10770. + * Maximum SSH command payload length in bytes. This is the physical maximum
  10771. + * length of the protocol. Implementations may set a more constrained limit.
  10772. + */
  10773. +#define SSH_COMMAND_MAX_PAYLOAD_SIZE \
  10774. + (SSH_FRAME_MAX_PAYLOAD_SIZE - sizeof(struct ssh_command))
  10775. +
  10776. +/**
  10777. + * struct ssh_notification_params - Command payload to enable/disable SSH
  10778. + * notifications.
  10779. + * @target_category: The target category for which notifications should be
  10780. + * enabled/disabled.
  10781. + * @flags: Flags determining how notifications are being sent.
  10782. + * @request_id: The request ID that is used to send these notifications.
  10783. + * @instance_id: The specific instance in the given target category for
  10784. + * which notifications should be enabled.
  10785. + */
  10786. +struct ssh_notification_params {
  10787. + u8 target_category;
  10788. + u8 flags;
  10789. + __le16 request_id;
  10790. + u8 instance_id;
  10791. +} __packed;
  10792. +
  10793. +/**
  10794. + * SSH message syncrhonization (SYN) bytes.
  10795. + */
  10796. +#define SSH_MSG_SYN ((u16)0x55aa)
  10797. +
  10798. +/**
  10799. + * Base-length of a SSH message. This is the minimum number of bytes required
  10800. + * to form a message. The actual message length is SSH_MSG_LEN_BASE plus the
  10801. + * length of the frame payload.
  10802. + */
  10803. +#define SSH_MSG_LEN_BASE (sizeof(struct ssh_frame) + 3ull * sizeof(u16))
  10804. +
  10805. +/**
  10806. + * Length of a SSH control message.
  10807. + */
  10808. +#define SSH_MSG_LEN_CTRL SSH_MSG_LEN_BASE
  10809. +
  10810. +/**
  10811. + * Length of a SSH message with payload of specified size.
  10812. + */
  10813. +#define SSH_MESSAGE_LENGTH(payload_size) (SSH_MSG_LEN_BASE + payload_size)
  10814. +
  10815. +/**
  10816. + * Length of a SSH command message with command payload of specified size.
  10817. + */
  10818. +#define SSH_COMMAND_MESSAGE_LENGTH(payload_size) \
  10819. + SSH_MESSAGE_LENGTH(sizeof(struct ssh_command) + payload_size)
  10820. +
  10821. +/**
  10822. + * Offset of the specified struct ssh_frame field in the raw SSH message data.
  10823. + */
  10824. +#define SSH_MSGOFFSET_FRAME(field) \
  10825. + (sizeof(u16) + offsetof(struct ssh_frame, field))
  10826. +
  10827. +/**
  10828. + * Offset of the specified struct ssh_command field in the raw SSH message data.
  10829. + */
  10830. +#define SSH_MSGOFFSET_COMMAND(field) \
  10831. + (2ull * sizeof(u16) + sizeof(struct ssh_frame) \
  10832. + + offsetof(struct ssh_command, field))
  10833. +
  10834. +struct sshp_span {
  10835. + u8 *ptr;
  10836. + size_t len;
  10837. +};
  10838. +
  10839. +
  10840. +/* -- Packet transport layer (ptl). ----------------------------------------- */
  10841. +
  10842. +enum ssh_packet_priority {
  10843. + SSH_PACKET_PRIORITY_FLUSH = 0,
  10844. + SSH_PACKET_PRIORITY_DATA = 0,
  10845. + SSH_PACKET_PRIORITY_NAK = 1 << 4,
  10846. + SSH_PACKET_PRIORITY_ACK = 2 << 4,
  10847. +};
  10848. +
  10849. +#define SSH_PACKET_PRIORITY(base, try) \
  10850. + ((SSH_PACKET_PRIORITY_##base) | ((try) & 0x0f))
  10851. +
  10852. +#define ssh_packet_priority_get_try(p) ((p) & 0x0f)
  10853. +
  10854. +
  10855. +enum ssh_packet_type_flags {
  10856. + SSH_PACKET_TY_FLUSH_BIT,
  10857. + SSH_PACKET_TY_SEQUENCED_BIT,
  10858. + SSH_PACKET_TY_BLOCKING_BIT,
  10859. +
  10860. + SSH_PACKET_TY_FLUSH = BIT(SSH_PACKET_TY_FLUSH_BIT),
  10861. + SSH_PACKET_TY_SEQUENCED = BIT(SSH_PACKET_TY_SEQUENCED_BIT),
  10862. + SSH_PACKET_TY_BLOCKING = BIT(SSH_PACKET_TY_BLOCKING_BIT),
  10863. +};
  10864. +
  10865. +enum ssh_packet_state_flags {
  10866. + SSH_PACKET_SF_LOCKED_BIT,
  10867. + SSH_PACKET_SF_QUEUED_BIT,
  10868. + SSH_PACKET_SF_PENDING_BIT,
  10869. + SSH_PACKET_SF_TRANSMITTING_BIT,
  10870. + SSH_PACKET_SF_TRANSMITTED_BIT,
  10871. + SSH_PACKET_SF_ACKED_BIT,
  10872. + SSH_PACKET_SF_CANCELED_BIT,
  10873. + SSH_PACKET_SF_COMPLETED_BIT,
  10874. +};
  10875. +
  10876. +
  10877. +struct ssh_ptl;
  10878. +struct ssh_packet;
  10879. +
  10880. +struct ssh_packet_ops {
  10881. + void (*release)(struct ssh_packet *packet);
  10882. + void (*complete)(struct ssh_packet *packet, int status);
  10883. +};
  10884. +
  10885. +struct ssh_packet {
  10886. + struct ssh_ptl *ptl;
  10887. + struct kref refcnt;
  10888. +
  10889. + u8 type;
  10890. + u8 priority;
  10891. + u16 data_length;
  10892. + u8 *data;
  10893. +
  10894. + unsigned long state;
  10895. + ktime_t timestamp;
  10896. +
  10897. + struct list_head queue_node;
  10898. + struct list_head pending_node;
  10899. +
  10900. + const struct ssh_packet_ops *ops;
  10901. +};
  10902. +
  10903. +
  10904. +/* -- Request transport layer (rtl). ---------------------------------------- */
  10905. +
  10906. +enum ssh_request_flags {
  10907. + SSH_REQUEST_SF_LOCKED_BIT,
  10908. + SSH_REQUEST_SF_QUEUED_BIT,
  10909. + SSH_REQUEST_SF_PENDING_BIT,
  10910. + SSH_REQUEST_SF_TRANSMITTING_BIT,
  10911. + SSH_REQUEST_SF_TRANSMITTED_BIT,
  10912. + SSH_REQUEST_SF_RSPRCVD_BIT,
  10913. + SSH_REQUEST_SF_CANCELED_BIT,
  10914. + SSH_REQUEST_SF_COMPLETED_BIT,
  10915. +
  10916. + SSH_REQUEST_TY_FLUSH_BIT,
  10917. + SSH_REQUEST_TY_HAS_RESPONSE_BIT,
  10918. +
  10919. + SSH_REQUEST_FLAGS_SF_MASK =
  10920. + BIT(SSH_REQUEST_SF_LOCKED_BIT)
  10921. + | BIT(SSH_REQUEST_SF_QUEUED_BIT)
  10922. + | BIT(SSH_REQUEST_SF_PENDING_BIT)
  10923. + | BIT(SSH_REQUEST_SF_TRANSMITTING_BIT)
  10924. + | BIT(SSH_REQUEST_SF_TRANSMITTED_BIT)
  10925. + | BIT(SSH_REQUEST_SF_RSPRCVD_BIT)
  10926. + | BIT(SSH_REQUEST_SF_CANCELED_BIT)
  10927. + | BIT(SSH_REQUEST_SF_COMPLETED_BIT),
  10928. +
  10929. + SSH_REQUEST_FLAGS_TY_MASK =
  10930. + BIT(SSH_REQUEST_TY_FLUSH_BIT)
  10931. + | BIT(SSH_REQUEST_TY_HAS_RESPONSE_BIT),
  10932. +};
  10933. +
  10934. +
  10935. +struct ssh_rtl;
  10936. +struct ssh_request;
  10937. +
  10938. +struct ssh_request_ops {
  10939. + void (*release)(struct ssh_request *rqst);
  10940. + void (*complete)(struct ssh_request *rqst,
  10941. + const struct ssh_command *cmd,
  10942. + const struct sshp_span *data, int status);
  10943. +};
  10944. +
  10945. +struct ssh_request {
  10946. + struct ssh_rtl *rtl;
  10947. + struct ssh_packet packet;
  10948. + struct list_head node;
  10949. +
  10950. + unsigned long state;
  10951. + ktime_t timestamp;
  10952. +
  10953. + const struct ssh_request_ops *ops;
  10954. +};
  10955. +
  10956. +
  10957. +/* -- Main data types and definitions --------------------------------------- */
  10958. +
  10959. +enum ssam_ssh_tc {
  10960. + SSAM_SSH_TC_SAM = 0x01, // generic system functionality, real-time clock
  10961. + SSAM_SSH_TC_BAT = 0x02, // battery/power subsystem
  10962. + SSAM_SSH_TC_TMP = 0x03, // thermal subsystem
  10963. + SSAM_SSH_TC_PMC = 0x04,
  10964. + SSAM_SSH_TC_FAN = 0x05,
  10965. + SSAM_SSH_TC_PoM = 0x06,
  10966. + SSAM_SSH_TC_DBG = 0x07,
  10967. + SSAM_SSH_TC_KBD = 0x08, // legacy keyboard (Laptop 1/2)
  10968. + SSAM_SSH_TC_FWU = 0x09,
  10969. + SSAM_SSH_TC_UNI = 0x0a,
  10970. + SSAM_SSH_TC_LPC = 0x0b,
  10971. + SSAM_SSH_TC_TCL = 0x0c,
  10972. + SSAM_SSH_TC_SFL = 0x0d,
  10973. + SSAM_SSH_TC_KIP = 0x0e,
  10974. + SSAM_SSH_TC_EXT = 0x0f,
  10975. + SSAM_SSH_TC_BLD = 0x10,
  10976. + SSAM_SSH_TC_BAS = 0x11, // detachment system (Surface Book 2/3)
  10977. + SSAM_SSH_TC_SEN = 0x12,
  10978. + SSAM_SSH_TC_SRQ = 0x13,
  10979. + SSAM_SSH_TC_MCU = 0x14,
  10980. + SSAM_SSH_TC_HID = 0x15, // generic HID input subsystem
  10981. + SSAM_SSH_TC_TCH = 0x16,
  10982. + SSAM_SSH_TC_BKL = 0x17,
  10983. + SSAM_SSH_TC_TAM = 0x18,
  10984. + SSAM_SSH_TC_ACC = 0x19,
  10985. + SSAM_SSH_TC_UFI = 0x1a,
  10986. + SSAM_SSH_TC_USC = 0x1b,
  10987. + SSAM_SSH_TC_PEN = 0x1c,
  10988. + SSAM_SSH_TC_VID = 0x1d,
  10989. + SSAM_SSH_TC_AUD = 0x1e,
  10990. + SSAM_SSH_TC_SMC = 0x1f,
  10991. + SSAM_SSH_TC_KPD = 0x20,
  10992. + SSAM_SSH_TC_REG = 0x21,
  10993. +};
  10994. +
  10995. +/**
  10996. + * struct ssam_event_flags - Flags for enabling/disabling SAM-over-SSH events
  10997. + * @SSAM_EVENT_SEQUENCED: The event will be sent via a sequenced data frame.
  10998. + */
  10999. +enum ssam_event_flags {
  11000. + SSAM_EVENT_SEQUENCED = BIT(0),
  11001. +};
  11002. +
  11003. +struct ssam_event {
  11004. + u8 target_category;
  11005. + u8 command_id;
  11006. + u8 instance_id;
  11007. + u8 channel;
  11008. + u16 length;
  11009. + u8 data[0];
  11010. +};
  11011. +
  11012. +
  11013. +/* -- Event notifier/callbacks. --------------------------------------------- */
  11014. +
  11015. +#define SSAM_NOTIF_STATE_SHIFT 2
  11016. +#define SSAM_NOTIF_STATE_MASK ((1 << SSAM_NOTIF_STATE_SHIFT) - 1)
  11017. +
  11018. +#define SSAM_NOTIF_HANDLED BIT(0)
  11019. +#define SSAM_NOTIF_STOP BIT(1)
  11020. +
  11021. +
  11022. +struct ssam_notifier_block;
  11023. +
  11024. +typedef u32 (*ssam_notifier_fn_t)(struct ssam_notifier_block *nb,
  11025. + const struct ssam_event *event);
  11026. +
  11027. +struct ssam_notifier_block {
  11028. + struct ssam_notifier_block __rcu *next;
  11029. + ssam_notifier_fn_t fn;
  11030. + int priority;
  11031. +};
  11032. +
  11033. +
  11034. +static inline u32 ssam_notifier_from_errno(int err)
  11035. +{
  11036. + WARN_ON(err > 0);
  11037. +
  11038. + if (err >= 0)
  11039. + return 0;
  11040. + else
  11041. + return ((-err) << SSAM_NOTIF_STATE_SHIFT) | SSAM_NOTIF_STOP;
  11042. +}
  11043. +
  11044. +static inline int ssam_notifier_to_errno(u32 ret)
  11045. +{
  11046. + return -(ret >> SSAM_NOTIF_STATE_SHIFT);
  11047. +}
  11048. +
  11049. +
  11050. +/* -- Event/notification registry. ------------------------------------------ */
  11051. +
  11052. +struct ssam_event_registry {
  11053. + u8 target_category;
  11054. + u8 channel;
  11055. + u8 cid_enable;
  11056. + u8 cid_disable;
  11057. +};
  11058. +
  11059. +struct ssam_event_id {
  11060. + u8 target_category;
  11061. + u8 instance;
  11062. +};
  11063. +
  11064. +
  11065. +#define SSAM_EVENT_REGISTRY(tc, chn, cid_en, cid_dis) \
  11066. + ((struct ssam_event_registry) { \
  11067. + .target_category = (tc), \
  11068. + .channel = (chn), \
  11069. + .cid_enable = (cid_en), \
  11070. + .cid_disable = (cid_dis), \
  11071. + })
  11072. +
  11073. +#define SSAM_EVENT_ID(tc, iid) \
  11074. + ((struct ssam_event_id) { \
  11075. + .target_category = tc, \
  11076. + .instance = iid, \
  11077. + })
  11078. +
  11079. +
  11080. +#define SSAM_EVENT_REGISTRY_SAM \
  11081. + SSAM_EVENT_REGISTRY(SSAM_SSH_TC_SAM, 0x01, 0x0b, 0x0c)
  11082. +
  11083. +#define SSAM_EVENT_REGISTRY_KIP \
  11084. + SSAM_EVENT_REGISTRY(SSAM_SSH_TC_KIP, 0x02, 0x27, 0x28)
  11085. +
  11086. +#define SSAM_EVENT_REGISTRY_REG \
  11087. + SSAM_EVENT_REGISTRY(SSAM_SSH_TC_REG, 0x02, 0x01, 0x02)
  11088. +
  11089. +
  11090. +struct ssam_event_notifier {
  11091. + struct ssam_notifier_block base;
  11092. +
  11093. + struct {
  11094. + struct ssam_event_registry reg;
  11095. + struct ssam_event_id id;
  11096. + u8 flags;
  11097. + } event;
  11098. +};
  11099. +
  11100. +
  11101. +/* -- TODO -------------------------------------------------------------------*/
  11102. +
  11103. +/*
  11104. + * Maximum response payload size in bytes.
  11105. + * Value based on ACPI (255 bytes minus header/status bytes).
  11106. + */
  11107. +#define SURFACE_SAM_SSH_MAX_RQST_RESPONSE (255 - 4)
  11108. +
  11109. +/*
  11110. + * The number of reserved event IDs, used for registering an SSH event
  11111. + * handler. Valid event IDs are numbers below or equal to this value, with
  11112. + * exception of zero, which is not an event ID. Thus, this is also the
  11113. + * absolute maximum number of event handlers that can be registered.
  11114. + */
  11115. +#define SURFACE_SAM_SSH_NUM_EVENTS 0x22
  11116. +
  11117. +/*
  11118. + * The number of communication channels used in the protocol.
  11119. + */
  11120. +#define SURFACE_SAM_SSH_NUM_CHANNELS 2
  11121. +
  11122. +
  11123. +struct surface_sam_ssh_buf {
  11124. + u8 cap;
  11125. + u8 len;
  11126. + u8 *data;
  11127. +};
  11128. +
  11129. +struct surface_sam_ssh_rqst {
  11130. + u8 tc; // target category
  11131. + u8 cid; // command ID
  11132. + u8 iid; // instance ID
  11133. + u8 chn; // channel
  11134. + u8 snc; // expect response flag (bool: 0/1)
  11135. + u16 cdl; // command data length (length of payload)
  11136. + u8 *pld; // pointer to payload of length cdl
  11137. +};
  11138. +
  11139. +// TODO: remove rqid on external api
  11140. +struct surface_sam_ssh_event {
  11141. + u16 rqid; // event type/source ID
  11142. + u8 tc; // target category
  11143. + u8 cid; // command ID
  11144. + u8 iid; // instance ID
  11145. + u8 chn; // channel
  11146. + u8 len; // length of payload
  11147. + u8 *pld; // payload of length len
  11148. +};
  11149. +
  11150. +
  11151. +int surface_sam_ssh_consumer_register(struct device *consumer);
  11152. +
  11153. +int surface_sam_ssh_notifier_register(struct ssam_event_notifier *n);
  11154. +int surface_sam_ssh_notifier_unregister(struct ssam_event_notifier *n);
  11155. +
  11156. +int surface_sam_ssh_rqst(const struct surface_sam_ssh_rqst *rqst, struct surface_sam_ssh_buf *result);
  11157. +
  11158. +#endif /* _SURFACE_SAM_SSH_H */
  11159. diff --git a/drivers/platform/x86/surface_sam/surface_sam_ssh_trace.h b/drivers/platform/x86/surface_sam/surface_sam_ssh_trace.h
  11160. new file mode 100644
  11161. index 0000000000000..801c60205128c
  11162. --- /dev/null
  11163. +++ b/drivers/platform/x86/surface_sam/surface_sam_ssh_trace.h
  11164. @@ -0,0 +1,536 @@
  11165. +#undef TRACE_SYSTEM
  11166. +#define TRACE_SYSTEM surface_sam_ssh
  11167. +
  11168. +#if !defined(_SURFACE_SAM_SSH_TRACE_H) || defined(TRACE_HEADER_MULTI_READ)
  11169. +#define _SURFACE_SAM_SSH_TRACE_H
  11170. +
  11171. +#include <linux/tracepoint.h>
  11172. +
  11173. +#include "surface_sam_ssh.h"
  11174. +
  11175. +
  11176. +TRACE_DEFINE_ENUM(SSH_FRAME_TYPE_DATA_SEQ);
  11177. +TRACE_DEFINE_ENUM(SSH_FRAME_TYPE_DATA_NSQ);
  11178. +TRACE_DEFINE_ENUM(SSH_FRAME_TYPE_ACK);
  11179. +TRACE_DEFINE_ENUM(SSH_FRAME_TYPE_NAK);
  11180. +
  11181. +TRACE_DEFINE_ENUM(SSH_PACKET_TY_FLUSH_BIT);
  11182. +TRACE_DEFINE_ENUM(SSH_PACKET_TY_SEQUENCED_BIT);
  11183. +TRACE_DEFINE_ENUM(SSH_PACKET_TY_BLOCKING_BIT);
  11184. +
  11185. +TRACE_DEFINE_ENUM(SSH_PACKET_TY_FLUSH);
  11186. +TRACE_DEFINE_ENUM(SSH_PACKET_TY_SEQUENCED);
  11187. +TRACE_DEFINE_ENUM(SSH_PACKET_TY_BLOCKING);
  11188. +
  11189. +TRACE_DEFINE_ENUM(SSH_PACKET_SF_LOCKED_BIT);
  11190. +TRACE_DEFINE_ENUM(SSH_PACKET_SF_QUEUED_BIT);
  11191. +TRACE_DEFINE_ENUM(SSH_PACKET_SF_PENDING_BIT);
  11192. +TRACE_DEFINE_ENUM(SSH_PACKET_SF_TRANSMITTING_BIT);
  11193. +TRACE_DEFINE_ENUM(SSH_PACKET_SF_TRANSMITTED_BIT);
  11194. +TRACE_DEFINE_ENUM(SSH_PACKET_SF_ACKED_BIT);
  11195. +TRACE_DEFINE_ENUM(SSH_PACKET_SF_CANCELED_BIT);
  11196. +TRACE_DEFINE_ENUM(SSH_PACKET_SF_COMPLETED_BIT);
  11197. +
  11198. +TRACE_DEFINE_ENUM(SSH_REQUEST_SF_LOCKED_BIT);
  11199. +TRACE_DEFINE_ENUM(SSH_REQUEST_SF_QUEUED_BIT);
  11200. +TRACE_DEFINE_ENUM(SSH_REQUEST_SF_PENDING_BIT);
  11201. +TRACE_DEFINE_ENUM(SSH_REQUEST_SF_TRANSMITTING_BIT);
  11202. +TRACE_DEFINE_ENUM(SSH_REQUEST_SF_TRANSMITTED_BIT);
  11203. +TRACE_DEFINE_ENUM(SSH_REQUEST_SF_RSPRCVD_BIT);
  11204. +TRACE_DEFINE_ENUM(SSH_REQUEST_SF_CANCELED_BIT);
  11205. +TRACE_DEFINE_ENUM(SSH_REQUEST_SF_COMPLETED_BIT);
  11206. +TRACE_DEFINE_ENUM(SSH_REQUEST_TY_FLUSH_BIT);
  11207. +TRACE_DEFINE_ENUM(SSH_REQUEST_TY_HAS_RESPONSE_BIT);
  11208. +
  11209. +TRACE_DEFINE_ENUM(SSH_REQUEST_FLAGS_SF_MASK);
  11210. +TRACE_DEFINE_ENUM(SSH_REQUEST_FLAGS_TY_MASK);
  11211. +
  11212. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_SAM);
  11213. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_BAT);
  11214. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_TMP);
  11215. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_PMC);
  11216. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_FAN);
  11217. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_PoM);
  11218. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_DBG);
  11219. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_KBD);
  11220. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_FWU);
  11221. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_UNI);
  11222. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_LPC);
  11223. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_TCL);
  11224. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_SFL);
  11225. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_KIP);
  11226. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_EXT);
  11227. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_BLD);
  11228. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_BAS);
  11229. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_SEN);
  11230. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_SRQ);
  11231. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_MCU);
  11232. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_HID);
  11233. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_TCH);
  11234. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_BKL);
  11235. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_TAM);
  11236. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_ACC);
  11237. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_UFI);
  11238. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_USC);
  11239. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_PEN);
  11240. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_VID);
  11241. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_AUD);
  11242. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_SMC);
  11243. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_KPD);
  11244. +TRACE_DEFINE_ENUM(SSAM_SSH_TC_REG);
  11245. +
  11246. +
  11247. +#define SSAM_PTR_UID_LEN 9
  11248. +#define SSAM_U8_FIELD_NOT_APPLICABLE ((u16)-1)
  11249. +#define SSAM_SEQ_NOT_APPLICABLE ((u16)-1)
  11250. +#define SSAM_RQID_NOT_APPLICABLE ((u32)-1)
  11251. +#define SSAM_SSH_TC_NOT_APPLICABLE 0
  11252. +
  11253. +
  11254. +#ifndef _SURFACE_SAM_SSH_TRACE_HELPERS
  11255. +#define _SURFACE_SAM_SSH_TRACE_HELPERS
  11256. +
  11257. +static inline void ssam_trace_ptr_uid(const void *ptr, char* uid_str)
  11258. +{
  11259. + char buf[2 * sizeof(void*) + 1];
  11260. +
  11261. + snprintf(buf, ARRAY_SIZE(buf), "%p", ptr);
  11262. + memcpy(uid_str, &buf[ARRAY_SIZE(buf) - SSAM_PTR_UID_LEN],
  11263. + SSAM_PTR_UID_LEN);
  11264. +}
  11265. +
  11266. +static inline u16 ssam_trace_get_packet_seq(const struct ssh_packet *p)
  11267. +{
  11268. + if (!p->data || p->data_length < SSH_MESSAGE_LENGTH(0))
  11269. + return SSAM_SEQ_NOT_APPLICABLE;
  11270. +
  11271. + return p->data[SSH_MSGOFFSET_FRAME(seq)];
  11272. +}
  11273. +
  11274. +static inline u32 ssam_trace_get_request_id(const struct ssh_packet *p)
  11275. +{
  11276. + if (!p->data || p->data_length < SSH_COMMAND_MESSAGE_LENGTH(0))
  11277. + return SSAM_RQID_NOT_APPLICABLE;
  11278. +
  11279. + return get_unaligned_le16(&p->data[SSH_MSGOFFSET_COMMAND(rqid)]);
  11280. +}
  11281. +
  11282. +static inline u32 ssam_trace_get_request_tc(const struct ssh_packet *p)
  11283. +{
  11284. + if (!p->data || p->data_length < SSH_COMMAND_MESSAGE_LENGTH(0))
  11285. + return SSAM_SSH_TC_NOT_APPLICABLE;
  11286. +
  11287. + return get_unaligned_le16(&p->data[SSH_MSGOFFSET_COMMAND(tc)]);
  11288. +}
  11289. +
  11290. +#endif /* _SURFACE_SAM_SSH_TRACE_HELPERS */
  11291. +
  11292. +#define ssam_trace_get_command_field_u8(packet, field) \
  11293. + ((!packet || packet->data_length < SSH_COMMAND_MESSAGE_LENGTH(0)) \
  11294. + ? 0 : p->data[SSH_MSGOFFSET_COMMAND(field)])
  11295. +
  11296. +#define ssam_show_generic_u8_field(value) \
  11297. + __print_symbolic(value, \
  11298. + { SSAM_U8_FIELD_NOT_APPLICABLE, "N/A" } \
  11299. + )
  11300. +
  11301. +
  11302. +#define ssam_show_frame_type(ty) \
  11303. + __print_symbolic(ty, \
  11304. + { SSH_FRAME_TYPE_DATA_SEQ, "DSEQ" }, \
  11305. + { SSH_FRAME_TYPE_DATA_NSQ, "DNSQ" }, \
  11306. + { SSH_FRAME_TYPE_ACK, "ACK" }, \
  11307. + { SSH_FRAME_TYPE_NAK, "NAK" } \
  11308. + )
  11309. +
  11310. +#define ssam_show_packet_type(type) \
  11311. + __print_flags(type, "", \
  11312. + { SSH_PACKET_TY_FLUSH, "F" }, \
  11313. + { SSH_PACKET_TY_SEQUENCED, "S" }, \
  11314. + { SSH_PACKET_TY_BLOCKING, "B" } \
  11315. + )
  11316. +
  11317. +#define ssam_show_packet_state(state) \
  11318. + __print_flags(state, "", \
  11319. + { BIT(SSH_PACKET_SF_LOCKED_BIT), "L" }, \
  11320. + { BIT(SSH_PACKET_SF_QUEUED_BIT), "Q" }, \
  11321. + { BIT(SSH_PACKET_SF_PENDING_BIT), "P" }, \
  11322. + { BIT(SSH_PACKET_SF_TRANSMITTING_BIT), "S" }, \
  11323. + { BIT(SSH_PACKET_SF_TRANSMITTED_BIT), "T" }, \
  11324. + { BIT(SSH_PACKET_SF_ACKED_BIT), "A" }, \
  11325. + { BIT(SSH_PACKET_SF_CANCELED_BIT), "C" }, \
  11326. + { BIT(SSH_PACKET_SF_COMPLETED_BIT), "F" } \
  11327. + )
  11328. +
  11329. +#define ssam_show_packet_seq(seq) \
  11330. + __print_symbolic(seq, \
  11331. + { SSAM_SEQ_NOT_APPLICABLE, "N/A" } \
  11332. + )
  11333. +
  11334. +
  11335. +#define ssam_show_request_type(flags) \
  11336. + __print_flags(flags & SSH_REQUEST_FLAGS_TY_MASK, "", \
  11337. + { BIT(SSH_REQUEST_TY_FLUSH_BIT), "F" }, \
  11338. + { BIT(SSH_REQUEST_TY_HAS_RESPONSE_BIT), "R" } \
  11339. + )
  11340. +
  11341. +#define ssam_show_request_state(flags) \
  11342. + __print_flags(flags & SSH_REQUEST_FLAGS_SF_MASK, "", \
  11343. + { BIT(SSH_REQUEST_SF_LOCKED_BIT), "L" }, \
  11344. + { BIT(SSH_REQUEST_SF_QUEUED_BIT), "Q" }, \
  11345. + { BIT(SSH_REQUEST_SF_PENDING_BIT), "P" }, \
  11346. + { BIT(SSH_REQUEST_SF_TRANSMITTING_BIT), "S" }, \
  11347. + { BIT(SSH_REQUEST_SF_TRANSMITTED_BIT), "T" }, \
  11348. + { BIT(SSH_REQUEST_SF_RSPRCVD_BIT), "A" }, \
  11349. + { BIT(SSH_REQUEST_SF_CANCELED_BIT), "C" }, \
  11350. + { BIT(SSH_REQUEST_SF_COMPLETED_BIT), "F" } \
  11351. + )
  11352. +
  11353. +#define ssam_show_request_id(rqid) \
  11354. + __print_symbolic(rqid, \
  11355. + { SSAM_RQID_NOT_APPLICABLE, "N/A" } \
  11356. + )
  11357. +
  11358. +#define ssam_show_ssh_tc(rqid) \
  11359. + __print_symbolic(rqid, \
  11360. + { SSAM_SSH_TC_NOT_APPLICABLE, "N/A" }, \
  11361. + { SSAM_SSH_TC_SAM, "SAM" }, \
  11362. + { SSAM_SSH_TC_BAT, "BAT" }, \
  11363. + { SSAM_SSH_TC_TMP, "TMP" }, \
  11364. + { SSAM_SSH_TC_PMC, "PMC" }, \
  11365. + { SSAM_SSH_TC_FAN, "FAN" }, \
  11366. + { SSAM_SSH_TC_PoM, "PoM" }, \
  11367. + { SSAM_SSH_TC_DBG, "DBG" }, \
  11368. + { SSAM_SSH_TC_KBD, "KBD" }, \
  11369. + { SSAM_SSH_TC_FWU, "FWU" }, \
  11370. + { SSAM_SSH_TC_UNI, "UNI" }, \
  11371. + { SSAM_SSH_TC_LPC, "LPC" }, \
  11372. + { SSAM_SSH_TC_TCL, "TCL" }, \
  11373. + { SSAM_SSH_TC_SFL, "SFL" }, \
  11374. + { SSAM_SSH_TC_KIP, "KIP" }, \
  11375. + { SSAM_SSH_TC_EXT, "EXT" }, \
  11376. + { SSAM_SSH_TC_BLD, "BLD" }, \
  11377. + { SSAM_SSH_TC_BAS, "BAS" }, \
  11378. + { SSAM_SSH_TC_SEN, "SEN" }, \
  11379. + { SSAM_SSH_TC_SRQ, "SRQ" }, \
  11380. + { SSAM_SSH_TC_MCU, "MCU" }, \
  11381. + { SSAM_SSH_TC_HID, "HID" }, \
  11382. + { SSAM_SSH_TC_TCH, "TCH" }, \
  11383. + { SSAM_SSH_TC_BKL, "BKL" }, \
  11384. + { SSAM_SSH_TC_TAM, "TAM" }, \
  11385. + { SSAM_SSH_TC_ACC, "ACC" }, \
  11386. + { SSAM_SSH_TC_UFI, "UFI" }, \
  11387. + { SSAM_SSH_TC_USC, "USC" }, \
  11388. + { SSAM_SSH_TC_PEN, "PEN" }, \
  11389. + { SSAM_SSH_TC_VID, "VID" }, \
  11390. + { SSAM_SSH_TC_AUD, "AUD" }, \
  11391. + { SSAM_SSH_TC_SMC, "SMC" }, \
  11392. + { SSAM_SSH_TC_KPD, "KPD" }, \
  11393. + { SSAM_SSH_TC_REG, "REG" } \
  11394. + )
  11395. +
  11396. +
  11397. +DECLARE_EVENT_CLASS(ssam_frame_class,
  11398. + TP_PROTO(const struct ssh_frame *frame),
  11399. +
  11400. + TP_ARGS(frame),
  11401. +
  11402. + TP_STRUCT__entry(
  11403. + __field(u8, type)
  11404. + __field(u8, seq)
  11405. + __field(u16, len)
  11406. + ),
  11407. +
  11408. + TP_fast_assign(
  11409. + __entry->type = frame->type;
  11410. + __entry->seq = frame->seq;
  11411. + __entry->len = get_unaligned_le16(&frame->len);
  11412. + ),
  11413. +
  11414. + TP_printk("ty=%s, seq=0x%02x, len=%u",
  11415. + ssam_show_frame_type(__entry->type),
  11416. + __entry->seq,
  11417. + __entry->len
  11418. + )
  11419. +);
  11420. +
  11421. +#define DEFINE_SSAM_FRAME_EVENT(name) \
  11422. + DEFINE_EVENT(ssam_frame_class, ssam_##name, \
  11423. + TP_PROTO(const struct ssh_frame *frame), \
  11424. + TP_ARGS(frame) \
  11425. + )
  11426. +
  11427. +
  11428. +DECLARE_EVENT_CLASS(ssam_command_class,
  11429. + TP_PROTO(const struct ssh_command *cmd, u16 len),
  11430. +
  11431. + TP_ARGS(cmd, len),
  11432. +
  11433. + TP_STRUCT__entry(
  11434. + __field(u16, rqid)
  11435. + __field(u16, len)
  11436. + __field(u8, tc)
  11437. + __field(u8, cid)
  11438. + __field(u8, iid)
  11439. + ),
  11440. +
  11441. + TP_fast_assign(
  11442. + __entry->rqid = get_unaligned_le16(&cmd->rqid);
  11443. + __entry->tc = cmd->tc;
  11444. + __entry->cid = cmd->cid;
  11445. + __entry->iid = cmd->iid;
  11446. + __entry->len = len;
  11447. + ),
  11448. +
  11449. + TP_printk("rqid=0x%04x, tc=%s, cid=0x%02x, iid=0x%02x, len=%u",
  11450. + __entry->rqid,
  11451. + ssam_show_ssh_tc(__entry->tc),
  11452. + __entry->cid,
  11453. + __entry->iid,
  11454. + __entry->len
  11455. + )
  11456. +);
  11457. +
  11458. +#define DEFINE_SSAM_COMMAND_EVENT(name) \
  11459. + DEFINE_EVENT(ssam_command_class, ssam_##name, \
  11460. + TP_PROTO(const struct ssh_command *cmd, u16 len), \
  11461. + TP_ARGS(cmd, len) \
  11462. + )
  11463. +
  11464. +
  11465. +DECLARE_EVENT_CLASS(ssam_packet_class,
  11466. + TP_PROTO(const struct ssh_packet *packet),
  11467. +
  11468. + TP_ARGS(packet),
  11469. +
  11470. + TP_STRUCT__entry(
  11471. + __array(char, uid, SSAM_PTR_UID_LEN)
  11472. + __field(u8, type)
  11473. + __field(u8, priority)
  11474. + __field(u16, length)
  11475. + __field(unsigned long, state)
  11476. + __field(u16, seq)
  11477. + ),
  11478. +
  11479. + TP_fast_assign(
  11480. + ssam_trace_ptr_uid(packet, __entry->uid);
  11481. + __entry->type = packet->type;
  11482. + __entry->priority = READ_ONCE(packet->priority);
  11483. + __entry->length = packet->data_length;
  11484. + __entry->state = READ_ONCE(packet->state);
  11485. + __entry->seq = ssam_trace_get_packet_seq(packet);
  11486. + ),
  11487. +
  11488. + TP_printk("uid=%s, seq=%s, ty=%s, pri=0x%02x, len=%u, sta=%s",
  11489. + __entry->uid,
  11490. + ssam_show_packet_seq(__entry->seq),
  11491. + ssam_show_packet_type(__entry->type),
  11492. + __entry->priority,
  11493. + __entry->length,
  11494. + ssam_show_packet_state(__entry->state)
  11495. + )
  11496. +);
  11497. +
  11498. +#define DEFINE_SSAM_PACKET_EVENT(name) \
  11499. + DEFINE_EVENT(ssam_packet_class, ssam_##name, \
  11500. + TP_PROTO(const struct ssh_packet *packet), \
  11501. + TP_ARGS(packet) \
  11502. + )
  11503. +
  11504. +
  11505. +DECLARE_EVENT_CLASS(ssam_packet_status_class,
  11506. + TP_PROTO(const struct ssh_packet *packet, int status),
  11507. +
  11508. + TP_ARGS(packet, status),
  11509. +
  11510. + TP_STRUCT__entry(
  11511. + __array(char, uid, SSAM_PTR_UID_LEN)
  11512. + __field(u8, type)
  11513. + __field(u8, priority)
  11514. + __field(u16, length)
  11515. + __field(unsigned long, state)
  11516. + __field(u16, seq)
  11517. + __field(int, status)
  11518. + ),
  11519. +
  11520. + TP_fast_assign(
  11521. + ssam_trace_ptr_uid(packet, __entry->uid);
  11522. + __entry->type = packet->type;
  11523. + __entry->priority = READ_ONCE(packet->priority);
  11524. + __entry->length = packet->data_length;
  11525. + __entry->state = READ_ONCE(packet->state);
  11526. + __entry->seq = ssam_trace_get_packet_seq(packet);
  11527. + __entry->status = status;
  11528. + ),
  11529. +
  11530. + TP_printk("uid=%s, seq=%s, ty=%s, pri=0x%02x, len=%u, sta=%s, status=%d",
  11531. + __entry->uid,
  11532. + ssam_show_packet_seq(__entry->seq),
  11533. + ssam_show_packet_type(__entry->type),
  11534. + __entry->priority,
  11535. + __entry->length,
  11536. + ssam_show_packet_state(__entry->state),
  11537. + __entry->status
  11538. + )
  11539. +);
  11540. +
  11541. +#define DEFINE_SSAM_PACKET_STATUS_EVENT(name) \
  11542. + DEFINE_EVENT(ssam_packet_status_class, ssam_##name, \
  11543. + TP_PROTO(const struct ssh_packet *packet, int status), \
  11544. + TP_ARGS(packet, status) \
  11545. + )
  11546. +
  11547. +
  11548. +DECLARE_EVENT_CLASS(ssam_request_class,
  11549. + TP_PROTO(const struct ssh_request *request),
  11550. +
  11551. + TP_ARGS(request),
  11552. +
  11553. + TP_STRUCT__entry(
  11554. + __array(char, uid, SSAM_PTR_UID_LEN)
  11555. + __field(unsigned long, state)
  11556. + __field(u32, rqid)
  11557. + __field(u8, tc)
  11558. + __field(u16, cid)
  11559. + __field(u16, iid)
  11560. + ),
  11561. +
  11562. + TP_fast_assign(
  11563. + const struct ssh_packet *p = &request->packet;
  11564. +
  11565. + // use packet for UID so we can match requests to packets
  11566. + ssam_trace_ptr_uid(p, __entry->uid);
  11567. + __entry->state = READ_ONCE(request->state);
  11568. + __entry->rqid = ssam_trace_get_request_id(p);
  11569. + __entry->tc = ssam_trace_get_request_tc(p);
  11570. + __entry->cid = ssam_trace_get_command_field_u8(p, cid);
  11571. + __entry->iid = ssam_trace_get_command_field_u8(p, iid);
  11572. + ),
  11573. +
  11574. + TP_printk("uid=%s, rqid=%s, ty=%s, sta=%s, tc=%s, cid=%s, iid=%s",
  11575. + __entry->uid,
  11576. + ssam_show_request_id(__entry->rqid),
  11577. + ssam_show_request_type(__entry->state),
  11578. + ssam_show_request_state(__entry->state),
  11579. + ssam_show_ssh_tc(__entry->tc),
  11580. + ssam_show_generic_u8_field(__entry->cid),
  11581. + ssam_show_generic_u8_field(__entry->iid)
  11582. + )
  11583. +);
  11584. +
  11585. +#define DEFINE_SSAM_REQUEST_EVENT(name) \
  11586. + DEFINE_EVENT(ssam_request_class, ssam_##name, \
  11587. + TP_PROTO(const struct ssh_request *request), \
  11588. + TP_ARGS(request) \
  11589. + )
  11590. +
  11591. +
  11592. +DECLARE_EVENT_CLASS(ssam_request_status_class,
  11593. + TP_PROTO(const struct ssh_request *request, int status),
  11594. +
  11595. + TP_ARGS(request, status),
  11596. +
  11597. + TP_STRUCT__entry(
  11598. + __array(char, uid, SSAM_PTR_UID_LEN)
  11599. + __field(unsigned long, state)
  11600. + __field(u32, rqid)
  11601. + __field(u8, tc)
  11602. + __field(u16, cid)
  11603. + __field(u16, iid)
  11604. + __field(int, status)
  11605. + ),
  11606. +
  11607. + TP_fast_assign(
  11608. + const struct ssh_packet *p = &request->packet;
  11609. +
  11610. + // use packet for UID so we can match requests to packets
  11611. + ssam_trace_ptr_uid(p, __entry->uid);
  11612. + __entry->state = READ_ONCE(request->state);
  11613. + __entry->rqid = ssam_trace_get_request_id(p);
  11614. + __entry->tc = ssam_trace_get_request_tc(p);
  11615. + __entry->cid = ssam_trace_get_command_field_u8(p, cid);
  11616. + __entry->iid = ssam_trace_get_command_field_u8(p, iid);
  11617. + __entry->status = status;
  11618. + ),
  11619. +
  11620. + TP_printk("uid=%s, rqid=%s, ty=%s, sta=%s, tc=%s, cid=%s, iid=%s, status=%d",
  11621. + __entry->uid,
  11622. + ssam_show_request_id(__entry->rqid),
  11623. + ssam_show_request_type(__entry->state),
  11624. + ssam_show_request_state(__entry->state),
  11625. + ssam_show_ssh_tc(__entry->tc),
  11626. + ssam_show_generic_u8_field(__entry->cid),
  11627. + ssam_show_generic_u8_field(__entry->iid),
  11628. + __entry->status
  11629. + )
  11630. +);
  11631. +
  11632. +#define DEFINE_SSAM_REQUEST_STATUS_EVENT(name) \
  11633. + DEFINE_EVENT(ssam_request_status_class, ssam_##name, \
  11634. + TP_PROTO(const struct ssh_request *request, int status),\
  11635. + TP_ARGS(request, status) \
  11636. + )
  11637. +
  11638. +
  11639. +DECLARE_EVENT_CLASS(ssam_generic_uint_class,
  11640. + TP_PROTO(const char* property, unsigned int value),
  11641. +
  11642. + TP_ARGS(property, value),
  11643. +
  11644. + TP_STRUCT__entry(
  11645. + __string(property, property)
  11646. + __field(unsigned int, value)
  11647. + ),
  11648. +
  11649. + TP_fast_assign(
  11650. + __assign_str(property, property);
  11651. + __entry->value = value;
  11652. + ),
  11653. +
  11654. + TP_printk("%s=%u", __get_str(property), __entry->value)
  11655. +);
  11656. +
  11657. +#define DEFINE_SSAM_GENERIC_UINT_EVENT(name) \
  11658. + DEFINE_EVENT(ssam_generic_uint_class, ssam_##name, \
  11659. + TP_PROTO(const char* property, unsigned int value), \
  11660. + TP_ARGS(property, value) \
  11661. + )
  11662. +
  11663. +
  11664. +DEFINE_SSAM_FRAME_EVENT(rx_frame_received);
  11665. +DEFINE_SSAM_COMMAND_EVENT(rx_response_received);
  11666. +DEFINE_SSAM_COMMAND_EVENT(rx_event_received);
  11667. +
  11668. +DEFINE_SSAM_PACKET_EVENT(packet_release);
  11669. +DEFINE_SSAM_PACKET_EVENT(packet_submit);
  11670. +DEFINE_SSAM_PACKET_EVENT(packet_resubmit);
  11671. +DEFINE_SSAM_PACKET_EVENT(packet_timeout);
  11672. +DEFINE_SSAM_PACKET_EVENT(packet_cancel);
  11673. +DEFINE_SSAM_PACKET_STATUS_EVENT(packet_complete);
  11674. +DEFINE_SSAM_GENERIC_UINT_EVENT(ptl_timeout_reap);
  11675. +
  11676. +DEFINE_SSAM_REQUEST_EVENT(request_submit);
  11677. +DEFINE_SSAM_REQUEST_EVENT(request_timeout);
  11678. +DEFINE_SSAM_REQUEST_EVENT(request_cancel);
  11679. +DEFINE_SSAM_REQUEST_STATUS_EVENT(request_complete);
  11680. +DEFINE_SSAM_GENERIC_UINT_EVENT(rtl_timeout_reap);
  11681. +
  11682. +DEFINE_SSAM_PACKET_EVENT(ei_tx_drop_ack_packet);
  11683. +DEFINE_SSAM_PACKET_EVENT(ei_tx_drop_nak_packet);
  11684. +DEFINE_SSAM_PACKET_EVENT(ei_tx_drop_dsq_packet);
  11685. +DEFINE_SSAM_PACKET_STATUS_EVENT(ei_tx_fail_write);
  11686. +DEFINE_SSAM_PACKET_EVENT(ei_tx_corrupt_data);
  11687. +DEFINE_SSAM_GENERIC_UINT_EVENT(ei_rx_corrupt_syn);
  11688. +DEFINE_SSAM_FRAME_EVENT(ei_rx_corrupt_data);
  11689. +DEFINE_SSAM_REQUEST_EVENT(ei_rx_drop_response);
  11690. +
  11691. +#endif /* _SURFACE_SAM_SSH_TRACE_H */
  11692. +
  11693. +/* This part must be outside protection */
  11694. +#undef TRACE_INCLUDE_PATH
  11695. +#undef TRACE_INCLUDE_FILE
  11696. +
  11697. +#define TRACE_INCLUDE_PATH .
  11698. +#define TRACE_INCLUDE_FILE surface_sam_ssh_trace
  11699. +
  11700. +#include <trace/define_trace.h>
  11701. diff --git a/drivers/platform/x86/surface_sam/surface_sam_vhf.c b/drivers/platform/x86/surface_sam/surface_sam_vhf.c
  11702. new file mode 100644
  11703. index 0000000000000..984035c55d63a
  11704. --- /dev/null
  11705. +++ b/drivers/platform/x86/surface_sam/surface_sam_vhf.c
  11706. @@ -0,0 +1,261 @@
  11707. +// SPDX-License-Identifier: GPL-2.0-or-later
  11708. +/*
  11709. + * Virtual HID Framework (VHF) driver for input events via SAM.
  11710. + * Used for keyboard input events on the Surface Laptops.
  11711. + */
  11712. +
  11713. +#include <linux/acpi.h>
  11714. +#include <linux/hid.h>
  11715. +#include <linux/input.h>
  11716. +#include <linux/platform_device.h>
  11717. +#include <linux/types.h>
  11718. +
  11719. +#include "surface_sam_ssh.h"
  11720. +
  11721. +
  11722. +#define USB_VENDOR_ID_MICROSOFT 0x045e
  11723. +#define USB_DEVICE_ID_MS_VHF 0xf001
  11724. +
  11725. +#define VHF_INPUT_NAME "Microsoft Virtual HID Framework Device"
  11726. +
  11727. +
  11728. +struct vhf_drvdata {
  11729. + struct platform_device *dev;
  11730. + struct hid_device *hid;
  11731. + struct ssam_event_notifier notif;
  11732. +};
  11733. +
  11734. +
  11735. +/*
  11736. + * These report descriptors have been extracted from a Surface Book 2.
  11737. + * They seems to be similar enough to be usable on the Surface Laptop.
  11738. + */
  11739. +static const u8 vhf_hid_desc[] = {
  11740. + // keyboard descriptor (event command ID 0x03)
  11741. + 0x05, 0x01, /* Usage Page (Desktop), */
  11742. + 0x09, 0x06, /* Usage (Keyboard), */
  11743. + 0xA1, 0x01, /* Collection (Application), */
  11744. + 0x85, 0x01, /* Report ID (1), */
  11745. + 0x15, 0x00, /* Logical Minimum (0), */
  11746. + 0x25, 0x01, /* Logical Maximum (1), */
  11747. + 0x75, 0x01, /* Report Size (1), */
  11748. + 0x95, 0x08, /* Report Count (8), */
  11749. + 0x05, 0x07, /* Usage Page (Keyboard), */
  11750. + 0x19, 0xE0, /* Usage Minimum (KB Leftcontrol), */
  11751. + 0x29, 0xE7, /* Usage Maximum (KB Right GUI), */
  11752. + 0x81, 0x02, /* Input (Variable), */
  11753. + 0x75, 0x08, /* Report Size (8), */
  11754. + 0x95, 0x0A, /* Report Count (10), */
  11755. + 0x19, 0x00, /* Usage Minimum (None), */
  11756. + 0x29, 0x91, /* Usage Maximum (KB LANG2), */
  11757. + 0x26, 0xFF, 0x00, /* Logical Maximum (255), */
  11758. + 0x81, 0x00, /* Input, */
  11759. + 0x05, 0x0C, /* Usage Page (Consumer), */
  11760. + 0x0A, 0xC0, 0x02, /* Usage (02C0h), */
  11761. + 0xA1, 0x02, /* Collection (Logical), */
  11762. + 0x1A, 0xC1, 0x02, /* Usage Minimum (02C1h), */
  11763. + 0x2A, 0xC6, 0x02, /* Usage Maximum (02C6h), */
  11764. + 0x95, 0x06, /* Report Count (6), */
  11765. + 0xB1, 0x03, /* Feature (Constant, Variable), */
  11766. + 0xC0, /* End Collection, */
  11767. + 0x05, 0x08, /* Usage Page (LED), */
  11768. + 0x19, 0x01, /* Usage Minimum (01h), */
  11769. + 0x29, 0x03, /* Usage Maximum (03h), */
  11770. + 0x75, 0x01, /* Report Size (1), */
  11771. + 0x95, 0x03, /* Report Count (3), */
  11772. + 0x25, 0x01, /* Logical Maximum (1), */
  11773. + 0x91, 0x02, /* Output (Variable), */
  11774. + 0x95, 0x05, /* Report Count (5), */
  11775. + 0x91, 0x01, /* Output (Constant), */
  11776. + 0xC0, /* End Collection, */
  11777. +
  11778. + // media key descriptor (event command ID 0x04)
  11779. + 0x05, 0x0C, /* Usage Page (Consumer), */
  11780. + 0x09, 0x01, /* Usage (Consumer Control), */
  11781. + 0xA1, 0x01, /* Collection (Application), */
  11782. + 0x85, 0x03, /* Report ID (3), */
  11783. + 0x75, 0x10, /* Report Size (16), */
  11784. + 0x15, 0x00, /* Logical Minimum (0), */
  11785. + 0x26, 0xFF, 0x03, /* Logical Maximum (1023), */
  11786. + 0x19, 0x00, /* Usage Minimum (00h), */
  11787. + 0x2A, 0xFF, 0x03, /* Usage Maximum (03FFh), */
  11788. + 0x81, 0x00, /* Input, */
  11789. + 0xC0, /* End Collection, */
  11790. +};
  11791. +
  11792. +
  11793. +static int vhf_hid_start(struct hid_device *hid)
  11794. +{
  11795. + hid_dbg(hid, "%s\n", __func__);
  11796. + return 0;
  11797. +}
  11798. +
  11799. +static void vhf_hid_stop(struct hid_device *hid)
  11800. +{
  11801. + hid_dbg(hid, "%s\n", __func__);
  11802. +}
  11803. +
  11804. +static int vhf_hid_open(struct hid_device *hid)
  11805. +{
  11806. + hid_dbg(hid, "%s\n", __func__);
  11807. + return 0;
  11808. +}
  11809. +
  11810. +static void vhf_hid_close(struct hid_device *hid)
  11811. +{
  11812. + hid_dbg(hid, "%s\n", __func__);
  11813. +}
  11814. +
  11815. +static int vhf_hid_parse(struct hid_device *hid)
  11816. +{
  11817. + return hid_parse_report(hid, (u8 *)vhf_hid_desc, ARRAY_SIZE(vhf_hid_desc));
  11818. +}
  11819. +
  11820. +static int vhf_hid_raw_request(struct hid_device *hid, unsigned char reportnum,
  11821. + u8 *buf, size_t len, unsigned char rtype,
  11822. + int reqtype)
  11823. +{
  11824. + hid_dbg(hid, "%s\n", __func__);
  11825. + return 0;
  11826. +}
  11827. +
  11828. +static int vhf_hid_output_report(struct hid_device *hid, u8 *buf, size_t len)
  11829. +{
  11830. + hid_dbg(hid, "%s\n", __func__);
  11831. + print_hex_dump_debug("report:", DUMP_PREFIX_OFFSET, 16, 1, buf, len, false);
  11832. +
  11833. + return len;
  11834. +}
  11835. +
  11836. +static struct hid_ll_driver vhf_hid_ll_driver = {
  11837. + .start = vhf_hid_start,
  11838. + .stop = vhf_hid_stop,
  11839. + .open = vhf_hid_open,
  11840. + .close = vhf_hid_close,
  11841. + .parse = vhf_hid_parse,
  11842. + .raw_request = vhf_hid_raw_request,
  11843. + .output_report = vhf_hid_output_report,
  11844. +};
  11845. +
  11846. +
  11847. +static struct hid_device *vhf_create_hid_device(struct platform_device *pdev)
  11848. +{
  11849. + struct hid_device *hid;
  11850. +
  11851. + hid = hid_allocate_device();
  11852. + if (IS_ERR(hid))
  11853. + return hid;
  11854. +
  11855. + hid->dev.parent = &pdev->dev;
  11856. +
  11857. + hid->bus = BUS_VIRTUAL;
  11858. + hid->vendor = USB_VENDOR_ID_MICROSOFT;
  11859. + hid->product = USB_DEVICE_ID_MS_VHF;
  11860. +
  11861. + hid->ll_driver = &vhf_hid_ll_driver;
  11862. +
  11863. + sprintf(hid->name, "%s", VHF_INPUT_NAME);
  11864. +
  11865. + return hid;
  11866. +}
  11867. +
  11868. +static u32 vhf_event_handler(struct ssam_notifier_block *nb, const struct ssam_event *event)
  11869. +{
  11870. + struct vhf_drvdata *drvdata = container_of(nb, struct vhf_drvdata, notif.base);
  11871. + int status;
  11872. +
  11873. + if (event->target_category != 0x08)
  11874. + return 0;
  11875. +
  11876. + if (event->command_id == 0x03 || event->command_id == 0x04) {
  11877. + status = hid_input_report(drvdata->hid, HID_INPUT_REPORT, (u8 *)&event->data[0], event->length, 1);
  11878. + return ssam_notifier_from_errno(status) | SSAM_NOTIF_HANDLED;
  11879. + }
  11880. +
  11881. + return 0;
  11882. +}
  11883. +
  11884. +static int surface_sam_vhf_probe(struct platform_device *pdev)
  11885. +{
  11886. + struct vhf_drvdata *drvdata;
  11887. + struct hid_device *hid;
  11888. + int status;
  11889. +
  11890. + // add device link to EC
  11891. + status = surface_sam_ssh_consumer_register(&pdev->dev);
  11892. + if (status)
  11893. + return status == -ENXIO ? -EPROBE_DEFER : status;
  11894. +
  11895. + drvdata = kzalloc(sizeof(struct vhf_drvdata), GFP_KERNEL);
  11896. + if (!drvdata)
  11897. + return -ENOMEM;
  11898. +
  11899. + hid = vhf_create_hid_device(pdev);
  11900. + if (IS_ERR(hid)) {
  11901. + status = PTR_ERR(hid);
  11902. + goto err_probe_hid;
  11903. + }
  11904. +
  11905. + status = hid_add_device(hid);
  11906. + if (status)
  11907. + goto err_add_hid;
  11908. +
  11909. + drvdata->dev = pdev;
  11910. + drvdata->hid = hid;
  11911. +
  11912. + drvdata->notif.base.priority = 1;
  11913. + drvdata->notif.base.fn = vhf_event_handler;
  11914. + drvdata->notif.event.reg = SSAM_EVENT_REGISTRY_SAM;
  11915. + drvdata->notif.event.id.target_category = SSAM_SSH_TC_KBD;
  11916. + drvdata->notif.event.id.instance = 0;
  11917. + drvdata->notif.event.flags = 0;
  11918. +
  11919. + platform_set_drvdata(pdev, drvdata);
  11920. +
  11921. + status = surface_sam_ssh_notifier_register(&drvdata->notif);
  11922. + if (status)
  11923. + goto err_add_hid;
  11924. +
  11925. + return 0;
  11926. +
  11927. +err_add_hid:
  11928. + hid_destroy_device(hid);
  11929. + platform_set_drvdata(pdev, NULL);
  11930. +err_probe_hid:
  11931. + kfree(drvdata);
  11932. + return status;
  11933. +}
  11934. +
  11935. +static int surface_sam_vhf_remove(struct platform_device *pdev)
  11936. +{
  11937. + struct vhf_drvdata *drvdata = platform_get_drvdata(pdev);
  11938. +
  11939. + surface_sam_ssh_notifier_unregister(&drvdata->notif);
  11940. + hid_destroy_device(drvdata->hid);
  11941. + kfree(drvdata);
  11942. +
  11943. + platform_set_drvdata(pdev, NULL);
  11944. + return 0;
  11945. +}
  11946. +
  11947. +
  11948. +static const struct acpi_device_id surface_sam_vhf_match[] = {
  11949. + { "MSHW0096" },
  11950. + { },
  11951. +};
  11952. +MODULE_DEVICE_TABLE(acpi, surface_sam_vhf_match);
  11953. +
  11954. +static struct platform_driver surface_sam_vhf = {
  11955. + .probe = surface_sam_vhf_probe,
  11956. + .remove = surface_sam_vhf_remove,
  11957. + .driver = {
  11958. + .name = "surface_sam_vhf",
  11959. + .acpi_match_table = surface_sam_vhf_match,
  11960. + .probe_type = PROBE_PREFER_ASYNCHRONOUS,
  11961. + },
  11962. +};
  11963. +module_platform_driver(surface_sam_vhf);
  11964. +
  11965. +MODULE_AUTHOR("Maximilian Luz <luzmaximilian@gmail.com>");
  11966. +MODULE_DESCRIPTION("Virtual HID Framework Driver for 5th Generation Surface Devices");
  11967. +MODULE_LICENSE("GPL");
  11968. diff --git a/drivers/tty/serdev/core.c b/drivers/tty/serdev/core.c
  11969. index c66a04d24f1d3..6b48fdfb20059 100644
  11970. --- a/drivers/tty/serdev/core.c
  11971. +++ b/drivers/tty/serdev/core.c
  11972. @@ -496,16 +496,97 @@ static int of_serdev_register_devices(struct serdev_controller *ctrl)
  11973. }
  11974. #ifdef CONFIG_ACPI
  11975. +
  11976. +#define SERDEV_ACPI_MAX_SCAN_DEPTH 32
  11977. +
  11978. +struct acpi_serdev_lookup {
  11979. + acpi_handle device_handle;
  11980. + acpi_handle controller_handle;
  11981. + int n;
  11982. + int index;
  11983. +};
  11984. +
  11985. +static int acpi_serdev_parse_resource(struct acpi_resource *ares, void *data)
  11986. +{
  11987. + struct acpi_serdev_lookup *lookup = data;
  11988. + struct acpi_resource_uart_serialbus *sb;
  11989. + acpi_status status;
  11990. +
  11991. + if (ares->type != ACPI_RESOURCE_TYPE_SERIAL_BUS)
  11992. + return 1;
  11993. +
  11994. + if (ares->data.common_serial_bus.type != ACPI_RESOURCE_SERIAL_TYPE_UART)
  11995. + return 1;
  11996. +
  11997. + if (lookup->index != -1 && lookup->n++ != lookup->index)
  11998. + return 1;
  11999. +
  12000. + sb = &ares->data.uart_serial_bus;
  12001. +
  12002. + status = acpi_get_handle(lookup->device_handle,
  12003. + sb->resource_source.string_ptr,
  12004. + &lookup->controller_handle);
  12005. + if (ACPI_FAILURE(status))
  12006. + return 1;
  12007. +
  12008. + /*
  12009. + * NOTE: Ideally, we would also want to retreive other properties here,
  12010. + * once setting them before opening the device is supported by serdev.
  12011. + */
  12012. +
  12013. + return 1;
  12014. +}
  12015. +
  12016. +static int acpi_serdev_do_lookup(struct acpi_device *adev,
  12017. + struct acpi_serdev_lookup *lookup)
  12018. +{
  12019. + struct list_head resource_list;
  12020. + int ret;
  12021. +
  12022. + lookup->device_handle = acpi_device_handle(adev);
  12023. + lookup->controller_handle = NULL;
  12024. + lookup->n = 0;
  12025. +
  12026. + INIT_LIST_HEAD(&resource_list);
  12027. + ret = acpi_dev_get_resources(adev, &resource_list,
  12028. + acpi_serdev_parse_resource, lookup);
  12029. + acpi_dev_free_resource_list(&resource_list);
  12030. +
  12031. + if (ret < 0)
  12032. + return -EINVAL;
  12033. +
  12034. + return 0;
  12035. +}
  12036. +
  12037. +static int acpi_serdev_check_resources(struct serdev_controller *ctrl,
  12038. + struct acpi_device *adev)
  12039. +{
  12040. + struct acpi_serdev_lookup lookup;
  12041. + int ret;
  12042. +
  12043. + if (acpi_bus_get_status(adev) || !adev->status.present)
  12044. + return -EINVAL;
  12045. +
  12046. + /* Look for UARTSerialBusV2 resource */
  12047. + lookup.index = -1; // we only care for the last device
  12048. +
  12049. + ret = acpi_serdev_do_lookup(adev, &lookup);
  12050. + if (ret)
  12051. + return ret;
  12052. +
  12053. + /* Make sure controller and ResourceSource handle match */
  12054. + if (ACPI_HANDLE(ctrl->dev.parent) != lookup.controller_handle)
  12055. + return -ENODEV;
  12056. +
  12057. + return 0;
  12058. +}
  12059. +
  12060. static acpi_status acpi_serdev_register_device(struct serdev_controller *ctrl,
  12061. - struct acpi_device *adev)
  12062. + struct acpi_device *adev)
  12063. {
  12064. - struct serdev_device *serdev = NULL;
  12065. + struct serdev_device *serdev;
  12066. int err;
  12067. - if (acpi_bus_get_status(adev) || !adev->status.present ||
  12068. - acpi_device_enumerated(adev))
  12069. - return AE_OK;
  12070. -
  12071. serdev = serdev_device_alloc(ctrl);
  12072. if (!serdev) {
  12073. dev_err(&ctrl->dev, "failed to allocate serdev device for %s\n",
  12074. @@ -533,7 +614,7 @@ static const struct acpi_device_id serdev_acpi_devices_blacklist[] = {
  12075. };
  12076. static acpi_status acpi_serdev_add_device(acpi_handle handle, u32 level,
  12077. - void *data, void **return_value)
  12078. + void *data, void **return_value)
  12079. {
  12080. struct serdev_controller *ctrl = data;
  12081. struct acpi_device *adev;
  12082. @@ -541,26 +622,31 @@ static acpi_status acpi_serdev_add_device(acpi_handle handle, u32 level,
  12083. if (acpi_bus_get_device(handle, &adev))
  12084. return AE_OK;
  12085. + if (acpi_device_enumerated(adev))
  12086. + return AE_OK;
  12087. +
  12088. /* Skip if black listed */
  12089. if (!acpi_match_device_ids(adev, serdev_acpi_devices_blacklist))
  12090. return AE_OK;
  12091. + if (acpi_serdev_check_resources(ctrl, adev))
  12092. + return AE_OK;
  12093. +
  12094. return acpi_serdev_register_device(ctrl, adev);
  12095. }
  12096. static int acpi_serdev_register_devices(struct serdev_controller *ctrl)
  12097. {
  12098. acpi_status status;
  12099. - acpi_handle handle;
  12100. - handle = ACPI_HANDLE(ctrl->dev.parent);
  12101. - if (!handle)
  12102. + if (!has_acpi_companion(ctrl->dev.parent))
  12103. return -ENODEV;
  12104. - status = acpi_walk_namespace(ACPI_TYPE_DEVICE, handle, 1,
  12105. + status = acpi_walk_namespace(ACPI_TYPE_DEVICE, ACPI_ROOT_OBJECT,
  12106. + SERDEV_ACPI_MAX_SCAN_DEPTH,
  12107. acpi_serdev_add_device, NULL, ctrl, NULL);
  12108. if (ACPI_FAILURE(status))
  12109. - dev_dbg(&ctrl->dev, "failed to enumerate serdev slaves\n");
  12110. + dev_warn(&ctrl->dev, "failed to enumerate serdev slaves\n");
  12111. if (!ctrl->serdev)
  12112. return -ENODEV;
  12113. --
  12114. 2.27.0