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