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