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