]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/stored/btape.c
Doc updates +
[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-2004 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 bool forge_on = false;
49
50 /*
51  * If you change the format of the state file, 
52  *  increment this value
53  */ 
54 static uint32_t btape_state_level = 2;
55
56 DEVICE *dev = NULL;
57 DCR *dcr;
58 DEVRES *device = NULL;
59
60             
61 /* Forward referenced subroutines */
62 static void do_tape_cmds();
63 static void helpcmd();
64 static void scancmd();
65 static void rewindcmd();
66 static void clearcmd();
67 static void wrcmd();
68 static void rrcmd();
69 static void eodcmd();
70 static void fillcmd();
71 static void qfillcmd();
72 static void statcmd();
73 static void unfillcmd();
74 static int flush_block(DEV_BLOCK *block, int dump);
75 static bool quickie_cb(DCR *dcr, DEV_RECORD *rec);
76 static bool compare_blocks(DEV_BLOCK *last_block, DEV_BLOCK *block);
77 static bool my_mount_next_read_volume(DCR *dcr);
78 static void scan_blocks();
79 static void set_volume_name(const char *VolName, int volnum);
80 static void rawfill_cmd();
81 static void bfill_cmd();
82 static bool open_the_device();
83 static void autochangercmd();
84 static void do_unfill();
85
86
87 /* Static variables */
88 #define CONFIG_FILE "bacula-sd.conf"
89 char *configfile;
90
91 #define MAX_CMD_ARGS 30
92 static POOLMEM *cmd;
93 static POOLMEM *args;
94 static char *argk[MAX_CMD_ARGS];
95 static char *argv[MAX_CMD_ARGS];
96 static int argc;
97
98 static int quickie_count = 0;
99 static BSR *bsr = NULL;
100 static int signals = TRUE;
101 static bool ok;
102 static int stop = 0;
103 static uint64_t vol_size;
104 static uint64_t VolBytes;
105 static time_t now;
106 static double kbs;
107 static int32_t file_index;
108 static int end_of_tape = 0;
109 static uint32_t LastBlock = 0;
110 static uint32_t eot_block;
111 static uint32_t eot_block_len;
112 static uint32_t eot_FileIndex;
113 static int dumped = 0;
114 static DEV_BLOCK *last_block1 = NULL;
115 static DEV_BLOCK *last_block2 = NULL;
116 static DEV_BLOCK *last_block = NULL;
117 static DEV_BLOCK *this_block = NULL;
118 static DEV_BLOCK *first_block = NULL;
119 static uint32_t last_file1 = 0;
120 static uint32_t last_file2 = 0;
121 static uint32_t last_file = 0;
122 static uint32_t last_block_num1 = 0;
123 static uint32_t last_block_num2 = 0;
124 static uint32_t last_block_num = 0;
125 static uint32_t BlockNumber = 0;
126 static bool simple = true; 
127
128 static const char *VolumeName = NULL;
129 static int vol_num = 0;
130
131 static JCR *jcr = NULL;
132
133
134 static void usage();
135 static void terminate_btape(int sig);
136 int get_cmd(const char *prompt);
137
138
139 /*********************************************************************
140  *
141  *         Main Bacula Pool Creation Program
142  *
143  */
144 int main(int margc, char *margv[])
145 {
146    int ch, i;
147    uint32_t x32, y32;
148    uint64_t x64, y64;
149    char buf[1000];
150
151    /* Sanity checks */
152    if (TAPE_BSIZE % DEV_BSIZE != 0 || TAPE_BSIZE / DEV_BSIZE == 0) {
153       Emsg2(M_ABORT, 0, "Tape block size (%d) not multiple of system size (%d)\n",
154          TAPE_BSIZE, DEV_BSIZE);
155    }
156    if (TAPE_BSIZE != (1 << (ffs(TAPE_BSIZE)-1))) {
157       Emsg1(M_ABORT, 0, "Tape block size (%d) is not a power of 2\n", TAPE_BSIZE);
158    }
159    if (sizeof(off_t) < 8) {
160       Pmsg1(-1, "\n\n!!!! Warning large disk addressing disabled. off_t=%d should be 8 or more !!!!!\n\n\n",
161          sizeof(off_t));
162    }
163    x32 = 123456789;
164    bsnprintf(buf, sizeof(buf), "%u", x32);
165    i = bsscanf(buf, "%u", &y32);
166    if (i != 1 || x32 != y32) {
167       Pmsg3(-1, "32 bit printf/scanf problem. i=%d x32=%u y32=%u\n", i, x32, y32);
168       exit(1);
169    }
170    x64 = 123456789;
171    x64 = x64 << 32;
172    x64 += 123456789;
173    bsnprintf(buf, sizeof(buf), "%" llu, x64);
174    i = bsscanf(buf, "%llu", &y64);
175    if (i != 1 || x64 != y64) {
176       Pmsg3(-1, "64 bit printf/scanf problem. i=%d x64=%" llu " y64=%" llu "\n", i, x64, y64);
177       exit(1);
178    }
179
180    printf("Tape block granularity is %d bytes.\n", TAPE_BSIZE);
181
182    working_directory = "/tmp";
183    my_name_is(margc, margv, "btape");
184    init_msg(NULL, NULL);
185
186    while ((ch = getopt(margc, margv, "b:c:d:psv?")) != -1) {
187       switch (ch) {
188       case 'b':                    /* bootstrap file */
189          bsr = parse_bsr(NULL, optarg);
190 //       dump_bsr(bsr, true);
191          break;
192
193       case 'c':                    /* specify config file */
194          if (configfile != NULL) {
195             free(configfile);
196          }
197          configfile = bstrdup(optarg);
198          break;
199
200       case 'd':                    /* set debug level */
201          debug_level = atoi(optarg);
202          if (debug_level <= 0) {
203             debug_level = 1; 
204          }
205          break;
206
207       case 'p':
208          forge_on = true;
209          break;
210
211       case 's':
212          signals = false;
213          break;
214
215       case 'v':
216          verbose++;
217          break;
218
219       case '?':
220       default:
221          helpcmd();
222          exit(0);
223
224       }  
225    }
226    margc -= optind;
227    margv += optind;
228
229    cmd = get_pool_memory(PM_FNAME);
230    args = get_pool_memory(PM_FNAME);
231    
232    if (signals) {
233       init_signals(terminate_btape);
234    }
235
236    if (configfile == NULL) {
237       configfile = bstrdup(CONFIG_FILE);
238    }
239
240    daemon_start_time = time(NULL);
241
242    parse_config(configfile);
243
244
245    /* See if we can open a device */
246    if (margc == 0) {
247       Pmsg0(000, "No archive name specified.\n");
248       usage();
249       exit(1);
250    } else if (margc != 1) {
251       Pmsg0(000, "Improper number of arguments specified.\n");
252       usage();
253       exit(1);
254    }
255
256    jcr = setup_jcr("btape", margv[0], bsr, NULL, 0); /* write */
257    if (!jcr) {
258       exit(1);
259    }
260    dev = jcr->dcr->dev;
261    if (!dev) {
262       exit(1);
263    }
264    dcr = jcr->dcr;
265    if (!open_the_device()) {
266       goto terminate;
267    }
268
269    Dmsg0(200, "Do tape commands\n");
270    do_tape_cmds();
271   
272 terminate:
273    terminate_btape(0);
274    return 0;
275 }
276
277 static void terminate_btape(int stat)
278 {
279
280    sm_check(__FILE__, __LINE__, false);
281    if (configfile) {
282       free(configfile);
283    }
284    free_config_resources();
285    if (args) {
286       free_pool_memory(args);
287       args = NULL;
288    }
289    if (cmd) {
290       free_pool_memory(cmd);
291       cmd = NULL;
292    }
293
294    if (bsr) {
295       free_bsr(bsr);
296    }
297
298    free_jcr(jcr);
299    jcr = NULL;
300
301    if (dev) {
302       term_dev(dev);
303    }
304
305    if (debug_level > 10)
306       print_memory_pool_stats(); 
307
308    if (this_block) {
309       free_block(this_block);
310    }
311
312    stop_watchdog();
313    term_msg();
314    close_memory_pool();               /* free memory in pool */
315
316    sm_dump(false);
317    exit(stat);
318 }
319
320 static bool open_the_device()
321 {
322    DEV_BLOCK *block;
323    
324    block = new_block(dev);
325    lock_device(dev);
326    if (!(dev->state & ST_OPENED)) {
327       Dmsg1(200, "Opening device %s\n", dcr->VolumeName);
328       if (open_dev(dev, dcr->VolumeName, OPEN_READ_WRITE) < 0) {
329          Emsg1(M_FATAL, 0, _("dev open failed: %s\n"), dev->errmsg);
330          unlock_device(dev);
331          free_block(block);
332          return false;
333       }
334    }
335    Pmsg1(000, "open_dev %s OK\n", dev_name(dev));
336    dev->state |= ST_APPEND;
337    unlock_device(dev);
338    free_block(block);
339    return true;
340 }
341
342
343 void quitcmd()
344 {
345    quit = 1;
346 }
347
348 /*
349  * Write a label to the tape   
350  */
351 static void labelcmd()
352 {
353    if (VolumeName) {
354       pm_strcpy(cmd, VolumeName);
355    } else {
356       if (!get_cmd("Enter Volume Name: ")) {
357          return;
358       }
359    }
360          
361    if (!(dev->state & ST_OPENED)) {
362       if (!first_open_device(dev)) {
363          Pmsg1(0, "Device open failed. ERR=%s\n", strerror_dev(dev));
364       }
365    }
366    rewind_dev(dev);
367    write_new_volume_label_to_dev(dcr, cmd, "Default");
368    Pmsg1(-1, "Wrote Volume label for volume \"%s\".\n", cmd);
369 }
370
371 /*
372  * Read the tape label   
373  */
374 static void readlabelcmd()
375 {
376    int save_debug_level = debug_level;
377    int stat;
378
379    stat = read_dev_volume_label(dcr);
380    switch (stat) {
381    case VOL_NO_LABEL:
382       Pmsg0(0, "Volume has no label.\n");
383       break;
384    case VOL_OK:
385       Pmsg0(0, "Volume label read correctly.\n");
386       break;
387    case VOL_IO_ERROR:
388       Pmsg1(0, "I/O error on device: ERR=%s", strerror_dev(dev));
389       break;
390    case VOL_NAME_ERROR:
391       Pmsg0(0, "Volume name error\n");
392       break;
393    case VOL_CREATE_ERROR:
394       Pmsg1(0, "Error creating label. ERR=%s", strerror_dev(dev));
395       break;
396    case VOL_VERSION_ERROR:
397       Pmsg0(0, "Volume version error.\n");
398       break;
399    case VOL_LABEL_ERROR:
400       Pmsg0(0, "Bad Volume label type.\n");
401       break;
402    default:
403       Pmsg0(0, "Unknown error.\n");
404       break;
405    }
406
407    debug_level = 20;
408    dump_volume_label(dev); 
409    debug_level = save_debug_level;
410 }
411
412
413 /*
414  * Load the tape should have prevously been taken
415  * off line, otherwise this command is not necessary.
416  */
417 static void loadcmd()
418 {
419
420    if (!load_dev(dev)) {
421       Pmsg1(0, "Bad status from load. ERR=%s\n", strerror_dev(dev));
422    } else
423       Pmsg1(0, "Loaded %s\n", dev_name(dev));
424 }
425
426 /*
427  * Rewind the tape.   
428  */
429 static void rewindcmd()
430 {
431    if (!rewind_dev(dev)) {
432       Pmsg1(0, "Bad status from rewind. ERR=%s\n", strerror_dev(dev));
433       clrerror_dev(dev, -1);
434    } else {
435       Pmsg1(0, "Rewound %s\n", dev_name(dev));
436    }
437 }
438
439 /*
440  * Clear any tape error   
441  */
442 static void clearcmd()
443 {
444    clrerror_dev(dev, -1);
445 }
446
447 /*
448  * Write and end of file on the tape   
449  */
450 static void weofcmd()
451 {
452    int stat;
453    int num = 1;
454    if (argc > 1) {
455       num = atoi(argk[1]);
456    }
457    if (num <= 0) {
458       num = 1;
459    }
460
461    if ((stat = weof_dev(dev, num)) < 0) {
462       Pmsg2(0, "Bad status from weof %d. ERR=%s\n", stat, strerror_dev(dev));
463       return;
464    } else {
465       Pmsg3(0, "Wrote %d EOF%s to %s\n", num, num==1?"":"s", dev_name(dev));
466    }
467 }
468
469
470 /* Go to the end of the medium -- raw command   
471  * The idea was orginally that the end of the Bacula
472  * medium would be flagged differently. This is not
473  * currently the case. So, this is identical to the
474  * eodcmd().
475  */
476 static void eomcmd()
477 {
478    if (!eod_dev(dev)) {
479       Pmsg1(0, "%s", strerror_dev(dev));
480       return;
481    } else {
482       Pmsg0(0, _("Moved to end of medium.\n"));
483    }
484 }
485
486 /*
487  * Go to the end of the medium (either hardware determined
488  *  or defined by two eofs.
489  */
490 static void eodcmd()
491 {
492    eomcmd();
493 }
494
495 /*
496  * Backspace file   
497  */
498 static void bsfcmd()
499 {
500    int num = 1;
501    if (argc > 1) {
502       num = atoi(argk[1]);
503    }
504    if (num <= 0) {
505       num = 1;
506    }
507
508    if (!bsf_dev(dev, num)) {
509       Pmsg1(0, _("Bad status from bsf. ERR=%s\n"), strerror_dev(dev));
510    } else {
511       Pmsg2(0, _("Backspaced %d file%s.\n"), num, num==1?"":"s");
512    }
513 }
514
515 /*
516  * Backspace record   
517  */
518 static void bsrcmd()
519 {
520    int num = 1;
521    if (argc > 1) {
522       num = atoi(argk[1]);
523    }
524    if (num <= 0) {
525       num = 1;
526    }
527    if (!bsr_dev(dev, num)) {
528       Pmsg1(0, _("Bad status from bsr. ERR=%s\n"), strerror_dev(dev));
529    } else {
530       Pmsg2(0, _("Backspaced %d record%s.\n"), num, num==1?"":"s");
531    }
532 }
533
534 /*
535  * List device capabilities as defined in the 
536  *  stored.conf file.
537  */
538 static void capcmd()
539 {
540    printf(_("Configured device capabilities:\n"));
541    printf("%sEOF ", dev->capabilities & CAP_EOF ? "" : "!");
542    printf("%sBSR ", dev->capabilities & CAP_BSR ? "" : "!");
543    printf("%sBSF ", dev->capabilities & CAP_BSF ? "" : "!");
544    printf("%sFSR ", dev->capabilities & CAP_FSR ? "" : "!");
545    printf("%sFSF ", dev->capabilities & CAP_FSF ? "" : "!");
546    printf("%sFASTFSF ", dev->capabilities & CAP_FASTFSF ? "" : "!");
547    printf("%sEOM ", dev->capabilities & CAP_EOM ? "" : "!");
548    printf("%sREM ", dev->capabilities & CAP_REM ? "" : "!");
549    printf("%sRACCESS ", dev->capabilities & CAP_RACCESS ? "" : "!");
550    printf("%sAUTOMOUNT ", dev->capabilities & CAP_AUTOMOUNT ? "" : "!");
551    printf("%sLABEL ", dev->capabilities & CAP_LABEL ? "" : "!");
552    printf("%sANONVOLS ", dev->capabilities & CAP_ANONVOLS ? "" : "!");
553    printf("%sALWAYSOPEN ", dev->capabilities & CAP_ALWAYSOPEN ? "" : "!");
554    printf("\n");
555
556    printf(_("Device status:\n"));
557    printf("%sOPENED ", dev->state & ST_OPENED ? "" : "!");
558    printf("%sTAPE ", dev->state & ST_TAPE ? "" : "!");
559    printf("%sLABEL ", dev->state & ST_LABEL ? "" : "!");
560    printf("%sMALLOC ", dev->state & ST_MALLOC ? "" : "!");
561    printf("%sAPPEND ", dev->state & ST_APPEND ? "" : "!");
562    printf("%sREAD ", dev->state & ST_READ ? "" : "!");
563    printf("%sEOT ", dev->state & ST_EOT ? "" : "!");
564    printf("%sWEOT ", dev->state & ST_WEOT ? "" : "!");
565    printf("%sEOF ", dev->state & ST_EOF ? "" : "!");
566    printf("%sNEXTVOL ", dev->state & ST_NEXTVOL ? "" : "!");
567    printf("%sSHORT ", dev->state & ST_SHORT ? "" : "!");
568    printf("\n");
569
570    printf(_("Device parameters:\n"));
571    printf("Device name: %s\n", dev->dev_name);
572    printf("File=%u block=%u\n", dev->file, dev->block_num);
573    printf("Min block=%u Max block=%u\n", dev->min_block_size, dev->max_block_size);
574
575    printf("Status:\n");
576    statcmd();
577
578 }
579
580 /*
581  * Test writting larger and larger records.  
582  * This is a torture test for records.
583  */
584 static void rectestcmd()
585 {
586    DEV_BLOCK *block;
587    DEV_RECORD *rec;
588    int i, blkno = 0;
589
590    Pmsg0(0, "Test writting larger and larger records.\n"
591 "This is a torture test for records.\nI am going to write\n"
592 "larger and larger records. It will stop when the record size\n"
593 "plus the header exceeds the block size (by default about 64K)\n");
594
595
596    get_cmd("Do you want to continue? (y/n): ");
597    if (cmd[0] != 'y') {
598       Pmsg0(000, "Command aborted.\n");
599       return;
600    }
601
602    sm_check(__FILE__, __LINE__, false);
603    block = new_block(dev);
604    rec = new_record();
605
606    for (i=1; i<500000; i++) {
607       rec->data = check_pool_memory_size(rec->data, i);
608       memset(rec->data, i & 0xFF, i);
609       rec->data_len = i;
610       sm_check(__FILE__, __LINE__, false);
611       if (write_record_to_block(block, rec)) {
612          empty_block(block);
613          blkno++;
614          Pmsg2(0, "Block %d i=%d\n", blkno, i);
615       } else {
616          break;
617       }
618       sm_check(__FILE__, __LINE__, false);
619    }
620    free_record(rec);
621    free_block(block);
622    sm_check(__FILE__, __LINE__, false);
623 }
624
625 /*
626  * This test attempts to re-read a block written by Bacula
627  *   normally at the end of the tape. Bacula will then back up
628  *   over the two eof marks, backup over the record and reread
629  *   it to make sure it is valid.  Bacula can skip this validation
630  *   if you set "Backward space record = no"
631  */
632 static int re_read_block_test()
633 {
634    DEV_BLOCK *block = dcr->block;
635    DEV_RECORD *rec;
636    int stat = 0;
637    int len;
638
639    if (!(dev->capabilities & CAP_BSR)) {
640       Pmsg0(-1, _("Skipping read backwards test because BSR turned off.\n"));
641       return 0;
642    }
643
644    Pmsg0(-1, _("\n=== Write, backup, and re-read test ===\n\n"
645       "I'm going to write three records and an EOF\n"
646       "then backup over the EOF and re-read the last record.\n"     
647       "Bacula does this after writing the last block on the\n"
648       "tape to verify that the block was written correctly.\n\n"
649       "This is not an *essential* feature ...\n\n")); 
650    rewindcmd();
651    empty_block(block);
652    rec = new_record();
653    rec->data = check_pool_memory_size(rec->data, block->buf_len);
654    len = rec->data_len = block->buf_len-100;
655    memset(rec->data, 1, rec->data_len);
656    if (!write_record_to_block(block, rec)) {
657       Pmsg0(0, _("Error writing record to block.\n")); 
658       goto bail_out;
659    }
660    if (!write_block_to_dev(dcr)) {
661       Pmsg0(0, _("Error writing block to device.\n")); 
662       goto bail_out;
663    } else {
664       Pmsg1(0, _("Wrote first record of %d bytes.\n"), rec->data_len);
665    }
666    memset(rec->data, 2, rec->data_len);
667    if (!write_record_to_block(block, rec)) {
668       Pmsg0(0, _("Error writing record to block.\n")); 
669       goto bail_out;
670    }
671    if (!write_block_to_dev(dcr)) {
672       Pmsg0(0, _("Error writing block to device.\n")); 
673       goto bail_out;
674    } else {
675       Pmsg1(0, _("Wrote second record of %d bytes.\n"), rec->data_len);
676    }
677    memset(rec->data, 3, rec->data_len);
678    if (!write_record_to_block(block, rec)) {
679       Pmsg0(0, _("Error writing record to block.\n")); 
680       goto bail_out;
681    }
682    if (!write_block_to_dev(dcr)) {
683       Pmsg0(0, _("Error writing block to device.\n")); 
684       goto bail_out;
685    } else {
686       Pmsg1(0, _("Wrote third record of %d bytes.\n"), rec->data_len);
687    }
688    weofcmd();
689    if (dev_cap(dev, CAP_TWOEOF)) {
690       weofcmd();
691    }
692    if (!bsf_dev(dev, 1)) {
693       Pmsg1(0, _("Backspace file failed! ERR=%s\n"), strerror_dev(dev));
694       goto bail_out;
695    }
696    if (dev_cap(dev, CAP_TWOEOF)) {
697       if (!bsf_dev(dev, 1)) {
698          Pmsg1(0, _("Backspace file failed! ERR=%s\n"), strerror_dev(dev));
699          goto bail_out;
700       }
701    }
702    Pmsg0(0, "Backspaced over EOF OK.\n");
703    if (!bsr_dev(dev, 1)) {
704       Pmsg1(0, _("Backspace record failed! ERR=%s\n"), strerror_dev(dev));
705       goto bail_out;
706    }
707    Pmsg0(0, "Backspace record OK.\n");
708    if (!read_block_from_dev(dcr, NO_BLOCK_NUMBER_CHECK)) {
709       Pmsg1(0, _("Read block failed! ERR=%s\n"), strerror(dev->dev_errno));
710       goto bail_out;
711    }
712    memset(rec->data, 0, rec->data_len);
713    if (!read_record_from_block(block, rec)) {
714       Pmsg1(0, _("Read block failed! ERR=%s\n"), strerror(dev->dev_errno));
715       goto bail_out;
716    }
717    for (int i=0; i<len; i++) {
718       if (rec->data[i] != 3) {
719          Pmsg0(0, _("Bad data in record. Test failed!\n"));
720          goto bail_out;
721       }
722    }
723    Pmsg0(0, _("\nBlock re-read correct. Test succeeded!\n"));
724    Pmsg0(-1, _("=== End Write, backup, and re-read test ===\n\n"));
725
726    stat = 1;
727
728 bail_out:
729    free_record(rec);
730    if (stat == 0) {
731       Pmsg0(0, _("This is not terribly serious since Bacula only uses\n"
732                  "this function to verify the last block written to the\n"
733                  "tape. Bacula will skip the last block verification\n"
734                  "if you add:\n\n"
735                   "Backward Space Record = No\n\n"
736                   "to your Storage daemon's Device resource definition.\n"));
737    }   
738    return stat;
739 }
740
741
742 /*
743  * This test writes Bacula blocks to the tape in
744  *   several files. It then rewinds the tape and attepts
745  *   to read these blocks back checking the data.
746  */
747 static int write_read_test()
748 {
749    DEV_BLOCK *block;
750    DEV_RECORD *rec;
751    int stat = 0;
752    int len, i, j;
753    int *p;
754
755    Pmsg0(-1, _("\n=== Write, rewind, and re-read test ===\n\n"
756       "I'm going to write 1000 records and an EOF\n"
757       "then write 1000 records and an EOF, then rewind,\n"     
758       "and re-read the data to verify that it is correct.\n\n"
759       "This is an *essential* feature ...\n\n")); 
760    block = dcr->block;
761    rec = new_record();
762    if (!rewind_dev(dev)) {
763       Pmsg1(0, "Bad status from rewind. ERR=%s\n", strerror_dev(dev));
764       goto bail_out;
765    }
766    rec->data = check_pool_memory_size(rec->data, block->buf_len);
767    rec->data_len = block->buf_len-100;
768    len = rec->data_len/sizeof(i);
769    for (i=1; i<=1000; i++) {
770       p = (int *)rec->data;
771       for (j=0; j<len; j++) {
772          *p++ = i;
773       }
774       if (!write_record_to_block(block, rec)) {
775          Pmsg0(0, _("Error writing record to block.\n")); 
776          goto bail_out;
777       }
778       if (!write_block_to_dev(dcr)) {
779          Pmsg0(0, _("Error writing block to device.\n")); 
780          goto bail_out;
781       }
782    }
783    Pmsg1(0, _("Wrote 1000 blocks of %d bytes.\n"), rec->data_len);
784    weofcmd();
785    for (i=1001; i<=2000; i++) {
786       p = (int *)rec->data;
787       for (j=0; j<len; j++) {
788          *p++ = i;
789       }
790       if (!write_record_to_block(block, rec)) {
791          Pmsg0(0, _("Error writing record to block.\n")); 
792          goto bail_out;
793       }
794       if (!write_block_to_dev(dcr)) {
795          Pmsg0(0, _("Error writing block to device.\n")); 
796          goto bail_out;
797       }
798    }
799    Pmsg1(0, _("Wrote 1000 blocks of %d bytes.\n"), rec->data_len);
800    weofcmd();
801    if (dev_cap(dev, CAP_TWOEOF)) {
802       weofcmd();
803    }
804    if (!rewind_dev(dev)) {
805       Pmsg1(0, "Bad status from rewind. ERR=%s\n", strerror_dev(dev));
806       goto bail_out;
807    } else {
808       Pmsg0(0, "Rewind OK.\n");
809    }
810    for (i=1; i<=2000; i++) {
811 read_again:
812       if (!read_block_from_dev(dcr, NO_BLOCK_NUMBER_CHECK)) {
813          if (dev_state(dev, ST_EOF)) {
814             Pmsg0(-1, _("Got EOF on tape.\n"));
815             goto read_again;
816          }
817          Pmsg1(0, _("Read block failed! ERR=%s\n"), strerror(dev->dev_errno));
818          goto bail_out;
819       }
820       memset(rec->data, 0, rec->data_len);
821       if (!read_record_from_block(block, rec)) {
822          Pmsg1(0, _("Read record failed! ERR=%s\n"), strerror(dev->dev_errno));
823          goto bail_out;
824       }
825       p = (int *)rec->data;
826       for (j=0; j<len; j++) {
827          if (*p != i) {
828             Pmsg3(0, _("Bad data in record. Expected %d, got %d at byte %d. Test failed!\n"),
829                i, *p, j);
830             goto bail_out;
831          }
832          p++;
833       }
834       if (i == 1000 || i == 2000) {
835          Pmsg0(-1, _("1000 blocks re-read correctly.\n"));
836       }
837    }
838    Pmsg0(-1, _("=== Test Succeeded. End Write, rewind, and re-read test ===\n\n"));
839    stat = 1;
840
841 bail_out:
842    free_record(rec);
843    return stat;
844 }
845
846 /*
847  * This test writes Bacula blocks to the tape in
848  *   several files. It then rewinds the tape and attepts
849  *   to read these blocks back checking the data.
850  */
851 static int position_test()
852 {
853    DEV_BLOCK *block = dcr->block;
854    DEV_RECORD *rec;
855    int stat = 0;
856    int len, i, j;
857    bool ok = true;
858    int recno = 0;
859    int file = 0, blk = 0;
860    int *p;
861
862    Pmsg0(-1, _("\n=== Write, rewind, and position test ===\n\n"
863       "I'm going to write 1000 records and an EOF\n"
864       "then write 1000 records and an EOF, then rewind,\n"     
865       "and position to a few blocks and verify that it is correct.\n\n"
866       "This is an *essential* feature ...\n\n")); 
867    empty_block(block);
868    rec = new_record();
869    if (!rewind_dev(dev)) {
870       Pmsg1(0, "Bad status from rewind. ERR=%s\n", strerror_dev(dev));
871       goto bail_out;
872    }
873    rec->data = check_pool_memory_size(rec->data, block->buf_len);
874    rec->data_len = block->buf_len-100;
875    len = rec->data_len/sizeof(i);
876    for (i=1; i<=1000; i++) {
877       p = (int *)rec->data;
878       for (j=0; j<len; j++) {
879          *p++ = i;
880       }
881       if (!write_record_to_block(block, rec)) {
882          Pmsg0(0, _("Error writing record to block.\n")); 
883          goto bail_out;
884       }
885       if (!write_block_to_dev(dcr)) {
886          Pmsg0(0, _("Error writing block to device.\n")); 
887          goto bail_out;
888       }
889    }
890    Pmsg1(0, _("Wrote 1000 blocks of %d bytes.\n"), rec->data_len);
891    weofcmd();
892    for (i=1001; i<=2000; i++) {
893       p = (int *)rec->data;
894       for (j=0; j<len; j++) {
895          *p++ = i;
896       }
897       if (!write_record_to_block(block, rec)) {
898          Pmsg0(0, _("Error writing record to block.\n")); 
899          goto bail_out;
900       }
901       if (!write_block_to_dev(dcr)) {
902          Pmsg0(0, _("Error writing block to device.\n")); 
903          goto bail_out;
904       }
905    }
906    Pmsg1(0, _("Wrote 1000 blocks of %d bytes.\n"), rec->data_len);
907    weofcmd();
908    if (dev_cap(dev, CAP_TWOEOF)) {
909       weofcmd();
910    }
911    if (!rewind_dev(dev)) {
912       Pmsg1(0, "Bad status from rewind. ERR=%s\n", strerror_dev(dev));
913       goto bail_out;
914    } else {
915       Pmsg0(0, "Rewind OK.\n");
916    }
917
918    while(ok) {
919       /* Set up next item to read based on where we are */
920       switch (recno) {
921       case 0:
922          recno = 5;
923          file = 0;
924          blk = 4;
925          break;
926       case 5:
927          recno = 201;
928          file = 0;
929          blk = 200;
930          break;
931       case 201:
932          recno = 1000;
933          file = 0;
934          blk = 999;
935          break;
936       case 1000:
937          recno = 1001;
938          file = 1;
939          blk = 0;
940          break;
941       case 1001:
942          recno = 1601;
943          file = 1;
944          blk = 600;
945          break;
946       case 1601:
947          recno = 2000;
948          file = 1;
949          blk = 999;
950          break;
951       case 2000:
952          ok = false;
953          continue;
954       }
955       Pmsg2(-1, "Reposition to file:block %d:%d\n", file, blk);
956       if (!reposition_dev(dev, file, blk)) {
957          Pmsg0(0, "Reposition error.\n");
958          goto bail_out;
959       }
960 read_again:
961       if (!read_block_from_dev(dcr, NO_BLOCK_NUMBER_CHECK)) {
962          if (dev_state(dev, ST_EOF)) {
963             Pmsg0(-1, _("Got EOF on tape.\n"));
964             goto read_again;
965          }
966          Pmsg1(0, _("Read block failed! ERR=%s\n\n"), strerror(dev->dev_errno));
967          Pmsg0(0, _("This may be because the tape drive block size is not\n"
968                     " set to variable blocking as normally used by Bacula.\n"
969                     " Please see the Tape Testing chapter in the manual and \n"
970                     " look for using mt with defblksize and setoptions\n"));
971          goto bail_out;
972       }
973       memset(rec->data, 0, rec->data_len);
974       if (!read_record_from_block(block, rec)) {
975          Pmsg1(0, _("Read record failed! ERR=%s\n"), strerror(dev->dev_errno));
976          goto bail_out;
977       }
978       p = (int *)rec->data;
979       for (j=0; j<len; j++) {
980          if (p[j] != recno) {
981             Pmsg3(0, _("Bad data in record. Expected %d, got %d at byte %d. Test failed!\n"),
982                recno, p[j], j);
983             goto bail_out;
984          }
985       }
986       Pmsg0(-1, _("Block re-read correctly.\n"));
987    }
988    Pmsg0(-1, _("=== Test Succeeded. End Write, rewind, and re-read test ===\n\n"));
989    stat = 1;
990
991 bail_out:
992    free_record(rec);
993    return stat;
994 }
995
996
997
998
999 /*
1000  * This test writes some records, then writes an end of file,
1001  *   rewinds the tape, moves to the end of the data and attepts
1002  *   to append to the tape.  This function is essential for
1003  *   Bacula to be able to write multiple jobs to the tape.
1004  */
1005 static int append_test()
1006 {
1007    Pmsg0(-1, _("\n\n=== Append files test ===\n\n"
1008                "This test is essential to Bacula.\n\n"
1009 "I'm going to write one record  in file 0,\n"
1010 "                   two records in file 1,\n"
1011 "             and three records in file 2\n\n"));
1012    argc = 1;
1013    rewindcmd();
1014    wrcmd();
1015    weofcmd();      /* end file 0 */
1016    wrcmd();
1017    wrcmd();
1018    weofcmd();      /* end file 1 */
1019    wrcmd();
1020    wrcmd();
1021    wrcmd();
1022    weofcmd();     /* end file 2 */
1023    if (dev_cap(dev, CAP_TWOEOF)) {
1024       weofcmd();
1025    }
1026    force_close_dev(dev);              /* release device */
1027    if (!open_the_device()) {
1028       return -1;
1029    }
1030    rewindcmd();
1031    Pmsg0(0, _("Now moving to end of medium.\n"));
1032    eodcmd();
1033    Pmsg2(-1, _("We should be in file 3. I am at file %d. This is %s\n"), 
1034       dev->file, dev->file == 3 ? "correct!" : "NOT correct!!!!");
1035
1036    if (dev->file != 3) {
1037       return -1;
1038    }
1039
1040    Pmsg0(-1, _("\nNow the important part, I am going to attempt to append to the tape.\n\n"));
1041    wrcmd(); 
1042    weofcmd();
1043    if (dev_cap(dev, CAP_TWOEOF)) {
1044       weofcmd();
1045    }
1046    rewindcmd();
1047    Pmsg0(-1, _("Done appending, there should be no I/O errors\n\n"));
1048    Pmsg0(-1, "Doing Bacula scan of blocks:\n");
1049    scan_blocks();
1050    Pmsg0(-1, _("End scanning the tape.\n"));
1051    Pmsg2(-1, _("We should be in file 4. I am at file %d. This is %s\n"), 
1052       dev->file, dev->file == 4 ? "correct!" : "NOT correct!!!!");
1053
1054    if (dev->file != 4) {
1055       return -2;
1056    }
1057    return 1;
1058 }
1059
1060
1061 /*
1062  * This test exercises the autochanger
1063  */
1064 static int autochanger_test()
1065 {
1066    POOLMEM *results, *changer;
1067    int slot, status, loaded;
1068    int timeout = jcr->device->max_changer_wait;
1069    int sleep_time = 0;
1070
1071    Dmsg1(100, "Max changer wait = %d sec\n", timeout);
1072    if (!dev_cap(dev, CAP_AUTOCHANGER)) {
1073       return 1;
1074    }
1075    if (!(jcr->device && jcr->device->changer_name && jcr->device->changer_command)) {
1076       Pmsg0(-1, "\nAutochanger enabled, but no name or no command device specified.\n");
1077       return 1;
1078    }
1079
1080    Pmsg0(-1, "\nAh, I see you have an autochanger configured.\n"
1081              "To test the autochanger you must have a blank tape\n"
1082              " that I can write on in Slot 1.\n");
1083    if (!get_cmd("\nDo you wish to continue with the Autochanger test? (y/n): ")) {
1084       return 0;
1085    }
1086    if (cmd[0] != 'y' && cmd[0] != 'Y') {
1087       return 0;
1088    }
1089
1090    Pmsg0(-1, _("\n\n=== Autochanger test ===\n\n"));
1091
1092    results = get_pool_memory(PM_MESSAGE);
1093    changer = get_pool_memory(PM_FNAME);
1094
1095 try_again:
1096    slot = 1;
1097    dcr->VolCatInfo.Slot = slot;
1098    /* Find out what is loaded, zero means device is unloaded */
1099    Pmsg0(-1, _("3301 Issuing autochanger \"loaded\" command.\n"));
1100    changer = edit_device_codes(jcr, changer, jcr->device->changer_command, 
1101                 "loaded");
1102    status = run_program(changer, timeout, results);
1103    Dmsg3(100, "run_prog: %s stat=%d result=\"%s\"\n", changer, status, results);
1104    if (status == 0) {
1105       loaded = atoi(results);
1106    } else {
1107       berrno be;
1108       be.set_errno(status);
1109       Pmsg1(-1, _("3991 Bad autochanger command: %s\n"), changer);
1110       Pmsg2(-1, _("3991 result=\"%s\": ERR=%s\n"), results, be.strerror());
1111       goto bail_out;
1112    }
1113    if (loaded) {
1114       Pmsg1(-1, "Slot %d loaded. I am going to unload it.\n", loaded);
1115    } else {
1116       Pmsg0(-1, "Nothing loaded in the drive. OK.\n");
1117    }
1118    Dmsg1(100, "Results from loaded query=%s\n", results);
1119    if (loaded) {
1120       dcr->VolCatInfo.Slot = loaded;
1121       offline_or_rewind_dev(dev);
1122       /* We are going to load a new tape, so close the device */
1123       force_close_dev(dev);
1124       Pmsg2(-1, _("3302 Issuing autochanger \"unload %d %d\" command.\n"),
1125          loaded, dev->drive_index);
1126       changer = edit_device_codes(jcr, changer, 
1127                      jcr->device->changer_command, "unload");
1128       status = run_program(changer, timeout, results);
1129       Pmsg2(-1, "unload status=%s %d\n", status==0?"OK":"Bad", status);
1130       if (status != 0) {
1131          berrno be;
1132          be.set_errno(status);
1133          Pmsg1(-1, _("3992 Bad autochanger command: %s\n"), changer);
1134          Pmsg2(-1, _("3992 result=\"%s\": ERR=%s\n"), results, be.strerror());
1135       }
1136    }
1137
1138    /*
1139     * Load the Slot 1
1140     */
1141    
1142    slot = 1;
1143    dcr->VolCatInfo.Slot = slot;
1144    Pmsg2(-1, _("3303 Issuing autochanger \"load slot %d %d\" command.\n"), 
1145       slot, dev->drive_index);
1146    changer = edit_device_codes(jcr, changer, jcr->device->changer_command, "load");
1147    Dmsg1(100, "Changer=%s\n", changer);
1148    force_close_dev(dev);
1149    status = run_program(changer, timeout, results);
1150    if (status == 0) {
1151       Pmsg2(-1,  _("3303 Autochanger \"load slot %d %d\" status is OK.\n"),
1152          slot, dev->drive_index);
1153    } else {
1154       berrno be;
1155       be.set_errno(status);
1156       Pmsg1(-1, _("3993 Bad autochanger command: %s\n"), changer);
1157       Pmsg2(-1, _("3993 result=\"%s\": ERR=%s\n"), results, be.strerror());
1158       goto bail_out;
1159    }
1160
1161    if (!open_the_device()) {
1162       goto bail_out;
1163    }
1164    /*  
1165     * Start with sleep_time 0 then increment by 30 seconds if we get
1166     * a failure.
1167     */
1168    bmicrosleep(sleep_time, 0);
1169    if (!rewind_dev(dev) || weof_dev(dev,1) < 0) {
1170       Pmsg1(0, "Bad status from rewind. ERR=%s\n", strerror_dev(dev));
1171       clrerror_dev(dev, -1);
1172       Pmsg0(-1, "\nThe test failed, probably because you need to put\n"
1173                 "a longer sleep time in the mtx-script in the load) case.\n" 
1174                 "Adding a 30 second sleep and trying again ...\n");
1175       sleep_time += 30;
1176       goto try_again;
1177    } else {
1178       Pmsg1(0, "Rewound %s\n", dev_name(dev));
1179    }
1180       
1181    if ((status = weof_dev(dev, 1)) < 0) {
1182       Pmsg2(0, "Bad status from weof %d. ERR=%s\n", status, strerror_dev(dev));
1183       goto bail_out;
1184    } else {
1185       Pmsg1(0, "Wrote EOF to %s\n", dev_name(dev));
1186    }
1187
1188    if (sleep_time) {
1189       Pmsg1(-1, "\nThe test worked this time. Please add:\n\n"
1190                 "   sleep %d\n\n"
1191                 "to your mtx-changer script in the load) case.\n\n",
1192                 sleep_time);
1193    } else {
1194       Pmsg0(-1, "\nThe test autochanger worked!!\n\n");
1195    }
1196
1197    free_pool_memory(changer);
1198    free_pool_memory(results);
1199    return 1;
1200
1201
1202 bail_out:
1203    free_pool_memory(changer);
1204    free_pool_memory(results);
1205    Pmsg0(-1, "You must correct this error or the Autochanger will not work.\n");
1206    return -2;
1207 }
1208
1209 static void autochangercmd()
1210 {
1211    autochanger_test();
1212 }
1213
1214
1215 /*
1216  * This test assumes that the append test has been done,
1217  *   then it tests the fsf function.
1218  */
1219 static int fsf_test()
1220 {
1221    bool set_off = false;
1222    
1223    Pmsg0(-1, _("\n\n=== Forward space files test ===\n\n"
1224                "This test is essential to Bacula.\n\n"
1225                "I'm going to write five files then test forward spacing\n\n"));
1226    argc = 1;
1227    rewindcmd();
1228    wrcmd();
1229    weofcmd();      /* end file 0 */
1230    wrcmd();
1231    wrcmd();
1232    weofcmd();      /* end file 1 */
1233    wrcmd();
1234    wrcmd();
1235    wrcmd();
1236    weofcmd();     /* end file 2 */
1237    wrcmd();
1238    wrcmd();
1239    weofcmd();     /* end file 3 */
1240    wrcmd();
1241    weofcmd();     /* end file 4 */
1242    if (dev_cap(dev, CAP_TWOEOF)) {
1243       weofcmd();
1244    }
1245
1246 test_again:
1247    rewindcmd();
1248    Pmsg0(0, _("Now forward spacing 1 file.\n"));
1249    if (!fsf_dev(dev, 1)) {
1250       Pmsg1(0, "Bad status from fsr. ERR=%s\n", strerror_dev(dev));
1251       goto bail_out;
1252    }
1253    Pmsg2(-1, _("We should be in file 1. I am at file %d. This is %s\n"), 
1254       dev->file, dev->file == 1 ? "correct!" : "NOT correct!!!!");
1255
1256    if (dev->file != 1) {
1257       goto bail_out;
1258    }
1259
1260    Pmsg0(0, _("Now forward spacing 2 files.\n"));
1261    if (!fsf_dev(dev, 2)) {
1262       Pmsg1(0, "Bad status from fsr. ERR=%s\n", strerror_dev(dev));
1263       goto bail_out;
1264    }
1265    Pmsg2(-1, _("We should be in file 3. I am at file %d. This is %s\n"), 
1266       dev->file, dev->file == 3 ? "correct!" : "NOT correct!!!!");
1267
1268    if (dev->file != 3) {
1269       goto bail_out;
1270    }
1271
1272    rewindcmd();
1273    Pmsg0(0, _("Now forward spacing 4 files.\n"));
1274    if (!fsf_dev(dev, 4)) {
1275       Pmsg1(0, "Bad status from fsr. ERR=%s\n", strerror_dev(dev));
1276       goto bail_out;
1277    }
1278    Pmsg2(-1, _("We should be in file 4. I am at file %d. This is %s\n"), 
1279       dev->file, dev->file == 4 ? "correct!" : "NOT correct!!!!");
1280
1281    if (dev->file != 4) {
1282       goto bail_out;
1283    }
1284    if (set_off) {
1285       Pmsg0(-1, "The test worked this time. Please add:\n\n"
1286                 "   Fast Forward Space File = no\n\n"
1287                 "to your Device resource for this drive.\n");
1288    }
1289
1290    Pmsg0(-1, "\n");
1291    Pmsg0(0, _("Now forward spacing 1 more file.\n"));
1292    if (!fsf_dev(dev, 1)) {
1293       Pmsg1(0, "Bad status from fsr. ERR=%s\n", strerror_dev(dev));
1294    }
1295    Pmsg2(-1, _("We should be in file 5. I am at file %d. This is %s\n"), 
1296       dev->file, dev->file == 5 ? "correct!" : "NOT correct!!!!");
1297    if (dev->file != 5) {
1298       goto bail_out;
1299    }
1300    Pmsg0(-1, _("\n=== End Forward space files test ===\n\n"));
1301    return 1;
1302
1303 bail_out:
1304    Pmsg0(-1, _("\nThe forward space file test failed.\n"));
1305    if (dev_cap(dev, CAP_FASTFSF)) {
1306       Pmsg0(-1, "You have Fast Forward Space File enabled.\n"
1307               "I am turning it off then retrying the test.\n");
1308       dev->capabilities &= ~CAP_FASTFSF;
1309       set_off = true;
1310       goto test_again;
1311    }
1312    Pmsg0(-1, "You must correct this error or Bacula will not work.\n");
1313    return -2;
1314 }
1315
1316
1317
1318
1319
1320 /* 
1321  * This is a general test of Bacula's functions
1322  *   needed to read and write the tape.
1323  */
1324 static void testcmd()
1325 {
1326    int stat;
1327
1328    if (!write_read_test()) {
1329       return;
1330    }
1331    if (!position_test()) {
1332       return;
1333    }
1334
1335    stat = append_test();
1336    if (stat == 1) {                   /* OK get out */
1337       goto all_done;
1338    }
1339    if (stat == -1) {                  /* first test failed */
1340       if (dev_cap(dev, CAP_EOM) || dev_cap(dev, CAP_FASTFSF)) {
1341          Pmsg0(-1, "\nAppend test failed. Attempting again.\n"
1342                    "Setting \"Hardware End of Medium = no\n"
1343                    "    and \"Fast Forward Space File = no\n"
1344                    "and retrying append test.\n\n");
1345          dev->capabilities &= ~CAP_EOM; /* turn off eom */
1346          dev->capabilities &= ~CAP_FASTFSF; /* turn off fast fsf */
1347          stat = append_test();
1348          if (stat == 1) {
1349             Pmsg0(-1, "\n\nIt looks like the test worked this time, please add:\n\n"
1350                      "    Hardware End of Medium = No\n\n"
1351                      "    Fast Forward Space File = No\n"
1352                      "to your Device resource in the Storage conf file.\n");
1353             goto all_done;
1354          }
1355          if (stat == -1) {
1356             Pmsg0(-1, "\n\nThat appears *NOT* to have corrected the problem.\n");
1357             goto failed;
1358          }
1359          /* Wrong count after append */
1360          if (stat == -2) {
1361             Pmsg0(-1, "\n\nIt looks like the append failed. Attempting again.\n"
1362                      "Setting \"BSF at EOM = yes\" and retrying append test.\n");
1363             dev->capabilities |= CAP_BSFATEOM; /* backspace on eom */
1364             stat = append_test();
1365             if (stat == 1) {
1366                Pmsg0(-1, "\n\nIt looks like the test worked this time, please add:\n\n"
1367                      "    Hardware End of Medium = No\n"
1368                      "    Fast Forward Space File = No\n"
1369                      "    BSF at EOM = yes\n\n"
1370                      "to your Device resource in the Storage conf file.\n");
1371                goto all_done;
1372             }
1373          }
1374
1375       }
1376 failed:
1377       Pmsg0(-1, "\nAppend test failed.\n\n");
1378       Pmsg0(-1, "\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n"
1379             "Unable to correct the problem. You MUST fix this\n"
1380              "problem before Bacula can use your tape drive correctly\n");
1381       Pmsg0(-1, "\nPerhaps running Bacula in fixed block mode will work.\n"
1382             "Do so by setting:\n\n"
1383             "Minimum Block Size = nnn\n"
1384             "Maximum Block Size = nnn\n\n"
1385             "in your Storage daemon's Device definition.\n"
1386             "nnn must match your tape driver's block size, which\n"
1387             "can be determined by reading your tape manufacturers\n"
1388             "information, and the information on your kernel dirver.\n"
1389             "Fixed block sizes, however, are not normally an ideal solution.\n");
1390        return;
1391    }
1392
1393 all_done:
1394    Pmsg0(-1, _("\nThe above Bacula scan should have output identical to what follows.\n"
1395         "Please double check it ...\n"
1396         "=== Sample correct output ===\n"
1397         "1 block of 64448 bytes in file 1\n"
1398         "End of File mark.\n"
1399         "2 blocks of 64448 bytes in file 2\n"
1400         "End of File mark.\n"
1401         "3 blocks of 64448 bytes in file 3\n"
1402         "End of File mark.\n"
1403         "1 block of 64448 bytes in file 4\n" 
1404         "End of File mark.\n"
1405         "Total files=4, blocks=7, bytes = 451,136\n"
1406         "=== End sample correct output ===\n\n"));
1407
1408    Pmsg0(-1, _("If the above scan output is not identical to the\n"
1409                "sample output, you MUST correct the problem\n"
1410                "or Bacula will not be able to write multiple Jobs to \n"
1411                "the tape.\n\n"));
1412
1413    if (stat == 1) {
1414       re_read_block_test();
1415    }
1416
1417    fsf_test();                        /* do fast forward space file test */
1418
1419    autochanger_test();                /* do autochanger test */
1420    
1421 }
1422
1423 /* Forward space a file */
1424 static void fsfcmd()
1425 {
1426    int num = 1;
1427    if (argc > 1) {
1428       num = atoi(argk[1]);
1429    }
1430    if (num <= 0) {
1431       num = 1;
1432    }
1433    if (!fsf_dev(dev, num)) {
1434       Pmsg1(0, "Bad status from fsf. ERR=%s\n", strerror_dev(dev));
1435       return;
1436    }
1437    Pmsg2(0, "Forward spaced %d file%s.\n", num, num==1?"":"s");
1438 }
1439
1440 /* Forward space a record */
1441 static void fsrcmd()
1442 {
1443    int num = 1;
1444    if (argc > 1) {
1445       num = atoi(argk[1]);
1446    }
1447    if (num <= 0) {
1448       num = 1;
1449    }
1450    if (!fsr_dev(dev, num)) {
1451       Pmsg1(0, "Bad status from fsr. ERR=%s\n", strerror_dev(dev));
1452       return;
1453    }
1454    Pmsg2(0, "Forward spaced %d record%s.\n", num, num==1?"":"s");
1455 }
1456
1457
1458 /*
1459  * Write a Bacula block to the tape
1460  */
1461 static void wrcmd()
1462 {
1463    DEV_BLOCK *block = dcr->block;
1464    DEV_RECORD *rec = dcr->rec;
1465    int i;
1466
1467    sm_check(__FILE__, __LINE__, false);
1468    empty_block(block);
1469    if (verbose > 1) {
1470       dump_block(block, "test");
1471    }
1472
1473    i = block->buf_len - 100;
1474    ASSERT (i > 0);
1475    rec->data = check_pool_memory_size(rec->data, i);
1476    memset(rec->data, i & 0xFF, i);
1477    rec->data_len = i;
1478    sm_check(__FILE__, __LINE__, false);
1479    if (!write_record_to_block(block, rec)) {
1480       Pmsg0(0, _("Error writing record to block.\n")); 
1481       goto bail_out;
1482    }
1483    if (!write_block_to_dev(dcr)) {
1484       Pmsg0(0, _("Error writing block to device.\n")); 
1485       goto bail_out;
1486    } else {
1487       Pmsg1(0, _("Wrote one record of %d bytes.\n"), i);
1488    }
1489    Pmsg0(0, _("Wrote block to device.\n"));
1490
1491 bail_out:
1492    sm_check(__FILE__, __LINE__, false);
1493    sm_check(__FILE__, __LINE__, false);
1494 }
1495
1496 /* 
1497  * Read a record from the tape
1498  */
1499 static void rrcmd()
1500 {
1501    char *buf;
1502    int stat, len;
1503
1504    if (!get_cmd("Enter length to read: ")) {
1505       return;
1506    }
1507    len = atoi(cmd);
1508    if (len < 0 || len > 1000000) {
1509       Pmsg0(0, _("Bad length entered, using default of 1024 bytes.\n"));
1510       len = 1024;
1511    }
1512    buf = (char *)malloc(len);
1513    stat = read(dev->fd, buf, len);
1514    if (stat > 0 && stat <= len) {
1515       errno = 0;
1516    }
1517    Pmsg3(0, _("Read of %d bytes gives stat=%d. ERR=%s\n"),
1518       len, stat, strerror(errno));
1519    free(buf);
1520 }
1521
1522
1523 /*
1524  * Scan tape by reading block by block. Report what is
1525  * on the tape.  Note, this command does raw reads, and as such
1526  * will not work with fixed block size devices.
1527  */
1528 static void scancmd()
1529 {
1530    int stat;
1531    int blocks, tot_blocks, tot_files;
1532    int block_size;
1533    uint64_t bytes;
1534    char ec1[50];
1535
1536
1537    blocks = block_size = tot_blocks = 0;
1538    bytes = 0;
1539    if (dev->state & ST_EOT) {
1540       Pmsg0(0, "End of tape\n");
1541       return; 
1542    }
1543    update_pos_dev(dev);
1544    tot_files = dev->file;
1545    Pmsg1(0, _("Starting scan at file %u\n"), dev->file);
1546    for (;;) {
1547       if ((stat = read(dev->fd, buf, sizeof(buf))) < 0) {
1548          clrerror_dev(dev, -1);
1549          Mmsg2(dev->errmsg, "read error on %s. ERR=%s.\n",
1550             dev->dev_name, strerror(dev->dev_errno));
1551          Pmsg2(0, "Bad status from read %d. ERR=%s\n", stat, strerror_dev(dev));
1552          if (blocks > 0)
1553             printf("%d block%s of %d bytes in file %d\n",        
1554                     blocks, blocks>1?"s":"", block_size, dev->file);
1555          return;
1556       }
1557       Dmsg1(200, "read status = %d\n", stat);
1558 /*    sleep(1); */
1559       if (stat != block_size) {
1560          update_pos_dev(dev);
1561          if (blocks > 0) {
1562             printf("%d block%s of %d bytes in file %d\n", 
1563                  blocks, blocks>1?"s":"", block_size, dev->file);
1564             blocks = 0;
1565          }
1566          block_size = stat;
1567       }
1568       if (stat == 0) {                /* EOF */
1569          update_pos_dev(dev);
1570          printf("End of File mark.\n");
1571          /* Two reads of zero means end of tape */
1572          if (dev->state & ST_EOF)
1573             dev->state |= ST_EOT;
1574          else {
1575             dev->state |= ST_EOF;
1576             dev->file++;
1577          }
1578          if (dev->state & ST_EOT) {
1579             printf("End of tape\n");
1580             break;
1581          }
1582       } else {                        /* Got data */
1583          dev->state &= ~ST_EOF;
1584          blocks++;
1585          tot_blocks++;
1586          bytes += stat;
1587       }
1588    }
1589    update_pos_dev(dev);
1590    tot_files = dev->file - tot_files;
1591    printf("Total files=%d, blocks=%d, bytes = %s\n", tot_files, tot_blocks, 
1592       edit_uint64_with_commas(bytes, ec1));
1593 }
1594
1595
1596 /*
1597  * Scan tape by reading Bacula block by block. Report what is
1598  * on the tape.  This function reads Bacula blocks, so if your
1599  * Device resource is correctly defined, it should work with
1600  * either variable or fixed block sizes.
1601  */
1602 static void scan_blocks()
1603 {
1604    int blocks, tot_blocks, tot_files;
1605    uint32_t block_size;
1606    uint64_t bytes;
1607    DEV_BLOCK *block = dcr->block;
1608    char ec1[50];
1609
1610    blocks = block_size = tot_blocks = 0;
1611    bytes = 0;
1612
1613    empty_block(block);
1614    update_pos_dev(dev);
1615    tot_files = dev->file;
1616    for (;;) {
1617       if (!read_block_from_device(dcr, NO_BLOCK_NUMBER_CHECK)) {
1618          Dmsg1(100, "!read_block(): ERR=%s\n", strerror_dev(dev));
1619          if (dev->state & ST_EOT) {
1620             if (blocks > 0) {
1621                printf("%d block%s of %d bytes in file %d\n", 
1622                     blocks, blocks>1?"s":"", block_size, dev->file);
1623                blocks = 0;
1624             }
1625             goto bail_out;
1626          }
1627          if (dev->state & ST_EOF) {
1628             if (blocks > 0) {
1629                printf("%d block%s of %d bytes in file %d\n",        
1630                        blocks, blocks>1?"s":"", block_size, dev->file);
1631                blocks = 0;
1632             }
1633             printf(_("End of File mark.\n"));
1634             continue;
1635          }
1636          if (dev->state & ST_SHORT) {
1637             if (blocks > 0) {
1638                printf("%d block%s of %d bytes in file %d\n",        
1639                        blocks, blocks>1?"s":"", block_size, dev->file);
1640                blocks = 0;
1641             }
1642             printf(_("Short block read.\n"));
1643             continue;
1644          }
1645          printf(_("Error reading block. ERR=%s\n"), strerror_dev(dev));
1646          goto bail_out;
1647       }
1648       if (block->block_len != block_size) {
1649          if (blocks > 0) {
1650             printf("%d block%s of %d bytes in file %d\n",        
1651                     blocks, blocks>1?"s":"", block_size, dev->file);
1652             blocks = 0;
1653          }
1654          block_size = block->block_len;
1655       }
1656       blocks++;
1657       tot_blocks++;
1658       bytes += block->block_len;
1659       Dmsg6(100, "Blk_blk=%u dev_blk=%u blen=%u bVer=%d SessId=%u SessTim=%u\n",
1660          block->BlockNumber, dev->block_num, block->block_len, block->BlockVer,
1661          block->VolSessionId, block->VolSessionTime);
1662       if (verbose == 1) {
1663          DEV_RECORD *rec = new_record();
1664          read_record_from_block(block, rec);
1665          Pmsg8(-1, "Blk_block: %u dev_blk=%u blen=%u First rec FI=%s SessId=%u SessTim=%u Strm=%s rlen=%d\n",
1666               block->BlockNumber, dev->block_num, block->block_len,
1667               FI_to_ascii(rec->FileIndex), rec->VolSessionId, rec->VolSessionTime,
1668               stream_to_ascii(rec->Stream, rec->FileIndex), rec->data_len);
1669          rec->remainder = 0;
1670          free_record(rec);
1671       } else if (verbose > 1) {
1672          dump_block(block, "");
1673       }
1674
1675    }
1676 bail_out:
1677    tot_files = dev->file - tot_files;
1678    printf("Total files=%d, blocks=%d, bytes = %s\n", tot_files, tot_blocks, 
1679       edit_uint64_with_commas(bytes, ec1));
1680 }
1681
1682
1683 static void statcmd()
1684 {
1685    int debug = debug_level;
1686    debug_level = 30;
1687    Pmsg2(0, "Device status: %u. ERR=%s\n", status_dev(dev), strerror_dev(dev));
1688 #ifdef xxxx
1689    dump_volume_label(dev);
1690 #endif
1691    debug_level = debug;
1692 }
1693
1694
1695 /* 
1696  * First we label the tape, then we fill
1697  *  it with data get a new tape and write a few blocks.
1698  */                            
1699 static void fillcmd()
1700 {
1701    DEV_RECORD rec;
1702    DEV_BLOCK  *block = dcr->block;
1703    char ec1[50];
1704    int fd;
1705    uint32_t i;
1706    uint32_t min_block_size;
1707
1708    ok = true;
1709    stop = 0;
1710    vol_num = 0;
1711    last_file = 0;
1712    last_block_num = 0;
1713    BlockNumber = 0;
1714
1715    Pmsg0(-1, "\n\
1716 This command simulates Bacula writing to a tape.\n\
1717 It requires either one or two blank tapes, which it\n\
1718 will label and write.\n\n\
1719 If you have an autochanger configured, it will use\n\
1720 the tapes that are in slots 1 and 2, otherwise, you will\n\
1721 be prompted to insert the tapes when necessary.\n\n\
1722 It will print a status approximately\n\
1723 every 322 MB, and write an EOF every 3.2 GB.  If you have\n\
1724 selected the simple test option, after writing the first tape\n\
1725 it will rewind it and re-read the last block written.\n\n\
1726 If you have selected the multiple tape test, when the first tape\n\
1727 fills, it will ask for a second, and after writing a few more \n\
1728 blocks, it will stop.  Then it will begin re-reading the\n\
1729 two tapes.\n\n\
1730 This may take a long time -- hours! ...\n\n");
1731
1732    get_cmd("Do you want to run the simplified test (s) with one tape\n"
1733            "or the complete multiple tape (m) test: (s/m) ");
1734    if (cmd[0] == 's') {
1735       Pmsg0(-1, "Simple test (single tape) selected.\n");
1736       simple = true;
1737    } else if (cmd[0] == 'm') {
1738       Pmsg0(-1, "Multiple tape test selected.\n"); 
1739       simple = false;
1740    } else {
1741       Pmsg0(000, "Command aborted.\n");
1742       return;
1743    }
1744
1745    Dmsg1(20, "Begin append device=%s\n", dev_name(dev));
1746    Dmsg1(20, "MaxVolSize=%s\n", edit_uint64(dev->max_volume_size, ec1));
1747
1748    /* Use fixed block size to simplify read back */
1749    min_block_size = dev->min_block_size;
1750    dev->min_block_size = dev->max_block_size;
1751    set_volume_name("TestVolume1", 1);
1752
1753    /* 
1754     * Acquire output device for writing.  Note, after acquiring a
1755     *   device, we MUST release it, which is done at the end of this
1756     *   subroutine.
1757     */
1758    Dmsg0(100, "just before acquire_device\n");
1759    if (!acquire_device_for_append(jcr)) {
1760       set_jcr_job_status(jcr, JS_ErrorTerminated);
1761       return;
1762    }
1763    block = jcr->dcr->block;
1764
1765    Dmsg0(100, "Just after acquire_device_for_append\n");
1766    /*
1767     * Write Begin Session Record
1768     */
1769    if (!write_session_label(dcr, SOS_LABEL)) {
1770       set_jcr_job_status(jcr, JS_ErrorTerminated);
1771       Jmsg1(jcr, M_FATAL, 0, _("Write session label failed. ERR=%s\n"),
1772          strerror_dev(dev));
1773       ok = false;
1774    }
1775    Pmsg0(-1, "Wrote Start Of Session label.\n");
1776
1777    memset(&rec, 0, sizeof(rec));
1778    rec.data = get_memory(100000);     /* max record size */
1779
1780 #define REC_SIZE 32768
1781    rec.data_len = REC_SIZE;
1782
1783    /* 
1784     * Put some random data in the record
1785     */
1786    fd = open("/dev/urandom", O_RDONLY);
1787    if (fd) {
1788       read(fd, rec.data, rec.data_len);
1789       close(fd);
1790    } else {
1791       uint32_t *p = (uint32_t *)rec.data;
1792       srandom(time(NULL));
1793       for (i=0; i<rec.data_len/sizeof(uint32_t); i++) {
1794          p[i] = random();
1795       }
1796    }
1797
1798    /* 
1799     * Generate data as if from File daemon, write to device   
1800     */
1801    jcr->dcr->VolFirstIndex = 0;
1802    time(&jcr->run_time);              /* start counting time for rates */
1803    if (simple) {
1804       Pmsg0(-1, "Begin writing Bacula records to tape ...\n");
1805    } else {
1806       Pmsg0(-1, "Begin writing Bacula records to first tape ...\n");
1807    }
1808    for (file_index = 0; ok && !job_canceled(jcr); ) {
1809       rec.VolSessionId = jcr->VolSessionId;
1810       rec.VolSessionTime = jcr->VolSessionTime;
1811       rec.FileIndex = ++file_index;
1812       rec.Stream = STREAM_FILE_DATA;
1813
1814       /* Mix up the data just a bit */
1815       uint32_t *lp = (uint32_t *)rec.data;
1816       lp[0] += lp[13];
1817       for (i=1; i < (rec.data_len-sizeof(uint32_t))/sizeof(uint32_t)-1; i++) {
1818          lp[i] += lp[i-1];
1819       }
1820
1821       Dmsg4(250, "before write_rec FI=%d SessId=%d Strm=%s len=%d\n",
1822          rec.FileIndex, rec.VolSessionId, stream_to_ascii(rec.Stream, rec.FileIndex), 
1823          rec.data_len);
1824        
1825       while (!write_record_to_block(block, &rec)) {
1826          /*
1827           * When we get here we have just filled a block
1828           */
1829          Dmsg2(150, "!write_record_to_block data_len=%d rem=%d\n", rec.data_len,
1830                     rec.remainder);
1831
1832          /* Write block to tape */
1833          if (!flush_block(block, 1)) {
1834             break;
1835          }
1836
1837          /* Every 5000 blocks (approx 322MB) report where we are.
1838           */
1839          if ((block->BlockNumber % 5000) == 0) {
1840             now = time(NULL);
1841             now -= jcr->run_time;
1842             if (now <= 0) {
1843                now = 1;          /* prevent divide error */
1844             }
1845             kbs = (double)dev->VolCatInfo.VolCatBytes / (1000.0 * (double)now);
1846             Pmsg4(-1, "Wrote blk_block=%u, dev_blk_num=%u VolBytes=%s rate=%.1f KB/s\n", 
1847                block->BlockNumber, dev->block_num,
1848                edit_uint64_with_commas(dev->VolCatInfo.VolCatBytes, ec1), (float)kbs);
1849          }
1850          /* Every 15000 blocks (approx 1GB) write an EOF.
1851           */
1852          if ((block->BlockNumber % 15000) == 0) {
1853             Pmsg0(-1, "Flush block, write EOF\n");
1854             flush_block(block, 0);
1855             weof_dev(dev, 1);
1856          }
1857
1858          /* Get out after writing 10 blocks to the second tape */
1859          if (++BlockNumber > 10 && stop != 0) {      /* get out */
1860             break;    
1861          }
1862       }
1863       if (!ok) {
1864          Pmsg0(000, _("Not OK\n"));
1865          break;
1866       }
1867       jcr->JobBytes += rec.data_len;   /* increment bytes this job */
1868       Dmsg4(190, "write_record FI=%s SessId=%d Strm=%s len=%d\n",
1869          FI_to_ascii(rec.FileIndex), rec.VolSessionId, 
1870          stream_to_ascii(rec.Stream, rec.FileIndex), rec.data_len);
1871
1872       /* Get out after writing 10 blocks to the second tape */
1873       if (BlockNumber > 10 && stop != 0) {      /* get out */
1874          Pmsg0(-1, "Done writing ...\n");
1875          break;    
1876       }
1877    }
1878    if (vol_num > 1) {
1879       Dmsg0(100, "Write_end_session_label()\n");
1880       /* Create Job status for end of session label */
1881       if (!job_canceled(jcr) && ok) {
1882          set_jcr_job_status(jcr, JS_Terminated);
1883       } else if (!ok) {
1884          set_jcr_job_status(jcr, JS_ErrorTerminated);
1885       }
1886       if (!write_session_label(dcr, EOS_LABEL)) {
1887          Pmsg1(000, _("Error writting end session label. ERR=%s\n"), strerror_dev(dev));
1888          ok = false;
1889       }
1890       /* Write out final block of this session */
1891       if (!write_block_to_device(dcr)) {
1892          Pmsg0(-1, _("Set ok=false after write_block_to_device.\n"));
1893          ok = false;
1894       }
1895       Pmsg0(-1, _("Wrote End Of Session label.\n"));
1896
1897       /* Save last block info for second tape */
1898       last_block_num2 = last_block_num;
1899       last_file2 = last_file;
1900       if (last_block2) {
1901          free_block(last_block2);
1902       }
1903       last_block2 = dup_block(last_block);
1904    }
1905
1906    sprintf(buf, "%s/btape.state", working_directory);
1907    fd = open(buf, O_CREAT|O_TRUNC|O_WRONLY, 0640);
1908    if (fd >= 0) {
1909       write(fd, &btape_state_level, sizeof(btape_state_level));
1910       write(fd, &simple, sizeof(simple));
1911       write(fd, &last_block_num1, sizeof(last_block_num1));
1912       write(fd, &last_block_num2, sizeof(last_block_num2));
1913       write(fd, &last_file1, sizeof(last_file1));
1914       write(fd, &last_file2, sizeof(last_file2));
1915       write(fd, last_block1->buf, last_block1->buf_len);
1916       write(fd, last_block2->buf, last_block2->buf_len);
1917       write(fd, first_block->buf, first_block->buf_len);
1918       close(fd);
1919       Pmsg2(-1, "Wrote state file last_block_num1=%d last_block_num2=%d\n",
1920          last_block_num1, last_block_num2);
1921    } else {
1922       Pmsg2(-1, _("Could not create state file: %s ERR=%s\n"), buf,
1923                  strerror(errno));
1924    }
1925
1926    /* Release the device if multiple tapes being used */
1927    if (!simple && !release_device(jcr)) {
1928       Pmsg0(-1, _("Error in release_device\n"));
1929       ok = false;
1930    }
1931
1932    Pmsg2(-1, _("\n\nDone filling tape%s. Now beginning re-read of %stape ...\n"),
1933       simple?"":"s", simple?"":"first ");
1934
1935    do_unfill();
1936
1937    dev->min_block_size = min_block_size;
1938    free_memory(rec.data);
1939 }
1940
1941 /*
1942  * Read two tapes written by the "fill" command and ensure
1943  *  that the data is valid.  If stop==1 we simulate full read back
1944  *  of two tapes.  If stop==-1 we simply read the last block and
1945  *  verify that it is correct.
1946  */
1947 static void unfillcmd()
1948 {
1949    int fd;
1950
1951    last_block1 = new_block(dev);
1952    last_block2 = new_block(dev);
1953    first_block = new_block(dev);
1954    sprintf(buf, "%s/btape.state", working_directory);
1955    fd = open(buf, O_RDONLY);
1956    if (fd >= 0) {
1957       uint32_t state_level;              
1958       read(fd, &state_level, sizeof(btape_state_level));
1959       read(fd, &simple, sizeof(simple));
1960       read(fd, &last_block_num1, sizeof(last_block_num1));
1961       read(fd, &last_block_num2, sizeof(last_block_num2));
1962       read(fd, &last_file1, sizeof(last_file1));
1963       read(fd, &last_file2, sizeof(last_file2));
1964       read(fd, last_block1->buf, last_block1->buf_len);
1965       read(fd, last_block2->buf, last_block2->buf_len);
1966       read(fd, first_block->buf, first_block->buf_len);
1967       close(fd);
1968       if (state_level != btape_state_level) {
1969           Pmsg0(-1, "\nThe state file level has changed. You must redo\n"
1970                   "the fill command.\n");
1971           return;
1972        }
1973    } else {
1974       Pmsg2(-1, "\nCould not find the state file: %s ERR=%s\n"
1975              "You must redo the fill command.\n", buf, strerror(errno));
1976       return;
1977    }
1978    do_unfill();
1979    this_block = NULL;
1980 }
1981
1982 static void do_unfill()
1983 {
1984    DEV_BLOCK *block = dcr->block;
1985    bool autochanger;
1986
1987    dumped = 0;
1988    VolBytes = 0;
1989    LastBlock = 0;
1990
1991    Dmsg0(20, "Enter do_unfill\n");
1992    dev->capabilities |= CAP_ANONVOLS; /* allow reading any volume */
1993    dev->capabilities &= ~CAP_LABEL;   /* don't label anything here */
1994
1995    end_of_tape = 0;
1996
1997    time(&jcr->run_time);              /* start counting time for rates */
1998    stop = 0;
1999    file_index = 0;
2000    if (last_block) {
2001       free_block(last_block);
2002    }
2003    last_block_num = last_block_num1;
2004    last_file = last_file1;
2005    last_block = last_block1;
2006
2007    if (!simple) {
2008       /* Multiple Volume tape */
2009       /* Close device so user can use autochanger if desired */
2010       if (dev_cap(dev, CAP_OFFLINEUNMOUNT)) {
2011          offline_dev(dev);
2012       }
2013       autochanger = autoload_device(dcr, 1, NULL);
2014       if (!autochanger) {
2015          force_close_dev(dev);
2016          get_cmd(_("Mount first tape. Press enter when ready: ")); 
2017       }
2018       free_vol_list(jcr);
2019       jcr->dcr = new_dcr(jcr, dev);
2020       set_volume_name("TestVolume1", 1);
2021       jcr->bsr = NULL;
2022       create_vol_list(jcr);
2023       close_dev(dev);
2024       dev->state &= ~ST_READ;
2025       if (!acquire_device_for_read(jcr)) {
2026          Pmsg1(-1, "%s", dev->errmsg);
2027          goto bail_out;
2028       }
2029    }
2030    /*
2031     * We now have the first tape mounted.
2032     * Note, re-reading last block may have caused us to 
2033     *   loose track of where we are (block number unknown).
2034     */
2035    rewind_dev(dev);                   /* get to a known place on tape */
2036    /* Read the first 1000 records */
2037    Pmsg0(-1, _("Reading the first 1000 records.\n"));
2038    read_records(dcr, quickie_cb, my_mount_next_read_volume);
2039    Pmsg4(-1, _("Reposition from %u:%u to %u:%u\n"), dev->file, dev->block_num,
2040          last_file, last_block_num);
2041    if (!reposition_dev(dev, last_file, last_block_num)) {
2042       Pmsg1(-1, "Reposition error. ERR=%s\n", strerror_dev(dev));
2043    }
2044    Pmsg1(-1, _("Reading block %u.\n"), last_block_num);
2045    if (!read_block_from_device(dcr, NO_BLOCK_NUMBER_CHECK)) {
2046       Pmsg1(-1, _("Error reading block: ERR=%s\n"), strerror_dev(dev));
2047       goto bail_out;
2048    }
2049    if (compare_blocks(last_block, block)) {
2050       if (simple) {
2051          Pmsg0(-1, _("\nThe last block on the tape matches. Test succeeded.\n\n"));
2052       } else {
2053          Pmsg0(-1, _("\nThe last block of the first tape matches.\n\n"));
2054       }
2055    }
2056    if (simple) {
2057       goto bail_out;
2058    }
2059
2060    /* restore info for last block on second Volume */
2061    last_block_num = last_block_num2;
2062    last_file = last_file2;
2063    last_block = last_block2;
2064
2065    /* Multiple Volume tape */
2066    /* Close device so user can use autochanger if desired */
2067    if (dev_cap(dev, CAP_OFFLINEUNMOUNT)) {
2068       offline_dev(dev);
2069    }
2070
2071    free_vol_list(jcr);
2072    set_volume_name("TestVolume2", 2);
2073    jcr->bsr = NULL;
2074    create_vol_list(jcr);
2075    autochanger = autoload_device(dcr, 1, NULL);
2076    if (!autochanger) {
2077       force_close_dev(dev);
2078       get_cmd(_("Mount second tape. Press enter when ready: ")); 
2079    }
2080
2081    dev->state &= ~ST_READ;
2082    if (!acquire_device_for_read(jcr)) {
2083       Pmsg1(-1, "%s", dev->errmsg);
2084       goto bail_out;
2085    }
2086
2087    /* Space to "first" block which is last block not written
2088     * on the previous tape.
2089     */
2090    Pmsg2(-1, _("Reposition from %u:%u to 0:1\n"), dev->file, dev->block_num);
2091    if (!reposition_dev(dev, 0, 1)) {
2092       Pmsg1(-1, "Reposition error. ERR=%s\n", strerror_dev(dev));
2093       goto bail_out;
2094    }
2095    Pmsg1(-1, _("Reading block %d.\n"), dev->block_num);
2096    if (!read_block_from_device(dcr, NO_BLOCK_NUMBER_CHECK)) {
2097       Pmsg1(-1, _("Error reading block: ERR=%s\n"), strerror_dev(dev));
2098       goto bail_out;
2099    }
2100    if (compare_blocks(first_block, block)) {
2101       Pmsg0(-1, _("\nThe first block on the second tape matches.\n\n"));
2102    }
2103
2104    /* Now find and compare the last block */
2105    Pmsg4(-1, _("Reposition from %u:%u to %u:%u\n"), dev->file, dev->block_num,
2106          last_file, last_block_num);
2107    if (!reposition_dev(dev, last_file, last_block_num)) {
2108       Pmsg1(-1, "Reposition error. ERR=%s\n", strerror_dev(dev));
2109       goto bail_out;
2110    }
2111    Pmsg1(-1, _("Reading block %d.\n"), dev->block_num);
2112    if (!read_block_from_device(dcr, NO_BLOCK_NUMBER_CHECK)) {
2113       Pmsg1(-1, _("Error reading block: ERR=%s\n"), strerror_dev(dev));
2114       goto bail_out;
2115    }
2116    if (compare_blocks(last_block, block)) {
2117       Pmsg0(-1, _("\nThe last block on the second tape matches. Test succeeded.\n\n"));
2118    }
2119
2120 bail_out:
2121    free_block(last_block1);
2122    free_block(last_block2);
2123    free_block(first_block);
2124 }
2125
2126 /* Read 1000 records then stop */
2127 static bool quickie_cb(DCR *dcr, DEV_RECORD *rec)
2128 {
2129    quickie_count++;
2130    return quickie_count <= 1000;
2131 }
2132
2133 static bool compare_blocks(DEV_BLOCK *last_block, DEV_BLOCK *block) 
2134 {
2135    char *p, *q;
2136    uint32_t CheckSum, block_len;
2137    ser_declare;
2138
2139    p = last_block->buf;      
2140    q = block->buf;
2141    unser_begin(q, BLKHDR2_LENGTH);
2142    unser_uint32(CheckSum);
2143    unser_uint32(block_len);
2144    while (q < (block->buf+block_len)) {
2145       if (*p == *q) {
2146          p++;
2147          q++;
2148          continue;
2149       }
2150       Pmsg0(-1, "\n");
2151       dump_block(last_block, _("Last block written"));
2152       Pmsg0(-1, "\n");
2153       dump_block(block, _("Block read back"));
2154       Pmsg1(-1, "\n\nThe blocks differ at byte %u\n", p - last_block->buf);
2155       Pmsg0(-1, "\n\n!!!! The last block written and the block\n"
2156                 "that was read back differ. The test FAILED !!!!\n"
2157                 "This must be corrected before you use Bacula\n"
2158                 "to write multi-tape Volumes.!!!!\n");
2159       return false;
2160    }
2161    if (verbose) {
2162       dump_block(last_block, _("Last block written"));
2163       dump_block(block, _("Block read back"));
2164    }
2165    return true;
2166 }
2167
2168
2169
2170
2171
2172 /*
2173  * Write current block to tape regardless of whether or
2174  *   not it is full. If the tape fills, attempt to
2175  *   acquire another tape.
2176  */
2177 static int flush_block(DEV_BLOCK *block, int dump)
2178 {
2179    char ec1[50];
2180    lock_device(dev);
2181    DEV_BLOCK *tblock;
2182    uint32_t this_file, this_block_num;
2183
2184    if (!this_block) {
2185       this_block = new_block(dev);
2186    }
2187    if (!last_block) {
2188       last_block = new_block(dev);
2189    }
2190    /* Copy block */
2191    this_file = dev->file;
2192    this_block_num = dev->block_num;
2193    if (!write_block_to_dev(dcr)) {
2194       Pmsg3(000, "Last block at: %u:%u this_dev_block_num=%d\n", 
2195                   last_file, last_block_num, this_block_num);
2196       if (vol_num == 1) {
2197          /* 
2198           * This is 1st tape, so save first tape info separate
2199           *  from second tape info 
2200           */
2201          last_block_num1 = last_block_num;
2202          last_file1 = last_file;
2203          last_block1 = dup_block(last_block);
2204          last_block2 = dup_block(last_block);
2205          first_block = dup_block(block); /* first block second tape */
2206       }
2207       if (verbose) {
2208          Pmsg3(000, "Block not written: FileIndex=%u blk_block=%u Size=%u\n", 
2209             (unsigned)file_index, block->BlockNumber, block->block_len);
2210          dump_block(last_block, "Last block written");
2211          Pmsg0(-1, "\n");
2212          dump_block(block, "Block not written");
2213       }
2214       if (stop == 0) {
2215          eot_block = block->BlockNumber;
2216          eot_block_len = block->block_len;
2217          eot_FileIndex = file_index;
2218          stop = 1;
2219       }
2220       now = time(NULL);
2221       now -= jcr->run_time;
2222       if (now <= 0) {
2223          now = 1;                     /* don't divide by zero */
2224       }
2225       kbs = (double)dev->VolCatInfo.VolCatBytes / (1000 * now);
2226       vol_size = dev->VolCatInfo.VolCatBytes;
2227       Pmsg2(000, "End of tape. VolumeCapacity=%s. Write rate = %.1f KB/s\n", 
2228          edit_uint64_with_commas(dev->VolCatInfo.VolCatBytes, ec1), kbs);
2229
2230       if (simple) {
2231          stop = -1;                   /* stop, but do simplified test */
2232       } else {
2233          /* Full test in progress */
2234          if (!fixup_device_block_write_error(jcr->dcr)) {
2235             Pmsg1(000, _("Cannot fixup device error. %s\n"), strerror_dev(dev));
2236             ok = false;
2237             unlock_device(dev);
2238             return 0;
2239          }
2240          BlockNumber = 0;             /* start counting for second tape */
2241       }
2242       unlock_device(dev);
2243       return 1;                       /* end of tape reached */
2244    }
2245
2246    /* Save contents after write so that the header is serialized */
2247    memcpy(this_block->buf, block->buf, this_block->buf_len);
2248
2249    /*
2250     * Toggle between two allocated blocks for efficiency.
2251     * Switch blocks so that the block just successfully written is
2252     *  always in last_block. 
2253     */
2254    tblock = last_block;
2255    last_block = this_block; 
2256    this_block = tblock;
2257    last_file = this_file;
2258    last_block_num = this_block_num;
2259
2260    unlock_device(dev);
2261    return 1;
2262 }
2263
2264
2265 /* 
2266  * First we label the tape, then we fill
2267  *  it with data get a new tape and write a few blocks.
2268  */                            
2269 static void qfillcmd()
2270 {
2271    DEV_BLOCK *block = dcr->block;
2272    DEV_RECORD *rec = dcr->rec;
2273    int i, count;
2274
2275    Pmsg0(0, "Test writing blocks of 64512 bytes to tape.\n");
2276
2277    get_cmd("How many blocks do you want to write? (1000): ");
2278
2279    count = atoi(cmd);
2280    if (count <= 0) {
2281       count = 1000;
2282    }
2283
2284    sm_check(__FILE__, __LINE__, false);
2285
2286    i = block->buf_len - 100;
2287    ASSERT (i > 0);
2288    rec->data = check_pool_memory_size(rec->data, i);
2289    memset(rec->data, i & 0xFF, i);
2290    rec->data_len = i;
2291    rewindcmd();
2292    Pmsg1(0, "Begin writing %d Bacula blocks to tape ...\n", count);
2293    for (i=0; i < count; i++) {
2294       if (i % 100 == 0) {
2295          printf("+");
2296          fflush(stdout);
2297       }
2298       if (!write_record_to_block(block, rec)) {
2299          Pmsg0(0, _("Error writing record to block.\n")); 
2300          goto bail_out;
2301       }
2302       if (!write_block_to_dev(dcr)) {
2303          Pmsg0(0, _("Error writing block to device.\n")); 
2304          goto bail_out;
2305       }
2306    }
2307    printf("\n");
2308    weofcmd();
2309    if (dev_cap(dev, CAP_TWOEOF)) {
2310       weofcmd();
2311    }
2312    rewindcmd();
2313    scan_blocks();
2314
2315 bail_out:
2316    sm_check(__FILE__, __LINE__, false);
2317 }
2318
2319 /*
2320  * Fill a tape using raw write() command
2321  */
2322 static void rawfill_cmd()
2323 {
2324    DEV_BLOCK *block = dcr->block;
2325    int stat;
2326    int fd;
2327    uint32_t block_num = 0;
2328    uint32_t *p;
2329    int my_errno;
2330    uint32_t i;
2331
2332    fd = open("/dev/urandom", O_RDONLY);
2333    if (fd) {
2334       read(fd, block->buf, block->buf_len);
2335       close(fd);
2336    } else {
2337       uint32_t *p = (uint32_t *)block->buf;
2338       srandom(time(NULL));
2339       for (i=0; i<block->buf_len/sizeof(uint32_t); i++) {
2340          p[i] = random();
2341       }
2342    }
2343    p = (uint32_t *)block->buf;
2344    Pmsg1(0, "Begin writing raw blocks of %u bytes.\n", block->buf_len);
2345    for ( ;; ) {
2346       *p = block_num;
2347       stat = write(dev->fd, block->buf, block->buf_len);
2348       if (stat == (int)block->buf_len) {
2349          if ((block_num++ % 100) == 0) {
2350             printf("+");
2351             fflush(stdout);
2352          }
2353          p[0] += p[13];
2354          for (i=1; i<(block->buf_len-sizeof(uint32_t))/sizeof(uint32_t)-1; i++) {
2355             p[i] += p[i-1];
2356          }
2357          continue;
2358       }
2359       break;
2360    }
2361    my_errno = errno;
2362    printf("\n");
2363    printf("Write failed at block %u. stat=%d ERR=%s\n", block_num, stat,
2364       strerror(my_errno));
2365    weofcmd();
2366 }
2367
2368
2369 /*
2370  * Fill a tape using raw write() command
2371  */
2372 static void bfill_cmd()
2373 {
2374    DEV_BLOCK *block = dcr->block;
2375    uint32_t block_num = 0;
2376    uint32_t *p;
2377    int my_errno;
2378    int fd;   
2379    uint32_t i;
2380
2381    fd = open("/dev/urandom", O_RDONLY);
2382    if (fd) {
2383       read(fd, block->buf, block->buf_len);
2384       close(fd);
2385    } else {
2386       uint32_t *p = (uint32_t *)block->buf;
2387       srandom(time(NULL));
2388       for (i=0; i<block->buf_len/sizeof(uint32_t); i++) {
2389          p[i] = random();
2390       }
2391    }
2392    p = (uint32_t *)block->buf;
2393    Pmsg1(0, "Begin writing Bacula blocks of %u bytes.\n", block->buf_len);
2394    for ( ;; ) {
2395       *p = block_num;
2396       block->binbuf = block->buf_len;
2397       block->bufp = block->buf + block->binbuf;
2398       if (!write_block_to_dev(dcr)) {
2399          break;
2400       }
2401       if ((block_num++ % 100) == 0) {
2402          printf("+");
2403          fflush(stdout);
2404       }
2405       p[0] += p[13];
2406       for (i=1; i<(block->buf_len/sizeof(uint32_t)-1); i++) {
2407          p[i] += p[i-1];
2408       }
2409    }
2410    my_errno = errno;
2411    printf("\n");
2412    printf("Write failed at block %u.\n", block_num);     
2413    weofcmd();
2414 }
2415
2416
2417 struct cmdstruct { const char *key; void (*func)(); const char *help; }; 
2418 static struct cmdstruct commands[] = {
2419  {"autochanger", autochangercmd, "test autochanger"},
2420  {"bsf",        bsfcmd,       "backspace file"},
2421  {"bsr",        bsrcmd,       "backspace record"},
2422  {"bfill",      bfill_cmd,    "fill tape using Bacula writes"},
2423  {"cap",        capcmd,       "list device capabilities"},
2424  {"clear",      clearcmd,     "clear tape errors"},
2425  {"eod",        eodcmd,       "go to end of Bacula data for append"},
2426  {"eom",        eomcmd,       "go to the physical end of medium"},
2427  {"fill",       fillcmd,      "fill tape, write onto second volume"},
2428  {"unfill",     unfillcmd,    "read filled tape"},
2429  {"fsf",        fsfcmd,       "forward space a file"},
2430  {"fsr",        fsrcmd,       "forward space a record"},
2431  {"help",       helpcmd,      "print this command"},
2432  {"label",      labelcmd,     "write a Bacula label to the tape"},
2433  {"load",       loadcmd,      "load a tape"},
2434  {"quit",       quitcmd,      "quit btape"},   
2435  {"rawfill",    rawfill_cmd,  "use write() to fill tape"},
2436  {"readlabel",  readlabelcmd, "read and print the Bacula tape label"},
2437  {"rectest",    rectestcmd,   "test record handling functions"},
2438  {"rewind",     rewindcmd,    "rewind the tape"},
2439  {"scan",       scancmd,      "read() tape block by block to EOT and report"}, 
2440  {"scanblocks", scan_blocks,  "Bacula read block by block to EOT and report"},
2441  {"status",     statcmd,      "print tape status"},
2442  {"test",       testcmd,      "General test Bacula tape functions"},
2443  {"weof",       weofcmd,      "write an EOF on the tape"},
2444  {"wr",         wrcmd,        "write a single Bacula block"}, 
2445  {"rr",         rrcmd,        "read a single record"},
2446  {"qfill",      qfillcmd,     "quick fill command"},
2447              };
2448 #define comsize (sizeof(commands)/sizeof(struct cmdstruct))
2449
2450 static void
2451 do_tape_cmds()
2452 {
2453    unsigned int i;
2454    bool found;
2455
2456    while (get_cmd("*")) {
2457       sm_check(__FILE__, __LINE__, false);
2458       found = false;
2459       parse_args(cmd, &args, &argc, argk, argv, MAX_CMD_ARGS);
2460       for (i=0; i<comsize; i++)       /* search for command */
2461          if (argc > 0 && fstrsch(argk[0],  commands[i].key)) {
2462             (*commands[i].func)();    /* go execute command */
2463             found = true;
2464             break;
2465          }
2466       if (!found)
2467          Pmsg1(0, _("%s is an illegal command\n"), cmd);
2468       if (quit)
2469          break;
2470    }
2471 }
2472
2473 static void helpcmd()
2474 {
2475    unsigned int i;
2476    usage();
2477    printf(_("Interactive commands:\n"));
2478    printf(_("  Command    Description\n  =======    ===========\n"));
2479    for (i=0; i<comsize; i++)
2480       printf("  %-10s %s\n", commands[i].key, commands[i].help);
2481    printf("\n");
2482 }
2483
2484 static void usage()
2485 {
2486    fprintf(stderr, _(
2487 "Copyright (C) 2000-2004 Kern Sibbald and John Walker.\n"
2488 "\nVersion: " VERSION " (" BDATE ")\n\n"
2489 "Usage: btape <options> <device_name>\n"
2490 "       -b <file>   specify bootstrap file\n"
2491 "       -c <file>   set configuration file to file\n"
2492 "       -d <nn>     set debug level to nn\n"
2493 "       -p          proceed inspite of I/O errors\n"
2494 "       -s          turn off signals\n"
2495 "       -v          be verbose\n"
2496 "       -?          print this message.\n"  
2497 "\n"));
2498
2499 }
2500
2501 /*      
2502  * Get next input command from terminal.  This
2503  * routine is REALLY primitive, and should be enhanced
2504  * to have correct backspacing, etc.
2505  */
2506 int 
2507 get_cmd(const char *prompt)
2508 {
2509    int i = 0;
2510    int ch;
2511    fprintf(stdout, prompt);
2512
2513    /* We really should turn off echoing and pretty this
2514     * up a bit.
2515     */
2516    cmd[i] = 0;
2517    while ((ch = fgetc(stdin)) != EOF) { 
2518       if (ch == '\n') {
2519          strip_trailing_junk(cmd);
2520          return 1;
2521       } else if (ch == 4 || ch == 0xd3 || ch == 0x8) {
2522          if (i > 0)
2523             cmd[--i] = 0;
2524          continue;
2525       } 
2526          
2527       cmd[i++] = ch;
2528       cmd[i] = 0;
2529    }
2530    quit = 1;
2531    return 0;
2532 }
2533
2534 /* Dummies to replace askdir.c */
2535 bool    dir_update_file_attributes(DCR *dcr, DEV_RECORD *rec) { return 1;}
2536 bool    dir_send_job_status(JCR *jcr) {return 1;}
2537
2538 bool dir_update_volume_info(DCR *dcr, bool relabel) 
2539
2540    return 1;
2541 }
2542
2543
2544 bool dir_get_volume_info(DCR *dcr, enum get_vol_info_rw  writing)             
2545 {
2546    Dmsg0(20, "Enter dir_get_volume_info\n");
2547    bstrncpy(dcr->VolCatInfo.VolCatName, dcr->VolumeName, sizeof(dcr->VolCatInfo.VolCatName));
2548    return 1;
2549 }
2550
2551 bool dir_create_jobmedia_record(DCR *dcr)
2552 {
2553    dcr->WroteVol = false;
2554    return 1;
2555 }
2556
2557
2558 bool dir_find_next_appendable_volume(DCR *dcr) 
2559
2560    Dmsg1(20, "Enter dir_find_next_appendable_volume. stop=%d\n", stop);
2561    return dcr->VolumeName[0] != 0;
2562 }
2563
2564 bool dir_ask_sysop_to_mount_volume(DCR *dcr)
2565 {
2566    DEVICE *dev = dcr->dev;
2567    Dmsg0(20, "Enter dir_ask_sysop_to_mount_volume\n");
2568    if (dcr->VolumeName[0] == 0) {
2569       return dir_ask_sysop_to_create_appendable_volume(dcr);
2570    }
2571    /* Close device so user can use autochanger if desired */
2572    if (dev_cap(dev, CAP_OFFLINEUNMOUNT)) {
2573       offline_dev(dev);
2574    }
2575    force_close_dev(dev);
2576    Pmsg1(-1, "%s", dev->errmsg);           /* print reason */
2577    if (dcr->VolumeName[0] == 0 || strcmp(dcr->VolumeName, "TestVolume2") == 0) {
2578       fprintf(stderr, "Mount second Volume on device %s and press return when ready: ",
2579          dev_name(dev));
2580    } else {
2581       fprintf(stderr, "Mount Volume \"%s\" on device %s and press return when ready: ",
2582          dcr->VolumeName, dev_name(dev));
2583    }
2584    getchar();   
2585    return true;
2586 }
2587
2588 bool dir_ask_sysop_to_create_appendable_volume(DCR *dcr)
2589 {
2590    bool autochanger;
2591    DEVICE *dev = dcr->dev;
2592    Dmsg0(20, "Enter dir_ask_sysop_to_create_appendable_volume\n");
2593    if (stop == 0) {
2594       set_volume_name("TestVolume1", 1);
2595    } else {
2596       set_volume_name("TestVolume2", 2);
2597    }
2598    /* Close device so user can use autochanger if desired */
2599    if (dev_cap(dev, CAP_OFFLINEUNMOUNT)) {
2600       offline_dev(dev);
2601    }
2602    autochanger = autoload_device(dcr, 1, NULL);
2603    if (!autochanger) {
2604       force_close_dev(dev);
2605       fprintf(stderr, "Mount blank Volume on device %s and press return when ready: ",
2606          dev_name(dev));
2607       getchar();   
2608    }
2609    open_device(dcr);
2610    labelcmd();
2611    VolumeName = NULL;
2612    BlockNumber = 0;
2613    return true;
2614 }
2615
2616 static bool my_mount_next_read_volume(DCR *dcr)
2617 {
2618    char ec1[50];
2619    JCR *jcr = dcr->jcr;
2620    DEV_BLOCK *block = dcr->block;
2621
2622    Dmsg0(20, "Enter my_mount_next_read_volume\n");
2623    Pmsg1(000, "End of Volume \"%s\"\n", dcr->VolumeName);
2624
2625    if (LastBlock != block->BlockNumber) {
2626       VolBytes += block->block_len;
2627    }
2628    LastBlock = block->BlockNumber;
2629    now = time(NULL);
2630    now -= jcr->run_time;
2631    if (now <= 0) {
2632       now = 1;
2633    }
2634    kbs = (double)VolBytes / (1000.0 * (double)now);
2635    Pmsg3(-1, "Read block=%u, VolBytes=%s rate=%.1f KB/s\n", block->BlockNumber,
2636             edit_uint64_with_commas(VolBytes, ec1), (float)kbs);
2637
2638    if (strcmp(dcr->VolumeName, "TestVolume2") == 0) {
2639       end_of_tape = 1;
2640       return false;
2641    }
2642
2643    free_vol_list(jcr);
2644    set_volume_name("TestVolume2", 2);
2645    jcr->bsr = NULL;
2646    create_vol_list(jcr);
2647    close_dev(dev);
2648    dev->state &= ~ST_READ; 
2649    if (!acquire_device_for_read(jcr)) {
2650       Pmsg2(0, "Cannot open Dev=%s, Vol=%s\n", dev_name(dev), dcr->VolumeName);
2651       return false;
2652    }
2653    return true;                    /* next volume mounted */
2654 }
2655
2656 static void set_volume_name(const char *VolName, int volnum) 
2657 {
2658    DCR *dcr = jcr->dcr;
2659    VolumeName = VolName;
2660    vol_num = volnum;
2661    bstrncpy(dev->VolCatInfo.VolCatName, VolName, sizeof(dev->VolCatInfo.VolCatName));
2662    bstrncpy(dcr->VolCatInfo.VolCatName, VolName, sizeof(dcr->VolCatInfo.VolCatName));
2663    bstrncpy(dcr->VolumeName, VolName, sizeof(dcr->VolumeName));
2664    dcr->VolCatInfo.Slot = volnum;
2665 }