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