xref: /openbmc/linux/drivers/scsi/sr.c (revision 83946783)
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->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 
731 	error = device_add_disk(&sdev->sdev_gendev, disk, NULL);
732 	if (error) {
733 		kref_put(&cd->kref, sr_kref_release);
734 		goto fail;
735 	}
736 
737 	sdev_printk(KERN_DEBUG, sdev,
738 		    "Attached scsi CD-ROM %s\n", cd->cdi.name);
739 	scsi_autopm_put_device(cd->device);
740 
741 	return 0;
742 
743 fail_minor:
744 	spin_lock(&sr_index_lock);
745 	clear_bit(minor, sr_index_bits);
746 	spin_unlock(&sr_index_lock);
747 fail_put:
748 	put_disk(disk);
749 	mutex_destroy(&cd->lock);
750 fail_free:
751 	kfree(cd);
752 fail:
753 	scsi_autopm_put_device(sdev);
754 	return error;
755 }
756 
757 
758 static void get_sectorsize(struct scsi_cd *cd)
759 {
760 	unsigned char cmd[10];
761 	unsigned char buffer[8];
762 	int the_result, retries = 3;
763 	int sector_size;
764 	struct request_queue *queue;
765 
766 	do {
767 		cmd[0] = READ_CAPACITY;
768 		memset((void *) &cmd[1], 0, 9);
769 		memset(buffer, 0, sizeof(buffer));
770 
771 		/* Do the command and wait.. */
772 		the_result = scsi_execute_req(cd->device, cmd, DMA_FROM_DEVICE,
773 					      buffer, sizeof(buffer), NULL,
774 					      SR_TIMEOUT, MAX_RETRIES, NULL);
775 
776 		retries--;
777 
778 	} while (the_result && retries);
779 
780 
781 	if (the_result) {
782 		cd->capacity = 0x1fffff;
783 		sector_size = 2048;	/* A guess, just in case */
784 	} else {
785 		long last_written;
786 
787 		cd->capacity = 1 + get_unaligned_be32(&buffer[0]);
788 		/*
789 		 * READ_CAPACITY doesn't return the correct size on
790 		 * certain UDF media.  If last_written is larger, use
791 		 * it instead.
792 		 *
793 		 * http://bugzilla.kernel.org/show_bug.cgi?id=9668
794 		 */
795 		if (!cdrom_get_last_written(&cd->cdi, &last_written))
796 			cd->capacity = max_t(long, cd->capacity, last_written);
797 
798 		sector_size = get_unaligned_be32(&buffer[4]);
799 		switch (sector_size) {
800 			/*
801 			 * HP 4020i CD-Recorder reports 2340 byte sectors
802 			 * Philips CD-Writers report 2352 byte sectors
803 			 *
804 			 * Use 2k sectors for them..
805 			 */
806 		case 0:
807 		case 2340:
808 		case 2352:
809 			sector_size = 2048;
810 			fallthrough;
811 		case 2048:
812 			cd->capacity *= 4;
813 			fallthrough;
814 		case 512:
815 			break;
816 		default:
817 			sr_printk(KERN_INFO, cd,
818 				  "unsupported sector size %d.", sector_size);
819 			cd->capacity = 0;
820 		}
821 
822 		cd->device->sector_size = sector_size;
823 
824 		/*
825 		 * Add this so that we have the ability to correctly gauge
826 		 * what the device is capable of.
827 		 */
828 		set_capacity(cd->disk, cd->capacity);
829 	}
830 
831 	queue = cd->device->request_queue;
832 	blk_queue_logical_block_size(queue, sector_size);
833 
834 	return;
835 }
836 
837 static void get_capabilities(struct scsi_cd *cd)
838 {
839 	unsigned char *buffer;
840 	struct scsi_mode_data data;
841 	struct scsi_sense_hdr sshdr;
842 	unsigned int ms_len = 128;
843 	int rc, n;
844 
845 	static const char *loadmech[] =
846 	{
847 		"caddy",
848 		"tray",
849 		"pop-up",
850 		"",
851 		"changer",
852 		"cartridge changer",
853 		"",
854 		""
855 	};
856 
857 
858 	/* allocate transfer buffer */
859 	buffer = kmalloc(512, GFP_KERNEL | GFP_DMA);
860 	if (!buffer) {
861 		sr_printk(KERN_ERR, cd, "out of memory.\n");
862 		return;
863 	}
864 
865 	/* eat unit attentions */
866 	scsi_test_unit_ready(cd->device, SR_TIMEOUT, MAX_RETRIES, &sshdr);
867 
868 	/* ask for mode page 0x2a */
869 	rc = scsi_mode_sense(cd->device, 0, 0x2a, buffer, ms_len,
870 			     SR_TIMEOUT, 3, &data, NULL);
871 
872 	if (rc < 0 || data.length > ms_len ||
873 	    data.header_length + data.block_descriptor_length > data.length) {
874 		/* failed, drive doesn't have capabilities mode page */
875 		cd->cdi.speed = 1;
876 		cd->cdi.mask |= (CDC_CD_R | CDC_CD_RW | CDC_DVD_R |
877 				 CDC_DVD | CDC_DVD_RAM |
878 				 CDC_SELECT_DISC | CDC_SELECT_SPEED |
879 				 CDC_MRW | CDC_MRW_W | CDC_RAM);
880 		kfree(buffer);
881 		sr_printk(KERN_INFO, cd, "scsi-1 drive");
882 		return;
883 	}
884 
885 	n = data.header_length + data.block_descriptor_length;
886 	cd->cdi.speed = get_unaligned_be16(&buffer[n + 8]) / 176;
887 	cd->readcd_known = 1;
888 	cd->readcd_cdda = buffer[n + 5] & 0x01;
889 	/* print some capability bits */
890 	sr_printk(KERN_INFO, cd,
891 		  "scsi3-mmc drive: %dx/%dx %s%s%s%s%s%s\n",
892 		  get_unaligned_be16(&buffer[n + 14]) / 176,
893 		  cd->cdi.speed,
894 		  buffer[n + 3] & 0x01 ? "writer " : "", /* CD Writer */
895 		  buffer[n + 3] & 0x20 ? "dvd-ram " : "",
896 		  buffer[n + 2] & 0x02 ? "cd/rw " : "", /* can read rewriteable */
897 		  buffer[n + 4] & 0x20 ? "xa/form2 " : "",	/* can read xa/from2 */
898 		  buffer[n + 5] & 0x01 ? "cdda " : "", /* can read audio data */
899 		  loadmech[buffer[n + 6] >> 5]);
900 	if ((buffer[n + 6] >> 5) == 0)
901 		/* caddy drives can't close tray... */
902 		cd->cdi.mask |= CDC_CLOSE_TRAY;
903 	if ((buffer[n + 2] & 0x8) == 0)
904 		/* not a DVD drive */
905 		cd->cdi.mask |= CDC_DVD;
906 	if ((buffer[n + 3] & 0x20) == 0)
907 		/* can't write DVD-RAM media */
908 		cd->cdi.mask |= CDC_DVD_RAM;
909 	if ((buffer[n + 3] & 0x10) == 0)
910 		/* can't write DVD-R media */
911 		cd->cdi.mask |= CDC_DVD_R;
912 	if ((buffer[n + 3] & 0x2) == 0)
913 		/* can't write CD-RW media */
914 		cd->cdi.mask |= CDC_CD_RW;
915 	if ((buffer[n + 3] & 0x1) == 0)
916 		/* can't write CD-R media */
917 		cd->cdi.mask |= CDC_CD_R;
918 	if ((buffer[n + 6] & 0x8) == 0)
919 		/* can't eject */
920 		cd->cdi.mask |= CDC_OPEN_TRAY;
921 
922 	if ((buffer[n + 6] >> 5) == mechtype_individual_changer ||
923 	    (buffer[n + 6] >> 5) == mechtype_cartridge_changer)
924 		cd->cdi.capacity =
925 		    cdrom_number_of_slots(&cd->cdi);
926 	if (cd->cdi.capacity <= 1)
927 		/* not a changer */
928 		cd->cdi.mask |= CDC_SELECT_DISC;
929 	/*else    I don't think it can close its tray
930 		cd->cdi.mask |= CDC_CLOSE_TRAY; */
931 
932 	/*
933 	 * if DVD-RAM, MRW-W or CD-RW, we are randomly writable
934 	 */
935 	if ((cd->cdi.mask & (CDC_DVD_RAM | CDC_MRW_W | CDC_RAM | CDC_CD_RW)) !=
936 			(CDC_DVD_RAM | CDC_MRW_W | CDC_RAM | CDC_CD_RW)) {
937 		cd->writeable = 1;
938 	}
939 
940 	kfree(buffer);
941 }
942 
943 /*
944  * sr_packet() is the entry point for the generic commands generated
945  * by the Uniform CD-ROM layer.
946  */
947 static int sr_packet(struct cdrom_device_info *cdi,
948 		struct packet_command *cgc)
949 {
950 	struct scsi_cd *cd = cdi->handle;
951 	struct scsi_device *sdev = cd->device;
952 
953 	if (cgc->cmd[0] == GPCMD_READ_DISC_INFO && sdev->no_read_disc_info)
954 		return -EDRIVE_CANT_DO_THIS;
955 
956 	if (cgc->timeout <= 0)
957 		cgc->timeout = IOCTL_TIMEOUT;
958 
959 	sr_do_ioctl(cd, cgc);
960 
961 	return cgc->stat;
962 }
963 
964 static int sr_read_cdda_bpc(struct cdrom_device_info *cdi, void __user *ubuf,
965 		u32 lba, u32 nr, u8 *last_sense)
966 {
967 	struct gendisk *disk = cdi->disk;
968 	u32 len = nr * CD_FRAMESIZE_RAW;
969 	struct scsi_request *req;
970 	struct request *rq;
971 	struct bio *bio;
972 	int ret;
973 
974 	rq = scsi_alloc_request(disk->queue, REQ_OP_DRV_IN, 0);
975 	if (IS_ERR(rq))
976 		return PTR_ERR(rq);
977 	req = scsi_req(rq);
978 
979 	ret = blk_rq_map_user(disk->queue, rq, NULL, ubuf, len, GFP_KERNEL);
980 	if (ret)
981 		goto out_put_request;
982 
983 	req->cmd[0] = GPCMD_READ_CD;
984 	req->cmd[1] = 1 << 2;
985 	req->cmd[2] = (lba >> 24) & 0xff;
986 	req->cmd[3] = (lba >> 16) & 0xff;
987 	req->cmd[4] = (lba >>  8) & 0xff;
988 	req->cmd[5] = lba & 0xff;
989 	req->cmd[6] = (nr >> 16) & 0xff;
990 	req->cmd[7] = (nr >>  8) & 0xff;
991 	req->cmd[8] = nr & 0xff;
992 	req->cmd[9] = 0xf8;
993 	req->cmd_len = 12;
994 	rq->timeout = 60 * HZ;
995 	bio = rq->bio;
996 
997 	blk_execute_rq(disk, rq, 0);
998 	if (scsi_req(rq)->result) {
999 		struct scsi_sense_hdr sshdr;
1000 
1001 		scsi_normalize_sense(req->sense, req->sense_len,
1002 				     &sshdr);
1003 		*last_sense = sshdr.sense_key;
1004 		ret = -EIO;
1005 	}
1006 
1007 	if (blk_rq_unmap_user(bio))
1008 		ret = -EFAULT;
1009 out_put_request:
1010 	blk_mq_free_request(rq);
1011 	return ret;
1012 }
1013 
1014 
1015 /**
1016  *	sr_kref_release - Called to free the scsi_cd structure
1017  *	@kref: pointer to embedded kref
1018  *
1019  *	sr_ref_mutex must be held entering this routine.  Because it is
1020  *	called on last put, you should always use the scsi_cd_get()
1021  *	scsi_cd_put() helpers which manipulate the semaphore directly
1022  *	and never do a direct kref_put().
1023  **/
1024 static void sr_kref_release(struct kref *kref)
1025 {
1026 	struct scsi_cd *cd = container_of(kref, struct scsi_cd, kref);
1027 	struct gendisk *disk = cd->disk;
1028 
1029 	spin_lock(&sr_index_lock);
1030 	clear_bit(MINOR(disk_devt(disk)), sr_index_bits);
1031 	spin_unlock(&sr_index_lock);
1032 
1033 	unregister_cdrom(&cd->cdi);
1034 
1035 	disk->private_data = NULL;
1036 
1037 	put_disk(disk);
1038 
1039 	mutex_destroy(&cd->lock);
1040 
1041 	kfree(cd);
1042 }
1043 
1044 static int sr_remove(struct device *dev)
1045 {
1046 	struct scsi_cd *cd = dev_get_drvdata(dev);
1047 
1048 	scsi_autopm_get_device(cd->device);
1049 
1050 	del_gendisk(cd->disk);
1051 	dev_set_drvdata(dev, NULL);
1052 
1053 	mutex_lock(&sr_ref_mutex);
1054 	kref_put(&cd->kref, sr_kref_release);
1055 	mutex_unlock(&sr_ref_mutex);
1056 
1057 	return 0;
1058 }
1059 
1060 static int __init init_sr(void)
1061 {
1062 	int rc;
1063 
1064 	rc = register_blkdev(SCSI_CDROM_MAJOR, "sr");
1065 	if (rc)
1066 		return rc;
1067 	rc = scsi_register_driver(&sr_template.gendrv);
1068 	if (rc)
1069 		unregister_blkdev(SCSI_CDROM_MAJOR, "sr");
1070 
1071 	return rc;
1072 }
1073 
1074 static void __exit exit_sr(void)
1075 {
1076 	scsi_unregister_driver(&sr_template.gendrv);
1077 	unregister_blkdev(SCSI_CDROM_MAJOR, "sr");
1078 }
1079 
1080 module_init(init_sr);
1081 module_exit(exit_sr);
1082 MODULE_LICENSE("GPL");
1083