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