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