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