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