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