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