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