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