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