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