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