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