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