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