firmware: arm_scmi: Add optional link_supplier() transport op
[linux-2.6-microblaze.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, u32 msg_hdr)
613 {
614         struct scmi_xfer *xfer;
615         struct device *dev = cinfo->dev;
616         struct scmi_info *info = handle_to_scmi_info(cinfo->handle);
617         struct scmi_xfers_info *minfo = &info->rx_minfo;
618         ktime_t ts;
619
620         ts = ktime_get_boottime();
621         xfer = scmi_xfer_get(cinfo->handle, minfo, false);
622         if (IS_ERR(xfer)) {
623                 dev_err(dev, "failed to get free message slot (%ld)\n",
624                         PTR_ERR(xfer));
625                 scmi_clear_channel(info, cinfo);
626                 return;
627         }
628
629         unpack_scmi_header(msg_hdr, &xfer->hdr);
630         info->desc->ops->fetch_notification(cinfo, info->desc->max_msg_size,
631                                             xfer);
632         scmi_notify(cinfo->handle, xfer->hdr.protocol_id,
633                     xfer->hdr.id, xfer->rx.buf, xfer->rx.len, ts);
634
635         trace_scmi_rx_done(xfer->transfer_id, xfer->hdr.id,
636                            xfer->hdr.protocol_id, xfer->hdr.seq,
637                            MSG_TYPE_NOTIFICATION);
638
639         __scmi_xfer_put(minfo, xfer);
640
641         scmi_clear_channel(info, cinfo);
642 }
643
644 static void scmi_handle_response(struct scmi_chan_info *cinfo, u32 msg_hdr)
645 {
646         struct scmi_xfer *xfer;
647         struct scmi_info *info = handle_to_scmi_info(cinfo->handle);
648
649         xfer = scmi_xfer_command_acquire(cinfo, msg_hdr);
650         if (IS_ERR(xfer)) {
651                 scmi_clear_channel(info, cinfo);
652                 return;
653         }
654
655         /* rx.len could be shrunk in the sync do_xfer, so reset to maxsz */
656         if (xfer->hdr.type == MSG_TYPE_DELAYED_RESP)
657                 xfer->rx.len = info->desc->max_msg_size;
658
659         info->desc->ops->fetch_response(cinfo, xfer);
660
661         trace_scmi_rx_done(xfer->transfer_id, xfer->hdr.id,
662                            xfer->hdr.protocol_id, xfer->hdr.seq,
663                            xfer->hdr.type);
664
665         if (xfer->hdr.type == MSG_TYPE_DELAYED_RESP) {
666                 scmi_clear_channel(info, cinfo);
667                 complete(xfer->async_done);
668         } else {
669                 complete(&xfer->done);
670         }
671
672         scmi_xfer_command_release(info, xfer);
673 }
674
675 /**
676  * scmi_rx_callback() - callback for receiving messages
677  *
678  * @cinfo: SCMI channel info
679  * @msg_hdr: Message header
680  *
681  * Processes one received message to appropriate transfer information and
682  * signals completion of the transfer.
683  *
684  * NOTE: This function will be invoked in IRQ context, hence should be
685  * as optimal as possible.
686  */
687 void scmi_rx_callback(struct scmi_chan_info *cinfo, u32 msg_hdr)
688 {
689         u8 msg_type = MSG_XTRACT_TYPE(msg_hdr);
690
691         switch (msg_type) {
692         case MSG_TYPE_NOTIFICATION:
693                 scmi_handle_notification(cinfo, msg_hdr);
694                 break;
695         case MSG_TYPE_COMMAND:
696         case MSG_TYPE_DELAYED_RESP:
697                 scmi_handle_response(cinfo, msg_hdr);
698                 break;
699         default:
700                 WARN_ONCE(1, "received unknown msg_type:%d\n", msg_type);
701                 break;
702         }
703 }
704
705 /**
706  * xfer_put() - Release a transmit message
707  *
708  * @ph: Pointer to SCMI protocol handle
709  * @xfer: message that was reserved by xfer_get_init
710  */
711 static void xfer_put(const struct scmi_protocol_handle *ph,
712                      struct scmi_xfer *xfer)
713 {
714         const struct scmi_protocol_instance *pi = ph_to_pi(ph);
715         struct scmi_info *info = handle_to_scmi_info(pi->handle);
716
717         __scmi_xfer_put(&info->tx_minfo, xfer);
718 }
719
720 #define SCMI_MAX_POLL_TO_NS     (100 * NSEC_PER_USEC)
721
722 static bool scmi_xfer_done_no_timeout(struct scmi_chan_info *cinfo,
723                                       struct scmi_xfer *xfer, ktime_t stop)
724 {
725         struct scmi_info *info = handle_to_scmi_info(cinfo->handle);
726
727         /*
728          * Poll also on xfer->done so that polling can be forcibly terminated
729          * in case of out-of-order receptions of delayed responses
730          */
731         return info->desc->ops->poll_done(cinfo, xfer) ||
732                try_wait_for_completion(&xfer->done) ||
733                ktime_after(ktime_get(), stop);
734 }
735
736 /**
737  * do_xfer() - Do one transfer
738  *
739  * @ph: Pointer to SCMI protocol handle
740  * @xfer: Transfer to initiate and wait for response
741  *
742  * Return: -ETIMEDOUT in case of no response, if transmit error,
743  *      return corresponding error, else if all goes well,
744  *      return 0.
745  */
746 static int do_xfer(const struct scmi_protocol_handle *ph,
747                    struct scmi_xfer *xfer)
748 {
749         int ret;
750         int timeout;
751         const struct scmi_protocol_instance *pi = ph_to_pi(ph);
752         struct scmi_info *info = handle_to_scmi_info(pi->handle);
753         struct device *dev = info->dev;
754         struct scmi_chan_info *cinfo;
755
756         if (xfer->hdr.poll_completion && !info->desc->ops->poll_done) {
757                 dev_warn_once(dev,
758                               "Polling mode is not supported by transport.\n");
759                 return -EINVAL;
760         }
761
762         /*
763          * Initialise protocol id now from protocol handle to avoid it being
764          * overridden by mistake (or malice) by the protocol code mangling with
765          * the scmi_xfer structure prior to this.
766          */
767         xfer->hdr.protocol_id = pi->proto->id;
768         reinit_completion(&xfer->done);
769
770         cinfo = idr_find(&info->tx_idr, xfer->hdr.protocol_id);
771         if (unlikely(!cinfo))
772                 return -EINVAL;
773
774         trace_scmi_xfer_begin(xfer->transfer_id, xfer->hdr.id,
775                               xfer->hdr.protocol_id, xfer->hdr.seq,
776                               xfer->hdr.poll_completion);
777
778         xfer->state = SCMI_XFER_SENT_OK;
779         /*
780          * Even though spinlocking is not needed here since no race is possible
781          * on xfer->state due to the monotonically increasing tokens allocation,
782          * we must anyway ensure xfer->state initialization is not re-ordered
783          * after the .send_message() to be sure that on the RX path an early
784          * ISR calling scmi_rx_callback() cannot see an old stale xfer->state.
785          */
786         smp_mb();
787
788         ret = info->desc->ops->send_message(cinfo, xfer);
789         if (ret < 0) {
790                 dev_dbg(dev, "Failed to send message %d\n", ret);
791                 return ret;
792         }
793
794         if (xfer->hdr.poll_completion) {
795                 ktime_t stop = ktime_add_ns(ktime_get(), SCMI_MAX_POLL_TO_NS);
796
797                 spin_until_cond(scmi_xfer_done_no_timeout(cinfo, xfer, stop));
798                 if (ktime_before(ktime_get(), stop)) {
799                         unsigned long flags;
800
801                         /*
802                          * Do not fetch_response if an out-of-order delayed
803                          * response is being processed.
804                          */
805                         spin_lock_irqsave(&xfer->lock, flags);
806                         if (xfer->state == SCMI_XFER_SENT_OK) {
807                                 info->desc->ops->fetch_response(cinfo, xfer);
808                                 xfer->state = SCMI_XFER_RESP_OK;
809                         }
810                         spin_unlock_irqrestore(&xfer->lock, flags);
811                 } else {
812                         ret = -ETIMEDOUT;
813                 }
814         } else {
815                 /* And we wait for the response. */
816                 timeout = msecs_to_jiffies(info->desc->max_rx_timeout_ms);
817                 if (!wait_for_completion_timeout(&xfer->done, timeout)) {
818                         dev_err(dev, "timed out in resp(caller: %pS)\n",
819                                 (void *)_RET_IP_);
820                         ret = -ETIMEDOUT;
821                 }
822         }
823
824         if (!ret && xfer->hdr.status)
825                 ret = scmi_to_linux_errno(xfer->hdr.status);
826
827         if (info->desc->ops->mark_txdone)
828                 info->desc->ops->mark_txdone(cinfo, ret);
829
830         trace_scmi_xfer_end(xfer->transfer_id, xfer->hdr.id,
831                             xfer->hdr.protocol_id, xfer->hdr.seq, ret);
832
833         return ret;
834 }
835
836 static void reset_rx_to_maxsz(const struct scmi_protocol_handle *ph,
837                               struct scmi_xfer *xfer)
838 {
839         const struct scmi_protocol_instance *pi = ph_to_pi(ph);
840         struct scmi_info *info = handle_to_scmi_info(pi->handle);
841
842         xfer->rx.len = info->desc->max_msg_size;
843 }
844
845 #define SCMI_MAX_RESPONSE_TIMEOUT       (2 * MSEC_PER_SEC)
846
847 /**
848  * do_xfer_with_response() - Do one transfer and wait until the delayed
849  *      response is received
850  *
851  * @ph: Pointer to SCMI protocol handle
852  * @xfer: Transfer to initiate and wait for response
853  *
854  * Return: -ETIMEDOUT in case of no delayed response, if transmit error,
855  *      return corresponding error, else if all goes well, return 0.
856  */
857 static int do_xfer_with_response(const struct scmi_protocol_handle *ph,
858                                  struct scmi_xfer *xfer)
859 {
860         int ret, timeout = msecs_to_jiffies(SCMI_MAX_RESPONSE_TIMEOUT);
861         DECLARE_COMPLETION_ONSTACK(async_response);
862
863         xfer->async_done = &async_response;
864
865         ret = do_xfer(ph, xfer);
866         if (!ret) {
867                 if (!wait_for_completion_timeout(xfer->async_done, timeout))
868                         ret = -ETIMEDOUT;
869                 else if (xfer->hdr.status)
870                         ret = scmi_to_linux_errno(xfer->hdr.status);
871         }
872
873         xfer->async_done = NULL;
874         return ret;
875 }
876
877 /**
878  * xfer_get_init() - Allocate and initialise one message for transmit
879  *
880  * @ph: Pointer to SCMI protocol handle
881  * @msg_id: Message identifier
882  * @tx_size: transmit message size
883  * @rx_size: receive message size
884  * @p: pointer to the allocated and initialised message
885  *
886  * This function allocates the message using @scmi_xfer_get and
887  * initialise the header.
888  *
889  * Return: 0 if all went fine with @p pointing to message, else
890  *      corresponding error.
891  */
892 static int xfer_get_init(const struct scmi_protocol_handle *ph,
893                          u8 msg_id, size_t tx_size, size_t rx_size,
894                          struct scmi_xfer **p)
895 {
896         int ret;
897         struct scmi_xfer *xfer;
898         const struct scmi_protocol_instance *pi = ph_to_pi(ph);
899         struct scmi_info *info = handle_to_scmi_info(pi->handle);
900         struct scmi_xfers_info *minfo = &info->tx_minfo;
901         struct device *dev = info->dev;
902
903         /* Ensure we have sane transfer sizes */
904         if (rx_size > info->desc->max_msg_size ||
905             tx_size > info->desc->max_msg_size)
906                 return -ERANGE;
907
908         xfer = scmi_xfer_get(pi->handle, minfo, true);
909         if (IS_ERR(xfer)) {
910                 ret = PTR_ERR(xfer);
911                 dev_err(dev, "failed to get free message slot(%d)\n", ret);
912                 return ret;
913         }
914
915         xfer->tx.len = tx_size;
916         xfer->rx.len = rx_size ? : info->desc->max_msg_size;
917         xfer->hdr.type = MSG_TYPE_COMMAND;
918         xfer->hdr.id = msg_id;
919         xfer->hdr.poll_completion = false;
920
921         *p = xfer;
922
923         return 0;
924 }
925
926 /**
927  * version_get() - command to get the revision of the SCMI entity
928  *
929  * @ph: Pointer to SCMI protocol handle
930  * @version: Holds returned version of protocol.
931  *
932  * Updates the SCMI information in the internal data structure.
933  *
934  * Return: 0 if all went fine, else return appropriate error.
935  */
936 static int version_get(const struct scmi_protocol_handle *ph, u32 *version)
937 {
938         int ret;
939         __le32 *rev_info;
940         struct scmi_xfer *t;
941
942         ret = xfer_get_init(ph, PROTOCOL_VERSION, 0, sizeof(*version), &t);
943         if (ret)
944                 return ret;
945
946         ret = do_xfer(ph, t);
947         if (!ret) {
948                 rev_info = t->rx.buf;
949                 *version = le32_to_cpu(*rev_info);
950         }
951
952         xfer_put(ph, t);
953         return ret;
954 }
955
956 /**
957  * scmi_set_protocol_priv  - Set protocol specific data at init time
958  *
959  * @ph: A reference to the protocol handle.
960  * @priv: The private data to set.
961  *
962  * Return: 0 on Success
963  */
964 static int scmi_set_protocol_priv(const struct scmi_protocol_handle *ph,
965                                   void *priv)
966 {
967         struct scmi_protocol_instance *pi = ph_to_pi(ph);
968
969         pi->priv = priv;
970
971         return 0;
972 }
973
974 /**
975  * scmi_get_protocol_priv  - Set protocol specific data at init time
976  *
977  * @ph: A reference to the protocol handle.
978  *
979  * Return: Protocol private data if any was set.
980  */
981 static void *scmi_get_protocol_priv(const struct scmi_protocol_handle *ph)
982 {
983         const struct scmi_protocol_instance *pi = ph_to_pi(ph);
984
985         return pi->priv;
986 }
987
988 static const struct scmi_xfer_ops xfer_ops = {
989         .version_get = version_get,
990         .xfer_get_init = xfer_get_init,
991         .reset_rx_to_maxsz = reset_rx_to_maxsz,
992         .do_xfer = do_xfer,
993         .do_xfer_with_response = do_xfer_with_response,
994         .xfer_put = xfer_put,
995 };
996
997 /**
998  * scmi_revision_area_get  - Retrieve version memory area.
999  *
1000  * @ph: A reference to the protocol handle.
1001  *
1002  * A helper to grab the version memory area reference during SCMI Base protocol
1003  * initialization.
1004  *
1005  * Return: A reference to the version memory area associated to the SCMI
1006  *         instance underlying this protocol handle.
1007  */
1008 struct scmi_revision_info *
1009 scmi_revision_area_get(const struct scmi_protocol_handle *ph)
1010 {
1011         const struct scmi_protocol_instance *pi = ph_to_pi(ph);
1012
1013         return pi->handle->version;
1014 }
1015
1016 /**
1017  * scmi_alloc_init_protocol_instance  - Allocate and initialize a protocol
1018  * instance descriptor.
1019  * @info: The reference to the related SCMI instance.
1020  * @proto: The protocol descriptor.
1021  *
1022  * Allocate a new protocol instance descriptor, using the provided @proto
1023  * description, against the specified SCMI instance @info, and initialize it;
1024  * all resources management is handled via a dedicated per-protocol devres
1025  * group.
1026  *
1027  * Context: Assumes to be called with @protocols_mtx already acquired.
1028  * Return: A reference to a freshly allocated and initialized protocol instance
1029  *         or ERR_PTR on failure. On failure the @proto reference is at first
1030  *         put using @scmi_protocol_put() before releasing all the devres group.
1031  */
1032 static struct scmi_protocol_instance *
1033 scmi_alloc_init_protocol_instance(struct scmi_info *info,
1034                                   const struct scmi_protocol *proto)
1035 {
1036         int ret = -ENOMEM;
1037         void *gid;
1038         struct scmi_protocol_instance *pi;
1039         const struct scmi_handle *handle = &info->handle;
1040
1041         /* Protocol specific devres group */
1042         gid = devres_open_group(handle->dev, NULL, GFP_KERNEL);
1043         if (!gid) {
1044                 scmi_protocol_put(proto->id);
1045                 goto out;
1046         }
1047
1048         pi = devm_kzalloc(handle->dev, sizeof(*pi), GFP_KERNEL);
1049         if (!pi)
1050                 goto clean;
1051
1052         pi->gid = gid;
1053         pi->proto = proto;
1054         pi->handle = handle;
1055         pi->ph.dev = handle->dev;
1056         pi->ph.xops = &xfer_ops;
1057         pi->ph.set_priv = scmi_set_protocol_priv;
1058         pi->ph.get_priv = scmi_get_protocol_priv;
1059         refcount_set(&pi->users, 1);
1060         /* proto->init is assured NON NULL by scmi_protocol_register */
1061         ret = pi->proto->instance_init(&pi->ph);
1062         if (ret)
1063                 goto clean;
1064
1065         ret = idr_alloc(&info->protocols, pi, proto->id, proto->id + 1,
1066                         GFP_KERNEL);
1067         if (ret != proto->id)
1068                 goto clean;
1069
1070         /*
1071          * Warn but ignore events registration errors since we do not want
1072          * to skip whole protocols if their notifications are messed up.
1073          */
1074         if (pi->proto->events) {
1075                 ret = scmi_register_protocol_events(handle, pi->proto->id,
1076                                                     &pi->ph,
1077                                                     pi->proto->events);
1078                 if (ret)
1079                         dev_warn(handle->dev,
1080                                  "Protocol:%X - Events Registration Failed - err:%d\n",
1081                                  pi->proto->id, ret);
1082         }
1083
1084         devres_close_group(handle->dev, pi->gid);
1085         dev_dbg(handle->dev, "Initialized protocol: 0x%X\n", pi->proto->id);
1086
1087         return pi;
1088
1089 clean:
1090         /* Take care to put the protocol module's owner before releasing all */
1091         scmi_protocol_put(proto->id);
1092         devres_release_group(handle->dev, gid);
1093 out:
1094         return ERR_PTR(ret);
1095 }
1096
1097 /**
1098  * scmi_get_protocol_instance  - Protocol initialization helper.
1099  * @handle: A reference to the SCMI platform instance.
1100  * @protocol_id: The protocol being requested.
1101  *
1102  * In case the required protocol has never been requested before for this
1103  * instance, allocate and initialize all the needed structures while handling
1104  * resource allocation with a dedicated per-protocol devres subgroup.
1105  *
1106  * Return: A reference to an initialized protocol instance or error on failure:
1107  *         in particular returns -EPROBE_DEFER when the desired protocol could
1108  *         NOT be found.
1109  */
1110 static struct scmi_protocol_instance * __must_check
1111 scmi_get_protocol_instance(const struct scmi_handle *handle, u8 protocol_id)
1112 {
1113         struct scmi_protocol_instance *pi;
1114         struct scmi_info *info = handle_to_scmi_info(handle);
1115
1116         mutex_lock(&info->protocols_mtx);
1117         pi = idr_find(&info->protocols, protocol_id);
1118
1119         if (pi) {
1120                 refcount_inc(&pi->users);
1121         } else {
1122                 const struct scmi_protocol *proto;
1123
1124                 /* Fails if protocol not registered on bus */
1125                 proto = scmi_protocol_get(protocol_id);
1126                 if (proto)
1127                         pi = scmi_alloc_init_protocol_instance(info, proto);
1128                 else
1129                         pi = ERR_PTR(-EPROBE_DEFER);
1130         }
1131         mutex_unlock(&info->protocols_mtx);
1132
1133         return pi;
1134 }
1135
1136 /**
1137  * scmi_protocol_acquire  - Protocol acquire
1138  * @handle: A reference to the SCMI platform instance.
1139  * @protocol_id: The protocol being requested.
1140  *
1141  * Register a new user for the requested protocol on the specified SCMI
1142  * platform instance, possibly triggering its initialization on first user.
1143  *
1144  * Return: 0 if protocol was acquired successfully.
1145  */
1146 int scmi_protocol_acquire(const struct scmi_handle *handle, u8 protocol_id)
1147 {
1148         return PTR_ERR_OR_ZERO(scmi_get_protocol_instance(handle, protocol_id));
1149 }
1150
1151 /**
1152  * scmi_protocol_release  - Protocol de-initialization helper.
1153  * @handle: A reference to the SCMI platform instance.
1154  * @protocol_id: The protocol being requested.
1155  *
1156  * Remove one user for the specified protocol and triggers de-initialization
1157  * and resources de-allocation once the last user has gone.
1158  */
1159 void scmi_protocol_release(const struct scmi_handle *handle, u8 protocol_id)
1160 {
1161         struct scmi_info *info = handle_to_scmi_info(handle);
1162         struct scmi_protocol_instance *pi;
1163
1164         mutex_lock(&info->protocols_mtx);
1165         pi = idr_find(&info->protocols, protocol_id);
1166         if (WARN_ON(!pi))
1167                 goto out;
1168
1169         if (refcount_dec_and_test(&pi->users)) {
1170                 void *gid = pi->gid;
1171
1172                 if (pi->proto->events)
1173                         scmi_deregister_protocol_events(handle, protocol_id);
1174
1175                 if (pi->proto->instance_deinit)
1176                         pi->proto->instance_deinit(&pi->ph);
1177
1178                 idr_remove(&info->protocols, protocol_id);
1179
1180                 scmi_protocol_put(protocol_id);
1181
1182                 devres_release_group(handle->dev, gid);
1183                 dev_dbg(handle->dev, "De-Initialized protocol: 0x%X\n",
1184                         protocol_id);
1185         }
1186
1187 out:
1188         mutex_unlock(&info->protocols_mtx);
1189 }
1190
1191 void scmi_setup_protocol_implemented(const struct scmi_protocol_handle *ph,
1192                                      u8 *prot_imp)
1193 {
1194         const struct scmi_protocol_instance *pi = ph_to_pi(ph);
1195         struct scmi_info *info = handle_to_scmi_info(pi->handle);
1196
1197         info->protocols_imp = prot_imp;
1198 }
1199
1200 static bool
1201 scmi_is_protocol_implemented(const struct scmi_handle *handle, u8 prot_id)
1202 {
1203         int i;
1204         struct scmi_info *info = handle_to_scmi_info(handle);
1205
1206         if (!info->protocols_imp)
1207                 return false;
1208
1209         for (i = 0; i < MAX_PROTOCOLS_IMP; i++)
1210                 if (info->protocols_imp[i] == prot_id)
1211                         return true;
1212         return false;
1213 }
1214
1215 struct scmi_protocol_devres {
1216         const struct scmi_handle *handle;
1217         u8 protocol_id;
1218 };
1219
1220 static void scmi_devm_release_protocol(struct device *dev, void *res)
1221 {
1222         struct scmi_protocol_devres *dres = res;
1223
1224         scmi_protocol_release(dres->handle, dres->protocol_id);
1225 }
1226
1227 /**
1228  * scmi_devm_protocol_get  - Devres managed get protocol operations and handle
1229  * @sdev: A reference to an scmi_device whose embedded struct device is to
1230  *        be used for devres accounting.
1231  * @protocol_id: The protocol being requested.
1232  * @ph: A pointer reference used to pass back the associated protocol handle.
1233  *
1234  * Get hold of a protocol accounting for its usage, eventually triggering its
1235  * initialization, and returning the protocol specific operations and related
1236  * protocol handle which will be used as first argument in most of the
1237  * protocols operations methods.
1238  * Being a devres based managed method, protocol hold will be automatically
1239  * released, and possibly de-initialized on last user, once the SCMI driver
1240  * owning the scmi_device is unbound from it.
1241  *
1242  * Return: A reference to the requested protocol operations or error.
1243  *         Must be checked for errors by caller.
1244  */
1245 static const void __must_check *
1246 scmi_devm_protocol_get(struct scmi_device *sdev, u8 protocol_id,
1247                        struct scmi_protocol_handle **ph)
1248 {
1249         struct scmi_protocol_instance *pi;
1250         struct scmi_protocol_devres *dres;
1251         struct scmi_handle *handle = sdev->handle;
1252
1253         if (!ph)
1254                 return ERR_PTR(-EINVAL);
1255
1256         dres = devres_alloc(scmi_devm_release_protocol,
1257                             sizeof(*dres), GFP_KERNEL);
1258         if (!dres)
1259                 return ERR_PTR(-ENOMEM);
1260
1261         pi = scmi_get_protocol_instance(handle, protocol_id);
1262         if (IS_ERR(pi)) {
1263                 devres_free(dres);
1264                 return pi;
1265         }
1266
1267         dres->handle = handle;
1268         dres->protocol_id = protocol_id;
1269         devres_add(&sdev->dev, dres);
1270
1271         *ph = &pi->ph;
1272
1273         return pi->proto->ops;
1274 }
1275
1276 static int scmi_devm_protocol_match(struct device *dev, void *res, void *data)
1277 {
1278         struct scmi_protocol_devres *dres = res;
1279
1280         if (WARN_ON(!dres || !data))
1281                 return 0;
1282
1283         return dres->protocol_id == *((u8 *)data);
1284 }
1285
1286 /**
1287  * scmi_devm_protocol_put  - Devres managed put protocol operations and handle
1288  * @sdev: A reference to an scmi_device whose embedded struct device is to
1289  *        be used for devres accounting.
1290  * @protocol_id: The protocol being requested.
1291  *
1292  * Explicitly release a protocol hold previously obtained calling the above
1293  * @scmi_devm_protocol_get.
1294  */
1295 static void scmi_devm_protocol_put(struct scmi_device *sdev, u8 protocol_id)
1296 {
1297         int ret;
1298
1299         ret = devres_release(&sdev->dev, scmi_devm_release_protocol,
1300                              scmi_devm_protocol_match, &protocol_id);
1301         WARN_ON(ret);
1302 }
1303
1304 static inline
1305 struct scmi_handle *scmi_handle_get_from_info_unlocked(struct scmi_info *info)
1306 {
1307         info->users++;
1308         return &info->handle;
1309 }
1310
1311 /**
1312  * scmi_handle_get() - Get the SCMI handle for a device
1313  *
1314  * @dev: pointer to device for which we want SCMI handle
1315  *
1316  * NOTE: The function does not track individual clients of the framework
1317  * and is expected to be maintained by caller of SCMI protocol library.
1318  * scmi_handle_put must be balanced with successful scmi_handle_get
1319  *
1320  * Return: pointer to handle if successful, NULL on error
1321  */
1322 struct scmi_handle *scmi_handle_get(struct device *dev)
1323 {
1324         struct list_head *p;
1325         struct scmi_info *info;
1326         struct scmi_handle *handle = NULL;
1327
1328         mutex_lock(&scmi_list_mutex);
1329         list_for_each(p, &scmi_list) {
1330                 info = list_entry(p, struct scmi_info, node);
1331                 if (dev->parent == info->dev) {
1332                         handle = scmi_handle_get_from_info_unlocked(info);
1333                         break;
1334                 }
1335         }
1336         mutex_unlock(&scmi_list_mutex);
1337
1338         return handle;
1339 }
1340
1341 /**
1342  * scmi_handle_put() - Release the handle acquired by scmi_handle_get
1343  *
1344  * @handle: handle acquired by scmi_handle_get
1345  *
1346  * NOTE: The function does not track individual clients of the framework
1347  * and is expected to be maintained by caller of SCMI protocol library.
1348  * scmi_handle_put must be balanced with successful scmi_handle_get
1349  *
1350  * Return: 0 is successfully released
1351  *      if null was passed, it returns -EINVAL;
1352  */
1353 int scmi_handle_put(const struct scmi_handle *handle)
1354 {
1355         struct scmi_info *info;
1356
1357         if (!handle)
1358                 return -EINVAL;
1359
1360         info = handle_to_scmi_info(handle);
1361         mutex_lock(&scmi_list_mutex);
1362         if (!WARN_ON(!info->users))
1363                 info->users--;
1364         mutex_unlock(&scmi_list_mutex);
1365
1366         return 0;
1367 }
1368
1369 static int __scmi_xfer_info_init(struct scmi_info *sinfo,
1370                                  struct scmi_xfers_info *info)
1371 {
1372         int i;
1373         struct scmi_xfer *xfer;
1374         struct device *dev = sinfo->dev;
1375         const struct scmi_desc *desc = sinfo->desc;
1376
1377         /* Pre-allocated messages, no more than what hdr.seq can support */
1378         if (WARN_ON(!info->max_msg || info->max_msg > MSG_TOKEN_MAX)) {
1379                 dev_err(dev,
1380                         "Invalid maximum messages %d, not in range [1 - %lu]\n",
1381                         info->max_msg, MSG_TOKEN_MAX);
1382                 return -EINVAL;
1383         }
1384
1385         hash_init(info->pending_xfers);
1386
1387         /* Allocate a bitmask sized to hold MSG_TOKEN_MAX tokens */
1388         info->xfer_alloc_table = devm_kcalloc(dev, BITS_TO_LONGS(MSG_TOKEN_MAX),
1389                                               sizeof(long), GFP_KERNEL);
1390         if (!info->xfer_alloc_table)
1391                 return -ENOMEM;
1392
1393         /*
1394          * Preallocate a number of xfers equal to max inflight messages,
1395          * pre-initialize the buffer pointer to pre-allocated buffers and
1396          * attach all of them to the free list
1397          */
1398         INIT_HLIST_HEAD(&info->free_xfers);
1399         for (i = 0; i < info->max_msg; i++) {
1400                 xfer = devm_kzalloc(dev, sizeof(*xfer), GFP_KERNEL);
1401                 if (!xfer)
1402                         return -ENOMEM;
1403
1404                 xfer->rx.buf = devm_kcalloc(dev, sizeof(u8), desc->max_msg_size,
1405                                             GFP_KERNEL);
1406                 if (!xfer->rx.buf)
1407                         return -ENOMEM;
1408
1409                 xfer->tx.buf = xfer->rx.buf;
1410                 init_completion(&xfer->done);
1411                 spin_lock_init(&xfer->lock);
1412
1413                 /* Add initialized xfer to the free list */
1414                 hlist_add_head(&xfer->node, &info->free_xfers);
1415         }
1416
1417         spin_lock_init(&info->xfer_lock);
1418
1419         return 0;
1420 }
1421
1422 static int scmi_channels_max_msg_configure(struct scmi_info *sinfo)
1423 {
1424         const struct scmi_desc *desc = sinfo->desc;
1425
1426         if (!desc->ops->get_max_msg) {
1427                 sinfo->tx_minfo.max_msg = desc->max_msg;
1428                 sinfo->rx_minfo.max_msg = desc->max_msg;
1429         } else {
1430                 struct scmi_chan_info *base_cinfo;
1431
1432                 base_cinfo = idr_find(&sinfo->tx_idr, SCMI_PROTOCOL_BASE);
1433                 if (!base_cinfo)
1434                         return -EINVAL;
1435                 sinfo->tx_minfo.max_msg = desc->ops->get_max_msg(base_cinfo);
1436
1437                 /* RX channel is optional so can be skipped */
1438                 base_cinfo = idr_find(&sinfo->rx_idr, SCMI_PROTOCOL_BASE);
1439                 if (base_cinfo)
1440                         sinfo->rx_minfo.max_msg =
1441                                 desc->ops->get_max_msg(base_cinfo);
1442         }
1443
1444         return 0;
1445 }
1446
1447 static int scmi_xfer_info_init(struct scmi_info *sinfo)
1448 {
1449         int ret;
1450
1451         ret = scmi_channels_max_msg_configure(sinfo);
1452         if (ret)
1453                 return ret;
1454
1455         ret = __scmi_xfer_info_init(sinfo, &sinfo->tx_minfo);
1456         if (!ret && idr_find(&sinfo->rx_idr, SCMI_PROTOCOL_BASE))
1457                 ret = __scmi_xfer_info_init(sinfo, &sinfo->rx_minfo);
1458
1459         return ret;
1460 }
1461
1462 static int scmi_chan_setup(struct scmi_info *info, struct device *dev,
1463                            int prot_id, bool tx)
1464 {
1465         int ret, idx;
1466         struct scmi_chan_info *cinfo;
1467         struct idr *idr;
1468
1469         /* Transmit channel is first entry i.e. index 0 */
1470         idx = tx ? 0 : 1;
1471         idr = tx ? &info->tx_idr : &info->rx_idr;
1472
1473         /* check if already allocated, used for multiple device per protocol */
1474         cinfo = idr_find(idr, prot_id);
1475         if (cinfo)
1476                 return 0;
1477
1478         if (!info->desc->ops->chan_available(dev, idx)) {
1479                 cinfo = idr_find(idr, SCMI_PROTOCOL_BASE);
1480                 if (unlikely(!cinfo)) /* Possible only if platform has no Rx */
1481                         return -EINVAL;
1482                 goto idr_alloc;
1483         }
1484
1485         cinfo = devm_kzalloc(info->dev, sizeof(*cinfo), GFP_KERNEL);
1486         if (!cinfo)
1487                 return -ENOMEM;
1488
1489         cinfo->dev = dev;
1490
1491         ret = info->desc->ops->chan_setup(cinfo, info->dev, tx);
1492         if (ret)
1493                 return ret;
1494
1495 idr_alloc:
1496         ret = idr_alloc(idr, cinfo, prot_id, prot_id + 1, GFP_KERNEL);
1497         if (ret != prot_id) {
1498                 dev_err(dev, "unable to allocate SCMI idr slot err %d\n", ret);
1499                 return ret;
1500         }
1501
1502         cinfo->handle = &info->handle;
1503         return 0;
1504 }
1505
1506 static inline int
1507 scmi_txrx_setup(struct scmi_info *info, struct device *dev, int prot_id)
1508 {
1509         int ret = scmi_chan_setup(info, dev, prot_id, true);
1510
1511         if (!ret) /* Rx is optional, hence no error check */
1512                 scmi_chan_setup(info, dev, prot_id, false);
1513
1514         return ret;
1515 }
1516
1517 /**
1518  * scmi_get_protocol_device  - Helper to get/create an SCMI device.
1519  *
1520  * @np: A device node representing a valid active protocols for the referred
1521  * SCMI instance.
1522  * @info: The referred SCMI instance for which we are getting/creating this
1523  * device.
1524  * @prot_id: The protocol ID.
1525  * @name: The device name.
1526  *
1527  * Referring to the specific SCMI instance identified by @info, this helper
1528  * takes care to return a properly initialized device matching the requested
1529  * @proto_id and @name: if device was still not existent it is created as a
1530  * child of the specified SCMI instance @info and its transport properly
1531  * initialized as usual.
1532  *
1533  * Return: A properly initialized scmi device, NULL otherwise.
1534  */
1535 static inline struct scmi_device *
1536 scmi_get_protocol_device(struct device_node *np, struct scmi_info *info,
1537                          int prot_id, const char *name)
1538 {
1539         struct scmi_device *sdev;
1540
1541         /* Already created for this parent SCMI instance ? */
1542         sdev = scmi_child_dev_find(info->dev, prot_id, name);
1543         if (sdev)
1544                 return sdev;
1545
1546         pr_debug("Creating SCMI device (%s) for protocol %x\n", name, prot_id);
1547
1548         sdev = scmi_device_create(np, info->dev, prot_id, name);
1549         if (!sdev) {
1550                 dev_err(info->dev, "failed to create %d protocol device\n",
1551                         prot_id);
1552                 return NULL;
1553         }
1554
1555         if (scmi_txrx_setup(info, &sdev->dev, prot_id)) {
1556                 dev_err(&sdev->dev, "failed to setup transport\n");
1557                 scmi_device_destroy(sdev);
1558                 return NULL;
1559         }
1560
1561         return sdev;
1562 }
1563
1564 static inline void
1565 scmi_create_protocol_device(struct device_node *np, struct scmi_info *info,
1566                             int prot_id, const char *name)
1567 {
1568         struct scmi_device *sdev;
1569
1570         sdev = scmi_get_protocol_device(np, info, prot_id, name);
1571         if (!sdev)
1572                 return;
1573
1574         /* setup handle now as the transport is ready */
1575         scmi_set_handle(sdev);
1576 }
1577
1578 /**
1579  * scmi_create_protocol_devices  - Create devices for all pending requests for
1580  * this SCMI instance.
1581  *
1582  * @np: The device node describing the protocol
1583  * @info: The SCMI instance descriptor
1584  * @prot_id: The protocol ID
1585  *
1586  * All devices previously requested for this instance (if any) are found and
1587  * created by scanning the proper @&scmi_requested_devices entry.
1588  */
1589 static void scmi_create_protocol_devices(struct device_node *np,
1590                                          struct scmi_info *info, int prot_id)
1591 {
1592         struct list_head *phead;
1593
1594         mutex_lock(&scmi_requested_devices_mtx);
1595         phead = idr_find(&scmi_requested_devices, prot_id);
1596         if (phead) {
1597                 struct scmi_requested_dev *rdev;
1598
1599                 list_for_each_entry(rdev, phead, node)
1600                         scmi_create_protocol_device(np, info, prot_id,
1601                                                     rdev->id_table->name);
1602         }
1603         mutex_unlock(&scmi_requested_devices_mtx);
1604 }
1605
1606 /**
1607  * scmi_protocol_device_request  - Helper to request a device
1608  *
1609  * @id_table: A protocol/name pair descriptor for the device to be created.
1610  *
1611  * This helper let an SCMI driver request specific devices identified by the
1612  * @id_table to be created for each active SCMI instance.
1613  *
1614  * The requested device name MUST NOT be already existent for any protocol;
1615  * at first the freshly requested @id_table is annotated in the IDR table
1616  * @scmi_requested_devices, then a matching device is created for each already
1617  * active SCMI instance. (if any)
1618  *
1619  * This way the requested device is created straight-away for all the already
1620  * initialized(probed) SCMI instances (handles) and it remains also annotated
1621  * as pending creation if the requesting SCMI driver was loaded before some
1622  * SCMI instance and related transports were available: when such late instance
1623  * is probed, its probe will take care to scan the list of pending requested
1624  * devices and create those on its own (see @scmi_create_protocol_devices and
1625  * its enclosing loop)
1626  *
1627  * Return: 0 on Success
1628  */
1629 int scmi_protocol_device_request(const struct scmi_device_id *id_table)
1630 {
1631         int ret = 0;
1632         unsigned int id = 0;
1633         struct list_head *head, *phead = NULL;
1634         struct scmi_requested_dev *rdev;
1635         struct scmi_info *info;
1636
1637         pr_debug("Requesting SCMI device (%s) for protocol %x\n",
1638                  id_table->name, id_table->protocol_id);
1639
1640         /*
1641          * Search for the matching protocol rdev list and then search
1642          * of any existent equally named device...fails if any duplicate found.
1643          */
1644         mutex_lock(&scmi_requested_devices_mtx);
1645         idr_for_each_entry(&scmi_requested_devices, head, id) {
1646                 if (!phead) {
1647                         /* A list found registered in the IDR is never empty */
1648                         rdev = list_first_entry(head, struct scmi_requested_dev,
1649                                                 node);
1650                         if (rdev->id_table->protocol_id ==
1651                             id_table->protocol_id)
1652                                 phead = head;
1653                 }
1654                 list_for_each_entry(rdev, head, node) {
1655                         if (!strcmp(rdev->id_table->name, id_table->name)) {
1656                                 pr_err("Ignoring duplicate request [%d] %s\n",
1657                                        rdev->id_table->protocol_id,
1658                                        rdev->id_table->name);
1659                                 ret = -EINVAL;
1660                                 goto out;
1661                         }
1662                 }
1663         }
1664
1665         /*
1666          * No duplicate found for requested id_table, so let's create a new
1667          * requested device entry for this new valid request.
1668          */
1669         rdev = kzalloc(sizeof(*rdev), GFP_KERNEL);
1670         if (!rdev) {
1671                 ret = -ENOMEM;
1672                 goto out;
1673         }
1674         rdev->id_table = id_table;
1675
1676         /*
1677          * Append the new requested device table descriptor to the head of the
1678          * related protocol list, eventually creating such head if not already
1679          * there.
1680          */
1681         if (!phead) {
1682                 phead = kzalloc(sizeof(*phead), GFP_KERNEL);
1683                 if (!phead) {
1684                         kfree(rdev);
1685                         ret = -ENOMEM;
1686                         goto out;
1687                 }
1688                 INIT_LIST_HEAD(phead);
1689
1690                 ret = idr_alloc(&scmi_requested_devices, (void *)phead,
1691                                 id_table->protocol_id,
1692                                 id_table->protocol_id + 1, GFP_KERNEL);
1693                 if (ret != id_table->protocol_id) {
1694                         pr_err("Failed to save SCMI device - ret:%d\n", ret);
1695                         kfree(rdev);
1696                         kfree(phead);
1697                         ret = -EINVAL;
1698                         goto out;
1699                 }
1700                 ret = 0;
1701         }
1702         list_add(&rdev->node, phead);
1703
1704         /*
1705          * Now effectively create and initialize the requested device for every
1706          * already initialized SCMI instance which has registered the requested
1707          * protocol as a valid active one: i.e. defined in DT and supported by
1708          * current platform FW.
1709          */
1710         mutex_lock(&scmi_list_mutex);
1711         list_for_each_entry(info, &scmi_list, node) {
1712                 struct device_node *child;
1713
1714                 child = idr_find(&info->active_protocols,
1715                                  id_table->protocol_id);
1716                 if (child) {
1717                         struct scmi_device *sdev;
1718
1719                         sdev = scmi_get_protocol_device(child, info,
1720                                                         id_table->protocol_id,
1721                                                         id_table->name);
1722                         /* Set handle if not already set: device existed */
1723                         if (sdev && !sdev->handle)
1724                                 sdev->handle =
1725                                         scmi_handle_get_from_info_unlocked(info);
1726                 } else {
1727                         dev_err(info->dev,
1728                                 "Failed. SCMI protocol %d not active.\n",
1729                                 id_table->protocol_id);
1730                 }
1731         }
1732         mutex_unlock(&scmi_list_mutex);
1733
1734 out:
1735         mutex_unlock(&scmi_requested_devices_mtx);
1736
1737         return ret;
1738 }
1739
1740 /**
1741  * scmi_protocol_device_unrequest  - Helper to unrequest a device
1742  *
1743  * @id_table: A protocol/name pair descriptor for the device to be unrequested.
1744  *
1745  * An helper to let an SCMI driver release its request about devices; note that
1746  * devices are created and initialized once the first SCMI driver request them
1747  * but they destroyed only on SCMI core unloading/unbinding.
1748  *
1749  * The current SCMI transport layer uses such devices as internal references and
1750  * as such they could be shared as same transport between multiple drivers so
1751  * that cannot be safely destroyed till the whole SCMI stack is removed.
1752  * (unless adding further burden of refcounting.)
1753  */
1754 void scmi_protocol_device_unrequest(const struct scmi_device_id *id_table)
1755 {
1756         struct list_head *phead;
1757
1758         pr_debug("Unrequesting SCMI device (%s) for protocol %x\n",
1759                  id_table->name, id_table->protocol_id);
1760
1761         mutex_lock(&scmi_requested_devices_mtx);
1762         phead = idr_find(&scmi_requested_devices, id_table->protocol_id);
1763         if (phead) {
1764                 struct scmi_requested_dev *victim, *tmp;
1765
1766                 list_for_each_entry_safe(victim, tmp, phead, node) {
1767                         if (!strcmp(victim->id_table->name, id_table->name)) {
1768                                 list_del(&victim->node);
1769                                 kfree(victim);
1770                                 break;
1771                         }
1772                 }
1773
1774                 if (list_empty(phead)) {
1775                         idr_remove(&scmi_requested_devices,
1776                                    id_table->protocol_id);
1777                         kfree(phead);
1778                 }
1779         }
1780         mutex_unlock(&scmi_requested_devices_mtx);
1781 }
1782
1783 static int scmi_probe(struct platform_device *pdev)
1784 {
1785         int ret;
1786         struct scmi_handle *handle;
1787         const struct scmi_desc *desc;
1788         struct scmi_info *info;
1789         struct device *dev = &pdev->dev;
1790         struct device_node *child, *np = dev->of_node;
1791
1792         desc = of_device_get_match_data(dev);
1793         if (!desc)
1794                 return -EINVAL;
1795
1796         info = devm_kzalloc(dev, sizeof(*info), GFP_KERNEL);
1797         if (!info)
1798                 return -ENOMEM;
1799
1800         info->dev = dev;
1801         info->desc = desc;
1802         INIT_LIST_HEAD(&info->node);
1803         idr_init(&info->protocols);
1804         mutex_init(&info->protocols_mtx);
1805         idr_init(&info->active_protocols);
1806
1807         platform_set_drvdata(pdev, info);
1808         idr_init(&info->tx_idr);
1809         idr_init(&info->rx_idr);
1810
1811         handle = &info->handle;
1812         handle->dev = info->dev;
1813         handle->version = &info->version;
1814         handle->devm_protocol_get = scmi_devm_protocol_get;
1815         handle->devm_protocol_put = scmi_devm_protocol_put;
1816
1817         if (desc->ops->link_supplier) {
1818                 ret = desc->ops->link_supplier(dev);
1819                 if (ret)
1820                         return ret;
1821         }
1822
1823         ret = scmi_txrx_setup(info, dev, SCMI_PROTOCOL_BASE);
1824         if (ret)
1825                 return ret;
1826
1827         ret = scmi_xfer_info_init(info);
1828         if (ret)
1829                 return ret;
1830
1831         if (scmi_notification_init(handle))
1832                 dev_err(dev, "SCMI Notifications NOT available.\n");
1833
1834         /*
1835          * Trigger SCMI Base protocol initialization.
1836          * It's mandatory and won't be ever released/deinit until the
1837          * SCMI stack is shutdown/unloaded as a whole.
1838          */
1839         ret = scmi_protocol_acquire(handle, SCMI_PROTOCOL_BASE);
1840         if (ret) {
1841                 dev_err(dev, "unable to communicate with SCMI\n");
1842                 return ret;
1843         }
1844
1845         mutex_lock(&scmi_list_mutex);
1846         list_add_tail(&info->node, &scmi_list);
1847         mutex_unlock(&scmi_list_mutex);
1848
1849         for_each_available_child_of_node(np, child) {
1850                 u32 prot_id;
1851
1852                 if (of_property_read_u32(child, "reg", &prot_id))
1853                         continue;
1854
1855                 if (!FIELD_FIT(MSG_PROTOCOL_ID_MASK, prot_id))
1856                         dev_err(dev, "Out of range protocol %d\n", prot_id);
1857
1858                 if (!scmi_is_protocol_implemented(handle, prot_id)) {
1859                         dev_err(dev, "SCMI protocol %d not implemented\n",
1860                                 prot_id);
1861                         continue;
1862                 }
1863
1864                 /*
1865                  * Save this valid DT protocol descriptor amongst
1866                  * @active_protocols for this SCMI instance/
1867                  */
1868                 ret = idr_alloc(&info->active_protocols, child,
1869                                 prot_id, prot_id + 1, GFP_KERNEL);
1870                 if (ret != prot_id) {
1871                         dev_err(dev, "SCMI protocol %d already activated. Skip\n",
1872                                 prot_id);
1873                         continue;
1874                 }
1875
1876                 of_node_get(child);
1877                 scmi_create_protocol_devices(child, info, prot_id);
1878         }
1879
1880         return 0;
1881 }
1882
1883 void scmi_free_channel(struct scmi_chan_info *cinfo, struct idr *idr, int id)
1884 {
1885         idr_remove(idr, id);
1886 }
1887
1888 static int scmi_remove(struct platform_device *pdev)
1889 {
1890         int ret = 0, id;
1891         struct scmi_info *info = platform_get_drvdata(pdev);
1892         struct idr *idr = &info->tx_idr;
1893         struct device_node *child;
1894
1895         mutex_lock(&scmi_list_mutex);
1896         if (info->users)
1897                 ret = -EBUSY;
1898         else
1899                 list_del(&info->node);
1900         mutex_unlock(&scmi_list_mutex);
1901
1902         if (ret)
1903                 return ret;
1904
1905         scmi_notification_exit(&info->handle);
1906
1907         mutex_lock(&info->protocols_mtx);
1908         idr_destroy(&info->protocols);
1909         mutex_unlock(&info->protocols_mtx);
1910
1911         idr_for_each_entry(&info->active_protocols, child, id)
1912                 of_node_put(child);
1913         idr_destroy(&info->active_protocols);
1914
1915         /* Safe to free channels since no more users */
1916         ret = idr_for_each(idr, info->desc->ops->chan_free, idr);
1917         idr_destroy(&info->tx_idr);
1918
1919         idr = &info->rx_idr;
1920         ret = idr_for_each(idr, info->desc->ops->chan_free, idr);
1921         idr_destroy(&info->rx_idr);
1922
1923         return ret;
1924 }
1925
1926 static ssize_t protocol_version_show(struct device *dev,
1927                                      struct device_attribute *attr, char *buf)
1928 {
1929         struct scmi_info *info = dev_get_drvdata(dev);
1930
1931         return sprintf(buf, "%u.%u\n", info->version.major_ver,
1932                        info->version.minor_ver);
1933 }
1934 static DEVICE_ATTR_RO(protocol_version);
1935
1936 static ssize_t firmware_version_show(struct device *dev,
1937                                      struct device_attribute *attr, char *buf)
1938 {
1939         struct scmi_info *info = dev_get_drvdata(dev);
1940
1941         return sprintf(buf, "0x%x\n", info->version.impl_ver);
1942 }
1943 static DEVICE_ATTR_RO(firmware_version);
1944
1945 static ssize_t vendor_id_show(struct device *dev,
1946                               struct device_attribute *attr, char *buf)
1947 {
1948         struct scmi_info *info = dev_get_drvdata(dev);
1949
1950         return sprintf(buf, "%s\n", info->version.vendor_id);
1951 }
1952 static DEVICE_ATTR_RO(vendor_id);
1953
1954 static ssize_t sub_vendor_id_show(struct device *dev,
1955                                   struct device_attribute *attr, char *buf)
1956 {
1957         struct scmi_info *info = dev_get_drvdata(dev);
1958
1959         return sprintf(buf, "%s\n", info->version.sub_vendor_id);
1960 }
1961 static DEVICE_ATTR_RO(sub_vendor_id);
1962
1963 static struct attribute *versions_attrs[] = {
1964         &dev_attr_firmware_version.attr,
1965         &dev_attr_protocol_version.attr,
1966         &dev_attr_vendor_id.attr,
1967         &dev_attr_sub_vendor_id.attr,
1968         NULL,
1969 };
1970 ATTRIBUTE_GROUPS(versions);
1971
1972 /* Each compatible listed below must have descriptor associated with it */
1973 static const struct of_device_id scmi_of_match[] = {
1974 #ifdef CONFIG_ARM_SCMI_TRANSPORT_MAILBOX
1975         { .compatible = "arm,scmi", .data = &scmi_mailbox_desc },
1976 #endif
1977 #ifdef CONFIG_ARM_SCMI_TRANSPORT_SMC
1978         { .compatible = "arm,scmi-smc", .data = &scmi_smc_desc},
1979 #endif
1980         { /* Sentinel */ },
1981 };
1982
1983 MODULE_DEVICE_TABLE(of, scmi_of_match);
1984
1985 static struct platform_driver scmi_driver = {
1986         .driver = {
1987                    .name = "arm-scmi",
1988                    .of_match_table = scmi_of_match,
1989                    .dev_groups = versions_groups,
1990                    },
1991         .probe = scmi_probe,
1992         .remove = scmi_remove,
1993 };
1994
1995 /**
1996  * __scmi_transports_setup  - Common helper to call transport-specific
1997  * .init/.exit code if provided.
1998  *
1999  * @init: A flag to distinguish between init and exit.
2000  *
2001  * Note that, if provided, we invoke .init/.exit functions for all the
2002  * transports currently compiled in.
2003  *
2004  * Return: 0 on Success.
2005  */
2006 static inline int __scmi_transports_setup(bool init)
2007 {
2008         int ret = 0;
2009         const struct of_device_id *trans;
2010
2011         for (trans = scmi_of_match; trans->data; trans++) {
2012                 const struct scmi_desc *tdesc = trans->data;
2013
2014                 if ((init && !tdesc->transport_init) ||
2015                     (!init && !tdesc->transport_exit))
2016                         continue;
2017
2018                 if (init)
2019                         ret = tdesc->transport_init();
2020                 else
2021                         tdesc->transport_exit();
2022
2023                 if (ret) {
2024                         pr_err("SCMI transport %s FAILED initialization!\n",
2025                                trans->compatible);
2026                         break;
2027                 }
2028         }
2029
2030         return ret;
2031 }
2032
2033 static int __init scmi_transports_init(void)
2034 {
2035         return __scmi_transports_setup(true);
2036 }
2037
2038 static void __exit scmi_transports_exit(void)
2039 {
2040         __scmi_transports_setup(false);
2041 }
2042
2043 static int __init scmi_driver_init(void)
2044 {
2045         int ret;
2046
2047         scmi_bus_init();
2048
2049         BUILD_BUG_ON(!IS_ENABLED(CONFIG_ARM_SCMI_HAVE_TRANSPORT));
2050
2051         /* Initialize any compiled-in transport which provided an init/exit */
2052         ret = scmi_transports_init();
2053         if (ret)
2054                 return ret;
2055
2056         scmi_base_register();
2057
2058         scmi_clock_register();
2059         scmi_perf_register();
2060         scmi_power_register();
2061         scmi_reset_register();
2062         scmi_sensors_register();
2063         scmi_voltage_register();
2064         scmi_system_register();
2065
2066         return platform_driver_register(&scmi_driver);
2067 }
2068 subsys_initcall(scmi_driver_init);
2069
2070 static void __exit scmi_driver_exit(void)
2071 {
2072         scmi_base_unregister();
2073
2074         scmi_clock_unregister();
2075         scmi_perf_unregister();
2076         scmi_power_unregister();
2077         scmi_reset_unregister();
2078         scmi_sensors_unregister();
2079         scmi_voltage_unregister();
2080         scmi_system_unregister();
2081
2082         scmi_bus_exit();
2083
2084         scmi_transports_exit();
2085
2086         platform_driver_unregister(&scmi_driver);
2087 }
2088 module_exit(scmi_driver_exit);
2089
2090 MODULE_ALIAS("platform: arm-scmi");
2091 MODULE_AUTHOR("Sudeep Holla <sudeep.holla@arm.com>");
2092 MODULE_DESCRIPTION("ARM SCMI protocol driver");
2093 MODULE_LICENSE("GPL v2");