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