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