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