linux/drivers/mmc/core/block.c
<<
>>
Prefs
   1/*
   2 * Block driver for media (i.e., flash cards)
   3 *
   4 * Copyright 2002 Hewlett-Packard Company
   5 * Copyright 2005-2008 Pierre Ossman
   6 *
   7 * Use consistent with the GNU GPL is permitted,
   8 * provided that this copyright notice is
   9 * preserved in its entirety in all copies and derived works.
  10 *
  11 * HEWLETT-PACKARD COMPANY MAKES NO WARRANTIES, EXPRESSED OR IMPLIED,
  12 * AS TO THE USEFULNESS OR CORRECTNESS OF THIS CODE OR ITS
  13 * FITNESS FOR ANY PARTICULAR PURPOSE.
  14 *
  15 * Many thanks to Alessandro Rubini and Jonathan Corbet!
  16 *
  17 * Author:  Andrew Christian
  18 *          28 May 2002
  19 */
  20#include <linux/moduleparam.h>
  21#include <linux/module.h>
  22#include <linux/init.h>
  23
  24#include <linux/kernel.h>
  25#include <linux/fs.h>
  26#include <linux/slab.h>
  27#include <linux/errno.h>
  28#include <linux/hdreg.h>
  29#include <linux/kdev_t.h>
  30#include <linux/blkdev.h>
  31#include <linux/cdev.h>
  32#include <linux/mutex.h>
  33#include <linux/scatterlist.h>
  34#include <linux/string_helpers.h>
  35#include <linux/delay.h>
  36#include <linux/capability.h>
  37#include <linux/compat.h>
  38#include <linux/pm_runtime.h>
  39#include <linux/idr.h>
  40#include <linux/debugfs.h>
  41
  42#include <linux/mmc/ioctl.h>
  43#include <linux/mmc/card.h>
  44#include <linux/mmc/host.h>
  45#include <linux/mmc/mmc.h>
  46#include <linux/mmc/sd.h>
  47
  48#include <linux/uaccess.h>
  49
  50#include "queue.h"
  51#include "block.h"
  52#include "core.h"
  53#include "card.h"
  54#include "host.h"
  55#include "bus.h"
  56#include "mmc_ops.h"
  57#include "quirks.h"
  58#include "sd_ops.h"
  59
  60MODULE_ALIAS("mmc:block");
  61#ifdef MODULE_PARAM_PREFIX
  62#undef MODULE_PARAM_PREFIX
  63#endif
  64#define MODULE_PARAM_PREFIX "mmcblk."
  65
  66/*
  67 * Set a 10 second timeout for polling write request busy state. Note, mmc core
  68 * is setting a 3 second timeout for SD cards, and SDHCI has long had a 10
  69 * second software timer to timeout the whole request, so 10 seconds should be
  70 * ample.
  71 */
  72#define MMC_BLK_TIMEOUT_MS  (10 * 1000)
  73#define MMC_SANITIZE_REQ_TIMEOUT 240000
  74#define MMC_EXTRACT_INDEX_FROM_ARG(x) ((x & 0x00FF0000) >> 16)
  75#define MMC_EXTRACT_VALUE_FROM_ARG(x) ((x & 0x0000FF00) >> 8)
  76
  77#define mmc_req_rel_wr(req)     ((req->cmd_flags & REQ_FUA) && \
  78                                  (rq_data_dir(req) == WRITE))
  79static DEFINE_MUTEX(block_mutex);
  80
  81/*
  82 * The defaults come from config options but can be overriden by module
  83 * or bootarg options.
  84 */
  85static int perdev_minors = CONFIG_MMC_BLOCK_MINORS;
  86
  87/*
  88 * We've only got one major, so number of mmcblk devices is
  89 * limited to (1 << 20) / number of minors per device.  It is also
  90 * limited by the MAX_DEVICES below.
  91 */
  92static int max_devices;
  93
  94#define MAX_DEVICES 256
  95
  96static DEFINE_IDA(mmc_blk_ida);
  97static DEFINE_IDA(mmc_rpmb_ida);
  98
  99/*
 100 * There is one mmc_blk_data per slot.
 101 */
 102struct mmc_blk_data {
 103        struct device   *parent;
 104        struct gendisk  *disk;
 105        struct mmc_queue queue;
 106        struct list_head part;
 107        struct list_head rpmbs;
 108
 109        unsigned int    flags;
 110#define MMC_BLK_CMD23   (1 << 0)        /* Can do SET_BLOCK_COUNT for multiblock */
 111#define MMC_BLK_REL_WR  (1 << 1)        /* MMC Reliable write support */
 112
 113        unsigned int    usage;
 114        unsigned int    read_only;
 115        unsigned int    part_type;
 116        unsigned int    reset_done;
 117#define MMC_BLK_READ            BIT(0)
 118#define MMC_BLK_WRITE           BIT(1)
 119#define MMC_BLK_DISCARD         BIT(2)
 120#define MMC_BLK_SECDISCARD      BIT(3)
 121#define MMC_BLK_CQE_RECOVERY    BIT(4)
 122
 123        /*
 124         * Only set in main mmc_blk_data associated
 125         * with mmc_card with dev_set_drvdata, and keeps
 126         * track of the current selected device partition.
 127         */
 128        unsigned int    part_curr;
 129        struct device_attribute force_ro;
 130        struct device_attribute power_ro_lock;
 131        int     area_type;
 132
 133        /* debugfs files (only in main mmc_blk_data) */
 134        struct dentry *status_dentry;
 135        struct dentry *ext_csd_dentry;
 136};
 137
 138/* Device type for RPMB character devices */
 139static dev_t mmc_rpmb_devt;
 140
 141/* Bus type for RPMB character devices */
 142static struct bus_type mmc_rpmb_bus_type = {
 143        .name = "mmc_rpmb",
 144};
 145
 146/**
 147 * struct mmc_rpmb_data - special RPMB device type for these areas
 148 * @dev: the device for the RPMB area
 149 * @chrdev: character device for the RPMB area
 150 * @id: unique device ID number
 151 * @part_index: partition index (0 on first)
 152 * @md: parent MMC block device
 153 * @node: list item, so we can put this device on a list
 154 */
 155struct mmc_rpmb_data {
 156        struct device dev;
 157        struct cdev chrdev;
 158        int id;
 159        unsigned int part_index;
 160        struct mmc_blk_data *md;
 161        struct list_head node;
 162};
 163
 164static DEFINE_MUTEX(open_lock);
 165
 166module_param(perdev_minors, int, 0444);
 167MODULE_PARM_DESC(perdev_minors, "Minors numbers to allocate per device");
 168
 169static inline int mmc_blk_part_switch(struct mmc_card *card,
 170                                      unsigned int part_type);
 171
 172static struct mmc_blk_data *mmc_blk_get(struct gendisk *disk)
 173{
 174        struct mmc_blk_data *md;
 175
 176        mutex_lock(&open_lock);
 177        md = disk->private_data;
 178        if (md && md->usage == 0)
 179                md = NULL;
 180        if (md)
 181                md->usage++;
 182        mutex_unlock(&open_lock);
 183
 184        return md;
 185}
 186
 187static inline int mmc_get_devidx(struct gendisk *disk)
 188{
 189        int devidx = disk->first_minor / perdev_minors;
 190        return devidx;
 191}
 192
 193static void mmc_blk_put(struct mmc_blk_data *md)
 194{
 195        mutex_lock(&open_lock);
 196        md->usage--;
 197        if (md->usage == 0) {
 198                int devidx = mmc_get_devidx(md->disk);
 199                blk_put_queue(md->queue.queue);
 200                ida_simple_remove(&mmc_blk_ida, devidx);
 201                put_disk(md->disk);
 202                kfree(md);
 203        }
 204        mutex_unlock(&open_lock);
 205}
 206
 207static ssize_t power_ro_lock_show(struct device *dev,
 208                struct device_attribute *attr, char *buf)
 209{
 210        int ret;
 211        struct mmc_blk_data *md = mmc_blk_get(dev_to_disk(dev));
 212        struct mmc_card *card = md->queue.card;
 213        int locked = 0;
 214
 215        if (card->ext_csd.boot_ro_lock & EXT_CSD_BOOT_WP_B_PERM_WP_EN)
 216                locked = 2;
 217        else if (card->ext_csd.boot_ro_lock & EXT_CSD_BOOT_WP_B_PWR_WP_EN)
 218                locked = 1;
 219
 220        ret = snprintf(buf, PAGE_SIZE, "%d\n", locked);
 221
 222        mmc_blk_put(md);
 223
 224        return ret;
 225}
 226
 227static ssize_t power_ro_lock_store(struct device *dev,
 228                struct device_attribute *attr, const char *buf, size_t count)
 229{
 230        int ret;
 231        struct mmc_blk_data *md, *part_md;
 232        struct mmc_queue *mq;
 233        struct request *req;
 234        unsigned long set;
 235
 236        if (kstrtoul(buf, 0, &set))
 237                return -EINVAL;
 238
 239        if (set != 1)
 240                return count;
 241
 242        md = mmc_blk_get(dev_to_disk(dev));
 243        mq = &md->queue;
 244
 245        /* Dispatch locking to the block layer */
 246        req = blk_get_request(mq->queue, REQ_OP_DRV_OUT, 0);
 247        if (IS_ERR(req)) {
 248                count = PTR_ERR(req);
 249                goto out_put;
 250        }
 251        req_to_mmc_queue_req(req)->drv_op = MMC_DRV_OP_BOOT_WP;
 252        blk_execute_rq(mq->queue, NULL, req, 0);
 253        ret = req_to_mmc_queue_req(req)->drv_op_result;
 254        blk_put_request(req);
 255
 256        if (!ret) {
 257                pr_info("%s: Locking boot partition ro until next power on\n",
 258                        md->disk->disk_name);
 259                set_disk_ro(md->disk, 1);
 260
 261                list_for_each_entry(part_md, &md->part, part)
 262                        if (part_md->area_type == MMC_BLK_DATA_AREA_BOOT) {
 263                                pr_info("%s: Locking boot partition ro until next power on\n", part_md->disk->disk_name);
 264                                set_disk_ro(part_md->disk, 1);
 265                        }
 266        }
 267out_put:
 268        mmc_blk_put(md);
 269        return count;
 270}
 271
 272static ssize_t force_ro_show(struct device *dev, struct device_attribute *attr,
 273                             char *buf)
 274{
 275        int ret;
 276        struct mmc_blk_data *md = mmc_blk_get(dev_to_disk(dev));
 277
 278        ret = snprintf(buf, PAGE_SIZE, "%d\n",
 279                       get_disk_ro(dev_to_disk(dev)) ^
 280                       md->read_only);
 281        mmc_blk_put(md);
 282        return ret;
 283}
 284
 285static ssize_t force_ro_store(struct device *dev, struct device_attribute *attr,
 286                              const char *buf, size_t count)
 287{
 288        int ret;
 289        char *end;
 290        struct mmc_blk_data *md = mmc_blk_get(dev_to_disk(dev));
 291        unsigned long set = simple_strtoul(buf, &end, 0);
 292        if (end == buf) {
 293                ret = -EINVAL;
 294                goto out;
 295        }
 296
 297        set_disk_ro(dev_to_disk(dev), set || md->read_only);
 298        ret = count;
 299out:
 300        mmc_blk_put(md);
 301        return ret;
 302}
 303
 304static int mmc_blk_open(struct block_device *bdev, fmode_t mode)
 305{
 306        struct mmc_blk_data *md = mmc_blk_get(bdev->bd_disk);
 307        int ret = -ENXIO;
 308
 309        mutex_lock(&block_mutex);
 310        if (md) {
 311                if (md->usage == 2)
 312                        check_disk_change(bdev);
 313                ret = 0;
 314
 315                if ((mode & FMODE_WRITE) && md->read_only) {
 316                        mmc_blk_put(md);
 317                        ret = -EROFS;
 318                }
 319        }
 320        mutex_unlock(&block_mutex);
 321
 322        return ret;
 323}
 324
 325static void mmc_blk_release(struct gendisk *disk, fmode_t mode)
 326{
 327        struct mmc_blk_data *md = disk->private_data;
 328
 329        mutex_lock(&block_mutex);
 330        mmc_blk_put(md);
 331        mutex_unlock(&block_mutex);
 332}
 333
 334static int
 335mmc_blk_getgeo(struct block_device *bdev, struct hd_geometry *geo)
 336{
 337        geo->cylinders = get_capacity(bdev->bd_disk) / (4 * 16);
 338        geo->heads = 4;
 339        geo->sectors = 16;
 340        return 0;
 341}
 342
 343struct mmc_blk_ioc_data {
 344        struct mmc_ioc_cmd ic;
 345        unsigned char *buf;
 346        u64 buf_bytes;
 347        struct mmc_rpmb_data *rpmb;
 348};
 349
 350static struct mmc_blk_ioc_data *mmc_blk_ioctl_copy_from_user(
 351        struct mmc_ioc_cmd __user *user)
 352{
 353        struct mmc_blk_ioc_data *idata;
 354        int err;
 355
 356        idata = kmalloc(sizeof(*idata), GFP_KERNEL);
 357        if (!idata) {
 358                err = -ENOMEM;
 359                goto out;
 360        }
 361
 362        if (copy_from_user(&idata->ic, user, sizeof(idata->ic))) {
 363                err = -EFAULT;
 364                goto idata_err;
 365        }
 366
 367        idata->buf_bytes = (u64) idata->ic.blksz * idata->ic.blocks;
 368        if (idata->buf_bytes > MMC_IOC_MAX_BYTES) {
 369                err = -EOVERFLOW;
 370                goto idata_err;
 371        }
 372
 373        if (!idata->buf_bytes) {
 374                idata->buf = NULL;
 375                return idata;
 376        }
 377
 378        idata->buf = memdup_user((void __user *)(unsigned long)
 379                                 idata->ic.data_ptr, idata->buf_bytes);
 380        if (IS_ERR(idata->buf)) {
 381                err = PTR_ERR(idata->buf);
 382                goto idata_err;
 383        }
 384
 385        return idata;
 386
 387idata_err:
 388        kfree(idata);
 389out:
 390        return ERR_PTR(err);
 391}
 392
 393static int mmc_blk_ioctl_copy_to_user(struct mmc_ioc_cmd __user *ic_ptr,
 394                                      struct mmc_blk_ioc_data *idata)
 395{
 396        struct mmc_ioc_cmd *ic = &idata->ic;
 397
 398        if (copy_to_user(&(ic_ptr->response), ic->response,
 399                         sizeof(ic->response)))
 400                return -EFAULT;
 401
 402        if (!idata->ic.write_flag) {
 403                if (copy_to_user((void __user *)(unsigned long)ic->data_ptr,
 404                                 idata->buf, idata->buf_bytes))
 405                        return -EFAULT;
 406        }
 407
 408        return 0;
 409}
 410
 411static int ioctl_rpmb_card_status_poll(struct mmc_card *card, u32 *status,
 412                                       u32 retries_max)
 413{
 414        int err;
 415        u32 retry_count = 0;
 416
 417        if (!status || !retries_max)
 418                return -EINVAL;
 419
 420        do {
 421                err = __mmc_send_status(card, status, 5);
 422                if (err)
 423                        break;
 424
 425                if (!R1_STATUS(*status) &&
 426                                (R1_CURRENT_STATE(*status) != R1_STATE_PRG))
 427                        break; /* RPMB programming operation complete */
 428
 429                /*
 430                 * Rechedule to give the MMC device a chance to continue
 431                 * processing the previous command without being polled too
 432                 * frequently.
 433                 */
 434                usleep_range(1000, 5000);
 435        } while (++retry_count < retries_max);
 436
 437        if (retry_count == retries_max)
 438                err = -EPERM;
 439
 440        return err;
 441}
 442
 443static int ioctl_do_sanitize(struct mmc_card *card)
 444{
 445        int err;
 446
 447        if (!mmc_can_sanitize(card)) {
 448                        pr_warn("%s: %s - SANITIZE is not supported\n",
 449                                mmc_hostname(card->host), __func__);
 450                        err = -EOPNOTSUPP;
 451                        goto out;
 452        }
 453
 454        pr_debug("%s: %s - SANITIZE IN PROGRESS...\n",
 455                mmc_hostname(card->host), __func__);
 456
 457        err = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL,
 458                                        EXT_CSD_SANITIZE_START, 1,
 459                                        MMC_SANITIZE_REQ_TIMEOUT);
 460
 461        if (err)
 462                pr_err("%s: %s - EXT_CSD_SANITIZE_START failed. err=%d\n",
 463                       mmc_hostname(card->host), __func__, err);
 464
 465        pr_debug("%s: %s - SANITIZE COMPLETED\n", mmc_hostname(card->host),
 466                                             __func__);
 467out:
 468        return err;
 469}
 470
 471static int __mmc_blk_ioctl_cmd(struct mmc_card *card, struct mmc_blk_data *md,
 472                               struct mmc_blk_ioc_data *idata)
 473{
 474        struct mmc_command cmd = {};
 475        struct mmc_data data = {};
 476        struct mmc_request mrq = {};
 477        struct scatterlist sg;
 478        int err;
 479        unsigned int target_part;
 480        u32 status = 0;
 481
 482        if (!card || !md || !idata)
 483                return -EINVAL;
 484
 485        /*
 486         * The RPMB accesses comes in from the character device, so we
 487         * need to target these explicitly. Else we just target the
 488         * partition type for the block device the ioctl() was issued
 489         * on.
 490         */
 491        if (idata->rpmb) {
 492                /* Support multiple RPMB partitions */
 493                target_part = idata->rpmb->part_index;
 494                target_part |= EXT_CSD_PART_CONFIG_ACC_RPMB;
 495        } else {
 496                target_part = md->part_type;
 497        }
 498
 499        cmd.opcode = idata->ic.opcode;
 500        cmd.arg = idata->ic.arg;
 501        cmd.flags = idata->ic.flags;
 502
 503        if (idata->buf_bytes) {
 504                data.sg = &sg;
 505                data.sg_len = 1;
 506                data.blksz = idata->ic.blksz;
 507                data.blocks = idata->ic.blocks;
 508
 509                sg_init_one(data.sg, idata->buf, idata->buf_bytes);
 510
 511                if (idata->ic.write_flag)
 512                        data.flags = MMC_DATA_WRITE;
 513                else
 514                        data.flags = MMC_DATA_READ;
 515
 516                /* data.flags must already be set before doing this. */
 517                mmc_set_data_timeout(&data, card);
 518
 519                /* Allow overriding the timeout_ns for empirical tuning. */
 520                if (idata->ic.data_timeout_ns)
 521                        data.timeout_ns = idata->ic.data_timeout_ns;
 522
 523                if ((cmd.flags & MMC_RSP_R1B) == MMC_RSP_R1B) {
 524                        /*
 525                         * Pretend this is a data transfer and rely on the
 526                         * host driver to compute timeout.  When all host
 527                         * drivers support cmd.cmd_timeout for R1B, this
 528                         * can be changed to:
 529                         *
 530                         *     mrq.data = NULL;
 531                         *     cmd.cmd_timeout = idata->ic.cmd_timeout_ms;
 532                         */
 533                        data.timeout_ns = idata->ic.cmd_timeout_ms * 1000000;
 534                }
 535
 536                mrq.data = &data;
 537        }
 538
 539        mrq.cmd = &cmd;
 540
 541        err = mmc_blk_part_switch(card, target_part);
 542        if (err)
 543                return err;
 544
 545        if (idata->ic.is_acmd) {
 546                err = mmc_app_cmd(card->host, card);
 547                if (err)
 548                        return err;
 549        }
 550
 551        if (idata->rpmb) {
 552                err = mmc_set_blockcount(card, data.blocks,
 553                        idata->ic.write_flag & (1 << 31));
 554                if (err)
 555                        return err;
 556        }
 557
 558        if ((MMC_EXTRACT_INDEX_FROM_ARG(cmd.arg) == EXT_CSD_SANITIZE_START) &&
 559            (cmd.opcode == MMC_SWITCH)) {
 560                err = ioctl_do_sanitize(card);
 561
 562                if (err)
 563                        pr_err("%s: ioctl_do_sanitize() failed. err = %d",
 564                               __func__, err);
 565
 566                return err;
 567        }
 568
 569        mmc_wait_for_req(card->host, &mrq);
 570
 571        if (cmd.error) {
 572                dev_err(mmc_dev(card->host), "%s: cmd error %d\n",
 573                                                __func__, cmd.error);
 574                return cmd.error;
 575        }
 576        if (data.error) {
 577                dev_err(mmc_dev(card->host), "%s: data error %d\n",
 578                                                __func__, data.error);
 579                return data.error;
 580        }
 581
 582        /*
 583         * Make sure the cache of the PARTITION_CONFIG register and
 584         * PARTITION_ACCESS bits is updated in case the ioctl ext_csd write
 585         * changed it successfully.
 586         */
 587        if ((MMC_EXTRACT_INDEX_FROM_ARG(cmd.arg) == EXT_CSD_PART_CONFIG) &&
 588            (cmd.opcode == MMC_SWITCH)) {
 589                struct mmc_blk_data *main_md = dev_get_drvdata(&card->dev);
 590                u8 value = MMC_EXTRACT_VALUE_FROM_ARG(cmd.arg);
 591
 592                /*
 593                 * Update cache so the next mmc_blk_part_switch call operates
 594                 * on up-to-date data.
 595                 */
 596                card->ext_csd.part_config = value;
 597                main_md->part_curr = value & EXT_CSD_PART_CONFIG_ACC_MASK;
 598        }
 599
 600        /*
 601         * According to the SD specs, some commands require a delay after
 602         * issuing the command.
 603         */
 604        if (idata->ic.postsleep_min_us)
 605                usleep_range(idata->ic.postsleep_min_us, idata->ic.postsleep_max_us);
 606
 607        memcpy(&(idata->ic.response), cmd.resp, sizeof(cmd.resp));
 608
 609        if (idata->rpmb) {
 610                /*
 611                 * Ensure RPMB command has completed by polling CMD13
 612                 * "Send Status".
 613                 */
 614                err = ioctl_rpmb_card_status_poll(card, &status, 5);
 615                if (err)
 616                        dev_err(mmc_dev(card->host),
 617                                        "%s: Card Status=0x%08X, error %d\n",
 618                                        __func__, status, err);
 619        }
 620
 621        return err;
 622}
 623
 624static int mmc_blk_ioctl_cmd(struct mmc_blk_data *md,
 625                             struct mmc_ioc_cmd __user *ic_ptr,
 626                             struct mmc_rpmb_data *rpmb)
 627{
 628        struct mmc_blk_ioc_data *idata;
 629        struct mmc_blk_ioc_data *idatas[1];
 630        struct mmc_queue *mq;
 631        struct mmc_card *card;
 632        int err = 0, ioc_err = 0;
 633        struct request *req;
 634
 635        idata = mmc_blk_ioctl_copy_from_user(ic_ptr);
 636        if (IS_ERR(idata))
 637                return PTR_ERR(idata);
 638        /* This will be NULL on non-RPMB ioctl():s */
 639        idata->rpmb = rpmb;
 640
 641        card = md->queue.card;
 642        if (IS_ERR(card)) {
 643                err = PTR_ERR(card);
 644                goto cmd_done;
 645        }
 646
 647        /*
 648         * Dispatch the ioctl() into the block request queue.
 649         */
 650        mq = &md->queue;
 651        req = blk_get_request(mq->queue,
 652                idata->ic.write_flag ? REQ_OP_DRV_OUT : REQ_OP_DRV_IN, 0);
 653        if (IS_ERR(req)) {
 654                err = PTR_ERR(req);
 655                goto cmd_done;
 656        }
 657        idatas[0] = idata;
 658        req_to_mmc_queue_req(req)->drv_op =
 659                rpmb ? MMC_DRV_OP_IOCTL_RPMB : MMC_DRV_OP_IOCTL;
 660        req_to_mmc_queue_req(req)->drv_op_data = idatas;
 661        req_to_mmc_queue_req(req)->ioc_count = 1;
 662        blk_execute_rq(mq->queue, NULL, req, 0);
 663        ioc_err = req_to_mmc_queue_req(req)->drv_op_result;
 664        err = mmc_blk_ioctl_copy_to_user(ic_ptr, idata);
 665        blk_put_request(req);
 666
 667cmd_done:
 668        kfree(idata->buf);
 669        kfree(idata);
 670        return ioc_err ? ioc_err : err;
 671}
 672
 673static int mmc_blk_ioctl_multi_cmd(struct mmc_blk_data *md,
 674                                   struct mmc_ioc_multi_cmd __user *user,
 675                                   struct mmc_rpmb_data *rpmb)
 676{
 677        struct mmc_blk_ioc_data **idata = NULL;
 678        struct mmc_ioc_cmd __user *cmds = user->cmds;
 679        struct mmc_card *card;
 680        struct mmc_queue *mq;
 681        int i, err = 0, ioc_err = 0;
 682        __u64 num_of_cmds;
 683        struct request *req;
 684
 685        if (copy_from_user(&num_of_cmds, &user->num_of_cmds,
 686                           sizeof(num_of_cmds)))
 687                return -EFAULT;
 688
 689        if (!num_of_cmds)
 690                return 0;
 691
 692        if (num_of_cmds > MMC_IOC_MAX_CMDS)
 693                return -EINVAL;
 694
 695        idata = kcalloc(num_of_cmds, sizeof(*idata), GFP_KERNEL);
 696        if (!idata)
 697                return -ENOMEM;
 698
 699        for (i = 0; i < num_of_cmds; i++) {
 700                idata[i] = mmc_blk_ioctl_copy_from_user(&cmds[i]);
 701                if (IS_ERR(idata[i])) {
 702                        err = PTR_ERR(idata[i]);
 703                        num_of_cmds = i;
 704                        goto cmd_err;
 705                }
 706                /* This will be NULL on non-RPMB ioctl():s */
 707                idata[i]->rpmb = rpmb;
 708        }
 709
 710        card = md->queue.card;
 711        if (IS_ERR(card)) {
 712                err = PTR_ERR(card);
 713                goto cmd_err;
 714        }
 715
 716
 717        /*
 718         * Dispatch the ioctl()s into the block request queue.
 719         */
 720        mq = &md->queue;
 721        req = blk_get_request(mq->queue,
 722                idata[0]->ic.write_flag ? REQ_OP_DRV_OUT : REQ_OP_DRV_IN, 0);
 723        if (IS_ERR(req)) {
 724                err = PTR_ERR(req);
 725                goto cmd_err;
 726        }
 727        req_to_mmc_queue_req(req)->drv_op =
 728                rpmb ? MMC_DRV_OP_IOCTL_RPMB : MMC_DRV_OP_IOCTL;
 729        req_to_mmc_queue_req(req)->drv_op_data = idata;
 730        req_to_mmc_queue_req(req)->ioc_count = num_of_cmds;
 731        blk_execute_rq(mq->queue, NULL, req, 0);
 732        ioc_err = req_to_mmc_queue_req(req)->drv_op_result;
 733
 734        /* copy to user if data and response */
 735        for (i = 0; i < num_of_cmds && !err; i++)
 736                err = mmc_blk_ioctl_copy_to_user(&cmds[i], idata[i]);
 737
 738        blk_put_request(req);
 739
 740cmd_err:
 741        for (i = 0; i < num_of_cmds; i++) {
 742                kfree(idata[i]->buf);
 743                kfree(idata[i]);
 744        }
 745        kfree(idata);
 746        return ioc_err ? ioc_err : err;
 747}
 748
 749static int mmc_blk_check_blkdev(struct block_device *bdev)
 750{
 751        /*
 752         * The caller must have CAP_SYS_RAWIO, and must be calling this on the
 753         * whole block device, not on a partition.  This prevents overspray
 754         * between sibling partitions.
 755         */
 756        if ((!capable(CAP_SYS_RAWIO)) || (bdev != bdev->bd_contains))
 757                return -EPERM;
 758        return 0;
 759}
 760
 761static int mmc_blk_ioctl(struct block_device *bdev, fmode_t mode,
 762        unsigned int cmd, unsigned long arg)
 763{
 764        struct mmc_blk_data *md;
 765        int ret;
 766
 767        switch (cmd) {
 768        case MMC_IOC_CMD:
 769                ret = mmc_blk_check_blkdev(bdev);
 770                if (ret)
 771                        return ret;
 772                md = mmc_blk_get(bdev->bd_disk);
 773                if (!md)
 774                        return -EINVAL;
 775                ret = mmc_blk_ioctl_cmd(md,
 776                                        (struct mmc_ioc_cmd __user *)arg,
 777                                        NULL);
 778                mmc_blk_put(md);
 779                return ret;
 780        case MMC_IOC_MULTI_CMD:
 781                ret = mmc_blk_check_blkdev(bdev);
 782                if (ret)
 783                        return ret;
 784                md = mmc_blk_get(bdev->bd_disk);
 785                if (!md)
 786                        return -EINVAL;
 787                ret = mmc_blk_ioctl_multi_cmd(md,
 788                                        (struct mmc_ioc_multi_cmd __user *)arg,
 789                                        NULL);
 790                mmc_blk_put(md);
 791                return ret;
 792        default:
 793                return -EINVAL;
 794        }
 795}
 796
 797#ifdef CONFIG_COMPAT
 798static int mmc_blk_compat_ioctl(struct block_device *bdev, fmode_t mode,
 799        unsigned int cmd, unsigned long arg)
 800{
 801        return mmc_blk_ioctl(bdev, mode, cmd, (unsigned long) compat_ptr(arg));
 802}
 803#endif
 804
 805static const struct block_device_operations mmc_bdops = {
 806        .open                   = mmc_blk_open,
 807        .release                = mmc_blk_release,
 808        .getgeo                 = mmc_blk_getgeo,
 809        .owner                  = THIS_MODULE,
 810        .ioctl                  = mmc_blk_ioctl,
 811#ifdef CONFIG_COMPAT
 812        .compat_ioctl           = mmc_blk_compat_ioctl,
 813#endif
 814};
 815
 816static int mmc_blk_part_switch_pre(struct mmc_card *card,
 817                                   unsigned int part_type)
 818{
 819        int ret = 0;
 820
 821        if (part_type == EXT_CSD_PART_CONFIG_ACC_RPMB) {
 822                if (card->ext_csd.cmdq_en) {
 823                        ret = mmc_cmdq_disable(card);
 824                        if (ret)
 825                                return ret;
 826                }
 827                mmc_retune_pause(card->host);
 828        }
 829
 830        return ret;
 831}
 832
 833static int mmc_blk_part_switch_post(struct mmc_card *card,
 834                                    unsigned int part_type)
 835{
 836        int ret = 0;
 837
 838        if (part_type == EXT_CSD_PART_CONFIG_ACC_RPMB) {
 839                mmc_retune_unpause(card->host);
 840                if (card->reenable_cmdq && !card->ext_csd.cmdq_en)
 841                        ret = mmc_cmdq_enable(card);
 842        }
 843
 844        return ret;
 845}
 846
 847static inline int mmc_blk_part_switch(struct mmc_card *card,
 848                                      unsigned int part_type)
 849{
 850        int ret = 0;
 851        struct mmc_blk_data *main_md = dev_get_drvdata(&card->dev);
 852
 853        if (main_md->part_curr == part_type)
 854                return 0;
 855
 856        if (mmc_card_mmc(card)) {
 857                u8 part_config = card->ext_csd.part_config;
 858
 859                ret = mmc_blk_part_switch_pre(card, part_type);
 860                if (ret)
 861                        return ret;
 862
 863                part_config &= ~EXT_CSD_PART_CONFIG_ACC_MASK;
 864                part_config |= part_type;
 865
 866                ret = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL,
 867                                 EXT_CSD_PART_CONFIG, part_config,
 868                                 card->ext_csd.part_time);
 869                if (ret) {
 870                        mmc_blk_part_switch_post(card, part_type);
 871                        return ret;
 872                }
 873
 874                card->ext_csd.part_config = part_config;
 875
 876                ret = mmc_blk_part_switch_post(card, main_md->part_curr);
 877        }
 878
 879        main_md->part_curr = part_type;
 880        return ret;
 881}
 882
 883static int mmc_sd_num_wr_blocks(struct mmc_card *card, u32 *written_blocks)
 884{
 885        int err;
 886        u32 result;
 887        __be32 *blocks;
 888
 889        struct mmc_request mrq = {};
 890        struct mmc_command cmd = {};
 891        struct mmc_data data = {};
 892
 893        struct scatterlist sg;
 894
 895        cmd.opcode = MMC_APP_CMD;
 896        cmd.arg = card->rca << 16;
 897        cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC;
 898
 899        err = mmc_wait_for_cmd(card->host, &cmd, 0);
 900        if (err)
 901                return err;
 902        if (!mmc_host_is_spi(card->host) && !(cmd.resp[0] & R1_APP_CMD))
 903                return -EIO;
 904
 905        memset(&cmd, 0, sizeof(struct mmc_command));
 906
 907        cmd.opcode = SD_APP_SEND_NUM_WR_BLKS;
 908        cmd.arg = 0;
 909        cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_ADTC;
 910
 911        data.blksz = 4;
 912        data.blocks = 1;
 913        data.flags = MMC_DATA_READ;
 914        data.sg = &sg;
 915        data.sg_len = 1;
 916        mmc_set_data_timeout(&data, card);
 917
 918        mrq.cmd = &cmd;
 919        mrq.data = &data;
 920
 921        blocks = kmalloc(4, GFP_KERNEL);
 922        if (!blocks)
 923                return -ENOMEM;
 924
 925        sg_init_one(&sg, blocks, 4);
 926
 927        mmc_wait_for_req(card->host, &mrq);
 928
 929        result = ntohl(*blocks);
 930        kfree(blocks);
 931
 932        if (cmd.error || data.error)
 933                return -EIO;
 934
 935        *written_blocks = result;
 936
 937        return 0;
 938}
 939
 940static unsigned int mmc_blk_clock_khz(struct mmc_host *host)
 941{
 942        if (host->actual_clock)
 943                return host->actual_clock / 1000;
 944
 945        /* Clock may be subject to a divisor, fudge it by a factor of 2. */
 946        if (host->ios.clock)
 947                return host->ios.clock / 2000;
 948
 949        /* How can there be no clock */
 950        WARN_ON_ONCE(1);
 951        return 100; /* 100 kHz is minimum possible value */
 952}
 953
 954static unsigned int mmc_blk_data_timeout_ms(struct mmc_host *host,
 955                                            struct mmc_data *data)
 956{
 957        unsigned int ms = DIV_ROUND_UP(data->timeout_ns, 1000000);
 958        unsigned int khz;
 959
 960        if (data->timeout_clks) {
 961                khz = mmc_blk_clock_khz(host);
 962                ms += DIV_ROUND_UP(data->timeout_clks, khz);
 963        }
 964
 965        return ms;
 966}
 967
 968static inline bool mmc_blk_in_tran_state(u32 status)
 969{
 970        /*
 971         * Some cards mishandle the status bits, so make sure to check both the
 972         * busy indication and the card state.
 973         */
 974        return status & R1_READY_FOR_DATA &&
 975               (R1_CURRENT_STATE(status) == R1_STATE_TRAN);
 976}
 977
 978static int card_busy_detect(struct mmc_card *card, unsigned int timeout_ms,
 979                            struct request *req, u32 *resp_errs)
 980{
 981        unsigned long timeout = jiffies + msecs_to_jiffies(timeout_ms);
 982        int err = 0;
 983        u32 status;
 984
 985        do {
 986                bool done = time_after(jiffies, timeout);
 987
 988                err = __mmc_send_status(card, &status, 5);
 989                if (err) {
 990                        pr_err("%s: error %d requesting status\n",
 991                               req->rq_disk->disk_name, err);
 992                        return err;
 993                }
 994
 995                /* Accumulate any response error bits seen */
 996                if (resp_errs)
 997                        *resp_errs |= status;
 998
 999                /*
1000                 * Timeout if the device never becomes ready for data and never
1001                 * leaves the program state.
1002                 */
1003                if (done) {
1004                        pr_err("%s: Card stuck in wrong state! %s %s status: %#x\n",
1005                                mmc_hostname(card->host),
1006                                req->rq_disk->disk_name, __func__, status);
1007                        return -ETIMEDOUT;
1008                }
1009
1010                /*
1011                 * Some cards mishandle the status bits,
1012                 * so make sure to check both the busy
1013                 * indication and the card state.
1014                 */
1015        } while (!mmc_blk_in_tran_state(status));
1016
1017        return err;
1018}
1019
1020static int mmc_blk_reset(struct mmc_blk_data *md, struct mmc_host *host,
1021                         int type)
1022{
1023        int err;
1024
1025        if (md->reset_done & type)
1026                return -EEXIST;
1027
1028        md->reset_done |= type;
1029        err = mmc_hw_reset(host);
1030        /* Ensure we switch back to the correct partition */
1031        if (err != -EOPNOTSUPP) {
1032                struct mmc_blk_data *main_md =
1033                        dev_get_drvdata(&host->card->dev);
1034                int part_err;
1035
1036                main_md->part_curr = main_md->part_type;
1037                part_err = mmc_blk_part_switch(host->card, md->part_type);
1038                if (part_err) {
1039                        /*
1040                         * We have failed to get back into the correct
1041                         * partition, so we need to abort the whole request.
1042                         */
1043                        return -ENODEV;
1044                }
1045        }
1046        return err;
1047}
1048
1049static inline void mmc_blk_reset_success(struct mmc_blk_data *md, int type)
1050{
1051        md->reset_done &= ~type;
1052}
1053
1054/*
1055 * The non-block commands come back from the block layer after it queued it and
1056 * processed it with all other requests and then they get issued in this
1057 * function.
1058 */
1059static void mmc_blk_issue_drv_op(struct mmc_queue *mq, struct request *req)
1060{
1061        struct mmc_queue_req *mq_rq;
1062        struct mmc_card *card = mq->card;
1063        struct mmc_blk_data *md = mq->blkdata;
1064        struct mmc_blk_ioc_data **idata;
1065        bool rpmb_ioctl;
1066        u8 **ext_csd;
1067        u32 status;
1068        int ret;
1069        int i;
1070
1071        mq_rq = req_to_mmc_queue_req(req);
1072        rpmb_ioctl = (mq_rq->drv_op == MMC_DRV_OP_IOCTL_RPMB);
1073
1074        switch (mq_rq->drv_op) {
1075        case MMC_DRV_OP_IOCTL:
1076        case MMC_DRV_OP_IOCTL_RPMB:
1077                idata = mq_rq->drv_op_data;
1078                for (i = 0, ret = 0; i < mq_rq->ioc_count; i++) {
1079                        ret = __mmc_blk_ioctl_cmd(card, md, idata[i]);
1080                        if (ret)
1081                                break;
1082                }
1083                /* Always switch back to main area after RPMB access */
1084                if (rpmb_ioctl)
1085                        mmc_blk_part_switch(card, 0);
1086                break;
1087        case MMC_DRV_OP_BOOT_WP:
1088                ret = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL, EXT_CSD_BOOT_WP,
1089                                 card->ext_csd.boot_ro_lock |
1090                                 EXT_CSD_BOOT_WP_B_PWR_WP_EN,
1091                                 card->ext_csd.part_time);
1092                if (ret)
1093                        pr_err("%s: Locking boot partition ro until next power on failed: %d\n",
1094                               md->disk->disk_name, ret);
1095                else
1096                        card->ext_csd.boot_ro_lock |=
1097                                EXT_CSD_BOOT_WP_B_PWR_WP_EN;
1098                break;
1099        case MMC_DRV_OP_GET_CARD_STATUS:
1100                ret = mmc_send_status(card, &status);
1101                if (!ret)
1102                        ret = status;
1103                break;
1104        case MMC_DRV_OP_GET_EXT_CSD:
1105                ext_csd = mq_rq->drv_op_data;
1106                ret = mmc_get_ext_csd(card, ext_csd);
1107                break;
1108        default:
1109                pr_err("%s: unknown driver specific operation\n",
1110                       md->disk->disk_name);
1111                ret = -EINVAL;
1112                break;
1113        }
1114        mq_rq->drv_op_result = ret;
1115        blk_mq_end_request(req, ret ? BLK_STS_IOERR : BLK_STS_OK);
1116}
1117
1118static void mmc_blk_issue_discard_rq(struct mmc_queue *mq, struct request *req)
1119{
1120        struct mmc_blk_data *md = mq->blkdata;
1121        struct mmc_card *card = md->queue.card;
1122        unsigned int from, nr, arg;
1123        int err = 0, type = MMC_BLK_DISCARD;
1124        blk_status_t status = BLK_STS_OK;
1125
1126        if (!mmc_can_erase(card)) {
1127                status = BLK_STS_NOTSUPP;
1128                goto fail;
1129        }
1130
1131        from = blk_rq_pos(req);
1132        nr = blk_rq_sectors(req);
1133
1134        if (mmc_can_discard(card))
1135                arg = MMC_DISCARD_ARG;
1136        else if (mmc_can_trim(card))
1137                arg = MMC_TRIM_ARG;
1138        else
1139                arg = MMC_ERASE_ARG;
1140        do {
1141                err = 0;
1142                if (card->quirks & MMC_QUIRK_INAND_CMD38) {
1143                        err = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL,
1144                                         INAND_CMD38_ARG_EXT_CSD,
1145                                         arg == MMC_TRIM_ARG ?
1146                                         INAND_CMD38_ARG_TRIM :
1147                                         INAND_CMD38_ARG_ERASE,
1148                                         0);
1149                }
1150                if (!err)
1151                        err = mmc_erase(card, from, nr, arg);
1152        } while (err == -EIO && !mmc_blk_reset(md, card->host, type));
1153        if (err)
1154                status = BLK_STS_IOERR;
1155        else
1156                mmc_blk_reset_success(md, type);
1157fail:
1158        blk_mq_end_request(req, status);
1159}
1160
1161static void mmc_blk_issue_secdiscard_rq(struct mmc_queue *mq,
1162                                       struct request *req)
1163{
1164        struct mmc_blk_data *md = mq->blkdata;
1165        struct mmc_card *card = md->queue.card;
1166        unsigned int from, nr, arg;
1167        int err = 0, type = MMC_BLK_SECDISCARD;
1168        blk_status_t status = BLK_STS_OK;
1169
1170        if (!(mmc_can_secure_erase_trim(card))) {
1171                status = BLK_STS_NOTSUPP;
1172                goto out;
1173        }
1174
1175        from = blk_rq_pos(req);
1176        nr = blk_rq_sectors(req);
1177
1178        if (mmc_can_trim(card) && !mmc_erase_group_aligned(card, from, nr))
1179                arg = MMC_SECURE_TRIM1_ARG;
1180        else
1181                arg = MMC_SECURE_ERASE_ARG;
1182
1183retry:
1184        if (card->quirks & MMC_QUIRK_INAND_CMD38) {
1185                err = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL,
1186                                 INAND_CMD38_ARG_EXT_CSD,
1187                                 arg == MMC_SECURE_TRIM1_ARG ?
1188                                 INAND_CMD38_ARG_SECTRIM1 :
1189                                 INAND_CMD38_ARG_SECERASE,
1190                                 0);
1191                if (err)
1192                        goto out_retry;
1193        }
1194
1195        err = mmc_erase(card, from, nr, arg);
1196        if (err == -EIO)
1197                goto out_retry;
1198        if (err) {
1199                status = BLK_STS_IOERR;
1200                goto out;
1201        }
1202
1203        if (arg == MMC_SECURE_TRIM1_ARG) {
1204                if (card->quirks & MMC_QUIRK_INAND_CMD38) {
1205                        err = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL,
1206                                         INAND_CMD38_ARG_EXT_CSD,
1207                                         INAND_CMD38_ARG_SECTRIM2,
1208                                         0);
1209                        if (err)
1210                                goto out_retry;
1211                }
1212
1213                err = mmc_erase(card, from, nr, MMC_SECURE_TRIM2_ARG);
1214                if (err == -EIO)
1215                        goto out_retry;
1216                if (err) {
1217                        status = BLK_STS_IOERR;
1218                        goto out;
1219                }
1220        }
1221
1222out_retry:
1223        if (err && !mmc_blk_reset(md, card->host, type))
1224                goto retry;
1225        if (!err)
1226                mmc_blk_reset_success(md, type);
1227out:
1228        blk_mq_end_request(req, status);
1229}
1230
1231static void mmc_blk_issue_flush(struct mmc_queue *mq, struct request *req)
1232{
1233        struct mmc_blk_data *md = mq->blkdata;
1234        struct mmc_card *card = md->queue.card;
1235        int ret = 0;
1236
1237        ret = mmc_flush_cache(card);
1238        blk_mq_end_request(req, ret ? BLK_STS_IOERR : BLK_STS_OK);
1239}
1240
1241/*
1242 * Reformat current write as a reliable write, supporting
1243 * both legacy and the enhanced reliable write MMC cards.
1244 * In each transfer we'll handle only as much as a single
1245 * reliable write can handle, thus finish the request in
1246 * partial completions.
1247 */
1248static inline void mmc_apply_rel_rw(struct mmc_blk_request *brq,
1249                                    struct mmc_card *card,
1250                                    struct request *req)
1251{
1252        if (!(card->ext_csd.rel_param & EXT_CSD_WR_REL_PARAM_EN)) {
1253                /* Legacy mode imposes restrictions on transfers. */
1254                if (!IS_ALIGNED(blk_rq_pos(req), card->ext_csd.rel_sectors))
1255                        brq->data.blocks = 1;
1256
1257                if (brq->data.blocks > card->ext_csd.rel_sectors)
1258                        brq->data.blocks = card->ext_csd.rel_sectors;
1259                else if (brq->data.blocks < card->ext_csd.rel_sectors)
1260                        brq->data.blocks = 1;
1261        }
1262}
1263
1264#define CMD_ERRORS_EXCL_OOR                                             \
1265        (R1_ADDRESS_ERROR |     /* Misaligned address */                \
1266         R1_BLOCK_LEN_ERROR |   /* Transferred block length incorrect */\
1267         R1_WP_VIOLATION |      /* Tried to write to protected block */ \
1268         R1_CARD_ECC_FAILED |   /* Card ECC failed */                   \
1269         R1_CC_ERROR |          /* Card controller error */             \
1270         R1_ERROR)              /* General/unknown error */
1271
1272#define CMD_ERRORS                                                      \
1273        (CMD_ERRORS_EXCL_OOR |                                          \
1274         R1_OUT_OF_RANGE)       /* Command argument out of range */     \
1275
1276static void mmc_blk_eval_resp_error(struct mmc_blk_request *brq)
1277{
1278        u32 val;
1279
1280        /*
1281         * Per the SD specification(physical layer version 4.10)[1],
1282         * section 4.3.3, it explicitly states that "When the last
1283         * block of user area is read using CMD18, the host should
1284         * ignore OUT_OF_RANGE error that may occur even the sequence
1285         * is correct". And JESD84-B51 for eMMC also has a similar
1286         * statement on section 6.8.3.
1287         *
1288         * Multiple block read/write could be done by either predefined
1289         * method, namely CMD23, or open-ending mode. For open-ending mode,
1290         * we should ignore the OUT_OF_RANGE error as it's normal behaviour.
1291         *
1292         * However the spec[1] doesn't tell us whether we should also
1293         * ignore that for predefined method. But per the spec[1], section
1294         * 4.15 Set Block Count Command, it says"If illegal block count
1295         * is set, out of range error will be indicated during read/write
1296         * operation (For example, data transfer is stopped at user area
1297         * boundary)." In another word, we could expect a out of range error
1298         * in the response for the following CMD18/25. And if argument of
1299         * CMD23 + the argument of CMD18/25 exceed the max number of blocks,
1300         * we could also expect to get a -ETIMEDOUT or any error number from
1301         * the host drivers due to missing data response(for write)/data(for
1302         * read), as the cards will stop the data transfer by itself per the
1303         * spec. So we only need to check R1_OUT_OF_RANGE for open-ending mode.
1304         */
1305
1306        if (!brq->stop.error) {
1307                bool oor_with_open_end;
1308                /* If there is no error yet, check R1 response */
1309
1310                val = brq->stop.resp[0] & CMD_ERRORS;
1311                oor_with_open_end = val & R1_OUT_OF_RANGE && !brq->mrq.sbc;
1312
1313                if (val && !oor_with_open_end)
1314                        brq->stop.error = -EIO;
1315        }
1316}
1317
1318static void mmc_blk_data_prep(struct mmc_queue *mq, struct mmc_queue_req *mqrq,
1319                              int disable_multi, bool *do_rel_wr_p,
1320                              bool *do_data_tag_p)
1321{
1322        struct mmc_blk_data *md = mq->blkdata;
1323        struct mmc_card *card = md->queue.card;
1324        struct mmc_blk_request *brq = &mqrq->brq;
1325        struct request *req = mmc_queue_req_to_req(mqrq);
1326        bool do_rel_wr, do_data_tag;
1327
1328        /*
1329         * Reliable writes are used to implement Forced Unit Access and
1330         * are supported only on MMCs.
1331         */
1332        do_rel_wr = (req->cmd_flags & REQ_FUA) &&
1333                    rq_data_dir(req) == WRITE &&
1334                    (md->flags & MMC_BLK_REL_WR);
1335
1336        memset(brq, 0, sizeof(struct mmc_blk_request));
1337
1338        brq->mrq.data = &brq->data;
1339        brq->mrq.tag = req->tag;
1340
1341        brq->stop.opcode = MMC_STOP_TRANSMISSION;
1342        brq->stop.arg = 0;
1343
1344        if (rq_data_dir(req) == READ) {
1345                brq->data.flags = MMC_DATA_READ;
1346                brq->stop.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC;
1347        } else {
1348                brq->data.flags = MMC_DATA_WRITE;
1349                brq->stop.flags = MMC_RSP_SPI_R1B | MMC_RSP_R1B | MMC_CMD_AC;
1350        }
1351
1352        brq->data.blksz = 512;
1353        brq->data.blocks = blk_rq_sectors(req);
1354        brq->data.blk_addr = blk_rq_pos(req);
1355
1356        /*
1357         * The command queue supports 2 priorities: "high" (1) and "simple" (0).
1358         * The eMMC will give "high" priority tasks priority over "simple"
1359         * priority tasks. Here we always set "simple" priority by not setting
1360         * MMC_DATA_PRIO.
1361         */
1362
1363        /*
1364         * The block layer doesn't support all sector count
1365         * restrictions, so we need to be prepared for too big
1366         * requests.
1367         */
1368        if (brq->data.blocks > card->host->max_blk_count)
1369                brq->data.blocks = card->host->max_blk_count;
1370
1371        if (brq->data.blocks > 1) {
1372                /*
1373                 * After a read error, we redo the request one sector
1374                 * at a time in order to accurately determine which
1375                 * sectors can be read successfully.
1376                 */
1377                if (disable_multi)
1378                        brq->data.blocks = 1;
1379
1380                /*
1381                 * Some controllers have HW issues while operating
1382                 * in multiple I/O mode
1383                 */
1384                if (card->host->ops->multi_io_quirk)
1385                        brq->data.blocks = card->host->ops->multi_io_quirk(card,
1386                                                (rq_data_dir(req) == READ) ?
1387                                                MMC_DATA_READ : MMC_DATA_WRITE,
1388                                                brq->data.blocks);
1389        }
1390
1391        if (do_rel_wr) {
1392                mmc_apply_rel_rw(brq, card, req);
1393                brq->data.flags |= MMC_DATA_REL_WR;
1394        }
1395
1396        /*
1397         * Data tag is used only during writing meta data to speed
1398         * up write and any subsequent read of this meta data
1399         */
1400        do_data_tag = card->ext_csd.data_tag_unit_size &&
1401                      (req->cmd_flags & REQ_META) &&
1402                      (rq_data_dir(req) == WRITE) &&
1403                      ((brq->data.blocks * brq->data.blksz) >=
1404                       card->ext_csd.data_tag_unit_size);
1405
1406        if (do_data_tag)
1407                brq->data.flags |= MMC_DATA_DAT_TAG;
1408
1409        mmc_set_data_timeout(&brq->data, card);
1410
1411        brq->data.sg = mqrq->sg;
1412        brq->data.sg_len = mmc_queue_map_sg(mq, mqrq);
1413
1414        /*
1415         * Adjust the sg list so it is the same size as the
1416         * request.
1417         */
1418        if (brq->data.blocks != blk_rq_sectors(req)) {
1419                int i, data_size = brq->data.blocks << 9;
1420                struct scatterlist *sg;
1421
1422                for_each_sg(brq->data.sg, sg, brq->data.sg_len, i) {
1423                        data_size -= sg->length;
1424                        if (data_size <= 0) {
1425                                sg->length += data_size;
1426                                i++;
1427                                break;
1428                        }
1429                }
1430                brq->data.sg_len = i;
1431        }
1432
1433        if (do_rel_wr_p)
1434                *do_rel_wr_p = do_rel_wr;
1435
1436        if (do_data_tag_p)
1437                *do_data_tag_p = do_data_tag;
1438}
1439
1440#define MMC_CQE_RETRIES 2
1441
1442static void mmc_blk_cqe_complete_rq(struct mmc_queue *mq, struct request *req)
1443{
1444        struct mmc_queue_req *mqrq = req_to_mmc_queue_req(req);
1445        struct mmc_request *mrq = &mqrq->brq.mrq;
1446        struct request_queue *q = req->q;
1447        struct mmc_host *host = mq->card->host;
1448        unsigned long flags;
1449        bool put_card;
1450        int err;
1451
1452        mmc_cqe_post_req(host, mrq);
1453
1454        if (mrq->cmd && mrq->cmd->error)
1455                err = mrq->cmd->error;
1456        else if (mrq->data && mrq->data->error)
1457                err = mrq->data->error;
1458        else
1459                err = 0;
1460
1461        if (err) {
1462                if (mqrq->retries++ < MMC_CQE_RETRIES)
1463                        blk_mq_requeue_request(req, true);
1464                else
1465                        blk_mq_end_request(req, BLK_STS_IOERR);
1466        } else if (mrq->data) {
1467                if (blk_update_request(req, BLK_STS_OK, mrq->data->bytes_xfered))
1468                        blk_mq_requeue_request(req, true);
1469                else
1470                        __blk_mq_end_request(req, BLK_STS_OK);
1471        } else {
1472                blk_mq_end_request(req, BLK_STS_OK);
1473        }
1474
1475        spin_lock_irqsave(&mq->lock, flags);
1476
1477        mq->in_flight[mmc_issue_type(mq, req)] -= 1;
1478
1479        put_card = (mmc_tot_in_flight(mq) == 0);
1480
1481        mmc_cqe_check_busy(mq);
1482
1483        spin_unlock_irqrestore(&mq->lock, flags);
1484
1485        if (!mq->cqe_busy)
1486                blk_mq_run_hw_queues(q, true);
1487
1488        if (put_card)
1489                mmc_put_card(mq->card, &mq->ctx);
1490}
1491
1492void mmc_blk_cqe_recovery(struct mmc_queue *mq)
1493{
1494        struct mmc_card *card = mq->card;
1495        struct mmc_host *host = card->host;
1496        int err;
1497
1498        pr_debug("%s: CQE recovery start\n", mmc_hostname(host));
1499
1500        err = mmc_cqe_recovery(host);
1501        if (err)
1502                mmc_blk_reset(mq->blkdata, host, MMC_BLK_CQE_RECOVERY);
1503        else
1504                mmc_blk_reset_success(mq->blkdata, MMC_BLK_CQE_RECOVERY);
1505
1506        pr_debug("%s: CQE recovery done\n", mmc_hostname(host));
1507}
1508
1509static void mmc_blk_cqe_req_done(struct mmc_request *mrq)
1510{
1511        struct mmc_queue_req *mqrq = container_of(mrq, struct mmc_queue_req,
1512                                                  brq.mrq);
1513        struct request *req = mmc_queue_req_to_req(mqrq);
1514        struct request_queue *q = req->q;
1515        struct mmc_queue *mq = q->queuedata;
1516
1517        /*
1518         * Block layer timeouts race with completions which means the normal
1519         * completion path cannot be used during recovery.
1520         */
1521        if (mq->in_recovery)
1522                mmc_blk_cqe_complete_rq(mq, req);
1523        else if (likely(!blk_should_fake_timeout(req->q)))
1524                blk_mq_complete_request(req);
1525}
1526
1527static int mmc_blk_cqe_start_req(struct mmc_host *host, struct mmc_request *mrq)
1528{
1529        mrq->done               = mmc_blk_cqe_req_done;
1530        mrq->recovery_notifier  = mmc_cqe_recovery_notifier;
1531
1532        return mmc_cqe_start_req(host, mrq);
1533}
1534
1535static struct mmc_request *mmc_blk_cqe_prep_dcmd(struct mmc_queue_req *mqrq,
1536                                                 struct request *req)
1537{
1538        struct mmc_blk_request *brq = &mqrq->brq;
1539
1540        memset(brq, 0, sizeof(*brq));
1541
1542        brq->mrq.cmd = &brq->cmd;
1543        brq->mrq.tag = req->tag;
1544
1545        return &brq->mrq;
1546}
1547
1548static int mmc_blk_cqe_issue_flush(struct mmc_queue *mq, struct request *req)
1549{
1550        struct mmc_queue_req *mqrq = req_to_mmc_queue_req(req);
1551        struct mmc_request *mrq = mmc_blk_cqe_prep_dcmd(mqrq, req);
1552
1553        mrq->cmd->opcode = MMC_SWITCH;
1554        mrq->cmd->arg = (MMC_SWITCH_MODE_WRITE_BYTE << 24) |
1555                        (EXT_CSD_FLUSH_CACHE << 16) |
1556                        (1 << 8) |
1557                        EXT_CSD_CMD_SET_NORMAL;
1558        mrq->cmd->flags = MMC_CMD_AC | MMC_RSP_R1B;
1559
1560        return mmc_blk_cqe_start_req(mq->card->host, mrq);
1561}
1562
1563static int mmc_blk_cqe_issue_rw_rq(struct mmc_queue *mq, struct request *req)
1564{
1565        struct mmc_queue_req *mqrq = req_to_mmc_queue_req(req);
1566
1567        mmc_blk_data_prep(mq, mqrq, 0, NULL, NULL);
1568
1569        return mmc_blk_cqe_start_req(mq->card->host, &mqrq->brq.mrq);
1570}
1571
1572static void mmc_blk_rw_rq_prep(struct mmc_queue_req *mqrq,
1573                               struct mmc_card *card,
1574                               int disable_multi,
1575                               struct mmc_queue *mq)
1576{
1577        u32 readcmd, writecmd;
1578        struct mmc_blk_request *brq = &mqrq->brq;
1579        struct request *req = mmc_queue_req_to_req(mqrq);
1580        struct mmc_blk_data *md = mq->blkdata;
1581        bool do_rel_wr, do_data_tag;
1582
1583        mmc_blk_data_prep(mq, mqrq, disable_multi, &do_rel_wr, &do_data_tag);
1584
1585        brq->mrq.cmd = &brq->cmd;
1586
1587        brq->cmd.arg = blk_rq_pos(req);
1588        if (!mmc_card_blockaddr(card))
1589                brq->cmd.arg <<= 9;
1590        brq->cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_ADTC;
1591
1592        if (brq->data.blocks > 1 || do_rel_wr) {
1593                /* SPI multiblock writes terminate using a special
1594                 * token, not a STOP_TRANSMISSION request.
1595                 */
1596                if (!mmc_host_is_spi(card->host) ||
1597                    rq_data_dir(req) == READ)
1598                        brq->mrq.stop = &brq->stop;
1599                readcmd = MMC_READ_MULTIPLE_BLOCK;
1600                writecmd = MMC_WRITE_MULTIPLE_BLOCK;
1601        } else {
1602                brq->mrq.stop = NULL;
1603                readcmd = MMC_READ_SINGLE_BLOCK;
1604                writecmd = MMC_WRITE_BLOCK;
1605        }
1606        brq->cmd.opcode = rq_data_dir(req) == READ ? readcmd : writecmd;
1607
1608        /*
1609         * Pre-defined multi-block transfers are preferable to
1610         * open ended-ones (and necessary for reliable writes).
1611         * However, it is not sufficient to just send CMD23,
1612         * and avoid the final CMD12, as on an error condition
1613         * CMD12 (stop) needs to be sent anyway. This, coupled
1614         * with Auto-CMD23 enhancements provided by some
1615         * hosts, means that the complexity of dealing
1616         * with this is best left to the host. If CMD23 is
1617         * supported by card and host, we'll fill sbc in and let
1618         * the host deal with handling it correctly. This means
1619         * that for hosts that don't expose MMC_CAP_CMD23, no
1620         * change of behavior will be observed.
1621         *
1622         * N.B: Some MMC cards experience perf degradation.
1623         * We'll avoid using CMD23-bounded multiblock writes for
1624         * these, while retaining features like reliable writes.
1625         */
1626        if ((md->flags & MMC_BLK_CMD23) && mmc_op_multi(brq->cmd.opcode) &&
1627            (do_rel_wr || !(card->quirks & MMC_QUIRK_BLK_NO_CMD23) ||
1628             do_data_tag)) {
1629                brq->sbc.opcode = MMC_SET_BLOCK_COUNT;
1630                brq->sbc.arg = brq->data.blocks |
1631                        (do_rel_wr ? (1 << 31) : 0) |
1632                        (do_data_tag ? (1 << 29) : 0);
1633                brq->sbc.flags = MMC_RSP_R1 | MMC_CMD_AC;
1634                brq->mrq.sbc = &brq->sbc;
1635        }
1636}
1637
1638#define MMC_MAX_RETRIES         5
1639#define MMC_DATA_RETRIES        2
1640#define MMC_NO_RETRIES          (MMC_MAX_RETRIES + 1)
1641
1642static int mmc_blk_send_stop(struct mmc_card *card, unsigned int timeout)
1643{
1644        struct mmc_command cmd = {
1645                .opcode = MMC_STOP_TRANSMISSION,
1646                .flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC,
1647                /* Some hosts wait for busy anyway, so provide a busy timeout */
1648                .busy_timeout = timeout,
1649        };
1650
1651        return mmc_wait_for_cmd(card->host, &cmd, 5);
1652}
1653
1654static int mmc_blk_fix_state(struct mmc_card *card, struct request *req)
1655{
1656        struct mmc_queue_req *mqrq = req_to_mmc_queue_req(req);
1657        struct mmc_blk_request *brq = &mqrq->brq;
1658        unsigned int timeout = mmc_blk_data_timeout_ms(card->host, &brq->data);
1659        int err;
1660
1661        mmc_retune_hold_now(card->host);
1662
1663        mmc_blk_send_stop(card, timeout);
1664
1665        err = card_busy_detect(card, timeout, req, NULL);
1666
1667        mmc_retune_release(card->host);
1668
1669        return err;
1670}
1671
1672#define MMC_READ_SINGLE_RETRIES 2
1673
1674/* Single sector read during recovery */
1675static void mmc_blk_read_single(struct mmc_queue *mq, struct request *req)
1676{
1677        struct mmc_queue_req *mqrq = req_to_mmc_queue_req(req);
1678        struct mmc_request *mrq = &mqrq->brq.mrq;
1679        struct mmc_card *card = mq->card;
1680        struct mmc_host *host = card->host;
1681        blk_status_t error = BLK_STS_OK;
1682        int retries = 0;
1683
1684        do {
1685                u32 status;
1686                int err;
1687
1688                mmc_blk_rw_rq_prep(mqrq, card, 1, mq);
1689
1690                mmc_wait_for_req(host, mrq);
1691
1692                err = mmc_send_status(card, &status);
1693                if (err)
1694                        goto error_exit;
1695
1696                if (!mmc_host_is_spi(host) &&
1697                    !mmc_blk_in_tran_state(status)) {
1698                        err = mmc_blk_fix_state(card, req);
1699                        if (err)
1700                                goto error_exit;
1701                }
1702
1703                if (mrq->cmd->error && retries++ < MMC_READ_SINGLE_RETRIES)
1704                        continue;
1705
1706                retries = 0;
1707
1708                if (mrq->cmd->error ||
1709                    mrq->data->error ||
1710                    (!mmc_host_is_spi(host) &&
1711                     (mrq->cmd->resp[0] & CMD_ERRORS || status & CMD_ERRORS)))
1712                        error = BLK_STS_IOERR;
1713                else
1714                        error = BLK_STS_OK;
1715
1716        } while (blk_update_request(req, error, 512));
1717
1718        return;
1719
1720error_exit:
1721        mrq->data->bytes_xfered = 0;
1722        blk_update_request(req, BLK_STS_IOERR, 512);
1723        /* Let it try the remaining request again */
1724        if (mqrq->retries > MMC_MAX_RETRIES - 1)
1725                mqrq->retries = MMC_MAX_RETRIES - 1;
1726}
1727
1728static inline bool mmc_blk_oor_valid(struct mmc_blk_request *brq)
1729{
1730        return !!brq->mrq.sbc;
1731}
1732
1733static inline u32 mmc_blk_stop_err_bits(struct mmc_blk_request *brq)
1734{
1735        return mmc_blk_oor_valid(brq) ? CMD_ERRORS : CMD_ERRORS_EXCL_OOR;
1736}
1737
1738/*
1739 * Check for errors the host controller driver might not have seen such as
1740 * response mode errors or invalid card state.
1741 */
1742static bool mmc_blk_status_error(struct request *req, u32 status)
1743{
1744        struct mmc_queue_req *mqrq = req_to_mmc_queue_req(req);
1745        struct mmc_blk_request *brq = &mqrq->brq;
1746        struct mmc_queue *mq = req->q->queuedata;
1747        u32 stop_err_bits;
1748
1749        if (mmc_host_is_spi(mq->card->host))
1750                return false;
1751
1752        stop_err_bits = mmc_blk_stop_err_bits(brq);
1753
1754        return brq->cmd.resp[0]  & CMD_ERRORS    ||
1755               brq->stop.resp[0] & stop_err_bits ||
1756               status            & stop_err_bits ||
1757               (rq_data_dir(req) == WRITE && !mmc_blk_in_tran_state(status));
1758}
1759
1760static inline bool mmc_blk_cmd_started(struct mmc_blk_request *brq)
1761{
1762        return !brq->sbc.error && !brq->cmd.error &&
1763               !(brq->cmd.resp[0] & CMD_ERRORS);
1764}
1765
1766/*
1767 * Requests are completed by mmc_blk_mq_complete_rq() which sets simple
1768 * policy:
1769 * 1. A request that has transferred at least some data is considered
1770 * successful and will be requeued if there is remaining data to
1771 * transfer.
1772 * 2. Otherwise the number of retries is incremented and the request
1773 * will be requeued if there are remaining retries.
1774 * 3. Otherwise the request will be errored out.
1775 * That means mmc_blk_mq_complete_rq() is controlled by bytes_xfered and
1776 * mqrq->retries. So there are only 4 possible actions here:
1777 *      1. do not accept the bytes_xfered value i.e. set it to zero
1778 *      2. change mqrq->retries to determine the number of retries
1779 *      3. try to reset the card
1780 *      4. read one sector at a time
1781 */
1782static void mmc_blk_mq_rw_recovery(struct mmc_queue *mq, struct request *req)
1783{
1784        int type = rq_data_dir(req) == READ ? MMC_BLK_READ : MMC_BLK_WRITE;
1785        struct mmc_queue_req *mqrq = req_to_mmc_queue_req(req);
1786        struct mmc_blk_request *brq = &mqrq->brq;
1787        struct mmc_blk_data *md = mq->blkdata;
1788        struct mmc_card *card = mq->card;
1789        u32 status;
1790        u32 blocks;
1791        int err;
1792
1793        /*
1794         * Some errors the host driver might not have seen. Set the number of
1795         * bytes transferred to zero in that case.
1796         */
1797        err = __mmc_send_status(card, &status, 0);
1798        if (err || mmc_blk_status_error(req, status))
1799                brq->data.bytes_xfered = 0;
1800
1801        mmc_retune_release(card->host);
1802
1803        /*
1804         * Try again to get the status. This also provides an opportunity for
1805         * re-tuning.
1806         */
1807        if (err)
1808                err = __mmc_send_status(card, &status, 0);
1809
1810        /*
1811         * Nothing more to do after the number of bytes transferred has been
1812         * updated and there is no card.
1813         */
1814        if (err && mmc_detect_card_removed(card->host))
1815                return;
1816
1817        /* Try to get back to "tran" state */
1818        if (!mmc_host_is_spi(mq->card->host) &&
1819            (err || !mmc_blk_in_tran_state(status)))
1820                err = mmc_blk_fix_state(mq->card, req);
1821
1822        /*
1823         * Special case for SD cards where the card might record the number of
1824         * blocks written.
1825         */
1826        if (!err && mmc_blk_cmd_started(brq) && mmc_card_sd(card) &&
1827            rq_data_dir(req) == WRITE) {
1828                if (mmc_sd_num_wr_blocks(card, &blocks))
1829                        brq->data.bytes_xfered = 0;
1830                else
1831                        brq->data.bytes_xfered = blocks << 9;
1832        }
1833
1834        /* Reset if the card is in a bad state */
1835        if (!mmc_host_is_spi(mq->card->host) &&
1836            err && mmc_blk_reset(md, card->host, type)) {
1837                pr_err("%s: recovery failed!\n", req->rq_disk->disk_name);
1838                mqrq->retries = MMC_NO_RETRIES;
1839                return;
1840        }
1841
1842        /*
1843         * If anything was done, just return and if there is anything remaining
1844         * on the request it will get requeued.
1845         */
1846        if (brq->data.bytes_xfered)
1847                return;
1848
1849        /* Reset before last retry */
1850        if (mqrq->retries + 1 == MMC_MAX_RETRIES)
1851                mmc_blk_reset(md, card->host, type);
1852
1853        /* Command errors fail fast, so use all MMC_MAX_RETRIES */
1854        if (brq->sbc.error || brq->cmd.error)
1855                return;
1856
1857        /* Reduce the remaining retries for data errors */
1858        if (mqrq->retries < MMC_MAX_RETRIES - MMC_DATA_RETRIES) {
1859                mqrq->retries = MMC_MAX_RETRIES - MMC_DATA_RETRIES;
1860                return;
1861        }
1862
1863        /* FIXME: Missing single sector read for large sector size */
1864        if (!mmc_large_sector(card) && rq_data_dir(req) == READ &&
1865            brq->data.blocks > 1) {
1866                /* Read one sector at a time */
1867                mmc_blk_read_single(mq, req);
1868                return;
1869        }
1870}
1871
1872static inline bool mmc_blk_rq_error(struct mmc_blk_request *brq)
1873{
1874        mmc_blk_eval_resp_error(brq);
1875
1876        return brq->sbc.error || brq->cmd.error || brq->stop.error ||
1877               brq->data.error || brq->cmd.resp[0] & CMD_ERRORS;
1878}
1879
1880static int mmc_blk_card_busy(struct mmc_card *card, struct request *req)
1881{
1882        struct mmc_queue_req *mqrq = req_to_mmc_queue_req(req);
1883        u32 status = 0;
1884        int err;
1885
1886        if (mmc_host_is_spi(card->host) || rq_data_dir(req) == READ)
1887                return 0;
1888
1889        err = card_busy_detect(card, MMC_BLK_TIMEOUT_MS, req, &status);
1890
1891        /*
1892         * Do not assume data transferred correctly if there are any error bits
1893         * set.
1894         */
1895        if (status & mmc_blk_stop_err_bits(&mqrq->brq)) {
1896                mqrq->brq.data.bytes_xfered = 0;
1897                err = err ? err : -EIO;
1898        }
1899
1900        /* Copy the exception bit so it will be seen later on */
1901        if (mmc_card_mmc(card) && status & R1_EXCEPTION_EVENT)
1902                mqrq->brq.cmd.resp[0] |= R1_EXCEPTION_EVENT;
1903
1904        return err;
1905}
1906
1907static inline void mmc_blk_rw_reset_success(struct mmc_queue *mq,
1908                                            struct request *req)
1909{
1910        int type = rq_data_dir(req) == READ ? MMC_BLK_READ : MMC_BLK_WRITE;
1911
1912        mmc_blk_reset_success(mq->blkdata, type);
1913}
1914
1915static void mmc_blk_mq_complete_rq(struct mmc_queue *mq, struct request *req)
1916{
1917        struct mmc_queue_req *mqrq = req_to_mmc_queue_req(req);
1918        unsigned int nr_bytes = mqrq->brq.data.bytes_xfered;
1919
1920        if (nr_bytes) {
1921                if (blk_update_request(req, BLK_STS_OK, nr_bytes))
1922                        blk_mq_requeue_request(req, true);
1923                else
1924                        __blk_mq_end_request(req, BLK_STS_OK);
1925        } else if (!blk_rq_bytes(req)) {
1926                __blk_mq_end_request(req, BLK_STS_IOERR);
1927        } else if (mqrq->retries++ < MMC_MAX_RETRIES) {
1928                blk_mq_requeue_request(req, true);
1929        } else {
1930                if (mmc_card_removed(mq->card))
1931                        req->rq_flags |= RQF_QUIET;
1932                blk_mq_end_request(req, BLK_STS_IOERR);
1933        }
1934}
1935
1936static bool mmc_blk_urgent_bkops_needed(struct mmc_queue *mq,
1937                                        struct mmc_queue_req *mqrq)
1938{
1939        return mmc_card_mmc(mq->card) && !mmc_host_is_spi(mq->card->host) &&
1940               (mqrq->brq.cmd.resp[0] & R1_EXCEPTION_EVENT ||
1941                mqrq->brq.stop.resp[0] & R1_EXCEPTION_EVENT);
1942}
1943
1944static void mmc_blk_urgent_bkops(struct mmc_queue *mq,
1945                                 struct mmc_queue_req *mqrq)
1946{
1947        if (mmc_blk_urgent_bkops_needed(mq, mqrq))
1948                mmc_start_bkops(mq->card, true);
1949}
1950
1951void mmc_blk_mq_complete(struct request *req)
1952{
1953        struct mmc_queue *mq = req->q->queuedata;
1954
1955        if (mq->use_cqe)
1956                mmc_blk_cqe_complete_rq(mq, req);
1957        else if (likely(!blk_should_fake_timeout(req->q)))
1958                mmc_blk_mq_complete_rq(mq, req);
1959}
1960
1961static void mmc_blk_mq_poll_completion(struct mmc_queue *mq,
1962                                       struct request *req)
1963{
1964        struct mmc_queue_req *mqrq = req_to_mmc_queue_req(req);
1965        struct mmc_host *host = mq->card->host;
1966
1967        if (mmc_blk_rq_error(&mqrq->brq) ||
1968            mmc_blk_card_busy(mq->card, req)) {
1969                mmc_blk_mq_rw_recovery(mq, req);
1970        } else {
1971                mmc_blk_rw_reset_success(mq, req);
1972                mmc_retune_release(host);
1973        }
1974
1975        mmc_blk_urgent_bkops(mq, mqrq);
1976}
1977
1978static void mmc_blk_mq_dec_in_flight(struct mmc_queue *mq, struct request *req)
1979{
1980        unsigned long flags;
1981        bool put_card;
1982
1983        spin_lock_irqsave(&mq->lock, flags);
1984
1985        mq->in_flight[mmc_issue_type(mq, req)] -= 1;
1986
1987        put_card = (mmc_tot_in_flight(mq) == 0);
1988
1989        spin_unlock_irqrestore(&mq->lock, flags);
1990
1991        if (put_card)
1992                mmc_put_card(mq->card, &mq->ctx);
1993}
1994
1995static void mmc_blk_mq_post_req(struct mmc_queue *mq, struct request *req)
1996{
1997        struct mmc_queue_req *mqrq = req_to_mmc_queue_req(req);
1998        struct mmc_request *mrq = &mqrq->brq.mrq;
1999        struct mmc_host *host = mq->card->host;
2000
2001        mmc_post_req(host, mrq, 0);
2002
2003        /*
2004         * Block layer timeouts race with completions which means the normal
2005         * completion path cannot be used during recovery.
2006         */
2007        if (mq->in_recovery)
2008                mmc_blk_mq_complete_rq(mq, req);
2009        else if (likely(!blk_should_fake_timeout(req->q)))
2010                blk_mq_complete_request(req);
2011
2012        mmc_blk_mq_dec_in_flight(mq, req);
2013}
2014
2015void mmc_blk_mq_recovery(struct mmc_queue *mq)
2016{
2017        struct request *req = mq->recovery_req;
2018        struct mmc_host *host = mq->card->host;
2019        struct mmc_queue_req *mqrq = req_to_mmc_queue_req(req);
2020
2021        mq->recovery_req = NULL;
2022        mq->rw_wait = false;
2023
2024        if (mmc_blk_rq_error(&mqrq->brq)) {
2025                mmc_retune_hold_now(host);
2026                mmc_blk_mq_rw_recovery(mq, req);
2027        }
2028
2029        mmc_blk_urgent_bkops(mq, mqrq);
2030
2031        mmc_blk_mq_post_req(mq, req);
2032}
2033
2034static void mmc_blk_mq_complete_prev_req(struct mmc_queue *mq,
2035                                         struct request **prev_req)
2036{
2037        if (mmc_host_done_complete(mq->card->host))
2038                return;
2039
2040        mutex_lock(&mq->complete_lock);
2041
2042        if (!mq->complete_req)
2043                goto out_unlock;
2044
2045        mmc_blk_mq_poll_completion(mq, mq->complete_req);
2046
2047        if (prev_req)
2048                *prev_req = mq->complete_req;
2049        else
2050                mmc_blk_mq_post_req(mq, mq->complete_req);
2051
2052        mq->complete_req = NULL;
2053
2054out_unlock:
2055        mutex_unlock(&mq->complete_lock);
2056}
2057
2058void mmc_blk_mq_complete_work(struct work_struct *work)
2059{
2060        struct mmc_queue *mq = container_of(work, struct mmc_queue,
2061                                            complete_work);
2062
2063        mmc_blk_mq_complete_prev_req(mq, NULL);
2064}
2065
2066static void mmc_blk_mq_req_done(struct mmc_request *mrq)
2067{
2068        struct mmc_queue_req *mqrq = container_of(mrq, struct mmc_queue_req,
2069                                                  brq.mrq);
2070        struct request *req = mmc_queue_req_to_req(mqrq);
2071        struct request_queue *q = req->q;
2072        struct mmc_queue *mq = q->queuedata;
2073        struct mmc_host *host = mq->card->host;
2074        unsigned long flags;
2075
2076        if (!mmc_host_done_complete(host)) {
2077                bool waiting;
2078
2079                /*
2080                 * We cannot complete the request in this context, so record
2081                 * that there is a request to complete, and that a following
2082                 * request does not need to wait (although it does need to
2083                 * complete complete_req first).
2084                 */
2085                spin_lock_irqsave(&mq->lock, flags);
2086                mq->complete_req = req;
2087                mq->rw_wait = false;
2088                waiting = mq->waiting;
2089                spin_unlock_irqrestore(&mq->lock, flags);
2090
2091                /*
2092                 * If 'waiting' then the waiting task will complete this
2093                 * request, otherwise queue a work to do it. Note that
2094                 * complete_work may still race with the dispatch of a following
2095                 * request.
2096                 */
2097                if (waiting)
2098                        wake_up(&mq->wait);
2099                else
2100                        kblockd_schedule_work(&mq->complete_work);
2101
2102                return;
2103        }
2104
2105        /* Take the recovery path for errors or urgent background operations */
2106        if (mmc_blk_rq_error(&mqrq->brq) ||
2107            mmc_blk_urgent_bkops_needed(mq, mqrq)) {
2108                spin_lock_irqsave(&mq->lock, flags);
2109                mq->recovery_needed = true;
2110                mq->recovery_req = req;
2111                spin_unlock_irqrestore(&mq->lock, flags);
2112                wake_up(&mq->wait);
2113                schedule_work(&mq->recovery_work);
2114                return;
2115        }
2116
2117        mmc_blk_rw_reset_success(mq, req);
2118
2119        mq->rw_wait = false;
2120        wake_up(&mq->wait);
2121
2122        mmc_blk_mq_post_req(mq, req);
2123}
2124
2125static bool mmc_blk_rw_wait_cond(struct mmc_queue *mq, int *err)
2126{
2127        unsigned long flags;
2128        bool done;
2129
2130        /*
2131         * Wait while there is another request in progress, but not if recovery
2132         * is needed. Also indicate whether there is a request waiting to start.
2133         */
2134        spin_lock_irqsave(&mq->lock, flags);
2135        if (mq->recovery_needed) {
2136                *err = -EBUSY;
2137                done = true;
2138        } else {
2139                done = !mq->rw_wait;
2140        }
2141        mq->waiting = !done;
2142        spin_unlock_irqrestore(&mq->lock, flags);
2143
2144        return done;
2145}
2146
2147static int mmc_blk_rw_wait(struct mmc_queue *mq, struct request **prev_req)
2148{
2149        int err = 0;
2150
2151        wait_event(mq->wait, mmc_blk_rw_wait_cond(mq, &err));
2152
2153        /* Always complete the previous request if there is one */
2154        mmc_blk_mq_complete_prev_req(mq, prev_req);
2155
2156        return err;
2157}
2158
2159static int mmc_blk_mq_issue_rw_rq(struct mmc_queue *mq,
2160                                  struct request *req)
2161{
2162        struct mmc_queue_req *mqrq = req_to_mmc_queue_req(req);
2163        struct mmc_host *host = mq->card->host;
2164        struct request *prev_req = NULL;
2165        int err = 0;
2166
2167        mmc_blk_rw_rq_prep(mqrq, mq->card, 0, mq);
2168
2169        mqrq->brq.mrq.done = mmc_blk_mq_req_done;
2170
2171        mmc_pre_req(host, &mqrq->brq.mrq);
2172
2173        err = mmc_blk_rw_wait(mq, &prev_req);
2174        if (err)
2175                goto out_post_req;
2176
2177        mq->rw_wait = true;
2178
2179        err = mmc_start_request(host, &mqrq->brq.mrq);
2180
2181        if (prev_req)
2182                mmc_blk_mq_post_req(mq, prev_req);
2183
2184        if (err)
2185                mq->rw_wait = false;
2186
2187        /* Release re-tuning here where there is no synchronization required */
2188        if (err || mmc_host_done_complete(host))
2189                mmc_retune_release(host);
2190
2191out_post_req:
2192        if (err)
2193                mmc_post_req(host, &mqrq->brq.mrq, err);
2194
2195        return err;
2196}
2197
2198static int mmc_blk_wait_for_idle(struct mmc_queue *mq, struct mmc_host *host)
2199{
2200        if (mq->use_cqe)
2201                return host->cqe_ops->cqe_wait_for_idle(host);
2202
2203        return mmc_blk_rw_wait(mq, NULL);
2204}
2205
2206enum mmc_issued mmc_blk_mq_issue_rq(struct mmc_queue *mq, struct request *req)
2207{
2208        struct mmc_blk_data *md = mq->blkdata;
2209        struct mmc_card *card = md->queue.card;
2210        struct mmc_host *host = card->host;
2211        int ret;
2212
2213        ret = mmc_blk_part_switch(card, md->part_type);
2214        if (ret)
2215                return MMC_REQ_FAILED_TO_START;
2216
2217        switch (mmc_issue_type(mq, req)) {
2218        case MMC_ISSUE_SYNC:
2219                ret = mmc_blk_wait_for_idle(mq, host);
2220                if (ret)
2221                        return MMC_REQ_BUSY;
2222                switch (req_op(req)) {
2223                case REQ_OP_DRV_IN:
2224                case REQ_OP_DRV_OUT:
2225                        mmc_blk_issue_drv_op(mq, req);
2226                        break;
2227                case REQ_OP_DISCARD:
2228                        mmc_blk_issue_discard_rq(mq, req);
2229                        break;
2230                case REQ_OP_SECURE_ERASE:
2231                        mmc_blk_issue_secdiscard_rq(mq, req);
2232                        break;
2233                case REQ_OP_FLUSH:
2234                        mmc_blk_issue_flush(mq, req);
2235                        break;
2236                default:
2237                        WARN_ON_ONCE(1);
2238                        return MMC_REQ_FAILED_TO_START;
2239                }
2240                return MMC_REQ_FINISHED;
2241        case MMC_ISSUE_DCMD:
2242        case MMC_ISSUE_ASYNC:
2243                switch (req_op(req)) {
2244                case REQ_OP_FLUSH:
2245                        ret = mmc_blk_cqe_issue_flush(mq, req);
2246                        break;
2247                case REQ_OP_READ:
2248                case REQ_OP_WRITE:
2249                        if (mq->use_cqe)
2250                                ret = mmc_blk_cqe_issue_rw_rq(mq, req);
2251                        else
2252                                ret = mmc_blk_mq_issue_rw_rq(mq, req);
2253                        break;
2254                default:
2255                        WARN_ON_ONCE(1);
2256                        ret = -EINVAL;
2257                }
2258                if (!ret)
2259                        return MMC_REQ_STARTED;
2260                return ret == -EBUSY ? MMC_REQ_BUSY : MMC_REQ_FAILED_TO_START;
2261        default:
2262                WARN_ON_ONCE(1);
2263                return MMC_REQ_FAILED_TO_START;
2264        }
2265}
2266
2267static inline int mmc_blk_readonly(struct mmc_card *card)
2268{
2269        return mmc_card_readonly(card) ||
2270               !(card->csd.cmdclass & CCC_BLOCK_WRITE);
2271}
2272
2273static struct mmc_blk_data *mmc_blk_alloc_req(struct mmc_card *card,
2274                                              struct device *parent,
2275                                              sector_t size,
2276                                              bool default_ro,
2277                                              const char *subname,
2278                                              int area_type)
2279{
2280        struct mmc_blk_data *md;
2281        int devidx, ret;
2282
2283        devidx = ida_simple_get(&mmc_blk_ida, 0, max_devices, GFP_KERNEL);
2284        if (devidx < 0) {
2285                /*
2286                 * We get -ENOSPC because there are no more any available
2287                 * devidx. The reason may be that, either userspace haven't yet
2288                 * unmounted the partitions, which postpones mmc_blk_release()
2289                 * from being called, or the device has more partitions than
2290                 * what we support.
2291                 */
2292                if (devidx == -ENOSPC)
2293                        dev_err(mmc_dev(card->host),
2294                                "no more device IDs available\n");
2295
2296                return ERR_PTR(devidx);
2297        }
2298
2299        md = kzalloc(sizeof(struct mmc_blk_data), GFP_KERNEL);
2300        if (!md) {
2301                ret = -ENOMEM;
2302                goto out;
2303        }
2304
2305        md->area_type = area_type;
2306
2307        /*
2308         * Set the read-only status based on the supported commands
2309         * and the write protect switch.
2310         */
2311        md->read_only = mmc_blk_readonly(card);
2312
2313        md->disk = alloc_disk(perdev_minors);
2314        if (md->disk == NULL) {
2315                ret = -ENOMEM;
2316                goto err_kfree;
2317        }
2318
2319        INIT_LIST_HEAD(&md->part);
2320        INIT_LIST_HEAD(&md->rpmbs);
2321        md->usage = 1;
2322
2323        ret = mmc_init_queue(&md->queue, card);
2324        if (ret)
2325                goto err_putdisk;
2326
2327        md->queue.blkdata = md;
2328
2329        /*
2330         * Keep an extra reference to the queue so that we can shutdown the
2331         * queue (i.e. call blk_cleanup_queue()) while there are still
2332         * references to the 'md'. The corresponding blk_put_queue() is in
2333         * mmc_blk_put().
2334         */
2335        if (!blk_get_queue(md->queue.queue)) {
2336                mmc_cleanup_queue(&md->queue);
2337                ret = -ENODEV;
2338                goto err_putdisk;
2339        }
2340
2341        md->disk->major = MMC_BLOCK_MAJOR;
2342        md->disk->first_minor = devidx * perdev_minors;
2343        md->disk->fops = &mmc_bdops;
2344        md->disk->private_data = md;
2345        md->disk->queue = md->queue.queue;
2346        md->parent = parent;
2347        set_disk_ro(md->disk, md->read_only || default_ro);
2348        md->disk->flags = GENHD_FL_EXT_DEVT;
2349        if (area_type & (MMC_BLK_DATA_AREA_RPMB | MMC_BLK_DATA_AREA_BOOT))
2350                md->disk->flags |= GENHD_FL_NO_PART_SCAN
2351                                   | GENHD_FL_SUPPRESS_PARTITION_INFO;
2352
2353        /*
2354         * As discussed on lkml, GENHD_FL_REMOVABLE should:
2355         *
2356         * - be set for removable media with permanent block devices
2357         * - be unset for removable block devices with permanent media
2358         *
2359         * Since MMC block devices clearly fall under the second
2360         * case, we do not set GENHD_FL_REMOVABLE.  Userspace
2361         * should use the block device creation/destruction hotplug
2362         * messages to tell when the card is present.
2363         */
2364
2365        snprintf(md->disk->disk_name, sizeof(md->disk->disk_name),
2366                 "mmcblk%u%s", card->host->index, subname ? subname : "");
2367
2368        set_capacity(md->disk, size);
2369
2370        if (mmc_host_cmd23(card->host)) {
2371                if ((mmc_card_mmc(card) &&
2372                     card->csd.mmca_vsn >= CSD_SPEC_VER_3) ||
2373                    (mmc_card_sd(card) &&
2374                     card->scr.cmds & SD_SCR_CMD23_SUPPORT))
2375                        md->flags |= MMC_BLK_CMD23;
2376        }
2377
2378        if (mmc_card_mmc(card) &&
2379            md->flags & MMC_BLK_CMD23 &&
2380            ((card->ext_csd.rel_param & EXT_CSD_WR_REL_PARAM_EN) ||
2381             card->ext_csd.rel_sectors)) {
2382                md->flags |= MMC_BLK_REL_WR;
2383                blk_queue_write_cache(md->queue.queue, true, true);
2384        }
2385
2386        return md;
2387
2388 err_putdisk:
2389        put_disk(md->disk);
2390 err_kfree:
2391        kfree(md);
2392 out:
2393        ida_simple_remove(&mmc_blk_ida, devidx);
2394        return ERR_PTR(ret);
2395}
2396
2397static struct mmc_blk_data *mmc_blk_alloc(struct mmc_card *card)
2398{
2399        sector_t size;
2400
2401        if (!mmc_card_sd(card) && mmc_card_blockaddr(card)) {
2402                /*
2403                 * The EXT_CSD sector count is in number or 512 byte
2404                 * sectors.
2405                 */
2406                size = card->ext_csd.sectors;
2407        } else {
2408                /*
2409                 * The CSD capacity field is in units of read_blkbits.
2410                 * set_capacity takes units of 512 bytes.
2411                 */
2412                size = (typeof(sector_t))card->csd.capacity
2413                        << (card->csd.read_blkbits - 9);
2414        }
2415
2416        return mmc_blk_alloc_req(card, &card->dev, size, false, NULL,
2417                                        MMC_BLK_DATA_AREA_MAIN);
2418}
2419
2420static int mmc_blk_alloc_part(struct mmc_card *card,
2421                              struct mmc_blk_data *md,
2422                              unsigned int part_type,
2423                              sector_t size,
2424                              bool default_ro,
2425                              const char *subname,
2426                              int area_type)
2427{
2428        char cap_str[10];
2429        struct mmc_blk_data *part_md;
2430
2431        part_md = mmc_blk_alloc_req(card, disk_to_dev(md->disk), size, default_ro,
2432                                    subname, area_type);
2433        if (IS_ERR(part_md))
2434                return PTR_ERR(part_md);
2435        part_md->part_type = part_type;
2436        list_add(&part_md->part, &md->part);
2437
2438        string_get_size((u64)get_capacity(part_md->disk), 512, STRING_UNITS_2,
2439                        cap_str, sizeof(cap_str));
2440        pr_info("%s: %s %s partition %u %s\n",
2441               part_md->disk->disk_name, mmc_card_id(card),
2442               mmc_card_name(card), part_md->part_type, cap_str);
2443        return 0;
2444}
2445
2446/**
2447 * mmc_rpmb_ioctl() - ioctl handler for the RPMB chardev
2448 * @filp: the character device file
2449 * @cmd: the ioctl() command
2450 * @arg: the argument from userspace
2451 *
2452 * This will essentially just redirect the ioctl()s coming in over to
2453 * the main block device spawning the RPMB character device.
2454 */
2455static long mmc_rpmb_ioctl(struct file *filp, unsigned int cmd,
2456                           unsigned long arg)
2457{
2458        struct mmc_rpmb_data *rpmb = filp->private_data;
2459        int ret;
2460
2461        switch (cmd) {
2462        case MMC_IOC_CMD:
2463                ret = mmc_blk_ioctl_cmd(rpmb->md,
2464                                        (struct mmc_ioc_cmd __user *)arg,
2465                                        rpmb);
2466                break;
2467        case MMC_IOC_MULTI_CMD:
2468                ret = mmc_blk_ioctl_multi_cmd(rpmb->md,
2469                                        (struct mmc_ioc_multi_cmd __user *)arg,
2470                                        rpmb);
2471                break;
2472        default:
2473                ret = -EINVAL;
2474                break;
2475        }
2476
2477        return ret;
2478}
2479
2480#ifdef CONFIG_COMPAT
2481static long mmc_rpmb_ioctl_compat(struct file *filp, unsigned int cmd,
2482                              unsigned long arg)
2483{
2484        return mmc_rpmb_ioctl(filp, cmd, (unsigned long)compat_ptr(arg));
2485}
2486#endif
2487
2488static int mmc_rpmb_chrdev_open(struct inode *inode, struct file *filp)
2489{
2490        struct mmc_rpmb_data *rpmb = container_of(inode->i_cdev,
2491                                                  struct mmc_rpmb_data, chrdev);
2492
2493        get_device(&rpmb->dev);
2494        filp->private_data = rpmb;
2495        mmc_blk_get(rpmb->md->disk);
2496
2497        return nonseekable_open(inode, filp);
2498}
2499
2500static int mmc_rpmb_chrdev_release(struct inode *inode, struct file *filp)
2501{
2502        struct mmc_rpmb_data *rpmb = container_of(inode->i_cdev,
2503                                                  struct mmc_rpmb_data, chrdev);
2504
2505        put_device(&rpmb->dev);
2506        mmc_blk_put(rpmb->md);
2507
2508        return 0;
2509}
2510
2511static const struct file_operations mmc_rpmb_fileops = {
2512        .release = mmc_rpmb_chrdev_release,
2513        .open = mmc_rpmb_chrdev_open,
2514        .owner = THIS_MODULE,
2515        .llseek = no_llseek,
2516        .unlocked_ioctl = mmc_rpmb_ioctl,
2517#ifdef CONFIG_COMPAT
2518        .compat_ioctl = mmc_rpmb_ioctl_compat,
2519#endif
2520};
2521
2522static void mmc_blk_rpmb_device_release(struct device *dev)
2523{
2524        struct mmc_rpmb_data *rpmb = dev_get_drvdata(dev);
2525
2526        ida_simple_remove(&mmc_rpmb_ida, rpmb->id);
2527        kfree(rpmb);
2528}
2529
2530static int mmc_blk_alloc_rpmb_part(struct mmc_card *card,
2531                                   struct mmc_blk_data *md,
2532                                   unsigned int part_index,
2533                                   sector_t size,
2534                                   const char *subname)
2535{
2536        int devidx, ret;
2537        char rpmb_name[DISK_NAME_LEN];
2538        char cap_str[10];
2539        struct mmc_rpmb_data *rpmb;
2540
2541        /* This creates the minor number for the RPMB char device */
2542        devidx = ida_simple_get(&mmc_rpmb_ida, 0, max_devices, GFP_KERNEL);
2543        if (devidx < 0)
2544                return devidx;
2545
2546        rpmb = kzalloc(sizeof(*rpmb), GFP_KERNEL);
2547        if (!rpmb) {
2548                ida_simple_remove(&mmc_rpmb_ida, devidx);
2549                return -ENOMEM;
2550        }
2551
2552        snprintf(rpmb_name, sizeof(rpmb_name),
2553                 "mmcblk%u%s", card->host->index, subname ? subname : "");
2554
2555        rpmb->id = devidx;
2556        rpmb->part_index = part_index;
2557        rpmb->dev.init_name = rpmb_name;
2558        rpmb->dev.bus = &mmc_rpmb_bus_type;
2559        rpmb->dev.devt = MKDEV(MAJOR(mmc_rpmb_devt), rpmb->id);
2560        rpmb->dev.parent = &card->dev;
2561        rpmb->dev.release = mmc_blk_rpmb_device_release;
2562        device_initialize(&rpmb->dev);
2563        dev_set_drvdata(&rpmb->dev, rpmb);
2564        rpmb->md = md;
2565
2566        cdev_init(&rpmb->chrdev, &mmc_rpmb_fileops);
2567        rpmb->chrdev.owner = THIS_MODULE;
2568        ret = cdev_device_add(&rpmb->chrdev, &rpmb->dev);
2569        if (ret) {
2570                pr_err("%s: could not add character device\n", rpmb_name);
2571                goto out_put_device;
2572        }
2573
2574        list_add(&rpmb->node, &md->rpmbs);
2575
2576        string_get_size((u64)size, 512, STRING_UNITS_2,
2577                        cap_str, sizeof(cap_str));
2578
2579        pr_info("%s: %s %s partition %u %s, chardev (%d:%d)\n",
2580                rpmb_name, mmc_card_id(card),
2581                mmc_card_name(card), EXT_CSD_PART_CONFIG_ACC_RPMB, cap_str,
2582                MAJOR(mmc_rpmb_devt), rpmb->id);
2583
2584        return 0;
2585
2586out_put_device:
2587        put_device(&rpmb->dev);
2588        return ret;
2589}
2590
2591static void mmc_blk_remove_rpmb_part(struct mmc_rpmb_data *rpmb)
2592
2593{
2594        cdev_device_del(&rpmb->chrdev, &rpmb->dev);
2595        put_device(&rpmb->dev);
2596}
2597
2598/* MMC Physical partitions consist of two boot partitions and
2599 * up to four general purpose partitions.
2600 * For each partition enabled in EXT_CSD a block device will be allocatedi
2601 * to provide access to the partition.
2602 */
2603
2604static int mmc_blk_alloc_parts(struct mmc_card *card, struct mmc_blk_data *md)
2605{
2606        int idx, ret;
2607
2608        if (!mmc_card_mmc(card))
2609                return 0;
2610
2611        for (idx = 0; idx < card->nr_parts; idx++) {
2612                if (card->part[idx].area_type & MMC_BLK_DATA_AREA_RPMB) {
2613                        /*
2614                         * RPMB partitions does not provide block access, they
2615                         * are only accessed using ioctl():s. Thus create
2616                         * special RPMB block devices that do not have a
2617                         * backing block queue for these.
2618                         */
2619                        ret = mmc_blk_alloc_rpmb_part(card, md,
2620                                card->part[idx].part_cfg,
2621                                card->part[idx].size >> 9,
2622                                card->part[idx].name);
2623                        if (ret)
2624                                return ret;
2625                } else if (card->part[idx].size) {
2626                        ret = mmc_blk_alloc_part(card, md,
2627                                card->part[idx].part_cfg,
2628                                card->part[idx].size >> 9,
2629                                card->part[idx].force_ro,
2630                                card->part[idx].name,
2631                                card->part[idx].area_type);
2632                        if (ret)
2633                                return ret;
2634                }
2635        }
2636
2637        return 0;
2638}
2639
2640static void mmc_blk_remove_req(struct mmc_blk_data *md)
2641{
2642        struct mmc_card *card;
2643
2644        if (md) {
2645                /*
2646                 * Flush remaining requests and free queues. It
2647                 * is freeing the queue that stops new requests
2648                 * from being accepted.
2649                 */
2650                card = md->queue.card;
2651                if (md->disk->flags & GENHD_FL_UP) {
2652                        device_remove_file(disk_to_dev(md->disk), &md->force_ro);
2653                        if ((md->area_type & MMC_BLK_DATA_AREA_BOOT) &&
2654                                        card->ext_csd.boot_ro_lockable)
2655                                device_remove_file(disk_to_dev(md->disk),
2656                                        &md->power_ro_lock);
2657
2658                        del_gendisk(md->disk);
2659                }
2660                mmc_cleanup_queue(&md->queue);
2661                mmc_blk_put(md);
2662        }
2663}
2664
2665static void mmc_blk_remove_parts(struct mmc_card *card,
2666                                 struct mmc_blk_data *md)
2667{
2668        struct list_head *pos, *q;
2669        struct mmc_blk_data *part_md;
2670        struct mmc_rpmb_data *rpmb;
2671
2672        /* Remove RPMB partitions */
2673        list_for_each_safe(pos, q, &md->rpmbs) {
2674                rpmb = list_entry(pos, struct mmc_rpmb_data, node);
2675                list_del(pos);
2676                mmc_blk_remove_rpmb_part(rpmb);
2677        }
2678        /* Remove block partitions */
2679        list_for_each_safe(pos, q, &md->part) {
2680                part_md = list_entry(pos, struct mmc_blk_data, part);
2681                list_del(pos);
2682                mmc_blk_remove_req(part_md);
2683        }
2684}
2685
2686static int mmc_add_disk(struct mmc_blk_data *md)
2687{
2688        int ret;
2689        struct mmc_card *card = md->queue.card;
2690
2691        device_add_disk(md->parent, md->disk, NULL);
2692        md->force_ro.show = force_ro_show;
2693        md->force_ro.store = force_ro_store;
2694        sysfs_attr_init(&md->force_ro.attr);
2695        md->force_ro.attr.name = "force_ro";
2696        md->force_ro.attr.mode = S_IRUGO | S_IWUSR;
2697        ret = device_create_file(disk_to_dev(md->disk), &md->force_ro);
2698        if (ret)
2699                goto force_ro_fail;
2700
2701        if ((md->area_type & MMC_BLK_DATA_AREA_BOOT) &&
2702             card->ext_csd.boot_ro_lockable) {
2703                umode_t mode;
2704
2705                if (card->ext_csd.boot_ro_lock & EXT_CSD_BOOT_WP_B_PWR_WP_DIS)
2706                        mode = S_IRUGO;
2707                else
2708                        mode = S_IRUGO | S_IWUSR;
2709
2710                md->power_ro_lock.show = power_ro_lock_show;
2711                md->power_ro_lock.store = power_ro_lock_store;
2712                sysfs_attr_init(&md->power_ro_lock.attr);
2713                md->power_ro_lock.attr.mode = mode;
2714                md->power_ro_lock.attr.name =
2715                                        "ro_lock_until_next_power_on";
2716                ret = device_create_file(disk_to_dev(md->disk),
2717                                &md->power_ro_lock);
2718                if (ret)
2719                        goto power_ro_lock_fail;
2720        }
2721        return ret;
2722
2723power_ro_lock_fail:
2724        device_remove_file(disk_to_dev(md->disk), &md->force_ro);
2725force_ro_fail:
2726        del_gendisk(md->disk);
2727
2728        return ret;
2729}
2730
2731#ifdef CONFIG_DEBUG_FS
2732
2733static int mmc_dbg_card_status_get(void *data, u64 *val)
2734{
2735        struct mmc_card *card = data;
2736        struct mmc_blk_data *md = dev_get_drvdata(&card->dev);
2737        struct mmc_queue *mq = &md->queue;
2738        struct request *req;
2739        int ret;
2740
2741        /* Ask the block layer about the card status */
2742        req = blk_get_request(mq->queue, REQ_OP_DRV_IN, 0);
2743        if (IS_ERR(req))
2744                return PTR_ERR(req);
2745        req_to_mmc_queue_req(req)->drv_op = MMC_DRV_OP_GET_CARD_STATUS;
2746        blk_execute_rq(mq->queue, NULL, req, 0);
2747        ret = req_to_mmc_queue_req(req)->drv_op_result;
2748        if (ret >= 0) {
2749                *val = ret;
2750                ret = 0;
2751        }
2752        blk_put_request(req);
2753
2754        return ret;
2755}
2756DEFINE_SIMPLE_ATTRIBUTE(mmc_dbg_card_status_fops, mmc_dbg_card_status_get,
2757                NULL, "%08llx\n");
2758
2759/* That is two digits * 512 + 1 for newline */
2760#define EXT_CSD_STR_LEN 1025
2761
2762static int mmc_ext_csd_open(struct inode *inode, struct file *filp)
2763{
2764        struct mmc_card *card = inode->i_private;
2765        struct mmc_blk_data *md = dev_get_drvdata(&card->dev);
2766        struct mmc_queue *mq = &md->queue;
2767        struct request *req;
2768        char *buf;
2769        ssize_t n = 0;
2770        u8 *ext_csd;
2771        int err, i;
2772
2773        buf = kmalloc(EXT_CSD_STR_LEN + 1, GFP_KERNEL);
2774        if (!buf)
2775                return -ENOMEM;
2776
2777        /* Ask the block layer for the EXT CSD */
2778        req = blk_get_request(mq->queue, REQ_OP_DRV_IN, 0);
2779        if (IS_ERR(req)) {
2780                err = PTR_ERR(req);
2781                goto out_free;
2782        }
2783        req_to_mmc_queue_req(req)->drv_op = MMC_DRV_OP_GET_EXT_CSD;
2784        req_to_mmc_queue_req(req)->drv_op_data = &ext_csd;
2785        blk_execute_rq(mq->queue, NULL, req, 0);
2786        err = req_to_mmc_queue_req(req)->drv_op_result;
2787        blk_put_request(req);
2788        if (err) {
2789                pr_err("FAILED %d\n", err);
2790                goto out_free;
2791        }
2792
2793        for (i = 0; i < 512; i++)
2794                n += sprintf(buf + n, "%02x", ext_csd[i]);
2795        n += sprintf(buf + n, "\n");
2796
2797        if (n != EXT_CSD_STR_LEN) {
2798                err = -EINVAL;
2799                kfree(ext_csd);
2800                goto out_free;
2801        }
2802
2803        filp->private_data = buf;
2804        kfree(ext_csd);
2805        return 0;
2806
2807out_free:
2808        kfree(buf);
2809        return err;
2810}
2811
2812static ssize_t mmc_ext_csd_read(struct file *filp, char __user *ubuf,
2813                                size_t cnt, loff_t *ppos)
2814{
2815        char *buf = filp->private_data;
2816
2817        return simple_read_from_buffer(ubuf, cnt, ppos,
2818                                       buf, EXT_CSD_STR_LEN);
2819}
2820
2821static int mmc_ext_csd_release(struct inode *inode, struct file *file)
2822{
2823        kfree(file->private_data);
2824        return 0;
2825}
2826
2827static const struct file_operations mmc_dbg_ext_csd_fops = {
2828        .open           = mmc_ext_csd_open,
2829        .read           = mmc_ext_csd_read,
2830        .release        = mmc_ext_csd_release,
2831        .llseek         = default_llseek,
2832};
2833
2834static int mmc_blk_add_debugfs(struct mmc_card *card, struct mmc_blk_data *md)
2835{
2836        struct dentry *root;
2837
2838        if (!card->debugfs_root)
2839                return 0;
2840
2841        root = card->debugfs_root;
2842
2843        if (mmc_card_mmc(card) || mmc_card_sd(card)) {
2844                md->status_dentry =
2845                        debugfs_create_file("status", S_IRUSR, root, card,
2846                                            &mmc_dbg_card_status_fops);
2847                if (!md->status_dentry)
2848                        return -EIO;
2849        }
2850
2851        if (mmc_card_mmc(card)) {
2852                md->ext_csd_dentry =
2853                        debugfs_create_file("ext_csd", S_IRUSR, root, card,
2854                                            &mmc_dbg_ext_csd_fops);
2855                if (!md->ext_csd_dentry)
2856                        return -EIO;
2857        }
2858
2859        return 0;
2860}
2861
2862static void mmc_blk_remove_debugfs(struct mmc_card *card,
2863                                   struct mmc_blk_data *md)
2864{
2865        if (!card->debugfs_root)
2866                return;
2867
2868        if (!IS_ERR_OR_NULL(md->status_dentry)) {
2869                debugfs_remove(md->status_dentry);
2870                md->status_dentry = NULL;
2871        }
2872
2873        if (!IS_ERR_OR_NULL(md->ext_csd_dentry)) {
2874                debugfs_remove(md->ext_csd_dentry);
2875                md->ext_csd_dentry = NULL;
2876        }
2877}
2878
2879#else
2880
2881static int mmc_blk_add_debugfs(struct mmc_card *card, struct mmc_blk_data *md)
2882{
2883        return 0;
2884}
2885
2886static void mmc_blk_remove_debugfs(struct mmc_card *card,
2887                                   struct mmc_blk_data *md)
2888{
2889}
2890
2891#endif /* CONFIG_DEBUG_FS */
2892
2893static int mmc_blk_probe(struct mmc_card *card)
2894{
2895        struct mmc_blk_data *md, *part_md;
2896        char cap_str[10];
2897
2898        /*
2899         * Check that the card supports the command class(es) we need.
2900         */
2901        if (!(card->csd.cmdclass & CCC_BLOCK_READ))
2902                return -ENODEV;
2903
2904        mmc_fixup_device(card, mmc_blk_fixups);
2905
2906        md = mmc_blk_alloc(card);
2907        if (IS_ERR(md))
2908                return PTR_ERR(md);
2909
2910        string_get_size((u64)get_capacity(md->disk), 512, STRING_UNITS_2,
2911                        cap_str, sizeof(cap_str));
2912        pr_info("%s: %s %s %s %s\n",
2913                md->disk->disk_name, mmc_card_id(card), mmc_card_name(card),
2914                cap_str, md->read_only ? "(ro)" : "");
2915
2916        if (mmc_blk_alloc_parts(card, md))
2917                goto out;
2918
2919        dev_set_drvdata(&card->dev, md);
2920
2921        if (mmc_add_disk(md))
2922                goto out;
2923
2924        list_for_each_entry(part_md, &md->part, part) {
2925                if (mmc_add_disk(part_md))
2926                        goto out;
2927        }
2928
2929        /* Add two debugfs entries */
2930        mmc_blk_add_debugfs(card, md);
2931
2932        pm_runtime_set_autosuspend_delay(&card->dev, 3000);
2933        pm_runtime_use_autosuspend(&card->dev);
2934
2935        /*
2936         * Don't enable runtime PM for SD-combo cards here. Leave that
2937         * decision to be taken during the SDIO init sequence instead.
2938         */
2939        if (card->type != MMC_TYPE_SD_COMBO) {
2940                pm_runtime_set_active(&card->dev);
2941                pm_runtime_enable(&card->dev);
2942        }
2943
2944        return 0;
2945
2946 out:
2947        mmc_blk_remove_parts(card, md);
2948        mmc_blk_remove_req(md);
2949        return 0;
2950}
2951
2952static void mmc_blk_remove(struct mmc_card *card)
2953{
2954        struct mmc_blk_data *md = dev_get_drvdata(&card->dev);
2955
2956        mmc_blk_remove_debugfs(card, md);
2957        mmc_blk_remove_parts(card, md);
2958        pm_runtime_get_sync(&card->dev);
2959        if (md->part_curr != md->part_type) {
2960                mmc_claim_host(card->host);
2961                mmc_blk_part_switch(card, md->part_type);
2962                mmc_release_host(card->host);
2963        }
2964        if (card->type != MMC_TYPE_SD_COMBO)
2965                pm_runtime_disable(&card->dev);
2966        pm_runtime_put_noidle(&card->dev);
2967        mmc_blk_remove_req(md);
2968        dev_set_drvdata(&card->dev, NULL);
2969}
2970
2971static int _mmc_blk_suspend(struct mmc_card *card)
2972{
2973        struct mmc_blk_data *part_md;
2974        struct mmc_blk_data *md = dev_get_drvdata(&card->dev);
2975
2976        if (md) {
2977                mmc_queue_suspend(&md->queue);
2978                list_for_each_entry(part_md, &md->part, part) {
2979                        mmc_queue_suspend(&part_md->queue);
2980                }
2981        }
2982        return 0;
2983}
2984
2985static void mmc_blk_shutdown(struct mmc_card *card)
2986{
2987        _mmc_blk_suspend(card);
2988}
2989
2990#ifdef CONFIG_PM_SLEEP
2991static int mmc_blk_suspend(struct device *dev)
2992{
2993        struct mmc_card *card = mmc_dev_to_card(dev);
2994
2995        return _mmc_blk_suspend(card);
2996}
2997
2998static int mmc_blk_resume(struct device *dev)
2999{
3000        struct mmc_blk_data *part_md;
3001        struct mmc_blk_data *md = dev_get_drvdata(dev);
3002
3003        if (md) {
3004                /*
3005                 * Resume involves the card going into idle state,
3006                 * so current partition is always the main one.
3007                 */
3008                md->part_curr = md->part_type;
3009                mmc_queue_resume(&md->queue);
3010                list_for_each_entry(part_md, &md->part, part) {
3011                        mmc_queue_resume(&part_md->queue);
3012                }
3013        }
3014        return 0;
3015}
3016#endif
3017
3018static SIMPLE_DEV_PM_OPS(mmc_blk_pm_ops, mmc_blk_suspend, mmc_blk_resume);
3019
3020static struct mmc_driver mmc_driver = {
3021        .drv            = {
3022                .name   = "mmcblk",
3023                .pm     = &mmc_blk_pm_ops,
3024        },
3025        .probe          = mmc_blk_probe,
3026        .remove         = mmc_blk_remove,
3027        .shutdown       = mmc_blk_shutdown,
3028};
3029
3030static int __init mmc_blk_init(void)
3031{
3032        int res;
3033
3034        res  = bus_register(&mmc_rpmb_bus_type);
3035        if (res < 0) {
3036                pr_err("mmcblk: could not register RPMB bus type\n");
3037                return res;
3038        }
3039        res = alloc_chrdev_region(&mmc_rpmb_devt, 0, MAX_DEVICES, "rpmb");
3040        if (res < 0) {
3041                pr_err("mmcblk: failed to allocate rpmb chrdev region\n");
3042                goto out_bus_unreg;
3043        }
3044
3045        if (perdev_minors != CONFIG_MMC_BLOCK_MINORS)
3046                pr_info("mmcblk: using %d minors per device\n", perdev_minors);
3047
3048        max_devices = min(MAX_DEVICES, (1 << MINORBITS) / perdev_minors);
3049
3050        res = register_blkdev(MMC_BLOCK_MAJOR, "mmc");
3051        if (res)
3052                goto out_chrdev_unreg;
3053
3054        res = mmc_register_driver(&mmc_driver);
3055        if (res)
3056                goto out_blkdev_unreg;
3057
3058        return 0;
3059
3060out_blkdev_unreg:
3061        unregister_blkdev(MMC_BLOCK_MAJOR, "mmc");
3062out_chrdev_unreg:
3063        unregister_chrdev_region(mmc_rpmb_devt, MAX_DEVICES);
3064out_bus_unreg:
3065        bus_unregister(&mmc_rpmb_bus_type);
3066        return res;
3067}
3068
3069static void __exit mmc_blk_exit(void)
3070{
3071        mmc_unregister_driver(&mmc_driver);
3072        unregister_blkdev(MMC_BLOCK_MAJOR, "mmc");
3073        unregister_chrdev_region(mmc_rpmb_devt, MAX_DEVICES);
3074        bus_unregister(&mmc_rpmb_bus_type);
3075}
3076
3077module_init(mmc_blk_init);
3078module_exit(mmc_blk_exit);
3079
3080MODULE_LICENSE("GPL");
3081MODULE_DESCRIPTION("Multimedia Card (MMC) block device driver");
3082
3083