]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/stored/tape_dev.c
Apply patches from bugs #2325 and #2326 to fix FIFO bugs
[bacula/bacula] / bacula / src / stored / tape_dev.c
1 /*
2    Bacula(R) - The Network Backup Solution
3
4    Copyright (C) 2000-2017 Kern Sibbald
5
6    The original author of Bacula is Kern Sibbald, with contributions
7    from many others, a complete list can be found in the file AUTHORS.
8
9    You may use this file and others of this release according to the
10    license defined in the LICENSE file, which includes the Affero General
11    Public License, v3.0 ("AGPLv3") and some additional permissions and
12    terms pursuant to its AGPLv3 Section 7.
13
14    This notice must be preserved when any source code is
15    conveyed and/or propagated.
16
17    Bacula(R) is a registered trademark of Kern Sibbald.
18 */
19 /*
20  *
21  *   tape_dev.c  -- low level operations on tape devices
22  *
23  *     written by, Kern Sibbald, MM
24  *     separated from dev.c in February 2014
25  *
26  *   The separation between tape and file is not yet clean.
27  *
28  */
29
30 /*
31  * Handling I/O errors and end of tape conditions are a bit tricky.
32  * This is how it is currently done when writing.
33  * On either an I/O error or end of tape,
34  * we will stop writing on the physical device (no I/O recovery is
35  * attempted at least in this daemon). The state flag will be sent
36  * to include ST_EOT, which is ephemeral, and ST_WEOT, which is
37  * persistent. Lots of routines clear ST_EOT, but ST_WEOT is
38  * cleared only when the problem goes away.  Now when ST_WEOT
39  * is set all calls to write_block_to_device() call the fix_up
40  * routine. In addition, all threads are blocked
41  * from writing on the tape by calling lock_dev(), and thread other
42  * than the first thread to hit the EOT will block on a condition
43  * variable. The first thread to hit the EOT will continue to
44  * be able to read and write the tape (he sort of tunnels through
45  * the locking mechanism -- see lock_dev() for details).
46  *
47  * Now presumably somewhere higher in the chain of command
48  * (device.c), someone will notice the EOT condition and
49  * get a new tape up, get the tape label read, and mark
50  * the label for rewriting. Then this higher level routine
51  * will write the unwritten buffer to the new volume.
52  * Finally, he will release
53  * any blocked threads by doing a broadcast on the condition
54  * variable.  At that point, we should be totally back in
55  * business with no lost data.
56  */
57
58 #include "bacula.h"
59 #include "stored.h"
60
61 #ifndef O_NONBLOCK
62 #define O_NONBLOCK 0
63 #endif
64
65 /* Imported functions */
66 extern void set_os_device_parameters(DCR *dcr);
67 extern bool dev_get_os_pos(DEVICE *dev, struct mtget *mt_stat);
68 extern uint32_t status_dev(DEVICE *dev);
69 const char *mode_to_str(int mode);
70
71 /*
72  */
73 bool tape_dev::open_device(DCR *dcr, int omode)
74 {
75    file_size = 0;
76    int timeout = max_open_wait;
77 #if !defined(HAVE_WIN32)
78    struct mtop mt_com;
79    utime_t start_time = time(NULL);
80 #endif
81
82    if (DEVICE::open_device(dcr, omode)) {
83       return true;              /* already open */
84    }
85    omode = openmode;            /* pickup possible new options */
86
87    mount(1);                    /* do mount if required */
88
89    Dmsg0(100, "Open dev: device is tape\n");
90
91    get_autochanger_loaded_slot(dcr);
92
93    openmode = omode;
94    set_mode(omode);
95
96    if (timeout < 1) {
97       timeout = 1;
98    }
99    errno = 0;
100    if (is_fifo() && timeout) {
101       /* Set open timer */
102       tid = start_thread_timer(dcr->jcr, pthread_self(), timeout);
103    }
104    Dmsg2(100, "Try open %s mode=%s\n", print_name(), mode_to_str(omode));
105
106 #if defined(HAVE_WIN32)
107
108    /*   Windows Code */
109    if ((m_fd = d_open(dev_name, mode)) < 0) {
110       dev_errno = errno;
111    }
112
113 #else
114
115    /*  UNIX  Code */
116    /* If busy retry each second for max_open_wait seconds */
117    for ( ;; ) {
118       /* Try non-blocking open */
119       m_fd = d_open(dev_name, mode+O_NONBLOCK);
120       if (m_fd < 0) {
121          berrno be;
122          dev_errno = errno;
123          Dmsg5(100, "Open error on %s omode=%d mode=%x errno=%d: ERR=%s\n",
124               print_name(), omode, mode, errno, be.bstrerror());
125       } else {
126          /* Tape open, now rewind it */
127          Dmsg0(100, "Rewind after open\n");
128          mt_com.mt_op = MTREW;
129          mt_com.mt_count = 1;
130          /* rewind only if dev is a tape */
131          if (is_tape() && (d_ioctl(m_fd, MTIOCTOP, (char *)&mt_com) < 0)) {
132             berrno be;
133             dev_errno = errno;           /* set error status from rewind */
134             d_close(m_fd);
135             clear_opened();
136             Dmsg2(100, "Rewind error on %s close: ERR=%s\n", print_name(),
137                   be.bstrerror(dev_errno));
138             /* If we get busy, device is probably rewinding, try again */
139             if (dev_errno != EBUSY) {
140                break;                    /* error -- no medium */
141             }
142          } else {
143             /* Got fd and rewind worked, so we must have medium in drive */
144             d_close(m_fd);
145             m_fd = d_open(dev_name, mode);  /* open normally */
146             if (m_fd < 0) {
147                berrno be;
148                dev_errno = errno;
149                Dmsg5(100, "Open error on %s omode=%d mode=%x errno=%d: ERR=%s\n",
150                      print_name(), omode, mode, errno, be.bstrerror());
151                break;
152             }
153             dev_errno = 0;
154             lock_door();
155             set_os_device_parameters(dcr);       /* do system dependent stuff */
156             break;                               /* Successfully opened and rewound */
157          }
158       }
159       bmicrosleep(5, 0);
160       /* Exceed wait time ? */
161       if (time(NULL) - start_time >= max_open_wait) {
162          break;                       /* yes, get out */
163       }
164    }
165 #endif
166
167    if (!is_open()) {
168       berrno be;
169       Mmsg2(errmsg, _("Unable to open device %s: ERR=%s\n"),
170             print_name(), be.bstrerror(dev_errno));
171       if (dcr->jcr) {
172          pm_strcpy(dcr->jcr->errmsg, errmsg);
173       }
174       Dmsg1(100, "%s", errmsg);
175    }
176
177    /* Stop any open() timer we started */
178    if (tid) {
179       stop_thread_timer(tid);
180       tid = 0;
181    }
182    Dmsg1(100, "open dev: tape %d opened\n", m_fd);
183    state |= preserve;                 /* reset any important state info */
184    return m_fd >= 0;
185 }
186
187
188 /*
189  * Rewind the device.
190  *  Returns: true  on success
191  *           false on failure
192  */
193 bool tape_dev::rewind(DCR *dcr)
194 {
195    struct mtop mt_com;
196    unsigned int i;
197    bool first = true;
198
199    Dmsg3(400, "rewind res=%d fd=%d %s\n", num_reserved(), m_fd, print_name());
200    state &= ~(ST_EOT|ST_EOF|ST_WEOT);  /* remove EOF/EOT flags */
201    block_num = file = 0;
202    file_size = 0;
203    file_addr = 0;
204    if (m_fd < 0) {
205       return false;
206    }
207    if (is_tape()) {
208       mt_com.mt_op = MTREW;
209       mt_com.mt_count = 1;
210       /* If we get an I/O error on rewind, it is probably because
211        * the drive is actually busy. We loop for (about 5 minutes)
212        * retrying every 5 seconds.
213        */
214       for (i=max_rewind_wait; ; i -= 5) {
215          if (d_ioctl(m_fd, MTIOCTOP, (char *)&mt_com) < 0) {
216             berrno be;
217             clrerror(MTREW);
218             if (i == max_rewind_wait) {
219                Dmsg1(200, "Rewind error, %s. retrying ...\n", be.bstrerror());
220             }
221             /*
222              * This is a gross hack, because if the user has the
223              *   device mounted (i.e. open), then uses mtx to load
224              *   a tape, the current open file descriptor is invalid.
225              *   So, we close the drive and re-open it.
226              */
227             if (first && dcr) {
228                int open_mode = openmode;
229                d_close(m_fd);
230                clear_opened();
231                open_device(dcr, open_mode);
232                if (m_fd < 0) {
233                   return false;
234                }
235                first = false;
236                continue;
237             }
238 #ifdef HAVE_SUN_OS
239             if (dev_errno == EIO) {
240                Mmsg1(errmsg, _("No tape loaded or drive offline on %s.\n"), print_name());
241                return false;
242             }
243 #else
244             if (dev_errno == EIO && i > 0) {
245                Dmsg0(200, "Sleeping 5 seconds.\n");
246                bmicrosleep(5, 0);
247                continue;
248             }
249 #endif
250             Mmsg2(errmsg, _("Rewind error on %s. ERR=%s.\n"),
251                print_name(), be.bstrerror());
252             return false;
253          }
254          break;
255       }
256    }
257    return true;
258 }
259
260 /*
261  * Check if the current position on the volume corresponds to
262  *  what is in the catalog.
263  *
264  */
265 bool tape_dev::is_eod_valid(DCR *dcr)
266 {
267    JCR *jcr = dcr->jcr;
268    /*
269     * Check if we are positioned on the tape at the same place
270     * that the database says we should be.
271     */
272    if (VolCatInfo.VolCatFiles == get_file()) {
273       Jmsg(jcr, M_INFO, 0, _("Ready to append to end of Volume \"%s\" at file=%d.\n"),
274            dcr->VolumeName, get_file());
275    } else if (get_file() > VolCatInfo.VolCatFiles) {
276       Jmsg(jcr, M_WARNING, 0, _("For Volume \"%s\":\n"
277            "The number of files mismatch! Volume=%u Catalog=%u\n"
278            "Correcting Catalog\n"),
279            dcr->VolumeName, get_file(), VolCatInfo.VolCatFiles);
280       VolCatInfo.VolCatFiles = get_file();
281       VolCatInfo.VolCatBlocks = get_block_num();
282       if (!dir_update_volume_info(dcr, false, true)) {
283          Jmsg(jcr, M_WARNING, 0, _("Error updating Catalog\n"));
284          dcr->mark_volume_in_error();
285          return false;
286       }
287    } else {
288       Jmsg(jcr, M_ERROR, 0, _("Bacula cannot write on tape Volume \"%s\" because:\n"
289            "The number of files mismatch! Volume=%u Catalog=%u\n"),
290            dcr->VolumeName, get_file(), VolCatInfo.VolCatFiles);
291       dcr->mark_volume_in_error();
292       return false;
293    }
294    return true;
295 }
296
297 /*
298  * Position device to end of medium (end of data)
299  *  Returns: true  on succes
300  *           false on error
301  */
302 bool tape_dev::eod(DCR *dcr)
303 {
304    struct mtop mt_com;
305    bool ok = true;
306    int32_t os_file;
307
308    Enter(100);
309    ok = DEVICE::eod(dcr);
310    if (!ok) {
311       return false;
312    }
313
314 #if defined (__digital__) && defined (__unix__)
315    return fsf(VolCatInfo.VolCatFiles);
316 #endif
317
318 #ifdef MTEOM
319    if (has_cap(CAP_FASTFSF) && !has_cap(CAP_EOM)) {
320       Dmsg0(100,"Using FAST FSF for EOM\n");
321       /* If unknown position, rewind */
322       if (get_os_tape_file() < 0) {
323         if (!rewind(dcr)) {
324           Dmsg0(100, "Rewind error\n");
325           Leave(100);
326           return false;
327         }
328       }
329       mt_com.mt_op = MTFSF;
330       /*
331        * ***FIXME*** fix code to handle case that INT16_MAX is
332        *   not large enough.
333        */
334       mt_com.mt_count = INT16_MAX;    /* use big positive number */
335       if (mt_com.mt_count < 0) {
336          mt_com.mt_count = INT16_MAX; /* brain damaged system */
337       }
338    }
339
340    if (has_cap(CAP_MTIOCGET) && (has_cap(CAP_FASTFSF) || has_cap(CAP_EOM))) {
341       if (has_cap(CAP_EOM)) {
342          Dmsg0(100,"Using EOM for EOM\n");
343          mt_com.mt_op = MTEOM;
344          mt_com.mt_count = 1;
345       }
346
347       if (d_ioctl(m_fd, MTIOCTOP, (char *)&mt_com) < 0) {
348          berrno be;
349          clrerror(mt_com.mt_op);
350          Dmsg1(50, "ioctl error: %s\n", be.bstrerror());
351          update_pos(dcr);
352          Mmsg2(errmsg, _("ioctl MTEOM error on %s. ERR=%s.\n"),
353             print_name(), be.bstrerror());
354          Dmsg1(100, "%s", errmsg);
355          Leave(100);
356          return false;
357       }
358
359       os_file = get_os_tape_file();
360       if (os_file < 0) {
361          berrno be;
362          clrerror(-1);
363          Mmsg2(errmsg, _("ioctl MTIOCGET error on %s. ERR=%s.\n"),
364             print_name(), be.bstrerror());
365          Dmsg1(100, "%s", errmsg);
366          Leave(100);
367          return false;
368       }
369       Dmsg1(100, "EOD file=%d\n", os_file);
370       set_ateof();
371       file = os_file;
372    } else {
373 #else
374    {
375 #endif
376       /*
377        * Rewind then use FSF until EOT reached
378        */
379       if (!rewind(dcr)) {
380          Dmsg0(100, "Rewind error.\n");
381          Leave(100);
382          return false;
383       }
384       /*
385        * Move file by file to the end of the tape
386        */
387       int file_num;
388       for (file_num=file; !at_eot(); file_num++) {
389          Dmsg0(200, "eod: doing fsf 1\n");
390          if (!fsf(1)) {
391             Dmsg0(100, "fsf error.\n");
392             Leave(100);
393             return false;
394          }
395          /*
396           * Avoid infinite loop by ensuring we advance.
397           */
398          if (!at_eot() && file_num == (int)file) {
399             Dmsg1(100, "fsf did not advance from file %d\n", file_num);
400             set_ateof();
401             os_file = get_os_tape_file();
402             if (os_file >= 0) {
403                Dmsg2(100, "Adjust file from %d to %d\n", file_num, os_file);
404                file = os_file;
405             }
406             break;
407          }
408       }
409    }
410    /*
411     * Some drivers leave us after second EOF when doing
412     * MTEOM, so we must backup so that appending overwrites
413     * the second EOF.
414     */
415    if (has_cap(CAP_BSFATEOM)) {
416       /* Backup over EOF */
417       ok = bsf(1);
418       /* If BSF worked and fileno is known (not -1), set file */
419       os_file = get_os_tape_file();
420       if (os_file >= 0) {
421          Dmsg2(100, "BSFATEOF adjust file from %d to %d\n", file , os_file);
422          file = os_file;
423       } else {
424          file++;                       /* wing it -- not correct on all OSes */
425       }
426    } else {
427       update_pos(dcr);                 /* update position */
428    }
429    Dmsg1(200, "EOD dev->file=%d\n", file);
430    Leave(100);
431    return ok;
432 }
433
434 /*
435  * Load medium in device
436  *  Returns: true  on success
437  *           false on failure
438  */
439 bool load_dev(DEVICE *dev)
440 {
441 #ifdef MTLOAD
442    struct mtop mt_com;
443 #endif
444
445    if (dev->fd() < 0) {
446       dev->dev_errno = EBADF;
447       Mmsg0(dev->errmsg, _("Bad call to load_dev. Device not open\n"));
448       Emsg0(M_FATAL, 0, dev->errmsg);
449       return false;
450    }
451    if (!(dev->is_tape())) {
452       return true;
453    }
454 #ifndef MTLOAD
455    Dmsg0(200, "stored: MTLOAD command not available\n");
456    berrno be;
457    dev->dev_errno = ENOTTY;           /* function not available */
458    Mmsg2(dev->errmsg, _("ioctl MTLOAD error on %s. ERR=%s.\n"),
459          dev->print_name(), be.bstrerror());
460    return false;
461 #else
462
463    dev->block_num = dev->file = 0;
464    dev->file_size = 0;
465    dev->file_addr = 0;
466    mt_com.mt_op = MTLOAD;
467    mt_com.mt_count = 1;
468    if (dev->d_ioctl(dev->fd(), MTIOCTOP, (char *)&mt_com) < 0) {
469       berrno be;
470       dev->dev_errno = errno;
471       Mmsg2(dev->errmsg, _("ioctl MTLOAD error on %s. ERR=%s.\n"),
472          dev->print_name(), be.bstrerror());
473       return false;
474    }
475    return true;
476 #endif
477 }
478
479 /*
480  * Rewind device and put it offline
481  *  Returns: true  on success
482  *           false on failure
483  */
484 bool tape_dev::offline(DCR *dcr)
485 {
486    struct mtop mt_com;
487
488    if (!is_tape()) {
489       return true;                    /* device not open */
490    }
491
492    state &= ~(ST_APPEND|ST_READ|ST_EOT|ST_EOF|ST_WEOT);  /* remove EOF/EOT flags */
493    block_num = file = 0;
494    file_size = 0;
495    file_addr = 0;
496    unlock_door();
497    mt_com.mt_op = MTOFFL;
498    mt_com.mt_count = 1;
499    if (d_ioctl(m_fd, MTIOCTOP, (char *)&mt_com) < 0) {
500       berrno be;
501       dev_errno = errno;
502       Mmsg2(errmsg, _("ioctl MTOFFL error on %s. ERR=%s.\n"),
503          print_name(), be.bstrerror());
504       return false;
505    }
506    Dmsg1(100, "Offlined device %s\n", print_name());
507    return true;
508 }
509
510 bool DEVICE::offline_or_rewind(DCR *dcr)
511 {
512    if (m_fd < 0) {
513       return false;
514    }
515    if (has_cap(CAP_OFFLINEUNMOUNT)) {
516       return offline(dcr);
517    } else {
518    /*
519     * Note, this rewind probably should not be here (it wasn't
520     *  in prior versions of Bacula), but on FreeBSD, this is
521     *  needed in the case the tape was "frozen" due to an error
522     *  such as backspacing after writing and EOF. If it is not
523     *  done, all future references to the drive get and I/O error.
524     */
525       clrerror(MTREW);
526       return rewind(dcr);
527    }
528 }
529
530 /*
531  * Foward space a file
532  *   Returns: true  on success
533  *            false on failure
534  */
535 bool tape_dev::fsf(int num)
536 {
537    int32_t os_file = 0;
538    struct mtop mt_com;
539    int stat = 0;
540
541    if (!is_open()) {
542       dev_errno = EBADF;
543       Mmsg0(errmsg, _("Bad call to fsf. Device not open\n"));
544       Emsg0(M_FATAL, 0, errmsg);
545       return false;
546    }
547
548    if (!is_tape()) {
549       return true;
550    }
551
552    if (at_eot()) {
553       dev_errno = 0;
554       Mmsg1(errmsg, _("Device %s at End of Tape.\n"), print_name());
555       return false;
556    }
557    if (at_eof()) {
558       Dmsg0(200, "ST_EOF set on entry to FSF\n");
559    }
560
561    Dmsg0(100, "fsf\n");
562    block_num = 0;
563    /*
564     * If Fast forward space file is set, then we
565     *  use MTFSF to forward space and MTIOCGET
566     *  to get the file position. We assume that
567     *  the SCSI driver will ensure that we do not
568     *  forward space past the end of the medium.
569     */
570    if (has_cap(CAP_FSF) && has_cap(CAP_MTIOCGET) && has_cap(CAP_FASTFSF)) {
571       int my_errno = 0;
572       mt_com.mt_op = MTFSF;
573       mt_com.mt_count = num;
574       stat = d_ioctl(m_fd, MTIOCTOP, (char *)&mt_com);
575       if (stat < 0) {
576          my_errno = errno;            /* save errno */
577       } else if ((os_file=get_os_tape_file()) < 0) {
578          my_errno = errno;            /* save errno */
579       }
580       if (my_errno != 0) {
581          berrno be;
582          set_eot();
583          Dmsg0(200, "Set ST_EOT\n");
584          clrerror(MTFSF);
585          Mmsg2(errmsg, _("ioctl MTFSF error on %s. ERR=%s.\n"),
586             print_name(), be.bstrerror(my_errno));
587          Dmsg1(200, "%s", errmsg);
588          return false;
589       }
590
591       Dmsg1(200, "fsf file=%d\n", os_file);
592       set_ateof();
593       file = os_file;
594       return true;
595
596    /*
597     * Here if CAP_FSF is set, and virtually all drives
598     *  these days support it, we read a record, then forward
599     *  space one file. Using this procedure, which is slow,
600     *  is the only way we can be sure that we don't read
601     *  two consecutive EOF marks, which means End of Data.
602     */
603    } else if (has_cap(CAP_FSF)) {
604       POOLMEM *rbuf;
605       int rbuf_len;
606       Dmsg0(200, "FSF has cap_fsf\n");
607       if (max_block_size == 0) {
608          rbuf_len = DEFAULT_BLOCK_SIZE;
609       } else {
610          rbuf_len = max_block_size;
611       }
612       rbuf = get_memory(rbuf_len);
613       mt_com.mt_op = MTFSF;
614       mt_com.mt_count = 1;
615       while (num-- && !at_eot()) {
616          Dmsg0(100, "Doing read before fsf\n");
617          if ((stat = this->read((char *)rbuf, rbuf_len)) < 0) {
618             if (errno == ENOMEM) {     /* tape record exceeds buf len */
619                stat = rbuf_len;        /* This is OK */
620             /*
621              * On IBM drives, they return ENOSPC at EOM
622              *  instead of EOF status
623              */
624             } else if (at_eof() && errno == ENOSPC) {
625                stat = 0;
626             } else {
627                berrno be;
628                set_eot();
629                clrerror(-1);
630                Dmsg2(100, "Set ST_EOT read errno=%d. ERR=%s\n", dev_errno,
631                   be.bstrerror());
632                Mmsg2(errmsg, _("read error on %s. ERR=%s.\n"),
633                   print_name(), be.bstrerror());
634                Dmsg1(100, "%s", errmsg);
635                break;
636             }
637          }
638          if (stat == 0) {                /* EOF */
639             Dmsg1(100, "End of File mark from read. File=%d\n", file+1);
640             /* Two reads of zero means end of tape */
641             if (at_eof()) {
642                set_eot();
643                Dmsg0(100, "Set ST_EOT\n");
644                break;
645             } else {
646                set_ateof();
647                continue;
648             }
649          } else {                        /* Got data */
650             clear_eot();
651             clear_eof();
652          }
653
654          Dmsg0(100, "Doing MTFSF\n");
655          stat = d_ioctl(m_fd, MTIOCTOP, (char *)&mt_com);
656          if (stat < 0) {                 /* error => EOT */
657             berrno be;
658             set_eot();
659             Dmsg0(100, "Set ST_EOT\n");
660             clrerror(MTFSF);
661             Mmsg2(errmsg, _("ioctl MTFSF error on %s. ERR=%s.\n"),
662                print_name(), be.bstrerror());
663             Dmsg0(100, "Got < 0 for MTFSF\n");
664             Dmsg1(100, "%s", errmsg);
665          } else {
666             set_ateof();
667          }
668       }
669       free_memory(rbuf);
670
671    /*
672     * No FSF, so use FSR to simulate it
673     */
674    } else {
675       Dmsg0(200, "Doing FSR for FSF\n");
676       while (num-- && !at_eot()) {
677          fsr(INT32_MAX);    /* returns -1 on EOF or EOT */
678       }
679       if (at_eot()) {
680          dev_errno = 0;
681          Mmsg1(errmsg, _("Device %s at End of Tape.\n"), print_name());
682          stat = -1;
683       } else {
684          stat = 0;
685       }
686    }
687    Dmsg1(200, "Return %d from FSF\n", stat);
688    if (at_eof()) {
689       Dmsg0(200, "ST_EOF set on exit FSF\n");
690    }
691    if (at_eot()) {
692       Dmsg0(200, "ST_EOT set on exit FSF\n");
693    }
694    Dmsg1(200, "Return from FSF file=%d\n", file);
695    return stat == 0;
696 }
697
698 /*
699  * Backward space a file
700  *  Returns: false on failure
701  *           true  on success
702  */
703 bool tape_dev::bsf(int num)
704 {
705    struct mtop mt_com;
706    int stat;
707
708    if (!is_open()) {
709       dev_errno = EBADF;
710       Mmsg0(errmsg, _("Bad call to bsf. Device not open\n"));
711       Emsg0(M_FATAL, 0, errmsg);
712       return false;
713    }
714
715    if (!is_tape()) {
716       Mmsg1(errmsg, _("Device %s cannot BSF because it is not a tape.\n"),
717          print_name());
718       return false;
719    }
720
721    Dmsg0(100, "bsf\n");
722    clear_eot();
723    clear_eof();
724    file -= num;
725    file_addr = 0;
726    file_size = 0;
727    mt_com.mt_op = MTBSF;
728    mt_com.mt_count = num;
729    stat = d_ioctl(m_fd, MTIOCTOP, (char *)&mt_com);
730    if (stat < 0) {
731       berrno be;
732       clrerror(MTBSF);
733       Mmsg2(errmsg, _("ioctl MTBSF error on %s. ERR=%s.\n"),
734          print_name(), be.bstrerror());
735    }
736    return stat == 0;
737 }
738
739
740 /*
741  * Foward space num records
742  *  Returns: false on failure
743  *           true  on success
744  */
745 bool DEVICE::fsr(int num)
746 {
747    struct mtop mt_com;
748    int stat;
749
750    if (!is_open()) {
751       dev_errno = EBADF;
752       Mmsg0(errmsg, _("Bad call to fsr. Device not open\n"));
753       Emsg0(M_FATAL, 0, errmsg);
754       return false;
755    }
756
757    if (!is_tape()) {
758       return false;
759    }
760
761    if (!has_cap(CAP_FSR)) {
762       Mmsg1(errmsg, _("ioctl MTFSR not permitted on %s.\n"), print_name());
763       return false;
764    }
765
766    Dmsg1(100, "fsr %d\n", num);
767    mt_com.mt_op = MTFSR;
768    mt_com.mt_count = num;
769    stat = d_ioctl(m_fd, MTIOCTOP, (char *)&mt_com);
770    if (stat == 0) {
771       clear_eof();
772       block_num += num;
773    } else {
774       berrno be;
775       struct mtget mt_stat;
776       clrerror(MTFSR);
777       Dmsg1(100, "FSF fail: ERR=%s\n", be.bstrerror());
778       if (dev_get_os_pos(this, &mt_stat)) {
779          Dmsg4(100, "Adjust from %d:%d to %d:%d\n", file,
780             block_num, mt_stat.mt_fileno, mt_stat.mt_blkno);
781          file = mt_stat.mt_fileno;
782          block_num = mt_stat.mt_blkno;
783       } else {
784          if (at_eof()) {
785             set_eot();
786          } else {
787             set_ateof();
788          }
789       }
790       Mmsg3(errmsg, _("ioctl MTFSR %d error on %s. ERR=%s.\n"),
791          num, print_name(), be.bstrerror());
792    }
793    return stat == 0;
794 }
795
796 /*
797  * Backward space a record
798  *   Returns:  false on failure
799  *             true  on success
800  */
801 bool DEVICE::bsr(int num)
802 {
803    struct mtop mt_com;
804    int stat;
805
806    if (!is_open()) {
807       dev_errno = EBADF;
808       Mmsg0(errmsg, _("Bad call to bsr_dev. Device not open\n"));
809       Emsg0(M_FATAL, 0, errmsg);
810       return false;
811    }
812
813    if (!is_tape()) {
814       return false;
815    }
816
817    if (!has_cap(CAP_BSR)) {
818       Mmsg1(errmsg, _("ioctl MTBSR not permitted on %s.\n"), print_name());
819       return false;
820    }
821
822    Dmsg0(100, "bsr_dev\n");
823    block_num -= num;
824    clear_eof();
825    clear_eot();
826    mt_com.mt_op = MTBSR;
827    mt_com.mt_count = num;
828    stat = d_ioctl(m_fd, MTIOCTOP, (char *)&mt_com);
829    if (stat < 0) {
830       berrno be;
831       clrerror(MTBSR);
832       Mmsg2(errmsg, _("ioctl MTBSR error on %s. ERR=%s.\n"),
833          print_name(), be.bstrerror());
834    }
835    return stat == 0;
836 }
837
838 void tape_dev::lock_door()
839 {
840 #ifdef MTLOCK
841    struct mtop mt_com;
842    if (!is_tape()) return;
843    mt_com.mt_op = MTLOCK;
844    mt_com.mt_count = 1;
845    d_ioctl(m_fd, MTIOCTOP, (char *)&mt_com);
846 #endif
847 }
848
849 void tape_dev::unlock_door()
850 {
851 #ifdef MTUNLOCK
852    struct mtop mt_com;
853    if (!is_tape()) return;
854    mt_com.mt_op = MTUNLOCK;
855    mt_com.mt_count = 1;
856    d_ioctl(m_fd, MTIOCTOP, (char *)&mt_com);
857 #endif
858 }
859
860 /*
861  * Reposition the device to file, block
862  * Returns: false on failure
863  *          true  on success
864  */
865 bool tape_dev::reposition(DCR *dcr, uint64_t raddr)
866 {
867    uint32_t rfile, rblock;
868
869    rfile = (uint32_t)(raddr>>32);
870    rblock = (uint32_t)raddr;
871    if (!is_open()) {
872       dev_errno = EBADF;
873       Mmsg0(errmsg, _("Bad call to reposition. Device not open\n"));
874       Emsg0(M_FATAL, 0, errmsg);
875       return false;
876    }
877
878    /* After this point, we are tape only */
879    Dmsg4(100, "reposition from %u:%u to %u:%u\n", file, block_num, rfile, rblock);
880    if (rfile < file) {
881       Dmsg0(100, "Rewind\n");
882       if (!rewind(dcr)) {
883          return false;
884       }
885    }
886    if (rfile > file) {
887       Dmsg1(100, "fsf %d\n", rfile-file);
888       if (!fsf(rfile-file)) {
889          Dmsg1(100, "fsf failed! ERR=%s\n", bstrerror());
890          return false;
891       }
892       Dmsg2(100, "wanted_file=%d at_file=%d\n", rfile, file);
893    }
894    if (rblock < block_num) {
895       Dmsg2(100, "wanted_blk=%d at_blk=%d\n", rblock, block_num);
896       Dmsg0(100, "bsf 1\n");
897       bsf(1);
898       Dmsg0(100, "fsf 1\n");
899       fsf(1);
900       Dmsg2(100, "wanted_blk=%d at_blk=%d\n", rblock, block_num);
901    }
902    if (has_cap(CAP_POSITIONBLOCKS) && rblock > block_num) {
903       /* Ignore errors as Bacula can read to the correct block */
904       Dmsg1(100, "fsr %d\n", rblock-block_num);
905       return fsr(rblock-block_num);
906    } else {
907       while (rblock > block_num) {
908          if (!dcr->read_block_from_dev(NO_BLOCK_NUMBER_CHECK)) {
909             berrno be;
910             dev_errno = errno;
911             Dmsg2(30, "Failed to find requested block on %s: ERR=%s",
912                print_name(), be.bstrerror());
913             return false;
914          }
915          Dmsg2(300, "moving forward wanted_blk=%d at_blk=%d\n", rblock, block_num);
916       }
917    }
918    return true;
919 }
920
921 /*
922  * Write an end of file on the device
923  *   Returns: true on success
924  *            false on failure
925  */
926 bool tape_dev::weof(DCR *dcr, int num)
927 {
928    struct mtop mt_com;
929    int stat;
930    Dmsg1(129, "=== weof_dev=%s\n", print_name());
931
932    if (!is_open()) {
933       dev_errno = EBADF;
934       Mmsg0(errmsg, _("Bad call to weof_dev. Device not open\n"));
935       Emsg0(M_FATAL, 0, errmsg);
936       return false;
937    }
938    file_size = 0;
939
940    if (!is_tape()) {
941       return true;
942    }
943    if (!can_append()) {
944       Mmsg0(errmsg, _("Attempt to WEOF on non-appendable Volume\n"));
945       Emsg0(M_FATAL, 0, errmsg);
946       return false;
947    }
948
949    clear_eof();
950    clear_eot();
951    mt_com.mt_op = MTWEOF;
952    mt_com.mt_count = num;
953    stat = d_ioctl(m_fd, MTIOCTOP, (char *)&mt_com);
954    if (stat == 0) {
955       block_num = 0;
956       file += num;
957       file_addr = 0;
958    } else {
959       berrno be;
960       clrerror(MTWEOF);
961       if (stat == -1) {
962          Mmsg2(errmsg, _("ioctl MTWEOF error on %s. ERR=%s.\n"),
963             print_name(), be.bstrerror());
964        }
965    }
966    /* DCR is null if called from within write_ansi_ibm_labels() */
967    if (dcr && stat == 0) {
968       if (!write_ansi_ibm_labels(dcr, ANSI_EOF_LABEL, VolHdr.VolumeName)) {
969          stat = -1;
970       }
971    }
972    return stat == 0;
973 }
974
975 /*
976  * If timeout, wait until the mount command returns 0.
977  * If !timeout, try to mount the device only once.
978  */
979 bool tape_dev::mount(int timeout)
980 {
981    Dmsg0(190, "Enter tape mount\n");
982
983    if (!is_mounted() && device->mount_command) {
984       return mount_tape(1, timeout);
985    }
986    return true;
987 }
988
989 /*
990  * Unmount the device
991  * If timeout, wait until the unmount command returns 0.
992  * If !timeout, try to unmount the device only once.
993  */
994 bool tape_dev::unmount(int timeout)
995 {
996    Dmsg0(100, "Enter tape  unmount\n");
997
998    if (!is_mounted() && requires_mount() && device->unmount_command) {
999       return mount_tape(0, timeout);
1000    }
1001    return true;
1002 }
1003
1004
1005 /*
1006  * (Un)mount the device (for tape devices)
1007  */
1008 bool tape_dev::mount_tape(int mount, int dotimeout)
1009 {
1010    POOL_MEM ocmd(PM_FNAME);
1011    POOLMEM *results;
1012    char *icmd;
1013    int status, tries;
1014    berrno be;
1015
1016    Dsm_check(200);
1017    if (mount) {
1018       icmd = device->mount_command;
1019    } else {
1020       icmd = device->unmount_command;
1021    }
1022
1023    edit_mount_codes(ocmd, icmd);
1024
1025    Dmsg2(100, "mount_tape: cmd=%s mounted=%d\n", ocmd.c_str(), !!is_mounted());
1026
1027    if (dotimeout) {
1028       /* Try at most 10 times to (un)mount the device. This should perhaps be configurable. */
1029       tries = 10;
1030    } else {
1031       tries = 1;
1032    }
1033    results = get_memory(4000);
1034
1035    /* If busy retry each second */
1036    Dmsg1(100, "mount_tape run_prog=%s\n", ocmd.c_str());
1037    while ((status = run_program_full_output(ocmd.c_str(), max_open_wait/2, results)) != 0) {
1038       if (tries-- > 0) {
1039          continue;
1040       }
1041
1042       Dmsg5(100, "Device %s cannot be %smounted. stat=%d result=%s ERR=%s\n", print_name(),
1043            (mount ? "" : "un"), status, results, be.bstrerror(status));
1044       Mmsg(errmsg, _("Device %s cannot be %smounted. ERR=%s\n"),
1045            print_name(), (mount ? "" : "un"), be.bstrerror(status));
1046
1047       set_mounted(false);
1048       free_pool_memory(results);
1049       Dmsg0(200, "============ mount=0\n");
1050       Dsm_check(200);
1051       return false;
1052    }
1053
1054    set_mounted(mount);              /* set/clear mounted flag */
1055    free_pool_memory(results);
1056    Dmsg1(200, "============ mount=%d\n", mount);
1057    return true;
1058 }
1059
1060 void tape_dev::set_ateof()
1061 {
1062    if (at_eof()) {
1063       return;
1064    }
1065    DEVICE::set_ateof();
1066    file++;
1067 }
1068
1069 const char *tape_dev::print_type()
1070 {
1071    return "Tape";
1072 }
1073
1074 DEVICE *tape_dev::get_dev(DCR */*dcr*/)
1075 {
1076    return this;
1077 }
1078
1079 uint32_t tape_dev::get_hi_addr()
1080 {
1081    return file;
1082 }
1083
1084 uint32_t tape_dev::get_low_addr()
1085 {
1086    return block_num;
1087 }
1088
1089 uint64_t tape_dev::get_full_addr()
1090 {
1091    return (((uint64_t)file) << 32) | (uint64_t)block_num;
1092 }
1093
1094 bool tape_dev::end_of_volume(DCR *dcr)
1095 {
1096    return write_ansi_ibm_labels(dcr, ANSI_EOV_LABEL, VolHdr.VolumeName);
1097 }
1098
1099 /* Print the address */
1100 char *tape_dev::print_addr(char *buf, int32_t buf_len)
1101 {
1102    buf[0] = 0;
1103    bsnprintf(buf, buf_len, "%lu:%lu", get_hi_addr(), get_low_addr());
1104    return buf;
1105 }
1106
1107 char *tape_dev::print_addr(char *buf, int32_t buf_len, boffset_t addr)
1108 {
1109    buf[0] = 0;
1110    bsnprintf(buf, buf_len, "%lu:%lu", (uint32_t)(addr>>32), (uint32_t)addr);
1111    return buf;
1112 }
1113
1114 /*
1115  * Clean up when terminating the device
1116  */
1117 void tape_dev::term(DCR *dcr)
1118 {
1119    delete_alerts();
1120    DEVICE::term(dcr);
1121 }