GNU Linux-libre 4.19.286-gnu1
[releases.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 ARM Ltd.
15  */
16
17 #include <linux/bitmap.h>
18 #include <linux/export.h>
19 #include <linux/io.h>
20 #include <linux/kernel.h>
21 #include <linux/ktime.h>
22 #include <linux/mailbox_client.h>
23 #include <linux/module.h>
24 #include <linux/of_address.h>
25 #include <linux/of_device.h>
26 #include <linux/processor.h>
27 #include <linux/semaphore.h>
28 #include <linux/slab.h>
29
30 #include "common.h"
31
32 #define MSG_ID_MASK             GENMASK(7, 0)
33 #define MSG_TYPE_MASK           GENMASK(9, 8)
34 #define MSG_PROTOCOL_ID_MASK    GENMASK(17, 10)
35 #define MSG_TOKEN_ID_MASK       GENMASK(27, 18)
36 #define MSG_XTRACT_TOKEN(hdr)   FIELD_GET(MSG_TOKEN_ID_MASK, (hdr))
37 #define MSG_TOKEN_MAX           (MSG_XTRACT_TOKEN(MSG_TOKEN_ID_MASK) + 1)
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
58 /**
59  * struct scmi_xfers_info - Structure to manage transfer information
60  *
61  * @xfer_block: Preallocated Message array
62  * @xfer_alloc_table: Bitmap table for allocated messages.
63  *      Index of this bitmap table is also used for message
64  *      sequence identifier.
65  * @xfer_lock: Protection for message allocation
66  */
67 struct scmi_xfers_info {
68         struct scmi_xfer *xfer_block;
69         unsigned long *xfer_alloc_table;
70         spinlock_t xfer_lock;
71 };
72
73 /**
74  * struct scmi_desc - Description of SoC integration
75  *
76  * @max_rx_timeout_ms: Timeout for communication with SoC (in Milliseconds)
77  * @max_msg: Maximum number of messages that can be pending
78  *      simultaneously in the system
79  * @max_msg_size: Maximum size of data per message that can be handled.
80  */
81 struct scmi_desc {
82         int max_rx_timeout_ms;
83         int max_msg;
84         int max_msg_size;
85 };
86
87 /**
88  * struct scmi_chan_info - Structure representing a SCMI channel informfation
89  *
90  * @cl: Mailbox Client
91  * @chan: Transmit/Receive mailbox channel
92  * @payload: Transmit/Receive mailbox channel payload area
93  * @dev: Reference to device in the SCMI hierarchy corresponding to this
94  *       channel
95  * @handle: Pointer to SCMI entity handle
96  */
97 struct scmi_chan_info {
98         struct mbox_client cl;
99         struct mbox_chan *chan;
100         void __iomem *payload;
101         struct device *dev;
102         struct scmi_handle *handle;
103 };
104
105 /**
106  * struct scmi_info - Structure representing a SCMI instance
107  *
108  * @dev: Device pointer
109  * @desc: SoC description for this instance
110  * @handle: Instance of SCMI handle to send to clients
111  * @version: SCMI revision information containing protocol version,
112  *      implementation version and (sub-)vendor identification.
113  * @minfo: Message info
114  * @tx_idr: IDR object to map protocol id to channel info pointer
115  * @protocols_imp: List of protocols implemented, currently maximum of
116  *      MAX_PROTOCOLS_IMP elements allocated by the base protocol
117  * @node: List head
118  * @users: Number of users of this instance
119  */
120 struct scmi_info {
121         struct device *dev;
122         const struct scmi_desc *desc;
123         struct scmi_revision_info version;
124         struct scmi_handle handle;
125         struct scmi_xfers_info minfo;
126         struct idr tx_idr;
127         u8 *protocols_imp;
128         struct list_head node;
129         int users;
130 };
131
132 #define client_to_scmi_chan_info(c) container_of(c, struct scmi_chan_info, cl)
133 #define handle_to_scmi_info(h)  container_of(h, struct scmi_info, handle)
134
135 /*
136  * SCMI specification requires all parameters, message headers, return
137  * arguments or any protocol data to be expressed in little endian
138  * format only.
139  */
140 struct scmi_shared_mem {
141         __le32 reserved;
142         __le32 channel_status;
143 #define SCMI_SHMEM_CHAN_STAT_CHANNEL_ERROR      BIT(1)
144 #define SCMI_SHMEM_CHAN_STAT_CHANNEL_FREE       BIT(0)
145         __le32 reserved1[2];
146         __le32 flags;
147 #define SCMI_SHMEM_FLAG_INTR_ENABLED    BIT(0)
148         __le32 length;
149         __le32 msg_header;
150         u8 msg_payload[0];
151 };
152
153 static const int scmi_linux_errmap[] = {
154         /* better than switch case as long as return value is continuous */
155         0,                      /* SCMI_SUCCESS */
156         -EOPNOTSUPP,            /* SCMI_ERR_SUPPORT */
157         -EINVAL,                /* SCMI_ERR_PARAM */
158         -EACCES,                /* SCMI_ERR_ACCESS */
159         -ENOENT,                /* SCMI_ERR_ENTRY */
160         -ERANGE,                /* SCMI_ERR_RANGE */
161         -EBUSY,                 /* SCMI_ERR_BUSY */
162         -ECOMM,                 /* SCMI_ERR_COMMS */
163         -EIO,                   /* SCMI_ERR_GENERIC */
164         -EREMOTEIO,             /* SCMI_ERR_HARDWARE */
165         -EPROTO,                /* SCMI_ERR_PROTOCOL */
166 };
167
168 static inline int scmi_to_linux_errno(int errno)
169 {
170         int err_idx = -errno;
171
172         if (err_idx >= SCMI_SUCCESS && err_idx < ARRAY_SIZE(scmi_linux_errmap))
173                 return scmi_linux_errmap[err_idx];
174         return -EIO;
175 }
176
177 /**
178  * scmi_dump_header_dbg() - Helper to dump a message header.
179  *
180  * @dev: Device pointer corresponding to the SCMI entity
181  * @hdr: pointer to header.
182  */
183 static inline void scmi_dump_header_dbg(struct device *dev,
184                                         struct scmi_msg_hdr *hdr)
185 {
186         dev_dbg(dev, "Command ID: %x Sequence ID: %x Protocol: %x\n",
187                 hdr->id, hdr->seq, hdr->protocol_id);
188 }
189
190 static void scmi_fetch_response(struct scmi_xfer *xfer,
191                                 struct scmi_shared_mem __iomem *mem)
192 {
193         xfer->hdr.status = ioread32(mem->msg_payload);
194         /* Skip the length of header and statues in payload area i.e 8 bytes*/
195         xfer->rx.len = min_t(size_t, xfer->rx.len, ioread32(&mem->length) - 8);
196
197         /* Take a copy to the rx buffer.. */
198         memcpy_fromio(xfer->rx.buf, mem->msg_payload + 4, xfer->rx.len);
199 }
200
201 /**
202  * scmi_rx_callback() - mailbox client callback for receive messages
203  *
204  * @cl: client pointer
205  * @m: mailbox message
206  *
207  * Processes one received message to appropriate transfer information and
208  * signals completion of the transfer.
209  *
210  * NOTE: This function will be invoked in IRQ context, hence should be
211  * as optimal as possible.
212  */
213 static void scmi_rx_callback(struct mbox_client *cl, void *m)
214 {
215         u16 xfer_id;
216         struct scmi_xfer *xfer;
217         struct scmi_chan_info *cinfo = client_to_scmi_chan_info(cl);
218         struct device *dev = cinfo->dev;
219         struct scmi_info *info = handle_to_scmi_info(cinfo->handle);
220         struct scmi_xfers_info *minfo = &info->minfo;
221         struct scmi_shared_mem __iomem *mem = cinfo->payload;
222
223         xfer_id = MSG_XTRACT_TOKEN(ioread32(&mem->msg_header));
224
225         /* Are we even expecting this? */
226         if (!test_bit(xfer_id, minfo->xfer_alloc_table)) {
227                 dev_err(dev, "message for %d is not expected!\n", xfer_id);
228                 return;
229         }
230
231         xfer = &minfo->xfer_block[xfer_id];
232
233         scmi_dump_header_dbg(dev, &xfer->hdr);
234         /* Is the message of valid length? */
235         if (xfer->rx.len > info->desc->max_msg_size) {
236                 dev_err(dev, "unable to handle %zu xfer(max %d)\n",
237                         xfer->rx.len, info->desc->max_msg_size);
238                 return;
239         }
240
241         scmi_fetch_response(xfer, mem);
242         complete(&xfer->done);
243 }
244
245 /**
246  * pack_scmi_header() - packs and returns 32-bit header
247  *
248  * @hdr: pointer to header containing all the information on message id,
249  *      protocol id and sequence id.
250  *
251  * Return: 32-bit packed command header to be sent to the platform.
252  */
253 static inline u32 pack_scmi_header(struct scmi_msg_hdr *hdr)
254 {
255         return FIELD_PREP(MSG_ID_MASK, hdr->id) |
256                 FIELD_PREP(MSG_TOKEN_ID_MASK, hdr->seq) |
257                 FIELD_PREP(MSG_PROTOCOL_ID_MASK, hdr->protocol_id);
258 }
259
260 /**
261  * scmi_tx_prepare() - mailbox client callback to prepare for the transfer
262  *
263  * @cl: client pointer
264  * @m: mailbox message
265  *
266  * This function prepares the shared memory which contains the header and the
267  * payload.
268  */
269 static void scmi_tx_prepare(struct mbox_client *cl, void *m)
270 {
271         struct scmi_xfer *t = m;
272         struct scmi_chan_info *cinfo = client_to_scmi_chan_info(cl);
273         struct scmi_shared_mem __iomem *mem = cinfo->payload;
274
275         /*
276          * Ideally channel must be free by now unless OS timeout last
277          * request and platform continued to process the same, wait
278          * until it releases the shared memory, otherwise we may endup
279          * overwriting its response with new message payload or vice-versa
280          */
281         spin_until_cond(ioread32(&mem->channel_status) &
282                         SCMI_SHMEM_CHAN_STAT_CHANNEL_FREE);
283         /* Mark channel busy + clear error */
284         iowrite32(0x0, &mem->channel_status);
285         iowrite32(t->hdr.poll_completion ? 0 : SCMI_SHMEM_FLAG_INTR_ENABLED,
286                   &mem->flags);
287         iowrite32(sizeof(mem->msg_header) + t->tx.len, &mem->length);
288         iowrite32(pack_scmi_header(&t->hdr), &mem->msg_header);
289         if (t->tx.buf)
290                 memcpy_toio(mem->msg_payload, t->tx.buf, t->tx.len);
291 }
292
293 /**
294  * scmi_xfer_get() - Allocate one message
295  *
296  * @handle: Pointer to SCMI entity handle
297  *
298  * Helper function which is used by various command functions that are
299  * exposed to clients of this driver for allocating a message traffic event.
300  *
301  * This function can sleep depending on pending requests already in the system
302  * for the SCMI entity. Further, this also holds a spinlock to maintain
303  * integrity of internal data structures.
304  *
305  * Return: 0 if all went fine, else corresponding error.
306  */
307 static struct scmi_xfer *scmi_xfer_get(const struct scmi_handle *handle)
308 {
309         u16 xfer_id;
310         struct scmi_xfer *xfer;
311         unsigned long flags, bit_pos;
312         struct scmi_info *info = handle_to_scmi_info(handle);
313         struct scmi_xfers_info *minfo = &info->minfo;
314
315         /* Keep the locked section as small as possible */
316         spin_lock_irqsave(&minfo->xfer_lock, flags);
317         bit_pos = find_first_zero_bit(minfo->xfer_alloc_table,
318                                       info->desc->max_msg);
319         if (bit_pos == info->desc->max_msg) {
320                 spin_unlock_irqrestore(&minfo->xfer_lock, flags);
321                 return ERR_PTR(-ENOMEM);
322         }
323         set_bit(bit_pos, minfo->xfer_alloc_table);
324         spin_unlock_irqrestore(&minfo->xfer_lock, flags);
325
326         xfer_id = bit_pos;
327
328         xfer = &minfo->xfer_block[xfer_id];
329         xfer->hdr.seq = xfer_id;
330         reinit_completion(&xfer->done);
331
332         return xfer;
333 }
334
335 /**
336  * scmi_xfer_put() - Release a message
337  *
338  * @handle: Pointer to SCMI entity handle
339  * @xfer: message that was reserved by scmi_xfer_get
340  *
341  * This holds a spinlock to maintain integrity of internal data structures.
342  */
343 void scmi_xfer_put(const struct scmi_handle *handle, struct scmi_xfer *xfer)
344 {
345         unsigned long flags;
346         struct scmi_info *info = handle_to_scmi_info(handle);
347         struct scmi_xfers_info *minfo = &info->minfo;
348
349         /*
350          * Keep the locked section as small as possible
351          * NOTE: we might escape with smp_mb and no lock here..
352          * but just be conservative and symmetric.
353          */
354         spin_lock_irqsave(&minfo->xfer_lock, flags);
355         clear_bit(xfer->hdr.seq, minfo->xfer_alloc_table);
356         spin_unlock_irqrestore(&minfo->xfer_lock, flags);
357 }
358
359 static bool
360 scmi_xfer_poll_done(const struct scmi_chan_info *cinfo, struct scmi_xfer *xfer)
361 {
362         struct scmi_shared_mem __iomem *mem = cinfo->payload;
363         u16 xfer_id = MSG_XTRACT_TOKEN(ioread32(&mem->msg_header));
364
365         if (xfer->hdr.seq != xfer_id)
366                 return false;
367
368         return ioread32(&mem->channel_status) &
369                 (SCMI_SHMEM_CHAN_STAT_CHANNEL_ERROR |
370                 SCMI_SHMEM_CHAN_STAT_CHANNEL_FREE);
371 }
372
373 #define SCMI_MAX_POLL_TO_NS     (100 * NSEC_PER_USEC)
374
375 static bool scmi_xfer_done_no_timeout(const struct scmi_chan_info *cinfo,
376                                       struct scmi_xfer *xfer, ktime_t stop)
377 {
378         ktime_t __cur = ktime_get();
379
380         return scmi_xfer_poll_done(cinfo, xfer) || ktime_after(__cur, stop);
381 }
382
383 /**
384  * scmi_do_xfer() - Do one transfer
385  *
386  * @handle: Pointer to SCMI entity handle
387  * @xfer: Transfer to initiate and wait for response
388  *
389  * Return: -ETIMEDOUT in case of no response, if transmit error,
390  *      return corresponding error, else if all goes well,
391  *      return 0.
392  */
393 int scmi_do_xfer(const struct scmi_handle *handle, struct scmi_xfer *xfer)
394 {
395         int ret;
396         int timeout;
397         struct scmi_info *info = handle_to_scmi_info(handle);
398         struct device *dev = info->dev;
399         struct scmi_chan_info *cinfo;
400
401         cinfo = idr_find(&info->tx_idr, xfer->hdr.protocol_id);
402         if (unlikely(!cinfo))
403                 return -EINVAL;
404
405         ret = mbox_send_message(cinfo->chan, xfer);
406         if (ret < 0) {
407                 dev_dbg(dev, "mbox send fail %d\n", ret);
408                 return ret;
409         }
410
411         /* mbox_send_message returns non-negative value on success, so reset */
412         ret = 0;
413
414         if (xfer->hdr.poll_completion) {
415                 ktime_t stop = ktime_add_ns(ktime_get(), SCMI_MAX_POLL_TO_NS);
416
417                 spin_until_cond(scmi_xfer_done_no_timeout(cinfo, xfer, stop));
418
419                 if (ktime_before(ktime_get(), stop))
420                         scmi_fetch_response(xfer, cinfo->payload);
421                 else
422                         ret = -ETIMEDOUT;
423         } else {
424                 /* And we wait for the response. */
425                 timeout = msecs_to_jiffies(info->desc->max_rx_timeout_ms);
426                 if (!wait_for_completion_timeout(&xfer->done, timeout)) {
427                         dev_err(dev, "mbox timed out in resp(caller: %pS)\n",
428                                 (void *)_RET_IP_);
429                         ret = -ETIMEDOUT;
430                 }
431         }
432
433         if (!ret && xfer->hdr.status)
434                 ret = scmi_to_linux_errno(xfer->hdr.status);
435
436         /*
437          * NOTE: we might prefer not to need the mailbox ticker to manage the
438          * transfer queueing since the protocol layer queues things by itself.
439          * Unfortunately, we have to kick the mailbox framework after we have
440          * received our message.
441          */
442         mbox_client_txdone(cinfo->chan, ret);
443
444         return ret;
445 }
446
447 /**
448  * scmi_xfer_get_init() - Allocate and initialise one message
449  *
450  * @handle: Pointer to SCMI entity handle
451  * @msg_id: Message identifier
452  * @prot_id: Protocol identifier for the message
453  * @tx_size: transmit message size
454  * @rx_size: receive message size
455  * @p: pointer to the allocated and initialised message
456  *
457  * This function allocates the message using @scmi_xfer_get and
458  * initialise the header.
459  *
460  * Return: 0 if all went fine with @p pointing to message, else
461  *      corresponding error.
462  */
463 int scmi_xfer_get_init(const struct scmi_handle *handle, u8 msg_id, u8 prot_id,
464                        size_t tx_size, size_t rx_size, struct scmi_xfer **p)
465 {
466         int ret;
467         struct scmi_xfer *xfer;
468         struct scmi_info *info = handle_to_scmi_info(handle);
469         struct device *dev = info->dev;
470
471         /* Ensure we have sane transfer sizes */
472         if (rx_size > info->desc->max_msg_size ||
473             tx_size > info->desc->max_msg_size)
474                 return -ERANGE;
475
476         xfer = scmi_xfer_get(handle);
477         if (IS_ERR(xfer)) {
478                 ret = PTR_ERR(xfer);
479                 dev_err(dev, "failed to get free message slot(%d)\n", ret);
480                 return ret;
481         }
482
483         xfer->tx.len = tx_size;
484         xfer->rx.len = rx_size ? : info->desc->max_msg_size;
485         xfer->hdr.id = msg_id;
486         xfer->hdr.protocol_id = prot_id;
487         xfer->hdr.poll_completion = false;
488
489         *p = xfer;
490
491         return 0;
492 }
493
494 /**
495  * scmi_version_get() - command to get the revision of the SCMI entity
496  *
497  * @handle: Pointer to SCMI entity handle
498  * @protocol: Protocol identifier for the message
499  * @version: Holds returned version of protocol.
500  *
501  * Updates the SCMI information in the internal data structure.
502  *
503  * Return: 0 if all went fine, else return appropriate error.
504  */
505 int scmi_version_get(const struct scmi_handle *handle, u8 protocol,
506                      u32 *version)
507 {
508         int ret;
509         __le32 *rev_info;
510         struct scmi_xfer *t;
511
512         ret = scmi_xfer_get_init(handle, PROTOCOL_VERSION, protocol, 0,
513                                  sizeof(*version), &t);
514         if (ret)
515                 return ret;
516
517         ret = scmi_do_xfer(handle, t);
518         if (!ret) {
519                 rev_info = t->rx.buf;
520                 *version = le32_to_cpu(*rev_info);
521         }
522
523         scmi_xfer_put(handle, t);
524         return ret;
525 }
526
527 void scmi_setup_protocol_implemented(const struct scmi_handle *handle,
528                                      u8 *prot_imp)
529 {
530         struct scmi_info *info = handle_to_scmi_info(handle);
531
532         info->protocols_imp = prot_imp;
533 }
534
535 static bool
536 scmi_is_protocol_implemented(const struct scmi_handle *handle, u8 prot_id)
537 {
538         int i;
539         struct scmi_info *info = handle_to_scmi_info(handle);
540
541         if (!info->protocols_imp)
542                 return false;
543
544         for (i = 0; i < MAX_PROTOCOLS_IMP; i++)
545                 if (info->protocols_imp[i] == prot_id)
546                         return true;
547         return false;
548 }
549
550 /**
551  * scmi_handle_get() - Get the SCMI handle for a device
552  *
553  * @dev: pointer to device for which we want SCMI handle
554  *
555  * NOTE: The function does not track individual clients of the framework
556  * and is expected to be maintained by caller of SCMI protocol library.
557  * scmi_handle_put must be balanced with successful scmi_handle_get
558  *
559  * Return: pointer to handle if successful, NULL on error
560  */
561 struct scmi_handle *scmi_handle_get(struct device *dev)
562 {
563         struct list_head *p;
564         struct scmi_info *info;
565         struct scmi_handle *handle = NULL;
566
567         mutex_lock(&scmi_list_mutex);
568         list_for_each(p, &scmi_list) {
569                 info = list_entry(p, struct scmi_info, node);
570                 if (dev->parent == info->dev) {
571                         handle = &info->handle;
572                         info->users++;
573                         break;
574                 }
575         }
576         mutex_unlock(&scmi_list_mutex);
577
578         return handle;
579 }
580
581 /**
582  * scmi_handle_put() - Release the handle acquired by scmi_handle_get
583  *
584  * @handle: handle acquired by scmi_handle_get
585  *
586  * NOTE: The function does not track individual clients of the framework
587  * and is expected to be maintained by caller of SCMI protocol library.
588  * scmi_handle_put must be balanced with successful scmi_handle_get
589  *
590  * Return: 0 is successfully released
591  *      if null was passed, it returns -EINVAL;
592  */
593 int scmi_handle_put(const struct scmi_handle *handle)
594 {
595         struct scmi_info *info;
596
597         if (!handle)
598                 return -EINVAL;
599
600         info = handle_to_scmi_info(handle);
601         mutex_lock(&scmi_list_mutex);
602         if (!WARN_ON(!info->users))
603                 info->users--;
604         mutex_unlock(&scmi_list_mutex);
605
606         return 0;
607 }
608
609 static const struct scmi_desc scmi_generic_desc = {
610         .max_rx_timeout_ms = 30,        /* We may increase this if required */
611         .max_msg = 20,          /* Limited by MBOX_TX_QUEUE_LEN */
612         .max_msg_size = 128,
613 };
614
615 /* Each compatible listed below must have descriptor associated with it */
616 static const struct of_device_id scmi_of_match[] = {
617         { .compatible = "arm,scmi", .data = &scmi_generic_desc },
618         { /* Sentinel */ },
619 };
620
621 MODULE_DEVICE_TABLE(of, scmi_of_match);
622
623 static int scmi_xfer_info_init(struct scmi_info *sinfo)
624 {
625         int i;
626         struct scmi_xfer *xfer;
627         struct device *dev = sinfo->dev;
628         const struct scmi_desc *desc = sinfo->desc;
629         struct scmi_xfers_info *info = &sinfo->minfo;
630
631         /* Pre-allocated messages, no more than what hdr.seq can support */
632         if (WARN_ON(!desc->max_msg || desc->max_msg > MSG_TOKEN_MAX)) {
633                 dev_err(dev,
634                         "Invalid maximum messages %d, not in range [1 - %lu]\n",
635                         desc->max_msg, MSG_TOKEN_MAX);
636                 return -EINVAL;
637         }
638
639         info->xfer_block = devm_kcalloc(dev, desc->max_msg,
640                                         sizeof(*info->xfer_block), GFP_KERNEL);
641         if (!info->xfer_block)
642                 return -ENOMEM;
643
644         info->xfer_alloc_table = devm_kcalloc(dev, BITS_TO_LONGS(desc->max_msg),
645                                               sizeof(long), GFP_KERNEL);
646         if (!info->xfer_alloc_table)
647                 return -ENOMEM;
648
649         /* Pre-initialize the buffer pointer to pre-allocated buffers */
650         for (i = 0, xfer = info->xfer_block; i < desc->max_msg; i++, xfer++) {
651                 xfer->rx.buf = devm_kcalloc(dev, sizeof(u8), desc->max_msg_size,
652                                             GFP_KERNEL);
653                 if (!xfer->rx.buf)
654                         return -ENOMEM;
655
656                 xfer->tx.buf = xfer->rx.buf;
657                 init_completion(&xfer->done);
658         }
659
660         spin_lock_init(&info->xfer_lock);
661
662         return 0;
663 }
664
665 static int scmi_mailbox_check(struct device_node *np)
666 {
667         return of_parse_phandle_with_args(np, "mboxes", "#mbox-cells", 0, NULL);
668 }
669
670 static int scmi_mbox_free_channel(int id, void *p, void *data)
671 {
672         struct scmi_chan_info *cinfo = p;
673         struct idr *idr = data;
674
675         if (!IS_ERR_OR_NULL(cinfo->chan)) {
676                 mbox_free_channel(cinfo->chan);
677                 cinfo->chan = NULL;
678         }
679
680         idr_remove(idr, id);
681
682         return 0;
683 }
684
685 static int scmi_remove(struct platform_device *pdev)
686 {
687         int ret = 0;
688         struct scmi_info *info = platform_get_drvdata(pdev);
689         struct idr *idr = &info->tx_idr;
690
691         mutex_lock(&scmi_list_mutex);
692         if (info->users)
693                 ret = -EBUSY;
694         else
695                 list_del(&info->node);
696         mutex_unlock(&scmi_list_mutex);
697
698         if (ret)
699                 return ret;
700
701         /* Safe to free channels since no more users */
702         ret = idr_for_each(idr, scmi_mbox_free_channel, idr);
703         idr_destroy(&info->tx_idr);
704
705         return ret;
706 }
707
708 static int scmi_mailbox_chan_validate(struct device *cdev)
709 {
710         int num_mb, num_sh, ret = 0;
711         struct device_node *np = cdev->of_node;
712
713         num_mb = of_count_phandle_with_args(np, "mboxes", "#mbox-cells");
714         num_sh = of_count_phandle_with_args(np, "shmem", NULL);
715         /* Bail out if mboxes and shmem descriptors are inconsistent */
716         if (num_mb <= 0 || num_sh > 2 || num_mb != num_sh) {
717                 dev_warn(cdev, "Invalid channel descriptor for '%s'\n",
718                          of_node_full_name(np));
719                 return -EINVAL;
720         }
721
722         if (num_sh > 1) {
723                 struct device_node *np_tx, *np_rx;
724
725                 np_tx = of_parse_phandle(np, "shmem", 0);
726                 np_rx = of_parse_phandle(np, "shmem", 1);
727                 /* SCMI Tx and Rx shared mem areas have to be distinct */
728                 if (!np_tx || !np_rx || np_tx == np_rx) {
729                         dev_warn(cdev, "Invalid shmem descriptor for '%s'\n",
730                                  of_node_full_name(np));
731                         ret = -EINVAL;
732                 }
733
734                 of_node_put(np_tx);
735                 of_node_put(np_rx);
736         }
737
738         return ret;
739 }
740
741 static inline int
742 scmi_mbox_chan_setup(struct scmi_info *info, struct device *dev, int prot_id)
743 {
744         int ret;
745         struct resource res;
746         resource_size_t size;
747         struct device_node *shmem, *np = dev->of_node;
748         struct scmi_chan_info *cinfo;
749         struct mbox_client *cl;
750
751         if (scmi_mailbox_check(np)) {
752                 cinfo = idr_find(&info->tx_idr, SCMI_PROTOCOL_BASE);
753                 goto idr_alloc;
754         }
755
756         ret = scmi_mailbox_chan_validate(dev);
757         if (ret)
758                 return ret;
759
760         cinfo = devm_kzalloc(info->dev, sizeof(*cinfo), GFP_KERNEL);
761         if (!cinfo)
762                 return -ENOMEM;
763
764         cinfo->dev = dev;
765
766         cl = &cinfo->cl;
767         cl->dev = dev;
768         cl->rx_callback = scmi_rx_callback;
769         cl->tx_prepare = scmi_tx_prepare;
770         cl->tx_block = false;
771         cl->knows_txdone = true;
772
773         shmem = of_parse_phandle(np, "shmem", 0);
774         ret = of_address_to_resource(shmem, 0, &res);
775         of_node_put(shmem);
776         if (ret) {
777                 dev_err(dev, "failed to get SCMI Tx payload mem resource\n");
778                 return ret;
779         }
780
781         size = resource_size(&res);
782         cinfo->payload = devm_ioremap(info->dev, res.start, size);
783         if (!cinfo->payload) {
784                 dev_err(dev, "failed to ioremap SCMI Tx payload\n");
785                 return -EADDRNOTAVAIL;
786         }
787
788         /* Transmit channel is first entry i.e. index 0 */
789         cinfo->chan = mbox_request_channel(cl, 0);
790         if (IS_ERR(cinfo->chan)) {
791                 ret = PTR_ERR(cinfo->chan);
792                 if (ret != -EPROBE_DEFER)
793                         dev_err(dev, "failed to request SCMI Tx mailbox\n");
794                 return ret;
795         }
796
797 idr_alloc:
798         ret = idr_alloc(&info->tx_idr, cinfo, prot_id, prot_id + 1, GFP_KERNEL);
799         if (ret != prot_id) {
800                 dev_err(dev, "unable to allocate SCMI idr slot err %d\n", ret);
801                 return ret;
802         }
803
804         cinfo->handle = &info->handle;
805         return 0;
806 }
807
808 static inline void
809 scmi_create_protocol_device(struct device_node *np, struct scmi_info *info,
810                             int prot_id)
811 {
812         struct scmi_device *sdev;
813
814         sdev = scmi_device_create(np, info->dev, prot_id);
815         if (!sdev) {
816                 dev_err(info->dev, "failed to create %d protocol device\n",
817                         prot_id);
818                 return;
819         }
820
821         if (scmi_mbox_chan_setup(info, &sdev->dev, prot_id)) {
822                 dev_err(&sdev->dev, "failed to setup transport\n");
823                 scmi_device_destroy(sdev);
824                 return;
825         }
826
827         /* setup handle now as the transport is ready */
828         scmi_set_handle(sdev);
829 }
830
831 static int scmi_probe(struct platform_device *pdev)
832 {
833         int ret;
834         struct scmi_handle *handle;
835         const struct scmi_desc *desc;
836         struct scmi_info *info;
837         struct device *dev = &pdev->dev;
838         struct device_node *child, *np = dev->of_node;
839
840         /* Only mailbox method supported, check for the presence of one */
841         if (scmi_mailbox_check(np)) {
842                 dev_err(dev, "no mailbox found in %pOF\n", np);
843                 return -EINVAL;
844         }
845
846         desc = of_match_device(scmi_of_match, dev)->data;
847
848         info = devm_kzalloc(dev, sizeof(*info), GFP_KERNEL);
849         if (!info)
850                 return -ENOMEM;
851
852         info->dev = dev;
853         info->desc = desc;
854         INIT_LIST_HEAD(&info->node);
855
856         ret = scmi_xfer_info_init(info);
857         if (ret)
858                 return ret;
859
860         platform_set_drvdata(pdev, info);
861         idr_init(&info->tx_idr);
862
863         handle = &info->handle;
864         handle->dev = info->dev;
865         handle->version = &info->version;
866
867         ret = scmi_mbox_chan_setup(info, dev, SCMI_PROTOCOL_BASE);
868         if (ret)
869                 return ret;
870
871         ret = scmi_base_protocol_init(handle);
872         if (ret) {
873                 dev_err(dev, "unable to communicate with SCMI(%d)\n", ret);
874                 return ret;
875         }
876
877         mutex_lock(&scmi_list_mutex);
878         list_add_tail(&info->node, &scmi_list);
879         mutex_unlock(&scmi_list_mutex);
880
881         for_each_available_child_of_node(np, child) {
882                 u32 prot_id;
883
884                 if (of_property_read_u32(child, "reg", &prot_id))
885                         continue;
886
887                 if (!FIELD_FIT(MSG_PROTOCOL_ID_MASK, prot_id))
888                         dev_err(dev, "Out of range protocol %d\n", prot_id);
889
890                 if (!scmi_is_protocol_implemented(handle, prot_id)) {
891                         dev_err(dev, "SCMI protocol %d not implemented\n",
892                                 prot_id);
893                         continue;
894                 }
895
896                 scmi_create_protocol_device(child, info, prot_id);
897         }
898
899         return 0;
900 }
901
902 static struct platform_driver scmi_driver = {
903         .driver = {
904                    .name = "arm-scmi",
905                    .of_match_table = scmi_of_match,
906                    },
907         .probe = scmi_probe,
908         .remove = scmi_remove,
909 };
910
911 module_platform_driver(scmi_driver);
912
913 MODULE_ALIAS("platform:arm-scmi");
914 MODULE_AUTHOR("Sudeep Holla <sudeep.holla@arm.com>");
915 MODULE_DESCRIPTION("ARM SCMI protocol driver");
916 MODULE_LICENSE("GPL v2");