]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/stored/btape.c
Fix Bacula bug #2020 overflow in btape -- Andreas Koch
[bacula/bacula] / bacula / src / stored / btape.c
1 /*
2    Bacula® - The Network Backup Solution
3
4    Copyright (C) 2000-2014 Free Software Foundation Europe e.V.
5
6    The main author of Bacula is Kern Sibbald, with contributions from many
7    others, a complete list can be found in the file AUTHORS.
8
9    You may use this file and others of this release according to the
10    license defined in the LICENSE file, which includes the Affero General
11    Public License, v3.0 ("AGPLv3") and some additional permissions and
12    terms pursuant to its AGPLv3 Section 7.
13
14    Bacula® is a registered trademark of Kern Sibbald.
15 */
16 /*
17  *
18  *   Bacula Tape manipulation program
19  *
20  *    Has various tape manipulation commands -- mostly for
21  *    use in determining how tapes really work.
22  *
23  *     Kern Sibbald, April MM
24  *
25  *   Note, this program reads stored.conf, and will only
26  *     talk to devices that are configured.
27  *
28  */
29
30 #include "bacula.h"
31 #include "stored.h"
32
33 #ifdef USE_VTAPE
34 #include "vtape_dev.h"
35 #endif
36
37 /* Dummy functions */
38 int generate_daemon_event(JCR *jcr, const char *event) { return 1; }
39 extern bool parse_sd_config(CONFIG *config, const char *configfile, int exit_code);
40
41 /* External subroutines */
42 extern void free_config_resources();
43
44 /* Exported variables */
45 void *start_heap;
46 int quit = 0;
47 char buf[100000];
48 int bsize = TAPE_BSIZE;
49 char VolName[MAX_NAME_LENGTH];
50 STORES *me = NULL;                    /* our Global resource */
51 bool forge_on = false;                /* proceed inspite of I/O errors */
52 pthread_mutex_t device_release_mutex = PTHREAD_MUTEX_INITIALIZER;
53 pthread_cond_t wait_device_release = PTHREAD_COND_INITIALIZER;
54
55 /*
56  * If you change the format of the state file,
57  *  increment this value
58  */
59 static uint32_t btape_state_level = 2;
60
61 DEVICE *dev = NULL;
62 DCR *dcr;
63 DEVRES *device = NULL;
64 int exit_code = 0;
65
66 #define REC_SIZE 32768
67
68 /* Forward referenced subroutines */
69 static void do_tape_cmds();
70 static void helpcmd();
71 static void scancmd();
72 static void rewindcmd();
73 static void clearcmd();
74 static void wrcmd();
75 static void rrcmd();
76 static void rbcmd();
77 static void eodcmd();
78 static void fillcmd();
79 static void qfillcmd();
80 static void statcmd();
81 static void unfillcmd();
82 static int flush_block(DEV_BLOCK *block, int dump);
83 static bool quickie_cb(DCR *dcr, DEV_RECORD *rec);
84 static bool compare_blocks(DEV_BLOCK *last_block, DEV_BLOCK *block);
85 static bool my_mount_next_read_volume(DCR *dcr);
86 static void scan_blocks();
87 static void set_volume_name(const char *VolName, int volnum);
88 static void rawfill_cmd();
89 static bool open_the_device();
90 static void autochangercmd();
91 static bool do_unfill();
92
93
94 /* Static variables */
95 static CONFIG *config;
96 #define CONFIG_FILE "bacula-sd.conf"
97 char *configfile = NULL;
98
99 #define MAX_CMD_ARGS 30
100 static POOLMEM *cmd;
101 static POOLMEM *args;
102 static char *argk[MAX_CMD_ARGS];
103 static char *argv[MAX_CMD_ARGS];
104 static int argc;
105
106 static int quickie_count = 0;
107 static uint64_t write_count = 0;
108 static BSR *bsr = NULL;
109 static int signals = TRUE;
110 static bool ok;
111 static int stop = 0;
112 static uint64_t vol_size;
113 static uint64_t VolBytes;
114 static time_t now;
115 static int32_t file_index;
116 static int end_of_tape = 0;
117 static uint32_t LastBlock = 0;
118 static uint32_t eot_block;
119 static uint32_t eot_block_len;
120 static uint32_t eot_FileIndex;
121 static int dumped = 0;
122 static DEV_BLOCK *last_block1 = NULL;
123 static DEV_BLOCK *last_block2 = NULL;
124 static DEV_BLOCK *last_block = NULL;
125 static DEV_BLOCK *this_block = NULL;
126 static DEV_BLOCK *first_block = NULL;
127 static uint32_t last_file1 = 0;
128 static uint32_t last_file2 = 0;
129 static uint32_t last_file = 0;
130 static uint32_t last_block_num1 = 0;
131 static uint32_t last_block_num2 = 0;
132 static uint32_t last_block_num = 0;
133 static uint32_t BlockNumber = 0;
134 static bool simple = true;
135
136 static const char *VolumeName = NULL;
137 static int vol_num = 0;
138
139 static JCR *jcr = NULL;
140
141
142 static void usage();
143 static void terminate_btape(int sig);
144 int get_cmd(const char *prompt);
145
146
147 /*********************************************************************
148  *
149  *     Bacula tape testing program
150  *
151  */
152 int main(int margc, char *margv[])
153 {
154    int ch, i;
155    uint32_t x32, y32;
156    uint64_t x64, y64;
157    char buf[1000];
158
159    setlocale(LC_ALL, "");
160    bindtextdomain("bacula", LOCALEDIR);
161    textdomain("bacula");
162    init_stack_dump();
163    lmgr_init_thread();
164
165    /* Sanity checks */
166    if (TAPE_BSIZE % B_DEV_BSIZE != 0 || TAPE_BSIZE / B_DEV_BSIZE == 0) {
167       Emsg2(M_ABORT, 0, _("Tape block size (%d) not multiple of system size (%d)\n"),
168          TAPE_BSIZE, B_DEV_BSIZE);
169    }
170    if (TAPE_BSIZE != (1 << (ffs(TAPE_BSIZE)-1))) {
171       Emsg1(M_ABORT, 0, _("Tape block size (%d) is not a power of 2\n"), TAPE_BSIZE);
172    }
173    if (sizeof(boffset_t) < 8) {
174       Pmsg1(-1, _("\n\n!!!! Warning large disk addressing disabled. boffset_t=%d should be 8 or more !!!!!\n\n\n"),
175          sizeof(boffset_t));
176    }
177    x32 = 123456789;
178    bsnprintf(buf, sizeof(buf), "%u", x32);
179    i = bsscanf(buf, "%lu", &y32);
180    if (i != 1 || x32 != y32) {
181       Pmsg3(-1, _("32 bit printf/scanf problem. i=%d x32=%u y32=%u\n"), i, x32, y32);
182       exit(1);
183    }
184    x64 = 123456789;
185    x64 = x64 << 32;
186    x64 += 123456789;
187    bsnprintf(buf, sizeof(buf), "%" llu, x64);
188    i = bsscanf(buf, "%llu", &y64);
189    if (i != 1 || x64 != y64) {
190       Pmsg3(-1, _("64 bit printf/scanf problem. i=%d x64=%" llu " y64=%" llu "\n"),
191             i, x64, y64);
192       exit(1);
193    }
194
195    printf(_("Tape block granularity is %d bytes.\n"), TAPE_BSIZE);
196
197    working_directory = "/tmp";
198    my_name_is(margc, margv, "btape");
199    init_msg(NULL, NULL);
200
201    OSDependentInit();
202
203    while ((ch = getopt(margc, margv, "b:c:d:psv?")) != -1) {
204       switch (ch) {
205       case 'b':                    /* bootstrap file */
206          bsr = parse_bsr(NULL, optarg);
207 //       dump_bsr(bsr, true);
208          break;
209
210       case 'c':                    /* specify config file */
211          if (configfile != NULL) {
212             free(configfile);
213          }
214          configfile = bstrdup(optarg);
215          break;
216
217       case 'd':                    /* set debug level */
218          if (*optarg == 't') {
219             dbg_timestamp = true;
220          } else {
221             debug_level = atoi(optarg);
222             if (debug_level <= 0) {
223                debug_level = 1;
224             }
225          }
226          break;
227
228       case 'p':
229          forge_on = true;
230          break;
231
232       case 's':
233          signals = false;
234          break;
235
236       case 'v':
237          verbose++;
238          break;
239
240       case '?':
241       default:
242          helpcmd();
243          exit(0);
244
245       }
246    }
247    margc -= optind;
248    margv += optind;
249
250    cmd = get_pool_memory(PM_FNAME);
251    args = get_pool_memory(PM_FNAME);
252
253    if (signals) {
254       init_signals(terminate_btape);
255    }
256
257    if (configfile == NULL) {
258       configfile = bstrdup(CONFIG_FILE);
259    }
260
261    daemon_start_time = time(NULL);
262
263    config = new_config_parser();
264    parse_sd_config(config, configfile, M_ERROR_TERM);
265    setup_me();
266    load_sd_plugins(me->plugin_directory);
267
268    /* See if we can open a device */
269    if (margc == 0) {
270       Pmsg0(000, _("No archive name specified.\n"));
271       usage();
272       exit(1);
273    } else if (margc != 1) {
274       Pmsg0(000, _("Improper number of arguments specified.\n"));
275       usage();
276       exit(1);
277    }
278
279    jcr = setup_jcr("btape", margv[0], bsr, NULL, SD_APPEND);
280    if (!jcr) {
281       exit(1);
282    }
283    dev = jcr->dcr->dev;
284    if (!dev) {
285       exit(1);
286    }
287    if (dev->is_dvd()) {
288       Pmsg0(000, _("btape does not work with DVD storage.\n"));
289       usage();
290       exit(1);
291    }
292    if (!dev->is_tape()) {
293       Pmsg0(000, _("btape only works with tape storage.\n"));
294       usage();
295       exit(1);
296    }
297    dcr = jcr->dcr;
298    if (!open_the_device()) {
299       exit(1);
300    }
301
302    Dmsg0(200, "Do tape commands\n");
303    do_tape_cmds();
304
305    terminate_btape(exit_code);
306 }
307
308 static void terminate_btape(int stat)
309 {
310
311    Dsm_check(200);
312    free_jcr(jcr);
313    jcr = NULL;
314
315    if (args) {
316       free_pool_memory(args);
317       args = NULL;
318    }
319    if (cmd) {
320       free_pool_memory(cmd);
321       cmd = NULL;
322    }
323
324    if (bsr) {
325       free_bsr(bsr);
326    }
327
328
329    free_volume_lists();
330
331    if (dev) {
332       dev->term();
333    }
334
335    if (configfile) {
336       free(configfile);
337    }
338
339    if (config) {
340       config->free_resources();
341       free(config);
342       config = NULL;
343    }
344
345    if (chk_dbglvl(10))
346       print_memory_pool_stats();
347
348    if (this_block) {
349       free_block(this_block);
350       this_block = NULL;
351    }
352
353    stop_watchdog();
354    term_msg();
355    term_last_jobs_list();
356    close_memory_pool();               /* free memory in pool */
357    lmgr_cleanup_main();
358
359    sm_dump(false);
360    exit(stat);
361 }
362
363
364 btime_t total_time=0;
365 uint64_t total_size=0;
366
367 static void init_total_speed()
368 {
369    total_size = 0;
370    total_time = 0;
371 }
372
373 static void print_total_speed()
374 {
375    char ec1[50], ec2[50];
376    uint64_t rate = total_size / total_time;
377    Pmsg2(000, _("Total Volume bytes=%sB. Total Write rate = %sB/s\n"),
378          edit_uint64_with_suffix(total_size, ec1),
379          edit_uint64_with_suffix(rate, ec2));
380 }
381
382 static void init_speed()
383 {
384    time(&jcr->run_time);              /* start counting time for rates */
385    jcr->JobBytes=0;
386 }
387
388 static void print_speed(uint64_t bytes)
389 {
390    char ec1[50], ec2[50];
391    uint64_t rate;
392
393    now = time(NULL);
394    now -= jcr->run_time;
395    if (now <= 0) {
396       now = 1;                     /* don't divide by zero */
397    }
398
399    total_time += now;
400    total_size += bytes;
401
402    rate = bytes / now;
403    Pmsg2(000, _("Volume bytes=%sB. Write rate = %sB/s\n"),
404          edit_uint64_with_suffix(bytes, ec1),
405          edit_uint64_with_suffix(rate, ec2));
406 }
407
408 /*
409  * Helper that fill a buffer with random data or not
410  */
411 typedef enum {
412    FILL_RANDOM,
413    FILL_ZERO
414 } fill_mode_t;
415
416 static void fill_buffer(fill_mode_t mode, char *buf, uint32_t len)
417 {
418    int fd;
419    switch (mode) {
420    case FILL_RANDOM:
421       fd = open("/dev/urandom", O_RDONLY);
422       if (fd != -1) {
423          read(fd, buf, len);
424          close(fd);
425       } else {
426          uint32_t *p = (uint32_t *)buf;
427          srandom(time(NULL));
428          for (uint32_t i=0; i<len/sizeof(uint32_t); i++) {
429             p[i] = random();
430          }
431       }
432       break;
433
434    case FILL_ZERO:
435       memset(buf, 0xFF, len);
436       break;
437
438    default:
439       ASSERT(0);
440    }
441 }
442
443 static void mix_buffer(fill_mode_t mode, char *data, uint32_t len)
444 {
445    uint32_t i;
446    uint32_t *lp = (uint32_t *)data;
447
448    if (mode == FILL_ZERO) {
449       return;
450    }
451
452    lp[0] += lp[13];
453    for (i=1; i < (len-sizeof(uint32_t))/sizeof(uint32_t)-1; i+=100) {
454       lp[i] += lp[0];
455    }
456 }
457
458 static bool open_the_device()
459 {
460    DEV_BLOCK *block;
461    bool ok = true;
462
463    block = new_block(dev);
464    dev->rLock(false);
465    Dmsg1(200, "Opening device %s\n", dcr->VolumeName);
466    if (!dev->open(dcr, OPEN_READ_WRITE)) {
467       Emsg1(M_FATAL, 0, _("dev open failed: %s\n"), dev->errmsg);
468       ok = false;
469       goto bail_out;
470    }
471    Pmsg1(000, _("open device %s: OK\n"), dev->print_name());
472    dev->set_append();                 /* put volume in append mode */
473
474 bail_out:
475    dev->Unlock();
476    free_block(block);
477    return ok;
478 }
479
480
481 void quitcmd()
482 {
483    quit = 1;
484 }
485
486 /*
487  * Write a label to the tape
488  */
489 static void labelcmd()
490 {
491    if (VolumeName) {
492       pm_strcpy(cmd, VolumeName);
493    } else {
494       if (!get_cmd(_("Enter Volume Name: "))) {
495          return;
496       }
497    }
498
499    if (!dev->is_open()) {
500       if (!first_open_device(dcr)) {
501          Pmsg1(0, _("Device open failed. ERR=%s\n"), dev->bstrerror());
502       }
503    }
504    dev->rewind(dcr);
505    write_new_volume_label_to_dev(dcr, cmd, "Default", false,/*no relabel*/ true /* label dvd now */);
506    Pmsg1(-1, _("Wrote Volume label for volume \"%s\".\n"), cmd);
507 }
508
509 /*
510  * Read the tape label
511  */
512 static void readlabelcmd()
513 {
514    int64_t save_debug_level = debug_level;
515    int stat;
516
517    stat = read_dev_volume_label(dcr);
518    switch (stat) {
519    case VOL_NO_LABEL:
520       Pmsg0(0, _("Volume has no label.\n"));
521       break;
522    case VOL_OK:
523       Pmsg0(0, _("Volume label read correctly.\n"));
524       break;
525    case VOL_IO_ERROR:
526       Pmsg1(0, _("I/O error on device: ERR=%s"), dev->bstrerror());
527       break;
528    case VOL_TYPE_ERROR:
529       Pmsg1(0, _("Volume type error: ERR=%s\n"), dev->errmsg);
530       break;
531    case VOL_NAME_ERROR:
532       Pmsg0(0, _("Volume name error\n"));
533       break;
534    case VOL_CREATE_ERROR:
535       Pmsg1(0, _("Error creating label. ERR=%s"), dev->bstrerror());
536       break;
537    case VOL_VERSION_ERROR:
538       Pmsg0(0, _("Volume version error.\n"));
539       break;
540    case VOL_LABEL_ERROR:
541       Pmsg0(0, _("Bad Volume label type.\n"));
542       break;
543    default:
544       Pmsg0(0, _("Unknown error.\n"));
545       break;
546    }
547
548    debug_level = 20;
549    dump_volume_label(dev);
550    debug_level = save_debug_level;
551 }
552
553
554 /*
555  * Load the tape should have prevously been taken
556  * off line, otherwise this command is not necessary.
557  */
558 static void loadcmd()
559 {
560
561    if (!load_dev(dev)) {
562       Pmsg1(0, _("Bad status from load. ERR=%s\n"), dev->bstrerror());
563    } else
564       Pmsg1(0, _("Loaded %s\n"), dev->print_name());
565 }
566
567 /*
568  * Rewind the tape.
569  */
570 static void rewindcmd()
571 {
572    if (!dev->rewind(dcr)) {
573       Pmsg1(0, _("Bad status from rewind. ERR=%s\n"), dev->bstrerror());
574       dev->clrerror(-1);
575    } else {
576       Pmsg1(0, _("Rewound %s\n"), dev->print_name());
577    }
578 }
579
580 /*
581  * Clear any tape error
582  */
583 static void clearcmd()
584 {
585    dev->clrerror(-1);
586 }
587
588 /*
589  * Write and end of file on the tape
590  */
591 static void weofcmd()
592 {
593    int num = 1;
594    if (argc > 1) {
595       num = atoi(argk[1]);
596    }
597    if (num <= 0) {
598       num = 1;
599    }
600
601    if (!dev->weof(num)) {
602       Pmsg1(0, _("Bad status from weof. ERR=%s\n"), dev->bstrerror());
603       return;
604    } else {
605       if (num==1) {
606          Pmsg1(0, _("Wrote 1 EOF to %s\n"), dev->print_name());
607       }
608       else {
609          Pmsg2(0, _("Wrote %d EOFs to %s\n"), num, dev->print_name());
610       }
611    }
612 }
613
614
615 /* Go to the end of the medium -- raw command
616  * The idea was orginally that the end of the Bacula
617  * medium would be flagged differently. This is not
618  * currently the case. So, this is identical to the
619  * eodcmd().
620  */
621 static void eomcmd()
622 {
623    if (!dev->eod(dcr)) {
624       Pmsg1(0, "%s", dev->bstrerror());
625       return;
626    } else {
627       Pmsg0(0, _("Moved to end of medium.\n"));
628    }
629 }
630
631 /*
632  * Go to the end of the medium (either hardware determined
633  *  or defined by two eofs.
634  */
635 static void eodcmd()
636 {
637    eomcmd();
638 }
639
640 /*
641  * Backspace file
642  */
643 static void bsfcmd()
644 {
645    int num = 1;
646    if (argc > 1) {
647       num = atoi(argk[1]);
648    }
649    if (num <= 0) {
650       num = 1;
651    }
652
653    if (!dev->bsf(num)) {
654       Pmsg1(0, _("Bad status from bsf. ERR=%s\n"), dev->bstrerror());
655    } else {
656       Pmsg2(0, _("Backspaced %d file%s.\n"), num, num==1?"":"s");
657    }
658 }
659
660 /*
661  * Backspace record
662  */
663 static void bsrcmd()
664 {
665    int num = 1;
666    if (argc > 1) {
667       num = atoi(argk[1]);
668    }
669    if (num <= 0) {
670       num = 1;
671    }
672    if (!dev->bsr(num)) {
673       Pmsg1(0, _("Bad status from bsr. ERR=%s\n"), dev->bstrerror());
674    } else {
675       Pmsg2(0, _("Backspaced %d record%s.\n"), num, num==1?"":"s");
676    }
677 }
678
679 /*
680  * List device capabilities as defined in the
681  *  stored.conf file.
682  */
683 static void capcmd()
684 {
685    printf(_("Configured device capabilities:\n"));
686    printf("%sEOF ", dev->capabilities & CAP_EOF ? "" : "!");
687    printf("%sBSR ", dev->capabilities & CAP_BSR ? "" : "!");
688    printf("%sBSF ", dev->capabilities & CAP_BSF ? "" : "!");
689    printf("%sFSR ", dev->capabilities & CAP_FSR ? "" : "!");
690    printf("%sFSF ", dev->capabilities & CAP_FSF ? "" : "!");
691    printf("%sFASTFSF ", dev->capabilities & CAP_FASTFSF ? "" : "!");
692    printf("%sBSFATEOM ", dev->capabilities & CAP_BSFATEOM ? "" : "!");
693    printf("%sEOM ", dev->capabilities & CAP_EOM ? "" : "!");
694    printf("%sREM ", dev->capabilities & CAP_REM ? "" : "!");
695    printf("%sRACCESS ", dev->capabilities & CAP_RACCESS ? "" : "!");
696    printf("%sAUTOMOUNT ", dev->capabilities & CAP_AUTOMOUNT ? "" : "!");
697    printf("%sLABEL ", dev->capabilities & CAP_LABEL ? "" : "!");
698    printf("%sANONVOLS ", dev->capabilities & CAP_ANONVOLS ? "" : "!");
699    printf("%sALWAYSOPEN ", dev->capabilities & CAP_ALWAYSOPEN ? "" : "!");
700    printf("%sMTIOCGET ", dev->capabilities & CAP_MTIOCGET ? "" : "!");
701    printf("\n");
702
703    printf(_("Device status:\n"));
704    printf("%sOPENED ", dev->is_open() ? "" : "!");
705    printf("%sTAPE ", dev->is_tape() ? "" : "!");
706    printf("%sLABEL ", dev->is_labeled() ? "" : "!");
707    printf("%sMALLOC ", dev->state & ST_MALLOC ? "" : "!");
708    printf("%sAPPEND ", dev->can_append() ? "" : "!");
709    printf("%sREAD ", dev->can_read() ? "" : "!");
710    printf("%sEOT ", dev->at_eot() ? "" : "!");
711    printf("%sWEOT ", dev->state & ST_WEOT ? "" : "!");
712    printf("%sEOF ", dev->at_eof() ? "" : "!");
713    printf("%sNEXTVOL ", dev->state & ST_NEXTVOL ? "" : "!");
714    printf("%sSHORT ", dev->state & ST_SHORT ? "" : "!");
715    printf("\n");
716
717    printf(_("Device parameters:\n"));
718    printf("Device name: %s\n", dev->dev_name);
719    printf("File=%u block=%u\n", dev->file, dev->block_num);
720    printf("Min block=%u Max block=%u\n", dev->min_block_size, dev->max_block_size);
721
722    printf(_("Status:\n"));
723    statcmd();
724
725 }
726
727 /*
728  * Test writing larger and larger records.
729  * This is a torture test for records.
730  */
731 static void rectestcmd()
732 {
733    DEV_BLOCK *save_block;
734    DEV_RECORD *rec;
735    int i, blkno = 0;
736
737    Pmsg0(0, _("Test writing larger and larger records.\n"
738 "This is a torture test for records.\nI am going to write\n"
739 "larger and larger records. It will stop when the record size\n"
740 "plus the header exceeds the block size (by default about 64K)\n"));
741
742
743    get_cmd(_("Do you want to continue? (y/n): "));
744    if (cmd[0] != 'y') {
745       Pmsg0(000, _("Command aborted.\n"));
746       return;
747    }
748
749    Dsm_check(200);
750    save_block = dcr->block;
751    dcr->block = new_block(dev);
752    rec = new_record();
753
754    for (i=1; i<500000; i++) {
755       rec->data = check_pool_memory_size(rec->data, i);
756       memset(rec->data, i & 0xFF, i);
757       rec->data_len = i;
758       Dsm_check(200);
759       if (write_record_to_block(dcr, rec)) {
760          empty_block(dcr->block);
761          blkno++;
762          Pmsg2(0, _("Block %d i=%d\n"), blkno, i);
763       } else {
764          break;
765       }
766       Dsm_check(200);
767    }
768    free_record(rec);
769    free_block(dcr->block);
770    dcr->block = save_block;     /* restore block to dcr */
771    Dsm_check(200);
772 }
773
774 /*
775  * This test attempts to re-read a block written by Bacula
776  *   normally at the end of the tape. Bacula will then back up
777  *   over the two eof marks, backup over the record and reread
778  *   it to make sure it is valid.  Bacula can skip this validation
779  *   if you set "Backward space record = no"
780  */
781 static bool re_read_block_test()
782 {
783    DEV_BLOCK *block = dcr->block;
784    DEV_RECORD *rec;
785    bool rc = false;
786    int len;
787
788    if (!(dev->capabilities & CAP_BSR)) {
789       Pmsg0(-1, _("Skipping read backwards test because BSR turned off.\n"));
790       return true;
791    }
792
793    Pmsg0(-1, _("\n=== Write, backup, and re-read test ===\n\n"
794       "I'm going to write three records and an EOF\n"
795       "then backup over the EOF and re-read the last record.\n"
796       "Bacula does this after writing the last block on the\n"
797       "tape to verify that the block was written correctly.\n\n"
798       "This is not an *essential* feature ...\n\n"));
799    rewindcmd();
800    empty_block(block);
801    rec = new_record();
802    rec->data = check_pool_memory_size(rec->data, block->buf_len);
803    len = rec->data_len = block->buf_len-100;
804    memset(rec->data, 1, rec->data_len);
805    if (!write_record_to_block(dcr, rec)) {
806       Pmsg0(0, _("Error writing record to block.\n"));
807       goto bail_out;
808    }
809    if (!dcr->write_block_to_dev()) {
810       Pmsg0(0, _("Error writing block to device.\n"));
811       goto bail_out;
812    } else {
813       Pmsg1(0, _("Wrote first record of %d bytes.\n"), rec->data_len);
814    }
815    memset(rec->data, 2, rec->data_len);
816    if (!write_record_to_block(dcr, rec)) {
817       Pmsg0(0, _("Error writing record to block.\n"));
818       goto bail_out;
819    }
820    if (!dcr->write_block_to_dev()) {
821       Pmsg0(0, _("Error writing block to device.\n"));
822       goto bail_out;
823    } else {
824       Pmsg1(0, _("Wrote second record of %d bytes.\n"), rec->data_len);
825    }
826    memset(rec->data, 3, rec->data_len);
827    if (!write_record_to_block(dcr, rec)) {
828       Pmsg0(0, _("Error writing record to block.\n"));
829       goto bail_out;
830    }
831    if (!dcr->write_block_to_dev()) {
832       Pmsg0(0, _("Error writing block to device.\n"));
833       goto bail_out;
834    } else {
835       Pmsg1(0, _("Wrote third record of %d bytes.\n"), rec->data_len);
836    }
837    weofcmd();
838    if (dev->has_cap(CAP_TWOEOF)) {
839       weofcmd();
840    }
841    if (!dev->bsf(1)) {
842       Pmsg1(0, _("Backspace file failed! ERR=%s\n"), dev->bstrerror());
843       goto bail_out;
844    }
845    if (dev->has_cap(CAP_TWOEOF)) {
846       if (!dev->bsf(1)) {
847          Pmsg1(0, _("Backspace file failed! ERR=%s\n"), dev->bstrerror());
848          goto bail_out;
849       }
850    }
851    Pmsg0(0, _("Backspaced over EOF OK.\n"));
852    if (!dev->bsr(1)) {
853       Pmsg1(0, _("Backspace record failed! ERR=%s\n"), dev->bstrerror());
854       goto bail_out;
855    }
856    Pmsg0(0, _("Backspace record OK.\n"));
857    if (!dcr->read_block_from_dev(NO_BLOCK_NUMBER_CHECK)) {
858       berrno be;
859       Pmsg1(0, _("Read block failed! ERR=%s\n"), be.bstrerror(dev->dev_errno));
860       goto bail_out;
861    }
862    memset(rec->data, 0, rec->data_len);
863    if (!read_record_from_block(dcr, rec)) {
864       berrno be;
865       Pmsg1(0, _("Read block failed! ERR=%s\n"), be.bstrerror(dev->dev_errno));
866       goto bail_out;
867    }
868    for (int i=0; i<len; i++) {
869       if (rec->data[i] != 3) {
870          Pmsg0(0, _("Bad data in record. Test failed!\n"));
871          goto bail_out;
872       }
873    }
874    Pmsg0(0, _("\nBlock re-read correct. Test succeeded!\n"));
875    Pmsg0(-1, _("=== End Write, backup, and re-read test ===\n\n"));
876
877    rc = true;
878
879 bail_out:
880    free_record(rec);
881    if (!rc) {
882       Pmsg0(0, _("This is not terribly serious since Bacula only uses\n"
883                  "this function to verify the last block written to the\n"
884                  "tape. Bacula will skip the last block verification\n"
885                  "if you add:\n\n"
886                   "Backward Space Record = No\n\n"
887                   "to your Storage daemon's Device resource definition.\n"));
888    }
889    return rc;
890 }
891
892 static bool speed_test_raw(fill_mode_t mode, uint64_t nb_gb, uint32_t nb)
893 {
894    DEV_BLOCK *block = dcr->block;
895    int stat;
896    uint32_t block_num = 0;
897    int my_errno;
898    char ed1[200];
899    nb_gb *= 1024*1024*1024;      /* convert size from nb to GB */
900
901    init_total_speed();
902    fill_buffer(mode, block->buf, block->buf_len);
903
904    Pmsg3(0, _("Begin writing %i files of %sB with raw blocks of %u bytes.\n"),
905          nb, edit_uint64_with_suffix(nb_gb, ed1), block->buf_len);
906
907    for (uint32_t j=0; j<nb; j++) {
908       init_speed();
909       for ( ;jcr->JobBytes < nb_gb; ) {
910          stat = dev->d_write(dev->fd(), block->buf, block->buf_len);
911          if (stat == (int)block->buf_len) {
912             if ((block_num++ % 500) == 0) {
913                printf("+");
914                fflush(stdout);
915             }
916
917             mix_buffer(mode, block->buf, block->buf_len);
918
919             jcr->JobBytes += stat;
920
921          } else {
922             my_errno = errno;
923             printf("\n");
924             berrno be;
925             printf(_("Write failed at block %u. stat=%d ERR=%s\n"), block_num,
926                    stat, be.bstrerror(my_errno));
927             return false;
928          }
929       }
930       printf("\n");
931       weofcmd();
932       print_speed(jcr->JobBytes);
933    }
934    print_total_speed();
935    printf("\n");
936    return true;
937 }
938
939
940 static bool speed_test_bacula(fill_mode_t mode, uint64_t nb_gb, uint32_t nb)
941 {
942    DEV_BLOCK *block = dcr->block;
943    char ed1[200];
944    DEV_RECORD *rec;
945    uint64_t last_bytes = dev->VolCatInfo.VolCatBytes;
946    uint64_t written=0;
947
948    nb_gb *= 1024*1024*1024;      /* convert size from nb to GB */
949
950    init_total_speed();
951
952    empty_block(block);
953    rec = new_record();
954    rec->data = check_pool_memory_size(rec->data, block->buf_len);
955    rec->data_len = block->buf_len-100;
956
957    fill_buffer(mode, rec->data, rec->data_len);
958
959    Pmsg3(0, _("Begin writing %i files of %sB with blocks of %u bytes.\n"),
960          nb, edit_uint64_with_suffix(nb_gb, ed1), block->buf_len);
961
962    for (uint32_t j=0; j<nb; j++) {
963       written = 0;
964       init_speed();
965       for ( ; written < nb_gb; ) {
966
967          if (!write_record_to_block(dcr, rec)) {
968             Pmsg0(0, _("\nError writing record to block.\n"));
969             goto bail_out;
970          }
971          if (!dcr->write_block_to_dev()) {
972             Pmsg0(0, _("\nError writing block to device.\n"));
973             goto bail_out;
974          }
975
976          if ((block->BlockNumber % 500) == 0) {
977             printf("+");
978             fflush(stdout);
979          }
980          written += dev->VolCatInfo.VolCatBytes - last_bytes;
981          last_bytes = dev->VolCatInfo.VolCatBytes;
982          mix_buffer(mode, rec->data, rec->data_len);
983       }
984       printf("\n");
985       weofcmd();
986       print_speed(written);
987    }
988    print_total_speed();
989    printf("\n");
990    free_record(rec);
991    return true;
992
993 bail_out:
994    free_record(rec);
995    return false;
996 }
997
998 /* TODO: use UAContext */
999 static int btape_find_arg(const char *keyword)
1000 {
1001    for (int i=1; i<argc; i++) {
1002       if (strcasecmp(keyword, argk[i]) == 0) {
1003          return i;
1004       }
1005    }
1006    return -1;
1007 }
1008
1009 #define ok(a)    if (!(a)) return
1010
1011 /*
1012  * For file (/dev/zero, /dev/urandom, normal?)
1013  *    use raw mode to write a suite of 3 files of 1, 2, 4, 8 GB
1014  *    use qfill mode to write the same
1015  *
1016  */
1017 static void speed_test()
1018 {
1019    bool do_zero=true, do_random=true, do_block=true, do_raw=true;
1020    uint32_t file_size=0, nb_file=3;
1021    int32_t i;
1022
1023    i = btape_find_arg("file_size");
1024    if (i > 0) {
1025       file_size = atoi(argv[i]);
1026       if (file_size > 100) {
1027          Pmsg0(0, _("The file_size is too big, stop this test with Ctrl-c.\n"));
1028       }
1029    }
1030
1031    i = btape_find_arg("nb_file");
1032    if (i > 0) {
1033       nb_file = atoi(argv[i]);
1034    }
1035
1036    if (btape_find_arg("skip_zero") > 0) {
1037       do_zero = false;
1038    }
1039
1040    if (btape_find_arg("skip_random") > 0) {
1041       do_random = false;
1042    }
1043
1044    if (btape_find_arg("skip_raw") > 0) {
1045       do_raw = false;
1046    }
1047
1048    if (btape_find_arg("skip_block") > 0) {
1049       do_block = false;
1050    }
1051
1052    if (do_raw) {
1053       dev->rewind(dcr);
1054       if (do_zero) {
1055          Pmsg0(0, _("Test with zero data, should give the "
1056                     "maximum throughput.\n"));
1057          if (file_size) {
1058             ok(speed_test_raw(FILL_ZERO, file_size, nb_file));
1059          } else {
1060             ok(speed_test_raw(FILL_ZERO, 1, nb_file));
1061             ok(speed_test_raw(FILL_ZERO, 2, nb_file));
1062             ok(speed_test_raw(FILL_ZERO, 4, nb_file));
1063          }
1064       }
1065
1066       if (do_random) {
1067          Pmsg0(0, _("Test with random data, should give the minimum "
1068                     "throughput.\n"));
1069          if (file_size) {
1070             ok(speed_test_raw(FILL_RANDOM, file_size, nb_file));
1071          } else {
1072             ok(speed_test_raw(FILL_RANDOM, 1, nb_file));
1073             ok(speed_test_raw(FILL_RANDOM, 2, nb_file));
1074             ok(speed_test_raw(FILL_RANDOM, 4, nb_file));
1075          }
1076       }
1077    }
1078
1079    if (do_block) {
1080       dev->rewind(dcr);
1081       if (do_zero) {
1082          Pmsg0(0, _("Test with zero data and bacula block structure.\n"));
1083          if (file_size) {
1084             ok(speed_test_bacula(FILL_ZERO, file_size, nb_file));
1085          } else {
1086             ok(speed_test_bacula(FILL_ZERO, 1, nb_file));
1087             ok(speed_test_bacula(FILL_ZERO, 2, nb_file));
1088                ok(speed_test_bacula(FILL_ZERO, 4, nb_file));
1089          }
1090       }
1091
1092       if (do_random) {
1093          Pmsg0(0, _("Test with random data, should give the minimum "
1094                     "throughput.\n"));
1095          if (file_size) {
1096             ok(speed_test_bacula(FILL_RANDOM, file_size, nb_file));
1097          } else {
1098             ok(speed_test_bacula(FILL_RANDOM, 1, nb_file));
1099             ok(speed_test_bacula(FILL_RANDOM, 2, nb_file));
1100             ok(speed_test_bacula(FILL_RANDOM, 4, nb_file));
1101          }
1102       }
1103    }
1104 }
1105
1106 const int num_recs = 10000;
1107
1108 static bool write_two_files()
1109 {
1110    DEV_BLOCK *block;
1111    DEV_RECORD *rec;
1112    int len, i, j;
1113    int *p;
1114    bool rc = false;       /* bad return code */
1115    DEVICE *dev = dcr->dev;
1116
1117    /*
1118     * Set big max_file_size so that write_record_to_block
1119     * doesn't insert any additional EOF marks
1120     * Do calculation in 64 bits to avoid overflow.  
1121     */
1122    dev->max_file_size = (uint64_t)2 * (uint64_t)num_recs * (uint64_t)dev->max_block_size;
1123    Pmsg2(-1, _("\n=== Write, rewind, and re-read test ===\n\n"
1124       "I'm going to write %d records and an EOF\n"
1125       "then write %d records and an EOF, then rewind,\n"
1126       "and re-read the data to verify that it is correct.\n\n"
1127       "This is an *essential* feature ...\n\n"), num_recs, num_recs);
1128
1129    block = dcr->block;
1130    empty_block(block);
1131    rec = new_record();
1132    rec->data = check_pool_memory_size(rec->data, block->buf_len);
1133    rec->data_len = block->buf_len-100;
1134    len = rec->data_len/sizeof(i);
1135
1136    if (!dev->rewind(dcr)) {
1137       Pmsg1(0, _("Bad status from rewind. ERR=%s\n"), dev->bstrerror());
1138       goto bail_out;
1139    }
1140
1141    for (i=1; i<=num_recs; i++) {
1142       p = (int *)rec->data;
1143       for (j=0; j<len; j++) {
1144          *p++ = i;
1145       }
1146       if (!write_record_to_block(dcr, rec)) {
1147          Pmsg0(0, _("Error writing record to block.\n"));
1148          goto bail_out;
1149       }
1150       if (!dcr->write_block_to_dev()) {
1151          Pmsg0(0, _("Error writing block to device.\n"));
1152          goto bail_out;
1153       }
1154    }
1155    Pmsg2(0, _("Wrote %d blocks of %d bytes.\n"), num_recs, rec->data_len);
1156    weofcmd();
1157    for (i=num_recs+1; i<=2*num_recs; i++) {
1158       p = (int *)rec->data;
1159       for (j=0; j<len; j++) {
1160          *p++ = i;
1161       }
1162       if (!write_record_to_block(dcr, rec)) {
1163          Pmsg0(0, _("Error writing record to block.\n"));
1164          goto bail_out;
1165       }
1166       if (!dcr->write_block_to_dev()) {
1167          Pmsg0(0, _("Error writing block to device.\n"));
1168          goto bail_out;
1169       }
1170    }
1171    Pmsg2(0, _("Wrote %d blocks of %d bytes.\n"), num_recs, rec->data_len);
1172    weofcmd();
1173    if (dev->has_cap(CAP_TWOEOF)) {
1174       weofcmd();
1175    }
1176    rc = true;
1177
1178 bail_out:
1179    free_record(rec);
1180    if (!rc) {
1181       exit_code = 1;
1182    }
1183    return rc;
1184
1185 }
1186
1187 /*
1188  * This test writes Bacula blocks to the tape in
1189  *   several files. It then rewinds the tape and attepts
1190  *   to read these blocks back checking the data.
1191  */
1192 static bool write_read_test()
1193 {
1194    DEV_BLOCK *block;
1195    DEV_RECORD *rec;
1196    bool rc = false;
1197    int len, i, j;
1198    int *p;
1199
1200    rec = new_record();
1201
1202    if (!write_two_files()) {
1203       goto bail_out;
1204    }
1205
1206    block = dcr->block;
1207    empty_block(block);
1208
1209    if (!dev->rewind(dcr)) {
1210       Pmsg1(0, _("Bad status from rewind. ERR=%s\n"), dev->bstrerror());
1211       goto bail_out;
1212    } else {
1213       Pmsg0(0, _("Rewind OK.\n"));
1214    }
1215
1216    rec->data = check_pool_memory_size(rec->data, block->buf_len);
1217    rec->data_len = block->buf_len-100;
1218    len = rec->data_len/sizeof(i);
1219
1220    /* Now read it back */
1221    for (i=1; i<=2*num_recs; i++) {
1222 read_again:
1223       if (!dcr->read_block_from_dev(NO_BLOCK_NUMBER_CHECK)) {
1224          berrno be;
1225          if (dev_state(dev, ST_EOF)) {
1226             Pmsg0(-1, _("Got EOF on tape.\n"));
1227             if (i == num_recs+1) {
1228                goto read_again;
1229             }
1230          }
1231          Pmsg2(0, _("Read block %d failed! ERR=%s\n"), i, be.bstrerror(dev->dev_errno));
1232          goto bail_out;
1233       }
1234       memset(rec->data, 0, rec->data_len);
1235       if (!read_record_from_block(dcr, rec)) {
1236          berrno be;
1237          Pmsg2(0, _("Read record failed. Block %d! ERR=%s\n"), i, be.bstrerror(dev->dev_errno));
1238          goto bail_out;
1239       }
1240       p = (int *)rec->data;
1241       for (j=0; j<len; j++) {
1242          if (*p != i) {
1243             Pmsg3(0, _("Bad data in record. Expected %d, got %d at byte %d. Test failed!\n"),
1244                i, *p, j);
1245             goto bail_out;
1246          }
1247          p++;
1248       }
1249       if (i == num_recs || i == 2*num_recs) {
1250          Pmsg1(-1, _("%d blocks re-read correctly.\n"), num_recs);
1251       }
1252    }
1253    Pmsg0(-1, _("=== Test Succeeded. End Write, rewind, and re-read test ===\n\n"));
1254    rc = true;
1255
1256 bail_out:
1257    free_record(rec);
1258    if (!rc) {
1259       exit_code = 1;
1260    }
1261    return rc;
1262 }
1263
1264 /*
1265  * This test writes Bacula blocks to the tape in
1266  *   several files. It then rewinds the tape and attepts
1267  *   to read these blocks back checking the data.
1268  */
1269 static bool position_test()
1270 {
1271    DEV_BLOCK *block = dcr->block;
1272    DEV_RECORD *rec;
1273    bool rc = false;
1274    int len, j;
1275    bool more = true;
1276    int recno = 0;
1277    int file = 0, blk = 0;
1278    int *p;
1279    bool got_eof = false;
1280
1281    Pmsg0(0, _("Block position test\n"));
1282    block = dcr->block;
1283    empty_block(block);
1284    rec = new_record();
1285    rec->data = check_pool_memory_size(rec->data, block->buf_len);
1286    rec->data_len = block->buf_len-100;
1287    len = rec->data_len/sizeof(j);
1288
1289    if (!dev->rewind(dcr)) {
1290       Pmsg1(0, _("Bad status from rewind. ERR=%s\n"), dev->bstrerror());
1291       goto bail_out;
1292    } else {
1293       Pmsg0(0, _("Rewind OK.\n"));
1294    }
1295
1296    while (more) {
1297       /* Set up next item to read based on where we are */
1298       /* At each step, recno is what we print for the "block number"
1299        *  and file, blk are the real positions to go to.
1300        */
1301       switch (recno) {
1302       case 0:
1303          recno = 5;
1304          file = 0;
1305          blk = 4;
1306          break;
1307       case 5:
1308          recno = 201;
1309          file = 0;
1310          blk = 200;
1311          break;
1312       case 201:
1313          recno = num_recs;
1314          file = 0;
1315          blk = num_recs-1;
1316          break;
1317       case num_recs:
1318          recno = num_recs+1;
1319          file = 1;
1320          blk = 0;
1321          break;
1322       case num_recs+1:
1323          recno = num_recs+601;
1324          file = 1;
1325          blk = 600;
1326          break;
1327       case num_recs+601:
1328          recno = 2*num_recs;
1329          file = 1;
1330          blk = num_recs-1;
1331          break;
1332       case 2*num_recs:
1333          more = false;
1334          continue;
1335       }
1336       Pmsg2(-1, _("Reposition to file:block %d:%d\n"), file, blk);
1337       if (!dev->reposition(dcr, file, blk)) {
1338          Pmsg0(0, _("Reposition error.\n"));
1339          goto bail_out;
1340       }
1341 read_again:
1342       if (!dcr->read_block_from_dev(NO_BLOCK_NUMBER_CHECK)) {
1343          berrno be;
1344          if (dev_state(dev, ST_EOF)) {
1345             Pmsg0(-1, _("Got EOF on tape.\n"));
1346             if (!got_eof) {
1347                got_eof = true;
1348                goto read_again;
1349             }
1350          }
1351          Pmsg4(0, _("Read block %d failed! file=%d blk=%d. ERR=%s\n\n"),
1352             recno, file, blk, be.bstrerror(dev->dev_errno));
1353          Pmsg0(0, _("This may be because the tape drive block size is not\n"
1354                     " set to variable blocking as normally used by Bacula.\n"
1355                     " Please see the Tape Testing chapter in the manual and \n"
1356                     " look for using mt with defblksize and setoptions\n"
1357                     "If your tape drive block size is correct, then perhaps\n"
1358                     " your SCSI driver is *really* stupid and does not\n"
1359                     " correctly report the file:block after a FSF. In this\n"
1360                     " case try setting:\n"
1361                     "    Fast Forward Space File = no\n"
1362                     " in your Device resource.\n"));
1363
1364          goto bail_out;
1365       }
1366       memset(rec->data, 0, rec->data_len);
1367       if (!read_record_from_block(dcr, rec)) {
1368          berrno be;
1369          Pmsg1(0, _("Read record failed! ERR=%s\n"), be.bstrerror(dev->dev_errno));
1370          goto bail_out;
1371       }
1372       p = (int *)rec->data;
1373       for (j=0; j<len; j++) {
1374          if (p[j] != recno) {
1375             Pmsg3(0, _("Bad data in record. Expected %d, got %d at byte %d. Test failed!\n"),
1376                recno, p[j], j);
1377             goto bail_out;
1378          }
1379       }
1380       Pmsg1(-1, _("Block %d re-read correctly.\n"), recno);
1381    }
1382    Pmsg0(-1, _("=== Test Succeeded. End Write, rewind, and re-read test ===\n\n"));
1383    rc = true;
1384
1385 bail_out:
1386    free_record(rec);
1387    return rc;
1388 }
1389
1390
1391
1392
1393 /*
1394  * This test writes some records, then writes an end of file,
1395  *   rewinds the tape, moves to the end of the data and attepts
1396  *   to append to the tape.  This function is essential for
1397  *   Bacula to be able to write multiple jobs to the tape.
1398  */
1399 static int append_test()
1400 {
1401    Pmsg0(-1, _("\n\n=== Append files test ===\n\n"
1402                "This test is essential to Bacula.\n\n"
1403 "I'm going to write one record  in file 0,\n"
1404 "                   two records in file 1,\n"
1405 "             and three records in file 2\n\n"));
1406    argc = 1;
1407    rewindcmd();
1408    wrcmd();
1409    weofcmd();      /* end file 0 */
1410    wrcmd();
1411    wrcmd();
1412    weofcmd();      /* end file 1 */
1413    wrcmd();
1414    wrcmd();
1415    wrcmd();
1416    weofcmd();     /* end file 2 */
1417    if (dev->has_cap(CAP_TWOEOF)) {
1418       weofcmd();
1419    }
1420    dev->close();              /* release device */
1421    if (!open_the_device()) {
1422       return -1;
1423    }
1424    rewindcmd();
1425    Pmsg0(0, _("Now moving to end of medium.\n"));
1426    eodcmd();
1427    Pmsg2(-1, _("We should be in file 3. I am at file %d. %s\n"),
1428       dev->file, dev->file == 3 ? _("This is correct!") : _("This is NOT correct!!!!"));
1429
1430    if (dev->file != 3) {
1431       return -1;
1432    }
1433
1434    Pmsg0(-1, _("\nNow the important part, I am going to attempt to append to the tape.\n\n"));
1435    wrcmd();
1436    weofcmd();
1437    if (dev->has_cap(CAP_TWOEOF)) {
1438       weofcmd();
1439    }
1440    rewindcmd();
1441    Pmsg0(-1, _("Done appending, there should be no I/O errors\n\n"));
1442    Pmsg0(-1, _("Doing Bacula scan of blocks:\n"));
1443    scan_blocks();
1444    Pmsg0(-1, _("End scanning the tape.\n"));
1445    Pmsg2(-1, _("We should be in file 4. I am at file %d. %s\n"),
1446       dev->file, dev->file == 4 ? _("This is correct!") : _("This is NOT correct!!!!"));
1447
1448    if (dev->file != 4) {
1449       return -2;
1450    }
1451    return 1;
1452 }
1453
1454
1455 /*
1456  * This test exercises the autochanger
1457  */
1458 static int autochanger_test()
1459 {
1460    POOLMEM *results, *changer;
1461    int slot, status, loaded;
1462    int timeout = dcr->device->max_changer_wait;
1463    int sleep_time = 0;
1464
1465    Dmsg1(100, "Max changer wait = %d sec\n", timeout);
1466    if (!dev->has_cap(CAP_AUTOCHANGER)) {
1467       return 1;
1468    }
1469    if (!(dcr->device && dcr->device->changer_name && dcr->device->changer_command)) {
1470       Pmsg0(-1, _("\nAutochanger enabled, but no name or no command device specified.\n"));
1471       return 1;
1472    }
1473
1474    Pmsg0(-1, _("\nAh, I see you have an autochanger configured.\n"
1475              "To test the autochanger you must have a blank tape\n"
1476              " that I can write on in Slot 1.\n"));
1477    if (!get_cmd(_("\nDo you wish to continue with the Autochanger test? (y/n): "))) {
1478       return 0;
1479    }
1480    if (cmd[0] != 'y' && cmd[0] != 'Y') {
1481       return 0;
1482    }
1483
1484    Pmsg0(-1, _("\n\n=== Autochanger test ===\n\n"));
1485
1486    results = get_pool_memory(PM_MESSAGE);
1487    changer = get_pool_memory(PM_FNAME);
1488
1489 try_again:
1490    slot = 1;
1491    dcr->VolCatInfo.Slot = slot;
1492    /* Find out what is loaded, zero means device is unloaded */
1493    Pmsg0(-1, _("3301 Issuing autochanger \"loaded\" command.\n"));
1494    changer = edit_device_codes(dcr, changer,
1495                 dcr->device->changer_command, "loaded");
1496    status = run_program(changer, timeout, results);
1497    Dmsg3(100, "run_prog: %s stat=%d result=\"%s\"\n", changer, status, results);
1498    if (status == 0) {
1499       loaded = atoi(results);
1500    } else {
1501       berrno be;
1502       Pmsg1(-1, _("3991 Bad autochanger command: %s\n"), changer);
1503       Pmsg2(-1, _("3991 result=\"%s\": ERR=%s\n"), results, be.bstrerror(status));
1504       goto bail_out;
1505    }
1506    if (loaded) {
1507       Pmsg1(-1, _("Slot %d loaded. I am going to unload it.\n"), loaded);
1508    } else {
1509       Pmsg0(-1, _("Nothing loaded in the drive. OK.\n"));
1510    }
1511    Dmsg1(100, "Results from loaded query=%s\n", results);
1512    if (loaded) {
1513       dcr->VolCatInfo.Slot = loaded;
1514       /* We are going to load a new tape, so close the device */
1515       dev->close();
1516       Pmsg2(-1, _("3302 Issuing autochanger \"unload %d %d\" command.\n"),
1517          loaded, dev->drive_index);
1518       changer = edit_device_codes(dcr, changer,
1519                    dcr->device->changer_command, "unload");
1520       status = run_program(changer, timeout, results);
1521       Pmsg2(-1, _("unload status=%s %d\n"), status==0?_("OK"):_("Bad"), status);
1522       if (status != 0) {
1523          berrno be;
1524          Pmsg1(-1, _("3992 Bad autochanger command: %s\n"), changer);
1525          Pmsg2(-1, _("3992 result=\"%s\": ERR=%s\n"), results, be.bstrerror(status));
1526       }
1527    }
1528
1529    /*
1530     * Load the Slot 1
1531     */
1532
1533    slot = 1;
1534    dcr->VolCatInfo.Slot = slot;
1535    Pmsg2(-1, _("3303 Issuing autochanger \"load %d %d\" command.\n"),
1536       slot, dev->drive_index);
1537    changer = edit_device_codes(dcr, changer,
1538                 dcr->device->changer_command, "load");
1539    Dmsg1(100, "Changer=%s\n", changer);
1540    dev->close();
1541    status = run_program(changer, timeout, results);
1542    if (status == 0) {
1543       Pmsg2(-1,  _("3303 Autochanger \"load %d %d\" status is OK.\n"),
1544          slot, dev->drive_index);
1545    } else {
1546       berrno be;
1547       Pmsg1(-1, _("3993 Bad autochanger command: %s\n"), changer);
1548       Pmsg2(-1, _("3993 result=\"%s\": ERR=%s\n"), results, be.bstrerror(status));
1549       goto bail_out;
1550    }
1551
1552    if (!open_the_device()) {
1553       goto bail_out;
1554    }
1555    /*
1556     * Start with sleep_time 0 then increment by 30 seconds if we get
1557     * a failure.
1558     */
1559    bmicrosleep(sleep_time, 0);
1560    if (!dev->rewind(dcr) || !dev->weof(1)) {
1561       Pmsg1(0, _("Bad status from rewind. ERR=%s\n"), dev->bstrerror());
1562       dev->clrerror(-1);
1563       Pmsg0(-1, _("\nThe test failed, probably because you need to put\n"
1564                 "a longer sleep time in the mtx-script in the load) case.\n"
1565                 "Adding a 30 second sleep and trying again ...\n"));
1566       sleep_time += 30;
1567       goto try_again;
1568    } else {
1569       Pmsg1(0, _("Rewound %s\n"), dev->print_name());
1570    }
1571
1572    if (!dev->weof(1)) {
1573       Pmsg1(0, _("Bad status from weof. ERR=%s\n"), dev->bstrerror());
1574       goto bail_out;
1575    } else {
1576       Pmsg1(0, _("Wrote EOF to %s\n"), dev->print_name());
1577    }
1578
1579    if (sleep_time) {
1580       Pmsg1(-1, _("\nThe test worked this time. Please add:\n\n"
1581                 "   sleep %d\n\n"
1582                 "to your mtx-changer script in the load) case.\n\n"),
1583                 sleep_time);
1584    } else {
1585       Pmsg0(-1, _("\nThe test autochanger worked!!\n\n"));
1586    }
1587
1588    free_pool_memory(changer);
1589    free_pool_memory(results);
1590    return 1;
1591
1592
1593 bail_out:
1594    free_pool_memory(changer);
1595    free_pool_memory(results);
1596    Pmsg0(-1, _("You must correct this error or the Autochanger will not work.\n"));
1597    return -2;
1598 }
1599
1600 static void autochangercmd()
1601 {
1602    autochanger_test();
1603 }
1604
1605
1606 /*
1607  * This test assumes that the append test has been done,
1608  *   then it tests the fsf function.
1609  */
1610 static bool fsf_test()
1611 {
1612    bool set_off = false;
1613
1614    Pmsg0(-1, _("\n\n=== Forward space files test ===\n\n"
1615                "This test is essential to Bacula.\n\n"
1616                "I'm going to write five files then test forward spacing\n\n"));
1617    argc = 1;
1618    rewindcmd();
1619    wrcmd();
1620    weofcmd();      /* end file 0 */
1621    wrcmd();
1622    wrcmd();
1623    weofcmd();      /* end file 1 */
1624    wrcmd();
1625    wrcmd();
1626    wrcmd();
1627    weofcmd();     /* end file 2 */
1628    wrcmd();
1629    wrcmd();
1630    weofcmd();     /* end file 3 */
1631    wrcmd();
1632    weofcmd();     /* end file 4 */
1633    if (dev->has_cap(CAP_TWOEOF)) {
1634       weofcmd();
1635    }
1636
1637 test_again:
1638    rewindcmd();
1639    Pmsg0(0, _("Now forward spacing 1 file.\n"));
1640    if (!dev->fsf(1)) {
1641       Pmsg1(0, _("Bad status from fsr. ERR=%s\n"), dev->bstrerror());
1642       goto bail_out;
1643    }
1644    Pmsg2(-1, _("We should be in file 1. I am at file %d. %s\n"),
1645       dev->file, dev->file == 1 ? _("This is correct!") : _("This is NOT correct!!!!"));
1646
1647    if (dev->file != 1) {
1648       goto bail_out;
1649    }
1650
1651    Pmsg0(0, _("Now forward spacing 2 files.\n"));
1652    if (!dev->fsf(2)) {
1653       Pmsg1(0, _("Bad status from fsr. ERR=%s\n"), dev->bstrerror());
1654       goto bail_out;
1655    }
1656    Pmsg2(-1, _("We should be in file 3. I am at file %d. %s\n"),
1657       dev->file, dev->file == 3 ? _("This is correct!") : _("This is NOT correct!!!!"));
1658
1659    if (dev->file != 3) {
1660       goto bail_out;
1661    }
1662
1663    rewindcmd();
1664    Pmsg0(0, _("Now forward spacing 4 files.\n"));
1665    if (!dev->fsf(4)) {
1666       Pmsg1(0, _("Bad status from fsr. ERR=%s\n"), dev->bstrerror());
1667       goto bail_out;
1668    }
1669    Pmsg2(-1, _("We should be in file 4. I am at file %d. %s\n"),
1670       dev->file, dev->file == 4 ? _("This is correct!") : _("This is NOT correct!!!!"));
1671
1672    if (dev->file != 4) {
1673       goto bail_out;
1674    }
1675    if (set_off) {
1676       Pmsg0(-1, _("The test worked this time. Please add:\n\n"
1677                 "   Fast Forward Space File = no\n\n"
1678                 "to your Device resource for this drive.\n"));
1679    }
1680
1681    Pmsg0(-1, "\n");
1682    Pmsg0(0, _("Now forward spacing 1 more file.\n"));
1683    if (!dev->fsf(1)) {
1684       Pmsg1(0, _("Bad status from fsr. ERR=%s\n"), dev->bstrerror());
1685    }
1686    Pmsg2(-1, _("We should be in file 5. I am at file %d. %s\n"),
1687       dev->file, dev->file == 5 ? _("This is correct!") : _("This is NOT correct!!!!"));
1688    if (dev->file != 5) {
1689       goto bail_out;
1690    }
1691    Pmsg0(-1, _("\n=== End Forward space files test ===\n\n"));
1692    return true;
1693
1694 bail_out:
1695    Pmsg0(-1, _("\nThe forward space file test failed.\n"));
1696    if (dev->has_cap(CAP_FASTFSF)) {
1697       Pmsg0(-1, _("You have Fast Forward Space File enabled.\n"
1698               "I am turning it off then retrying the test.\n"));
1699       dev->clear_cap(CAP_FASTFSF);
1700       set_off = true;
1701       goto test_again;
1702    }
1703    Pmsg0(-1, _("You must correct this error or Bacula will not work.\n"
1704             "Some systems, e.g. OpenBSD, require you to set\n"
1705             "   Use MTIOCGET= no\n"
1706             "in your device resource. Use with caution.\n"));
1707    return false;
1708 }
1709
1710
1711
1712
1713
1714 /*
1715  * This is a general test of Bacula's functions
1716  *   needed to read and write the tape.
1717  */
1718 static void testcmd()
1719 {
1720    int stat;
1721
1722    if (!write_read_test()) {
1723       exit_code = 1;
1724       return;
1725    }
1726    if (!position_test()) {
1727       exit_code = 1;
1728       return;
1729    }
1730
1731    stat = append_test();
1732    if (stat == 1) {                   /* OK get out */
1733       goto all_done;
1734    }
1735    if (stat == -1) {                  /* first test failed */
1736       if (dev->has_cap(CAP_EOM) || dev->has_cap(CAP_FASTFSF)) {
1737          Pmsg0(-1, _("\nAppend test failed. Attempting again.\n"
1738                    "Setting \"Hardware End of Medium = no\n"
1739                    "    and \"Fast Forward Space File = no\n"
1740                    "and retrying append test.\n\n"));
1741          dev->clear_cap(CAP_EOM);      /* turn off eom */
1742          dev->clear_cap(CAP_FASTFSF);  /* turn off fast fsf */
1743          stat = append_test();
1744          if (stat == 1) {
1745             Pmsg0(-1, _("\n\nIt looks like the test worked this time, please add:\n\n"
1746                      "    Hardware End of Medium = No\n\n"
1747                      "    Fast Forward Space File = No\n"
1748                      "to your Device resource in the Storage conf file.\n"));
1749             goto all_done;
1750          }
1751          if (stat == -1) {
1752             Pmsg0(-1, _("\n\nThat appears *NOT* to have corrected the problem.\n"));
1753             goto failed;
1754          }
1755          /* Wrong count after append */
1756          if (stat == -2) {
1757             Pmsg0(-1, _("\n\nIt looks like the append failed. Attempting again.\n"
1758                      "Setting \"BSF at EOM = yes\" and retrying append test.\n"));
1759             dev->capabilities |= CAP_BSFATEOM; /* backspace on eom */
1760             stat = append_test();
1761             if (stat == 1) {
1762                Pmsg0(-1, _("\n\nIt looks like the test worked this time, please add:\n\n"
1763                      "    Hardware End of Medium = No\n"
1764                      "    Fast Forward Space File = No\n"
1765                      "    BSF at EOM = yes\n\n"
1766                      "to your Device resource in the Storage conf file.\n"));
1767                goto all_done;
1768             }
1769          }
1770
1771       }
1772 failed:
1773       Pmsg0(-1, _("\nAppend test failed.\n\n"
1774             "\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n"
1775             "Unable to correct the problem. You MUST fix this\n"
1776              "problem before Bacula can use your tape drive correctly\n"
1777             "\nPerhaps running Bacula in fixed block mode will work.\n"
1778             "Do so by setting:\n\n"
1779             "Minimum Block Size = nnn\n"
1780             "Maximum Block Size = nnn\n\n"
1781             "in your Storage daemon's Device definition.\n"
1782             "nnn must match your tape driver's block size, which\n"
1783             "can be determined by reading your tape manufacturers\n"
1784             "information, and the information on your kernel dirver.\n"
1785             "Fixed block sizes, however, are not normally an ideal solution.\n"
1786             "\n"
1787             "Some systems, e.g. OpenBSD, require you to set\n"
1788             "   Use MTIOCGET= no\n"
1789             "in your device resource. Use with caution.\n"));
1790        exit_code = 1;
1791        return;
1792    }
1793
1794 all_done:
1795    Pmsg0(-1, _("\nThe above Bacula scan should have output identical to what follows.\n"
1796         "Please double check it ...\n"
1797         "=== Sample correct output ===\n"
1798         "1 block of 64448 bytes in file 1\n"
1799         "End of File mark.\n"
1800         "2 blocks of 64448 bytes in file 2\n"
1801         "End of File mark.\n"
1802         "3 blocks of 64448 bytes in file 3\n"
1803         "End of File mark.\n"
1804         "1 block of 64448 bytes in file 4\n"
1805         "End of File mark.\n"
1806         "Total files=4, blocks=7, bytes = 451,136\n"
1807         "=== End sample correct output ===\n\n"
1808         "If the above scan output is not identical to the\n"
1809         "sample output, you MUST correct the problem\n"
1810         "or Bacula will not be able to write multiple Jobs to \n"
1811         "the tape.\n\n"));
1812
1813    if (stat == 1) {
1814       if (!re_read_block_test()) {
1815          exit_code = 1;
1816       }
1817    }
1818
1819    if (!fsf_test()) {                  /* do fast forward space file test */
1820       exit_code = 1;
1821    }
1822
1823    autochanger_test();                /* do autochanger test */
1824
1825 }
1826
1827 /* Forward space a file */
1828 static void fsfcmd()
1829 {
1830    int num = 1;
1831    if (argc > 1) {
1832       num = atoi(argk[1]);
1833    }
1834    if (num <= 0) {
1835       num = 1;
1836    }
1837    if (!dev->fsf(num)) {
1838       Pmsg1(0, _("Bad status from fsf. ERR=%s\n"), dev->bstrerror());
1839       return;
1840    }
1841    if (num == 1) {
1842       Pmsg0(0, _("Forward spaced 1 file.\n"));
1843    }
1844    else {
1845       Pmsg1(0, _("Forward spaced %d files.\n"), num);
1846    }
1847 }
1848
1849 /* Forward space a record */
1850 static void fsrcmd()
1851 {
1852    int num = 1;
1853    if (argc > 1) {
1854       num = atoi(argk[1]);
1855    }
1856    if (num <= 0) {
1857       num = 1;
1858    }
1859    if (!dev->fsr(num)) {
1860       Pmsg1(0, _("Bad status from fsr. ERR=%s\n"), dev->bstrerror());
1861       return;
1862    }
1863    if (num == 1) {
1864       Pmsg0(0, _("Forward spaced 1 record.\n"));
1865    }
1866    else {
1867       Pmsg1(0, _("Forward spaced %d records.\n"), num);
1868    }
1869 }
1870
1871 /*
1872  * Read a Bacula block from the tape
1873  */
1874 static void rbcmd()
1875 {
1876    dev->open(dcr, OPEN_READ_ONLY);
1877    dcr->read_block_from_dev(NO_BLOCK_NUMBER_CHECK);
1878 }
1879
1880 /*
1881  * Write a Bacula block to the tape
1882  */
1883 static void wrcmd()
1884 {
1885    DEV_BLOCK *block = dcr->block;
1886    DEV_RECORD *rec = dcr->rec;
1887    int i;
1888
1889    if (!dev->is_open()) {
1890       open_the_device();
1891    }
1892    Dsm_check(200);
1893    empty_block(block);
1894    if (verbose > 1) {
1895       dump_block(block, "test");
1896    }
1897
1898    i = block->buf_len - 100;
1899    ASSERT (i > 0);
1900    rec->data = check_pool_memory_size(rec->data, i);
1901    memset(rec->data, i & 0xFF, i);
1902    rec->data_len = i;
1903    Dsm_check(200);
1904    if (!write_record_to_block(dcr, rec)) {
1905       Pmsg0(0, _("Error writing record to block.\n"));
1906       goto bail_out;
1907    }
1908    if (!dcr->write_block_to_dev()) {
1909       Pmsg0(0, _("Error writing block to device.\n"));
1910       goto bail_out;
1911    } else {
1912       Pmsg1(0, _("Wrote one record of %d bytes.\n"), i);
1913    }
1914    Pmsg0(0, _("Wrote block to device.\n"));
1915
1916 bail_out:
1917    Dsm_check(200);
1918 }
1919
1920 /*
1921  * Read a record from the tape
1922  */
1923 static void rrcmd()
1924 {
1925    char *buf;
1926    int stat, len;
1927
1928    if (!get_cmd(_("Enter length to read: "))) {
1929       return;
1930    }
1931    len = atoi(cmd);
1932    if (len < 0 || len > 1000000) {
1933       Pmsg0(0, _("Bad length entered, using default of 1024 bytes.\n"));
1934       len = 1024;
1935    }
1936    buf = (char *)malloc(len);
1937    stat = read(dev->fd(), buf, len);
1938    if (stat > 0 && stat <= len) {
1939       errno = 0;
1940    }
1941    berrno be;
1942    Pmsg3(0, _("Read of %d bytes gives stat=%d. ERR=%s\n"),
1943       len, stat, be.bstrerror());
1944    free(buf);
1945 }
1946
1947
1948 /*
1949  * Scan tape by reading block by block. Report what is
1950  * on the tape.  Note, this command does raw reads, and as such
1951  * will not work with fixed block size devices.
1952  */
1953 static void scancmd()
1954 {
1955    int stat;
1956    int blocks, tot_blocks, tot_files;
1957    int block_size;
1958    uint64_t bytes;
1959    char ec1[50];
1960
1961
1962    blocks = block_size = tot_blocks = 0;
1963    bytes = 0;
1964    if (dev->state & ST_EOT) {
1965       Pmsg0(0, _("End of tape\n"));
1966       return;
1967    }
1968    dev->update_pos(dcr);
1969    tot_files = dev->file;
1970    Pmsg1(0, _("Starting scan at file %u\n"), dev->file);
1971    for (;;) {
1972       if ((stat = read(dev->fd(), buf, sizeof(buf))) < 0) {
1973          berrno be;
1974          dev->clrerror(-1);
1975          Mmsg2(dev->errmsg, _("read error on %s. ERR=%s.\n"),
1976             dev->dev_name, be.bstrerror());
1977          Pmsg2(0, _("Bad status from read %d. ERR=%s\n"), stat, dev->bstrerror());
1978          if (blocks > 0) {
1979             if (blocks==1) {
1980                printf(_("1 block of %d bytes in file %d\n"), block_size, dev->file);
1981             }
1982             else {
1983                printf(_("%d blocks of %d bytes in file %d\n"), blocks, block_size, dev->file);
1984             }
1985          }
1986          return;
1987       }
1988       Dmsg1(200, "read status = %d\n", stat);
1989 /*    sleep(1); */
1990       if (stat != block_size) {
1991          dev->update_pos(dcr);
1992          if (blocks > 0) {
1993             if (blocks==1) {
1994                printf(_("1 block of %d bytes in file %d\n"), block_size, dev->file);
1995             }
1996             else {
1997                printf(_("%d blocks of %d bytes in file %d\n"), blocks, block_size, dev->file);
1998             }
1999             blocks = 0;
2000          }
2001          block_size = stat;
2002       }
2003       if (stat == 0) {                /* EOF */
2004          dev->update_pos(dcr);
2005          printf(_("End of File mark.\n"));
2006          /* Two reads of zero means end of tape */
2007          if (dev->state & ST_EOF)
2008             dev->state |= ST_EOT;
2009          else {
2010             dev->state |= ST_EOF;
2011             dev->file++;
2012          }
2013          if (dev->state & ST_EOT) {
2014             printf(_("End of tape\n"));
2015             break;
2016          }
2017       } else {                        /* Got data */
2018          dev->state &= ~ST_EOF;
2019          blocks++;
2020          tot_blocks++;
2021          bytes += stat;
2022       }
2023    }
2024    dev->update_pos(dcr);
2025    tot_files = dev->file - tot_files;
2026    printf(_("Total files=%d, blocks=%d, bytes = %s\n"), tot_files, tot_blocks,
2027       edit_uint64_with_commas(bytes, ec1));
2028 }
2029
2030
2031 /*
2032  * Scan tape by reading Bacula block by block. Report what is
2033  * on the tape.  This function reads Bacula blocks, so if your
2034  * Device resource is correctly defined, it should work with
2035  * either variable or fixed block sizes.
2036  */
2037 static void scan_blocks()
2038 {
2039    int blocks, tot_blocks, tot_files;
2040    uint32_t block_size;
2041    uint64_t bytes;
2042    DEV_BLOCK *block = dcr->block;
2043    char ec1[50];
2044    char buf1[100], buf2[100];
2045
2046    blocks = block_size = tot_blocks = 0;
2047    bytes = 0;
2048
2049    empty_block(block);
2050    dev->update_pos(dcr);
2051    tot_files = dev->file;
2052    for (;;) {
2053       if (!dcr->read_block_from_device(NO_BLOCK_NUMBER_CHECK)) {
2054          Dmsg1(100, "!read_block(): ERR=%s\n", dev->bstrerror());
2055          if (dev->state & ST_EOT) {
2056             if (blocks > 0) {
2057                if (blocks==1) {
2058                   printf(_("1 block of %d bytes in file %d\n"), block_size, dev->file);
2059                }
2060                else {
2061                   printf(_("%d blocks of %d bytes in file %d\n"), blocks, block_size, dev->file);
2062                }
2063                blocks = 0;
2064             }
2065             goto bail_out;
2066          }
2067          if (dev->state & ST_EOF) {
2068             if (blocks > 0) {
2069                if (blocks==1) {
2070                   printf(_("1 block of %d bytes in file %d\n"), block_size, dev->file);
2071                }
2072                else {
2073                   printf(_("%d blocks of %d bytes in file %d\n"), blocks, block_size, dev->file);
2074                }
2075                blocks = 0;
2076             }
2077             printf(_("End of File mark.\n"));
2078             continue;
2079          }
2080          if (dev->state & ST_SHORT) {
2081             if (blocks > 0) {
2082                if (blocks==1) {
2083                   printf(_("1 block of %d bytes in file %d\n"), block_size, dev->file);
2084                }
2085                else {
2086                   printf(_("%d blocks of %d bytes in file %d\n"), blocks, block_size, dev->file);
2087                }
2088                blocks = 0;
2089             }
2090             printf(_("Short block read.\n"));
2091             continue;
2092          }
2093          printf(_("Error reading block. ERR=%s\n"), dev->bstrerror());
2094          goto bail_out;
2095       }
2096       if (block->block_len != block_size) {
2097          if (blocks > 0) {
2098             if (blocks==1) {
2099                printf(_("1 block of %d bytes in file %d\n"), block_size, dev->file);
2100             }
2101             else {
2102                printf(_("%d blocks of %d bytes in file %d\n"), blocks, block_size, dev->file);
2103             }
2104             blocks = 0;
2105          }
2106          block_size = block->block_len;
2107       }
2108       blocks++;
2109       tot_blocks++;
2110       bytes += block->block_len;
2111       Dmsg7(100, "Blk_blk=%u file,blk=%u,%u blen=%u bVer=%d SessId=%u SessTim=%u\n",
2112          block->BlockNumber, dev->file, dev->block_num, block->block_len, block->BlockVer,
2113          block->VolSessionId, block->VolSessionTime);
2114       if (verbose == 1) {
2115          DEV_RECORD *rec = new_record();
2116          read_record_from_block(dcr, rec);
2117          Pmsg9(-1, _("Block=%u file,blk=%u,%u blen=%u First rec FI=%s SessId=%u SessTim=%u Strm=%s rlen=%d\n"),
2118               block->BlockNumber, dev->file, dev->block_num, block->block_len,
2119               FI_to_ascii(buf1, rec->FileIndex), rec->VolSessionId, rec->VolSessionTime,
2120               stream_to_ascii(buf2, rec->Stream, rec->FileIndex), rec->data_len);
2121          rec->remainder = 0;
2122          free_record(rec);
2123       } else if (verbose > 1) {
2124          dump_block(block, "");
2125       }
2126
2127    }
2128 bail_out:
2129    tot_files = dev->file - tot_files;
2130    printf(_("Total files=%d, blocks=%d, bytes = %s\n"), tot_files, tot_blocks,
2131       edit_uint64_with_commas(bytes, ec1));
2132 }
2133
2134
2135 static void statcmd()
2136 {
2137    int64_t debug = debug_level;
2138    debug_level = 30;
2139    Pmsg2(0, _("Device status: %u. ERR=%s\n"), status_dev(dev), dev->bstrerror());
2140 #ifdef xxxx
2141    dump_volume_label(dev);
2142 #endif
2143    debug_level = debug;
2144 }
2145
2146
2147 /*
2148  * First we label the tape, then we fill
2149  *  it with data get a new tape and write a few blocks.
2150  */
2151 static void fillcmd()
2152 {
2153    DEV_RECORD rec;
2154    DEV_BLOCK  *block = dcr->block;
2155    char ec1[50], ec2[50];
2156    char buf1[100], buf2[100];
2157    uint64_t write_eof;
2158    uint64_t rate;
2159    uint32_t min_block_size;
2160    int fd;
2161    struct tm tm;
2162
2163    ok = true;
2164    stop = 0;
2165    vol_num = 0;
2166    last_file = 0;
2167    last_block_num = 0;
2168    BlockNumber = 0;
2169    exit_code = 0;
2170
2171    Pmsg1(-1, _("\n"
2172 "This command simulates Bacula writing to a tape.\n"
2173 "It requires either one or two blank tapes, which it\n"
2174 "will label and write.\n\n"
2175 "If you have an autochanger configured, it will use\n"
2176 "the tapes that are in slots 1 and 2, otherwise, you will\n"
2177 "be prompted to insert the tapes when necessary.\n\n"
2178 "It will print a status approximately\n"
2179 "every 322 MB, and write an EOF every %s.  If you have\n"
2180 "selected the simple test option, after writing the first tape\n"
2181 "it will rewind it and re-read the last block written.\n\n"
2182 "If you have selected the multiple tape test, when the first tape\n"
2183 "fills, it will ask for a second, and after writing a few more \n"
2184 "blocks, it will stop.  Then it will begin re-reading the\n"
2185 "two tapes.\n\n"
2186 "This may take a long time -- hours! ...\n\n"),
2187          edit_uint64_with_suffix(dev->max_file_size, buf1));
2188
2189    get_cmd(_("Do you want to run the simplified test (s) with one tape\n"
2190            "or the complete multiple tape (m) test: (s/m) "));
2191    if (cmd[0] == 's') {
2192       Pmsg0(-1, _("Simple test (single tape) selected.\n"));
2193       simple = true;
2194    } else if (cmd[0] == 'm') {
2195       Pmsg0(-1, _("Multiple tape test selected.\n"));
2196       simple = false;
2197    } else {
2198       Pmsg0(000, _("Command aborted.\n"));
2199       exit_code = 1;
2200       return;
2201    }
2202
2203    Dmsg1(20, "Begin append device=%s\n", dev->print_name());
2204    Dmsg1(20, "MaxVolSize=%s\n", edit_uint64(dev->max_volume_size, ec1));
2205
2206    /* Use fixed block size to simplify read back */
2207    min_block_size = dev->min_block_size;
2208    dev->min_block_size = dev->max_block_size;
2209    write_eof = dev->max_file_size / REC_SIZE; /*compute when we add EOF*/
2210    set_volume_name("TestVolume1", 1);
2211    dir_ask_sysop_to_create_appendable_volume(dcr);
2212    dev->set_append();                 /* force volume to be relabeled */
2213
2214    /*
2215     * Acquire output device for writing.  Note, after acquiring a
2216     *   device, we MUST release it, which is done at the end of this
2217     *   subroutine.
2218     */
2219    Dmsg0(100, "just before acquire_device\n");
2220    if (!acquire_device_for_append(dcr)) {
2221       jcr->setJobStatus(JS_ErrorTerminated);
2222       exit_code = 1;
2223       return;
2224    }
2225    block = jcr->dcr->block;
2226
2227    Dmsg0(100, "Just after acquire_device_for_append\n");
2228    /*
2229     * Write Begin Session Record
2230     */
2231    if (!write_session_label(dcr, SOS_LABEL)) {
2232       jcr->setJobStatus(JS_ErrorTerminated);
2233       Jmsg1(jcr, M_FATAL, 0, _("Write session label failed. ERR=%s\n"),
2234          dev->bstrerror());
2235       ok = false;
2236    }
2237    Pmsg0(-1, _("Wrote Start of Session label.\n"));
2238
2239    memset(&rec, 0, sizeof(rec));
2240    rec.data = get_memory(100000);     /* max record size */
2241    rec.data_len = REC_SIZE;
2242
2243    /*
2244     * Put some random data in the record
2245     */
2246    fill_buffer(FILL_RANDOM, rec.data, rec.data_len);
2247
2248    /*
2249     * Generate data as if from File daemon, write to device
2250     */
2251    jcr->dcr->VolFirstIndex = 0;
2252    time(&jcr->run_time);              /* start counting time for rates */
2253    (void)localtime_r(&jcr->run_time, &tm);
2254    strftime(buf1, sizeof(buf1), "%H:%M:%S", &tm);
2255    if (simple) {
2256       Pmsg1(-1, _("%s Begin writing Bacula records to tape ...\n"), buf1);
2257    } else {
2258       Pmsg1(-1, _("%s Begin writing Bacula records to first tape ...\n"), buf1);
2259    }
2260    for (file_index = 0; ok && !job_canceled(jcr); ) {
2261       rec.VolSessionId = jcr->VolSessionId;
2262       rec.VolSessionTime = jcr->VolSessionTime;
2263       rec.FileIndex = ++file_index;
2264       rec.Stream = STREAM_FILE_DATA;
2265       rec.maskedStream = STREAM_FILE_DATA;
2266
2267       /* Mix up the data just a bit */
2268       mix_buffer(FILL_RANDOM, rec.data, rec.data_len);
2269
2270       Dmsg4(250, "before write_rec FI=%d SessId=%d Strm=%s len=%d\n",
2271          rec.FileIndex, rec.VolSessionId,
2272          stream_to_ascii(buf1, rec.Stream, rec.FileIndex),
2273          rec.data_len);
2274
2275       while (!write_record_to_block(dcr, &rec)) {
2276          /*
2277           * When we get here we have just filled a block
2278           */
2279          Dmsg2(150, "!write_record_to_block data_len=%d rem=%d\n", rec.data_len,
2280                     rec.remainder);
2281
2282          /* Write block to tape */
2283          if (!flush_block(block, 1)) {
2284             Pmsg0(000, _("Flush block failed.\n"));
2285             exit_code = 1;
2286             break;
2287          }
2288
2289          /* Every 5000 blocks (approx 322MB) report where we are.
2290           */
2291          if ((block->BlockNumber % 5000) == 0) {
2292             now = time(NULL);
2293             now -= jcr->run_time;
2294             if (now <= 0) {
2295                now = 1;          /* prevent divide error */
2296             }
2297             rate = dev->VolCatInfo.VolCatBytes / now;
2298             Pmsg5(-1, _("Wrote block=%u, file,blk=%u,%u VolBytes=%s rate=%sB/s\n"),
2299                block->BlockNumber, dev->file, dev->block_num,
2300                edit_uint64_with_commas(dev->VolCatInfo.VolCatBytes, ec1),
2301                edit_uint64_with_suffix(rate, ec2));
2302          }
2303          /* Every X blocks (dev->max_file_size) write an EOF.
2304           */
2305          if ((block->BlockNumber % write_eof) == 0) {
2306             now = time(NULL);
2307             (void)localtime_r(&now, &tm);
2308             strftime(buf1, sizeof(buf1), "%H:%M:%S", &tm);
2309             Pmsg1(-1, _("%s Flush block, write EOF\n"), buf1);
2310             flush_block(block, 0);
2311 #ifdef needed_xxx
2312             dev->weof(1);
2313 #endif
2314          }
2315
2316          /* Get out after writing 1000 blocks to the second tape */
2317          if (++BlockNumber > 1000 && stop != 0) {      /* get out */
2318             Pmsg0(000, _("Wrote 1000 blocks on second tape. Done.\n"));
2319             break;
2320          }
2321       }
2322       if (!ok) {
2323          Pmsg0(000, _("Not OK\n"));
2324          exit_code = 1;
2325          break;
2326       }
2327       jcr->JobBytes += rec.data_len;   /* increment bytes this job */
2328       Dmsg4(190, "write_record FI=%s SessId=%d Strm=%s len=%d\n",
2329          FI_to_ascii(buf1, rec.FileIndex), rec.VolSessionId,
2330          stream_to_ascii(buf2, rec.Stream, rec.FileIndex), rec.data_len);
2331
2332       /* Get out after writing 1000 blocks to the second tape */
2333       if (BlockNumber > 1000 && stop != 0) {      /* get out */
2334          char ed1[50];
2335          Pmsg1(-1, "Done writing %s records ...\n",
2336              edit_uint64_with_commas(write_count, ed1));
2337          break;
2338       }
2339    } /* end big for loop */
2340
2341    if (vol_num > 1) {
2342       Dmsg0(100, "Write_end_session_label()\n");
2343       /* Create Job status for end of session label */
2344       if (!job_canceled(jcr) && ok) {
2345          jcr->setJobStatus(JS_Terminated);
2346       } else if (!ok) {
2347          Pmsg0(000, _("Job canceled.\n"));
2348          jcr->setJobStatus(JS_ErrorTerminated);
2349          exit_code = 1;
2350       }
2351       if (!write_session_label(dcr, EOS_LABEL)) {
2352          Pmsg1(000, _("Error writing end session label. ERR=%s\n"), dev->bstrerror());
2353          ok = false;
2354          exit_code = 1;
2355       }
2356       /* Write out final block of this session */
2357       if (!dcr->write_block_to_device()) {
2358          Pmsg0(-1, _("Set ok=false after write_block_to_device.\n"));
2359          ok = false;
2360          exit_code = 1;
2361       }
2362       Pmsg0(-1, _("Wrote End of Session label.\n"));
2363
2364       /* Save last block info for second tape */
2365       last_block_num2 = last_block_num;
2366       last_file2 = last_file;
2367       if (last_block2) {
2368          free_block(last_block2);
2369       }
2370       last_block2 = dup_block(last_block);
2371    }
2372
2373    sprintf(buf, "%s/btape.state", working_directory);
2374    fd = open(buf, O_CREAT|O_TRUNC|O_WRONLY, 0640);
2375    if (fd >= 0) {
2376       write(fd, &btape_state_level, sizeof(btape_state_level));
2377       write(fd, &simple, sizeof(simple));
2378       write(fd, &last_block_num1, sizeof(last_block_num1));
2379       write(fd, &last_block_num2, sizeof(last_block_num2));
2380       write(fd, &last_file1, sizeof(last_file1));
2381       write(fd, &last_file2, sizeof(last_file2));
2382       write(fd, last_block1->buf, last_block1->buf_len);
2383       write(fd, last_block2->buf, last_block2->buf_len);
2384       write(fd, first_block->buf, first_block->buf_len);
2385       close(fd);
2386       Pmsg2(0, _("Wrote state file last_block_num1=%d last_block_num2=%d\n"),
2387          last_block_num1, last_block_num2);
2388    } else {
2389       berrno be;
2390       Pmsg2(0, _("Could not create state file: %s ERR=%s\n"), buf,
2391                  be.bstrerror());
2392       exit_code = 1;
2393       ok = false;
2394    }
2395
2396    now = time(NULL);
2397    (void)localtime_r(&now, &tm);
2398    strftime(buf1, sizeof(buf1), "%H:%M:%S", &tm);
2399    if (ok) {
2400       if (simple) {
2401          Pmsg3(0, _("\n\n%s Done filling tape at %d:%d. Now beginning re-read of tape ...\n"),
2402                buf1, jcr->dcr->dev->file, jcr->dcr->dev->block_num);
2403       } else {
2404          Pmsg3(0, _("\n\n%s Done filling tapes at %d:%d. Now beginning re-read of first tape ...\n"),
2405                buf1, jcr->dcr->dev->file, jcr->dcr->dev->block_num);
2406       }
2407
2408       jcr->dcr->block = block;
2409       if (!do_unfill()) {
2410          Pmsg0(000, _("do_unfill failed.\n"));
2411          exit_code = 1;
2412          ok = false;
2413       }
2414    } else {
2415       Pmsg1(000, _("%s: Error during test.\n"), buf1);
2416    }
2417    dev->min_block_size = min_block_size;
2418    free_memory(rec.data);
2419 }
2420
2421 /*
2422  * Read two tapes written by the "fill" command and ensure
2423  *  that the data is valid.  If stop==1 we simulate full read back
2424  *  of two tapes.  If stop==-1 we simply read the last block and
2425  *  verify that it is correct.
2426  */
2427 static void unfillcmd()
2428 {
2429    int fd;
2430
2431    exit_code = 0;
2432    last_block1 = new_block(dev);
2433    last_block2 = new_block(dev);
2434    first_block = new_block(dev);
2435    sprintf(buf, "%s/btape.state", working_directory);
2436    fd = open(buf, O_RDONLY);
2437    if (fd >= 0) {
2438       uint32_t state_level;
2439       read(fd, &state_level, sizeof(btape_state_level));
2440       read(fd, &simple, sizeof(simple));
2441       read(fd, &last_block_num1, sizeof(last_block_num1));
2442       read(fd, &last_block_num2, sizeof(last_block_num2));
2443       read(fd, &last_file1, sizeof(last_file1));
2444       read(fd, &last_file2, sizeof(last_file2));
2445       read(fd, last_block1->buf, last_block1->buf_len);
2446       read(fd, last_block2->buf, last_block2->buf_len);
2447       read(fd, first_block->buf, first_block->buf_len);
2448       close(fd);
2449       if (state_level != btape_state_level) {
2450           Pmsg0(-1, _("\nThe state file level has changed. You must redo\n"
2451                   "the fill command.\n"));
2452           exit_code = 1;
2453           return;
2454        }
2455    } else {
2456       berrno be;
2457       Pmsg2(-1, _("\nCould not find the state file: %s ERR=%s\n"
2458              "You must redo the fill command.\n"), buf, be.bstrerror());
2459       exit_code = 1;
2460       return;
2461    }
2462    if (!do_unfill()) {
2463       exit_code = 1;
2464    }
2465    this_block = NULL;
2466 }
2467
2468 /*
2469  * This is the second part of the fill command. After the tape or
2470  *  tapes are written, we are called here to reread parts, particularly
2471  *  the last block.
2472  */
2473 static bool do_unfill()
2474 {
2475    DEV_BLOCK *block = dcr->block;
2476    int autochanger;
2477    bool rc = false;
2478
2479    dumped = 0;
2480    VolBytes = 0;
2481    LastBlock = 0;
2482
2483    Pmsg0(000, "Enter do_unfill\n");
2484    dev->set_cap(CAP_ANONVOLS);        /* allow reading any volume */
2485    dev->clear_cap(CAP_LABEL);         /* don't label anything here */
2486
2487    end_of_tape = 0;
2488
2489    time(&jcr->run_time);              /* start counting time for rates */
2490    stop = 0;
2491    file_index = 0;
2492    if (last_block) {
2493       free_block(last_block);
2494       last_block = NULL;
2495    }
2496    last_block_num = last_block_num1;
2497    last_file = last_file1;
2498    last_block = last_block1;
2499
2500    free_restore_volume_list(jcr);
2501    jcr->bsr = NULL;
2502    bstrncpy(dcr->VolumeName, "TestVolume1|TestVolume2", sizeof(dcr->VolumeName));
2503    create_restore_volume_list(jcr);
2504    if (jcr->VolList != NULL) {
2505       jcr->VolList->Slot = 1;
2506       if (jcr->VolList->next != NULL) {
2507          jcr->VolList->next->Slot = 2;
2508       }
2509    }
2510
2511    set_volume_name("TestVolume1", 1);
2512
2513    if (!simple) {
2514       /* Multiple Volume tape */
2515       /* Close device so user can use autochanger if desired */
2516       if (dev->has_cap(CAP_OFFLINEUNMOUNT)) {
2517          dev->offline();
2518       }
2519       autochanger = autoload_device(dcr, 1, NULL);
2520       if (autochanger != 1) {
2521          Pmsg1(100, "Autochanger returned: %d\n", autochanger);
2522          dev->close();
2523          get_cmd(_("Mount first tape. Press enter when ready: "));
2524          Pmsg0(000, "\n");
2525       }
2526    }
2527
2528    dev->close();
2529    dev->num_writers = 0;
2530    if (!acquire_device_for_read(dcr)) {
2531       Pmsg1(-1, "%s", dev->errmsg);
2532       goto bail_out;
2533    }
2534    /*
2535     * We now have the first tape mounted.
2536     * Note, re-reading last block may have caused us to
2537     *   loose track of where we are (block number unknown).
2538     */
2539    Pmsg0(-1, _("Rewinding.\n"));
2540    if (!dev->rewind(dcr)) {                /* get to a known place on tape */
2541       goto bail_out;
2542    }
2543    /* Read the first 10000 records */
2544    Pmsg2(-1, _("Reading the first 10000 records from %u:%u.\n"),
2545       dev->file, dev->block_num);
2546    quickie_count = 0;
2547    read_records(dcr, quickie_cb, my_mount_next_read_volume);
2548    Pmsg4(-1, _("Reposition from %u:%u to %u:%u\n"), dev->file, dev->block_num,
2549          last_file, last_block_num);
2550    if (!dev->reposition(dcr, last_file, last_block_num)) {
2551       Pmsg1(-1, _("Reposition error. ERR=%s\n"), dev->bstrerror());
2552       goto bail_out;
2553    }
2554    Pmsg1(-1, _("Reading block %u.\n"), last_block_num);
2555    if (!dcr->read_block_from_device(NO_BLOCK_NUMBER_CHECK)) {
2556       Pmsg1(-1, _("Error reading block: ERR=%s\n"), dev->bstrerror());
2557       goto bail_out;
2558    }
2559    if (compare_blocks(last_block, block)) {
2560       if (simple) {
2561          Pmsg0(-1, _("\nThe last block on the tape matches. Test succeeded.\n\n"));
2562          rc = true;
2563       } else {
2564          Pmsg0(-1, _("\nThe last block of the first tape matches.\n\n"));
2565       }
2566    }
2567    if (simple) {
2568       goto bail_out;
2569    }
2570
2571    /* restore info for last block on second Volume */
2572    last_block_num = last_block_num2;
2573    last_file = last_file2;
2574    last_block = last_block2;
2575
2576    /* Multiple Volume tape */
2577    /* Close device so user can use autochanger if desired */
2578    if (dev->has_cap(CAP_OFFLINEUNMOUNT)) {
2579       dev->offline();
2580    }
2581
2582    set_volume_name("TestVolume2", 2);
2583
2584    autochanger = autoload_device(dcr, 1, NULL);
2585    if (autochanger != 1) {
2586       Pmsg1(100, "Autochanger returned: %d\n", autochanger);
2587       dev->close();
2588       get_cmd(_("Mount second tape. Press enter when ready: "));
2589       Pmsg0(000, "\n");
2590    }
2591
2592    dev->clear_read();
2593    if (!acquire_device_for_read(dcr)) {
2594       Pmsg1(-1, "%s", dev->errmsg);
2595       goto bail_out;
2596    }
2597
2598    /* Space to "first" block which is last block not written
2599     * on the previous tape.
2600     */
2601    Pmsg2(-1, _("Reposition from %u:%u to 0:1\n"), dev->file, dev->block_num);
2602    if (!dev->reposition(dcr, 0, 1)) {
2603       Pmsg1(-1, _("Reposition error. ERR=%s\n"), dev->bstrerror());
2604       goto bail_out;
2605    }
2606    Pmsg1(-1, _("Reading block %d.\n"), dev->block_num);
2607    if (!dcr->read_block_from_device(NO_BLOCK_NUMBER_CHECK)) {
2608       Pmsg1(-1, _("Error reading block: ERR=%s\n"), dev->bstrerror());
2609       goto bail_out;
2610    }
2611    if (compare_blocks(first_block, block)) {
2612       Pmsg0(-1, _("\nThe first block on the second tape matches.\n\n"));
2613    }
2614
2615    /* Now find and compare the last block */
2616    Pmsg4(-1, _("Reposition from %u:%u to %u:%u\n"), dev->file, dev->block_num,
2617          last_file, last_block_num);
2618    if (!dev->reposition(dcr, last_file, last_block_num)) {
2619       Pmsg1(-1, _("Reposition error. ERR=%s\n"), dev->bstrerror());
2620       goto bail_out;
2621    }
2622    Pmsg1(-1, _("Reading block %d.\n"), dev->block_num);
2623    if (!dcr->read_block_from_device(NO_BLOCK_NUMBER_CHECK)) {
2624       Pmsg1(-1, _("Error reading block: ERR=%s\n"), dev->bstrerror());
2625       goto bail_out;
2626    }
2627    if (compare_blocks(last_block, block)) {
2628       Pmsg0(-1, _("\nThe last block on the second tape matches. Test succeeded.\n\n"));
2629       rc = true;
2630    }
2631
2632 bail_out:
2633    free_block(last_block1);
2634    free_block(last_block2);
2635    free_block(first_block);
2636    last_block = first_block = last_block1 = last_block2 = NULL;
2637    return rc;
2638 }
2639
2640 /* Read 10000 records then stop */
2641 static bool quickie_cb(DCR *dcr, DEV_RECORD *rec)
2642 {
2643    DEVICE *dev = dcr->dev;
2644    quickie_count++;
2645    if (quickie_count == 10000) {
2646       Pmsg2(-1, _("10000 records read now at %d:%d\n"), dev->file, dev->block_num);
2647    }
2648    return quickie_count < 10000;
2649 }
2650
2651 static bool compare_blocks(DEV_BLOCK *last_block, DEV_BLOCK *block)
2652 {
2653    char *p, *q;
2654    union {
2655       uint32_t CheckSum;
2656       uint32_t block_len;
2657    };
2658    ser_declare;
2659
2660    p = last_block->buf;
2661    q = block->buf;
2662    unser_begin(q, BLKHDR2_LENGTH);
2663    unser_uint32(CheckSum);
2664    unser_uint32(block_len);
2665    while (q < (block->buf+block_len)) {
2666       if (*p == *q) {
2667          p++;
2668          q++;
2669          continue;
2670       }
2671       Pmsg0(-1, "\n");
2672       dump_block(last_block, _("Last block written"));
2673       Pmsg0(-1, "\n");
2674       dump_block(block, _("Block read back"));
2675       Pmsg1(-1, _("\n\nThe blocks differ at byte %u\n"), p - last_block->buf);
2676       Pmsg0(-1, _("\n\n!!!! The last block written and the block\n"
2677                 "that was read back differ. The test FAILED !!!!\n"
2678                 "This must be corrected before you use Bacula\n"
2679                 "to write multi-tape Volumes.!!!!\n"));
2680       return false;
2681    }
2682    if (verbose) {
2683       dump_block(last_block, _("Last block written"));
2684       dump_block(block, _("Block read back"));
2685    }
2686    return true;
2687 }
2688
2689 /*
2690  * Write current block to tape regardless of whether or
2691  *   not it is full. If the tape fills, attempt to
2692  *   acquire another tape.
2693  */
2694 static int flush_block(DEV_BLOCK *block, int dump)
2695 {
2696    char ec1[50], ec2[50];
2697    uint64_t rate;
2698    DEV_BLOCK *tblock;
2699    uint32_t this_file, this_block_num;
2700
2701    dev->rLock(false);
2702    if (!this_block) {
2703       this_block = new_block(dev);
2704    }
2705    if (!last_block) {
2706       last_block = new_block(dev);
2707    }
2708    /* Copy block */
2709    this_file = dev->file;
2710    this_block_num = dev->block_num;
2711    if (!dcr->write_block_to_dev()) {
2712       Pmsg3(000, _("Last block at: %u:%u this_dev_block_num=%d\n"),
2713                   last_file, last_block_num, this_block_num);
2714       if (vol_num == 1) {
2715          /*
2716           * This is 1st tape, so save first tape info separate
2717           *  from second tape info
2718           */
2719          last_block_num1 = last_block_num;
2720          last_file1 = last_file;
2721          last_block1 = dup_block(last_block);
2722          last_block2 = dup_block(last_block);
2723          first_block = dup_block(block); /* first block second tape */
2724       }
2725       if (verbose) {
2726          Pmsg3(000, _("Block not written: FileIndex=%u blk_block=%u Size=%u\n"),
2727             (unsigned)file_index, block->BlockNumber, block->block_len);
2728          dump_block(last_block, _("Last block written"));
2729          Pmsg0(-1, "\n");
2730          dump_block(block, _("Block not written"));
2731       }
2732       if (stop == 0) {
2733          eot_block = block->BlockNumber;
2734          eot_block_len = block->block_len;
2735          eot_FileIndex = file_index;
2736          stop = 1;
2737       }
2738       now = time(NULL);
2739       now -= jcr->run_time;
2740       if (now <= 0) {
2741          now = 1;                     /* don't divide by zero */
2742       }
2743       rate = dev->VolCatInfo.VolCatBytes / now;
2744       vol_size = dev->VolCatInfo.VolCatBytes;
2745       Pmsg4(000, _("End of tape %d:%d. Volume Bytes=%s. Write rate = %sB/s\n"),
2746          dev->file, dev->block_num,
2747          edit_uint64_with_commas(dev->VolCatInfo.VolCatBytes, ec1),
2748          edit_uint64_with_suffix(rate, ec2));
2749
2750       if (simple) {
2751          stop = -1;                   /* stop, but do simplified test */
2752       } else {
2753          /* Full test in progress */
2754          if (!fixup_device_block_write_error(jcr->dcr)) {
2755             Pmsg1(000, _("Cannot fixup device error. %s\n"), dev->bstrerror());
2756             ok = false;
2757             dev->Unlock();
2758             return 0;
2759          }
2760          BlockNumber = 0;             /* start counting for second tape */
2761       }
2762       dev->Unlock();
2763       return 1;                       /* end of tape reached */
2764    }
2765
2766    /* Save contents after write so that the header is serialized */
2767    memcpy(this_block->buf, block->buf, this_block->buf_len);
2768
2769    /*
2770     * Note, we always read/write to block, but we toggle
2771     *  copying it to one or another of two allocated blocks.
2772     * Switch blocks so that the block just successfully written is
2773     *  always in last_block.
2774     */
2775    tblock = last_block;
2776    last_block = this_block;
2777    this_block = tblock;
2778    last_file = this_file;
2779    last_block_num = this_block_num;
2780
2781    dev->Unlock();
2782    return 1;
2783 }
2784
2785
2786 /*
2787  * First we label the tape, then we fill
2788  *  it with data get a new tape and write a few blocks.
2789  */
2790 static void qfillcmd()
2791 {
2792    DEV_BLOCK *block = dcr->block;
2793    DEV_RECORD *rec = dcr->rec;
2794    int i, count;
2795
2796    Pmsg0(0, _("Test writing blocks of 64512 bytes to tape.\n"));
2797
2798    get_cmd(_("How many blocks do you want to write? (1000): "));
2799
2800    count = atoi(cmd);
2801    if (count <= 0) {
2802       count = 1000;
2803    }
2804
2805    Dsm_check(200);
2806
2807    i = block->buf_len - 100;
2808    ASSERT (i > 0);
2809    rec->data = check_pool_memory_size(rec->data, i);
2810    memset(rec->data, i & 0xFF, i);
2811    rec->data_len = i;
2812    rewindcmd();
2813    init_speed();
2814
2815    Pmsg1(0, _("Begin writing %d Bacula blocks to tape ...\n"), count);
2816    for (i=0; i < count; i++) {
2817       if (i % 100 == 0) {
2818          printf("+");
2819          fflush(stdout);
2820       }
2821       if (!write_record_to_block(dcr, rec)) {
2822          Pmsg0(0, _("Error writing record to block.\n"));
2823          goto bail_out;
2824       }
2825       if (!dcr->write_block_to_dev()) {
2826          Pmsg0(0, _("Error writing block to device.\n"));
2827          goto bail_out;
2828       }
2829    }
2830    printf("\n");
2831    print_speed(dev->VolCatInfo.VolCatBytes);
2832    weofcmd();
2833    if (dev->has_cap(CAP_TWOEOF)) {
2834       weofcmd();
2835    }
2836    rewindcmd();
2837    scan_blocks();
2838
2839 bail_out:
2840    Dsm_check(200);
2841 }
2842
2843 /*
2844  * Fill a tape using raw write() command
2845  */
2846 static void rawfill_cmd()
2847 {
2848    DEV_BLOCK *block = dcr->block;
2849    int stat;
2850    uint32_t block_num = 0;
2851    uint32_t *p;
2852    int my_errno;
2853
2854    fill_buffer(FILL_RANDOM, block->buf, block->buf_len);
2855    init_speed();
2856
2857    p = (uint32_t *)block->buf;
2858    Pmsg1(0, _("Begin writing raw blocks of %u bytes.\n"), block->buf_len);
2859    for ( ;; ) {
2860       *p = block_num;
2861       stat = dev->d_write(dev->fd(), block->buf, block->buf_len);
2862       if (stat == (int)block->buf_len) {
2863          if ((block_num++ % 100) == 0) {
2864             printf("+");
2865             fflush(stdout);
2866          }
2867
2868          mix_buffer(FILL_RANDOM, block->buf, block->buf_len);
2869
2870          jcr->JobBytes += stat;
2871          continue;
2872       }
2873       break;
2874    }
2875    my_errno = errno;
2876    printf("\n");
2877    berrno be;
2878    printf(_("Write failed at block %u. stat=%d ERR=%s\n"), block_num, stat,
2879       be.bstrerror(my_errno));
2880
2881    print_speed(jcr->JobBytes);
2882    weofcmd();
2883 }
2884
2885
2886
2887 struct cmdstruct { const char *key; void (*func)(); const char *help; };
2888 static struct cmdstruct commands[] = {
2889  {NT_("autochanger"),autochangercmd, _("test autochanger")},
2890  {NT_("bsf"),       bsfcmd,       _("backspace file")},
2891  {NT_("bsr"),       bsrcmd,       _("backspace record")},
2892  {NT_("cap"),       capcmd,       _("list device capabilities")},
2893  {NT_("clear"),     clearcmd,     _("clear tape errors")},
2894  {NT_("eod"),       eodcmd,       _("go to end of Bacula data for append")},
2895  {NT_("eom"),       eomcmd,       _("go to the physical end of medium")},
2896  {NT_("fill"),      fillcmd,      _("fill tape, write onto second volume")},
2897  {NT_("unfill"),    unfillcmd,    _("read filled tape")},
2898  {NT_("fsf"),       fsfcmd,       _("forward space a file")},
2899  {NT_("fsr"),       fsrcmd,       _("forward space a record")},
2900  {NT_("help"),      helpcmd,      _("print this command")},
2901  {NT_("label"),     labelcmd,     _("write a Bacula label to the tape")},
2902  {NT_("load"),      loadcmd,      _("load a tape")},
2903  {NT_("quit"),      quitcmd,      _("quit btape")},
2904  {NT_("rawfill"),   rawfill_cmd,  _("use write() to fill tape")},
2905  {NT_("readlabel"), readlabelcmd, _("read and print the Bacula tape label")},
2906  {NT_("rectest"),   rectestcmd,   _("test record handling functions")},
2907  {NT_("rewind"),    rewindcmd,    _("rewind the tape")},
2908  {NT_("scan"),      scancmd,      _("read() tape block by block to EOT and report")},
2909  {NT_("scanblocks"),scan_blocks,  _("Bacula read block by block to EOT and report")},
2910  {NT_("speed"),     speed_test,   _("[file_size=n(GB)|nb_file=3|skip_zero|skip_random|skip_raw|skip_block] report drive speed")},
2911  {NT_("status"),    statcmd,      _("print tape status")},
2912  {NT_("test"),      testcmd,      _("General test Bacula tape functions")},
2913  {NT_("weof"),      weofcmd,      _("write an EOF on the tape")},
2914  {NT_("wr"),        wrcmd,        _("write a single Bacula block")},
2915  {NT_("rr"),        rrcmd,        _("read a single record")},
2916  {NT_("rb"),        rbcmd,        _("read a single Bacula block")},
2917  {NT_("qfill"),     qfillcmd,     _("quick fill command")}
2918              };
2919 #define comsize (sizeof(commands)/sizeof(struct cmdstruct))
2920
2921 static void
2922 do_tape_cmds()
2923 {
2924    unsigned int i;
2925    bool found;
2926
2927    while (!quit && get_cmd("*")) {
2928       Dsm_check(200);
2929       found = false;
2930       parse_args(cmd, &args, &argc, argk, argv, MAX_CMD_ARGS);
2931       for (i=0; i<comsize; i++)       /* search for command */
2932          if (argc > 0 && fstrsch(argk[0],  commands[i].key)) {
2933             (*commands[i].func)();    /* go execute command */
2934             found = true;
2935             break;
2936          }
2937       if (*cmd && !found) {
2938          Pmsg1(0, _("\"%s\" is an invalid command\n"), cmd);
2939       }
2940    }
2941 }
2942
2943 static void helpcmd()
2944 {
2945    unsigned int i;
2946    usage();
2947    printf(_("Interactive commands:\n"));
2948    printf(_("  Command    Description\n  =======    ===========\n"));
2949    for (i=0; i<comsize; i++)
2950       printf("  %-10s %s\n", commands[i].key, commands[i].help);
2951    printf("\n");
2952 }
2953
2954 static void usage()
2955 {
2956    fprintf(stderr, _(
2957 PROG_COPYRIGHT
2958 "\nVersion: %s (%s)\n\n"
2959 "Usage: btape <options> <device_name>\n"
2960 "       -b <file>   specify bootstrap file\n"
2961 "       -c <file>   set configuration file to file\n"
2962 "       -d <nn>     set debug level to <nn>\n"
2963 "       -dt         print timestamp in debug output\n"
2964 "       -p          proceed inspite of I/O errors\n"
2965 "       -s          turn off signals\n"
2966 "       -v          be verbose\n"
2967 "       -?          print this message.\n"
2968 "\n"), 2000, VERSION, BDATE);
2969
2970 }
2971
2972 /*
2973  * Get next input command from terminal.  This
2974  * routine is REALLY primitive, and should be enhanced
2975  * to have correct backspacing, etc.
2976  */
2977 int
2978 get_cmd(const char *prompt)
2979 {
2980    int i = 0;
2981    int ch;
2982
2983    fprintf(stdout, "%s", prompt);
2984
2985    /* We really should turn off echoing and pretty this
2986     * up a bit.
2987     */
2988    cmd[i] = 0;
2989    while ((ch = fgetc(stdin)) != EOF) {
2990       if (ch == '\n') {
2991          strip_trailing_junk(cmd);
2992          return 1;
2993       } else if (ch == 4 || ch == 0xd3 || ch == 0x8) {
2994          if (i > 0) {
2995             cmd[--i] = 0;
2996          }
2997          continue;
2998       }
2999
3000       cmd[i++] = ch;
3001       cmd[i] = 0;
3002    }
3003    quit = 1;
3004    return 0;
3005 }
3006
3007 /* Dummies to replace askdir.c */
3008 bool    dir_update_file_attributes(DCR *dcr, DEV_RECORD *rec) { return 1;}
3009 bool    dir_send_job_status(JCR *jcr) {return 1;}
3010
3011 bool dir_update_volume_info(DCR *dcr, bool relabel, bool update_LastWritten)
3012 {
3013    return 1;
3014 }
3015
3016
3017 bool dir_get_volume_info(DCR *dcr, enum get_vol_info_rw  writing)
3018 {
3019    Dmsg0(20, "Enter dir_get_volume_info\n");
3020    dcr->setVolCatName(dcr->VolumeName);
3021    return 1;
3022 }
3023
3024 bool dir_create_jobmedia_record(DCR *dcr, bool zero)
3025 {
3026    dcr->WroteVol = false;
3027    return 1;
3028 }
3029
3030
3031 bool dir_find_next_appendable_volume(DCR *dcr)
3032 {
3033    Dmsg1(20, "Enter dir_find_next_appendable_volume. stop=%d\n", stop);
3034    return dcr->VolumeName[0] != 0;
3035 }
3036
3037 bool dir_ask_sysop_to_mount_volume(DCR *dcr, bool /* writing */)
3038 {
3039    DEVICE *dev = dcr->dev;
3040    Dmsg0(20, "Enter dir_ask_sysop_to_mount_volume\n");
3041    if (dcr->VolumeName[0] == 0) {
3042       return dir_ask_sysop_to_create_appendable_volume(dcr);
3043    }
3044    Pmsg1(-1, "%s", dev->errmsg);           /* print reason */
3045    if (dcr->VolumeName[0] == 0 || strcmp(dcr->VolumeName, "TestVolume2") == 0) {
3046       fprintf(stderr, _("Mount second Volume on device %s and press return when ready: "),
3047          dev->print_name());
3048    } else {
3049       fprintf(stderr, _("Mount Volume \"%s\" on device %s and press return when ready: "),
3050          dcr->VolumeName, dev->print_name());
3051    }
3052    dev->close();
3053    getchar();
3054    return true;
3055 }
3056
3057 bool dir_ask_sysop_to_create_appendable_volume(DCR *dcr)
3058 {
3059    int autochanger;
3060    DEVICE *dev = dcr->dev;
3061    Dmsg0(20, "Enter dir_ask_sysop_to_create_appendable_volume\n");
3062    if (stop == 0) {
3063       set_volume_name("TestVolume1", 1);
3064    } else {
3065       set_volume_name("TestVolume2", 2);
3066    }
3067    /* Close device so user can use autochanger if desired */
3068    if (dev->has_cap(CAP_OFFLINEUNMOUNT)) {
3069       dev->offline();
3070    }
3071    autochanger = autoload_device(dcr, 1, NULL);
3072    if (autochanger != 1) {
3073       Pmsg1(100, "Autochanger returned: %d\n", autochanger);
3074       fprintf(stderr, _("Mount blank Volume on device %s and press return when ready: "),
3075          dev->print_name());
3076       dev->close();
3077       getchar();
3078       Pmsg0(000, "\n");
3079    }
3080    labelcmd();
3081    VolumeName = NULL;
3082    BlockNumber = 0;
3083    return true;
3084 }
3085
3086 static bool my_mount_next_read_volume(DCR *dcr)
3087 {
3088    char ec1[50], ec2[50];
3089    uint64_t rate;
3090    JCR *jcr = dcr->jcr;
3091    DEV_BLOCK *block = dcr->block;
3092
3093    Dmsg0(20, "Enter my_mount_next_read_volume\n");
3094    Pmsg2(000, _("End of Volume \"%s\" %d records.\n"), dcr->VolumeName,
3095       quickie_count);
3096
3097    volume_unused(dcr);             /* release current volume */
3098    if (LastBlock != block->BlockNumber) {
3099       VolBytes += block->block_len;
3100    }
3101    LastBlock = block->BlockNumber;
3102    now = time(NULL);
3103    now -= jcr->run_time;
3104    if (now <= 0) {
3105       now = 1;
3106    }
3107    rate = VolBytes / now;
3108    Pmsg3(-1, _("Read block=%u, VolBytes=%s rate=%sB/s\n"), block->BlockNumber,
3109             edit_uint64_with_commas(VolBytes, ec1),
3110             edit_uint64_with_suffix(rate, ec2));
3111
3112    if (strcmp(dcr->VolumeName, "TestVolume2") == 0) {
3113       end_of_tape = 1;
3114       return false;
3115    }
3116
3117    set_volume_name("TestVolume2", 2);
3118
3119    dev->close();
3120    if (!acquire_device_for_read(dcr)) {
3121       Pmsg2(0, _("Cannot open Dev=%s, Vol=%s\n"), dev->print_name(), dcr->VolumeName);
3122       return false;
3123    }
3124    return true;                    /* next volume mounted */
3125 }
3126
3127 static void set_volume_name(const char *VolName, int volnum)
3128 {
3129    DCR *dcr = jcr->dcr;
3130    VolumeName = VolName;
3131    vol_num = volnum;
3132    dev->setVolCatName(VolName);
3133    dcr->setVolCatName(VolName);
3134    bstrncpy(dcr->VolumeName, VolName, sizeof(dcr->VolumeName));
3135    dcr->VolCatInfo.Slot = volnum;
3136    dcr->VolCatInfo.InChanger = true;
3137 }