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 * This program issues the SCSI command WRITE AND VERIFY to a given SCSI
10 * device. It sends the command with the logical block address passed as the
11 * LBA argument, for the given number of blocks. The number of bytes sent is
12 * supplied separately, either by the size of the given file (IF) or
13 * explicitly with ILEN.
14 *
15 * This code was contributed by Bruno Goncalves
16 */
17
18 #include <unistd.h>
19 #include <fcntl.h>
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <stdarg.h>
23 #include <stdbool.h>
24 #include <string.h>
25 #include <errno.h>
26 #include <limits.h>
27 #include <getopt.h>
28 #include <sys/types.h>
29 #include <sys/stat.h>
30 #define __STDC_FORMAT_MACROS 1
31 #include <inttypes.h>
32
33 #ifdef HAVE_CONFIG_H
34 #include "config.h"
35 #endif
36
37 #include "sg_lib.h"
38 #include "sg_pt.h"
39 #include "sg_cmds_basic.h"
40 #include "sg_unaligned.h"
41 #include "sg_pr2serr.h"
42
43 static const char * version_str = "1.21 20220127";
44
45
46 #define ME "sg_write_verify: "
47
48 #define SENSE_BUFF_LEN 64 /* Arbitrary, could be larger */
49
50 #define WRITE_VERIFY10_CMD 0x2e
51 #define WRITE_VERIFY10_CMDLEN 10
52 #define WRITE_VERIFY16_CMD 0x8e
53 #define WRITE_VERIFY16_CMDLEN 16
54
55 #define WRPROTECT_MASK (0x7)
56 #define WRPROTECT_SHIFT (5)
57
58 #define DEF_TIMEOUT_SECS 60
59
60
61 static struct option long_options[] = {
62 {"16", no_argument, 0, 'S'},
63 {"bytchk", required_argument, 0, 'b'},
64 {"dpo", no_argument, 0, 'd'},
65 {"group", required_argument, 0, 'g'},
66 {"help", no_argument, 0, 'h'},
67 {"ilen", required_argument, 0, 'I'},
68 {"in", required_argument, 0, 'i'},
69 {"lba", required_argument, 0, 'l'},
70 {"num", required_argument, 0, 'n'},
71 {"repeat", no_argument, 0, 'R'},
72 {"timeout", required_argument, 0, 't'},
73 {"verbose", no_argument, 0, 'v'},
74 {"version", no_argument, 0, 'V'},
75 {"wrprotect", required_argument, 0, 'w'},
76 {0, 0, 0, 0},
77 };
78
79
80 static void
usage()81 usage()
82 {
83 pr2serr("Usage: sg_write_verify [--16] [--bytchk=BC] [--dpo] [--group=GN] "
84 "[--help]\n"
85 " [--ilen=IL] [--in=IF] --lba=LBA "
86 "[--num=NUM]\n"
87 " [--repeat] [--timeout=TO] [--verbose] "
88 "[--version]\n"
89 " [--wrprotect=WPR] DEVICE\n"
90 " where:\n"
91 " --16|-S do WRITE AND VERIFY(16) (default: 10)\n"
92 " --bytchk=BC|-b BC set BYTCHK field (default: 0)\n"
93 " --dpo|-d set DPO bit (default: 0)\n"
94 " --group=GN|-g GN GN is group number (default: 0)\n"
95 " --help|-h print out usage message\n"
96 " --ilen=IL| -I IL input (file) length in bytes, becomes "
97 "data-out\n"
98 " buffer length (def: deduced from IF "
99 "size)\n"
100 " --in=IF|-i IF IF is a file containing the data to "
101 "be written\n"
102 " --lba=LBA|-l LBA LBA of the first block to write "
103 "and verify;\n"
104 " no default, must be given\n"
105 " --num=NUM|-n NUM logical blocks to write and verify "
106 "(def: 1)\n"
107 " --repeat|-R while IF still has data to read, send "
108 "another\n"
109 " command, bumping LBA with up to NUM "
110 "blocks again\n"
111 " --timeout=TO|-t TO command timeout in seconds (def: 60)\n"
112 " --verbose|-v increase verbosity\n"
113 " --version|-V print version string then exit\n"
114 " --wrprotect|-w WPR WPR is the WRPROTECT field value "
115 "(def: 0)\n\n"
116 "Performs a SCSI WRITE AND VERIFY (10 or 16) command on DEVICE, "
117 "startings\nat LBA for NUM logical blocks. More commands "
118 "performed only if '--repeat'\noption given. Data to be written "
119 "is fetched from the IF file.\n"
120 );
121 }
122
123 /* Invokes a SCSI WRITE AND VERIFY according with CDB. Returns 0 -> success,
124 * various SG_LIB_CAT_* positive values or -1 -> other errors */
125 static int
run_scsi_transaction(int sg_fd,const uint8_t * cdbp,int cdb_len,uint8_t * dop,int do_len,int timeout,bool noisy,int verbose)126 run_scsi_transaction(int sg_fd, const uint8_t *cdbp, int cdb_len,
127 uint8_t *dop, int do_len, int timeout,
128 bool noisy, int verbose)
129 {
130 int res, sense_cat, ret;
131 struct sg_pt_base * ptvp;
132 uint8_t sense_b[SENSE_BUFF_LEN] SG_C_CPP_ZERO_INIT;
133 char b[32];
134
135 snprintf(b, sizeof(b), "Write and verify(%d)", cdb_len);
136 if (verbose) {
137 char d[128];
138
139 pr2serr(" %s cdb: %s\n", b,
140 sg_get_command_str(cdbp, cdb_len, false, sizeof(d), d));
141 if ((verbose > 2) && dop && do_len) {
142 pr2serr(" Data out buffer [%d bytes]:\n", do_len);
143 hex2stderr(dop, do_len, -1);
144 }
145 }
146 ptvp = construct_scsi_pt_obj();
147 if (NULL == ptvp) {
148 pr2serr("%s: out of memory\n", b);
149 return -1;
150 }
151 set_scsi_pt_cdb(ptvp, cdbp, cdb_len);
152 set_scsi_pt_sense(ptvp, sense_b, sizeof(sense_b));
153 set_scsi_pt_data_out(ptvp, dop, do_len);
154 res = do_scsi_pt(ptvp, sg_fd, timeout, verbose);
155 ret = sg_cmds_process_resp(ptvp, b, res, noisy, verbose, &sense_cat);
156 if (-1 == ret) {
157 if (get_scsi_pt_transport_err(ptvp))
158 ret = SG_LIB_TRANSPORT_ERROR;
159 else
160 ret = sg_convert_errno(get_scsi_pt_os_err(ptvp));
161 } else if (-2 == ret) {
162 switch (sense_cat) {
163 case SG_LIB_CAT_RECOVERED:
164 case SG_LIB_CAT_NO_SENSE:
165 ret = 0;
166 break;
167 case SG_LIB_CAT_MEDIUM_HARD: /* write or verify failed */
168 {
169 bool valid;
170 int slen;
171 uint64_t ull = 0;
172
173 slen = get_scsi_pt_sense_len(ptvp);
174 valid = sg_get_sense_info_fld(sense_b, slen, &ull);
175 if (valid)
176 pr2serr("Medium or hardware error starting at lba=%"
177 PRIu64 " [0x%" PRIx64 "]\n", ull, ull);
178 }
179 ret = sense_cat;
180 break;
181 case SG_LIB_CAT_ILLEGAL_REQ:
182 if (verbose)
183 sg_print_command_len(cdbp, cdb_len);
184 /* FALL THROUGH */
185 case SG_LIB_CAT_PROTECTION: /* PI failure */
186 case SG_LIB_CAT_MISCOMPARE: /* only in bytchk=1 case */
187 default:
188 ret = sense_cat;
189 break;
190 }
191 } else
192 ret = 0;
193
194 destruct_scsi_pt_obj(ptvp);
195 return ret;
196 }
197
198 /* Invokes a SCSI WRITE AND VERIFY (10) command (SBC). Returns 0 -> success,
199 * various SG_LIB_CAT_* positive values or -1 -> other errors */
200 static int
sg_ll_write_verify10(int sg_fd,int wrprotect,bool dpo,int bytchk,unsigned int lba,int num_lb,int group,uint8_t * dop,int do_len,int timeout,bool noisy,int verbose)201 sg_ll_write_verify10(int sg_fd, int wrprotect, bool dpo, int bytchk,
202 unsigned int lba, int num_lb, int group,
203 uint8_t *dop, int do_len, int timeout,
204 bool noisy, int verbose)
205 {
206 int ret;
207 uint8_t wv_cdb[WRITE_VERIFY10_CMDLEN];
208
209 memset(wv_cdb, 0, WRITE_VERIFY10_CMDLEN);
210 wv_cdb[0] = WRITE_VERIFY10_CMD;
211 wv_cdb[1] = ((wrprotect & WRPROTECT_MASK) << WRPROTECT_SHIFT);
212 if (dpo)
213 wv_cdb[1] |= 0x10;
214 if (bytchk)
215 wv_cdb[1] |= ((bytchk & 0x3) << 1);
216
217 sg_put_unaligned_be32((uint32_t)lba, wv_cdb + 2);
218 wv_cdb[6] = group & GRPNUM_MASK;
219 sg_put_unaligned_be16((uint16_t)num_lb, wv_cdb + 7);
220 ret = run_scsi_transaction(sg_fd, wv_cdb, sizeof(wv_cdb), dop, do_len,
221 timeout, noisy, verbose);
222 return ret;
223 }
224
225 /* Invokes a SCSI WRITE AND VERIFY (16) command (SBC). Returns 0 -> success,
226 * various SG_LIB_CAT_* positive values or -1 -> other errors */
227 static int
sg_ll_write_verify16(int sg_fd,int wrprotect,bool dpo,int bytchk,uint64_t llba,int num_lb,int group,uint8_t * dop,int do_len,int timeout,bool noisy,int verbose)228 sg_ll_write_verify16(int sg_fd, int wrprotect, bool dpo, int bytchk,
229 uint64_t llba, int num_lb, int group, uint8_t *dop,
230 int do_len, int timeout, bool noisy, int verbose)
231 {
232 int ret;
233 uint8_t wv_cdb[WRITE_VERIFY16_CMDLEN];
234
235
236 memset(wv_cdb, 0, sizeof(wv_cdb));
237 wv_cdb[0] = WRITE_VERIFY16_CMD;
238 wv_cdb[1] = ((wrprotect & WRPROTECT_MASK) << WRPROTECT_SHIFT);
239 if (dpo)
240 wv_cdb[1] |= 0x10;
241 if (bytchk)
242 wv_cdb[1] |= ((bytchk & 0x3) << 1);
243
244 sg_put_unaligned_be64(llba, wv_cdb + 2);
245 sg_put_unaligned_be32((uint32_t)num_lb, wv_cdb + 10);
246 wv_cdb[14] = group & GRPNUM_MASK;
247 ret = run_scsi_transaction(sg_fd, wv_cdb, sizeof(wv_cdb), dop, do_len,
248 timeout, noisy, verbose);
249 return ret;
250 }
251
252 /* Returns file descriptor ( >= 0) if successful. Else a negated sg3_utils
253 * error code is returned. */
254 static int
open_if(const char * fn,int got_stdin)255 open_if(const char * fn, int got_stdin)
256 {
257 int fd, err;
258
259 if (got_stdin)
260 fd = STDIN_FILENO;
261 else {
262 fd = open(fn, O_RDONLY);
263 if (fd < 0) {
264 err = errno;
265 pr2serr(ME "open error: %s: %s\n", fn, safe_strerror(err));
266 return -sg_convert_errno(err);
267 }
268 }
269 if (sg_set_binary_mode(fd) < 0) {
270 perror("sg_set_binary_mode");
271 return -SG_LIB_FILE_ERROR;
272 }
273 return fd;
274 }
275
276 int
main(int argc,char * argv[])277 main(int argc, char * argv[])
278 {
279 bool do_16 = false;
280 bool dpo = false;
281 bool first_time;
282 bool given_do_16 = false;
283 bool has_filename = false;
284 bool lba_given = false;
285 bool repeat = false;
286 bool verbose_given = false;
287 bool version_given = false;
288 int sg_fd, res, c, n;
289 int bytchk = 0;
290 int group = 0;
291 int ilen = -1;
292 int ifd = -1;
293 int b_p_lb = 512;
294 int ret = 1;
295 int timeout = DEF_TIMEOUT_SECS;
296 int tnum_lb_wr = 0;
297 int verbose = 0;
298 int wrprotect = 0;
299 uint32_t num_lb = 1;
300 uint32_t snum_lb = 1;
301 uint64_t llba = 0;
302 int64_t ll;
303 uint8_t * wvb = NULL;
304 uint8_t * wrkBuff = NULL;
305 uint8_t * free_wrkBuff = NULL;
306 const char * device_name = NULL;
307 const char * ifnp;
308 char cmd_name[32];
309
310 ifnp = ""; /* keep MinGW quiet */
311 while (1) {
312 int option_index = 0;
313
314 c = getopt_long(argc, argv, "b:dg:hi:I:l:n:RSt:w:vV", long_options,
315 &option_index);
316 if (c == -1)
317 break;
318
319 switch (c) {
320 case 'b':
321 /* Only bytchk=0 and =1 are meaningful for this command in
322 * sbc4r02 (not =2 nor =3) but that may change in the future. */
323 bytchk = sg_get_num(optarg);
324 if ((bytchk < 0) || (bytchk > 3)) {
325 pr2serr("argument to '--bytchk' expected to be 0 to 3\n");
326 return SG_LIB_SYNTAX_ERROR;
327 }
328 break;
329 case 'd':
330 dpo = true;
331 break;
332 case 'g':
333 group = sg_get_num(optarg);
334 if ((group < 0) || (group > 63)) {
335 pr2serr("argument to '--group' expected to be 0 to 63\n");
336 return SG_LIB_SYNTAX_ERROR;
337 }
338 break;
339 case 'h':
340 case '?':
341 usage();
342 return 0;
343 case 'i':
344 ifnp = optarg;
345 has_filename = true;
346 break;
347 case 'I':
348 ilen = sg_get_num(optarg);
349 if (-1 == ilen) {
350 pr2serr("bad argument to '--ilen'\n");
351 return SG_LIB_SYNTAX_ERROR;
352 }
353 break;
354 case 'l':
355 if (lba_given) {
356 pr2serr("must have one and only one '--lba'\n");
357 return SG_LIB_SYNTAX_ERROR;
358 }
359 ll = sg_get_llnum(optarg);
360 if (ll < 0) {
361 pr2serr("bad argument to '--lba'\n");
362 return SG_LIB_SYNTAX_ERROR;
363 }
364 llba = (uint64_t)ll;
365 lba_given = true;
366 break;
367 case 'n':
368 n = sg_get_num(optarg);
369 if (-1 == n) {
370 pr2serr("bad argument to '--num'\n");
371 return SG_LIB_SYNTAX_ERROR;
372 }
373 num_lb = (uint32_t)n;
374 break;
375 case 'R':
376 repeat = true;
377 break;
378 case 'S':
379 do_16 = true;
380 given_do_16 = true;
381 break;
382 case 't':
383 timeout = sg_get_num(optarg);
384 if (timeout < 1) {
385 pr2serr("bad argument to '--timeout'\n");
386 return SG_LIB_SYNTAX_ERROR;
387 }
388 break;
389 case 'v':
390 verbose_given = true;
391 ++verbose;
392 break;
393 case 'V':
394 version_given = true;
395 break;
396 case 'w':
397 wrprotect = sg_get_num(optarg);
398 if ((wrprotect < 0) || (wrprotect > 7)) {
399 pr2serr("wrprotect (%d) is out of range ( < %d)\n", wrprotect,
400 7);
401 return SG_LIB_SYNTAX_ERROR;
402 }
403
404 break;
405 default:
406 pr2serr("unrecognised option code 0x%x ??\n", c);
407 usage();
408 return SG_LIB_SYNTAX_ERROR;
409 }
410 }
411 if (optind < argc) {
412 if (NULL == device_name) {
413 device_name = argv[optind];
414 ++optind;
415 }
416 if (optind < argc) {
417 for (; optind < argc; ++optind)
418 pr2serr("Unexpected extra argument: %s\n", argv[optind]);
419 usage();
420 return SG_LIB_SYNTAX_ERROR;
421 }
422 }
423
424 #ifdef DEBUG
425 pr2serr("In DEBUG mode, ");
426 if (verbose_given && version_given) {
427 pr2serr("but override: '-vV' given, zero verbose and continue\n");
428 verbose_given = false;
429 version_given = false;
430 verbose = 0;
431 } else if (! verbose_given) {
432 pr2serr("set '-vv'\n");
433 verbose = 2;
434 } else
435 pr2serr("keep verbose=%d\n", verbose);
436 #else
437 if (verbose_given && version_given)
438 pr2serr("Not in DEBUG mode, so '-vV' has no special action\n");
439 #endif
440 if (version_given) {
441 pr2serr(ME "version: %s\n", version_str);
442 return 0;
443 }
444
445 if (NULL == device_name) {
446 pr2serr("Missing device name!\n\n");
447 usage();
448 return SG_LIB_SYNTAX_ERROR;
449 }
450 if (! lba_given) {
451 pr2serr("need a --lba=LBA option\n");
452 usage();
453 return SG_LIB_SYNTAX_ERROR;
454 }
455 if (repeat) {
456 if (! has_filename) {
457 pr2serr("with '--repeat' need '--in=IF' option\n");
458 usage();
459 return SG_LIB_CONTRADICT;
460 }
461 if (ilen < 1) {
462 pr2serr("with '--repeat' need '--ilen=ILEN' option\n");
463 usage();
464 return SG_LIB_CONTRADICT;
465 } else {
466 b_p_lb = ilen / num_lb;
467 if (b_p_lb < 64) {
468 pr2serr("calculated %d bytes per logical block, too small\n",
469 b_p_lb);
470 usage();
471 return SG_LIB_SYNTAX_ERROR;
472 }
473 }
474 }
475
476 sg_fd = sg_cmds_open_device(device_name, false /* rw */, verbose);
477 if (sg_fd < 0) {
478 ret = sg_convert_errno(-sg_fd);
479 pr2serr(ME "open error: %s: %s\n", device_name, safe_strerror(-sg_fd));
480 goto err_out;
481 }
482
483 if ((! do_16) && (llba > UINT_MAX))
484 do_16 = true;
485 if ((! do_16) && (num_lb > 0xffff))
486 do_16 = true;
487 snprintf(cmd_name, sizeof(cmd_name), "Write and verify(%d)",
488 (do_16 ? 16 : 10));
489 if (verbose && (! given_do_16) && do_16)
490 pr2serr("Switching to %s because LBA or NUM too large\n", cmd_name);
491 if (verbose) {
492 pr2serr("Issue %s to device %s\n\tilen=%d", cmd_name, device_name,
493 ilen);
494 if (ilen > 0)
495 pr2serr(" [0x%x]", ilen);
496 pr2serr(", lba=%" PRIu64 " [0x%" PRIx64 "]\n\twrprotect=%d, dpo=%d, "
497 "bytchk=%d, group=%d, repeat=%d\n", llba, llba, wrprotect,
498 (int)dpo, bytchk, group, (int)repeat);
499 }
500
501 first_time = true;
502 do {
503 if (first_time) {
504 //If a file with data to write has been provided
505 if (has_filename) {
506 struct stat a_stat;
507
508 if ((1 == strlen(ifnp)) && ('-' == ifnp[0])) {
509 ifd = STDIN_FILENO;
510 ifnp = "<stdin>";
511 if (verbose > 1)
512 pr2serr("Reading input data from stdin\n");
513 } else {
514 ifd = open_if(ifnp, 0);
515 if (ifd < 0) {
516 ret = -ifd;
517 goto err_out;
518 }
519 }
520 if (ilen < 1) {
521 if (fstat(ifd, &a_stat) < 0) {
522 pr2serr("Could not fstat(%s)\n", ifnp);
523 goto err_out;
524 }
525 if (! S_ISREG(a_stat.st_mode)) {
526 pr2serr("Cannot determine IF size, please give "
527 "'--ilen='\n");
528 goto err_out;
529 }
530 ilen = (int)a_stat.st_size;
531 if (ilen < 1) {
532 pr2serr("%s file size too small\n", ifnp);
533 goto err_out;
534 } else if (verbose)
535 pr2serr("Using file size of %d bytes\n", ilen);
536 }
537 if (NULL == (wrkBuff = (uint8_t *)sg_memalign(ilen, 0,
538 &free_wrkBuff, verbose > 3))) {
539 pr2serr(ME "out of memory\n");
540 ret = sg_convert_errno(ENOMEM);
541 goto err_out;
542 }
543 wvb = (uint8_t *)wrkBuff;
544 res = read(ifd, wvb, ilen);
545 if (res < 0) {
546 pr2serr("Could not read from %s", ifnp);
547 goto err_out;
548 }
549 if (res < ilen) {
550 pr2serr("Read only %d bytes (expected %d) from %s\n", res,
551 ilen, ifnp);
552 if (repeat)
553 pr2serr("Will scale subsequent pieces when "
554 "repeat=true, but this is first\n");
555 goto err_out;
556 }
557 } else {
558 if (ilen < 1) {
559 if (verbose)
560 pr2serr("Default write length to %d*%d=%d bytes\n",
561 num_lb, 512, 512 * num_lb);
562 ilen = 512 * num_lb;
563 }
564 if (NULL == (wrkBuff = (uint8_t *)sg_memalign(ilen, 0,
565 &free_wrkBuff, verbose > 3))) {
566 pr2serr(ME "out of memory\n");
567 ret = sg_convert_errno(ENOMEM);
568 goto err_out;
569 }
570 wvb = (uint8_t *)wrkBuff;
571 /* Not sure about this: default contents to 0xff bytes */
572 memset(wrkBuff, 0xff, ilen);
573 }
574 first_time = false;
575 snum_lb = num_lb;
576 } else { /* repeat=true, first_time=false, must be reading file */
577 llba += snum_lb;
578 res = read(ifd, wvb, ilen);
579 if (res < 0) {
580 pr2serr("Could not read from %s", ifnp);
581 goto err_out;
582 } else {
583 if (verbose > 1)
584 pr2serr("Subsequent read from %s got %d bytes\n", ifnp, res);
585 if (0 == res)
586 break;
587 if (res < ilen) {
588 snum_lb = (uint32_t)(res / b_p_lb);
589 n = res % b_p_lb;
590 if (0 != n)
591 pr2serr(">>> warning: ignoring last %d bytes of %s\n",
592 n, ifnp);
593 if (snum_lb < 1)
594 break;
595 }
596 }
597 }
598 if (do_16)
599 res = sg_ll_write_verify16(sg_fd, wrprotect, dpo, bytchk, llba,
600 snum_lb, group, wvb, ilen, timeout,
601 verbose > 0, verbose);
602 else
603 res = sg_ll_write_verify10(sg_fd, wrprotect, dpo, bytchk,
604 (unsigned int)llba, snum_lb, group,
605 wvb, ilen, timeout, verbose > 0,
606 verbose);
607 ret = res;
608 if (repeat && (0 == ret))
609 tnum_lb_wr += snum_lb;
610 if (ret || (snum_lb != num_lb))
611 break;
612 } while (repeat);
613
614 err_out:
615 if (repeat)
616 pr2serr("%d [0x%x] logical blocks written, in total\n", tnum_lb_wr,
617 tnum_lb_wr);
618 if (free_wrkBuff)
619 free(free_wrkBuff);
620 if ((ifd >= 0) && (STDIN_FILENO != ifd))
621 close(ifd);
622 res = sg_cmds_close_device(sg_fd);
623 if (res < 0) {
624 pr2serr("close error: %s\n", safe_strerror(-res));
625 if (0 == ret)
626 ret = sg_convert_errno(-res);
627 }
628 if (ret && (0 == verbose)) {
629 if (! sg_if_can2stderr("sg_write_verify failed: ", ret))
630 pr2serr("Some error occurred, try again with '-v' "
631 "or '-vv' for more information\n");
632 }
633 return (ret >= 0) ? ret : SG_LIB_CAT_OTHER;
634 }
635