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