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