]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/stored/dev.c
More DCR changes
[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-2004 Kern Sibbald and John Walker
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 /* Forward referenced functions */
84
85 /* 
86  * Allocate and initialize the DEVICE structure
87  * Note, if dev is non-NULL, it is already allocated,
88  * thus we neither allocate it nor free it. This allows
89  * the caller to put the packet in shared memory.
90  *
91  *  Note, for a tape, the device->device_name is the device name
92  *     (e.g. /dev/nst0), and for a file, the device name
93  *     is the directory in which the file will be placed.
94  *
95  */
96 DEVICE *
97 init_dev(DEVICE *dev, DEVRES *device)
98 {
99    struct stat statp;
100    bool tape, fifo;
101    int errstat;
102    DCR *dcr = NULL;
103
104    /* Check that device is available */
105    if (stat(device->device_name, &statp) < 0) {
106       if (dev) {
107          dev->dev_errno = errno;
108       } 
109       Emsg2(M_FATAL, 0, "Unable to stat device %s : %s\n", device->device_name, 
110             strerror(errno));
111       return NULL;
112    }
113    tape = false;
114    fifo = false;
115    if (S_ISDIR(statp.st_mode)) {
116       tape = false;
117    } else if (S_ISCHR(statp.st_mode)) {
118       tape = true;
119    } else if (S_ISFIFO(statp.st_mode)) {
120       fifo = true;
121    } else {
122       if (dev) {
123          dev->dev_errno = ENODEV;
124       }
125       Emsg2(M_FATAL, 0, _("%s is an unknown device type. Must be tape or directory. st_mode=%x\n"),
126          device->device_name, statp.st_mode);
127       return NULL;
128    }
129    if (!dev) {
130       dev = (DEVICE *)get_memory(sizeof(DEVICE));
131       memset(dev, 0, sizeof(DEVICE));
132       dev->state = ST_MALLOC;
133    } else {
134       memset(dev, 0, sizeof(DEVICE));
135    }
136
137    /* Copy user supplied device parameters from Resource */
138    dev->dev_name = get_memory(strlen(device->device_name)+1);
139    strcpy(dev->dev_name, device->device_name);
140    dev->capabilities = device->cap_bits;
141    dev->min_block_size = device->min_block_size;
142    dev->max_block_size = device->max_block_size;
143    dev->max_volume_size = device->max_volume_size;
144    dev->max_file_size = device->max_file_size;
145    dev->volume_capacity = device->volume_capacity;
146    dev->max_rewind_wait = device->max_rewind_wait;
147    dev->max_open_wait = device->max_open_wait;
148    dev->max_open_vols = device->max_open_vols;
149    dev->vol_poll_interval = device->vol_poll_interval;
150    dev->max_spool_size = device->max_spool_size;
151    dev->drive_index = device->drive_index;
152    /* Sanity check */
153    if (dev->vol_poll_interval && dev->vol_poll_interval < 60) {
154       dev->vol_poll_interval = 60;
155    }
156    dev->device = device;
157
158    if (tape) {
159       dev->state |= ST_TAPE;
160    } else if (fifo) {
161       dev->state |= ST_FIFO;
162       dev->capabilities |= CAP_STREAM; /* set stream device */
163    } else {
164       dev->state |= ST_FILE;
165    }
166
167    if (dev->max_block_size > 1000000) {
168       Emsg3(M_ERROR, 0, _("Block size %u on device %s is too large, using default %u\n"), 
169          dev->max_block_size, dev->dev_name, DEFAULT_BLOCK_SIZE);
170       dev->max_block_size = 0;
171    }
172    if (dev->max_block_size % TAPE_BSIZE != 0) {
173       Emsg2(M_WARNING, 0, _("Max block size %u not multiple of device %s block size.\n"),
174          dev->max_block_size, dev->dev_name);
175    }   
176          
177    dev->errmsg = get_pool_memory(PM_EMSG);
178    *dev->errmsg = 0;
179
180    if ((errstat = pthread_mutex_init(&dev->mutex, NULL)) != 0) {
181       dev->dev_errno = errstat;
182       Mmsg1(&dev->errmsg, _("Unable to init mutex: ERR=%s\n"), strerror(errstat));
183       Emsg0(M_FATAL, 0, dev->errmsg);
184    }
185    if ((errstat = pthread_cond_init(&dev->wait, NULL)) != 0) {
186       dev->dev_errno = errstat;
187       Mmsg1(&dev->errmsg, _("Unable to init cond variable: ERR=%s\n"), strerror(errstat));
188       Emsg0(M_FATAL, 0, dev->errmsg);
189    }
190    if ((errstat = pthread_cond_init(&dev->wait_next_vol, NULL)) != 0) {
191       dev->dev_errno = errstat;
192       Mmsg1(&dev->errmsg, _("Unable to init cond variable: ERR=%s\n"), strerror(errstat));
193       Emsg0(M_FATAL, 0, dev->errmsg);
194    }
195    if ((errstat = pthread_mutex_init(&dev->spool_mutex, NULL)) != 0) {
196       dev->dev_errno = errstat;
197       Mmsg1(&dev->errmsg, _("Unable to init mutex: ERR=%s\n"), strerror(errstat));
198       Emsg0(M_FATAL, 0, dev->errmsg);
199    }
200 #ifdef xxx
201    if ((errstat = rwl_init(&dev->lock)) != 0) {
202       dev->dev_errno = errstat;
203       Mmsg1(&dev->errmsg, _("Unable to init mutex: ERR=%s\n"), strerror(errstat));
204       Emsg0(M_FATAL, 0, dev->errmsg);
205    }
206 #endif
207
208    dev->fd = -1;
209    dev->attached_dcrs = new dlist(dcr, &dcr->dev_link);
210    Dmsg2(29, "init_dev: tape=%d dev_name=%s\n", dev_is_tape(dev), dev->dev_name);
211
212    return dev;
213 }
214
215 /* Open the device with the operating system and
216  * initialize buffer pointers.
217  *
218  * Note, for a tape, the VolName is the name we give to the
219  *    volume (not really used here), but for a file, the
220  *    VolName represents the name of the file to be created/opened.
221  *    In the case of a file, the full name is the device name
222  *    (archive_name) with the VolName concatenated.
223  */
224 int
225 open_dev(DEVICE *dev, char *VolName, int mode)
226 {
227    POOLMEM *archive_name;
228
229    if (dev->state & ST_OPENED) {
230       /*
231        *  *****FIXME***** how to handle two threads wanting
232        *  different volumes mounted???? E.g. one is waiting
233        *  for the next volume to be mounted, and a new job
234        *  starts and snatches up the device.
235        */
236       if (VolName && strcmp(dev->VolCatInfo.VolCatName, VolName) != 0) {
237          return -1;
238       }
239       dev->use_count++;
240       Mmsg2(&dev->errmsg, _("WARNING!!!! device %s opened %d times!!!\n"), 
241             dev->dev_name, dev->use_count);
242       Emsg1(M_WARNING, 0, "%s", dev->errmsg);
243       return dev->fd;
244    }
245    if (VolName) {
246       bstrncpy(dev->VolCatInfo.VolCatName, VolName, sizeof(dev->VolCatInfo.VolCatName));
247    }
248
249    Dmsg3(29, "open_dev: tape=%d dev_name=%s vol=%s\n", dev_is_tape(dev), 
250          dev->dev_name, dev->VolCatInfo.VolCatName);
251    dev->state &= ~(ST_LABEL|ST_APPEND|ST_READ|ST_EOT|ST_WEOT|ST_EOF);
252    if (dev->state & (ST_TAPE|ST_FIFO)) {
253       int timeout;
254       Dmsg0(29, "open_dev: device is tape\n");
255       if (mode == OPEN_READ_WRITE) {
256          dev->mode = O_RDWR | O_BINARY;
257       } else if (mode == OPEN_READ_ONLY) {
258          dev->mode = O_RDONLY | O_BINARY;
259       } else if (mode == OPEN_WRITE_ONLY) {
260          dev->mode = O_WRONLY | O_BINARY;
261       } else {
262          Emsg0(M_ABORT, 0, _("Illegal mode given to open_dev.\n")); 
263       }
264       timeout = dev->max_open_wait;
265       errno = 0;
266       if (dev->state & ST_FIFO && timeout) {
267          /* Set open timer */
268          dev->tid = start_thread_timer(pthread_self(), timeout);
269       }
270       /* If busy retry each second for max_open_wait seconds */
271       while ((dev->fd = open(dev->dev_name, dev->mode, MODE_RW)) < 0) {
272          if (errno == EINTR || errno == EAGAIN) {
273             continue;
274          }
275          if (errno == EBUSY && timeout-- > 0) {
276             Dmsg2(100, "Device %s busy. ERR=%s\n", dev->dev_name, strerror(errno));
277             bmicrosleep(1, 0);
278             continue;
279          }
280          dev->dev_errno = errno;
281          Mmsg2(&dev->errmsg, _("stored: unable to open device %s: ERR=%s\n"), 
282                dev->dev_name, strerror(dev->dev_errno));
283          /* Stop any open timer we set */
284          if (dev->tid) {
285             stop_thread_timer(dev->tid);
286             dev->tid = 0;
287          }
288          Emsg0(M_FATAL, 0, dev->errmsg);
289          break;
290       }
291       if (dev->fd >= 0) {
292          dev->dev_errno = 0;
293          dev->state |= ST_OPENED;
294          dev->use_count = 1;
295          update_pos_dev(dev);             /* update position */
296       }
297       /* Stop any open() timer we started */
298       if (dev->tid) {
299          stop_thread_timer(dev->tid);
300          dev->tid = 0;
301       }
302       Dmsg1(29, "open_dev: tape %d opened\n", dev->fd);
303    } else {
304       /*
305        * Handle opening of File Archive (not a tape)
306        */
307       if (VolName == NULL || *VolName == 0) {
308          Mmsg(&dev->errmsg, _("Could not open file device %s. No Volume name given.\n"),
309             dev->dev_name);
310          return -1;
311       }
312       archive_name = get_pool_memory(PM_FNAME);
313       pm_strcpy(&archive_name, dev->dev_name);
314       if (archive_name[strlen(archive_name)] != '/') {
315          pm_strcat(&archive_name, "/");
316       }
317       pm_strcat(&archive_name, VolName);
318       Dmsg1(29, "open_dev: device is disk %s\n", archive_name);
319       if (mode == OPEN_READ_WRITE) {
320          dev->mode = O_CREAT | O_RDWR | O_BINARY;
321       } else if (mode == OPEN_READ_ONLY) {
322          dev->mode = O_RDONLY | O_BINARY;
323       } else if (mode == OPEN_WRITE_ONLY) {
324          dev->mode = O_WRONLY | O_BINARY;
325       } else {
326          Emsg0(M_ABORT, 0, _("Illegal mode given to open_dev.\n")); 
327       }
328       /* If creating file, give 0640 permissions */
329       if ((dev->fd = open(archive_name, dev->mode, 0640)) < 0) {
330          dev->dev_errno = errno;
331          Mmsg2(&dev->errmsg, _("Could not open: %s, ERR=%s\n"), archive_name, strerror(dev->dev_errno));
332          Emsg0(M_FATAL, 0, dev->errmsg);
333       } else {
334          dev->dev_errno = 0;
335          dev->state |= ST_OPENED;
336          dev->use_count = 1;
337          update_pos_dev(dev);                /* update position */
338       }
339       Dmsg1(29, "open_dev: disk fd=%d opened\n", dev->fd);
340       free_pool_memory(archive_name);
341    }
342    return dev->fd;
343 }
344
345 #ifdef debug_tracing
346 #undef rewind_dev
347 int _rewind_dev(char *file, int line, DEVICE *dev)
348 {
349    Dmsg2(100, "rewind_dev called from %s:%d\n", file, line);
350    return rewind_dev(dev);
351 }
352 #endif
353
354
355 /*
356  * Rewind the device.
357  *  Returns: 1 on success
358  *           0 on failure
359  */
360 int rewind_dev(DEVICE *dev)
361 {
362    struct mtop mt_com;
363    unsigned int i;
364
365    Dmsg1(29, "rewind_dev %s\n", dev->dev_name);
366    if (dev->fd < 0) {
367       dev->dev_errno = EBADF;
368       Mmsg1(&dev->errmsg, _("Bad call to rewind_dev. Device %s not open\n"),
369             dev->dev_name);
370       Emsg0(M_FATAL, 0, dev->errmsg);
371       return 0;
372    }
373    dev->state &= ~(ST_APPEND|ST_READ|ST_EOT|ST_EOF|ST_WEOT);  /* remove EOF/EOT flags */
374    dev->block_num = dev->file = 0;
375    dev->file_addr = 0;
376    if (dev->state & ST_TAPE) {
377       mt_com.mt_op = MTREW;
378       mt_com.mt_count = 1;
379       /* If we get an I/O error on rewind, it is probably because
380        * the drive is actually busy. We loop for (about 5 minutes)
381        * retrying every 5 seconds.
382        */
383       for (i=dev->max_rewind_wait; ; i -= 5) {
384          if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
385             if (i == dev->max_rewind_wait) {
386                Dmsg1(200, "Rewind error, %s. retrying ...\n", strerror(errno));
387             }
388             clrerror_dev(dev, MTREW);
389             if (dev->dev_errno == EIO && i > 0) {
390                Dmsg0(200, "Sleeping 5 seconds.\n");
391                bmicrosleep(5, 0);
392                continue;
393             }
394             Mmsg2(&dev->errmsg, _("Rewind error on %s. ERR=%s.\n"),
395                dev->dev_name, strerror(dev->dev_errno));
396             return 0;
397          }
398          break;
399       }
400    } else if (dev->state & ST_FILE) {
401       if (lseek(dev->fd, (off_t)0, SEEK_SET) < 0) {
402          dev->dev_errno = errno;
403          Mmsg2(&dev->errmsg, _("lseek error on %s. ERR=%s.\n"),
404             dev->dev_name, strerror(dev->dev_errno));
405          return 0;
406       }
407    }
408    return 1;
409 }
410
411 /* 
412  * Position device to end of medium (end of data)
413  *  Returns: 1 on succes
414  *           0 on error
415  */
416 int 
417 eod_dev(DEVICE *dev)
418 {
419    struct mtop mt_com;
420    struct mtget mt_stat;
421    int stat = 0;
422    off_t pos;
423
424    Dmsg0(29, "eod_dev\n");
425    if (dev->state & ST_EOT) {
426       return 1;
427    }
428    dev->state &= ~(ST_EOF);  /* remove EOF flags */
429    dev->block_num = dev->file = 0;
430    dev->file_addr = 0;
431    if (dev->state & (ST_FIFO | ST_PROG)) {
432       return 1;
433    }
434    if (!(dev->state & ST_TAPE)) {
435       pos = lseek(dev->fd, (off_t)0, SEEK_END);
436 //    Dmsg1(100, "====== Seek to %lld\n", pos);
437       if (pos >= 0) {
438          update_pos_dev(dev);
439          dev->state |= ST_EOT;
440          return 1;
441       }
442       dev->dev_errno = errno;
443       Mmsg2(&dev->errmsg, _("lseek error on %s. ERR=%s.\n"),
444              dev->dev_name, strerror(dev->dev_errno));
445       return 0;
446    }
447 #ifdef MTEOM
448
449    if (dev_cap(dev, CAP_FASTFSF) && !dev_cap(dev, CAP_EOM)) {
450       struct mtget mt_stat;
451       Dmsg0(100,"Using FAST FSF for EOM\n");
452       if (ioctl(dev->fd, MTIOCGET, (char *)&mt_stat) == 0 && mt_stat.mt_fileno <= 0) {
453         if (!rewind_dev(dev)) {
454           return 0;
455         }
456       }
457       mt_com.mt_op = MTFSF;
458       /*
459        * ***FIXEM*** fix code to handle case that INT16_MAX is
460        *   not large enough.
461        */
462       mt_com.mt_count = INT16_MAX;    /* use big positive number */
463       if (mt_com.mt_count < 0) {
464          mt_com.mt_count = INT16_MAX; /* brain damaged system */
465       }
466    }
467
468    if (dev_cap(dev, CAP_EOM)) {
469       Dmsg0(100,"Using EOM for EOM\n");
470       mt_com.mt_op = MTEOM;
471       mt_com.mt_count = 1;
472    }
473    if (dev_cap(dev, CAP_FASTFSF) || dev_cap(dev, CAP_EOM)) {
474       if ((stat=ioctl(dev->fd, MTIOCTOP, (char *)&mt_com)) < 0) {
475          Dmsg1(50, "ioctl error: %s\n", strerror(dev->dev_errno));
476          clrerror_dev(dev, mt_com.mt_op);
477          update_pos_dev(dev);
478          Mmsg2(&dev->errmsg, _("ioctl MTEOM error on %s. ERR=%s.\n"),
479             dev->dev_name, strerror(dev->dev_errno));
480          return 0;
481       }
482
483       if (ioctl(dev->fd, MTIOCGET, (char *)&mt_stat) < 0) {
484          dev->dev_errno = errno;
485          Mmsg2(&dev->errmsg, _("ioctl MTIOCGET error on %s. ERR=%s.\n"),
486             dev->dev_name, strerror(dev->dev_errno));
487          return 0;
488       }
489       Dmsg2(100, "EOD file=%d block=%d\n", mt_stat.mt_fileno, mt_stat.mt_blkno);
490       dev->file = mt_stat.mt_fileno;
491
492    /*
493     * Rewind then use FSF until EOT reached
494     */
495    } else {
496 #else
497    {
498 #endif
499       if (!rewind_dev(dev)) {
500          return 0;
501       }
502       /* 
503        * Move file by file to the end of the tape
504        */
505       int file_num;
506       for (file_num=dev->file; !(dev->state & ST_EOT); file_num++) {
507          Dmsg0(200, "eod_dev: doing fsf 1\n");
508          if (!fsf_dev(dev, 1)) {
509             Dmsg0(200, "fsf_dev error.\n");
510             return 0;
511          }
512          /*
513           * Avoid infinite loop. ***FIXME*** possibly add code
514           *   to set EOD or to turn off CAP_FASTFSF if on.
515           */
516          if (file_num == (int)dev->file) {
517             struct mtget mt_stat;
518             Dmsg1(100, "fsf_dev did not advance from file %d\n", file_num);
519             if (ioctl(dev->fd, MTIOCGET, (char *)&mt_stat) == 0 && 
520                       mt_stat.mt_fileno >= 0) {
521                Dmsg2(000, "Adjust file from %d to %d\n", dev->file , mt_stat.mt_fileno);
522                dev->file = mt_stat.mt_fileno;
523             }
524             stat = 0;
525             break;                    /* we are not progressing, bail out */
526          }
527       }
528    }
529    /*
530     * Some drivers leave us after second EOF when doing
531     * MTEOM, so we must backup so that appending overwrites
532     * the second EOF.
533     */
534    if (dev_cap(dev, CAP_BSFATEOM)) {
535       struct mtget mt_stat;
536       /* Backup over EOF */
537       stat = bsf_dev(dev, 1);
538       /* If BSF worked and fileno is known (not -1), set file */
539       if (ioctl(dev->fd, MTIOCGET, (char *)&mt_stat) == 0 && mt_stat.mt_fileno >= 0) {
540          Dmsg2(100, "Adjust file from %d to %d\n", dev->file , mt_stat.mt_fileno);
541          dev->file = mt_stat.mt_fileno;
542       } else {
543          dev->file++;                 /* wing it -- not correct on all OSes */
544       }
545    } else {
546       update_pos_dev(dev);                   /* update position */
547       stat = 1;
548    }
549    Dmsg1(200, "EOD dev->file=%d\n", dev->file);
550    return stat;
551 }
552
553 /*
554  * Set the position of the device -- only for files
555  *   For other devices, there is no generic way to do it.
556  *  Returns: 1 on succes
557  *           0 on error
558  */
559 int update_pos_dev(DEVICE *dev)
560 {
561    off_t pos;
562    int stat = 0;
563
564    if (dev->fd < 0) {
565       dev->dev_errno = EBADF;
566       Mmsg0(&dev->errmsg, _("Bad device call. Archive not open\n"));
567       Emsg0(M_FATAL, 0, dev->errmsg);
568       return 0;
569    }
570
571    /* Find out where we are */
572    if (dev->state & ST_FILE) {
573       dev->file = 0;
574       dev->file_addr = 0;
575       pos = lseek(dev->fd, (off_t)0, SEEK_CUR);
576       if (pos < 0) {
577          Pmsg1(000, "Seek error: ERR=%s\n", strerror(dev->dev_errno));
578          dev->dev_errno = errno;
579          Mmsg2(&dev->errmsg, _("lseek error on %s. ERR=%s.\n"),
580             dev->dev_name, strerror(dev->dev_errno));
581       } else {
582          stat = 1;
583          dev->file_addr = pos;
584       }
585       return stat;
586    }
587    return 1;
588 }
589
590
591 /* 
592  * Return the status of the device.  This was meant
593  * to be a generic routine. Unfortunately, it doesn't
594  * seem possible (at least I do not know how to do it
595  * currently), which means that for the moment, this
596  * routine has very little value.
597  *
598  *   Returns: status
599  */
600 uint32_t status_dev(DEVICE *dev)
601 {
602    struct mtget mt_stat;
603    uint32_t stat = 0;
604
605    if (dev->state & (ST_EOT | ST_WEOT)) {
606       stat |= BMT_EOD;
607       Dmsg0(-20, " EOD");
608    }
609    if (dev->state & ST_EOF) {
610       stat |= BMT_EOF;
611       Dmsg0(-20, " EOF");
612    }
613    if (dev->state & ST_TAPE) {
614       stat |= BMT_TAPE;
615       Dmsg0(-20," Bacula status:");
616       Dmsg2(-20," file=%d block=%d\n", dev->file, dev->block_num);
617       if (ioctl(dev->fd, MTIOCGET, (char *)&mt_stat) < 0) {
618          dev->dev_errno = errno;
619          Mmsg2(&dev->errmsg, _("ioctl MTIOCGET error on %s. ERR=%s.\n"),
620             dev->dev_name, strerror(dev->dev_errno));
621          return 0;
622       }
623       Dmsg0(-20, " Device status:");
624
625 #if defined(HAVE_LINUX_OS)
626       if (GMT_EOF(mt_stat.mt_gstat)) {
627          stat |= BMT_EOF;
628          Dmsg0(-20, " EOF");
629       }
630       if (GMT_BOT(mt_stat.mt_gstat)) {
631          stat |= BMT_BOT;
632          Dmsg0(-20, " BOT");
633       }
634       if (GMT_EOT(mt_stat.mt_gstat)) {
635          stat |= BMT_EOT;
636          Dmsg0(-20, " EOT");
637       }
638       if (GMT_SM(mt_stat.mt_gstat)) {
639          stat |= BMT_SM;
640          Dmsg0(-20, " SM");
641       }
642       if (GMT_EOD(mt_stat.mt_gstat)) {
643          stat |= BMT_EOD;
644          Dmsg0(-20, " EOD");
645       }
646       if (GMT_WR_PROT(mt_stat.mt_gstat)) {
647          stat |= BMT_WR_PROT;
648          Dmsg0(-20, " WR_PROT");
649       }
650       if (GMT_ONLINE(mt_stat.mt_gstat)) {
651          stat |= BMT_ONLINE;
652          Dmsg0(-20, " ONLINE");
653       }
654       if (GMT_DR_OPEN(mt_stat.mt_gstat)) {
655          stat |= BMT_DR_OPEN;
656          Dmsg0(-20, " DR_OPEN");       
657       }
658       if (GMT_IM_REP_EN(mt_stat.mt_gstat)) {
659          stat |= BMT_IM_REP_EN;
660          Dmsg0(-20, " IM_REP_EN");
661       }
662 #endif /* !SunOS && !OSF */
663       Dmsg2(-20, " file=%d block=%d\n", mt_stat.mt_fileno, mt_stat.mt_blkno);
664    } else {
665       stat |= BMT_ONLINE | BMT_BOT;
666    }
667    return stat;
668 }
669
670
671 /*
672  * Load medium in device
673  *  Returns: 1 on success
674  *           0 on failure
675  */
676 int load_dev(DEVICE *dev)
677 {
678 #ifdef MTLOAD
679    struct mtop mt_com;
680 #endif
681
682    if (dev->fd < 0) {
683       dev->dev_errno = EBADF;
684       Mmsg0(&dev->errmsg, _("Bad call to load_dev. Archive not open\n"));
685       Emsg0(M_FATAL, 0, dev->errmsg);
686       return 0;
687    }
688    if (!(dev->state & ST_TAPE)) {
689       return 1;
690    }
691 #ifndef MTLOAD
692    Dmsg0(200, "stored: MTLOAD command not available\n");
693    dev->dev_errno = ENOTTY;           /* function not available */
694    Mmsg2(&dev->errmsg, _("ioctl MTLOAD error on %s. ERR=%s.\n"),
695          dev->dev_name, strerror(dev->dev_errno));      return 0;
696    return 0;
697 #else
698
699    dev->block_num = dev->file = 0;
700    dev->file_addr = 0;
701    mt_com.mt_op = MTLOAD;
702    mt_com.mt_count = 1;
703    if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
704       dev->dev_errno = errno;
705       Mmsg2(&dev->errmsg, _("ioctl MTLOAD error on %s. ERR=%s.\n"),
706          dev->dev_name, strerror(dev->dev_errno));      return 0;
707    }
708    return 1;
709 #endif
710 }
711
712 /*
713  * Rewind device and put it offline
714  *  Returns: 1 on success
715  *           0 on failure
716  */
717 int offline_dev(DEVICE *dev)
718 {
719    struct mtop mt_com;
720
721    if (dev->fd < 0) {
722       dev->dev_errno = EBADF;
723       Mmsg0(&dev->errmsg, _("Bad call to offline_dev. Archive not open\n"));
724       Emsg0(M_FATAL, 0, dev->errmsg);
725       return 0;
726    }
727    if (!(dev->state & ST_TAPE)) {
728       return 1;
729    }
730
731    dev->state &= ~(ST_APPEND|ST_READ|ST_EOT|ST_EOF|ST_WEOT);  /* remove EOF/EOT flags */
732    dev->block_num = dev->file = 0;
733    dev->file_addr = 0;
734 #ifdef MTUNLOCK
735    mt_com.mt_op = MTUNLOCK;
736    mt_com.mt_count = 1;
737    ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
738 #endif
739    mt_com.mt_op = MTOFFL;
740    mt_com.mt_count = 1;
741    if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
742       dev->dev_errno = errno;
743       Mmsg2(&dev->errmsg, _("ioctl MTOFFL error on %s. ERR=%s.\n"),
744          dev->dev_name, strerror(dev->dev_errno));
745       return 0;
746    }
747    Dmsg1(100, "Offlined device %s\n", dev->dev_name);
748    return 1;
749 }
750
751 int offline_or_rewind_dev(DEVICE *dev)
752 {
753    if (dev_cap(dev, CAP_OFFLINEUNMOUNT)) {
754       return offline_dev(dev);
755    } else {
756    /*            
757     * Note, this rewind probably should not be here (it wasn't
758     *  in prior versions of Bacula), but on FreeBSD, this is
759     *  needed in the case the tape was "frozen" due to an error
760     *  such as backspacing after writing and EOF. If it is not
761     *  done, all future references to the drive get and I/O error.
762     */
763       return rewind_dev(dev);
764    }
765 }
766
767 /* 
768  * Foward space a file  
769  *   Returns: 1 on success
770  *            0 on failure
771  */
772 int
773 fsf_dev(DEVICE *dev, int num)
774
775    struct mtget mt_stat;
776    struct mtop mt_com;
777    int stat = 0;
778
779    if (dev->fd < 0) {
780       dev->dev_errno = EBADF;
781       Mmsg0(&dev->errmsg, _("Bad call to fsf_dev. Archive not open\n"));
782       Emsg0(M_FATAL, 0, dev->errmsg);
783       return 0;
784    }
785
786    if (!(dev->state & ST_TAPE)) {
787       return 1;
788    }
789    if (dev->state & ST_EOT) {
790       dev->dev_errno = 0;
791       Mmsg1(&dev->errmsg, _("Device %s at End of Tape.\n"), dev->dev_name);
792       return 0;
793    }
794    if (dev->state & ST_EOF) {
795       Dmsg0(200, "ST_EOF set on entry to FSF\n");
796    }
797       
798    Dmsg0(29, "fsf_dev\n");
799    dev->block_num = 0;
800    /*
801     * If Fast forward space file is set, then we
802     *  use MTFSF to forward space and MTIOCGET
803     *  to get the file position. We assume that 
804     *  the SCSI driver will ensure that we do not
805     *  forward space over the end of data mark.
806     */
807    if (dev_cap(dev, CAP_FSF) && dev_cap(dev, CAP_FASTFSF)) {
808       mt_com.mt_op = MTFSF;
809       mt_com.mt_count = num;
810       stat = ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
811       if (stat < 0 || ioctl(dev->fd, MTIOCGET, (char *)&mt_stat) < 0) {
812          dev->state |= ST_EOT;
813          Dmsg0(200, "Set ST_EOT\n");
814          clrerror_dev(dev, MTFSF);
815          Mmsg2(&dev->errmsg, _("ioctl MTFSF error on %s. ERR=%s.\n"),
816             dev->dev_name, strerror(dev->dev_errno));
817          Dmsg1(200, "%s", dev->errmsg);
818          return 0;
819       }
820       Dmsg2(200, "fsf file=%d block=%d\n", mt_stat.mt_fileno, mt_stat.mt_blkno);
821       dev->file = mt_stat.mt_fileno;
822       dev->state |= ST_EOF;     /* just read EOF */
823       dev->file_addr = 0;
824       return 1;
825
826    /* 
827     * Here if CAP_FSF is set, and virtually all drives
828     *  these days support it, we read a record, then forward
829     *  space one file. Using this procedure, which is slow,
830     *  is the only way we can be sure that we don't read
831     *  two consecutive EOF marks, which means End of Data.
832     */
833    } else if (dev_cap(dev, CAP_FSF)) {
834       POOLMEM *rbuf;
835       int rbuf_len;
836       Dmsg0(200, "FSF has cap_fsf\n");
837       if (dev->max_block_size == 0) {
838          rbuf_len = DEFAULT_BLOCK_SIZE;
839       } else {
840          rbuf_len = dev->max_block_size;
841       }
842       rbuf = get_memory(rbuf_len);
843       mt_com.mt_op = MTFSF;
844       mt_com.mt_count = 1;
845       while (num-- && !(dev->state & ST_EOT)) {
846          Dmsg0(200, "Doing read before fsf\n");
847          if ((stat = read(dev->fd, (char *)rbuf, rbuf_len)) < 0) {
848             if (errno == ENOMEM) {     /* tape record exceeds buf len */
849                stat = rbuf_len;        /* This is OK */
850             } else {
851                dev->state |= ST_EOT;
852                clrerror_dev(dev, -1);
853                Dmsg2(200, "Set ST_EOT read errno=%d. ERR=%s\n", dev->dev_errno,
854                   strerror(dev->dev_errno));
855                Mmsg2(&dev->errmsg, _("read error on %s. ERR=%s.\n"),
856                   dev->dev_name, strerror(dev->dev_errno));
857                Dmsg1(200, "%s", dev->errmsg);
858                break;
859             }
860          }
861          if (stat == 0) {                /* EOF */
862             update_pos_dev(dev);
863             Dmsg1(200, "End of File mark from read. File=%d\n", dev->file+1);
864             /* Two reads of zero means end of tape */
865             if (dev->state & ST_EOF) {
866                dev->state |= ST_EOT;
867                Dmsg0(200, "Set ST_EOT\n");
868                break;
869             } else {
870                dev->state |= ST_EOF;
871                dev->file++;
872                dev->file_addr = 0;
873                continue;
874             }
875          } else {                        /* Got data */
876             dev->state &= ~(ST_EOF|ST_EOT);
877          }
878
879          Dmsg0(200, "Doing MTFSF\n");
880          stat = ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
881          if (stat < 0) {                 /* error => EOT */
882             dev->state |= ST_EOT;
883             Dmsg0(200, "Set ST_EOT\n");
884             clrerror_dev(dev, MTFSF);
885             Mmsg2(&dev->errmsg, _("ioctl MTFSF error on %s. ERR=%s.\n"),
886                dev->dev_name, strerror(dev->dev_errno));
887             Dmsg0(200, "Got < 0 for MTFSF\n");
888             Dmsg1(200, "%s", dev->errmsg);
889          } else {
890             dev->state |= ST_EOF;     /* just read EOF */
891             dev->file++;
892             dev->file_addr = 0;
893          }   
894       }
895       free_memory(rbuf);
896    
897    /*
898     * No FSF, so use FSR to simulate it
899     */
900    } else {
901       Dmsg0(200, "Doing FSR for FSF\n");
902       while (num-- && !(dev->state & ST_EOT)) {
903          fsr_dev(dev, INT32_MAX);    /* returns -1 on EOF or EOT */
904       }
905       if (dev->state & ST_EOT) {
906          dev->dev_errno = 0;
907          Mmsg1(&dev->errmsg, _("Device %s at End of Tape.\n"), dev->dev_name);
908          stat = -1;
909       } else {
910          stat = 0;
911       }
912    }
913    update_pos_dev(dev);
914    Dmsg1(200, "Return %d from FSF\n", stat);
915    if (dev->state & ST_EOF)
916       Dmsg0(200, "ST_EOF set on exit FSF\n");
917    if (dev->state & ST_EOT)
918       Dmsg0(200, "ST_EOT set on exit FSF\n");
919    Dmsg1(200, "Return from FSF file=%d\n", dev->file);
920    return stat == 0 ? 1 : 0;
921 }
922
923 /* 
924  * Backward space a file  
925  *  Returns: 0 on failure
926  *           1 on success
927  */
928 int
929 bsf_dev(DEVICE *dev, int num)
930
931    struct mtop mt_com;
932    int stat;
933
934    if (dev->fd < 0) {
935       dev->dev_errno = EBADF;
936       Mmsg0(&dev->errmsg, _("Bad call to bsf_dev. Archive device not open\n"));
937       Emsg0(M_FATAL, 0, dev->errmsg);
938       return 0;
939    }
940
941    if (!(dev_state(dev, ST_TAPE))) {
942       Mmsg1(&dev->errmsg, _("Device %s cannot BSF because it is not a tape.\n"),
943          dev->dev_name);
944       return 0;
945    }
946    Dmsg0(29, "bsf_dev\n");
947    dev->state &= ~(ST_EOT|ST_EOF);
948    dev->file -= num;
949    dev->file_addr = 0;
950    mt_com.mt_op = MTBSF;
951    mt_com.mt_count = num;
952    stat = ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
953    if (stat < 0) {
954       clrerror_dev(dev, MTBSF);
955       Mmsg2(&dev->errmsg, _("ioctl MTBSF error on %s. ERR=%s.\n"),
956          dev->dev_name, strerror(dev->dev_errno));
957    }
958    update_pos_dev(dev);
959    return stat == 0 ? 1 : 0;
960 }
961
962
963 /* 
964  * Foward space a record
965  *  Returns: 0 on failure
966  *           1 on success
967  */
968 int
969 fsr_dev(DEVICE *dev, int num)
970
971    struct mtop mt_com;
972    int stat;
973
974    if (dev->fd < 0) {
975       dev->dev_errno = EBADF;
976       Mmsg0(&dev->errmsg, _("Bad call to fsr_dev. Archive not open\n"));
977       Emsg0(M_FATAL, 0, dev->errmsg);
978       return 0;
979    }
980
981    if (!(dev_state(dev, ST_TAPE))) {
982       return 0;
983    }
984    Dmsg0(29, "fsr_dev\n");
985    mt_com.mt_op = MTFSR;
986    mt_com.mt_count = num;
987    stat = ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
988    if (stat == 0) {
989       dev->state &= ~ST_EOF;
990       dev->block_num += num;
991    } else {
992       struct mtget mt_stat;
993       if (ioctl(dev->fd, MTIOCGET, (char *)&mt_stat) == 0 && mt_stat.mt_fileno >= 0) {
994          Dmsg4(100, "Adjust from %d:%d to %d:%d\n", dev->file, 
995             dev->block_num, mt_stat.mt_fileno, mt_stat.mt_blkno);
996          dev->file = mt_stat.mt_fileno;
997          dev->block_num = mt_stat.mt_blkno;
998       } else {
999          if (dev->state & ST_EOF) {
1000             dev->state |= ST_EOT;
1001          } else {
1002             dev->state |= ST_EOF;           /* assume EOF */
1003             dev->file++;
1004             dev->block_num = 0;
1005             dev->file_addr = 0;
1006          }
1007       }
1008       clrerror_dev(dev, MTFSR);
1009       Mmsg2(&dev->errmsg, _("ioctl MTFSR error on %s. ERR=%s.\n"),
1010          dev->dev_name, strerror(dev->dev_errno));
1011    }
1012    update_pos_dev(dev);
1013    return stat == 0 ? 1 : 0;
1014 }
1015
1016 /* 
1017  * Backward space a record
1018  *   Returns:  0 on failure
1019  *             1 on success
1020  */
1021 int
1022 bsr_dev(DEVICE *dev, int num)
1023
1024    struct mtop mt_com;
1025    int stat;
1026
1027    if (dev->fd < 0) {
1028       dev->dev_errno = EBADF;
1029       Mmsg0(&dev->errmsg, _("Bad call to bsr_dev. Archive not open\n"));
1030       Emsg0(M_FATAL, 0, dev->errmsg);
1031       return 0;
1032    }
1033
1034    if (!(dev->state & ST_TAPE)) {
1035       return 0;
1036    }
1037
1038    if (!dev_cap(dev, CAP_BSR)) {
1039       Mmsg1(&dev->errmsg, _("ioctl MTBSR not permitted on %s.\n"),
1040          dev->dev_name);
1041       return 0;
1042    }
1043
1044    Dmsg0(29, "bsr_dev\n");
1045    dev->block_num -= num;
1046    dev->state &= ~(ST_EOF|ST_EOT|ST_EOF);
1047    mt_com.mt_op = MTBSR;
1048    mt_com.mt_count = num;
1049    stat = ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
1050    if (stat < 0) {
1051       clrerror_dev(dev, MTBSR);
1052       Mmsg2(&dev->errmsg, _("ioctl MTBSR error on %s. ERR=%s.\n"),
1053          dev->dev_name, strerror(dev->dev_errno));
1054    }
1055    update_pos_dev(dev);
1056    return stat == 0 ? 1 : 0;
1057 }
1058
1059 /* 
1060  * Reposition the device to file, block
1061  * Returns: 0 on failure
1062  *          1 on success
1063  */
1064 int
1065 reposition_dev(DEVICE *dev, uint32_t file, uint32_t block)
1066
1067    if (dev->fd < 0) {
1068       dev->dev_errno = EBADF;
1069       Mmsg0(&dev->errmsg, _("Bad call to reposition_dev. Archive not open\n"));
1070       Emsg0(M_FATAL, 0, dev->errmsg);
1071       return 0;
1072    }
1073
1074    if (!(dev_state(dev, ST_TAPE))) {
1075       off_t pos = (((off_t)file)<<32) + block;
1076       Dmsg1(100, "===== lseek to %d\n", (int)pos);
1077       if (lseek(dev->fd, pos, SEEK_SET) == (off_t)-1) {
1078          dev->dev_errno = errno;
1079          Mmsg2(&dev->errmsg, _("lseek error on %s. ERR=%s.\n"),
1080             dev->dev_name, strerror(dev->dev_errno));
1081          return 0;
1082       }
1083       dev->file = file;
1084       dev->block_num = block;
1085       dev->file_addr = pos;
1086       return 1;
1087    }
1088    Dmsg4(100, "reposition_dev from %u:%u to %u:%u\n", 
1089       dev->file, dev->block_num, file, block);
1090    if (file < dev->file) {
1091       Dmsg0(100, "Rewind_dev\n");
1092       if (!rewind_dev(dev)) {
1093          return 0;
1094       }
1095    }
1096    if (file > dev->file) {
1097       Dmsg1(100, "fsf %d\n", file-dev->file);
1098       if (!fsf_dev(dev, file-dev->file)) {
1099          return 0;
1100       }
1101    }
1102    if (block < dev->block_num) {
1103       bsf_dev(dev, 1);
1104       fsf_dev(dev, 1);
1105    }
1106    if (block > dev->block_num) {
1107       /* Ignore errors as Bacula can read to the correct block */
1108       Dmsg1(100, "fsr %d\n", block-dev->block_num);
1109       fsr_dev(dev, block-dev->block_num);
1110    }
1111    return 1;
1112 }
1113
1114
1115
1116 /*
1117  * Write an end of file on the device
1118  *   Returns: 0 on success
1119  *            non-zero on failure
1120  */
1121 int 
1122 weof_dev(DEVICE *dev, int num)
1123
1124    struct mtop mt_com;
1125    int stat;
1126
1127    if (dev->fd < 0) {
1128       dev->dev_errno = EBADF;
1129       Mmsg0(&dev->errmsg, _("Bad call to weof_dev. Archive drive not open\n"));
1130       Emsg0(M_FATAL, 0, dev->errmsg);
1131       return -1;
1132    }
1133
1134    if (!(dev_state(dev, ST_TAPE))) {
1135       return 0;
1136    }
1137    dev->state &= ~(ST_EOT | ST_EOF);  /* remove EOF/EOT flags */
1138    dev->block_num = 0;
1139    Dmsg0(29, "weof_dev\n");
1140    mt_com.mt_op = MTWEOF;
1141    mt_com.mt_count = num;
1142    stat = ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
1143    if (stat == 0) {
1144       dev->file += num;
1145       dev->file_addr = 0;
1146    } else {
1147       clrerror_dev(dev, MTWEOF);
1148       if (stat == -1) {
1149          Mmsg2(&dev->errmsg, _("ioctl MTWEOF error on %s. ERR=%s.\n"),
1150             dev->dev_name, strerror(dev->dev_errno));
1151        }
1152    }
1153    return stat;
1154 }
1155
1156 /*
1157  * Return string message with last error in English
1158  *  Be careful not to call this routine from within dev.c
1159  *  while editing an Mmsg(&) or you will end up in a recursive
1160  *  loop creating a Segmentation Violation.
1161  */
1162 char *
1163 strerror_dev(DEVICE *dev)
1164 {
1165    return dev->errmsg;
1166 }
1167
1168
1169 /*
1170  * If implemented in system, clear the tape
1171  * error status.
1172  */
1173 void
1174 clrerror_dev(DEVICE *dev, int func)
1175 {
1176    const char *msg = NULL;
1177
1178    dev->dev_errno = errno;         /* save errno */
1179    if (errno == EIO) {
1180       dev->VolCatInfo.VolCatErrors++;
1181    }
1182
1183    if (!(dev->state & ST_TAPE)) {
1184       return;
1185    }
1186    if (errno == ENOTTY || errno == ENOSYS) { /* Function not implemented */
1187       switch (func) {
1188       case -1:
1189          Emsg0(M_ABORT, 0, "Got ENOTTY on read/write!\n");
1190          break;
1191       case MTWEOF:
1192          msg = "WTWEOF";
1193          dev->capabilities &= ~CAP_EOF; /* turn off feature */
1194          break;
1195 #ifdef MTEOM
1196       case MTEOM:
1197          msg = "WTEOM";
1198          dev->capabilities &= ~CAP_EOM; /* turn off feature */
1199          break;
1200 #endif 
1201       case MTFSF:
1202          msg = "MTFSF";
1203          dev->capabilities &= ~CAP_FSF; /* turn off feature */
1204          break;
1205       case MTBSF:
1206          msg = "MTBSF";
1207          dev->capabilities &= ~CAP_BSF; /* turn off feature */
1208          break;
1209       case MTFSR:
1210          msg = "MTFSR";
1211          dev->capabilities &= ~CAP_FSR; /* turn off feature */
1212          break;
1213       case MTBSR:
1214          msg = "MTBSR";
1215          dev->capabilities &= ~CAP_BSR; /* turn off feature */
1216          break;
1217       default:
1218          msg = "Unknown";
1219          break;
1220       }
1221       if (msg != NULL) {
1222          dev->dev_errno = ENOSYS;
1223          Mmsg1(&dev->errmsg, _("This device does not support %s.\n"), msg);
1224          Emsg0(M_ERROR, 0, dev->errmsg);
1225       }
1226    }
1227 /* Found on Linux */
1228 #ifdef MTIOCLRERR
1229 {
1230    struct mtop mt_com;
1231    mt_com.mt_op = MTIOCLRERR;
1232    mt_com.mt_count = 1;
1233    /* Clear any error condition on the tape */
1234    ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
1235    Dmsg0(200, "Did MTIOCLRERR\n");
1236 }
1237 #endif
1238
1239 /* Typically on FreeBSD */
1240 #ifdef MTIOCERRSTAT
1241 {
1242    /* Read and clear SCSI error status */
1243    union mterrstat mt_errstat;
1244    Dmsg2(200, "Doing MTIOCERRSTAT errno=%d ERR=%s\n", dev->dev_errno,
1245       strerror(dev->dev_errno));
1246    ioctl(dev->fd, MTIOCERRSTAT, (char *)&mt_errstat);
1247 }
1248 #endif
1249 }
1250
1251 /*
1252  * Flush buffer contents
1253  *  No longer used.
1254  */
1255 int flush_dev(DEVICE *dev)
1256 {
1257    return 1;
1258 }
1259
1260 static void do_close(DEVICE *dev)
1261 {
1262
1263    Dmsg1(29, "really close_dev %s\n", dev->dev_name);
1264    if (dev->fd >= 0) {
1265       close(dev->fd);
1266    }
1267    /* Clean up device packet so it can be reused */
1268    dev->fd = -1;
1269    dev->state &= ~(ST_OPENED|ST_LABEL|ST_READ|ST_APPEND|ST_EOT|ST_WEOT|ST_EOF);
1270    dev->file = dev->block_num = 0;
1271    dev->file_addr = 0;
1272    dev->EndFile = dev->EndBlock = 0;
1273    memset(&dev->VolCatInfo, 0, sizeof(dev->VolCatInfo));
1274    memset(&dev->VolHdr, 0, sizeof(dev->VolHdr));
1275    if (dev->tid) {
1276       stop_thread_timer(dev->tid);
1277       dev->tid = 0;
1278    }
1279    dev->use_count = 0;
1280 }
1281
1282 /* 
1283  * Close the device
1284  */
1285 void
1286 close_dev(DEVICE *dev)
1287 {
1288    if (!dev) {
1289       Mmsg0(&dev->errmsg, _("Bad call to close_dev. Archive not open\n"));
1290       Emsg0(M_FATAL, 0, dev->errmsg);
1291       return;
1292    }
1293    if (dev->fd >= 0 && dev->use_count == 1) {
1294       do_close(dev);
1295    } else if (dev->use_count > 0) {
1296       dev->use_count--;
1297    }
1298            
1299 #ifdef FULL_DEBUG
1300    ASSERT(dev->use_count >= 0);
1301 #endif
1302 }
1303
1304 /*
1305  * Used when unmounting the device, ignore use_count
1306  */
1307 void force_close_dev(DEVICE *dev)
1308 {
1309    if (!dev) {
1310       Mmsg0(&dev->errmsg, _("Bad call to force_close_dev. Archive not open\n"));
1311       Emsg0(M_FATAL, 0, dev->errmsg);
1312       return;
1313    }
1314    Dmsg1(29, "Force close_dev %s\n", dev->dev_name);
1315    do_close(dev);
1316
1317 #ifdef FULL_DEBUG
1318    ASSERT(dev->use_count >= 0);
1319 #endif
1320 }
1321
1322 int truncate_dev(DEVICE *dev)
1323 {
1324    if (dev->state & ST_TAPE) {
1325       return 1;
1326    }
1327    if (ftruncate(dev->fd, 0) != 0) {
1328       Mmsg1(&dev->errmsg, _("Unable to truncate device. ERR=%s\n"), strerror(errno));
1329       return 0;
1330    }
1331    return 1;
1332 }
1333
1334 int 
1335 dev_is_tape(DEVICE *dev)
1336 {  
1337    return (dev->state & ST_TAPE) ? 1 : 0;
1338 }
1339
1340
1341 /*
1342  * return 1 if the device is read for write, and 0 otherwise
1343  *   This is meant for checking at the end of a job to see
1344  *   if we still have a tape (perhaps not if at end of tape
1345  *   and the job is canceled).
1346  */
1347 int
1348 dev_can_write(DEVICE *dev)
1349 {
1350    if ((dev->state & ST_OPENED) &&  (dev->state & ST_APPEND) &&
1351        (dev->state & ST_LABEL)  && !(dev->state & ST_WEOT)) {
1352       return 1;
1353    } else {
1354       return 0;
1355    }
1356 }
1357
1358 char *
1359 dev_name(DEVICE *dev)
1360 {
1361    return dev->dev_name;
1362 }
1363
1364 char *
1365 dev_vol_name(DEVICE *dev)
1366 {
1367    return dev->VolCatInfo.VolCatName;
1368 }
1369
1370 uint32_t dev_block(DEVICE *dev)
1371 {
1372    update_pos_dev(dev);
1373    return dev->block_num;
1374 }
1375
1376 uint32_t dev_file(DEVICE *dev)
1377 {
1378    update_pos_dev(dev);
1379    return dev->file;
1380 }
1381
1382 /* 
1383  * Free memory allocated for the device
1384  */
1385 void
1386 term_dev(DEVICE *dev)
1387 {
1388    if (!dev) {
1389       dev->dev_errno = EBADF;
1390       Mmsg0(&dev->errmsg, _("Bad call to term_dev. Archive not open\n"));
1391       Emsg0(M_FATAL, 0, dev->errmsg);
1392       return;
1393    }
1394    do_close(dev);
1395    Dmsg0(29, "term_dev\n");
1396    if (dev->dev_name) {
1397       free_memory(dev->dev_name);
1398       dev->dev_name = NULL;
1399    }
1400    if (dev->errmsg) {
1401       free_pool_memory(dev->errmsg);
1402       dev->errmsg = NULL;
1403    }
1404    pthread_mutex_destroy(&dev->mutex);
1405    pthread_cond_destroy(&dev->wait);
1406    pthread_cond_destroy(&dev->wait_next_vol);
1407    pthread_mutex_destroy(&dev->spool_mutex);
1408    if (dev->attached_dcrs) {
1409       delete dev->attached_dcrs;
1410       dev->attached_dcrs = NULL;
1411    }
1412    if (dev->state & ST_MALLOC) {
1413       free_pool_memory((POOLMEM *)dev);
1414    }
1415 }
1416
1417 /*
1418  * We attach a jcr to the device so that when
1419  *   the Volume is full during writing, a  
1420  *   JobMedia record will be created for this 
1421  *   Job.
1422  */
1423 void attach_jcr_to_device(DEVICE *dev, JCR *jcr)
1424 {
1425    jcr->prev_dev = (JCR *)NULL;
1426    jcr->next_dev = dev->attached_jcrs;
1427    if (dev->attached_jcrs) {
1428       dev->attached_jcrs->prev_dev = jcr;
1429    }
1430    dev->attached_jcrs = jcr;
1431    Dmsg1(100, "Attached Job %s\n", jcr->Job);
1432 }
1433
1434 void detach_jcr_from_device(DEVICE *dev, JCR *jcr)
1435 {
1436    if (!jcr->prev_dev) {
1437       dev->attached_jcrs = jcr->next_dev;
1438    } else {
1439       jcr->prev_dev->next_dev = jcr->next_dev;
1440    }
1441    if (jcr->next_dev) {
1442       jcr->next_dev->prev_dev = jcr->prev_dev; 
1443    }
1444    jcr->next_dev = jcr->prev_dev = NULL;
1445    Dmsg1(100, "Detached Job %s\n", jcr->Job);
1446 }
1447
1448 JCR *next_attached_jcr(DEVICE *dev, JCR *jcr)
1449 {
1450    if (jcr == (JCR *)NULL) {
1451       return dev->attached_jcrs;
1452    }
1453    return jcr->next_dev;
1454 }
1455
1456 /*
1457  * This routine initializes the device wait timers
1458  */
1459 void init_dev_wait_timers(DEVICE *dev)
1460 {
1461    /* ******FIXME******* put these on config variables */
1462    dev->min_wait = 60 * 60;
1463    dev->max_wait = 24 * 60 * 60;
1464    dev->max_num_wait = 9;              /* 5 waits =~ 1 day, then 1 day at a time */
1465    dev->wait_sec = dev->min_wait;
1466    dev->rem_wait_sec = dev->wait_sec;
1467    dev->num_wait = 0;
1468    dev->poll = false;
1469    dev->BadVolName[0] = 0;
1470 }
1471
1472 /*
1473  * Returns: true if time doubled
1474  *          false if max time expired
1475  */
1476 bool double_dev_wait_time(DEVICE *dev)
1477 {
1478    dev->wait_sec *= 2;               /* double wait time */
1479    if (dev->wait_sec > dev->max_wait) {   /* but not longer than maxtime */
1480       dev->wait_sec = dev->max_wait;
1481    }
1482    dev->num_wait++;
1483    dev->rem_wait_sec = dev->wait_sec;
1484    if (dev->num_wait >= dev->max_num_wait) {
1485       return false;
1486    }
1487    return true;
1488 }