xref: /haiku/src/add-ons/kernel/drivers/disk/scsi/scsi_cd/scsi_cd.cpp (revision 7a74a5df454197933bc6e80a542102362ee98703)
1 /*
2  * Copyright 2004-2010, Haiku, Inc. All rights reserved.
3  * Copyright 2002-2003, Thomas Kurschel. All rights reserved.
4  *
5  * Distributed under the terms of the MIT License.
6  */
7 
8 
9 /*!	Peripheral driver to handle CD-ROM drives. To be more
10 	precisely, it supports CD-ROM and WORM drives (well -
11 	I've never _seen_ a WORM driver).
12 
13 	Much work is done by scsi_periph and block_io.
14 */
15 
16 
17 #include "scsi_cd.h"
18 
19 #include <stdlib.h>
20 #include <string.h>
21 
22 #include <algorithm>
23 
24 #include <io_requests.h>
25 #include <vm/vm_page.h>
26 
27 #include "IOCache.h"
28 #include "IOSchedulerSimple.h"
29 
30 
31 //#define TRACE_CD_DISK
32 #ifdef TRACE_CD_DISK
33 #	define TRACE(x...) dprintf("scsi_cd: " x)
34 #else
35 #	define TRACE(x...) ;
36 #endif
37 
38 
39 static const uint8 kCDIcon[] = {
40 	0x6e, 0x63, 0x69, 0x66, 0x05, 0x05, 0x00, 0x02, 0x03, 0x06, 0x05, 0xb8,
41 	0x12, 0xa5, 0xbe, 0x03, 0xe1, 0x3d, 0xe7, 0x84, 0xb8, 0x02, 0x10, 0x49,
42 	0xf7, 0x9f, 0x49, 0xed, 0xd8, 0x00, 0xf1, 0xf1, 0xf1, 0x36, 0xd9, 0xdd,
43 	0xf4, 0x8a, 0x99, 0x96, 0xb9, 0xb4, 0xb8, 0xbe, 0xdb, 0xff, 0xf4, 0xf4,
44 	0xf4, 0x04, 0xeb, 0xd0, 0x02, 0x00, 0x06, 0x02, 0x3c, 0x92, 0xc0, 0x38,
45 	0x8f, 0x5f, 0xb8, 0x54, 0x50, 0x3c, 0x57, 0x63, 0x48, 0xd8, 0xdf, 0x48,
46 	0x89, 0x5b, 0x00, 0x41, 0x37, 0xa9, 0xff, 0xb9, 0xb9, 0xb9, 0x04, 0x01,
47 	0x7e, 0x04, 0x02, 0x04, 0x3f, 0x2c, 0x4e, 0x2c, 0x30, 0x2c, 0x22, 0x40,
48 	0x22, 0x34, 0x22, 0x4c, 0x3f, 0x54, 0x30, 0x54, 0x4e, 0x54, 0x5c, 0x40,
49 	0x5c, 0x4c, 0x5c, 0x34, 0x02, 0x04, 0x3f, 0x3a, 0x43, 0x3a, 0x3b, 0x3a,
50 	0x39, 0x3e, 0x39, 0x3c, 0x39, 0x40, 0x3f, 0x42, 0x3b, 0x42, 0x43, 0x42,
51 	0x45, 0x3e, 0x45, 0x40, 0x45, 0x3c, 0x02, 0x04, 0x4b, 0x3e, 0x4b, 0x3a,
52 	0x4b, 0x42, 0x3f, 0x46, 0x47, 0x46, 0x37, 0x46, 0x33, 0x3e, 0x33, 0x42,
53 	0x33, 0x3a, 0x3f, 0xbb, 0xf7, 0x37, 0xbb, 0xf7, 0x47, 0xbb, 0xf7, 0x02,
54 	0x04, 0x40, 0x2a, 0x54, 0x2a, 0x50, 0x2c, 0x5c, 0x40, 0x5c, 0x34, 0x5c,
55 	0x4c, 0x40, 0x56, 0x50, 0x54, 0x54, 0x56, 0x60, 0x40, 0x60, 0x4c, 0x60,
56 	0x34, 0x06, 0x0a, 0x04, 0x01, 0x03, 0x00, 0x0a, 0x00, 0x02, 0x00, 0x01,
57 	0x18, 0x15, 0xff, 0x01, 0x17, 0x84, 0x00, 0x04, 0x0a, 0x00, 0x02, 0x00,
58 	0x01, 0x18, 0x00, 0x15, 0x01, 0x17, 0x86, 0x00, 0x04, 0x0a, 0x01, 0x02,
59 	0x00, 0x02, 0x00, 0x0a, 0x02, 0x02, 0x02, 0x01, 0x00, 0x0a, 0x03, 0x01,
60 	0x02, 0x10, 0x01, 0x17, 0x82, 0x00, 0x04
61 };
62 
63 
64 static scsi_periph_interface *sSCSIPeripheral;
65 static device_manager_info *sDeviceManager;
66 
67 
68 #define SCSI_CD_STD_TIMEOUT 10
69 
70 
71 static status_t
72 update_capacity(cd_driver_info *info)
73 {
74 	TRACE("update_capacity()\n");
75 
76 	scsi_ccb *ccb = info->scsi->alloc_ccb(info->scsi_device);
77 	if (ccb == NULL)
78 		return B_NO_MEMORY;
79 
80 	status_t status = sSCSIPeripheral->check_capacity(
81 		info->scsi_periph_device, ccb);
82 
83 	info->scsi->free_ccb(ccb);
84 
85 	return status;
86 }
87 
88 
89 /*!	Iteratively correct the reported capacity by trying to read from the device
90 	close to its end.
91 */
92 static uint64
93 test_capacity(cd_driver_info *info)
94 {
95 	static const size_t kMaxEntries = 4;
96 	const uint32 blockSize = info->block_size;
97 	const size_t kBufferSize = blockSize * 4;
98 
99 	TRACE("test_capacity: read with buffer size %" B_PRIuSIZE ", block size %"
100 		B_PRIu32", capacity %llu\n", kBufferSize, blockSize,
101 		info->original_capacity);
102 
103 	info->capacity = info->original_capacity;
104 
105 	size_t numBlocks = B_PAGE_SIZE / blockSize;
106 	uint64 offset = info->original_capacity;
107 	if (offset <= numBlocks)
108 		return B_OK;
109 
110 	offset -= numBlocks;
111 
112 	scsi_ccb *request = info->scsi->alloc_ccb(info->scsi_device);
113 	if (request == NULL)
114 		return B_NO_MEMORY;
115 
116 	// Allocate buffer
117 
118 	physical_entry entries[4];
119 	size_t numEntries = 0;
120 
121 	vm_page_reservation reservation;
122 	vm_page_reserve_pages(&reservation,
123 		(kBufferSize - 1 + B_PAGE_SIZE) / B_PAGE_SIZE, VM_PRIORITY_SYSTEM);
124 
125 	for (size_t left = kBufferSize; numEntries < kMaxEntries && left > 0;
126 			numEntries++) {
127 		size_t bytes = std::min(left, (size_t)B_PAGE_SIZE);
128 
129 		vm_page* page = vm_page_allocate_page(&reservation,
130 			PAGE_STATE_WIRED | VM_PAGE_ALLOC_BUSY);
131 
132 		entries[numEntries].address = page->physical_page_number * B_PAGE_SIZE;
133 		entries[numEntries].size = bytes;;
134 
135 		left -= bytes;
136 	}
137 
138 	vm_page_unreserve_pages(&reservation);
139 
140 	// Read close to the end of the device to find out its real end
141 
142 	// Only try 1 second before the end (= 75 blocks)
143 	while (offset > info->original_capacity - 75) {
144 		size_t bytesTransferred;
145 		status_t status = sSCSIPeripheral->read_write(info->scsi_periph_device,
146 			request, offset, numBlocks, entries, numEntries, false,
147 			&bytesTransferred);
148 
149 		TRACE("test_capacity: read from offset %llu: %s\n", offset,
150 			strerror(status));
151 
152 		if (status == B_OK || (request->sense[0] & 0x7f) != 0x70)
153 			break;
154 
155 		switch (request->sense[2]) {
156 			case SCSIS_KEY_MEDIUM_ERROR:
157 			case SCSIS_KEY_ILLEGAL_REQUEST:
158 			case SCSIS_KEY_VOLUME_OVERFLOW:
159 			{
160 				// find out the problematic sector
161 				uint32 errorBlock = (request->sense[3] << 24U)
162 					| (request->sense[4] << 16U) | (request->sense[5] << 8U)
163 					| request->sense[6];
164 				if (errorBlock >= offset)
165 					info->capacity = errorBlock;
166 				break;
167 			}
168 
169 			default:
170 				break;
171 		}
172 
173 		if (numBlocks > offset)
174 			break;
175 
176 		offset -= numBlocks;
177 	}
178 
179 	info->scsi->free_ccb(request);
180 
181 	for (size_t i = 0; i < numEntries; i++) {
182 		vm_page_set_state(vm_lookup_page(entries[i].address / B_PAGE_SIZE),
183 			PAGE_STATE_FREE);
184 	}
185 
186 	if (info->capacity != info->original_capacity) {
187 		dprintf("scsi_cd: adjusted capacity from %llu to %llu blocks.\n",
188 			info->original_capacity, info->capacity);
189 	}
190 
191 	return B_OK;
192 }
193 
194 
195 static status_t
196 get_geometry(cd_handle *handle, device_geometry *geometry)
197 {
198 	cd_driver_info *info = handle->info;
199 
200 	status_t status = update_capacity(info);
201 
202 	// it seems that Be expects B_GET_GEOMETRY to always succeed unless
203 	// the medium has been changed; e.g. if we report B_DEV_NO_MEDIA, the
204 	// info is ignored by the CDPlayer and CDBurner
205 	if (status == B_DEV_MEDIA_CHANGED)
206 		return B_DEV_MEDIA_CHANGED;
207 
208 	geometry->bytes_per_sector = info->block_size;
209 	geometry->sectors_per_track = 1;
210 	geometry->cylinder_count = info->capacity;
211 	geometry->head_count = 1;
212 	geometry->device_type = info->device_type;
213 	geometry->removable = info->removable;
214 
215 	// TBD: for all but CD-ROMs, read mode sense - medium type
216 	// (bit 7 of block device specific parameter for Optical Memory Block Device)
217 	// (same for Direct-Access Block Devices)
218 	// (same for write-once block devices)
219 	// (same for optical memory block devices)
220 	geometry->read_only = true;
221 	geometry->write_once = info->device_type == scsi_dev_WORM;
222 
223 	TRACE("scsi_disk: get_geometry(): %ld, %ld, %ld, %ld, %d, %d, %d, %d\n",
224 		geometry->bytes_per_sector, geometry->sectors_per_track,
225 		geometry->cylinder_count, geometry->head_count, geometry->device_type,
226 		geometry->removable, geometry->read_only, geometry->write_once);
227 
228 	return B_OK;
229 }
230 
231 
232 static status_t
233 get_toc(cd_driver_info *info, scsi_toc *toc)
234 {
235 	scsi_ccb *ccb;
236 	status_t res;
237 	scsi_cmd_read_toc *cmd;
238 	size_t dataLength;
239 	scsi_toc_general *shortResponse = (scsi_toc_general *)toc->toc_data;
240 
241 	TRACE("get_toc()\n");
242 
243 	ccb = info->scsi->alloc_ccb(info->scsi_device);
244 	if (ccb == NULL)
245 		return B_NO_MEMORY;
246 
247 	// first read number of tracks only
248 	ccb->flags = SCSI_DIR_IN;
249 
250 	cmd = (scsi_cmd_read_toc *)ccb->cdb;
251 
252 	memset(cmd, 0, sizeof(*cmd));
253 	cmd->opcode = SCSI_OP_READ_TOC;
254 	cmd->time = 1;
255 	cmd->format = SCSI_TOC_FORMAT_TOC;
256 	cmd->track = 1;
257 	cmd->allocation_length = B_HOST_TO_BENDIAN_INT16(sizeof(scsi_toc_general));
258 
259 	ccb->cdb_length = sizeof(*cmd);
260 
261 	ccb->sort = -1;
262 	ccb->timeout = SCSI_CD_STD_TIMEOUT;
263 
264 	ccb->data = toc->toc_data;
265 	ccb->sg_list = NULL;
266 	ccb->data_length = sizeof(toc->toc_data);
267 
268 	res = sSCSIPeripheral->safe_exec(info->scsi_periph_device, ccb);
269 	if (res != B_OK)
270 		goto err;
271 
272 	// then read all track infos
273 	// (little hint: number of tracks is last - first + 1;
274 	//  but scsi_toc_toc has already one track, so we get
275 	//  last - first extra tracks; finally, we want the lead-out as
276 	//  well, so we add an extra track)
277 	dataLength = (shortResponse->last - shortResponse->first + 1)
278 		* sizeof(scsi_toc_track) + sizeof(scsi_toc_toc);
279 	dataLength = min_c(dataLength, sizeof(toc->toc_data));
280 
281 	TRACE("  tracks: %d - %d, data length %d\n", shortResponse->first,
282 		shortResponse->last, (int)dataLength);
283 
284 	cmd->allocation_length = B_HOST_TO_BENDIAN_INT16(dataLength);
285 
286 	res = sSCSIPeripheral->safe_exec(info->scsi_periph_device, ccb);
287 
288 err:
289 	info->scsi->free_ccb(ccb);
290 
291 	return res;
292 }
293 
294 
295 static status_t
296 load_eject(cd_driver_info *info, bool load)
297 {
298 	TRACE("load_eject()\n");
299 
300 	scsi_ccb *ccb = info->scsi->alloc_ccb(info->scsi_device);
301 	if (ccb == NULL)
302 		return B_NO_MEMORY;
303 
304 	err_res result = sSCSIPeripheral->send_start_stop(
305 		info->scsi_periph_device, ccb, load, true);
306 
307 	info->scsi->free_ccb(ccb);
308 
309 	return result.error_code;
310 }
311 
312 
313 static status_t
314 get_position(cd_driver_info *info, scsi_position *position)
315 {
316 	scsi_cmd_read_subchannel cmd;
317 
318 	TRACE("get_position()\n");
319 
320 	memset(&cmd, 0, sizeof(cmd));
321 	cmd.opcode = SCSI_OP_READ_SUB_CHANNEL;
322 	cmd.time = 1;
323 	cmd.subq = 1;
324 	cmd.parameter_list = scsi_sub_channel_parameter_list_cd_pos;
325 	cmd.track = 0;
326 	cmd.allocation_length = B_HOST_TO_BENDIAN_INT16(sizeof(scsi_position));
327 
328 	return sSCSIPeripheral->simple_exec(info->scsi_periph_device,
329 		&cmd, sizeof(cmd), position, sizeof(*position), SCSI_DIR_IN);
330 }
331 
332 
333 static status_t
334 get_set_volume(cd_driver_info *info, scsi_volume *volume, bool set)
335 {
336 	scsi_cmd_mode_sense_6 cmd;
337 	scsi_mode_param_header_6 header;
338 	size_t len;
339 	void *buffer;
340 	scsi_modepage_audio	*page;
341 	status_t res;
342 
343 	TRACE("get_set_volume()\n");
344 
345 	// determine size of block descriptor
346 	memset(&cmd, 0, sizeof(cmd));
347 	cmd.opcode = SCSI_OP_MODE_SENSE_6;
348 	cmd.page_code = SCSI_MODEPAGE_AUDIO;
349 	cmd.page_control = SCSI_MODE_SENSE_PC_CURRENT;
350 	cmd.allocation_length = sizeof(header);
351 
352 	memset(&header, -2, sizeof(header));
353 
354 	res = sSCSIPeripheral->simple_exec(info->scsi_periph_device, &cmd,
355 		sizeof(cmd), &header, sizeof(header), SCSI_DIR_IN);
356 	if (res != B_OK)
357 		return res;
358 
359 	TRACE("  block_desc_len=%d", header.block_desc_length);
360 #if 0
361 	// ToDo: why this??
362 	return B_ERROR;
363 #endif
364 
365 	// retrieve param header, block descriptor and actual codepage
366 	len = sizeof(header) + header.block_desc_length
367 		+ sizeof(scsi_modepage_audio);
368 
369 	buffer = malloc(len);
370 	if (buffer == NULL)
371 		return B_NO_MEMORY;
372 
373 	memset(buffer, -1, sizeof(buffer));
374 
375 	cmd.allocation_length = len;
376 
377 	res = sSCSIPeripheral->simple_exec(info->scsi_periph_device, &cmd,
378 		sizeof(cmd), buffer, len, SCSI_DIR_IN);
379 	if (res != B_OK) {
380 		free(buffer);
381 		return res;
382 	}
383 
384 	TRACE("  mode_data_len=%d, block_desc_len=%d",
385 		((scsi_mode_param_header_6 *)buffer)->mode_data_length,
386 		((scsi_mode_param_header_6 *)buffer)->block_desc_length);
387 
388 	// find control page and retrieve values
389 	page = (scsi_modepage_audio *)((char *)buffer + sizeof(header)
390 		+ header.block_desc_length);
391 
392 	TRACE("  page=%p, codepage=%d", page, page->header.page_code);
393 
394 	if (!set) {
395 		volume->port0_channel = page->ports[0].channel;
396 		volume->port0_volume  = page->ports[0].volume;
397 		volume->port1_channel = page->ports[1].channel;
398 		volume->port1_volume  = page->ports[1].volume;
399 		volume->port2_channel = page->ports[2].channel;
400 		volume->port2_volume  = page->ports[2].volume;
401 		volume->port3_channel = page->ports[3].channel;
402 		volume->port3_volume  = page->ports[3].volume;
403 
404 #if 0
405 		SHOW_FLOW(3, "1: %d - %d", volume->port0_channel, volume->port0_volume);
406 		SHOW_FLOW(3, "2: %d - %d", volume->port1_channel, volume->port1_volume);
407 		SHOW_FLOW(3, "3: %d - %d", volume->port2_channel, volume->port2_volume);
408 		SHOW_FLOW(3, "4: %d - %d", volume->port3_channel, volume->port3_volume);
409 #endif
410 		res = B_OK;
411 	} else {
412 		scsi_cmd_mode_select_6 cmd;
413 
414 		if (volume->flags & 0x01)
415 			page->ports[0].channel = volume->port0_channel;
416 		if (volume->flags & 0x02)
417 			page->ports[0].volume = volume->port0_volume;
418 		if (volume->flags & 0x04)
419 			page->ports[1].channel = volume->port1_channel;
420 		if (volume->flags & 0x08)
421 			page->ports[1].volume = volume->port1_volume;
422 		if (volume->flags & 0x10)
423 			page->ports[2].channel = volume->port2_channel;
424 		if (volume->flags & 0x20)
425 			page->ports[2].volume = volume->port2_volume;
426 		if (volume->flags & 0x40)
427 			page->ports[3].channel = volume->port3_channel;
428 		if (volume->flags & 0x80)
429 			page->ports[3].volume = volume->port3_volume;
430 
431 		memset(&cmd, 0, sizeof(cmd));
432 		cmd.opcode = SCSI_OP_MODE_SELECT_6;
433 		cmd.pf = 1;
434 		cmd.param_list_length = sizeof(header) + header.block_desc_length
435 			+ sizeof(*page);
436 
437 		res = sSCSIPeripheral->simple_exec(info->scsi_periph_device,
438 			&cmd, sizeof(cmd), buffer, len, SCSI_DIR_OUT);
439 	}
440 
441 	free(buffer);
442 	return res;
443 }
444 
445 
446 /*!	Play audio cd; time is in MSF */
447 static status_t
448 play_msf(cd_driver_info *info, const scsi_play_position *position)
449 {
450 	scsi_cmd_play_msf cmd;
451 
452 	TRACE("play_msf(): %d:%d:%d-%d:%d:%d\n", position->start_m,
453 		position->start_s, position->start_f, position->end_m, position->end_s,
454 		position->end_f);
455 
456 	memset(&cmd, 0, sizeof(cmd));
457 
458 	cmd.opcode = SCSI_OP_PLAY_MSF;
459 	cmd.start_minute = position->start_m;
460 	cmd.start_second = position->start_s;
461 	cmd.start_frame = position->start_f;
462 	cmd.end_minute = position->end_m;
463 	cmd.end_second = position->end_s;
464 	cmd.end_frame = position->end_f;
465 
466 	return sSCSIPeripheral->simple_exec(info->scsi_periph_device,
467 		&cmd, sizeof(cmd), NULL, 0, SCSI_DIR_NONE);
468 }
469 
470 
471 /*! Play audio cd; time is in track/index */
472 static status_t
473 play_track_index(cd_driver_info *info, const scsi_play_track *buf)
474 {
475 	scsi_toc generic_toc;
476 	scsi_toc_toc *toc;
477 	status_t res;
478 	int start_track, end_track;
479 	scsi_play_position position;
480 
481 	TRACE("play_track_index(): %d-%d\n", buf->start_track, buf->end_track);
482 
483 	// the corresponding command PLAY AUDIO TRACK/INDEX	is deprecated,
484 	// so we have to simulate it by converting track to time via TOC
485 	res = get_toc(info, &generic_toc);
486 	if (res != B_OK)
487 		return res;
488 
489 	toc = (scsi_toc_toc *)&generic_toc.toc_data[0];
490 
491 	start_track = buf->start_track;
492 	end_track = buf->end_track;
493 
494 	if (start_track > toc->last_track)
495 		return B_BAD_INDEX;
496 
497 	if (end_track > toc->last_track)
498 		end_track = toc->last_track + 1;
499 
500 	if (end_track < toc->last_track + 1)
501 		++end_track;
502 
503 	start_track -= toc->first_track;
504 	end_track -= toc->first_track;
505 
506 	if (start_track < 0 || end_track < 0)
507 		return B_BAD_INDEX;
508 
509 	position.start_m = toc->tracks[start_track].start.time.minute;
510 	position.start_s = toc->tracks[start_track].start.time.second;
511 	position.start_f = toc->tracks[start_track].start.time.frame;
512 
513 	position.end_m = toc->tracks[end_track].start.time.minute;
514 	position.end_s = toc->tracks[end_track].start.time.second;
515 	position.end_f = toc->tracks[end_track].start.time.frame;
516 
517 	return play_msf(info, &position);
518 }
519 
520 
521 static status_t
522 stop_audio(cd_driver_info *info)
523 {
524 	scsi_cmd_stop_play cmd;
525 
526 	TRACE("stop_audio()\n");
527 
528 	memset( &cmd, 0, sizeof( cmd ));
529 	cmd.opcode = SCSI_OP_STOP_PLAY;
530 
531 	return sSCSIPeripheral->simple_exec(info->scsi_periph_device,
532 		&cmd, sizeof(cmd), NULL, 0, SCSI_DIR_NONE);
533 }
534 
535 
536 static status_t
537 pause_resume(cd_driver_info *info, bool resume)
538 {
539 	scsi_cmd_pause_resume cmd;
540 
541 	TRACE("pause_resume()\n");
542 
543 	memset(&cmd, 0, sizeof(cmd));
544 	cmd.opcode = SCSI_OP_PAUSE_RESUME;
545 	cmd.resume = resume;
546 
547 	return sSCSIPeripheral->simple_exec(info->scsi_periph_device,
548 		&cmd, sizeof(cmd), NULL, 0, SCSI_DIR_NONE);
549 }
550 
551 
552 static status_t
553 scan(cd_driver_info *info, const scsi_scan *buf)
554 {
555 	scsi_cmd_scan cmd;
556 	scsi_position curPos;
557 	scsi_cd_current_position *cdPos;
558 
559 	TRACE("scan(direction =% d)\n", buf->direction);
560 
561 	status_t res = get_position(info, &curPos);
562 	if (res != B_OK)
563 		return res;
564 
565 	cdPos = (scsi_cd_current_position *)((char *)&curPos
566 		+ sizeof(scsi_subchannel_data_header));
567 
568 	if (buf->direction == 0) {
569 		scsi_play_position playPos;
570 
571 		// to stop scan, we issue play command with "open end"
572 		playPos.start_m = cdPos->absolute_address.time.minute;
573 		playPos.start_s = cdPos->absolute_address.time.second;
574 		playPos.start_f = cdPos->absolute_address.time.frame;
575 		playPos.end_m = 99;
576 		playPos.end_s = 59;
577 		playPos.end_f = 24;
578 
579 		return play_msf(info, &playPos);
580 	}
581 
582 	memset(&cmd, 0, sizeof(cmd));
583 
584 	cmd.opcode = SCSI_OP_SCAN;
585 	cmd.direct = buf->direction < 0;
586 	cmd.start.time = cdPos->absolute_address.time;
587 	cmd.type = scsi_scan_msf;
588 
589 	/*
590 	tmp = (uint8 *)&cmd;
591 	dprintf("%d %d %d %d %d %d %d %d %d %d %d %d\n",
592 		tmp[0], tmp[1], tmp[2], tmp[3], tmp[4], tmp[5],
593 		tmp[6], tmp[7], tmp[8], tmp[9], tmp[10], tmp[11]);
594 	*/
595 
596 	return sSCSIPeripheral->simple_exec(info->scsi_periph_device,
597 		&cmd, sizeof(cmd), NULL, 0, SCSI_DIR_NONE);
598 }
599 
600 
601 static status_t
602 read_cd(cd_driver_info *info, const scsi_read_cd *readCD)
603 {
604 	scsi_cmd_read_cd *cmd;
605 	uint32 lba, length;
606 	scsi_ccb *ccb;
607 	status_t res;
608 
609 	// we use safe_exec instead of simple_exec as we want to set
610 	// the sorting order manually (only makes much sense if you grab
611 	// multiple tracks at once, but we are prepared)
612 	ccb = info->scsi->alloc_ccb(info->scsi_device);
613 
614 	if (ccb == NULL)
615 		return B_NO_MEMORY;
616 
617 	cmd = (scsi_cmd_read_cd *)ccb->cdb;
618 	memset(cmd, 0, sizeof(*cmd));
619 	cmd->opcode = SCSI_OP_READ_CD;
620 	cmd->sector_type = 1;
621 
622 	// skip first two seconds, they are lead-in
623 	lba = (readCD->start_m * 60 + readCD->start_s) * 75 + readCD->start_f
624 		- 2 * 75;
625 	length = (readCD->length_m * 60 + readCD->length_s) * 75 + readCD->length_f;
626 
627 	cmd->lba = B_HOST_TO_BENDIAN_INT32(lba);
628 	cmd->high_length = (length >> 16) & 0xff;
629 	cmd->mid_length = (length >> 8) & 0xff;
630 	cmd->low_length = length & 0xff;
631 
632 	cmd->error_field = scsi_read_cd_error_none;
633 	cmd->edc_ecc = 0;
634 	cmd->user_data = 1;
635 	cmd->header_code = scsi_read_cd_header_none;
636 	cmd->sync = 0;
637 	cmd->sub_channel_selection = scsi_read_cd_sub_channel_none;
638 
639 	ccb->cdb_length = sizeof(*cmd);
640 
641 	ccb->flags = SCSI_DIR_IN | SCSI_DIS_DISCONNECT;
642 	ccb->sort = lba;
643 	// are 10 seconds enough for timeout?
644 	ccb->timeout = 10;
645 
646 	// TODO: we pass a user buffer here!
647 	ccb->data = (uint8 *)readCD->buffer;
648 	ccb->sg_list = NULL;
649 	ccb->data_length = readCD->buffer_length;
650 
651 	res = sSCSIPeripheral->safe_exec(info->scsi_periph_device, ccb);
652 
653 	info->scsi->free_ccb(ccb);
654 
655 	return res;
656 }
657 
658 
659 static int
660 log2(uint32 x)
661 {
662 	int y;
663 
664 	for (y = 31; y >= 0; --y) {
665 		if (x == (1UL << y))
666 			break;
667 	}
668 
669 	return y;
670 }
671 
672 
673 static status_t
674 do_io(void* cookie, IOOperation* operation)
675 {
676 	cd_driver_info* info = (cd_driver_info*)cookie;
677 
678 	// TODO: this can go away as soon as we pushed the IOOperation to the upper
679 	// layers - we can then set scsi_periph::io() as callback for the scheduler
680 	size_t bytesTransferred;
681 	status_t status = sSCSIPeripheral->io(info->scsi_periph_device, operation,
682 		&bytesTransferred);
683 
684 	info->io_scheduler->OperationCompleted(operation, status, bytesTransferred);
685 	return status;
686 }
687 
688 
689 //	#pragma mark - device module API
690 
691 
692 static status_t
693 cd_init_device(void* _info, void** _cookie)
694 {
695 	cd_driver_info* info = (cd_driver_info*)_info;
696 
697 	update_capacity(info);
698 		// Get initial capacity, but ignore the result; we do not care
699 		// whether or not a media is present
700 
701 	*_cookie = info;
702 	return B_OK;
703 }
704 
705 
706 static void
707 cd_uninit_device(void* _cookie)
708 {
709 	cd_driver_info* info = (cd_driver_info*)_cookie;
710 
711 	delete info->io_scheduler;
712 	delete info->dma_resource;
713 }
714 
715 
716 static status_t
717 cd_open(void* _info, const char* path, int openMode, void** _cookie)
718 {
719 	cd_driver_info* info = (cd_driver_info*)_info;
720 
721 	cd_handle* handle = (cd_handle*)malloc(sizeof(cd_handle));
722 	if (handle == NULL)
723 		return B_NO_MEMORY;
724 
725 	handle->info = info;
726 
727 	status_t status = sSCSIPeripheral->handle_open(info->scsi_periph_device,
728 		(periph_handle_cookie)handle, &handle->scsi_periph_handle);
729 	if (status < B_OK) {
730 		free(handle);
731 		return status;
732 	}
733 
734 	*_cookie = handle;
735 	return B_OK;
736 }
737 
738 
739 static status_t
740 cd_close(void* cookie)
741 {
742 	cd_handle* handle = (cd_handle*)cookie;
743 	TRACE("close()\n");
744 
745 	sSCSIPeripheral->handle_close(handle->scsi_periph_handle);
746 	return B_OK;
747 }
748 
749 
750 static status_t
751 cd_free(void* cookie)
752 {
753 	cd_handle* handle = (cd_handle*)cookie;
754 	TRACE("free()\n");
755 
756 	sSCSIPeripheral->handle_free(handle->scsi_periph_handle);
757 	free(handle);
758 	return B_OK;
759 }
760 
761 
762 static status_t
763 cd_read(void* cookie, off_t pos, void* buffer, size_t* _length)
764 {
765 	cd_handle* handle = (cd_handle*)cookie;
766 	size_t length = *_length;
767 
768 	if (handle->info->capacity == 0)
769 		return B_DEV_NO_MEDIA;
770 
771 	IORequest request;
772 	status_t status = request.Init(pos, (addr_t)buffer, length, false, 0);
773 	if (status != B_OK)
774 		return status;
775 
776 	status = handle->info->io_scheduler->ScheduleRequest(&request);
777 	if (status != B_OK)
778 		return status;
779 
780 	status = request.Wait(0, 0);
781 	if (status == B_OK)
782 		*_length = length;
783 	else
784 		dprintf("cd_read(): request.Wait() returned: %s\n", strerror(status));
785 
786 	return status;
787 }
788 
789 
790 static status_t
791 cd_write(void* cookie, off_t pos, const void* buffer, size_t* _length)
792 {
793 	cd_handle* handle = (cd_handle*)cookie;
794 	size_t length = *_length;
795 
796 	if (handle->info->capacity == 0)
797 		return B_DEV_NO_MEDIA;
798 
799 	IORequest request;
800 	status_t status = request.Init(pos, (addr_t)buffer, length, true, 0);
801 	if (status != B_OK)
802 		return status;
803 
804 	status = handle->info->io_scheduler->ScheduleRequest(&request);
805 	if (status != B_OK)
806 		return status;
807 
808 	status = request.Wait(0, 0);
809 	if (status == B_OK)
810 		*_length = length;
811 	else
812 		dprintf("cd_write(): request.Wait() returned: %s\n", strerror(status));
813 
814 	return status;
815 }
816 
817 
818 static status_t
819 cd_io(void* cookie, io_request* request)
820 {
821 	cd_handle* handle = (cd_handle*)cookie;
822 
823 	if (handle->info->capacity == 0) {
824 		notify_io_request(request, B_DEV_NO_MEDIA);
825 		return B_DEV_NO_MEDIA;
826 	}
827 
828 	return handle->info->io_scheduler->ScheduleRequest(request);
829 }
830 
831 
832 static status_t
833 cd_ioctl(void* cookie, uint32 op, void* buffer, size_t length)
834 {
835 	cd_handle* handle = (cd_handle*)cookie;
836 	cd_driver_info *info = handle->info;
837 
838 	TRACE("ioctl(op = %lu)\n", op);
839 
840 	switch (op) {
841 		case B_GET_DEVICE_SIZE:
842 		{
843 			status_t status = update_capacity(info);
844 			if (status != B_OK)
845 				return status;
846 
847 			size_t size = info->capacity * info->block_size;
848 			return user_memcpy(buffer, &size, sizeof(size_t));
849 		}
850 
851 		case B_GET_GEOMETRY:
852 		{
853 			if (buffer == NULL /*|| length != sizeof(device_geometry)*/)
854 				return B_BAD_VALUE;
855 
856 		 	device_geometry geometry;
857 			status_t status = get_geometry(handle, &geometry);
858 			if (status != B_OK)
859 				return status;
860 
861 			return user_memcpy(buffer, &geometry, sizeof(device_geometry));
862 		}
863 
864 		case B_GET_ICON_NAME:
865 			return user_strlcpy((char*)buffer, "devices/drive-optical",
866 				B_FILE_NAME_LENGTH);
867 
868 		case B_GET_VECTOR_ICON:
869 		{
870 			device_icon iconData;
871 			if (length != sizeof(device_icon))
872 				return B_BAD_VALUE;
873 			if (user_memcpy(&iconData, buffer, sizeof(device_icon)) != B_OK)
874 				return B_BAD_ADDRESS;
875 
876 			if (iconData.icon_size >= (int32)sizeof(kCDIcon)) {
877 				if (user_memcpy(iconData.icon_data, kCDIcon,
878 						sizeof(kCDIcon)) != B_OK)
879 					return B_BAD_ADDRESS;
880 			}
881 
882 			iconData.icon_size = sizeof(kCDIcon);
883 			return user_memcpy(buffer, &iconData, sizeof(device_icon));
884 		}
885 
886 		case B_SCSI_GET_TOC:
887 			// TODO: we pass a user buffer here!
888 			return get_toc(info, (scsi_toc *)buffer);
889 
890 		case B_EJECT_DEVICE:
891 		case B_SCSI_EJECT:
892 			return load_eject(info, false);
893 
894 		case B_LOAD_MEDIA:
895 			return load_eject(info, true);
896 
897 		case B_SCSI_GET_POSITION:
898 		{
899 			if (buffer == NULL)
900 				return B_BAD_VALUE;
901 
902 			scsi_position position;
903 			status_t status = get_position(info, &position);
904 			if (status != B_OK)
905 				return status;
906 
907 			return user_memcpy(buffer, &position, sizeof(scsi_position));
908 		}
909 
910 		case B_SCSI_GET_VOLUME:
911 			// TODO: we pass a user buffer here!
912 			return get_set_volume(info, (scsi_volume *)buffer, false);
913 		case B_SCSI_SET_VOLUME:
914 			// TODO: we pass a user buffer here!
915 			return get_set_volume(info, (scsi_volume *)buffer, true);
916 
917 		case B_SCSI_PLAY_TRACK:
918 		{
919 			scsi_play_track track;
920 			if (user_memcpy(&track, buffer, sizeof(scsi_play_track)) != B_OK)
921 				return B_BAD_ADDRESS;
922 
923 			return play_track_index(info, &track);
924 		}
925 		case B_SCSI_PLAY_POSITION:
926 		{
927 			scsi_play_position position;
928 			if (user_memcpy(&position, buffer, sizeof(scsi_play_position))
929 					!= B_OK)
930 				return B_BAD_ADDRESS;
931 
932 			return play_msf(info, &position);
933 		}
934 
935 		case B_SCSI_STOP_AUDIO:
936 			return stop_audio(info);
937 		case B_SCSI_PAUSE_AUDIO:
938 			return pause_resume(info, false);
939 		case B_SCSI_RESUME_AUDIO:
940 			return pause_resume(info, true);
941 
942 		case B_SCSI_SCAN:
943 		{
944 			scsi_scan scanBuffer;
945 			if (user_memcpy(&scanBuffer, buffer, sizeof(scsi_scan)) != B_OK)
946 				return B_BAD_ADDRESS;
947 
948 			return scan(info, &scanBuffer);
949 		}
950 		case B_SCSI_READ_CD:
951 			// TODO: we pass a user buffer here!
952 			return read_cd(info, (scsi_read_cd *)buffer);
953 
954 		default:
955 			return sSCSIPeripheral->ioctl(handle->scsi_periph_handle, op,
956 				buffer, length);
957 	}
958 }
959 
960 
961 //	#pragma mark - scsi_periph callbacks
962 
963 
964 static void
965 cd_set_capacity(cd_driver_info* info, uint64 capacity, uint32 blockSize)
966 {
967 	TRACE("cd_set_capacity(info = %p, capacity = %Ld, blockSize = %ld)\n",
968 		info, capacity, blockSize);
969 
970 	// get log2, if possible
971 	uint32 blockShift = log2(blockSize);
972 
973 	if ((1UL << blockShift) != blockSize)
974 		blockShift = 0;
975 
976 	if (info->block_size != blockSize) {
977 		if (capacity == 0) {
978 			// there is obviously no medium in the drive, don't try to update
979 			// the DMA resource
980 			return;
981 		}
982 
983 		if (info->block_size != 0) {
984 			dprintf("old %ld, new %ld\n", info->block_size, blockSize);
985 			panic("updating DMAResource not yet implemented...");
986 		}
987 
988 		// TODO: we need to replace the DMAResource in our IOScheduler
989 		status_t status = info->dma_resource->Init(info->node, blockSize, 1024,
990 			32);
991 		if (status != B_OK)
992 			panic("initializing DMAResource failed: %s", strerror(status));
993 
994 		// Allocate the I/O scheduler. If there seems to be sufficient memory
995 		// we use an IOCache, since that adds caching at the lowest I/O layer
996 		// and thus dramatically reduces I/O operations and seeks. The
997 		// disadvantage is that it increases free memory (physical pages)
998 		// fragmentation, which makes large contiguous allocations more likely
999 		// to fail.
1000 		size_t freeMemory = vm_page_num_free_pages();
1001 		if (freeMemory > 180 * 1024 * 1024 / B_PAGE_SIZE) {
1002 			info->io_scheduler = new(std::nothrow) IOCache(info->dma_resource,
1003 				1024 * 1024);
1004 		} else {
1005 			dprintf("scsi_cd: Using IOSchedulerSimple instead of IOCache to "
1006 				"avoid memory allocation issues.\n");
1007 			info->io_scheduler = new(std::nothrow) IOSchedulerSimple(
1008 				info->dma_resource);
1009 		}
1010 
1011 		if (info->io_scheduler == NULL)
1012 			panic("allocating IOScheduler failed.");
1013 
1014 		// TODO: use whole device name here
1015 		status = info->io_scheduler->Init("scsi");
1016 		if (status != B_OK)
1017 			panic("initializing IOScheduler failed: %s", strerror(status));
1018 
1019 		info->io_scheduler->SetCallback(do_io, info);
1020 		info->block_size = blockSize;
1021 	}
1022 
1023 	if (info->original_capacity != capacity && info->io_scheduler != NULL) {
1024 		info->original_capacity = capacity;
1025 
1026 		// For CDs, it's obviously relatively normal that they report a larger
1027 		// capacity than it can actually address. Therefore we'll manually
1028 		// correct the value here.
1029 		test_capacity(info);
1030 
1031 		info->io_scheduler->SetDeviceCapacity(info->capacity * blockSize);
1032 	}
1033 }
1034 
1035 
1036 static void
1037 cd_media_changed(cd_driver_info* info, scsi_ccb* request)
1038 {
1039 	// do a capacity check
1040 	// TODO: is this a good idea (e.g. if this is an empty CD)?
1041 	info->original_capacity = 0;
1042 	info->capacity = 0;
1043 	sSCSIPeripheral->check_capacity(info->scsi_periph_device, request);
1044 
1045 	if (info->io_scheduler != NULL)
1046 		info->io_scheduler->MediaChanged();
1047 }
1048 
1049 
1050 scsi_periph_callbacks callbacks = {
1051 	(void (*)(periph_device_cookie, uint64, uint32))cd_set_capacity,
1052 	(void (*)(periph_device_cookie, scsi_ccb *))cd_media_changed
1053 };
1054 
1055 
1056 //	#pragma mark - driver module API
1057 
1058 
1059 static float
1060 cd_supports_device(device_node* parent)
1061 {
1062 	const char* bus;
1063 	uint8 deviceType;
1064 
1065 	// make sure parent is really the SCSI bus manager
1066 	if (sDeviceManager->get_attr_string(parent, B_DEVICE_BUS, &bus, false))
1067 		return -1;
1068 
1069 	if (strcmp(bus, "scsi"))
1070 		return 0.0;
1071 
1072 	// check whether it's really a CD-ROM or WORM
1073 	if (sDeviceManager->get_attr_uint8(parent, SCSI_DEVICE_TYPE_ITEM,
1074 			&deviceType, true) != B_OK
1075 		|| (deviceType != scsi_dev_CDROM && deviceType != scsi_dev_WORM))
1076 		return 0.0;
1077 
1078 	return 0.6;
1079 }
1080 
1081 
1082 /*!	Called whenever a new device was added to system;
1083 	if we really support it, we create a new node that gets
1084 	server by the block_io module
1085 */
1086 static status_t
1087 cd_register_device(device_node* node)
1088 {
1089 	const scsi_res_inquiry* deviceInquiry = NULL;
1090 	size_t inquiryLength;
1091 	uint32 maxBlocks;
1092 
1093 	// get inquiry data
1094 	if (sDeviceManager->get_attr_raw(node, SCSI_DEVICE_INQUIRY_ITEM,
1095 			(const void**)&deviceInquiry, &inquiryLength, true) != B_OK
1096 		|| inquiryLength < sizeof(deviceInquiry))
1097 		return B_ERROR;
1098 
1099 	// get block limit of underlying hardware to lower it (if necessary)
1100 	if (sDeviceManager->get_attr_uint32(node, B_DMA_MAX_TRANSFER_BLOCKS,
1101 			&maxBlocks, true) != B_OK)
1102 		maxBlocks = INT_MAX;
1103 
1104 	// using 10 byte commands, at most 0xffff blocks can be transmitted at once
1105 	// (sadly, we cannot update this value later on if only 6 byte commands
1106 	//  are supported, but the block_io module can live with that)
1107 	maxBlocks = min_c(maxBlocks, 0xffff);
1108 
1109 	// ready to register
1110 	device_attr attrs[] = {
1111 		{"removable", B_UINT8_TYPE, {ui8: deviceInquiry->removable_medium}},
1112 		{B_DMA_MAX_TRANSFER_BLOCKS, B_UINT32_TYPE, {ui32: maxBlocks}},
1113 		{ NULL }
1114 	};
1115 
1116 	return sDeviceManager->register_node(node, SCSI_CD_DRIVER_MODULE_NAME,
1117 		attrs, NULL, NULL);
1118 }
1119 
1120 
1121 static status_t
1122 cd_init_driver(device_node* node, void** _cookie)
1123 {
1124 	TRACE("cd_init_driver\n");
1125 
1126 	uint8 removable;
1127 	status_t status = sDeviceManager->get_attr_uint8(node, "removable",
1128 		&removable, false);
1129 	if (status != B_OK)
1130 		return status;
1131 
1132 	cd_driver_info* info = (cd_driver_info*)malloc(sizeof(cd_driver_info));
1133 	if (info == NULL)
1134 		return B_NO_MEMORY;
1135 
1136 	memset(info, 0, sizeof(cd_driver_info));
1137 
1138 	info->dma_resource = new(std::nothrow) DMAResource;
1139 	if (info->dma_resource == NULL) {
1140 		free(info);
1141 		return B_NO_MEMORY;
1142 	}
1143 
1144 	info->node = node;
1145 	info->removable = removable;
1146 
1147 	// set capacity to zero, so it get checked on first opened handle
1148 	info->original_capacity = 0;
1149 	info->capacity = 0;
1150 	info->block_size = 0;
1151 
1152 	sDeviceManager->get_attr_uint8(node, SCSI_DEVICE_TYPE_ITEM,
1153 		&info->device_type, true);
1154 
1155 	device_node *parent = sDeviceManager->get_parent_node(node);
1156 	sDeviceManager->get_driver(parent, (driver_module_info**)&info->scsi,
1157 		(void**)&info->scsi_device);
1158 	sDeviceManager->put_node(parent);
1159 
1160 	status = sSCSIPeripheral->register_device((periph_device_cookie)info,
1161 		&callbacks, info->scsi_device, info->scsi, info->node,
1162 		info->removable, 10, &info->scsi_periph_device);
1163 	if (status != B_OK) {
1164 		free(info);
1165 		return status;
1166 	}
1167 
1168 	*_cookie = info;
1169 	return B_OK;
1170 }
1171 
1172 
1173 static void
1174 cd_uninit_driver(void* _cookie)
1175 {
1176 	cd_driver_info* info = (cd_driver_info*)_cookie;
1177 
1178 	sSCSIPeripheral->unregister_device(info->scsi_periph_device);
1179 	free(info);
1180 }
1181 
1182 
1183 static status_t
1184 cd_register_child_devices(void* _cookie)
1185 {
1186 	cd_driver_info* info = (cd_driver_info*)_cookie;
1187 
1188 	char* name = sSCSIPeripheral->compose_device_name(info->node, "disk/scsi");
1189 	if (name == NULL)
1190 		return B_ERROR;
1191 
1192 	status_t status = sDeviceManager->publish_device(info->node, name,
1193 		SCSI_CD_DEVICE_MODULE_NAME);
1194 
1195 	free(name);
1196 	return status;
1197 }
1198 
1199 
1200 module_dependency module_dependencies[] = {
1201 	{SCSI_PERIPH_MODULE_NAME, (module_info**)&sSCSIPeripheral},
1202 	{B_DEVICE_MANAGER_MODULE_NAME, (module_info**)&sDeviceManager},
1203 	{}
1204 };
1205 
1206 struct device_module_info sSCSICDDevice = {
1207 	{
1208 		SCSI_CD_DEVICE_MODULE_NAME,
1209 		0,
1210 		NULL
1211 	},
1212 
1213 	cd_init_device,
1214 	cd_uninit_device,
1215 	NULL,	// remove,
1216 
1217 	cd_open,
1218 	cd_close,
1219 	cd_free,
1220 	cd_read,
1221 	cd_write,
1222 	cd_io,
1223 	cd_ioctl,
1224 
1225 	NULL,	// select
1226 	NULL,	// deselect
1227 };
1228 
1229 struct driver_module_info sSCSICDDriver = {
1230 	{
1231 		SCSI_CD_DRIVER_MODULE_NAME,
1232 		0,
1233 		NULL
1234 	},
1235 
1236 	cd_supports_device,
1237 	cd_register_device,
1238 	cd_init_driver,
1239 	cd_uninit_driver,
1240 	cd_register_child_devices,
1241 	NULL,	// rescan
1242 	NULL,	// removed
1243 };
1244 
1245 module_info* modules[] = {
1246 	(module_info*)&sSCSICDDriver,
1247 	(module_info*)&sSCSICDDevice,
1248 	NULL
1249 };
1250