]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/stored/mount.c
Fix bug #2346 Dir blocks when max reloads reached
[bacula/bacula] / bacula / src / stored / mount.c
1 /*
2    Bacula(R) - The Network Backup Solution
3
4    Copyright (C) 2000-2017 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 /* Make sure some EROFS is defined */
32 #ifndef EROFS                         /* read-only file system */
33 #define EROFS -1                      /* make impossible errno */
34 #endif
35
36 static pthread_mutex_t mount_mutex = PTHREAD_MUTEX_INITIALIZER;
37
38 enum {
39    try_next_vol = 1,
40    try_read_vol,
41    try_error,
42    try_default
43 };
44
45 enum {
46    check_next_vol = 1,
47    check_ok,
48    check_read_vol,
49    check_error
50 };
51
52 /*
53  * If release is set, we rewind the current volume,
54  * which we no longer want, and ask the user (console)
55  * to mount the next volume.
56  *
57  *  Continue trying until we get it, and then ensure
58  *  that we can write on it.
59  *
60  * This routine returns a 0 only if it is REALLY
61  *  impossible to get the requested Volume.
62  *
63  * This routine is entered with the device blocked, but not
64  *   locked.
65  *
66  */
67 bool DCR::mount_next_write_volume()
68 {
69    int retry = 0;
70    bool ask = false, recycle, autochanger;
71    DCR *dcr = this;
72
73    Enter(200);
74    set_ameta();
75    Dmsg2(100, "Enter mount_next_volume(release=%d) dev=%s\n", dev->must_unload(),
76       dev->print_name());
77
78    init_device_wait_timers(dcr);
79
80    P(mount_mutex);
81
82    /*
83     * Attempt to mount the next volume. If something non-fatal goes
84     *  wrong, we come back here to re-try (new op messages, re-read
85     *  Volume, ...)
86     */
87 mount_next_vol:
88    Dmsg1(100, "mount_next_vol retry=%d\n", retry);
89    /* Ignore retry if this is poll request */
90    if (dev->is_nospace() || retry++ > 4) {
91       /* Last ditch effort before giving up, force operator to respond */
92       VolCatInfo.Slot = 0;
93       V(mount_mutex);
94       if (!dir_ask_sysop_to_mount_volume(dcr, SD_APPEND)) {
95          Jmsg(jcr, M_FATAL, 0, _("Too many errors trying to mount %s device %s.\n"),
96               dev->print_type(), dev->print_name());
97          goto no_lock_bail_out;
98       }
99       P(mount_mutex);
100       Dmsg1(90, "Continue after dir_ask_sysop_to_mount. must_load=%d\n", dev->must_load());
101    }
102    if (job_canceled(jcr)) {
103       Jmsg(jcr, M_FATAL, 0, _("Job %d canceled.\n"), jcr->JobId);
104       goto bail_out;
105    }
106    recycle = false;
107
108    if (dev->must_unload()) {
109       ask = true;                     /* ask operator to mount tape */
110    }
111    do_unload();
112    do_swapping(SD_APPEND);
113    do_load(SD_APPEND);
114
115    if (!find_a_volume()) {
116       goto bail_out;
117    }
118
119    if (job_canceled(jcr)) {
120       goto bail_out;
121    }
122    Dmsg3(100, "After find_a_volume. Vol=%s Slot=%d VolType=%d\n",
123          getVolCatName(), VolCatInfo.Slot, VolCatInfo.VolCatType);
124
125    dev->notify_newvol_in_attached_dcrs(getVolCatName());
126
127    /*
128     * Get next volume and ready it for append
129     * This code ensures that the device is ready for
130     * writing. We start from the assumption that there
131     * may not be a tape mounted.
132     *
133     * If the device is a file, we create the output
134     * file. If it is a tape, we check the volume name
135     * and move the tape to the end of data.
136     *
137     */
138    dcr->setVolCatInfo(false);   /* out of date when Vols unlocked */
139    if (autoload_device(dcr, SD_APPEND, NULL) > 0) {
140       autochanger = true;
141       ask = false;
142    } else {
143       autochanger = false;
144       VolCatInfo.Slot = 0;
145       if (dev->is_autochanger() && !VolCatInfo.InChanger) {
146          ask = true;      /* not in changer, do not retry */
147       } else {
148          ask = retry >= 2;
149       }
150    }
151    Dmsg1(100, "autoload_dev returns %d\n", autochanger);
152    /*
153     * If we autochanged to correct Volume or (we have not just
154     *   released the Volume AND we can automount) we go ahead
155     *   and read the label. If there is no tape in the drive,
156     *   we will fail, recurse and ask the operator the next time.
157     */
158    if (!dev->must_unload() && dev->is_tape() && dev->has_cap(CAP_AUTOMOUNT)) {
159       Dmsg0(250, "(1)Ask=0\n");
160       ask = false;                 /* don't ask SYSOP this time */
161    }
162    /* Don't ask if not removable */
163    if (!dev->is_removable()) {
164       Dmsg0(250, "(2)Ask=0\n");
165       ask = false;
166    }
167    Dmsg2(100, "Ask=%d autochanger=%d\n", ask, autochanger);
168
169    if (ask) {
170       V(mount_mutex);
171       dcr->setVolCatInfo(false);   /* out of date when Vols unlocked */
172       if (!dir_ask_sysop_to_mount_volume(dcr, SD_APPEND)) {
173          Dmsg0(150, "Error return ask_sysop ...\n");
174          goto no_lock_bail_out;
175       }
176       P(mount_mutex);
177    }
178    if (job_canceled(jcr)) {
179       goto bail_out;
180    }
181    Dmsg3(100, "want vol=%s devvol=%s dev=%s\n", VolumeName,
182       dev->VolHdr.VolumeName, dev->print_name());
183
184    if (dev->poll && dev->has_cap(CAP_CLOSEONPOLL)) {
185       dev->close(this);
186       free_volume(dev);
187    }
188
189    /* Try autolabel if enabled */
190    Dmsg1(100, "Try open Vol=%s\n", getVolCatName());
191    if (!dev->open_device(dcr, OPEN_READ_WRITE)) {
192       Dmsg1(100, "Try autolabel Vol=%s\n", getVolCatName());
193       if (!dev->poll) {
194          try_autolabel(false);      /* try to create a new volume label */
195       }
196    }
197    while (!dev->open_device(dcr, OPEN_READ_WRITE)) {
198       Dmsg1(100, "open_device failed: ERR=%s", dev->bstrerror());
199       if (dev->is_file() && dev->is_removable()) {
200          bool ok = true;
201          Dmsg0(150, "call scan_dir_for_vol\n");
202          if (ok && dev->scan_dir_for_volume(dcr)) {
203             if (dev->open_device(dcr, OPEN_READ_WRITE)) {
204                break;                    /* got a valid volume */
205             }
206          }
207       }
208       if (try_autolabel(false) == try_read_vol) {
209          break;                       /* created a new volume label */
210       }
211
212       /* ***FIXME*** if autochanger, before giving up try unload and load */
213
214       Jmsg4(jcr, M_WARNING, 0, _("Open of %s device %s Volume \"%s\" failed: ERR=%s\n"),
215             dev->print_type(), dev->print_name(), dcr->VolumeName, dev->bstrerror());
216
217       /* If not removable, Volume is broken. This is a serious issue here. */
218       if (dev->is_file() && !dev->is_removable()) {
219          Dmsg3(40, "Volume \"%s\" not loaded on %s device %s.\n",
220                dcr->VolumeName, dev->print_type(), dev->print_name());
221          if (dev->dev_errno == EACCES || dev->dev_errno == EROFS) {
222             mark_volume_read_only();
223          } else {
224             mark_volume_in_error();
225          }
226
227       } else {
228          Dmsg0(100, "set_unload\n");
229          if (dev->dev_errno == EACCES || dev->dev_errno == EROFS) {
230             mark_volume_read_only();
231          }
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->set_volcatinfo_from_dcr(this);
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 (!dev->rewrite_volume_label(dcr, 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 (!dev->is_eod_valid(dcr)) {
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, VolumeName, 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, VolumeName, 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    set_ameta();
402    /*
403     * If we are writing to a stream device, ASSUME the volume label
404     *  is correct.
405     */
406    if (dev->has_cap(CAP_STREAM)) {
407       vol_label_status = VOL_OK;
408       create_volume_header(dev, VolumeName, "Default", false);
409       dev->VolHdr.LabelType = PRE_LABEL;
410    } else {
411       vol_label_status = dev->read_dev_volume_label(this);
412    }
413    if (job_canceled(jcr)) {
414       goto check_bail_out;
415    }
416
417    Dmsg2(150, "Want dirVol=%s dirStat=%s\n", VolumeName,
418       VolCatInfo.VolCatStatus);
419
420    /*
421     * At this point, dev->VolCatInfo has what is in the drive, if anything,
422     *          and   dcr->VolCatInfo has what the Director wants.
423     */
424    switch (vol_label_status) {
425    case VOL_OK:
426       Dmsg1(150, "Vol OK name=%s\n", dev->VolHdr.VolumeName);
427       dev->VolCatInfo = VolCatInfo;       /* structure assignment */
428       break;                    /* got a Volume */
429    case VOL_NAME_ERROR:
430       VOLUME_CAT_INFO dcrVolCatInfo, devVolCatInfo;
431       char saveVolumeName[MAX_NAME_LENGTH];
432
433       Dmsg2(40, "Vol NAME Error Have=%s, want=%s\n", dev->VolHdr.VolumeName, VolumeName);
434       if (dev->is_volume_to_unload()) {
435          ask = true;
436          goto check_next_volume;
437       }
438
439 #ifdef xxx
440       /* If not removable, Volume is broken */
441       if (!dev->is_removable()) {
442          Jmsg3(jcr, M_WARNING, 0, _("Volume \"%s\" not loaded on %s device %s.\n"),
443             VolumeName, dev->print_type(), dev->print_name());
444          Dmsg3(40, "Volume \"%s\" not loaded on %s device %s.\n",
445             VolumeName, dev->print_type(), dev->print_name());
446          mark_volume_in_error();
447          goto check_next_volume;
448       }
449 #endif
450
451       /*
452        * OK, we got a different volume mounted. First save the
453        *  requested Volume info (dcr) structure, then query if
454        *  this volume is really OK. If not, put back the desired
455        *  volume name, mark it not in changer and continue.
456        */
457       dcrVolCatInfo = VolCatInfo;      /* structure assignment */
458       devVolCatInfo = dev->VolCatInfo;      /* structure assignment */
459       /* Check if this is a valid Volume in the pool */
460       bstrncpy(saveVolumeName, VolumeName, sizeof(saveVolumeName));
461       bstrncpy(VolumeName, dev->VolHdr.VolumeName, sizeof(VolumeName));
462       if (!dir_get_volume_info(this, VolumeName, GET_VOL_INFO_FOR_WRITE)) {
463          POOL_MEM vol_info_msg;
464          pm_strcpy(vol_info_msg, jcr->dir_bsock->msg);  /* save error message */
465          /* Restore desired volume name, note device info out of sync */
466          /* This gets the info regardless of the Pool */
467          bstrncpy(VolumeName, dev->VolHdr.VolumeName, sizeof(VolumeName));
468          if (autochanger && !dir_get_volume_info(this, VolumeName, GET_VOL_INFO_FOR_READ)) {
469             /*
470              * If we get here, we know we cannot write on the Volume,
471              *  and we know that we cannot read it either, so it
472              *  is not in the autochanger.
473              */
474             mark_volume_not_inchanger();
475          }
476          dev->VolCatInfo = devVolCatInfo;    /* structure assignment */
477          dev->set_unload();                  /* unload this volume */
478          Jmsg(jcr, M_WARNING, 0, _("Director wanted Volume \"%s\".\n"
479               "    Current Volume \"%s\" not acceptable because:\n"
480               "    %s"),
481              dcrVolCatInfo.VolCatName, dev->VolHdr.VolumeName,
482              vol_info_msg.c_str());
483          ask = true;
484          /* Restore saved DCR before continuing */
485          bstrncpy(VolumeName, saveVolumeName, sizeof(VolumeName));
486          VolCatInfo = dcrVolCatInfo;  /* structure assignment */
487          goto check_next_volume;
488       }
489       /*
490        * This was not the volume we expected, but it is OK with
491        * the Director, so use it.
492        */
493       Dmsg1(150, "Got new Volume name=%s\n", VolumeName);
494       dev->VolCatInfo = VolCatInfo;   /* structure assignment */
495       Dmsg1(100, "Call reserve_volume=%s\n", dev->VolHdr.VolumeName);
496       if (reserve_volume(this, dev->VolHdr.VolumeName) == NULL) {
497          if (!jcr->errmsg[0]) {
498             Jmsg3(jcr, M_WARNING, 0, _("Could not reserve volume %s on %s device %s\n"),
499                dev->VolHdr.VolumeName, dev->print_type(), dev->print_name());
500          } else {
501             Jmsg(jcr, M_WARNING, 0, "%s", jcr->errmsg);
502          }
503          ask = true;
504          dev->setVolCatInfo(false);
505          setVolCatInfo(false);
506          goto check_next_volume;
507       }
508       break;                /* got a Volume */
509    /*
510     * At this point, we assume we have a blank tape mounted.
511     */
512    case VOL_IO_ERROR:
513       /* Fall through wanted */
514    case VOL_NO_LABEL:
515       switch (try_autolabel(true)) {
516       case try_next_vol:
517          goto check_next_volume;
518       case try_read_vol:
519          goto check_read_volume;
520       case try_error:
521          goto check_bail_out;
522       case try_default:
523          break;
524       }
525       /* NOTE! Fall-through wanted. */
526    case VOL_NO_MEDIA:
527    default:
528       Dmsg0(200, "VOL_NO_MEDIA or default.\n");
529       /* Send error message */
530       if (!dev->poll) {
531       } else {
532          Dmsg1(200, "Msg suppressed by poll: %s\n", jcr->errmsg);
533       }
534       ask = true;
535       /* Needed, so the medium can be changed */
536       if (dev->requires_mount()) {
537          dev->close(this);
538          free_volume(dev);
539       }
540       goto check_next_volume;
541    }
542    Leave(200);
543    return check_ok;
544
545 check_next_volume:
546    dev->setVolCatInfo(false);
547    setVolCatInfo(false);
548    Leave(200);
549    return check_next_vol;
550
551 check_bail_out:
552    Leave(200);
553    return check_error;
554
555 check_read_volume:
556    Leave(200);
557    return check_read_vol;
558
559 }
560
561
562 bool DCR::is_suitable_volume_mounted()
563 {
564    bool ok;
565
566    /* Volume mounted? */
567    if (dev->VolHdr.VolumeName[0] == 0 || dev->swap_dev || dev->must_unload()) {
568       return false;                      /* no */
569    }
570    bstrncpy(VolumeName, dev->VolHdr.VolumeName, sizeof(VolumeName));
571    ok = dir_get_volume_info(this, VolumeName, GET_VOL_INFO_FOR_WRITE);
572    if (!ok) {
573       Dmsg1(40, "dir_get_volume_info failed: %s", jcr->errmsg);
574       dev->set_wait();
575    }
576    return ok;
577 }
578
579 bool DCR::do_unload()
580 {
581    if (dev->must_unload()) {
582       Dmsg1(100, "must_unload release %s\n", dev->print_name());
583       release_volume();
584    }
585    return false;
586 }
587
588 bool DCR::do_load(bool is_writing)
589 {
590    if (dev->must_load()) {
591       Dmsg1(100, "Must load dev=%s\n", dev->print_name());
592       if (autoload_device(this, is_writing, NULL) > 0) {
593          dev->clear_load();
594          return true;
595       }
596       return false;
597    }
598    return true;
599 }
600
601 void DCR::do_swapping(bool is_writing)
602 {
603    /*
604     * See if we are asked to swap the Volume from another device
605     *  if so, unload the other device here, and attach the
606     *  volume to our drive.
607     */
608    if (dev->swap_dev) {
609       if (dev->swap_dev->must_unload()) {
610          if (dev->vol) {
611             dev->swap_dev->set_slot(dev->vol->get_slot());
612          }
613          Dmsg2(100, "Swap unloading slot=%d %s\n", dev->swap_dev->get_slot(),
614                dev->swap_dev->print_name());
615          unload_dev(this, dev->swap_dev);
616       }
617       if (dev->vol) {
618          dev->vol->clear_swapping();
619          Dmsg1(100, "=== set in_use vol=%s\n", dev->vol->vol_name);
620          dev->vol->clear_in_use();
621          dev->VolHdr.VolumeName[0] = 0;  /* don't yet have right Volume */
622       } else {
623          Dmsg1(100, "No vol on dev=%s\n", dev->print_name());
624       }
625       if (dev->swap_dev->vol) {
626          Dmsg2(100, "Vol=%s on dev=%s\n", dev->swap_dev->vol->vol_name,
627               dev->swap_dev->print_name());
628       }
629       Dmsg2(100, "Set swap_dev=NULL for dev=%s swap_dev=%s\n",
630          dev->print_name(), dev->swap_dev->print_name());
631       dev->swap_dev = NULL;
632    } else {
633       if (dev->vol) {
634       Dmsg1(100, "No swap_dev set. dev->vol=%p\n", dev->vol);
635       } else {
636       Dmsg1(100, "No swap_dev set. dev->vol=%p\n", dev->vol);
637       }
638    }
639 }
640
641 /*
642  * If permitted, we label the device, make sure we can do
643  *   it by checking that the VolCatBytes is zero => not labeled,
644  *   once the Volume is labeled we don't want to label another
645  *   blank tape with the same name.  For disk, we go ahead and
646  *   label it anyway, because the OS insures that there is only
647  *   one Volume with that name.
648  * As noted above, at this point dcr->VolCatInfo has what
649  *   the Director wants and dev->VolCatInfo has info on the
650  *   previous tape (or nothing).
651  *
652  * Return codes are:
653  *   try_next_vol        label failed, look for another volume
654  *   try_read_vol        labeled volume, now re-read the label
655  *   try_error           hard error (catalog update)
656  *   try_default         I couldn't do anything
657  */
658 int DCR::try_autolabel(bool opened)
659 {
660    DCR *dcr = this;
661
662    if (dev->poll && !dev->is_tape()) {
663       Dmsg0(100, "No autolabel because polling.\n");
664       return try_default;       /* if polling, don't try to create new labels */
665    }
666    /* For a tape require it to be opened and read before labeling */
667    if (!opened && (dev->is_tape() || dev->is_null())) {
668       return try_default;
669    }
670    if (dev->has_cap(CAP_LABEL) && (VolCatInfo.VolCatBytes == 0 ||
671          (!dev->is_tape() && strcmp(VolCatInfo.VolCatStatus,
672                                 "Recycle") == 0))) {
673       Dmsg1(40, "Create new volume label vol=%s\n", VolumeName);
674       /* Create a new Volume label and write it to the device */
675       if (!dev->write_volume_label(dcr, VolumeName,
676              pool_name, false, /* no relabel */ false /* defer label */)) {
677          Dmsg2(100, "write_vol_label failed. vol=%s, pool=%s\n",
678            VolumeName, pool_name);
679          if (opened) {
680             mark_volume_in_error();
681          }
682          return try_next_vol;
683       }
684       Dmsg0(150, "dir_update_vol_info. Set Append\n");
685       /* Copy Director's info into the device info */
686       dev->VolCatInfo = VolCatInfo;    /* structure assignment */
687       if (!dir_update_volume_info(dcr, true, true)) {  /* indicate tape labeled */
688          Dmsg3(100, "Update_vol_info failed no autolabel Volume \"%s\" on %s device %s.\n",
689             VolumeName, dev->print_type(), dev->print_name());
690          return try_error;
691       }
692       Jmsg(dcr->jcr, M_INFO, 0, _("Labeled new Volume \"%s\" on %s device %s.\n"),
693          VolumeName, dev->print_type(), dev->print_name());
694       Dmsg3(100, "Labeled new Volume \"%s\" on %s device %s.\n",
695          VolumeName, dev->print_type(), dev->print_name());
696       return try_read_vol;   /* read label we just wrote */
697    } else {
698       Dmsg4(40, "=== Cannot autolabel: cap_label=%d VolCatBytes=%lld is_tape=%d VolCatStatus=%s\n",
699          dev->has_cap(CAP_LABEL), VolCatInfo.VolCatBytes, dev->is_tape(),
700          VolCatInfo.VolCatStatus);
701    }
702    if (!dev->has_cap(CAP_LABEL) && VolCatInfo.VolCatBytes == 0) {
703       Jmsg(jcr, M_WARNING, 0, _("%s device %s not configured to autolabel Volumes.\n"),
704          dev->print_type(), dev->print_name());
705    }
706 #ifdef xxx
707    /* If not removable, Volume is broken */
708    if (!dev->is_removable()) {
709       Jmsg3(jcr, M_WARNING, 0, _("Volume \"%s\" not loaded on %s device %s.\n"),
710          VolumeName, dev->print_type(), dev->print_name());
711       Dmsg3(40, "Volume \"%s\" not loaded on %s device %s.\n",
712          VolumeName, dev->print_type(), dev->print_name());
713
714       mark_volume_in_error();
715       return try_next_vol;
716    }
717 #endif
718    return try_default;
719 }
720
721
722 /*
723  * Mark volume in error in catalog
724  */
725 void DCR::mark_volume_in_error()
726 {
727    Jmsg(jcr, M_INFO, 0, _("Marking Volume \"%s\" in Error in Catalog.\n"),
728         VolumeName);
729    dev->VolCatInfo = VolCatInfo;       /* structure assignment */
730    dev->setVolCatStatus("Error");
731    Dmsg0(150, "dir_update_vol_info. Set Error.\n");
732    dir_update_volume_info(this, false, false);
733    volume_unused(this);
734    Dmsg0(50, "set_unload\n");
735    dev->set_unload();                 /* must get a new volume */
736 }
737
738 /*
739  * Mark volume read_only in catalog
740  */
741 void DCR::mark_volume_read_only()
742 {
743    Jmsg(jcr, M_INFO, 0, _("Marking Volume \"%s\" Read-Only in Catalog.\n"),
744         VolumeName);
745    dev->VolCatInfo = VolCatInfo;       /* structure assignment */
746    dev->setVolCatStatus("Read-Only");
747    Dmsg0(150, "dir_update_vol_info. Set Read-Only.\n");
748    dir_update_volume_info(this, false, false);
749    volume_unused(this);
750    Dmsg0(50, "set_unload\n");
751    dev->set_unload();                 /* must get a new volume */
752 }
753
754
755 /*
756  * The Volume is not in the correct slot, so mark this
757  *   Volume as not being in the Changer.
758  */
759 void DCR::mark_volume_not_inchanger()
760 {
761    Jmsg(jcr, M_ERROR, 0, _("Autochanger Volume \"%s\" not found in slot %d.\n"
762 "    Setting InChanger to zero in catalog.\n"),
763         getVolCatName(), VolCatInfo.Slot);
764    dev->VolCatInfo = VolCatInfo;    /* structure assignment */
765    VolCatInfo.InChanger = false;
766    dev->VolCatInfo.InChanger = false;
767    Dmsg0(400, "update vol info in mount\n");
768    dir_update_volume_info(this, true, false);  /* set new status */
769 }
770
771 /*
772  * Either because we are going to hang a new volume, or because
773  *  of explicit user request, we release the current volume.
774  */
775 void DCR::release_volume()
776 {
777    unload_autochanger(this, -1);
778
779    if (WroteVol) {
780       Jmsg0(jcr, M_ERROR, 0, _("Hey!!!!! WroteVol non-zero !!!!!\n"));
781       Pmsg0(190, "Hey!!!!! WroteVol non-zero !!!!!\n");
782    }
783
784    if (dev->is_open() && (!dev->is_tape() || !dev->has_cap(CAP_ALWAYSOPEN))) {
785       generate_plugin_event(jcr, bsdEventDeviceClose, this);
786       dev->close(this);
787    }
788
789    /* If we have not closed the device, then at least rewind the tape */
790    if (dev->is_open()) {
791       dev->offline_or_rewind(this);
792    }
793
794    /*
795     * Erase all memory of the current volume
796     */
797    free_volume(dev);
798    dev->block_num = dev->file = 0;
799    dev->EndBlock = dev->EndFile = 0;
800    memset(&dev->VolCatInfo, 0, sizeof(dev->VolCatInfo));
801    dev->clear_volhdr();
802    /* Force re-read of label */
803    dev->clear_labeled();
804    dev->clear_read();
805    dev->clear_append();
806    dev->label_type = B_BACULA_LABEL;
807    VolumeName[0] = 0;
808
809    Dmsg0(190, "release_volume\n");
810 }
811
812 /*
813  *      Insanity check
814  *
815  * Check to see if the tape position as defined by the OS is
816  *  the same as our concept.  If it is not,
817  *  it means the user has probably manually rewound the tape.
818  * Note, we check only if num_writers == 0, but this code will
819  *  also work fine for any number of writers. If num_writers > 0,
820  *  we probably should cancel all jobs using this device, or
821  *  perhaps even abort the SD, or at a minimum, mark the tape
822  *  in error.  Another strategy with num_writers == 0, would be
823  *  to rewind the tape and do a new eod() request.
824  */
825 bool DCR::is_tape_position_ok()
826 {
827    if (dev->is_tape() && dev->num_writers == 0) {
828       int32_t file = dev->get_os_tape_file();
829       if (file >= 0 && file != (int32_t)dev->get_file()) {
830          Jmsg(jcr, M_ERROR, 0, _("Invalid tape position on volume \"%s\""
831               " on device %s. Expected %d, got %d\n"),
832               dev->VolHdr.VolumeName, dev->print_name(), dev->get_file(), file);
833          /*
834           * If the current file is greater than zero, it means we probably
835           *  have some bad count of EOF marks, so mark tape in error.  Otherwise
836           *  the operator might have moved the tape, so we just release it
837           *  and try again.
838           */
839          if (file > 0) {
840             mark_volume_in_error();
841          }
842          release_volume();
843          return false;
844       }
845    }
846    return true;
847 }
848
849
850 /*
851  * If we are reading, we come here at the end of the tape
852  *  and see if there are more volumes to be mounted.
853  */
854 bool mount_next_read_volume(DCR *dcr)
855 {
856    DEVICE *dev = dcr->dev;
857    JCR *jcr = dcr->jcr;
858    Dmsg2(90, "NumReadVolumes=%d CurReadVolume=%d\n", jcr->NumReadVolumes, jcr->CurReadVolume);
859
860    volume_unused(dcr);                /* release current volume */
861    /*
862     * End Of Tape -- mount next Volume (if another specified)
863     */
864    if (jcr->NumReadVolumes > 1 && jcr->CurReadVolume < jcr->NumReadVolumes) {
865       dev->Lock();
866       dev->close(dcr);
867       dev->set_read();
868       dcr->set_reserved_for_read();
869       dev->Unlock();
870       if (!acquire_device_for_read(dcr)) {
871          Jmsg3(jcr, M_FATAL, 0, _("Cannot open %s Dev=%s, Vol=%s for reading.\n"),
872             dev->print_type(), dev->print_name(), dcr->VolumeName);
873          jcr->setJobStatus(JS_FatalError); /* Jmsg is not working for *SystemJob* */
874          return false;
875       }
876       return true;                    /* next volume mounted */
877    }
878    Dmsg0(90, "End of Device reached.\n");
879    return false;
880 }