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