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