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