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