]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/stored/askdir.c
Remove debug EndFile debug code
[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 " EndFile=%u EndBlock=%u";
52
53
54 static char OK_create[] = "1000 OK CreateJobMedia\n";
55
56 /* Forward referenced functions */
57 static int wait_for_sysop(DCR *dcr);
58
59 /*
60  * Send current JobStatus to Director
61  */
62 bool 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: true  on success and vol info in dcr->VolCatInfo
74  *           false on failure
75  */
76 static bool do_get_volume_info(DCR *dcr)
77 {
78     JCR *jcr = dcr->jcr;
79     BSOCK *dir = jcr->dir_bsock;
80     VOLUME_CAT_INFO vol;
81     int n;
82     int InChanger;
83
84     dcr->VolumeName[0] = 0;           /* No volume */
85     if (bnet_recv(dir) <= 0) {
86        Dmsg0(200, "getvolname error bnet_recv\n");
87        Mmsg(jcr->errmsg, _("Network error on bnet_recv in req_vol_info.\n"));
88        return false;
89     }
90     memset(&vol, 0, sizeof(vol));
91     Dmsg1(200, "Get vol info=%s\n", dir->msg);
92     n = sscanf(dir->msg, OK_media, vol.VolCatName, 
93                &vol.VolCatJobs, &vol.VolCatFiles,
94                &vol.VolCatBlocks, &vol.VolCatBytes,
95                &vol.VolCatMounts, &vol.VolCatErrors,
96                &vol.VolCatWrites, &vol.VolCatMaxBytes,
97                &vol.VolCatCapacityBytes, vol.VolCatStatus,
98                &vol.Slot, &vol.VolCatMaxJobs, &vol.VolCatMaxFiles,
99                &InChanger, &vol.VolReadTime, &vol.VolWriteTime,
100                &vol.EndFile, &vol.EndBlock);
101     if (n != 19) {
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 false;
105     }
106     vol.InChanger = InChanger;        /* bool in structure */
107     unbash_spaces(vol.VolCatName);
108     bstrncpy(dcr->VolumeName, vol.VolCatName, sizeof(dcr->VolumeName));
109     memcpy(&dcr->VolCatInfo, &vol, sizeof(dcr->VolCatInfo));
110     
111     Dmsg2(200, "do_reqest_vol_info got slot=%d Volume=%s\n", 
112           vol.Slot, vol.VolCatName);
113     return true;
114 }
115
116
117 /*
118  * Get Volume info for a specific volume from the Director's Database
119  *
120  * Returns: true  on success   (not Director guarantees that Pool and MediaType
121  *                             are correct and VolStatus==Append or
122  *                             VolStatus==Recycle)
123  *          false on failure
124  *
125  *          Volume information returned in jcr
126  */
127 bool dir_get_volume_info(DCR *dcr, enum get_vol_info_rw writing)
128 {
129     JCR *jcr = dcr->jcr;
130     BSOCK *dir = jcr->dir_bsock;
131
132     bstrncpy(dcr->VolCatInfo.VolCatName, dcr->VolumeName, sizeof(dcr->VolCatInfo.VolCatName));
133     Dmsg1(200, "dir_get_volume_info=%s\n", dcr->VolCatInfo.VolCatName);
134     bash_spaces(dcr->VolCatInfo.VolCatName);
135     bnet_fsend(dir, Get_Vol_Info, jcr->Job, dcr->VolCatInfo.VolCatName, 
136        writing==GET_VOL_INFO_FOR_WRITE?1:0);
137     return do_get_volume_info(dcr);
138 }
139
140
141
142 /*
143  * Get info on the next appendable volume in the Director's database
144  * Returns: true  on success
145  *          false on failure
146  *
147  *          Volume information returned in jcr
148  *
149  */
150 bool dir_find_next_appendable_volume(DCR *dcr)
151 {
152     JCR *jcr = dcr->jcr;
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(dcr)) {
160           Dmsg2(200, "JobId=%d got possible Vol=%s\n", jcr->JobId, dcr->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->dcr->VolumeName);
175              if (njcr->dcr && strcmp(dcr->VolumeName, njcr->dcr->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 bool dir_update_volume_info(DCR *dcr, bool label)
204 {
205    JCR *jcr = dcr->jcr;
206    BSOCK *dir = jcr->dir_bsock;
207    DEVICE *dev = dcr->dev;
208    time_t LastWritten = time(NULL);
209    char ed1[50], ed2[50], ed3[50], ed4[50];
210    VOLUME_CAT_INFO *vol = &dev->VolCatInfo;
211    int InChanger;
212
213    if (vol->VolCatName[0] == 0) {
214       Jmsg0(jcr, M_FATAL, 0, _("NULL Volume name. This shouldn't happen!!!\n"));
215       return false;
216    }
217    if (dev_state(dev, ST_READ)) {
218       Jmsg0(jcr, M_FATAL, 0, _("Attempt to update_volume_info in read mode!!!\n"));
219       return false;
220    }
221
222    Dmsg1(100, "Update cat VolFiles=%d\n", dev->file);
223    /* Just labeled or relabeled the tape */
224    if (label) {
225       bstrncpy(vol->VolCatStatus, "Append", sizeof(vol->VolCatStatus));
226       vol->VolCatBytes = 1;           /* indicates tape labeled */
227    }
228    bash_spaces(vol->VolCatName);
229    InChanger = vol->InChanger;
230    bnet_fsend(dir, Update_media, jcr->Job, 
231       vol->VolCatName, vol->VolCatJobs, vol->VolCatFiles,
232       vol->VolCatBlocks, edit_uint64(vol->VolCatBytes, ed1),
233       vol->VolCatMounts, vol->VolCatErrors,
234       vol->VolCatWrites, edit_uint64(vol->VolCatMaxBytes, ed2), 
235       LastWritten, vol->VolCatStatus, vol->Slot, label,
236       InChanger,                      /* bool in structure */
237       edit_uint64(vol->VolReadTime, ed3), 
238       edit_uint64(vol->VolWriteTime, ed4) );
239
240    Dmsg1(120, "update_volume_info(): %s", dir->msg);
241    unbash_spaces(vol->VolCatName);
242
243    if (!do_get_volume_info(dcr)) {
244       Jmsg(jcr, M_FATAL, 0, "%s", jcr->errmsg);
245       return false;
246    }
247    Dmsg1(120, "get_volume_info(): %s", dir->msg);
248    /* Update dev Volume info in case something changed (e.g. expired) */
249    memcpy(&dev->VolCatInfo, &dcr->VolCatInfo, sizeof(dev->VolCatInfo));
250    return true;
251 }
252
253 /*
254  * After writing a Volume, create the JobMedia record.
255  */
256 bool dir_create_jobmedia_record(DCR *dcr)
257 {
258    JCR *jcr = dcr->jcr;
259    BSOCK *dir = jcr->dir_bsock;
260
261    if (!dcr->WroteVol) {
262       return true;                    /* nothing written to tape */
263    }
264
265    dcr->WroteVol = false;
266    bnet_fsend(dir, Create_job_media, jcr->Job, 
267       dcr->VolFirstIndex, dcr->VolLastIndex,
268       dcr->StartFile, dcr->EndFile,
269       dcr->StartBlock, dcr->EndBlock);
270    Dmsg1(100, "create_jobmedia(): %s", dir->msg);
271    if (bnet_recv(dir) <= 0) {
272       Dmsg0(190, "create_jobmedia error bnet_recv\n");
273       Jmsg(jcr, M_FATAL, 0, _("Error creating JobMedia record: ERR=%s\n"), 
274            bnet_strerror(dir));
275       return false;
276    }
277    Dmsg1(120, "Create_jobmedia: %s", dir->msg);
278    if (strcmp(dir->msg, OK_create) != 0) {
279       Dmsg1(130, "Bad response from Dir: %s\n", dir->msg);
280       Jmsg(jcr, M_FATAL, 0, _("Error creating JobMedia record: %s\n"), dir->msg);
281       return false;
282    }
283    return true;
284 }
285
286
287 /* 
288  * Update File Attribute data
289  */
290 bool dir_update_file_attributes(DCR *dcr, DEV_RECORD *rec)
291 {
292    JCR *jcr = dcr->jcr;
293    BSOCK *dir = jcr->dir_bsock;
294    ser_declare;
295
296    dir->msglen = sprintf(dir->msg, FileAttributes, jcr->Job);
297    dir->msg = check_pool_memory_size(dir->msg, dir->msglen + 
298                 sizeof(DEV_RECORD) + rec->data_len);
299    ser_begin(dir->msg + dir->msglen, 0);
300    ser_uint32(rec->VolSessionId);
301    ser_uint32(rec->VolSessionTime);
302    ser_int32(rec->FileIndex);
303    ser_int32(rec->Stream);
304    ser_uint32(rec->data_len);
305    ser_bytes(rec->data, rec->data_len);
306    dir->msglen = ser_length(dir->msg);
307    return bnet_send(dir);
308 }
309
310
311 /*
312  *   Request the sysop to create an appendable volume
313  *
314  *   Entered with device blocked.
315  *   Leaves with device blocked.
316  *
317  *   Returns: true  on success (operator issues a mount command)
318  *            false on failure
319  *              Note, must create dev->errmsg on error return.
320  *
321  *    On success, dcr->VolumeName and dcr->VolCatInfo contain
322  *      information on suggested volume, but this may not be the
323  *      same as what is actually mounted.
324  *
325  *    When we return with success, the correct tape may or may not
326  *      actually be mounted. The calling routine must read it and
327  *      verify the label.
328  */
329 bool dir_ask_sysop_to_create_appendable_volume(DCR *dcr)
330 {
331    int stat = 0, jstat;
332    bool unmounted;
333    bool first = true;
334    DEVICE *dev = dcr->dev;
335    JCR *jcr = dcr->jcr;
336
337    Dmsg0(200, "enter dir_ask_sysop_to_create_appendable_volume\n");
338    ASSERT(dev->dev_blocked);
339    for ( ;; ) {
340       if (job_canceled(jcr)) {
341          Mmsg(dev->errmsg,
342               _("Job %s canceled while waiting for mount on Storage Device \"%s\".\n"), 
343               jcr->Job, dcr->dev_name);
344          Jmsg(jcr, M_INFO, 0, "%s", dev->errmsg);
345          return false;
346       }
347       /* First pass, we *know* there are no appendable volumes, so no need to call */
348       if (!first && dir_find_next_appendable_volume(dcr)) { /* get suggested volume */
349          unmounted = (dev->dev_blocked == BST_UNMOUNTED) ||
350                      (dev->dev_blocked == BST_UNMOUNTED_WAITING_FOR_SYSOP);
351          /*
352           * If we have a valid volume name and we are not
353           *   removable media, return now, or if we have a
354           *   Slot for an autochanger, otherwise wait
355           *   for the operator to mount the media.
356           */
357          if (!unmounted && ((dcr->VolumeName[0] && !dev_cap(dev, CAP_REM) && 
358                 dev_cap(dev, CAP_LABEL)) ||
359                  (dcr->VolumeName[0] && dcr->VolCatInfo.Slot))) {
360             Dmsg0(200, "Return 1 from mount without wait.\n");
361             return true;
362          }
363          jstat = JS_WaitMount;
364          if (!dev->poll) {
365             Jmsg(jcr, M_MOUNT, 0, _(
366 "Please mount Volume \"%s\" on Storage Device \"%s\" for Job %s\n"
367 "Use \"mount\" command to release Job.\n"),
368               dcr->VolumeName, dcr->dev_name, jcr->Job);
369             Dmsg3(200, "Mount %s on %s for Job %s\n",
370                   dcr->VolumeName, dcr->dev_name, jcr->Job);
371          }
372       } else {
373          jstat = JS_WaitMedia;
374          if (!dev->poll) {
375             Jmsg(jcr, M_MOUNT, 0, _(
376 "Job %s waiting. Cannot find any appendable volumes.\n\
377 Please use the \"label\"  command to create a new Volume for:\n\
378     Storage:      %s\n\
379     Media type:   %s\n\
380     Pool:         %s\n"),
381                jcr->Job, 
382                dcr->dev_name, 
383                dcr->media_type,
384                dcr->pool_name);
385          }
386       }
387       first = false;
388
389       jcr->JobStatus = jstat;
390       dir_send_job_status(jcr);
391
392       stat = wait_for_sysop(dcr);
393       if (dev->poll) {
394          Dmsg1(200, "Poll timeout in create append vol on device %s\n", dev_name(dev));
395          continue;
396       }
397
398       if (stat == ETIMEDOUT) {
399          if (!double_dev_wait_time(dev)) {
400             Mmsg(dev->errmsg, _("Max time exceeded waiting to mount Storage Device \"%s\" for Job %s\n"), 
401                dev_name(dev), jcr->Job);
402             Jmsg(jcr, M_FATAL, 0, "%s", dev->errmsg);
403             Dmsg1(200, "Gave up waiting on device %s\n", dev_name(dev));
404             return false;             /* exceeded maximum waits */
405          }
406          continue;
407       }
408       if (stat == EINVAL) {
409          berrno be;
410          Mmsg2(dev->errmsg, _("pthread error in mount_next_volume stat=%d ERR=%s\n"),
411                stat, be.strerror(stat));
412          Jmsg(jcr, M_FATAL, 0, "%s", dev->errmsg);
413          return false;
414       }
415       if (stat != 0) {
416          berrno be;
417          Jmsg(jcr, M_WARNING, 0, _("pthread error in mount_next_volume stat=%d ERR=%s\n"), stat,
418             be.strerror(stat));
419       }
420       Dmsg1(200, "Someone woke me for device %s\n", dev_name(dev));
421
422       /* If no VolumeName, and cannot get one, try again */
423       if (dcr->VolumeName[0] == 0 && !job_canceled(jcr) &&
424           !dir_find_next_appendable_volume(dcr)) {
425          Jmsg(jcr, M_MOUNT, 0, _(
426 "Someone woke me up, but I cannot find any appendable\n\
427 volumes for Job=%s.\n"), jcr->Job);
428          /* Restart wait counters after user interaction */
429          init_dev_wait_timers(dev);
430          continue;
431       }       
432       unmounted = (dev->dev_blocked == BST_UNMOUNTED) ||
433                   (dev->dev_blocked == BST_UNMOUNTED_WAITING_FOR_SYSOP);
434       if (unmounted) {
435          continue;                    /* continue to wait */
436       }
437
438       /*
439        * Device mounted, we have a volume, break and return   
440        */
441       break;
442    }
443    set_jcr_job_status(jcr, JS_Running);
444    dir_send_job_status(jcr);
445    Dmsg0(200, "leave dir_ask_sysop_to_mount_create_appendable_volume\n");
446    return true;
447 }
448
449 /*
450  *   Request to mount specific Volume
451  *
452  *   Entered with device blocked and dcr->VolumeName is desired
453  *      volume.
454  *   Leaves with device blocked.
455  *
456  *   Returns: true  on success (operator issues a mount command)
457  *            false on failure
458  *                  Note, must create dev->errmsg on error return.
459  *
460  */
461 bool dir_ask_sysop_to_mount_volume(DCR *dcr)
462 {
463    int stat = 0;
464    const char *msg;
465    DEVICE *dev = dcr->dev;
466    JCR *jcr = dcr->jcr;
467
468    Dmsg0(200, "enter dir_ask_sysop_to_mount_volume\n");
469    if (!dcr->VolumeName[0]) {
470       Mmsg0(dev->errmsg, _("Cannot request another volume: no volume name given.\n"));
471       return false;
472    }
473    ASSERT(dev->dev_blocked);
474    for ( ;; ) {
475       if (job_canceled(jcr)) {
476          Mmsg(dev->errmsg, _("Job %s canceled while waiting for mount on Storage Device \"%s\".\n"), 
477               jcr->Job, dcr->dev_name);
478          return false;
479       }
480
481       if (!dev->poll) {
482          msg = _("Please mount");
483          Jmsg(jcr, M_MOUNT, 0, _("%s Volume \"%s\" on Storage Device \"%s\" for Job %s\n"),
484               msg, dcr->VolumeName, dcr->dev_name, jcr->Job);
485          Dmsg3(200, "Mount \"%s\" on device \"%s\" for Job %s\n",
486                dcr->VolumeName, dcr->dev_name, jcr->Job);
487       }
488
489       jcr->JobStatus = JS_WaitMount;
490       dir_send_job_status(jcr);
491
492       stat = wait_for_sysop(dcr);    ;     /* wait on device */
493       if (dev->poll) {
494          Dmsg1(200, "Poll timeout in mount vol on device %s\n", dev_name(dev));
495          Dmsg1(200, "Blocked=%s\n", edit_blocked_reason(dev));
496          return true;
497       }
498
499       if (stat == ETIMEDOUT) {
500          if (!double_dev_wait_time(dev)) {
501             Mmsg(dev->errmsg, _("Max time exceeded waiting to mount Storage Device \"%s\" for Job %s\n"), 
502                dev_name(dev), jcr->Job);
503             Jmsg(jcr, M_FATAL, 0, "%s", dev->errmsg);
504             Dmsg1(200, "Gave up waiting on device %s\n", dev_name(dev));
505             return false;             /* exceeded maximum waits */
506          }
507          continue;
508       }
509       if (stat == EINVAL) {
510          berrno be;
511          Mmsg2(dev->errmsg, _("pthread error in mount_volume stat=%d ERR=%s\n"),
512                stat, be.strerror(stat));
513          Jmsg(jcr, M_FATAL, 0, "%s", dev->errmsg);
514          return false;
515       }
516       if (stat != 0) {
517          berrno be;
518          Jmsg(jcr, M_FATAL, 0, _("pthread error in mount_next_volume stat=%d ERR=%s\n"), stat,
519             be.strerror(stat));
520       }
521       Dmsg1(200, "Someone woke me for device %s\n", dev_name(dev));
522       break;
523    }
524    set_jcr_job_status(jcr, JS_Running);
525    dir_send_job_status(jcr);
526    Dmsg0(200, "leave dir_ask_sysop_to_mount_volume\n");
527    return true;
528 }
529
530 /*
531  * Wait for SysOp to mount a tape
532  */
533 static int wait_for_sysop(DCR *dcr)
534 {
535    struct timeval tv;
536    struct timezone tz;
537    struct timespec timeout;
538    time_t last_heartbeat = 0;
539    time_t first_start = time(NULL);
540    int stat = 0;
541    int add_wait;
542    bool unmounted;
543    DEVICE *dev = dcr->dev;
544    JCR *jcr = dcr->jcr;
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 the user did not unmount the tape and we are polling, ensure
562     *  that we poll at the correct interval. 
563     */
564    if (!unmounted && dev->vol_poll_interval && add_wait > dev->vol_poll_interval) {
565       add_wait = dev->vol_poll_interval;
566    }
567    gettimeofday(&tv, &tz);
568    timeout.tv_nsec = tv.tv_usec * 1000;
569    timeout.tv_sec = tv.tv_sec + add_wait;
570
571    if (!unmounted) {
572       dev->dev_prev_blocked = dev->dev_blocked;
573       dev->dev_blocked = BST_WAITING_FOR_SYSOP; /* indicate waiting for mount */
574    }
575
576    for ( ; !job_canceled(jcr); ) {
577       time_t now, start;
578
579       Dmsg3(200, "I'm going to sleep on device %s. HB=%d wait=%d\n", dev_name(dev),
580          (int)me->heartbeat_interval, dev->wait_sec);
581       start = time(NULL);
582       /* Wait required time */
583       stat = pthread_cond_timedwait(&dev->wait_next_vol, &dev->mutex, &timeout);
584       Dmsg1(200, "Wokeup from sleep on device stat=%d\n", stat);
585
586       now = time(NULL);
587       dev->rem_wait_sec -= (now - start);
588
589       /* Note, this always triggers the first time. We want that. */
590       if (me->heartbeat_interval) {
591          if (now - last_heartbeat >= me->heartbeat_interval) {
592             /* send heartbeats */
593             if (jcr->file_bsock) {
594                bnet_sig(jcr->file_bsock, BNET_HEARTBEAT);
595                Dmsg0(200, "Send heartbeat to FD.\n");
596             }
597             if (jcr->dir_bsock) {
598                bnet_sig(jcr->dir_bsock, BNET_HEARTBEAT);
599             }
600             last_heartbeat = now;
601          }
602       }
603
604       /*
605        * Check if user unmounted the device while we were waiting
606        */
607       unmounted = (dev->dev_blocked == BST_UNMOUNTED) ||
608                    (dev->dev_blocked == BST_UNMOUNTED_WAITING_FOR_SYSOP);
609
610       if (stat != ETIMEDOUT) {     /* we blocked the device */
611          break;                    /* on error return */
612       }
613       if (dev->rem_wait_sec <= 0) {  /* on exceeding wait time return */
614          Dmsg0(200, "Exceed wait time.\n");
615          break;
616       }
617       
618       if (!unmounted && dev->vol_poll_interval &&       
619           (now - first_start >= dev->vol_poll_interval)) {
620          Dmsg1(200, "In wait blocked=%s\n", edit_blocked_reason(dev));
621          dev->poll = true;            /* returning a poll event */
622          break;
623       }
624       /*
625        * Check if user mounted the device while we were waiting
626        */
627       if (dev->dev_blocked == BST_MOUNT) {   /* mount request ? */
628          stat = 0;
629          break;
630       }
631
632       add_wait = dev->wait_sec - (now - start);
633       if (add_wait < 0) {
634          add_wait = 0;
635       }
636       if (me->heartbeat_interval && add_wait > me->heartbeat_interval) {
637          add_wait = me->heartbeat_interval;
638       }
639       gettimeofday(&tv, &tz);
640       timeout.tv_nsec = tv.tv_usec * 1000;
641       timeout.tv_sec = tv.tv_sec + add_wait; /* additional wait */
642       Dmsg1(200, "Additional wait %d sec.\n", add_wait);
643    }
644
645    if (!unmounted) {
646       dev->dev_blocked = dev->dev_prev_blocked;    /* restore entry state */
647    }
648    V(dev->mutex);
649    return stat;
650 }