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