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