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