1 /*
2    Bacula(R) - The Network Backup Solution
3 
4    Copyright (C) 2000-2020 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  */
mount_next_write_volume()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       if (strcmp(dev->VolHdr.VolumeName, dcr->VolCatInfo.VolCatName) == 0) {
266          dev->set_volcatinfo_from_dcr(this);
267 
268       } else {      /* We have a volume, but not the current one */
269          Dmsg2(5, "Will need to re-mount volumes %s %s\n",
270                dev->VolHdr.VolumeName, dcr->VolCatInfo.VolCatName);
271          goto mount_next_vol;
272       }
273    }
274 
275    /*
276     * See if we have a fresh tape or a tape with data.
277     *
278     * Note, if the LabelType is PRE_LABEL, it was labeled
279     *  but never written. If so, rewrite the label but set as
280     *  VOL_LABEL.  We rewind and return the label (reconstructed)
281     *  in the block so that in the case of a new tape, data can
282     *  be appended just after the block label.  If we are writing
283     *  a second volume, the calling routine will write the label
284     *  before writing the overflow block.
285     *
286     *  If the tape is marked as Recycle, we rewrite the label.
287     */
288    recycle = strcmp(dev->VolCatInfo.VolCatStatus, "Recycle") == 0;
289    if (dev->VolHdr.LabelType == PRE_LABEL || recycle) {
290       dcr->WroteVol = false;
291       if (!dev->rewrite_volume_label(dcr, recycle)) {
292          mark_volume_in_error();
293          goto mount_next_vol;
294       }
295    } else {
296       /*
297        * OK, at this point, we have a valid Bacula label, but
298        * we need to position to the end of the volume, since we are
299        * just now putting it into append mode.
300        */
301       Dmsg1(100, "Device previously written, moving to end of data. Expect %lld bytes\n",
302            dev->VolCatInfo.VolCatBytes);
303       Jmsg(jcr, M_INFO, 0, _("Volume \"%s\" previously written, moving to end of data.\n"),
304          VolumeName);
305 
306       if (!dev->eod(dcr)) {
307          Dmsg3(050, "Unable to position to end of data on %s device %s: ERR=%s\n",
308             dev->print_type(), dev->print_name(), dev->bstrerror());
309          Jmsg(jcr, M_ERROR, 0, _("Unable to position to end of data on %s device %s: ERR=%s\n"),
310             dev->print_type(), dev->print_name(), dev->bstrerror());
311          mark_volume_in_error();
312          goto mount_next_vol;
313       }
314 
315       if (!dev->is_eod_valid(dcr)) {
316          Dmsg0(100, "goto mount_next_vol\n");
317          goto mount_next_vol;
318       }
319 
320       dev->VolCatInfo.VolCatMounts++;      /* Update mounts */
321       Dmsg1(150, "update volinfo mounts=%d\n", dev->VolCatInfo.VolCatMounts);
322       if (!dir_update_volume_info(dcr, false, false)) {
323          goto bail_out;
324       }
325 
326       /* Return an empty block */
327       empty_block(block);             /* we used it for reading so set for write */
328    }
329    dev->set_append();
330    Dmsg1(150, "set APPEND, normal return from mount_next_write_volume. dev=%s\n",
331       dev->print_name());
332 
333    V(mount_mutex);
334    return true;
335 
336 bail_out:
337    V(mount_mutex);
338 
339 no_lock_bail_out:
340    Leave(200);
341    return false;
342 }
343 
344 /*
345  * This routine is meant to be called once the first pass
346  *   to ensure that we have a candidate volume to mount.
347  *   Otherwise, we ask the sysop to created one.
348  * Note, mount_mutex is already locked on entry and thus
349  *   must remain locked on exit from this function.
350  */
find_a_volume()351 bool DCR::find_a_volume()
352 {
353    DCR *dcr = this;
354    bool ok;
355 
356    if (!is_suitable_volume_mounted()) {
357       bool have_vol = false;
358       /* Do we have a candidate volume? */
359       if (dev->vol) {
360          bstrncpy(VolumeName, dev->vol->vol_name, sizeof(VolumeName));
361          have_vol = dir_get_volume_info(this, VolumeName, GET_VOL_INFO_FOR_WRITE);
362       }
363       /*
364        * Get Director's idea of what tape we should have mounted.
365        *    in dcr->VolCatInfo
366        */
367       if (!have_vol) {
368          Dmsg0(200, "Before dir_find_next_appendable_volume.\n");
369          while (!dir_find_next_appendable_volume(dcr)) {
370             Dmsg0(200, "not dir_find_next\n");
371             if (job_canceled(jcr)) {
372                return false;
373             }
374             /*
375              * Unlock the mount mutex while waiting or
376              *   the Director for a new volume
377              */
378             V(mount_mutex);
379             if (dev->must_wait()) {
380                int retries = 5;
381                Dmsg0(40, "No appendable volume. Calling wait_for_device\n");
382                wait_for_device(dcr, retries);
383                ok = true;
384             } else {
385                ok = dir_ask_sysop_to_create_appendable_volume(dcr);
386             }
387             P(mount_mutex);
388             if (!ok || job_canceled(jcr)) {
389                return false;
390             }
391             Dmsg0(150, "Again dir_find_next_append...\n");
392          }
393          dev->clear_wait();
394       }
395    }
396    if (dcr->haveVolCatInfo()) {
397       return true;
398    }
399    return dir_get_volume_info(dcr, VolumeName, GET_VOL_INFO_FOR_WRITE);
400 }
401 
check_volume_label(bool & ask,bool & autochanger)402 int DCR::check_volume_label(bool &ask, bool &autochanger)
403 {
404    int vol_label_status;
405 
406    Enter(200);
407 
408    set_ameta();
409    /*
410     * If we are writing to a stream device, ASSUME the volume label
411     *  is correct.
412     */
413    if (dev->has_cap(CAP_STREAM)) {
414       vol_label_status = VOL_OK;
415       create_volume_header(dev, VolumeName, "Default", false);
416       dev->VolHdr.LabelType = PRE_LABEL;
417    } else {
418       vol_label_status = dev->read_dev_volume_label(this);
419    }
420    if (job_canceled(jcr)) {
421       goto check_bail_out;
422    }
423 
424    Dmsg2(150, "Want dirVol=%s dirStat=%s\n", VolumeName,
425       VolCatInfo.VolCatStatus);
426 
427    /*
428     * At this point, dev->VolCatInfo has what is in the drive, if anything,
429     *          and   dcr->VolCatInfo has what the Director wants.
430     */
431    switch (vol_label_status) {
432    case VOL_OK:
433       Dmsg1(150, "Vol OK name=%s\n", dev->VolHdr.VolumeName);
434       dev->VolCatInfo = VolCatInfo;       /* structure assignment */
435       break;                    /* got a Volume */
436    case VOL_NAME_ERROR:
437       VOLUME_CAT_INFO dcrVolCatInfo, devVolCatInfo;
438       char saveVolumeName[MAX_NAME_LENGTH];
439 
440       Dmsg2(40, "Vol NAME Error Have=%s, want=%s\n", dev->VolHdr.VolumeName, VolumeName);
441       if (dev->is_volume_to_unload()) {
442          ask = true;
443          goto check_next_volume;
444       }
445 
446 #ifdef xxx
447       /* If not removable, Volume is broken */
448       if (!dev->is_removable()) {
449          Jmsg3(jcr, M_WARNING, 0, _("Volume \"%s\" not loaded on %s device %s.\n"),
450             VolumeName, dev->print_type(), dev->print_name());
451          Dmsg3(40, "Volume \"%s\" not loaded on %s device %s.\n",
452             VolumeName, dev->print_type(), dev->print_name());
453          mark_volume_in_error();
454          goto check_next_volume;
455       }
456 #endif
457 
458       /*
459        * OK, we got a different volume mounted. First save the
460        *  requested Volume info (dcr) structure, then query if
461        *  this volume is really OK. If not, put back the desired
462        *  volume name, mark it not in changer and continue.
463        */
464       dcrVolCatInfo = VolCatInfo;      /* structure assignment */
465       devVolCatInfo = dev->VolCatInfo;      /* structure assignment */
466       /* Check if this is a valid Volume in the pool */
467       bstrncpy(saveVolumeName, VolumeName, sizeof(saveVolumeName));
468       bstrncpy(VolumeName, dev->VolHdr.VolumeName, sizeof(VolumeName));
469       if (!dir_get_volume_info(this, VolumeName, GET_VOL_INFO_FOR_WRITE)) {
470          POOL_MEM vol_info_msg;
471          pm_strcpy(vol_info_msg, jcr->dir_bsock->msg);  /* save error message */
472          /* Restore desired volume name, note device info out of sync */
473          /* This gets the info regardless of the Pool */
474          bstrncpy(VolumeName, dev->VolHdr.VolumeName, sizeof(VolumeName));
475          if (autochanger && !dir_get_volume_info(this, VolumeName, GET_VOL_INFO_FOR_READ)) {
476             /*
477              * If we get here, we know we cannot write on the Volume,
478              *  and we know that we cannot read it either, so it
479              *  is not in the autochanger.
480              */
481             mark_volume_not_inchanger();
482          }
483          dev->VolCatInfo = devVolCatInfo;    /* structure assignment */
484          dev->set_unload();                  /* unload this volume */
485          Jmsg(jcr, M_WARNING, 0, _("Director wanted Volume \"%s\".\n"
486               "    Current Volume \"%s\" not acceptable because:\n"
487               "    %s"),
488              dcrVolCatInfo.VolCatName, dev->VolHdr.VolumeName,
489              vol_info_msg.c_str());
490          ask = true;
491          /* Restore saved DCR before continuing */
492          bstrncpy(VolumeName, saveVolumeName, sizeof(VolumeName));
493          VolCatInfo = dcrVolCatInfo;  /* structure assignment */
494          goto check_next_volume;
495       }
496       /*
497        * This was not the volume we expected, but it is OK with
498        * the Director, so use it.
499        */
500       Dmsg1(150, "Got new Volume name=%s\n", VolumeName);
501       dev->VolCatInfo = VolCatInfo;   /* structure assignment */
502       Dmsg1(100, "Call reserve_volume=%s\n", dev->VolHdr.VolumeName);
503       if (reserve_volume(this, dev->VolHdr.VolumeName) == NULL) {
504          if (!jcr->errmsg[0]) {
505             Jmsg3(jcr, M_WARNING, 0, _("Could not reserve volume %s on %s device %s\n"),
506                dev->VolHdr.VolumeName, dev->print_type(), dev->print_name());
507          } else {
508             Jmsg(jcr, M_WARNING, 0, "%s", jcr->errmsg);
509          }
510          ask = true;
511          dev->setVolCatInfo(false);
512          setVolCatInfo(false);
513          goto check_next_volume;
514       }
515       break;                /* got a Volume */
516    /*
517     * At this point, we assume we have a blank tape mounted.
518     */
519    case VOL_IO_ERROR:
520       /* Fall through wanted */
521    case VOL_NO_LABEL:
522       switch (try_autolabel(true)) {
523       case try_next_vol:
524          goto check_next_volume;
525       case try_read_vol:
526          goto check_read_volume;
527       case try_error:
528          goto check_bail_out;
529       case try_default:
530          break;
531       }
532       /* NOTE! Fall-through wanted. */
533    case VOL_NO_MEDIA:
534    default:
535       Dmsg0(200, "VOL_NO_MEDIA or default.\n");
536       /* Send error message */
537       if (!dev->poll) {
538       } else {
539          Dmsg1(200, "Msg suppressed by poll: %s\n", jcr->errmsg);
540       }
541       ask = true;
542       /* Needed, so the medium can be changed */
543       if (dev->requires_mount()) {
544          dev->close(this);
545          free_volume(dev);
546       }
547       goto check_next_volume;
548    }
549    Leave(200);
550    return check_ok;
551 
552 check_next_volume:
553    dev->setVolCatInfo(false);
554    setVolCatInfo(false);
555    Leave(200);
556    return check_next_vol;
557 
558 check_bail_out:
559    Leave(200);
560    return check_error;
561 
562 check_read_volume:
563    Leave(200);
564    return check_read_vol;
565 
566 }
567 
568 
is_suitable_volume_mounted()569 bool DCR::is_suitable_volume_mounted()
570 {
571    bool ok;
572 
573    /* Volume mounted? */
574    if (dev->VolHdr.VolumeName[0] == 0 || dev->swap_dev || dev->must_unload()) {
575       return false;                      /* no */
576    }
577    bstrncpy(VolumeName, dev->VolHdr.VolumeName, sizeof(VolumeName));
578    ok = dir_get_volume_info(this, VolumeName, GET_VOL_INFO_FOR_WRITE);
579    if (!ok) {
580       Dmsg1(40, "dir_get_volume_info failed: %s", jcr->errmsg);
581       dev->set_wait();
582    }
583    return ok;
584 }
585 
do_unload()586 bool DCR::do_unload()
587 {
588    if (dev->must_unload()) {
589       Dmsg1(100, "must_unload release %s\n", dev->print_name());
590       release_volume();
591    }
592    return false;
593 }
594 
do_load(bool is_writing)595 bool DCR::do_load(bool is_writing)
596 {
597    if (dev->must_load()) {
598       Dmsg1(100, "Must load dev=%s\n", dev->print_name());
599       if (autoload_device(this, is_writing, NULL) > 0) {
600          dev->clear_load();
601          return true;
602       }
603       return false;
604    }
605    return true;
606 }
607 
do_swapping(bool is_writing)608 void DCR::do_swapping(bool is_writing)
609 {
610    /*
611     * See if we are asked to swap the Volume from another device
612     *  if so, unload the other device here, and attach the
613     *  volume to our drive.
614     */
615    if (dev->swap_dev) {
616       if (dev->swap_dev->must_unload()) {
617          if (dev->vol) {
618             dev->swap_dev->set_slot(dev->vol->get_slot());
619          }
620          Dmsg2(100, "Swap unloading slot=%d %s\n", dev->swap_dev->get_slot(),
621                dev->swap_dev->print_name());
622          unload_dev(this, dev->swap_dev);
623       }
624       if (dev->vol) {
625          dev->vol->clear_swapping();
626          Dmsg1(100, "=== set in_use vol=%s\n", dev->vol->vol_name);
627          dev->vol->clear_in_use();
628          dev->VolHdr.VolumeName[0] = 0;  /* don't yet have right Volume */
629       } else {
630          Dmsg1(100, "No vol on dev=%s\n", dev->print_name());
631       }
632       if (dev->swap_dev->vol) {
633          Dmsg2(100, "Vol=%s on dev=%s\n", dev->swap_dev->vol->vol_name,
634               dev->swap_dev->print_name());
635       }
636       Dmsg2(100, "Set swap_dev=NULL for dev=%s swap_dev=%s\n",
637          dev->print_name(), dev->swap_dev->print_name());
638       dev->swap_dev = NULL;
639    } else {
640       if (dev->vol) {
641       Dmsg1(100, "No swap_dev set. dev->vol=%p\n", dev->vol);
642       } else {
643       Dmsg1(100, "No swap_dev set. dev->vol=%p\n", dev->vol);
644       }
645    }
646 }
647 
648 /*
649  * If permitted, we label the device, make sure we can do
650  *   it by checking that the VolCatBytes is zero => not labeled,
651  *   once the Volume is labeled we don't want to label another
652  *   blank tape with the same name.  For disk, we go ahead and
653  *   label it anyway, because the OS insures that there is only
654  *   one Volume with that name.
655  * As noted above, at this point dcr->VolCatInfo has what
656  *   the Director wants and dev->VolCatInfo has info on the
657  *   previous tape (or nothing).
658  *
659  * Return codes are:
660  *   try_next_vol        label failed, look for another volume
661  *   try_read_vol        labeled volume, now re-read the label
662  *   try_error           hard error (catalog update)
663  *   try_default         I couldn't do anything
664  */
try_autolabel(bool opened)665 int DCR::try_autolabel(bool opened)
666 {
667    DCR *dcr = this;
668 
669    if (dev->poll && !dev->is_tape()) {
670       Dmsg0(100, "No autolabel because polling.\n");
671       return try_default;       /* if polling, don't try to create new labels */
672    }
673    /* For a tape require it to be opened and read before labeling */
674    if (!opened && (dev->is_tape() || dev->is_null())) {
675       return try_default;
676    }
677    if (dev->has_cap(CAP_LABEL) && (VolCatInfo.VolCatBytes == 0 ||
678          (!dev->is_tape() && strcmp(VolCatInfo.VolCatStatus,
679                                 "Recycle") == 0))) {
680       Dmsg1(40, "Create new volume label vol=%s\n", VolumeName);
681       /* Create a new Volume label and write it to the device */
682       if (!dev->write_volume_label(dcr, VolumeName,
683              pool_name, false, /* no relabel */ false /* defer label */)) {
684          Dmsg2(100, "write_vol_label failed. vol=%s, pool=%s\n",
685            VolumeName, pool_name);
686          if (opened) {
687             mark_volume_in_error();
688          }
689          return try_next_vol;
690       }
691       Dmsg0(150, "dir_update_vol_info. Set Append\n");
692       /* Copy Director's info into the device info */
693       dev->VolCatInfo = VolCatInfo;    /* structure assignment */
694       if (!dir_update_volume_info(dcr, true, true)) {  /* indicate tape labeled */
695          Dmsg3(100, "Update_vol_info failed no autolabel Volume \"%s\" on %s device %s.\n",
696             VolumeName, dev->print_type(), dev->print_name());
697          return try_error;
698       }
699       Jmsg(dcr->jcr, M_INFO, 0, _("Labeled new Volume \"%s\" on %s device %s.\n"),
700          VolumeName, dev->print_type(), dev->print_name());
701       Dmsg3(100, "Labeled new Volume \"%s\" on %s device %s.\n",
702          VolumeName, dev->print_type(), dev->print_name());
703       return try_read_vol;   /* read label we just wrote */
704    } else {
705       Dmsg4(40, "=== Cannot autolabel: cap_label=%d VolCatBytes=%lld is_tape=%d VolCatStatus=%s\n",
706          dev->has_cap(CAP_LABEL), VolCatInfo.VolCatBytes, dev->is_tape(),
707          VolCatInfo.VolCatStatus);
708    }
709    if (!dev->has_cap(CAP_LABEL) && VolCatInfo.VolCatBytes == 0) {
710       Jmsg(jcr, M_WARNING, 0, _("%s device %s not configured to autolabel Volumes.\n"),
711          dev->print_type(), dev->print_name());
712    }
713 #ifdef xxx
714    /* If not removable, Volume is broken */
715    if (!dev->is_removable()) {
716       Jmsg3(jcr, M_WARNING, 0, _("Volume \"%s\" not loaded on %s device %s.\n"),
717          VolumeName, dev->print_type(), dev->print_name());
718       Dmsg3(40, "Volume \"%s\" not loaded on %s device %s.\n",
719          VolumeName, dev->print_type(), dev->print_name());
720 
721       mark_volume_in_error();
722       return try_next_vol;
723    }
724 #endif
725    return try_default;
726 }
727 
728 
729 /*
730  * Mark volume in error in catalog
731  */
mark_volume_in_error()732 void DCR::mark_volume_in_error()
733 {
734    Jmsg(jcr, M_INFO, 0, _("Marking Volume \"%s\" in Error in Catalog.\n"),
735         VolumeName);
736    dev->VolCatInfo = VolCatInfo;       /* structure assignment */
737    dev->setVolCatStatus("Error");
738    Dmsg0(150, "dir_update_vol_info. Set Error.\n");
739    dir_update_volume_info(this, false, false);
740    volume_unused(this);
741    Dmsg0(50, "set_unload\n");
742    dev->set_unload();                 /* must get a new volume */
743 }
744 
745 /*
746  * Mark volume read_only in catalog
747  */
mark_volume_read_only()748 void DCR::mark_volume_read_only()
749 {
750    Jmsg(jcr, M_INFO, 0, _("Marking Volume \"%s\" Read-Only in Catalog.\n"),
751         VolumeName);
752    dev->VolCatInfo = VolCatInfo;       /* structure assignment */
753    dev->setVolCatStatus("Read-Only");
754    Dmsg0(150, "dir_update_vol_info. Set Read-Only.\n");
755    dir_update_volume_info(this, false, false);
756    volume_unused(this);
757    Dmsg0(50, "set_unload\n");
758    dev->set_unload();                 /* must get a new volume */
759 }
760 
761 
762 /*
763  * The Volume is not in the correct slot, so mark this
764  *   Volume as not being in the Changer.
765  */
mark_volume_not_inchanger()766 void DCR::mark_volume_not_inchanger()
767 {
768    Jmsg(jcr, M_ERROR, 0, _("Autochanger Volume \"%s\" not found in slot %d.\n"
769 "    Setting InChanger to zero in catalog.\n"),
770         getVolCatName(), VolCatInfo.Slot);
771    dev->VolCatInfo = VolCatInfo;    /* structure assignment */
772    VolCatInfo.InChanger = false;
773    dev->VolCatInfo.InChanger = false;
774    Dmsg0(400, "update vol info in mount\n");
775    dir_update_volume_info(this, true, false);  /* set new status */
776 }
777 
778 /*
779  * Either because we are going to hang a new volume, or because
780  *  of explicit user request, we release the current volume.
781  */
release_volume()782 void DCR::release_volume()
783 {
784    unload_autochanger(this, -1);
785 
786    if (WroteVol) {
787       Jmsg0(jcr, M_ERROR, 0, _("Hey!!!!! WroteVol non-zero !!!!!\n"));
788       Pmsg0(190, "Hey!!!!! WroteVol non-zero !!!!!\n");
789    }
790 
791    if (dev->is_open() && (!dev->is_tape() || !dev->has_cap(CAP_ALWAYSOPEN))) {
792       generate_plugin_event(jcr, bsdEventDeviceClose, this);
793       dev->close(this);
794    }
795 
796    /* If we have not closed the device, then at least rewind the tape */
797    if (dev->is_open()) {
798       dev->offline_or_rewind(this);
799    }
800 
801    /*
802     * Erase all memory of the current volume
803     */
804    free_volume(dev);
805    dev->block_num = dev->file = 0;
806    dev->EndBlock = dev->EndFile = 0;
807    memset(&dev->VolCatInfo, 0, sizeof(dev->VolCatInfo));
808    dev->clear_volhdr();
809    /* Force re-read of label */
810    dev->clear_labeled();
811    dev->clear_read();
812    dev->clear_append();
813    dev->label_type = B_BACULA_LABEL;
814    VolumeName[0] = 0;
815 
816    Dmsg0(190, "release_volume\n");
817 }
818 
819 /*
820  *      Insanity check
821  *
822  * Check to see if the tape position as defined by the OS is
823  *  the same as our concept.  If it is not,
824  *  it means the user has probably manually rewound the tape.
825  * Note, we check only if num_writers == 0, but this code will
826  *  also work fine for any number of writers. If num_writers > 0,
827  *  we probably should cancel all jobs using this device, or
828  *  perhaps even abort the SD, or at a minimum, mark the tape
829  *  in error.  Another strategy with num_writers == 0, would be
830  *  to rewind the tape and do a new eod() request.
831  */
is_tape_position_ok()832 bool DCR::is_tape_position_ok()
833 {
834    if (dev->is_tape() && dev->num_writers == 0) {
835       int32_t file = dev->get_os_tape_file();
836       if (file >= 0 && file != (int32_t)dev->get_file()) {
837          Jmsg(jcr, M_ERROR, 0, _("Invalid tape position on volume \"%s\""
838               " on device %s. Expected %d, got %d\n"),
839               dev->VolHdr.VolumeName, dev->print_name(), dev->get_file(), file);
840          /*
841           * If the current file is greater than zero, it means we probably
842           *  have some bad count of EOF marks, so mark tape in error.  Otherwise
843           *  the operator might have moved the tape, so we just release it
844           *  and try again.
845           */
846          if (file > 0) {
847             mark_volume_in_error();
848          }
849          release_volume();
850          return false;
851       }
852    }
853    return true;
854 }
855 
856 
857 /*
858  * If we are reading, we come here at the end of the tape
859  *  and see if there are more volumes to be mounted.
860  */
mount_next_read_volume(DCR * dcr)861 bool mount_next_read_volume(DCR *dcr)
862 {
863    DEVICE *dev = dcr->dev;
864    JCR *jcr = dcr->jcr;
865    Dmsg2(90, "NumReadVolumes=%d CurReadVolume=%d\n", jcr->NumReadVolumes, jcr->CurReadVolume);
866 
867    volume_unused(dcr);                /* release current volume */
868    /*
869     * End Of Tape -- mount next Volume (if another specified)
870     */
871    if (jcr->NumReadVolumes > 1 && jcr->CurReadVolume < jcr->NumReadVolumes) {
872       dev->Lock();
873       dev->close(dcr);
874       dev->set_read();
875       dcr->set_reserved_for_read();
876       dev->Unlock();
877       if (!acquire_device_for_read(dcr)) {
878          Jmsg3(jcr, M_FATAL, 0, _("Cannot open %s Dev=%s, Vol=%s for reading.\n"),
879             dev->print_type(), dev->print_name(), dcr->VolumeName);
880          jcr->setJobStatus(JS_FatalError); /* Jmsg is not working for *SystemJob* */
881          return false;
882       }
883       return true;                    /* next volume mounted */
884    }
885    Dmsg0(90, "End of Device reached.\n");
886    return false;
887 }
888