linux/drivers/firmware/arm_scmi/driver.c
<<
>>
Prefs
   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/list.h>
  25#include <linux/module.h>
  26#include <linux/of_address.h>
  27#include <linux/of_device.h>
  28#include <linux/processor.h>
  29#include <linux/refcount.h>
  30#include <linux/slab.h>
  31
  32#include "common.h"
  33#include "notify.h"
  34
  35#define CREATE_TRACE_POINTS
  36#include <trace/events/scmi.h>
  37
  38enum scmi_error_codes {
  39        SCMI_SUCCESS = 0,       /* Success */
  40        SCMI_ERR_SUPPORT = -1,  /* Not supported */
  41        SCMI_ERR_PARAMS = -2,   /* Invalid Parameters */
  42        SCMI_ERR_ACCESS = -3,   /* Invalid access/permission denied */
  43        SCMI_ERR_ENTRY = -4,    /* Not found */
  44        SCMI_ERR_RANGE = -5,    /* Value out of range */
  45        SCMI_ERR_BUSY = -6,     /* Device busy */
  46        SCMI_ERR_COMMS = -7,    /* Communication Error */
  47        SCMI_ERR_GENERIC = -8,  /* Generic Error */
  48        SCMI_ERR_HARDWARE = -9, /* Hardware Error */
  49        SCMI_ERR_PROTOCOL = -10,/* Protocol Error */
  50};
  51
  52/* List of all SCMI devices active in system */
  53static LIST_HEAD(scmi_list);
  54/* Protection for the entire list */
  55static DEFINE_MUTEX(scmi_list_mutex);
  56/* Track the unique id for the transfers for debug & profiling purpose */
  57static atomic_t transfer_last_id;
  58
  59static DEFINE_IDR(scmi_requested_devices);
  60static DEFINE_MUTEX(scmi_requested_devices_mtx);
  61
  62struct scmi_requested_dev {
  63        const struct scmi_device_id *id_table;
  64        struct list_head node;
  65};
  66
  67/**
  68 * struct scmi_xfers_info - Structure to manage transfer information
  69 *
  70 * @xfer_block: Preallocated Message array
  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 */
  76struct scmi_xfers_info {
  77        struct scmi_xfer *xfer_block;
  78        unsigned long *xfer_alloc_table;
  79        spinlock_t xfer_lock;
  80};
  81
  82/**
  83 * struct scmi_protocol_instance  - Describe an initialized protocol instance.
  84 * @handle: Reference to the SCMI handle associated to this protocol instance.
  85 * @proto: A reference to the protocol descriptor.
  86 * @gid: A reference for per-protocol devres management.
  87 * @users: A refcount to track effective users of this protocol.
  88 * @priv: Reference for optional protocol private data.
  89 * @ph: An embedded protocol handle that will be passed down to protocol
  90 *      initialization code to identify this instance.
  91 *
  92 * Each protocol is initialized independently once for each SCMI platform in
  93 * which is defined by DT and implemented by the SCMI server fw.
  94 */
  95struct scmi_protocol_instance {
  96        const struct scmi_handle        *handle;
  97        const struct scmi_protocol      *proto;
  98        void                            *gid;
  99        refcount_t                      users;
 100        void                            *priv;
 101        struct scmi_protocol_handle     ph;
 102};
 103
 104#define ph_to_pi(h)     container_of(h, struct scmi_protocol_instance, ph)
 105
 106/**
 107 * struct scmi_info - Structure representing a SCMI instance
 108 *
 109 * @dev: Device pointer
 110 * @desc: SoC description for this instance
 111 * @version: SCMI revision information containing protocol version,
 112 *      implementation version and (sub-)vendor identification.
 113 * @handle: Instance of SCMI handle to send to clients
 114 * @tx_minfo: Universal Transmit Message management info
 115 * @rx_minfo: Universal Receive Message management info
 116 * @tx_idr: IDR object to map protocol id to Tx channel info pointer
 117 * @rx_idr: IDR object to map protocol id to Rx channel info pointer
 118 * @protocols: IDR for protocols' instance descriptors initialized for
 119 *             this SCMI instance: populated on protocol's first attempted
 120 *             usage.
 121 * @protocols_mtx: A mutex to protect protocols instances initialization.
 122 * @protocols_imp: List of protocols implemented, currently maximum of
 123 *      MAX_PROTOCOLS_IMP elements allocated by the base protocol
 124 * @active_protocols: IDR storing device_nodes for protocols actually defined
 125 *                    in the DT and confirmed as implemented by fw.
 126 * @notify_priv: Pointer to private data structure specific to notifications.
 127 * @node: List head
 128 * @users: Number of users of this instance
 129 */
 130struct scmi_info {
 131        struct device *dev;
 132        const struct scmi_desc *desc;
 133        struct scmi_revision_info version;
 134        struct scmi_handle handle;
 135        struct scmi_xfers_info tx_minfo;
 136        struct scmi_xfers_info rx_minfo;
 137        struct idr tx_idr;
 138        struct idr rx_idr;
 139        struct idr protocols;
 140        /* Ensure mutual exclusive access to protocols instance array */
 141        struct mutex protocols_mtx;
 142        u8 *protocols_imp;
 143        struct idr active_protocols;
 144        void *notify_priv;
 145        struct list_head node;
 146        int users;
 147};
 148
 149#define handle_to_scmi_info(h)  container_of(h, struct scmi_info, handle)
 150
 151static const int scmi_linux_errmap[] = {
 152        /* better than switch case as long as return value is continuous */
 153        0,                      /* SCMI_SUCCESS */
 154        -EOPNOTSUPP,            /* SCMI_ERR_SUPPORT */
 155        -EINVAL,                /* SCMI_ERR_PARAM */
 156        -EACCES,                /* SCMI_ERR_ACCESS */
 157        -ENOENT,                /* SCMI_ERR_ENTRY */
 158        -ERANGE,                /* SCMI_ERR_RANGE */
 159        -EBUSY,                 /* SCMI_ERR_BUSY */
 160        -ECOMM,                 /* SCMI_ERR_COMMS */
 161        -EIO,                   /* SCMI_ERR_GENERIC */
 162        -EREMOTEIO,             /* SCMI_ERR_HARDWARE */
 163        -EPROTO,                /* SCMI_ERR_PROTOCOL */
 164};
 165
 166static inline int scmi_to_linux_errno(int errno)
 167{
 168        int err_idx = -errno;
 169
 170        if (err_idx >= SCMI_SUCCESS && err_idx < ARRAY_SIZE(scmi_linux_errmap))
 171                return scmi_linux_errmap[err_idx];
 172        return -EIO;
 173}
 174
 175/**
 176 * scmi_dump_header_dbg() - Helper to dump a message header.
 177 *
 178 * @dev: Device pointer corresponding to the SCMI entity
 179 * @hdr: pointer to header.
 180 */
 181static inline void scmi_dump_header_dbg(struct device *dev,
 182                                        struct scmi_msg_hdr *hdr)
 183{
 184        dev_dbg(dev, "Message ID: %x Sequence ID: %x Protocol: %x\n",
 185                hdr->id, hdr->seq, hdr->protocol_id);
 186}
 187
 188void scmi_notification_instance_data_set(const struct scmi_handle *handle,
 189                                         void *priv)
 190{
 191        struct scmi_info *info = handle_to_scmi_info(handle);
 192
 193        info->notify_priv = priv;
 194        /* Ensure updated protocol private date are visible */
 195        smp_wmb();
 196}
 197
 198void *scmi_notification_instance_data_get(const struct scmi_handle *handle)
 199{
 200        struct scmi_info *info = handle_to_scmi_info(handle);
 201
 202        /* Ensure protocols_private_data has been updated */
 203        smp_rmb();
 204        return info->notify_priv;
 205}
 206
 207/**
 208 * scmi_xfer_get() - Allocate one message
 209 *
 210 * @handle: Pointer to SCMI entity handle
 211 * @minfo: Pointer to Tx/Rx Message management info based on channel type
 212 *
 213 * Helper function which is used by various message functions that are
 214 * exposed to clients of this driver for allocating a message traffic event.
 215 *
 216 * This function can sleep depending on pending requests already in the system
 217 * for the SCMI entity. Further, this also holds a spinlock to maintain
 218 * integrity of internal data structures.
 219 *
 220 * Return: 0 if all went fine, else corresponding error.
 221 */
 222static struct scmi_xfer *scmi_xfer_get(const struct scmi_handle *handle,
 223                                       struct scmi_xfers_info *minfo)
 224{
 225        u16 xfer_id;
 226        struct scmi_xfer *xfer;
 227        unsigned long flags, bit_pos;
 228        struct scmi_info *info = handle_to_scmi_info(handle);
 229
 230        /* Keep the locked section as small as possible */
 231        spin_lock_irqsave(&minfo->xfer_lock, flags);
 232        bit_pos = find_first_zero_bit(minfo->xfer_alloc_table,
 233                                      info->desc->max_msg);
 234        if (bit_pos == info->desc->max_msg) {
 235                spin_unlock_irqrestore(&minfo->xfer_lock, flags);
 236                return ERR_PTR(-ENOMEM);
 237        }
 238        set_bit(bit_pos, minfo->xfer_alloc_table);
 239        spin_unlock_irqrestore(&minfo->xfer_lock, flags);
 240
 241        xfer_id = bit_pos;
 242
 243        xfer = &minfo->xfer_block[xfer_id];
 244        xfer->hdr.seq = xfer_id;
 245        reinit_completion(&xfer->done);
 246        xfer->transfer_id = atomic_inc_return(&transfer_last_id);
 247
 248        return xfer;
 249}
 250
 251/**
 252 * __scmi_xfer_put() - Release a message
 253 *
 254 * @minfo: Pointer to Tx/Rx Message management info based on channel type
 255 * @xfer: message that was reserved by scmi_xfer_get
 256 *
 257 * This holds a spinlock to maintain integrity of internal data structures.
 258 */
 259static void
 260__scmi_xfer_put(struct scmi_xfers_info *minfo, struct scmi_xfer *xfer)
 261{
 262        unsigned long flags;
 263
 264        /*
 265         * Keep the locked section as small as possible
 266         * NOTE: we might escape with smp_mb and no lock here..
 267         * but just be conservative and symmetric.
 268         */
 269        spin_lock_irqsave(&minfo->xfer_lock, flags);
 270        clear_bit(xfer->hdr.seq, minfo->xfer_alloc_table);
 271        spin_unlock_irqrestore(&minfo->xfer_lock, flags);
 272}
 273
 274static void scmi_handle_notification(struct scmi_chan_info *cinfo, u32 msg_hdr)
 275{
 276        struct scmi_xfer *xfer;
 277        struct device *dev = cinfo->dev;
 278        struct scmi_info *info = handle_to_scmi_info(cinfo->handle);
 279        struct scmi_xfers_info *minfo = &info->rx_minfo;
 280        ktime_t ts;
 281
 282        ts = ktime_get_boottime();
 283        xfer = scmi_xfer_get(cinfo->handle, minfo);
 284        if (IS_ERR(xfer)) {
 285                dev_err(dev, "failed to get free message slot (%ld)\n",
 286                        PTR_ERR(xfer));
 287                info->desc->ops->clear_channel(cinfo);
 288                return;
 289        }
 290
 291        unpack_scmi_header(msg_hdr, &xfer->hdr);
 292        scmi_dump_header_dbg(dev, &xfer->hdr);
 293        info->desc->ops->fetch_notification(cinfo, info->desc->max_msg_size,
 294                                            xfer);
 295        scmi_notify(cinfo->handle, xfer->hdr.protocol_id,
 296                    xfer->hdr.id, xfer->rx.buf, xfer->rx.len, ts);
 297
 298        trace_scmi_rx_done(xfer->transfer_id, xfer->hdr.id,
 299                           xfer->hdr.protocol_id, xfer->hdr.seq,
 300                           MSG_TYPE_NOTIFICATION);
 301
 302        __scmi_xfer_put(minfo, xfer);
 303
 304        info->desc->ops->clear_channel(cinfo);
 305}
 306
 307static void scmi_handle_response(struct scmi_chan_info *cinfo,
 308                                 u16 xfer_id, u8 msg_type)
 309{
 310        struct scmi_xfer *xfer;
 311        struct device *dev = cinfo->dev;
 312        struct scmi_info *info = handle_to_scmi_info(cinfo->handle);
 313        struct scmi_xfers_info *minfo = &info->tx_minfo;
 314
 315        /* Are we even expecting this? */
 316        if (!test_bit(xfer_id, minfo->xfer_alloc_table)) {
 317                dev_err(dev, "message for %d is not expected!\n", xfer_id);
 318                info->desc->ops->clear_channel(cinfo);
 319                return;
 320        }
 321
 322        xfer = &minfo->xfer_block[xfer_id];
 323        /*
 324         * Even if a response was indeed expected on this slot at this point,
 325         * a buggy platform could wrongly reply feeding us an unexpected
 326         * delayed response we're not prepared to handle: bail-out safely
 327         * blaming firmware.
 328         */
 329        if (unlikely(msg_type == MSG_TYPE_DELAYED_RESP && !xfer->async_done)) {
 330                dev_err(dev,
 331                        "Delayed Response for %d not expected! Buggy F/W ?\n",
 332                        xfer_id);
 333                info->desc->ops->clear_channel(cinfo);
 334                /* It was unexpected, so nobody will clear the xfer if not us */
 335                __scmi_xfer_put(minfo, xfer);
 336                return;
 337        }
 338
 339        /* rx.len could be shrunk in the sync do_xfer, so reset to maxsz */
 340        if (msg_type == MSG_TYPE_DELAYED_RESP)
 341                xfer->rx.len = info->desc->max_msg_size;
 342
 343        scmi_dump_header_dbg(dev, &xfer->hdr);
 344
 345        info->desc->ops->fetch_response(cinfo, xfer);
 346
 347        trace_scmi_rx_done(xfer->transfer_id, xfer->hdr.id,
 348                           xfer->hdr.protocol_id, xfer->hdr.seq,
 349                           msg_type);
 350
 351        if (msg_type == MSG_TYPE_DELAYED_RESP) {
 352                info->desc->ops->clear_channel(cinfo);
 353                complete(xfer->async_done);
 354        } else {
 355                complete(&xfer->done);
 356        }
 357}
 358
 359/**
 360 * scmi_rx_callback() - callback for receiving messages
 361 *
 362 * @cinfo: SCMI channel info
 363 * @msg_hdr: Message header
 364 *
 365 * Processes one received message to appropriate transfer information and
 366 * signals completion of the transfer.
 367 *
 368 * NOTE: This function will be invoked in IRQ context, hence should be
 369 * as optimal as possible.
 370 */
 371void scmi_rx_callback(struct scmi_chan_info *cinfo, u32 msg_hdr)
 372{
 373        u16 xfer_id = MSG_XTRACT_TOKEN(msg_hdr);
 374        u8 msg_type = MSG_XTRACT_TYPE(msg_hdr);
 375
 376        switch (msg_type) {
 377        case MSG_TYPE_NOTIFICATION:
 378                scmi_handle_notification(cinfo, msg_hdr);
 379                break;
 380        case MSG_TYPE_COMMAND:
 381        case MSG_TYPE_DELAYED_RESP:
 382                scmi_handle_response(cinfo, xfer_id, msg_type);
 383                break;
 384        default:
 385                WARN_ONCE(1, "received unknown msg_type:%d\n", msg_type);
 386                break;
 387        }
 388}
 389
 390/**
 391 * xfer_put() - Release a transmit message
 392 *
 393 * @ph: Pointer to SCMI protocol handle
 394 * @xfer: message that was reserved by scmi_xfer_get
 395 */
 396static void xfer_put(const struct scmi_protocol_handle *ph,
 397                     struct scmi_xfer *xfer)
 398{
 399        const struct scmi_protocol_instance *pi = ph_to_pi(ph);
 400        struct scmi_info *info = handle_to_scmi_info(pi->handle);
 401
 402        __scmi_xfer_put(&info->tx_minfo, xfer);
 403}
 404
 405#define SCMI_MAX_POLL_TO_NS     (100 * NSEC_PER_USEC)
 406
 407static bool scmi_xfer_done_no_timeout(struct scmi_chan_info *cinfo,
 408                                      struct scmi_xfer *xfer, ktime_t stop)
 409{
 410        struct scmi_info *info = handle_to_scmi_info(cinfo->handle);
 411
 412        return info->desc->ops->poll_done(cinfo, xfer) ||
 413               ktime_after(ktime_get(), stop);
 414}
 415
 416/**
 417 * do_xfer() - Do one transfer
 418 *
 419 * @ph: Pointer to SCMI protocol handle
 420 * @xfer: Transfer to initiate and wait for response
 421 *
 422 * Return: -ETIMEDOUT in case of no response, if transmit error,
 423 *      return corresponding error, else if all goes well,
 424 *      return 0.
 425 */
 426static int do_xfer(const struct scmi_protocol_handle *ph,
 427                   struct scmi_xfer *xfer)
 428{
 429        int ret;
 430        int timeout;
 431        const struct scmi_protocol_instance *pi = ph_to_pi(ph);
 432        struct scmi_info *info = handle_to_scmi_info(pi->handle);
 433        struct device *dev = info->dev;
 434        struct scmi_chan_info *cinfo;
 435
 436        /*
 437         * Re-instate protocol id here from protocol handle so that cannot be
 438         * overridden by mistake (or malice) by the protocol code mangling with
 439         * the scmi_xfer structure.
 440         */
 441        xfer->hdr.protocol_id = pi->proto->id;
 442
 443        cinfo = idr_find(&info->tx_idr, xfer->hdr.protocol_id);
 444        if (unlikely(!cinfo))
 445                return -EINVAL;
 446
 447        trace_scmi_xfer_begin(xfer->transfer_id, xfer->hdr.id,
 448                              xfer->hdr.protocol_id, xfer->hdr.seq,
 449                              xfer->hdr.poll_completion);
 450
 451        ret = info->desc->ops->send_message(cinfo, xfer);
 452        if (ret < 0) {
 453                dev_dbg(dev, "Failed to send message %d\n", ret);
 454                return ret;
 455        }
 456
 457        if (xfer->hdr.poll_completion) {
 458                ktime_t stop = ktime_add_ns(ktime_get(), SCMI_MAX_POLL_TO_NS);
 459
 460                spin_until_cond(scmi_xfer_done_no_timeout(cinfo, xfer, stop));
 461
 462                if (ktime_before(ktime_get(), stop))
 463                        info->desc->ops->fetch_response(cinfo, xfer);
 464                else
 465                        ret = -ETIMEDOUT;
 466        } else {
 467                /* And we wait for the response. */
 468                timeout = msecs_to_jiffies(info->desc->max_rx_timeout_ms);
 469                if (!wait_for_completion_timeout(&xfer->done, timeout)) {
 470                        dev_err(dev, "timed out in resp(caller: %pS)\n",
 471                                (void *)_RET_IP_);
 472                        ret = -ETIMEDOUT;
 473                }
 474        }
 475
 476        if (!ret && xfer->hdr.status)
 477                ret = scmi_to_linux_errno(xfer->hdr.status);
 478
 479        if (info->desc->ops->mark_txdone)
 480                info->desc->ops->mark_txdone(cinfo, ret);
 481
 482        trace_scmi_xfer_end(xfer->transfer_id, xfer->hdr.id,
 483                            xfer->hdr.protocol_id, xfer->hdr.seq, ret);
 484
 485        return ret;
 486}
 487
 488static void reset_rx_to_maxsz(const struct scmi_protocol_handle *ph,
 489                              struct scmi_xfer *xfer)
 490{
 491        const struct scmi_protocol_instance *pi = ph_to_pi(ph);
 492        struct scmi_info *info = handle_to_scmi_info(pi->handle);
 493
 494        xfer->rx.len = info->desc->max_msg_size;
 495}
 496
 497#define SCMI_MAX_RESPONSE_TIMEOUT       (2 * MSEC_PER_SEC)
 498
 499/**
 500 * do_xfer_with_response() - Do one transfer and wait until the delayed
 501 *      response is received
 502 *
 503 * @ph: Pointer to SCMI protocol handle
 504 * @xfer: Transfer to initiate and wait for response
 505 *
 506 * Return: -ETIMEDOUT in case of no delayed response, if transmit error,
 507 *      return corresponding error, else if all goes well, return 0.
 508 */
 509static int do_xfer_with_response(const struct scmi_protocol_handle *ph,
 510                                 struct scmi_xfer *xfer)
 511{
 512        int ret, timeout = msecs_to_jiffies(SCMI_MAX_RESPONSE_TIMEOUT);
 513        const struct scmi_protocol_instance *pi = ph_to_pi(ph);
 514        DECLARE_COMPLETION_ONSTACK(async_response);
 515
 516        xfer->hdr.protocol_id = pi->proto->id;
 517
 518        xfer->async_done = &async_response;
 519
 520        ret = do_xfer(ph, xfer);
 521        if (!ret) {
 522                if (!wait_for_completion_timeout(xfer->async_done, timeout))
 523                        ret = -ETIMEDOUT;
 524                else if (xfer->hdr.status)
 525                        ret = scmi_to_linux_errno(xfer->hdr.status);
 526        }
 527
 528        xfer->async_done = NULL;
 529        return ret;
 530}
 531
 532/**
 533 * xfer_get_init() - Allocate and initialise one message for transmit
 534 *
 535 * @ph: Pointer to SCMI protocol handle
 536 * @msg_id: Message identifier
 537 * @tx_size: transmit message size
 538 * @rx_size: receive message size
 539 * @p: pointer to the allocated and initialised message
 540 *
 541 * This function allocates the message using @scmi_xfer_get and
 542 * initialise the header.
 543 *
 544 * Return: 0 if all went fine with @p pointing to message, else
 545 *      corresponding error.
 546 */
 547static int xfer_get_init(const struct scmi_protocol_handle *ph,
 548                         u8 msg_id, size_t tx_size, size_t rx_size,
 549                         struct scmi_xfer **p)
 550{
 551        int ret;
 552        struct scmi_xfer *xfer;
 553        const struct scmi_protocol_instance *pi = ph_to_pi(ph);
 554        struct scmi_info *info = handle_to_scmi_info(pi->handle);
 555        struct scmi_xfers_info *minfo = &info->tx_minfo;
 556        struct device *dev = info->dev;
 557
 558        /* Ensure we have sane transfer sizes */
 559        if (rx_size > info->desc->max_msg_size ||
 560            tx_size > info->desc->max_msg_size)
 561                return -ERANGE;
 562
 563        xfer = scmi_xfer_get(pi->handle, minfo);
 564        if (IS_ERR(xfer)) {
 565                ret = PTR_ERR(xfer);
 566                dev_err(dev, "failed to get free message slot(%d)\n", ret);
 567                return ret;
 568        }
 569
 570        xfer->tx.len = tx_size;
 571        xfer->rx.len = rx_size ? : info->desc->max_msg_size;
 572        xfer->hdr.id = msg_id;
 573        xfer->hdr.protocol_id = pi->proto->id;
 574        xfer->hdr.poll_completion = false;
 575
 576        *p = xfer;
 577
 578        return 0;
 579}
 580
 581/**
 582 * version_get() - command to get the revision of the SCMI entity
 583 *
 584 * @ph: Pointer to SCMI protocol handle
 585 * @version: Holds returned version of protocol.
 586 *
 587 * Updates the SCMI information in the internal data structure.
 588 *
 589 * Return: 0 if all went fine, else return appropriate error.
 590 */
 591static int version_get(const struct scmi_protocol_handle *ph, u32 *version)
 592{
 593        int ret;
 594        __le32 *rev_info;
 595        struct scmi_xfer *t;
 596
 597        ret = xfer_get_init(ph, PROTOCOL_VERSION, 0, sizeof(*version), &t);
 598        if (ret)
 599                return ret;
 600
 601        ret = do_xfer(ph, t);
 602        if (!ret) {
 603                rev_info = t->rx.buf;
 604                *version = le32_to_cpu(*rev_info);
 605        }
 606
 607        xfer_put(ph, t);
 608        return ret;
 609}
 610
 611/**
 612 * scmi_set_protocol_priv  - Set protocol specific data at init time
 613 *
 614 * @ph: A reference to the protocol handle.
 615 * @priv: The private data to set.
 616 *
 617 * Return: 0 on Success
 618 */
 619static int scmi_set_protocol_priv(const struct scmi_protocol_handle *ph,
 620                                  void *priv)
 621{
 622        struct scmi_protocol_instance *pi = ph_to_pi(ph);
 623
 624        pi->priv = priv;
 625
 626        return 0;
 627}
 628
 629/**
 630 * scmi_get_protocol_priv  - Set protocol specific data at init time
 631 *
 632 * @ph: A reference to the protocol handle.
 633 *
 634 * Return: Protocol private data if any was set.
 635 */
 636static void *scmi_get_protocol_priv(const struct scmi_protocol_handle *ph)
 637{
 638        const struct scmi_protocol_instance *pi = ph_to_pi(ph);
 639
 640        return pi->priv;
 641}
 642
 643static const struct scmi_xfer_ops xfer_ops = {
 644        .version_get = version_get,
 645        .xfer_get_init = xfer_get_init,
 646        .reset_rx_to_maxsz = reset_rx_to_maxsz,
 647        .do_xfer = do_xfer,
 648        .do_xfer_with_response = do_xfer_with_response,
 649        .xfer_put = xfer_put,
 650};
 651
 652/**
 653 * scmi_revision_area_get  - Retrieve version memory area.
 654 *
 655 * @ph: A reference to the protocol handle.
 656 *
 657 * A helper to grab the version memory area reference during SCMI Base protocol
 658 * initialization.
 659 *
 660 * Return: A reference to the version memory area associated to the SCMI
 661 *         instance underlying this protocol handle.
 662 */
 663struct scmi_revision_info *
 664scmi_revision_area_get(const struct scmi_protocol_handle *ph)
 665{
 666        const struct scmi_protocol_instance *pi = ph_to_pi(ph);
 667
 668        return pi->handle->version;
 669}
 670
 671/**
 672 * scmi_alloc_init_protocol_instance  - Allocate and initialize a protocol
 673 * instance descriptor.
 674 * @info: The reference to the related SCMI instance.
 675 * @proto: The protocol descriptor.
 676 *
 677 * Allocate a new protocol instance descriptor, using the provided @proto
 678 * description, against the specified SCMI instance @info, and initialize it;
 679 * all resources management is handled via a dedicated per-protocol devres
 680 * group.
 681 *
 682 * Context: Assumes to be called with @protocols_mtx already acquired.
 683 * Return: A reference to a freshly allocated and initialized protocol instance
 684 *         or ERR_PTR on failure. On failure the @proto reference is at first
 685 *         put using @scmi_protocol_put() before releasing all the devres group.
 686 */
 687static struct scmi_protocol_instance *
 688scmi_alloc_init_protocol_instance(struct scmi_info *info,
 689                                  const struct scmi_protocol *proto)
 690{
 691        int ret = -ENOMEM;
 692        void *gid;
 693        struct scmi_protocol_instance *pi;
 694        const struct scmi_handle *handle = &info->handle;
 695
 696        /* Protocol specific devres group */
 697        gid = devres_open_group(handle->dev, NULL, GFP_KERNEL);
 698        if (!gid) {
 699                scmi_protocol_put(proto->id);
 700                goto out;
 701        }
 702
 703        pi = devm_kzalloc(handle->dev, sizeof(*pi), GFP_KERNEL);
 704        if (!pi)
 705                goto clean;
 706
 707        pi->gid = gid;
 708        pi->proto = proto;
 709        pi->handle = handle;
 710        pi->ph.dev = handle->dev;
 711        pi->ph.xops = &xfer_ops;
 712        pi->ph.set_priv = scmi_set_protocol_priv;
 713        pi->ph.get_priv = scmi_get_protocol_priv;
 714        refcount_set(&pi->users, 1);
 715        /* proto->init is assured NON NULL by scmi_protocol_register */
 716        ret = pi->proto->instance_init(&pi->ph);
 717        if (ret)
 718                goto clean;
 719
 720        ret = idr_alloc(&info->protocols, pi, proto->id, proto->id + 1,
 721                        GFP_KERNEL);
 722        if (ret != proto->id)
 723                goto clean;
 724
 725        /*
 726         * Warn but ignore events registration errors since we do not want
 727         * to skip whole protocols if their notifications are messed up.
 728         */
 729        if (pi->proto->events) {
 730                ret = scmi_register_protocol_events(handle, pi->proto->id,
 731                                                    &pi->ph,
 732                                                    pi->proto->events);
 733                if (ret)
 734                        dev_warn(handle->dev,
 735                                 "Protocol:%X - Events Registration Failed - err:%d\n",
 736                                 pi->proto->id, ret);
 737        }
 738
 739        devres_close_group(handle->dev, pi->gid);
 740        dev_dbg(handle->dev, "Initialized protocol: 0x%X\n", pi->proto->id);
 741
 742        return pi;
 743
 744clean:
 745        /* Take care to put the protocol module's owner before releasing all */
 746        scmi_protocol_put(proto->id);
 747        devres_release_group(handle->dev, gid);
 748out:
 749        return ERR_PTR(ret);
 750}
 751
 752/**
 753 * scmi_get_protocol_instance  - Protocol initialization helper.
 754 * @handle: A reference to the SCMI platform instance.
 755 * @protocol_id: The protocol being requested.
 756 *
 757 * In case the required protocol has never been requested before for this
 758 * instance, allocate and initialize all the needed structures while handling
 759 * resource allocation with a dedicated per-protocol devres subgroup.
 760 *
 761 * Return: A reference to an initialized protocol instance or error on failure:
 762 *         in particular returns -EPROBE_DEFER when the desired protocol could
 763 *         NOT be found.
 764 */
 765static struct scmi_protocol_instance * __must_check
 766scmi_get_protocol_instance(const struct scmi_handle *handle, u8 protocol_id)
 767{
 768        struct scmi_protocol_instance *pi;
 769        struct scmi_info *info = handle_to_scmi_info(handle);
 770
 771        mutex_lock(&info->protocols_mtx);
 772        pi = idr_find(&info->protocols, protocol_id);
 773
 774        if (pi) {
 775                refcount_inc(&pi->users);
 776        } else {
 777                const struct scmi_protocol *proto;
 778
 779                /* Fails if protocol not registered on bus */
 780                proto = scmi_protocol_get(protocol_id);
 781                if (proto)
 782                        pi = scmi_alloc_init_protocol_instance(info, proto);
 783                else
 784                        pi = ERR_PTR(-EPROBE_DEFER);
 785        }
 786        mutex_unlock(&info->protocols_mtx);
 787
 788        return pi;
 789}
 790
 791/**
 792 * scmi_protocol_acquire  - Protocol acquire
 793 * @handle: A reference to the SCMI platform instance.
 794 * @protocol_id: The protocol being requested.
 795 *
 796 * Register a new user for the requested protocol on the specified SCMI
 797 * platform instance, possibly triggering its initialization on first user.
 798 *
 799 * Return: 0 if protocol was acquired successfully.
 800 */
 801int scmi_protocol_acquire(const struct scmi_handle *handle, u8 protocol_id)
 802{
 803        return PTR_ERR_OR_ZERO(scmi_get_protocol_instance(handle, protocol_id));
 804}
 805
 806/**
 807 * scmi_protocol_release  - Protocol de-initialization helper.
 808 * @handle: A reference to the SCMI platform instance.
 809 * @protocol_id: The protocol being requested.
 810 *
 811 * Remove one user for the specified protocol and triggers de-initialization
 812 * and resources de-allocation once the last user has gone.
 813 */
 814void scmi_protocol_release(const struct scmi_handle *handle, u8 protocol_id)
 815{
 816        struct scmi_info *info = handle_to_scmi_info(handle);
 817        struct scmi_protocol_instance *pi;
 818
 819        mutex_lock(&info->protocols_mtx);
 820        pi = idr_find(&info->protocols, protocol_id);
 821        if (WARN_ON(!pi))
 822                goto out;
 823
 824        if (refcount_dec_and_test(&pi->users)) {
 825                void *gid = pi->gid;
 826
 827                if (pi->proto->events)
 828                        scmi_deregister_protocol_events(handle, protocol_id);
 829
 830                if (pi->proto->instance_deinit)
 831                        pi->proto->instance_deinit(&pi->ph);
 832
 833                idr_remove(&info->protocols, protocol_id);
 834
 835                scmi_protocol_put(protocol_id);
 836
 837                devres_release_group(handle->dev, gid);
 838                dev_dbg(handle->dev, "De-Initialized protocol: 0x%X\n",
 839                        protocol_id);
 840        }
 841
 842out:
 843        mutex_unlock(&info->protocols_mtx);
 844}
 845
 846void scmi_setup_protocol_implemented(const struct scmi_protocol_handle *ph,
 847                                     u8 *prot_imp)
 848{
 849        const struct scmi_protocol_instance *pi = ph_to_pi(ph);
 850        struct scmi_info *info = handle_to_scmi_info(pi->handle);
 851
 852        info->protocols_imp = prot_imp;
 853}
 854
 855static bool
 856scmi_is_protocol_implemented(const struct scmi_handle *handle, u8 prot_id)
 857{
 858        int i;
 859        struct scmi_info *info = handle_to_scmi_info(handle);
 860
 861        if (!info->protocols_imp)
 862                return false;
 863
 864        for (i = 0; i < MAX_PROTOCOLS_IMP; i++)
 865                if (info->protocols_imp[i] == prot_id)
 866                        return true;
 867        return false;
 868}
 869
 870struct scmi_protocol_devres {
 871        const struct scmi_handle *handle;
 872        u8 protocol_id;
 873};
 874
 875static void scmi_devm_release_protocol(struct device *dev, void *res)
 876{
 877        struct scmi_protocol_devres *dres = res;
 878
 879        scmi_protocol_release(dres->handle, dres->protocol_id);
 880}
 881
 882/**
 883 * scmi_devm_protocol_get  - Devres managed get protocol operations and handle
 884 * @sdev: A reference to an scmi_device whose embedded struct device is to
 885 *        be used for devres accounting.
 886 * @protocol_id: The protocol being requested.
 887 * @ph: A pointer reference used to pass back the associated protocol handle.
 888 *
 889 * Get hold of a protocol accounting for its usage, eventually triggering its
 890 * initialization, and returning the protocol specific operations and related
 891 * protocol handle which will be used as first argument in most of the
 892 * protocols operations methods.
 893 * Being a devres based managed method, protocol hold will be automatically
 894 * released, and possibly de-initialized on last user, once the SCMI driver
 895 * owning the scmi_device is unbound from it.
 896 *
 897 * Return: A reference to the requested protocol operations or error.
 898 *         Must be checked for errors by caller.
 899 */
 900static const void __must_check *
 901scmi_devm_protocol_get(struct scmi_device *sdev, u8 protocol_id,
 902                       struct scmi_protocol_handle **ph)
 903{
 904        struct scmi_protocol_instance *pi;
 905        struct scmi_protocol_devres *dres;
 906        struct scmi_handle *handle = sdev->handle;
 907
 908        if (!ph)
 909                return ERR_PTR(-EINVAL);
 910
 911        dres = devres_alloc(scmi_devm_release_protocol,
 912                            sizeof(*dres), GFP_KERNEL);
 913        if (!dres)
 914                return ERR_PTR(-ENOMEM);
 915
 916        pi = scmi_get_protocol_instance(handle, protocol_id);
 917        if (IS_ERR(pi)) {
 918                devres_free(dres);
 919                return pi;
 920        }
 921
 922        dres->handle = handle;
 923        dres->protocol_id = protocol_id;
 924        devres_add(&sdev->dev, dres);
 925
 926        *ph = &pi->ph;
 927
 928        return pi->proto->ops;
 929}
 930
 931static int scmi_devm_protocol_match(struct device *dev, void *res, void *data)
 932{
 933        struct scmi_protocol_devres *dres = res;
 934
 935        if (WARN_ON(!dres || !data))
 936                return 0;
 937
 938        return dres->protocol_id == *((u8 *)data);
 939}
 940
 941/**
 942 * scmi_devm_protocol_put  - Devres managed put protocol operations and handle
 943 * @sdev: A reference to an scmi_device whose embedded struct device is to
 944 *        be used for devres accounting.
 945 * @protocol_id: The protocol being requested.
 946 *
 947 * Explicitly release a protocol hold previously obtained calling the above
 948 * @scmi_devm_protocol_get.
 949 */
 950static void scmi_devm_protocol_put(struct scmi_device *sdev, u8 protocol_id)
 951{
 952        int ret;
 953
 954        ret = devres_release(&sdev->dev, scmi_devm_release_protocol,
 955                             scmi_devm_protocol_match, &protocol_id);
 956        WARN_ON(ret);
 957}
 958
 959static inline
 960struct scmi_handle *scmi_handle_get_from_info_unlocked(struct scmi_info *info)
 961{
 962        info->users++;
 963        return &info->handle;
 964}
 965
 966/**
 967 * scmi_handle_get() - Get the SCMI handle for a device
 968 *
 969 * @dev: pointer to device for which we want SCMI handle
 970 *
 971 * NOTE: The function does not track individual clients of the framework
 972 * and is expected to be maintained by caller of SCMI protocol library.
 973 * scmi_handle_put must be balanced with successful scmi_handle_get
 974 *
 975 * Return: pointer to handle if successful, NULL on error
 976 */
 977struct scmi_handle *scmi_handle_get(struct device *dev)
 978{
 979        struct list_head *p;
 980        struct scmi_info *info;
 981        struct scmi_handle *handle = NULL;
 982
 983        mutex_lock(&scmi_list_mutex);
 984        list_for_each(p, &scmi_list) {
 985                info = list_entry(p, struct scmi_info, node);
 986                if (dev->parent == info->dev) {
 987                        handle = scmi_handle_get_from_info_unlocked(info);
 988                        break;
 989                }
 990        }
 991        mutex_unlock(&scmi_list_mutex);
 992
 993        return handle;
 994}
 995
 996/**
 997 * scmi_handle_put() - Release the handle acquired by scmi_handle_get
 998 *
 999 * @handle: handle acquired by scmi_handle_get
1000 *
1001 * NOTE: The function does not track individual clients of the framework
1002 * and is expected to be maintained by caller of SCMI protocol library.
1003 * scmi_handle_put must be balanced with successful scmi_handle_get
1004 *
1005 * Return: 0 is successfully released
1006 *      if null was passed, it returns -EINVAL;
1007 */
1008int scmi_handle_put(const struct scmi_handle *handle)
1009{
1010        struct scmi_info *info;
1011
1012        if (!handle)
1013                return -EINVAL;
1014
1015        info = handle_to_scmi_info(handle);
1016        mutex_lock(&scmi_list_mutex);
1017        if (!WARN_ON(!info->users))
1018                info->users--;
1019        mutex_unlock(&scmi_list_mutex);
1020
1021        return 0;
1022}
1023
1024static int __scmi_xfer_info_init(struct scmi_info *sinfo,
1025                                 struct scmi_xfers_info *info)
1026{
1027        int i;
1028        struct scmi_xfer *xfer;
1029        struct device *dev = sinfo->dev;
1030        const struct scmi_desc *desc = sinfo->desc;
1031
1032        /* Pre-allocated messages, no more than what hdr.seq can support */
1033        if (WARN_ON(!desc->max_msg || desc->max_msg > MSG_TOKEN_MAX)) {
1034                dev_err(dev,
1035                        "Invalid maximum messages %d, not in range [1 - %lu]\n",
1036                        desc->max_msg, MSG_TOKEN_MAX);
1037                return -EINVAL;
1038        }
1039
1040        info->xfer_block = devm_kcalloc(dev, desc->max_msg,
1041                                        sizeof(*info->xfer_block), GFP_KERNEL);
1042        if (!info->xfer_block)
1043                return -ENOMEM;
1044
1045        info->xfer_alloc_table = devm_kcalloc(dev, BITS_TO_LONGS(desc->max_msg),
1046                                              sizeof(long), GFP_KERNEL);
1047        if (!info->xfer_alloc_table)
1048                return -ENOMEM;
1049
1050        /* Pre-initialize the buffer pointer to pre-allocated buffers */
1051        for (i = 0, xfer = info->xfer_block; i < desc->max_msg; i++, xfer++) {
1052                xfer->rx.buf = devm_kcalloc(dev, sizeof(u8), desc->max_msg_size,
1053                                            GFP_KERNEL);
1054                if (!xfer->rx.buf)
1055                        return -ENOMEM;
1056
1057                xfer->tx.buf = xfer->rx.buf;
1058                init_completion(&xfer->done);
1059        }
1060
1061        spin_lock_init(&info->xfer_lock);
1062
1063        return 0;
1064}
1065
1066static int scmi_xfer_info_init(struct scmi_info *sinfo)
1067{
1068        int ret = __scmi_xfer_info_init(sinfo, &sinfo->tx_minfo);
1069
1070        if (!ret && idr_find(&sinfo->rx_idr, SCMI_PROTOCOL_BASE))
1071                ret = __scmi_xfer_info_init(sinfo, &sinfo->rx_minfo);
1072
1073        return ret;
1074}
1075
1076static int scmi_chan_setup(struct scmi_info *info, struct device *dev,
1077                           int prot_id, bool tx)
1078{
1079        int ret, idx;
1080        struct scmi_chan_info *cinfo;
1081        struct idr *idr;
1082
1083        /* Transmit channel is first entry i.e. index 0 */
1084        idx = tx ? 0 : 1;
1085        idr = tx ? &info->tx_idr : &info->rx_idr;
1086
1087        /* check if already allocated, used for multiple device per protocol */
1088        cinfo = idr_find(idr, prot_id);
1089        if (cinfo)
1090                return 0;
1091
1092        if (!info->desc->ops->chan_available(dev, idx)) {
1093                cinfo = idr_find(idr, SCMI_PROTOCOL_BASE);
1094                if (unlikely(!cinfo)) /* Possible only if platform has no Rx */
1095                        return -EINVAL;
1096                goto idr_alloc;
1097        }
1098
1099        cinfo = devm_kzalloc(info->dev, sizeof(*cinfo), GFP_KERNEL);
1100        if (!cinfo)
1101                return -ENOMEM;
1102
1103        cinfo->dev = dev;
1104
1105        ret = info->desc->ops->chan_setup(cinfo, info->dev, tx);
1106        if (ret)
1107                return ret;
1108
1109idr_alloc:
1110        ret = idr_alloc(idr, cinfo, prot_id, prot_id + 1, GFP_KERNEL);
1111        if (ret != prot_id) {
1112                dev_err(dev, "unable to allocate SCMI idr slot err %d\n", ret);
1113                return ret;
1114        }
1115
1116        cinfo->handle = &info->handle;
1117        return 0;
1118}
1119
1120static inline int
1121scmi_txrx_setup(struct scmi_info *info, struct device *dev, int prot_id)
1122{
1123        int ret = scmi_chan_setup(info, dev, prot_id, true);
1124
1125        if (!ret) /* Rx is optional, hence no error check */
1126                scmi_chan_setup(info, dev, prot_id, false);
1127
1128        return ret;
1129}
1130
1131/**
1132 * scmi_get_protocol_device  - Helper to get/create an SCMI device.
1133 *
1134 * @np: A device node representing a valid active protocols for the referred
1135 * SCMI instance.
1136 * @info: The referred SCMI instance for which we are getting/creating this
1137 * device.
1138 * @prot_id: The protocol ID.
1139 * @name: The device name.
1140 *
1141 * Referring to the specific SCMI instance identified by @info, this helper
1142 * takes care to return a properly initialized device matching the requested
1143 * @proto_id and @name: if device was still not existent it is created as a
1144 * child of the specified SCMI instance @info and its transport properly
1145 * initialized as usual.
1146 */
1147static inline struct scmi_device *
1148scmi_get_protocol_device(struct device_node *np, struct scmi_info *info,
1149                         int prot_id, const char *name)
1150{
1151        struct scmi_device *sdev;
1152
1153        /* Already created for this parent SCMI instance ? */
1154        sdev = scmi_child_dev_find(info->dev, prot_id, name);
1155        if (sdev)
1156                return sdev;
1157
1158        pr_debug("Creating SCMI device (%s) for protocol %x\n", name, prot_id);
1159
1160        sdev = scmi_device_create(np, info->dev, prot_id, name);
1161        if (!sdev) {
1162                dev_err(info->dev, "failed to create %d protocol device\n",
1163                        prot_id);
1164                return NULL;
1165        }
1166
1167        if (scmi_txrx_setup(info, &sdev->dev, prot_id)) {
1168                dev_err(&sdev->dev, "failed to setup transport\n");
1169                scmi_device_destroy(sdev);
1170                return NULL;
1171        }
1172
1173        return sdev;
1174}
1175
1176static inline void
1177scmi_create_protocol_device(struct device_node *np, struct scmi_info *info,
1178                            int prot_id, const char *name)
1179{
1180        struct scmi_device *sdev;
1181
1182        sdev = scmi_get_protocol_device(np, info, prot_id, name);
1183        if (!sdev)
1184                return;
1185
1186        /* setup handle now as the transport is ready */
1187        scmi_set_handle(sdev);
1188}
1189
1190/**
1191 * scmi_create_protocol_devices  - Create devices for all pending requests for
1192 * this SCMI instance.
1193 *
1194 * @np: The device node describing the protocol
1195 * @info: The SCMI instance descriptor
1196 * @prot_id: The protocol ID
1197 *
1198 * All devices previously requested for this instance (if any) are found and
1199 * created by scanning the proper @&scmi_requested_devices entry.
1200 */
1201static void scmi_create_protocol_devices(struct device_node *np,
1202                                         struct scmi_info *info, int prot_id)
1203{
1204        struct list_head *phead;
1205
1206        mutex_lock(&scmi_requested_devices_mtx);
1207        phead = idr_find(&scmi_requested_devices, prot_id);
1208        if (phead) {
1209                struct scmi_requested_dev *rdev;
1210
1211                list_for_each_entry(rdev, phead, node)
1212                        scmi_create_protocol_device(np, info, prot_id,
1213                                                    rdev->id_table->name);
1214        }
1215        mutex_unlock(&scmi_requested_devices_mtx);
1216}
1217
1218/**
1219 * scmi_protocol_device_request  - Helper to request a device
1220 *
1221 * @id_table: A protocol/name pair descriptor for the device to be created.
1222 *
1223 * This helper let an SCMI driver request specific devices identified by the
1224 * @id_table to be created for each active SCMI instance.
1225 *
1226 * The requested device name MUST NOT be already existent for any protocol;
1227 * at first the freshly requested @id_table is annotated in the IDR table
1228 * @scmi_requested_devices, then a matching device is created for each already
1229 * active SCMI instance. (if any)
1230 *
1231 * This way the requested device is created straight-away for all the already
1232 * initialized(probed) SCMI instances (handles) and it remains also annotated
1233 * as pending creation if the requesting SCMI driver was loaded before some
1234 * SCMI instance and related transports were available: when such late instance
1235 * is probed, its probe will take care to scan the list of pending requested
1236 * devices and create those on its own (see @scmi_create_protocol_devices and
1237 * its enclosing loop)
1238 *
1239 * Return: 0 on Success
1240 */
1241int scmi_protocol_device_request(const struct scmi_device_id *id_table)
1242{
1243        int ret = 0;
1244        unsigned int id = 0;
1245        struct list_head *head, *phead = NULL;
1246        struct scmi_requested_dev *rdev;
1247        struct scmi_info *info;
1248
1249        pr_debug("Requesting SCMI device (%s) for protocol %x\n",
1250                 id_table->name, id_table->protocol_id);
1251
1252        /*
1253         * Search for the matching protocol rdev list and then search
1254         * of any existent equally named device...fails if any duplicate found.
1255         */
1256        mutex_lock(&scmi_requested_devices_mtx);
1257        idr_for_each_entry(&scmi_requested_devices, head, id) {
1258                if (!phead) {
1259                        /* A list found registered in the IDR is never empty */
1260                        rdev = list_first_entry(head, struct scmi_requested_dev,
1261                                                node);
1262                        if (rdev->id_table->protocol_id ==
1263                            id_table->protocol_id)
1264                                phead = head;
1265                }
1266                list_for_each_entry(rdev, head, node) {
1267                        if (!strcmp(rdev->id_table->name, id_table->name)) {
1268                                pr_err("Ignoring duplicate request [%d] %s\n",
1269                                       rdev->id_table->protocol_id,
1270                                       rdev->id_table->name);
1271                                ret = -EINVAL;
1272                                goto out;
1273                        }
1274                }
1275        }
1276
1277        /*
1278         * No duplicate found for requested id_table, so let's create a new
1279         * requested device entry for this new valid request.
1280         */
1281        rdev = kzalloc(sizeof(*rdev), GFP_KERNEL);
1282        if (!rdev) {
1283                ret = -ENOMEM;
1284                goto out;
1285        }
1286        rdev->id_table = id_table;
1287
1288        /*
1289         * Append the new requested device table descriptor to the head of the
1290         * related protocol list, eventually creating such head if not already
1291         * there.
1292         */
1293        if (!phead) {
1294                phead = kzalloc(sizeof(*phead), GFP_KERNEL);
1295                if (!phead) {
1296                        kfree(rdev);
1297                        ret = -ENOMEM;
1298                        goto out;
1299                }
1300                INIT_LIST_HEAD(phead);
1301
1302                ret = idr_alloc(&scmi_requested_devices, (void *)phead,
1303                                id_table->protocol_id,
1304                                id_table->protocol_id + 1, GFP_KERNEL);
1305                if (ret != id_table->protocol_id) {
1306                        pr_err("Failed to save SCMI device - ret:%d\n", ret);
1307                        kfree(rdev);
1308                        kfree(phead);
1309                        ret = -EINVAL;
1310                        goto out;
1311                }
1312                ret = 0;
1313        }
1314        list_add(&rdev->node, phead);
1315
1316        /*
1317         * Now effectively create and initialize the requested device for every
1318         * already initialized SCMI instance which has registered the requested
1319         * protocol as a valid active one: i.e. defined in DT and supported by
1320         * current platform FW.
1321         */
1322        mutex_lock(&scmi_list_mutex);
1323        list_for_each_entry(info, &scmi_list, node) {
1324                struct device_node *child;
1325
1326                child = idr_find(&info->active_protocols,
1327                                 id_table->protocol_id);
1328                if (child) {
1329                        struct scmi_device *sdev;
1330
1331                        sdev = scmi_get_protocol_device(child, info,
1332                                                        id_table->protocol_id,
1333                                                        id_table->name);
1334                        /* Set handle if not already set: device existed */
1335                        if (sdev && !sdev->handle)
1336                                sdev->handle =
1337                                        scmi_handle_get_from_info_unlocked(info);
1338                } else {
1339                        dev_err(info->dev,
1340                                "Failed. SCMI protocol %d not active.\n",
1341                                id_table->protocol_id);
1342                }
1343        }
1344        mutex_unlock(&scmi_list_mutex);
1345
1346out:
1347        mutex_unlock(&scmi_requested_devices_mtx);
1348
1349        return ret;
1350}
1351
1352/**
1353 * scmi_protocol_device_unrequest  - Helper to unrequest a device
1354 *
1355 * @id_table: A protocol/name pair descriptor for the device to be unrequested.
1356 *
1357 * An helper to let an SCMI driver release its request about devices; note that
1358 * devices are created and initialized once the first SCMI driver request them
1359 * but they destroyed only on SCMI core unloading/unbinding.
1360 *
1361 * The current SCMI transport layer uses such devices as internal references and
1362 * as such they could be shared as same transport between multiple drivers so
1363 * that cannot be safely destroyed till the whole SCMI stack is removed.
1364 * (unless adding further burden of refcounting.)
1365 */
1366void scmi_protocol_device_unrequest(const struct scmi_device_id *id_table)
1367{
1368        struct list_head *phead;
1369
1370        pr_debug("Unrequesting SCMI device (%s) for protocol %x\n",
1371                 id_table->name, id_table->protocol_id);
1372
1373        mutex_lock(&scmi_requested_devices_mtx);
1374        phead = idr_find(&scmi_requested_devices, id_table->protocol_id);
1375        if (phead) {
1376                struct scmi_requested_dev *victim, *tmp;
1377
1378                list_for_each_entry_safe(victim, tmp, phead, node) {
1379                        if (!strcmp(victim->id_table->name, id_table->name)) {
1380                                list_del(&victim->node);
1381                                kfree(victim);
1382                                break;
1383                        }
1384                }
1385
1386                if (list_empty(phead)) {
1387                        idr_remove(&scmi_requested_devices,
1388                                   id_table->protocol_id);
1389                        kfree(phead);
1390                }
1391        }
1392        mutex_unlock(&scmi_requested_devices_mtx);
1393}
1394
1395static int scmi_probe(struct platform_device *pdev)
1396{
1397        int ret;
1398        struct scmi_handle *handle;
1399        const struct scmi_desc *desc;
1400        struct scmi_info *info;
1401        struct device *dev = &pdev->dev;
1402        struct device_node *child, *np = dev->of_node;
1403
1404        desc = of_device_get_match_data(dev);
1405        if (!desc)
1406                return -EINVAL;
1407
1408        info = devm_kzalloc(dev, sizeof(*info), GFP_KERNEL);
1409        if (!info)
1410                return -ENOMEM;
1411
1412        info->dev = dev;
1413        info->desc = desc;
1414        INIT_LIST_HEAD(&info->node);
1415        idr_init(&info->protocols);
1416        mutex_init(&info->protocols_mtx);
1417        idr_init(&info->active_protocols);
1418
1419        platform_set_drvdata(pdev, info);
1420        idr_init(&info->tx_idr);
1421        idr_init(&info->rx_idr);
1422
1423        handle = &info->handle;
1424        handle->dev = info->dev;
1425        handle->version = &info->version;
1426        handle->devm_protocol_get = scmi_devm_protocol_get;
1427        handle->devm_protocol_put = scmi_devm_protocol_put;
1428
1429        ret = scmi_txrx_setup(info, dev, SCMI_PROTOCOL_BASE);
1430        if (ret)
1431                return ret;
1432
1433        ret = scmi_xfer_info_init(info);
1434        if (ret)
1435                return ret;
1436
1437        if (scmi_notification_init(handle))
1438                dev_err(dev, "SCMI Notifications NOT available.\n");
1439
1440        /*
1441         * Trigger SCMI Base protocol initialization.
1442         * It's mandatory and won't be ever released/deinit until the
1443         * SCMI stack is shutdown/unloaded as a whole.
1444         */
1445        ret = scmi_protocol_acquire(handle, SCMI_PROTOCOL_BASE);
1446        if (ret) {
1447                dev_err(dev, "unable to communicate with SCMI\n");
1448                return ret;
1449        }
1450
1451        mutex_lock(&scmi_list_mutex);
1452        list_add_tail(&info->node, &scmi_list);
1453        mutex_unlock(&scmi_list_mutex);
1454
1455        for_each_available_child_of_node(np, child) {
1456                u32 prot_id;
1457
1458                if (of_property_read_u32(child, "reg", &prot_id))
1459                        continue;
1460
1461                if (!FIELD_FIT(MSG_PROTOCOL_ID_MASK, prot_id))
1462                        dev_err(dev, "Out of range protocol %d\n", prot_id);
1463
1464                if (!scmi_is_protocol_implemented(handle, prot_id)) {
1465                        dev_err(dev, "SCMI protocol %d not implemented\n",
1466                                prot_id);
1467                        continue;
1468                }
1469
1470                /*
1471                 * Save this valid DT protocol descriptor amongst
1472                 * @active_protocols for this SCMI instance/
1473                 */
1474                ret = idr_alloc(&info->active_protocols, child,
1475                                prot_id, prot_id + 1, GFP_KERNEL);
1476                if (ret != prot_id) {
1477                        dev_err(dev, "SCMI protocol %d already activated. Skip\n",
1478                                prot_id);
1479                        continue;
1480                }
1481
1482                of_node_get(child);
1483                scmi_create_protocol_devices(child, info, prot_id);
1484        }
1485
1486        return 0;
1487}
1488
1489void scmi_free_channel(struct scmi_chan_info *cinfo, struct idr *idr, int id)
1490{
1491        idr_remove(idr, id);
1492}
1493
1494static int scmi_remove(struct platform_device *pdev)
1495{
1496        int ret = 0, id;
1497        struct scmi_info *info = platform_get_drvdata(pdev);
1498        struct idr *idr = &info->tx_idr;
1499        struct device_node *child;
1500
1501        mutex_lock(&scmi_list_mutex);
1502        if (info->users)
1503                ret = -EBUSY;
1504        else
1505                list_del(&info->node);
1506        mutex_unlock(&scmi_list_mutex);
1507
1508        if (ret)
1509                return ret;
1510
1511        scmi_notification_exit(&info->handle);
1512
1513        mutex_lock(&info->protocols_mtx);
1514        idr_destroy(&info->protocols);
1515        mutex_unlock(&info->protocols_mtx);
1516
1517        idr_for_each_entry(&info->active_protocols, child, id)
1518                of_node_put(child);
1519        idr_destroy(&info->active_protocols);
1520
1521        /* Safe to free channels since no more users */
1522        ret = idr_for_each(idr, info->desc->ops->chan_free, idr);
1523        idr_destroy(&info->tx_idr);
1524
1525        idr = &info->rx_idr;
1526        ret = idr_for_each(idr, info->desc->ops->chan_free, idr);
1527        idr_destroy(&info->rx_idr);
1528
1529        return ret;
1530}
1531
1532static ssize_t protocol_version_show(struct device *dev,
1533                                     struct device_attribute *attr, char *buf)
1534{
1535        struct scmi_info *info = dev_get_drvdata(dev);
1536
1537        return sprintf(buf, "%u.%u\n", info->version.major_ver,
1538                       info->version.minor_ver);
1539}
1540static DEVICE_ATTR_RO(protocol_version);
1541
1542static ssize_t firmware_version_show(struct device *dev,
1543                                     struct device_attribute *attr, char *buf)
1544{
1545        struct scmi_info *info = dev_get_drvdata(dev);
1546
1547        return sprintf(buf, "0x%x\n", info->version.impl_ver);
1548}
1549static DEVICE_ATTR_RO(firmware_version);
1550
1551static ssize_t vendor_id_show(struct device *dev,
1552                              struct device_attribute *attr, char *buf)
1553{
1554        struct scmi_info *info = dev_get_drvdata(dev);
1555
1556        return sprintf(buf, "%s\n", info->version.vendor_id);
1557}
1558static DEVICE_ATTR_RO(vendor_id);
1559
1560static ssize_t sub_vendor_id_show(struct device *dev,
1561                                  struct device_attribute *attr, char *buf)
1562{
1563        struct scmi_info *info = dev_get_drvdata(dev);
1564
1565        return sprintf(buf, "%s\n", info->version.sub_vendor_id);
1566}
1567static DEVICE_ATTR_RO(sub_vendor_id);
1568
1569static struct attribute *versions_attrs[] = {
1570        &dev_attr_firmware_version.attr,
1571        &dev_attr_protocol_version.attr,
1572        &dev_attr_vendor_id.attr,
1573        &dev_attr_sub_vendor_id.attr,
1574        NULL,
1575};
1576ATTRIBUTE_GROUPS(versions);
1577
1578/* Each compatible listed below must have descriptor associated with it */
1579static const struct of_device_id scmi_of_match[] = {
1580#ifdef CONFIG_MAILBOX
1581        { .compatible = "arm,scmi", .data = &scmi_mailbox_desc },
1582#endif
1583#ifdef CONFIG_HAVE_ARM_SMCCC_DISCOVERY
1584        { .compatible = "arm,scmi-smc", .data = &scmi_smc_desc},
1585#endif
1586        { /* Sentinel */ },
1587};
1588
1589MODULE_DEVICE_TABLE(of, scmi_of_match);
1590
1591static struct platform_driver scmi_driver = {
1592        .driver = {
1593                   .name = "arm-scmi",
1594                   .of_match_table = scmi_of_match,
1595                   .dev_groups = versions_groups,
1596                   },
1597        .probe = scmi_probe,
1598        .remove = scmi_remove,
1599};
1600
1601static int __init scmi_driver_init(void)
1602{
1603        scmi_bus_init();
1604
1605        scmi_base_register();
1606
1607        scmi_clock_register();
1608        scmi_perf_register();
1609        scmi_power_register();
1610        scmi_reset_register();
1611        scmi_sensors_register();
1612        scmi_voltage_register();
1613        scmi_system_register();
1614
1615        return platform_driver_register(&scmi_driver);
1616}
1617subsys_initcall(scmi_driver_init);
1618
1619static void __exit scmi_driver_exit(void)
1620{
1621        scmi_base_unregister();
1622
1623        scmi_clock_unregister();
1624        scmi_perf_unregister();
1625        scmi_power_unregister();
1626        scmi_reset_unregister();
1627        scmi_sensors_unregister();
1628        scmi_voltage_unregister();
1629        scmi_system_unregister();
1630
1631        scmi_bus_exit();
1632
1633        platform_driver_unregister(&scmi_driver);
1634}
1635module_exit(scmi_driver_exit);
1636
1637MODULE_ALIAS("platform: arm-scmi");
1638MODULE_AUTHOR("Sudeep Holla <sudeep.holla@arm.com>");
1639MODULE_DESCRIPTION("ARM SCMI protocol driver");
1640MODULE_LICENSE("GPL v2");
1641