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