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