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