]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/stored/device.c
Make Recycle work -- kes25May02
[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, 0); /* 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, 0); /* send Volume info to Director */
206       }
207    } else {
208       Jmsg1(jcr, 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 (recycle) {
412          if (!truncate_dev(dev)) {
413             Jmsg2(jcr, M_WARNING, 0, _("Truncate error on device %s. ERR=%s\n"), 
414                   dev_name(dev), strerror_dev(dev));
415          }
416       }
417       if (!write_block_to_dev(dev, block)) {
418          Jmsg2(jcr, M_ERROR, 0, _("Unable to write device %s. ERR=%s\n"),
419             dev_name(dev), strerror_dev(dev));
420          return 0;
421       }
422       if (!rewind_dev(dev)) {
423          Jmsg2(jcr, M_ERROR, 0, _("Unable to rewind device %s. ERR=%s\n"),
424             dev_name(dev), strerror_dev(dev));
425          return 0;
426       }
427       /* Recreate a correct volume label and return it in the block */
428       write_volume_label_to_block(jcr, dev, block);
429       dev->VolCatInfo.VolCatJobs = 1;
430       dev->VolCatInfo.VolCatFiles = 1;
431       dev->VolCatInfo.VolCatErrors = 0;
432       dev->VolCatInfo.VolCatBlocks = 1;
433       if (recycle) {
434          dev->VolCatInfo.VolCatMounts++;  
435          dev->VolCatInfo.VolCatRecycles++;
436       } else {
437          dev->VolCatInfo.VolCatMounts = 1;
438          dev->VolCatInfo.VolCatRecycles = 0;
439          dev->VolCatInfo.VolCatWrites = 1;
440          dev->VolCatInfo.VolCatReads = 1;
441       }
442       strcpy(dev->VolCatInfo.VolCatStatus, "Append");
443       dir_update_volume_info(jcr, &dev->VolCatInfo, 1);  /* indicate doing relabel */
444       if (recycle) {
445          Jmsg(jcr, M_INFO, 0, _("Recycled volume %s on device %s, all previous data lost.\n"),
446             jcr->VolumeName, dev_name(dev));
447       } else {
448          Jmsg(jcr, M_INFO, 0, _("Wrote label to prelabeled Volume %s on device %s\n"),
449             jcr->VolumeName, dev_name(dev));
450       }
451
452    } else {
453       /* OK, at this point, we have a valid Bacula label, but
454        * we need to position to the end of the volume.
455        */
456       Dmsg0(20, "Device previously written, moving to end of data\n");
457       Jmsg(jcr, M_INFO, 0, _("Volume %s previously written, moving to end of data.\n"),
458          jcr->VolumeName);
459       if (!eod_dev(dev)) {
460          Jmsg(jcr, M_ERROR, 0, _("Unable to position to end of data %s. ERR=%s\n"),
461             dev_name(dev), strerror_dev(dev));
462          Jmsg(jcr, M_INFO, 0, _("Marking Volume %s in Error in Catalog.\n"),
463             jcr->VolumeName);
464          strcpy(dev->VolCatInfo.VolCatStatus, "Error");
465          dir_update_volume_info(jcr, &dev->VolCatInfo, 0);
466          return 0;
467       }
468       /* *****FIXME**** we might do some checking for files too */
469       if (dev_is_tape(dev)) {
470          Jmsg(jcr, M_INFO, 0, _("Ready to append to end of Volume at file=%d.\n"), dev_file(dev));
471          if (dev->VolCatInfo.VolCatFiles != dev_file(dev) + 1) {
472             /* ****FIXME**** this should refuse to write on tape */
473             Jmsg(jcr, M_INFO, 0, _("Hey! Num files mismatch! Catalog Files=%d\n"), dev->VolCatInfo.VolCatFiles);
474          }
475       }
476       /* Return an empty block */
477       empty_block(block);             /* we used it for reading so set for write */
478    }
479    dev->state |= ST_APPEND;
480    Dmsg0(100, "Normal return from read_dev_for_append\n");
481    return 1; 
482 }
483
484 /*
485  * This routine ensures that the device is ready for
486  * reading. If it is a file, it opens it.
487  * If it is a tape, it checks the volume name 
488  *
489  *  Returns 0 on failure
490  *  Returns 1 on success
491  */
492 int ready_dev_for_read(JCR *jcr, DEVICE *dev, DEV_BLOCK *block)
493 {
494    if (!(dev->state & ST_OPENED)) {
495        Dmsg1(20, "bstored: open vol=%s\n", jcr->VolumeName);
496        if (open_dev(dev, jcr->VolumeName, READ_ONLY) < 0) {
497           Jmsg(jcr, M_FATAL, 0, _("Open device %s volume %s failed, ERR=%s\n"), 
498               dev_name(dev), jcr->VolumeName, strerror_dev(dev));
499           return 0;
500        }
501        Dmsg1(29, "open_dev %s OK\n", dev_name(dev));
502    }
503
504    for (;;) {
505       if (job_cancelled(jcr)) {
506          Mmsg0(&dev->errmsg, _("Job cancelled.\n"));
507          return 0;
508       }
509       if (!rewind_dev(dev)) {
510          Jmsg2(jcr, M_WARNING, 0, _("Rewind error on device %s. ERR=%s\n"), 
511                dev_name(dev), strerror_dev(dev));
512       }
513       switch (read_dev_volume_label(jcr, dev, block)) {
514          case VOL_OK:
515             break;                    /* got it */
516          default:
517             /* Send error message generated by read_dev_volume_label() */
518             Jmsg(jcr, M_WARNING, 0, "%s", jcr->errmsg);                         
519             if (!rewind_dev(dev)) {
520                Jmsg2(jcr, M_WARNING, 0, _("Rewind error on device %s. ERR=%s\n"), 
521                      dev_name(dev), strerror_dev(dev));
522             }
523             if (!dir_ask_sysop_to_mount_volume(jcr, dev)) {
524                return 0;              /* error return */
525             }
526             continue;                 /* try reading again */
527       }
528       break;
529    }
530
531    dev->state |= ST_READ;
532    return 1; 
533 }
534
535 /*
536  * This is the dreaded moment. We either have an end of
537  * medium condition or worse, and error condition.
538  * Attempt to "recover" by obtaining a new Volume.
539  *
540  * We enter with device locked, and 
541  *     exit with device locked.
542  *
543  * Note, we are called only from one place in block.c
544  *
545  *  Returns: 1 on success
546  *           0 on failure
547  */
548 int fixup_device_block_write_error(JCR *jcr, DEVICE *dev, DEV_BLOCK *block)
549 {
550    uint32_t stat = 0;                   
551    char PrevVolName[MAX_NAME_LENGTH];
552    DEV_BLOCK *label_blk;
553    char b1[30], b2[30];
554    time_t wait_time;
555
556    wait_time = time(NULL);
557    status_dev(dev, &stat);
558    if (stat & MT_EOD) {
559       Dmsg0(90, "======= Got EOD ========\n");
560
561       block_device(dev, BST_DOING_ACQUIRE);
562
563       strcpy(dev->VolCatInfo.VolCatStatus, "Full");
564       Dmsg0(90, "Call update_vol_info\n");
565       if (!dir_update_volume_info(jcr, &dev->VolCatInfo, 0)) {    /* send Volume info to Director */
566          Jmsg(jcr, M_ERROR, 0, _("Could not update Volume info Volume=%s Job=%s\n"),
567             dev->VolCatInfo.VolCatName, jcr->Job);
568          return 0;                    /* device locked */
569       }
570       Dmsg0(90, "Back from update_vol_info\n");
571
572       strcpy(PrevVolName, dev->VolCatInfo.VolCatName);
573       strcpy(dev->VolHdr.PrevVolName, PrevVolName);
574
575       label_blk = new_block(dev);
576
577       /* Inform User about end of media */
578       Jmsg(jcr, M_INFO, 0, _("End of media on Volume %s Bytes=%s Blocks=%s.\n"), 
579            PrevVolName, edit_uint64_with_commas(dev->VolCatInfo.VolCatBytes, b1),
580            edit_uint64_with_commas(dev->VolCatInfo.VolCatBlocks, b2));
581
582       if (!dev_is_tape(dev)) {           /* If file, */
583          close_dev(dev);                 /* yes, close it */
584       }
585
586       /* Unlock, but leave BLOCKED */
587       unlock_device(dev);
588       if (!mount_next_volume(jcr, dev, label_blk)) {
589          P(dev->mutex);
590          unblock_device(dev);
591          return 0;                    /* device locked */
592       }
593
594       P(dev->mutex);                  /* lock again */
595
596       Jmsg(jcr, M_INFO, 0, _("New volume %s mounted on device %s\n"),
597          jcr->VolumeName, dev_name(dev));
598
599       /* 
600        * If this is a new tape, the label_blk will contain the
601        *  label, so write it now. If this is a previously
602        *  used tape, mount_next_volume() will return an
603        *  empty label_blk, and nothing will be written.
604        */
605       Dmsg0(90, "write label block to dev\n");
606       if (!write_block_to_dev(dev, label_blk)) {
607          Dmsg1(0, "write_block_to_device Volume label failed. ERR=%s",
608            strerror_dev(dev));
609          free_block(label_blk);
610          unblock_device(dev);
611          return 0;                    /* device locked */
612       }
613
614       /* Write overflow block to tape */
615       Dmsg0(90, "Write overflow block to dev\n");
616       if (!write_block_to_dev(dev, block)) {
617          Dmsg1(0, "write_block_to_device overflow block failed. ERR=%s",
618            strerror_dev(dev));
619          free_block(label_blk);
620          unblock_device(dev);
621          return 0;                    /* device locked */
622       }
623
624       jcr->NumVolumes++;
625       Dmsg0(90, "Wake up any waiting threads.\n");
626       free_block(label_blk);
627       unblock_device(dev);
628       jcr->run_time += time(NULL) - wait_time; /* correct run time */
629       return 1;                                /* device locked */
630    }
631    free_block(label_blk);
632    return 0;                          /* device locked */
633 }
634
635
636 /*
637  *   Open the device. Expect dev to already be initialized.  
638  *
639  *   This routine is used only when the Storage daemon starts 
640  *   and always_open is set, and in the stand-alone utility
641  *   routines such as bextract.
642  *
643  *   Note, opening of a normal file is deferred to later so
644  *    that we can get the filename; the device_name for
645  *    a file is the directory only. 
646  *
647  *   Retuns: 0 on failure
648  *           1 on success
649  */
650 int open_device(DEVICE *dev)
651 {
652    Dmsg0(20, "start open_output_device()\n");
653    if (!dev) {
654       return 0;
655    }
656
657    lock_device(dev);
658
659    /* Defer opening files */
660    if (!dev_is_tape(dev)) {
661       Dmsg0(29, "Device is file, deferring open.\n");
662       unlock_device(dev);
663       return 1;
664    }
665
666    if (!(dev->state & ST_OPENED)) {
667       Dmsg0(29, "Opening device.\n");
668       if (open_dev(dev, NULL, READ_WRITE) < 0) {
669          Emsg1(M_FATAL, 0, _("dev open failed: %s\n"), dev->errmsg);
670          unlock_device(dev);
671          return 0;
672       }
673    }
674    Dmsg1(29, "open_dev %s OK\n", dev_name(dev));
675
676    unlock_device(dev);
677    return 1;
678 }
679
680
681 /* 
682  * When dev_blocked is set, all threads EXCEPT thread with id no_wait_id
683  * must wait. The no_wait_id thread is out obtaining a new volume
684  * and preparing the label.
685  */
686 void lock_device(DEVICE *dev)
687 {
688    int stat;
689
690    Dmsg1(90, "lock %d\n", dev->dev_blocked);
691    P(dev->mutex);
692    if (dev->dev_blocked && !pthread_equal(dev->no_wait_id, pthread_self())) {
693       dev->num_waiting++;             /* indicate that I am waiting */
694       while (dev->dev_blocked) {
695          if ((stat = pthread_cond_wait(&dev->wait, &dev->mutex)) != 0) {
696             V(dev->mutex);
697             Emsg1(M_ABORT, 0, _("pthread_cond_wait failure. ERR=%s\n"),
698                strerror(stat));
699          }
700       }
701       dev->num_waiting--;             /* no longer waiting */
702    }
703 }
704
705 void unlock_device(DEVICE *dev) 
706 {
707    Dmsg0(90, "unlock\n");
708    V(dev->mutex);
709 }
710
711 /* 
712  * Block all other threads from using the device
713  *  Device must already be locked.  After this call,
714  *  the device is blocked to any thread calling lock_device(),
715  *  but the device is not locked (i.e. no P on device).  Also,
716  *  the current thread can do slip through the lock_device()
717  *  calls without blocking.
718  */
719 void block_device(DEVICE *dev, int state)
720 {
721    Dmsg1(90, "block set %d\n", state);
722    ASSERT(dev->dev_blocked == BST_NOT_BLOCKED);
723    dev->dev_blocked = state;          /* make other threads wait */
724    dev->no_wait_id = pthread_self();  /* allow us to continue */
725 }
726
727 /*
728  * Unblock the device, and wake up anyone who went to sleep.
729  */
730 void unblock_device(DEVICE *dev)
731 {
732    Dmsg1(90, "unblock %d\n", dev->dev_blocked);
733    ASSERT(dev->dev_blocked);
734    dev->dev_blocked = BST_NOT_BLOCKED;
735    if (dev->num_waiting > 0) {
736       pthread_cond_broadcast(&dev->wait); /* wake them up */
737    }
738 }