]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/stored/dev.c
- Fix name space pollution by OpenSSL 0.9.8 reported by
[bacula/bacula] / bacula / src / stored / dev.c
1 /*
2  *
3  *   dev.c  -- low level operations on device (storage device)
4  *
5  *              Kern Sibbald, MM
6  *
7  *     NOTE!!!! None of these routines are reentrant. You must
8  *        use lock_device() and unlock_device() at a higher level,
9  *        or use the xxx_device() equivalents.  By moving the
10  *        thread synchronization to a higher level, we permit
11  *        the higher level routines to "seize" the device and
12  *        to carry out operations without worrying about who
13  *        set what lock (i.e. race conditions).
14  *
15  *     Note, this is the device dependent code, and my have
16  *           to be modified for each system, but is meant to
17  *           be as "generic" as possible.
18  *
19  *     The purpose of this code is to develop a SIMPLE Storage
20  *     daemon. More complicated coding (double buffering, writer
21  *     thread, ...) is left for a later version.
22  *
23  *     Unfortunately, I have had to add more and more complication
24  *     to this code. This was not foreseen as noted above, and as
25  *     a consequence has lead to something more contorted than is
26  *     really necessary -- KES.  Note, this contortion has been
27  *     corrected to a large extent by a rewrite (Apr MMI).
28  *
29  *   Version $Id$
30  */
31 /*
32    Copyright (C) 2000-2005 Kern Sibbald
33
34    This program is free software; you can redistribute it and/or
35    modify it under the terms of the GNU General Public License
36    version 2 as amended with additional clauses defined in the
37    file LICENSE in the main source directory.
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 
42    the file LICENSE for additional details.
43
44  */
45
46 /*
47  * Handling I/O errors and end of tape conditions are a bit tricky.
48  * This is how it is currently done when writting.
49  * On either an I/O error or end of tape,
50  * we will stop writing on the physical device (no I/O recovery is
51  * attempted at least in this daemon). The state flag will be sent
52  * to include ST_EOT, which is ephimeral, and ST_WEOT, which is
53  * persistent. Lots of routines clear ST_EOT, but ST_WEOT is
54  * cleared only when the problem goes away.  Now when ST_WEOT
55  * is set all calls to write_block_to_device() call the fix_up
56  * routine. In addition, all threads are blocked
57  * from writing on the tape by calling lock_dev(), and thread other
58  * than the first thread to hit the EOT will block on a condition
59  * variable. The first thread to hit the EOT will continue to
60  * be able to read and write the tape (he sort of tunnels through
61  * the locking mechanism -- see lock_dev() for details).
62  *
63  * Now presumably somewhere higher in the chain of command
64  * (device.c), someone will notice the EOT condition and
65  * get a new tape up, get the tape label read, and mark
66  * the label for rewriting. Then this higher level routine
67  * will write the unwritten buffer to the new volume.
68  * Finally, he will release
69  * any blocked threads by doing a broadcast on the condition
70  * variable.  At that point, we should be totally back in
71  * business with no lost data.
72  */
73
74
75 #include "bacula.h"
76 #include "stored.h"
77
78 #ifndef O_NONBLOCK 
79 #define O_NONBLOCK 0
80 #endif
81
82 /* Functions in dvd.c */ 
83 void update_free_space_dev(DEVICE* dev);
84
85
86 /* Forward referenced functions */
87 void set_os_device_parameters(DEVICE *dev);
88 static bool dev_get_os_pos(DEVICE *dev, struct mtget *mt_stat);
89 static char *mode_to_str(int mode);
90
91 /*
92  * Allocate and initialize the DEVICE structure
93  * Note, if dev is non-NULL, it is already allocated,
94  * thus we neither allocate it nor free it. This allows
95  * the caller to put the packet in shared memory.
96  *
97  *  Note, for a tape, the device->device_name is the device name
98  *     (e.g. /dev/nst0), and for a file, the device name
99  *     is the directory in which the file will be placed.
100  *
101  */
102 DEVICE *
103 init_dev(JCR *jcr, DEVRES *device)
104 {
105    struct stat statp;
106    bool tape, fifo;
107    int errstat;
108    DCR *dcr = NULL;
109    DEVICE *dev;
110
111    /* Check that device is available */
112    if (stat(device->device_name, &statp) < 0) {
113       berrno be;
114       Jmsg2(jcr, M_ERROR, 0, _("Unable to stat device %s: ERR=%s\n"), 
115          device->device_name, be.strerror());
116       return NULL;
117    }
118    
119    
120    tape = false;
121    fifo = false;
122    if (S_ISDIR(statp.st_mode)) {
123       tape = false;
124    } else if (S_ISCHR(statp.st_mode)) {
125       tape = true;
126    } else if (S_ISFIFO(statp.st_mode)) {
127       fifo = true;
128    } else if (!(device->cap_bits & CAP_REQMOUNT)) {
129       Jmsg2(jcr, M_ERROR, 0, _("%s is an unknown device type. Must be tape or directory\n"
130             " or have RequiresMount=yes for DVD. st_mode=%x\n"),
131          device->device_name, statp.st_mode);
132       return NULL;
133    }
134
135    dev = (DEVICE *)get_memory(sizeof(DEVICE));
136    memset(dev, 0, sizeof(DEVICE));
137    dev->state = ST_MALLOC;
138
139    /* Copy user supplied device parameters from Resource */
140    dev->dev_name = get_memory(strlen(device->device_name)+1);
141    pm_strcpy(dev->dev_name, device->device_name);
142    dev->prt_name = get_memory(strlen(device->device_name) + strlen(device->hdr.name) + 20);
143    /* We edit "Resource-name" (physical-name) */
144    Mmsg(dev->prt_name, "\"%s\" (%s)", device->hdr.name, device->device_name);
145    dev->capabilities = device->cap_bits;
146    dev->min_block_size = device->min_block_size;
147    dev->max_block_size = device->max_block_size;
148    dev->max_volume_size = device->max_volume_size;
149    dev->max_file_size = device->max_file_size;
150    dev->volume_capacity = device->volume_capacity;
151    dev->max_rewind_wait = device->max_rewind_wait;
152    dev->max_open_wait = device->max_open_wait;
153    dev->max_open_vols = device->max_open_vols;
154    dev->vol_poll_interval = device->vol_poll_interval;
155    dev->max_spool_size = device->max_spool_size;
156    dev->drive_index = device->drive_index;
157    dev->autoselect = device->autoselect;
158    if (tape) { /* No parts on tapes */
159       dev->max_part_size = 0;
160    }
161    else {
162       dev->max_part_size = device->max_part_size;
163    }
164    /* Sanity check */
165    if (dev->vol_poll_interval && dev->vol_poll_interval < 60) {
166       dev->vol_poll_interval = 60;
167    }
168    dev->device = device;
169
170    if (tape) {
171       dev->state |= ST_TAPE;
172    } else if (fifo) {
173       dev->state |= ST_FIFO;
174       dev->capabilities |= CAP_STREAM; /* set stream device */
175    } else {
176       dev->state |= ST_FILE;
177    }
178
179    /* If the device requires mount :
180     * - Check that the mount point is available 
181     * - Check that (un)mount commands are defined
182     */
183    if (dev->is_file() && dev->requires_mount()) {
184       if (stat(device->mount_point, &statp) < 0) {
185          berrno be;
186          dev->dev_errno = errno;
187          Jmsg2(jcr, M_ERROR, 0, _("Unable to stat mount point %s: ERR=%s\n"), 
188             device->mount_point, be.strerror());
189          return NULL;
190       }
191       if (!device->mount_command || !device->unmount_command) {
192          Jmsg0(jcr, M_ERROR_TERM, 0, _("Mount and unmount commands must defined for a device which requires mount.\n"));
193       }
194       if (!device->write_part_command) {
195          Jmsg0(jcr, M_ERROR_TERM, 0, _("Write part command must be defined for a device which requires mount.\n"));
196       }
197       dev->state |= ST_DVD;
198    }
199
200    if (dev->max_block_size > 1000000) {
201       Jmsg3(jcr, M_ERROR, 0, _("Block size %u on device %s is too large, using default %u\n"),
202          dev->max_block_size, dev->print_name(), DEFAULT_BLOCK_SIZE);
203       dev->max_block_size = 0;
204    }
205    if (dev->max_block_size % TAPE_BSIZE != 0) {
206       Jmsg2(jcr, M_WARNING, 0, _("Max block size %u not multiple of device %s block size.\n"),
207          dev->max_block_size, dev->print_name());
208    }
209
210    dev->errmsg = get_pool_memory(PM_EMSG);
211    *dev->errmsg = 0;
212
213    if ((errstat = pthread_mutex_init(&dev->mutex, NULL)) != 0) {
214       berrno be;
215       dev->dev_errno = errstat;
216       Mmsg1(dev->errmsg, _("Unable to init mutex: ERR=%s\n"), be.strerror(errstat));
217       Jmsg0(jcr, M_ERROR_TERM, 0, dev->errmsg);
218    }
219    if ((errstat = pthread_cond_init(&dev->wait, NULL)) != 0) {
220       berrno be;
221       dev->dev_errno = errstat;
222       Mmsg1(dev->errmsg, _("Unable to init cond variable: ERR=%s\n"), be.strerror(errstat));
223       Jmsg0(jcr, M_ERROR_TERM, 0, dev->errmsg);
224    }
225    if ((errstat = pthread_cond_init(&dev->wait_next_vol, NULL)) != 0) {
226       berrno be;
227       dev->dev_errno = errstat;
228       Mmsg1(dev->errmsg, _("Unable to init cond variable: ERR=%s\n"), be.strerror(errstat));
229       Jmsg0(jcr, M_ERROR_TERM, 0, dev->errmsg);
230    }
231    if ((errstat = pthread_mutex_init(&dev->spool_mutex, NULL)) != 0) {
232       berrno be;
233       dev->dev_errno = errstat;
234       Mmsg1(dev->errmsg, _("Unable to init mutex: ERR=%s\n"), be.strerror(errstat));
235       Jmsg0(jcr, M_ERROR_TERM, 0, dev->errmsg);
236    }
237    if ((errstat = rwl_init(&dev->lock)) != 0) {
238       berrno be;
239       dev->dev_errno = errstat;
240       Mmsg1(dev->errmsg, _("Unable to init mutex: ERR=%s\n"), be.strerror(errstat));
241       Jmsg0(jcr, M_ERROR_TERM, 0, dev->errmsg);
242    }
243
244    dev->fd = -1;
245    dev->attached_dcrs = New(dlist(dcr, &dcr->dev_link));
246    Dmsg2(29, "init_dev: tape=%d dev_name=%s\n", dev->is_tape(), dev->dev_name);
247    
248    return dev;
249 }
250
251 /*
252  * Open the device with the operating system and
253  * initialize buffer pointers.
254  *
255  * Returns:  -1  on error
256  *           fd  on success
257  *
258  * Note, for a tape, the VolName is the name we give to the
259  *    volume (not really used here), but for a file, the
260  *    VolName represents the name of the file to be created/opened.
261  *    In the case of a file, the full name is the device name
262  *    (archive_name) with the VolName concatenated.
263  */
264 int
265 DEVICE::open(DCR *dcr, int omode)
266 {
267    if (is_open()) {
268       if (openmode == omode) {
269          return fd;
270       } else {
271         ::close(fd); /* use system close so correct mode will be used on open */
272       }
273    }
274   if (dcr) {
275      bstrncpy(VolCatInfo.VolCatName, dcr->VolumeName, sizeof(VolCatInfo.VolCatName));
276   }
277
278    Dmsg4(29, "open dev: tape=%d dev_name=%s vol=%s mode=%s\n", is_tape(),
279          dev_name, VolCatInfo.VolCatName, mode_to_str(omode));
280    state &= ~(ST_LABEL|ST_APPEND|ST_READ|ST_EOT|ST_WEOT|ST_EOF);
281    label_type = B_BACULA_LABEL;
282    if (is_tape() || is_fifo()) {
283       open_tape_device(omode);
284    } else if (is_dvd()) {
285       Dmsg1(100, "call open_dvd_device mode=%s\n", mode_to_str(omode));
286       open_dvd_device(dcr, omode);
287    } else {
288       Dmsg1(100, "call open_file_device mode=%s\n", mode_to_str(omode));
289       open_file_device(omode);
290    }
291    return fd;
292 }
293
294 void DEVICE::set_mode(int new_mode) 
295 {
296    switch (new_mode) {
297    case CREATE_READ_WRITE:
298       mode = O_CREAT | O_RDWR | O_BINARY;
299       break;
300    case OPEN_READ_WRITE:
301       if (is_dvd() || is_file()) {
302          mode = O_CREAT | O_RDWR | O_BINARY;
303       } else {
304          mode = O_RDWR | O_BINARY;
305       }
306       break;
307    case OPEN_READ_ONLY:
308       mode = O_RDONLY | O_BINARY;
309       break;
310    case OPEN_WRITE_ONLY:
311       mode = O_WRONLY | O_BINARY;
312       break;
313    default:
314       Emsg0(M_ABORT, 0, _("Illegal mode given to open dev.\n"));
315    }
316 }
317
318 void DEVICE::open_tape_device(int omode) 
319 {
320    int nonblocking = 0;;
321    file_size = 0;
322    int timeout;
323    int ioerrcnt = 10;
324    Dmsg0(29, "open dev: device is tape\n");
325
326    set_mode(omode);
327    timeout = max_open_wait;
328    errno = 0;
329    if (open_nowait) {
330        /* Set wait counters to zero for no wait */
331        timeout = ioerrcnt = 0;
332        /* Open drive in non-block mode */
333        nonblocking = O_NONBLOCK;
334    }
335    if (is_fifo() && timeout) {
336       /* Set open timer */
337       tid = start_thread_timer(pthread_self(), timeout);
338    }
339    /* If busy retry each second for max_open_wait seconds */
340 open_again:
341    Dmsg1(500, "Try open %s\n", dev_name);
342    /* Use system open() */
343    while ((fd = ::open(dev_name, mode, MODE_RW+nonblocking)) < 0) {
344       berrno be;
345       Dmsg2(500, "Open error errno=%d ERR=%s\n", errno, be.strerror());
346       if (errno == EINTR || errno == EAGAIN) {
347          Dmsg0(500, "Continue open\n");
348          continue;
349       }
350       /* Busy wait for specified time (default = 5 mins) */
351       if (errno == EBUSY && timeout-- > 0) {
352          Dmsg2(100, "Device %s busy. ERR=%s\n", print_name(), be.strerror());
353          bmicrosleep(1, 0);
354          continue;
355       }
356       /* IO error (no volume) try 10 times every 6 seconds */
357       if (errno == EIO && ioerrcnt-- > 0) {
358          bmicrosleep(5, 0);
359          Dmsg0(500, "Continue open\n");
360          continue;
361       }
362       dev_errno = errno;
363       Mmsg2(errmsg, _("Unable to open device %s: ERR=%s\n"),
364             print_name(), be.strerror(dev_errno));
365       /* Stop any open timer we set */
366       if (tid) {
367          stop_thread_timer(tid);
368          tid = 0;
369       }
370       Emsg0(M_FATAL, 0, errmsg);
371       break;
372    }
373    if (fd >= 0) {
374       /* If opened in non-block mode, close it an open it normally */
375       if (nonblocking) {
376          nonblocking = 0;
377          ::close(fd);                /* use system close() */
378          goto open_again;
379       }
380       openmode = mode;               /* save open mode */
381       dev_errno = 0;
382       set_opened();
383       use_count = 1;
384       update_pos_dev(this);                /* update position */
385       set_os_device_parameters(this);      /* do system dependent stuff */
386       Dmsg0(500, "Open OK\n");
387    }
388    /* Stop any open() timer we started */
389    if (tid) {
390       stop_thread_timer(tid);
391       tid = 0;
392    }
393    Dmsg1(29, "open dev: tape %d opened\n", fd);
394 }
395
396 /*
397  * Open a file device
398  */
399 void DEVICE::open_file_device(int omode) 
400 {
401    POOL_MEM archive_name(PM_FNAME);
402
403    /*
404     * Handle opening of File Archive (not a tape)
405     */     
406    Dmsg3(29, "Enter: open_file_dev: %s dev=%s mode=%s\n", is_dvd()?"DVD":"disk",
407          archive_name.c_str(), mode_to_str(omode));
408
409    if (VolCatInfo.VolCatName[0] == 0) {
410       Mmsg(errmsg, _("Could not open file device %s. No Volume name given.\n"),
411          print_name());
412       fd = -1;
413       return;
414    }
415
416    pm_strcpy(archive_name, dev_name);
417    if (archive_name.c_str()[strlen(archive_name.c_str())-1] != '/') {
418       pm_strcat(archive_name, "/");
419    }
420    pm_strcat(archive_name, VolCatInfo.VolCatName);
421          
422    Dmsg3(29, "open dev: %s dev=%s mode=%s\n", is_dvd()?"DVD":"disk",
423          archive_name.c_str(), mode_to_str(omode));
424    openmode = omode;
425    
426    set_mode(omode);
427    /* If creating file, give 0640 permissions */
428    Dmsg3(29, "mode=%s open(%s, 0x%x, 0640)\n", mode_to_str(omode), 
429          archive_name.c_str(), mode);
430    /* Use system open() */
431    if ((fd = ::open(archive_name.c_str(), mode, 0640)) < 0) {
432       berrno be;
433       dev_errno = errno;
434       Mmsg2(errmsg, _("Could not open: %s, ERR=%s\n"), archive_name.c_str(), 
435             be.strerror());
436       Dmsg1(29, "open failed: %s", errmsg);
437       Emsg0(M_FATAL, 0, errmsg);
438    } else {
439       dev_errno = 0;
440       set_opened();
441       use_count = 1;
442       update_pos_dev(this);                /* update position */
443    }
444    Dmsg5(29, "open dev: %s fd=%d opened, part=%d/%d, part_size=%u\n", 
445       is_dvd()?"DVD":"disk", fd, part, num_parts, 
446       part_size);
447 }
448
449 /*
450  * Open a DVD device. N.B. at this point, dcr->VolCatInfo.VolCatName
451  *  has the desired Volume name, but there is NO assurance that
452  *  any other field of VolCatInfo is correct.
453  */
454 void DEVICE::open_dvd_device(DCR *dcr, int omode) 
455 {
456    POOL_MEM archive_name(PM_FNAME);
457    struct stat filestat;
458
459    /*
460     * Handle opening of DVD Volume
461     */     
462    Dmsg3(29, "Enter: open_dvd_dev: %s dev=%s mode=%s\n", is_dvd()?"DVD":"disk",
463          archive_name.c_str(), mode_to_str(omode));
464
465    if (VolCatInfo.VolCatName[0] == 0) {
466       Mmsg(errmsg, _("Could not open file device %s. No Volume name given.\n"),
467          print_name());
468       fd = -1;
469       return;
470    }
471
472    if (part == 0) {
473       file_size = 0;
474    }
475    part_size = 0;
476    
477
478    if (!mount_dev(this, 1)) {
479       Mmsg(errmsg, _("Could not mount device %s.\n"), print_name());
480       Emsg0(M_FATAL, 0, errmsg);
481       fd = -1;
482       return;
483    }
484          
485    Dmsg5(29, "open dev: %s dev=%s mode=%s part=%d npart=%d\n", 
486       is_dvd()?"DVD":"disk", archive_name.c_str(), mode_to_str(omode),
487       part, num_parts);
488    openmode = omode;
489    
490    /*
491     * If we are not trying to access the last part, set mode to 
492     *   OPEN_READ_ONLY as writing would be an error.
493     */
494    if (part < num_parts) {
495       omode = OPEN_READ_ONLY;
496    }
497    set_mode(omode);
498
499    /* 
500     * If we are opening it read-only, it is *probably* on the
501     *   DVD, so try the DVD first, otherwise look in the spool dir.
502     */
503    if (omode == OPEN_READ_ONLY) {
504       make_mounted_dvd_filename(this, archive_name);
505    } else {
506       make_spooled_dvd_filename(this, archive_name);
507    }
508
509    /* If creating file, give 0640 permissions */
510    Dmsg3(29, "mode=%s open(%s, 0x%x, 0640)\n", mode_to_str(omode), 
511          archive_name.c_str(), mode);
512    /* Use system open() */
513    if ((fd = ::open(archive_name.c_str(), mode, 0640)) < 0) {
514       berrno be;
515       dev_errno = errno;
516       Mmsg2(errmsg, _("Could not open: %s, ERR=%s\n"), archive_name.c_str(), 
517             be.strerror());
518       Dmsg1(29, "open failed: %s", errmsg);
519       if (omode == OPEN_READ_ONLY) {
520          make_spooled_dvd_filename(this, archive_name);
521         /* Use system open() */
522          fd = ::open(archive_name.c_str(), mode, 0640);  /* try on spool */
523       }
524    }
525    if (fd >= 0) {
526       /* Get size of file */
527       if (fstat(fd, &filestat) < 0) {
528          berrno be;
529          dev_errno = errno;
530          Mmsg2(errmsg, _("Could not fstat: %s, ERR=%s\n"), archive_name.c_str(), 
531                be.strerror());
532          Dmsg1(29, "open failed: %s", errmsg);
533          /* Use system close() */
534          ::close(fd);
535          fd = -1;
536       } else {
537          part_size = filestat.st_size;
538          dev_errno = 0;
539          set_opened();
540          use_count = 1;
541          update_pos_dev(this);                /* update position */
542          /* Just created Volume */
543          if (omode == OPEN_READ_WRITE && part_size == 0) {
544             part++;
545             num_parts++;
546             VolCatInfo.VolCatParts = num_parts;
547          }
548       }
549    }
550    Dmsg4(29, "open dev: DVD fd=%d opened, part=%d nump=%d, part_size=%u\n", 
551       fd, part, num_parts, part_size);
552    if (is_open() && is_dvd() && (omode != OPEN_READ_ONLY) && 
553        (free_space_errno == 0 || num_parts == part)) {
554       update_free_space_dev(this);
555    }
556 }
557
558
559 #ifdef debug_tracing
560 #undef rewind_dev
561 bool _rewind_dev(char *file, int line, DEVICE *dev)
562 {
563    Dmsg2(100, "rewind_dev called from %s:%d\n", file, line);
564    return rewind_dev(dev);
565 }
566 #endif
567
568 /*
569  * Rewind the device.
570  *  Returns: true  on success
571  *           false on failure
572  */
573 bool rewind_dev(DEVICE *dev)
574 {
575    struct mtop mt_com;
576    unsigned int i;
577
578    Dmsg1(29, "rewind_dev %s\n", dev->print_name());
579    if (dev->fd < 0) {
580       dev->dev_errno = EBADF;
581       Mmsg1(dev->errmsg, _("Bad call to rewind_dev. Device %s not open\n"),
582             dev->print_name());
583       Emsg0(M_ABORT, 0, dev->errmsg);
584       return false;
585    }
586    dev->state &= ~(ST_EOT|ST_EOF|ST_WEOT);  /* remove EOF/EOT flags */
587    dev->block_num = dev->file = 0;
588    dev->file_size = 0;
589    dev->file_addr = 0;
590    if (dev->is_tape()) {
591       mt_com.mt_op = MTREW;
592       mt_com.mt_count = 1;
593       /* If we get an I/O error on rewind, it is probably because
594        * the drive is actually busy. We loop for (about 5 minutes)
595        * retrying every 5 seconds.
596        */
597       for (i=dev->max_rewind_wait; ; i -= 5) {
598          if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
599             berrno be;
600             clrerror_dev(dev, MTREW);
601             if (i == dev->max_rewind_wait) {
602                Dmsg1(200, "Rewind error, %s. retrying ...\n", be.strerror());
603             }
604             if (dev->dev_errno == EIO && i > 0) {
605                Dmsg0(200, "Sleeping 5 seconds.\n");
606                bmicrosleep(5, 0);
607                continue;
608             }
609             Mmsg2(dev->errmsg, _("Rewind error on %s. ERR=%s.\n"),
610                dev->print_name(), be.strerror());
611             return false;
612          }
613          break;
614       }
615    } else if (dev->is_file()) {      
616       if (lseek_dev(dev, (off_t)0, SEEK_SET) < 0) {
617          berrno be;
618          dev->dev_errno = errno;
619          Mmsg2(dev->errmsg, _("lseek_dev error on %s. ERR=%s.\n"),
620             dev->print_name(), be.strerror());
621          return false;
622       }
623    }
624    return true;
625 }
626
627 void DEVICE::block(int why)
628 {
629    lock_device(this);
630    block_device(this, why);
631    V(mutex);
632 }
633
634 void DEVICE::unblock()
635 {  
636    P(mutex);
637    unblock_device(this);
638    V(mutex);
639 }
640
641 const char *DEVICE::print_blocked() const 
642 {
643    switch (dev_blocked) {
644    case BST_NOT_BLOCKED:
645       return "BST_NOT_BLOCKED";
646    case BST_UNMOUNTED:
647       return "BST_UNMOUNTED";
648    case BST_WAITING_FOR_SYSOP:
649       return "BST_WAITING_FOR_SYSOP";
650    case BST_DOING_ACQUIRE:
651       return "BST_DOING_ACQUIRE";
652    case BST_WRITING_LABEL:
653       return "BST_WRITING_LABEL";
654    case BST_UNMOUNTED_WAITING_FOR_SYSOP:
655       return "BST_UNMOUNTED_WAITING_FOR_SYSOP";
656    case BST_MOUNT:
657       return "BST_MOUNT";
658    default:
659       return "unknown blocked code";
660    }
661 }
662
663 /*
664  * Called to indicate that we have just read an
665  *  EOF from the device.
666  */
667 void DEVICE::set_ateof() 
668
669    set_eof();
670    file++;
671    file_addr = 0;
672    file_size = 0;
673    block_num = 0;
674 }
675
676 /*
677  * Called to indicate we are now at the end of the tape, and
678  *   writing is not possible.
679  */
680 void DEVICE::set_ateot() 
681 {
682    /* Make tape effectively read-only */
683    state |= (ST_EOF|ST_EOT|ST_WEOT);
684    clear_append();
685 }
686
687 /*
688  * Position device to end of medium (end of data)
689  *  Returns: true  on succes
690  *           false on error
691  */
692 bool
693 eod_dev(DEVICE *dev)
694 {
695    struct mtop mt_com;
696    struct mtget mt_stat;
697    bool ok = true;
698    off_t pos;
699
700    if (dev->fd < 0) {
701       dev->dev_errno = EBADF;
702       Mmsg1(dev->errmsg, _("Bad call to eod_dev. Device %s not open\n"),
703             dev->print_name());
704       return false;
705    }
706
707 #if defined (__digital__) && defined (__unix__)
708    return dev->fsf(dev->VolCatInfo.VolCatFiles);
709 #endif
710
711    Dmsg0(29, "eod_dev\n");
712    if (dev->at_eot()) {
713       return true;
714    }
715    dev->state &= ~(ST_EOF);  /* remove EOF flags */
716    dev->block_num = dev->file = 0;
717    dev->file_size = 0;
718    dev->file_addr = 0;
719    if (dev->state & (ST_FIFO | ST_PROG)) {
720       return true;
721    }
722    if (!dev->is_tape()) {
723       pos = lseek_dev(dev, (off_t)0, SEEK_END);
724 //    Dmsg1(100, "====== Seek to %lld\n", pos);
725       if (pos >= 0) {
726          update_pos_dev(dev);
727          dev->state |= ST_EOT;
728          return true;
729       }
730       dev->dev_errno = errno;
731       berrno be;
732       Mmsg2(dev->errmsg, _("lseek_dev error on %s. ERR=%s.\n"),
733              dev->print_name(), be.strerror());
734       return false;
735    }
736 #ifdef MTEOM
737    if (dev_cap(dev, CAP_FASTFSF) && !dev_cap(dev, CAP_EOM)) {
738       Dmsg0(100,"Using FAST FSF for EOM\n");
739       /* If unknown position, rewind */
740       if (!dev_get_os_pos(dev, &mt_stat)) {
741         if (!rewind_dev(dev)) {
742           return false;
743         }
744       }
745       mt_com.mt_op = MTFSF;
746       /*
747        * ***FIXME*** fix code to handle case that INT16_MAX is
748        *   not large enough.
749        */
750       mt_com.mt_count = INT16_MAX;    /* use big positive number */
751       if (mt_com.mt_count < 0) {
752          mt_com.mt_count = INT16_MAX; /* brain damaged system */
753       }
754    }
755
756    if (dev_cap(dev, CAP_MTIOCGET) && (dev_cap(dev, CAP_FASTFSF) || dev_cap(dev, CAP_EOM))) {
757       if (dev_cap(dev, CAP_EOM)) {
758          Dmsg0(100,"Using EOM for EOM\n");
759          mt_com.mt_op = MTEOM;
760          mt_com.mt_count = 1;
761       }
762
763       if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
764          berrno be;
765          clrerror_dev(dev, mt_com.mt_op);
766          Dmsg1(50, "ioctl error: %s\n", be.strerror());
767          update_pos_dev(dev);
768          Mmsg2(dev->errmsg, _("ioctl MTEOM error on %s. ERR=%s.\n"),
769             dev->print_name(), be.strerror());
770          return false;
771       }
772
773       if (!dev_get_os_pos(dev, &mt_stat)) {
774          berrno be;
775          clrerror_dev(dev, -1);
776          Mmsg2(dev->errmsg, _("ioctl MTIOCGET error on %s. ERR=%s.\n"),
777             dev->print_name(), be.strerror());
778          return false;
779       }
780       Dmsg2(100, "EOD file=%d block=%d\n", mt_stat.mt_fileno, mt_stat.mt_blkno);
781       dev->set_ateof();
782       dev->file = mt_stat.mt_fileno;
783    } else {
784 #else
785    {
786 #endif
787       /*
788        * Rewind then use FSF until EOT reached
789        */
790       if (!rewind_dev(dev)) {
791          return false;
792       }
793       /*
794        * Move file by file to the end of the tape
795        */
796       int file_num;
797       for (file_num=dev->file; !dev->at_eot(); file_num++) {
798          Dmsg0(200, "eod_dev: doing fsf 1\n");
799          if (!dev->fsf(1)) {
800             Dmsg0(200, "fsf error.\n");
801             return false;
802          }
803          /*
804           * Avoid infinite loop. ***FIXME*** possibly add code
805           *   to set EOD or to turn off CAP_FASTFSF if on.
806           */
807          if (file_num == (int)dev->file) {
808             struct mtget mt_stat;
809             Dmsg1(100, "fsf did not advance from file %d\n", file_num);
810             if (dev_get_os_pos(dev, &mt_stat)) {
811                Dmsg2(100, "Adjust file from %d to %d\n", dev->file , mt_stat.mt_fileno);
812                dev->set_ateof();
813                dev->file = mt_stat.mt_fileno;
814             }
815             return false;
816          }
817       }
818    }
819    /*
820     * Some drivers leave us after second EOF when doing
821     * MTEOM, so we must backup so that appending overwrites
822     * the second EOF.
823     */
824    if (dev_cap(dev, CAP_BSFATEOM)) {
825       struct mtget mt_stat;
826       /* Backup over EOF */
827       ok = bsf_dev(dev, 1);
828       /* If BSF worked and fileno is known (not -1), set file */
829       if (dev_get_os_pos(dev, &mt_stat)) {
830          Dmsg2(100, "BSFATEOF adjust file from %d to %d\n", dev->file , mt_stat.mt_fileno);
831          dev->file = mt_stat.mt_fileno;
832       } else {
833          dev->file++;                 /* wing it -- not correct on all OSes */
834       }
835    } else {
836       update_pos_dev(dev);                   /* update position */
837    }
838    Dmsg1(200, "EOD dev->file=%d\n", dev->file);
839    return ok;
840 }
841
842 /*
843  * Set the position of the device -- only for files
844  *   For other devices, there is no generic way to do it.
845  *  Returns: true  on succes
846  *           false on error
847  */
848 bool update_pos_dev(DEVICE *dev)
849 {
850    off_t pos;
851    bool ok = true;
852
853    if (dev->fd < 0) {
854       dev->dev_errno = EBADF;
855       Mmsg0(dev->errmsg, _("Bad device call. Device not open\n"));
856       Emsg0(M_FATAL, 0, dev->errmsg);
857       return false;
858    }
859
860    /* Find out where we are */
861    if (dev->is_file()) {
862       dev->file = 0;
863       dev->file_addr = 0;
864       pos = lseek_dev(dev, (off_t)0, SEEK_CUR);
865       if (pos < 0) {
866          berrno be;
867          dev->dev_errno = errno;
868          Pmsg1(000, "Seek error: ERR=%s\n", be.strerror());
869          Mmsg2(dev->errmsg, _("lseek_dev error on %s. ERR=%s.\n"),
870             dev->print_name(), be.strerror());
871          ok = false;
872       } else {
873          dev->file_addr = pos;
874       }
875    }
876    return ok;
877 }
878
879
880 /*
881  * Return the status of the device.  This was meant
882  * to be a generic routine. Unfortunately, it doesn't
883  * seem possible (at least I do not know how to do it
884  * currently), which means that for the moment, this
885  * routine has very little value.
886  *
887  *   Returns: status
888  */
889 uint32_t status_dev(DEVICE *dev)
890 {
891    struct mtget mt_stat;
892    uint32_t stat = 0;
893
894    if (dev->state & (ST_EOT | ST_WEOT)) {
895       stat |= BMT_EOD;
896       Pmsg0(-20, " EOD");
897    }
898    if (dev->state & ST_EOF) {
899       stat |= BMT_EOF;
900       Pmsg0(-20, " EOF");
901    }
902    if (dev->is_tape()) {
903       stat |= BMT_TAPE;
904       Pmsg0(-20," Bacula status:");
905       Pmsg2(-20," file=%d block=%d\n", dev->file, dev->block_num);
906       if (ioctl(dev->fd, MTIOCGET, (char *)&mt_stat) < 0) {
907          berrno be;
908          dev->dev_errno = errno;
909          Mmsg2(dev->errmsg, _("ioctl MTIOCGET error on %s. ERR=%s.\n"),
910             dev->print_name(), be.strerror());
911          return 0;
912       }
913       Pmsg0(-20, " Device status:");
914
915 #if defined(HAVE_LINUX_OS)
916       if (GMT_EOF(mt_stat.mt_gstat)) {
917          stat |= BMT_EOF;
918          Pmsg0(-20, " EOF");
919       }
920       if (GMT_BOT(mt_stat.mt_gstat)) {
921          stat |= BMT_BOT;
922          Pmsg0(-20, " BOT");
923       }
924       if (GMT_EOT(mt_stat.mt_gstat)) {
925          stat |= BMT_EOT;
926          Pmsg0(-20, " EOT");
927       }
928       if (GMT_SM(mt_stat.mt_gstat)) {
929          stat |= BMT_SM;
930          Pmsg0(-20, " SM");
931       }
932       if (GMT_EOD(mt_stat.mt_gstat)) {
933          stat |= BMT_EOD;
934          Pmsg0(-20, " EOD");
935       }
936       if (GMT_WR_PROT(mt_stat.mt_gstat)) {
937          stat |= BMT_WR_PROT;
938          Pmsg0(-20, " WR_PROT");
939       }
940       if (GMT_ONLINE(mt_stat.mt_gstat)) {
941          stat |= BMT_ONLINE;
942          Pmsg0(-20, " ONLINE");
943       }
944       if (GMT_DR_OPEN(mt_stat.mt_gstat)) {
945          stat |= BMT_DR_OPEN;
946          Pmsg0(-20, " DR_OPEN");
947       }
948       if (GMT_IM_REP_EN(mt_stat.mt_gstat)) {
949          stat |= BMT_IM_REP_EN;
950          Pmsg0(-20, " IM_REP_EN");
951       }
952 #endif /* !SunOS && !OSF */
953       if (dev_cap(dev, CAP_MTIOCGET)) {
954          Pmsg2(-20, " file=%d block=%d\n", mt_stat.mt_fileno, mt_stat.mt_blkno);
955       } else {
956          Pmsg2(-20, " file=%d block=%d\n", -1, -1);
957       }
958    } else {
959       stat |= BMT_ONLINE | BMT_BOT;
960    }
961    return stat;
962 }
963
964
965 /*
966  * Load medium in device
967  *  Returns: true  on success
968  *           false on failure
969  */
970 bool load_dev(DEVICE *dev)
971 {
972 #ifdef MTLOAD
973    struct mtop mt_com;
974 #endif
975
976    if (dev->fd < 0) {
977       dev->dev_errno = EBADF;
978       Mmsg0(dev->errmsg, _("Bad call to load_dev. Device not open\n"));
979       Emsg0(M_FATAL, 0, dev->errmsg);
980       return false;
981    }
982    if (!(dev->is_tape())) {
983       return true;
984    }
985 #ifndef MTLOAD
986    Dmsg0(200, "stored: MTLOAD command not available\n");
987    berrno be;
988    dev->dev_errno = ENOTTY;           /* function not available */
989    Mmsg2(dev->errmsg, _("ioctl MTLOAD error on %s. ERR=%s.\n"),
990          dev->print_name(), be.strerror());
991    return false;
992 #else
993
994    dev->block_num = dev->file = 0;
995    dev->file_size = 0;
996    dev->file_addr = 0;
997    mt_com.mt_op = MTLOAD;
998    mt_com.mt_count = 1;
999    if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
1000       berrno be;
1001       dev->dev_errno = errno;
1002       Mmsg2(dev->errmsg, _("ioctl MTLOAD error on %s. ERR=%s.\n"),
1003          dev->print_name(), be.strerror());
1004       return false;
1005    }
1006    return true;
1007 #endif
1008 }
1009
1010 /*
1011  * Rewind device and put it offline
1012  *  Returns: true  on success
1013  *           false on failure
1014  */
1015 bool offline_dev(DEVICE *dev)
1016 {
1017    struct mtop mt_com;
1018
1019    if (dev->fd < 0) {
1020       dev->dev_errno = EBADF;
1021       Mmsg0(dev->errmsg, _("Bad call to offline_dev. Device not open\n"));
1022       Emsg0(M_FATAL, 0, dev->errmsg);
1023       return false;
1024    }
1025    if (!(dev->is_tape())) {
1026       return true;
1027    }
1028
1029    dev->state &= ~(ST_APPEND|ST_READ|ST_EOT|ST_EOF|ST_WEOT);  /* remove EOF/EOT flags */
1030    dev->block_num = dev->file = 0;
1031    dev->file_size = 0;
1032    dev->file_addr = 0;
1033    dev->part = 0;
1034 #ifdef MTUNLOCK
1035    mt_com.mt_op = MTUNLOCK;
1036    mt_com.mt_count = 1;
1037    ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
1038 #endif
1039    mt_com.mt_op = MTOFFL;
1040    mt_com.mt_count = 1;
1041    if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
1042       berrno be;
1043       dev->dev_errno = errno;
1044       Mmsg2(dev->errmsg, _("ioctl MTOFFL error on %s. ERR=%s.\n"),
1045          dev->print_name(), be.strerror());
1046       return false;
1047    }
1048    Dmsg1(100, "Offlined device %s\n", dev->print_name());
1049    return true;
1050 }
1051
1052 bool offline_or_rewind_dev(DEVICE *dev)
1053 {
1054    if (dev->fd < 0) {
1055       return false;
1056    }
1057    if (dev_cap(dev, CAP_OFFLINEUNMOUNT)) {
1058       return offline_dev(dev);
1059    } else {
1060    /*
1061     * Note, this rewind probably should not be here (it wasn't
1062     *  in prior versions of Bacula), but on FreeBSD, this is
1063     *  needed in the case the tape was "frozen" due to an error
1064     *  such as backspacing after writing and EOF. If it is not
1065     *  done, all future references to the drive get and I/O error.
1066     */
1067       clrerror_dev(dev, MTREW);
1068       return rewind_dev(dev);
1069    }
1070 }
1071
1072 /*
1073  * Foward space a file
1074  *   Returns: true  on success
1075  *            false on failure
1076  */
1077 bool DEVICE::fsf(int num)
1078 {
1079    struct mtget mt_stat;
1080    struct mtop mt_com;
1081    int stat = 0;
1082
1083    if (fd < 0) {
1084       dev_errno = EBADF;
1085       Mmsg0(errmsg, _("Bad call to fsf_dev. Device not open\n"));
1086       Emsg0(M_FATAL, 0, errmsg);
1087       return false;
1088    }
1089
1090    if (!is_tape()) {
1091       return true;
1092    }
1093    if (at_eot()) {
1094       dev_errno = 0;
1095       Mmsg1(errmsg, _("Device %s at End of Tape.\n"), print_name());
1096       return false;
1097    }
1098    if (at_eof()) {
1099       Dmsg0(200, "ST_EOF set on entry to FSF\n");
1100    }
1101
1102    Dmsg0(100, "fsf\n");
1103    block_num = 0;
1104    /*
1105     * If Fast forward space file is set, then we
1106     *  use MTFSF to forward space and MTIOCGET
1107     *  to get the file position. We assume that
1108     *  the SCSI driver will ensure that we do not
1109     *  forward space past the end of the medium.
1110     */
1111    if (dev_cap(this, CAP_FSF) && dev_cap(this, CAP_MTIOCGET) && dev_cap(this, CAP_FASTFSF)) {
1112       mt_com.mt_op = MTFSF;
1113       mt_com.mt_count = num;
1114       stat = ioctl(fd, MTIOCTOP, (char *)&mt_com);
1115       if (stat < 0 || !dev_get_os_pos(this, &mt_stat)) {
1116          berrno be;
1117          set_eot();
1118          Dmsg0(200, "Set ST_EOT\n");
1119          clrerror_dev(this, MTFSF);
1120          Mmsg2(errmsg, _("ioctl MTFSF error on %s. ERR=%s.\n"),
1121             print_name(), be.strerror());
1122          Dmsg1(200, "%s", errmsg);
1123          return false;
1124       }
1125       Dmsg2(200, "fsf file=%d block=%d\n", mt_stat.mt_fileno, mt_stat.mt_blkno);
1126       set_ateof();
1127       file = mt_stat.mt_fileno;
1128       return true;
1129
1130    /*
1131     * Here if CAP_FSF is set, and virtually all drives
1132     *  these days support it, we read a record, then forward
1133     *  space one file. Using this procedure, which is slow,
1134     *  is the only way we can be sure that we don't read
1135     *  two consecutive EOF marks, which means End of Data.
1136     */
1137    } else if (dev_cap(this, CAP_FSF)) {
1138       POOLMEM *rbuf;
1139       int rbuf_len;
1140       Dmsg0(200, "FSF has cap_fsf\n");
1141       if (max_block_size == 0) {
1142          rbuf_len = DEFAULT_BLOCK_SIZE;
1143       } else {
1144          rbuf_len = max_block_size;
1145       }
1146       rbuf = get_memory(rbuf_len);
1147       mt_com.mt_op = MTFSF;
1148       mt_com.mt_count = 1;
1149       while (num-- && !at_eot()) {
1150          Dmsg0(100, "Doing read before fsf\n");
1151          if ((stat = read(fd, (char *)rbuf, rbuf_len)) < 0) {
1152             if (errno == ENOMEM) {     /* tape record exceeds buf len */
1153                stat = rbuf_len;        /* This is OK */
1154             /*
1155              * On IBM drives, they return ENOSPC at EOM
1156              *  instead of EOF status
1157              */
1158             } else if (at_eof() && errno == ENOSPC) {
1159                stat = 0;
1160             } else {
1161                berrno be;
1162                set_eot();
1163                clrerror_dev(this, -1);
1164                Dmsg2(100, "Set ST_EOT read errno=%d. ERR=%s\n", dev_errno,
1165                   be.strerror());
1166                Mmsg2(errmsg, _("read error on %s. ERR=%s.\n"),
1167                   print_name(), be.strerror());
1168                Dmsg1(100, "%s", errmsg);
1169                break;
1170             }
1171          }
1172          if (stat == 0) {                /* EOF */
1173             update_pos_dev(this);
1174             Dmsg1(100, "End of File mark from read. File=%d\n", file+1);
1175             /* Two reads of zero means end of tape */
1176             if (at_eof()) {
1177                set_eot();
1178                Dmsg0(100, "Set ST_EOT\n");
1179                break;
1180             } else {
1181                set_ateof();
1182                continue;
1183             }
1184          } else {                        /* Got data */
1185             clear_eot();
1186             clear_eof();
1187          }
1188
1189          Dmsg0(100, "Doing MTFSF\n");
1190          stat = ioctl(fd, MTIOCTOP, (char *)&mt_com);
1191          if (stat < 0) {                 /* error => EOT */
1192             berrno be;
1193             set_eot();
1194             Dmsg0(100, "Set ST_EOT\n");
1195             clrerror_dev(this, MTFSF);
1196             Mmsg2(errmsg, _("ioctl MTFSF error on %s. ERR=%s.\n"),
1197                print_name(), be.strerror());
1198             Dmsg0(100, "Got < 0 for MTFSF\n");
1199             Dmsg1(100, "%s", errmsg);
1200          } else {
1201             set_ateof();
1202          }
1203       }
1204       free_memory(rbuf);
1205
1206    /*
1207     * No FSF, so use FSR to simulate it
1208     */
1209    } else {
1210       Dmsg0(200, "Doing FSR for FSF\n");
1211       while (num-- && !at_eot()) {
1212          fsr(INT32_MAX);    /* returns -1 on EOF or EOT */
1213       }
1214       if (at_eot()) {
1215          dev_errno = 0;
1216          Mmsg1(errmsg, _("Device %s at End of Tape.\n"), print_name());
1217          stat = -1;
1218       } else {
1219          stat = 0;
1220       }
1221    }
1222    update_pos_dev(this);
1223    Dmsg1(200, "Return %d from FSF\n", stat);
1224    if (at_eof())
1225       Dmsg0(200, "ST_EOF set on exit FSF\n");
1226    if (at_eot())
1227       Dmsg0(200, "ST_EOT set on exit FSF\n");
1228    Dmsg1(200, "Return from FSF file=%d\n", file);
1229    return stat == 0;
1230 }
1231
1232 /*
1233  * Backward space a file
1234  *  Returns: false on failure
1235  *           true  on success
1236  */
1237 bool
1238 bsf_dev(DEVICE *dev, int num)
1239 {
1240    struct mtop mt_com;
1241    int stat;
1242
1243    if (dev->fd < 0) {
1244       dev->dev_errno = EBADF;
1245       Mmsg0(dev->errmsg, _("Bad call to bsf_dev. Device not open\n"));
1246       Emsg0(M_FATAL, 0, dev->errmsg);
1247       return false;
1248    }
1249
1250    if (!dev->is_tape()) {
1251       Mmsg1(dev->errmsg, _("Device %s cannot BSF because it is not a tape.\n"),
1252          dev->print_name());
1253       return false;
1254    }
1255    Dmsg0(29, "bsf_dev\n");
1256    dev->state &= ~(ST_EOT|ST_EOF);
1257    dev->file -= num;
1258    dev->file_addr = 0;
1259    dev->file_size = 0;
1260    mt_com.mt_op = MTBSF;
1261    mt_com.mt_count = num;
1262    stat = ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
1263    if (stat < 0) {
1264       berrno be;
1265       clrerror_dev(dev, MTBSF);
1266       Mmsg2(dev->errmsg, _("ioctl MTBSF error on %s. ERR=%s.\n"),
1267          dev->print_name(), be.strerror());
1268    }
1269    update_pos_dev(dev);
1270    return stat == 0;
1271 }
1272
1273
1274 /*
1275  * Foward space num records
1276  *  Returns: false on failure
1277  *           true  on success
1278  */
1279 bool DEVICE::fsr(int num)
1280 {
1281    struct mtop mt_com;
1282    int stat;
1283
1284    if (fd < 0) {
1285       dev_errno = EBADF;
1286       Mmsg0(errmsg, _("Bad call to fsr. Device not open\n"));
1287       Emsg0(M_FATAL, 0, errmsg);
1288       return false;
1289    }
1290
1291    if (!is_tape()) {
1292       return false;
1293    }
1294    if (!dev_cap(this, CAP_FSR)) {
1295       Mmsg1(errmsg, _("ioctl MTFSR not permitted on %s.\n"), print_name());
1296       return false;
1297    }
1298
1299    Dmsg1(29, "fsr %d\n", num);
1300    mt_com.mt_op = MTFSR;
1301    mt_com.mt_count = num;
1302    stat = ioctl(fd, MTIOCTOP, (char *)&mt_com);
1303    if (stat == 0) {
1304       clear_eof();
1305       block_num += num;
1306    } else {
1307       berrno be;
1308       struct mtget mt_stat;
1309       clrerror_dev(this, MTFSR);
1310       Dmsg1(100, "FSF fail: ERR=%s\n", be.strerror());
1311       if (dev_get_os_pos(this, &mt_stat)) {
1312          Dmsg4(100, "Adjust from %d:%d to %d:%d\n", file,
1313             block_num, mt_stat.mt_fileno, mt_stat.mt_blkno);
1314          file = mt_stat.mt_fileno;
1315          block_num = mt_stat.mt_blkno;
1316       } else {
1317          if (at_eof()) {
1318             set_eot();
1319          } else {
1320             set_ateof();
1321          }
1322       }
1323       Mmsg3(errmsg, _("ioctl MTFSR %d error on %s. ERR=%s.\n"),
1324          num, print_name(), be.strerror());
1325    }
1326    update_pos_dev(this);
1327    return stat == 0;
1328 }
1329
1330 /*
1331  * Backward space a record
1332  *   Returns:  false on failure
1333  *             true  on success
1334  */
1335 bool
1336 bsr_dev(DEVICE *dev, int num)
1337 {
1338    struct mtop mt_com;
1339    int stat;
1340
1341    if (dev->fd < 0) {
1342       dev->dev_errno = EBADF;
1343       Mmsg0(dev->errmsg, _("Bad call to bsr_dev. Device not open\n"));
1344       Emsg0(M_FATAL, 0, dev->errmsg);
1345       return false;
1346    }
1347
1348    if (!dev->is_tape()) {
1349       return false;
1350    }
1351
1352    if (!dev_cap(dev, CAP_BSR)) {
1353       Mmsg1(dev->errmsg, _("ioctl MTBSR not permitted on %s.\n"), dev->print_name());
1354       return false;
1355    }
1356
1357    Dmsg0(29, "bsr_dev\n");
1358    dev->block_num -= num;
1359    dev->state &= ~(ST_EOF|ST_EOT|ST_EOF);
1360    mt_com.mt_op = MTBSR;
1361    mt_com.mt_count = num;
1362    stat = ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
1363    if (stat < 0) {
1364       berrno be;
1365       clrerror_dev(dev, MTBSR);
1366       Mmsg2(dev->errmsg, _("ioctl MTBSR error on %s. ERR=%s.\n"),
1367          dev->print_name(), be.strerror());
1368    }
1369    update_pos_dev(dev);
1370    return stat == 0;
1371 }
1372
1373 /*
1374  * Reposition the device to file, block
1375  * Returns: false on failure
1376  *          true  on success
1377  */
1378 bool
1379 reposition_dev(DEVICE *dev, uint32_t file, uint32_t block)
1380 {
1381    if (dev->fd < 0) {
1382       dev->dev_errno = EBADF;
1383       Mmsg0(dev->errmsg, _("Bad call to reposition_dev. Device not open\n"));
1384       Emsg0(M_FATAL, 0, dev->errmsg);
1385       return false;
1386    }
1387
1388    if (!dev->is_tape()) {
1389       off_t pos = (((off_t)file)<<32) + block;
1390       Dmsg1(100, "===== lseek_dev to %d\n", (int)pos);
1391       if (lseek_dev(dev, pos, SEEK_SET) == (off_t)-1) {
1392          berrno be;
1393          dev->dev_errno = errno;
1394          Mmsg2(dev->errmsg, _("lseek_dev error on %s. ERR=%s.\n"),
1395             dev->print_name(), be.strerror());
1396          return false;
1397       }
1398       dev->file = file;
1399       dev->block_num = block;
1400       dev->file_addr = pos;
1401       return true;
1402    }
1403    Dmsg4(100, "reposition_dev from %u:%u to %u:%u\n",
1404       dev->file, dev->block_num, file, block);
1405    if (file < dev->file) {
1406       Dmsg0(100, "Rewind_dev\n");
1407       if (!rewind_dev(dev)) {
1408          return false;
1409       }
1410    }
1411    if (file > dev->file) {
1412       Dmsg1(100, "fsf %d\n", file-dev->file);
1413       if (!dev->fsf(file-dev->file)) {
1414          Dmsg1(100, "fsf failed! ERR=%s\n", strerror_dev(dev));
1415          return false;
1416       }
1417       Dmsg2(100, "wanted_file=%d at_file=%d\n", file, dev->file);
1418    }
1419    if (block < dev->block_num) {
1420       Dmsg2(100, "wanted_blk=%d at_blk=%d\n", block, dev->block_num);
1421       Dmsg0(100, "bsf_dev 1\n");
1422       bsf_dev(dev, 1);
1423       Dmsg0(100, "fsf_dev 1\n");
1424       dev->fsf(1);
1425       Dmsg2(100, "wanted_blk=%d at_blk=%d\n", block, dev->block_num);
1426    }
1427    if (dev_cap(dev, CAP_POSITIONBLOCKS) && block > dev->block_num) {
1428       /* Ignore errors as Bacula can read to the correct block */
1429       Dmsg1(100, "fsr %d\n", block-dev->block_num);
1430       return dev->fsr(block-dev->block_num);
1431    }
1432    return true;
1433 }
1434
1435
1436
1437 /*
1438  * Write an end of file on the device
1439  *   Returns: 0 on success
1440  *            non-zero on failure
1441  */
1442 int
1443 weof_dev(DEVICE *dev, int num)
1444 {
1445    struct mtop mt_com;
1446    int stat;
1447    Dmsg0(29, "weof_dev\n");
1448    
1449    if (dev->fd < 0) {
1450       dev->dev_errno = EBADF;
1451       Mmsg0(dev->errmsg, _("Bad call to weof_dev. Device not open\n"));
1452       Emsg0(M_FATAL, 0, dev->errmsg);
1453       return -1;
1454    }
1455    dev->file_size = 0;
1456
1457    if (!dev->is_tape()) {
1458       return 0;
1459    }
1460    if (!dev->can_append()) {
1461       Mmsg0(dev->errmsg, _("Attempt to WEOF on non-appendable Volume\n"));
1462       Emsg0(M_FATAL, 0, dev->errmsg);
1463       return -1;
1464    }
1465       
1466    dev->state &= ~(ST_EOT | ST_EOF);  /* remove EOF/EOT flags */
1467    mt_com.mt_op = MTWEOF;
1468    mt_com.mt_count = num;
1469    stat = ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
1470    if (stat == 0) {
1471       dev->block_num = 0;
1472       dev->file += num;
1473       dev->file_addr = 0;
1474    } else {
1475       berrno be;
1476       clrerror_dev(dev, MTWEOF);
1477       if (stat == -1) {
1478          Mmsg2(dev->errmsg, _("ioctl MTWEOF error on %s. ERR=%s.\n"),
1479             dev->print_name(), be.strerror());
1480        }
1481    }
1482    return stat;
1483 }
1484
1485 /*
1486  * Return string message with last error in English
1487  *  Be careful not to call this routine from within dev.c
1488  *  while editing an Mmsg() or you will end up in a recursive
1489  *  loop creating a Segmentation Violation.
1490  */
1491 char *
1492 strerror_dev(DEVICE *dev)
1493 {
1494    return dev->errmsg;
1495 }
1496
1497
1498 /*
1499  * If implemented in system, clear the tape
1500  * error status.
1501  */
1502 void
1503 clrerror_dev(DEVICE *dev, int func)
1504 {
1505    const char *msg = NULL;
1506    struct mtget mt_stat;
1507    char buf[100];
1508
1509    dev->dev_errno = errno;         /* save errno */
1510    if (errno == EIO) {
1511       dev->VolCatInfo.VolCatErrors++;
1512    }
1513
1514    if (!dev->is_tape()) {
1515       return;
1516    }
1517    if (errno == ENOTTY || errno == ENOSYS) { /* Function not implemented */
1518       switch (func) {
1519       case -1:
1520          Emsg0(M_ABORT, 0, "Got ENOTTY on read/write!\n");
1521          break;
1522       case MTWEOF:
1523          msg = "WTWEOF";
1524          dev->capabilities &= ~CAP_EOF; /* turn off feature */
1525          break;
1526 #ifdef MTEOM
1527       case MTEOM:
1528          msg = "WTEOM";
1529          dev->capabilities &= ~CAP_EOM; /* turn off feature */
1530          break;
1531 #endif
1532       case MTFSF:
1533          msg = "MTFSF";
1534          dev->capabilities &= ~CAP_FSF; /* turn off feature */
1535          break;
1536       case MTBSF:
1537          msg = "MTBSF";
1538          dev->capabilities &= ~CAP_BSF; /* turn off feature */
1539          break;
1540       case MTFSR:
1541          msg = "MTFSR";
1542          dev->capabilities &= ~CAP_FSR; /* turn off feature */
1543          break;
1544       case MTBSR:
1545          msg = "MTBSR";
1546          dev->capabilities &= ~CAP_BSR; /* turn off feature */
1547          break;
1548       case MTREW:
1549          msg = "MTREW";
1550          break;
1551 #ifdef MTSETBLK
1552       case MTSETBLK:
1553          msg = "MTSETBLK";
1554          break;
1555 #endif
1556 #ifdef MTSETBSIZ 
1557       case MTSETBSIZ:
1558          msg = "MTSETBSIZ";
1559          break;
1560 #endif
1561 #ifdef MTSRSZ
1562       case MTSRSZ:
1563          msg = "MTSRSZ";
1564          break;
1565 #endif
1566       default:
1567          bsnprintf(buf, sizeof(buf), "unknown func code %d", func);
1568          msg = buf;
1569          break;
1570       }
1571       if (msg != NULL) {
1572          dev->dev_errno = ENOSYS;
1573          Mmsg1(dev->errmsg, _("I/O function \"%s\" not supported on this device.\n"), msg);
1574          Emsg0(M_ERROR, 0, dev->errmsg);
1575       }
1576    }
1577    /* On some systems such as NetBSD, this clears all errors */
1578    ioctl(dev->fd, MTIOCGET, (char *)&mt_stat);
1579
1580 /* Found on Linux */
1581 #ifdef MTIOCLRERR
1582 {
1583    struct mtop mt_com;
1584    mt_com.mt_op = MTIOCLRERR;
1585    mt_com.mt_count = 1;
1586    /* Clear any error condition on the tape */
1587    ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
1588    Dmsg0(200, "Did MTIOCLRERR\n");
1589 }
1590 #endif
1591
1592 /* Typically on FreeBSD */
1593 #ifdef MTIOCERRSTAT
1594 {
1595    /* Read and clear SCSI error status */
1596    union mterrstat mt_errstat;
1597    Dmsg2(200, "Doing MTIOCERRSTAT errno=%d ERR=%s\n", dev->dev_errno,
1598       strerror(dev->dev_errno));
1599    ioctl(dev->fd, MTIOCERRSTAT, (char *)&mt_errstat);
1600 }
1601 #endif
1602
1603 /* Clear Subsystem Exception OSF1 */
1604 #ifdef MTCSE
1605 {
1606    struct mtop mt_com;
1607    mt_com.mt_op = MTCSE;
1608    mt_com.mt_count = 1;
1609    /* Clear any error condition on the tape */
1610    ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
1611    Dmsg0(200, "Did MTCSE\n");
1612 }
1613 #endif
1614 }
1615
1616 /*
1617  * Flush buffer contents
1618  *  No longer used.
1619  */
1620 int flush_dev(DEVICE *dev)
1621 {
1622    return 1;
1623 }
1624
1625 static void do_close(DEVICE *dev)
1626 {
1627
1628    Dmsg1(29, "really close_dev %s\n", dev->print_name());
1629    if (dev->fd >= 0) {
1630       close(dev->fd);
1631    }
1632
1633    if (!unmount_dev(dev, 1)) {
1634       Dmsg1(0, "Cannot unmount device %s.\n", dev->print_name());
1635    }
1636    
1637    /* Remove the last part file if it is empty */
1638    if (dev->can_append() && (dev->num_parts > 0)) {
1639       struct stat statp;
1640       POOL_MEM archive_name(PM_FNAME);
1641       dev->part = dev->num_parts;
1642       Dmsg1(100, "Call make_dvd_filename. Vol=%s\n", dev->VolCatInfo.VolCatName);
1643       make_spooled_dvd_filename(dev, archive_name);
1644       /* Check that the part file is empty */
1645       if ((stat(archive_name.c_str(), &statp) == 0) && (statp.st_size == 0)) {
1646          Dmsg1(100, "unlink(%s)\n", archive_name.c_str());
1647          unlink(archive_name.c_str());
1648       }
1649    }
1650    
1651    /* Clean up device packet so it can be reused */
1652    dev->fd = -1;
1653    dev->state &= ~(ST_OPENED|ST_LABEL|ST_READ|ST_APPEND|ST_EOT|ST_WEOT|ST_EOF);
1654    dev->label_type = B_BACULA_LABEL;
1655    dev->file = dev->block_num = 0;
1656    dev->file_size = 0;
1657    dev->file_addr = 0;
1658    dev->part = 0;
1659    dev->part_size = 0;
1660    dev->part_start = 0;
1661    dev->EndFile = dev->EndBlock = 0;
1662    memset(&dev->VolCatInfo, 0, sizeof(dev->VolCatInfo));
1663    memset(&dev->VolHdr, 0, sizeof(dev->VolHdr));
1664    if (dev->tid) {
1665       stop_thread_timer(dev->tid);
1666       dev->tid = 0;
1667    }
1668    dev->use_count = 0;
1669    dev->openmode = 0;
1670 }
1671
1672 /*
1673  * Close the device
1674  */
1675 void DEVICE::close()
1676 {
1677    /*if (fd >= 0 && use_count == 1) {*/
1678    /* No need to check if fd >= 0: it is checked again
1679     * in do_close, and do_close MUST be called for volumes
1680     * splitted in parts, even if fd == -1. */
1681    if (use_count == 1) {
1682       do_close(this);
1683    } else if (use_count > 0) {
1684       use_count--;
1685    }
1686
1687 #ifdef FULL_DEBUG
1688    ASSERT(use_count >= 0);
1689 #endif
1690 }
1691
1692
1693 bool truncate_dev(DEVICE *dev)
1694 {
1695    Dmsg1(100, "truncate_dev %s\n", dev->print_name());
1696    if (dev->is_tape()) {
1697       return true;                    /* we don't really truncate tapes */
1698       /* maybe we should rewind and write and eof ???? */
1699    }
1700    
1701    if (dev->is_dvd()) {
1702       Mmsg1(dev->errmsg, _("Truncate DVD %s not supported.\n"), dev->print_name());
1703       return false;   /* we cannot truncate DVDs */
1704    }
1705    
1706    if (ftruncate(dev->fd, 0) != 0) {
1707       berrno be;
1708       Mmsg2(dev->errmsg, _("Unable to truncate device %s. ERR=%s\n"), 
1709             dev->print_name(), be.strerror());
1710       return false;
1711    }
1712    return true;
1713 }
1714
1715 /* Return the resource name for the device */
1716 const char *DEVICE::name() const
1717 {
1718    return device->hdr.name;
1719 }
1720
1721 char *
1722 dev_vol_name(DEVICE *dev)
1723 {
1724    return dev->VolCatInfo.VolCatName;
1725 }
1726
1727 uint32_t dev_block(DEVICE *dev)
1728 {
1729    update_pos_dev(dev);
1730    return dev->block_num;
1731 }
1732
1733 uint32_t dev_file(DEVICE *dev)
1734 {
1735    update_pos_dev(dev);
1736    return dev->file;
1737 }
1738
1739 /*
1740  * Free memory allocated for the device
1741  */
1742 void
1743 term_dev(DEVICE *dev)
1744 {
1745    if (!dev) {
1746       dev->dev_errno = EBADF;
1747       Mmsg0(dev->errmsg, _("Bad call to term_dev. Device not open\n"));
1748       Emsg0(M_FATAL, 0, dev->errmsg);
1749       return;
1750    }
1751    Dmsg1(29, "term_dev: %s\n", dev->print_name());
1752    do_close(dev);
1753    if (dev->dev_name) {
1754       free_memory(dev->dev_name);
1755       dev->dev_name = NULL;
1756    }
1757    if (dev->prt_name) {
1758       free_memory(dev->prt_name);
1759       dev->prt_name = NULL;
1760    }
1761    if (dev->errmsg) {
1762       free_pool_memory(dev->errmsg);
1763       dev->errmsg = NULL;
1764    }
1765    pthread_mutex_destroy(&dev->mutex);
1766    pthread_cond_destroy(&dev->wait);
1767    pthread_cond_destroy(&dev->wait_next_vol);
1768    pthread_mutex_destroy(&dev->spool_mutex);
1769    rwl_destroy(&dev->lock);
1770    if (dev->attached_dcrs) {
1771       delete dev->attached_dcrs;
1772       dev->attached_dcrs = NULL;
1773    }
1774    if (dev->state & ST_MALLOC) {
1775       free_pool_memory((POOLMEM *)dev);
1776    }
1777 }
1778
1779 /*
1780  * This routine initializes the device wait timers
1781  */
1782 void init_device_wait_timers(DCR *dcr)
1783 {
1784    DEVICE *dev = dcr->dev;
1785    JCR *jcr = dcr->jcr;
1786
1787    /* ******FIXME******* put these on config variables */
1788    dev->min_wait = 60 * 60;
1789    dev->max_wait = 24 * 60 * 60;
1790    dev->max_num_wait = 9;              /* 5 waits =~ 1 day, then 1 day at a time */
1791    dev->wait_sec = dev->min_wait;
1792    dev->rem_wait_sec = dev->wait_sec;
1793    dev->num_wait = 0;
1794    dev->poll = false;
1795    dev->BadVolName[0] = 0;
1796
1797    jcr->min_wait = 60 * 60;
1798    jcr->max_wait = 24 * 60 * 60;
1799    jcr->max_num_wait = 9;              /* 5 waits =~ 1 day, then 1 day at a time */
1800    jcr->wait_sec = jcr->min_wait;
1801    jcr->rem_wait_sec = jcr->wait_sec;
1802    jcr->num_wait = 0;
1803
1804 }
1805
1806 void init_jcr_device_wait_timers(JCR *jcr)
1807 {
1808    /* ******FIXME******* put these on config variables */
1809    jcr->min_wait = 60 * 60;
1810    jcr->max_wait = 24 * 60 * 60;
1811    jcr->max_num_wait = 9;              /* 5 waits =~ 1 day, then 1 day at a time */
1812    jcr->wait_sec = jcr->min_wait;
1813    jcr->rem_wait_sec = jcr->wait_sec;
1814    jcr->num_wait = 0;
1815 }
1816
1817
1818 /*
1819  * The dev timers are used for waiting on a particular device 
1820  *
1821  * Returns: true if time doubled
1822  *          false if max time expired
1823  */
1824 bool double_dev_wait_time(DEVICE *dev)
1825 {
1826    dev->wait_sec *= 2;               /* double wait time */
1827    if (dev->wait_sec > dev->max_wait) {   /* but not longer than maxtime */
1828       dev->wait_sec = dev->max_wait;
1829    }
1830    dev->num_wait++;
1831    dev->rem_wait_sec = dev->wait_sec;
1832    if (dev->num_wait >= dev->max_num_wait) {
1833       return false;
1834    }
1835    return true;
1836 }
1837
1838
1839 void set_os_device_parameters(DEVICE *dev)
1840 {
1841 #ifdef HAVE_LINUX_OS
1842    struct mtop mt_com;
1843    if (dev->min_block_size == dev->max_block_size &&
1844        dev->min_block_size == 0) {    /* variable block mode */
1845       mt_com.mt_op = MTSETBLK;
1846       mt_com.mt_count = 0;
1847       if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
1848          clrerror_dev(dev, MTSETBLK);
1849       }
1850       mt_com.mt_op = MTSETDRVBUFFER;
1851       mt_com.mt_count = MT_ST_CLEARBOOLEANS;
1852       if (!dev_cap(dev, CAP_TWOEOF)) {
1853          mt_com.mt_count |= MT_ST_TWO_FM;
1854       }
1855       if (dev_cap(dev, CAP_EOM)) {
1856          mt_com.mt_count |= MT_ST_FAST_MTEOM;
1857       }
1858       if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
1859          clrerror_dev(dev, MTSETBLK);
1860       }
1861    }
1862    return;
1863 #endif
1864
1865 #ifdef HAVE_NETBSD_OS
1866    struct mtop mt_com;
1867    if (dev->min_block_size == dev->max_block_size &&
1868        dev->min_block_size == 0) {    /* variable block mode */
1869       mt_com.mt_op = MTSETBSIZ;
1870       mt_com.mt_count = 0;
1871       if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
1872          clrerror_dev(dev, MTSETBSIZ);
1873       }
1874       /* Get notified at logical end of tape */
1875       mt_com.mt_op = MTEWARN;
1876       mt_com.mt_count = 1;
1877       if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
1878          clrerror_dev(dev, MTEWARN);
1879       }
1880    }
1881    return;
1882 #endif
1883
1884 #if HAVE_FREEBSD_OS || HAVE_OPENBSD_OS
1885    struct mtop mt_com;
1886    if (dev->min_block_size == dev->max_block_size &&
1887        dev->min_block_size == 0) {    /* variable block mode */
1888       mt_com.mt_op = MTSETBSIZ;
1889       mt_com.mt_count = 0;
1890       if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
1891          clrerror_dev(dev, MTSETBSIZ);
1892       }
1893    }
1894    return;
1895 #endif
1896
1897 #ifdef HAVE_SUN_OS
1898    struct mtop mt_com;
1899    if (dev->min_block_size == dev->max_block_size &&
1900        dev->min_block_size == 0) {    /* variable block mode */
1901       mt_com.mt_op = MTSRSZ;
1902       mt_com.mt_count = 0;
1903       if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
1904          clrerror_dev(dev, MTSRSZ);
1905       }
1906    }
1907    return;
1908 #endif
1909 }
1910
1911 static bool dev_get_os_pos(DEVICE *dev, struct mtget *mt_stat)
1912 {
1913    return dev_cap(dev, CAP_MTIOCGET) && 
1914           ioctl(dev->fd, MTIOCGET, (char *)mt_stat) == 0 &&
1915           mt_stat->mt_fileno >= 0;
1916 }
1917
1918 static char *modes[] = {
1919    "CREATE_READ_WRITE",
1920    "OPEN_READ_WRITE",
1921    "OPEN_READ_ONLY",
1922    "OPEN_WRITE_ONLY"
1923 };
1924
1925
1926 static char *mode_to_str(int mode)  
1927 {
1928    return modes[mode-1];
1929 }