]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/stored/device.c
Implement Auto Prune and Auto Recycle
[bacula/bacula] / bacula / src / stored / device.c
1 /*
2  *
3  *  Higher Level Device routines. 
4  *  Knows about Bacula tape labels and such  
5  *
6  *  NOTE! In general, subroutines that have the word
7  *        "device" in the name do locking.  Subroutines
8  *        that have the word "dev" in the name do not
9  *        do locking.  Thus if xxx_device() calls
10  *        yyy_dev(), all is OK, but if xxx_device()
11  *        calls yyy_device(), everything will hang.
12  *        Obviously, no zzz_dev() is allowed to call
13  *        a www_device() or everything falls apart. 
14  *
15  * Concerning the routines lock_device() and block_device()
16  *  see the end of this module for details.  In general,
17  *  blocking a device leaves it in a state where all threads
18  *  other than the current thread block when they attempt to 
19  *  lock the device. They remain suspended (blocked) until the device
20  *  is unblocked. So, a device is blocked during an operation
21  *  that takes a long time (initialization, mounting a new
22  *  volume, ...) locking a device is done for an operation
23  *  that takes a short time such as writing data to the   
24  *  device.
25  *
26  *
27  *   Kern Sibbald, MM, MMI
28  *                            
29  *   Version $Id$
30  */
31 /*
32    Copyright (C) 2000, 2001, 2002 Kern Sibbald and John Walker
33
34    This program is free software; you can redistribute it and/or
35    modify it under the terms of the GNU General Public License as
36    published by the Free Software Foundation; either version 2 of
37    the License, or (at your option) any later version.
38
39    This program is distributed in the hope that it will be useful,
40    but WITHOUT ANY WARRANTY; without even the implied warranty of
41    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
42    General Public License for more details.
43
44    You should have received a copy of the GNU General Public
45    License along with this program; if not, write to the Free
46    Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
47    MA 02111-1307, USA.
48
49  */
50
51 #include "bacula.h"                   /* pull in global headers */
52 #include "stored.h"                   /* pull in Storage Deamon headers */
53
54 /* Forward referenced functions */
55 static int ready_dev_for_append(JCR *jcr, DEVICE *dev, DEV_BLOCK *block);
56 static int mount_next_volume(JCR *jcr, DEVICE *dev, DEV_BLOCK *label_blk);
57
58 extern char my_name[];
59 extern int debug_level;
60
61
62 /********************************************************************* 
63  * Acquire device for reading.  We permit (for the moment)
64  *  only one reader.  We read the Volume label from the block and
65  *  leave the block pointers just after the label.
66  *
67  *  Returns: 0 if failed for any reason
68  *           1 if successful
69  */
70 int acquire_device_for_read(JCR *jcr, DEVICE *dev, DEV_BLOCK *block)
71 {
72    int stat;
73
74    lock_device(dev);
75    if (dev->state & ST_READ || dev->num_writers > 0) {
76       Jmsg(jcr, M_FATAL, 0, _("Device %s is busy.\n"), dev_name(dev));
77       unlock_device(dev);
78       return 0;
79    }
80    dev->state &= ~ST_LABEL;           /* force reread of label */
81    block_device(dev, BST_DOING_ACQUIRE);
82    unlock_device(dev);
83    stat = ready_dev_for_read(jcr, dev, block);  
84    P(dev->mutex); 
85    unblock_device(dev);
86    V(dev->mutex);
87    return stat;
88 }
89
90 /*
91  * Acquire device for writing. We permit multiple writers.
92  *  If this is the first one, we read the label.
93  *
94  *  Returns: 0 if failed for any reason
95  *           1 if successful
96  */
97 int acquire_device_for_append(JCR *jcr, DEVICE *dev, DEV_BLOCK *block)
98 {
99
100    lock_device(dev);
101    Dmsg1(90, "acquire_append device is %s\n", dev_is_tape(dev)?"tape":"disk");
102    if (!(dev->state & ST_APPEND)) {
103       if (dev->state & ST_READ) {
104          Jmsg(jcr, M_FATAL, 0, _("Device %s is busy reading.\n"), dev_name(dev));
105          unlock_device(dev);
106          return 0;
107       } 
108       ASSERT(dev->num_writers == 0);
109       block_device(dev, BST_DOING_ACQUIRE);
110       unlock_device(dev);
111       if (!ready_dev_for_append(jcr, dev, block)) {
112          Jmsg(jcr, M_FATAL, 0, _("Could not ready device %s for append.\n"),
113             dev_name(dev));
114          P(dev->mutex);
115          unblock_device(dev);
116          V(dev->mutex);
117          return 0;
118       }
119       P(dev->mutex);
120       dev->VolCatInfo.VolCatJobs++;         /* increment number of jobs on this media */
121       dev->num_writers = 1;
122       if (jcr->NumVolumes == 0) {
123          jcr->NumVolumes = 1;
124       }
125       unblock_device(dev);
126       V(dev->mutex);
127       return 1;
128    } else { 
129       /* 
130        * Device already in append mode   
131        *
132        * Check if we have the right Volume mounted   
133        *  OK if AnonVols and volume info OK
134        *  OK if next volume matches current volume
135        *  otherwise mount desired volume obtained from
136        *    dir_find_next_appendable_volume
137        */
138       strcpy(jcr->VolumeName, dev->VolHdr.VolName);
139       if (((dev->capabilities & CAP_ANONVOLS) &&
140             !dir_get_volume_info(jcr)) ||
141           (!dir_find_next_appendable_volume(jcr) || 
142             strcmp(dev->VolHdr.VolName, jcr->VolumeName) != 0)) { /* wrong tape mounted */
143          if (dev->num_writers != 0) {
144             Jmsg(jcr, M_FATAL, 0, _("Device %s is busy writing with another Volume.\n"), dev_name(dev));
145             unlock_device(dev);
146             return 0;
147          }
148          /* Wrong tape currently mounted */  
149          block_device(dev, BST_DOING_ACQUIRE);
150          unlock_device(dev);
151          if (!mount_next_volume(jcr, dev, block)) {
152             Jmsg(jcr, M_FATAL, 0, _("Unable to mount desired volume.\n"));
153             P(dev->mutex);
154             unblock_device(dev);
155             V(dev->mutex);
156             return 0;
157          }
158          P(dev->mutex);
159          unblock_device(dev);
160       }
161    }
162    dev->VolCatInfo.VolCatJobs++;            /* increment number of jobs on this media */
163    dev->num_writers++;
164    if (dev->num_writers > 1) {
165       Dmsg2(0, "Hey!!!! There are %d writers on device %s\n", dev->num_writers,
166          dev_name(dev));
167    }
168    if (jcr->NumVolumes == 0) {
169       jcr->NumVolumes = 1;
170    }
171    unlock_device(dev);
172    return 1;                          /* got it */
173 }
174
175 /*
176  * This job is done, so release the device. From a Unix standpoint,
177  *  the device remains open.
178  *
179  */
180 int release_device(JCR *jcr, DEVICE *dev, DEV_BLOCK *block)
181 {
182    P(dev->mutex);
183    Dmsg1(90, "release_device device is %s\n", dev_is_tape(dev)?"tape":"disk");
184    if (dev->state & ST_READ) {
185       dev->state &= ~ST_READ;         /* clear read bit */
186       if (!dev_is_tape(dev)) {
187          close_dev(dev);
188       }
189       /******FIXME**** send read volume info to director */
190
191    } else if (dev->num_writers > 0) {
192       dev->num_writers--;
193       Dmsg1(90, "There are %d writers in release_device\n", dev->num_writers);
194       if (dev->num_writers == 0) {
195          weof_dev(dev, 1);
196          dev->VolCatInfo.VolCatFiles++;             /* increment number of files */
197          /* Note! do volume update before close, which zaps VolCatInfo */
198          dir_update_volume_info(jcr, &dev->VolCatInfo);   /* send Volume info to Director */
199          if (!dev_is_tape(dev)) {
200             close_dev(dev);
201          } else {
202             Dmsg0(90, "Device is tape leave open in release_device\n");
203          }
204       } else {
205          dir_update_volume_info(jcr, &dev->VolCatInfo);   /* send Volume info to Director */
206       }
207    } else {
208       Emsg1(M_ERROR, 0, _("BAD ERROR: release_device %s not in use.\n"), dev_name(dev));
209    }
210    V(dev->mutex);
211    return 1;
212 }
213
214
215
216 /*
217  * We rewind the current volume, which we no longer want, and
218  *  ask the user (console) to mount the next volume.
219  *
220  *  Continue trying until we get it, and we call
221  *  ready_dev_for_append() so that we can write on it.
222  *
223  * This routine retuns a 0 only if it is REALLY
224  *  impossible to get the requested Volume.
225  */
226 static int mount_next_volume(JCR *jcr, DEVICE *dev, DEV_BLOCK *label_blk)
227 {
228    Dmsg0(90, "Enter mount_next_volume()\n");
229
230    /* 
231     * First erase all memory of the current volume   
232     */
233    dev->block_num = 0;
234    dev->file = 0;
235    dev->LastBlockNumWritten = 0;
236    memset(&dev->VolCatInfo, 0, sizeof(dev->VolCatInfo));
237    memset(&dev->VolHdr, 0, sizeof(dev->VolHdr));
238
239    /* Keep trying until we get something good mounted */
240    for ( ;; ) {
241       if (job_cancelled(jcr)) {
242          Mmsg0(&dev->errmsg, "Job cancelled.\n");
243          return 0;
244       }
245
246       if (dev->state & ST_OPENED && !rewind_dev(dev)) {
247          Jmsg2(jcr, M_WARNING, 0, _("Rewind error on device %s. ERR=%s\n"), 
248                dev_name(dev), strerror_dev(dev));
249       }
250
251       /*
252        * Ask to mount and wait if necessary   
253        */
254       if (!dir_ask_sysop_to_mount_next_volume(jcr, dev)) {
255          Jmsg(jcr, M_FATAL, 0, _("Unable to mount next Volume on device %s\n"),
256             dev_name(dev));
257          return 0;
258       }
259
260       /* 
261        * Ready output device for writing
262        */
263       Dmsg1(120, "just before ready_dev_for_append dev=%x\n", dev);
264       if (!ready_dev_for_append(jcr, dev, label_blk)) {
265          continue;
266       }
267       dev->VolCatInfo.VolCatMounts++;
268       jcr->VolFirstFile = 0;
269       break;                       /* Got new volume, continue */
270    }
271    return 1;
272 }
273
274
275 /*
276  * This routine ensures that the device is ready for
277  * writing. We start from the assumption that there
278  * may not be a tape mounted. 
279  *
280  * If the device is a file, we create the output
281  * file. If it is a tape, we check the volume name
282  * and move the tape to the end of data.
283  *
284  * It assumes that the device is not already in use!
285  *
286  *  Returns 0 on failure
287  *  Returns 1 on success
288  */
289 static int ready_dev_for_append(JCR *jcr, DEVICE *dev, DEV_BLOCK *block)
290 {
291    int mounted = 0;
292    int recycle = 0;
293
294    Dmsg0(100, "Enter ready_dev_for_append\n");
295
296    dev->state &= ~(ST_LABEL|ST_APPEND|ST_READ|ST_EOT|ST_WEOT|ST_EOF);
297
298
299    for ( ;; ) {
300       if (job_cancelled(jcr)) {
301          Mmsg(&dev->errmsg, "Job %s cancelled.\n", jcr->Job);
302          return 0;
303       }
304
305       /* 
306        * Ask Director for Volume Info (Name, attributes) to use.         
307        */
308       if (!dir_find_next_appendable_volume(jcr)) {
309          if (!dir_ask_sysop_to_mount_next_volume(jcr, dev)) {
310             Jmsg1(jcr, M_ERROR, 0, _("Unable to mount desired Volume for device %s.\n"),
311                dev_name(dev));
312             return 0;              /* error return */
313          }
314       }
315       Dmsg1(200, "want vol=%s\n", jcr->VolumeName);
316
317       /* Open device */
318       for ( ; !(dev->state & ST_OPENED); ) {
319           if (open_dev(dev, jcr->VolCatInfo.VolCatName, READ_WRITE) < 0) {
320              if (dev->dev_errno == EAGAIN || dev->dev_errno == EBUSY) {
321                 sleep(30);
322              }
323              Jmsg2(jcr, M_ERROR, 0, _("Unable to open device %s. ERR=%s\n"), 
324                 dev_name(dev), strerror_dev(dev));
325              return 0;
326           }
327       }
328
329       /*
330        * Now make sure we have the right tape mounted
331        */
332       switch (read_dev_volume_label(jcr, dev, block)) {
333          case VOL_OK:
334             Dmsg1(200, "Vol OK name=%s\n", jcr->VolumeName);
335             memcpy(&dev->VolCatInfo, &jcr->VolCatInfo, sizeof(jcr->VolCatInfo));
336             if (strcmp(dev->VolCatInfo.VolCatStatus, "Recycle") == 0) {
337                recycle = 1;
338             }
339             break;                    /* got it */
340          case VOL_NAME_ERROR:
341             /* Check if we can accept this as an anonymous volume */
342             strcpy(jcr->VolumeName, dev->VolHdr.VolName);
343             if (!dev->capabilities & CAP_ANONVOLS ||
344                 !dir_get_volume_info(jcr)) {
345                goto mount_next_vol;
346             }
347             Dmsg1(200, "want new name=%s\n", jcr->VolumeName);
348             memcpy(&dev->VolCatInfo, &jcr->VolCatInfo, sizeof(jcr->VolCatInfo));
349             break;
350
351          case VOL_NO_LABEL:
352          case VOL_IO_ERROR:
353             /* If permitted, create a label */
354             if (dev->capabilities & CAP_LABEL) {
355                Dmsg0(90, "Create volume label\n");
356                if (!write_volume_label_to_dev(jcr, (DEVRES *)dev->device, jcr->VolumeName,
357                       jcr->pool_name)) {
358                   return 0;
359                }
360                Jmsg(jcr, M_INFO, 0, _("Created Volume label %s on device %s.\n"),
361                   jcr->VolumeName, dev_name(dev));
362                mounted = 1;
363                continue;              /* read label we just wrote */
364             } 
365             /* NOTE! Fall-through wanted. */
366          default:
367 mount_next_vol:
368             /* Send error message generated by read_dev_volume_label() */
369             Jmsg(jcr, M_WARNING, 0, "%s", jcr->errmsg);                         
370             rewind_dev(dev);
371             if (!dir_ask_sysop_to_mount_next_volume(jcr, dev)) {
372                Jmsg1(jcr, M_ERROR, 0, _("Unable to mount desired Volume for device %s.\n"),
373                   dev_name(dev));
374                return 0;              /* error return */
375             }
376             mounted = 1;
377             continue;                 /* try reading again */
378       }
379       break;
380    }
381    if (mounted) {
382       dev->VolCatInfo.VolCatMounts++;
383    }
384
385    /* 
386     * See if we have a fresh tape or tape with data.
387     *
388     * Note, if the LabelType is PRE_LABEL, it was labeled
389     *  but never written. If so, rewrite the label but set as
390     *  VOL_LABEL.  We rewind and return the label (reconstructed)
391     *  in the block so that in the case of a new tape, data can
392     *  be appended just after the block label.  If we are writing
393     *  an second volume, the calling routine will write the label
394     *  before writing the overflow block.
395     *
396     *  If the tape is marked as Recycle, we rewrite the label.
397     */
398    if (dev->VolHdr.LabelType == PRE_LABEL || recycle) {
399       Dmsg1(90, "ready_for_append found freshly labeled volume. dev=%x\n", dev);
400       dev->VolHdr.LabelType = VOL_LABEL; /* set Volume label */
401       write_volume_label_to_block(jcr, dev, block);
402       /*
403        * Write the block now to ensure we have write permission.
404        *  It is better to find out now rather than later.
405        */
406       dev->VolCatInfo.VolCatBytes = 0;
407       if (!rewind_dev(dev)) {
408          Jmsg2(jcr, M_WARNING, 0, _("Rewind error on device %s. ERR=%s\n"), 
409                dev_name(dev), strerror_dev(dev));
410       }
411       if (!write_block_to_dev(dev, block)) {
412          Jmsg2(jcr, M_ERROR, 0, _("Unable to write device %s. ERR=%s\n"),
413             dev_name(dev), strerror_dev(dev));
414          return 0;
415       }
416       if (!rewind_dev(dev)) {
417          Jmsg2(jcr, M_ERROR, 0, _("Unable to rewind device %s. ERR=%s\n"),
418             dev_name(dev), strerror_dev(dev));
419          return 0;
420       }
421       /* Recreate a correct volume label and return it in the block */
422       write_volume_label_to_block(jcr, dev, block);
423       dev->VolCatInfo.VolCatJobs = 1;
424       dev->VolCatInfo.VolCatFiles = 1;
425       dev->VolCatInfo.VolCatErrors = 0;
426       dev->VolCatInfo.VolCatBlocks = 1;
427       if (recycle) {
428          dev->VolCatInfo.VolCatMounts++;  
429          dev->VolCatInfo.VolCatRecycles++;
430       } else {
431          dev->VolCatInfo.VolCatMounts = 1;
432          dev->VolCatInfo.VolCatRecycles = 0;
433          dev->VolCatInfo.VolCatWrites = 1;
434          dev->VolCatInfo.VolCatReads = 1;
435       }
436       strcpy(dev->VolCatInfo.VolCatStatus, "Append");
437       dir_update_volume_info(jcr, &dev->VolCatInfo);
438       if (recycle) {
439          Jmsg(jcr, M_INFO, 0, _("Recycled volume %s on device %s, all previous data lost.\n"),
440             jcr->VolumeName, dev_name(dev));
441       } else {
442          Jmsg(jcr, M_INFO, 0, _("Wrote label to prelabeled Volume %s on device %s\n"),
443             jcr->VolumeName, dev_name(dev));
444       }
445
446    } else {
447       /* OK, at this point, we have a valid Bacula label, but
448        * we need to position to the end of the volume.
449        */
450       Dmsg0(20, "Device previously written, moving to end of data\n");
451       Jmsg(jcr, M_INFO, 0, _("Volume %s previously written, moving to end of data.\n"),
452          jcr->VolumeName);
453       if (!eod_dev(dev)) {
454          Jmsg(jcr, M_ERROR, 0, _("Unable to position to end of data %s. ERR=%s\n"),
455             dev_name(dev), strerror_dev(dev));
456          Jmsg(jcr, M_INFO, 0, _("Marking Volume %s in Error in Catalog.\n"),
457             jcr->VolumeName);
458          strcpy(dev->VolCatInfo.VolCatStatus, "Error");
459          dir_update_volume_info(jcr, &dev->VolCatInfo);
460          return 0;
461       }
462       /* *****FIXME**** we might do some checking for files too */
463       if (dev_is_tape(dev)) {
464          Jmsg(jcr, M_INFO, 0, _("Ready to append to end of Volume at file=%d.\n"), dev_file(dev));
465          if (dev->VolCatInfo.VolCatFiles != dev_file(dev) + 1) {
466             /* ****FIXME**** this should refuse to write on tape */
467             Jmsg(jcr, M_INFO, 0, _("Hey! Num files mismatch! Catalog Files=%d\n"), dev->VolCatInfo.VolCatFiles);
468          }
469       }
470       /* Return an empty block */
471       empty_block(block);             /* we used it for reading so set for write */
472    }
473    dev->state |= ST_APPEND;
474    Dmsg0(100, "Normal return from read_dev_for_append\n");
475    return 1; 
476 }
477
478 /*
479  * This routine ensures that the device is ready for
480  * reading. If it is a file, it opens it.
481  * If it is a tape, it checks the volume name 
482  *
483  *  Returns 0 on failure
484  *  Returns 1 on success
485  */
486 int ready_dev_for_read(JCR *jcr, DEVICE *dev, DEV_BLOCK *block)
487 {
488    if (!(dev->state & ST_OPENED)) {
489        Dmsg1(20, "bstored: open vol=%s\n", jcr->VolumeName);
490        if (open_dev(dev, jcr->VolumeName, READ_ONLY) < 0) {
491           Jmsg(jcr, M_FATAL, 0, _("Open device %s volume %s failed, ERR=%s\n"), 
492               dev_name(dev), jcr->VolumeName, strerror_dev(dev));
493           return 0;
494        }
495        Dmsg1(29, "open_dev %s OK\n", dev_name(dev));
496    }
497
498    for (;;) {
499       if (job_cancelled(jcr)) {
500          Mmsg0(&dev->errmsg, _("Job cancelled.\n"));
501          return 0;
502       }
503       if (!rewind_dev(dev)) {
504          Jmsg2(jcr, M_WARNING, 0, _("Rewind error on device %s. ERR=%s\n"), 
505                dev_name(dev), strerror_dev(dev));
506       }
507       switch (read_dev_volume_label(jcr, dev, block)) {
508          case VOL_OK:
509             break;                    /* got it */
510          default:
511             /* Send error message generated by read_dev_volume_label() */
512             Jmsg(jcr, M_WARNING, 0, "%s", jcr->errmsg);                         
513             if (!rewind_dev(dev)) {
514                Jmsg2(jcr, M_WARNING, 0, _("Rewind error on device %s. ERR=%s\n"), 
515                      dev_name(dev), strerror_dev(dev));
516             }
517             if (!dir_ask_sysop_to_mount_volume(jcr, dev)) {
518                return 0;              /* error return */
519             }
520             continue;                 /* try reading again */
521       }
522       break;
523    }
524
525    dev->state |= ST_READ;
526    return 1; 
527 }
528
529 /*
530  * This is the dreaded moment. We either have an end of
531  * medium condition or worse, and error condition.
532  * Attempt to "recover" by obtaining a new Volume.
533  *
534  * We enter with device locked, and 
535  *     exit with device locked.
536  *
537  * Note, we are called only from one place in block.c
538  *
539  *  Returns: 1 on success
540  *           0 on failure
541  */
542 int fixup_device_block_write_error(JCR *jcr, DEVICE *dev, DEV_BLOCK *block)
543 {
544    uint32_t stat = 0;                   
545    char PrevVolName[MAX_NAME_LENGTH];
546    DEV_BLOCK *label_blk;
547    char b1[30], b2[30];
548    time_t wait_time;
549
550    wait_time = time(NULL);
551    status_dev(dev, &stat);
552    if (stat & MT_EOD) {
553       Dmsg0(90, "======= Got EOD ========\n");
554
555       block_device(dev, BST_DOING_ACQUIRE);
556
557       strcpy(dev->VolCatInfo.VolCatStatus, "Full");
558       Dmsg0(90, "Call update_vol_info\n");
559       if (!dir_update_volume_info(jcr, &dev->VolCatInfo)) {    /* send Volume info to Director */
560          Jmsg(jcr, M_ERROR, 0, _("Could not update Volume info Volume=%s Job=%s\n"),
561             dev->VolCatInfo.VolCatName, jcr->Job);
562          return 0;                    /* device locked */
563       }
564       Dmsg0(90, "Back from update_vol_info\n");
565
566       strcpy(PrevVolName, dev->VolCatInfo.VolCatName);
567       strcpy(dev->VolHdr.PrevVolName, PrevVolName);
568
569       label_blk = new_block(dev);
570
571       /* Inform User about end of media */
572       Jmsg(jcr, M_INFO, 0, _("End of media on Volume %s Bytes=%s Blocks=%s.\n"), 
573            PrevVolName, edit_uint64_with_commas(dev->VolCatInfo.VolCatBytes, b1),
574            edit_uint64_with_commas(dev->VolCatInfo.VolCatBlocks, b2));
575
576       if (!dev_is_tape(dev)) {           /* If file, */
577          close_dev(dev);                 /* yes, close it */
578       }
579
580       /* Unlock, but leave BLOCKED */
581       unlock_device(dev);
582       if (!mount_next_volume(jcr, dev, label_blk)) {
583          P(dev->mutex);
584          unblock_device(dev);
585          return 0;                    /* device locked */
586       }
587
588       P(dev->mutex);                  /* lock again */
589
590       Jmsg(jcr, M_INFO, 0, _("New volume %s mounted on device %s\n"),
591          jcr->VolumeName, dev_name(dev));
592
593       /* 
594        * If this is a new tape, the label_blk will contain the
595        *  label, so write it now. If this is a previously
596        *  used tape, mount_next_volume() will return an
597        *  empty label_blk, and nothing will be written.
598        */
599       Dmsg0(90, "write label block to dev\n");
600       if (!write_block_to_dev(dev, label_blk)) {
601          Dmsg1(0, "write_block_to_device Volume label failed. ERR=%s",
602            strerror_dev(dev));
603          free_block(label_blk);
604          unblock_device(dev);
605          return 0;                    /* device locked */
606       }
607
608       /* Write overflow block to tape */
609       Dmsg0(90, "Write overflow block to dev\n");
610       if (!write_block_to_dev(dev, block)) {
611          Dmsg1(0, "write_block_to_device overflow block failed. ERR=%s",
612            strerror_dev(dev));
613          free_block(label_blk);
614          unblock_device(dev);
615          return 0;                    /* device locked */
616       }
617
618       jcr->NumVolumes++;
619       Dmsg0(90, "Wake up any waiting threads.\n");
620       free_block(label_blk);
621       unblock_device(dev);
622       jcr->run_time += time(NULL) - wait_time; /* correct run time */
623       return 1;                                /* device locked */
624    }
625    free_block(label_blk);
626    return 0;                          /* device locked */
627 }
628
629
630 /*
631  *   Open the device. Expect dev to already be initialized.  
632  *
633  *   This routine is used only when the Storage daemon starts 
634  *   and always_open is set, and in the stand-alone utility
635  *   routines such as bextract.
636  *
637  *   Note, opening of a normal file is deferred to later so
638  *    that we can get the filename; the device_name for
639  *    a file is the directory only. 
640  *
641  *   Retuns: 0 on failure
642  *           1 on success
643  */
644 int open_device(DEVICE *dev)
645 {
646    Dmsg0(20, "start open_output_device()\n");
647    if (!dev) {
648       return 0;
649    }
650
651    lock_device(dev);
652
653    /* Defer opening files */
654    if (!dev_is_tape(dev)) {
655       Dmsg0(29, "Device is file, deferring open.\n");
656       unlock_device(dev);
657       return 1;
658    }
659
660    if (!(dev->state & ST_OPENED)) {
661       Dmsg0(29, "Opening device.\n");
662       if (open_dev(dev, NULL, READ_WRITE) < 0) {
663          Emsg1(M_FATAL, 0, _("dev open failed: %s\n"), dev->errmsg);
664          unlock_device(dev);
665          return 0;
666       }
667    }
668    Dmsg1(29, "open_dev %s OK\n", dev_name(dev));
669
670    unlock_device(dev);
671    return 1;
672 }
673
674
675 /* 
676  * When dev_blocked is set, all threads EXCEPT thread with id no_wait_id
677  * must wait. The no_wait_id thread is out obtaining a new volume
678  * and preparing the label.
679  */
680 void lock_device(DEVICE *dev)
681 {
682    int stat;
683
684    Dmsg1(90, "lock %d\n", dev->dev_blocked);
685    P(dev->mutex);
686    if (dev->dev_blocked && !pthread_equal(dev->no_wait_id, pthread_self())) {
687       dev->num_waiting++;             /* indicate that I am waiting */
688       while (dev->dev_blocked) {
689          if ((stat = pthread_cond_wait(&dev->wait, &dev->mutex)) != 0) {
690             V(dev->mutex);
691             Emsg1(M_ABORT, 0, _("pthread_cond_wait failure. ERR=%s\n"),
692                strerror(stat));
693          }
694       }
695       dev->num_waiting--;             /* no longer waiting */
696    }
697 }
698
699 void unlock_device(DEVICE *dev) 
700 {
701    Dmsg0(90, "unlock\n");
702    V(dev->mutex);
703 }
704
705 /* 
706  * Block all other threads from using the device
707  *  Device must already be locked.  After this call,
708  *  the device is blocked to any thread calling lock_device(),
709  *  but the device is not locked (i.e. no P on device).  Also,
710  *  the current thread can do slip through the lock_device()
711  *  calls without blocking.
712  */
713 void block_device(DEVICE *dev, int state)
714 {
715    Dmsg1(90, "block set %d\n", state);
716    ASSERT(dev->dev_blocked == BST_NOT_BLOCKED);
717    dev->dev_blocked = state;          /* make other threads wait */
718    dev->no_wait_id = pthread_self();  /* allow us to continue */
719 }
720
721 /*
722  * Unblock the device, and wake up anyone who went to sleep.
723  */
724 void unblock_device(DEVICE *dev)
725 {
726    Dmsg1(90, "unblock %d\n", dev->dev_blocked);
727    ASSERT(dev->dev_blocked);
728    dev->dev_blocked = BST_NOT_BLOCKED;
729    if (dev->num_waiting > 0) {
730       pthread_cond_broadcast(&dev->wait); /* wake them up */
731    }
732 }