]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/stored/btape.c
Make btape fill/unfill work
[bacula/bacula] / bacula / src / stored / btape.c
1 /*
2  *
3  *   Bacula Tape manipulation program
4  *
5  *    Has various tape manipulation commands -- mostly for
6  *    use in determining how tapes really work.
7  *
8  *     Kern Sibbald, April MM
9  *
10  *   Note, this program reads stored.conf, and will only
11  *     talk to devices that are configured.
12  *
13  *   Version $Id$
14  *
15  */
16 /*
17    Copyright (C) 2000-2003 Kern Sibbald and John Walker
18
19    This program is free software; you can redistribute it and/or
20    modify it under the terms of the GNU General Public License as
21    published by the Free Software Foundation; either version 2 of
22    the License, or (at your option) any later version.
23
24    This program is distributed in the hope that it will be useful,
25    but WITHOUT ANY WARRANTY; without even the implied warranty of
26    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
27    General Public License for more details.
28
29    You should have received a copy of the GNU General Public
30    License along with this program; if not, write to the Free
31    Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
32    MA 02111-1307, USA.
33
34  */
35
36 #include "bacula.h"
37 #include "stored.h"
38
39
40 /* External subroutines */
41 extern void free_config_resources();
42
43 /* Exported variables */
44 int quit = 0;
45 char buf[100000];
46 int bsize = TAPE_BSIZE;
47 char VolName[MAX_NAME_LENGTH];
48
49 DEVICE *dev = NULL;
50 DEVRES *device = NULL;
51
52             
53 /* Forward referenced subroutines */
54 static void do_tape_cmds();
55 static void helpcmd();
56 static void scancmd();
57 static void rewindcmd();
58 static void clearcmd();
59 static void wrcmd();
60 static void rrcmd();
61 static void eodcmd();
62 static void fillcmd();
63 static void statcmd();
64 static void unfillcmd();
65 static int flush_block(DEV_BLOCK *block, int dump);
66 static void record_cb(JCR *jcr, DEVICE *dev, DEV_BLOCK *block, DEV_RECORD *rec);
67 static int my_mount_next_read_volume(JCR *jcr, DEVICE *dev, DEV_BLOCK *block);
68 static void scan_blocks();
69 static void set_volume_name(char *VolName, int volnum);
70
71
72 /* Static variables */
73 #define CONFIG_FILE "bacula-sd.conf"
74 char *configfile;
75
76 static BSR *bsr = NULL;
77 static char cmd[1000];
78 static int signals = TRUE;
79 static int ok;
80 static int stop;
81 static uint64_t vol_size;
82 static uint64_t VolBytes;
83 static time_t now;
84 static double kbs;
85 static long file_index;
86 static int end_of_tape = 0;
87 static uint32_t LastBlock = 0;
88 static uint32_t eot_block;
89 static uint32_t eot_block_len;
90 static uint32_t eot_FileIndex;
91 static int dumped = 0;
92 static DEV_BLOCK *last_block = NULL;
93 static DEV_BLOCK *this_block = NULL;
94 static uint32_t last_file = 0;
95 static uint32_t last_block_num = 0;
96 static uint32_t BlockNumber = 0;
97 static int simple = FALSE;
98
99 static char *VolumeName = NULL;
100 static int vol_num;
101
102 static JCR *jcr = NULL;
103
104
105 static void usage();
106 static void terminate_btape(int sig);
107 int get_cmd(char *prompt);
108
109
110 int write_dev(DEVICE *dev, char *buf, size_t len) 
111 {
112    Emsg0(M_ABORT, 0, "write_dev not implemented.\n");
113    return 0;
114 }
115
116 int read_dev(DEVICE *dev, char *buf, size_t len)
117 {
118    Emsg0(M_ABORT, 0, "read_dev not implemented.\n");
119    return 0;
120 }
121
122
123 /*********************************************************************
124  *
125  *         Main Bacula Pool Creation Program
126  *
127  */
128 int main(int argc, char *argv[])
129 {
130    int ch;
131    DEV_BLOCK *block;
132
133    /* Sanity checks */
134    if (TAPE_BSIZE % DEV_BSIZE != 0 || TAPE_BSIZE / DEV_BSIZE == 0) {
135       Emsg2(M_ABORT, 0, "Tape block size (%d) not multiple of system size (%d)\n",
136          TAPE_BSIZE, DEV_BSIZE);
137    }
138    if (TAPE_BSIZE != (1 << (ffs(TAPE_BSIZE)-1))) {
139       Emsg1(M_ABORT, 0, "Tape block size (%d) is not a power of 2\n", TAPE_BSIZE);
140    }
141
142    printf("Tape block granularity is %d bytes.\n", TAPE_BSIZE);
143
144    working_directory = "/tmp";
145    my_name_is(argc, argv, "btape");
146    init_msg(NULL, NULL);
147
148    while ((ch = getopt(argc, argv, "b:c:d:sv?")) != -1) {
149       switch (ch) {
150          case 'b':                    /* bootstrap file */
151             bsr = parse_bsr(NULL, optarg);
152 //          dump_bsr(bsr);
153             break;
154
155          case 'c':                    /* specify config file */
156             if (configfile != NULL) {
157                free(configfile);
158             }
159             configfile = bstrdup(optarg);
160             break;
161
162          case 'd':                    /* set debug level */
163             debug_level = atoi(optarg);
164             if (debug_level <= 0) {
165                debug_level = 1; 
166             }
167             break;
168
169          case 's':
170             signals = FALSE;
171             break;
172
173          case 'v':
174             verbose++;
175             break;
176
177          case '?':
178          default:
179             helpcmd();
180             exit(0);
181
182       }  
183    }
184    argc -= optind;
185    argv += optind;
186
187
188    
189    if (signals) {
190       init_signals(terminate_btape);
191    }
192
193    if (configfile == NULL) {
194       configfile = bstrdup(CONFIG_FILE);
195    }
196
197    daemon_start_time = time(NULL);
198
199    parse_config(configfile);
200
201
202    /* See if we can open a device */
203    if (argc == 0) {
204       Pmsg0(000, "No archive name specified.\n");
205       usage();
206       exit(1);
207    } else if (argc != 1) {
208       Pmsg0(000, "Improper number of arguments specified.\n");
209       usage();
210       exit(1);
211    }
212
213    jcr = setup_jcr("btape", argv[0], bsr, NULL);
214    dev = setup_to_access_device(jcr, 0);     /* acquire for write */
215    if (!dev) {
216       exit(1);
217    }
218    block = new_block(dev);
219    lock_device(dev);
220    if (!(dev->state & ST_OPENED)) {
221       Dmsg0(129, "Opening device.\n");
222       if (open_dev(dev, jcr->VolumeName, READ_WRITE) < 0) {
223          Emsg1(M_FATAL, 0, _("dev open failed: %s\n"), dev->errmsg);
224          unlock_device(dev);
225          free_block(block);
226          goto terminate;
227       }
228    }
229    Dmsg1(129, "open_dev %s OK\n", dev_name(dev));
230    unlock_device(dev);
231    free_block(block);
232
233    Dmsg0(200, "Do tape commands\n");
234    do_tape_cmds();
235   
236 terminate:
237    terminate_btape(0);
238    return 0;
239 }
240
241 static void terminate_btape(int stat)
242 {
243
244    sm_check(__FILE__, __LINE__, False);
245    if (configfile) {
246       free(configfile);
247    }
248    free_config_resources();
249
250    if (dev) {
251       term_dev(dev);
252    }
253
254    if (debug_level > 10)
255       print_memory_pool_stats(); 
256
257    free_jcr(jcr);
258    jcr = NULL;
259
260    if (bsr) {
261       free_bsr(bsr);
262    }
263
264    if (last_block) {
265       free_block(last_block);
266    }
267    if (this_block) {
268       free_block(this_block);
269    }
270
271    term_msg();
272    close_memory_pool();               /* free memory in pool */
273
274    sm_dump(False);
275    exit(stat);
276 }
277
278 void quitcmd()
279 {
280    quit = 1;
281 }
282
283 /*
284  * Write a label to the tape   
285  */
286 static void labelcmd()
287 {
288    DEVRES *device;
289    int found = 0;
290
291    LockRes();
292    for (device=NULL; (device=(DEVRES *)GetNextRes(R_DEVICE, (RES *)device)); ) {
293       if (strcmp(device->device_name, dev->dev_name) == 0) {
294          jcr->device = device;        /* Arggg a bit of duplication here */
295          device->dev = dev;
296          dev->device = device;
297          found = 1;
298          break;
299       }
300    } 
301    UnlockRes();
302    if (!found) {
303       Pmsg2(0, "Could not find device %s in %s\n", dev->dev_name, configfile);
304       return;
305    }
306
307    if (VolumeName) {
308       strcpy(cmd, VolumeName);
309    } else {
310       if (!get_cmd("Enter Volume Name: ")) {
311          return;
312       }
313    }
314          
315    if (!(dev->state & ST_OPENED)) {
316       if (!open_device(dev)) {
317          Pmsg1(0, "Device open failed. ERR=%s\n", strerror_dev(dev));
318       }
319    }
320    write_volume_label_to_dev(jcr, device, cmd, "Default");
321 }
322
323 /*
324  * Read the tape label   
325  */
326 static void readlabelcmd()
327 {
328    int save_debug_level = debug_level;
329    int stat;
330    DEV_BLOCK *block;
331
332    block = new_block(dev);
333    stat = read_dev_volume_label(jcr, dev, block);
334    switch (stat) {
335       case VOL_NO_LABEL:
336          Pmsg0(0, "Volume has no label.\n");
337          break;
338       case VOL_OK:
339          Pmsg0(0, "Volume label read correctly.\n");
340          break;
341       case VOL_IO_ERROR:
342          Pmsg1(0, "I/O error on device: ERR=%s", strerror_dev(dev));
343          break;
344       case VOL_NAME_ERROR:
345          Pmsg0(0, "Volume name error\n");
346          break;
347       case VOL_CREATE_ERROR:
348          Pmsg1(0, "Error creating label. ERR=%s", strerror_dev(dev));
349          break;
350       case VOL_VERSION_ERROR:
351          Pmsg0(0, "Volume version error.\n");
352          break;
353       case VOL_LABEL_ERROR:
354          Pmsg0(0, "Bad Volume label type.\n");
355          break;
356       default:
357          Pmsg0(0, "Unknown error.\n");
358          break;
359    }
360
361    debug_level = 20;
362    dump_volume_label(dev); 
363    debug_level = save_debug_level;
364    free_block(block);
365 }
366
367
368 /*
369  * Load the tape should have prevously been taken
370  * off line, otherwise this command is not necessary.
371  */
372 static void loadcmd()
373 {
374
375    if (!load_dev(dev)) {
376       Pmsg1(0, "Bad status from load. ERR=%s\n", strerror_dev(dev));
377    } else
378       Pmsg1(0, "Loaded %s\n", dev_name(dev));
379 }
380
381 /*
382  * Rewind the tape.   
383  */
384 static void rewindcmd()
385 {
386    if (!rewind_dev(dev)) {
387       Pmsg1(0, "Bad status from rewind. ERR=%s\n", strerror_dev(dev));
388       clrerror_dev(dev, -1);
389    } else {
390       Pmsg1(0, "Rewound %s\n", dev_name(dev));
391    }
392 }
393
394 /*
395  * Clear any tape error   
396  */
397 static void clearcmd()
398 {
399    clrerror_dev(dev, -1);
400 }
401
402 /*
403  * Write and end of file on the tape   
404  */
405 static void weofcmd()
406 {
407    int stat;
408
409    if ((stat = weof_dev(dev, 1)) < 0) {
410       Pmsg2(0, "Bad status from weof %d. ERR=%s\n", stat, strerror_dev(dev));
411       return;
412    } else {
413       Pmsg1(0, "Wrote EOF to %s\n", dev_name(dev));
414    }
415 }
416
417
418 /* Go to the end of the medium -- raw command   
419  * The idea was orginally that the end of the Bacula
420  * medium would be flagged differently. This is not
421  * currently the case. So, this is identical to the
422  * eodcmd().
423  */
424 static void eomcmd()
425 {
426    if (!eod_dev(dev)) {
427       Pmsg1(0, _("Bad status from eod. ERR=%s\n"), strerror_dev(dev));
428       return;
429    } else {
430       Pmsg0(0, _("Moved to end of media\n"));
431    }
432 }
433
434 /*
435  * Go to the end of the media (either hardware determined
436  *  or defined by two eofs.
437  */
438 static void eodcmd()
439 {
440    eomcmd();
441 }
442
443 /*
444  * Backspace file   
445  */
446 static void bsfcmd()
447 {
448    int stat;
449
450    if ((stat=bsf_dev(dev, 1)) < 0) {
451       Pmsg1(0, _("Bad status from bsf. ERR=%s\n"), strerror(errno));
452    } else {
453       Pmsg0(0, _("Back spaced one file.\n"));
454    }
455 }
456
457 /*
458  * Backspace record   
459  */
460 static void bsrcmd()
461 {
462    int stat;
463
464    if ((stat=bsr_dev(dev, 1)) < 0) {
465       Pmsg1(0, _("Bad status from bsr. ERR=%s\n"), strerror(errno));
466    } else {
467       Pmsg0(0, _("Back spaced one record.\n"));
468    }
469 }
470
471 /*
472  * List device capabilities as defined in the 
473  *  stored.conf file.
474  */
475 static void capcmd()
476 {
477    printf(_("Device capabilities:\n"));
478    printf("%sEOF ", dev->capabilities & CAP_EOF ? "" : "!");
479    printf("%sBSR ", dev->capabilities & CAP_BSR ? "" : "!");
480    printf("%sBSF ", dev->capabilities & CAP_BSF ? "" : "!");
481    printf("%sFSR ", dev->capabilities & CAP_FSR ? "" : "!");
482    printf("%sFSF ", dev->capabilities & CAP_FSF ? "" : "!");
483    printf("%sEOM ", dev->capabilities & CAP_EOM ? "" : "!");
484    printf("%sREM ", dev->capabilities & CAP_REM ? "" : "!");
485    printf("%sRACCESS ", dev->capabilities & CAP_RACCESS ? "" : "!");
486    printf("%sAUTOMOUNT ", dev->capabilities & CAP_AUTOMOUNT ? "" : "!");
487    printf("%sLABEL ", dev->capabilities & CAP_LABEL ? "" : "!");
488    printf("%sANONVOLS ", dev->capabilities & CAP_ANONVOLS ? "" : "!");
489    printf("%sALWAYSOPEN ", dev->capabilities & CAP_ALWAYSOPEN ? "" : "!");
490    printf("\n");
491
492    printf(_("Device status:\n"));
493    printf("%sOPENED ", dev->state & ST_OPENED ? "" : "!");
494    printf("%sTAPE ", dev->state & ST_TAPE ? "" : "!");
495    printf("%sLABEL ", dev->state & ST_LABEL ? "" : "!");
496    printf("%sMALLOC ", dev->state & ST_MALLOC ? "" : "!");
497    printf("%sAPPEND ", dev->state & ST_APPEND ? "" : "!");
498    printf("%sREAD ", dev->state & ST_READ ? "" : "!");
499    printf("%sEOT ", dev->state & ST_EOT ? "" : "!");
500    printf("%sWEOT ", dev->state & ST_WEOT ? "" : "!");
501    printf("%sEOF ", dev->state & ST_EOF ? "" : "!");
502    printf("%sNEXTVOL ", dev->state & ST_NEXTVOL ? "" : "!");
503    printf("%sSHORT ", dev->state & ST_SHORT ? "" : "!");
504    printf("\n");
505
506    printf(_("Device parameters:\n"));
507    printf("Device name: %s\n", dev->dev_name);
508    printf("File=%u block=%u\n", dev->file, dev->block_num);
509    printf("Min block=%u Max block=%u\n", dev->min_block_size, dev->max_block_size);
510
511    printf("Status:\n");
512    statcmd();
513
514 }
515
516 /*
517  * Test writting larger and larger records.  
518  * This is a torture test for records.
519  */
520 static void rectestcmd()
521 {
522    DEV_BLOCK *block;
523    DEV_RECORD *rec;
524    int i, blkno = 0;
525
526    Pmsg0(0, "Test writting larger and larger records.\n"
527 "This is a torture test for records.\nI am going to write\n"
528 "larger and larger records. It will stop when the record size\n"
529 "plus the header exceeds the block size (by default about 64K)\n");
530
531
532    get_cmd("Do you want to continue? (y/n): ");
533    if (cmd[0] != 'y') {
534       Pmsg0(000, "Command aborted.\n");
535       return;
536    }
537
538    sm_check(__FILE__, __LINE__, False);
539    block = new_block(dev);
540    rec = new_record();
541
542    for (i=1; i<500000; i++) {
543       rec->data = check_pool_memory_size(rec->data, i);
544       memset(rec->data, i & 0xFF, i);
545       rec->data_len = i;
546       sm_check(__FILE__, __LINE__, False);
547       if (write_record_to_block(block, rec)) {
548          empty_block(block);
549          blkno++;
550          Pmsg2(0, "Block %d i=%d\n", blkno, i);
551       } else {
552          break;
553       }
554       sm_check(__FILE__, __LINE__, False);
555    }
556    free_record(rec);
557    free_block(block);
558    sm_check(__FILE__, __LINE__, False);
559 }
560
561 /*
562  * This test attempts to re-read a block written by Bacula
563  *   normally at the end of the tape. Bacula will then back up
564  *   over the two eof marks, backup over the record and reread
565  *   it to make sure it is valid.  Bacula can skip this validation
566  *   if you set "Backward space record = no"
567  */
568 static int re_read_block_test()
569 {
570    DEV_BLOCK *block;
571    DEV_RECORD *rec;
572    int stat = 0;
573    int len;
574
575    if (!(dev->capabilities & CAP_BSR)) {
576       Pmsg0(-1, _("Skipping read backwards test because BSR turned off.\n"));
577       return 0;
578    }
579
580    Pmsg0(-1, _("\n=== Write, backup, and re-read test ===\n\n"
581       "I'm going to write three records and two eof's\n"
582       "then backup over the eof's and re-read the last record.\n"     
583       "Bacula does this after writing the last block on the\n"
584       "tape to verify that the block was written correctly.\n"
585       "It is not an *essential* feature ...\n\n")); 
586    rewindcmd();
587    block = new_block(dev);
588    rec = new_record();
589    rec->data = check_pool_memory_size(rec->data, block->buf_len);
590    len = rec->data_len = block->buf_len-100;
591    memset(rec->data, 1, rec->data_len);
592    if (!write_record_to_block(block, rec)) {
593       Pmsg0(0, _("Error writing record to block.\n")); 
594       goto bail_out;
595    }
596    if (!write_block_to_dev(jcr, dev, block)) {
597       Pmsg0(0, _("Error writing block to device.\n")); 
598       goto bail_out;
599    } else {
600       Pmsg1(0, _("Wrote first record of %d bytes.\n"), rec->data_len);
601    }
602    memset(rec->data, 2, rec->data_len);
603    if (!write_record_to_block(block, rec)) {
604       Pmsg0(0, _("Error writing record to block.\n")); 
605       goto bail_out;
606    }
607    if (!write_block_to_dev(jcr, dev, block)) {
608       Pmsg0(0, _("Error writing block to device.\n")); 
609       goto bail_out;
610    } else {
611       Pmsg1(0, _("Wrote second record of %d bytes.\n"), rec->data_len);
612    }
613    memset(rec->data, 3, rec->data_len);
614    if (!write_record_to_block(block, rec)) {
615       Pmsg0(0, _("Error writing record to block.\n")); 
616       goto bail_out;
617    }
618    if (!write_block_to_dev(jcr, dev, block)) {
619       Pmsg0(0, _("Error writing block to device.\n")); 
620       goto bail_out;
621    } else {
622       Pmsg1(0, _("Wrote third record of %d bytes.\n"), rec->data_len);
623    }
624    weofcmd();
625    weofcmd();
626    if (bsf_dev(dev, 1) != 0) {
627       Pmsg1(0, _("Back space file failed! ERR=%s\n"), strerror(dev->dev_errno));
628       goto bail_out;
629    }
630    if (bsf_dev(dev, 1) != 0) {
631       Pmsg1(0, _("Back space file failed! ERR=%s\n"), strerror(dev->dev_errno));
632       goto bail_out;
633    }
634    Pmsg0(0, "Backspaced over two EOFs OK.\n");
635    if (bsr_dev(dev, 1) != 0) {
636       Pmsg1(0, _("Back space record failed! ERR=%s\n"), strerror(dev->dev_errno));
637       goto bail_out;
638    }
639    Pmsg0(0, "Backspace record OK.\n");
640    if (!read_block_from_dev(jcr, dev, block, NO_BLOCK_NUMBER_CHECK)) {
641       Pmsg1(0, _("Read block failed! ERR=%s\n"), strerror(dev->dev_errno));
642       goto bail_out;
643    }
644    memset(rec->data, 0, rec->data_len);
645    if (!read_record_from_block(block, rec)) {
646       Pmsg1(0, _("Read block failed! ERR=%s\n"), strerror(dev->dev_errno));
647       goto bail_out;
648    }
649    for (int i=0; i<len; i++) {
650       if (rec->data[i] != 3) {
651          Pmsg0(0, _("Bad data in record. Test failed!\n"));
652          goto bail_out;
653       }
654    }
655    Pmsg0(0, _("\nBlock re-read correct. Test succeeded!\n"));
656    Pmsg0(-1, _("=== End Write, backup, and re-read test ===\n\n"));
657
658    stat = 1;
659
660 bail_out:
661    free_block(block);
662    free_record(rec);
663    if (stat == 0) {
664       Pmsg0(0, _("This is not terribly serious since Bacula only uses\n"
665                  "this function to verify the last block written to the\n"
666                  "tape. Bacula will skip the last block verification\n"
667                  "if you add:\n\n"
668                   "Backward Space Record = No\n\n"
669                   "to your Storage daemon's Device resource definition.\n"));
670    }   
671    return stat;
672 }
673
674 /*
675  * This test writes some records, then writes an end of file,
676  *   rewinds the tape, moves to the end of the data and attepts
677  *   to append to the tape.  This function is essential for
678  *   Bacula to be able to write multiple jobs to the tape.
679  */
680 static int append_test()
681 {
682    Pmsg0(-1, _("\n\n=== Append files test ===\n\n"
683                "This test is essential to Bacula.\n\n"
684 "I'm going to write one record  in file 0,\n"
685 "                   two records in file 1,\n"
686 "             and three records in file 2\n\n"));
687    rewindcmd();
688    wrcmd();
689    weofcmd();      /* end file 0 */
690    wrcmd();
691    wrcmd();
692    weofcmd();      /* end file 1 */
693    wrcmd();
694    wrcmd();
695    wrcmd();
696    weofcmd();     /* end file 2 */
697    rewindcmd();
698    Pmsg0(0, _("Now moving to end of media.\n"));
699    eodcmd();
700    Pmsg2(-1, _("We should be in file 3. I am at file %d. This is %s\n"), 
701       dev->file, dev->file == 3 ? "correct!" : "NOT correct!!!!");
702
703    if (dev->file != 3) {
704       return -1;
705    }
706
707    Pmsg0(-1, _("\nNow the important part, I am going to attempt to append to the tape.\n\n"));
708    wrcmd(); 
709    weofcmd();
710    rewindcmd();
711    Pmsg0(-1, _("Done appending, there should be no I/O errors\n\n"));
712    Pmsg0(-1, "Doing Bacula scan of blocks:\n");
713    scan_blocks();
714    Pmsg0(-1, _("End scanning the tape.\n"));
715    Pmsg2(-1, _("We should be in file 4. I am at file %d. This is %s\n"), 
716       dev->file, dev->file == 4 ? "correct!" : "NOT correct!!!!");
717
718    if (dev->file != 4) {
719       return -2;
720    }
721
722    return 1;
723 }
724
725 /* 
726  * This is a general test of Bacula's functions
727  *   needed to read and write the tape.
728  */
729 static void testcmd()
730 {
731    int stat;
732
733    stat = append_test();
734    if (stat == 1) {                   /* OK get out */
735       goto all_done;
736    }
737    if (stat == -1) {                  /* first test failed */
738       if (dev_cap(dev, CAP_EOM)) {
739          Pmsg0(-1, "\nAppend test failed. Attempting again.\n"
740                    "Setting \"Hardware End of Medium = no\" and retrying append test.\n\n");
741          dev->capabilities &= ~CAP_EOM; /* turn off eom */
742          stat = append_test();
743          if (stat == 1) {
744             Pmsg0(-1, "\n\nIt looks like the test worked this time, please add:\n\n"
745                      "    Hardware End of Medium = No\n\n"
746                      "to your Device resource in the Storage conf file.\n");
747             goto all_done;
748          }
749          if (stat == -1) {
750             Pmsg0(-1, "\n\nThat appears not to have corrected the problem.\n");
751             goto all_done;
752          }
753          /* Wrong count after append */
754          if (stat == -2) {
755             Pmsg0(-1, "\n\nIt looks like the append failed. Attempting again.\n"
756                      "Setting \"BSF at EOM = yes\" and retrying append test.\n");
757             dev->capabilities |= CAP_BSFATEOM; /* backspace on eom */
758             stat = append_test();
759             if (stat == 1) {
760                Pmsg0(-1, "\n\nIt looks like the test worked this time, please add:\n\n"
761                      "    Hardware End of Medium = No\n"
762                      "    BSR at EOM = yes\n\n"
763                      "to your Device resource in the Storage conf file.\n");
764                goto all_done;
765             }
766          }
767
768          Pmsg0(-1, "\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n"
769                "Unable to correct the problem. You MUST fix this\n"
770                 "problem before Bacula can use your tape drive correctly\n");
771          Pmsg0(-1, "\nPerhaps running Bacula in fixed block mode will work.\n"
772                "Do so by setting:\n\n"
773                "Minimum Block Size = nnn\n"
774                "Maximum Block Size = nnn\n\n"
775                "in your Storage daemon's Device definition.\n"
776                "nnn must match your tape driver's block size.\n"
777                "This, however, is not really an ideal solution.\n");
778       }
779    }
780
781 all_done:
782    Pmsg0(-1, _("\nThe above Bacula scan should have output identical to what follows.\n"
783         "Please double check it ...\n"
784         "=== Sample correct output ===\n"
785         "1 block of 64448 bytes in file 1\n"
786         "End of File mark.\n"
787         "2 blocks of 64448 bytes in file 2\n"
788         "End of File mark.\n"
789         "3 blocks of 64448 bytes in file 3\n"
790         "End of File mark.\n"
791         "1 block of 64448 bytes in file 4\n" 
792         "End of File mark.\n"
793         "Total files=4, blocks=7, bytes = 451136\n"
794         "=== End sample correct output ===\n\n"));
795
796    Pmsg0(-1, _("If the above scan output is not identical to the\n"
797                "sample output, you MUST correct the problem\n"
798                "or Bacula will not be able to write multiple Jobs to \n"
799                "the tape.\n\n"));
800
801    if (stat == 1) {
802       re_read_block_test();
803    }
804
805    Pmsg0(-1, _("\n=== End Append files test ===\n"));
806    
807 }
808
809 /* Forward space a file */
810 static void fsfcmd()
811 {
812    if (!fsf_dev(dev, 1)) {
813       Pmsg1(0, "Bad status from fsf. ERR=%s\n", strerror_dev(dev));
814       return;
815    }
816    Pmsg0(0, "Forward spaced one file.\n");
817 }
818
819 /* Forward space a record */
820 static void fsrcmd()
821 {
822    int stat;
823
824    if ((stat=fsr_dev(dev, 1)) < 0) {
825       Pmsg2(0, "Bad status from fsr %d. ERR=%s\n", stat, strerror_dev(dev));
826       return;
827    }
828    Pmsg0(0, "Forward spaced one record.\n");
829 }
830
831
832 /*
833  * Write a Bacula block to the tape
834  */
835 static void wrcmd()
836 {
837    DEV_BLOCK *block;
838    DEV_RECORD *rec;
839    int i;
840
841    sm_check(__FILE__, __LINE__, False);
842    block = new_block(dev);
843    rec = new_record();
844    dump_block(block, "test");
845
846    i = block->buf_len - 100;
847    ASSERT (i > 0);
848    rec->data = check_pool_memory_size(rec->data, i);
849    memset(rec->data, i & 0xFF, i);
850    rec->data_len = i;
851    sm_check(__FILE__, __LINE__, False);
852    if (!write_record_to_block(block, rec)) {
853       Pmsg0(0, _("Error writing record to block.\n")); 
854       goto bail_out;
855    }
856    if (!write_block_to_dev(jcr, dev, block)) {
857       Pmsg0(0, _("Error writing block to device.\n")); 
858       goto bail_out;
859    } else {
860       Pmsg1(0, _("Wrote one record of %d bytes.\n"), i);
861    }
862    Pmsg0(0, _("Wrote block to device.\n"));
863
864 bail_out:
865    sm_check(__FILE__, __LINE__, False);
866    free_record(rec);
867    free_block(block);
868    sm_check(__FILE__, __LINE__, False);
869 }
870
871 /* 
872  * Read a record from the tape
873  */
874 static void rrcmd()
875 {
876    char *buf;
877    int stat, len;
878
879    if (!get_cmd("Enter length to read: ")) {
880       return;
881    }
882    len = atoi(cmd);
883    if (len < 0 || len > 1000000) {
884       Pmsg0(0, _("Bad length entered, using default of 1024 bytes.\n"));
885       len = 1024;
886    }
887    buf = (char *)malloc(len);
888    stat = read(dev->fd, buf, len);
889    if (stat > 0 && stat <= len) {
890       errno = 0;
891    }
892    Pmsg3(0, _("Read of %d bytes gives stat=%d. ERR=%s\n"),
893       len, stat, strerror(errno));
894    free(buf);
895 }
896
897
898 /*
899  * Scan tape by reading block by block. Report what is
900  * on the tape.  Note, this command does raw reads, and as such
901  * will not work with fixed block size devices.
902  */
903 static void scancmd()
904 {
905    int stat;
906    int blocks, tot_blocks, tot_files;
907    int block_size;
908    uint64_t bytes;
909
910
911    blocks = block_size = tot_blocks = 0;
912    bytes = 0;
913    if (dev->state & ST_EOT) {
914       Pmsg0(0, "End of tape\n");
915       return; 
916    }
917    update_pos_dev(dev);
918    tot_files = dev->file;
919    for (;;) {
920       if ((stat = read(dev->fd, buf, sizeof(buf))) < 0) {
921          clrerror_dev(dev, -1);
922          Mmsg2(&dev->errmsg, "read error on %s. ERR=%s.\n",
923             dev->dev_name, strerror(dev->dev_errno));
924          Pmsg2(0, "Bad status from read %d. ERR=%s\n", stat, strerror_dev(dev));
925          if (blocks > 0)
926             printf("%d block%s of %d bytes in file %d\n",        
927                     blocks, blocks>1?"s":"", block_size, dev->file);
928          return;
929       }
930       Dmsg1(200, "read status = %d\n", stat);
931 /*    sleep(1); */
932       if (stat != block_size) {
933          update_pos_dev(dev);
934          if (blocks > 0) {
935             printf("%d block%s of %d bytes in file %d\n", 
936                  blocks, blocks>1?"s":"", block_size, dev->file);
937             blocks = 0;
938          }
939          block_size = stat;
940       }
941       if (stat == 0) {                /* EOF */
942          update_pos_dev(dev);
943          printf("End of File mark.\n");
944          /* Two reads of zero means end of tape */
945          if (dev->state & ST_EOF)
946             dev->state |= ST_EOT;
947          else {
948             dev->state |= ST_EOF;
949             dev->file++;
950          }
951          if (dev->state & ST_EOT) {
952             printf("End of tape\n");
953             break;
954          }
955       } else {                        /* Got data */
956          dev->state &= ~ST_EOF;
957          blocks++;
958          tot_blocks++;
959          bytes += stat;
960       }
961    }
962    update_pos_dev(dev);
963    tot_files = dev->file - tot_files;
964    printf("Total files=%d, blocks=%d, bytes = %" lld "\n", tot_files, tot_blocks, bytes);
965 }
966
967
968 /*
969  * Scan tape by reading Bacula block by block. Report what is
970  * on the tape.  This function reads Bacula blocks, so if your
971  * Device resource is correctly defined, it should work with
972  * either variable or fixed block sizes.
973  */
974 static void scan_blocks()
975 {
976    int blocks, tot_blocks, tot_files;
977    uint32_t block_size;
978    uint64_t bytes;
979    DEV_BLOCK *block;
980
981    block = new_block(dev);
982    blocks = block_size = tot_blocks = 0;
983    bytes = 0;
984
985    update_pos_dev(dev);
986    tot_files = dev->file;
987    for (;;) {
988       if (!read_block_from_device(jcr, dev, block, NO_BLOCK_NUMBER_CHECK)) {
989          Dmsg1(100, "!read_block(): ERR=%s\n", strerror_dev(dev));
990          if (dev->state & ST_EOT) {
991             if (blocks > 0) {
992                printf("%d block%s of %d bytes in file %d\n", 
993                     blocks, blocks>1?"s":"", block_size, dev->file);
994                blocks = 0;
995             }
996             goto bail_out;
997          }
998          if (dev->state & ST_EOF) {
999             if (blocks > 0) {
1000                printf("%d block%s of %d bytes in file %d\n",        
1001                        blocks, blocks>1?"s":"", block_size, dev->file);
1002                blocks = 0;
1003             }
1004             printf(_("End of File mark.\n"));
1005             continue;
1006          }
1007          if (dev->state & ST_SHORT) {
1008             if (blocks > 0) {
1009                printf("%d block%s of %d bytes in file %d\n",        
1010                        blocks, blocks>1?"s":"", block_size, dev->file);
1011                blocks = 0;
1012             }
1013             printf(_("Short block read.\n"));
1014             continue;
1015          }
1016          printf(_("Error reading block. ERR=%s\n"), strerror_dev(dev));
1017          goto bail_out;
1018       }
1019       if (block->block_len != block_size) {
1020          if (blocks > 0) {
1021             printf("%d block%s of %d bytes in file %d\n",        
1022                     blocks, blocks>1?"s":"", block_size, dev->file);
1023             blocks = 0;
1024          }
1025          block_size = block->block_len;
1026       }
1027       blocks++;
1028       tot_blocks++;
1029       bytes += block->block_len;
1030       Dmsg5(100, "Blk=%u blen=%u bVer=%d SessId=%u SessTim=%u\n",
1031          block->BlockNumber, block->block_len, block->BlockVer,
1032          block->VolSessionId, block->VolSessionTime);
1033       if (verbose == 1) {
1034          DEV_RECORD *rec = new_record();
1035          read_record_from_block(block, rec);
1036          Pmsg7(-1, "Block: %u blen=%u First rec FI=%s SessId=%u SessTim=%u Strm=%s rlen=%d\n",
1037               block->BlockNumber, block->block_len,
1038               FI_to_ascii(rec->FileIndex), rec->VolSessionId, rec->VolSessionTime,
1039               stream_to_ascii(rec->Stream, rec->FileIndex), rec->data_len);
1040          rec->remainder = 0;
1041          free_record(rec);
1042       } else if (verbose > 1) {
1043          dump_block(block, "");
1044       }
1045
1046    }
1047 bail_out:
1048    free_block(block);
1049    tot_files = dev->file - tot_files;
1050    printf("Total files=%d, blocks=%d, bytes = %" lld "\n", tot_files, tot_blocks, bytes);
1051 }
1052
1053
1054 static void statcmd()
1055 {
1056    int stat = 0;
1057    int debug;
1058    uint32_t status;
1059
1060    debug = debug_level;
1061    debug_level = 30;
1062    if (!status_dev(dev, &status)) {
1063       Pmsg2(0, "Bad status from status %d. ERR=%s\n", stat, strerror_dev(dev));
1064    }
1065 #ifdef xxxx
1066    dump_volume_label(dev);
1067 #endif
1068    debug_level = debug;
1069 }
1070
1071
1072 /* 
1073  * First we label the tape, then we fill
1074  *  it with data get a new tape and write a few blocks.
1075  */                            
1076 static void fillcmd()
1077 {
1078    DEV_RECORD rec;
1079    DEV_BLOCK  *block;
1080    char ec1[50];
1081
1082    ok = TRUE;
1083    stop = 0;
1084    vol_num = 0;
1085
1086    Pmsg0(-1, "\n\
1087 This command simulates Bacula writing to a tape.\n\
1088 It requires either one or two blank tapes, which it\n\
1089 will label and write. It will print a status approximately\n\
1090 every 322 MB, and write an EOF every 3.2 GB.  If you have\n\
1091 selected the simple test option, after writing the first tape\n\
1092 it will rewind it and re-read the last block written.\n\
1093 If you have selected the multiple tape test, when the first tape\n\
1094 fills, it will ask for a second, and after writing a few more \n\
1095 blocks, it will stop.  Then it will begin re-reading the\n\
1096 two tapes.\n\n\
1097 This may take a long time -- hours! ...\n\n");
1098
1099    get_cmd("Insert a blank tape then indicate if you want\n"
1100            "to run the simplified test (s) with one tape or\n"
1101            "the complete multiple tape (m) test: (s/m) ");
1102    if (cmd[0] == 's') {
1103       Pmsg0(-1, "Simple test (single tape) selected.\n");
1104       simple = TRUE;
1105    } else if (cmd[0] == 'm') {
1106       Pmsg0(-1, "Complete multiple tape test selected.\n"); 
1107       simple = FALSE;
1108    } else {
1109       Pmsg0(000, "Command aborted.\n");
1110       return;
1111    }
1112
1113    set_volume_name("TestVolume1", 1);
1114    labelcmd();
1115    VolumeName = NULL;
1116
1117    
1118    Dmsg1(20, "Begin append device=%s\n", dev_name(dev));
1119
1120    block = new_block(dev);
1121
1122    /* 
1123     * Acquire output device for writing.  Note, after acquiring a
1124     *   device, we MUST release it, which is done at the end of this
1125     *   subroutine.
1126     */
1127    Dmsg0(100, "just before acquire_device\n");
1128    if (!(dev=acquire_device_for_append(jcr, dev, block))) {
1129       set_jcr_job_status(jcr, JS_ErrorTerminated);
1130       free_block(block);
1131       return;
1132    }
1133
1134    Dmsg0(100, "Just after acquire_device_for_append\n");
1135    /*
1136     * Write Begin Session Record
1137     */
1138    if (!write_session_label(jcr, block, SOS_LABEL)) {
1139       set_jcr_job_status(jcr, JS_ErrorTerminated);
1140       Jmsg1(jcr, M_FATAL, 0, _("Write session label failed. ERR=%s\n"),
1141          strerror_dev(dev));
1142       ok = FALSE;
1143    }
1144    Pmsg0(-1, "Wrote Start Of Session label.\n");
1145
1146    memset(&rec, 0, sizeof(rec));
1147    rec.data = get_memory(100000);     /* max record size */
1148
1149 #define REC_SIZE 32768
1150    rec.data_len = REC_SIZE;
1151
1152    /* 
1153     * Generate data as if from File daemon, write to device   
1154     */
1155    jcr->VolFirstIndex = 0;
1156    time(&jcr->run_time);              /* start counting time for rates */
1157    Pmsg0(-1, "Begin writing records to first tape ...\n");
1158    for (file_index = 0; ok && !job_canceled(jcr); ) {
1159       rec.VolSessionId = jcr->VolSessionId;
1160       rec.VolSessionTime = jcr->VolSessionTime;
1161       rec.FileIndex = ++file_index;
1162       rec.Stream = STREAM_FILE_DATA;
1163
1164       /* 
1165        * Fill the buffer with the file_index negated. Negation ensures that
1166        *   more bits are turned on.
1167        */
1168       uint64_t *lp = (uint64_t *)rec.data;
1169       for (uint32_t i=0; i < (rec.data_len-sizeof(uint64_t))/sizeof(uint64_t); i++) {
1170          *lp++ = ~file_index;
1171       }
1172
1173       Dmsg4(250, "before writ_rec FI=%d SessId=%d Strm=%s len=%d\n",
1174          rec.FileIndex, rec.VolSessionId, stream_to_ascii(rec.Stream, rec.FileIndex), 
1175          rec.data_len);
1176        
1177       while (!write_record_to_block(block, &rec)) {
1178          /*
1179           * When we get here we have just filled a block
1180           */
1181          Dmsg2(150, "!write_record_to_block data_len=%d rem=%d\n", rec.data_len,
1182                     rec.remainder);
1183
1184          /* Write block to tape */
1185          if (!flush_block(block, 1)) {
1186             return;
1187          }
1188
1189          /* Every 5000 blocks (approx 322MB) report where we are.
1190           */
1191          if ((block->BlockNumber % 5000) == 0) {
1192             now = time(NULL);
1193             now -= jcr->run_time;
1194             if (now <= 0) {
1195                now = 1;
1196             }
1197             kbs = (double)dev->VolCatInfo.VolCatBytes / (1000.0 * (double)now);
1198             Pmsg3(-1, "Wrote block=%u, VolBytes=%s rate=%.1f KB/s\n", block->BlockNumber,
1199                edit_uint64_with_commas(dev->VolCatInfo.VolCatBytes, ec1), (float)kbs);
1200          }
1201          /* Every 15000 blocks (approx 1GB) write an EOF.
1202           */
1203          if ((block->BlockNumber % 15000) == 0) {
1204             Pmsg0(-1, "Flush block, write EOF\n");
1205             flush_block(block, 0);
1206             weof_dev(dev, 1);
1207          }
1208
1209          /* Get out after writing 10 blocks to the second tape */
1210          if (++BlockNumber > 10 && stop != 0) {      /* get out */
1211             break;    
1212          }
1213       }
1214       if (!ok) {
1215          Pmsg0(000, _("Not OK\n"));
1216          break;
1217       }
1218       jcr->JobBytes += rec.data_len;   /* increment bytes this job */
1219       Dmsg4(190, "write_record FI=%s SessId=%d Strm=%s len=%d\n",
1220          FI_to_ascii(rec.FileIndex), rec.VolSessionId, 
1221          stream_to_ascii(rec.Stream, rec.FileIndex), rec.data_len);
1222
1223       /* Get out after writing 10 blocks to the second tape */
1224       if (BlockNumber > 10 && stop != 0) {      /* get out */
1225          Pmsg0(-1, "Done writing 10 blocks to second tape.\n");
1226          break;    
1227       }
1228    }
1229    if (stop > 0) {
1230       Dmsg0(100, "Write_end_session_label()\n");
1231       /* Create Job status for end of session label */
1232       if (!job_canceled(jcr) && ok) {
1233          set_jcr_job_status(jcr, JS_Terminated);
1234       } else if (!ok) {
1235          set_jcr_job_status(jcr, JS_ErrorTerminated);
1236       }
1237       if (!write_session_label(jcr, block, EOS_LABEL)) {
1238          Pmsg1(000, _("Error writting end session label. ERR=%s\n"), strerror_dev(dev));
1239          ok = FALSE;
1240       }
1241       /* Write out final block of this session */
1242       if (!write_block_to_device(jcr, dev, block)) {
1243          Pmsg0(-1, _("Set ok=FALSE after write_block_to_device.\n"));
1244          ok = FALSE;
1245       }
1246       Pmsg0(-1, "Wrote End Of Session label.\n");
1247    }
1248
1249    /* Release the device */
1250    if (!release_device(jcr, dev)) {
1251       Pmsg0(-1, _("Error in release_device\n"));
1252       ok = FALSE;
1253    }
1254
1255    free_block(block);
1256    free_memory(rec.data);
1257    Pmsg0(-1, _("\n\nDone filling tape. Now beginning re-read of tape ...\n"));
1258
1259    dump_block(last_block, _("Last block written to tape.\n"));
1260
1261    unfillcmd();
1262 }
1263
1264 /*
1265  * Read two tapes written by the "fill" command and ensure
1266  *  that the data is valid.  If stop==1 we simulate full read back
1267  *  of two tapes.  If stop==-1 we simply read the last block and
1268  *  verify that it is correct.
1269  */
1270 static void unfillcmd()
1271 {
1272    DEV_BLOCK *block;
1273
1274    dumped = 0;
1275    VolBytes = 0;
1276    LastBlock = 0;
1277    block = new_block(dev);
1278
1279    dev->capabilities |= CAP_ANONVOLS; /* allow reading any volume */
1280    dev->capabilities &= ~CAP_LABEL;   /* don't label anything here */
1281
1282    end_of_tape = 0;
1283
1284    get_cmd(_("Mount first tape. Press enter when ready: ")); 
1285    
1286    free_vol_list(jcr);
1287    set_volume_name("TestVolume1", 1);
1288    jcr->bsr = NULL;
1289    create_vol_list(jcr);
1290    close_dev(dev);
1291    dev->state &= ~ST_READ;
1292    if (!acquire_device_for_read(jcr, dev, block)) {
1293       Pmsg1(-1, "%s", dev->errmsg);
1294       return;
1295    }
1296
1297    time(&jcr->run_time);              /* start counting time for rates */
1298    stop = 0;
1299    file_index = 0;
1300    if (!simple) {
1301       /* Read all records and then second tape */
1302       read_records(jcr, dev, record_cb, my_mount_next_read_volume);
1303    } else {
1304       /*
1305        * Simplified test, we simply fsf to file, then read the
1306        * last block and make sure it is the same as the saved block.
1307        */
1308       Pmsg0(000, "Rewinding tape ...\n");
1309       if (!rewind_dev(dev)) {
1310          Pmsg1(-1, _("Error rewinding: ERR=%s\n"), strerror_dev(dev));
1311          goto bail_out;
1312       }
1313       if (last_file > 0) {
1314          Pmsg1(000, "Forward spacing to last file=%u\n", last_file);
1315          if (!fsf_dev(dev, last_file)) {
1316             Pmsg1(-1, _("Error in FSF: ERR=%s\n"), strerror_dev(dev));
1317             goto bail_out;
1318          }
1319       }
1320       Pmsg1(-1, _("Forward space to file %u complete. Reading blocks ...\n"), 
1321             last_file);
1322       Pmsg1(-1, _("Now reading to block %u.\n"), last_block_num);
1323       for (uint32_t i= 0; i < last_block_num; i++) {
1324          if (!read_block_from_device(jcr, dev, block, NO_BLOCK_NUMBER_CHECK)) {
1325             Pmsg1(-1, _("Error reading blocks: ERR=%s\n"), strerror_dev(dev));
1326             Pmsg2(-1, _("Wanted block %u error at block %u\n"), last_block_num, i);
1327             goto bail_out;
1328          }
1329          if (i > 0 && i % 1000 == 0) {
1330             Pmsg1(-1, _("At block %u\n"), i);
1331          }
1332       }
1333       if (last_block) {
1334          dump_block(last_block, _("Last block written"));
1335          dump_block(block, _("Block read back"));
1336          Pmsg0(-1, _("Except for the buffer address, the contents of\n"
1337                      "the above two block dumps should be the same.\n"
1338                      "If not you have a problem ...\n"));
1339       }
1340    }
1341
1342 bail_out:
1343    free_block(block);
1344
1345    Pmsg0(000, _("Done with reread of fill data.\n"));
1346 }
1347
1348
1349 /* 
1350  * We are called here from "unfill" for each record on the tape.
1351  */
1352 static void record_cb(JCR *jcr, DEVICE *dev, DEV_BLOCK *block, DEV_RECORD *rec)
1353 {
1354
1355    SESSION_LABEL label;
1356    if (stop > 1) {                    /* on second tape */
1357       Pmsg4(-1, "Blk: FileIndex=%d: block=%u size=%d vol=%s\n", 
1358            rec->FileIndex, block->BlockNumber, block->block_len, dev->VolHdr.VolName);
1359       Pmsg6(-1, "   Rec: VId=%d VT=%d FI=%s Strm=%s len=%d state=%x\n",
1360            rec->VolSessionId, rec->VolSessionTime, 
1361            FI_to_ascii(rec->FileIndex), stream_to_ascii(rec->Stream, rec->FileIndex),
1362            rec->data_len, rec->state);
1363
1364       if (!dumped) {
1365          dumped = 1;
1366          dump_block(block, "Block not written to previous tape");
1367       }
1368    }
1369    if (rec->FileIndex < 0) {
1370       if (verbose > 1) {
1371          dump_label_record(dev, rec, 1);
1372       }
1373       switch (rec->FileIndex) {
1374       case PRE_LABEL:
1375          Pmsg0(-1, "Volume is prelabeled. This tape cannot be scanned.\n");
1376          return;
1377       case VOL_LABEL:
1378          unser_volume_label(dev, rec);
1379          Pmsg3(-1, "VOL_LABEL: block=%u size=%d vol=%s\n", block->BlockNumber, 
1380             block->block_len, dev->VolHdr.VolName);
1381          stop++;
1382          break;
1383       case SOS_LABEL:
1384          unser_session_label(&label, rec);
1385          Pmsg1(-1, "SOS_LABEL: JobId=%u\n", label.JobId);
1386          break;
1387       case EOS_LABEL:
1388          unser_session_label(&label, rec);
1389          Pmsg2(-1, "EOS_LABEL: block=%u JobId=%u\n", block->BlockNumber, 
1390             label.JobId);
1391          break;
1392       case EOM_LABEL:
1393          Pmsg0(-1, "EOM_LABEL:\n");
1394          break;
1395       case EOT_LABEL:              /* end of all tapes */
1396          char ec1[50];
1397
1398          if (LastBlock != block->BlockNumber) {
1399             VolBytes += block->block_len;
1400          }
1401          LastBlock = block->BlockNumber;
1402          now = time(NULL);
1403          now -= jcr->run_time;
1404          if (now <= 0) {
1405             now = 1;
1406          }
1407          kbs = (double)VolBytes / (1000 * now);
1408          Pmsg3(000, "Read block=%u, VolBytes=%s rate=%.1f KB/s\n", block->BlockNumber,
1409                   edit_uint64_with_commas(VolBytes, ec1), (float)kbs);
1410
1411          Pmsg0(000, "End of all tapes.\n");
1412
1413          break;
1414       default:
1415          break;
1416       }
1417       return;
1418    }
1419    if (++file_index != rec->FileIndex) {
1420       Pmsg3(000, "Incorrect FileIndex in Block %u. Got %d, expected %d.\n", 
1421          block->BlockNumber, rec->FileIndex, file_index);
1422    }
1423    /*
1424     * Now check that the right data is in the record.
1425     */
1426    uint64_t *lp = (uint64_t *)rec->data;
1427    uint64_t val = ~file_index;
1428    for (uint32_t i=0; i < (REC_SIZE-sizeof(uint64_t))/sizeof(uint64_t); i++) {
1429       if (*lp++ != val) {
1430          Pmsg2(000, "Record %d contains bad data in Block %u.\n",
1431             file_index, block->BlockNumber);
1432          break;
1433       }
1434    }
1435
1436    if (LastBlock != block->BlockNumber) {
1437       VolBytes += block->block_len;
1438    }
1439    if ((block->BlockNumber != LastBlock) && (block->BlockNumber % 50000) == 0) {
1440       char ec1[50];
1441       now = time(NULL);
1442       now -= jcr->run_time;
1443       if (now <= 0) {
1444          now = 1;
1445       }
1446       kbs = (double)VolBytes / (1000 * now);
1447       Pmsg3(000, "Read block=%u, VolBytes=%s rate=%.1f KB/s\n", block->BlockNumber,
1448                edit_uint64_with_commas(VolBytes, ec1), (float)kbs);
1449    }
1450    LastBlock = block->BlockNumber;
1451    if (end_of_tape) {
1452       Pmsg1(000, "End of all blocks. Block=%u\n", block->BlockNumber);
1453    }
1454 }
1455
1456
1457
1458 /*
1459  * Write current block to tape regardless of whether or
1460  *   not it is full. If the tape fills, attempt to
1461  *   acquire another tape.
1462  */
1463 static int flush_block(DEV_BLOCK *block, int dump)
1464 {
1465    char ec1[50];
1466    lock_device(dev);
1467    DEV_BLOCK *tblock;
1468    uint32_t this_file, this_block_num;
1469
1470    if (!this_block) {
1471       this_block = new_block(dev);
1472    }
1473    /* Copy block */
1474    free_memory(this_block->buf);    
1475    memcpy(this_block, block, sizeof(DEV_BLOCK));
1476    this_block->buf = get_memory(block->buf_len);
1477    memcpy(this_block->buf, block->buf, this_block->buf_len);
1478    this_file = dev->file;
1479    this_block_num = dev->block_num;
1480    if (!write_block_to_dev(jcr, dev, block)) {
1481       Pmsg0(000, strerror_dev(dev));            
1482       Pmsg3(000, "Block not written: FileIndex=%u Block=%u Size=%u\n", 
1483          (unsigned)file_index, block->BlockNumber, block->block_len);
1484       if (dump) {
1485          dump_block(block, "Block not written");
1486       }
1487       if (stop == 0) {
1488          eot_block = block->BlockNumber;
1489          eot_block_len = block->block_len;
1490          eot_FileIndex = file_index;
1491       }
1492       now = time(NULL);
1493       now -= jcr->run_time;
1494       if (now <= 0) {
1495          now = 1;
1496       }
1497       kbs = (double)dev->VolCatInfo.VolCatBytes / (1000 * now);
1498       vol_size = dev->VolCatInfo.VolCatBytes;
1499       Pmsg2(000, "End of tape. VolumeCapacity=%s. Write rate = %.1f KB/s\n", 
1500          edit_uint64_with_commas(dev->VolCatInfo.VolCatBytes, ec1), kbs);
1501
1502       if (simple) {
1503          stop = -1;                   /* stop, but do simplified test */
1504       } else {
1505          /* Full test in progress */
1506          if (!fixup_device_block_write_error(jcr, dev, block)) {
1507             Pmsg1(000, _("Cannot fixup device error. %s\n"), strerror_dev(dev));
1508             ok = FALSE;
1509             unlock_device(dev);
1510             return 0;
1511          }
1512          stop = 1;                                                     
1513          BlockNumber = 0;             /* start counting for second tape */
1514       }
1515       unlock_device(dev);
1516       return 1;                       /* end of tape reached */
1517    }
1518
1519    /*
1520     * Toggle between two allocated blocks for efficiency.
1521     * Switch blocks so that the block just successfully written is
1522     *  always in last_block. 
1523     */
1524    tblock = last_block;
1525    last_block = this_block; 
1526    this_block = tblock;
1527    last_file = this_file;
1528    last_block_num = this_block_num;
1529
1530    unlock_device(dev);
1531    return 1;
1532 }
1533
1534
1535 struct cmdstruct { char *key; void (*func)(); char *help; }; 
1536 static struct cmdstruct commands[] = {
1537  {"bsf",        bsfcmd,       "backspace file"},
1538  {"bsr",        bsrcmd,       "backspace record"},
1539  {"cap",        capcmd,       "list device capabilities"},
1540  {"clear",      clearcmd,     "clear tape errors"},
1541  {"eod",        eodcmd,       "go to end of Bacula data for append"},
1542  {"eom",        eomcmd,       "go to the physical end of medium"},
1543  {"fill",       fillcmd,      "fill tape, write onto second volume"},
1544  {"unfill",     unfillcmd,    "read filled tape"},
1545  {"fsf",        fsfcmd,       "forward space a file"},
1546  {"fsr",        fsrcmd,       "forward space a record"},
1547  {"help",       helpcmd,      "print this command"},
1548  {"label",      labelcmd,     "write a Bacula label to the tape"},
1549  {"load",       loadcmd,      "load a tape"},
1550  {"quit",       quitcmd,      "quit btape"},   
1551  {"readlabel",  readlabelcmd, "read and print the Bacula tape label"},
1552  {"rectest",    rectestcmd,   "test record handling functions"},
1553  {"rewind",     rewindcmd,    "rewind the tape"},
1554  {"scan",       scancmd,      "read tape block by block to EOT and report"}, 
1555  {"status",     statcmd,      "print tape status"},
1556  {"test",       testcmd,      "General test Bacula tape functions"},
1557  {"weof",       weofcmd,      "write an EOF on the tape"},
1558  {"wr",         wrcmd,        "write a single Bacula block"}, 
1559  {"rr",         rrcmd,        "read a single record"},
1560              };
1561 #define comsize (sizeof(commands)/sizeof(struct cmdstruct))
1562
1563 static void
1564 do_tape_cmds()
1565 {
1566    unsigned int i;
1567    int found;
1568
1569    while (get_cmd("*")) {
1570       sm_check(__FILE__, __LINE__, False);
1571       found = 0;
1572       for (i=0; i<comsize; i++)       /* search for command */
1573          if (fstrsch(cmd,  commands[i].key)) {
1574             (*commands[i].func)();    /* go execute command */
1575             found = 1;
1576             break;
1577          }
1578       if (!found)
1579          Pmsg1(0, _("%s is an illegal command\n"), cmd);
1580       if (quit)
1581          break;
1582    }
1583 }
1584
1585 static void helpcmd()
1586 {
1587    unsigned int i;
1588    usage();
1589    printf(_("  Command    Description\n  =======    ===========\n"));
1590    for (i=0; i<comsize; i++)
1591       printf("  %-10s %s\n", commands[i].key, commands[i].help);
1592    printf("\n");
1593 }
1594
1595 static void usage()
1596 {
1597    fprintf(stderr, _(
1598 "\nVersion: " VERSION " (" BDATE ")\n\n"
1599 "Usage: btape [-c config_file] [-d debug_level] [device_name]\n"
1600 "       -c <file>   set configuration file to file\n"
1601 "       -dnn        set debug level to nn\n"
1602 "       -s          turn off signals\n"
1603 "       -t          open the default tape device\n"
1604 "       -?          print this message.\n"  
1605 "\n"));
1606
1607 }
1608
1609 /*      
1610  * Get next input command from terminal.  This
1611  * routine is REALLY primitive, and should be enhanced
1612  * to have correct backspacing, etc.
1613  */
1614 int 
1615 get_cmd(char *prompt)
1616 {
1617    int i = 0;
1618    int ch;
1619    fprintf(stdout, prompt);
1620
1621    /* We really should turn off echoing and pretty this
1622     * up a bit.
1623     */
1624    cmd[i] = 0;
1625    while ((ch = fgetc(stdin)) != EOF) { 
1626       if (ch == '\n') {
1627          strip_trailing_junk(cmd);
1628          return 1;
1629       } else if (ch == 4 || ch == 0xd3 || ch == 0x8) {
1630          if (i > 0)
1631             cmd[--i] = 0;
1632          continue;
1633       } 
1634          
1635       cmd[i++] = ch;
1636       cmd[i] = 0;
1637    }
1638    quit = 1;
1639    return 0;
1640 }
1641
1642 /* Dummies to replace askdir.c */
1643 int     dir_get_volume_info(JCR *jcr, int writing) { return 1;}
1644 int     dir_update_volume_info(JCR *jcr, VOLUME_CAT_INFO *vol, int relabel) { return 1; }
1645 int     dir_create_jobmedia_record(JCR *jcr) { return 1; }
1646 int     dir_update_file_attributes(JCR *jcr, DEV_RECORD *rec) { return 1;}
1647 int     dir_send_job_status(JCR *jcr) {return 1;}
1648
1649
1650
1651 int     dir_find_next_appendable_volume(JCR *jcr) 
1652
1653    return 1; 
1654 }
1655
1656 int dir_ask_sysop_to_mount_volume(JCR *jcr, DEVICE *dev)
1657 {
1658    Pmsg1(-1, "%s", dev->errmsg);           /* print reason */
1659    fprintf(stderr, "Mount Volume \"%s\" on device %s and press return when ready: ",
1660       jcr->VolumeName, dev_name(dev));
1661    getchar();   
1662    return 1;
1663 }
1664
1665 int dir_ask_sysop_to_mount_next_volume(JCR *jcr, DEVICE *dev)
1666 {
1667    fprintf(stderr, "Mount next Volume on device %s and press return when ready: ",
1668       dev_name(dev));
1669    getchar();   
1670    set_volume_name("TestVolume2", 2);
1671    labelcmd();
1672    VolumeName = NULL;
1673    BlockNumber = 0;
1674    stop = 1;
1675    return 1;
1676 }
1677
1678 static int my_mount_next_read_volume(JCR *jcr, DEVICE *dev, DEV_BLOCK *block)
1679 {
1680    char ec1[50];
1681
1682    Pmsg1(000, "End of Volume \"%s\"\n", jcr->VolumeName);
1683
1684    if (LastBlock != block->BlockNumber) {
1685       VolBytes += block->block_len;
1686    }
1687    LastBlock = block->BlockNumber;
1688    now = time(NULL);
1689    now -= jcr->run_time;
1690    if (now <= 0) {
1691       now = 1;
1692    }
1693    kbs = (double)VolBytes / (1000.0 * (double)now);
1694    Pmsg3(-1, "Read block=%u, VolBytes=%s rate=%.1f KB/s\n", block->BlockNumber,
1695             edit_uint64_with_commas(VolBytes, ec1), (float)kbs);
1696
1697    if (strcmp(jcr->VolumeName, "TestVolume2") == 0) {
1698       end_of_tape = 1;
1699       return 0;
1700    }
1701
1702    free_vol_list(jcr);
1703    set_volume_name("TestVolume2", 2);
1704    jcr->bsr = NULL;
1705    create_vol_list(jcr);
1706    close_dev(dev);
1707    dev->state &= ~ST_READ; 
1708    if (!acquire_device_for_read(jcr, dev, block)) {
1709       Pmsg2(0, "Cannot open Dev=%s, Vol=%s\n", dev_name(dev), jcr->VolumeName);
1710       return 0;
1711    }
1712    return 1;                       /* next volume mounted */
1713 }
1714
1715 static void set_volume_name(char *VolName, int volnum) 
1716 {
1717    VolumeName = VolName;
1718    vol_num = volnum;
1719    pm_strcpy(&jcr->VolumeName, VolName);
1720    bstrncpy(dev->VolCatInfo.VolCatName, VolName, sizeof(dev->VolCatInfo.VolCatName));
1721 }