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