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