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-2024 ARM Ltd.
17 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
19 #include <linux/bitmap.h>
20 #include <linux/debugfs.h>
21 #include <linux/device.h>
22 #include <linux/export.h>
23 #include <linux/idr.h>
25 #include <linux/io-64-nonatomic-hi-lo.h>
26 #include <linux/kernel.h>
27 #include <linux/kmod.h>
28 #include <linux/ktime.h>
29 #include <linux/hashtable.h>
30 #include <linux/list.h>
31 #include <linux/module.h>
33 #include <linux/platform_device.h>
34 #include <linux/processor.h>
35 #include <linux/refcount.h>
36 #include <linux/slab.h>
37 #include <linux/xarray.h>
44 #define CREATE_TRACE_POINTS
45 #include <trace/events/scmi.h>
47 #define SCMI_VENDOR_MODULE_ALIAS_FMT "scmi-protocol-0x%02x-%s"
49 static DEFINE_IDA(scmi_id);
51 static DEFINE_XARRAY(scmi_protocols);
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 struct dentry *scmi_top_dentry;
63 * struct scmi_xfers_info - Structure to manage transfer information
65 * @xfer_alloc_table: Bitmap table for allocated messages.
66 * Index of this bitmap table is also used for message
67 * sequence identifier.
68 * @xfer_lock: Protection for message allocation
69 * @max_msg: Maximum number of messages that can be pending
70 * @free_xfers: A free list for available to use xfers. It is initialized with
71 * a number of xfers equal to the maximum allowed in-flight
73 * @pending_xfers: An hashtable, indexed by msg_hdr.seq, used to keep all the
74 * currently in-flight messages.
76 struct scmi_xfers_info {
77 unsigned long *xfer_alloc_table;
80 struct hlist_head free_xfers;
81 DECLARE_HASHTABLE(pending_xfers, SCMI_PENDING_XFERS_HT_ORDER_SZ);
85 * struct scmi_protocol_instance - Describe an initialized protocol instance.
86 * @handle: Reference to the SCMI handle associated to this protocol instance.
87 * @proto: A reference to the protocol descriptor.
88 * @gid: A reference for per-protocol devres management.
89 * @users: A refcount to track effective users of this protocol.
90 * @priv: Reference for optional protocol private data.
91 * @version: Protocol version supported by the platform as detected at runtime.
92 * @negotiated_version: When the platform supports a newer protocol version,
93 * the agent will try to negotiate with the platform the
94 * usage of the newest version known to it, since
95 * backward compatibility is NOT automatically assured.
96 * This field is NON-zero when a successful negotiation
98 * @ph: An embedded protocol handle that will be passed down to protocol
99 * initialization code to identify this instance.
101 * Each protocol is initialized independently once for each SCMI platform in
102 * which is defined by DT and implemented by the SCMI server fw.
104 struct scmi_protocol_instance {
105 const struct scmi_handle *handle;
106 const struct scmi_protocol *proto;
110 unsigned int version;
111 unsigned int negotiated_version;
112 struct scmi_protocol_handle ph;
115 #define ph_to_pi(h) container_of(h, struct scmi_protocol_instance, ph)
118 * struct scmi_debug_info - Debug common info
119 * @top_dentry: A reference to the top debugfs dentry
120 * @name: Name of this SCMI instance
121 * @type: Type of this SCMI instance
122 * @is_atomic: Flag to state if the transport of this instance is atomic
123 * @counters: An array of atomic_c's used for tracking statistics (if enabled)
125 struct scmi_debug_info {
126 struct dentry *top_dentry;
130 atomic_t counters[SCMI_DEBUG_COUNTERS_LAST];
134 * struct scmi_info - Structure representing a SCMI instance
136 * @id: A sequence number starting from zero identifying this instance
137 * @dev: Device pointer
138 * @desc: SoC description for this instance
139 * @version: SCMI revision information containing protocol version,
140 * implementation version and (sub-)vendor identification.
141 * @handle: Instance of SCMI handle to send to clients
142 * @tx_minfo: Universal Transmit Message management info
143 * @rx_minfo: Universal Receive Message management info
144 * @tx_idr: IDR object to map protocol id to Tx channel info pointer
145 * @rx_idr: IDR object to map protocol id to Rx channel info pointer
146 * @protocols: IDR for protocols' instance descriptors initialized for
147 * this SCMI instance: populated on protocol's first attempted
149 * @protocols_mtx: A mutex to protect protocols instances initialization.
150 * @protocols_imp: List of protocols implemented, currently maximum of
151 * scmi_revision_info.num_protocols elements allocated by the
153 * @active_protocols: IDR storing device_nodes for protocols actually defined
154 * in the DT and confirmed as implemented by fw.
155 * @notify_priv: Pointer to private data structure specific to notifications.
157 * @users: Number of users of this instance
158 * @bus_nb: A notifier to listen for device bind/unbind on the scmi bus
159 * @dev_req_nb: A notifier to listen for device request/unrequest on the scmi
161 * @devreq_mtx: A mutex to serialize device creation for this SCMI instance
162 * @dbg: A pointer to debugfs related data (if any)
163 * @raw: An opaque reference handle used by SCMI Raw mode.
168 const struct scmi_desc *desc;
169 struct scmi_revision_info version;
170 struct scmi_handle handle;
171 struct scmi_xfers_info tx_minfo;
172 struct scmi_xfers_info rx_minfo;
175 struct idr protocols;
176 /* Ensure mutual exclusive access to protocols instance array */
177 struct mutex protocols_mtx;
179 struct idr active_protocols;
181 struct list_head node;
183 struct notifier_block bus_nb;
184 struct notifier_block dev_req_nb;
185 /* Serialize device creation process for this instance */
186 struct mutex devreq_mtx;
187 struct scmi_debug_info *dbg;
191 #define handle_to_scmi_info(h) container_of(h, struct scmi_info, handle)
192 #define bus_nb_to_scmi_info(nb) container_of(nb, struct scmi_info, bus_nb)
193 #define req_nb_to_scmi_info(nb) container_of(nb, struct scmi_info, dev_req_nb)
195 static void scmi_rx_callback(struct scmi_chan_info *cinfo,
196 u32 msg_hdr, void *priv);
197 static void scmi_bad_message_trace(struct scmi_chan_info *cinfo,
198 u32 msg_hdr, enum scmi_bad_msg err);
200 static struct scmi_transport_core_operations scmi_trans_core_ops = {
201 .bad_message_trace = scmi_bad_message_trace,
202 .rx_callback = scmi_rx_callback,
206 scmi_vendor_protocol_signature(unsigned int protocol_id, char *vendor_id,
207 char *sub_vendor_id, u32 impl_ver)
210 unsigned long hash = 0;
212 /* vendor_id/sub_vendor_id guaranteed <= SCMI_SHORT_NAME_MAX_SIZE */
213 signature = kasprintf(GFP_KERNEL, "%02X|%s|%s|0x%08X", protocol_id,
214 vendor_id ?: "", sub_vendor_id ?: "", impl_ver);
220 hash = partial_name_hash(tolower(*p++), hash);
221 hash = end_name_hash(hash);
229 scmi_protocol_key_calculate(int protocol_id, char *vendor_id,
230 char *sub_vendor_id, u32 impl_ver)
232 if (protocol_id < SCMI_PROTOCOL_VENDOR_BASE)
235 return scmi_vendor_protocol_signature(protocol_id, vendor_id,
236 sub_vendor_id, impl_ver);
239 static const struct scmi_protocol *
240 __scmi_vendor_protocol_lookup(int protocol_id, char *vendor_id,
241 char *sub_vendor_id, u32 impl_ver)
244 struct scmi_protocol *proto = NULL;
246 key = scmi_protocol_key_calculate(protocol_id, vendor_id,
247 sub_vendor_id, impl_ver);
249 proto = xa_load(&scmi_protocols, key);
254 static const struct scmi_protocol *
255 scmi_vendor_protocol_lookup(int protocol_id, char *vendor_id,
256 char *sub_vendor_id, u32 impl_ver)
258 const struct scmi_protocol *proto = NULL;
260 /* Searching for closest match ...*/
261 proto = __scmi_vendor_protocol_lookup(protocol_id, vendor_id,
262 sub_vendor_id, impl_ver);
266 /* Any match just on vendor/sub_vendor ? */
268 proto = __scmi_vendor_protocol_lookup(protocol_id, vendor_id,
274 /* Any match just on the vendor ? */
276 proto = __scmi_vendor_protocol_lookup(protocol_id, vendor_id,
281 static const struct scmi_protocol *
282 scmi_vendor_protocol_get(int protocol_id, struct scmi_revision_info *version)
284 const struct scmi_protocol *proto;
286 proto = scmi_vendor_protocol_lookup(protocol_id, version->vendor_id,
287 version->sub_vendor_id,
292 pr_debug("Looking for '" SCMI_VENDOR_MODULE_ALIAS_FMT "'\n",
293 protocol_id, version->vendor_id);
295 /* Note that vendor_id is mandatory for vendor protocols */
296 ret = request_module(SCMI_VENDOR_MODULE_ALIAS_FMT,
297 protocol_id, version->vendor_id);
299 pr_warn("Problem loading module for protocol 0x%x\n",
304 /* Lookup again, once modules loaded */
305 proto = scmi_vendor_protocol_lookup(protocol_id,
307 version->sub_vendor_id,
312 pr_info("Loaded SCMI Vendor Protocol 0x%x - %s %s %X\n",
313 protocol_id, proto->vendor_id ?: "",
314 proto->sub_vendor_id ?: "", proto->impl_ver);
319 static const struct scmi_protocol *
320 scmi_protocol_get(int protocol_id, struct scmi_revision_info *version)
322 const struct scmi_protocol *proto = NULL;
324 if (protocol_id < SCMI_PROTOCOL_VENDOR_BASE)
325 proto = xa_load(&scmi_protocols, protocol_id);
327 proto = scmi_vendor_protocol_get(protocol_id, version);
329 if (!proto || !try_module_get(proto->owner)) {
330 pr_warn("SCMI Protocol 0x%x not found!\n", protocol_id);
334 pr_debug("Found SCMI Protocol 0x%x\n", protocol_id);
339 static void scmi_protocol_put(const struct scmi_protocol *proto)
342 module_put(proto->owner);
345 static int scmi_vendor_protocol_check(const struct scmi_protocol *proto)
347 if (!proto->vendor_id) {
348 pr_err("missing vendor_id for protocol 0x%x\n", proto->id);
352 if (strlen(proto->vendor_id) >= SCMI_SHORT_NAME_MAX_SIZE) {
353 pr_err("malformed vendor_id for protocol 0x%x\n", proto->id);
357 if (proto->sub_vendor_id &&
358 strlen(proto->sub_vendor_id) >= SCMI_SHORT_NAME_MAX_SIZE) {
359 pr_err("malformed sub_vendor_id for protocol 0x%x\n",
367 int scmi_protocol_register(const struct scmi_protocol *proto)
373 pr_err("invalid protocol\n");
377 if (!proto->instance_init) {
378 pr_err("missing init for protocol 0x%x\n", proto->id);
382 if (proto->id >= SCMI_PROTOCOL_VENDOR_BASE &&
383 scmi_vendor_protocol_check(proto))
387 * Calculate a protocol key to register this protocol with the core;
388 * key value 0 is considered invalid.
390 key = scmi_protocol_key_calculate(proto->id, proto->vendor_id,
391 proto->sub_vendor_id,
396 ret = xa_insert(&scmi_protocols, key, (void *)proto, GFP_KERNEL);
398 pr_err("unable to allocate SCMI protocol slot for 0x%x - err %d\n",
403 pr_debug("Registered SCMI Protocol 0x%x - %s %s 0x%08X\n",
404 proto->id, proto->vendor_id, proto->sub_vendor_id,
409 EXPORT_SYMBOL_GPL(scmi_protocol_register);
411 void scmi_protocol_unregister(const struct scmi_protocol *proto)
415 key = scmi_protocol_key_calculate(proto->id, proto->vendor_id,
416 proto->sub_vendor_id,
421 xa_erase(&scmi_protocols, key);
423 pr_debug("Unregistered SCMI Protocol 0x%x\n", proto->id);
425 EXPORT_SYMBOL_GPL(scmi_protocol_unregister);
428 * scmi_create_protocol_devices - Create devices for all pending requests for
429 * this SCMI instance.
431 * @np: The device node describing the protocol
432 * @info: The SCMI instance descriptor
433 * @prot_id: The protocol ID
434 * @name: The optional name of the device to be created: if not provided this
435 * call will lead to the creation of all the devices currently requested
436 * for the specified protocol.
438 static void scmi_create_protocol_devices(struct device_node *np,
439 struct scmi_info *info,
440 int prot_id, const char *name)
442 struct scmi_device *sdev;
444 mutex_lock(&info->devreq_mtx);
445 sdev = scmi_device_create(np, info->dev, prot_id, name);
448 "failed to create device for protocol 0x%X (%s)\n",
450 mutex_unlock(&info->devreq_mtx);
453 static void scmi_destroy_protocol_devices(struct scmi_info *info,
454 int prot_id, const char *name)
456 mutex_lock(&info->devreq_mtx);
457 scmi_device_destroy(info->dev, prot_id, name);
458 mutex_unlock(&info->devreq_mtx);
461 void scmi_notification_instance_data_set(const struct scmi_handle *handle,
464 struct scmi_info *info = handle_to_scmi_info(handle);
466 info->notify_priv = priv;
467 /* Ensure updated protocol private date are visible */
471 void *scmi_notification_instance_data_get(const struct scmi_handle *handle)
473 struct scmi_info *info = handle_to_scmi_info(handle);
475 /* Ensure protocols_private_data has been updated */
477 return info->notify_priv;
481 * scmi_xfer_token_set - Reserve and set new token for the xfer at hand
483 * @minfo: Pointer to Tx/Rx Message management info based on channel type
484 * @xfer: The xfer to act upon
486 * Pick the next unused monotonically increasing token and set it into
487 * xfer->hdr.seq: picking a monotonically increasing value avoids immediate
488 * reuse of freshly completed or timed-out xfers, thus mitigating the risk
489 * of incorrect association of a late and expired xfer with a live in-flight
490 * transaction, both happening to re-use the same token identifier.
492 * Since platform is NOT required to answer our request in-order we should
493 * account for a few rare but possible scenarios:
495 * - exactly 'next_token' may be NOT available so pick xfer_id >= next_token
496 * using find_next_zero_bit() starting from candidate next_token bit
498 * - all tokens ahead upto (MSG_TOKEN_ID_MASK - 1) are used in-flight but we
499 * are plenty of free tokens at start, so try a second pass using
500 * find_next_zero_bit() and starting from 0.
508 * -----------+----------------------------------------------------------
509 * | | |X|X|X| | | | | | ... ... ... ... ... ... ... ... ... ... ...|X|X|
510 * ----------------------------------------------------------------------
514 * Out-of-order pending at start
515 * -----------------------------
517 * |- xfer_id picked, last_token fixed
518 * -----+----------------------------------------------------------------
519 * |X|X| | | | |X|X| ... ... ... ... ... ... ... ... ... ... ... ...|X| |
520 * ----------------------------------------------------------------------
525 * Out-of-order pending at end
526 * ---------------------------
528 * |- xfer_id picked, last_token fixed
529 * -----+----------------------------------------------------------------
530 * |X|X| | | | |X|X| ... ... ... ... ... ... ... ... ... ... |X|X|X||X|X|
531 * ----------------------------------------------------------------------
535 * Context: Assumes to be called with @xfer_lock already acquired.
537 * Return: 0 on Success or error
539 static int scmi_xfer_token_set(struct scmi_xfers_info *minfo,
540 struct scmi_xfer *xfer)
542 unsigned long xfer_id, next_token;
545 * Pick a candidate monotonic token in range [0, MSG_TOKEN_MAX - 1]
546 * using the pre-allocated transfer_id as a base.
547 * Note that the global transfer_id is shared across all message types
548 * so there could be holes in the allocated set of monotonic sequence
549 * numbers, but that is going to limit the effectiveness of the
550 * mitigation only in very rare limit conditions.
552 next_token = (xfer->transfer_id & (MSG_TOKEN_MAX - 1));
554 /* Pick the next available xfer_id >= next_token */
555 xfer_id = find_next_zero_bit(minfo->xfer_alloc_table,
556 MSG_TOKEN_MAX, next_token);
557 if (xfer_id == MSG_TOKEN_MAX) {
559 * After heavily out-of-order responses, there are no free
560 * tokens ahead, but only at start of xfer_alloc_table so
561 * try again from the beginning.
563 xfer_id = find_next_zero_bit(minfo->xfer_alloc_table,
566 * Something is wrong if we got here since there can be a
567 * maximum number of (MSG_TOKEN_MAX - 1) in-flight messages
568 * but we have not found any free token [0, MSG_TOKEN_MAX - 1].
570 if (WARN_ON_ONCE(xfer_id == MSG_TOKEN_MAX))
574 /* Update +/- last_token accordingly if we skipped some hole */
575 if (xfer_id != next_token)
576 atomic_add((int)(xfer_id - next_token), &transfer_last_id);
578 xfer->hdr.seq = (u16)xfer_id;
584 * scmi_xfer_token_clear - Release the token
586 * @minfo: Pointer to Tx/Rx Message management info based on channel type
587 * @xfer: The xfer to act upon
589 static inline void scmi_xfer_token_clear(struct scmi_xfers_info *minfo,
590 struct scmi_xfer *xfer)
592 clear_bit(xfer->hdr.seq, minfo->xfer_alloc_table);
596 * scmi_xfer_inflight_register_unlocked - Register the xfer as in-flight
598 * @xfer: The xfer to register
599 * @minfo: Pointer to Tx/Rx Message management info based on channel type
601 * Note that this helper assumes that the xfer to be registered as in-flight
602 * had been built using an xfer sequence number which still corresponds to a
603 * free slot in the xfer_alloc_table.
605 * Context: Assumes to be called with @xfer_lock already acquired.
608 scmi_xfer_inflight_register_unlocked(struct scmi_xfer *xfer,
609 struct scmi_xfers_info *minfo)
612 set_bit(xfer->hdr.seq, minfo->xfer_alloc_table);
613 hash_add(minfo->pending_xfers, &xfer->node, xfer->hdr.seq);
614 xfer->pending = true;
618 * scmi_xfer_inflight_register - Try to register an xfer as in-flight
620 * @xfer: The xfer to register
621 * @minfo: Pointer to Tx/Rx Message management info based on channel type
623 * Note that this helper does NOT assume anything about the sequence number
624 * that was baked into the provided xfer, so it checks at first if it can
625 * be mapped to a free slot and fails with an error if another xfer with the
626 * same sequence number is currently still registered as in-flight.
628 * Return: 0 on Success or -EBUSY if sequence number embedded in the xfer
629 * could not rbe mapped to a free slot in the xfer_alloc_table.
631 static int scmi_xfer_inflight_register(struct scmi_xfer *xfer,
632 struct scmi_xfers_info *minfo)
637 spin_lock_irqsave(&minfo->xfer_lock, flags);
638 if (!test_bit(xfer->hdr.seq, minfo->xfer_alloc_table))
639 scmi_xfer_inflight_register_unlocked(xfer, minfo);
642 spin_unlock_irqrestore(&minfo->xfer_lock, flags);
648 * scmi_xfer_raw_inflight_register - An helper to register the given xfer as in
649 * flight on the TX channel, if possible.
651 * @handle: Pointer to SCMI entity handle
652 * @xfer: The xfer to register
654 * Return: 0 on Success, error otherwise
656 int scmi_xfer_raw_inflight_register(const struct scmi_handle *handle,
657 struct scmi_xfer *xfer)
659 struct scmi_info *info = handle_to_scmi_info(handle);
661 return scmi_xfer_inflight_register(xfer, &info->tx_minfo);
665 * scmi_xfer_pending_set - Pick a proper sequence number and mark the xfer
666 * as pending in-flight
668 * @xfer: The xfer to act upon
669 * @minfo: Pointer to Tx/Rx Message management info based on channel type
671 * Return: 0 on Success or error otherwise
673 static inline int scmi_xfer_pending_set(struct scmi_xfer *xfer,
674 struct scmi_xfers_info *minfo)
679 spin_lock_irqsave(&minfo->xfer_lock, flags);
680 /* Set a new monotonic token as the xfer sequence number */
681 ret = scmi_xfer_token_set(minfo, xfer);
683 scmi_xfer_inflight_register_unlocked(xfer, minfo);
684 spin_unlock_irqrestore(&minfo->xfer_lock, flags);
690 * scmi_xfer_get() - Allocate one message
692 * @handle: Pointer to SCMI entity handle
693 * @minfo: Pointer to Tx/Rx Message management info based on channel type
695 * Helper function which is used by various message functions that are
696 * exposed to clients of this driver for allocating a message traffic event.
698 * Picks an xfer from the free list @free_xfers (if any available) and perform
699 * a basic initialization.
701 * Note that, at this point, still no sequence number is assigned to the
702 * allocated xfer, nor it is registered as a pending transaction.
704 * The successfully initialized xfer is refcounted.
706 * Context: Holds @xfer_lock while manipulating @free_xfers.
708 * Return: An initialized xfer if all went fine, else pointer error.
710 static struct scmi_xfer *scmi_xfer_get(const struct scmi_handle *handle,
711 struct scmi_xfers_info *minfo)
714 struct scmi_xfer *xfer;
716 spin_lock_irqsave(&minfo->xfer_lock, flags);
717 if (hlist_empty(&minfo->free_xfers)) {
718 spin_unlock_irqrestore(&minfo->xfer_lock, flags);
719 return ERR_PTR(-ENOMEM);
722 /* grab an xfer from the free_list */
723 xfer = hlist_entry(minfo->free_xfers.first, struct scmi_xfer, node);
724 hlist_del_init(&xfer->node);
727 * Allocate transfer_id early so that can be used also as base for
728 * monotonic sequence number generation if needed.
730 xfer->transfer_id = atomic_inc_return(&transfer_last_id);
732 refcount_set(&xfer->users, 1);
733 atomic_set(&xfer->busy, SCMI_XFER_FREE);
734 spin_unlock_irqrestore(&minfo->xfer_lock, flags);
740 * scmi_xfer_raw_get - Helper to get a bare free xfer from the TX channel
742 * @handle: Pointer to SCMI entity handle
744 * Note that xfer is taken from the TX channel structures.
746 * Return: A valid xfer on Success, or an error-pointer otherwise
748 struct scmi_xfer *scmi_xfer_raw_get(const struct scmi_handle *handle)
750 struct scmi_xfer *xfer;
751 struct scmi_info *info = handle_to_scmi_info(handle);
753 xfer = scmi_xfer_get(handle, &info->tx_minfo);
755 xfer->flags |= SCMI_XFER_FLAG_IS_RAW;
761 * scmi_xfer_raw_channel_get - Helper to get a reference to the proper channel
762 * to use for a specific protocol_id Raw transaction.
764 * @handle: Pointer to SCMI entity handle
765 * @protocol_id: Identifier of the protocol
767 * Note that in a regular SCMI stack, usually, a protocol has to be defined in
768 * the DT to have an associated channel and be usable; but in Raw mode any
769 * protocol in range is allowed, re-using the Base channel, so as to enable
770 * fuzzing on any protocol without the need of a fully compiled DT.
772 * Return: A reference to the channel to use, or an ERR_PTR
774 struct scmi_chan_info *
775 scmi_xfer_raw_channel_get(const struct scmi_handle *handle, u8 protocol_id)
777 struct scmi_chan_info *cinfo;
778 struct scmi_info *info = handle_to_scmi_info(handle);
780 cinfo = idr_find(&info->tx_idr, protocol_id);
782 if (protocol_id == SCMI_PROTOCOL_BASE)
783 return ERR_PTR(-EINVAL);
784 /* Use Base channel for protocols not defined for DT */
785 cinfo = idr_find(&info->tx_idr, SCMI_PROTOCOL_BASE);
787 return ERR_PTR(-EINVAL);
788 dev_warn_once(handle->dev,
789 "Using Base channel for protocol 0x%X\n",
797 * __scmi_xfer_put() - Release a message
799 * @minfo: Pointer to Tx/Rx Message management info based on channel type
800 * @xfer: message that was reserved by scmi_xfer_get
802 * After refcount check, possibly release an xfer, clearing the token slot,
803 * removing xfer from @pending_xfers and putting it back into free_xfers.
805 * This holds a spinlock to maintain integrity of internal data structures.
808 __scmi_xfer_put(struct scmi_xfers_info *minfo, struct scmi_xfer *xfer)
812 spin_lock_irqsave(&minfo->xfer_lock, flags);
813 if (refcount_dec_and_test(&xfer->users)) {
815 scmi_xfer_token_clear(minfo, xfer);
816 hash_del(&xfer->node);
817 xfer->pending = false;
819 hlist_add_head(&xfer->node, &minfo->free_xfers);
821 spin_unlock_irqrestore(&minfo->xfer_lock, flags);
825 * scmi_xfer_raw_put - Release an xfer that was taken by @scmi_xfer_raw_get
827 * @handle: Pointer to SCMI entity handle
828 * @xfer: A reference to the xfer to put
830 * Note that as with other xfer_put() handlers the xfer is really effectively
831 * released only if there are no more users on the system.
833 void scmi_xfer_raw_put(const struct scmi_handle *handle, struct scmi_xfer *xfer)
835 struct scmi_info *info = handle_to_scmi_info(handle);
837 xfer->flags &= ~SCMI_XFER_FLAG_IS_RAW;
838 xfer->flags &= ~SCMI_XFER_FLAG_CHAN_SET;
839 return __scmi_xfer_put(&info->tx_minfo, xfer);
843 * scmi_xfer_lookup_unlocked - Helper to lookup an xfer_id
845 * @minfo: Pointer to Tx/Rx Message management info based on channel type
846 * @xfer_id: Token ID to lookup in @pending_xfers
848 * Refcounting is untouched.
850 * Context: Assumes to be called with @xfer_lock already acquired.
852 * Return: A valid xfer on Success or error otherwise
854 static struct scmi_xfer *
855 scmi_xfer_lookup_unlocked(struct scmi_xfers_info *minfo, u16 xfer_id)
857 struct scmi_xfer *xfer = NULL;
859 if (test_bit(xfer_id, minfo->xfer_alloc_table))
860 xfer = XFER_FIND(minfo->pending_xfers, xfer_id);
862 return xfer ?: ERR_PTR(-EINVAL);
866 * scmi_bad_message_trace - A helper to trace weird messages
868 * @cinfo: A reference to the channel descriptor on which the message was
870 * @msg_hdr: Message header to track
871 * @err: A specific error code used as a status value in traces.
873 * This helper can be used to trace any kind of weird, incomplete, unexpected,
874 * timed-out message that arrives and as such, can be traced only referring to
875 * the header content, since the payload is missing/unreliable.
877 static void scmi_bad_message_trace(struct scmi_chan_info *cinfo, u32 msg_hdr,
878 enum scmi_bad_msg err)
881 struct scmi_info *info = handle_to_scmi_info(cinfo->handle);
883 switch (MSG_XTRACT_TYPE(msg_hdr)) {
884 case MSG_TYPE_COMMAND:
887 case MSG_TYPE_DELAYED_RESP:
890 case MSG_TYPE_NOTIFICATION:
898 trace_scmi_msg_dump(info->id, cinfo->id,
899 MSG_XTRACT_PROT_ID(msg_hdr),
900 MSG_XTRACT_ID(msg_hdr), tag,
901 MSG_XTRACT_TOKEN(msg_hdr), err, NULL, 0);
905 * scmi_msg_response_validate - Validate message type against state of related
908 * @cinfo: A reference to the channel descriptor.
909 * @msg_type: Message type to check
910 * @xfer: A reference to the xfer to validate against @msg_type
912 * This function checks if @msg_type is congruent with the current state of
913 * a pending @xfer; if an asynchronous delayed response is received before the
914 * related synchronous response (Out-of-Order Delayed Response) the missing
915 * synchronous response is assumed to be OK and completed, carrying on with the
916 * Delayed Response: this is done to address the case in which the underlying
917 * SCMI transport can deliver such out-of-order responses.
919 * Context: Assumes to be called with xfer->lock already acquired.
921 * Return: 0 on Success, error otherwise
923 static inline int scmi_msg_response_validate(struct scmi_chan_info *cinfo,
925 struct scmi_xfer *xfer)
928 * Even if a response was indeed expected on this slot at this point,
929 * a buggy platform could wrongly reply feeding us an unexpected
930 * delayed response we're not prepared to handle: bail-out safely
933 if (msg_type == MSG_TYPE_DELAYED_RESP && !xfer->async_done) {
935 "Delayed Response for %d not expected! Buggy F/W ?\n",
940 switch (xfer->state) {
941 case SCMI_XFER_SENT_OK:
942 if (msg_type == MSG_TYPE_DELAYED_RESP) {
944 * Delayed Response expected but delivered earlier.
945 * Assume message RESPONSE was OK and skip state.
947 xfer->hdr.status = SCMI_SUCCESS;
948 xfer->state = SCMI_XFER_RESP_OK;
949 complete(&xfer->done);
951 "Received valid OoO Delayed Response for %d\n",
955 case SCMI_XFER_RESP_OK:
956 if (msg_type != MSG_TYPE_DELAYED_RESP)
959 case SCMI_XFER_DRESP_OK:
960 /* No further message expected once in SCMI_XFER_DRESP_OK */
968 * scmi_xfer_state_update - Update xfer state
970 * @xfer: A reference to the xfer to update
971 * @msg_type: Type of message being processed.
973 * Note that this message is assumed to have been already successfully validated
974 * by @scmi_msg_response_validate(), so here we just update the state.
976 * Context: Assumes to be called on an xfer exclusively acquired using the
979 static inline void scmi_xfer_state_update(struct scmi_xfer *xfer, u8 msg_type)
981 xfer->hdr.type = msg_type;
983 /* Unknown command types were already discarded earlier */
984 if (xfer->hdr.type == MSG_TYPE_COMMAND)
985 xfer->state = SCMI_XFER_RESP_OK;
987 xfer->state = SCMI_XFER_DRESP_OK;
990 static bool scmi_xfer_acquired(struct scmi_xfer *xfer)
994 ret = atomic_cmpxchg(&xfer->busy, SCMI_XFER_FREE, SCMI_XFER_BUSY);
996 return ret == SCMI_XFER_FREE;
1000 * scmi_xfer_command_acquire - Helper to lookup and acquire a command xfer
1002 * @cinfo: A reference to the channel descriptor.
1003 * @msg_hdr: A message header to use as lookup key
1005 * When a valid xfer is found for the sequence number embedded in the provided
1006 * msg_hdr, reference counting is properly updated and exclusive access to this
1007 * xfer is granted till released with @scmi_xfer_command_release.
1009 * Return: A valid @xfer on Success or error otherwise.
1011 static inline struct scmi_xfer *
1012 scmi_xfer_command_acquire(struct scmi_chan_info *cinfo, u32 msg_hdr)
1015 unsigned long flags;
1016 struct scmi_xfer *xfer;
1017 struct scmi_info *info = handle_to_scmi_info(cinfo->handle);
1018 struct scmi_xfers_info *minfo = &info->tx_minfo;
1019 u8 msg_type = MSG_XTRACT_TYPE(msg_hdr);
1020 u16 xfer_id = MSG_XTRACT_TOKEN(msg_hdr);
1022 /* Are we even expecting this? */
1023 spin_lock_irqsave(&minfo->xfer_lock, flags);
1024 xfer = scmi_xfer_lookup_unlocked(minfo, xfer_id);
1027 "Message for %d type %d is not expected!\n",
1029 spin_unlock_irqrestore(&minfo->xfer_lock, flags);
1031 scmi_bad_message_trace(cinfo, msg_hdr, MSG_UNEXPECTED);
1032 scmi_inc_count(info->dbg->counters, ERR_MSG_UNEXPECTED);
1036 refcount_inc(&xfer->users);
1037 spin_unlock_irqrestore(&minfo->xfer_lock, flags);
1039 spin_lock_irqsave(&xfer->lock, flags);
1040 ret = scmi_msg_response_validate(cinfo, msg_type, xfer);
1042 * If a pending xfer was found which was also in a congruent state with
1043 * the received message, acquire exclusive access to it setting the busy
1045 * Spins only on the rare limit condition of concurrent reception of
1046 * RESP and DRESP for the same xfer.
1049 spin_until_cond(scmi_xfer_acquired(xfer));
1050 scmi_xfer_state_update(xfer, msg_type);
1052 spin_unlock_irqrestore(&xfer->lock, flags);
1056 "Invalid message type:%d for %d - HDR:0x%X state:%d\n",
1057 msg_type, xfer_id, msg_hdr, xfer->state);
1059 scmi_bad_message_trace(cinfo, msg_hdr, MSG_INVALID);
1060 scmi_inc_count(info->dbg->counters, ERR_MSG_INVALID);
1062 /* On error the refcount incremented above has to be dropped */
1063 __scmi_xfer_put(minfo, xfer);
1064 xfer = ERR_PTR(-EINVAL);
1070 static inline void scmi_xfer_command_release(struct scmi_info *info,
1071 struct scmi_xfer *xfer)
1073 atomic_set(&xfer->busy, SCMI_XFER_FREE);
1074 __scmi_xfer_put(&info->tx_minfo, xfer);
1077 static inline void scmi_clear_channel(struct scmi_info *info,
1078 struct scmi_chan_info *cinfo)
1080 if (!cinfo->is_p2a) {
1081 dev_warn(cinfo->dev, "Invalid clear on A2P channel !\n");
1085 if (info->desc->ops->clear_channel)
1086 info->desc->ops->clear_channel(cinfo);
1089 static void scmi_handle_notification(struct scmi_chan_info *cinfo,
1090 u32 msg_hdr, void *priv)
1092 struct scmi_xfer *xfer;
1093 struct device *dev = cinfo->dev;
1094 struct scmi_info *info = handle_to_scmi_info(cinfo->handle);
1095 struct scmi_xfers_info *minfo = &info->rx_minfo;
1098 ts = ktime_get_boottime();
1099 xfer = scmi_xfer_get(cinfo->handle, minfo);
1101 dev_err(dev, "failed to get free message slot (%ld)\n",
1104 scmi_bad_message_trace(cinfo, msg_hdr, MSG_NOMEM);
1105 scmi_inc_count(info->dbg->counters, ERR_MSG_NOMEM);
1107 scmi_clear_channel(info, cinfo);
1111 unpack_scmi_header(msg_hdr, &xfer->hdr);
1113 /* Ensure order between xfer->priv store and following ops */
1114 smp_store_mb(xfer->priv, priv);
1115 info->desc->ops->fetch_notification(cinfo, info->desc->max_msg_size,
1118 trace_scmi_msg_dump(info->id, cinfo->id, xfer->hdr.protocol_id,
1119 xfer->hdr.id, "NOTI", xfer->hdr.seq,
1120 xfer->hdr.status, xfer->rx.buf, xfer->rx.len);
1121 scmi_inc_count(info->dbg->counters, NOTIFICATION_OK);
1123 scmi_notify(cinfo->handle, xfer->hdr.protocol_id,
1124 xfer->hdr.id, xfer->rx.buf, xfer->rx.len, ts);
1126 trace_scmi_rx_done(xfer->transfer_id, xfer->hdr.id,
1127 xfer->hdr.protocol_id, xfer->hdr.seq,
1128 MSG_TYPE_NOTIFICATION);
1130 if (IS_ENABLED(CONFIG_ARM_SCMI_RAW_MODE_SUPPORT)) {
1131 xfer->hdr.seq = MSG_XTRACT_TOKEN(msg_hdr);
1132 scmi_raw_message_report(info->raw, xfer, SCMI_RAW_NOTIF_QUEUE,
1136 __scmi_xfer_put(minfo, xfer);
1138 scmi_clear_channel(info, cinfo);
1141 static void scmi_handle_response(struct scmi_chan_info *cinfo,
1142 u32 msg_hdr, void *priv)
1144 struct scmi_xfer *xfer;
1145 struct scmi_info *info = handle_to_scmi_info(cinfo->handle);
1147 xfer = scmi_xfer_command_acquire(cinfo, msg_hdr);
1149 if (IS_ENABLED(CONFIG_ARM_SCMI_RAW_MODE_SUPPORT))
1150 scmi_raw_error_report(info->raw, cinfo, msg_hdr, priv);
1152 if (MSG_XTRACT_TYPE(msg_hdr) == MSG_TYPE_DELAYED_RESP)
1153 scmi_clear_channel(info, cinfo);
1157 /* rx.len could be shrunk in the sync do_xfer, so reset to maxsz */
1158 if (xfer->hdr.type == MSG_TYPE_DELAYED_RESP)
1159 xfer->rx.len = info->desc->max_msg_size;
1162 /* Ensure order between xfer->priv store and following ops */
1163 smp_store_mb(xfer->priv, priv);
1164 info->desc->ops->fetch_response(cinfo, xfer);
1166 trace_scmi_msg_dump(info->id, cinfo->id, xfer->hdr.protocol_id,
1168 xfer->hdr.type == MSG_TYPE_DELAYED_RESP ?
1169 (!SCMI_XFER_IS_RAW(xfer) ? "DLYD" : "dlyd") :
1170 (!SCMI_XFER_IS_RAW(xfer) ? "RESP" : "resp"),
1171 xfer->hdr.seq, xfer->hdr.status,
1172 xfer->rx.buf, xfer->rx.len);
1174 trace_scmi_rx_done(xfer->transfer_id, xfer->hdr.id,
1175 xfer->hdr.protocol_id, xfer->hdr.seq,
1178 if (xfer->hdr.type == MSG_TYPE_DELAYED_RESP) {
1179 scmi_clear_channel(info, cinfo);
1180 complete(xfer->async_done);
1181 scmi_inc_count(info->dbg->counters, DELAYED_RESPONSE_OK);
1183 complete(&xfer->done);
1184 scmi_inc_count(info->dbg->counters, RESPONSE_OK);
1187 if (IS_ENABLED(CONFIG_ARM_SCMI_RAW_MODE_SUPPORT)) {
1189 * When in polling mode avoid to queue the Raw xfer on the IRQ
1190 * RX path since it will be already queued at the end of the TX
1193 if (!xfer->hdr.poll_completion)
1194 scmi_raw_message_report(info->raw, xfer,
1195 SCMI_RAW_REPLY_QUEUE,
1199 scmi_xfer_command_release(info, xfer);
1203 * scmi_rx_callback() - callback for receiving messages
1205 * @cinfo: SCMI channel info
1206 * @msg_hdr: Message header
1207 * @priv: Transport specific private data.
1209 * Processes one received message to appropriate transfer information and
1210 * signals completion of the transfer.
1212 * NOTE: This function will be invoked in IRQ context, hence should be
1213 * as optimal as possible.
1215 static void scmi_rx_callback(struct scmi_chan_info *cinfo, u32 msg_hdr,
1218 u8 msg_type = MSG_XTRACT_TYPE(msg_hdr);
1221 case MSG_TYPE_NOTIFICATION:
1222 scmi_handle_notification(cinfo, msg_hdr, priv);
1224 case MSG_TYPE_COMMAND:
1225 case MSG_TYPE_DELAYED_RESP:
1226 scmi_handle_response(cinfo, msg_hdr, priv);
1229 WARN_ONCE(1, "received unknown msg_type:%d\n", msg_type);
1230 scmi_bad_message_trace(cinfo, msg_hdr, MSG_UNKNOWN);
1236 * xfer_put() - Release a transmit message
1238 * @ph: Pointer to SCMI protocol handle
1239 * @xfer: message that was reserved by xfer_get_init
1241 static void xfer_put(const struct scmi_protocol_handle *ph,
1242 struct scmi_xfer *xfer)
1244 const struct scmi_protocol_instance *pi = ph_to_pi(ph);
1245 struct scmi_info *info = handle_to_scmi_info(pi->handle);
1247 __scmi_xfer_put(&info->tx_minfo, xfer);
1250 static bool scmi_xfer_done_no_timeout(struct scmi_chan_info *cinfo,
1251 struct scmi_xfer *xfer, ktime_t stop)
1253 struct scmi_info *info = handle_to_scmi_info(cinfo->handle);
1256 * Poll also on xfer->done so that polling can be forcibly terminated
1257 * in case of out-of-order receptions of delayed responses
1259 return info->desc->ops->poll_done(cinfo, xfer) ||
1260 try_wait_for_completion(&xfer->done) ||
1261 ktime_after(ktime_get(), stop);
1264 static int scmi_wait_for_reply(struct device *dev, const struct scmi_desc *desc,
1265 struct scmi_chan_info *cinfo,
1266 struct scmi_xfer *xfer, unsigned int timeout_ms)
1269 struct scmi_info *info = handle_to_scmi_info(cinfo->handle);
1271 if (xfer->hdr.poll_completion) {
1273 * Real polling is needed only if transport has NOT declared
1274 * itself to support synchronous commands replies.
1276 if (!desc->sync_cmds_completed_on_ret) {
1278 * Poll on xfer using transport provided .poll_done();
1279 * assumes no completion interrupt was available.
1281 ktime_t stop = ktime_add_ms(ktime_get(), timeout_ms);
1283 spin_until_cond(scmi_xfer_done_no_timeout(cinfo,
1285 if (ktime_after(ktime_get(), stop)) {
1287 "timed out in resp(caller: %pS) - polling\n",
1290 scmi_inc_count(info->dbg->counters, XFERS_RESPONSE_POLLED_TIMEOUT);
1295 unsigned long flags;
1298 * Do not fetch_response if an out-of-order delayed
1299 * response is being processed.
1301 spin_lock_irqsave(&xfer->lock, flags);
1302 if (xfer->state == SCMI_XFER_SENT_OK) {
1303 desc->ops->fetch_response(cinfo, xfer);
1304 xfer->state = SCMI_XFER_RESP_OK;
1306 spin_unlock_irqrestore(&xfer->lock, flags);
1308 /* Trace polled replies. */
1309 trace_scmi_msg_dump(info->id, cinfo->id,
1310 xfer->hdr.protocol_id, xfer->hdr.id,
1311 !SCMI_XFER_IS_RAW(xfer) ?
1313 xfer->hdr.seq, xfer->hdr.status,
1314 xfer->rx.buf, xfer->rx.len);
1315 scmi_inc_count(info->dbg->counters, RESPONSE_POLLED_OK);
1317 if (IS_ENABLED(CONFIG_ARM_SCMI_RAW_MODE_SUPPORT)) {
1318 scmi_raw_message_report(info->raw, xfer,
1319 SCMI_RAW_REPLY_QUEUE,
1324 /* And we wait for the response. */
1325 if (!wait_for_completion_timeout(&xfer->done,
1326 msecs_to_jiffies(timeout_ms))) {
1327 dev_err(dev, "timed out in resp(caller: %pS)\n",
1330 scmi_inc_count(info->dbg->counters, XFERS_RESPONSE_TIMEOUT);
1338 * scmi_wait_for_message_response - An helper to group all the possible ways of
1339 * waiting for a synchronous message response.
1341 * @cinfo: SCMI channel info
1342 * @xfer: Reference to the transfer being waited for.
1344 * Chooses waiting strategy (sleep-waiting vs busy-waiting) depending on
1345 * configuration flags like xfer->hdr.poll_completion.
1347 * Return: 0 on Success, error otherwise.
1349 static int scmi_wait_for_message_response(struct scmi_chan_info *cinfo,
1350 struct scmi_xfer *xfer)
1352 struct scmi_info *info = handle_to_scmi_info(cinfo->handle);
1353 struct device *dev = info->dev;
1355 trace_scmi_xfer_response_wait(xfer->transfer_id, xfer->hdr.id,
1356 xfer->hdr.protocol_id, xfer->hdr.seq,
1357 info->desc->max_rx_timeout_ms,
1358 xfer->hdr.poll_completion);
1360 return scmi_wait_for_reply(dev, info->desc, cinfo, xfer,
1361 info->desc->max_rx_timeout_ms);
1365 * scmi_xfer_raw_wait_for_message_response - An helper to wait for a message
1366 * reply to an xfer raw request on a specific channel for the required timeout.
1368 * @cinfo: SCMI channel info
1369 * @xfer: Reference to the transfer being waited for.
1370 * @timeout_ms: The maximum timeout in milliseconds
1372 * Return: 0 on Success, error otherwise.
1374 int scmi_xfer_raw_wait_for_message_response(struct scmi_chan_info *cinfo,
1375 struct scmi_xfer *xfer,
1376 unsigned int timeout_ms)
1379 struct scmi_info *info = handle_to_scmi_info(cinfo->handle);
1380 struct device *dev = info->dev;
1382 ret = scmi_wait_for_reply(dev, info->desc, cinfo, xfer, timeout_ms);
1384 dev_dbg(dev, "timed out in RAW response - HDR:%08X\n",
1385 pack_scmi_header(&xfer->hdr));
1391 * do_xfer() - Do one transfer
1393 * @ph: Pointer to SCMI protocol handle
1394 * @xfer: Transfer to initiate and wait for response
1396 * Return: -ETIMEDOUT in case of no response, if transmit error,
1397 * return corresponding error, else if all goes well,
1400 static int do_xfer(const struct scmi_protocol_handle *ph,
1401 struct scmi_xfer *xfer)
1404 const struct scmi_protocol_instance *pi = ph_to_pi(ph);
1405 struct scmi_info *info = handle_to_scmi_info(pi->handle);
1406 struct device *dev = info->dev;
1407 struct scmi_chan_info *cinfo;
1409 /* Check for polling request on custom command xfers at first */
1410 if (xfer->hdr.poll_completion &&
1411 !is_transport_polling_capable(info->desc)) {
1413 "Polling mode is not supported by transport.\n");
1414 scmi_inc_count(info->dbg->counters, SENT_FAIL_POLLING_UNSUPPORTED);
1418 cinfo = idr_find(&info->tx_idr, pi->proto->id);
1419 if (unlikely(!cinfo)) {
1420 scmi_inc_count(info->dbg->counters, SENT_FAIL_CHANNEL_NOT_FOUND);
1423 /* True ONLY if also supported by transport. */
1424 if (is_polling_enabled(cinfo, info->desc))
1425 xfer->hdr.poll_completion = true;
1428 * Initialise protocol id now from protocol handle to avoid it being
1429 * overridden by mistake (or malice) by the protocol code mangling with
1430 * the scmi_xfer structure prior to this.
1432 xfer->hdr.protocol_id = pi->proto->id;
1433 reinit_completion(&xfer->done);
1435 trace_scmi_xfer_begin(xfer->transfer_id, xfer->hdr.id,
1436 xfer->hdr.protocol_id, xfer->hdr.seq,
1437 xfer->hdr.poll_completion);
1439 /* Clear any stale status */
1440 xfer->hdr.status = SCMI_SUCCESS;
1441 xfer->state = SCMI_XFER_SENT_OK;
1443 * Even though spinlocking is not needed here since no race is possible
1444 * on xfer->state due to the monotonically increasing tokens allocation,
1445 * we must anyway ensure xfer->state initialization is not re-ordered
1446 * after the .send_message() to be sure that on the RX path an early
1447 * ISR calling scmi_rx_callback() cannot see an old stale xfer->state.
1451 ret = info->desc->ops->send_message(cinfo, xfer);
1453 dev_dbg(dev, "Failed to send message %d\n", ret);
1454 scmi_inc_count(info->dbg->counters, SENT_FAIL);
1458 trace_scmi_msg_dump(info->id, cinfo->id, xfer->hdr.protocol_id,
1459 xfer->hdr.id, "CMND", xfer->hdr.seq,
1460 xfer->hdr.status, xfer->tx.buf, xfer->tx.len);
1461 scmi_inc_count(info->dbg->counters, SENT_OK);
1463 ret = scmi_wait_for_message_response(cinfo, xfer);
1464 if (!ret && xfer->hdr.status) {
1465 ret = scmi_to_linux_errno(xfer->hdr.status);
1466 scmi_inc_count(info->dbg->counters, ERR_PROTOCOL);
1469 if (info->desc->ops->mark_txdone)
1470 info->desc->ops->mark_txdone(cinfo, ret, xfer);
1472 trace_scmi_xfer_end(xfer->transfer_id, xfer->hdr.id,
1473 xfer->hdr.protocol_id, xfer->hdr.seq, ret);
1478 static void reset_rx_to_maxsz(const struct scmi_protocol_handle *ph,
1479 struct scmi_xfer *xfer)
1481 const struct scmi_protocol_instance *pi = ph_to_pi(ph);
1482 struct scmi_info *info = handle_to_scmi_info(pi->handle);
1484 xfer->rx.len = info->desc->max_msg_size;
1488 * do_xfer_with_response() - Do one transfer and wait until the delayed
1489 * response is received
1491 * @ph: Pointer to SCMI protocol handle
1492 * @xfer: Transfer to initiate and wait for response
1494 * Using asynchronous commands in atomic/polling mode should be avoided since
1495 * it could cause long busy-waiting here, so ignore polling for the delayed
1496 * response and WARN if it was requested for this command transaction since
1497 * upper layers should refrain from issuing such kind of requests.
1499 * The only other option would have been to refrain from using any asynchronous
1500 * command even if made available, when an atomic transport is detected, and
1501 * instead forcibly use the synchronous version (thing that can be easily
1502 * attained at the protocol layer), but this would also have led to longer
1503 * stalls of the channel for synchronous commands and possibly timeouts.
1504 * (in other words there is usually a good reason if a platform provides an
1505 * asynchronous version of a command and we should prefer to use it...just not
1506 * when using atomic/polling mode)
1508 * Return: -ETIMEDOUT in case of no delayed response, if transmit error,
1509 * return corresponding error, else if all goes well, return 0.
1511 static int do_xfer_with_response(const struct scmi_protocol_handle *ph,
1512 struct scmi_xfer *xfer)
1514 int ret, timeout = msecs_to_jiffies(SCMI_MAX_RESPONSE_TIMEOUT);
1515 DECLARE_COMPLETION_ONSTACK(async_response);
1517 xfer->async_done = &async_response;
1520 * Delayed responses should not be polled, so an async command should
1521 * not have been used when requiring an atomic/poll context; WARN and
1522 * perform instead a sleeping wait.
1523 * (Note Async + IgnoreDelayedResponses are sent via do_xfer)
1525 WARN_ON_ONCE(xfer->hdr.poll_completion);
1527 ret = do_xfer(ph, xfer);
1529 if (!wait_for_completion_timeout(xfer->async_done, timeout)) {
1531 "timed out in delayed resp(caller: %pS)\n",
1534 } else if (xfer->hdr.status) {
1535 ret = scmi_to_linux_errno(xfer->hdr.status);
1539 xfer->async_done = NULL;
1544 * xfer_get_init() - Allocate and initialise one message for transmit
1546 * @ph: Pointer to SCMI protocol handle
1547 * @msg_id: Message identifier
1548 * @tx_size: transmit message size
1549 * @rx_size: receive message size
1550 * @p: pointer to the allocated and initialised message
1552 * This function allocates the message using @scmi_xfer_get and
1553 * initialise the header.
1555 * Return: 0 if all went fine with @p pointing to message, else
1556 * corresponding error.
1558 static int xfer_get_init(const struct scmi_protocol_handle *ph,
1559 u8 msg_id, size_t tx_size, size_t rx_size,
1560 struct scmi_xfer **p)
1563 struct scmi_xfer *xfer;
1564 const struct scmi_protocol_instance *pi = ph_to_pi(ph);
1565 struct scmi_info *info = handle_to_scmi_info(pi->handle);
1566 struct scmi_xfers_info *minfo = &info->tx_minfo;
1567 struct device *dev = info->dev;
1569 /* Ensure we have sane transfer sizes */
1570 if (rx_size > info->desc->max_msg_size ||
1571 tx_size > info->desc->max_msg_size)
1574 xfer = scmi_xfer_get(pi->handle, minfo);
1576 ret = PTR_ERR(xfer);
1577 dev_err(dev, "failed to get free message slot(%d)\n", ret);
1581 /* Pick a sequence number and register this xfer as in-flight */
1582 ret = scmi_xfer_pending_set(xfer, minfo);
1584 dev_err(pi->handle->dev,
1585 "Failed to get monotonic token %d\n", ret);
1586 __scmi_xfer_put(minfo, xfer);
1590 xfer->tx.len = tx_size;
1591 xfer->rx.len = rx_size ? : info->desc->max_msg_size;
1592 xfer->hdr.type = MSG_TYPE_COMMAND;
1593 xfer->hdr.id = msg_id;
1594 xfer->hdr.poll_completion = false;
1602 * version_get() - command to get the revision of the SCMI entity
1604 * @ph: Pointer to SCMI protocol handle
1605 * @version: Holds returned version of protocol.
1607 * Updates the SCMI information in the internal data structure.
1609 * Return: 0 if all went fine, else return appropriate error.
1611 static int version_get(const struct scmi_protocol_handle *ph, u32 *version)
1615 struct scmi_xfer *t;
1617 ret = xfer_get_init(ph, PROTOCOL_VERSION, 0, sizeof(*version), &t);
1621 ret = do_xfer(ph, t);
1623 rev_info = t->rx.buf;
1624 *version = le32_to_cpu(*rev_info);
1632 * scmi_set_protocol_priv - Set protocol specific data at init time
1634 * @ph: A reference to the protocol handle.
1635 * @priv: The private data to set.
1636 * @version: The detected protocol version for the core to register.
1638 * Return: 0 on Success
1640 static int scmi_set_protocol_priv(const struct scmi_protocol_handle *ph,
1641 void *priv, u32 version)
1643 struct scmi_protocol_instance *pi = ph_to_pi(ph);
1646 pi->version = version;
1652 * scmi_get_protocol_priv - Set protocol specific data at init time
1654 * @ph: A reference to the protocol handle.
1656 * Return: Protocol private data if any was set.
1658 static void *scmi_get_protocol_priv(const struct scmi_protocol_handle *ph)
1660 const struct scmi_protocol_instance *pi = ph_to_pi(ph);
1665 static const struct scmi_xfer_ops xfer_ops = {
1666 .version_get = version_get,
1667 .xfer_get_init = xfer_get_init,
1668 .reset_rx_to_maxsz = reset_rx_to_maxsz,
1670 .do_xfer_with_response = do_xfer_with_response,
1671 .xfer_put = xfer_put,
1674 struct scmi_msg_resp_domain_name_get {
1676 u8 name[SCMI_MAX_STR_SIZE];
1680 * scmi_common_extended_name_get - Common helper to get extended resources name
1681 * @ph: A protocol handle reference.
1682 * @cmd_id: The specific command ID to use.
1683 * @res_id: The specific resource ID to use.
1684 * @flags: A pointer to specific flags to use, if any.
1685 * @name: A pointer to the preallocated area where the retrieved name will be
1686 * stored as a NULL terminated string.
1687 * @len: The len in bytes of the @name char array.
1689 * Return: 0 on Succcess
1691 static int scmi_common_extended_name_get(const struct scmi_protocol_handle *ph,
1692 u8 cmd_id, u32 res_id, u32 *flags,
1693 char *name, size_t len)
1697 struct scmi_xfer *t;
1698 struct scmi_msg_resp_domain_name_get *resp;
1700 txlen = !flags ? sizeof(res_id) : sizeof(res_id) + sizeof(*flags);
1701 ret = ph->xops->xfer_get_init(ph, cmd_id, txlen, sizeof(*resp), &t);
1705 put_unaligned_le32(res_id, t->tx.buf);
1707 put_unaligned_le32(*flags, t->tx.buf + sizeof(res_id));
1710 ret = ph->xops->do_xfer(ph, t);
1712 strscpy(name, resp->name, len);
1714 ph->xops->xfer_put(ph, t);
1718 "Failed to get extended name - id:%u (ret:%d). Using %s\n",
1724 * scmi_common_get_max_msg_size - Get maximum message size
1725 * @ph: A protocol handle reference.
1727 * Return: Maximum message size for the current protocol.
1729 static int scmi_common_get_max_msg_size(const struct scmi_protocol_handle *ph)
1731 const struct scmi_protocol_instance *pi = ph_to_pi(ph);
1732 struct scmi_info *info = handle_to_scmi_info(pi->handle);
1734 return info->desc->max_msg_size;
1738 * struct scmi_iterator - Iterator descriptor
1739 * @msg: A reference to the message TX buffer; filled by @prepare_message with
1740 * a proper custom command payload for each multi-part command request.
1741 * @resp: A reference to the response RX buffer; used by @update_state and
1742 * @process_response to parse the multi-part replies.
1743 * @t: A reference to the underlying xfer initialized and used transparently by
1744 * the iterator internal routines.
1745 * @ph: A reference to the associated protocol handle to be used.
1746 * @ops: A reference to the custom provided iterator operations.
1747 * @state: The current iterator state; used and updated in turn by the iterators
1748 * internal routines and by the caller-provided @scmi_iterator_ops.
1749 * @priv: A reference to optional private data as provided by the caller and
1750 * passed back to the @@scmi_iterator_ops.
1752 struct scmi_iterator {
1755 struct scmi_xfer *t;
1756 const struct scmi_protocol_handle *ph;
1757 struct scmi_iterator_ops *ops;
1758 struct scmi_iterator_state state;
1762 static void *scmi_iterator_init(const struct scmi_protocol_handle *ph,
1763 struct scmi_iterator_ops *ops,
1764 unsigned int max_resources, u8 msg_id,
1765 size_t tx_size, void *priv)
1768 struct scmi_iterator *i;
1770 i = devm_kzalloc(ph->dev, sizeof(*i), GFP_KERNEL);
1772 return ERR_PTR(-ENOMEM);
1778 ret = ph->xops->xfer_get_init(ph, msg_id, tx_size, 0, &i->t);
1780 devm_kfree(ph->dev, i);
1781 return ERR_PTR(ret);
1784 i->state.max_resources = max_resources;
1785 i->msg = i->t->tx.buf;
1786 i->resp = i->t->rx.buf;
1791 static int scmi_iterator_run(void *iter)
1794 struct scmi_iterator_ops *iops;
1795 const struct scmi_protocol_handle *ph;
1796 struct scmi_iterator_state *st;
1797 struct scmi_iterator *i = iter;
1799 if (!i || !i->ops || !i->ph)
1807 iops->prepare_message(i->msg, st->desc_index, i->priv);
1808 ret = ph->xops->do_xfer(ph, i->t);
1812 st->rx_len = i->t->rx.len;
1813 ret = iops->update_state(st, i->resp, i->priv);
1817 if (st->num_returned > st->max_resources - st->desc_index) {
1819 "No. of resources can't exceed %d\n",
1825 for (st->loop_idx = 0; st->loop_idx < st->num_returned;
1827 ret = iops->process_response(ph, i->resp, st, i->priv);
1832 st->desc_index += st->num_returned;
1833 ph->xops->reset_rx_to_maxsz(ph, i->t);
1835 * check for both returned and remaining to avoid infinite
1836 * loop due to buggy firmware
1838 } while (st->num_returned && st->num_remaining);
1841 /* Finalize and destroy iterator */
1842 ph->xops->xfer_put(ph, i->t);
1843 devm_kfree(ph->dev, i);
1848 struct scmi_msg_get_fc_info {
1853 struct scmi_msg_resp_desc_fc {
1855 #define SUPPORTS_DOORBELL(x) ((x) & BIT(0))
1856 #define DOORBELL_REG_WIDTH(x) FIELD_GET(GENMASK(2, 1), (x))
1858 __le32 chan_addr_low;
1859 __le32 chan_addr_high;
1862 __le32 db_addr_high;
1863 __le32 db_set_lmask;
1864 __le32 db_set_hmask;
1865 __le32 db_preserve_lmask;
1866 __le32 db_preserve_hmask;
1870 scmi_common_fastchannel_init(const struct scmi_protocol_handle *ph,
1871 u8 describe_id, u32 message_id, u32 valid_size,
1872 u32 domain, void __iomem **p_addr,
1873 struct scmi_fc_db_info **p_db, u32 *rate_limit)
1880 struct scmi_xfer *t;
1881 struct scmi_fc_db_info *db = NULL;
1882 struct scmi_msg_get_fc_info *info;
1883 struct scmi_msg_resp_desc_fc *resp;
1884 const struct scmi_protocol_instance *pi = ph_to_pi(ph);
1891 ret = ph->xops->xfer_get_init(ph, describe_id,
1892 sizeof(*info), sizeof(*resp), &t);
1897 info->domain = cpu_to_le32(domain);
1898 info->message_id = cpu_to_le32(message_id);
1901 * Bail out on error leaving fc_info addresses zeroed; this includes
1902 * the case in which the requested domain/message_id does NOT support
1903 * fastchannels at all.
1905 ret = ph->xops->do_xfer(ph, t);
1910 flags = le32_to_cpu(resp->attr);
1911 size = le32_to_cpu(resp->chan_size);
1912 if (size != valid_size) {
1918 *rate_limit = le32_to_cpu(resp->rate_limit) & GENMASK(19, 0);
1920 phys_addr = le32_to_cpu(resp->chan_addr_low);
1921 phys_addr |= (u64)le32_to_cpu(resp->chan_addr_high) << 32;
1922 addr = devm_ioremap(ph->dev, phys_addr, size);
1924 ret = -EADDRNOTAVAIL;
1930 if (p_db && SUPPORTS_DOORBELL(flags)) {
1931 db = devm_kzalloc(ph->dev, sizeof(*db), GFP_KERNEL);
1937 size = 1 << DOORBELL_REG_WIDTH(flags);
1938 phys_addr = le32_to_cpu(resp->db_addr_low);
1939 phys_addr |= (u64)le32_to_cpu(resp->db_addr_high) << 32;
1940 addr = devm_ioremap(ph->dev, phys_addr, size);
1942 ret = -EADDRNOTAVAIL;
1948 db->set = le32_to_cpu(resp->db_set_lmask);
1949 db->set |= (u64)le32_to_cpu(resp->db_set_hmask) << 32;
1950 db->mask = le32_to_cpu(resp->db_preserve_lmask);
1951 db->mask |= (u64)le32_to_cpu(resp->db_preserve_hmask) << 32;
1956 ph->xops->xfer_put(ph, t);
1959 "Using valid FC for protocol %X [MSG_ID:%u / RES_ID:%u]\n",
1960 pi->proto->id, message_id, domain);
1965 devm_kfree(ph->dev, db);
1971 ph->xops->xfer_put(ph, t);
1975 "Failed to get FC for protocol %X [MSG_ID:%u / RES_ID:%u] - ret:%d. Using regular messaging.\n",
1976 pi->proto->id, message_id, domain, ret);
1979 #define SCMI_PROTO_FC_RING_DB(w) \
1984 val = ioread##w(db->addr) & db->mask; \
1985 iowrite##w((u##w)db->set | val, db->addr); \
1988 static void scmi_common_fastchannel_db_ring(struct scmi_fc_db_info *db)
1990 if (!db || !db->addr)
1994 SCMI_PROTO_FC_RING_DB(8);
1995 else if (db->width == 2)
1996 SCMI_PROTO_FC_RING_DB(16);
1997 else if (db->width == 4)
1998 SCMI_PROTO_FC_RING_DB(32);
1999 else /* db->width == 8 */
2001 SCMI_PROTO_FC_RING_DB(64);
2007 val = ioread64_hi_lo(db->addr) & db->mask;
2008 iowrite64_hi_lo(db->set | val, db->addr);
2014 * scmi_protocol_msg_check - Check protocol message attributes
2016 * @ph: A reference to the protocol handle.
2017 * @message_id: The ID of the message to check.
2018 * @attributes: A parameter to optionally return the retrieved message
2019 * attributes, in case of Success.
2021 * An helper to check protocol message attributes for a specific protocol
2024 * Return: 0 on SUCCESS
2026 static int scmi_protocol_msg_check(const struct scmi_protocol_handle *ph,
2027 u32 message_id, u32 *attributes)
2030 struct scmi_xfer *t;
2032 ret = xfer_get_init(ph, PROTOCOL_MESSAGE_ATTRIBUTES,
2033 sizeof(__le32), 0, &t);
2037 put_unaligned_le32(message_id, t->tx.buf);
2038 ret = do_xfer(ph, t);
2039 if (!ret && attributes)
2040 *attributes = get_unaligned_le32(t->rx.buf);
2046 static const struct scmi_proto_helpers_ops helpers_ops = {
2047 .extended_name_get = scmi_common_extended_name_get,
2048 .get_max_msg_size = scmi_common_get_max_msg_size,
2049 .iter_response_init = scmi_iterator_init,
2050 .iter_response_run = scmi_iterator_run,
2051 .protocol_msg_check = scmi_protocol_msg_check,
2052 .fastchannel_init = scmi_common_fastchannel_init,
2053 .fastchannel_db_ring = scmi_common_fastchannel_db_ring,
2057 * scmi_revision_area_get - Retrieve version memory area.
2059 * @ph: A reference to the protocol handle.
2061 * A helper to grab the version memory area reference during SCMI Base protocol
2064 * Return: A reference to the version memory area associated to the SCMI
2065 * instance underlying this protocol handle.
2067 struct scmi_revision_info *
2068 scmi_revision_area_get(const struct scmi_protocol_handle *ph)
2070 const struct scmi_protocol_instance *pi = ph_to_pi(ph);
2072 return pi->handle->version;
2076 * scmi_protocol_version_negotiate - Negotiate protocol version
2078 * @ph: A reference to the protocol handle.
2080 * An helper to negotiate a protocol version different from the latest
2081 * advertised as supported from the platform: on Success backward
2082 * compatibility is assured by the platform.
2084 * Return: 0 on Success
2086 static int scmi_protocol_version_negotiate(struct scmi_protocol_handle *ph)
2089 struct scmi_xfer *t;
2090 struct scmi_protocol_instance *pi = ph_to_pi(ph);
2092 /* At first check if NEGOTIATE_PROTOCOL_VERSION is supported ... */
2093 ret = scmi_protocol_msg_check(ph, NEGOTIATE_PROTOCOL_VERSION, NULL);
2097 /* ... then attempt protocol version negotiation */
2098 ret = xfer_get_init(ph, NEGOTIATE_PROTOCOL_VERSION,
2099 sizeof(__le32), 0, &t);
2103 put_unaligned_le32(pi->proto->supported_version, t->tx.buf);
2104 ret = do_xfer(ph, t);
2106 pi->negotiated_version = pi->proto->supported_version;
2114 * scmi_alloc_init_protocol_instance - Allocate and initialize a protocol
2115 * instance descriptor.
2116 * @info: The reference to the related SCMI instance.
2117 * @proto: The protocol descriptor.
2119 * Allocate a new protocol instance descriptor, using the provided @proto
2120 * description, against the specified SCMI instance @info, and initialize it;
2121 * all resources management is handled via a dedicated per-protocol devres
2124 * Context: Assumes to be called with @protocols_mtx already acquired.
2125 * Return: A reference to a freshly allocated and initialized protocol instance
2126 * or ERR_PTR on failure. On failure the @proto reference is at first
2127 * put using @scmi_protocol_put() before releasing all the devres group.
2129 static struct scmi_protocol_instance *
2130 scmi_alloc_init_protocol_instance(struct scmi_info *info,
2131 const struct scmi_protocol *proto)
2135 struct scmi_protocol_instance *pi;
2136 const struct scmi_handle *handle = &info->handle;
2138 /* Protocol specific devres group */
2139 gid = devres_open_group(handle->dev, NULL, GFP_KERNEL);
2141 scmi_protocol_put(proto);
2145 pi = devm_kzalloc(handle->dev, sizeof(*pi), GFP_KERNEL);
2151 pi->handle = handle;
2152 pi->ph.dev = handle->dev;
2153 pi->ph.xops = &xfer_ops;
2154 pi->ph.hops = &helpers_ops;
2155 pi->ph.set_priv = scmi_set_protocol_priv;
2156 pi->ph.get_priv = scmi_get_protocol_priv;
2157 refcount_set(&pi->users, 1);
2158 /* proto->init is assured NON NULL by scmi_protocol_register */
2159 ret = pi->proto->instance_init(&pi->ph);
2163 ret = idr_alloc(&info->protocols, pi, proto->id, proto->id + 1,
2165 if (ret != proto->id)
2169 * Warn but ignore events registration errors since we do not want
2170 * to skip whole protocols if their notifications are messed up.
2172 if (pi->proto->events) {
2173 ret = scmi_register_protocol_events(handle, pi->proto->id,
2177 dev_warn(handle->dev,
2178 "Protocol:%X - Events Registration Failed - err:%d\n",
2179 pi->proto->id, ret);
2182 devres_close_group(handle->dev, pi->gid);
2183 dev_dbg(handle->dev, "Initialized protocol: 0x%X\n", pi->proto->id);
2185 if (pi->version > proto->supported_version) {
2186 ret = scmi_protocol_version_negotiate(&pi->ph);
2188 dev_info(handle->dev,
2189 "Protocol 0x%X successfully negotiated version 0x%X\n",
2190 proto->id, pi->negotiated_version);
2192 dev_warn(handle->dev,
2193 "Detected UNSUPPORTED higher version 0x%X for protocol 0x%X.\n",
2194 pi->version, pi->proto->id);
2195 dev_warn(handle->dev,
2196 "Trying version 0x%X. Backward compatibility is NOT assured.\n",
2197 pi->proto->supported_version);
2204 /* Take care to put the protocol module's owner before releasing all */
2205 scmi_protocol_put(proto);
2206 devres_release_group(handle->dev, gid);
2208 return ERR_PTR(ret);
2212 * scmi_get_protocol_instance - Protocol initialization helper.
2213 * @handle: A reference to the SCMI platform instance.
2214 * @protocol_id: The protocol being requested.
2216 * In case the required protocol has never been requested before for this
2217 * instance, allocate and initialize all the needed structures while handling
2218 * resource allocation with a dedicated per-protocol devres subgroup.
2220 * Return: A reference to an initialized protocol instance or error on failure:
2221 * in particular returns -EPROBE_DEFER when the desired protocol could
2224 static struct scmi_protocol_instance * __must_check
2225 scmi_get_protocol_instance(const struct scmi_handle *handle, u8 protocol_id)
2227 struct scmi_protocol_instance *pi;
2228 struct scmi_info *info = handle_to_scmi_info(handle);
2230 mutex_lock(&info->protocols_mtx);
2231 pi = idr_find(&info->protocols, protocol_id);
2234 refcount_inc(&pi->users);
2236 const struct scmi_protocol *proto;
2238 /* Fails if protocol not registered on bus */
2239 proto = scmi_protocol_get(protocol_id, &info->version);
2241 pi = scmi_alloc_init_protocol_instance(info, proto);
2243 pi = ERR_PTR(-EPROBE_DEFER);
2245 mutex_unlock(&info->protocols_mtx);
2251 * scmi_protocol_acquire - Protocol acquire
2252 * @handle: A reference to the SCMI platform instance.
2253 * @protocol_id: The protocol being requested.
2255 * Register a new user for the requested protocol on the specified SCMI
2256 * platform instance, possibly triggering its initialization on first user.
2258 * Return: 0 if protocol was acquired successfully.
2260 int scmi_protocol_acquire(const struct scmi_handle *handle, u8 protocol_id)
2262 return PTR_ERR_OR_ZERO(scmi_get_protocol_instance(handle, protocol_id));
2266 * scmi_protocol_release - Protocol de-initialization helper.
2267 * @handle: A reference to the SCMI platform instance.
2268 * @protocol_id: The protocol being requested.
2270 * Remove one user for the specified protocol and triggers de-initialization
2271 * and resources de-allocation once the last user has gone.
2273 void scmi_protocol_release(const struct scmi_handle *handle, u8 protocol_id)
2275 struct scmi_info *info = handle_to_scmi_info(handle);
2276 struct scmi_protocol_instance *pi;
2278 mutex_lock(&info->protocols_mtx);
2279 pi = idr_find(&info->protocols, protocol_id);
2283 if (refcount_dec_and_test(&pi->users)) {
2284 void *gid = pi->gid;
2286 if (pi->proto->events)
2287 scmi_deregister_protocol_events(handle, protocol_id);
2289 if (pi->proto->instance_deinit)
2290 pi->proto->instance_deinit(&pi->ph);
2292 idr_remove(&info->protocols, protocol_id);
2294 scmi_protocol_put(pi->proto);
2296 devres_release_group(handle->dev, gid);
2297 dev_dbg(handle->dev, "De-Initialized protocol: 0x%X\n",
2302 mutex_unlock(&info->protocols_mtx);
2305 void scmi_setup_protocol_implemented(const struct scmi_protocol_handle *ph,
2308 const struct scmi_protocol_instance *pi = ph_to_pi(ph);
2309 struct scmi_info *info = handle_to_scmi_info(pi->handle);
2311 info->protocols_imp = prot_imp;
2315 scmi_is_protocol_implemented(const struct scmi_handle *handle, u8 prot_id)
2318 struct scmi_info *info = handle_to_scmi_info(handle);
2319 struct scmi_revision_info *rev = handle->version;
2321 if (!info->protocols_imp)
2324 for (i = 0; i < rev->num_protocols; i++)
2325 if (info->protocols_imp[i] == prot_id)
2330 struct scmi_protocol_devres {
2331 const struct scmi_handle *handle;
2335 static void scmi_devm_release_protocol(struct device *dev, void *res)
2337 struct scmi_protocol_devres *dres = res;
2339 scmi_protocol_release(dres->handle, dres->protocol_id);
2342 static struct scmi_protocol_instance __must_check *
2343 scmi_devres_protocol_instance_get(struct scmi_device *sdev, u8 protocol_id)
2345 struct scmi_protocol_instance *pi;
2346 struct scmi_protocol_devres *dres;
2348 dres = devres_alloc(scmi_devm_release_protocol,
2349 sizeof(*dres), GFP_KERNEL);
2351 return ERR_PTR(-ENOMEM);
2353 pi = scmi_get_protocol_instance(sdev->handle, protocol_id);
2359 dres->handle = sdev->handle;
2360 dres->protocol_id = protocol_id;
2361 devres_add(&sdev->dev, dres);
2367 * scmi_devm_protocol_get - Devres managed get protocol operations and handle
2368 * @sdev: A reference to an scmi_device whose embedded struct device is to
2369 * be used for devres accounting.
2370 * @protocol_id: The protocol being requested.
2371 * @ph: A pointer reference used to pass back the associated protocol handle.
2373 * Get hold of a protocol accounting for its usage, eventually triggering its
2374 * initialization, and returning the protocol specific operations and related
2375 * protocol handle which will be used as first argument in most of the
2376 * protocols operations methods.
2377 * Being a devres based managed method, protocol hold will be automatically
2378 * released, and possibly de-initialized on last user, once the SCMI driver
2379 * owning the scmi_device is unbound from it.
2381 * Return: A reference to the requested protocol operations or error.
2382 * Must be checked for errors by caller.
2384 static const void __must_check *
2385 scmi_devm_protocol_get(struct scmi_device *sdev, u8 protocol_id,
2386 struct scmi_protocol_handle **ph)
2388 struct scmi_protocol_instance *pi;
2391 return ERR_PTR(-EINVAL);
2393 pi = scmi_devres_protocol_instance_get(sdev, protocol_id);
2399 return pi->proto->ops;
2403 * scmi_devm_protocol_acquire - Devres managed helper to get hold of a protocol
2404 * @sdev: A reference to an scmi_device whose embedded struct device is to
2405 * be used for devres accounting.
2406 * @protocol_id: The protocol being requested.
2408 * Get hold of a protocol accounting for its usage, possibly triggering its
2409 * initialization but without getting access to its protocol specific operations
2412 * Being a devres based managed method, protocol hold will be automatically
2413 * released, and possibly de-initialized on last user, once the SCMI driver
2414 * owning the scmi_device is unbound from it.
2416 * Return: 0 on SUCCESS
2418 static int __must_check scmi_devm_protocol_acquire(struct scmi_device *sdev,
2421 struct scmi_protocol_instance *pi;
2423 pi = scmi_devres_protocol_instance_get(sdev, protocol_id);
2430 static int scmi_devm_protocol_match(struct device *dev, void *res, void *data)
2432 struct scmi_protocol_devres *dres = res;
2434 if (WARN_ON(!dres || !data))
2437 return dres->protocol_id == *((u8 *)data);
2441 * scmi_devm_protocol_put - Devres managed put protocol operations and handle
2442 * @sdev: A reference to an scmi_device whose embedded struct device is to
2443 * be used for devres accounting.
2444 * @protocol_id: The protocol being requested.
2446 * Explicitly release a protocol hold previously obtained calling the above
2447 * @scmi_devm_protocol_get.
2449 static void scmi_devm_protocol_put(struct scmi_device *sdev, u8 protocol_id)
2453 ret = devres_release(&sdev->dev, scmi_devm_release_protocol,
2454 scmi_devm_protocol_match, &protocol_id);
2459 * scmi_is_transport_atomic - Method to check if underlying transport for an
2460 * SCMI instance is configured as atomic.
2462 * @handle: A reference to the SCMI platform instance.
2463 * @atomic_threshold: An optional return value for the system wide currently
2464 * configured threshold for atomic operations.
2466 * Return: True if transport is configured as atomic
2468 static bool scmi_is_transport_atomic(const struct scmi_handle *handle,
2469 unsigned int *atomic_threshold)
2472 struct scmi_info *info = handle_to_scmi_info(handle);
2474 ret = info->desc->atomic_enabled &&
2475 is_transport_polling_capable(info->desc);
2476 if (ret && atomic_threshold)
2477 *atomic_threshold = info->desc->atomic_threshold;
2483 * scmi_handle_get() - Get the SCMI handle for a device
2485 * @dev: pointer to device for which we want SCMI handle
2487 * NOTE: The function does not track individual clients of the framework
2488 * and is expected to be maintained by caller of SCMI protocol library.
2489 * scmi_handle_put must be balanced with successful scmi_handle_get
2491 * Return: pointer to handle if successful, NULL on error
2493 static struct scmi_handle *scmi_handle_get(struct device *dev)
2495 struct list_head *p;
2496 struct scmi_info *info;
2497 struct scmi_handle *handle = NULL;
2499 mutex_lock(&scmi_list_mutex);
2500 list_for_each(p, &scmi_list) {
2501 info = list_entry(p, struct scmi_info, node);
2502 if (dev->parent == info->dev) {
2504 handle = &info->handle;
2508 mutex_unlock(&scmi_list_mutex);
2514 * scmi_handle_put() - Release the handle acquired by scmi_handle_get
2516 * @handle: handle acquired by scmi_handle_get
2518 * NOTE: The function does not track individual clients of the framework
2519 * and is expected to be maintained by caller of SCMI protocol library.
2520 * scmi_handle_put must be balanced with successful scmi_handle_get
2522 * Return: 0 is successfully released
2523 * if null was passed, it returns -EINVAL;
2525 static int scmi_handle_put(const struct scmi_handle *handle)
2527 struct scmi_info *info;
2532 info = handle_to_scmi_info(handle);
2533 mutex_lock(&scmi_list_mutex);
2534 if (!WARN_ON(!info->users))
2536 mutex_unlock(&scmi_list_mutex);
2541 static void scmi_device_link_add(struct device *consumer,
2542 struct device *supplier)
2544 struct device_link *link;
2546 link = device_link_add(consumer, supplier, DL_FLAG_AUTOREMOVE_CONSUMER);
2551 static void scmi_set_handle(struct scmi_device *scmi_dev)
2553 scmi_dev->handle = scmi_handle_get(&scmi_dev->dev);
2554 if (scmi_dev->handle)
2555 scmi_device_link_add(&scmi_dev->dev, scmi_dev->handle->dev);
2558 static int __scmi_xfer_info_init(struct scmi_info *sinfo,
2559 struct scmi_xfers_info *info)
2562 struct scmi_xfer *xfer;
2563 struct device *dev = sinfo->dev;
2564 const struct scmi_desc *desc = sinfo->desc;
2566 /* Pre-allocated messages, no more than what hdr.seq can support */
2567 if (WARN_ON(!info->max_msg || info->max_msg > MSG_TOKEN_MAX)) {
2569 "Invalid maximum messages %d, not in range [1 - %lu]\n",
2570 info->max_msg, MSG_TOKEN_MAX);
2574 hash_init(info->pending_xfers);
2576 /* Allocate a bitmask sized to hold MSG_TOKEN_MAX tokens */
2577 info->xfer_alloc_table = devm_bitmap_zalloc(dev, MSG_TOKEN_MAX,
2579 if (!info->xfer_alloc_table)
2583 * Preallocate a number of xfers equal to max inflight messages,
2584 * pre-initialize the buffer pointer to pre-allocated buffers and
2585 * attach all of them to the free list
2587 INIT_HLIST_HEAD(&info->free_xfers);
2588 for (i = 0; i < info->max_msg; i++) {
2589 xfer = devm_kzalloc(dev, sizeof(*xfer), GFP_KERNEL);
2593 xfer->rx.buf = devm_kcalloc(dev, sizeof(u8), desc->max_msg_size,
2598 xfer->tx.buf = xfer->rx.buf;
2599 init_completion(&xfer->done);
2600 spin_lock_init(&xfer->lock);
2602 /* Add initialized xfer to the free list */
2603 hlist_add_head(&xfer->node, &info->free_xfers);
2606 spin_lock_init(&info->xfer_lock);
2611 static int scmi_channels_max_msg_configure(struct scmi_info *sinfo)
2613 const struct scmi_desc *desc = sinfo->desc;
2615 if (!desc->ops->get_max_msg) {
2616 sinfo->tx_minfo.max_msg = desc->max_msg;
2617 sinfo->rx_minfo.max_msg = desc->max_msg;
2619 struct scmi_chan_info *base_cinfo;
2621 base_cinfo = idr_find(&sinfo->tx_idr, SCMI_PROTOCOL_BASE);
2624 sinfo->tx_minfo.max_msg = desc->ops->get_max_msg(base_cinfo);
2626 /* RX channel is optional so can be skipped */
2627 base_cinfo = idr_find(&sinfo->rx_idr, SCMI_PROTOCOL_BASE);
2629 sinfo->rx_minfo.max_msg =
2630 desc->ops->get_max_msg(base_cinfo);
2636 static int scmi_xfer_info_init(struct scmi_info *sinfo)
2640 ret = scmi_channels_max_msg_configure(sinfo);
2644 ret = __scmi_xfer_info_init(sinfo, &sinfo->tx_minfo);
2645 if (!ret && !idr_is_empty(&sinfo->rx_idr))
2646 ret = __scmi_xfer_info_init(sinfo, &sinfo->rx_minfo);
2651 static int scmi_chan_setup(struct scmi_info *info, struct device_node *of_node,
2652 int prot_id, bool tx)
2656 struct scmi_chan_info *cinfo;
2658 struct scmi_device *tdev = NULL;
2660 /* Transmit channel is first entry i.e. index 0 */
2662 idr = tx ? &info->tx_idr : &info->rx_idr;
2664 if (!info->desc->ops->chan_available(of_node, idx)) {
2665 cinfo = idr_find(idr, SCMI_PROTOCOL_BASE);
2666 if (unlikely(!cinfo)) /* Possible only if platform has no Rx */
2671 cinfo = devm_kzalloc(info->dev, sizeof(*cinfo), GFP_KERNEL);
2675 cinfo->is_p2a = !tx;
2676 cinfo->rx_timeout_ms = info->desc->max_rx_timeout_ms;
2677 cinfo->max_msg_size = info->desc->max_msg_size;
2679 /* Create a unique name for this transport device */
2680 snprintf(name, 32, "__scmi_transport_device_%s_%02X",
2681 idx ? "rx" : "tx", prot_id);
2682 /* Create a uniquely named, dedicated transport device for this chan */
2683 tdev = scmi_device_create(of_node, info->dev, prot_id, name);
2686 "failed to create transport device (%s)\n", name);
2687 devm_kfree(info->dev, cinfo);
2690 of_node_get(of_node);
2692 cinfo->id = prot_id;
2693 cinfo->dev = &tdev->dev;
2694 ret = info->desc->ops->chan_setup(cinfo, info->dev, tx);
2696 of_node_put(of_node);
2697 scmi_device_destroy(info->dev, prot_id, name);
2698 devm_kfree(info->dev, cinfo);
2702 if (tx && is_polling_required(cinfo, info->desc)) {
2703 if (is_transport_polling_capable(info->desc))
2704 dev_info(&tdev->dev,
2705 "Enabled polling mode TX channel - prot_id:%d\n",
2708 dev_warn(&tdev->dev,
2709 "Polling mode NOT supported by transport.\n");
2713 ret = idr_alloc(idr, cinfo, prot_id, prot_id + 1, GFP_KERNEL);
2714 if (ret != prot_id) {
2716 "unable to allocate SCMI idr slot err %d\n", ret);
2717 /* Destroy channel and device only if created by this call. */
2719 of_node_put(of_node);
2720 scmi_device_destroy(info->dev, prot_id, name);
2721 devm_kfree(info->dev, cinfo);
2726 cinfo->handle = &info->handle;
2731 scmi_txrx_setup(struct scmi_info *info, struct device_node *of_node,
2734 int ret = scmi_chan_setup(info, of_node, prot_id, true);
2737 /* Rx is optional, report only memory errors */
2738 ret = scmi_chan_setup(info, of_node, prot_id, false);
2739 if (ret && ret != -ENOMEM)
2745 "failed to setup channel for protocol:0x%X\n", prot_id);
2751 * scmi_channels_setup - Helper to initialize all required channels
2753 * @info: The SCMI instance descriptor.
2755 * Initialize all the channels found described in the DT against the underlying
2756 * configured transport using custom defined dedicated devices instead of
2757 * borrowing devices from the SCMI drivers; this way channels are initialized
2758 * upfront during core SCMI stack probing and are no more coupled with SCMI
2759 * devices used by SCMI drivers.
2761 * Note that, even though a pair of TX/RX channels is associated to each
2762 * protocol defined in the DT, a distinct freshly initialized channel is
2763 * created only if the DT node for the protocol at hand describes a dedicated
2764 * channel: in all the other cases the common BASE protocol channel is reused.
2766 * Return: 0 on Success
2768 static int scmi_channels_setup(struct scmi_info *info)
2771 struct device_node *top_np = info->dev->of_node;
2773 /* Initialize a common generic channel at first */
2774 ret = scmi_txrx_setup(info, top_np, SCMI_PROTOCOL_BASE);
2778 for_each_available_child_of_node_scoped(top_np, child) {
2781 if (of_property_read_u32(child, "reg", &prot_id))
2784 if (!FIELD_FIT(MSG_PROTOCOL_ID_MASK, prot_id))
2786 "Out of range protocol %d\n", prot_id);
2788 ret = scmi_txrx_setup(info, child, prot_id);
2796 static int scmi_chan_destroy(int id, void *p, void *idr)
2798 struct scmi_chan_info *cinfo = p;
2801 struct scmi_info *info = handle_to_scmi_info(cinfo->handle);
2802 struct scmi_device *sdev = to_scmi_dev(cinfo->dev);
2804 of_node_put(cinfo->dev->of_node);
2805 scmi_device_destroy(info->dev, id, sdev->name);
2809 idr_remove(idr, id);
2814 static void scmi_cleanup_channels(struct scmi_info *info, struct idr *idr)
2816 /* At first free all channels at the transport layer ... */
2817 idr_for_each(idr, info->desc->ops->chan_free, idr);
2819 /* ...then destroy all underlying devices */
2820 idr_for_each(idr, scmi_chan_destroy, idr);
2825 static void scmi_cleanup_txrx_channels(struct scmi_info *info)
2827 scmi_cleanup_channels(info, &info->tx_idr);
2829 scmi_cleanup_channels(info, &info->rx_idr);
2832 static int scmi_bus_notifier(struct notifier_block *nb,
2833 unsigned long action, void *data)
2835 struct scmi_info *info = bus_nb_to_scmi_info(nb);
2836 struct scmi_device *sdev = to_scmi_dev(data);
2838 /* Skip transport devices and devices of different SCMI instances */
2839 if (!strncmp(sdev->name, "__scmi_transport_device", 23) ||
2840 sdev->dev.parent != info->dev)
2844 case BUS_NOTIFY_BIND_DRIVER:
2845 /* setup handle now as the transport is ready */
2846 scmi_set_handle(sdev);
2848 case BUS_NOTIFY_UNBOUND_DRIVER:
2849 scmi_handle_put(sdev->handle);
2850 sdev->handle = NULL;
2856 dev_dbg(info->dev, "Device %s (%s) is now %s\n", dev_name(&sdev->dev),
2857 sdev->name, action == BUS_NOTIFY_BIND_DRIVER ?
2858 "about to be BOUND." : "UNBOUND.");
2863 static int scmi_device_request_notifier(struct notifier_block *nb,
2864 unsigned long action, void *data)
2866 struct device_node *np;
2867 struct scmi_device_id *id_table = data;
2868 struct scmi_info *info = req_nb_to_scmi_info(nb);
2870 np = idr_find(&info->active_protocols, id_table->protocol_id);
2874 dev_dbg(info->dev, "%sRequested device (%s) for protocol 0x%x\n",
2875 action == SCMI_BUS_NOTIFY_DEVICE_REQUEST ? "" : "UN-",
2876 id_table->name, id_table->protocol_id);
2879 case SCMI_BUS_NOTIFY_DEVICE_REQUEST:
2880 scmi_create_protocol_devices(np, info, id_table->protocol_id,
2883 case SCMI_BUS_NOTIFY_DEVICE_UNREQUEST:
2884 scmi_destroy_protocol_devices(info, id_table->protocol_id,
2894 static const char * const dbg_counter_strs[] = {
2897 "sent_fail_polling_unsupported",
2898 "sent_fail_channel_not_found",
2901 "delayed_response_ok",
2902 "xfers_response_timeout",
2903 "xfers_response_polled_timeout",
2904 "response_polled_ok",
2905 "err_msg_unexpected",
2911 static ssize_t reset_all_on_write(struct file *filp, const char __user *buf,
2912 size_t count, loff_t *ppos)
2914 struct scmi_debug_info *dbg = filp->private_data;
2916 for (int i = 0; i < SCMI_DEBUG_COUNTERS_LAST; i++)
2917 atomic_set(&dbg->counters[i], 0);
2922 static const struct file_operations fops_reset_counts = {
2923 .owner = THIS_MODULE,
2924 .open = simple_open,
2925 .write = reset_all_on_write,
2928 static void scmi_debugfs_counters_setup(struct scmi_debug_info *dbg,
2929 struct dentry *trans)
2931 struct dentry *counters;
2934 counters = debugfs_create_dir("counters", trans);
2936 for (idx = 0; idx < SCMI_DEBUG_COUNTERS_LAST; idx++)
2937 debugfs_create_atomic_t(dbg_counter_strs[idx], 0600, counters,
2938 &dbg->counters[idx]);
2940 debugfs_create_file("reset", 0200, counters, dbg, &fops_reset_counts);
2943 static void scmi_debugfs_common_cleanup(void *d)
2945 struct scmi_debug_info *dbg = d;
2950 debugfs_remove_recursive(dbg->top_dentry);
2955 static struct scmi_debug_info *scmi_debugfs_common_setup(struct scmi_info *info)
2958 struct dentry *trans, *top_dentry;
2959 struct scmi_debug_info *dbg;
2960 const char *c_ptr = NULL;
2962 dbg = devm_kzalloc(info->dev, sizeof(*dbg), GFP_KERNEL);
2966 dbg->name = kstrdup(of_node_full_name(info->dev->of_node), GFP_KERNEL);
2968 devm_kfree(info->dev, dbg);
2972 of_property_read_string(info->dev->of_node, "compatible", &c_ptr);
2973 dbg->type = kstrdup(c_ptr, GFP_KERNEL);
2976 devm_kfree(info->dev, dbg);
2980 snprintf(top_dir, 16, "%d", info->id);
2981 top_dentry = debugfs_create_dir(top_dir, scmi_top_dentry);
2982 trans = debugfs_create_dir("transport", top_dentry);
2984 dbg->is_atomic = info->desc->atomic_enabled &&
2985 is_transport_polling_capable(info->desc);
2987 debugfs_create_str("instance_name", 0400, top_dentry,
2988 (char **)&dbg->name);
2990 debugfs_create_u32("atomic_threshold_us", 0400, top_dentry,
2991 (u32 *)&info->desc->atomic_threshold);
2993 debugfs_create_str("type", 0400, trans, (char **)&dbg->type);
2995 debugfs_create_bool("is_atomic", 0400, trans, &dbg->is_atomic);
2997 debugfs_create_u32("max_rx_timeout_ms", 0400, trans,
2998 (u32 *)&info->desc->max_rx_timeout_ms);
3000 debugfs_create_u32("max_msg_size", 0400, trans,
3001 (u32 *)&info->desc->max_msg_size);
3003 debugfs_create_u32("tx_max_msg", 0400, trans,
3004 (u32 *)&info->tx_minfo.max_msg);
3006 debugfs_create_u32("rx_max_msg", 0400, trans,
3007 (u32 *)&info->rx_minfo.max_msg);
3009 if (IS_ENABLED(CONFIG_ARM_SCMI_DEBUG_COUNTERS))
3010 scmi_debugfs_counters_setup(dbg, trans);
3012 dbg->top_dentry = top_dentry;
3014 if (devm_add_action_or_reset(info->dev,
3015 scmi_debugfs_common_cleanup, dbg))
3021 static int scmi_debugfs_raw_mode_setup(struct scmi_info *info)
3023 int id, num_chans = 0, ret = 0;
3024 struct scmi_chan_info *cinfo;
3025 u8 channels[SCMI_MAX_CHANNELS] = {};
3026 DECLARE_BITMAP(protos, SCMI_MAX_CHANNELS) = {};
3031 /* Enumerate all channels to collect their ids */
3032 idr_for_each_entry(&info->tx_idr, cinfo, id) {
3034 * Cannot happen, but be defensive.
3035 * Zero as num_chans is ok, warn and carry on.
3037 if (num_chans >= SCMI_MAX_CHANNELS || !cinfo) {
3039 "SCMI RAW - Error enumerating channels\n");
3043 if (!test_bit(cinfo->id, protos)) {
3044 channels[num_chans++] = cinfo->id;
3045 set_bit(cinfo->id, protos);
3049 info->raw = scmi_raw_mode_init(&info->handle, info->dbg->top_dentry,
3050 info->id, channels, num_chans,
3051 info->desc, info->tx_minfo.max_msg);
3052 if (IS_ERR(info->raw)) {
3053 dev_err(info->dev, "Failed to initialize SCMI RAW Mode !\n");
3054 ret = PTR_ERR(info->raw);
3061 static const struct scmi_desc *scmi_transport_setup(struct device *dev)
3063 struct scmi_transport *trans;
3066 trans = dev_get_platdata(dev);
3067 if (!trans || !trans->supplier || !trans->core_ops)
3070 if (!device_link_add(dev, trans->supplier, DL_FLAG_AUTOREMOVE_CONSUMER)) {
3072 "Adding link to supplier transport device failed\n");
3076 /* Provide core transport ops */
3077 *trans->core_ops = &scmi_trans_core_ops;
3079 dev_info(dev, "Using %s\n", dev_driver_string(trans->supplier));
3081 ret = of_property_read_u32(dev->of_node, "arm,max-rx-timeout-ms",
3082 &trans->desc.max_rx_timeout_ms);
3083 if (ret && ret != -EINVAL)
3084 dev_err(dev, "Malformed arm,max-rx-timeout-ms DT property.\n");
3086 ret = of_property_read_u32(dev->of_node, "arm,max-msg-size",
3087 &trans->desc.max_msg_size);
3088 if (ret && ret != -EINVAL)
3089 dev_err(dev, "Malformed arm,max-msg-size DT property.\n");
3091 ret = of_property_read_u32(dev->of_node, "arm,max-msg",
3092 &trans->desc.max_msg);
3093 if (ret && ret != -EINVAL)
3094 dev_err(dev, "Malformed arm,max-msg DT property.\n");
3097 "SCMI max-rx-timeout: %dms / max-msg-size: %dbytes / max-msg: %d\n",
3098 trans->desc.max_rx_timeout_ms, trans->desc.max_msg_size,
3099 trans->desc.max_msg);
3101 /* System wide atomic threshold for atomic ops .. if any */
3102 if (!of_property_read_u32(dev->of_node, "atomic-threshold-us",
3103 &trans->desc.atomic_threshold))
3105 "SCMI System wide atomic threshold set to %u us\n",
3106 trans->desc.atomic_threshold);
3108 return &trans->desc;
3111 static int scmi_probe(struct platform_device *pdev)
3114 char *err_str = "probe failure\n";
3115 struct scmi_handle *handle;
3116 const struct scmi_desc *desc;
3117 struct scmi_info *info;
3118 bool coex = IS_ENABLED(CONFIG_ARM_SCMI_RAW_MODE_SUPPORT_COEX);
3119 struct device *dev = &pdev->dev;
3120 struct device_node *child, *np = dev->of_node;
3122 desc = scmi_transport_setup(dev);
3124 err_str = "transport invalid\n";
3129 info = devm_kzalloc(dev, sizeof(*info), GFP_KERNEL);
3133 info->id = ida_alloc_min(&scmi_id, 0, GFP_KERNEL);
3139 info->bus_nb.notifier_call = scmi_bus_notifier;
3140 info->dev_req_nb.notifier_call = scmi_device_request_notifier;
3141 INIT_LIST_HEAD(&info->node);
3142 idr_init(&info->protocols);
3143 mutex_init(&info->protocols_mtx);
3144 idr_init(&info->active_protocols);
3145 mutex_init(&info->devreq_mtx);
3147 platform_set_drvdata(pdev, info);
3148 idr_init(&info->tx_idr);
3149 idr_init(&info->rx_idr);
3151 handle = &info->handle;
3152 handle->dev = info->dev;
3153 handle->version = &info->version;
3154 handle->devm_protocol_acquire = scmi_devm_protocol_acquire;
3155 handle->devm_protocol_get = scmi_devm_protocol_get;
3156 handle->devm_protocol_put = scmi_devm_protocol_put;
3157 handle->is_transport_atomic = scmi_is_transport_atomic;
3159 /* Setup all channels described in the DT at first */
3160 ret = scmi_channels_setup(info);
3162 err_str = "failed to setup channels\n";
3166 ret = bus_register_notifier(&scmi_bus_type, &info->bus_nb);
3168 err_str = "failed to register bus notifier\n";
3169 goto clear_txrx_setup;
3172 ret = blocking_notifier_chain_register(&scmi_requested_devices_nh,
3175 err_str = "failed to register device notifier\n";
3176 goto clear_bus_notifier;
3179 ret = scmi_xfer_info_init(info);
3181 err_str = "failed to init xfers pool\n";
3182 goto clear_dev_req_notifier;
3185 if (scmi_top_dentry) {
3186 info->dbg = scmi_debugfs_common_setup(info);
3188 dev_warn(dev, "Failed to setup SCMI debugfs.\n");
3190 if (IS_ENABLED(CONFIG_ARM_SCMI_RAW_MODE_SUPPORT)) {
3191 ret = scmi_debugfs_raw_mode_setup(info);
3194 goto clear_dev_req_notifier;
3196 /* Bail out anyway when coex disabled. */
3200 /* Coex enabled, carry on in any case. */
3201 dev_info(dev, "SCMI RAW Mode COEX enabled !\n");
3205 if (scmi_notification_init(handle))
3206 dev_err(dev, "SCMI Notifications NOT available.\n");
3208 if (info->desc->atomic_enabled &&
3209 !is_transport_polling_capable(info->desc))
3211 "Transport is not polling capable. Atomic mode not supported.\n");
3214 * Trigger SCMI Base protocol initialization.
3215 * It's mandatory and won't be ever released/deinit until the
3216 * SCMI stack is shutdown/unloaded as a whole.
3218 ret = scmi_protocol_acquire(handle, SCMI_PROTOCOL_BASE);
3220 err_str = "unable to communicate with SCMI\n";
3222 dev_err(dev, "%s", err_str);
3225 goto notification_exit;
3228 mutex_lock(&scmi_list_mutex);
3229 list_add_tail(&info->node, &scmi_list);
3230 mutex_unlock(&scmi_list_mutex);
3232 for_each_available_child_of_node(np, child) {
3235 if (of_property_read_u32(child, "reg", &prot_id))
3238 if (!FIELD_FIT(MSG_PROTOCOL_ID_MASK, prot_id))
3239 dev_err(dev, "Out of range protocol %d\n", prot_id);
3241 if (!scmi_is_protocol_implemented(handle, prot_id)) {
3242 dev_err(dev, "SCMI protocol %d not implemented\n",
3248 * Save this valid DT protocol descriptor amongst
3249 * @active_protocols for this SCMI instance/
3251 ret = idr_alloc(&info->active_protocols, child,
3252 prot_id, prot_id + 1, GFP_KERNEL);
3253 if (ret != prot_id) {
3254 dev_err(dev, "SCMI protocol %d already activated. Skip\n",
3260 scmi_create_protocol_devices(child, info, prot_id, NULL);
3266 if (IS_ENABLED(CONFIG_ARM_SCMI_RAW_MODE_SUPPORT))
3267 scmi_raw_mode_cleanup(info->raw);
3268 scmi_notification_exit(&info->handle);
3269 clear_dev_req_notifier:
3270 blocking_notifier_chain_unregister(&scmi_requested_devices_nh,
3273 bus_unregister_notifier(&scmi_bus_type, &info->bus_nb);
3275 scmi_cleanup_txrx_channels(info);
3277 ida_free(&scmi_id, info->id);
3280 return dev_err_probe(dev, ret, "%s", err_str);
3283 static void scmi_remove(struct platform_device *pdev)
3286 struct scmi_info *info = platform_get_drvdata(pdev);
3287 struct device_node *child;
3289 if (IS_ENABLED(CONFIG_ARM_SCMI_RAW_MODE_SUPPORT))
3290 scmi_raw_mode_cleanup(info->raw);
3292 mutex_lock(&scmi_list_mutex);
3294 dev_warn(&pdev->dev,
3295 "Still active SCMI users will be forcibly unbound.\n");
3296 list_del(&info->node);
3297 mutex_unlock(&scmi_list_mutex);
3299 scmi_notification_exit(&info->handle);
3301 mutex_lock(&info->protocols_mtx);
3302 idr_destroy(&info->protocols);
3303 mutex_unlock(&info->protocols_mtx);
3305 idr_for_each_entry(&info->active_protocols, child, id)
3307 idr_destroy(&info->active_protocols);
3309 blocking_notifier_chain_unregister(&scmi_requested_devices_nh,
3311 bus_unregister_notifier(&scmi_bus_type, &info->bus_nb);
3313 /* Safe to free channels since no more users */
3314 scmi_cleanup_txrx_channels(info);
3316 ida_free(&scmi_id, info->id);
3319 static ssize_t protocol_version_show(struct device *dev,
3320 struct device_attribute *attr, char *buf)
3322 struct scmi_info *info = dev_get_drvdata(dev);
3324 return sprintf(buf, "%u.%u\n", info->version.major_ver,
3325 info->version.minor_ver);
3327 static DEVICE_ATTR_RO(protocol_version);
3329 static ssize_t firmware_version_show(struct device *dev,
3330 struct device_attribute *attr, char *buf)
3332 struct scmi_info *info = dev_get_drvdata(dev);
3334 return sprintf(buf, "0x%x\n", info->version.impl_ver);
3336 static DEVICE_ATTR_RO(firmware_version);
3338 static ssize_t vendor_id_show(struct device *dev,
3339 struct device_attribute *attr, char *buf)
3341 struct scmi_info *info = dev_get_drvdata(dev);
3343 return sprintf(buf, "%s\n", info->version.vendor_id);
3345 static DEVICE_ATTR_RO(vendor_id);
3347 static ssize_t sub_vendor_id_show(struct device *dev,
3348 struct device_attribute *attr, char *buf)
3350 struct scmi_info *info = dev_get_drvdata(dev);
3352 return sprintf(buf, "%s\n", info->version.sub_vendor_id);
3354 static DEVICE_ATTR_RO(sub_vendor_id);
3356 static struct attribute *versions_attrs[] = {
3357 &dev_attr_firmware_version.attr,
3358 &dev_attr_protocol_version.attr,
3359 &dev_attr_vendor_id.attr,
3360 &dev_attr_sub_vendor_id.attr,
3363 ATTRIBUTE_GROUPS(versions);
3365 static struct platform_driver scmi_driver = {
3368 .suppress_bind_attrs = true,
3369 .dev_groups = versions_groups,
3371 .probe = scmi_probe,
3372 .remove = scmi_remove,
3375 static struct dentry *scmi_debugfs_init(void)
3379 d = debugfs_create_dir("scmi", NULL);
3381 pr_err("Could NOT create SCMI top dentry.\n");
3388 static int __init scmi_driver_init(void)
3390 /* Bail out if no SCMI transport was configured */
3391 if (WARN_ON(!IS_ENABLED(CONFIG_ARM_SCMI_HAVE_TRANSPORT)))
3394 if (IS_ENABLED(CONFIG_ARM_SCMI_HAVE_SHMEM))
3395 scmi_trans_core_ops.shmem = scmi_shared_mem_operations_get();
3397 if (IS_ENABLED(CONFIG_ARM_SCMI_HAVE_MSG))
3398 scmi_trans_core_ops.msg = scmi_message_operations_get();
3400 if (IS_ENABLED(CONFIG_ARM_SCMI_NEED_DEBUGFS))
3401 scmi_top_dentry = scmi_debugfs_init();
3403 scmi_base_register();
3405 scmi_clock_register();
3406 scmi_perf_register();
3407 scmi_power_register();
3408 scmi_reset_register();
3409 scmi_sensors_register();
3410 scmi_voltage_register();
3411 scmi_system_register();
3412 scmi_powercap_register();
3413 scmi_pinctrl_register();
3415 return platform_driver_register(&scmi_driver);
3417 module_init(scmi_driver_init);
3419 static void __exit scmi_driver_exit(void)
3421 scmi_base_unregister();
3423 scmi_clock_unregister();
3424 scmi_perf_unregister();
3425 scmi_power_unregister();
3426 scmi_reset_unregister();
3427 scmi_sensors_unregister();
3428 scmi_voltage_unregister();
3429 scmi_system_unregister();
3430 scmi_powercap_unregister();
3431 scmi_pinctrl_unregister();
3433 platform_driver_unregister(&scmi_driver);
3435 debugfs_remove_recursive(scmi_top_dentry);
3437 module_exit(scmi_driver_exit);
3439 MODULE_ALIAS("platform:arm-scmi");
3441 MODULE_DESCRIPTION("ARM SCMI protocol driver");
3442 MODULE_LICENSE("GPL v2");