xref: /dragonfly/sbin/camcontrol/camcontrol.c (revision f02303f9)
1 /*
2  * Copyright (c) 1997, 1998, 1999, 2000, 2001, 2002 Kenneth D. Merry
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. The name of the author may not be used to endorse or promote products
14  *    derived from this software without specific prior written permission.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  *
28  * $FreeBSD: src/sbin/camcontrol/camcontrol.c,v 1.21.2.13 2003/01/08 17:55:02 njl Exp $
29  * $DragonFly: src/sbin/camcontrol/camcontrol.c,v 1.4 2007/01/30 16:03:04 swildner Exp $
30  */
31 
32 #include <sys/ioctl.h>
33 #include <sys/types.h>
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <unistd.h>
38 #include <fcntl.h>
39 #include <ctype.h>
40 #include <err.h>
41 
42 #include <cam/cam.h>
43 #include <cam/cam_debug.h>
44 #include <cam/cam_ccb.h>
45 #include <cam/scsi/scsi_all.h>
46 #include <cam/scsi/scsi_da.h>
47 #include <cam/scsi/scsi_pass.h>
48 #include <cam/scsi/scsi_message.h>
49 #include <camlib.h>
50 #include "camcontrol.h"
51 
52 typedef enum {
53 	CAM_CMD_NONE		= 0x00000000,
54 	CAM_CMD_DEVLIST		= 0x00000001,
55 	CAM_CMD_TUR		= 0x00000002,
56 	CAM_CMD_INQUIRY		= 0x00000003,
57 	CAM_CMD_STARTSTOP	= 0x00000004,
58 	CAM_CMD_RESCAN		= 0x00000005,
59 	CAM_CMD_READ_DEFECTS	= 0x00000006,
60 	CAM_CMD_MODE_PAGE	= 0x00000007,
61 	CAM_CMD_SCSI_CMD	= 0x00000008,
62 	CAM_CMD_DEVTREE		= 0x00000009,
63 	CAM_CMD_USAGE		= 0x0000000a,
64 	CAM_CMD_DEBUG		= 0x0000000b,
65 	CAM_CMD_RESET		= 0x0000000c,
66 	CAM_CMD_FORMAT		= 0x0000000d,
67 	CAM_CMD_TAG		= 0x0000000e,
68 	CAM_CMD_RATE		= 0x0000000f,
69 	CAM_CMD_DETACH		= 0x00000010,
70 } cam_cmdmask;
71 
72 typedef enum {
73 	CAM_ARG_NONE		= 0x00000000,
74 	CAM_ARG_VERBOSE		= 0x00000001,
75 	CAM_ARG_DEVICE		= 0x00000002,
76 	CAM_ARG_BUS		= 0x00000004,
77 	CAM_ARG_TARGET		= 0x00000008,
78 	CAM_ARG_LUN		= 0x00000010,
79 	CAM_ARG_EJECT		= 0x00000020,
80 	CAM_ARG_UNIT		= 0x00000040,
81 	CAM_ARG_FORMAT_BLOCK	= 0x00000080,
82 	CAM_ARG_FORMAT_BFI	= 0x00000100,
83 	CAM_ARG_FORMAT_PHYS	= 0x00000200,
84 	CAM_ARG_PLIST		= 0x00000400,
85 	CAM_ARG_GLIST		= 0x00000800,
86 	CAM_ARG_GET_SERIAL	= 0x00001000,
87 	CAM_ARG_GET_STDINQ	= 0x00002000,
88 	CAM_ARG_GET_XFERRATE	= 0x00004000,
89 	CAM_ARG_INQ_MASK	= 0x00007000,
90 	CAM_ARG_MODE_EDIT	= 0x00008000,
91 	CAM_ARG_PAGE_CNTL	= 0x00010000,
92 	CAM_ARG_TIMEOUT		= 0x00020000,
93 	CAM_ARG_CMD_IN		= 0x00040000,
94 	CAM_ARG_CMD_OUT		= 0x00080000,
95 	CAM_ARG_DBD		= 0x00100000,
96 	CAM_ARG_ERR_RECOVER	= 0x00200000,
97 	CAM_ARG_RETRIES		= 0x00400000,
98 	CAM_ARG_START_UNIT	= 0x00800000,
99 	CAM_ARG_DEBUG_INFO	= 0x01000000,
100 	CAM_ARG_DEBUG_TRACE	= 0x02000000,
101 	CAM_ARG_DEBUG_SUBTRACE	= 0x04000000,
102 	CAM_ARG_DEBUG_CDB	= 0x08000000,
103 	CAM_ARG_DEBUG_XPT	= 0x10000000,
104 	CAM_ARG_DEBUG_PERIPH	= 0x20000000,
105 } cam_argmask;
106 
107 struct camcontrol_opts {
108 	const char 	*optname;
109 	cam_cmdmask	cmdnum;
110 	cam_argmask	argnum;
111 	const char	*subopt;
112 };
113 
114 #ifndef MINIMALISTIC
115 static const char scsicmd_opts[] = "c:i:o:";
116 static const char readdefect_opts[] = "f:GP";
117 static const char negotiate_opts[] = "acD:O:qR:T:UW:";
118 #endif
119 
120 struct camcontrol_opts option_table[] = {
121 #ifndef MINIMALISTIC
122 	{"tur", CAM_CMD_TUR, CAM_ARG_NONE, NULL},
123 	{"inquiry", CAM_CMD_INQUIRY, CAM_ARG_NONE, "DSR"},
124 	{"start", CAM_CMD_STARTSTOP, CAM_ARG_START_UNIT, NULL},
125 	{"stop", CAM_CMD_STARTSTOP, CAM_ARG_NONE, NULL},
126 	{"load", CAM_CMD_STARTSTOP, CAM_ARG_START_UNIT | CAM_ARG_EJECT, NULL},
127 	{"eject", CAM_CMD_STARTSTOP, CAM_ARG_EJECT, NULL},
128 #endif /* MINIMALISTIC */
129 	{"rescan", CAM_CMD_RESCAN, CAM_ARG_NONE, NULL},
130 	{"reset", CAM_CMD_RESET, CAM_ARG_NONE, NULL},
131 #ifndef MINIMALISTIC
132 	{"cmd", CAM_CMD_SCSI_CMD, CAM_ARG_NONE, scsicmd_opts},
133 	{"command", CAM_CMD_SCSI_CMD, CAM_ARG_NONE, scsicmd_opts},
134 	{"defects", CAM_CMD_READ_DEFECTS, CAM_ARG_NONE, readdefect_opts},
135 	{"defectlist", CAM_CMD_READ_DEFECTS, CAM_ARG_NONE, readdefect_opts},
136 #endif /* MINIMALISTIC */
137 	{"devlist", CAM_CMD_DEVTREE, CAM_ARG_NONE, NULL},
138 #ifndef MINIMALISTIC
139 	{"periphlist", CAM_CMD_DEVLIST, CAM_ARG_NONE, NULL},
140 	{"modepage", CAM_CMD_MODE_PAGE, CAM_ARG_NONE, "bdelm:P:"},
141 	{"tags", CAM_CMD_TAG, CAM_ARG_NONE, "N:q"},
142 	{"negotiate", CAM_CMD_RATE, CAM_ARG_NONE, negotiate_opts},
143 	{"rate", CAM_CMD_RATE, CAM_ARG_NONE, negotiate_opts},
144 	{"debug", CAM_CMD_DEBUG, CAM_ARG_NONE, "IPTSXc"},
145 	{"format", CAM_CMD_FORMAT, CAM_ARG_NONE, "qwy"},
146 #endif /* MINIMALISTIC */
147 	{"help", CAM_CMD_USAGE, CAM_ARG_NONE, NULL},
148 	{"-?", CAM_CMD_USAGE, CAM_ARG_NONE, NULL},
149 	{"-h", CAM_CMD_USAGE, CAM_ARG_NONE, NULL},
150 	{NULL, 0, 0, NULL}
151 };
152 
153 typedef enum {
154 	CC_OR_NOT_FOUND,
155 	CC_OR_AMBIGUOUS,
156 	CC_OR_FOUND
157 } camcontrol_optret;
158 
159 cam_cmdmask cmdlist;
160 cam_argmask arglist;
161 int bus, target, lun;
162 
163 
164 camcontrol_optret	getoption(char *, cam_cmdmask *, cam_argmask *,
165 				  const char **);
166 #ifndef MINIMALISTIC
167 static int	getdevlist(struct cam_device *);
168 static int	getdevtree(void);
169 static int	testunitready(struct cam_device *, int, int, int);
170 static int	scsistart(struct cam_device *, int, int, int, int);
171 static int	scsidoinquiry(struct cam_device *, int, char **, char *, int,
172 		int);
173 static int	scsiinquiry(struct cam_device *, int, int);
174 static int	scsiserial(struct cam_device *, int, int);
175 static int	scsixferrate(struct cam_device *);
176 #endif /* MINIMALISTIC */
177 static int	parse_btl(char *, int *, int *, int *, cam_argmask *);
178 static int	dorescan_or_reset(int, char **, int);
179 static int	rescan_or_reset_bus(int, int);
180 static int	scanlun_or_reset_dev(int, int, int, int);
181 #ifndef MINIMALISTIC
182 static int	readdefects(struct cam_device *, int, char **, char *, int,
183 		int);
184 static void	modepage(struct cam_device *, int, char **, char *, int, int);
185 static int	scsicmd(struct cam_device *, int, char **, char *, int, int);
186 static int	tagcontrol(struct cam_device *, int, char **, char *);
187 static void	cts_print(struct cam_device *device,
188 		struct ccb_trans_settings *);
189 static void	cpi_print(struct ccb_pathinq *);
190 static int	get_cpi(struct cam_device *, struct ccb_pathinq *);
191 static int	get_print_cts(struct cam_device *, int, int,
192 			 struct ccb_trans_settings *);
193 static int	ratecontrol(struct cam_device *, int, int, int, char **,
194 		char *);
195 static int	scsiformat(struct cam_device *, int, char **, char *, int, int);
196 #endif /* MINIMALISTIC */
197 
198 
199 camcontrol_optret
200 getoption(char *arg, cam_cmdmask *cmdnum, cam_argmask *argnum,
201 	  const char **subopt)
202 {
203 	struct camcontrol_opts *opts;
204 	int num_matches = 0;
205 
206 	for (opts = option_table; (opts != NULL) && (opts->optname != NULL);
207 	     opts++) {
208 		if (strncmp(opts->optname, arg, strlen(arg)) == 0) {
209 			*cmdnum = opts->cmdnum;
210 			*argnum = opts->argnum;
211 			*subopt = opts->subopt;
212 			if (++num_matches > 1)
213 				return(CC_OR_AMBIGUOUS);
214 		}
215 	}
216 
217 	if (num_matches > 0)
218 		return(CC_OR_FOUND);
219 	else
220 		return(CC_OR_NOT_FOUND);
221 }
222 
223 #ifndef MINIMALISTIC
224 static int
225 getdevlist(struct cam_device *device)
226 {
227 	union ccb *ccb;
228 	char status[32];
229 	int error = 0;
230 
231 	ccb = cam_getccb(device);
232 
233 	ccb->ccb_h.func_code = XPT_GDEVLIST;
234 	ccb->ccb_h.flags = CAM_DIR_NONE;
235 	ccb->ccb_h.retry_count = 1;
236 	ccb->cgdl.index = 0;
237 	ccb->cgdl.status = CAM_GDEVLIST_MORE_DEVS;
238 	while (ccb->cgdl.status == CAM_GDEVLIST_MORE_DEVS) {
239 		if (cam_send_ccb(device, ccb) < 0) {
240 			perror("error getting device list");
241 			cam_freeccb(ccb);
242 			return(1);
243 		}
244 
245 		status[0] = '\0';
246 
247 		switch (ccb->cgdl.status) {
248 			case CAM_GDEVLIST_MORE_DEVS:
249 				strcpy(status, "MORE");
250 				break;
251 			case CAM_GDEVLIST_LAST_DEVICE:
252 				strcpy(status, "LAST");
253 				break;
254 			case CAM_GDEVLIST_LIST_CHANGED:
255 				strcpy(status, "CHANGED");
256 				break;
257 			case CAM_GDEVLIST_ERROR:
258 				strcpy(status, "ERROR");
259 				error = 1;
260 				break;
261 		}
262 
263 		fprintf(stdout, "%s%d:  generation: %d index: %d status: %s\n",
264 			ccb->cgdl.periph_name,
265 			ccb->cgdl.unit_number,
266 			ccb->cgdl.generation,
267 			ccb->cgdl.index,
268 			status);
269 
270 		/*
271 		 * If the list has changed, we need to start over from the
272 		 * beginning.
273 		 */
274 		if (ccb->cgdl.status == CAM_GDEVLIST_LIST_CHANGED)
275 			ccb->cgdl.index = 0;
276 	}
277 
278 	cam_freeccb(ccb);
279 
280 	return(error);
281 }
282 #endif /* MINIMALISTIC */
283 
284 static int
285 getdevtree(void)
286 {
287 	union ccb ccb;
288 	int bufsize, fd;
289 	unsigned int i;
290 	int need_close = 0;
291 	int error = 0;
292 	int skip_device = 0;
293 
294 	if ((fd = open(XPT_DEVICE, O_RDWR)) == -1) {
295 		warn("couldn't open %s", XPT_DEVICE);
296 		return(1);
297 	}
298 
299 	bzero(&(&ccb.ccb_h)[1],
300 	      sizeof(struct ccb_dev_match) - sizeof(struct ccb_hdr));
301 
302 	ccb.ccb_h.func_code = XPT_DEV_MATCH;
303 	bufsize = sizeof(struct dev_match_result) * 100;
304 	ccb.cdm.match_buf_len = bufsize;
305 	ccb.cdm.matches = (struct dev_match_result *)malloc(bufsize);
306 	if (ccb.cdm.matches == NULL) {
307 		warnx("can't malloc memory for matches");
308 		close(fd);
309 		return(1);
310 	}
311 	ccb.cdm.num_matches = 0;
312 
313 	/*
314 	 * We fetch all nodes, since we display most of them in the default
315 	 * case, and all in the verbose case.
316 	 */
317 	ccb.cdm.num_patterns = 0;
318 	ccb.cdm.pattern_buf_len = 0;
319 
320 	/*
321 	 * We do the ioctl multiple times if necessary, in case there are
322 	 * more than 100 nodes in the EDT.
323 	 */
324 	do {
325 		if (ioctl(fd, CAMIOCOMMAND, &ccb) == -1) {
326 			warn("error sending CAMIOCOMMAND ioctl");
327 			error = 1;
328 			break;
329 		}
330 
331 		if ((ccb.ccb_h.status != CAM_REQ_CMP)
332 		 || ((ccb.cdm.status != CAM_DEV_MATCH_LAST)
333 		    && (ccb.cdm.status != CAM_DEV_MATCH_MORE))) {
334 			warnx("got CAM error %#x, CDM error %d\n",
335 			      ccb.ccb_h.status, ccb.cdm.status);
336 			error = 1;
337 			break;
338 		}
339 
340 		for (i = 0; i < ccb.cdm.num_matches; i++) {
341 			switch (ccb.cdm.matches[i].type) {
342 			case DEV_MATCH_BUS: {
343 				struct bus_match_result *bus_result;
344 
345 				/*
346 				 * Only print the bus information if the
347 				 * user turns on the verbose flag.
348 				 */
349 				if ((arglist & CAM_ARG_VERBOSE) == 0)
350 					break;
351 
352 				bus_result =
353 					&ccb.cdm.matches[i].result.bus_result;
354 
355 				if (need_close) {
356 					fprintf(stdout, ")\n");
357 					need_close = 0;
358 				}
359 
360 				fprintf(stdout, "scbus%d on %s%d bus %d:\n",
361 					bus_result->path_id,
362 					bus_result->dev_name,
363 					bus_result->unit_number,
364 					bus_result->bus_id);
365 				break;
366 			}
367 			case DEV_MATCH_DEVICE: {
368 				struct device_match_result *dev_result;
369 				char vendor[16], product[48], revision[16];
370 				char tmpstr[256];
371 
372 				dev_result =
373 				     &ccb.cdm.matches[i].result.device_result;
374 
375 				if ((dev_result->flags
376 				     & DEV_RESULT_UNCONFIGURED)
377 				 && ((arglist & CAM_ARG_VERBOSE) == 0)) {
378 					skip_device = 1;
379 					break;
380 				} else
381 					skip_device = 0;
382 
383 				cam_strvis(vendor, dev_result->inq_data.vendor,
384 					   sizeof(dev_result->inq_data.vendor),
385 					   sizeof(vendor));
386 				cam_strvis(product,
387 					   dev_result->inq_data.product,
388 					   sizeof(dev_result->inq_data.product),
389 					   sizeof(product));
390 				cam_strvis(revision,
391 					   dev_result->inq_data.revision,
392 					  sizeof(dev_result->inq_data.revision),
393 					   sizeof(revision));
394 				sprintf(tmpstr, "<%s %s %s>", vendor, product,
395 					revision);
396 				if (need_close) {
397 					fprintf(stdout, ")\n");
398 					need_close = 0;
399 				}
400 
401 				fprintf(stdout, "%-33s  at scbus%d "
402 					"target %d lun %d (",
403 					tmpstr,
404 					dev_result->path_id,
405 					dev_result->target_id,
406 					dev_result->target_lun);
407 
408 				need_close = 1;
409 
410 				break;
411 			}
412 			case DEV_MATCH_PERIPH: {
413 				struct periph_match_result *periph_result;
414 
415 				periph_result =
416 				      &ccb.cdm.matches[i].result.periph_result;
417 
418 				if (skip_device != 0)
419 					break;
420 
421 				if (need_close > 1)
422 					fprintf(stdout, ",");
423 
424 				fprintf(stdout, "%s%d",
425 					periph_result->periph_name,
426 					periph_result->unit_number);
427 
428 				need_close++;
429 				break;
430 			}
431 			default:
432 				fprintf(stdout, "unknown match type\n");
433 				break;
434 			}
435 		}
436 
437 	} while ((ccb.ccb_h.status == CAM_REQ_CMP)
438 		&& (ccb.cdm.status == CAM_DEV_MATCH_MORE));
439 
440 	if (need_close)
441 		fprintf(stdout, ")\n");
442 
443 	close(fd);
444 
445 	return(error);
446 }
447 
448 #ifndef MINIMALISTIC
449 static int
450 testunitready(struct cam_device *device, int retry_count, int timeout,
451 	      int quiet)
452 {
453 	int error = 0;
454 	union ccb *ccb;
455 
456 	ccb = cam_getccb(device);
457 
458 	scsi_test_unit_ready(&ccb->csio,
459 			     /* retries */ retry_count,
460 			     /* cbfcnp */ NULL,
461 			     /* tag_action */ MSG_SIMPLE_Q_TAG,
462 			     /* sense_len */ SSD_FULL_SIZE,
463 			     /* timeout */ timeout ? timeout : 5000);
464 
465 	/* Disable freezing the device queue */
466 	ccb->ccb_h.flags |= CAM_DEV_QFRZDIS;
467 
468 	if (arglist & CAM_ARG_ERR_RECOVER)
469 		ccb->ccb_h.flags |= CAM_PASS_ERR_RECOVER;
470 
471 	if (cam_send_ccb(device, ccb) < 0) {
472 		if (quiet == 0)
473 			perror("error sending test unit ready");
474 
475 		if (arglist & CAM_ARG_VERBOSE) {
476 		 	if ((ccb->ccb_h.status & CAM_STATUS_MASK) ==
477 			    CAM_SCSI_STATUS_ERROR)
478 				scsi_sense_print(device, &ccb->csio, stderr);
479 			else
480 				fprintf(stderr, "CAM status is %#x\n",
481 					ccb->ccb_h.status);
482 		}
483 
484 		cam_freeccb(ccb);
485 		return(1);
486 	}
487 
488 	if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
489 		if (quiet == 0)
490 			fprintf(stdout, "Unit is ready\n");
491 	} else {
492 		if (quiet == 0)
493 			fprintf(stdout, "Unit is not ready\n");
494 		error = 1;
495 
496 		if (arglist & CAM_ARG_VERBOSE) {
497 		 	if ((ccb->ccb_h.status & CAM_STATUS_MASK) ==
498 			    CAM_SCSI_STATUS_ERROR)
499 				scsi_sense_print(device, &ccb->csio, stderr);
500 			else
501 				fprintf(stderr, "CAM status is %#x\n",
502 					ccb->ccb_h.status);
503 		}
504 	}
505 
506 	cam_freeccb(ccb);
507 
508 	return(error);
509 }
510 
511 static int
512 scsistart(struct cam_device *device, int startstop, int loadeject,
513 	  int retry_count, int timeout)
514 {
515 	union ccb *ccb;
516 	int error = 0;
517 
518 	ccb = cam_getccb(device);
519 
520 	/*
521 	 * If we're stopping, send an ordered tag so the drive in question
522 	 * will finish any previously queued writes before stopping.  If
523 	 * the device isn't capable of tagged queueing, or if tagged
524 	 * queueing is turned off, the tag action is a no-op.
525 	 */
526 	scsi_start_stop(&ccb->csio,
527 			/* retries */ retry_count,
528 			/* cbfcnp */ NULL,
529 			/* tag_action */ startstop ? MSG_SIMPLE_Q_TAG :
530 						     MSG_ORDERED_Q_TAG,
531 			/* start/stop */ startstop,
532 			/* load_eject */ loadeject,
533 			/* immediate */ 0,
534 			/* sense_len */ SSD_FULL_SIZE,
535 			/* timeout */ timeout ? timeout : 120000);
536 
537 	/* Disable freezing the device queue */
538 	ccb->ccb_h.flags |= CAM_DEV_QFRZDIS;
539 
540 	if (arglist & CAM_ARG_ERR_RECOVER)
541 		ccb->ccb_h.flags |= CAM_PASS_ERR_RECOVER;
542 
543 	if (cam_send_ccb(device, ccb) < 0) {
544 		perror("error sending start unit");
545 
546 		if (arglist & CAM_ARG_VERBOSE) {
547 		 	if ((ccb->ccb_h.status & CAM_STATUS_MASK) ==
548 			    CAM_SCSI_STATUS_ERROR)
549 				scsi_sense_print(device, &ccb->csio, stderr);
550 			else
551 				fprintf(stderr, "CAM status is %#x\n",
552 					ccb->ccb_h.status);
553 		}
554 
555 		cam_freeccb(ccb);
556 		return(1);
557 	}
558 
559 	if ((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP)
560 		if (startstop) {
561 			fprintf(stdout, "Unit started successfully");
562 			if (loadeject)
563 				fprintf(stdout,", Media loaded\n");
564 			else
565 				fprintf(stdout,"\n");
566 		} else {
567 			fprintf(stdout, "Unit stopped successfully");
568 			if (loadeject)
569 				fprintf(stdout, ", Media ejected\n");
570 			else
571 				fprintf(stdout, "\n");
572 		}
573 	else {
574 		error = 1;
575 		if (startstop)
576 			fprintf(stdout,
577 				"Error received from start unit command\n");
578 		else
579 			fprintf(stdout,
580 				"Error received from stop unit command\n");
581 
582 		if (arglist & CAM_ARG_VERBOSE) {
583 		 	if ((ccb->ccb_h.status & CAM_STATUS_MASK) ==
584 			    CAM_SCSI_STATUS_ERROR)
585 				scsi_sense_print(device, &ccb->csio, stderr);
586 			else
587 				fprintf(stderr, "CAM status is %#x\n",
588 					ccb->ccb_h.status);
589 		}
590 	}
591 
592 	cam_freeccb(ccb);
593 
594 	return(error);
595 }
596 
597 static int
598 scsidoinquiry(struct cam_device *device, int argc, char **argv,
599 	      char *combinedopt, int retry_count, int timeout)
600 {
601 	int c;
602 	int error = 0;
603 
604 	while ((c = getopt(argc, argv, combinedopt)) != -1) {
605 		switch(c) {
606 		case 'D':
607 			arglist |= CAM_ARG_GET_STDINQ;
608 			break;
609 		case 'R':
610 			arglist |= CAM_ARG_GET_XFERRATE;
611 			break;
612 		case 'S':
613 			arglist |= CAM_ARG_GET_SERIAL;
614 			break;
615 		default:
616 			break;
617 		}
618 	}
619 
620 	/*
621 	 * If the user didn't specify any inquiry options, he wants all of
622 	 * them.
623 	 */
624 	if ((arglist & CAM_ARG_INQ_MASK) == 0)
625 		arglist |= CAM_ARG_INQ_MASK;
626 
627 	if (arglist & CAM_ARG_GET_STDINQ)
628 		error = scsiinquiry(device, retry_count, timeout);
629 
630 	if (error != 0)
631 		return(error);
632 
633 	if (arglist & CAM_ARG_GET_SERIAL)
634 		scsiserial(device, retry_count, timeout);
635 
636 	if (error != 0)
637 		return(error);
638 
639 	if (arglist & CAM_ARG_GET_XFERRATE)
640 		error = scsixferrate(device);
641 
642 	return(error);
643 }
644 
645 static int
646 scsiinquiry(struct cam_device *device, int retry_count, int timeout)
647 {
648 	union ccb *ccb;
649 	struct scsi_inquiry_data *inq_buf;
650 	int error = 0;
651 
652 	ccb = cam_getccb(device);
653 
654 	if (ccb == NULL) {
655 		warnx("couldn't allocate CCB");
656 		return(1);
657 	}
658 
659 	/* cam_getccb cleans up the header, caller has to zero the payload */
660 	bzero(&(&ccb->ccb_h)[1],
661 	      sizeof(struct ccb_scsiio) - sizeof(struct ccb_hdr));
662 
663 	inq_buf = (struct scsi_inquiry_data *)malloc(
664 		sizeof(struct scsi_inquiry_data));
665 
666 	if (inq_buf == NULL) {
667 		cam_freeccb(ccb);
668 		warnx("can't malloc memory for inquiry\n");
669 		return(1);
670 	}
671 	bzero(inq_buf, sizeof(*inq_buf));
672 
673 	/*
674 	 * Note that although the size of the inquiry buffer is the full
675 	 * 256 bytes specified in the SCSI spec, we only tell the device
676 	 * that we have allocated SHORT_INQUIRY_LENGTH bytes.  There are
677 	 * two reasons for this:
678 	 *
679 	 *  - The SCSI spec says that when a length field is only 1 byte,
680 	 *    a value of 0 will be interpreted as 256.  Therefore
681 	 *    scsi_inquiry() will convert an inq_len (which is passed in as
682 	 *    a u_int32_t, but the field in the CDB is only 1 byte) of 256
683 	 *    to 0.  Evidently, very few devices meet the spec in that
684 	 *    regard.  Some devices, like many Seagate disks, take the 0 as
685 	 *    0, and don't return any data.  One Pioneer DVD-R drive
686 	 *    returns more data than the command asked for.
687 	 *
688 	 *    So, since there are numerous devices that just don't work
689 	 *    right with the full inquiry size, we don't send the full size.
690 	 *
691 	 *  - The second reason not to use the full inquiry data length is
692 	 *    that we don't need it here.  The only reason we issue a
693 	 *    standard inquiry is to get the vendor name, device name,
694 	 *    and revision so scsi_print_inquiry() can print them.
695 	 *
696 	 * If, at some point in the future, more inquiry data is needed for
697 	 * some reason, this code should use a procedure similar to the
698 	 * probe code.  i.e., issue a short inquiry, and determine from
699 	 * the additional length passed back from the device how much
700 	 * inquiry data the device supports.  Once the amount the device
701 	 * supports is determined, issue an inquiry for that amount and no
702 	 * more.
703 	 *
704 	 * KDM, 2/18/2000
705 	 */
706 	scsi_inquiry(&ccb->csio,
707 		     /* retries */ retry_count,
708 		     /* cbfcnp */ NULL,
709 		     /* tag_action */ MSG_SIMPLE_Q_TAG,
710 		     /* inq_buf */ (u_int8_t *)inq_buf,
711 		     /* inq_len */ SHORT_INQUIRY_LENGTH,
712 		     /* evpd */ 0,
713 		     /* page_code */ 0,
714 		     /* sense_len */ SSD_FULL_SIZE,
715 		     /* timeout */ timeout ? timeout : 5000);
716 
717 	/* Disable freezing the device queue */
718 	ccb->ccb_h.flags |= CAM_DEV_QFRZDIS;
719 
720 	if (arglist & CAM_ARG_ERR_RECOVER)
721 		ccb->ccb_h.flags |= CAM_PASS_ERR_RECOVER;
722 
723 	if (cam_send_ccb(device, ccb) < 0) {
724 		perror("error sending SCSI inquiry");
725 
726 		if (arglist & CAM_ARG_VERBOSE) {
727 		 	if ((ccb->ccb_h.status & CAM_STATUS_MASK) ==
728 			    CAM_SCSI_STATUS_ERROR)
729 				scsi_sense_print(device, &ccb->csio, stderr);
730 			else
731 				fprintf(stderr, "CAM status is %#x\n",
732 					ccb->ccb_h.status);
733 		}
734 
735 		cam_freeccb(ccb);
736 		return(1);
737 	}
738 
739 	if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
740 		error = 1;
741 
742 		if (arglist & CAM_ARG_VERBOSE) {
743 		 	if ((ccb->ccb_h.status & CAM_STATUS_MASK) ==
744 			    CAM_SCSI_STATUS_ERROR)
745 				scsi_sense_print(device, &ccb->csio, stderr);
746 			else
747 				fprintf(stderr, "CAM status is %#x\n",
748 					ccb->ccb_h.status);
749 		}
750 	}
751 
752 	cam_freeccb(ccb);
753 
754 	if (error != 0) {
755 		free(inq_buf);
756 		return(error);
757 	}
758 
759 	fprintf(stdout, "%s%d: ", device->device_name,
760 		device->dev_unit_num);
761 	scsi_print_inquiry(inq_buf);
762 
763 	free(inq_buf);
764 
765 	return(0);
766 }
767 
768 static int
769 scsiserial(struct cam_device *device, int retry_count, int timeout)
770 {
771 	union ccb *ccb;
772 	struct scsi_vpd_unit_serial_number *serial_buf;
773 	char serial_num[SVPD_SERIAL_NUM_SIZE + 1];
774 	int error = 0;
775 
776 	ccb = cam_getccb(device);
777 
778 	if (ccb == NULL) {
779 		warnx("couldn't allocate CCB");
780 		return(1);
781 	}
782 
783 	/* cam_getccb cleans up the header, caller has to zero the payload */
784 	bzero(&(&ccb->ccb_h)[1],
785 	      sizeof(struct ccb_scsiio) - sizeof(struct ccb_hdr));
786 
787 	serial_buf = (struct scsi_vpd_unit_serial_number *)
788 		malloc(sizeof(*serial_buf));
789 
790 	if (serial_buf == NULL) {
791 		cam_freeccb(ccb);
792 		warnx("can't malloc memory for serial number");
793 		return(1);
794 	}
795 
796 	scsi_inquiry(&ccb->csio,
797 		     /*retries*/ retry_count,
798 		     /*cbfcnp*/ NULL,
799 		     /* tag_action */ MSG_SIMPLE_Q_TAG,
800 		     /* inq_buf */ (u_int8_t *)serial_buf,
801 		     /* inq_len */ sizeof(*serial_buf),
802 		     /* evpd */ 1,
803 		     /* page_code */ SVPD_UNIT_SERIAL_NUMBER,
804 		     /* sense_len */ SSD_FULL_SIZE,
805 		     /* timeout */ timeout ? timeout : 5000);
806 
807 	/* Disable freezing the device queue */
808 	ccb->ccb_h.flags |= CAM_DEV_QFRZDIS;
809 
810 	if (arglist & CAM_ARG_ERR_RECOVER)
811 		ccb->ccb_h.flags |= CAM_PASS_ERR_RECOVER;
812 
813 	if (cam_send_ccb(device, ccb) < 0) {
814 		warn("error getting serial number");
815 
816 		if (arglist & CAM_ARG_VERBOSE) {
817 		 	if ((ccb->ccb_h.status & CAM_STATUS_MASK) ==
818 			    CAM_SCSI_STATUS_ERROR)
819 				scsi_sense_print(device, &ccb->csio, stderr);
820 			else
821 				fprintf(stderr, "CAM status is %#x\n",
822 					ccb->ccb_h.status);
823 		}
824 
825 		cam_freeccb(ccb);
826 		free(serial_buf);
827 		return(1);
828 	}
829 
830 	if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
831 		error = 1;
832 
833 		if (arglist & CAM_ARG_VERBOSE) {
834 		 	if ((ccb->ccb_h.status & CAM_STATUS_MASK) ==
835 			    CAM_SCSI_STATUS_ERROR)
836 				scsi_sense_print(device, &ccb->csio, stderr);
837 			else
838 				fprintf(stderr, "CAM status is %#x\n",
839 					ccb->ccb_h.status);
840 		}
841 	}
842 
843 	cam_freeccb(ccb);
844 
845 	if (error != 0) {
846 		free(serial_buf);
847 		return(error);
848 	}
849 
850 	bcopy(serial_buf->serial_num, serial_num, serial_buf->length);
851 	serial_num[serial_buf->length] = '\0';
852 
853 	if ((arglist & CAM_ARG_GET_STDINQ)
854 	 || (arglist & CAM_ARG_GET_XFERRATE))
855 		fprintf(stdout, "%s%d: Serial Number ",
856 			device->device_name, device->dev_unit_num);
857 
858 	fprintf(stdout, "%.60s\n", serial_num);
859 
860 	free(serial_buf);
861 
862 	return(0);
863 }
864 
865 static int
866 scsixferrate(struct cam_device *device)
867 {
868 	u_int32_t freq;
869 	u_int32_t speed;
870 	union ccb *ccb;
871 	u_int mb;
872 	int retval = 0;
873 
874 	ccb = cam_getccb(device);
875 
876 	if (ccb == NULL) {
877 		warnx("couldn't allocate CCB");
878 		return(1);
879 	}
880 
881 	bzero(&(&ccb->ccb_h)[1],
882 	      sizeof(struct ccb_trans_settings) - sizeof(struct ccb_hdr));
883 
884 	ccb->ccb_h.func_code = XPT_GET_TRAN_SETTINGS;
885 	ccb->cts.flags = CCB_TRANS_CURRENT_SETTINGS;
886 
887 	if (((retval = cam_send_ccb(device, ccb)) < 0)
888 	 || ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP)) {
889 		const char error_string[] = "error getting transfer settings";
890 
891 		if (retval < 0)
892 			warn(error_string);
893 		else
894 			warnx(error_string);
895 
896 		/*
897 		 * If there is an error, it won't be a SCSI error since
898 		 * this isn't a SCSI CCB.
899 		 */
900 		if (arglist & CAM_ARG_VERBOSE)
901 			fprintf(stderr, "CAM status is %#x\n",
902 				ccb->ccb_h.status);
903 
904 		retval = 1;
905 
906 		goto xferrate_bailout;
907 
908 	}
909 
910 	if (((ccb->cts.valid & CCB_TRANS_SYNC_OFFSET_VALID) != 0)
911 	 && (ccb->cts.sync_offset != 0)) {
912 		freq = scsi_calc_syncsrate(ccb->cts.sync_period);
913 		speed = freq;
914 	} else {
915 		struct ccb_pathinq cpi;
916 
917 		retval = get_cpi(device, &cpi);
918 
919 		if (retval != 0)
920 			goto xferrate_bailout;
921 
922 		speed = cpi.base_transfer_speed;
923 		freq = 0;
924 	}
925 
926 	fprintf(stdout, "%s%d: ", device->device_name,
927 		device->dev_unit_num);
928 
929 	if ((ccb->cts.valid & CCB_TRANS_BUS_WIDTH_VALID) != 0)
930 		speed *= (0x01 << device->bus_width);
931 
932 	mb = speed / 1000;
933 
934 	if (mb > 0)
935 		fprintf(stdout, "%d.%03dMB/s transfers ",
936 			mb, speed % 1000);
937 	else
938 		fprintf(stdout, "%dKB/s transfers ",
939 			speed);
940 
941 	if (((ccb->cts.valid & CCB_TRANS_SYNC_OFFSET_VALID) != 0)
942 	 && (ccb->cts.sync_offset != 0))
943                 fprintf(stdout, "(%d.%03dMHz, offset %d", freq / 1000,
944 			freq % 1000, ccb->cts.sync_offset);
945 
946 	if (((ccb->cts.valid & CCB_TRANS_BUS_WIDTH_VALID) != 0)
947 	 && (ccb->cts.bus_width > 0)) {
948 		if (((ccb->cts.valid & CCB_TRANS_SYNC_OFFSET_VALID) != 0)
949 		 && (ccb->cts.sync_offset != 0)) {
950 			fprintf(stdout, ", ");
951 		} else {
952 			fprintf(stdout, " (");
953 		}
954 		fprintf(stdout, "%dbit)", 8 * (0x01 << ccb->cts.bus_width));
955 	} else if (((ccb->cts.valid & CCB_TRANS_SYNC_OFFSET_VALID) != 0)
956 		&& (ccb->cts.sync_offset != 0)) {
957 		fprintf(stdout, ")");
958 	}
959 
960 	if (((ccb->cts.valid & CCB_TRANS_TQ_VALID) != 0)
961 	 && (ccb->cts.flags & CCB_TRANS_TAG_ENB))
962                 fprintf(stdout, ", Tagged Queueing Enabled");
963 
964         fprintf(stdout, "\n");
965 
966 xferrate_bailout:
967 
968 	cam_freeccb(ccb);
969 
970 	return(retval);
971 }
972 #endif /* MINIMALISTIC */
973 
974 /*
975  * Parse out a bus, or a bus, target and lun in the following
976  * format:
977  * bus
978  * bus:target
979  * bus:target:lun
980  *
981  * Returns the number of parsed components, or 0.
982  */
983 static int
984 parse_btl(char *tstr, int *mybus, int *mytarget, int *mylun,
985 	  cam_argmask *myarglist)
986 {
987 	char *tmpstr;
988 	int convs = 0;
989 
990 	while (isspace(*tstr) && (*tstr != '\0'))
991 		tstr++;
992 
993 	tmpstr = (char *)strtok(tstr, ":");
994 	if ((tmpstr != NULL) && (*tmpstr != '\0')) {
995 		*mybus = strtol(tmpstr, NULL, 0);
996 		*myarglist |= CAM_ARG_BUS;
997 		convs++;
998 		tmpstr = (char *)strtok(NULL, ":");
999 		if ((tmpstr != NULL) && (*tmpstr != '\0')) {
1000 			*mytarget = strtol(tmpstr, NULL, 0);
1001 			*myarglist |= CAM_ARG_TARGET;
1002 			convs++;
1003 			tmpstr = (char *)strtok(NULL, ":");
1004 			if ((tmpstr != NULL) && (*tmpstr != '\0')) {
1005 				*mylun = strtol(tmpstr, NULL, 0);
1006 				*myarglist |= CAM_ARG_LUN;
1007 				convs++;
1008 			}
1009 		}
1010 	}
1011 
1012 	return convs;
1013 }
1014 
1015 static int
1016 dorescan_or_reset(int argc, char **argv, int rescan)
1017 {
1018 	static const char must[] =
1019 		"you must specify \"all\", a bus, or a bus:target:lun to %s";
1020 	int rv, error = 0;
1021 	int mybus = -1, mytarget = -1, mylun = -1;
1022 	char *tstr;
1023 
1024 	if (argc < 3) {
1025 		warnx(must, rescan? "rescan" : "reset");
1026 		return(1);
1027 	}
1028 
1029 	tstr = argv[optind];
1030 	while (isspace(*tstr) && (*tstr != '\0'))
1031 		tstr++;
1032 	if (strncasecmp(tstr, "all", strlen("all")) == 0)
1033 		arglist |= CAM_ARG_BUS;
1034 	else {
1035 		rv = parse_btl(argv[optind], &mybus, &mytarget, &mylun,
1036 			       &arglist);
1037 		if (rv != 1 && rv != 3) {
1038 			warnx(must, rescan? "rescan" : "reset");
1039 			return(1);
1040 		}
1041 	}
1042 
1043 	if ((arglist & CAM_ARG_BUS)
1044 	    && (arglist & CAM_ARG_TARGET)
1045 	    && (arglist & CAM_ARG_LUN))
1046 		error = scanlun_or_reset_dev(mybus, mytarget, mylun, rescan);
1047 	else
1048 		error = rescan_or_reset_bus(mybus, rescan);
1049 
1050 	return(error);
1051 }
1052 
1053 static int
1054 rescan_or_reset_bus(int mybus, int rescan)
1055 {
1056 	union ccb ccb, matchccb;
1057 	int fd, retval;
1058 	int bufsize;
1059 
1060 	retval = 0;
1061 
1062 	if ((fd = open(XPT_DEVICE, O_RDWR)) < 0) {
1063 		warnx("error opening transport layer device %s", XPT_DEVICE);
1064 		warn("%s", XPT_DEVICE);
1065 		return(1);
1066 	}
1067 
1068 	if (mybus != -1) {
1069 		ccb.ccb_h.func_code = rescan ? XPT_SCAN_BUS : XPT_RESET_BUS;
1070 		ccb.ccb_h.path_id = mybus;
1071 		ccb.ccb_h.target_id = CAM_TARGET_WILDCARD;
1072 		ccb.ccb_h.target_lun = CAM_LUN_WILDCARD;
1073 		ccb.crcn.flags = CAM_FLAG_NONE;
1074 
1075 		/* run this at a low priority */
1076 		ccb.ccb_h.pinfo.priority = 5;
1077 
1078 		if (ioctl(fd, CAMIOCOMMAND, &ccb) == -1) {
1079 			warn("CAMIOCOMMAND ioctl failed");
1080 			close(fd);
1081 			return(1);
1082 		}
1083 
1084 		if ((ccb.ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
1085 			fprintf(stdout, "%s of bus %d was successful\n",
1086 			    rescan ? "Re-scan" : "Reset", mybus);
1087 		} else {
1088 			fprintf(stdout, "%s of bus %d returned error %#x\n",
1089 				rescan ? "Re-scan" : "Reset", mybus,
1090 				ccb.ccb_h.status & CAM_STATUS_MASK);
1091 			retval = 1;
1092 		}
1093 
1094 		close(fd);
1095 		return(retval);
1096 
1097 	}
1098 
1099 
1100 	/*
1101 	 * The right way to handle this is to modify the xpt so that it can
1102 	 * handle a wildcarded bus in a rescan or reset CCB.  At the moment
1103 	 * that isn't implemented, so instead we enumerate the busses and
1104 	 * send the rescan or reset to those busses in the case where the
1105 	 * given bus is -1 (wildcard).  We don't send a rescan or reset
1106 	 * to the xpt bus; sending a rescan to the xpt bus is effectively a
1107 	 * no-op, sending a rescan to the xpt bus would result in a status of
1108 	 * CAM_REQ_INVALID.
1109 	 */
1110 	bzero(&(&matchccb.ccb_h)[1],
1111 	      sizeof(struct ccb_dev_match) - sizeof(struct ccb_hdr));
1112 	matchccb.ccb_h.func_code = XPT_DEV_MATCH;
1113 	bufsize = sizeof(struct dev_match_result) * 20;
1114 	matchccb.cdm.match_buf_len = bufsize;
1115 	matchccb.cdm.matches=(struct dev_match_result *)malloc(bufsize);
1116 	if (matchccb.cdm.matches == NULL) {
1117 		warnx("can't malloc memory for matches");
1118 		retval = 1;
1119 		goto bailout;
1120 	}
1121 	matchccb.cdm.num_matches = 0;
1122 
1123 	matchccb.cdm.num_patterns = 1;
1124 	matchccb.cdm.pattern_buf_len = sizeof(struct dev_match_pattern);
1125 
1126 	matchccb.cdm.patterns = (struct dev_match_pattern *)malloc(
1127 		matchccb.cdm.pattern_buf_len);
1128 	if (matchccb.cdm.patterns == NULL) {
1129 		warnx("can't malloc memory for patterns");
1130 		retval = 1;
1131 		goto bailout;
1132 	}
1133 	matchccb.cdm.patterns[0].type = DEV_MATCH_BUS;
1134 	matchccb.cdm.patterns[0].pattern.bus_pattern.flags = BUS_MATCH_ANY;
1135 
1136 	do {
1137 		unsigned int i;
1138 
1139 		if (ioctl(fd, CAMIOCOMMAND, &matchccb) == -1) {
1140 			warn("CAMIOCOMMAND ioctl failed");
1141 			retval = 1;
1142 			goto bailout;
1143 		}
1144 
1145 		if ((matchccb.ccb_h.status != CAM_REQ_CMP)
1146 		 || ((matchccb.cdm.status != CAM_DEV_MATCH_LAST)
1147 		   && (matchccb.cdm.status != CAM_DEV_MATCH_MORE))) {
1148 			warnx("got CAM error %#x, CDM error %d\n",
1149 			      matchccb.ccb_h.status, matchccb.cdm.status);
1150 			retval = 1;
1151 			goto bailout;
1152 		}
1153 
1154 		for (i = 0; i < matchccb.cdm.num_matches; i++) {
1155 			struct bus_match_result *bus_result;
1156 
1157 			/* This shouldn't happen. */
1158 			if (matchccb.cdm.matches[i].type != DEV_MATCH_BUS)
1159 				continue;
1160 
1161 			bus_result = &matchccb.cdm.matches[i].result.bus_result;
1162 
1163 			/*
1164 			 * We don't want to rescan or reset the xpt bus.
1165 			 * See above.
1166 			 */
1167 			if ((int)bus_result->path_id == -1)
1168 				continue;
1169 
1170 			ccb.ccb_h.func_code = rescan ? XPT_SCAN_BUS :
1171 						       XPT_RESET_BUS;
1172 			ccb.ccb_h.path_id = bus_result->path_id;
1173 			ccb.ccb_h.target_id = CAM_TARGET_WILDCARD;
1174 			ccb.ccb_h.target_lun = CAM_LUN_WILDCARD;
1175 			ccb.crcn.flags = CAM_FLAG_NONE;
1176 
1177 			/* run this at a low priority */
1178 			ccb.ccb_h.pinfo.priority = 5;
1179 
1180 			if (ioctl(fd, CAMIOCOMMAND, &ccb) == -1) {
1181 				warn("CAMIOCOMMAND ioctl failed");
1182 				retval = 1;
1183 				goto bailout;
1184 			}
1185 
1186 			if ((ccb.ccb_h.status & CAM_STATUS_MASK) ==CAM_REQ_CMP){
1187 				fprintf(stdout, "%s of bus %d was successful\n",
1188 					rescan? "Re-scan" : "Reset",
1189 					bus_result->path_id);
1190 			} else {
1191 				/*
1192 				 * Don't bail out just yet, maybe the other
1193 				 * rescan or reset commands will complete
1194 				 * successfully.
1195 				 */
1196 				fprintf(stderr, "%s of bus %d returned error "
1197 					"%#x\n", rescan? "Re-scan" : "Reset",
1198 					bus_result->path_id,
1199 					ccb.ccb_h.status & CAM_STATUS_MASK);
1200 				retval = 1;
1201 			}
1202 		}
1203 	} while ((matchccb.ccb_h.status == CAM_REQ_CMP)
1204 		 && (matchccb.cdm.status == CAM_DEV_MATCH_MORE));
1205 
1206 bailout:
1207 
1208 	if (fd != -1)
1209 		close(fd);
1210 
1211 	if (matchccb.cdm.patterns != NULL)
1212 		free(matchccb.cdm.patterns);
1213 	if (matchccb.cdm.matches != NULL)
1214 		free(matchccb.cdm.matches);
1215 
1216 	return(retval);
1217 }
1218 
1219 static int
1220 scanlun_or_reset_dev(int mybus, int mytarget, int mylun, int scan)
1221 {
1222 	union ccb ccb;
1223 	struct cam_device *device;
1224 	int fd;
1225 
1226 	device = NULL;
1227 
1228 	if (mybus < 0) {
1229 		warnx("invalid bus number %d", mybus);
1230 		return(1);
1231 	}
1232 
1233 	if (mytarget < 0) {
1234 		warnx("invalid target number %d", mytarget);
1235 		return(1);
1236 	}
1237 
1238 	if (mylun < 0) {
1239 		warnx("invalid lun number %d", mylun);
1240 		return(1);
1241 	}
1242 
1243 	fd = -1;
1244 
1245 	bzero(&ccb, sizeof(union ccb));
1246 
1247 	if (scan) {
1248 		if ((fd = open(XPT_DEVICE, O_RDWR)) < 0) {
1249 			warnx("error opening transport layer device %s\n",
1250 			    XPT_DEVICE);
1251 			warn("%s", XPT_DEVICE);
1252 			return(1);
1253 		}
1254 	} else {
1255 		device = cam_open_btl(mybus, mytarget, mylun, O_RDWR, NULL);
1256 		if (device == NULL) {
1257 			warnx("%s", cam_errbuf);
1258 			return(1);
1259 		}
1260 	}
1261 
1262 	ccb.ccb_h.func_code = (scan)? XPT_SCAN_LUN : XPT_RESET_DEV;
1263 	ccb.ccb_h.path_id = mybus;
1264 	ccb.ccb_h.target_id = mytarget;
1265 	ccb.ccb_h.target_lun = mylun;
1266 	ccb.ccb_h.timeout = 5000;
1267 	ccb.crcn.flags = CAM_FLAG_NONE;
1268 
1269 	/* run this at a low priority */
1270 	ccb.ccb_h.pinfo.priority = 5;
1271 
1272 	if (scan) {
1273 		if (ioctl(fd, CAMIOCOMMAND, &ccb) < 0) {
1274 			warn("CAMIOCOMMAND ioctl failed");
1275 			close(fd);
1276 			return(1);
1277 		}
1278 	} else {
1279 		if (cam_send_ccb(device, &ccb) < 0) {
1280 			warn("error sending XPT_RESET_DEV CCB");
1281 			cam_close_device(device);
1282 			return(1);
1283 		}
1284 	}
1285 
1286 	if (scan)
1287 		close(fd);
1288 	else
1289 		cam_close_device(device);
1290 
1291 	/*
1292 	 * An error code of CAM_BDR_SENT is normal for a BDR request.
1293 	 */
1294 	if (((ccb.ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP)
1295 	 || ((!scan)
1296 	  && ((ccb.ccb_h.status & CAM_STATUS_MASK) == CAM_BDR_SENT))) {
1297 		fprintf(stdout, "%s of %d:%d:%d was successful\n",
1298 		    scan? "Re-scan" : "Reset", mybus, mytarget, mylun);
1299 		return(0);
1300 	} else {
1301 		fprintf(stdout, "%s of %d:%d:%d returned error %#x\n",
1302 		    scan? "Re-scan" : "Reset", mybus, mytarget, mylun,
1303 		    ccb.ccb_h.status & CAM_STATUS_MASK);
1304 		return(1);
1305 	}
1306 }
1307 
1308 #ifndef MINIMALISTIC
1309 static int
1310 readdefects(struct cam_device *device, int argc, char **argv,
1311 	    char *combinedopt, int retry_count, int timeout)
1312 {
1313 	union ccb *ccb = NULL;
1314 	struct scsi_read_defect_data_10 *rdd_cdb;
1315 	u_int8_t *defect_list = NULL;
1316 	u_int32_t dlist_length = 65000;
1317 	u_int32_t returned_length = 0;
1318 	u_int32_t num_returned = 0;
1319 	u_int8_t returned_format;
1320 	unsigned int i;
1321 	int c, error = 0;
1322 	int lists_specified = 0;
1323 
1324 	while ((c = getopt(argc, argv, combinedopt)) != -1) {
1325 		switch(c){
1326 		case 'f':
1327 		{
1328 			char *tstr;
1329 			tstr = optarg;
1330 			while (isspace(*tstr) && (*tstr != '\0'))
1331 				tstr++;
1332 			if (strcmp(tstr, "block") == 0)
1333 				arglist |= CAM_ARG_FORMAT_BLOCK;
1334 			else if (strcmp(tstr, "bfi") == 0)
1335 				arglist |= CAM_ARG_FORMAT_BFI;
1336 			else if (strcmp(tstr, "phys") == 0)
1337 				arglist |= CAM_ARG_FORMAT_PHYS;
1338 			else {
1339 				error = 1;
1340 				warnx("invalid defect format %s", tstr);
1341 				goto defect_bailout;
1342 			}
1343 			break;
1344 		}
1345 		case 'G':
1346 			arglist |= CAM_ARG_GLIST;
1347 			break;
1348 		case 'P':
1349 			arglist |= CAM_ARG_PLIST;
1350 			break;
1351 		default:
1352 			break;
1353 		}
1354 	}
1355 
1356 	ccb = cam_getccb(device);
1357 
1358 	/*
1359 	 * Hopefully 65000 bytes is enough to hold the defect list.  If it
1360 	 * isn't, the disk is probably dead already.  We'd have to go with
1361 	 * 12 byte command (i.e. alloc_length is 32 bits instead of 16)
1362 	 * to hold them all.
1363 	 */
1364 	defect_list = malloc(dlist_length);
1365 	if (defect_list == NULL) {
1366 		warnx("can't malloc memory for defect list");
1367 		error = 1;
1368 		goto defect_bailout;
1369 	}
1370 
1371 	rdd_cdb =(struct scsi_read_defect_data_10 *)&ccb->csio.cdb_io.cdb_bytes;
1372 
1373 	/*
1374 	 * cam_getccb() zeros the CCB header only.  So we need to zero the
1375 	 * payload portion of the ccb.
1376 	 */
1377 	bzero(&(&ccb->ccb_h)[1],
1378 	      sizeof(struct ccb_scsiio) - sizeof(struct ccb_hdr));
1379 
1380 	cam_fill_csio(&ccb->csio,
1381 		      /*retries*/ retry_count,
1382 		      /*cbfcnp*/ NULL,
1383 		      /*flags*/ CAM_DIR_IN | ((arglist & CAM_ARG_ERR_RECOVER) ?
1384 					      CAM_PASS_ERR_RECOVER : 0),
1385 		      /*tag_action*/ MSG_SIMPLE_Q_TAG,
1386 		      /*data_ptr*/ defect_list,
1387 		      /*dxfer_len*/ dlist_length,
1388 		      /*sense_len*/ SSD_FULL_SIZE,
1389 		      /*cdb_len*/ sizeof(struct scsi_read_defect_data_10),
1390 		      /*timeout*/ timeout ? timeout : 5000);
1391 
1392 	rdd_cdb->opcode = READ_DEFECT_DATA_10;
1393 	if (arglist & CAM_ARG_FORMAT_BLOCK)
1394 		rdd_cdb->format = SRDD10_BLOCK_FORMAT;
1395 	else if (arglist & CAM_ARG_FORMAT_BFI)
1396 		rdd_cdb->format = SRDD10_BYTES_FROM_INDEX_FORMAT;
1397 	else if (arglist & CAM_ARG_FORMAT_PHYS)
1398 		rdd_cdb->format = SRDD10_PHYSICAL_SECTOR_FORMAT;
1399 	else {
1400 		error = 1;
1401 		warnx("no defect list format specified");
1402 		goto defect_bailout;
1403 	}
1404 	if (arglist & CAM_ARG_PLIST) {
1405 		rdd_cdb->format |= SRDD10_PLIST;
1406 		lists_specified++;
1407 	}
1408 
1409 	if (arglist & CAM_ARG_GLIST) {
1410 		rdd_cdb->format |= SRDD10_GLIST;
1411 		lists_specified++;
1412 	}
1413 
1414 	scsi_ulto2b(dlist_length, rdd_cdb->alloc_length);
1415 
1416 	/* Disable freezing the device queue */
1417 	ccb->ccb_h.flags |= CAM_DEV_QFRZDIS;
1418 
1419 	if (cam_send_ccb(device, ccb) < 0) {
1420 		perror("error reading defect list");
1421 
1422 		if (arglist & CAM_ARG_VERBOSE) {
1423 		 	if ((ccb->ccb_h.status & CAM_STATUS_MASK) ==
1424 			    CAM_SCSI_STATUS_ERROR)
1425 				scsi_sense_print(device, &ccb->csio, stderr);
1426 			else
1427 				fprintf(stderr, "CAM status is %#x\n",
1428 					ccb->ccb_h.status);
1429 		}
1430 
1431 		error = 1;
1432 		goto defect_bailout;
1433 	}
1434 
1435 	if (arglist & CAM_ARG_VERBOSE)
1436 		scsi_sense_print(device, &ccb->csio, stderr);
1437 
1438 	returned_length = scsi_2btoul(((struct
1439 		scsi_read_defect_data_hdr_10 *)defect_list)->length);
1440 
1441 	returned_format = ((struct scsi_read_defect_data_hdr_10 *)
1442 			defect_list)->format;
1443 
1444 	if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1445 		struct scsi_sense_data *sense;
1446 		int error_code, sense_key, asc, ascq;
1447 
1448 		sense = &ccb->csio.sense_data;
1449 		scsi_extract_sense(sense, &error_code, &sense_key, &asc, &ascq);
1450 
1451 		/*
1452 		 * According to the SCSI spec, if the disk doesn't support
1453 		 * the requested format, it will generally return a sense
1454 		 * key of RECOVERED ERROR, and an additional sense code
1455 		 * of "DEFECT LIST NOT FOUND".  So, we check for that, and
1456 		 * also check to make sure that the returned length is
1457 		 * greater than 0, and then print out whatever format the
1458 		 * disk gave us.
1459 		 */
1460 		if ((sense_key == SSD_KEY_RECOVERED_ERROR)
1461 		 && (asc == 0x1c) && (ascq == 0x00)
1462 		 && (returned_length > 0)) {
1463 			warnx("requested defect format not available");
1464 			switch(returned_format & SRDDH10_DLIST_FORMAT_MASK) {
1465 			case SRDD10_BLOCK_FORMAT:
1466 				warnx("Device returned block format");
1467 				break;
1468 			case SRDD10_BYTES_FROM_INDEX_FORMAT:
1469 				warnx("Device returned bytes from index"
1470 				      " format");
1471 				break;
1472 			case SRDD10_PHYSICAL_SECTOR_FORMAT:
1473 				warnx("Device returned physical sector format");
1474 				break;
1475 			default:
1476 				error = 1;
1477 				warnx("Device returned unknown defect"
1478 				     " data format %#x", returned_format);
1479 				goto defect_bailout;
1480 				break; /* NOTREACHED */
1481 			}
1482 		} else {
1483 			error = 1;
1484 			warnx("Error returned from read defect data command");
1485 			goto defect_bailout;
1486 		}
1487 	}
1488 
1489 	/*
1490 	 * XXX KDM  I should probably clean up the printout format for the
1491 	 * disk defects.
1492 	 */
1493 	switch (returned_format & SRDDH10_DLIST_FORMAT_MASK){
1494 		case SRDDH10_PHYSICAL_SECTOR_FORMAT:
1495 		{
1496 			struct scsi_defect_desc_phys_sector *dlist;
1497 
1498 			dlist = (struct scsi_defect_desc_phys_sector *)
1499 				(defect_list +
1500 				sizeof(struct scsi_read_defect_data_hdr_10));
1501 
1502 			num_returned = returned_length /
1503 				sizeof(struct scsi_defect_desc_phys_sector);
1504 
1505 			fprintf(stderr, "Got %d defect", num_returned);
1506 
1507 			if ((lists_specified == 0) || (num_returned == 0)) {
1508 				fprintf(stderr, "s.\n");
1509 				break;
1510 			} else if (num_returned == 1)
1511 				fprintf(stderr, ":\n");
1512 			else
1513 				fprintf(stderr, "s:\n");
1514 
1515 			for (i = 0; i < num_returned; i++) {
1516 				fprintf(stdout, "%d:%d:%d\n",
1517 					scsi_3btoul(dlist[i].cylinder),
1518 					dlist[i].head,
1519 					scsi_4btoul(dlist[i].sector));
1520 			}
1521 			break;
1522 		}
1523 		case SRDDH10_BYTES_FROM_INDEX_FORMAT:
1524 		{
1525 			struct scsi_defect_desc_bytes_from_index *dlist;
1526 
1527 			dlist = (struct scsi_defect_desc_bytes_from_index *)
1528 				(defect_list +
1529 				sizeof(struct scsi_read_defect_data_hdr_10));
1530 
1531 			num_returned = returned_length /
1532 			      sizeof(struct scsi_defect_desc_bytes_from_index);
1533 
1534 			fprintf(stderr, "Got %d defect", num_returned);
1535 
1536 			if ((lists_specified == 0) || (num_returned == 0)) {
1537 				fprintf(stderr, "s.\n");
1538 				break;
1539 			} else if (num_returned == 1)
1540 				fprintf(stderr, ":\n");
1541 			else
1542 				fprintf(stderr, "s:\n");
1543 
1544 			for (i = 0; i < num_returned; i++) {
1545 				fprintf(stdout, "%d:%d:%d\n",
1546 					scsi_3btoul(dlist[i].cylinder),
1547 					dlist[i].head,
1548 					scsi_4btoul(dlist[i].bytes_from_index));
1549 			}
1550 			break;
1551 		}
1552 		case SRDDH10_BLOCK_FORMAT:
1553 		{
1554 			struct scsi_defect_desc_block *dlist;
1555 
1556 			dlist = (struct scsi_defect_desc_block *)(defect_list +
1557 				sizeof(struct scsi_read_defect_data_hdr_10));
1558 
1559 			num_returned = returned_length /
1560 			      sizeof(struct scsi_defect_desc_block);
1561 
1562 			fprintf(stderr, "Got %d defect", num_returned);
1563 
1564 			if ((lists_specified == 0) || (num_returned == 0)) {
1565 				fprintf(stderr, "s.\n");
1566 				break;
1567 			} else if (num_returned == 1)
1568 				fprintf(stderr, ":\n");
1569 			else
1570 				fprintf(stderr, "s:\n");
1571 
1572 			for (i = 0; i < num_returned; i++)
1573 				fprintf(stdout, "%u\n",
1574 					scsi_4btoul(dlist[i].address));
1575 			break;
1576 		}
1577 		default:
1578 			fprintf(stderr, "Unknown defect format %d\n",
1579 				returned_format & SRDDH10_DLIST_FORMAT_MASK);
1580 			error = 1;
1581 			break;
1582 	}
1583 defect_bailout:
1584 
1585 	if (defect_list != NULL)
1586 		free(defect_list);
1587 
1588 	if (ccb != NULL)
1589 		cam_freeccb(ccb);
1590 
1591 	return(error);
1592 }
1593 #endif /* MINIMALISTIC */
1594 
1595 #if 0
1596 void
1597 reassignblocks(struct cam_device *device, u_int32_t *blocks, int num_blocks)
1598 {
1599 	union ccb *ccb;
1600 
1601 	ccb = cam_getccb(device);
1602 
1603 	cam_freeccb(ccb);
1604 }
1605 #endif
1606 
1607 #ifndef MINIMALISTIC
1608 void
1609 mode_sense(struct cam_device *device, int mode_page, int page_control,
1610 	   int dbd, int retry_count, int timeout, u_int8_t *data, int datalen)
1611 {
1612 	union ccb *ccb;
1613 	int retval;
1614 
1615 	ccb = cam_getccb(device);
1616 
1617 	if (ccb == NULL)
1618 		errx(1, "mode_sense: couldn't allocate CCB");
1619 
1620 	bzero(&(&ccb->ccb_h)[1],
1621 	      sizeof(struct ccb_scsiio) - sizeof(struct ccb_hdr));
1622 
1623 	scsi_mode_sense(&ccb->csio,
1624 			/* retries */ retry_count,
1625 			/* cbfcnp */ NULL,
1626 			/* tag_action */ MSG_SIMPLE_Q_TAG,
1627 			/* dbd */ dbd,
1628 			/* page_code */ page_control << 6,
1629 			/* page */ mode_page,
1630 			/* param_buf */ data,
1631 			/* param_len */ datalen,
1632 			/* sense_len */ SSD_FULL_SIZE,
1633 			/* timeout */ timeout ? timeout : 5000);
1634 
1635 	if (arglist & CAM_ARG_ERR_RECOVER)
1636 		ccb->ccb_h.flags |= CAM_PASS_ERR_RECOVER;
1637 
1638 	/* Disable freezing the device queue */
1639 	ccb->ccb_h.flags |= CAM_DEV_QFRZDIS;
1640 
1641 	if (((retval = cam_send_ccb(device, ccb)) < 0)
1642 	 || ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP)) {
1643 		if (arglist & CAM_ARG_VERBOSE) {
1644 		 	if ((ccb->ccb_h.status & CAM_STATUS_MASK) ==
1645 			    CAM_SCSI_STATUS_ERROR)
1646 				scsi_sense_print(device, &ccb->csio, stderr);
1647 			else
1648 				fprintf(stderr, "CAM status is %#x\n",
1649 					ccb->ccb_h.status);
1650 		}
1651 		cam_freeccb(ccb);
1652 		cam_close_device(device);
1653 		if (retval < 0)
1654 			err(1, "error sending mode sense command");
1655 		else
1656 			errx(1, "error sending mode sense command");
1657 	}
1658 
1659 	cam_freeccb(ccb);
1660 }
1661 
1662 void
1663 mode_select(struct cam_device *device, int save_pages, int retry_count,
1664 	   int timeout, u_int8_t *data, int datalen)
1665 {
1666 	union ccb *ccb;
1667 	int retval;
1668 
1669 	ccb = cam_getccb(device);
1670 
1671 	if (ccb == NULL)
1672 		errx(1, "mode_select: couldn't allocate CCB");
1673 
1674 	bzero(&(&ccb->ccb_h)[1],
1675 	      sizeof(struct ccb_scsiio) - sizeof(struct ccb_hdr));
1676 
1677 	scsi_mode_select(&ccb->csio,
1678 			 /* retries */ retry_count,
1679 			 /* cbfcnp */ NULL,
1680 			 /* tag_action */ MSG_SIMPLE_Q_TAG,
1681 			 /* scsi_page_fmt */ 1,
1682 			 /* save_pages */ save_pages,
1683 			 /* param_buf */ data,
1684 			 /* param_len */ datalen,
1685 			 /* sense_len */ SSD_FULL_SIZE,
1686 			 /* timeout */ timeout ? timeout : 5000);
1687 
1688 	if (arglist & CAM_ARG_ERR_RECOVER)
1689 		ccb->ccb_h.flags |= CAM_PASS_ERR_RECOVER;
1690 
1691 	/* Disable freezing the device queue */
1692 	ccb->ccb_h.flags |= CAM_DEV_QFRZDIS;
1693 
1694 	if (((retval = cam_send_ccb(device, ccb)) < 0)
1695 	 || ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP)) {
1696 		if (arglist & CAM_ARG_VERBOSE) {
1697 		 	if ((ccb->ccb_h.status & CAM_STATUS_MASK) ==
1698 			    CAM_SCSI_STATUS_ERROR)
1699 				scsi_sense_print(device, &ccb->csio, stderr);
1700 			else
1701 				fprintf(stderr, "CAM status is %#x\n",
1702 					ccb->ccb_h.status);
1703 		}
1704 		cam_freeccb(ccb);
1705 		cam_close_device(device);
1706 
1707 		if (retval < 0)
1708 			err(1, "error sending mode select command");
1709 		else
1710 			errx(1, "error sending mode select command");
1711 
1712 	}
1713 
1714 	cam_freeccb(ccb);
1715 }
1716 
1717 void
1718 modepage(struct cam_device *device, int argc, char **argv, char *combinedopt,
1719 	 int retry_count, int timeout)
1720 {
1721 	int c, mode_page = -1, page_control = 0;
1722 	int binary = 0, list = 0;
1723 
1724 	while ((c = getopt(argc, argv, combinedopt)) != -1) {
1725 		switch(c) {
1726 		case 'b':
1727 			binary = 1;
1728 			break;
1729 		case 'd':
1730 			arglist |= CAM_ARG_DBD;
1731 			break;
1732 		case 'e':
1733 			arglist |= CAM_ARG_MODE_EDIT;
1734 			break;
1735 		case 'l':
1736 			list = 1;
1737 			break;
1738 		case 'm':
1739 			mode_page = strtol(optarg, NULL, 0);
1740 			if (mode_page < 0)
1741 				errx(1, "invalid mode page %d", mode_page);
1742 			break;
1743 		case 'P':
1744 			page_control = strtol(optarg, NULL, 0);
1745 			if ((page_control < 0) || (page_control > 3))
1746 				errx(1, "invalid page control field %d",
1747 				     page_control);
1748 			arglist |= CAM_ARG_PAGE_CNTL;
1749 			break;
1750 		default:
1751 			break;
1752 		}
1753 	}
1754 
1755 	if (mode_page == -1 && list == 0)
1756 		errx(1, "you must specify a mode page!");
1757 
1758 	if (list) {
1759 		mode_list(device, page_control, arglist & CAM_ARG_DBD,
1760 		    retry_count, timeout);
1761 	} else {
1762 		mode_edit(device, mode_page, page_control,
1763 		    arglist & CAM_ARG_DBD, arglist & CAM_ARG_MODE_EDIT, binary,
1764 		    retry_count, timeout);
1765 	}
1766 }
1767 
1768 static int
1769 scsicmd(struct cam_device *device, int argc, char **argv, char *combinedopt,
1770 	int retry_count, int timeout)
1771 {
1772 	union ccb *ccb;
1773 	u_int32_t flags = CAM_DIR_NONE;
1774 	u_int8_t *data_ptr = NULL;
1775 	u_int8_t cdb[20];
1776 	struct get_hook hook;
1777 	int c, data_bytes = 0;
1778 	int cdb_len = 0;
1779 	char *datastr = NULL, *tstr;
1780 	int error = 0;
1781 	int fd_data = 0;
1782 	int retval;
1783 
1784 	ccb = cam_getccb(device);
1785 
1786 	if (ccb == NULL) {
1787 		warnx("scsicmd: error allocating ccb");
1788 		return(1);
1789 	}
1790 
1791 	bzero(&(&ccb->ccb_h)[1],
1792 	      sizeof(struct ccb_scsiio) - sizeof(struct ccb_hdr));
1793 
1794 	while ((c = getopt(argc, argv, combinedopt)) != -1) {
1795 		switch(c) {
1796 		case 'c':
1797 			tstr = optarg;
1798 			while (isspace(*tstr) && (*tstr != '\0'))
1799 				tstr++;
1800 			hook.argc = argc - optind;
1801 			hook.argv = argv + optind;
1802 			hook.got = 0;
1803 			cdb_len = buff_encode_visit(cdb, sizeof(cdb), tstr,
1804 						    iget, &hook);
1805 			/*
1806 			 * Increment optind by the number of arguments the
1807 			 * encoding routine processed.  After each call to
1808 			 * getopt(3), optind points to the argument that
1809 			 * getopt should process _next_.  In this case,
1810 			 * that means it points to the first command string
1811 			 * argument, if there is one.  Once we increment
1812 			 * this, it should point to either the next command
1813 			 * line argument, or it should be past the end of
1814 			 * the list.
1815 			 */
1816 			optind += hook.got;
1817 			break;
1818 		case 'i':
1819 			if (arglist & CAM_ARG_CMD_OUT) {
1820 				warnx("command must either be "
1821 				      "read or write, not both");
1822 				error = 1;
1823 				goto scsicmd_bailout;
1824 			}
1825 			arglist |= CAM_ARG_CMD_IN;
1826 			flags = CAM_DIR_IN;
1827 			data_bytes = strtol(optarg, NULL, 0);
1828 			if (data_bytes <= 0) {
1829 				warnx("invalid number of input bytes %d",
1830 				      data_bytes);
1831 				error = 1;
1832 				goto scsicmd_bailout;
1833 			}
1834 			hook.argc = argc - optind;
1835 			hook.argv = argv + optind;
1836 			hook.got = 0;
1837 			optind++;
1838 			datastr = cget(&hook, NULL);
1839 			/*
1840 			 * If the user supplied "-" instead of a format, he
1841 			 * wants the data to be written to stdout.
1842 			 */
1843 			if ((datastr != NULL)
1844 			 && (datastr[0] == '-'))
1845 				fd_data = 1;
1846 
1847 			data_ptr = (u_int8_t *)malloc(data_bytes);
1848 			if (data_ptr == NULL) {
1849 				warnx("can't malloc memory for data_ptr");
1850 				error = 1;
1851 				goto scsicmd_bailout;
1852 			}
1853 			break;
1854 		case 'o':
1855 			if (arglist & CAM_ARG_CMD_IN) {
1856 				warnx("command must either be "
1857 				      "read or write, not both");
1858 				error = 1;
1859 				goto scsicmd_bailout;
1860 			}
1861 			arglist |= CAM_ARG_CMD_OUT;
1862 			flags = CAM_DIR_OUT;
1863 			data_bytes = strtol(optarg, NULL, 0);
1864 			if (data_bytes <= 0) {
1865 				warnx("invalid number of output bytes %d",
1866 				      data_bytes);
1867 				error = 1;
1868 				goto scsicmd_bailout;
1869 			}
1870 			hook.argc = argc - optind;
1871 			hook.argv = argv + optind;
1872 			hook.got = 0;
1873 			datastr = cget(&hook, NULL);
1874 			data_ptr = (u_int8_t *)malloc(data_bytes);
1875 			if (data_ptr == NULL) {
1876 				warnx("can't malloc memory for data_ptr");
1877 				error = 1;
1878 				goto scsicmd_bailout;
1879 			}
1880 			/*
1881 			 * If the user supplied "-" instead of a format, he
1882 			 * wants the data to be read from stdin.
1883 			 */
1884 			if ((datastr != NULL)
1885 			 && (datastr[0] == '-'))
1886 				fd_data = 1;
1887 			else
1888 				buff_encode_visit(data_ptr, data_bytes, datastr,
1889 						  iget, &hook);
1890 			optind += hook.got;
1891 			break;
1892 		default:
1893 			break;
1894 		}
1895 	}
1896 
1897 	/*
1898 	 * If fd_data is set, and we're writing to the device, we need to
1899 	 * read the data the user wants written from stdin.
1900 	 */
1901 	if ((fd_data == 1) && (arglist & CAM_ARG_CMD_OUT)) {
1902 		ssize_t amt_read;
1903 		int amt_to_read = data_bytes;
1904 		u_int8_t *buf_ptr = data_ptr;
1905 
1906 		for (amt_read = 0; amt_to_read > 0;
1907 		     amt_read = read(STDIN_FILENO, buf_ptr, amt_to_read)) {
1908 			if (amt_read == -1) {
1909 				warn("error reading data from stdin");
1910 				error = 1;
1911 				goto scsicmd_bailout;
1912 			}
1913 			amt_to_read -= amt_read;
1914 			buf_ptr += amt_read;
1915 		}
1916 	}
1917 
1918 	if (arglist & CAM_ARG_ERR_RECOVER)
1919 		flags |= CAM_PASS_ERR_RECOVER;
1920 
1921 	/* Disable freezing the device queue */
1922 	flags |= CAM_DEV_QFRZDIS;
1923 
1924 	/*
1925 	 * This is taken from the SCSI-3 draft spec.
1926 	 * (T10/1157D revision 0.3)
1927 	 * The top 3 bits of an opcode are the group code.  The next 5 bits
1928 	 * are the command code.
1929 	 * Group 0:  six byte commands
1930 	 * Group 1:  ten byte commands
1931 	 * Group 2:  ten byte commands
1932 	 * Group 3:  reserved
1933 	 * Group 4:  sixteen byte commands
1934 	 * Group 5:  twelve byte commands
1935 	 * Group 6:  vendor specific
1936 	 * Group 7:  vendor specific
1937 	 */
1938 	switch((cdb[0] >> 5) & 0x7) {
1939 		case 0:
1940 			cdb_len = 6;
1941 			break;
1942 		case 1:
1943 		case 2:
1944 			cdb_len = 10;
1945 			break;
1946 		case 3:
1947 		case 6:
1948 		case 7:
1949 		        /* computed by buff_encode_visit */
1950 			break;
1951 		case 4:
1952 			cdb_len = 16;
1953 			break;
1954 		case 5:
1955 			cdb_len = 12;
1956 			break;
1957 	}
1958 
1959 	/*
1960 	 * We should probably use csio_build_visit or something like that
1961 	 * here, but it's easier to encode arguments as you go.  The
1962 	 * alternative would be skipping the CDB argument and then encoding
1963 	 * it here, since we've got the data buffer argument by now.
1964 	 */
1965 	bcopy(cdb, &ccb->csio.cdb_io.cdb_bytes, cdb_len);
1966 
1967 	cam_fill_csio(&ccb->csio,
1968 		      /*retries*/ retry_count,
1969 		      /*cbfcnp*/ NULL,
1970 		      /*flags*/ flags,
1971 		      /*tag_action*/ MSG_SIMPLE_Q_TAG,
1972 		      /*data_ptr*/ data_ptr,
1973 		      /*dxfer_len*/ data_bytes,
1974 		      /*sense_len*/ SSD_FULL_SIZE,
1975 		      /*cdb_len*/ cdb_len,
1976 		      /*timeout*/ timeout ? timeout : 5000);
1977 
1978 	if (((retval = cam_send_ccb(device, ccb)) < 0)
1979 	 || ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP)) {
1980 		if (retval < 0)
1981 			warn("error sending command");
1982 		else
1983 			warnx("error sending command");
1984 
1985 		if (arglist & CAM_ARG_VERBOSE) {
1986 		 	if ((ccb->ccb_h.status & CAM_STATUS_MASK) ==
1987 			    CAM_SCSI_STATUS_ERROR)
1988 				scsi_sense_print(device, &ccb->csio, stderr);
1989 			else
1990 				fprintf(stderr, "CAM status is %#x\n",
1991 					ccb->ccb_h.status);
1992 		}
1993 
1994 		error = 1;
1995 		goto scsicmd_bailout;
1996 	}
1997 
1998 
1999 	if (((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP)
2000 	 && (arglist & CAM_ARG_CMD_IN)
2001 	 && (data_bytes > 0)) {
2002 		if (fd_data == 0) {
2003 			buff_decode_visit(data_ptr, data_bytes, datastr,
2004 					  arg_put, NULL);
2005 			fprintf(stdout, "\n");
2006 		} else {
2007 			ssize_t amt_written;
2008 			int amt_to_write = data_bytes;
2009 			u_int8_t *buf_ptr = data_ptr;
2010 
2011 			for (amt_written = 0; (amt_to_write > 0) &&
2012 			     (amt_written =write(1, buf_ptr,amt_to_write))> 0;){
2013 				amt_to_write -= amt_written;
2014 				buf_ptr += amt_written;
2015 			}
2016 			if (amt_written == -1) {
2017 				warn("error writing data to stdout");
2018 				error = 1;
2019 				goto scsicmd_bailout;
2020 			} else if ((amt_written == 0)
2021 				&& (amt_to_write > 0)) {
2022 				warnx("only wrote %u bytes out of %u",
2023 				      data_bytes - amt_to_write, data_bytes);
2024 			}
2025 		}
2026 	}
2027 
2028 scsicmd_bailout:
2029 
2030 	if ((data_bytes > 0) && (data_ptr != NULL))
2031 		free(data_ptr);
2032 
2033 	cam_freeccb(ccb);
2034 
2035 	return(error);
2036 }
2037 
2038 static int
2039 camdebug(int argc, char **argv, char *combinedopt)
2040 {
2041 	int c, fd;
2042 	int mybus = -1, mytarget = -1, mylun = -1;
2043 	char *tstr, *tmpstr = NULL;
2044 	union ccb ccb;
2045 	int error = 0;
2046 
2047 	bzero(&ccb, sizeof(union ccb));
2048 
2049 	while ((c = getopt(argc, argv, combinedopt)) != -1) {
2050 		switch(c) {
2051 		case 'I':
2052 			arglist |= CAM_ARG_DEBUG_INFO;
2053 			ccb.cdbg.flags |= CAM_DEBUG_INFO;
2054 			break;
2055 		case 'P':
2056 			arglist |= CAM_ARG_DEBUG_PERIPH;
2057 			ccb.cdbg.flags |= CAM_DEBUG_PERIPH;
2058 			break;
2059 		case 'S':
2060 			arglist |= CAM_ARG_DEBUG_SUBTRACE;
2061 			ccb.cdbg.flags |= CAM_DEBUG_SUBTRACE;
2062 			break;
2063 		case 'T':
2064 			arglist |= CAM_ARG_DEBUG_TRACE;
2065 			ccb.cdbg.flags |= CAM_DEBUG_TRACE;
2066 			break;
2067 		case 'X':
2068 			arglist |= CAM_ARG_DEBUG_XPT;
2069 			ccb.cdbg.flags |= CAM_DEBUG_XPT;
2070 			break;
2071 		case 'c':
2072 			arglist |= CAM_ARG_DEBUG_CDB;
2073 			ccb.cdbg.flags |= CAM_DEBUG_CDB;
2074 			break;
2075 		default:
2076 			break;
2077 		}
2078 	}
2079 
2080 	if ((fd = open(XPT_DEVICE, O_RDWR)) < 0) {
2081 		warnx("error opening transport layer device %s", XPT_DEVICE);
2082 		warn("%s", XPT_DEVICE);
2083 		return(1);
2084 	}
2085 	argc -= optind;
2086 	argv += optind;
2087 
2088 	if (argc <= 0) {
2089 		warnx("you must specify \"off\", \"all\" or a bus,");
2090 		warnx("bus:target, or bus:target:lun");
2091 		close(fd);
2092 		return(1);
2093 	}
2094 
2095 	tstr = *argv;
2096 
2097 	while (isspace(*tstr) && (*tstr != '\0'))
2098 		tstr++;
2099 
2100 	if (strncmp(tstr, "off", 3) == 0) {
2101 		ccb.cdbg.flags = CAM_DEBUG_NONE;
2102 		arglist &= ~(CAM_ARG_DEBUG_INFO|CAM_ARG_DEBUG_PERIPH|
2103 			     CAM_ARG_DEBUG_TRACE|CAM_ARG_DEBUG_SUBTRACE|
2104 			     CAM_ARG_DEBUG_XPT);
2105 	} else if (strncmp(tstr, "all", 3) != 0) {
2106 		tmpstr = (char *)strtok(tstr, ":");
2107 		if ((tmpstr != NULL) && (*tmpstr != '\0')){
2108 			mybus = strtol(tmpstr, NULL, 0);
2109 			arglist |= CAM_ARG_BUS;
2110 			tmpstr = (char *)strtok(NULL, ":");
2111 			if ((tmpstr != NULL) && (*tmpstr != '\0')){
2112 				mytarget = strtol(tmpstr, NULL, 0);
2113 				arglist |= CAM_ARG_TARGET;
2114 				tmpstr = (char *)strtok(NULL, ":");
2115 				if ((tmpstr != NULL) && (*tmpstr != '\0')){
2116 					mylun = strtol(tmpstr, NULL, 0);
2117 					arglist |= CAM_ARG_LUN;
2118 				}
2119 			}
2120 		} else {
2121 			error = 1;
2122 			warnx("you must specify \"all\", \"off\", or a bus,");
2123 			warnx("bus:target, or bus:target:lun to debug");
2124 		}
2125 	}
2126 
2127 	if (error == 0) {
2128 
2129 		ccb.ccb_h.func_code = XPT_DEBUG;
2130 		ccb.ccb_h.path_id = mybus;
2131 		ccb.ccb_h.target_id = mytarget;
2132 		ccb.ccb_h.target_lun = mylun;
2133 
2134 		if (ioctl(fd, CAMIOCOMMAND, &ccb) == -1) {
2135 			warn("CAMIOCOMMAND ioctl failed");
2136 			error = 1;
2137 		}
2138 
2139 		if (error == 0) {
2140 			if ((ccb.ccb_h.status & CAM_STATUS_MASK) ==
2141 			     CAM_FUNC_NOTAVAIL) {
2142 				warnx("CAM debugging not available");
2143 				warnx("you need to put options CAMDEBUG in"
2144 				      " your kernel config file!");
2145 				error = 1;
2146 			} else if ((ccb.ccb_h.status & CAM_STATUS_MASK) !=
2147 				    CAM_REQ_CMP) {
2148 				warnx("XPT_DEBUG CCB failed with status %#x",
2149 				      ccb.ccb_h.status);
2150 				error = 1;
2151 			} else {
2152 				if (ccb.cdbg.flags == CAM_DEBUG_NONE) {
2153 					fprintf(stderr,
2154 						"Debugging turned off\n");
2155 				} else {
2156 					fprintf(stderr,
2157 						"Debugging enabled for "
2158 						"%d:%d:%d\n",
2159 						mybus, mytarget, mylun);
2160 				}
2161 			}
2162 		}
2163 		close(fd);
2164 	}
2165 
2166 	return(error);
2167 }
2168 
2169 static int
2170 tagcontrol(struct cam_device *device, int argc, char **argv,
2171 	   char *combinedopt)
2172 {
2173 	int c;
2174 	union ccb *ccb;
2175 	int numtags = -1;
2176 	int retval = 0;
2177 	int quiet = 0;
2178 	char pathstr[1024];
2179 
2180 	ccb = cam_getccb(device);
2181 
2182 	if (ccb == NULL) {
2183 		warnx("tagcontrol: error allocating ccb");
2184 		return(1);
2185 	}
2186 
2187 	while ((c = getopt(argc, argv, combinedopt)) != -1) {
2188 		switch(c) {
2189 		case 'N':
2190 			numtags = strtol(optarg, NULL, 0);
2191 			if (numtags < 0) {
2192 				warnx("tag count %d is < 0", numtags);
2193 				retval = 1;
2194 				goto tagcontrol_bailout;
2195 			}
2196 			break;
2197 		case 'q':
2198 			quiet++;
2199 			break;
2200 		default:
2201 			break;
2202 		}
2203 	}
2204 
2205 	cam_path_string(device, pathstr, sizeof(pathstr));
2206 
2207 	if (numtags >= 0) {
2208 		bzero(&(&ccb->ccb_h)[1],
2209 		      sizeof(struct ccb_relsim) - sizeof(struct ccb_hdr));
2210 		ccb->ccb_h.func_code = XPT_REL_SIMQ;
2211 		ccb->crs.release_flags = RELSIM_ADJUST_OPENINGS;
2212 		ccb->crs.openings = numtags;
2213 
2214 
2215 		if (cam_send_ccb(device, ccb) < 0) {
2216 			perror("error sending XPT_REL_SIMQ CCB");
2217 			retval = 1;
2218 			goto tagcontrol_bailout;
2219 		}
2220 
2221 		if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
2222 			warnx("XPT_REL_SIMQ CCB failed, status %#x",
2223 			      ccb->ccb_h.status);
2224 			retval = 1;
2225 			goto tagcontrol_bailout;
2226 		}
2227 
2228 
2229 		if (quiet == 0)
2230 			fprintf(stdout, "%stagged openings now %d\n",
2231 				pathstr, ccb->crs.openings);
2232 	}
2233 
2234 	bzero(&(&ccb->ccb_h)[1],
2235 	      sizeof(struct ccb_getdevstats) - sizeof(struct ccb_hdr));
2236 
2237 	ccb->ccb_h.func_code = XPT_GDEV_STATS;
2238 
2239 	if (cam_send_ccb(device, ccb) < 0) {
2240 		perror("error sending XPT_GDEV_STATS CCB");
2241 		retval = 1;
2242 		goto tagcontrol_bailout;
2243 	}
2244 
2245 	if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
2246 		warnx("XPT_GDEV_STATS CCB failed, status %#x",
2247 		      ccb->ccb_h.status);
2248 		retval = 1;
2249 		goto tagcontrol_bailout;
2250 	}
2251 
2252 	if (arglist & CAM_ARG_VERBOSE) {
2253 		fprintf(stdout, "%s", pathstr);
2254 		fprintf(stdout, "dev_openings  %d\n", ccb->cgds.dev_openings);
2255 		fprintf(stdout, "%s", pathstr);
2256 		fprintf(stdout, "dev_active    %d\n", ccb->cgds.dev_active);
2257 		fprintf(stdout, "%s", pathstr);
2258 		fprintf(stdout, "devq_openings %d\n", ccb->cgds.devq_openings);
2259 		fprintf(stdout, "%s", pathstr);
2260 		fprintf(stdout, "devq_queued   %d\n", ccb->cgds.devq_queued);
2261 		fprintf(stdout, "%s", pathstr);
2262 		fprintf(stdout, "held          %d\n", ccb->cgds.held);
2263 		fprintf(stdout, "%s", pathstr);
2264 		fprintf(stdout, "mintags       %d\n", ccb->cgds.mintags);
2265 		fprintf(stdout, "%s", pathstr);
2266 		fprintf(stdout, "maxtags       %d\n", ccb->cgds.maxtags);
2267 	} else {
2268 		if (quiet == 0) {
2269 			fprintf(stdout, "%s", pathstr);
2270 			fprintf(stdout, "device openings: ");
2271 		}
2272 		fprintf(stdout, "%d\n", ccb->cgds.dev_openings +
2273 			ccb->cgds.dev_active);
2274 	}
2275 
2276 tagcontrol_bailout:
2277 
2278 	cam_freeccb(ccb);
2279 	return(retval);
2280 }
2281 
2282 static void
2283 cts_print(struct cam_device *device, struct ccb_trans_settings *cts)
2284 {
2285 	char pathstr[1024];
2286 
2287 	cam_path_string(device, pathstr, sizeof(pathstr));
2288 
2289 	if ((cts->valid & CCB_TRANS_SYNC_RATE_VALID) != 0) {
2290 
2291 		fprintf(stdout, "%ssync parameter: %d\n", pathstr,
2292 			cts->sync_period);
2293 
2294 		if (cts->sync_offset != 0) {
2295 			u_int freq;
2296 
2297 			freq = scsi_calc_syncsrate(cts->sync_period);
2298 			fprintf(stdout, "%sfrequency: %d.%03dMHz\n", pathstr,
2299 				freq / 1000, freq % 1000);
2300 		}
2301 	}
2302 
2303 	if (cts->valid & CCB_TRANS_SYNC_OFFSET_VALID)
2304 		fprintf(stdout, "%soffset: %d\n", pathstr, cts->sync_offset);
2305 
2306 	if (cts->valid & CCB_TRANS_BUS_WIDTH_VALID)
2307 		fprintf(stdout, "%sbus width: %d bits\n", pathstr,
2308 			(0x01 << cts->bus_width) * 8);
2309 
2310 	if (cts->valid & CCB_TRANS_DISC_VALID)
2311 		fprintf(stdout, "%sdisconnection is %s\n", pathstr,
2312 			(cts->flags & CCB_TRANS_DISC_ENB) ? "enabled" :
2313 			"disabled");
2314 
2315 	if (cts->valid & CCB_TRANS_TQ_VALID)
2316 		fprintf(stdout, "%stagged queueing is %s\n", pathstr,
2317 			(cts->flags & CCB_TRANS_TAG_ENB) ? "enabled" :
2318 			"disabled");
2319 
2320 }
2321 
2322 /*
2323  * Get a path inquiry CCB for the specified device.
2324  */
2325 static int
2326 get_cpi(struct cam_device *device, struct ccb_pathinq *cpi)
2327 {
2328 	union ccb *ccb;
2329 	int retval = 0;
2330 
2331 	ccb = cam_getccb(device);
2332 
2333 	if (ccb == NULL) {
2334 		warnx("get_cpi: couldn't allocate CCB");
2335 		return(1);
2336 	}
2337 
2338 	bzero(&(&ccb->ccb_h)[1],
2339 	      sizeof(struct ccb_pathinq) - sizeof(struct ccb_hdr));
2340 
2341 	ccb->ccb_h.func_code = XPT_PATH_INQ;
2342 
2343 	if (cam_send_ccb(device, ccb) < 0) {
2344 		warn("get_cpi: error sending Path Inquiry CCB");
2345 
2346 		if (arglist & CAM_ARG_VERBOSE)
2347 			fprintf(stderr, "CAM status is %#x\n",
2348 				ccb->ccb_h.status);
2349 
2350 		retval = 1;
2351 
2352 		goto get_cpi_bailout;
2353 	}
2354 
2355 	if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
2356 
2357 		if (arglist & CAM_ARG_VERBOSE)
2358 			fprintf(stderr, "get_cpi: CAM status is %#x\n",
2359 				ccb->ccb_h.status);
2360 
2361 		retval = 1;
2362 
2363 		goto get_cpi_bailout;
2364 	}
2365 
2366 	bcopy(&ccb->cpi, cpi, sizeof(struct ccb_pathinq));
2367 
2368 get_cpi_bailout:
2369 
2370 	cam_freeccb(ccb);
2371 
2372 	return(retval);
2373 }
2374 
2375 static void
2376 cpi_print(struct ccb_pathinq *cpi)
2377 {
2378 	char adapter_str[1024];
2379 	int i;
2380 
2381 	snprintf(adapter_str, sizeof(adapter_str),
2382 		 "%s%d:", cpi->dev_name, cpi->unit_number);
2383 
2384 	fprintf(stdout, "%s SIM/HBA version: %d\n", adapter_str,
2385 		cpi->version_num);
2386 
2387 	for (i = 1; i < 0xff; i = i << 1) {
2388 		const char *str;
2389 
2390 		if ((i & cpi->hba_inquiry) == 0)
2391 			continue;
2392 
2393 		fprintf(stdout, "%s supports ", adapter_str);
2394 
2395 		switch(i) {
2396 		case PI_MDP_ABLE:
2397 			str = "MDP message";
2398 			break;
2399 		case PI_WIDE_32:
2400 			str = "32 bit wide SCSI";
2401 			break;
2402 		case PI_WIDE_16:
2403 			str = "16 bit wide SCSI";
2404 			break;
2405 		case PI_SDTR_ABLE:
2406 			str = "SDTR message";
2407 			break;
2408 		case PI_LINKED_CDB:
2409 			str = "linked CDBs";
2410 			break;
2411 		case PI_TAG_ABLE:
2412 			str = "tag queue messages";
2413 			break;
2414 		case PI_SOFT_RST:
2415 			str = "soft reset alternative";
2416 			break;
2417 		default:
2418 			str = "unknown PI bit set";
2419 			break;
2420 		}
2421 		fprintf(stdout, "%s\n", str);
2422 	}
2423 
2424 	for (i = 1; i < 0xff; i = i << 1) {
2425 		const char *str;
2426 
2427 		if ((i & cpi->hba_misc) == 0)
2428 			continue;
2429 
2430 		fprintf(stdout, "%s ", adapter_str);
2431 
2432 		switch(i) {
2433 		case PIM_SCANHILO:
2434 			str = "bus scans from high ID to low ID";
2435 			break;
2436 		case PIM_NOREMOVE:
2437 			str = "removable devices not included in scan";
2438 			break;
2439 		case PIM_NOINITIATOR:
2440 			str = "initiator role not supported";
2441 			break;
2442 		case PIM_NOBUSRESET:
2443 			str = "user has disabled initial BUS RESET or"
2444 			      " controller is in target/mixed mode";
2445 			break;
2446 		default:
2447 			str = "unknown PIM bit set";
2448 			break;
2449 		}
2450 		fprintf(stdout, "%s\n", str);
2451 	}
2452 
2453 	for (i = 1; i < 0xff; i = i << 1) {
2454 		const char *str;
2455 
2456 		if ((i & cpi->target_sprt) == 0)
2457 			continue;
2458 
2459 		fprintf(stdout, "%s supports ", adapter_str);
2460 		switch(i) {
2461 		case PIT_PROCESSOR:
2462 			str = "target mode processor mode";
2463 			break;
2464 		case PIT_PHASE:
2465 			str = "target mode phase cog. mode";
2466 			break;
2467 		case PIT_DISCONNECT:
2468 			str = "disconnects in target mode";
2469 			break;
2470 		case PIT_TERM_IO:
2471 			str = "terminate I/O message in target mode";
2472 			break;
2473 		case PIT_GRP_6:
2474 			str = "group 6 commands in target mode";
2475 			break;
2476 		case PIT_GRP_7:
2477 			str = "group 7 commands in target mode";
2478 			break;
2479 		default:
2480 			str = "unknown PIT bit set";
2481 			break;
2482 		}
2483 
2484 		fprintf(stdout, "%s\n", str);
2485 	}
2486 	fprintf(stdout, "%s HBA engine count: %d\n", adapter_str,
2487 		cpi->hba_eng_cnt);
2488 	fprintf(stdout, "%s maximum target: %d\n", adapter_str,
2489 		cpi->max_target);
2490 	fprintf(stdout, "%s maximum LUN: %d\n", adapter_str,
2491 		cpi->max_lun);
2492 	fprintf(stdout, "%s highest path ID in subsystem: %d\n",
2493 		adapter_str, cpi->hpath_id);
2494 	fprintf(stdout, "%s initiator ID: %d\n", adapter_str,
2495 		cpi->initiator_id);
2496 	fprintf(stdout, "%s SIM vendor: %s\n", adapter_str, cpi->sim_vid);
2497 	fprintf(stdout, "%s HBA vendor: %s\n", adapter_str, cpi->hba_vid);
2498 	fprintf(stdout, "%s bus ID: %d\n", adapter_str, cpi->bus_id);
2499 	fprintf(stdout, "%s base transfer speed: ", adapter_str);
2500 	if (cpi->base_transfer_speed > 1000)
2501 		fprintf(stdout, "%d.%03dMB/sec\n",
2502 			cpi->base_transfer_speed / 1000,
2503 			cpi->base_transfer_speed % 1000);
2504 	else
2505 		fprintf(stdout, "%dKB/sec\n",
2506 			(cpi->base_transfer_speed % 1000) * 1000);
2507 }
2508 
2509 static int
2510 get_print_cts(struct cam_device *device, int user_settings, int quiet,
2511 	      struct ccb_trans_settings *cts)
2512 {
2513 	int retval;
2514 	union ccb *ccb;
2515 
2516 	retval = 0;
2517 	ccb = cam_getccb(device);
2518 
2519 	if (ccb == NULL) {
2520 		warnx("get_print_cts: error allocating ccb");
2521 		return(1);
2522 	}
2523 
2524 	bzero(&(&ccb->ccb_h)[1],
2525 	      sizeof(struct ccb_trans_settings) - sizeof(struct ccb_hdr));
2526 
2527 	ccb->ccb_h.func_code = XPT_GET_TRAN_SETTINGS;
2528 
2529 	if (user_settings == 0)
2530 		ccb->cts.flags = CCB_TRANS_CURRENT_SETTINGS;
2531 	else
2532 		ccb->cts.flags = CCB_TRANS_USER_SETTINGS;
2533 
2534 	if (cam_send_ccb(device, ccb) < 0) {
2535 		perror("error sending XPT_GET_TRAN_SETTINGS CCB");
2536 		retval = 1;
2537 		goto get_print_cts_bailout;
2538 	}
2539 
2540 	if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
2541 		warnx("XPT_GET_TRANS_SETTINGS CCB failed, status %#x",
2542 		      ccb->ccb_h.status);
2543 		retval = 1;
2544 		goto get_print_cts_bailout;
2545 	}
2546 
2547 	if (quiet == 0)
2548 		cts_print(device, &ccb->cts);
2549 
2550 	if (cts != NULL)
2551 		bcopy(&ccb->cts, cts, sizeof(struct ccb_trans_settings));
2552 
2553 get_print_cts_bailout:
2554 
2555 	cam_freeccb(ccb);
2556 
2557 	return(retval);
2558 }
2559 
2560 static int
2561 ratecontrol(struct cam_device *device, int retry_count, int timeout,
2562 	    int argc, char **argv, char *combinedopt)
2563 {
2564 	int c;
2565 	union ccb *ccb;
2566 	int user_settings = 0;
2567 	int retval = 0;
2568 	int disc_enable = -1, tag_enable = -1;
2569 	int offset = -1;
2570 	double syncrate = -1;
2571 	int bus_width = -1;
2572 	int quiet = 0;
2573 	int change_settings = 0, send_tur = 0;
2574 	struct ccb_pathinq cpi;
2575 
2576 	ccb = cam_getccb(device);
2577 
2578 	if (ccb == NULL) {
2579 		warnx("ratecontrol: error allocating ccb");
2580 		return(1);
2581 	}
2582 
2583 	while ((c = getopt(argc, argv, combinedopt)) != -1) {
2584 		switch(c){
2585 		case 'a':
2586 			send_tur = 1;
2587 			break;
2588 		case 'c':
2589 			user_settings = 0;
2590 			break;
2591 		case 'D':
2592 			if (strncasecmp(optarg, "enable", 6) == 0)
2593 				disc_enable = 1;
2594 			else if (strncasecmp(optarg, "disable", 7) == 0)
2595 				disc_enable = 0;
2596 			else {
2597 				warnx("-D argument \"%s\" is unknown", optarg);
2598 				retval = 1;
2599 				goto ratecontrol_bailout;
2600 			}
2601 			change_settings = 1;
2602 			break;
2603 		case 'O':
2604 			offset = strtol(optarg, NULL, 0);
2605 			if (offset < 0) {
2606 				warnx("offset value %d is < 0", offset);
2607 				retval = 1;
2608 				goto ratecontrol_bailout;
2609 			}
2610 			change_settings = 1;
2611 			break;
2612 		case 'q':
2613 			quiet++;
2614 			break;
2615 		case 'R':
2616 			syncrate = atof(optarg);
2617 
2618 			if (syncrate < 0) {
2619 				warnx("sync rate %f is < 0", syncrate);
2620 				retval = 1;
2621 				goto ratecontrol_bailout;
2622 			}
2623 			change_settings = 1;
2624 			break;
2625 		case 'T':
2626 			if (strncasecmp(optarg, "enable", 6) == 0)
2627 				tag_enable = 1;
2628 			else if (strncasecmp(optarg, "disable", 7) == 0)
2629 				tag_enable = 0;
2630 			else {
2631 				warnx("-T argument \"%s\" is unknown", optarg);
2632 				retval = 1;
2633 				goto ratecontrol_bailout;
2634 			}
2635 			change_settings = 1;
2636 			break;
2637 		case 'U':
2638 			user_settings = 1;
2639 			break;
2640 		case 'W':
2641 			bus_width = strtol(optarg, NULL, 0);
2642 			if (bus_width < 0) {
2643 				warnx("bus width %d is < 0", bus_width);
2644 				retval = 1;
2645 				goto ratecontrol_bailout;
2646 			}
2647 			change_settings = 1;
2648 			break;
2649 		default:
2650 			break;
2651 		}
2652 	}
2653 
2654 	bzero(&(&ccb->ccb_h)[1],
2655 	      sizeof(struct ccb_pathinq) - sizeof(struct ccb_hdr));
2656 
2657 	/*
2658 	 * Grab path inquiry information, so we can determine whether
2659 	 * or not the initiator is capable of the things that the user
2660 	 * requests.
2661 	 */
2662 	ccb->ccb_h.func_code = XPT_PATH_INQ;
2663 
2664 	if (cam_send_ccb(device, ccb) < 0) {
2665 		perror("error sending XPT_PATH_INQ CCB");
2666 		retval = 1;
2667 		goto ratecontrol_bailout;
2668 	}
2669 
2670 	if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
2671 		warnx("XPT_PATH_INQ CCB failed, status %#x",
2672 		      ccb->ccb_h.status);
2673 		retval = 1;
2674 		goto ratecontrol_bailout;
2675 	}
2676 
2677 	bcopy(&ccb->cpi, &cpi, sizeof(struct ccb_pathinq));
2678 
2679 	bzero(&(&ccb->ccb_h)[1],
2680 	      sizeof(struct ccb_trans_settings) - sizeof(struct ccb_hdr));
2681 
2682 	if (quiet == 0)
2683 		fprintf(stdout, "Current Parameters:\n");
2684 
2685 	retval = get_print_cts(device, user_settings, quiet, &ccb->cts);
2686 
2687 	if (retval != 0)
2688 		goto ratecontrol_bailout;
2689 
2690 	if (arglist & CAM_ARG_VERBOSE)
2691 		cpi_print(&cpi);
2692 
2693 	if (change_settings) {
2694 		if (disc_enable != -1) {
2695 			ccb->cts.valid |= CCB_TRANS_DISC_VALID;
2696 			if (disc_enable == 0)
2697 				ccb->cts.flags &= ~CCB_TRANS_DISC_ENB;
2698 			else
2699 				ccb->cts.flags |= CCB_TRANS_DISC_ENB;
2700 		} else
2701 			ccb->cts.valid &= ~CCB_TRANS_DISC_VALID;
2702 
2703 		if (tag_enable != -1) {
2704 			if ((cpi.hba_inquiry & PI_TAG_ABLE) == 0) {
2705 				warnx("HBA does not support tagged queueing, "
2706 				      "so you cannot modify tag settings");
2707 				retval = 1;
2708 				goto ratecontrol_bailout;
2709 			}
2710 
2711 			ccb->cts.valid |= CCB_TRANS_TQ_VALID;
2712 
2713 			if (tag_enable == 0)
2714 				ccb->cts.flags &= ~CCB_TRANS_TAG_ENB;
2715 			else
2716 				ccb->cts.flags |= CCB_TRANS_TAG_ENB;
2717 		} else
2718 			ccb->cts.valid &= ~CCB_TRANS_TQ_VALID;
2719 
2720 		if (offset != -1) {
2721 			if ((cpi.hba_inquiry & PI_SDTR_ABLE) == 0) {
2722 				warnx("HBA at %s%d is not cable of changing "
2723 				      "offset", cpi.dev_name,
2724 				      cpi.unit_number);
2725 				retval = 1;
2726 				goto ratecontrol_bailout;
2727 			}
2728 			ccb->cts.valid |= CCB_TRANS_SYNC_OFFSET_VALID;
2729 			ccb->cts.sync_offset = offset;
2730 		} else
2731 			ccb->cts.valid &= ~CCB_TRANS_SYNC_OFFSET_VALID;
2732 
2733 		if (syncrate != -1) {
2734 			int prelim_sync_period;
2735 			u_int freq;
2736 
2737 			if ((cpi.hba_inquiry & PI_SDTR_ABLE) == 0) {
2738 				warnx("HBA at %s%d is not cable of changing "
2739 				      "transfer rates", cpi.dev_name,
2740 				      cpi.unit_number);
2741 				retval = 1;
2742 				goto ratecontrol_bailout;
2743 			}
2744 
2745 			ccb->cts.valid |= CCB_TRANS_SYNC_RATE_VALID;
2746 
2747 			/*
2748 			 * The sync rate the user gives us is in MHz.
2749 			 * We need to translate it into KHz for this
2750 			 * calculation.
2751 			 */
2752 			syncrate *= 1000;
2753 
2754 			/*
2755 			 * Next, we calculate a "preliminary" sync period
2756 			 * in tenths of a nanosecond.
2757 			 */
2758 			if (syncrate == 0)
2759 				prelim_sync_period = 0;
2760 			else
2761 				prelim_sync_period = 10000000 / syncrate;
2762 
2763 			ccb->cts.sync_period =
2764 				scsi_calc_syncparam(prelim_sync_period);
2765 
2766 			freq = scsi_calc_syncsrate(ccb->cts.sync_period);
2767 		} else
2768 			ccb->cts.valid &= ~CCB_TRANS_SYNC_RATE_VALID;
2769 
2770 		/*
2771 		 * The bus_width argument goes like this:
2772 		 * 0 == 8 bit
2773 		 * 1 == 16 bit
2774 		 * 2 == 32 bit
2775 		 * Therefore, if you shift the number of bits given on the
2776 		 * command line right by 4, you should get the correct
2777 		 * number.
2778 		 */
2779 		if (bus_width != -1) {
2780 
2781 			/*
2782 			 * We might as well validate things here with a
2783 			 * decipherable error message, rather than what
2784 			 * will probably be an indecipherable error message
2785 			 * by the time it gets back to us.
2786 			 */
2787 			if ((bus_width == 16)
2788 			 && ((cpi.hba_inquiry & PI_WIDE_16) == 0)) {
2789 				warnx("HBA does not support 16 bit bus width");
2790 				retval = 1;
2791 				goto ratecontrol_bailout;
2792 			} else if ((bus_width == 32)
2793 				&& ((cpi.hba_inquiry & PI_WIDE_32) == 0)) {
2794 				warnx("HBA does not support 32 bit bus width");
2795 				retval = 1;
2796 				goto ratecontrol_bailout;
2797 			} else if ((bus_width != 8)
2798 				&& (bus_width != 16)
2799 				&& (bus_width != 32)) {
2800 				warnx("Invalid bus width %d", bus_width);
2801 				retval = 1;
2802 				goto ratecontrol_bailout;
2803 			}
2804 
2805 			ccb->cts.valid |= CCB_TRANS_BUS_WIDTH_VALID;
2806 			ccb->cts.bus_width = bus_width >> 4;
2807 		} else
2808 			ccb->cts.valid &= ~CCB_TRANS_BUS_WIDTH_VALID;
2809 
2810 		ccb->ccb_h.func_code = XPT_SET_TRAN_SETTINGS;
2811 
2812 		if (cam_send_ccb(device, ccb) < 0) {
2813 			perror("error sending XPT_SET_TRAN_SETTINGS CCB");
2814 			retval = 1;
2815 			goto ratecontrol_bailout;
2816 		}
2817 
2818 		if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
2819 			warnx("XPT_SET_TRANS_SETTINGS CCB failed, status %#x",
2820 			      ccb->ccb_h.status);
2821 			retval = 1;
2822 			goto ratecontrol_bailout;
2823 		}
2824 	}
2825 
2826 	if (send_tur) {
2827 		retval = testunitready(device, retry_count, timeout,
2828 				       (arglist & CAM_ARG_VERBOSE) ? 0 : 1);
2829 
2830 		/*
2831 		 * If the TUR didn't succeed, just bail.
2832 		 */
2833 		if (retval != 0) {
2834 			if (quiet == 0)
2835 				fprintf(stderr, "Test Unit Ready failed\n");
2836 			goto ratecontrol_bailout;
2837 		}
2838 
2839 		/*
2840 		 * If the user wants things quiet, there's no sense in
2841 		 * getting the transfer settings, if we're not going
2842 		 * to print them.
2843 		 */
2844 		if (quiet != 0)
2845 			goto ratecontrol_bailout;
2846 
2847 		fprintf(stdout, "New Parameters:\n");
2848 		retval = get_print_cts(device, user_settings, 0, NULL);
2849 	}
2850 
2851 ratecontrol_bailout:
2852 
2853 	cam_freeccb(ccb);
2854 	return(retval);
2855 }
2856 
2857 static int
2858 scsiformat(struct cam_device *device, int argc, char **argv,
2859 	   char *combinedopt, int retry_count, int timeout)
2860 {
2861 	union ccb *ccb;
2862 	int c;
2863 	int ycount = 0, quiet = 0;
2864 	int error = 0, response = 0, retval = 0;
2865 	int use_timeout = 10800 * 1000;
2866 	int immediate = 1;
2867 	struct format_defect_list_header fh;
2868 	u_int8_t *data_ptr = NULL;
2869 	u_int32_t dxfer_len = 0;
2870 	u_int8_t byte2 = 0;
2871 	int num_warnings = 0;
2872 
2873 	ccb = cam_getccb(device);
2874 
2875 	if (ccb == NULL) {
2876 		warnx("scsiformat: error allocating ccb");
2877 		return(1);
2878 	}
2879 
2880 	bzero(&(&ccb->ccb_h)[1],
2881 	      sizeof(struct ccb_scsiio) - sizeof(struct ccb_hdr));
2882 
2883 	while ((c = getopt(argc, argv, combinedopt)) != -1) {
2884 		switch(c) {
2885 		case 'q':
2886 			quiet++;
2887 			break;
2888 		case 'w':
2889 			immediate = 0;
2890 			break;
2891 		case 'y':
2892 			ycount++;
2893 			break;
2894 		}
2895 	}
2896 
2897 	if (quiet == 0) {
2898 		fprintf(stdout, "You are about to REMOVE ALL DATA from the "
2899 			"following device:\n");
2900 
2901 		error = scsidoinquiry(device, argc, argv, combinedopt,
2902 				      retry_count, timeout);
2903 
2904 		if (error != 0) {
2905 			warnx("scsiformat: error sending inquiry");
2906 			goto scsiformat_bailout;
2907 		}
2908 	}
2909 
2910 	if (ycount == 0) {
2911 
2912 		do {
2913 			char str[1024];
2914 
2915 			fprintf(stdout, "Are you SURE you want to do "
2916 				"this? (yes/no) ");
2917 
2918 			if (fgets(str, sizeof(str), stdin) != NULL) {
2919 
2920 				if (strncasecmp(str, "yes", 3) == 0)
2921 					response = 1;
2922 				else if (strncasecmp(str, "no", 2) == 0)
2923 					response = -1;
2924 				else {
2925 					fprintf(stdout, "Please answer"
2926 						" \"yes\" or \"no\"\n");
2927 				}
2928 			}
2929 		} while (response == 0);
2930 
2931 		if (response == -1) {
2932 			error = 1;
2933 			goto scsiformat_bailout;
2934 		}
2935 	}
2936 
2937 	if (timeout != 0)
2938 		use_timeout = timeout;
2939 
2940 	if (quiet == 0) {
2941 		fprintf(stdout, "Current format timeout is %d seconds\n",
2942 			use_timeout / 1000);
2943 	}
2944 
2945 	/*
2946 	 * If the user hasn't disabled questions and didn't specify a
2947 	 * timeout on the command line, ask them if they want the current
2948 	 * timeout.
2949 	 */
2950 	if ((ycount == 0)
2951 	 && (timeout == 0)) {
2952 		char str[1024];
2953 		int new_timeout = 0;
2954 
2955 		fprintf(stdout, "Enter new timeout in seconds or press\n"
2956 			"return to keep the current timeout [%d] ",
2957 			use_timeout / 1000);
2958 
2959 		if (fgets(str, sizeof(str), stdin) != NULL) {
2960 			if (str[0] != '\0')
2961 				new_timeout = atoi(str);
2962 		}
2963 
2964 		if (new_timeout != 0) {
2965 			use_timeout = new_timeout * 1000;
2966 			fprintf(stdout, "Using new timeout value %d\n",
2967 				use_timeout / 1000);
2968 		}
2969 	}
2970 
2971 	/*
2972 	 * Keep this outside the if block below to silence any unused
2973 	 * variable warnings.
2974 	 */
2975 	bzero(&fh, sizeof(fh));
2976 
2977 	/*
2978 	 * If we're in immediate mode, we've got to include the format
2979 	 * header
2980 	 */
2981 	if (immediate != 0) {
2982 		fh.byte2 = FU_DLH_IMMED;
2983 		data_ptr = (u_int8_t *)&fh;
2984 		dxfer_len = sizeof(fh);
2985 		byte2 = FU_FMT_DATA;
2986 	} else if (quiet == 0) {
2987 		fprintf(stdout, "Formatting...");
2988 		fflush(stdout);
2989 	}
2990 
2991 	scsi_format_unit(&ccb->csio,
2992 			 /* retries */ retry_count,
2993 			 /* cbfcnp */ NULL,
2994 			 /* tag_action */ MSG_SIMPLE_Q_TAG,
2995 			 /* byte2 */ byte2,
2996 			 /* ileave */ 0,
2997 			 /* data_ptr */ data_ptr,
2998 			 /* dxfer_len */ dxfer_len,
2999 			 /* sense_len */ SSD_FULL_SIZE,
3000 			 /* timeout */ use_timeout);
3001 
3002 	/* Disable freezing the device queue */
3003 	ccb->ccb_h.flags |= CAM_DEV_QFRZDIS;
3004 
3005 	if (arglist & CAM_ARG_ERR_RECOVER)
3006 		ccb->ccb_h.flags |= CAM_PASS_ERR_RECOVER;
3007 
3008 	if (((retval = cam_send_ccb(device, ccb)) < 0)
3009 	 || ((immediate == 0)
3010 	   && ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP))) {
3011 		const char errstr[] = "error sending format command";
3012 
3013 		if (retval < 0)
3014 			warn(errstr);
3015 		else
3016 			warnx(errstr);
3017 
3018 		if (arglist & CAM_ARG_VERBOSE) {
3019 			if ((ccb->ccb_h.status & CAM_STATUS_MASK) ==
3020 			    CAM_SCSI_STATUS_ERROR)
3021 				scsi_sense_print(device, &ccb->csio, stderr);
3022 			else
3023 				fprintf(stderr, "CAM status is %#x\n",
3024 					ccb->ccb_h.status);
3025 		}
3026 		error = 1;
3027 		goto scsiformat_bailout;
3028 	}
3029 
3030 	/*
3031 	 * If we ran in non-immediate mode, we already checked for errors
3032 	 * above and printed out any necessary information.  If we're in
3033 	 * immediate mode, we need to loop through and get status
3034 	 * information periodically.
3035 	 */
3036 	if (immediate == 0) {
3037 		if (quiet == 0) {
3038 			fprintf(stdout, "Format Complete\n");
3039 		}
3040 		goto scsiformat_bailout;
3041 	}
3042 
3043 	do {
3044 		cam_status status;
3045 
3046 		bzero(&(&ccb->ccb_h)[1],
3047 		      sizeof(struct ccb_scsiio) - sizeof(struct ccb_hdr));
3048 
3049 		/*
3050 		 * There's really no need to do error recovery or
3051 		 * retries here, since we're just going to sit in a
3052 		 * loop and wait for the device to finish formatting.
3053 		 */
3054 		scsi_test_unit_ready(&ccb->csio,
3055 				     /* retries */ 0,
3056 				     /* cbfcnp */ NULL,
3057 				     /* tag_action */ MSG_SIMPLE_Q_TAG,
3058 				     /* sense_len */ SSD_FULL_SIZE,
3059 				     /* timeout */ 5000);
3060 
3061 		/* Disable freezing the device queue */
3062 		ccb->ccb_h.flags |= CAM_DEV_QFRZDIS;
3063 
3064 		retval = cam_send_ccb(device, ccb);
3065 
3066 		/*
3067 		 * If we get an error from the ioctl, bail out.  SCSI
3068 		 * errors are expected.
3069 		 */
3070 		if (retval < 0) {
3071 			warn("error sending CAMIOCOMMAND ioctl");
3072 			if (arglist & CAM_ARG_VERBOSE) {
3073 				if ((ccb->ccb_h.status & CAM_STATUS_MASK) ==
3074 				    CAM_SCSI_STATUS_ERROR)
3075 					scsi_sense_print(device, &ccb->csio,
3076 							 stderr);
3077 				else
3078 					fprintf(stderr, "CAM status is %#x\n",
3079 						ccb->ccb_h.status);
3080 			}
3081 			error = 1;
3082 			goto scsiformat_bailout;
3083 		}
3084 
3085 		status = ccb->ccb_h.status & CAM_STATUS_MASK;
3086 
3087 		if ((status != CAM_REQ_CMP)
3088 		 && (status == CAM_SCSI_STATUS_ERROR)) {
3089 			struct scsi_sense_data *sense;
3090 			int error_code, sense_key, asc, ascq;
3091 
3092 			sense = &ccb->csio.sense_data;
3093 			scsi_extract_sense(sense, &error_code, &sense_key,
3094 					   &asc, &ascq);
3095 
3096 			/*
3097 			 * According to the SCSI-2 and SCSI-3 specs, a
3098 			 * drive that is in the middle of a format should
3099 			 * return NOT READY with an ASC of "logical unit
3100 			 * not ready, format in progress".  The sense key
3101 			 * specific bytes will then be a progress indicator.
3102 			 */
3103 			if ((sense_key == SSD_KEY_NOT_READY)
3104 			 && (asc == 0x04) && (ascq == 0x04)) {
3105 				if ((sense->extra_len >= 10)
3106 				 && ((sense->sense_key_spec[0] &
3107 				      SSD_SCS_VALID) != 0)
3108 				 && (quiet == 0)) {
3109 					int val;
3110 					u_int64_t percentage;
3111 
3112 					val = scsi_2btoul(
3113 						&sense->sense_key_spec[1]);
3114 					percentage = 10000 * val;
3115 
3116 					fprintf(stdout,
3117 						"\rFormatting:  %qd.%02qd %% "
3118 						"(%d/%d) done",
3119 						percentage / (0x10000 * 100),
3120 						(percentage / 0x10000) % 100,
3121 						val, 0x10000);
3122 					fflush(stdout);
3123 				} else if ((quiet == 0)
3124 					&& (++num_warnings <= 1)) {
3125 					warnx("Unexpected SCSI Sense Key "
3126 					      "Specific value returned "
3127 					      "during format:");
3128 					scsi_sense_print(device, &ccb->csio,
3129 							 stderr);
3130 					warnx("Unable to print status "
3131 					      "information, but format will "
3132 					      "proceed.");
3133 					warnx("will exit when format is "
3134 					      "complete");
3135 				}
3136 				sleep(1);
3137 			} else {
3138 				warnx("Unexpected SCSI error during format");
3139 				scsi_sense_print(device, &ccb->csio, stderr);
3140 				error = 1;
3141 				goto scsiformat_bailout;
3142 			}
3143 
3144 		} else if (status != CAM_REQ_CMP) {
3145 			warnx("Unexpected CAM status %#x", status);
3146 			error = 1;
3147 			goto scsiformat_bailout;
3148 		}
3149 
3150 	} while((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP);
3151 
3152 	if (quiet == 0)
3153 		fprintf(stdout, "\nFormat Complete\n");
3154 
3155 scsiformat_bailout:
3156 
3157 	cam_freeccb(ccb);
3158 
3159 	return(error);
3160 }
3161 #endif /* MINIMALISTIC */
3162 
3163 void
3164 usage(int verbose)
3165 {
3166 	fprintf(verbose ? stdout : stderr,
3167 "usage:  camcontrol <command>  [device id][generic args][command args]\n"
3168 "        camcontrol devlist    [-v]\n"
3169 #ifndef MINIMALISTIC
3170 "        camcontrol periphlist [dev_id][-n dev_name] [-u unit]\n"
3171 "        camcontrol tur        [dev_id][generic args]\n"
3172 "        camcontrol inquiry    [dev_id][generic args] [-D] [-S] [-R]\n"
3173 "        camcontrol start      [dev_id][generic args]\n"
3174 "        camcontrol stop       [dev_id][generic args]\n"
3175 "        camcontrol load       [dev_id][generic args]\n"
3176 "        camcontrol eject      [dev_id][generic args]\n"
3177 #endif /* MINIMALISTIC */
3178 "        camcontrol rescan     <all | bus[:target:lun]>\n"
3179 "        camcontrol reset      <all | bus[:target:lun]>\n"
3180 #ifndef MINIMALISTIC
3181 "        camcontrol defects    [dev_id][generic args] <-f format> [-P][-G]\n"
3182 "        camcontrol modepage   [dev_id][generic args] <-m page | -l>\n"
3183 "                              [-P pagectl][-e | -b][-d]\n"
3184 "        camcontrol cmd        [dev_id][generic args] <-c cmd [args]>\n"
3185 "                              [-i len fmt|-o len fmt [args]]\n"
3186 "        camcontrol debug      [-I][-P][-T][-S][-X][-c]\n"
3187 "                              <all|bus[:target[:lun]]|off>\n"
3188 "        camcontrol tags       [dev_id][generic args] [-N tags] [-q] [-v]\n"
3189 "        camcontrol negotiate  [dev_id][generic args] [-a][-c]\n"
3190 "                              [-D <enable|disable>][-O offset][-q]\n"
3191 "                              [-R syncrate][-v][-T <enable|disable>]\n"
3192 "                              [-U][-W bus_width]\n"
3193 "        camcontrol format     [dev_id][generic args][-q][-w][-y]\n"
3194 #endif /* MINIMALISTIC */
3195 "        camcontrol help\n");
3196 	if (!verbose)
3197 		return;
3198 #ifndef MINIMALISTIC
3199 	fprintf(stdout,
3200 "Specify one of the following options:\n"
3201 "devlist     list all CAM devices\n"
3202 "periphlist  list all CAM peripheral drivers attached to a device\n"
3203 "tur         send a test unit ready to the named device\n"
3204 "inquiry     send a SCSI inquiry command to the named device\n"
3205 "start       send a Start Unit command to the device\n"
3206 "stop        send a Stop Unit command to the device\n"
3207 "load        send a Start Unit command to the device with the load bit set\n"
3208 "eject       send a Stop Unit command to the device with the eject bit set\n"
3209 "rescan      rescan all busses, the given bus, or bus:target:lun\n"
3210 "reset       reset all busses, the given bus, or bus:target:lun\n"
3211 "defects     read the defect list of the specified device\n"
3212 "modepage    display or edit (-e) the given mode page\n"
3213 "cmd         send the given scsi command, may need -i or -o as well\n"
3214 "debug       turn debugging on/off for a bus, target, or lun, or all devices\n"
3215 "tags        report or set the number of transaction slots for a device\n"
3216 "negotiate   report or set device negotiation parameters\n"
3217 "format      send the SCSI FORMAT UNIT command to the named device\n"
3218 "help        this message\n"
3219 "Device Identifiers:\n"
3220 "bus:target        specify the bus and target, lun defaults to 0\n"
3221 "bus:target:lun    specify the bus, target and lun\n"
3222 "deviceUNIT        specify the device name, like \"da4\" or \"cd2\"\n"
3223 "Generic arguments:\n"
3224 "-v                be verbose, print out sense information\n"
3225 "-t timeout        command timeout in seconds, overrides default timeout\n"
3226 "-n dev_name       specify device name, e.g. \"da\", \"cd\"\n"
3227 "-u unit           specify unit number, e.g. \"0\", \"5\"\n"
3228 "-E                have the kernel attempt to perform SCSI error recovery\n"
3229 "-C count          specify the SCSI command retry count (needs -E to work)\n"
3230 "modepage arguments:\n"
3231 "-l                list all available mode pages\n"
3232 "-m page           specify the mode page to view or edit\n"
3233 "-e                edit the specified mode page\n"
3234 "-b                force view to binary mode\n"
3235 "-d                disable block descriptors for mode sense\n"
3236 "-P pgctl          page control field 0-3\n"
3237 "defects arguments:\n"
3238 "-f format         specify defect list format (block, bfi or phys)\n"
3239 "-G                get the grown defect list\n"
3240 "-P                get the permanant defect list\n"
3241 "inquiry arguments:\n"
3242 "-D                get the standard inquiry data\n"
3243 "-S                get the serial number\n"
3244 "-R                get the transfer rate, etc.\n"
3245 "cmd arguments:\n"
3246 "-c cdb [args]     specify the SCSI CDB\n"
3247 "-i len fmt        specify input data and input data format\n"
3248 "-o len fmt [args] specify output data and output data fmt\n"
3249 "debug arguments:\n"
3250 "-I                CAM_DEBUG_INFO -- scsi commands, errors, data\n"
3251 "-T                CAM_DEBUG_TRACE -- routine flow tracking\n"
3252 "-S                CAM_DEBUG_SUBTRACE -- internal routine command flow\n"
3253 "-c                CAM_DEBUG_CDB -- print out SCSI CDBs only\n"
3254 "tags arguments:\n"
3255 "-N tags           specify the number of tags to use for this device\n"
3256 "-q                be quiet, don't report the number of tags\n"
3257 "-v                report a number of tag-related parameters\n"
3258 "negotiate arguments:\n"
3259 "-a                send a test unit ready after negotiation\n"
3260 "-c                report/set current negotiation settings\n"
3261 "-D <arg>          \"enable\" or \"disable\" disconnection\n"
3262 "-O offset         set command delay offset\n"
3263 "-q                be quiet, don't report anything\n"
3264 "-R syncrate       synchronization rate in MHz\n"
3265 "-T <arg>          \"enable\" or \"disable\" tagged queueing\n"
3266 "-U                report/set user negotiation settings\n"
3267 "-W bus_width      set the bus width in bits (8, 16 or 32)\n"
3268 "-v                also print a Path Inquiry CCB for the controller\n"
3269 "format arguments:\n"
3270 "-q                be quiet, don't print status messages\n"
3271 "-w                don't send immediate format command\n"
3272 "-y                don't ask any questions\n");
3273 #endif /* MINIMALISTIC */
3274 }
3275 
3276 int
3277 main(int argc, char **argv)
3278 {
3279 	int c;
3280 	char *device = NULL;
3281 	int unit = 0;
3282 	struct cam_device *cam_dev = NULL;
3283 	int timeout = 0, retry_count = 1;
3284 	camcontrol_optret optreturn;
3285 	char *tstr;
3286 	const char *mainopt = "C:En:t:u:v";
3287 	const char *subopt = NULL;
3288 	char combinedopt[256];
3289 	int error = 0, optstart = 2;
3290 	int devopen = 1;
3291 
3292 	cmdlist = CAM_CMD_NONE;
3293 	arglist = CAM_ARG_NONE;
3294 
3295 	if (argc < 2) {
3296 		usage(0);
3297 		exit(1);
3298 	}
3299 
3300 	/*
3301 	 * Get the base option.
3302 	 */
3303 	optreturn = getoption(argv[1], &cmdlist, &arglist, &subopt);
3304 
3305 	if (optreturn == CC_OR_AMBIGUOUS) {
3306 		warnx("ambiguous option %s", argv[1]);
3307 		usage(0);
3308 		exit(1);
3309 	} else if (optreturn == CC_OR_NOT_FOUND) {
3310 		warnx("option %s not found", argv[1]);
3311 		usage(0);
3312 		exit(1);
3313 	}
3314 
3315 	/*
3316 	 * Ahh, getopt(3) is a pain.
3317 	 *
3318 	 * This is a gross hack.  There really aren't many other good
3319 	 * options (excuse the pun) for parsing options in a situation like
3320 	 * this.  getopt is kinda braindead, so you end up having to run
3321 	 * through the options twice, and give each invocation of getopt
3322 	 * the option string for the other invocation.
3323 	 *
3324 	 * You would think that you could just have two groups of options.
3325 	 * The first group would get parsed by the first invocation of
3326 	 * getopt, and the second group would get parsed by the second
3327 	 * invocation of getopt.  It doesn't quite work out that way.  When
3328 	 * the first invocation of getopt finishes, it leaves optind pointing
3329 	 * to the argument _after_ the first argument in the second group.
3330 	 * So when the second invocation of getopt comes around, it doesn't
3331 	 * recognize the first argument it gets and then bails out.
3332 	 *
3333 	 * A nice alternative would be to have a flag for getopt that says
3334 	 * "just keep parsing arguments even when you encounter an unknown
3335 	 * argument", but there isn't one.  So there's no real clean way to
3336 	 * easily parse two sets of arguments without having one invocation
3337 	 * of getopt know about the other.
3338 	 *
3339 	 * Without this hack, the first invocation of getopt would work as
3340 	 * long as the generic arguments are first, but the second invocation
3341 	 * (in the subfunction) would fail in one of two ways.  In the case
3342 	 * where you don't set optreset, it would fail because optind may be
3343 	 * pointing to the argument after the one it should be pointing at.
3344 	 * In the case where you do set optreset, and reset optind, it would
3345 	 * fail because getopt would run into the first set of options, which
3346 	 * it doesn't understand.
3347 	 *
3348 	 * All of this would "sort of" work if you could somehow figure out
3349 	 * whether optind had been incremented one option too far.  The
3350 	 * mechanics of that, however, are more daunting than just giving
3351 	 * both invocations all of the expect options for either invocation.
3352 	 *
3353 	 * Needless to say, I wouldn't mind if someone invented a better
3354 	 * (non-GPL!) command line parsing interface than getopt.  I
3355 	 * wouldn't mind if someone added more knobs to getopt to make it
3356 	 * work better.  Who knows, I may talk myself into doing it someday,
3357 	 * if the standards weenies let me.  As it is, it just leads to
3358 	 * hackery like this and causes people to avoid it in some cases.
3359 	 *
3360 	 * KDM, September 8th, 1998
3361 	 */
3362 	if (subopt != NULL)
3363 		sprintf(combinedopt, "%s%s", mainopt, subopt);
3364 	else
3365 		sprintf(combinedopt, "%s", mainopt);
3366 
3367 	/*
3368 	 * For these options we do not parse optional device arguments and
3369 	 * we do not open a passthrough device.
3370 	 */
3371 	if ((cmdlist == CAM_CMD_RESCAN)
3372 	 || (cmdlist == CAM_CMD_RESET)
3373 	 || (cmdlist == CAM_CMD_DEVTREE)
3374 	 || (cmdlist == CAM_CMD_USAGE)
3375 	 || (cmdlist == CAM_CMD_DEBUG))
3376 		devopen = 0;
3377 
3378 #ifndef MINIMALISTIC
3379 	if ((devopen == 1)
3380 	 && (argc > 2 && argv[2][0] != '-')) {
3381 		char name[30];
3382 		int rv;
3383 
3384 		/*
3385 		 * First catch people who try to do things like:
3386 		 * camcontrol tur /dev/da0
3387 		 * camcontrol doesn't take device nodes as arguments.
3388 		 */
3389 		if (argv[2][0] == '/') {
3390 			warnx("%s is not a valid device identifier", argv[2]);
3391 			errx(1, "please read the camcontrol(8) man page");
3392 		} else if (isdigit(argv[2][0])) {
3393 			/* device specified as bus:target[:lun] */
3394 			rv = parse_btl(argv[2], &bus, &target, &lun, &arglist);
3395 			if (rv < 2)
3396 				errx(1, "numeric device specification must "
3397 				     "be either bus:target, or "
3398 				     "bus:target:lun");
3399 			optstart++;
3400 		} else {
3401 			if (cam_get_device(argv[2], name, sizeof name, &unit)
3402 			    == -1)
3403 				errx(1, "%s", cam_errbuf);
3404 			device = strdup(name);
3405 			arglist |= CAM_ARG_DEVICE | CAM_ARG_UNIT;
3406 			optstart++;
3407 		}
3408 	}
3409 #endif /* MINIMALISTIC */
3410 	/*
3411 	 * Start getopt processing at argv[2/3], since we've already
3412 	 * accepted argv[1..2] as the command name, and as a possible
3413 	 * device name.
3414 	 */
3415 	optind = optstart;
3416 
3417 	/*
3418 	 * Now we run through the argument list looking for generic
3419 	 * options, and ignoring options that possibly belong to
3420 	 * subfunctions.
3421 	 */
3422 	while ((c = getopt(argc, argv, combinedopt))!= -1){
3423 		switch(c) {
3424 			case 'C':
3425 				retry_count = strtol(optarg, NULL, 0);
3426 				if (retry_count < 0)
3427 					errx(1, "retry count %d is < 0",
3428 					     retry_count);
3429 				arglist |= CAM_ARG_RETRIES;
3430 				break;
3431 			case 'E':
3432 				arglist |= CAM_ARG_ERR_RECOVER;
3433 				break;
3434 			case 'n':
3435 				arglist |= CAM_ARG_DEVICE;
3436 				tstr = optarg;
3437 				while (isspace(*tstr) && (*tstr != '\0'))
3438 					tstr++;
3439 				device = (char *)strdup(tstr);
3440 				break;
3441 			case 't':
3442 				timeout = strtol(optarg, NULL, 0);
3443 				if (timeout < 0)
3444 					errx(1, "invalid timeout %d", timeout);
3445 				/* Convert the timeout from seconds to ms */
3446 				timeout *= 1000;
3447 				arglist |= CAM_ARG_TIMEOUT;
3448 				break;
3449 			case 'u':
3450 				arglist |= CAM_ARG_UNIT;
3451 				unit = strtol(optarg, NULL, 0);
3452 				break;
3453 			case 'v':
3454 				arglist |= CAM_ARG_VERBOSE;
3455 				break;
3456 			default:
3457 				break;
3458 		}
3459 	}
3460 
3461 #ifndef MINIMALISTIC
3462 	/*
3463 	 * For most commands we'll want to open the passthrough device
3464 	 * associated with the specified device.  In the case of the rescan
3465 	 * commands, we don't use a passthrough device at all, just the
3466 	 * transport layer device.
3467 	 */
3468 	if (devopen == 1) {
3469 		if (((arglist & (CAM_ARG_BUS|CAM_ARG_TARGET)) == 0)
3470 		 && (((arglist & CAM_ARG_DEVICE) == 0)
3471 		  || ((arglist & CAM_ARG_UNIT) == 0))) {
3472 			errx(1, "subcommand \"%s\" requires a valid device "
3473 			     "identifier", argv[1]);
3474 		}
3475 
3476 		if ((cam_dev = ((arglist & (CAM_ARG_BUS | CAM_ARG_TARGET))?
3477 				cam_open_btl(bus, target, lun, O_RDWR, NULL) :
3478 				cam_open_spec_device(device,unit,O_RDWR,NULL)))
3479 		     == NULL)
3480 			errx(1,"%s", cam_errbuf);
3481 	}
3482 #endif /* MINIMALISTIC */
3483 
3484 	/*
3485 	 * Reset optind to 2, and reset getopt, so these routines can parse
3486 	 * the arguments again.
3487 	 */
3488 	optind = optstart;
3489 	optreset = 1;
3490 
3491 	switch(cmdlist) {
3492 #ifndef MINIMALISTIC
3493 		case CAM_CMD_DEVLIST:
3494 			error = getdevlist(cam_dev);
3495 			break;
3496 #endif /* MINIMALISTIC */
3497 		case CAM_CMD_DEVTREE:
3498 			error = getdevtree();
3499 			break;
3500 #ifndef MINIMALISTIC
3501 		case CAM_CMD_TUR:
3502 			error = testunitready(cam_dev, retry_count, timeout, 0);
3503 			break;
3504 		case CAM_CMD_INQUIRY:
3505 			error = scsidoinquiry(cam_dev, argc, argv, combinedopt,
3506 					      retry_count, timeout);
3507 			break;
3508 		case CAM_CMD_STARTSTOP:
3509 			error = scsistart(cam_dev, arglist & CAM_ARG_START_UNIT,
3510 					  arglist & CAM_ARG_EJECT, retry_count,
3511 					  timeout);
3512 			break;
3513 #endif /* MINIMALISTIC */
3514 		case CAM_CMD_RESCAN:
3515 			error = dorescan_or_reset(argc, argv, 1);
3516 			break;
3517 		case CAM_CMD_RESET:
3518 			error = dorescan_or_reset(argc, argv, 0);
3519 			break;
3520 #ifndef MINIMALISTIC
3521 		case CAM_CMD_READ_DEFECTS:
3522 			error = readdefects(cam_dev, argc, argv, combinedopt,
3523 					    retry_count, timeout);
3524 			break;
3525 		case CAM_CMD_MODE_PAGE:
3526 			modepage(cam_dev, argc, argv, combinedopt,
3527 				 retry_count, timeout);
3528 			break;
3529 		case CAM_CMD_SCSI_CMD:
3530 			error = scsicmd(cam_dev, argc, argv, combinedopt,
3531 					retry_count, timeout);
3532 			break;
3533 		case CAM_CMD_DEBUG:
3534 			error = camdebug(argc, argv, combinedopt);
3535 			break;
3536 		case CAM_CMD_TAG:
3537 			error = tagcontrol(cam_dev, argc, argv, combinedopt);
3538 			break;
3539 		case CAM_CMD_RATE:
3540 			error = ratecontrol(cam_dev, retry_count, timeout,
3541 					    argc, argv, combinedopt);
3542 			break;
3543 		case CAM_CMD_FORMAT:
3544 			error = scsiformat(cam_dev, argc, argv,
3545 					   combinedopt, retry_count, timeout);
3546 			break;
3547 #endif /* MINIMALISTIC */
3548 		case CAM_CMD_USAGE:
3549 			usage(1);
3550 			break;
3551 		default:
3552 			usage(0);
3553 			error = 1;
3554 			break;
3555 	}
3556 
3557 	if (cam_dev != NULL)
3558 		cam_close_device(cam_dev);
3559 
3560 	exit(error);
3561 }
3562