controller.c 86 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847
  1. // SPDX-License-Identifier: GPL-2.0+
  2. /*
  3. * Main SSAM/SSH controller structure and functionality.
  4. *
  5. * Copyright (C) 2019-2022 Maximilian Luz <luzmaximilian@gmail.com>
  6. */
  7. #include <linux/acpi.h>
  8. #include <linux/atomic.h>
  9. #include <linux/completion.h>
  10. #include <linux/gpio/consumer.h>
  11. #include <linux/interrupt.h>
  12. #include <linux/kref.h>
  13. #include <linux/limits.h>
  14. #include <linux/list.h>
  15. #include <linux/lockdep.h>
  16. #include <linux/mutex.h>
  17. #include <linux/rculist.h>
  18. #include <linux/rbtree.h>
  19. #include <linux/rwsem.h>
  20. #include <linux/serdev.h>
  21. #include <linux/slab.h>
  22. #include <linux/spinlock.h>
  23. #include <linux/srcu.h>
  24. #include <linux/types.h>
  25. #include <linux/workqueue.h>
  26. #include <linux/surface_aggregator/controller.h>
  27. #include <linux/surface_aggregator/serial_hub.h>
  28. #include "controller.h"
  29. #include "ssh_msgb.h"
  30. #include "ssh_request_layer.h"
  31. #include "trace.h"
  32. /* -- Safe counters. -------------------------------------------------------- */
  33. /**
  34. * ssh_seq_reset() - Reset/initialize sequence ID counter.
  35. * @c: The counter to reset.
  36. */
  37. static void ssh_seq_reset(struct ssh_seq_counter *c)
  38. {
  39. WRITE_ONCE(c->value, 0);
  40. }
  41. /**
  42. * ssh_seq_next() - Get next sequence ID.
  43. * @c: The counter providing the sequence IDs.
  44. *
  45. * Return: Returns the next sequence ID of the counter.
  46. */
  47. static u8 ssh_seq_next(struct ssh_seq_counter *c)
  48. {
  49. u8 old = READ_ONCE(c->value);
  50. u8 new = old + 1;
  51. u8 ret;
  52. while (unlikely((ret = cmpxchg(&c->value, old, new)) != old)) {
  53. old = ret;
  54. new = old + 1;
  55. }
  56. return old;
  57. }
  58. /**
  59. * ssh_rqid_reset() - Reset/initialize request ID counter.
  60. * @c: The counter to reset.
  61. */
  62. static void ssh_rqid_reset(struct ssh_rqid_counter *c)
  63. {
  64. WRITE_ONCE(c->value, 0);
  65. }
  66. /**
  67. * ssh_rqid_next() - Get next request ID.
  68. * @c: The counter providing the request IDs.
  69. *
  70. * Return: Returns the next request ID of the counter, skipping any reserved
  71. * request IDs.
  72. */
  73. static u16 ssh_rqid_next(struct ssh_rqid_counter *c)
  74. {
  75. u16 old = READ_ONCE(c->value);
  76. u16 new = ssh_rqid_next_valid(old);
  77. u16 ret;
  78. while (unlikely((ret = cmpxchg(&c->value, old, new)) != old)) {
  79. old = ret;
  80. new = ssh_rqid_next_valid(old);
  81. }
  82. return old;
  83. }
  84. /* -- Event notifier/callbacks. --------------------------------------------- */
  85. /*
  86. * The notifier system is based on linux/notifier.h, specifically the SRCU
  87. * implementation. The difference to that is, that some bits of the notifier
  88. * call return value can be tracked across multiple calls. This is done so
  89. * that handling of events can be tracked and a warning can be issued in case
  90. * an event goes unhandled. The idea of that warning is that it should help
  91. * discover and identify new/currently unimplemented features.
  92. */
  93. /**
  94. * ssam_event_matches_notifier() - Test if an event matches a notifier.
  95. * @n: The event notifier to test against.
  96. * @event: The event to test.
  97. *
  98. * Return: Returns %true if the given event matches the given notifier
  99. * according to the rules set in the notifier's event mask, %false otherwise.
  100. */
  101. static bool ssam_event_matches_notifier(const struct ssam_event_notifier *n,
  102. const struct ssam_event *event)
  103. {
  104. bool match = n->event.id.target_category == event->target_category;
  105. if (n->event.mask & SSAM_EVENT_MASK_TARGET)
  106. match &= n->event.reg.target_id == event->target_id;
  107. if (n->event.mask & SSAM_EVENT_MASK_INSTANCE)
  108. match &= n->event.id.instance == event->instance_id;
  109. return match;
  110. }
  111. /**
  112. * ssam_nfblk_call_chain() - Call event notifier callbacks of the given chain.
  113. * @nh: The notifier head for which the notifier callbacks should be called.
  114. * @event: The event data provided to the callbacks.
  115. *
  116. * Call all registered notifier callbacks in order of their priority until
  117. * either no notifier is left or a notifier returns a value with the
  118. * %SSAM_NOTIF_STOP bit set. Note that this bit is automatically set via
  119. * ssam_notifier_from_errno() on any non-zero error value.
  120. *
  121. * Return: Returns the notifier status value, which contains the notifier
  122. * status bits (%SSAM_NOTIF_HANDLED and %SSAM_NOTIF_STOP) as well as a
  123. * potential error value returned from the last executed notifier callback.
  124. * Use ssam_notifier_to_errno() to convert this value to the original error
  125. * value.
  126. */
  127. static int ssam_nfblk_call_chain(struct ssam_nf_head *nh, struct ssam_event *event)
  128. {
  129. struct ssam_event_notifier *nf;
  130. int ret = 0, idx;
  131. idx = srcu_read_lock(&nh->srcu);
  132. list_for_each_entry_rcu(nf, &nh->head, base.node,
  133. srcu_read_lock_held(&nh->srcu)) {
  134. if (ssam_event_matches_notifier(nf, event)) {
  135. ret = (ret & SSAM_NOTIF_STATE_MASK) | nf->base.fn(nf, event);
  136. if (ret & SSAM_NOTIF_STOP)
  137. break;
  138. }
  139. }
  140. srcu_read_unlock(&nh->srcu, idx);
  141. return ret;
  142. }
  143. /**
  144. * ssam_nfblk_insert() - Insert a new notifier block into the given notifier
  145. * list.
  146. * @nh: The notifier head into which the block should be inserted.
  147. * @nb: The notifier block to add.
  148. *
  149. * Note: This function must be synchronized by the caller with respect to other
  150. * insert, find, and/or remove calls by holding ``struct ssam_nf.lock``.
  151. *
  152. * Return: Returns zero on success, %-EEXIST if the notifier block has already
  153. * been registered.
  154. */
  155. static int ssam_nfblk_insert(struct ssam_nf_head *nh, struct ssam_notifier_block *nb)
  156. {
  157. struct ssam_notifier_block *p;
  158. struct list_head *h;
  159. /* Runs under lock, no need for RCU variant. */
  160. list_for_each(h, &nh->head) {
  161. p = list_entry(h, struct ssam_notifier_block, node);
  162. if (unlikely(p == nb)) {
  163. WARN(1, "double register detected");
  164. return -EEXIST;
  165. }
  166. if (nb->priority > p->priority)
  167. break;
  168. }
  169. list_add_tail_rcu(&nb->node, h);
  170. return 0;
  171. }
  172. /**
  173. * ssam_nfblk_find() - Check if a notifier block is registered on the given
  174. * notifier head.
  175. * list.
  176. * @nh: The notifier head on which to search.
  177. * @nb: The notifier block to search for.
  178. *
  179. * Note: This function must be synchronized by the caller with respect to other
  180. * insert, find, and/or remove calls by holding ``struct ssam_nf.lock``.
  181. *
  182. * Return: Returns true if the given notifier block is registered on the given
  183. * notifier head, false otherwise.
  184. */
  185. static bool ssam_nfblk_find(struct ssam_nf_head *nh, struct ssam_notifier_block *nb)
  186. {
  187. struct ssam_notifier_block *p;
  188. /* Runs under lock, no need for RCU variant. */
  189. list_for_each_entry(p, &nh->head, node) {
  190. if (p == nb)
  191. return true;
  192. }
  193. return false;
  194. }
  195. /**
  196. * ssam_nfblk_remove() - Remove a notifier block from its notifier list.
  197. * @nb: The notifier block to be removed.
  198. *
  199. * Note: This function must be synchronized by the caller with respect to
  200. * other insert, find, and/or remove calls by holding ``struct ssam_nf.lock``.
  201. * Furthermore, the caller _must_ ensure SRCU synchronization by calling
  202. * synchronize_srcu() with ``nh->srcu`` after leaving the critical section, to
  203. * ensure that the removed notifier block is not in use any more.
  204. */
  205. static void ssam_nfblk_remove(struct ssam_notifier_block *nb)
  206. {
  207. list_del_rcu(&nb->node);
  208. }
  209. /**
  210. * ssam_nf_head_init() - Initialize the given notifier head.
  211. * @nh: The notifier head to initialize.
  212. */
  213. static int ssam_nf_head_init(struct ssam_nf_head *nh)
  214. {
  215. int status;
  216. status = init_srcu_struct(&nh->srcu);
  217. if (status)
  218. return status;
  219. INIT_LIST_HEAD(&nh->head);
  220. return 0;
  221. }
  222. /**
  223. * ssam_nf_head_destroy() - Deinitialize the given notifier head.
  224. * @nh: The notifier head to deinitialize.
  225. */
  226. static void ssam_nf_head_destroy(struct ssam_nf_head *nh)
  227. {
  228. cleanup_srcu_struct(&nh->srcu);
  229. }
  230. /* -- Event/notification registry. ------------------------------------------ */
  231. /**
  232. * struct ssam_nf_refcount_key - Key used for event activation reference
  233. * counting.
  234. * @reg: The registry via which the event is enabled/disabled.
  235. * @id: The ID uniquely describing the event.
  236. */
  237. struct ssam_nf_refcount_key {
  238. struct ssam_event_registry reg;
  239. struct ssam_event_id id;
  240. };
  241. /**
  242. * struct ssam_nf_refcount_entry - RB-tree entry for reference counting event
  243. * activations.
  244. * @node: The node of this entry in the rb-tree.
  245. * @key: The key of the event.
  246. * @refcount: The reference-count of the event.
  247. * @flags: The flags used when enabling the event.
  248. */
  249. struct ssam_nf_refcount_entry {
  250. struct rb_node node;
  251. struct ssam_nf_refcount_key key;
  252. int refcount;
  253. u8 flags;
  254. };
  255. /**
  256. * ssam_nf_refcount_inc() - Increment reference-/activation-count of the given
  257. * event.
  258. * @nf: The notifier system reference.
  259. * @reg: The registry used to enable/disable the event.
  260. * @id: The event ID.
  261. *
  262. * Increments the reference-/activation-count associated with the specified
  263. * event type/ID, allocating a new entry for this event ID if necessary. A
  264. * newly allocated entry will have a refcount of one.
  265. *
  266. * Note: ``nf->lock`` must be held when calling this function.
  267. *
  268. * Return: Returns the refcount entry on success. Returns an error pointer
  269. * with %-ENOSPC if there have already been %INT_MAX events of the specified
  270. * ID and type registered, or %-ENOMEM if the entry could not be allocated.
  271. */
  272. static struct ssam_nf_refcount_entry *
  273. ssam_nf_refcount_inc(struct ssam_nf *nf, struct ssam_event_registry reg,
  274. struct ssam_event_id id)
  275. {
  276. struct ssam_nf_refcount_entry *entry;
  277. struct ssam_nf_refcount_key key;
  278. struct rb_node **link = &nf->refcount.rb_node;
  279. struct rb_node *parent = NULL;
  280. int cmp;
  281. lockdep_assert_held(&nf->lock);
  282. key.reg = reg;
  283. key.id = id;
  284. while (*link) {
  285. entry = rb_entry(*link, struct ssam_nf_refcount_entry, node);
  286. parent = *link;
  287. cmp = memcmp(&key, &entry->key, sizeof(key));
  288. if (cmp < 0) {
  289. link = &(*link)->rb_left;
  290. } else if (cmp > 0) {
  291. link = &(*link)->rb_right;
  292. } else if (entry->refcount < INT_MAX) {
  293. entry->refcount++;
  294. return entry;
  295. } else {
  296. WARN_ON(1);
  297. return ERR_PTR(-ENOSPC);
  298. }
  299. }
  300. entry = kzalloc_obj(*entry);
  301. if (!entry)
  302. return ERR_PTR(-ENOMEM);
  303. entry->key = key;
  304. entry->refcount = 1;
  305. rb_link_node(&entry->node, parent, link);
  306. rb_insert_color(&entry->node, &nf->refcount);
  307. return entry;
  308. }
  309. /**
  310. * ssam_nf_refcount_dec() - Decrement reference-/activation-count of the given
  311. * event.
  312. * @nf: The notifier system reference.
  313. * @reg: The registry used to enable/disable the event.
  314. * @id: The event ID.
  315. *
  316. * Decrements the reference-/activation-count of the specified event,
  317. * returning its entry. If the returned entry has a refcount of zero, the
  318. * caller is responsible for freeing it using kfree().
  319. *
  320. * Note: ``nf->lock`` must be held when calling this function.
  321. *
  322. * Return: Returns the refcount entry on success or %NULL if the entry has not
  323. * been found.
  324. */
  325. static struct ssam_nf_refcount_entry *
  326. ssam_nf_refcount_dec(struct ssam_nf *nf, struct ssam_event_registry reg,
  327. struct ssam_event_id id)
  328. {
  329. struct ssam_nf_refcount_entry *entry;
  330. struct ssam_nf_refcount_key key;
  331. struct rb_node *node = nf->refcount.rb_node;
  332. int cmp;
  333. lockdep_assert_held(&nf->lock);
  334. key.reg = reg;
  335. key.id = id;
  336. while (node) {
  337. entry = rb_entry(node, struct ssam_nf_refcount_entry, node);
  338. cmp = memcmp(&key, &entry->key, sizeof(key));
  339. if (cmp < 0) {
  340. node = node->rb_left;
  341. } else if (cmp > 0) {
  342. node = node->rb_right;
  343. } else {
  344. entry->refcount--;
  345. if (entry->refcount == 0)
  346. rb_erase(&entry->node, &nf->refcount);
  347. return entry;
  348. }
  349. }
  350. return NULL;
  351. }
  352. /**
  353. * ssam_nf_refcount_dec_free() - Decrement reference-/activation-count of the
  354. * given event and free its entry if the reference count reaches zero.
  355. * @nf: The notifier system reference.
  356. * @reg: The registry used to enable/disable the event.
  357. * @id: The event ID.
  358. *
  359. * Decrements the reference-/activation-count of the specified event, freeing
  360. * its entry if it reaches zero.
  361. *
  362. * Note: ``nf->lock`` must be held when calling this function.
  363. */
  364. static void ssam_nf_refcount_dec_free(struct ssam_nf *nf,
  365. struct ssam_event_registry reg,
  366. struct ssam_event_id id)
  367. {
  368. struct ssam_nf_refcount_entry *entry;
  369. lockdep_assert_held(&nf->lock);
  370. entry = ssam_nf_refcount_dec(nf, reg, id);
  371. if (entry && entry->refcount == 0)
  372. kfree(entry);
  373. }
  374. /**
  375. * ssam_nf_refcount_empty() - Test if the notification system has any
  376. * enabled/active events.
  377. * @nf: The notification system.
  378. */
  379. static bool ssam_nf_refcount_empty(struct ssam_nf *nf)
  380. {
  381. return RB_EMPTY_ROOT(&nf->refcount);
  382. }
  383. /**
  384. * ssam_nf_call() - Call notification callbacks for the provided event.
  385. * @nf: The notifier system
  386. * @dev: The associated device, only used for logging.
  387. * @rqid: The request ID of the event.
  388. * @event: The event provided to the callbacks.
  389. *
  390. * Execute registered callbacks in order of their priority until either no
  391. * callback is left or a callback returns a value with the %SSAM_NOTIF_STOP
  392. * bit set. Note that this bit is set automatically when converting non-zero
  393. * error values via ssam_notifier_from_errno() to notifier values.
  394. *
  395. * Also note that any callback that could handle an event should return a value
  396. * with bit %SSAM_NOTIF_HANDLED set, indicating that the event does not go
  397. * unhandled/ignored. In case no registered callback could handle an event,
  398. * this function will emit a warning.
  399. *
  400. * In case a callback failed, this function will emit an error message.
  401. */
  402. static void ssam_nf_call(struct ssam_nf *nf, struct device *dev, u16 rqid,
  403. struct ssam_event *event)
  404. {
  405. struct ssam_nf_head *nf_head;
  406. int status, nf_ret;
  407. if (!ssh_rqid_is_event(rqid)) {
  408. dev_warn(dev, "event: unsupported rqid: %#06x\n", rqid);
  409. return;
  410. }
  411. nf_head = &nf->head[ssh_rqid_to_event(rqid)];
  412. nf_ret = ssam_nfblk_call_chain(nf_head, event);
  413. status = ssam_notifier_to_errno(nf_ret);
  414. if (status < 0) {
  415. dev_err(dev,
  416. "event: error handling event: %d (tc: %#04x, tid: %#04x, cid: %#04x, iid: %#04x)\n",
  417. status, event->target_category, event->target_id,
  418. event->command_id, event->instance_id);
  419. } else if (!(nf_ret & SSAM_NOTIF_HANDLED)) {
  420. dev_warn(dev,
  421. "event: unhandled event (rqid: %#04x, tc: %#04x, tid: %#04x, cid: %#04x, iid: %#04x)\n",
  422. rqid, event->target_category, event->target_id,
  423. event->command_id, event->instance_id);
  424. }
  425. }
  426. /**
  427. * ssam_nf_init() - Initialize the notifier system.
  428. * @nf: The notifier system to initialize.
  429. */
  430. static int ssam_nf_init(struct ssam_nf *nf)
  431. {
  432. int i, status;
  433. for (i = 0; i < SSH_NUM_EVENTS; i++) {
  434. status = ssam_nf_head_init(&nf->head[i]);
  435. if (status)
  436. break;
  437. }
  438. if (status) {
  439. while (i--)
  440. ssam_nf_head_destroy(&nf->head[i]);
  441. return status;
  442. }
  443. mutex_init(&nf->lock);
  444. return 0;
  445. }
  446. /**
  447. * ssam_nf_destroy() - Deinitialize the notifier system.
  448. * @nf: The notifier system to deinitialize.
  449. */
  450. static void ssam_nf_destroy(struct ssam_nf *nf)
  451. {
  452. int i;
  453. for (i = 0; i < SSH_NUM_EVENTS; i++)
  454. ssam_nf_head_destroy(&nf->head[i]);
  455. mutex_destroy(&nf->lock);
  456. }
  457. /* -- Event/async request completion system. -------------------------------- */
  458. #define SSAM_CPLT_WQ_NAME "ssam_cpltq"
  459. /*
  460. * SSAM_CPLT_WQ_BATCH - Maximum number of event item completions executed per
  461. * work execution. Used to prevent livelocking of the workqueue. Value chosen
  462. * via educated guess, may be adjusted.
  463. */
  464. #define SSAM_CPLT_WQ_BATCH 10
  465. /*
  466. * SSAM_EVENT_ITEM_CACHE_PAYLOAD_LEN - Maximum payload length for a cached
  467. * &struct ssam_event_item.
  468. *
  469. * This length has been chosen to be accommodate standard touchpad and
  470. * keyboard input events. Events with larger payloads will be allocated
  471. * separately.
  472. */
  473. #define SSAM_EVENT_ITEM_CACHE_PAYLOAD_LEN 32
  474. static struct kmem_cache *ssam_event_item_cache;
  475. /**
  476. * ssam_event_item_cache_init() - Initialize the event item cache.
  477. */
  478. int ssam_event_item_cache_init(void)
  479. {
  480. const unsigned int size = sizeof(struct ssam_event_item)
  481. + SSAM_EVENT_ITEM_CACHE_PAYLOAD_LEN;
  482. const unsigned int align = __alignof__(struct ssam_event_item);
  483. struct kmem_cache *cache;
  484. cache = kmem_cache_create("ssam_event_item", size, align, 0, NULL);
  485. if (!cache)
  486. return -ENOMEM;
  487. ssam_event_item_cache = cache;
  488. return 0;
  489. }
  490. /**
  491. * ssam_event_item_cache_destroy() - Deinitialize the event item cache.
  492. */
  493. void ssam_event_item_cache_destroy(void)
  494. {
  495. kmem_cache_destroy(ssam_event_item_cache);
  496. ssam_event_item_cache = NULL;
  497. }
  498. static void __ssam_event_item_free_cached(struct ssam_event_item *item)
  499. {
  500. kmem_cache_free(ssam_event_item_cache, item);
  501. }
  502. static void __ssam_event_item_free_generic(struct ssam_event_item *item)
  503. {
  504. kfree(item);
  505. }
  506. /**
  507. * ssam_event_item_free() - Free the provided event item.
  508. * @item: The event item to free.
  509. */
  510. static void ssam_event_item_free(struct ssam_event_item *item)
  511. {
  512. trace_ssam_event_item_free(item);
  513. item->ops.free(item);
  514. }
  515. /**
  516. * ssam_event_item_alloc() - Allocate an event item with the given payload size.
  517. * @len: The event payload length.
  518. * @flags: The flags used for allocation.
  519. *
  520. * Allocate an event item with the given payload size, preferring allocation
  521. * from the event item cache if the payload is small enough (i.e. smaller than
  522. * %SSAM_EVENT_ITEM_CACHE_PAYLOAD_LEN). Sets the item operations and payload
  523. * length values. The item free callback (``ops.free``) should not be
  524. * overwritten after this call.
  525. *
  526. * Return: Returns the newly allocated event item.
  527. */
  528. static struct ssam_event_item *ssam_event_item_alloc(size_t len, gfp_t flags)
  529. {
  530. struct ssam_event_item *item;
  531. if (len <= SSAM_EVENT_ITEM_CACHE_PAYLOAD_LEN) {
  532. item = kmem_cache_alloc(ssam_event_item_cache, flags);
  533. if (!item)
  534. return NULL;
  535. item->ops.free = __ssam_event_item_free_cached;
  536. } else {
  537. item = kzalloc_flex(*item, event.data, len, flags);
  538. if (!item)
  539. return NULL;
  540. item->ops.free = __ssam_event_item_free_generic;
  541. }
  542. item->event.length = len;
  543. trace_ssam_event_item_alloc(item, len);
  544. return item;
  545. }
  546. /**
  547. * ssam_event_queue_push() - Push an event item to the event queue.
  548. * @q: The event queue.
  549. * @item: The item to add.
  550. */
  551. static void ssam_event_queue_push(struct ssam_event_queue *q,
  552. struct ssam_event_item *item)
  553. {
  554. spin_lock(&q->lock);
  555. list_add_tail(&item->node, &q->head);
  556. spin_unlock(&q->lock);
  557. }
  558. /**
  559. * ssam_event_queue_pop() - Pop the next event item from the event queue.
  560. * @q: The event queue.
  561. *
  562. * Returns and removes the next event item from the queue. Returns %NULL If
  563. * there is no event item left.
  564. */
  565. static struct ssam_event_item *ssam_event_queue_pop(struct ssam_event_queue *q)
  566. {
  567. struct ssam_event_item *item;
  568. spin_lock(&q->lock);
  569. item = list_first_entry_or_null(&q->head, struct ssam_event_item, node);
  570. if (item)
  571. list_del(&item->node);
  572. spin_unlock(&q->lock);
  573. return item;
  574. }
  575. /**
  576. * ssam_event_queue_is_empty() - Check if the event queue is empty.
  577. * @q: The event queue.
  578. */
  579. static bool ssam_event_queue_is_empty(struct ssam_event_queue *q)
  580. {
  581. bool empty;
  582. spin_lock(&q->lock);
  583. empty = list_empty(&q->head);
  584. spin_unlock(&q->lock);
  585. return empty;
  586. }
  587. /**
  588. * ssam_cplt_get_event_queue() - Get the event queue for the given parameters.
  589. * @cplt: The completion system on which to look for the queue.
  590. * @tid: The target ID of the queue.
  591. * @rqid: The request ID representing the event ID for which to get the queue.
  592. *
  593. * Return: Returns the event queue corresponding to the event type described
  594. * by the given parameters. If the request ID does not represent an event,
  595. * this function returns %NULL. If the target ID is not supported, this
  596. * function will fall back to the default target ID (``tid = 1``).
  597. */
  598. static
  599. struct ssam_event_queue *ssam_cplt_get_event_queue(struct ssam_cplt *cplt,
  600. u8 tid, u16 rqid)
  601. {
  602. u16 event = ssh_rqid_to_event(rqid);
  603. u16 tidx = ssh_tid_to_index(tid);
  604. if (!ssh_rqid_is_event(rqid)) {
  605. dev_err(cplt->dev, "event: unsupported request ID: %#06x\n", rqid);
  606. return NULL;
  607. }
  608. if (!ssh_tid_is_valid(tid)) {
  609. dev_warn(cplt->dev, "event: unsupported target ID: %u\n", tid);
  610. tidx = 0;
  611. }
  612. return &cplt->event.target[tidx].queue[event];
  613. }
  614. /**
  615. * ssam_cplt_submit() - Submit a work item to the completion system workqueue.
  616. * @cplt: The completion system.
  617. * @work: The work item to submit.
  618. */
  619. static bool ssam_cplt_submit(struct ssam_cplt *cplt, struct work_struct *work)
  620. {
  621. return queue_work(cplt->wq, work);
  622. }
  623. /**
  624. * ssam_cplt_submit_event() - Submit an event to the completion system.
  625. * @cplt: The completion system.
  626. * @item: The event item to submit.
  627. *
  628. * Submits the event to the completion system by queuing it on the event item
  629. * queue and queuing the respective event queue work item on the completion
  630. * workqueue, which will eventually complete the event.
  631. *
  632. * Return: Returns zero on success, %-EINVAL if there is no event queue that
  633. * can handle the given event item.
  634. */
  635. static int ssam_cplt_submit_event(struct ssam_cplt *cplt,
  636. struct ssam_event_item *item)
  637. {
  638. struct ssam_event_queue *evq;
  639. evq = ssam_cplt_get_event_queue(cplt, item->event.target_id, item->rqid);
  640. if (!evq)
  641. return -EINVAL;
  642. ssam_event_queue_push(evq, item);
  643. ssam_cplt_submit(cplt, &evq->work);
  644. return 0;
  645. }
  646. /**
  647. * ssam_cplt_flush() - Flush the completion system.
  648. * @cplt: The completion system.
  649. *
  650. * Flush the completion system by waiting until all currently submitted work
  651. * items have been completed.
  652. *
  653. * Note: This function does not guarantee that all events will have been
  654. * handled once this call terminates. In case of a larger number of
  655. * to-be-completed events, the event queue work function may re-schedule its
  656. * work item, which this flush operation will ignore.
  657. *
  658. * This operation is only intended to, during normal operation prior to
  659. * shutdown, try to complete most events and requests to get them out of the
  660. * system while the system is still fully operational. It does not aim to
  661. * provide any guarantee that all of them have been handled.
  662. */
  663. static void ssam_cplt_flush(struct ssam_cplt *cplt)
  664. {
  665. flush_workqueue(cplt->wq);
  666. }
  667. static void ssam_event_queue_work_fn(struct work_struct *work)
  668. {
  669. struct ssam_event_queue *queue;
  670. struct ssam_event_item *item;
  671. struct ssam_nf *nf;
  672. struct device *dev;
  673. unsigned int iterations = SSAM_CPLT_WQ_BATCH;
  674. queue = container_of(work, struct ssam_event_queue, work);
  675. nf = &queue->cplt->event.notif;
  676. dev = queue->cplt->dev;
  677. /* Limit number of processed events to avoid livelocking. */
  678. do {
  679. item = ssam_event_queue_pop(queue);
  680. if (!item)
  681. return;
  682. ssam_nf_call(nf, dev, item->rqid, &item->event);
  683. ssam_event_item_free(item);
  684. } while (--iterations);
  685. if (!ssam_event_queue_is_empty(queue))
  686. ssam_cplt_submit(queue->cplt, &queue->work);
  687. }
  688. /**
  689. * ssam_event_queue_init() - Initialize an event queue.
  690. * @cplt: The completion system on which the queue resides.
  691. * @evq: The event queue to initialize.
  692. */
  693. static void ssam_event_queue_init(struct ssam_cplt *cplt,
  694. struct ssam_event_queue *evq)
  695. {
  696. evq->cplt = cplt;
  697. spin_lock_init(&evq->lock);
  698. INIT_LIST_HEAD(&evq->head);
  699. INIT_WORK(&evq->work, ssam_event_queue_work_fn);
  700. }
  701. /**
  702. * ssam_cplt_init() - Initialize completion system.
  703. * @cplt: The completion system to initialize.
  704. * @dev: The device used for logging.
  705. */
  706. static int ssam_cplt_init(struct ssam_cplt *cplt, struct device *dev)
  707. {
  708. struct ssam_event_target *target;
  709. int status, c, i;
  710. cplt->dev = dev;
  711. cplt->wq = alloc_workqueue(SSAM_CPLT_WQ_NAME, WQ_UNBOUND | WQ_MEM_RECLAIM, 0);
  712. if (!cplt->wq)
  713. return -ENOMEM;
  714. for (c = 0; c < ARRAY_SIZE(cplt->event.target); c++) {
  715. target = &cplt->event.target[c];
  716. for (i = 0; i < ARRAY_SIZE(target->queue); i++)
  717. ssam_event_queue_init(cplt, &target->queue[i]);
  718. }
  719. status = ssam_nf_init(&cplt->event.notif);
  720. if (status)
  721. destroy_workqueue(cplt->wq);
  722. return status;
  723. }
  724. /**
  725. * ssam_cplt_destroy() - Deinitialize the completion system.
  726. * @cplt: The completion system to deinitialize.
  727. *
  728. * Deinitialize the given completion system and ensure that all pending, i.e.
  729. * yet-to-be-completed, event items and requests have been handled.
  730. */
  731. static void ssam_cplt_destroy(struct ssam_cplt *cplt)
  732. {
  733. /*
  734. * Note: destroy_workqueue ensures that all currently queued work will
  735. * be fully completed and the workqueue drained. This means that this
  736. * call will inherently also free any queued ssam_event_items, thus we
  737. * don't have to take care of that here explicitly.
  738. */
  739. destroy_workqueue(cplt->wq);
  740. ssam_nf_destroy(&cplt->event.notif);
  741. }
  742. /* -- Main SSAM device structures. ------------------------------------------ */
  743. /**
  744. * ssam_controller_device() - Get the &struct device associated with this
  745. * controller.
  746. * @c: The controller for which to get the device.
  747. *
  748. * Return: Returns the &struct device associated with this controller,
  749. * providing its lower-level transport.
  750. */
  751. struct device *ssam_controller_device(struct ssam_controller *c)
  752. {
  753. return ssh_rtl_get_device(&c->rtl);
  754. }
  755. EXPORT_SYMBOL_GPL(ssam_controller_device);
  756. static void __ssam_controller_release(struct kref *kref)
  757. {
  758. struct ssam_controller *ctrl = to_ssam_controller(kref, kref);
  759. /*
  760. * The lock-call here is to satisfy lockdep. At this point we really
  761. * expect this to be the last remaining reference to the controller.
  762. * Anything else is a bug.
  763. */
  764. ssam_controller_lock(ctrl);
  765. ssam_controller_destroy(ctrl);
  766. ssam_controller_unlock(ctrl);
  767. kfree(ctrl);
  768. }
  769. /**
  770. * ssam_controller_get() - Increment reference count of controller.
  771. * @c: The controller.
  772. *
  773. * Return: Returns the controller provided as input.
  774. */
  775. struct ssam_controller *ssam_controller_get(struct ssam_controller *c)
  776. {
  777. if (c)
  778. kref_get(&c->kref);
  779. return c;
  780. }
  781. EXPORT_SYMBOL_GPL(ssam_controller_get);
  782. /**
  783. * ssam_controller_put() - Decrement reference count of controller.
  784. * @c: The controller.
  785. */
  786. void ssam_controller_put(struct ssam_controller *c)
  787. {
  788. if (c)
  789. kref_put(&c->kref, __ssam_controller_release);
  790. }
  791. EXPORT_SYMBOL_GPL(ssam_controller_put);
  792. /**
  793. * ssam_controller_statelock() - Lock the controller against state transitions.
  794. * @c: The controller to lock.
  795. *
  796. * Lock the controller against state transitions. Holding this lock guarantees
  797. * that the controller will not transition between states, i.e. if the
  798. * controller is in state "started", when this lock has been acquired, it will
  799. * remain in this state at least until the lock has been released.
  800. *
  801. * Multiple clients may concurrently hold this lock. In other words: The
  802. * ``statelock`` functions represent the read-lock part of a r/w-semaphore.
  803. * Actions causing state transitions of the controller must be executed while
  804. * holding the write-part of this r/w-semaphore (see ssam_controller_lock()
  805. * and ssam_controller_unlock() for that).
  806. *
  807. * See ssam_controller_stateunlock() for the corresponding unlock function.
  808. */
  809. void ssam_controller_statelock(struct ssam_controller *c)
  810. {
  811. down_read(&c->lock);
  812. }
  813. EXPORT_SYMBOL_GPL(ssam_controller_statelock);
  814. /**
  815. * ssam_controller_stateunlock() - Unlock controller state transitions.
  816. * @c: The controller to unlock.
  817. *
  818. * See ssam_controller_statelock() for the corresponding lock function.
  819. */
  820. void ssam_controller_stateunlock(struct ssam_controller *c)
  821. {
  822. up_read(&c->lock);
  823. }
  824. EXPORT_SYMBOL_GPL(ssam_controller_stateunlock);
  825. /**
  826. * ssam_controller_lock() - Acquire the main controller lock.
  827. * @c: The controller to lock.
  828. *
  829. * This lock must be held for any state transitions, including transition to
  830. * suspend/resumed states and during shutdown. See ssam_controller_statelock()
  831. * for more details on controller locking.
  832. *
  833. * See ssam_controller_unlock() for the corresponding unlock function.
  834. */
  835. void ssam_controller_lock(struct ssam_controller *c)
  836. {
  837. down_write(&c->lock);
  838. }
  839. /*
  840. * ssam_controller_unlock() - Release the main controller lock.
  841. * @c: The controller to unlock.
  842. *
  843. * See ssam_controller_lock() for the corresponding lock function.
  844. */
  845. void ssam_controller_unlock(struct ssam_controller *c)
  846. {
  847. up_write(&c->lock);
  848. }
  849. static void ssam_handle_event(struct ssh_rtl *rtl,
  850. const struct ssh_command *cmd,
  851. const struct ssam_span *data)
  852. {
  853. struct ssam_controller *ctrl = to_ssam_controller(rtl, rtl);
  854. struct ssam_event_item *item;
  855. item = ssam_event_item_alloc(data->len, GFP_KERNEL);
  856. if (!item)
  857. return;
  858. item->rqid = get_unaligned_le16(&cmd->rqid);
  859. item->event.target_category = cmd->tc;
  860. item->event.target_id = cmd->sid;
  861. item->event.command_id = cmd->cid;
  862. item->event.instance_id = cmd->iid;
  863. memcpy(&item->event.data[0], data->ptr, data->len);
  864. if (WARN_ON(ssam_cplt_submit_event(&ctrl->cplt, item)))
  865. ssam_event_item_free(item);
  866. }
  867. static const struct ssh_rtl_ops ssam_rtl_ops = {
  868. .handle_event = ssam_handle_event,
  869. };
  870. static bool ssam_notifier_is_empty(struct ssam_controller *ctrl);
  871. static void ssam_notifier_unregister_all(struct ssam_controller *ctrl);
  872. #define SSAM_SSH_DSM_REVISION 0
  873. /* d5e383e1-d892-4a76-89fc-f6aaae7ed5b5 */
  874. static const guid_t SSAM_SSH_DSM_GUID =
  875. GUID_INIT(0xd5e383e1, 0xd892, 0x4a76,
  876. 0x89, 0xfc, 0xf6, 0xaa, 0xae, 0x7e, 0xd5, 0xb5);
  877. enum ssh_dsm_fn {
  878. SSH_DSM_FN_SSH_POWER_PROFILE = 0x05,
  879. SSH_DSM_FN_SCREEN_ON_SLEEP_IDLE_TIMEOUT = 0x06,
  880. SSH_DSM_FN_SCREEN_OFF_SLEEP_IDLE_TIMEOUT = 0x07,
  881. SSH_DSM_FN_D3_CLOSES_HANDLE = 0x08,
  882. SSH_DSM_FN_SSH_BUFFER_SIZE = 0x09,
  883. };
  884. static int ssam_dsm_get_functions(acpi_handle handle, u64 *funcs)
  885. {
  886. union acpi_object *obj;
  887. u64 mask = 0;
  888. int i;
  889. *funcs = 0;
  890. /*
  891. * The _DSM function is only present on newer models. It is not
  892. * present on 5th and 6th generation devices (i.e. up to and including
  893. * Surface Pro 6, Surface Laptop 2, Surface Book 2).
  894. *
  895. * If the _DSM is not present, indicate that no function is supported.
  896. * This will result in default values being set.
  897. */
  898. if (!acpi_has_method(handle, "_DSM"))
  899. return 0;
  900. obj = acpi_evaluate_dsm_typed(handle, &SSAM_SSH_DSM_GUID,
  901. SSAM_SSH_DSM_REVISION, 0, NULL,
  902. ACPI_TYPE_BUFFER);
  903. if (!obj)
  904. return -EIO;
  905. for (i = 0; i < obj->buffer.length && i < 8; i++)
  906. mask |= (((u64)obj->buffer.pointer[i]) << (i * 8));
  907. if (mask & BIT(0))
  908. *funcs = mask;
  909. ACPI_FREE(obj);
  910. return 0;
  911. }
  912. static int ssam_dsm_load_u32(acpi_handle handle, u64 funcs, u64 func, u32 *ret)
  913. {
  914. union acpi_object *obj;
  915. u64 val;
  916. if (!(funcs & BIT_ULL(func)))
  917. return 0; /* Not supported, leave *ret at its default value */
  918. obj = acpi_evaluate_dsm_typed(handle, &SSAM_SSH_DSM_GUID,
  919. SSAM_SSH_DSM_REVISION, func, NULL,
  920. ACPI_TYPE_INTEGER);
  921. if (!obj)
  922. return -EIO;
  923. val = obj->integer.value;
  924. ACPI_FREE(obj);
  925. if (val > U32_MAX)
  926. return -ERANGE;
  927. *ret = val;
  928. return 0;
  929. }
  930. /**
  931. * ssam_controller_caps_load_from_acpi() - Load controller capabilities from
  932. * ACPI _DSM.
  933. * @handle: The handle of the ACPI controller/SSH device.
  934. * @caps: Where to store the capabilities in.
  935. *
  936. * Initializes the given controller capabilities with default values, then
  937. * checks and, if the respective _DSM functions are available, loads the
  938. * actual capabilities from the _DSM.
  939. *
  940. * Return: Returns zero on success, a negative error code on failure.
  941. */
  942. static
  943. int ssam_controller_caps_load_from_acpi(acpi_handle handle,
  944. struct ssam_controller_caps *caps)
  945. {
  946. u32 d3_closes_handle = false;
  947. u64 funcs;
  948. int status;
  949. /* Pre-load supported DSM functions. */
  950. status = ssam_dsm_get_functions(handle, &funcs);
  951. if (status)
  952. return status;
  953. /* Load actual values from ACPI, if present. */
  954. status = ssam_dsm_load_u32(handle, funcs, SSH_DSM_FN_SSH_POWER_PROFILE,
  955. &caps->ssh_power_profile);
  956. if (status)
  957. return status;
  958. status = ssam_dsm_load_u32(handle, funcs,
  959. SSH_DSM_FN_SCREEN_ON_SLEEP_IDLE_TIMEOUT,
  960. &caps->screen_on_sleep_idle_timeout);
  961. if (status)
  962. return status;
  963. status = ssam_dsm_load_u32(handle, funcs,
  964. SSH_DSM_FN_SCREEN_OFF_SLEEP_IDLE_TIMEOUT,
  965. &caps->screen_off_sleep_idle_timeout);
  966. if (status)
  967. return status;
  968. status = ssam_dsm_load_u32(handle, funcs, SSH_DSM_FN_D3_CLOSES_HANDLE,
  969. &d3_closes_handle);
  970. if (status)
  971. return status;
  972. caps->d3_closes_handle = !!d3_closes_handle;
  973. status = ssam_dsm_load_u32(handle, funcs, SSH_DSM_FN_SSH_BUFFER_SIZE,
  974. &caps->ssh_buffer_size);
  975. if (status)
  976. return status;
  977. return 0;
  978. }
  979. /**
  980. * ssam_controller_caps_load_from_of() - Load controller capabilities from OF/DT.
  981. * @dev: A pointer to the controller device
  982. * @caps: Where to store the capabilities in.
  983. *
  984. * Return: Returns zero on success, a negative error code on failure.
  985. */
  986. static int ssam_controller_caps_load_from_of(struct device *dev, struct ssam_controller_caps *caps)
  987. {
  988. /*
  989. * Every device starting with Surface Pro X through Laptop 7 uses these
  990. * identical values, which makes them good defaults.
  991. */
  992. caps->d3_closes_handle = true;
  993. caps->screen_on_sleep_idle_timeout = 5000;
  994. caps->screen_off_sleep_idle_timeout = 30;
  995. caps->ssh_buffer_size = 48;
  996. /* TODO: figure out power profile */
  997. return 0;
  998. }
  999. /**
  1000. * ssam_controller_caps_load() - Load controller capabilities
  1001. * @dev: A pointer to the controller device
  1002. * @caps: Where to store the capabilities in.
  1003. *
  1004. * Return: Returns zero on success, a negative error code on failure.
  1005. */
  1006. static int ssam_controller_caps_load(struct device *dev, struct ssam_controller_caps *caps)
  1007. {
  1008. acpi_handle handle = ACPI_HANDLE(dev);
  1009. /* Set defaults. */
  1010. caps->ssh_power_profile = U32_MAX;
  1011. caps->screen_on_sleep_idle_timeout = U32_MAX;
  1012. caps->screen_off_sleep_idle_timeout = U32_MAX;
  1013. caps->d3_closes_handle = false;
  1014. caps->ssh_buffer_size = U32_MAX;
  1015. if (handle)
  1016. return ssam_controller_caps_load_from_acpi(handle, caps);
  1017. else
  1018. return ssam_controller_caps_load_from_of(dev, caps);
  1019. }
  1020. /**
  1021. * ssam_controller_init() - Initialize SSAM controller.
  1022. * @ctrl: The controller to initialize.
  1023. * @serdev: The serial device representing the underlying data transport.
  1024. *
  1025. * Initializes the given controller. Does neither start receiver nor
  1026. * transmitter threads. After this call, the controller has to be hooked up to
  1027. * the serdev core separately via &struct serdev_device_ops, relaying calls to
  1028. * ssam_controller_receive_buf() and ssam_controller_write_wakeup(). Once the
  1029. * controller has been hooked up, transmitter and receiver threads may be
  1030. * started via ssam_controller_start(). These setup steps need to be completed
  1031. * before controller can be used for requests.
  1032. */
  1033. int ssam_controller_init(struct ssam_controller *ctrl,
  1034. struct serdev_device *serdev)
  1035. {
  1036. int status;
  1037. init_rwsem(&ctrl->lock);
  1038. kref_init(&ctrl->kref);
  1039. status = ssam_controller_caps_load(&serdev->dev, &ctrl->caps);
  1040. if (status)
  1041. return status;
  1042. dev_dbg(&serdev->dev,
  1043. "device capabilities:\n"
  1044. " ssh_power_profile: %u\n"
  1045. " ssh_buffer_size: %u\n"
  1046. " screen_on_sleep_idle_timeout: %u\n"
  1047. " screen_off_sleep_idle_timeout: %u\n"
  1048. " d3_closes_handle: %u\n",
  1049. ctrl->caps.ssh_power_profile,
  1050. ctrl->caps.ssh_buffer_size,
  1051. ctrl->caps.screen_on_sleep_idle_timeout,
  1052. ctrl->caps.screen_off_sleep_idle_timeout,
  1053. ctrl->caps.d3_closes_handle);
  1054. ssh_seq_reset(&ctrl->counter.seq);
  1055. ssh_rqid_reset(&ctrl->counter.rqid);
  1056. /* Initialize event/request completion system. */
  1057. status = ssam_cplt_init(&ctrl->cplt, &serdev->dev);
  1058. if (status)
  1059. return status;
  1060. /* Initialize request and packet transport layers. */
  1061. status = ssh_rtl_init(&ctrl->rtl, serdev, &ssam_rtl_ops);
  1062. if (status) {
  1063. ssam_cplt_destroy(&ctrl->cplt);
  1064. return status;
  1065. }
  1066. /*
  1067. * Set state via write_once even though we expect to be in an
  1068. * exclusive context, due to smoke-testing in
  1069. * ssam_request_sync_submit().
  1070. */
  1071. WRITE_ONCE(ctrl->state, SSAM_CONTROLLER_INITIALIZED);
  1072. return 0;
  1073. }
  1074. /**
  1075. * ssam_controller_start() - Start the receiver and transmitter threads of the
  1076. * controller.
  1077. * @ctrl: The controller.
  1078. *
  1079. * Note: When this function is called, the controller should be properly
  1080. * hooked up to the serdev core via &struct serdev_device_ops. Please refer
  1081. * to ssam_controller_init() for more details on controller initialization.
  1082. *
  1083. * This function must be called with the main controller lock held (i.e. by
  1084. * calling ssam_controller_lock()).
  1085. */
  1086. int ssam_controller_start(struct ssam_controller *ctrl)
  1087. {
  1088. int status;
  1089. lockdep_assert_held_write(&ctrl->lock);
  1090. if (ctrl->state != SSAM_CONTROLLER_INITIALIZED)
  1091. return -EINVAL;
  1092. status = ssh_rtl_start(&ctrl->rtl);
  1093. if (status)
  1094. return status;
  1095. /*
  1096. * Set state via write_once even though we expect to be locked/in an
  1097. * exclusive context, due to smoke-testing in
  1098. * ssam_request_sync_submit().
  1099. */
  1100. WRITE_ONCE(ctrl->state, SSAM_CONTROLLER_STARTED);
  1101. return 0;
  1102. }
  1103. /*
  1104. * SSAM_CTRL_SHUTDOWN_FLUSH_TIMEOUT - Timeout for flushing requests during
  1105. * shutdown.
  1106. *
  1107. * Chosen to be larger than one full request timeout, including packets timing
  1108. * out. This value should give ample time to complete any outstanding requests
  1109. * during normal operation and account for the odd package timeout.
  1110. */
  1111. #define SSAM_CTRL_SHUTDOWN_FLUSH_TIMEOUT msecs_to_jiffies(5000)
  1112. /**
  1113. * ssam_controller_shutdown() - Shut down the controller.
  1114. * @ctrl: The controller.
  1115. *
  1116. * Shuts down the controller by flushing all pending requests and stopping the
  1117. * transmitter and receiver threads. All requests submitted after this call
  1118. * will fail with %-ESHUTDOWN. While it is discouraged to do so, this function
  1119. * is safe to use in parallel with ongoing request submission.
  1120. *
  1121. * In the course of this shutdown procedure, all currently registered
  1122. * notifiers will be unregistered. It is, however, strongly recommended to not
  1123. * rely on this behavior, and instead the party registering the notifier
  1124. * should unregister it before the controller gets shut down, e.g. via the
  1125. * SSAM bus which guarantees client devices to be removed before a shutdown.
  1126. *
  1127. * Note that events may still be pending after this call, but, due to the
  1128. * notifiers being unregistered, these events will be dropped when the
  1129. * controller is subsequently destroyed via ssam_controller_destroy().
  1130. *
  1131. * This function must be called with the main controller lock held (i.e. by
  1132. * calling ssam_controller_lock()).
  1133. */
  1134. void ssam_controller_shutdown(struct ssam_controller *ctrl)
  1135. {
  1136. enum ssam_controller_state s = ctrl->state;
  1137. int status;
  1138. lockdep_assert_held_write(&ctrl->lock);
  1139. if (s == SSAM_CONTROLLER_UNINITIALIZED || s == SSAM_CONTROLLER_STOPPED)
  1140. return;
  1141. /*
  1142. * Try to flush pending events and requests while everything still
  1143. * works. Note: There may still be packets and/or requests in the
  1144. * system after this call (e.g. via control packets submitted by the
  1145. * packet transport layer or flush timeout / failure, ...). Those will
  1146. * be handled with the ssh_rtl_shutdown() call below.
  1147. */
  1148. status = ssh_rtl_flush(&ctrl->rtl, SSAM_CTRL_SHUTDOWN_FLUSH_TIMEOUT);
  1149. if (status) {
  1150. ssam_err(ctrl, "failed to flush request transport layer: %d\n",
  1151. status);
  1152. }
  1153. /* Try to flush all currently completing requests and events. */
  1154. ssam_cplt_flush(&ctrl->cplt);
  1155. /*
  1156. * We expect all notifiers to have been removed by the respective client
  1157. * driver that set them up at this point. If this warning occurs, some
  1158. * client driver has not done that...
  1159. */
  1160. WARN_ON(!ssam_notifier_is_empty(ctrl));
  1161. /*
  1162. * Nevertheless, we should still take care of drivers that don't behave
  1163. * well. Thus disable all enabled events, unregister all notifiers.
  1164. */
  1165. ssam_notifier_unregister_all(ctrl);
  1166. /*
  1167. * Cancel remaining requests. Ensure no new ones can be queued and stop
  1168. * threads.
  1169. */
  1170. ssh_rtl_shutdown(&ctrl->rtl);
  1171. /*
  1172. * Set state via write_once even though we expect to be locked/in an
  1173. * exclusive context, due to smoke-testing in
  1174. * ssam_request_sync_submit().
  1175. */
  1176. WRITE_ONCE(ctrl->state, SSAM_CONTROLLER_STOPPED);
  1177. ctrl->rtl.ptl.serdev = NULL;
  1178. }
  1179. /**
  1180. * ssam_controller_destroy() - Destroy the controller and free its resources.
  1181. * @ctrl: The controller.
  1182. *
  1183. * Ensures that all resources associated with the controller get freed. This
  1184. * function should only be called after the controller has been stopped via
  1185. * ssam_controller_shutdown(). In general, this function should not be called
  1186. * directly. The only valid place to call this function directly is during
  1187. * initialization, before the controller has been fully initialized and passed
  1188. * to other processes. This function is called automatically when the
  1189. * reference count of the controller reaches zero.
  1190. *
  1191. * This function must be called with the main controller lock held (i.e. by
  1192. * calling ssam_controller_lock()).
  1193. */
  1194. void ssam_controller_destroy(struct ssam_controller *ctrl)
  1195. {
  1196. lockdep_assert_held_write(&ctrl->lock);
  1197. if (ctrl->state == SSAM_CONTROLLER_UNINITIALIZED)
  1198. return;
  1199. WARN_ON(ctrl->state != SSAM_CONTROLLER_STOPPED &&
  1200. ctrl->state != SSAM_CONTROLLER_INITIALIZED);
  1201. /*
  1202. * Note: New events could still have been received after the previous
  1203. * flush in ssam_controller_shutdown, before the request transport layer
  1204. * has been shut down. At this point, after the shutdown, we can be sure
  1205. * that no new events will be queued. The call to ssam_cplt_destroy will
  1206. * ensure that those remaining are being completed and freed.
  1207. */
  1208. /* Actually free resources. */
  1209. ssam_cplt_destroy(&ctrl->cplt);
  1210. ssh_rtl_destroy(&ctrl->rtl);
  1211. /*
  1212. * Set state via write_once even though we expect to be locked/in an
  1213. * exclusive context, due to smoke-testing in
  1214. * ssam_request_sync_submit().
  1215. */
  1216. WRITE_ONCE(ctrl->state, SSAM_CONTROLLER_UNINITIALIZED);
  1217. }
  1218. /**
  1219. * ssam_controller_suspend() - Suspend the controller.
  1220. * @ctrl: The controller to suspend.
  1221. *
  1222. * Marks the controller as suspended. Note that display-off and D0-exit
  1223. * notifications have to be sent manually before transitioning the controller
  1224. * into the suspended state via this function.
  1225. *
  1226. * See ssam_controller_resume() for the corresponding resume function.
  1227. *
  1228. * Return: Returns %-EINVAL if the controller is currently not in the
  1229. * "started" state.
  1230. */
  1231. int ssam_controller_suspend(struct ssam_controller *ctrl)
  1232. {
  1233. ssam_controller_lock(ctrl);
  1234. if (ctrl->state != SSAM_CONTROLLER_STARTED) {
  1235. ssam_controller_unlock(ctrl);
  1236. return -EINVAL;
  1237. }
  1238. ssam_dbg(ctrl, "pm: suspending controller\n");
  1239. /*
  1240. * Set state via write_once even though we're locked, due to
  1241. * smoke-testing in ssam_request_sync_submit().
  1242. */
  1243. WRITE_ONCE(ctrl->state, SSAM_CONTROLLER_SUSPENDED);
  1244. ssam_controller_unlock(ctrl);
  1245. return 0;
  1246. }
  1247. /**
  1248. * ssam_controller_resume() - Resume the controller from suspend.
  1249. * @ctrl: The controller to resume.
  1250. *
  1251. * Resume the controller from the suspended state it was put into via
  1252. * ssam_controller_suspend(). This function does not issue display-on and
  1253. * D0-entry notifications. If required, those have to be sent manually after
  1254. * this call.
  1255. *
  1256. * Return: Returns %-EINVAL if the controller is currently not suspended.
  1257. */
  1258. int ssam_controller_resume(struct ssam_controller *ctrl)
  1259. {
  1260. ssam_controller_lock(ctrl);
  1261. if (ctrl->state != SSAM_CONTROLLER_SUSPENDED) {
  1262. ssam_controller_unlock(ctrl);
  1263. return -EINVAL;
  1264. }
  1265. ssam_dbg(ctrl, "pm: resuming controller\n");
  1266. /*
  1267. * Set state via write_once even though we're locked, due to
  1268. * smoke-testing in ssam_request_sync_submit().
  1269. */
  1270. WRITE_ONCE(ctrl->state, SSAM_CONTROLLER_STARTED);
  1271. ssam_controller_unlock(ctrl);
  1272. return 0;
  1273. }
  1274. /* -- Top-level request interface ------------------------------------------- */
  1275. /**
  1276. * ssam_request_write_data() - Construct and write SAM request message to
  1277. * buffer.
  1278. * @buf: The buffer to write the data to.
  1279. * @ctrl: The controller via which the request will be sent.
  1280. * @spec: The request data and specification.
  1281. *
  1282. * Constructs a SAM/SSH request message and writes it to the provided buffer.
  1283. * The request and transport counters, specifically RQID and SEQ, will be set
  1284. * in this call. These counters are obtained from the controller. It is thus
  1285. * only valid to send the resulting message via the controller specified here.
  1286. *
  1287. * For calculation of the required buffer size, refer to the
  1288. * SSH_COMMAND_MESSAGE_LENGTH() macro.
  1289. *
  1290. * Return: Returns the number of bytes used in the buffer on success. Returns
  1291. * %-EINVAL if the payload length provided in the request specification is too
  1292. * large (larger than %SSH_COMMAND_MAX_PAYLOAD_SIZE) or if the provided buffer
  1293. * is too small.
  1294. */
  1295. ssize_t ssam_request_write_data(struct ssam_span *buf,
  1296. struct ssam_controller *ctrl,
  1297. const struct ssam_request *spec)
  1298. {
  1299. struct msgbuf msgb;
  1300. u16 rqid;
  1301. u8 seq;
  1302. if (spec->length > SSH_COMMAND_MAX_PAYLOAD_SIZE)
  1303. return -EINVAL;
  1304. if (SSH_COMMAND_MESSAGE_LENGTH(spec->length) > buf->len)
  1305. return -EINVAL;
  1306. msgb_init(&msgb, buf->ptr, buf->len);
  1307. seq = ssh_seq_next(&ctrl->counter.seq);
  1308. rqid = ssh_rqid_next(&ctrl->counter.rqid);
  1309. msgb_push_cmd(&msgb, seq, rqid, spec);
  1310. return msgb_bytes_used(&msgb);
  1311. }
  1312. EXPORT_SYMBOL_GPL(ssam_request_write_data);
  1313. static void ssam_request_sync_complete(struct ssh_request *rqst,
  1314. const struct ssh_command *cmd,
  1315. const struct ssam_span *data, int status)
  1316. {
  1317. struct ssh_rtl *rtl = ssh_request_rtl(rqst);
  1318. struct ssam_request_sync *r;
  1319. r = container_of(rqst, struct ssam_request_sync, base);
  1320. r->status = status;
  1321. if (r->resp)
  1322. r->resp->length = 0;
  1323. if (status) {
  1324. rtl_dbg_cond(rtl, "rsp: request failed: %d\n", status);
  1325. return;
  1326. }
  1327. if (!data) /* Handle requests without a response. */
  1328. return;
  1329. if (!r->resp || !r->resp->pointer) {
  1330. if (data->len)
  1331. rtl_warn(rtl, "rsp: no response buffer provided, dropping data\n");
  1332. return;
  1333. }
  1334. if (data->len > r->resp->capacity) {
  1335. rtl_err(rtl,
  1336. "rsp: response buffer too small, capacity: %zu bytes, got: %zu bytes\n",
  1337. r->resp->capacity, data->len);
  1338. r->status = -ENOSPC;
  1339. return;
  1340. }
  1341. r->resp->length = data->len;
  1342. memcpy(r->resp->pointer, data->ptr, data->len);
  1343. }
  1344. static void ssam_request_sync_release(struct ssh_request *rqst)
  1345. {
  1346. complete_all(&container_of(rqst, struct ssam_request_sync, base)->comp);
  1347. }
  1348. static const struct ssh_request_ops ssam_request_sync_ops = {
  1349. .release = ssam_request_sync_release,
  1350. .complete = ssam_request_sync_complete,
  1351. };
  1352. /**
  1353. * ssam_request_sync_alloc() - Allocate a synchronous request.
  1354. * @payload_len: The length of the request payload.
  1355. * @flags: Flags used for allocation.
  1356. * @rqst: Where to store the pointer to the allocated request.
  1357. * @buffer: Where to store the buffer descriptor for the message buffer of
  1358. * the request.
  1359. *
  1360. * Allocates a synchronous request with corresponding message buffer. The
  1361. * request still needs to be initialized ssam_request_sync_init() before
  1362. * it can be submitted, and the message buffer data must still be set to the
  1363. * returned buffer via ssam_request_sync_set_data() after it has been filled,
  1364. * if need be with adjusted message length.
  1365. *
  1366. * After use, the request and its corresponding message buffer should be freed
  1367. * via ssam_request_sync_free(). The buffer must not be freed separately.
  1368. *
  1369. * Return: Returns zero on success, %-ENOMEM if the request could not be
  1370. * allocated.
  1371. */
  1372. int ssam_request_sync_alloc(size_t payload_len, gfp_t flags,
  1373. struct ssam_request_sync **rqst,
  1374. struct ssam_span *buffer)
  1375. {
  1376. size_t msglen = SSH_COMMAND_MESSAGE_LENGTH(payload_len);
  1377. *rqst = kzalloc(sizeof(**rqst) + msglen, flags);
  1378. if (!*rqst)
  1379. return -ENOMEM;
  1380. buffer->ptr = (u8 *)(*rqst + 1);
  1381. buffer->len = msglen;
  1382. return 0;
  1383. }
  1384. EXPORT_SYMBOL_GPL(ssam_request_sync_alloc);
  1385. /**
  1386. * ssam_request_sync_free() - Free a synchronous request.
  1387. * @rqst: The request to be freed.
  1388. *
  1389. * Free a synchronous request and its corresponding buffer allocated with
  1390. * ssam_request_sync_alloc(). Do not use for requests allocated on the stack
  1391. * or via any other function.
  1392. *
  1393. * Warning: The caller must ensure that the request is not in use any more.
  1394. * I.e. the caller must ensure that it has the only reference to the request
  1395. * and the request is not currently pending. This means that the caller has
  1396. * either never submitted the request, request submission has failed, or the
  1397. * caller has waited until the submitted request has been completed via
  1398. * ssam_request_sync_wait().
  1399. */
  1400. void ssam_request_sync_free(struct ssam_request_sync *rqst)
  1401. {
  1402. kfree(rqst);
  1403. }
  1404. EXPORT_SYMBOL_GPL(ssam_request_sync_free);
  1405. /**
  1406. * ssam_request_sync_init() - Initialize a synchronous request struct.
  1407. * @rqst: The request to initialize.
  1408. * @flags: The request flags.
  1409. *
  1410. * Initializes the given request struct. Does not initialize the request
  1411. * message data. This has to be done explicitly after this call via
  1412. * ssam_request_sync_set_data() and the actual message data has to be written
  1413. * via ssam_request_write_data().
  1414. *
  1415. * Return: Returns zero on success or %-EINVAL if the given flags are invalid.
  1416. */
  1417. int ssam_request_sync_init(struct ssam_request_sync *rqst,
  1418. enum ssam_request_flags flags)
  1419. {
  1420. int status;
  1421. status = ssh_request_init(&rqst->base, flags, &ssam_request_sync_ops);
  1422. if (status)
  1423. return status;
  1424. init_completion(&rqst->comp);
  1425. rqst->resp = NULL;
  1426. rqst->status = 0;
  1427. return 0;
  1428. }
  1429. EXPORT_SYMBOL_GPL(ssam_request_sync_init);
  1430. /**
  1431. * ssam_request_sync_submit() - Submit a synchronous request.
  1432. * @ctrl: The controller with which to submit the request.
  1433. * @rqst: The request to submit.
  1434. *
  1435. * Submit a synchronous request. The request has to be initialized and
  1436. * properly set up, including response buffer (may be %NULL if no response is
  1437. * expected) and command message data. This function does not wait for the
  1438. * request to be completed.
  1439. *
  1440. * If this function succeeds, ssam_request_sync_wait() must be used to ensure
  1441. * that the request has been completed before the response data can be
  1442. * accessed and/or the request can be freed. On failure, the request may
  1443. * immediately be freed.
  1444. *
  1445. * This function may only be used if the controller is active, i.e. has been
  1446. * initialized and not suspended.
  1447. */
  1448. int ssam_request_sync_submit(struct ssam_controller *ctrl,
  1449. struct ssam_request_sync *rqst)
  1450. {
  1451. int status;
  1452. /*
  1453. * This is only a superficial check. In general, the caller needs to
  1454. * ensure that the controller is initialized and is not (and does not
  1455. * get) suspended during use, i.e. until the request has been completed
  1456. * (if _absolutely_ necessary, by use of ssam_controller_statelock/
  1457. * ssam_controller_stateunlock, but something like ssam_client_link
  1458. * should be preferred as this needs to last until the request has been
  1459. * completed).
  1460. *
  1461. * Note that it is actually safe to use this function while the
  1462. * controller is in the process of being shut down (as ssh_rtl_submit
  1463. * is safe with regards to this), but it is generally discouraged to do
  1464. * so.
  1465. */
  1466. if (WARN_ON(READ_ONCE(ctrl->state) != SSAM_CONTROLLER_STARTED)) {
  1467. ssh_request_put(&rqst->base);
  1468. return -ENODEV;
  1469. }
  1470. status = ssh_rtl_submit(&ctrl->rtl, &rqst->base);
  1471. ssh_request_put(&rqst->base);
  1472. return status;
  1473. }
  1474. EXPORT_SYMBOL_GPL(ssam_request_sync_submit);
  1475. /**
  1476. * ssam_request_do_sync() - Execute a synchronous request.
  1477. * @ctrl: The controller via which the request will be submitted.
  1478. * @spec: The request specification and payload.
  1479. * @rsp: The response buffer.
  1480. *
  1481. * Allocates a synchronous request with its message data buffer on the heap
  1482. * via ssam_request_sync_alloc(), fully initializes it via the provided
  1483. * request specification, submits it, and finally waits for its completion
  1484. * before freeing it and returning its status.
  1485. *
  1486. * Return: Returns the status of the request or any failure during setup.
  1487. */
  1488. int ssam_request_do_sync(struct ssam_controller *ctrl,
  1489. const struct ssam_request *spec,
  1490. struct ssam_response *rsp)
  1491. {
  1492. struct ssam_request_sync *rqst;
  1493. struct ssam_span buf;
  1494. ssize_t len;
  1495. int status;
  1496. status = ssam_request_sync_alloc(spec->length, GFP_KERNEL, &rqst, &buf);
  1497. if (status)
  1498. return status;
  1499. status = ssam_request_sync_init(rqst, spec->flags);
  1500. if (status) {
  1501. ssam_request_sync_free(rqst);
  1502. return status;
  1503. }
  1504. ssam_request_sync_set_resp(rqst, rsp);
  1505. len = ssam_request_write_data(&buf, ctrl, spec);
  1506. if (len < 0) {
  1507. ssam_request_sync_free(rqst);
  1508. return len;
  1509. }
  1510. ssam_request_sync_set_data(rqst, buf.ptr, len);
  1511. status = ssam_request_sync_submit(ctrl, rqst);
  1512. if (!status)
  1513. status = ssam_request_sync_wait(rqst);
  1514. ssam_request_sync_free(rqst);
  1515. return status;
  1516. }
  1517. EXPORT_SYMBOL_GPL(ssam_request_do_sync);
  1518. /**
  1519. * ssam_request_do_sync_with_buffer() - Execute a synchronous request with the
  1520. * provided buffer as back-end for the message buffer.
  1521. * @ctrl: The controller via which the request will be submitted.
  1522. * @spec: The request specification and payload.
  1523. * @rsp: The response buffer.
  1524. * @buf: The buffer for the request message data.
  1525. *
  1526. * Allocates a synchronous request struct on the stack, fully initializes it
  1527. * using the provided buffer as message data buffer, submits it, and then
  1528. * waits for its completion before returning its status. The
  1529. * SSH_COMMAND_MESSAGE_LENGTH() macro can be used to compute the required
  1530. * message buffer size.
  1531. *
  1532. * This function does essentially the same as ssam_request_do_sync(), but
  1533. * instead of dynamically allocating the request and message data buffer, it
  1534. * uses the provided message data buffer and stores the (small) request struct
  1535. * on the heap.
  1536. *
  1537. * Return: Returns the status of the request or any failure during setup.
  1538. */
  1539. int ssam_request_do_sync_with_buffer(struct ssam_controller *ctrl,
  1540. const struct ssam_request *spec,
  1541. struct ssam_response *rsp,
  1542. struct ssam_span *buf)
  1543. {
  1544. struct ssam_request_sync rqst;
  1545. ssize_t len;
  1546. int status;
  1547. status = ssam_request_sync_init(&rqst, spec->flags);
  1548. if (status)
  1549. return status;
  1550. ssam_request_sync_set_resp(&rqst, rsp);
  1551. len = ssam_request_write_data(buf, ctrl, spec);
  1552. if (len < 0)
  1553. return len;
  1554. ssam_request_sync_set_data(&rqst, buf->ptr, len);
  1555. status = ssam_request_sync_submit(ctrl, &rqst);
  1556. if (!status)
  1557. status = ssam_request_sync_wait(&rqst);
  1558. return status;
  1559. }
  1560. EXPORT_SYMBOL_GPL(ssam_request_do_sync_with_buffer);
  1561. /* -- Internal SAM requests. ------------------------------------------------ */
  1562. SSAM_DEFINE_SYNC_REQUEST_R(ssam_ssh_get_firmware_version, __le32, {
  1563. .target_category = SSAM_SSH_TC_SAM,
  1564. .target_id = SSAM_SSH_TID_SAM,
  1565. .command_id = 0x13,
  1566. .instance_id = 0x00,
  1567. });
  1568. SSAM_DEFINE_SYNC_REQUEST_R(ssam_ssh_notif_display_off, u8, {
  1569. .target_category = SSAM_SSH_TC_SAM,
  1570. .target_id = SSAM_SSH_TID_SAM,
  1571. .command_id = 0x15,
  1572. .instance_id = 0x00,
  1573. });
  1574. SSAM_DEFINE_SYNC_REQUEST_R(ssam_ssh_notif_display_on, u8, {
  1575. .target_category = SSAM_SSH_TC_SAM,
  1576. .target_id = SSAM_SSH_TID_SAM,
  1577. .command_id = 0x16,
  1578. .instance_id = 0x00,
  1579. });
  1580. SSAM_DEFINE_SYNC_REQUEST_R(ssam_ssh_notif_d0_exit, u8, {
  1581. .target_category = SSAM_SSH_TC_SAM,
  1582. .target_id = SSAM_SSH_TID_SAM,
  1583. .command_id = 0x33,
  1584. .instance_id = 0x00,
  1585. });
  1586. SSAM_DEFINE_SYNC_REQUEST_R(ssam_ssh_notif_d0_entry, u8, {
  1587. .target_category = SSAM_SSH_TC_SAM,
  1588. .target_id = SSAM_SSH_TID_SAM,
  1589. .command_id = 0x34,
  1590. .instance_id = 0x00,
  1591. });
  1592. /**
  1593. * struct ssh_notification_params - Command payload to enable/disable SSH
  1594. * notifications.
  1595. * @target_category: The target category for which notifications should be
  1596. * enabled/disabled.
  1597. * @flags: Flags determining how notifications are being sent.
  1598. * @request_id: The request ID that is used to send these notifications.
  1599. * @instance_id: The specific instance in the given target category for
  1600. * which notifications should be enabled.
  1601. */
  1602. struct ssh_notification_params {
  1603. u8 target_category;
  1604. u8 flags;
  1605. __le16 request_id;
  1606. u8 instance_id;
  1607. } __packed;
  1608. static_assert(sizeof(struct ssh_notification_params) == 5);
  1609. static int __ssam_ssh_event_request(struct ssam_controller *ctrl,
  1610. struct ssam_event_registry reg, u8 cid,
  1611. struct ssam_event_id id, u8 flags)
  1612. {
  1613. struct ssh_notification_params params;
  1614. struct ssam_request rqst;
  1615. struct ssam_response result;
  1616. int status;
  1617. u16 rqid = ssh_tc_to_rqid(id.target_category);
  1618. u8 buf = 0;
  1619. /* Only allow RQIDs that lie within the event spectrum. */
  1620. if (!ssh_rqid_is_event(rqid))
  1621. return -EINVAL;
  1622. params.target_category = id.target_category;
  1623. params.instance_id = id.instance;
  1624. params.flags = flags;
  1625. put_unaligned_le16(rqid, &params.request_id);
  1626. rqst.target_category = reg.target_category;
  1627. rqst.target_id = reg.target_id;
  1628. rqst.command_id = cid;
  1629. rqst.instance_id = 0x00;
  1630. rqst.flags = SSAM_REQUEST_HAS_RESPONSE;
  1631. rqst.length = sizeof(params);
  1632. rqst.payload = (u8 *)&params;
  1633. result.capacity = sizeof(buf);
  1634. result.length = 0;
  1635. result.pointer = &buf;
  1636. status = ssam_retry(ssam_request_do_sync_onstack, ctrl, &rqst, &result,
  1637. sizeof(params));
  1638. return status < 0 ? status : buf;
  1639. }
  1640. /**
  1641. * ssam_ssh_event_enable() - Enable SSH event.
  1642. * @ctrl: The controller for which to enable the event.
  1643. * @reg: The event registry describing what request to use for enabling and
  1644. * disabling the event.
  1645. * @id: The event identifier.
  1646. * @flags: The event flags.
  1647. *
  1648. * Enables the specified event on the EC. This function does not manage
  1649. * reference counting of enabled events and is basically only a wrapper for
  1650. * the raw EC request. If the specified event is already enabled, the EC will
  1651. * ignore this request.
  1652. *
  1653. * Return: Returns the status of the executed SAM request (zero on success and
  1654. * negative on direct failure) or %-EPROTO if the request response indicates a
  1655. * failure.
  1656. */
  1657. static int ssam_ssh_event_enable(struct ssam_controller *ctrl,
  1658. struct ssam_event_registry reg,
  1659. struct ssam_event_id id, u8 flags)
  1660. {
  1661. int status;
  1662. status = __ssam_ssh_event_request(ctrl, reg, reg.cid_enable, id, flags);
  1663. if (status < 0 && status != -EINVAL) {
  1664. ssam_err(ctrl,
  1665. "failed to enable event source (tc: %#04x, iid: %#04x, reg: %#04x)\n",
  1666. id.target_category, id.instance, reg.target_category);
  1667. }
  1668. if (status > 0) {
  1669. ssam_err(ctrl,
  1670. "unexpected result while enabling event source: %#04x (tc: %#04x, iid: %#04x, reg: %#04x)\n",
  1671. status, id.target_category, id.instance, reg.target_category);
  1672. return -EPROTO;
  1673. }
  1674. return status;
  1675. }
  1676. /**
  1677. * ssam_ssh_event_disable() - Disable SSH event.
  1678. * @ctrl: The controller for which to disable the event.
  1679. * @reg: The event registry describing what request to use for enabling and
  1680. * disabling the event (must be same as used when enabling the event).
  1681. * @id: The event identifier.
  1682. * @flags: The event flags (likely ignored for disabling of events).
  1683. *
  1684. * Disables the specified event on the EC. This function does not manage
  1685. * reference counting of enabled events and is basically only a wrapper for
  1686. * the raw EC request. If the specified event is already disabled, the EC will
  1687. * ignore this request.
  1688. *
  1689. * Return: Returns the status of the executed SAM request (zero on success and
  1690. * negative on direct failure) or %-EPROTO if the request response indicates a
  1691. * failure.
  1692. */
  1693. static int ssam_ssh_event_disable(struct ssam_controller *ctrl,
  1694. struct ssam_event_registry reg,
  1695. struct ssam_event_id id, u8 flags)
  1696. {
  1697. int status;
  1698. status = __ssam_ssh_event_request(ctrl, reg, reg.cid_disable, id, flags);
  1699. if (status < 0 && status != -EINVAL) {
  1700. ssam_err(ctrl,
  1701. "failed to disable event source (tc: %#04x, iid: %#04x, reg: %#04x)\n",
  1702. id.target_category, id.instance, reg.target_category);
  1703. }
  1704. if (status > 0) {
  1705. ssam_err(ctrl,
  1706. "unexpected result while disabling event source: %#04x (tc: %#04x, iid: %#04x, reg: %#04x)\n",
  1707. status, id.target_category, id.instance, reg.target_category);
  1708. return -EPROTO;
  1709. }
  1710. return status;
  1711. }
  1712. /* -- Wrappers for internal SAM requests. ----------------------------------- */
  1713. /**
  1714. * ssam_get_firmware_version() - Get the SAM/EC firmware version.
  1715. * @ctrl: The controller.
  1716. * @version: Where to store the version number.
  1717. *
  1718. * Return: Returns zero on success or the status of the executed SAM request
  1719. * if that request failed.
  1720. */
  1721. int ssam_get_firmware_version(struct ssam_controller *ctrl, u32 *version)
  1722. {
  1723. __le32 __version;
  1724. int status;
  1725. status = ssam_retry(ssam_ssh_get_firmware_version, ctrl, &__version);
  1726. if (status)
  1727. return status;
  1728. *version = le32_to_cpu(__version);
  1729. return 0;
  1730. }
  1731. /**
  1732. * ssam_ctrl_notif_display_off() - Notify EC that the display has been turned
  1733. * off.
  1734. * @ctrl: The controller.
  1735. *
  1736. * Notify the EC that the display has been turned off and the driver may enter
  1737. * a lower-power state. This will prevent events from being sent directly.
  1738. * Rather, the EC signals an event by pulling the wakeup GPIO high for as long
  1739. * as there are pending events. The events then need to be manually released,
  1740. * one by one, via the GPIO callback request. All pending events accumulated
  1741. * during this state can also be released by issuing the display-on
  1742. * notification, e.g. via ssam_ctrl_notif_display_on(), which will also reset
  1743. * the GPIO.
  1744. *
  1745. * On some devices, specifically ones with an integrated keyboard, the keyboard
  1746. * backlight will be turned off by this call.
  1747. *
  1748. * This function will only send the display-off notification command if
  1749. * display notifications are supported by the EC. Currently all known devices
  1750. * support these notifications.
  1751. *
  1752. * Use ssam_ctrl_notif_display_on() to reverse the effects of this function.
  1753. *
  1754. * Return: Returns zero on success or if no request has been executed, the
  1755. * status of the executed SAM request if that request failed, or %-EPROTO if
  1756. * an unexpected response has been received.
  1757. */
  1758. int ssam_ctrl_notif_display_off(struct ssam_controller *ctrl)
  1759. {
  1760. int status;
  1761. u8 response;
  1762. ssam_dbg(ctrl, "pm: notifying display off\n");
  1763. status = ssam_retry(ssam_ssh_notif_display_off, ctrl, &response);
  1764. if (status)
  1765. return status;
  1766. if (response != 0) {
  1767. ssam_err(ctrl, "unexpected response from display-off notification: %#04x\n",
  1768. response);
  1769. return -EPROTO;
  1770. }
  1771. return 0;
  1772. }
  1773. /**
  1774. * ssam_ctrl_notif_display_on() - Notify EC that the display has been turned on.
  1775. * @ctrl: The controller.
  1776. *
  1777. * Notify the EC that the display has been turned back on and the driver has
  1778. * exited its lower-power state. This notification is the counterpart to the
  1779. * display-off notification sent via ssam_ctrl_notif_display_off() and will
  1780. * reverse its effects, including resetting events to their default behavior.
  1781. *
  1782. * This function will only send the display-on notification command if display
  1783. * notifications are supported by the EC. Currently all known devices support
  1784. * these notifications.
  1785. *
  1786. * See ssam_ctrl_notif_display_off() for more details.
  1787. *
  1788. * Return: Returns zero on success or if no request has been executed, the
  1789. * status of the executed SAM request if that request failed, or %-EPROTO if
  1790. * an unexpected response has been received.
  1791. */
  1792. int ssam_ctrl_notif_display_on(struct ssam_controller *ctrl)
  1793. {
  1794. int status;
  1795. u8 response;
  1796. ssam_dbg(ctrl, "pm: notifying display on\n");
  1797. status = ssam_retry(ssam_ssh_notif_display_on, ctrl, &response);
  1798. if (status)
  1799. return status;
  1800. if (response != 0) {
  1801. ssam_err(ctrl, "unexpected response from display-on notification: %#04x\n",
  1802. response);
  1803. return -EPROTO;
  1804. }
  1805. return 0;
  1806. }
  1807. /**
  1808. * ssam_ctrl_notif_d0_exit() - Notify EC that the driver/device exits the D0
  1809. * power state.
  1810. * @ctrl: The controller
  1811. *
  1812. * Notifies the EC that the driver prepares to exit the D0 power state in
  1813. * favor of a lower-power state. Exact effects of this function related to the
  1814. * EC are currently unknown.
  1815. *
  1816. * This function will only send the D0-exit notification command if D0-state
  1817. * notifications are supported by the EC. Only newer Surface generations
  1818. * support these notifications.
  1819. *
  1820. * Use ssam_ctrl_notif_d0_entry() to reverse the effects of this function.
  1821. *
  1822. * Return: Returns zero on success or if no request has been executed, the
  1823. * status of the executed SAM request if that request failed, or %-EPROTO if
  1824. * an unexpected response has been received.
  1825. */
  1826. int ssam_ctrl_notif_d0_exit(struct ssam_controller *ctrl)
  1827. {
  1828. int status;
  1829. u8 response;
  1830. if (!ctrl->caps.d3_closes_handle)
  1831. return 0;
  1832. ssam_dbg(ctrl, "pm: notifying D0 exit\n");
  1833. status = ssam_retry(ssam_ssh_notif_d0_exit, ctrl, &response);
  1834. if (status)
  1835. return status;
  1836. if (response != 0) {
  1837. ssam_err(ctrl, "unexpected response from D0-exit notification: %#04x\n",
  1838. response);
  1839. return -EPROTO;
  1840. }
  1841. return 0;
  1842. }
  1843. /**
  1844. * ssam_ctrl_notif_d0_entry() - Notify EC that the driver/device enters the D0
  1845. * power state.
  1846. * @ctrl: The controller
  1847. *
  1848. * Notifies the EC that the driver has exited a lower-power state and entered
  1849. * the D0 power state. Exact effects of this function related to the EC are
  1850. * currently unknown.
  1851. *
  1852. * This function will only send the D0-entry notification command if D0-state
  1853. * notifications are supported by the EC. Only newer Surface generations
  1854. * support these notifications.
  1855. *
  1856. * See ssam_ctrl_notif_d0_exit() for more details.
  1857. *
  1858. * Return: Returns zero on success or if no request has been executed, the
  1859. * status of the executed SAM request if that request failed, or %-EPROTO if
  1860. * an unexpected response has been received.
  1861. */
  1862. int ssam_ctrl_notif_d0_entry(struct ssam_controller *ctrl)
  1863. {
  1864. int status;
  1865. u8 response;
  1866. if (!ctrl->caps.d3_closes_handle)
  1867. return 0;
  1868. ssam_dbg(ctrl, "pm: notifying D0 entry\n");
  1869. status = ssam_retry(ssam_ssh_notif_d0_entry, ctrl, &response);
  1870. if (status)
  1871. return status;
  1872. if (response != 0) {
  1873. ssam_err(ctrl, "unexpected response from D0-entry notification: %#04x\n",
  1874. response);
  1875. return -EPROTO;
  1876. }
  1877. return 0;
  1878. }
  1879. /* -- Top-level event registry interface. ----------------------------------- */
  1880. /**
  1881. * ssam_nf_refcount_enable() - Enable event for reference count entry if it has
  1882. * not already been enabled.
  1883. * @ctrl: The controller to enable the event on.
  1884. * @entry: The reference count entry for the event to be enabled.
  1885. * @flags: The flags used for enabling the event on the EC.
  1886. *
  1887. * Enable the event associated with the given reference count entry if the
  1888. * reference count equals one, i.e. the event has not previously been enabled.
  1889. * If the event has already been enabled (i.e. reference count not equal to
  1890. * one), check that the flags used for enabling match and warn about this if
  1891. * they do not.
  1892. *
  1893. * This does not modify the reference count itself, which is done with
  1894. * ssam_nf_refcount_inc() / ssam_nf_refcount_dec().
  1895. *
  1896. * Note: ``nf->lock`` must be held when calling this function.
  1897. *
  1898. * Return: Returns zero on success. If the event is enabled by this call,
  1899. * returns the status of the event-enable EC command.
  1900. */
  1901. static int ssam_nf_refcount_enable(struct ssam_controller *ctrl,
  1902. struct ssam_nf_refcount_entry *entry, u8 flags)
  1903. {
  1904. const struct ssam_event_registry reg = entry->key.reg;
  1905. const struct ssam_event_id id = entry->key.id;
  1906. struct ssam_nf *nf = &ctrl->cplt.event.notif;
  1907. int status;
  1908. lockdep_assert_held(&nf->lock);
  1909. ssam_dbg(ctrl, "enabling event (reg: %#04x, tc: %#04x, iid: %#04x, rc: %d)\n",
  1910. reg.target_category, id.target_category, id.instance, entry->refcount);
  1911. if (entry->refcount == 1) {
  1912. status = ssam_ssh_event_enable(ctrl, reg, id, flags);
  1913. if (status)
  1914. return status;
  1915. entry->flags = flags;
  1916. } else if (entry->flags != flags) {
  1917. ssam_warn(ctrl,
  1918. "inconsistent flags when enabling event: got %#04x, expected %#04x (reg: %#04x, tc: %#04x, iid: %#04x)\n",
  1919. flags, entry->flags, reg.target_category, id.target_category,
  1920. id.instance);
  1921. }
  1922. return 0;
  1923. }
  1924. /**
  1925. * ssam_nf_refcount_disable_free() - Disable event for reference count entry if
  1926. * it is no longer in use and free the corresponding entry.
  1927. * @ctrl: The controller to disable the event on.
  1928. * @entry: The reference count entry for the event to be disabled.
  1929. * @flags: The flags used for enabling the event on the EC.
  1930. * @ec: Flag specifying if the event should actually be disabled on the EC.
  1931. *
  1932. * If ``ec`` equals ``true`` and the reference count equals zero (i.e. the
  1933. * event is no longer requested by any client), the specified event will be
  1934. * disabled on the EC via the corresponding request.
  1935. *
  1936. * If ``ec`` equals ``false``, no request will be sent to the EC and the event
  1937. * can be considered in a detached state (i.e. no longer used but still
  1938. * enabled). Disabling an event via this method may be required for
  1939. * hot-removable devices, where event disable requests may time out after the
  1940. * device has been physically removed.
  1941. *
  1942. * In both cases, if the reference count equals zero, the corresponding
  1943. * reference count entry will be freed. The reference count entry must not be
  1944. * used any more after a call to this function.
  1945. *
  1946. * Also checks if the flags used for disabling the event match the flags used
  1947. * for enabling the event and warns if they do not (regardless of reference
  1948. * count).
  1949. *
  1950. * This does not modify the reference count itself, which is done with
  1951. * ssam_nf_refcount_inc() / ssam_nf_refcount_dec().
  1952. *
  1953. * Note: ``nf->lock`` must be held when calling this function.
  1954. *
  1955. * Return: Returns zero on success. If the event is disabled by this call,
  1956. * returns the status of the event-enable EC command.
  1957. */
  1958. static int ssam_nf_refcount_disable_free(struct ssam_controller *ctrl,
  1959. struct ssam_nf_refcount_entry *entry, u8 flags, bool ec)
  1960. {
  1961. const struct ssam_event_registry reg = entry->key.reg;
  1962. const struct ssam_event_id id = entry->key.id;
  1963. struct ssam_nf *nf = &ctrl->cplt.event.notif;
  1964. int status = 0;
  1965. lockdep_assert_held(&nf->lock);
  1966. ssam_dbg(ctrl, "%s event (reg: %#04x, tc: %#04x, iid: %#04x, rc: %d)\n",
  1967. ec ? "disabling" : "detaching", reg.target_category, id.target_category,
  1968. id.instance, entry->refcount);
  1969. if (entry->flags != flags) {
  1970. ssam_warn(ctrl,
  1971. "inconsistent flags when disabling event: got %#04x, expected %#04x (reg: %#04x, tc: %#04x, iid: %#04x)\n",
  1972. flags, entry->flags, reg.target_category, id.target_category,
  1973. id.instance);
  1974. }
  1975. if (ec && entry->refcount == 0) {
  1976. status = ssam_ssh_event_disable(ctrl, reg, id, flags);
  1977. kfree(entry);
  1978. }
  1979. return status;
  1980. }
  1981. /**
  1982. * ssam_notifier_register() - Register an event notifier.
  1983. * @ctrl: The controller to register the notifier on.
  1984. * @n: The event notifier to register.
  1985. *
  1986. * Register an event notifier. Increment the usage counter of the associated
  1987. * SAM event if the notifier is not marked as an observer. If the event is not
  1988. * marked as an observer and is currently not enabled, it will be enabled
  1989. * during this call. If the notifier is marked as an observer, no attempt will
  1990. * be made at enabling any event and no reference count will be modified.
  1991. *
  1992. * Notifiers marked as observers do not need to be associated with one specific
  1993. * event, i.e. as long as no event matching is performed, only the event target
  1994. * category needs to be set.
  1995. *
  1996. * Return: Returns zero on success, %-ENOSPC if there have already been
  1997. * %INT_MAX notifiers for the event ID/type associated with the notifier block
  1998. * registered, %-ENOMEM if the corresponding event entry could not be
  1999. * allocated. If this is the first time that a notifier block is registered
  2000. * for the specific associated event, returns the status of the event-enable
  2001. * EC-command.
  2002. */
  2003. int ssam_notifier_register(struct ssam_controller *ctrl, struct ssam_event_notifier *n)
  2004. {
  2005. u16 rqid = ssh_tc_to_rqid(n->event.id.target_category);
  2006. struct ssam_nf_refcount_entry *entry = NULL;
  2007. struct ssam_nf_head *nf_head;
  2008. struct ssam_nf *nf;
  2009. int status;
  2010. if (!ssh_rqid_is_event(rqid))
  2011. return -EINVAL;
  2012. nf = &ctrl->cplt.event.notif;
  2013. nf_head = &nf->head[ssh_rqid_to_event(rqid)];
  2014. mutex_lock(&nf->lock);
  2015. if (!(n->flags & SSAM_EVENT_NOTIFIER_OBSERVER)) {
  2016. entry = ssam_nf_refcount_inc(nf, n->event.reg, n->event.id);
  2017. if (IS_ERR(entry)) {
  2018. mutex_unlock(&nf->lock);
  2019. return PTR_ERR(entry);
  2020. }
  2021. }
  2022. status = ssam_nfblk_insert(nf_head, &n->base);
  2023. if (status) {
  2024. if (entry)
  2025. ssam_nf_refcount_dec_free(nf, n->event.reg, n->event.id);
  2026. mutex_unlock(&nf->lock);
  2027. return status;
  2028. }
  2029. if (entry) {
  2030. status = ssam_nf_refcount_enable(ctrl, entry, n->event.flags);
  2031. if (status) {
  2032. ssam_nfblk_remove(&n->base);
  2033. ssam_nf_refcount_dec_free(nf, n->event.reg, n->event.id);
  2034. mutex_unlock(&nf->lock);
  2035. synchronize_srcu(&nf_head->srcu);
  2036. return status;
  2037. }
  2038. }
  2039. mutex_unlock(&nf->lock);
  2040. return 0;
  2041. }
  2042. EXPORT_SYMBOL_GPL(ssam_notifier_register);
  2043. /**
  2044. * __ssam_notifier_unregister() - Unregister an event notifier.
  2045. * @ctrl: The controller the notifier has been registered on.
  2046. * @n: The event notifier to unregister.
  2047. * @disable: Whether to disable the corresponding event on the EC.
  2048. *
  2049. * Unregister an event notifier. Decrement the usage counter of the associated
  2050. * SAM event if the notifier is not marked as an observer. If the usage counter
  2051. * reaches zero and ``disable`` equals ``true``, the event will be disabled.
  2052. *
  2053. * Useful for hot-removable devices, where communication may fail once the
  2054. * device has been physically removed. In that case, specifying ``disable`` as
  2055. * ``false`` avoids communication with the EC.
  2056. *
  2057. * Return: Returns zero on success, %-ENOENT if the given notifier block has
  2058. * not been registered on the controller. If the given notifier block was the
  2059. * last one associated with its specific event, returns the status of the
  2060. * event-disable EC-command.
  2061. */
  2062. int __ssam_notifier_unregister(struct ssam_controller *ctrl, struct ssam_event_notifier *n,
  2063. bool disable)
  2064. {
  2065. u16 rqid = ssh_tc_to_rqid(n->event.id.target_category);
  2066. struct ssam_nf_refcount_entry *entry;
  2067. struct ssam_nf_head *nf_head;
  2068. struct ssam_nf *nf;
  2069. int status = 0;
  2070. if (!ssh_rqid_is_event(rqid))
  2071. return -EINVAL;
  2072. nf = &ctrl->cplt.event.notif;
  2073. nf_head = &nf->head[ssh_rqid_to_event(rqid)];
  2074. mutex_lock(&nf->lock);
  2075. if (!ssam_nfblk_find(nf_head, &n->base)) {
  2076. mutex_unlock(&nf->lock);
  2077. return -ENOENT;
  2078. }
  2079. /*
  2080. * If this is an observer notifier, do not attempt to disable the
  2081. * event, just remove it.
  2082. */
  2083. if (!(n->flags & SSAM_EVENT_NOTIFIER_OBSERVER)) {
  2084. entry = ssam_nf_refcount_dec(nf, n->event.reg, n->event.id);
  2085. if (WARN_ON(!entry)) {
  2086. /*
  2087. * If this does not return an entry, there's a logic
  2088. * error somewhere: The notifier block is registered,
  2089. * but the event refcount entry is not there. Remove
  2090. * the notifier block anyways.
  2091. */
  2092. status = -ENOENT;
  2093. goto remove;
  2094. }
  2095. status = ssam_nf_refcount_disable_free(ctrl, entry, n->event.flags, disable);
  2096. }
  2097. remove:
  2098. ssam_nfblk_remove(&n->base);
  2099. mutex_unlock(&nf->lock);
  2100. synchronize_srcu(&nf_head->srcu);
  2101. return status;
  2102. }
  2103. EXPORT_SYMBOL_GPL(__ssam_notifier_unregister);
  2104. /**
  2105. * ssam_controller_event_enable() - Enable the specified event.
  2106. * @ctrl: The controller to enable the event for.
  2107. * @reg: The event registry to use for enabling the event.
  2108. * @id: The event ID specifying the event to be enabled.
  2109. * @flags: The SAM event flags used for enabling the event.
  2110. *
  2111. * Increment the event reference count of the specified event. If the event has
  2112. * not been enabled previously, it will be enabled by this call.
  2113. *
  2114. * Note: In general, ssam_notifier_register() with a non-observer notifier
  2115. * should be preferred for enabling/disabling events, as this will guarantee
  2116. * proper ordering and event forwarding in case of errors during event
  2117. * enabling/disabling.
  2118. *
  2119. * Return: Returns zero on success, %-ENOSPC if the reference count for the
  2120. * specified event has reached its maximum, %-ENOMEM if the corresponding event
  2121. * entry could not be allocated. If this is the first time that this event has
  2122. * been enabled (i.e. the reference count was incremented from zero to one by
  2123. * this call), returns the status of the event-enable EC-command.
  2124. */
  2125. int ssam_controller_event_enable(struct ssam_controller *ctrl,
  2126. struct ssam_event_registry reg,
  2127. struct ssam_event_id id, u8 flags)
  2128. {
  2129. u16 rqid = ssh_tc_to_rqid(id.target_category);
  2130. struct ssam_nf *nf = &ctrl->cplt.event.notif;
  2131. struct ssam_nf_refcount_entry *entry;
  2132. int status;
  2133. if (!ssh_rqid_is_event(rqid))
  2134. return -EINVAL;
  2135. mutex_lock(&nf->lock);
  2136. entry = ssam_nf_refcount_inc(nf, reg, id);
  2137. if (IS_ERR(entry)) {
  2138. mutex_unlock(&nf->lock);
  2139. return PTR_ERR(entry);
  2140. }
  2141. status = ssam_nf_refcount_enable(ctrl, entry, flags);
  2142. if (status) {
  2143. ssam_nf_refcount_dec_free(nf, reg, id);
  2144. mutex_unlock(&nf->lock);
  2145. return status;
  2146. }
  2147. mutex_unlock(&nf->lock);
  2148. return 0;
  2149. }
  2150. EXPORT_SYMBOL_GPL(ssam_controller_event_enable);
  2151. /**
  2152. * ssam_controller_event_disable() - Disable the specified event.
  2153. * @ctrl: The controller to disable the event for.
  2154. * @reg: The event registry to use for disabling the event.
  2155. * @id: The event ID specifying the event to be disabled.
  2156. * @flags: The flags used when enabling the event.
  2157. *
  2158. * Decrement the reference count of the specified event. If the reference count
  2159. * reaches zero, the event will be disabled.
  2160. *
  2161. * Note: In general, ssam_notifier_register()/ssam_notifier_unregister() with a
  2162. * non-observer notifier should be preferred for enabling/disabling events, as
  2163. * this will guarantee proper ordering and event forwarding in case of errors
  2164. * during event enabling/disabling.
  2165. *
  2166. * Return: Returns zero on success, %-ENOENT if the given event has not been
  2167. * enabled on the controller. If the reference count of the event reaches zero
  2168. * during this call, returns the status of the event-disable EC-command.
  2169. */
  2170. int ssam_controller_event_disable(struct ssam_controller *ctrl,
  2171. struct ssam_event_registry reg,
  2172. struct ssam_event_id id, u8 flags)
  2173. {
  2174. u16 rqid = ssh_tc_to_rqid(id.target_category);
  2175. struct ssam_nf *nf = &ctrl->cplt.event.notif;
  2176. struct ssam_nf_refcount_entry *entry;
  2177. int status;
  2178. if (!ssh_rqid_is_event(rqid))
  2179. return -EINVAL;
  2180. mutex_lock(&nf->lock);
  2181. entry = ssam_nf_refcount_dec(nf, reg, id);
  2182. if (!entry) {
  2183. mutex_unlock(&nf->lock);
  2184. return -ENOENT;
  2185. }
  2186. status = ssam_nf_refcount_disable_free(ctrl, entry, flags, true);
  2187. mutex_unlock(&nf->lock);
  2188. return status;
  2189. }
  2190. EXPORT_SYMBOL_GPL(ssam_controller_event_disable);
  2191. /**
  2192. * ssam_notifier_disable_registered() - Disable events for all registered
  2193. * notifiers.
  2194. * @ctrl: The controller for which to disable the notifiers/events.
  2195. *
  2196. * Disables events for all currently registered notifiers. In case of an error
  2197. * (EC command failing), all previously disabled events will be restored and
  2198. * the error code returned.
  2199. *
  2200. * This function is intended to disable all events prior to hibernation entry.
  2201. * See ssam_notifier_restore_registered() to restore/re-enable all events
  2202. * disabled with this function.
  2203. *
  2204. * Note that this function will not disable events for notifiers registered
  2205. * after calling this function. It should thus be made sure that no new
  2206. * notifiers are going to be added after this call and before the corresponding
  2207. * call to ssam_notifier_restore_registered().
  2208. *
  2209. * Return: Returns zero on success. In case of failure returns the error code
  2210. * returned by the failed EC command to disable an event.
  2211. */
  2212. int ssam_notifier_disable_registered(struct ssam_controller *ctrl)
  2213. {
  2214. struct ssam_nf *nf = &ctrl->cplt.event.notif;
  2215. struct rb_node *n;
  2216. int status;
  2217. mutex_lock(&nf->lock);
  2218. for (n = rb_first(&nf->refcount); n; n = rb_next(n)) {
  2219. struct ssam_nf_refcount_entry *e;
  2220. e = rb_entry(n, struct ssam_nf_refcount_entry, node);
  2221. status = ssam_ssh_event_disable(ctrl, e->key.reg,
  2222. e->key.id, e->flags);
  2223. if (status)
  2224. goto err;
  2225. }
  2226. mutex_unlock(&nf->lock);
  2227. return 0;
  2228. err:
  2229. for (n = rb_prev(n); n; n = rb_prev(n)) {
  2230. struct ssam_nf_refcount_entry *e;
  2231. e = rb_entry(n, struct ssam_nf_refcount_entry, node);
  2232. ssam_ssh_event_enable(ctrl, e->key.reg, e->key.id, e->flags);
  2233. }
  2234. mutex_unlock(&nf->lock);
  2235. return status;
  2236. }
  2237. /**
  2238. * ssam_notifier_restore_registered() - Restore/re-enable events for all
  2239. * registered notifiers.
  2240. * @ctrl: The controller for which to restore the notifiers/events.
  2241. *
  2242. * Restores/re-enables all events for which notifiers have been registered on
  2243. * the given controller. In case of a failure, the error is logged and the
  2244. * function continues to try and enable the remaining events.
  2245. *
  2246. * This function is intended to restore/re-enable all registered events after
  2247. * hibernation. See ssam_notifier_disable_registered() for the counter part
  2248. * disabling the events and more details.
  2249. */
  2250. void ssam_notifier_restore_registered(struct ssam_controller *ctrl)
  2251. {
  2252. struct ssam_nf *nf = &ctrl->cplt.event.notif;
  2253. struct rb_node *n;
  2254. mutex_lock(&nf->lock);
  2255. for (n = rb_first(&nf->refcount); n; n = rb_next(n)) {
  2256. struct ssam_nf_refcount_entry *e;
  2257. e = rb_entry(n, struct ssam_nf_refcount_entry, node);
  2258. /* Ignore errors, will get logged in call. */
  2259. ssam_ssh_event_enable(ctrl, e->key.reg, e->key.id, e->flags);
  2260. }
  2261. mutex_unlock(&nf->lock);
  2262. }
  2263. /**
  2264. * ssam_notifier_is_empty() - Check if there are any registered notifiers.
  2265. * @ctrl: The controller to check on.
  2266. *
  2267. * Return: Returns %true if there are currently no notifiers registered on the
  2268. * controller, %false otherwise.
  2269. */
  2270. static bool ssam_notifier_is_empty(struct ssam_controller *ctrl)
  2271. {
  2272. struct ssam_nf *nf = &ctrl->cplt.event.notif;
  2273. bool result;
  2274. mutex_lock(&nf->lock);
  2275. result = ssam_nf_refcount_empty(nf);
  2276. mutex_unlock(&nf->lock);
  2277. return result;
  2278. }
  2279. /**
  2280. * ssam_notifier_unregister_all() - Unregister all currently registered
  2281. * notifiers.
  2282. * @ctrl: The controller to unregister the notifiers on.
  2283. *
  2284. * Unregisters all currently registered notifiers. This function is used to
  2285. * ensure that all notifiers will be unregistered and associated
  2286. * entries/resources freed when the controller is being shut down.
  2287. */
  2288. static void ssam_notifier_unregister_all(struct ssam_controller *ctrl)
  2289. {
  2290. struct ssam_nf *nf = &ctrl->cplt.event.notif;
  2291. struct ssam_nf_refcount_entry *e, *n;
  2292. mutex_lock(&nf->lock);
  2293. rbtree_postorder_for_each_entry_safe(e, n, &nf->refcount, node) {
  2294. /* Ignore errors, will get logged in call. */
  2295. ssam_ssh_event_disable(ctrl, e->key.reg, e->key.id, e->flags);
  2296. kfree(e);
  2297. }
  2298. nf->refcount = RB_ROOT;
  2299. mutex_unlock(&nf->lock);
  2300. }
  2301. /* -- Wakeup IRQ. ----------------------------------------------------------- */
  2302. static irqreturn_t ssam_irq_handle(int irq, void *dev_id)
  2303. {
  2304. struct ssam_controller *ctrl = dev_id;
  2305. ssam_dbg(ctrl, "pm: wake irq triggered\n");
  2306. /*
  2307. * Note: Proper wakeup detection is currently unimplemented.
  2308. * When the EC is in display-off or any other non-D0 state, it
  2309. * does not send events/notifications to the host. Instead it
  2310. * signals that there are events available via the wakeup IRQ.
  2311. * This driver is responsible for calling back to the EC to
  2312. * release these events one-by-one.
  2313. *
  2314. * This IRQ should not cause a full system resume by its own.
  2315. * Instead, events should be handled by their respective subsystem
  2316. * drivers, which in turn should signal whether a full system
  2317. * resume should be performed.
  2318. *
  2319. * TODO: Send GPIO callback command repeatedly to EC until callback
  2320. * returns 0x00. Return flag of callback is "has more events".
  2321. * Each time the command is sent, one event is "released". Once
  2322. * all events have been released (return = 0x00), the GPIO is
  2323. * re-armed. Detect wakeup events during this process, go back to
  2324. * sleep if no wakeup event has been received.
  2325. */
  2326. return IRQ_HANDLED;
  2327. }
  2328. /**
  2329. * ssam_irq_setup() - Set up SAM EC wakeup-GPIO interrupt.
  2330. * @ctrl: The controller for which the IRQ should be set up.
  2331. *
  2332. * Set up an IRQ for the wakeup-GPIO pin of the SAM EC. This IRQ can be used
  2333. * to wake the device from a low power state.
  2334. *
  2335. * Note that this IRQ can only be triggered while the EC is in the display-off
  2336. * state. In this state, events are not sent to the host in the usual way.
  2337. * Instead the wakeup-GPIO gets pulled to "high" as long as there are pending
  2338. * events and these events need to be released one-by-one via the GPIO
  2339. * callback request, either until there are no events left and the GPIO is
  2340. * reset, or all at once by transitioning the EC out of the display-off state,
  2341. * which will also clear the GPIO.
  2342. *
  2343. * Not all events, however, should trigger a full system wakeup. Instead the
  2344. * driver should, if necessary, inspect and forward each event to the
  2345. * corresponding subsystem, which in turn should decide if the system needs to
  2346. * be woken up. This logic has not been implemented yet, thus wakeup by this
  2347. * IRQ should be disabled by default to avoid spurious wake-ups, caused, for
  2348. * example, by the remaining battery percentage changing. Refer to comments in
  2349. * this function and comments in the corresponding IRQ handler for more
  2350. * details on how this should be implemented.
  2351. *
  2352. * See also ssam_ctrl_notif_display_off() and ssam_ctrl_notif_display_off()
  2353. * for functions to transition the EC into and out of the display-off state as
  2354. * well as more details on it.
  2355. *
  2356. * The IRQ is disabled by default and has to be enabled before it can wake up
  2357. * the device from suspend via ssam_irq_arm_for_wakeup(). On teardown, the IRQ
  2358. * should be freed via ssam_irq_free().
  2359. */
  2360. int ssam_irq_setup(struct ssam_controller *ctrl)
  2361. {
  2362. struct device *dev = ssam_controller_device(ctrl);
  2363. struct gpio_desc *gpiod;
  2364. int irq;
  2365. int status;
  2366. /*
  2367. * The actual GPIO interrupt is declared in ACPI as TRIGGER_HIGH.
  2368. * However, the GPIO line only gets reset by sending the GPIO callback
  2369. * command to SAM (or alternatively the display-on notification). As
  2370. * proper handling for this interrupt is not implemented yet, leaving
  2371. * the IRQ at TRIGGER_HIGH would cause an IRQ storm (as the callback
  2372. * never gets sent and thus the line never gets reset). To avoid this,
  2373. * mark the IRQ as TRIGGER_RISING for now, only creating a single
  2374. * interrupt, and let the SAM resume callback during the controller
  2375. * resume process clear it.
  2376. */
  2377. const int irqf = IRQF_ONESHOT | IRQF_TRIGGER_RISING | IRQF_NO_AUTOEN;
  2378. gpiod = gpiod_get(dev, "ssam_wakeup-int", GPIOD_ASIS);
  2379. if (IS_ERR(gpiod)) {
  2380. irq = fwnode_irq_get(dev_fwnode(dev), 0);
  2381. } else {
  2382. irq = gpiod_to_irq(gpiod);
  2383. gpiod_put(gpiod);
  2384. }
  2385. if (irq < 0)
  2386. return irq;
  2387. status = request_threaded_irq(irq, NULL, ssam_irq_handle, irqf,
  2388. "ssam_wakeup", ctrl);
  2389. if (status)
  2390. return status;
  2391. ctrl->irq.num = irq;
  2392. return 0;
  2393. }
  2394. /**
  2395. * ssam_irq_free() - Free SAM EC wakeup-GPIO interrupt.
  2396. * @ctrl: The controller for which the IRQ should be freed.
  2397. *
  2398. * Free the wakeup-GPIO IRQ previously set-up via ssam_irq_setup().
  2399. */
  2400. void ssam_irq_free(struct ssam_controller *ctrl)
  2401. {
  2402. free_irq(ctrl->irq.num, ctrl);
  2403. ctrl->irq.num = -1;
  2404. }
  2405. /**
  2406. * ssam_irq_arm_for_wakeup() - Arm the EC IRQ for wakeup, if enabled.
  2407. * @ctrl: The controller for which the IRQ should be armed.
  2408. *
  2409. * Sets up the IRQ so that it can be used to wake the device. Specifically,
  2410. * this function enables the irq and then, if the device is allowed to wake up
  2411. * the system, calls enable_irq_wake(). See ssam_irq_disarm_wakeup() for the
  2412. * corresponding function to disable the IRQ.
  2413. *
  2414. * This function is intended to arm the IRQ before entering S2idle suspend.
  2415. *
  2416. * Note: calls to ssam_irq_arm_for_wakeup() and ssam_irq_disarm_wakeup() must
  2417. * be balanced.
  2418. */
  2419. int ssam_irq_arm_for_wakeup(struct ssam_controller *ctrl)
  2420. {
  2421. struct device *dev = ssam_controller_device(ctrl);
  2422. int status;
  2423. enable_irq(ctrl->irq.num);
  2424. if (device_may_wakeup(dev)) {
  2425. status = enable_irq_wake(ctrl->irq.num);
  2426. if (status) {
  2427. ssam_err(ctrl, "failed to enable wake IRQ: %d\n", status);
  2428. disable_irq(ctrl->irq.num);
  2429. return status;
  2430. }
  2431. ctrl->irq.wakeup_enabled = true;
  2432. } else {
  2433. ctrl->irq.wakeup_enabled = false;
  2434. }
  2435. return 0;
  2436. }
  2437. /**
  2438. * ssam_irq_disarm_wakeup() - Disarm the wakeup IRQ.
  2439. * @ctrl: The controller for which the IRQ should be disarmed.
  2440. *
  2441. * Disarm the IRQ previously set up for wake via ssam_irq_arm_for_wakeup().
  2442. *
  2443. * This function is intended to disarm the IRQ after exiting S2idle suspend.
  2444. *
  2445. * Note: calls to ssam_irq_arm_for_wakeup() and ssam_irq_disarm_wakeup() must
  2446. * be balanced.
  2447. */
  2448. void ssam_irq_disarm_wakeup(struct ssam_controller *ctrl)
  2449. {
  2450. int status;
  2451. if (ctrl->irq.wakeup_enabled) {
  2452. status = disable_irq_wake(ctrl->irq.num);
  2453. if (status)
  2454. ssam_err(ctrl, "failed to disable wake IRQ: %d\n", status);
  2455. ctrl->irq.wakeup_enabled = false;
  2456. }
  2457. disable_irq(ctrl->irq.num);
  2458. }