]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/stored/dev.c
Change dev->open() to return bool
[bacula/bacula] / bacula / src / stored / dev.c
1 /*
2    Bacula® - The Network Backup Solution
3
4    Copyright (C) 2000-2012 Free Software Foundation Europe e.V.
5
6    The main author of Bacula is Kern Sibbald, with contributions from
7    many others, a complete list can be found in the file AUTHORS.
8    This program is Free Software; you can redistribute it and/or
9    modify it under the terms of version three of the GNU Affero General Public
10    License as published by the Free Software Foundation and included
11    in the file LICENSE.
12
13    This program is distributed in the hope that it will be useful, but
14    WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16    General Public License for more details.
17
18    You should have received a copy of the GNU Affero General Public License
19    along with this program; if not, write to the Free Software
20    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
21    02110-1301, USA.
22
23    Bacula® is a registered trademark of Kern Sibbald.
24    The licensor of Bacula is the Free Software Foundation Europe
25    (FSFE), Fiduciary Program, Sumatrastrasse 25, 8006 Zürich,
26    Switzerland, email:ftf@fsfeurope.org.
27 */
28 /*
29  *
30  *   dev.c  -- low level operations on device (storage device)
31  *
32  *              Kern Sibbald, MM
33  *
34  *     NOTE!!!! None of these routines are reentrant. You must
35  *        use dev->r_dlock() and dev->unlock() at a higher level,
36  *        or use the xxx_device() equivalents.  By moving the
37  *        thread synchronization to a higher level, we permit
38  *        the higher level routines to "seize" the device and
39  *        to carry out operations without worrying about who
40  *        set what lock (i.e. race conditions).
41  *
42  *     Note, this is the device dependent code, and may have
43  *           to be modified for each system, but is meant to
44  *           be as "generic" as possible.
45  *
46  *     The purpose of this code is to develop a SIMPLE Storage
47  *     daemon. More complicated coding (double buffering, writer
48  *     thread, ...) is left for a later version.
49  *
50  */
51
52 /*
53  * Handling I/O errors and end of tape conditions are a bit tricky.
54  * This is how it is currently done when writing.
55  * On either an I/O error or end of tape,
56  * we will stop writing on the physical device (no I/O recovery is
57  * attempted at least in this daemon). The state flag will be sent
58  * to include ST_EOT, which is ephemeral, and ST_WEOT, which is
59  * persistent. Lots of routines clear ST_EOT, but ST_WEOT is
60  * cleared only when the problem goes away.  Now when ST_WEOT
61  * is set all calls to write_block_to_device() call the fix_up
62  * routine. In addition, all threads are blocked
63  * from writing on the tape by calling lock_dev(), and thread other
64  * than the first thread to hit the EOT will block on a condition
65  * variable. The first thread to hit the EOT will continue to
66  * be able to read and write the tape (he sort of tunnels through
67  * the locking mechanism -- see lock_dev() for details).
68  *
69  * Now presumably somewhere higher in the chain of command
70  * (device.c), someone will notice the EOT condition and
71  * get a new tape up, get the tape label read, and mark
72  * the label for rewriting. Then this higher level routine
73  * will write the unwritten buffer to the new volume.
74  * Finally, he will release
75  * any blocked threads by doing a broadcast on the condition
76  * variable.  At that point, we should be totally back in
77  * business with no lost data.
78  */
79
80
81 #include "bacula.h"
82 #include "stored.h"
83
84 #ifndef O_NONBLOCK 
85 #define O_NONBLOCK 0
86 #endif
87
88 /* Forward referenced functions */
89 void set_os_device_parameters(DCR *dcr);   
90 static bool dev_get_os_pos(DEVICE *dev, struct mtget *mt_stat);
91 static const char *mode_to_str(int mode);
92
93 /*
94  * Allocate and initialize the DEVICE structure
95  * Note, if dev is non-NULL, it is already allocated,
96  * thus we neither allocate it nor free it. This allows
97  * the caller to put the packet in shared memory.
98  *
99  *  Note, for a tape, the device->device_name is the device name
100  *     (e.g. /dev/nst0), and for a file, the device name
101  *     is the directory in which the file will be placed.
102  *
103  */
104 DEVICE *
105 init_dev(JCR *jcr, DEVRES *device)
106 {
107    struct stat statp;
108    int errstat;
109    DCR *dcr = NULL;
110    DEVICE *dev;
111    uint32_t max_bs;
112
113
114    /* If no device type specified, try to guess */
115    if (!device->dev_type) {
116       /* Check that device is available */
117       if (stat(device->device_name, &statp) < 0) {
118          berrno be;
119          Jmsg2(jcr, M_ERROR, 0, _("Unable to stat device %s: ERR=%s\n"), 
120             device->device_name, be.bstrerror());
121          return NULL;
122       }
123       if (S_ISDIR(statp.st_mode)) {
124          device->dev_type = B_FILE_DEV;
125       } else if (S_ISCHR(statp.st_mode)) {
126          device->dev_type = B_TAPE_DEV;
127       } else if (S_ISFIFO(statp.st_mode)) {
128          device->dev_type = B_FIFO_DEV;
129 #ifdef USE_VTAPE
130       /* must set DeviceType = Vtape 
131        * in normal mode, autodetection is disabled
132        */
133       } else if (S_ISREG(statp.st_mode)) { 
134          device->dev_type = B_VTAPE_DEV;
135 #endif
136       } else if (!(device->cap_bits & CAP_REQMOUNT)) {
137          Jmsg2(jcr, M_ERROR, 0, _("%s is an unknown device type. Must be tape or directory\n"
138                " or have RequiresMount=yes for DVD. st_mode=%x\n"),
139             device->device_name, statp.st_mode);
140          return NULL;
141       } else {
142          device->dev_type = B_DVD_DEV;
143       }
144    }
145    switch (device->dev_type) {
146    case B_DVD_DEV:
147       Jmsg0(jcr, M_FATAL, 0, _("DVD support is now deprecated\n"));
148       return NULL;
149    case B_VTAPE_DEV:
150       dev = New(vtape);
151       break;
152 #ifdef USE_FTP
153    case B_FTP_DEV:
154       dev = New(ftp_device);
155       break;
156 #endif
157 #ifdef HAVE_WIN32
158 /* TODO: defined in src/win32/stored/mtops.cpp */
159    case B_TAPE_DEV:
160       dev = New(win32_tape_device);
161       break;
162    case B_FILE_DEV:
163       dev = New(win32_file_device);
164       break;
165 #else
166    case B_TAPE_DEV:
167    case B_FILE_DEV:
168    case B_FIFO_DEV:
169       dev = New(DEVICE);
170       break;
171 #endif
172    default:
173          return NULL;
174    }
175    dev->clear_slot();         /* unknown */
176
177    /* Copy user supplied device parameters from Resource */
178    dev->dev_name = get_memory(strlen(device->device_name)+1);
179    pm_strcpy(dev->dev_name, device->device_name);
180    dev->prt_name = get_memory(strlen(device->device_name) + strlen(device->hdr.name) + 20);
181    /* We edit "Resource-name" (physical-name) */
182    Mmsg(dev->prt_name, "\"%s\" (%s)", device->hdr.name, device->device_name);
183    Dmsg1(400, "Allocate dev=%s\n", dev->print_name());
184    dev->capabilities = device->cap_bits;
185    dev->min_block_size = device->min_block_size;
186    dev->max_block_size = device->max_block_size;
187    dev->max_volume_size = device->max_volume_size;
188    dev->max_file_size = device->max_file_size;
189    dev->max_concurrent_jobs = device->max_concurrent_jobs;
190    dev->volume_capacity = device->volume_capacity;
191    dev->max_rewind_wait = device->max_rewind_wait;
192    dev->max_open_wait = device->max_open_wait;
193    dev->max_open_vols = device->max_open_vols;
194    dev->vol_poll_interval = device->vol_poll_interval;
195    dev->max_spool_size = device->max_spool_size;
196    dev->drive_index = device->drive_index;
197    dev->autoselect = device->autoselect;
198    dev->dev_type = device->dev_type;
199    if (dev->is_tape()) { /* No parts on tapes */
200       dev->max_part_size = 0;
201    } else {
202       dev->max_part_size = device->max_part_size;
203    }
204    /* Sanity check */
205    if (dev->vol_poll_interval && dev->vol_poll_interval < 60) {
206       dev->vol_poll_interval = 60;
207    }
208    /* Link the dev and device structures together */
209    dev->device = device;
210    device->dev = dev;
211
212    if (dev->is_fifo()) {
213       dev->capabilities |= CAP_STREAM; /* set stream device */
214    }
215
216    /* If the device requires mount :
217     * - Check that the mount point is available 
218     * - Check that (un)mount commands are defined
219     */
220    if (dev->is_file() && dev->requires_mount()) {
221       if (!device->mount_point || stat(device->mount_point, &statp) < 0) {
222          berrno be;
223          dev->dev_errno = errno;
224          Jmsg2(jcr, M_ERROR_TERM, 0, _("Unable to stat mount point %s: ERR=%s\n"), 
225             device->mount_point, be.bstrerror());
226       }
227    
228       if (!device->mount_command || !device->unmount_command) {
229          Jmsg0(jcr, M_ERROR_TERM, 0, _("Mount and unmount commands must defined for a device which requires mount.\n"));
230       }
231    }
232
233    /* Sanity check */
234    if (dev->max_block_size == 0) {
235       max_bs = DEFAULT_BLOCK_SIZE;
236    } else {
237       max_bs = dev->max_block_size;
238    }
239    if (dev->min_block_size > max_bs) {
240       Jmsg(jcr, M_ERROR_TERM, 0, _("Min block size > max on device %s\n"), 
241            dev->print_name());
242    }
243    if (dev->max_block_size > 4096000) {
244       Jmsg3(jcr, M_ERROR, 0, _("Block size %u on device %s is too large, using default %u\n"),
245          dev->max_block_size, dev->print_name(), DEFAULT_BLOCK_SIZE);
246       dev->max_block_size = 0;
247    }
248    if (dev->max_block_size % TAPE_BSIZE != 0) {
249       Jmsg3(jcr, M_WARNING, 0, _("Max block size %u not multiple of device %s block size=%d.\n"),
250          dev->max_block_size, dev->print_name(), TAPE_BSIZE);
251    }
252    if (dev->max_volume_size != 0 && dev->max_volume_size < (dev->max_block_size << 4)) {
253       Jmsg(jcr, M_ERROR_TERM, 0, _("Max Vol Size < 8 * Max Block Size for device %s\n"), 
254            dev->print_name());
255    }
256
257    dev->errmsg = get_pool_memory(PM_EMSG);
258    *dev->errmsg = 0;
259
260    if ((errstat = pthread_mutex_init(&dev->m_mutex, NULL)) != 0) {
261       berrno be;
262       dev->dev_errno = errstat;
263       Mmsg1(dev->errmsg, _("Unable to init mutex: ERR=%s\n"), be.bstrerror(errstat));
264       Jmsg0(jcr, M_ERROR_TERM, 0, dev->errmsg);
265    }
266    if ((errstat = pthread_cond_init(&dev->wait, NULL)) != 0) {
267       berrno be;
268       dev->dev_errno = errstat;
269       Mmsg1(dev->errmsg, _("Unable to init cond variable: ERR=%s\n"), be.bstrerror(errstat));
270       Jmsg0(jcr, M_ERROR_TERM, 0, dev->errmsg);
271    }
272    if ((errstat = pthread_cond_init(&dev->wait_next_vol, NULL)) != 0) {
273       berrno be;
274       dev->dev_errno = errstat;
275       Mmsg1(dev->errmsg, _("Unable to init cond variable: ERR=%s\n"), be.bstrerror(errstat));
276       Jmsg0(jcr, M_ERROR_TERM, 0, dev->errmsg);
277    }
278    if ((errstat = pthread_mutex_init(&dev->spool_mutex, NULL)) != 0) {
279       berrno be;
280       dev->dev_errno = errstat;
281       Mmsg1(dev->errmsg, _("Unable to init mutex: ERR=%s\n"), be.bstrerror(errstat));
282       Jmsg0(jcr, M_ERROR_TERM, 0, dev->errmsg);
283    }
284    if ((errstat = pthread_mutex_init(&dev->acquire_mutex, NULL)) != 0) {
285       berrno be;
286       dev->dev_errno = errstat;
287       Mmsg1(dev->errmsg, _("Unable to init mutex: ERR=%s\n"), be.bstrerror(errstat));
288       Jmsg0(jcr, M_ERROR_TERM, 0, dev->errmsg);
289    }
290    /* Ensure that we respect this order in P/V operations */
291    bthread_mutex_set_priority(&dev->m_mutex,       PRIO_SD_DEV_ACCESS);
292    bthread_mutex_set_priority(&dev->spool_mutex,   PRIO_SD_DEV_SPOOL);
293    bthread_mutex_set_priority(&dev->acquire_mutex, PRIO_SD_DEV_ACQUIRE);
294    if ((errstat = pthread_mutex_init(&dev->read_acquire_mutex, NULL)) != 0) {
295       berrno be;
296       dev->dev_errno = errstat;
297       Mmsg1(dev->errmsg, _("Unable to init mutex: ERR=%s\n"), be.bstrerror(errstat));
298       Jmsg0(jcr, M_ERROR_TERM, 0, dev->errmsg);
299    }
300 #ifdef xxx
301    if ((errstat = rwl_init(&dev->lock)) != 0) {
302       berrno be;
303       dev->dev_errno = errstat;
304       Mmsg1(dev->errmsg, _("Unable to init mutex: ERR=%s\n"), be.bstrerror(errstat));
305       Jmsg0(jcr, M_ERROR_TERM, 0, dev->errmsg);
306    }
307 #endif
308
309    dev->clear_opened();
310    dev->attached_dcrs = New(dlist(dcr, &dcr->dev_link));
311    Dmsg2(100, "init_dev: tape=%d dev_name=%s\n", dev->is_tape(), dev->dev_name);
312    dev->initiated = true;
313    
314    return dev;
315 }
316
317 /* default primitives are designed for file */
318 int DEVICE::d_open(const char *pathname, int flags)
319 {
320    return ::open(pathname, flags);
321 }
322
323 int DEVICE::d_close(int fd)
324 {
325    return ::close(fd);
326 }
327
328 int DEVICE::d_ioctl(int fd, ioctl_req_t request, char *mt_com)
329 {
330    return ::ioctl(fd, request, mt_com);
331 }
332
333 ssize_t DEVICE::d_read(int fd, void *buffer, size_t count)
334 {
335    return ::read(fd, buffer, count);
336 }
337
338 ssize_t DEVICE::d_write(int fd, const void *buffer, size_t count)
339 {
340    return ::write(fd, buffer, count);
341 }
342
343 /*
344  * Open the device with the operating system and
345  * initialize buffer pointers.
346  *
347  * Returns:  true on success
348  *           false on error
349  *
350  * Note, for a tape, the VolName is the name we give to the
351  *    volume (not really used here), but for a file, the
352  *    VolName represents the name of the file to be created/opened.
353  *    In the case of a file, the full name is the device name
354  *    (archive_name) with the VolName concatenated.
355  */
356 bool
357 DEVICE::open(DCR *dcr, int omode)
358 {
359    int preserve = 0;
360    if (is_open()) {
361       if (openmode == omode) {
362          return true;
363       } else {
364          d_close(m_fd);
365          clear_opened();
366          Dmsg0(100, "Close fd for mode change.\n");
367          preserve = state & (ST_LABEL|ST_APPEND|ST_READ);
368       }
369    }
370    if (dcr) {
371       dcr->setVolCatName(dcr->VolumeName);
372       VolCatInfo = dcr->VolCatInfo;    /* structure assign */
373    }
374
375    Dmsg4(100, "open dev: type=%d dev_name=%s vol=%s mode=%s\n", dev_type,
376          print_name(), getVolCatName(), mode_to_str(omode));
377    state &= ~(ST_LABEL|ST_APPEND|ST_READ|ST_EOT|ST_WEOT|ST_EOF);
378    label_type = B_BACULA_LABEL;
379
380    if (is_tape() || is_fifo()) {
381       open_tape_device(dcr, omode);
382    } else if (is_ftp()) {
383       open_device(dcr, omode);
384    } else {
385       Dmsg1(100, "call open_file_device mode=%s\n", mode_to_str(omode));
386       open_file_device(dcr, omode);
387    }
388    state |= preserve;                 /* reset any important state info */
389    Dmsg2(100, "preserve=0x%x fd=%d\n", preserve, m_fd);
390    return m_fd >= 0;
391 }
392
393 void DEVICE::set_mode(int new_mode) 
394 {
395    switch (new_mode) {
396    case CREATE_READ_WRITE:
397       mode = O_CREAT | O_RDWR | O_BINARY;
398       break;
399    case OPEN_READ_WRITE:
400       mode = O_RDWR | O_BINARY;
401       break;
402    case OPEN_READ_ONLY:
403       mode = O_RDONLY | O_BINARY;
404       break;
405    case OPEN_WRITE_ONLY:
406       mode = O_WRONLY | O_BINARY;
407       break;
408    default:
409       Emsg0(M_ABORT, 0, _("Illegal mode given to open dev.\n"));
410    }
411 }
412
413 /*
414  */
415 void DEVICE::open_tape_device(DCR *dcr, int omode) 
416 {
417    file_size = 0;
418    int timeout = max_open_wait;
419 #if !defined(HAVE_WIN32)
420    struct mtop mt_com;
421    utime_t start_time = time(NULL);
422 #endif
423
424    mount(1);                          /* do mount if required */
425
426    Dmsg0(100, "Open dev: device is tape\n");
427
428    get_autochanger_loaded_slot(dcr);
429
430    openmode = omode;
431    set_mode(omode);
432
433    if (timeout < 1) {
434       timeout = 1;
435    }
436    errno = 0;
437    if (is_fifo() && timeout) {
438       /* Set open timer */
439       tid = start_thread_timer(dcr->jcr, pthread_self(), timeout);
440    }
441    Dmsg2(100, "Try open %s mode=%s\n", print_name(), mode_to_str(omode));
442 #if defined(HAVE_WIN32)
443
444    /*   Windows Code */
445    if ((m_fd = d_open(dev_name, mode)) < 0) {
446       dev_errno = errno;
447    }
448
449 #else
450
451    /*  UNIX  Code */
452    /* If busy retry each second for max_open_wait seconds */
453    for ( ;; ) {
454       /* Try non-blocking open */
455       m_fd = d_open(dev_name, mode+O_NONBLOCK);
456       if (m_fd < 0) {
457          berrno be;
458          dev_errno = errno;
459          Dmsg5(100, "Open error on %s omode=%d mode=%x errno=%d: ERR=%s\n", 
460               print_name(), omode, mode, errno, be.bstrerror());
461       } else {
462          /* Tape open, now rewind it */
463          Dmsg0(100, "Rewind after open\n");
464          mt_com.mt_op = MTREW;
465          mt_com.mt_count = 1;
466          /* rewind only if dev is a tape */
467          if (is_tape() && (d_ioctl(m_fd, MTIOCTOP, (char *)&mt_com) < 0)) {
468             berrno be;
469             dev_errno = errno;           /* set error status from rewind */
470             d_close(m_fd);
471             clear_opened();
472             Dmsg2(100, "Rewind error on %s close: ERR=%s\n", print_name(),
473                   be.bstrerror(dev_errno));
474             /* If we get busy, device is probably rewinding, try again */
475             if (dev_errno != EBUSY) {
476                break;                    /* error -- no medium */
477             }
478          } else {
479             /* Got fd and rewind worked, so we must have medium in drive */
480             d_close(m_fd);
481             m_fd = d_open(dev_name, mode);  /* open normally */
482             if (m_fd < 0) {
483                berrno be;
484                dev_errno = errno;
485                Dmsg5(100, "Open error on %s omode=%d mode=%x errno=%d: ERR=%s\n", 
486                      print_name(), omode, mode, errno, be.bstrerror());
487                break;
488             }
489             dev_errno = 0;
490             lock_door();
491             set_os_device_parameters(dcr);       /* do system dependent stuff */
492             break;                               /* Successfully opened and rewound */
493          }
494       }
495       bmicrosleep(5, 0);
496       /* Exceed wait time ? */
497       if (time(NULL) - start_time >= max_open_wait) {
498          break;                       /* yes, get out */
499       }
500    }
501 #endif
502
503    if (!is_open()) {
504       berrno be;
505       Mmsg2(errmsg, _("Unable to open device %s: ERR=%s\n"),
506             print_name(), be.bstrerror(dev_errno));
507       Dmsg1(100, "%s", errmsg);
508    }
509
510    /* Stop any open() timer we started */
511    if (tid) {
512       stop_thread_timer(tid);
513       tid = 0;
514    }
515    Dmsg1(100, "open dev: tape %d opened\n", m_fd);
516 }
517
518 void DEVICE::open_device(DCR *dcr, int omode)
519 {
520    /* do nothing waiting to split open_file/tape_device */
521 }
522
523 /*
524  * Open a file device
525  */
526 void DEVICE::open_file_device(DCR *dcr, int omode) 
527 {
528    POOL_MEM archive_name(PM_FNAME);
529
530    get_autochanger_loaded_slot(dcr);
531
532    /*
533     * Handle opening of File Archive (not a tape)
534     */     
535
536    pm_strcpy(archive_name, dev_name);
537    /*  
538     * If this is a virtual autochanger (i.e. changer_res != NULL)
539     *  we simply use the device name, assuming it has been
540     *  appropriately setup by the "autochanger".
541     */
542    if (!device->changer_res || device->changer_command[0] == 0) {
543       if (VolCatInfo.VolCatName[0] == 0) {
544          Mmsg(errmsg, _("Could not open file device %s. No Volume name given.\n"),
545             print_name());
546          clear_opened();
547          return;
548       }
549
550       if (!IsPathSeparator(archive_name.c_str()[strlen(archive_name.c_str())-1])) {
551          pm_strcat(archive_name, "/");
552       }
553       pm_strcat(archive_name, getVolCatName());
554    }
555
556    mount(1);                          /* do mount if required */
557          
558    openmode = omode;
559    set_mode(omode);
560    /* If creating file, give 0640 permissions */
561    Dmsg3(100, "open disk: mode=%s open(%s, 0x%x, 0640)\n", mode_to_str(omode), 
562          archive_name.c_str(), mode);
563    /* Use system open() */
564    if ((m_fd = ::open(archive_name.c_str(), mode, 0640)) < 0) {
565       berrno be;
566       dev_errno = errno;
567       Mmsg2(errmsg, _("Could not open: %s, ERR=%s\n"), archive_name.c_str(), 
568             be.bstrerror());
569       Dmsg1(100, "open failed: %s", errmsg);
570    }
571    if (m_fd >= 0) {
572       dev_errno = 0;
573       file = 0;
574       file_addr = 0;
575    }
576    Dmsg4(100, "open dev: disk fd=%d opened, part=%d/%d, part_size=%u\n", 
577       m_fd, part, num_dvd_parts, part_size);
578 }
579
580 /*
581  * Rewind the device.
582  *  Returns: true  on success
583  *           false on failure
584  */
585 bool DEVICE::rewind(DCR *dcr)
586 {
587    struct mtop mt_com;
588    unsigned int i;
589    bool first = true;
590
591    Dmsg3(400, "rewind res=%d fd=%d %s\n", num_reserved(), m_fd, print_name());
592    state &= ~(ST_EOT|ST_EOF|ST_WEOT);  /* remove EOF/EOT flags */
593    block_num = file = 0;
594    file_size = 0;
595    file_addr = 0;
596    if (m_fd < 0) {
597       return false;
598    }
599    if (is_tape()) {
600       mt_com.mt_op = MTREW;
601       mt_com.mt_count = 1;
602       /* If we get an I/O error on rewind, it is probably because
603        * the drive is actually busy. We loop for (about 5 minutes)
604        * retrying every 5 seconds.
605        */
606       for (i=max_rewind_wait; ; i -= 5) {
607          if (d_ioctl(m_fd, MTIOCTOP, (char *)&mt_com) < 0) {
608             berrno be;
609             clrerror(MTREW);
610             if (i == max_rewind_wait) {
611                Dmsg1(200, "Rewind error, %s. retrying ...\n", be.bstrerror());
612             }
613             /*
614              * This is a gross hack, because if the user has the
615              *   device mounted (i.e. open), then uses mtx to load
616              *   a tape, the current open file descriptor is invalid.
617              *   So, we close the drive and re-open it.
618              */
619             if (first && dcr) {
620                int open_mode = openmode;
621                d_close(m_fd);
622                clear_opened();
623                open(dcr, open_mode);
624                if (m_fd < 0) {
625                   return false;
626                }
627                first = false;
628                continue;
629             }
630 #ifdef HAVE_SUN_OS
631             if (dev_errno == EIO) {         
632                Mmsg1(errmsg, _("No tape loaded or drive offline on %s.\n"), print_name());
633                return false;
634             }
635 #else
636             if (dev_errno == EIO && i > 0) {
637                Dmsg0(200, "Sleeping 5 seconds.\n");
638                bmicrosleep(5, 0);
639                continue;
640             }
641 #endif
642             Mmsg2(errmsg, _("Rewind error on %s. ERR=%s.\n"),
643                print_name(), be.bstrerror());
644             return false;
645          }
646          break;
647       }
648    } else if (is_file()) {
649       if (lseek(dcr, (boffset_t)0, SEEK_SET) < 0) {
650          berrno be;
651          dev_errno = errno;
652          Mmsg2(errmsg, _("lseek error on %s. ERR=%s.\n"),
653             print_name(), be.bstrerror());
654          return false;
655       }
656    }
657    return true;
658 }
659
660
661 /*
662  * Called to indicate that we have just read an
663  *  EOF from the device.
664  */
665 void DEVICE::set_ateof() 
666
667    set_eof();
668    if (is_tape()) {
669       file++;
670    }
671    file_addr = 0;
672    file_size = 0;
673    block_num = 0;
674 }
675
676 /*
677  * Called to indicate we are now at the end of the tape, and
678  *   writing is not possible.
679  */
680 void DEVICE::set_ateot() 
681 {
682    /* Make tape effectively read-only */
683    state |= (ST_EOF|ST_EOT|ST_WEOT);
684    clear_append();
685 }
686
687 /*
688  * Position device to end of medium (end of data)
689  *  Returns: true  on succes
690  *           false on error
691  */
692 bool DEVICE::eod(DCR *dcr)
693 {
694    struct mtop mt_com;
695    bool ok = true;
696    boffset_t pos;
697    int32_t os_file;
698
699    if (m_fd < 0) {
700       dev_errno = EBADF;
701       Mmsg1(errmsg, _("Bad call to eod. Device %s not open\n"), print_name());
702       return false;
703    }
704
705 #if defined (__digital__) && defined (__unix__)
706    return fsf(VolCatInfo.VolCatFiles);
707 #endif
708
709    Dmsg0(100, "Enter eod\n");
710    if (at_eot()) {
711       return true;
712    }
713    clear_eof();         /* remove EOF flag */
714    block_num = file = 0;
715    file_size = 0;
716    file_addr = 0;
717    if (is_fifo()) {
718       return true;
719    }
720    if (!is_tape()) {
721       pos = lseek(dcr, (boffset_t)0, SEEK_END);
722       Dmsg1(200, "====== Seek to %lld\n", pos);
723       if (pos >= 0) {
724          update_pos(dcr);
725          set_eot();
726          return true;
727       }
728       dev_errno = errno;
729       berrno be;
730       Mmsg2(errmsg, _("lseek error on %s. ERR=%s.\n"),
731              print_name(), be.bstrerror());
732       Dmsg0(100, errmsg);
733       return false;
734    }
735 #ifdef MTEOM
736    if (has_cap(CAP_FASTFSF) && !has_cap(CAP_EOM)) {
737       Dmsg0(100,"Using FAST FSF for EOM\n");
738       /* If unknown position, rewind */
739       if (get_os_tape_file() < 0) {
740         if (!rewind(NULL)) {
741           Dmsg0(100, "Rewind error\n");
742           return false;
743         }
744       }
745       mt_com.mt_op = MTFSF;
746       /*
747        * ***FIXME*** fix code to handle case that INT16_MAX is
748        *   not large enough.
749        */
750       mt_com.mt_count = INT16_MAX;    /* use big positive number */
751       if (mt_com.mt_count < 0) {
752          mt_com.mt_count = INT16_MAX; /* brain damaged system */
753       }
754    }
755
756    if (has_cap(CAP_MTIOCGET) && (has_cap(CAP_FASTFSF) || has_cap(CAP_EOM))) {
757       if (has_cap(CAP_EOM)) {
758          Dmsg0(100,"Using EOM for EOM\n");
759          mt_com.mt_op = MTEOM;
760          mt_com.mt_count = 1;
761       }
762
763       if (d_ioctl(m_fd, MTIOCTOP, (char *)&mt_com) < 0) {
764          berrno be;
765          clrerror(mt_com.mt_op);
766          Dmsg1(50, "ioctl error: %s\n", be.bstrerror());
767          update_pos(dcr);
768          Mmsg2(errmsg, _("ioctl MTEOM error on %s. ERR=%s.\n"),
769             print_name(), be.bstrerror());
770          Dmsg0(100, errmsg);
771          return false;
772       }
773
774       os_file = get_os_tape_file();
775       if (os_file < 0) {
776          berrno be;
777          clrerror(-1);
778          Mmsg2(errmsg, _("ioctl MTIOCGET error on %s. ERR=%s.\n"),
779             print_name(), be.bstrerror());
780          Dmsg0(100, errmsg);
781          return false;
782       }
783       Dmsg1(100, "EOD file=%d\n", os_file);
784       set_ateof();
785       file = os_file;
786    } else {
787 #else
788    {
789 #endif
790       /*
791        * Rewind then use FSF until EOT reached
792        */
793       if (!rewind(NULL)) {
794          Dmsg0(100, "Rewind error.\n");
795          return false;
796       }
797       /*
798        * Move file by file to the end of the tape
799        */
800       int file_num;
801       for (file_num=file; !at_eot(); file_num++) {
802          Dmsg0(200, "eod: doing fsf 1\n");
803          if (!fsf(1)) {
804             Dmsg0(100, "fsf error.\n");
805             return false;
806          }
807          /*
808           * Avoid infinite loop by ensuring we advance.
809           */
810          if (!at_eot() && file_num == (int)file) {
811             Dmsg1(100, "fsf did not advance from file %d\n", file_num);
812             set_ateof();
813             os_file = get_os_tape_file();
814             if (os_file >= 0) {
815                Dmsg2(100, "Adjust file from %d to %d\n", file_num, os_file);
816                file = os_file;
817             }       
818             break;
819          }
820       }
821    }
822    /*
823     * Some drivers leave us after second EOF when doing
824     * MTEOM, so we must backup so that appending overwrites
825     * the second EOF.
826     */
827    if (has_cap(CAP_BSFATEOM)) {
828       /* Backup over EOF */
829       ok = bsf(1);
830       /* If BSF worked and fileno is known (not -1), set file */
831       os_file = get_os_tape_file();
832       if (os_file >= 0) {
833          Dmsg2(100, "BSFATEOF adjust file from %d to %d\n", file , os_file);
834          file = os_file;
835       } else {
836          file++;                       /* wing it -- not correct on all OSes */
837       }
838    } else {
839       update_pos(dcr);                 /* update position */
840    }
841    Dmsg1(200, "EOD dev->file=%d\n", file);
842    return ok;
843 }
844
845 /*
846  * Set the position of the device -- only for files and DVD
847  *   For other devices, there is no generic way to do it.
848  *  Returns: true  on succes
849  *           false on error
850  */
851 bool DEVICE::update_pos(DCR *dcr)
852 {
853    boffset_t pos;
854    bool ok = true;
855
856    if (!is_open()) {
857       dev_errno = EBADF;
858       Mmsg0(errmsg, _("Bad device call. Device not open\n"));
859       Emsg1(M_FATAL, 0, "%s", errmsg);
860       return false;
861    }
862
863    if (is_file()) {
864       file = 0;
865       file_addr = 0;
866       pos = lseek(dcr, (boffset_t)0, SEEK_CUR);
867       if (pos < 0) {
868          berrno be;
869          dev_errno = errno;
870          Pmsg1(000, _("Seek error: ERR=%s\n"), be.bstrerror());
871          Mmsg2(errmsg, _("lseek error on %s. ERR=%s.\n"),
872                print_name(), be.bstrerror());
873          ok = false;
874       } else {
875          file_addr = pos;
876          block_num = (uint32_t)pos;
877          file = (uint32_t)(pos >> 32);
878       }
879    }
880    return ok;
881 }
882
883 /*
884  * Return the status of the device.  This was meant
885  * to be a generic routine. Unfortunately, it doesn't
886  * seem possible (at least I do not know how to do it
887  * currently), which means that for the moment, this
888  * routine has very little value.
889  *
890  *   Returns: status
891  */
892 uint32_t status_dev(DEVICE *dev)
893 {
894    struct mtget mt_stat;
895    uint32_t stat = 0;
896
897    if (dev->state & (ST_EOT | ST_WEOT)) {
898       stat |= BMT_EOD;
899       Pmsg0(-20, " EOD");
900    }
901    if (dev->state & ST_EOF) {
902       stat |= BMT_EOF;
903       Pmsg0(-20, " EOF");
904    }
905    if (dev->is_tape()) {
906       stat |= BMT_TAPE;
907       Pmsg0(-20,_(" Bacula status:"));
908       Pmsg2(-20,_(" file=%d block=%d\n"), dev->file, dev->block_num);
909       if (dev->d_ioctl(dev->fd(), MTIOCGET, (char *)&mt_stat) < 0) {
910          berrno be;
911          dev->dev_errno = errno;
912          Mmsg2(dev->errmsg, _("ioctl MTIOCGET error on %s. ERR=%s.\n"),
913             dev->print_name(), be.bstrerror());
914          return 0;
915       }
916       Pmsg0(-20, _(" Device status:"));
917
918 #if defined(HAVE_LINUX_OS)
919       if (GMT_EOF(mt_stat.mt_gstat)) {
920          stat |= BMT_EOF;
921          Pmsg0(-20, " EOF");
922       }
923       if (GMT_BOT(mt_stat.mt_gstat)) {
924          stat |= BMT_BOT;
925          Pmsg0(-20, " BOT");
926       }
927       if (GMT_EOT(mt_stat.mt_gstat)) {
928          stat |= BMT_EOT;
929          Pmsg0(-20, " EOT");
930       }
931       if (GMT_SM(mt_stat.mt_gstat)) {
932          stat |= BMT_SM;
933          Pmsg0(-20, " SM");
934       }
935       if (GMT_EOD(mt_stat.mt_gstat)) {
936          stat |= BMT_EOD;
937          Pmsg0(-20, " EOD");
938       }
939       if (GMT_WR_PROT(mt_stat.mt_gstat)) {
940          stat |= BMT_WR_PROT;
941          Pmsg0(-20, " WR_PROT");
942       }
943       if (GMT_ONLINE(mt_stat.mt_gstat)) {
944          stat |= BMT_ONLINE;
945          Pmsg0(-20, " ONLINE");
946       }
947       if (GMT_DR_OPEN(mt_stat.mt_gstat)) {
948          stat |= BMT_DR_OPEN;
949          Pmsg0(-20, " DR_OPEN");
950       }
951       if (GMT_IM_REP_EN(mt_stat.mt_gstat)) {
952          stat |= BMT_IM_REP_EN;
953          Pmsg0(-20, " IM_REP_EN");
954       }
955 #elif defined(HAVE_WIN32)
956       if (GMT_EOF(mt_stat.mt_gstat)) {
957          stat |= BMT_EOF;
958          Pmsg0(-20, " EOF");
959       }
960       if (GMT_BOT(mt_stat.mt_gstat)) {
961          stat |= BMT_BOT;
962          Pmsg0(-20, " BOT");
963       }
964       if (GMT_EOT(mt_stat.mt_gstat)) {
965          stat |= BMT_EOT;
966          Pmsg0(-20, " EOT");
967       }
968       if (GMT_EOD(mt_stat.mt_gstat)) {
969          stat |= BMT_EOD;
970          Pmsg0(-20, " EOD");
971       }
972       if (GMT_WR_PROT(mt_stat.mt_gstat)) {
973          stat |= BMT_WR_PROT;
974          Pmsg0(-20, " WR_PROT");
975       }
976       if (GMT_ONLINE(mt_stat.mt_gstat)) {
977          stat |= BMT_ONLINE;
978          Pmsg0(-20, " ONLINE");
979       }
980       if (GMT_DR_OPEN(mt_stat.mt_gstat)) {
981          stat |= BMT_DR_OPEN;
982          Pmsg0(-20, " DR_OPEN");
983       }
984       if (GMT_IM_REP_EN(mt_stat.mt_gstat)) {
985          stat |= BMT_IM_REP_EN;
986          Pmsg0(-20, " IM_REP_EN");
987       }
988
989 #endif /* !SunOS && !OSF */
990       if (dev->has_cap(CAP_MTIOCGET)) {
991          Pmsg2(-20, _(" file=%d block=%d\n"), mt_stat.mt_fileno, mt_stat.mt_blkno);
992       } else {
993          Pmsg2(-20, _(" file=%d block=%d\n"), -1, -1);
994       }
995    } else {
996       stat |= BMT_ONLINE | BMT_BOT;
997    }
998    return stat;
999 }
1000
1001
1002 /*
1003  * Load medium in device
1004  *  Returns: true  on success
1005  *           false on failure
1006  */
1007 bool load_dev(DEVICE *dev)
1008 {
1009 #ifdef MTLOAD
1010    struct mtop mt_com;
1011 #endif
1012
1013    if (dev->fd() < 0) {
1014       dev->dev_errno = EBADF;
1015       Mmsg0(dev->errmsg, _("Bad call to load_dev. Device not open\n"));
1016       Emsg0(M_FATAL, 0, dev->errmsg);
1017       return false;
1018    }
1019    if (!(dev->is_tape())) {
1020       return true;
1021    }
1022 #ifndef MTLOAD
1023    Dmsg0(200, "stored: MTLOAD command not available\n");
1024    berrno be;
1025    dev->dev_errno = ENOTTY;           /* function not available */
1026    Mmsg2(dev->errmsg, _("ioctl MTLOAD error on %s. ERR=%s.\n"),
1027          dev->print_name(), be.bstrerror());
1028    return false;
1029 #else
1030
1031    dev->block_num = dev->file = 0;
1032    dev->file_size = 0;
1033    dev->file_addr = 0;
1034    mt_com.mt_op = MTLOAD;
1035    mt_com.mt_count = 1;
1036    if (dev->d_ioctl(dev->fd(), MTIOCTOP, (char *)&mt_com) < 0) {
1037       berrno be;
1038       dev->dev_errno = errno;
1039       Mmsg2(dev->errmsg, _("ioctl MTLOAD error on %s. ERR=%s.\n"),
1040          dev->print_name(), be.bstrerror());
1041       return false;
1042    }
1043    return true;
1044 #endif
1045 }
1046
1047 /*
1048  * Rewind device and put it offline
1049  *  Returns: true  on success
1050  *           false on failure
1051  */
1052 bool DEVICE::offline()
1053 {
1054    struct mtop mt_com;
1055
1056    if (!is_tape()) {
1057       return true;                    /* device not open */
1058    }
1059
1060    state &= ~(ST_APPEND|ST_READ|ST_EOT|ST_EOF|ST_WEOT);  /* remove EOF/EOT flags */
1061    block_num = file = 0;
1062    file_size = 0;
1063    file_addr = 0;
1064    unlock_door();
1065    mt_com.mt_op = MTOFFL;
1066    mt_com.mt_count = 1;
1067    if (d_ioctl(m_fd, MTIOCTOP, (char *)&mt_com) < 0) {
1068       berrno be;
1069       dev_errno = errno;
1070       Mmsg2(errmsg, _("ioctl MTOFFL error on %s. ERR=%s.\n"),
1071          print_name(), be.bstrerror());
1072       return false;
1073    }
1074    Dmsg1(100, "Offlined device %s\n", print_name());
1075    return true;
1076 }
1077
1078 bool DEVICE::offline_or_rewind()
1079 {
1080    if (m_fd < 0) {
1081       return false;
1082    }
1083    if (has_cap(CAP_OFFLINEUNMOUNT)) {
1084       return offline();
1085    } else {
1086    /*
1087     * Note, this rewind probably should not be here (it wasn't
1088     *  in prior versions of Bacula), but on FreeBSD, this is
1089     *  needed in the case the tape was "frozen" due to an error
1090     *  such as backspacing after writing and EOF. If it is not
1091     *  done, all future references to the drive get and I/O error.
1092     */
1093       clrerror(MTREW);
1094       return rewind(NULL);
1095    }
1096 }
1097
1098 /*
1099  * Foward space a file
1100  *   Returns: true  on success
1101  *            false on failure
1102  */
1103 bool DEVICE::fsf(int num)
1104 {
1105    int32_t os_file = 0;
1106    struct mtop mt_com;
1107    int stat = 0;
1108
1109    if (!is_open()) {
1110       dev_errno = EBADF;
1111       Mmsg0(errmsg, _("Bad call to fsf. Device not open\n"));
1112       Emsg0(M_FATAL, 0, errmsg);
1113       return false;
1114    }
1115
1116    if (!is_tape()) {
1117       return true;
1118    }
1119
1120    if (at_eot()) {
1121       dev_errno = 0;
1122       Mmsg1(errmsg, _("Device %s at End of Tape.\n"), print_name());
1123       return false;
1124    }
1125    if (at_eof()) {
1126       Dmsg0(200, "ST_EOF set on entry to FSF\n");
1127    }
1128
1129    Dmsg0(100, "fsf\n");
1130    block_num = 0;
1131    /*
1132     * If Fast forward space file is set, then we
1133     *  use MTFSF to forward space and MTIOCGET
1134     *  to get the file position. We assume that
1135     *  the SCSI driver will ensure that we do not
1136     *  forward space past the end of the medium.
1137     */
1138    if (has_cap(CAP_FSF) && has_cap(CAP_MTIOCGET) && has_cap(CAP_FASTFSF)) {
1139       int my_errno = 0;
1140       mt_com.mt_op = MTFSF;
1141       mt_com.mt_count = num;
1142       stat = d_ioctl(m_fd, MTIOCTOP, (char *)&mt_com);
1143       if (stat < 0) {
1144          my_errno = errno;            /* save errno */
1145       } else if ((os_file=get_os_tape_file()) < 0) {
1146          my_errno = errno;            /* save errno */
1147       }
1148       if (my_errno != 0) {
1149          berrno be;
1150          set_eot();
1151          Dmsg0(200, "Set ST_EOT\n");
1152          clrerror(MTFSF);
1153          Mmsg2(errmsg, _("ioctl MTFSF error on %s. ERR=%s.\n"),
1154             print_name(), be.bstrerror(my_errno));
1155          Dmsg1(200, "%s", errmsg);
1156          return false;
1157       }
1158
1159       Dmsg1(200, "fsf file=%d\n", os_file);
1160       set_ateof();
1161       file = os_file;
1162       return true;
1163
1164    /*
1165     * Here if CAP_FSF is set, and virtually all drives
1166     *  these days support it, we read a record, then forward
1167     *  space one file. Using this procedure, which is slow,
1168     *  is the only way we can be sure that we don't read
1169     *  two consecutive EOF marks, which means End of Data.
1170     */
1171    } else if (has_cap(CAP_FSF)) {
1172       POOLMEM *rbuf;
1173       int rbuf_len;
1174       Dmsg0(200, "FSF has cap_fsf\n");
1175       if (max_block_size == 0) {
1176          rbuf_len = DEFAULT_BLOCK_SIZE;
1177       } else {
1178          rbuf_len = max_block_size;
1179       }
1180       rbuf = get_memory(rbuf_len);
1181       mt_com.mt_op = MTFSF;
1182       mt_com.mt_count = 1;
1183       while (num-- && !at_eot()) {
1184          Dmsg0(100, "Doing read before fsf\n");
1185          if ((stat = this->read((char *)rbuf, rbuf_len)) < 0) {
1186             if (errno == ENOMEM) {     /* tape record exceeds buf len */
1187                stat = rbuf_len;        /* This is OK */
1188             /*
1189              * On IBM drives, they return ENOSPC at EOM
1190              *  instead of EOF status
1191              */
1192             } else if (at_eof() && errno == ENOSPC) {
1193                stat = 0;
1194             } else {
1195                berrno be;
1196                set_eot();
1197                clrerror(-1);
1198                Dmsg2(100, "Set ST_EOT read errno=%d. ERR=%s\n", dev_errno,
1199                   be.bstrerror());
1200                Mmsg2(errmsg, _("read error on %s. ERR=%s.\n"),
1201                   print_name(), be.bstrerror());
1202                Dmsg1(100, "%s", errmsg);
1203                break;
1204             }
1205          }
1206          if (stat == 0) {                /* EOF */
1207             Dmsg1(100, "End of File mark from read. File=%d\n", file+1);
1208             /* Two reads of zero means end of tape */
1209             if (at_eof()) {
1210                set_eot();
1211                Dmsg0(100, "Set ST_EOT\n");
1212                break;
1213             } else {
1214                set_ateof();
1215                continue;
1216             }
1217          } else {                        /* Got data */
1218             clear_eot();
1219             clear_eof();
1220          }
1221
1222          Dmsg0(100, "Doing MTFSF\n");
1223          stat = d_ioctl(m_fd, MTIOCTOP, (char *)&mt_com);
1224          if (stat < 0) {                 /* error => EOT */
1225             berrno be;
1226             set_eot();
1227             Dmsg0(100, "Set ST_EOT\n");
1228             clrerror(MTFSF);
1229             Mmsg2(errmsg, _("ioctl MTFSF error on %s. ERR=%s.\n"),
1230                print_name(), be.bstrerror());
1231             Dmsg0(100, "Got < 0 for MTFSF\n");
1232             Dmsg1(100, "%s", errmsg);
1233          } else {
1234             set_ateof();
1235          }
1236       }
1237       free_memory(rbuf);
1238
1239    /*
1240     * No FSF, so use FSR to simulate it
1241     */
1242    } else {
1243       Dmsg0(200, "Doing FSR for FSF\n");
1244       while (num-- && !at_eot()) {
1245          fsr(INT32_MAX);    /* returns -1 on EOF or EOT */
1246       }
1247       if (at_eot()) {
1248          dev_errno = 0;
1249          Mmsg1(errmsg, _("Device %s at End of Tape.\n"), print_name());
1250          stat = -1;
1251       } else {
1252          stat = 0;
1253       }
1254    }
1255    Dmsg1(200, "Return %d from FSF\n", stat);
1256    if (at_eof()) {
1257       Dmsg0(200, "ST_EOF set on exit FSF\n");
1258    }
1259    if (at_eot()) {
1260       Dmsg0(200, "ST_EOT set on exit FSF\n");
1261    }
1262    Dmsg1(200, "Return from FSF file=%d\n", file);
1263    return stat == 0;
1264 }
1265
1266 /*
1267  * Backward space a file
1268  *  Returns: false on failure
1269  *           true  on success
1270  */
1271 bool DEVICE::bsf(int num)
1272 {
1273    struct mtop mt_com;
1274    int stat;
1275
1276    if (!is_open()) {
1277       dev_errno = EBADF;
1278       Mmsg0(errmsg, _("Bad call to bsf. Device not open\n"));
1279       Emsg0(M_FATAL, 0, errmsg);
1280       return false;
1281    }
1282
1283    if (!is_tape()) {
1284       Mmsg1(errmsg, _("Device %s cannot BSF because it is not a tape.\n"),
1285          print_name());
1286       return false;
1287    }
1288
1289    Dmsg0(100, "bsf\n");
1290    clear_eot();
1291    clear_eof();
1292    file -= num;
1293    file_addr = 0;
1294    file_size = 0;
1295    mt_com.mt_op = MTBSF;
1296    mt_com.mt_count = num;
1297    stat = d_ioctl(m_fd, MTIOCTOP, (char *)&mt_com);
1298    if (stat < 0) {
1299       berrno be;
1300       clrerror(MTBSF);
1301       Mmsg2(errmsg, _("ioctl MTBSF error on %s. ERR=%s.\n"),
1302          print_name(), be.bstrerror());
1303    }
1304    return stat == 0;
1305 }
1306
1307
1308 /*
1309  * Foward space num records
1310  *  Returns: false on failure
1311  *           true  on success
1312  */
1313 bool DEVICE::fsr(int num)
1314 {
1315    struct mtop mt_com;
1316    int stat;
1317
1318    if (!is_open()) {
1319       dev_errno = EBADF;
1320       Mmsg0(errmsg, _("Bad call to fsr. Device not open\n"));
1321       Emsg0(M_FATAL, 0, errmsg);
1322       return false;
1323    }
1324
1325    if (!is_tape()) {
1326       return false;
1327    }
1328
1329    if (!has_cap(CAP_FSR)) {
1330       Mmsg1(errmsg, _("ioctl MTFSR not permitted on %s.\n"), print_name());
1331       return false;
1332    }
1333
1334    Dmsg1(100, "fsr %d\n", num);
1335    mt_com.mt_op = MTFSR;
1336    mt_com.mt_count = num;
1337    stat = d_ioctl(m_fd, MTIOCTOP, (char *)&mt_com);
1338    if (stat == 0) {
1339       clear_eof();
1340       block_num += num;
1341    } else {
1342       berrno be;
1343       struct mtget mt_stat;
1344       clrerror(MTFSR);
1345       Dmsg1(100, "FSF fail: ERR=%s\n", be.bstrerror());
1346       if (dev_get_os_pos(this, &mt_stat)) {
1347          Dmsg4(100, "Adjust from %d:%d to %d:%d\n", file,
1348             block_num, mt_stat.mt_fileno, mt_stat.mt_blkno);
1349          file = mt_stat.mt_fileno;
1350          block_num = mt_stat.mt_blkno;
1351       } else {
1352          if (at_eof()) {
1353             set_eot();
1354          } else {
1355             set_ateof();
1356          }
1357       }
1358       Mmsg3(errmsg, _("ioctl MTFSR %d error on %s. ERR=%s.\n"),
1359          num, print_name(), be.bstrerror());
1360    }
1361    return stat == 0;
1362 }
1363
1364 /*
1365  * Backward space a record
1366  *   Returns:  false on failure
1367  *             true  on success
1368  */
1369 bool DEVICE::bsr(int num)
1370 {
1371    struct mtop mt_com;
1372    int stat;
1373
1374    if (!is_open()) {
1375       dev_errno = EBADF;
1376       Mmsg0(errmsg, _("Bad call to bsr_dev. Device not open\n"));
1377       Emsg0(M_FATAL, 0, errmsg);
1378       return false;
1379    }
1380
1381    if (!is_tape()) {
1382       return false;
1383    }
1384
1385    if (!has_cap(CAP_BSR)) {
1386       Mmsg1(errmsg, _("ioctl MTBSR not permitted on %s.\n"), print_name());
1387       return false;
1388    }
1389
1390    Dmsg0(100, "bsr_dev\n");
1391    block_num -= num;
1392    clear_eof();
1393    clear_eot();
1394    mt_com.mt_op = MTBSR;
1395    mt_com.mt_count = num;
1396    stat = d_ioctl(m_fd, MTIOCTOP, (char *)&mt_com);
1397    if (stat < 0) {
1398       berrno be;
1399       clrerror(MTBSR);
1400       Mmsg2(errmsg, _("ioctl MTBSR error on %s. ERR=%s.\n"),
1401          print_name(), be.bstrerror());
1402    }
1403    return stat == 0;
1404 }
1405
1406 void DEVICE::lock_door()
1407 {
1408 #ifdef MTLOCK
1409    struct mtop mt_com;
1410    mt_com.mt_op = MTLOCK;
1411    mt_com.mt_count = 1;
1412    d_ioctl(m_fd, MTIOCTOP, (char *)&mt_com);
1413 #endif
1414 }
1415
1416 void DEVICE::unlock_door()
1417 {
1418 #ifdef MTUNLOCK
1419    struct mtop mt_com;
1420    mt_com.mt_op = MTUNLOCK;
1421    mt_com.mt_count = 1;
1422    d_ioctl(m_fd, MTIOCTOP, (char *)&mt_com);
1423 #endif
1424 }
1425
1426 void DEVICE::set_slot(int32_t slot)
1427
1428    m_slot = slot; 
1429    if (vol) vol->clear_slot();
1430 }
1431
1432 void DEVICE::clear_slot()
1433
1434    m_slot = -1; 
1435    if (vol) vol->set_slot(-1);
1436 }
1437
1438  
1439
1440 /*
1441  * Reposition the device to file, block
1442  * Returns: false on failure
1443  *          true  on success
1444  */
1445 bool DEVICE::reposition(DCR *dcr, uint32_t rfile, uint32_t rblock)
1446 {
1447    if (!is_open()) {
1448       dev_errno = EBADF;
1449       Mmsg0(errmsg, _("Bad call to reposition. Device not open\n"));
1450       Emsg0(M_FATAL, 0, errmsg);
1451       return false;
1452    }
1453
1454    if (!is_tape()) {
1455       boffset_t pos = (((boffset_t)rfile)<<32) | rblock;
1456       Dmsg1(100, "===== lseek to %d\n", (int)pos);
1457       if (lseek(dcr, pos, SEEK_SET) == (boffset_t)-1) {
1458          berrno be;
1459          dev_errno = errno;
1460          Mmsg2(errmsg, _("lseek error on %s. ERR=%s.\n"),
1461             print_name(), be.bstrerror());
1462          return false;
1463       }
1464       file = rfile;
1465       block_num = rblock;
1466       file_addr = pos;
1467       return true;
1468    }
1469
1470    /* After this point, we are tape only */
1471    Dmsg4(100, "reposition from %u:%u to %u:%u\n", file, block_num, rfile, rblock);
1472    if (rfile < file) {
1473       Dmsg0(100, "Rewind\n");
1474       if (!rewind(NULL)) {
1475          return false;
1476       }
1477    }
1478    if (rfile > file) {
1479       Dmsg1(100, "fsf %d\n", rfile-file);
1480       if (!fsf(rfile-file)) {
1481          Dmsg1(100, "fsf failed! ERR=%s\n", bstrerror());
1482          return false;
1483       }
1484       Dmsg2(100, "wanted_file=%d at_file=%d\n", rfile, file);
1485    }
1486    if (rblock < block_num) {
1487       Dmsg2(100, "wanted_blk=%d at_blk=%d\n", rblock, block_num);
1488       Dmsg0(100, "bsf 1\n");
1489       bsf(1);
1490       Dmsg0(100, "fsf 1\n");
1491       fsf(1);
1492       Dmsg2(100, "wanted_blk=%d at_blk=%d\n", rblock, block_num);
1493    }
1494    if (has_cap(CAP_POSITIONBLOCKS) && rblock > block_num) {
1495       /* Ignore errors as Bacula can read to the correct block */
1496       Dmsg1(100, "fsr %d\n", rblock-block_num);
1497       return fsr(rblock-block_num);
1498    } else {
1499       while (rblock > block_num) {
1500          if (!read_block_from_dev(dcr, NO_BLOCK_NUMBER_CHECK)) {
1501             berrno be;
1502             dev_errno = errno;
1503             Dmsg2(30, "Failed to find requested block on %s: ERR=%s",
1504                print_name(), be.bstrerror());
1505             return false;
1506          }
1507          Dmsg2(300, "moving forward wanted_blk=%d at_blk=%d\n", rblock, block_num);
1508       }
1509    }
1510    return true;
1511 }
1512
1513
1514
1515 /*
1516  * Write an end of file on the device
1517  *   Returns: true on success
1518  *            false on failure
1519  */
1520 bool DEVICE::weof(int num)
1521 {
1522    struct mtop mt_com;
1523    int stat;
1524    Dmsg1(129, "=== weof_dev=%s\n", print_name());
1525    
1526    if (!is_open()) {
1527       dev_errno = EBADF;
1528       Mmsg0(errmsg, _("Bad call to weof_dev. Device not open\n"));
1529       Emsg0(M_FATAL, 0, errmsg);
1530       return false;
1531    }
1532    file_size = 0;
1533
1534    if (!is_tape()) {
1535       return true;
1536    }
1537    if (!can_append()) {
1538       Mmsg0(errmsg, _("Attempt to WEOF on non-appendable Volume\n"));
1539       Emsg0(M_FATAL, 0, errmsg);
1540       return false;
1541    }
1542       
1543    clear_eof();
1544    clear_eot();
1545    mt_com.mt_op = MTWEOF;
1546    mt_com.mt_count = num;
1547    stat = d_ioctl(m_fd, MTIOCTOP, (char *)&mt_com);
1548    if (stat == 0) {
1549       block_num = 0;
1550       file += num;
1551       file_addr = 0;
1552    } else {
1553       berrno be;
1554       clrerror(MTWEOF);
1555       if (stat == -1) {
1556          Mmsg2(errmsg, _("ioctl MTWEOF error on %s. ERR=%s.\n"),
1557             print_name(), be.bstrerror());
1558        }
1559    }
1560    return stat == 0;
1561 }
1562
1563
1564 /*
1565  * If implemented in system, clear the tape
1566  * error status.
1567  */
1568 void DEVICE::clrerror(int func)
1569 {
1570    const char *msg = NULL;
1571    char buf[100];
1572
1573    dev_errno = errno;         /* save errno */
1574    if (errno == EIO) {
1575       VolCatInfo.VolCatErrors++;
1576    }
1577
1578    if (!is_tape()) {
1579       return;
1580    }
1581
1582    if (errno == ENOTTY || errno == ENOSYS) { /* Function not implemented */
1583       switch (func) {
1584       case -1:
1585          break;                  /* ignore message printed later */
1586       case MTWEOF:
1587          msg = "WTWEOF";
1588          clear_cap(CAP_EOF);     /* turn off feature */
1589          break;
1590 #ifdef MTEOM
1591       case MTEOM:
1592          msg = "WTEOM";
1593          clear_cap(CAP_EOM);     /* turn off feature */
1594          break;
1595 #endif
1596       case MTFSF:
1597          msg = "MTFSF";
1598          clear_cap(CAP_FSF);     /* turn off feature */
1599          break;
1600       case MTBSF:
1601          msg = "MTBSF";
1602          clear_cap(CAP_BSF);     /* turn off feature */
1603          break;
1604       case MTFSR:
1605          msg = "MTFSR";
1606          clear_cap(CAP_FSR);     /* turn off feature */
1607          break;
1608       case MTBSR:
1609          msg = "MTBSR";
1610          clear_cap(CAP_BSR);     /* turn off feature */
1611          break;
1612       case MTREW:
1613          msg = "MTREW";
1614          break;
1615 #ifdef MTSETBLK
1616       case MTSETBLK:
1617          msg = "MTSETBLK";
1618          break;
1619 #endif
1620 #ifdef MTSETDRVBUFFER
1621       case MTSETDRVBUFFER:
1622          msg = "MTSETDRVBUFFER";
1623          break;
1624 #endif
1625 #ifdef MTRESET
1626       case MTRESET:
1627          msg = "MTRESET";
1628          break;
1629 #endif
1630
1631 #ifdef MTSETBSIZ 
1632       case MTSETBSIZ:
1633          msg = "MTSETBSIZ";
1634          break;
1635 #endif
1636 #ifdef MTSRSZ
1637       case MTSRSZ:
1638          msg = "MTSRSZ";
1639          break;
1640 #endif
1641 #ifdef MTLOAD
1642       case MTLOAD:
1643          msg = "MTLOAD";
1644          break;
1645 #endif
1646 #ifdef MTUNLOCK
1647       case MTUNLOCK:
1648          msg = "MTUNLOCK";
1649          break;
1650 #endif
1651       case MTOFFL:
1652          msg = "MTOFFL";
1653          break;
1654       default:
1655          bsnprintf(buf, sizeof(buf), _("unknown func code %d"), func);
1656          msg = buf;
1657          break;
1658       }
1659       if (msg != NULL) {
1660          dev_errno = ENOSYS;
1661          Mmsg1(errmsg, _("I/O function \"%s\" not supported on this device.\n"), msg);
1662          Emsg0(M_ERROR, 0, errmsg);
1663       }
1664    }
1665
1666    /*
1667     * Now we try different methods of clearing the error
1668     *  status on the drive so that it is not locked for
1669     *  further operations.
1670     */
1671
1672    /* On some systems such as NetBSD, this clears all errors */
1673    get_os_tape_file();
1674
1675 /* Found on Solaris */
1676 #ifdef MTIOCLRERR
1677 {
1678    d_ioctl(m_fd, MTIOCLRERR);
1679    Dmsg0(200, "Did MTIOCLRERR\n");
1680 }
1681 #endif
1682
1683 /* Typically on FreeBSD */
1684 #ifdef MTIOCERRSTAT
1685 {
1686   berrno be;
1687    /* Read and clear SCSI error status */
1688    union mterrstat mt_errstat;
1689    Dmsg2(200, "Doing MTIOCERRSTAT errno=%d ERR=%s\n", dev_errno,
1690       be.bstrerror(dev_errno));
1691    d_ioctl(m_fd, MTIOCERRSTAT, (char *)&mt_errstat);
1692 }
1693 #endif
1694
1695 /* Clear Subsystem Exception TRU64 */
1696 #ifdef MTCSE
1697 {
1698    struct mtop mt_com;
1699    mt_com.mt_op = MTCSE;
1700    mt_com.mt_count = 1;
1701    /* Clear any error condition on the tape */
1702    d_ioctl(m_fd, MTIOCTOP, (char *)&mt_com);
1703    Dmsg0(200, "Did MTCSE\n");
1704 }
1705 #endif
1706 }
1707
1708
1709 /*
1710  * Set to unload the current volume in the drive
1711  */
1712 void DEVICE::set_unload()
1713 {
1714    if (!m_unload && VolHdr.VolumeName[0] != 0) {
1715        m_unload = true;
1716        memcpy(UnloadVolName, VolHdr.VolumeName, sizeof(UnloadVolName));
1717    }
1718 }
1719
1720
1721 /*
1722  * Clear volume header
1723  */
1724 void DEVICE::clear_volhdr()
1725 {
1726    Dmsg1(100, "Clear volhdr vol=%s\n", VolHdr.VolumeName);
1727    memset(&VolHdr, 0, sizeof(VolHdr));
1728    setVolCatInfo(false);
1729 }
1730
1731
1732 /*
1733  * Close the device
1734  */
1735 void DEVICE::close()
1736 {
1737    Dmsg1(100, "close_dev %s\n", print_name());
1738    offline_or_rewind();
1739
1740    if (!is_open()) {
1741       Dmsg2(100, "device %s already closed vol=%s\n", print_name(),
1742          VolHdr.VolumeName);
1743       return;                         /* already closed */
1744    }
1745
1746    switch (dev_type) {
1747    case B_VTL_DEV:
1748    case B_VTAPE_DEV:
1749    case B_TAPE_DEV:
1750       unlock_door(); 
1751    default:
1752       d_close(m_fd);
1753       break;
1754    }
1755
1756    unmount(1);                        /* do unmount if required */
1757
1758    /* Clean up device packet so it can be reused */
1759    clear_opened();
1760    /*
1761     * Be careful not to clear items needed by the DVD driver
1762     *    when it is closing a single part.
1763     */
1764    state &= ~(ST_LABEL|ST_READ|ST_APPEND|ST_EOT|ST_WEOT|ST_EOF|
1765               ST_MOUNTED|ST_MEDIA|ST_SHORT);
1766    label_type = B_BACULA_LABEL;
1767    file = block_num = 0;
1768    file_size = 0;
1769    file_addr = 0;
1770    EndFile = EndBlock = 0;
1771    openmode = 0;
1772    clear_volhdr();
1773    memset(&VolCatInfo, 0, sizeof(VolCatInfo));
1774    if (tid) {
1775       stop_thread_timer(tid);
1776       tid = 0;
1777    }
1778 }
1779
1780 /*
1781  * This call closes the device, but it is used in DVD handling
1782  *  where we close one part and then open the next part. The
1783  *  difference between close_part() and close() is that close_part()
1784  *  saves the state information of the device (e.g. the Volume lable,
1785  *  the Volume Catalog record, ...  This permits opening and closing
1786  *  the Volume parts multiple times without losing track of what the    
1787  *  main Volume parameters are.
1788  */
1789 void DEVICE::close_part(DCR * /*dcr*/)
1790 {
1791    VOLUME_LABEL saveVolHdr;
1792    VOLUME_CAT_INFO saveVolCatInfo;     /* Volume Catalog Information */
1793
1794
1795    saveVolHdr = VolHdr;               /* structure assignment */
1796    saveVolCatInfo = VolCatInfo;       /* structure assignment */
1797    close();                           /* close current part */
1798    VolHdr = saveVolHdr;               /* structure assignment */
1799    VolCatInfo = saveVolCatInfo;       /* structure assignment */
1800 }
1801
1802 boffset_t DEVICE::lseek(DCR *dcr, boffset_t offset, int whence)
1803 {
1804    switch (dev_type) {
1805    case B_FILE_DEV:
1806 #if defined(HAVE_WIN32)
1807       return ::_lseeki64(m_fd, (__int64)offset, whence);
1808 #else
1809       return ::lseek(m_fd, offset, whence);
1810 #endif
1811    }
1812    return -1;
1813 }
1814
1815
1816 bool DEVICE::truncate(DCR *dcr) /* We need the DCR for DVD-writing */
1817 {
1818    struct stat st;
1819
1820    Dmsg1(100, "truncate %s\n", print_name());
1821    switch (dev_type) {
1822    case B_VTL_DEV:
1823    case B_VTAPE_DEV:
1824    case B_TAPE_DEV:
1825       /* maybe we should rewind and write and eof ???? */
1826       return true;                    /* we don't really truncate tapes */
1827    case B_FILE_DEV:
1828       if (ftruncate(m_fd, 0) != 0) {
1829          berrno be;
1830          Mmsg2(errmsg, _("Unable to truncate device %s. ERR=%s\n"), 
1831                print_name(), be.bstrerror());
1832          return false;
1833       }
1834           
1835       /*
1836        * Check for a successful ftruncate() and issue a work-around for devices 
1837        * (mostly cheap NAS) that don't support truncation. 
1838        * Workaround supplied by Martin Schmid as a solution to bug #1011.
1839        * 1. close file
1840        * 2. delete file
1841        * 3. open new file with same mode
1842        * 4. change ownership to original
1843        */
1844
1845       if (fstat(m_fd, &st) != 0) {
1846          berrno be;
1847          Mmsg2(errmsg, _("Unable to stat device %s. ERR=%s\n"), 
1848                print_name(), be.bstrerror());
1849          return false;
1850       }
1851           
1852       if (st.st_size != 0) {             /* ftruncate() didn't work */
1853          POOL_MEM archive_name(PM_FNAME);
1854                 
1855          pm_strcpy(archive_name, dev_name);
1856          if (!IsPathSeparator(archive_name.c_str()[strlen(archive_name.c_str())-1])) {
1857             pm_strcat(archive_name, "/");
1858          }
1859          pm_strcat(archive_name, dcr->VolumeName);
1860                    
1861          Mmsg2(errmsg, _("Device %s doesn't support ftruncate(). Recreating file %s.\n"), 
1862                print_name(), archive_name.c_str());
1863
1864          /* Close file and blow it away */
1865          ::close(m_fd);
1866          ::unlink(archive_name.c_str());
1867                    
1868          /* Recreate the file -- of course, empty */
1869          set_mode(CREATE_READ_WRITE);
1870          if ((m_fd = ::open(archive_name.c_str(), mode, st.st_mode)) < 0) {
1871             berrno be;
1872             dev_errno = errno;
1873             Mmsg2(errmsg, _("Could not reopen: %s, ERR=%s\n"), archive_name.c_str(), 
1874                   be.bstrerror());
1875             Dmsg1(100, "reopen failed: %s", errmsg);
1876             Emsg0(M_FATAL, 0, errmsg);
1877             return false;
1878          }
1879                    
1880          /* Reset proper owner */
1881          chown(archive_name.c_str(), st.st_uid, st.st_gid);  
1882       }
1883           
1884       return true;
1885    }
1886    return false;
1887 }
1888
1889 /*
1890  * Mount the device.
1891  * If timeout, wait until the mount command returns 0.
1892  * If !timeout, try to mount the device only once.
1893  */
1894 bool DEVICE::mount(int timeout) 
1895 {
1896    Dmsg0(190, "Enter mount\n");
1897
1898    if (is_mounted()) {
1899       return true;
1900    }
1901
1902    switch (dev_type) {
1903    case B_VTL_DEV:
1904    case B_VTAPE_DEV:
1905    case B_TAPE_DEV:
1906       if (device->mount_command) {
1907          return do_tape_mount(1, timeout);
1908       }
1909       break;
1910    case B_FILE_DEV:
1911       if (requires_mount() && device->mount_command) {
1912          return do_file_mount(1, timeout);
1913       }
1914       break;
1915    default:
1916       break;
1917    }
1918
1919    return true;
1920 }
1921
1922 /*
1923  * Unmount the device
1924  * If timeout, wait until the unmount command returns 0.
1925  * If !timeout, try to unmount the device only once.
1926  */
1927 bool DEVICE::unmount(int timeout) 
1928 {
1929    Dmsg0(100, "Enter unmount\n");
1930
1931    if (!is_mounted()) {
1932       return true;
1933    }
1934
1935    switch (dev_type) {
1936    case B_VTL_DEV:
1937    case B_VTAPE_DEV:
1938    case B_TAPE_DEV:
1939       if (device->unmount_command) {
1940          return do_tape_mount(0, timeout);
1941       }
1942       break;
1943    case B_FILE_DEV:
1944    case B_DVD_DEV:
1945       if (requires_mount() && device->unmount_command) {
1946          return do_file_mount(0, timeout);
1947       }
1948       break;
1949    default:
1950       break;
1951    }
1952
1953    return true;
1954 }
1955
1956 /*
1957  * (Un)mount the device (for tape devices)
1958  */
1959 bool DEVICE::do_tape_mount(int mount, int dotimeout)
1960 {
1961    POOL_MEM ocmd(PM_FNAME);
1962    POOLMEM *results;
1963    char *icmd;
1964    int status, tries;
1965    berrno be;
1966
1967    Dsm_check(200);
1968    if (mount) {
1969       icmd = device->mount_command;
1970    } else {
1971       icmd = device->unmount_command;
1972    }
1973
1974    edit_mount_codes(ocmd, icmd);
1975
1976    Dmsg2(100, "do_tape_mount: cmd=%s mounted=%d\n", ocmd.c_str(), !!is_mounted());
1977
1978    if (dotimeout) {
1979       /* Try at most 10 times to (un)mount the device. This should perhaps be configurable. */
1980       tries = 10;
1981    } else {
1982       tries = 1;
1983    }
1984    results = get_memory(4000);
1985
1986    /* If busy retry each second */
1987    Dmsg1(100, "do_tape_mount run_prog=%s\n", ocmd.c_str());
1988    while ((status = run_program_full_output(ocmd.c_str(), max_open_wait/2, results)) != 0) {
1989       if (tries-- > 0) {
1990          continue;
1991       }
1992
1993       Dmsg5(100, "Device %s cannot be %smounted. stat=%d result=%s ERR=%s\n", print_name(),
1994            (mount ? "" : "un"), status, results, be.bstrerror(status));
1995       Mmsg(errmsg, _("Device %s cannot be %smounted. ERR=%s\n"),
1996            print_name(), (mount ? "" : "un"), be.bstrerror(status));
1997
1998       set_mounted(false);
1999       free_pool_memory(results);
2000       Dmsg0(200, "============ mount=0\n");
2001       Dsm_check(200);
2002       return false;
2003    }
2004
2005    set_mounted(mount);              /* set/clear mounted flag */
2006    free_pool_memory(results);
2007    Dmsg1(200, "============ mount=%d\n", mount);
2008    return true;
2009 }
2010
2011 /*
2012  * (Un)mount the device (either a FILE or DVD device)
2013  */
2014 bool DEVICE::do_file_mount(int mount, int dotimeout) 
2015 {
2016    POOL_MEM ocmd(PM_FNAME);
2017    POOLMEM *results;
2018    DIR* dp;
2019    char *icmd;
2020    struct dirent *entry, *result;
2021    int status, tries, name_max, count;
2022    berrno be;
2023
2024    Dsm_check(200);
2025    if (mount) {
2026       icmd = device->mount_command;
2027    } else {
2028       icmd = device->unmount_command;
2029    }
2030    
2031    clear_freespace_ok();
2032    edit_mount_codes(ocmd, icmd);
2033    
2034    Dmsg2(100, "do_file_mount: cmd=%s mounted=%d\n", ocmd.c_str(), !!is_mounted());
2035
2036    if (dotimeout) {
2037       /* Try at most 10 times to (un)mount the device. This should perhaps be configurable. */
2038       tries = 10;
2039    } else {
2040       tries = 1;
2041    }
2042    results = get_memory(4000);
2043
2044    /* If busy retry each second */
2045    Dmsg1(100, "do_file_mount run_prog=%s\n", ocmd.c_str());
2046    while ((status = run_program_full_output(ocmd.c_str(), max_open_wait/2, results)) != 0) {
2047       /* Doesn't work with internationalization (This is not a problem) */
2048       if (mount && fnmatch("*is already mounted on*", results, 0) == 0) {
2049          break;
2050       }
2051       if (!mount && fnmatch("* not mounted*", results, 0) == 0) {
2052          break;
2053       }
2054       if (tries-- > 0) {
2055          /* Sometimes the device cannot be mounted because it is already mounted.
2056           * Try to unmount it, then remount it */
2057          if (mount) {
2058             Dmsg1(400, "Trying to unmount the device %s...\n", print_name());
2059             do_file_mount(0, 0);
2060          }
2061          bmicrosleep(1, 0);
2062          continue;
2063       }
2064       Dmsg5(100, "Device %s cannot be %smounted. stat=%d result=%s ERR=%s\n", print_name(),
2065            (mount ? "" : "un"), status, results, be.bstrerror(status));
2066       Mmsg(errmsg, _("Device %s cannot be %smounted. ERR=%s\n"),
2067            print_name(), (mount ? "" : "un"), be.bstrerror(status));
2068
2069       /*
2070        * Now, just to be sure it is not mounted, try to read the filesystem.
2071        */
2072       name_max = pathconf(".", _PC_NAME_MAX);
2073       if (name_max < 1024) {
2074          name_max = 1024;
2075       }
2076          
2077       if (!(dp = opendir(device->mount_point))) {
2078          berrno be;
2079          dev_errno = errno;
2080          Dmsg3(100, "do_file_mount: failed to open dir %s (dev=%s), ERR=%s\n", 
2081                device->mount_point, print_name(), be.bstrerror());
2082          goto get_out;
2083       }
2084       
2085       entry = (struct dirent *)malloc(sizeof(struct dirent) + name_max + 1000);
2086       count = 0;
2087       while (1) {
2088          if ((readdir_r(dp, entry, &result) != 0) || (result == NULL)) {
2089             dev_errno = EIO;
2090             Dmsg2(129, "do_file_mount: failed to find suitable file in dir %s (dev=%s)\n", 
2091                   device->mount_point, print_name());
2092             break;
2093          }
2094          if ((strcmp(result->d_name, ".")) && (strcmp(result->d_name, "..")) && (strcmp(result->d_name, ".keep"))) {
2095             count++; /* result->d_name != ., .. or .keep (Gentoo-specific) */
2096             break;
2097          } else {
2098             Dmsg2(129, "do_file_mount: ignoring %s in %s\n", result->d_name, device->mount_point);
2099          }
2100       }
2101       free(entry);
2102       closedir(dp);
2103       
2104       Dmsg1(100, "do_file_mount: got %d files in the mount point (not counting ., .. and .keep)\n", count);
2105       
2106       if (count > 0) {
2107          /* If we got more than ., .. and .keep */
2108          /*   there must be something mounted */
2109          if (mount) {
2110             Dmsg1(100, "Did Mount by count=%d\n", count);
2111             break;
2112          } else {
2113             /* An unmount request. We failed to unmount - report an error */
2114             set_mounted(true);
2115             free_pool_memory(results);
2116             Dmsg0(200, "== error mount=1 wanted unmount\n");
2117             return false;
2118          }
2119       }
2120 get_out:
2121       set_mounted(false);
2122       free_pool_memory(results);
2123       Dmsg0(200, "============ mount=0\n");
2124       Dsm_check(200);
2125       return false;
2126    }
2127    
2128    set_mounted(mount);              /* set/clear mounted flag */
2129    free_pool_memory(results);
2130    /* Do not check free space when unmounting */
2131    if (mount && !update_freespace()) {
2132       return false;
2133    }
2134    Dmsg1(200, "============ mount=%d\n", mount);
2135    return true;
2136 }
2137
2138 /*
2139  * Edit codes into (Un)MountCommand, Write(First)PartCommand
2140  *  %% = %
2141  *  %a = archive device name
2142  *  %e = erase (set if cannot mount and first part)
2143  *  %n = part number
2144  *  %m = mount point
2145  *  %v = last part name
2146  *
2147  *  omsg = edited output message
2148  *  imsg = input string containing edit codes (%x)
2149  *
2150  */
2151 void DEVICE::edit_mount_codes(POOL_MEM &omsg, const char *imsg)
2152 {
2153    const char *p;
2154    const char *str;
2155    char add[20];
2156    
2157    POOL_MEM archive_name(PM_FNAME);
2158
2159    omsg.c_str()[0] = 0;
2160    Dmsg1(800, "edit_mount_codes: %s\n", imsg);
2161    for (p=imsg; *p; p++) {
2162       if (*p == '%') {
2163          switch (*++p) {
2164          case '%':
2165             str = "%";
2166             break;
2167          case 'a':
2168             str = dev_name;
2169             break;
2170          case 'e':
2171             if (num_dvd_parts == 0) {
2172                if (truncating || blank_dvd) {
2173                   str = "2";
2174                } else {
2175                   str = "1";
2176                }
2177             } else {
2178                str = "0";
2179             }
2180             break;
2181          case 'n':
2182             bsnprintf(add, sizeof(add), "%d", part);
2183             str = add;
2184             break;
2185          case 'm':
2186             str = device->mount_point;
2187             break;
2188          case 'v':
2189             make_spooled_dvd_filename(this, archive_name);
2190             str = archive_name.c_str();
2191             break;
2192          default:
2193             add[0] = '%';
2194             add[1] = *p;
2195             add[2] = 0;
2196             str = add;
2197             break;
2198          }
2199       } else {
2200          add[0] = *p;
2201          add[1] = 0;
2202          str = add;
2203       }
2204       Dmsg1(1900, "add_str %s\n", str);
2205       pm_strcat(omsg, (char *)str);
2206       Dmsg1(1800, "omsg=%s\n", omsg.c_str());
2207    }
2208 }
2209
2210 /* return the last timer interval (ms) 
2211  * or 0 if something goes wrong
2212  */
2213 btime_t DEVICE::get_timer_count()
2214 {
2215    btime_t temp = last_timer;
2216    last_timer = get_current_btime();
2217    temp = last_timer - temp;   /* get elapsed time */
2218    return (temp>0)?temp:0;     /* take care of skewed clock */
2219 }
2220
2221 /* read from fd */
2222 ssize_t DEVICE::read(void *buf, size_t len)
2223 {
2224    ssize_t read_len ;
2225
2226    get_timer_count();
2227
2228    read_len = d_read(m_fd, buf, len);
2229
2230    last_tick = get_timer_count();
2231
2232    DevReadTime += last_tick;
2233    VolCatInfo.VolReadTime += last_tick;
2234
2235    if (read_len > 0) {          /* skip error */
2236       DevReadBytes += read_len;
2237    }
2238
2239    return read_len;   
2240 }
2241
2242 /* write to fd */
2243 ssize_t DEVICE::write(const void *buf, size_t len)
2244 {
2245    ssize_t write_len ;
2246
2247    get_timer_count();
2248
2249    write_len = d_write(m_fd, buf, len);
2250
2251    last_tick = get_timer_count();
2252
2253    DevWriteTime += last_tick;
2254    VolCatInfo.VolWriteTime += last_tick;
2255
2256    if (write_len > 0) {         /* skip error */
2257       DevWriteBytes += write_len;
2258    }
2259
2260    return write_len;   
2261 }
2262
2263 /* Return the resource name for the device */
2264 const char *DEVICE::name() const
2265 {
2266    return device->hdr.name;
2267 }
2268
2269 /* Returns file position on tape or -1 */
2270 int32_t DEVICE::get_os_tape_file()
2271 {
2272    struct mtget mt_stat;
2273
2274    if (has_cap(CAP_MTIOCGET) &&
2275        d_ioctl(m_fd, MTIOCGET, (char *)&mt_stat) == 0) {
2276       return mt_stat.mt_fileno;
2277    }
2278    return -1;
2279 }
2280
2281 char *
2282 dev_vol_name(DEVICE *dev)
2283 {
2284    return dev->getVolCatName();
2285 }
2286
2287
2288 /*
2289  * Free memory allocated for the device
2290  */
2291 void DEVICE::term(void)
2292 {
2293    Dmsg1(900, "term dev: %s\n", print_name());
2294    close();
2295    if (dev_name) {
2296       free_memory(dev_name);
2297       dev_name = NULL;
2298    }
2299    if (prt_name) {
2300       free_memory(prt_name);
2301       prt_name = NULL;
2302    }
2303    if (errmsg) {
2304       free_pool_memory(errmsg);
2305       errmsg = NULL;
2306    }
2307    pthread_mutex_destroy(&m_mutex);
2308    pthread_cond_destroy(&wait);
2309    pthread_cond_destroy(&wait_next_vol);
2310    pthread_mutex_destroy(&spool_mutex);
2311 // rwl_destroy(&lock);
2312    if (attached_dcrs) {
2313       delete attached_dcrs;
2314       attached_dcrs = NULL;
2315    }
2316    if (device) {
2317       device->dev = NULL;
2318    }
2319    delete this;
2320 }
2321
2322 /*
2323  * This routine initializes the device wait timers
2324  */
2325 void init_device_wait_timers(DCR *dcr)
2326 {
2327    DEVICE *dev = dcr->dev;
2328    JCR *jcr = dcr->jcr;
2329
2330    /* ******FIXME******* put these on config variables */
2331    dev->min_wait = 60 * 60;
2332    dev->max_wait = 24 * 60 * 60;
2333    dev->max_num_wait = 9;              /* 5 waits =~ 1 day, then 1 day at a time */
2334    dev->wait_sec = dev->min_wait;
2335    dev->rem_wait_sec = dev->wait_sec;
2336    dev->num_wait = 0;
2337    dev->poll = false;
2338
2339    jcr->min_wait = 60 * 60;
2340    jcr->max_wait = 24 * 60 * 60;
2341    jcr->max_num_wait = 9;              /* 5 waits =~ 1 day, then 1 day at a time */
2342    jcr->wait_sec = jcr->min_wait;
2343    jcr->rem_wait_sec = jcr->wait_sec;
2344    jcr->num_wait = 0;
2345
2346 }
2347
2348 void init_jcr_device_wait_timers(JCR *jcr)
2349 {
2350    /* ******FIXME******* put these on config variables */
2351    jcr->min_wait = 60 * 60;
2352    jcr->max_wait = 24 * 60 * 60;
2353    jcr->max_num_wait = 9;              /* 5 waits =~ 1 day, then 1 day at a time */
2354    jcr->wait_sec = jcr->min_wait;
2355    jcr->rem_wait_sec = jcr->wait_sec;
2356    jcr->num_wait = 0;
2357 }
2358
2359
2360 /*
2361  * The dev timers are used for waiting on a particular device 
2362  *
2363  * Returns: true if time doubled
2364  *          false if max time expired
2365  */
2366 bool double_dev_wait_time(DEVICE *dev)
2367 {
2368    dev->wait_sec *= 2;               /* double wait time */
2369    if (dev->wait_sec > dev->max_wait) {   /* but not longer than maxtime */
2370       dev->wait_sec = dev->max_wait;
2371    }
2372    dev->num_wait++;
2373    dev->rem_wait_sec = dev->wait_sec;
2374    if (dev->num_wait >= dev->max_num_wait) {
2375       return false;
2376    }
2377    return true;
2378 }
2379
2380
2381 void set_os_device_parameters(DCR *dcr)
2382 {
2383    DEVICE *dev = dcr->dev;
2384
2385    if (strcmp(dev->dev_name, "/dev/null") == 0) {
2386       return;                            /* no use trying to set /dev/null */
2387    }
2388
2389 #if defined(HAVE_LINUX_OS) || defined(HAVE_WIN32)
2390    struct mtop mt_com;
2391
2392    Dmsg0(100, "In set_os_device_parameters\n");
2393 #if defined(MTSETBLK) 
2394    if (dev->min_block_size == dev->max_block_size &&
2395        dev->min_block_size == 0) {    /* variable block mode */
2396       mt_com.mt_op = MTSETBLK;
2397       mt_com.mt_count = 0;
2398       Dmsg0(100, "Set block size to zero\n");
2399       if (dev->d_ioctl(dev->fd(), MTIOCTOP, (char *)&mt_com) < 0) {
2400          dev->clrerror(MTSETBLK);
2401       }
2402    }
2403 #endif
2404 #if defined(MTSETDRVBUFFER)
2405    if (getuid() == 0) {          /* Only root can do this */
2406       mt_com.mt_op = MTSETDRVBUFFER;
2407       mt_com.mt_count = MT_ST_CLEARBOOLEANS;
2408       if (!dev->has_cap(CAP_TWOEOF)) {
2409          mt_com.mt_count |= MT_ST_TWO_FM;
2410       }
2411       if (dev->has_cap(CAP_EOM)) {
2412          mt_com.mt_count |= MT_ST_FAST_MTEOM;
2413       }
2414       Dmsg0(100, "MTSETDRVBUFFER\n");
2415       if (dev->d_ioctl(dev->fd(), MTIOCTOP, (char *)&mt_com) < 0) {
2416          dev->clrerror(MTSETDRVBUFFER);
2417       }
2418    }
2419 #endif
2420    return;
2421 #endif
2422
2423 #ifdef HAVE_NETBSD_OS
2424    struct mtop mt_com;
2425    if (dev->min_block_size == dev->max_block_size &&
2426        dev->min_block_size == 0) {    /* variable block mode */
2427       mt_com.mt_op = MTSETBSIZ;
2428       mt_com.mt_count = 0;
2429       if (dev->d_ioctl(dev->fd(), MTIOCTOP, (char *)&mt_com) < 0) {
2430          dev->clrerror(MTSETBSIZ);
2431       }
2432       /* Get notified at logical end of tape */
2433       mt_com.mt_op = MTEWARN;
2434       mt_com.mt_count = 1;
2435       if (dev->d_ioctl(dev->fd(), MTIOCTOP, (char *)&mt_com) < 0) {
2436          dev->clrerror(MTEWARN);
2437       }
2438    }
2439    return;
2440 #endif
2441
2442 #if HAVE_FREEBSD_OS || HAVE_OPENBSD_OS
2443    struct mtop mt_com;
2444    if (dev->min_block_size == dev->max_block_size &&
2445        dev->min_block_size == 0) {    /* variable block mode */
2446       mt_com.mt_op = MTSETBSIZ;
2447       mt_com.mt_count = 0;
2448       if (dev->d_ioctl(dev->fd(), MTIOCTOP, (char *)&mt_com) < 0) {
2449          dev->clrerror(MTSETBSIZ);
2450       }
2451    }
2452 #if defined(MTIOCSETEOTMODEL) 
2453    uint32_t neof;
2454    if (dev->has_cap(CAP_TWOEOF)) {
2455       neof = 2;
2456    } else {
2457       neof = 1;
2458    }
2459    if (dev->d_ioctl(dev->fd(), MTIOCSETEOTMODEL, (caddr_t)&neof) < 0) {
2460       berrno be;
2461       dev->dev_errno = errno;         /* save errno */
2462       Mmsg2(dev->errmsg, _("Unable to set eotmodel on device %s: ERR=%s\n"),
2463             dev->print_name(), be.bstrerror(dev->dev_errno));
2464       Jmsg(dcr->jcr, M_FATAL, 0, dev->errmsg);
2465    }
2466 #endif
2467    return;
2468 #endif
2469
2470 #ifdef HAVE_SUN_OS
2471    struct mtop mt_com;
2472    if (dev->min_block_size == dev->max_block_size &&
2473        dev->min_block_size == 0) {    /* variable block mode */
2474       mt_com.mt_op = MTSRSZ;
2475       mt_com.mt_count = 0;
2476       if (dev->d_ioctl(dev->fd(), MTIOCTOP, (char *)&mt_com) < 0) {
2477          dev->clrerror(MTSRSZ);
2478       }
2479    }
2480    return;
2481 #endif
2482 }
2483
2484 static bool dev_get_os_pos(DEVICE *dev, struct mtget *mt_stat)
2485 {
2486    Dmsg0(100, "dev_get_os_pos\n");
2487    return dev->has_cap(CAP_MTIOCGET) && 
2488           dev->d_ioctl(dev->fd(), MTIOCGET, (char *)mt_stat) == 0 &&
2489           mt_stat->mt_fileno >= 0;
2490 }
2491
2492 static const char *modes[] = {
2493    "CREATE_READ_WRITE",
2494    "OPEN_READ_WRITE",
2495    "OPEN_READ_ONLY",
2496    "OPEN_WRITE_ONLY"
2497 };
2498
2499
2500 static const char *mode_to_str(int mode)  
2501 {
2502    static char buf[100];
2503    if (mode < 1 || mode > 4) {
2504       bsnprintf(buf, sizeof(buf), "BAD mode=%d", mode);
2505       return buf;
2506     }
2507    return modes[mode-1];
2508 }