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