notify.c 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * System Control and Management Interface (SCMI) Notification support
  4. *
  5. * Copyright (C) 2020-2021 ARM Ltd.
  6. */
  7. /**
  8. * DOC: Theory of operation
  9. *
  10. * SCMI Protocol specification allows the platform to signal events to
  11. * interested agents via notification messages: this is an implementation
  12. * of the dispatch and delivery of such notifications to the interested users
  13. * inside the Linux kernel.
  14. *
  15. * An SCMI Notification core instance is initialized for each active platform
  16. * instance identified by the means of the usual &struct scmi_handle.
  17. *
  18. * Each SCMI Protocol implementation, during its initialization, registers with
  19. * this core its set of supported events using scmi_register_protocol_events():
  20. * all the needed descriptors are stored in the &struct registered_protocols and
  21. * &struct registered_events arrays.
  22. *
  23. * Kernel users interested in some specific event can register their callbacks
  24. * providing the usual notifier_block descriptor, since this core implements
  25. * events' delivery using the standard Kernel notification chains machinery.
  26. *
  27. * Given the number of possible events defined by SCMI and the extensibility
  28. * of the SCMI Protocol itself, the underlying notification chains are created
  29. * and destroyed dynamically on demand depending on the number of users
  30. * effectively registered for an event, so that no support structures or chains
  31. * are allocated until at least one user has registered a notifier_block for
  32. * such event. Similarly, events' generation itself is enabled at the platform
  33. * level only after at least one user has registered, and it is shutdown after
  34. * the last user for that event has gone.
  35. *
  36. * All users provided callbacks and allocated notification-chains are stored in
  37. * the @registered_events_handlers hashtable. Callbacks' registration requests
  38. * for still to be registered events are instead kept in the dedicated common
  39. * hashtable @pending_events_handlers.
  40. *
  41. * An event is identified univocally by the tuple (proto_id, evt_id, src_id)
  42. * and is served by its own dedicated notification chain; information contained
  43. * in such tuples is used, in a few different ways, to generate the needed
  44. * hash-keys.
  45. *
  46. * Here proto_id and evt_id are simply the protocol_id and message_id numbers
  47. * as described in the SCMI Protocol specification, while src_id represents an
  48. * optional, protocol dependent, source identifier (like domain_id, perf_id
  49. * or sensor_id and so forth).
  50. *
  51. * Upon reception of a notification message from the platform the SCMI RX ISR
  52. * passes the received message payload and some ancillary information (including
  53. * an arrival timestamp in nanoseconds) to the core via @scmi_notify() which
  54. * pushes the event-data itself on a protocol-dedicated kfifo queue for further
  55. * deferred processing as specified in @scmi_events_dispatcher().
  56. *
  57. * Each protocol has it own dedicated work_struct and worker which, once kicked
  58. * by the ISR, takes care to empty its own dedicated queue, deliverying the
  59. * queued items into the proper notification-chain: notifications processing can
  60. * proceed concurrently on distinct workers only between events belonging to
  61. * different protocols while delivery of events within the same protocol is
  62. * still strictly sequentially ordered by time of arrival.
  63. *
  64. * Events' information is then extracted from the SCMI Notification messages and
  65. * conveyed, converted into a custom per-event report struct, as the void *data
  66. * param to the user callback provided by the registered notifier_block, so that
  67. * from the user perspective his callback will look invoked like:
  68. *
  69. * int user_cb(struct notifier_block *nb, unsigned long event_id, void *report)
  70. *
  71. */
  72. #define dev_fmt(fmt) "SCMI Notifications - " fmt
  73. #define pr_fmt(fmt) "SCMI Notifications - " fmt
  74. #include <linux/bitfield.h>
  75. #include <linux/bug.h>
  76. #include <linux/compiler.h>
  77. #include <linux/device.h>
  78. #include <linux/err.h>
  79. #include <linux/hashtable.h>
  80. #include <linux/kernel.h>
  81. #include <linux/ktime.h>
  82. #include <linux/kfifo.h>
  83. #include <linux/list.h>
  84. #include <linux/mutex.h>
  85. #include <linux/notifier.h>
  86. #include <linux/refcount.h>
  87. #include <linux/scmi_protocol.h>
  88. #include <linux/slab.h>
  89. #include <linux/types.h>
  90. #include <linux/workqueue.h>
  91. #include "common.h"
  92. #include "notify.h"
  93. #define SCMI_MAX_PROTO 256
  94. #define PROTO_ID_MASK GENMASK(31, 24)
  95. #define EVT_ID_MASK GENMASK(23, 16)
  96. #define SRC_ID_MASK GENMASK(15, 0)
  97. #define NOTIF_UNSUPP -1
  98. /*
  99. * Builds an unsigned 32bit key from the given input tuple to be used
  100. * as a key in hashtables.
  101. */
  102. #define MAKE_HASH_KEY(p, e, s) \
  103. (FIELD_PREP(PROTO_ID_MASK, (p)) | \
  104. FIELD_PREP(EVT_ID_MASK, (e)) | \
  105. FIELD_PREP(SRC_ID_MASK, (s)))
  106. #define MAKE_ALL_SRCS_KEY(p, e) MAKE_HASH_KEY((p), (e), SRC_ID_MASK)
  107. /*
  108. * Assumes that the stored obj includes its own hash-key in a field named 'key':
  109. * with this simplification this macro can be equally used for all the objects'
  110. * types hashed by this implementation.
  111. *
  112. * @__ht: The hashtable name
  113. * @__obj: A pointer to the object type to be retrieved from the hashtable;
  114. * it will be used as a cursor while scanning the hastable and it will
  115. * be possibly left as NULL when @__k is not found
  116. * @__k: The key to search for
  117. */
  118. #define KEY_FIND(__ht, __obj, __k) \
  119. ({ \
  120. typeof(__k) k_ = __k; \
  121. typeof(__obj) obj_; \
  122. \
  123. hash_for_each_possible((__ht), obj_, hash, k_) \
  124. if (obj_->key == k_) \
  125. break; \
  126. __obj = obj_; \
  127. })
  128. #define KEY_XTRACT_PROTO_ID(key) FIELD_GET(PROTO_ID_MASK, (key))
  129. #define KEY_XTRACT_EVT_ID(key) FIELD_GET(EVT_ID_MASK, (key))
  130. #define KEY_XTRACT_SRC_ID(key) FIELD_GET(SRC_ID_MASK, (key))
  131. /*
  132. * A set of macros used to access safely @registered_protocols and
  133. * @registered_events arrays; these are fixed in size and each entry is possibly
  134. * populated at protocols' registration time and then only read but NEVER
  135. * modified or removed.
  136. */
  137. #define SCMI_GET_PROTO(__ni, __pid) \
  138. ({ \
  139. typeof(__ni) ni_ = __ni; \
  140. struct scmi_registered_events_desc *__pd = NULL; \
  141. \
  142. if (ni_) \
  143. __pd = READ_ONCE(ni_->registered_protocols[(__pid)]); \
  144. __pd; \
  145. })
  146. #define SCMI_GET_REVT_FROM_PD(__pd, __eid) \
  147. ({ \
  148. typeof(__pd) pd_ = __pd; \
  149. typeof(__eid) eid_ = __eid; \
  150. struct scmi_registered_event *__revt = NULL; \
  151. \
  152. if (pd_ && eid_ < pd_->num_events) \
  153. __revt = READ_ONCE(pd_->registered_events[eid_]); \
  154. __revt; \
  155. })
  156. #define SCMI_GET_REVT(__ni, __pid, __eid) \
  157. ({ \
  158. struct scmi_registered_event *__revt; \
  159. struct scmi_registered_events_desc *__pd; \
  160. \
  161. __pd = SCMI_GET_PROTO((__ni), (__pid)); \
  162. __revt = SCMI_GET_REVT_FROM_PD(__pd, (__eid)); \
  163. __revt; \
  164. })
  165. /* A couple of utility macros to limit cruft when calling protocols' helpers */
  166. #define REVT_NOTIFY_SET_STATUS(revt, eid, sid, state) \
  167. ({ \
  168. typeof(revt) r = revt; \
  169. r->proto->ops->set_notify_enabled(r->proto->ph, \
  170. (eid), (sid), (state)); \
  171. })
  172. #define REVT_NOTIFY_ENABLE(revt, eid, sid) \
  173. REVT_NOTIFY_SET_STATUS((revt), (eid), (sid), true)
  174. #define REVT_NOTIFY_DISABLE(revt, eid, sid) \
  175. REVT_NOTIFY_SET_STATUS((revt), (eid), (sid), false)
  176. #define REVT_FILL_REPORT(revt, ...) \
  177. ({ \
  178. typeof(revt) r = revt; \
  179. r->proto->ops->fill_custom_report(r->proto->ph, \
  180. __VA_ARGS__); \
  181. })
  182. #define SCMI_PENDING_HASH_SZ 4
  183. #define SCMI_REGISTERED_HASH_SZ 6
  184. struct scmi_registered_events_desc;
  185. /**
  186. * struct scmi_notify_instance - Represents an instance of the notification
  187. * core
  188. * @gid: GroupID used for devres
  189. * @handle: A reference to the platform instance
  190. * @init_work: A work item to perform final initializations of pending handlers
  191. * @notify_wq: A reference to the allocated Kernel cmwq
  192. * @pending_mtx: A mutex to protect @pending_events_handlers
  193. * @registered_protocols: A statically allocated array containing pointers to
  194. * all the registered protocol-level specific information
  195. * related to events' handling
  196. * @pending_events_handlers: An hashtable containing all pending events'
  197. * handlers descriptors
  198. *
  199. * Each platform instance, represented by a handle, has its own instance of
  200. * the notification subsystem represented by this structure.
  201. */
  202. struct scmi_notify_instance {
  203. void *gid;
  204. struct scmi_handle *handle;
  205. struct work_struct init_work;
  206. struct workqueue_struct *notify_wq;
  207. /* lock to protect pending_events_handlers */
  208. struct mutex pending_mtx;
  209. struct scmi_registered_events_desc **registered_protocols;
  210. DECLARE_HASHTABLE(pending_events_handlers, SCMI_PENDING_HASH_SZ);
  211. };
  212. /**
  213. * struct events_queue - Describes a queue and its associated worker
  214. * @sz: Size in bytes of the related kfifo
  215. * @kfifo: A dedicated Kernel kfifo descriptor
  216. * @notify_work: A custom work item bound to this queue
  217. * @wq: A reference to the associated workqueue
  218. *
  219. * Each protocol has its own dedicated events_queue descriptor.
  220. */
  221. struct events_queue {
  222. size_t sz;
  223. struct kfifo kfifo;
  224. struct work_struct notify_work;
  225. struct workqueue_struct *wq;
  226. };
  227. /**
  228. * struct scmi_event_header - A utility header
  229. * @timestamp: The timestamp, in nanoseconds (boottime), which was associated
  230. * to this event as soon as it entered the SCMI RX ISR
  231. * @payld_sz: Effective size of the embedded message payload which follows
  232. * @evt_id: Event ID (corresponds to the Event MsgID for this Protocol)
  233. * @payld: A reference to the embedded event payload
  234. *
  235. * This header is prepended to each received event message payload before
  236. * queueing it on the related &struct events_queue.
  237. */
  238. struct scmi_event_header {
  239. ktime_t timestamp;
  240. size_t payld_sz;
  241. unsigned char evt_id;
  242. unsigned char payld[];
  243. };
  244. struct scmi_registered_event;
  245. /**
  246. * struct scmi_registered_events_desc - Protocol Specific information
  247. * @id: Protocol ID
  248. * @ops: Protocol specific and event-related operations
  249. * @equeue: The embedded per-protocol events_queue
  250. * @ni: A reference to the initialized instance descriptor
  251. * @eh: A reference to pre-allocated buffer to be used as a scratch area by the
  252. * deferred worker when fetching data from the kfifo
  253. * @eh_sz: Size of the pre-allocated buffer @eh
  254. * @in_flight: A reference to an in flight &struct scmi_registered_event
  255. * @num_events: Number of events in @registered_events
  256. * @registered_events: A dynamically allocated array holding all the registered
  257. * events' descriptors, whose fixed-size is determined at
  258. * compile time.
  259. * @registered_mtx: A mutex to protect @registered_events_handlers
  260. * @ph: SCMI protocol handle reference
  261. * @registered_events_handlers: An hashtable containing all events' handlers
  262. * descriptors registered for this protocol
  263. *
  264. * All protocols that register at least one event have their protocol-specific
  265. * information stored here, together with the embedded allocated events_queue.
  266. * These descriptors are stored in the @registered_protocols array at protocol
  267. * registration time.
  268. *
  269. * Once these descriptors are successfully registered, they are NEVER again
  270. * removed or modified since protocols do not unregister ever, so that, once
  271. * we safely grab a NON-NULL reference from the array we can keep it and use it.
  272. */
  273. struct scmi_registered_events_desc {
  274. u8 id;
  275. const struct scmi_event_ops *ops;
  276. struct events_queue equeue;
  277. struct scmi_notify_instance *ni;
  278. struct scmi_event_header *eh;
  279. size_t eh_sz;
  280. void *in_flight;
  281. int num_events;
  282. struct scmi_registered_event **registered_events;
  283. /* mutex to protect registered_events_handlers */
  284. struct mutex registered_mtx;
  285. const struct scmi_protocol_handle *ph;
  286. DECLARE_HASHTABLE(registered_events_handlers, SCMI_REGISTERED_HASH_SZ);
  287. };
  288. /**
  289. * struct scmi_registered_event - Event Specific Information
  290. * @proto: A reference to the associated protocol descriptor
  291. * @evt: A reference to the associated event descriptor (as provided at
  292. * registration time)
  293. * @report: A pre-allocated buffer used by the deferred worker to fill a
  294. * customized event report
  295. * @num_sources: The number of possible sources for this event as stated at
  296. * events' registration time
  297. * @sources: A reference to a dynamically allocated array used to refcount the
  298. * events' enable requests for all the existing sources
  299. * @sources_mtx: A mutex to serialize the access to @sources
  300. *
  301. * All registered events are represented by one of these structures that are
  302. * stored in the @registered_events array at protocol registration time.
  303. *
  304. * Once these descriptors are successfully registered, they are NEVER again
  305. * removed or modified since protocols do not unregister ever, so that once we
  306. * safely grab a NON-NULL reference from the table we can keep it and use it.
  307. */
  308. struct scmi_registered_event {
  309. struct scmi_registered_events_desc *proto;
  310. const struct scmi_event *evt;
  311. void *report;
  312. u32 num_sources;
  313. refcount_t *sources;
  314. /* locking to serialize the access to sources */
  315. struct mutex sources_mtx;
  316. };
  317. /**
  318. * struct scmi_event_handler - Event handler information
  319. * @key: The used hashkey
  320. * @users: A reference count for number of active users for this handler
  321. * @r_evt: A reference to the associated registered event; when this is NULL
  322. * this handler is pending, which means that identifies a set of
  323. * callbacks intended to be attached to an event which is still not
  324. * known nor registered by any protocol at that point in time
  325. * @chain: The notification chain dedicated to this specific event tuple
  326. * @hash: The hlist_node used for collision handling
  327. * @enabled: A boolean which records if event's generation has been already
  328. * enabled for this handler as a whole
  329. *
  330. * This structure collects all the information needed to process a received
  331. * event identified by the tuple (proto_id, evt_id, src_id).
  332. * These descriptors are stored in a per-protocol @registered_events_handlers
  333. * table using as a key a value derived from that tuple.
  334. */
  335. struct scmi_event_handler {
  336. u32 key;
  337. refcount_t users;
  338. struct scmi_registered_event *r_evt;
  339. struct blocking_notifier_head chain;
  340. struct hlist_node hash;
  341. bool enabled;
  342. };
  343. #define IS_HNDL_PENDING(hndl) (!(hndl)->r_evt)
  344. static struct scmi_event_handler *
  345. scmi_get_active_handler(struct scmi_notify_instance *ni, u32 evt_key);
  346. static void scmi_put_active_handler(struct scmi_notify_instance *ni,
  347. struct scmi_event_handler *hndl);
  348. static bool scmi_put_handler_unlocked(struct scmi_notify_instance *ni,
  349. struct scmi_event_handler *hndl);
  350. /**
  351. * scmi_lookup_and_call_event_chain() - Lookup the proper chain and call it
  352. * @ni: A reference to the notification instance to use
  353. * @evt_key: The key to use to lookup the related notification chain
  354. * @report: The customized event-specific report to pass down to the callbacks
  355. * as their *data parameter.
  356. */
  357. static inline void
  358. scmi_lookup_and_call_event_chain(struct scmi_notify_instance *ni,
  359. u32 evt_key, void *report)
  360. {
  361. int ret;
  362. struct scmi_event_handler *hndl;
  363. /*
  364. * Here ensure the event handler cannot vanish while using it.
  365. * It is legitimate, though, for an handler not to be found at all here,
  366. * e.g. when it has been unregistered by the user after some events had
  367. * already been queued.
  368. */
  369. hndl = scmi_get_active_handler(ni, evt_key);
  370. if (!hndl)
  371. return;
  372. ret = blocking_notifier_call_chain(&hndl->chain,
  373. KEY_XTRACT_EVT_ID(evt_key),
  374. report);
  375. /* Notifiers are NOT supposed to cut the chain ... */
  376. WARN_ON_ONCE(ret & NOTIFY_STOP_MASK);
  377. scmi_put_active_handler(ni, hndl);
  378. }
  379. /**
  380. * scmi_process_event_header() - Dequeue and process an event header
  381. * @eq: The queue to use
  382. * @pd: The protocol descriptor to use
  383. *
  384. * Read an event header from the protocol queue into the dedicated scratch
  385. * buffer and looks for a matching registered event; in case an anomalously
  386. * sized read is detected just flush the queue.
  387. *
  388. * Return:
  389. * * a reference to the matching registered event when found
  390. * * ERR_PTR(-EINVAL) when NO registered event could be found
  391. * * NULL when the queue is empty
  392. */
  393. static inline struct scmi_registered_event *
  394. scmi_process_event_header(struct events_queue *eq,
  395. struct scmi_registered_events_desc *pd)
  396. {
  397. unsigned int outs;
  398. struct scmi_registered_event *r_evt;
  399. outs = kfifo_out(&eq->kfifo, pd->eh,
  400. sizeof(struct scmi_event_header));
  401. if (!outs)
  402. return NULL;
  403. if (outs != sizeof(struct scmi_event_header)) {
  404. dev_err(pd->ni->handle->dev, "corrupted EVT header. Flush.\n");
  405. kfifo_reset_out(&eq->kfifo);
  406. return NULL;
  407. }
  408. r_evt = SCMI_GET_REVT_FROM_PD(pd, pd->eh->evt_id);
  409. if (!r_evt)
  410. r_evt = ERR_PTR(-EINVAL);
  411. return r_evt;
  412. }
  413. /**
  414. * scmi_process_event_payload() - Dequeue and process an event payload
  415. * @eq: The queue to use
  416. * @pd: The protocol descriptor to use
  417. * @r_evt: The registered event descriptor to use
  418. *
  419. * Read an event payload from the protocol queue into the dedicated scratch
  420. * buffer, fills a custom report and then look for matching event handlers and
  421. * call them; skip any unknown event (as marked by scmi_process_event_header())
  422. * and in case an anomalously sized read is detected just flush the queue.
  423. *
  424. * Return: False when the queue is empty
  425. */
  426. static inline bool
  427. scmi_process_event_payload(struct events_queue *eq,
  428. struct scmi_registered_events_desc *pd,
  429. struct scmi_registered_event *r_evt)
  430. {
  431. u32 src_id, key;
  432. unsigned int outs;
  433. void *report = NULL;
  434. outs = kfifo_out(&eq->kfifo, pd->eh->payld, pd->eh->payld_sz);
  435. if (!outs)
  436. return false;
  437. /* Any in-flight event has now been officially processed */
  438. pd->in_flight = NULL;
  439. if (outs != pd->eh->payld_sz) {
  440. dev_err(pd->ni->handle->dev, "corrupted EVT Payload. Flush.\n");
  441. kfifo_reset_out(&eq->kfifo);
  442. return false;
  443. }
  444. if (IS_ERR(r_evt)) {
  445. dev_warn(pd->ni->handle->dev,
  446. "SKIP UNKNOWN EVT - proto:%X evt:%d\n",
  447. pd->id, pd->eh->evt_id);
  448. return true;
  449. }
  450. report = REVT_FILL_REPORT(r_evt, pd->eh->evt_id, pd->eh->timestamp,
  451. pd->eh->payld, pd->eh->payld_sz,
  452. r_evt->report, &src_id);
  453. if (!report) {
  454. dev_err(pd->ni->handle->dev,
  455. "report not available - proto:%X evt:%d\n",
  456. pd->id, pd->eh->evt_id);
  457. return true;
  458. }
  459. /* At first search for a generic ALL src_ids handler... */
  460. key = MAKE_ALL_SRCS_KEY(pd->id, pd->eh->evt_id);
  461. scmi_lookup_and_call_event_chain(pd->ni, key, report);
  462. /* ...then search for any specific src_id */
  463. key = MAKE_HASH_KEY(pd->id, pd->eh->evt_id, src_id);
  464. scmi_lookup_and_call_event_chain(pd->ni, key, report);
  465. return true;
  466. }
  467. /**
  468. * scmi_events_dispatcher() - Common worker logic for all work items.
  469. * @work: The work item to use, which is associated to a dedicated events_queue
  470. *
  471. * Logic:
  472. * 1. dequeue one pending RX notification (queued in SCMI RX ISR context)
  473. * 2. generate a custom event report from the received event message
  474. * 3. lookup for any registered ALL_SRC_IDs handler:
  475. * - > call the related notification chain passing in the report
  476. * 4. lookup for any registered specific SRC_ID handler:
  477. * - > call the related notification chain passing in the report
  478. *
  479. * Note that:
  480. * * a dedicated per-protocol kfifo queue is used: in this way an anomalous
  481. * flood of events cannot saturate other protocols' queues.
  482. * * each per-protocol queue is associated to a distinct work_item, which
  483. * means, in turn, that:
  484. * + all protocols can process their dedicated queues concurrently
  485. * (since notify_wq:max_active != 1)
  486. * + anyway at most one worker instance is allowed to run on the same queue
  487. * concurrently: this ensures that we can have only one concurrent
  488. * reader/writer on the associated kfifo, so that we can use it lock-less
  489. *
  490. * Context: Process context.
  491. */
  492. static void scmi_events_dispatcher(struct work_struct *work)
  493. {
  494. struct events_queue *eq;
  495. struct scmi_registered_events_desc *pd;
  496. struct scmi_registered_event *r_evt;
  497. eq = container_of(work, struct events_queue, notify_work);
  498. pd = container_of(eq, struct scmi_registered_events_desc, equeue);
  499. /*
  500. * In order to keep the queue lock-less and the number of memcopies
  501. * to the bare minimum needed, the dispatcher accounts for the
  502. * possibility of per-protocol in-flight events: i.e. an event whose
  503. * reception could end up being split across two subsequent runs of this
  504. * worker, first the header, then the payload.
  505. */
  506. do {
  507. if (!pd->in_flight) {
  508. r_evt = scmi_process_event_header(eq, pd);
  509. if (!r_evt)
  510. break;
  511. pd->in_flight = r_evt;
  512. } else {
  513. r_evt = pd->in_flight;
  514. }
  515. } while (scmi_process_event_payload(eq, pd, r_evt));
  516. }
  517. /**
  518. * scmi_notify() - Queues a notification for further deferred processing
  519. * @handle: The handle identifying the platform instance from which the
  520. * dispatched event is generated
  521. * @proto_id: Protocol ID
  522. * @evt_id: Event ID (msgID)
  523. * @buf: Event Message Payload (without the header)
  524. * @len: Event Message Payload size
  525. * @ts: RX Timestamp in nanoseconds (boottime)
  526. *
  527. * Context: Called in interrupt context to queue a received event for
  528. * deferred processing.
  529. *
  530. * Return: 0 on Success
  531. */
  532. int scmi_notify(const struct scmi_handle *handle, u8 proto_id, u8 evt_id,
  533. const void *buf, size_t len, ktime_t ts)
  534. {
  535. struct scmi_registered_event *r_evt;
  536. struct scmi_event_header eh;
  537. struct scmi_notify_instance *ni;
  538. ni = scmi_notification_instance_data_get(handle);
  539. if (!ni)
  540. return 0;
  541. r_evt = SCMI_GET_REVT(ni, proto_id, evt_id);
  542. if (!r_evt)
  543. return -EINVAL;
  544. if (len > r_evt->evt->max_payld_sz) {
  545. dev_err(handle->dev, "discard badly sized message\n");
  546. return -EINVAL;
  547. }
  548. if (kfifo_avail(&r_evt->proto->equeue.kfifo) < sizeof(eh) + len) {
  549. dev_warn(handle->dev,
  550. "queue full, dropping proto_id:%d evt_id:%d ts:%lld\n",
  551. proto_id, evt_id, ktime_to_ns(ts));
  552. return -ENOMEM;
  553. }
  554. eh.timestamp = ts;
  555. eh.evt_id = evt_id;
  556. eh.payld_sz = len;
  557. /*
  558. * Header and payload are enqueued with two distinct kfifo_in() (so non
  559. * atomic), but this situation is handled properly on the consumer side
  560. * with in-flight events tracking.
  561. */
  562. kfifo_in(&r_evt->proto->equeue.kfifo, &eh, sizeof(eh));
  563. kfifo_in(&r_evt->proto->equeue.kfifo, buf, len);
  564. /*
  565. * Don't care about return value here since we just want to ensure that
  566. * a work is queued all the times whenever some items have been pushed
  567. * on the kfifo:
  568. * - if work was already queued it will simply fail to queue a new one
  569. * since it is not needed
  570. * - if work was not queued already it will be now, even in case work
  571. * was in fact already running: this behavior avoids any possible race
  572. * when this function pushes new items onto the kfifos after the
  573. * related executing worker had already determined the kfifo to be
  574. * empty and it was terminating.
  575. */
  576. queue_work(r_evt->proto->equeue.wq,
  577. &r_evt->proto->equeue.notify_work);
  578. return 0;
  579. }
  580. /**
  581. * scmi_kfifo_free() - Devres action helper to free the kfifo
  582. * @kfifo: The kfifo to free
  583. */
  584. static void scmi_kfifo_free(void *kfifo)
  585. {
  586. kfifo_free((struct kfifo *)kfifo);
  587. }
  588. /**
  589. * scmi_initialize_events_queue() - Allocate/Initialize a kfifo buffer
  590. * @ni: A reference to the notification instance to use
  591. * @equeue: The events_queue to initialize
  592. * @sz: Size of the kfifo buffer to allocate
  593. *
  594. * Allocate a buffer for the kfifo and initialize it.
  595. *
  596. * Return: 0 on Success
  597. */
  598. static int scmi_initialize_events_queue(struct scmi_notify_instance *ni,
  599. struct events_queue *equeue, size_t sz)
  600. {
  601. int ret;
  602. if (kfifo_alloc(&equeue->kfifo, sz, GFP_KERNEL))
  603. return -ENOMEM;
  604. /* Size could have been roundup to power-of-two */
  605. equeue->sz = kfifo_size(&equeue->kfifo);
  606. ret = devm_add_action_or_reset(ni->handle->dev, scmi_kfifo_free,
  607. &equeue->kfifo);
  608. if (ret)
  609. return ret;
  610. INIT_WORK(&equeue->notify_work, scmi_events_dispatcher);
  611. equeue->wq = ni->notify_wq;
  612. return ret;
  613. }
  614. /**
  615. * scmi_allocate_registered_events_desc() - Allocate a registered events'
  616. * descriptor
  617. * @ni: A reference to the &struct scmi_notify_instance notification instance
  618. * to use
  619. * @proto_id: Protocol ID
  620. * @queue_sz: Size of the associated queue to allocate
  621. * @eh_sz: Size of the event header scratch area to pre-allocate
  622. * @num_events: Number of events to support (size of @registered_events)
  623. * @ops: Pointer to a struct holding references to protocol specific helpers
  624. * needed during events handling
  625. *
  626. * It is supposed to be called only once for each protocol at protocol
  627. * initialization time, so it warns if the requested protocol is found already
  628. * registered.
  629. *
  630. * Return: The allocated and registered descriptor on Success
  631. */
  632. static struct scmi_registered_events_desc *
  633. scmi_allocate_registered_events_desc(struct scmi_notify_instance *ni,
  634. u8 proto_id, size_t queue_sz, size_t eh_sz,
  635. int num_events,
  636. const struct scmi_event_ops *ops)
  637. {
  638. int ret;
  639. struct scmi_registered_events_desc *pd;
  640. /* Ensure protocols are up to date */
  641. smp_rmb();
  642. if (WARN_ON(ni->registered_protocols[proto_id]))
  643. return ERR_PTR(-EINVAL);
  644. pd = devm_kzalloc(ni->handle->dev, sizeof(*pd), GFP_KERNEL);
  645. if (!pd)
  646. return ERR_PTR(-ENOMEM);
  647. pd->id = proto_id;
  648. pd->ops = ops;
  649. pd->ni = ni;
  650. ret = scmi_initialize_events_queue(ni, &pd->equeue, queue_sz);
  651. if (ret)
  652. return ERR_PTR(ret);
  653. pd->eh = devm_kzalloc(ni->handle->dev, eh_sz, GFP_KERNEL);
  654. if (!pd->eh)
  655. return ERR_PTR(-ENOMEM);
  656. pd->eh_sz = eh_sz;
  657. pd->registered_events = devm_kcalloc(ni->handle->dev, num_events,
  658. sizeof(char *), GFP_KERNEL);
  659. if (!pd->registered_events)
  660. return ERR_PTR(-ENOMEM);
  661. pd->num_events = num_events;
  662. /* Initialize per protocol handlers table */
  663. mutex_init(&pd->registered_mtx);
  664. hash_init(pd->registered_events_handlers);
  665. return pd;
  666. }
  667. /**
  668. * scmi_register_protocol_events() - Register Protocol Events with the core
  669. * @handle: The handle identifying the platform instance against which the
  670. * protocol's events are registered
  671. * @proto_id: Protocol ID
  672. * @ph: SCMI protocol handle.
  673. * @ee: A structure describing the events supported by this protocol.
  674. *
  675. * Used by SCMI Protocols initialization code to register with the notification
  676. * core the list of supported events and their descriptors: takes care to
  677. * pre-allocate and store all needed descriptors, scratch buffers and event
  678. * queues.
  679. *
  680. * Return: 0 on Success
  681. */
  682. int scmi_register_protocol_events(const struct scmi_handle *handle, u8 proto_id,
  683. const struct scmi_protocol_handle *ph,
  684. const struct scmi_protocol_events *ee)
  685. {
  686. int i;
  687. unsigned int num_sources;
  688. size_t payld_sz = 0;
  689. struct scmi_registered_events_desc *pd;
  690. struct scmi_notify_instance *ni;
  691. const struct scmi_event *evt;
  692. if (!ee || !ee->ops || !ee->evts || !ph ||
  693. (!ee->num_sources && !ee->ops->get_num_sources))
  694. return -EINVAL;
  695. ni = scmi_notification_instance_data_get(handle);
  696. if (!ni)
  697. return -ENOMEM;
  698. /* num_sources cannot be <= 0 */
  699. if (ee->num_sources) {
  700. num_sources = ee->num_sources;
  701. } else {
  702. int nsrc = ee->ops->get_num_sources(ph);
  703. if (nsrc <= 0)
  704. return -EINVAL;
  705. num_sources = nsrc;
  706. }
  707. evt = ee->evts;
  708. for (i = 0; i < ee->num_events; i++)
  709. payld_sz = max_t(size_t, payld_sz, evt[i].max_payld_sz);
  710. payld_sz += sizeof(struct scmi_event_header);
  711. pd = scmi_allocate_registered_events_desc(ni, proto_id, ee->queue_sz,
  712. payld_sz, ee->num_events,
  713. ee->ops);
  714. if (IS_ERR(pd))
  715. return PTR_ERR(pd);
  716. pd->ph = ph;
  717. for (i = 0; i < ee->num_events; i++, evt++) {
  718. int id;
  719. struct scmi_registered_event *r_evt;
  720. r_evt = devm_kzalloc(ni->handle->dev, sizeof(*r_evt),
  721. GFP_KERNEL);
  722. if (!r_evt)
  723. return -ENOMEM;
  724. r_evt->proto = pd;
  725. r_evt->evt = evt;
  726. r_evt->sources = devm_kcalloc(ni->handle->dev, num_sources,
  727. sizeof(refcount_t), GFP_KERNEL);
  728. if (!r_evt->sources)
  729. return -ENOMEM;
  730. r_evt->num_sources = num_sources;
  731. mutex_init(&r_evt->sources_mtx);
  732. r_evt->report = devm_kzalloc(ni->handle->dev,
  733. evt->max_report_sz, GFP_KERNEL);
  734. if (!r_evt->report)
  735. return -ENOMEM;
  736. for (id = 0; id < r_evt->num_sources; id++)
  737. if (ee->ops->is_notify_supported &&
  738. !ee->ops->is_notify_supported(ph, r_evt->evt->id, id))
  739. refcount_set(&r_evt->sources[id], NOTIF_UNSUPP);
  740. pd->registered_events[i] = r_evt;
  741. /* Ensure events are updated */
  742. smp_wmb();
  743. dev_dbg(handle->dev, "registered event - %lX\n",
  744. MAKE_ALL_SRCS_KEY(r_evt->proto->id, r_evt->evt->id));
  745. }
  746. /* Register protocol and events...it will never be removed */
  747. ni->registered_protocols[proto_id] = pd;
  748. /* Ensure protocols are updated */
  749. smp_wmb();
  750. /*
  751. * Finalize any pending events' handler which could have been waiting
  752. * for this protocol's events registration.
  753. */
  754. schedule_work(&ni->init_work);
  755. return 0;
  756. }
  757. /**
  758. * scmi_deregister_protocol_events - Deregister protocol events with the core
  759. * @handle: The handle identifying the platform instance against which the
  760. * protocol's events are registered
  761. * @proto_id: Protocol ID
  762. */
  763. void scmi_deregister_protocol_events(const struct scmi_handle *handle,
  764. u8 proto_id)
  765. {
  766. struct scmi_notify_instance *ni;
  767. struct scmi_registered_events_desc *pd;
  768. ni = scmi_notification_instance_data_get(handle);
  769. if (!ni)
  770. return;
  771. pd = ni->registered_protocols[proto_id];
  772. if (!pd)
  773. return;
  774. ni->registered_protocols[proto_id] = NULL;
  775. /* Ensure protocols are updated */
  776. smp_wmb();
  777. cancel_work_sync(&pd->equeue.notify_work);
  778. }
  779. /**
  780. * scmi_allocate_event_handler() - Allocate Event handler
  781. * @ni: A reference to the notification instance to use
  782. * @evt_key: 32bit key uniquely bind to the event identified by the tuple
  783. * (proto_id, evt_id, src_id)
  784. *
  785. * Allocate an event handler and related notification chain associated with
  786. * the provided event handler key.
  787. * Note that, at this point, a related registered_event is still to be
  788. * associated to this handler descriptor (hndl->r_evt == NULL), so the handler
  789. * is initialized as pending.
  790. *
  791. * Context: Assumes to be called with @pending_mtx already acquired.
  792. * Return: the freshly allocated structure on Success
  793. */
  794. static struct scmi_event_handler *
  795. scmi_allocate_event_handler(struct scmi_notify_instance *ni, u32 evt_key)
  796. {
  797. struct scmi_event_handler *hndl;
  798. hndl = kzalloc(sizeof(*hndl), GFP_KERNEL);
  799. if (!hndl)
  800. return NULL;
  801. hndl->key = evt_key;
  802. BLOCKING_INIT_NOTIFIER_HEAD(&hndl->chain);
  803. refcount_set(&hndl->users, 1);
  804. /* New handlers are created pending */
  805. hash_add(ni->pending_events_handlers, &hndl->hash, hndl->key);
  806. return hndl;
  807. }
  808. /**
  809. * scmi_free_event_handler() - Free the provided Event handler
  810. * @hndl: The event handler structure to free
  811. *
  812. * Context: Assumes to be called with proper locking acquired depending
  813. * on the situation.
  814. */
  815. static void scmi_free_event_handler(struct scmi_event_handler *hndl)
  816. {
  817. hash_del(&hndl->hash);
  818. kfree(hndl);
  819. }
  820. /**
  821. * scmi_bind_event_handler() - Helper to attempt binding an handler to an event
  822. * @ni: A reference to the notification instance to use
  823. * @hndl: The event handler to bind
  824. *
  825. * If an associated registered event is found, move the handler from the pending
  826. * into the registered table.
  827. *
  828. * Context: Assumes to be called with @pending_mtx already acquired.
  829. *
  830. * Return: 0 on Success
  831. */
  832. static inline int scmi_bind_event_handler(struct scmi_notify_instance *ni,
  833. struct scmi_event_handler *hndl)
  834. {
  835. struct scmi_registered_event *r_evt;
  836. r_evt = SCMI_GET_REVT(ni, KEY_XTRACT_PROTO_ID(hndl->key),
  837. KEY_XTRACT_EVT_ID(hndl->key));
  838. if (!r_evt)
  839. return -EINVAL;
  840. /*
  841. * Remove from pending and insert into registered while getting hold
  842. * of protocol instance.
  843. */
  844. hash_del(&hndl->hash);
  845. /*
  846. * Acquire protocols only for NON pending handlers, so as NOT to trigger
  847. * protocol initialization when a notifier is registered against a still
  848. * not registered protocol, since it would make little sense to force init
  849. * protocols for which still no SCMI driver user exists: they wouldn't
  850. * emit any event anyway till some SCMI driver starts using it.
  851. */
  852. scmi_protocol_acquire(ni->handle, KEY_XTRACT_PROTO_ID(hndl->key));
  853. hndl->r_evt = r_evt;
  854. mutex_lock(&r_evt->proto->registered_mtx);
  855. hash_add(r_evt->proto->registered_events_handlers,
  856. &hndl->hash, hndl->key);
  857. mutex_unlock(&r_evt->proto->registered_mtx);
  858. return 0;
  859. }
  860. /**
  861. * scmi_valid_pending_handler() - Helper to check pending status of handlers
  862. * @ni: A reference to the notification instance to use
  863. * @hndl: The event handler to check
  864. *
  865. * An handler is considered pending when its r_evt == NULL, because the related
  866. * event was still unknown at handler's registration time; anyway, since all
  867. * protocols register their supported events once for all at protocols'
  868. * initialization time, a pending handler cannot be considered valid anymore if
  869. * the underlying event (which it is waiting for), belongs to an already
  870. * initialized and registered protocol.
  871. *
  872. * Return: 0 on Success
  873. */
  874. static inline int scmi_valid_pending_handler(struct scmi_notify_instance *ni,
  875. struct scmi_event_handler *hndl)
  876. {
  877. struct scmi_registered_events_desc *pd;
  878. if (!IS_HNDL_PENDING(hndl))
  879. return -EINVAL;
  880. pd = SCMI_GET_PROTO(ni, KEY_XTRACT_PROTO_ID(hndl->key));
  881. if (pd)
  882. return -EINVAL;
  883. return 0;
  884. }
  885. /**
  886. * scmi_register_event_handler() - Register whenever possible an Event handler
  887. * @ni: A reference to the notification instance to use
  888. * @hndl: The event handler to register
  889. *
  890. * At first try to bind an event handler to its associated event, then check if
  891. * it was at least a valid pending handler: if it was not bound nor valid return
  892. * false.
  893. *
  894. * Valid pending incomplete bindings will be periodically retried by a dedicated
  895. * worker which is kicked each time a new protocol completes its own
  896. * registration phase.
  897. *
  898. * Context: Assumes to be called with @pending_mtx acquired.
  899. *
  900. * Return: 0 on Success
  901. */
  902. static int scmi_register_event_handler(struct scmi_notify_instance *ni,
  903. struct scmi_event_handler *hndl)
  904. {
  905. int ret;
  906. ret = scmi_bind_event_handler(ni, hndl);
  907. if (!ret) {
  908. dev_dbg(ni->handle->dev, "registered NEW handler - key:%X\n",
  909. hndl->key);
  910. } else {
  911. ret = scmi_valid_pending_handler(ni, hndl);
  912. if (!ret)
  913. dev_dbg(ni->handle->dev,
  914. "registered PENDING handler - key:%X\n",
  915. hndl->key);
  916. }
  917. return ret;
  918. }
  919. /**
  920. * __scmi_event_handler_get_ops() - Utility to get or create an event handler
  921. * @ni: A reference to the notification instance to use
  922. * @evt_key: The event key to use
  923. * @create: A boolean flag to specify if a handler must be created when
  924. * not already existent
  925. *
  926. * Search for the desired handler matching the key in both the per-protocol
  927. * registered table and the common pending table:
  928. * * if found adjust users refcount
  929. * * if not found and @create is true, create and register the new handler:
  930. * handler could end up being registered as pending if no matching event
  931. * could be found.
  932. *
  933. * An handler is guaranteed to reside in one and only one of the tables at
  934. * any one time; to ensure this the whole search and create is performed
  935. * holding the @pending_mtx lock, with @registered_mtx additionally acquired
  936. * if needed.
  937. *
  938. * Note that when a nested acquisition of these mutexes is needed the locking
  939. * order is always (same as in @init_work):
  940. * 1. pending_mtx
  941. * 2. registered_mtx
  942. *
  943. * Events generation is NOT enabled right after creation within this routine
  944. * since at creation time we usually want to have all setup and ready before
  945. * events really start flowing.
  946. *
  947. * Return: A properly refcounted handler on Success, NULL on Failure
  948. */
  949. static inline struct scmi_event_handler *
  950. __scmi_event_handler_get_ops(struct scmi_notify_instance *ni,
  951. u32 evt_key, bool create)
  952. {
  953. struct scmi_registered_event *r_evt;
  954. struct scmi_event_handler *hndl = NULL;
  955. r_evt = SCMI_GET_REVT(ni, KEY_XTRACT_PROTO_ID(evt_key),
  956. KEY_XTRACT_EVT_ID(evt_key));
  957. mutex_lock(&ni->pending_mtx);
  958. /* Search registered events at first ... if possible at all */
  959. if (r_evt) {
  960. mutex_lock(&r_evt->proto->registered_mtx);
  961. hndl = KEY_FIND(r_evt->proto->registered_events_handlers,
  962. hndl, evt_key);
  963. if (hndl)
  964. refcount_inc(&hndl->users);
  965. mutex_unlock(&r_evt->proto->registered_mtx);
  966. }
  967. /* ...then amongst pending. */
  968. if (!hndl) {
  969. hndl = KEY_FIND(ni->pending_events_handlers, hndl, evt_key);
  970. if (hndl)
  971. refcount_inc(&hndl->users);
  972. }
  973. /* Create if still not found and required */
  974. if (!hndl && create) {
  975. hndl = scmi_allocate_event_handler(ni, evt_key);
  976. if (hndl && scmi_register_event_handler(ni, hndl)) {
  977. dev_dbg(ni->handle->dev,
  978. "purging UNKNOWN handler - key:%X\n",
  979. hndl->key);
  980. /* this hndl can be only a pending one */
  981. scmi_put_handler_unlocked(ni, hndl);
  982. hndl = NULL;
  983. }
  984. }
  985. mutex_unlock(&ni->pending_mtx);
  986. return hndl;
  987. }
  988. static struct scmi_event_handler *
  989. scmi_get_handler(struct scmi_notify_instance *ni, u32 evt_key)
  990. {
  991. return __scmi_event_handler_get_ops(ni, evt_key, false);
  992. }
  993. static struct scmi_event_handler *
  994. scmi_get_or_create_handler(struct scmi_notify_instance *ni, u32 evt_key)
  995. {
  996. return __scmi_event_handler_get_ops(ni, evt_key, true);
  997. }
  998. /**
  999. * scmi_get_active_handler() - Helper to get active handlers only
  1000. * @ni: A reference to the notification instance to use
  1001. * @evt_key: The event key to use
  1002. *
  1003. * Search for the desired handler matching the key only in the per-protocol
  1004. * table of registered handlers: this is called only from the dispatching path
  1005. * so want to be as quick as possible and do not care about pending.
  1006. *
  1007. * Return: A properly refcounted active handler
  1008. */
  1009. static struct scmi_event_handler *
  1010. scmi_get_active_handler(struct scmi_notify_instance *ni, u32 evt_key)
  1011. {
  1012. struct scmi_registered_event *r_evt;
  1013. struct scmi_event_handler *hndl = NULL;
  1014. r_evt = SCMI_GET_REVT(ni, KEY_XTRACT_PROTO_ID(evt_key),
  1015. KEY_XTRACT_EVT_ID(evt_key));
  1016. if (r_evt) {
  1017. mutex_lock(&r_evt->proto->registered_mtx);
  1018. hndl = KEY_FIND(r_evt->proto->registered_events_handlers,
  1019. hndl, evt_key);
  1020. if (hndl)
  1021. refcount_inc(&hndl->users);
  1022. mutex_unlock(&r_evt->proto->registered_mtx);
  1023. }
  1024. return hndl;
  1025. }
  1026. /**
  1027. * __scmi_enable_evt() - Enable/disable events generation
  1028. * @r_evt: The registered event to act upon
  1029. * @src_id: The src_id to act upon
  1030. * @enable: The action to perform: true->Enable, false->Disable
  1031. *
  1032. * Takes care of proper refcounting while performing enable/disable: handles
  1033. * the special case of ALL sources requests by itself.
  1034. * Returns successfully if at least one of the required src_id has been
  1035. * successfully enabled/disabled.
  1036. *
  1037. * Return: 0 on Success
  1038. */
  1039. static inline int __scmi_enable_evt(struct scmi_registered_event *r_evt,
  1040. u32 src_id, bool enable)
  1041. {
  1042. int retvals = 0;
  1043. u32 num_sources;
  1044. refcount_t *sid;
  1045. if (src_id == SRC_ID_MASK) {
  1046. src_id = 0;
  1047. num_sources = r_evt->num_sources;
  1048. } else if (src_id < r_evt->num_sources) {
  1049. num_sources = 1;
  1050. } else {
  1051. return -EINVAL;
  1052. }
  1053. mutex_lock(&r_evt->sources_mtx);
  1054. if (enable) {
  1055. for (; num_sources; src_id++, num_sources--) {
  1056. int ret = 0;
  1057. sid = &r_evt->sources[src_id];
  1058. if (refcount_read(sid) == NOTIF_UNSUPP) {
  1059. dev_dbg(r_evt->proto->ph->dev,
  1060. "Notification NOT supported - proto_id:%d evt_id:%d src_id:%d",
  1061. r_evt->proto->id, r_evt->evt->id,
  1062. src_id);
  1063. ret = -EOPNOTSUPP;
  1064. } else if (refcount_read(sid) == 0) {
  1065. ret = REVT_NOTIFY_ENABLE(r_evt, r_evt->evt->id,
  1066. src_id);
  1067. if (!ret)
  1068. refcount_set(sid, 1);
  1069. } else {
  1070. refcount_inc(sid);
  1071. }
  1072. retvals += !ret;
  1073. }
  1074. } else {
  1075. for (; num_sources; src_id++, num_sources--) {
  1076. sid = &r_evt->sources[src_id];
  1077. if (refcount_read(sid) == NOTIF_UNSUPP)
  1078. continue;
  1079. if (refcount_dec_and_test(sid))
  1080. REVT_NOTIFY_DISABLE(r_evt,
  1081. r_evt->evt->id, src_id);
  1082. }
  1083. retvals = 1;
  1084. }
  1085. mutex_unlock(&r_evt->sources_mtx);
  1086. return retvals ? 0 : -EINVAL;
  1087. }
  1088. static int scmi_enable_events(struct scmi_event_handler *hndl)
  1089. {
  1090. int ret = 0;
  1091. if (!hndl->enabled) {
  1092. ret = __scmi_enable_evt(hndl->r_evt,
  1093. KEY_XTRACT_SRC_ID(hndl->key), true);
  1094. if (!ret)
  1095. hndl->enabled = true;
  1096. }
  1097. return ret;
  1098. }
  1099. static int scmi_disable_events(struct scmi_event_handler *hndl)
  1100. {
  1101. int ret = 0;
  1102. if (hndl->enabled) {
  1103. ret = __scmi_enable_evt(hndl->r_evt,
  1104. KEY_XTRACT_SRC_ID(hndl->key), false);
  1105. if (!ret)
  1106. hndl->enabled = false;
  1107. }
  1108. return ret;
  1109. }
  1110. /**
  1111. * scmi_put_handler_unlocked() - Put an event handler
  1112. * @ni: A reference to the notification instance to use
  1113. * @hndl: The event handler to act upon
  1114. *
  1115. * After having got exclusive access to the registered handlers hashtable,
  1116. * update the refcount and if @hndl is no more in use by anyone:
  1117. * * ask for events' generation disabling
  1118. * * unregister and free the handler itself
  1119. *
  1120. * Context: Assumes all the proper locking has been managed by the caller.
  1121. *
  1122. * Return: True if handler was freed (users dropped to zero)
  1123. */
  1124. static bool scmi_put_handler_unlocked(struct scmi_notify_instance *ni,
  1125. struct scmi_event_handler *hndl)
  1126. {
  1127. bool freed = false;
  1128. if (refcount_dec_and_test(&hndl->users)) {
  1129. if (!IS_HNDL_PENDING(hndl))
  1130. scmi_disable_events(hndl);
  1131. scmi_free_event_handler(hndl);
  1132. freed = true;
  1133. }
  1134. return freed;
  1135. }
  1136. static void scmi_put_handler(struct scmi_notify_instance *ni,
  1137. struct scmi_event_handler *hndl)
  1138. {
  1139. bool freed;
  1140. u8 protocol_id;
  1141. struct scmi_registered_event *r_evt = hndl->r_evt;
  1142. mutex_lock(&ni->pending_mtx);
  1143. if (r_evt) {
  1144. protocol_id = r_evt->proto->id;
  1145. mutex_lock(&r_evt->proto->registered_mtx);
  1146. }
  1147. freed = scmi_put_handler_unlocked(ni, hndl);
  1148. if (r_evt) {
  1149. mutex_unlock(&r_evt->proto->registered_mtx);
  1150. /*
  1151. * Only registered handler acquired protocol; must be here
  1152. * released only AFTER unlocking registered_mtx, since
  1153. * releasing a protocol can trigger its de-initialization
  1154. * (ie. including r_evt and registered_mtx)
  1155. */
  1156. if (freed)
  1157. scmi_protocol_release(ni->handle, protocol_id);
  1158. }
  1159. mutex_unlock(&ni->pending_mtx);
  1160. }
  1161. static void scmi_put_active_handler(struct scmi_notify_instance *ni,
  1162. struct scmi_event_handler *hndl)
  1163. {
  1164. bool freed;
  1165. struct scmi_registered_event *r_evt = hndl->r_evt;
  1166. u8 protocol_id = r_evt->proto->id;
  1167. mutex_lock(&r_evt->proto->registered_mtx);
  1168. freed = scmi_put_handler_unlocked(ni, hndl);
  1169. mutex_unlock(&r_evt->proto->registered_mtx);
  1170. if (freed)
  1171. scmi_protocol_release(ni->handle, protocol_id);
  1172. }
  1173. /**
  1174. * scmi_event_handler_enable_events() - Enable events associated to an handler
  1175. * @hndl: The Event handler to act upon
  1176. *
  1177. * Return: 0 on Success
  1178. */
  1179. static int scmi_event_handler_enable_events(struct scmi_event_handler *hndl)
  1180. {
  1181. if (scmi_enable_events(hndl)) {
  1182. pr_err("Failed to ENABLE events for key:%X !\n", hndl->key);
  1183. return -EINVAL;
  1184. }
  1185. return 0;
  1186. }
  1187. /**
  1188. * scmi_notifier_register() - Register a notifier_block for an event
  1189. * @handle: The handle identifying the platform instance against which the
  1190. * callback is registered
  1191. * @proto_id: Protocol ID
  1192. * @evt_id: Event ID
  1193. * @src_id: Source ID, when NULL register for events coming form ALL possible
  1194. * sources
  1195. * @nb: A standard notifier block to register for the specified event
  1196. *
  1197. * Generic helper to register a notifier_block against a protocol event.
  1198. *
  1199. * A notifier_block @nb will be registered for each distinct event identified
  1200. * by the tuple (proto_id, evt_id, src_id) on a dedicated notification chain
  1201. * so that:
  1202. *
  1203. * (proto_X, evt_Y, src_Z) --> chain_X_Y_Z
  1204. *
  1205. * @src_id meaning is protocol specific and identifies the origin of the event
  1206. * (like domain_id, sensor_id and so forth).
  1207. *
  1208. * @src_id can be NULL to signify that the caller is interested in receiving
  1209. * notifications from ALL the available sources for that protocol OR simply that
  1210. * the protocol does not support distinct sources.
  1211. *
  1212. * As soon as one user for the specified tuple appears, an handler is created,
  1213. * and that specific event's generation is enabled at the platform level, unless
  1214. * an associated registered event is found missing, meaning that the needed
  1215. * protocol is still to be initialized and the handler has just been registered
  1216. * as still pending.
  1217. *
  1218. * Return: 0 on Success
  1219. */
  1220. static int scmi_notifier_register(const struct scmi_handle *handle,
  1221. u8 proto_id, u8 evt_id, const u32 *src_id,
  1222. struct notifier_block *nb)
  1223. {
  1224. int ret = 0;
  1225. u32 evt_key;
  1226. struct scmi_event_handler *hndl;
  1227. struct scmi_notify_instance *ni;
  1228. ni = scmi_notification_instance_data_get(handle);
  1229. if (!ni)
  1230. return -ENODEV;
  1231. evt_key = MAKE_HASH_KEY(proto_id, evt_id,
  1232. src_id ? *src_id : SRC_ID_MASK);
  1233. hndl = scmi_get_or_create_handler(ni, evt_key);
  1234. if (!hndl)
  1235. return -EINVAL;
  1236. blocking_notifier_chain_register(&hndl->chain, nb);
  1237. /* Enable events for not pending handlers */
  1238. if (!IS_HNDL_PENDING(hndl)) {
  1239. ret = scmi_event_handler_enable_events(hndl);
  1240. if (ret)
  1241. scmi_put_handler(ni, hndl);
  1242. }
  1243. return ret;
  1244. }
  1245. /**
  1246. * scmi_notifier_unregister() - Unregister a notifier_block for an event
  1247. * @handle: The handle identifying the platform instance against which the
  1248. * callback is unregistered
  1249. * @proto_id: Protocol ID
  1250. * @evt_id: Event ID
  1251. * @src_id: Source ID
  1252. * @nb: The notifier_block to unregister
  1253. *
  1254. * Takes care to unregister the provided @nb from the notification chain
  1255. * associated to the specified event and, if there are no more users for the
  1256. * event handler, frees also the associated event handler structures.
  1257. * (this could possibly cause disabling of event's generation at platform level)
  1258. *
  1259. * Return: 0 on Success
  1260. */
  1261. static int scmi_notifier_unregister(const struct scmi_handle *handle,
  1262. u8 proto_id, u8 evt_id, const u32 *src_id,
  1263. struct notifier_block *nb)
  1264. {
  1265. u32 evt_key;
  1266. struct scmi_event_handler *hndl;
  1267. struct scmi_notify_instance *ni;
  1268. ni = scmi_notification_instance_data_get(handle);
  1269. if (!ni)
  1270. return -ENODEV;
  1271. evt_key = MAKE_HASH_KEY(proto_id, evt_id,
  1272. src_id ? *src_id : SRC_ID_MASK);
  1273. hndl = scmi_get_handler(ni, evt_key);
  1274. if (!hndl)
  1275. return -EINVAL;
  1276. /*
  1277. * Note that this chain unregistration call is safe on its own
  1278. * being internally protected by an rwsem.
  1279. */
  1280. blocking_notifier_chain_unregister(&hndl->chain, nb);
  1281. scmi_put_handler(ni, hndl);
  1282. /*
  1283. * This balances the initial get issued in @scmi_notifier_register.
  1284. * If this notifier_block happened to be the last known user callback
  1285. * for this event, the handler is here freed and the event's generation
  1286. * stopped.
  1287. *
  1288. * Note that, an ongoing concurrent lookup on the delivery workqueue
  1289. * path could still hold the refcount to 1 even after this routine
  1290. * completes: in such a case it will be the final put on the delivery
  1291. * path which will finally free this unused handler.
  1292. */
  1293. scmi_put_handler(ni, hndl);
  1294. return 0;
  1295. }
  1296. struct scmi_notifier_devres {
  1297. const struct scmi_handle *handle;
  1298. u8 proto_id;
  1299. u8 evt_id;
  1300. u32 __src_id;
  1301. u32 *src_id;
  1302. struct notifier_block *nb;
  1303. };
  1304. static void scmi_devm_release_notifier(struct device *dev, void *res)
  1305. {
  1306. struct scmi_notifier_devres *dres = res;
  1307. scmi_notifier_unregister(dres->handle, dres->proto_id, dres->evt_id,
  1308. dres->src_id, dres->nb);
  1309. }
  1310. /**
  1311. * scmi_devm_notifier_register() - Managed registration of a notifier_block
  1312. * for an event
  1313. * @sdev: A reference to an scmi_device whose embedded struct device is to
  1314. * be used for devres accounting.
  1315. * @proto_id: Protocol ID
  1316. * @evt_id: Event ID
  1317. * @src_id: Source ID, when NULL register for events coming form ALL possible
  1318. * sources
  1319. * @nb: A standard notifier block to register for the specified event
  1320. *
  1321. * Generic devres managed helper to register a notifier_block against a
  1322. * protocol event.
  1323. *
  1324. * Return: 0 on Success
  1325. */
  1326. static int scmi_devm_notifier_register(struct scmi_device *sdev,
  1327. u8 proto_id, u8 evt_id,
  1328. const u32 *src_id,
  1329. struct notifier_block *nb)
  1330. {
  1331. int ret;
  1332. struct scmi_notifier_devres *dres;
  1333. dres = devres_alloc(scmi_devm_release_notifier,
  1334. sizeof(*dres), GFP_KERNEL);
  1335. if (!dres)
  1336. return -ENOMEM;
  1337. ret = scmi_notifier_register(sdev->handle, proto_id,
  1338. evt_id, src_id, nb);
  1339. if (ret) {
  1340. devres_free(dres);
  1341. return ret;
  1342. }
  1343. dres->handle = sdev->handle;
  1344. dres->proto_id = proto_id;
  1345. dres->evt_id = evt_id;
  1346. dres->nb = nb;
  1347. if (src_id) {
  1348. dres->__src_id = *src_id;
  1349. dres->src_id = &dres->__src_id;
  1350. } else {
  1351. dres->src_id = NULL;
  1352. }
  1353. devres_add(&sdev->dev, dres);
  1354. return ret;
  1355. }
  1356. static int scmi_devm_notifier_match(struct device *dev, void *res, void *data)
  1357. {
  1358. struct scmi_notifier_devres *dres = res;
  1359. struct notifier_block *nb = data;
  1360. if (WARN_ON(!dres || !nb))
  1361. return 0;
  1362. return dres->nb == nb;
  1363. }
  1364. /**
  1365. * scmi_devm_notifier_unregister() - Managed un-registration of a
  1366. * notifier_block for an event
  1367. * @sdev: A reference to an scmi_device whose embedded struct device is to
  1368. * be used for devres accounting.
  1369. * @nb: A standard notifier block to register for the specified event
  1370. *
  1371. * Generic devres managed helper to explicitly un-register a notifier_block
  1372. * against a protocol event, which was previously registered using the above
  1373. * @scmi_devm_notifier_register.
  1374. *
  1375. * Return: 0 on Success
  1376. */
  1377. static int scmi_devm_notifier_unregister(struct scmi_device *sdev,
  1378. struct notifier_block *nb)
  1379. {
  1380. int ret;
  1381. ret = devres_release(&sdev->dev, scmi_devm_release_notifier,
  1382. scmi_devm_notifier_match, nb);
  1383. WARN_ON(ret);
  1384. return ret;
  1385. }
  1386. /**
  1387. * scmi_protocols_late_init() - Worker for late initialization
  1388. * @work: The work item to use associated to the proper SCMI instance
  1389. *
  1390. * This kicks in whenever a new protocol has completed its own registration via
  1391. * scmi_register_protocol_events(): it is in charge of scanning the table of
  1392. * pending handlers (registered by users while the related protocol was still
  1393. * not initialized) and finalizing their initialization whenever possible;
  1394. * invalid pending handlers are purged at this point in time.
  1395. */
  1396. static void scmi_protocols_late_init(struct work_struct *work)
  1397. {
  1398. int bkt;
  1399. struct scmi_event_handler *hndl;
  1400. struct scmi_notify_instance *ni;
  1401. struct hlist_node *tmp;
  1402. ni = container_of(work, struct scmi_notify_instance, init_work);
  1403. /* Ensure protocols and events are up to date */
  1404. smp_rmb();
  1405. mutex_lock(&ni->pending_mtx);
  1406. hash_for_each_safe(ni->pending_events_handlers, bkt, tmp, hndl, hash) {
  1407. int ret;
  1408. ret = scmi_bind_event_handler(ni, hndl);
  1409. if (!ret) {
  1410. dev_dbg(ni->handle->dev,
  1411. "finalized PENDING handler - key:%X\n",
  1412. hndl->key);
  1413. ret = scmi_event_handler_enable_events(hndl);
  1414. if (ret) {
  1415. dev_dbg(ni->handle->dev,
  1416. "purging INVALID handler - key:%X\n",
  1417. hndl->key);
  1418. scmi_put_active_handler(ni, hndl);
  1419. }
  1420. } else {
  1421. ret = scmi_valid_pending_handler(ni, hndl);
  1422. if (ret) {
  1423. dev_dbg(ni->handle->dev,
  1424. "purging PENDING handler - key:%X\n",
  1425. hndl->key);
  1426. /* this hndl can be only a pending one */
  1427. scmi_put_handler_unlocked(ni, hndl);
  1428. }
  1429. }
  1430. }
  1431. mutex_unlock(&ni->pending_mtx);
  1432. }
  1433. /*
  1434. * notify_ops are attached to the handle so that can be accessed
  1435. * directly from an scmi_driver to register its own notifiers.
  1436. */
  1437. static const struct scmi_notify_ops notify_ops = {
  1438. .devm_event_notifier_register = scmi_devm_notifier_register,
  1439. .devm_event_notifier_unregister = scmi_devm_notifier_unregister,
  1440. .event_notifier_register = scmi_notifier_register,
  1441. .event_notifier_unregister = scmi_notifier_unregister,
  1442. };
  1443. /**
  1444. * scmi_notification_init() - Initializes Notification Core Support
  1445. * @handle: The handle identifying the platform instance to initialize
  1446. *
  1447. * This function lays out all the basic resources needed by the notification
  1448. * core instance identified by the provided handle: once done, all of the
  1449. * SCMI Protocols can register their events with the core during their own
  1450. * initializations.
  1451. *
  1452. * Note that failing to initialize the core notifications support does not
  1453. * cause the whole SCMI Protocols stack to fail its initialization.
  1454. *
  1455. * SCMI Notification Initialization happens in 2 steps:
  1456. * * initialization: basic common allocations (this function)
  1457. * * registration: protocols asynchronously come into life and registers their
  1458. * own supported list of events with the core; this causes
  1459. * further per-protocol allocations
  1460. *
  1461. * Any user's callback registration attempt, referring a still not registered
  1462. * event, will be registered as pending and finalized later (if possible)
  1463. * by scmi_protocols_late_init() work.
  1464. * This allows for lazy initialization of SCMI Protocols due to late (or
  1465. * missing) SCMI drivers' modules loading.
  1466. *
  1467. * Return: 0 on Success
  1468. */
  1469. int scmi_notification_init(struct scmi_handle *handle)
  1470. {
  1471. void *gid;
  1472. struct scmi_notify_instance *ni;
  1473. gid = devres_open_group(handle->dev, NULL, GFP_KERNEL);
  1474. if (!gid)
  1475. return -ENOMEM;
  1476. ni = devm_kzalloc(handle->dev, sizeof(*ni), GFP_KERNEL);
  1477. if (!ni)
  1478. goto err;
  1479. ni->gid = gid;
  1480. ni->handle = handle;
  1481. ni->registered_protocols = devm_kcalloc(handle->dev, SCMI_MAX_PROTO,
  1482. sizeof(char *), GFP_KERNEL);
  1483. if (!ni->registered_protocols)
  1484. goto err;
  1485. ni->notify_wq = alloc_workqueue(dev_name(handle->dev),
  1486. WQ_UNBOUND | WQ_FREEZABLE | WQ_SYSFS,
  1487. 0);
  1488. if (!ni->notify_wq)
  1489. goto err;
  1490. mutex_init(&ni->pending_mtx);
  1491. hash_init(ni->pending_events_handlers);
  1492. INIT_WORK(&ni->init_work, scmi_protocols_late_init);
  1493. scmi_notification_instance_data_set(handle, ni);
  1494. handle->notify_ops = &notify_ops;
  1495. /* Ensure handle is up to date */
  1496. smp_wmb();
  1497. dev_info(handle->dev, "Core Enabled.\n");
  1498. devres_close_group(handle->dev, ni->gid);
  1499. return 0;
  1500. err:
  1501. dev_warn(handle->dev, "Initialization Failed.\n");
  1502. devres_release_group(handle->dev, gid);
  1503. return -ENOMEM;
  1504. }
  1505. /**
  1506. * scmi_notification_exit() - Shutdown and clean Notification core
  1507. * @handle: The handle identifying the platform instance to shutdown
  1508. */
  1509. void scmi_notification_exit(struct scmi_handle *handle)
  1510. {
  1511. struct scmi_notify_instance *ni;
  1512. ni = scmi_notification_instance_data_get(handle);
  1513. if (!ni)
  1514. return;
  1515. scmi_notification_instance_data_set(handle, NULL);
  1516. /* Destroy while letting pending work complete */
  1517. destroy_workqueue(ni->notify_wq);
  1518. devres_release_group(ni->handle->dev, ni->gid);
  1519. }