xref: /linux/drivers/firmware/arm_scmi/driver.c (revision 566ab427f827b0256d3e8ce0235d088e6a9c28bd)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * System Control and Management Interface (SCMI) Message Protocol driver
4  *
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
8  * Cortex M3 and AP.
9  *
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.
13  *
14  * Copyright (C) 2018-2024 ARM Ltd.
15  */
16 
17 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
18 
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>
24 #include <linux/io.h>
25 #include <linux/io-64-nonatomic-hi-lo.h>
26 #include <linux/kernel.h>
27 #include <linux/ktime.h>
28 #include <linux/hashtable.h>
29 #include <linux/list.h>
30 #include <linux/module.h>
31 #include <linux/of.h>
32 #include <linux/platform_device.h>
33 #include <linux/processor.h>
34 #include <linux/refcount.h>
35 #include <linux/slab.h>
36 #include <linux/xarray.h>
37 
38 #include "common.h"
39 #include "notify.h"
40 
41 #include "raw_mode.h"
42 
43 #define CREATE_TRACE_POINTS
44 #include <trace/events/scmi.h>
45 
46 static DEFINE_IDA(scmi_id);
47 
48 static DEFINE_XARRAY(scmi_protocols);
49 
50 /* List of all SCMI devices active in system */
51 static LIST_HEAD(scmi_list);
52 /* Protection for the entire list */
53 static DEFINE_MUTEX(scmi_list_mutex);
54 /* Track the unique id for the transfers for debug & profiling purpose */
55 static atomic_t transfer_last_id;
56 
57 static struct dentry *scmi_top_dentry;
58 
59 /**
60  * struct scmi_xfers_info - Structure to manage transfer information
61  *
62  * @xfer_alloc_table: Bitmap table for allocated messages.
63  *	Index of this bitmap table is also used for message
64  *	sequence identifier.
65  * @xfer_lock: Protection for message allocation
66  * @max_msg: Maximum number of messages that can be pending
67  * @free_xfers: A free list for available to use xfers. It is initialized with
68  *		a number of xfers equal to the maximum allowed in-flight
69  *		messages.
70  * @pending_xfers: An hashtable, indexed by msg_hdr.seq, used to keep all the
71  *		   currently in-flight messages.
72  */
73 struct scmi_xfers_info {
74 	unsigned long *xfer_alloc_table;
75 	spinlock_t xfer_lock;
76 	int max_msg;
77 	struct hlist_head free_xfers;
78 	DECLARE_HASHTABLE(pending_xfers, SCMI_PENDING_XFERS_HT_ORDER_SZ);
79 };
80 
81 /**
82  * struct scmi_protocol_instance  - Describe an initialized protocol instance.
83  * @handle: Reference to the SCMI handle associated to this protocol instance.
84  * @proto: A reference to the protocol descriptor.
85  * @gid: A reference for per-protocol devres management.
86  * @users: A refcount to track effective users of this protocol.
87  * @priv: Reference for optional protocol private data.
88  * @version: Protocol version supported by the platform as detected at runtime.
89  * @negotiated_version: When the platform supports a newer protocol version,
90  *			the agent will try to negotiate with the platform the
91  *			usage of the newest version known to it, since
92  *			backward compatibility is NOT automatically assured.
93  *			This field is NON-zero when a successful negotiation
94  *			has completed.
95  * @ph: An embedded protocol handle that will be passed down to protocol
96  *	initialization code to identify this instance.
97  *
98  * Each protocol is initialized independently once for each SCMI platform in
99  * which is defined by DT and implemented by the SCMI server fw.
100  */
101 struct scmi_protocol_instance {
102 	const struct scmi_handle	*handle;
103 	const struct scmi_protocol	*proto;
104 	void				*gid;
105 	refcount_t			users;
106 	void				*priv;
107 	unsigned int			version;
108 	unsigned int			negotiated_version;
109 	struct scmi_protocol_handle	ph;
110 };
111 
112 #define ph_to_pi(h)	container_of(h, struct scmi_protocol_instance, ph)
113 
114 /**
115  * struct scmi_debug_info  - Debug common info
116  * @top_dentry: A reference to the top debugfs dentry
117  * @name: Name of this SCMI instance
118  * @type: Type of this SCMI instance
119  * @is_atomic: Flag to state if the transport of this instance is atomic
120  * @counters: An array of atomic_c's used for tracking statistics (if enabled)
121  */
122 struct scmi_debug_info {
123 	struct dentry *top_dentry;
124 	const char *name;
125 	const char *type;
126 	bool is_atomic;
127 	atomic_t counters[SCMI_DEBUG_COUNTERS_LAST];
128 };
129 
130 /**
131  * struct scmi_info - Structure representing a SCMI instance
132  *
133  * @id: A sequence number starting from zero identifying this instance
134  * @dev: Device pointer
135  * @desc: SoC description for this instance
136  * @version: SCMI revision information containing protocol version,
137  *	implementation version and (sub-)vendor identification.
138  * @handle: Instance of SCMI handle to send to clients
139  * @tx_minfo: Universal Transmit Message management info
140  * @rx_minfo: Universal Receive Message management info
141  * @tx_idr: IDR object to map protocol id to Tx channel info pointer
142  * @rx_idr: IDR object to map protocol id to Rx channel info pointer
143  * @protocols: IDR for protocols' instance descriptors initialized for
144  *	       this SCMI instance: populated on protocol's first attempted
145  *	       usage.
146  * @protocols_mtx: A mutex to protect protocols instances initialization.
147  * @protocols_imp: List of protocols implemented, currently maximum of
148  *		   scmi_revision_info.num_protocols elements allocated by the
149  *		   base protocol
150  * @active_protocols: IDR storing device_nodes for protocols actually defined
151  *		      in the DT and confirmed as implemented by fw.
152  * @atomic_threshold: Optional system wide DT-configured threshold, expressed
153  *		      in microseconds, for atomic operations.
154  *		      Only SCMI synchronous commands reported by the platform
155  *		      to have an execution latency lesser-equal to the threshold
156  *		      should be considered for atomic mode operation: such
157  *		      decision is finally left up to the SCMI drivers.
158  * @notify_priv: Pointer to private data structure specific to notifications.
159  * @node: List head
160  * @users: Number of users of this instance
161  * @bus_nb: A notifier to listen for device bind/unbind on the scmi bus
162  * @dev_req_nb: A notifier to listen for device request/unrequest on the scmi
163  *		bus
164  * @devreq_mtx: A mutex to serialize device creation for this SCMI instance
165  * @dbg: A pointer to debugfs related data (if any)
166  * @raw: An opaque reference handle used by SCMI Raw mode.
167  */
168 struct scmi_info {
169 	int id;
170 	struct device *dev;
171 	const struct scmi_desc *desc;
172 	struct scmi_revision_info version;
173 	struct scmi_handle handle;
174 	struct scmi_xfers_info tx_minfo;
175 	struct scmi_xfers_info rx_minfo;
176 	struct idr tx_idr;
177 	struct idr rx_idr;
178 	struct idr protocols;
179 	/* Ensure mutual exclusive access to protocols instance array */
180 	struct mutex protocols_mtx;
181 	u8 *protocols_imp;
182 	struct idr active_protocols;
183 	unsigned int atomic_threshold;
184 	void *notify_priv;
185 	struct list_head node;
186 	int users;
187 	struct notifier_block bus_nb;
188 	struct notifier_block dev_req_nb;
189 	/* Serialize device creation process for this instance */
190 	struct mutex devreq_mtx;
191 	struct scmi_debug_info *dbg;
192 	void *raw;
193 };
194 
195 #define handle_to_scmi_info(h)	container_of(h, struct scmi_info, handle)
196 #define bus_nb_to_scmi_info(nb)	container_of(nb, struct scmi_info, bus_nb)
197 #define req_nb_to_scmi_info(nb)	container_of(nb, struct scmi_info, dev_req_nb)
198 
199 static void scmi_rx_callback(struct scmi_chan_info *cinfo,
200 			     u32 msg_hdr, void *priv);
201 static void scmi_bad_message_trace(struct scmi_chan_info *cinfo,
202 				   u32 msg_hdr, enum scmi_bad_msg err);
203 
204 static struct scmi_transport_core_operations scmi_trans_core_ops = {
205 	.bad_message_trace = scmi_bad_message_trace,
206 	.rx_callback = scmi_rx_callback,
207 };
208 
209 static unsigned long
210 scmi_vendor_protocol_signature(unsigned int protocol_id, char *vendor_id,
211 			       char *sub_vendor_id, u32 impl_ver)
212 {
213 	char *signature, *p;
214 	unsigned long hash = 0;
215 
216 	/* vendor_id/sub_vendor_id guaranteed <= SCMI_SHORT_NAME_MAX_SIZE */
217 	signature = kasprintf(GFP_KERNEL, "%02X|%s|%s|0x%08X", protocol_id,
218 			      vendor_id ?: "", sub_vendor_id ?: "", impl_ver);
219 	if (!signature)
220 		return 0;
221 
222 	p = signature;
223 	while (*p)
224 		hash = partial_name_hash(tolower(*p++), hash);
225 	hash = end_name_hash(hash);
226 
227 	kfree(signature);
228 
229 	return hash;
230 }
231 
232 static unsigned long
233 scmi_protocol_key_calculate(int protocol_id, char *vendor_id,
234 			    char *sub_vendor_id, u32 impl_ver)
235 {
236 	if (protocol_id < SCMI_PROTOCOL_VENDOR_BASE)
237 		return protocol_id;
238 	else
239 		return scmi_vendor_protocol_signature(protocol_id, vendor_id,
240 						      sub_vendor_id, impl_ver);
241 }
242 
243 static const struct scmi_protocol *
244 __scmi_vendor_protocol_lookup(int protocol_id, char *vendor_id,
245 			      char *sub_vendor_id, u32 impl_ver)
246 {
247 	unsigned long key;
248 	struct scmi_protocol *proto = NULL;
249 
250 	key = scmi_protocol_key_calculate(protocol_id, vendor_id,
251 					  sub_vendor_id, impl_ver);
252 	if (key)
253 		proto = xa_load(&scmi_protocols, key);
254 
255 	return proto;
256 }
257 
258 static const struct scmi_protocol *
259 scmi_vendor_protocol_lookup(int protocol_id, char *vendor_id,
260 			    char *sub_vendor_id, u32 impl_ver)
261 {
262 	const struct scmi_protocol *proto = NULL;
263 
264 	/* Searching for closest match ...*/
265 	proto = __scmi_vendor_protocol_lookup(protocol_id, vendor_id,
266 					      sub_vendor_id, impl_ver);
267 	if (proto)
268 		return proto;
269 
270 	/* Any match just on vendor/sub_vendor ? */
271 	if (impl_ver) {
272 		proto = __scmi_vendor_protocol_lookup(protocol_id, vendor_id,
273 						      sub_vendor_id, 0);
274 		if (proto)
275 			return proto;
276 	}
277 
278 	/* Any match just on the vendor ? */
279 	if (sub_vendor_id)
280 		proto = __scmi_vendor_protocol_lookup(protocol_id, vendor_id,
281 						      NULL, 0);
282 	return proto;
283 }
284 
285 static const struct scmi_protocol *
286 scmi_protocol_get(int protocol_id, struct scmi_revision_info *version)
287 {
288 	const struct scmi_protocol *proto = NULL;
289 
290 	if (protocol_id < SCMI_PROTOCOL_VENDOR_BASE)
291 		proto = xa_load(&scmi_protocols, protocol_id);
292 	else
293 		proto = scmi_vendor_protocol_lookup(protocol_id,
294 						    version->vendor_id,
295 						    version->sub_vendor_id,
296 						    version->impl_ver);
297 	if (!proto || !try_module_get(proto->owner)) {
298 		pr_warn("SCMI Protocol 0x%x not found!\n", protocol_id);
299 		return NULL;
300 	}
301 
302 	pr_debug("Found SCMI Protocol 0x%x\n", protocol_id);
303 
304 	if (protocol_id >= SCMI_PROTOCOL_VENDOR_BASE)
305 		pr_info("Loaded SCMI Vendor Protocol 0x%x - %s %s %X\n",
306 			protocol_id, proto->vendor_id ?: "",
307 			proto->sub_vendor_id ?: "", proto->impl_ver);
308 
309 	return proto;
310 }
311 
312 static void scmi_protocol_put(const struct scmi_protocol *proto)
313 {
314 	if (proto)
315 		module_put(proto->owner);
316 }
317 
318 static int scmi_vendor_protocol_check(const struct scmi_protocol *proto)
319 {
320 	if (!proto->vendor_id) {
321 		pr_err("missing vendor_id for protocol 0x%x\n", proto->id);
322 		return -EINVAL;
323 	}
324 
325 	if (strlen(proto->vendor_id) >= SCMI_SHORT_NAME_MAX_SIZE) {
326 		pr_err("malformed vendor_id for protocol 0x%x\n", proto->id);
327 		return -EINVAL;
328 	}
329 
330 	if (proto->sub_vendor_id &&
331 	    strlen(proto->sub_vendor_id) >= SCMI_SHORT_NAME_MAX_SIZE) {
332 		pr_err("malformed sub_vendor_id for protocol 0x%x\n",
333 		       proto->id);
334 		return -EINVAL;
335 	}
336 
337 	return 0;
338 }
339 
340 int scmi_protocol_register(const struct scmi_protocol *proto)
341 {
342 	int ret;
343 	unsigned long key;
344 
345 	if (!proto) {
346 		pr_err("invalid protocol\n");
347 		return -EINVAL;
348 	}
349 
350 	if (!proto->instance_init) {
351 		pr_err("missing init for protocol 0x%x\n", proto->id);
352 		return -EINVAL;
353 	}
354 
355 	if (proto->id >= SCMI_PROTOCOL_VENDOR_BASE &&
356 	    scmi_vendor_protocol_check(proto))
357 		return -EINVAL;
358 
359 	/*
360 	 * Calculate a protocol key to register this protocol with the core;
361 	 * key value 0 is considered invalid.
362 	 */
363 	key = scmi_protocol_key_calculate(proto->id, proto->vendor_id,
364 					  proto->sub_vendor_id,
365 					  proto->impl_ver);
366 	if (!key)
367 		return -EINVAL;
368 
369 	ret = xa_insert(&scmi_protocols, key, (void *)proto, GFP_KERNEL);
370 	if (ret) {
371 		pr_err("unable to allocate SCMI protocol slot for 0x%x - err %d\n",
372 		       proto->id, ret);
373 		return ret;
374 	}
375 
376 	pr_debug("Registered SCMI Protocol 0x%x\n", proto->id);
377 
378 	return 0;
379 }
380 EXPORT_SYMBOL_GPL(scmi_protocol_register);
381 
382 void scmi_protocol_unregister(const struct scmi_protocol *proto)
383 {
384 	unsigned long key;
385 
386 	key = scmi_protocol_key_calculate(proto->id, proto->vendor_id,
387 					  proto->sub_vendor_id,
388 					  proto->impl_ver);
389 	if (!key)
390 		return;
391 
392 	xa_erase(&scmi_protocols, key);
393 
394 	pr_debug("Unregistered SCMI Protocol 0x%x\n", proto->id);
395 }
396 EXPORT_SYMBOL_GPL(scmi_protocol_unregister);
397 
398 /**
399  * scmi_create_protocol_devices  - Create devices for all pending requests for
400  * this SCMI instance.
401  *
402  * @np: The device node describing the protocol
403  * @info: The SCMI instance descriptor
404  * @prot_id: The protocol ID
405  * @name: The optional name of the device to be created: if not provided this
406  *	  call will lead to the creation of all the devices currently requested
407  *	  for the specified protocol.
408  */
409 static void scmi_create_protocol_devices(struct device_node *np,
410 					 struct scmi_info *info,
411 					 int prot_id, const char *name)
412 {
413 	struct scmi_device *sdev;
414 
415 	mutex_lock(&info->devreq_mtx);
416 	sdev = scmi_device_create(np, info->dev, prot_id, name);
417 	if (name && !sdev)
418 		dev_err(info->dev,
419 			"failed to create device for protocol 0x%X (%s)\n",
420 			prot_id, name);
421 	mutex_unlock(&info->devreq_mtx);
422 }
423 
424 static void scmi_destroy_protocol_devices(struct scmi_info *info,
425 					  int prot_id, const char *name)
426 {
427 	mutex_lock(&info->devreq_mtx);
428 	scmi_device_destroy(info->dev, prot_id, name);
429 	mutex_unlock(&info->devreq_mtx);
430 }
431 
432 void scmi_notification_instance_data_set(const struct scmi_handle *handle,
433 					 void *priv)
434 {
435 	struct scmi_info *info = handle_to_scmi_info(handle);
436 
437 	info->notify_priv = priv;
438 	/* Ensure updated protocol private date are visible */
439 	smp_wmb();
440 }
441 
442 void *scmi_notification_instance_data_get(const struct scmi_handle *handle)
443 {
444 	struct scmi_info *info = handle_to_scmi_info(handle);
445 
446 	/* Ensure protocols_private_data has been updated */
447 	smp_rmb();
448 	return info->notify_priv;
449 }
450 
451 /**
452  * scmi_xfer_token_set  - Reserve and set new token for the xfer at hand
453  *
454  * @minfo: Pointer to Tx/Rx Message management info based on channel type
455  * @xfer: The xfer to act upon
456  *
457  * Pick the next unused monotonically increasing token and set it into
458  * xfer->hdr.seq: picking a monotonically increasing value avoids immediate
459  * reuse of freshly completed or timed-out xfers, thus mitigating the risk
460  * of incorrect association of a late and expired xfer with a live in-flight
461  * transaction, both happening to re-use the same token identifier.
462  *
463  * Since platform is NOT required to answer our request in-order we should
464  * account for a few rare but possible scenarios:
465  *
466  *  - exactly 'next_token' may be NOT available so pick xfer_id >= next_token
467  *    using find_next_zero_bit() starting from candidate next_token bit
468  *
469  *  - all tokens ahead upto (MSG_TOKEN_ID_MASK - 1) are used in-flight but we
470  *    are plenty of free tokens at start, so try a second pass using
471  *    find_next_zero_bit() and starting from 0.
472  *
473  *  X = used in-flight
474  *
475  * Normal
476  * ------
477  *
478  *		|- xfer_id picked
479  *   -----------+----------------------------------------------------------
480  *   | | |X|X|X| | | | | | ... ... ... ... ... ... ... ... ... ... ...|X|X|
481  *   ----------------------------------------------------------------------
482  *		^
483  *		|- next_token
484  *
485  * Out-of-order pending at start
486  * -----------------------------
487  *
488  *	  |- xfer_id picked, last_token fixed
489  *   -----+----------------------------------------------------------------
490  *   |X|X| | | | |X|X| ... ... ... ... ... ... ... ... ... ... ... ...|X| |
491  *   ----------------------------------------------------------------------
492  *    ^
493  *    |- next_token
494  *
495  *
496  * Out-of-order pending at end
497  * ---------------------------
498  *
499  *	  |- xfer_id picked, last_token fixed
500  *   -----+----------------------------------------------------------------
501  *   |X|X| | | | |X|X| ... ... ... ... ... ... ... ... ... ... |X|X|X||X|X|
502  *   ----------------------------------------------------------------------
503  *								^
504  *								|- next_token
505  *
506  * Context: Assumes to be called with @xfer_lock already acquired.
507  *
508  * Return: 0 on Success or error
509  */
510 static int scmi_xfer_token_set(struct scmi_xfers_info *minfo,
511 			       struct scmi_xfer *xfer)
512 {
513 	unsigned long xfer_id, next_token;
514 
515 	/*
516 	 * Pick a candidate monotonic token in range [0, MSG_TOKEN_MAX - 1]
517 	 * using the pre-allocated transfer_id as a base.
518 	 * Note that the global transfer_id is shared across all message types
519 	 * so there could be holes in the allocated set of monotonic sequence
520 	 * numbers, but that is going to limit the effectiveness of the
521 	 * mitigation only in very rare limit conditions.
522 	 */
523 	next_token = (xfer->transfer_id & (MSG_TOKEN_MAX - 1));
524 
525 	/* Pick the next available xfer_id >= next_token */
526 	xfer_id = find_next_zero_bit(minfo->xfer_alloc_table,
527 				     MSG_TOKEN_MAX, next_token);
528 	if (xfer_id == MSG_TOKEN_MAX) {
529 		/*
530 		 * After heavily out-of-order responses, there are no free
531 		 * tokens ahead, but only at start of xfer_alloc_table so
532 		 * try again from the beginning.
533 		 */
534 		xfer_id = find_next_zero_bit(minfo->xfer_alloc_table,
535 					     MSG_TOKEN_MAX, 0);
536 		/*
537 		 * Something is wrong if we got here since there can be a
538 		 * maximum number of (MSG_TOKEN_MAX - 1) in-flight messages
539 		 * but we have not found any free token [0, MSG_TOKEN_MAX - 1].
540 		 */
541 		if (WARN_ON_ONCE(xfer_id == MSG_TOKEN_MAX))
542 			return -ENOMEM;
543 	}
544 
545 	/* Update +/- last_token accordingly if we skipped some hole */
546 	if (xfer_id != next_token)
547 		atomic_add((int)(xfer_id - next_token), &transfer_last_id);
548 
549 	xfer->hdr.seq = (u16)xfer_id;
550 
551 	return 0;
552 }
553 
554 /**
555  * scmi_xfer_token_clear  - Release the token
556  *
557  * @minfo: Pointer to Tx/Rx Message management info based on channel type
558  * @xfer: The xfer to act upon
559  */
560 static inline void scmi_xfer_token_clear(struct scmi_xfers_info *minfo,
561 					 struct scmi_xfer *xfer)
562 {
563 	clear_bit(xfer->hdr.seq, minfo->xfer_alloc_table);
564 }
565 
566 /**
567  * scmi_xfer_inflight_register_unlocked  - Register the xfer as in-flight
568  *
569  * @xfer: The xfer to register
570  * @minfo: Pointer to Tx/Rx Message management info based on channel type
571  *
572  * Note that this helper assumes that the xfer to be registered as in-flight
573  * had been built using an xfer sequence number which still corresponds to a
574  * free slot in the xfer_alloc_table.
575  *
576  * Context: Assumes to be called with @xfer_lock already acquired.
577  */
578 static inline void
579 scmi_xfer_inflight_register_unlocked(struct scmi_xfer *xfer,
580 				     struct scmi_xfers_info *minfo)
581 {
582 	/* Set in-flight */
583 	set_bit(xfer->hdr.seq, minfo->xfer_alloc_table);
584 	hash_add(minfo->pending_xfers, &xfer->node, xfer->hdr.seq);
585 	xfer->pending = true;
586 }
587 
588 /**
589  * scmi_xfer_inflight_register  - Try to register an xfer as in-flight
590  *
591  * @xfer: The xfer to register
592  * @minfo: Pointer to Tx/Rx Message management info based on channel type
593  *
594  * Note that this helper does NOT assume anything about the sequence number
595  * that was baked into the provided xfer, so it checks at first if it can
596  * be mapped to a free slot and fails with an error if another xfer with the
597  * same sequence number is currently still registered as in-flight.
598  *
599  * Return: 0 on Success or -EBUSY if sequence number embedded in the xfer
600  *	   could not rbe mapped to a free slot in the xfer_alloc_table.
601  */
602 static int scmi_xfer_inflight_register(struct scmi_xfer *xfer,
603 				       struct scmi_xfers_info *minfo)
604 {
605 	int ret = 0;
606 	unsigned long flags;
607 
608 	spin_lock_irqsave(&minfo->xfer_lock, flags);
609 	if (!test_bit(xfer->hdr.seq, minfo->xfer_alloc_table))
610 		scmi_xfer_inflight_register_unlocked(xfer, minfo);
611 	else
612 		ret = -EBUSY;
613 	spin_unlock_irqrestore(&minfo->xfer_lock, flags);
614 
615 	return ret;
616 }
617 
618 /**
619  * scmi_xfer_raw_inflight_register  - An helper to register the given xfer as in
620  * flight on the TX channel, if possible.
621  *
622  * @handle: Pointer to SCMI entity handle
623  * @xfer: The xfer to register
624  *
625  * Return: 0 on Success, error otherwise
626  */
627 int scmi_xfer_raw_inflight_register(const struct scmi_handle *handle,
628 				    struct scmi_xfer *xfer)
629 {
630 	struct scmi_info *info = handle_to_scmi_info(handle);
631 
632 	return scmi_xfer_inflight_register(xfer, &info->tx_minfo);
633 }
634 
635 /**
636  * scmi_xfer_pending_set  - Pick a proper sequence number and mark the xfer
637  * as pending in-flight
638  *
639  * @xfer: The xfer to act upon
640  * @minfo: Pointer to Tx/Rx Message management info based on channel type
641  *
642  * Return: 0 on Success or error otherwise
643  */
644 static inline int scmi_xfer_pending_set(struct scmi_xfer *xfer,
645 					struct scmi_xfers_info *minfo)
646 {
647 	int ret;
648 	unsigned long flags;
649 
650 	spin_lock_irqsave(&minfo->xfer_lock, flags);
651 	/* Set a new monotonic token as the xfer sequence number */
652 	ret = scmi_xfer_token_set(minfo, xfer);
653 	if (!ret)
654 		scmi_xfer_inflight_register_unlocked(xfer, minfo);
655 	spin_unlock_irqrestore(&minfo->xfer_lock, flags);
656 
657 	return ret;
658 }
659 
660 /**
661  * scmi_xfer_get() - Allocate one message
662  *
663  * @handle: Pointer to SCMI entity handle
664  * @minfo: Pointer to Tx/Rx Message management info based on channel type
665  *
666  * Helper function which is used by various message functions that are
667  * exposed to clients of this driver for allocating a message traffic event.
668  *
669  * Picks an xfer from the free list @free_xfers (if any available) and perform
670  * a basic initialization.
671  *
672  * Note that, at this point, still no sequence number is assigned to the
673  * allocated xfer, nor it is registered as a pending transaction.
674  *
675  * The successfully initialized xfer is refcounted.
676  *
677  * Context: Holds @xfer_lock while manipulating @free_xfers.
678  *
679  * Return: An initialized xfer if all went fine, else pointer error.
680  */
681 static struct scmi_xfer *scmi_xfer_get(const struct scmi_handle *handle,
682 				       struct scmi_xfers_info *minfo)
683 {
684 	unsigned long flags;
685 	struct scmi_xfer *xfer;
686 
687 	spin_lock_irqsave(&minfo->xfer_lock, flags);
688 	if (hlist_empty(&minfo->free_xfers)) {
689 		spin_unlock_irqrestore(&minfo->xfer_lock, flags);
690 		return ERR_PTR(-ENOMEM);
691 	}
692 
693 	/* grab an xfer from the free_list */
694 	xfer = hlist_entry(minfo->free_xfers.first, struct scmi_xfer, node);
695 	hlist_del_init(&xfer->node);
696 
697 	/*
698 	 * Allocate transfer_id early so that can be used also as base for
699 	 * monotonic sequence number generation if needed.
700 	 */
701 	xfer->transfer_id = atomic_inc_return(&transfer_last_id);
702 
703 	refcount_set(&xfer->users, 1);
704 	atomic_set(&xfer->busy, SCMI_XFER_FREE);
705 	spin_unlock_irqrestore(&minfo->xfer_lock, flags);
706 
707 	return xfer;
708 }
709 
710 /**
711  * scmi_xfer_raw_get  - Helper to get a bare free xfer from the TX channel
712  *
713  * @handle: Pointer to SCMI entity handle
714  *
715  * Note that xfer is taken from the TX channel structures.
716  *
717  * Return: A valid xfer on Success, or an error-pointer otherwise
718  */
719 struct scmi_xfer *scmi_xfer_raw_get(const struct scmi_handle *handle)
720 {
721 	struct scmi_xfer *xfer;
722 	struct scmi_info *info = handle_to_scmi_info(handle);
723 
724 	xfer = scmi_xfer_get(handle, &info->tx_minfo);
725 	if (!IS_ERR(xfer))
726 		xfer->flags |= SCMI_XFER_FLAG_IS_RAW;
727 
728 	return xfer;
729 }
730 
731 /**
732  * scmi_xfer_raw_channel_get  - Helper to get a reference to the proper channel
733  * to use for a specific protocol_id Raw transaction.
734  *
735  * @handle: Pointer to SCMI entity handle
736  * @protocol_id: Identifier of the protocol
737  *
738  * Note that in a regular SCMI stack, usually, a protocol has to be defined in
739  * the DT to have an associated channel and be usable; but in Raw mode any
740  * protocol in range is allowed, re-using the Base channel, so as to enable
741  * fuzzing on any protocol without the need of a fully compiled DT.
742  *
743  * Return: A reference to the channel to use, or an ERR_PTR
744  */
745 struct scmi_chan_info *
746 scmi_xfer_raw_channel_get(const struct scmi_handle *handle, u8 protocol_id)
747 {
748 	struct scmi_chan_info *cinfo;
749 	struct scmi_info *info = handle_to_scmi_info(handle);
750 
751 	cinfo = idr_find(&info->tx_idr, protocol_id);
752 	if (!cinfo) {
753 		if (protocol_id == SCMI_PROTOCOL_BASE)
754 			return ERR_PTR(-EINVAL);
755 		/* Use Base channel for protocols not defined for DT */
756 		cinfo = idr_find(&info->tx_idr, SCMI_PROTOCOL_BASE);
757 		if (!cinfo)
758 			return ERR_PTR(-EINVAL);
759 		dev_warn_once(handle->dev,
760 			      "Using Base channel for protocol 0x%X\n",
761 			      protocol_id);
762 	}
763 
764 	return cinfo;
765 }
766 
767 /**
768  * __scmi_xfer_put() - Release a message
769  *
770  * @minfo: Pointer to Tx/Rx Message management info based on channel type
771  * @xfer: message that was reserved by scmi_xfer_get
772  *
773  * After refcount check, possibly release an xfer, clearing the token slot,
774  * removing xfer from @pending_xfers and putting it back into free_xfers.
775  *
776  * This holds a spinlock to maintain integrity of internal data structures.
777  */
778 static void
779 __scmi_xfer_put(struct scmi_xfers_info *minfo, struct scmi_xfer *xfer)
780 {
781 	unsigned long flags;
782 
783 	spin_lock_irqsave(&minfo->xfer_lock, flags);
784 	if (refcount_dec_and_test(&xfer->users)) {
785 		if (xfer->pending) {
786 			scmi_xfer_token_clear(minfo, xfer);
787 			hash_del(&xfer->node);
788 			xfer->pending = false;
789 		}
790 		hlist_add_head(&xfer->node, &minfo->free_xfers);
791 	}
792 	spin_unlock_irqrestore(&minfo->xfer_lock, flags);
793 }
794 
795 /**
796  * scmi_xfer_raw_put  - Release an xfer that was taken by @scmi_xfer_raw_get
797  *
798  * @handle: Pointer to SCMI entity handle
799  * @xfer: A reference to the xfer to put
800  *
801  * Note that as with other xfer_put() handlers the xfer is really effectively
802  * released only if there are no more users on the system.
803  */
804 void scmi_xfer_raw_put(const struct scmi_handle *handle, struct scmi_xfer *xfer)
805 {
806 	struct scmi_info *info = handle_to_scmi_info(handle);
807 
808 	xfer->flags &= ~SCMI_XFER_FLAG_IS_RAW;
809 	xfer->flags &= ~SCMI_XFER_FLAG_CHAN_SET;
810 	return __scmi_xfer_put(&info->tx_minfo, xfer);
811 }
812 
813 /**
814  * scmi_xfer_lookup_unlocked  -  Helper to lookup an xfer_id
815  *
816  * @minfo: Pointer to Tx/Rx Message management info based on channel type
817  * @xfer_id: Token ID to lookup in @pending_xfers
818  *
819  * Refcounting is untouched.
820  *
821  * Context: Assumes to be called with @xfer_lock already acquired.
822  *
823  * Return: A valid xfer on Success or error otherwise
824  */
825 static struct scmi_xfer *
826 scmi_xfer_lookup_unlocked(struct scmi_xfers_info *minfo, u16 xfer_id)
827 {
828 	struct scmi_xfer *xfer = NULL;
829 
830 	if (test_bit(xfer_id, minfo->xfer_alloc_table))
831 		xfer = XFER_FIND(minfo->pending_xfers, xfer_id);
832 
833 	return xfer ?: ERR_PTR(-EINVAL);
834 }
835 
836 /**
837  * scmi_bad_message_trace  - A helper to trace weird messages
838  *
839  * @cinfo: A reference to the channel descriptor on which the message was
840  *	   received
841  * @msg_hdr: Message header to track
842  * @err: A specific error code used as a status value in traces.
843  *
844  * This helper can be used to trace any kind of weird, incomplete, unexpected,
845  * timed-out message that arrives and as such, can be traced only referring to
846  * the header content, since the payload is missing/unreliable.
847  */
848 static void scmi_bad_message_trace(struct scmi_chan_info *cinfo, u32 msg_hdr,
849 				   enum scmi_bad_msg err)
850 {
851 	char *tag;
852 	struct scmi_info *info = handle_to_scmi_info(cinfo->handle);
853 
854 	switch (MSG_XTRACT_TYPE(msg_hdr)) {
855 	case MSG_TYPE_COMMAND:
856 		tag = "!RESP";
857 		break;
858 	case MSG_TYPE_DELAYED_RESP:
859 		tag = "!DLYD";
860 		break;
861 	case MSG_TYPE_NOTIFICATION:
862 		tag = "!NOTI";
863 		break;
864 	default:
865 		tag = "!UNKN";
866 		break;
867 	}
868 
869 	trace_scmi_msg_dump(info->id, cinfo->id,
870 			    MSG_XTRACT_PROT_ID(msg_hdr),
871 			    MSG_XTRACT_ID(msg_hdr), tag,
872 			    MSG_XTRACT_TOKEN(msg_hdr), err, NULL, 0);
873 }
874 
875 /**
876  * scmi_msg_response_validate  - Validate message type against state of related
877  * xfer
878  *
879  * @cinfo: A reference to the channel descriptor.
880  * @msg_type: Message type to check
881  * @xfer: A reference to the xfer to validate against @msg_type
882  *
883  * This function checks if @msg_type is congruent with the current state of
884  * a pending @xfer; if an asynchronous delayed response is received before the
885  * related synchronous response (Out-of-Order Delayed Response) the missing
886  * synchronous response is assumed to be OK and completed, carrying on with the
887  * Delayed Response: this is done to address the case in which the underlying
888  * SCMI transport can deliver such out-of-order responses.
889  *
890  * Context: Assumes to be called with xfer->lock already acquired.
891  *
892  * Return: 0 on Success, error otherwise
893  */
894 static inline int scmi_msg_response_validate(struct scmi_chan_info *cinfo,
895 					     u8 msg_type,
896 					     struct scmi_xfer *xfer)
897 {
898 	/*
899 	 * Even if a response was indeed expected on this slot at this point,
900 	 * a buggy platform could wrongly reply feeding us an unexpected
901 	 * delayed response we're not prepared to handle: bail-out safely
902 	 * blaming firmware.
903 	 */
904 	if (msg_type == MSG_TYPE_DELAYED_RESP && !xfer->async_done) {
905 		dev_err(cinfo->dev,
906 			"Delayed Response for %d not expected! Buggy F/W ?\n",
907 			xfer->hdr.seq);
908 		return -EINVAL;
909 	}
910 
911 	switch (xfer->state) {
912 	case SCMI_XFER_SENT_OK:
913 		if (msg_type == MSG_TYPE_DELAYED_RESP) {
914 			/*
915 			 * Delayed Response expected but delivered earlier.
916 			 * Assume message RESPONSE was OK and skip state.
917 			 */
918 			xfer->hdr.status = SCMI_SUCCESS;
919 			xfer->state = SCMI_XFER_RESP_OK;
920 			complete(&xfer->done);
921 			dev_warn(cinfo->dev,
922 				 "Received valid OoO Delayed Response for %d\n",
923 				 xfer->hdr.seq);
924 		}
925 		break;
926 	case SCMI_XFER_RESP_OK:
927 		if (msg_type != MSG_TYPE_DELAYED_RESP)
928 			return -EINVAL;
929 		break;
930 	case SCMI_XFER_DRESP_OK:
931 		/* No further message expected once in SCMI_XFER_DRESP_OK */
932 		return -EINVAL;
933 	}
934 
935 	return 0;
936 }
937 
938 /**
939  * scmi_xfer_state_update  - Update xfer state
940  *
941  * @xfer: A reference to the xfer to update
942  * @msg_type: Type of message being processed.
943  *
944  * Note that this message is assumed to have been already successfully validated
945  * by @scmi_msg_response_validate(), so here we just update the state.
946  *
947  * Context: Assumes to be called on an xfer exclusively acquired using the
948  *	    busy flag.
949  */
950 static inline void scmi_xfer_state_update(struct scmi_xfer *xfer, u8 msg_type)
951 {
952 	xfer->hdr.type = msg_type;
953 
954 	/* Unknown command types were already discarded earlier */
955 	if (xfer->hdr.type == MSG_TYPE_COMMAND)
956 		xfer->state = SCMI_XFER_RESP_OK;
957 	else
958 		xfer->state = SCMI_XFER_DRESP_OK;
959 }
960 
961 static bool scmi_xfer_acquired(struct scmi_xfer *xfer)
962 {
963 	int ret;
964 
965 	ret = atomic_cmpxchg(&xfer->busy, SCMI_XFER_FREE, SCMI_XFER_BUSY);
966 
967 	return ret == SCMI_XFER_FREE;
968 }
969 
970 /**
971  * scmi_xfer_command_acquire  -  Helper to lookup and acquire a command xfer
972  *
973  * @cinfo: A reference to the channel descriptor.
974  * @msg_hdr: A message header to use as lookup key
975  *
976  * When a valid xfer is found for the sequence number embedded in the provided
977  * msg_hdr, reference counting is properly updated and exclusive access to this
978  * xfer is granted till released with @scmi_xfer_command_release.
979  *
980  * Return: A valid @xfer on Success or error otherwise.
981  */
982 static inline struct scmi_xfer *
983 scmi_xfer_command_acquire(struct scmi_chan_info *cinfo, u32 msg_hdr)
984 {
985 	int ret;
986 	unsigned long flags;
987 	struct scmi_xfer *xfer;
988 	struct scmi_info *info = handle_to_scmi_info(cinfo->handle);
989 	struct scmi_xfers_info *minfo = &info->tx_minfo;
990 	u8 msg_type = MSG_XTRACT_TYPE(msg_hdr);
991 	u16 xfer_id = MSG_XTRACT_TOKEN(msg_hdr);
992 
993 	/* Are we even expecting this? */
994 	spin_lock_irqsave(&minfo->xfer_lock, flags);
995 	xfer = scmi_xfer_lookup_unlocked(minfo, xfer_id);
996 	if (IS_ERR(xfer)) {
997 		dev_err(cinfo->dev,
998 			"Message for %d type %d is not expected!\n",
999 			xfer_id, msg_type);
1000 		spin_unlock_irqrestore(&minfo->xfer_lock, flags);
1001 
1002 		scmi_bad_message_trace(cinfo, msg_hdr, MSG_UNEXPECTED);
1003 		scmi_inc_count(info->dbg->counters, ERR_MSG_UNEXPECTED);
1004 
1005 		return xfer;
1006 	}
1007 	refcount_inc(&xfer->users);
1008 	spin_unlock_irqrestore(&minfo->xfer_lock, flags);
1009 
1010 	spin_lock_irqsave(&xfer->lock, flags);
1011 	ret = scmi_msg_response_validate(cinfo, msg_type, xfer);
1012 	/*
1013 	 * If a pending xfer was found which was also in a congruent state with
1014 	 * the received message, acquire exclusive access to it setting the busy
1015 	 * flag.
1016 	 * Spins only on the rare limit condition of concurrent reception of
1017 	 * RESP and DRESP for the same xfer.
1018 	 */
1019 	if (!ret) {
1020 		spin_until_cond(scmi_xfer_acquired(xfer));
1021 		scmi_xfer_state_update(xfer, msg_type);
1022 	}
1023 	spin_unlock_irqrestore(&xfer->lock, flags);
1024 
1025 	if (ret) {
1026 		dev_err(cinfo->dev,
1027 			"Invalid message type:%d for %d - HDR:0x%X  state:%d\n",
1028 			msg_type, xfer_id, msg_hdr, xfer->state);
1029 
1030 		scmi_bad_message_trace(cinfo, msg_hdr, MSG_INVALID);
1031 		scmi_inc_count(info->dbg->counters, ERR_MSG_INVALID);
1032 
1033 		/* On error the refcount incremented above has to be dropped */
1034 		__scmi_xfer_put(minfo, xfer);
1035 		xfer = ERR_PTR(-EINVAL);
1036 	}
1037 
1038 	return xfer;
1039 }
1040 
1041 static inline void scmi_xfer_command_release(struct scmi_info *info,
1042 					     struct scmi_xfer *xfer)
1043 {
1044 	atomic_set(&xfer->busy, SCMI_XFER_FREE);
1045 	__scmi_xfer_put(&info->tx_minfo, xfer);
1046 }
1047 
1048 static inline void scmi_clear_channel(struct scmi_info *info,
1049 				      struct scmi_chan_info *cinfo)
1050 {
1051 	if (info->desc->ops->clear_channel)
1052 		info->desc->ops->clear_channel(cinfo);
1053 }
1054 
1055 static void scmi_handle_notification(struct scmi_chan_info *cinfo,
1056 				     u32 msg_hdr, void *priv)
1057 {
1058 	struct scmi_xfer *xfer;
1059 	struct device *dev = cinfo->dev;
1060 	struct scmi_info *info = handle_to_scmi_info(cinfo->handle);
1061 	struct scmi_xfers_info *minfo = &info->rx_minfo;
1062 	ktime_t ts;
1063 
1064 	ts = ktime_get_boottime();
1065 	xfer = scmi_xfer_get(cinfo->handle, minfo);
1066 	if (IS_ERR(xfer)) {
1067 		dev_err(dev, "failed to get free message slot (%ld)\n",
1068 			PTR_ERR(xfer));
1069 
1070 		scmi_bad_message_trace(cinfo, msg_hdr, MSG_NOMEM);
1071 		scmi_inc_count(info->dbg->counters, ERR_MSG_NOMEM);
1072 
1073 		scmi_clear_channel(info, cinfo);
1074 		return;
1075 	}
1076 
1077 	unpack_scmi_header(msg_hdr, &xfer->hdr);
1078 	if (priv)
1079 		/* Ensure order between xfer->priv store and following ops */
1080 		smp_store_mb(xfer->priv, priv);
1081 	info->desc->ops->fetch_notification(cinfo, info->desc->max_msg_size,
1082 					    xfer);
1083 
1084 	trace_scmi_msg_dump(info->id, cinfo->id, xfer->hdr.protocol_id,
1085 			    xfer->hdr.id, "NOTI", xfer->hdr.seq,
1086 			    xfer->hdr.status, xfer->rx.buf, xfer->rx.len);
1087 	scmi_inc_count(info->dbg->counters, NOTIFICATION_OK);
1088 
1089 	scmi_notify(cinfo->handle, xfer->hdr.protocol_id,
1090 		    xfer->hdr.id, xfer->rx.buf, xfer->rx.len, ts);
1091 
1092 	trace_scmi_rx_done(xfer->transfer_id, xfer->hdr.id,
1093 			   xfer->hdr.protocol_id, xfer->hdr.seq,
1094 			   MSG_TYPE_NOTIFICATION);
1095 
1096 	if (IS_ENABLED(CONFIG_ARM_SCMI_RAW_MODE_SUPPORT)) {
1097 		xfer->hdr.seq = MSG_XTRACT_TOKEN(msg_hdr);
1098 		scmi_raw_message_report(info->raw, xfer, SCMI_RAW_NOTIF_QUEUE,
1099 					cinfo->id);
1100 	}
1101 
1102 	__scmi_xfer_put(minfo, xfer);
1103 
1104 	scmi_clear_channel(info, cinfo);
1105 }
1106 
1107 static void scmi_handle_response(struct scmi_chan_info *cinfo,
1108 				 u32 msg_hdr, void *priv)
1109 {
1110 	struct scmi_xfer *xfer;
1111 	struct scmi_info *info = handle_to_scmi_info(cinfo->handle);
1112 
1113 	xfer = scmi_xfer_command_acquire(cinfo, msg_hdr);
1114 	if (IS_ERR(xfer)) {
1115 		if (IS_ENABLED(CONFIG_ARM_SCMI_RAW_MODE_SUPPORT))
1116 			scmi_raw_error_report(info->raw, cinfo, msg_hdr, priv);
1117 
1118 		if (MSG_XTRACT_TYPE(msg_hdr) == MSG_TYPE_DELAYED_RESP)
1119 			scmi_clear_channel(info, cinfo);
1120 		return;
1121 	}
1122 
1123 	/* rx.len could be shrunk in the sync do_xfer, so reset to maxsz */
1124 	if (xfer->hdr.type == MSG_TYPE_DELAYED_RESP)
1125 		xfer->rx.len = info->desc->max_msg_size;
1126 
1127 	if (priv)
1128 		/* Ensure order between xfer->priv store and following ops */
1129 		smp_store_mb(xfer->priv, priv);
1130 	info->desc->ops->fetch_response(cinfo, xfer);
1131 
1132 	trace_scmi_msg_dump(info->id, cinfo->id, xfer->hdr.protocol_id,
1133 			    xfer->hdr.id,
1134 			    xfer->hdr.type == MSG_TYPE_DELAYED_RESP ?
1135 			    (!SCMI_XFER_IS_RAW(xfer) ? "DLYD" : "dlyd") :
1136 			    (!SCMI_XFER_IS_RAW(xfer) ? "RESP" : "resp"),
1137 			    xfer->hdr.seq, xfer->hdr.status,
1138 			    xfer->rx.buf, xfer->rx.len);
1139 
1140 	trace_scmi_rx_done(xfer->transfer_id, xfer->hdr.id,
1141 			   xfer->hdr.protocol_id, xfer->hdr.seq,
1142 			   xfer->hdr.type);
1143 
1144 	if (xfer->hdr.type == MSG_TYPE_DELAYED_RESP) {
1145 		scmi_clear_channel(info, cinfo);
1146 		complete(xfer->async_done);
1147 		scmi_inc_count(info->dbg->counters, DELAYED_RESPONSE_OK);
1148 	} else {
1149 		complete(&xfer->done);
1150 		scmi_inc_count(info->dbg->counters, RESPONSE_OK);
1151 	}
1152 
1153 	if (IS_ENABLED(CONFIG_ARM_SCMI_RAW_MODE_SUPPORT)) {
1154 		/*
1155 		 * When in polling mode avoid to queue the Raw xfer on the IRQ
1156 		 * RX path since it will be already queued at the end of the TX
1157 		 * poll loop.
1158 		 */
1159 		if (!xfer->hdr.poll_completion)
1160 			scmi_raw_message_report(info->raw, xfer,
1161 						SCMI_RAW_REPLY_QUEUE,
1162 						cinfo->id);
1163 	}
1164 
1165 	scmi_xfer_command_release(info, xfer);
1166 }
1167 
1168 /**
1169  * scmi_rx_callback() - callback for receiving messages
1170  *
1171  * @cinfo: SCMI channel info
1172  * @msg_hdr: Message header
1173  * @priv: Transport specific private data.
1174  *
1175  * Processes one received message to appropriate transfer information and
1176  * signals completion of the transfer.
1177  *
1178  * NOTE: This function will be invoked in IRQ context, hence should be
1179  * as optimal as possible.
1180  */
1181 static void scmi_rx_callback(struct scmi_chan_info *cinfo, u32 msg_hdr,
1182 			     void *priv)
1183 {
1184 	u8 msg_type = MSG_XTRACT_TYPE(msg_hdr);
1185 
1186 	switch (msg_type) {
1187 	case MSG_TYPE_NOTIFICATION:
1188 		scmi_handle_notification(cinfo, msg_hdr, priv);
1189 		break;
1190 	case MSG_TYPE_COMMAND:
1191 	case MSG_TYPE_DELAYED_RESP:
1192 		scmi_handle_response(cinfo, msg_hdr, priv);
1193 		break;
1194 	default:
1195 		WARN_ONCE(1, "received unknown msg_type:%d\n", msg_type);
1196 		scmi_bad_message_trace(cinfo, msg_hdr, MSG_UNKNOWN);
1197 		break;
1198 	}
1199 }
1200 
1201 /**
1202  * xfer_put() - Release a transmit message
1203  *
1204  * @ph: Pointer to SCMI protocol handle
1205  * @xfer: message that was reserved by xfer_get_init
1206  */
1207 static void xfer_put(const struct scmi_protocol_handle *ph,
1208 		     struct scmi_xfer *xfer)
1209 {
1210 	const struct scmi_protocol_instance *pi = ph_to_pi(ph);
1211 	struct scmi_info *info = handle_to_scmi_info(pi->handle);
1212 
1213 	__scmi_xfer_put(&info->tx_minfo, xfer);
1214 }
1215 
1216 static bool scmi_xfer_done_no_timeout(struct scmi_chan_info *cinfo,
1217 				      struct scmi_xfer *xfer, ktime_t stop)
1218 {
1219 	struct scmi_info *info = handle_to_scmi_info(cinfo->handle);
1220 
1221 	/*
1222 	 * Poll also on xfer->done so that polling can be forcibly terminated
1223 	 * in case of out-of-order receptions of delayed responses
1224 	 */
1225 	return info->desc->ops->poll_done(cinfo, xfer) ||
1226 	       try_wait_for_completion(&xfer->done) ||
1227 	       ktime_after(ktime_get(), stop);
1228 }
1229 
1230 static int scmi_wait_for_reply(struct device *dev, const struct scmi_desc *desc,
1231 			       struct scmi_chan_info *cinfo,
1232 			       struct scmi_xfer *xfer, unsigned int timeout_ms)
1233 {
1234 	int ret = 0;
1235 	struct scmi_info *info = handle_to_scmi_info(cinfo->handle);
1236 
1237 	if (xfer->hdr.poll_completion) {
1238 		/*
1239 		 * Real polling is needed only if transport has NOT declared
1240 		 * itself to support synchronous commands replies.
1241 		 */
1242 		if (!desc->sync_cmds_completed_on_ret) {
1243 			/*
1244 			 * Poll on xfer using transport provided .poll_done();
1245 			 * assumes no completion interrupt was available.
1246 			 */
1247 			ktime_t stop = ktime_add_ms(ktime_get(), timeout_ms);
1248 
1249 			spin_until_cond(scmi_xfer_done_no_timeout(cinfo,
1250 								  xfer, stop));
1251 			if (ktime_after(ktime_get(), stop)) {
1252 				dev_err(dev,
1253 					"timed out in resp(caller: %pS) - polling\n",
1254 					(void *)_RET_IP_);
1255 				ret = -ETIMEDOUT;
1256 				scmi_inc_count(info->dbg->counters, XFERS_RESPONSE_POLLED_TIMEOUT);
1257 			}
1258 		}
1259 
1260 		if (!ret) {
1261 			unsigned long flags;
1262 
1263 			/*
1264 			 * Do not fetch_response if an out-of-order delayed
1265 			 * response is being processed.
1266 			 */
1267 			spin_lock_irqsave(&xfer->lock, flags);
1268 			if (xfer->state == SCMI_XFER_SENT_OK) {
1269 				desc->ops->fetch_response(cinfo, xfer);
1270 				xfer->state = SCMI_XFER_RESP_OK;
1271 			}
1272 			spin_unlock_irqrestore(&xfer->lock, flags);
1273 
1274 			/* Trace polled replies. */
1275 			trace_scmi_msg_dump(info->id, cinfo->id,
1276 					    xfer->hdr.protocol_id, xfer->hdr.id,
1277 					    !SCMI_XFER_IS_RAW(xfer) ?
1278 					    "RESP" : "resp",
1279 					    xfer->hdr.seq, xfer->hdr.status,
1280 					    xfer->rx.buf, xfer->rx.len);
1281 			scmi_inc_count(info->dbg->counters, RESPONSE_POLLED_OK);
1282 
1283 			if (IS_ENABLED(CONFIG_ARM_SCMI_RAW_MODE_SUPPORT)) {
1284 				scmi_raw_message_report(info->raw, xfer,
1285 							SCMI_RAW_REPLY_QUEUE,
1286 							cinfo->id);
1287 			}
1288 		}
1289 	} else {
1290 		/* And we wait for the response. */
1291 		if (!wait_for_completion_timeout(&xfer->done,
1292 						 msecs_to_jiffies(timeout_ms))) {
1293 			dev_err(dev, "timed out in resp(caller: %pS)\n",
1294 				(void *)_RET_IP_);
1295 			ret = -ETIMEDOUT;
1296 			scmi_inc_count(info->dbg->counters, XFERS_RESPONSE_TIMEOUT);
1297 		}
1298 	}
1299 
1300 	return ret;
1301 }
1302 
1303 /**
1304  * scmi_wait_for_message_response  - An helper to group all the possible ways of
1305  * waiting for a synchronous message response.
1306  *
1307  * @cinfo: SCMI channel info
1308  * @xfer: Reference to the transfer being waited for.
1309  *
1310  * Chooses waiting strategy (sleep-waiting vs busy-waiting) depending on
1311  * configuration flags like xfer->hdr.poll_completion.
1312  *
1313  * Return: 0 on Success, error otherwise.
1314  */
1315 static int scmi_wait_for_message_response(struct scmi_chan_info *cinfo,
1316 					  struct scmi_xfer *xfer)
1317 {
1318 	struct scmi_info *info = handle_to_scmi_info(cinfo->handle);
1319 	struct device *dev = info->dev;
1320 
1321 	trace_scmi_xfer_response_wait(xfer->transfer_id, xfer->hdr.id,
1322 				      xfer->hdr.protocol_id, xfer->hdr.seq,
1323 				      info->desc->max_rx_timeout_ms,
1324 				      xfer->hdr.poll_completion);
1325 
1326 	return scmi_wait_for_reply(dev, info->desc, cinfo, xfer,
1327 				   info->desc->max_rx_timeout_ms);
1328 }
1329 
1330 /**
1331  * scmi_xfer_raw_wait_for_message_response  - An helper to wait for a message
1332  * reply to an xfer raw request on a specific channel for the required timeout.
1333  *
1334  * @cinfo: SCMI channel info
1335  * @xfer: Reference to the transfer being waited for.
1336  * @timeout_ms: The maximum timeout in milliseconds
1337  *
1338  * Return: 0 on Success, error otherwise.
1339  */
1340 int scmi_xfer_raw_wait_for_message_response(struct scmi_chan_info *cinfo,
1341 					    struct scmi_xfer *xfer,
1342 					    unsigned int timeout_ms)
1343 {
1344 	int ret;
1345 	struct scmi_info *info = handle_to_scmi_info(cinfo->handle);
1346 	struct device *dev = info->dev;
1347 
1348 	ret = scmi_wait_for_reply(dev, info->desc, cinfo, xfer, timeout_ms);
1349 	if (ret)
1350 		dev_dbg(dev, "timed out in RAW response - HDR:%08X\n",
1351 			pack_scmi_header(&xfer->hdr));
1352 
1353 	return ret;
1354 }
1355 
1356 /**
1357  * do_xfer() - Do one transfer
1358  *
1359  * @ph: Pointer to SCMI protocol handle
1360  * @xfer: Transfer to initiate and wait for response
1361  *
1362  * Return: -ETIMEDOUT in case of no response, if transmit error,
1363  *	return corresponding error, else if all goes well,
1364  *	return 0.
1365  */
1366 static int do_xfer(const struct scmi_protocol_handle *ph,
1367 		   struct scmi_xfer *xfer)
1368 {
1369 	int ret;
1370 	const struct scmi_protocol_instance *pi = ph_to_pi(ph);
1371 	struct scmi_info *info = handle_to_scmi_info(pi->handle);
1372 	struct device *dev = info->dev;
1373 	struct scmi_chan_info *cinfo;
1374 
1375 	/* Check for polling request on custom command xfers at first */
1376 	if (xfer->hdr.poll_completion &&
1377 	    !is_transport_polling_capable(info->desc)) {
1378 		dev_warn_once(dev,
1379 			      "Polling mode is not supported by transport.\n");
1380 		scmi_inc_count(info->dbg->counters, SENT_FAIL_POLLING_UNSUPPORTED);
1381 		return -EINVAL;
1382 	}
1383 
1384 	cinfo = idr_find(&info->tx_idr, pi->proto->id);
1385 	if (unlikely(!cinfo)) {
1386 		scmi_inc_count(info->dbg->counters, SENT_FAIL_CHANNEL_NOT_FOUND);
1387 		return -EINVAL;
1388 	}
1389 	/* True ONLY if also supported by transport. */
1390 	if (is_polling_enabled(cinfo, info->desc))
1391 		xfer->hdr.poll_completion = true;
1392 
1393 	/*
1394 	 * Initialise protocol id now from protocol handle to avoid it being
1395 	 * overridden by mistake (or malice) by the protocol code mangling with
1396 	 * the scmi_xfer structure prior to this.
1397 	 */
1398 	xfer->hdr.protocol_id = pi->proto->id;
1399 	reinit_completion(&xfer->done);
1400 
1401 	trace_scmi_xfer_begin(xfer->transfer_id, xfer->hdr.id,
1402 			      xfer->hdr.protocol_id, xfer->hdr.seq,
1403 			      xfer->hdr.poll_completion);
1404 
1405 	/* Clear any stale status */
1406 	xfer->hdr.status = SCMI_SUCCESS;
1407 	xfer->state = SCMI_XFER_SENT_OK;
1408 	/*
1409 	 * Even though spinlocking is not needed here since no race is possible
1410 	 * on xfer->state due to the monotonically increasing tokens allocation,
1411 	 * we must anyway ensure xfer->state initialization is not re-ordered
1412 	 * after the .send_message() to be sure that on the RX path an early
1413 	 * ISR calling scmi_rx_callback() cannot see an old stale xfer->state.
1414 	 */
1415 	smp_mb();
1416 
1417 	ret = info->desc->ops->send_message(cinfo, xfer);
1418 	if (ret < 0) {
1419 		dev_dbg(dev, "Failed to send message %d\n", ret);
1420 		scmi_inc_count(info->dbg->counters, SENT_FAIL);
1421 		return ret;
1422 	}
1423 
1424 	trace_scmi_msg_dump(info->id, cinfo->id, xfer->hdr.protocol_id,
1425 			    xfer->hdr.id, "CMND", xfer->hdr.seq,
1426 			    xfer->hdr.status, xfer->tx.buf, xfer->tx.len);
1427 	scmi_inc_count(info->dbg->counters, SENT_OK);
1428 
1429 	ret = scmi_wait_for_message_response(cinfo, xfer);
1430 	if (!ret && xfer->hdr.status) {
1431 		ret = scmi_to_linux_errno(xfer->hdr.status);
1432 		scmi_inc_count(info->dbg->counters, ERR_PROTOCOL);
1433 	}
1434 
1435 	if (info->desc->ops->mark_txdone)
1436 		info->desc->ops->mark_txdone(cinfo, ret, xfer);
1437 
1438 	trace_scmi_xfer_end(xfer->transfer_id, xfer->hdr.id,
1439 			    xfer->hdr.protocol_id, xfer->hdr.seq, ret);
1440 
1441 	return ret;
1442 }
1443 
1444 static void reset_rx_to_maxsz(const struct scmi_protocol_handle *ph,
1445 			      struct scmi_xfer *xfer)
1446 {
1447 	const struct scmi_protocol_instance *pi = ph_to_pi(ph);
1448 	struct scmi_info *info = handle_to_scmi_info(pi->handle);
1449 
1450 	xfer->rx.len = info->desc->max_msg_size;
1451 }
1452 
1453 /**
1454  * do_xfer_with_response() - Do one transfer and wait until the delayed
1455  *	response is received
1456  *
1457  * @ph: Pointer to SCMI protocol handle
1458  * @xfer: Transfer to initiate and wait for response
1459  *
1460  * Using asynchronous commands in atomic/polling mode should be avoided since
1461  * it could cause long busy-waiting here, so ignore polling for the delayed
1462  * response and WARN if it was requested for this command transaction since
1463  * upper layers should refrain from issuing such kind of requests.
1464  *
1465  * The only other option would have been to refrain from using any asynchronous
1466  * command even if made available, when an atomic transport is detected, and
1467  * instead forcibly use the synchronous version (thing that can be easily
1468  * attained at the protocol layer), but this would also have led to longer
1469  * stalls of the channel for synchronous commands and possibly timeouts.
1470  * (in other words there is usually a good reason if a platform provides an
1471  *  asynchronous version of a command and we should prefer to use it...just not
1472  *  when using atomic/polling mode)
1473  *
1474  * Return: -ETIMEDOUT in case of no delayed response, if transmit error,
1475  *	return corresponding error, else if all goes well, return 0.
1476  */
1477 static int do_xfer_with_response(const struct scmi_protocol_handle *ph,
1478 				 struct scmi_xfer *xfer)
1479 {
1480 	int ret, timeout = msecs_to_jiffies(SCMI_MAX_RESPONSE_TIMEOUT);
1481 	DECLARE_COMPLETION_ONSTACK(async_response);
1482 
1483 	xfer->async_done = &async_response;
1484 
1485 	/*
1486 	 * Delayed responses should not be polled, so an async command should
1487 	 * not have been used when requiring an atomic/poll context; WARN and
1488 	 * perform instead a sleeping wait.
1489 	 * (Note Async + IgnoreDelayedResponses are sent via do_xfer)
1490 	 */
1491 	WARN_ON_ONCE(xfer->hdr.poll_completion);
1492 
1493 	ret = do_xfer(ph, xfer);
1494 	if (!ret) {
1495 		if (!wait_for_completion_timeout(xfer->async_done, timeout)) {
1496 			dev_err(ph->dev,
1497 				"timed out in delayed resp(caller: %pS)\n",
1498 				(void *)_RET_IP_);
1499 			ret = -ETIMEDOUT;
1500 		} else if (xfer->hdr.status) {
1501 			ret = scmi_to_linux_errno(xfer->hdr.status);
1502 		}
1503 	}
1504 
1505 	xfer->async_done = NULL;
1506 	return ret;
1507 }
1508 
1509 /**
1510  * xfer_get_init() - Allocate and initialise one message for transmit
1511  *
1512  * @ph: Pointer to SCMI protocol handle
1513  * @msg_id: Message identifier
1514  * @tx_size: transmit message size
1515  * @rx_size: receive message size
1516  * @p: pointer to the allocated and initialised message
1517  *
1518  * This function allocates the message using @scmi_xfer_get and
1519  * initialise the header.
1520  *
1521  * Return: 0 if all went fine with @p pointing to message, else
1522  *	corresponding error.
1523  */
1524 static int xfer_get_init(const struct scmi_protocol_handle *ph,
1525 			 u8 msg_id, size_t tx_size, size_t rx_size,
1526 			 struct scmi_xfer **p)
1527 {
1528 	int ret;
1529 	struct scmi_xfer *xfer;
1530 	const struct scmi_protocol_instance *pi = ph_to_pi(ph);
1531 	struct scmi_info *info = handle_to_scmi_info(pi->handle);
1532 	struct scmi_xfers_info *minfo = &info->tx_minfo;
1533 	struct device *dev = info->dev;
1534 
1535 	/* Ensure we have sane transfer sizes */
1536 	if (rx_size > info->desc->max_msg_size ||
1537 	    tx_size > info->desc->max_msg_size)
1538 		return -ERANGE;
1539 
1540 	xfer = scmi_xfer_get(pi->handle, minfo);
1541 	if (IS_ERR(xfer)) {
1542 		ret = PTR_ERR(xfer);
1543 		dev_err(dev, "failed to get free message slot(%d)\n", ret);
1544 		return ret;
1545 	}
1546 
1547 	/* Pick a sequence number and register this xfer as in-flight */
1548 	ret = scmi_xfer_pending_set(xfer, minfo);
1549 	if (ret) {
1550 		dev_err(pi->handle->dev,
1551 			"Failed to get monotonic token %d\n", ret);
1552 		__scmi_xfer_put(minfo, xfer);
1553 		return ret;
1554 	}
1555 
1556 	xfer->tx.len = tx_size;
1557 	xfer->rx.len = rx_size ? : info->desc->max_msg_size;
1558 	xfer->hdr.type = MSG_TYPE_COMMAND;
1559 	xfer->hdr.id = msg_id;
1560 	xfer->hdr.poll_completion = false;
1561 
1562 	*p = xfer;
1563 
1564 	return 0;
1565 }
1566 
1567 /**
1568  * version_get() - command to get the revision of the SCMI entity
1569  *
1570  * @ph: Pointer to SCMI protocol handle
1571  * @version: Holds returned version of protocol.
1572  *
1573  * Updates the SCMI information in the internal data structure.
1574  *
1575  * Return: 0 if all went fine, else return appropriate error.
1576  */
1577 static int version_get(const struct scmi_protocol_handle *ph, u32 *version)
1578 {
1579 	int ret;
1580 	__le32 *rev_info;
1581 	struct scmi_xfer *t;
1582 
1583 	ret = xfer_get_init(ph, PROTOCOL_VERSION, 0, sizeof(*version), &t);
1584 	if (ret)
1585 		return ret;
1586 
1587 	ret = do_xfer(ph, t);
1588 	if (!ret) {
1589 		rev_info = t->rx.buf;
1590 		*version = le32_to_cpu(*rev_info);
1591 	}
1592 
1593 	xfer_put(ph, t);
1594 	return ret;
1595 }
1596 
1597 /**
1598  * scmi_set_protocol_priv  - Set protocol specific data at init time
1599  *
1600  * @ph: A reference to the protocol handle.
1601  * @priv: The private data to set.
1602  * @version: The detected protocol version for the core to register.
1603  *
1604  * Return: 0 on Success
1605  */
1606 static int scmi_set_protocol_priv(const struct scmi_protocol_handle *ph,
1607 				  void *priv, u32 version)
1608 {
1609 	struct scmi_protocol_instance *pi = ph_to_pi(ph);
1610 
1611 	pi->priv = priv;
1612 	pi->version = version;
1613 
1614 	return 0;
1615 }
1616 
1617 /**
1618  * scmi_get_protocol_priv  - Set protocol specific data at init time
1619  *
1620  * @ph: A reference to the protocol handle.
1621  *
1622  * Return: Protocol private data if any was set.
1623  */
1624 static void *scmi_get_protocol_priv(const struct scmi_protocol_handle *ph)
1625 {
1626 	const struct scmi_protocol_instance *pi = ph_to_pi(ph);
1627 
1628 	return pi->priv;
1629 }
1630 
1631 static const struct scmi_xfer_ops xfer_ops = {
1632 	.version_get = version_get,
1633 	.xfer_get_init = xfer_get_init,
1634 	.reset_rx_to_maxsz = reset_rx_to_maxsz,
1635 	.do_xfer = do_xfer,
1636 	.do_xfer_with_response = do_xfer_with_response,
1637 	.xfer_put = xfer_put,
1638 };
1639 
1640 struct scmi_msg_resp_domain_name_get {
1641 	__le32 flags;
1642 	u8 name[SCMI_MAX_STR_SIZE];
1643 };
1644 
1645 /**
1646  * scmi_common_extended_name_get  - Common helper to get extended resources name
1647  * @ph: A protocol handle reference.
1648  * @cmd_id: The specific command ID to use.
1649  * @res_id: The specific resource ID to use.
1650  * @flags: A pointer to specific flags to use, if any.
1651  * @name: A pointer to the preallocated area where the retrieved name will be
1652  *	  stored as a NULL terminated string.
1653  * @len: The len in bytes of the @name char array.
1654  *
1655  * Return: 0 on Succcess
1656  */
1657 static int scmi_common_extended_name_get(const struct scmi_protocol_handle *ph,
1658 					 u8 cmd_id, u32 res_id, u32 *flags,
1659 					 char *name, size_t len)
1660 {
1661 	int ret;
1662 	size_t txlen;
1663 	struct scmi_xfer *t;
1664 	struct scmi_msg_resp_domain_name_get *resp;
1665 
1666 	txlen = !flags ? sizeof(res_id) : sizeof(res_id) + sizeof(*flags);
1667 	ret = ph->xops->xfer_get_init(ph, cmd_id, txlen, sizeof(*resp), &t);
1668 	if (ret)
1669 		goto out;
1670 
1671 	put_unaligned_le32(res_id, t->tx.buf);
1672 	if (flags)
1673 		put_unaligned_le32(*flags, t->tx.buf + sizeof(res_id));
1674 	resp = t->rx.buf;
1675 
1676 	ret = ph->xops->do_xfer(ph, t);
1677 	if (!ret)
1678 		strscpy(name, resp->name, len);
1679 
1680 	ph->xops->xfer_put(ph, t);
1681 out:
1682 	if (ret)
1683 		dev_warn(ph->dev,
1684 			 "Failed to get extended name - id:%u (ret:%d). Using %s\n",
1685 			 res_id, ret, name);
1686 	return ret;
1687 }
1688 
1689 /**
1690  * scmi_common_get_max_msg_size  - Get maximum message size
1691  * @ph: A protocol handle reference.
1692  *
1693  * Return: Maximum message size for the current protocol.
1694  */
1695 static int scmi_common_get_max_msg_size(const struct scmi_protocol_handle *ph)
1696 {
1697 	const struct scmi_protocol_instance *pi = ph_to_pi(ph);
1698 	struct scmi_info *info = handle_to_scmi_info(pi->handle);
1699 
1700 	return info->desc->max_msg_size;
1701 }
1702 
1703 /**
1704  * struct scmi_iterator  - Iterator descriptor
1705  * @msg: A reference to the message TX buffer; filled by @prepare_message with
1706  *	 a proper custom command payload for each multi-part command request.
1707  * @resp: A reference to the response RX buffer; used by @update_state and
1708  *	  @process_response to parse the multi-part replies.
1709  * @t: A reference to the underlying xfer initialized and used transparently by
1710  *     the iterator internal routines.
1711  * @ph: A reference to the associated protocol handle to be used.
1712  * @ops: A reference to the custom provided iterator operations.
1713  * @state: The current iterator state; used and updated in turn by the iterators
1714  *	   internal routines and by the caller-provided @scmi_iterator_ops.
1715  * @priv: A reference to optional private data as provided by the caller and
1716  *	  passed back to the @@scmi_iterator_ops.
1717  */
1718 struct scmi_iterator {
1719 	void *msg;
1720 	void *resp;
1721 	struct scmi_xfer *t;
1722 	const struct scmi_protocol_handle *ph;
1723 	struct scmi_iterator_ops *ops;
1724 	struct scmi_iterator_state state;
1725 	void *priv;
1726 };
1727 
1728 static void *scmi_iterator_init(const struct scmi_protocol_handle *ph,
1729 				struct scmi_iterator_ops *ops,
1730 				unsigned int max_resources, u8 msg_id,
1731 				size_t tx_size, void *priv)
1732 {
1733 	int ret;
1734 	struct scmi_iterator *i;
1735 
1736 	i = devm_kzalloc(ph->dev, sizeof(*i), GFP_KERNEL);
1737 	if (!i)
1738 		return ERR_PTR(-ENOMEM);
1739 
1740 	i->ph = ph;
1741 	i->ops = ops;
1742 	i->priv = priv;
1743 
1744 	ret = ph->xops->xfer_get_init(ph, msg_id, tx_size, 0, &i->t);
1745 	if (ret) {
1746 		devm_kfree(ph->dev, i);
1747 		return ERR_PTR(ret);
1748 	}
1749 
1750 	i->state.max_resources = max_resources;
1751 	i->msg = i->t->tx.buf;
1752 	i->resp = i->t->rx.buf;
1753 
1754 	return i;
1755 }
1756 
1757 static int scmi_iterator_run(void *iter)
1758 {
1759 	int ret = -EINVAL;
1760 	struct scmi_iterator_ops *iops;
1761 	const struct scmi_protocol_handle *ph;
1762 	struct scmi_iterator_state *st;
1763 	struct scmi_iterator *i = iter;
1764 
1765 	if (!i || !i->ops || !i->ph)
1766 		return ret;
1767 
1768 	iops = i->ops;
1769 	ph = i->ph;
1770 	st = &i->state;
1771 
1772 	do {
1773 		iops->prepare_message(i->msg, st->desc_index, i->priv);
1774 		ret = ph->xops->do_xfer(ph, i->t);
1775 		if (ret)
1776 			break;
1777 
1778 		st->rx_len = i->t->rx.len;
1779 		ret = iops->update_state(st, i->resp, i->priv);
1780 		if (ret)
1781 			break;
1782 
1783 		if (st->num_returned > st->max_resources - st->desc_index) {
1784 			dev_err(ph->dev,
1785 				"No. of resources can't exceed %d\n",
1786 				st->max_resources);
1787 			ret = -EINVAL;
1788 			break;
1789 		}
1790 
1791 		for (st->loop_idx = 0; st->loop_idx < st->num_returned;
1792 		     st->loop_idx++) {
1793 			ret = iops->process_response(ph, i->resp, st, i->priv);
1794 			if (ret)
1795 				goto out;
1796 		}
1797 
1798 		st->desc_index += st->num_returned;
1799 		ph->xops->reset_rx_to_maxsz(ph, i->t);
1800 		/*
1801 		 * check for both returned and remaining to avoid infinite
1802 		 * loop due to buggy firmware
1803 		 */
1804 	} while (st->num_returned && st->num_remaining);
1805 
1806 out:
1807 	/* Finalize and destroy iterator */
1808 	ph->xops->xfer_put(ph, i->t);
1809 	devm_kfree(ph->dev, i);
1810 
1811 	return ret;
1812 }
1813 
1814 struct scmi_msg_get_fc_info {
1815 	__le32 domain;
1816 	__le32 message_id;
1817 };
1818 
1819 struct scmi_msg_resp_desc_fc {
1820 	__le32 attr;
1821 #define SUPPORTS_DOORBELL(x)		((x) & BIT(0))
1822 #define DOORBELL_REG_WIDTH(x)		FIELD_GET(GENMASK(2, 1), (x))
1823 	__le32 rate_limit;
1824 	__le32 chan_addr_low;
1825 	__le32 chan_addr_high;
1826 	__le32 chan_size;
1827 	__le32 db_addr_low;
1828 	__le32 db_addr_high;
1829 	__le32 db_set_lmask;
1830 	__le32 db_set_hmask;
1831 	__le32 db_preserve_lmask;
1832 	__le32 db_preserve_hmask;
1833 };
1834 
1835 static void
1836 scmi_common_fastchannel_init(const struct scmi_protocol_handle *ph,
1837 			     u8 describe_id, u32 message_id, u32 valid_size,
1838 			     u32 domain, void __iomem **p_addr,
1839 			     struct scmi_fc_db_info **p_db, u32 *rate_limit)
1840 {
1841 	int ret;
1842 	u32 flags;
1843 	u64 phys_addr;
1844 	u8 size;
1845 	void __iomem *addr;
1846 	struct scmi_xfer *t;
1847 	struct scmi_fc_db_info *db = NULL;
1848 	struct scmi_msg_get_fc_info *info;
1849 	struct scmi_msg_resp_desc_fc *resp;
1850 	const struct scmi_protocol_instance *pi = ph_to_pi(ph);
1851 
1852 	if (!p_addr) {
1853 		ret = -EINVAL;
1854 		goto err_out;
1855 	}
1856 
1857 	ret = ph->xops->xfer_get_init(ph, describe_id,
1858 				      sizeof(*info), sizeof(*resp), &t);
1859 	if (ret)
1860 		goto err_out;
1861 
1862 	info = t->tx.buf;
1863 	info->domain = cpu_to_le32(domain);
1864 	info->message_id = cpu_to_le32(message_id);
1865 
1866 	/*
1867 	 * Bail out on error leaving fc_info addresses zeroed; this includes
1868 	 * the case in which the requested domain/message_id does NOT support
1869 	 * fastchannels at all.
1870 	 */
1871 	ret = ph->xops->do_xfer(ph, t);
1872 	if (ret)
1873 		goto err_xfer;
1874 
1875 	resp = t->rx.buf;
1876 	flags = le32_to_cpu(resp->attr);
1877 	size = le32_to_cpu(resp->chan_size);
1878 	if (size != valid_size) {
1879 		ret = -EINVAL;
1880 		goto err_xfer;
1881 	}
1882 
1883 	if (rate_limit)
1884 		*rate_limit = le32_to_cpu(resp->rate_limit) & GENMASK(19, 0);
1885 
1886 	phys_addr = le32_to_cpu(resp->chan_addr_low);
1887 	phys_addr |= (u64)le32_to_cpu(resp->chan_addr_high) << 32;
1888 	addr = devm_ioremap(ph->dev, phys_addr, size);
1889 	if (!addr) {
1890 		ret = -EADDRNOTAVAIL;
1891 		goto err_xfer;
1892 	}
1893 
1894 	*p_addr = addr;
1895 
1896 	if (p_db && SUPPORTS_DOORBELL(flags)) {
1897 		db = devm_kzalloc(ph->dev, sizeof(*db), GFP_KERNEL);
1898 		if (!db) {
1899 			ret = -ENOMEM;
1900 			goto err_db;
1901 		}
1902 
1903 		size = 1 << DOORBELL_REG_WIDTH(flags);
1904 		phys_addr = le32_to_cpu(resp->db_addr_low);
1905 		phys_addr |= (u64)le32_to_cpu(resp->db_addr_high) << 32;
1906 		addr = devm_ioremap(ph->dev, phys_addr, size);
1907 		if (!addr) {
1908 			ret = -EADDRNOTAVAIL;
1909 			goto err_db_mem;
1910 		}
1911 
1912 		db->addr = addr;
1913 		db->width = size;
1914 		db->set = le32_to_cpu(resp->db_set_lmask);
1915 		db->set |= (u64)le32_to_cpu(resp->db_set_hmask) << 32;
1916 		db->mask = le32_to_cpu(resp->db_preserve_lmask);
1917 		db->mask |= (u64)le32_to_cpu(resp->db_preserve_hmask) << 32;
1918 
1919 		*p_db = db;
1920 	}
1921 
1922 	ph->xops->xfer_put(ph, t);
1923 
1924 	dev_dbg(ph->dev,
1925 		"Using valid FC for protocol %X [MSG_ID:%u / RES_ID:%u]\n",
1926 		pi->proto->id, message_id, domain);
1927 
1928 	return;
1929 
1930 err_db_mem:
1931 	devm_kfree(ph->dev, db);
1932 
1933 err_db:
1934 	*p_addr = NULL;
1935 
1936 err_xfer:
1937 	ph->xops->xfer_put(ph, t);
1938 
1939 err_out:
1940 	dev_warn(ph->dev,
1941 		 "Failed to get FC for protocol %X [MSG_ID:%u / RES_ID:%u] - ret:%d. Using regular messaging.\n",
1942 		 pi->proto->id, message_id, domain, ret);
1943 }
1944 
1945 #define SCMI_PROTO_FC_RING_DB(w)			\
1946 do {							\
1947 	u##w val = 0;					\
1948 							\
1949 	if (db->mask)					\
1950 		val = ioread##w(db->addr) & db->mask;	\
1951 	iowrite##w((u##w)db->set | val, db->addr);	\
1952 } while (0)
1953 
1954 static void scmi_common_fastchannel_db_ring(struct scmi_fc_db_info *db)
1955 {
1956 	if (!db || !db->addr)
1957 		return;
1958 
1959 	if (db->width == 1)
1960 		SCMI_PROTO_FC_RING_DB(8);
1961 	else if (db->width == 2)
1962 		SCMI_PROTO_FC_RING_DB(16);
1963 	else if (db->width == 4)
1964 		SCMI_PROTO_FC_RING_DB(32);
1965 	else /* db->width == 8 */
1966 #ifdef CONFIG_64BIT
1967 		SCMI_PROTO_FC_RING_DB(64);
1968 #else
1969 	{
1970 		u64 val = 0;
1971 
1972 		if (db->mask)
1973 			val = ioread64_hi_lo(db->addr) & db->mask;
1974 		iowrite64_hi_lo(db->set | val, db->addr);
1975 	}
1976 #endif
1977 }
1978 
1979 /**
1980  * scmi_protocol_msg_check  - Check protocol message attributes
1981  *
1982  * @ph: A reference to the protocol handle.
1983  * @message_id: The ID of the message to check.
1984  * @attributes: A parameter to optionally return the retrieved message
1985  *		attributes, in case of Success.
1986  *
1987  * An helper to check protocol message attributes for a specific protocol
1988  * and message pair.
1989  *
1990  * Return: 0 on SUCCESS
1991  */
1992 static int scmi_protocol_msg_check(const struct scmi_protocol_handle *ph,
1993 				   u32 message_id, u32 *attributes)
1994 {
1995 	int ret;
1996 	struct scmi_xfer *t;
1997 
1998 	ret = xfer_get_init(ph, PROTOCOL_MESSAGE_ATTRIBUTES,
1999 			    sizeof(__le32), 0, &t);
2000 	if (ret)
2001 		return ret;
2002 
2003 	put_unaligned_le32(message_id, t->tx.buf);
2004 	ret = do_xfer(ph, t);
2005 	if (!ret && attributes)
2006 		*attributes = get_unaligned_le32(t->rx.buf);
2007 	xfer_put(ph, t);
2008 
2009 	return ret;
2010 }
2011 
2012 static const struct scmi_proto_helpers_ops helpers_ops = {
2013 	.extended_name_get = scmi_common_extended_name_get,
2014 	.get_max_msg_size = scmi_common_get_max_msg_size,
2015 	.iter_response_init = scmi_iterator_init,
2016 	.iter_response_run = scmi_iterator_run,
2017 	.protocol_msg_check = scmi_protocol_msg_check,
2018 	.fastchannel_init = scmi_common_fastchannel_init,
2019 	.fastchannel_db_ring = scmi_common_fastchannel_db_ring,
2020 };
2021 
2022 /**
2023  * scmi_revision_area_get  - Retrieve version memory area.
2024  *
2025  * @ph: A reference to the protocol handle.
2026  *
2027  * A helper to grab the version memory area reference during SCMI Base protocol
2028  * initialization.
2029  *
2030  * Return: A reference to the version memory area associated to the SCMI
2031  *	   instance underlying this protocol handle.
2032  */
2033 struct scmi_revision_info *
2034 scmi_revision_area_get(const struct scmi_protocol_handle *ph)
2035 {
2036 	const struct scmi_protocol_instance *pi = ph_to_pi(ph);
2037 
2038 	return pi->handle->version;
2039 }
2040 
2041 /**
2042  * scmi_protocol_version_negotiate  - Negotiate protocol version
2043  *
2044  * @ph: A reference to the protocol handle.
2045  *
2046  * An helper to negotiate a protocol version different from the latest
2047  * advertised as supported from the platform: on Success backward
2048  * compatibility is assured by the platform.
2049  *
2050  * Return: 0 on Success
2051  */
2052 static int scmi_protocol_version_negotiate(struct scmi_protocol_handle *ph)
2053 {
2054 	int ret;
2055 	struct scmi_xfer *t;
2056 	struct scmi_protocol_instance *pi = ph_to_pi(ph);
2057 
2058 	/* At first check if NEGOTIATE_PROTOCOL_VERSION is supported ... */
2059 	ret = scmi_protocol_msg_check(ph, NEGOTIATE_PROTOCOL_VERSION, NULL);
2060 	if (ret)
2061 		return ret;
2062 
2063 	/* ... then attempt protocol version negotiation */
2064 	ret = xfer_get_init(ph, NEGOTIATE_PROTOCOL_VERSION,
2065 			    sizeof(__le32), 0, &t);
2066 	if (ret)
2067 		return ret;
2068 
2069 	put_unaligned_le32(pi->proto->supported_version, t->tx.buf);
2070 	ret = do_xfer(ph, t);
2071 	if (!ret)
2072 		pi->negotiated_version = pi->proto->supported_version;
2073 
2074 	xfer_put(ph, t);
2075 
2076 	return ret;
2077 }
2078 
2079 /**
2080  * scmi_alloc_init_protocol_instance  - Allocate and initialize a protocol
2081  * instance descriptor.
2082  * @info: The reference to the related SCMI instance.
2083  * @proto: The protocol descriptor.
2084  *
2085  * Allocate a new protocol instance descriptor, using the provided @proto
2086  * description, against the specified SCMI instance @info, and initialize it;
2087  * all resources management is handled via a dedicated per-protocol devres
2088  * group.
2089  *
2090  * Context: Assumes to be called with @protocols_mtx already acquired.
2091  * Return: A reference to a freshly allocated and initialized protocol instance
2092  *	   or ERR_PTR on failure. On failure the @proto reference is at first
2093  *	   put using @scmi_protocol_put() before releasing all the devres group.
2094  */
2095 static struct scmi_protocol_instance *
2096 scmi_alloc_init_protocol_instance(struct scmi_info *info,
2097 				  const struct scmi_protocol *proto)
2098 {
2099 	int ret = -ENOMEM;
2100 	void *gid;
2101 	struct scmi_protocol_instance *pi;
2102 	const struct scmi_handle *handle = &info->handle;
2103 
2104 	/* Protocol specific devres group */
2105 	gid = devres_open_group(handle->dev, NULL, GFP_KERNEL);
2106 	if (!gid) {
2107 		scmi_protocol_put(proto);
2108 		goto out;
2109 	}
2110 
2111 	pi = devm_kzalloc(handle->dev, sizeof(*pi), GFP_KERNEL);
2112 	if (!pi)
2113 		goto clean;
2114 
2115 	pi->gid = gid;
2116 	pi->proto = proto;
2117 	pi->handle = handle;
2118 	pi->ph.dev = handle->dev;
2119 	pi->ph.xops = &xfer_ops;
2120 	pi->ph.hops = &helpers_ops;
2121 	pi->ph.set_priv = scmi_set_protocol_priv;
2122 	pi->ph.get_priv = scmi_get_protocol_priv;
2123 	refcount_set(&pi->users, 1);
2124 	/* proto->init is assured NON NULL by scmi_protocol_register */
2125 	ret = pi->proto->instance_init(&pi->ph);
2126 	if (ret)
2127 		goto clean;
2128 
2129 	ret = idr_alloc(&info->protocols, pi, proto->id, proto->id + 1,
2130 			GFP_KERNEL);
2131 	if (ret != proto->id)
2132 		goto clean;
2133 
2134 	/*
2135 	 * Warn but ignore events registration errors since we do not want
2136 	 * to skip whole protocols if their notifications are messed up.
2137 	 */
2138 	if (pi->proto->events) {
2139 		ret = scmi_register_protocol_events(handle, pi->proto->id,
2140 						    &pi->ph,
2141 						    pi->proto->events);
2142 		if (ret)
2143 			dev_warn(handle->dev,
2144 				 "Protocol:%X - Events Registration Failed - err:%d\n",
2145 				 pi->proto->id, ret);
2146 	}
2147 
2148 	devres_close_group(handle->dev, pi->gid);
2149 	dev_dbg(handle->dev, "Initialized protocol: 0x%X\n", pi->proto->id);
2150 
2151 	if (pi->version > proto->supported_version) {
2152 		ret = scmi_protocol_version_negotiate(&pi->ph);
2153 		if (!ret) {
2154 			dev_info(handle->dev,
2155 				 "Protocol 0x%X successfully negotiated version 0x%X\n",
2156 				 proto->id, pi->negotiated_version);
2157 		} else {
2158 			dev_warn(handle->dev,
2159 				 "Detected UNSUPPORTED higher version 0x%X for protocol 0x%X.\n",
2160 				 pi->version, pi->proto->id);
2161 			dev_warn(handle->dev,
2162 				 "Trying version 0x%X. Backward compatibility is NOT assured.\n",
2163 				 pi->proto->supported_version);
2164 		}
2165 	}
2166 
2167 	return pi;
2168 
2169 clean:
2170 	/* Take care to put the protocol module's owner before releasing all */
2171 	scmi_protocol_put(proto);
2172 	devres_release_group(handle->dev, gid);
2173 out:
2174 	return ERR_PTR(ret);
2175 }
2176 
2177 /**
2178  * scmi_get_protocol_instance  - Protocol initialization helper.
2179  * @handle: A reference to the SCMI platform instance.
2180  * @protocol_id: The protocol being requested.
2181  *
2182  * In case the required protocol has never been requested before for this
2183  * instance, allocate and initialize all the needed structures while handling
2184  * resource allocation with a dedicated per-protocol devres subgroup.
2185  *
2186  * Return: A reference to an initialized protocol instance or error on failure:
2187  *	   in particular returns -EPROBE_DEFER when the desired protocol could
2188  *	   NOT be found.
2189  */
2190 static struct scmi_protocol_instance * __must_check
2191 scmi_get_protocol_instance(const struct scmi_handle *handle, u8 protocol_id)
2192 {
2193 	struct scmi_protocol_instance *pi;
2194 	struct scmi_info *info = handle_to_scmi_info(handle);
2195 
2196 	mutex_lock(&info->protocols_mtx);
2197 	pi = idr_find(&info->protocols, protocol_id);
2198 
2199 	if (pi) {
2200 		refcount_inc(&pi->users);
2201 	} else {
2202 		const struct scmi_protocol *proto;
2203 
2204 		/* Fails if protocol not registered on bus */
2205 		proto = scmi_protocol_get(protocol_id, &info->version);
2206 		if (proto)
2207 			pi = scmi_alloc_init_protocol_instance(info, proto);
2208 		else
2209 			pi = ERR_PTR(-EPROBE_DEFER);
2210 	}
2211 	mutex_unlock(&info->protocols_mtx);
2212 
2213 	return pi;
2214 }
2215 
2216 /**
2217  * scmi_protocol_acquire  - Protocol acquire
2218  * @handle: A reference to the SCMI platform instance.
2219  * @protocol_id: The protocol being requested.
2220  *
2221  * Register a new user for the requested protocol on the specified SCMI
2222  * platform instance, possibly triggering its initialization on first user.
2223  *
2224  * Return: 0 if protocol was acquired successfully.
2225  */
2226 int scmi_protocol_acquire(const struct scmi_handle *handle, u8 protocol_id)
2227 {
2228 	return PTR_ERR_OR_ZERO(scmi_get_protocol_instance(handle, protocol_id));
2229 }
2230 
2231 /**
2232  * scmi_protocol_release  - Protocol de-initialization helper.
2233  * @handle: A reference to the SCMI platform instance.
2234  * @protocol_id: The protocol being requested.
2235  *
2236  * Remove one user for the specified protocol and triggers de-initialization
2237  * and resources de-allocation once the last user has gone.
2238  */
2239 void scmi_protocol_release(const struct scmi_handle *handle, u8 protocol_id)
2240 {
2241 	struct scmi_info *info = handle_to_scmi_info(handle);
2242 	struct scmi_protocol_instance *pi;
2243 
2244 	mutex_lock(&info->protocols_mtx);
2245 	pi = idr_find(&info->protocols, protocol_id);
2246 	if (WARN_ON(!pi))
2247 		goto out;
2248 
2249 	if (refcount_dec_and_test(&pi->users)) {
2250 		void *gid = pi->gid;
2251 
2252 		if (pi->proto->events)
2253 			scmi_deregister_protocol_events(handle, protocol_id);
2254 
2255 		if (pi->proto->instance_deinit)
2256 			pi->proto->instance_deinit(&pi->ph);
2257 
2258 		idr_remove(&info->protocols, protocol_id);
2259 
2260 		scmi_protocol_put(pi->proto);
2261 
2262 		devres_release_group(handle->dev, gid);
2263 		dev_dbg(handle->dev, "De-Initialized protocol: 0x%X\n",
2264 			protocol_id);
2265 	}
2266 
2267 out:
2268 	mutex_unlock(&info->protocols_mtx);
2269 }
2270 
2271 void scmi_setup_protocol_implemented(const struct scmi_protocol_handle *ph,
2272 				     u8 *prot_imp)
2273 {
2274 	const struct scmi_protocol_instance *pi = ph_to_pi(ph);
2275 	struct scmi_info *info = handle_to_scmi_info(pi->handle);
2276 
2277 	info->protocols_imp = prot_imp;
2278 }
2279 
2280 static bool
2281 scmi_is_protocol_implemented(const struct scmi_handle *handle, u8 prot_id)
2282 {
2283 	int i;
2284 	struct scmi_info *info = handle_to_scmi_info(handle);
2285 	struct scmi_revision_info *rev = handle->version;
2286 
2287 	if (!info->protocols_imp)
2288 		return false;
2289 
2290 	for (i = 0; i < rev->num_protocols; i++)
2291 		if (info->protocols_imp[i] == prot_id)
2292 			return true;
2293 	return false;
2294 }
2295 
2296 struct scmi_protocol_devres {
2297 	const struct scmi_handle *handle;
2298 	u8 protocol_id;
2299 };
2300 
2301 static void scmi_devm_release_protocol(struct device *dev, void *res)
2302 {
2303 	struct scmi_protocol_devres *dres = res;
2304 
2305 	scmi_protocol_release(dres->handle, dres->protocol_id);
2306 }
2307 
2308 static struct scmi_protocol_instance __must_check *
2309 scmi_devres_protocol_instance_get(struct scmi_device *sdev, u8 protocol_id)
2310 {
2311 	struct scmi_protocol_instance *pi;
2312 	struct scmi_protocol_devres *dres;
2313 
2314 	dres = devres_alloc(scmi_devm_release_protocol,
2315 			    sizeof(*dres), GFP_KERNEL);
2316 	if (!dres)
2317 		return ERR_PTR(-ENOMEM);
2318 
2319 	pi = scmi_get_protocol_instance(sdev->handle, protocol_id);
2320 	if (IS_ERR(pi)) {
2321 		devres_free(dres);
2322 		return pi;
2323 	}
2324 
2325 	dres->handle = sdev->handle;
2326 	dres->protocol_id = protocol_id;
2327 	devres_add(&sdev->dev, dres);
2328 
2329 	return pi;
2330 }
2331 
2332 /**
2333  * scmi_devm_protocol_get  - Devres managed get protocol operations and handle
2334  * @sdev: A reference to an scmi_device whose embedded struct device is to
2335  *	  be used for devres accounting.
2336  * @protocol_id: The protocol being requested.
2337  * @ph: A pointer reference used to pass back the associated protocol handle.
2338  *
2339  * Get hold of a protocol accounting for its usage, eventually triggering its
2340  * initialization, and returning the protocol specific operations and related
2341  * protocol handle which will be used as first argument in most of the
2342  * protocols operations methods.
2343  * Being a devres based managed method, protocol hold will be automatically
2344  * released, and possibly de-initialized on last user, once the SCMI driver
2345  * owning the scmi_device is unbound from it.
2346  *
2347  * Return: A reference to the requested protocol operations or error.
2348  *	   Must be checked for errors by caller.
2349  */
2350 static const void __must_check *
2351 scmi_devm_protocol_get(struct scmi_device *sdev, u8 protocol_id,
2352 		       struct scmi_protocol_handle **ph)
2353 {
2354 	struct scmi_protocol_instance *pi;
2355 
2356 	if (!ph)
2357 		return ERR_PTR(-EINVAL);
2358 
2359 	pi = scmi_devres_protocol_instance_get(sdev, protocol_id);
2360 	if (IS_ERR(pi))
2361 		return pi;
2362 
2363 	*ph = &pi->ph;
2364 
2365 	return pi->proto->ops;
2366 }
2367 
2368 /**
2369  * scmi_devm_protocol_acquire  - Devres managed helper to get hold of a protocol
2370  * @sdev: A reference to an scmi_device whose embedded struct device is to
2371  *	  be used for devres accounting.
2372  * @protocol_id: The protocol being requested.
2373  *
2374  * Get hold of a protocol accounting for its usage, possibly triggering its
2375  * initialization but without getting access to its protocol specific operations
2376  * and handle.
2377  *
2378  * Being a devres based managed method, protocol hold will be automatically
2379  * released, and possibly de-initialized on last user, once the SCMI driver
2380  * owning the scmi_device is unbound from it.
2381  *
2382  * Return: 0 on SUCCESS
2383  */
2384 static int __must_check scmi_devm_protocol_acquire(struct scmi_device *sdev,
2385 						   u8 protocol_id)
2386 {
2387 	struct scmi_protocol_instance *pi;
2388 
2389 	pi = scmi_devres_protocol_instance_get(sdev, protocol_id);
2390 	if (IS_ERR(pi))
2391 		return PTR_ERR(pi);
2392 
2393 	return 0;
2394 }
2395 
2396 static int scmi_devm_protocol_match(struct device *dev, void *res, void *data)
2397 {
2398 	struct scmi_protocol_devres *dres = res;
2399 
2400 	if (WARN_ON(!dres || !data))
2401 		return 0;
2402 
2403 	return dres->protocol_id == *((u8 *)data);
2404 }
2405 
2406 /**
2407  * scmi_devm_protocol_put  - Devres managed put protocol operations and handle
2408  * @sdev: A reference to an scmi_device whose embedded struct device is to
2409  *	  be used for devres accounting.
2410  * @protocol_id: The protocol being requested.
2411  *
2412  * Explicitly release a protocol hold previously obtained calling the above
2413  * @scmi_devm_protocol_get.
2414  */
2415 static void scmi_devm_protocol_put(struct scmi_device *sdev, u8 protocol_id)
2416 {
2417 	int ret;
2418 
2419 	ret = devres_release(&sdev->dev, scmi_devm_release_protocol,
2420 			     scmi_devm_protocol_match, &protocol_id);
2421 	WARN_ON(ret);
2422 }
2423 
2424 /**
2425  * scmi_is_transport_atomic  - Method to check if underlying transport for an
2426  * SCMI instance is configured as atomic.
2427  *
2428  * @handle: A reference to the SCMI platform instance.
2429  * @atomic_threshold: An optional return value for the system wide currently
2430  *		      configured threshold for atomic operations.
2431  *
2432  * Return: True if transport is configured as atomic
2433  */
2434 static bool scmi_is_transport_atomic(const struct scmi_handle *handle,
2435 				     unsigned int *atomic_threshold)
2436 {
2437 	bool ret;
2438 	struct scmi_info *info = handle_to_scmi_info(handle);
2439 
2440 	ret = info->desc->atomic_enabled &&
2441 		is_transport_polling_capable(info->desc);
2442 	if (ret && atomic_threshold)
2443 		*atomic_threshold = info->atomic_threshold;
2444 
2445 	return ret;
2446 }
2447 
2448 /**
2449  * scmi_handle_get() - Get the SCMI handle for a device
2450  *
2451  * @dev: pointer to device for which we want SCMI handle
2452  *
2453  * NOTE: The function does not track individual clients of the framework
2454  * and is expected to be maintained by caller of SCMI protocol library.
2455  * scmi_handle_put must be balanced with successful scmi_handle_get
2456  *
2457  * Return: pointer to handle if successful, NULL on error
2458  */
2459 static struct scmi_handle *scmi_handle_get(struct device *dev)
2460 {
2461 	struct list_head *p;
2462 	struct scmi_info *info;
2463 	struct scmi_handle *handle = NULL;
2464 
2465 	mutex_lock(&scmi_list_mutex);
2466 	list_for_each(p, &scmi_list) {
2467 		info = list_entry(p, struct scmi_info, node);
2468 		if (dev->parent == info->dev) {
2469 			info->users++;
2470 			handle = &info->handle;
2471 			break;
2472 		}
2473 	}
2474 	mutex_unlock(&scmi_list_mutex);
2475 
2476 	return handle;
2477 }
2478 
2479 /**
2480  * scmi_handle_put() - Release the handle acquired by scmi_handle_get
2481  *
2482  * @handle: handle acquired by scmi_handle_get
2483  *
2484  * NOTE: The function does not track individual clients of the framework
2485  * and is expected to be maintained by caller of SCMI protocol library.
2486  * scmi_handle_put must be balanced with successful scmi_handle_get
2487  *
2488  * Return: 0 is successfully released
2489  *	if null was passed, it returns -EINVAL;
2490  */
2491 static int scmi_handle_put(const struct scmi_handle *handle)
2492 {
2493 	struct scmi_info *info;
2494 
2495 	if (!handle)
2496 		return -EINVAL;
2497 
2498 	info = handle_to_scmi_info(handle);
2499 	mutex_lock(&scmi_list_mutex);
2500 	if (!WARN_ON(!info->users))
2501 		info->users--;
2502 	mutex_unlock(&scmi_list_mutex);
2503 
2504 	return 0;
2505 }
2506 
2507 static void scmi_device_link_add(struct device *consumer,
2508 				 struct device *supplier)
2509 {
2510 	struct device_link *link;
2511 
2512 	link = device_link_add(consumer, supplier, DL_FLAG_AUTOREMOVE_CONSUMER);
2513 
2514 	WARN_ON(!link);
2515 }
2516 
2517 static void scmi_set_handle(struct scmi_device *scmi_dev)
2518 {
2519 	scmi_dev->handle = scmi_handle_get(&scmi_dev->dev);
2520 	if (scmi_dev->handle)
2521 		scmi_device_link_add(&scmi_dev->dev, scmi_dev->handle->dev);
2522 }
2523 
2524 static int __scmi_xfer_info_init(struct scmi_info *sinfo,
2525 				 struct scmi_xfers_info *info)
2526 {
2527 	int i;
2528 	struct scmi_xfer *xfer;
2529 	struct device *dev = sinfo->dev;
2530 	const struct scmi_desc *desc = sinfo->desc;
2531 
2532 	/* Pre-allocated messages, no more than what hdr.seq can support */
2533 	if (WARN_ON(!info->max_msg || info->max_msg > MSG_TOKEN_MAX)) {
2534 		dev_err(dev,
2535 			"Invalid maximum messages %d, not in range [1 - %lu]\n",
2536 			info->max_msg, MSG_TOKEN_MAX);
2537 		return -EINVAL;
2538 	}
2539 
2540 	hash_init(info->pending_xfers);
2541 
2542 	/* Allocate a bitmask sized to hold MSG_TOKEN_MAX tokens */
2543 	info->xfer_alloc_table = devm_bitmap_zalloc(dev, MSG_TOKEN_MAX,
2544 						    GFP_KERNEL);
2545 	if (!info->xfer_alloc_table)
2546 		return -ENOMEM;
2547 
2548 	/*
2549 	 * Preallocate a number of xfers equal to max inflight messages,
2550 	 * pre-initialize the buffer pointer to pre-allocated buffers and
2551 	 * attach all of them to the free list
2552 	 */
2553 	INIT_HLIST_HEAD(&info->free_xfers);
2554 	for (i = 0; i < info->max_msg; i++) {
2555 		xfer = devm_kzalloc(dev, sizeof(*xfer), GFP_KERNEL);
2556 		if (!xfer)
2557 			return -ENOMEM;
2558 
2559 		xfer->rx.buf = devm_kcalloc(dev, sizeof(u8), desc->max_msg_size,
2560 					    GFP_KERNEL);
2561 		if (!xfer->rx.buf)
2562 			return -ENOMEM;
2563 
2564 		xfer->tx.buf = xfer->rx.buf;
2565 		init_completion(&xfer->done);
2566 		spin_lock_init(&xfer->lock);
2567 
2568 		/* Add initialized xfer to the free list */
2569 		hlist_add_head(&xfer->node, &info->free_xfers);
2570 	}
2571 
2572 	spin_lock_init(&info->xfer_lock);
2573 
2574 	return 0;
2575 }
2576 
2577 static int scmi_channels_max_msg_configure(struct scmi_info *sinfo)
2578 {
2579 	const struct scmi_desc *desc = sinfo->desc;
2580 
2581 	if (!desc->ops->get_max_msg) {
2582 		sinfo->tx_minfo.max_msg = desc->max_msg;
2583 		sinfo->rx_minfo.max_msg = desc->max_msg;
2584 	} else {
2585 		struct scmi_chan_info *base_cinfo;
2586 
2587 		base_cinfo = idr_find(&sinfo->tx_idr, SCMI_PROTOCOL_BASE);
2588 		if (!base_cinfo)
2589 			return -EINVAL;
2590 		sinfo->tx_minfo.max_msg = desc->ops->get_max_msg(base_cinfo);
2591 
2592 		/* RX channel is optional so can be skipped */
2593 		base_cinfo = idr_find(&sinfo->rx_idr, SCMI_PROTOCOL_BASE);
2594 		if (base_cinfo)
2595 			sinfo->rx_minfo.max_msg =
2596 				desc->ops->get_max_msg(base_cinfo);
2597 	}
2598 
2599 	return 0;
2600 }
2601 
2602 static int scmi_xfer_info_init(struct scmi_info *sinfo)
2603 {
2604 	int ret;
2605 
2606 	ret = scmi_channels_max_msg_configure(sinfo);
2607 	if (ret)
2608 		return ret;
2609 
2610 	ret = __scmi_xfer_info_init(sinfo, &sinfo->tx_minfo);
2611 	if (!ret && !idr_is_empty(&sinfo->rx_idr))
2612 		ret = __scmi_xfer_info_init(sinfo, &sinfo->rx_minfo);
2613 
2614 	return ret;
2615 }
2616 
2617 static int scmi_chan_setup(struct scmi_info *info, struct device_node *of_node,
2618 			   int prot_id, bool tx)
2619 {
2620 	int ret, idx;
2621 	char name[32];
2622 	struct scmi_chan_info *cinfo;
2623 	struct idr *idr;
2624 	struct scmi_device *tdev = NULL;
2625 
2626 	/* Transmit channel is first entry i.e. index 0 */
2627 	idx = tx ? 0 : 1;
2628 	idr = tx ? &info->tx_idr : &info->rx_idr;
2629 
2630 	if (!info->desc->ops->chan_available(of_node, idx)) {
2631 		cinfo = idr_find(idr, SCMI_PROTOCOL_BASE);
2632 		if (unlikely(!cinfo)) /* Possible only if platform has no Rx */
2633 			return -EINVAL;
2634 		goto idr_alloc;
2635 	}
2636 
2637 	cinfo = devm_kzalloc(info->dev, sizeof(*cinfo), GFP_KERNEL);
2638 	if (!cinfo)
2639 		return -ENOMEM;
2640 
2641 	cinfo->rx_timeout_ms = info->desc->max_rx_timeout_ms;
2642 
2643 	/* Create a unique name for this transport device */
2644 	snprintf(name, 32, "__scmi_transport_device_%s_%02X",
2645 		 idx ? "rx" : "tx", prot_id);
2646 	/* Create a uniquely named, dedicated transport device for this chan */
2647 	tdev = scmi_device_create(of_node, info->dev, prot_id, name);
2648 	if (!tdev) {
2649 		dev_err(info->dev,
2650 			"failed to create transport device (%s)\n", name);
2651 		devm_kfree(info->dev, cinfo);
2652 		return -EINVAL;
2653 	}
2654 	of_node_get(of_node);
2655 
2656 	cinfo->id = prot_id;
2657 	cinfo->dev = &tdev->dev;
2658 	ret = info->desc->ops->chan_setup(cinfo, info->dev, tx);
2659 	if (ret) {
2660 		of_node_put(of_node);
2661 		scmi_device_destroy(info->dev, prot_id, name);
2662 		devm_kfree(info->dev, cinfo);
2663 		return ret;
2664 	}
2665 
2666 	if (tx && is_polling_required(cinfo, info->desc)) {
2667 		if (is_transport_polling_capable(info->desc))
2668 			dev_info(&tdev->dev,
2669 				 "Enabled polling mode TX channel - prot_id:%d\n",
2670 				 prot_id);
2671 		else
2672 			dev_warn(&tdev->dev,
2673 				 "Polling mode NOT supported by transport.\n");
2674 	}
2675 
2676 idr_alloc:
2677 	ret = idr_alloc(idr, cinfo, prot_id, prot_id + 1, GFP_KERNEL);
2678 	if (ret != prot_id) {
2679 		dev_err(info->dev,
2680 			"unable to allocate SCMI idr slot err %d\n", ret);
2681 		/* Destroy channel and device only if created by this call. */
2682 		if (tdev) {
2683 			of_node_put(of_node);
2684 			scmi_device_destroy(info->dev, prot_id, name);
2685 			devm_kfree(info->dev, cinfo);
2686 		}
2687 		return ret;
2688 	}
2689 
2690 	cinfo->handle = &info->handle;
2691 	return 0;
2692 }
2693 
2694 static inline int
2695 scmi_txrx_setup(struct scmi_info *info, struct device_node *of_node,
2696 		int prot_id)
2697 {
2698 	int ret = scmi_chan_setup(info, of_node, prot_id, true);
2699 
2700 	if (!ret) {
2701 		/* Rx is optional, report only memory errors */
2702 		ret = scmi_chan_setup(info, of_node, prot_id, false);
2703 		if (ret && ret != -ENOMEM)
2704 			ret = 0;
2705 	}
2706 
2707 	if (ret)
2708 		dev_err(info->dev,
2709 			"failed to setup channel for protocol:0x%X\n", prot_id);
2710 
2711 	return ret;
2712 }
2713 
2714 /**
2715  * scmi_channels_setup  - Helper to initialize all required channels
2716  *
2717  * @info: The SCMI instance descriptor.
2718  *
2719  * Initialize all the channels found described in the DT against the underlying
2720  * configured transport using custom defined dedicated devices instead of
2721  * borrowing devices from the SCMI drivers; this way channels are initialized
2722  * upfront during core SCMI stack probing and are no more coupled with SCMI
2723  * devices used by SCMI drivers.
2724  *
2725  * Note that, even though a pair of TX/RX channels is associated to each
2726  * protocol defined in the DT, a distinct freshly initialized channel is
2727  * created only if the DT node for the protocol at hand describes a dedicated
2728  * channel: in all the other cases the common BASE protocol channel is reused.
2729  *
2730  * Return: 0 on Success
2731  */
2732 static int scmi_channels_setup(struct scmi_info *info)
2733 {
2734 	int ret;
2735 	struct device_node *top_np = info->dev->of_node;
2736 
2737 	/* Initialize a common generic channel at first */
2738 	ret = scmi_txrx_setup(info, top_np, SCMI_PROTOCOL_BASE);
2739 	if (ret)
2740 		return ret;
2741 
2742 	for_each_available_child_of_node_scoped(top_np, child) {
2743 		u32 prot_id;
2744 
2745 		if (of_property_read_u32(child, "reg", &prot_id))
2746 			continue;
2747 
2748 		if (!FIELD_FIT(MSG_PROTOCOL_ID_MASK, prot_id))
2749 			dev_err(info->dev,
2750 				"Out of range protocol %d\n", prot_id);
2751 
2752 		ret = scmi_txrx_setup(info, child, prot_id);
2753 		if (ret)
2754 			return ret;
2755 	}
2756 
2757 	return 0;
2758 }
2759 
2760 static int scmi_chan_destroy(int id, void *p, void *idr)
2761 {
2762 	struct scmi_chan_info *cinfo = p;
2763 
2764 	if (cinfo->dev) {
2765 		struct scmi_info *info = handle_to_scmi_info(cinfo->handle);
2766 		struct scmi_device *sdev = to_scmi_dev(cinfo->dev);
2767 
2768 		of_node_put(cinfo->dev->of_node);
2769 		scmi_device_destroy(info->dev, id, sdev->name);
2770 		cinfo->dev = NULL;
2771 	}
2772 
2773 	idr_remove(idr, id);
2774 
2775 	return 0;
2776 }
2777 
2778 static void scmi_cleanup_channels(struct scmi_info *info, struct idr *idr)
2779 {
2780 	/* At first free all channels at the transport layer ... */
2781 	idr_for_each(idr, info->desc->ops->chan_free, idr);
2782 
2783 	/* ...then destroy all underlying devices */
2784 	idr_for_each(idr, scmi_chan_destroy, idr);
2785 
2786 	idr_destroy(idr);
2787 }
2788 
2789 static void scmi_cleanup_txrx_channels(struct scmi_info *info)
2790 {
2791 	scmi_cleanup_channels(info, &info->tx_idr);
2792 
2793 	scmi_cleanup_channels(info, &info->rx_idr);
2794 }
2795 
2796 static int scmi_bus_notifier(struct notifier_block *nb,
2797 			     unsigned long action, void *data)
2798 {
2799 	struct scmi_info *info = bus_nb_to_scmi_info(nb);
2800 	struct scmi_device *sdev = to_scmi_dev(data);
2801 
2802 	/* Skip transport devices and devices of different SCMI instances */
2803 	if (!strncmp(sdev->name, "__scmi_transport_device", 23) ||
2804 	    sdev->dev.parent != info->dev)
2805 		return NOTIFY_DONE;
2806 
2807 	switch (action) {
2808 	case BUS_NOTIFY_BIND_DRIVER:
2809 		/* setup handle now as the transport is ready */
2810 		scmi_set_handle(sdev);
2811 		break;
2812 	case BUS_NOTIFY_UNBOUND_DRIVER:
2813 		scmi_handle_put(sdev->handle);
2814 		sdev->handle = NULL;
2815 		break;
2816 	default:
2817 		return NOTIFY_DONE;
2818 	}
2819 
2820 	dev_dbg(info->dev, "Device %s (%s) is now %s\n", dev_name(&sdev->dev),
2821 		sdev->name, action == BUS_NOTIFY_BIND_DRIVER ?
2822 		"about to be BOUND." : "UNBOUND.");
2823 
2824 	return NOTIFY_OK;
2825 }
2826 
2827 static int scmi_device_request_notifier(struct notifier_block *nb,
2828 					unsigned long action, void *data)
2829 {
2830 	struct device_node *np;
2831 	struct scmi_device_id *id_table = data;
2832 	struct scmi_info *info = req_nb_to_scmi_info(nb);
2833 
2834 	np = idr_find(&info->active_protocols, id_table->protocol_id);
2835 	if (!np)
2836 		return NOTIFY_DONE;
2837 
2838 	dev_dbg(info->dev, "%sRequested device (%s) for protocol 0x%x\n",
2839 		action == SCMI_BUS_NOTIFY_DEVICE_REQUEST ? "" : "UN-",
2840 		id_table->name, id_table->protocol_id);
2841 
2842 	switch (action) {
2843 	case SCMI_BUS_NOTIFY_DEVICE_REQUEST:
2844 		scmi_create_protocol_devices(np, info, id_table->protocol_id,
2845 					     id_table->name);
2846 		break;
2847 	case SCMI_BUS_NOTIFY_DEVICE_UNREQUEST:
2848 		scmi_destroy_protocol_devices(info, id_table->protocol_id,
2849 					      id_table->name);
2850 		break;
2851 	default:
2852 		return NOTIFY_DONE;
2853 	}
2854 
2855 	return NOTIFY_OK;
2856 }
2857 
2858 static const char * const dbg_counter_strs[] = {
2859 	"sent_ok",
2860 	"sent_fail",
2861 	"sent_fail_polling_unsupported",
2862 	"sent_fail_channel_not_found",
2863 	"response_ok",
2864 	"notification_ok",
2865 	"delayed_response_ok",
2866 	"xfers_response_timeout",
2867 	"xfers_response_polled_timeout",
2868 	"response_polled_ok",
2869 	"err_msg_unexpected",
2870 	"err_msg_invalid",
2871 	"err_msg_nomem",
2872 	"err_protocol",
2873 };
2874 
2875 static ssize_t reset_all_on_write(struct file *filp, const char __user *buf,
2876 				  size_t count, loff_t *ppos)
2877 {
2878 	struct scmi_debug_info *dbg = filp->private_data;
2879 
2880 	for (int i = 0; i < SCMI_DEBUG_COUNTERS_LAST; i++)
2881 		atomic_set(&dbg->counters[i], 0);
2882 
2883 	return count;
2884 }
2885 
2886 static const struct file_operations fops_reset_counts = {
2887 	.owner = THIS_MODULE,
2888 	.open = simple_open,
2889 	.write = reset_all_on_write,
2890 };
2891 
2892 static void scmi_debugfs_counters_setup(struct scmi_debug_info *dbg,
2893 					struct dentry *trans)
2894 {
2895 	struct dentry *counters;
2896 	int idx;
2897 
2898 	counters = debugfs_create_dir("counters", trans);
2899 
2900 	for (idx = 0; idx < SCMI_DEBUG_COUNTERS_LAST; idx++)
2901 		debugfs_create_atomic_t(dbg_counter_strs[idx], 0600, counters,
2902 					&dbg->counters[idx]);
2903 
2904 	debugfs_create_file("reset", 0200, counters, dbg, &fops_reset_counts);
2905 }
2906 
2907 static void scmi_debugfs_common_cleanup(void *d)
2908 {
2909 	struct scmi_debug_info *dbg = d;
2910 
2911 	if (!dbg)
2912 		return;
2913 
2914 	debugfs_remove_recursive(dbg->top_dentry);
2915 	kfree(dbg->name);
2916 	kfree(dbg->type);
2917 }
2918 
2919 static struct scmi_debug_info *scmi_debugfs_common_setup(struct scmi_info *info)
2920 {
2921 	char top_dir[16];
2922 	struct dentry *trans, *top_dentry;
2923 	struct scmi_debug_info *dbg;
2924 	const char *c_ptr = NULL;
2925 
2926 	dbg = devm_kzalloc(info->dev, sizeof(*dbg), GFP_KERNEL);
2927 	if (!dbg)
2928 		return NULL;
2929 
2930 	dbg->name = kstrdup(of_node_full_name(info->dev->of_node), GFP_KERNEL);
2931 	if (!dbg->name) {
2932 		devm_kfree(info->dev, dbg);
2933 		return NULL;
2934 	}
2935 
2936 	of_property_read_string(info->dev->of_node, "compatible", &c_ptr);
2937 	dbg->type = kstrdup(c_ptr, GFP_KERNEL);
2938 	if (!dbg->type) {
2939 		kfree(dbg->name);
2940 		devm_kfree(info->dev, dbg);
2941 		return NULL;
2942 	}
2943 
2944 	snprintf(top_dir, 16, "%d", info->id);
2945 	top_dentry = debugfs_create_dir(top_dir, scmi_top_dentry);
2946 	trans = debugfs_create_dir("transport", top_dentry);
2947 
2948 	dbg->is_atomic = info->desc->atomic_enabled &&
2949 				is_transport_polling_capable(info->desc);
2950 
2951 	debugfs_create_str("instance_name", 0400, top_dentry,
2952 			   (char **)&dbg->name);
2953 
2954 	debugfs_create_u32("atomic_threshold_us", 0400, top_dentry,
2955 			   &info->atomic_threshold);
2956 
2957 	debugfs_create_str("type", 0400, trans, (char **)&dbg->type);
2958 
2959 	debugfs_create_bool("is_atomic", 0400, trans, &dbg->is_atomic);
2960 
2961 	debugfs_create_u32("max_rx_timeout_ms", 0400, trans,
2962 			   (u32 *)&info->desc->max_rx_timeout_ms);
2963 
2964 	debugfs_create_u32("max_msg_size", 0400, trans,
2965 			   (u32 *)&info->desc->max_msg_size);
2966 
2967 	debugfs_create_u32("tx_max_msg", 0400, trans,
2968 			   (u32 *)&info->tx_minfo.max_msg);
2969 
2970 	debugfs_create_u32("rx_max_msg", 0400, trans,
2971 			   (u32 *)&info->rx_minfo.max_msg);
2972 
2973 	if (IS_ENABLED(CONFIG_ARM_SCMI_DEBUG_COUNTERS))
2974 		scmi_debugfs_counters_setup(dbg, trans);
2975 
2976 	dbg->top_dentry = top_dentry;
2977 
2978 	if (devm_add_action_or_reset(info->dev,
2979 				     scmi_debugfs_common_cleanup, dbg)) {
2980 		scmi_debugfs_common_cleanup(dbg);
2981 		return NULL;
2982 	}
2983 
2984 	return dbg;
2985 }
2986 
2987 static int scmi_debugfs_raw_mode_setup(struct scmi_info *info)
2988 {
2989 	int id, num_chans = 0, ret = 0;
2990 	struct scmi_chan_info *cinfo;
2991 	u8 channels[SCMI_MAX_CHANNELS] = {};
2992 	DECLARE_BITMAP(protos, SCMI_MAX_CHANNELS) = {};
2993 
2994 	if (!info->dbg)
2995 		return -EINVAL;
2996 
2997 	/* Enumerate all channels to collect their ids */
2998 	idr_for_each_entry(&info->tx_idr, cinfo, id) {
2999 		/*
3000 		 * Cannot happen, but be defensive.
3001 		 * Zero as num_chans is ok, warn and carry on.
3002 		 */
3003 		if (num_chans >= SCMI_MAX_CHANNELS || !cinfo) {
3004 			dev_warn(info->dev,
3005 				 "SCMI RAW - Error enumerating channels\n");
3006 			break;
3007 		}
3008 
3009 		if (!test_bit(cinfo->id, protos)) {
3010 			channels[num_chans++] = cinfo->id;
3011 			set_bit(cinfo->id, protos);
3012 		}
3013 	}
3014 
3015 	info->raw = scmi_raw_mode_init(&info->handle, info->dbg->top_dentry,
3016 				       info->id, channels, num_chans,
3017 				       info->desc, info->tx_minfo.max_msg);
3018 	if (IS_ERR(info->raw)) {
3019 		dev_err(info->dev, "Failed to initialize SCMI RAW Mode !\n");
3020 		ret = PTR_ERR(info->raw);
3021 		info->raw = NULL;
3022 	}
3023 
3024 	return ret;
3025 }
3026 
3027 static const struct scmi_desc *scmi_transport_setup(struct device *dev)
3028 {
3029 	struct scmi_transport *trans;
3030 	int ret;
3031 
3032 	trans = dev_get_platdata(dev);
3033 	if (!trans || !trans->desc || !trans->supplier || !trans->core_ops)
3034 		return NULL;
3035 
3036 	if (!device_link_add(dev, trans->supplier, DL_FLAG_AUTOREMOVE_CONSUMER)) {
3037 		dev_err(dev,
3038 			"Adding link to supplier transport device failed\n");
3039 		return NULL;
3040 	}
3041 
3042 	/* Provide core transport ops */
3043 	*trans->core_ops = &scmi_trans_core_ops;
3044 
3045 	dev_info(dev, "Using %s\n", dev_driver_string(trans->supplier));
3046 
3047 	ret = of_property_read_u32(dev->of_node, "max-rx-timeout-ms",
3048 				   &trans->desc->max_rx_timeout_ms);
3049 	if (ret && ret != -EINVAL)
3050 		dev_err(dev, "Malformed max-rx-timeout-ms DT property.\n");
3051 
3052 	dev_info(dev, "SCMI max-rx-timeout: %dms\n",
3053 		 trans->desc->max_rx_timeout_ms);
3054 
3055 	return trans->desc;
3056 }
3057 
3058 static int scmi_probe(struct platform_device *pdev)
3059 {
3060 	int ret;
3061 	char *err_str = "probe failure\n";
3062 	struct scmi_handle *handle;
3063 	const struct scmi_desc *desc;
3064 	struct scmi_info *info;
3065 	bool coex = IS_ENABLED(CONFIG_ARM_SCMI_RAW_MODE_SUPPORT_COEX);
3066 	struct device *dev = &pdev->dev;
3067 	struct device_node *child, *np = dev->of_node;
3068 
3069 	desc = scmi_transport_setup(dev);
3070 	if (!desc) {
3071 		err_str = "transport invalid\n";
3072 		ret = -EINVAL;
3073 		goto out_err;
3074 	}
3075 
3076 	info = devm_kzalloc(dev, sizeof(*info), GFP_KERNEL);
3077 	if (!info)
3078 		return -ENOMEM;
3079 
3080 	info->id = ida_alloc_min(&scmi_id, 0, GFP_KERNEL);
3081 	if (info->id < 0)
3082 		return info->id;
3083 
3084 	info->dev = dev;
3085 	info->desc = desc;
3086 	info->bus_nb.notifier_call = scmi_bus_notifier;
3087 	info->dev_req_nb.notifier_call = scmi_device_request_notifier;
3088 	INIT_LIST_HEAD(&info->node);
3089 	idr_init(&info->protocols);
3090 	mutex_init(&info->protocols_mtx);
3091 	idr_init(&info->active_protocols);
3092 	mutex_init(&info->devreq_mtx);
3093 
3094 	platform_set_drvdata(pdev, info);
3095 	idr_init(&info->tx_idr);
3096 	idr_init(&info->rx_idr);
3097 
3098 	handle = &info->handle;
3099 	handle->dev = info->dev;
3100 	handle->version = &info->version;
3101 	handle->devm_protocol_acquire = scmi_devm_protocol_acquire;
3102 	handle->devm_protocol_get = scmi_devm_protocol_get;
3103 	handle->devm_protocol_put = scmi_devm_protocol_put;
3104 
3105 	/* System wide atomic threshold for atomic ops .. if any */
3106 	if (!of_property_read_u32(np, "atomic-threshold-us",
3107 				  &info->atomic_threshold))
3108 		dev_info(dev,
3109 			 "SCMI System wide atomic threshold set to %d us\n",
3110 			 info->atomic_threshold);
3111 	handle->is_transport_atomic = scmi_is_transport_atomic;
3112 
3113 	/* Setup all channels described in the DT at first */
3114 	ret = scmi_channels_setup(info);
3115 	if (ret) {
3116 		err_str = "failed to setup channels\n";
3117 		goto clear_ida;
3118 	}
3119 
3120 	ret = bus_register_notifier(&scmi_bus_type, &info->bus_nb);
3121 	if (ret) {
3122 		err_str = "failed to register bus notifier\n";
3123 		goto clear_txrx_setup;
3124 	}
3125 
3126 	ret = blocking_notifier_chain_register(&scmi_requested_devices_nh,
3127 					       &info->dev_req_nb);
3128 	if (ret) {
3129 		err_str = "failed to register device notifier\n";
3130 		goto clear_bus_notifier;
3131 	}
3132 
3133 	ret = scmi_xfer_info_init(info);
3134 	if (ret) {
3135 		err_str = "failed to init xfers pool\n";
3136 		goto clear_dev_req_notifier;
3137 	}
3138 
3139 	if (scmi_top_dentry) {
3140 		info->dbg = scmi_debugfs_common_setup(info);
3141 		if (!info->dbg)
3142 			dev_warn(dev, "Failed to setup SCMI debugfs.\n");
3143 
3144 		if (IS_ENABLED(CONFIG_ARM_SCMI_RAW_MODE_SUPPORT)) {
3145 			ret = scmi_debugfs_raw_mode_setup(info);
3146 			if (!coex) {
3147 				if (ret)
3148 					goto clear_dev_req_notifier;
3149 
3150 				/* Bail out anyway when coex disabled. */
3151 				return 0;
3152 			}
3153 
3154 			/* Coex enabled, carry on in any case. */
3155 			dev_info(dev, "SCMI RAW Mode COEX enabled !\n");
3156 		}
3157 	}
3158 
3159 	if (scmi_notification_init(handle))
3160 		dev_err(dev, "SCMI Notifications NOT available.\n");
3161 
3162 	if (info->desc->atomic_enabled &&
3163 	    !is_transport_polling_capable(info->desc))
3164 		dev_err(dev,
3165 			"Transport is not polling capable. Atomic mode not supported.\n");
3166 
3167 	/*
3168 	 * Trigger SCMI Base protocol initialization.
3169 	 * It's mandatory and won't be ever released/deinit until the
3170 	 * SCMI stack is shutdown/unloaded as a whole.
3171 	 */
3172 	ret = scmi_protocol_acquire(handle, SCMI_PROTOCOL_BASE);
3173 	if (ret) {
3174 		err_str = "unable to communicate with SCMI\n";
3175 		if (coex) {
3176 			dev_err(dev, "%s", err_str);
3177 			return 0;
3178 		}
3179 		goto notification_exit;
3180 	}
3181 
3182 	mutex_lock(&scmi_list_mutex);
3183 	list_add_tail(&info->node, &scmi_list);
3184 	mutex_unlock(&scmi_list_mutex);
3185 
3186 	for_each_available_child_of_node(np, child) {
3187 		u32 prot_id;
3188 
3189 		if (of_property_read_u32(child, "reg", &prot_id))
3190 			continue;
3191 
3192 		if (!FIELD_FIT(MSG_PROTOCOL_ID_MASK, prot_id))
3193 			dev_err(dev, "Out of range protocol %d\n", prot_id);
3194 
3195 		if (!scmi_is_protocol_implemented(handle, prot_id)) {
3196 			dev_err(dev, "SCMI protocol %d not implemented\n",
3197 				prot_id);
3198 			continue;
3199 		}
3200 
3201 		/*
3202 		 * Save this valid DT protocol descriptor amongst
3203 		 * @active_protocols for this SCMI instance/
3204 		 */
3205 		ret = idr_alloc(&info->active_protocols, child,
3206 				prot_id, prot_id + 1, GFP_KERNEL);
3207 		if (ret != prot_id) {
3208 			dev_err(dev, "SCMI protocol %d already activated. Skip\n",
3209 				prot_id);
3210 			continue;
3211 		}
3212 
3213 		of_node_get(child);
3214 		scmi_create_protocol_devices(child, info, prot_id, NULL);
3215 	}
3216 
3217 	return 0;
3218 
3219 notification_exit:
3220 	if (IS_ENABLED(CONFIG_ARM_SCMI_RAW_MODE_SUPPORT))
3221 		scmi_raw_mode_cleanup(info->raw);
3222 	scmi_notification_exit(&info->handle);
3223 clear_dev_req_notifier:
3224 	blocking_notifier_chain_unregister(&scmi_requested_devices_nh,
3225 					   &info->dev_req_nb);
3226 clear_bus_notifier:
3227 	bus_unregister_notifier(&scmi_bus_type, &info->bus_nb);
3228 clear_txrx_setup:
3229 	scmi_cleanup_txrx_channels(info);
3230 clear_ida:
3231 	ida_free(&scmi_id, info->id);
3232 
3233 out_err:
3234 	return dev_err_probe(dev, ret, "%s", err_str);
3235 }
3236 
3237 static void scmi_remove(struct platform_device *pdev)
3238 {
3239 	int id;
3240 	struct scmi_info *info = platform_get_drvdata(pdev);
3241 	struct device_node *child;
3242 
3243 	if (IS_ENABLED(CONFIG_ARM_SCMI_RAW_MODE_SUPPORT))
3244 		scmi_raw_mode_cleanup(info->raw);
3245 
3246 	mutex_lock(&scmi_list_mutex);
3247 	if (info->users)
3248 		dev_warn(&pdev->dev,
3249 			 "Still active SCMI users will be forcibly unbound.\n");
3250 	list_del(&info->node);
3251 	mutex_unlock(&scmi_list_mutex);
3252 
3253 	scmi_notification_exit(&info->handle);
3254 
3255 	mutex_lock(&info->protocols_mtx);
3256 	idr_destroy(&info->protocols);
3257 	mutex_unlock(&info->protocols_mtx);
3258 
3259 	idr_for_each_entry(&info->active_protocols, child, id)
3260 		of_node_put(child);
3261 	idr_destroy(&info->active_protocols);
3262 
3263 	blocking_notifier_chain_unregister(&scmi_requested_devices_nh,
3264 					   &info->dev_req_nb);
3265 	bus_unregister_notifier(&scmi_bus_type, &info->bus_nb);
3266 
3267 	/* Safe to free channels since no more users */
3268 	scmi_cleanup_txrx_channels(info);
3269 
3270 	ida_free(&scmi_id, info->id);
3271 }
3272 
3273 static ssize_t protocol_version_show(struct device *dev,
3274 				     struct device_attribute *attr, char *buf)
3275 {
3276 	struct scmi_info *info = dev_get_drvdata(dev);
3277 
3278 	return sprintf(buf, "%u.%u\n", info->version.major_ver,
3279 		       info->version.minor_ver);
3280 }
3281 static DEVICE_ATTR_RO(protocol_version);
3282 
3283 static ssize_t firmware_version_show(struct device *dev,
3284 				     struct device_attribute *attr, char *buf)
3285 {
3286 	struct scmi_info *info = dev_get_drvdata(dev);
3287 
3288 	return sprintf(buf, "0x%x\n", info->version.impl_ver);
3289 }
3290 static DEVICE_ATTR_RO(firmware_version);
3291 
3292 static ssize_t vendor_id_show(struct device *dev,
3293 			      struct device_attribute *attr, char *buf)
3294 {
3295 	struct scmi_info *info = dev_get_drvdata(dev);
3296 
3297 	return sprintf(buf, "%s\n", info->version.vendor_id);
3298 }
3299 static DEVICE_ATTR_RO(vendor_id);
3300 
3301 static ssize_t sub_vendor_id_show(struct device *dev,
3302 				  struct device_attribute *attr, char *buf)
3303 {
3304 	struct scmi_info *info = dev_get_drvdata(dev);
3305 
3306 	return sprintf(buf, "%s\n", info->version.sub_vendor_id);
3307 }
3308 static DEVICE_ATTR_RO(sub_vendor_id);
3309 
3310 static struct attribute *versions_attrs[] = {
3311 	&dev_attr_firmware_version.attr,
3312 	&dev_attr_protocol_version.attr,
3313 	&dev_attr_vendor_id.attr,
3314 	&dev_attr_sub_vendor_id.attr,
3315 	NULL,
3316 };
3317 ATTRIBUTE_GROUPS(versions);
3318 
3319 static struct platform_driver scmi_driver = {
3320 	.driver = {
3321 		   .name = "arm-scmi",
3322 		   .suppress_bind_attrs = true,
3323 		   .dev_groups = versions_groups,
3324 		   },
3325 	.probe = scmi_probe,
3326 	.remove_new = scmi_remove,
3327 };
3328 
3329 static struct dentry *scmi_debugfs_init(void)
3330 {
3331 	struct dentry *d;
3332 
3333 	d = debugfs_create_dir("scmi", NULL);
3334 	if (IS_ERR(d)) {
3335 		pr_err("Could NOT create SCMI top dentry.\n");
3336 		return NULL;
3337 	}
3338 
3339 	return d;
3340 }
3341 
3342 static int __init scmi_driver_init(void)
3343 {
3344 	/* Bail out if no SCMI transport was configured */
3345 	if (WARN_ON(!IS_ENABLED(CONFIG_ARM_SCMI_HAVE_TRANSPORT)))
3346 		return -EINVAL;
3347 
3348 	if (IS_ENABLED(CONFIG_ARM_SCMI_HAVE_SHMEM))
3349 		scmi_trans_core_ops.shmem = scmi_shared_mem_operations_get();
3350 
3351 	if (IS_ENABLED(CONFIG_ARM_SCMI_HAVE_MSG))
3352 		scmi_trans_core_ops.msg = scmi_message_operations_get();
3353 
3354 	if (IS_ENABLED(CONFIG_ARM_SCMI_NEED_DEBUGFS))
3355 		scmi_top_dentry = scmi_debugfs_init();
3356 
3357 	scmi_base_register();
3358 
3359 	scmi_clock_register();
3360 	scmi_perf_register();
3361 	scmi_power_register();
3362 	scmi_reset_register();
3363 	scmi_sensors_register();
3364 	scmi_voltage_register();
3365 	scmi_system_register();
3366 	scmi_powercap_register();
3367 	scmi_pinctrl_register();
3368 
3369 	return platform_driver_register(&scmi_driver);
3370 }
3371 module_init(scmi_driver_init);
3372 
3373 static void __exit scmi_driver_exit(void)
3374 {
3375 	scmi_base_unregister();
3376 
3377 	scmi_clock_unregister();
3378 	scmi_perf_unregister();
3379 	scmi_power_unregister();
3380 	scmi_reset_unregister();
3381 	scmi_sensors_unregister();
3382 	scmi_voltage_unregister();
3383 	scmi_system_unregister();
3384 	scmi_powercap_unregister();
3385 	scmi_pinctrl_unregister();
3386 
3387 	platform_driver_unregister(&scmi_driver);
3388 
3389 	debugfs_remove_recursive(scmi_top_dentry);
3390 }
3391 module_exit(scmi_driver_exit);
3392 
3393 MODULE_ALIAS("platform:arm-scmi");
3394 MODULE_AUTHOR("Sudeep Holla <sudeep.holla@arm.com>");
3395 MODULE_DESCRIPTION("ARM SCMI protocol driver");
3396 MODULE_LICENSE("GPL v2");
3397