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