Merge drm/drm-next into drm-intel-gt-next
[linux-2.6-microblaze.git] / drivers / scsi / sr.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *  sr.c Copyright (C) 1992 David Giller
4  *           Copyright (C) 1993, 1994, 1995, 1999 Eric Youngdale
5  *
6  *  adapted from:
7  *      sd.c Copyright (C) 1992 Drew Eckhardt
8  *      Linux scsi disk driver by
9  *              Drew Eckhardt <drew@colorado.edu>
10  *
11  *      Modified by Eric Youngdale ericy@andante.org to
12  *      add scatter-gather, multiple outstanding request, and other
13  *      enhancements.
14  *
15  *      Modified by Eric Youngdale eric@andante.org to support loadable
16  *      low-level scsi drivers.
17  *
18  *      Modified by Thomas Quinot thomas@melchior.cuivre.fdn.fr to
19  *      provide auto-eject.
20  *
21  *      Modified by Gerd Knorr <kraxel@cs.tu-berlin.de> to support the
22  *      generic cdrom interface
23  *
24  *      Modified by Jens Axboe <axboe@suse.de> - Uniform sr_packet()
25  *      interface, capabilities probe additions, ioctl cleanups, etc.
26  *
27  *      Modified by Richard Gooch <rgooch@atnf.csiro.au> to support devfs
28  *
29  *      Modified by Jens Axboe <axboe@suse.de> - support DVD-RAM
30  *      transparently and lose the GHOST hack
31  *
32  *      Modified by Arnaldo Carvalho de Melo <acme@conectiva.com.br>
33  *      check resource allocation in sr_init and some cleanups
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/compat.h>
42 #include <linux/string.h>
43 #include <linux/errno.h>
44 #include <linux/cdrom.h>
45 #include <linux/interrupt.h>
46 #include <linux/init.h>
47 #include <linux/major.h>
48 #include <linux/blkdev.h>
49 #include <linux/blk-pm.h>
50 #include <linux/mutex.h>
51 #include <linux/slab.h>
52 #include <linux/pm_runtime.h>
53 #include <linux/uaccess.h>
54
55 #include <asm/unaligned.h>
56
57 #include <scsi/scsi.h>
58 #include <scsi/scsi_dbg.h>
59 #include <scsi/scsi_device.h>
60 #include <scsi/scsi_driver.h>
61 #include <scsi/scsi_cmnd.h>
62 #include <scsi/scsi_eh.h>
63 #include <scsi/scsi_host.h>
64 #include <scsi/scsi_ioctl.h>    /* For the door lock/unlock commands */
65
66 #include "scsi_logging.h"
67 #include "sr.h"
68
69
70 MODULE_DESCRIPTION("SCSI cdrom (sr) driver");
71 MODULE_LICENSE("GPL");
72 MODULE_ALIAS_BLOCKDEV_MAJOR(SCSI_CDROM_MAJOR);
73 MODULE_ALIAS_SCSI_DEVICE(TYPE_ROM);
74 MODULE_ALIAS_SCSI_DEVICE(TYPE_WORM);
75
76 #define SR_DISKS        256
77
78 #define SR_CAPABILITIES \
79         (CDC_CLOSE_TRAY|CDC_OPEN_TRAY|CDC_LOCK|CDC_SELECT_SPEED| \
80          CDC_SELECT_DISC|CDC_MULTI_SESSION|CDC_MCN|CDC_MEDIA_CHANGED| \
81          CDC_PLAY_AUDIO|CDC_RESET|CDC_DRIVE_STATUS| \
82          CDC_CD_R|CDC_CD_RW|CDC_DVD|CDC_DVD_R|CDC_DVD_RAM|CDC_GENERIC_PACKET| \
83          CDC_MRW|CDC_MRW_W|CDC_RAM)
84
85 static int sr_probe(struct device *);
86 static int sr_remove(struct device *);
87 static blk_status_t sr_init_command(struct scsi_cmnd *SCpnt);
88 static int sr_done(struct scsi_cmnd *);
89 static int sr_runtime_suspend(struct device *dev);
90
91 static const struct dev_pm_ops sr_pm_ops = {
92         .runtime_suspend        = sr_runtime_suspend,
93 };
94
95 static struct scsi_driver sr_template = {
96         .gendrv = {
97                 .name           = "sr",
98                 .owner          = THIS_MODULE,
99                 .probe          = sr_probe,
100                 .remove         = sr_remove,
101                 .pm             = &sr_pm_ops,
102         },
103         .init_command           = sr_init_command,
104         .done                   = sr_done,
105 };
106
107 static unsigned long sr_index_bits[SR_DISKS / BITS_PER_LONG];
108 static DEFINE_SPINLOCK(sr_index_lock);
109
110 static struct lock_class_key sr_bio_compl_lkclass;
111
112 /* This semaphore is used to mediate the 0->1 reference get in the
113  * face of object destruction (i.e. we can't allow a get on an
114  * object after last put) */
115 static DEFINE_MUTEX(sr_ref_mutex);
116
117 static int sr_open(struct cdrom_device_info *, int);
118 static void sr_release(struct cdrom_device_info *);
119
120 static void get_sectorsize(struct scsi_cd *);
121 static void get_capabilities(struct scsi_cd *);
122
123 static unsigned int sr_check_events(struct cdrom_device_info *cdi,
124                                     unsigned int clearing, int slot);
125 static int sr_packet(struct cdrom_device_info *, struct packet_command *);
126 static int sr_read_cdda_bpc(struct cdrom_device_info *cdi, void __user *ubuf,
127                 u32 lba, u32 nr, u8 *last_sense);
128
129 static const struct cdrom_device_ops sr_dops = {
130         .open                   = sr_open,
131         .release                = sr_release,
132         .drive_status           = sr_drive_status,
133         .check_events           = sr_check_events,
134         .tray_move              = sr_tray_move,
135         .lock_door              = sr_lock_door,
136         .select_speed           = sr_select_speed,
137         .get_last_session       = sr_get_last_session,
138         .get_mcn                = sr_get_mcn,
139         .reset                  = sr_reset,
140         .audio_ioctl            = sr_audio_ioctl,
141         .generic_packet         = sr_packet,
142         .read_cdda_bpc          = sr_read_cdda_bpc,
143         .capability             = SR_CAPABILITIES,
144 };
145
146 static void sr_kref_release(struct kref *kref);
147
148 static inline struct scsi_cd *scsi_cd(struct gendisk *disk)
149 {
150         return container_of(disk->private_data, struct scsi_cd, driver);
151 }
152
153 static int sr_runtime_suspend(struct device *dev)
154 {
155         struct scsi_cd *cd = dev_get_drvdata(dev);
156
157         if (!cd)        /* E.g.: runtime suspend following sr_remove() */
158                 return 0;
159
160         if (cd->media_present)
161                 return -EBUSY;
162         else
163                 return 0;
164 }
165
166 /*
167  * The get and put routines for the struct scsi_cd.  Note this entity
168  * has a scsi_device pointer and owns a reference to this.
169  */
170 static inline struct scsi_cd *scsi_cd_get(struct gendisk *disk)
171 {
172         struct scsi_cd *cd = NULL;
173
174         mutex_lock(&sr_ref_mutex);
175         if (disk->private_data == NULL)
176                 goto out;
177         cd = scsi_cd(disk);
178         kref_get(&cd->kref);
179         if (scsi_device_get(cd->device)) {
180                 kref_put(&cd->kref, sr_kref_release);
181                 cd = NULL;
182         }
183  out:
184         mutex_unlock(&sr_ref_mutex);
185         return cd;
186 }
187
188 static void scsi_cd_put(struct scsi_cd *cd)
189 {
190         struct scsi_device *sdev = cd->device;
191
192         mutex_lock(&sr_ref_mutex);
193         kref_put(&cd->kref, sr_kref_release);
194         scsi_device_put(sdev);
195         mutex_unlock(&sr_ref_mutex);
196 }
197
198 static unsigned int sr_get_events(struct scsi_device *sdev)
199 {
200         u8 buf[8];
201         u8 cmd[] = { GET_EVENT_STATUS_NOTIFICATION,
202                      1,                 /* polled */
203                      0, 0,              /* reserved */
204                      1 << 4,            /* notification class: media */
205                      0, 0,              /* reserved */
206                      0, sizeof(buf),    /* allocation length */
207                      0,                 /* control */
208         };
209         struct event_header *eh = (void *)buf;
210         struct media_event_desc *med = (void *)(buf + 4);
211         struct scsi_sense_hdr sshdr;
212         int result;
213
214         result = scsi_execute_req(sdev, cmd, DMA_FROM_DEVICE, buf, sizeof(buf),
215                                   &sshdr, SR_TIMEOUT, MAX_RETRIES, NULL);
216         if (scsi_sense_valid(&sshdr) && sshdr.sense_key == UNIT_ATTENTION)
217                 return DISK_EVENT_MEDIA_CHANGE;
218
219         if (result || be16_to_cpu(eh->data_len) < sizeof(*med))
220                 return 0;
221
222         if (eh->nea || eh->notification_class != 0x4)
223                 return 0;
224
225         if (med->media_event_code == 1)
226                 return DISK_EVENT_EJECT_REQUEST;
227         else if (med->media_event_code == 2)
228                 return DISK_EVENT_MEDIA_CHANGE;
229         else if (med->media_event_code == 3)
230                 return DISK_EVENT_MEDIA_CHANGE;
231         return 0;
232 }
233
234 /*
235  * This function checks to see if the media has been changed or eject
236  * button has been pressed.  It is possible that we have already
237  * sensed a change, or the drive may have sensed one and not yet
238  * reported it.  The past events are accumulated in sdev->changed and
239  * returned together with the current state.
240  */
241 static unsigned int sr_check_events(struct cdrom_device_info *cdi,
242                                     unsigned int clearing, int slot)
243 {
244         struct scsi_cd *cd = cdi->handle;
245         bool last_present;
246         struct scsi_sense_hdr sshdr;
247         unsigned int events;
248         int ret;
249
250         /* no changer support */
251         if (CDSL_CURRENT != slot)
252                 return 0;
253
254         events = sr_get_events(cd->device);
255         cd->get_event_changed |= events & DISK_EVENT_MEDIA_CHANGE;
256
257         /*
258          * If earlier GET_EVENT_STATUS_NOTIFICATION and TUR did not agree
259          * for several times in a row.  We rely on TUR only for this likely
260          * broken device, to prevent generating incorrect media changed
261          * events for every open().
262          */
263         if (cd->ignore_get_event) {
264                 events &= ~DISK_EVENT_MEDIA_CHANGE;
265                 goto do_tur;
266         }
267
268         /*
269          * GET_EVENT_STATUS_NOTIFICATION is enough unless MEDIA_CHANGE
270          * is being cleared.  Note that there are devices which hang
271          * if asked to execute TUR repeatedly.
272          */
273         if (cd->device->changed) {
274                 events |= DISK_EVENT_MEDIA_CHANGE;
275                 cd->device->changed = 0;
276                 cd->tur_changed = true;
277         }
278
279         if (!(clearing & DISK_EVENT_MEDIA_CHANGE))
280                 return events;
281 do_tur:
282         /* let's see whether the media is there with TUR */
283         last_present = cd->media_present;
284         ret = scsi_test_unit_ready(cd->device, SR_TIMEOUT, MAX_RETRIES, &sshdr);
285
286         /*
287          * Media is considered to be present if TUR succeeds or fails with
288          * sense data indicating something other than media-not-present
289          * (ASC 0x3a).
290          */
291         cd->media_present = scsi_status_is_good(ret) ||
292                 (scsi_sense_valid(&sshdr) && sshdr.asc != 0x3a);
293
294         if (last_present != cd->media_present)
295                 cd->device->changed = 1;
296
297         if (cd->device->changed) {
298                 events |= DISK_EVENT_MEDIA_CHANGE;
299                 cd->device->changed = 0;
300                 cd->tur_changed = true;
301         }
302
303         if (cd->ignore_get_event)
304                 return events;
305
306         /* check whether GET_EVENT is reporting spurious MEDIA_CHANGE */
307         if (!cd->tur_changed) {
308                 if (cd->get_event_changed) {
309                         if (cd->tur_mismatch++ > 8) {
310                                 sr_printk(KERN_WARNING, cd,
311                                           "GET_EVENT and TUR disagree continuously, suppress GET_EVENT events\n");
312                                 cd->ignore_get_event = true;
313                         }
314                 } else {
315                         cd->tur_mismatch = 0;
316                 }
317         }
318         cd->tur_changed = false;
319         cd->get_event_changed = false;
320
321         return events;
322 }
323
324 /*
325  * sr_done is the interrupt routine for the device driver.
326  *
327  * It will be notified on the end of a SCSI read / write, and will take one
328  * of several actions based on success or failure.
329  */
330 static int sr_done(struct scsi_cmnd *SCpnt)
331 {
332         int result = SCpnt->result;
333         int this_count = scsi_bufflen(SCpnt);
334         int good_bytes = (result == 0 ? this_count : 0);
335         int block_sectors = 0;
336         long error_sector;
337         struct request *rq = scsi_cmd_to_rq(SCpnt);
338         struct scsi_cd *cd = scsi_cd(rq->q->disk);
339
340 #ifdef DEBUG
341         scmd_printk(KERN_INFO, SCpnt, "done: %x\n", result);
342 #endif
343
344         /*
345          * Handle MEDIUM ERRORs or VOLUME OVERFLOWs that indicate partial
346          * success.  Since this is a relatively rare error condition, no
347          * care is taken to avoid unnecessary additional work such as
348          * memcpy's that could be avoided.
349          */
350         if (scsi_status_is_check_condition(result) &&
351             (SCpnt->sense_buffer[0] & 0x7f) == 0x70) { /* Sense current */
352                 switch (SCpnt->sense_buffer[2]) {
353                 case MEDIUM_ERROR:
354                 case VOLUME_OVERFLOW:
355                 case ILLEGAL_REQUEST:
356                         if (!(SCpnt->sense_buffer[0] & 0x90))
357                                 break;
358                         error_sector =
359                                 get_unaligned_be32(&SCpnt->sense_buffer[3]);
360                         if (rq->bio != NULL)
361                                 block_sectors = bio_sectors(rq->bio);
362                         if (block_sectors < 4)
363                                 block_sectors = 4;
364                         if (cd->device->sector_size == 2048)
365                                 error_sector <<= 2;
366                         error_sector &= ~(block_sectors - 1);
367                         good_bytes = (error_sector - blk_rq_pos(rq)) << 9;
368                         if (good_bytes < 0 || good_bytes >= this_count)
369                                 good_bytes = 0;
370                         /*
371                          * The SCSI specification allows for the value
372                          * returned by READ CAPACITY to be up to 75 2K
373                          * sectors past the last readable block.
374                          * Therefore, if we hit a medium error within the
375                          * last 75 2K sectors, we decrease the saved size
376                          * value.
377                          */
378                         if (error_sector < get_capacity(cd->disk) &&
379                             cd->capacity - error_sector < 4 * 75)
380                                 set_capacity(cd->disk, error_sector);
381                         break;
382
383                 case RECOVERED_ERROR:
384                         good_bytes = this_count;
385                         break;
386
387                 default:
388                         break;
389                 }
390         }
391
392         return good_bytes;
393 }
394
395 static blk_status_t sr_init_command(struct scsi_cmnd *SCpnt)
396 {
397         int block = 0, this_count, s_size;
398         struct scsi_cd *cd;
399         struct request *rq = scsi_cmd_to_rq(SCpnt);
400         blk_status_t ret;
401
402         ret = scsi_alloc_sgtables(SCpnt);
403         if (ret != BLK_STS_OK)
404                 return ret;
405         cd = scsi_cd(rq->q->disk);
406
407         SCSI_LOG_HLQUEUE(1, scmd_printk(KERN_INFO, SCpnt,
408                 "Doing sr request, block = %d\n", block));
409
410         if (!cd->device || !scsi_device_online(cd->device)) {
411                 SCSI_LOG_HLQUEUE(2, scmd_printk(KERN_INFO, SCpnt,
412                         "Finishing %u sectors\n", blk_rq_sectors(rq)));
413                 SCSI_LOG_HLQUEUE(2, scmd_printk(KERN_INFO, SCpnt,
414                         "Retry with 0x%p\n", SCpnt));
415                 goto out;
416         }
417
418         if (cd->device->changed) {
419                 /*
420                  * quietly refuse to do anything to a changed disc until the
421                  * changed bit has been reset
422                  */
423                 goto out;
424         }
425
426         s_size = cd->device->sector_size;
427         if (s_size != 512 && s_size != 1024 && s_size != 2048) {
428                 scmd_printk(KERN_ERR, SCpnt, "bad sector size %d\n", s_size);
429                 goto out;
430         }
431
432         switch (req_op(rq)) {
433         case REQ_OP_WRITE:
434                 if (!cd->writeable)
435                         goto out;
436                 SCpnt->cmnd[0] = WRITE_10;
437                 cd->cdi.media_written = 1;
438                 break;
439         case REQ_OP_READ:
440                 SCpnt->cmnd[0] = READ_10;
441                 break;
442         default:
443                 blk_dump_rq_flags(rq, "Unknown sr command");
444                 goto out;
445         }
446
447         {
448                 struct scatterlist *sg;
449                 int i, size = 0, sg_count = scsi_sg_count(SCpnt);
450
451                 scsi_for_each_sg(SCpnt, sg, sg_count, i)
452                         size += sg->length;
453
454                 if (size != scsi_bufflen(SCpnt)) {
455                         scmd_printk(KERN_ERR, SCpnt,
456                                 "mismatch count %d, bytes %d\n",
457                                 size, scsi_bufflen(SCpnt));
458                         if (scsi_bufflen(SCpnt) > size)
459                                 SCpnt->sdb.length = size;
460                 }
461         }
462
463         /*
464          * request doesn't start on hw block boundary, add scatter pads
465          */
466         if (((unsigned int)blk_rq_pos(rq) % (s_size >> 9)) ||
467             (scsi_bufflen(SCpnt) % s_size)) {
468                 scmd_printk(KERN_NOTICE, SCpnt, "unaligned transfer\n");
469                 goto out;
470         }
471
472         this_count = (scsi_bufflen(SCpnt) >> 9) / (s_size >> 9);
473
474
475         SCSI_LOG_HLQUEUE(2, scmd_printk(KERN_INFO, SCpnt,
476                                         "%s %d/%u 512 byte blocks.\n",
477                                         (rq_data_dir(rq) == WRITE) ?
478                                         "writing" : "reading",
479                                         this_count, blk_rq_sectors(rq)));
480
481         SCpnt->cmnd[1] = 0;
482         block = (unsigned int)blk_rq_pos(rq) / (s_size >> 9);
483
484         if (this_count > 0xffff) {
485                 this_count = 0xffff;
486                 SCpnt->sdb.length = this_count * s_size;
487         }
488
489         put_unaligned_be32(block, &SCpnt->cmnd[2]);
490         SCpnt->cmnd[6] = SCpnt->cmnd[9] = 0;
491         put_unaligned_be16(this_count, &SCpnt->cmnd[7]);
492
493         /*
494          * We shouldn't disconnect in the middle of a sector, so with a dumb
495          * host adapter, it's safe to assume that we can at least transfer
496          * this many bytes between each connect / disconnect.
497          */
498         SCpnt->transfersize = cd->device->sector_size;
499         SCpnt->underflow = this_count << 9;
500         SCpnt->allowed = MAX_RETRIES;
501         SCpnt->cmd_len = 10;
502
503         /*
504          * This indicates that the command is ready from our end to be queued.
505          */
506         return BLK_STS_OK;
507  out:
508         scsi_free_sgtables(SCpnt);
509         return BLK_STS_IOERR;
510 }
511
512 static void sr_revalidate_disk(struct scsi_cd *cd)
513 {
514         struct scsi_sense_hdr sshdr;
515
516         /* if the unit is not ready, nothing more to do */
517         if (scsi_test_unit_ready(cd->device, SR_TIMEOUT, MAX_RETRIES, &sshdr))
518                 return;
519         sr_cd_check(&cd->cdi);
520         get_sectorsize(cd);
521 }
522
523 static int sr_block_open(struct block_device *bdev, fmode_t mode)
524 {
525         struct scsi_cd *cd;
526         struct scsi_device *sdev;
527         int ret = -ENXIO;
528
529         cd = scsi_cd_get(bdev->bd_disk);
530         if (!cd)
531                 goto out;
532
533         sdev = cd->device;
534         scsi_autopm_get_device(sdev);
535         if (bdev_check_media_change(bdev))
536                 sr_revalidate_disk(cd);
537
538         mutex_lock(&cd->lock);
539         ret = cdrom_open(&cd->cdi, bdev, mode);
540         mutex_unlock(&cd->lock);
541
542         scsi_autopm_put_device(sdev);
543         if (ret)
544                 scsi_cd_put(cd);
545
546 out:
547         return ret;
548 }
549
550 static void sr_block_release(struct gendisk *disk, fmode_t mode)
551 {
552         struct scsi_cd *cd = scsi_cd(disk);
553
554         mutex_lock(&cd->lock);
555         cdrom_release(&cd->cdi, mode);
556         mutex_unlock(&cd->lock);
557
558         scsi_cd_put(cd);
559 }
560
561 static int sr_block_ioctl(struct block_device *bdev, fmode_t mode, unsigned cmd,
562                           unsigned long arg)
563 {
564         struct scsi_cd *cd = scsi_cd(bdev->bd_disk);
565         struct scsi_device *sdev = cd->device;
566         void __user *argp = (void __user *)arg;
567         int ret;
568
569         if (bdev_is_partition(bdev) && !capable(CAP_SYS_RAWIO))
570                 return -ENOIOCTLCMD;
571
572         mutex_lock(&cd->lock);
573
574         ret = scsi_ioctl_block_when_processing_errors(sdev, cmd,
575                         (mode & FMODE_NDELAY) != 0);
576         if (ret)
577                 goto out;
578
579         scsi_autopm_get_device(sdev);
580
581         if (ret != CDROMCLOSETRAY && ret != CDROMEJECT) {
582                 ret = cdrom_ioctl(&cd->cdi, bdev, mode, cmd, arg);
583                 if (ret != -ENOSYS)
584                         goto put;
585         }
586         ret = scsi_ioctl(sdev, mode, cmd, argp);
587
588 put:
589         scsi_autopm_put_device(sdev);
590 out:
591         mutex_unlock(&cd->lock);
592         return ret;
593 }
594
595 static unsigned int sr_block_check_events(struct gendisk *disk,
596                                           unsigned int clearing)
597 {
598         unsigned int ret = 0;
599         struct scsi_cd *cd;
600
601         cd = scsi_cd_get(disk);
602         if (!cd)
603                 return 0;
604
605         if (!atomic_read(&cd->device->disk_events_disable_depth))
606                 ret = cdrom_check_events(&cd->cdi, clearing);
607
608         scsi_cd_put(cd);
609         return ret;
610 }
611
612 static const struct block_device_operations sr_bdops =
613 {
614         .owner          = THIS_MODULE,
615         .open           = sr_block_open,
616         .release        = sr_block_release,
617         .ioctl          = sr_block_ioctl,
618         .compat_ioctl   = blkdev_compat_ptr_ioctl,
619         .check_events   = sr_block_check_events,
620 };
621
622 static int sr_open(struct cdrom_device_info *cdi, int purpose)
623 {
624         struct scsi_cd *cd = cdi->handle;
625         struct scsi_device *sdev = cd->device;
626         int retval;
627
628         /*
629          * If the device is in error recovery, wait until it is done.
630          * If the device is offline, then disallow any access to it.
631          */
632         retval = -ENXIO;
633         if (!scsi_block_when_processing_errors(sdev))
634                 goto error_out;
635
636         return 0;
637
638 error_out:
639         return retval;  
640 }
641
642 static void sr_release(struct cdrom_device_info *cdi)
643 {
644 }
645
646 static int sr_probe(struct device *dev)
647 {
648         struct scsi_device *sdev = to_scsi_device(dev);
649         struct gendisk *disk;
650         struct scsi_cd *cd;
651         int minor, error;
652
653         scsi_autopm_get_device(sdev);
654         error = -ENODEV;
655         if (sdev->type != TYPE_ROM && sdev->type != TYPE_WORM)
656                 goto fail;
657
658         error = -ENOMEM;
659         cd = kzalloc(sizeof(*cd), GFP_KERNEL);
660         if (!cd)
661                 goto fail;
662
663         kref_init(&cd->kref);
664
665         disk = __alloc_disk_node(sdev->request_queue, NUMA_NO_NODE,
666                                  &sr_bio_compl_lkclass);
667         if (!disk)
668                 goto fail_free;
669         mutex_init(&cd->lock);
670
671         spin_lock(&sr_index_lock);
672         minor = find_first_zero_bit(sr_index_bits, SR_DISKS);
673         if (minor == SR_DISKS) {
674                 spin_unlock(&sr_index_lock);
675                 error = -EBUSY;
676                 goto fail_put;
677         }
678         __set_bit(minor, sr_index_bits);
679         spin_unlock(&sr_index_lock);
680
681         disk->major = SCSI_CDROM_MAJOR;
682         disk->first_minor = minor;
683         disk->minors = 1;
684         sprintf(disk->disk_name, "sr%d", minor);
685         disk->fops = &sr_bdops;
686         disk->flags |= GENHD_FL_REMOVABLE | GENHD_FL_NO_PART;
687         disk->events = DISK_EVENT_MEDIA_CHANGE | DISK_EVENT_EJECT_REQUEST;
688         disk->event_flags = DISK_EVENT_FLAG_POLL | DISK_EVENT_FLAG_UEVENT |
689                                 DISK_EVENT_FLAG_BLOCK_ON_EXCL_WRITE;
690
691         blk_queue_rq_timeout(sdev->request_queue, SR_TIMEOUT);
692
693         cd->device = sdev;
694         cd->disk = disk;
695         cd->driver = &sr_template;
696         cd->capacity = 0x1fffff;
697         cd->device->changed = 1;        /* force recheck CD type */
698         cd->media_present = 1;
699         cd->use = 1;
700         cd->readcd_known = 0;
701         cd->readcd_cdda = 0;
702
703         cd->cdi.ops = &sr_dops;
704         cd->cdi.handle = cd;
705         cd->cdi.mask = 0;
706         cd->cdi.capacity = 1;
707         sprintf(cd->cdi.name, "sr%d", minor);
708
709         sdev->sector_size = 2048;       /* A guess, just in case */
710
711         /* FIXME: need to handle a get_capabilities failure properly ?? */
712         get_capabilities(cd);
713         sr_vendor_init(cd);
714
715         set_capacity(disk, cd->capacity);
716         disk->private_data = &cd->driver;
717
718         if (register_cdrom(disk, &cd->cdi))
719                 goto fail_minor;
720
721         /*
722          * Initialize block layer runtime PM stuffs before the
723          * periodic event checking request gets started in add_disk.
724          */
725         blk_pm_runtime_init(sdev->request_queue, dev);
726
727         dev_set_drvdata(dev, cd);
728         sr_revalidate_disk(cd);
729
730         error = device_add_disk(&sdev->sdev_gendev, disk, NULL);
731         if (error) {
732                 kref_put(&cd->kref, sr_kref_release);
733                 goto fail;
734         }
735
736         sdev_printk(KERN_DEBUG, sdev,
737                     "Attached scsi CD-ROM %s\n", cd->cdi.name);
738         scsi_autopm_put_device(cd->device);
739
740         return 0;
741
742 fail_minor:
743         spin_lock(&sr_index_lock);
744         clear_bit(minor, sr_index_bits);
745         spin_unlock(&sr_index_lock);
746 fail_put:
747         put_disk(disk);
748         mutex_destroy(&cd->lock);
749 fail_free:
750         kfree(cd);
751 fail:
752         scsi_autopm_put_device(sdev);
753         return error;
754 }
755
756
757 static void get_sectorsize(struct scsi_cd *cd)
758 {
759         unsigned char cmd[10];
760         unsigned char buffer[8];
761         int the_result, retries = 3;
762         int sector_size;
763         struct request_queue *queue;
764
765         do {
766                 cmd[0] = READ_CAPACITY;
767                 memset((void *) &cmd[1], 0, 9);
768                 memset(buffer, 0, sizeof(buffer));
769
770                 /* Do the command and wait.. */
771                 the_result = scsi_execute_req(cd->device, cmd, DMA_FROM_DEVICE,
772                                               buffer, sizeof(buffer), NULL,
773                                               SR_TIMEOUT, MAX_RETRIES, NULL);
774
775                 retries--;
776
777         } while (the_result && retries);
778
779
780         if (the_result) {
781                 cd->capacity = 0x1fffff;
782                 sector_size = 2048;     /* A guess, just in case */
783         } else {
784                 long last_written;
785
786                 cd->capacity = 1 + get_unaligned_be32(&buffer[0]);
787                 /*
788                  * READ_CAPACITY doesn't return the correct size on
789                  * certain UDF media.  If last_written is larger, use
790                  * it instead.
791                  *
792                  * http://bugzilla.kernel.org/show_bug.cgi?id=9668
793                  */
794                 if (!cdrom_get_last_written(&cd->cdi, &last_written))
795                         cd->capacity = max_t(long, cd->capacity, last_written);
796
797                 sector_size = get_unaligned_be32(&buffer[4]);
798                 switch (sector_size) {
799                         /*
800                          * HP 4020i CD-Recorder reports 2340 byte sectors
801                          * Philips CD-Writers report 2352 byte sectors
802                          *
803                          * Use 2k sectors for them..
804                          */
805                 case 0:
806                 case 2340:
807                 case 2352:
808                         sector_size = 2048;
809                         fallthrough;
810                 case 2048:
811                         cd->capacity *= 4;
812                         fallthrough;
813                 case 512:
814                         break;
815                 default:
816                         sr_printk(KERN_INFO, cd,
817                                   "unsupported sector size %d.", sector_size);
818                         cd->capacity = 0;
819                 }
820
821                 cd->device->sector_size = sector_size;
822
823                 /*
824                  * Add this so that we have the ability to correctly gauge
825                  * what the device is capable of.
826                  */
827                 set_capacity(cd->disk, cd->capacity);
828         }
829
830         queue = cd->device->request_queue;
831         blk_queue_logical_block_size(queue, sector_size);
832
833         return;
834 }
835
836 static void get_capabilities(struct scsi_cd *cd)
837 {
838         unsigned char *buffer;
839         struct scsi_mode_data data;
840         struct scsi_sense_hdr sshdr;
841         unsigned int ms_len = 128;
842         int rc, n;
843
844         static const char *loadmech[] =
845         {
846                 "caddy",
847                 "tray",
848                 "pop-up",
849                 "",
850                 "changer",
851                 "cartridge changer",
852                 "",
853                 ""
854         };
855
856
857         /* allocate transfer buffer */
858         buffer = kmalloc(512, GFP_KERNEL);
859         if (!buffer) {
860                 sr_printk(KERN_ERR, cd, "out of memory.\n");
861                 return;
862         }
863
864         /* eat unit attentions */
865         scsi_test_unit_ready(cd->device, SR_TIMEOUT, MAX_RETRIES, &sshdr);
866
867         /* ask for mode page 0x2a */
868         rc = scsi_mode_sense(cd->device, 0, 0x2a, buffer, ms_len,
869                              SR_TIMEOUT, 3, &data, NULL);
870
871         if (rc < 0 || data.length > ms_len ||
872             data.header_length + data.block_descriptor_length > data.length) {
873                 /* failed, drive doesn't have capabilities mode page */
874                 cd->cdi.speed = 1;
875                 cd->cdi.mask |= (CDC_CD_R | CDC_CD_RW | CDC_DVD_R |
876                                  CDC_DVD | CDC_DVD_RAM |
877                                  CDC_SELECT_DISC | CDC_SELECT_SPEED |
878                                  CDC_MRW | CDC_MRW_W | CDC_RAM);
879                 kfree(buffer);
880                 sr_printk(KERN_INFO, cd, "scsi-1 drive");
881                 return;
882         }
883
884         n = data.header_length + data.block_descriptor_length;
885         cd->cdi.speed = get_unaligned_be16(&buffer[n + 8]) / 176;
886         cd->readcd_known = 1;
887         cd->readcd_cdda = buffer[n + 5] & 0x01;
888         /* print some capability bits */
889         sr_printk(KERN_INFO, cd,
890                   "scsi3-mmc drive: %dx/%dx %s%s%s%s%s%s\n",
891                   get_unaligned_be16(&buffer[n + 14]) / 176,
892                   cd->cdi.speed,
893                   buffer[n + 3] & 0x01 ? "writer " : "", /* CD Writer */
894                   buffer[n + 3] & 0x20 ? "dvd-ram " : "",
895                   buffer[n + 2] & 0x02 ? "cd/rw " : "", /* can read rewriteable */
896                   buffer[n + 4] & 0x20 ? "xa/form2 " : "",      /* can read xa/from2 */
897                   buffer[n + 5] & 0x01 ? "cdda " : "", /* can read audio data */
898                   loadmech[buffer[n + 6] >> 5]);
899         if ((buffer[n + 6] >> 5) == 0)
900                 /* caddy drives can't close tray... */
901                 cd->cdi.mask |= CDC_CLOSE_TRAY;
902         if ((buffer[n + 2] & 0x8) == 0)
903                 /* not a DVD drive */
904                 cd->cdi.mask |= CDC_DVD;
905         if ((buffer[n + 3] & 0x20) == 0)
906                 /* can't write DVD-RAM media */
907                 cd->cdi.mask |= CDC_DVD_RAM;
908         if ((buffer[n + 3] & 0x10) == 0)
909                 /* can't write DVD-R media */
910                 cd->cdi.mask |= CDC_DVD_R;
911         if ((buffer[n + 3] & 0x2) == 0)
912                 /* can't write CD-RW media */
913                 cd->cdi.mask |= CDC_CD_RW;
914         if ((buffer[n + 3] & 0x1) == 0)
915                 /* can't write CD-R media */
916                 cd->cdi.mask |= CDC_CD_R;
917         if ((buffer[n + 6] & 0x8) == 0)
918                 /* can't eject */
919                 cd->cdi.mask |= CDC_OPEN_TRAY;
920
921         if ((buffer[n + 6] >> 5) == mechtype_individual_changer ||
922             (buffer[n + 6] >> 5) == mechtype_cartridge_changer)
923                 cd->cdi.capacity =
924                     cdrom_number_of_slots(&cd->cdi);
925         if (cd->cdi.capacity <= 1)
926                 /* not a changer */
927                 cd->cdi.mask |= CDC_SELECT_DISC;
928         /*else    I don't think it can close its tray
929                 cd->cdi.mask |= CDC_CLOSE_TRAY; */
930
931         /*
932          * if DVD-RAM, MRW-W or CD-RW, we are randomly writable
933          */
934         if ((cd->cdi.mask & (CDC_DVD_RAM | CDC_MRW_W | CDC_RAM | CDC_CD_RW)) !=
935                         (CDC_DVD_RAM | CDC_MRW_W | CDC_RAM | CDC_CD_RW)) {
936                 cd->writeable = 1;
937         }
938
939         kfree(buffer);
940 }
941
942 /*
943  * sr_packet() is the entry point for the generic commands generated
944  * by the Uniform CD-ROM layer.
945  */
946 static int sr_packet(struct cdrom_device_info *cdi,
947                 struct packet_command *cgc)
948 {
949         struct scsi_cd *cd = cdi->handle;
950         struct scsi_device *sdev = cd->device;
951
952         if (cgc->cmd[0] == GPCMD_READ_DISC_INFO && sdev->no_read_disc_info)
953                 return -EDRIVE_CANT_DO_THIS;
954
955         if (cgc->timeout <= 0)
956                 cgc->timeout = IOCTL_TIMEOUT;
957
958         sr_do_ioctl(cd, cgc);
959
960         return cgc->stat;
961 }
962
963 static int sr_read_cdda_bpc(struct cdrom_device_info *cdi, void __user *ubuf,
964                 u32 lba, u32 nr, u8 *last_sense)
965 {
966         struct gendisk *disk = cdi->disk;
967         u32 len = nr * CD_FRAMESIZE_RAW;
968         struct scsi_request *req;
969         struct request *rq;
970         struct bio *bio;
971         int ret;
972
973         rq = scsi_alloc_request(disk->queue, REQ_OP_DRV_IN, 0);
974         if (IS_ERR(rq))
975                 return PTR_ERR(rq);
976         req = scsi_req(rq);
977
978         ret = blk_rq_map_user(disk->queue, rq, NULL, ubuf, len, GFP_KERNEL);
979         if (ret)
980                 goto out_put_request;
981
982         req->cmd[0] = GPCMD_READ_CD;
983         req->cmd[1] = 1 << 2;
984         req->cmd[2] = (lba >> 24) & 0xff;
985         req->cmd[3] = (lba >> 16) & 0xff;
986         req->cmd[4] = (lba >>  8) & 0xff;
987         req->cmd[5] = lba & 0xff;
988         req->cmd[6] = (nr >> 16) & 0xff;
989         req->cmd[7] = (nr >>  8) & 0xff;
990         req->cmd[8] = nr & 0xff;
991         req->cmd[9] = 0xf8;
992         req->cmd_len = 12;
993         rq->timeout = 60 * HZ;
994         bio = rq->bio;
995
996         blk_execute_rq(rq, false);
997         if (scsi_req(rq)->result) {
998                 struct scsi_sense_hdr sshdr;
999
1000                 scsi_normalize_sense(req->sense, req->sense_len,
1001                                      &sshdr);
1002                 *last_sense = sshdr.sense_key;
1003                 ret = -EIO;
1004         }
1005
1006         if (blk_rq_unmap_user(bio))
1007                 ret = -EFAULT;
1008 out_put_request:
1009         blk_mq_free_request(rq);
1010         return ret;
1011 }
1012
1013
1014 /**
1015  *      sr_kref_release - Called to free the scsi_cd structure
1016  *      @kref: pointer to embedded kref
1017  *
1018  *      sr_ref_mutex must be held entering this routine.  Because it is
1019  *      called on last put, you should always use the scsi_cd_get()
1020  *      scsi_cd_put() helpers which manipulate the semaphore directly
1021  *      and never do a direct kref_put().
1022  **/
1023 static void sr_kref_release(struct kref *kref)
1024 {
1025         struct scsi_cd *cd = container_of(kref, struct scsi_cd, kref);
1026         struct gendisk *disk = cd->disk;
1027
1028         spin_lock(&sr_index_lock);
1029         clear_bit(MINOR(disk_devt(disk)), sr_index_bits);
1030         spin_unlock(&sr_index_lock);
1031
1032         unregister_cdrom(&cd->cdi);
1033
1034         disk->private_data = NULL;
1035
1036         put_disk(disk);
1037
1038         mutex_destroy(&cd->lock);
1039
1040         kfree(cd);
1041 }
1042
1043 static int sr_remove(struct device *dev)
1044 {
1045         struct scsi_cd *cd = dev_get_drvdata(dev);
1046
1047         scsi_autopm_get_device(cd->device);
1048
1049         del_gendisk(cd->disk);
1050         dev_set_drvdata(dev, NULL);
1051
1052         mutex_lock(&sr_ref_mutex);
1053         kref_put(&cd->kref, sr_kref_release);
1054         mutex_unlock(&sr_ref_mutex);
1055
1056         return 0;
1057 }
1058
1059 static int __init init_sr(void)
1060 {
1061         int rc;
1062
1063         rc = register_blkdev(SCSI_CDROM_MAJOR, "sr");
1064         if (rc)
1065                 return rc;
1066         rc = scsi_register_driver(&sr_template.gendrv);
1067         if (rc)
1068                 unregister_blkdev(SCSI_CDROM_MAJOR, "sr");
1069
1070         return rc;
1071 }
1072
1073 static void __exit exit_sr(void)
1074 {
1075         scsi_unregister_driver(&sr_template.gendrv);
1076         unregister_blkdev(SCSI_CDROM_MAJOR, "sr");
1077 }
1078
1079 module_init(init_sr);
1080 module_exit(exit_sr);
1081 MODULE_LICENSE("GPL");