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