]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/stored/dev.c
1484edcf66ff2b736a1999573fba12d7f94193b8
[bacula/bacula] / bacula / src / stored / dev.c
1 /*
2  *
3  *   dev.c  -- low level operations on device (storage device)
4  *
5  *              Kern Sibbald, MM
6  *
7  *     NOTE!!!! None of these routines are reentrant. You must
8  *        use lock_device() and unlock_device() at a higher level,
9  *        or use the xxx_device() equivalents.  By moving the
10  *        thread synchronization to a higher level, we permit
11  *        the higher level routines to "seize" the device and
12  *        to carry out operations without worrying about who
13  *        set what lock (i.e. race conditions).
14  *
15  *     Note, this is the device dependent code, and my have
16  *           to be modified for each system, but is meant to
17  *           be as "generic" as possible.
18  *
19  *     The purpose of this code is to develop a SIMPLE Storage
20  *     daemon. More complicated coding (double buffering, writer
21  *     thread, ...) is left for a later version.
22  *
23  *     Unfortunately, I have had to add more and more complication
24  *     to this code. This was not foreseen as noted above, and as
25  *     a consequence has lead to something more contorted than is
26  *     really necessary -- KES.  Note, this contortion has been
27  *     corrected to a large extent by a rewrite (Apr MMI).
28  *
29  *   Version $Id$
30  */
31 /*
32    Copyright (C) 2000-2005 Kern Sibbald
33
34    This program is free software; you can redistribute it and/or
35    modify it under the terms of the GNU General Public License
36    version 2 as ammended with additional clauses defined in the
37    file LICENSE in the main source directory.
38
39    This program is distributed in the hope that it will be useful,
40    but WITHOUT ANY WARRANTY; without even the implied warranty of
41    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 
42    the file LICENSE for additional details.
43
44  */
45
46 /*
47  * Handling I/O errors and end of tape conditions are a bit tricky.
48  * This is how it is currently done when writting.
49  * On either an I/O error or end of tape,
50  * we will stop writing on the physical device (no I/O recovery is
51  * attempted at least in this daemon). The state flag will be sent
52  * to include ST_EOT, which is ephimeral, and ST_WEOT, which is
53  * persistent. Lots of routines clear ST_EOT, but ST_WEOT is
54  * cleared only when the problem goes away.  Now when ST_WEOT
55  * is set all calls to write_block_to_device() call the fix_up
56  * routine. In addition, all threads are blocked
57  * from writing on the tape by calling lock_dev(), and thread other
58  * than the first thread to hit the EOT will block on a condition
59  * variable. The first thread to hit the EOT will continue to
60  * be able to read and write the tape (he sort of tunnels through
61  * the locking mechanism -- see lock_dev() for details).
62  *
63  * Now presumably somewhere higher in the chain of command
64  * (device.c), someone will notice the EOT condition and
65  * get a new tape up, get the tape label read, and mark
66  * the label for rewriting. Then this higher level routine
67  * will write the unwritten buffer to the new volume.
68  * Finally, he will release
69  * any blocked threads by doing a broadcast on the condition
70  * variable.  At that point, we should be totally back in
71  * business with no lost data.
72  */
73
74
75 #include "bacula.h"
76 #include "stored.h"
77
78 #ifndef O_NONBLOCK 
79 #define O_NONBLOCK 0
80 #endif
81
82 /* Functions in dvd.c */ 
83 void update_free_space_dev(DEVICE* dev);
84
85
86 /* Forward referenced functions */
87 void set_os_device_parameters(DEVICE *dev);
88 static bool dev_get_os_pos(DEVICE *dev, struct mtget *mt_stat);
89 static void open_tape_device(DCR *dcr, int mode);
90 static void open_file_device(DCR *dcr, int mode);
91 static void open_dvd_device(DCR *dcr, int mode);
92 static char *mode_to_str(int mode);
93
94 /*
95  * Allocate and initialize the DEVICE structure
96  * Note, if dev is non-NULL, it is already allocated,
97  * thus we neither allocate it nor free it. This allows
98  * the caller to put the packet in shared memory.
99  *
100  *  Note, for a tape, the device->device_name is the device name
101  *     (e.g. /dev/nst0), and for a file, the device name
102  *     is the directory in which the file will be placed.
103  *
104  */
105 DEVICE *
106 init_dev(JCR *jcr, DEVRES *device)
107 {
108    struct stat statp;
109    bool tape, fifo;
110    int errstat;
111    DCR *dcr = NULL;
112    DEVICE *dev;
113
114    /* Check that device is available */
115    if (stat(device->device_name, &statp) < 0) {
116       berrno be;
117       Jmsg2(jcr, M_ERROR, 0, _("Unable to stat device %s: ERR=%s\n"), 
118          device->device_name, be.strerror());
119       return NULL;
120    }
121    
122    
123    tape = false;
124    fifo = false;
125    if (S_ISDIR(statp.st_mode)) {
126       tape = false;
127    } else if (S_ISCHR(statp.st_mode)) {
128       tape = true;
129    } else if (S_ISFIFO(statp.st_mode)) {
130       fifo = true;
131    } else if (!(device->cap_bits & CAP_REQMOUNT)) {
132       Jmsg2(jcr, M_ERROR, 0, _("%s is an unknown device type. Must be tape or directory\n"
133             " or have RequiresMount=yes for DVD. st_mode=%x\n"),
134          device->device_name, statp.st_mode);
135       return NULL;
136    }
137
138    dev = (DEVICE *)get_memory(sizeof(DEVICE));
139    memset(dev, 0, sizeof(DEVICE));
140    dev->state = ST_MALLOC;
141
142    /* Copy user supplied device parameters from Resource */
143    dev->dev_name = get_memory(strlen(device->device_name)+1);
144    pm_strcpy(dev->dev_name, device->device_name);
145    dev->prt_name = get_memory(strlen(device->device_name) + strlen(device->hdr.name) + 20);
146    /* We edit "Resource-name" (physical-name) */
147    Mmsg(dev->prt_name, "\"%s\" (%s)", device->hdr.name, device->device_name);
148    dev->capabilities = device->cap_bits;
149    dev->min_block_size = device->min_block_size;
150    dev->max_block_size = device->max_block_size;
151    dev->max_volume_size = device->max_volume_size;
152    dev->max_file_size = device->max_file_size;
153    dev->volume_capacity = device->volume_capacity;
154    dev->max_rewind_wait = device->max_rewind_wait;
155    dev->max_open_wait = device->max_open_wait;
156    dev->max_open_vols = device->max_open_vols;
157    dev->vol_poll_interval = device->vol_poll_interval;
158    dev->max_spool_size = device->max_spool_size;
159    dev->drive_index = device->drive_index;
160    dev->autoselect = device->autoselect;
161    if (tape) { /* No parts on tapes */
162       dev->max_part_size = 0;
163    }
164    else {
165       dev->max_part_size = device->max_part_size;
166    }
167    /* Sanity check */
168    if (dev->vol_poll_interval && dev->vol_poll_interval < 60) {
169       dev->vol_poll_interval = 60;
170    }
171    dev->device = device;
172
173    if (tape) {
174       dev->state |= ST_TAPE;
175    } else if (fifo) {
176       dev->state |= ST_FIFO;
177       dev->capabilities |= CAP_STREAM; /* set stream device */
178    } else {
179       dev->state |= ST_FILE;
180    }
181
182    /* If the device requires mount :
183     * - Check that the mount point is available 
184     * - Check that (un)mount commands are defined
185     */
186    if (dev->is_file() && dev->requires_mount()) {
187       if (stat(device->mount_point, &statp) < 0) {
188          berrno be;
189          dev->dev_errno = errno;
190          Jmsg2(jcr, M_ERROR, 0, _("Unable to stat mount point %s: ERR=%s\n"), 
191             device->mount_point, be.strerror());
192          return NULL;
193       }
194       if (!device->mount_command || !device->unmount_command) {
195          Jmsg0(jcr, M_ERROR_TERM, 0, _("Mount and unmount commands must defined for a device which requires mount.\n"));
196       }
197       if (!device->write_part_command) {
198          Jmsg0(jcr, M_ERROR_TERM, 0, _("Write part command must be defined for a device which requires mount.\n"));
199       }
200       dev->state |= ST_DVD;
201    }
202
203    if (dev->max_block_size > 1000000) {
204       Jmsg3(jcr, M_ERROR, 0, _("Block size %u on device %s is too large, using default %u\n"),
205          dev->max_block_size, dev->print_name(), DEFAULT_BLOCK_SIZE);
206       dev->max_block_size = 0;
207    }
208    if (dev->max_block_size % TAPE_BSIZE != 0) {
209       Jmsg2(jcr, M_WARNING, 0, _("Max block size %u not multiple of device %s block size.\n"),
210          dev->max_block_size, dev->print_name());
211    }
212
213    dev->errmsg = get_pool_memory(PM_EMSG);
214    *dev->errmsg = 0;
215
216    if ((errstat = pthread_mutex_init(&dev->mutex, NULL)) != 0) {
217       berrno be;
218       dev->dev_errno = errstat;
219       Mmsg1(dev->errmsg, _("Unable to init mutex: ERR=%s\n"), be.strerror(errstat));
220       Jmsg0(jcr, M_ERROR_TERM, 0, dev->errmsg);
221    }
222    if ((errstat = pthread_cond_init(&dev->wait, NULL)) != 0) {
223       berrno be;
224       dev->dev_errno = errstat;
225       Mmsg1(dev->errmsg, _("Unable to init cond variable: ERR=%s\n"), be.strerror(errstat));
226       Jmsg0(jcr, M_ERROR_TERM, 0, dev->errmsg);
227    }
228    if ((errstat = pthread_cond_init(&dev->wait_next_vol, NULL)) != 0) {
229       berrno be;
230       dev->dev_errno = errstat;
231       Mmsg1(dev->errmsg, _("Unable to init cond variable: ERR=%s\n"), be.strerror(errstat));
232       Jmsg0(jcr, M_ERROR_TERM, 0, dev->errmsg);
233    }
234    if ((errstat = pthread_mutex_init(&dev->spool_mutex, NULL)) != 0) {
235       berrno be;
236       dev->dev_errno = errstat;
237       Mmsg1(dev->errmsg, _("Unable to init mutex: ERR=%s\n"), be.strerror(errstat));
238       Jmsg0(jcr, M_ERROR_TERM, 0, dev->errmsg);
239    }
240    if ((errstat = rwl_init(&dev->lock)) != 0) {
241       berrno be;
242       dev->dev_errno = errstat;
243       Mmsg1(dev->errmsg, _("Unable to init mutex: ERR=%s\n"), be.strerror(errstat));
244       Jmsg0(jcr, M_ERROR_TERM, 0, dev->errmsg);
245    }
246
247    dev->fd = -1;
248    dev->attached_dcrs = New(dlist(dcr, &dcr->dev_link));
249    Dmsg2(29, "init_dev: tape=%d dev_name=%s\n", dev->is_tape(), dev->dev_name);
250    
251    return dev;
252 }
253
254 /*
255  * Open the device with the operating system and
256  * initialize buffer pointers.
257  *
258  * Returns:  -1  on error
259  *           fd  on success
260  *
261  * Note, for a tape, the VolName is the name we give to the
262  *    volume (not really used here), but for a file, the
263  *    VolName represents the name of the file to be created/opened.
264  *    In the case of a file, the full name is the device name
265  *    (archive_name) with the VolName concatenated.
266  */
267 int
268 DEVICE::open(DCR *dcr, int mode)
269 {
270    if (is_open()) {
271       if (openmode == mode) {
272          return fd;
273       } else {
274         ::close(fd); /* use system close so correct mode will be used on open */
275       }
276    }
277   if (dcr) {
278      bstrncpy(VolCatInfo.VolCatName, dcr->VolumeName, sizeof(VolCatInfo.VolCatName));
279   }
280
281    Dmsg4(29, "open dev: tape=%d dev_name=%s vol=%s mode=%s\n", is_tape(),
282          dev_name, VolCatInfo.VolCatName, mode_to_str(mode));
283    state &= ~(ST_LABEL|ST_APPEND|ST_READ|ST_EOT|ST_WEOT|ST_EOF);
284    label_type = B_BACULA_LABEL;
285    if (is_tape() || is_fifo()) {
286       open_tape_device(dcr, mode);
287    } else if (is_dvd()) {
288       Dmsg1(100, "call open_dvd_device mode=%s\n", mode_to_str(mode));
289       open_dvd_device(dcr, mode);
290    } else {
291       Dmsg1(100, "call open_file_device mode=%d\n", mode_to_str(mode));
292       open_file_device(dcr, mode);
293    }
294    return fd;
295 }
296
297 void DEVICE::set_mode(int new_mode) 
298 {
299    switch (new_mode) {
300    case CREATE_READ_WRITE:
301       mode = O_CREAT | O_RDWR | O_BINARY;
302       break;
303    case OPEN_READ_WRITE:
304       if (is_dvd() || is_file()) {
305          mode = O_CREAT | O_RDWR | O_BINARY;
306       } else {
307          mode = O_RDWR | O_BINARY;
308       }
309       break;
310    case OPEN_READ_ONLY:
311       mode = O_RDONLY | O_BINARY;
312       break;
313    case OPEN_WRITE_ONLY:
314       mode = O_WRONLY | O_BINARY;
315       break;
316    default:
317       Emsg0(M_ABORT, 0, _("Illegal mode given to open dev.\n"));
318    }
319 }
320
321 static void open_tape_device(DCR *dcr, int mode) 
322 {
323    DEVICE *dev = dcr->dev;
324    int nonblocking = 0;;
325    dev->file_size = 0;
326    int timeout;
327    int ioerrcnt = 10;
328    Dmsg0(29, "open dev: device is tape\n");
329
330    dev->set_mode(mode);
331    timeout = dev->max_open_wait;
332    errno = 0;
333    if (dev->open_nowait) {
334        /* Set wait counters to zero for no wait */
335        timeout = ioerrcnt = 0;
336        /* Open drive in non-block mode */
337        nonblocking = O_NONBLOCK;
338    }
339    if (dev->is_fifo() && timeout) {
340       /* Set open timer */
341       dev->tid = start_thread_timer(pthread_self(), timeout);
342    }
343    /* If busy retry each second for max_open_wait seconds */
344 open_again:
345    Dmsg1(500, "Try open %s\n", dev->dev_name);
346    while ((dev->fd = open(dev->dev_name, dev->mode, MODE_RW+nonblocking)) < 0) {
347       berrno be;
348       Dmsg2(500, "Open error errno=%d ERR=%s\n", errno, be.strerror());
349       if (errno == EINTR || errno == EAGAIN) {
350          Dmsg0(500, "Continue open\n");
351          continue;
352       }
353       /* Busy wait for specified time (default = 5 mins) */
354       if (errno == EBUSY && timeout-- > 0) {
355          Dmsg2(100, "Device %s busy. ERR=%s\n", dev->print_name(), be.strerror());
356          bmicrosleep(1, 0);
357          continue;
358       }
359       /* IO error (no volume) try 10 times every 6 seconds */
360       if (errno == EIO && ioerrcnt-- > 0) {
361          bmicrosleep(5, 0);
362          Dmsg0(500, "Continue open\n");
363          continue;
364       }
365       dev->dev_errno = errno;
366       Mmsg2(dev->errmsg, _("Unable to open device %s: ERR=%s\n"),
367             dev->print_name(), be.strerror(dev->dev_errno));
368       /* Stop any open timer we set */
369       if (dev->tid) {
370          stop_thread_timer(dev->tid);
371          dev->tid = 0;
372       }
373       Emsg0(M_FATAL, 0, dev->errmsg);
374       break;
375    }
376    if (dev->fd >= 0) {
377       /* If opened in non-block mode, close it an open it normally */
378       if (nonblocking) {
379          nonblocking = 0;
380          close(dev->fd);
381          goto open_again;
382       }
383       dev->openmode = mode;               /* save open mode */
384       dev->dev_errno = 0;
385       dev->state |= ST_OPENED;
386       dev->use_count = 1;
387       update_pos_dev(dev);                /* update position */
388       set_os_device_parameters(dev);      /* do system dependent stuff */
389       Dmsg0(500, "Open OK\n");
390    }
391    /* Stop any open() timer we started */
392    if (dev->tid) {
393       stop_thread_timer(dev->tid);
394       dev->tid = 0;
395    }
396    Dmsg1(29, "open dev: tape %d opened\n", dev->fd);
397 }
398
399 /*
400  * Open a file device
401  */
402 static void open_file_device(DCR *dcr, int mode) 
403 {
404    DEVICE *dev = dcr->dev;
405    POOL_MEM archive_name(PM_FNAME);
406
407    /*
408     * Handle opening of File Archive (not a tape)
409     */     
410    Dmsg3(29, "Enter: open_file_dev: %s dev=%s mode=%s\n", dev->is_dvd()?"DVD":"disk",
411          archive_name.c_str(), mode_to_str(mode));
412
413    if (dev->VolCatInfo.VolCatName[0] == 0) {
414       Mmsg(dev->errmsg, _("Could not open file device %s. No Volume name given.\n"),
415          dev->print_name());
416       dev->fd = -1;
417       return;
418    }
419
420    pm_strcpy(archive_name, dev->dev_name);
421    if (archive_name.c_str()[strlen(archive_name.c_str())-1] != '/') {
422       pm_strcat(archive_name, "/");
423    }
424    pm_strcat(archive_name, dev->VolCatInfo.VolCatName);
425          
426    Dmsg3(29, "open dev: %s dev=%s mode=%s\n", dev->is_dvd()?"DVD":"disk",
427          archive_name.c_str(), mode_to_str(mode));
428    dev->openmode = mode;
429    
430    dev->set_mode(mode);
431    /* If creating file, give 0640 permissions */
432    Dmsg3(29, "mode=%s open(%s, 0x%x, 0640)\n", mode, archive_name.c_str(), 
433          mode_to_str(dev->mode));
434    if ((dev->fd = open(archive_name.c_str(), dev->mode, 0640)) < 0) {
435       berrno be;
436       dev->dev_errno = errno;
437       Mmsg2(dev->errmsg, _("Could not open: %s, ERR=%s\n"), archive_name.c_str(), 
438             be.strerror());
439       Dmsg1(29, "open failed: %s", dev->errmsg);
440       Emsg0(M_FATAL, 0, dev->errmsg);
441    } else {
442       dev->dev_errno = 0;
443       dev->state |= ST_OPENED;
444       dev->use_count = 1;
445       update_pos_dev(dev);                /* update position */
446    }
447    Dmsg5(29, "open dev: %s fd=%d opened, part=%d/%d, part_size=%u\n", 
448       dev->is_dvd()?"DVD":"disk", dev->fd, dev->part, dev->num_parts, 
449       dev->part_size);
450 }
451
452 /*
453  * Open a DVD device. N.B. at this point, dcr->VolCatInfo.VolCatName
454  *  has the desired Volume name, but there is NO assurance that
455  *  any other field of VolCatInfo is correct.
456  */
457 static void open_dvd_device(DCR *dcr, int mode) 
458 {
459    DEVICE *dev = dcr->dev;
460    POOL_MEM archive_name(PM_FNAME);
461    struct stat filestat;
462
463    /*
464     * Handle opening of DVD Volume
465     */     
466    Dmsg3(29, "Enter: open_dvd_dev: %s dev=%s mode=%s\n", dev->is_dvd()?"DVD":"disk",
467          archive_name.c_str(), mode_to_str(mode));
468
469    if (dev->VolCatInfo.VolCatName[0] == 0) {
470       Mmsg(dev->errmsg, _("Could not open file device %s. No Volume name given.\n"),
471          dev->print_name());
472       dev->fd = -1;
473       return;
474    }
475
476    if (dev->part == 0) {
477       dev->file_size = 0;
478    }
479    dev->part_size = 0;
480    
481
482    if (mount_dev(dev, 1) < 0) {
483       Mmsg(dev->errmsg, _("Could not mount device %s.\n"),
484            dev->print_name());
485       Emsg0(M_FATAL, 0, dev->errmsg);
486       dev->fd = -1;
487       return;
488    }
489          
490    Dmsg3(29, "open dev: %s dev=%s mode=%s\n", dev->is_dvd()?"DVD":"disk",
491          archive_name.c_str(), mode_to_str(mode));
492    dev->openmode = mode;
493    
494    /*
495     * If we are not trying to access the last part, set mode to 
496     *   OPEN_READ_ONLY as writing would be an error.
497     */
498    if (dev->part < dev->num_parts) {
499       mode = OPEN_READ_ONLY;
500    }
501    dev->set_mode(mode);
502
503    /* 
504     * If we are opening it read-only, it is *probably* on the
505     *   DVD, so try the DVD first, otherwise look in the spool dir.
506     */
507    if (mode == OPEN_READ_ONLY) {
508       make_mounted_dvd_filename(dev, archive_name);
509    } else {
510       make_spooled_dvd_filename(dev, archive_name);
511    }
512
513    /* If creating file, give 0640 permissions */
514    Dmsg3(29, "mode=%s open(%s, 0x%x, 0640)\n", mode_to_str(mode), 
515          archive_name.c_str(), dev->mode);
516    if ((dev->fd = open(archive_name.c_str(), dev->mode, 0640)) < 0) {
517       berrno be;
518       dev->dev_errno = errno;
519       Mmsg2(dev->errmsg, _("Could not open: %s, ERR=%s\n"), archive_name.c_str(), 
520             be.strerror());
521       Dmsg1(29, "open failed: %s", dev->errmsg);
522       if (mode == OPEN_READ_ONLY) {
523          make_spooled_dvd_filename(dev, archive_name);
524          dev->fd = open(archive_name.c_str(), dev->mode, 0640);  /* try on spool */
525       }
526    }
527    if (dev->fd >= 0) {
528       /* Get size of file */
529       if (fstat(dev->fd, &filestat) < 0) {
530          berrno be;
531          dev->dev_errno = errno;
532          Mmsg2(dev->errmsg, _("Could not fstat: %s, ERR=%s\n"), archive_name.c_str(), 
533                be.strerror());
534          Dmsg1(29, "open failed: %s", dev->errmsg);
535          close(dev->fd);
536          dev->fd = -1;
537       } else {
538          dev->part_size = filestat.st_size;
539          dev->dev_errno = 0;
540          dev->state |= ST_OPENED;
541          dev->use_count = 1;
542          update_pos_dev(dev);                /* update position */
543       }
544    }
545    Dmsg4(29, "open dev: DVD fd=%d opened, part=%d/%d, part_size=%u\n", 
546       dev->fd, dev->part, dev->num_parts, dev->part_size);
547    if (dev->is_open() && dev->is_dvd() && (mode != OPEN_READ_ONLY) && 
548        (dev->free_space_errno == 0 || dev->num_parts == dev->part)) {
549       update_free_space_dev(dev);
550    }
551 }
552
553
554 #ifdef debug_tracing
555 #undef rewind_dev
556 bool _rewind_dev(char *file, int line, DEVICE *dev)
557 {
558    Dmsg2(100, "rewind_dev called from %s:%d\n", file, line);
559    return rewind_dev(dev);
560 }
561 #endif
562
563 /*
564  * Rewind the device.
565  *  Returns: true  on success
566  *           false on failure
567  */
568 bool rewind_dev(DEVICE *dev)
569 {
570    struct mtop mt_com;
571    unsigned int i;
572
573    Dmsg1(29, "rewind_dev %s\n", dev->print_name());
574    if (dev->fd < 0) {
575       dev->dev_errno = EBADF;
576       Mmsg1(dev->errmsg, _("Bad call to rewind_dev. Device %s not open\n"),
577             dev->print_name());
578       Emsg0(M_ABORT, 0, dev->errmsg);
579       return false;
580    }
581    dev->state &= ~(ST_EOT|ST_EOF|ST_WEOT);  /* remove EOF/EOT flags */
582    dev->block_num = dev->file = 0;
583    dev->file_size = 0;
584    dev->file_addr = 0;
585    if (dev->is_tape()) {
586       mt_com.mt_op = MTREW;
587       mt_com.mt_count = 1;
588       /* If we get an I/O error on rewind, it is probably because
589        * the drive is actually busy. We loop for (about 5 minutes)
590        * retrying every 5 seconds.
591        */
592       for (i=dev->max_rewind_wait; ; i -= 5) {
593          if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
594             berrno be;
595             clrerror_dev(dev, MTREW);
596             if (i == dev->max_rewind_wait) {
597                Dmsg1(200, "Rewind error, %s. retrying ...\n", be.strerror());
598             }
599             if (dev->dev_errno == EIO && i > 0) {
600                Dmsg0(200, "Sleeping 5 seconds.\n");
601                bmicrosleep(5, 0);
602                continue;
603             }
604             Mmsg2(dev->errmsg, _("Rewind error on %s. ERR=%s.\n"),
605                dev->print_name(), be.strerror());
606             return false;
607          }
608          break;
609       }
610    } else if (dev->is_file()) {      
611       if (lseek_dev(dev, (off_t)0, SEEK_SET) < 0) {
612          berrno be;
613          dev->dev_errno = errno;
614          Mmsg2(dev->errmsg, _("lseek_dev error on %s. ERR=%s.\n"),
615             dev->print_name(), be.strerror());
616          return false;
617       }
618    }
619    return true;
620 }
621
622 void DEVICE::block(int why)
623 {
624    lock_device(this);
625    block_device(this, why);
626    V(mutex);
627 }
628
629 void DEVICE::unblock()
630 {  
631    P(mutex);
632    unblock_device(this);
633    V(mutex);
634 }
635
636 /*
637  * Called to indicate that we have just read an
638  *  EOF from the device.
639  */
640 void DEVICE::set_ateof() 
641
642    set_eof();
643    file++;
644    file_addr = 0;
645    file_size = 0;
646    block_num = 0;
647 }
648
649 /*
650  * Called to indicate we are now at the end of the tape, and
651  *   writing is not possible.
652  */
653 void DEVICE::set_ateot() 
654 {
655    /* Make tape effectively read-only */
656    state |= (ST_EOF|ST_EOT|ST_WEOT);
657    clear_append();
658 }
659
660 /*
661  * Position device to end of medium (end of data)
662  *  Returns: true  on succes
663  *           false on error
664  */
665 bool
666 eod_dev(DEVICE *dev)
667 {
668    struct mtop mt_com;
669    struct mtget mt_stat;
670    bool ok = true;
671    off_t pos;
672
673    if (dev->fd < 0) {
674       dev->dev_errno = EBADF;
675       Mmsg1(dev->errmsg, _("Bad call to eod_dev. Device %s not open\n"),
676             dev->print_name());
677       return false;
678    }
679
680 #if defined (__digital__) && defined (__unix__)
681    return fsf_dev(dev, dev->VolCatInfo.VolCatFiles);
682 #endif
683
684    Dmsg0(29, "eod_dev\n");
685    if (dev->at_eot()) {
686       return true;
687    }
688    dev->state &= ~(ST_EOF);  /* remove EOF flags */
689    dev->block_num = dev->file = 0;
690    dev->file_size = 0;
691    dev->file_addr = 0;
692    if (dev->state & (ST_FIFO | ST_PROG)) {
693       return true;
694    }
695    if (!dev->is_tape()) {
696       pos = lseek_dev(dev, (off_t)0, SEEK_END);
697 //    Dmsg1(100, "====== Seek to %lld\n", pos);
698       if (pos >= 0) {
699          update_pos_dev(dev);
700          dev->state |= ST_EOT;
701          return true;
702       }
703       dev->dev_errno = errno;
704       berrno be;
705       Mmsg2(dev->errmsg, _("lseek_dev error on %s. ERR=%s.\n"),
706              dev->print_name(), be.strerror());
707       return false;
708    }
709 #ifdef MTEOM
710    if (dev_cap(dev, CAP_FASTFSF) && !dev_cap(dev, CAP_EOM)) {
711       Dmsg0(100,"Using FAST FSF for EOM\n");
712       /* If unknown position, rewind */
713       if (!dev_get_os_pos(dev, &mt_stat)) {
714         if (!rewind_dev(dev)) {
715           return false;
716         }
717       }
718       mt_com.mt_op = MTFSF;
719       /*
720        * ***FIXME*** fix code to handle case that INT16_MAX is
721        *   not large enough.
722        */
723       mt_com.mt_count = INT16_MAX;    /* use big positive number */
724       if (mt_com.mt_count < 0) {
725          mt_com.mt_count = INT16_MAX; /* brain damaged system */
726       }
727    }
728
729    if (dev_cap(dev, CAP_MTIOCGET) && (dev_cap(dev, CAP_FASTFSF) || dev_cap(dev, CAP_EOM))) {
730       if (dev_cap(dev, CAP_EOM)) {
731          Dmsg0(100,"Using EOM for EOM\n");
732          mt_com.mt_op = MTEOM;
733          mt_com.mt_count = 1;
734       }
735
736       if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
737          berrno be;
738          clrerror_dev(dev, mt_com.mt_op);
739          Dmsg1(50, "ioctl error: %s\n", be.strerror());
740          update_pos_dev(dev);
741          Mmsg2(dev->errmsg, _("ioctl MTEOM error on %s. ERR=%s.\n"),
742             dev->print_name(), be.strerror());
743          return false;
744       }
745
746       if (!dev_get_os_pos(dev, &mt_stat)) {
747          berrno be;
748          clrerror_dev(dev, -1);
749          Mmsg2(dev->errmsg, _("ioctl MTIOCGET error on %s. ERR=%s.\n"),
750             dev->print_name(), be.strerror());
751          return false;
752       }
753       Dmsg2(100, "EOD file=%d block=%d\n", mt_stat.mt_fileno, mt_stat.mt_blkno);
754       dev->set_ateof();
755       dev->file = mt_stat.mt_fileno;
756    } else {
757 #else
758    {
759 #endif
760       /*
761        * Rewind then use FSF until EOT reached
762        */
763       if (!rewind_dev(dev)) {
764          return false;
765       }
766       /*
767        * Move file by file to the end of the tape
768        */
769       int file_num;
770       for (file_num=dev->file; !dev->at_eot(); file_num++) {
771          Dmsg0(200, "eod_dev: doing fsf 1\n");
772          if (!fsf_dev(dev, 1)) {
773             Dmsg0(200, "fsf_dev error.\n");
774             return false;
775          }
776          /*
777           * Avoid infinite loop. ***FIXME*** possibly add code
778           *   to set EOD or to turn off CAP_FASTFSF if on.
779           */
780          if (file_num == (int)dev->file) {
781             struct mtget mt_stat;
782             Dmsg1(100, "fsf_dev did not advance from file %d\n", file_num);
783             if (dev_get_os_pos(dev, &mt_stat)) {
784                Dmsg2(100, "Adjust file from %d to %d\n", dev->file , mt_stat.mt_fileno);
785                dev->set_ateof();
786                dev->file = mt_stat.mt_fileno;
787             }
788             return false;
789          }
790       }
791    }
792    /*
793     * Some drivers leave us after second EOF when doing
794     * MTEOM, so we must backup so that appending overwrites
795     * the second EOF.
796     */
797    if (dev_cap(dev, CAP_BSFATEOM)) {
798       struct mtget mt_stat;
799       /* Backup over EOF */
800       ok = bsf_dev(dev, 1);
801       /* If BSF worked and fileno is known (not -1), set file */
802       if (dev_get_os_pos(dev, &mt_stat)) {
803          Dmsg2(100, "BSFATEOF adjust file from %d to %d\n", dev->file , mt_stat.mt_fileno);
804          dev->file = mt_stat.mt_fileno;
805       } else {
806          dev->file++;                 /* wing it -- not correct on all OSes */
807       }
808    } else {
809       update_pos_dev(dev);                   /* update position */
810    }
811    Dmsg1(200, "EOD dev->file=%d\n", dev->file);
812    return ok;
813 }
814
815 /*
816  * Set the position of the device -- only for files
817  *   For other devices, there is no generic way to do it.
818  *  Returns: true  on succes
819  *           false on error
820  */
821 bool update_pos_dev(DEVICE *dev)
822 {
823    off_t pos;
824    bool ok = true;
825
826    if (dev->fd < 0) {
827       dev->dev_errno = EBADF;
828       Mmsg0(dev->errmsg, _("Bad device call. Device not open\n"));
829       Emsg0(M_FATAL, 0, dev->errmsg);
830       return false;
831    }
832
833    /* Find out where we are */
834    if (dev->is_file()) {
835       dev->file = 0;
836       dev->file_addr = 0;
837       pos = lseek_dev(dev, (off_t)0, SEEK_CUR);
838       if (pos < 0) {
839          berrno be;
840          dev->dev_errno = errno;
841          Pmsg1(000, "Seek error: ERR=%s\n", be.strerror());
842          Mmsg2(dev->errmsg, _("lseek_dev error on %s. ERR=%s.\n"),
843             dev->print_name(), be.strerror());
844          ok = false;
845       } else {
846          dev->file_addr = pos;
847       }
848    }
849    return ok;
850 }
851
852
853 /*
854  * Return the status of the device.  This was meant
855  * to be a generic routine. Unfortunately, it doesn't
856  * seem possible (at least I do not know how to do it
857  * currently), which means that for the moment, this
858  * routine has very little value.
859  *
860  *   Returns: status
861  */
862 uint32_t status_dev(DEVICE *dev)
863 {
864    struct mtget mt_stat;
865    uint32_t stat = 0;
866
867    if (dev->state & (ST_EOT | ST_WEOT)) {
868       stat |= BMT_EOD;
869       Pmsg0(-20, " EOD");
870    }
871    if (dev->state & ST_EOF) {
872       stat |= BMT_EOF;
873       Pmsg0(-20, " EOF");
874    }
875    if (dev->is_tape()) {
876       stat |= BMT_TAPE;
877       Pmsg0(-20," Bacula status:");
878       Pmsg2(-20," file=%d block=%d\n", dev->file, dev->block_num);
879       if (ioctl(dev->fd, MTIOCGET, (char *)&mt_stat) < 0) {
880          berrno be;
881          dev->dev_errno = errno;
882          Mmsg2(dev->errmsg, _("ioctl MTIOCGET error on %s. ERR=%s.\n"),
883             dev->print_name(), be.strerror());
884          return 0;
885       }
886       Pmsg0(-20, " Device status:");
887
888 #if defined(HAVE_LINUX_OS)
889       if (GMT_EOF(mt_stat.mt_gstat)) {
890          stat |= BMT_EOF;
891          Pmsg0(-20, " EOF");
892       }
893       if (GMT_BOT(mt_stat.mt_gstat)) {
894          stat |= BMT_BOT;
895          Pmsg0(-20, " BOT");
896       }
897       if (GMT_EOT(mt_stat.mt_gstat)) {
898          stat |= BMT_EOT;
899          Pmsg0(-20, " EOT");
900       }
901       if (GMT_SM(mt_stat.mt_gstat)) {
902          stat |= BMT_SM;
903          Pmsg0(-20, " SM");
904       }
905       if (GMT_EOD(mt_stat.mt_gstat)) {
906          stat |= BMT_EOD;
907          Pmsg0(-20, " EOD");
908       }
909       if (GMT_WR_PROT(mt_stat.mt_gstat)) {
910          stat |= BMT_WR_PROT;
911          Pmsg0(-20, " WR_PROT");
912       }
913       if (GMT_ONLINE(mt_stat.mt_gstat)) {
914          stat |= BMT_ONLINE;
915          Pmsg0(-20, " ONLINE");
916       }
917       if (GMT_DR_OPEN(mt_stat.mt_gstat)) {
918          stat |= BMT_DR_OPEN;
919          Pmsg0(-20, " DR_OPEN");
920       }
921       if (GMT_IM_REP_EN(mt_stat.mt_gstat)) {
922          stat |= BMT_IM_REP_EN;
923          Pmsg0(-20, " IM_REP_EN");
924       }
925 #endif /* !SunOS && !OSF */
926       if (dev_cap(dev, CAP_MTIOCGET)) {
927          Pmsg2(-20, " file=%d block=%d\n", mt_stat.mt_fileno, mt_stat.mt_blkno);
928       } else {
929          Pmsg2(-20, " file=%d block=%d\n", -1, -1);
930       }
931    } else {
932       stat |= BMT_ONLINE | BMT_BOT;
933    }
934    return stat;
935 }
936
937
938 /*
939  * Load medium in device
940  *  Returns: true  on success
941  *           false on failure
942  */
943 bool load_dev(DEVICE *dev)
944 {
945 #ifdef MTLOAD
946    struct mtop mt_com;
947 #endif
948
949    if (dev->fd < 0) {
950       dev->dev_errno = EBADF;
951       Mmsg0(dev->errmsg, _("Bad call to load_dev. Device not open\n"));
952       Emsg0(M_FATAL, 0, dev->errmsg);
953       return false;
954    }
955    if (!(dev->is_tape())) {
956       return true;
957    }
958 #ifndef MTLOAD
959    Dmsg0(200, "stored: MTLOAD command not available\n");
960    berrno be;
961    dev->dev_errno = ENOTTY;           /* function not available */
962    Mmsg2(dev->errmsg, _("ioctl MTLOAD error on %s. ERR=%s.\n"),
963          dev->print_name(), be.strerror());
964    return false;
965 #else
966
967    dev->block_num = dev->file = 0;
968    dev->file_size = 0;
969    dev->file_addr = 0;
970    mt_com.mt_op = MTLOAD;
971    mt_com.mt_count = 1;
972    if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
973       berrno be;
974       dev->dev_errno = errno;
975       Mmsg2(dev->errmsg, _("ioctl MTLOAD error on %s. ERR=%s.\n"),
976          dev->print_name(), be.strerror());
977       return false;
978    }
979    return true;
980 #endif
981 }
982
983 /*
984  * Rewind device and put it offline
985  *  Returns: true  on success
986  *           false on failure
987  */
988 bool offline_dev(DEVICE *dev)
989 {
990    struct mtop mt_com;
991
992    if (dev->fd < 0) {
993       dev->dev_errno = EBADF;
994       Mmsg0(dev->errmsg, _("Bad call to offline_dev. Device not open\n"));
995       Emsg0(M_FATAL, 0, dev->errmsg);
996       return false;
997    }
998    if (!(dev->is_tape())) {
999       return true;
1000    }
1001
1002    dev->state &= ~(ST_APPEND|ST_READ|ST_EOT|ST_EOF|ST_WEOT);  /* remove EOF/EOT flags */
1003    dev->block_num = dev->file = 0;
1004    dev->file_size = 0;
1005    dev->file_addr = 0;
1006    dev->part = 0;
1007 #ifdef MTUNLOCK
1008    mt_com.mt_op = MTUNLOCK;
1009    mt_com.mt_count = 1;
1010    ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
1011 #endif
1012    mt_com.mt_op = MTOFFL;
1013    mt_com.mt_count = 1;
1014    if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
1015       berrno be;
1016       dev->dev_errno = errno;
1017       Mmsg2(dev->errmsg, _("ioctl MTOFFL error on %s. ERR=%s.\n"),
1018          dev->print_name(), be.strerror());
1019       return false;
1020    }
1021    Dmsg1(100, "Offlined device %s\n", dev->print_name());
1022    return true;
1023 }
1024
1025 bool offline_or_rewind_dev(DEVICE *dev)
1026 {
1027    if (dev->fd < 0) {
1028       return false;
1029    }
1030    if (dev_cap(dev, CAP_OFFLINEUNMOUNT)) {
1031       return offline_dev(dev);
1032    } else {
1033    /*
1034     * Note, this rewind probably should not be here (it wasn't
1035     *  in prior versions of Bacula), but on FreeBSD, this is
1036     *  needed in the case the tape was "frozen" due to an error
1037     *  such as backspacing after writing and EOF. If it is not
1038     *  done, all future references to the drive get and I/O error.
1039     */
1040       clrerror_dev(dev, MTREW);
1041       return rewind_dev(dev);
1042    }
1043 }
1044
1045 /*
1046  * Foward space a file
1047  *   Returns: true  on success
1048  *            false on failure
1049  */
1050 bool
1051 fsf_dev(DEVICE *dev, int num)
1052 {
1053    struct mtget mt_stat;
1054    struct mtop mt_com;
1055    int stat = 0;
1056
1057    if (dev->fd < 0) {
1058       dev->dev_errno = EBADF;
1059       Mmsg0(dev->errmsg, _("Bad call to fsf_dev. Device not open\n"));
1060       Emsg0(M_FATAL, 0, dev->errmsg);
1061       return false;
1062    }
1063
1064    if (!dev->is_tape()) {
1065       return true;
1066    }
1067    if (dev->state & ST_EOT) {
1068       dev->dev_errno = 0;
1069       Mmsg1(dev->errmsg, _("Device %s at End of Tape.\n"), dev->print_name());
1070       return false;
1071    }
1072    if (dev->state & ST_EOF) {
1073       Dmsg0(200, "ST_EOF set on entry to FSF\n");
1074    }
1075
1076    Dmsg0(100, "fsf_dev\n");
1077    dev->block_num = 0;
1078    /*
1079     * If Fast forward space file is set, then we
1080     *  use MTFSF to forward space and MTIOCGET
1081     *  to get the file position. We assume that
1082     *  the SCSI driver will ensure that we do not
1083     *  forward space past the end of the medium.
1084     */
1085    if (dev_cap(dev, CAP_FSF) && dev_cap(dev, CAP_MTIOCGET) && dev_cap(dev, CAP_FASTFSF)) {
1086       mt_com.mt_op = MTFSF;
1087       mt_com.mt_count = num;
1088       stat = ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
1089       if (stat < 0 || !dev_get_os_pos(dev, &mt_stat)) {
1090          berrno be;
1091          dev->state |= ST_EOT;
1092          Dmsg0(200, "Set ST_EOT\n");
1093          clrerror_dev(dev, MTFSF);
1094          Mmsg2(dev->errmsg, _("ioctl MTFSF error on %s. ERR=%s.\n"),
1095             dev->print_name(), be.strerror());
1096          Dmsg1(200, "%s", dev->errmsg);
1097          return false;
1098       }
1099       Dmsg2(200, "fsf file=%d block=%d\n", mt_stat.mt_fileno, mt_stat.mt_blkno);
1100       dev->set_ateof();
1101       dev->file = mt_stat.mt_fileno;
1102       return true;
1103
1104    /*
1105     * Here if CAP_FSF is set, and virtually all drives
1106     *  these days support it, we read a record, then forward
1107     *  space one file. Using this procedure, which is slow,
1108     *  is the only way we can be sure that we don't read
1109     *  two consecutive EOF marks, which means End of Data.
1110     */
1111    } else if (dev_cap(dev, CAP_FSF)) {
1112       POOLMEM *rbuf;
1113       int rbuf_len;
1114       Dmsg0(200, "FSF has cap_fsf\n");
1115       if (dev->max_block_size == 0) {
1116          rbuf_len = DEFAULT_BLOCK_SIZE;
1117       } else {
1118          rbuf_len = dev->max_block_size;
1119       }
1120       rbuf = get_memory(rbuf_len);
1121       mt_com.mt_op = MTFSF;
1122       mt_com.mt_count = 1;
1123       while (num-- && !(dev->state & ST_EOT)) {
1124          Dmsg0(100, "Doing read before fsf\n");
1125          if ((stat = read(dev->fd, (char *)rbuf, rbuf_len)) < 0) {
1126             if (errno == ENOMEM) {     /* tape record exceeds buf len */
1127                stat = rbuf_len;        /* This is OK */
1128             } else {
1129                berrno be;
1130                dev->state |= ST_EOT;
1131                clrerror_dev(dev, -1);
1132                Dmsg2(100, "Set ST_EOT read errno=%d. ERR=%s\n", dev->dev_errno,
1133                   be.strerror());
1134                Mmsg2(dev->errmsg, _("read error on %s. ERR=%s.\n"),
1135                   dev->print_name(), be.strerror());
1136                Dmsg1(100, "%s", dev->errmsg);
1137                break;
1138             }
1139          }
1140          if (stat == 0) {                /* EOF */
1141             update_pos_dev(dev);
1142             Dmsg1(100, "End of File mark from read. File=%d\n", dev->file+1);
1143             /* Two reads of zero means end of tape */
1144             if (dev->state & ST_EOF) {
1145                dev->state |= ST_EOT;
1146                Dmsg0(100, "Set ST_EOT\n");
1147                break;
1148             } else {
1149                dev->set_ateof();
1150                continue;
1151             }
1152          } else {                        /* Got data */
1153             dev->state &= ~(ST_EOF|ST_EOT);
1154          }
1155
1156          Dmsg0(100, "Doing MTFSF\n");
1157          stat = ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
1158          if (stat < 0) {                 /* error => EOT */
1159             berrno be;
1160             dev->state |= ST_EOT;
1161             Dmsg0(100, "Set ST_EOT\n");
1162             clrerror_dev(dev, MTFSF);
1163             Mmsg2(dev->errmsg, _("ioctl MTFSF error on %s. ERR=%s.\n"),
1164                dev->print_name(), be.strerror());
1165             Dmsg0(100, "Got < 0 for MTFSF\n");
1166             Dmsg1(100, "%s", dev->errmsg);
1167          } else {
1168             dev->set_ateof();
1169          }
1170       }
1171       free_memory(rbuf);
1172
1173    /*
1174     * No FSF, so use FSR to simulate it
1175     */
1176    } else {
1177       Dmsg0(200, "Doing FSR for FSF\n");
1178       while (num-- && !(dev->state & ST_EOT)) {
1179          dev->fsr(INT32_MAX);    /* returns -1 on EOF or EOT */
1180       }
1181       if (dev->state & ST_EOT) {
1182          dev->dev_errno = 0;
1183          Mmsg1(dev->errmsg, _("Device %s at End of Tape.\n"), dev->print_name());
1184          stat = -1;
1185       } else {
1186          stat = 0;
1187       }
1188    }
1189    update_pos_dev(dev);
1190    Dmsg1(200, "Return %d from FSF\n", stat);
1191    if (dev->state & ST_EOF)
1192       Dmsg0(200, "ST_EOF set on exit FSF\n");
1193    if (dev->state & ST_EOT)
1194       Dmsg0(200, "ST_EOT set on exit FSF\n");
1195    Dmsg1(200, "Return from FSF file=%d\n", dev->file);
1196    return stat == 0;
1197 }
1198
1199 /*
1200  * Backward space a file
1201  *  Returns: false on failure
1202  *           true  on success
1203  */
1204 bool
1205 bsf_dev(DEVICE *dev, int num)
1206 {
1207    struct mtop mt_com;
1208    int stat;
1209
1210    if (dev->fd < 0) {
1211       dev->dev_errno = EBADF;
1212       Mmsg0(dev->errmsg, _("Bad call to bsf_dev. Device not open\n"));
1213       Emsg0(M_FATAL, 0, dev->errmsg);
1214       return false;
1215    }
1216
1217    if (!dev->is_tape()) {
1218       Mmsg1(dev->errmsg, _("Device %s cannot BSF because it is not a tape.\n"),
1219          dev->print_name());
1220       return false;
1221    }
1222    Dmsg0(29, "bsf_dev\n");
1223    dev->state &= ~(ST_EOT|ST_EOF);
1224    dev->file -= num;
1225    dev->file_addr = 0;
1226    dev->file_size = 0;
1227    mt_com.mt_op = MTBSF;
1228    mt_com.mt_count = num;
1229    stat = ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
1230    if (stat < 0) {
1231       berrno be;
1232       clrerror_dev(dev, MTBSF);
1233       Mmsg2(dev->errmsg, _("ioctl MTBSF error on %s. ERR=%s.\n"),
1234          dev->print_name(), be.strerror());
1235    }
1236    update_pos_dev(dev);
1237    return stat == 0;
1238 }
1239
1240
1241 /*
1242  * Foward space num records
1243  *  Returns: false on failure
1244  *           true  on success
1245  */
1246 bool DEVICE::fsr(int num)
1247 {
1248    struct mtop mt_com;
1249    int stat;
1250
1251    if (fd < 0) {
1252       dev_errno = EBADF;
1253       Mmsg0(errmsg, _("Bad call to fsr. Device not open\n"));
1254       Emsg0(M_FATAL, 0, errmsg);
1255       return false;
1256    }
1257
1258    if (!is_tape()) {
1259       return false;
1260    }
1261    if (!dev_cap(this, CAP_FSR)) {
1262       Mmsg1(errmsg, _("ioctl MTFSR not permitted on %s.\n"), print_name());
1263       return false;
1264    }
1265
1266    Dmsg1(29, "fsr %d\n", num);
1267    mt_com.mt_op = MTFSR;
1268    mt_com.mt_count = num;
1269    stat = ioctl(fd, MTIOCTOP, (char *)&mt_com);
1270    if (stat == 0) {
1271       clear_eof();
1272       block_num += num;
1273    } else {
1274       berrno be;
1275       struct mtget mt_stat;
1276       clrerror_dev(this, MTFSR);
1277       Dmsg1(100, "FSF fail: ERR=%s\n", be.strerror());
1278       if (dev_get_os_pos(this, &mt_stat)) {
1279          Dmsg4(100, "Adjust from %d:%d to %d:%d\n", file,
1280             block_num, mt_stat.mt_fileno, mt_stat.mt_blkno);
1281          file = mt_stat.mt_fileno;
1282          block_num = mt_stat.mt_blkno;
1283       } else {
1284          if (at_eof()) {
1285             set_eot();
1286          } else {
1287             set_ateof();
1288          }
1289       }
1290       Mmsg3(errmsg, _("ioctl MTFSR %d error on %s. ERR=%s.\n"),
1291          num, print_name(), be.strerror());
1292    }
1293    update_pos_dev(this);
1294    return stat == 0;
1295 }
1296
1297 /*
1298  * Backward space a record
1299  *   Returns:  false on failure
1300  *             true  on success
1301  */
1302 bool
1303 bsr_dev(DEVICE *dev, int num)
1304 {
1305    struct mtop mt_com;
1306    int stat;
1307
1308    if (dev->fd < 0) {
1309       dev->dev_errno = EBADF;
1310       Mmsg0(dev->errmsg, _("Bad call to bsr_dev. Device not open\n"));
1311       Emsg0(M_FATAL, 0, dev->errmsg);
1312       return false;
1313    }
1314
1315    if (!dev->is_tape()) {
1316       return false;
1317    }
1318
1319    if (!dev_cap(dev, CAP_BSR)) {
1320       Mmsg1(dev->errmsg, _("ioctl MTBSR not permitted on %s.\n"), dev->print_name());
1321       return false;
1322    }
1323
1324    Dmsg0(29, "bsr_dev\n");
1325    dev->block_num -= num;
1326    dev->state &= ~(ST_EOF|ST_EOT|ST_EOF);
1327    mt_com.mt_op = MTBSR;
1328    mt_com.mt_count = num;
1329    stat = ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
1330    if (stat < 0) {
1331       berrno be;
1332       clrerror_dev(dev, MTBSR);
1333       Mmsg2(dev->errmsg, _("ioctl MTBSR error on %s. ERR=%s.\n"),
1334          dev->print_name(), be.strerror());
1335    }
1336    update_pos_dev(dev);
1337    return stat == 0;
1338 }
1339
1340 /*
1341  * Reposition the device to file, block
1342  * Returns: false on failure
1343  *          true  on success
1344  */
1345 bool
1346 reposition_dev(DEVICE *dev, uint32_t file, uint32_t block)
1347 {
1348    if (dev->fd < 0) {
1349       dev->dev_errno = EBADF;
1350       Mmsg0(dev->errmsg, _("Bad call to reposition_dev. Device not open\n"));
1351       Emsg0(M_FATAL, 0, dev->errmsg);
1352       return false;
1353    }
1354
1355    if (!dev->is_tape()) {
1356       off_t pos = (((off_t)file)<<32) + block;
1357       Dmsg1(100, "===== lseek_dev to %d\n", (int)pos);
1358       if (lseek_dev(dev, pos, SEEK_SET) == (off_t)-1) {
1359          berrno be;
1360          dev->dev_errno = errno;
1361          Mmsg2(dev->errmsg, _("lseek_dev error on %s. ERR=%s.\n"),
1362             dev->print_name(), be.strerror());
1363          return false;
1364       }
1365       dev->file = file;
1366       dev->block_num = block;
1367       dev->file_addr = pos;
1368       return true;
1369    }
1370    Dmsg4(100, "reposition_dev from %u:%u to %u:%u\n",
1371       dev->file, dev->block_num, file, block);
1372    if (file < dev->file) {
1373       Dmsg0(100, "Rewind_dev\n");
1374       if (!rewind_dev(dev)) {
1375          return false;
1376       }
1377    }
1378    if (file > dev->file) {
1379       Dmsg1(100, "fsf %d\n", file-dev->file);
1380       if (!fsf_dev(dev, file-dev->file)) {
1381          Dmsg1(100, "fsf failed! ERR=%s\n", strerror_dev(dev));
1382          return false;
1383       }
1384       Dmsg2(100, "wanted_file=%d at_file=%d\n", file, dev->file);
1385    }
1386    if (block < dev->block_num) {
1387       Dmsg2(100, "wanted_blk=%d at_blk=%d\n", block, dev->block_num);
1388       Dmsg0(100, "bsf_dev 1\n");
1389       bsf_dev(dev, 1);
1390       Dmsg0(100, "fsf_dev 1\n");
1391       fsf_dev(dev, 1);
1392       Dmsg2(100, "wanted_blk=%d at_blk=%d\n", block, dev->block_num);
1393    }
1394    if (dev_cap(dev, CAP_POSITIONBLOCKS) && block > dev->block_num) {
1395       /* Ignore errors as Bacula can read to the correct block */
1396       Dmsg1(100, "fsr %d\n", block-dev->block_num);
1397       return dev->fsr(block-dev->block_num);
1398    }
1399    return true;
1400 }
1401
1402
1403
1404 /*
1405  * Write an end of file on the device
1406  *   Returns: 0 on success
1407  *            non-zero on failure
1408  */
1409 int
1410 weof_dev(DEVICE *dev, int num)
1411 {
1412    struct mtop mt_com;
1413    int stat;
1414    Dmsg0(29, "weof_dev\n");
1415    
1416    if (dev->fd < 0) {
1417       dev->dev_errno = EBADF;
1418       Mmsg0(dev->errmsg, _("Bad call to weof_dev. Device not open\n"));
1419       Emsg0(M_FATAL, 0, dev->errmsg);
1420       return -1;
1421    }
1422    dev->file_size = 0;
1423
1424    if (!dev->is_tape()) {
1425       return 0;
1426    }
1427    if (!dev->can_append()) {
1428       Mmsg0(dev->errmsg, _("Attempt to WEOF on non-appendable Volume\n"));
1429       Emsg0(M_FATAL, 0, dev->errmsg);
1430       return -1;
1431    }
1432       
1433    dev->state &= ~(ST_EOT | ST_EOF);  /* remove EOF/EOT flags */
1434    mt_com.mt_op = MTWEOF;
1435    mt_com.mt_count = num;
1436    stat = ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
1437    if (stat == 0) {
1438       dev->block_num = 0;
1439       dev->file += num;
1440       dev->file_addr = 0;
1441    } else {
1442       berrno be;
1443       clrerror_dev(dev, MTWEOF);
1444       if (stat == -1) {
1445          Mmsg2(dev->errmsg, _("ioctl MTWEOF error on %s. ERR=%s.\n"),
1446             dev->print_name(), be.strerror());
1447        }
1448    }
1449    return stat;
1450 }
1451
1452 /*
1453  * Return string message with last error in English
1454  *  Be careful not to call this routine from within dev.c
1455  *  while editing an Mmsg() or you will end up in a recursive
1456  *  loop creating a Segmentation Violation.
1457  */
1458 char *
1459 strerror_dev(DEVICE *dev)
1460 {
1461    return dev->errmsg;
1462 }
1463
1464
1465 /*
1466  * If implemented in system, clear the tape
1467  * error status.
1468  */
1469 void
1470 clrerror_dev(DEVICE *dev, int func)
1471 {
1472    const char *msg = NULL;
1473    struct mtget mt_stat;
1474    char buf[100];
1475
1476    dev->dev_errno = errno;         /* save errno */
1477    if (errno == EIO) {
1478       dev->VolCatInfo.VolCatErrors++;
1479    }
1480
1481    if (!dev->is_tape()) {
1482       return;
1483    }
1484    if (errno == ENOTTY || errno == ENOSYS) { /* Function not implemented */
1485       switch (func) {
1486       case -1:
1487          Emsg0(M_ABORT, 0, "Got ENOTTY on read/write!\n");
1488          break;
1489       case MTWEOF:
1490          msg = "WTWEOF";
1491          dev->capabilities &= ~CAP_EOF; /* turn off feature */
1492          break;
1493 #ifdef MTEOM
1494       case MTEOM:
1495          msg = "WTEOM";
1496          dev->capabilities &= ~CAP_EOM; /* turn off feature */
1497          break;
1498 #endif
1499       case MTFSF:
1500          msg = "MTFSF";
1501          dev->capabilities &= ~CAP_FSF; /* turn off feature */
1502          break;
1503       case MTBSF:
1504          msg = "MTBSF";
1505          dev->capabilities &= ~CAP_BSF; /* turn off feature */
1506          break;
1507       case MTFSR:
1508          msg = "MTFSR";
1509          dev->capabilities &= ~CAP_FSR; /* turn off feature */
1510          break;
1511       case MTBSR:
1512          msg = "MTBSR";
1513          dev->capabilities &= ~CAP_BSR; /* turn off feature */
1514          break;
1515       case MTREW:
1516          msg = "MTREW";
1517          break;
1518 #ifdef MTSETBLK
1519       case MTSETBLK:
1520          msg = "MTSETBLK";
1521          break;
1522 #endif
1523 #ifdef MTSETBSIZ 
1524       case MTSETBSIZ:
1525          msg = "MTSETBSIZ";
1526          break;
1527 #endif
1528 #ifdef MTSRSZ
1529       case MTSRSZ:
1530          msg = "MTSRSZ";
1531          break;
1532 #endif
1533       default:
1534          bsnprintf(buf, sizeof(buf), "unknown func code %d", func);
1535          msg = buf;
1536          break;
1537       }
1538       if (msg != NULL) {
1539          dev->dev_errno = ENOSYS;
1540          Mmsg1(dev->errmsg, _("I/O function \"%s\" not supported on this device.\n"), msg);
1541          Emsg0(M_ERROR, 0, dev->errmsg);
1542       }
1543    }
1544    /* On some systems such as NetBSD, this clears all errors */
1545    ioctl(dev->fd, MTIOCGET, (char *)&mt_stat);
1546
1547 /* Found on Linux */
1548 #ifdef MTIOCLRERR
1549 {
1550    struct mtop mt_com;
1551    mt_com.mt_op = MTIOCLRERR;
1552    mt_com.mt_count = 1;
1553    /* Clear any error condition on the tape */
1554    ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
1555    Dmsg0(200, "Did MTIOCLRERR\n");
1556 }
1557 #endif
1558
1559 /* Typically on FreeBSD */
1560 #ifdef MTIOCERRSTAT
1561 {
1562    /* Read and clear SCSI error status */
1563    union mterrstat mt_errstat;
1564    Dmsg2(200, "Doing MTIOCERRSTAT errno=%d ERR=%s\n", dev->dev_errno,
1565       strerror(dev->dev_errno));
1566    ioctl(dev->fd, MTIOCERRSTAT, (char *)&mt_errstat);
1567 }
1568 #endif
1569
1570 /* Clear Subsystem Exception OSF1 */
1571 #ifdef MTCSE
1572 {
1573    struct mtop mt_com;
1574    mt_com.mt_op = MTCSE;
1575    mt_com.mt_count = 1;
1576    /* Clear any error condition on the tape */
1577    ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
1578    Dmsg0(200, "Did MTCSE\n");
1579 }
1580 #endif
1581 }
1582
1583 /*
1584  * Flush buffer contents
1585  *  No longer used.
1586  */
1587 int flush_dev(DEVICE *dev)
1588 {
1589    return 1;
1590 }
1591
1592 static void do_close(DEVICE *dev)
1593 {
1594
1595    Dmsg1(29, "really close_dev %s\n", dev->print_name());
1596    if (dev->fd >= 0) {
1597       close(dev->fd);
1598    }
1599
1600    if (unmount_dev(dev, 1) < 0) {
1601       Dmsg1(0, "Cannot unmount device %s.\n", dev->print_name());
1602    }
1603    
1604    /* Remove the last part file if it is empty */
1605    if (dev->can_append() && (dev->num_parts > 0)) {
1606       struct stat statp;
1607       POOL_MEM archive_name(PM_FNAME);
1608       dev->part = dev->num_parts;
1609       Dmsg1(100, "Call make_dvd_filename. Vol=%s\n", dev->VolCatInfo.VolCatName);
1610       make_spooled_dvd_filename(dev, archive_name);
1611       /* Check that the part file is empty */
1612       if ((stat(archive_name.c_str(), &statp) == 0) && (statp.st_size == 0)) {
1613          Dmsg1(100, "unlink(%s)\n", archive_name.c_str());
1614          unlink(archive_name.c_str());
1615       }
1616    }
1617    
1618    /* Clean up device packet so it can be reused */
1619    dev->fd = -1;
1620    dev->state &= ~(ST_OPENED|ST_LABEL|ST_READ|ST_APPEND|ST_EOT|ST_WEOT|ST_EOF);
1621    dev->label_type = B_BACULA_LABEL;
1622    dev->file = dev->block_num = 0;
1623    dev->file_size = 0;
1624    dev->file_addr = 0;
1625    dev->part = 0;
1626    dev->part_size = 0;
1627    dev->part_start = 0;
1628    dev->EndFile = dev->EndBlock = 0;
1629    memset(&dev->VolCatInfo, 0, sizeof(dev->VolCatInfo));
1630    memset(&dev->VolHdr, 0, sizeof(dev->VolHdr));
1631    if (dev->tid) {
1632       stop_thread_timer(dev->tid);
1633       dev->tid = 0;
1634    }
1635    dev->use_count = 0;
1636    dev->openmode = 0;
1637 }
1638
1639 /*
1640  * Close the device
1641  */
1642 void DEVICE::close()
1643 {
1644    /*if (fd >= 0 && use_count == 1) {*/
1645    /* No need to check if fd >= 0: it is checked again
1646     * in do_close, and do_close MUST be called for volumes
1647     * splitted in parts, even if fd == -1. */
1648    if (use_count == 1) {
1649       do_close(this);
1650    } else if (use_count > 0) {
1651       use_count--;
1652    }
1653
1654 #ifdef FULL_DEBUG
1655    ASSERT(use_count >= 0);
1656 #endif
1657 }
1658
1659
1660 bool truncate_dev(DEVICE *dev)
1661 {
1662    Dmsg1(100, "truncate_dev %s\n", dev->print_name());
1663    if (dev->is_tape()) {
1664       return true;                    /* we don't really truncate tapes */
1665       /* maybe we should rewind and write and eof ???? */
1666    }
1667    
1668    if (dev->is_dvd()) {
1669       Mmsg1(dev->errmsg, _("Truncate DVD %s not supported.\n"), dev->print_name());
1670       return false;   /* we cannot truncate DVDs */
1671    }
1672    
1673    if (ftruncate(dev->fd, 0) != 0) {
1674       berrno be;
1675       Mmsg2(dev->errmsg, _("Unable to truncate device %s. ERR=%s\n"), 
1676             dev->print_name(), be.strerror());
1677       return false;
1678    }
1679    return true;
1680 }
1681
1682 /* Return the resource name for the device */
1683 const char *DEVICE::name() const
1684 {
1685    return device->hdr.name;
1686 }
1687
1688 char *
1689 dev_vol_name(DEVICE *dev)
1690 {
1691    return dev->VolCatInfo.VolCatName;
1692 }
1693
1694 uint32_t dev_block(DEVICE *dev)
1695 {
1696    update_pos_dev(dev);
1697    return dev->block_num;
1698 }
1699
1700 uint32_t dev_file(DEVICE *dev)
1701 {
1702    update_pos_dev(dev);
1703    return dev->file;
1704 }
1705
1706 /*
1707  * Free memory allocated for the device
1708  */
1709 void
1710 term_dev(DEVICE *dev)
1711 {
1712    if (!dev) {
1713       dev->dev_errno = EBADF;
1714       Mmsg0(dev->errmsg, _("Bad call to term_dev. Device not open\n"));
1715       Emsg0(M_FATAL, 0, dev->errmsg);
1716       return;
1717    }
1718    Dmsg1(29, "term_dev: %s\n", dev->print_name());
1719    do_close(dev);
1720    if (dev->dev_name) {
1721       free_memory(dev->dev_name);
1722       dev->dev_name = NULL;
1723    }
1724    if (dev->prt_name) {
1725       free_memory(dev->prt_name);
1726       dev->prt_name = NULL;
1727    }
1728    if (dev->errmsg) {
1729       free_pool_memory(dev->errmsg);
1730       dev->errmsg = NULL;
1731    }
1732    pthread_mutex_destroy(&dev->mutex);
1733    pthread_cond_destroy(&dev->wait);
1734    pthread_cond_destroy(&dev->wait_next_vol);
1735    pthread_mutex_destroy(&dev->spool_mutex);
1736    rwl_destroy(&dev->lock);
1737    if (dev->attached_dcrs) {
1738       delete dev->attached_dcrs;
1739       dev->attached_dcrs = NULL;
1740    }
1741    if (dev->state & ST_MALLOC) {
1742       free_pool_memory((POOLMEM *)dev);
1743    }
1744 }
1745
1746 /*
1747  * This routine initializes the device wait timers
1748  */
1749 void init_device_wait_timers(DCR *dcr)
1750 {
1751    DEVICE *dev = dcr->dev;
1752    JCR *jcr = dcr->jcr;
1753
1754    /* ******FIXME******* put these on config variables */
1755    dev->min_wait = 60 * 60;
1756    dev->max_wait = 24 * 60 * 60;
1757    dev->max_num_wait = 9;              /* 5 waits =~ 1 day, then 1 day at a time */
1758    dev->wait_sec = dev->min_wait;
1759    dev->rem_wait_sec = dev->wait_sec;
1760    dev->num_wait = 0;
1761    dev->poll = false;
1762    dev->BadVolName[0] = 0;
1763
1764    jcr->min_wait = 60 * 60;
1765    jcr->max_wait = 24 * 60 * 60;
1766    jcr->max_num_wait = 9;              /* 5 waits =~ 1 day, then 1 day at a time */
1767    jcr->wait_sec = jcr->min_wait;
1768    jcr->rem_wait_sec = jcr->wait_sec;
1769    jcr->num_wait = 0;
1770
1771 }
1772
1773 void init_jcr_device_wait_timers(JCR *jcr)
1774 {
1775    /* ******FIXME******* put these on config variables */
1776    jcr->min_wait = 60 * 60;
1777    jcr->max_wait = 24 * 60 * 60;
1778    jcr->max_num_wait = 9;              /* 5 waits =~ 1 day, then 1 day at a time */
1779    jcr->wait_sec = jcr->min_wait;
1780    jcr->rem_wait_sec = jcr->wait_sec;
1781    jcr->num_wait = 0;
1782 }
1783
1784
1785 /*
1786  * The dev timers are used for waiting on a particular device 
1787  *
1788  * Returns: true if time doubled
1789  *          false if max time expired
1790  */
1791 bool double_dev_wait_time(DEVICE *dev)
1792 {
1793    dev->wait_sec *= 2;               /* double wait time */
1794    if (dev->wait_sec > dev->max_wait) {   /* but not longer than maxtime */
1795       dev->wait_sec = dev->max_wait;
1796    }
1797    dev->num_wait++;
1798    dev->rem_wait_sec = dev->wait_sec;
1799    if (dev->num_wait >= dev->max_num_wait) {
1800       return false;
1801    }
1802    return true;
1803 }
1804
1805
1806 void set_os_device_parameters(DEVICE *dev)
1807 {
1808 #ifdef HAVE_LINUX_OS
1809    struct mtop mt_com;
1810    if (dev->min_block_size == dev->max_block_size &&
1811        dev->min_block_size == 0) {    /* variable block mode */
1812       mt_com.mt_op = MTSETBLK;
1813       mt_com.mt_count = 0;
1814       if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
1815          clrerror_dev(dev, MTSETBLK);
1816       }
1817       mt_com.mt_op = MTSETDRVBUFFER;
1818       mt_com.mt_count = MT_ST_CLEARBOOLEANS;
1819       if (!dev_cap(dev, CAP_TWOEOF)) {
1820          mt_com.mt_count |= MT_ST_TWO_FM;
1821       }
1822       if (dev_cap(dev, CAP_EOM)) {
1823          mt_com.mt_count |= MT_ST_FAST_MTEOM;
1824       }
1825       if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
1826          clrerror_dev(dev, MTSETBLK);
1827       }
1828    }
1829    return;
1830 #endif
1831
1832 #ifdef HAVE_NETBSD_OS
1833    struct mtop mt_com;
1834    if (dev->min_block_size == dev->max_block_size &&
1835        dev->min_block_size == 0) {    /* variable block mode */
1836       mt_com.mt_op = MTSETBSIZ;
1837       mt_com.mt_count = 0;
1838       if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
1839          clrerror_dev(dev, MTSETBSIZ);
1840       }
1841       /* Get notified at logical end of tape */
1842       mt_com.mt_op = MTEWARN;
1843       mt_com.mt_count = 1;
1844       if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
1845          clrerror_dev(dev, MTEWARN);
1846       }
1847    }
1848    return;
1849 #endif
1850
1851 #if HAVE_FREEBSD_OS || HAVE_OPENBSD_OS
1852    struct mtop mt_com;
1853    if (dev->min_block_size == dev->max_block_size &&
1854        dev->min_block_size == 0) {    /* variable block mode */
1855       mt_com.mt_op = MTSETBSIZ;
1856       mt_com.mt_count = 0;
1857       if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
1858          clrerror_dev(dev, MTSETBSIZ);
1859       }
1860    }
1861    return;
1862 #endif
1863
1864 #ifdef HAVE_SUN_OS
1865    struct mtop mt_com;
1866    if (dev->min_block_size == dev->max_block_size &&
1867        dev->min_block_size == 0) {    /* variable block mode */
1868       mt_com.mt_op = MTSRSZ;
1869       mt_com.mt_count = 0;
1870       if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
1871          clrerror_dev(dev, MTSRSZ);
1872       }
1873    }
1874    return;
1875 #endif
1876 }
1877
1878 static bool dev_get_os_pos(DEVICE *dev, struct mtget *mt_stat)
1879 {
1880    return dev_cap(dev, CAP_MTIOCGET) && 
1881           ioctl(dev->fd, MTIOCGET, (char *)mt_stat) == 0 &&
1882           mt_stat->mt_fileno >= 0;
1883 }
1884
1885 static char *modes[] = {
1886    "CREATE_READ_WRITE",
1887    "OPEN_READ_WRITE",
1888    "OPEN_READ_ONLY",
1889    "OPEN_WRITE_ONLY"
1890 };
1891
1892
1893 static char *mode_to_str(int mode)  
1894 {
1895    return modes[mode-1];
1896 }