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