]> CyberLeo.Net >> Repos - FreeBSD/stable/8.git/blob - sbin/camcontrol/camcontrol.c
MFC r197419:
[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_GEN2)
1023                         printf(" SATA 2.x\n");
1024                 else if (parm->satacapabilities & ATA_SATA_GEN1)
1025                         printf(" SATA 1.x\n");
1026                 else
1027                         printf(" SATA x.x\n");
1028         }
1029         else
1030                 printf("\n");
1031         printf("device model          %.40s\n", parm->model);
1032         printf("serial number         %.20s\n", parm->serial);
1033         printf("firmware revision     %.8s\n", parm->revision);
1034
1035         printf("cylinders             %d\n", parm->cylinders);
1036         printf("heads                 %d\n", parm->heads);
1037         printf("sectors/track         %d\n", parm->sectors);
1038
1039         if (parm->config == ATA_PROTO_CFA ||
1040             (parm->support.command2 & ATA_SUPPORT_CFA))
1041                 printf("CFA supported\n");
1042
1043         printf("LBA%ssupported         ",
1044                 parm->capabilities1 & ATA_SUPPORT_LBA ? " " : " not ");
1045         if (lbasize)
1046                 printf("%d sectors\n", lbasize);
1047         else
1048                 printf("\n");
1049
1050         printf("LBA48%ssupported       ",
1051                 parm->support.command2 & ATA_SUPPORT_ADDRESS48 ? " " : " not ");
1052         if (lbasize48)
1053                 printf("%ju sectors\n", (uintmax_t)lbasize48);
1054         else
1055                 printf("\n");
1056
1057         printf("PIO supported         PIO");
1058         switch (ata_max_pmode(parm)) {
1059         case ATA_PIO4:
1060                 printf("4");
1061                 break;
1062         case ATA_PIO3:
1063                 printf("3");
1064                 break;
1065         case ATA_PIO2:
1066                 printf("2");
1067                 break;
1068         case ATA_PIO1:
1069                 printf("1");
1070                 break;
1071         default:
1072                 printf("0");
1073         }
1074         printf("\n");
1075
1076         printf("DMA%ssupported         ",
1077                 parm->capabilities1 & ATA_SUPPORT_DMA ? " " : " not ");
1078         if (parm->capabilities1 & ATA_SUPPORT_DMA) {
1079                 if (parm->mwdmamodes & 0xff) {
1080                         printf("WDMA");
1081                         if (parm->mwdmamodes & 0x04)
1082                                 printf("2");
1083                         else if (parm->mwdmamodes & 0x02)
1084                                 printf("1");
1085                         else if (parm->mwdmamodes & 0x01)
1086                                 printf("0");
1087                         printf(" ");
1088                 }
1089                 if ((parm->atavalid & ATA_FLAG_88) &&
1090                     (parm->udmamodes & 0xff)) {
1091                         printf("UDMA");
1092                         if (parm->udmamodes & 0x40)
1093                                 printf("6");
1094                         else if (parm->udmamodes & 0x20)
1095                                 printf("5");
1096                         else if (parm->udmamodes & 0x10)
1097                                 printf("4");
1098                         else if (parm->udmamodes & 0x08)
1099                                 printf("3");
1100                         else if (parm->udmamodes & 0x04)
1101                                 printf("2");
1102                         else if (parm->udmamodes & 0x02)
1103                                 printf("1");
1104                         else if (parm->udmamodes & 0x01)
1105                                 printf("0");
1106                         printf(" ");
1107                 }
1108         }
1109         printf("\n");
1110
1111         printf("overlap%ssupported\n",
1112                 parm->capabilities1 & ATA_SUPPORT_OVERLAP ? " " : " not ");
1113
1114         printf("\nFeature                      "
1115                 "Support  Enable    Value           Vendor\n");
1116
1117         printf("write cache                    %s       %s\n",
1118                 parm->support.command1 & ATA_SUPPORT_WRITECACHE ? "yes" : "no",
1119                 parm->enabled.command1 & ATA_SUPPORT_WRITECACHE ? "yes" : "no");
1120
1121         printf("read ahead                     %s       %s\n",
1122                 parm->support.command1 & ATA_SUPPORT_LOOKAHEAD ? "yes" : "no",
1123                 parm->enabled.command1 & ATA_SUPPORT_LOOKAHEAD ? "yes" : "no");
1124
1125         if (parm->satacapabilities && parm->satacapabilities != 0xffff) {
1126                 printf("Native Command Queuing (NCQ)   %s       "
1127                         "       %d/0x%02X\n",
1128                         parm->satacapabilities & ATA_SUPPORT_NCQ ?
1129                                 "yes" : "no",
1130                         (parm->satacapabilities & ATA_SUPPORT_NCQ) ?
1131                                 ATA_QUEUE_LEN(parm->queue) : 0,
1132                         (parm->satacapabilities & ATA_SUPPORT_NCQ) ?
1133                                 ATA_QUEUE_LEN(parm->queue) : 0);
1134         }
1135         printf("Tagged Command Queuing (TCQ)   %s       %s      %d/0x%02X\n",
1136                 parm->support.command2 & ATA_SUPPORT_QUEUED ? "yes" : "no",
1137                 parm->enabled.command2 & ATA_SUPPORT_QUEUED ? "yes" : "no",
1138                 ATA_QUEUE_LEN(parm->queue), ATA_QUEUE_LEN(parm->queue));
1139
1140         printf("SMART                          %s       %s\n",
1141                 parm->support.command1 & ATA_SUPPORT_SMART ? "yes" : "no",
1142                 parm->enabled.command1 & ATA_SUPPORT_SMART ? "yes" : "no");
1143
1144         printf("microcode download             %s       %s\n",
1145                 parm->support.command2 & ATA_SUPPORT_MICROCODE ? "yes" : "no",
1146                 parm->enabled.command2 & ATA_SUPPORT_MICROCODE ? "yes" : "no");
1147
1148         printf("security                       %s       %s\n",
1149                 parm->support.command1 & ATA_SUPPORT_SECURITY ? "yes" : "no",
1150                 parm->enabled.command1 & ATA_SUPPORT_SECURITY ? "yes" : "no");
1151
1152         printf("power management               %s       %s\n",
1153                 parm->support.command1 & ATA_SUPPORT_POWERMGT ? "yes" : "no",
1154                 parm->enabled.command1 & ATA_SUPPORT_POWERMGT ? "yes" : "no");
1155
1156         printf("advanced power management      %s       %s      %d/0x%02X\n",
1157                 parm->support.command2 & ATA_SUPPORT_APM ? "yes" : "no",
1158                 parm->enabled.command2 & ATA_SUPPORT_APM ? "yes" : "no",
1159                 parm->apm_value, parm->apm_value);
1160
1161         printf("automatic acoustic management  %s       %s      "
1162                 "%d/0x%02X      %d/0x%02X\n",
1163                 parm->support.command2 & ATA_SUPPORT_AUTOACOUSTIC ? "yes" :"no",
1164                 parm->enabled.command2 & ATA_SUPPORT_AUTOACOUSTIC ? "yes" :"no",
1165                 ATA_ACOUSTIC_CURRENT(parm->acoustic),
1166                 ATA_ACOUSTIC_CURRENT(parm->acoustic),
1167                 ATA_ACOUSTIC_VENDOR(parm->acoustic),
1168                 ATA_ACOUSTIC_VENDOR(parm->acoustic));
1169 }
1170
1171
1172 static int
1173 ataidentify(struct cam_device *device, int retry_count, int timeout)
1174 {
1175         union ccb *ccb;
1176         struct ata_params *ident_buf;
1177         struct ccb_getdev cgd;
1178         u_int i, error = 0;
1179         int16_t *ptr;
1180
1181         if (get_cgd(device, &cgd) != 0) {
1182                 warnx("couldn't get CGD");
1183                 return(1);
1184         }
1185         ccb = cam_getccb(device);
1186
1187         if (ccb == NULL) {
1188                 warnx("couldn't allocate CCB");
1189                 return(1);
1190         }
1191
1192         /* cam_getccb cleans up the header, caller has to zero the payload */
1193         bzero(&(&ccb->ccb_h)[1],
1194               sizeof(struct ccb_ataio) - sizeof(struct ccb_hdr));
1195
1196         ptr = (uint16_t *)malloc(sizeof(struct ata_params));
1197
1198         if (ptr == NULL) {
1199                 cam_freeccb(ccb);
1200                 warnx("can't malloc memory for identify\n");
1201                 return(1);
1202         }
1203         bzero(ptr, sizeof(struct ata_params));
1204
1205         cam_fill_ataio(&ccb->ataio,
1206                       retry_count,
1207                       NULL,
1208                       /*flags*/CAM_DIR_IN,
1209                       MSG_SIMPLE_Q_TAG,
1210                       /*data_ptr*/(u_int8_t *)ptr,
1211                       /*dxfer_len*/sizeof(struct ata_params),
1212                       timeout ? timeout : 30 * 1000);
1213         if (cgd.protocol == PROTO_ATA)
1214                 ata_28bit_cmd(&ccb->ataio, ATA_ATA_IDENTIFY, 0, 0, 0);
1215         else
1216                 ata_28bit_cmd(&ccb->ataio, ATA_ATAPI_IDENTIFY, 0, 0, 0);
1217
1218         /* Disable freezing the device queue */
1219         ccb->ccb_h.flags |= CAM_DEV_QFRZDIS;
1220
1221         if (arglist & CAM_ARG_ERR_RECOVER)
1222                 ccb->ccb_h.flags |= CAM_PASS_ERR_RECOVER;
1223
1224         if (cam_send_ccb(device, ccb) < 0) {
1225                 perror("error sending ATA identify");
1226
1227                 if (arglist & CAM_ARG_VERBOSE) {
1228                         cam_error_print(device, ccb, CAM_ESF_ALL,
1229                                         CAM_EPF_ALL, stderr);
1230                 }
1231
1232                 free(ptr);
1233                 cam_freeccb(ccb);
1234                 return(1);
1235         }
1236
1237         if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1238                 error = 1;
1239
1240                 if (arglist & CAM_ARG_VERBOSE) {
1241                         cam_error_print(device, ccb, CAM_ESF_ALL,
1242                                         CAM_EPF_ALL, stderr);
1243                 }
1244         }
1245
1246         cam_freeccb(ccb);
1247
1248         if (error != 0) {
1249                 free(ptr);
1250                 return(error);
1251         }
1252
1253         for (i = 0; i < sizeof(struct ata_params) / 2; i++)
1254                 ptr[i] = le16toh(ptr[i]);
1255         ident_buf = (struct ata_params *)ptr;
1256
1257         if (strncmp(ident_buf->model, "FX", 2) &&
1258             strncmp(ident_buf->model, "NEC", 3) &&
1259             strncmp(ident_buf->model, "Pioneer", 7) &&
1260             strncmp(ident_buf->model, "SHARP", 5)) {
1261                 ata_bswap(ident_buf->model, sizeof(ident_buf->model));
1262                 ata_bswap(ident_buf->revision, sizeof(ident_buf->revision));
1263                 ata_bswap(ident_buf->serial, sizeof(ident_buf->serial));
1264         }
1265         ata_btrim(ident_buf->model, sizeof(ident_buf->model));
1266         ata_bpack(ident_buf->model, ident_buf->model, sizeof(ident_buf->model));
1267         ata_btrim(ident_buf->revision, sizeof(ident_buf->revision));
1268         ata_bpack(ident_buf->revision, ident_buf->revision, sizeof(ident_buf->revision));
1269         ata_btrim(ident_buf->serial, sizeof(ident_buf->serial));
1270         ata_bpack(ident_buf->serial, ident_buf->serial, sizeof(ident_buf->serial));
1271
1272         fprintf(stdout, "%s%d: ", device->device_name,
1273                 device->dev_unit_num);
1274         ata_print_ident(ident_buf);
1275         atacapprint(ident_buf);
1276
1277         free(ident_buf);
1278
1279         return(0);
1280 }
1281 #endif /* MINIMALISTIC */
1282
1283 /*
1284  * Parse out a bus, or a bus, target and lun in the following
1285  * format:
1286  * bus
1287  * bus:target
1288  * bus:target:lun
1289  *
1290  * Returns the number of parsed components, or 0.
1291  */
1292 static int
1293 parse_btl(char *tstr, int *bus, int *target, int *lun, cam_argmask *arglst)
1294 {
1295         char *tmpstr;
1296         int convs = 0;
1297
1298         while (isspace(*tstr) && (*tstr != '\0'))
1299                 tstr++;
1300
1301         tmpstr = (char *)strtok(tstr, ":");
1302         if ((tmpstr != NULL) && (*tmpstr != '\0')) {
1303                 *bus = strtol(tmpstr, NULL, 0);
1304                 *arglst |= CAM_ARG_BUS;
1305                 convs++;
1306                 tmpstr = (char *)strtok(NULL, ":");
1307                 if ((tmpstr != NULL) && (*tmpstr != '\0')) {
1308                         *target = strtol(tmpstr, NULL, 0);
1309                         *arglst |= CAM_ARG_TARGET;
1310                         convs++;
1311                         tmpstr = (char *)strtok(NULL, ":");
1312                         if ((tmpstr != NULL) && (*tmpstr != '\0')) {
1313                                 *lun = strtol(tmpstr, NULL, 0);
1314                                 *arglst |= CAM_ARG_LUN;
1315                                 convs++;
1316                         }
1317                 }
1318         }
1319
1320         return convs;
1321 }
1322
1323 static int
1324 dorescan_or_reset(int argc, char **argv, int rescan)
1325 {
1326         static const char must[] =
1327                 "you must specify \"all\", a bus, or a bus:target:lun to %s";
1328         int rv, error = 0;
1329         int bus = -1, target = -1, lun = -1;
1330         char *tstr;
1331
1332         if (argc < 3) {
1333                 warnx(must, rescan? "rescan" : "reset");
1334                 return(1);
1335         }
1336
1337         tstr = argv[optind];
1338         while (isspace(*tstr) && (*tstr != '\0'))
1339                 tstr++;
1340         if (strncasecmp(tstr, "all", strlen("all")) == 0)
1341                 arglist |= CAM_ARG_BUS;
1342         else {
1343                 rv = parse_btl(argv[optind], &bus, &target, &lun, &arglist);
1344                 if (rv != 1 && rv != 3) {
1345                         warnx(must, rescan? "rescan" : "reset");
1346                         return(1);
1347                 }
1348         }
1349
1350         if ((arglist & CAM_ARG_BUS)
1351             && (arglist & CAM_ARG_TARGET)
1352             && (arglist & CAM_ARG_LUN))
1353                 error = scanlun_or_reset_dev(bus, target, lun, rescan);
1354         else
1355                 error = rescan_or_reset_bus(bus, rescan);
1356
1357         return(error);
1358 }
1359
1360 static int
1361 rescan_or_reset_bus(int bus, int rescan)
1362 {
1363         union ccb ccb, matchccb;
1364         int fd, retval;
1365         int bufsize;
1366
1367         retval = 0;
1368
1369         if ((fd = open(XPT_DEVICE, O_RDWR)) < 0) {
1370                 warnx("error opening transport layer device %s", XPT_DEVICE);
1371                 warn("%s", XPT_DEVICE);
1372                 return(1);
1373         }
1374
1375         if (bus != -1) {
1376                 ccb.ccb_h.func_code = rescan ? XPT_SCAN_BUS : XPT_RESET_BUS;
1377                 ccb.ccb_h.path_id = bus;
1378                 ccb.ccb_h.target_id = CAM_TARGET_WILDCARD;
1379                 ccb.ccb_h.target_lun = CAM_LUN_WILDCARD;
1380                 ccb.crcn.flags = CAM_FLAG_NONE;
1381
1382                 /* run this at a low priority */
1383                 ccb.ccb_h.pinfo.priority = 5;
1384
1385                 if (ioctl(fd, CAMIOCOMMAND, &ccb) == -1) {
1386                         warn("CAMIOCOMMAND ioctl failed");
1387                         close(fd);
1388                         return(1);
1389                 }
1390
1391                 if ((ccb.ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP) {
1392                         fprintf(stdout, "%s of bus %d was successful\n",
1393                             rescan ? "Re-scan" : "Reset", bus);
1394                 } else {
1395                         fprintf(stdout, "%s of bus %d returned error %#x\n",
1396                                 rescan ? "Re-scan" : "Reset", bus,
1397                                 ccb.ccb_h.status & CAM_STATUS_MASK);
1398                         retval = 1;
1399                 }
1400
1401                 close(fd);
1402                 return(retval);
1403
1404         }
1405
1406
1407         /*
1408          * The right way to handle this is to modify the xpt so that it can
1409          * handle a wildcarded bus in a rescan or reset CCB.  At the moment
1410          * that isn't implemented, so instead we enumerate the busses and
1411          * send the rescan or reset to those busses in the case where the
1412          * given bus is -1 (wildcard).  We don't send a rescan or reset
1413          * to the xpt bus; sending a rescan to the xpt bus is effectively a
1414          * no-op, sending a rescan to the xpt bus would result in a status of
1415          * CAM_REQ_INVALID.
1416          */
1417         bzero(&(&matchccb.ccb_h)[1],
1418               sizeof(struct ccb_dev_match) - sizeof(struct ccb_hdr));
1419         matchccb.ccb_h.func_code = XPT_DEV_MATCH;
1420         bufsize = sizeof(struct dev_match_result) * 20;
1421         matchccb.cdm.match_buf_len = bufsize;
1422         matchccb.cdm.matches=(struct dev_match_result *)malloc(bufsize);
1423         if (matchccb.cdm.matches == NULL) {
1424                 warnx("can't malloc memory for matches");
1425                 retval = 1;
1426                 goto bailout;
1427         }
1428         matchccb.cdm.num_matches = 0;
1429
1430         matchccb.cdm.num_patterns = 1;
1431         matchccb.cdm.pattern_buf_len = sizeof(struct dev_match_pattern);
1432
1433         matchccb.cdm.patterns = (struct dev_match_pattern *)malloc(
1434                 matchccb.cdm.pattern_buf_len);
1435         if (matchccb.cdm.patterns == NULL) {
1436                 warnx("can't malloc memory for patterns");
1437                 retval = 1;
1438                 goto bailout;
1439         }
1440         matchccb.cdm.patterns[0].type = DEV_MATCH_BUS;
1441         matchccb.cdm.patterns[0].pattern.bus_pattern.flags = BUS_MATCH_ANY;
1442
1443         do {
1444                 unsigned int i;
1445
1446                 if (ioctl(fd, CAMIOCOMMAND, &matchccb) == -1) {
1447                         warn("CAMIOCOMMAND ioctl failed");
1448                         retval = 1;
1449                         goto bailout;
1450                 }
1451
1452                 if ((matchccb.ccb_h.status != CAM_REQ_CMP)
1453                  || ((matchccb.cdm.status != CAM_DEV_MATCH_LAST)
1454                    && (matchccb.cdm.status != CAM_DEV_MATCH_MORE))) {
1455                         warnx("got CAM error %#x, CDM error %d\n",
1456                               matchccb.ccb_h.status, matchccb.cdm.status);
1457                         retval = 1;
1458                         goto bailout;
1459                 }
1460
1461                 for (i = 0; i < matchccb.cdm.num_matches; i++) {
1462                         struct bus_match_result *bus_result;
1463
1464                         /* This shouldn't happen. */
1465                         if (matchccb.cdm.matches[i].type != DEV_MATCH_BUS)
1466                                 continue;
1467
1468                         bus_result = &matchccb.cdm.matches[i].result.bus_result;
1469
1470                         /*
1471                          * We don't want to rescan or reset the xpt bus.
1472                          * See above.
1473                          */
1474                         if ((int)bus_result->path_id == -1)
1475                                 continue;
1476
1477                         ccb.ccb_h.func_code = rescan ? XPT_SCAN_BUS :
1478                                                        XPT_RESET_BUS;
1479                         ccb.ccb_h.path_id = bus_result->path_id;
1480                         ccb.ccb_h.target_id = CAM_TARGET_WILDCARD;
1481                         ccb.ccb_h.target_lun = CAM_LUN_WILDCARD;
1482                         ccb.crcn.flags = CAM_FLAG_NONE;
1483
1484                         /* run this at a low priority */
1485                         ccb.ccb_h.pinfo.priority = 5;
1486
1487                         if (ioctl(fd, CAMIOCOMMAND, &ccb) == -1) {
1488                                 warn("CAMIOCOMMAND ioctl failed");
1489                                 retval = 1;
1490                                 goto bailout;
1491                         }
1492
1493                         if ((ccb.ccb_h.status & CAM_STATUS_MASK) ==CAM_REQ_CMP){
1494                                 fprintf(stdout, "%s of bus %d was successful\n",
1495                                         rescan? "Re-scan" : "Reset",
1496                                         bus_result->path_id);
1497                         } else {
1498                                 /*
1499                                  * Don't bail out just yet, maybe the other
1500                                  * rescan or reset commands will complete
1501                                  * successfully.
1502                                  */
1503                                 fprintf(stderr, "%s of bus %d returned error "
1504                                         "%#x\n", rescan? "Re-scan" : "Reset",
1505                                         bus_result->path_id,
1506                                         ccb.ccb_h.status & CAM_STATUS_MASK);
1507                                 retval = 1;
1508                         }
1509                 }
1510         } while ((matchccb.ccb_h.status == CAM_REQ_CMP)
1511                  && (matchccb.cdm.status == CAM_DEV_MATCH_MORE));
1512
1513 bailout:
1514
1515         if (fd != -1)
1516                 close(fd);
1517
1518         if (matchccb.cdm.patterns != NULL)
1519                 free(matchccb.cdm.patterns);
1520         if (matchccb.cdm.matches != NULL)
1521                 free(matchccb.cdm.matches);
1522
1523         return(retval);
1524 }
1525
1526 static int
1527 scanlun_or_reset_dev(int bus, int target, int lun, int scan)
1528 {
1529         union ccb ccb;
1530         struct cam_device *device;
1531         int fd;
1532
1533         device = NULL;
1534
1535         if (bus < 0) {
1536                 warnx("invalid bus number %d", bus);
1537                 return(1);
1538         }
1539
1540         if (target < 0) {
1541                 warnx("invalid target number %d", target);
1542                 return(1);
1543         }
1544
1545         if (lun < 0) {
1546                 warnx("invalid lun number %d", lun);
1547                 return(1);
1548         }
1549
1550         fd = -1;
1551
1552         bzero(&ccb, sizeof(union ccb));
1553
1554         if (scan) {
1555                 if ((fd = open(XPT_DEVICE, O_RDWR)) < 0) {
1556                         warnx("error opening transport layer device %s\n",
1557                             XPT_DEVICE);
1558                         warn("%s", XPT_DEVICE);
1559                         return(1);
1560                 }
1561         } else {
1562                 device = cam_open_btl(bus, target, lun, O_RDWR, NULL);
1563                 if (device == NULL) {
1564                         warnx("%s", cam_errbuf);
1565                         return(1);
1566                 }
1567         }
1568
1569         ccb.ccb_h.func_code = (scan)? XPT_SCAN_LUN : XPT_RESET_DEV;
1570         ccb.ccb_h.path_id = bus;
1571         ccb.ccb_h.target_id = target;
1572         ccb.ccb_h.target_lun = lun;
1573         ccb.ccb_h.timeout = 5000;
1574         ccb.crcn.flags = CAM_FLAG_NONE;
1575
1576         /* run this at a low priority */
1577         ccb.ccb_h.pinfo.priority = 5;
1578
1579         if (scan) {
1580                 if (ioctl(fd, CAMIOCOMMAND, &ccb) < 0) {
1581                         warn("CAMIOCOMMAND ioctl failed");
1582                         close(fd);
1583                         return(1);
1584                 }
1585         } else {
1586                 if (cam_send_ccb(device, &ccb) < 0) {
1587                         warn("error sending XPT_RESET_DEV CCB");
1588                         cam_close_device(device);
1589                         return(1);
1590                 }
1591         }
1592
1593         if (scan)
1594                 close(fd);
1595         else
1596                 cam_close_device(device);
1597
1598         /*
1599          * An error code of CAM_BDR_SENT is normal for a BDR request.
1600          */
1601         if (((ccb.ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP)
1602          || ((!scan)
1603           && ((ccb.ccb_h.status & CAM_STATUS_MASK) == CAM_BDR_SENT))) {
1604                 fprintf(stdout, "%s of %d:%d:%d was successful\n",
1605                     scan? "Re-scan" : "Reset", bus, target, lun);
1606                 return(0);
1607         } else {
1608                 fprintf(stdout, "%s of %d:%d:%d returned error %#x\n",
1609                     scan? "Re-scan" : "Reset", bus, target, lun,
1610                     ccb.ccb_h.status & CAM_STATUS_MASK);
1611                 return(1);
1612         }
1613 }
1614
1615 #ifndef MINIMALISTIC
1616 static int
1617 readdefects(struct cam_device *device, int argc, char **argv,
1618             char *combinedopt, int retry_count, int timeout)
1619 {
1620         union ccb *ccb = NULL;
1621         struct scsi_read_defect_data_10 *rdd_cdb;
1622         u_int8_t *defect_list = NULL;
1623         u_int32_t dlist_length = 65000;
1624         u_int32_t returned_length = 0;
1625         u_int32_t num_returned = 0;
1626         u_int8_t returned_format;
1627         unsigned int i;
1628         int c, error = 0;
1629         int lists_specified = 0;
1630
1631         while ((c = getopt(argc, argv, combinedopt)) != -1) {
1632                 switch(c){
1633                 case 'f':
1634                 {
1635                         char *tstr;
1636                         tstr = optarg;
1637                         while (isspace(*tstr) && (*tstr != '\0'))
1638                                 tstr++;
1639                         if (strcmp(tstr, "block") == 0)
1640                                 arglist |= CAM_ARG_FORMAT_BLOCK;
1641                         else if (strcmp(tstr, "bfi") == 0)
1642                                 arglist |= CAM_ARG_FORMAT_BFI;
1643                         else if (strcmp(tstr, "phys") == 0)
1644                                 arglist |= CAM_ARG_FORMAT_PHYS;
1645                         else {
1646                                 error = 1;
1647                                 warnx("invalid defect format %s", tstr);
1648                                 goto defect_bailout;
1649                         }
1650                         break;
1651                 }
1652                 case 'G':
1653                         arglist |= CAM_ARG_GLIST;
1654                         break;
1655                 case 'P':
1656                         arglist |= CAM_ARG_PLIST;
1657                         break;
1658                 default:
1659                         break;
1660                 }
1661         }
1662
1663         ccb = cam_getccb(device);
1664
1665         /*
1666          * Hopefully 65000 bytes is enough to hold the defect list.  If it
1667          * isn't, the disk is probably dead already.  We'd have to go with
1668          * 12 byte command (i.e. alloc_length is 32 bits instead of 16)
1669          * to hold them all.
1670          */
1671         defect_list = malloc(dlist_length);
1672         if (defect_list == NULL) {
1673                 warnx("can't malloc memory for defect list");
1674                 error = 1;
1675                 goto defect_bailout;
1676         }
1677
1678         rdd_cdb =(struct scsi_read_defect_data_10 *)&ccb->csio.cdb_io.cdb_bytes;
1679
1680         /*
1681          * cam_getccb() zeros the CCB header only.  So we need to zero the
1682          * payload portion of the ccb.
1683          */
1684         bzero(&(&ccb->ccb_h)[1],
1685               sizeof(struct ccb_scsiio) - sizeof(struct ccb_hdr));
1686
1687         cam_fill_csio(&ccb->csio,
1688                       /*retries*/ retry_count,
1689                       /*cbfcnp*/ NULL,
1690                       /*flags*/ CAM_DIR_IN | ((arglist & CAM_ARG_ERR_RECOVER) ?
1691                                               CAM_PASS_ERR_RECOVER : 0),
1692                       /*tag_action*/ MSG_SIMPLE_Q_TAG,
1693                       /*data_ptr*/ defect_list,
1694                       /*dxfer_len*/ dlist_length,
1695                       /*sense_len*/ SSD_FULL_SIZE,
1696                       /*cdb_len*/ sizeof(struct scsi_read_defect_data_10),
1697                       /*timeout*/ timeout ? timeout : 5000);
1698
1699         rdd_cdb->opcode = READ_DEFECT_DATA_10;
1700         if (arglist & CAM_ARG_FORMAT_BLOCK)
1701                 rdd_cdb->format = SRDD10_BLOCK_FORMAT;
1702         else if (arglist & CAM_ARG_FORMAT_BFI)
1703                 rdd_cdb->format = SRDD10_BYTES_FROM_INDEX_FORMAT;
1704         else if (arglist & CAM_ARG_FORMAT_PHYS)
1705                 rdd_cdb->format = SRDD10_PHYSICAL_SECTOR_FORMAT;
1706         else {
1707                 error = 1;
1708                 warnx("no defect list format specified");
1709                 goto defect_bailout;
1710         }
1711         if (arglist & CAM_ARG_PLIST) {
1712                 rdd_cdb->format |= SRDD10_PLIST;
1713                 lists_specified++;
1714         }
1715
1716         if (arglist & CAM_ARG_GLIST) {
1717                 rdd_cdb->format |= SRDD10_GLIST;
1718                 lists_specified++;
1719         }
1720
1721         scsi_ulto2b(dlist_length, rdd_cdb->alloc_length);
1722
1723         /* Disable freezing the device queue */
1724         ccb->ccb_h.flags |= CAM_DEV_QFRZDIS;
1725
1726         if (cam_send_ccb(device, ccb) < 0) {
1727                 perror("error reading defect list");
1728
1729                 if (arglist & CAM_ARG_VERBOSE) {
1730                         cam_error_print(device, ccb, CAM_ESF_ALL,
1731                                         CAM_EPF_ALL, stderr);
1732                 }
1733
1734                 error = 1;
1735                 goto defect_bailout;
1736         }
1737
1738         returned_length = scsi_2btoul(((struct
1739                 scsi_read_defect_data_hdr_10 *)defect_list)->length);
1740
1741         returned_format = ((struct scsi_read_defect_data_hdr_10 *)
1742                         defect_list)->format;
1743
1744         if (((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_SCSI_STATUS_ERROR)
1745          && (ccb->csio.scsi_status == SCSI_STATUS_CHECK_COND)
1746          && ((ccb->ccb_h.status & CAM_AUTOSNS_VALID) != 0)) {
1747                 struct scsi_sense_data *sense;
1748                 int error_code, sense_key, asc, ascq;
1749
1750                 sense = &ccb->csio.sense_data;
1751                 scsi_extract_sense(sense, &error_code, &sense_key, &asc, &ascq);
1752
1753                 /*
1754                  * According to the SCSI spec, if the disk doesn't support
1755                  * the requested format, it will generally return a sense
1756                  * key of RECOVERED ERROR, and an additional sense code
1757                  * of "DEFECT LIST NOT FOUND".  So, we check for that, and
1758                  * also check to make sure that the returned length is
1759                  * greater than 0, and then print out whatever format the
1760                  * disk gave us.
1761                  */
1762                 if ((sense_key == SSD_KEY_RECOVERED_ERROR)
1763                  && (asc == 0x1c) && (ascq == 0x00)
1764                  && (returned_length > 0)) {
1765                         warnx("requested defect format not available");
1766                         switch(returned_format & SRDDH10_DLIST_FORMAT_MASK) {
1767                         case SRDD10_BLOCK_FORMAT:
1768                                 warnx("Device returned block format");
1769                                 break;
1770                         case SRDD10_BYTES_FROM_INDEX_FORMAT:
1771                                 warnx("Device returned bytes from index"
1772                                       " format");
1773                                 break;
1774                         case SRDD10_PHYSICAL_SECTOR_FORMAT:
1775                                 warnx("Device returned physical sector format");
1776                                 break;
1777                         default:
1778                                 error = 1;
1779                                 warnx("Device returned unknown defect"
1780                                      " data format %#x", returned_format);
1781                                 goto defect_bailout;
1782                                 break; /* NOTREACHED */
1783                         }
1784                 } else {
1785                         error = 1;
1786                         warnx("Error returned from read defect data command");
1787                         if (arglist & CAM_ARG_VERBOSE)
1788                                 cam_error_print(device, ccb, CAM_ESF_ALL,
1789                                                 CAM_EPF_ALL, stderr);
1790                         goto defect_bailout;
1791                 }
1792         } else if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
1793                 error = 1;
1794                 warnx("Error returned from read defect data command");
1795                 if (arglist & CAM_ARG_VERBOSE)
1796                         cam_error_print(device, ccb, CAM_ESF_ALL,
1797                                         CAM_EPF_ALL, stderr);
1798                 goto defect_bailout;
1799         }
1800
1801         /*
1802          * XXX KDM  I should probably clean up the printout format for the
1803          * disk defects. 
1804          */
1805         switch (returned_format & SRDDH10_DLIST_FORMAT_MASK){
1806                 case SRDDH10_PHYSICAL_SECTOR_FORMAT:
1807                 {
1808                         struct scsi_defect_desc_phys_sector *dlist;
1809
1810                         dlist = (struct scsi_defect_desc_phys_sector *)
1811                                 (defect_list +
1812                                 sizeof(struct scsi_read_defect_data_hdr_10));
1813
1814                         num_returned = returned_length /
1815                                 sizeof(struct scsi_defect_desc_phys_sector);
1816
1817                         fprintf(stderr, "Got %d defect", num_returned);
1818
1819                         if ((lists_specified == 0) || (num_returned == 0)) {
1820                                 fprintf(stderr, "s.\n");
1821                                 break;
1822                         } else if (num_returned == 1)
1823                                 fprintf(stderr, ":\n");
1824                         else
1825                                 fprintf(stderr, "s:\n");
1826
1827                         for (i = 0; i < num_returned; i++) {
1828                                 fprintf(stdout, "%d:%d:%d\n",
1829                                         scsi_3btoul(dlist[i].cylinder),
1830                                         dlist[i].head,
1831                                         scsi_4btoul(dlist[i].sector));
1832                         }
1833                         break;
1834                 }
1835                 case SRDDH10_BYTES_FROM_INDEX_FORMAT:
1836                 {
1837                         struct scsi_defect_desc_bytes_from_index *dlist;
1838
1839                         dlist = (struct scsi_defect_desc_bytes_from_index *)
1840                                 (defect_list +
1841                                 sizeof(struct scsi_read_defect_data_hdr_10));
1842
1843                         num_returned = returned_length /
1844                               sizeof(struct scsi_defect_desc_bytes_from_index);
1845
1846                         fprintf(stderr, "Got %d defect", num_returned);
1847
1848                         if ((lists_specified == 0) || (num_returned == 0)) {
1849                                 fprintf(stderr, "s.\n");
1850                                 break;
1851                         } else if (num_returned == 1)
1852                                 fprintf(stderr, ":\n");
1853                         else
1854                                 fprintf(stderr, "s:\n");
1855
1856                         for (i = 0; i < num_returned; i++) {
1857                                 fprintf(stdout, "%d:%d:%d\n",
1858                                         scsi_3btoul(dlist[i].cylinder),
1859                                         dlist[i].head,
1860                                         scsi_4btoul(dlist[i].bytes_from_index));
1861                         }
1862                         break;
1863                 }
1864                 case SRDDH10_BLOCK_FORMAT:
1865                 {
1866                         struct scsi_defect_desc_block *dlist;
1867
1868                         dlist = (struct scsi_defect_desc_block *)(defect_list +
1869                                 sizeof(struct scsi_read_defect_data_hdr_10));
1870
1871                         num_returned = returned_length /
1872                               sizeof(struct scsi_defect_desc_block);
1873
1874                         fprintf(stderr, "Got %d defect", num_returned);
1875
1876                         if ((lists_specified == 0) || (num_returned == 0)) {
1877                                 fprintf(stderr, "s.\n");
1878                                 break;
1879                         } else if (num_returned == 1)
1880                                 fprintf(stderr, ":\n");
1881                         else
1882                                 fprintf(stderr, "s:\n");
1883
1884                         for (i = 0; i < num_returned; i++)
1885                                 fprintf(stdout, "%u\n",
1886                                         scsi_4btoul(dlist[i].address));
1887                         break;
1888                 }
1889                 default:
1890                         fprintf(stderr, "Unknown defect format %d\n",
1891                                 returned_format & SRDDH10_DLIST_FORMAT_MASK);
1892                         error = 1;
1893                         break;
1894         }
1895 defect_bailout:
1896
1897         if (defect_list != NULL)
1898                 free(defect_list);
1899
1900         if (ccb != NULL)
1901                 cam_freeccb(ccb);
1902
1903         return(error);
1904 }
1905 #endif /* MINIMALISTIC */
1906
1907 #if 0
1908 void
1909 reassignblocks(struct cam_device *device, u_int32_t *blocks, int num_blocks)
1910 {
1911         union ccb *ccb;
1912         
1913         ccb = cam_getccb(device);
1914
1915         cam_freeccb(ccb);
1916 }
1917 #endif
1918
1919 #ifndef MINIMALISTIC
1920 void
1921 mode_sense(struct cam_device *device, int mode_page, int page_control,
1922            int dbd, int retry_count, int timeout, u_int8_t *data, int datalen)
1923 {
1924         union ccb *ccb;
1925         int retval;
1926
1927         ccb = cam_getccb(device);
1928
1929         if (ccb == NULL)
1930                 errx(1, "mode_sense: couldn't allocate CCB");
1931
1932         bzero(&(&ccb->ccb_h)[1],
1933               sizeof(struct ccb_scsiio) - sizeof(struct ccb_hdr));
1934
1935         scsi_mode_sense(&ccb->csio,
1936                         /* retries */ retry_count,
1937                         /* cbfcnp */ NULL,
1938                         /* tag_action */ MSG_SIMPLE_Q_TAG,
1939                         /* dbd */ dbd,
1940                         /* page_code */ page_control << 6,
1941                         /* page */ mode_page,
1942                         /* param_buf */ data,
1943                         /* param_len */ datalen,
1944                         /* sense_len */ SSD_FULL_SIZE,
1945                         /* timeout */ timeout ? timeout : 5000);
1946
1947         if (arglist & CAM_ARG_ERR_RECOVER)
1948                 ccb->ccb_h.flags |= CAM_PASS_ERR_RECOVER;
1949
1950         /* Disable freezing the device queue */
1951         ccb->ccb_h.flags |= CAM_DEV_QFRZDIS;
1952
1953         if (((retval = cam_send_ccb(device, ccb)) < 0)
1954          || ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP)) {
1955                 if (arglist & CAM_ARG_VERBOSE) {
1956                         cam_error_print(device, ccb, CAM_ESF_ALL,
1957                                         CAM_EPF_ALL, stderr);
1958                 }
1959                 cam_freeccb(ccb);
1960                 cam_close_device(device);
1961                 if (retval < 0)
1962                         err(1, "error sending mode sense command");
1963                 else
1964                         errx(1, "error sending mode sense command");
1965         }
1966
1967         cam_freeccb(ccb);
1968 }
1969
1970 void
1971 mode_select(struct cam_device *device, int save_pages, int retry_count,
1972            int timeout, u_int8_t *data, int datalen)
1973 {
1974         union ccb *ccb;
1975         int retval;
1976
1977         ccb = cam_getccb(device);
1978
1979         if (ccb == NULL)
1980                 errx(1, "mode_select: couldn't allocate CCB");
1981
1982         bzero(&(&ccb->ccb_h)[1],
1983               sizeof(struct ccb_scsiio) - sizeof(struct ccb_hdr));
1984
1985         scsi_mode_select(&ccb->csio,
1986                          /* retries */ retry_count,
1987                          /* cbfcnp */ NULL,
1988                          /* tag_action */ MSG_SIMPLE_Q_TAG,
1989                          /* scsi_page_fmt */ 1,
1990                          /* save_pages */ save_pages,
1991                          /* param_buf */ data,
1992                          /* param_len */ datalen,
1993                          /* sense_len */ SSD_FULL_SIZE,
1994                          /* timeout */ timeout ? timeout : 5000);
1995
1996         if (arglist & CAM_ARG_ERR_RECOVER)
1997                 ccb->ccb_h.flags |= CAM_PASS_ERR_RECOVER;
1998
1999         /* Disable freezing the device queue */
2000         ccb->ccb_h.flags |= CAM_DEV_QFRZDIS;
2001
2002         if (((retval = cam_send_ccb(device, ccb)) < 0)
2003          || ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP)) {
2004                 if (arglist & CAM_ARG_VERBOSE) {
2005                         cam_error_print(device, ccb, CAM_ESF_ALL,
2006                                         CAM_EPF_ALL, stderr);
2007                 }
2008                 cam_freeccb(ccb);
2009                 cam_close_device(device);
2010
2011                 if (retval < 0)
2012                         err(1, "error sending mode select command");
2013                 else
2014                         errx(1, "error sending mode select command");
2015                 
2016         }
2017
2018         cam_freeccb(ccb);
2019 }
2020
2021 void
2022 modepage(struct cam_device *device, int argc, char **argv, char *combinedopt,
2023          int retry_count, int timeout)
2024 {
2025         int c, mode_page = -1, page_control = 0;
2026         int binary = 0, list = 0;
2027
2028         while ((c = getopt(argc, argv, combinedopt)) != -1) {
2029                 switch(c) {
2030                 case 'b':
2031                         binary = 1;
2032                         break;
2033                 case 'd':
2034                         arglist |= CAM_ARG_DBD;
2035                         break;
2036                 case 'e':
2037                         arglist |= CAM_ARG_MODE_EDIT;
2038                         break;
2039                 case 'l':
2040                         list = 1;
2041                         break;
2042                 case 'm':
2043                         mode_page = strtol(optarg, NULL, 0);
2044                         if (mode_page < 0)
2045                                 errx(1, "invalid mode page %d", mode_page);
2046                         break;
2047                 case 'P':
2048                         page_control = strtol(optarg, NULL, 0);
2049                         if ((page_control < 0) || (page_control > 3))
2050                                 errx(1, "invalid page control field %d",
2051                                      page_control);
2052                         arglist |= CAM_ARG_PAGE_CNTL;
2053                         break;
2054                 default:
2055                         break;
2056                 }
2057         }
2058
2059         if (mode_page == -1 && list == 0)
2060                 errx(1, "you must specify a mode page!");
2061
2062         if (list) {
2063                 mode_list(device, page_control, arglist & CAM_ARG_DBD,
2064                     retry_count, timeout);
2065         } else {
2066                 mode_edit(device, mode_page, page_control,
2067                     arglist & CAM_ARG_DBD, arglist & CAM_ARG_MODE_EDIT, binary,
2068                     retry_count, timeout);
2069         }
2070 }
2071
2072 static int
2073 scsicmd(struct cam_device *device, int argc, char **argv, char *combinedopt,
2074         int retry_count, int timeout)
2075 {
2076         union ccb *ccb;
2077         u_int32_t flags = CAM_DIR_NONE;
2078         u_int8_t *data_ptr = NULL;
2079         u_int8_t cdb[20];
2080         u_int8_t atacmd[12];
2081         struct get_hook hook;
2082         int c, data_bytes = 0;
2083         int cdb_len = 0;
2084         int atacmd_len = 0;
2085         int need_res = 0;
2086         char *datastr = NULL, *tstr, *resstr = NULL;
2087         int error = 0;
2088         int fd_data = 0, fd_res = 0;
2089         int retval;
2090
2091         ccb = cam_getccb(device);
2092
2093         if (ccb == NULL) {
2094                 warnx("scsicmd: error allocating ccb");
2095                 return(1);
2096         }
2097
2098         bzero(&(&ccb->ccb_h)[1],
2099               sizeof(union ccb) - sizeof(struct ccb_hdr));
2100
2101         while ((c = getopt(argc, argv, combinedopt)) != -1) {
2102                 switch(c) {
2103                 case 'a':
2104                         tstr = optarg;
2105                         while (isspace(*tstr) && (*tstr != '\0'))
2106                                 tstr++;
2107                         hook.argc = argc - optind;
2108                         hook.argv = argv + optind;
2109                         hook.got = 0;
2110                         atacmd_len = buff_encode_visit(atacmd, sizeof(atacmd), tstr,
2111                                                     iget, &hook);
2112                         /*
2113                          * Increment optind by the number of arguments the
2114                          * encoding routine processed.  After each call to
2115                          * getopt(3), optind points to the argument that
2116                          * getopt should process _next_.  In this case,
2117                          * that means it points to the first command string
2118                          * argument, if there is one.  Once we increment
2119                          * this, it should point to either the next command
2120                          * line argument, or it should be past the end of
2121                          * the list.
2122                          */
2123                         optind += hook.got;
2124                         break;
2125                 case 'c':
2126                         tstr = optarg;
2127                         while (isspace(*tstr) && (*tstr != '\0'))
2128                                 tstr++;
2129                         hook.argc = argc - optind;
2130                         hook.argv = argv + optind;
2131                         hook.got = 0;
2132                         cdb_len = buff_encode_visit(cdb, sizeof(cdb), tstr,
2133                                                     iget, &hook);
2134                         /*
2135                          * Increment optind by the number of arguments the
2136                          * encoding routine processed.  After each call to
2137                          * getopt(3), optind points to the argument that
2138                          * getopt should process _next_.  In this case,
2139                          * that means it points to the first command string
2140                          * argument, if there is one.  Once we increment
2141                          * this, it should point to either the next command
2142                          * line argument, or it should be past the end of
2143                          * the list.
2144                          */
2145                         optind += hook.got;
2146                         break;
2147                 case 'i':
2148                         if (arglist & CAM_ARG_CMD_OUT) {
2149                                 warnx("command must either be "
2150                                       "read or write, not both");
2151                                 error = 1;
2152                                 goto scsicmd_bailout;
2153                         }
2154                         arglist |= CAM_ARG_CMD_IN;
2155                         flags = CAM_DIR_IN;
2156                         data_bytes = strtol(optarg, NULL, 0);
2157                         if (data_bytes <= 0) {
2158                                 warnx("invalid number of input bytes %d",
2159                                       data_bytes);
2160                                 error = 1;
2161                                 goto scsicmd_bailout;
2162                         }
2163                         hook.argc = argc - optind;
2164                         hook.argv = argv + optind;
2165                         hook.got = 0;
2166                         optind++;
2167                         datastr = cget(&hook, NULL);
2168                         /*
2169                          * If the user supplied "-" instead of a format, he
2170                          * wants the data to be written to stdout.
2171                          */
2172                         if ((datastr != NULL)
2173                          && (datastr[0] == '-'))
2174                                 fd_data = 1;
2175
2176                         data_ptr = (u_int8_t *)malloc(data_bytes);
2177                         if (data_ptr == NULL) {
2178                                 warnx("can't malloc memory for data_ptr");
2179                                 error = 1;
2180                                 goto scsicmd_bailout;
2181                         }
2182                         break;
2183                 case 'o':
2184                         if (arglist & CAM_ARG_CMD_IN) {
2185                                 warnx("command must either be "
2186                                       "read or write, not both");
2187                                 error = 1;      
2188                                 goto scsicmd_bailout;
2189                         }
2190                         arglist |= CAM_ARG_CMD_OUT;
2191                         flags = CAM_DIR_OUT;
2192                         data_bytes = strtol(optarg, NULL, 0);
2193                         if (data_bytes <= 0) {
2194                                 warnx("invalid number of output bytes %d",
2195                                       data_bytes);
2196                                 error = 1;
2197                                 goto scsicmd_bailout;
2198                         }
2199                         hook.argc = argc - optind;
2200                         hook.argv = argv + optind;
2201                         hook.got = 0;
2202                         datastr = cget(&hook, NULL);
2203                         data_ptr = (u_int8_t *)malloc(data_bytes);
2204                         if (data_ptr == NULL) {
2205                                 warnx("can't malloc memory for data_ptr");
2206                                 error = 1;
2207                                 goto scsicmd_bailout;
2208                         }
2209                         /*
2210                          * If the user supplied "-" instead of a format, he
2211                          * wants the data to be read from stdin.
2212                          */
2213                         if ((datastr != NULL)
2214                          && (datastr[0] == '-'))
2215                                 fd_data = 1;
2216                         else
2217                                 buff_encode_visit(data_ptr, data_bytes, datastr,
2218                                                   iget, &hook);
2219                         optind += hook.got;
2220                         break;
2221                 case 'r':
2222                         need_res = 1;
2223                         hook.argc = argc - optind;
2224                         hook.argv = argv + optind;
2225                         hook.got = 0;
2226                         resstr = cget(&hook, NULL);
2227                         if ((resstr != NULL) && (resstr[0] == '-'))
2228                                 fd_res = 1;
2229                         optind += hook.got;
2230                         break;
2231                 default:
2232                         break;
2233                 }
2234         }
2235
2236         /*
2237          * If fd_data is set, and we're writing to the device, we need to
2238          * read the data the user wants written from stdin.
2239          */
2240         if ((fd_data == 1) && (arglist & CAM_ARG_CMD_OUT)) {
2241                 ssize_t amt_read;
2242                 int amt_to_read = data_bytes;
2243                 u_int8_t *buf_ptr = data_ptr;
2244
2245                 for (amt_read = 0; amt_to_read > 0;
2246                      amt_read = read(STDIN_FILENO, buf_ptr, amt_to_read)) {
2247                         if (amt_read == -1) {
2248                                 warn("error reading data from stdin");
2249                                 error = 1;
2250                                 goto scsicmd_bailout;
2251                         }
2252                         amt_to_read -= amt_read;
2253                         buf_ptr += amt_read;
2254                 }
2255         }
2256
2257         if (arglist & CAM_ARG_ERR_RECOVER)
2258                 flags |= CAM_PASS_ERR_RECOVER;
2259
2260         /* Disable freezing the device queue */
2261         flags |= CAM_DEV_QFRZDIS;
2262
2263         if (cdb_len) {
2264                 /*
2265                  * This is taken from the SCSI-3 draft spec.
2266                  * (T10/1157D revision 0.3)
2267                  * The top 3 bits of an opcode are the group code.
2268                  * The next 5 bits are the command code.
2269                  * Group 0:  six byte commands
2270                  * Group 1:  ten byte commands
2271                  * Group 2:  ten byte commands
2272                  * Group 3:  reserved
2273                  * Group 4:  sixteen byte commands
2274                  * Group 5:  twelve byte commands
2275                  * Group 6:  vendor specific
2276                  * Group 7:  vendor specific
2277                  */
2278                 switch((cdb[0] >> 5) & 0x7) {
2279                         case 0:
2280                                 cdb_len = 6;
2281                                 break;
2282                         case 1:
2283                         case 2:
2284                                 cdb_len = 10;
2285                                 break;
2286                         case 3:
2287                         case 6:
2288                         case 7:
2289                                 /* computed by buff_encode_visit */
2290                                 break;
2291                         case 4:
2292                                 cdb_len = 16;
2293                                 break;
2294                         case 5:
2295                                 cdb_len = 12;
2296                                 break;
2297                 }
2298
2299                 /*
2300                  * We should probably use csio_build_visit or something like that
2301                  * here, but it's easier to encode arguments as you go.  The
2302                  * alternative would be skipping the CDB argument and then encoding
2303                  * it here, since we've got the data buffer argument by now.
2304                  */
2305                 bcopy(cdb, &ccb->csio.cdb_io.cdb_bytes, cdb_len);
2306
2307                 cam_fill_csio(&ccb->csio,
2308                       /*retries*/ retry_count,
2309                       /*cbfcnp*/ NULL,
2310                       /*flags*/ flags,
2311                       /*tag_action*/ MSG_SIMPLE_Q_TAG,
2312                       /*data_ptr*/ data_ptr,
2313                       /*dxfer_len*/ data_bytes,
2314                       /*sense_len*/ SSD_FULL_SIZE,
2315                       /*cdb_len*/ cdb_len,
2316                       /*timeout*/ timeout ? timeout : 5000);
2317         } else {
2318                 atacmd_len = 12;
2319                 bcopy(atacmd, &ccb->ataio.cmd.command, atacmd_len);
2320                 if (need_res)
2321                         ccb->ataio.cmd.flags |= CAM_ATAIO_NEEDRESULT;
2322
2323                 cam_fill_ataio(&ccb->ataio,
2324                       /*retries*/ retry_count,
2325                       /*cbfcnp*/ NULL,
2326                       /*flags*/ flags,
2327                       /*tag_action*/ 0,
2328                       /*data_ptr*/ data_ptr,
2329                       /*dxfer_len*/ data_bytes,
2330                       /*timeout*/ timeout ? timeout : 5000);
2331         }
2332
2333         if (((retval = cam_send_ccb(device, ccb)) < 0)
2334          || ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP)) {
2335                 if (retval < 0)
2336                         warn("error sending command");
2337                 else
2338                         warnx("error sending command");
2339
2340                 if (arglist & CAM_ARG_VERBOSE) {
2341                         cam_error_print(device, ccb, CAM_ESF_ALL,
2342                                         CAM_EPF_ALL, stderr);
2343                 }
2344
2345                 error = 1;
2346                 goto scsicmd_bailout;
2347         }
2348
2349         if (atacmd_len && need_res) {
2350                 if (fd_res == 0) {
2351                         buff_decode_visit(&ccb->ataio.res.status, 11, resstr,
2352                                           arg_put, NULL);
2353                         fprintf(stdout, "\n");
2354                 } else {
2355                         fprintf(stdout,
2356                             "%02X %02X %02X %02X %02X %02X %02X %02X %02X %02X %02X\n",
2357                             ccb->ataio.res.status,
2358                             ccb->ataio.res.error,
2359                             ccb->ataio.res.lba_low,
2360                             ccb->ataio.res.lba_mid,
2361                             ccb->ataio.res.lba_high,
2362                             ccb->ataio.res.device,
2363                             ccb->ataio.res.lba_low_exp,
2364                             ccb->ataio.res.lba_mid_exp,
2365                             ccb->ataio.res.lba_high_exp,
2366                             ccb->ataio.res.sector_count,
2367                             ccb->ataio.res.sector_count_exp);
2368                         fflush(stdout);
2369                 }
2370         }
2371
2372         if (((ccb->ccb_h.status & CAM_STATUS_MASK) == CAM_REQ_CMP)
2373          && (arglist & CAM_ARG_CMD_IN)
2374          && (data_bytes > 0)) {
2375                 if (fd_data == 0) {
2376                         buff_decode_visit(data_ptr, data_bytes, datastr,
2377                                           arg_put, NULL);
2378                         fprintf(stdout, "\n");
2379                 } else {
2380                         ssize_t amt_written;
2381                         int amt_to_write = data_bytes;
2382                         u_int8_t *buf_ptr = data_ptr;
2383
2384                         for (amt_written = 0; (amt_to_write > 0) &&
2385                              (amt_written =write(1, buf_ptr,amt_to_write))> 0;){
2386                                 amt_to_write -= amt_written;
2387                                 buf_ptr += amt_written;
2388                         }
2389                         if (amt_written == -1) {
2390                                 warn("error writing data to stdout");
2391                                 error = 1;
2392                                 goto scsicmd_bailout;
2393                         } else if ((amt_written == 0)
2394                                 && (amt_to_write > 0)) {
2395                                 warnx("only wrote %u bytes out of %u",
2396                                       data_bytes - amt_to_write, data_bytes);
2397                         }
2398                 }
2399         }
2400
2401 scsicmd_bailout:
2402
2403         if ((data_bytes > 0) && (data_ptr != NULL))
2404                 free(data_ptr);
2405
2406         cam_freeccb(ccb);
2407
2408         return(error);
2409 }
2410
2411 static int
2412 camdebug(int argc, char **argv, char *combinedopt)
2413 {
2414         int c, fd;
2415         int bus = -1, target = -1, lun = -1;
2416         char *tstr, *tmpstr = NULL;
2417         union ccb ccb;
2418         int error = 0;
2419
2420         bzero(&ccb, sizeof(union ccb));
2421
2422         while ((c = getopt(argc, argv, combinedopt)) != -1) {
2423                 switch(c) {
2424                 case 'I':
2425                         arglist |= CAM_ARG_DEBUG_INFO;
2426                         ccb.cdbg.flags |= CAM_DEBUG_INFO;
2427                         break;
2428                 case 'P':
2429                         arglist |= CAM_ARG_DEBUG_PERIPH;
2430                         ccb.cdbg.flags |= CAM_DEBUG_PERIPH;
2431                         break;
2432                 case 'S':
2433                         arglist |= CAM_ARG_DEBUG_SUBTRACE;
2434                         ccb.cdbg.flags |= CAM_DEBUG_SUBTRACE;
2435                         break;
2436                 case 'T':
2437                         arglist |= CAM_ARG_DEBUG_TRACE;
2438                         ccb.cdbg.flags |= CAM_DEBUG_TRACE;
2439                         break;
2440                 case 'X':
2441                         arglist |= CAM_ARG_DEBUG_XPT;
2442                         ccb.cdbg.flags |= CAM_DEBUG_XPT;
2443                         break;
2444                 case 'c':
2445                         arglist |= CAM_ARG_DEBUG_CDB;
2446                         ccb.cdbg.flags |= CAM_DEBUG_CDB;
2447                         break;
2448                 default:
2449                         break;
2450                 }
2451         }
2452
2453         if ((fd = open(XPT_DEVICE, O_RDWR)) < 0) {
2454                 warnx("error opening transport layer device %s", XPT_DEVICE);
2455                 warn("%s", XPT_DEVICE);
2456                 return(1);
2457         }
2458         argc -= optind;
2459         argv += optind;
2460
2461         if (argc <= 0) {
2462                 warnx("you must specify \"off\", \"all\" or a bus,");
2463                 warnx("bus:target, or bus:target:lun");
2464                 close(fd);
2465                 return(1);
2466         }
2467
2468         tstr = *argv;
2469
2470         while (isspace(*tstr) && (*tstr != '\0'))
2471                 tstr++;
2472
2473         if (strncmp(tstr, "off", 3) == 0) {
2474                 ccb.cdbg.flags = CAM_DEBUG_NONE;
2475                 arglist &= ~(CAM_ARG_DEBUG_INFO|CAM_ARG_DEBUG_PERIPH|
2476                              CAM_ARG_DEBUG_TRACE|CAM_ARG_DEBUG_SUBTRACE|
2477                              CAM_ARG_DEBUG_XPT);
2478         } else if (strncmp(tstr, "all", 3) != 0) {
2479                 tmpstr = (char *)strtok(tstr, ":");
2480                 if ((tmpstr != NULL) && (*tmpstr != '\0')){
2481                         bus = strtol(tmpstr, NULL, 0);
2482                         arglist |= CAM_ARG_BUS;
2483                         tmpstr = (char *)strtok(NULL, ":");
2484                         if ((tmpstr != NULL) && (*tmpstr != '\0')){
2485                                 target = strtol(tmpstr, NULL, 0);
2486                                 arglist |= CAM_ARG_TARGET;
2487                                 tmpstr = (char *)strtok(NULL, ":");
2488                                 if ((tmpstr != NULL) && (*tmpstr != '\0')){
2489                                         lun = strtol(tmpstr, NULL, 0);
2490                                         arglist |= CAM_ARG_LUN;
2491                                 }
2492                         }
2493                 } else {
2494                         error = 1;
2495                         warnx("you must specify \"all\", \"off\", or a bus,");
2496                         warnx("bus:target, or bus:target:lun to debug");
2497                 }
2498         }
2499         
2500         if (error == 0) {
2501
2502                 ccb.ccb_h.func_code = XPT_DEBUG;
2503                 ccb.ccb_h.path_id = bus;
2504                 ccb.ccb_h.target_id = target;
2505                 ccb.ccb_h.target_lun = lun;
2506
2507                 if (ioctl(fd, CAMIOCOMMAND, &ccb) == -1) {
2508                         warn("CAMIOCOMMAND ioctl failed");
2509                         error = 1;
2510                 }
2511
2512                 if (error == 0) {
2513                         if ((ccb.ccb_h.status & CAM_STATUS_MASK) ==
2514                              CAM_FUNC_NOTAVAIL) {
2515                                 warnx("CAM debugging not available");
2516                                 warnx("you need to put options CAMDEBUG in"
2517                                       " your kernel config file!");
2518                                 error = 1;
2519                         } else if ((ccb.ccb_h.status & CAM_STATUS_MASK) !=
2520                                     CAM_REQ_CMP) {
2521                                 warnx("XPT_DEBUG CCB failed with status %#x",
2522                                       ccb.ccb_h.status);
2523                                 error = 1;
2524                         } else {
2525                                 if (ccb.cdbg.flags == CAM_DEBUG_NONE) {
2526                                         fprintf(stderr,
2527                                                 "Debugging turned off\n");
2528                                 } else {
2529                                         fprintf(stderr,
2530                                                 "Debugging enabled for "
2531                                                 "%d:%d:%d\n",
2532                                                 bus, target, lun);
2533                                 }
2534                         }
2535                 }
2536                 close(fd);
2537         }
2538
2539         return(error);
2540 }
2541
2542 static int
2543 tagcontrol(struct cam_device *device, int argc, char **argv,
2544            char *combinedopt)
2545 {
2546         int c;
2547         union ccb *ccb;
2548         int numtags = -1;
2549         int retval = 0;
2550         int quiet = 0;
2551         char pathstr[1024];
2552
2553         ccb = cam_getccb(device);
2554
2555         if (ccb == NULL) {
2556                 warnx("tagcontrol: error allocating ccb");
2557                 return(1);
2558         }
2559
2560         while ((c = getopt(argc, argv, combinedopt)) != -1) {
2561                 switch(c) {
2562                 case 'N':
2563                         numtags = strtol(optarg, NULL, 0);
2564                         if (numtags < 0) {
2565                                 warnx("tag count %d is < 0", numtags);
2566                                 retval = 1;
2567                                 goto tagcontrol_bailout;
2568                         }
2569                         break;
2570                 case 'q':
2571                         quiet++;
2572                         break;
2573                 default:
2574                         break;
2575                 }
2576         }
2577
2578         cam_path_string(device, pathstr, sizeof(pathstr));
2579
2580         if (numtags >= 0) {
2581                 bzero(&(&ccb->ccb_h)[1],
2582                       sizeof(struct ccb_relsim) - sizeof(struct ccb_hdr));
2583                 ccb->ccb_h.func_code = XPT_REL_SIMQ;
2584                 ccb->crs.release_flags = RELSIM_ADJUST_OPENINGS;
2585                 ccb->crs.openings = numtags;
2586
2587
2588                 if (cam_send_ccb(device, ccb) < 0) {
2589                         perror("error sending XPT_REL_SIMQ CCB");
2590                         retval = 1;
2591                         goto tagcontrol_bailout;
2592                 }
2593
2594                 if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
2595                         warnx("XPT_REL_SIMQ CCB failed");
2596                         cam_error_print(device, ccb, CAM_ESF_ALL,
2597                                         CAM_EPF_ALL, stderr);
2598                         retval = 1;
2599                         goto tagcontrol_bailout;
2600                 }
2601
2602
2603                 if (quiet == 0)
2604                         fprintf(stdout, "%stagged openings now %d\n",
2605                                 pathstr, ccb->crs.openings);
2606         }
2607
2608         bzero(&(&ccb->ccb_h)[1],
2609               sizeof(struct ccb_getdevstats) - sizeof(struct ccb_hdr));
2610
2611         ccb->ccb_h.func_code = XPT_GDEV_STATS;
2612
2613         if (cam_send_ccb(device, ccb) < 0) {
2614                 perror("error sending XPT_GDEV_STATS CCB");
2615                 retval = 1;
2616                 goto tagcontrol_bailout;
2617         }
2618
2619         if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
2620                 warnx("XPT_GDEV_STATS CCB failed");
2621                 cam_error_print(device, ccb, CAM_ESF_ALL,
2622                                 CAM_EPF_ALL, stderr);
2623                 retval = 1;
2624                 goto tagcontrol_bailout;
2625         }
2626
2627         if (arglist & CAM_ARG_VERBOSE) {
2628                 fprintf(stdout, "%s", pathstr);
2629                 fprintf(stdout, "dev_openings  %d\n", ccb->cgds.dev_openings);
2630                 fprintf(stdout, "%s", pathstr);
2631                 fprintf(stdout, "dev_active    %d\n", ccb->cgds.dev_active);
2632                 fprintf(stdout, "%s", pathstr);
2633                 fprintf(stdout, "devq_openings %d\n", ccb->cgds.devq_openings);
2634                 fprintf(stdout, "%s", pathstr);
2635                 fprintf(stdout, "devq_queued   %d\n", ccb->cgds.devq_queued);
2636                 fprintf(stdout, "%s", pathstr);
2637                 fprintf(stdout, "held          %d\n", ccb->cgds.held);
2638                 fprintf(stdout, "%s", pathstr);
2639                 fprintf(stdout, "mintags       %d\n", ccb->cgds.mintags);
2640                 fprintf(stdout, "%s", pathstr);
2641                 fprintf(stdout, "maxtags       %d\n", ccb->cgds.maxtags);
2642         } else {
2643                 if (quiet == 0) {
2644                         fprintf(stdout, "%s", pathstr);
2645                         fprintf(stdout, "device openings: ");
2646                 }
2647                 fprintf(stdout, "%d\n", ccb->cgds.dev_openings +
2648                         ccb->cgds.dev_active);
2649         }
2650
2651 tagcontrol_bailout:
2652
2653         cam_freeccb(ccb);
2654         return(retval);
2655 }
2656
2657 static void
2658 cts_print(struct cam_device *device, struct ccb_trans_settings *cts)
2659 {
2660         char pathstr[1024];
2661
2662         cam_path_string(device, pathstr, sizeof(pathstr));
2663
2664         if (cts->transport == XPORT_SPI) {
2665                 struct ccb_trans_settings_spi *spi =
2666                     &cts->xport_specific.spi;
2667
2668                 if ((spi->valid & CTS_SPI_VALID_SYNC_RATE) != 0) {
2669
2670                         fprintf(stdout, "%ssync parameter: %d\n", pathstr,
2671                                 spi->sync_period);
2672
2673                         if (spi->sync_offset != 0) {
2674                                 u_int freq;
2675
2676                                 freq = scsi_calc_syncsrate(spi->sync_period);
2677                                 fprintf(stdout, "%sfrequency: %d.%03dMHz\n",
2678                                         pathstr, freq / 1000, freq % 1000);
2679                         }
2680                 }
2681
2682                 if (spi->valid & CTS_SPI_VALID_SYNC_OFFSET) {
2683                         fprintf(stdout, "%soffset: %d\n", pathstr,
2684                             spi->sync_offset);
2685                 }
2686
2687                 if (spi->valid & CTS_SPI_VALID_BUS_WIDTH) {
2688                         fprintf(stdout, "%sbus width: %d bits\n", pathstr,
2689                                 (0x01 << spi->bus_width) * 8);
2690                 }
2691
2692                 if (spi->valid & CTS_SPI_VALID_DISC) {
2693                         fprintf(stdout, "%sdisconnection is %s\n", pathstr,
2694                                 (spi->flags & CTS_SPI_FLAGS_DISC_ENB) ?
2695                                 "enabled" : "disabled");
2696                 }
2697         }
2698
2699         if (cts->protocol == PROTO_SCSI) {
2700                 struct ccb_trans_settings_scsi *scsi=
2701                     &cts->proto_specific.scsi;
2702
2703                 if (scsi->valid & CTS_SCSI_VALID_TQ) {
2704                         fprintf(stdout, "%stagged queueing is %s\n", pathstr,
2705                                 (scsi->flags & CTS_SCSI_FLAGS_TAG_ENB) ?
2706                                 "enabled" : "disabled");
2707                 }
2708         }
2709
2710 }
2711
2712 /*
2713  * Get a path inquiry CCB for the specified device.  
2714  */
2715 static int
2716 get_cpi(struct cam_device *device, struct ccb_pathinq *cpi)
2717 {
2718         union ccb *ccb;
2719         int retval = 0;
2720
2721         ccb = cam_getccb(device);
2722         if (ccb == NULL) {
2723                 warnx("get_cpi: couldn't allocate CCB");
2724                 return(1);
2725         }
2726         bzero(&(&ccb->ccb_h)[1],
2727               sizeof(struct ccb_pathinq) - sizeof(struct ccb_hdr));
2728         ccb->ccb_h.func_code = XPT_PATH_INQ;
2729         if (cam_send_ccb(device, ccb) < 0) {
2730                 warn("get_cpi: error sending Path Inquiry CCB");
2731                 if (arglist & CAM_ARG_VERBOSE)
2732                         cam_error_print(device, ccb, CAM_ESF_ALL,
2733                                         CAM_EPF_ALL, stderr);
2734                 retval = 1;
2735                 goto get_cpi_bailout;
2736         }
2737         if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
2738                 if (arglist & CAM_ARG_VERBOSE)
2739                         cam_error_print(device, ccb, CAM_ESF_ALL,
2740                                         CAM_EPF_ALL, stderr);
2741                 retval = 1;
2742                 goto get_cpi_bailout;
2743         }
2744         bcopy(&ccb->cpi, cpi, sizeof(struct ccb_pathinq));
2745
2746 get_cpi_bailout:
2747         cam_freeccb(ccb);
2748         return(retval);
2749 }
2750
2751 /*
2752  * Get a get device CCB for the specified device.  
2753  */
2754 static int
2755 get_cgd(struct cam_device *device, struct ccb_getdev *cgd)
2756 {
2757         union ccb *ccb;
2758         int retval = 0;
2759
2760         ccb = cam_getccb(device);
2761         if (ccb == NULL) {
2762                 warnx("get_cgd: couldn't allocate CCB");
2763                 return(1);
2764         }
2765         bzero(&(&ccb->ccb_h)[1],
2766               sizeof(struct ccb_pathinq) - sizeof(struct ccb_hdr));
2767         ccb->ccb_h.func_code = XPT_GDEV_TYPE;
2768         if (cam_send_ccb(device, ccb) < 0) {
2769                 warn("get_cgd: error sending Path Inquiry CCB");
2770                 if (arglist & CAM_ARG_VERBOSE)
2771                         cam_error_print(device, ccb, CAM_ESF_ALL,
2772                                         CAM_EPF_ALL, stderr);
2773                 retval = 1;
2774                 goto get_cgd_bailout;
2775         }
2776         if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
2777                 if (arglist & CAM_ARG_VERBOSE)
2778                         cam_error_print(device, ccb, CAM_ESF_ALL,
2779                                         CAM_EPF_ALL, stderr);
2780                 retval = 1;
2781                 goto get_cgd_bailout;
2782         }
2783         bcopy(&ccb->cgd, cgd, sizeof(struct ccb_getdev));
2784
2785 get_cgd_bailout:
2786         cam_freeccb(ccb);
2787         return(retval);
2788 }
2789
2790 static void
2791 cpi_print(struct ccb_pathinq *cpi)
2792 {
2793         char adapter_str[1024];
2794         int i;
2795
2796         snprintf(adapter_str, sizeof(adapter_str),
2797                  "%s%d:", cpi->dev_name, cpi->unit_number);
2798
2799         fprintf(stdout, "%s SIM/HBA version: %d\n", adapter_str,
2800                 cpi->version_num);
2801
2802         for (i = 1; i < 0xff; i = i << 1) {
2803                 const char *str;
2804
2805                 if ((i & cpi->hba_inquiry) == 0)
2806                         continue;
2807
2808                 fprintf(stdout, "%s supports ", adapter_str);
2809
2810                 switch(i) {
2811                 case PI_MDP_ABLE:
2812                         str = "MDP message";
2813                         break;
2814                 case PI_WIDE_32:
2815                         str = "32 bit wide SCSI";
2816                         break;
2817                 case PI_WIDE_16:
2818                         str = "16 bit wide SCSI";
2819                         break;
2820                 case PI_SDTR_ABLE:
2821                         str = "SDTR message";
2822                         break;
2823                 case PI_LINKED_CDB:
2824                         str = "linked CDBs";
2825                         break;
2826                 case PI_TAG_ABLE:
2827                         str = "tag queue messages";
2828                         break;
2829                 case PI_SOFT_RST:
2830                         str = "soft reset alternative";
2831                         break;
2832                 case PI_SATAPM:
2833                         str = "SATA Port Multiplier";
2834                         break;
2835                 default:
2836                         str = "unknown PI bit set";
2837                         break;
2838                 }
2839                 fprintf(stdout, "%s\n", str);
2840         }
2841
2842         for (i = 1; i < 0xff; i = i << 1) {
2843                 const char *str;
2844
2845                 if ((i & cpi->hba_misc) == 0)
2846                         continue;
2847
2848                 fprintf(stdout, "%s ", adapter_str);
2849
2850                 switch(i) {
2851                 case PIM_SCANHILO:
2852                         str = "bus scans from high ID to low ID";
2853                         break;
2854                 case PIM_NOREMOVE:
2855                         str = "removable devices not included in scan";
2856                         break;
2857                 case PIM_NOINITIATOR:
2858                         str = "initiator role not supported";
2859                         break;
2860                 case PIM_NOBUSRESET:
2861                         str = "user has disabled initial BUS RESET or"
2862                               " controller is in target/mixed mode";
2863                         break;
2864                 case PIM_NO_6_BYTE:
2865                         str = "do not send 6-byte commands";
2866                         break;
2867                 case PIM_SEQSCAN:
2868                         str = "scan bus sequentially";
2869                         break;
2870                 default:
2871                         str = "unknown PIM bit set";
2872                         break;
2873                 }
2874                 fprintf(stdout, "%s\n", str);
2875         }
2876
2877         for (i = 1; i < 0xff; i = i << 1) {
2878                 const char *str;
2879
2880                 if ((i & cpi->target_sprt) == 0)
2881                         continue;
2882
2883                 fprintf(stdout, "%s supports ", adapter_str);
2884                 switch(i) {
2885                 case PIT_PROCESSOR:
2886                         str = "target mode processor mode";
2887                         break;
2888                 case PIT_PHASE:
2889                         str = "target mode phase cog. mode";
2890                         break;
2891                 case PIT_DISCONNECT:
2892                         str = "disconnects in target mode";
2893                         break;
2894                 case PIT_TERM_IO:
2895                         str = "terminate I/O message in target mode";
2896                         break;
2897                 case PIT_GRP_6:
2898                         str = "group 6 commands in target mode";
2899                         break;
2900                 case PIT_GRP_7:
2901                         str = "group 7 commands in target mode";
2902                         break;
2903                 default:
2904                         str = "unknown PIT bit set";
2905                         break;
2906                 }
2907
2908                 fprintf(stdout, "%s\n", str);
2909         }
2910         fprintf(stdout, "%s HBA engine count: %d\n", adapter_str,
2911                 cpi->hba_eng_cnt);
2912         fprintf(stdout, "%s maximum target: %d\n", adapter_str,
2913                 cpi->max_target);
2914         fprintf(stdout, "%s maximum LUN: %d\n", adapter_str,
2915                 cpi->max_lun);
2916         fprintf(stdout, "%s highest path ID in subsystem: %d\n",
2917                 adapter_str, cpi->hpath_id);
2918         fprintf(stdout, "%s initiator ID: %d\n", adapter_str,
2919                 cpi->initiator_id);
2920         fprintf(stdout, "%s SIM vendor: %s\n", adapter_str, cpi->sim_vid);
2921         fprintf(stdout, "%s HBA vendor: %s\n", adapter_str, cpi->hba_vid);
2922         fprintf(stdout, "%s bus ID: %d\n", adapter_str, cpi->bus_id);
2923         fprintf(stdout, "%s base transfer speed: ", adapter_str);
2924         if (cpi->base_transfer_speed > 1000)
2925                 fprintf(stdout, "%d.%03dMB/sec\n",
2926                         cpi->base_transfer_speed / 1000,
2927                         cpi->base_transfer_speed % 1000);
2928         else
2929                 fprintf(stdout, "%dKB/sec\n",
2930                         (cpi->base_transfer_speed % 1000) * 1000);
2931 }
2932
2933 static int
2934 get_print_cts(struct cam_device *device, int user_settings, int quiet,
2935               struct ccb_trans_settings *cts)
2936 {
2937         int retval;
2938         union ccb *ccb;
2939
2940         retval = 0;
2941         ccb = cam_getccb(device);
2942
2943         if (ccb == NULL) {
2944                 warnx("get_print_cts: error allocating ccb");
2945                 return(1);
2946         }
2947
2948         bzero(&(&ccb->ccb_h)[1],
2949               sizeof(struct ccb_trans_settings) - sizeof(struct ccb_hdr));
2950
2951         ccb->ccb_h.func_code = XPT_GET_TRAN_SETTINGS;
2952
2953         if (user_settings == 0)
2954                 ccb->cts.type = CTS_TYPE_CURRENT_SETTINGS;
2955         else
2956                 ccb->cts.type = CTS_TYPE_USER_SETTINGS;
2957
2958         if (cam_send_ccb(device, ccb) < 0) {
2959                 perror("error sending XPT_GET_TRAN_SETTINGS CCB");
2960                 if (arglist & CAM_ARG_VERBOSE)
2961                         cam_error_print(device, ccb, CAM_ESF_ALL,
2962                                         CAM_EPF_ALL, stderr);
2963                 retval = 1;
2964                 goto get_print_cts_bailout;
2965         }
2966
2967         if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
2968                 warnx("XPT_GET_TRANS_SETTINGS CCB failed");
2969                 if (arglist & CAM_ARG_VERBOSE)
2970                         cam_error_print(device, ccb, CAM_ESF_ALL,
2971                                         CAM_EPF_ALL, stderr);
2972                 retval = 1;
2973                 goto get_print_cts_bailout;
2974         }
2975
2976         if (quiet == 0)
2977                 cts_print(device, &ccb->cts);
2978
2979         if (cts != NULL)
2980                 bcopy(&ccb->cts, cts, sizeof(struct ccb_trans_settings));
2981
2982 get_print_cts_bailout:
2983
2984         cam_freeccb(ccb);
2985
2986         return(retval);
2987 }
2988
2989 static int
2990 ratecontrol(struct cam_device *device, int retry_count, int timeout,
2991             int argc, char **argv, char *combinedopt)
2992 {
2993         int c;
2994         union ccb *ccb;
2995         int user_settings = 0;
2996         int retval = 0;
2997         int disc_enable = -1, tag_enable = -1;
2998         int offset = -1;
2999         double syncrate = -1;
3000         int bus_width = -1;
3001         int quiet = 0;
3002         int change_settings = 0, send_tur = 0;
3003         struct ccb_pathinq cpi;
3004
3005         ccb = cam_getccb(device);
3006
3007         if (ccb == NULL) {
3008                 warnx("ratecontrol: error allocating ccb");
3009                 return(1);
3010         }
3011
3012         while ((c = getopt(argc, argv, combinedopt)) != -1) {
3013                 switch(c){
3014                 case 'a':
3015                         send_tur = 1;
3016                         break;
3017                 case 'c':
3018                         user_settings = 0;
3019                         break;
3020                 case 'D':
3021                         if (strncasecmp(optarg, "enable", 6) == 0)
3022                                 disc_enable = 1;
3023                         else if (strncasecmp(optarg, "disable", 7) == 0)
3024                                 disc_enable = 0;
3025                         else {
3026                                 warnx("-D argument \"%s\" is unknown", optarg);
3027                                 retval = 1;
3028                                 goto ratecontrol_bailout;
3029                         }
3030                         change_settings = 1;
3031                         break;
3032                 case 'O':
3033                         offset = strtol(optarg, NULL, 0);
3034                         if (offset < 0) {
3035                                 warnx("offset value %d is < 0", offset);
3036                                 retval = 1;
3037                                 goto ratecontrol_bailout;
3038                         }
3039                         change_settings = 1;
3040                         break;
3041                 case 'q':
3042                         quiet++;
3043                         break;
3044                 case 'R':
3045                         syncrate = atof(optarg);
3046
3047                         if (syncrate < 0) {
3048                                 warnx("sync rate %f is < 0", syncrate);
3049                                 retval = 1;
3050                                 goto ratecontrol_bailout;
3051                         }
3052                         change_settings = 1;
3053                         break;
3054                 case 'T':
3055                         if (strncasecmp(optarg, "enable", 6) == 0)
3056                                 tag_enable = 1;
3057                         else if (strncasecmp(optarg, "disable", 7) == 0)
3058                                 tag_enable = 0;
3059                         else {
3060                                 warnx("-T argument \"%s\" is unknown", optarg);
3061                                 retval = 1;
3062                                 goto ratecontrol_bailout;
3063                         }
3064                         change_settings = 1;
3065                         break;
3066                 case 'U':
3067                         user_settings = 1;
3068                         break;
3069                 case 'W':
3070                         bus_width = strtol(optarg, NULL, 0);
3071                         if (bus_width < 0) {
3072                                 warnx("bus width %d is < 0", bus_width);
3073                                 retval = 1;
3074                                 goto ratecontrol_bailout;
3075                         }
3076                         change_settings = 1;
3077                         break;
3078                 default:
3079                         break;
3080                 }
3081         }
3082
3083         bzero(&(&ccb->ccb_h)[1],
3084               sizeof(struct ccb_pathinq) - sizeof(struct ccb_hdr));
3085
3086         /*
3087          * Grab path inquiry information, so we can determine whether
3088          * or not the initiator is capable of the things that the user
3089          * requests.
3090          */
3091         ccb->ccb_h.func_code = XPT_PATH_INQ;
3092
3093         if (cam_send_ccb(device, ccb) < 0) {
3094                 perror("error sending XPT_PATH_INQ CCB");
3095                 if (arglist & CAM_ARG_VERBOSE) {
3096                         cam_error_print(device, ccb, CAM_ESF_ALL,
3097                                         CAM_EPF_ALL, stderr);
3098                 }
3099                 retval = 1;
3100                 goto ratecontrol_bailout;
3101         }
3102
3103         if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
3104                 warnx("XPT_PATH_INQ CCB failed");
3105                 if (arglist & CAM_ARG_VERBOSE) {
3106                         cam_error_print(device, ccb, CAM_ESF_ALL,
3107                                         CAM_EPF_ALL, stderr);
3108                 }
3109                 retval = 1;
3110                 goto ratecontrol_bailout;
3111         }
3112
3113         bcopy(&ccb->cpi, &cpi, sizeof(struct ccb_pathinq));
3114
3115         bzero(&(&ccb->ccb_h)[1],
3116               sizeof(struct ccb_trans_settings) - sizeof(struct ccb_hdr));
3117
3118         if (quiet == 0)
3119                 fprintf(stdout, "Current Parameters:\n");
3120
3121         retval = get_print_cts(device, user_settings, quiet, &ccb->cts);
3122
3123         if (retval != 0)
3124                 goto ratecontrol_bailout;
3125
3126         if (arglist & CAM_ARG_VERBOSE)
3127                 cpi_print(&cpi);
3128
3129         if (change_settings) {
3130                 int didsettings = 0;
3131                 struct ccb_trans_settings_spi *spi = NULL;
3132                 struct ccb_trans_settings_scsi *scsi = NULL;
3133
3134                 if (ccb->cts.transport == XPORT_SPI) {
3135                         spi = &ccb->cts.xport_specific.spi;
3136                         spi->valid = 0;
3137                 }
3138                 if (ccb->cts.protocol == PROTO_SCSI) {
3139                         scsi = &ccb->cts.proto_specific.scsi;
3140                         scsi->valid = 0;
3141                 }
3142                 if (spi && disc_enable != -1) {
3143                         spi->valid |= CTS_SPI_VALID_DISC;
3144                         if (disc_enable == 0)
3145                                 spi->flags &= ~CTS_SPI_FLAGS_DISC_ENB;
3146                         else
3147                                 spi->flags |= CTS_SPI_FLAGS_DISC_ENB;
3148                 }
3149
3150                 if (scsi && tag_enable != -1) {
3151                         if ((cpi.hba_inquiry & PI_TAG_ABLE) == 0) {
3152                                 warnx("HBA does not support tagged queueing, "
3153                                       "so you cannot modify tag settings");
3154                                 retval = 1;
3155                                 goto ratecontrol_bailout;
3156                         }
3157
3158                         scsi->valid |= CTS_SCSI_VALID_TQ;
3159
3160                         if (tag_enable == 0)
3161                                 scsi->flags &= ~CTS_SCSI_FLAGS_TAG_ENB;
3162                         else
3163                                 scsi->flags |= CTS_SCSI_FLAGS_TAG_ENB;
3164                         didsettings++;
3165                 }
3166
3167                 if (spi && offset != -1) {
3168                         if ((cpi.hba_inquiry & PI_SDTR_ABLE) == 0) {
3169                                 warnx("HBA at %s%d is not cable of changing "
3170                                       "offset", cpi.dev_name,
3171                                       cpi.unit_number);
3172                                 retval = 1;
3173                                 goto ratecontrol_bailout;
3174                         }
3175                         spi->valid |= CTS_SPI_VALID_SYNC_OFFSET;
3176                         spi->sync_offset = offset;
3177                         didsettings++;
3178                 }
3179
3180                 if (spi && syncrate != -1) {
3181                         int prelim_sync_period;
3182                         u_int freq;
3183
3184                         if ((cpi.hba_inquiry & PI_SDTR_ABLE) == 0) {
3185                                 warnx("HBA at %s%d is not cable of changing "
3186                                       "transfer rates", cpi.dev_name,
3187                                       cpi.unit_number);
3188                                 retval = 1;
3189                                 goto ratecontrol_bailout;
3190                         }
3191
3192                         spi->valid |= CTS_SPI_VALID_SYNC_RATE;
3193
3194                         /*
3195                          * The sync rate the user gives us is in MHz.
3196                          * We need to translate it into KHz for this
3197                          * calculation.
3198                          */
3199                         syncrate *= 1000;
3200
3201                         /*
3202                          * Next, we calculate a "preliminary" sync period
3203                          * in tenths of a nanosecond.
3204                          */
3205                         if (syncrate == 0)
3206                                 prelim_sync_period = 0;
3207                         else
3208                                 prelim_sync_period = 10000000 / syncrate;
3209
3210                         spi->sync_period =
3211                                 scsi_calc_syncparam(prelim_sync_period);
3212
3213                         freq = scsi_calc_syncsrate(spi->sync_period);
3214                         didsettings++;
3215                 }
3216
3217                 /*
3218                  * The bus_width argument goes like this:
3219                  * 0 == 8 bit
3220                  * 1 == 16 bit
3221                  * 2 == 32 bit
3222                  * Therefore, if you shift the number of bits given on the
3223                  * command line right by 4, you should get the correct
3224                  * number.
3225                  */
3226                 if (spi && bus_width != -1) {
3227
3228                         /*
3229                          * We might as well validate things here with a
3230                          * decipherable error message, rather than what
3231                          * will probably be an indecipherable error message
3232                          * by the time it gets back to us.
3233                          */
3234                         if ((bus_width == 16)
3235                          && ((cpi.hba_inquiry & PI_WIDE_16) == 0)) {
3236                                 warnx("HBA does not support 16 bit bus width");
3237                                 retval = 1;
3238                                 goto ratecontrol_bailout;
3239                         } else if ((bus_width == 32)
3240                                 && ((cpi.hba_inquiry & PI_WIDE_32) == 0)) {
3241                                 warnx("HBA does not support 32 bit bus width");
3242                                 retval = 1;
3243                                 goto ratecontrol_bailout;
3244                         } else if ((bus_width != 8)
3245                                 && (bus_width != 16)
3246                                 && (bus_width != 32)) {
3247                                 warnx("Invalid bus width %d", bus_width);
3248                                 retval = 1;
3249                                 goto ratecontrol_bailout;
3250                         }
3251
3252                         spi->valid |= CTS_SPI_VALID_BUS_WIDTH;
3253                         spi->bus_width = bus_width >> 4;
3254                         didsettings++;
3255                 }
3256
3257                 if  (didsettings == 0) {
3258                         goto ratecontrol_bailout;
3259                 }
3260                 ccb->ccb_h.func_code = XPT_SET_TRAN_SETTINGS;
3261
3262                 if (cam_send_ccb(device, ccb) < 0) {
3263                         perror("error sending XPT_SET_TRAN_SETTINGS CCB");
3264                         if (arglist & CAM_ARG_VERBOSE) {
3265                                 cam_error_print(device, ccb, CAM_ESF_ALL,
3266                                                 CAM_EPF_ALL, stderr);
3267                         }
3268                         retval = 1;
3269                         goto ratecontrol_bailout;
3270                 }
3271
3272                 if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
3273                         warnx("XPT_SET_TRANS_SETTINGS CCB failed");
3274                         if (arglist & CAM_ARG_VERBOSE) {
3275                                 cam_error_print(device, ccb, CAM_ESF_ALL,
3276                                                 CAM_EPF_ALL, stderr);
3277                         }
3278                         retval = 1;
3279                         goto ratecontrol_bailout;
3280                 }
3281         }
3282
3283         if (send_tur) {
3284                 retval = testunitready(device, retry_count, timeout,
3285                                        (arglist & CAM_ARG_VERBOSE) ? 0 : 1);
3286
3287                 /*
3288                  * If the TUR didn't succeed, just bail.
3289                  */
3290                 if (retval != 0) {
3291                         if (quiet == 0)
3292                                 fprintf(stderr, "Test Unit Ready failed\n");
3293                         goto ratecontrol_bailout;
3294                 }
3295
3296                 /*
3297                  * If the user wants things quiet, there's no sense in
3298                  * getting the transfer settings, if we're not going
3299                  * to print them.
3300                  */
3301                 if (quiet != 0)
3302                         goto ratecontrol_bailout;
3303
3304                 fprintf(stdout, "New Parameters:\n");
3305                 retval = get_print_cts(device, user_settings, 0, NULL);
3306         }
3307
3308 ratecontrol_bailout:
3309
3310         cam_freeccb(ccb);
3311         return(retval);
3312 }
3313
3314 static int
3315 scsiformat(struct cam_device *device, int argc, char **argv,
3316            char *combinedopt, int retry_count, int timeout)
3317 {
3318         union ccb *ccb;
3319         int c;
3320         int ycount = 0, quiet = 0;
3321         int error = 0, response = 0, retval = 0;
3322         int use_timeout = 10800 * 1000;
3323         int immediate = 1;
3324         struct format_defect_list_header fh;
3325         u_int8_t *data_ptr = NULL;
3326         u_int32_t dxfer_len = 0;
3327         u_int8_t byte2 = 0;
3328         int num_warnings = 0;
3329         int reportonly = 0;
3330
3331         ccb = cam_getccb(device);
3332
3333         if (ccb == NULL) {
3334                 warnx("scsiformat: error allocating ccb");
3335                 return(1);
3336         }
3337
3338         bzero(&(&ccb->ccb_h)[1],
3339               sizeof(struct ccb_scsiio) - sizeof(struct ccb_hdr));
3340
3341         while ((c = getopt(argc, argv, combinedopt)) != -1) {
3342                 switch(c) {
3343                 case 'q':
3344                         quiet++;
3345                         break;
3346                 case 'r':
3347                         reportonly = 1;
3348                         break;
3349                 case 'w':
3350                         immediate = 0;
3351                         break;
3352                 case 'y':
3353                         ycount++;
3354                         break;
3355                 }
3356         }
3357
3358         if (reportonly)
3359                 goto doreport;
3360
3361         if (quiet == 0) {
3362                 fprintf(stdout, "You are about to REMOVE ALL DATA from the "
3363                         "following device:\n");
3364
3365                 error = scsidoinquiry(device, argc, argv, combinedopt,
3366                                       retry_count, timeout);
3367
3368                 if (error != 0) {
3369                         warnx("scsiformat: error sending inquiry");
3370                         goto scsiformat_bailout;
3371                 }
3372         }
3373
3374         if (ycount == 0) {
3375
3376                 do {
3377                         char str[1024];
3378
3379                         fprintf(stdout, "Are you SURE you want to do "
3380                                 "this? (yes/no) ");
3381
3382                         if (fgets(str, sizeof(str), stdin) != NULL) {
3383
3384                                 if (strncasecmp(str, "yes", 3) == 0)
3385                                         response = 1;
3386                                 else if (strncasecmp(str, "no", 2) == 0)
3387                                         response = -1;
3388                                 else {
3389                                         fprintf(stdout, "Please answer"
3390                                                 " \"yes\" or \"no\"\n");
3391                                 }
3392                         }
3393                 } while (response == 0);
3394
3395                 if (response == -1) {
3396                         error = 1;
3397                         goto scsiformat_bailout;
3398                 }
3399         }
3400
3401         if (timeout != 0)
3402                 use_timeout = timeout;
3403
3404         if (quiet == 0) {
3405                 fprintf(stdout, "Current format timeout is %d seconds\n",
3406                         use_timeout / 1000);
3407         }
3408
3409         /*
3410          * If the user hasn't disabled questions and didn't specify a
3411          * timeout on the command line, ask them if they want the current
3412          * timeout.
3413          */
3414         if ((ycount == 0)
3415          && (timeout == 0)) {
3416                 char str[1024];
3417                 int new_timeout = 0;
3418
3419                 fprintf(stdout, "Enter new timeout in seconds or press\n"
3420                         "return to keep the current timeout [%d] ",
3421                         use_timeout / 1000);
3422
3423                 if (fgets(str, sizeof(str), stdin) != NULL) {
3424                         if (str[0] != '\0')
3425                                 new_timeout = atoi(str);
3426                 }
3427
3428                 if (new_timeout != 0) {
3429                         use_timeout = new_timeout * 1000;
3430                         fprintf(stdout, "Using new timeout value %d\n",
3431                                 use_timeout / 1000);
3432                 }
3433         }
3434
3435         /*
3436          * Keep this outside the if block below to silence any unused
3437          * variable warnings.
3438          */
3439         bzero(&fh, sizeof(fh));
3440
3441         /*
3442          * If we're in immediate mode, we've got to include the format
3443          * header
3444          */
3445         if (immediate != 0) {
3446                 fh.byte2 = FU_DLH_IMMED;
3447                 data_ptr = (u_int8_t *)&fh;
3448                 dxfer_len = sizeof(fh);
3449                 byte2 = FU_FMT_DATA;
3450         } else if (quiet == 0) {
3451                 fprintf(stdout, "Formatting...");
3452                 fflush(stdout);
3453         }
3454
3455         scsi_format_unit(&ccb->csio,
3456                          /* retries */ retry_count,
3457                          /* cbfcnp */ NULL,
3458                          /* tag_action */ MSG_SIMPLE_Q_TAG,
3459                          /* byte2 */ byte2,
3460                          /* ileave */ 0,
3461                          /* data_ptr */ data_ptr,
3462                          /* dxfer_len */ dxfer_len,
3463                          /* sense_len */ SSD_FULL_SIZE,
3464                          /* timeout */ use_timeout);
3465
3466         /* Disable freezing the device queue */
3467         ccb->ccb_h.flags |= CAM_DEV_QFRZDIS;
3468
3469         if (arglist & CAM_ARG_ERR_RECOVER)
3470                 ccb->ccb_h.flags |= CAM_PASS_ERR_RECOVER;
3471
3472         if (((retval = cam_send_ccb(device, ccb)) < 0)
3473          || ((immediate == 0)
3474            && ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP))) {
3475                 const char errstr[] = "error sending format command";
3476
3477                 if (retval < 0)
3478                         warn(errstr);
3479                 else
3480                         warnx(errstr);
3481
3482                 if (arglist & CAM_ARG_VERBOSE) {
3483                         cam_error_print(device, ccb, CAM_ESF_ALL,
3484                                         CAM_EPF_ALL, stderr);
3485                 }
3486                 error = 1;
3487                 goto scsiformat_bailout;
3488         }
3489
3490         /*
3491          * If we ran in non-immediate mode, we already checked for errors
3492          * above and printed out any necessary information.  If we're in
3493          * immediate mode, we need to loop through and get status
3494          * information periodically.
3495          */
3496         if (immediate == 0) {
3497                 if (quiet == 0) {
3498                         fprintf(stdout, "Format Complete\n");
3499                 }
3500                 goto scsiformat_bailout;
3501         }
3502
3503 doreport:
3504         do {
3505                 cam_status status;
3506
3507                 bzero(&(&ccb->ccb_h)[1],
3508                       sizeof(struct ccb_scsiio) - sizeof(struct ccb_hdr));
3509
3510                 /*
3511                  * There's really no need to do error recovery or
3512                  * retries here, since we're just going to sit in a
3513                  * loop and wait for the device to finish formatting.
3514                  */
3515                 scsi_test_unit_ready(&ccb->csio,
3516                                      /* retries */ 0,
3517                                      /* cbfcnp */ NULL,
3518                                      /* tag_action */ MSG_SIMPLE_Q_TAG,
3519                                      /* sense_len */ SSD_FULL_SIZE,
3520                                      /* timeout */ 5000);
3521
3522                 /* Disable freezing the device queue */
3523                 ccb->ccb_h.flags |= CAM_DEV_QFRZDIS;
3524
3525                 retval = cam_send_ccb(device, ccb);
3526
3527                 /*
3528                  * If we get an error from the ioctl, bail out.  SCSI
3529                  * errors are expected.
3530                  */
3531                 if (retval < 0) {
3532                         warn("error sending CAMIOCOMMAND ioctl");
3533                         if (arglist & CAM_ARG_VERBOSE) {
3534                                 cam_error_print(device, ccb, CAM_ESF_ALL,
3535                                                 CAM_EPF_ALL, stderr);
3536                         }
3537                         error = 1;
3538                         goto scsiformat_bailout;
3539                 }
3540
3541                 status = ccb->ccb_h.status & CAM_STATUS_MASK;
3542
3543                 if ((status != CAM_REQ_CMP)
3544                  && (status == CAM_SCSI_STATUS_ERROR)
3545                  && ((ccb->ccb_h.status & CAM_AUTOSNS_VALID) != 0)) {
3546                         struct scsi_sense_data *sense;
3547                         int error_code, sense_key, asc, ascq;
3548
3549                         sense = &ccb->csio.sense_data;
3550                         scsi_extract_sense(sense, &error_code, &sense_key,
3551                                            &asc, &ascq);
3552
3553                         /*
3554                          * According to the SCSI-2 and SCSI-3 specs, a
3555                          * drive that is in the middle of a format should
3556                          * return NOT READY with an ASC of "logical unit
3557                          * not ready, format in progress".  The sense key
3558                          * specific bytes will then be a progress indicator.
3559                          */
3560                         if ((sense_key == SSD_KEY_NOT_READY)
3561                          && (asc == 0x04) && (ascq == 0x04)) {
3562                                 if ((sense->extra_len >= 10)
3563                                  && ((sense->sense_key_spec[0] &
3564                                       SSD_SCS_VALID) != 0)
3565                                  && (quiet == 0)) {
3566                                         int val;
3567                                         u_int64_t percentage;
3568
3569                                         val = scsi_2btoul(
3570                                                 &sense->sense_key_spec[1]);
3571                                         percentage = 10000 * val;
3572
3573                                         fprintf(stdout,
3574                                                 "\rFormatting:  %ju.%02u %% "
3575                                                 "(%d/%d) done",
3576                                                 (uintmax_t)(percentage / 
3577                                                 (0x10000 * 100)),
3578                                                 (unsigned)((percentage / 
3579                                                 0x10000) % 100),
3580                                                 val, 0x10000);
3581                                         fflush(stdout);
3582                                 } else if ((quiet == 0)
3583                                         && (++num_warnings <= 1)) {
3584                                         warnx("Unexpected SCSI Sense Key "
3585                                               "Specific value returned "
3586                                               "during format:");
3587                                         scsi_sense_print(device, &ccb->csio,
3588                                                          stderr);
3589                                         warnx("Unable to print status "
3590                                               "information, but format will "
3591                                               "proceed.");
3592                                         warnx("will exit when format is "
3593                                               "complete");
3594                                 }
3595                                 sleep(1);
3596                         } else {
3597                                 warnx("Unexpected SCSI error during format");
3598                                 cam_error_print(device, ccb, CAM_ESF_ALL,
3599                                                 CAM_EPF_ALL, stderr);
3600                                 error = 1;
3601                                 goto scsiformat_bailout;
3602                         }
3603
3604                 } else if (status != CAM_REQ_CMP) {
3605                         warnx("Unexpected CAM status %#x", status);
3606                         if (arglist & CAM_ARG_VERBOSE)
3607                                 cam_error_print(device, ccb, CAM_ESF_ALL,
3608                                                 CAM_EPF_ALL, stderr);
3609                         error = 1;
3610                         goto scsiformat_bailout;
3611                 }
3612
3613         } while((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP);
3614
3615         if (quiet == 0)
3616                 fprintf(stdout, "\nFormat Complete\n");
3617
3618 scsiformat_bailout:
3619
3620         cam_freeccb(ccb);
3621
3622         return(error);
3623 }
3624
3625 static int
3626 scsireportluns(struct cam_device *device, int argc, char **argv,
3627                char *combinedopt, int retry_count, int timeout)
3628 {
3629         union ccb *ccb;
3630         int c, countonly, lunsonly;
3631         struct scsi_report_luns_data *lundata;
3632         int alloc_len;
3633         uint8_t report_type;
3634         uint32_t list_len, i, j;
3635         int retval;
3636
3637         retval = 0;
3638         lundata = NULL;
3639         report_type = RPL_REPORT_DEFAULT;
3640         ccb = cam_getccb(device);
3641
3642         if (ccb == NULL) {
3643                 warnx("%s: error allocating ccb", __func__);
3644                 return (1);
3645         }
3646
3647         bzero(&(&ccb->ccb_h)[1],
3648               sizeof(struct ccb_scsiio) - sizeof(struct ccb_hdr));
3649
3650         countonly = 0;
3651         lunsonly = 0;
3652
3653         while ((c = getopt(argc, argv, combinedopt)) != -1) {
3654                 switch (c) {
3655                 case 'c':
3656                         countonly++;
3657                         break;
3658                 case 'l':
3659                         lunsonly++;
3660                         break;
3661                 case 'r':
3662                         if (strcasecmp(optarg, "default") == 0)
3663                                 report_type = RPL_REPORT_DEFAULT;
3664                         else if (strcasecmp(optarg, "wellknown") == 0)
3665                                 report_type = RPL_REPORT_WELLKNOWN;
3666                         else if (strcasecmp(optarg, "all") == 0)
3667                                 report_type = RPL_REPORT_ALL;
3668                         else {
3669                                 warnx("%s: invalid report type \"%s\"",
3670                                       __func__, optarg);
3671                                 retval = 1;
3672                                 goto bailout;
3673                         }
3674                         break;
3675                 default:
3676                         break;
3677                 }
3678         }
3679
3680         if ((countonly != 0)
3681          && (lunsonly != 0)) {
3682                 warnx("%s: you can only specify one of -c or -l", __func__);
3683                 retval = 1;
3684                 goto bailout;
3685         }
3686         /*
3687          * According to SPC-4, the allocation length must be at least 16
3688          * bytes -- enough for the header and one LUN.
3689          */
3690         alloc_len = sizeof(*lundata) + 8;
3691
3692 retry:
3693
3694         lundata = malloc(alloc_len);
3695
3696         if (lundata == NULL) {
3697                 warn("%s: error mallocing %d bytes", __func__, alloc_len);
3698                 retval = 1;
3699                 goto bailout;
3700         }
3701
3702         scsi_report_luns(&ccb->csio,
3703                          /*retries*/ retry_count,
3704                          /*cbfcnp*/ NULL,
3705                          /*tag_action*/ MSG_SIMPLE_Q_TAG,
3706                          /*select_report*/ report_type,
3707                          /*rpl_buf*/ lundata,
3708                          /*alloc_len*/ alloc_len,
3709                          /*sense_len*/ SSD_FULL_SIZE,
3710                          /*timeout*/ timeout ? timeout : 5000);
3711
3712         /* Disable freezing the device queue */
3713         ccb->ccb_h.flags |= CAM_DEV_QFRZDIS;
3714
3715         if (arglist & CAM_ARG_ERR_RECOVER)
3716                 ccb->ccb_h.flags |= CAM_PASS_ERR_RECOVER;
3717
3718         if (cam_send_ccb(device, ccb) < 0) {
3719                 warn("error sending REPORT LUNS command");
3720
3721                 if (arglist & CAM_ARG_VERBOSE)
3722                         cam_error_print(device, ccb, CAM_ESF_ALL,
3723                                         CAM_EPF_ALL, stderr);
3724
3725                 retval = 1;
3726                 goto bailout;
3727         }
3728
3729         if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
3730                 cam_error_print(device, ccb, CAM_ESF_ALL, CAM_EPF_ALL, stderr);
3731                 retval = 1;
3732                 goto bailout;
3733         }
3734
3735
3736         list_len = scsi_4btoul(lundata->length);
3737
3738         /*
3739          * If we need to list the LUNs, and our allocation
3740          * length was too short, reallocate and retry.
3741          */
3742         if ((countonly == 0)
3743          && (list_len > (alloc_len - sizeof(*lundata)))) {
3744                 alloc_len = list_len + sizeof(*lundata);
3745                 free(lundata);
3746                 goto retry;
3747         }
3748
3749         if (lunsonly == 0)
3750                 fprintf(stdout, "%u LUN%s found\n", list_len / 8,
3751                         ((list_len / 8) > 1) ? "s" : "");
3752
3753         if (countonly != 0)
3754                 goto bailout;
3755
3756         for (i = 0; i < (list_len / 8); i++) {
3757                 int no_more;
3758
3759                 no_more = 0;
3760                 for (j = 0; j < sizeof(lundata->luns[i].lundata); j += 2) {
3761                         if (j != 0)
3762                                 fprintf(stdout, ",");
3763                         switch (lundata->luns[i].lundata[j] &
3764                                 RPL_LUNDATA_ATYP_MASK) {
3765                         case RPL_LUNDATA_ATYP_PERIPH:
3766                                 if ((lundata->luns[i].lundata[j] &
3767                                     RPL_LUNDATA_PERIPH_BUS_MASK) != 0)
3768                                         fprintf(stdout, "%d:", 
3769                                                 lundata->luns[i].lundata[j] &
3770                                                 RPL_LUNDATA_PERIPH_BUS_MASK);
3771                                 else if ((j == 0)
3772                                       && ((lundata->luns[i].lundata[j+2] &
3773                                           RPL_LUNDATA_PERIPH_BUS_MASK) == 0))
3774                                         no_more = 1;
3775
3776                                 fprintf(stdout, "%d",
3777                                         lundata->luns[i].lundata[j+1]);
3778                                 break;
3779                         case RPL_LUNDATA_ATYP_FLAT: {
3780                                 uint8_t tmplun[2];
3781                                 tmplun[0] = lundata->luns[i].lundata[j] &
3782                                         RPL_LUNDATA_FLAT_LUN_MASK;
3783                                 tmplun[1] = lundata->luns[i].lundata[j+1];
3784
3785                                 fprintf(stdout, "%d", scsi_2btoul(tmplun));
3786                                 no_more = 1;
3787                                 break;
3788                         }
3789                         case RPL_LUNDATA_ATYP_LUN:
3790                                 fprintf(stdout, "%d:%d:%d",
3791                                         (lundata->luns[i].lundata[j+1] &
3792                                         RPL_LUNDATA_LUN_BUS_MASK) >> 5,
3793                                         lundata->luns[i].lundata[j] &
3794                                         RPL_LUNDATA_LUN_TARG_MASK,
3795                                         lundata->luns[i].lundata[j+1] &
3796                                         RPL_LUNDATA_LUN_LUN_MASK);
3797                                 break;
3798                         case RPL_LUNDATA_ATYP_EXTLUN: {
3799                                 int field_len, field_len_code, eam_code;
3800
3801                                 eam_code = lundata->luns[i].lundata[j] &
3802                                         RPL_LUNDATA_EXT_EAM_MASK;
3803                                 field_len_code = (lundata->luns[i].lundata[j] &
3804                                         RPL_LUNDATA_EXT_LEN_MASK) >> 4;
3805                                 field_len = field_len_code * 2;
3806                 
3807                                 if ((eam_code == RPL_LUNDATA_EXT_EAM_WK)
3808                                  && (field_len_code == 0x00)) {
3809                                         fprintf(stdout, "%d",
3810                                                 lundata->luns[i].lundata[j+1]);
3811                                 } else if ((eam_code ==
3812                                             RPL_LUNDATA_EXT_EAM_NOT_SPEC)
3813                                         && (field_len_code == 0x03)) {
3814                                         uint8_t tmp_lun[8];
3815
3816                                         /*
3817                                          * This format takes up all 8 bytes.
3818                                          * If we aren't starting at offset 0,
3819                                          * that's a bug.
3820                                          */
3821                                         if (j != 0) {
3822                                                 fprintf(stdout, "Invalid "
3823                                                         "offset %d for "
3824                                                         "Extended LUN not "
3825                                                         "specified format", j);
3826                                                 no_more = 1;
3827                                                 break;
3828                                         }
3829                                         bzero(tmp_lun, sizeof(tmp_lun));
3830                                         bcopy(&lundata->luns[i].lundata[j+1],
3831                                               &tmp_lun[1], sizeof(tmp_lun) - 1);
3832                                         fprintf(stdout, "%#jx",
3833                                                (intmax_t)scsi_8btou64(tmp_lun));
3834                                         no_more = 1;
3835                                 } else {
3836                                         fprintf(stderr, "Unknown Extended LUN"
3837                                                 "Address method %#x, length "
3838                                                 "code %#x", eam_code,
3839                                                 field_len_code);
3840                                         no_more = 1;
3841                                 }
3842                                 break;
3843                         }
3844                         default:
3845                                 fprintf(stderr, "Unknown LUN address method "
3846                                         "%#x\n", lundata->luns[i].lundata[0] &
3847                                         RPL_LUNDATA_ATYP_MASK);
3848                                 break;
3849                         }
3850                         /*
3851                          * For the flat addressing method, there are no
3852                          * other levels after it.
3853                          */
3854                         if (no_more != 0)
3855                                 break;
3856                 }
3857                 fprintf(stdout, "\n");
3858         }
3859
3860 bailout:
3861
3862         cam_freeccb(ccb);
3863
3864         free(lundata);
3865
3866         return (retval);
3867 }
3868
3869 static int
3870 scsireadcapacity(struct cam_device *device, int argc, char **argv,
3871                  char *combinedopt, int retry_count, int timeout)
3872 {
3873         union ccb *ccb;
3874         int blocksizeonly, humanize, numblocks, quiet, sizeonly, baseten;
3875         struct scsi_read_capacity_data rcap;
3876         struct scsi_read_capacity_data_long rcaplong;
3877         uint64_t maxsector;
3878         uint32_t block_len;
3879         int retval;
3880         int c;
3881
3882         blocksizeonly = 0;
3883         humanize = 0;
3884         numblocks = 0;
3885         quiet = 0;
3886         sizeonly = 0;
3887         baseten = 0;
3888         retval = 0;
3889
3890         ccb = cam_getccb(device);
3891
3892         if (ccb == NULL) {
3893                 warnx("%s: error allocating ccb", __func__);
3894                 return (1);
3895         }
3896
3897         bzero(&(&ccb->ccb_h)[1],
3898               sizeof(struct ccb_scsiio) - sizeof(struct ccb_hdr));
3899
3900         while ((c = getopt(argc, argv, combinedopt)) != -1) {
3901                 switch (c) {
3902                 case 'b':
3903                         blocksizeonly++;
3904                         break;
3905                 case 'h':
3906                         humanize++;
3907                         baseten = 0;
3908                         break;
3909                 case 'H':
3910                         humanize++;
3911                         baseten++;
3912                         break;
3913                 case 'N':
3914                         numblocks++;
3915                         break;
3916                 case 'q':
3917                         quiet++;
3918                         break;
3919                 case 's':
3920                         sizeonly++;
3921                         break;
3922                 default:
3923                         break;
3924                 }
3925         }
3926
3927         if ((blocksizeonly != 0)
3928          && (numblocks != 0)) {
3929                 warnx("%s: you can only specify one of -b or -N", __func__);
3930                 retval = 1;
3931                 goto bailout;
3932         }
3933
3934         if ((blocksizeonly != 0)
3935          && (sizeonly != 0)) {
3936                 warnx("%s: you can only specify one of -b or -s", __func__);
3937                 retval = 1;
3938                 goto bailout;
3939         }
3940
3941         if ((humanize != 0)
3942          && (quiet != 0)) {
3943                 warnx("%s: you can only specify one of -h/-H or -q", __func__);
3944                 retval = 1;
3945                 goto bailout;
3946         }
3947
3948         if ((humanize != 0)
3949          && (blocksizeonly != 0)) {
3950                 warnx("%s: you can only specify one of -h/-H or -b", __func__);
3951                 retval = 1;
3952                 goto bailout;
3953         }
3954
3955         scsi_read_capacity(&ccb->csio,
3956                            /*retries*/ retry_count,
3957                            /*cbfcnp*/ NULL,
3958                            /*tag_action*/ MSG_SIMPLE_Q_TAG,
3959                            &rcap,
3960                            SSD_FULL_SIZE,
3961                            /*timeout*/ timeout ? timeout : 5000);
3962
3963         /* Disable freezing the device queue */
3964         ccb->ccb_h.flags |= CAM_DEV_QFRZDIS;
3965
3966         if (arglist & CAM_ARG_ERR_RECOVER)
3967                 ccb->ccb_h.flags |= CAM_PASS_ERR_RECOVER;
3968
3969         if (cam_send_ccb(device, ccb) < 0) {
3970                 warn("error sending READ CAPACITY command");
3971
3972                 if (arglist & CAM_ARG_VERBOSE)
3973                         cam_error_print(device, ccb, CAM_ESF_ALL,
3974                                         CAM_EPF_ALL, stderr);
3975
3976                 retval = 1;
3977                 goto bailout;
3978         }
3979
3980         if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
3981                 cam_error_print(device, ccb, CAM_ESF_ALL, CAM_EPF_ALL, stderr);
3982                 retval = 1;
3983                 goto bailout;
3984         }
3985
3986         maxsector = scsi_4btoul(rcap.addr);
3987         block_len = scsi_4btoul(rcap.length);
3988
3989         /*
3990          * A last block of 2^32-1 means that the true capacity is over 2TB,
3991          * and we need to issue the long READ CAPACITY to get the real
3992          * capacity.  Otherwise, we're all set.
3993          */
3994         if (maxsector != 0xffffffff)
3995                 goto do_print;
3996
3997         scsi_read_capacity_16(&ccb->csio,
3998                               /*retries*/ retry_count,
3999                               /*cbfcnp*/ NULL,
4000                               /*tag_action*/ MSG_SIMPLE_Q_TAG,
4001                               /*lba*/ 0,
4002                               /*reladdr*/ 0,
4003                               /*pmi*/ 0,
4004                               &rcaplong,
4005                               /*sense_len*/ SSD_FULL_SIZE,
4006                               /*timeout*/ timeout ? timeout : 5000);
4007
4008         /* Disable freezing the device queue */
4009         ccb->ccb_h.flags |= CAM_DEV_QFRZDIS;
4010
4011         if (arglist & CAM_ARG_ERR_RECOVER)
4012                 ccb->ccb_h.flags |= CAM_PASS_ERR_RECOVER;
4013
4014         if (cam_send_ccb(device, ccb) < 0) {
4015                 warn("error sending READ CAPACITY (16) command");
4016
4017                 if (arglist & CAM_ARG_VERBOSE)
4018                         cam_error_print(device, ccb, CAM_ESF_ALL,
4019                                         CAM_EPF_ALL, stderr);
4020
4021                 retval = 1;
4022                 goto bailout;
4023         }
4024
4025         if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
4026                 cam_error_print(device, ccb, CAM_ESF_ALL, CAM_EPF_ALL, stderr);
4027                 retval = 1;
4028                 goto bailout;
4029         }
4030
4031         maxsector = scsi_8btou64(rcaplong.addr);
4032         block_len = scsi_4btoul(rcaplong.length);
4033
4034 do_print:
4035         if (blocksizeonly == 0) {
4036                 /*
4037                  * Humanize implies !quiet, and also implies numblocks.
4038                  */
4039                 if (humanize != 0) {
4040                         char tmpstr[6];
4041                         int64_t tmpbytes;
4042                         int ret;
4043
4044                         tmpbytes = (maxsector + 1) * block_len;
4045                         ret = humanize_number(tmpstr, sizeof(tmpstr),
4046                                               tmpbytes, "", HN_AUTOSCALE,
4047                                               HN_B | HN_DECIMAL |
4048                                               ((baseten != 0) ?
4049                                               HN_DIVISOR_1000 : 0));
4050                         if (ret == -1) {
4051                                 warnx("%s: humanize_number failed!", __func__);
4052                                 retval = 1;
4053                                 goto bailout;
4054                         }
4055                         fprintf(stdout, "Device Size: %s%s", tmpstr,
4056                                 (sizeonly == 0) ?  ", " : "\n");
4057                 } else if (numblocks != 0) {
4058                         fprintf(stdout, "%s%ju%s", (quiet == 0) ?
4059                                 "Blocks: " : "", (uintmax_t)maxsector + 1,
4060                                 (sizeonly == 0) ? ", " : "\n");
4061                 } else {
4062                         fprintf(stdout, "%s%ju%s", (quiet == 0) ?
4063                                 "Last Block: " : "", (uintmax_t)maxsector,
4064                                 (sizeonly == 0) ? ", " : "\n");
4065                 }
4066         }
4067         if (sizeonly == 0)
4068                 fprintf(stdout, "%s%u%s\n", (quiet == 0) ?
4069                         "Block Length: " : "", block_len, (quiet == 0) ?
4070                         " bytes" : "");
4071 bailout:
4072         cam_freeccb(ccb);
4073
4074         return (retval);
4075 }
4076
4077 #endif /* MINIMALISTIC */
4078
4079 void 
4080 usage(int verbose)
4081 {
4082         fprintf(verbose ? stdout : stderr,
4083 "usage:  camcontrol <command>  [device id][generic args][command args]\n"
4084 "        camcontrol devlist    [-v]\n"
4085 #ifndef MINIMALISTIC
4086 "        camcontrol periphlist [dev_id][-n dev_name] [-u unit]\n"
4087 "        camcontrol tur        [dev_id][generic args]\n"
4088 "        camcontrol inquiry    [dev_id][generic args] [-D] [-S] [-R]\n"
4089 "        camcontrol identify   [dev_id][generic args]\n"
4090 "        camcontrol reportluns [dev_id][generic args] [-c] [-l] [-r report]\n"
4091 "        camcontrol readcap    [dev_id][generic args] [-b] [-h] [-H] [-N]\n"
4092 "                              [-q] [-s]\n"
4093 "        camcontrol start      [dev_id][generic args]\n"
4094 "        camcontrol stop       [dev_id][generic args]\n"
4095 "        camcontrol load       [dev_id][generic args]\n"
4096 "        camcontrol eject      [dev_id][generic args]\n"
4097 #endif /* MINIMALISTIC */
4098 "        camcontrol rescan     <all | bus[:target:lun]>\n"
4099 "        camcontrol reset      <all | bus[:target:lun]>\n"
4100 #ifndef MINIMALISTIC
4101 "        camcontrol defects    [dev_id][generic args] <-f format> [-P][-G]\n"
4102 "        camcontrol modepage   [dev_id][generic args] <-m page | -l>\n"
4103 "                              [-P pagectl][-e | -b][-d]\n"
4104 "        camcontrol cmd        [dev_id][generic args]\n"
4105 "                              <-a cmd [args] | -c cmd [args]>\n"
4106 "                              [-i len fmt|-o len fmt [args]] [-r fmt]\n"
4107 "        camcontrol debug      [-I][-P][-T][-S][-X][-c]\n"
4108 "                              <all|bus[:target[:lun]]|off>\n"
4109 "        camcontrol tags       [dev_id][generic args] [-N tags] [-q] [-v]\n"
4110 "        camcontrol negotiate  [dev_id][generic args] [-a][-c]\n"
4111 "                              [-D <enable|disable>][-O offset][-q]\n"
4112 "                              [-R syncrate][-v][-T <enable|disable>]\n"
4113 "                              [-U][-W bus_width]\n"
4114 "        camcontrol format     [dev_id][generic args][-q][-r][-w][-y]\n"
4115 #endif /* MINIMALISTIC */
4116 "        camcontrol help\n");
4117         if (!verbose)
4118                 return;
4119 #ifndef MINIMALISTIC
4120         fprintf(stdout,
4121 "Specify one of the following options:\n"
4122 "devlist     list all CAM devices\n"
4123 "periphlist  list all CAM peripheral drivers attached to a device\n"
4124 "tur         send a test unit ready to the named device\n"
4125 "inquiry     send a SCSI inquiry command to the named device\n"
4126 "identify    send a ATA identify command to the named device\n"
4127 "reportluns  send a SCSI report luns command to the device\n"
4128 "readcap     send a SCSI read capacity command to the device\n"
4129 "start       send a Start Unit command to the device\n"
4130 "stop        send a Stop Unit command to the device\n"
4131 "load        send a Start Unit command to the device with the load bit set\n"
4132 "eject       send a Stop Unit command to the device with the eject bit set\n"
4133 "rescan      rescan all busses, the given bus, or bus:target:lun\n"
4134 "reset       reset all busses, the given bus, or bus:target:lun\n"
4135 "defects     read the defect list of the specified device\n"
4136 "modepage    display or edit (-e) the given mode page\n"
4137 "cmd         send the given scsi command, may need -i or -o as well\n"
4138 "debug       turn debugging on/off for a bus, target, or lun, or all devices\n"
4139 "tags        report or set the number of transaction slots for a device\n"
4140 "negotiate   report or set device negotiation parameters\n"
4141 "format      send the SCSI FORMAT UNIT command to the named device\n"
4142 "help        this message\n"
4143 "Device Identifiers:\n"
4144 "bus:target        specify the bus and target, lun defaults to 0\n"
4145 "bus:target:lun    specify the bus, target and lun\n"
4146 "deviceUNIT        specify the device name, like \"da4\" or \"cd2\"\n"
4147 "Generic arguments:\n"
4148 "-v                be verbose, print out sense information\n"
4149 "-t timeout        command timeout in seconds, overrides default timeout\n"
4150 "-n dev_name       specify device name, e.g. \"da\", \"cd\"\n"
4151 "-u unit           specify unit number, e.g. \"0\", \"5\"\n"
4152 "-E                have the kernel attempt to perform SCSI error recovery\n"
4153 "-C count          specify the SCSI command retry count (needs -E to work)\n"
4154 "modepage arguments:\n"
4155 "-l                list all available mode pages\n"
4156 "-m page           specify the mode page to view or edit\n"
4157 "-e                edit the specified mode page\n"
4158 "-b                force view to binary mode\n"
4159 "-d                disable block descriptors for mode sense\n"
4160 "-P pgctl          page control field 0-3\n"
4161 "defects arguments:\n"
4162 "-f format         specify defect list format (block, bfi or phys)\n"
4163 "-G                get the grown defect list\n"
4164 "-P                get the permanant defect list\n"
4165 "inquiry arguments:\n"
4166 "-D                get the standard inquiry data\n"
4167 "-S                get the serial number\n"
4168 "-R                get the transfer rate, etc.\n"
4169 "reportluns arguments:\n"
4170 "-c                only report a count of available LUNs\n"
4171 "-l                only print out luns, and not a count\n"
4172 "-r <reporttype>   specify \"default\", \"wellknown\" or \"all\"\n"
4173 "readcap arguments\n"
4174 "-b                only report the blocksize\n"
4175 "-h                human readable device size, base 2\n"
4176 "-H                human readable device size, base 10\n"
4177 "-N                print the number of blocks instead of last block\n"
4178 "-q                quiet, print numbers only\n"
4179 "-s                only report the last block/device size\n"
4180 "cmd arguments:\n"
4181 "-c cdb [args]     specify the SCSI CDB\n"
4182 "-i len fmt        specify input data and input data format\n"
4183 "-o len fmt [args] specify output data and output data fmt\n"
4184 "debug arguments:\n"
4185 "-I                CAM_DEBUG_INFO -- scsi commands, errors, data\n"
4186 "-T                CAM_DEBUG_TRACE -- routine flow tracking\n"
4187 "-S                CAM_DEBUG_SUBTRACE -- internal routine command flow\n"
4188 "-c                CAM_DEBUG_CDB -- print out SCSI CDBs only\n"
4189 "tags arguments:\n"
4190 "-N tags           specify the number of tags to use for this device\n"
4191 "-q                be quiet, don't report the number of tags\n"
4192 "-v                report a number of tag-related parameters\n"
4193 "negotiate arguments:\n"
4194 "-a                send a test unit ready after negotiation\n"
4195 "-c                report/set current negotiation settings\n"
4196 "-D <arg>          \"enable\" or \"disable\" disconnection\n"
4197 "-O offset         set command delay offset\n"
4198 "-q                be quiet, don't report anything\n"
4199 "-R syncrate       synchronization rate in MHz\n"
4200 "-T <arg>          \"enable\" or \"disable\" tagged queueing\n"
4201 "-U                report/set user negotiation settings\n"
4202 "-W bus_width      set the bus width in bits (8, 16 or 32)\n"
4203 "-v                also print a Path Inquiry CCB for the controller\n"
4204 "format arguments:\n"
4205 "-q                be quiet, don't print status messages\n"
4206 "-r                run in report only mode\n"
4207 "-w                don't send immediate format command\n"
4208 "-y                don't ask any questions\n");
4209 #endif /* MINIMALISTIC */
4210 }
4211
4212 int 
4213 main(int argc, char **argv)
4214 {
4215         int c;
4216         char *device = NULL;
4217         int unit = 0;
4218         struct cam_device *cam_dev = NULL;
4219         int timeout = 0, retry_count = 1;
4220         camcontrol_optret optreturn;
4221         char *tstr;
4222         const char *mainopt = "C:En:t:u:v";
4223         const char *subopt = NULL;
4224         char combinedopt[256];
4225         int error = 0, optstart = 2;
4226         int devopen = 1;
4227 #ifndef MINIMALISTIC
4228         int bus, target, lun;
4229 #endif /* MINIMALISTIC */
4230
4231         cmdlist = CAM_CMD_NONE;
4232         arglist = CAM_ARG_NONE;
4233
4234         if (argc < 2) {
4235                 usage(0);
4236                 exit(1);
4237         }
4238
4239         /*
4240          * Get the base option.
4241          */
4242         optreturn = getoption(argv[1], &cmdlist, &arglist, &subopt);
4243
4244         if (optreturn == CC_OR_AMBIGUOUS) {
4245                 warnx("ambiguous option %s", argv[1]);
4246                 usage(0);
4247                 exit(1);
4248         } else if (optreturn == CC_OR_NOT_FOUND) {
4249                 warnx("option %s not found", argv[1]);
4250                 usage(0);
4251                 exit(1);
4252         }
4253
4254         /*
4255          * Ahh, getopt(3) is a pain.
4256          *
4257          * This is a gross hack.  There really aren't many other good
4258          * options (excuse the pun) for parsing options in a situation like
4259          * this.  getopt is kinda braindead, so you end up having to run
4260          * through the options twice, and give each invocation of getopt
4261          * the option string for the other invocation.
4262          * 
4263          * You would think that you could just have two groups of options.
4264          * The first group would get parsed by the first invocation of
4265          * getopt, and the second group would get parsed by the second
4266          * invocation of getopt.  It doesn't quite work out that way.  When
4267          * the first invocation of getopt finishes, it leaves optind pointing
4268          * to the argument _after_ the first argument in the second group.
4269          * So when the second invocation of getopt comes around, it doesn't
4270          * recognize the first argument it gets and then bails out.
4271          * 
4272          * A nice alternative would be to have a flag for getopt that says
4273          * "just keep parsing arguments even when you encounter an unknown
4274          * argument", but there isn't one.  So there's no real clean way to
4275          * easily parse two sets of arguments without having one invocation
4276          * of getopt know about the other.
4277          * 
4278          * Without this hack, the first invocation of getopt would work as
4279          * long as the generic arguments are first, but the second invocation
4280          * (in the subfunction) would fail in one of two ways.  In the case
4281          * where you don't set optreset, it would fail because optind may be
4282          * pointing to the argument after the one it should be pointing at.
4283          * In the case where you do set optreset, and reset optind, it would
4284          * fail because getopt would run into the first set of options, which
4285          * it doesn't understand.
4286          *
4287          * All of this would "sort of" work if you could somehow figure out
4288          * whether optind had been incremented one option too far.  The
4289          * mechanics of that, however, are more daunting than just giving
4290          * both invocations all of the expect options for either invocation.
4291          * 
4292          * Needless to say, I wouldn't mind if someone invented a better
4293          * (non-GPL!) command line parsing interface than getopt.  I
4294          * wouldn't mind if someone added more knobs to getopt to make it
4295          * work better.  Who knows, I may talk myself into doing it someday,
4296          * if the standards weenies let me.  As it is, it just leads to
4297          * hackery like this and causes people to avoid it in some cases.
4298          * 
4299          * KDM, September 8th, 1998
4300          */
4301         if (subopt != NULL)
4302                 sprintf(combinedopt, "%s%s", mainopt, subopt);
4303         else
4304                 sprintf(combinedopt, "%s", mainopt);
4305
4306         /*
4307          * For these options we do not parse optional device arguments and
4308          * we do not open a passthrough device.
4309          */
4310         if ((cmdlist == CAM_CMD_RESCAN)
4311          || (cmdlist == CAM_CMD_RESET)
4312          || (cmdlist == CAM_CMD_DEVTREE)
4313          || (cmdlist == CAM_CMD_USAGE)
4314          || (cmdlist == CAM_CMD_DEBUG))
4315                 devopen = 0;
4316
4317 #ifndef MINIMALISTIC
4318         if ((devopen == 1)
4319          && (argc > 2 && argv[2][0] != '-')) {
4320                 char name[30];
4321                 int rv;
4322
4323                 /*
4324                  * First catch people who try to do things like:
4325                  * camcontrol tur /dev/da0 
4326                  * camcontrol doesn't take device nodes as arguments.
4327                  */
4328                 if (argv[2][0] == '/') {
4329                         warnx("%s is not a valid device identifier", argv[2]);
4330                         errx(1, "please read the camcontrol(8) man page");
4331                 } else if (isdigit(argv[2][0])) {
4332                         /* device specified as bus:target[:lun] */
4333                         rv = parse_btl(argv[2], &bus, &target, &lun, &arglist);
4334                         if (rv < 2)
4335                                 errx(1, "numeric device specification must "
4336                                      "be either bus:target, or "
4337                                      "bus:target:lun");
4338                         /* default to 0 if lun was not specified */
4339                         if ((arglist & CAM_ARG_LUN) == 0) {
4340                                 lun = 0;
4341                                 arglist |= CAM_ARG_LUN;
4342                         }
4343                         optstart++;
4344                 } else {
4345                         if (cam_get_device(argv[2], name, sizeof name, &unit)
4346                             == -1)
4347                                 errx(1, "%s", cam_errbuf);
4348                         device = strdup(name);
4349                         arglist |= CAM_ARG_DEVICE | CAM_ARG_UNIT;
4350                         optstart++;
4351                 }
4352         }
4353 #endif /* MINIMALISTIC */
4354         /*
4355          * Start getopt processing at argv[2/3], since we've already
4356          * accepted argv[1..2] as the command name, and as a possible
4357          * device name.
4358          */
4359         optind = optstart;
4360
4361         /*
4362          * Now we run through the argument list looking for generic
4363          * options, and ignoring options that possibly belong to
4364          * subfunctions.
4365          */
4366         while ((c = getopt(argc, argv, combinedopt))!= -1){
4367                 switch(c) {
4368                         case 'C':
4369                                 retry_count = strtol(optarg, NULL, 0);
4370                                 if (retry_count < 0)
4371                                         errx(1, "retry count %d is < 0",
4372                                              retry_count);
4373                                 arglist |= CAM_ARG_RETRIES;
4374                                 break;
4375                         case 'E':
4376                                 arglist |= CAM_ARG_ERR_RECOVER;
4377                                 break;
4378                         case 'n':
4379                                 arglist |= CAM_ARG_DEVICE;
4380                                 tstr = optarg;
4381                                 while (isspace(*tstr) && (*tstr != '\0'))
4382                                         tstr++;
4383                                 device = (char *)strdup(tstr);
4384                                 break;
4385                         case 't':
4386                                 timeout = strtol(optarg, NULL, 0);
4387                                 if (timeout < 0)
4388                                         errx(1, "invalid timeout %d", timeout);
4389                                 /* Convert the timeout from seconds to ms */
4390                                 timeout *= 1000;
4391                                 arglist |= CAM_ARG_TIMEOUT;
4392                                 break;
4393                         case 'u':
4394                                 arglist |= CAM_ARG_UNIT;
4395                                 unit = strtol(optarg, NULL, 0);
4396                                 break;
4397                         case 'v':
4398                                 arglist |= CAM_ARG_VERBOSE;
4399                                 break;
4400                         default:
4401                                 break;
4402                 }
4403         }
4404
4405 #ifndef MINIMALISTIC
4406         /*
4407          * For most commands we'll want to open the passthrough device
4408          * associated with the specified device.  In the case of the rescan
4409          * commands, we don't use a passthrough device at all, just the
4410          * transport layer device.
4411          */
4412         if (devopen == 1) {
4413                 if (((arglist & (CAM_ARG_BUS|CAM_ARG_TARGET)) == 0)
4414                  && (((arglist & CAM_ARG_DEVICE) == 0)
4415                   || ((arglist & CAM_ARG_UNIT) == 0))) {
4416                         errx(1, "subcommand \"%s\" requires a valid device "
4417                              "identifier", argv[1]);
4418                 }
4419
4420                 if ((cam_dev = ((arglist & (CAM_ARG_BUS | CAM_ARG_TARGET))?
4421                                 cam_open_btl(bus, target, lun, O_RDWR, NULL) :
4422                                 cam_open_spec_device(device,unit,O_RDWR,NULL)))
4423                      == NULL)
4424                         errx(1,"%s", cam_errbuf);
4425         }
4426 #endif /* MINIMALISTIC */
4427
4428         /*
4429          * Reset optind to 2, and reset getopt, so these routines can parse
4430          * the arguments again.
4431          */
4432         optind = optstart;
4433         optreset = 1;
4434
4435         switch(cmdlist) {
4436 #ifndef MINIMALISTIC
4437                 case CAM_CMD_DEVLIST:
4438                         error = getdevlist(cam_dev);
4439                         break;
4440 #endif /* MINIMALISTIC */
4441                 case CAM_CMD_DEVTREE:
4442                         error = getdevtree();
4443                         break;
4444 #ifndef MINIMALISTIC
4445                 case CAM_CMD_TUR:
4446                         error = testunitready(cam_dev, retry_count, timeout, 0);
4447                         break;
4448                 case CAM_CMD_INQUIRY:
4449                         error = scsidoinquiry(cam_dev, argc, argv, combinedopt,
4450                                               retry_count, timeout);
4451                         break;
4452                 case CAM_CMD_IDENTIFY:
4453                         error = ataidentify(cam_dev, retry_count, timeout);
4454                         break;
4455                 case CAM_CMD_STARTSTOP:
4456                         error = scsistart(cam_dev, arglist & CAM_ARG_START_UNIT,
4457                                           arglist & CAM_ARG_EJECT, retry_count,
4458                                           timeout);
4459                         break;
4460 #endif /* MINIMALISTIC */
4461                 case CAM_CMD_RESCAN:
4462                         error = dorescan_or_reset(argc, argv, 1);
4463                         break;
4464                 case CAM_CMD_RESET:
4465                         error = dorescan_or_reset(argc, argv, 0);
4466                         break;
4467 #ifndef MINIMALISTIC
4468                 case CAM_CMD_READ_DEFECTS:
4469                         error = readdefects(cam_dev, argc, argv, combinedopt,
4470                                             retry_count, timeout);
4471                         break;
4472                 case CAM_CMD_MODE_PAGE:
4473                         modepage(cam_dev, argc, argv, combinedopt,
4474                                  retry_count, timeout);
4475                         break;
4476                 case CAM_CMD_SCSI_CMD:
4477                         error = scsicmd(cam_dev, argc, argv, combinedopt,
4478                                         retry_count, timeout);
4479                         break;
4480                 case CAM_CMD_DEBUG:
4481                         error = camdebug(argc, argv, combinedopt);
4482                         break;
4483                 case CAM_CMD_TAG:
4484                         error = tagcontrol(cam_dev, argc, argv, combinedopt);
4485                         break;
4486                 case CAM_CMD_RATE:
4487                         error = ratecontrol(cam_dev, retry_count, timeout,
4488                                             argc, argv, combinedopt);
4489                         break;
4490                 case CAM_CMD_FORMAT:
4491                         error = scsiformat(cam_dev, argc, argv,
4492                                            combinedopt, retry_count, timeout);
4493                         break;
4494                 case CAM_CMD_REPORTLUNS:
4495                         error = scsireportluns(cam_dev, argc, argv,
4496                                                combinedopt, retry_count,
4497                                                timeout);
4498                         break;
4499                 case CAM_CMD_READCAP:
4500                         error = scsireadcapacity(cam_dev, argc, argv,
4501                                                  combinedopt, retry_count,
4502                                                  timeout);
4503                         break;
4504 #endif /* MINIMALISTIC */
4505                 case CAM_CMD_USAGE:
4506                         usage(1);
4507                         break;
4508                 default:
4509                         usage(0);
4510                         error = 1;
4511                         break;
4512         }
4513
4514         if (cam_dev != NULL)
4515                 cam_close_device(cam_dev);
4516
4517         exit(error);
4518 }