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