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