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