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