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