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