]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/stored/dev.c
- Integrated Preben 'Peppe' Guldberg <peppe@wielders.org>
[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_MTIOCGET) && 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        * ***FIXME*** 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_MTIOCGET) && (dev_cap(dev, CAP_FASTFSF) || dev_cap(dev, CAP_EOM))) {
483       if (dev_cap(dev, CAP_EOM)) {
484          Dmsg0(100,"Using EOM for EOM\n");
485          mt_com.mt_op = MTEOM;
486          mt_com.mt_count = 1;
487       }
488
489       if ((stat=ioctl(dev->fd, MTIOCTOP, (char *)&mt_com)) < 0) {
490          berrno be;
491          clrerror_dev(dev, mt_com.mt_op);
492          Dmsg1(50, "ioctl error: %s\n", be.strerror());
493          update_pos_dev(dev);
494          Mmsg2(&dev->errmsg, _("ioctl MTEOM error on %s. ERR=%s.\n"),
495             dev->dev_name, be.strerror());
496          return 0;
497       }
498
499       if (ioctl(dev->fd, MTIOCGET, (char *)&mt_stat) < 0) {
500          berrno be;
501          clrerror_dev(dev, -1);
502          Mmsg2(&dev->errmsg, _("ioctl MTIOCGET error on %s. ERR=%s.\n"),
503             dev->dev_name, be.strerror());
504          return 0;
505       }
506       Dmsg2(100, "EOD file=%d block=%d\n", mt_stat.mt_fileno, mt_stat.mt_blkno);
507       dev->file = mt_stat.mt_fileno;
508
509    /*
510     * Rewind then use FSF until EOT reached
511     */
512    } else {
513 #else
514    {
515 #endif
516       if (!rewind_dev(dev)) {
517          return 0;
518       }
519       /* 
520        * Move file by file to the end of the tape
521        */
522       int file_num;
523       for (file_num=dev->file; !(dev->state & ST_EOT); file_num++) {
524          Dmsg0(200, "eod_dev: doing fsf 1\n");
525          if (!fsf_dev(dev, 1)) {
526             Dmsg0(200, "fsf_dev error.\n");
527             return 0;
528          }
529          /*
530           * Avoid infinite loop. ***FIXME*** possibly add code
531           *   to set EOD or to turn off CAP_FASTFSF if on.
532           */
533          if (file_num == (int)dev->file) {
534             struct mtget mt_stat;
535             Dmsg1(100, "fsf_dev did not advance from file %d\n", file_num);
536             if (dev_cap(dev, CAP_MTIOCGET) && ioctl(dev->fd, MTIOCGET, (char *)&mt_stat) == 0 && 
537                       mt_stat.mt_fileno >= 0) {
538                Dmsg2(100, "Adjust file from %d to %d\n", dev->file , mt_stat.mt_fileno);
539                dev->file = mt_stat.mt_fileno;
540             }
541             stat = 0;
542             break;                    /* we are not progressing, bail out */
543          }
544       }
545    }
546    /*
547     * Some drivers leave us after second EOF when doing
548     * MTEOM, so we must backup so that appending overwrites
549     * the second EOF.
550     */
551    if (dev_cap(dev, CAP_BSFATEOM)) {
552       struct mtget mt_stat;
553       /* Backup over EOF */
554       stat = bsf_dev(dev, 1);
555       /* If BSF worked and fileno is known (not -1), set file */
556       if (dev_cap(dev, CAP_MTIOCGET) && ioctl(dev->fd, MTIOCGET, (char *)&mt_stat) == 0 && mt_stat.mt_fileno >= 0) {
557          Dmsg2(100, "BSFATEOF adjust file from %d to %d\n", dev->file , mt_stat.mt_fileno);
558          dev->file = mt_stat.mt_fileno;
559       } else {
560          dev->file++;                 /* wing it -- not correct on all OSes */
561       }
562    } else {
563       update_pos_dev(dev);                   /* update position */
564       stat = 1;
565    }
566    Dmsg1(200, "EOD dev->file=%d\n", dev->file);
567    return stat;
568 }
569
570 /*
571  * Set the position of the device -- only for files
572  *   For other devices, there is no generic way to do it.
573  *  Returns: true  on succes
574  *           false on error
575  */
576 bool update_pos_dev(DEVICE *dev)
577 {
578    off_t pos;
579    bool ok = true;
580
581    if (dev->fd < 0) {
582       dev->dev_errno = EBADF;
583       Mmsg0(&dev->errmsg, _("Bad device call. Archive not open\n"));
584       Emsg0(M_FATAL, 0, dev->errmsg);
585       return false;
586    }
587
588    /* Find out where we are */
589    if (dev->state & ST_FILE) {
590       dev->file = 0;
591       dev->file_addr = 0;
592       pos = lseek(dev->fd, (off_t)0, SEEK_CUR);
593       if (pos < 0) {
594          berrno be;
595          dev->dev_errno = errno;
596          Pmsg1(000, "Seek error: ERR=%s\n", be.strerror());
597          Mmsg2(&dev->errmsg, _("lseek error on %s. ERR=%s.\n"),
598             dev->dev_name, be.strerror());
599          ok = false;
600       } else {
601          dev->file_addr = pos;
602       }
603    }
604    return ok;
605 }
606
607
608 /* 
609  * Return the status of the device.  This was meant
610  * to be a generic routine. Unfortunately, it doesn't
611  * seem possible (at least I do not know how to do it
612  * currently), which means that for the moment, this
613  * routine has very little value.
614  *
615  *   Returns: status
616  */
617 uint32_t status_dev(DEVICE *dev)
618 {
619    struct mtget mt_stat;
620    uint32_t stat = 0;
621
622    if (dev->state & (ST_EOT | ST_WEOT)) {
623       stat |= BMT_EOD;
624       Dmsg0(-20, " EOD");
625    }
626    if (dev->state & ST_EOF) {
627       stat |= BMT_EOF;
628       Dmsg0(-20, " EOF");
629    }
630    if (dev->state & ST_TAPE) {
631       stat |= BMT_TAPE;
632       Dmsg0(-20," Bacula status:");
633       Dmsg2(-20," file=%d block=%d\n", dev->file, dev->block_num);
634       if (ioctl(dev->fd, MTIOCGET, (char *)&mt_stat) < 0) {
635          berrno be;
636          dev->dev_errno = errno;
637          Mmsg2(&dev->errmsg, _("ioctl MTIOCGET error on %s. ERR=%s.\n"),
638             dev->dev_name, be.strerror());
639          return 0;
640       }
641       Dmsg0(-20, " Device status:");
642
643 #if defined(HAVE_LINUX_OS)
644       if (GMT_EOF(mt_stat.mt_gstat)) {
645          stat |= BMT_EOF;
646          Dmsg0(-20, " EOF");
647       }
648       if (GMT_BOT(mt_stat.mt_gstat)) {
649          stat |= BMT_BOT;
650          Dmsg0(-20, " BOT");
651       }
652       if (GMT_EOT(mt_stat.mt_gstat)) {
653          stat |= BMT_EOT;
654          Dmsg0(-20, " EOT");
655       }
656       if (GMT_SM(mt_stat.mt_gstat)) {
657          stat |= BMT_SM;
658          Dmsg0(-20, " SM");
659       }
660       if (GMT_EOD(mt_stat.mt_gstat)) {
661          stat |= BMT_EOD;
662          Dmsg0(-20, " EOD");
663       }
664       if (GMT_WR_PROT(mt_stat.mt_gstat)) {
665          stat |= BMT_WR_PROT;
666          Dmsg0(-20, " WR_PROT");
667       }
668       if (GMT_ONLINE(mt_stat.mt_gstat)) {
669          stat |= BMT_ONLINE;
670          Dmsg0(-20, " ONLINE");
671       }
672       if (GMT_DR_OPEN(mt_stat.mt_gstat)) {
673          stat |= BMT_DR_OPEN;
674          Dmsg0(-20, " DR_OPEN");       
675       }
676       if (GMT_IM_REP_EN(mt_stat.mt_gstat)) {
677          stat |= BMT_IM_REP_EN;
678          Dmsg0(-20, " IM_REP_EN");
679       }
680 #endif /* !SunOS && !OSF */
681       if (dev_cap(dev, CAP_MTIOCGET)) {
682          Dmsg2(-20, " file=%d block=%d\n", mt_stat.mt_fileno, mt_stat.mt_blkno);
683       } else {
684          Dmsg2(-20, " file=%d block=%d\n", -1, -1);
685       }
686    } else {
687       stat |= BMT_ONLINE | BMT_BOT;
688    }
689    return stat;
690 }
691
692
693 /*
694  * Load medium in device
695  *  Returns: true  on success
696  *           false on failure
697  */
698 bool load_dev(DEVICE *dev)
699 {
700 #ifdef MTLOAD
701    struct mtop mt_com;
702 #endif
703
704    if (dev->fd < 0) {
705       dev->dev_errno = EBADF;
706       Mmsg0(&dev->errmsg, _("Bad call to load_dev. Archive not open\n"));
707       Emsg0(M_FATAL, 0, dev->errmsg);
708       return false;
709    }
710    if (!(dev->state & ST_TAPE)) {
711       return true;
712    }
713 #ifndef MTLOAD
714    Dmsg0(200, "stored: MTLOAD command not available\n");
715    berrno be;
716    dev->dev_errno = ENOTTY;           /* function not available */
717    Mmsg2(&dev->errmsg, _("ioctl MTLOAD error on %s. ERR=%s.\n"),
718          dev->dev_name, be.strerror());
719    return false;
720 #else
721
722    dev->block_num = dev->file = 0;
723    dev->file_size = 0;
724    dev->file_addr = 0;
725    mt_com.mt_op = MTLOAD;
726    mt_com.mt_count = 1;
727    if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
728       berrno be;
729       dev->dev_errno = errno;
730       Mmsg2(&dev->errmsg, _("ioctl MTLOAD error on %s. ERR=%s.\n"),
731          dev->dev_name, be.strerror());
732       return false;
733    }
734    return true;
735 #endif
736 }
737
738 /*
739  * Rewind device and put it offline
740  *  Returns: true  on success
741  *           false on failure
742  */
743 bool offline_dev(DEVICE *dev)
744 {
745    struct mtop mt_com;
746
747    if (dev->fd < 0) {
748       dev->dev_errno = EBADF;
749       Mmsg0(&dev->errmsg, _("Bad call to offline_dev. Archive not open\n"));
750       Emsg0(M_FATAL, 0, dev->errmsg);
751       return false;
752    }
753    if (!(dev->state & ST_TAPE)) {
754       return true;
755    }
756
757    dev->state &= ~(ST_APPEND|ST_READ|ST_EOT|ST_EOF|ST_WEOT);  /* remove EOF/EOT flags */
758    dev->block_num = dev->file = 0;
759    dev->file_size = 0;
760    dev->file_addr = 0;
761 #ifdef MTUNLOCK
762    mt_com.mt_op = MTUNLOCK;
763    mt_com.mt_count = 1;
764    ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
765 #endif
766    mt_com.mt_op = MTOFFL;
767    mt_com.mt_count = 1;
768    if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
769       berrno be;
770       dev->dev_errno = errno;
771       Mmsg2(&dev->errmsg, _("ioctl MTOFFL error on %s. ERR=%s.\n"),
772          dev->dev_name, be.strerror());
773       return false;
774    }
775    Dmsg1(100, "Offlined device %s\n", dev->dev_name);
776    return true;
777 }
778
779 bool offline_or_rewind_dev(DEVICE *dev)
780 {
781    if (dev->fd < 0) {
782       return false;
783    }
784    if (dev_cap(dev, CAP_OFFLINEUNMOUNT)) {
785       return offline_dev(dev);
786    } else {
787    /*            
788     * Note, this rewind probably should not be here (it wasn't
789     *  in prior versions of Bacula), but on FreeBSD, this is
790     *  needed in the case the tape was "frozen" due to an error
791     *  such as backspacing after writing and EOF. If it is not
792     *  done, all future references to the drive get and I/O error.
793     */
794       clrerror_dev(dev, MTREW);
795       return rewind_dev(dev);
796    }
797 }
798
799 /* 
800  * Foward space a file  
801  *   Returns: true  on success
802  *            false on failure
803  */
804 bool
805 fsf_dev(DEVICE *dev, int num)
806
807    struct mtget mt_stat;
808    struct mtop mt_com;
809    int stat = 0;
810
811    if (dev->fd < 0) {
812       dev->dev_errno = EBADF;
813       Mmsg0(&dev->errmsg, _("Bad call to fsf_dev. Archive not open\n"));
814       Emsg0(M_FATAL, 0, dev->errmsg);
815       return false;
816    }
817
818    if (!(dev->state & ST_TAPE)) {
819       return true;
820    }
821    if (dev->state & ST_EOT) {
822       dev->dev_errno = 0;
823       Mmsg1(dev->errmsg, _("Device %s at End of Tape.\n"), dev->dev_name);
824       return false;
825    }
826    if (dev->state & ST_EOF) {
827       Dmsg0(200, "ST_EOF set on entry to FSF\n");
828    }
829       
830    Dmsg0(100, "fsf_dev\n");
831    dev->block_num = 0;
832    /*
833     * If Fast forward space file is set, then we
834     *  use MTFSF to forward space and MTIOCGET
835     *  to get the file position. We assume that 
836     *  the SCSI driver will ensure that we do not
837     *  forward space past the end of the medium.
838     */
839    if (dev_cap(dev, CAP_FSF) && dev_cap(dev, CAP_MTIOCGET) && dev_cap(dev, CAP_FASTFSF)) {
840       mt_com.mt_op = MTFSF;
841       mt_com.mt_count = num;
842       stat = ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
843       if (stat < 0 || ioctl(dev->fd, MTIOCGET, (char *)&mt_stat) < 0) {
844          berrno be;
845          dev->state |= ST_EOT;
846          Dmsg0(200, "Set ST_EOT\n");
847          clrerror_dev(dev, MTFSF);
848          Mmsg2(dev->errmsg, _("ioctl MTFSF error on %s. ERR=%s.\n"),
849             dev->dev_name, be.strerror());
850          Dmsg1(200, "%s", dev->errmsg);
851          return false;
852       }
853       Dmsg2(200, "fsf file=%d block=%d\n", mt_stat.mt_fileno, mt_stat.mt_blkno);
854       dev->file = mt_stat.mt_fileno;
855       dev->state |= ST_EOF;     /* just read EOF */
856       dev->file_addr = 0;
857       dev->file_size = 0;
858       return true;
859
860    /* 
861     * Here if CAP_FSF is set, and virtually all drives
862     *  these days support it, we read a record, then forward
863     *  space one file. Using this procedure, which is slow,
864     *  is the only way we can be sure that we don't read
865     *  two consecutive EOF marks, which means End of Data.
866     */
867    } else if (dev_cap(dev, CAP_FSF)) {
868       POOLMEM *rbuf;
869       int rbuf_len;
870       Dmsg0(200, "FSF has cap_fsf\n");
871       if (dev->max_block_size == 0) {
872          rbuf_len = DEFAULT_BLOCK_SIZE;
873       } else {
874          rbuf_len = dev->max_block_size;
875       }
876       rbuf = get_memory(rbuf_len);
877       mt_com.mt_op = MTFSF;
878       mt_com.mt_count = 1;
879       while (num-- && !(dev->state & ST_EOT)) {
880          Dmsg0(100, "Doing read before fsf\n");
881          if ((stat = read(dev->fd, (char *)rbuf, rbuf_len)) < 0) {
882             if (errno == ENOMEM) {     /* tape record exceeds buf len */
883                stat = rbuf_len;        /* This is OK */
884             } else {
885                berrno be;
886                dev->state |= ST_EOT;
887                clrerror_dev(dev, -1);
888                Dmsg2(100, "Set ST_EOT read errno=%d. ERR=%s\n", dev->dev_errno,
889                   be.strerror());
890                Mmsg2(dev->errmsg, _("read error on %s. ERR=%s.\n"),
891                   dev->dev_name, be.strerror());
892                Dmsg1(100, "%s", dev->errmsg);
893                break;
894             }
895          }
896          if (stat == 0) {                /* EOF */
897             update_pos_dev(dev);
898             Dmsg1(100, "End of File mark from read. File=%d\n", dev->file+1);
899             /* Two reads of zero means end of tape */
900             if (dev->state & ST_EOF) {
901                dev->state |= ST_EOT;
902                Dmsg0(100, "Set ST_EOT\n");
903                break;
904             } else {
905                dev->state |= ST_EOF;
906                dev->file++;
907                dev->file_addr = 0;
908                dev->file_size = 0;
909                continue;
910             }
911          } else {                        /* Got data */
912             dev->state &= ~(ST_EOF|ST_EOT);
913          }
914
915          Dmsg0(100, "Doing MTFSF\n");
916          stat = ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
917          if (stat < 0) {                 /* error => EOT */
918             berrno be;
919             dev->state |= ST_EOT;
920             Dmsg0(100, "Set ST_EOT\n");
921             clrerror_dev(dev, MTFSF);
922             Mmsg2(&dev->errmsg, _("ioctl MTFSF error on %s. ERR=%s.\n"),
923                dev->dev_name, be.strerror());
924             Dmsg0(100, "Got < 0 for MTFSF\n");
925             Dmsg1(100, "%s", dev->errmsg);
926          } else {
927             dev->state |= ST_EOF;     /* just read EOF */
928             dev->file++;
929             dev->file_addr = 0;
930             dev->file_size = 0;
931          }   
932       }
933       free_memory(rbuf);
934    
935    /*
936     * No FSF, so use FSR to simulate it
937     */
938    } else {
939       Dmsg0(200, "Doing FSR for FSF\n");
940       while (num-- && !(dev->state & ST_EOT)) {
941          fsr_dev(dev, INT32_MAX);    /* returns -1 on EOF or EOT */
942       }
943       if (dev->state & ST_EOT) {
944          dev->dev_errno = 0;
945          Mmsg1(dev->errmsg, _("Device %s at End of Tape.\n"), dev->dev_name);
946          stat = -1;
947       } else {
948          stat = 0;
949       }
950    }
951    update_pos_dev(dev);
952    Dmsg1(200, "Return %d from FSF\n", stat);
953    if (dev->state & ST_EOF)
954       Dmsg0(200, "ST_EOF set on exit FSF\n");
955    if (dev->state & ST_EOT)
956       Dmsg0(200, "ST_EOT set on exit FSF\n");
957    Dmsg1(200, "Return from FSF file=%d\n", dev->file);
958    return stat == 0;
959 }
960
961 /* 
962  * Backward space a file  
963  *  Returns: false on failure
964  *           true  on success
965  */
966 bool
967 bsf_dev(DEVICE *dev, int num)
968
969    struct mtop mt_com;
970    int stat;
971
972    if (dev->fd < 0) {
973       dev->dev_errno = EBADF;
974       Mmsg0(dev->errmsg, _("Bad call to bsf_dev. Archive device not open\n"));
975       Emsg0(M_FATAL, 0, dev->errmsg);
976       return false;
977    }
978
979    if (!(dev_state(dev, ST_TAPE))) {
980       Mmsg1(dev->errmsg, _("Device %s cannot BSF because it is not a tape.\n"),
981          dev->dev_name);
982       return false;
983    }
984    Dmsg0(29, "bsf_dev\n");
985    dev->state &= ~(ST_EOT|ST_EOF);
986    dev->file -= num;
987    dev->file_addr = 0;
988    dev->file_size = 0;
989    mt_com.mt_op = MTBSF;
990    mt_com.mt_count = num;
991    stat = ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
992    if (stat < 0) {
993       berrno be;
994       clrerror_dev(dev, MTBSF);
995       Mmsg2(dev->errmsg, _("ioctl MTBSF error on %s. ERR=%s.\n"),
996          dev->dev_name, be.strerror());
997    }
998    update_pos_dev(dev);
999    return stat == 0;
1000 }
1001
1002
1003 /* 
1004  * Foward space a record
1005  *  Returns: false on failure
1006  *           true  on success
1007  */
1008 bool
1009 fsr_dev(DEVICE *dev, int num)
1010
1011    struct mtop mt_com;
1012    int stat;
1013
1014    if (dev->fd < 0) {
1015       dev->dev_errno = EBADF;
1016       Mmsg0(dev->errmsg, _("Bad call to fsr_dev. Archive not open\n"));
1017       Emsg0(M_FATAL, 0, dev->errmsg);
1018       return false;
1019    }
1020
1021    if (!(dev_state(dev, ST_TAPE))) {
1022       return false;
1023    }
1024    if (!dev_cap(dev, CAP_FSR)) {
1025       Mmsg1(dev->errmsg, _("ioctl MTFSR not permitted on %s.\n"), dev->dev_name);
1026       return false;
1027    }
1028
1029    Dmsg1(29, "fsr_dev %d\n", num);
1030    mt_com.mt_op = MTFSR;
1031    mt_com.mt_count = num;
1032    stat = ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
1033    if (stat == 0) {
1034       dev->state &= ~ST_EOF;
1035       dev->block_num += num;
1036    } else {
1037       berrno be;
1038       struct mtget mt_stat;
1039       clrerror_dev(dev, MTFSR);
1040       Dmsg1(100, "FSF fail: ERR=%s\n", be.strerror());
1041       if (dev_cap(dev, CAP_MTIOCGET) && ioctl(dev->fd, MTIOCGET, (char *)&mt_stat) == 0 && mt_stat.mt_fileno >= 0) {
1042          Dmsg4(100, "Adjust from %d:%d to %d:%d\n", dev->file, 
1043             dev->block_num, mt_stat.mt_fileno, mt_stat.mt_blkno);
1044          dev->file = mt_stat.mt_fileno;
1045          dev->block_num = mt_stat.mt_blkno;
1046       } else {
1047          if (dev->state & ST_EOF) {
1048             dev->state |= ST_EOT;
1049          } else {
1050             dev->state |= ST_EOF;           /* assume EOF */
1051             dev->file++;
1052             dev->block_num = 0;
1053             dev->file_addr = 0;
1054             dev->file_size = 0;
1055          }
1056       }
1057       Mmsg2(dev->errmsg, _("ioctl MTFSR error on %s. ERR=%s.\n"),
1058          dev->dev_name, be.strerror());
1059    }
1060    update_pos_dev(dev);
1061    return stat == 0;
1062 }
1063
1064 /* 
1065  * Backward space a record
1066  *   Returns:  false on failure
1067  *             true  on success
1068  */
1069 bool
1070 bsr_dev(DEVICE *dev, int num)
1071
1072    struct mtop mt_com;
1073    int stat;
1074
1075    if (dev->fd < 0) {
1076       dev->dev_errno = EBADF;
1077       Mmsg0(dev->errmsg, _("Bad call to bsr_dev. Archive not open\n"));
1078       Emsg0(M_FATAL, 0, dev->errmsg);
1079       return false;
1080    }
1081
1082    if (!(dev->state & ST_TAPE)) {
1083       return false;
1084    }
1085
1086    if (!dev_cap(dev, CAP_BSR)) {
1087       Mmsg1(dev->errmsg, _("ioctl MTBSR not permitted on %s.\n"), dev->dev_name);
1088       return false;
1089    }
1090
1091    Dmsg0(29, "bsr_dev\n");
1092    dev->block_num -= num;
1093    dev->state &= ~(ST_EOF|ST_EOT|ST_EOF);
1094    mt_com.mt_op = MTBSR;
1095    mt_com.mt_count = num;
1096    stat = ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
1097    if (stat < 0) {
1098       berrno be;
1099       clrerror_dev(dev, MTBSR);
1100       Mmsg2(dev->errmsg, _("ioctl MTBSR error on %s. ERR=%s.\n"),
1101          dev->dev_name, be.strerror());
1102    }
1103    update_pos_dev(dev);
1104    return stat == 0;
1105 }
1106
1107 /* 
1108  * Reposition the device to file, block
1109  * Returns: false on failure
1110  *          true  on success
1111  */
1112 bool
1113 reposition_dev(DEVICE *dev, uint32_t file, uint32_t block)
1114
1115    if (dev->fd < 0) {
1116       dev->dev_errno = EBADF;
1117       Mmsg0(dev->errmsg, _("Bad call to reposition_dev. Archive not open\n"));
1118       Emsg0(M_FATAL, 0, dev->errmsg);
1119       return false;
1120    }
1121
1122    if (!(dev_state(dev, ST_TAPE))) {
1123       off_t pos = (((off_t)file)<<32) + block;
1124       Dmsg1(100, "===== lseek to %d\n", (int)pos);
1125       if (lseek(dev->fd, pos, SEEK_SET) == (off_t)-1) {
1126          berrno be;
1127          dev->dev_errno = errno;
1128          Mmsg2(dev->errmsg, _("lseek error on %s. ERR=%s.\n"),
1129             dev->dev_name, be.strerror());
1130          return false;
1131       }
1132       dev->file = file;
1133       dev->block_num = block;
1134       dev->file_addr = pos;
1135       return true;
1136    }
1137    Dmsg4(100, "reposition_dev from %u:%u to %u:%u\n", 
1138       dev->file, dev->block_num, file, block);
1139    if (file < dev->file) {
1140       Dmsg0(100, "Rewind_dev\n");
1141       if (!rewind_dev(dev)) {
1142          return false;
1143       }
1144    }
1145    if (file > dev->file) {
1146       Dmsg1(100, "fsf %d\n", file-dev->file);
1147       if (!fsf_dev(dev, file-dev->file)) {
1148          Dmsg1(100, "fsf failed! ERR=%s\n", strerror_dev(dev));
1149          return false;
1150       }
1151       Dmsg2(100, "wanted_file=%d at_file=%d\n", file, dev->file);
1152    }
1153    if (block < dev->block_num) {
1154       Dmsg2(100, "wanted_blk=%d at_blk=%d\n", block, dev->block_num);
1155       Dmsg0(100, "bsf_dev 1\n");
1156       bsf_dev(dev, 1);
1157       Dmsg0(100, "fsf_dev 1\n");
1158       fsf_dev(dev, 1);
1159       Dmsg2(100, "wanted_blk=%d at_blk=%d\n", block, dev->block_num);
1160    }
1161    if (dev_cap(dev, CAP_POSITIONBLOCKS) && block > dev->block_num) {
1162       /* Ignore errors as Bacula can read to the correct block */
1163       Dmsg1(100, "fsr %d\n", block-dev->block_num);
1164       return fsr_dev(dev, block-dev->block_num);
1165    }
1166    return true;
1167 }
1168
1169
1170
1171 /*
1172  * Write an end of file on the device
1173  *   Returns: 0 on success
1174  *            non-zero on failure
1175  */
1176 int 
1177 weof_dev(DEVICE *dev, int num)
1178
1179    struct mtop mt_com;
1180    int stat;
1181
1182    if (dev->fd < 0) {
1183       dev->dev_errno = EBADF;
1184       Mmsg0(dev->errmsg, _("Bad call to weof_dev. Archive drive not open\n"));
1185       Emsg0(M_FATAL, 0, dev->errmsg);
1186       return -1;
1187    }
1188    dev->file_size = 0;
1189
1190    if (!(dev_state(dev, ST_TAPE))) {
1191       return 0;
1192    }
1193    dev->state &= ~(ST_EOT | ST_EOF);  /* remove EOF/EOT flags */
1194    Dmsg0(29, "weof_dev\n");
1195    mt_com.mt_op = MTWEOF;
1196    mt_com.mt_count = num;
1197    stat = ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
1198    if (stat == 0) {
1199       dev->block_num = 0;
1200       dev->file += num;
1201       dev->file_addr = 0;
1202    } else {
1203       berrno be;
1204       clrerror_dev(dev, MTWEOF);
1205       if (stat == -1) {
1206          Mmsg2(dev->errmsg, _("ioctl MTWEOF error on %s. ERR=%s.\n"),
1207             dev->dev_name, be.strerror());
1208        }
1209    }
1210    return stat;
1211 }
1212
1213 /*
1214  * Return string message with last error in English
1215  *  Be careful not to call this routine from within dev.c
1216  *  while editing an Mmsg() or you will end up in a recursive
1217  *  loop creating a Segmentation Violation.
1218  */
1219 char *
1220 strerror_dev(DEVICE *dev)
1221 {
1222    return dev->errmsg;
1223 }
1224
1225
1226 /*
1227  * If implemented in system, clear the tape
1228  * error status.
1229  */
1230 void
1231 clrerror_dev(DEVICE *dev, int func)
1232 {
1233    const char *msg = NULL;
1234    struct mtget mt_stat;
1235
1236    dev->dev_errno = errno;         /* save errno */
1237    if (errno == EIO) {
1238       dev->VolCatInfo.VolCatErrors++;
1239    }
1240
1241    if (!(dev->state & ST_TAPE)) {
1242       return;
1243    }
1244    if (errno == ENOTTY || errno == ENOSYS) { /* Function not implemented */
1245       switch (func) {
1246       case -1:
1247          Emsg0(M_ABORT, 0, "Got ENOTTY on read/write!\n");
1248          break;
1249       case MTWEOF:
1250          msg = "WTWEOF";
1251          dev->capabilities &= ~CAP_EOF; /* turn off feature */
1252          break;
1253 #ifdef MTEOM
1254       case MTEOM:
1255          msg = "WTEOM";
1256          dev->capabilities &= ~CAP_EOM; /* turn off feature */
1257          break;
1258 #endif 
1259       case MTFSF:
1260          msg = "MTFSF";
1261          dev->capabilities &= ~CAP_FSF; /* turn off feature */
1262          break;
1263       case MTBSF:
1264          msg = "MTBSF";
1265          dev->capabilities &= ~CAP_BSF; /* turn off feature */
1266          break;
1267       case MTFSR:
1268          msg = "MTFSR";
1269          dev->capabilities &= ~CAP_FSR; /* turn off feature */
1270          break;
1271       case MTBSR:
1272          msg = "MTBSR";
1273          dev->capabilities &= ~CAP_BSR; /* turn off feature */
1274          break;
1275       default:
1276          msg = "Unknown";
1277          break;
1278       }
1279       if (msg != NULL) {
1280          dev->dev_errno = ENOSYS;
1281          Mmsg1(&dev->errmsg, _("This device does not support %s.\n"), msg);
1282          Emsg0(M_ERROR, 0, dev->errmsg);
1283       }
1284    }
1285    /* On some systems such as NetBSD, this clears all errors */
1286    ioctl(dev->fd, MTIOCGET, (char *)&mt_stat);      
1287
1288 /* Found on Linux */
1289 #ifdef MTIOCLRERR
1290 {
1291    struct mtop mt_com;
1292    mt_com.mt_op = MTIOCLRERR;
1293    mt_com.mt_count = 1;
1294    /* Clear any error condition on the tape */
1295    ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
1296    Dmsg0(200, "Did MTIOCLRERR\n");
1297 }
1298 #endif
1299
1300 /* Typically on FreeBSD */
1301 #ifdef MTIOCERRSTAT
1302 {
1303    /* Read and clear SCSI error status */
1304    union mterrstat mt_errstat;
1305    Dmsg2(200, "Doing MTIOCERRSTAT errno=%d ERR=%s\n", dev->dev_errno,
1306       strerror(dev->dev_errno));
1307    ioctl(dev->fd, MTIOCERRSTAT, (char *)&mt_errstat);
1308 }
1309 #endif
1310
1311 /* Clear Subsystem Exception OSF1 */
1312 #ifdef MTCSE
1313 {
1314    struct mtop mt_com;
1315    mt_com.mt_op = MTCSE;
1316    mt_com.mt_count = 1;
1317    /* Clear any error condition on the tape */
1318    ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
1319    Dmsg0(200, "Did MTCSE\n");
1320 }
1321 #endif
1322 }
1323
1324 /*
1325  * Flush buffer contents
1326  *  No longer used.
1327  */
1328 int flush_dev(DEVICE *dev)
1329 {
1330    return 1;
1331 }
1332
1333 static void do_close(DEVICE *dev)
1334 {
1335
1336    Dmsg1(29, "really close_dev %s\n", dev->dev_name);
1337    if (dev->fd >= 0) {
1338       close(dev->fd);
1339    }
1340    /* Clean up device packet so it can be reused */
1341    dev->fd = -1;
1342    dev->state &= ~(ST_OPENED|ST_LABEL|ST_READ|ST_APPEND|ST_EOT|ST_WEOT|ST_EOF);
1343    dev->file = dev->block_num = 0;
1344    dev->file_size = 0;
1345    dev->file_addr = 0;
1346    dev->EndFile = dev->EndBlock = 0;
1347    memset(&dev->VolCatInfo, 0, sizeof(dev->VolCatInfo));
1348    memset(&dev->VolHdr, 0, sizeof(dev->VolHdr));
1349    if (dev->tid) {
1350       stop_thread_timer(dev->tid);
1351       dev->tid = 0;
1352    }
1353    dev->use_count = 0;
1354 }
1355
1356 /* 
1357  * Close the device
1358  */
1359 void
1360 close_dev(DEVICE *dev)
1361 {
1362    if (!dev) {
1363       Mmsg0(&dev->errmsg, _("Bad call to close_dev. Archive not open\n"));
1364       Emsg0(M_FATAL, 0, dev->errmsg);
1365       return;
1366    }
1367    if (dev->fd >= 0 && dev->use_count == 1) {
1368       do_close(dev);
1369    } else if (dev->use_count > 0) {
1370       dev->use_count--;
1371    }
1372            
1373 #ifdef FULL_DEBUG
1374    ASSERT(dev->use_count >= 0);
1375 #endif
1376 }
1377
1378 /*
1379  * Used when unmounting the device, ignore use_count
1380  */
1381 void force_close_dev(DEVICE *dev)
1382 {
1383    if (!dev) {
1384       Mmsg0(&dev->errmsg, _("Bad call to force_close_dev. Archive not open\n"));
1385       Emsg0(M_FATAL, 0, dev->errmsg);
1386       return;
1387    }
1388    Dmsg1(29, "Force close_dev %s\n", dev->dev_name);
1389    do_close(dev);
1390
1391 #ifdef FULL_DEBUG
1392    ASSERT(dev->use_count >= 0);
1393 #endif
1394 }
1395
1396 bool truncate_dev(DEVICE *dev)
1397 {
1398    if (dev->state & ST_TAPE) {
1399       return true;                    /* we don't really truncate tapes */
1400       /* maybe we should rewind and write and eof ???? */
1401    }
1402    if (ftruncate(dev->fd, 0) != 0) {
1403       berrno be;
1404       Mmsg1(&dev->errmsg, _("Unable to truncate device. ERR=%s\n"), be.strerror());
1405       return false;
1406    }
1407    return true;
1408 }
1409
1410 bool
1411 dev_is_tape(DEVICE *dev)
1412 {  
1413    return (dev->state & ST_TAPE) ? true : false;
1414 }
1415
1416
1417 /*
1418  * return 1 if the device is read for write, and 0 otherwise
1419  *   This is meant for checking at the end of a job to see
1420  *   if we still have a tape (perhaps not if at end of tape
1421  *   and the job is canceled).
1422  */
1423 bool
1424 dev_can_write(DEVICE *dev)
1425 {
1426    if ((dev->state & ST_OPENED) &&  (dev->state & ST_APPEND) &&
1427        (dev->state & ST_LABEL)  && !(dev->state & ST_WEOT)) {
1428       return true;
1429    } else {
1430       return false;
1431    }
1432 }
1433
1434 char *
1435 dev_name(DEVICE *dev)
1436 {
1437    return dev->dev_name;
1438 }
1439
1440 char *
1441 dev_vol_name(DEVICE *dev)
1442 {
1443    return dev->VolCatInfo.VolCatName;
1444 }
1445
1446 uint32_t dev_block(DEVICE *dev)
1447 {
1448    update_pos_dev(dev);
1449    return dev->block_num;
1450 }
1451
1452 uint32_t dev_file(DEVICE *dev)
1453 {
1454    update_pos_dev(dev);
1455    return dev->file;
1456 }
1457
1458 /* 
1459  * Free memory allocated for the device
1460  */
1461 void
1462 term_dev(DEVICE *dev)
1463 {
1464    if (!dev) {
1465       dev->dev_errno = EBADF;
1466       Mmsg0(&dev->errmsg, _("Bad call to term_dev. Archive not open\n"));
1467       Emsg0(M_FATAL, 0, dev->errmsg);
1468       return;
1469    }
1470    do_close(dev);
1471    Dmsg0(29, "term_dev\n");
1472    if (dev->dev_name) {
1473       free_memory(dev->dev_name);
1474       dev->dev_name = NULL;
1475    }
1476    if (dev->errmsg) {
1477       free_pool_memory(dev->errmsg);
1478       dev->errmsg = NULL;
1479    }
1480    pthread_mutex_destroy(&dev->mutex);
1481    pthread_cond_destroy(&dev->wait);
1482    pthread_cond_destroy(&dev->wait_next_vol);
1483    pthread_mutex_destroy(&dev->spool_mutex);
1484    rwl_destroy(&dev->lock);
1485    if (dev->attached_dcrs) {
1486       delete dev->attached_dcrs;
1487       dev->attached_dcrs = NULL;
1488    }
1489    if (dev->state & ST_MALLOC) {
1490       free_pool_memory((POOLMEM *)dev);
1491    }
1492 }
1493
1494 /*
1495  * This routine initializes the device wait timers
1496  */
1497 void init_dev_wait_timers(DEVICE *dev)
1498 {
1499    /* ******FIXME******* put these on config variables */
1500    dev->min_wait = 60 * 60;
1501    dev->max_wait = 24 * 60 * 60;
1502    dev->max_num_wait = 9;              /* 5 waits =~ 1 day, then 1 day at a time */
1503    dev->wait_sec = dev->min_wait;
1504    dev->rem_wait_sec = dev->wait_sec;
1505    dev->num_wait = 0;
1506    dev->poll = false;
1507    dev->BadVolName[0] = 0;
1508 }
1509
1510 /*
1511  * Returns: true if time doubled
1512  *          false if max time expired
1513  */
1514 bool double_dev_wait_time(DEVICE *dev)
1515 {
1516    dev->wait_sec *= 2;               /* double wait time */
1517    if (dev->wait_sec > dev->max_wait) {   /* but not longer than maxtime */
1518       dev->wait_sec = dev->max_wait;
1519    }
1520    dev->num_wait++;
1521    dev->rem_wait_sec = dev->wait_sec;
1522    if (dev->num_wait >= dev->max_num_wait) {
1523       return false;
1524    }
1525    return true;
1526 }
1527
1528 void set_os_device_parameters(DEVICE *dev)
1529 {
1530 #ifdef HAVE_LINUX_OS
1531    struct mtop mt_com;
1532    if (dev->min_block_size == dev->max_block_size &&
1533        dev->min_block_size == 0) {    /* variable block mode */
1534       mt_com.mt_op = MTSETBLK;
1535       mt_com.mt_count = 0;
1536       if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
1537          clrerror_dev(dev, MTSETBLK);
1538       }
1539       mt_com.mt_op = MTSETDRVBUFFER;
1540       mt_com.mt_count = MT_ST_CLEARBOOLEANS;
1541       if (!dev_cap(dev, CAP_TWOEOF)) {
1542          mt_com.mt_count |= MT_ST_TWO_FM;
1543       }
1544       if (dev_cap(dev, CAP_EOM)) {
1545          mt_com.mt_count |= MT_ST_FAST_MTEOM;
1546       }
1547       if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
1548          clrerror_dev(dev, MTSETBLK);
1549       }
1550    }
1551    return;
1552 #endif
1553
1554 #ifdef HAVE_NETBSD_OS
1555    struct mtop mt_com;
1556    if (dev->min_block_size == dev->max_block_size &&
1557        dev->min_block_size == 0) {    /* variable block mode */
1558       mt_com.mt_op = MTSETBSIZ;
1559       mt_com.mt_count = 0;
1560       if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
1561          clrerror_dev(dev, MTSETBSIZ);
1562       }
1563       /* Get notified at logical end of tape */
1564       mt_com.mt_op = MTEWARN;
1565       mt_com.mt_count = 1;
1566       if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
1567          clrerror_dev(dev, MTEWARN);
1568       }
1569    }
1570    return;
1571 #endif
1572
1573 #if HAVE_FREEBSD_OS || HAVE_OPENBSD_OS
1574    struct mtop mt_com;
1575    if (dev->min_block_size == dev->max_block_size &&
1576        dev->min_block_size == 0) {    /* variable block mode */
1577       mt_com.mt_op = MTSETBSIZ;
1578       mt_com.mt_count = 0;
1579       if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
1580          clrerror_dev(dev, MTSETBSIZ);
1581       }
1582    }
1583    return;
1584 #endif
1585
1586 #ifdef HAVE_SUN_OS
1587    struct mtop mt_com;
1588    if (dev->min_block_size == dev->max_block_size &&
1589        dev->min_block_size == 0) {    /* variable block mode */
1590       mt_com.mt_op = MTSRSZ;
1591       mt_com.mt_count = 0;
1592       if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
1593          clrerror_dev(dev, MTSRSZ);
1594       }
1595    }
1596    return;
1597 #endif
1598 }