]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/stored/dev.c
Fixed configure script so scripts/dvd-freespace/writepart are created at configure...
[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 /* Forward referenced functions */
84 void set_os_device_parameters(DEVICE *dev);
85 int mount_dev(DEVICE* dev, int timeout);
86 int unmount_dev(DEVICE* dev, int timeout);
87 int write_part(DEVICE *dev);
88 char *edit_device_codes_dev(DEVICE* dev, char *omsg, const char *imsg);
89 void get_filename(DEVICE *dev, char *VolName, POOL_MEM& archive_name);
90 void update_free_space_dev(DEVICE* dev);
91
92 /*
93  * Allocate and initialize the DEVICE structure
94  * Note, if dev is non-NULL, it is already allocated,
95  * thus we neither allocate it nor free it. This allows
96  * the caller to put the packet in shared memory.
97  *
98  *  Note, for a tape, the device->device_name is the device name
99  *     (e.g. /dev/nst0), and for a file, the device name
100  *     is the directory in which the file will be placed.
101  *
102  */
103 DEVICE *
104 init_dev(DEVICE *dev, DEVRES *device)
105 {
106    struct stat statp;
107    bool tape, fifo;
108    int errstat;
109    DCR *dcr = NULL;
110
111    /* Check that device is available */
112    if (stat(device->device_name, &statp) < 0) {
113       berrno be;
114       if (dev) {
115          dev->dev_errno = errno;
116       }
117       Emsg2(M_FATAL, 0, "Unable to stat device %s : %s\n", device->device_name,
118          be.strerror());
119       return NULL;
120    }
121    
122    /* If the device requires mount :
123     * - Check that the mount point is available 
124     * - Check that (un)mount commands are defined
125     */
126    if (device->cap_bits & CAP_REQMOUNT) {
127       if (stat(device->mount_point, &statp) < 0) {
128          berrno be;
129          if (dev) {
130             dev->dev_errno = errno;
131          }
132          Emsg2(M_FATAL, 0, "Unable to stat mount point %s : %s\n", device->mount_point,
133             be.strerror());
134          return NULL;
135       }
136       if (!device->mount_command || !device->unmount_command) {
137          Emsg0(M_FATAL, 0, "Mount and unmount commands must defined for a device which requires mount.\n");
138          return NULL;
139       }
140       if (!device->write_part_command) {
141          Emsg0(M_FATAL, 0, "Write part command must be defined for a device which requires mount.\n");
142          return NULL;
143       }
144    }
145    
146    tape = false;
147    fifo = false;
148    if (S_ISDIR(statp.st_mode)) {
149       tape = false;
150    } else if (S_ISCHR(statp.st_mode)) {
151       tape = true;
152    } else if (S_ISFIFO(statp.st_mode)) {
153       fifo = true;
154    } else {
155       if (dev) {
156          dev->dev_errno = ENODEV;
157       }
158       Emsg2(M_FATAL, 0, _("%s is an unknown device type. Must be tape or directory. st_mode=%x\n"),
159          device->device_name, statp.st_mode);
160       return NULL;
161    }
162    if (!dev) {
163       dev = (DEVICE *)get_memory(sizeof(DEVICE));
164       memset(dev, 0, sizeof(DEVICE));
165       dev->state = ST_MALLOC;
166    } else {
167       memset(dev, 0, sizeof(DEVICE));
168    }
169
170    /* Copy user supplied device parameters from Resource */
171    dev->dev_name = get_memory(strlen(device->device_name)+1);
172    strcpy(dev->dev_name, device->device_name);
173    dev->capabilities = device->cap_bits;
174    dev->min_block_size = device->min_block_size;
175    dev->max_block_size = device->max_block_size;
176    dev->max_volume_size = device->max_volume_size;
177    dev->max_file_size = device->max_file_size;
178    dev->volume_capacity = device->volume_capacity;
179    dev->max_rewind_wait = device->max_rewind_wait;
180    dev->max_open_wait = device->max_open_wait;
181    dev->max_open_vols = device->max_open_vols;
182    dev->vol_poll_interval = device->vol_poll_interval;
183    dev->max_spool_size = device->max_spool_size;
184    dev->drive_index = device->drive_index;
185    if (tape) { /* No parts on tapes */
186       dev->max_part_size = 0;
187    }
188    else {
189       dev->max_part_size = device->max_part_size;
190    }
191    /* Sanity check */
192    if (dev->vol_poll_interval && dev->vol_poll_interval < 60) {
193       dev->vol_poll_interval = 60;
194    }
195    dev->device = device;
196
197    if (tape) {
198       dev->state |= ST_TAPE;
199    } else if (fifo) {
200       dev->state |= ST_FIFO;
201       dev->capabilities |= CAP_STREAM; /* set stream device */
202    } else {
203       dev->state |= ST_FILE;
204    }
205
206    if (dev->max_block_size > 1000000) {
207       Emsg3(M_ERROR, 0, _("Block size %u on device %s is too large, using default %u\n"),
208          dev->max_block_size, dev->dev_name, DEFAULT_BLOCK_SIZE);
209       dev->max_block_size = 0;
210    }
211    if (dev->max_block_size % TAPE_BSIZE != 0) {
212       Emsg2(M_WARNING, 0, _("Max block size %u not multiple of device %s block size.\n"),
213          dev->max_block_size, dev->dev_name);
214    }
215
216    dev->errmsg = get_pool_memory(PM_EMSG);
217    *dev->errmsg = 0;
218
219    if ((errstat = pthread_mutex_init(&dev->mutex, NULL)) != 0) {
220       berrno be;
221       dev->dev_errno = errstat;
222       Mmsg1(dev->errmsg, _("Unable to init mutex: ERR=%s\n"), be.strerror(errstat));
223       Emsg0(M_FATAL, 0, dev->errmsg);
224    }
225    if ((errstat = pthread_cond_init(&dev->wait, NULL)) != 0) {
226       berrno be;
227       dev->dev_errno = errstat;
228       Mmsg1(dev->errmsg, _("Unable to init cond variable: ERR=%s\n"), be.strerror(errstat));
229       Emsg0(M_FATAL, 0, dev->errmsg);
230    }
231    if ((errstat = pthread_cond_init(&dev->wait_next_vol, NULL)) != 0) {
232       berrno be;
233       dev->dev_errno = errstat;
234       Mmsg1(dev->errmsg, _("Unable to init cond variable: ERR=%s\n"), be.strerror(errstat));
235       Emsg0(M_FATAL, 0, dev->errmsg);
236    }
237    if ((errstat = pthread_mutex_init(&dev->spool_mutex, NULL)) != 0) {
238       berrno be;
239       dev->dev_errno = errstat;
240       Mmsg1(dev->errmsg, _("Unable to init mutex: ERR=%s\n"), be.strerror(errstat));
241       Emsg0(M_FATAL, 0, dev->errmsg);
242    }
243    if ((errstat = rwl_init(&dev->lock)) != 0) {
244       berrno be;
245       dev->dev_errno = errstat;
246       Mmsg1(dev->errmsg, _("Unable to init mutex: ERR=%s\n"), be.strerror(errstat));
247       Emsg0(M_FATAL, 0, dev->errmsg);
248    }
249
250    dev->fd = -1;
251    dev->attached_dcrs = New(dlist(dcr, &dcr->dev_link));
252    Dmsg2(29, "init_dev: tape=%d dev_name=%s\n", dev_is_tape(dev), dev->dev_name);
253    
254    return dev;
255 }
256
257 /* 
258  * Write the current volume/part filename to archive_name.
259  */
260
261 void get_filename(DEVICE *dev, char *VolName, POOL_MEM& archive_name) {
262    char partnumber[20];
263    
264    if (dev_cap(dev, CAP_REQMOUNT)) {
265          /* If we try to open the last part, just open it from disk, 
266          * otherwise, open it from the spooling directory */
267       if (dev->part < dev->num_parts) {
268          pm_strcpy(archive_name, dev->device->mount_point);
269       }
270       else {
271          /* Use the working directory if spool directory is not defined */
272          if (dev->device->spool_directory) {
273             pm_strcpy(archive_name, dev->device->spool_directory);
274          } else {
275             pm_strcpy(archive_name, working_directory);
276          }
277       }
278    }
279    else {
280       pm_strcpy(archive_name, dev->dev_name);
281    }
282       
283    if (archive_name.c_str()[strlen(archive_name.c_str())-1] != '/') {
284       pm_strcat(archive_name, "/");
285    }
286    pm_strcat(archive_name, VolName);
287    /* if part != 0, append .# to the filename (where # is the part number) */
288    if (dev->part != 0) {
289       pm_strcat(archive_name, ".");
290       bsnprintf(partnumber, sizeof(partnumber), "%d", dev->part);
291       pm_strcat(archive_name, partnumber);
292    }
293 }  
294
295 /* Open the device with the operating system and
296  * initialize buffer pointers.
297  *
298  * Note, for a tape, the VolName is the name we give to the
299  *    volume (not really used here), but for a file, the
300  *    VolName represents the name of the file to be created/opened.
301  *    In the case of a file, the full name is the device name
302  *    (archive_name) with the VolName concatenated.
303  */
304 int
305 open_dev(DEVICE *dev, char *VolName, int mode)
306 {
307    if (dev->state & ST_OPENED) {
308       /*
309        *  *****FIXME***** how to handle two threads wanting
310        *  different volumes mounted???? E.g. one is waiting
311        *  for the next volume to be mounted, and a new job
312        *  starts and snatches up the device.
313        */
314       if (VolName && strcmp(dev->VolCatInfo.VolCatName, VolName) != 0) {
315          return -1;
316       }
317       dev->use_count++;
318       Mmsg2(&dev->errmsg, _("WARNING!!!! device %s opened %d times!!!\n"),
319             dev->dev_name, dev->use_count);
320       Emsg1(M_WARNING, 0, "%s", dev->errmsg);
321       return dev->fd;
322    }
323    if (VolName) {
324       bstrncpy(dev->VolCatInfo.VolCatName, VolName, sizeof(dev->VolCatInfo.VolCatName));
325    }
326
327    Dmsg3(29, "open_dev: tape=%d dev_name=%s vol=%s\n", dev_is_tape(dev),
328          dev->dev_name, dev->VolCatInfo.VolCatName);
329    dev->state &= ~(ST_LABEL|ST_APPEND|ST_READ|ST_EOT|ST_WEOT|ST_EOF);
330    if (dev->state & (ST_TAPE|ST_FIFO)) {
331       dev->file_size = 0;
332       int timeout;
333       Dmsg0(29, "open_dev: device is tape\n");
334       if (mode == OPEN_READ_WRITE) {
335          dev->mode = O_RDWR | O_BINARY;
336       } else if (mode == OPEN_READ_ONLY) {
337          dev->mode = O_RDONLY | O_BINARY;
338       } else if (mode == OPEN_WRITE_ONLY) {
339          dev->mode = O_WRONLY | O_BINARY;
340       } else {
341          Emsg0(M_ABORT, 0, _("Illegal mode given to open_dev.\n"));
342       }
343       timeout = dev->max_open_wait;
344       errno = 0;
345       if (dev->state & ST_FIFO && timeout) {
346          /* Set open timer */
347          dev->tid = start_thread_timer(pthread_self(), timeout);
348       }
349       /* If busy retry each second for max_open_wait seconds */
350       while ((dev->fd = open(dev->dev_name, dev->mode, MODE_RW)) < 0) {
351          berrno be;
352          if (errno == EINTR || errno == EAGAIN) {
353             continue;
354          }
355          if (errno == EBUSY && timeout-- > 0) {
356             Dmsg2(100, "Device %s busy. ERR=%s\n", dev->dev_name, be.strerror());
357             bmicrosleep(1, 0);
358             continue;
359          }
360          dev->dev_errno = errno;
361          Mmsg2(&dev->errmsg, _("stored: unable to open device %s: ERR=%s\n"),
362                dev->dev_name, be.strerror());
363          /* Stop any open timer we set */
364          if (dev->tid) {
365             stop_thread_timer(dev->tid);
366             dev->tid = 0;
367          }
368          Emsg0(M_FATAL, 0, dev->errmsg);
369          break;
370       }
371       if (dev->fd >= 0) {
372          dev->dev_errno = 0;
373          dev->state |= ST_OPENED;
374          dev->use_count = 1;
375          update_pos_dev(dev);             /* update position */
376          set_os_device_parameters(dev);      /* do system dependent stuff */
377       }
378       /* Stop any open() timer we started */
379       if (dev->tid) {
380          stop_thread_timer(dev->tid);
381          dev->tid = 0;
382       }
383       Dmsg1(29, "open_dev: tape %d opened\n", dev->fd);
384    } else {
385       POOL_MEM archive_name(PM_FNAME);
386       struct stat filestat;
387       /*
388        * Handle opening of File Archive (not a tape)
389        */     
390       if (dev->part == 0) {
391          dev->file_size = 0;
392       }
393       dev->part_size = 0;
394       
395       /* if num_parts has not been set, but VolCatInfo is available, copy
396        * it from the VolCatInfo.VolCatParts */
397       if (dev->num_parts < dev->VolCatInfo.VolCatParts) {
398          dev->num_parts = dev->VolCatInfo.VolCatParts;
399       }
400       
401       if (VolName == NULL || *VolName == 0) {
402          Mmsg(dev->errmsg, _("Could not open file device %s. No Volume name given.\n"),
403             dev->dev_name);
404          return -1;
405       }
406       get_filename(dev, VolName, archive_name);
407
408       if (dev_cap(dev, CAP_REQMOUNT) && (dev->num_parts > 0)) {
409          if (mount_dev(dev, 1) < 0) {
410             Mmsg(dev->errmsg, _("Could not mount device %s.\n"),
411                  dev->dev_name);
412             Emsg0(M_FATAL, 0, dev->errmsg);
413             dev->fd = -1;
414             return dev->fd;
415          }
416       }
417             
418       Dmsg2(29, "open_dev: device is disk %s (mode:%d)\n", archive_name.c_str(), mode);
419       dev->openmode = mode;
420       
421       /* If we are not trying to access the last part, set mode to OPEN_READ_ONLY,
422        * as writing would be an error.
423        */
424       if (dev->part < dev->num_parts) {
425          mode = OPEN_READ_ONLY;
426       }
427       
428       if (mode == OPEN_READ_WRITE) {
429          dev->mode = O_CREAT | O_RDWR | O_BINARY;
430       } else if (mode == OPEN_READ_ONLY) {
431          dev->mode = O_RDONLY | O_BINARY;
432       } else if (mode == OPEN_WRITE_ONLY) {
433          dev->mode = O_WRONLY | O_BINARY;
434       } else {
435          Emsg0(M_ABORT, 0, _("Illegal mode given to open_dev.\n"));
436       }
437       /* If creating file, give 0640 permissions */
438       if ((dev->fd = open(archive_name.c_str(), dev->mode, 0640)) < 0) {
439          berrno be;
440          dev->dev_errno = errno;
441          Mmsg2(&dev->errmsg, _("Could not open: %s, ERR=%s\n"), archive_name.c_str(), be.strerror());
442          Emsg0(M_FATAL, 0, dev->errmsg);
443       } else {
444          dev->dev_errno = 0;
445          dev->state |= ST_OPENED;
446          dev->use_count = 1;
447          update_pos_dev(dev);                /* update position */
448          if (fstat(dev->fd, &filestat) < 0) {
449             berrno be;
450             dev->dev_errno = errno;
451             Mmsg2(&dev->errmsg, _("Could not open: %s, ERR=%s\n"), archive_name.c_str(), be.strerror());
452             Emsg0(M_FATAL, 0, dev->errmsg);
453          }
454          else {
455             dev->part_size = filestat.st_size;
456          }
457       }
458       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);
459       if ((dev->mode != OPEN_READ_ONLY) && ((dev->free_space_errno == 0) || (dev->num_parts == dev->part))) {
460          update_free_space_dev(dev);
461       }
462    }
463    return dev->fd;
464 }
465
466 /* (Un)mount the device */
467 int do_mount_dev(DEVICE* dev, int mount, int dotimeout) {
468    POOL_MEM ocmd(PM_FNAME);
469    POOLMEM* results;
470    results = get_pool_memory(PM_MESSAGE);
471    char* icmd;
472    int status, timeout;
473    
474    if (mount) {
475       icmd = dev->device->mount_command;
476    }
477    else {
478       icmd = dev->device->unmount_command;
479    }
480    
481    edit_device_codes_dev(dev, ocmd.c_str(), icmd);
482    
483    Dmsg2(29, "do_mount_dev: cmd=%s state=%d\n", ocmd.c_str(), dev->state & ST_MOUNTED);
484
485    if (dotimeout) {
486       /* Try at most 5 times to (un)mount the device. This should perhaps be configurable. */
487       timeout = 5;
488    }
489    else {
490       timeout = 0;
491    }
492    /* If busy retry each second */
493    while ((status = run_program_full_output(ocmd.c_str(), dev->max_open_wait/2, results)) != 0) {
494       if (--timeout > 0) {
495          Dmsg2(40, "Device %s cannot be (un)mounted. Retrying... ERR=%s\n", dev->dev_name, results);
496          /* Sometimes the device cannot be mounted because it is already mounted.
497           * Try to unmount it, then remount it */
498          if (mount) {
499             Dmsg1(40, "Trying to unmount the device %s...\n", dev->dev_name);
500             do_mount_dev(dev, 0, 0);
501          }
502          bmicrosleep(1, 0);
503          continue;
504       }
505       free_pool_memory(results);
506       Dmsg2(40, "Device %s cannot be mounted. ERR=%s\n", dev->dev_name, results);
507       return -1;
508    }
509    
510    if (mount) {
511      dev->state |= ST_MOUNTED;
512    }
513    else {
514      dev->state &= ~ST_MOUNTED;
515    }
516    free_pool_memory(results);
517    
518    Dmsg1(29, "do_mount_dev: end_state=%d\n", dev->state & ST_MOUNTED);
519    return 0;
520 }
521
522 /* Only for devices that requires mount.
523  * Try to find the volume name of the loaded device, and open the
524  * first part of this volume. 
525  *
526  * Returns 0 if read_dev_volume_label can now read the label,
527  * -1 if an error occured, and read_dev_volume_label_guess must abort with an IO_ERROR.
528  *
529  * To guess the device name, it lists all the files on the DVD, and searches for a 
530  * file which has a minimum size (500 bytes). If this file has a numeric extension,
531  * like part files, try to open the file which has no extension (e.g. the first
532  * part file).
533  * So, if the DVD does not contains a Bacula volume, a random file is opened,
534  * and no valid label could be read from this file.
535  *
536  * It is useful, so the operator can be told that a wrong volume is mounted, with
537  * the label name of the current volume. We can also check that the currently
538  * mounted disk is writable. (See also read_dev_volume_label_guess in label.c).
539  *
540  * Note that if the right volume is mounted, open_guess_name_dev returns the same
541  * result as an usual open_dev.
542  */
543 int open_guess_name_dev(DEVICE *dev) {
544    Dmsg1(29, "open_guess_name_dev: dev=%s\n", dev->dev_name);
545    POOL_MEM guessedname(PM_FNAME);
546    DIR* dp;
547    struct dirent *entry, *result;
548    struct stat statp;
549    int index;
550    int name_max;
551    
552    if (!dev_cap(dev, CAP_REQMOUNT)) {
553       Dmsg1(100, "open_guess_name_dev: device does not require mount, returning 0. dev=%s\n", dev->dev_name);
554       return 0;
555    }
556
557 #ifndef HAVE_DIRENT_H
558    Dmsg0(29, "open_guess_name_dev: readdir not available, cannot guess volume name\n");
559    return 0; 
560 #endif
561    
562    update_free_space_dev(dev);
563
564    if (mount_dev(dev, 1) < 0) {
565       /* If the device cannot be mounted, check if it is writable */
566       if (dev->free_space_errno >= 0) {
567          Dmsg1(100, "open_guess_name_dev: device cannot be mounted, but it seems to be writable, returning 0. dev=%s\n", dev->dev_name);
568          return 0;
569       }
570       else {
571          Dmsg1(100, "open_guess_name_dev: device cannot be mounted, and is not writable, returning 0. dev=%s\n", dev->dev_name);
572          /* read_dev_volume_label_guess must now check dev->free_space_errno to understand that the media is not writable. */
573          return 0;
574       }
575    }
576       
577    name_max = pathconf(".", _PC_NAME_MAX);
578    if (name_max < 1024) {
579       name_max = 1024;
580    }
581       
582    if (!(dp = opendir(dev->device->mount_point))) {
583       berrno be;
584       dev->dev_errno = errno;
585       Dmsg3(29, "open_guess_name_dev: failed to open dir %s (dev=%s), ERR=%s\n", dev->device->mount_point, dev->dev_name, be.strerror());
586       return -1;
587    }
588    
589    entry = (struct dirent *)malloc(sizeof(struct dirent) + name_max + 100);
590    while (1) {
591       if ((readdir_r(dp, entry, &result) != 0) || (result == NULL)) {
592          dev->dev_errno = ENOENT;
593          Dmsg2(29, "open_guess_name_dev: failed to find suitable file in dir %s (dev=%s)\n", dev->device->mount_point, dev->dev_name);
594          closedir(dp);
595          return -1;
596       }
597       
598       ASSERT(name_max+1 > (int)sizeof(struct dirent) + (int)NAMELEN(entry));
599       
600       if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
601          continue;
602       }
603       
604       pm_strcpy(guessedname, dev->device->mount_point);
605       if (guessedname.c_str()[strlen(guessedname.c_str())-1] != '/') {
606          pm_strcat(guessedname, "/");
607       }
608       pm_strcat(guessedname, entry->d_name);
609       
610       if (stat(guessedname.c_str(), &statp) < 0) {
611          berrno be;
612          Dmsg3(29, "open_guess_name_dev: failed to stat %s (dev=%s), ERR=%s\n",
613                guessedname.c_str(), dev->dev_name, be.strerror());
614          continue;
615       }
616       
617       if (!S_ISREG(statp.st_mode) || (statp.st_size < 500)) {
618          Dmsg2(100, "open_guess_name_dev: %s is not a regular file, or less than 500 bytes (dev=%s)\n", 
619                guessedname.c_str(), dev->dev_name);
620          continue;
621       }
622       
623       /* Ok, we found a good file, remove the part extension if possible. */
624       for (index = strlen(guessedname.c_str())-1; index >= 0; index--) {
625          if ((guessedname.c_str()[index] == '/') || 
626              (guessedname.c_str()[index] < '0') || 
627              (guessedname.c_str()[index] > '9')) {
628             break;
629          }
630          if (guessedname.c_str()[index] == '.') {
631             guessedname.c_str()[index] = '\0';
632             break;
633          }
634       }
635       
636       if ((stat(guessedname.c_str(), &statp) < 0) || (statp.st_size < 500)) {
637          /* The file with extension truncated does not exists or is too small, so use it with its extension. */
638          berrno be;
639          Dmsg3(100, "open_guess_name_dev: failed to stat %s (dev=%s), using the file with its extension, ERR=%s\n", 
640                guessedname.c_str(), dev->dev_name, be.strerror());
641          pm_strcpy(guessedname, dev->device->mount_point);
642          if (guessedname.c_str()[strlen(guessedname.c_str())-1] != '/') {
643             pm_strcat(guessedname, "/");
644          }
645          pm_strcat(guessedname, entry->d_name);
646          continue;
647       }
648       break;
649    }
650    
651    closedir(dp);
652    
653    if (dev->fd >= 0) {
654       close(dev->fd);
655    }
656      
657    if ((dev->fd = open(guessedname.c_str(), O_RDONLY | O_BINARY)) < 0) {
658       berrno be;
659       dev->dev_errno = errno;
660       Dmsg3(29, "open_guess_name_dev: failed to open %s (dev=%s), ERR=%s\n", 
661             guessedname.c_str(), dev->dev_name, be.strerror());
662       if (open_first_part(dev) < 0) {
663          berrno be;
664          dev->dev_errno = errno;
665          Mmsg1(&dev->errmsg, _("Could not open_first_part, ERR=%s\n"), be.strerror());
666          Emsg0(M_FATAL, 0, dev->errmsg);         
667       }
668       return -1;
669    }
670    dev->part_start = 0;
671    dev->part_size = statp.st_size;
672    dev->part = 0;
673    dev->state |= ST_OPENED;
674    dev->use_count = 1;
675    
676    Dmsg2(29, "open_guess_name_dev: %s opened (dev=%s)\n", guessedname.c_str(), dev->dev_name);
677    
678    return 0;
679 }
680
681 /* Mount the device.
682  * If timeout, wait until the mount command returns 0.
683  * If !timeout, try to mount the device only once.
684  */
685 int mount_dev(DEVICE* dev, int timeout) {
686    if (dev->state & ST_MOUNTED) {
687       Dmsg0(100, "mount_dev: Device already mounted\n");
688       return 0;
689    }
690    else {
691       return do_mount_dev(dev, 1, timeout);
692    }
693 }
694
695 /* Unmount the device
696  * If timeout, wait until the unmount command returns 0.
697  * If !timeout, try to unmount the device only once.
698  */
699 int unmount_dev(DEVICE* dev, int timeout) {
700    if (dev->state & ST_MOUNTED) {
701       return do_mount_dev(dev, 0, timeout);
702    }
703    else {
704       Dmsg0(100, "mount_dev: Device already unmounted\n");
705       return 0;
706    }
707 }
708
709 /* Update the free space on the device */
710 void update_free_space_dev(DEVICE* dev) {
711    POOL_MEM ocmd(PM_FNAME);
712    POOLMEM* results;
713    char* icmd;
714    int timeout;
715    char* statstr;
716    long long int free;
717    
718    icmd = dev->device->free_space_command;
719    
720    if (!icmd) {
721       dev->free_space = 0;
722       dev->free_space_errno = 0;
723       Dmsg2(29, "update_free_space_dev: free_space=%d, free_space_errno=%d (!icmd)\n", dev->free_space, dev->free_space_errno);
724       return;
725    }
726    
727    edit_device_codes_dev(dev, ocmd.c_str(), icmd);
728    
729    Dmsg1(29, "update_free_space_dev: cmd=%s\n", ocmd.c_str());
730
731    results = get_pool_memory(PM_MESSAGE);
732    
733    /* Try at most 3 times to get the free space on the device. This should perhaps be configurable. */
734    timeout = 3;
735    
736    while (1) {
737       if (run_program_full_output(ocmd.c_str(), dev->max_open_wait/2, results) == 0) {
738          Dmsg1(100, "Free space program run : %s\n", results);
739          /* We also need negatives values, so we can't use dev->free_space, which is unsigned */
740          free = strtoll(results, &statstr, 10);
741          if (results != statstr) { /* Something parsed */
742             if (free >= 0) {
743                dev->free_space = free;
744                dev->free_space_errno = 1;
745                Mmsg0(dev->errmsg, "");
746                break;
747             }
748             else {
749                dev->free_space_errno = free;
750                dev->free_space = 0;
751                if (*statstr == '\n') {
752                   statstr++;
753                }
754                if (statstr[strlen(statstr)-1] == '\n') {
755                   statstr[strlen(statstr)-1] = 0;
756                }
757                Mmsg1(dev->errmsg, "Error while getting free space (%s)", statstr);
758             }
759          }
760          else {
761             dev->free_space = 0;
762             dev->free_space_errno = -EPIPE;
763             Mmsg1(dev->errmsg, "Error while getting free space (output=%s)", results);
764          }
765       }
766       else {
767          dev->free_space = 0;
768          dev->free_space_errno = -EPIPE;
769          Mmsg1(dev->errmsg, "Cannot run free space command (%s)", results);
770       }
771       
772       if (--timeout > 0) {
773          Dmsg4(40, "Cannot get free space on device %s. free_space=%lld, free_space_errno=%d ERR=%s\n", dev->dev_name, 
774                dev->free_space, dev->free_space_errno, dev->errmsg);
775          bmicrosleep(1, 0);
776          continue;
777       }
778
779       dev->dev_errno = -dev->free_space_errno;
780       Dmsg4(40, "Cannot get free space on device %s. free_space=%lld, free_space_errno=%d ERR=%s\n",
781             dev->dev_name, dev->free_space, dev->free_space_errno, dev->errmsg);
782       free_pool_memory(results);
783       return;
784    }
785    
786    free_pool_memory(results);
787    
788    Dmsg2(29, "update_free_space_dev: free_space=%lld, free_space_errno=%d\n", dev->free_space, dev->free_space_errno);
789 }
790
791 int write_part(DEVICE *dev) {
792    Dmsg1(29, "write_part: device is %s\n", dev->dev_name);
793    
794    if (unmount_dev(dev, 1) < 0) {
795       Dmsg0(29, "write_part: unable to unmount the device\n");
796    }
797    
798    POOL_MEM ocmd(PM_FNAME);
799    POOLMEM *results;
800    results = get_pool_memory(PM_MESSAGE);
801    char* icmd;
802    int status;
803    int timeout;
804    
805    icmd = dev->device->write_part_command;
806    
807    edit_device_codes_dev(dev, ocmd.c_str(), icmd);
808       
809    /* Wait at most the time a maximum size part is written in DVD 0.5x speed
810     * FIXME: Minimum speed should be in device configuration 
811     */
812    timeout = dev->max_open_wait + (dev->max_part_size/(1350*1024/2));
813    
814    Dmsg2(29, "write_part: cmd=%s timeout=%d\n", ocmd.c_str(), timeout);
815       
816    status = run_program_full_output(ocmd.c_str(), timeout, results);
817    if (status != 0) {
818       Mmsg1(dev->errmsg, "Error while writing current part to the DVD: %s", results);
819       dev->dev_errno = EIO;
820       free_pool_memory(results);
821       return -1;
822    }
823    else {
824       Dmsg1(29, "write_part: command output=%s\n", results);
825       POOL_MEM archive_name(PM_FNAME);
826       get_filename(dev, dev->VolCatInfo.VolCatName, archive_name);
827       unlink(archive_name.c_str());
828       free_pool_memory(results);
829       return 0;
830    }
831 }
832
833 /* Open the next part file.
834  *  - Close the fd
835  *  - Increment part number 
836  *  - Reopen the device
837  */
838 int open_next_part(DEVICE *dev) {
839    int state;
840       
841    Dmsg3(29, "open_next_part %s %s %d\n", dev->dev_name, dev->VolCatInfo.VolCatName, dev->openmode);
842    /* When appending, do not open a new part if the current is empty */
843    if ((dev->state & ST_APPEND) && (dev->part == dev->num_parts) && (dev->part_size == 0)) {
844       Dmsg0(29, "open_next_part exited immediatly (dev->part_size == 0).\n");
845       return dev->fd;
846    }
847    
848    if (dev->fd >= 0) {
849       close(dev->fd);
850    }
851    
852    dev->fd = -1;
853    
854    state = dev->state;
855    dev->state &= ~ST_OPENED;
856    
857    if ((dev_cap(dev, CAP_REQMOUNT)) && (dev->part == dev->num_parts) && (dev->state & ST_APPEND)) {
858       if (write_part(dev) < 0) {
859          return -1;
860       }
861    }
862      
863    dev->part_start += dev->part_size;
864    dev->part++;
865    
866    if ((dev->num_parts < dev->part) && (dev->state & ST_APPEND)) {
867       dev->num_parts = dev->part;
868       
869       /* Check that the next part file does not exists.
870        * If it does, move it away... */
871       POOL_MEM archive_name(PM_FNAME);
872       POOL_MEM archive_bkp_name(PM_FNAME);
873       struct stat buf;
874       
875       get_filename(dev, dev->VolCatInfo.VolCatName, archive_name);
876       
877       /* Check if the next part exists. */
878       if ((stat(archive_name.c_str(), &buf) == 0) || (errno != ENOENT)) {
879          Dmsg1(29, "open_next_part %s is in the way, moving it away...\n", archive_name.c_str());
880          pm_strcpy(archive_bkp_name, archive_name.c_str());
881          pm_strcat(archive_bkp_name, ".bak");
882          unlink(archive_bkp_name.c_str()); 
883          
884          /* First try to rename it */
885          if (rename(archive_name.c_str(), archive_bkp_name.c_str()) < 0) {
886             berrno be;
887             Dmsg3(29, "open_next_part can't rename %s to %s, ERR=%s\n", 
888                   archive_name.c_str(), archive_bkp_name.c_str(), be.strerror());
889             /* Then try to unlink it */
890             if (unlink(archive_name.c_str()) < 0) {
891                berrno be;
892                dev->dev_errno = errno;
893                Mmsg2(&dev->errmsg, _("open_next_part can't unlink existing part %s, ERR=%s\n"), 
894                       archive_name.c_str(), be.strerror());
895                Emsg0(M_FATAL, 0, dev->errmsg);
896                return -1;
897             }
898          }
899       }
900    }
901    
902    if (open_dev(dev, dev->VolCatInfo.VolCatName, dev->openmode) < 0) {
903       return -1;
904    }
905    else {
906       dev->state = state;
907       return dev->fd;
908    }
909 }
910
911 /* Open the first part file.
912  *  - Close the fd
913  *  - Reopen the device
914  */
915 int open_first_part(DEVICE *dev) {
916    int state;
917       
918    Dmsg3(29, "open_first_part %s %s %d\n", dev->dev_name, dev->VolCatInfo.VolCatName, dev->openmode);
919    if (dev->fd >= 0) {
920       close(dev->fd);
921    }
922    
923    dev->fd = -1;
924    state = dev->state;
925    dev->state &= ~ST_OPENED;
926    
927    dev->part_start = 0;
928    dev->part = 0;
929    
930    if (open_dev(dev, dev->VolCatInfo.VolCatName, dev->openmode)) {
931       dev->state = state;
932       return dev->fd;
933    }
934    else {
935       return 0;
936    }
937 }
938
939 #ifdef debug_tracing
940 #undef rewind_dev
941 bool _rewind_dev(char *file, int line, DEVICE *dev)
942 {
943    Dmsg2(100, "rewind_dev called from %s:%d\n", file, line);
944    return rewind_dev(dev);
945 }
946 #endif
947
948 /* Protected version of lseek, which opens the right part if necessary */
949 off_t lseek_dev(DEVICE *dev, off_t offset, int whence) {
950    int pos, openmode;
951    
952    if (dev->num_parts == 0) { /* If there is only one part, simply call lseek. */
953       return lseek(dev->fd, offset, whence);
954    }
955       
956    switch(whence) {
957       case SEEK_SET:
958          Dmsg1(100, "lseek_dev SEEK_SET called %d\n", offset);
959          if ((uint64_t)offset >= dev->part_start) {
960             if ((uint64_t)(offset - dev->part_start) < dev->part_size) {
961                /* We are staying in the current part, just seek */
962                if ((pos = lseek(dev->fd, (off_t)(offset-dev->part_start), SEEK_SET)) < 0) {
963                   return pos;   
964                }
965                else {
966                   return pos + dev->part_start;
967                }
968             }
969             else {
970                /* Load next part, and start again */
971                if (open_next_part(dev) < 0) {
972                   Dmsg0(100, "lseek_dev failed while trying to open the next part\n");
973                   return -1;
974                }
975                return lseek_dev(dev, offset, SEEK_SET);
976             }
977          }
978          else {
979             /* pos < dev->part_start :
980              * We need to access a previous part, 
981              * so just load the first one, and seek again
982              * until the right one is loaded */
983             if (open_first_part(dev) < 0) {
984                Dmsg0(100, "lseek_dev failed while trying to open the first part\n");
985                return -1;
986             }
987             return lseek_dev(dev, offset, SEEK_SET);
988          }
989          break;
990       case SEEK_CUR:
991          Dmsg1(100, "lseek_dev SEEK_CUR called %d\n", offset);
992          if ((pos = lseek(dev->fd, (off_t)0, SEEK_CUR)) < 0) {
993             return pos;   
994          }
995          pos += dev->part_start;
996          if (offset == 0) {
997             return pos;
998          }
999          else { /* Not used in Bacula, but should work */
1000             return lseek_dev(dev, pos, SEEK_SET);
1001          }
1002          break;
1003       case SEEK_END:
1004          Dmsg1(100, "lseek_dev SEEK_END called %d\n", offset);
1005          if (offset > 0) { /* Not used by bacula */
1006             Dmsg1(100, "lseek_dev SEEK_END called with an invalid offset %d\n", offset);
1007             errno = EINVAL;
1008             return -1;
1009          }
1010          
1011          if (dev->part == dev->num_parts) { /* The right part is already loaded */
1012             if ((pos = lseek(dev->fd, (off_t)0, SEEK_END)) < 0) {
1013                return pos;   
1014             }
1015             else {
1016                return pos + dev->part_start;
1017             }
1018          }
1019          else {
1020             /* Load the first part, then load the next until we reach the last one.
1021              * This is the only way to be sure we compute the right file address. */
1022             /* Save previous openmode, and open all but last part read-only (useful for DVDs) */
1023             openmode = dev->openmode;
1024             dev->openmode = OPEN_READ_ONLY;
1025             
1026             /* Works because num_parts > 0. */
1027             if (open_first_part(dev) < 0) {
1028                Dmsg0(100, "lseek_dev failed while trying to open the first part\n");
1029                return -1;
1030             }
1031             while (dev->part < (dev->num_parts-1)) {
1032                if (open_next_part(dev) < 0) {
1033                   Dmsg0(100, "lseek_dev failed while trying to open the next part\n");
1034                   return -1;
1035                }
1036             }
1037             dev->openmode = openmode;
1038             if (open_next_part(dev) < 0) {
1039                Dmsg0(100, "lseek_dev failed while trying to open the next part\n");
1040                return -1;
1041             }
1042             return lseek_dev(dev, 0, SEEK_END);
1043          }
1044          break;
1045       default:
1046          errno = EINVAL;
1047          return -1;
1048    }
1049 }
1050
1051 /*
1052  * Rewind the device.
1053  *  Returns: true  on success
1054  *           false on failure
1055  */
1056 bool rewind_dev(DEVICE *dev)
1057 {
1058    struct mtop mt_com;
1059    unsigned int i;
1060
1061    Dmsg1(29, "rewind_dev %s\n", dev->dev_name);
1062    if (dev->fd < 0) {
1063       dev->dev_errno = EBADF;
1064       Mmsg1(&dev->errmsg, _("Bad call to rewind_dev. Device %s not open\n"),
1065             dev->dev_name);
1066       Emsg0(M_ABORT, 0, dev->errmsg);
1067       return false;
1068    }
1069    dev->state &= ~(ST_EOT|ST_EOF|ST_WEOT);  /* remove EOF/EOT flags */
1070    dev->block_num = dev->file = 0;
1071    dev->file_size = 0;
1072    dev->file_addr = 0;
1073    if (dev->state & ST_TAPE) {
1074       mt_com.mt_op = MTREW;
1075       mt_com.mt_count = 1;
1076       /* If we get an I/O error on rewind, it is probably because
1077        * the drive is actually busy. We loop for (about 5 minutes)
1078        * retrying every 5 seconds.
1079        */
1080       for (i=dev->max_rewind_wait; ; i -= 5) {
1081          if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
1082             berrno be;
1083             clrerror_dev(dev, MTREW);
1084             if (i == dev->max_rewind_wait) {
1085                Dmsg1(200, "Rewind error, %s. retrying ...\n", be.strerror());
1086             }
1087             if (dev->dev_errno == EIO && i > 0) {
1088                Dmsg0(200, "Sleeping 5 seconds.\n");
1089                bmicrosleep(5, 0);
1090                continue;
1091             }
1092             Mmsg2(&dev->errmsg, _("Rewind error on %s. ERR=%s.\n"),
1093                dev->dev_name, be.strerror());
1094             return false;
1095          }
1096          break;
1097       }
1098    } else if (dev->state & ST_FILE) {      
1099       if (lseek_dev(dev, (off_t)0, SEEK_SET) < 0) {
1100          berrno be;
1101          dev->dev_errno = errno;
1102          Mmsg2(&dev->errmsg, _("lseek_dev error on %s. ERR=%s.\n"),
1103             dev->dev_name, be.strerror());
1104          return false;
1105       }
1106    }
1107    return true;
1108 }
1109
1110 /*
1111  * Position device to end of medium (end of data)
1112  *  Returns: 1 on succes
1113  *           0 on error
1114  */
1115 int
1116 eod_dev(DEVICE *dev)
1117 {
1118    struct mtop mt_com;
1119    struct mtget mt_stat;
1120    int stat = 0;
1121    off_t pos;
1122
1123    Dmsg0(29, "eod_dev\n");
1124    if (dev->state & ST_EOT) {
1125       return 1;
1126    }
1127    dev->state &= ~(ST_EOF);  /* remove EOF flags */
1128    dev->block_num = dev->file = 0;
1129    dev->file_size = 0;
1130    dev->file_addr = 0;
1131    if (dev->state & (ST_FIFO | ST_PROG)) {
1132       return 1;
1133    }
1134    if (!(dev->state & ST_TAPE)) {
1135       pos = lseek_dev(dev, (off_t)0, SEEK_END);
1136 //    Dmsg1(100, "====== Seek to %lld\n", pos);
1137       if (pos >= 0) {
1138          update_pos_dev(dev);
1139          dev->state |= ST_EOT;
1140          return 1;
1141       }
1142       dev->dev_errno = errno;
1143       berrno be;
1144       Mmsg2(&dev->errmsg, _("lseek_dev error on %s. ERR=%s.\n"),
1145              dev->dev_name, be.strerror());
1146       return 0;
1147    }
1148 #ifdef MTEOM
1149
1150    if (dev_cap(dev, CAP_MTIOCGET) && dev_cap(dev, CAP_FASTFSF) && !dev_cap(dev, CAP_EOM)) {
1151       struct mtget mt_stat;
1152       Dmsg0(100,"Using FAST FSF for EOM\n");
1153       if (ioctl(dev->fd, MTIOCGET, (char *)&mt_stat) == 0 && mt_stat.mt_fileno <= 0) {
1154         if (!rewind_dev(dev)) {
1155           return 0;
1156         }
1157       }
1158       mt_com.mt_op = MTFSF;
1159       /*
1160        * ***FIXME*** fix code to handle case that INT16_MAX is
1161        *   not large enough.
1162        */
1163       mt_com.mt_count = INT16_MAX;    /* use big positive number */
1164       if (mt_com.mt_count < 0) {
1165          mt_com.mt_count = INT16_MAX; /* brain damaged system */
1166       }
1167    }
1168
1169    if (dev_cap(dev, CAP_MTIOCGET) && (dev_cap(dev, CAP_FASTFSF) || dev_cap(dev, CAP_EOM))) {
1170       if (dev_cap(dev, CAP_EOM)) {
1171          Dmsg0(100,"Using EOM for EOM\n");
1172          mt_com.mt_op = MTEOM;
1173          mt_com.mt_count = 1;
1174       }
1175
1176       if ((stat=ioctl(dev->fd, MTIOCTOP, (char *)&mt_com)) < 0) {
1177          berrno be;
1178          clrerror_dev(dev, mt_com.mt_op);
1179          Dmsg1(50, "ioctl error: %s\n", be.strerror());
1180          update_pos_dev(dev);
1181          Mmsg2(&dev->errmsg, _("ioctl MTEOM error on %s. ERR=%s.\n"),
1182             dev->dev_name, be.strerror());
1183          return 0;
1184       }
1185
1186       if (ioctl(dev->fd, MTIOCGET, (char *)&mt_stat) < 0) {
1187          berrno be;
1188          clrerror_dev(dev, -1);
1189          Mmsg2(&dev->errmsg, _("ioctl MTIOCGET error on %s. ERR=%s.\n"),
1190             dev->dev_name, be.strerror());
1191          return 0;
1192       }
1193       Dmsg2(100, "EOD file=%d block=%d\n", mt_stat.mt_fileno, mt_stat.mt_blkno);
1194       dev->file = mt_stat.mt_fileno;
1195
1196    /*
1197     * Rewind then use FSF until EOT reached
1198     */
1199    } else {
1200 #else
1201    {
1202 #endif
1203       if (!rewind_dev(dev)) {
1204          return 0;
1205       }
1206       /*
1207        * Move file by file to the end of the tape
1208        */
1209       int file_num;
1210       for (file_num=dev->file; !(dev->state & ST_EOT); file_num++) {
1211          Dmsg0(200, "eod_dev: doing fsf 1\n");
1212          if (!fsf_dev(dev, 1)) {
1213             Dmsg0(200, "fsf_dev error.\n");
1214             return 0;
1215          }
1216          /*
1217           * Avoid infinite loop. ***FIXME*** possibly add code
1218           *   to set EOD or to turn off CAP_FASTFSF if on.
1219           */
1220          if (file_num == (int)dev->file) {
1221             struct mtget mt_stat;
1222             Dmsg1(100, "fsf_dev did not advance from file %d\n", file_num);
1223             if (dev_cap(dev, CAP_MTIOCGET) && ioctl(dev->fd, MTIOCGET, (char *)&mt_stat) == 0 &&
1224                       mt_stat.mt_fileno >= 0) {
1225                Dmsg2(100, "Adjust file from %d to %d\n", dev->file , mt_stat.mt_fileno);
1226                dev->file = mt_stat.mt_fileno;
1227             }
1228             stat = 0;
1229             break;                    /* we are not progressing, bail out */
1230          }
1231       }
1232    }
1233    /*
1234     * Some drivers leave us after second EOF when doing
1235     * MTEOM, so we must backup so that appending overwrites
1236     * the second EOF.
1237     */
1238    if (dev_cap(dev, CAP_BSFATEOM)) {
1239       struct mtget mt_stat;
1240       /* Backup over EOF */
1241       stat = bsf_dev(dev, 1);
1242       /* If BSF worked and fileno is known (not -1), set file */
1243       if (dev_cap(dev, CAP_MTIOCGET) && ioctl(dev->fd, MTIOCGET, (char *)&mt_stat) == 0 && mt_stat.mt_fileno >= 0) {
1244          Dmsg2(100, "BSFATEOF adjust file from %d to %d\n", dev->file , mt_stat.mt_fileno);
1245          dev->file = mt_stat.mt_fileno;
1246       } else {
1247          dev->file++;                 /* wing it -- not correct on all OSes */
1248       }
1249    } else {
1250       update_pos_dev(dev);                   /* update position */
1251       stat = 1;
1252    }
1253    Dmsg1(200, "EOD dev->file=%d\n", dev->file);
1254    return stat;
1255 }
1256
1257 /*
1258  * Set the position of the device -- only for files
1259  *   For other devices, there is no generic way to do it.
1260  *  Returns: true  on succes
1261  *           false on error
1262  */
1263 bool update_pos_dev(DEVICE *dev)
1264 {
1265    off_t pos;
1266    bool ok = true;
1267
1268    if (dev->fd < 0) {
1269       dev->dev_errno = EBADF;
1270       Mmsg0(&dev->errmsg, _("Bad device call. Archive not open\n"));
1271       Emsg0(M_FATAL, 0, dev->errmsg);
1272       return false;
1273    }
1274
1275    /* Find out where we are */
1276    if (dev->state & ST_FILE) {
1277       dev->file = 0;
1278       dev->file_addr = 0;
1279       pos = lseek_dev(dev, (off_t)0, SEEK_CUR);
1280       if (pos < 0) {
1281          berrno be;
1282          dev->dev_errno = errno;
1283          Pmsg1(000, "Seek error: ERR=%s\n", be.strerror());
1284          Mmsg2(&dev->errmsg, _("lseek_dev error on %s. ERR=%s.\n"),
1285             dev->dev_name, be.strerror());
1286          ok = false;
1287       } else {
1288          dev->file_addr = pos;
1289       }
1290    }
1291    return ok;
1292 }
1293
1294
1295 /*
1296  * Return the status of the device.  This was meant
1297  * to be a generic routine. Unfortunately, it doesn't
1298  * seem possible (at least I do not know how to do it
1299  * currently), which means that for the moment, this
1300  * routine has very little value.
1301  *
1302  *   Returns: status
1303  */
1304 uint32_t status_dev(DEVICE *dev)
1305 {
1306    struct mtget mt_stat;
1307    uint32_t stat = 0;
1308
1309    if (dev->state & (ST_EOT | ST_WEOT)) {
1310       stat |= BMT_EOD;
1311       Dmsg0(-20, " EOD");
1312    }
1313    if (dev->state & ST_EOF) {
1314       stat |= BMT_EOF;
1315       Dmsg0(-20, " EOF");
1316    }
1317    if (dev->state & ST_TAPE) {
1318       stat |= BMT_TAPE;
1319       Dmsg0(-20," Bacula status:");
1320       Dmsg2(-20," file=%d block=%d\n", dev->file, dev->block_num);
1321       if (ioctl(dev->fd, MTIOCGET, (char *)&mt_stat) < 0) {
1322          berrno be;
1323          dev->dev_errno = errno;
1324          Mmsg2(&dev->errmsg, _("ioctl MTIOCGET error on %s. ERR=%s.\n"),
1325             dev->dev_name, be.strerror());
1326          return 0;
1327       }
1328       Dmsg0(-20, " Device status:");
1329
1330 #if defined(HAVE_LINUX_OS)
1331       if (GMT_EOF(mt_stat.mt_gstat)) {
1332          stat |= BMT_EOF;
1333          Dmsg0(-20, " EOF");
1334       }
1335       if (GMT_BOT(mt_stat.mt_gstat)) {
1336          stat |= BMT_BOT;
1337          Dmsg0(-20, " BOT");
1338       }
1339       if (GMT_EOT(mt_stat.mt_gstat)) {
1340          stat |= BMT_EOT;
1341          Dmsg0(-20, " EOT");
1342       }
1343       if (GMT_SM(mt_stat.mt_gstat)) {
1344          stat |= BMT_SM;
1345          Dmsg0(-20, " SM");
1346       }
1347       if (GMT_EOD(mt_stat.mt_gstat)) {
1348          stat |= BMT_EOD;
1349          Dmsg0(-20, " EOD");
1350       }
1351       if (GMT_WR_PROT(mt_stat.mt_gstat)) {
1352          stat |= BMT_WR_PROT;
1353          Dmsg0(-20, " WR_PROT");
1354       }
1355       if (GMT_ONLINE(mt_stat.mt_gstat)) {
1356          stat |= BMT_ONLINE;
1357          Dmsg0(-20, " ONLINE");
1358       }
1359       if (GMT_DR_OPEN(mt_stat.mt_gstat)) {
1360          stat |= BMT_DR_OPEN;
1361          Dmsg0(-20, " DR_OPEN");
1362       }
1363       if (GMT_IM_REP_EN(mt_stat.mt_gstat)) {
1364          stat |= BMT_IM_REP_EN;
1365          Dmsg0(-20, " IM_REP_EN");
1366       }
1367 #endif /* !SunOS && !OSF */
1368       if (dev_cap(dev, CAP_MTIOCGET)) {
1369          Dmsg2(-20, " file=%d block=%d\n", mt_stat.mt_fileno, mt_stat.mt_blkno);
1370       } else {
1371          Dmsg2(-20, " file=%d block=%d\n", -1, -1);
1372       }
1373    } else {
1374       stat |= BMT_ONLINE | BMT_BOT;
1375    }
1376    return stat;
1377 }
1378
1379
1380 /*
1381  * Load medium in device
1382  *  Returns: true  on success
1383  *           false on failure
1384  */
1385 bool load_dev(DEVICE *dev)
1386 {
1387 #ifdef MTLOAD
1388    struct mtop mt_com;
1389 #endif
1390
1391    if (dev->fd < 0) {
1392       dev->dev_errno = EBADF;
1393       Mmsg0(&dev->errmsg, _("Bad call to load_dev. Archive not open\n"));
1394       Emsg0(M_FATAL, 0, dev->errmsg);
1395       return false;
1396    }
1397    if (!(dev->state & ST_TAPE)) {
1398       return true;
1399    }
1400 #ifndef MTLOAD
1401    Dmsg0(200, "stored: MTLOAD command not available\n");
1402    berrno be;
1403    dev->dev_errno = ENOTTY;           /* function not available */
1404    Mmsg2(&dev->errmsg, _("ioctl MTLOAD error on %s. ERR=%s.\n"),
1405          dev->dev_name, be.strerror());
1406    return false;
1407 #else
1408
1409    dev->block_num = dev->file = 0;
1410    dev->file_size = 0;
1411    dev->file_addr = 0;
1412    mt_com.mt_op = MTLOAD;
1413    mt_com.mt_count = 1;
1414    if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
1415       berrno be;
1416       dev->dev_errno = errno;
1417       Mmsg2(&dev->errmsg, _("ioctl MTLOAD error on %s. ERR=%s.\n"),
1418          dev->dev_name, be.strerror());
1419       return false;
1420    }
1421    return true;
1422 #endif
1423 }
1424
1425 /*
1426  * Rewind device and put it offline
1427  *  Returns: true  on success
1428  *           false on failure
1429  */
1430 bool offline_dev(DEVICE *dev)
1431 {
1432    struct mtop mt_com;
1433
1434    if (dev->fd < 0) {
1435       dev->dev_errno = EBADF;
1436       Mmsg0(&dev->errmsg, _("Bad call to offline_dev. Archive not open\n"));
1437       Emsg0(M_FATAL, 0, dev->errmsg);
1438       return false;
1439    }
1440    if (!(dev->state & ST_TAPE)) {
1441       return true;
1442    }
1443
1444    dev->state &= ~(ST_APPEND|ST_READ|ST_EOT|ST_EOF|ST_WEOT);  /* remove EOF/EOT flags */
1445    dev->block_num = dev->file = 0;
1446    dev->file_size = 0;
1447    dev->file_addr = 0;
1448    dev->part = 0;
1449 #ifdef MTUNLOCK
1450    mt_com.mt_op = MTUNLOCK;
1451    mt_com.mt_count = 1;
1452    ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
1453 #endif
1454    mt_com.mt_op = MTOFFL;
1455    mt_com.mt_count = 1;
1456    if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
1457       berrno be;
1458       dev->dev_errno = errno;
1459       Mmsg2(&dev->errmsg, _("ioctl MTOFFL error on %s. ERR=%s.\n"),
1460          dev->dev_name, be.strerror());
1461       return false;
1462    }
1463    Dmsg1(100, "Offlined device %s\n", dev->dev_name);
1464    return true;
1465 }
1466
1467 bool offline_or_rewind_dev(DEVICE *dev)
1468 {
1469    if (dev->fd < 0) {
1470       return false;
1471    }
1472    if (dev_cap(dev, CAP_OFFLINEUNMOUNT)) {
1473       return offline_dev(dev);
1474    } else {
1475    /*
1476     * Note, this rewind probably should not be here (it wasn't
1477     *  in prior versions of Bacula), but on FreeBSD, this is
1478     *  needed in the case the tape was "frozen" due to an error
1479     *  such as backspacing after writing and EOF. If it is not
1480     *  done, all future references to the drive get and I/O error.
1481     */
1482       clrerror_dev(dev, MTREW);
1483       return rewind_dev(dev);
1484    }
1485 }
1486
1487 /*
1488  * Foward space a file
1489  *   Returns: true  on success
1490  *            false on failure
1491  */
1492 bool
1493 fsf_dev(DEVICE *dev, int num)
1494 {
1495    struct mtget mt_stat;
1496    struct mtop mt_com;
1497    int stat = 0;
1498
1499    if (dev->fd < 0) {
1500       dev->dev_errno = EBADF;
1501       Mmsg0(&dev->errmsg, _("Bad call to fsf_dev. Archive not open\n"));
1502       Emsg0(M_FATAL, 0, dev->errmsg);
1503       return false;
1504    }
1505
1506    if (!(dev->state & ST_TAPE)) {
1507       return true;
1508    }
1509    if (dev->state & ST_EOT) {
1510       dev->dev_errno = 0;
1511       Mmsg1(dev->errmsg, _("Device %s at End of Tape.\n"), dev->dev_name);
1512       return false;
1513    }
1514    if (dev->state & ST_EOF) {
1515       Dmsg0(200, "ST_EOF set on entry to FSF\n");
1516    }
1517
1518    Dmsg0(100, "fsf_dev\n");
1519    dev->block_num = 0;
1520    /*
1521     * If Fast forward space file is set, then we
1522     *  use MTFSF to forward space and MTIOCGET
1523     *  to get the file position. We assume that
1524     *  the SCSI driver will ensure that we do not
1525     *  forward space past the end of the medium.
1526     */
1527    if (dev_cap(dev, CAP_FSF) && dev_cap(dev, CAP_MTIOCGET) && dev_cap(dev, CAP_FASTFSF)) {
1528       mt_com.mt_op = MTFSF;
1529       mt_com.mt_count = num;
1530       stat = ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
1531       if (stat < 0 || ioctl(dev->fd, MTIOCGET, (char *)&mt_stat) < 0) {
1532          berrno be;
1533          dev->state |= ST_EOT;
1534          Dmsg0(200, "Set ST_EOT\n");
1535          clrerror_dev(dev, MTFSF);
1536          Mmsg2(dev->errmsg, _("ioctl MTFSF error on %s. ERR=%s.\n"),
1537             dev->dev_name, be.strerror());
1538          Dmsg1(200, "%s", dev->errmsg);
1539          return false;
1540       }
1541       Dmsg2(200, "fsf file=%d block=%d\n", mt_stat.mt_fileno, mt_stat.mt_blkno);
1542       dev->file = mt_stat.mt_fileno;
1543       dev->state |= ST_EOF;     /* just read EOF */
1544       dev->file_addr = 0;
1545       dev->file_size = 0;
1546       return true;
1547
1548    /*
1549     * Here if CAP_FSF is set, and virtually all drives
1550     *  these days support it, we read a record, then forward
1551     *  space one file. Using this procedure, which is slow,
1552     *  is the only way we can be sure that we don't read
1553     *  two consecutive EOF marks, which means End of Data.
1554     */
1555    } else if (dev_cap(dev, CAP_FSF)) {
1556       POOLMEM *rbuf;
1557       int rbuf_len;
1558       Dmsg0(200, "FSF has cap_fsf\n");
1559       if (dev->max_block_size == 0) {
1560          rbuf_len = DEFAULT_BLOCK_SIZE;
1561       } else {
1562          rbuf_len = dev->max_block_size;
1563       }
1564       rbuf = get_memory(rbuf_len);
1565       mt_com.mt_op = MTFSF;
1566       mt_com.mt_count = 1;
1567       while (num-- && !(dev->state & ST_EOT)) {
1568          Dmsg0(100, "Doing read before fsf\n");
1569          if ((stat = read(dev->fd, (char *)rbuf, rbuf_len)) < 0) {
1570             if (errno == ENOMEM) {     /* tape record exceeds buf len */
1571                stat = rbuf_len;        /* This is OK */
1572             } else {
1573                berrno be;
1574                dev->state |= ST_EOT;
1575                clrerror_dev(dev, -1);
1576                Dmsg2(100, "Set ST_EOT read errno=%d. ERR=%s\n", dev->dev_errno,
1577                   be.strerror());
1578                Mmsg2(dev->errmsg, _("read error on %s. ERR=%s.\n"),
1579                   dev->dev_name, be.strerror());
1580                Dmsg1(100, "%s", dev->errmsg);
1581                break;
1582             }
1583          }
1584          if (stat == 0) {                /* EOF */
1585             update_pos_dev(dev);
1586             Dmsg1(100, "End of File mark from read. File=%d\n", dev->file+1);
1587             /* Two reads of zero means end of tape */
1588             if (dev->state & ST_EOF) {
1589                dev->state |= ST_EOT;
1590                Dmsg0(100, "Set ST_EOT\n");
1591                break;
1592             } else {
1593                dev->state |= ST_EOF;
1594                dev->file++;
1595                dev->file_addr = 0;
1596                dev->file_size = 0;
1597                continue;
1598             }
1599          } else {                        /* Got data */
1600             dev->state &= ~(ST_EOF|ST_EOT);
1601          }
1602
1603          Dmsg0(100, "Doing MTFSF\n");
1604          stat = ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
1605          if (stat < 0) {                 /* error => EOT */
1606             berrno be;
1607             dev->state |= ST_EOT;
1608             Dmsg0(100, "Set ST_EOT\n");
1609             clrerror_dev(dev, MTFSF);
1610             Mmsg2(&dev->errmsg, _("ioctl MTFSF error on %s. ERR=%s.\n"),
1611                dev->dev_name, be.strerror());
1612             Dmsg0(100, "Got < 0 for MTFSF\n");
1613             Dmsg1(100, "%s", dev->errmsg);
1614          } else {
1615             dev->state |= ST_EOF;     /* just read EOF */
1616             dev->file++;
1617             dev->file_addr = 0;
1618             dev->file_size = 0;
1619          }
1620       }
1621       free_memory(rbuf);
1622
1623    /*
1624     * No FSF, so use FSR to simulate it
1625     */
1626    } else {
1627       Dmsg0(200, "Doing FSR for FSF\n");
1628       while (num-- && !(dev->state & ST_EOT)) {
1629          fsr_dev(dev, INT32_MAX);    /* returns -1 on EOF or EOT */
1630       }
1631       if (dev->state & ST_EOT) {
1632          dev->dev_errno = 0;
1633          Mmsg1(dev->errmsg, _("Device %s at End of Tape.\n"), dev->dev_name);
1634          stat = -1;
1635       } else {
1636          stat = 0;
1637       }
1638    }
1639    update_pos_dev(dev);
1640    Dmsg1(200, "Return %d from FSF\n", stat);
1641    if (dev->state & ST_EOF)
1642       Dmsg0(200, "ST_EOF set on exit FSF\n");
1643    if (dev->state & ST_EOT)
1644       Dmsg0(200, "ST_EOT set on exit FSF\n");
1645    Dmsg1(200, "Return from FSF file=%d\n", dev->file);
1646    return stat == 0;
1647 }
1648
1649 /*
1650  * Backward space a file
1651  *  Returns: false on failure
1652  *           true  on success
1653  */
1654 bool
1655 bsf_dev(DEVICE *dev, int num)
1656 {
1657    struct mtop mt_com;
1658    int stat;
1659
1660    if (dev->fd < 0) {
1661       dev->dev_errno = EBADF;
1662       Mmsg0(dev->errmsg, _("Bad call to bsf_dev. Archive device not open\n"));
1663       Emsg0(M_FATAL, 0, dev->errmsg);
1664       return false;
1665    }
1666
1667    if (!(dev_state(dev, ST_TAPE))) {
1668       Mmsg1(dev->errmsg, _("Device %s cannot BSF because it is not a tape.\n"),
1669          dev->dev_name);
1670       return false;
1671    }
1672    Dmsg0(29, "bsf_dev\n");
1673    dev->state &= ~(ST_EOT|ST_EOF);
1674    dev->file -= num;
1675    dev->file_addr = 0;
1676    dev->file_size = 0;
1677    mt_com.mt_op = MTBSF;
1678    mt_com.mt_count = num;
1679    stat = ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
1680    if (stat < 0) {
1681       berrno be;
1682       clrerror_dev(dev, MTBSF);
1683       Mmsg2(dev->errmsg, _("ioctl MTBSF error on %s. ERR=%s.\n"),
1684          dev->dev_name, be.strerror());
1685    }
1686    update_pos_dev(dev);
1687    return stat == 0;
1688 }
1689
1690
1691 /*
1692  * Foward space a record
1693  *  Returns: false on failure
1694  *           true  on success
1695  */
1696 bool
1697 fsr_dev(DEVICE *dev, int num)
1698 {
1699    struct mtop mt_com;
1700    int stat;
1701
1702    if (dev->fd < 0) {
1703       dev->dev_errno = EBADF;
1704       Mmsg0(dev->errmsg, _("Bad call to fsr_dev. Archive not open\n"));
1705       Emsg0(M_FATAL, 0, dev->errmsg);
1706       return false;
1707    }
1708
1709    if (!(dev_state(dev, ST_TAPE))) {
1710       return false;
1711    }
1712    if (!dev_cap(dev, CAP_FSR)) {
1713       Mmsg1(dev->errmsg, _("ioctl MTFSR not permitted on %s.\n"), dev->dev_name);
1714       return false;
1715    }
1716
1717    Dmsg1(29, "fsr_dev %d\n", num);
1718    mt_com.mt_op = MTFSR;
1719    mt_com.mt_count = num;
1720    stat = ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
1721    if (stat == 0) {
1722       dev->state &= ~ST_EOF;
1723       dev->block_num += num;
1724    } else {
1725       berrno be;
1726       struct mtget mt_stat;
1727       clrerror_dev(dev, MTFSR);
1728       Dmsg1(100, "FSF fail: ERR=%s\n", be.strerror());
1729       if (dev_cap(dev, CAP_MTIOCGET) && ioctl(dev->fd, MTIOCGET, (char *)&mt_stat) == 0 && mt_stat.mt_fileno >= 0) {
1730          Dmsg4(100, "Adjust from %d:%d to %d:%d\n", dev->file,
1731             dev->block_num, mt_stat.mt_fileno, mt_stat.mt_blkno);
1732          dev->file = mt_stat.mt_fileno;
1733          dev->block_num = mt_stat.mt_blkno;
1734       } else {
1735          if (dev->state & ST_EOF) {
1736             dev->state |= ST_EOT;
1737          } else {
1738             dev->state |= ST_EOF;           /* assume EOF */
1739             dev->file++;
1740             dev->block_num = 0;
1741             dev->file_addr = 0;
1742             dev->file_size = 0;
1743          }
1744       }
1745       Mmsg2(dev->errmsg, _("ioctl MTFSR error on %s. ERR=%s.\n"),
1746          dev->dev_name, be.strerror());
1747    }
1748    update_pos_dev(dev);
1749    return stat == 0;
1750 }
1751
1752 /*
1753  * Backward space a record
1754  *   Returns:  false on failure
1755  *             true  on success
1756  */
1757 bool
1758 bsr_dev(DEVICE *dev, int num)
1759 {
1760    struct mtop mt_com;
1761    int stat;
1762
1763    if (dev->fd < 0) {
1764       dev->dev_errno = EBADF;
1765       Mmsg0(dev->errmsg, _("Bad call to bsr_dev. Archive not open\n"));
1766       Emsg0(M_FATAL, 0, dev->errmsg);
1767       return false;
1768    }
1769
1770    if (!(dev->state & ST_TAPE)) {
1771       return false;
1772    }
1773
1774    if (!dev_cap(dev, CAP_BSR)) {
1775       Mmsg1(dev->errmsg, _("ioctl MTBSR not permitted on %s.\n"), dev->dev_name);
1776       return false;
1777    }
1778
1779    Dmsg0(29, "bsr_dev\n");
1780    dev->block_num -= num;
1781    dev->state &= ~(ST_EOF|ST_EOT|ST_EOF);
1782    mt_com.mt_op = MTBSR;
1783    mt_com.mt_count = num;
1784    stat = ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
1785    if (stat < 0) {
1786       berrno be;
1787       clrerror_dev(dev, MTBSR);
1788       Mmsg2(dev->errmsg, _("ioctl MTBSR error on %s. ERR=%s.\n"),
1789          dev->dev_name, be.strerror());
1790    }
1791    update_pos_dev(dev);
1792    return stat == 0;
1793 }
1794
1795 /*
1796  * Reposition the device to file, block
1797  * Returns: false on failure
1798  *          true  on success
1799  */
1800 bool
1801 reposition_dev(DEVICE *dev, uint32_t file, uint32_t block)
1802 {
1803    if (dev->fd < 0) {
1804       dev->dev_errno = EBADF;
1805       Mmsg0(dev->errmsg, _("Bad call to reposition_dev. Archive not open\n"));
1806       Emsg0(M_FATAL, 0, dev->errmsg);
1807       return false;
1808    }
1809
1810    if (!(dev_state(dev, ST_TAPE))) {
1811       off_t pos = (((off_t)file)<<32) + block;
1812       Dmsg1(100, "===== lseek_dev to %d\n", (int)pos);
1813       if (lseek_dev(dev, pos, SEEK_SET) == (off_t)-1) {
1814          berrno be;
1815          dev->dev_errno = errno;
1816          Mmsg2(dev->errmsg, _("lseek_dev error on %s. ERR=%s.\n"),
1817             dev->dev_name, be.strerror());
1818          return false;
1819       }
1820       dev->file = file;
1821       dev->block_num = block;
1822       dev->file_addr = pos;
1823       return true;
1824    }
1825    Dmsg4(100, "reposition_dev from %u:%u to %u:%u\n",
1826       dev->file, dev->block_num, file, block);
1827    if (file < dev->file) {
1828       Dmsg0(100, "Rewind_dev\n");
1829       if (!rewind_dev(dev)) {
1830          return false;
1831       }
1832    }
1833    if (file > dev->file) {
1834       Dmsg1(100, "fsf %d\n", file-dev->file);
1835       if (!fsf_dev(dev, file-dev->file)) {
1836          Dmsg1(100, "fsf failed! ERR=%s\n", strerror_dev(dev));
1837          return false;
1838       }
1839       Dmsg2(100, "wanted_file=%d at_file=%d\n", file, dev->file);
1840    }
1841    if (block < dev->block_num) {
1842       Dmsg2(100, "wanted_blk=%d at_blk=%d\n", block, dev->block_num);
1843       Dmsg0(100, "bsf_dev 1\n");
1844       bsf_dev(dev, 1);
1845       Dmsg0(100, "fsf_dev 1\n");
1846       fsf_dev(dev, 1);
1847       Dmsg2(100, "wanted_blk=%d at_blk=%d\n", block, dev->block_num);
1848    }
1849    if (dev_cap(dev, CAP_POSITIONBLOCKS) && block > dev->block_num) {
1850       /* Ignore errors as Bacula can read to the correct block */
1851       Dmsg1(100, "fsr %d\n", block-dev->block_num);
1852       return fsr_dev(dev, block-dev->block_num);
1853    }
1854    return true;
1855 }
1856
1857
1858
1859 /*
1860  * Write an end of file on the device
1861  *   Returns: 0 on success
1862  *            non-zero on failure
1863  */
1864 int
1865 weof_dev(DEVICE *dev, int num)
1866 {
1867    struct mtop mt_com;
1868    int stat;
1869    Dmsg0(29, "weof_dev\n");
1870    
1871    if (dev->fd < 0) {
1872       dev->dev_errno = EBADF;
1873       Mmsg0(dev->errmsg, _("Bad call to weof_dev. Archive drive not open\n"));
1874       Emsg0(M_FATAL, 0, dev->errmsg);
1875       return -1;
1876    }
1877    dev->file_size = 0;
1878
1879    if (!(dev_state(dev, ST_TAPE))) {
1880       return 0;
1881    }
1882    dev->state &= ~(ST_EOT | ST_EOF);  /* remove EOF/EOT flags */
1883    mt_com.mt_op = MTWEOF;
1884    mt_com.mt_count = num;
1885    stat = ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
1886    if (stat == 0) {
1887       dev->block_num = 0;
1888       dev->file += num;
1889       dev->file_addr = 0;
1890    } else {
1891       berrno be;
1892       clrerror_dev(dev, MTWEOF);
1893       if (stat == -1) {
1894          Mmsg2(dev->errmsg, _("ioctl MTWEOF error on %s. ERR=%s.\n"),
1895             dev->dev_name, be.strerror());
1896        }
1897    }
1898    return stat;
1899 }
1900
1901 /*
1902  * Return string message with last error in English
1903  *  Be careful not to call this routine from within dev.c
1904  *  while editing an Mmsg() or you will end up in a recursive
1905  *  loop creating a Segmentation Violation.
1906  */
1907 char *
1908 strerror_dev(DEVICE *dev)
1909 {
1910    return dev->errmsg;
1911 }
1912
1913
1914 /*
1915  * If implemented in system, clear the tape
1916  * error status.
1917  */
1918 void
1919 clrerror_dev(DEVICE *dev, int func)
1920 {
1921    const char *msg = NULL;
1922    struct mtget mt_stat;
1923
1924    dev->dev_errno = errno;         /* save errno */
1925    if (errno == EIO) {
1926       dev->VolCatInfo.VolCatErrors++;
1927    }
1928
1929    if (!(dev->state & ST_TAPE)) {
1930       return;
1931    }
1932    if (errno == ENOTTY || errno == ENOSYS) { /* Function not implemented */
1933       switch (func) {
1934       case -1:
1935          Emsg0(M_ABORT, 0, "Got ENOTTY on read/write!\n");
1936          break;
1937       case MTWEOF:
1938          msg = "WTWEOF";
1939          dev->capabilities &= ~CAP_EOF; /* turn off feature */
1940          break;
1941 #ifdef MTEOM
1942       case MTEOM:
1943          msg = "WTEOM";
1944          dev->capabilities &= ~CAP_EOM; /* turn off feature */
1945          break;
1946 #endif
1947       case MTFSF:
1948          msg = "MTFSF";
1949          dev->capabilities &= ~CAP_FSF; /* turn off feature */
1950          break;
1951       case MTBSF:
1952          msg = "MTBSF";
1953          dev->capabilities &= ~CAP_BSF; /* turn off feature */
1954          break;
1955       case MTFSR:
1956          msg = "MTFSR";
1957          dev->capabilities &= ~CAP_FSR; /* turn off feature */
1958          break;
1959       case MTBSR:
1960          msg = "MTBSR";
1961          dev->capabilities &= ~CAP_BSR; /* turn off feature */
1962          break;
1963       default:
1964          msg = "Unknown";
1965          break;
1966       }
1967       if (msg != NULL) {
1968          dev->dev_errno = ENOSYS;
1969          Mmsg1(&dev->errmsg, _("This device does not support %s.\n"), msg);
1970          Emsg0(M_ERROR, 0, dev->errmsg);
1971       }
1972    }
1973    /* On some systems such as NetBSD, this clears all errors */
1974    ioctl(dev->fd, MTIOCGET, (char *)&mt_stat);
1975
1976 /* Found on Linux */
1977 #ifdef MTIOCLRERR
1978 {
1979    struct mtop mt_com;
1980    mt_com.mt_op = MTIOCLRERR;
1981    mt_com.mt_count = 1;
1982    /* Clear any error condition on the tape */
1983    ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
1984    Dmsg0(200, "Did MTIOCLRERR\n");
1985 }
1986 #endif
1987
1988 /* Typically on FreeBSD */
1989 #ifdef MTIOCERRSTAT
1990 {
1991    /* Read and clear SCSI error status */
1992    union mterrstat mt_errstat;
1993    Dmsg2(200, "Doing MTIOCERRSTAT errno=%d ERR=%s\n", dev->dev_errno,
1994       strerror(dev->dev_errno));
1995    ioctl(dev->fd, MTIOCERRSTAT, (char *)&mt_errstat);
1996 }
1997 #endif
1998
1999 /* Clear Subsystem Exception OSF1 */
2000 #ifdef MTCSE
2001 {
2002    struct mtop mt_com;
2003    mt_com.mt_op = MTCSE;
2004    mt_com.mt_count = 1;
2005    /* Clear any error condition on the tape */
2006    ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
2007    Dmsg0(200, "Did MTCSE\n");
2008 }
2009 #endif
2010 }
2011
2012 /*
2013  * Flush buffer contents
2014  *  No longer used.
2015  */
2016 int flush_dev(DEVICE *dev)
2017 {
2018    return 1;
2019 }
2020
2021 static void do_close(DEVICE *dev)
2022 {
2023
2024    Dmsg1(29, "really close_dev %s\n", dev->dev_name);
2025    if (dev->fd >= 0) {
2026       close(dev->fd);
2027    }
2028    if (dev_cap(dev, CAP_REQMOUNT)) {
2029       if (unmount_dev(dev, 1) < 0) {
2030          Dmsg1(0, "Cannot unmount device %s.\n", dev->dev_name);
2031       }
2032    }
2033    
2034    /* Remove the last part file if it is empty */
2035    if ((dev->state & ST_APPEND) && (dev->num_parts > 0)) {
2036       struct stat statp;
2037       POOL_MEM archive_name(PM_FNAME);
2038       dev->part = dev->num_parts;
2039       get_filename(dev, dev->VolCatInfo.VolCatName, archive_name);
2040       /* Check that the part file is empty */
2041       if ((stat(archive_name.c_str(), &statp) == 0) && (statp.st_size == 0)) {
2042          unlink(archive_name.c_str());
2043       }
2044    }
2045    
2046    /* Clean up device packet so it can be reused */
2047    dev->fd = -1;
2048    dev->state &= ~(ST_OPENED|ST_LABEL|ST_READ|ST_APPEND|ST_EOT|ST_WEOT|ST_EOF);
2049    dev->file = dev->block_num = 0;
2050    dev->file_size = 0;
2051    dev->file_addr = 0;
2052    dev->part = 0;
2053    dev->part_size = 0;
2054    dev->part_start = 0;
2055    dev->EndFile = dev->EndBlock = 0;
2056    memset(&dev->VolCatInfo, 0, sizeof(dev->VolCatInfo));
2057    memset(&dev->VolHdr, 0, sizeof(dev->VolHdr));
2058    if (dev->tid) {
2059       stop_thread_timer(dev->tid);
2060       dev->tid = 0;
2061    }
2062    dev->use_count = 0;
2063 }
2064
2065 /*
2066  * Close the device
2067  */
2068 void
2069 close_dev(DEVICE *dev)
2070 {
2071    if (!dev) {
2072       Mmsg0(&dev->errmsg, _("Bad call to close_dev. Archive not open\n"));
2073       Emsg0(M_FATAL, 0, dev->errmsg);
2074       return;
2075    }
2076    /*if (dev->fd >= 0 && dev->use_count == 1) {*/
2077    /* No need to check if dev->fd >= 0: it is checked again
2078     * in do_close, and do_close MUST be called for volumes
2079     * splitted in parts, even if dev->fd == -1. */
2080    if (dev->use_count == 1) {
2081       do_close(dev);
2082    } else if (dev->use_count > 0) {
2083       dev->use_count--;
2084    }
2085
2086 #ifdef FULL_DEBUG
2087    ASSERT(dev->use_count >= 0);
2088 #endif
2089 }
2090
2091 /*
2092  * Used when unmounting the device, ignore use_count
2093  */
2094 void force_close_dev(DEVICE *dev)
2095 {
2096    if (!dev) {
2097       Mmsg0(&dev->errmsg, _("Bad call to force_close_dev. Archive not open\n"));
2098       Emsg0(M_FATAL, 0, dev->errmsg);
2099       return;
2100    }
2101    Dmsg1(29, "Force close_dev %s\n", dev->dev_name);
2102    do_close(dev);
2103
2104 #ifdef FULL_DEBUG
2105    ASSERT(dev->use_count >= 0);
2106 #endif
2107 }
2108
2109 bool truncate_dev(DEVICE *dev)
2110 {
2111    Dmsg1(100, "truncate_dev %s\n", dev->dev_name);
2112    if (dev->state & ST_TAPE) {
2113       return true;                    /* we don't really truncate tapes */
2114       /* maybe we should rewind and write and eof ???? */
2115    }
2116    
2117    /* If there is more than one part, open the first one, and then truncate it. */
2118    if (dev->num_parts > 0) {
2119       dev->num_parts = 0;
2120       dev->VolCatInfo.VolCatParts = 0;
2121       if (open_first_part(dev) < 0) {
2122          berrno be;
2123          Mmsg1(&dev->errmsg, "Unable to truncate device, because I'm unable to open the first part. ERR=%s\n", be.strerror());
2124       }
2125    }
2126    
2127    if (ftruncate(dev->fd, 0) != 0) {
2128       berrno be;
2129       Mmsg1(&dev->errmsg, _("Unable to truncate device. ERR=%s\n"), be.strerror());
2130       return false;
2131    }
2132    return true;
2133 }
2134
2135 bool
2136 dev_is_tape(DEVICE *dev)
2137 {
2138    return (dev->state & ST_TAPE) ? true : false;
2139 }
2140
2141
2142 /*
2143  * return 1 if the device is read for write, and 0 otherwise
2144  *   This is meant for checking at the end of a job to see
2145  *   if we still have a tape (perhaps not if at end of tape
2146  *   and the job is canceled).
2147  */
2148 bool
2149 dev_can_write(DEVICE *dev)
2150 {
2151    if ((dev->state & ST_OPENED) &&  (dev->state & ST_APPEND) &&
2152        (dev->state & ST_LABEL)  && !(dev->state & ST_WEOT)) {
2153       return true;
2154    } else {
2155       return false;
2156    }
2157 }
2158
2159 char *
2160 dev_name(DEVICE *dev)
2161 {
2162    return dev->dev_name;
2163 }
2164
2165 char *
2166 dev_vol_name(DEVICE *dev)
2167 {
2168    return dev->VolCatInfo.VolCatName;
2169 }
2170
2171 uint32_t dev_block(DEVICE *dev)
2172 {
2173    update_pos_dev(dev);
2174    return dev->block_num;
2175 }
2176
2177 uint32_t dev_file(DEVICE *dev)
2178 {
2179    update_pos_dev(dev);
2180    return dev->file;
2181 }
2182
2183 /*
2184  * Free memory allocated for the device
2185  */
2186 void
2187 term_dev(DEVICE *dev)
2188 {
2189    if (!dev) {
2190       dev->dev_errno = EBADF;
2191       Mmsg0(&dev->errmsg, _("Bad call to term_dev. Archive not open\n"));
2192       Emsg0(M_FATAL, 0, dev->errmsg);
2193       return;
2194    }
2195    do_close(dev);
2196    Dmsg0(29, "term_dev\n");
2197    if (dev->dev_name) {
2198       free_memory(dev->dev_name);
2199       dev->dev_name = NULL;
2200    }
2201    if (dev->errmsg) {
2202       free_pool_memory(dev->errmsg);
2203       dev->errmsg = NULL;
2204    }
2205    pthread_mutex_destroy(&dev->mutex);
2206    pthread_cond_destroy(&dev->wait);
2207    pthread_cond_destroy(&dev->wait_next_vol);
2208    pthread_mutex_destroy(&dev->spool_mutex);
2209    rwl_destroy(&dev->lock);
2210    if (dev->attached_dcrs) {
2211       delete dev->attached_dcrs;
2212       dev->attached_dcrs = NULL;
2213    }
2214    if (dev->state & ST_MALLOC) {
2215       free_pool_memory((POOLMEM *)dev);
2216    }
2217 }
2218
2219 /*
2220  * This routine initializes the device wait timers
2221  */
2222 void init_dev_wait_timers(DEVICE *dev)
2223 {
2224    /* ******FIXME******* put these on config variables */
2225    dev->min_wait = 60 * 60;
2226    dev->max_wait = 24 * 60 * 60;
2227    dev->max_num_wait = 9;              /* 5 waits =~ 1 day, then 1 day at a time */
2228    dev->wait_sec = dev->min_wait;
2229    dev->rem_wait_sec = dev->wait_sec;
2230    dev->num_wait = 0;
2231    dev->poll = false;
2232    dev->BadVolName[0] = 0;
2233 }
2234
2235 /*
2236  * Returns: true if time doubled
2237  *          false if max time expired
2238  */
2239 bool double_dev_wait_time(DEVICE *dev)
2240 {
2241    dev->wait_sec *= 2;               /* double wait time */
2242    if (dev->wait_sec > dev->max_wait) {   /* but not longer than maxtime */
2243       dev->wait_sec = dev->max_wait;
2244    }
2245    dev->num_wait++;
2246    dev->rem_wait_sec = dev->wait_sec;
2247    if (dev->num_wait >= dev->max_num_wait) {
2248       return false;
2249    }
2250    return true;
2251 }
2252
2253 void set_os_device_parameters(DEVICE *dev)
2254 {
2255 #ifdef HAVE_LINUX_OS
2256    struct mtop mt_com;
2257    if (dev->min_block_size == dev->max_block_size &&
2258        dev->min_block_size == 0) {    /* variable block mode */
2259       mt_com.mt_op = MTSETBLK;
2260       mt_com.mt_count = 0;
2261       if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
2262          clrerror_dev(dev, MTSETBLK);
2263       }
2264       mt_com.mt_op = MTSETDRVBUFFER;
2265       mt_com.mt_count = MT_ST_CLEARBOOLEANS;
2266       if (!dev_cap(dev, CAP_TWOEOF)) {
2267          mt_com.mt_count |= MT_ST_TWO_FM;
2268       }
2269       if (dev_cap(dev, CAP_EOM)) {
2270          mt_com.mt_count |= MT_ST_FAST_MTEOM;
2271       }
2272       if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
2273          clrerror_dev(dev, MTSETBLK);
2274       }
2275    }
2276    return;
2277 #endif
2278
2279 #ifdef HAVE_NETBSD_OS
2280    struct mtop mt_com;
2281    if (dev->min_block_size == dev->max_block_size &&
2282        dev->min_block_size == 0) {    /* variable block mode */
2283       mt_com.mt_op = MTSETBSIZ;
2284       mt_com.mt_count = 0;
2285       if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
2286          clrerror_dev(dev, MTSETBSIZ);
2287       }
2288       /* Get notified at logical end of tape */
2289       mt_com.mt_op = MTEWARN;
2290       mt_com.mt_count = 1;
2291       if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
2292          clrerror_dev(dev, MTEWARN);
2293       }
2294    }
2295    return;
2296 #endif
2297
2298 #if HAVE_FREEBSD_OS || HAVE_OPENBSD_OS
2299    struct mtop mt_com;
2300    if (dev->min_block_size == dev->max_block_size &&
2301        dev->min_block_size == 0) {    /* variable block mode */
2302       mt_com.mt_op = MTSETBSIZ;
2303       mt_com.mt_count = 0;
2304       if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
2305          clrerror_dev(dev, MTSETBSIZ);
2306       }
2307    }
2308    return;
2309 #endif
2310
2311 #ifdef HAVE_SUN_OS
2312    struct mtop mt_com;
2313    if (dev->min_block_size == dev->max_block_size &&
2314        dev->min_block_size == 0) {    /* variable block mode */
2315       mt_com.mt_op = MTSRSZ;
2316       mt_com.mt_count = 0;
2317       if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
2318          clrerror_dev(dev, MTSRSZ);
2319       }
2320    }
2321    return;
2322 #endif
2323 }
2324
2325 /*
2326  * Edit codes into (Un)MountCommand, Write(First)PartCommand
2327  *  %% = %
2328  *  %a = archive device name
2329  *  %m = mount point
2330  *  %v = last part name
2331  *
2332  *  omsg = edited output message
2333  *  imsg = input string containing edit codes (%x)
2334  *
2335  */
2336 char *edit_device_codes_dev(DEVICE* dev, char *omsg, const char *imsg)
2337 {
2338    const char *p;
2339    const char *str;
2340    char add[20];
2341    
2342    POOL_MEM archive_name(PM_FNAME);
2343    get_filename(dev, dev->VolCatInfo.VolCatName, archive_name);
2344
2345    *omsg = 0;
2346    Dmsg1(800, "edit_device_codes: %s\n", imsg);
2347    for (p=imsg; *p; p++) {
2348       if (*p == '%') {
2349          switch (*++p) {
2350             case '%':
2351                str = "%";
2352                break;
2353             case 'n':
2354                bsnprintf(add, sizeof(add), "%d", dev->part);
2355                str = add;
2356                break;
2357             case 'a':
2358                str = dev->dev_name;
2359                break;
2360             case 'm':
2361                str = dev->device->mount_point;
2362                break;
2363             case 'v':
2364                str = archive_name.c_str();
2365                break;
2366             default:
2367                add[0] = '%';
2368                add[1] = *p;
2369                add[2] = 0;
2370                str = add;
2371                break;
2372          }
2373       } else {
2374          add[0] = *p;
2375          add[1] = 0;
2376          str = add;
2377       }
2378       Dmsg1(900, "add_str %s\n", str);
2379       pm_strcat(&omsg, (char *)str);
2380       Dmsg1(800, "omsg=%s\n", omsg);
2381    }
2382    return omsg;
2383 }