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