• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 #ifndef SG_LIB_H
2 #define SG_LIB_H
3 
4 /*
5  * Copyright (c) 2004-2022 Douglas Gilbert.
6  * All rights reserved.
7  * Use of this source code is governed by a BSD-style
8  * license that can be found in the BSD_LICENSE file.
9  *
10  * SPDX-License-Identifier: BSD-2-Clause
11  */
12 
13 /*
14  *
15  * On 5th October 2004 a FreeBSD license was added to this file.
16  * The intention is to keep this file and the related sg_lib.c file
17  * as open source and encourage their unencumbered use.
18  *
19  * Current version number of this library is in the sg_lib_data.c file and
20  * can be accessed with the sg_lib_version() function.
21  */
22 
23 
24 /*
25  * This header file contains defines and function declarations that may
26  * be useful to applications that communicate with devices that use a
27  * SCSI command set. These command sets have names like SPC-4, SBC-3,
28  * SSC-3, SES-2 and draft standards defining them can be found at
29  * https://www.t10.org . Virtually all devices in the Linux SCSI subsystem
30  * utilize SCSI command sets. Many devices in other Linux device subsystems
31  * utilize SCSI command sets either natively or via emulation (e.g. a
32  * SATA disk in a USB enclosure).
33  */
34 
35 #include <stdio.h>
36 #include <stdint.h>
37 #include <stdbool.h>
38 
39 #ifdef __cplusplus
40 extern "C" {
41 #endif
42 
43 /* SCSI Peripheral Device Types (PDT) [5 bit field] */
44 #define PDT_DISK 0x0    /* direct access block device (disk) */
45 #define PDT_TAPE 0x1    /* sequential access device (magnetic tape) */
46 #define PDT_PRINTER 0x2 /* printer device (see SSC-1) */
47 #define PDT_PROCESSOR 0x3       /* processor device (e.g. SAFTE device) */
48 #define PDT_WO 0x4      /* write once device (some optical disks) */
49 #define PDT_MMC 0x5     /* CD/DVD/BD (multi-media) */
50 #define PDT_SCANNER 0x6 /* obsolete */
51 #define PDT_OPTICAL 0x7 /* optical memory device (some optical disks) */
52 #define PDT_MCHANGER 0x8        /* media changer device (e.g. tape robot) */
53 #define PDT_COMMS 0x9   /* communications device (obsolete) */
54 #define PDT_SAC 0xc     /* storage array controller device */
55 #define PDT_SES 0xd     /* SCSI Enclosure Services (SES) device */
56 #define PDT_RBC 0xe     /* Reduced Block Commands (simplified PDT_DISK) */
57 #define PDT_OCRW 0xf    /* optical card read/write device */
58 #define PDT_BCC 0x10    /* bridge controller commands */
59 #define PDT_OSD 0x11    /* Object Storage Device (OSD) */
60 #define PDT_ADC 0x12    /* Automation/drive commands (ADC) */
61 #define PDT_SMD 0x13    /* Security Manager Device (SMD) */
62 #define PDT_ZBC 0x14    /* Zoned Block Commands (ZBC) */
63 #define PDT_WLUN 0x1e   /* Well known logical unit (WLUN) */
64 #define PDT_UNKNOWN 0x1f        /* Unknown or no device type */
65 #define PDT_MASK 0x1f   /* For byte 0 of INQUIRY response */
66 #define PDT_MAX 0x1f
67 
68 #define GRPNUM_MASK 0x3f
69 
70 /* ZBC disks use either PDT_ZBC (if 'host managed') or PDT_DISK .
71  * So squeeze two PDTs into one integer. Use sg_pdt_s_eq() to compare.
72  * N.B. Must not use PDT_DISK as upper */
73 #define PDT_DISK_ZBC (PDT_DISK | (PDT_ZBC << 8))
74 #define PDT_ALL (-1)    /* for common to all PDTs */
75 #define PDT_LOWER_MASK 0xff
76 #define PDT_UPPER_MASK (~PDT_LOWER_MASK)
77 
78 #ifndef SAM_STAT_GOOD
79 /* The SCSI status codes as found in SAM-4 at www.t10.org */
80 #define SAM_STAT_GOOD 0x0
81 #define SAM_STAT_CHECK_CONDITION 0x2
82 #define SAM_STAT_CONDITION_MET 0x4                /* this is not an error */
83 #define SAM_STAT_BUSY 0x8
84 #define SAM_STAT_INTERMEDIATE 0x10                /* obsolete in SAM-4 */
85 #define SAM_STAT_INTERMEDIATE_CONDITION_MET 0x14  /* obsolete in SAM-4 */
86 #define SAM_STAT_RESERVATION_CONFLICT 0x18
87 #define SAM_STAT_COMMAND_TERMINATED 0x22          /* obsolete in SAM-3 */
88 #define SAM_STAT_TASK_SET_FULL 0x28
89 #define SAM_STAT_ACA_ACTIVE 0x30
90 #define SAM_STAT_TASK_ABORTED 0x40
91 #endif
92 
93 /* The SCSI sense key codes as found in SPC-4 at www.t10.org */
94 #define SPC_SK_NO_SENSE 0x0
95 #define SPC_SK_RECOVERED_ERROR 0x1
96 #define SPC_SK_NOT_READY 0x2
97 #define SPC_SK_MEDIUM_ERROR 0x3
98 #define SPC_SK_HARDWARE_ERROR 0x4
99 #define SPC_SK_ILLEGAL_REQUEST 0x5
100 #define SPC_SK_UNIT_ATTENTION 0x6
101 #define SPC_SK_DATA_PROTECT 0x7
102 #define SPC_SK_BLANK_CHECK 0x8
103 #define SPC_SK_VENDOR_SPECIFIC 0x9
104 #define SPC_SK_COPY_ABORTED 0xa
105 #define SPC_SK_ABORTED_COMMAND 0xb
106 #define SPC_SK_RESERVED 0xc
107 #define SPC_SK_VOLUME_OVERFLOW 0xd
108 #define SPC_SK_MISCOMPARE 0xe
109 #define SPC_SK_COMPLETED 0xf
110 
111 /* Transport protocol identifiers or just Protocol identifiers */
112 #define TPROTO_FCP 0
113 #define TPROTO_SPI 1
114 #define TPROTO_SSA 2
115 #define TPROTO_1394 3
116 #define TPROTO_SRP 4            /* SCSI over RDMA */
117 #define TPROTO_ISCSI 5
118 #define TPROTO_SAS 6
119 #define TPROTO_ADT 7
120 #define TPROTO_ATA 8
121 #define TPROTO_UAS 9            /* USB attached SCSI */
122 #define TPROTO_SOP 0xa          /* SCSI over PCIe */
123 #define TPROTO_PCIE 0xb         /* includes NVMe */
124 #define TPROTO_NONE 0xf
125 
126 /* SCSI Feature Sets (sfs) */
127 #define SCSI_FS_SPC_DISCOVERY_2016 0x1
128 #define SCSI_FS_SBC_BASE_2010 0x102
129 #define SCSI_FS_SBC_BASE_2016 0x101
130 #define SCSI_FS_SBC_BASIC_PROV_2016 0x103
131 #define SCSI_FS_SBC_DRIVE_MAINT_2016 0x104
132 #define SCSI_FS_ZBC_HOST_AWARE_2020 0x300
133 #define SCSI_FS_ZBC_HOST_MANAGED_2020 0x301
134 #define SCSI_FS_ZBC_DOMAINS_REALMS_2020 0x302
135 
136 /* Often SCSI responses use the highest integer that can fit in a field
137  * to indicate "unbounded" or limit does not apply. Sometimes represented
138  * in output as "-1" for brevity */
139 #define SG_LIB_UNBOUNDED_16BIT 0xffff
140 #define SG_LIB_UNBOUNDED_32BIT 0xffffffffU
141 #define SG_LIB_UNBOUNDED_64BIT 0xffffffffffffffffULL
142 
143 #if (__STDC_VERSION__ >= 199901L)  /* C99 or later */
144     typedef uintptr_t sg_uintptr_t;
145 #else
146     typedef unsigned long sg_uintptr_t;
147 #endif
148 
149 /* Borrowed from Linux kernel; no check that 'arr' actually is one */
150 #define SG_ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))
151 
152 /* Doesn't seem to be a common C and C++ technique for clearing an
153  * aggregrate (e.g. a struct instance) on the stack. Hence this hack: */
154 #ifdef __cplusplus
155 #define SG_C_CPP_ZERO_INIT {}
156 #else
157 #define SG_C_CPP_ZERO_INIT ={0}
158 #endif
159 
160 
161 /* The format of the version string is like this: "2.26 20170906" */
162 const char * sg_lib_version();
163 
164 /* Returns length of SCSI command given the opcode (first byte).
165  * Yields the wrong answer for variable length commands (opcode=0x7f)
166  * and potentially some vendor specific commands. */
167 int sg_get_command_size(uint8_t cdb_byte0);
168 
169 /* Command name given pointer to the cdb. Certain command names
170  * depend on peripheral type (give 0 or -1 if unknown). Places command
171  * name into buff and will write no more than buff_len bytes. */
172 void sg_get_command_name(const uint8_t * cdbp, int peri_type, int buff_len,
173                          char * buff);
174 
175 /* Command name given only the first byte (byte 0) of a cdb and
176  * peripheral type (give 0 or -1 if unknown). */
177 void sg_get_opcode_name(uint8_t cdb_byte0, int peri_type, int buff_len,
178                         char * buff);
179 
180 /* Command name given opcode (byte 0), service action and peripheral type.
181  * If no service action give 0, if unknown peripheral type give 0 or -1 . */
182 void sg_get_opcode_sa_name(uint8_t cdb_byte0, int service_action,
183                            int peri_type, int buff_len, char * buff);
184 
185 /* Fetch NVMe command name given first byte (byte offset 0 in 64 byte
186  * command) of command. Gets Admin NVMe command name if 'admin' is true
187  * (e.g. opcode=0x6 -> Identify), otherwise gets NVM command set name
188  * (e.g. opcode=0 -> Flush). Returns 'buff'. */
189 char * sg_get_nvme_opcode_name(uint8_t cmd_byte0, bool admin, int buff_len,
190                                char * buff);
191 
192 /* Fetch scsi status string. */
193 void sg_get_scsi_status_str(int scsi_status, int buff_len, char * buff);
194 
195 /* This is a slightly stretched SCSI sense "descriptor" format header.
196  * The addition is to allow the 0x70 and 0x71 response codes. The idea
197  * is to place the salient data of both "fixed" and "descriptor" sense
198  * format into one structure to ease application processing.
199  * The original sense buffer should be kept around for those cases
200  * in which more information is required (e.g. the LBA of a MEDIUM ERROR). */
201 struct sg_scsi_sense_hdr {
202     uint8_t response_code; /* permit: 0x0, 0x70, 0x71, 0x72, 0x73 */
203     uint8_t sense_key;
204     uint8_t asc;
205     uint8_t ascq;
206     uint8_t byte4;      /* descriptor: SDAT_OVFL; fixed: lower three ... */
207     uint8_t byte5;      /* ... bytes of INFO field */
208     uint8_t byte6;
209     uint8_t additional_length;  /* zero for fixed format sense data */
210 };
211 
212 /* The '_is_good()' returns true when status is SAM_STAT_GOOD or
213  * SAM_STAT_CONDITION_MET, returns false otherwise. Ignores bit 0. The
214  * '_is_bad() variant is the logical inverse. */
215 bool sg_scsi_status_is_good(int sstatus);
216 bool sg_scsi_status_is_bad(int sstatus);
217 
218 /* Maps the salient data from a sense buffer which is in either fixed or
219  * descriptor format into a structure mimicking a descriptor format
220  * header (i.e. the first 8 bytes of sense descriptor format).
221  * If zero response code returns false. Otherwise returns true and if 'sshp'
222  * is non-NULL then zero all fields and then set the appropriate fields in
223  * that structure. sshp::additional_length is always 0 for response
224  * codes 0x70 and 0x71 (fixed format). */
225 bool sg_scsi_normalize_sense(const uint8_t * sensep, int sense_len,
226                              struct sg_scsi_sense_hdr * sshp);
227 
228 /* Attempt to find the first SCSI sense data descriptor that matches the
229  * given 'desc_type'. If found return pointer to start of sense data
230  * descriptor; otherwise (including fixed format sense data) returns NULL. */
231 const uint8_t * sg_scsi_sense_desc_find(const uint8_t * sensep, int sense_len,
232                                         int desc_type);
233 
234 /* Get sense key from sense buffer. If successful returns a sense key value
235  * between 0 and 15. If sense buffer cannot be decode, returns -1 . */
236 int sg_get_sense_key(const uint8_t * sensep, int sense_len);
237 
238 /* Yield string associated with sense_key value. Returns 'buff'. */
239 char * sg_get_sense_key_str(int sense_key, int buff_len, char * buff);
240 
241 /* Yield string associated with ASC/ASCQ values. Returns 'buff'. Prefixes
242  * any valid additional sense found with "Additional sense: ". */
243 char * sg_get_asc_ascq_str(int asc, int ascq, int buff_len, char * buff);
244 
245 /* Same as sg_get_asc_ascq_str() when add_sense_leadin is true. When it is
246  * false this function does _not_ prefix any valid additional sense found
247  * with "Additional sense: ". */
248 char * sg_get_additional_sense_str(int asc, int ascq, bool add_sense_leadin,
249                                    int buff_len, char * buff);
250 
251 /* Returns true if valid bit set, false if valid bit clear. Irrespective the
252  * information field is written out via 'info_outp' (except when it is
253  * NULL). Handles both fixed and descriptor sense formats. */
254 bool sg_get_sense_info_fld(const uint8_t * sensep, int sb_len,
255                            uint64_t * info_outp);
256 
257 /* Returns true if fixed format or command specific information descriptor
258  * is found in the descriptor sense; else false. If available the command
259  * specific information field (4 byte integer in fixed format, 8 byte
260  * integer in descriptor format) is written out via 'cmd_spec_outp'.
261  * Handles both fixed and descriptor sense formats. */
262 bool sg_get_sense_cmd_spec_fld(const uint8_t * sensep, int sb_len,
263                                uint64_t * cmd_spec_outp);
264 
265 /* Returns true if any of the 3 bits (i.e. FILEMARK, EOM or ILI) are set.
266  * In descriptor format if the stream commands descriptor not found
267  * then returns false. Writes true or false corresponding to these bits to
268  * the last three arguments if they are non-NULL. */
269 bool sg_get_sense_filemark_eom_ili(const uint8_t * sensep, int sb_len,
270                                    bool * filemark_p, bool * eom_p,
271                                    bool * ili_p);
272 
273 /* Returns true if SKSV is set and sense key is NO_SENSE or NOT_READY. Also
274  * returns true if progress indication sense data descriptor found. Places
275  * progress field from sense data where progress_outp points. If progress
276  * field is not available returns false. Handles both fixed and descriptor
277  * sense formats. N.B. App should multiply by 100 and divide by 65536
278  * to get percentage completion from given value. */
279 bool sg_get_sense_progress_fld(const uint8_t * sensep, int sb_len,
280                                int * progress_outp);
281 
282 /* Closely related to sg_print_sense(). Puts decoded sense data in 'buff'.
283  * Usually multiline with multiple '\n' including one trailing. If
284  * 'raw_sinfo' set appends sense buffer in hex. 'leadin' is string prepended
285  * to each line written to 'buff', NULL treated as "". Returns the number of
286  * bytes written to 'buff' excluding the trailing '\0'.
287  * N.B. prior to sg3_utils v 1.42 'leadin' was only prepended to the first
288  * line output. Also this function returned type void. */
289 int sg_get_sense_str(const char * leadin, const uint8_t * sense_buffer,
290                      int sb_len, bool raw_sinfo, int buff_len, char * buff);
291 
292 /* Decode descriptor format sense descriptors (assumes sense buffer is
293  * in descriptor format). 'leadin' is string prepended to each line written
294  * to 'b', NULL treated as "". Returns the number of bytes written to 'b'
295  * excluding the trailing '\0'. If problem, returns 0. */
296 int sg_get_sense_descriptors_str(const char * leadin,
297                                  const uint8_t * sense_buffer,
298                                  int sb_len, int blen, char * b);
299 
300 /* Decodes a designation descriptor (e.g. as found in the Device
301  * Identification VPD page (0x83)) into string 'b' whose maximum length is
302  * blen. 'leadin' is string prepended to each line written to 'b', NULL
303  * treated as "". Returns the number of bytes written to 'b' excluding the
304  * trailing '\0'. */
305 int sg_get_designation_descriptor_str(const char * leadin,
306                                       const uint8_t * ddp, int dd_len,
307                                       bool print_assoc, bool do_long,
308                                       int blen, char * b);
309 
310 /* Expects a T10 UUID designator (as found in the Device Identification VPD
311  * page) pointed to by 'dp'. To not produce an error string in 'b', c_set
312  * should be 1 (binary) and dlen should be 18. Currently T10 only supports
313  * locally assigned UUIDs. Writes output to string 'b' of no more than blen
314  * bytes and returns the number of bytes actually written to 'b' but doesn't
315  * count the trailing null character it always appends (if blen > 0). 'lip'
316  * is lead-in string (on each line) than may be NULL. skip_prefix avoids
317  * outputting: '   Locally assigned UUID: ' before the UUID. */
318 int sg_t10_uuid_desig2str(const uint8_t * dp, int dlen, int c_set,
319                           bool do_long, bool skip_prefix,
320                           const char * lip, int blen, char * b);
321 
322 /* Yield string associated with peripheral device type (pdt). Returns
323  * 'buff'. If 'pdt' out of range yields "bad pdt" string. */
324 char * sg_get_pdt_str(int pdt, int buff_len, char * buff);
325 
326 /* Some lesser used PDTs share a lot in common with a more used PDT.
327  * Examples are PDT_ADC decaying to PDT_TAPE and PDT_ZBC to PDT_DISK.
328  * If such a lesser used 'dev_pdt' is given to this function, then it will
329  * return the more used PDT (i.e. "decays to"); otherwise 'dev_pdt' is
330  * returned. Valid for 'pdt' 0 to 31, for other values returns 0. */
331 int sg_lib_pdt_decay(int dev_pdt);
332 
333 /* Yield string associated with transport protocol identifier (tpi). Returns
334  * 'buff'. If 'tpi' out of range yields "bad tpi" string. */
335 char * sg_get_trans_proto_str(int tpi, int buff_len, char * buff);
336 
337 /* Decode TransportID pointed to by 'bp' of length 'bplen'. Place decoded
338  * string output in 'buff' which is also the return value. Each new line
339  * is prefixed by 'leadin'. If leadin NULL treat as "". */
340 char * sg_decode_transportid_str(const char * leadin, uint8_t * bp, int bplen,
341                                  bool only_one, int buff_len, char * buff);
342 
343 /* Returns a designator's type string given 'val' (0 to 15 inclusive),
344  * otherwise returns NULL. */
345 const char * sg_get_desig_type_str(int val);
346 
347 /* Returns a designator's code_set string given 'val' (0 to 15 inclusive),
348  * otherwise returns NULL. */
349 const char * sg_get_desig_code_set_str(int val);
350 
351 /* Returns a designator's association string given 'val' (0 to 3 inclusive),
352  * otherwise returns NULL. */
353 const char * sg_get_desig_assoc_str(int val);
354 
355 /* Yield string associated with zone type (see ZBC and ZBC-2) [e.g. REPORT
356  * ZONES command response]. Returns 'buff' unless buff_len < 1 in which
357  * NULL is returned. */
358 char * sg_get_zone_type_str(uint8_t zt, int buff_len, char * buff);
359 
360 /* Yield SCSI Feature Set (sfs) string. When 'peri_type' is < -1 (or > 31)
361  * returns pointer to string (same as 'buff') associated with 'sfs_code'.
362  * When 'peri_type' is between -1 (for SPC) and 31 (inclusive) then a match
363  * on both 'sfs_code' and 'peri_type' is required. If 'foundp' is not NULL
364  * then where it points is set to true if a match is found else it is set to
365  * false. If 'buff' is not NULL then in the case of a match a descriptive
366  * string is written to 'buff' while if there is not a not then a string
367  * ending in "Reserved" is written (and may be prefixed with SPC, SBC, SSC
368  * or ZBC). Returns 'buff' (i.e. a pointer value) even if it is NULL.
369  * Example:
370  *    char b[64];
371  *    ...
372  *    printf("%s\n", sg_get_sfs_str(sfs_code, -2, sizeof(b), b, NULL, 0));
373  */
374 const char * sg_get_sfs_str(uint16_t sfs_code, int peri_type, int buff_len,
375                             char * buff, bool * foundp, int verbose);
376 
377 /* This is a heuristic that takes into account the command bytes and length
378  * to decide whether the presented unstructured sequence of bytes could be
379  * a SCSI command. If so it returns true otherwise false. Vendor specific
380  * SCSI commands (i.e. opcodes from 0xc0 to 0xff), if presented, are assumed
381  * to follow SCSI conventions (i.e. length of 6, 10, 12 or 16 bytes). The
382  * only SCSI commands considered above 16 bytes of length are the Variable
383  * Length Commands (opcode 0x7f) and the XCDB wrapped commands (opcode 0x7e).
384  * Both have an inbuilt length field which can be cross checked with clen.
385  * No NVMe commands (64 bytes long plus some extra added by some OSes) have
386  * opcodes 0x7e or 0x7f yet. ATA is register based but SATA has FIS
387  * structures that are sent across the wire. The 'FIS register' structure is
388  * used to move a command from a SATA host to device, but the ATA 'command'
389  * is not the first byte. So it is harder to say what will happen if a
390  * FIS structure is presented as a SCSI command, hopefully there is a low
391  * probability this function will yield true in that case. */
392 bool sg_is_scsi_cdb(const uint8_t * cdbp, int clen);
393 
394 /* Yield string associated with NVMe command status value in sct_sc. It
395  * expects to decode DW3 bits 27:17 from the completion queue. Bits 27:25
396  * are the Status Code Type (SCT) and bits 24:17 are the Status Code (SC).
397  * Bit 17 in DW3 should be bit 0 in sct_sc. If no status string is found
398  * a string of the form "Reserved [0x<sct_sc_in_hex>]" is generated.
399  * Returns 'buff'. Does nothing if buff_len<=0 or if buff is NULL.*/
400 char * sg_get_nvme_cmd_status_str(uint16_t sct_sc, int buff_len, char * buff);
401 
402 /* Attempts to map NVMe status value ((SCT << 8) | SC) n sct_sc to a SCSI
403  * status, sense_key, asc and ascq tuple. If successful returns true and
404  * writes to non-NULL pointer arguments; otherwise returns false. */
405 bool sg_nvme_status2scsi(uint16_t sct_sc, uint8_t * status_p, uint8_t * sk_p,
406                          uint8_t * asc_p, uint8_t * ascq_p);
407 
408 /* Add vendor (sg3_utils) specific sense descriptor for the NVMe Status
409  * field. Assumes descriptor (i.e. not fixed) sense. Assume sbp has room. */
410 void sg_nvme_desc2sense(uint8_t * sbp, bool dnr, bool more, uint16_t sct_sc);
411 
412 /* Build minimum sense buffer, either descriptor type (desc=true) or fixed
413  * type (desc=false). Assume sbp has enough room (8 or 14 bytes
414  * respectively). sbp should have room for 32 or 18 bytes respectively */
415 void sg_build_sense_buffer(bool desc, uint8_t *sbp, uint8_t skey,
416                            uint8_t asc, uint8_t ascq);
417 
418 /* Returns true if left argument is "equal" to the right argument. l_pdt_s
419  * is a compound PDT (SCSI Peripheral Device Type) or a negative number
420  * which represents a wildcard (i.e. match anything). r_pdt_s has a similar
421  * form. PDT values are 5 bits long (0 to 31) and a compound pdt_s is
422  * formed by shifting the second (upper) PDT by eight bits to the left and
423  * OR-ing it with the first PDT. The pdt_s values must be defined so
424  * PDT_DISK (0) is _not_ the upper value in a compound pdt_s. */
425 bool sg_pdt_s_eq(int l_pdt_s, int r_pdt_s);
426 
427 extern FILE * sg_warnings_strm;
428 
429 void sg_set_warnings_strm(FILE * warnings_strm);
430 
431 /* Given a SCSI command pointed to by cdbp of sz bytes this function forms a
432  * SCSI command in ASCII hex surrounded by square brackets in 'b'. 'b' is at
433  * least blen bytes long. If cmd_name is true then the command is prefixed
434  * by its SCSI command name (e.g.  "VERIFY(10) [2f ...]". The command is
435  * shown as spaced separated pairs of hexadecimal digits (i.e. 0-9, a-f).
436  * Each pair represents byte. The leftmost pair of digits is cdbp[0] . If
437  * sz <= 0 then this function tries to guess the length of the command. */
438 char *
439 sg_get_command_str(const uint8_t * cdbp, int sz, bool cmd_name, int blen,
440                    char * b);
441 
442 /* The following "print" functions send ASCII to 'sg_warnings_strm' file
443  * descriptor (default value is stderr). 'leadin' is string prepended to
444  * each line printed out, NULL treated as "". */
445 void sg_print_command_len(const uint8_t * command, int len);
446 void sg_print_command(const uint8_t * command);
447 void sg_print_scsi_status(int scsi_status);
448 
449 /* DSENSE is 'descriptor sense' as opposed to the older 'fixed sense'. Reads
450  * environment variable SG3_UTILS_DSENSE. Only (currently) used in SNTL. */
451 bool sg_get_initial_dsense(void);
452 
453 /* 'leadin' is string prepended to each line printed out, NULL treated as
454  * "". N.B. prior to sg3_utils v 1.42 'leadin' was only prepended to the
455  * first line printed. */
456 void sg_print_sense(const char * leadin, const uint8_t * sense_buffer,
457                     int sb_len, bool raw_info);
458 
459 /* This examines exit_status and if an error message is known it is output
460  * to stdout/stderr and true is returned. If no error message is
461  * available nothing is output and false is returned. If exit_status is
462  * zero (no error) nothing is output and true is returned. If exit_status
463  * is negative then nothing is output and false is returned. If leadin is
464  * non-NULL then it is printed before the error message. All messages are
465  * a single line with a trailing LF. */
466 bool sg_if_can2stdout(const char * leadin, int exit_status);
467 bool sg_if_can2stderr(const char * leadin, int exit_status);
468 
469 /* This examines exit_status and if an error message is known it is output
470  * as a string to 'b' and true is returned. If 'longer' is true and extra
471  * information is available then it is added to the output. If no error
472  * message is available a null character is output and false is returned.
473  * If exit_status is zero (no error) and 'longer' is true then the string
474  * 'No errors' is output; if 'longer' is false then a null character is
475  * output; in both cases true is returned. If exit_status is negative then
476  * a null character is output and false is returned. All messages are a
477  * single line (less than 80 characters) with no trailing LF. The output
478  * string including the trailing null character is no longer than b_len. */
479 bool sg_exit2str(int exit_status, bool longer, int b_len, char * b);
480 
481 /* Utilities can use these exit status values for syntax errors and
482  * file (device node) problems (e.g. not found or permissions). */
483 #define SG_LIB_SYNTAX_ERROR 1   /* command line syntax problem */
484 
485 /* The sg_err_category_sense() function returns one of the following.
486  * These may be used as exit status values (from a process). Notice that
487  * some of the lower values correspond to SCSI sense key values. */
488 #define SG_LIB_CAT_CLEAN 0      /* No errors or other information */
489 #define SG_LIB_OK_TRUE SG_LIB_CAT_CLEAN  /* No error, reporting true */
490 /* Value 1 left unused for utilities to use SG_LIB_SYNTAX_ERROR */
491 #define SG_LIB_CAT_NOT_READY 2  /* sense key: not ready, see 12 and 13
492                                  *  [sk,asc,ascq: 0x2,<most>,<most>] */
493 #define SG_LIB_CAT_MEDIUM_HARD 3 /* medium or hardware error, blank check
494                                   *       [sk,asc,ascq: 0x3/0x4/0x8,*,*] */
495 #define SG_LIB_CAT_ILLEGAL_REQ 5 /* Illegal request (other than invalid
496                                   * opcode):   [sk,asc,ascq: 0x5,*,*] */
497 #define SG_LIB_CAT_UNIT_ATTENTION 6 /* sense key, device state changed
498                                      *       [sk,asc,ascq: 0x6,*,*] */
499         /* was SG_LIB_CAT_MEDIA_CHANGED earlier [sk,asc,ascq: 0x6,0x28,*] */
500 #define SG_LIB_CAT_DATA_PROTECT 7 /* sense key, media write protected?
501                                    *       [sk,asc,ascq: 0x7,*,*] */
502 #define SG_LIB_CAT_INVALID_OP 9 /* (Illegal request,) Invalid opcode:
503                                  *       [sk,asc,ascq: 0x5,0x20,0x0] */
504 #define SG_LIB_CAT_COPY_ABORTED 10 /* sense key, some data transferred
505                                     *       [sk,asc,ascq: 0xa,*,*] */
506 #define SG_LIB_CAT_ABORTED_COMMAND 11 /* interpreted from sense buffer
507                                        *       [sk,asc,ascq: 0xb,! 0x10,*] */
508 #define SG_LIB_CAT_STANDBY 12   /* sense key: not ready, special case
509                                  *      [sk,asc, ascq: 0x2, 0x4, 0xb] */
510 #define SG_LIB_CAT_UNAVAILABLE 13 /* sense key: not ready, special case
511                                    *      [sk,asc, ascq: 0x2, 0x4, 0xc] */
512 #define SG_LIB_CAT_MISCOMPARE 14 /* sense key, probably verify
513                                   *       [sk,asc,ascq: 0xe,*,*] */
514 #define SG_LIB_FILE_ERROR 15    /* device or other file problem */
515 /* for 17 and 18, see below */
516 #define SG_LIB_CAT_NO_SENSE 20  /* sense data with key of "no sense"
517                                  *       [sk,asc,ascq: 0x0,*,*] */
518 #define SG_LIB_CAT_RECOVERED 21 /* Successful command after recovered err
519                                  *       [sk,asc,ascq: 0x1,*,*] */
520 #define SG_LIB_LBA_OUT_OF_RANGE 22 /* Illegal request, LBA Out Of Range
521                                     *    [sk,asc,ascq: 0x5,0x21,0x0] */
522 #define SG_LIB_CAT_RES_CONFLICT SAM_STAT_RESERVATION_CONFLICT
523                                 /* 24: this is a SCSI status, not sense.
524                                  * It indicates reservation by another
525                                  * machine blocks this command */
526 #define SG_LIB_CAT_CONDITION_MET 25 /* SCSI status, not sense key.
527                                      * Only from PRE-FETCH (SBC-4) */
528 #define SG_LIB_CAT_BUSY       26 /* SCSI status, not sense. Invites retry */
529 #define SG_LIB_CAT_TS_FULL    27 /* SCSI status, not sense. Wait then retry */
530 #define SG_LIB_CAT_ACA_ACTIVE 28 /* SCSI status; ACA seldom used */
531 #define SG_LIB_CAT_TASK_ABORTED 29 /* SCSI status, this command aborted by? */
532 #define SG_LIB_CONTRADICT 31    /* error involving two or more cl options */
533 #define SG_LIB_LOGIC_ERROR 32   /* unexpected situation in code */
534 /* for 33 see SG_LIB_CAT_TIMEOUT below */
535 #define SG_LIB_WINDOWS_ERR 34   /* Windows error number don't fit in 7 bits so
536                                  * map to a single value for exit statuses */
537 #define SG_LIB_TRANSPORT_ERROR 35       /* driver or interconnect */
538 #define SG_LIB_OK_FALSE 36      /* no error, reporting false (cf. no error,
539                                  * reporting true is SG_LIB_OK_TRUE(0) ) */
540 #define SG_LIB_CAT_PROTECTION 40 /* subset of aborted command (for PI, DIF)
541                                   *       [sk,asc,ascq: 0xb,0x10,*] */
542 /* 47: flock error used in ddpt utility */
543 #define SG_LIB_NVME_STATUS 48   /* NVMe Status Field (SF) other than 0 */
544 #define SG_LIB_WILD_RESID 49    /* Residual value for data-in transfer of a
545                                  * SCSI command is nonsensical */
546 #define SG_LIB_OS_BASE_ERR 50   /* in Linux: values found in:
547                                  * include/uapi/asm-generic/errno-base.h
548                                  * Example: ENOMEM reported as 62 (=50+12)
549                                  * if errno > 46 then use this value */
550 /* 51-->96 set aside for Unix errno values shifted by SG_LIB_OS_BASE_ERR */
551 #define SG_LIB_CAT_MALFORMED 97 /* Response to SCSI command malformed */
552 #define SG_LIB_CAT_SENSE 98     /* Something else is in the sense buffer */
553 #define SG_LIB_CAT_OTHER 99     /* Some other error/warning has occurred
554                                  * (e.g. a transport or driver error) */
555 /* 100 to 120 (inclusive) used by ddpt utility */
556 #define SG_LIB_UNUSED_ABOVE 120  /* Put extra errors in holes below this */
557 
558 /* Returns a SG_LIB_CAT_* value. If cannot decode sense_buffer or a less
559  * common sense key then return SG_LIB_CAT_SENSE .*/
560 int sg_err_category_sense(const uint8_t * sense_buffer, int sb_len);
561 
562 /* Here are some additional sense data categories that are not returned
563  * by sg_err_category_sense() but are returned by some related functions. */
564 #define SG_LIB_CAT_ILLEGAL_REQ_WITH_INFO 17 /* Illegal request (other than */
565                                 /* invalid opcode) plus 'info' field: */
566                                 /*  [sk,asc,ascq: 0x5,*,*] */
567 #define SG_LIB_CAT_MEDIUM_HARD_WITH_INFO 18 /* medium or hardware error */
568                                 /* sense key plus 'info' field: */
569                                 /*       [sk,asc,ascq: 0x3/0x4,*,*] */
570 #define SG_LIB_CAT_TIMEOUT 33   /* SCSI command timeout */
571 #define SG_LIB_CAT_PROTECTION_WITH_INFO 41 /* aborted command sense key, */
572                                 /* protection plus 'info' field: */
573                                 /*  [sk,asc,ascq: 0xb,0x10,*] */
574 
575 /* Yield string associated with sense category. Returns 'buff' (or pointer
576  * to "Bad sense category" if 'buff' is NULL). If sense_cat unknown then
577  * yield "Sense category: <sense_cat)val>" string. The original 'sense
578  * category' concept has been expanded to most detected errors and is
579  * returned by these utilities as their exit status value (an (unsigned)
580  * 8 bit value where 0 means good (i.e. no errors)).  Uses the
581  * sg_exit2str() function. */
582 const char * sg_get_category_sense_str(int sense_cat, int buff_len,
583                                        char * buff, int verbose);
584 
585 
586 /* Iterates to next designation descriptor in the device identification
587  * VPD page. The 'initial_desig_desc' should point to start of first
588  * descriptor with 'page_len' being the number of valid bytes in that
589  * and following descriptors. To start, 'off' should point to a negative
590  * value, thereafter it should point to the value yielded by the previous
591  * call. If 0 returned then 'initial_desig_desc + *off' should be a valid
592  * descriptor; returns -1 if normal end condition and -2 for an abnormal
593  * termination. Matches association, designator_type and/or code_set when
594  * any of those values are greater than or equal to zero. */
595 int sg_vpd_dev_id_iter(const uint8_t * initial_desig_desc, int page_len,
596                        int * off, int m_assoc, int m_desig_type,
597                        int m_code_set);
598 
599 
600 /* <<< General purpose (i.e. not SCSI specific) utility functions >>> */
601 
602 /* Always returns valid string even if errnum is wild (or library problem).
603  * If errnum is negative, flip its sign. */
604 char * safe_strerror(int errnum);
605 
606 /* Not all platforms support the Unix sleep(seconds) function. */
607 void sg_sleep_secs(int num_secs);
608 
609 /* There are several SCSI commands that are very destructive for the user
610  * data stored on a device. The FORMAT UNIT command is the prime example
611  * but there are an increasing number of newer SCSI commands that remove or
612  * destroy some or all of the user's data. This function takes 15 seconds,
613  * divided into three parts, saying that 'cmd_name' will be executed on
614  * 'dev_name' and then waits for 5 seconds inviting the user to press
615  * control-C to abort the operation. After three such prompts the function
616  * returns and the utility start to execute the "dangerous" SCSI command,
617  * Utilities that use this function usually have a --quick option to bypass
618  * this call. That may be appropriate if the utility in question is called
619  * from a script or in background processing. If 'stress_all' is true then
620  * state "ALL data" will be lost, if false drop the "ALL". */
621 void
622 sg_warn_and_wait(const char * cmd_name, const char * dev_name,
623                  bool stress_all);
624 
625 
626 /* Print (to stdout) 'str' of bytes in hex, 16 bytes per line optionally
627  * followed at the right hand side of the line with an ASCII interpretation.
628  * Each line is prefixed with an address, starting at 0 for str[0]..str[15].
629  * All output numbers are in hex.
630  * 'no_ascii' selects on of  3 output format types:
631  *     > 0     each line has address then up to 16 ASCII-hex bytes
632  *     = 0     in addition, the bytes are listed in ASCII to the right
633  *     < 0     only the ASCII-hex bytes are listed (i.e. without address)
634 */
635 void dStrHex(const char * str, int len, int no_ascii);
636 
637 /* Print (to sg_warnings_strm (stderr)) 'str' of bytes in hex, 16 bytes per
638  * line optionally followed at right by its ASCII interpretation. Same
639  * logic as dStrHex() with different output stream (i.e. stderr). */
640 void dStrHexErr(const char * str, int len, int no_ascii);
641 
642 /* Read binary starting at 'str' for 'len' bytes and output as ASCII
643  * hexadecimal into file pointer (fp). 16 bytes per line are output with an
644  * additional space between 8th and 9th byte on each line (for readability).
645  * 'no_ascii' selects one of 3 output format types as shown in dStrHex() . */
646 void dStrHexFp(const char* str, int len, int no_ascii, FILE * fp);
647 
648 /* Read 'len' bytes from 'str' and output as ASCII-Hex bytes (space separated)
649  * to 'b' not to exceed 'b_len' characters. Each line starts with 'leadin'
650  * (NULL for no leadin) and there are 16 bytes per line with an extra space
651  * between the 8th and 9th bytes. 'oformat' is 0 for repeat in printable ASCII
652  * ('.' for non printable chars) to right of each line; 1 don't (so just
653  * output ASCII hex). If 'oformat' is 2 output same as 1 but any LFs are
654  * replaced by space (and trailing spaces are trimmed). Note that an address
655  * is _not_ printed on each line preceding the hex data. Returns number of
656  * bytes written to 'b' excluding the trailing '\0'. The only difference
657  * between dStrHexStr() and hex2str() is the type of the first argument. */
658 int dStrHexStr(const char * str, int len, const char * leadin, int oformat,
659                int cb_len, char * cbp);
660 int hex2str(const uint8_t * b_str, int len, const char * leadin, int oformat,
661             int cb_len, char * cbp);
662 
663 /* Similar to hex2str() but outputs to file pointed to be fp */
664 void hex2fp(const uint8_t * b_str, int len, const char * leadin, int oformat,
665             FILE * fp);
666 
667 /* The following 2 functions are equivalent to dStrHex() and dStrHexErr()
668  * respectively. The difference is only the type of the first of argument:
669  * uint8_t instead of char. The name of the argument is changed to b_str to
670  * stress it is a pointer to the start of a binary string. */
671 void hex2stdout(const uint8_t * b_str, int len, int no_ascii);
672 void hex2stderr(const uint8_t * b_str, int len, int no_ascii);
673 
674 /* Read ASCII hex bytes or binary from fname (a file named '-' taken as
675  * stdin). If reading ASCII hex then there should be either one entry per
676  * line or a comma, space, hyphen or tab separated list of bytes. If no_space
677  * is set then a string of ACSII hex digits is expected, 2 per byte.
678  * Everything from and including a '#' on a line is ignored. Returns 0 if ok,
679  * or an error code. If the error code is SG_LIB_LBA_OUT_OF_RANGE then mp_arr
680  * would be exceeded and both mp_arr and mp_arr_len are written to.
681  * The max_arr_len_and argument may carry extra information: when it is
682  * negative its absolute value is used for the maximum number of bytes to
683  * write to mp_arr _and_ the first hexadecimal value on each line is skipped.
684  * Many hexadecimal output programs place a running address (index) as the
685  * first field on each line. When as_binary and/or no_space are true, the
686  * absolute value of max_arr_len_and is used. */
687 int sg_f2hex_arr(const char * fname, bool as_binary, bool no_space,
688                  uint8_t * mp_arr, int * mp_arr_len, int max_arr_len_and);
689 
690 /* Returns true when executed on big endian machine; else returns false.
691  * Useful for displaying ATA identify words (which need swapping on a
692  * big endian machine). */
693 bool sg_is_big_endian();
694 
695 /* Returns true if byte sequence starting at bp with a length of b_len is
696  * all zeros (for sg_all_zeros()) or all 0xff_s (for sg_all_ffs());
697  * otherwise returns false. If bp is NULL or b_len <= 0 returns false. */
698 bool sg_all_zeros(const uint8_t * bp, int b_len);
699 bool sg_all_ffs(const uint8_t * bp, int b_len);
700 
701 /* Extract character sequence from ATA words as in the model string
702  * in a IDENTIFY DEVICE response. Returns number of characters
703  * written to 'ochars' before 0 character is found or 'num' words
704  * are processed. */
705 int sg_ata_get_chars(const uint16_t * word_arr, int start_word,
706                      int num_words, bool is_big_endian, char * ochars);
707 
708 /* Print (to stdout) 16 bit 'words' in hex, 8 words per line optionally
709  * followed at the right hand side of the line with an ASCII interpretation
710  * (pairs of ASCII characters in big endian order (upper first)).
711  * Each line is prefixed with an address, starting at 0.
712  * All output numbers are in hex. 'no_ascii' allows for 3 output types:
713  *     > 0     each line has address then up to 8 ASCII-hex words
714  *     = 0     in addition, the words are listed in ASCII pairs to the right
715  *     = -1    only the ASCII-hex words are listed (i.e. without address)
716  *     = -2    only the ASCII-hex words, formatted for "hdparm --Istdin"
717  *     < -2    same as -1
718  * If 'swapb' is true then bytes in each word swapped. Needs to be set
719  * for ATA IDENTIFY DEVICE response on big-endian machines.
720 */
721 void dWordHex(const uint16_t * words, int num, int no_ascii, bool swapb);
722 
723 /* If the number in 'buf' can not be decoded or the multiplier is unknown
724  * then -1 is returned. Accepts a hex prefix (0x or 0X) or a decimal
725  * multiplier suffix (as per GNU's dd (since 2002: SI and IEC 60027-2)).
726  * Main (SI) multipliers supported: K, M, G. Ignore leading spaces and
727  * tabs; accept comma, hyphen, space, tab and hash as terminator.
728  * Handles zero and positive values up to 2**31-1 .
729  * Experimental: left argument (must in with hexadecimal digit) added
730  * to, or multiplied, by right argument. No embedded spaces.
731  * Examples: '3+1k' (evaluates to 1027) and '0xf+0x3'. */
732 int sg_get_num(const char * buf);
733 
734 /* If the number in 'buf' can not be decoded then -1 is returned. Accepts a
735  * hex prefix (0x or 0X) or a 'h' (or 'H') suffix; otherwise decimal is
736  * assumed. Does not accept multipliers. Accept a comma (","), hyphen ("-"),
737  * a whitespace or newline as terminator. Only decimal numbers can represent
738  * negative numbers and '-1' must be treated separately. */
739 int sg_get_num_nomult(const char * buf);
740 
741 /* If the number in 'buf' can not be decoded or the multiplier is unknown
742  * then -1LL is returned. Accepts a hex prefix (0x or 0X), hex suffix
743  * (h or H), or a decimal multiplier suffix (as per GNU's dd (since 2002:
744  * SI and IEC 60027-2)).  Main (SI) multipliers supported: K, M, G, T, P
745  * and E. Ignore leading spaces and tabs; accept comma, hyphen, space, tab
746  * and hash as terminator. Handles zero and positive values up to 2**63-1 .
747  * Experimental: the left argument (must end in with hexadecimal digit)
748  * added to, or multiplied by, the right argument. No embedded spaces.
749  * Examples: '3+1k' (evaluates to 1027) and '0xf+0x3'. */
750 int64_t sg_get_llnum(const char * buf);
751 
752 /* If the number in 'buf' can not be decoded then -1 is returned. Accepts a
753  * hex prefix (0x or 0X) or a 'h' (or 'H') suffix; otherwise decimal is
754  * assumed. Does not accept multipliers. Accept a comma (","), hyphen ("-"),
755  * a whitespace or newline as terminator. Only decimal numbers can represent
756  * negative numbers and '-1' must be treated separately. */
757 int64_t sg_get_llnum_nomult(const char * buf);
758 
759 /* Returns pointer to heap (or NULL) that is aligned to a align_to byte
760  * boundary. Sends back *buff_to_free pointer in third argument that may be
761  * different from the return value. If it is different then the *buff_to_free
762  * pointer should be freed (rather than the returned value) when the heap is
763  * no longer needed. If align_to is 0 then aligns to OS's page size. Sets all
764  * returned heap to zeros. If num_bytes is 0 then set to page size. */
765 uint8_t * sg_memalign(uint32_t num_bytes, uint32_t align_to,
766                       uint8_t ** buff_to_free, bool vb);
767 
768 /* Returns OS page size in bytes. If uncertain returns 4096. */
769 uint32_t sg_get_page_size(void);
770 
771 /* If byte_count is 0 or less then the OS page size is used as denominator.
772  * Returns true  if the remainder of ((unsigned)pointer % byte_count) is 0,
773  * else returns false. */
774 bool sg_is_aligned(const void * pointer, int byte_count);
775 
776 /* Does similar job to sg_get_unaligned_be*() but this function starts at
777  * a given start_bit (i.e. within byte, so 7 is MSbit of byte and 0 is LSbit)
778  * offset. Maximum number of num_bits is 64. For example, these two
779  * invocations are equivalent (and should yield the same result);
780  *       sg_get_big_endian(from_bp, 7, 16)
781  *       sg_get_unaligned_be16(from_bp)  */
782 uint64_t sg_get_big_endian(const uint8_t * from_bp,
783                            int start_bit /* 0 to 7 */,
784                            int num_bits /* 1 to 64 */);
785 
786 /* Does similar job to sg_put_unaligned_be*() but this function starts at
787  * a given start_bit offset. Maximum number of num_bits is 64. Preserves
788  * residual bits in partially written bytes. start_bit 7 is MSb. */
789 void sg_set_big_endian(uint64_t val, uint8_t * to, int start_bit /* 0 to 7 */,
790                        int num_bits /* 1 to 64 */);
791 
792 /* If os_err_num is within bounds then the returned value is 'os_err_num +
793  * SG_LIB_OS_BASE_ERR' otherwise SG_LIB_OS_BASE_ERR is returned. If
794  * os_err_num is 0 then 0 is returned. */
795 int sg_convert_errno(int os_err_num);
796 
797 
798 /* <<< Architectural support functions [is there a better place?] >>> */
799 
800 /* Non Unix OSes distinguish between text and binary files.
801  * Set text mode on fd. Does nothing in Unix. Returns negative number on
802  * failure. */
803 int sg_set_text_mode(int fd);
804 
805 /* Set binary mode on fd. Does nothing in Unix. Returns negative number on
806  * failure. */
807 int sg_set_binary_mode(int fd);
808 
809 #ifdef __cplusplus
810 }
811 #endif
812 
813 #endif          /* SG_LIB_H */
814