• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2014-2022 Douglas Gilbert.
3  * All rights reserved.
4  * Use of this source code is governed by a BSD-style
5  * license that can be found in the BSD_LICENSE file.
6  *
7  * SPDX-License-Identifier: BSD-2-Clause
8  */
9 
10 #include <unistd.h>
11 #include <fcntl.h>
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <stdarg.h>
15 #include <stdbool.h>
16 #include <string.h>
17 #include <ctype.h>
18 #include <errno.h>
19 #include <getopt.h>
20 #define __STDC_FORMAT_MACROS 1
21 #include <inttypes.h>
22 
23 #ifdef HAVE_CONFIG_H
24 #include "config.h"
25 #endif
26 
27 #include "sg_lib.h"
28 #include "sg_lib_data.h"
29 #include "sg_pt.h"
30 #include "sg_cmds_basic.h"
31 #include "sg_unaligned.h"
32 #include "sg_pr2serr.h"
33 
34 /* A utility program originally written for the Linux OS SCSI subsystem.
35  *
36  *
37  * This program issues either a SCSI ZONE ACTIVATE command or a ZONE QUERY
38  * command to the given SCSI device. Based on zbc2r12.pdf .
39  */
40 
41 static const char * version_str = "1.04 20220729";
42 
43 #define SG_ZBC_IN_CMDLEN 16
44 #define Z_ACTIVATE_SA 0x8
45 #define Z_QUERY_SA 0x9
46 
47 #define SENSE_BUFF_LEN 64       /* Arbitrary, could be larger */
48 #define DEF_PT_TIMEOUT 60       /* 60 seconds */
49 #define DEF_ALLOC_LEN 8192
50 #define Z_ACT_DESC_LEN 32
51 #define MAX_ACT_QUERY_BUFF_LEN (16 * 1024 * 1024)
52 
53 struct opts_t {
54     bool do_all;
55     bool do_activate;
56     bool do_force;
57     bool do_query;
58     bool do_raw;
59     bool maxlen_given;
60     uint8_t other_zdid;
61     uint16_t max_alloc;
62     uint16_t num_zones;
63     int hex_count;
64     int vb;
65     uint64_t st_lba;    /* Zone ID */
66     const char * device_name;
67     const char * inhex_fn;
68 };
69 
70 static struct option long_options[] = {
71         {"activate", no_argument, 0, 'A'},
72         {"all", no_argument, 0, 'a'},
73         {"force", no_argument, 0, 'f'},
74         {"help", no_argument, 0, 'h'},
75         {"hex", no_argument, 0, 'H'},
76         {"in", required_argument, 0, 'i'},      /* silent, same as --inhex= */
77         {"inhex", required_argument, 0, 'i'},
78         {"maxlen", required_argument, 0, 'm'},
79         {"num", required_argument, 0, 'n'},
80         {"other", required_argument, 0, 'o'},
81         {"query", no_argument, 0, 'q'},
82         {"raw", no_argument, 0, 'r'},
83         {"verbose", no_argument, 0, 'v'},
84         {"version", no_argument, 0, 'V'},
85         {"zone", required_argument, 0, 'z'},
86         {0, 0, 0, 0},
87 };
88 
89 
90 static void
usage()91 usage()
92 {
93     pr2serr("Usage: "
94             "sg_z_act_query [--activate] [--all] [--force] [--help] "
95             "[--hex]\n"
96             "                      [--inhex=FN] [--maxlen=LEN] [--num=ZS] "
97             "[--other=ZDID]\n"
98             "                      [--query] [--raw] [--verbose] "
99             "[--version]\n"
100             "                      [--zone=ID] DEVICE\n");
101     pr2serr("  where:\n"
102             "    --activate|-A      do ZONE ACTIVATE command (def: ZONE "
103             "QUERY)\n"
104             "    --all|-a           sets the ALL flag in the cdb\n"
105             "    --force|-f         bypass some sanity checks\n"
106             "    --help|-h          print out usage message\n"
107             "    --hex|-H           print out response in hexadecimal\n"
108             "    --inhex=FN|-i FN    decode contents of FN, ignore DEVICE\n"
109             "    --maxlen=LEN|-m LEN    LEN place in cdb's allocation "
110             "length field\n"
111             "                           (def: 8192 (bytes))\n"
112             "    --num=ZS|-n ZS     ZS is the number of zones and is placed "
113             "in the cdb;\n"
114             "                       default value is 1, ignored if --all "
115             "given\n"
116             "    --other=ZDID|-o ZDID    ZDID is placed in Other zone domain "
117             "ID field\n"
118             "    --query|-q         do ZONE QUERY command (def: ZONE "
119             "QUERY)\n"
120             "    --raw|-r           output response in binary, or if "
121             "--inhex=FN is\n"
122             "                       given, then FN's contents are binary\n"
123             "    --verbose|-v       increase verbosity\n"
124             "    --version|-V       print version string and exit\n"
125             "    --zone=ID|-z ID    ID is the starting LBA of the zone "
126             "(def: 0)\n\n"
127             "Performs either a SCSI ZONE ACTIVATE command, or a ZONE QUERY "
128             "command.\nArguments to options are decimal by default, for hex "
129             "use a leading '0x'\nor a trailing 'h'. The default action is to "
130             "send a ZONE QUERY command.\n");
131 }
132 
133 /* Invokes a ZBC IN command (with either a ZONE ACTIVATE or a ZONE QUERY
134  * service action).  Return of 0 -> success, various SG_LIB_CAT_* positive
135  * values or -1 -> other errors */
136 static int
sg_ll_zone_act_query(int sg_fd,const struct opts_t * op,void * resp,int * residp)137 sg_ll_zone_act_query(int sg_fd, const struct opts_t * op, void * resp,
138                      int * residp)
139 {
140     uint8_t sa = op->do_activate ? Z_ACTIVATE_SA : Z_QUERY_SA;
141     int ret, res, sense_cat;
142     struct sg_pt_base * ptvp;
143     uint8_t zi_cdb[SG_ZBC_IN_CMDLEN] =
144           {SG_ZBC_IN, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0,  0, 0, 0, 0};
145     uint8_t sense_b[SENSE_BUFF_LEN] SG_C_CPP_ZERO_INIT;
146     char b[64];
147 
148     zi_cdb[1] = 0x1f & sa;
149     if (op->do_all)
150         zi_cdb[1] |= 0x80;
151 
152     sg_put_unaligned_be64(op->st_lba, zi_cdb + 2);
153     sg_put_unaligned_be16(op->num_zones, zi_cdb + 10);
154     sg_put_unaligned_be16(op->max_alloc, zi_cdb + 12);
155     zi_cdb[14] = op->other_zdid;
156     sg_get_opcode_sa_name(zi_cdb[0], sa, -1, sizeof(b), b);
157     if (op->vb) {
158         char d[128];
159 
160         pr2serr("    %s cdb: %s\n", b,
161                 sg_get_command_str(zi_cdb, SG_ZBC_IN_CMDLEN, false,
162                                    sizeof(d), d));
163     }
164     ptvp = construct_scsi_pt_obj();
165     if (NULL == ptvp) {
166         pr2serr("%s: out of memory\n", b);
167         return -1;
168     }
169     set_scsi_pt_cdb(ptvp, zi_cdb, sizeof(zi_cdb));
170     set_scsi_pt_sense(ptvp, sense_b, sizeof(sense_b));
171     set_scsi_pt_data_in(ptvp, (uint8_t *)resp, op->max_alloc);
172     res = do_scsi_pt(ptvp, sg_fd, DEF_PT_TIMEOUT, op->vb);
173     ret = sg_cmds_process_resp(ptvp, b, res, true /* noisy */,
174                                op->vb, &sense_cat);
175     if (-1 == ret) {
176         if (get_scsi_pt_transport_err(ptvp))
177             ret = SG_LIB_TRANSPORT_ERROR;
178         else
179             ret = sg_convert_errno(get_scsi_pt_os_err(ptvp));
180     } else if (-2 == ret) {
181         switch (sense_cat) {
182         case SG_LIB_CAT_RECOVERED:
183         case SG_LIB_CAT_NO_SENSE:
184             ret = 0;
185             break;
186         default:
187             ret = sense_cat;
188             break;
189         }
190     } else
191         ret = 0;
192     if (residp)
193         *residp = get_scsi_pt_resid(ptvp);
194     destruct_scsi_pt_obj(ptvp);
195     return ret;
196 }
197 
198 static const char *
zone_condition_str(int zc,char * b,int blen,int vb)199 zone_condition_str(int zc, char * b, int blen, int vb)
200 {
201     const char * cp;
202 
203     if (NULL == b)
204         return "zone_condition_str: NULL ptr)";
205     switch (zc) {
206     case 0:
207         cp = "Not write pointer";
208         break;
209     case 1:
210         cp = "Empty";
211         break;
212     case 2:
213         cp = "Implicitly opened";
214         break;
215     case 3:
216         cp = "Explicitly opened";
217         break;
218     case 4:
219         cp = "Closed";
220         break;
221     case 5:
222         cp = "Inactive";
223         break;
224     case 0xd:
225         cp = "Read only";
226         break;
227     case 0xe:
228         cp = "Full";
229         break;
230     case 0xf:
231         cp = "Offline";
232         break;
233     default:
234         cp = NULL;
235         break;
236     }
237     if (cp) {
238         if (vb)
239             snprintf(b, blen, "%s [0x%x]", cp, zc);
240         else
241             snprintf(b, blen, "%s", cp);
242     } else
243         snprintf(b, blen, "Reserved [0x%x]", zc);
244     return b;
245 }
246 
247 /* The allocation length field in each cdb cannot be less than 64 but the
248  * transport could still trim the response. */
249 static int
decode_z_act_query(const uint8_t * ziBuff,int act_len,uint32_t zar_len,const struct opts_t * op)250 decode_z_act_query(const uint8_t * ziBuff, int act_len, uint32_t zar_len,
251                    const struct opts_t * op)
252 {
253     uint8_t zt;
254     int k, zc, num_desc;
255     const uint8_t * bp;
256     char b[80];
257 
258     if ((uint32_t)act_len < zar_len) {
259         num_desc = (act_len >= 64) ? ((act_len - 64) / Z_ACT_DESC_LEN) : 0;
260         if (act_len == op->max_alloc) {
261             if (op->maxlen_given)
262                 pr2serr("response length [%u bytes] may be constrained by "
263                         "given --maxlen value, try increasing\n", zar_len);
264             else
265                 pr2serr("perhaps --maxlen=%u needs to be used\n", zar_len);
266         } else if (op->inhex_fn)
267             pr2serr("perhaps %s has been truncated\n", op->inhex_fn);
268     } else
269         num_desc = (zar_len - 64) / Z_ACT_DESC_LEN;
270     if (act_len <= 8)
271         return 0;
272     if (0x80 & ziBuff[8]) {
273         printf("  Nz_valid=1\n");
274         if (act_len > 19)
275             printf("    Number of zones: %u\n",
276                    sg_get_unaligned_be32(ziBuff + 16));
277     } else
278         printf("  Nz_valid=0\n");
279     if (0x40 & ziBuff[8]) {
280         printf("  Ziwup_valid=1\n");
281         if (act_len > 31)
282             printf("    Zone ID with unmet prerequisite: 0x%" PRIx64 "\n",
283                    sg_get_unaligned_be64(ziBuff + 24));
284     } else
285         printf("  Ziwup_valid=0\n");
286     printf("  Activated=%d\n", (0x1 & ziBuff[8]));
287     if (act_len <= 9)
288         return 0;
289     printf("  Unmet prerequisites:\n");
290     if (0 == ziBuff[9])
291         printf("    none\n");
292     else {
293         if (0x40 & ziBuff[9])
294              printf("    security\n");
295         if (0x20 & ziBuff[9])
296              printf("    mult domn\n");
297         if (0x10 & ziBuff[9])
298              printf("    rlm rstct\n");
299         if (0x8 & ziBuff[9])
300              printf("    mult ztyp\n");
301         if (0x4 & ziBuff[9])
302              printf("    rlm align\n");
303         if (0x2 & ziBuff[9])
304              printf("    not empty\n");
305         if (0x1 & ziBuff[9])
306              printf("    not inact\n");
307     }
308     if (act_len <= 10)
309         return 0;
310     printf("  Other zone domain ID: %u\n", ziBuff[10]);
311     if (act_len <= 11)
312         return 0;
313     printf("  All: %d\n", (0x1 & ziBuff[11]));
314 
315     if (((uint32_t)act_len < zar_len) &&
316         ((num_desc * Z_ACT_DESC_LEN) + 64 > act_len)) {
317         pr2serr("Skip due to truncated response, try using --num= to a "
318                 "value less than %d\n", num_desc);
319         return SG_LIB_CAT_MALFORMED;
320     }
321     for (k = 0, bp = ziBuff + 64; k < num_desc; ++k, bp += Z_ACT_DESC_LEN) {
322         printf("  Zone activation descriptor: %d\n", k);
323         if (op->hex_count) {
324             hex2stdout(bp, Z_ACT_DESC_LEN, -1);
325             continue;
326         }
327         zt = bp[0] & 0xf;
328         zc = (bp[1] >> 4) & 0xf;
329         printf("    Zone type: %s\n", sg_get_zone_type_str(zt, sizeof(b),
330                b));
331         printf("    Zone condition: %s\n", zone_condition_str(zc, b,
332                sizeof(b), op->vb));
333         printf("    Zone domain ID: %u\n", bp[2]);
334         printf("    Zone range size: %" PRIu64 "\n",
335                sg_get_unaligned_be64(bp + 8));
336         printf("    Starting zone locator: 0x%" PRIx64 "\n",
337                sg_get_unaligned_be64(bp + 16));
338     }
339     return 0;
340 }
341 
342 static void
dStrRaw(const uint8_t * str,int len)343 dStrRaw(const uint8_t * str, int len)
344 {
345     int k;
346 
347     for (k = 0; k < len; ++k)
348         printf("%c", str[k]);
349 }
350 
351 
352 int
main(int argc,char * argv[])353 main(int argc, char * argv[])
354 {
355     bool no_final_msg = false;
356     bool version_given = false;
357     int res, c, n, in_len, rlen, act_len;
358     int sg_fd = -1;
359     int resid = 0;
360     int verbose = 0;
361     int ret = 0;
362     uint32_t zar_len, zarr_len;
363     int64_t ll;
364     uint8_t * ziBuff = NULL;
365     uint8_t * free_zibp = NULL;
366     const char * sa_name;
367     char b[80];
368     struct opts_t opts SG_C_CPP_ZERO_INIT;
369     struct opts_t * op = &opts;
370 
371     while (1) {
372         int option_index = 0;
373 
374         c = getopt_long(argc, argv, "aAfhHi:m:n:o:qrvVz:", long_options,
375                         &option_index);
376         if (c == -1)
377             break;
378 
379         switch (c) {
380         case 'a':
381             op->do_all = true;
382             break;
383         case 'A':
384             op->do_activate = true;
385             break;
386         case 'f':
387             op->do_force = true;
388             break;
389         case 'h':
390         case '?':
391             usage();
392             return 0;
393         case 'H':
394             ++op->hex_count;
395             break;
396         case 'i':
397             op->inhex_fn = optarg;
398             break;
399         case 'm':
400             n = sg_get_num(optarg);
401             if ((n < 0) || (n > 0xffff)) {
402                 pr2serr("--maxlen= expects an argument between 0 and 0xffff "
403                         "inclusive\n");
404                 return SG_LIB_SYNTAX_ERROR;
405             }
406             op->maxlen_given = true;
407             op->max_alloc = (uint16_t)n;
408             break;
409         case 'n':
410             n = sg_get_num(optarg);
411             if ((n < 0) || (n > 0xffff)) {
412                 pr2serr("--num=ZS expects an argument between 0 and 0xffff "
413                         "inclusive\n");
414                 return SG_LIB_SYNTAX_ERROR;
415             }
416             op->num_zones = (uint16_t)n;
417             break;
418         case 'o':
419             n = sg_get_num(optarg);
420             if ((n < 0) || (n > 0xff)) {
421                 pr2serr("--other=ZDID expects an argument between 0 and 0xff "
422                         "inclusive\n");
423                 return SG_LIB_SYNTAX_ERROR;
424             }
425             op->other_zdid = (uint8_t)n;
426             break;
427         case 'q':
428             op->do_query = true;
429             break;
430         case 'r':
431             op->do_raw = true;
432             break;
433         case 'v':
434             ++op->vb;
435             break;
436         case 'V':
437             version_given = true;
438             break;
439         case 'z':
440             if ((2 == strlen(optarg)) && (0 == memcmp("-1", optarg, 2))) {
441                 op->st_lba = UINT64_MAX;
442                 break;
443             }
444             ll = sg_get_llnum(optarg);
445             if (-1 == ll) {
446                 pr2serr("bad argument to '--zone=ID'\n");
447                 return SG_LIB_SYNTAX_ERROR;
448             }
449             op->st_lba = (uint64_t)ll;  /* Zone ID is starting LBA */
450             break;
451         default:
452             pr2serr("unrecognised option code 0x%x ??\n\n", c);
453             usage();
454             return SG_LIB_SYNTAX_ERROR;
455         }
456     }
457     if (optind < argc) {
458         if (NULL == op->device_name) {
459             op->device_name = argv[optind];
460             ++optind;
461         }
462         if (optind < argc) {
463             for (; optind < argc; ++optind)
464                 pr2serr("Unexpected extra argument: %s\n",
465                         argv[optind]);
466             usage();
467             return SG_LIB_SYNTAX_ERROR;
468         }
469     }
470 
471     if (version_given) {
472         pr2serr("version: %s\n", version_str);
473         return 0;
474     }
475 
476     if ((! op->do_all) && (0 == op->num_zones))
477         op->num_zones = 1;
478     if (op->do_activate && op->do_query){
479         pr2serr("only one of these options: --activate and --query may be "
480                 "given\n\n");
481         usage();
482         return SG_LIB_CONTRADICT;
483     }
484     sa_name = op->do_activate ? "Zone activate" : "Zone query";
485     if (op->device_name && op->inhex_fn) {
486         pr2serr("ignoring DEVICE, best to give DEVICE or --inhex=FN, but "
487                 "not both\n");
488         op->device_name = NULL;
489     }
490     if (op->max_alloc < 4) {
491         if (op->max_alloc > 0)
492             pr2serr("Won't accept --maxlen= of 1, 2 or 3, using %d "
493                     "instead\n", DEF_ALLOC_LEN);
494         op->max_alloc = DEF_ALLOC_LEN;
495     }
496     ziBuff = (uint8_t *)sg_memalign(op->max_alloc, 0, &free_zibp, op->vb > 3);
497     if (NULL == ziBuff) {
498         pr2serr("unable to sg_memalign %d bytes\n", op->max_alloc);
499         return sg_convert_errno(ENOMEM);
500     }
501 
502     if (NULL == op->device_name) {
503         if (op->inhex_fn) {
504             if ((ret = sg_f2hex_arr(op->inhex_fn, op->do_raw, false, ziBuff,
505                                     &in_len, op->max_alloc))) {
506                 if (SG_LIB_LBA_OUT_OF_RANGE == ret) {
507                     no_final_msg = true;
508                     pr2serr("... decode what we have, --maxlen=%d needs to "
509                             "be increased\n", op->max_alloc);
510                 } else
511                     goto the_end;
512             }
513             if (verbose > 2)
514                 pr2serr("Read %d [0x%x] bytes of user supplied data\n",
515                         in_len, in_len);
516             if (op->do_raw)
517                 op->do_raw = false;    /* can interfere on decode */
518             if (in_len < 4) {
519                 pr2serr("--inhex=%s only decoded %d bytes (needs 4 at "
520                         "least)\n", op->inhex_fn, in_len);
521                 ret = SG_LIB_SYNTAX_ERROR;
522                 goto the_end;
523             }
524             res = 0;
525             goto start_response;
526         } else {
527             pr2serr("missing device name!\n\n");
528             usage();
529             ret = SG_LIB_FILE_ERROR;
530             no_final_msg = true;
531             goto the_end;
532         }
533     } else
534         in_len = 0;
535 
536     if (op->do_raw) {
537         if (sg_set_binary_mode(STDOUT_FILENO) < 0) {
538             perror("sg_set_binary_mode");
539             return SG_LIB_FILE_ERROR;
540         }
541     }
542 
543     sg_fd = sg_cmds_open_device(op->device_name, false /* rw */, verbose);
544     if (sg_fd < 0) {
545         int err = -sg_fd;
546         if (verbose)
547             pr2serr("open error: %s: %s\n", op->device_name,
548                     safe_strerror(err));
549         ret = sg_convert_errno(err);
550         goto the_end;
551     }
552 
553     res = sg_ll_zone_act_query(sg_fd, op, ziBuff, &resid);
554     ret = res;
555     if (res) {
556         if (SG_LIB_CAT_INVALID_OP == res)
557             pr2serr("%s command not supported\n", sa_name);
558         else {
559             sg_get_category_sense_str(res, sizeof(b), b, verbose);
560             pr2serr("%s command: %s\n", sa_name, b);
561         }
562     }
563 
564 start_response:
565     if (0 == res) {
566         if ((resid < 0) || (resid > op->max_alloc)) {
567             pr2serr("Unexpected resid=%d\n", resid);
568             ret = SG_LIB_CAT_MALFORMED;
569             goto the_end;
570         }
571         rlen = op->inhex_fn ? in_len : (op->max_alloc - resid);
572         if (rlen < 4) {
573             pr2serr("Decoded response length (%d) too short\n", rlen);
574             ret = SG_LIB_CAT_MALFORMED;
575             goto the_end;
576         }
577         zar_len = sg_get_unaligned_be32(ziBuff + 0) + 64;
578         zarr_len = sg_get_unaligned_be32(ziBuff + 4) + 64;
579         if ((zar_len > MAX_ACT_QUERY_BUFF_LEN) ||
580             (zarr_len > MAX_ACT_QUERY_BUFF_LEN) || (zarr_len > zar_len)) {
581             if (! op->do_force) {
582                 pr2serr("zar or zarr length [%u/%u bytes] seems wild, use "
583                         "--force override\n", zar_len, zarr_len);
584                 return SG_LIB_CAT_MALFORMED;
585             }
586         }
587         if (zarr_len > (uint32_t)rlen) {
588             pr2serr("zarr response length is %u bytes, but system "
589                     "reports %d bytes received??\n", zarr_len, rlen);
590             if (op->do_force)
591                 act_len = rlen;
592             else {
593                 pr2serr("Exiting, use --force to override\n");
594                 ret = SG_LIB_CAT_MALFORMED;
595                 goto the_end;
596             }
597         } else
598             act_len = zarr_len;
599         if (op->do_raw) {
600             dStrRaw(ziBuff, act_len);
601             goto the_end;
602         }
603         if (op->hex_count && (2 != op->hex_count)) {
604             hex2stdout(ziBuff, act_len, ((1 == op->hex_count) ? 1 : -1));
605             goto the_end;
606         }
607         printf("%s response:\n", sa_name);
608         if (act_len < 64) {
609             pr2serr("Zone length [%d] too short (perhaps after truncation\n)",
610                     act_len);
611             ret = SG_LIB_CAT_MALFORMED;
612             goto the_end;
613         }
614         ret = decode_z_act_query(ziBuff, act_len, zar_len, op);
615     } else if (SG_LIB_CAT_INVALID_OP == res)
616         pr2serr("%s command not supported\n", sa_name);
617     else {
618         sg_get_category_sense_str(res, sizeof(b), b, op->vb);
619         pr2serr("%s command: %s\n", sa_name, b);
620     }
621 
622 the_end:
623     if (sg_fd >= 0) {
624         res = sg_cmds_close_device(sg_fd);
625         if (res < 0) {
626             pr2serr("close error: %s\n", safe_strerror(-res));
627             if (0 == ret)
628                 ret = sg_convert_errno(-res);
629         }
630     }
631     if (free_zibp)
632         free(free_zibp);
633     if ((0 == verbose) && (! no_final_msg)) {
634         if (! sg_if_can2stderr("sg_z_act_query failed: ", ret))
635             pr2serr("Some error occurred, try again with '-v' "
636                     "or '-vv' for more information\n");
637     }
638     return (ret >= 0) ? ret : SG_LIB_CAT_OTHER;
639 }
640