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