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