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