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