]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/stored/dev.c
- Modified ANSI label code to preserve any ANSI label
[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    if (tape) { /* No parts on tapes */
163       dev->max_part_size = 0;
164    }
165    else {
166       dev->max_part_size = device->max_part_size;
167    }
168    /* Sanity check */
169    if (dev->vol_poll_interval && dev->vol_poll_interval < 60) {
170       dev->vol_poll_interval = 60;
171    }
172    dev->device = device;
173
174    if (tape) {
175       dev->state |= ST_TAPE;
176    } else if (fifo) {
177       dev->state |= ST_FIFO;
178       dev->capabilities |= CAP_STREAM; /* set stream device */
179    } else {
180       dev->state |= ST_FILE;
181    }
182
183    /* If the device requires mount :
184     * - Check that the mount point is available 
185     * - Check that (un)mount commands are defined
186     */
187    if (dev->is_file() && device->cap_bits & CAP_REQMOUNT) {
188       if (stat(device->mount_point, &statp) < 0) {
189          berrno be;
190          dev->dev_errno = errno;
191          Jmsg2(NULL, M_FATAL, 0, _("Unable to stat mount point %s: ERR=%s\n"), 
192             device->mount_point, be.strerror());
193          return NULL;
194       }
195       if (!device->mount_command || !device->unmount_command) {
196          Jmsg0(NULL, M_ERROR_TERM, 0, _("Mount and unmount commands must defined for a device which requires mount.\n"));
197       }
198       if (!device->write_part_command) {
199          Jmsg0(NULL, M_ERROR_TERM, 0, _("Write part command must be defined for a device which requires mount.\n"));
200       }
201       dev->state |= ST_DVD;
202    }
203
204    if (dev->max_block_size > 1000000) {
205       Emsg3(M_ERROR, 0, _("Block size %u on device %s is too large, using default %u\n"),
206          dev->max_block_size, dev->dev_name, DEFAULT_BLOCK_SIZE);
207       dev->max_block_size = 0;
208    }
209    if (dev->max_block_size % TAPE_BSIZE != 0) {
210       Emsg2(M_WARNING, 0, _("Max block size %u not multiple of device %s block size.\n"),
211          dev->max_block_size, dev->dev_name);
212    }
213
214    dev->errmsg = get_pool_memory(PM_EMSG);
215    *dev->errmsg = 0;
216
217    if ((errstat = pthread_mutex_init(&dev->mutex, NULL)) != 0) {
218       berrno be;
219       dev->dev_errno = errstat;
220       Mmsg1(dev->errmsg, _("Unable to init mutex: ERR=%s\n"), be.strerror(errstat));
221       Emsg0(M_FATAL, 0, dev->errmsg);
222    }
223    if ((errstat = pthread_cond_init(&dev->wait, NULL)) != 0) {
224       berrno be;
225       dev->dev_errno = errstat;
226       Mmsg1(dev->errmsg, _("Unable to init cond variable: ERR=%s\n"), be.strerror(errstat));
227       Emsg0(M_ERROR_TERM, 0, dev->errmsg);
228    }
229    if ((errstat = pthread_cond_init(&dev->wait_next_vol, NULL)) != 0) {
230       berrno be;
231       dev->dev_errno = errstat;
232       Mmsg1(dev->errmsg, _("Unable to init cond variable: ERR=%s\n"), be.strerror(errstat));
233       Emsg0(M_ERROR_TERM, 0, dev->errmsg);
234    }
235    if ((errstat = pthread_mutex_init(&dev->spool_mutex, NULL)) != 0) {
236       berrno be;
237       dev->dev_errno = errstat;
238       Mmsg1(dev->errmsg, _("Unable to init mutex: ERR=%s\n"), be.strerror(errstat));
239       Emsg0(M_ERROR_TERM, 0, dev->errmsg);
240    }
241    if ((errstat = rwl_init(&dev->lock)) != 0) {
242       berrno be;
243       dev->dev_errno = errstat;
244       Mmsg1(dev->errmsg, _("Unable to init mutex: ERR=%s\n"), be.strerror(errstat));
245       Emsg0(M_ERROR_TERM, 0, dev->errmsg);
246    }
247
248    dev->fd = -1;
249    dev->attached_dcrs = New(dlist(dcr, &dcr->dev_link));
250    Dmsg2(29, "init_dev: tape=%d dev_name=%s\n", dev_is_tape(dev), dev->dev_name);
251    
252    return dev;
253 }
254
255 /* 
256  * Write the current volume/part filename to archive_name.
257  */
258 static void get_filename(DEVICE *dev, char *VolName, POOL_MEM& archive_name) 
259 {
260    char partnumber[20];
261    
262    if (dev->is_dvd()) {
263          /* If we try to open the last part, just open it from disk, 
264          * otherwise, open it from the spooling directory */
265       if (dev->part < dev->num_parts) {
266          pm_strcpy(archive_name, dev->device->mount_point);
267       } else {
268          /* Use the working directory if spool directory is not defined */
269          if (dev->device->spool_directory) {
270             pm_strcpy(archive_name, dev->device->spool_directory);
271          } else {
272             pm_strcpy(archive_name, working_directory);
273          }
274       }
275    } else {
276       pm_strcpy(archive_name, dev->dev_name);
277    }
278       
279    if (archive_name.c_str()[strlen(archive_name.c_str())-1] != '/') {
280       pm_strcat(archive_name, "/");
281    }
282    pm_strcat(archive_name, VolName);
283    /* if part != 0, append .# to the filename (where # is the part number) */
284    if (dev->is_dvd() && dev->part != 0) {
285       pm_strcat(archive_name, ".");
286       bsnprintf(partnumber, sizeof(partnumber), "%d", dev->part);
287       pm_strcat(archive_name, partnumber);
288    }
289 }  
290
291 /*
292  * Open the device with the operating system and
293  * initialize buffer pointers.
294  *
295  * Returns:  -1  on error
296  *           fd  on success
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->is_open()) {
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    dev->label_type = B_BACULA_LABEL;
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
925 /* Protected version of lseek, which opens the right part if necessary */
926 off_t lseek_dev(DEVICE *dev, off_t offset, int whence)
927 {
928    int pos, openmode;
929    
930    if (dev->num_parts == 0) { /* If there is only one part, simply call lseek. */
931       return lseek(dev->fd, offset, whence);
932    }
933       
934    switch(whence) {
935    case SEEK_SET:
936       Dmsg1(100, "lseek_dev SEEK_SET called %d\n", offset);
937       if ((uint64_t)offset >= dev->part_start) {
938          if ((uint64_t)(offset - dev->part_start) < dev->part_size) {
939             /* We are staying in the current part, just seek */
940             if ((pos = lseek(dev->fd, (off_t)(offset-dev->part_start), SEEK_SET)) < 0) {
941                return pos;   
942             } else {
943                return pos + dev->part_start;
944             }
945          } else {
946             /* Load next part, and start again */
947             if (open_next_part(dev) < 0) {
948                Dmsg0(100, "lseek_dev failed while trying to open the next part\n");
949                return -1;
950             }
951             return lseek_dev(dev, offset, SEEK_SET);
952          }
953       } else {
954          /* pos < dev->part_start :
955           * We need to access a previous part, 
956           * so just load the first one, and seek again
957           * until the right one is loaded */
958          if (open_first_part(dev) < 0) {
959             Dmsg0(100, "lseek_dev failed while trying to open the first part\n");
960             return -1;
961          }
962          return lseek_dev(dev, offset, SEEK_SET);
963       }
964       break;
965    case SEEK_CUR:
966       Dmsg1(100, "lseek_dev SEEK_CUR called %d\n", offset);
967       if ((pos = lseek(dev->fd, (off_t)0, SEEK_CUR)) < 0) {
968          return pos;   
969       }
970       pos += dev->part_start;
971       if (offset == 0) {
972          return pos;
973       }
974       else { /* Not used in Bacula, but should work */
975          return lseek_dev(dev, pos, SEEK_SET);
976       }
977       break;
978    case SEEK_END:
979       Dmsg1(100, "lseek_dev SEEK_END called %d\n", offset);
980       if (offset > 0) { /* Not used by bacula */
981          Dmsg1(100, "lseek_dev SEEK_END called with an invalid offset %d\n", offset);
982          errno = EINVAL;
983          return -1;
984       }
985       
986       if (dev->part == dev->num_parts) { /* The right part is already loaded */
987          if ((pos = lseek(dev->fd, (off_t)0, SEEK_END)) < 0) {
988             return pos;   
989          } else {
990             return pos + dev->part_start;
991          }
992       } else {
993          /* Load the first part, then load the next until we reach the last one.
994           * This is the only way to be sure we compute the right file address. */
995          /* Save previous openmode, and open all but last part read-only (useful for DVDs) */
996          openmode = dev->openmode;
997          dev->openmode = OPEN_READ_ONLY;
998          
999          /* Works because num_parts > 0. */
1000          if (open_first_part(dev) < 0) {
1001             Dmsg0(100, "lseek_dev failed while trying to open the first part\n");
1002             return -1;
1003          }
1004          while (dev->part < (dev->num_parts-1)) {
1005             if (open_next_part(dev) < 0) {
1006                Dmsg0(100, "lseek_dev failed while trying to open the next part\n");
1007                return -1;
1008             }
1009          }
1010          dev->openmode = openmode;
1011          if (open_next_part(dev) < 0) {
1012             Dmsg0(100, "lseek_dev failed while trying to open the next part\n");
1013             return -1;
1014          }
1015          return lseek_dev(dev, 0, SEEK_END);
1016       }
1017       break;
1018    default:
1019       errno = EINVAL;
1020       return -1;
1021    }
1022 }
1023
1024 #ifdef debug_tracing
1025 #undef rewind_dev
1026 bool _rewind_dev(char *file, int line, DEVICE *dev)
1027 {
1028    Dmsg2(100, "rewind_dev called from %s:%d\n", file, line);
1029    return rewind_dev(dev);
1030 }
1031 #endif
1032
1033 /*
1034  * Rewind the device.
1035  *  Returns: true  on success
1036  *           false on failure
1037  */
1038 bool rewind_dev(DEVICE *dev)
1039 {
1040    struct mtop mt_com;
1041    unsigned int i;
1042
1043    Dmsg1(29, "rewind_dev %s\n", dev->dev_name);
1044    if (dev->fd < 0) {
1045       dev->dev_errno = EBADF;
1046       Mmsg1(&dev->errmsg, _("Bad call to rewind_dev. Device %s not open\n"),
1047             dev->dev_name);
1048       Emsg0(M_ABORT, 0, dev->errmsg);
1049       return false;
1050    }
1051    dev->state &= ~(ST_EOT|ST_EOF|ST_WEOT);  /* remove EOF/EOT flags */
1052    dev->block_num = dev->file = 0;
1053    dev->file_size = 0;
1054    dev->file_addr = 0;
1055    if (dev->is_tape()) {
1056       mt_com.mt_op = MTREW;
1057       mt_com.mt_count = 1;
1058       /* If we get an I/O error on rewind, it is probably because
1059        * the drive is actually busy. We loop for (about 5 minutes)
1060        * retrying every 5 seconds.
1061        */
1062       for (i=dev->max_rewind_wait; ; i -= 5) {
1063          if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
1064             berrno be;
1065             clrerror_dev(dev, MTREW);
1066             if (i == dev->max_rewind_wait) {
1067                Dmsg1(200, "Rewind error, %s. retrying ...\n", be.strerror());
1068             }
1069             if (dev->dev_errno == EIO && i > 0) {
1070                Dmsg0(200, "Sleeping 5 seconds.\n");
1071                bmicrosleep(5, 0);
1072                continue;
1073             }
1074             Mmsg2(&dev->errmsg, _("Rewind error on %s. ERR=%s.\n"),
1075                dev->dev_name, be.strerror());
1076             return false;
1077          }
1078          break;
1079       }
1080    } else if (dev->is_file()) {      
1081       if (lseek_dev(dev, (off_t)0, SEEK_SET) < 0) {
1082          berrno be;
1083          dev->dev_errno = errno;
1084          Mmsg2(&dev->errmsg, _("lseek_dev error on %s. ERR=%s.\n"),
1085             dev->dev_name, be.strerror());
1086          return false;
1087       }
1088    }
1089    return true;
1090 }
1091
1092 /*
1093  * Called to indicate that we have just read an
1094  *  EOF from the device.
1095  */
1096 void DEVICE::set_eof() 
1097
1098    state |= ST_EOF;
1099    file++;
1100    file_addr = 0;
1101    file_size = 0;
1102    block_num = 0;
1103 }
1104
1105 /*
1106  * Position device to end of medium (end of data)
1107  *  Returns: 1 on succes
1108  *           0 on error
1109  */
1110 int
1111 eod_dev(DEVICE *dev)
1112 {
1113    struct mtop mt_com;
1114    struct mtget mt_stat;
1115    int stat = 0;
1116    off_t pos;
1117
1118    Dmsg0(29, "eod_dev\n");
1119    if (dev->at_eot()) {
1120       return 1;
1121    }
1122    dev->state &= ~(ST_EOF);  /* remove EOF flags */
1123    dev->block_num = dev->file = 0;
1124    dev->file_size = 0;
1125    dev->file_addr = 0;
1126    if (dev->state & (ST_FIFO | ST_PROG)) {
1127       return 1;
1128    }
1129    if (!dev->is_tape()) {
1130       pos = lseek_dev(dev, (off_t)0, SEEK_END);
1131 //    Dmsg1(100, "====== Seek to %lld\n", pos);
1132       if (pos >= 0) {
1133          update_pos_dev(dev);
1134          dev->state |= ST_EOT;
1135          return 1;
1136       }
1137       dev->dev_errno = errno;
1138       berrno be;
1139       Mmsg2(&dev->errmsg, _("lseek_dev error on %s. ERR=%s.\n"),
1140              dev->dev_name, be.strerror());
1141       return 0;
1142    }
1143 #ifdef MTEOM
1144
1145    if (dev_cap(dev, CAP_MTIOCGET) && dev_cap(dev, CAP_FASTFSF) && 
1146       !dev_cap(dev, CAP_EOM)) {
1147       struct mtget mt_stat;
1148       Dmsg0(100,"Using FAST FSF for EOM\n");
1149       if (ioctl(dev->fd, MTIOCGET, (char *)&mt_stat) == 0 && mt_stat.mt_fileno <= 0) {
1150         if (!rewind_dev(dev)) {
1151           return 0;
1152         }
1153       }
1154       mt_com.mt_op = MTFSF;
1155       /*
1156        * ***FIXME*** fix code to handle case that INT16_MAX is
1157        *   not large enough.
1158        */
1159       mt_com.mt_count = INT16_MAX;    /* use big positive number */
1160       if (mt_com.mt_count < 0) {
1161          mt_com.mt_count = INT16_MAX; /* brain damaged system */
1162       }
1163    }
1164
1165    if (dev_cap(dev, CAP_MTIOCGET) && (dev_cap(dev, CAP_FASTFSF) || dev_cap(dev, CAP_EOM))) {
1166       if (dev_cap(dev, CAP_EOM)) {
1167          Dmsg0(100,"Using EOM for EOM\n");
1168          mt_com.mt_op = MTEOM;
1169          mt_com.mt_count = 1;
1170       }
1171
1172       if ((stat=ioctl(dev->fd, MTIOCTOP, (char *)&mt_com)) < 0) {
1173          berrno be;
1174          clrerror_dev(dev, mt_com.mt_op);
1175          Dmsg1(50, "ioctl error: %s\n", be.strerror());
1176          update_pos_dev(dev);
1177          Mmsg2(&dev->errmsg, _("ioctl MTEOM error on %s. ERR=%s.\n"),
1178             dev->dev_name, be.strerror());
1179          return 0;
1180       }
1181
1182       if (ioctl(dev->fd, MTIOCGET, (char *)&mt_stat) < 0) {
1183          berrno be;
1184          clrerror_dev(dev, -1);
1185          Mmsg2(&dev->errmsg, _("ioctl MTIOCGET error on %s. ERR=%s.\n"),
1186             dev->dev_name, be.strerror());
1187          return 0;
1188       }
1189       Dmsg2(100, "EOD file=%d block=%d\n", mt_stat.mt_fileno, mt_stat.mt_blkno);
1190       dev->set_eof();
1191       dev->file = mt_stat.mt_fileno;
1192
1193    /*
1194     * Rewind then use FSF until EOT reached
1195     */
1196    } else {
1197 #else
1198    {
1199 #endif
1200       if (!rewind_dev(dev)) {
1201          return 0;
1202       }
1203       /*
1204        * Move file by file to the end of the tape
1205        */
1206       int file_num;
1207       for (file_num=dev->file; !dev->at_eot(); file_num++) {
1208          Dmsg0(200, "eod_dev: doing fsf 1\n");
1209          if (!fsf_dev(dev, 1)) {
1210             Dmsg0(200, "fsf_dev error.\n");
1211             return 0;
1212          }
1213          /*
1214           * Avoid infinite loop. ***FIXME*** possibly add code
1215           *   to set EOD or to turn off CAP_FASTFSF if on.
1216           */
1217          if (file_num == (int)dev->file) {
1218             struct mtget mt_stat;
1219             Dmsg1(100, "fsf_dev did not advance from file %d\n", file_num);
1220             if (dev_cap(dev, CAP_MTIOCGET) && ioctl(dev->fd, MTIOCGET, (char *)&mt_stat) == 0 &&
1221                       mt_stat.mt_fileno >= 0) {
1222                Dmsg2(100, "Adjust file from %d to %d\n", dev->file , mt_stat.mt_fileno);
1223                dev->set_eof();
1224                dev->file = mt_stat.mt_fileno;
1225             }
1226             stat = 0;
1227             break;                    /* we are not progressing, bail out */
1228          }
1229       }
1230    }
1231    /*
1232     * Some drivers leave us after second EOF when doing
1233     * MTEOM, so we must backup so that appending overwrites
1234     * the second EOF.
1235     */
1236    if (dev_cap(dev, CAP_BSFATEOM)) {
1237       struct mtget mt_stat;
1238       /* Backup over EOF */
1239       stat = bsf_dev(dev, 1);
1240       /* If BSF worked and fileno is known (not -1), set file */
1241       if (dev_cap(dev, CAP_MTIOCGET) && ioctl(dev->fd, MTIOCGET, (char *)&mt_stat) == 0 && mt_stat.mt_fileno >= 0) {
1242          Dmsg2(100, "BSFATEOF adjust file from %d to %d\n", dev->file , mt_stat.mt_fileno);
1243          dev->file = mt_stat.mt_fileno;
1244       } else {
1245          dev->file++;                 /* wing it -- not correct on all OSes */
1246       }
1247    } else {
1248       update_pos_dev(dev);                   /* update position */
1249       stat = 1;
1250    }
1251    Dmsg1(200, "EOD dev->file=%d\n", dev->file);
1252    return stat;
1253 }
1254
1255 /*
1256  * Set the position of the device -- only for files
1257  *   For other devices, there is no generic way to do it.
1258  *  Returns: true  on succes
1259  *           false on error
1260  */
1261 bool update_pos_dev(DEVICE *dev)
1262 {
1263    off_t pos;
1264    bool ok = true;
1265
1266    if (dev->fd < 0) {
1267       dev->dev_errno = EBADF;
1268       Mmsg0(&dev->errmsg, _("Bad device call. Archive not open\n"));
1269       Emsg0(M_FATAL, 0, dev->errmsg);
1270       return false;
1271    }
1272
1273    /* Find out where we are */
1274    if (dev->is_file()) {
1275       dev->file = 0;
1276       dev->file_addr = 0;
1277       pos = lseek_dev(dev, (off_t)0, SEEK_CUR);
1278       if (pos < 0) {
1279          berrno be;
1280          dev->dev_errno = errno;
1281          Pmsg1(000, "Seek error: ERR=%s\n", be.strerror());
1282          Mmsg2(&dev->errmsg, _("lseek_dev error on %s. ERR=%s.\n"),
1283             dev->dev_name, be.strerror());
1284          ok = false;
1285       } else {
1286          dev->file_addr = pos;
1287       }
1288    }
1289    return ok;
1290 }
1291
1292
1293 /*
1294  * Return the status of the device.  This was meant
1295  * to be a generic routine. Unfortunately, it doesn't
1296  * seem possible (at least I do not know how to do it
1297  * currently), which means that for the moment, this
1298  * routine has very little value.
1299  *
1300  *   Returns: status
1301  */
1302 uint32_t status_dev(DEVICE *dev)
1303 {
1304    struct mtget mt_stat;
1305    uint32_t stat = 0;
1306
1307    if (dev->state & (ST_EOT | ST_WEOT)) {
1308       stat |= BMT_EOD;
1309       Dmsg0(-20, " EOD");
1310    }
1311    if (dev->state & ST_EOF) {
1312       stat |= BMT_EOF;
1313       Dmsg0(-20, " EOF");
1314    }
1315    if (dev->is_tape()) {
1316       stat |= BMT_TAPE;
1317       Dmsg0(-20," Bacula status:");
1318       Dmsg2(-20," file=%d block=%d\n", dev->file, dev->block_num);
1319       if (ioctl(dev->fd, MTIOCGET, (char *)&mt_stat) < 0) {
1320          berrno be;
1321          dev->dev_errno = errno;
1322          Mmsg2(&dev->errmsg, _("ioctl MTIOCGET error on %s. ERR=%s.\n"),
1323             dev->dev_name, be.strerror());
1324          return 0;
1325       }
1326       Dmsg0(-20, " Device status:");
1327
1328 #if defined(HAVE_LINUX_OS)
1329       if (GMT_EOF(mt_stat.mt_gstat)) {
1330          stat |= BMT_EOF;
1331          Dmsg0(-20, " EOF");
1332       }
1333       if (GMT_BOT(mt_stat.mt_gstat)) {
1334          stat |= BMT_BOT;
1335          Dmsg0(-20, " BOT");
1336       }
1337       if (GMT_EOT(mt_stat.mt_gstat)) {
1338          stat |= BMT_EOT;
1339          Dmsg0(-20, " EOT");
1340       }
1341       if (GMT_SM(mt_stat.mt_gstat)) {
1342          stat |= BMT_SM;
1343          Dmsg0(-20, " SM");
1344       }
1345       if (GMT_EOD(mt_stat.mt_gstat)) {
1346          stat |= BMT_EOD;
1347          Dmsg0(-20, " EOD");
1348       }
1349       if (GMT_WR_PROT(mt_stat.mt_gstat)) {
1350          stat |= BMT_WR_PROT;
1351          Dmsg0(-20, " WR_PROT");
1352       }
1353       if (GMT_ONLINE(mt_stat.mt_gstat)) {
1354          stat |= BMT_ONLINE;
1355          Dmsg0(-20, " ONLINE");
1356       }
1357       if (GMT_DR_OPEN(mt_stat.mt_gstat)) {
1358          stat |= BMT_DR_OPEN;
1359          Dmsg0(-20, " DR_OPEN");
1360       }
1361       if (GMT_IM_REP_EN(mt_stat.mt_gstat)) {
1362          stat |= BMT_IM_REP_EN;
1363          Dmsg0(-20, " IM_REP_EN");
1364       }
1365 #endif /* !SunOS && !OSF */
1366       if (dev_cap(dev, CAP_MTIOCGET)) {
1367          Dmsg2(-20, " file=%d block=%d\n", mt_stat.mt_fileno, mt_stat.mt_blkno);
1368       } else {
1369          Dmsg2(-20, " file=%d block=%d\n", -1, -1);
1370       }
1371    } else {
1372       stat |= BMT_ONLINE | BMT_BOT;
1373    }
1374    return stat;
1375 }
1376
1377
1378 /*
1379  * Load medium in device
1380  *  Returns: true  on success
1381  *           false on failure
1382  */
1383 bool load_dev(DEVICE *dev)
1384 {
1385 #ifdef MTLOAD
1386    struct mtop mt_com;
1387 #endif
1388
1389    if (dev->fd < 0) {
1390       dev->dev_errno = EBADF;
1391       Mmsg0(&dev->errmsg, _("Bad call to load_dev. Archive not open\n"));
1392       Emsg0(M_FATAL, 0, dev->errmsg);
1393       return false;
1394    }
1395    if (!(dev->is_tape())) {
1396       return true;
1397    }
1398 #ifndef MTLOAD
1399    Dmsg0(200, "stored: MTLOAD command not available\n");
1400    berrno be;
1401    dev->dev_errno = ENOTTY;           /* function not available */
1402    Mmsg2(&dev->errmsg, _("ioctl MTLOAD error on %s. ERR=%s.\n"),
1403          dev->dev_name, be.strerror());
1404    return false;
1405 #else
1406
1407    dev->block_num = dev->file = 0;
1408    dev->file_size = 0;
1409    dev->file_addr = 0;
1410    mt_com.mt_op = MTLOAD;
1411    mt_com.mt_count = 1;
1412    if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
1413       berrno be;
1414       dev->dev_errno = errno;
1415       Mmsg2(&dev->errmsg, _("ioctl MTLOAD error on %s. ERR=%s.\n"),
1416          dev->dev_name, be.strerror());
1417       return false;
1418    }
1419    return true;
1420 #endif
1421 }
1422
1423 /*
1424  * Rewind device and put it offline
1425  *  Returns: true  on success
1426  *           false on failure
1427  */
1428 bool offline_dev(DEVICE *dev)
1429 {
1430    struct mtop mt_com;
1431
1432    if (dev->fd < 0) {
1433       dev->dev_errno = EBADF;
1434       Mmsg0(&dev->errmsg, _("Bad call to offline_dev. Archive not open\n"));
1435       Emsg0(M_FATAL, 0, dev->errmsg);
1436       return false;
1437    }
1438    if (!(dev->is_tape())) {
1439       return true;
1440    }
1441
1442    dev->state &= ~(ST_APPEND|ST_READ|ST_EOT|ST_EOF|ST_WEOT);  /* remove EOF/EOT flags */
1443    dev->block_num = dev->file = 0;
1444    dev->file_size = 0;
1445    dev->file_addr = 0;
1446    dev->part = 0;
1447 #ifdef MTUNLOCK
1448    mt_com.mt_op = MTUNLOCK;
1449    mt_com.mt_count = 1;
1450    ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
1451 #endif
1452    mt_com.mt_op = MTOFFL;
1453    mt_com.mt_count = 1;
1454    if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
1455       berrno be;
1456       dev->dev_errno = errno;
1457       Mmsg2(&dev->errmsg, _("ioctl MTOFFL error on %s. ERR=%s.\n"),
1458          dev->dev_name, be.strerror());
1459       return false;
1460    }
1461    Dmsg1(100, "Offlined device %s\n", dev->dev_name);
1462    return true;
1463 }
1464
1465 bool offline_or_rewind_dev(DEVICE *dev)
1466 {
1467    if (dev->fd < 0) {
1468       return false;
1469    }
1470    if (dev_cap(dev, CAP_OFFLINEUNMOUNT)) {
1471       return offline_dev(dev);
1472    } else {
1473    /*
1474     * Note, this rewind probably should not be here (it wasn't
1475     *  in prior versions of Bacula), but on FreeBSD, this is
1476     *  needed in the case the tape was "frozen" due to an error
1477     *  such as backspacing after writing and EOF. If it is not
1478     *  done, all future references to the drive get and I/O error.
1479     */
1480       clrerror_dev(dev, MTREW);
1481       return rewind_dev(dev);
1482    }
1483 }
1484
1485 /*
1486  * Foward space a file
1487  *   Returns: true  on success
1488  *            false on failure
1489  */
1490 bool
1491 fsf_dev(DEVICE *dev, int num)
1492 {
1493    struct mtget mt_stat;
1494    struct mtop mt_com;
1495    int stat = 0;
1496
1497    if (dev->fd < 0) {
1498       dev->dev_errno = EBADF;
1499       Mmsg0(&dev->errmsg, _("Bad call to fsf_dev. Archive not open\n"));
1500       Emsg0(M_FATAL, 0, dev->errmsg);
1501       return false;
1502    }
1503
1504    if (!dev->is_tape()) {
1505       return true;
1506    }
1507    if (dev->state & ST_EOT) {
1508       dev->dev_errno = 0;
1509       Mmsg1(dev->errmsg, _("Device %s at End of Tape.\n"), dev->dev_name);
1510       return false;
1511    }
1512    if (dev->state & ST_EOF) {
1513       Dmsg0(200, "ST_EOF set on entry to FSF\n");
1514    }
1515
1516    Dmsg0(100, "fsf_dev\n");
1517    dev->block_num = 0;
1518    /*
1519     * If Fast forward space file is set, then we
1520     *  use MTFSF to forward space and MTIOCGET
1521     *  to get the file position. We assume that
1522     *  the SCSI driver will ensure that we do not
1523     *  forward space past the end of the medium.
1524     */
1525    if (dev_cap(dev, CAP_FSF) && dev_cap(dev, CAP_MTIOCGET) && dev_cap(dev, CAP_FASTFSF)) {
1526       mt_com.mt_op = MTFSF;
1527       mt_com.mt_count = num;
1528       stat = ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
1529       if (stat < 0 || ioctl(dev->fd, MTIOCGET, (char *)&mt_stat) < 0) {
1530          berrno be;
1531          dev->state |= ST_EOT;
1532          Dmsg0(200, "Set ST_EOT\n");
1533          clrerror_dev(dev, MTFSF);
1534          Mmsg2(dev->errmsg, _("ioctl MTFSF error on %s. ERR=%s.\n"),
1535             dev->dev_name, be.strerror());
1536          Dmsg1(200, "%s", dev->errmsg);
1537          return false;
1538       }
1539       Dmsg2(200, "fsf file=%d block=%d\n", mt_stat.mt_fileno, mt_stat.mt_blkno);
1540       dev->set_eof();
1541       dev->file = mt_stat.mt_fileno;
1542       return true;
1543
1544    /*
1545     * Here if CAP_FSF is set, and virtually all drives
1546     *  these days support it, we read a record, then forward
1547     *  space one file. Using this procedure, which is slow,
1548     *  is the only way we can be sure that we don't read
1549     *  two consecutive EOF marks, which means End of Data.
1550     */
1551    } else if (dev_cap(dev, CAP_FSF)) {
1552       POOLMEM *rbuf;
1553       int rbuf_len;
1554       Dmsg0(200, "FSF has cap_fsf\n");
1555       if (dev->max_block_size == 0) {
1556          rbuf_len = DEFAULT_BLOCK_SIZE;
1557       } else {
1558          rbuf_len = dev->max_block_size;
1559       }
1560       rbuf = get_memory(rbuf_len);
1561       mt_com.mt_op = MTFSF;
1562       mt_com.mt_count = 1;
1563       while (num-- && !(dev->state & ST_EOT)) {
1564          Dmsg0(100, "Doing read before fsf\n");
1565          if ((stat = read(dev->fd, (char *)rbuf, rbuf_len)) < 0) {
1566             if (errno == ENOMEM) {     /* tape record exceeds buf len */
1567                stat = rbuf_len;        /* This is OK */
1568             } else {
1569                berrno be;
1570                dev->state |= ST_EOT;
1571                clrerror_dev(dev, -1);
1572                Dmsg2(100, "Set ST_EOT read errno=%d. ERR=%s\n", dev->dev_errno,
1573                   be.strerror());
1574                Mmsg2(dev->errmsg, _("read error on %s. ERR=%s.\n"),
1575                   dev->dev_name, be.strerror());
1576                Dmsg1(100, "%s", dev->errmsg);
1577                break;
1578             }
1579          }
1580          if (stat == 0) {                /* EOF */
1581             update_pos_dev(dev);
1582             Dmsg1(100, "End of File mark from read. File=%d\n", dev->file+1);
1583             /* Two reads of zero means end of tape */
1584             if (dev->state & ST_EOF) {
1585                dev->state |= ST_EOT;
1586                Dmsg0(100, "Set ST_EOT\n");
1587                break;
1588             } else {
1589                dev->set_eof();
1590                continue;
1591             }
1592          } else {                        /* Got data */
1593             dev->state &= ~(ST_EOF|ST_EOT);
1594          }
1595
1596          Dmsg0(100, "Doing MTFSF\n");
1597          stat = ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
1598          if (stat < 0) {                 /* error => EOT */
1599             berrno be;
1600             dev->state |= ST_EOT;
1601             Dmsg0(100, "Set ST_EOT\n");
1602             clrerror_dev(dev, MTFSF);
1603             Mmsg2(&dev->errmsg, _("ioctl MTFSF error on %s. ERR=%s.\n"),
1604                dev->dev_name, be.strerror());
1605             Dmsg0(100, "Got < 0 for MTFSF\n");
1606             Dmsg1(100, "%s", dev->errmsg);
1607          } else {
1608             dev->set_eof();
1609          }
1610       }
1611       free_memory(rbuf);
1612
1613    /*
1614     * No FSF, so use FSR to simulate it
1615     */
1616    } else {
1617       Dmsg0(200, "Doing FSR for FSF\n");
1618       while (num-- && !(dev->state & ST_EOT)) {
1619          fsr_dev(dev, INT32_MAX);    /* returns -1 on EOF or EOT */
1620       }
1621       if (dev->state & ST_EOT) {
1622          dev->dev_errno = 0;
1623          Mmsg1(dev->errmsg, _("Device %s at End of Tape.\n"), dev->dev_name);
1624          stat = -1;
1625       } else {
1626          stat = 0;
1627       }
1628    }
1629    update_pos_dev(dev);
1630    Dmsg1(200, "Return %d from FSF\n", stat);
1631    if (dev->state & ST_EOF)
1632       Dmsg0(200, "ST_EOF set on exit FSF\n");
1633    if (dev->state & ST_EOT)
1634       Dmsg0(200, "ST_EOT set on exit FSF\n");
1635    Dmsg1(200, "Return from FSF file=%d\n", dev->file);
1636    return stat == 0;
1637 }
1638
1639 /*
1640  * Backward space a file
1641  *  Returns: false on failure
1642  *           true  on success
1643  */
1644 bool
1645 bsf_dev(DEVICE *dev, int num)
1646 {
1647    struct mtop mt_com;
1648    int stat;
1649
1650    if (dev->fd < 0) {
1651       dev->dev_errno = EBADF;
1652       Mmsg0(dev->errmsg, _("Bad call to bsf_dev. Archive device not open\n"));
1653       Emsg0(M_FATAL, 0, dev->errmsg);
1654       return false;
1655    }
1656
1657    if (!dev->is_tape()) {
1658       Mmsg1(dev->errmsg, _("Device %s cannot BSF because it is not a tape.\n"),
1659          dev->dev_name);
1660       return false;
1661    }
1662    Dmsg0(29, "bsf_dev\n");
1663    dev->state &= ~(ST_EOT|ST_EOF);
1664    dev->file -= num;
1665    dev->file_addr = 0;
1666    dev->file_size = 0;
1667    mt_com.mt_op = MTBSF;
1668    mt_com.mt_count = num;
1669    stat = ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
1670    if (stat < 0) {
1671       berrno be;
1672       clrerror_dev(dev, MTBSF);
1673       Mmsg2(dev->errmsg, _("ioctl MTBSF error on %s. ERR=%s.\n"),
1674          dev->dev_name, be.strerror());
1675    }
1676    update_pos_dev(dev);
1677    return stat == 0;
1678 }
1679
1680
1681 /*
1682  * Foward space a record
1683  *  Returns: false on failure
1684  *           true  on success
1685  */
1686 bool
1687 fsr_dev(DEVICE *dev, int num)
1688 {
1689    struct mtop mt_com;
1690    int stat;
1691
1692    if (dev->fd < 0) {
1693       dev->dev_errno = EBADF;
1694       Mmsg0(dev->errmsg, _("Bad call to fsr_dev. Archive not open\n"));
1695       Emsg0(M_FATAL, 0, dev->errmsg);
1696       return false;
1697    }
1698
1699    if (!dev->is_tape()) {
1700       return false;
1701    }
1702    if (!dev_cap(dev, CAP_FSR)) {
1703       Mmsg1(dev->errmsg, _("ioctl MTFSR not permitted on %s.\n"), dev->dev_name);
1704       return false;
1705    }
1706
1707    Dmsg1(29, "fsr_dev %d\n", num);
1708    mt_com.mt_op = MTFSR;
1709    mt_com.mt_count = num;
1710    stat = ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
1711    if (stat == 0) {
1712       dev->state &= ~ST_EOF;
1713       dev->block_num += num;
1714    } else {
1715       berrno be;
1716       struct mtget mt_stat;
1717       clrerror_dev(dev, MTFSR);
1718       Dmsg1(100, "FSF fail: ERR=%s\n", be.strerror());
1719       if (dev_cap(dev, CAP_MTIOCGET) && ioctl(dev->fd, MTIOCGET, (char *)&mt_stat) == 0 && mt_stat.mt_fileno >= 0) {
1720          Dmsg4(100, "Adjust from %d:%d to %d:%d\n", dev->file,
1721             dev->block_num, mt_stat.mt_fileno, mt_stat.mt_blkno);
1722          dev->file = mt_stat.mt_fileno;
1723          dev->block_num = mt_stat.mt_blkno;
1724       } else {
1725          if (dev->state & ST_EOF) {
1726             dev->state |= ST_EOT;
1727          } else {
1728             dev->set_eof();
1729          }
1730       }
1731       Mmsg2(dev->errmsg, _("ioctl MTFSR error on %s. ERR=%s.\n"),
1732          dev->dev_name, be.strerror());
1733    }
1734    update_pos_dev(dev);
1735    return stat == 0;
1736 }
1737
1738 /*
1739  * Backward space a record
1740  *   Returns:  false on failure
1741  *             true  on success
1742  */
1743 bool
1744 bsr_dev(DEVICE *dev, int num)
1745 {
1746    struct mtop mt_com;
1747    int stat;
1748
1749    if (dev->fd < 0) {
1750       dev->dev_errno = EBADF;
1751       Mmsg0(dev->errmsg, _("Bad call to bsr_dev. Archive not open\n"));
1752       Emsg0(M_FATAL, 0, dev->errmsg);
1753       return false;
1754    }
1755
1756    if (!dev->is_tape()) {
1757       return false;
1758    }
1759
1760    if (!dev_cap(dev, CAP_BSR)) {
1761       Mmsg1(dev->errmsg, _("ioctl MTBSR not permitted on %s.\n"), dev->dev_name);
1762       return false;
1763    }
1764
1765    Dmsg0(29, "bsr_dev\n");
1766    dev->block_num -= num;
1767    dev->state &= ~(ST_EOF|ST_EOT|ST_EOF);
1768    mt_com.mt_op = MTBSR;
1769    mt_com.mt_count = num;
1770    stat = ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
1771    if (stat < 0) {
1772       berrno be;
1773       clrerror_dev(dev, MTBSR);
1774       Mmsg2(dev->errmsg, _("ioctl MTBSR error on %s. ERR=%s.\n"),
1775          dev->dev_name, be.strerror());
1776    }
1777    update_pos_dev(dev);
1778    return stat == 0;
1779 }
1780
1781 /*
1782  * Reposition the device to file, block
1783  * Returns: false on failure
1784  *          true  on success
1785  */
1786 bool
1787 reposition_dev(DEVICE *dev, uint32_t file, uint32_t block)
1788 {
1789    if (dev->fd < 0) {
1790       dev->dev_errno = EBADF;
1791       Mmsg0(dev->errmsg, _("Bad call to reposition_dev. Archive not open\n"));
1792       Emsg0(M_FATAL, 0, dev->errmsg);
1793       return false;
1794    }
1795
1796    if (!dev->is_tape()) {
1797       off_t pos = (((off_t)file)<<32) + block;
1798       Dmsg1(100, "===== lseek_dev to %d\n", (int)pos);
1799       if (lseek_dev(dev, pos, SEEK_SET) == (off_t)-1) {
1800          berrno be;
1801          dev->dev_errno = errno;
1802          Mmsg2(dev->errmsg, _("lseek_dev error on %s. ERR=%s.\n"),
1803             dev->dev_name, be.strerror());
1804          return false;
1805       }
1806       dev->file = file;
1807       dev->block_num = block;
1808       dev->file_addr = pos;
1809       return true;
1810    }
1811    Dmsg4(100, "reposition_dev from %u:%u to %u:%u\n",
1812       dev->file, dev->block_num, file, block);
1813    if (file < dev->file) {
1814       Dmsg0(100, "Rewind_dev\n");
1815       if (!rewind_dev(dev)) {
1816          return false;
1817       }
1818    }
1819    if (file > dev->file) {
1820       Dmsg1(100, "fsf %d\n", file-dev->file);
1821       if (!fsf_dev(dev, file-dev->file)) {
1822          Dmsg1(100, "fsf failed! ERR=%s\n", strerror_dev(dev));
1823          return false;
1824       }
1825       Dmsg2(100, "wanted_file=%d at_file=%d\n", file, dev->file);
1826    }
1827    if (block < dev->block_num) {
1828       Dmsg2(100, "wanted_blk=%d at_blk=%d\n", block, dev->block_num);
1829       Dmsg0(100, "bsf_dev 1\n");
1830       bsf_dev(dev, 1);
1831       Dmsg0(100, "fsf_dev 1\n");
1832       fsf_dev(dev, 1);
1833       Dmsg2(100, "wanted_blk=%d at_blk=%d\n", block, dev->block_num);
1834    }
1835    if (dev_cap(dev, CAP_POSITIONBLOCKS) && block > dev->block_num) {
1836       /* Ignore errors as Bacula can read to the correct block */
1837       Dmsg1(100, "fsr %d\n", block-dev->block_num);
1838       return fsr_dev(dev, block-dev->block_num);
1839    }
1840    return true;
1841 }
1842
1843
1844
1845 /*
1846  * Write an end of file on the device
1847  *   Returns: 0 on success
1848  *            non-zero on failure
1849  */
1850 int
1851 weof_dev(DEVICE *dev, int num)
1852 {
1853    struct mtop mt_com;
1854    int stat;
1855    Dmsg0(29, "weof_dev\n");
1856    
1857    if (dev->fd < 0) {
1858       dev->dev_errno = EBADF;
1859       Mmsg0(dev->errmsg, _("Bad call to weof_dev. Archive drive not open\n"));
1860       Emsg0(M_FATAL, 0, dev->errmsg);
1861       return -1;
1862    }
1863    dev->file_size = 0;
1864
1865    if (!dev->is_tape()) {
1866       return 0;
1867    }
1868    if (!dev->can_append()) {
1869       Mmsg0(dev->errmsg, _("Attempt to WEOF on non-appendable Volume\n"));
1870       Emsg0(M_FATAL, 0, dev->errmsg);
1871       return -1;
1872    }
1873       
1874    dev->state &= ~(ST_EOT | ST_EOF);  /* remove EOF/EOT flags */
1875    mt_com.mt_op = MTWEOF;
1876    mt_com.mt_count = num;
1877    stat = ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
1878    if (stat == 0) {
1879       dev->block_num = 0;
1880       dev->file += num;
1881       dev->file_addr = 0;
1882    } else {
1883       berrno be;
1884       clrerror_dev(dev, MTWEOF);
1885       if (stat == -1) {
1886          Mmsg2(dev->errmsg, _("ioctl MTWEOF error on %s. ERR=%s.\n"),
1887             dev->dev_name, be.strerror());
1888        }
1889    }
1890    return stat;
1891 }
1892
1893 /*
1894  * Return string message with last error in English
1895  *  Be careful not to call this routine from within dev.c
1896  *  while editing an Mmsg() or you will end up in a recursive
1897  *  loop creating a Segmentation Violation.
1898  */
1899 char *
1900 strerror_dev(DEVICE *dev)
1901 {
1902    return dev->errmsg;
1903 }
1904
1905
1906 /*
1907  * If implemented in system, clear the tape
1908  * error status.
1909  */
1910 void
1911 clrerror_dev(DEVICE *dev, int func)
1912 {
1913    const char *msg = NULL;
1914    struct mtget mt_stat;
1915    char buf[100];
1916
1917    dev->dev_errno = errno;         /* save errno */
1918    if (errno == EIO) {
1919       dev->VolCatInfo.VolCatErrors++;
1920    }
1921
1922    if (!dev->is_tape()) {
1923       return;
1924    }
1925    if (errno == ENOTTY || errno == ENOSYS) { /* Function not implemented */
1926       switch (func) {
1927       case -1:
1928          Emsg0(M_ABORT, 0, "Got ENOTTY on read/write!\n");
1929          break;
1930       case MTWEOF:
1931          msg = "WTWEOF";
1932          dev->capabilities &= ~CAP_EOF; /* turn off feature */
1933          break;
1934 #ifdef MTEOM
1935       case MTEOM:
1936          msg = "WTEOM";
1937          dev->capabilities &= ~CAP_EOM; /* turn off feature */
1938          break;
1939 #endif
1940       case MTFSF:
1941          msg = "MTFSF";
1942          dev->capabilities &= ~CAP_FSF; /* turn off feature */
1943          break;
1944       case MTBSF:
1945          msg = "MTBSF";
1946          dev->capabilities &= ~CAP_BSF; /* turn off feature */
1947          break;
1948       case MTFSR:
1949          msg = "MTFSR";
1950          dev->capabilities &= ~CAP_FSR; /* turn off feature */
1951          break;
1952       case MTBSR:
1953          msg = "MTBSR";
1954          dev->capabilities &= ~CAP_BSR; /* turn off feature */
1955          break;
1956       case MTREW:
1957          msg = "MTREW";
1958          break;
1959 #ifdef MTSETBLK
1960       case MTSETBLK:
1961          msg = "MTSETBLK";
1962          break;
1963 #endif
1964 #ifdef MTSETBSIZ 
1965       case MTSETBSIZ:
1966          msg = "MTSETBSIZ";
1967          break;
1968 #endif
1969 #ifdef MTSRSZ
1970       case MTSRSZ:
1971          msg = "MTSRSZ";
1972          break;
1973 #endif
1974       default:
1975          bsnprintf(buf, sizeof(buf), "unknown func code %d", func);
1976          msg = buf;
1977          break;
1978       }
1979       if (msg != NULL) {
1980          dev->dev_errno = ENOSYS;
1981          Mmsg1(dev->errmsg, _("I/O function \"%s\" not supported on this device.\n"), msg);
1982          Emsg0(M_ERROR, 0, dev->errmsg);
1983       }
1984    }
1985    /* On some systems such as NetBSD, this clears all errors */
1986    ioctl(dev->fd, MTIOCGET, (char *)&mt_stat);
1987
1988 /* Found on Linux */
1989 #ifdef MTIOCLRERR
1990 {
1991    struct mtop mt_com;
1992    mt_com.mt_op = MTIOCLRERR;
1993    mt_com.mt_count = 1;
1994    /* Clear any error condition on the tape */
1995    ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
1996    Dmsg0(200, "Did MTIOCLRERR\n");
1997 }
1998 #endif
1999
2000 /* Typically on FreeBSD */
2001 #ifdef MTIOCERRSTAT
2002 {
2003    /* Read and clear SCSI error status */
2004    union mterrstat mt_errstat;
2005    Dmsg2(200, "Doing MTIOCERRSTAT errno=%d ERR=%s\n", dev->dev_errno,
2006       strerror(dev->dev_errno));
2007    ioctl(dev->fd, MTIOCERRSTAT, (char *)&mt_errstat);
2008 }
2009 #endif
2010
2011 /* Clear Subsystem Exception OSF1 */
2012 #ifdef MTCSE
2013 {
2014    struct mtop mt_com;
2015    mt_com.mt_op = MTCSE;
2016    mt_com.mt_count = 1;
2017    /* Clear any error condition on the tape */
2018    ioctl(dev->fd, MTIOCTOP, (char *)&mt_com);
2019    Dmsg0(200, "Did MTCSE\n");
2020 }
2021 #endif
2022 }
2023
2024 /*
2025  * Flush buffer contents
2026  *  No longer used.
2027  */
2028 int flush_dev(DEVICE *dev)
2029 {
2030    return 1;
2031 }
2032
2033 static void do_close(DEVICE *dev)
2034 {
2035
2036    Dmsg1(29, "really close_dev %s\n", dev->dev_name);
2037    if (dev->fd >= 0) {
2038       close(dev->fd);
2039    }
2040    if (dev_cap(dev, CAP_REQMOUNT)) {
2041       if (unmount_dev(dev, 1) < 0) {
2042          Dmsg1(0, "Cannot unmount device %s.\n", dev->dev_name);
2043       }
2044    }
2045    
2046    /* Remove the last part file if it is empty */
2047    if (dev->can_append() && (dev->num_parts > 0)) {
2048       struct stat statp;
2049       POOL_MEM archive_name(PM_FNAME);
2050       dev->part = dev->num_parts;
2051       get_filename(dev, dev->VolCatInfo.VolCatName, archive_name);
2052       /* Check that the part file is empty */
2053       if ((stat(archive_name.c_str(), &statp) == 0) && (statp.st_size == 0)) {
2054          unlink(archive_name.c_str());
2055       }
2056    }
2057    
2058    /* Clean up device packet so it can be reused */
2059    dev->fd = -1;
2060    dev->state &= ~(ST_OPENED|ST_LABEL|ST_READ|ST_APPEND|ST_EOT|ST_WEOT|ST_EOF);
2061    dev->label_type = B_BACULA_LABEL;
2062    dev->file = dev->block_num = 0;
2063    dev->file_size = 0;
2064    dev->file_addr = 0;
2065    dev->part = 0;
2066    dev->part_size = 0;
2067    dev->part_start = 0;
2068    dev->EndFile = dev->EndBlock = 0;
2069    memset(&dev->VolCatInfo, 0, sizeof(dev->VolCatInfo));
2070    memset(&dev->VolHdr, 0, sizeof(dev->VolHdr));
2071    if (dev->tid) {
2072       stop_thread_timer(dev->tid);
2073       dev->tid = 0;
2074    }
2075    dev->use_count = 0;
2076 }
2077
2078 /*
2079  * Close the device
2080  */
2081 void
2082 close_dev(DEVICE *dev)
2083 {
2084    if (!dev) {
2085       Mmsg0(&dev->errmsg, _("Bad call to close_dev. Archive not open\n"));
2086       Emsg0(M_FATAL, 0, dev->errmsg);
2087       return;
2088    }
2089    /*if (dev->fd >= 0 && dev->use_count == 1) {*/
2090    /* No need to check if dev->fd >= 0: it is checked again
2091     * in do_close, and do_close MUST be called for volumes
2092     * splitted in parts, even if dev->fd == -1. */
2093    if (dev->use_count == 1) {
2094       do_close(dev);
2095    } else if (dev->use_count > 0) {
2096       dev->use_count--;
2097    }
2098
2099 #ifdef FULL_DEBUG
2100    ASSERT(dev->use_count >= 0);
2101 #endif
2102 }
2103
2104 /*
2105  * Used when unmounting the device, ignore use_count
2106  */
2107 void force_close_dev(DEVICE *dev)
2108 {
2109    if (!dev) {
2110       Mmsg0(&dev->errmsg, _("Bad call to force_close_dev. Archive not open\n"));
2111       Emsg0(M_FATAL, 0, dev->errmsg);
2112       return;
2113    }
2114    Dmsg1(29, "Force close_dev %s\n", dev->dev_name);
2115    do_close(dev);
2116
2117 #ifdef FULL_DEBUG
2118    ASSERT(dev->use_count >= 0);
2119 #endif
2120 }
2121
2122 bool truncate_dev(DEVICE *dev)
2123 {
2124    Dmsg1(100, "truncate_dev %s\n", dev->dev_name);
2125    if (dev->is_tape()) {
2126       return true;                    /* we don't really truncate tapes */
2127       /* maybe we should rewind and write and eof ???? */
2128    }
2129    
2130    /* If there is more than one part, open the first one, and then truncate it. */
2131    if (dev->num_parts > 0) {
2132       dev->num_parts = 0;
2133       dev->VolCatInfo.VolCatParts = 0;
2134       if (open_first_part(dev) < 0) {
2135          berrno be;
2136          Mmsg1(&dev->errmsg, "Unable to truncate device, because I'm unable to open the first part. ERR=%s\n", be.strerror());
2137       }
2138    }
2139    
2140    if (ftruncate(dev->fd, 0) != 0) {
2141       berrno be;
2142       Mmsg1(&dev->errmsg, _("Unable to truncate device. ERR=%s\n"), be.strerror());
2143       return false;
2144    }
2145    return true;
2146 }
2147
2148 bool
2149 dev_is_tape(DEVICE *dev)
2150 {
2151    return dev->is_tape() ? true : false;
2152 }
2153
2154
2155 /*
2156  * return 1 if the device is read for write, and 0 otherwise
2157  *   This is meant for checking at the end of a job to see
2158  *   if we still have a tape (perhaps not if at end of tape
2159  *   and the job is canceled).
2160  */
2161 bool
2162 dev_can_write(DEVICE *dev)
2163 {
2164    if (dev->is_open() &&  dev->can_append() &&
2165        dev->is_labeled()  && !(dev->state & ST_WEOT)) {
2166       return true;
2167    } else {
2168       return false;
2169    }
2170 }
2171
2172 char *
2173 dev_name(DEVICE *dev)
2174 {
2175    return dev->dev_name;
2176 }
2177
2178 char *
2179 dev_vol_name(DEVICE *dev)
2180 {
2181    return dev->VolCatInfo.VolCatName;
2182 }
2183
2184 uint32_t dev_block(DEVICE *dev)
2185 {
2186    update_pos_dev(dev);
2187    return dev->block_num;
2188 }
2189
2190 uint32_t dev_file(DEVICE *dev)
2191 {
2192    update_pos_dev(dev);
2193    return dev->file;
2194 }
2195
2196 /*
2197  * Free memory allocated for the device
2198  */
2199 void
2200 term_dev(DEVICE *dev)
2201 {
2202    if (!dev) {
2203       dev->dev_errno = EBADF;
2204       Mmsg0(&dev->errmsg, _("Bad call to term_dev. Archive not open\n"));
2205       Emsg0(M_FATAL, 0, dev->errmsg);
2206       return;
2207    }
2208    do_close(dev);
2209    Dmsg0(29, "term_dev\n");
2210    if (dev->dev_name) {
2211       free_memory(dev->dev_name);
2212       dev->dev_name = NULL;
2213    }
2214    if (dev->errmsg) {
2215       free_pool_memory(dev->errmsg);
2216       dev->errmsg = NULL;
2217    }
2218    pthread_mutex_destroy(&dev->mutex);
2219    pthread_cond_destroy(&dev->wait);
2220    pthread_cond_destroy(&dev->wait_next_vol);
2221    pthread_mutex_destroy(&dev->spool_mutex);
2222    rwl_destroy(&dev->lock);
2223    if (dev->attached_dcrs) {
2224       delete dev->attached_dcrs;
2225       dev->attached_dcrs = NULL;
2226    }
2227    if (dev->state & ST_MALLOC) {
2228       free_pool_memory((POOLMEM *)dev);
2229    }
2230 }
2231
2232 /*
2233  * This routine initializes the device wait timers
2234  */
2235 void init_dev_wait_timers(DEVICE *dev)
2236 {
2237    /* ******FIXME******* put these on config variables */
2238    dev->min_wait = 60 * 60;
2239    dev->max_wait = 24 * 60 * 60;
2240    dev->max_num_wait = 9;              /* 5 waits =~ 1 day, then 1 day at a time */
2241    dev->wait_sec = dev->min_wait;
2242    dev->rem_wait_sec = dev->wait_sec;
2243    dev->num_wait = 0;
2244    dev->poll = false;
2245    dev->BadVolName[0] = 0;
2246 }
2247
2248 /*
2249  * Returns: true if time doubled
2250  *          false if max time expired
2251  */
2252 bool double_dev_wait_time(DEVICE *dev)
2253 {
2254    dev->wait_sec *= 2;               /* double wait time */
2255    if (dev->wait_sec > dev->max_wait) {   /* but not longer than maxtime */
2256       dev->wait_sec = dev->max_wait;
2257    }
2258    dev->num_wait++;
2259    dev->rem_wait_sec = dev->wait_sec;
2260    if (dev->num_wait >= dev->max_num_wait) {
2261       return false;
2262    }
2263    return true;
2264 }
2265
2266 void set_os_device_parameters(DEVICE *dev)
2267 {
2268 #ifdef HAVE_LINUX_OS
2269    struct mtop mt_com;
2270    if (dev->min_block_size == dev->max_block_size &&
2271        dev->min_block_size == 0) {    /* variable block mode */
2272       mt_com.mt_op = MTSETBLK;
2273       mt_com.mt_count = 0;
2274       if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
2275          clrerror_dev(dev, MTSETBLK);
2276       }
2277       mt_com.mt_op = MTSETDRVBUFFER;
2278       mt_com.mt_count = MT_ST_CLEARBOOLEANS;
2279       if (!dev_cap(dev, CAP_TWOEOF)) {
2280          mt_com.mt_count |= MT_ST_TWO_FM;
2281       }
2282       if (dev_cap(dev, CAP_EOM)) {
2283          mt_com.mt_count |= MT_ST_FAST_MTEOM;
2284       }
2285       if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
2286          clrerror_dev(dev, MTSETBLK);
2287       }
2288    }
2289    return;
2290 #endif
2291
2292 #ifdef HAVE_NETBSD_OS
2293    struct mtop mt_com;
2294    if (dev->min_block_size == dev->max_block_size &&
2295        dev->min_block_size == 0) {    /* variable block mode */
2296       mt_com.mt_op = MTSETBSIZ;
2297       mt_com.mt_count = 0;
2298       if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
2299          clrerror_dev(dev, MTSETBSIZ);
2300       }
2301       /* Get notified at logical end of tape */
2302       mt_com.mt_op = MTEWARN;
2303       mt_com.mt_count = 1;
2304       if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
2305          clrerror_dev(dev, MTEWARN);
2306       }
2307    }
2308    return;
2309 #endif
2310
2311 #if HAVE_FREEBSD_OS || HAVE_OPENBSD_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 = MTSETBSIZ;
2316       mt_com.mt_count = 0;
2317       if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
2318          clrerror_dev(dev, MTSETBSIZ);
2319       }
2320    }
2321    return;
2322 #endif
2323
2324 #ifdef HAVE_SUN_OS
2325    struct mtop mt_com;
2326    if (dev->min_block_size == dev->max_block_size &&
2327        dev->min_block_size == 0) {    /* variable block mode */
2328       mt_com.mt_op = MTSRSZ;
2329       mt_com.mt_count = 0;
2330       if (ioctl(dev->fd, MTIOCTOP, (char *)&mt_com) < 0) {
2331          clrerror_dev(dev, MTSRSZ);
2332       }
2333    }
2334    return;
2335 #endif
2336 }
2337
2338 /*
2339  * Edit codes into (Un)MountCommand, Write(First)PartCommand
2340  *  %% = %
2341  *  %a = archive device name
2342  *  %m = mount point
2343  *  %v = last part name
2344  *
2345  *  omsg = edited output message
2346  *  imsg = input string containing edit codes (%x)
2347  *
2348  */
2349 char *edit_device_codes_dev(DEVICE* dev, char *omsg, const char *imsg)
2350 {
2351    const char *p;
2352    const char *str;
2353    char add[20];
2354    
2355    POOL_MEM archive_name(PM_FNAME);
2356    get_filename(dev, dev->VolCatInfo.VolCatName, archive_name);
2357
2358    *omsg = 0;
2359    Dmsg1(800, "edit_device_codes: %s\n", imsg);
2360    for (p=imsg; *p; p++) {
2361       if (*p == '%') {
2362          switch (*++p) {
2363             case '%':
2364                str = "%";
2365                break;
2366             case 'n':
2367                bsnprintf(add, sizeof(add), "%d", dev->part);
2368                str = add;
2369                break;
2370             case 'a':
2371                str = dev->dev_name;
2372                break;
2373             case 'm':
2374                str = dev->device->mount_point;
2375                break;
2376             case 'v':
2377                str = archive_name.c_str();
2378                break;
2379             default:
2380                add[0] = '%';
2381                add[1] = *p;
2382                add[2] = 0;
2383                str = add;
2384                break;
2385          }
2386       } else {
2387          add[0] = *p;
2388          add[1] = 0;
2389          str = add;
2390       }
2391       Dmsg1(900, "add_str %s\n", str);
2392       pm_strcat(&omsg, (char *)str);
2393       Dmsg1(800, "omsg=%s\n", omsg);
2394    }
2395    return omsg;
2396 }