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