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