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