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