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