]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/stored/askdir.c
Add more DCRs
[bacula/bacula] / bacula / src / stored / askdir.c
1 /*
2  *  Subroutines to handle Catalog reqests sent to the Director
3  *   Reqests/commands from the Director are handled in dircmd.c
4  *
5  *   Kern Sibbald, December 2000
6  *
7  *   Version $Id$
8  */
9 /*
10    Copyright (C) 2000-2004 Kern Sibbald and John Walker
11
12    This program is free software; you can redistribute it and/or
13    modify it under the terms of the GNU General Public License as
14    published by the Free Software Foundation; either version 2 of
15    the License, or (at your option) any later version.
16
17    This program is distributed in the hope that it will be useful,
18    but WITHOUT ANY WARRANTY; without even the implied warranty of
19    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20    General Public License for more details.
21
22    You should have received a copy of the GNU General Public
23    License along with this program; if not, write to the Free
24    Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
25    MA 02111-1307, USA.
26
27  */
28
29 #include "bacula.h"                   /* pull in global headers */
30 #include "stored.h"                   /* pull in Storage Deamon headers */
31
32 /* Requests sent to the Director */
33 static char Find_media[]   = "CatReq Job=%s FindMedia=%d\n";
34 static char Get_Vol_Info[] = "CatReq Job=%s GetVolInfo VolName=%s write=%d\n";
35 static char Update_media[] = "CatReq Job=%s UpdateMedia VolName=%s"
36    " VolJobs=%u VolFiles=%u VolBlocks=%u VolBytes=%s VolMounts=%u"
37    " VolErrors=%u VolWrites=%u MaxVolBytes=%s EndTime=%d VolStatus=%s"
38    " Slot=%d relabel=%d InChanger=%d VolReadTime=%s VolWriteTime=%s\n";
39 static char Create_job_media[] = "CatReq Job=%s CreateJobMedia" 
40    " FirstIndex=%u LastIndex=%u StartFile=%u EndFile=%u" 
41    " StartBlock=%u EndBlock=%u\n";
42 static char FileAttributes[] = "UpdCat Job=%s FileAttributes ";
43 static char Job_status[]     = "3012 Job %s jobstatus %d\n";
44
45
46 /* Responses received from the Director */
47 static char OK_media[] = "1000 OK VolName=%127s VolJobs=%u VolFiles=%u"
48    " VolBlocks=%u VolBytes=%" lld " VolMounts=%u VolErrors=%u VolWrites=%u"
49    " MaxVolBytes=%" lld " VolCapacityBytes=%" lld " VolStatus=%20s"
50    " Slot=%d MaxVolJobs=%u MaxVolFiles=%u InChanger=%d"
51    " VolReadTime=%" lld " VolWriteTime=%" lld;
52
53
54 static char OK_create[] = "1000 OK CreateJobMedia\n";
55
56 /* Forward referenced functions */
57 static int wait_for_sysop(JCR *jcr, DEVICE *dev);
58
59 /*
60  * Send current JobStatus to Director
61  */
62 int dir_send_job_status(JCR *jcr)
63 {
64    return bnet_fsend(jcr->dir_bsock, Job_status, jcr->Job, jcr->JobStatus);
65 }
66
67 /*
68  * Common routine for:
69  *   dir_get_volume_info()
70  * and
71  *   dir_find_next_appendable_volume()
72  * 
73  *  Returns: 1 on success and vol info in jcr->VolCatInfo
74  *           0 on failure
75  */
76 static int do_get_volume_info(JCR *jcr)
77 {
78     BSOCK *dir = jcr->dir_bsock;
79     DCR *dcr = jcr->dcr;
80     VOLUME_CAT_INFO vol;
81     int n;
82     int InChanger;
83
84     jcr->VolumeName[0] = 0;           /* No volume */
85     dcr->VolumeName[0] = 0;           /* No volume */
86     if (bnet_recv(dir) <= 0) {
87        Dmsg0(200, "getvolname error bnet_recv\n");
88        Mmsg(&jcr->errmsg, _("Network error on bnet_recv in req_vol_info.\n"));
89        return 0;
90     }
91     memset(&vol, 0, sizeof(vol));
92     Dmsg1(200, "Get vol info=%s\n", dir->msg);
93     n = sscanf(dir->msg, OK_media, vol.VolCatName, 
94                &vol.VolCatJobs, &vol.VolCatFiles,
95                &vol.VolCatBlocks, &vol.VolCatBytes,
96                &vol.VolCatMounts, &vol.VolCatErrors,
97                &vol.VolCatWrites, &vol.VolCatMaxBytes,
98                &vol.VolCatCapacityBytes, vol.VolCatStatus,
99                &vol.Slot, &vol.VolCatMaxJobs, &vol.VolCatMaxFiles,
100                &InChanger, &vol.VolReadTime, &vol.VolWriteTime);
101     if (n != 17) {
102        Dmsg2(100, "Bad response from Dir fields=%d: %s\n", n, dir->msg);
103        Mmsg(&jcr->errmsg, _("Error getting Volume info: %s\n"), dir->msg);
104        return 0;
105     }
106     vol.InChanger = InChanger;        /* bool in structure */
107     unbash_spaces(vol.VolCatName);
108     pm_strcpy(&jcr->VolumeName, vol.VolCatName); /* set desired VolumeName */
109     bstrncpy(dcr->VolumeName, vol.VolCatName, sizeof(dcr->VolumeName));
110     memcpy(&jcr->VolCatInfo, &vol, sizeof(jcr->VolCatInfo));
111     memcpy(&dcr->VolCatInfo, &vol, sizeof(dcr->VolCatInfo));
112     
113     Dmsg2(200, "do_reqest_vol_info got slot=%d Volume=%s\n", 
114           vol.Slot, vol.VolCatName);
115     return 1;
116 }
117
118
119 /*
120  * Get Volume info for a specific volume from the Director's Database
121  *
122  * Returns: 1 on success   (not Director guarantees that Pool and MediaType
123  *                          are correct and VolStatus==Append or
124  *                          VolStatus==Recycle)
125  *          0 on failure
126  *
127  *          Volume information returned in jcr
128  */
129 int dir_get_volume_info(JCR *jcr, enum get_vol_info_rw writing)
130 {
131     BSOCK *dir = jcr->dir_bsock;
132
133     bstrncpy(jcr->VolCatInfo.VolCatName, jcr->VolumeName, sizeof(jcr->VolCatInfo.VolCatName));
134     Dmsg1(200, "dir_get_volume_info=%s\n", jcr->VolCatInfo.VolCatName);
135     bash_spaces(jcr->VolCatInfo.VolCatName);
136     bnet_fsend(dir, Get_Vol_Info, jcr->Job, jcr->VolCatInfo.VolCatName, 
137        writing==GET_VOL_INFO_FOR_WRITE?1:0);
138     return do_get_volume_info(jcr);
139 }
140
141
142
143 /*
144  * Get info on the next appendable volume in the Director's database
145  * Returns: 1 on success
146  *          0 on failure
147  *
148  *          Volume information returned in jcr
149  *
150  */
151 int dir_find_next_appendable_volume(JCR *jcr)
152 {
153     BSOCK *dir = jcr->dir_bsock;
154     JCR *njcr;
155
156     Dmsg0(200, "dir_find_next_appendable_volume\n");
157     for (int vol_index=1;  vol_index < 3; vol_index++) {
158        bnet_fsend(dir, Find_media, jcr->Job, vol_index);
159        if (do_get_volume_info(jcr)) {
160           Dmsg2(200, "JobId=%d got possible Vol=%s\n", jcr->JobId, jcr->VolumeName);
161           bool found = false;
162           /* 
163            * Walk through all jobs and see if the volume is   
164            *  already mounted. If so, try a different one.
165            * This would be better done by walking through  
166            *  all the devices.
167            */
168           lock_jcr_chain();
169           foreach_jcr(njcr) {
170              if (jcr == njcr) {
171                 free_locked_jcr(njcr);
172                 continue;             /* us */
173              }
174              Dmsg2(200, "Compare to JobId=%d using Vol=%s\n", njcr->JobId, njcr->VolumeName);
175              if (strcmp(jcr->VolumeName, njcr->VolumeName) == 0) {
176                 found = true;
177                 Dmsg1(200, "Vol in use by JobId=%u\n", njcr->JobId);
178                 free_locked_jcr(njcr);
179                 break;
180              }
181              free_locked_jcr(njcr);
182           }
183           unlock_jcr_chain();
184           if (!found) {
185              Dmsg0(200, "dir_find_next_appendable_volume return true\n");
186              return true;             /* Got good Volume */
187           }
188        } else {
189           Dmsg0(200, "No volume info, return false\n");
190           return false;
191        }
192     }
193     Dmsg0(200, "dir_find_next_appendable_volume return true\n");
194     return true; 
195 }
196
197     
198 /*
199  * After writing a Volume, send the updated statistics
200  * back to the director. The information comes from the
201  * dev record.     
202  */
203 int dir_update_volume_info(JCR *jcr, DEVICE *dev, int label)
204 {
205    BSOCK *dir = jcr->dir_bsock;
206    time_t LastWritten = time(NULL);
207    char ed1[50], ed2[50], ed3[50], ed4[50];
208    VOLUME_CAT_INFO *vol = &dev->VolCatInfo;
209    int InChanger;
210
211    if (vol->VolCatName[0] == 0) {
212       Jmsg0(jcr, M_ERROR, 0, _("NULL Volume name. This shouldn't happen!!!\n"));
213       return 0;
214    }
215    if (dev_state(dev, ST_READ)) {
216       Jmsg0(jcr, M_ERROR, 0, _("Attempt to update_volume_info in read mode!!!\n"));
217       return 0;
218    }
219
220    Dmsg1(100, "Update cat VolFiles=%d\n", dev->file);
221    /* Just labeled or relabeled the tape */
222    if (label) {
223       bstrncpy(vol->VolCatStatus, "Append", sizeof(vol->VolCatStatus));
224       vol->VolCatBytes = 1;           /* indicates tape labeled */
225    }
226    bash_spaces(vol->VolCatName);
227    InChanger = vol->InChanger;
228    bnet_fsend(dir, Update_media, jcr->Job, 
229       vol->VolCatName, vol->VolCatJobs, vol->VolCatFiles,
230       vol->VolCatBlocks, edit_uint64(vol->VolCatBytes, ed1),
231       vol->VolCatMounts, vol->VolCatErrors,
232       vol->VolCatWrites, edit_uint64(vol->VolCatMaxBytes, ed2), 
233       LastWritten, vol->VolCatStatus, vol->Slot, label,
234       InChanger,                      /* bool in structure */
235       edit_uint64(vol->VolReadTime, ed3), 
236       edit_uint64(vol->VolWriteTime, ed4) );
237
238    Dmsg1(120, "update_volume_info(): %s", dir->msg);
239    unbash_spaces(vol->VolCatName);
240
241    if (!do_get_volume_info(jcr)) {
242       Jmsg(jcr, M_ERROR, 0, "%s", jcr->errmsg);
243       return 0;
244    }
245    Dmsg1(120, "get_volume_info(): %s", dir->msg);
246    /* Update dev Volume info in case something changed (e.g. expired) */
247    memcpy(&dev->VolCatInfo, &jcr->VolCatInfo, sizeof(dev->VolCatInfo));
248    return 1;
249 }
250
251 /*
252  * After writing a Volume, create the JobMedia record.
253  */
254 int dir_create_jobmedia_record(JCR *jcr)
255 {
256    BSOCK *dir = jcr->dir_bsock;
257    DCR *dcr = jcr->dcr;
258
259    if (!dcr->WroteVol) {
260       return 1;                       /* nothing written to tape */
261    }
262
263    dcr->WroteVol = false;
264    bnet_fsend(dir, Create_job_media, jcr->Job, 
265       dcr->VolFirstIndex, dcr->VolLastIndex,
266       dcr->StartFile, dcr->EndFile,
267       dcr->StartBlock, dcr->EndBlock);
268    Dmsg1(100, "create_jobmedia(): %s", dir->msg);
269    if (bnet_recv(dir) <= 0) {
270       Dmsg0(190, "create_jobmedia error bnet_recv\n");
271       Jmsg(jcr, M_ERROR, 0, _("Error creating JobMedia record: ERR=%s\n"), 
272            bnet_strerror(dir));
273       return 0;
274    }
275    Dmsg1(120, "Create_jobmedia: %s", dir->msg);
276    if (strcmp(dir->msg, OK_create) != 0) {
277       Dmsg1(130, "Bad response from Dir: %s\n", dir->msg);
278       Jmsg(jcr, M_ERROR, 0, _("Error creating JobMedia record: %s\n"), dir->msg);
279       return 0;
280    }
281    return 1;
282 }
283
284
285 /* 
286  * Update File Attribute data
287  */
288 int dir_update_file_attributes(JCR *jcr, DEV_RECORD *rec)
289 {
290    BSOCK *dir = jcr->dir_bsock;
291    ser_declare;
292
293    dir->msglen = sprintf(dir->msg, FileAttributes, jcr->Job);
294    dir->msg = check_pool_memory_size(dir->msg, dir->msglen + 
295                 sizeof(DEV_RECORD) + rec->data_len);
296    ser_begin(dir->msg + dir->msglen, 0);
297    ser_uint32(rec->VolSessionId);
298    ser_uint32(rec->VolSessionTime);
299    ser_int32(rec->FileIndex);
300    ser_int32(rec->Stream);
301    ser_uint32(rec->data_len);
302    ser_bytes(rec->data, rec->data_len);
303    dir->msglen = ser_length(dir->msg);
304    return bnet_send(dir);
305 }
306
307
308 /*
309  *   Request the sysop to create an appendable volume
310  *
311  *   Entered with device blocked.
312  *   Leaves with device blocked.
313  *
314  *   Returns: 1 on success (operator issues a mount command)
315  *            0 on failure
316  *              Note, must create dev->errmsg on error return.
317  *
318  *    On success, jcr->VolumeName and jcr->VolCatInfo contain
319  *      information on suggested volume, but this may not be the
320  *      same as what is actually mounted.
321  *
322  *    When we return with success, the correct tape may or may not
323  *      actually be mounted. The calling routine must read it and
324  *      verify the label.
325  */
326 int dir_ask_sysop_to_create_appendable_volume(JCR *jcr, DEVICE *dev)
327 {
328    int stat = 0, jstat;
329    bool unmounted;
330    bool first = true;
331
332    Dmsg0(130, "enter dir_ask_sysop_to_create_appendable_volume\n");
333    ASSERT(dev->dev_blocked);
334    for ( ;; ) {
335       if (job_canceled(jcr)) {
336          Mmsg(&dev->errmsg,
337               _("Job %s canceled while waiting for mount on Storage Device \"%s\".\n"), 
338               jcr->Job, jcr->dev_name);
339          Jmsg(jcr, M_INFO, 0, "%s", dev->errmsg);
340          return 0;
341       }
342       /* First pass, we *know* there are no appendable volumes, so no need to call */
343       if (!first && dir_find_next_appendable_volume(jcr)) { /* get suggested volume */
344          unmounted = (dev->dev_blocked == BST_UNMOUNTED) ||
345                      (dev->dev_blocked == BST_UNMOUNTED_WAITING_FOR_SYSOP);
346          /*
347           * If we have a valid volume name and we are not
348           *   removable media, return now, or if we have a
349           *   Slot for an autochanger, otherwise wait
350           *   for the operator to mount the media.
351           */
352          if (!unmounted && ((jcr->VolumeName[0] && !dev_cap(dev, CAP_REM) && 
353                 dev_cap(dev, CAP_LABEL)) ||
354                  (jcr->VolumeName[0] && jcr->VolCatInfo.Slot))) {
355             Dmsg0(100, "Return 1 from mount without wait.\n");
356             return 1;
357          }
358          jstat = JS_WaitMount;
359          if (!dev->poll) {
360             Jmsg(jcr, M_MOUNT, 0, _(
361 "Please mount Volume \"%s\" on Storage Device \"%s\" for Job %s\n"
362 "Use \"mount\" command to release Job.\n"),
363               jcr->VolumeName, jcr->dev_name, jcr->Job);
364             Dmsg3(190, "Mount %s on %s for Job %s\n",
365                   jcr->VolumeName, jcr->dev_name, jcr->Job);
366          }
367       } else {
368          jstat = JS_WaitMedia;
369          if (!dev->poll) {
370             Jmsg(jcr, M_MOUNT, 0, _(
371 "Job %s waiting. Cannot find any appendable volumes.\n\
372 Please use the \"label\"  command to create a new Volume for:\n\
373     Storage:      %s\n\
374     Media type:   %s\n\
375     Pool:         %s\n"),
376                jcr->Job, 
377                jcr->dev_name, 
378                jcr->media_type,
379                jcr->pool_name);
380          }
381       }
382       first = false;
383
384       jcr->JobStatus = jstat;
385       dir_send_job_status(jcr);
386
387       stat = wait_for_sysop(jcr, dev);
388       if (dev->poll) {
389          Dmsg1(200, "Poll timeout in create append vol on device %s\n", dev_name(dev));
390          continue;
391       }
392
393       if (stat == ETIMEDOUT) {
394          if (!double_dev_wait_time(dev)) {
395             Mmsg(&dev->errmsg, _("Gave up waiting to mount Storage Device \"%s\" for Job %s\n"), 
396                dev_name(dev), jcr->Job);
397             Jmsg(jcr, M_FATAL, 0, "%s", dev->errmsg);
398             Dmsg1(190, "Gave up waiting on device %s\n", dev_name(dev));
399             return 0;                 /* exceeded maximum waits */
400          }
401          continue;
402       }
403       if (stat == EINVAL) {
404          Mmsg2(&dev->errmsg, _("pthread error in mount_next_volume stat=%d ERR=%s\n"),
405                stat, strerror(stat));
406          Jmsg(jcr, M_FATAL, 0, "%s", dev->errmsg);
407          return 0;
408       }
409       if (stat != 0) {
410          Jmsg(jcr, M_WARNING, 0, _("pthread error in mount_next_volume stat=%d ERR=%s\n"), stat,
411             strerror(stat));
412       }
413       Dmsg1(190, "Someone woke me for device %s\n", dev_name(dev));
414
415       /* If no VolumeName, and cannot get one, try again */
416       if (jcr->VolumeName[0] == 0 && !job_canceled(jcr) &&
417           !dir_find_next_appendable_volume(jcr)) {
418          Jmsg(jcr, M_MOUNT, 0, _(
419 "Someone woke me up, but I cannot find any appendable\n\
420 volumes for Job=%s.\n"), jcr->Job);
421          /* Restart wait counters after user interaction */
422          init_dev_wait_timers(dev);
423          continue;
424       }       
425       unmounted = (dev->dev_blocked == BST_UNMOUNTED) ||
426                   (dev->dev_blocked == BST_UNMOUNTED_WAITING_FOR_SYSOP);
427       if (unmounted) {
428          continue;                    /* continue to wait */
429       }
430
431       /*
432        * Device mounted, we have a volume, break and return   
433        */
434       break;
435    }
436    set_jcr_job_status(jcr, JS_Running);
437    dir_send_job_status(jcr);
438    Dmsg0(130, "leave dir_ask_sysop_to_mount_create_appendable_volume\n");
439    return 1;
440 }
441
442 /*
443  *   Request to mount specific Volume
444  *
445  *   Entered with device blocked and jcr->VolumeName is desired
446  *      volume.
447  *   Leaves with device blocked.
448  *
449  *   Returns: 1 on success (operator issues a mount command)
450  *            0 on failure
451  *              Note, must create dev->errmsg on error return.
452  *
453  */
454 int dir_ask_sysop_to_mount_volume(JCR *jcr, DEVICE *dev)
455 {
456    int stat = 0;
457    const char *msg;
458
459    Dmsg0(130, "enter dir_ask_sysop_to_mount_volume\n");
460    if (!jcr->VolumeName[0]) {
461       Mmsg0(&dev->errmsg, _("Cannot request another volume: no volume name given.\n"));
462       return 0;
463    }
464    ASSERT(dev->dev_blocked);
465    for ( ;; ) {
466       if (job_canceled(jcr)) {
467          Mmsg(&dev->errmsg, _("Job %s canceled while waiting for mount on Storage Device \"%s\".\n"), 
468               jcr->Job, jcr->dev_name);
469          return 0;
470       }
471
472 #ifdef needed
473       /*
474        * If we have a valid volume name and we are not
475        *   removable media, return now, or if we have a
476        *   Slot for an autochanger, otherwise wait
477        *   for the operator to mount the media.
478        */
479       if ((!dev_cap(dev, CAP_REM) && dev_cap(dev, CAP_LABEL)) || jcr->VolCatInfo.Slot) {
480          Dmsg0(100, "Return 1 from mount without wait.\n");
481          return 1;
482       }
483 #endif
484
485       if (!dev->poll) {
486          msg = _("Please mount");
487          Jmsg(jcr, M_MOUNT, 0, _("%s Volume \"%s\" on Storage Device \"%s\" for Job %s\n"),
488               msg, jcr->VolumeName, jcr->dev_name, jcr->Job);
489          Dmsg3(190, "Mount %s on %s for Job %s\n",
490                jcr->VolumeName, jcr->dev_name, jcr->Job);
491       }
492
493       jcr->JobStatus = JS_WaitMount;
494       dir_send_job_status(jcr);
495
496       stat = wait_for_sysop(jcr, dev);     /* wait on device */
497       if (dev->poll) {
498          Dmsg1(200, "Poll timeout in mount vol on device %s\n", dev_name(dev));
499          Dmsg1(200, "Blocked=%d\n", dev->dev_blocked);
500          return 1;
501       }
502
503       if (stat == ETIMEDOUT) {
504          if (!double_dev_wait_time(dev)) {
505             Mmsg(&dev->errmsg, _("Gave up waiting to mount Storage Device \"%s\" for Job %s\n"), 
506                dev_name(dev), jcr->Job);
507             Jmsg(jcr, M_FATAL, 0, "%s", dev->errmsg);
508             Dmsg1(190, "Gave up waiting on device %s\n", dev_name(dev));
509             return 0;                 /* exceeded maximum waits */
510          }
511          continue;
512       }
513       if (stat == EINVAL) {
514          Mmsg2(&dev->errmsg, _("pthread error in mount_volume stat=%d ERR=%s\n"),
515                stat, strerror(stat));
516          Jmsg(jcr, M_FATAL, 0, "%s", dev->errmsg);
517          return 0;
518       }
519       if (stat != 0) {
520          Jmsg(jcr, M_ERROR, 0, _("pthread error in mount_next_volume stat=%d ERR=%s\n"), stat,
521             strerror(stat));
522       }
523       Dmsg1(190, "Someone woke me for device %s\n", dev_name(dev));
524       break;
525    }
526    set_jcr_job_status(jcr, JS_Running);
527    dir_send_job_status(jcr);
528    Dmsg0(130, "leave dir_ask_sysop_to_mount_volume\n");
529    return 1;
530 }
531
532 /*
533  * Wait for SysOp to mount a tape
534  */
535 static int wait_for_sysop(JCR *jcr, DEVICE *dev)
536 {
537    struct timeval tv;
538    struct timezone tz;
539    struct timespec timeout;
540    time_t last_heartbeat = 0;
541    time_t first_start = time(NULL);
542    int stat = 0;
543    int add_wait;
544    bool unmounted;
545    
546    P(dev->mutex);
547    unmounted = (dev->dev_blocked == BST_UNMOUNTED) ||
548                 (dev->dev_blocked == BST_UNMOUNTED_WAITING_FOR_SYSOP);
549
550    dev->poll = false;
551    /*
552     * Wait requested time (dev->rem_wait_sec).  However, we also wake up every
553     *    HB_TIME seconds and send a heartbeat to the FD and the Director
554     *    to keep stateful firewalls from closing them down while waiting
555     *    for the operator.
556     */
557    add_wait = dev->rem_wait_sec;
558    if (me->heartbeat_interval && add_wait > me->heartbeat_interval) {
559       add_wait = me->heartbeat_interval;
560    }
561    if (!unmounted && dev->vol_poll_interval && add_wait > dev->vol_poll_interval) {
562       add_wait = dev->vol_poll_interval;
563    }
564    gettimeofday(&tv, &tz);
565    timeout.tv_nsec = tv.tv_usec * 1000;
566    timeout.tv_sec = tv.tv_sec + add_wait;
567
568    if (!unmounted) {
569       dev->dev_prev_blocked = dev->dev_blocked;
570       dev->dev_blocked = BST_WAITING_FOR_SYSOP; /* indicate waiting for mount */
571    }
572
573    for ( ; !job_canceled(jcr); ) {
574       time_t now, start;
575
576       Dmsg3(100, "I'm going to sleep on device %s. HB=%d wait=%d\n", dev_name(dev),
577          (int)me->heartbeat_interval, dev->wait_sec);
578       start = time(NULL);
579       stat = pthread_cond_timedwait(&dev->wait_next_vol, &dev->mutex, &timeout);
580       Dmsg1(100, "Wokeup from sleep on device stat=%d\n", stat);
581
582       now = time(NULL);
583       dev->rem_wait_sec -= (now - start);
584
585       /* Note, this always triggers the first time. We want that. */
586       if (me->heartbeat_interval) {
587          if (now - last_heartbeat >= me->heartbeat_interval) {
588             /* send heartbeats */
589             if (jcr->file_bsock) {
590                bnet_sig(jcr->file_bsock, BNET_HEARTBEAT);
591                Dmsg0(100, "Send heartbeat to FD.\n");
592             }
593             if (jcr->dir_bsock) {
594                bnet_sig(jcr->dir_bsock, BNET_HEARTBEAT);
595             }
596             last_heartbeat = now;
597          }
598       }
599
600       /*
601        * Check if user unmounted the device while we were waiting
602        */
603       unmounted = (dev->dev_blocked == BST_UNMOUNTED) ||
604                    (dev->dev_blocked == BST_UNMOUNTED_WAITING_FOR_SYSOP);
605
606       if (stat != ETIMEDOUT) {     /* we blocked the device */
607          break;                    /* on error return */
608       }
609       if (dev->rem_wait_sec <= 0) {  /* on exceeding wait time return */
610          Dmsg0(100, "Exceed wait time.\n");
611          break;
612       }
613       
614       if (!unmounted && dev->vol_poll_interval &&       
615           (now - first_start >= dev->vol_poll_interval)) {
616          Dmsg1(200, "In wait blocked=%d\n", dev->dev_blocked);
617          dev->poll = true;
618          break;
619       }
620       /*
621        * Check if user mounted the device while we were waiting
622        */
623       if (dev->dev_blocked == BST_MOUNT) {   /* mount request ? */
624          stat = 0;
625          break;
626       }
627
628       add_wait = dev->wait_sec - (now - start);
629       if (add_wait < 0) {
630          add_wait = 0;
631       }
632       if (me->heartbeat_interval && add_wait > me->heartbeat_interval) {
633          add_wait = me->heartbeat_interval;
634       }
635       gettimeofday(&tv, &tz);
636       timeout.tv_nsec = tv.tv_usec * 1000;
637       timeout.tv_sec = tv.tv_sec + add_wait; /* additional wait */
638       Dmsg1(100, "Additional wait %d sec.\n", add_wait);
639    }
640
641    if (!unmounted) {
642       dev->dev_blocked = dev->dev_prev_blocked;    /* restore entry state */
643    }
644    V(dev->mutex);
645    return stat;
646 }