]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/stored/btape.c
Misc cleanup
[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);
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, _("Bad status from MTEOD. ERR=%s\n"), 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    int stat;
439
440    if ((stat=bsf_dev(dev, 1)) < 0) {
441       Pmsg1(0, _("Bad status from bsf. ERR=%s\n"), strerror(errno));
442    } else {
443       Pmsg0(0, _("Backspaced one file.\n"));
444    }
445 }
446
447 /*
448  * Backspace record   
449  */
450 static void bsrcmd()
451 {
452    int stat;
453
454    if ((stat=bsr_dev(dev, 1)) < 0) {
455       Pmsg1(0, _("Bad status from bsr. ERR=%s\n"), strerror(errno));
456    } else {
457       Pmsg0(0, _("Backspaced one record.\n"));
458    }
459 }
460
461 /*
462  * List device capabilities as defined in the 
463  *  stored.conf file.
464  */
465 static void capcmd()
466 {
467    printf(_("Device capabilities:\n"));
468    printf("%sEOF ", dev->capabilities & CAP_EOF ? "" : "!");
469    printf("%sBSR ", dev->capabilities & CAP_BSR ? "" : "!");
470    printf("%sBSF ", dev->capabilities & CAP_BSF ? "" : "!");
471    printf("%sFSR ", dev->capabilities & CAP_FSR ? "" : "!");
472    printf("%sFSF ", dev->capabilities & CAP_FSF ? "" : "!");
473    printf("%sEOM ", dev->capabilities & CAP_EOM ? "" : "!");
474    printf("%sREM ", dev->capabilities & CAP_REM ? "" : "!");
475    printf("%sRACCESS ", dev->capabilities & CAP_RACCESS ? "" : "!");
476    printf("%sAUTOMOUNT ", dev->capabilities & CAP_AUTOMOUNT ? "" : "!");
477    printf("%sLABEL ", dev->capabilities & CAP_LABEL ? "" : "!");
478    printf("%sANONVOLS ", dev->capabilities & CAP_ANONVOLS ? "" : "!");
479    printf("%sALWAYSOPEN ", dev->capabilities & CAP_ALWAYSOPEN ? "" : "!");
480    printf("\n");
481
482    printf(_("Device status:\n"));
483    printf("%sOPENED ", dev->state & ST_OPENED ? "" : "!");
484    printf("%sTAPE ", dev->state & ST_TAPE ? "" : "!");
485    printf("%sLABEL ", dev->state & ST_LABEL ? "" : "!");
486    printf("%sMALLOC ", dev->state & ST_MALLOC ? "" : "!");
487    printf("%sAPPEND ", dev->state & ST_APPEND ? "" : "!");
488    printf("%sREAD ", dev->state & ST_READ ? "" : "!");
489    printf("%sEOT ", dev->state & ST_EOT ? "" : "!");
490    printf("%sWEOT ", dev->state & ST_WEOT ? "" : "!");
491    printf("%sEOF ", dev->state & ST_EOF ? "" : "!");
492    printf("%sNEXTVOL ", dev->state & ST_NEXTVOL ? "" : "!");
493    printf("%sSHORT ", dev->state & ST_SHORT ? "" : "!");
494    printf("\n");
495
496    printf(_("Device parameters:\n"));
497    printf("Device name: %s\n", dev->dev_name);
498    printf("File=%u block=%u\n", dev->file, dev->block_num);
499    printf("Min block=%u Max block=%u\n", dev->min_block_size, dev->max_block_size);
500
501    printf("Status:\n");
502    statcmd();
503
504 }
505
506 /*
507  * Test writting larger and larger records.  
508  * This is a torture test for records.
509  */
510 static void rectestcmd()
511 {
512    DEV_BLOCK *block;
513    DEV_RECORD *rec;
514    int i, blkno = 0;
515
516    Pmsg0(0, "Test writting larger and larger records.\n"
517 "This is a torture test for records.\nI am going to write\n"
518 "larger and larger records. It will stop when the record size\n"
519 "plus the header exceeds the block size (by default about 64K)\n");
520
521
522    get_cmd("Do you want to continue? (y/n): ");
523    if (cmd[0] != 'y') {
524       Pmsg0(000, "Command aborted.\n");
525       return;
526    }
527
528    sm_check(__FILE__, __LINE__, False);
529    block = new_block(dev);
530    rec = new_record();
531
532    for (i=1; i<500000; i++) {
533       rec->data = check_pool_memory_size(rec->data, i);
534       memset(rec->data, i & 0xFF, i);
535       rec->data_len = i;
536       sm_check(__FILE__, __LINE__, False);
537       if (write_record_to_block(block, rec)) {
538          empty_block(block);
539          blkno++;
540          Pmsg2(0, "Block %d i=%d\n", blkno, i);
541       } else {
542          break;
543       }
544       sm_check(__FILE__, __LINE__, False);
545    }
546    free_record(rec);
547    free_block(block);
548    sm_check(__FILE__, __LINE__, False);
549 }
550
551 /*
552  * This test attempts to re-read a block written by Bacula
553  *   normally at the end of the tape. Bacula will then back up
554  *   over the two eof marks, backup over the record and reread
555  *   it to make sure it is valid.  Bacula can skip this validation
556  *   if you set "Backward space record = no"
557  */
558 static int re_read_block_test()
559 {
560    DEV_BLOCK *block;
561    DEV_RECORD *rec;
562    int stat = 0;
563    int len;
564
565    if (!(dev->capabilities & CAP_BSR)) {
566       Pmsg0(-1, _("Skipping read backwards test because BSR turned off.\n"));
567       return 0;
568    }
569
570    Pmsg0(-1, _("\n=== Write, backup, and re-read test ===\n\n"
571       "I'm going to write three records and two eof's\n"
572       "then backup over the eof's and re-read the last record.\n"     
573       "Bacula does this after writing the last block on the\n"
574       "tape to verify that the block was written correctly.\n"
575       "It is not an *essential* feature ...\n\n")); 
576    rewindcmd();
577    block = new_block(dev);
578    rec = new_record();
579    rec->data = check_pool_memory_size(rec->data, block->buf_len);
580    len = rec->data_len = block->buf_len-100;
581    memset(rec->data, 1, rec->data_len);
582    if (!write_record_to_block(block, rec)) {
583       Pmsg0(0, _("Error writing record to block.\n")); 
584       goto bail_out;
585    }
586    if (!write_block_to_dev(jcr, dev, block)) {
587       Pmsg0(0, _("Error writing block to device.\n")); 
588       goto bail_out;
589    } else {
590       Pmsg1(0, _("Wrote first record of %d bytes.\n"), rec->data_len);
591    }
592    memset(rec->data, 2, rec->data_len);
593    if (!write_record_to_block(block, rec)) {
594       Pmsg0(0, _("Error writing record to block.\n")); 
595       goto bail_out;
596    }
597    if (!write_block_to_dev(jcr, dev, block)) {
598       Pmsg0(0, _("Error writing block to device.\n")); 
599       goto bail_out;
600    } else {
601       Pmsg1(0, _("Wrote second record of %d bytes.\n"), rec->data_len);
602    }
603    memset(rec->data, 3, rec->data_len);
604    if (!write_record_to_block(block, rec)) {
605       Pmsg0(0, _("Error writing record to block.\n")); 
606       goto bail_out;
607    }
608    if (!write_block_to_dev(jcr, dev, block)) {
609       Pmsg0(0, _("Error writing block to device.\n")); 
610       goto bail_out;
611    } else {
612       Pmsg1(0, _("Wrote third record of %d bytes.\n"), rec->data_len);
613    }
614    weofcmd();
615    weofcmd();
616    if (bsf_dev(dev, 1) != 0) {
617       Pmsg1(0, _("Backspace file failed! ERR=%s\n"), strerror(dev->dev_errno));
618       goto bail_out;
619    }
620    if (bsf_dev(dev, 1) != 0) {
621       Pmsg1(0, _("Backspace file failed! ERR=%s\n"), strerror(dev->dev_errno));
622       goto bail_out;
623    }
624    Pmsg0(0, "Backspaced over two EOFs OK.\n");
625    if (bsr_dev(dev, 1) != 0) {
626       Pmsg1(0, _("Backspace record failed! ERR=%s\n"), strerror(dev->dev_errno));
627       goto bail_out;
628    }
629    Pmsg0(0, "Backspace record OK.\n");
630    if (!read_block_from_dev(jcr, dev, block, NO_BLOCK_NUMBER_CHECK)) {
631       Pmsg1(0, _("Read block failed! ERR=%s\n"), strerror(dev->dev_errno));
632       goto bail_out;
633    }
634    memset(rec->data, 0, rec->data_len);
635    if (!read_record_from_block(block, rec)) {
636       Pmsg1(0, _("Read block failed! ERR=%s\n"), strerror(dev->dev_errno));
637       goto bail_out;
638    }
639    for (int i=0; i<len; i++) {
640       if (rec->data[i] != 3) {
641          Pmsg0(0, _("Bad data in record. Test failed!\n"));
642          goto bail_out;
643       }
644    }
645    Pmsg0(0, _("\nBlock re-read correct. Test succeeded!\n"));
646    Pmsg0(-1, _("=== End Write, backup, and re-read test ===\n\n"));
647
648    stat = 1;
649
650 bail_out:
651    free_block(block);
652    free_record(rec);
653    if (stat == 0) {
654       Pmsg0(0, _("This is not terribly serious since Bacula only uses\n"
655                  "this function to verify the last block written to the\n"
656                  "tape. Bacula will skip the last block verification\n"
657                  "if you add:\n\n"
658                   "Backward Space Record = No\n\n"
659                   "to your Storage daemon's Device resource definition.\n"));
660    }   
661    return stat;
662 }
663
664 /*
665  * This test writes some records, then writes an end of file,
666  *   rewinds the tape, moves to the end of the data and attepts
667  *   to append to the tape.  This function is essential for
668  *   Bacula to be able to write multiple jobs to the tape.
669  */
670 static int append_test()
671 {
672    Pmsg0(-1, _("\n\n=== Append files test ===\n\n"
673                "This test is essential to Bacula.\n\n"
674 "I'm going to write one record  in file 0,\n"
675 "                   two records in file 1,\n"
676 "             and three records in file 2\n\n"));
677    rewindcmd();
678    wrcmd();
679    weofcmd();      /* end file 0 */
680    wrcmd();
681    wrcmd();
682    weofcmd();      /* end file 1 */
683    wrcmd();
684    wrcmd();
685    wrcmd();
686    weofcmd();     /* end file 2 */
687    rewindcmd();
688    Pmsg0(0, _("Now moving to end of medium.\n"));
689    eodcmd();
690    Pmsg2(-1, _("We should be in file 3. I am at file %d. This is %s\n"), 
691       dev->file, dev->file == 3 ? "correct!" : "NOT correct!!!!");
692
693    if (dev->file != 3) {
694       return -1;
695    }
696
697    Pmsg0(-1, _("\nNow the important part, I am going to attempt to append to the tape.\n\n"));
698    wrcmd(); 
699    weofcmd();
700    rewindcmd();
701    Pmsg0(-1, _("Done appending, there should be no I/O errors\n\n"));
702    Pmsg0(-1, "Doing Bacula scan of blocks:\n");
703    scan_blocks();
704    Pmsg0(-1, _("End scanning the tape.\n"));
705    Pmsg2(-1, _("We should be in file 4. I am at file %d. This is %s\n"), 
706       dev->file, dev->file == 4 ? "correct!" : "NOT correct!!!!");
707
708    if (dev->file != 4) {
709       return -2;
710    }
711
712    return 1;
713 }
714
715 /* 
716  * This is a general test of Bacula's functions
717  *   needed to read and write the tape.
718  */
719 static void testcmd()
720 {
721    int stat;
722
723    stat = append_test();
724    if (stat == 1) {                   /* OK get out */
725       goto all_done;
726    }
727    if (stat == -1) {                  /* first test failed */
728       if (dev_cap(dev, CAP_EOM)) {
729          Pmsg0(-1, "\nAppend test failed. Attempting again.\n"
730                    "Setting \"Hardware End of Medium = no\" and retrying append test.\n\n");
731          dev->capabilities &= ~CAP_EOM; /* turn off eom */
732          stat = append_test();
733          if (stat == 1) {
734             Pmsg0(-1, "\n\nIt looks like the test worked this time, please add:\n\n"
735                      "    Hardware End of Medium = No\n\n"
736                      "to your Device resource in the Storage conf file.\n");
737             goto all_done;
738          }
739          if (stat == -1) {
740             Pmsg0(-1, "\n\nThat appears not to have corrected the problem.\n");
741             goto all_done;
742          }
743          /* Wrong count after append */
744          if (stat == -2) {
745             Pmsg0(-1, "\n\nIt looks like the append failed. Attempting again.\n"
746                      "Setting \"BSF at EOM = yes\" and retrying append test.\n");
747             dev->capabilities |= CAP_BSFATEOM; /* backspace on eom */
748             stat = append_test();
749             if (stat == 1) {
750                Pmsg0(-1, "\n\nIt looks like the test worked this time, please add:\n\n"
751                      "    Hardware End of Medium = No\n"
752                      "    BSR at EOM = yes\n\n"
753                      "to your Device resource in the Storage conf file.\n");
754                goto all_done;
755             }
756          }
757
758          Pmsg0(-1, "\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n"
759                "Unable to correct the problem. You MUST fix this\n"
760                 "problem before Bacula can use your tape drive correctly\n");
761          Pmsg0(-1, "\nPerhaps running Bacula in fixed block mode will work.\n"
762                "Do so by setting:\n\n"
763                "Minimum Block Size = nnn\n"
764                "Maximum Block Size = nnn\n\n"
765                "in your Storage daemon's Device definition.\n"
766                "nnn must match your tape driver's block size.\n"
767                "This, however, is not really an ideal solution.\n");
768       }
769    }
770
771 all_done:
772    Pmsg0(-1, _("\nThe above Bacula scan should have output identical to what follows.\n"
773         "Please double check it ...\n"
774         "=== Sample correct output ===\n"
775         "1 block of 64448 bytes in file 1\n"
776         "End of File mark.\n"
777         "2 blocks of 64448 bytes in file 2\n"
778         "End of File mark.\n"
779         "3 blocks of 64448 bytes in file 3\n"
780         "End of File mark.\n"
781         "1 block of 64448 bytes in file 4\n" 
782         "End of File mark.\n"
783         "Total files=4, blocks=7, bytes = 451136\n"
784         "=== End sample correct output ===\n\n"));
785
786    Pmsg0(-1, _("If the above scan output is not identical to the\n"
787                "sample output, you MUST correct the problem\n"
788                "or Bacula will not be able to write multiple Jobs to \n"
789                "the tape.\n\n"));
790
791    if (stat == 1) {
792       re_read_block_test();
793    }
794
795    Pmsg0(-1, _("\n=== End Append files test ===\n"));
796    
797 }
798
799 /* Forward space a file */
800 static void fsfcmd()
801 {
802    if (!fsf_dev(dev, 1)) {
803       Pmsg1(0, "Bad status from fsf. ERR=%s\n", strerror_dev(dev));
804       return;
805    }
806    Pmsg0(0, "Forward spaced one file.\n");
807 }
808
809 /* Forward space a record */
810 static void fsrcmd()
811 {
812    int stat;
813
814    if ((stat=fsr_dev(dev, 1)) < 0) {
815       Pmsg2(0, "Bad status from fsr %d. ERR=%s\n", stat, strerror_dev(dev));
816       return;
817    }
818    Pmsg0(0, "Forward spaced one record.\n");
819 }
820
821
822 /*
823  * Write a Bacula block to the tape
824  */
825 static void wrcmd()
826 {
827    DEV_BLOCK *block;
828    DEV_RECORD *rec;
829    int i;
830
831    sm_check(__FILE__, __LINE__, False);
832    block = new_block(dev);
833    rec = new_record();
834    dump_block(block, "test");
835
836    i = block->buf_len - 100;
837    ASSERT (i > 0);
838    rec->data = check_pool_memory_size(rec->data, i);
839    memset(rec->data, i & 0xFF, i);
840    rec->data_len = i;
841    sm_check(__FILE__, __LINE__, False);
842    if (!write_record_to_block(block, rec)) {
843       Pmsg0(0, _("Error writing record to block.\n")); 
844       goto bail_out;
845    }
846    if (!write_block_to_dev(jcr, dev, block)) {
847       Pmsg0(0, _("Error writing block to device.\n")); 
848       goto bail_out;
849    } else {
850       Pmsg1(0, _("Wrote one record of %d bytes.\n"), i);
851    }
852    Pmsg0(0, _("Wrote block to device.\n"));
853
854 bail_out:
855    sm_check(__FILE__, __LINE__, False);
856    free_record(rec);
857    free_block(block);
858    sm_check(__FILE__, __LINE__, False);
859 }
860
861 /* 
862  * Read a record from the tape
863  */
864 static void rrcmd()
865 {
866    char *buf;
867    int stat, len;
868
869    if (!get_cmd("Enter length to read: ")) {
870       return;
871    }
872    len = atoi(cmd);
873    if (len < 0 || len > 1000000) {
874       Pmsg0(0, _("Bad length entered, using default of 1024 bytes.\n"));
875       len = 1024;
876    }
877    buf = (char *)malloc(len);
878    stat = read(dev->fd, buf, len);
879    if (stat > 0 && stat <= len) {
880       errno = 0;
881    }
882    Pmsg3(0, _("Read of %d bytes gives stat=%d. ERR=%s\n"),
883       len, stat, strerror(errno));
884    free(buf);
885 }
886
887
888 /*
889  * Scan tape by reading block by block. Report what is
890  * on the tape.  Note, this command does raw reads, and as such
891  * will not work with fixed block size devices.
892  */
893 static void scancmd()
894 {
895    int stat;
896    int blocks, tot_blocks, tot_files;
897    int block_size;
898    uint64_t bytes;
899    char ec1[50];
900
901
902    blocks = block_size = tot_blocks = 0;
903    bytes = 0;
904    if (dev->state & ST_EOT) {
905       Pmsg0(0, "End of tape\n");
906       return; 
907    }
908    update_pos_dev(dev);
909    tot_files = dev->file;
910    Pmsg1(0, _("Starting scan at file %u\n"), dev->file);
911    for (;;) {
912       if ((stat = read(dev->fd, buf, sizeof(buf))) < 0) {
913          clrerror_dev(dev, -1);
914          Mmsg2(&dev->errmsg, "read error on %s. ERR=%s.\n",
915             dev->dev_name, strerror(dev->dev_errno));
916          Pmsg2(0, "Bad status from read %d. ERR=%s\n", stat, strerror_dev(dev));
917          if (blocks > 0)
918             printf("%d block%s of %d bytes in file %d\n",        
919                     blocks, blocks>1?"s":"", block_size, dev->file);
920          return;
921       }
922       Dmsg1(200, "read status = %d\n", stat);
923 /*    sleep(1); */
924       if (stat != block_size) {
925          update_pos_dev(dev);
926          if (blocks > 0) {
927             printf("%d block%s of %d bytes in file %d\n", 
928                  blocks, blocks>1?"s":"", block_size, dev->file);
929             blocks = 0;
930          }
931          block_size = stat;
932       }
933       if (stat == 0) {                /* EOF */
934          update_pos_dev(dev);
935          printf("End of File mark.\n");
936          /* Two reads of zero means end of tape */
937          if (dev->state & ST_EOF)
938             dev->state |= ST_EOT;
939          else {
940             dev->state |= ST_EOF;
941             dev->file++;
942          }
943          if (dev->state & ST_EOT) {
944             printf("End of tape\n");
945             break;
946          }
947       } else {                        /* Got data */
948          dev->state &= ~ST_EOF;
949          blocks++;
950          tot_blocks++;
951          bytes += stat;
952       }
953    }
954    update_pos_dev(dev);
955    tot_files = dev->file - tot_files;
956    printf("Total files=%d, blocks=%d, bytes = %s\n", tot_files, tot_blocks, 
957       edit_uint64_with_commas(bytes, ec1));
958 }
959
960
961 /*
962  * Scan tape by reading Bacula block by block. Report what is
963  * on the tape.  This function reads Bacula blocks, so if your
964  * Device resource is correctly defined, it should work with
965  * either variable or fixed block sizes.
966  */
967 static void scan_blocks()
968 {
969    int blocks, tot_blocks, tot_files;
970    uint32_t block_size;
971    uint64_t bytes;
972    DEV_BLOCK *block;
973    char ec1[50];
974
975    block = new_block(dev);
976    blocks = block_size = tot_blocks = 0;
977    bytes = 0;
978
979    update_pos_dev(dev);
980    tot_files = dev->file;
981    for (;;) {
982       if (!read_block_from_device(jcr, dev, block, NO_BLOCK_NUMBER_CHECK)) {
983          Dmsg1(100, "!read_block(): ERR=%s\n", strerror_dev(dev));
984          if (dev->state & ST_EOT) {
985             if (blocks > 0) {
986                printf("%d block%s of %d bytes in file %d\n", 
987                     blocks, blocks>1?"s":"", block_size, dev->file);
988                blocks = 0;
989             }
990             goto bail_out;
991          }
992          if (dev->state & ST_EOF) {
993             if (blocks > 0) {
994                printf("%d block%s of %d bytes in file %d\n",        
995                        blocks, blocks>1?"s":"", block_size, dev->file);
996                blocks = 0;
997             }
998             printf(_("End of File mark.\n"));
999             continue;
1000          }
1001          if (dev->state & ST_SHORT) {
1002             if (blocks > 0) {
1003                printf("%d block%s of %d bytes in file %d\n",        
1004                        blocks, blocks>1?"s":"", block_size, dev->file);
1005                blocks = 0;
1006             }
1007             printf(_("Short block read.\n"));
1008             continue;
1009          }
1010          printf(_("Error reading block. ERR=%s\n"), strerror_dev(dev));
1011          goto bail_out;
1012       }
1013       if (block->block_len != block_size) {
1014          if (blocks > 0) {
1015             printf("%d block%s of %d bytes in file %d\n",        
1016                     blocks, blocks>1?"s":"", block_size, dev->file);
1017             blocks = 0;
1018          }
1019          block_size = block->block_len;
1020       }
1021       blocks++;
1022       tot_blocks++;
1023       bytes += block->block_len;
1024       Dmsg6(100, "Blk_blk=%u dev_blk=%u blen=%u bVer=%d SessId=%u SessTim=%u\n",
1025          block->BlockNumber, dev->block_num, block->block_len, block->BlockVer,
1026          block->VolSessionId, block->VolSessionTime);
1027       if (verbose == 1) {
1028          DEV_RECORD *rec = new_record();
1029          read_record_from_block(block, rec);
1030          Pmsg8(-1, "Blk_block: %u dev_blk=%u blen=%u First rec FI=%s SessId=%u SessTim=%u Strm=%s rlen=%d\n",
1031               block->BlockNumber, dev->block_num, block->block_len,
1032               FI_to_ascii(rec->FileIndex), rec->VolSessionId, rec->VolSessionTime,
1033               stream_to_ascii(rec->Stream, rec->FileIndex), rec->data_len);
1034          rec->remainder = 0;
1035          free_record(rec);
1036       } else if (verbose > 1) {
1037          dump_block(block, "");
1038       }
1039
1040    }
1041 bail_out:
1042    free_block(block);
1043    tot_files = dev->file - tot_files;
1044    printf("Total files=%d, blocks=%d, bytes = %s\n", tot_files, tot_blocks, 
1045       edit_uint64_with_commas(bytes, ec1));
1046 }
1047
1048
1049 static void statcmd()
1050 {
1051    int stat = 0;
1052    int debug;
1053    uint32_t status;
1054
1055    debug = debug_level;
1056    debug_level = 30;
1057    if (!status_dev(dev, &status)) {
1058       Pmsg2(0, "Bad status from status %d. ERR=%s\n", stat, strerror_dev(dev));
1059    }
1060 #ifdef xxxx
1061    dump_volume_label(dev);
1062 #endif
1063    debug_level = debug;
1064 }
1065
1066
1067 /* 
1068  * First we label the tape, then we fill
1069  *  it with data get a new tape and write a few blocks.
1070  */                            
1071 static void fillcmd()
1072 {
1073    DEV_RECORD rec;
1074    DEV_BLOCK  *block;
1075    char ec1[50];
1076
1077    ok = TRUE;
1078    stop = 0;
1079    vol_num = 0;
1080
1081    Pmsg0(-1, "\n\
1082 This command simulates Bacula writing to a tape.\n\
1083 It requires either one or two blank tapes, which it\n\
1084 will label and write. It will print a status approximately\n\
1085 every 322 MB, and write an EOF every 3.2 GB.  If you have\n\
1086 selected the simple test option, after writing the first tape\n\
1087 it will rewind it and re-read the last block written.\n\
1088 If you have selected the multiple tape test, when the first tape\n\
1089 fills, it will ask for a second, and after writing a few more \n\
1090 blocks, it will stop.  Then it will begin re-reading the\n\
1091 two tapes.\n\n\
1092 This may take a long time -- hours! ...\n\n");
1093
1094    get_cmd("Insert a blank tape then indicate if you want\n"
1095            "to run the simplified test (s) with one tape or\n"
1096            "the complete multiple tape (m) test: (s/m) ");
1097    if (cmd[0] == 's') {
1098       Pmsg0(-1, "Simple test (single tape) selected.\n");
1099       simple = TRUE;
1100    } else if (cmd[0] == 'm') {
1101       Pmsg0(-1, "Complete multiple tape test selected.\n"); 
1102       simple = FALSE;
1103    } else {
1104       Pmsg0(000, "Command aborted.\n");
1105       return;
1106    }
1107
1108    set_volume_name("TestVolume1", 1);
1109    labelcmd();
1110    VolumeName = NULL;
1111
1112    
1113    Dmsg1(20, "Begin append device=%s\n", dev_name(dev));
1114
1115    block = new_block(dev);
1116
1117    /* 
1118     * Acquire output device for writing.  Note, after acquiring a
1119     *   device, we MUST release it, which is done at the end of this
1120     *   subroutine.
1121     */
1122    Dmsg0(100, "just before acquire_device\n");
1123    if (!(dev=acquire_device_for_append(jcr, dev, block))) {
1124       set_jcr_job_status(jcr, JS_ErrorTerminated);
1125       free_block(block);
1126       return;
1127    }
1128
1129    Dmsg0(100, "Just after acquire_device_for_append\n");
1130    /*
1131     * Write Begin Session Record
1132     */
1133    if (!write_session_label(jcr, block, SOS_LABEL)) {
1134       set_jcr_job_status(jcr, JS_ErrorTerminated);
1135       Jmsg1(jcr, M_FATAL, 0, _("Write session label failed. ERR=%s\n"),
1136          strerror_dev(dev));
1137       ok = FALSE;
1138    }
1139    Pmsg0(-1, "Wrote Start Of Session label.\n");
1140
1141    memset(&rec, 0, sizeof(rec));
1142    rec.data = get_memory(100000);     /* max record size */
1143
1144 #define REC_SIZE 32768
1145    rec.data_len = REC_SIZE;
1146
1147    /* 
1148     * Generate data as if from File daemon, write to device   
1149     */
1150    jcr->VolFirstIndex = 0;
1151    time(&jcr->run_time);              /* start counting time for rates */
1152    Pmsg0(-1, "Begin writing Bacula records to first tape ...\n");
1153    Pmsg1(-1, "Block num = %d\n", dev->block_num);
1154    for (file_index = 0; ok && !job_canceled(jcr); ) {
1155       rec.VolSessionId = jcr->VolSessionId;
1156       rec.VolSessionTime = jcr->VolSessionTime;
1157       rec.FileIndex = ++file_index;
1158       rec.Stream = STREAM_FILE_DATA;
1159
1160       /* 
1161        * Fill the buffer with the file_index negated. Negation ensures that
1162        *   more bits are turned on.
1163        */
1164       uint64_t *lp = (uint64_t *)rec.data;
1165       for (uint32_t i=0; i < (rec.data_len-sizeof(uint64_t))/sizeof(uint64_t); i++) {
1166          *lp++ = ~file_index;
1167       }
1168
1169       Dmsg4(250, "before writ_rec FI=%d SessId=%d Strm=%s len=%d\n",
1170          rec.FileIndex, rec.VolSessionId, stream_to_ascii(rec.Stream, rec.FileIndex), 
1171          rec.data_len);
1172        
1173       while (!write_record_to_block(block, &rec)) {
1174          /*
1175           * When we get here we have just filled a block
1176           */
1177          Dmsg2(150, "!write_record_to_block data_len=%d rem=%d\n", rec.data_len,
1178                     rec.remainder);
1179
1180          /* Write block to tape */
1181          if (!flush_block(block, 1)) {
1182             break;
1183          }
1184
1185          /* Every 5000 blocks (approx 322MB) report where we are.
1186           */
1187          if ((block->BlockNumber % 5000) == 0) {
1188             now = time(NULL);
1189             now -= jcr->run_time;
1190             if (now <= 0) {
1191                now = 1;
1192             }
1193             kbs = (double)dev->VolCatInfo.VolCatBytes / (1000.0 * (double)now);
1194             Pmsg4(-1, "Wrote block=%u, blk_num=%d VolBytes=%s rate=%.1f KB/s\n", block->BlockNumber,
1195                dev->block_num,
1196                edit_uint64_with_commas(dev->VolCatInfo.VolCatBytes, ec1), (float)kbs);
1197          }
1198          /* Every 15000 blocks (approx 1GB) write an EOF.
1199           */
1200          if ((block->BlockNumber % 15000) == 0) {
1201             Pmsg0(-1, "Flush block, write EOF\n");
1202             flush_block(block, 0);
1203             weof_dev(dev, 1);
1204          }
1205
1206          /* Get out after writing 10 blocks to the second tape */
1207          if (++BlockNumber > 10 && stop != 0) {      /* get out */
1208             break;    
1209          }
1210       }
1211       if (!ok) {
1212          Pmsg0(000, _("Not OK\n"));
1213          break;
1214       }
1215       jcr->JobBytes += rec.data_len;   /* increment bytes this job */
1216       Dmsg4(190, "write_record FI=%s SessId=%d Strm=%s len=%d\n",
1217          FI_to_ascii(rec.FileIndex), rec.VolSessionId, 
1218          stream_to_ascii(rec.Stream, rec.FileIndex), rec.data_len);
1219
1220       /* Get out after writing 10 blocks to the second tape */
1221       if (BlockNumber > 10 && stop != 0) {      /* get out */
1222          Pmsg0(-1, "Done writing ...\n");
1223          break;    
1224       }
1225    }
1226    if (stop > 0) {
1227       Dmsg0(100, "Write_end_session_label()\n");
1228       /* Create Job status for end of session label */
1229       if (!job_canceled(jcr) && ok) {
1230          set_jcr_job_status(jcr, JS_Terminated);
1231       } else if (!ok) {
1232          set_jcr_job_status(jcr, JS_ErrorTerminated);
1233       }
1234       if (!write_session_label(jcr, block, EOS_LABEL)) {
1235          Pmsg1(000, _("Error writting end session label. ERR=%s\n"), strerror_dev(dev));
1236          ok = FALSE;
1237       }
1238       /* Write out final block of this session */
1239       if (!write_block_to_device(jcr, dev, block)) {
1240          Pmsg0(-1, _("Set ok=FALSE after write_block_to_device.\n"));
1241          ok = FALSE;
1242       }
1243       Pmsg0(-1, "Wrote End Of Session label.\n");
1244    }
1245
1246    /* Release the device */
1247    if (!release_device(jcr, dev)) {
1248       Pmsg0(-1, _("Error in release_device\n"));
1249       ok = FALSE;
1250    }
1251
1252    free_block(block);
1253    free_memory(rec.data);
1254
1255    dump_block(last_block, _("Last block written to tape.\n"));
1256
1257    Pmsg0(-1, _("\n\nDone filling tape. Now beginning re-read of tape ...\n"));
1258
1259    unfillcmd();
1260 }
1261
1262 /*
1263  * Read two tapes written by the "fill" command and ensure
1264  *  that the data is valid.  If stop==1 we simulate full read back
1265  *  of two tapes.  If stop==-1 we simply read the last block and
1266  *  verify that it is correct.
1267  */
1268 static void unfillcmd()
1269 {
1270    DEV_BLOCK *block;
1271
1272    dumped = 0;
1273    VolBytes = 0;
1274    LastBlock = 0;
1275    block = new_block(dev);
1276
1277    dev->capabilities |= CAP_ANONVOLS; /* allow reading any volume */
1278    dev->capabilities &= ~CAP_LABEL;   /* don't label anything here */
1279
1280    end_of_tape = 0;
1281
1282    if (!simple) {
1283       /* Close device so user can use autochanger if desired */
1284       if (dev_cap(dev, CAP_OFFLINEUNMOUNT)) {
1285          offline_dev(dev);
1286       }
1287       force_close_dev(dev);
1288       get_cmd(_("Mount first tape. Press enter when ready: ")); 
1289    
1290       free_vol_list(jcr);
1291       set_volume_name("TestVolume1", 1);
1292       jcr->bsr = NULL;
1293       create_vol_list(jcr);
1294       close_dev(dev);
1295       dev->state &= ~ST_READ;
1296       if (!acquire_device_for_read(jcr, dev, block)) {
1297          Pmsg1(-1, "%s", dev->errmsg);
1298          return;
1299       }
1300    }
1301
1302    time(&jcr->run_time);              /* start counting time for rates */
1303    stop = 0;
1304    file_index = 0;
1305    if (!simple) {
1306       /* Read all records and then second tape */
1307       read_records(jcr, dev, record_cb, my_mount_next_read_volume);
1308    } else {
1309       /*
1310        * Simplified test, we simply fsf to file, then read the
1311        * last block and make sure it is the same as the saved block.
1312        */
1313       Pmsg0(000, "Rewinding tape ...\n");
1314       if (!rewind_dev(dev)) {
1315          Pmsg1(-1, _("Error rewinding: ERR=%s\n"), strerror_dev(dev));
1316          goto bail_out;
1317       }
1318       if (last_file > 0) {
1319          Pmsg1(000, "Forward spacing to last file=%u\n", last_file);
1320          if (!fsf_dev(dev, last_file)) {
1321             Pmsg1(-1, _("Error in FSF: ERR=%s\n"), strerror_dev(dev));
1322             goto bail_out;
1323          }
1324       }
1325       Pmsg1(-1, _("Forward space to file %u complete. Reading blocks ...\n"), 
1326             last_file);
1327       Pmsg1(-1, _("Now reading to block %u.\n"), last_block_num);
1328       for (uint32_t i=0; i <= last_block_num; i++) {
1329          if (!read_block_from_device(jcr, dev, block, NO_BLOCK_NUMBER_CHECK)) {
1330             Pmsg1(-1, _("Error reading blocks: ERR=%s\n"), strerror_dev(dev));
1331             Pmsg2(-1, _("Wanted block %u error at block %u\n"), last_block_num, i);
1332             goto bail_out;
1333          }
1334          if (i > 0 && i % 1000 == 0) {
1335             Pmsg1(-1, _("At block %u\n"), i);
1336          }
1337       }
1338       if (last_block) {
1339          dump_block(last_block, _("Last block written"));
1340          dump_block(block, _("Block read back"));
1341          Pmsg0(-1, _("Except for the buffer address, the contents of\n"
1342                      "the above two block dumps should be the same.\n"
1343                      "If not you have a problem ...\n"));
1344       }
1345    }
1346
1347 bail_out:
1348    free_block(block);
1349
1350    Pmsg0(000, _("Done with reread of fill data.\n"));
1351 }
1352
1353 /* 
1354  * We are called here from "unfill" for each record on the tape.
1355  */
1356 static int record_cb(JCR *jcr, DEVICE *dev, DEV_BLOCK *block, DEV_RECORD *rec)
1357 {
1358    SESSION_LABEL label;
1359
1360    if (stop > 1 && !dumped) {         /* on second tape */
1361       dumped = 1;
1362       dump_block(block, "First block on second tape");
1363       Pmsg4(-1, "Blk: FileIndex=%d: block=%u size=%d vol=%s\n", 
1364            rec->FileIndex, block->BlockNumber, block->block_len, dev->VolHdr.VolName);
1365       Pmsg6(-1, "   Rec: VId=%d VT=%d FI=%s Strm=%s len=%d state=%x\n",
1366            rec->VolSessionId, rec->VolSessionTime, 
1367            FI_to_ascii(rec->FileIndex), stream_to_ascii(rec->Stream, rec->FileIndex),
1368            rec->data_len, rec->state);
1369    }
1370    if (rec->FileIndex < 0) {
1371       if (verbose > 1) {
1372          dump_label_record(dev, rec, 1);
1373       }
1374       switch (rec->FileIndex) {
1375       case PRE_LABEL:
1376          Pmsg0(-1, "Volume is prelabeled. This tape cannot be scanned.\n");
1377          return 1;;
1378       case VOL_LABEL:
1379          unser_volume_label(dev, rec);
1380          Pmsg3(-1, "VOL_LABEL: block=%u size=%d vol=%s\n", block->BlockNumber, 
1381             block->block_len, dev->VolHdr.VolName);
1382          stop++;
1383          break;
1384       case SOS_LABEL:
1385          unser_session_label(&label, rec);
1386          Pmsg1(-1, "SOS_LABEL: JobId=%u\n", label.JobId);
1387          break;
1388       case EOS_LABEL:
1389          unser_session_label(&label, rec);
1390          Pmsg2(-1, "EOS_LABEL: block=%u JobId=%u\n", block->BlockNumber, 
1391             label.JobId);
1392          break;
1393       case EOM_LABEL:
1394          Pmsg0(-1, "EOM_LABEL:\n");
1395          break;
1396       case EOT_LABEL:              /* end of all tapes */
1397          char ec1[50];
1398
1399          if (LastBlock != block->BlockNumber) {
1400             VolBytes += block->block_len;
1401          }
1402          LastBlock = block->BlockNumber;
1403          now = time(NULL);
1404          now -= jcr->run_time;
1405          if (now <= 0) {
1406             now = 1;
1407          }
1408          kbs = (double)VolBytes / (1000 * now);
1409          Pmsg3(000, "Read block=%u, VolBytes=%s rate=%.1f KB/s\n", block->BlockNumber,
1410                   edit_uint64_with_commas(VolBytes, ec1), (float)kbs);
1411
1412          Pmsg0(000, "End of all tapes.\n");
1413
1414          break;
1415       default:
1416          break;
1417       }
1418       return 1;
1419    }
1420    if (++file_index != rec->FileIndex) {
1421       Pmsg3(000, "Incorrect FileIndex in Block %u. Got %d, expected %d.\n", 
1422          block->BlockNumber, rec->FileIndex, file_index);
1423    }
1424    /*
1425     * Now check that the right data is in the record.
1426     */
1427    uint64_t *lp = (uint64_t *)rec->data;
1428    uint64_t val = ~file_index;
1429    for (uint32_t i=0; i < (REC_SIZE-sizeof(uint64_t))/sizeof(uint64_t); i++) {
1430       if (*lp++ != val) {
1431          Pmsg2(000, "Record %d contains bad data in Block %u.\n",
1432             file_index, block->BlockNumber);
1433          break;
1434       }
1435    }
1436
1437    if (LastBlock != block->BlockNumber) {
1438       VolBytes += block->block_len;
1439    }
1440    if ((block->BlockNumber != LastBlock) && (block->BlockNumber % 50000) == 0) {
1441       char ec1[50];
1442       now = time(NULL);
1443       now -= jcr->run_time;
1444       if (now <= 0) {
1445          now = 1;
1446       }
1447       kbs = (double)VolBytes / (1000 * now);
1448       Pmsg3(000, "Read block=%u, VolBytes=%s rate=%.1f KB/s\n", block->BlockNumber,
1449                edit_uint64_with_commas(VolBytes, ec1), (float)kbs);
1450    }
1451    LastBlock = block->BlockNumber;
1452    if (end_of_tape) {
1453       Pmsg1(000, "End of all blocks. Block=%u\n", block->BlockNumber);
1454    }
1455    return 1;
1456 }
1457
1458
1459
1460 /*
1461  * Write current block to tape regardless of whether or
1462  *   not it is full. If the tape fills, attempt to
1463  *   acquire another tape.
1464  */
1465 static int flush_block(DEV_BLOCK *block, int dump)
1466 {
1467    char ec1[50];
1468    lock_device(dev);
1469    DEV_BLOCK *tblock;
1470    uint32_t this_file, this_block_num;
1471
1472    if (!this_block) {
1473       this_block = new_block(dev);
1474    }
1475    /* Copy block */
1476    free_memory(this_block->buf);    
1477    memcpy(this_block, block, sizeof(DEV_BLOCK));
1478    this_block->buf = get_memory(block->buf_len);
1479    memcpy(this_block->buf, block->buf, this_block->buf_len);
1480    this_file = dev->file;
1481    this_block_num = dev->block_num;
1482    if (!write_block_to_dev(jcr, dev, block)) {
1483       Pmsg3(000, "Block not written: FileIndex=%u Block=%u Size=%u\n", 
1484          (unsigned)file_index, block->BlockNumber, block->block_len);
1485       Pmsg2(000, "last_block_num=%u this_block_num=%d\n", last_block_num,
1486          this_block_num);
1487       if (dump) {
1488          dump_block(block, "Block not written");
1489       }
1490       if (stop == 0) {
1491          eot_block = block->BlockNumber;
1492          eot_block_len = block->block_len;
1493          eot_FileIndex = file_index;
1494       }
1495       now = time(NULL);
1496       now -= jcr->run_time;
1497       if (now <= 0) {
1498          now = 1;
1499       }
1500       kbs = (double)dev->VolCatInfo.VolCatBytes / (1000 * now);
1501       vol_size = dev->VolCatInfo.VolCatBytes;
1502       Pmsg2(000, "End of tape. VolumeCapacity=%s. Write rate = %.1f KB/s\n", 
1503          edit_uint64_with_commas(dev->VolCatInfo.VolCatBytes, ec1), kbs);
1504
1505       if (simple) {
1506          stop = -1;                   /* stop, but do simplified test */
1507       } else {
1508          /* Full test in progress */
1509          if (!fixup_device_block_write_error(jcr, dev, block)) {
1510             Pmsg1(000, _("Cannot fixup device error. %s\n"), strerror_dev(dev));
1511             ok = FALSE;
1512             unlock_device(dev);
1513             return 0;
1514          }
1515          stop = 1;                                                     
1516          BlockNumber = 0;             /* start counting for second tape */
1517       }
1518       unlock_device(dev);
1519       return 1;                       /* end of tape reached */
1520    }
1521
1522    /*
1523     * Toggle between two allocated blocks for efficiency.
1524     * Switch blocks so that the block just successfully written is
1525     *  always in last_block. 
1526     */
1527    tblock = last_block;
1528    last_block = this_block; 
1529    this_block = tblock;
1530    last_file = this_file;
1531    last_block_num = this_block_num;
1532
1533    unlock_device(dev);
1534    return 1;
1535 }
1536
1537
1538 /* 
1539  * First we label the tape, then we fill
1540  *  it with data get a new tape and write a few blocks.
1541  */                            
1542 static void qfillcmd()
1543 {
1544    DEV_BLOCK *block;
1545    DEV_RECORD *rec;
1546    int i, count;
1547
1548    Pmsg0(0, "Test writing blocks of 64512 bytes to tape.\n");
1549
1550    get_cmd("How many blocks do you want to write? (1000): ");
1551
1552    count = atoi(cmd);
1553    if (count <= 0) {
1554       count = 1000;
1555    }
1556
1557    sm_check(__FILE__, __LINE__, False);
1558    block = new_block(dev);
1559    rec = new_record();
1560
1561    i = block->buf_len - 100;
1562    ASSERT (i > 0);
1563    rec->data = check_pool_memory_size(rec->data, i);
1564    memset(rec->data, i & 0xFF, i);
1565    rec->data_len = i;
1566    rewindcmd();
1567    Pmsg1(0, "Begin writing %d Bacula blocks to tape ...\n", count);
1568    for (i=0; i < count; i++) {
1569       if (i % 100 == 0) {
1570          printf("+");
1571          fflush(stdout);
1572       }
1573       if (!write_record_to_block(block, rec)) {
1574          Pmsg0(0, _("Error writing record to block.\n")); 
1575          goto bail_out;
1576       }
1577       if (!write_block_to_dev(jcr, dev, block)) {
1578          Pmsg0(0, _("Error writing block to device.\n")); 
1579          goto bail_out;
1580       }
1581    }
1582    printf("\n");
1583    weofcmd();
1584    weofcmd();
1585    rewindcmd();
1586    scan_blocks();
1587
1588 bail_out:
1589    sm_check(__FILE__, __LINE__, False);
1590    free_record(rec);
1591    free_block(block);
1592    sm_check(__FILE__, __LINE__, False);
1593
1594 }
1595
1596 /*
1597  * Fill a tape using raw write() command
1598  */
1599 static void rawfill_cmd()
1600 {
1601    DEV_BLOCK *block;
1602    int stat;
1603    int fd;
1604    uint32_t block_num = 0;
1605    uint32_t *p;
1606    int my_errno;
1607
1608    block = new_block(dev);
1609    fd = open("/dev/urandom", O_RDONLY);
1610    if (fd) {
1611       read(fd, block->buf, block->buf_len);
1612    } else {
1613       Pmsg0(0, "Cannot open /dev/urandom.\n");
1614       free_block(block);
1615       return;
1616    }
1617    p = (uint32_t *)block->buf;
1618    Pmsg1(0, "Begin writing raw blocks of %u bytes.\n", block->buf_len);
1619    for ( ;; ) {
1620       *p = block_num;
1621       stat = write(dev->fd, block->buf, block->buf_len);
1622       if (stat == (int)block->buf_len) {
1623          if ((block_num++ % 100) == 0) {
1624             printf("+");
1625             fflush(stdout);
1626          }
1627          continue;
1628       }
1629       break;
1630    }
1631    my_errno = errno;
1632    printf("\n");
1633    printf("Write failed at block %u. stat=%d ERR=%s\n", block_num, stat,
1634       strerror(my_errno));
1635    weofcmd();
1636    free_block(block);
1637 }
1638
1639
1640 /*
1641  * Fill a tape using raw write() command
1642  */
1643 static void bfill_cmd()
1644 {
1645    DEV_BLOCK *block;
1646    uint32_t block_num = 0;
1647    uint32_t *p;
1648    int my_errno;
1649    int fd;
1650
1651    block = new_block(dev);
1652    fd = open("/dev/urandom", O_RDONLY);
1653    if (fd) {
1654       read(fd, block->buf, block->buf_len);
1655    } else {
1656       Pmsg0(0, "Cannot open /dev/urandom.\n");
1657       free_block(block);
1658       return;
1659    }
1660    p = (uint32_t *)block->buf;
1661    Pmsg1(0, "Begin writing Bacula blocks of %u bytes.\n", block->buf_len);
1662    for ( ;; ) {
1663       *p = block_num;
1664       block->binbuf = block->buf_len;
1665       block->bufp = block->buf + block->binbuf;
1666       if (!write_block_to_dev(jcr, dev, block)) {
1667          break;
1668       }
1669       if ((block_num++ % 100) == 0) {
1670          printf("+");
1671          fflush(stdout);
1672       }
1673    }
1674    my_errno = errno;
1675    printf("\n");
1676    printf("Write failed at block %u.\n", block_num);     
1677    weofcmd();
1678    free_block(block);
1679 }
1680
1681
1682 struct cmdstruct { char *key; void (*func)(); char *help; }; 
1683 static struct cmdstruct commands[] = {
1684  {"bsf",        bsfcmd,       "backspace file"},
1685  {"bsr",        bsrcmd,       "backspace record"},
1686  {"bfill",      bfill_cmd,    "fill tape using Bacula writes"},
1687  {"cap",        capcmd,       "list device capabilities"},
1688  {"clear",      clearcmd,     "clear tape errors"},
1689  {"eod",        eodcmd,       "go to end of Bacula data for append"},
1690  {"eom",        eomcmd,       "go to the physical end of medium"},
1691  {"fill",       fillcmd,      "fill tape, write onto second volume"},
1692  {"unfill",     unfillcmd,    "read filled tape"},
1693  {"fsf",        fsfcmd,       "forward space a file"},
1694  {"fsr",        fsrcmd,       "forward space a record"},
1695  {"help",       helpcmd,      "print this command"},
1696  {"label",      labelcmd,     "write a Bacula label to the tape"},
1697  {"load",       loadcmd,      "load a tape"},
1698  {"quit",       quitcmd,      "quit btape"},   
1699  {"rawfill",    rawfill_cmd,  "use write() to fill tape"},
1700  {"readlabel",  readlabelcmd, "read and print the Bacula tape label"},
1701  {"rectest",    rectestcmd,   "test record handling functions"},
1702  {"rewind",     rewindcmd,    "rewind the tape"},
1703  {"scan",       scancmd,      "read() tape block by block to EOT and report"}, 
1704  {"scanblocks", scan_blocks,  "Bacula read block by block to EOT and report"},
1705  {"status",     statcmd,      "print tape status"},
1706  {"test",       testcmd,      "General test Bacula tape functions"},
1707  {"weof",       weofcmd,      "write an EOF on the tape"},
1708  {"wr",         wrcmd,        "write a single Bacula block"}, 
1709  {"rr",         rrcmd,        "read a single record"},
1710  {"qfill",      qfillcmd,     "quick fill command"},
1711              };
1712 #define comsize (sizeof(commands)/sizeof(struct cmdstruct))
1713
1714 static void
1715 do_tape_cmds()
1716 {
1717    unsigned int i;
1718    int found;
1719
1720    while (get_cmd("*")) {
1721       sm_check(__FILE__, __LINE__, False);
1722       found = 0;
1723       for (i=0; i<comsize; i++)       /* search for command */
1724          if (fstrsch(cmd,  commands[i].key)) {
1725             (*commands[i].func)();    /* go execute command */
1726             found = 1;
1727             break;
1728          }
1729       if (!found)
1730          Pmsg1(0, _("%s is an illegal command\n"), cmd);
1731       if (quit)
1732          break;
1733    }
1734 }
1735
1736 static void helpcmd()
1737 {
1738    unsigned int i;
1739    usage();
1740    printf(_("  Command    Description\n  =======    ===========\n"));
1741    for (i=0; i<comsize; i++)
1742       printf("  %-10s %s\n", commands[i].key, commands[i].help);
1743    printf("\n");
1744 }
1745
1746 static void usage()
1747 {
1748    fprintf(stderr, _(
1749 "\nVersion: " VERSION " (" BDATE ")\n\n"
1750 "Usage: btape [-c config_file] [-d debug_level] [device_name]\n"
1751 "       -c <file>   set configuration file to file\n"
1752 "       -dnn        set debug level to nn\n"
1753 "       -s          turn off signals\n"
1754 "       -t          open the default tape device\n"
1755 "       -?          print this message.\n"  
1756 "\n"));
1757
1758 }
1759
1760 /*      
1761  * Get next input command from terminal.  This
1762  * routine is REALLY primitive, and should be enhanced
1763  * to have correct backspacing, etc.
1764  */
1765 int 
1766 get_cmd(char *prompt)
1767 {
1768    int i = 0;
1769    int ch;
1770    fprintf(stdout, prompt);
1771
1772    /* We really should turn off echoing and pretty this
1773     * up a bit.
1774     */
1775    cmd[i] = 0;
1776    while ((ch = fgetc(stdin)) != EOF) { 
1777       if (ch == '\n') {
1778          strip_trailing_junk(cmd);
1779          return 1;
1780       } else if (ch == 4 || ch == 0xd3 || ch == 0x8) {
1781          if (i > 0)
1782             cmd[--i] = 0;
1783          continue;
1784       } 
1785          
1786       cmd[i++] = ch;
1787       cmd[i] = 0;
1788    }
1789    quit = 1;
1790    return 0;
1791 }
1792
1793 /* Dummies to replace askdir.c */
1794 int     dir_get_volume_info(JCR *jcr, enum get_vol_info_rw  writing) { return 1;}
1795 int     dir_update_volume_info(JCR *jcr, VOLUME_CAT_INFO *vol, int relabel) { return 1; }
1796 int     dir_create_jobmedia_record(JCR *jcr) { return 1; }
1797 int     dir_update_file_attributes(JCR *jcr, DEV_RECORD *rec) { return 1;}
1798 int     dir_send_job_status(JCR *jcr) {return 1;}
1799
1800
1801
1802 int     dir_find_next_appendable_volume(JCR *jcr) 
1803
1804    return 1; 
1805 }
1806
1807 int dir_ask_sysop_to_mount_volume(JCR *jcr, DEVICE *dev)
1808 {
1809    /* Close device so user can use autochanger if desired */
1810    if (dev_cap(dev, CAP_OFFLINEUNMOUNT)) {
1811       offline_dev(dev);
1812    }
1813    force_close_dev(dev);
1814    Pmsg1(-1, "%s", dev->errmsg);           /* print reason */
1815    fprintf(stderr, "Mount Volume \"%s\" on device %s and press return when ready: ",
1816       jcr->VolumeName, dev_name(dev));
1817    getchar();   
1818    return 1;
1819 }
1820
1821 int dir_ask_sysop_to_mount_next_volume(JCR *jcr, DEVICE *dev)
1822 {
1823    /* Close device so user can use autochanger if desired */
1824    if (dev_cap(dev, CAP_OFFLINEUNMOUNT)) {
1825       offline_dev(dev);
1826    }
1827    force_close_dev(dev);
1828    fprintf(stderr, "Mount next Volume on device %s and press return when ready: ",
1829       dev_name(dev));
1830    getchar();   
1831    set_volume_name("TestVolume2", 2);
1832    labelcmd();
1833    VolumeName = NULL;
1834    BlockNumber = 0;
1835    stop = 1;
1836    return 1;
1837 }
1838
1839 static int my_mount_next_read_volume(JCR *jcr, DEVICE *dev, DEV_BLOCK *block)
1840 {
1841    char ec1[50];
1842
1843    Pmsg1(000, "End of Volume \"%s\"\n", jcr->VolumeName);
1844
1845    if (LastBlock != block->BlockNumber) {
1846       VolBytes += block->block_len;
1847    }
1848    LastBlock = block->BlockNumber;
1849    now = time(NULL);
1850    now -= jcr->run_time;
1851    if (now <= 0) {
1852       now = 1;
1853    }
1854    kbs = (double)VolBytes / (1000.0 * (double)now);
1855    Pmsg3(-1, "Read block=%u, VolBytes=%s rate=%.1f KB/s\n", block->BlockNumber,
1856             edit_uint64_with_commas(VolBytes, ec1), (float)kbs);
1857
1858    if (strcmp(jcr->VolumeName, "TestVolume2") == 0) {
1859       end_of_tape = 1;
1860       return 0;
1861    }
1862
1863    free_vol_list(jcr);
1864    set_volume_name("TestVolume2", 2);
1865    jcr->bsr = NULL;
1866    create_vol_list(jcr);
1867    close_dev(dev);
1868    dev->state &= ~ST_READ; 
1869    if (!acquire_device_for_read(jcr, dev, block)) {
1870       Pmsg2(0, "Cannot open Dev=%s, Vol=%s\n", dev_name(dev), jcr->VolumeName);
1871       return 0;
1872    }
1873    return 1;                       /* next volume mounted */
1874 }
1875
1876 static void set_volume_name(char *VolName, int volnum) 
1877 {
1878    VolumeName = VolName;
1879    vol_num = volnum;
1880    pm_strcpy(&jcr->VolumeName, VolName);
1881    bstrncpy(dev->VolCatInfo.VolCatName, VolName, sizeof(dev->VolCatInfo.VolCatName));
1882 }