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