xref: /illumos-gate/usr/src/cmd/cdrw/misc_scsi.c (revision 6dfee4834394825da35b977ca71cdc965bc7b6a4)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License, Version 1.0 only
6  * (the "License").  You may not use this file except in compliance
7  * with the License.
8  *
9  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
10  * or http://www.opensolaris.org/os/licensing.
11  * See the License for the specific language governing permissions
12  * and limitations under the License.
13  *
14  * When distributing Covered Code, include this CDDL HEADER in each
15  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
16  * If applicable, add the following below this CDDL HEADER, with the
17  * fields enclosed by brackets "[]" replaced with your own identifying
18  * information: Portions Copyright [yyyy] [name of copyright owner]
19  *
20  * CDDL HEADER END
21  */
22 /*
23  * Copyright 2005 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 
27 #pragma ident	"%Z%%M%	%I%	%E% SMI"
28 
29 #include <sys/types.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <stdio.h>
33 #include <sys/dkio.h>
34 #include <unistd.h>
35 #include <errno.h>
36 #include <libintl.h>
37 #include <sys/time.h>
38 
39 #include "mmc.h"
40 #include "util.h"
41 #include "misc_scsi.h"
42 #include "transport.h"
43 #include "main.h"
44 #include "toshiba.h"
45 #include "msgs.h"
46 #include "device.h"
47 
48 uint32_t
49 read_scsi32(void *addr)
50 {
51 	uchar_t *ad = (uchar_t *)addr;
52 	uint32_t ret;
53 
54 	ret = ((((uint32_t)ad[0]) << 24) | (((uint32_t)ad[1]) << 16) |
55 	    (((uint32_t)ad[2]) << 8) | ad[3]);
56 	return (ret);
57 }
58 
59 uint16_t
60 read_scsi16(void *addr)
61 {
62 	uchar_t *ad = (uchar_t *)addr;
63 	uint16_t ret;
64 
65 	ret = ((((uint16_t)ad[0]) << 8) | ad[1]);
66 	return (ret);
67 }
68 
69 void
70 load_scsi32(void *addr, uint32_t v)
71 {
72 	uchar_t *ad = (uchar_t *)addr;
73 
74 	ad[0] = (uchar_t)(v >> 24);
75 	ad[1] = (uchar_t)(v >> 16);
76 	ad[2] = (uchar_t)(v >> 8);
77 	ad[3] = (uchar_t)v;
78 }
79 
80 void
81 load_scsi16(void *addr, uint16_t v)
82 {
83 	uchar_t *ad = (uchar_t *)addr;
84 	ad[0] = (uchar_t)(v >> 8);
85 	ad[1] = (uchar_t)v;
86 }
87 /*
88  * will get the mode page only i.e. will strip off the header.
89  */
90 int
91 get_mode_page(int fd, int page_no, int pc, int buf_len, uchar_t *buffer)
92 {
93 	int ret;
94 	uchar_t byte2, *buf;
95 	uint_t header_len, page_len, copy_cnt;
96 
97 	byte2 = (uchar_t)(((pc << 6) & 0xC0) | (page_no & 0x3f));
98 	buf = (uchar_t *)my_zalloc(256);
99 
100 	/* Ask 254 bytes only to make our IDE driver happy */
101 	ret = mode_sense(fd, byte2, 1, 254, buf);
102 	if (ret == 0) {
103 		free(buf);
104 		return (0);
105 	}
106 
107 	header_len = 8 + read_scsi16(&buf[6]);
108 	page_len = buf[header_len + 1] + 2;
109 
110 	copy_cnt = (page_len > buf_len) ? buf_len : page_len;
111 	(void) memcpy(buffer, &buf[header_len], copy_cnt);
112 	free(buf);
113 
114 	return (1);
115 }
116 
117 /*
118  * will take care of adding mode header and any extra bytes at the end.
119  */
120 int
121 set_mode_page(int fd, uchar_t *buffer)
122 {
123 	int ret;
124 	uchar_t *buf;
125 	uint_t total, p_len;
126 
127 	p_len = buffer[1] + 2;
128 	total = p_len + 8;
129 	buf = (uchar_t *)my_zalloc(total);
130 
131 	(void) memcpy(&buf[8], buffer, p_len);
132 	if (debug) {
133 		int i;
134 
135 		(void) printf("MODE: [");
136 		for (i = 0; i < p_len; i++) {
137 			(void) printf("0x%02x ", (uchar_t)buffer[i]);
138 		}
139 
140 		(void) printf("]\n");
141 	}
142 	ret = mode_select(fd, total, buf);
143 	free(buf);
144 
145 	return (ret);
146 }
147 
148 /*
149  * Builds track information database for track trackno. If trackno is
150  * -1, builds the database for next blank track.
151  */
152 int
153 build_track_info(cd_device *dev, int trackno, struct track_info *t_info)
154 {
155 	uchar_t *ti;
156 	uchar_t toc[20];		/* 2 entries + 4 byte header */
157 	int ret;
158 
159 	(void) memset(t_info, 0, sizeof (*t_info));
160 	/* 1st try READ TRACK INFORMATION */
161 	ti = (uchar_t *)my_zalloc(TRACK_INFO_SIZE);
162 	t_info->ti_track_no = trackno;
163 
164 	/* Gererate faked information for writing to DVD */
165 	if (device_type != CD_RW) {
166 		uint_t bsize;
167 
168 		t_info->ti_flags = 0x3000;
169 		t_info->ti_track_no = 1;
170 		t_info->ti_session_no = 1;
171 		t_info->ti_track_mode = 0x4;
172 		t_info->ti_data_mode = 1;
173 		t_info->ti_start_address = 0;
174 
175 		/* only 1 track on DVD make it max size */
176 		t_info->ti_track_size = read_format_capacity(target->d_fd,
177 		    &bsize);
178 		if (t_info->ti_track_size < MAX_CD_BLKS) {
179 			t_info->ti_track_size = MAX_DVD_BLKS;
180 		}
181 
182 		t_info->ti_nwa = 0;
183 		t_info->ti_lra = 0;
184 		t_info->ti_packet_size = 0x10;
185 		t_info->ti_free_blocks = 0;
186 	}
187 
188 	if (read_track_info(dev->d_fd, trackno, ti)) {
189 
190 		if (debug)
191 			(void) printf("using read_track_info for TOC \n");
192 
193 		t_info->ti_track_no = ti[2];
194 		t_info->ti_session_no = ti[3];
195 		t_info->ti_flags = (ti[6] >> 4) & 0xf;
196 		t_info->ti_flags |= (uint32_t)(ti[5] & 0xf0);
197 		t_info->ti_flags |= (uint32_t)(ti[7]) << 8;
198 		t_info->ti_flags |= TI_SESSION_NO_VALID | TI_FREE_BLOCKS_VALID;
199 		t_info->ti_track_mode = ti[5] & 0xf;
200 		if ((ti[6] & 0xf) == 0xf)
201 			t_info->ti_data_mode = 0xff;
202 		else
203 			t_info->ti_data_mode = ti[6] & 0xf;
204 		t_info->ti_start_address = read_scsi32(&ti[8]);
205 		t_info->ti_nwa = read_scsi32(&ti[12]);
206 		t_info->ti_free_blocks = read_scsi32(&ti[16]);
207 		t_info->ti_packet_size = read_scsi32(&ti[20]);
208 		t_info->ti_track_size = read_scsi32(&ti[24]);
209 		t_info->ti_lra = read_scsi32(&ti[28]);
210 		free(ti);
211 		return (1);
212 	}
213 	/* READ TRACK INFORMATION not supported, try other options */
214 	free(ti);
215 	/*
216 	 * We can get info for next blank track if READ TRACK INFO is not
217 	 * supported.
218 	 */
219 	if (trackno == -1)
220 		return (0);
221 
222 	if (debug)
223 		(void) printf("using READ_TOC for TOC\n");
224 
225 	/* Try Read TOC */
226 	if (!read_toc(dev->d_fd, 0, trackno, 20, toc)) {
227 		return (0);
228 	}
229 	t_info->ti_start_address = read_scsi32(&toc[8]);
230 	t_info->ti_track_mode = toc[5] & 0xf;
231 	t_info->ti_track_size = read_scsi32(&toc[16]) - read_scsi32(&toc[8]);
232 	t_info->ti_data_mode = get_data_mode(dev->d_fd, read_scsi32(&toc[8]));
233 
234 	/* Numbers for audio tracks are always in 2K chunks */
235 	if ((dev->d_blksize == 512) && ((t_info->ti_track_mode & 4) == 0)) {
236 		t_info->ti_start_address /= 4;
237 		t_info->ti_track_size /= 4;
238 	}
239 
240 	/* Now find out the session thing */
241 	ret = read_toc(dev->d_fd, 1, trackno, 12, toc);
242 
243 	/*
244 	 * Make sure that the call succeeds and returns the requested
245 	 * TOC size correctly.
246 	 */
247 
248 	if ((ret == 0) || (toc[1] != 0x0a)) {
249 
250 		/* For ATAPI drives or old Toshiba drives */
251 		ret = read_toc_as_per_8020(dev->d_fd, 1, trackno, 12, toc);
252 	}
253 	/* If this goes through well TOC length will always be 0x0a */
254 	if (ret && (toc[1] == 0x0a)) {
255 		if (trackno >= toc[6]) {
256 			t_info->ti_session_no = toc[3];
257 			t_info->ti_flags |= TI_SESSION_NO_VALID;
258 		}
259 		/*
260 		 * This might be the last track of this session. If so,
261 		 * exclude the leadout and next lead in.
262 		 */
263 		if (trackno == (toc[6] - 1)) {
264 			/*
265 			 * 1.5 Min leadout + 1 min. leadin + 2 sec. pre-gap.
266 			 * For 2nd+ leadout it will be 0.5 min. But currently
267 			 * there is no direct way. And it will not happen
268 			 * for any normal case.
269 			 *
270 			 * 75 frames/sec, 60 sec/min, so leadin gap is
271 			 * ((1.5 +1)*60 + 2)*75 = 11400 frames (blocks)
272 			 */
273 			t_info->ti_track_size -= 11400;
274 		}
275 	}
276 	return (1);
277 }
278 
279 uchar_t
280 get_data_mode(int fd, uint32_t lba)
281 {
282 	int ret;
283 	uchar_t *buf;
284 	uchar_t mode;
285 
286 	buf = (uchar_t *)my_zalloc(8);
287 	ret = read_header(fd, lba, buf);
288 	if (ret == 0)
289 		mode = 0xff;
290 	else
291 		mode = buf[0];
292 	free(buf);
293 	return (mode);
294 }
295 
296 /*
297  * Set page code 5 for TAO mode.
298  */
299 int
300 prepare_for_write(cd_device *dev, int track_mode, int test_write,
301     int keep_disc_open)
302 {
303 	uchar_t *buf;
304 	int no_err;
305 	int reset_device;
306 
307 	if ((write_mode == DAO_MODE) && keep_disc_open) {
308 		(void) printf(gettext(
309 		    "Multi-session is not supported on DVD media\n"));
310 		exit(1);
311 	}
312 
313 	if ((write_mode == DAO_MODE) && debug) {
314 		(void) printf("Preparing to write in DAO\n");
315 	}
316 
317 	(void) start_stop(dev->d_fd, 1);
318 	/* Some drives do not support this command but still do it */
319 	(void) rezero_unit(dev->d_fd);
320 
321 	buf = (uchar_t *)my_zalloc(64);
322 
323 	no_err = get_mode_page(dev->d_fd, 5, 0, 64, buf);
324 	if (no_err)
325 		no_err = ((buf[1] + 2) > 64) ? 0 : 1;
326 	/*
327 	 * If the device is already in simulation mode and again a
328 	 * simulation is requested, then set the device in non-simulation
329 	 * 1st and then take it to simulation mode. This will flush any
330 	 * previous fake state in the drive.
331 	 */
332 	if (no_err && test_write && (buf[2] & 0x10)) {
333 		reset_device = 1;
334 	} else {
335 		reset_device = 0;
336 	}
337 	if (no_err != 0) {
338 		buf[0] &= 0x3f;
339 
340 		/* set TAO or DAO writing mode */
341 		buf[2] = (write_mode == TAO_MODE)?1:2;
342 
343 		/* set simulation flag */
344 		if (test_write && (!reset_device)) {
345 			buf[2] |= 0x10;
346 		} else {
347 			buf[2] &= ~0x10;
348 		}
349 
350 		/* Turn on HW buffer underrun protection (BUFE) */
351 		if (!test_write) {
352 			buf[2] |= 0x40;
353 		}
354 
355 		/* set track mode type */
356 		if (device_type == CD_RW) {
357 			buf[3] = track_mode & 0x0f;	/* ctrl nibble */
358 		} else {
359 			buf[3] = 5;	/* always 5 for DVD */
360 		}
361 
362 		if (keep_disc_open) {
363 			buf[3] |= 0xc0;		/* Allow more sessions */
364 		}
365 
366 		/* Select track type (audio or data) */
367 		if (track_mode == TRACK_MODE_DATA) {
368 			buf[4] = 8;		/* 2048 byte sector */
369 		} else {
370 			buf[4] = 0;		/* 2352 byte sector */
371 		}
372 		buf[7] = buf[8] = 0;
373 
374 		/* Need to clear these fields for setting into DAO */
375 		if (write_mode == DAO_MODE)
376 			buf[5] = buf[15] = 0;
377 
378 		/* print out mode for detailed log */
379 		if (debug && verbose) {
380 			int i;
381 
382 			(void) printf("setting = [ ");
383 			for (i = 0; i < 15; i++)
384 				(void) printf("0x%x ", buf[i]);
385 			(void) printf("]\n");
386 		}
387 
388 		no_err = set_mode_page(dev->d_fd, buf);
389 
390 		if (no_err && reset_device) {
391 			/* Turn the test write bit back on */
392 			buf[2] |= 0x10;
393 			no_err = set_mode_page(dev->d_fd, buf);
394 		}
395 
396 		/*
397 		 * Since BUFE is the only optional flag we are
398 		 * setting we will try to turn it off if the command
399 		 * fails.
400 		 */
401 		if (!no_err) {
402 			/*
403 			 * Some old drives may not support HW
404 			 * buffer underrun protection, try again
405 			 * after turning it off.
406 			 */
407 			if (debug)
408 				(void) printf("Turning off BUFE\n");
409 			buf[2] &= ~0x40;
410 			no_err = set_mode_page(dev->d_fd, buf);
411 		}
412 	}
413 
414 	free(buf);
415 	return (no_err);
416 }
417 
418 /*
419  * Close session. This will write TOC.
420  */
421 int
422 finalize(cd_device *dev)
423 {
424 	uchar_t *di;
425 	int count, ret, err;
426 	int immediate;
427 	int finalize_max;
428 
429 	/*
430 	 * For ATAPI devices we will use the immediate mode and will
431 	 * poll the command for completion so that this command may
432 	 * not hog the channel. But for SCSI, we will use the treditional
433 	 * way of issuing the command with a large enough timeout. This
434 	 * is done because immediate mode was designed for ATAPI and some
435 	 * SCSI RW drives might not be even tested with it.
436 	 */
437 	if ((dev->d_inq[2] & 7) != 0) {
438 		/* SCSI device */
439 		immediate = 0;
440 	} else {
441 		/* non-SCSI (e.g ATAPI) device */
442 		immediate = 1;
443 	}
444 
445 	/* We need to close track before close session */
446 	if (device_type == DVD_PLUS) {
447 		if (!close_track(dev->d_fd, 0, 0, immediate))
448 			return (0);
449 	}
450 
451 	if (!close_track(dev->d_fd, 0, 1, immediate)) {
452 		/*
453 		 * For DVD-RW close track is not well defined
454 		 * some drives dont like it, others want us
455 		 * to close track before closing the session.
456 		 * NOTE that for MMC specification it is not mandatory
457 		 * to support close track.
458 		 */
459 		if (device_type == DVD_MINUS) {
460 			if (!close_track(dev->d_fd, 1, 0, immediate)) {
461 				return (0);
462 			} else {
463 				/* command is already done */
464 				if (!immediate)
465 					return (1);
466 			}
467 		} else {
468 			return (0);
469 		}
470 	} else {
471 		if (!immediate)
472 			return (1);
473 	}
474 	if (immediate) {
475 		(void) sleep(10);
476 
477 		di = (uchar_t *)my_zalloc(DISC_INFO_BLOCK_SIZE);
478 		err = 0;
479 
480 		if (device_type == CD_RW) {
481 			/* Finalization should not take more than 6 minutes */
482 			finalize_max = FINALIZE_TIMEOUT;
483 		} else {
484 			/* some DVD-RW drives take longer than 6 minutes */
485 			finalize_max = FINALIZE_TIMEOUT*2;
486 		}
487 
488 		for (count = 0; count < finalize_max; count++) {
489 			ret = read_disc_info(dev->d_fd, di);
490 			if (ret != 0)
491 				break;
492 			if (uscsi_status != 2)
493 				err = 1;
494 			if (SENSE_KEY(rqbuf) == 2) {
495 				/* not ready but not becoming ready */
496 				if (ASC(rqbuf) != 4)
497 					err = 1;
498 			} else if (SENSE_KEY(rqbuf) == 5) {
499 				/* illegal mode for this track */
500 				if (ASC(rqbuf) != 0x64)
501 					err = 1;
502 			} else {
503 				err = 1;
504 			}
505 			if (err == 1) {
506 				if (debug) {
507 					(void) printf("Finalization failed\n");
508 					(void) printf("%x %x %x %x\n",
509 					    uscsi_status, SENSE_KEY(rqbuf),
510 					    ASC(rqbuf), ASCQ(rqbuf));
511 				}
512 				free(di);
513 				return (0);
514 			}
515 			if (uscsi_status == 2) {
516 				int i;
517 				/* illegal field in command packet */
518 				if (ASC(rqbuf) == 0x24) {
519 					/* print it out! */
520 					(void) printf("\n");
521 					for (i = 0; i < 18; i++)
522 						(void) printf("%x ",
523 						    (unsigned)(rqbuf[i]));
524 					(void) printf("\n");
525 				}
526 			}
527 			(void) sleep(5);
528 		}
529 		free(di);
530 	}
531 	return (ret);
532 }
533 
534 /*
535  * Find out media capacity.
536  */
537 int
538 get_last_possible_lba(cd_device *dev)
539 {
540 	uchar_t *di;
541 	int cap;
542 
543 	di = (uchar_t *)my_zalloc(DISC_INFO_BLOCK_SIZE);
544 	if (!read_disc_info(dev->d_fd, di)) {
545 		free(di);
546 		return (0);
547 	}
548 	if ((di[21] != 0) && (di[21] != 0xff)) {
549 		cap = ((di[21] * 60) + di[22]) * 75;
550 	} else {
551 		cap = 0;
552 	}
553 
554 	free(di);
555 	return (cap);
556 }
557 
558 int
559 read_audio_through_read_cd(cd_device *dev, uint_t start_lba, uint_t nblks,
560     uchar_t *buf)
561 {
562 	int retry;
563 	int ret;
564 
565 	for (retry = 0; retry < 3; retry++) {
566 		ret = read_cd(dev->d_fd, (uint32_t)start_lba, (uint16_t)nblks,
567 		    1, buf, (uint32_t)(nblks * 2352));
568 		if (ret)
569 			break;
570 	}
571 	return (ret);
572 }
573 
574 int
575 eject_media(cd_device *dev)
576 {
577 	if (vol_running) {
578 		/* If there is a media, try using DKIOCEJECT 1st */
579 		if (check_device(dev, CHECK_NO_MEDIA) == 0) {
580 			if (ioctl(dev->d_fd, DKIOCEJECT, 0) == 0) {
581 				return (1);
582 			}
583 		}
584 	}
585 	if (load_unload(dev->d_fd, 0) == 0) {
586 		/* if eject fails */
587 		if ((uscsi_status == 2) && (ASC(rqbuf) == 0x53)) {
588 			/*
589 			 * check that eject is not blocked on the device
590 			 */
591 			if (!prevent_allow_mr(dev->d_fd, 1))
592 				return (0);
593 			return (load_unload(dev->d_fd, 0));
594 		}
595 		return (0);
596 	}
597 	return (1);
598 }
599 
600 /*
601  * Get current Read or Write Speed from Mode Page 0x2a.
602  *
603  * Use the size of the Page to determine which Multimedia Command
604  * set (MMC) is present.  Based on the MMC version, get the
605  * specified Read/Write Speed.
606  *
607  * Note that some MMC versions do not necessarily support a
608  * (current) Read or Write Speed.  As a result, this function
609  * _can_ return a value of zero.
610  *
611  * The newer standards (reserve and) mark the field(s) as Obsolete,
612  * yet many vendors populate the Obsolete fields with valid values
613  * (assumedly for backward compatibility).  This is important, as
614  * a command like GET PERFORMANCE cannot return _the_ speed; it can
615  * only return a Logical-Block-Address-dependent (LBA) speed.  Such
616  * values can vary widely between the innermost and outermost Track.
617  * Mode Page 0x2a is the best solution identifying "the current
618  * (nominal) speed".
619  */
620 static uint16_t
621 cd_speed_get(cd_device *dev, int cmd)
622 {
623 	uchar_t		*mp2a;
624 	uint16_t	rate = 0;
625 	int		offset;
626 	uint_t		buflen = 254;
627 
628 	/*
629 	 * Allocate a buffer acceptably larger than any nominal
630 	 * Page for Page Code 0x2A.
631 	 */
632 	mp2a = (uchar_t *)my_zalloc(buflen);
633 	if (get_mode_page(dev->d_fd, 0x2A, 0, buflen, mp2a) == 0)
634 		goto end;
635 
636 	/* Determine MMC version based on 'Page Length' field */
637 	switch (mp2a[1]) {
638 	case 0x14:  /* MMC-1 */
639 		if (debug)
640 			(void) printf("Mode Page 2A: MMC-1\n");
641 
642 		offset = (cmd == GET_READ_SPEED) ? 14 : 20;
643 		rate = read_scsi16(&mp2a[offset]);
644 		break;
645 
646 
647 	case 0x18: /* MMC-2 */
648 		if (debug)
649 			(void) printf("Mode Page 2A: MMC-2;"
650 			    " Read and Write Speeds are "
651 			    "obsolete\n");
652 
653 		/* see if "Obsolete" values are valid: */
654 		offset = (cmd == GET_READ_SPEED) ? 14 : 20;
655 		rate = read_scsi16(&mp2a[offset]);
656 		break;
657 
658 	default: /* MMC-3 or newer */
659 		if (debug)
660 			(void) printf("Mode Page 2A: MMC-3 or"
661 			    " newer; Read Speed is obsolete.\n");
662 
663 		if (cmd == GET_READ_SPEED) {
664 			/* this is Obsolete, but try it */
665 			offset = 14;
666 			rate = read_scsi16(&mp2a[offset]);
667 		} else {
668 			/* Write Speed is not obsolete */
669 			offset = 28;
670 			rate = read_scsi16(&mp2a[offset]);
671 
672 			if (rate == 0) {
673 				/*
674 				 * then try an Obsolete field
675 				 * (but this shouldn't happen!)
676 				 */
677 				offset = 20;
678 				rate = read_scsi16(&mp2a[offset]);
679 			}
680 		}
681 		break;
682 	}
683 end:
684 	free(mp2a);
685 
686 	if (debug)
687 		(void) printf("cd_speed_get: %s Speed is "
688 		    "%uX\n", (cmd == GET_READ_SPEED) ?
689 		    "Read" : "Write", cdrw_bandwidth_to_x(rate));
690 	return (rate);
691 }
692 
693 /*
694  * CD speed related functions (ioctl style) for drives which do not support
695  * real time streaming.
696  *
697  * For the SET operations, the SET CD SPEED command needs
698  * both the Read Speed and the Write Speed.  Eg, if
699  * we're trying to set the Write Speed (SET_WRITE_SPEED),
700  * then we first need to obtain the current Read Speed.
701  * That speed is specified along with the chosen_speed (the
702  * Write Speed in this case) in the SET CD SPEED command.
703  */
704 int
705 cd_speed_ctrl(cd_device *dev, int cmd, int speed)
706 {
707 	uint16_t rate;
708 
709 	switch (cmd) {
710 	case GET_READ_SPEED:
711 		rate = cd_speed_get(dev, GET_READ_SPEED);
712 		return (cdrw_bandwidth_to_x(rate));
713 
714 	case GET_WRITE_SPEED:
715 		rate = cd_speed_get(dev, GET_WRITE_SPEED);
716 		return (cdrw_bandwidth_to_x(rate));
717 
718 	case SET_READ_SPEED:
719 		rate = cd_speed_get(dev, GET_WRITE_SPEED);
720 		return (set_cd_speed(dev->d_fd,
721 		    cdrw_x_to_bandwidth(speed), rate));
722 		break;
723 
724 	case SET_WRITE_SPEED:
725 		rate = cd_speed_get(dev, GET_READ_SPEED);
726 		return (set_cd_speed(dev->d_fd, rate,
727 		    cdrw_x_to_bandwidth(speed)));
728 		break;
729 
730 	default:
731 		return (0);
732 	}
733 }
734 
735 /*
736  * Manage sending of SET STREAMING command using the specified
737  * read_speed and write_speed.
738  *
739  * This function allocates and initializes a Performance
740  * Descriptor, which is sent as part of the SET STREAMING
741  * command.  The descriptor is deallocated before function
742  * exit.
743  */
744 static int
745 do_set_streaming(cd_device *dev, uint_t read_speed,
746 	uint_t write_speed)
747 {
748 	int ret;
749 	uchar_t *str;
750 
751 	/* Allocate and initialize the Performance Descriptor */
752 	str = (uchar_t *)my_zalloc(SET_STREAM_DATA_LEN);
753 
754 	/* Read Time (in milliseconds) */
755 	load_scsi32(&str[16], 1000);
756 	/* Write Time (in milliseconds) */
757 	load_scsi32(&str[24], 1000);
758 
759 	/* Read Speed */
760 	load_scsi32(&str[12], (uint32_t)read_speed);
761 	/* Write Speed */
762 	load_scsi32(&str[20], (uint32_t)write_speed);
763 
764 	/* issue SET STREAMING command */
765 	ret = set_streaming(dev->d_fd, str);
766 	free(str);
767 
768 	return (ret);
769 }
770 
771 /*
772  * cd speed related functions for drives which support
773  * Real-Time Streaming Feature.
774  *
775  * For the SET operations, the SET STREAMING command needs
776  * both the Read Speed and the Write Speed.  Eg, if
777  * we're trying to set the Write Speed (SET_WRITE_SPEED),
778  * then we first need to obtain the current Read Speed.
779  * That speed is specified along with the chosen_speed (the
780  * Write Speed in this case) in the SET STREAMING command.
781  */
782 int
783 rt_streaming_ctrl(cd_device *dev, int cmd, int speed)
784 {
785 	int ret = 0;
786 	uint_t rate;
787 
788 	switch (cmd) {
789 	case GET_WRITE_SPEED:
790 		rate = cd_speed_get(dev, GET_WRITE_SPEED);
791 		ret = (int)cdrw_bandwidth_to_x(rate);
792 		break;
793 
794 	case GET_READ_SPEED:
795 		rate = cd_speed_get(dev, GET_READ_SPEED);
796 		ret = (int)cdrw_bandwidth_to_x(rate);
797 		break;
798 
799 	case SET_READ_SPEED: {
800 		uint_t write_speed = cd_speed_get(dev, GET_WRITE_SPEED);
801 
802 		/* set Read Speed using SET STREAMING */
803 		ret = do_set_streaming(dev,
804 		    cdrw_x_to_bandwidth(speed), write_speed);
805 
806 		/* If rt_speed_ctrl fails for any reason use cd_speed_ctrl */
807 		if (ret == 0) {
808 			if (debug)
809 				(void) printf(" real time speed control"
810 				    " failed, using CD speed control\n");
811 
812 			dev->d_speed_ctrl = cd_speed_ctrl;
813 			ret = dev->d_speed_ctrl(dev, cmd, speed);
814 		}
815 		break;
816 	}
817 
818 	case SET_WRITE_SPEED: {
819 		uint_t read_speed = cd_speed_get(dev, GET_READ_SPEED);
820 
821 		/* set Write Speed using SET STREAMING */
822 		ret = do_set_streaming(dev, read_speed,
823 		    cdrw_x_to_bandwidth(speed));
824 
825 		/* If rt_speed_ctrl fails for any reason use cd_speed_ctrl */
826 		if (ret == 0) {
827 			if (debug)
828 				(void) printf(" real time speed control"
829 				    " failed, using CD speed control\n");
830 
831 			dev->d_speed_ctrl = cd_speed_ctrl;
832 			ret = dev->d_speed_ctrl(dev, cmd, speed);
833 		}
834 		break;
835 	}
836 
837 	default:
838 		break;
839 	}
840 
841 	return (ret);
842 }
843 
844 /*
845  * Initialize device for track-at-once mode of writing. All of the data will
846  * need to be written to the track without interruption.
847  * This initialized TAO by setting page code 5 and speed.
848  */
849 void
850 write_init(int mode)
851 {
852 	(void) printf(gettext("Initializing device"));
853 	if (simulation)
854 		(void) printf(gettext("(Simulation mode)"));
855 	print_n_flush("...");
856 
857 	get_media_type(target->d_fd);
858 
859 	/* DVD- requires DAO mode */
860 	if (device_type == DVD_MINUS) {
861 		write_mode = DAO_MODE;
862 	}
863 
864 	/* For debug, print out device config information */
865 	if (debug) {
866 		int i;
867 		uchar_t cap[80];
868 
869 		if (get_configuration(target->d_fd, 0, 80, cap))
870 			(void) printf("Drive profile = ");
871 			for (i = 10; i < 70; i += 8)
872 				(void) printf(" 0x%x", cap[i]);
873 			(void) printf("\n");
874 	}
875 
876 	/* DVD+ and DVD- have no support for AUDIO, bail out */
877 	if ((mode == TRACK_MODE_AUDIO) && (device_type != CD_RW)) {
878 		err_msg(gettext("Audio mode is only supported for CD media\n"));
879 		exit(1);
880 	}
881 	if (simulation &&
882 	    check_device(target, CHECK_MEDIA_IS_NOT_BLANK) &&
883 	    !check_device(target, CHECK_MEDIA_IS_NOT_ERASABLE) &&
884 	    device_type != DVD_PLUS_W) {
885 		/*
886 		 * If we were in simulation mode, and media wasn't blank,
887 		 * but medium was erasable, then cdrw goes to erase the
888 		 * contents of the media after the simulation writing in order
889 		 * to cleanup the ghost TOC (see write_fini() calls blank()).
890 		 * This is bad because it removes existing data if media was
891 		 * multi-session. Therefore, we no longer allow simulation
892 		 * writing if such condition is met. we don't blank the DVD+RW
893 		 * media, so DVD+RWs are fine.
894 		 */
895 		err_msg(gettext(
896 		    "Cannot perform simulation for non-blank media\n"));
897 		exit(1);
898 	}
899 
900 	if (!prepare_for_write(target, mode, simulation, keep_disc_open)) {
901 		/* l10n_NOTE : 'failed' as in Initializing device...failed  */
902 		(void) printf(gettext("failed.\n"));
903 		err_msg(gettext("Cannot initialize device for write\n"));
904 		exit(1);
905 	}
906 	/* l10n_NOTE : 'done' as in "Initializing device...done"  */
907 	(void) printf(gettext("done.\n"));
908 
909 	/* if speed change option was used (-p) then try to set the speed */
910 	if (requested_speed != 0) {
911 		if (verbose)
912 			(void) printf(gettext("Trying to set speed to %dX.\n"),
913 			    requested_speed);
914 		if (target->d_speed_ctrl(target, SET_WRITE_SPEED,
915 		    requested_speed) == 0) {
916 			err_msg(gettext("Unable to set speed.\n"));
917 			exit(1);
918 		}
919 		if (verbose) {
920 			int speed;
921 			speed = target->d_speed_ctrl(target,
922 			    GET_WRITE_SPEED, 0);
923 			if (speed == requested_speed) {
924 				(void) printf(gettext("Speed set to %dX.\n"),
925 				    speed);
926 			} else if (speed == 0) {
927 				(void) printf(gettext("Could not obtain "
928 				    "current Write Speed.\n"));
929 			} else {
930 				(void) printf(
931 				gettext("Speed set to closest approximation "
932 				    "of %dX allowed by device (%dX).\n"),
933 				    requested_speed, speed);
934 			}
935 		}
936 	}
937 }
938 
939 void
940 write_fini(void)
941 {
942 	print_n_flush(gettext("Finalizing (Can take several minutes)..."));
943 	/* Some drives don't like this while in test write mode */
944 	if (!simulation) {
945 		if (!finalize(target)) {
946 			/*
947 			 * It is possible that the drive is busy writing the
948 			 * buffered portion. So do not get upset yet.
949 			 */
950 			(void) sleep(10);
951 			if (!finalize(target)) {
952 				if (debug) {
953 					(void) printf("status %x, %x/%x/%x\n",
954 					    uscsi_status, SENSE_KEY(rqbuf),
955 					    ASC(rqbuf), ASCQ(rqbuf));
956 				}
957 
958 				if ((device_type == DVD_MINUS) &&
959 				    (SENSE_KEY(rqbuf) == 5)) {
960 
961 					if (verbose) {
962 						(void) printf(
963 						    "skipping finalizing\n");
964 					}
965 				} else {
966 
967 			/* l10n_NOTE : 'failed' as in finishing up...failed  */
968 					(void) printf(gettext("failed.\n"));
969 
970 					err_msg(gettext(
971 					    "Could not finalize the disc.\n"));
972 					exit(1);
973 				}
974 
975 
976 			}
977 		}
978 		if (vol_running) {
979 			(void) eject_media(target);
980 		}
981 	} else if (check_device(target, CHECK_MEDIA_IS_NOT_BLANK)) {
982 		/*
983 		 * Some drives such as the pioneer A04 will retain a
984 		 * ghost TOC after a simulation write is done. The
985 		 * media will actually be blank, but the drive will
986 		 * report a TOC. There is currently no other way to
987 		 * re-initialize the media other than ejecting or
988 		 * to ask the drive to clear the leadout. The laser
989 		 * is currently off so nothing is written to the
990 		 * media (on a good behaving drive).
991 		 * NOTE that a device reset does not work to make
992 		 * the drive re-initialize the media.
993 		 */
994 
995 		blanking_type = "clear_ghost";
996 		blank();
997 
998 	}
999 	/* l10n_NOTE : 'done' as in "Finishing up...done"  */
1000 	(void) printf(gettext("done.\n"));
1001 }
1002