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