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