]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/stored/mount.c
960ef83cdf7b0db05a26f90f2f4fa8ca06678c48
[bacula/bacula] / bacula / src / stored / mount.c
1 /*
2    Bacula(R) - The Network Backup Solution
3
4    Copyright (C) 2000-2016 Kern Sibbald
5
6    The original author of Bacula is Kern Sibbald, with contributions
7    from many others, a complete list can be found in the file AUTHORS.
8
9    You may use this file and others of this release according to the
10    license defined in the LICENSE file, which includes the Affero General
11    Public License, v3.0 ("AGPLv3") and some additional permissions and
12    terms pursuant to its AGPLv3 Section 7.
13
14    This notice must be preserved when any source code is 
15    conveyed and/or propagated.
16
17    Bacula(R) is a registered trademark of Kern Sibbald.
18 */
19 /*
20  *
21  *  Routines for handling mounting tapes for reading and for
22  *    writing.
23  *
24  *   Kern Sibbald, August MMII
25  *
26  */
27
28 #include "bacula.h"                   /* pull in global headers */
29 #include "stored.h"                   /* pull in Storage Deamon headers */
30
31 static pthread_mutex_t mount_mutex = PTHREAD_MUTEX_INITIALIZER;
32
33 enum {
34    try_next_vol = 1,
35    try_read_vol,
36    try_error,
37    try_default
38 };
39
40 enum {
41    check_next_vol = 1,
42    check_ok,
43    check_read_vol,
44    check_error
45 };
46
47 /*
48  * If release is set, we rewind the current volume,
49  * which we no longer want, and ask the user (console)
50  * to mount the next volume.
51  *
52  *  Continue trying until we get it, and then ensure
53  *  that we can write on it.
54  *
55  * This routine returns a 0 only if it is REALLY
56  *  impossible to get the requested Volume.
57  *
58  * This routine is entered with the device blocked, but not
59  *   locked.
60  *
61  */
62 bool DCR::mount_next_write_volume()
63 {
64    int retry = 0;
65    bool ask = false, recycle, autochanger;
66    int mode;
67    DCR *dcr = this;
68
69    Enter(200);
70    Dmsg2(100, "Enter mount_next_volume(release=%d) dev=%s\n", dev->must_unload(),
71       dev->print_name());
72
73    init_device_wait_timers(dcr);
74
75    P(mount_mutex);
76
77    /*
78     * Attempt to mount the next volume. If something non-fatal goes
79     *  wrong, we come back here to re-try (new op messages, re-read
80     *  Volume, ...)
81     */
82 mount_next_vol:
83    Dmsg1(100, "mount_next_vol retry=%d\n", retry);
84    /* Ignore retry if this is poll request */
85    if (dev->is_nospace() || retry++ > 4) {
86       /* Last ditch effort before giving up, force operator to respond */
87       VolCatInfo.Slot = 0;
88       V(mount_mutex);
89       if (!dir_ask_sysop_to_mount_volume(dcr, SD_APPEND)) {
90          Jmsg(jcr, M_FATAL, 0, _("Too many errors trying to mount %s device %s.\n"),
91               dev->print_type(), dev->print_name());
92          goto no_lock_bail_out;
93       }
94       P(mount_mutex);
95       Dmsg1(90, "Continue after dir_ask_sysop_to_mount. must_load=%d\n", dev->must_load());
96    }
97    if (job_canceled(jcr)) {
98       Jmsg(jcr, M_FATAL, 0, _("Job %d canceled.\n"), jcr->JobId);
99       goto bail_out;
100    }
101    recycle = false;
102
103    if (dev->must_unload()) {
104       ask = true;                     /* ask operator to mount tape */
105    }
106    do_unload();
107    do_swapping(SD_APPEND);
108    do_load(SD_APPEND);
109
110    if (!find_a_volume()) {
111       goto bail_out;
112    }
113
114    if (job_canceled(jcr)) {
115       goto bail_out;
116    }
117    Dmsg3(100, "After find_a_volume. Vol=%s Slot=%d VolType=%d\n",
118          getVolCatName(), VolCatInfo.Slot, VolCatInfo.VolCatType);
119
120    dev->notify_newvol_in_attached_dcrs(getVolCatName());
121
122    /*
123     * Get next volume and ready it for append
124     * This code ensures that the device is ready for
125     * writing. We start from the assumption that there
126     * may not be a tape mounted.
127     *
128     * If the device is a file, we create the output
129     * file. If it is a tape, we check the volume name
130     * and move the tape to the end of data.
131     *
132     */
133    dcr->setVolCatInfo(false);   /* out of date when Vols unlocked */
134    if (autoload_device(dcr, SD_APPEND, NULL) > 0) {
135       autochanger = true;
136       ask = false;
137    } else {
138       autochanger = false;
139       VolCatInfo.Slot = 0;
140       if (dev->is_autochanger() && !VolCatInfo.InChanger) {
141          ask = true;      /* not in changer, do not retry */
142       } else {
143          ask = retry >= 2;
144       }
145    }
146    Dmsg1(100, "autoload_dev returns %d\n", autochanger);
147    /*
148     * If we autochanged to correct Volume or (we have not just
149     *   released the Volume AND we can automount) we go ahead
150     *   and read the label. If there is no tape in the drive,
151     *   we will fail, recurse and ask the operator the next time.
152     */
153    if (!dev->must_unload() && dev->is_tape() && dev->has_cap(CAP_AUTOMOUNT)) {
154       Dmsg0(250, "(1)Ask=0\n");
155       ask = false;                 /* don't ask SYSOP this time */
156    }
157    /* Don't ask if not removable */
158    if (!dev->is_removable()) {
159       Dmsg0(250, "(2)Ask=0\n");
160       ask = false;
161    }
162    Dmsg2(100, "Ask=%d autochanger=%d\n", ask, autochanger);
163
164    if (ask) {
165       V(mount_mutex);
166       dcr->setVolCatInfo(false);   /* out of date when Vols unlocked */
167       if (!dir_ask_sysop_to_mount_volume(dcr, SD_APPEND)) {
168          Dmsg0(150, "Error return ask_sysop ...\n");
169          goto no_lock_bail_out;
170       }
171       P(mount_mutex);
172    }
173    if (job_canceled(jcr)) {
174       goto bail_out;
175    }
176    Dmsg3(100, "want vol=%s devvol=%s dev=%s\n", VolumeName,
177       dev->VolHdr.VolumeName, dev->print_name());
178
179    if (dev->poll && dev->has_cap(CAP_CLOSEONPOLL)) {
180       dev->close();
181       free_volume(dev);
182    }
183
184    /* Ensure the device is open */
185    if (dev->has_cap(CAP_STREAM)) {
186       mode = OPEN_WRITE_ONLY;
187    } else {
188       mode = OPEN_READ_WRITE;
189    }
190    /* Try autolabel if enabled */
191    Dmsg1(100, "Try open Vol=%s\n", getVolCatName());
192    if (!dev->open(dcr, mode)) {
193       Dmsg1(100, "Try autolabel Vol=%s\n", getVolCatName());
194       try_autolabel(false);      /* try to create a new volume label */
195    }
196    while (!dev->open(dcr, mode)) {
197       Dmsg1(100, "open_device failed: ERR=%s\n", dev->bstrerror());
198       if ((dev->is_file() && dev->is_removable()) || dev->is_dvd()) {
199          bool ok = true;
200          Dmsg0(150, "call scan_dir_for_vol\n");
201          if (dev->is_dvd()) {
202             if (!dev->mount(0)) {
203                ok = false;
204             }
205          }
206          if (ok && dev->scan_dir_for_volume(dcr)) {
207             if (dev->open(dcr, mode)) {
208                break;                    /* got a valid volume */
209             }
210          }
211          if (ok && dev->is_dvd()) {
212             dev->unmount(0);
213          }
214       }
215       if (try_autolabel(false) == try_read_vol) {
216          break;                       /* created a new volume label */
217       }
218
219       /* ***FIXME*** if autochanger, before giving up try unload and load */
220
221       Jmsg4(jcr, M_WARNING, 0, _("Open of %s device %s Volume \"%s\" failed: ERR=%s\n"),
222             dev->print_type(), dev->print_name(), dcr->VolumeName, dev->bstrerror());
223
224       /* If not removable, Volume is broken. This is a serious issue here. */
225       if(dev->is_file() && !dev->is_removable()) {
226          Dmsg3(40, "Volume \"%s\" not loaded on %s device %s.\n",
227                dcr->VolumeName, dev->print_type(), dev->print_name());
228          mark_volume_in_error();
229
230       } else {
231          Dmsg0(100, "set_unload\n");
232          dev->set_unload();              /* force ask sysop */
233          ask = true;
234       }
235
236       Dmsg0(100, "goto mount_next_vol\n");
237       goto mount_next_vol;
238    }
239
240    /*
241     * Now check the volume label to make sure we have the right tape mounted
242     */
243 read_volume:
244    switch (check_volume_label(ask, autochanger)) {
245    case check_next_vol:
246       Dmsg0(50, "set_unload\n");
247       dev->set_unload();                 /* want a different Volume */
248       Dmsg0(100, "goto mount_next_vol\n");
249       goto mount_next_vol;
250    case check_read_vol:
251       goto read_volume;
252    case check_error:
253       goto bail_out;
254    case check_ok:
255       break;
256    }
257    /*
258     * Check that volcatinfo is good
259     */
260    if (!dev->haveVolCatInfo()) {
261       Dmsg0(100, "Do not have volcatinfo\n");
262       if (!find_a_volume()) {
263          goto mount_next_vol;
264       }
265       dev->VolCatInfo = VolCatInfo;      /* structure assignment */
266    }
267
268    /*
269     * See if we have a fresh tape or a tape with data.
270     *
271     * Note, if the LabelType is PRE_LABEL, it was labeled
272     *  but never written. If so, rewrite the label but set as
273     *  VOL_LABEL.  We rewind and return the label (reconstructed)
274     *  in the block so that in the case of a new tape, data can
275     *  be appended just after the block label.  If we are writing
276     *  a second volume, the calling routine will write the label
277     *  before writing the overflow block.
278     *
279     *  If the tape is marked as Recycle, we rewrite the label.
280     */
281    recycle = strcmp(dev->VolCatInfo.VolCatStatus, "Recycle") == 0;
282    if (dev->VolHdr.LabelType == PRE_LABEL || recycle) {
283       dcr->WroteVol = false;
284       if (!dcr->rewrite_volume_label(recycle)) {
285          mark_volume_in_error();
286          goto mount_next_vol;
287       }
288    } else {
289       /*
290        * OK, at this point, we have a valid Bacula label, but
291        * we need to position to the end of the volume, since we are
292        * just now putting it into append mode.
293        */
294       Dmsg1(100, "Device previously written, moving to end of data. Expect %lld bytes\n",
295            dev->VolCatInfo.VolCatBytes);
296       Jmsg(jcr, M_INFO, 0, _("Volume \"%s\" previously written, moving to end of data.\n"),
297          VolumeName);
298
299       if (!dev->eod(dcr)) {
300          Dmsg3(050, "Unable to position to end of data on %s device %s: ERR=%s\n",
301             dev->print_type(), dev->print_name(), dev->bstrerror());
302          Jmsg(jcr, M_ERROR, 0, _("Unable to position to end of data on %s device %s: ERR=%s\n"),
303             dev->print_type(), dev->print_name(), dev->bstrerror());
304          mark_volume_in_error();
305          goto mount_next_vol;
306       }
307
308       if (!is_eod_valid()) {
309          Dmsg0(100, "goto mount_next_vol\n");
310          goto mount_next_vol;
311       }
312
313       dev->VolCatInfo.VolCatMounts++;      /* Update mounts */
314       Dmsg1(150, "update volinfo mounts=%d\n", dev->VolCatInfo.VolCatMounts);
315       if (!dir_update_volume_info(dcr, false, false)) {
316          goto bail_out;
317       }
318
319       /* Return an empty block */
320       empty_block(block);             /* we used it for reading so set for write */
321    }
322    dev->set_append();
323    Dmsg1(150, "set APPEND, normal return from mount_next_write_volume. dev=%s\n",
324       dev->print_name());
325
326    V(mount_mutex);
327    return true;
328
329 bail_out:
330    V(mount_mutex);
331
332 no_lock_bail_out:
333    Leave(200);
334    return false;
335 }
336
337 /*
338  * This routine is meant to be called once the first pass
339  *   to ensure that we have a candidate volume to mount.
340  *   Otherwise, we ask the sysop to created one.
341  * Note, mount_mutex is already locked on entry and thus
342  *   must remain locked on exit from this function.
343  */
344 bool DCR::find_a_volume()
345 {
346    DCR *dcr = this;
347    bool ok;
348
349    if (!is_suitable_volume_mounted()) {
350       bool have_vol = false;
351       /* Do we have a candidate volume? */
352       if (dev->vol) {
353          bstrncpy(VolumeName, dev->vol->vol_name, sizeof(VolumeName));
354          have_vol = dir_get_volume_info(this, GET_VOL_INFO_FOR_WRITE);
355       }
356       /*
357        * Get Director's idea of what tape we should have mounted.
358        *    in dcr->VolCatInfo
359        */
360       if (!have_vol) {
361          Dmsg0(200, "Before dir_find_next_appendable_volume.\n");
362          while (!dir_find_next_appendable_volume(dcr)) {
363             Dmsg0(200, "not dir_find_next\n");
364             if (job_canceled(jcr)) {
365                return false;
366             }
367             /*
368              * Unlock the mount mutex while waiting or
369              *   the Director for a new volume
370              */
371             V(mount_mutex);
372             if (dev->must_wait()) {
373                int retries = 5;
374                Dmsg0(40, "No appendable volume. Calling wait_for_device\n");
375                wait_for_device(dcr, retries);
376                ok = true;
377             } else {
378                ok = dir_ask_sysop_to_create_appendable_volume(dcr);
379             }
380             P(mount_mutex);
381             if (!ok || job_canceled(jcr)) {
382                return false;
383             }
384             Dmsg0(150, "Again dir_find_next_append...\n");
385          }
386          dev->clear_wait();
387       }
388    }
389    if (dcr->haveVolCatInfo()) {
390       return true;
391    }
392    return dir_get_volume_info(dcr, GET_VOL_INFO_FOR_WRITE);
393 }
394
395 int DCR::check_volume_label(bool &ask, bool &autochanger)
396 {
397    int vol_label_status;
398
399    Enter(200);
400
401    /*
402     * If we are writing to a stream device, ASSUME the volume label
403     *  is correct.
404     */
405    if (dev->has_cap(CAP_STREAM)) {
406       vol_label_status = VOL_OK;
407       create_volume_header(dev, VolumeName, "Default", false /* not DVD */);
408       dev->VolHdr.LabelType = PRE_LABEL;
409    } else {
410       vol_label_status = read_dev_volume_label(this);
411    }
412    if (job_canceled(jcr)) {
413       goto check_bail_out;
414    }
415
416    Dmsg2(150, "Want dirVol=%s dirStat=%s\n", VolumeName,
417       VolCatInfo.VolCatStatus);
418
419    /*
420     * At this point, dev->VolCatInfo has what is in the drive, if anything,
421     *          and   dcr->VolCatInfo has what the Director wants.
422     */
423    switch (vol_label_status) {
424    case VOL_OK:
425       Dmsg1(150, "Vol OK name=%s\n", dev->VolHdr.VolumeName);
426       dev->VolCatInfo = VolCatInfo;       /* structure assignment */
427       break;                    /* got a Volume */
428    case VOL_NAME_ERROR:
429       VOLUME_CAT_INFO dcrVolCatInfo, devVolCatInfo;
430       char saveVolumeName[MAX_NAME_LENGTH];
431
432       Dmsg2(40, "Vol NAME Error Have=%s, want=%s\n", dev->VolHdr.VolumeName, VolumeName);
433       if (dev->is_volume_to_unload()) {
434          ask = true;
435          goto check_next_volume;
436       }
437
438 #ifdef xxx
439       /* If not removable, Volume is broken */
440       if (!dev->is_removable()) {
441          Jmsg3(jcr, M_WARNING, 0, _("Volume \"%s\" not loaded on %s device %s.\n"),
442             VolumeName, dev->print_type(), dev->print_name());
443          Dmsg3(40, "Volume \"%s\" not loaded on %s device %s.\n",
444             VolumeName, dev->print_type(), dev->print_name());
445          mark_volume_in_error();
446          goto check_next_volume;
447       }
448 #endif
449
450       /*
451        * OK, we got a different volume mounted. First save the
452        *  requested Volume info (dcr) structure, then query if
453        *  this volume is really OK. If not, put back the desired
454        *  volume name, mark it not in changer and continue.
455        */
456       dcrVolCatInfo = VolCatInfo;      /* structure assignment */
457       devVolCatInfo = dev->VolCatInfo;      /* structure assignment */
458       /* Check if this is a valid Volume in the pool */
459       bstrncpy(saveVolumeName, VolumeName, sizeof(saveVolumeName));
460       bstrncpy(VolumeName, dev->VolHdr.VolumeName, sizeof(VolumeName));
461       if (!dir_get_volume_info(this, GET_VOL_INFO_FOR_WRITE)) {
462          POOL_MEM vol_info_msg;
463          pm_strcpy(vol_info_msg, jcr->dir_bsock->msg);  /* save error message */
464          /* Restore desired volume name, note device info out of sync */
465          /* This gets the info regardless of the Pool */
466          bstrncpy(VolumeName, dev->VolHdr.VolumeName, sizeof(VolumeName));
467          if (autochanger && !dir_get_volume_info(this, GET_VOL_INFO_FOR_READ)) {
468             /*
469              * If we get here, we know we cannot write on the Volume,
470              *  and we know that we cannot read it either, so it
471              *  is not in the autochanger.
472              */
473             mark_volume_not_inchanger();
474          }
475          dev->VolCatInfo = devVolCatInfo;    /* structure assignment */
476          dev->set_unload();                  /* unload this volume */
477          Jmsg(jcr, M_WARNING, 0, _("Director wanted Volume \"%s\".\n"
478               "    Current Volume \"%s\" not acceptable because:\n"
479               "    %s"),
480              dcrVolCatInfo.VolCatName, dev->VolHdr.VolumeName,
481              vol_info_msg.c_str());
482          ask = true;
483          /* Restore saved DCR before continuing */
484          bstrncpy(VolumeName, saveVolumeName, sizeof(VolumeName));
485          VolCatInfo = dcrVolCatInfo;  /* structure assignment */
486          goto check_next_volume;
487       }
488       /*
489        * This was not the volume we expected, but it is OK with
490        * the Director, so use it.
491        */
492       Dmsg1(150, "Got new Volume name=%s\n", VolumeName);
493       dev->VolCatInfo = VolCatInfo;   /* structure assignment */
494       Dmsg1(100, "Call reserve_volume=%s\n", dev->VolHdr.VolumeName);
495       if (reserve_volume(this, dev->VolHdr.VolumeName) == NULL) {
496          if (!jcr->errmsg[0]) {
497             Jmsg3(jcr, M_WARNING, 0, _("Could not reserve volume %s on %s device %s\n"),
498                dev->VolHdr.VolumeName, dev->print_type(), dev->print_name());
499          } else {
500             Jmsg(jcr, M_WARNING, 0, "%s", jcr->errmsg);
501          }
502          ask = true;
503          dev->setVolCatInfo(false);
504          setVolCatInfo(false);
505          goto check_next_volume;
506       }
507       break;                /* got a Volume */
508    /*
509     * At this point, we assume we have a blank tape mounted.
510     */
511    case VOL_IO_ERROR:
512       if (dev->is_dvd()) {
513          Jmsg(jcr, M_FATAL, 0, "%s", jcr->errmsg);
514          mark_volume_in_error();
515          goto check_bail_out;       /* we could not write on DVD */
516       }
517       /* Fall through wanted */
518    case VOL_NO_LABEL:
519       switch (try_autolabel(true)) {
520       case try_next_vol:
521          goto check_next_volume;
522       case try_read_vol:
523          goto check_read_volume;
524       case try_error:
525          goto check_bail_out;
526       case try_default:
527          break;
528       }
529       /* NOTE! Fall-through wanted. */
530    case VOL_NO_MEDIA:
531    default:
532       Dmsg0(200, "VOL_NO_MEDIA or default.\n");
533       /* Send error message */
534       if (!dev->poll) {
535       } else {
536          Dmsg1(200, "Msg suppressed by poll: %s\n", jcr->errmsg);
537       }
538       ask = true;
539       /* Needed, so the medium can be changed */
540       if (dev->requires_mount()) {
541          dev->close();
542          free_volume(dev);
543       }
544       goto check_next_volume;
545    }
546    Leave(200);
547    return check_ok;
548
549 check_next_volume:
550    dev->setVolCatInfo(false);
551    setVolCatInfo(false);
552    Leave(200);
553    return check_next_vol;
554
555 check_bail_out:
556    Leave(200);
557    return check_error;
558
559 check_read_volume:
560    Leave(200);
561    return check_read_vol;
562
563 }
564
565
566 bool DCR::is_suitable_volume_mounted()
567 {
568    bool ok;
569
570    /* Volume mounted? */
571    if (dev->VolHdr.VolumeName[0] == 0 || dev->swap_dev || dev->must_unload()) {
572       return false;                      /* no */
573    }
574    bstrncpy(VolumeName, dev->VolHdr.VolumeName, sizeof(VolumeName));
575    ok = dir_get_volume_info(this, GET_VOL_INFO_FOR_WRITE);
576    if (!ok) {
577       Dmsg1(40, "dir_get_volume_info failed: %s", jcr->errmsg);
578       dev->set_wait();
579    }
580    return ok;
581 }
582
583 bool DCR::do_unload()
584 {
585    if (dev->must_unload()) {
586       Dmsg1(100, "must_unload release %s\n", dev->print_name());
587       release_volume();
588    }
589    return false;
590 }
591
592 bool DCR::do_load(bool is_writing)
593 {
594    if (dev->must_load()) {
595       Dmsg1(100, "Must load dev=%s\n", dev->print_name());
596       if (autoload_device(this, is_writing, NULL) > 0) {
597          dev->clear_load();
598          return true;
599       }
600       return false;
601    }
602    return true;
603 }
604
605 void DCR::do_swapping(bool is_writing)
606 {
607    /*
608     * See if we are asked to swap the Volume from another device
609     *  if so, unload the other device here, and attach the
610     *  volume to our drive.
611     */
612    if (dev->swap_dev) {
613       if (dev->swap_dev->must_unload()) {
614          if (dev->vol) {
615             dev->swap_dev->set_slot(dev->vol->get_slot());
616          }
617          Dmsg2(100, "Swap unloading slot=%d %s\n", dev->swap_dev->get_slot(),
618                dev->swap_dev->print_name());
619          unload_dev(this, dev->swap_dev);
620       }
621       if (dev->vol) {
622          dev->vol->clear_swapping();
623          Dmsg1(100, "=== set in_use vol=%s\n", dev->vol->vol_name);
624          dev->vol->clear_in_use();
625          dev->VolHdr.VolumeName[0] = 0;  /* don't yet have right Volume */
626       } else {
627          Dmsg1(100, "No vol on dev=%s\n", dev->print_name());
628       }
629       if (dev->swap_dev->vol) {
630          Dmsg2(100, "Vol=%s on dev=%s\n", dev->swap_dev->vol->vol_name,
631               dev->swap_dev->print_name());
632       }
633       Dmsg2(100, "Set swap_dev=NULL for dev=%s swap_dev=%s\n",
634          dev->print_name(), dev->swap_dev->print_name());
635       dev->swap_dev = NULL;
636    } else {
637       if (dev->vol) {
638       Dmsg1(100, "No swap_dev set. dev->vol=%p\n", dev->vol);
639       } else {
640       Dmsg1(100, "No swap_dev set. dev->vol=%p\n", dev->vol);
641       }
642    }
643 }
644
645
646 /*
647  * Check if the current position on the volume corresponds to
648  *  what is in the catalog.
649  */
650 bool DCR::is_eod_valid()
651 {
652    if (dev->is_dvd()) {
653       char ed1[50], ed2[50];
654       if (dev->VolCatInfo.VolCatBytes == dev->part_start + dev->part_size) {
655          Jmsg(jcr, M_INFO, 0, _("Ready to append to end of Volume \"%s\""
656               " part=%d size=%s\n"), VolumeName,
657               dev->part, edit_uint64_with_commas(dev->VolCatInfo.VolCatBytes,ed1));
658       } else {
659          Jmsg(jcr, M_ERROR, 0, _("Bacula cannot write on DVD Volume \"%s\" because: "
660               "The sizes do not match! Volume=%s Catalog=%s\n"),
661               VolumeName,
662               edit_uint64_with_commas(dev->part_start + dev->part_size, ed1),
663               edit_uint64_with_commas(dev->VolCatInfo.VolCatBytes, ed2));
664          mark_volume_in_error();
665          return false;
666       }
667    } else if (dev->is_tape()) {
668       /*
669        * Check if we are positioned on the tape at the same place
670        * that the database says we should be.
671        */
672       if (dev->VolCatInfo.VolCatFiles == dev->get_file()) {
673          Jmsg(jcr, M_INFO, 0, _("Ready to append to end of Volume \"%s\" at file=%d.\n"),
674               VolumeName, dev->get_file());
675       } else if (dev->get_file() > dev->VolCatInfo.VolCatFiles) {
676          Jmsg(jcr, M_WARNING, 0, _("For Volume \"%s\":\n"
677               "The number of files mismatch! Volume=%u Catalog=%u\n"
678               "Correcting Catalog\n"),
679               VolumeName, dev->get_file(), dev->VolCatInfo.VolCatFiles);
680          dev->VolCatInfo.VolCatFiles = dev->get_file();
681          dev->VolCatInfo.VolCatBlocks = dev->get_block_num();
682          if (!dir_update_volume_info(this, false, true)) {
683             Jmsg(jcr, M_WARNING, 0, _("Error updating Catalog\n"));
684             mark_volume_in_error();
685             return false;
686          }
687       } else {
688          Jmsg(jcr, M_ERROR, 0, _("Bacula cannot write on tape Volume \"%s\" because:\n"
689               "The number of files mismatch! Volume=%u Catalog=%u\n"),
690               VolumeName, dev->get_file(), dev->VolCatInfo.VolCatFiles);
691          mark_volume_in_error();
692          return false;
693       }
694    /*
695     * File device.
696     */
697    } else if (dev->is_file()) {
698       char ed1[50], ed2[50];
699       boffset_t pos;
700
701       pos = dev->lseek(this, (boffset_t)0, SEEK_END);
702       if (dev->VolCatInfo.VolCatAmetaBytes == (uint64_t)pos) {
703          Jmsg(jcr, M_INFO, 0, _("Ready to append to end of Volume \"%s\""
704               " size=%s\n"), VolumeName,
705               edit_uint64_with_commas(dev->VolCatInfo.VolCatAmetaBytes, ed1));
706       } else if ((uint64_t)pos >= dev->VolCatInfo.VolCatAmetaBytes) {
707          if ((uint64_t)pos != dev->VolCatInfo.VolCatAmetaBytes) {
708             Jmsg(jcr, M_WARNING, 0, _("For Volume \"%s\":\n"
709                "   The sizes do not match! Volume=%s Catalog=%s\n"
710                "   Correcting Catalog\n"),
711                VolumeName, edit_uint64_with_commas(pos, ed1),
712                edit_uint64_with_commas(dev->VolCatInfo.VolCatAmetaBytes, ed2));
713          }
714          dev->VolCatInfo.VolCatAmetaBytes = pos;
715          dev->VolCatInfo.VolCatBytes = pos;
716          dev->VolCatInfo.VolCatFiles = (uint32_t)(pos >> 32);
717          if (!dir_update_volume_info(this, false, true)) {
718             Jmsg(jcr, M_WARNING, 0, _("Error updating Catalog\n"));
719             mark_volume_in_error();
720             return false;
721          }
722       } else {
723          Mmsg(jcr->errmsg, _("Bacula cannot write on disk Volume \"%s\" because: "
724               "The sizes do not match! Volume=%s Catalog=%s\n"),
725               VolumeName,
726               edit_uint64_with_commas(pos, ed1),
727               edit_uint64_with_commas(dev->VolCatInfo.VolCatBytes, ed2));
728          Jmsg(jcr, M_ERROR, 0, jcr->errmsg);
729          Dmsg0(100, jcr->errmsg);
730          mark_volume_in_error();
731          return false;
732       }
733    }
734    return true;
735 }
736
737
738 /*
739  * If permitted, we label the device, make sure we can do
740  *   it by checking that the VolCatBytes is zero => not labeled,
741  *   once the Volume is labeled we don't want to label another
742  *   blank tape with the same name.  For disk, we go ahead and
743  *   label it anyway, because the OS insures that there is only
744  *   one Volume with that name.
745  * As noted above, at this point dcr->VolCatInfo has what
746  *   the Director wants and dev->VolCatInfo has info on the
747  *   previous tape (or nothing).
748  *
749  * Return codes are:
750  *   try_next_vol        label failed, look for another volume
751  *   try_read_vol        labeled volume, now re-read the label
752  *   try_error           hard error (catalog update)
753  *   try_default         I couldn't do anything
754  */
755 int DCR::try_autolabel(bool opened)
756 {
757    DCR *dcr = this;
758
759    if (dev->poll && !dev->is_tape()) {
760       Dmsg0(100, "No autolabel because polling.\n");
761       return try_default;       /* if polling, don't try to create new labels */
762    }
763    /* For a tape require it to be opened and read before labeling */
764    if (!opened && (dev->is_tape() || dev->is_null())) {
765       return try_default;
766    }
767    if (dev->has_cap(CAP_LABEL) && (VolCatInfo.VolCatBytes == 0 ||
768          (!dev->is_tape() && strcmp(VolCatInfo.VolCatStatus,
769                                 "Recycle") == 0))) {
770       Dmsg1(40, "Create new volume label vol=%s\n", VolumeName);
771       /* Create a new Volume label and write it to the device */
772       if (!write_new_volume_label_to_dev(dcr, VolumeName,
773              pool_name, false, /* no relabel */ false /* defer DVD label */)) {
774          Dmsg2(100, "write_vol_label failed. vol=%s, pool=%s\n",
775            VolumeName, pool_name);
776          if (opened) {
777             mark_volume_in_error();
778          }
779          return try_next_vol;
780       }
781       Dmsg0(150, "dir_update_vol_info. Set Append\n");
782       /* Copy Director's info into the device info */
783       dev->VolCatInfo = VolCatInfo;    /* structure assignment */
784       if (!dir_update_volume_info(dcr, true, true)) {  /* indicate tape labeled */
785          Dmsg3(100, "Update_vol_info failed no autolabel Volume \"%s\" on %s device %s.\n",
786             VolumeName, dev->print_type(), dev->print_name());
787          return try_error;
788       }
789       Jmsg(dcr->jcr, M_INFO, 0, _("Labeled new Volume \"%s\" on %s device %s.\n"),
790          VolumeName, dev->print_type(), dev->print_name());
791       Dmsg3(100, "Labeled new Volume \"%s\" on %s device %s.\n",
792          VolumeName, dev->print_type(), dev->print_name());
793       return try_read_vol;   /* read label we just wrote */
794    } else {
795       Dmsg4(40, "=== Cannot autolabel: cap_label=%d VolCatBytes=%lld is_tape=%d VolCatStatus=%s\n",
796          dev->has_cap(CAP_LABEL), VolCatInfo.VolCatBytes, dev->is_tape(),
797          VolCatInfo.VolCatStatus);
798    }
799    if (!dev->has_cap(CAP_LABEL) && VolCatInfo.VolCatBytes == 0) {
800       Jmsg(jcr, M_WARNING, 0, _("%s device %s not configured to autolabel Volumes.\n"),
801          dev->print_type(), dev->print_name());
802    }
803 #ifdef xxx
804    /* If not removable, Volume is broken */
805    if (!dev->is_removable()) {
806       Jmsg3(jcr, M_WARNING, 0, _("Volume \"%s\" not loaded on %s device %s.\n"),
807          VolumeName, dev->print_type(), dev->print_name());
808       Dmsg3(40, "Volume \"%s\" not loaded on %s device %s.\n",
809          VolumeName, dev->print_type(), dev->print_name());
810
811       mark_volume_in_error();
812       return try_next_vol;
813    }
814 #endif
815    return try_default;
816 }
817
818
819 /*
820  * Mark volume in error in catalog
821  */
822 void DCR::mark_volume_in_error()
823 {
824    Jmsg(jcr, M_INFO, 0, _("Marking Volume \"%s\" in Error in Catalog.\n"),
825         VolumeName);
826    dev->VolCatInfo = VolCatInfo;       /* structure assignment */
827    dev->setVolCatStatus("Error");
828    Dmsg0(150, "dir_update_vol_info. Set Error.\n");
829    dir_update_volume_info(this, false, false);
830    volume_unused(this);
831    Dmsg0(50, "set_unload\n");
832    dev->set_unload();                 /* must get a new volume */
833 }
834
835 /*
836  * The Volume is not in the correct slot, so mark this
837  *   Volume as not being in the Changer.
838  */
839 void DCR::mark_volume_not_inchanger()
840 {
841    Jmsg(jcr, M_ERROR, 0, _("Autochanger Volume \"%s\" not found in slot %d.\n"
842 "    Setting InChanger to zero in catalog.\n"),
843         getVolCatName(), VolCatInfo.Slot);
844    dev->VolCatInfo = VolCatInfo;    /* structure assignment */
845    VolCatInfo.InChanger = false;
846    dev->VolCatInfo.InChanger = false;
847    Dmsg0(400, "update vol info in mount\n");
848    dir_update_volume_info(this, true, false);  /* set new status */
849 }
850
851 /*
852  * Either because we are going to hang a new volume, or because
853  *  of explicit user request, we release the current volume.
854  */
855 void DCR::release_volume()
856 {
857    unload_autochanger(this, -1);
858
859    if (WroteVol) {
860       Jmsg0(jcr, M_ERROR, 0, _("Hey!!!!! WroteVol non-zero !!!!!\n"));
861       Pmsg0(190, "Hey!!!!! WroteVol non-zero !!!!!\n");
862    }
863
864    if (dev->is_open() && (!dev->is_tape() || !dev->has_cap(CAP_ALWAYSOPEN))) {
865       generate_plugin_event(jcr, bsdEventDeviceClose, this);
866       dev->close();
867    }
868
869    /* If we have not closed the device, then at least rewind the tape */
870    if (dev->is_open()) {
871       dev->offline_or_rewind();
872    }
873
874    /*
875     * Erase all memory of the current volume
876     */
877    free_volume(dev);
878    dev->block_num = dev->file = 0;
879    dev->EndBlock = dev->EndFile = 0;
880    memset(&dev->VolCatInfo, 0, sizeof(dev->VolCatInfo));
881    dev->clear_volhdr();
882    /* Force re-read of label */
883    dev->clear_labeled();
884    dev->clear_read();
885    dev->clear_append();
886    dev->label_type = B_BACULA_LABEL;
887    VolumeName[0] = 0;
888
889    Dmsg0(190, "release_volume\n");
890 }
891
892 /*
893  *      Insanity check
894  *
895  * Check to see if the tape position as defined by the OS is
896  *  the same as our concept.  If it is not,
897  *  it means the user has probably manually rewound the tape.
898  * Note, we check only if num_writers == 0, but this code will
899  *  also work fine for any number of writers. If num_writers > 0,
900  *  we probably should cancel all jobs using this device, or
901  *  perhaps even abort the SD, or at a minimum, mark the tape
902  *  in error.  Another strategy with num_writers == 0, would be
903  *  to rewind the tape and do a new eod() request.
904  */
905 bool DCR::is_tape_position_ok()
906 {
907    if (dev->is_tape() && dev->num_writers == 0) {
908       int32_t file = dev->get_os_tape_file();
909       if (file >= 0 && file != (int32_t)dev->get_file()) {
910          Jmsg(jcr, M_ERROR, 0, _("Invalid tape position on volume \"%s\""
911               " on device %s. Expected %d, got %d\n"),
912               dev->VolHdr.VolumeName, dev->print_name(), dev->get_file(), file);
913          /*
914           * If the current file is greater than zero, it means we probably
915           *  have some bad count of EOF marks, so mark tape in error.  Otherwise
916           *  the operator might have moved the tape, so we just release it
917           *  and try again.
918           */
919          if (file > 0) {
920             mark_volume_in_error();
921          }
922          release_volume();
923          return false;
924       }
925    }
926    return true;
927 }
928
929
930 /*
931  * If we are reading, we come here at the end of the tape
932  *  and see if there are more volumes to be mounted.
933  */
934 bool mount_next_read_volume(DCR *dcr)
935 {
936    DEVICE *dev = dcr->dev;
937    JCR *jcr = dcr->jcr;
938    Dmsg2(90, "NumReadVolumes=%d CurReadVolume=%d\n", jcr->NumReadVolumes, jcr->CurReadVolume);
939
940    volume_unused(dcr);                /* release current volume */
941    /*
942     * End Of Tape -- mount next Volume (if another specified)
943     */
944    if (jcr->NumReadVolumes > 1 && jcr->CurReadVolume < jcr->NumReadVolumes) {
945       dev->Lock();
946       dev->close();
947       dev->set_read();
948       dcr->set_reserved_for_read();
949       dev->Unlock();
950       if (!acquire_device_for_read(dcr)) {
951          Jmsg3(jcr, M_FATAL, 0, _("Cannot open %s Dev=%s, Vol=%s for reading.\n"),
952             dev->print_type(), dev->print_name(), dcr->VolumeName);
953          jcr->setJobStatus(JS_FatalError); /* Jmsg is not working for *SystemJob* */
954          return false;
955       }
956       return true;                    /* next volume mounted */
957    }
958    Dmsg0(90, "End of Device reached.\n");
959    return false;
960 }