]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/stored/device.c
Add auto-changer support -- kes17Jul02
[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 mount_next_volume(JCR *jcr, DEVICE *dev, DEV_BLOCK *label_blk, int release);
56 static char *edit_device_codes(JCR *jcr, char *omsg, char *imsg, char *cmd);
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    int release = 0;
100    int do_mount = 0;
101
102    lock_device(dev);
103    Dmsg1(90, "acquire_append device is %s\n", dev_is_tape(dev)?"tape":"disk");
104
105
106    if (dev->state & ST_APPEND) {
107       /* 
108        * Device already in append mode   
109        *
110        * Check if we have the right Volume mounted   
111        *  OK if AnonVols and volume info OK
112        *  OK if next volume matches current volume
113        *  otherwise mount desired volume obtained from
114        *    dir_find_next_appendable_volume
115        */
116       strcpy(jcr->VolumeName, dev->VolHdr.VolName);
117       if (((dev->capabilities & CAP_ANONVOLS) &&
118             !dir_get_volume_info(jcr)) ||
119           (!dir_find_next_appendable_volume(jcr) || 
120             strcmp(dev->VolHdr.VolName, jcr->VolumeName) != 0)) { /* wrong tape mounted */
121          if (dev->num_writers != 0) {
122             Jmsg(jcr, M_FATAL, 0, _("Device %s is busy writing with another Volume.\n"), dev_name(dev));
123             unlock_device(dev);
124             return 0;
125          }
126          /* Wrong tape mounted, release it, then fall through to get correct one */
127          release = 1;
128          do_mount = 1;
129       }
130    } else { 
131       /* Not already in append mode, so mount the device */
132       if (dev->state & ST_READ) {
133          Jmsg(jcr, M_FATAL, 0, _("Device %s is busy reading.\n"), dev_name(dev));
134          unlock_device(dev);
135          return 0;
136       } 
137       ASSERT(dev->num_writers == 0);
138       do_mount = 1;
139    }
140
141    if (do_mount) {
142       block_device(dev, BST_DOING_ACQUIRE);
143       unlock_device(dev);
144       if (!mount_next_volume(jcr, dev, block, release)) {
145          Jmsg(jcr, M_FATAL, 0, _("Could not ready device %s for append.\n"),
146             dev_name(dev));
147          P(dev->mutex);
148          unblock_device(dev);
149          unlock_device(dev);
150          return 0;
151       }
152       P(dev->mutex);
153       unblock_device(dev);
154    }
155
156    dev->num_writers++;
157    if (dev->num_writers > 1) {
158       Dmsg2(0, "Hey!!!! There are %d writers on device %s\n", dev->num_writers,
159          dev_name(dev));
160    }
161    if (jcr->NumVolumes == 0) {
162       jcr->NumVolumes = 1;
163    }
164    unlock_device(dev);
165    return 1;                          /* got it */
166 }
167
168 /*
169  * This job is done, so release the device. From a Unix standpoint,
170  *  the device remains open.
171  *
172  */
173 int release_device(JCR *jcr, DEVICE *dev, DEV_BLOCK *block)
174 {
175    P(dev->mutex);
176    Dmsg1(90, "release_device device is %s\n", dev_is_tape(dev)?"tape":"disk");
177    if (dev->state & ST_READ) {
178       dev->state &= ~ST_READ;         /* clear read bit */
179       if (!dev_is_tape(dev)) {
180          close_dev(dev);
181       }
182       /******FIXME**** send read volume usage statistics to director */
183
184    } else if (dev->num_writers > 0) {
185       dev->num_writers--;
186       Dmsg1(90, "There are %d writers in release_device\n", dev->num_writers);
187       if (dev->num_writers == 0) {
188          weof_dev(dev, 1);
189          dir_create_job_media_record(jcr);
190          dev->VolCatInfo.VolCatFiles++;             /* increment number of files */
191          /* Note! do volume update before close, which zaps VolCatInfo */
192          dir_update_volume_info(jcr, &dev->VolCatInfo, 0); /* send Volume info to Director */
193          if (!dev_is_tape(dev)) {
194             close_dev(dev);
195          } else {
196             Dmsg0(90, "Device is tape leave open in release_device\n");
197          }
198       } else {
199          dir_create_job_media_record(jcr);
200          dir_update_volume_info(jcr, &dev->VolCatInfo, 0); /* send Volume info to Director */
201       }
202    } else {
203       Jmsg1(jcr, M_ERROR, 0, _("BAD ERROR: release_device %s not in use.\n"), dev_name(dev));
204    }
205    V(dev->mutex);
206    return 1;
207 }
208
209
210
211 /*
212  * If release is set, we rewind the current volume, 
213  * which we no longer want, and ask the user (console) 
214  * to mount the next volume.
215  *
216  *  Continue trying until we get it, and then ensure
217  *  that we can write on it.
218  *
219  * This routine returns a 0 only if it is REALLY
220  *  impossible to get the requested Volume.
221  */
222 static int mount_next_volume(JCR *jcr, DEVICE *dev, DEV_BLOCK *block, int release)
223 {
224    int recycle, ask, retry = 0;
225
226    Dmsg0(90, "Enter mount_next_volume()\n");
227
228 mount_next_vol:
229    if (retry++ > 5) {
230       Mmsg0(&dev->errmsg, _("Too many retries.\n"));
231       return 0;
232    }
233    if (job_cancelled(jcr)) {
234       Mmsg0(&dev->errmsg, _("Job cancelled.\n"));
235       return 0;
236    }
237    recycle = 0;
238    ask = 0;
239    if (release) {
240       Dmsg0(500, "mount_next_volume release=1\n");
241       /* 
242        * First erase all memory of the current volume   
243        */
244       dev->block_num = 0;
245       dev->file = 0;
246       dev->LastBlockNumWritten = 0;
247       memset(&dev->VolCatInfo, 0, sizeof(dev->VolCatInfo));
248       memset(&dev->VolHdr, 0, sizeof(dev->VolHdr));
249       dev->state &= ~ST_LABEL;        /* label not yet read */
250
251       /* Rewind device */                                    
252       if (dev->state & ST_OPENED) {
253          if (!rewind_dev(dev)) {
254             Jmsg2(jcr, M_WARNING, 0, _("Rewind error on device %s. ERR=%s\n"), 
255                   dev_name(dev), strerror_dev(dev));
256          }
257       }
258       ask = 1;                        /* ask operator to mount tape */
259    } else {
260       /* 
261        * Get Director's idea of what tape we should have mounted. 
262        */
263       if (!dir_find_next_appendable_volume(jcr)) {
264          ask = 1;                     /* we must ask */
265       }
266    }
267    release = 1;                       /* release if we "recurse" */
268
269    /* 
270     * Get next volume and ready it for append
271     * This code ensures that the device is ready for
272     * writing. We start from the assumption that there
273     * may not be a tape mounted. 
274     *
275     * If the device is a file, we create the output
276     * file. If it is a tape, we check the volume name
277     * and move the tape to the end of data.
278     *
279     * It assumes that the device is not already in use!
280     *
281     */
282
283    Dmsg0(100, "Enter ready_dev_for_append\n");
284
285    dev->state &= ~(ST_APPEND|ST_READ|ST_EOT|ST_WEOT|ST_EOF);
286
287    jcr->VolFirstFile = 0;             /* first update of Vol FileIndex */
288    for ( ;; ) {
289       int slot = jcr->VolCatInfo.Slot;
290         
291       /*
292        * Handle autoloaders here.  If we cannot autoload it, we
293        *  will fall through to ask the sysop.
294        */
295       if (dev->capabilities && CAP_AUTOCHANGER && slot <= 0) {
296          if (dir_find_next_appendable_volume(jcr)) {
297             slot = jcr->VolCatInfo.Slot; 
298          }
299       }
300       Dmsg1(100, "Want changer slot=%d\n", slot);
301
302       if (slot > 0 && jcr->device->changer_name && jcr->device->changer_command) {
303          uint32_t timeout = jcr->device->changer_timeout;
304          POOLMEM *changer, *results;
305          int status, loaded;
306
307          results = get_pool_memory(PM_MESSAGE);
308          changer = get_pool_memory(PM_FNAME);
309          /* Find out what is loaded */
310          changer = edit_device_codes(jcr, changer, jcr->device->changer_command, 
311                       "loaded");
312          status = run_program(changer, timeout, results);
313          if (status == 0) {
314             loaded = atoi(results);
315          } else {
316             loaded = -1;              /* force unload */
317          }
318          Dmsg1(100, "loaded=%s\n", results);
319
320          /* If bad status or tape we want is not loaded, load it. */
321          if (status != 0 || loaded != slot) { 
322             if (dev->capabilities & CAP_OFFLINEUNMOUNT) {
323                offline_dev(dev);
324             }
325             /* We are going to load a new tape, so close the device */
326             force_close_dev(dev);
327             if (loaded != 0) {        /* must unload drive */
328                Dmsg0(100, "Doing changer unload.\n");
329                changer = edit_device_codes(jcr, changer, 
330                            jcr->device->changer_command, "unload");
331                status = run_program(changer, timeout, NULL);
332                Dmsg1(100, "unload status=%d\n", status);
333             }
334             /*
335              * Load the desired cassette    
336              */
337             Dmsg1(100, "Doing changer load slot %d\n", slot);
338             changer = edit_device_codes(jcr, changer, 
339                          jcr->device->changer_command, "load");
340             status = run_program(changer, timeout, NULL);
341             Dmsg2(100, "load slot %d status=%d\n", slot, status);
342          }
343          free_pool_memory(changer);
344          free_pool_memory(results);
345          Dmsg1(100, "After changer, status=%d\n", status);
346          if (status == 0) {           /* did we succeed? */
347             ask = 0;                  /* yes, got vol, no need to ask sysop */
348          }
349       }
350
351
352       if (ask && !dir_ask_sysop_to_mount_next_volume(jcr, dev)) {
353          return 0;              /* error return */
354       }
355       Dmsg1(200, "want vol=%s\n", jcr->VolumeName);
356
357       /* Open device */
358       for ( ; !(dev->state & ST_OPENED); ) {
359           if (open_dev(dev, jcr->VolCatInfo.VolCatName, READ_WRITE) < 0) {
360              if (dev->dev_errno == EAGAIN || dev->dev_errno == EBUSY) {
361                 sleep(30);
362              }
363              Jmsg2(jcr, M_FATAL, 0, _("Unable to open device %s. ERR=%s\n"), 
364                 dev_name(dev), strerror_dev(dev));
365              return 0;
366           }
367       }
368
369       /*
370        * Now make sure we have the right tape mounted
371        */
372 read_volume:
373       switch (read_dev_volume_label(jcr, dev, block)) {
374          case VOL_OK:
375             Dmsg1(500, "Vol OK name=%s\n", jcr->VolumeName);
376             memcpy(&dev->VolCatInfo, &jcr->VolCatInfo, sizeof(jcr->VolCatInfo));
377             if (strcmp(dev->VolCatInfo.VolCatStatus, "Recycle") == 0) {
378                recycle = 1;
379             }
380             break;                    /* got it */
381          case VOL_NAME_ERROR:
382             Dmsg1(500, "Vol NAME Error Name=%s\n", jcr->VolumeName);
383             /* Check if we can accept this as an anonymous volume */
384             strcpy(jcr->VolumeName, dev->VolHdr.VolName);
385             if (!dev->capabilities & CAP_ANONVOLS || !dir_get_volume_info(jcr)) {
386                goto mount_next_vol;
387             }
388             Dmsg1(200, "want new name=%s\n", jcr->VolumeName);
389             memcpy(&dev->VolCatInfo, &jcr->VolCatInfo, sizeof(jcr->VolCatInfo));
390             break;
391
392          case VOL_NO_LABEL:
393          case VOL_IO_ERROR:
394             Dmsg1(500, "Vol NO_LABEL or IO_ERROR name=%s\n", jcr->VolumeName);
395             /* If permitted, create a label */
396             if (dev->capabilities & CAP_LABEL) {
397                Dmsg0(90, "Create volume label\n");
398                if (!write_volume_label_to_dev(jcr, (DEVRES *)dev->device, jcr->VolumeName,
399                       jcr->pool_name)) {
400                   goto mount_next_vol;
401                }
402                Jmsg(jcr, M_INFO, 0, _("Created Volume label %s on device %s.\n"),
403                   jcr->VolumeName, dev_name(dev));
404                goto read_volume;      /* read label we just wrote */
405             } 
406             /* NOTE! Fall-through wanted. */
407          default:
408             /* Send error message */
409             Jmsg(jcr, M_WARNING, 0, "%s", jcr->errmsg);                         
410             goto mount_next_vol;
411       }
412       break;
413    }
414
415    /* 
416     * See if we have a fresh tape or tape with data.
417     *
418     * Note, if the LabelType is PRE_LABEL, it was labeled
419     *  but never written. If so, rewrite the label but set as
420     *  VOL_LABEL.  We rewind and return the label (reconstructed)
421     *  in the block so that in the case of a new tape, data can
422     *  be appended just after the block label.  If we are writing
423     *  an second volume, the calling routine will write the label
424     *  before writing the overflow block.
425     *
426     *  If the tape is marked as Recycle, we rewrite the label.
427     */
428    if (dev->VolHdr.LabelType == PRE_LABEL || recycle) {
429       Dmsg1(90, "ready_for_append found freshly labeled volume. dev=%x\n", dev);
430       dev->VolHdr.LabelType = VOL_LABEL; /* set Volume label */
431       write_volume_label_to_block(jcr, dev, block);
432       /*
433        * Write the block now to ensure we have write permission.
434        *  It is better to find out now rather than later.
435        */
436       dev->VolCatInfo.VolCatBytes = 0;
437       if (!rewind_dev(dev)) {
438          Jmsg2(jcr, M_WARNING, 0, _("Rewind error on device %s. ERR=%s\n"), 
439                dev_name(dev), strerror_dev(dev));
440       }
441       if (recycle) {
442          if (!truncate_dev(dev)) {
443             Jmsg2(jcr, M_WARNING, 0, _("Truncate error on device %s. ERR=%s\n"), 
444                   dev_name(dev), strerror_dev(dev));
445          }
446       }
447       if (!write_block_to_dev(dev, block)) {
448          Jmsg2(jcr, M_ERROR, 0, _("Unable to write device %s. ERR=%s\n"),
449             dev_name(dev), strerror_dev(dev));
450          goto mount_next_vol;
451       }
452       if (!rewind_dev(dev)) {
453          Jmsg2(jcr, M_ERROR, 0, _("Unable to rewind device %s. ERR=%s\n"),
454             dev_name(dev), strerror_dev(dev));
455          goto mount_next_vol;
456       }
457       /* Recreate a correct volume label and return it in the block */
458       write_volume_label_to_block(jcr, dev, block);
459       dev->VolCatInfo.VolCatJobs = 1;
460       dev->VolCatInfo.VolCatFiles = 1;
461       dev->VolCatInfo.VolCatErrors = 0;
462       dev->VolCatInfo.VolCatBlocks = 1;
463       if (recycle) {
464          dev->VolCatInfo.VolCatMounts++;  
465          dev->VolCatInfo.VolCatRecycles++;
466       } else {
467          dev->VolCatInfo.VolCatMounts = 1;
468          dev->VolCatInfo.VolCatRecycles = 0;
469          dev->VolCatInfo.VolCatWrites = 1;
470          dev->VolCatInfo.VolCatReads = 1;
471       }
472       strcpy(dev->VolCatInfo.VolCatStatus, "Append");
473       dir_update_volume_info(jcr, &dev->VolCatInfo, 1);  /* indicate doing relabel */
474       if (recycle) {
475          Jmsg(jcr, M_INFO, 0, _("Recycled volume %s on device %s, all previous data lost.\n"),
476             jcr->VolumeName, dev_name(dev));
477       } else {
478          Jmsg(jcr, M_INFO, 0, _("Wrote label to prelabeled Volume %s on device %s\n"),
479             jcr->VolumeName, dev_name(dev));
480       }
481
482    } else {
483       /*
484        * OK, at this point, we have a valid Bacula label, but
485        * we need to position to the end of the volume, since we are
486        * just now putting it into append mode.
487        */
488       Dmsg0(20, "Device previously written, moving to end of data\n");
489       Jmsg(jcr, M_INFO, 0, _("Volume %s previously written, moving to end of data.\n"),
490          jcr->VolumeName);
491       if (!eod_dev(dev)) {
492          Jmsg(jcr, M_ERROR, 0, _("Unable to position to end of data %s. ERR=%s\n"),
493             dev_name(dev), strerror_dev(dev));
494          Jmsg(jcr, M_INFO, 0, _("Marking Volume %s in Error in Catalog.\n"),
495             jcr->VolumeName);
496          strcpy(dev->VolCatInfo.VolCatStatus, "Error");
497          dir_update_volume_info(jcr, &dev->VolCatInfo, 0);
498          goto mount_next_vol;
499       }
500       /* *****FIXME**** we should do some checking for files too */
501       if (dev_is_tape(dev)) {
502          Jmsg(jcr, M_INFO, 0, _("Ready to append to end of Volume at file=%d.\n"), dev_file(dev));
503          /*
504           * Check if we are positioned on the tape at the same place
505           * that the database says we should be.
506           */
507          if (dev->VolCatInfo.VolCatFiles != dev_file(dev) + 1) {
508             /* ****FIXME**** this should refuse to write on tape */
509             Jmsg(jcr, M_ERROR, 0, _("Hey! Num files mismatch! Volume=%d Catalog=%d\n"), 
510                dev_file(dev)+1, dev->VolCatInfo.VolCatFiles);
511          }
512       }
513       /* Update Volume Info -- will be written at end of Job */
514       dev->VolCatInfo.VolCatMounts++;      /* Update mounts */
515       dev->VolCatInfo.VolCatJobs++;
516       /* Return an empty block */
517       empty_block(block);             /* we used it for reading so set for write */
518    }
519    dev->state |= ST_APPEND;
520    Dmsg0(100, "Normal return from read_dev_for_append\n");
521    return 1; 
522 }
523
524 /*
525  * This routine ensures that the device is ready for
526  * reading. If it is a file, it opens it.
527  * If it is a tape, it checks the volume name 
528  *
529  *  Returns 0 on failure
530  *  Returns 1 on success
531  */
532 int ready_dev_for_read(JCR *jcr, DEVICE *dev, DEV_BLOCK *block)
533 {
534    if (!(dev->state & ST_OPENED)) {
535        Dmsg1(20, "bstored: open vol=%s\n", jcr->VolumeName);
536        if (open_dev(dev, jcr->VolumeName, READ_ONLY) < 0) {
537           Jmsg(jcr, M_FATAL, 0, _("Open device %s volume %s failed, ERR=%s\n"), 
538               dev_name(dev), jcr->VolumeName, strerror_dev(dev));
539           return 0;
540        }
541        Dmsg1(29, "open_dev %s OK\n", dev_name(dev));
542    }
543
544    for (;;) {
545       if (job_cancelled(jcr)) {
546          Mmsg0(&dev->errmsg, _("Job cancelled.\n"));
547          return 0;
548       }
549       if (!rewind_dev(dev)) {
550          Jmsg2(jcr, M_WARNING, 0, _("Rewind error on device %s. ERR=%s\n"), 
551                dev_name(dev), strerror_dev(dev));
552       }
553       switch (read_dev_volume_label(jcr, dev, block)) {
554          case VOL_OK:
555             break;                    /* got it */
556          default:
557             /* Send error message generated by read_dev_volume_label() */
558             Jmsg(jcr, M_WARNING, 0, "%s", jcr->errmsg);                         
559             if (!rewind_dev(dev)) {
560                Jmsg2(jcr, M_WARNING, 0, _("Rewind error on device %s. ERR=%s\n"), 
561                      dev_name(dev), strerror_dev(dev));
562             }
563             /* Mount a specific volume and no other */
564             if (!dir_ask_sysop_to_mount_volume(jcr, dev)) {
565                return 0;              /* error return */
566             }
567             continue;                 /* try reading again */
568       }
569       break;
570    }
571
572    dev->state |= ST_READ;
573    return 1; 
574 }
575
576 /*
577  * This is the dreaded moment. We either have an end of
578  * medium condition or worse, and error condition.
579  * Attempt to "recover" by obtaining a new Volume.
580  *
581  * We enter with device locked, and 
582  *     exit with device locked.
583  *
584  * Note, we are called only from one place in block.c
585  *
586  *  Returns: 1 on success
587  *           0 on failure
588  */
589 int fixup_device_block_write_error(JCR *jcr, DEVICE *dev, DEV_BLOCK *block)
590 {
591    uint32_t stat = 0;                   
592    char PrevVolName[MAX_NAME_LENGTH];
593    DEV_BLOCK *label_blk;
594    char b1[30], b2[30];
595    time_t wait_time;
596
597    wait_time = time(NULL);
598    status_dev(dev, &stat);
599    if (stat & MT_EOD) {
600       Dmsg0(90, "======= Got EOD ========\n");
601
602       block_device(dev, BST_DOING_ACQUIRE);
603
604       strcpy(dev->VolCatInfo.VolCatStatus, "Full");
605       Dmsg0(90, "Call update_vol_info\n");
606       /* Update position counters */
607       jcr->end_block = dev->block_num;
608       jcr->end_file = dev->file;
609       /*
610        * ****FIXME**** update JobMedia record of every job using
611        * this device 
612        */
613       if (!dir_create_job_media_record(jcr) ||
614           !dir_update_volume_info(jcr, &dev->VolCatInfo, 0)) {    /* send Volume info to Director */
615          Jmsg(jcr, M_ERROR, 0, _("Could not update Volume info Volume=%s Job=%s\n"),
616             dev->VolCatInfo.VolCatName, jcr->Job);
617          return 0;                    /* device locked */
618       }
619       Dmsg0(90, "Back from update_vol_info\n");
620
621       strcpy(PrevVolName, dev->VolCatInfo.VolCatName);
622       strcpy(dev->VolHdr.PrevVolName, PrevVolName);
623
624       label_blk = new_block(dev);
625
626       /* Inform User about end of media */
627       Jmsg(jcr, M_INFO, 0, _("End of media on Volume %s Bytes=%s Blocks=%s.\n"), 
628            PrevVolName, edit_uint64_with_commas(dev->VolCatInfo.VolCatBytes, b1),
629            edit_uint64_with_commas(dev->VolCatInfo.VolCatBlocks, b2));
630
631       if (!dev_is_tape(dev)) {           /* If file, */
632          close_dev(dev);                 /* yes, close it */
633       }
634
635       /* Unlock, but leave BLOCKED */
636       unlock_device(dev);
637       if (!mount_next_volume(jcr, dev, label_blk, 1)) {
638          P(dev->mutex);
639          unblock_device(dev);
640          return 0;                    /* device locked */
641       }
642
643       P(dev->mutex);                  /* lock again */
644
645       Jmsg(jcr, M_INFO, 0, _("New volume %s mounted on device %s\n"),
646          jcr->VolumeName, dev_name(dev));
647
648       /* 
649        * If this is a new tape, the label_blk will contain the
650        *  label, so write it now. If this is a previously
651        *  used tape, mount_next_volume() will return an
652        *  empty label_blk, and nothing will be written.
653        */
654       Dmsg0(90, "write label block to dev\n");
655       if (!write_block_to_dev(dev, label_blk)) {
656          Dmsg1(0, "write_block_to_device Volume label failed. ERR=%s",
657            strerror_dev(dev));
658          free_block(label_blk);
659          unblock_device(dev);
660          return 0;                    /* device locked */
661       }
662
663       /* Write overflow block to tape */
664       Dmsg0(90, "Write overflow block to dev\n");
665       if (!write_block_to_dev(dev, block)) {
666          Dmsg1(0, "write_block_to_device overflow block failed. ERR=%s",
667            strerror_dev(dev));
668          free_block(label_blk);
669          unblock_device(dev);
670          return 0;                    /* device locked */
671       }
672
673       jcr->NumVolumes++;
674       Dmsg0(90, "Wake up any waiting threads.\n");
675       free_block(label_blk);
676       /* Set new start/end positions */
677       jcr->start_block = dev->block_num;
678       jcr->start_file = dev->file;
679       unblock_device(dev);
680       jcr->run_time += time(NULL) - wait_time; /* correct run time */
681       return 1;                                /* device locked */
682    }
683    free_block(label_blk);
684    return 0;                          /* device locked */
685 }
686
687
688 /*
689  *   Open the device. Expect dev to already be initialized.  
690  *
691  *   This routine is used only when the Storage daemon starts 
692  *   and always_open is set, and in the stand-alone utility
693  *   routines such as bextract.
694  *
695  *   Note, opening of a normal file is deferred to later so
696  *    that we can get the filename; the device_name for
697  *    a file is the directory only. 
698  *
699  *   Retuns: 0 on failure
700  *           1 on success
701  */
702 int open_device(DEVICE *dev)
703 {
704    Dmsg0(20, "start open_output_device()\n");
705    if (!dev) {
706       return 0;
707    }
708
709    lock_device(dev);
710
711    /* Defer opening files */
712    if (!dev_is_tape(dev)) {
713       Dmsg0(29, "Device is file, deferring open.\n");
714       unlock_device(dev);
715       return 1;
716    }
717
718    if (!(dev->state & ST_OPENED)) {
719       Dmsg0(29, "Opening device.\n");
720       if (open_dev(dev, NULL, READ_WRITE) < 0) {
721          Emsg1(M_FATAL, 0, _("dev open failed: %s\n"), dev->errmsg);
722          unlock_device(dev);
723          return 0;
724       }
725    }
726    Dmsg1(29, "open_dev %s OK\n", dev_name(dev));
727
728    unlock_device(dev);
729    return 1;
730 }
731
732
733 /* 
734  * When dev_blocked is set, all threads EXCEPT thread with id no_wait_id
735  * must wait. The no_wait_id thread is out obtaining a new volume
736  * and preparing the label.
737  */
738 void lock_device(DEVICE *dev)
739 {
740    int stat;
741
742    Dmsg1(90, "lock %d\n", dev->dev_blocked);
743    P(dev->mutex);
744    if (dev->dev_blocked && !pthread_equal(dev->no_wait_id, pthread_self())) {
745       dev->num_waiting++;             /* indicate that I am waiting */
746       while (dev->dev_blocked) {
747          if ((stat = pthread_cond_wait(&dev->wait, &dev->mutex)) != 0) {
748             V(dev->mutex);
749             Emsg1(M_ABORT, 0, _("pthread_cond_wait failure. ERR=%s\n"),
750                strerror(stat));
751          }
752       }
753       dev->num_waiting--;             /* no longer waiting */
754    }
755 }
756
757 void unlock_device(DEVICE *dev) 
758 {
759    Dmsg0(90, "unlock\n");
760    V(dev->mutex);
761 }
762
763 /* 
764  * Block all other threads from using the device
765  *  Device must already be locked.  After this call,
766  *  the device is blocked to any thread calling lock_device(),
767  *  but the device is not locked (i.e. no P on device).  Also,
768  *  the current thread can do slip through the lock_device()
769  *  calls without blocking.
770  */
771 void block_device(DEVICE *dev, int state)
772 {
773    Dmsg1(90, "block set %d\n", state);
774    ASSERT(dev->dev_blocked == BST_NOT_BLOCKED);
775    dev->dev_blocked = state;          /* make other threads wait */
776    dev->no_wait_id = pthread_self();  /* allow us to continue */
777 }
778
779 /*
780  * Unblock the device, and wake up anyone who went to sleep.
781  */
782 void unblock_device(DEVICE *dev)
783 {
784    Dmsg1(90, "unblock %d\n", dev->dev_blocked);
785    ASSERT(dev->dev_blocked);
786    dev->dev_blocked = BST_NOT_BLOCKED;
787    if (dev->num_waiting > 0) {
788       pthread_cond_broadcast(&dev->wait); /* wake them up */
789    }
790 }
791
792
793
794 /*
795  * Edit codes into ChangerCommand
796  *  %% = %
797  *  %a = archive device name
798  *  %c = changer device name
799  *  %f = Client's name
800  *  %j = Job name
801  *  %o = command
802  *  %s = Slot base 0
803  *  %S = Slot base 1
804  *  %v = Volume name
805  *
806  *
807  *  omsg = edited output message
808  *  imsg = input string containing edit codes (%x)
809  *  cmd = command string (load, unload, ...) 
810  *
811  */
812 static char *edit_device_codes(JCR *jcr, char *omsg, char *imsg, char *cmd) 
813 {
814    char *p, *o;
815    const char *str;
816    char add[20];
817
818    Dmsg1(200, "edit_job_codes: %s\n", imsg);
819    add[2] = 0;
820    o = omsg;
821    for (p=imsg; *p; p++) {
822       if (*p == '%') {
823          switch (*++p) {
824          case '%':
825             add[0] = '%';
826             add[1] = 0;
827             str = add;
828             break;
829          case 'a':
830             str = jcr->device->dev->dev_name;
831             break;
832          case 'c':
833             str = NPRT(jcr->device->changer_name);
834             break;
835          case 'o':
836             str = NPRT(cmd);
837             break;
838          case 's':
839             sprintf(add, "%d", jcr->VolCatInfo.Slot - 1);
840             str = add;
841             break;
842          case 'S':
843             sprintf(add, "%d", jcr->VolCatInfo.Slot);
844             str = add;
845             break;
846          case 'j':                    /* Job name */
847             str = jcr->Job;
848             break;
849          case 'v':
850             str = jcr->VolumeName;
851             if (!str) {
852                str = "";
853             }
854             break;
855          case 'f':
856             str = jcr->client_name;
857             if (!str) {
858                str = "";
859             }
860             break;
861
862          default:
863             add[0] = '%';
864             add[1] = *p;
865             str = add;
866             break;
867          }
868       } else {
869          add[0] = *p;
870          add[1] = 0;
871          str = add;
872       }
873       Dmsg1(200, "add_str %s\n", str);
874       add_str_to_pool_mem(&omsg, &o, (char *)str);
875       *o = 0;
876       Dmsg1(200, "omsg=%s\n", omsg);
877    }
878    *o = 0;
879    return omsg;
880 }