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