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