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