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-2021 ARM Ltd.
15  */
16 
17 #include <linux/bitmap.h>
18 #include <linux/device.h>
19 #include <linux/export.h>
20 #include <linux/idr.h>
21 #include <linux/io.h>
22 #include <linux/kernel.h>
23 #include <linux/ktime.h>
24 #include <linux/hashtable.h>
25 #include <linux/list.h>
26 #include <linux/module.h>
27 #include <linux/of_address.h>
28 #include <linux/of_device.h>
29 #include <linux/processor.h>
30 #include <linux/refcount.h>
31 #include <linux/slab.h>
32 
33 #include "common.h"
34 #include "notify.h"
35 
36 #define CREATE_TRACE_POINTS
37 #include <trace/events/scmi.h>
38 
39 enum scmi_error_codes {
40 	SCMI_SUCCESS = 0,	/* Success */
41 	SCMI_ERR_SUPPORT = -1,	/* Not supported */
42 	SCMI_ERR_PARAMS = -2,	/* Invalid Parameters */
43 	SCMI_ERR_ACCESS = -3,	/* Invalid access/permission denied */
44 	SCMI_ERR_ENTRY = -4,	/* Not found */
45 	SCMI_ERR_RANGE = -5,	/* Value out of range */
46 	SCMI_ERR_BUSY = -6,	/* Device busy */
47 	SCMI_ERR_COMMS = -7,	/* Communication Error */
48 	SCMI_ERR_GENERIC = -8,	/* Generic Error */
49 	SCMI_ERR_HARDWARE = -9,	/* Hardware Error */
50 	SCMI_ERR_PROTOCOL = -10,/* Protocol Error */
51 };
52 
53 /* List of all SCMI devices active in system */
54 static LIST_HEAD(scmi_list);
55 /* Protection for the entire list */
56 static DEFINE_MUTEX(scmi_list_mutex);
57 /* Track the unique id for the transfers for debug & profiling purpose */
58 static atomic_t transfer_last_id;
59 
60 static DEFINE_IDR(scmi_requested_devices);
61 static DEFINE_MUTEX(scmi_requested_devices_mtx);
62 
63 struct scmi_requested_dev {
64 	const struct scmi_device_id *id_table;
65 	struct list_head node;
66 };
67 
68 /**
69  * struct scmi_xfers_info - Structure to manage transfer information
70  *
71  * @xfer_alloc_table: Bitmap table for allocated messages.
72  *	Index of this bitmap table is also used for message
73  *	sequence identifier.
74  * @xfer_lock: Protection for message allocation
75  * @max_msg: Maximum number of messages that can be pending
76  * @free_xfers: A free list for available to use xfers. It is initialized with
77  *		a number of xfers equal to the maximum allowed in-flight
78  *		messages.
79  * @pending_xfers: An hashtable, indexed by msg_hdr.seq, used to keep all the
80  *		   currently in-flight messages.
81  */
82 struct scmi_xfers_info {
83 	unsigned long *xfer_alloc_table;
84 	spinlock_t xfer_lock;
85 	int max_msg;
86 	struct hlist_head free_xfers;
87 	DECLARE_HASHTABLE(pending_xfers, SCMI_PENDING_XFERS_HT_ORDER_SZ);
88 };
89 
90 /**
91  * struct scmi_protocol_instance  - Describe an initialized protocol instance.
92  * @handle: Reference to the SCMI handle associated to this protocol instance.
93  * @proto: A reference to the protocol descriptor.
94  * @gid: A reference for per-protocol devres management.
95  * @users: A refcount to track effective users of this protocol.
96  * @priv: Reference for optional protocol private data.
97  * @ph: An embedded protocol handle that will be passed down to protocol
98  *	initialization code to identify this instance.
99  *
100  * Each protocol is initialized independently once for each SCMI platform in
101  * which is defined by DT and implemented by the SCMI server fw.
102  */
103 struct scmi_protocol_instance {
104 	const struct scmi_handle	*handle;
105 	const struct scmi_protocol	*proto;
106 	void				*gid;
107 	refcount_t			users;
108 	void				*priv;
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_info - Structure representing a SCMI instance
116  *
117  * @dev: Device pointer
118  * @desc: SoC description for this instance
119  * @version: SCMI revision information containing protocol version,
120  *	implementation version and (sub-)vendor identification.
121  * @handle: Instance of SCMI handle to send to clients
122  * @tx_minfo: Universal Transmit Message management info
123  * @rx_minfo: Universal Receive Message management info
124  * @tx_idr: IDR object to map protocol id to Tx channel info pointer
125  * @rx_idr: IDR object to map protocol id to Rx channel info pointer
126  * @protocols: IDR for protocols' instance descriptors initialized for
127  *	       this SCMI instance: populated on protocol's first attempted
128  *	       usage.
129  * @protocols_mtx: A mutex to protect protocols instances initialization.
130  * @protocols_imp: List of protocols implemented, currently maximum of
131  *		   scmi_revision_info.num_protocols elements allocated by the
132  *		   base protocol
133  * @active_protocols: IDR storing device_nodes for protocols actually defined
134  *		      in the DT and confirmed as implemented by fw.
135  * @atomic_threshold: Optional system wide DT-configured threshold, expressed
136  *		      in microseconds, for atomic operations.
137  *		      Only SCMI synchronous commands reported by the platform
138  *		      to have an execution latency lesser-equal to the threshold
139  *		      should be considered for atomic mode operation: such
140  *		      decision is finally left up to the SCMI drivers.
141  * @notify_priv: Pointer to private data structure specific to notifications.
142  * @node: List head
143  * @users: Number of users of this instance
144  */
145 struct scmi_info {
146 	struct device *dev;
147 	const struct scmi_desc *desc;
148 	struct scmi_revision_info version;
149 	struct scmi_handle handle;
150 	struct scmi_xfers_info tx_minfo;
151 	struct scmi_xfers_info rx_minfo;
152 	struct idr tx_idr;
153 	struct idr rx_idr;
154 	struct idr protocols;
155 	/* Ensure mutual exclusive access to protocols instance array */
156 	struct mutex protocols_mtx;
157 	u8 *protocols_imp;
158 	struct idr active_protocols;
159 	unsigned int atomic_threshold;
160 	void *notify_priv;
161 	struct list_head node;
162 	int users;
163 };
164 
165 #define handle_to_scmi_info(h)	container_of(h, struct scmi_info, handle)
166 
167 static const int scmi_linux_errmap[] = {
168 	/* better than switch case as long as return value is continuous */
169 	0,			/* SCMI_SUCCESS */
170 	-EOPNOTSUPP,		/* SCMI_ERR_SUPPORT */
171 	-EINVAL,		/* SCMI_ERR_PARAM */
172 	-EACCES,		/* SCMI_ERR_ACCESS */
173 	-ENOENT,		/* SCMI_ERR_ENTRY */
174 	-ERANGE,		/* SCMI_ERR_RANGE */
175 	-EBUSY,			/* SCMI_ERR_BUSY */
176 	-ECOMM,			/* SCMI_ERR_COMMS */
177 	-EIO,			/* SCMI_ERR_GENERIC */
178 	-EREMOTEIO,		/* SCMI_ERR_HARDWARE */
179 	-EPROTO,		/* SCMI_ERR_PROTOCOL */
180 };
181 
182 static inline int scmi_to_linux_errno(int errno)
183 {
184 	int err_idx = -errno;
185 
186 	if (err_idx >= SCMI_SUCCESS && err_idx < ARRAY_SIZE(scmi_linux_errmap))
187 		return scmi_linux_errmap[err_idx];
188 	return -EIO;
189 }
190 
191 void scmi_notification_instance_data_set(const struct scmi_handle *handle,
192 					 void *priv)
193 {
194 	struct scmi_info *info = handle_to_scmi_info(handle);
195 
196 	info->notify_priv = priv;
197 	/* Ensure updated protocol private date are visible */
198 	smp_wmb();
199 }
200 
201 void *scmi_notification_instance_data_get(const struct scmi_handle *handle)
202 {
203 	struct scmi_info *info = handle_to_scmi_info(handle);
204 
205 	/* Ensure protocols_private_data has been updated */
206 	smp_rmb();
207 	return info->notify_priv;
208 }
209 
210 /**
211  * scmi_xfer_token_set  - Reserve and set new token for the xfer at hand
212  *
213  * @minfo: Pointer to Tx/Rx Message management info based on channel type
214  * @xfer: The xfer to act upon
215  *
216  * Pick the next unused monotonically increasing token and set it into
217  * xfer->hdr.seq: picking a monotonically increasing value avoids immediate
218  * reuse of freshly completed or timed-out xfers, thus mitigating the risk
219  * of incorrect association of a late and expired xfer with a live in-flight
220  * transaction, both happening to re-use the same token identifier.
221  *
222  * Since platform is NOT required to answer our request in-order we should
223  * account for a few rare but possible scenarios:
224  *
225  *  - exactly 'next_token' may be NOT available so pick xfer_id >= next_token
226  *    using find_next_zero_bit() starting from candidate next_token bit
227  *
228  *  - all tokens ahead upto (MSG_TOKEN_ID_MASK - 1) are used in-flight but we
229  *    are plenty of free tokens at start, so try a second pass using
230  *    find_next_zero_bit() and starting from 0.
231  *
232  *  X = used in-flight
233  *
234  * Normal
235  * ------
236  *
237  *		|- xfer_id picked
238  *   -----------+----------------------------------------------------------
239  *   | | |X|X|X| | | | | | ... ... ... ... ... ... ... ... ... ... ...|X|X|
240  *   ----------------------------------------------------------------------
241  *		^
242  *		|- next_token
243  *
244  * Out-of-order pending at start
245  * -----------------------------
246  *
247  *	  |- xfer_id picked, last_token fixed
248  *   -----+----------------------------------------------------------------
249  *   |X|X| | | | |X|X| ... ... ... ... ... ... ... ... ... ... ... ...|X| |
250  *   ----------------------------------------------------------------------
251  *    ^
252  *    |- next_token
253  *
254  *
255  * Out-of-order pending at end
256  * ---------------------------
257  *
258  *	  |- xfer_id picked, last_token fixed
259  *   -----+----------------------------------------------------------------
260  *   |X|X| | | | |X|X| ... ... ... ... ... ... ... ... ... ... |X|X|X||X|X|
261  *   ----------------------------------------------------------------------
262  *								^
263  *								|- next_token
264  *
265  * Context: Assumes to be called with @xfer_lock already acquired.
266  *
267  * Return: 0 on Success or error
268  */
269 static int scmi_xfer_token_set(struct scmi_xfers_info *minfo,
270 			       struct scmi_xfer *xfer)
271 {
272 	unsigned long xfer_id, next_token;
273 
274 	/*
275 	 * Pick a candidate monotonic token in range [0, MSG_TOKEN_MAX - 1]
276 	 * using the pre-allocated transfer_id as a base.
277 	 * Note that the global transfer_id is shared across all message types
278 	 * so there could be holes in the allocated set of monotonic sequence
279 	 * numbers, but that is going to limit the effectiveness of the
280 	 * mitigation only in very rare limit conditions.
281 	 */
282 	next_token = (xfer->transfer_id & (MSG_TOKEN_MAX - 1));
283 
284 	/* Pick the next available xfer_id >= next_token */
285 	xfer_id = find_next_zero_bit(minfo->xfer_alloc_table,
286 				     MSG_TOKEN_MAX, next_token);
287 	if (xfer_id == MSG_TOKEN_MAX) {
288 		/*
289 		 * After heavily out-of-order responses, there are no free
290 		 * tokens ahead, but only at start of xfer_alloc_table so
291 		 * try again from the beginning.
292 		 */
293 		xfer_id = find_next_zero_bit(minfo->xfer_alloc_table,
294 					     MSG_TOKEN_MAX, 0);
295 		/*
296 		 * Something is wrong if we got here since there can be a
297 		 * maximum number of (MSG_TOKEN_MAX - 1) in-flight messages
298 		 * but we have not found any free token [0, MSG_TOKEN_MAX - 1].
299 		 */
300 		if (WARN_ON_ONCE(xfer_id == MSG_TOKEN_MAX))
301 			return -ENOMEM;
302 	}
303 
304 	/* Update +/- last_token accordingly if we skipped some hole */
305 	if (xfer_id != next_token)
306 		atomic_add((int)(xfer_id - next_token), &transfer_last_id);
307 
308 	/* Set in-flight */
309 	set_bit(xfer_id, minfo->xfer_alloc_table);
310 	xfer->hdr.seq = (u16)xfer_id;
311 
312 	return 0;
313 }
314 
315 /**
316  * scmi_xfer_token_clear  - Release the token
317  *
318  * @minfo: Pointer to Tx/Rx Message management info based on channel type
319  * @xfer: The xfer to act upon
320  */
321 static inline void scmi_xfer_token_clear(struct scmi_xfers_info *minfo,
322 					 struct scmi_xfer *xfer)
323 {
324 	clear_bit(xfer->hdr.seq, minfo->xfer_alloc_table);
325 }
326 
327 /**
328  * scmi_xfer_get() - Allocate one message
329  *
330  * @handle: Pointer to SCMI entity handle
331  * @minfo: Pointer to Tx/Rx Message management info based on channel type
332  * @set_pending: If true a monotonic token is picked and the xfer is added to
333  *		 the pending hash table.
334  *
335  * Helper function which is used by various message functions that are
336  * exposed to clients of this driver for allocating a message traffic event.
337  *
338  * Picks an xfer from the free list @free_xfers (if any available) and, if
339  * required, sets a monotonically increasing token and stores the inflight xfer
340  * into the @pending_xfers hashtable for later retrieval.
341  *
342  * The successfully initialized xfer is refcounted.
343  *
344  * Context: Holds @xfer_lock while manipulating @xfer_alloc_table and
345  *	    @free_xfers.
346  *
347  * Return: 0 if all went fine, else corresponding error.
348  */
349 static struct scmi_xfer *scmi_xfer_get(const struct scmi_handle *handle,
350 				       struct scmi_xfers_info *minfo,
351 				       bool set_pending)
352 {
353 	int ret;
354 	unsigned long flags;
355 	struct scmi_xfer *xfer;
356 
357 	spin_lock_irqsave(&minfo->xfer_lock, flags);
358 	if (hlist_empty(&minfo->free_xfers)) {
359 		spin_unlock_irqrestore(&minfo->xfer_lock, flags);
360 		return ERR_PTR(-ENOMEM);
361 	}
362 
363 	/* grab an xfer from the free_list */
364 	xfer = hlist_entry(minfo->free_xfers.first, struct scmi_xfer, node);
365 	hlist_del_init(&xfer->node);
366 
367 	/*
368 	 * Allocate transfer_id early so that can be used also as base for
369 	 * monotonic sequence number generation if needed.
370 	 */
371 	xfer->transfer_id = atomic_inc_return(&transfer_last_id);
372 
373 	if (set_pending) {
374 		/* Pick and set monotonic token */
375 		ret = scmi_xfer_token_set(minfo, xfer);
376 		if (!ret) {
377 			hash_add(minfo->pending_xfers, &xfer->node,
378 				 xfer->hdr.seq);
379 			xfer->pending = true;
380 		} else {
381 			dev_err(handle->dev,
382 				"Failed to get monotonic token %d\n", ret);
383 			hlist_add_head(&xfer->node, &minfo->free_xfers);
384 			xfer = ERR_PTR(ret);
385 		}
386 	}
387 
388 	if (!IS_ERR(xfer)) {
389 		refcount_set(&xfer->users, 1);
390 		atomic_set(&xfer->busy, SCMI_XFER_FREE);
391 	}
392 	spin_unlock_irqrestore(&minfo->xfer_lock, flags);
393 
394 	return xfer;
395 }
396 
397 /**
398  * __scmi_xfer_put() - Release a message
399  *
400  * @minfo: Pointer to Tx/Rx Message management info based on channel type
401  * @xfer: message that was reserved by scmi_xfer_get
402  *
403  * After refcount check, possibly release an xfer, clearing the token slot,
404  * removing xfer from @pending_xfers and putting it back into free_xfers.
405  *
406  * This holds a spinlock to maintain integrity of internal data structures.
407  */
408 static void
409 __scmi_xfer_put(struct scmi_xfers_info *minfo, struct scmi_xfer *xfer)
410 {
411 	unsigned long flags;
412 
413 	spin_lock_irqsave(&minfo->xfer_lock, flags);
414 	if (refcount_dec_and_test(&xfer->users)) {
415 		if (xfer->pending) {
416 			scmi_xfer_token_clear(minfo, xfer);
417 			hash_del(&xfer->node);
418 			xfer->pending = false;
419 		}
420 		hlist_add_head(&xfer->node, &minfo->free_xfers);
421 	}
422 	spin_unlock_irqrestore(&minfo->xfer_lock, flags);
423 }
424 
425 /**
426  * scmi_xfer_lookup_unlocked  -  Helper to lookup an xfer_id
427  *
428  * @minfo: Pointer to Tx/Rx Message management info based on channel type
429  * @xfer_id: Token ID to lookup in @pending_xfers
430  *
431  * Refcounting is untouched.
432  *
433  * Context: Assumes to be called with @xfer_lock already acquired.
434  *
435  * Return: A valid xfer on Success or error otherwise
436  */
437 static struct scmi_xfer *
438 scmi_xfer_lookup_unlocked(struct scmi_xfers_info *minfo, u16 xfer_id)
439 {
440 	struct scmi_xfer *xfer = NULL;
441 
442 	if (test_bit(xfer_id, minfo->xfer_alloc_table))
443 		xfer = XFER_FIND(minfo->pending_xfers, xfer_id);
444 
445 	return xfer ?: ERR_PTR(-EINVAL);
446 }
447 
448 /**
449  * scmi_msg_response_validate  - Validate message type against state of related
450  * xfer
451  *
452  * @cinfo: A reference to the channel descriptor.
453  * @msg_type: Message type to check
454  * @xfer: A reference to the xfer to validate against @msg_type
455  *
456  * This function checks if @msg_type is congruent with the current state of
457  * a pending @xfer; if an asynchronous delayed response is received before the
458  * related synchronous response (Out-of-Order Delayed Response) the missing
459  * synchronous response is assumed to be OK and completed, carrying on with the
460  * Delayed Response: this is done to address the case in which the underlying
461  * SCMI transport can deliver such out-of-order responses.
462  *
463  * Context: Assumes to be called with xfer->lock already acquired.
464  *
465  * Return: 0 on Success, error otherwise
466  */
467 static inline int scmi_msg_response_validate(struct scmi_chan_info *cinfo,
468 					     u8 msg_type,
469 					     struct scmi_xfer *xfer)
470 {
471 	/*
472 	 * Even if a response was indeed expected on this slot at this point,
473 	 * a buggy platform could wrongly reply feeding us an unexpected
474 	 * delayed response we're not prepared to handle: bail-out safely
475 	 * blaming firmware.
476 	 */
477 	if (msg_type == MSG_TYPE_DELAYED_RESP && !xfer->async_done) {
478 		dev_err(cinfo->dev,
479 			"Delayed Response for %d not expected! Buggy F/W ?\n",
480 			xfer->hdr.seq);
481 		return -EINVAL;
482 	}
483 
484 	switch (xfer->state) {
485 	case SCMI_XFER_SENT_OK:
486 		if (msg_type == MSG_TYPE_DELAYED_RESP) {
487 			/*
488 			 * Delayed Response expected but delivered earlier.
489 			 * Assume message RESPONSE was OK and skip state.
490 			 */
491 			xfer->hdr.status = SCMI_SUCCESS;
492 			xfer->state = SCMI_XFER_RESP_OK;
493 			complete(&xfer->done);
494 			dev_warn(cinfo->dev,
495 				 "Received valid OoO Delayed Response for %d\n",
496 				 xfer->hdr.seq);
497 		}
498 		break;
499 	case SCMI_XFER_RESP_OK:
500 		if (msg_type != MSG_TYPE_DELAYED_RESP)
501 			return -EINVAL;
502 		break;
503 	case SCMI_XFER_DRESP_OK:
504 		/* No further message expected once in SCMI_XFER_DRESP_OK */
505 		return -EINVAL;
506 	}
507 
508 	return 0;
509 }
510 
511 /**
512  * scmi_xfer_state_update  - Update xfer state
513  *
514  * @xfer: A reference to the xfer to update
515  * @msg_type: Type of message being processed.
516  *
517  * Note that this message is assumed to have been already successfully validated
518  * by @scmi_msg_response_validate(), so here we just update the state.
519  *
520  * Context: Assumes to be called on an xfer exclusively acquired using the
521  *	    busy flag.
522  */
523 static inline void scmi_xfer_state_update(struct scmi_xfer *xfer, u8 msg_type)
524 {
525 	xfer->hdr.type = msg_type;
526 
527 	/* Unknown command types were already discarded earlier */
528 	if (xfer->hdr.type == MSG_TYPE_COMMAND)
529 		xfer->state = SCMI_XFER_RESP_OK;
530 	else
531 		xfer->state = SCMI_XFER_DRESP_OK;
532 }
533 
534 static bool scmi_xfer_acquired(struct scmi_xfer *xfer)
535 {
536 	int ret;
537 
538 	ret = atomic_cmpxchg(&xfer->busy, SCMI_XFER_FREE, SCMI_XFER_BUSY);
539 
540 	return ret == SCMI_XFER_FREE;
541 }
542 
543 /**
544  * scmi_xfer_command_acquire  -  Helper to lookup and acquire a command xfer
545  *
546  * @cinfo: A reference to the channel descriptor.
547  * @msg_hdr: A message header to use as lookup key
548  *
549  * When a valid xfer is found for the sequence number embedded in the provided
550  * msg_hdr, reference counting is properly updated and exclusive access to this
551  * xfer is granted till released with @scmi_xfer_command_release.
552  *
553  * Return: A valid @xfer on Success or error otherwise.
554  */
555 static inline struct scmi_xfer *
556 scmi_xfer_command_acquire(struct scmi_chan_info *cinfo, u32 msg_hdr)
557 {
558 	int ret;
559 	unsigned long flags;
560 	struct scmi_xfer *xfer;
561 	struct scmi_info *info = handle_to_scmi_info(cinfo->handle);
562 	struct scmi_xfers_info *minfo = &info->tx_minfo;
563 	u8 msg_type = MSG_XTRACT_TYPE(msg_hdr);
564 	u16 xfer_id = MSG_XTRACT_TOKEN(msg_hdr);
565 
566 	/* Are we even expecting this? */
567 	spin_lock_irqsave(&minfo->xfer_lock, flags);
568 	xfer = scmi_xfer_lookup_unlocked(minfo, xfer_id);
569 	if (IS_ERR(xfer)) {
570 		dev_err(cinfo->dev,
571 			"Message for %d type %d is not expected!\n",
572 			xfer_id, msg_type);
573 		spin_unlock_irqrestore(&minfo->xfer_lock, flags);
574 		return xfer;
575 	}
576 	refcount_inc(&xfer->users);
577 	spin_unlock_irqrestore(&minfo->xfer_lock, flags);
578 
579 	spin_lock_irqsave(&xfer->lock, flags);
580 	ret = scmi_msg_response_validate(cinfo, msg_type, xfer);
581 	/*
582 	 * If a pending xfer was found which was also in a congruent state with
583 	 * the received message, acquire exclusive access to it setting the busy
584 	 * flag.
585 	 * Spins only on the rare limit condition of concurrent reception of
586 	 * RESP and DRESP for the same xfer.
587 	 */
588 	if (!ret) {
589 		spin_until_cond(scmi_xfer_acquired(xfer));
590 		scmi_xfer_state_update(xfer, msg_type);
591 	}
592 	spin_unlock_irqrestore(&xfer->lock, flags);
593 
594 	if (ret) {
595 		dev_err(cinfo->dev,
596 			"Invalid message type:%d for %d - HDR:0x%X  state:%d\n",
597 			msg_type, xfer_id, msg_hdr, xfer->state);
598 		/* On error the refcount incremented above has to be dropped */
599 		__scmi_xfer_put(minfo, xfer);
600 		xfer = ERR_PTR(-EINVAL);
601 	}
602 
603 	return xfer;
604 }
605 
606 static inline void scmi_xfer_command_release(struct scmi_info *info,
607 					     struct scmi_xfer *xfer)
608 {
609 	atomic_set(&xfer->busy, SCMI_XFER_FREE);
610 	__scmi_xfer_put(&info->tx_minfo, xfer);
611 }
612 
613 static inline void scmi_clear_channel(struct scmi_info *info,
614 				      struct scmi_chan_info *cinfo)
615 {
616 	if (info->desc->ops->clear_channel)
617 		info->desc->ops->clear_channel(cinfo);
618 }
619 
620 static inline bool is_polling_required(struct scmi_chan_info *cinfo,
621 				       struct scmi_info *info)
622 {
623 	return cinfo->no_completion_irq || info->desc->force_polling;
624 }
625 
626 static inline bool is_transport_polling_capable(struct scmi_info *info)
627 {
628 	return info->desc->ops->poll_done ||
629 		info->desc->sync_cmds_completed_on_ret;
630 }
631 
632 static inline bool is_polling_enabled(struct scmi_chan_info *cinfo,
633 				      struct scmi_info *info)
634 {
635 	return is_polling_required(cinfo, info) &&
636 		is_transport_polling_capable(info);
637 }
638 
639 static void scmi_handle_notification(struct scmi_chan_info *cinfo,
640 				     u32 msg_hdr, void *priv)
641 {
642 	struct scmi_xfer *xfer;
643 	struct device *dev = cinfo->dev;
644 	struct scmi_info *info = handle_to_scmi_info(cinfo->handle);
645 	struct scmi_xfers_info *minfo = &info->rx_minfo;
646 	ktime_t ts;
647 
648 	ts = ktime_get_boottime();
649 	xfer = scmi_xfer_get(cinfo->handle, minfo, false);
650 	if (IS_ERR(xfer)) {
651 		dev_err(dev, "failed to get free message slot (%ld)\n",
652 			PTR_ERR(xfer));
653 		scmi_clear_channel(info, cinfo);
654 		return;
655 	}
656 
657 	unpack_scmi_header(msg_hdr, &xfer->hdr);
658 	if (priv)
659 		/* Ensure order between xfer->priv store and following ops */
660 		smp_store_mb(xfer->priv, priv);
661 	info->desc->ops->fetch_notification(cinfo, info->desc->max_msg_size,
662 					    xfer);
663 	scmi_notify(cinfo->handle, xfer->hdr.protocol_id,
664 		    xfer->hdr.id, xfer->rx.buf, xfer->rx.len, ts);
665 
666 	trace_scmi_rx_done(xfer->transfer_id, xfer->hdr.id,
667 			   xfer->hdr.protocol_id, xfer->hdr.seq,
668 			   MSG_TYPE_NOTIFICATION);
669 
670 	__scmi_xfer_put(minfo, xfer);
671 
672 	scmi_clear_channel(info, cinfo);
673 }
674 
675 static void scmi_handle_response(struct scmi_chan_info *cinfo,
676 				 u32 msg_hdr, void *priv)
677 {
678 	struct scmi_xfer *xfer;
679 	struct scmi_info *info = handle_to_scmi_info(cinfo->handle);
680 
681 	xfer = scmi_xfer_command_acquire(cinfo, msg_hdr);
682 	if (IS_ERR(xfer)) {
683 		if (MSG_XTRACT_TYPE(msg_hdr) == MSG_TYPE_DELAYED_RESP)
684 			scmi_clear_channel(info, cinfo);
685 		return;
686 	}
687 
688 	/* rx.len could be shrunk in the sync do_xfer, so reset to maxsz */
689 	if (xfer->hdr.type == MSG_TYPE_DELAYED_RESP)
690 		xfer->rx.len = info->desc->max_msg_size;
691 
692 	if (priv)
693 		/* Ensure order between xfer->priv store and following ops */
694 		smp_store_mb(xfer->priv, priv);
695 	info->desc->ops->fetch_response(cinfo, xfer);
696 
697 	trace_scmi_rx_done(xfer->transfer_id, xfer->hdr.id,
698 			   xfer->hdr.protocol_id, xfer->hdr.seq,
699 			   xfer->hdr.type);
700 
701 	if (xfer->hdr.type == MSG_TYPE_DELAYED_RESP) {
702 		scmi_clear_channel(info, cinfo);
703 		complete(xfer->async_done);
704 	} else {
705 		complete(&xfer->done);
706 	}
707 
708 	scmi_xfer_command_release(info, xfer);
709 }
710 
711 /**
712  * scmi_rx_callback() - callback for receiving messages
713  *
714  * @cinfo: SCMI channel info
715  * @msg_hdr: Message header
716  * @priv: Transport specific private data.
717  *
718  * Processes one received message to appropriate transfer information and
719  * signals completion of the transfer.
720  *
721  * NOTE: This function will be invoked in IRQ context, hence should be
722  * as optimal as possible.
723  */
724 void scmi_rx_callback(struct scmi_chan_info *cinfo, u32 msg_hdr, void *priv)
725 {
726 	u8 msg_type = MSG_XTRACT_TYPE(msg_hdr);
727 
728 	switch (msg_type) {
729 	case MSG_TYPE_NOTIFICATION:
730 		scmi_handle_notification(cinfo, msg_hdr, priv);
731 		break;
732 	case MSG_TYPE_COMMAND:
733 	case MSG_TYPE_DELAYED_RESP:
734 		scmi_handle_response(cinfo, msg_hdr, priv);
735 		break;
736 	default:
737 		WARN_ONCE(1, "received unknown msg_type:%d\n", msg_type);
738 		break;
739 	}
740 }
741 
742 /**
743  * xfer_put() - Release a transmit message
744  *
745  * @ph: Pointer to SCMI protocol handle
746  * @xfer: message that was reserved by xfer_get_init
747  */
748 static void xfer_put(const struct scmi_protocol_handle *ph,
749 		     struct scmi_xfer *xfer)
750 {
751 	const struct scmi_protocol_instance *pi = ph_to_pi(ph);
752 	struct scmi_info *info = handle_to_scmi_info(pi->handle);
753 
754 	__scmi_xfer_put(&info->tx_minfo, xfer);
755 }
756 
757 static bool scmi_xfer_done_no_timeout(struct scmi_chan_info *cinfo,
758 				      struct scmi_xfer *xfer, ktime_t stop)
759 {
760 	struct scmi_info *info = handle_to_scmi_info(cinfo->handle);
761 
762 	/*
763 	 * Poll also on xfer->done so that polling can be forcibly terminated
764 	 * in case of out-of-order receptions of delayed responses
765 	 */
766 	return info->desc->ops->poll_done(cinfo, xfer) ||
767 	       try_wait_for_completion(&xfer->done) ||
768 	       ktime_after(ktime_get(), stop);
769 }
770 
771 /**
772  * scmi_wait_for_message_response  - An helper to group all the possible ways of
773  * waiting for a synchronous message response.
774  *
775  * @cinfo: SCMI channel info
776  * @xfer: Reference to the transfer being waited for.
777  *
778  * Chooses waiting strategy (sleep-waiting vs busy-waiting) depending on
779  * configuration flags like xfer->hdr.poll_completion.
780  *
781  * Return: 0 on Success, error otherwise.
782  */
783 static int scmi_wait_for_message_response(struct scmi_chan_info *cinfo,
784 					  struct scmi_xfer *xfer)
785 {
786 	struct scmi_info *info = handle_to_scmi_info(cinfo->handle);
787 	struct device *dev = info->dev;
788 	int ret = 0, timeout_ms = info->desc->max_rx_timeout_ms;
789 
790 	trace_scmi_xfer_response_wait(xfer->transfer_id, xfer->hdr.id,
791 				      xfer->hdr.protocol_id, xfer->hdr.seq,
792 				      timeout_ms,
793 				      xfer->hdr.poll_completion);
794 
795 	if (xfer->hdr.poll_completion) {
796 		/*
797 		 * Real polling is needed only if transport has NOT declared
798 		 * itself to support synchronous commands replies.
799 		 */
800 		if (!info->desc->sync_cmds_completed_on_ret) {
801 			/*
802 			 * Poll on xfer using transport provided .poll_done();
803 			 * assumes no completion interrupt was available.
804 			 */
805 			ktime_t stop = ktime_add_ms(ktime_get(), timeout_ms);
806 
807 			spin_until_cond(scmi_xfer_done_no_timeout(cinfo,
808 								  xfer, stop));
809 			if (ktime_after(ktime_get(), stop)) {
810 				dev_err(dev,
811 					"timed out in resp(caller: %pS) - polling\n",
812 					(void *)_RET_IP_);
813 				ret = -ETIMEDOUT;
814 			}
815 		}
816 
817 		if (!ret) {
818 			unsigned long flags;
819 
820 			/*
821 			 * Do not fetch_response if an out-of-order delayed
822 			 * response is being processed.
823 			 */
824 			spin_lock_irqsave(&xfer->lock, flags);
825 			if (xfer->state == SCMI_XFER_SENT_OK) {
826 				info->desc->ops->fetch_response(cinfo, xfer);
827 				xfer->state = SCMI_XFER_RESP_OK;
828 			}
829 			spin_unlock_irqrestore(&xfer->lock, flags);
830 		}
831 	} else {
832 		/* And we wait for the response. */
833 		if (!wait_for_completion_timeout(&xfer->done,
834 						 msecs_to_jiffies(timeout_ms))) {
835 			dev_err(dev, "timed out in resp(caller: %pS)\n",
836 				(void *)_RET_IP_);
837 			ret = -ETIMEDOUT;
838 		}
839 	}
840 
841 	return ret;
842 }
843 
844 /**
845  * do_xfer() - Do one transfer
846  *
847  * @ph: Pointer to SCMI protocol handle
848  * @xfer: Transfer to initiate and wait for response
849  *
850  * Return: -ETIMEDOUT in case of no response, if transmit error,
851  *	return corresponding error, else if all goes well,
852  *	return 0.
853  */
854 static int do_xfer(const struct scmi_protocol_handle *ph,
855 		   struct scmi_xfer *xfer)
856 {
857 	int ret;
858 	const struct scmi_protocol_instance *pi = ph_to_pi(ph);
859 	struct scmi_info *info = handle_to_scmi_info(pi->handle);
860 	struct device *dev = info->dev;
861 	struct scmi_chan_info *cinfo;
862 
863 	/* Check for polling request on custom command xfers at first */
864 	if (xfer->hdr.poll_completion && !is_transport_polling_capable(info)) {
865 		dev_warn_once(dev,
866 			      "Polling mode is not supported by transport.\n");
867 		return -EINVAL;
868 	}
869 
870 	cinfo = idr_find(&info->tx_idr, pi->proto->id);
871 	if (unlikely(!cinfo))
872 		return -EINVAL;
873 
874 	/* True ONLY if also supported by transport. */
875 	if (is_polling_enabled(cinfo, info))
876 		xfer->hdr.poll_completion = true;
877 
878 	/*
879 	 * Initialise protocol id now from protocol handle to avoid it being
880 	 * overridden by mistake (or malice) by the protocol code mangling with
881 	 * the scmi_xfer structure prior to this.
882 	 */
883 	xfer->hdr.protocol_id = pi->proto->id;
884 	reinit_completion(&xfer->done);
885 
886 	trace_scmi_xfer_begin(xfer->transfer_id, xfer->hdr.id,
887 			      xfer->hdr.protocol_id, xfer->hdr.seq,
888 			      xfer->hdr.poll_completion);
889 
890 	xfer->state = SCMI_XFER_SENT_OK;
891 	/*
892 	 * Even though spinlocking is not needed here since no race is possible
893 	 * on xfer->state due to the monotonically increasing tokens allocation,
894 	 * we must anyway ensure xfer->state initialization is not re-ordered
895 	 * after the .send_message() to be sure that on the RX path an early
896 	 * ISR calling scmi_rx_callback() cannot see an old stale xfer->state.
897 	 */
898 	smp_mb();
899 
900 	ret = info->desc->ops->send_message(cinfo, xfer);
901 	if (ret < 0) {
902 		dev_dbg(dev, "Failed to send message %d\n", ret);
903 		return ret;
904 	}
905 
906 	ret = scmi_wait_for_message_response(cinfo, xfer);
907 	if (!ret && xfer->hdr.status)
908 		ret = scmi_to_linux_errno(xfer->hdr.status);
909 
910 	if (info->desc->ops->mark_txdone)
911 		info->desc->ops->mark_txdone(cinfo, ret, xfer);
912 
913 	trace_scmi_xfer_end(xfer->transfer_id, xfer->hdr.id,
914 			    xfer->hdr.protocol_id, xfer->hdr.seq, ret);
915 
916 	return ret;
917 }
918 
919 static void reset_rx_to_maxsz(const struct scmi_protocol_handle *ph,
920 			      struct scmi_xfer *xfer)
921 {
922 	const struct scmi_protocol_instance *pi = ph_to_pi(ph);
923 	struct scmi_info *info = handle_to_scmi_info(pi->handle);
924 
925 	xfer->rx.len = info->desc->max_msg_size;
926 }
927 
928 #define SCMI_MAX_RESPONSE_TIMEOUT	(2 * MSEC_PER_SEC)
929 
930 /**
931  * do_xfer_with_response() - Do one transfer and wait until the delayed
932  *	response is received
933  *
934  * @ph: Pointer to SCMI protocol handle
935  * @xfer: Transfer to initiate and wait for response
936  *
937  * Using asynchronous commands in atomic/polling mode should be avoided since
938  * it could cause long busy-waiting here, so ignore polling for the delayed
939  * response and WARN if it was requested for this command transaction since
940  * upper layers should refrain from issuing such kind of requests.
941  *
942  * The only other option would have been to refrain from using any asynchronous
943  * command even if made available, when an atomic transport is detected, and
944  * instead forcibly use the synchronous version (thing that can be easily
945  * attained at the protocol layer), but this would also have led to longer
946  * stalls of the channel for synchronous commands and possibly timeouts.
947  * (in other words there is usually a good reason if a platform provides an
948  *  asynchronous version of a command and we should prefer to use it...just not
949  *  when using atomic/polling mode)
950  *
951  * Return: -ETIMEDOUT in case of no delayed response, if transmit error,
952  *	return corresponding error, else if all goes well, return 0.
953  */
954 static int do_xfer_with_response(const struct scmi_protocol_handle *ph,
955 				 struct scmi_xfer *xfer)
956 {
957 	int ret, timeout = msecs_to_jiffies(SCMI_MAX_RESPONSE_TIMEOUT);
958 	DECLARE_COMPLETION_ONSTACK(async_response);
959 
960 	xfer->async_done = &async_response;
961 
962 	/*
963 	 * Delayed responses should not be polled, so an async command should
964 	 * not have been used when requiring an atomic/poll context; WARN and
965 	 * perform instead a sleeping wait.
966 	 * (Note Async + IgnoreDelayedResponses are sent via do_xfer)
967 	 */
968 	WARN_ON_ONCE(xfer->hdr.poll_completion);
969 
970 	ret = do_xfer(ph, xfer);
971 	if (!ret) {
972 		if (!wait_for_completion_timeout(xfer->async_done, timeout)) {
973 			dev_err(ph->dev,
974 				"timed out in delayed resp(caller: %pS)\n",
975 				(void *)_RET_IP_);
976 			ret = -ETIMEDOUT;
977 		} else if (xfer->hdr.status) {
978 			ret = scmi_to_linux_errno(xfer->hdr.status);
979 		}
980 	}
981 
982 	xfer->async_done = NULL;
983 	return ret;
984 }
985 
986 /**
987  * xfer_get_init() - Allocate and initialise one message for transmit
988  *
989  * @ph: Pointer to SCMI protocol handle
990  * @msg_id: Message identifier
991  * @tx_size: transmit message size
992  * @rx_size: receive message size
993  * @p: pointer to the allocated and initialised message
994  *
995  * This function allocates the message using @scmi_xfer_get and
996  * initialise the header.
997  *
998  * Return: 0 if all went fine with @p pointing to message, else
999  *	corresponding error.
1000  */
1001 static int xfer_get_init(const struct scmi_protocol_handle *ph,
1002 			 u8 msg_id, size_t tx_size, size_t rx_size,
1003 			 struct scmi_xfer **p)
1004 {
1005 	int ret;
1006 	struct scmi_xfer *xfer;
1007 	const struct scmi_protocol_instance *pi = ph_to_pi(ph);
1008 	struct scmi_info *info = handle_to_scmi_info(pi->handle);
1009 	struct scmi_xfers_info *minfo = &info->tx_minfo;
1010 	struct device *dev = info->dev;
1011 
1012 	/* Ensure we have sane transfer sizes */
1013 	if (rx_size > info->desc->max_msg_size ||
1014 	    tx_size > info->desc->max_msg_size)
1015 		return -ERANGE;
1016 
1017 	xfer = scmi_xfer_get(pi->handle, minfo, true);
1018 	if (IS_ERR(xfer)) {
1019 		ret = PTR_ERR(xfer);
1020 		dev_err(dev, "failed to get free message slot(%d)\n", ret);
1021 		return ret;
1022 	}
1023 
1024 	xfer->tx.len = tx_size;
1025 	xfer->rx.len = rx_size ? : info->desc->max_msg_size;
1026 	xfer->hdr.type = MSG_TYPE_COMMAND;
1027 	xfer->hdr.id = msg_id;
1028 	xfer->hdr.poll_completion = false;
1029 
1030 	*p = xfer;
1031 
1032 	return 0;
1033 }
1034 
1035 /**
1036  * version_get() - command to get the revision of the SCMI entity
1037  *
1038  * @ph: Pointer to SCMI protocol handle
1039  * @version: Holds returned version of protocol.
1040  *
1041  * Updates the SCMI information in the internal data structure.
1042  *
1043  * Return: 0 if all went fine, else return appropriate error.
1044  */
1045 static int version_get(const struct scmi_protocol_handle *ph, u32 *version)
1046 {
1047 	int ret;
1048 	__le32 *rev_info;
1049 	struct scmi_xfer *t;
1050 
1051 	ret = xfer_get_init(ph, PROTOCOL_VERSION, 0, sizeof(*version), &t);
1052 	if (ret)
1053 		return ret;
1054 
1055 	ret = do_xfer(ph, t);
1056 	if (!ret) {
1057 		rev_info = t->rx.buf;
1058 		*version = le32_to_cpu(*rev_info);
1059 	}
1060 
1061 	xfer_put(ph, t);
1062 	return ret;
1063 }
1064 
1065 /**
1066  * scmi_set_protocol_priv  - Set protocol specific data at init time
1067  *
1068  * @ph: A reference to the protocol handle.
1069  * @priv: The private data to set.
1070  *
1071  * Return: 0 on Success
1072  */
1073 static int scmi_set_protocol_priv(const struct scmi_protocol_handle *ph,
1074 				  void *priv)
1075 {
1076 	struct scmi_protocol_instance *pi = ph_to_pi(ph);
1077 
1078 	pi->priv = priv;
1079 
1080 	return 0;
1081 }
1082 
1083 /**
1084  * scmi_get_protocol_priv  - Set protocol specific data at init time
1085  *
1086  * @ph: A reference to the protocol handle.
1087  *
1088  * Return: Protocol private data if any was set.
1089  */
1090 static void *scmi_get_protocol_priv(const struct scmi_protocol_handle *ph)
1091 {
1092 	const struct scmi_protocol_instance *pi = ph_to_pi(ph);
1093 
1094 	return pi->priv;
1095 }
1096 
1097 static const struct scmi_xfer_ops xfer_ops = {
1098 	.version_get = version_get,
1099 	.xfer_get_init = xfer_get_init,
1100 	.reset_rx_to_maxsz = reset_rx_to_maxsz,
1101 	.do_xfer = do_xfer,
1102 	.do_xfer_with_response = do_xfer_with_response,
1103 	.xfer_put = xfer_put,
1104 };
1105 
1106 struct scmi_msg_resp_domain_name_get {
1107 	__le32 flags;
1108 	u8 name[SCMI_MAX_STR_SIZE];
1109 };
1110 
1111 /**
1112  * scmi_common_extended_name_get  - Common helper to get extended resources name
1113  * @ph: A protocol handle reference.
1114  * @cmd_id: The specific command ID to use.
1115  * @res_id: The specific resource ID to use.
1116  * @name: A pointer to the preallocated area where the retrieved name will be
1117  *	  stored as a NULL terminated string.
1118  * @len: The len in bytes of the @name char array.
1119  *
1120  * Return: 0 on Succcess
1121  */
1122 static int scmi_common_extended_name_get(const struct scmi_protocol_handle *ph,
1123 					 u8 cmd_id, u32 res_id, char *name,
1124 					 size_t len)
1125 {
1126 	int ret;
1127 	struct scmi_xfer *t;
1128 	struct scmi_msg_resp_domain_name_get *resp;
1129 
1130 	ret = ph->xops->xfer_get_init(ph, cmd_id, sizeof(res_id),
1131 				      sizeof(*resp), &t);
1132 	if (ret)
1133 		goto out;
1134 
1135 	put_unaligned_le32(res_id, t->tx.buf);
1136 	resp = t->rx.buf;
1137 
1138 	ret = ph->xops->do_xfer(ph, t);
1139 	if (!ret)
1140 		strscpy(name, resp->name, len);
1141 
1142 	ph->xops->xfer_put(ph, t);
1143 out:
1144 	if (ret)
1145 		dev_warn(ph->dev,
1146 			 "Failed to get extended name - id:%u (ret:%d). Using %s\n",
1147 			 res_id, ret, name);
1148 	return ret;
1149 }
1150 
1151 /**
1152  * struct scmi_iterator  - Iterator descriptor
1153  * @msg: A reference to the message TX buffer; filled by @prepare_message with
1154  *	 a proper custom command payload for each multi-part command request.
1155  * @resp: A reference to the response RX buffer; used by @update_state and
1156  *	  @process_response to parse the multi-part replies.
1157  * @t: A reference to the underlying xfer initialized and used transparently by
1158  *     the iterator internal routines.
1159  * @ph: A reference to the associated protocol handle to be used.
1160  * @ops: A reference to the custom provided iterator operations.
1161  * @state: The current iterator state; used and updated in turn by the iterators
1162  *	   internal routines and by the caller-provided @scmi_iterator_ops.
1163  * @priv: A reference to optional private data as provided by the caller and
1164  *	  passed back to the @@scmi_iterator_ops.
1165  */
1166 struct scmi_iterator {
1167 	void *msg;
1168 	void *resp;
1169 	struct scmi_xfer *t;
1170 	const struct scmi_protocol_handle *ph;
1171 	struct scmi_iterator_ops *ops;
1172 	struct scmi_iterator_state state;
1173 	void *priv;
1174 };
1175 
1176 static void *scmi_iterator_init(const struct scmi_protocol_handle *ph,
1177 				struct scmi_iterator_ops *ops,
1178 				unsigned int max_resources, u8 msg_id,
1179 				size_t tx_size, void *priv)
1180 {
1181 	int ret;
1182 	struct scmi_iterator *i;
1183 
1184 	i = devm_kzalloc(ph->dev, sizeof(*i), GFP_KERNEL);
1185 	if (!i)
1186 		return ERR_PTR(-ENOMEM);
1187 
1188 	i->ph = ph;
1189 	i->ops = ops;
1190 	i->priv = priv;
1191 
1192 	ret = ph->xops->xfer_get_init(ph, msg_id, tx_size, 0, &i->t);
1193 	if (ret) {
1194 		devm_kfree(ph->dev, i);
1195 		return ERR_PTR(ret);
1196 	}
1197 
1198 	i->state.max_resources = max_resources;
1199 	i->msg = i->t->tx.buf;
1200 	i->resp = i->t->rx.buf;
1201 
1202 	return i;
1203 }
1204 
1205 static int scmi_iterator_run(void *iter)
1206 {
1207 	int ret = -EINVAL;
1208 	struct scmi_iterator_ops *iops;
1209 	const struct scmi_protocol_handle *ph;
1210 	struct scmi_iterator_state *st;
1211 	struct scmi_iterator *i = iter;
1212 
1213 	if (!i || !i->ops || !i->ph)
1214 		return ret;
1215 
1216 	iops = i->ops;
1217 	ph = i->ph;
1218 	st = &i->state;
1219 
1220 	do {
1221 		iops->prepare_message(i->msg, st->desc_index, i->priv);
1222 		ret = ph->xops->do_xfer(ph, i->t);
1223 		if (ret)
1224 			break;
1225 
1226 		ret = iops->update_state(st, i->resp, i->priv);
1227 		if (ret)
1228 			break;
1229 
1230 		if (st->num_returned > st->max_resources - st->desc_index) {
1231 			dev_err(ph->dev,
1232 				"No. of resources can't exceed %d\n",
1233 				st->max_resources);
1234 			ret = -EINVAL;
1235 			break;
1236 		}
1237 
1238 		for (st->loop_idx = 0; st->loop_idx < st->num_returned;
1239 		     st->loop_idx++) {
1240 			ret = iops->process_response(ph, i->resp, st, i->priv);
1241 			if (ret)
1242 				goto out;
1243 		}
1244 
1245 		st->desc_index += st->num_returned;
1246 		ph->xops->reset_rx_to_maxsz(ph, i->t);
1247 		/*
1248 		 * check for both returned and remaining to avoid infinite
1249 		 * loop due to buggy firmware
1250 		 */
1251 	} while (st->num_returned && st->num_remaining);
1252 
1253 out:
1254 	/* Finalize and destroy iterator */
1255 	ph->xops->xfer_put(ph, i->t);
1256 	devm_kfree(ph->dev, i);
1257 
1258 	return ret;
1259 }
1260 
1261 static const struct scmi_proto_helpers_ops helpers_ops = {
1262 	.extended_name_get = scmi_common_extended_name_get,
1263 	.iter_response_init = scmi_iterator_init,
1264 	.iter_response_run = scmi_iterator_run,
1265 };
1266 
1267 /**
1268  * scmi_revision_area_get  - Retrieve version memory area.
1269  *
1270  * @ph: A reference to the protocol handle.
1271  *
1272  * A helper to grab the version memory area reference during SCMI Base protocol
1273  * initialization.
1274  *
1275  * Return: A reference to the version memory area associated to the SCMI
1276  *	   instance underlying this protocol handle.
1277  */
1278 struct scmi_revision_info *
1279 scmi_revision_area_get(const struct scmi_protocol_handle *ph)
1280 {
1281 	const struct scmi_protocol_instance *pi = ph_to_pi(ph);
1282 
1283 	return pi->handle->version;
1284 }
1285 
1286 /**
1287  * scmi_alloc_init_protocol_instance  - Allocate and initialize a protocol
1288  * instance descriptor.
1289  * @info: The reference to the related SCMI instance.
1290  * @proto: The protocol descriptor.
1291  *
1292  * Allocate a new protocol instance descriptor, using the provided @proto
1293  * description, against the specified SCMI instance @info, and initialize it;
1294  * all resources management is handled via a dedicated per-protocol devres
1295  * group.
1296  *
1297  * Context: Assumes to be called with @protocols_mtx already acquired.
1298  * Return: A reference to a freshly allocated and initialized protocol instance
1299  *	   or ERR_PTR on failure. On failure the @proto reference is at first
1300  *	   put using @scmi_protocol_put() before releasing all the devres group.
1301  */
1302 static struct scmi_protocol_instance *
1303 scmi_alloc_init_protocol_instance(struct scmi_info *info,
1304 				  const struct scmi_protocol *proto)
1305 {
1306 	int ret = -ENOMEM;
1307 	void *gid;
1308 	struct scmi_protocol_instance *pi;
1309 	const struct scmi_handle *handle = &info->handle;
1310 
1311 	/* Protocol specific devres group */
1312 	gid = devres_open_group(handle->dev, NULL, GFP_KERNEL);
1313 	if (!gid) {
1314 		scmi_protocol_put(proto->id);
1315 		goto out;
1316 	}
1317 
1318 	pi = devm_kzalloc(handle->dev, sizeof(*pi), GFP_KERNEL);
1319 	if (!pi)
1320 		goto clean;
1321 
1322 	pi->gid = gid;
1323 	pi->proto = proto;
1324 	pi->handle = handle;
1325 	pi->ph.dev = handle->dev;
1326 	pi->ph.xops = &xfer_ops;
1327 	pi->ph.hops = &helpers_ops;
1328 	pi->ph.set_priv = scmi_set_protocol_priv;
1329 	pi->ph.get_priv = scmi_get_protocol_priv;
1330 	refcount_set(&pi->users, 1);
1331 	/* proto->init is assured NON NULL by scmi_protocol_register */
1332 	ret = pi->proto->instance_init(&pi->ph);
1333 	if (ret)
1334 		goto clean;
1335 
1336 	ret = idr_alloc(&info->protocols, pi, proto->id, proto->id + 1,
1337 			GFP_KERNEL);
1338 	if (ret != proto->id)
1339 		goto clean;
1340 
1341 	/*
1342 	 * Warn but ignore events registration errors since we do not want
1343 	 * to skip whole protocols if their notifications are messed up.
1344 	 */
1345 	if (pi->proto->events) {
1346 		ret = scmi_register_protocol_events(handle, pi->proto->id,
1347 						    &pi->ph,
1348 						    pi->proto->events);
1349 		if (ret)
1350 			dev_warn(handle->dev,
1351 				 "Protocol:%X - Events Registration Failed - err:%d\n",
1352 				 pi->proto->id, ret);
1353 	}
1354 
1355 	devres_close_group(handle->dev, pi->gid);
1356 	dev_dbg(handle->dev, "Initialized protocol: 0x%X\n", pi->proto->id);
1357 
1358 	return pi;
1359 
1360 clean:
1361 	/* Take care to put the protocol module's owner before releasing all */
1362 	scmi_protocol_put(proto->id);
1363 	devres_release_group(handle->dev, gid);
1364 out:
1365 	return ERR_PTR(ret);
1366 }
1367 
1368 /**
1369  * scmi_get_protocol_instance  - Protocol initialization helper.
1370  * @handle: A reference to the SCMI platform instance.
1371  * @protocol_id: The protocol being requested.
1372  *
1373  * In case the required protocol has never been requested before for this
1374  * instance, allocate and initialize all the needed structures while handling
1375  * resource allocation with a dedicated per-protocol devres subgroup.
1376  *
1377  * Return: A reference to an initialized protocol instance or error on failure:
1378  *	   in particular returns -EPROBE_DEFER when the desired protocol could
1379  *	   NOT be found.
1380  */
1381 static struct scmi_protocol_instance * __must_check
1382 scmi_get_protocol_instance(const struct scmi_handle *handle, u8 protocol_id)
1383 {
1384 	struct scmi_protocol_instance *pi;
1385 	struct scmi_info *info = handle_to_scmi_info(handle);
1386 
1387 	mutex_lock(&info->protocols_mtx);
1388 	pi = idr_find(&info->protocols, protocol_id);
1389 
1390 	if (pi) {
1391 		refcount_inc(&pi->users);
1392 	} else {
1393 		const struct scmi_protocol *proto;
1394 
1395 		/* Fails if protocol not registered on bus */
1396 		proto = scmi_protocol_get(protocol_id);
1397 		if (proto)
1398 			pi = scmi_alloc_init_protocol_instance(info, proto);
1399 		else
1400 			pi = ERR_PTR(-EPROBE_DEFER);
1401 	}
1402 	mutex_unlock(&info->protocols_mtx);
1403 
1404 	return pi;
1405 }
1406 
1407 /**
1408  * scmi_protocol_acquire  - Protocol acquire
1409  * @handle: A reference to the SCMI platform instance.
1410  * @protocol_id: The protocol being requested.
1411  *
1412  * Register a new user for the requested protocol on the specified SCMI
1413  * platform instance, possibly triggering its initialization on first user.
1414  *
1415  * Return: 0 if protocol was acquired successfully.
1416  */
1417 int scmi_protocol_acquire(const struct scmi_handle *handle, u8 protocol_id)
1418 {
1419 	return PTR_ERR_OR_ZERO(scmi_get_protocol_instance(handle, protocol_id));
1420 }
1421 
1422 /**
1423  * scmi_protocol_release  - Protocol de-initialization helper.
1424  * @handle: A reference to the SCMI platform instance.
1425  * @protocol_id: The protocol being requested.
1426  *
1427  * Remove one user for the specified protocol and triggers de-initialization
1428  * and resources de-allocation once the last user has gone.
1429  */
1430 void scmi_protocol_release(const struct scmi_handle *handle, u8 protocol_id)
1431 {
1432 	struct scmi_info *info = handle_to_scmi_info(handle);
1433 	struct scmi_protocol_instance *pi;
1434 
1435 	mutex_lock(&info->protocols_mtx);
1436 	pi = idr_find(&info->protocols, protocol_id);
1437 	if (WARN_ON(!pi))
1438 		goto out;
1439 
1440 	if (refcount_dec_and_test(&pi->users)) {
1441 		void *gid = pi->gid;
1442 
1443 		if (pi->proto->events)
1444 			scmi_deregister_protocol_events(handle, protocol_id);
1445 
1446 		if (pi->proto->instance_deinit)
1447 			pi->proto->instance_deinit(&pi->ph);
1448 
1449 		idr_remove(&info->protocols, protocol_id);
1450 
1451 		scmi_protocol_put(protocol_id);
1452 
1453 		devres_release_group(handle->dev, gid);
1454 		dev_dbg(handle->dev, "De-Initialized protocol: 0x%X\n",
1455 			protocol_id);
1456 	}
1457 
1458 out:
1459 	mutex_unlock(&info->protocols_mtx);
1460 }
1461 
1462 void scmi_setup_protocol_implemented(const struct scmi_protocol_handle *ph,
1463 				     u8 *prot_imp)
1464 {
1465 	const struct scmi_protocol_instance *pi = ph_to_pi(ph);
1466 	struct scmi_info *info = handle_to_scmi_info(pi->handle);
1467 
1468 	info->protocols_imp = prot_imp;
1469 }
1470 
1471 static bool
1472 scmi_is_protocol_implemented(const struct scmi_handle *handle, u8 prot_id)
1473 {
1474 	int i;
1475 	struct scmi_info *info = handle_to_scmi_info(handle);
1476 	struct scmi_revision_info *rev = handle->version;
1477 
1478 	if (!info->protocols_imp)
1479 		return false;
1480 
1481 	for (i = 0; i < rev->num_protocols; i++)
1482 		if (info->protocols_imp[i] == prot_id)
1483 			return true;
1484 	return false;
1485 }
1486 
1487 struct scmi_protocol_devres {
1488 	const struct scmi_handle *handle;
1489 	u8 protocol_id;
1490 };
1491 
1492 static void scmi_devm_release_protocol(struct device *dev, void *res)
1493 {
1494 	struct scmi_protocol_devres *dres = res;
1495 
1496 	scmi_protocol_release(dres->handle, dres->protocol_id);
1497 }
1498 
1499 /**
1500  * scmi_devm_protocol_get  - Devres managed get protocol operations and handle
1501  * @sdev: A reference to an scmi_device whose embedded struct device is to
1502  *	  be used for devres accounting.
1503  * @protocol_id: The protocol being requested.
1504  * @ph: A pointer reference used to pass back the associated protocol handle.
1505  *
1506  * Get hold of a protocol accounting for its usage, eventually triggering its
1507  * initialization, and returning the protocol specific operations and related
1508  * protocol handle which will be used as first argument in most of the
1509  * protocols operations methods.
1510  * Being a devres based managed method, protocol hold will be automatically
1511  * released, and possibly de-initialized on last user, once the SCMI driver
1512  * owning the scmi_device is unbound from it.
1513  *
1514  * Return: A reference to the requested protocol operations or error.
1515  *	   Must be checked for errors by caller.
1516  */
1517 static const void __must_check *
1518 scmi_devm_protocol_get(struct scmi_device *sdev, u8 protocol_id,
1519 		       struct scmi_protocol_handle **ph)
1520 {
1521 	struct scmi_protocol_instance *pi;
1522 	struct scmi_protocol_devres *dres;
1523 	struct scmi_handle *handle = sdev->handle;
1524 
1525 	if (!ph)
1526 		return ERR_PTR(-EINVAL);
1527 
1528 	dres = devres_alloc(scmi_devm_release_protocol,
1529 			    sizeof(*dres), GFP_KERNEL);
1530 	if (!dres)
1531 		return ERR_PTR(-ENOMEM);
1532 
1533 	pi = scmi_get_protocol_instance(handle, protocol_id);
1534 	if (IS_ERR(pi)) {
1535 		devres_free(dres);
1536 		return pi;
1537 	}
1538 
1539 	dres->handle = handle;
1540 	dres->protocol_id = protocol_id;
1541 	devres_add(&sdev->dev, dres);
1542 
1543 	*ph = &pi->ph;
1544 
1545 	return pi->proto->ops;
1546 }
1547 
1548 static int scmi_devm_protocol_match(struct device *dev, void *res, void *data)
1549 {
1550 	struct scmi_protocol_devres *dres = res;
1551 
1552 	if (WARN_ON(!dres || !data))
1553 		return 0;
1554 
1555 	return dres->protocol_id == *((u8 *)data);
1556 }
1557 
1558 /**
1559  * scmi_devm_protocol_put  - Devres managed put protocol operations and handle
1560  * @sdev: A reference to an scmi_device whose embedded struct device is to
1561  *	  be used for devres accounting.
1562  * @protocol_id: The protocol being requested.
1563  *
1564  * Explicitly release a protocol hold previously obtained calling the above
1565  * @scmi_devm_protocol_get.
1566  */
1567 static void scmi_devm_protocol_put(struct scmi_device *sdev, u8 protocol_id)
1568 {
1569 	int ret;
1570 
1571 	ret = devres_release(&sdev->dev, scmi_devm_release_protocol,
1572 			     scmi_devm_protocol_match, &protocol_id);
1573 	WARN_ON(ret);
1574 }
1575 
1576 /**
1577  * scmi_is_transport_atomic  - Method to check if underlying transport for an
1578  * SCMI instance is configured as atomic.
1579  *
1580  * @handle: A reference to the SCMI platform instance.
1581  * @atomic_threshold: An optional return value for the system wide currently
1582  *		      configured threshold for atomic operations.
1583  *
1584  * Return: True if transport is configured as atomic
1585  */
1586 static bool scmi_is_transport_atomic(const struct scmi_handle *handle,
1587 				     unsigned int *atomic_threshold)
1588 {
1589 	bool ret;
1590 	struct scmi_info *info = handle_to_scmi_info(handle);
1591 
1592 	ret = info->desc->atomic_enabled && is_transport_polling_capable(info);
1593 	if (ret && atomic_threshold)
1594 		*atomic_threshold = info->atomic_threshold;
1595 
1596 	return ret;
1597 }
1598 
1599 static inline
1600 struct scmi_handle *scmi_handle_get_from_info_unlocked(struct scmi_info *info)
1601 {
1602 	info->users++;
1603 	return &info->handle;
1604 }
1605 
1606 /**
1607  * scmi_handle_get() - Get the SCMI handle for a device
1608  *
1609  * @dev: pointer to device for which we want SCMI handle
1610  *
1611  * NOTE: The function does not track individual clients of the framework
1612  * and is expected to be maintained by caller of SCMI protocol library.
1613  * scmi_handle_put must be balanced with successful scmi_handle_get
1614  *
1615  * Return: pointer to handle if successful, NULL on error
1616  */
1617 struct scmi_handle *scmi_handle_get(struct device *dev)
1618 {
1619 	struct list_head *p;
1620 	struct scmi_info *info;
1621 	struct scmi_handle *handle = NULL;
1622 
1623 	mutex_lock(&scmi_list_mutex);
1624 	list_for_each(p, &scmi_list) {
1625 		info = list_entry(p, struct scmi_info, node);
1626 		if (dev->parent == info->dev) {
1627 			handle = scmi_handle_get_from_info_unlocked(info);
1628 			break;
1629 		}
1630 	}
1631 	mutex_unlock(&scmi_list_mutex);
1632 
1633 	return handle;
1634 }
1635 
1636 /**
1637  * scmi_handle_put() - Release the handle acquired by scmi_handle_get
1638  *
1639  * @handle: handle acquired by scmi_handle_get
1640  *
1641  * NOTE: The function does not track individual clients of the framework
1642  * and is expected to be maintained by caller of SCMI protocol library.
1643  * scmi_handle_put must be balanced with successful scmi_handle_get
1644  *
1645  * Return: 0 is successfully released
1646  *	if null was passed, it returns -EINVAL;
1647  */
1648 int scmi_handle_put(const struct scmi_handle *handle)
1649 {
1650 	struct scmi_info *info;
1651 
1652 	if (!handle)
1653 		return -EINVAL;
1654 
1655 	info = handle_to_scmi_info(handle);
1656 	mutex_lock(&scmi_list_mutex);
1657 	if (!WARN_ON(!info->users))
1658 		info->users--;
1659 	mutex_unlock(&scmi_list_mutex);
1660 
1661 	return 0;
1662 }
1663 
1664 static int __scmi_xfer_info_init(struct scmi_info *sinfo,
1665 				 struct scmi_xfers_info *info)
1666 {
1667 	int i;
1668 	struct scmi_xfer *xfer;
1669 	struct device *dev = sinfo->dev;
1670 	const struct scmi_desc *desc = sinfo->desc;
1671 
1672 	/* Pre-allocated messages, no more than what hdr.seq can support */
1673 	if (WARN_ON(!info->max_msg || info->max_msg > MSG_TOKEN_MAX)) {
1674 		dev_err(dev,
1675 			"Invalid maximum messages %d, not in range [1 - %lu]\n",
1676 			info->max_msg, MSG_TOKEN_MAX);
1677 		return -EINVAL;
1678 	}
1679 
1680 	hash_init(info->pending_xfers);
1681 
1682 	/* Allocate a bitmask sized to hold MSG_TOKEN_MAX tokens */
1683 	info->xfer_alloc_table = devm_kcalloc(dev, BITS_TO_LONGS(MSG_TOKEN_MAX),
1684 					      sizeof(long), GFP_KERNEL);
1685 	if (!info->xfer_alloc_table)
1686 		return -ENOMEM;
1687 
1688 	/*
1689 	 * Preallocate a number of xfers equal to max inflight messages,
1690 	 * pre-initialize the buffer pointer to pre-allocated buffers and
1691 	 * attach all of them to the free list
1692 	 */
1693 	INIT_HLIST_HEAD(&info->free_xfers);
1694 	for (i = 0; i < info->max_msg; i++) {
1695 		xfer = devm_kzalloc(dev, sizeof(*xfer), GFP_KERNEL);
1696 		if (!xfer)
1697 			return -ENOMEM;
1698 
1699 		xfer->rx.buf = devm_kcalloc(dev, sizeof(u8), desc->max_msg_size,
1700 					    GFP_KERNEL);
1701 		if (!xfer->rx.buf)
1702 			return -ENOMEM;
1703 
1704 		xfer->tx.buf = xfer->rx.buf;
1705 		init_completion(&xfer->done);
1706 		spin_lock_init(&xfer->lock);
1707 
1708 		/* Add initialized xfer to the free list */
1709 		hlist_add_head(&xfer->node, &info->free_xfers);
1710 	}
1711 
1712 	spin_lock_init(&info->xfer_lock);
1713 
1714 	return 0;
1715 }
1716 
1717 static int scmi_channels_max_msg_configure(struct scmi_info *sinfo)
1718 {
1719 	const struct scmi_desc *desc = sinfo->desc;
1720 
1721 	if (!desc->ops->get_max_msg) {
1722 		sinfo->tx_minfo.max_msg = desc->max_msg;
1723 		sinfo->rx_minfo.max_msg = desc->max_msg;
1724 	} else {
1725 		struct scmi_chan_info *base_cinfo;
1726 
1727 		base_cinfo = idr_find(&sinfo->tx_idr, SCMI_PROTOCOL_BASE);
1728 		if (!base_cinfo)
1729 			return -EINVAL;
1730 		sinfo->tx_minfo.max_msg = desc->ops->get_max_msg(base_cinfo);
1731 
1732 		/* RX channel is optional so can be skipped */
1733 		base_cinfo = idr_find(&sinfo->rx_idr, SCMI_PROTOCOL_BASE);
1734 		if (base_cinfo)
1735 			sinfo->rx_minfo.max_msg =
1736 				desc->ops->get_max_msg(base_cinfo);
1737 	}
1738 
1739 	return 0;
1740 }
1741 
1742 static int scmi_xfer_info_init(struct scmi_info *sinfo)
1743 {
1744 	int ret;
1745 
1746 	ret = scmi_channels_max_msg_configure(sinfo);
1747 	if (ret)
1748 		return ret;
1749 
1750 	ret = __scmi_xfer_info_init(sinfo, &sinfo->tx_minfo);
1751 	if (!ret && idr_find(&sinfo->rx_idr, SCMI_PROTOCOL_BASE))
1752 		ret = __scmi_xfer_info_init(sinfo, &sinfo->rx_minfo);
1753 
1754 	return ret;
1755 }
1756 
1757 static int scmi_chan_setup(struct scmi_info *info, struct device *dev,
1758 			   int prot_id, bool tx)
1759 {
1760 	int ret, idx;
1761 	struct scmi_chan_info *cinfo;
1762 	struct idr *idr;
1763 
1764 	/* Transmit channel is first entry i.e. index 0 */
1765 	idx = tx ? 0 : 1;
1766 	idr = tx ? &info->tx_idr : &info->rx_idr;
1767 
1768 	/* check if already allocated, used for multiple device per protocol */
1769 	cinfo = idr_find(idr, prot_id);
1770 	if (cinfo)
1771 		return 0;
1772 
1773 	if (!info->desc->ops->chan_available(dev, idx)) {
1774 		cinfo = idr_find(idr, SCMI_PROTOCOL_BASE);
1775 		if (unlikely(!cinfo)) /* Possible only if platform has no Rx */
1776 			return -EINVAL;
1777 		goto idr_alloc;
1778 	}
1779 
1780 	cinfo = devm_kzalloc(info->dev, sizeof(*cinfo), GFP_KERNEL);
1781 	if (!cinfo)
1782 		return -ENOMEM;
1783 
1784 	cinfo->dev = dev;
1785 
1786 	ret = info->desc->ops->chan_setup(cinfo, info->dev, tx);
1787 	if (ret)
1788 		return ret;
1789 
1790 	if (tx && is_polling_required(cinfo, info)) {
1791 		if (is_transport_polling_capable(info))
1792 			dev_info(dev,
1793 				 "Enabled polling mode TX channel - prot_id:%d\n",
1794 				 prot_id);
1795 		else
1796 			dev_warn(dev,
1797 				 "Polling mode NOT supported by transport.\n");
1798 	}
1799 
1800 idr_alloc:
1801 	ret = idr_alloc(idr, cinfo, prot_id, prot_id + 1, GFP_KERNEL);
1802 	if (ret != prot_id) {
1803 		dev_err(dev, "unable to allocate SCMI idr slot err %d\n", ret);
1804 		return ret;
1805 	}
1806 
1807 	cinfo->handle = &info->handle;
1808 	return 0;
1809 }
1810 
1811 static inline int
1812 scmi_txrx_setup(struct scmi_info *info, struct device *dev, int prot_id)
1813 {
1814 	int ret = scmi_chan_setup(info, dev, prot_id, true);
1815 
1816 	if (!ret) /* Rx is optional, hence no error check */
1817 		scmi_chan_setup(info, dev, prot_id, false);
1818 
1819 	return ret;
1820 }
1821 
1822 /**
1823  * scmi_get_protocol_device  - Helper to get/create an SCMI device.
1824  *
1825  * @np: A device node representing a valid active protocols for the referred
1826  * SCMI instance.
1827  * @info: The referred SCMI instance for which we are getting/creating this
1828  * device.
1829  * @prot_id: The protocol ID.
1830  * @name: The device name.
1831  *
1832  * Referring to the specific SCMI instance identified by @info, this helper
1833  * takes care to return a properly initialized device matching the requested
1834  * @proto_id and @name: if device was still not existent it is created as a
1835  * child of the specified SCMI instance @info and its transport properly
1836  * initialized as usual.
1837  *
1838  * Return: A properly initialized scmi device, NULL otherwise.
1839  */
1840 static inline struct scmi_device *
1841 scmi_get_protocol_device(struct device_node *np, struct scmi_info *info,
1842 			 int prot_id, const char *name)
1843 {
1844 	struct scmi_device *sdev;
1845 
1846 	/* Already created for this parent SCMI instance ? */
1847 	sdev = scmi_child_dev_find(info->dev, prot_id, name);
1848 	if (sdev)
1849 		return sdev;
1850 
1851 	pr_debug("Creating SCMI device (%s) for protocol %x\n", name, prot_id);
1852 
1853 	sdev = scmi_device_create(np, info->dev, prot_id, name);
1854 	if (!sdev) {
1855 		dev_err(info->dev, "failed to create %d protocol device\n",
1856 			prot_id);
1857 		return NULL;
1858 	}
1859 
1860 	if (scmi_txrx_setup(info, &sdev->dev, prot_id)) {
1861 		dev_err(&sdev->dev, "failed to setup transport\n");
1862 		scmi_device_destroy(sdev);
1863 		return NULL;
1864 	}
1865 
1866 	return sdev;
1867 }
1868 
1869 static inline void
1870 scmi_create_protocol_device(struct device_node *np, struct scmi_info *info,
1871 			    int prot_id, const char *name)
1872 {
1873 	struct scmi_device *sdev;
1874 
1875 	sdev = scmi_get_protocol_device(np, info, prot_id, name);
1876 	if (!sdev)
1877 		return;
1878 
1879 	/* setup handle now as the transport is ready */
1880 	scmi_set_handle(sdev);
1881 }
1882 
1883 /**
1884  * scmi_create_protocol_devices  - Create devices for all pending requests for
1885  * this SCMI instance.
1886  *
1887  * @np: The device node describing the protocol
1888  * @info: The SCMI instance descriptor
1889  * @prot_id: The protocol ID
1890  *
1891  * All devices previously requested for this instance (if any) are found and
1892  * created by scanning the proper @&scmi_requested_devices entry.
1893  */
1894 static void scmi_create_protocol_devices(struct device_node *np,
1895 					 struct scmi_info *info, int prot_id)
1896 {
1897 	struct list_head *phead;
1898 
1899 	mutex_lock(&scmi_requested_devices_mtx);
1900 	phead = idr_find(&scmi_requested_devices, prot_id);
1901 	if (phead) {
1902 		struct scmi_requested_dev *rdev;
1903 
1904 		list_for_each_entry(rdev, phead, node)
1905 			scmi_create_protocol_device(np, info, prot_id,
1906 						    rdev->id_table->name);
1907 	}
1908 	mutex_unlock(&scmi_requested_devices_mtx);
1909 }
1910 
1911 /**
1912  * scmi_protocol_device_request  - Helper to request a device
1913  *
1914  * @id_table: A protocol/name pair descriptor for the device to be created.
1915  *
1916  * This helper let an SCMI driver request specific devices identified by the
1917  * @id_table to be created for each active SCMI instance.
1918  *
1919  * The requested device name MUST NOT be already existent for any protocol;
1920  * at first the freshly requested @id_table is annotated in the IDR table
1921  * @scmi_requested_devices, then a matching device is created for each already
1922  * active SCMI instance. (if any)
1923  *
1924  * This way the requested device is created straight-away for all the already
1925  * initialized(probed) SCMI instances (handles) and it remains also annotated
1926  * as pending creation if the requesting SCMI driver was loaded before some
1927  * SCMI instance and related transports were available: when such late instance
1928  * is probed, its probe will take care to scan the list of pending requested
1929  * devices and create those on its own (see @scmi_create_protocol_devices and
1930  * its enclosing loop)
1931  *
1932  * Return: 0 on Success
1933  */
1934 int scmi_protocol_device_request(const struct scmi_device_id *id_table)
1935 {
1936 	int ret = 0;
1937 	unsigned int id = 0;
1938 	struct list_head *head, *phead = NULL;
1939 	struct scmi_requested_dev *rdev;
1940 	struct scmi_info *info;
1941 
1942 	pr_debug("Requesting SCMI device (%s) for protocol %x\n",
1943 		 id_table->name, id_table->protocol_id);
1944 
1945 	/*
1946 	 * Search for the matching protocol rdev list and then search
1947 	 * of any existent equally named device...fails if any duplicate found.
1948 	 */
1949 	mutex_lock(&scmi_requested_devices_mtx);
1950 	idr_for_each_entry(&scmi_requested_devices, head, id) {
1951 		if (!phead) {
1952 			/* A list found registered in the IDR is never empty */
1953 			rdev = list_first_entry(head, struct scmi_requested_dev,
1954 						node);
1955 			if (rdev->id_table->protocol_id ==
1956 			    id_table->protocol_id)
1957 				phead = head;
1958 		}
1959 		list_for_each_entry(rdev, head, node) {
1960 			if (!strcmp(rdev->id_table->name, id_table->name)) {
1961 				pr_err("Ignoring duplicate request [%d] %s\n",
1962 				       rdev->id_table->protocol_id,
1963 				       rdev->id_table->name);
1964 				ret = -EINVAL;
1965 				goto out;
1966 			}
1967 		}
1968 	}
1969 
1970 	/*
1971 	 * No duplicate found for requested id_table, so let's create a new
1972 	 * requested device entry for this new valid request.
1973 	 */
1974 	rdev = kzalloc(sizeof(*rdev), GFP_KERNEL);
1975 	if (!rdev) {
1976 		ret = -ENOMEM;
1977 		goto out;
1978 	}
1979 	rdev->id_table = id_table;
1980 
1981 	/*
1982 	 * Append the new requested device table descriptor to the head of the
1983 	 * related protocol list, eventually creating such head if not already
1984 	 * there.
1985 	 */
1986 	if (!phead) {
1987 		phead = kzalloc(sizeof(*phead), GFP_KERNEL);
1988 		if (!phead) {
1989 			kfree(rdev);
1990 			ret = -ENOMEM;
1991 			goto out;
1992 		}
1993 		INIT_LIST_HEAD(phead);
1994 
1995 		ret = idr_alloc(&scmi_requested_devices, (void *)phead,
1996 				id_table->protocol_id,
1997 				id_table->protocol_id + 1, GFP_KERNEL);
1998 		if (ret != id_table->protocol_id) {
1999 			pr_err("Failed to save SCMI device - ret:%d\n", ret);
2000 			kfree(rdev);
2001 			kfree(phead);
2002 			ret = -EINVAL;
2003 			goto out;
2004 		}
2005 		ret = 0;
2006 	}
2007 	list_add(&rdev->node, phead);
2008 
2009 	/*
2010 	 * Now effectively create and initialize the requested device for every
2011 	 * already initialized SCMI instance which has registered the requested
2012 	 * protocol as a valid active one: i.e. defined in DT and supported by
2013 	 * current platform FW.
2014 	 */
2015 	mutex_lock(&scmi_list_mutex);
2016 	list_for_each_entry(info, &scmi_list, node) {
2017 		struct device_node *child;
2018 
2019 		child = idr_find(&info->active_protocols,
2020 				 id_table->protocol_id);
2021 		if (child) {
2022 			struct scmi_device *sdev;
2023 
2024 			sdev = scmi_get_protocol_device(child, info,
2025 							id_table->protocol_id,
2026 							id_table->name);
2027 			/* Set handle if not already set: device existed */
2028 			if (sdev && !sdev->handle)
2029 				sdev->handle =
2030 					scmi_handle_get_from_info_unlocked(info);
2031 		} else {
2032 			dev_err(info->dev,
2033 				"Failed. SCMI protocol %d not active.\n",
2034 				id_table->protocol_id);
2035 		}
2036 	}
2037 	mutex_unlock(&scmi_list_mutex);
2038 
2039 out:
2040 	mutex_unlock(&scmi_requested_devices_mtx);
2041 
2042 	return ret;
2043 }
2044 
2045 /**
2046  * scmi_protocol_device_unrequest  - Helper to unrequest a device
2047  *
2048  * @id_table: A protocol/name pair descriptor for the device to be unrequested.
2049  *
2050  * An helper to let an SCMI driver release its request about devices; note that
2051  * devices are created and initialized once the first SCMI driver request them
2052  * but they destroyed only on SCMI core unloading/unbinding.
2053  *
2054  * The current SCMI transport layer uses such devices as internal references and
2055  * as such they could be shared as same transport between multiple drivers so
2056  * that cannot be safely destroyed till the whole SCMI stack is removed.
2057  * (unless adding further burden of refcounting.)
2058  */
2059 void scmi_protocol_device_unrequest(const struct scmi_device_id *id_table)
2060 {
2061 	struct list_head *phead;
2062 
2063 	pr_debug("Unrequesting SCMI device (%s) for protocol %x\n",
2064 		 id_table->name, id_table->protocol_id);
2065 
2066 	mutex_lock(&scmi_requested_devices_mtx);
2067 	phead = idr_find(&scmi_requested_devices, id_table->protocol_id);
2068 	if (phead) {
2069 		struct scmi_requested_dev *victim, *tmp;
2070 
2071 		list_for_each_entry_safe(victim, tmp, phead, node) {
2072 			if (!strcmp(victim->id_table->name, id_table->name)) {
2073 				list_del(&victim->node);
2074 				kfree(victim);
2075 				break;
2076 			}
2077 		}
2078 
2079 		if (list_empty(phead)) {
2080 			idr_remove(&scmi_requested_devices,
2081 				   id_table->protocol_id);
2082 			kfree(phead);
2083 		}
2084 	}
2085 	mutex_unlock(&scmi_requested_devices_mtx);
2086 }
2087 
2088 static int scmi_cleanup_txrx_channels(struct scmi_info *info)
2089 {
2090 	int ret;
2091 	struct idr *idr = &info->tx_idr;
2092 
2093 	ret = idr_for_each(idr, info->desc->ops->chan_free, idr);
2094 	idr_destroy(&info->tx_idr);
2095 
2096 	idr = &info->rx_idr;
2097 	ret = idr_for_each(idr, info->desc->ops->chan_free, idr);
2098 	idr_destroy(&info->rx_idr);
2099 
2100 	return ret;
2101 }
2102 
2103 static int scmi_probe(struct platform_device *pdev)
2104 {
2105 	int ret;
2106 	struct scmi_handle *handle;
2107 	const struct scmi_desc *desc;
2108 	struct scmi_info *info;
2109 	struct device *dev = &pdev->dev;
2110 	struct device_node *child, *np = dev->of_node;
2111 
2112 	desc = of_device_get_match_data(dev);
2113 	if (!desc)
2114 		return -EINVAL;
2115 
2116 	info = devm_kzalloc(dev, sizeof(*info), GFP_KERNEL);
2117 	if (!info)
2118 		return -ENOMEM;
2119 
2120 	info->dev = dev;
2121 	info->desc = desc;
2122 	INIT_LIST_HEAD(&info->node);
2123 	idr_init(&info->protocols);
2124 	mutex_init(&info->protocols_mtx);
2125 	idr_init(&info->active_protocols);
2126 
2127 	platform_set_drvdata(pdev, info);
2128 	idr_init(&info->tx_idr);
2129 	idr_init(&info->rx_idr);
2130 
2131 	handle = &info->handle;
2132 	handle->dev = info->dev;
2133 	handle->version = &info->version;
2134 	handle->devm_protocol_get = scmi_devm_protocol_get;
2135 	handle->devm_protocol_put = scmi_devm_protocol_put;
2136 
2137 	/* System wide atomic threshold for atomic ops .. if any */
2138 	if (!of_property_read_u32(np, "atomic-threshold-us",
2139 				  &info->atomic_threshold))
2140 		dev_info(dev,
2141 			 "SCMI System wide atomic threshold set to %d us\n",
2142 			 info->atomic_threshold);
2143 	handle->is_transport_atomic = scmi_is_transport_atomic;
2144 
2145 	if (desc->ops->link_supplier) {
2146 		ret = desc->ops->link_supplier(dev);
2147 		if (ret)
2148 			return ret;
2149 	}
2150 
2151 	ret = scmi_txrx_setup(info, dev, SCMI_PROTOCOL_BASE);
2152 	if (ret)
2153 		return ret;
2154 
2155 	ret = scmi_xfer_info_init(info);
2156 	if (ret)
2157 		goto clear_txrx_setup;
2158 
2159 	if (scmi_notification_init(handle))
2160 		dev_err(dev, "SCMI Notifications NOT available.\n");
2161 
2162 	if (info->desc->atomic_enabled && !is_transport_polling_capable(info))
2163 		dev_err(dev,
2164 			"Transport is not polling capable. Atomic mode not supported.\n");
2165 
2166 	/*
2167 	 * Trigger SCMI Base protocol initialization.
2168 	 * It's mandatory and won't be ever released/deinit until the
2169 	 * SCMI stack is shutdown/unloaded as a whole.
2170 	 */
2171 	ret = scmi_protocol_acquire(handle, SCMI_PROTOCOL_BASE);
2172 	if (ret) {
2173 		dev_err(dev, "unable to communicate with SCMI\n");
2174 		goto notification_exit;
2175 	}
2176 
2177 	mutex_lock(&scmi_list_mutex);
2178 	list_add_tail(&info->node, &scmi_list);
2179 	mutex_unlock(&scmi_list_mutex);
2180 
2181 	for_each_available_child_of_node(np, child) {
2182 		u32 prot_id;
2183 
2184 		if (of_property_read_u32(child, "reg", &prot_id))
2185 			continue;
2186 
2187 		if (!FIELD_FIT(MSG_PROTOCOL_ID_MASK, prot_id))
2188 			dev_err(dev, "Out of range protocol %d\n", prot_id);
2189 
2190 		if (!scmi_is_protocol_implemented(handle, prot_id)) {
2191 			dev_err(dev, "SCMI protocol %d not implemented\n",
2192 				prot_id);
2193 			continue;
2194 		}
2195 
2196 		/*
2197 		 * Save this valid DT protocol descriptor amongst
2198 		 * @active_protocols for this SCMI instance/
2199 		 */
2200 		ret = idr_alloc(&info->active_protocols, child,
2201 				prot_id, prot_id + 1, GFP_KERNEL);
2202 		if (ret != prot_id) {
2203 			dev_err(dev, "SCMI protocol %d already activated. Skip\n",
2204 				prot_id);
2205 			continue;
2206 		}
2207 
2208 		of_node_get(child);
2209 		scmi_create_protocol_devices(child, info, prot_id);
2210 	}
2211 
2212 	return 0;
2213 
2214 notification_exit:
2215 	scmi_notification_exit(&info->handle);
2216 clear_txrx_setup:
2217 	scmi_cleanup_txrx_channels(info);
2218 	return ret;
2219 }
2220 
2221 void scmi_free_channel(struct scmi_chan_info *cinfo, struct idr *idr, int id)
2222 {
2223 	idr_remove(idr, id);
2224 }
2225 
2226 static int scmi_remove(struct platform_device *pdev)
2227 {
2228 	int ret = 0, id;
2229 	struct scmi_info *info = platform_get_drvdata(pdev);
2230 	struct device_node *child;
2231 
2232 	mutex_lock(&scmi_list_mutex);
2233 	if (info->users)
2234 		ret = -EBUSY;
2235 	else
2236 		list_del(&info->node);
2237 	mutex_unlock(&scmi_list_mutex);
2238 
2239 	if (ret)
2240 		return ret;
2241 
2242 	scmi_notification_exit(&info->handle);
2243 
2244 	mutex_lock(&info->protocols_mtx);
2245 	idr_destroy(&info->protocols);
2246 	mutex_unlock(&info->protocols_mtx);
2247 
2248 	idr_for_each_entry(&info->active_protocols, child, id)
2249 		of_node_put(child);
2250 	idr_destroy(&info->active_protocols);
2251 
2252 	/* Safe to free channels since no more users */
2253 	return scmi_cleanup_txrx_channels(info);
2254 }
2255 
2256 static ssize_t protocol_version_show(struct device *dev,
2257 				     struct device_attribute *attr, char *buf)
2258 {
2259 	struct scmi_info *info = dev_get_drvdata(dev);
2260 
2261 	return sprintf(buf, "%u.%u\n", info->version.major_ver,
2262 		       info->version.minor_ver);
2263 }
2264 static DEVICE_ATTR_RO(protocol_version);
2265 
2266 static ssize_t firmware_version_show(struct device *dev,
2267 				     struct device_attribute *attr, char *buf)
2268 {
2269 	struct scmi_info *info = dev_get_drvdata(dev);
2270 
2271 	return sprintf(buf, "0x%x\n", info->version.impl_ver);
2272 }
2273 static DEVICE_ATTR_RO(firmware_version);
2274 
2275 static ssize_t vendor_id_show(struct device *dev,
2276 			      struct device_attribute *attr, char *buf)
2277 {
2278 	struct scmi_info *info = dev_get_drvdata(dev);
2279 
2280 	return sprintf(buf, "%s\n", info->version.vendor_id);
2281 }
2282 static DEVICE_ATTR_RO(vendor_id);
2283 
2284 static ssize_t sub_vendor_id_show(struct device *dev,
2285 				  struct device_attribute *attr, char *buf)
2286 {
2287 	struct scmi_info *info = dev_get_drvdata(dev);
2288 
2289 	return sprintf(buf, "%s\n", info->version.sub_vendor_id);
2290 }
2291 static DEVICE_ATTR_RO(sub_vendor_id);
2292 
2293 static struct attribute *versions_attrs[] = {
2294 	&dev_attr_firmware_version.attr,
2295 	&dev_attr_protocol_version.attr,
2296 	&dev_attr_vendor_id.attr,
2297 	&dev_attr_sub_vendor_id.attr,
2298 	NULL,
2299 };
2300 ATTRIBUTE_GROUPS(versions);
2301 
2302 /* Each compatible listed below must have descriptor associated with it */
2303 static const struct of_device_id scmi_of_match[] = {
2304 #ifdef CONFIG_ARM_SCMI_TRANSPORT_MAILBOX
2305 	{ .compatible = "arm,scmi", .data = &scmi_mailbox_desc },
2306 #endif
2307 #ifdef CONFIG_ARM_SCMI_TRANSPORT_OPTEE
2308 	{ .compatible = "linaro,scmi-optee", .data = &scmi_optee_desc },
2309 #endif
2310 #ifdef CONFIG_ARM_SCMI_TRANSPORT_SMC
2311 	{ .compatible = "arm,scmi-smc", .data = &scmi_smc_desc},
2312 #endif
2313 #ifdef CONFIG_ARM_SCMI_TRANSPORT_VIRTIO
2314 	{ .compatible = "arm,scmi-virtio", .data = &scmi_virtio_desc},
2315 #endif
2316 	{ /* Sentinel */ },
2317 };
2318 
2319 MODULE_DEVICE_TABLE(of, scmi_of_match);
2320 
2321 static struct platform_driver scmi_driver = {
2322 	.driver = {
2323 		   .name = "arm-scmi",
2324 		   .of_match_table = scmi_of_match,
2325 		   .dev_groups = versions_groups,
2326 		   },
2327 	.probe = scmi_probe,
2328 	.remove = scmi_remove,
2329 };
2330 
2331 /**
2332  * __scmi_transports_setup  - Common helper to call transport-specific
2333  * .init/.exit code if provided.
2334  *
2335  * @init: A flag to distinguish between init and exit.
2336  *
2337  * Note that, if provided, we invoke .init/.exit functions for all the
2338  * transports currently compiled in.
2339  *
2340  * Return: 0 on Success.
2341  */
2342 static inline int __scmi_transports_setup(bool init)
2343 {
2344 	int ret = 0;
2345 	const struct of_device_id *trans;
2346 
2347 	for (trans = scmi_of_match; trans->data; trans++) {
2348 		const struct scmi_desc *tdesc = trans->data;
2349 
2350 		if ((init && !tdesc->transport_init) ||
2351 		    (!init && !tdesc->transport_exit))
2352 			continue;
2353 
2354 		if (init)
2355 			ret = tdesc->transport_init();
2356 		else
2357 			tdesc->transport_exit();
2358 
2359 		if (ret) {
2360 			pr_err("SCMI transport %s FAILED initialization!\n",
2361 			       trans->compatible);
2362 			break;
2363 		}
2364 	}
2365 
2366 	return ret;
2367 }
2368 
2369 static int __init scmi_transports_init(void)
2370 {
2371 	return __scmi_transports_setup(true);
2372 }
2373 
2374 static void __exit scmi_transports_exit(void)
2375 {
2376 	__scmi_transports_setup(false);
2377 }
2378 
2379 static int __init scmi_driver_init(void)
2380 {
2381 	int ret;
2382 
2383 	/* Bail out if no SCMI transport was configured */
2384 	if (WARN_ON(!IS_ENABLED(CONFIG_ARM_SCMI_HAVE_TRANSPORT)))
2385 		return -EINVAL;
2386 
2387 	scmi_bus_init();
2388 
2389 	/* Initialize any compiled-in transport which provided an init/exit */
2390 	ret = scmi_transports_init();
2391 	if (ret)
2392 		return ret;
2393 
2394 	scmi_base_register();
2395 
2396 	scmi_clock_register();
2397 	scmi_perf_register();
2398 	scmi_power_register();
2399 	scmi_reset_register();
2400 	scmi_sensors_register();
2401 	scmi_voltage_register();
2402 	scmi_system_register();
2403 
2404 	return platform_driver_register(&scmi_driver);
2405 }
2406 subsys_initcall(scmi_driver_init);
2407 
2408 static void __exit scmi_driver_exit(void)
2409 {
2410 	scmi_base_unregister();
2411 
2412 	scmi_clock_unregister();
2413 	scmi_perf_unregister();
2414 	scmi_power_unregister();
2415 	scmi_reset_unregister();
2416 	scmi_sensors_unregister();
2417 	scmi_voltage_unregister();
2418 	scmi_system_unregister();
2419 
2420 	scmi_bus_exit();
2421 
2422 	scmi_transports_exit();
2423 
2424 	platform_driver_unregister(&scmi_driver);
2425 }
2426 module_exit(scmi_driver_exit);
2427 
2428 MODULE_ALIAS("platform:arm-scmi");
2429 MODULE_AUTHOR("Sudeep Holla <sudeep.holla@arm.com>");
2430 MODULE_DESCRIPTION("ARM SCMI protocol driver");
2431 MODULE_LICENSE("GPL v2");
2432