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