Merge tag 'dma-mapping-5.20-2022-08-06' of git://git.infradead.org/users/hch/dma...
[platform/kernel/linux-starfive.git] / drivers / scsi / sd.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *      sd.c Copyright (C) 1992 Drew Eckhardt
4  *           Copyright (C) 1993, 1994, 1995, 1999 Eric Youngdale
5  *
6  *      Linux scsi disk driver
7  *              Initial versions: Drew Eckhardt
8  *              Subsequent revisions: Eric Youngdale
9  *      Modification history:
10  *       - Drew Eckhardt <drew@colorado.edu> original
11  *       - Eric Youngdale <eric@andante.org> add scatter-gather, multiple 
12  *         outstanding request, and other enhancements.
13  *         Support loadable low-level scsi drivers.
14  *       - Jirka Hanika <geo@ff.cuni.cz> support more scsi disks using 
15  *         eight major numbers.
16  *       - Richard Gooch <rgooch@atnf.csiro.au> support devfs.
17  *       - Torben Mathiasen <tmm@image.dk> Resource allocation fixes in 
18  *         sd_init and cleanups.
19  *       - Alex Davis <letmein@erols.com> Fix problem where partition info
20  *         not being read in sd_open. Fix problem where removable media 
21  *         could be ejected after sd_open.
22  *       - Douglas Gilbert <dgilbert@interlog.com> cleanup for lk 2.5.x
23  *       - Badari Pulavarty <pbadari@us.ibm.com>, Matthew Wilcox 
24  *         <willy@debian.org>, Kurt Garloff <garloff@suse.de>: 
25  *         Support 32k/1M disks.
26  *
27  *      Logging policy (needs CONFIG_SCSI_LOGGING defined):
28  *       - setting up transfer: SCSI_LOG_HLQUEUE levels 1 and 2
29  *       - end of transfer (bh + scsi_lib): SCSI_LOG_HLCOMPLETE level 1
30  *       - entering sd_ioctl: SCSI_LOG_IOCTL level 1
31  *       - entering other commands: SCSI_LOG_HLQUEUE level 3
32  *      Note: when the logging level is set by the user, it must be greater
33  *      than the level indicated above to trigger output.       
34  */
35
36 #include <linux/module.h>
37 #include <linux/fs.h>
38 #include <linux/kernel.h>
39 #include <linux/mm.h>
40 #include <linux/bio.h>
41 #include <linux/hdreg.h>
42 #include <linux/errno.h>
43 #include <linux/idr.h>
44 #include <linux/interrupt.h>
45 #include <linux/init.h>
46 #include <linux/blkdev.h>
47 #include <linux/blkpg.h>
48 #include <linux/blk-pm.h>
49 #include <linux/delay.h>
50 #include <linux/major.h>
51 #include <linux/mutex.h>
52 #include <linux/string_helpers.h>
53 #include <linux/slab.h>
54 #include <linux/sed-opal.h>
55 #include <linux/pm_runtime.h>
56 #include <linux/pr.h>
57 #include <linux/t10-pi.h>
58 #include <linux/uaccess.h>
59 #include <asm/unaligned.h>
60
61 #include <scsi/scsi.h>
62 #include <scsi/scsi_cmnd.h>
63 #include <scsi/scsi_dbg.h>
64 #include <scsi/scsi_device.h>
65 #include <scsi/scsi_driver.h>
66 #include <scsi/scsi_eh.h>
67 #include <scsi/scsi_host.h>
68 #include <scsi/scsi_ioctl.h>
69 #include <scsi/scsicam.h>
70
71 #include "sd.h"
72 #include "scsi_priv.h"
73 #include "scsi_logging.h"
74
75 MODULE_AUTHOR("Eric Youngdale");
76 MODULE_DESCRIPTION("SCSI disk (sd) driver");
77 MODULE_LICENSE("GPL");
78
79 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK0_MAJOR);
80 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK1_MAJOR);
81 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK2_MAJOR);
82 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK3_MAJOR);
83 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK4_MAJOR);
84 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK5_MAJOR);
85 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK6_MAJOR);
86 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK7_MAJOR);
87 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK8_MAJOR);
88 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK9_MAJOR);
89 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK10_MAJOR);
90 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK11_MAJOR);
91 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK12_MAJOR);
92 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK13_MAJOR);
93 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK14_MAJOR);
94 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_DISK15_MAJOR);
95 MODULE_ALIAS_SCSI_DEVICE(TYPE_DISK);
96 MODULE_ALIAS_SCSI_DEVICE(TYPE_MOD);
97 MODULE_ALIAS_SCSI_DEVICE(TYPE_RBC);
98 MODULE_ALIAS_SCSI_DEVICE(TYPE_ZBC);
99
100 #define SD_MINORS       16
101
102 static void sd_config_discard(struct scsi_disk *, unsigned int);
103 static void sd_config_write_same(struct scsi_disk *);
104 static int  sd_revalidate_disk(struct gendisk *);
105 static void sd_unlock_native_capacity(struct gendisk *disk);
106 static void sd_start_done_work(struct work_struct *work);
107 static int  sd_probe(struct device *);
108 static int  sd_remove(struct device *);
109 static void sd_shutdown(struct device *);
110 static int sd_suspend_system(struct device *);
111 static int sd_suspend_runtime(struct device *);
112 static int sd_resume_system(struct device *);
113 static int sd_resume_runtime(struct device *);
114 static void sd_rescan(struct device *);
115 static blk_status_t sd_init_command(struct scsi_cmnd *SCpnt);
116 static void sd_uninit_command(struct scsi_cmnd *SCpnt);
117 static int sd_done(struct scsi_cmnd *);
118 static void sd_eh_reset(struct scsi_cmnd *);
119 static int sd_eh_action(struct scsi_cmnd *, int);
120 static void sd_read_capacity(struct scsi_disk *sdkp, unsigned char *buffer);
121 static void scsi_disk_release(struct device *cdev);
122
123 static DEFINE_IDA(sd_index_ida);
124
125 static struct kmem_cache *sd_cdb_cache;
126 static mempool_t *sd_page_pool;
127 static struct lock_class_key sd_bio_compl_lkclass;
128
129 static const char *sd_cache_types[] = {
130         "write through", "none", "write back",
131         "write back, no read (daft)"
132 };
133
134 static void sd_set_flush_flag(struct scsi_disk *sdkp)
135 {
136         bool wc = false, fua = false;
137
138         if (sdkp->WCE) {
139                 wc = true;
140                 if (sdkp->DPOFUA)
141                         fua = true;
142         }
143
144         blk_queue_write_cache(sdkp->disk->queue, wc, fua);
145 }
146
147 static ssize_t
148 cache_type_store(struct device *dev, struct device_attribute *attr,
149                  const char *buf, size_t count)
150 {
151         int ct, rcd, wce, sp;
152         struct scsi_disk *sdkp = to_scsi_disk(dev);
153         struct scsi_device *sdp = sdkp->device;
154         char buffer[64];
155         char *buffer_data;
156         struct scsi_mode_data data;
157         struct scsi_sense_hdr sshdr;
158         static const char temp[] = "temporary ";
159         int len;
160
161         if (sdp->type != TYPE_DISK && sdp->type != TYPE_ZBC)
162                 /* no cache control on RBC devices; theoretically they
163                  * can do it, but there's probably so many exceptions
164                  * it's not worth the risk */
165                 return -EINVAL;
166
167         if (strncmp(buf, temp, sizeof(temp) - 1) == 0) {
168                 buf += sizeof(temp) - 1;
169                 sdkp->cache_override = 1;
170         } else {
171                 sdkp->cache_override = 0;
172         }
173
174         ct = sysfs_match_string(sd_cache_types, buf);
175         if (ct < 0)
176                 return -EINVAL;
177
178         rcd = ct & 0x01 ? 1 : 0;
179         wce = (ct & 0x02) && !sdkp->write_prot ? 1 : 0;
180
181         if (sdkp->cache_override) {
182                 sdkp->WCE = wce;
183                 sdkp->RCD = rcd;
184                 sd_set_flush_flag(sdkp);
185                 return count;
186         }
187
188         if (scsi_mode_sense(sdp, 0x08, 8, buffer, sizeof(buffer), SD_TIMEOUT,
189                             sdkp->max_retries, &data, NULL))
190                 return -EINVAL;
191         len = min_t(size_t, sizeof(buffer), data.length - data.header_length -
192                   data.block_descriptor_length);
193         buffer_data = buffer + data.header_length +
194                 data.block_descriptor_length;
195         buffer_data[2] &= ~0x05;
196         buffer_data[2] |= wce << 2 | rcd;
197         sp = buffer_data[0] & 0x80 ? 1 : 0;
198         buffer_data[0] &= ~0x80;
199
200         /*
201          * Ensure WP, DPOFUA, and RESERVED fields are cleared in
202          * received mode parameter buffer before doing MODE SELECT.
203          */
204         data.device_specific = 0;
205
206         if (scsi_mode_select(sdp, 1, sp, buffer_data, len, SD_TIMEOUT,
207                              sdkp->max_retries, &data, &sshdr)) {
208                 if (scsi_sense_valid(&sshdr))
209                         sd_print_sense_hdr(sdkp, &sshdr);
210                 return -EINVAL;
211         }
212         sd_revalidate_disk(sdkp->disk);
213         return count;
214 }
215
216 static ssize_t
217 manage_start_stop_show(struct device *dev, struct device_attribute *attr,
218                        char *buf)
219 {
220         struct scsi_disk *sdkp = to_scsi_disk(dev);
221         struct scsi_device *sdp = sdkp->device;
222
223         return sprintf(buf, "%u\n", sdp->manage_start_stop);
224 }
225
226 static ssize_t
227 manage_start_stop_store(struct device *dev, struct device_attribute *attr,
228                         const char *buf, size_t count)
229 {
230         struct scsi_disk *sdkp = to_scsi_disk(dev);
231         struct scsi_device *sdp = sdkp->device;
232         bool v;
233
234         if (!capable(CAP_SYS_ADMIN))
235                 return -EACCES;
236
237         if (kstrtobool(buf, &v))
238                 return -EINVAL;
239
240         sdp->manage_start_stop = v;
241
242         return count;
243 }
244 static DEVICE_ATTR_RW(manage_start_stop);
245
246 static ssize_t
247 allow_restart_show(struct device *dev, struct device_attribute *attr, char *buf)
248 {
249         struct scsi_disk *sdkp = to_scsi_disk(dev);
250
251         return sprintf(buf, "%u\n", sdkp->device->allow_restart);
252 }
253
254 static ssize_t
255 allow_restart_store(struct device *dev, struct device_attribute *attr,
256                     const char *buf, size_t count)
257 {
258         bool v;
259         struct scsi_disk *sdkp = to_scsi_disk(dev);
260         struct scsi_device *sdp = sdkp->device;
261
262         if (!capable(CAP_SYS_ADMIN))
263                 return -EACCES;
264
265         if (sdp->type != TYPE_DISK && sdp->type != TYPE_ZBC)
266                 return -EINVAL;
267
268         if (kstrtobool(buf, &v))
269                 return -EINVAL;
270
271         sdp->allow_restart = v;
272
273         return count;
274 }
275 static DEVICE_ATTR_RW(allow_restart);
276
277 static ssize_t
278 cache_type_show(struct device *dev, struct device_attribute *attr, char *buf)
279 {
280         struct scsi_disk *sdkp = to_scsi_disk(dev);
281         int ct = sdkp->RCD + 2*sdkp->WCE;
282
283         return sprintf(buf, "%s\n", sd_cache_types[ct]);
284 }
285 static DEVICE_ATTR_RW(cache_type);
286
287 static ssize_t
288 FUA_show(struct device *dev, struct device_attribute *attr, char *buf)
289 {
290         struct scsi_disk *sdkp = to_scsi_disk(dev);
291
292         return sprintf(buf, "%u\n", sdkp->DPOFUA);
293 }
294 static DEVICE_ATTR_RO(FUA);
295
296 static ssize_t
297 protection_type_show(struct device *dev, struct device_attribute *attr,
298                      char *buf)
299 {
300         struct scsi_disk *sdkp = to_scsi_disk(dev);
301
302         return sprintf(buf, "%u\n", sdkp->protection_type);
303 }
304
305 static ssize_t
306 protection_type_store(struct device *dev, struct device_attribute *attr,
307                       const char *buf, size_t count)
308 {
309         struct scsi_disk *sdkp = to_scsi_disk(dev);
310         unsigned int val;
311         int err;
312
313         if (!capable(CAP_SYS_ADMIN))
314                 return -EACCES;
315
316         err = kstrtouint(buf, 10, &val);
317
318         if (err)
319                 return err;
320
321         if (val <= T10_PI_TYPE3_PROTECTION)
322                 sdkp->protection_type = val;
323
324         return count;
325 }
326 static DEVICE_ATTR_RW(protection_type);
327
328 static ssize_t
329 protection_mode_show(struct device *dev, struct device_attribute *attr,
330                      char *buf)
331 {
332         struct scsi_disk *sdkp = to_scsi_disk(dev);
333         struct scsi_device *sdp = sdkp->device;
334         unsigned int dif, dix;
335
336         dif = scsi_host_dif_capable(sdp->host, sdkp->protection_type);
337         dix = scsi_host_dix_capable(sdp->host, sdkp->protection_type);
338
339         if (!dix && scsi_host_dix_capable(sdp->host, T10_PI_TYPE0_PROTECTION)) {
340                 dif = 0;
341                 dix = 1;
342         }
343
344         if (!dif && !dix)
345                 return sprintf(buf, "none\n");
346
347         return sprintf(buf, "%s%u\n", dix ? "dix" : "dif", dif);
348 }
349 static DEVICE_ATTR_RO(protection_mode);
350
351 static ssize_t
352 app_tag_own_show(struct device *dev, struct device_attribute *attr, char *buf)
353 {
354         struct scsi_disk *sdkp = to_scsi_disk(dev);
355
356         return sprintf(buf, "%u\n", sdkp->ATO);
357 }
358 static DEVICE_ATTR_RO(app_tag_own);
359
360 static ssize_t
361 thin_provisioning_show(struct device *dev, struct device_attribute *attr,
362                        char *buf)
363 {
364         struct scsi_disk *sdkp = to_scsi_disk(dev);
365
366         return sprintf(buf, "%u\n", sdkp->lbpme);
367 }
368 static DEVICE_ATTR_RO(thin_provisioning);
369
370 /* sysfs_match_string() requires dense arrays */
371 static const char *lbp_mode[] = {
372         [SD_LBP_FULL]           = "full",
373         [SD_LBP_UNMAP]          = "unmap",
374         [SD_LBP_WS16]           = "writesame_16",
375         [SD_LBP_WS10]           = "writesame_10",
376         [SD_LBP_ZERO]           = "writesame_zero",
377         [SD_LBP_DISABLE]        = "disabled",
378 };
379
380 static ssize_t
381 provisioning_mode_show(struct device *dev, struct device_attribute *attr,
382                        char *buf)
383 {
384         struct scsi_disk *sdkp = to_scsi_disk(dev);
385
386         return sprintf(buf, "%s\n", lbp_mode[sdkp->provisioning_mode]);
387 }
388
389 static ssize_t
390 provisioning_mode_store(struct device *dev, struct device_attribute *attr,
391                         const char *buf, size_t count)
392 {
393         struct scsi_disk *sdkp = to_scsi_disk(dev);
394         struct scsi_device *sdp = sdkp->device;
395         int mode;
396
397         if (!capable(CAP_SYS_ADMIN))
398                 return -EACCES;
399
400         if (sd_is_zoned(sdkp)) {
401                 sd_config_discard(sdkp, SD_LBP_DISABLE);
402                 return count;
403         }
404
405         if (sdp->type != TYPE_DISK)
406                 return -EINVAL;
407
408         mode = sysfs_match_string(lbp_mode, buf);
409         if (mode < 0)
410                 return -EINVAL;
411
412         sd_config_discard(sdkp, mode);
413
414         return count;
415 }
416 static DEVICE_ATTR_RW(provisioning_mode);
417
418 /* sysfs_match_string() requires dense arrays */
419 static const char *zeroing_mode[] = {
420         [SD_ZERO_WRITE]         = "write",
421         [SD_ZERO_WS]            = "writesame",
422         [SD_ZERO_WS16_UNMAP]    = "writesame_16_unmap",
423         [SD_ZERO_WS10_UNMAP]    = "writesame_10_unmap",
424 };
425
426 static ssize_t
427 zeroing_mode_show(struct device *dev, struct device_attribute *attr,
428                   char *buf)
429 {
430         struct scsi_disk *sdkp = to_scsi_disk(dev);
431
432         return sprintf(buf, "%s\n", zeroing_mode[sdkp->zeroing_mode]);
433 }
434
435 static ssize_t
436 zeroing_mode_store(struct device *dev, struct device_attribute *attr,
437                    const char *buf, size_t count)
438 {
439         struct scsi_disk *sdkp = to_scsi_disk(dev);
440         int mode;
441
442         if (!capable(CAP_SYS_ADMIN))
443                 return -EACCES;
444
445         mode = sysfs_match_string(zeroing_mode, buf);
446         if (mode < 0)
447                 return -EINVAL;
448
449         sdkp->zeroing_mode = mode;
450
451         return count;
452 }
453 static DEVICE_ATTR_RW(zeroing_mode);
454
455 static ssize_t
456 max_medium_access_timeouts_show(struct device *dev,
457                                 struct device_attribute *attr, char *buf)
458 {
459         struct scsi_disk *sdkp = to_scsi_disk(dev);
460
461         return sprintf(buf, "%u\n", sdkp->max_medium_access_timeouts);
462 }
463
464 static ssize_t
465 max_medium_access_timeouts_store(struct device *dev,
466                                  struct device_attribute *attr, const char *buf,
467                                  size_t count)
468 {
469         struct scsi_disk *sdkp = to_scsi_disk(dev);
470         int err;
471
472         if (!capable(CAP_SYS_ADMIN))
473                 return -EACCES;
474
475         err = kstrtouint(buf, 10, &sdkp->max_medium_access_timeouts);
476
477         return err ? err : count;
478 }
479 static DEVICE_ATTR_RW(max_medium_access_timeouts);
480
481 static ssize_t
482 max_write_same_blocks_show(struct device *dev, struct device_attribute *attr,
483                            char *buf)
484 {
485         struct scsi_disk *sdkp = to_scsi_disk(dev);
486
487         return sprintf(buf, "%u\n", sdkp->max_ws_blocks);
488 }
489
490 static ssize_t
491 max_write_same_blocks_store(struct device *dev, struct device_attribute *attr,
492                             const char *buf, size_t count)
493 {
494         struct scsi_disk *sdkp = to_scsi_disk(dev);
495         struct scsi_device *sdp = sdkp->device;
496         unsigned long max;
497         int err;
498
499         if (!capable(CAP_SYS_ADMIN))
500                 return -EACCES;
501
502         if (sdp->type != TYPE_DISK && sdp->type != TYPE_ZBC)
503                 return -EINVAL;
504
505         err = kstrtoul(buf, 10, &max);
506
507         if (err)
508                 return err;
509
510         if (max == 0)
511                 sdp->no_write_same = 1;
512         else if (max <= SD_MAX_WS16_BLOCKS) {
513                 sdp->no_write_same = 0;
514                 sdkp->max_ws_blocks = max;
515         }
516
517         sd_config_write_same(sdkp);
518
519         return count;
520 }
521 static DEVICE_ATTR_RW(max_write_same_blocks);
522
523 static ssize_t
524 zoned_cap_show(struct device *dev, struct device_attribute *attr, char *buf)
525 {
526         struct scsi_disk *sdkp = to_scsi_disk(dev);
527
528         if (sdkp->device->type == TYPE_ZBC)
529                 return sprintf(buf, "host-managed\n");
530         if (sdkp->zoned == 1)
531                 return sprintf(buf, "host-aware\n");
532         if (sdkp->zoned == 2)
533                 return sprintf(buf, "drive-managed\n");
534         return sprintf(buf, "none\n");
535 }
536 static DEVICE_ATTR_RO(zoned_cap);
537
538 static ssize_t
539 max_retries_store(struct device *dev, struct device_attribute *attr,
540                   const char *buf, size_t count)
541 {
542         struct scsi_disk *sdkp = to_scsi_disk(dev);
543         struct scsi_device *sdev = sdkp->device;
544         int retries, err;
545
546         err = kstrtoint(buf, 10, &retries);
547         if (err)
548                 return err;
549
550         if (retries == SCSI_CMD_RETRIES_NO_LIMIT || retries <= SD_MAX_RETRIES) {
551                 sdkp->max_retries = retries;
552                 return count;
553         }
554
555         sdev_printk(KERN_ERR, sdev, "max_retries must be between -1 and %d\n",
556                     SD_MAX_RETRIES);
557         return -EINVAL;
558 }
559
560 static ssize_t
561 max_retries_show(struct device *dev, struct device_attribute *attr,
562                  char *buf)
563 {
564         struct scsi_disk *sdkp = to_scsi_disk(dev);
565
566         return sprintf(buf, "%d\n", sdkp->max_retries);
567 }
568
569 static DEVICE_ATTR_RW(max_retries);
570
571 static struct attribute *sd_disk_attrs[] = {
572         &dev_attr_cache_type.attr,
573         &dev_attr_FUA.attr,
574         &dev_attr_allow_restart.attr,
575         &dev_attr_manage_start_stop.attr,
576         &dev_attr_protection_type.attr,
577         &dev_attr_protection_mode.attr,
578         &dev_attr_app_tag_own.attr,
579         &dev_attr_thin_provisioning.attr,
580         &dev_attr_provisioning_mode.attr,
581         &dev_attr_zeroing_mode.attr,
582         &dev_attr_max_write_same_blocks.attr,
583         &dev_attr_max_medium_access_timeouts.attr,
584         &dev_attr_zoned_cap.attr,
585         &dev_attr_max_retries.attr,
586         NULL,
587 };
588 ATTRIBUTE_GROUPS(sd_disk);
589
590 static struct class sd_disk_class = {
591         .name           = "scsi_disk",
592         .owner          = THIS_MODULE,
593         .dev_release    = scsi_disk_release,
594         .dev_groups     = sd_disk_groups,
595 };
596
597 static const struct dev_pm_ops sd_pm_ops = {
598         .suspend                = sd_suspend_system,
599         .resume                 = sd_resume_system,
600         .poweroff               = sd_suspend_system,
601         .restore                = sd_resume_system,
602         .runtime_suspend        = sd_suspend_runtime,
603         .runtime_resume         = sd_resume_runtime,
604 };
605
606 static struct scsi_driver sd_template = {
607         .gendrv = {
608                 .name           = "sd",
609                 .owner          = THIS_MODULE,
610                 .probe          = sd_probe,
611                 .probe_type     = PROBE_PREFER_ASYNCHRONOUS,
612                 .remove         = sd_remove,
613                 .shutdown       = sd_shutdown,
614                 .pm             = &sd_pm_ops,
615         },
616         .rescan                 = sd_rescan,
617         .init_command           = sd_init_command,
618         .uninit_command         = sd_uninit_command,
619         .done                   = sd_done,
620         .eh_action              = sd_eh_action,
621         .eh_reset               = sd_eh_reset,
622 };
623
624 /*
625  * Don't request a new module, as that could deadlock in multipath
626  * environment.
627  */
628 static void sd_default_probe(dev_t devt)
629 {
630 }
631
632 /*
633  * Device no to disk mapping:
634  * 
635  *       major         disc2     disc  p1
636  *   |............|.............|....|....| <- dev_t
637  *    31        20 19          8 7  4 3  0
638  * 
639  * Inside a major, we have 16k disks, however mapped non-
640  * contiguously. The first 16 disks are for major0, the next
641  * ones with major1, ... Disk 256 is for major0 again, disk 272 
642  * for major1, ... 
643  * As we stay compatible with our numbering scheme, we can reuse 
644  * the well-know SCSI majors 8, 65--71, 136--143.
645  */
646 static int sd_major(int major_idx)
647 {
648         switch (major_idx) {
649         case 0:
650                 return SCSI_DISK0_MAJOR;
651         case 1 ... 7:
652                 return SCSI_DISK1_MAJOR + major_idx - 1;
653         case 8 ... 15:
654                 return SCSI_DISK8_MAJOR + major_idx - 8;
655         default:
656                 BUG();
657                 return 0;       /* shut up gcc */
658         }
659 }
660
661 #ifdef CONFIG_BLK_SED_OPAL
662 static int sd_sec_submit(void *data, u16 spsp, u8 secp, void *buffer,
663                 size_t len, bool send)
664 {
665         struct scsi_disk *sdkp = data;
666         struct scsi_device *sdev = sdkp->device;
667         u8 cdb[12] = { 0, };
668         int ret;
669
670         cdb[0] = send ? SECURITY_PROTOCOL_OUT : SECURITY_PROTOCOL_IN;
671         cdb[1] = secp;
672         put_unaligned_be16(spsp, &cdb[2]);
673         put_unaligned_be32(len, &cdb[6]);
674
675         ret = scsi_execute(sdev, cdb, send ? DMA_TO_DEVICE : DMA_FROM_DEVICE,
676                 buffer, len, NULL, NULL, SD_TIMEOUT, sdkp->max_retries, 0,
677                 RQF_PM, NULL);
678         return ret <= 0 ? ret : -EIO;
679 }
680 #endif /* CONFIG_BLK_SED_OPAL */
681
682 /*
683  * Look up the DIX operation based on whether the command is read or
684  * write and whether dix and dif are enabled.
685  */
686 static unsigned int sd_prot_op(bool write, bool dix, bool dif)
687 {
688         /* Lookup table: bit 2 (write), bit 1 (dix), bit 0 (dif) */
689         static const unsigned int ops[] = {     /* wrt dix dif */
690                 SCSI_PROT_NORMAL,               /*  0   0   0  */
691                 SCSI_PROT_READ_STRIP,           /*  0   0   1  */
692                 SCSI_PROT_READ_INSERT,          /*  0   1   0  */
693                 SCSI_PROT_READ_PASS,            /*  0   1   1  */
694                 SCSI_PROT_NORMAL,               /*  1   0   0  */
695                 SCSI_PROT_WRITE_INSERT,         /*  1   0   1  */
696                 SCSI_PROT_WRITE_STRIP,          /*  1   1   0  */
697                 SCSI_PROT_WRITE_PASS,           /*  1   1   1  */
698         };
699
700         return ops[write << 2 | dix << 1 | dif];
701 }
702
703 /*
704  * Returns a mask of the protection flags that are valid for a given DIX
705  * operation.
706  */
707 static unsigned int sd_prot_flag_mask(unsigned int prot_op)
708 {
709         static const unsigned int flag_mask[] = {
710                 [SCSI_PROT_NORMAL]              = 0,
711
712                 [SCSI_PROT_READ_STRIP]          = SCSI_PROT_TRANSFER_PI |
713                                                   SCSI_PROT_GUARD_CHECK |
714                                                   SCSI_PROT_REF_CHECK |
715                                                   SCSI_PROT_REF_INCREMENT,
716
717                 [SCSI_PROT_READ_INSERT]         = SCSI_PROT_REF_INCREMENT |
718                                                   SCSI_PROT_IP_CHECKSUM,
719
720                 [SCSI_PROT_READ_PASS]           = SCSI_PROT_TRANSFER_PI |
721                                                   SCSI_PROT_GUARD_CHECK |
722                                                   SCSI_PROT_REF_CHECK |
723                                                   SCSI_PROT_REF_INCREMENT |
724                                                   SCSI_PROT_IP_CHECKSUM,
725
726                 [SCSI_PROT_WRITE_INSERT]        = SCSI_PROT_TRANSFER_PI |
727                                                   SCSI_PROT_REF_INCREMENT,
728
729                 [SCSI_PROT_WRITE_STRIP]         = SCSI_PROT_GUARD_CHECK |
730                                                   SCSI_PROT_REF_CHECK |
731                                                   SCSI_PROT_REF_INCREMENT |
732                                                   SCSI_PROT_IP_CHECKSUM,
733
734                 [SCSI_PROT_WRITE_PASS]          = SCSI_PROT_TRANSFER_PI |
735                                                   SCSI_PROT_GUARD_CHECK |
736                                                   SCSI_PROT_REF_CHECK |
737                                                   SCSI_PROT_REF_INCREMENT |
738                                                   SCSI_PROT_IP_CHECKSUM,
739         };
740
741         return flag_mask[prot_op];
742 }
743
744 static unsigned char sd_setup_protect_cmnd(struct scsi_cmnd *scmd,
745                                            unsigned int dix, unsigned int dif)
746 {
747         struct request *rq = scsi_cmd_to_rq(scmd);
748         struct bio *bio = rq->bio;
749         unsigned int prot_op = sd_prot_op(rq_data_dir(rq), dix, dif);
750         unsigned int protect = 0;
751
752         if (dix) {                              /* DIX Type 0, 1, 2, 3 */
753                 if (bio_integrity_flagged(bio, BIP_IP_CHECKSUM))
754                         scmd->prot_flags |= SCSI_PROT_IP_CHECKSUM;
755
756                 if (bio_integrity_flagged(bio, BIP_CTRL_NOCHECK) == false)
757                         scmd->prot_flags |= SCSI_PROT_GUARD_CHECK;
758         }
759
760         if (dif != T10_PI_TYPE3_PROTECTION) {   /* DIX/DIF Type 0, 1, 2 */
761                 scmd->prot_flags |= SCSI_PROT_REF_INCREMENT;
762
763                 if (bio_integrity_flagged(bio, BIP_CTRL_NOCHECK) == false)
764                         scmd->prot_flags |= SCSI_PROT_REF_CHECK;
765         }
766
767         if (dif) {                              /* DIX/DIF Type 1, 2, 3 */
768                 scmd->prot_flags |= SCSI_PROT_TRANSFER_PI;
769
770                 if (bio_integrity_flagged(bio, BIP_DISK_NOCHECK))
771                         protect = 3 << 5;       /* Disable target PI checking */
772                 else
773                         protect = 1 << 5;       /* Enable target PI checking */
774         }
775
776         scsi_set_prot_op(scmd, prot_op);
777         scsi_set_prot_type(scmd, dif);
778         scmd->prot_flags &= sd_prot_flag_mask(prot_op);
779
780         return protect;
781 }
782
783 static void sd_config_discard(struct scsi_disk *sdkp, unsigned int mode)
784 {
785         struct request_queue *q = sdkp->disk->queue;
786         unsigned int logical_block_size = sdkp->device->sector_size;
787         unsigned int max_blocks = 0;
788
789         q->limits.discard_alignment =
790                 sdkp->unmap_alignment * logical_block_size;
791         q->limits.discard_granularity =
792                 max(sdkp->physical_block_size,
793                     sdkp->unmap_granularity * logical_block_size);
794         sdkp->provisioning_mode = mode;
795
796         switch (mode) {
797
798         case SD_LBP_FULL:
799         case SD_LBP_DISABLE:
800                 blk_queue_max_discard_sectors(q, 0);
801                 return;
802
803         case SD_LBP_UNMAP:
804                 max_blocks = min_not_zero(sdkp->max_unmap_blocks,
805                                           (u32)SD_MAX_WS16_BLOCKS);
806                 break;
807
808         case SD_LBP_WS16:
809                 if (sdkp->device->unmap_limit_for_ws)
810                         max_blocks = sdkp->max_unmap_blocks;
811                 else
812                         max_blocks = sdkp->max_ws_blocks;
813
814                 max_blocks = min_not_zero(max_blocks, (u32)SD_MAX_WS16_BLOCKS);
815                 break;
816
817         case SD_LBP_WS10:
818                 if (sdkp->device->unmap_limit_for_ws)
819                         max_blocks = sdkp->max_unmap_blocks;
820                 else
821                         max_blocks = sdkp->max_ws_blocks;
822
823                 max_blocks = min_not_zero(max_blocks, (u32)SD_MAX_WS10_BLOCKS);
824                 break;
825
826         case SD_LBP_ZERO:
827                 max_blocks = min_not_zero(sdkp->max_ws_blocks,
828                                           (u32)SD_MAX_WS10_BLOCKS);
829                 break;
830         }
831
832         blk_queue_max_discard_sectors(q, max_blocks * (logical_block_size >> 9));
833 }
834
835 static blk_status_t sd_setup_unmap_cmnd(struct scsi_cmnd *cmd)
836 {
837         struct scsi_device *sdp = cmd->device;
838         struct request *rq = scsi_cmd_to_rq(cmd);
839         struct scsi_disk *sdkp = scsi_disk(rq->q->disk);
840         u64 lba = sectors_to_logical(sdp, blk_rq_pos(rq));
841         u32 nr_blocks = sectors_to_logical(sdp, blk_rq_sectors(rq));
842         unsigned int data_len = 24;
843         char *buf;
844
845         rq->special_vec.bv_page = mempool_alloc(sd_page_pool, GFP_ATOMIC);
846         if (!rq->special_vec.bv_page)
847                 return BLK_STS_RESOURCE;
848         clear_highpage(rq->special_vec.bv_page);
849         rq->special_vec.bv_offset = 0;
850         rq->special_vec.bv_len = data_len;
851         rq->rq_flags |= RQF_SPECIAL_PAYLOAD;
852
853         cmd->cmd_len = 10;
854         cmd->cmnd[0] = UNMAP;
855         cmd->cmnd[8] = 24;
856
857         buf = bvec_virt(&rq->special_vec);
858         put_unaligned_be16(6 + 16, &buf[0]);
859         put_unaligned_be16(16, &buf[2]);
860         put_unaligned_be64(lba, &buf[8]);
861         put_unaligned_be32(nr_blocks, &buf[16]);
862
863         cmd->allowed = sdkp->max_retries;
864         cmd->transfersize = data_len;
865         rq->timeout = SD_TIMEOUT;
866
867         return scsi_alloc_sgtables(cmd);
868 }
869
870 static blk_status_t sd_setup_write_same16_cmnd(struct scsi_cmnd *cmd,
871                 bool unmap)
872 {
873         struct scsi_device *sdp = cmd->device;
874         struct request *rq = scsi_cmd_to_rq(cmd);
875         struct scsi_disk *sdkp = scsi_disk(rq->q->disk);
876         u64 lba = sectors_to_logical(sdp, blk_rq_pos(rq));
877         u32 nr_blocks = sectors_to_logical(sdp, blk_rq_sectors(rq));
878         u32 data_len = sdp->sector_size;
879
880         rq->special_vec.bv_page = mempool_alloc(sd_page_pool, GFP_ATOMIC);
881         if (!rq->special_vec.bv_page)
882                 return BLK_STS_RESOURCE;
883         clear_highpage(rq->special_vec.bv_page);
884         rq->special_vec.bv_offset = 0;
885         rq->special_vec.bv_len = data_len;
886         rq->rq_flags |= RQF_SPECIAL_PAYLOAD;
887
888         cmd->cmd_len = 16;
889         cmd->cmnd[0] = WRITE_SAME_16;
890         if (unmap)
891                 cmd->cmnd[1] = 0x8; /* UNMAP */
892         put_unaligned_be64(lba, &cmd->cmnd[2]);
893         put_unaligned_be32(nr_blocks, &cmd->cmnd[10]);
894
895         cmd->allowed = sdkp->max_retries;
896         cmd->transfersize = data_len;
897         rq->timeout = unmap ? SD_TIMEOUT : SD_WRITE_SAME_TIMEOUT;
898
899         return scsi_alloc_sgtables(cmd);
900 }
901
902 static blk_status_t sd_setup_write_same10_cmnd(struct scsi_cmnd *cmd,
903                 bool unmap)
904 {
905         struct scsi_device *sdp = cmd->device;
906         struct request *rq = scsi_cmd_to_rq(cmd);
907         struct scsi_disk *sdkp = scsi_disk(rq->q->disk);
908         u64 lba = sectors_to_logical(sdp, blk_rq_pos(rq));
909         u32 nr_blocks = sectors_to_logical(sdp, blk_rq_sectors(rq));
910         u32 data_len = sdp->sector_size;
911
912         rq->special_vec.bv_page = mempool_alloc(sd_page_pool, GFP_ATOMIC);
913         if (!rq->special_vec.bv_page)
914                 return BLK_STS_RESOURCE;
915         clear_highpage(rq->special_vec.bv_page);
916         rq->special_vec.bv_offset = 0;
917         rq->special_vec.bv_len = data_len;
918         rq->rq_flags |= RQF_SPECIAL_PAYLOAD;
919
920         cmd->cmd_len = 10;
921         cmd->cmnd[0] = WRITE_SAME;
922         if (unmap)
923                 cmd->cmnd[1] = 0x8; /* UNMAP */
924         put_unaligned_be32(lba, &cmd->cmnd[2]);
925         put_unaligned_be16(nr_blocks, &cmd->cmnd[7]);
926
927         cmd->allowed = sdkp->max_retries;
928         cmd->transfersize = data_len;
929         rq->timeout = unmap ? SD_TIMEOUT : SD_WRITE_SAME_TIMEOUT;
930
931         return scsi_alloc_sgtables(cmd);
932 }
933
934 static blk_status_t sd_setup_write_zeroes_cmnd(struct scsi_cmnd *cmd)
935 {
936         struct request *rq = scsi_cmd_to_rq(cmd);
937         struct scsi_device *sdp = cmd->device;
938         struct scsi_disk *sdkp = scsi_disk(rq->q->disk);
939         u64 lba = sectors_to_logical(sdp, blk_rq_pos(rq));
940         u32 nr_blocks = sectors_to_logical(sdp, blk_rq_sectors(rq));
941
942         if (!(rq->cmd_flags & REQ_NOUNMAP)) {
943                 switch (sdkp->zeroing_mode) {
944                 case SD_ZERO_WS16_UNMAP:
945                         return sd_setup_write_same16_cmnd(cmd, true);
946                 case SD_ZERO_WS10_UNMAP:
947                         return sd_setup_write_same10_cmnd(cmd, true);
948                 }
949         }
950
951         if (sdp->no_write_same) {
952                 rq->rq_flags |= RQF_QUIET;
953                 return BLK_STS_TARGET;
954         }
955
956         if (sdkp->ws16 || lba > 0xffffffff || nr_blocks > 0xffff)
957                 return sd_setup_write_same16_cmnd(cmd, false);
958
959         return sd_setup_write_same10_cmnd(cmd, false);
960 }
961
962 static void sd_config_write_same(struct scsi_disk *sdkp)
963 {
964         struct request_queue *q = sdkp->disk->queue;
965         unsigned int logical_block_size = sdkp->device->sector_size;
966
967         if (sdkp->device->no_write_same) {
968                 sdkp->max_ws_blocks = 0;
969                 goto out;
970         }
971
972         /* Some devices can not handle block counts above 0xffff despite
973          * supporting WRITE SAME(16). Consequently we default to 64k
974          * blocks per I/O unless the device explicitly advertises a
975          * bigger limit.
976          */
977         if (sdkp->max_ws_blocks > SD_MAX_WS10_BLOCKS)
978                 sdkp->max_ws_blocks = min_not_zero(sdkp->max_ws_blocks,
979                                                    (u32)SD_MAX_WS16_BLOCKS);
980         else if (sdkp->ws16 || sdkp->ws10 || sdkp->device->no_report_opcodes)
981                 sdkp->max_ws_blocks = min_not_zero(sdkp->max_ws_blocks,
982                                                    (u32)SD_MAX_WS10_BLOCKS);
983         else {
984                 sdkp->device->no_write_same = 1;
985                 sdkp->max_ws_blocks = 0;
986         }
987
988         if (sdkp->lbprz && sdkp->lbpws)
989                 sdkp->zeroing_mode = SD_ZERO_WS16_UNMAP;
990         else if (sdkp->lbprz && sdkp->lbpws10)
991                 sdkp->zeroing_mode = SD_ZERO_WS10_UNMAP;
992         else if (sdkp->max_ws_blocks)
993                 sdkp->zeroing_mode = SD_ZERO_WS;
994         else
995                 sdkp->zeroing_mode = SD_ZERO_WRITE;
996
997         if (sdkp->max_ws_blocks &&
998             sdkp->physical_block_size > logical_block_size) {
999                 /*
1000                  * Reporting a maximum number of blocks that is not aligned
1001                  * on the device physical size would cause a large write same
1002                  * request to be split into physically unaligned chunks by
1003                  * __blkdev_issue_write_zeroes() even if the caller of this
1004                  * functions took care to align the large request. So make sure
1005                  * the maximum reported is aligned to the device physical block
1006                  * size. This is only an optional optimization for regular
1007                  * disks, but this is mandatory to avoid failure of large write
1008                  * same requests directed at sequential write required zones of
1009                  * host-managed ZBC disks.
1010                  */
1011                 sdkp->max_ws_blocks =
1012                         round_down(sdkp->max_ws_blocks,
1013                                    bytes_to_logical(sdkp->device,
1014                                                     sdkp->physical_block_size));
1015         }
1016
1017 out:
1018         blk_queue_max_write_zeroes_sectors(q, sdkp->max_ws_blocks *
1019                                          (logical_block_size >> 9));
1020 }
1021
1022 static blk_status_t sd_setup_flush_cmnd(struct scsi_cmnd *cmd)
1023 {
1024         struct request *rq = scsi_cmd_to_rq(cmd);
1025         struct scsi_disk *sdkp = scsi_disk(rq->q->disk);
1026
1027         /* flush requests don't perform I/O, zero the S/G table */
1028         memset(&cmd->sdb, 0, sizeof(cmd->sdb));
1029
1030         cmd->cmnd[0] = SYNCHRONIZE_CACHE;
1031         cmd->cmd_len = 10;
1032         cmd->transfersize = 0;
1033         cmd->allowed = sdkp->max_retries;
1034
1035         rq->timeout = rq->q->rq_timeout * SD_FLUSH_TIMEOUT_MULTIPLIER;
1036         return BLK_STS_OK;
1037 }
1038
1039 static blk_status_t sd_setup_rw32_cmnd(struct scsi_cmnd *cmd, bool write,
1040                                        sector_t lba, unsigned int nr_blocks,
1041                                        unsigned char flags)
1042 {
1043         cmd->cmd_len = SD_EXT_CDB_SIZE;
1044         cmd->cmnd[0]  = VARIABLE_LENGTH_CMD;
1045         cmd->cmnd[7]  = 0x18; /* Additional CDB len */
1046         cmd->cmnd[9]  = write ? WRITE_32 : READ_32;
1047         cmd->cmnd[10] = flags;
1048         put_unaligned_be64(lba, &cmd->cmnd[12]);
1049         put_unaligned_be32(lba, &cmd->cmnd[20]); /* Expected Indirect LBA */
1050         put_unaligned_be32(nr_blocks, &cmd->cmnd[28]);
1051
1052         return BLK_STS_OK;
1053 }
1054
1055 static blk_status_t sd_setup_rw16_cmnd(struct scsi_cmnd *cmd, bool write,
1056                                        sector_t lba, unsigned int nr_blocks,
1057                                        unsigned char flags)
1058 {
1059         cmd->cmd_len  = 16;
1060         cmd->cmnd[0]  = write ? WRITE_16 : READ_16;
1061         cmd->cmnd[1]  = flags;
1062         cmd->cmnd[14] = 0;
1063         cmd->cmnd[15] = 0;
1064         put_unaligned_be64(lba, &cmd->cmnd[2]);
1065         put_unaligned_be32(nr_blocks, &cmd->cmnd[10]);
1066
1067         return BLK_STS_OK;
1068 }
1069
1070 static blk_status_t sd_setup_rw10_cmnd(struct scsi_cmnd *cmd, bool write,
1071                                        sector_t lba, unsigned int nr_blocks,
1072                                        unsigned char flags)
1073 {
1074         cmd->cmd_len = 10;
1075         cmd->cmnd[0] = write ? WRITE_10 : READ_10;
1076         cmd->cmnd[1] = flags;
1077         cmd->cmnd[6] = 0;
1078         cmd->cmnd[9] = 0;
1079         put_unaligned_be32(lba, &cmd->cmnd[2]);
1080         put_unaligned_be16(nr_blocks, &cmd->cmnd[7]);
1081
1082         return BLK_STS_OK;
1083 }
1084
1085 static blk_status_t sd_setup_rw6_cmnd(struct scsi_cmnd *cmd, bool write,
1086                                       sector_t lba, unsigned int nr_blocks,
1087                                       unsigned char flags)
1088 {
1089         /* Avoid that 0 blocks gets translated into 256 blocks. */
1090         if (WARN_ON_ONCE(nr_blocks == 0))
1091                 return BLK_STS_IOERR;
1092
1093         if (unlikely(flags & 0x8)) {
1094                 /*
1095                  * This happens only if this drive failed 10byte rw
1096                  * command with ILLEGAL_REQUEST during operation and
1097                  * thus turned off use_10_for_rw.
1098                  */
1099                 scmd_printk(KERN_ERR, cmd, "FUA write on READ/WRITE(6) drive\n");
1100                 return BLK_STS_IOERR;
1101         }
1102
1103         cmd->cmd_len = 6;
1104         cmd->cmnd[0] = write ? WRITE_6 : READ_6;
1105         cmd->cmnd[1] = (lba >> 16) & 0x1f;
1106         cmd->cmnd[2] = (lba >> 8) & 0xff;
1107         cmd->cmnd[3] = lba & 0xff;
1108         cmd->cmnd[4] = nr_blocks;
1109         cmd->cmnd[5] = 0;
1110
1111         return BLK_STS_OK;
1112 }
1113
1114 static blk_status_t sd_setup_read_write_cmnd(struct scsi_cmnd *cmd)
1115 {
1116         struct request *rq = scsi_cmd_to_rq(cmd);
1117         struct scsi_device *sdp = cmd->device;
1118         struct scsi_disk *sdkp = scsi_disk(rq->q->disk);
1119         sector_t lba = sectors_to_logical(sdp, blk_rq_pos(rq));
1120         sector_t threshold;
1121         unsigned int nr_blocks = sectors_to_logical(sdp, blk_rq_sectors(rq));
1122         unsigned int mask = logical_to_sectors(sdp, 1) - 1;
1123         bool write = rq_data_dir(rq) == WRITE;
1124         unsigned char protect, fua;
1125         blk_status_t ret;
1126         unsigned int dif;
1127         bool dix;
1128
1129         ret = scsi_alloc_sgtables(cmd);
1130         if (ret != BLK_STS_OK)
1131                 return ret;
1132
1133         ret = BLK_STS_IOERR;
1134         if (!scsi_device_online(sdp) || sdp->changed) {
1135                 scmd_printk(KERN_ERR, cmd, "device offline or changed\n");
1136                 goto fail;
1137         }
1138
1139         if (blk_rq_pos(rq) + blk_rq_sectors(rq) > get_capacity(rq->q->disk)) {
1140                 scmd_printk(KERN_ERR, cmd, "access beyond end of device\n");
1141                 goto fail;
1142         }
1143
1144         if ((blk_rq_pos(rq) & mask) || (blk_rq_sectors(rq) & mask)) {
1145                 scmd_printk(KERN_ERR, cmd, "request not aligned to the logical block size\n");
1146                 goto fail;
1147         }
1148
1149         /*
1150          * Some SD card readers can't handle accesses which touch the
1151          * last one or two logical blocks. Split accesses as needed.
1152          */
1153         threshold = sdkp->capacity - SD_LAST_BUGGY_SECTORS;
1154
1155         if (unlikely(sdp->last_sector_bug && lba + nr_blocks > threshold)) {
1156                 if (lba < threshold) {
1157                         /* Access up to the threshold but not beyond */
1158                         nr_blocks = threshold - lba;
1159                 } else {
1160                         /* Access only a single logical block */
1161                         nr_blocks = 1;
1162                 }
1163         }
1164
1165         if (req_op(rq) == REQ_OP_ZONE_APPEND) {
1166                 ret = sd_zbc_prepare_zone_append(cmd, &lba, nr_blocks);
1167                 if (ret)
1168                         goto fail;
1169         }
1170
1171         fua = rq->cmd_flags & REQ_FUA ? 0x8 : 0;
1172         dix = scsi_prot_sg_count(cmd);
1173         dif = scsi_host_dif_capable(cmd->device->host, sdkp->protection_type);
1174
1175         if (dif || dix)
1176                 protect = sd_setup_protect_cmnd(cmd, dix, dif);
1177         else
1178                 protect = 0;
1179
1180         if (protect && sdkp->protection_type == T10_PI_TYPE2_PROTECTION) {
1181                 ret = sd_setup_rw32_cmnd(cmd, write, lba, nr_blocks,
1182                                          protect | fua);
1183         } else if (sdp->use_16_for_rw || (nr_blocks > 0xffff)) {
1184                 ret = sd_setup_rw16_cmnd(cmd, write, lba, nr_blocks,
1185                                          protect | fua);
1186         } else if ((nr_blocks > 0xff) || (lba > 0x1fffff) ||
1187                    sdp->use_10_for_rw || protect) {
1188                 ret = sd_setup_rw10_cmnd(cmd, write, lba, nr_blocks,
1189                                          protect | fua);
1190         } else {
1191                 ret = sd_setup_rw6_cmnd(cmd, write, lba, nr_blocks,
1192                                         protect | fua);
1193         }
1194
1195         if (unlikely(ret != BLK_STS_OK))
1196                 goto fail;
1197
1198         /*
1199          * We shouldn't disconnect in the middle of a sector, so with a dumb
1200          * host adapter, it's safe to assume that we can at least transfer
1201          * this many bytes between each connect / disconnect.
1202          */
1203         cmd->transfersize = sdp->sector_size;
1204         cmd->underflow = nr_blocks << 9;
1205         cmd->allowed = sdkp->max_retries;
1206         cmd->sdb.length = nr_blocks * sdp->sector_size;
1207
1208         SCSI_LOG_HLQUEUE(1,
1209                          scmd_printk(KERN_INFO, cmd,
1210                                      "%s: block=%llu, count=%d\n", __func__,
1211                                      (unsigned long long)blk_rq_pos(rq),
1212                                      blk_rq_sectors(rq)));
1213         SCSI_LOG_HLQUEUE(2,
1214                          scmd_printk(KERN_INFO, cmd,
1215                                      "%s %d/%u 512 byte blocks.\n",
1216                                      write ? "writing" : "reading", nr_blocks,
1217                                      blk_rq_sectors(rq)));
1218
1219         /*
1220          * This indicates that the command is ready from our end to be queued.
1221          */
1222         return BLK_STS_OK;
1223 fail:
1224         scsi_free_sgtables(cmd);
1225         return ret;
1226 }
1227
1228 static blk_status_t sd_init_command(struct scsi_cmnd *cmd)
1229 {
1230         struct request *rq = scsi_cmd_to_rq(cmd);
1231
1232         switch (req_op(rq)) {
1233         case REQ_OP_DISCARD:
1234                 switch (scsi_disk(rq->q->disk)->provisioning_mode) {
1235                 case SD_LBP_UNMAP:
1236                         return sd_setup_unmap_cmnd(cmd);
1237                 case SD_LBP_WS16:
1238                         return sd_setup_write_same16_cmnd(cmd, true);
1239                 case SD_LBP_WS10:
1240                         return sd_setup_write_same10_cmnd(cmd, true);
1241                 case SD_LBP_ZERO:
1242                         return sd_setup_write_same10_cmnd(cmd, false);
1243                 default:
1244                         return BLK_STS_TARGET;
1245                 }
1246         case REQ_OP_WRITE_ZEROES:
1247                 return sd_setup_write_zeroes_cmnd(cmd);
1248         case REQ_OP_FLUSH:
1249                 return sd_setup_flush_cmnd(cmd);
1250         case REQ_OP_READ:
1251         case REQ_OP_WRITE:
1252         case REQ_OP_ZONE_APPEND:
1253                 return sd_setup_read_write_cmnd(cmd);
1254         case REQ_OP_ZONE_RESET:
1255                 return sd_zbc_setup_zone_mgmt_cmnd(cmd, ZO_RESET_WRITE_POINTER,
1256                                                    false);
1257         case REQ_OP_ZONE_RESET_ALL:
1258                 return sd_zbc_setup_zone_mgmt_cmnd(cmd, ZO_RESET_WRITE_POINTER,
1259                                                    true);
1260         case REQ_OP_ZONE_OPEN:
1261                 return sd_zbc_setup_zone_mgmt_cmnd(cmd, ZO_OPEN_ZONE, false);
1262         case REQ_OP_ZONE_CLOSE:
1263                 return sd_zbc_setup_zone_mgmt_cmnd(cmd, ZO_CLOSE_ZONE, false);
1264         case REQ_OP_ZONE_FINISH:
1265                 return sd_zbc_setup_zone_mgmt_cmnd(cmd, ZO_FINISH_ZONE, false);
1266         default:
1267                 WARN_ON_ONCE(1);
1268                 return BLK_STS_NOTSUPP;
1269         }
1270 }
1271
1272 static void sd_uninit_command(struct scsi_cmnd *SCpnt)
1273 {
1274         struct request *rq = scsi_cmd_to_rq(SCpnt);
1275
1276         if (rq->rq_flags & RQF_SPECIAL_PAYLOAD)
1277                 mempool_free(rq->special_vec.bv_page, sd_page_pool);
1278 }
1279
1280 static bool sd_need_revalidate(struct block_device *bdev,
1281                 struct scsi_disk *sdkp)
1282 {
1283         if (sdkp->device->removable || sdkp->write_prot) {
1284                 if (bdev_check_media_change(bdev))
1285                         return true;
1286         }
1287
1288         /*
1289          * Force a full rescan after ioctl(BLKRRPART).  While the disk state has
1290          * nothing to do with partitions, BLKRRPART is used to force a full
1291          * revalidate after things like a format for historical reasons.
1292          */
1293         return test_bit(GD_NEED_PART_SCAN, &bdev->bd_disk->state);
1294 }
1295
1296 /**
1297  *      sd_open - open a scsi disk device
1298  *      @bdev: Block device of the scsi disk to open
1299  *      @mode: FMODE_* mask
1300  *
1301  *      Returns 0 if successful. Returns a negated errno value in case 
1302  *      of error.
1303  *
1304  *      Note: This can be called from a user context (e.g. fsck(1) )
1305  *      or from within the kernel (e.g. as a result of a mount(1) ).
1306  *      In the latter case @inode and @filp carry an abridged amount
1307  *      of information as noted above.
1308  *
1309  *      Locking: called with bdev->bd_disk->open_mutex held.
1310  **/
1311 static int sd_open(struct block_device *bdev, fmode_t mode)
1312 {
1313         struct scsi_disk *sdkp = scsi_disk(bdev->bd_disk);
1314         struct scsi_device *sdev = sdkp->device;
1315         int retval;
1316
1317         if (scsi_device_get(sdev))
1318                 return -ENXIO;
1319
1320         SCSI_LOG_HLQUEUE(3, sd_printk(KERN_INFO, sdkp, "sd_open\n"));
1321
1322         /*
1323          * If the device is in error recovery, wait until it is done.
1324          * If the device is offline, then disallow any access to it.
1325          */
1326         retval = -ENXIO;
1327         if (!scsi_block_when_processing_errors(sdev))
1328                 goto error_out;
1329
1330         if (sd_need_revalidate(bdev, sdkp))
1331                 sd_revalidate_disk(bdev->bd_disk);
1332
1333         /*
1334          * If the drive is empty, just let the open fail.
1335          */
1336         retval = -ENOMEDIUM;
1337         if (sdev->removable && !sdkp->media_present && !(mode & FMODE_NDELAY))
1338                 goto error_out;
1339
1340         /*
1341          * If the device has the write protect tab set, have the open fail
1342          * if the user expects to be able to write to the thing.
1343          */
1344         retval = -EROFS;
1345         if (sdkp->write_prot && (mode & FMODE_WRITE))
1346                 goto error_out;
1347
1348         /*
1349          * It is possible that the disk changing stuff resulted in
1350          * the device being taken offline.  If this is the case,
1351          * report this to the user, and don't pretend that the
1352          * open actually succeeded.
1353          */
1354         retval = -ENXIO;
1355         if (!scsi_device_online(sdev))
1356                 goto error_out;
1357
1358         if ((atomic_inc_return(&sdkp->openers) == 1) && sdev->removable) {
1359                 if (scsi_block_when_processing_errors(sdev))
1360                         scsi_set_medium_removal(sdev, SCSI_REMOVAL_PREVENT);
1361         }
1362
1363         return 0;
1364
1365 error_out:
1366         scsi_device_put(sdev);
1367         return retval;  
1368 }
1369
1370 /**
1371  *      sd_release - invoked when the (last) close(2) is called on this
1372  *      scsi disk.
1373  *      @disk: disk to release
1374  *      @mode: FMODE_* mask
1375  *
1376  *      Returns 0. 
1377  *
1378  *      Note: may block (uninterruptible) if error recovery is underway
1379  *      on this disk.
1380  *
1381  *      Locking: called with bdev->bd_disk->open_mutex held.
1382  **/
1383 static void sd_release(struct gendisk *disk, fmode_t mode)
1384 {
1385         struct scsi_disk *sdkp = scsi_disk(disk);
1386         struct scsi_device *sdev = sdkp->device;
1387
1388         SCSI_LOG_HLQUEUE(3, sd_printk(KERN_INFO, sdkp, "sd_release\n"));
1389
1390         if (atomic_dec_return(&sdkp->openers) == 0 && sdev->removable) {
1391                 if (scsi_block_when_processing_errors(sdev))
1392                         scsi_set_medium_removal(sdev, SCSI_REMOVAL_ALLOW);
1393         }
1394
1395         scsi_device_put(sdev);
1396 }
1397
1398 static int sd_getgeo(struct block_device *bdev, struct hd_geometry *geo)
1399 {
1400         struct scsi_disk *sdkp = scsi_disk(bdev->bd_disk);
1401         struct scsi_device *sdp = sdkp->device;
1402         struct Scsi_Host *host = sdp->host;
1403         sector_t capacity = logical_to_sectors(sdp, sdkp->capacity);
1404         int diskinfo[4];
1405
1406         /* default to most commonly used values */
1407         diskinfo[0] = 0x40;     /* 1 << 6 */
1408         diskinfo[1] = 0x20;     /* 1 << 5 */
1409         diskinfo[2] = capacity >> 11;
1410
1411         /* override with calculated, extended default, or driver values */
1412         if (host->hostt->bios_param)
1413                 host->hostt->bios_param(sdp, bdev, capacity, diskinfo);
1414         else
1415                 scsicam_bios_param(bdev, capacity, diskinfo);
1416
1417         geo->heads = diskinfo[0];
1418         geo->sectors = diskinfo[1];
1419         geo->cylinders = diskinfo[2];
1420         return 0;
1421 }
1422
1423 /**
1424  *      sd_ioctl - process an ioctl
1425  *      @bdev: target block device
1426  *      @mode: FMODE_* mask
1427  *      @cmd: ioctl command number
1428  *      @arg: this is third argument given to ioctl(2) system call.
1429  *      Often contains a pointer.
1430  *
1431  *      Returns 0 if successful (some ioctls return positive numbers on
1432  *      success as well). Returns a negated errno value in case of error.
1433  *
1434  *      Note: most ioctls are forward onto the block subsystem or further
1435  *      down in the scsi subsystem.
1436  **/
1437 static int sd_ioctl(struct block_device *bdev, fmode_t mode,
1438                     unsigned int cmd, unsigned long arg)
1439 {
1440         struct gendisk *disk = bdev->bd_disk;
1441         struct scsi_disk *sdkp = scsi_disk(disk);
1442         struct scsi_device *sdp = sdkp->device;
1443         void __user *p = (void __user *)arg;
1444         int error;
1445     
1446         SCSI_LOG_IOCTL(1, sd_printk(KERN_INFO, sdkp, "sd_ioctl: disk=%s, "
1447                                     "cmd=0x%x\n", disk->disk_name, cmd));
1448
1449         if (bdev_is_partition(bdev) && !capable(CAP_SYS_RAWIO))
1450                 return -ENOIOCTLCMD;
1451
1452         /*
1453          * If we are in the middle of error recovery, don't let anyone
1454          * else try and use this device.  Also, if error recovery fails, it
1455          * may try and take the device offline, in which case all further
1456          * access to the device is prohibited.
1457          */
1458         error = scsi_ioctl_block_when_processing_errors(sdp, cmd,
1459                         (mode & FMODE_NDELAY) != 0);
1460         if (error)
1461                 return error;
1462
1463         if (is_sed_ioctl(cmd))
1464                 return sed_ioctl(sdkp->opal_dev, cmd, p);
1465         return scsi_ioctl(sdp, mode, cmd, p);
1466 }
1467
1468 static void set_media_not_present(struct scsi_disk *sdkp)
1469 {
1470         if (sdkp->media_present)
1471                 sdkp->device->changed = 1;
1472
1473         if (sdkp->device->removable) {
1474                 sdkp->media_present = 0;
1475                 sdkp->capacity = 0;
1476         }
1477 }
1478
1479 static int media_not_present(struct scsi_disk *sdkp,
1480                              struct scsi_sense_hdr *sshdr)
1481 {
1482         if (!scsi_sense_valid(sshdr))
1483                 return 0;
1484
1485         /* not invoked for commands that could return deferred errors */
1486         switch (sshdr->sense_key) {
1487         case UNIT_ATTENTION:
1488         case NOT_READY:
1489                 /* medium not present */
1490                 if (sshdr->asc == 0x3A) {
1491                         set_media_not_present(sdkp);
1492                         return 1;
1493                 }
1494         }
1495         return 0;
1496 }
1497
1498 /**
1499  *      sd_check_events - check media events
1500  *      @disk: kernel device descriptor
1501  *      @clearing: disk events currently being cleared
1502  *
1503  *      Returns mask of DISK_EVENT_*.
1504  *
1505  *      Note: this function is invoked from the block subsystem.
1506  **/
1507 static unsigned int sd_check_events(struct gendisk *disk, unsigned int clearing)
1508 {
1509         struct scsi_disk *sdkp = disk->private_data;
1510         struct scsi_device *sdp;
1511         int retval;
1512         bool disk_changed;
1513
1514         if (!sdkp)
1515                 return 0;
1516
1517         sdp = sdkp->device;
1518         SCSI_LOG_HLQUEUE(3, sd_printk(KERN_INFO, sdkp, "sd_check_events\n"));
1519
1520         /*
1521          * If the device is offline, don't send any commands - just pretend as
1522          * if the command failed.  If the device ever comes back online, we
1523          * can deal with it then.  It is only because of unrecoverable errors
1524          * that we would ever take a device offline in the first place.
1525          */
1526         if (!scsi_device_online(sdp)) {
1527                 set_media_not_present(sdkp);
1528                 goto out;
1529         }
1530
1531         /*
1532          * Using TEST_UNIT_READY enables differentiation between drive with
1533          * no cartridge loaded - NOT READY, drive with changed cartridge -
1534          * UNIT ATTENTION, or with same cartridge - GOOD STATUS.
1535          *
1536          * Drives that auto spin down. eg iomega jaz 1G, will be started
1537          * by sd_spinup_disk() from sd_revalidate_disk(), which happens whenever
1538          * sd_revalidate() is called.
1539          */
1540         if (scsi_block_when_processing_errors(sdp)) {
1541                 struct scsi_sense_hdr sshdr = { 0, };
1542
1543                 retval = scsi_test_unit_ready(sdp, SD_TIMEOUT, sdkp->max_retries,
1544                                               &sshdr);
1545
1546                 /* failed to execute TUR, assume media not present */
1547                 if (retval < 0 || host_byte(retval)) {
1548                         set_media_not_present(sdkp);
1549                         goto out;
1550                 }
1551
1552                 if (media_not_present(sdkp, &sshdr))
1553                         goto out;
1554         }
1555
1556         /*
1557          * For removable scsi disk we have to recognise the presence
1558          * of a disk in the drive.
1559          */
1560         if (!sdkp->media_present)
1561                 sdp->changed = 1;
1562         sdkp->media_present = 1;
1563 out:
1564         /*
1565          * sdp->changed is set under the following conditions:
1566          *
1567          *      Medium present state has changed in either direction.
1568          *      Device has indicated UNIT_ATTENTION.
1569          */
1570         disk_changed = sdp->changed;
1571         sdp->changed = 0;
1572         return disk_changed ? DISK_EVENT_MEDIA_CHANGE : 0;
1573 }
1574
1575 static int sd_sync_cache(struct scsi_disk *sdkp, struct scsi_sense_hdr *sshdr)
1576 {
1577         int retries, res;
1578         struct scsi_device *sdp = sdkp->device;
1579         const int timeout = sdp->request_queue->rq_timeout
1580                 * SD_FLUSH_TIMEOUT_MULTIPLIER;
1581         struct scsi_sense_hdr my_sshdr;
1582
1583         if (!scsi_device_online(sdp))
1584                 return -ENODEV;
1585
1586         /* caller might not be interested in sense, but we need it */
1587         if (!sshdr)
1588                 sshdr = &my_sshdr;
1589
1590         for (retries = 3; retries > 0; --retries) {
1591                 unsigned char cmd[10] = { 0 };
1592
1593                 cmd[0] = SYNCHRONIZE_CACHE;
1594                 /*
1595                  * Leave the rest of the command zero to indicate
1596                  * flush everything.
1597                  */
1598                 res = scsi_execute(sdp, cmd, DMA_NONE, NULL, 0, NULL, sshdr,
1599                                 timeout, sdkp->max_retries, 0, RQF_PM, NULL);
1600                 if (res == 0)
1601                         break;
1602         }
1603
1604         if (res) {
1605                 sd_print_result(sdkp, "Synchronize Cache(10) failed", res);
1606
1607                 if (res < 0)
1608                         return res;
1609
1610                 if (scsi_status_is_check_condition(res) &&
1611                     scsi_sense_valid(sshdr)) {
1612                         sd_print_sense_hdr(sdkp, sshdr);
1613
1614                         /* we need to evaluate the error return  */
1615                         if (sshdr->asc == 0x3a ||       /* medium not present */
1616                             sshdr->asc == 0x20 ||       /* invalid command */
1617                             (sshdr->asc == 0x74 && sshdr->ascq == 0x71))        /* drive is password locked */
1618                                 /* this is no error here */
1619                                 return 0;
1620                 }
1621
1622                 switch (host_byte(res)) {
1623                 /* ignore errors due to racing a disconnection */
1624                 case DID_BAD_TARGET:
1625                 case DID_NO_CONNECT:
1626                         return 0;
1627                 /* signal the upper layer it might try again */
1628                 case DID_BUS_BUSY:
1629                 case DID_IMM_RETRY:
1630                 case DID_REQUEUE:
1631                 case DID_SOFT_ERROR:
1632                         return -EBUSY;
1633                 default:
1634                         return -EIO;
1635                 }
1636         }
1637         return 0;
1638 }
1639
1640 static void sd_rescan(struct device *dev)
1641 {
1642         struct scsi_disk *sdkp = dev_get_drvdata(dev);
1643
1644         sd_revalidate_disk(sdkp->disk);
1645 }
1646
1647 static int sd_get_unique_id(struct gendisk *disk, u8 id[16],
1648                 enum blk_unique_id type)
1649 {
1650         struct scsi_device *sdev = scsi_disk(disk)->device;
1651         const struct scsi_vpd *vpd;
1652         const unsigned char *d;
1653         int ret = -ENXIO, len;
1654
1655         rcu_read_lock();
1656         vpd = rcu_dereference(sdev->vpd_pg83);
1657         if (!vpd)
1658                 goto out_unlock;
1659
1660         ret = -EINVAL;
1661         for (d = vpd->data + 4; d < vpd->data + vpd->len; d += d[3] + 4) {
1662                 /* we only care about designators with LU association */
1663                 if (((d[1] >> 4) & 0x3) != 0x00)
1664                         continue;
1665                 if ((d[1] & 0xf) != type)
1666                         continue;
1667
1668                 /*
1669                  * Only exit early if a 16-byte descriptor was found.  Otherwise
1670                  * keep looking as one with more entropy might still show up.
1671                  */
1672                 len = d[3];
1673                 if (len != 8 && len != 12 && len != 16)
1674                         continue;
1675                 ret = len;
1676                 memcpy(id, d + 4, len);
1677                 if (len == 16)
1678                         break;
1679         }
1680 out_unlock:
1681         rcu_read_unlock();
1682         return ret;
1683 }
1684
1685 static char sd_pr_type(enum pr_type type)
1686 {
1687         switch (type) {
1688         case PR_WRITE_EXCLUSIVE:
1689                 return 0x01;
1690         case PR_EXCLUSIVE_ACCESS:
1691                 return 0x03;
1692         case PR_WRITE_EXCLUSIVE_REG_ONLY:
1693                 return 0x05;
1694         case PR_EXCLUSIVE_ACCESS_REG_ONLY:
1695                 return 0x06;
1696         case PR_WRITE_EXCLUSIVE_ALL_REGS:
1697                 return 0x07;
1698         case PR_EXCLUSIVE_ACCESS_ALL_REGS:
1699                 return 0x08;
1700         default:
1701                 return 0;
1702         }
1703 };
1704
1705 static int sd_pr_command(struct block_device *bdev, u8 sa,
1706                 u64 key, u64 sa_key, u8 type, u8 flags)
1707 {
1708         struct scsi_disk *sdkp = scsi_disk(bdev->bd_disk);
1709         struct scsi_device *sdev = sdkp->device;
1710         struct scsi_sense_hdr sshdr;
1711         int result;
1712         u8 cmd[16] = { 0, };
1713         u8 data[24] = { 0, };
1714
1715         cmd[0] = PERSISTENT_RESERVE_OUT;
1716         cmd[1] = sa;
1717         cmd[2] = type;
1718         put_unaligned_be32(sizeof(data), &cmd[5]);
1719
1720         put_unaligned_be64(key, &data[0]);
1721         put_unaligned_be64(sa_key, &data[8]);
1722         data[20] = flags;
1723
1724         result = scsi_execute_req(sdev, cmd, DMA_TO_DEVICE, &data, sizeof(data),
1725                         &sshdr, SD_TIMEOUT, sdkp->max_retries, NULL);
1726
1727         if (scsi_status_is_check_condition(result) &&
1728             scsi_sense_valid(&sshdr)) {
1729                 sdev_printk(KERN_INFO, sdev, "PR command failed: %d\n", result);
1730                 scsi_print_sense_hdr(sdev, NULL, &sshdr);
1731         }
1732
1733         return result;
1734 }
1735
1736 static int sd_pr_register(struct block_device *bdev, u64 old_key, u64 new_key,
1737                 u32 flags)
1738 {
1739         if (flags & ~PR_FL_IGNORE_KEY)
1740                 return -EOPNOTSUPP;
1741         return sd_pr_command(bdev, (flags & PR_FL_IGNORE_KEY) ? 0x06 : 0x00,
1742                         old_key, new_key, 0,
1743                         (1 << 0) /* APTPL */);
1744 }
1745
1746 static int sd_pr_reserve(struct block_device *bdev, u64 key, enum pr_type type,
1747                 u32 flags)
1748 {
1749         if (flags)
1750                 return -EOPNOTSUPP;
1751         return sd_pr_command(bdev, 0x01, key, 0, sd_pr_type(type), 0);
1752 }
1753
1754 static int sd_pr_release(struct block_device *bdev, u64 key, enum pr_type type)
1755 {
1756         return sd_pr_command(bdev, 0x02, key, 0, sd_pr_type(type), 0);
1757 }
1758
1759 static int sd_pr_preempt(struct block_device *bdev, u64 old_key, u64 new_key,
1760                 enum pr_type type, bool abort)
1761 {
1762         return sd_pr_command(bdev, abort ? 0x05 : 0x04, old_key, new_key,
1763                              sd_pr_type(type), 0);
1764 }
1765
1766 static int sd_pr_clear(struct block_device *bdev, u64 key)
1767 {
1768         return sd_pr_command(bdev, 0x03, key, 0, 0, 0);
1769 }
1770
1771 static const struct pr_ops sd_pr_ops = {
1772         .pr_register    = sd_pr_register,
1773         .pr_reserve     = sd_pr_reserve,
1774         .pr_release     = sd_pr_release,
1775         .pr_preempt     = sd_pr_preempt,
1776         .pr_clear       = sd_pr_clear,
1777 };
1778
1779 static void scsi_disk_free_disk(struct gendisk *disk)
1780 {
1781         struct scsi_disk *sdkp = scsi_disk(disk);
1782
1783         put_device(&sdkp->disk_dev);
1784 }
1785
1786 static const struct block_device_operations sd_fops = {
1787         .owner                  = THIS_MODULE,
1788         .open                   = sd_open,
1789         .release                = sd_release,
1790         .ioctl                  = sd_ioctl,
1791         .getgeo                 = sd_getgeo,
1792         .compat_ioctl           = blkdev_compat_ptr_ioctl,
1793         .check_events           = sd_check_events,
1794         .unlock_native_capacity = sd_unlock_native_capacity,
1795         .report_zones           = sd_zbc_report_zones,
1796         .get_unique_id          = sd_get_unique_id,
1797         .free_disk              = scsi_disk_free_disk,
1798         .pr_ops                 = &sd_pr_ops,
1799 };
1800
1801 /**
1802  *      sd_eh_reset - reset error handling callback
1803  *      @scmd:          sd-issued command that has failed
1804  *
1805  *      This function is called by the SCSI midlayer before starting
1806  *      SCSI EH. When counting medium access failures we have to be
1807  *      careful to register it only only once per device and SCSI EH run;
1808  *      there might be several timed out commands which will cause the
1809  *      'max_medium_access_timeouts' counter to trigger after the first
1810  *      SCSI EH run already and set the device to offline.
1811  *      So this function resets the internal counter before starting SCSI EH.
1812  **/
1813 static void sd_eh_reset(struct scsi_cmnd *scmd)
1814 {
1815         struct scsi_disk *sdkp = scsi_disk(scsi_cmd_to_rq(scmd)->q->disk);
1816
1817         /* New SCSI EH run, reset gate variable */
1818         sdkp->ignore_medium_access_errors = false;
1819 }
1820
1821 /**
1822  *      sd_eh_action - error handling callback
1823  *      @scmd:          sd-issued command that has failed
1824  *      @eh_disp:       The recovery disposition suggested by the midlayer
1825  *
1826  *      This function is called by the SCSI midlayer upon completion of an
1827  *      error test command (currently TEST UNIT READY). The result of sending
1828  *      the eh command is passed in eh_disp.  We're looking for devices that
1829  *      fail medium access commands but are OK with non access commands like
1830  *      test unit ready (so wrongly see the device as having a successful
1831  *      recovery)
1832  **/
1833 static int sd_eh_action(struct scsi_cmnd *scmd, int eh_disp)
1834 {
1835         struct scsi_disk *sdkp = scsi_disk(scsi_cmd_to_rq(scmd)->q->disk);
1836         struct scsi_device *sdev = scmd->device;
1837
1838         if (!scsi_device_online(sdev) ||
1839             !scsi_medium_access_command(scmd) ||
1840             host_byte(scmd->result) != DID_TIME_OUT ||
1841             eh_disp != SUCCESS)
1842                 return eh_disp;
1843
1844         /*
1845          * The device has timed out executing a medium access command.
1846          * However, the TEST UNIT READY command sent during error
1847          * handling completed successfully. Either the device is in the
1848          * process of recovering or has it suffered an internal failure
1849          * that prevents access to the storage medium.
1850          */
1851         if (!sdkp->ignore_medium_access_errors) {
1852                 sdkp->medium_access_timed_out++;
1853                 sdkp->ignore_medium_access_errors = true;
1854         }
1855
1856         /*
1857          * If the device keeps failing read/write commands but TEST UNIT
1858          * READY always completes successfully we assume that medium
1859          * access is no longer possible and take the device offline.
1860          */
1861         if (sdkp->medium_access_timed_out >= sdkp->max_medium_access_timeouts) {
1862                 scmd_printk(KERN_ERR, scmd,
1863                             "Medium access timeout failure. Offlining disk!\n");
1864                 mutex_lock(&sdev->state_mutex);
1865                 scsi_device_set_state(sdev, SDEV_OFFLINE);
1866                 mutex_unlock(&sdev->state_mutex);
1867
1868                 return SUCCESS;
1869         }
1870
1871         return eh_disp;
1872 }
1873
1874 static unsigned int sd_completed_bytes(struct scsi_cmnd *scmd)
1875 {
1876         struct request *req = scsi_cmd_to_rq(scmd);
1877         struct scsi_device *sdev = scmd->device;
1878         unsigned int transferred, good_bytes;
1879         u64 start_lba, end_lba, bad_lba;
1880
1881         /*
1882          * Some commands have a payload smaller than the device logical
1883          * block size (e.g. INQUIRY on a 4K disk).
1884          */
1885         if (scsi_bufflen(scmd) <= sdev->sector_size)
1886                 return 0;
1887
1888         /* Check if we have a 'bad_lba' information */
1889         if (!scsi_get_sense_info_fld(scmd->sense_buffer,
1890                                      SCSI_SENSE_BUFFERSIZE,
1891                                      &bad_lba))
1892                 return 0;
1893
1894         /*
1895          * If the bad lba was reported incorrectly, we have no idea where
1896          * the error is.
1897          */
1898         start_lba = sectors_to_logical(sdev, blk_rq_pos(req));
1899         end_lba = start_lba + bytes_to_logical(sdev, scsi_bufflen(scmd));
1900         if (bad_lba < start_lba || bad_lba >= end_lba)
1901                 return 0;
1902
1903         /*
1904          * resid is optional but mostly filled in.  When it's unused,
1905          * its value is zero, so we assume the whole buffer transferred
1906          */
1907         transferred = scsi_bufflen(scmd) - scsi_get_resid(scmd);
1908
1909         /* This computation should always be done in terms of the
1910          * resolution of the device's medium.
1911          */
1912         good_bytes = logical_to_bytes(sdev, bad_lba - start_lba);
1913
1914         return min(good_bytes, transferred);
1915 }
1916
1917 /**
1918  *      sd_done - bottom half handler: called when the lower level
1919  *      driver has completed (successfully or otherwise) a scsi command.
1920  *      @SCpnt: mid-level's per command structure.
1921  *
1922  *      Note: potentially run from within an ISR. Must not block.
1923  **/
1924 static int sd_done(struct scsi_cmnd *SCpnt)
1925 {
1926         int result = SCpnt->result;
1927         unsigned int good_bytes = result ? 0 : scsi_bufflen(SCpnt);
1928         unsigned int sector_size = SCpnt->device->sector_size;
1929         unsigned int resid;
1930         struct scsi_sense_hdr sshdr;
1931         struct request *req = scsi_cmd_to_rq(SCpnt);
1932         struct scsi_disk *sdkp = scsi_disk(req->q->disk);
1933         int sense_valid = 0;
1934         int sense_deferred = 0;
1935
1936         switch (req_op(req)) {
1937         case REQ_OP_DISCARD:
1938         case REQ_OP_WRITE_ZEROES:
1939         case REQ_OP_ZONE_RESET:
1940         case REQ_OP_ZONE_RESET_ALL:
1941         case REQ_OP_ZONE_OPEN:
1942         case REQ_OP_ZONE_CLOSE:
1943         case REQ_OP_ZONE_FINISH:
1944                 if (!result) {
1945                         good_bytes = blk_rq_bytes(req);
1946                         scsi_set_resid(SCpnt, 0);
1947                 } else {
1948                         good_bytes = 0;
1949                         scsi_set_resid(SCpnt, blk_rq_bytes(req));
1950                 }
1951                 break;
1952         default:
1953                 /*
1954                  * In case of bogus fw or device, we could end up having
1955                  * an unaligned partial completion. Check this here and force
1956                  * alignment.
1957                  */
1958                 resid = scsi_get_resid(SCpnt);
1959                 if (resid & (sector_size - 1)) {
1960                         sd_printk(KERN_INFO, sdkp,
1961                                 "Unaligned partial completion (resid=%u, sector_sz=%u)\n",
1962                                 resid, sector_size);
1963                         scsi_print_command(SCpnt);
1964                         resid = min(scsi_bufflen(SCpnt),
1965                                     round_up(resid, sector_size));
1966                         scsi_set_resid(SCpnt, resid);
1967                 }
1968         }
1969
1970         if (result) {
1971                 sense_valid = scsi_command_normalize_sense(SCpnt, &sshdr);
1972                 if (sense_valid)
1973                         sense_deferred = scsi_sense_is_deferred(&sshdr);
1974         }
1975         sdkp->medium_access_timed_out = 0;
1976
1977         if (!scsi_status_is_check_condition(result) &&
1978             (!sense_valid || sense_deferred))
1979                 goto out;
1980
1981         switch (sshdr.sense_key) {
1982         case HARDWARE_ERROR:
1983         case MEDIUM_ERROR:
1984                 good_bytes = sd_completed_bytes(SCpnt);
1985                 break;
1986         case RECOVERED_ERROR:
1987                 good_bytes = scsi_bufflen(SCpnt);
1988                 break;
1989         case NO_SENSE:
1990                 /* This indicates a false check condition, so ignore it.  An
1991                  * unknown amount of data was transferred so treat it as an
1992                  * error.
1993                  */
1994                 SCpnt->result = 0;
1995                 memset(SCpnt->sense_buffer, 0, SCSI_SENSE_BUFFERSIZE);
1996                 break;
1997         case ABORTED_COMMAND:
1998                 if (sshdr.asc == 0x10)  /* DIF: Target detected corruption */
1999                         good_bytes = sd_completed_bytes(SCpnt);
2000                 break;
2001         case ILLEGAL_REQUEST:
2002                 switch (sshdr.asc) {
2003                 case 0x10:      /* DIX: Host detected corruption */
2004                         good_bytes = sd_completed_bytes(SCpnt);
2005                         break;
2006                 case 0x20:      /* INVALID COMMAND OPCODE */
2007                 case 0x24:      /* INVALID FIELD IN CDB */
2008                         switch (SCpnt->cmnd[0]) {
2009                         case UNMAP:
2010                                 sd_config_discard(sdkp, SD_LBP_DISABLE);
2011                                 break;
2012                         case WRITE_SAME_16:
2013                         case WRITE_SAME:
2014                                 if (SCpnt->cmnd[1] & 8) { /* UNMAP */
2015                                         sd_config_discard(sdkp, SD_LBP_DISABLE);
2016                                 } else {
2017                                         sdkp->device->no_write_same = 1;
2018                                         sd_config_write_same(sdkp);
2019                                         req->rq_flags |= RQF_QUIET;
2020                                 }
2021                                 break;
2022                         }
2023                 }
2024                 break;
2025         default:
2026                 break;
2027         }
2028
2029  out:
2030         if (sd_is_zoned(sdkp))
2031                 good_bytes = sd_zbc_complete(SCpnt, good_bytes, &sshdr);
2032
2033         SCSI_LOG_HLCOMPLETE(1, scmd_printk(KERN_INFO, SCpnt,
2034                                            "sd_done: completed %d of %d bytes\n",
2035                                            good_bytes, scsi_bufflen(SCpnt)));
2036
2037         return good_bytes;
2038 }
2039
2040 /*
2041  * spinup disk - called only in sd_revalidate_disk()
2042  */
2043 static void
2044 sd_spinup_disk(struct scsi_disk *sdkp)
2045 {
2046         unsigned char cmd[10];
2047         unsigned long spintime_expire = 0;
2048         int retries, spintime;
2049         unsigned int the_result;
2050         struct scsi_sense_hdr sshdr;
2051         int sense_valid = 0;
2052
2053         spintime = 0;
2054
2055         /* Spin up drives, as required.  Only do this at boot time */
2056         /* Spinup needs to be done for module loads too. */
2057         do {
2058                 retries = 0;
2059
2060                 do {
2061                         bool media_was_present = sdkp->media_present;
2062
2063                         cmd[0] = TEST_UNIT_READY;
2064                         memset((void *) &cmd[1], 0, 9);
2065
2066                         the_result = scsi_execute_req(sdkp->device, cmd,
2067                                                       DMA_NONE, NULL, 0,
2068                                                       &sshdr, SD_TIMEOUT,
2069                                                       sdkp->max_retries, NULL);
2070
2071                         /*
2072                          * If the drive has indicated to us that it
2073                          * doesn't have any media in it, don't bother
2074                          * with any more polling.
2075                          */
2076                         if (media_not_present(sdkp, &sshdr)) {
2077                                 if (media_was_present)
2078                                         sd_printk(KERN_NOTICE, sdkp, "Media removed, stopped polling\n");
2079                                 return;
2080                         }
2081
2082                         if (the_result)
2083                                 sense_valid = scsi_sense_valid(&sshdr);
2084                         retries++;
2085                 } while (retries < 3 &&
2086                          (!scsi_status_is_good(the_result) ||
2087                           (scsi_status_is_check_condition(the_result) &&
2088                           sense_valid && sshdr.sense_key == UNIT_ATTENTION)));
2089
2090                 if (!scsi_status_is_check_condition(the_result)) {
2091                         /* no sense, TUR either succeeded or failed
2092                          * with a status error */
2093                         if(!spintime && !scsi_status_is_good(the_result)) {
2094                                 sd_print_result(sdkp, "Test Unit Ready failed",
2095                                                 the_result);
2096                         }
2097                         break;
2098                 }
2099
2100                 /*
2101                  * The device does not want the automatic start to be issued.
2102                  */
2103                 if (sdkp->device->no_start_on_add)
2104                         break;
2105
2106                 if (sense_valid && sshdr.sense_key == NOT_READY) {
2107                         if (sshdr.asc == 4 && sshdr.ascq == 3)
2108                                 break;  /* manual intervention required */
2109                         if (sshdr.asc == 4 && sshdr.ascq == 0xb)
2110                                 break;  /* standby */
2111                         if (sshdr.asc == 4 && sshdr.ascq == 0xc)
2112                                 break;  /* unavailable */
2113                         if (sshdr.asc == 4 && sshdr.ascq == 0x1b)
2114                                 break;  /* sanitize in progress */
2115                         /*
2116                          * Issue command to spin up drive when not ready
2117                          */
2118                         if (!spintime) {
2119                                 sd_printk(KERN_NOTICE, sdkp, "Spinning up disk...");
2120                                 cmd[0] = START_STOP;
2121                                 cmd[1] = 1;     /* Return immediately */
2122                                 memset((void *) &cmd[2], 0, 8);
2123                                 cmd[4] = 1;     /* Start spin cycle */
2124                                 if (sdkp->device->start_stop_pwr_cond)
2125                                         cmd[4] |= 1 << 4;
2126                                 scsi_execute_req(sdkp->device, cmd, DMA_NONE,
2127                                                  NULL, 0, &sshdr,
2128                                                  SD_TIMEOUT, sdkp->max_retries,
2129                                                  NULL);
2130                                 spintime_expire = jiffies + 100 * HZ;
2131                                 spintime = 1;
2132                         }
2133                         /* Wait 1 second for next try */
2134                         msleep(1000);
2135                         printk(KERN_CONT ".");
2136
2137                 /*
2138                  * Wait for USB flash devices with slow firmware.
2139                  * Yes, this sense key/ASC combination shouldn't
2140                  * occur here.  It's characteristic of these devices.
2141                  */
2142                 } else if (sense_valid &&
2143                                 sshdr.sense_key == UNIT_ATTENTION &&
2144                                 sshdr.asc == 0x28) {
2145                         if (!spintime) {
2146                                 spintime_expire = jiffies + 5 * HZ;
2147                                 spintime = 1;
2148                         }
2149                         /* Wait 1 second for next try */
2150                         msleep(1000);
2151                 } else {
2152                         /* we don't understand the sense code, so it's
2153                          * probably pointless to loop */
2154                         if(!spintime) {
2155                                 sd_printk(KERN_NOTICE, sdkp, "Unit Not Ready\n");
2156                                 sd_print_sense_hdr(sdkp, &sshdr);
2157                         }
2158                         break;
2159                 }
2160                                 
2161         } while (spintime && time_before_eq(jiffies, spintime_expire));
2162
2163         if (spintime) {
2164                 if (scsi_status_is_good(the_result))
2165                         printk(KERN_CONT "ready\n");
2166                 else
2167                         printk(KERN_CONT "not responding...\n");
2168         }
2169 }
2170
2171 /*
2172  * Determine whether disk supports Data Integrity Field.
2173  */
2174 static int sd_read_protection_type(struct scsi_disk *sdkp, unsigned char *buffer)
2175 {
2176         struct scsi_device *sdp = sdkp->device;
2177         u8 type;
2178
2179         if (scsi_device_protection(sdp) == 0 || (buffer[12] & 1) == 0) {
2180                 sdkp->protection_type = 0;
2181                 return 0;
2182         }
2183
2184         type = ((buffer[12] >> 1) & 7) + 1; /* P_TYPE 0 = Type 1 */
2185
2186         if (type > T10_PI_TYPE3_PROTECTION) {
2187                 sd_printk(KERN_ERR, sdkp, "formatted with unsupported"  \
2188                           " protection type %u. Disabling disk!\n",
2189                           type);
2190                 sdkp->protection_type = 0;
2191                 return -ENODEV;
2192         }
2193
2194         sdkp->protection_type = type;
2195
2196         return 0;
2197 }
2198
2199 static void sd_config_protection(struct scsi_disk *sdkp)
2200 {
2201         struct scsi_device *sdp = sdkp->device;
2202
2203         if (!sdkp->first_scan)
2204                 return;
2205
2206         sd_dif_config_host(sdkp);
2207
2208         if (!sdkp->protection_type)
2209                 return;
2210
2211         if (!scsi_host_dif_capable(sdp->host, sdkp->protection_type)) {
2212                 sd_printk(KERN_NOTICE, sdkp,
2213                           "Disabling DIF Type %u protection\n",
2214                           sdkp->protection_type);
2215                 sdkp->protection_type = 0;
2216         }
2217
2218         sd_printk(KERN_NOTICE, sdkp, "Enabling DIF Type %u protection\n",
2219                   sdkp->protection_type);
2220 }
2221
2222 static void read_capacity_error(struct scsi_disk *sdkp, struct scsi_device *sdp,
2223                         struct scsi_sense_hdr *sshdr, int sense_valid,
2224                         int the_result)
2225 {
2226         if (sense_valid)
2227                 sd_print_sense_hdr(sdkp, sshdr);
2228         else
2229                 sd_printk(KERN_NOTICE, sdkp, "Sense not available.\n");
2230
2231         /*
2232          * Set dirty bit for removable devices if not ready -
2233          * sometimes drives will not report this properly.
2234          */
2235         if (sdp->removable &&
2236             sense_valid && sshdr->sense_key == NOT_READY)
2237                 set_media_not_present(sdkp);
2238
2239         /*
2240          * We used to set media_present to 0 here to indicate no media
2241          * in the drive, but some drives fail read capacity even with
2242          * media present, so we can't do that.
2243          */
2244         sdkp->capacity = 0; /* unknown mapped to zero - as usual */
2245 }
2246
2247 #define RC16_LEN 32
2248 #if RC16_LEN > SD_BUF_SIZE
2249 #error RC16_LEN must not be more than SD_BUF_SIZE
2250 #endif
2251
2252 #define READ_CAPACITY_RETRIES_ON_RESET  10
2253
2254 static int read_capacity_16(struct scsi_disk *sdkp, struct scsi_device *sdp,
2255                                                 unsigned char *buffer)
2256 {
2257         unsigned char cmd[16];
2258         struct scsi_sense_hdr sshdr;
2259         int sense_valid = 0;
2260         int the_result;
2261         int retries = 3, reset_retries = READ_CAPACITY_RETRIES_ON_RESET;
2262         unsigned int alignment;
2263         unsigned long long lba;
2264         unsigned sector_size;
2265
2266         if (sdp->no_read_capacity_16)
2267                 return -EINVAL;
2268
2269         do {
2270                 memset(cmd, 0, 16);
2271                 cmd[0] = SERVICE_ACTION_IN_16;
2272                 cmd[1] = SAI_READ_CAPACITY_16;
2273                 cmd[13] = RC16_LEN;
2274                 memset(buffer, 0, RC16_LEN);
2275
2276                 the_result = scsi_execute_req(sdp, cmd, DMA_FROM_DEVICE,
2277                                         buffer, RC16_LEN, &sshdr,
2278                                         SD_TIMEOUT, sdkp->max_retries, NULL);
2279
2280                 if (media_not_present(sdkp, &sshdr))
2281                         return -ENODEV;
2282
2283                 if (the_result > 0) {
2284                         sense_valid = scsi_sense_valid(&sshdr);
2285                         if (sense_valid &&
2286                             sshdr.sense_key == ILLEGAL_REQUEST &&
2287                             (sshdr.asc == 0x20 || sshdr.asc == 0x24) &&
2288                             sshdr.ascq == 0x00)
2289                                 /* Invalid Command Operation Code or
2290                                  * Invalid Field in CDB, just retry
2291                                  * silently with RC10 */
2292                                 return -EINVAL;
2293                         if (sense_valid &&
2294                             sshdr.sense_key == UNIT_ATTENTION &&
2295                             sshdr.asc == 0x29 && sshdr.ascq == 0x00)
2296                                 /* Device reset might occur several times,
2297                                  * give it one more chance */
2298                                 if (--reset_retries > 0)
2299                                         continue;
2300                 }
2301                 retries--;
2302
2303         } while (the_result && retries);
2304
2305         if (the_result) {
2306                 sd_print_result(sdkp, "Read Capacity(16) failed", the_result);
2307                 read_capacity_error(sdkp, sdp, &sshdr, sense_valid, the_result);
2308                 return -EINVAL;
2309         }
2310
2311         sector_size = get_unaligned_be32(&buffer[8]);
2312         lba = get_unaligned_be64(&buffer[0]);
2313
2314         if (sd_read_protection_type(sdkp, buffer) < 0) {
2315                 sdkp->capacity = 0;
2316                 return -ENODEV;
2317         }
2318
2319         /* Logical blocks per physical block exponent */
2320         sdkp->physical_block_size = (1 << (buffer[13] & 0xf)) * sector_size;
2321
2322         /* RC basis */
2323         sdkp->rc_basis = (buffer[12] >> 4) & 0x3;
2324
2325         /* Lowest aligned logical block */
2326         alignment = ((buffer[14] & 0x3f) << 8 | buffer[15]) * sector_size;
2327         blk_queue_alignment_offset(sdp->request_queue, alignment);
2328         if (alignment && sdkp->first_scan)
2329                 sd_printk(KERN_NOTICE, sdkp,
2330                           "physical block alignment offset: %u\n", alignment);
2331
2332         if (buffer[14] & 0x80) { /* LBPME */
2333                 sdkp->lbpme = 1;
2334
2335                 if (buffer[14] & 0x40) /* LBPRZ */
2336                         sdkp->lbprz = 1;
2337
2338                 sd_config_discard(sdkp, SD_LBP_WS16);
2339         }
2340
2341         sdkp->capacity = lba + 1;
2342         return sector_size;
2343 }
2344
2345 static int read_capacity_10(struct scsi_disk *sdkp, struct scsi_device *sdp,
2346                                                 unsigned char *buffer)
2347 {
2348         unsigned char cmd[16];
2349         struct scsi_sense_hdr sshdr;
2350         int sense_valid = 0;
2351         int the_result;
2352         int retries = 3, reset_retries = READ_CAPACITY_RETRIES_ON_RESET;
2353         sector_t lba;
2354         unsigned sector_size;
2355
2356         do {
2357                 cmd[0] = READ_CAPACITY;
2358                 memset(&cmd[1], 0, 9);
2359                 memset(buffer, 0, 8);
2360
2361                 the_result = scsi_execute_req(sdp, cmd, DMA_FROM_DEVICE,
2362                                         buffer, 8, &sshdr,
2363                                         SD_TIMEOUT, sdkp->max_retries, NULL);
2364
2365                 if (media_not_present(sdkp, &sshdr))
2366                         return -ENODEV;
2367
2368                 if (the_result > 0) {
2369                         sense_valid = scsi_sense_valid(&sshdr);
2370                         if (sense_valid &&
2371                             sshdr.sense_key == UNIT_ATTENTION &&
2372                             sshdr.asc == 0x29 && sshdr.ascq == 0x00)
2373                                 /* Device reset might occur several times,
2374                                  * give it one more chance */
2375                                 if (--reset_retries > 0)
2376                                         continue;
2377                 }
2378                 retries--;
2379
2380         } while (the_result && retries);
2381
2382         if (the_result) {
2383                 sd_print_result(sdkp, "Read Capacity(10) failed", the_result);
2384                 read_capacity_error(sdkp, sdp, &sshdr, sense_valid, the_result);
2385                 return -EINVAL;
2386         }
2387
2388         sector_size = get_unaligned_be32(&buffer[4]);
2389         lba = get_unaligned_be32(&buffer[0]);
2390
2391         if (sdp->no_read_capacity_16 && (lba == 0xffffffff)) {
2392                 /* Some buggy (usb cardreader) devices return an lba of
2393                    0xffffffff when the want to report a size of 0 (with
2394                    which they really mean no media is present) */
2395                 sdkp->capacity = 0;
2396                 sdkp->physical_block_size = sector_size;
2397                 return sector_size;
2398         }
2399
2400         sdkp->capacity = lba + 1;
2401         sdkp->physical_block_size = sector_size;
2402         return sector_size;
2403 }
2404
2405 static int sd_try_rc16_first(struct scsi_device *sdp)
2406 {
2407         if (sdp->host->max_cmd_len < 16)
2408                 return 0;
2409         if (sdp->try_rc_10_first)
2410                 return 0;
2411         if (sdp->scsi_level > SCSI_SPC_2)
2412                 return 1;
2413         if (scsi_device_protection(sdp))
2414                 return 1;
2415         return 0;
2416 }
2417
2418 /*
2419  * read disk capacity
2420  */
2421 static void
2422 sd_read_capacity(struct scsi_disk *sdkp, unsigned char *buffer)
2423 {
2424         int sector_size;
2425         struct scsi_device *sdp = sdkp->device;
2426
2427         if (sd_try_rc16_first(sdp)) {
2428                 sector_size = read_capacity_16(sdkp, sdp, buffer);
2429                 if (sector_size == -EOVERFLOW)
2430                         goto got_data;
2431                 if (sector_size == -ENODEV)
2432                         return;
2433                 if (sector_size < 0)
2434                         sector_size = read_capacity_10(sdkp, sdp, buffer);
2435                 if (sector_size < 0)
2436                         return;
2437         } else {
2438                 sector_size = read_capacity_10(sdkp, sdp, buffer);
2439                 if (sector_size == -EOVERFLOW)
2440                         goto got_data;
2441                 if (sector_size < 0)
2442                         return;
2443                 if ((sizeof(sdkp->capacity) > 4) &&
2444                     (sdkp->capacity > 0xffffffffULL)) {
2445                         int old_sector_size = sector_size;
2446                         sd_printk(KERN_NOTICE, sdkp, "Very big device. "
2447                                         "Trying to use READ CAPACITY(16).\n");
2448                         sector_size = read_capacity_16(sdkp, sdp, buffer);
2449                         if (sector_size < 0) {
2450                                 sd_printk(KERN_NOTICE, sdkp,
2451                                         "Using 0xffffffff as device size\n");
2452                                 sdkp->capacity = 1 + (sector_t) 0xffffffff;
2453                                 sector_size = old_sector_size;
2454                                 goto got_data;
2455                         }
2456                         /* Remember that READ CAPACITY(16) succeeded */
2457                         sdp->try_rc_10_first = 0;
2458                 }
2459         }
2460
2461         /* Some devices are known to return the total number of blocks,
2462          * not the highest block number.  Some devices have versions
2463          * which do this and others which do not.  Some devices we might
2464          * suspect of doing this but we don't know for certain.
2465          *
2466          * If we know the reported capacity is wrong, decrement it.  If
2467          * we can only guess, then assume the number of blocks is even
2468          * (usually true but not always) and err on the side of lowering
2469          * the capacity.
2470          */
2471         if (sdp->fix_capacity ||
2472             (sdp->guess_capacity && (sdkp->capacity & 0x01))) {
2473                 sd_printk(KERN_INFO, sdkp, "Adjusting the sector count "
2474                                 "from its reported value: %llu\n",
2475                                 (unsigned long long) sdkp->capacity);
2476                 --sdkp->capacity;
2477         }
2478
2479 got_data:
2480         if (sector_size == 0) {
2481                 sector_size = 512;
2482                 sd_printk(KERN_NOTICE, sdkp, "Sector size 0 reported, "
2483                           "assuming 512.\n");
2484         }
2485
2486         if (sector_size != 512 &&
2487             sector_size != 1024 &&
2488             sector_size != 2048 &&
2489             sector_size != 4096) {
2490                 sd_printk(KERN_NOTICE, sdkp, "Unsupported sector size %d.\n",
2491                           sector_size);
2492                 /*
2493                  * The user might want to re-format the drive with
2494                  * a supported sectorsize.  Once this happens, it
2495                  * would be relatively trivial to set the thing up.
2496                  * For this reason, we leave the thing in the table.
2497                  */
2498                 sdkp->capacity = 0;
2499                 /*
2500                  * set a bogus sector size so the normal read/write
2501                  * logic in the block layer will eventually refuse any
2502                  * request on this device without tripping over power
2503                  * of two sector size assumptions
2504                  */
2505                 sector_size = 512;
2506         }
2507         blk_queue_logical_block_size(sdp->request_queue, sector_size);
2508         blk_queue_physical_block_size(sdp->request_queue,
2509                                       sdkp->physical_block_size);
2510         sdkp->device->sector_size = sector_size;
2511
2512         if (sdkp->capacity > 0xffffffff)
2513                 sdp->use_16_for_rw = 1;
2514
2515 }
2516
2517 /*
2518  * Print disk capacity
2519  */
2520 static void
2521 sd_print_capacity(struct scsi_disk *sdkp,
2522                   sector_t old_capacity)
2523 {
2524         int sector_size = sdkp->device->sector_size;
2525         char cap_str_2[10], cap_str_10[10];
2526
2527         if (!sdkp->first_scan && old_capacity == sdkp->capacity)
2528                 return;
2529
2530         string_get_size(sdkp->capacity, sector_size,
2531                         STRING_UNITS_2, cap_str_2, sizeof(cap_str_2));
2532         string_get_size(sdkp->capacity, sector_size,
2533                         STRING_UNITS_10, cap_str_10, sizeof(cap_str_10));
2534
2535         sd_printk(KERN_NOTICE, sdkp,
2536                   "%llu %d-byte logical blocks: (%s/%s)\n",
2537                   (unsigned long long)sdkp->capacity,
2538                   sector_size, cap_str_10, cap_str_2);
2539
2540         if (sdkp->physical_block_size != sector_size)
2541                 sd_printk(KERN_NOTICE, sdkp,
2542                           "%u-byte physical blocks\n",
2543                           sdkp->physical_block_size);
2544 }
2545
2546 /* called with buffer of length 512 */
2547 static inline int
2548 sd_do_mode_sense(struct scsi_disk *sdkp, int dbd, int modepage,
2549                  unsigned char *buffer, int len, struct scsi_mode_data *data,
2550                  struct scsi_sense_hdr *sshdr)
2551 {
2552         /*
2553          * If we must use MODE SENSE(10), make sure that the buffer length
2554          * is at least 8 bytes so that the mode sense header fits.
2555          */
2556         if (sdkp->device->use_10_for_ms && len < 8)
2557                 len = 8;
2558
2559         return scsi_mode_sense(sdkp->device, dbd, modepage, buffer, len,
2560                                SD_TIMEOUT, sdkp->max_retries, data,
2561                                sshdr);
2562 }
2563
2564 /*
2565  * read write protect setting, if possible - called only in sd_revalidate_disk()
2566  * called with buffer of length SD_BUF_SIZE
2567  */
2568 static void
2569 sd_read_write_protect_flag(struct scsi_disk *sdkp, unsigned char *buffer)
2570 {
2571         int res;
2572         struct scsi_device *sdp = sdkp->device;
2573         struct scsi_mode_data data;
2574         int old_wp = sdkp->write_prot;
2575
2576         set_disk_ro(sdkp->disk, 0);
2577         if (sdp->skip_ms_page_3f) {
2578                 sd_first_printk(KERN_NOTICE, sdkp, "Assuming Write Enabled\n");
2579                 return;
2580         }
2581
2582         if (sdp->use_192_bytes_for_3f) {
2583                 res = sd_do_mode_sense(sdkp, 0, 0x3F, buffer, 192, &data, NULL);
2584         } else {
2585                 /*
2586                  * First attempt: ask for all pages (0x3F), but only 4 bytes.
2587                  * We have to start carefully: some devices hang if we ask
2588                  * for more than is available.
2589                  */
2590                 res = sd_do_mode_sense(sdkp, 0, 0x3F, buffer, 4, &data, NULL);
2591
2592                 /*
2593                  * Second attempt: ask for page 0 When only page 0 is
2594                  * implemented, a request for page 3F may return Sense Key
2595                  * 5: Illegal Request, Sense Code 24: Invalid field in
2596                  * CDB.
2597                  */
2598                 if (res < 0)
2599                         res = sd_do_mode_sense(sdkp, 0, 0, buffer, 4, &data, NULL);
2600
2601                 /*
2602                  * Third attempt: ask 255 bytes, as we did earlier.
2603                  */
2604                 if (res < 0)
2605                         res = sd_do_mode_sense(sdkp, 0, 0x3F, buffer, 255,
2606                                                &data, NULL);
2607         }
2608
2609         if (res < 0) {
2610                 sd_first_printk(KERN_WARNING, sdkp,
2611                           "Test WP failed, assume Write Enabled\n");
2612         } else {
2613                 sdkp->write_prot = ((data.device_specific & 0x80) != 0);
2614                 set_disk_ro(sdkp->disk, sdkp->write_prot);
2615                 if (sdkp->first_scan || old_wp != sdkp->write_prot) {
2616                         sd_printk(KERN_NOTICE, sdkp, "Write Protect is %s\n",
2617                                   sdkp->write_prot ? "on" : "off");
2618                         sd_printk(KERN_DEBUG, sdkp, "Mode Sense: %4ph\n", buffer);
2619                 }
2620         }
2621 }
2622
2623 /*
2624  * sd_read_cache_type - called only from sd_revalidate_disk()
2625  * called with buffer of length SD_BUF_SIZE
2626  */
2627 static void
2628 sd_read_cache_type(struct scsi_disk *sdkp, unsigned char *buffer)
2629 {
2630         int len = 0, res;
2631         struct scsi_device *sdp = sdkp->device;
2632
2633         int dbd;
2634         int modepage;
2635         int first_len;
2636         struct scsi_mode_data data;
2637         struct scsi_sense_hdr sshdr;
2638         int old_wce = sdkp->WCE;
2639         int old_rcd = sdkp->RCD;
2640         int old_dpofua = sdkp->DPOFUA;
2641
2642
2643         if (sdkp->cache_override)
2644                 return;
2645
2646         first_len = 4;
2647         if (sdp->skip_ms_page_8) {
2648                 if (sdp->type == TYPE_RBC)
2649                         goto defaults;
2650                 else {
2651                         if (sdp->skip_ms_page_3f)
2652                                 goto defaults;
2653                         modepage = 0x3F;
2654                         if (sdp->use_192_bytes_for_3f)
2655                                 first_len = 192;
2656                         dbd = 0;
2657                 }
2658         } else if (sdp->type == TYPE_RBC) {
2659                 modepage = 6;
2660                 dbd = 8;
2661         } else {
2662                 modepage = 8;
2663                 dbd = 0;
2664         }
2665
2666         /* cautiously ask */
2667         res = sd_do_mode_sense(sdkp, dbd, modepage, buffer, first_len,
2668                         &data, &sshdr);
2669
2670         if (res < 0)
2671                 goto bad_sense;
2672
2673         if (!data.header_length) {
2674                 modepage = 6;
2675                 first_len = 0;
2676                 sd_first_printk(KERN_ERR, sdkp,
2677                                 "Missing header in MODE_SENSE response\n");
2678         }
2679
2680         /* that went OK, now ask for the proper length */
2681         len = data.length;
2682
2683         /*
2684          * We're only interested in the first three bytes, actually.
2685          * But the data cache page is defined for the first 20.
2686          */
2687         if (len < 3)
2688                 goto bad_sense;
2689         else if (len > SD_BUF_SIZE) {
2690                 sd_first_printk(KERN_NOTICE, sdkp, "Truncating mode parameter "
2691                           "data from %d to %d bytes\n", len, SD_BUF_SIZE);
2692                 len = SD_BUF_SIZE;
2693         }
2694         if (modepage == 0x3F && sdp->use_192_bytes_for_3f)
2695                 len = 192;
2696
2697         /* Get the data */
2698         if (len > first_len)
2699                 res = sd_do_mode_sense(sdkp, dbd, modepage, buffer, len,
2700                                 &data, &sshdr);
2701
2702         if (!res) {
2703                 int offset = data.header_length + data.block_descriptor_length;
2704
2705                 while (offset < len) {
2706                         u8 page_code = buffer[offset] & 0x3F;
2707                         u8 spf       = buffer[offset] & 0x40;
2708
2709                         if (page_code == 8 || page_code == 6) {
2710                                 /* We're interested only in the first 3 bytes.
2711                                  */
2712                                 if (len - offset <= 2) {
2713                                         sd_first_printk(KERN_ERR, sdkp,
2714                                                 "Incomplete mode parameter "
2715                                                         "data\n");
2716                                         goto defaults;
2717                                 } else {
2718                                         modepage = page_code;
2719                                         goto Page_found;
2720                                 }
2721                         } else {
2722                                 /* Go to the next page */
2723                                 if (spf && len - offset > 3)
2724                                         offset += 4 + (buffer[offset+2] << 8) +
2725                                                 buffer[offset+3];
2726                                 else if (!spf && len - offset > 1)
2727                                         offset += 2 + buffer[offset+1];
2728                                 else {
2729                                         sd_first_printk(KERN_ERR, sdkp,
2730                                                         "Incomplete mode "
2731                                                         "parameter data\n");
2732                                         goto defaults;
2733                                 }
2734                         }
2735                 }
2736
2737                 sd_first_printk(KERN_WARNING, sdkp,
2738                                 "No Caching mode page found\n");
2739                 goto defaults;
2740
2741         Page_found:
2742                 if (modepage == 8) {
2743                         sdkp->WCE = ((buffer[offset + 2] & 0x04) != 0);
2744                         sdkp->RCD = ((buffer[offset + 2] & 0x01) != 0);
2745                 } else {
2746                         sdkp->WCE = ((buffer[offset + 2] & 0x01) == 0);
2747                         sdkp->RCD = 0;
2748                 }
2749
2750                 sdkp->DPOFUA = (data.device_specific & 0x10) != 0;
2751                 if (sdp->broken_fua) {
2752                         sd_first_printk(KERN_NOTICE, sdkp, "Disabling FUA\n");
2753                         sdkp->DPOFUA = 0;
2754                 } else if (sdkp->DPOFUA && !sdkp->device->use_10_for_rw &&
2755                            !sdkp->device->use_16_for_rw) {
2756                         sd_first_printk(KERN_NOTICE, sdkp,
2757                                   "Uses READ/WRITE(6), disabling FUA\n");
2758                         sdkp->DPOFUA = 0;
2759                 }
2760
2761                 /* No cache flush allowed for write protected devices */
2762                 if (sdkp->WCE && sdkp->write_prot)
2763                         sdkp->WCE = 0;
2764
2765                 if (sdkp->first_scan || old_wce != sdkp->WCE ||
2766                     old_rcd != sdkp->RCD || old_dpofua != sdkp->DPOFUA)
2767                         sd_printk(KERN_NOTICE, sdkp,
2768                                   "Write cache: %s, read cache: %s, %s\n",
2769                                   sdkp->WCE ? "enabled" : "disabled",
2770                                   sdkp->RCD ? "disabled" : "enabled",
2771                                   sdkp->DPOFUA ? "supports DPO and FUA"
2772                                   : "doesn't support DPO or FUA");
2773
2774                 return;
2775         }
2776
2777 bad_sense:
2778         if (scsi_sense_valid(&sshdr) &&
2779             sshdr.sense_key == ILLEGAL_REQUEST &&
2780             sshdr.asc == 0x24 && sshdr.ascq == 0x0)
2781                 /* Invalid field in CDB */
2782                 sd_first_printk(KERN_NOTICE, sdkp, "Cache data unavailable\n");
2783         else
2784                 sd_first_printk(KERN_ERR, sdkp,
2785                                 "Asking for cache data failed\n");
2786
2787 defaults:
2788         if (sdp->wce_default_on) {
2789                 sd_first_printk(KERN_NOTICE, sdkp,
2790                                 "Assuming drive cache: write back\n");
2791                 sdkp->WCE = 1;
2792         } else {
2793                 sd_first_printk(KERN_WARNING, sdkp,
2794                                 "Assuming drive cache: write through\n");
2795                 sdkp->WCE = 0;
2796         }
2797         sdkp->RCD = 0;
2798         sdkp->DPOFUA = 0;
2799 }
2800
2801 /*
2802  * The ATO bit indicates whether the DIF application tag is available
2803  * for use by the operating system.
2804  */
2805 static void sd_read_app_tag_own(struct scsi_disk *sdkp, unsigned char *buffer)
2806 {
2807         int res, offset;
2808         struct scsi_device *sdp = sdkp->device;
2809         struct scsi_mode_data data;
2810         struct scsi_sense_hdr sshdr;
2811
2812         if (sdp->type != TYPE_DISK && sdp->type != TYPE_ZBC)
2813                 return;
2814
2815         if (sdkp->protection_type == 0)
2816                 return;
2817
2818         res = scsi_mode_sense(sdp, 1, 0x0a, buffer, 36, SD_TIMEOUT,
2819                               sdkp->max_retries, &data, &sshdr);
2820
2821         if (res < 0 || !data.header_length ||
2822             data.length < 6) {
2823                 sd_first_printk(KERN_WARNING, sdkp,
2824                           "getting Control mode page failed, assume no ATO\n");
2825
2826                 if (scsi_sense_valid(&sshdr))
2827                         sd_print_sense_hdr(sdkp, &sshdr);
2828
2829                 return;
2830         }
2831
2832         offset = data.header_length + data.block_descriptor_length;
2833
2834         if ((buffer[offset] & 0x3f) != 0x0a) {
2835                 sd_first_printk(KERN_ERR, sdkp, "ATO Got wrong page\n");
2836                 return;
2837         }
2838
2839         if ((buffer[offset + 5] & 0x80) == 0)
2840                 return;
2841
2842         sdkp->ATO = 1;
2843
2844         return;
2845 }
2846
2847 /**
2848  * sd_read_block_limits - Query disk device for preferred I/O sizes.
2849  * @sdkp: disk to query
2850  */
2851 static void sd_read_block_limits(struct scsi_disk *sdkp)
2852 {
2853         struct scsi_vpd *vpd;
2854
2855         rcu_read_lock();
2856
2857         vpd = rcu_dereference(sdkp->device->vpd_pgb0);
2858         if (!vpd || vpd->len < 16)
2859                 goto out;
2860
2861         sdkp->min_xfer_blocks = get_unaligned_be16(&vpd->data[6]);
2862         sdkp->max_xfer_blocks = get_unaligned_be32(&vpd->data[8]);
2863         sdkp->opt_xfer_blocks = get_unaligned_be32(&vpd->data[12]);
2864
2865         if (vpd->len >= 64) {
2866                 unsigned int lba_count, desc_count;
2867
2868                 sdkp->max_ws_blocks = (u32)get_unaligned_be64(&vpd->data[36]);
2869
2870                 if (!sdkp->lbpme)
2871                         goto out;
2872
2873                 lba_count = get_unaligned_be32(&vpd->data[20]);
2874                 desc_count = get_unaligned_be32(&vpd->data[24]);
2875
2876                 if (lba_count && desc_count)
2877                         sdkp->max_unmap_blocks = lba_count;
2878
2879                 sdkp->unmap_granularity = get_unaligned_be32(&vpd->data[28]);
2880
2881                 if (vpd->data[32] & 0x80)
2882                         sdkp->unmap_alignment =
2883                                 get_unaligned_be32(&vpd->data[32]) & ~(1 << 31);
2884
2885                 if (!sdkp->lbpvpd) { /* LBP VPD page not provided */
2886
2887                         if (sdkp->max_unmap_blocks)
2888                                 sd_config_discard(sdkp, SD_LBP_UNMAP);
2889                         else
2890                                 sd_config_discard(sdkp, SD_LBP_WS16);
2891
2892                 } else {        /* LBP VPD page tells us what to use */
2893                         if (sdkp->lbpu && sdkp->max_unmap_blocks)
2894                                 sd_config_discard(sdkp, SD_LBP_UNMAP);
2895                         else if (sdkp->lbpws)
2896                                 sd_config_discard(sdkp, SD_LBP_WS16);
2897                         else if (sdkp->lbpws10)
2898                                 sd_config_discard(sdkp, SD_LBP_WS10);
2899                         else
2900                                 sd_config_discard(sdkp, SD_LBP_DISABLE);
2901                 }
2902         }
2903
2904  out:
2905         rcu_read_unlock();
2906 }
2907
2908 /**
2909  * sd_read_block_characteristics - Query block dev. characteristics
2910  * @sdkp: disk to query
2911  */
2912 static void sd_read_block_characteristics(struct scsi_disk *sdkp)
2913 {
2914         struct request_queue *q = sdkp->disk->queue;
2915         struct scsi_vpd *vpd;
2916         u16 rot;
2917         u8 zoned;
2918
2919         rcu_read_lock();
2920         vpd = rcu_dereference(sdkp->device->vpd_pgb1);
2921
2922         if (!vpd || vpd->len < 8) {
2923                 rcu_read_unlock();
2924                 return;
2925         }
2926
2927         rot = get_unaligned_be16(&vpd->data[4]);
2928         zoned = (vpd->data[8] >> 4) & 3;
2929         rcu_read_unlock();
2930
2931         if (rot == 1) {
2932                 blk_queue_flag_set(QUEUE_FLAG_NONROT, q);
2933                 blk_queue_flag_clear(QUEUE_FLAG_ADD_RANDOM, q);
2934         }
2935
2936         if (sdkp->device->type == TYPE_ZBC) {
2937                 /* Host-managed */
2938                 disk_set_zoned(sdkp->disk, BLK_ZONED_HM);
2939         } else {
2940                 sdkp->zoned = zoned;
2941                 if (sdkp->zoned == 1) {
2942                         /* Host-aware */
2943                         disk_set_zoned(sdkp->disk, BLK_ZONED_HA);
2944                 } else {
2945                         /* Regular disk or drive managed disk */
2946                         disk_set_zoned(sdkp->disk, BLK_ZONED_NONE);
2947                 }
2948         }
2949
2950         if (!sdkp->first_scan)
2951                 return;
2952
2953         if (blk_queue_is_zoned(q)) {
2954                 sd_printk(KERN_NOTICE, sdkp, "Host-%s zoned block device\n",
2955                       q->limits.zoned == BLK_ZONED_HM ? "managed" : "aware");
2956         } else {
2957                 if (sdkp->zoned == 1)
2958                         sd_printk(KERN_NOTICE, sdkp,
2959                                   "Host-aware SMR disk used as regular disk\n");
2960                 else if (sdkp->zoned == 2)
2961                         sd_printk(KERN_NOTICE, sdkp,
2962                                   "Drive-managed SMR disk\n");
2963         }
2964 }
2965
2966 /**
2967  * sd_read_block_provisioning - Query provisioning VPD page
2968  * @sdkp: disk to query
2969  */
2970 static void sd_read_block_provisioning(struct scsi_disk *sdkp)
2971 {
2972         struct scsi_vpd *vpd;
2973
2974         if (sdkp->lbpme == 0)
2975                 return;
2976
2977         rcu_read_lock();
2978         vpd = rcu_dereference(sdkp->device->vpd_pgb2);
2979
2980         if (!vpd || vpd->len < 8) {
2981                 rcu_read_unlock();
2982                 return;
2983         }
2984
2985         sdkp->lbpvpd    = 1;
2986         sdkp->lbpu      = (vpd->data[5] >> 7) & 1; /* UNMAP */
2987         sdkp->lbpws     = (vpd->data[5] >> 6) & 1; /* WRITE SAME(16) w/ UNMAP */
2988         sdkp->lbpws10   = (vpd->data[5] >> 5) & 1; /* WRITE SAME(10) w/ UNMAP */
2989         rcu_read_unlock();
2990 }
2991
2992 static void sd_read_write_same(struct scsi_disk *sdkp, unsigned char *buffer)
2993 {
2994         struct scsi_device *sdev = sdkp->device;
2995
2996         if (sdev->host->no_write_same) {
2997                 sdev->no_write_same = 1;
2998
2999                 return;
3000         }
3001
3002         if (scsi_report_opcode(sdev, buffer, SD_BUF_SIZE, INQUIRY) < 0) {
3003                 struct scsi_vpd *vpd;
3004
3005                 sdev->no_report_opcodes = 1;
3006
3007                 /* Disable WRITE SAME if REPORT SUPPORTED OPERATION
3008                  * CODES is unsupported and the device has an ATA
3009                  * Information VPD page (SAT).
3010                  */
3011                 rcu_read_lock();
3012                 vpd = rcu_dereference(sdev->vpd_pg89);
3013                 if (vpd)
3014                         sdev->no_write_same = 1;
3015                 rcu_read_unlock();
3016         }
3017
3018         if (scsi_report_opcode(sdev, buffer, SD_BUF_SIZE, WRITE_SAME_16) == 1)
3019                 sdkp->ws16 = 1;
3020
3021         if (scsi_report_opcode(sdev, buffer, SD_BUF_SIZE, WRITE_SAME) == 1)
3022                 sdkp->ws10 = 1;
3023 }
3024
3025 static void sd_read_security(struct scsi_disk *sdkp, unsigned char *buffer)
3026 {
3027         struct scsi_device *sdev = sdkp->device;
3028
3029         if (!sdev->security_supported)
3030                 return;
3031
3032         if (scsi_report_opcode(sdev, buffer, SD_BUF_SIZE,
3033                         SECURITY_PROTOCOL_IN) == 1 &&
3034             scsi_report_opcode(sdev, buffer, SD_BUF_SIZE,
3035                         SECURITY_PROTOCOL_OUT) == 1)
3036                 sdkp->security = 1;
3037 }
3038
3039 static inline sector_t sd64_to_sectors(struct scsi_disk *sdkp, u8 *buf)
3040 {
3041         return logical_to_sectors(sdkp->device, get_unaligned_be64(buf));
3042 }
3043
3044 /**
3045  * sd_read_cpr - Query concurrent positioning ranges
3046  * @sdkp:       disk to query
3047  */
3048 static void sd_read_cpr(struct scsi_disk *sdkp)
3049 {
3050         struct blk_independent_access_ranges *iars = NULL;
3051         unsigned char *buffer = NULL;
3052         unsigned int nr_cpr = 0;
3053         int i, vpd_len, buf_len = SD_BUF_SIZE;
3054         u8 *desc;
3055
3056         /*
3057          * We need to have the capacity set first for the block layer to be
3058          * able to check the ranges.
3059          */
3060         if (sdkp->first_scan)
3061                 return;
3062
3063         if (!sdkp->capacity)
3064                 goto out;
3065
3066         /*
3067          * Concurrent Positioning Ranges VPD: there can be at most 256 ranges,
3068          * leading to a maximum page size of 64 + 256*32 bytes.
3069          */
3070         buf_len = 64 + 256*32;
3071         buffer = kmalloc(buf_len, GFP_KERNEL);
3072         if (!buffer || scsi_get_vpd_page(sdkp->device, 0xb9, buffer, buf_len))
3073                 goto out;
3074
3075         /* We must have at least a 64B header and one 32B range descriptor */
3076         vpd_len = get_unaligned_be16(&buffer[2]) + 4;
3077         if (vpd_len > buf_len || vpd_len < 64 + 32 || (vpd_len & 31)) {
3078                 sd_printk(KERN_ERR, sdkp,
3079                           "Invalid Concurrent Positioning Ranges VPD page\n");
3080                 goto out;
3081         }
3082
3083         nr_cpr = (vpd_len - 64) / 32;
3084         if (nr_cpr == 1) {
3085                 nr_cpr = 0;
3086                 goto out;
3087         }
3088
3089         iars = disk_alloc_independent_access_ranges(sdkp->disk, nr_cpr);
3090         if (!iars) {
3091                 nr_cpr = 0;
3092                 goto out;
3093         }
3094
3095         desc = &buffer[64];
3096         for (i = 0; i < nr_cpr; i++, desc += 32) {
3097                 if (desc[0] != i) {
3098                         sd_printk(KERN_ERR, sdkp,
3099                                 "Invalid Concurrent Positioning Range number\n");
3100                         nr_cpr = 0;
3101                         break;
3102                 }
3103
3104                 iars->ia_range[i].sector = sd64_to_sectors(sdkp, desc + 8);
3105                 iars->ia_range[i].nr_sectors = sd64_to_sectors(sdkp, desc + 16);
3106         }
3107
3108 out:
3109         disk_set_independent_access_ranges(sdkp->disk, iars);
3110         if (nr_cpr && sdkp->nr_actuators != nr_cpr) {
3111                 sd_printk(KERN_NOTICE, sdkp,
3112                           "%u concurrent positioning ranges\n", nr_cpr);
3113                 sdkp->nr_actuators = nr_cpr;
3114         }
3115
3116         kfree(buffer);
3117 }
3118
3119 static bool sd_validate_min_xfer_size(struct scsi_disk *sdkp)
3120 {
3121         struct scsi_device *sdp = sdkp->device;
3122         unsigned int min_xfer_bytes =
3123                 logical_to_bytes(sdp, sdkp->min_xfer_blocks);
3124
3125         if (sdkp->min_xfer_blocks == 0)
3126                 return false;
3127
3128         if (min_xfer_bytes & (sdkp->physical_block_size - 1)) {
3129                 sd_first_printk(KERN_WARNING, sdkp,
3130                                 "Preferred minimum I/O size %u bytes not a " \
3131                                 "multiple of physical block size (%u bytes)\n",
3132                                 min_xfer_bytes, sdkp->physical_block_size);
3133                 sdkp->min_xfer_blocks = 0;
3134                 return false;
3135         }
3136
3137         sd_first_printk(KERN_INFO, sdkp, "Preferred minimum I/O size %u bytes\n",
3138                         min_xfer_bytes);
3139         return true;
3140 }
3141
3142 /*
3143  * Determine the device's preferred I/O size for reads and writes
3144  * unless the reported value is unreasonably small, large, not a
3145  * multiple of the physical block size, or simply garbage.
3146  */
3147 static bool sd_validate_opt_xfer_size(struct scsi_disk *sdkp,
3148                                       unsigned int dev_max)
3149 {
3150         struct scsi_device *sdp = sdkp->device;
3151         unsigned int opt_xfer_bytes =
3152                 logical_to_bytes(sdp, sdkp->opt_xfer_blocks);
3153         unsigned int min_xfer_bytes =
3154                 logical_to_bytes(sdp, sdkp->min_xfer_blocks);
3155
3156         if (sdkp->opt_xfer_blocks == 0)
3157                 return false;
3158
3159         if (sdkp->opt_xfer_blocks > dev_max) {
3160                 sd_first_printk(KERN_WARNING, sdkp,
3161                                 "Optimal transfer size %u logical blocks " \
3162                                 "> dev_max (%u logical blocks)\n",
3163                                 sdkp->opt_xfer_blocks, dev_max);
3164                 return false;
3165         }
3166
3167         if (sdkp->opt_xfer_blocks > SD_DEF_XFER_BLOCKS) {
3168                 sd_first_printk(KERN_WARNING, sdkp,
3169                                 "Optimal transfer size %u logical blocks " \
3170                                 "> sd driver limit (%u logical blocks)\n",
3171                                 sdkp->opt_xfer_blocks, SD_DEF_XFER_BLOCKS);
3172                 return false;
3173         }
3174
3175         if (opt_xfer_bytes < PAGE_SIZE) {
3176                 sd_first_printk(KERN_WARNING, sdkp,
3177                                 "Optimal transfer size %u bytes < " \
3178                                 "PAGE_SIZE (%u bytes)\n",
3179                                 opt_xfer_bytes, (unsigned int)PAGE_SIZE);
3180                 return false;
3181         }
3182
3183         if (min_xfer_bytes && opt_xfer_bytes % min_xfer_bytes) {
3184                 sd_first_printk(KERN_WARNING, sdkp,
3185                                 "Optimal transfer size %u bytes not a " \
3186                                 "multiple of preferred minimum block " \
3187                                 "size (%u bytes)\n",
3188                                 opt_xfer_bytes, min_xfer_bytes);
3189                 return false;
3190         }
3191
3192         if (opt_xfer_bytes & (sdkp->physical_block_size - 1)) {
3193                 sd_first_printk(KERN_WARNING, sdkp,
3194                                 "Optimal transfer size %u bytes not a " \
3195                                 "multiple of physical block size (%u bytes)\n",
3196                                 opt_xfer_bytes, sdkp->physical_block_size);
3197                 return false;
3198         }
3199
3200         sd_first_printk(KERN_INFO, sdkp, "Optimal transfer size %u bytes\n",
3201                         opt_xfer_bytes);
3202         return true;
3203 }
3204
3205 /**
3206  *      sd_revalidate_disk - called the first time a new disk is seen,
3207  *      performs disk spin up, read_capacity, etc.
3208  *      @disk: struct gendisk we care about
3209  **/
3210 static int sd_revalidate_disk(struct gendisk *disk)
3211 {
3212         struct scsi_disk *sdkp = scsi_disk(disk);
3213         struct scsi_device *sdp = sdkp->device;
3214         struct request_queue *q = sdkp->disk->queue;
3215         sector_t old_capacity = sdkp->capacity;
3216         unsigned char *buffer;
3217         unsigned int dev_max, rw_max;
3218
3219         SCSI_LOG_HLQUEUE(3, sd_printk(KERN_INFO, sdkp,
3220                                       "sd_revalidate_disk\n"));
3221
3222         /*
3223          * If the device is offline, don't try and read capacity or any
3224          * of the other niceties.
3225          */
3226         if (!scsi_device_online(sdp))
3227                 goto out;
3228
3229         buffer = kmalloc(SD_BUF_SIZE, GFP_KERNEL);
3230         if (!buffer) {
3231                 sd_printk(KERN_WARNING, sdkp, "sd_revalidate_disk: Memory "
3232                           "allocation failure.\n");
3233                 goto out;
3234         }
3235
3236         sd_spinup_disk(sdkp);
3237
3238         /*
3239          * Without media there is no reason to ask; moreover, some devices
3240          * react badly if we do.
3241          */
3242         if (sdkp->media_present) {
3243                 sd_read_capacity(sdkp, buffer);
3244
3245                 /*
3246                  * set the default to rotational.  All non-rotational devices
3247                  * support the block characteristics VPD page, which will
3248                  * cause this to be updated correctly and any device which
3249                  * doesn't support it should be treated as rotational.
3250                  */
3251                 blk_queue_flag_clear(QUEUE_FLAG_NONROT, q);
3252                 blk_queue_flag_set(QUEUE_FLAG_ADD_RANDOM, q);
3253
3254                 if (scsi_device_supports_vpd(sdp)) {
3255                         sd_read_block_provisioning(sdkp);
3256                         sd_read_block_limits(sdkp);
3257                         sd_read_block_characteristics(sdkp);
3258                         sd_zbc_read_zones(sdkp, buffer);
3259                         sd_read_cpr(sdkp);
3260                 }
3261
3262                 sd_print_capacity(sdkp, old_capacity);
3263
3264                 sd_read_write_protect_flag(sdkp, buffer);
3265                 sd_read_cache_type(sdkp, buffer);
3266                 sd_read_app_tag_own(sdkp, buffer);
3267                 sd_read_write_same(sdkp, buffer);
3268                 sd_read_security(sdkp, buffer);
3269                 sd_config_protection(sdkp);
3270         }
3271
3272         /*
3273          * We now have all cache related info, determine how we deal
3274          * with flush requests.
3275          */
3276         sd_set_flush_flag(sdkp);
3277
3278         /* Initial block count limit based on CDB TRANSFER LENGTH field size. */
3279         dev_max = sdp->use_16_for_rw ? SD_MAX_XFER_BLOCKS : SD_DEF_XFER_BLOCKS;
3280
3281         /* Some devices report a maximum block count for READ/WRITE requests. */
3282         dev_max = min_not_zero(dev_max, sdkp->max_xfer_blocks);
3283         q->limits.max_dev_sectors = logical_to_sectors(sdp, dev_max);
3284
3285         if (sd_validate_min_xfer_size(sdkp))
3286                 blk_queue_io_min(sdkp->disk->queue,
3287                                  logical_to_bytes(sdp, sdkp->min_xfer_blocks));
3288         else
3289                 blk_queue_io_min(sdkp->disk->queue, 0);
3290
3291         if (sd_validate_opt_xfer_size(sdkp, dev_max)) {
3292                 q->limits.io_opt = logical_to_bytes(sdp, sdkp->opt_xfer_blocks);
3293                 rw_max = logical_to_sectors(sdp, sdkp->opt_xfer_blocks);
3294         } else {
3295                 q->limits.io_opt = 0;
3296                 rw_max = min_not_zero(logical_to_sectors(sdp, dev_max),
3297                                       (sector_t)BLK_DEF_MAX_SECTORS);
3298         }
3299
3300         /*
3301          * Limit default to SCSI host optimal sector limit if set. There may be
3302          * an impact on performance for when the size of a request exceeds this
3303          * host limit.
3304          */
3305         rw_max = min_not_zero(rw_max, sdp->host->opt_sectors);
3306
3307         /* Do not exceed controller limit */
3308         rw_max = min(rw_max, queue_max_hw_sectors(q));
3309
3310         /*
3311          * Only update max_sectors if previously unset or if the current value
3312          * exceeds the capabilities of the hardware.
3313          */
3314         if (sdkp->first_scan ||
3315             q->limits.max_sectors > q->limits.max_dev_sectors ||
3316             q->limits.max_sectors > q->limits.max_hw_sectors)
3317                 q->limits.max_sectors = rw_max;
3318
3319         sdkp->first_scan = 0;
3320
3321         set_capacity_and_notify(disk, logical_to_sectors(sdp, sdkp->capacity));
3322         sd_config_write_same(sdkp);
3323         kfree(buffer);
3324
3325         /*
3326          * For a zoned drive, revalidating the zones can be done only once
3327          * the gendisk capacity is set. So if this fails, set back the gendisk
3328          * capacity to 0.
3329          */
3330         if (sd_zbc_revalidate_zones(sdkp))
3331                 set_capacity_and_notify(disk, 0);
3332
3333  out:
3334         return 0;
3335 }
3336
3337 /**
3338  *      sd_unlock_native_capacity - unlock native capacity
3339  *      @disk: struct gendisk to set capacity for
3340  *
3341  *      Block layer calls this function if it detects that partitions
3342  *      on @disk reach beyond the end of the device.  If the SCSI host
3343  *      implements ->unlock_native_capacity() method, it's invoked to
3344  *      give it a chance to adjust the device capacity.
3345  *
3346  *      CONTEXT:
3347  *      Defined by block layer.  Might sleep.
3348  */
3349 static void sd_unlock_native_capacity(struct gendisk *disk)
3350 {
3351         struct scsi_device *sdev = scsi_disk(disk)->device;
3352
3353         if (sdev->host->hostt->unlock_native_capacity)
3354                 sdev->host->hostt->unlock_native_capacity(sdev);
3355 }
3356
3357 /**
3358  *      sd_format_disk_name - format disk name
3359  *      @prefix: name prefix - ie. "sd" for SCSI disks
3360  *      @index: index of the disk to format name for
3361  *      @buf: output buffer
3362  *      @buflen: length of the output buffer
3363  *
3364  *      SCSI disk names starts at sda.  The 26th device is sdz and the
3365  *      27th is sdaa.  The last one for two lettered suffix is sdzz
3366  *      which is followed by sdaaa.
3367  *
3368  *      This is basically 26 base counting with one extra 'nil' entry
3369  *      at the beginning from the second digit on and can be
3370  *      determined using similar method as 26 base conversion with the
3371  *      index shifted -1 after each digit is computed.
3372  *
3373  *      CONTEXT:
3374  *      Don't care.
3375  *
3376  *      RETURNS:
3377  *      0 on success, -errno on failure.
3378  */
3379 static int sd_format_disk_name(char *prefix, int index, char *buf, int buflen)
3380 {
3381         const int base = 'z' - 'a' + 1;
3382         char *begin = buf + strlen(prefix);
3383         char *end = buf + buflen;
3384         char *p;
3385         int unit;
3386
3387         p = end - 1;
3388         *p = '\0';
3389         unit = base;
3390         do {
3391                 if (p == begin)
3392                         return -EINVAL;
3393                 *--p = 'a' + (index % unit);
3394                 index = (index / unit) - 1;
3395         } while (index >= 0);
3396
3397         memmove(begin, p, end - p);
3398         memcpy(buf, prefix, strlen(prefix));
3399
3400         return 0;
3401 }
3402
3403 /**
3404  *      sd_probe - called during driver initialization and whenever a
3405  *      new scsi device is attached to the system. It is called once
3406  *      for each scsi device (not just disks) present.
3407  *      @dev: pointer to device object
3408  *
3409  *      Returns 0 if successful (or not interested in this scsi device 
3410  *      (e.g. scanner)); 1 when there is an error.
3411  *
3412  *      Note: this function is invoked from the scsi mid-level.
3413  *      This function sets up the mapping between a given 
3414  *      <host,channel,id,lun> (found in sdp) and new device name 
3415  *      (e.g. /dev/sda). More precisely it is the block device major 
3416  *      and minor number that is chosen here.
3417  *
3418  *      Assume sd_probe is not re-entrant (for time being)
3419  *      Also think about sd_probe() and sd_remove() running coincidentally.
3420  **/
3421 static int sd_probe(struct device *dev)
3422 {
3423         struct scsi_device *sdp = to_scsi_device(dev);
3424         struct scsi_disk *sdkp;
3425         struct gendisk *gd;
3426         int index;
3427         int error;
3428
3429         scsi_autopm_get_device(sdp);
3430         error = -ENODEV;
3431         if (sdp->type != TYPE_DISK &&
3432             sdp->type != TYPE_ZBC &&
3433             sdp->type != TYPE_MOD &&
3434             sdp->type != TYPE_RBC)
3435                 goto out;
3436
3437         if (!IS_ENABLED(CONFIG_BLK_DEV_ZONED) && sdp->type == TYPE_ZBC) {
3438                 sdev_printk(KERN_WARNING, sdp,
3439                             "Unsupported ZBC host-managed device.\n");
3440                 goto out;
3441         }
3442
3443         SCSI_LOG_HLQUEUE(3, sdev_printk(KERN_INFO, sdp,
3444                                         "sd_probe\n"));
3445
3446         error = -ENOMEM;
3447         sdkp = kzalloc(sizeof(*sdkp), GFP_KERNEL);
3448         if (!sdkp)
3449                 goto out;
3450
3451         gd = blk_mq_alloc_disk_for_queue(sdp->request_queue,
3452                                          &sd_bio_compl_lkclass);
3453         if (!gd)
3454                 goto out_free;
3455
3456         index = ida_alloc(&sd_index_ida, GFP_KERNEL);
3457         if (index < 0) {
3458                 sdev_printk(KERN_WARNING, sdp, "sd_probe: memory exhausted.\n");
3459                 goto out_put;
3460         }
3461
3462         error = sd_format_disk_name("sd", index, gd->disk_name, DISK_NAME_LEN);
3463         if (error) {
3464                 sdev_printk(KERN_WARNING, sdp, "SCSI disk (sd) name length exceeded.\n");
3465                 goto out_free_index;
3466         }
3467
3468         sdkp->device = sdp;
3469         sdkp->disk = gd;
3470         sdkp->index = index;
3471         sdkp->max_retries = SD_MAX_RETRIES;
3472         atomic_set(&sdkp->openers, 0);
3473         atomic_set(&sdkp->device->ioerr_cnt, 0);
3474         INIT_WORK(&sdkp->start_done_work, sd_start_done_work);
3475
3476         if (!sdp->request_queue->rq_timeout) {
3477                 if (sdp->type != TYPE_MOD)
3478                         blk_queue_rq_timeout(sdp->request_queue, SD_TIMEOUT);
3479                 else
3480                         blk_queue_rq_timeout(sdp->request_queue,
3481                                              SD_MOD_TIMEOUT);
3482         }
3483
3484         device_initialize(&sdkp->disk_dev);
3485         sdkp->disk_dev.parent = get_device(dev);
3486         sdkp->disk_dev.class = &sd_disk_class;
3487         dev_set_name(&sdkp->disk_dev, "%s", dev_name(dev));
3488
3489         error = device_add(&sdkp->disk_dev);
3490         if (error) {
3491                 put_device(&sdkp->disk_dev);
3492                 goto out;
3493         }
3494
3495         dev_set_drvdata(dev, sdkp);
3496
3497         gd->major = sd_major((index & 0xf0) >> 4);
3498         gd->first_minor = ((index & 0xf) << 4) | (index & 0xfff00);
3499         gd->minors = SD_MINORS;
3500
3501         gd->fops = &sd_fops;
3502         gd->private_data = sdkp;
3503
3504         /* defaults, until the device tells us otherwise */
3505         sdp->sector_size = 512;
3506         sdkp->capacity = 0;
3507         sdkp->media_present = 1;
3508         sdkp->write_prot = 0;
3509         sdkp->cache_override = 0;
3510         sdkp->WCE = 0;
3511         sdkp->RCD = 0;
3512         sdkp->ATO = 0;
3513         sdkp->first_scan = 1;
3514         sdkp->max_medium_access_timeouts = SD_MAX_MEDIUM_TIMEOUTS;
3515
3516         sd_revalidate_disk(gd);
3517
3518         if (sdp->removable) {
3519                 gd->flags |= GENHD_FL_REMOVABLE;
3520                 gd->events |= DISK_EVENT_MEDIA_CHANGE;
3521                 gd->event_flags = DISK_EVENT_FLAG_POLL | DISK_EVENT_FLAG_UEVENT;
3522         }
3523
3524         blk_pm_runtime_init(sdp->request_queue, dev);
3525         if (sdp->rpm_autosuspend) {
3526                 pm_runtime_set_autosuspend_delay(dev,
3527                         sdp->host->hostt->rpm_autosuspend_delay);
3528         }
3529
3530         error = device_add_disk(dev, gd, NULL);
3531         if (error) {
3532                 put_device(&sdkp->disk_dev);
3533                 put_disk(gd);
3534                 goto out;
3535         }
3536
3537         if (sdkp->security) {
3538                 sdkp->opal_dev = init_opal_dev(sdkp, &sd_sec_submit);
3539                 if (sdkp->opal_dev)
3540                         sd_printk(KERN_NOTICE, sdkp, "supports TCG Opal\n");
3541         }
3542
3543         sd_printk(KERN_NOTICE, sdkp, "Attached SCSI %sdisk\n",
3544                   sdp->removable ? "removable " : "");
3545         scsi_autopm_put_device(sdp);
3546
3547         return 0;
3548
3549  out_free_index:
3550         ida_free(&sd_index_ida, index);
3551  out_put:
3552         put_disk(gd);
3553  out_free:
3554         kfree(sdkp);
3555  out:
3556         scsi_autopm_put_device(sdp);
3557         return error;
3558 }
3559
3560 /**
3561  *      sd_remove - called whenever a scsi disk (previously recognized by
3562  *      sd_probe) is detached from the system. It is called (potentially
3563  *      multiple times) during sd module unload.
3564  *      @dev: pointer to device object
3565  *
3566  *      Note: this function is invoked from the scsi mid-level.
3567  *      This function potentially frees up a device name (e.g. /dev/sdc)
3568  *      that could be re-used by a subsequent sd_probe().
3569  *      This function is not called when the built-in sd driver is "exit-ed".
3570  **/
3571 static int sd_remove(struct device *dev)
3572 {
3573         struct scsi_disk *sdkp = dev_get_drvdata(dev);
3574
3575         scsi_autopm_get_device(sdkp->device);
3576
3577         device_del(&sdkp->disk_dev);
3578         del_gendisk(sdkp->disk);
3579         sd_shutdown(dev);
3580
3581         put_disk(sdkp->disk);
3582         return 0;
3583 }
3584
3585 static void scsi_disk_release(struct device *dev)
3586 {
3587         struct scsi_disk *sdkp = to_scsi_disk(dev);
3588
3589         ida_free(&sd_index_ida, sdkp->index);
3590         sd_zbc_free_zone_info(sdkp);
3591         put_device(&sdkp->device->sdev_gendev);
3592         free_opal_dev(sdkp->opal_dev);
3593
3594         kfree(sdkp);
3595 }
3596
3597 /* Process sense data after a START command finished. */
3598 static void sd_start_done_work(struct work_struct *work)
3599 {
3600         struct scsi_disk *sdkp = container_of(work, typeof(*sdkp),
3601                                               start_done_work);
3602         struct scsi_sense_hdr sshdr;
3603         int res = sdkp->start_result;
3604
3605         if (res == 0)
3606                 return;
3607
3608         sd_print_result(sdkp, "Start/Stop Unit failed", res);
3609
3610         if (res < 0)
3611                 return;
3612
3613         if (scsi_normalize_sense(sdkp->start_sense_buffer,
3614                                  sdkp->start_sense_len, &sshdr))
3615                 sd_print_sense_hdr(sdkp, &sshdr);
3616 }
3617
3618 /* A START command finished. May be called from interrupt context. */
3619 static void sd_start_done(struct request *req, blk_status_t status)
3620 {
3621         const struct scsi_cmnd *scmd = blk_mq_rq_to_pdu(req);
3622         struct scsi_disk *sdkp = scsi_disk(req->q->disk);
3623
3624         sdkp->start_result = scmd->result;
3625         WARN_ON_ONCE(scmd->sense_len > SCSI_SENSE_BUFFERSIZE);
3626         sdkp->start_sense_len = scmd->sense_len;
3627         memcpy(sdkp->start_sense_buffer, scmd->sense_buffer,
3628                ARRAY_SIZE(sdkp->start_sense_buffer));
3629         WARN_ON_ONCE(!schedule_work(&sdkp->start_done_work));
3630 }
3631
3632 /* Submit a START command asynchronously. */
3633 static int sd_submit_start(struct scsi_disk *sdkp, u8 cmd[], u8 cmd_len)
3634 {
3635         struct scsi_device *sdev = sdkp->device;
3636         struct request_queue *q = sdev->request_queue;
3637         struct request *req;
3638         struct scsi_cmnd *scmd;
3639
3640         req = scsi_alloc_request(q, REQ_OP_DRV_IN, BLK_MQ_REQ_PM);
3641         if (IS_ERR(req))
3642                 return PTR_ERR(req);
3643
3644         scmd = blk_mq_rq_to_pdu(req);
3645         scmd->cmd_len = cmd_len;
3646         memcpy(scmd->cmnd, cmd, cmd_len);
3647         scmd->allowed = sdkp->max_retries;
3648         req->timeout = SD_TIMEOUT;
3649         req->rq_flags |= RQF_PM | RQF_QUIET;
3650         req->end_io = sd_start_done;
3651         blk_execute_rq_nowait(req, /*at_head=*/true);
3652
3653         return 0;
3654 }
3655
3656 static int sd_start_stop_device(struct scsi_disk *sdkp, int start)
3657 {
3658         unsigned char cmd[6] = { START_STOP };  /* START_VALID */
3659         struct scsi_device *sdp = sdkp->device;
3660
3661         if (start)
3662                 cmd[4] |= 1;    /* START */
3663
3664         if (sdp->start_stop_pwr_cond)
3665                 cmd[4] |= start ? 1 << 4 : 3 << 4;      /* Active or Standby */
3666
3667         if (!scsi_device_online(sdp))
3668                 return -ENODEV;
3669
3670         /* Wait until processing of sense data has finished. */
3671         flush_work(&sdkp->start_done_work);
3672
3673         return sd_submit_start(sdkp, cmd, sizeof(cmd));
3674 }
3675
3676 /*
3677  * Send a SYNCHRONIZE CACHE instruction down to the device through
3678  * the normal SCSI command structure.  Wait for the command to
3679  * complete.
3680  */
3681 static void sd_shutdown(struct device *dev)
3682 {
3683         struct scsi_disk *sdkp = dev_get_drvdata(dev);
3684
3685         if (!sdkp)
3686                 return;         /* this can happen */
3687
3688         if (pm_runtime_suspended(dev))
3689                 return;
3690
3691         if (sdkp->WCE && sdkp->media_present) {
3692                 sd_printk(KERN_NOTICE, sdkp, "Synchronizing SCSI cache\n");
3693                 sd_sync_cache(sdkp, NULL);
3694         }
3695
3696         if (system_state != SYSTEM_RESTART && sdkp->device->manage_start_stop) {
3697                 sd_printk(KERN_NOTICE, sdkp, "Stopping disk\n");
3698                 sd_start_stop_device(sdkp, 0);
3699         }
3700
3701         flush_work(&sdkp->start_done_work);
3702 }
3703
3704 static int sd_suspend_common(struct device *dev, bool ignore_stop_errors)
3705 {
3706         struct scsi_disk *sdkp = dev_get_drvdata(dev);
3707         struct scsi_sense_hdr sshdr;
3708         int ret = 0;
3709
3710         if (!sdkp)      /* E.g.: runtime suspend following sd_remove() */
3711                 return 0;
3712
3713         if (sdkp->WCE && sdkp->media_present) {
3714                 if (!sdkp->device->silence_suspend)
3715                         sd_printk(KERN_NOTICE, sdkp, "Synchronizing SCSI cache\n");
3716                 ret = sd_sync_cache(sdkp, &sshdr);
3717
3718                 if (ret) {
3719                         /* ignore OFFLINE device */
3720                         if (ret == -ENODEV)
3721                                 return 0;
3722
3723                         if (!scsi_sense_valid(&sshdr) ||
3724                             sshdr.sense_key != ILLEGAL_REQUEST)
3725                                 return ret;
3726
3727                         /*
3728                          * sshdr.sense_key == ILLEGAL_REQUEST means this drive
3729                          * doesn't support sync. There's not much to do and
3730                          * suspend shouldn't fail.
3731                          */
3732                         ret = 0;
3733                 }
3734         }
3735
3736         if (sdkp->device->manage_start_stop) {
3737                 if (!sdkp->device->silence_suspend)
3738                         sd_printk(KERN_NOTICE, sdkp, "Stopping disk\n");
3739                 /* an error is not worth aborting a system sleep */
3740                 ret = sd_start_stop_device(sdkp, 0);
3741                 if (ignore_stop_errors)
3742                         ret = 0;
3743         }
3744
3745         return ret;
3746 }
3747
3748 static int sd_suspend_system(struct device *dev)
3749 {
3750         if (pm_runtime_suspended(dev))
3751                 return 0;
3752
3753         return sd_suspend_common(dev, true);
3754 }
3755
3756 static int sd_suspend_runtime(struct device *dev)
3757 {
3758         return sd_suspend_common(dev, false);
3759 }
3760
3761 static int sd_resume(struct device *dev)
3762 {
3763         struct scsi_disk *sdkp = dev_get_drvdata(dev);
3764         int ret;
3765
3766         if (!sdkp)      /* E.g.: runtime resume at the start of sd_probe() */
3767                 return 0;
3768
3769         if (!sdkp->device->manage_start_stop)
3770                 return 0;
3771
3772         sd_printk(KERN_NOTICE, sdkp, "Starting disk\n");
3773         ret = sd_start_stop_device(sdkp, 1);
3774         if (!ret)
3775                 opal_unlock_from_suspend(sdkp->opal_dev);
3776         return ret;
3777 }
3778
3779 static int sd_resume_system(struct device *dev)
3780 {
3781         if (pm_runtime_suspended(dev))
3782                 return 0;
3783
3784         return sd_resume(dev);
3785 }
3786
3787 static int sd_resume_runtime(struct device *dev)
3788 {
3789         struct scsi_disk *sdkp = dev_get_drvdata(dev);
3790         struct scsi_device *sdp;
3791
3792         if (!sdkp)      /* E.g.: runtime resume at the start of sd_probe() */
3793                 return 0;
3794
3795         sdp = sdkp->device;
3796
3797         if (sdp->ignore_media_change) {
3798                 /* clear the device's sense data */
3799                 static const u8 cmd[10] = { REQUEST_SENSE };
3800
3801                 if (scsi_execute(sdp, cmd, DMA_NONE, NULL, 0, NULL,
3802                                  NULL, sdp->request_queue->rq_timeout, 1, 0,
3803                                  RQF_PM, NULL))
3804                         sd_printk(KERN_NOTICE, sdkp,
3805                                   "Failed to clear sense data\n");
3806         }
3807
3808         return sd_resume(dev);
3809 }
3810
3811 /**
3812  *      init_sd - entry point for this driver (both when built in or when
3813  *      a module).
3814  *
3815  *      Note: this function registers this driver with the scsi mid-level.
3816  **/
3817 static int __init init_sd(void)
3818 {
3819         int majors = 0, i, err;
3820
3821         SCSI_LOG_HLQUEUE(3, printk("init_sd: sd driver entry point\n"));
3822
3823         for (i = 0; i < SD_MAJORS; i++) {
3824                 if (__register_blkdev(sd_major(i), "sd", sd_default_probe))
3825                         continue;
3826                 majors++;
3827         }
3828
3829         if (!majors)
3830                 return -ENODEV;
3831
3832         err = class_register(&sd_disk_class);
3833         if (err)
3834                 goto err_out;
3835
3836         sd_cdb_cache = kmem_cache_create("sd_ext_cdb", SD_EXT_CDB_SIZE,
3837                                          0, 0, NULL);
3838         if (!sd_cdb_cache) {
3839                 printk(KERN_ERR "sd: can't init extended cdb cache\n");
3840                 err = -ENOMEM;
3841                 goto err_out_class;
3842         }
3843
3844         sd_page_pool = mempool_create_page_pool(SD_MEMPOOL_SIZE, 0);
3845         if (!sd_page_pool) {
3846                 printk(KERN_ERR "sd: can't init discard page pool\n");
3847                 err = -ENOMEM;
3848                 goto err_out_cache;
3849         }
3850
3851         err = scsi_register_driver(&sd_template.gendrv);
3852         if (err)
3853                 goto err_out_driver;
3854
3855         return 0;
3856
3857 err_out_driver:
3858         mempool_destroy(sd_page_pool);
3859
3860 err_out_cache:
3861         kmem_cache_destroy(sd_cdb_cache);
3862
3863 err_out_class:
3864         class_unregister(&sd_disk_class);
3865 err_out:
3866         for (i = 0; i < SD_MAJORS; i++)
3867                 unregister_blkdev(sd_major(i), "sd");
3868         return err;
3869 }
3870
3871 /**
3872  *      exit_sd - exit point for this driver (when it is a module).
3873  *
3874  *      Note: this function unregisters this driver from the scsi mid-level.
3875  **/
3876 static void __exit exit_sd(void)
3877 {
3878         int i;
3879
3880         SCSI_LOG_HLQUEUE(3, printk("exit_sd: exiting sd driver\n"));
3881
3882         scsi_unregister_driver(&sd_template.gendrv);
3883         mempool_destroy(sd_page_pool);
3884         kmem_cache_destroy(sd_cdb_cache);
3885
3886         class_unregister(&sd_disk_class);
3887
3888         for (i = 0; i < SD_MAJORS; i++)
3889                 unregister_blkdev(sd_major(i), "sd");
3890 }
3891
3892 module_init(init_sd);
3893 module_exit(exit_sd);
3894
3895 void sd_print_sense_hdr(struct scsi_disk *sdkp, struct scsi_sense_hdr *sshdr)
3896 {
3897         scsi_print_sense_hdr(sdkp->device,
3898                              sdkp->disk ? sdkp->disk->disk_name : NULL, sshdr);
3899 }
3900
3901 void sd_print_result(const struct scsi_disk *sdkp, const char *msg, int result)
3902 {
3903         const char *hb_string = scsi_hostbyte_string(result);
3904
3905         if (hb_string)
3906                 sd_printk(KERN_INFO, sdkp,
3907                           "%s: Result: hostbyte=%s driverbyte=%s\n", msg,
3908                           hb_string ? hb_string : "invalid",
3909                           "DRIVER_OK");
3910         else
3911                 sd_printk(KERN_INFO, sdkp,
3912                           "%s: Result: hostbyte=0x%02x driverbyte=%s\n",
3913                           msg, host_byte(result), "DRIVER_OK");
3914 }