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