1 // SPDX-License-Identifier: GPL-2.0
3 * System Control and Management Interface (SCMI) Message Protocol driver
5 * SCMI Message Protocol is used between the System Control Processor(SCP)
6 * and the Application Processors(AP). The Message Handling Unit(MHU)
7 * provides a mechanism for inter-processor communication between SCP's
10 * SCP offers control and management of the core/cluster power states,
11 * various power domain DVFS including the core/cluster, certain system
12 * clocks configuration, thermal sensors and many others.
14 * Copyright (C) 2018-2021 ARM Ltd.
17 #include <linux/bitmap.h>
18 #include <linux/device.h>
19 #include <linux/export.h>
20 #include <linux/idr.h>
22 #include <linux/kernel.h>
23 #include <linux/ktime.h>
24 #include <linux/hashtable.h>
25 #include <linux/list.h>
26 #include <linux/module.h>
27 #include <linux/of_address.h>
28 #include <linux/of_device.h>
29 #include <linux/processor.h>
30 #include <linux/refcount.h>
31 #include <linux/slab.h>
36 #define CREATE_TRACE_POINTS
37 #include <trace/events/scmi.h>
39 enum scmi_error_codes {
40 SCMI_SUCCESS = 0, /* Success */
41 SCMI_ERR_SUPPORT = -1, /* Not supported */
42 SCMI_ERR_PARAMS = -2, /* Invalid Parameters */
43 SCMI_ERR_ACCESS = -3, /* Invalid access/permission denied */
44 SCMI_ERR_ENTRY = -4, /* Not found */
45 SCMI_ERR_RANGE = -5, /* Value out of range */
46 SCMI_ERR_BUSY = -6, /* Device busy */
47 SCMI_ERR_COMMS = -7, /* Communication Error */
48 SCMI_ERR_GENERIC = -8, /* Generic Error */
49 SCMI_ERR_HARDWARE = -9, /* Hardware Error */
50 SCMI_ERR_PROTOCOL = -10,/* Protocol Error */
53 /* List of all SCMI devices active in system */
54 static LIST_HEAD(scmi_list);
55 /* Protection for the entire list */
56 static DEFINE_MUTEX(scmi_list_mutex);
57 /* Track the unique id for the transfers for debug & profiling purpose */
58 static atomic_t transfer_last_id;
60 static DEFINE_IDR(scmi_requested_devices);
61 static DEFINE_MUTEX(scmi_requested_devices_mtx);
63 struct scmi_requested_dev {
64 const struct scmi_device_id *id_table;
65 struct list_head node;
69 * struct scmi_xfers_info - Structure to manage transfer information
71 * @xfer_alloc_table: Bitmap table for allocated messages.
72 * Index of this bitmap table is also used for message
73 * sequence identifier.
74 * @xfer_lock: Protection for message allocation
75 * @max_msg: Maximum number of messages that can be pending
76 * @free_xfers: A free list for available to use xfers. It is initialized with
77 * a number of xfers equal to the maximum allowed in-flight
79 * @pending_xfers: An hashtable, indexed by msg_hdr.seq, used to keep all the
80 * currently in-flight messages.
82 struct scmi_xfers_info {
83 unsigned long *xfer_alloc_table;
86 struct hlist_head free_xfers;
87 DECLARE_HASHTABLE(pending_xfers, SCMI_PENDING_XFERS_HT_ORDER_SZ);
91 * struct scmi_protocol_instance - Describe an initialized protocol instance.
92 * @handle: Reference to the SCMI handle associated to this protocol instance.
93 * @proto: A reference to the protocol descriptor.
94 * @gid: A reference for per-protocol devres management.
95 * @users: A refcount to track effective users of this protocol.
96 * @priv: Reference for optional protocol private data.
97 * @ph: An embedded protocol handle that will be passed down to protocol
98 * initialization code to identify this instance.
100 * Each protocol is initialized independently once for each SCMI platform in
101 * which is defined by DT and implemented by the SCMI server fw.
103 struct scmi_protocol_instance {
104 const struct scmi_handle *handle;
105 const struct scmi_protocol *proto;
109 struct scmi_protocol_handle ph;
112 #define ph_to_pi(h) container_of(h, struct scmi_protocol_instance, ph)
115 * struct scmi_info - Structure representing a SCMI instance
117 * @dev: Device pointer
118 * @desc: SoC description for this instance
119 * @version: SCMI revision information containing protocol version,
120 * implementation version and (sub-)vendor identification.
121 * @handle: Instance of SCMI handle to send to clients
122 * @tx_minfo: Universal Transmit Message management info
123 * @rx_minfo: Universal Receive Message management info
124 * @tx_idr: IDR object to map protocol id to Tx channel info pointer
125 * @rx_idr: IDR object to map protocol id to Rx channel info pointer
126 * @protocols: IDR for protocols' instance descriptors initialized for
127 * this SCMI instance: populated on protocol's first attempted
129 * @protocols_mtx: A mutex to protect protocols instances initialization.
130 * @protocols_imp: List of protocols implemented, currently maximum of
131 * MAX_PROTOCOLS_IMP elements allocated by the base protocol
132 * @active_protocols: IDR storing device_nodes for protocols actually defined
133 * in the DT and confirmed as implemented by fw.
134 * @notify_priv: Pointer to private data structure specific to notifications.
136 * @users: Number of users of this instance
140 const struct scmi_desc *desc;
141 struct scmi_revision_info version;
142 struct scmi_handle handle;
143 struct scmi_xfers_info tx_minfo;
144 struct scmi_xfers_info rx_minfo;
147 struct idr protocols;
148 /* Ensure mutual exclusive access to protocols instance array */
149 struct mutex protocols_mtx;
151 struct idr active_protocols;
153 struct list_head node;
157 #define handle_to_scmi_info(h) container_of(h, struct scmi_info, handle)
159 static const int scmi_linux_errmap[] = {
160 /* better than switch case as long as return value is continuous */
161 0, /* SCMI_SUCCESS */
162 -EOPNOTSUPP, /* SCMI_ERR_SUPPORT */
163 -EINVAL, /* SCMI_ERR_PARAM */
164 -EACCES, /* SCMI_ERR_ACCESS */
165 -ENOENT, /* SCMI_ERR_ENTRY */
166 -ERANGE, /* SCMI_ERR_RANGE */
167 -EBUSY, /* SCMI_ERR_BUSY */
168 -ECOMM, /* SCMI_ERR_COMMS */
169 -EIO, /* SCMI_ERR_GENERIC */
170 -EREMOTEIO, /* SCMI_ERR_HARDWARE */
171 -EPROTO, /* SCMI_ERR_PROTOCOL */
174 static inline int scmi_to_linux_errno(int errno)
176 int err_idx = -errno;
178 if (err_idx >= SCMI_SUCCESS && err_idx < ARRAY_SIZE(scmi_linux_errmap))
179 return scmi_linux_errmap[err_idx];
183 void scmi_notification_instance_data_set(const struct scmi_handle *handle,
186 struct scmi_info *info = handle_to_scmi_info(handle);
188 info->notify_priv = priv;
189 /* Ensure updated protocol private date are visible */
193 void *scmi_notification_instance_data_get(const struct scmi_handle *handle)
195 struct scmi_info *info = handle_to_scmi_info(handle);
197 /* Ensure protocols_private_data has been updated */
199 return info->notify_priv;
203 * scmi_xfer_token_set - Reserve and set new token for the xfer at hand
205 * @minfo: Pointer to Tx/Rx Message management info based on channel type
206 * @xfer: The xfer to act upon
208 * Pick the next unused monotonically increasing token and set it into
209 * xfer->hdr.seq: picking a monotonically increasing value avoids immediate
210 * reuse of freshly completed or timed-out xfers, thus mitigating the risk
211 * of incorrect association of a late and expired xfer with a live in-flight
212 * transaction, both happening to re-use the same token identifier.
214 * Since platform is NOT required to answer our request in-order we should
215 * account for a few rare but possible scenarios:
217 * - exactly 'next_token' may be NOT available so pick xfer_id >= next_token
218 * using find_next_zero_bit() starting from candidate next_token bit
220 * - all tokens ahead upto (MSG_TOKEN_ID_MASK - 1) are used in-flight but we
221 * are plenty of free tokens at start, so try a second pass using
222 * find_next_zero_bit() and starting from 0.
230 * -----------+----------------------------------------------------------
231 * | | |X|X|X| | | | | | ... ... ... ... ... ... ... ... ... ... ...|X|X|
232 * ----------------------------------------------------------------------
236 * Out-of-order pending at start
237 * -----------------------------
239 * |- xfer_id picked, last_token fixed
240 * -----+----------------------------------------------------------------
241 * |X|X| | | | |X|X| ... ... ... ... ... ... ... ... ... ... ... ...|X| |
242 * ----------------------------------------------------------------------
247 * Out-of-order pending at end
248 * ---------------------------
250 * |- xfer_id picked, last_token fixed
251 * -----+----------------------------------------------------------------
252 * |X|X| | | | |X|X| ... ... ... ... ... ... ... ... ... ... |X|X|X||X|X|
253 * ----------------------------------------------------------------------
257 * Context: Assumes to be called with @xfer_lock already acquired.
259 * Return: 0 on Success or error
261 static int scmi_xfer_token_set(struct scmi_xfers_info *minfo,
262 struct scmi_xfer *xfer)
264 unsigned long xfer_id, next_token;
267 * Pick a candidate monotonic token in range [0, MSG_TOKEN_MAX - 1]
268 * using the pre-allocated transfer_id as a base.
269 * Note that the global transfer_id is shared across all message types
270 * so there could be holes in the allocated set of monotonic sequence
271 * numbers, but that is going to limit the effectiveness of the
272 * mitigation only in very rare limit conditions.
274 next_token = (xfer->transfer_id & (MSG_TOKEN_MAX - 1));
276 /* Pick the next available xfer_id >= next_token */
277 xfer_id = find_next_zero_bit(minfo->xfer_alloc_table,
278 MSG_TOKEN_MAX, next_token);
279 if (xfer_id == MSG_TOKEN_MAX) {
281 * After heavily out-of-order responses, there are no free
282 * tokens ahead, but only at start of xfer_alloc_table so
283 * try again from the beginning.
285 xfer_id = find_next_zero_bit(minfo->xfer_alloc_table,
288 * Something is wrong if we got here since there can be a
289 * maximum number of (MSG_TOKEN_MAX - 1) in-flight messages
290 * but we have not found any free token [0, MSG_TOKEN_MAX - 1].
292 if (WARN_ON_ONCE(xfer_id == MSG_TOKEN_MAX))
296 /* Update +/- last_token accordingly if we skipped some hole */
297 if (xfer_id != next_token)
298 atomic_add((int)(xfer_id - next_token), &transfer_last_id);
301 set_bit(xfer_id, minfo->xfer_alloc_table);
302 xfer->hdr.seq = (u16)xfer_id;
308 * scmi_xfer_token_clear - Release the token
310 * @minfo: Pointer to Tx/Rx Message management info based on channel type
311 * @xfer: The xfer to act upon
313 static inline void scmi_xfer_token_clear(struct scmi_xfers_info *minfo,
314 struct scmi_xfer *xfer)
316 clear_bit(xfer->hdr.seq, minfo->xfer_alloc_table);
320 * scmi_xfer_get() - Allocate one message
322 * @handle: Pointer to SCMI entity handle
323 * @minfo: Pointer to Tx/Rx Message management info based on channel type
324 * @set_pending: If true a monotonic token is picked and the xfer is added to
325 * the pending hash table.
327 * Helper function which is used by various message functions that are
328 * exposed to clients of this driver for allocating a message traffic event.
330 * Picks an xfer from the free list @free_xfers (if any available) and, if
331 * required, sets a monotonically increasing token and stores the inflight xfer
332 * into the @pending_xfers hashtable for later retrieval.
334 * The successfully initialized xfer is refcounted.
336 * Context: Holds @xfer_lock while manipulating @xfer_alloc_table and
339 * Return: 0 if all went fine, else corresponding error.
341 static struct scmi_xfer *scmi_xfer_get(const struct scmi_handle *handle,
342 struct scmi_xfers_info *minfo,
347 struct scmi_xfer *xfer;
349 spin_lock_irqsave(&minfo->xfer_lock, flags);
350 if (hlist_empty(&minfo->free_xfers)) {
351 spin_unlock_irqrestore(&minfo->xfer_lock, flags);
352 return ERR_PTR(-ENOMEM);
355 /* grab an xfer from the free_list */
356 xfer = hlist_entry(minfo->free_xfers.first, struct scmi_xfer, node);
357 hlist_del_init(&xfer->node);
360 * Allocate transfer_id early so that can be used also as base for
361 * monotonic sequence number generation if needed.
363 xfer->transfer_id = atomic_inc_return(&transfer_last_id);
366 /* Pick and set monotonic token */
367 ret = scmi_xfer_token_set(minfo, xfer);
369 hash_add(minfo->pending_xfers, &xfer->node,
371 xfer->pending = true;
374 "Failed to get monotonic token %d\n", ret);
375 hlist_add_head(&xfer->node, &minfo->free_xfers);
381 refcount_set(&xfer->users, 1);
382 atomic_set(&xfer->busy, SCMI_XFER_FREE);
384 spin_unlock_irqrestore(&minfo->xfer_lock, flags);
390 * __scmi_xfer_put() - Release a message
392 * @minfo: Pointer to Tx/Rx Message management info based on channel type
393 * @xfer: message that was reserved by scmi_xfer_get
395 * After refcount check, possibly release an xfer, clearing the token slot,
396 * removing xfer from @pending_xfers and putting it back into free_xfers.
398 * This holds a spinlock to maintain integrity of internal data structures.
401 __scmi_xfer_put(struct scmi_xfers_info *minfo, struct scmi_xfer *xfer)
405 spin_lock_irqsave(&minfo->xfer_lock, flags);
406 if (refcount_dec_and_test(&xfer->users)) {
408 scmi_xfer_token_clear(minfo, xfer);
409 hash_del(&xfer->node);
410 xfer->pending = false;
412 hlist_add_head(&xfer->node, &minfo->free_xfers);
414 spin_unlock_irqrestore(&minfo->xfer_lock, flags);
418 * scmi_xfer_lookup_unlocked - Helper to lookup an xfer_id
420 * @minfo: Pointer to Tx/Rx Message management info based on channel type
421 * @xfer_id: Token ID to lookup in @pending_xfers
423 * Refcounting is untouched.
425 * Context: Assumes to be called with @xfer_lock already acquired.
427 * Return: A valid xfer on Success or error otherwise
429 static struct scmi_xfer *
430 scmi_xfer_lookup_unlocked(struct scmi_xfers_info *minfo, u16 xfer_id)
432 struct scmi_xfer *xfer = NULL;
434 if (test_bit(xfer_id, minfo->xfer_alloc_table))
435 xfer = XFER_FIND(minfo->pending_xfers, xfer_id);
437 return xfer ?: ERR_PTR(-EINVAL);
441 * scmi_msg_response_validate - Validate message type against state of related
444 * @cinfo: A reference to the channel descriptor.
445 * @msg_type: Message type to check
446 * @xfer: A reference to the xfer to validate against @msg_type
448 * This function checks if @msg_type is congruent with the current state of
449 * a pending @xfer; if an asynchronous delayed response is received before the
450 * related synchronous response (Out-of-Order Delayed Response) the missing
451 * synchronous response is assumed to be OK and completed, carrying on with the
452 * Delayed Response: this is done to address the case in which the underlying
453 * SCMI transport can deliver such out-of-order responses.
455 * Context: Assumes to be called with xfer->lock already acquired.
457 * Return: 0 on Success, error otherwise
459 static inline int scmi_msg_response_validate(struct scmi_chan_info *cinfo,
461 struct scmi_xfer *xfer)
464 * Even if a response was indeed expected on this slot at this point,
465 * a buggy platform could wrongly reply feeding us an unexpected
466 * delayed response we're not prepared to handle: bail-out safely
469 if (msg_type == MSG_TYPE_DELAYED_RESP && !xfer->async_done) {
471 "Delayed Response for %d not expected! Buggy F/W ?\n",
476 switch (xfer->state) {
477 case SCMI_XFER_SENT_OK:
478 if (msg_type == MSG_TYPE_DELAYED_RESP) {
480 * Delayed Response expected but delivered earlier.
481 * Assume message RESPONSE was OK and skip state.
483 xfer->hdr.status = SCMI_SUCCESS;
484 xfer->state = SCMI_XFER_RESP_OK;
485 complete(&xfer->done);
487 "Received valid OoO Delayed Response for %d\n",
491 case SCMI_XFER_RESP_OK:
492 if (msg_type != MSG_TYPE_DELAYED_RESP)
495 case SCMI_XFER_DRESP_OK:
496 /* No further message expected once in SCMI_XFER_DRESP_OK */
504 * scmi_xfer_state_update - Update xfer state
506 * @xfer: A reference to the xfer to update
507 * @msg_type: Type of message being processed.
509 * Note that this message is assumed to have been already successfully validated
510 * by @scmi_msg_response_validate(), so here we just update the state.
512 * Context: Assumes to be called on an xfer exclusively acquired using the
515 static inline void scmi_xfer_state_update(struct scmi_xfer *xfer, u8 msg_type)
517 xfer->hdr.type = msg_type;
519 /* Unknown command types were already discarded earlier */
520 if (xfer->hdr.type == MSG_TYPE_COMMAND)
521 xfer->state = SCMI_XFER_RESP_OK;
523 xfer->state = SCMI_XFER_DRESP_OK;
526 static bool scmi_xfer_acquired(struct scmi_xfer *xfer)
530 ret = atomic_cmpxchg(&xfer->busy, SCMI_XFER_FREE, SCMI_XFER_BUSY);
532 return ret == SCMI_XFER_FREE;
536 * scmi_xfer_command_acquire - Helper to lookup and acquire a command xfer
538 * @cinfo: A reference to the channel descriptor.
539 * @msg_hdr: A message header to use as lookup key
541 * When a valid xfer is found for the sequence number embedded in the provided
542 * msg_hdr, reference counting is properly updated and exclusive access to this
543 * xfer is granted till released with @scmi_xfer_command_release.
545 * Return: A valid @xfer on Success or error otherwise.
547 static inline struct scmi_xfer *
548 scmi_xfer_command_acquire(struct scmi_chan_info *cinfo, u32 msg_hdr)
552 struct scmi_xfer *xfer;
553 struct scmi_info *info = handle_to_scmi_info(cinfo->handle);
554 struct scmi_xfers_info *minfo = &info->tx_minfo;
555 u8 msg_type = MSG_XTRACT_TYPE(msg_hdr);
556 u16 xfer_id = MSG_XTRACT_TOKEN(msg_hdr);
558 /* Are we even expecting this? */
559 spin_lock_irqsave(&minfo->xfer_lock, flags);
560 xfer = scmi_xfer_lookup_unlocked(minfo, xfer_id);
563 "Message for %d type %d is not expected!\n",
565 spin_unlock_irqrestore(&minfo->xfer_lock, flags);
568 refcount_inc(&xfer->users);
569 spin_unlock_irqrestore(&minfo->xfer_lock, flags);
571 spin_lock_irqsave(&xfer->lock, flags);
572 ret = scmi_msg_response_validate(cinfo, msg_type, xfer);
574 * If a pending xfer was found which was also in a congruent state with
575 * the received message, acquire exclusive access to it setting the busy
577 * Spins only on the rare limit condition of concurrent reception of
578 * RESP and DRESP for the same xfer.
581 spin_until_cond(scmi_xfer_acquired(xfer));
582 scmi_xfer_state_update(xfer, msg_type);
584 spin_unlock_irqrestore(&xfer->lock, flags);
588 "Invalid message type:%d for %d - HDR:0x%X state:%d\n",
589 msg_type, xfer_id, msg_hdr, xfer->state);
590 /* On error the refcount incremented above has to be dropped */
591 __scmi_xfer_put(minfo, xfer);
592 xfer = ERR_PTR(-EINVAL);
598 static inline void scmi_xfer_command_release(struct scmi_info *info,
599 struct scmi_xfer *xfer)
601 atomic_set(&xfer->busy, SCMI_XFER_FREE);
602 __scmi_xfer_put(&info->tx_minfo, xfer);
605 static inline void scmi_clear_channel(struct scmi_info *info,
606 struct scmi_chan_info *cinfo)
608 if (info->desc->ops->clear_channel)
609 info->desc->ops->clear_channel(cinfo);
612 static void scmi_handle_notification(struct scmi_chan_info *cinfo,
613 u32 msg_hdr, void *priv)
615 struct scmi_xfer *xfer;
616 struct device *dev = cinfo->dev;
617 struct scmi_info *info = handle_to_scmi_info(cinfo->handle);
618 struct scmi_xfers_info *minfo = &info->rx_minfo;
621 ts = ktime_get_boottime();
622 xfer = scmi_xfer_get(cinfo->handle, minfo, false);
624 dev_err(dev, "failed to get free message slot (%ld)\n",
626 scmi_clear_channel(info, cinfo);
630 unpack_scmi_header(msg_hdr, &xfer->hdr);
633 info->desc->ops->fetch_notification(cinfo, info->desc->max_msg_size,
635 scmi_notify(cinfo->handle, xfer->hdr.protocol_id,
636 xfer->hdr.id, xfer->rx.buf, xfer->rx.len, ts);
638 trace_scmi_rx_done(xfer->transfer_id, xfer->hdr.id,
639 xfer->hdr.protocol_id, xfer->hdr.seq,
640 MSG_TYPE_NOTIFICATION);
642 __scmi_xfer_put(minfo, xfer);
644 scmi_clear_channel(info, cinfo);
647 static void scmi_handle_response(struct scmi_chan_info *cinfo,
648 u32 msg_hdr, void *priv)
650 struct scmi_xfer *xfer;
651 struct scmi_info *info = handle_to_scmi_info(cinfo->handle);
653 xfer = scmi_xfer_command_acquire(cinfo, msg_hdr);
655 if (MSG_XTRACT_TYPE(msg_hdr) == MSG_TYPE_DELAYED_RESP)
656 scmi_clear_channel(info, cinfo);
660 /* rx.len could be shrunk in the sync do_xfer, so reset to maxsz */
661 if (xfer->hdr.type == MSG_TYPE_DELAYED_RESP)
662 xfer->rx.len = info->desc->max_msg_size;
666 info->desc->ops->fetch_response(cinfo, xfer);
668 trace_scmi_rx_done(xfer->transfer_id, xfer->hdr.id,
669 xfer->hdr.protocol_id, xfer->hdr.seq,
672 if (xfer->hdr.type == MSG_TYPE_DELAYED_RESP) {
673 scmi_clear_channel(info, cinfo);
674 complete(xfer->async_done);
676 complete(&xfer->done);
679 scmi_xfer_command_release(info, xfer);
683 * scmi_rx_callback() - callback for receiving messages
685 * @cinfo: SCMI channel info
686 * @msg_hdr: Message header
687 * @priv: Transport specific private data.
689 * Processes one received message to appropriate transfer information and
690 * signals completion of the transfer.
692 * NOTE: This function will be invoked in IRQ context, hence should be
693 * as optimal as possible.
695 void scmi_rx_callback(struct scmi_chan_info *cinfo, u32 msg_hdr, void *priv)
697 u8 msg_type = MSG_XTRACT_TYPE(msg_hdr);
700 case MSG_TYPE_NOTIFICATION:
701 scmi_handle_notification(cinfo, msg_hdr, priv);
703 case MSG_TYPE_COMMAND:
704 case MSG_TYPE_DELAYED_RESP:
705 scmi_handle_response(cinfo, msg_hdr, priv);
708 WARN_ONCE(1, "received unknown msg_type:%d\n", msg_type);
714 * xfer_put() - Release a transmit message
716 * @ph: Pointer to SCMI protocol handle
717 * @xfer: message that was reserved by xfer_get_init
719 static void xfer_put(const struct scmi_protocol_handle *ph,
720 struct scmi_xfer *xfer)
722 const struct scmi_protocol_instance *pi = ph_to_pi(ph);
723 struct scmi_info *info = handle_to_scmi_info(pi->handle);
725 __scmi_xfer_put(&info->tx_minfo, xfer);
728 #define SCMI_MAX_POLL_TO_NS (100 * NSEC_PER_USEC)
730 static bool scmi_xfer_done_no_timeout(struct scmi_chan_info *cinfo,
731 struct scmi_xfer *xfer, ktime_t stop)
733 struct scmi_info *info = handle_to_scmi_info(cinfo->handle);
736 * Poll also on xfer->done so that polling can be forcibly terminated
737 * in case of out-of-order receptions of delayed responses
739 return info->desc->ops->poll_done(cinfo, xfer) ||
740 try_wait_for_completion(&xfer->done) ||
741 ktime_after(ktime_get(), stop);
745 * do_xfer() - Do one transfer
747 * @ph: Pointer to SCMI protocol handle
748 * @xfer: Transfer to initiate and wait for response
750 * Return: -ETIMEDOUT in case of no response, if transmit error,
751 * return corresponding error, else if all goes well,
754 static int do_xfer(const struct scmi_protocol_handle *ph,
755 struct scmi_xfer *xfer)
759 const struct scmi_protocol_instance *pi = ph_to_pi(ph);
760 struct scmi_info *info = handle_to_scmi_info(pi->handle);
761 struct device *dev = info->dev;
762 struct scmi_chan_info *cinfo;
764 if (xfer->hdr.poll_completion && !info->desc->ops->poll_done) {
766 "Polling mode is not supported by transport.\n");
771 * Initialise protocol id now from protocol handle to avoid it being
772 * overridden by mistake (or malice) by the protocol code mangling with
773 * the scmi_xfer structure prior to this.
775 xfer->hdr.protocol_id = pi->proto->id;
776 reinit_completion(&xfer->done);
778 cinfo = idr_find(&info->tx_idr, xfer->hdr.protocol_id);
779 if (unlikely(!cinfo))
782 trace_scmi_xfer_begin(xfer->transfer_id, xfer->hdr.id,
783 xfer->hdr.protocol_id, xfer->hdr.seq,
784 xfer->hdr.poll_completion);
786 xfer->state = SCMI_XFER_SENT_OK;
788 * Even though spinlocking is not needed here since no race is possible
789 * on xfer->state due to the monotonically increasing tokens allocation,
790 * we must anyway ensure xfer->state initialization is not re-ordered
791 * after the .send_message() to be sure that on the RX path an early
792 * ISR calling scmi_rx_callback() cannot see an old stale xfer->state.
796 ret = info->desc->ops->send_message(cinfo, xfer);
798 dev_dbg(dev, "Failed to send message %d\n", ret);
802 if (xfer->hdr.poll_completion) {
803 ktime_t stop = ktime_add_ns(ktime_get(), SCMI_MAX_POLL_TO_NS);
805 spin_until_cond(scmi_xfer_done_no_timeout(cinfo, xfer, stop));
806 if (ktime_before(ktime_get(), stop)) {
810 * Do not fetch_response if an out-of-order delayed
811 * response is being processed.
813 spin_lock_irqsave(&xfer->lock, flags);
814 if (xfer->state == SCMI_XFER_SENT_OK) {
815 info->desc->ops->fetch_response(cinfo, xfer);
816 xfer->state = SCMI_XFER_RESP_OK;
818 spin_unlock_irqrestore(&xfer->lock, flags);
823 /* And we wait for the response. */
824 timeout = msecs_to_jiffies(info->desc->max_rx_timeout_ms);
825 if (!wait_for_completion_timeout(&xfer->done, timeout)) {
826 dev_err(dev, "timed out in resp(caller: %pS)\n",
832 if (!ret && xfer->hdr.status)
833 ret = scmi_to_linux_errno(xfer->hdr.status);
835 if (info->desc->ops->mark_txdone)
836 info->desc->ops->mark_txdone(cinfo, ret);
838 trace_scmi_xfer_end(xfer->transfer_id, xfer->hdr.id,
839 xfer->hdr.protocol_id, xfer->hdr.seq, ret);
844 static void reset_rx_to_maxsz(const struct scmi_protocol_handle *ph,
845 struct scmi_xfer *xfer)
847 const struct scmi_protocol_instance *pi = ph_to_pi(ph);
848 struct scmi_info *info = handle_to_scmi_info(pi->handle);
850 xfer->rx.len = info->desc->max_msg_size;
853 #define SCMI_MAX_RESPONSE_TIMEOUT (2 * MSEC_PER_SEC)
856 * do_xfer_with_response() - Do one transfer and wait until the delayed
857 * response is received
859 * @ph: Pointer to SCMI protocol handle
860 * @xfer: Transfer to initiate and wait for response
862 * Return: -ETIMEDOUT in case of no delayed response, if transmit error,
863 * return corresponding error, else if all goes well, return 0.
865 static int do_xfer_with_response(const struct scmi_protocol_handle *ph,
866 struct scmi_xfer *xfer)
868 int ret, timeout = msecs_to_jiffies(SCMI_MAX_RESPONSE_TIMEOUT);
869 DECLARE_COMPLETION_ONSTACK(async_response);
871 xfer->async_done = &async_response;
873 ret = do_xfer(ph, xfer);
875 if (!wait_for_completion_timeout(xfer->async_done, timeout))
877 else if (xfer->hdr.status)
878 ret = scmi_to_linux_errno(xfer->hdr.status);
881 xfer->async_done = NULL;
886 * xfer_get_init() - Allocate and initialise one message for transmit
888 * @ph: Pointer to SCMI protocol handle
889 * @msg_id: Message identifier
890 * @tx_size: transmit message size
891 * @rx_size: receive message size
892 * @p: pointer to the allocated and initialised message
894 * This function allocates the message using @scmi_xfer_get and
895 * initialise the header.
897 * Return: 0 if all went fine with @p pointing to message, else
898 * corresponding error.
900 static int xfer_get_init(const struct scmi_protocol_handle *ph,
901 u8 msg_id, size_t tx_size, size_t rx_size,
902 struct scmi_xfer **p)
905 struct scmi_xfer *xfer;
906 const struct scmi_protocol_instance *pi = ph_to_pi(ph);
907 struct scmi_info *info = handle_to_scmi_info(pi->handle);
908 struct scmi_xfers_info *minfo = &info->tx_minfo;
909 struct device *dev = info->dev;
911 /* Ensure we have sane transfer sizes */
912 if (rx_size > info->desc->max_msg_size ||
913 tx_size > info->desc->max_msg_size)
916 xfer = scmi_xfer_get(pi->handle, minfo, true);
919 dev_err(dev, "failed to get free message slot(%d)\n", ret);
923 xfer->tx.len = tx_size;
924 xfer->rx.len = rx_size ? : info->desc->max_msg_size;
925 xfer->hdr.type = MSG_TYPE_COMMAND;
926 xfer->hdr.id = msg_id;
927 xfer->hdr.poll_completion = false;
935 * version_get() - command to get the revision of the SCMI entity
937 * @ph: Pointer to SCMI protocol handle
938 * @version: Holds returned version of protocol.
940 * Updates the SCMI information in the internal data structure.
942 * Return: 0 if all went fine, else return appropriate error.
944 static int version_get(const struct scmi_protocol_handle *ph, u32 *version)
950 ret = xfer_get_init(ph, PROTOCOL_VERSION, 0, sizeof(*version), &t);
954 ret = do_xfer(ph, t);
956 rev_info = t->rx.buf;
957 *version = le32_to_cpu(*rev_info);
965 * scmi_set_protocol_priv - Set protocol specific data at init time
967 * @ph: A reference to the protocol handle.
968 * @priv: The private data to set.
970 * Return: 0 on Success
972 static int scmi_set_protocol_priv(const struct scmi_protocol_handle *ph,
975 struct scmi_protocol_instance *pi = ph_to_pi(ph);
983 * scmi_get_protocol_priv - Set protocol specific data at init time
985 * @ph: A reference to the protocol handle.
987 * Return: Protocol private data if any was set.
989 static void *scmi_get_protocol_priv(const struct scmi_protocol_handle *ph)
991 const struct scmi_protocol_instance *pi = ph_to_pi(ph);
996 static const struct scmi_xfer_ops xfer_ops = {
997 .version_get = version_get,
998 .xfer_get_init = xfer_get_init,
999 .reset_rx_to_maxsz = reset_rx_to_maxsz,
1001 .do_xfer_with_response = do_xfer_with_response,
1002 .xfer_put = xfer_put,
1006 * scmi_revision_area_get - Retrieve version memory area.
1008 * @ph: A reference to the protocol handle.
1010 * A helper to grab the version memory area reference during SCMI Base protocol
1013 * Return: A reference to the version memory area associated to the SCMI
1014 * instance underlying this protocol handle.
1016 struct scmi_revision_info *
1017 scmi_revision_area_get(const struct scmi_protocol_handle *ph)
1019 const struct scmi_protocol_instance *pi = ph_to_pi(ph);
1021 return pi->handle->version;
1025 * scmi_alloc_init_protocol_instance - Allocate and initialize a protocol
1026 * instance descriptor.
1027 * @info: The reference to the related SCMI instance.
1028 * @proto: The protocol descriptor.
1030 * Allocate a new protocol instance descriptor, using the provided @proto
1031 * description, against the specified SCMI instance @info, and initialize it;
1032 * all resources management is handled via a dedicated per-protocol devres
1035 * Context: Assumes to be called with @protocols_mtx already acquired.
1036 * Return: A reference to a freshly allocated and initialized protocol instance
1037 * or ERR_PTR on failure. On failure the @proto reference is at first
1038 * put using @scmi_protocol_put() before releasing all the devres group.
1040 static struct scmi_protocol_instance *
1041 scmi_alloc_init_protocol_instance(struct scmi_info *info,
1042 const struct scmi_protocol *proto)
1046 struct scmi_protocol_instance *pi;
1047 const struct scmi_handle *handle = &info->handle;
1049 /* Protocol specific devres group */
1050 gid = devres_open_group(handle->dev, NULL, GFP_KERNEL);
1052 scmi_protocol_put(proto->id);
1056 pi = devm_kzalloc(handle->dev, sizeof(*pi), GFP_KERNEL);
1062 pi->handle = handle;
1063 pi->ph.dev = handle->dev;
1064 pi->ph.xops = &xfer_ops;
1065 pi->ph.set_priv = scmi_set_protocol_priv;
1066 pi->ph.get_priv = scmi_get_protocol_priv;
1067 refcount_set(&pi->users, 1);
1068 /* proto->init is assured NON NULL by scmi_protocol_register */
1069 ret = pi->proto->instance_init(&pi->ph);
1073 ret = idr_alloc(&info->protocols, pi, proto->id, proto->id + 1,
1075 if (ret != proto->id)
1079 * Warn but ignore events registration errors since we do not want
1080 * to skip whole protocols if their notifications are messed up.
1082 if (pi->proto->events) {
1083 ret = scmi_register_protocol_events(handle, pi->proto->id,
1087 dev_warn(handle->dev,
1088 "Protocol:%X - Events Registration Failed - err:%d\n",
1089 pi->proto->id, ret);
1092 devres_close_group(handle->dev, pi->gid);
1093 dev_dbg(handle->dev, "Initialized protocol: 0x%X\n", pi->proto->id);
1098 /* Take care to put the protocol module's owner before releasing all */
1099 scmi_protocol_put(proto->id);
1100 devres_release_group(handle->dev, gid);
1102 return ERR_PTR(ret);
1106 * scmi_get_protocol_instance - Protocol initialization helper.
1107 * @handle: A reference to the SCMI platform instance.
1108 * @protocol_id: The protocol being requested.
1110 * In case the required protocol has never been requested before for this
1111 * instance, allocate and initialize all the needed structures while handling
1112 * resource allocation with a dedicated per-protocol devres subgroup.
1114 * Return: A reference to an initialized protocol instance or error on failure:
1115 * in particular returns -EPROBE_DEFER when the desired protocol could
1118 static struct scmi_protocol_instance * __must_check
1119 scmi_get_protocol_instance(const struct scmi_handle *handle, u8 protocol_id)
1121 struct scmi_protocol_instance *pi;
1122 struct scmi_info *info = handle_to_scmi_info(handle);
1124 mutex_lock(&info->protocols_mtx);
1125 pi = idr_find(&info->protocols, protocol_id);
1128 refcount_inc(&pi->users);
1130 const struct scmi_protocol *proto;
1132 /* Fails if protocol not registered on bus */
1133 proto = scmi_protocol_get(protocol_id);
1135 pi = scmi_alloc_init_protocol_instance(info, proto);
1137 pi = ERR_PTR(-EPROBE_DEFER);
1139 mutex_unlock(&info->protocols_mtx);
1145 * scmi_protocol_acquire - Protocol acquire
1146 * @handle: A reference to the SCMI platform instance.
1147 * @protocol_id: The protocol being requested.
1149 * Register a new user for the requested protocol on the specified SCMI
1150 * platform instance, possibly triggering its initialization on first user.
1152 * Return: 0 if protocol was acquired successfully.
1154 int scmi_protocol_acquire(const struct scmi_handle *handle, u8 protocol_id)
1156 return PTR_ERR_OR_ZERO(scmi_get_protocol_instance(handle, protocol_id));
1160 * scmi_protocol_release - Protocol de-initialization helper.
1161 * @handle: A reference to the SCMI platform instance.
1162 * @protocol_id: The protocol being requested.
1164 * Remove one user for the specified protocol and triggers de-initialization
1165 * and resources de-allocation once the last user has gone.
1167 void scmi_protocol_release(const struct scmi_handle *handle, u8 protocol_id)
1169 struct scmi_info *info = handle_to_scmi_info(handle);
1170 struct scmi_protocol_instance *pi;
1172 mutex_lock(&info->protocols_mtx);
1173 pi = idr_find(&info->protocols, protocol_id);
1177 if (refcount_dec_and_test(&pi->users)) {
1178 void *gid = pi->gid;
1180 if (pi->proto->events)
1181 scmi_deregister_protocol_events(handle, protocol_id);
1183 if (pi->proto->instance_deinit)
1184 pi->proto->instance_deinit(&pi->ph);
1186 idr_remove(&info->protocols, protocol_id);
1188 scmi_protocol_put(protocol_id);
1190 devres_release_group(handle->dev, gid);
1191 dev_dbg(handle->dev, "De-Initialized protocol: 0x%X\n",
1196 mutex_unlock(&info->protocols_mtx);
1199 void scmi_setup_protocol_implemented(const struct scmi_protocol_handle *ph,
1202 const struct scmi_protocol_instance *pi = ph_to_pi(ph);
1203 struct scmi_info *info = handle_to_scmi_info(pi->handle);
1205 info->protocols_imp = prot_imp;
1209 scmi_is_protocol_implemented(const struct scmi_handle *handle, u8 prot_id)
1212 struct scmi_info *info = handle_to_scmi_info(handle);
1214 if (!info->protocols_imp)
1217 for (i = 0; i < MAX_PROTOCOLS_IMP; i++)
1218 if (info->protocols_imp[i] == prot_id)
1223 struct scmi_protocol_devres {
1224 const struct scmi_handle *handle;
1228 static void scmi_devm_release_protocol(struct device *dev, void *res)
1230 struct scmi_protocol_devres *dres = res;
1232 scmi_protocol_release(dres->handle, dres->protocol_id);
1236 * scmi_devm_protocol_get - Devres managed get protocol operations and handle
1237 * @sdev: A reference to an scmi_device whose embedded struct device is to
1238 * be used for devres accounting.
1239 * @protocol_id: The protocol being requested.
1240 * @ph: A pointer reference used to pass back the associated protocol handle.
1242 * Get hold of a protocol accounting for its usage, eventually triggering its
1243 * initialization, and returning the protocol specific operations and related
1244 * protocol handle which will be used as first argument in most of the
1245 * protocols operations methods.
1246 * Being a devres based managed method, protocol hold will be automatically
1247 * released, and possibly de-initialized on last user, once the SCMI driver
1248 * owning the scmi_device is unbound from it.
1250 * Return: A reference to the requested protocol operations or error.
1251 * Must be checked for errors by caller.
1253 static const void __must_check *
1254 scmi_devm_protocol_get(struct scmi_device *sdev, u8 protocol_id,
1255 struct scmi_protocol_handle **ph)
1257 struct scmi_protocol_instance *pi;
1258 struct scmi_protocol_devres *dres;
1259 struct scmi_handle *handle = sdev->handle;
1262 return ERR_PTR(-EINVAL);
1264 dres = devres_alloc(scmi_devm_release_protocol,
1265 sizeof(*dres), GFP_KERNEL);
1267 return ERR_PTR(-ENOMEM);
1269 pi = scmi_get_protocol_instance(handle, protocol_id);
1275 dres->handle = handle;
1276 dres->protocol_id = protocol_id;
1277 devres_add(&sdev->dev, dres);
1281 return pi->proto->ops;
1284 static int scmi_devm_protocol_match(struct device *dev, void *res, void *data)
1286 struct scmi_protocol_devres *dres = res;
1288 if (WARN_ON(!dres || !data))
1291 return dres->protocol_id == *((u8 *)data);
1295 * scmi_devm_protocol_put - Devres managed put protocol operations and handle
1296 * @sdev: A reference to an scmi_device whose embedded struct device is to
1297 * be used for devres accounting.
1298 * @protocol_id: The protocol being requested.
1300 * Explicitly release a protocol hold previously obtained calling the above
1301 * @scmi_devm_protocol_get.
1303 static void scmi_devm_protocol_put(struct scmi_device *sdev, u8 protocol_id)
1307 ret = devres_release(&sdev->dev, scmi_devm_release_protocol,
1308 scmi_devm_protocol_match, &protocol_id);
1313 struct scmi_handle *scmi_handle_get_from_info_unlocked(struct scmi_info *info)
1316 return &info->handle;
1320 * scmi_handle_get() - Get the SCMI handle for a device
1322 * @dev: pointer to device for which we want SCMI handle
1324 * NOTE: The function does not track individual clients of the framework
1325 * and is expected to be maintained by caller of SCMI protocol library.
1326 * scmi_handle_put must be balanced with successful scmi_handle_get
1328 * Return: pointer to handle if successful, NULL on error
1330 struct scmi_handle *scmi_handle_get(struct device *dev)
1332 struct list_head *p;
1333 struct scmi_info *info;
1334 struct scmi_handle *handle = NULL;
1336 mutex_lock(&scmi_list_mutex);
1337 list_for_each(p, &scmi_list) {
1338 info = list_entry(p, struct scmi_info, node);
1339 if (dev->parent == info->dev) {
1340 handle = scmi_handle_get_from_info_unlocked(info);
1344 mutex_unlock(&scmi_list_mutex);
1350 * scmi_handle_put() - Release the handle acquired by scmi_handle_get
1352 * @handle: handle acquired by scmi_handle_get
1354 * NOTE: The function does not track individual clients of the framework
1355 * and is expected to be maintained by caller of SCMI protocol library.
1356 * scmi_handle_put must be balanced with successful scmi_handle_get
1358 * Return: 0 is successfully released
1359 * if null was passed, it returns -EINVAL;
1361 int scmi_handle_put(const struct scmi_handle *handle)
1363 struct scmi_info *info;
1368 info = handle_to_scmi_info(handle);
1369 mutex_lock(&scmi_list_mutex);
1370 if (!WARN_ON(!info->users))
1372 mutex_unlock(&scmi_list_mutex);
1377 static int __scmi_xfer_info_init(struct scmi_info *sinfo,
1378 struct scmi_xfers_info *info)
1381 struct scmi_xfer *xfer;
1382 struct device *dev = sinfo->dev;
1383 const struct scmi_desc *desc = sinfo->desc;
1385 /* Pre-allocated messages, no more than what hdr.seq can support */
1386 if (WARN_ON(!info->max_msg || info->max_msg > MSG_TOKEN_MAX)) {
1388 "Invalid maximum messages %d, not in range [1 - %lu]\n",
1389 info->max_msg, MSG_TOKEN_MAX);
1393 hash_init(info->pending_xfers);
1395 /* Allocate a bitmask sized to hold MSG_TOKEN_MAX tokens */
1396 info->xfer_alloc_table = devm_kcalloc(dev, BITS_TO_LONGS(MSG_TOKEN_MAX),
1397 sizeof(long), GFP_KERNEL);
1398 if (!info->xfer_alloc_table)
1402 * Preallocate a number of xfers equal to max inflight messages,
1403 * pre-initialize the buffer pointer to pre-allocated buffers and
1404 * attach all of them to the free list
1406 INIT_HLIST_HEAD(&info->free_xfers);
1407 for (i = 0; i < info->max_msg; i++) {
1408 xfer = devm_kzalloc(dev, sizeof(*xfer), GFP_KERNEL);
1412 xfer->rx.buf = devm_kcalloc(dev, sizeof(u8), desc->max_msg_size,
1417 xfer->tx.buf = xfer->rx.buf;
1418 init_completion(&xfer->done);
1419 spin_lock_init(&xfer->lock);
1421 /* Add initialized xfer to the free list */
1422 hlist_add_head(&xfer->node, &info->free_xfers);
1425 spin_lock_init(&info->xfer_lock);
1430 static int scmi_channels_max_msg_configure(struct scmi_info *sinfo)
1432 const struct scmi_desc *desc = sinfo->desc;
1434 if (!desc->ops->get_max_msg) {
1435 sinfo->tx_minfo.max_msg = desc->max_msg;
1436 sinfo->rx_minfo.max_msg = desc->max_msg;
1438 struct scmi_chan_info *base_cinfo;
1440 base_cinfo = idr_find(&sinfo->tx_idr, SCMI_PROTOCOL_BASE);
1443 sinfo->tx_minfo.max_msg = desc->ops->get_max_msg(base_cinfo);
1445 /* RX channel is optional so can be skipped */
1446 base_cinfo = idr_find(&sinfo->rx_idr, SCMI_PROTOCOL_BASE);
1448 sinfo->rx_minfo.max_msg =
1449 desc->ops->get_max_msg(base_cinfo);
1455 static int scmi_xfer_info_init(struct scmi_info *sinfo)
1459 ret = scmi_channels_max_msg_configure(sinfo);
1463 ret = __scmi_xfer_info_init(sinfo, &sinfo->tx_minfo);
1464 if (!ret && idr_find(&sinfo->rx_idr, SCMI_PROTOCOL_BASE))
1465 ret = __scmi_xfer_info_init(sinfo, &sinfo->rx_minfo);
1470 static int scmi_chan_setup(struct scmi_info *info, struct device *dev,
1471 int prot_id, bool tx)
1474 struct scmi_chan_info *cinfo;
1477 /* Transmit channel is first entry i.e. index 0 */
1479 idr = tx ? &info->tx_idr : &info->rx_idr;
1481 /* check if already allocated, used for multiple device per protocol */
1482 cinfo = idr_find(idr, prot_id);
1486 if (!info->desc->ops->chan_available(dev, idx)) {
1487 cinfo = idr_find(idr, SCMI_PROTOCOL_BASE);
1488 if (unlikely(!cinfo)) /* Possible only if platform has no Rx */
1493 cinfo = devm_kzalloc(info->dev, sizeof(*cinfo), GFP_KERNEL);
1499 ret = info->desc->ops->chan_setup(cinfo, info->dev, tx);
1504 ret = idr_alloc(idr, cinfo, prot_id, prot_id + 1, GFP_KERNEL);
1505 if (ret != prot_id) {
1506 dev_err(dev, "unable to allocate SCMI idr slot err %d\n", ret);
1510 cinfo->handle = &info->handle;
1515 scmi_txrx_setup(struct scmi_info *info, struct device *dev, int prot_id)
1517 int ret = scmi_chan_setup(info, dev, prot_id, true);
1519 if (!ret) /* Rx is optional, hence no error check */
1520 scmi_chan_setup(info, dev, prot_id, false);
1526 * scmi_get_protocol_device - Helper to get/create an SCMI device.
1528 * @np: A device node representing a valid active protocols for the referred
1530 * @info: The referred SCMI instance for which we are getting/creating this
1532 * @prot_id: The protocol ID.
1533 * @name: The device name.
1535 * Referring to the specific SCMI instance identified by @info, this helper
1536 * takes care to return a properly initialized device matching the requested
1537 * @proto_id and @name: if device was still not existent it is created as a
1538 * child of the specified SCMI instance @info and its transport properly
1539 * initialized as usual.
1541 * Return: A properly initialized scmi device, NULL otherwise.
1543 static inline struct scmi_device *
1544 scmi_get_protocol_device(struct device_node *np, struct scmi_info *info,
1545 int prot_id, const char *name)
1547 struct scmi_device *sdev;
1549 /* Already created for this parent SCMI instance ? */
1550 sdev = scmi_child_dev_find(info->dev, prot_id, name);
1554 pr_debug("Creating SCMI device (%s) for protocol %x\n", name, prot_id);
1556 sdev = scmi_device_create(np, info->dev, prot_id, name);
1558 dev_err(info->dev, "failed to create %d protocol device\n",
1563 if (scmi_txrx_setup(info, &sdev->dev, prot_id)) {
1564 dev_err(&sdev->dev, "failed to setup transport\n");
1565 scmi_device_destroy(sdev);
1573 scmi_create_protocol_device(struct device_node *np, struct scmi_info *info,
1574 int prot_id, const char *name)
1576 struct scmi_device *sdev;
1578 sdev = scmi_get_protocol_device(np, info, prot_id, name);
1582 /* setup handle now as the transport is ready */
1583 scmi_set_handle(sdev);
1587 * scmi_create_protocol_devices - Create devices for all pending requests for
1588 * this SCMI instance.
1590 * @np: The device node describing the protocol
1591 * @info: The SCMI instance descriptor
1592 * @prot_id: The protocol ID
1594 * All devices previously requested for this instance (if any) are found and
1595 * created by scanning the proper @&scmi_requested_devices entry.
1597 static void scmi_create_protocol_devices(struct device_node *np,
1598 struct scmi_info *info, int prot_id)
1600 struct list_head *phead;
1602 mutex_lock(&scmi_requested_devices_mtx);
1603 phead = idr_find(&scmi_requested_devices, prot_id);
1605 struct scmi_requested_dev *rdev;
1607 list_for_each_entry(rdev, phead, node)
1608 scmi_create_protocol_device(np, info, prot_id,
1609 rdev->id_table->name);
1611 mutex_unlock(&scmi_requested_devices_mtx);
1615 * scmi_protocol_device_request - Helper to request a device
1617 * @id_table: A protocol/name pair descriptor for the device to be created.
1619 * This helper let an SCMI driver request specific devices identified by the
1620 * @id_table to be created for each active SCMI instance.
1622 * The requested device name MUST NOT be already existent for any protocol;
1623 * at first the freshly requested @id_table is annotated in the IDR table
1624 * @scmi_requested_devices, then a matching device is created for each already
1625 * active SCMI instance. (if any)
1627 * This way the requested device is created straight-away for all the already
1628 * initialized(probed) SCMI instances (handles) and it remains also annotated
1629 * as pending creation if the requesting SCMI driver was loaded before some
1630 * SCMI instance and related transports were available: when such late instance
1631 * is probed, its probe will take care to scan the list of pending requested
1632 * devices and create those on its own (see @scmi_create_protocol_devices and
1633 * its enclosing loop)
1635 * Return: 0 on Success
1637 int scmi_protocol_device_request(const struct scmi_device_id *id_table)
1640 unsigned int id = 0;
1641 struct list_head *head, *phead = NULL;
1642 struct scmi_requested_dev *rdev;
1643 struct scmi_info *info;
1645 pr_debug("Requesting SCMI device (%s) for protocol %x\n",
1646 id_table->name, id_table->protocol_id);
1649 * Search for the matching protocol rdev list and then search
1650 * of any existent equally named device...fails if any duplicate found.
1652 mutex_lock(&scmi_requested_devices_mtx);
1653 idr_for_each_entry(&scmi_requested_devices, head, id) {
1655 /* A list found registered in the IDR is never empty */
1656 rdev = list_first_entry(head, struct scmi_requested_dev,
1658 if (rdev->id_table->protocol_id ==
1659 id_table->protocol_id)
1662 list_for_each_entry(rdev, head, node) {
1663 if (!strcmp(rdev->id_table->name, id_table->name)) {
1664 pr_err("Ignoring duplicate request [%d] %s\n",
1665 rdev->id_table->protocol_id,
1666 rdev->id_table->name);
1674 * No duplicate found for requested id_table, so let's create a new
1675 * requested device entry for this new valid request.
1677 rdev = kzalloc(sizeof(*rdev), GFP_KERNEL);
1682 rdev->id_table = id_table;
1685 * Append the new requested device table descriptor to the head of the
1686 * related protocol list, eventually creating such head if not already
1690 phead = kzalloc(sizeof(*phead), GFP_KERNEL);
1696 INIT_LIST_HEAD(phead);
1698 ret = idr_alloc(&scmi_requested_devices, (void *)phead,
1699 id_table->protocol_id,
1700 id_table->protocol_id + 1, GFP_KERNEL);
1701 if (ret != id_table->protocol_id) {
1702 pr_err("Failed to save SCMI device - ret:%d\n", ret);
1710 list_add(&rdev->node, phead);
1713 * Now effectively create and initialize the requested device for every
1714 * already initialized SCMI instance which has registered the requested
1715 * protocol as a valid active one: i.e. defined in DT and supported by
1716 * current platform FW.
1718 mutex_lock(&scmi_list_mutex);
1719 list_for_each_entry(info, &scmi_list, node) {
1720 struct device_node *child;
1722 child = idr_find(&info->active_protocols,
1723 id_table->protocol_id);
1725 struct scmi_device *sdev;
1727 sdev = scmi_get_protocol_device(child, info,
1728 id_table->protocol_id,
1730 /* Set handle if not already set: device existed */
1731 if (sdev && !sdev->handle)
1733 scmi_handle_get_from_info_unlocked(info);
1736 "Failed. SCMI protocol %d not active.\n",
1737 id_table->protocol_id);
1740 mutex_unlock(&scmi_list_mutex);
1743 mutex_unlock(&scmi_requested_devices_mtx);
1749 * scmi_protocol_device_unrequest - Helper to unrequest a device
1751 * @id_table: A protocol/name pair descriptor for the device to be unrequested.
1753 * An helper to let an SCMI driver release its request about devices; note that
1754 * devices are created and initialized once the first SCMI driver request them
1755 * but they destroyed only on SCMI core unloading/unbinding.
1757 * The current SCMI transport layer uses such devices as internal references and
1758 * as such they could be shared as same transport between multiple drivers so
1759 * that cannot be safely destroyed till the whole SCMI stack is removed.
1760 * (unless adding further burden of refcounting.)
1762 void scmi_protocol_device_unrequest(const struct scmi_device_id *id_table)
1764 struct list_head *phead;
1766 pr_debug("Unrequesting SCMI device (%s) for protocol %x\n",
1767 id_table->name, id_table->protocol_id);
1769 mutex_lock(&scmi_requested_devices_mtx);
1770 phead = idr_find(&scmi_requested_devices, id_table->protocol_id);
1772 struct scmi_requested_dev *victim, *tmp;
1774 list_for_each_entry_safe(victim, tmp, phead, node) {
1775 if (!strcmp(victim->id_table->name, id_table->name)) {
1776 list_del(&victim->node);
1782 if (list_empty(phead)) {
1783 idr_remove(&scmi_requested_devices,
1784 id_table->protocol_id);
1788 mutex_unlock(&scmi_requested_devices_mtx);
1791 static int scmi_cleanup_txrx_channels(struct scmi_info *info)
1794 struct idr *idr = &info->tx_idr;
1796 ret = idr_for_each(idr, info->desc->ops->chan_free, idr);
1797 idr_destroy(&info->tx_idr);
1799 idr = &info->rx_idr;
1800 ret = idr_for_each(idr, info->desc->ops->chan_free, idr);
1801 idr_destroy(&info->rx_idr);
1806 static int scmi_probe(struct platform_device *pdev)
1809 struct scmi_handle *handle;
1810 const struct scmi_desc *desc;
1811 struct scmi_info *info;
1812 struct device *dev = &pdev->dev;
1813 struct device_node *child, *np = dev->of_node;
1815 desc = of_device_get_match_data(dev);
1819 info = devm_kzalloc(dev, sizeof(*info), GFP_KERNEL);
1825 INIT_LIST_HEAD(&info->node);
1826 idr_init(&info->protocols);
1827 mutex_init(&info->protocols_mtx);
1828 idr_init(&info->active_protocols);
1830 platform_set_drvdata(pdev, info);
1831 idr_init(&info->tx_idr);
1832 idr_init(&info->rx_idr);
1834 handle = &info->handle;
1835 handle->dev = info->dev;
1836 handle->version = &info->version;
1837 handle->devm_protocol_get = scmi_devm_protocol_get;
1838 handle->devm_protocol_put = scmi_devm_protocol_put;
1840 if (desc->ops->link_supplier) {
1841 ret = desc->ops->link_supplier(dev);
1846 ret = scmi_txrx_setup(info, dev, SCMI_PROTOCOL_BASE);
1850 ret = scmi_xfer_info_init(info);
1852 goto clear_txrx_setup;
1854 if (scmi_notification_init(handle))
1855 dev_err(dev, "SCMI Notifications NOT available.\n");
1858 * Trigger SCMI Base protocol initialization.
1859 * It's mandatory and won't be ever released/deinit until the
1860 * SCMI stack is shutdown/unloaded as a whole.
1862 ret = scmi_protocol_acquire(handle, SCMI_PROTOCOL_BASE);
1864 dev_err(dev, "unable to communicate with SCMI\n");
1865 goto notification_exit;
1868 mutex_lock(&scmi_list_mutex);
1869 list_add_tail(&info->node, &scmi_list);
1870 mutex_unlock(&scmi_list_mutex);
1872 for_each_available_child_of_node(np, child) {
1875 if (of_property_read_u32(child, "reg", &prot_id))
1878 if (!FIELD_FIT(MSG_PROTOCOL_ID_MASK, prot_id))
1879 dev_err(dev, "Out of range protocol %d\n", prot_id);
1881 if (!scmi_is_protocol_implemented(handle, prot_id)) {
1882 dev_err(dev, "SCMI protocol %d not implemented\n",
1888 * Save this valid DT protocol descriptor amongst
1889 * @active_protocols for this SCMI instance/
1891 ret = idr_alloc(&info->active_protocols, child,
1892 prot_id, prot_id + 1, GFP_KERNEL);
1893 if (ret != prot_id) {
1894 dev_err(dev, "SCMI protocol %d already activated. Skip\n",
1900 scmi_create_protocol_devices(child, info, prot_id);
1906 scmi_notification_exit(&info->handle);
1908 scmi_cleanup_txrx_channels(info);
1912 void scmi_free_channel(struct scmi_chan_info *cinfo, struct idr *idr, int id)
1914 idr_remove(idr, id);
1917 static int scmi_remove(struct platform_device *pdev)
1920 struct scmi_info *info = platform_get_drvdata(pdev);
1921 struct device_node *child;
1923 mutex_lock(&scmi_list_mutex);
1927 list_del(&info->node);
1928 mutex_unlock(&scmi_list_mutex);
1933 scmi_notification_exit(&info->handle);
1935 mutex_lock(&info->protocols_mtx);
1936 idr_destroy(&info->protocols);
1937 mutex_unlock(&info->protocols_mtx);
1939 idr_for_each_entry(&info->active_protocols, child, id)
1941 idr_destroy(&info->active_protocols);
1943 /* Safe to free channels since no more users */
1944 return scmi_cleanup_txrx_channels(info);
1947 static ssize_t protocol_version_show(struct device *dev,
1948 struct device_attribute *attr, char *buf)
1950 struct scmi_info *info = dev_get_drvdata(dev);
1952 return sprintf(buf, "%u.%u\n", info->version.major_ver,
1953 info->version.minor_ver);
1955 static DEVICE_ATTR_RO(protocol_version);
1957 static ssize_t firmware_version_show(struct device *dev,
1958 struct device_attribute *attr, char *buf)
1960 struct scmi_info *info = dev_get_drvdata(dev);
1962 return sprintf(buf, "0x%x\n", info->version.impl_ver);
1964 static DEVICE_ATTR_RO(firmware_version);
1966 static ssize_t vendor_id_show(struct device *dev,
1967 struct device_attribute *attr, char *buf)
1969 struct scmi_info *info = dev_get_drvdata(dev);
1971 return sprintf(buf, "%s\n", info->version.vendor_id);
1973 static DEVICE_ATTR_RO(vendor_id);
1975 static ssize_t sub_vendor_id_show(struct device *dev,
1976 struct device_attribute *attr, char *buf)
1978 struct scmi_info *info = dev_get_drvdata(dev);
1980 return sprintf(buf, "%s\n", info->version.sub_vendor_id);
1982 static DEVICE_ATTR_RO(sub_vendor_id);
1984 static struct attribute *versions_attrs[] = {
1985 &dev_attr_firmware_version.attr,
1986 &dev_attr_protocol_version.attr,
1987 &dev_attr_vendor_id.attr,
1988 &dev_attr_sub_vendor_id.attr,
1991 ATTRIBUTE_GROUPS(versions);
1993 /* Each compatible listed below must have descriptor associated with it */
1994 static const struct of_device_id scmi_of_match[] = {
1995 #ifdef CONFIG_ARM_SCMI_TRANSPORT_MAILBOX
1996 { .compatible = "arm,scmi", .data = &scmi_mailbox_desc },
1998 #ifdef CONFIG_ARM_SCMI_TRANSPORT_SMC
1999 { .compatible = "arm,scmi-smc", .data = &scmi_smc_desc},
2001 #ifdef CONFIG_ARM_SCMI_TRANSPORT_VIRTIO
2002 { .compatible = "arm,scmi-virtio", .data = &scmi_virtio_desc},
2007 MODULE_DEVICE_TABLE(of, scmi_of_match);
2009 static struct platform_driver scmi_driver = {
2012 .of_match_table = scmi_of_match,
2013 .dev_groups = versions_groups,
2015 .probe = scmi_probe,
2016 .remove = scmi_remove,
2020 * __scmi_transports_setup - Common helper to call transport-specific
2021 * .init/.exit code if provided.
2023 * @init: A flag to distinguish between init and exit.
2025 * Note that, if provided, we invoke .init/.exit functions for all the
2026 * transports currently compiled in.
2028 * Return: 0 on Success.
2030 static inline int __scmi_transports_setup(bool init)
2033 const struct of_device_id *trans;
2035 for (trans = scmi_of_match; trans->data; trans++) {
2036 const struct scmi_desc *tdesc = trans->data;
2038 if ((init && !tdesc->transport_init) ||
2039 (!init && !tdesc->transport_exit))
2043 ret = tdesc->transport_init();
2045 tdesc->transport_exit();
2048 pr_err("SCMI transport %s FAILED initialization!\n",
2057 static int __init scmi_transports_init(void)
2059 return __scmi_transports_setup(true);
2062 static void __exit scmi_transports_exit(void)
2064 __scmi_transports_setup(false);
2067 static int __init scmi_driver_init(void)
2071 /* Bail out if no SCMI transport was configured */
2072 if (WARN_ON(!IS_ENABLED(CONFIG_ARM_SCMI_HAVE_TRANSPORT)))
2077 /* Initialize any compiled-in transport which provided an init/exit */
2078 ret = scmi_transports_init();
2082 scmi_base_register();
2084 scmi_clock_register();
2085 scmi_perf_register();
2086 scmi_power_register();
2087 scmi_reset_register();
2088 scmi_sensors_register();
2089 scmi_voltage_register();
2090 scmi_system_register();
2092 return platform_driver_register(&scmi_driver);
2094 subsys_initcall(scmi_driver_init);
2096 static void __exit scmi_driver_exit(void)
2098 scmi_base_unregister();
2100 scmi_clock_unregister();
2101 scmi_perf_unregister();
2102 scmi_power_unregister();
2103 scmi_reset_unregister();
2104 scmi_sensors_unregister();
2105 scmi_voltage_unregister();
2106 scmi_system_unregister();
2110 scmi_transports_exit();
2112 platform_driver_unregister(&scmi_driver);
2114 module_exit(scmi_driver_exit);
2116 MODULE_ALIAS("platform:arm-scmi");
2117 MODULE_AUTHOR("Sudeep Holla <sudeep.holla@arm.com>");
2118 MODULE_DESCRIPTION("ARM SCMI protocol driver");
2119 MODULE_LICENSE("GPL v2");