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