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