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