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