notify.c 53 KB

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