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