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