mmc: dw_mmc: remove the unnecessary slot variable
[muen/linux.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/mutex.h>
32 #include <linux/scatterlist.h>
33 #include <linux/string_helpers.h>
34 #include <linux/delay.h>
35 #include <linux/capability.h>
36 #include <linux/compat.h>
37 #include <linux/pm_runtime.h>
38 #include <linux/idr.h>
39
40 #include <linux/mmc/ioctl.h>
41 #include <linux/mmc/card.h>
42 #include <linux/mmc/host.h>
43 #include <linux/mmc/mmc.h>
44 #include <linux/mmc/sd.h>
45
46 #include <linux/uaccess.h>
47
48 #include "queue.h"
49 #include "block.h"
50 #include "core.h"
51 #include "card.h"
52 #include "host.h"
53 #include "bus.h"
54 #include "mmc_ops.h"
55 #include "quirks.h"
56 #include "sd_ops.h"
57
58 MODULE_ALIAS("mmc:block");
59 #ifdef MODULE_PARAM_PREFIX
60 #undef MODULE_PARAM_PREFIX
61 #endif
62 #define MODULE_PARAM_PREFIX "mmcblk."
63
64 #define MMC_BLK_TIMEOUT_MS  (10 * 60 * 1000)        /* 10 minute timeout */
65 #define MMC_SANITIZE_REQ_TIMEOUT 240000
66 #define MMC_EXTRACT_INDEX_FROM_ARG(x) ((x & 0x00FF0000) >> 16)
67
68 #define mmc_req_rel_wr(req)     ((req->cmd_flags & REQ_FUA) && \
69                                   (rq_data_dir(req) == WRITE))
70 static DEFINE_MUTEX(block_mutex);
71
72 /*
73  * The defaults come from config options but can be overriden by module
74  * or bootarg options.
75  */
76 static int perdev_minors = CONFIG_MMC_BLOCK_MINORS;
77
78 /*
79  * We've only got one major, so number of mmcblk devices is
80  * limited to (1 << 20) / number of minors per device.  It is also
81  * limited by the MAX_DEVICES below.
82  */
83 static int max_devices;
84
85 #define MAX_DEVICES 256
86
87 static DEFINE_IDA(mmc_blk_ida);
88
89 /*
90  * There is one mmc_blk_data per slot.
91  */
92 struct mmc_blk_data {
93         spinlock_t      lock;
94         struct device   *parent;
95         struct gendisk  *disk;
96         struct mmc_queue queue;
97         struct list_head part;
98
99         unsigned int    flags;
100 #define MMC_BLK_CMD23   (1 << 0)        /* Can do SET_BLOCK_COUNT for multiblock */
101 #define MMC_BLK_REL_WR  (1 << 1)        /* MMC Reliable write support */
102
103         unsigned int    usage;
104         unsigned int    read_only;
105         unsigned int    part_type;
106         unsigned int    reset_done;
107 #define MMC_BLK_READ            BIT(0)
108 #define MMC_BLK_WRITE           BIT(1)
109 #define MMC_BLK_DISCARD         BIT(2)
110 #define MMC_BLK_SECDISCARD      BIT(3)
111
112         /*
113          * Only set in main mmc_blk_data associated
114          * with mmc_card with dev_set_drvdata, and keeps
115          * track of the current selected device partition.
116          */
117         unsigned int    part_curr;
118         struct device_attribute force_ro;
119         struct device_attribute power_ro_lock;
120         int     area_type;
121 };
122
123 static DEFINE_MUTEX(open_lock);
124
125 module_param(perdev_minors, int, 0444);
126 MODULE_PARM_DESC(perdev_minors, "Minors numbers to allocate per device");
127
128 static inline int mmc_blk_part_switch(struct mmc_card *card,
129                                       struct mmc_blk_data *md);
130
131 static struct mmc_blk_data *mmc_blk_get(struct gendisk *disk)
132 {
133         struct mmc_blk_data *md;
134
135         mutex_lock(&open_lock);
136         md = disk->private_data;
137         if (md && md->usage == 0)
138                 md = NULL;
139         if (md)
140                 md->usage++;
141         mutex_unlock(&open_lock);
142
143         return md;
144 }
145
146 static inline int mmc_get_devidx(struct gendisk *disk)
147 {
148         int devidx = disk->first_minor / perdev_minors;
149         return devidx;
150 }
151
152 static void mmc_blk_put(struct mmc_blk_data *md)
153 {
154         mutex_lock(&open_lock);
155         md->usage--;
156         if (md->usage == 0) {
157                 int devidx = mmc_get_devidx(md->disk);
158                 blk_cleanup_queue(md->queue.queue);
159                 ida_simple_remove(&mmc_blk_ida, devidx);
160                 put_disk(md->disk);
161                 kfree(md);
162         }
163         mutex_unlock(&open_lock);
164 }
165
166 static ssize_t power_ro_lock_show(struct device *dev,
167                 struct device_attribute *attr, char *buf)
168 {
169         int ret;
170         struct mmc_blk_data *md = mmc_blk_get(dev_to_disk(dev));
171         struct mmc_card *card = md->queue.card;
172         int locked = 0;
173
174         if (card->ext_csd.boot_ro_lock & EXT_CSD_BOOT_WP_B_PERM_WP_EN)
175                 locked = 2;
176         else if (card->ext_csd.boot_ro_lock & EXT_CSD_BOOT_WP_B_PWR_WP_EN)
177                 locked = 1;
178
179         ret = snprintf(buf, PAGE_SIZE, "%d\n", locked);
180
181         mmc_blk_put(md);
182
183         return ret;
184 }
185
186 static ssize_t power_ro_lock_store(struct device *dev,
187                 struct device_attribute *attr, const char *buf, size_t count)
188 {
189         int ret;
190         struct mmc_blk_data *md, *part_md;
191         struct mmc_card *card;
192         struct mmc_queue *mq;
193         struct request *req;
194         unsigned long set;
195
196         if (kstrtoul(buf, 0, &set))
197                 return -EINVAL;
198
199         if (set != 1)
200                 return count;
201
202         md = mmc_blk_get(dev_to_disk(dev));
203         mq = &md->queue;
204         card = md->queue.card;
205
206         /* Dispatch locking to the block layer */
207         req = blk_get_request(mq->queue, REQ_OP_DRV_OUT, __GFP_RECLAIM);
208         req_to_mmc_queue_req(req)->drv_op = MMC_DRV_OP_BOOT_WP;
209         blk_execute_rq(mq->queue, NULL, req, 0);
210         ret = req_to_mmc_queue_req(req)->drv_op_result;
211
212         if (!ret) {
213                 pr_info("%s: Locking boot partition ro until next power on\n",
214                         md->disk->disk_name);
215                 set_disk_ro(md->disk, 1);
216
217                 list_for_each_entry(part_md, &md->part, part)
218                         if (part_md->area_type == MMC_BLK_DATA_AREA_BOOT) {
219                                 pr_info("%s: Locking boot partition ro until next power on\n", part_md->disk->disk_name);
220                                 set_disk_ro(part_md->disk, 1);
221                         }
222         }
223
224         mmc_blk_put(md);
225         return count;
226 }
227
228 static ssize_t force_ro_show(struct device *dev, struct device_attribute *attr,
229                              char *buf)
230 {
231         int ret;
232         struct mmc_blk_data *md = mmc_blk_get(dev_to_disk(dev));
233
234         ret = snprintf(buf, PAGE_SIZE, "%d\n",
235                        get_disk_ro(dev_to_disk(dev)) ^
236                        md->read_only);
237         mmc_blk_put(md);
238         return ret;
239 }
240
241 static ssize_t force_ro_store(struct device *dev, struct device_attribute *attr,
242                               const char *buf, size_t count)
243 {
244         int ret;
245         char *end;
246         struct mmc_blk_data *md = mmc_blk_get(dev_to_disk(dev));
247         unsigned long set = simple_strtoul(buf, &end, 0);
248         if (end == buf) {
249                 ret = -EINVAL;
250                 goto out;
251         }
252
253         set_disk_ro(dev_to_disk(dev), set || md->read_only);
254         ret = count;
255 out:
256         mmc_blk_put(md);
257         return ret;
258 }
259
260 static int mmc_blk_open(struct block_device *bdev, fmode_t mode)
261 {
262         struct mmc_blk_data *md = mmc_blk_get(bdev->bd_disk);
263         int ret = -ENXIO;
264
265         mutex_lock(&block_mutex);
266         if (md) {
267                 if (md->usage == 2)
268                         check_disk_change(bdev);
269                 ret = 0;
270
271                 if ((mode & FMODE_WRITE) && md->read_only) {
272                         mmc_blk_put(md);
273                         ret = -EROFS;
274                 }
275         }
276         mutex_unlock(&block_mutex);
277
278         return ret;
279 }
280
281 static void mmc_blk_release(struct gendisk *disk, fmode_t mode)
282 {
283         struct mmc_blk_data *md = disk->private_data;
284
285         mutex_lock(&block_mutex);
286         mmc_blk_put(md);
287         mutex_unlock(&block_mutex);
288 }
289
290 static int
291 mmc_blk_getgeo(struct block_device *bdev, struct hd_geometry *geo)
292 {
293         geo->cylinders = get_capacity(bdev->bd_disk) / (4 * 16);
294         geo->heads = 4;
295         geo->sectors = 16;
296         return 0;
297 }
298
299 struct mmc_blk_ioc_data {
300         struct mmc_ioc_cmd ic;
301         unsigned char *buf;
302         u64 buf_bytes;
303 };
304
305 static struct mmc_blk_ioc_data *mmc_blk_ioctl_copy_from_user(
306         struct mmc_ioc_cmd __user *user)
307 {
308         struct mmc_blk_ioc_data *idata;
309         int err;
310
311         idata = kmalloc(sizeof(*idata), GFP_KERNEL);
312         if (!idata) {
313                 err = -ENOMEM;
314                 goto out;
315         }
316
317         if (copy_from_user(&idata->ic, user, sizeof(idata->ic))) {
318                 err = -EFAULT;
319                 goto idata_err;
320         }
321
322         idata->buf_bytes = (u64) idata->ic.blksz * idata->ic.blocks;
323         if (idata->buf_bytes > MMC_IOC_MAX_BYTES) {
324                 err = -EOVERFLOW;
325                 goto idata_err;
326         }
327
328         if (!idata->buf_bytes) {
329                 idata->buf = NULL;
330                 return idata;
331         }
332
333         idata->buf = kmalloc(idata->buf_bytes, GFP_KERNEL);
334         if (!idata->buf) {
335                 err = -ENOMEM;
336                 goto idata_err;
337         }
338
339         if (copy_from_user(idata->buf, (void __user *)(unsigned long)
340                                         idata->ic.data_ptr, idata->buf_bytes)) {
341                 err = -EFAULT;
342                 goto copy_err;
343         }
344
345         return idata;
346
347 copy_err:
348         kfree(idata->buf);
349 idata_err:
350         kfree(idata);
351 out:
352         return ERR_PTR(err);
353 }
354
355 static int mmc_blk_ioctl_copy_to_user(struct mmc_ioc_cmd __user *ic_ptr,
356                                       struct mmc_blk_ioc_data *idata)
357 {
358         struct mmc_ioc_cmd *ic = &idata->ic;
359
360         if (copy_to_user(&(ic_ptr->response), ic->response,
361                          sizeof(ic->response)))
362                 return -EFAULT;
363
364         if (!idata->ic.write_flag) {
365                 if (copy_to_user((void __user *)(unsigned long)ic->data_ptr,
366                                  idata->buf, idata->buf_bytes))
367                         return -EFAULT;
368         }
369
370         return 0;
371 }
372
373 static int ioctl_rpmb_card_status_poll(struct mmc_card *card, u32 *status,
374                                        u32 retries_max)
375 {
376         int err;
377         u32 retry_count = 0;
378
379         if (!status || !retries_max)
380                 return -EINVAL;
381
382         do {
383                 err = __mmc_send_status(card, status, 5);
384                 if (err)
385                         break;
386
387                 if (!R1_STATUS(*status) &&
388                                 (R1_CURRENT_STATE(*status) != R1_STATE_PRG))
389                         break; /* RPMB programming operation complete */
390
391                 /*
392                  * Rechedule to give the MMC device a chance to continue
393                  * processing the previous command without being polled too
394                  * frequently.
395                  */
396                 usleep_range(1000, 5000);
397         } while (++retry_count < retries_max);
398
399         if (retry_count == retries_max)
400                 err = -EPERM;
401
402         return err;
403 }
404
405 static int ioctl_do_sanitize(struct mmc_card *card)
406 {
407         int err;
408
409         if (!mmc_can_sanitize(card)) {
410                         pr_warn("%s: %s - SANITIZE is not supported\n",
411                                 mmc_hostname(card->host), __func__);
412                         err = -EOPNOTSUPP;
413                         goto out;
414         }
415
416         pr_debug("%s: %s - SANITIZE IN PROGRESS...\n",
417                 mmc_hostname(card->host), __func__);
418
419         err = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL,
420                                         EXT_CSD_SANITIZE_START, 1,
421                                         MMC_SANITIZE_REQ_TIMEOUT);
422
423         if (err)
424                 pr_err("%s: %s - EXT_CSD_SANITIZE_START failed. err=%d\n",
425                        mmc_hostname(card->host), __func__, err);
426
427         pr_debug("%s: %s - SANITIZE COMPLETED\n", mmc_hostname(card->host),
428                                              __func__);
429 out:
430         return err;
431 }
432
433 static int __mmc_blk_ioctl_cmd(struct mmc_card *card, struct mmc_blk_data *md,
434                                struct mmc_blk_ioc_data *idata)
435 {
436         struct mmc_command cmd = {};
437         struct mmc_data data = {};
438         struct mmc_request mrq = {};
439         struct scatterlist sg;
440         int err;
441         bool is_rpmb = false;
442         u32 status = 0;
443
444         if (!card || !md || !idata)
445                 return -EINVAL;
446
447         if (md->area_type & MMC_BLK_DATA_AREA_RPMB)
448                 is_rpmb = true;
449
450         cmd.opcode = idata->ic.opcode;
451         cmd.arg = idata->ic.arg;
452         cmd.flags = idata->ic.flags;
453
454         if (idata->buf_bytes) {
455                 data.sg = &sg;
456                 data.sg_len = 1;
457                 data.blksz = idata->ic.blksz;
458                 data.blocks = idata->ic.blocks;
459
460                 sg_init_one(data.sg, idata->buf, idata->buf_bytes);
461
462                 if (idata->ic.write_flag)
463                         data.flags = MMC_DATA_WRITE;
464                 else
465                         data.flags = MMC_DATA_READ;
466
467                 /* data.flags must already be set before doing this. */
468                 mmc_set_data_timeout(&data, card);
469
470                 /* Allow overriding the timeout_ns for empirical tuning. */
471                 if (idata->ic.data_timeout_ns)
472                         data.timeout_ns = idata->ic.data_timeout_ns;
473
474                 if ((cmd.flags & MMC_RSP_R1B) == MMC_RSP_R1B) {
475                         /*
476                          * Pretend this is a data transfer and rely on the
477                          * host driver to compute timeout.  When all host
478                          * drivers support cmd.cmd_timeout for R1B, this
479                          * can be changed to:
480                          *
481                          *     mrq.data = NULL;
482                          *     cmd.cmd_timeout = idata->ic.cmd_timeout_ms;
483                          */
484                         data.timeout_ns = idata->ic.cmd_timeout_ms * 1000000;
485                 }
486
487                 mrq.data = &data;
488         }
489
490         mrq.cmd = &cmd;
491
492         err = mmc_blk_part_switch(card, md);
493         if (err)
494                 return err;
495
496         if (idata->ic.is_acmd) {
497                 err = mmc_app_cmd(card->host, card);
498                 if (err)
499                         return err;
500         }
501
502         if (is_rpmb) {
503                 err = mmc_set_blockcount(card, data.blocks,
504                         idata->ic.write_flag & (1 << 31));
505                 if (err)
506                         return err;
507         }
508
509         if ((MMC_EXTRACT_INDEX_FROM_ARG(cmd.arg) == EXT_CSD_SANITIZE_START) &&
510             (cmd.opcode == MMC_SWITCH)) {
511                 err = ioctl_do_sanitize(card);
512
513                 if (err)
514                         pr_err("%s: ioctl_do_sanitize() failed. err = %d",
515                                __func__, err);
516
517                 return err;
518         }
519
520         mmc_wait_for_req(card->host, &mrq);
521
522         if (cmd.error) {
523                 dev_err(mmc_dev(card->host), "%s: cmd error %d\n",
524                                                 __func__, cmd.error);
525                 return cmd.error;
526         }
527         if (data.error) {
528                 dev_err(mmc_dev(card->host), "%s: data error %d\n",
529                                                 __func__, data.error);
530                 return data.error;
531         }
532
533         /*
534          * According to the SD specs, some commands require a delay after
535          * issuing the command.
536          */
537         if (idata->ic.postsleep_min_us)
538                 usleep_range(idata->ic.postsleep_min_us, idata->ic.postsleep_max_us);
539
540         memcpy(&(idata->ic.response), cmd.resp, sizeof(cmd.resp));
541
542         if (is_rpmb) {
543                 /*
544                  * Ensure RPMB command has completed by polling CMD13
545                  * "Send Status".
546                  */
547                 err = ioctl_rpmb_card_status_poll(card, &status, 5);
548                 if (err)
549                         dev_err(mmc_dev(card->host),
550                                         "%s: Card Status=0x%08X, error %d\n",
551                                         __func__, status, err);
552         }
553
554         return err;
555 }
556
557 static int mmc_blk_ioctl_cmd(struct block_device *bdev,
558                              struct mmc_ioc_cmd __user *ic_ptr)
559 {
560         struct mmc_blk_ioc_data *idata;
561         struct mmc_blk_ioc_data *idatas[1];
562         struct mmc_blk_data *md;
563         struct mmc_queue *mq;
564         struct mmc_card *card;
565         int err = 0, ioc_err = 0;
566         struct request *req;
567
568         /*
569          * The caller must have CAP_SYS_RAWIO, and must be calling this on the
570          * whole block device, not on a partition.  This prevents overspray
571          * between sibling partitions.
572          */
573         if ((!capable(CAP_SYS_RAWIO)) || (bdev != bdev->bd_contains))
574                 return -EPERM;
575
576         idata = mmc_blk_ioctl_copy_from_user(ic_ptr);
577         if (IS_ERR(idata))
578                 return PTR_ERR(idata);
579
580         md = mmc_blk_get(bdev->bd_disk);
581         if (!md) {
582                 err = -EINVAL;
583                 goto cmd_err;
584         }
585
586         card = md->queue.card;
587         if (IS_ERR(card)) {
588                 err = PTR_ERR(card);
589                 goto cmd_done;
590         }
591
592         /*
593          * Dispatch the ioctl() into the block request queue.
594          */
595         mq = &md->queue;
596         req = blk_get_request(mq->queue,
597                 idata->ic.write_flag ? REQ_OP_DRV_OUT : REQ_OP_DRV_IN,
598                 __GFP_RECLAIM);
599         idatas[0] = idata;
600         req_to_mmc_queue_req(req)->drv_op = MMC_DRV_OP_IOCTL;
601         req_to_mmc_queue_req(req)->idata = idatas;
602         req_to_mmc_queue_req(req)->ioc_count = 1;
603         blk_execute_rq(mq->queue, NULL, req, 0);
604         ioc_err = req_to_mmc_queue_req(req)->drv_op_result;
605         err = mmc_blk_ioctl_copy_to_user(ic_ptr, idata);
606         blk_put_request(req);
607
608 cmd_done:
609         mmc_blk_put(md);
610 cmd_err:
611         kfree(idata->buf);
612         kfree(idata);
613         return ioc_err ? ioc_err : err;
614 }
615
616 static int mmc_blk_ioctl_multi_cmd(struct block_device *bdev,
617                                    struct mmc_ioc_multi_cmd __user *user)
618 {
619         struct mmc_blk_ioc_data **idata = NULL;
620         struct mmc_ioc_cmd __user *cmds = user->cmds;
621         struct mmc_card *card;
622         struct mmc_blk_data *md;
623         struct mmc_queue *mq;
624         int i, err = 0, ioc_err = 0;
625         __u64 num_of_cmds;
626         struct request *req;
627
628         /*
629          * The caller must have CAP_SYS_RAWIO, and must be calling this on the
630          * whole block device, not on a partition.  This prevents overspray
631          * between sibling partitions.
632          */
633         if ((!capable(CAP_SYS_RAWIO)) || (bdev != bdev->bd_contains))
634                 return -EPERM;
635
636         if (copy_from_user(&num_of_cmds, &user->num_of_cmds,
637                            sizeof(num_of_cmds)))
638                 return -EFAULT;
639
640         if (num_of_cmds > MMC_IOC_MAX_CMDS)
641                 return -EINVAL;
642
643         idata = kcalloc(num_of_cmds, sizeof(*idata), GFP_KERNEL);
644         if (!idata)
645                 return -ENOMEM;
646
647         for (i = 0; i < num_of_cmds; i++) {
648                 idata[i] = mmc_blk_ioctl_copy_from_user(&cmds[i]);
649                 if (IS_ERR(idata[i])) {
650                         err = PTR_ERR(idata[i]);
651                         num_of_cmds = i;
652                         goto cmd_err;
653                 }
654         }
655
656         md = mmc_blk_get(bdev->bd_disk);
657         if (!md) {
658                 err = -EINVAL;
659                 goto cmd_err;
660         }
661
662         card = md->queue.card;
663         if (IS_ERR(card)) {
664                 err = PTR_ERR(card);
665                 goto cmd_done;
666         }
667
668
669         /*
670          * Dispatch the ioctl()s into the block request queue.
671          */
672         mq = &md->queue;
673         req = blk_get_request(mq->queue,
674                 idata[0]->ic.write_flag ? REQ_OP_DRV_OUT : REQ_OP_DRV_IN,
675                 __GFP_RECLAIM);
676         req_to_mmc_queue_req(req)->drv_op = MMC_DRV_OP_IOCTL;
677         req_to_mmc_queue_req(req)->idata = idata;
678         req_to_mmc_queue_req(req)->ioc_count = num_of_cmds;
679         blk_execute_rq(mq->queue, NULL, req, 0);
680         ioc_err = req_to_mmc_queue_req(req)->drv_op_result;
681
682         /* copy to user if data and response */
683         for (i = 0; i < num_of_cmds && !err; i++)
684                 err = mmc_blk_ioctl_copy_to_user(&cmds[i], idata[i]);
685
686         blk_put_request(req);
687
688 cmd_done:
689         mmc_blk_put(md);
690 cmd_err:
691         for (i = 0; i < num_of_cmds; i++) {
692                 kfree(idata[i]->buf);
693                 kfree(idata[i]);
694         }
695         kfree(idata);
696         return ioc_err ? ioc_err : err;
697 }
698
699 static int mmc_blk_ioctl(struct block_device *bdev, fmode_t mode,
700         unsigned int cmd, unsigned long arg)
701 {
702         switch (cmd) {
703         case MMC_IOC_CMD:
704                 return mmc_blk_ioctl_cmd(bdev,
705                                 (struct mmc_ioc_cmd __user *)arg);
706         case MMC_IOC_MULTI_CMD:
707                 return mmc_blk_ioctl_multi_cmd(bdev,
708                                 (struct mmc_ioc_multi_cmd __user *)arg);
709         default:
710                 return -EINVAL;
711         }
712 }
713
714 #ifdef CONFIG_COMPAT
715 static int mmc_blk_compat_ioctl(struct block_device *bdev, fmode_t mode,
716         unsigned int cmd, unsigned long arg)
717 {
718         return mmc_blk_ioctl(bdev, mode, cmd, (unsigned long) compat_ptr(arg));
719 }
720 #endif
721
722 static const struct block_device_operations mmc_bdops = {
723         .open                   = mmc_blk_open,
724         .release                = mmc_blk_release,
725         .getgeo                 = mmc_blk_getgeo,
726         .owner                  = THIS_MODULE,
727         .ioctl                  = mmc_blk_ioctl,
728 #ifdef CONFIG_COMPAT
729         .compat_ioctl           = mmc_blk_compat_ioctl,
730 #endif
731 };
732
733 static int mmc_blk_part_switch_pre(struct mmc_card *card,
734                                    unsigned int part_type)
735 {
736         int ret = 0;
737
738         if (part_type == EXT_CSD_PART_CONFIG_ACC_RPMB) {
739                 if (card->ext_csd.cmdq_en) {
740                         ret = mmc_cmdq_disable(card);
741                         if (ret)
742                                 return ret;
743                 }
744                 mmc_retune_pause(card->host);
745         }
746
747         return ret;
748 }
749
750 static int mmc_blk_part_switch_post(struct mmc_card *card,
751                                     unsigned int part_type)
752 {
753         int ret = 0;
754
755         if (part_type == EXT_CSD_PART_CONFIG_ACC_RPMB) {
756                 mmc_retune_unpause(card->host);
757                 if (card->reenable_cmdq && !card->ext_csd.cmdq_en)
758                         ret = mmc_cmdq_enable(card);
759         }
760
761         return ret;
762 }
763
764 static inline int mmc_blk_part_switch(struct mmc_card *card,
765                                       struct mmc_blk_data *md)
766 {
767         int ret = 0;
768         struct mmc_blk_data *main_md = dev_get_drvdata(&card->dev);
769
770         if (main_md->part_curr == md->part_type)
771                 return 0;
772
773         if (mmc_card_mmc(card)) {
774                 u8 part_config = card->ext_csd.part_config;
775
776                 ret = mmc_blk_part_switch_pre(card, md->part_type);
777                 if (ret)
778                         return ret;
779
780                 part_config &= ~EXT_CSD_PART_CONFIG_ACC_MASK;
781                 part_config |= md->part_type;
782
783                 ret = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL,
784                                  EXT_CSD_PART_CONFIG, part_config,
785                                  card->ext_csd.part_time);
786                 if (ret) {
787                         mmc_blk_part_switch_post(card, md->part_type);
788                         return ret;
789                 }
790
791                 card->ext_csd.part_config = part_config;
792
793                 ret = mmc_blk_part_switch_post(card, main_md->part_curr);
794         }
795
796         main_md->part_curr = md->part_type;
797         return ret;
798 }
799
800 static int mmc_sd_num_wr_blocks(struct mmc_card *card, u32 *written_blocks)
801 {
802         int err;
803         u32 result;
804         __be32 *blocks;
805
806         struct mmc_request mrq = {};
807         struct mmc_command cmd = {};
808         struct mmc_data data = {};
809
810         struct scatterlist sg;
811
812         cmd.opcode = MMC_APP_CMD;
813         cmd.arg = card->rca << 16;
814         cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC;
815
816         err = mmc_wait_for_cmd(card->host, &cmd, 0);
817         if (err)
818                 return err;
819         if (!mmc_host_is_spi(card->host) && !(cmd.resp[0] & R1_APP_CMD))
820                 return -EIO;
821
822         memset(&cmd, 0, sizeof(struct mmc_command));
823
824         cmd.opcode = SD_APP_SEND_NUM_WR_BLKS;
825         cmd.arg = 0;
826         cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_ADTC;
827
828         data.blksz = 4;
829         data.blocks = 1;
830         data.flags = MMC_DATA_READ;
831         data.sg = &sg;
832         data.sg_len = 1;
833         mmc_set_data_timeout(&data, card);
834
835         mrq.cmd = &cmd;
836         mrq.data = &data;
837
838         blocks = kmalloc(4, GFP_KERNEL);
839         if (!blocks)
840                 return -ENOMEM;
841
842         sg_init_one(&sg, blocks, 4);
843
844         mmc_wait_for_req(card->host, &mrq);
845
846         result = ntohl(*blocks);
847         kfree(blocks);
848
849         if (cmd.error || data.error)
850                 return -EIO;
851
852         *written_blocks = result;
853
854         return 0;
855 }
856
857 static int card_busy_detect(struct mmc_card *card, unsigned int timeout_ms,
858                 bool hw_busy_detect, struct request *req, bool *gen_err)
859 {
860         unsigned long timeout = jiffies + msecs_to_jiffies(timeout_ms);
861         int err = 0;
862         u32 status;
863
864         do {
865                 err = __mmc_send_status(card, &status, 5);
866                 if (err) {
867                         pr_err("%s: error %d requesting status\n",
868                                req->rq_disk->disk_name, err);
869                         return err;
870                 }
871
872                 if (status & R1_ERROR) {
873                         pr_err("%s: %s: error sending status cmd, status %#x\n",
874                                 req->rq_disk->disk_name, __func__, status);
875                         *gen_err = true;
876                 }
877
878                 /* We may rely on the host hw to handle busy detection.*/
879                 if ((card->host->caps & MMC_CAP_WAIT_WHILE_BUSY) &&
880                         hw_busy_detect)
881                         break;
882
883                 /*
884                  * Timeout if the device never becomes ready for data and never
885                  * leaves the program state.
886                  */
887                 if (time_after(jiffies, timeout)) {
888                         pr_err("%s: Card stuck in programming state! %s %s\n",
889                                 mmc_hostname(card->host),
890                                 req->rq_disk->disk_name, __func__);
891                         return -ETIMEDOUT;
892                 }
893
894                 /*
895                  * Some cards mishandle the status bits,
896                  * so make sure to check both the busy
897                  * indication and the card state.
898                  */
899         } while (!(status & R1_READY_FOR_DATA) ||
900                  (R1_CURRENT_STATE(status) == R1_STATE_PRG));
901
902         return err;
903 }
904
905 static int send_stop(struct mmc_card *card, unsigned int timeout_ms,
906                 struct request *req, bool *gen_err, u32 *stop_status)
907 {
908         struct mmc_host *host = card->host;
909         struct mmc_command cmd = {};
910         int err;
911         bool use_r1b_resp = rq_data_dir(req) == WRITE;
912
913         /*
914          * Normally we use R1B responses for WRITE, but in cases where the host
915          * has specified a max_busy_timeout we need to validate it. A failure
916          * means we need to prevent the host from doing hw busy detection, which
917          * is done by converting to a R1 response instead.
918          */
919         if (host->max_busy_timeout && (timeout_ms > host->max_busy_timeout))
920                 use_r1b_resp = false;
921
922         cmd.opcode = MMC_STOP_TRANSMISSION;
923         if (use_r1b_resp) {
924                 cmd.flags = MMC_RSP_SPI_R1B | MMC_RSP_R1B | MMC_CMD_AC;
925                 cmd.busy_timeout = timeout_ms;
926         } else {
927                 cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC;
928         }
929
930         err = mmc_wait_for_cmd(host, &cmd, 5);
931         if (err)
932                 return err;
933
934         *stop_status = cmd.resp[0];
935
936         /* No need to check card status in case of READ. */
937         if (rq_data_dir(req) == READ)
938                 return 0;
939
940         if (!mmc_host_is_spi(host) &&
941                 (*stop_status & R1_ERROR)) {
942                 pr_err("%s: %s: general error sending stop command, resp %#x\n",
943                         req->rq_disk->disk_name, __func__, *stop_status);
944                 *gen_err = true;
945         }
946
947         return card_busy_detect(card, timeout_ms, use_r1b_resp, req, gen_err);
948 }
949
950 #define ERR_NOMEDIUM    3
951 #define ERR_RETRY       2
952 #define ERR_ABORT       1
953 #define ERR_CONTINUE    0
954
955 static int mmc_blk_cmd_error(struct request *req, const char *name, int error,
956         bool status_valid, u32 status)
957 {
958         switch (error) {
959         case -EILSEQ:
960                 /* response crc error, retry the r/w cmd */
961                 pr_err("%s: %s sending %s command, card status %#x\n",
962                         req->rq_disk->disk_name, "response CRC error",
963                         name, status);
964                 return ERR_RETRY;
965
966         case -ETIMEDOUT:
967                 pr_err("%s: %s sending %s command, card status %#x\n",
968                         req->rq_disk->disk_name, "timed out", name, status);
969
970                 /* If the status cmd initially failed, retry the r/w cmd */
971                 if (!status_valid) {
972                         pr_err("%s: status not valid, retrying timeout\n",
973                                 req->rq_disk->disk_name);
974                         return ERR_RETRY;
975                 }
976
977                 /*
978                  * If it was a r/w cmd crc error, or illegal command
979                  * (eg, issued in wrong state) then retry - we should
980                  * have corrected the state problem above.
981                  */
982                 if (status & (R1_COM_CRC_ERROR | R1_ILLEGAL_COMMAND)) {
983                         pr_err("%s: command error, retrying timeout\n",
984                                 req->rq_disk->disk_name);
985                         return ERR_RETRY;
986                 }
987
988                 /* Otherwise abort the command */
989                 return ERR_ABORT;
990
991         default:
992                 /* We don't understand the error code the driver gave us */
993                 pr_err("%s: unknown error %d sending read/write command, card status %#x\n",
994                        req->rq_disk->disk_name, error, status);
995                 return ERR_ABORT;
996         }
997 }
998
999 /*
1000  * Initial r/w and stop cmd error recovery.
1001  * We don't know whether the card received the r/w cmd or not, so try to
1002  * restore things back to a sane state.  Essentially, we do this as follows:
1003  * - Obtain card status.  If the first attempt to obtain card status fails,
1004  *   the status word will reflect the failed status cmd, not the failed
1005  *   r/w cmd.  If we fail to obtain card status, it suggests we can no
1006  *   longer communicate with the card.
1007  * - Check the card state.  If the card received the cmd but there was a
1008  *   transient problem with the response, it might still be in a data transfer
1009  *   mode.  Try to send it a stop command.  If this fails, we can't recover.
1010  * - If the r/w cmd failed due to a response CRC error, it was probably
1011  *   transient, so retry the cmd.
1012  * - If the r/w cmd timed out, but we didn't get the r/w cmd status, retry.
1013  * - If the r/w cmd timed out, and the r/w cmd failed due to CRC error or
1014  *   illegal cmd, retry.
1015  * Otherwise we don't understand what happened, so abort.
1016  */
1017 static int mmc_blk_cmd_recovery(struct mmc_card *card, struct request *req,
1018         struct mmc_blk_request *brq, bool *ecc_err, bool *gen_err)
1019 {
1020         bool prev_cmd_status_valid = true;
1021         u32 status, stop_status = 0;
1022         int err, retry;
1023
1024         if (mmc_card_removed(card))
1025                 return ERR_NOMEDIUM;
1026
1027         /*
1028          * Try to get card status which indicates both the card state
1029          * and why there was no response.  If the first attempt fails,
1030          * we can't be sure the returned status is for the r/w command.
1031          */
1032         for (retry = 2; retry >= 0; retry--) {
1033                 err = __mmc_send_status(card, &status, 0);
1034                 if (!err)
1035                         break;
1036
1037                 /* Re-tune if needed */
1038                 mmc_retune_recheck(card->host);
1039
1040                 prev_cmd_status_valid = false;
1041                 pr_err("%s: error %d sending status command, %sing\n",
1042                        req->rq_disk->disk_name, err, retry ? "retry" : "abort");
1043         }
1044
1045         /* We couldn't get a response from the card.  Give up. */
1046         if (err) {
1047                 /* Check if the card is removed */
1048                 if (mmc_detect_card_removed(card->host))
1049                         return ERR_NOMEDIUM;
1050                 return ERR_ABORT;
1051         }
1052
1053         /* Flag ECC errors */
1054         if ((status & R1_CARD_ECC_FAILED) ||
1055             (brq->stop.resp[0] & R1_CARD_ECC_FAILED) ||
1056             (brq->cmd.resp[0] & R1_CARD_ECC_FAILED))
1057                 *ecc_err = true;
1058
1059         /* Flag General errors */
1060         if (!mmc_host_is_spi(card->host) && rq_data_dir(req) != READ)
1061                 if ((status & R1_ERROR) ||
1062                         (brq->stop.resp[0] & R1_ERROR)) {
1063                         pr_err("%s: %s: general error sending stop or status command, stop cmd response %#x, card status %#x\n",
1064                                req->rq_disk->disk_name, __func__,
1065                                brq->stop.resp[0], status);
1066                         *gen_err = true;
1067                 }
1068
1069         /*
1070          * Check the current card state.  If it is in some data transfer
1071          * mode, tell it to stop (and hopefully transition back to TRAN.)
1072          */
1073         if (R1_CURRENT_STATE(status) == R1_STATE_DATA ||
1074             R1_CURRENT_STATE(status) == R1_STATE_RCV) {
1075                 err = send_stop(card,
1076                         DIV_ROUND_UP(brq->data.timeout_ns, 1000000),
1077                         req, gen_err, &stop_status);
1078                 if (err) {
1079                         pr_err("%s: error %d sending stop command\n",
1080                                req->rq_disk->disk_name, err);
1081                         /*
1082                          * If the stop cmd also timed out, the card is probably
1083                          * not present, so abort. Other errors are bad news too.
1084                          */
1085                         return ERR_ABORT;
1086                 }
1087
1088                 if (stop_status & R1_CARD_ECC_FAILED)
1089                         *ecc_err = true;
1090         }
1091
1092         /* Check for set block count errors */
1093         if (brq->sbc.error)
1094                 return mmc_blk_cmd_error(req, "SET_BLOCK_COUNT", brq->sbc.error,
1095                                 prev_cmd_status_valid, status);
1096
1097         /* Check for r/w command errors */
1098         if (brq->cmd.error)
1099                 return mmc_blk_cmd_error(req, "r/w cmd", brq->cmd.error,
1100                                 prev_cmd_status_valid, status);
1101
1102         /* Data errors */
1103         if (!brq->stop.error)
1104                 return ERR_CONTINUE;
1105
1106         /* Now for stop errors.  These aren't fatal to the transfer. */
1107         pr_info("%s: error %d sending stop command, original cmd response %#x, card status %#x\n",
1108                req->rq_disk->disk_name, brq->stop.error,
1109                brq->cmd.resp[0], status);
1110
1111         /*
1112          * Subsitute in our own stop status as this will give the error
1113          * state which happened during the execution of the r/w command.
1114          */
1115         if (stop_status) {
1116                 brq->stop.resp[0] = stop_status;
1117                 brq->stop.error = 0;
1118         }
1119         return ERR_CONTINUE;
1120 }
1121
1122 static int mmc_blk_reset(struct mmc_blk_data *md, struct mmc_host *host,
1123                          int type)
1124 {
1125         int err;
1126
1127         if (md->reset_done & type)
1128                 return -EEXIST;
1129
1130         md->reset_done |= type;
1131         err = mmc_hw_reset(host);
1132         /* Ensure we switch back to the correct partition */
1133         if (err != -EOPNOTSUPP) {
1134                 struct mmc_blk_data *main_md =
1135                         dev_get_drvdata(&host->card->dev);
1136                 int part_err;
1137
1138                 main_md->part_curr = main_md->part_type;
1139                 part_err = mmc_blk_part_switch(host->card, md);
1140                 if (part_err) {
1141                         /*
1142                          * We have failed to get back into the correct
1143                          * partition, so we need to abort the whole request.
1144                          */
1145                         return -ENODEV;
1146                 }
1147         }
1148         return err;
1149 }
1150
1151 static inline void mmc_blk_reset_success(struct mmc_blk_data *md, int type)
1152 {
1153         md->reset_done &= ~type;
1154 }
1155
1156 int mmc_access_rpmb(struct mmc_queue *mq)
1157 {
1158         struct mmc_blk_data *md = mq->blkdata;
1159         /*
1160          * If this is a RPMB partition access, return ture
1161          */
1162         if (md && md->part_type == EXT_CSD_PART_CONFIG_ACC_RPMB)
1163                 return true;
1164
1165         return false;
1166 }
1167
1168 /*
1169  * The non-block commands come back from the block layer after it queued it and
1170  * processed it with all other requests and then they get issued in this
1171  * function.
1172  */
1173 static void mmc_blk_issue_drv_op(struct mmc_queue *mq, struct request *req)
1174 {
1175         struct mmc_queue_req *mq_rq;
1176         struct mmc_card *card = mq->card;
1177         struct mmc_blk_data *md = mq->blkdata;
1178         int ret;
1179         int i;
1180
1181         mq_rq = req_to_mmc_queue_req(req);
1182
1183         switch (mq_rq->drv_op) {
1184         case MMC_DRV_OP_IOCTL:
1185                 for (i = 0; i < mq_rq->ioc_count; i++) {
1186                         ret = __mmc_blk_ioctl_cmd(card, md, mq_rq->idata[i]);
1187                         if (ret)
1188                                 break;
1189                 }
1190                 /* Always switch back to main area after RPMB access */
1191                 if (md->area_type & MMC_BLK_DATA_AREA_RPMB)
1192                         mmc_blk_part_switch(card, dev_get_drvdata(&card->dev));
1193                 break;
1194         case MMC_DRV_OP_BOOT_WP:
1195                 ret = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL, EXT_CSD_BOOT_WP,
1196                                  card->ext_csd.boot_ro_lock |
1197                                  EXT_CSD_BOOT_WP_B_PWR_WP_EN,
1198                                  card->ext_csd.part_time);
1199                 if (ret)
1200                         pr_err("%s: Locking boot partition ro until next power on failed: %d\n",
1201                                md->disk->disk_name, ret);
1202                 else
1203                         card->ext_csd.boot_ro_lock |=
1204                                 EXT_CSD_BOOT_WP_B_PWR_WP_EN;
1205                 break;
1206         default:
1207                 pr_err("%s: unknown driver specific operation\n",
1208                        md->disk->disk_name);
1209                 ret = -EINVAL;
1210                 break;
1211         }
1212         mq_rq->drv_op_result = ret;
1213         blk_end_request_all(req, ret);
1214 }
1215
1216 static void mmc_blk_issue_discard_rq(struct mmc_queue *mq, struct request *req)
1217 {
1218         struct mmc_blk_data *md = mq->blkdata;
1219         struct mmc_card *card = md->queue.card;
1220         unsigned int from, nr, arg;
1221         int err = 0, type = MMC_BLK_DISCARD;
1222
1223         if (!mmc_can_erase(card)) {
1224                 err = -EOPNOTSUPP;
1225                 goto fail;
1226         }
1227
1228         from = blk_rq_pos(req);
1229         nr = blk_rq_sectors(req);
1230
1231         if (mmc_can_discard(card))
1232                 arg = MMC_DISCARD_ARG;
1233         else if (mmc_can_trim(card))
1234                 arg = MMC_TRIM_ARG;
1235         else
1236                 arg = MMC_ERASE_ARG;
1237         do {
1238                 err = 0;
1239                 if (card->quirks & MMC_QUIRK_INAND_CMD38) {
1240                         err = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL,
1241                                          INAND_CMD38_ARG_EXT_CSD,
1242                                          arg == MMC_TRIM_ARG ?
1243                                          INAND_CMD38_ARG_TRIM :
1244                                          INAND_CMD38_ARG_ERASE,
1245                                          0);
1246                 }
1247                 if (!err)
1248                         err = mmc_erase(card, from, nr, arg);
1249         } while (err == -EIO && !mmc_blk_reset(md, card->host, type));
1250         if (!err)
1251                 mmc_blk_reset_success(md, type);
1252 fail:
1253         blk_end_request(req, err, blk_rq_bytes(req));
1254 }
1255
1256 static void mmc_blk_issue_secdiscard_rq(struct mmc_queue *mq,
1257                                        struct request *req)
1258 {
1259         struct mmc_blk_data *md = mq->blkdata;
1260         struct mmc_card *card = md->queue.card;
1261         unsigned int from, nr, arg;
1262         int err = 0, type = MMC_BLK_SECDISCARD;
1263
1264         if (!(mmc_can_secure_erase_trim(card))) {
1265                 err = -EOPNOTSUPP;
1266                 goto out;
1267         }
1268
1269         from = blk_rq_pos(req);
1270         nr = blk_rq_sectors(req);
1271
1272         if (mmc_can_trim(card) && !mmc_erase_group_aligned(card, from, nr))
1273                 arg = MMC_SECURE_TRIM1_ARG;
1274         else
1275                 arg = MMC_SECURE_ERASE_ARG;
1276
1277 retry:
1278         if (card->quirks & MMC_QUIRK_INAND_CMD38) {
1279                 err = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL,
1280                                  INAND_CMD38_ARG_EXT_CSD,
1281                                  arg == MMC_SECURE_TRIM1_ARG ?
1282                                  INAND_CMD38_ARG_SECTRIM1 :
1283                                  INAND_CMD38_ARG_SECERASE,
1284                                  0);
1285                 if (err)
1286                         goto out_retry;
1287         }
1288
1289         err = mmc_erase(card, from, nr, arg);
1290         if (err == -EIO)
1291                 goto out_retry;
1292         if (err)
1293                 goto out;
1294
1295         if (arg == MMC_SECURE_TRIM1_ARG) {
1296                 if (card->quirks & MMC_QUIRK_INAND_CMD38) {
1297                         err = mmc_switch(card, EXT_CSD_CMD_SET_NORMAL,
1298                                          INAND_CMD38_ARG_EXT_CSD,
1299                                          INAND_CMD38_ARG_SECTRIM2,
1300                                          0);
1301                         if (err)
1302                                 goto out_retry;
1303                 }
1304
1305                 err = mmc_erase(card, from, nr, MMC_SECURE_TRIM2_ARG);
1306                 if (err == -EIO)
1307                         goto out_retry;
1308                 if (err)
1309                         goto out;
1310         }
1311
1312 out_retry:
1313         if (err && !mmc_blk_reset(md, card->host, type))
1314                 goto retry;
1315         if (!err)
1316                 mmc_blk_reset_success(md, type);
1317 out:
1318         blk_end_request(req, err, blk_rq_bytes(req));
1319 }
1320
1321 static void mmc_blk_issue_flush(struct mmc_queue *mq, struct request *req)
1322 {
1323         struct mmc_blk_data *md = mq->blkdata;
1324         struct mmc_card *card = md->queue.card;
1325         int ret = 0;
1326
1327         ret = mmc_flush_cache(card);
1328         if (ret)
1329                 ret = -EIO;
1330
1331         blk_end_request_all(req, ret);
1332 }
1333
1334 /*
1335  * Reformat current write as a reliable write, supporting
1336  * both legacy and the enhanced reliable write MMC cards.
1337  * In each transfer we'll handle only as much as a single
1338  * reliable write can handle, thus finish the request in
1339  * partial completions.
1340  */
1341 static inline void mmc_apply_rel_rw(struct mmc_blk_request *brq,
1342                                     struct mmc_card *card,
1343                                     struct request *req)
1344 {
1345         if (!(card->ext_csd.rel_param & EXT_CSD_WR_REL_PARAM_EN)) {
1346                 /* Legacy mode imposes restrictions on transfers. */
1347                 if (!IS_ALIGNED(blk_rq_pos(req), card->ext_csd.rel_sectors))
1348                         brq->data.blocks = 1;
1349
1350                 if (brq->data.blocks > card->ext_csd.rel_sectors)
1351                         brq->data.blocks = card->ext_csd.rel_sectors;
1352                 else if (brq->data.blocks < card->ext_csd.rel_sectors)
1353                         brq->data.blocks = 1;
1354         }
1355 }
1356
1357 #define CMD_ERRORS                                                      \
1358         (R1_OUT_OF_RANGE |      /* Command argument out of range */     \
1359          R1_ADDRESS_ERROR |     /* Misaligned address */                \
1360          R1_BLOCK_LEN_ERROR |   /* Transferred block length incorrect */\
1361          R1_WP_VIOLATION |      /* Tried to write to protected block */ \
1362          R1_CARD_ECC_FAILED |   /* Card ECC failed */                   \
1363          R1_CC_ERROR |          /* Card controller error */             \
1364          R1_ERROR)              /* General/unknown error */
1365
1366 static bool mmc_blk_has_cmd_err(struct mmc_command *cmd)
1367 {
1368         if (!cmd->error && cmd->resp[0] & CMD_ERRORS)
1369                 cmd->error = -EIO;
1370
1371         return cmd->error;
1372 }
1373
1374 static enum mmc_blk_status mmc_blk_err_check(struct mmc_card *card,
1375                                              struct mmc_async_req *areq)
1376 {
1377         struct mmc_queue_req *mq_mrq = container_of(areq, struct mmc_queue_req,
1378                                                     areq);
1379         struct mmc_blk_request *brq = &mq_mrq->brq;
1380         struct request *req = mmc_queue_req_to_req(mq_mrq);
1381         int need_retune = card->host->need_retune;
1382         bool ecc_err = false;
1383         bool gen_err = false;
1384
1385         /*
1386          * sbc.error indicates a problem with the set block count
1387          * command.  No data will have been transferred.
1388          *
1389          * cmd.error indicates a problem with the r/w command.  No
1390          * data will have been transferred.
1391          *
1392          * stop.error indicates a problem with the stop command.  Data
1393          * may have been transferred, or may still be transferring.
1394          */
1395         if (brq->sbc.error || brq->cmd.error || mmc_blk_has_cmd_err(&brq->stop) ||
1396             brq->data.error) {
1397                 switch (mmc_blk_cmd_recovery(card, req, brq, &ecc_err, &gen_err)) {
1398                 case ERR_RETRY:
1399                         return MMC_BLK_RETRY;
1400                 case ERR_ABORT:
1401                         return MMC_BLK_ABORT;
1402                 case ERR_NOMEDIUM:
1403                         return MMC_BLK_NOMEDIUM;
1404                 case ERR_CONTINUE:
1405                         break;
1406                 }
1407         }
1408
1409         /*
1410          * Check for errors relating to the execution of the
1411          * initial command - such as address errors.  No data
1412          * has been transferred.
1413          */
1414         if (brq->cmd.resp[0] & CMD_ERRORS) {
1415                 pr_err("%s: r/w command failed, status = %#x\n",
1416                        req->rq_disk->disk_name, brq->cmd.resp[0]);
1417                 return MMC_BLK_ABORT;
1418         }
1419
1420         /*
1421          * Everything else is either success, or a data error of some
1422          * kind.  If it was a write, we may have transitioned to
1423          * program mode, which we have to wait for it to complete.
1424          */
1425         if (!mmc_host_is_spi(card->host) && rq_data_dir(req) != READ) {
1426                 int err;
1427
1428                 /* Check stop command response */
1429                 if (brq->stop.resp[0] & R1_ERROR) {
1430                         pr_err("%s: %s: general error sending stop command, stop cmd response %#x\n",
1431                                req->rq_disk->disk_name, __func__,
1432                                brq->stop.resp[0]);
1433                         gen_err = true;
1434                 }
1435
1436                 err = card_busy_detect(card, MMC_BLK_TIMEOUT_MS, false, req,
1437                                         &gen_err);
1438                 if (err)
1439                         return MMC_BLK_CMD_ERR;
1440         }
1441
1442         /* if general error occurs, retry the write operation. */
1443         if (gen_err) {
1444                 pr_warn("%s: retrying write for general error\n",
1445                                 req->rq_disk->disk_name);
1446                 return MMC_BLK_RETRY;
1447         }
1448
1449         /* Some errors (ECC) are flagged on the next commmand, so check stop, too */
1450         if (brq->data.error || brq->stop.error) {
1451                 if (need_retune && !brq->retune_retry_done) {
1452                         pr_debug("%s: retrying because a re-tune was needed\n",
1453                                  req->rq_disk->disk_name);
1454                         brq->retune_retry_done = 1;
1455                         return MMC_BLK_RETRY;
1456                 }
1457                 pr_err("%s: error %d transferring data, sector %u, nr %u, cmd response %#x, card status %#x\n",
1458                        req->rq_disk->disk_name, brq->data.error ?: brq->stop.error,
1459                        (unsigned)blk_rq_pos(req),
1460                        (unsigned)blk_rq_sectors(req),
1461                        brq->cmd.resp[0], brq->stop.resp[0]);
1462
1463                 if (rq_data_dir(req) == READ) {
1464                         if (ecc_err)
1465                                 return MMC_BLK_ECC_ERR;
1466                         return MMC_BLK_DATA_ERR;
1467                 } else {
1468                         return MMC_BLK_CMD_ERR;
1469                 }
1470         }
1471
1472         if (!brq->data.bytes_xfered)
1473                 return MMC_BLK_RETRY;
1474
1475         if (blk_rq_bytes(req) != brq->data.bytes_xfered)
1476                 return MMC_BLK_PARTIAL;
1477
1478         return MMC_BLK_SUCCESS;
1479 }
1480
1481 static void mmc_blk_data_prep(struct mmc_queue *mq, struct mmc_queue_req *mqrq,
1482                               int disable_multi, bool *do_rel_wr,
1483                               bool *do_data_tag)
1484 {
1485         struct mmc_blk_data *md = mq->blkdata;
1486         struct mmc_card *card = md->queue.card;
1487         struct mmc_blk_request *brq = &mqrq->brq;
1488         struct request *req = mmc_queue_req_to_req(mqrq);
1489
1490         /*
1491          * Reliable writes are used to implement Forced Unit Access and
1492          * are supported only on MMCs.
1493          */
1494         *do_rel_wr = (req->cmd_flags & REQ_FUA) &&
1495                      rq_data_dir(req) == WRITE &&
1496                      (md->flags & MMC_BLK_REL_WR);
1497
1498         memset(brq, 0, sizeof(struct mmc_blk_request));
1499
1500         brq->mrq.data = &brq->data;
1501
1502         brq->stop.opcode = MMC_STOP_TRANSMISSION;
1503         brq->stop.arg = 0;
1504
1505         if (rq_data_dir(req) == READ) {
1506                 brq->data.flags = MMC_DATA_READ;
1507                 brq->stop.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_AC;
1508         } else {
1509                 brq->data.flags = MMC_DATA_WRITE;
1510                 brq->stop.flags = MMC_RSP_SPI_R1B | MMC_RSP_R1B | MMC_CMD_AC;
1511         }
1512
1513         brq->data.blksz = 512;
1514         brq->data.blocks = blk_rq_sectors(req);
1515
1516         /*
1517          * The block layer doesn't support all sector count
1518          * restrictions, so we need to be prepared for too big
1519          * requests.
1520          */
1521         if (brq->data.blocks > card->host->max_blk_count)
1522                 brq->data.blocks = card->host->max_blk_count;
1523
1524         if (brq->data.blocks > 1) {
1525                 /*
1526                  * After a read error, we redo the request one sector
1527                  * at a time in order to accurately determine which
1528                  * sectors can be read successfully.
1529                  */
1530                 if (disable_multi)
1531                         brq->data.blocks = 1;
1532
1533                 /*
1534                  * Some controllers have HW issues while operating
1535                  * in multiple I/O mode
1536                  */
1537                 if (card->host->ops->multi_io_quirk)
1538                         brq->data.blocks = card->host->ops->multi_io_quirk(card,
1539                                                 (rq_data_dir(req) == READ) ?
1540                                                 MMC_DATA_READ : MMC_DATA_WRITE,
1541                                                 brq->data.blocks);
1542         }
1543
1544         if (*do_rel_wr)
1545                 mmc_apply_rel_rw(brq, card, req);
1546
1547         /*
1548          * Data tag is used only during writing meta data to speed
1549          * up write and any subsequent read of this meta data
1550          */
1551         *do_data_tag = card->ext_csd.data_tag_unit_size &&
1552                        (req->cmd_flags & REQ_META) &&
1553                        (rq_data_dir(req) == WRITE) &&
1554                        ((brq->data.blocks * brq->data.blksz) >=
1555                         card->ext_csd.data_tag_unit_size);
1556
1557         mmc_set_data_timeout(&brq->data, card);
1558
1559         brq->data.sg = mqrq->sg;
1560         brq->data.sg_len = mmc_queue_map_sg(mq, mqrq);
1561
1562         /*
1563          * Adjust the sg list so it is the same size as the
1564          * request.
1565          */
1566         if (brq->data.blocks != blk_rq_sectors(req)) {
1567                 int i, data_size = brq->data.blocks << 9;
1568                 struct scatterlist *sg;
1569
1570                 for_each_sg(brq->data.sg, sg, brq->data.sg_len, i) {
1571                         data_size -= sg->length;
1572                         if (data_size <= 0) {
1573                                 sg->length += data_size;
1574                                 i++;
1575                                 break;
1576                         }
1577                 }
1578                 brq->data.sg_len = i;
1579         }
1580
1581         mqrq->areq.mrq = &brq->mrq;
1582
1583         mmc_queue_bounce_pre(mqrq);
1584 }
1585
1586 static void mmc_blk_rw_rq_prep(struct mmc_queue_req *mqrq,
1587                                struct mmc_card *card,
1588                                int disable_multi,
1589                                struct mmc_queue *mq)
1590 {
1591         u32 readcmd, writecmd;
1592         struct mmc_blk_request *brq = &mqrq->brq;
1593         struct request *req = mmc_queue_req_to_req(mqrq);
1594         struct mmc_blk_data *md = mq->blkdata;
1595         bool do_rel_wr, do_data_tag;
1596
1597         mmc_blk_data_prep(mq, mqrq, disable_multi, &do_rel_wr, &do_data_tag);
1598
1599         brq->mrq.cmd = &brq->cmd;
1600
1601         brq->cmd.arg = blk_rq_pos(req);
1602         if (!mmc_card_blockaddr(card))
1603                 brq->cmd.arg <<= 9;
1604         brq->cmd.flags = MMC_RSP_SPI_R1 | MMC_RSP_R1 | MMC_CMD_ADTC;
1605
1606         if (brq->data.blocks > 1 || do_rel_wr) {
1607                 /* SPI multiblock writes terminate using a special
1608                  * token, not a STOP_TRANSMISSION request.
1609                  */
1610                 if (!mmc_host_is_spi(card->host) ||
1611                     rq_data_dir(req) == READ)
1612                         brq->mrq.stop = &brq->stop;
1613                 readcmd = MMC_READ_MULTIPLE_BLOCK;
1614                 writecmd = MMC_WRITE_MULTIPLE_BLOCK;
1615         } else {
1616                 brq->mrq.stop = NULL;
1617                 readcmd = MMC_READ_SINGLE_BLOCK;
1618                 writecmd = MMC_WRITE_BLOCK;
1619         }
1620         brq->cmd.opcode = rq_data_dir(req) == READ ? readcmd : writecmd;
1621
1622         /*
1623          * Pre-defined multi-block transfers are preferable to
1624          * open ended-ones (and necessary for reliable writes).
1625          * However, it is not sufficient to just send CMD23,
1626          * and avoid the final CMD12, as on an error condition
1627          * CMD12 (stop) needs to be sent anyway. This, coupled
1628          * with Auto-CMD23 enhancements provided by some
1629          * hosts, means that the complexity of dealing
1630          * with this is best left to the host. If CMD23 is
1631          * supported by card and host, we'll fill sbc in and let
1632          * the host deal with handling it correctly. This means
1633          * that for hosts that don't expose MMC_CAP_CMD23, no
1634          * change of behavior will be observed.
1635          *
1636          * N.B: Some MMC cards experience perf degradation.
1637          * We'll avoid using CMD23-bounded multiblock writes for
1638          * these, while retaining features like reliable writes.
1639          */
1640         if ((md->flags & MMC_BLK_CMD23) && mmc_op_multi(brq->cmd.opcode) &&
1641             (do_rel_wr || !(card->quirks & MMC_QUIRK_BLK_NO_CMD23) ||
1642              do_data_tag)) {
1643                 brq->sbc.opcode = MMC_SET_BLOCK_COUNT;
1644                 brq->sbc.arg = brq->data.blocks |
1645                         (do_rel_wr ? (1 << 31) : 0) |
1646                         (do_data_tag ? (1 << 29) : 0);
1647                 brq->sbc.flags = MMC_RSP_R1 | MMC_CMD_AC;
1648                 brq->mrq.sbc = &brq->sbc;
1649         }
1650
1651         mqrq->areq.err_check = mmc_blk_err_check;
1652 }
1653
1654 static bool mmc_blk_rw_cmd_err(struct mmc_blk_data *md, struct mmc_card *card,
1655                                struct mmc_blk_request *brq, struct request *req,
1656                                bool old_req_pending)
1657 {
1658         bool req_pending;
1659
1660         /*
1661          * If this is an SD card and we're writing, we can first
1662          * mark the known good sectors as ok.
1663          *
1664          * If the card is not SD, we can still ok written sectors
1665          * as reported by the controller (which might be less than
1666          * the real number of written sectors, but never more).
1667          */
1668         if (mmc_card_sd(card)) {
1669                 u32 blocks;
1670                 int err;
1671
1672                 err = mmc_sd_num_wr_blocks(card, &blocks);
1673                 if (err)
1674                         req_pending = old_req_pending;
1675                 else
1676                         req_pending = blk_end_request(req, 0, blocks << 9);
1677         } else {
1678                 req_pending = blk_end_request(req, 0, brq->data.bytes_xfered);
1679         }
1680         return req_pending;
1681 }
1682
1683 static void mmc_blk_rw_cmd_abort(struct mmc_queue *mq, struct mmc_card *card,
1684                                  struct request *req,
1685                                  struct mmc_queue_req *mqrq)
1686 {
1687         if (mmc_card_removed(card))
1688                 req->rq_flags |= RQF_QUIET;
1689         while (blk_end_request(req, -EIO, blk_rq_cur_bytes(req)));
1690         mq->qcnt--;
1691 }
1692
1693 /**
1694  * mmc_blk_rw_try_restart() - tries to restart the current async request
1695  * @mq: the queue with the card and host to restart
1696  * @req: a new request that want to be started after the current one
1697  */
1698 static void mmc_blk_rw_try_restart(struct mmc_queue *mq, struct request *req,
1699                                    struct mmc_queue_req *mqrq)
1700 {
1701         if (!req)
1702                 return;
1703
1704         /*
1705          * If the card was removed, just cancel everything and return.
1706          */
1707         if (mmc_card_removed(mq->card)) {
1708                 req->rq_flags |= RQF_QUIET;
1709                 blk_end_request_all(req, -EIO);
1710                 mq->qcnt--; /* FIXME: just set to 0? */
1711                 return;
1712         }
1713         /* Else proceed and try to restart the current async request */
1714         mmc_blk_rw_rq_prep(mqrq, mq->card, 0, mq);
1715         mmc_start_areq(mq->card->host, &mqrq->areq, NULL);
1716 }
1717
1718 static void mmc_blk_issue_rw_rq(struct mmc_queue *mq, struct request *new_req)
1719 {
1720         struct mmc_blk_data *md = mq->blkdata;
1721         struct mmc_card *card = md->queue.card;
1722         struct mmc_blk_request *brq;
1723         int disable_multi = 0, retry = 0, type, retune_retry_done = 0;
1724         enum mmc_blk_status status;
1725         struct mmc_queue_req *mqrq_cur = NULL;
1726         struct mmc_queue_req *mq_rq;
1727         struct request *old_req;
1728         struct mmc_async_req *new_areq;
1729         struct mmc_async_req *old_areq;
1730         bool req_pending = true;
1731
1732         if (new_req) {
1733                 mqrq_cur = req_to_mmc_queue_req(new_req);
1734                 mq->qcnt++;
1735         }
1736
1737         if (!mq->qcnt)
1738                 return;
1739
1740         do {
1741                 if (new_req) {
1742                         /*
1743                          * When 4KB native sector is enabled, only 8 blocks
1744                          * multiple read or write is allowed
1745                          */
1746                         if (mmc_large_sector(card) &&
1747                                 !IS_ALIGNED(blk_rq_sectors(new_req), 8)) {
1748                                 pr_err("%s: Transfer size is not 4KB sector size aligned\n",
1749                                         new_req->rq_disk->disk_name);
1750                                 mmc_blk_rw_cmd_abort(mq, card, new_req, mqrq_cur);
1751                                 return;
1752                         }
1753
1754                         mmc_blk_rw_rq_prep(mqrq_cur, card, 0, mq);
1755                         new_areq = &mqrq_cur->areq;
1756                 } else
1757                         new_areq = NULL;
1758
1759                 old_areq = mmc_start_areq(card->host, new_areq, &status);
1760                 if (!old_areq) {
1761                         /*
1762                          * We have just put the first request into the pipeline
1763                          * and there is nothing more to do until it is
1764                          * complete.
1765                          */
1766                         return;
1767                 }
1768
1769                 /*
1770                  * An asynchronous request has been completed and we proceed
1771                  * to handle the result of it.
1772                  */
1773                 mq_rq = container_of(old_areq, struct mmc_queue_req, areq);
1774                 brq = &mq_rq->brq;
1775                 old_req = mmc_queue_req_to_req(mq_rq);
1776                 type = rq_data_dir(old_req) == READ ? MMC_BLK_READ : MMC_BLK_WRITE;
1777                 mmc_queue_bounce_post(mq_rq);
1778
1779                 switch (status) {
1780                 case MMC_BLK_SUCCESS:
1781                 case MMC_BLK_PARTIAL:
1782                         /*
1783                          * A block was successfully transferred.
1784                          */
1785                         mmc_blk_reset_success(md, type);
1786
1787                         req_pending = blk_end_request(old_req, 0,
1788                                                       brq->data.bytes_xfered);
1789                         /*
1790                          * If the blk_end_request function returns non-zero even
1791                          * though all data has been transferred and no errors
1792                          * were returned by the host controller, it's a bug.
1793                          */
1794                         if (status == MMC_BLK_SUCCESS && req_pending) {
1795                                 pr_err("%s BUG rq_tot %d d_xfer %d\n",
1796                                        __func__, blk_rq_bytes(old_req),
1797                                        brq->data.bytes_xfered);
1798                                 mmc_blk_rw_cmd_abort(mq, card, old_req, mq_rq);
1799                                 return;
1800                         }
1801                         break;
1802                 case MMC_BLK_CMD_ERR:
1803                         req_pending = mmc_blk_rw_cmd_err(md, card, brq, old_req, req_pending);
1804                         if (mmc_blk_reset(md, card->host, type)) {
1805                                 if (req_pending)
1806                                         mmc_blk_rw_cmd_abort(mq, card, old_req, mq_rq);
1807                                 else
1808                                         mq->qcnt--;
1809                                 mmc_blk_rw_try_restart(mq, new_req, mqrq_cur);
1810                                 return;
1811                         }
1812                         if (!req_pending) {
1813                                 mq->qcnt--;
1814                                 mmc_blk_rw_try_restart(mq, new_req, mqrq_cur);
1815                                 return;
1816                         }
1817                         break;
1818                 case MMC_BLK_RETRY:
1819                         retune_retry_done = brq->retune_retry_done;
1820                         if (retry++ < 5)
1821                                 break;
1822                         /* Fall through */
1823                 case MMC_BLK_ABORT:
1824                         if (!mmc_blk_reset(md, card->host, type))
1825                                 break;
1826                         mmc_blk_rw_cmd_abort(mq, card, old_req, mq_rq);
1827                         mmc_blk_rw_try_restart(mq, new_req, mqrq_cur);
1828                         return;
1829                 case MMC_BLK_DATA_ERR: {
1830                         int err;
1831
1832                         err = mmc_blk_reset(md, card->host, type);
1833                         if (!err)
1834                                 break;
1835                         if (err == -ENODEV) {
1836                                 mmc_blk_rw_cmd_abort(mq, card, old_req, mq_rq);
1837                                 mmc_blk_rw_try_restart(mq, new_req, mqrq_cur);
1838                                 return;
1839                         }
1840                         /* Fall through */
1841                 }
1842                 case MMC_BLK_ECC_ERR:
1843                         if (brq->data.blocks > 1) {
1844                                 /* Redo read one sector at a time */
1845                                 pr_warn("%s: retrying using single block read\n",
1846                                         old_req->rq_disk->disk_name);
1847                                 disable_multi = 1;
1848                                 break;
1849                         }
1850                         /*
1851                          * After an error, we redo I/O one sector at a
1852                          * time, so we only reach here after trying to
1853                          * read a single sector.
1854                          */
1855                         req_pending = blk_end_request(old_req, -EIO,
1856                                                       brq->data.blksz);
1857                         if (!req_pending) {
1858                                 mq->qcnt--;
1859                                 mmc_blk_rw_try_restart(mq, new_req, mqrq_cur);
1860                                 return;
1861                         }
1862                         break;
1863                 case MMC_BLK_NOMEDIUM:
1864                         mmc_blk_rw_cmd_abort(mq, card, old_req, mq_rq);
1865                         mmc_blk_rw_try_restart(mq, new_req, mqrq_cur);
1866                         return;
1867                 default:
1868                         pr_err("%s: Unhandled return value (%d)",
1869                                         old_req->rq_disk->disk_name, status);
1870                         mmc_blk_rw_cmd_abort(mq, card, old_req, mq_rq);
1871                         mmc_blk_rw_try_restart(mq, new_req, mqrq_cur);
1872                         return;
1873                 }
1874
1875                 if (req_pending) {
1876                         /*
1877                          * In case of a incomplete request
1878                          * prepare it again and resend.
1879                          */
1880                         mmc_blk_rw_rq_prep(mq_rq, card,
1881                                         disable_multi, mq);
1882                         mmc_start_areq(card->host,
1883                                         &mq_rq->areq, NULL);
1884                         mq_rq->brq.retune_retry_done = retune_retry_done;
1885                 }
1886         } while (req_pending);
1887
1888         mq->qcnt--;
1889 }
1890
1891 void mmc_blk_issue_rq(struct mmc_queue *mq, struct request *req)
1892 {
1893         int ret;
1894         struct mmc_blk_data *md = mq->blkdata;
1895         struct mmc_card *card = md->queue.card;
1896
1897         if (req && !mq->qcnt)
1898                 /* claim host only for the first request */
1899                 mmc_get_card(card);
1900
1901         ret = mmc_blk_part_switch(card, md);
1902         if (ret) {
1903                 if (req) {
1904                         blk_end_request_all(req, -EIO);
1905                 }
1906                 goto out;
1907         }
1908
1909         if (req) {
1910                 switch (req_op(req)) {
1911                 case REQ_OP_DRV_IN:
1912                 case REQ_OP_DRV_OUT:
1913                         /*
1914                          * Complete ongoing async transfer before issuing
1915                          * ioctl()s
1916                          */
1917                         if (mq->qcnt)
1918                                 mmc_blk_issue_rw_rq(mq, NULL);
1919                         mmc_blk_issue_drv_op(mq, req);
1920                         break;
1921                 case REQ_OP_DISCARD:
1922                         /*
1923                          * Complete ongoing async transfer before issuing
1924                          * discard.
1925                          */
1926                         if (mq->qcnt)
1927                                 mmc_blk_issue_rw_rq(mq, NULL);
1928                         mmc_blk_issue_discard_rq(mq, req);
1929                         break;
1930                 case REQ_OP_SECURE_ERASE:
1931                         /*
1932                          * Complete ongoing async transfer before issuing
1933                          * secure erase.
1934                          */
1935                         if (mq->qcnt)
1936                                 mmc_blk_issue_rw_rq(mq, NULL);
1937                         mmc_blk_issue_secdiscard_rq(mq, req);
1938                         break;
1939                 case REQ_OP_FLUSH:
1940                         /*
1941                          * Complete ongoing async transfer before issuing
1942                          * flush.
1943                          */
1944                         if (mq->qcnt)
1945                                 mmc_blk_issue_rw_rq(mq, NULL);
1946                         mmc_blk_issue_flush(mq, req);
1947                         break;
1948                 default:
1949                         /* Normal request, just issue it */
1950                         mmc_blk_issue_rw_rq(mq, req);
1951                         card->host->context_info.is_waiting_last_req = false;
1952                         break;
1953                 }
1954         } else {
1955                 /* No request, flushing the pipeline with NULL */
1956                 mmc_blk_issue_rw_rq(mq, NULL);
1957                 card->host->context_info.is_waiting_last_req = false;
1958         }
1959
1960 out:
1961         if (!mq->qcnt)
1962                 mmc_put_card(card);
1963 }
1964
1965 static inline int mmc_blk_readonly(struct mmc_card *card)
1966 {
1967         return mmc_card_readonly(card) ||
1968                !(card->csd.cmdclass & CCC_BLOCK_WRITE);
1969 }
1970
1971 static struct mmc_blk_data *mmc_blk_alloc_req(struct mmc_card *card,
1972                                               struct device *parent,
1973                                               sector_t size,
1974                                               bool default_ro,
1975                                               const char *subname,
1976                                               int area_type)
1977 {
1978         struct mmc_blk_data *md;
1979         int devidx, ret;
1980
1981         devidx = ida_simple_get(&mmc_blk_ida, 0, max_devices, GFP_KERNEL);
1982         if (devidx < 0)
1983                 return ERR_PTR(devidx);
1984
1985         md = kzalloc(sizeof(struct mmc_blk_data), GFP_KERNEL);
1986         if (!md) {
1987                 ret = -ENOMEM;
1988                 goto out;
1989         }
1990
1991         md->area_type = area_type;
1992
1993         /*
1994          * Set the read-only status based on the supported commands
1995          * and the write protect switch.
1996          */
1997         md->read_only = mmc_blk_readonly(card);
1998
1999         md->disk = alloc_disk(perdev_minors);
2000         if (md->disk == NULL) {
2001                 ret = -ENOMEM;
2002                 goto err_kfree;
2003         }
2004
2005         spin_lock_init(&md->lock);
2006         INIT_LIST_HEAD(&md->part);
2007         md->usage = 1;
2008
2009         ret = mmc_init_queue(&md->queue, card, &md->lock, subname);
2010         if (ret)
2011                 goto err_putdisk;
2012
2013         md->queue.blkdata = md;
2014
2015         md->disk->major = MMC_BLOCK_MAJOR;
2016         md->disk->first_minor = devidx * perdev_minors;
2017         md->disk->fops = &mmc_bdops;
2018         md->disk->private_data = md;
2019         md->disk->queue = md->queue.queue;
2020         md->parent = parent;
2021         set_disk_ro(md->disk, md->read_only || default_ro);
2022         md->disk->flags = GENHD_FL_EXT_DEVT;
2023         if (area_type & (MMC_BLK_DATA_AREA_RPMB | MMC_BLK_DATA_AREA_BOOT))
2024                 md->disk->flags |= GENHD_FL_NO_PART_SCAN;
2025
2026         /*
2027          * As discussed on lkml, GENHD_FL_REMOVABLE should:
2028          *
2029          * - be set for removable media with permanent block devices
2030          * - be unset for removable block devices with permanent media
2031          *
2032          * Since MMC block devices clearly fall under the second
2033          * case, we do not set GENHD_FL_REMOVABLE.  Userspace
2034          * should use the block device creation/destruction hotplug
2035          * messages to tell when the card is present.
2036          */
2037
2038         snprintf(md->disk->disk_name, sizeof(md->disk->disk_name),
2039                  "mmcblk%u%s", card->host->index, subname ? subname : "");
2040
2041         if (mmc_card_mmc(card))
2042                 blk_queue_logical_block_size(md->queue.queue,
2043                                              card->ext_csd.data_sector_size);
2044         else
2045                 blk_queue_logical_block_size(md->queue.queue, 512);
2046
2047         set_capacity(md->disk, size);
2048
2049         if (mmc_host_cmd23(card->host)) {
2050                 if ((mmc_card_mmc(card) &&
2051                      card->csd.mmca_vsn >= CSD_SPEC_VER_3) ||
2052                     (mmc_card_sd(card) &&
2053                      card->scr.cmds & SD_SCR_CMD23_SUPPORT))
2054                         md->flags |= MMC_BLK_CMD23;
2055         }
2056
2057         if (mmc_card_mmc(card) &&
2058             md->flags & MMC_BLK_CMD23 &&
2059             ((card->ext_csd.rel_param & EXT_CSD_WR_REL_PARAM_EN) ||
2060              card->ext_csd.rel_sectors)) {
2061                 md->flags |= MMC_BLK_REL_WR;
2062                 blk_queue_write_cache(md->queue.queue, true, true);
2063         }
2064
2065         return md;
2066
2067  err_putdisk:
2068         put_disk(md->disk);
2069  err_kfree:
2070         kfree(md);
2071  out:
2072         ida_simple_remove(&mmc_blk_ida, devidx);
2073         return ERR_PTR(ret);
2074 }
2075
2076 static struct mmc_blk_data *mmc_blk_alloc(struct mmc_card *card)
2077 {
2078         sector_t size;
2079
2080         if (!mmc_card_sd(card) && mmc_card_blockaddr(card)) {
2081                 /*
2082                  * The EXT_CSD sector count is in number or 512 byte
2083                  * sectors.
2084                  */
2085                 size = card->ext_csd.sectors;
2086         } else {
2087                 /*
2088                  * The CSD capacity field is in units of read_blkbits.
2089                  * set_capacity takes units of 512 bytes.
2090                  */
2091                 size = (typeof(sector_t))card->csd.capacity
2092                         << (card->csd.read_blkbits - 9);
2093         }
2094
2095         return mmc_blk_alloc_req(card, &card->dev, size, false, NULL,
2096                                         MMC_BLK_DATA_AREA_MAIN);
2097 }
2098
2099 static int mmc_blk_alloc_part(struct mmc_card *card,
2100                               struct mmc_blk_data *md,
2101                               unsigned int part_type,
2102                               sector_t size,
2103                               bool default_ro,
2104                               const char *subname,
2105                               int area_type)
2106 {
2107         char cap_str[10];
2108         struct mmc_blk_data *part_md;
2109
2110         part_md = mmc_blk_alloc_req(card, disk_to_dev(md->disk), size, default_ro,
2111                                     subname, area_type);
2112         if (IS_ERR(part_md))
2113                 return PTR_ERR(part_md);
2114         part_md->part_type = part_type;
2115         list_add(&part_md->part, &md->part);
2116
2117         string_get_size((u64)get_capacity(part_md->disk), 512, STRING_UNITS_2,
2118                         cap_str, sizeof(cap_str));
2119         pr_info("%s: %s %s partition %u %s\n",
2120                part_md->disk->disk_name, mmc_card_id(card),
2121                mmc_card_name(card), part_md->part_type, cap_str);
2122         return 0;
2123 }
2124
2125 /* MMC Physical partitions consist of two boot partitions and
2126  * up to four general purpose partitions.
2127  * For each partition enabled in EXT_CSD a block device will be allocatedi
2128  * to provide access to the partition.
2129  */
2130
2131 static int mmc_blk_alloc_parts(struct mmc_card *card, struct mmc_blk_data *md)
2132 {
2133         int idx, ret = 0;
2134
2135         if (!mmc_card_mmc(card))
2136                 return 0;
2137
2138         for (idx = 0; idx < card->nr_parts; idx++) {
2139                 if (card->part[idx].size) {
2140                         ret = mmc_blk_alloc_part(card, md,
2141                                 card->part[idx].part_cfg,
2142                                 card->part[idx].size >> 9,
2143                                 card->part[idx].force_ro,
2144                                 card->part[idx].name,
2145                                 card->part[idx].area_type);
2146                         if (ret)
2147                                 return ret;
2148                 }
2149         }
2150
2151         return ret;
2152 }
2153
2154 static void mmc_blk_remove_req(struct mmc_blk_data *md)
2155 {
2156         struct mmc_card *card;
2157
2158         if (md) {
2159                 /*
2160                  * Flush remaining requests and free queues. It
2161                  * is freeing the queue that stops new requests
2162                  * from being accepted.
2163                  */
2164                 card = md->queue.card;
2165                 mmc_cleanup_queue(&md->queue);
2166                 if (md->disk->flags & GENHD_FL_UP) {
2167                         device_remove_file(disk_to_dev(md->disk), &md->force_ro);
2168                         if ((md->area_type & MMC_BLK_DATA_AREA_BOOT) &&
2169                                         card->ext_csd.boot_ro_lockable)
2170                                 device_remove_file(disk_to_dev(md->disk),
2171                                         &md->power_ro_lock);
2172
2173                         del_gendisk(md->disk);
2174                 }
2175                 mmc_blk_put(md);
2176         }
2177 }
2178
2179 static void mmc_blk_remove_parts(struct mmc_card *card,
2180                                  struct mmc_blk_data *md)
2181 {
2182         struct list_head *pos, *q;
2183         struct mmc_blk_data *part_md;
2184
2185         list_for_each_safe(pos, q, &md->part) {
2186                 part_md = list_entry(pos, struct mmc_blk_data, part);
2187                 list_del(pos);
2188                 mmc_blk_remove_req(part_md);
2189         }
2190 }
2191
2192 static int mmc_add_disk(struct mmc_blk_data *md)
2193 {
2194         int ret;
2195         struct mmc_card *card = md->queue.card;
2196
2197         device_add_disk(md->parent, md->disk);
2198         md->force_ro.show = force_ro_show;
2199         md->force_ro.store = force_ro_store;
2200         sysfs_attr_init(&md->force_ro.attr);
2201         md->force_ro.attr.name = "force_ro";
2202         md->force_ro.attr.mode = S_IRUGO | S_IWUSR;
2203         ret = device_create_file(disk_to_dev(md->disk), &md->force_ro);
2204         if (ret)
2205                 goto force_ro_fail;
2206
2207         if ((md->area_type & MMC_BLK_DATA_AREA_BOOT) &&
2208              card->ext_csd.boot_ro_lockable) {
2209                 umode_t mode;
2210
2211                 if (card->ext_csd.boot_ro_lock & EXT_CSD_BOOT_WP_B_PWR_WP_DIS)
2212                         mode = S_IRUGO;
2213                 else
2214                         mode = S_IRUGO | S_IWUSR;
2215
2216                 md->power_ro_lock.show = power_ro_lock_show;
2217                 md->power_ro_lock.store = power_ro_lock_store;
2218                 sysfs_attr_init(&md->power_ro_lock.attr);
2219                 md->power_ro_lock.attr.mode = mode;
2220                 md->power_ro_lock.attr.name =
2221                                         "ro_lock_until_next_power_on";
2222                 ret = device_create_file(disk_to_dev(md->disk),
2223                                 &md->power_ro_lock);
2224                 if (ret)
2225                         goto power_ro_lock_fail;
2226         }
2227         return ret;
2228
2229 power_ro_lock_fail:
2230         device_remove_file(disk_to_dev(md->disk), &md->force_ro);
2231 force_ro_fail:
2232         del_gendisk(md->disk);
2233
2234         return ret;
2235 }
2236
2237 static int mmc_blk_probe(struct mmc_card *card)
2238 {
2239         struct mmc_blk_data *md, *part_md;
2240         char cap_str[10];
2241
2242         /*
2243          * Check that the card supports the command class(es) we need.
2244          */
2245         if (!(card->csd.cmdclass & CCC_BLOCK_READ))
2246                 return -ENODEV;
2247
2248         mmc_fixup_device(card, mmc_blk_fixups);
2249
2250         md = mmc_blk_alloc(card);
2251         if (IS_ERR(md))
2252                 return PTR_ERR(md);
2253
2254         string_get_size((u64)get_capacity(md->disk), 512, STRING_UNITS_2,
2255                         cap_str, sizeof(cap_str));
2256         pr_info("%s: %s %s %s %s\n",
2257                 md->disk->disk_name, mmc_card_id(card), mmc_card_name(card),
2258                 cap_str, md->read_only ? "(ro)" : "");
2259
2260         if (mmc_blk_alloc_parts(card, md))
2261                 goto out;
2262
2263         dev_set_drvdata(&card->dev, md);
2264
2265         if (mmc_add_disk(md))
2266                 goto out;
2267
2268         list_for_each_entry(part_md, &md->part, part) {
2269                 if (mmc_add_disk(part_md))
2270                         goto out;
2271         }
2272
2273         pm_runtime_set_autosuspend_delay(&card->dev, 3000);
2274         pm_runtime_use_autosuspend(&card->dev);
2275
2276         /*
2277          * Don't enable runtime PM for SD-combo cards here. Leave that
2278          * decision to be taken during the SDIO init sequence instead.
2279          */
2280         if (card->type != MMC_TYPE_SD_COMBO) {
2281                 pm_runtime_set_active(&card->dev);
2282                 pm_runtime_enable(&card->dev);
2283         }
2284
2285         return 0;
2286
2287  out:
2288         mmc_blk_remove_parts(card, md);
2289         mmc_blk_remove_req(md);
2290         return 0;
2291 }
2292
2293 static void mmc_blk_remove(struct mmc_card *card)
2294 {
2295         struct mmc_blk_data *md = dev_get_drvdata(&card->dev);
2296
2297         mmc_blk_remove_parts(card, md);
2298         pm_runtime_get_sync(&card->dev);
2299         mmc_claim_host(card->host);
2300         mmc_blk_part_switch(card, md);
2301         mmc_release_host(card->host);
2302         if (card->type != MMC_TYPE_SD_COMBO)
2303                 pm_runtime_disable(&card->dev);
2304         pm_runtime_put_noidle(&card->dev);
2305         mmc_blk_remove_req(md);
2306         dev_set_drvdata(&card->dev, NULL);
2307 }
2308
2309 static int _mmc_blk_suspend(struct mmc_card *card)
2310 {
2311         struct mmc_blk_data *part_md;
2312         struct mmc_blk_data *md = dev_get_drvdata(&card->dev);
2313
2314         if (md) {
2315                 mmc_queue_suspend(&md->queue);
2316                 list_for_each_entry(part_md, &md->part, part) {
2317                         mmc_queue_suspend(&part_md->queue);
2318                 }
2319         }
2320         return 0;
2321 }
2322
2323 static void mmc_blk_shutdown(struct mmc_card *card)
2324 {
2325         _mmc_blk_suspend(card);
2326 }
2327
2328 #ifdef CONFIG_PM_SLEEP
2329 static int mmc_blk_suspend(struct device *dev)
2330 {
2331         struct mmc_card *card = mmc_dev_to_card(dev);
2332
2333         return _mmc_blk_suspend(card);
2334 }
2335
2336 static int mmc_blk_resume(struct device *dev)
2337 {
2338         struct mmc_blk_data *part_md;
2339         struct mmc_blk_data *md = dev_get_drvdata(dev);
2340
2341         if (md) {
2342                 /*
2343                  * Resume involves the card going into idle state,
2344                  * so current partition is always the main one.
2345                  */
2346                 md->part_curr = md->part_type;
2347                 mmc_queue_resume(&md->queue);
2348                 list_for_each_entry(part_md, &md->part, part) {
2349                         mmc_queue_resume(&part_md->queue);
2350                 }
2351         }
2352         return 0;
2353 }
2354 #endif
2355
2356 static SIMPLE_DEV_PM_OPS(mmc_blk_pm_ops, mmc_blk_suspend, mmc_blk_resume);
2357
2358 static struct mmc_driver mmc_driver = {
2359         .drv            = {
2360                 .name   = "mmcblk",
2361                 .pm     = &mmc_blk_pm_ops,
2362         },
2363         .probe          = mmc_blk_probe,
2364         .remove         = mmc_blk_remove,
2365         .shutdown       = mmc_blk_shutdown,
2366 };
2367
2368 static int __init mmc_blk_init(void)
2369 {
2370         int res;
2371
2372         if (perdev_minors != CONFIG_MMC_BLOCK_MINORS)
2373                 pr_info("mmcblk: using %d minors per device\n", perdev_minors);
2374
2375         max_devices = min(MAX_DEVICES, (1 << MINORBITS) / perdev_minors);
2376
2377         res = register_blkdev(MMC_BLOCK_MAJOR, "mmc");
2378         if (res)
2379                 goto out;
2380
2381         res = mmc_register_driver(&mmc_driver);
2382         if (res)
2383                 goto out2;
2384
2385         return 0;
2386  out2:
2387         unregister_blkdev(MMC_BLOCK_MAJOR, "mmc");
2388  out:
2389         return res;
2390 }
2391
2392 static void __exit mmc_blk_exit(void)
2393 {
2394         mmc_unregister_driver(&mmc_driver);
2395         unregister_blkdev(MMC_BLOCK_MAJOR, "mmc");
2396 }
2397
2398 module_init(mmc_blk_init);
2399 module_exit(mmc_blk_exit);
2400
2401 MODULE_LICENSE("GPL");
2402 MODULE_DESCRIPTION("Multimedia Card (MMC) block device driver");
2403