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