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