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