]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/stored/dev.c
7b54e032269a520a382da163f1f8e59d5453fae6
[bacula/bacula] / bacula / src / stored / dev.c
1 /*
2    Bacula(R) - The Network Backup Solution
3
4    Copyright (C) 2000-2016 Kern Sibbald
5
6    The original author of Bacula is Kern Sibbald, with contributions
7    from many others, a complete list can be found in the file AUTHORS.
8
9    You may use this file and others of this release according to the
10    license defined in the LICENSE file, which includes the Affero General
11    Public License, v3.0 ("AGPLv3") and some additional permissions and
12    terms pursuant to its AGPLv3 Section 7.
13
14    This notice must be preserved when any source code is 
15    conveyed and/or propagated.
16
17    Bacula(R) is a registered trademark of Kern Sibbald.
18 */
19 /*
20  *
21  *   dev.c  -- low level operations on device (storage device)
22  *
23  *     written by, Kern Sibbald, MM
24  *
25  *     NOTE!!!! None of these routines are reentrant. You must
26  *        use dev->rLock() and dev->Unlock() at a higher level,
27  *        or use the xxx_device() equivalents.  By moving the
28  *        thread synchronization to a higher level, we permit
29  *        the higher level routines to "seize" the device and
30  *        to carry out operations without worrying about who
31  *        set what lock (i.e. race conditions).
32  *
33  *     Note, this is the device dependent code, and may have
34  *           to be modified for each system, but is meant to
35  *           be as "generic" as possible.
36  *
37  *     The purpose of this code is to develop a SIMPLE Storage
38  *     daemon. More complicated coding (double buffering, writer
39  *     thread, ...) is left for a later version.
40  *
41  */
42
43 /*
44  * Handling I/O errors and end of tape conditions are a bit tricky.
45  * This is how it is currently done when writing.
46  * On either an I/O error or end of tape,
47  * we will stop writing on the physical device (no I/O recovery is
48  * attempted at least in this daemon). The state flag will be sent
49  * to include ST_EOT, which is ephemeral, and ST_WEOT, which is
50  * persistent. Lots of routines clear ST_EOT, but ST_WEOT is
51  * cleared only when the problem goes away.  Now when ST_WEOT
52  * is set all calls to write_block_to_device() call the fix_up
53  * routine. In addition, all threads are blocked
54  * from writing on the tape by calling lock_dev(), and thread other
55  * than the first thread to hit the EOT will block on a condition
56  * variable. The first thread to hit the EOT will continue to
57  * be able to read and write the tape (he sort of tunnels through
58  * the locking mechanism -- see lock_dev() for details).
59  *
60  * Now presumably somewhere higher in the chain of command
61  * (device.c), someone will notice the EOT condition and
62  * get a new tape up, get the tape label read, and mark
63  * the label for rewriting. Then this higher level routine
64  * will write the unwritten buffer to the new volume.
65  * Finally, he will release
66  * any blocked threads by doing a broadcast on the condition
67  * variable.  At that point, we should be totally back in
68  * business with no lost data.
69  */
70
71 #include "bacula.h"
72 #include "stored.h"
73
74 #ifndef O_NONBLOCK
75 #define O_NONBLOCK 0
76 #endif
77
78 /* Imported functions */
79 extern void set_os_device_parameters(DCR *dcr);
80 extern bool dev_get_os_pos(DEVICE *dev, struct mtget *mt_stat);
81 extern uint32_t status_dev(DEVICE *dev);
82
83 /* Forward referenced functions */
84 const char *mode_to_str(int mode);
85 DEVICE *m_init_dev(JCR *jcr, DEVRES *device);
86 /*
87  * Device types for printing
88  */
89 static const char *prt_dev_types[] = {
90    "*none*",
91    "file",
92    "tape",
93    "DVD",
94    "FIFO",
95    "Vtape",
96    "FTP",
97    "VTL"
98 };
99
100 /*
101  * Allocate and initialize the DEVICE structure
102  * Note, if dev is non-NULL, it is already allocated,
103  * thus we neither allocate it nor free it. This allows
104  * the caller to put the packet in shared memory.
105  *
106  *  Note, for a tape, the device->device_name is the device name
107  *     (e.g. /dev/nst0), and for a file, the device name
108  *     is the directory in which the file will be placed.
109  *
110  */
111 DEVICE *init_dev(JCR *jcr, DEVRES *device)
112 {
113    generate_global_plugin_event(bsdGlobalEventDeviceInit, device);
114    DEVICE *dev = m_init_dev(jcr, device);
115    return dev;
116 }
117
118 DEVICE *m_init_dev(JCR *jcr, DEVRES *device)
119 {
120    struct stat statp;
121    int errstat;
122    DCR *dcr = NULL;
123    DEVICE *dev = NULL;
124    uint32_t max_bs;
125
126    /* If no device type specified, try to guess */
127    if (!device->dev_type) {
128       /* Check that device is available */
129       if (stat(device->device_name, &statp) < 0) {
130          berrno be;
131          Jmsg2(jcr, M_ERROR, 0, _("Unable to stat device %s: ERR=%s\n"),
132             device->device_name, be.bstrerror());
133          return NULL;
134       }
135       if (S_ISDIR(statp.st_mode)) {
136          device->dev_type = B_FILE_DEV;
137       } else if (S_ISCHR(statp.st_mode)) {
138          device->dev_type = B_TAPE_DEV;
139       } else if (S_ISFIFO(statp.st_mode)) {
140          device->dev_type = B_FIFO_DEV;
141 #ifdef USE_VTAPE
142       /* must set DeviceType = Vtape
143        * in normal mode, autodetection is disabled
144        */
145       } else if (S_ISREG(statp.st_mode)) {
146          device->dev_type = B_VTAPE_DEV;
147 #endif
148       } else if (!(device->cap_bits & CAP_REQMOUNT)) {
149          Jmsg2(jcr, M_ERROR, 0, _("%s is an unknown device type. Must be tape or directory\n"
150                " or have RequiresMount=yes for DVD. st_mode=%x\n"),
151             device->device_name, statp.st_mode);
152          return NULL;
153       } else {
154          device->dev_type = B_DVD_DEV;
155       }
156       if (strcmp(device->device_name, "/dev/null") == 0) {
157          device->dev_type = B_NULL_DEV;
158       }
159    }
160    switch (device->dev_type) {
161    case B_DVD_DEV:
162       Jmsg0(jcr, M_FATAL, 0, _("DVD support is now deprecated.\n"));
163       return NULL;
164    case B_VTAPE_DEV:
165       dev = New(vtape);
166       break;
167 #ifdef USE_FTP
168    case B_FTP_DEV:
169       dev = New(ftp_device);
170       break;
171 #endif
172    case B_TAPE_DEV:
173       dev = New(tape_dev);
174       break;
175    case B_FILE_DEV:
176    case B_FIFO_DEV:
177    case B_NULL_DEV:
178       dev = New(file_dev);
179       break;
180    default:
181       return NULL;
182    }
183    dev->clear_slot();         /* unknown */
184
185    /* Copy user supplied device parameters from Resource */
186    dev->dev_name = get_memory(strlen(device->device_name)+1);
187    pm_strcpy(dev->dev_name, device->device_name);
188    dev->prt_name = get_memory(strlen(device->device_name) + strlen(device->hdr.name) + 20);
189    /* We edit "Resource-name" (physical-name) */
190    Mmsg(dev->prt_name, "\"%s\" (%s)", device->hdr.name, device->device_name);
191    Dmsg1(400, "Allocate dev=%s\n", dev->print_name());
192    dev->capabilities = device->cap_bits;
193    dev->min_free_space = device->min_free_space;
194    dev->min_block_size = device->min_block_size;
195    dev->max_block_size = device->max_block_size;
196    dev->max_volume_size = device->max_volume_size;
197    dev->max_file_size = device->max_file_size;
198    dev->max_concurrent_jobs = device->max_concurrent_jobs;
199    dev->volume_capacity = device->volume_capacity;
200    dev->max_rewind_wait = device->max_rewind_wait;
201    dev->max_open_wait = device->max_open_wait;
202    dev->vol_poll_interval = device->vol_poll_interval;
203    dev->max_spool_size = device->max_spool_size;
204    dev->drive_index = device->drive_index;
205    dev->enabled = device->enabled;
206    dev->autoselect = device->autoselect;
207    dev->read_only = device->read_only;
208    dev->dev_type = device->dev_type;
209    dev->device = device;
210    if (dev->is_tape()) { /* No parts on tapes */
211       dev->max_part_size = 0;
212    } else {
213       dev->max_part_size = device->max_part_size;
214    }
215    /* Sanity check */
216    if (dev->vol_poll_interval && dev->vol_poll_interval < 60) {
217       dev->vol_poll_interval = 60;
218    }
219
220    if (!device->dev) {
221       /* The first time we create a DEVICE from the DEVRES, we keep a pointer
222        * to the DEVICE accessible from the DEVRES.
223        */
224       device->dev = dev;
225    }
226
227    if (dev->is_fifo()) {
228       dev->capabilities |= CAP_STREAM; /* set stream device */
229    }
230
231    /* If the device requires mount :
232     * - Check that the mount point is available
233     * - Check that (un)mount commands are defined
234     */
235    if (dev->is_file() && dev->requires_mount()) {
236       if (!device->mount_point || stat(device->mount_point, &statp) < 0) {
237          berrno be;
238          dev->dev_errno = errno;
239          Jmsg2(jcr, M_ERROR_TERM, 0, _("Unable to stat mount point %s: ERR=%s\n"),
240             device->mount_point, be.bstrerror());
241       }
242
243       if (!device->mount_command || !device->unmount_command) {
244          Jmsg0(jcr, M_ERROR_TERM, 0, _("Mount and unmount commands must defined for a device which requires mount.\n"));
245       }
246    } 
247
248    /* Keep the device ID in the DEVICE struct to identify the hardware */
249    if (dev->is_file() && stat(dev->archive_name(), &statp) == 0) {
250          dev->devno = statp.st_dev;
251    } 
252
253    /* Sanity check */
254    if (dev->max_block_size == 0) {
255       max_bs = DEFAULT_BLOCK_SIZE;
256    } else {
257       max_bs = dev->max_block_size;
258    }
259    if (dev->min_block_size > max_bs) {
260       Jmsg(jcr, M_ERROR_TERM, 0, _("Min block size > max on device %s\n"),
261            dev->print_name());
262    }
263    if (dev->max_block_size > 4096000) {
264       Jmsg3(jcr, M_ERROR, 0, _("Block size %u on device %s is too large, using default %u\n"),
265          dev->max_block_size, dev->print_name(), DEFAULT_BLOCK_SIZE);
266       dev->max_block_size = 0;
267    }
268    if (dev->max_block_size % TAPE_BSIZE != 0) {
269       Jmsg3(jcr, M_WARNING, 0, _("Max block size %u not multiple of device %s block size=%d.\n"),
270          dev->max_block_size, dev->print_name(), TAPE_BSIZE);
271    }
272    if (dev->max_volume_size != 0 && dev->max_volume_size < (dev->max_block_size << 4)) {
273       Jmsg(jcr, M_ERROR_TERM, 0, _("Max Vol Size < 8 * Max Block Size for device %s\n"),
274            dev->print_name());
275    }
276
277    dev->errmsg = get_pool_memory(PM_EMSG);
278    *dev->errmsg = 0;
279
280    if ((errstat = dev->init_mutex()) != 0) {
281       berrno be;
282       dev->dev_errno = errstat;
283       Mmsg1(dev->errmsg, _("Unable to init mutex: ERR=%s\n"), be.bstrerror(errstat));
284       Jmsg0(jcr, M_ERROR_TERM, 0, dev->errmsg);
285    }
286    if ((errstat = pthread_cond_init(&dev->wait, NULL)) != 0) {
287       berrno be;
288       dev->dev_errno = errstat;
289       Mmsg1(dev->errmsg, _("Unable to init cond variable: ERR=%s\n"), be.bstrerror(errstat));
290       Jmsg0(jcr, M_ERROR_TERM, 0, dev->errmsg);
291    }
292    if ((errstat = pthread_cond_init(&dev->wait_next_vol, NULL)) != 0) {
293       berrno be;
294       dev->dev_errno = errstat;
295       Mmsg1(dev->errmsg, _("Unable to init cond variable: ERR=%s\n"), be.bstrerror(errstat));
296       Jmsg0(jcr, M_ERROR_TERM, 0, dev->errmsg);
297    }
298    if ((errstat = pthread_mutex_init(&dev->spool_mutex, NULL)) != 0) {
299       berrno be;
300       dev->dev_errno = errstat;
301       Mmsg1(dev->errmsg, _("Unable to init spool mutex: ERR=%s\n"), be.bstrerror(errstat));
302       Jmsg0(jcr, M_ERROR_TERM, 0, dev->errmsg);
303    }
304    if ((errstat = dev->init_acquire_mutex()) != 0) {
305       berrno be;
306       dev->dev_errno = errstat;
307       Mmsg1(dev->errmsg, _("Unable to init acquire mutex: ERR=%s\n"), be.bstrerror(errstat));
308       Jmsg0(jcr, M_ERROR_TERM, 0, dev->errmsg);
309    }
310    if ((errstat = dev->init_freespace_mutex()) != 0) {
311       berrno be;
312       dev->dev_errno = errstat;
313       Mmsg1(dev->errmsg, _("Unable to init freespace mutex: ERR=%s\n"), be.bstrerror(errstat));
314       Jmsg0(jcr, M_ERROR_TERM, 0, dev->errmsg);
315    }
316    if ((errstat = dev->init_read_acquire_mutex()) != 0) {
317       berrno be;
318       dev->dev_errno = errstat;
319       Mmsg1(dev->errmsg, _("Unable to init read acquire mutex: ERR=%s\n"), be.bstrerror(errstat));
320       Jmsg0(jcr, M_ERROR_TERM, 0, dev->errmsg);
321    }
322    if ((errstat = dev->init_volcat_mutex()) != 0) {
323       berrno be;
324       dev->dev_errno = errstat;
325       Mmsg1(dev->errmsg, _("Unable to init volcat mutex: ERR=%s\n"), be.bstrerror(errstat));
326       Jmsg0(jcr, M_ERROR_TERM, 0, dev->errmsg);
327    }
328    if ((errstat = dev->init_dcrs_mutex()) != 0) {
329       berrno be;
330       dev->dev_errno = errstat;
331       Mmsg1(dev->errmsg, _("Unable to init dcrs mutex: ERR=%s\n"), be.bstrerror(errstat));
332       Jmsg0(jcr, M_ERROR_TERM, 0, dev->errmsg);
333    }
334
335    dev->set_mutex_priorities();
336
337 #ifdef xxx
338    if ((errstat = rwl_init(&dev->lock)) != 0) {
339       berrno be;
340       dev->dev_errno = errstat;
341       Mmsg1(dev->errmsg, _("Unable to init mutex: ERR=%s\n"), be.bstrerror(errstat));
342       Jmsg0(jcr, M_ERROR_TERM, 0, dev->errmsg);
343    }
344 #endif
345
346    dev->clear_opened();
347    dev->attached_dcrs = New(dlist(dcr, &dcr->dev_link));
348    Dmsg2(100, "init_dev: tape=%d dev_name=%s\n", dev->is_tape(), dev->dev_name);
349    dev->initiated = true;
350
351    return dev;
352 }
353
354 /*
355  * Open the device with the operating system and
356  * initialize buffer pointers.
357  *
358  * Returns:  true on success
359  *           false on error
360  *
361  * Note, for a tape, the VolName is the name we give to the
362  *    volume (not really used here), but for a file, the
363  *    VolName represents the name of the file to be created/opened.
364  *    In the case of a file, the full name is the device name
365  *    (archive_name) with the VolName concatenated.
366  */
367 bool DEVICE::open(DCR *dcr, int omode)
368 {
369    int preserve = 0;
370    if (is_open()) {
371       if (openmode == omode) {
372          return true;
373       } else {
374          Dmsg1(200, "Close fd=%d for mode change in open().\n", m_fd);
375          d_close(m_fd);
376          clear_opened();
377          preserve = state & (ST_LABEL|ST_APPEND|ST_READ);
378       }
379    }
380    if (dcr) {
381       dcr->setVolCatName(dcr->VolumeName);
382       VolCatInfo = dcr->VolCatInfo;    /* structure assign */
383    }
384
385    state &= ~(ST_NOSPACE|ST_LABEL|ST_APPEND|ST_READ|ST_EOT|ST_WEOT|ST_EOF);
386    label_type = B_BACULA_LABEL;
387
388    if (is_tape() || is_fifo()) {
389       open_tape_device(dcr, omode);
390    } else if (is_ftp()) {
391       open_device(dcr, omode);
392    } else {
393       Dmsg1(100, "call open_file_device mode=%s\n", mode_to_str(omode));
394       open_file_device(dcr, omode);
395    }
396    state |= preserve;                 /* reset any important state info */
397    Dmsg2(100, "preserve=0x%x fd=%d\n", preserve, m_fd);
398
399    Dmsg7(100, "open dev: fd=%d dev=%p dcr=%p vol=%s type=%d dev_name=%s mode=%s\n",
400          m_fd, getVolCatName(), this, dcr, dev_type, print_name(), mode_to_str(omode));
401    return m_fd >= 0;
402 }
403
404 void DEVICE::set_mode(int new_mode)
405 {
406    switch (new_mode) {
407    case CREATE_READ_WRITE:
408       mode = O_CREAT | O_RDWR | O_BINARY;
409       break;
410    case OPEN_READ_WRITE:
411       mode = O_RDWR | O_BINARY;
412       break;
413    case OPEN_READ_ONLY:
414       mode = O_RDONLY | O_BINARY;
415       break;
416    case OPEN_WRITE_ONLY:
417       mode = O_WRONLY | O_BINARY;
418       break;
419    default:
420       Emsg0(M_ABORT, 0, _("Illegal mode given to open dev.\n"));
421    }
422 }
423
424
425 void DEVICE::open_device(DCR *dcr, int omode)
426 {
427    /* do nothing waiting to split open_file/tape_device */
428 }
429
430
431 /*
432  * Called to indicate that we have just read an
433  *  EOF from the device.
434  */
435 void DEVICE::set_ateof()
436 {
437    set_eof();
438    if (is_tape()) {
439       file++;
440    }
441    file_addr = 0;
442    file_size = 0;
443    block_num = 0;
444 }
445
446 /*
447  * Called to indicate we are now at the end of the tape, and
448  *   writing is not possible.
449  */
450 void DEVICE::set_ateot()
451 {
452    /* Make tape effectively read-only */
453    Dmsg0(200, "==== Set AtEof\n");
454    state |= (ST_EOF|ST_EOT|ST_WEOT);
455    clear_append();
456 }
457
458
459 /*
460  * Set the position of the device -- only for files and DVD
461  *   For other devices, there is no generic way to do it.
462  *  Returns: true  on succes
463  *           false on error
464  */
465 bool DEVICE::update_pos(DCR *dcr)
466 {
467    boffset_t pos;
468    bool ok = true;
469
470    if (!is_open()) {
471       dev_errno = EBADF;
472       Mmsg0(errmsg, _("Bad device call. Device not open\n"));
473       Emsg1(M_FATAL, 0, "%s", errmsg);
474       return false;
475    }
476
477    if (is_file()) {
478       file = 0;
479       file_addr = 0;
480       pos = lseek(dcr, (boffset_t)0, SEEK_CUR);
481       if (pos < 0) {
482          berrno be;
483          dev_errno = errno;
484          Pmsg1(000, _("Seek error: ERR=%s\n"), be.bstrerror());
485          Mmsg2(errmsg, _("lseek error on %s. ERR=%s.\n"),
486                print_name(), be.bstrerror());
487          ok = false;
488       } else {
489          file_addr = pos;
490          block_num = (uint32_t)pos;
491          file = (uint32_t)(pos >> 32);
492       }
493    }
494    return ok;
495 }
496
497 void DEVICE::set_slot(int32_t slot)
498 {
499    m_slot = slot;
500    if (vol) vol->clear_slot();
501 }
502
503 void DEVICE::clear_slot()
504 {
505    m_slot = -1;
506    if (vol) vol->set_slot(-1);
507 }
508
509 const char *DEVICE::print_type() const
510 {
511    return prt_dev_types[device->dev_type];
512 }
513
514 /*
515  * Set to unload the current volume in the drive
516  */
517 void DEVICE::set_unload()
518 {
519    if (!m_unload && VolHdr.VolumeName[0] != 0) {
520        m_unload = true;
521        memcpy(UnloadVolName, VolHdr.VolumeName, sizeof(UnloadVolName));
522        notify_newvol_in_attached_dcrs(NULL);
523    }
524 }
525
526 /*
527  * Clear volume header
528  */
529 void DEVICE::clear_volhdr()
530 {
531    Dmsg1(100, "Clear volhdr vol=%s\n", VolHdr.VolumeName);
532    memset(&VolHdr, 0, sizeof(VolHdr));
533    setVolCatInfo(false);
534 }
535
536 void DEVICE::set_nospace()
537 {
538    state |= ST_NOSPACE;
539 }
540
541 void DEVICE::clear_nospace()
542 {
543    state &= ~ST_NOSPACE;
544 }
545
546 /* Put device in append mode */
547 void DEVICE::set_append()
548 {
549    state &= ~(ST_NOSPACE|ST_READ|ST_EOT|ST_EOF|ST_WEOT);  /* remove EOF/EOT flags */
550    state |= ST_APPEND;
551 }
552
553 /* Clear append mode */
554 void DEVICE::clear_append()
555 {
556    state &= ~ST_APPEND;
557 }
558
559 /* Put device in read mode */
560 void DEVICE::set_read()
561 {
562    state &= ~(ST_APPEND|ST_EOT|ST_EOF|ST_WEOT);  /* remove EOF/EOT flags */
563    state |= ST_READ;
564 }
565
566 /* Clear read mode */
567 void DEVICE::clear_read()
568 {
569    state &= ~ST_READ;
570 }
571
572 /*
573  * Get freespace using OS calls
574  * TODO: See if it's working with mount commands
575  */
576 bool DEVICE::get_os_device_freespace()
577 {
578    int64_t freespace, totalspace;
579
580    if (!is_file()) {
581       return true;
582    }
583    if (fs_get_free_space(dev_name, &freespace, &totalspace) == 0) {
584       set_freespace(freespace,  totalspace, 0, true);
585       Mmsg(errmsg, "");
586       return true;
587
588    } else {
589       set_freespace(0, 0, 0, false); /* No valid freespace */
590    }
591    return false;
592 }
593
594 /* Update the free space on the device */
595 bool DEVICE::update_freespace()
596 {
597    POOL_MEM ocmd(PM_FNAME);
598    POOLMEM* results;
599    char* icmd;
600    char* p;
601    uint64_t free, total;
602    char ed1[50];
603    bool ok = false;
604    int status;
605    berrno be;
606
607    if (!is_file()) {
608       Mmsg(errmsg, "");
609       return true;
610    }
611
612    /* The device must be mounted in order for freespace to work */
613    if (requires_mount()) {
614       mount(1);
615    }
616
617    if (get_os_device_freespace()) {
618       Dmsg4(20, "get_os_device_freespace: free_space=%s freespace_ok=%d free_space_errno=%d have_media=%d\n",
619          edit_uint64(free_space, ed1), !!is_freespace_ok(), free_space_errno, !!have_media());
620       return true;
621    }
622
623    icmd = device->free_space_command;
624
625    if (!icmd) {
626       set_freespace(0, 0, 0, false);
627       Dmsg2(20, "ERROR: update_free_space_dev: free_space=%s, free_space_errno=%d (!icmd)\n",
628             edit_uint64(free_space, ed1), free_space_errno);
629       Mmsg(errmsg, _("No FreeSpace command defined.\n"));
630       return false;
631    }
632
633    edit_mount_codes(ocmd, icmd);
634
635    Dmsg1(20, "update_freespace: cmd=%s\n", ocmd.c_str());
636
637    results = get_pool_memory(PM_MESSAGE);
638
639    Dmsg1(20, "Run freespace prog=%s\n", ocmd.c_str());
640    status = run_program_full_output(ocmd.c_str(), max_open_wait/2, results);
641    Dmsg2(20, "Freespace status=%d result=%s\n", status, results);
642    /* Should report "1223232 12323232\n"  "free  total\n" */
643    if (status == 0) {
644       free = str_to_int64(results) * 1024;
645       p = results;
646
647       if (skip_nonspaces(&p)) {
648          total = str_to_int64(p) * 1024;
649
650       } else {
651          total = 0;
652       }
653
654       Dmsg1(400, "Free space program run: Freespace=%s\n", results);
655       if (free >= 0) {
656          set_freespace(free, total, 0, true); /* have valid freespace */
657          Mmsg(errmsg, "");
658          ok = true;
659       }
660    } else {
661       set_freespace(0, 0, EPIPE, false); /* no valid freespace */
662       Mmsg2(errmsg, _("Cannot run free space command. Results=%s ERR=%s\n"),
663             results, be.bstrerror(status));
664
665       dev_errno = free_space_errno;
666       Dmsg4(20, "Cannot get free space on device %s. free_space=%s, "
667          "free_space_errno=%d ERR=%s\n",
668             print_name(), edit_uint64(free_space, ed1),
669             free_space_errno, errmsg);
670    }
671    free_pool_memory(results);
672    Dmsg4(20, "leave update_freespace: free_space=%s freespace_ok=%d free_space_errno=%d have_media=%d\n",
673       edit_uint64(free_space, ed1), !!is_freespace_ok(), free_space_errno, !!have_media());
674    return ok;
675 }
676
677 void DEVICE::updateVolCatBytes(uint64_t bytes)
678 {
679    DEVICE *dev = this;
680    Lock_VolCatInfo();
681    dev->VolCatInfo.VolCatAmetaBytes += bytes;
682    Dmsg1(200, "updateVolBytes ameta=%lld\n",
683       dev->VolCatInfo.VolCatAmetaBytes);
684    dev->VolCatInfo.VolCatBytes += bytes;
685    setVolCatInfo(false);
686    Unlock_VolCatInfo();
687 }
688
689 void DEVICE::updateVolCatBlocks(uint32_t blocks)
690 {
691    DEVICE *dev = this;
692    Lock_VolCatInfo();
693    dev->VolCatInfo.VolCatAmetaBlocks += blocks;
694    dev->VolCatInfo.VolCatBlocks += blocks;
695    setVolCatInfo(false);
696    Unlock_VolCatInfo();
697 }
698
699
700 void DEVICE::updateVolCatWrites(uint32_t writes)
701 {
702    DEVICE *dev = this;
703    Lock_VolCatInfo();
704    dev->VolCatInfo.VolCatAmetaWrites += writes;
705    dev->VolCatInfo.VolCatWrites += writes;
706    setVolCatInfo(false);
707    Unlock_VolCatInfo();
708 }
709
710 void DEVICE::updateVolCatReads(uint32_t reads)
711 {
712    DEVICE *dev = this;
713    Lock_VolCatInfo();
714    dev->VolCatInfo.VolCatAmetaReads += reads;
715    dev->VolCatInfo.VolCatReads += reads;
716    setVolCatInfo(false);
717    Unlock_VolCatInfo();
718 }
719
720 void DEVICE::updateVolCatReadBytes(uint64_t bytes)
721 {
722    DEVICE *dev = this;
723    Lock_VolCatInfo();
724    dev->VolCatInfo.VolCatAmetaRBytes += bytes;
725    dev->VolCatInfo.VolCatRBytes += bytes;
726    setVolCatInfo(false);
727    Unlock_VolCatInfo();
728 }
729
730 /*
731  * Close the device
732  */
733 bool DEVICE::close()
734 {
735    bool ok = true;
736
737    Dmsg4(40, "close_dev vol=%s fd=%d dev=%p dev=%s\n",
738       VolHdr.VolumeName, m_fd, this, print_name());
739    offline_or_rewind();
740
741    if (!is_open()) {
742       Dmsg2(200, "device %s already closed vol=%s\n", print_name(),
743          VolHdr.VolumeName);
744       return true;                    /* already closed */
745    }
746
747    switch (dev_type) {
748    case B_VTL_DEV:
749    case B_VTAPE_DEV:
750    case B_TAPE_DEV:
751       unlock_door();
752       /* Fall through wanted */
753    default:
754       if (d_close(m_fd) != 0) {
755          berrno be;
756          dev_errno = errno;
757          Mmsg2(errmsg, _("Error closing device %s. ERR=%s.\n"),
758                print_name(), be.bstrerror());
759          ok = false;
760       }
761       break; 
762    }
763
764    unmount(1);                       /* do unmount if required */
765  
766    /* Clean up device packet so it can be reused */
767    clear_opened();
768
769    /*
770     * Be careful not to clear items needed by the DVD driver
771     *    when it is closing a single part.
772     */
773    state &= ~(ST_LABEL|ST_READ|ST_APPEND|ST_EOT|ST_WEOT|ST_EOF|
774               ST_NOSPACE|ST_MOUNTED|ST_MEDIA|ST_SHORT);
775    label_type = B_BACULA_LABEL;
776    file = block_num = 0;
777    file_size = 0;
778    file_addr = 0;
779    EndFile = EndBlock = 0;
780    openmode = 0;
781    clear_volhdr();
782    memset(&VolCatInfo, 0, sizeof(VolCatInfo));
783    if (tid) {
784       stop_thread_timer(tid);
785       tid = 0;
786    }
787    return ok;
788 }
789
790 /*
791  * This call closes the device, but it is used in DVD handling
792  *  where we close one part and then open the next part. The
793  *  difference between close_part() and close() is that close_part()
794  *  saves the state information of the device (e.g. the Volume lable,
795  *  the Volume Catalog record, ...  This permits opening and closing
796  *  the Volume parts multiple times without losing track of what the
797  *  main Volume parameters are.
798  */
799 void DEVICE::close_part(DCR * /*dcr*/)
800 {
801    VOLUME_LABEL saveVolHdr;
802    VOLUME_CAT_INFO saveVolCatInfo;     /* Volume Catalog Information */
803
804
805    saveVolHdr = VolHdr;               /* structure assignment */
806    saveVolCatInfo = VolCatInfo;       /* structure assignment */
807    close();                           /* close current part */
808    VolHdr = saveVolHdr;               /* structure assignment */
809    VolCatInfo = saveVolCatInfo;       /* structure assignment */
810 }
811
812 /* 
813  * If timeout, wait until the mount command returns 0.
814  * If !timeout, try to mount the device only once.
815  */
816 bool DEVICE::mount(int timeout)
817 {
818    Dmsg0(190, "Enter mount\n");
819    if (!is_mounted() && device->mount_command) {
820       return mount_file(1, timeout);
821    } 
822    return true;
823 }
824
825 /* 
826  * Unmount the device 
827  * If timeout, wait until the unmount command returns 0.
828  * If !timeout, try to unmount the device only once.
829  */
830 bool DEVICE::unmount(int timeout)
831 {
832    Dmsg0(100, "Enter unmount\n");
833    if (is_mounted() && requires_mount() && device->unmount_command) {
834       return mount_file(0, timeout);
835    } 
836    return true;
837 }
838
839
840 /*
841  * Edit codes into (Un)MountCommand, Write(First)PartCommand
842  *  %% = %
843  *  %a = archive device name
844  *  %e = erase (set if cannot mount and first part)
845  *  %n = part number
846  *  %m = mount point
847  *  %v = last part name
848  *
849  *  omsg = edited output message
850  *  imsg = input string containing edit codes (%x)
851  *
852  */
853 void DEVICE::edit_mount_codes(POOL_MEM &omsg, const char *imsg)
854 {
855    const char *p;
856    const char *str;
857    char add[20];
858
859    POOL_MEM archive_name(PM_FNAME);
860
861    omsg.c_str()[0] = 0;
862    Dmsg1(800, "edit_mount_codes: %s\n", imsg);
863    for (p=imsg; *p; p++) {
864       if (*p == '%') {
865          switch (*++p) {
866          case '%':
867             str = "%";
868             break;
869          case 'a':
870             str = dev_name;
871             break;
872          case 'e':
873             if (num_dvd_parts == 0) {
874                if (truncating || blank_dvd) {
875                   str = "2";
876                } else {
877                   str = "1";
878                }
879             } else {
880                str = "0";
881             }
882             break;
883          case 'n':
884             bsnprintf(add, sizeof(add), "%d", part);
885             str = add;
886             break;
887          case 'm':
888             str = device->mount_point;
889             break;
890          default:
891             add[0] = '%';
892             add[1] = *p;
893             add[2] = 0;
894             str = add;
895             break;
896          }
897       } else {
898          add[0] = *p;
899          add[1] = 0;
900          str = add;
901       }
902       Dmsg1(1900, "add_str %s\n", str);
903       pm_strcat(omsg, (char *)str);
904       Dmsg1(1800, "omsg=%s\n", omsg.c_str());
905    }
906 }
907
908 /* return the last timer interval (ms)
909  * or 0 if something goes wrong
910  */
911 btime_t DEVICE::get_timer_count()
912 {
913    btime_t temp = last_timer;
914    last_timer = get_current_btime();
915    temp = last_timer - temp;   /* get elapsed time */
916    return (temp>0)?temp:0;     /* take care of skewed clock */
917 }
918
919 /* read from fd */
920 ssize_t DEVICE::read(void *buf, size_t len)
921 {
922    ssize_t read_len ;
923
924    get_timer_count();
925
926    read_len = d_read(m_fd, buf, len);
927
928    last_tick = get_timer_count();
929
930    DevReadTime += last_tick;
931    VolCatInfo.VolReadTime += last_tick;
932
933    if (read_len > 0) {          /* skip error */
934       DevReadBytes += read_len;
935    }
936
937    return read_len;
938 }
939
940 /* write to fd */
941 ssize_t DEVICE::write(const void *buf, size_t len)
942 {
943    ssize_t write_len ;
944
945    get_timer_count();
946
947    write_len = d_write(m_fd, buf, len);
948
949    last_tick = get_timer_count();
950
951    DevWriteTime += last_tick;
952    VolCatInfo.VolWriteTime += last_tick;
953
954    if (write_len > 0) {         /* skip error */
955       DevWriteBytes += write_len;
956    }
957
958    return write_len;
959 }
960
961 /* Return the resource name for the device */
962 const char *DEVICE::name() const
963 {
964    return device->hdr.name;
965 }
966
967 uint32_t DEVICE::get_file()
968 {
969    if (is_dvd() || is_tape()) {
970       return file;
971    } else {
972       uint64_t bytes = VolCatInfo.VolCatAdataBytes + VolCatInfo.VolCatAmetaBytes;
973       return (uint32_t)(bytes >> 32);
974    }
975 }
976
977 uint32_t DEVICE::get_block_num()
978 {
979    if (is_dvd() || is_tape()) {
980       return block_num;
981    } else {
982       return  VolCatInfo.VolCatAdataBlocks + VolCatInfo.VolCatAmetaBlocks;
983    }
984 }
985
986 /*
987  * Walk through all attached jcrs indicating the volume has changed
988  *   Note: If you have the new VolumeName, it is passed here,
989  *     otherwise pass a NULL.
990  */
991 void
992 DEVICE::notify_newvol_in_attached_dcrs(const char *newVolumeName)
993 {
994    Dmsg2(140, "Notify dcrs of vol change. oldVolume=%s NewVolume=%s\n",
995       getVolCatName(), newVolumeName?"*None*":newVolumeName);
996    Lock_dcrs();
997    DCR *mdcr;
998    foreach_dlist(mdcr, attached_dcrs) {
999       if (mdcr->jcr->JobId == 0) {
1000          continue;                 /* ignore console */
1001       }
1002       mdcr->NewVol = true;
1003       mdcr->NewFile = true;
1004       if (newVolumeName && mdcr->VolumeName != newVolumeName) {
1005          bstrncpy(mdcr->VolumeName, newVolumeName, sizeof(mdcr->VolumeName));
1006          Dmsg2(140, "Set NewVol=%s in JobId=%d\n", mdcr->VolumeName, mdcr->jcr->JobId);
1007       }
1008    }
1009    Unlock_dcrs();
1010 }
1011
1012 /*
1013  * Walk through all attached jcrs indicating the File has changed
1014  */
1015 void
1016 DEVICE::notify_newfile_in_attached_dcrs()
1017 {
1018    Dmsg1(140, "Notify dcrs of file change. Volume=%s\n", getVolCatName());
1019    Lock_dcrs();
1020    DCR *mdcr;
1021    foreach_dlist(mdcr, attached_dcrs) {
1022       if (mdcr->jcr->JobId == 0) {
1023          continue;                 /* ignore console */
1024       }
1025       Dmsg1(140, "Notify JobI=%d\n", mdcr->jcr->JobId);
1026       mdcr->NewFile = true;
1027    }
1028    Unlock_dcrs();
1029 }
1030
1031
1032
1033 /*
1034  * Free memory allocated for the device
1035  */
1036 void DEVICE::term(void)
1037 {
1038    DEVICE *dev = NULL;
1039    Dmsg1(900, "term dev: %s\n", print_name());
1040    close();
1041    if (dev_name) {
1042       free_memory(dev_name);
1043       dev_name = NULL;
1044    }
1045    if (prt_name) {
1046       free_memory(prt_name);
1047       prt_name = NULL;
1048    }
1049    if (errmsg) {
1050       free_pool_memory(errmsg);
1051       errmsg = NULL;
1052    }
1053    pthread_mutex_destroy(&m_mutex);
1054    pthread_cond_destroy(&wait);
1055    pthread_cond_destroy(&wait_next_vol);
1056    pthread_mutex_destroy(&spool_mutex);
1057    pthread_mutex_destroy(&freespace_mutex);
1058    if (attached_dcrs) {
1059       delete attached_dcrs;
1060       attached_dcrs = NULL;
1061    }
1062    /* We let the DEVRES pointer if not our device */
1063    if (device && device->dev == this) {
1064       device->dev = NULL;
1065    }
1066    delete this;
1067    if (dev) {
1068       dev->term();
1069    }
1070 }
1071
1072 /* Get freespace values */
1073 void DEVICE::get_freespace(uint64_t *freeval, uint64_t *totalval)
1074 {
1075    get_os_device_freespace();
1076    P(freespace_mutex);
1077    if (is_freespace_ok()) {
1078       *freeval = free_space;
1079       *totalval = total_space;
1080    } else {
1081       *freeval = *totalval = 0;
1082    }
1083    V(freespace_mutex);
1084 }
1085
1086 /* Set freespace values */
1087 void DEVICE::set_freespace(uint64_t freeval, uint64_t totalval, int errnoval, bool valid)
1088 {
1089    P(freespace_mutex);
1090    free_space = freeval;
1091    total_space = totalval;
1092    free_space_errno = errnoval;
1093    if (valid) {
1094       set_freespace_ok();
1095    } else {
1096       clear_freespace_ok();
1097    }
1098    V(freespace_mutex);
1099 }
1100
1101 /*
1102  * This routine initializes the device wait timers
1103  */
1104 void init_device_wait_timers(DCR *dcr)
1105 {
1106    DEVICE *dev = dcr->dev;
1107    JCR *jcr = dcr->jcr;
1108
1109    /* ******FIXME******* put these on config variables */
1110    dev->min_wait = 60 * 60;
1111    dev->max_wait = 24 * 60 * 60;
1112    dev->max_num_wait = 9;              /* 5 waits =~ 1 day, then 1 day at a time */
1113    dev->wait_sec = dev->min_wait;
1114    dev->rem_wait_sec = dev->wait_sec;
1115    dev->num_wait = 0;
1116    dev->poll = false;
1117
1118    jcr->min_wait = 60 * 60;
1119    jcr->max_wait = 24 * 60 * 60;
1120    jcr->max_num_wait = 9;              /* 5 waits =~ 1 day, then 1 day at a time */
1121    jcr->wait_sec = jcr->min_wait;
1122    jcr->rem_wait_sec = jcr->wait_sec;
1123    jcr->num_wait = 0;
1124
1125 }
1126
1127 void init_jcr_device_wait_timers(JCR *jcr)
1128 {
1129    /* ******FIXME******* put these on config variables */
1130    jcr->min_wait = 60 * 60;
1131    jcr->max_wait = 24 * 60 * 60;
1132    jcr->max_num_wait = 9;              /* 5 waits =~ 1 day, then 1 day at a time */
1133    jcr->wait_sec = jcr->min_wait;
1134    jcr->rem_wait_sec = jcr->wait_sec;
1135    jcr->num_wait = 0;
1136 }
1137
1138
1139 /*
1140  * The dev timers are used for waiting on a particular device
1141  *
1142  * Returns: true if time doubled
1143  *          false if max time expired
1144  */
1145 bool double_dev_wait_time(DEVICE *dev)
1146 {
1147    dev->wait_sec *= 2;               /* double wait time */
1148    if (dev->wait_sec > dev->max_wait) {   /* but not longer than maxtime */
1149       dev->wait_sec = dev->max_wait;
1150    }
1151    dev->num_wait++;
1152    dev->rem_wait_sec = dev->wait_sec;
1153    if (dev->num_wait >= dev->max_num_wait) {
1154       return false;
1155    }
1156    return true;
1157 }
1158
1159 static const char *modes[] = {
1160    "CREATE_READ_WRITE",
1161    "OPEN_READ_WRITE",
1162    "OPEN_READ_ONLY",
1163    "OPEN_WRITE_ONLY"
1164 };
1165
1166
1167 const char *mode_to_str(int mode)
1168 {
1169    static char buf[100];
1170    if (mode < 1 || mode > 4) {
1171       bsnprintf(buf, sizeof(buf), "BAD mode=%d", mode);
1172       return buf;
1173     }
1174    return modes[mode-1];
1175 }