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