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