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