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