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