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