]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/stored/reserve.c
kes Generally clean up the manual tape loading code. The main
[bacula/bacula] / bacula / src / stored / reserve.c
1 /*
2    Bacula® - The Network Backup Solution
3
4    Copyright (C) 2000-2008 Free Software Foundation Europe e.V.
5
6    The main author of Bacula is Kern Sibbald, with contributions from
7    many others, a complete list can be found in the file AUTHORS.
8    This program is Free Software; you can redistribute it and/or
9    modify it under the terms of version two of the GNU General Public
10    License as published by the Free Software Foundation and included
11    in the file LICENSE.
12
13    This program is distributed in the hope that it will be useful, but
14    WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16    General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program; if not, write to the Free Software
20    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
21    02110-1301, USA.
22
23    Bacula® is a registered trademark of John Walker.
24    The licensor of Bacula is the Free Software Foundation Europe
25    (FSFE), Fiduciary Program, Sumatrastrasse 25, 8006 Zürich,
26    Switzerland, email:ftf@fsfeurope.org.
27 */
28 /*
29  *   Drive reservation functions for Storage Daemon
30  *
31  *   Kern Sibbald, MM
32  *
33  *   Split from job.c and acquire.c June 2005
34  *
35  *   Version $Id$
36  *
37  */
38
39 #include "bacula.h"
40 #include "stored.h"
41
42 #define jid() ((int)get_jobid_from_tid())
43
44 const int dbglvl =  50;
45
46 static dlist *vol_list = NULL;
47 static brwlock_t reservation_lock;
48 static brwlock_t vol_list_lock;
49
50 /* Forward referenced functions */
51 static int can_reserve_drive(DCR *dcr, RCTX &rctx);
52 static int reserve_device(RCTX &rctx);
53 static bool reserve_device_for_read(DCR *dcr);
54 static bool reserve_device_for_append(DCR *dcr, RCTX &rctx);
55 static bool use_storage_cmd(JCR *jcr);
56 static void queue_reserve_message(JCR *jcr);
57 static void pop_reserve_messages(JCR *jcr);
58 //void switch_device(DCR *dcr, DEVICE *dev);
59
60 /* Requests from the Director daemon */
61 static char use_storage[]  = "use storage=%127s media_type=%127s "
62    "pool_name=%127s pool_type=%127s append=%d copy=%d stripe=%d\n";
63 static char use_device[]  = "use device=%127s\n";
64
65 /* Responses sent to Director daemon */
66 static char OK_device[] = "3000 OK use device device=%s\n";
67 static char NO_device[] = "3924 Device \"%s\" not in SD Device resources.\n";
68 static char BAD_use[]   = "3913 Bad use command: %s\n";
69
70 bool use_cmd(JCR *jcr) 
71 {
72    /*
73     * Get the device, media, and pool information
74     */
75    if (!use_storage_cmd(jcr)) {
76       set_jcr_job_status(jcr, JS_ErrorTerminated);
77       memset(jcr->sd_auth_key, 0, strlen(jcr->sd_auth_key));
78       return false;
79    }
80    return true;
81 }
82
83 static int my_compare(void *item1, void *item2)
84 {
85    return strcmp(((VOLRES *)item1)->vol_name, ((VOLRES *)item2)->vol_name);
86 }
87
88 /*
89  * This allows a given thread to recursively call lock_reservations.
90  *   It must, of course, call unlock_... the same number of times.
91  */
92 void init_reservations_lock()
93 {
94    int errstat;
95    if ((errstat=rwl_init(&reservation_lock)) != 0) {
96       berrno be;
97       Emsg1(M_ABORT, 0, _("Unable to initialize reservation lock. ERR=%s\n"),
98             be.bstrerror(errstat));
99    }
100
101    if ((errstat=rwl_init(&vol_list_lock)) != 0) {
102       berrno be;
103       Emsg1(M_ABORT, 0, _("Unable to initialize volume list lock. ERR=%s\n"),
104             be.bstrerror(errstat));
105    }
106 }
107
108 void term_reservations_lock()
109 {
110    rwl_destroy(&reservation_lock);
111    rwl_destroy(&vol_list_lock);
112 }
113
114 int reservations_lock_count = 0;
115
116 /* This applies to a drive and to Volumes */
117 void _lock_reservations()
118 {
119    int errstat;
120    reservations_lock_count++;
121    if ((errstat=rwl_writelock(&reservation_lock)) != 0) {
122       berrno be;
123       Emsg2(M_ABORT, 0, "rwl_writelock failure. stat=%d: ERR=%s\n",
124            errstat, be.bstrerror(errstat));
125    }
126 }
127
128 void _unlock_reservations()
129 {
130    int errstat;
131    reservations_lock_count--;
132    if ((errstat=rwl_writeunlock(&reservation_lock)) != 0) {
133       berrno be;
134       Emsg2(M_ABORT, 0, "rwl_writeunlock failure. stat=%d: ERR=%s\n",
135            errstat, be.bstrerror(errstat));
136    }
137 }
138
139 int vol_list_lock_count = 0;
140
141 /* 
142  * This allows a given thread to recursively call to lock_volumes()
143  */
144 void _lock_volumes()
145 {
146    int errstat;
147    vol_list_lock_count++;
148    if ((errstat=rwl_writelock(&vol_list_lock)) != 0) {
149       berrno be;
150       Emsg2(M_ABORT, 0, "rwl_writelock failure. stat=%d: ERR=%s\n",
151            errstat, be.bstrerror(errstat));
152    }
153 }
154
155 void _unlock_volumes()
156 {
157    int errstat;
158    vol_list_lock_count--;
159    if ((errstat=rwl_writeunlock(&vol_list_lock)) != 0) {
160       berrno be;
161       Emsg2(M_ABORT, 0, "rwl_writeunlock failure. stat=%d: ERR=%s\n",
162            errstat, be.bstrerror(errstat));
163    }
164 }
165
166
167 /*
168  * List Volumes -- this should be moved to status.c
169  */
170 enum {
171    debug_lock = true,
172    debug_nolock = false
173 };
174
175 void debug_list_volumes(const char *imsg)
176 {
177    VOLRES *vol;
178    POOL_MEM msg(PM_MESSAGE);
179
180    lock_volumes();
181    foreach_dlist(vol, vol_list) {
182       if (vol->dev) {
183          Mmsg(msg, "List %s: %s in_use=%d on device %s\n", imsg, 
184               vol->vol_name, vol->is_in_use(), vol->dev->print_name());
185       } else {
186          Mmsg(msg, "List %s: %s in_use=%d no dev\n", imsg, vol->vol_name, 
187               vol->is_in_use());
188       }
189       Dmsg2(dbglvl, "jid=%u %s", jid(), msg.c_str());
190    }
191
192    unlock_volumes();
193 }
194
195
196 /*
197  * List Volumes -- this should be moved to status.c
198  */
199 void list_volumes(void sendit(const char *msg, int len, void *sarg), void *arg)
200 {
201    VOLRES *vol;
202    POOL_MEM msg(PM_MESSAGE);
203    int len;
204
205    lock_volumes();
206    foreach_dlist(vol, vol_list) {
207       DEVICE *dev = vol->dev;
208       if (dev) {
209          len = Mmsg(msg, "%s on device %s\n", vol->vol_name, dev->print_name());
210          sendit(msg.c_str(), len, arg);
211          len = Mmsg(msg, "    Reader=%d writers=%d devres=%d volinuse=%d\n", 
212             dev->can_read()?1:0, dev->num_writers, dev->num_reserved(),   
213             vol->is_in_use());
214          sendit(msg.c_str(), len, arg);
215       } else {
216          len = Mmsg(msg, "%s no device. volinuse= %d\n", vol->vol_name, 
217             vol->is_in_use());
218          sendit(msg.c_str(), len, arg);
219       }
220    }
221    unlock_volumes();
222 }
223
224 /*
225  * Create a Volume item to put in the Volume list
226  *   Ensure that the device points to it.
227  */
228 static VOLRES *new_vol_item(DCR *dcr, const char *VolumeName)
229 {
230    VOLRES *vol;
231    vol = (VOLRES *)malloc(sizeof(VOLRES));
232    memset(vol, 0, sizeof(VOLRES));
233    vol->vol_name = bstrdup(VolumeName);
234    vol->dev = dcr->dev;
235    Dmsg4(dbglvl, "jid=%u new Vol=%s at %p dev=%s\n", (int)dcr->jcr->JobId,
236          VolumeName, vol->vol_name, vol->dev->print_name());
237    return vol;
238 }
239
240 static void free_vol_item(VOLRES *vol)
241 {
242    DEVICE *dev = NULL;
243
244    free(vol->vol_name);
245    if (vol->dev) {
246       dev = vol->dev;
247    }
248    free(vol);
249    if (dev) {
250       dev->vol = NULL;
251    }
252 }
253
254 /*
255  * Put a new Volume entry in the Volume list. This
256  *  effectively reserves the volume so that it will
257  *  not be mounted again.
258  *
259  * If the device has any current volume associated with it,
260  *  and it is a different Volume, and the device is not busy,
261  *  we release the old Volume item and insert the new one.
262  * 
263  * It is assumed that the device is free and locked so that
264  *  we can change the device structure.
265  *
266  * Some details of the Volume list handling:
267  *
268  *  1. The Volume list entry must be attached to the drive (rather than 
269  *       attached to a job as it currently is. I.e. the drive that "owns" 
270  *       the volume (in use, mounted)
271  *       must point to the volume (still to be maintained in a list).
272  *
273  *  2. The Volume is entered in the list when a drive is reserved.  
274  *
275  *  3. When a drive is in use, the device code must appropriately update the
276  *      volume name as it changes (currently the list is static -- an entry is
277  *      removed when the Volume is no longer reserved, in use or mounted).  
278  *      The new code must keep the same list entry as long as the drive
279  *       has any volume associated with it but the volume name in the list
280  *       must be updated when the drive has a different volume mounted.
281  *
282  *  4. A job that has reserved a volume, can un-reserve the volume, and if the 
283  *      volume is not mounted, and not reserved, and not in use, it will be
284  *      removed from the list.
285  *
286  *  5. If a job wants to reserve a drive with a different Volume from the one on
287  *      the drive, it can re-use the drive for the new Volume.
288  *
289  *  6. If a job wants a Volume that is in a different drive, it can either use the
290  *      other drive or take the volume, only if the other drive is not in use or
291  *      not reserved.
292  *
293  *  One nice aspect of this is that the reserve use count and the writer use count 
294  *  already exist and are correctly programmed and will need no changes -- use 
295  *  counts are always very tricky.
296  *
297  *  The old code had a concept of "reserving" a Volume, but was changed 
298  *  to reserving and using a drive.  A volume is must be attached to (owned by) a 
299  *  drive and can move from drive to drive or be unused given certain specific 
300  *  conditions of the drive.  The key is that the drive must "own" the Volume.  
301  *  The old code had the job (dcr) owning the volume (more or less).  The job was
302  *  to change the insertion and removal of the volumes from the list to be based 
303  *  on the drive rather than the job.  
304  *
305  *  Return: VOLRES entry on success
306  *          NULL volume busy on another drive
307  */
308 VOLRES *reserve_volume(DCR *dcr, const char *VolumeName)
309 {
310    VOLRES *vol, *nvol;
311    DEVICE * volatile dev = dcr->dev;
312
313    ASSERT(dev != NULL);
314
315    Dmsg3(dbglvl, "jid=%u enter reserve_volume=%s drive=%s\n", jid(), VolumeName, 
316       dcr->dev->print_name());
317    /* 
318     * We lock the reservations system here to ensure
319     *  when adding a new volume that no newly scheduled
320     *  job can reserve it.
321     */
322    lock_volumes();
323    debug_list_volumes("begin reserve_volume");
324    /* 
325     * First, remove any old volume attached to this device as it
326     *  is no longer used.
327     */
328    if (dev->vol) {
329       vol = dev->vol;
330       Dmsg5(dbglvl, "jid=%u Vol attached=%s, newvol=%s volinuse=%d on %s\n",
331          jid(), vol->vol_name, VolumeName, vol->is_in_use(), dev->print_name());
332       /*
333        * Make sure we don't remove the current volume we are inserting
334        *  because it was probably inserted by another job, or it
335        *  is not being used and is marked as not reserved.
336        */
337       if (strcmp(vol->vol_name, VolumeName) == 0) {
338          Dmsg3(dbglvl, "jid=%u === set reserved vol=%s dev=%s\n", jid(), VolumeName,
339                vol->dev->print_name());
340          vol->set_in_use();             /* retake vol if released previously */
341          dcr->reserved_volume = true;   /* reserved volume */
342          goto get_out;                  /* Volume already on this device */
343       } else {
344          /* Don't release a volume if it was reserved by someone other than us */
345          if (vol->is_in_use() && !dcr->reserved_volume) { 
346             Dmsg2(dbglvl, "jid=%u Cannot free vol=%s. It is reserved.\n", jid(), vol->vol_name);
347             vol = NULL;                  /* vol in use */
348             goto get_out;
349          }
350          Dmsg3(dbglvl, "jid=%u reserve_vol free vol=%s at %p\n", jid(), vol->vol_name, vol->vol_name);
351          free_volume(dev);
352          dev->set_unload();             /* have to unload current volume */
353          debug_list_volumes("reserve_vol free");
354       }
355    }
356
357    /* Create a new Volume entry */
358    nvol = new_vol_item(dcr, VolumeName);
359
360    /*
361     * Now try to insert the new Volume
362     */
363    vol = (VOLRES *)vol_list->binary_insert(nvol, my_compare);
364    if (vol != nvol) {
365       Dmsg3(dbglvl, "jid=%u Found vol=%s dev-same=%d\n", jid(), vol->vol_name, dev==vol->dev);
366       /*
367        * At this point, a Volume with this name already is in the list,
368        *   so we simply release our new Volume entry. Note, this should
369        *   only happen if we are moving the volume from one drive to another.
370        */
371       Dmsg3(dbglvl, "jid=%u reserve_vol free-tmp vol=%s at %p\n", 
372             (int)dcr->jcr->JobId, vol->vol_name, vol->vol_name);
373       /*
374        * Clear dev pointer so that free_vol_item() doesn't 
375        *  take away our volume. 
376        */
377       nvol->dev = NULL;                  /* don't zap dev entry */
378       free_vol_item(nvol);
379
380       /*
381        * Check if we are trying to use the Volume on a different drive
382        *  dev      is our device
383        *  vol->dev is where the Volume we want is
384        */
385       if (dev != vol->dev) {
386          /* Caller wants to switch Volume to another device */
387          if (!vol->dev->is_busy() && !vol->is_swapping()) {
388             int32_t slot;
389             Dmsg4(dbglvl, "==== jid=%u Swap vol=%s from dev=%s to %s\n", jid(),
390                VolumeName, vol->dev->print_name(), dev->print_name());
391             free_volume(dev);            /* free any volume attached to our drive */
392             dev->set_unload();           /* Unload any volume that is on our drive */
393             dcr->dev = vol->dev;         /* temp point to other dev */
394             slot = get_autochanger_loaded_slot(dcr);  /* get slot on other drive */
395             dcr->dev = dev;              /* restore dev */
396             vol->set_slot(slot);         /* save slot */
397             vol->dev->set_unload();      /* unload the other drive */
398             vol->set_swapping();         /* swap from other drive */
399             dev->swap_dev = vol->dev;    /* remember to get this vol */
400             dev->set_load();             /* then reload on our drive */
401             vol->dev->vol = NULL;        /* remove volume from other drive */
402             vol->dev = dev;              /* point the Volume at our drive */
403             dev->vol = vol;              /* point our drive at the Volume */
404          } else {
405             Dmsg4(dbglvl, "jid=%u ==== Swap not possible Vol busy vol=%s from dev=%s to %s\n", jid(),
406                VolumeName, vol->dev->print_name(), dev->print_name());
407             vol = NULL;                  /* device busy */
408             goto get_out;
409          }
410       } else {
411          dev->vol = vol;
412       }
413    } else {
414       dev->vol = vol;                    /* point to newly inserted volume */
415    }
416
417 get_out:
418    if (vol) {
419       Dmsg3(dbglvl, "jid=%u === set in_use. vol=%s dev=%s\n", jid(), vol->vol_name,
420             vol->dev->print_name());
421       vol->set_in_use();
422       dcr->reserved_volume = true;
423       bstrncpy(dcr->VolumeName, vol->vol_name, sizeof(dcr->VolumeName));
424    }
425    debug_list_volumes("end new volume");
426    unlock_volumes();
427    return vol;
428 }
429
430 /* 
431  * Switch from current device to given device  
432  *   (not yet used) 
433  */
434 #ifdef xxx
435 void switch_device(DCR *dcr, DEVICE *dev)
436 {
437    DCR save_dcr;
438
439    dev->dlock();
440    memcpy(&save_dcr, dcr, sizeof(save_dcr));
441    clean_device(dcr);                  /* clean up the dcr */
442
443    dcr->dev = dev;                     /* get new device pointer */
444    Jmsg(dcr->jcr, M_INFO, 0, _("Device switch. New device %s chosen.\n"),
445       dcr->dev->print_name());
446
447    bstrncpy(dcr->VolumeName, save_dcr.VolumeName, sizeof(dcr->VolumeName));
448    bstrncpy(dcr->media_type, save_dcr.media_type, sizeof(dcr->media_type));
449    dcr->VolCatInfo.Slot = save_dcr.VolCatInfo.Slot;
450    bstrncpy(dcr->pool_name, save_dcr.pool_name, sizeof(dcr->pool_name));
451    bstrncpy(dcr->pool_type, save_dcr.pool_type, sizeof(dcr->pool_type));
452    bstrncpy(dcr->dev_name, dev->dev_name, sizeof(dcr->dev_name));
453
454 // dcr->set_reserved();
455
456    dev->dunlock();
457 }
458 #endif
459
460 /*
461  * Search for a Volume name in the Volume list.
462  *
463  *  Returns: VOLRES entry on success
464  *           NULL if the Volume is not in the list
465  */
466 VOLRES *find_volume(const char *VolumeName) 
467 {
468    VOLRES vol, *fvol;
469    /* Do not lock reservations here */
470    lock_volumes();
471    vol.vol_name = bstrdup(VolumeName);
472    fvol = (VOLRES *)vol_list->binary_search(&vol, my_compare);
473    free(vol.vol_name);
474    Dmsg3(dbglvl, "jid=%u find_vol=%s found=%d\n", jid(), VolumeName, fvol!=NULL);
475    debug_list_volumes("find_volume");
476    unlock_volumes();
477    return fvol;
478 }
479
480 void DCR::set_reserved()
481 {
482    m_reserved = true;
483    Dmsg2(dbglvl, "Inc reserve=%d dev=%s\n", dev->num_reserved(), dev->print_name());
484    dev->inc_reserved();
485 }
486
487 void DCR::clear_reserved()
488 {
489    if (m_reserved) {
490       m_reserved = false;
491       dev->dec_reserved();
492       Dmsg2(dbglvl, "Dec reserve=%d dev=%s\n", dev->num_reserved(), dev->print_name());
493    }
494 }
495
496 /* 
497  * Remove any reservation from a drive and tell the system
498  *  that the volume is unused at least by us.
499  */
500 void DCR::unreserve_device()
501 {
502    lock_volumes();
503    if (is_reserved()) {
504       clear_reserved();
505       reserved_volume = false;
506       /* If we set read mode in reserving, remove it */
507       if (dev->can_read()) {
508          dev->clear_read();
509       }
510       if (dev->num_writers < 0) {
511          Jmsg1(jcr, M_ERROR, 0, _("Hey! num_writers=%d!!!!\n"), dev->num_writers);
512          dev->num_writers = 0;
513       }
514       if (dev->num_reserved() == 0 && dev->num_writers == 0) {
515          volume_unused(this);
516       }
517    }
518    unlock_volumes();
519 }
520
521 /*  
522  * Free a Volume from the Volume list if it is no longer used
523  *   Note, for tape drives we want to remember where the Volume
524  *   was when last used, so rather than free the volume entry,
525  *   we simply mark it "not reserved" so when the drive is really
526  *   needed for another volume, we can reuse it.
527  *
528  *  Returns: true if the Volume found and "removed" from the list
529  *           false if the Volume is not in the list or is in use
530  */
531 bool volume_unused(DCR *dcr)
532 {
533    DEVICE *dev = dcr->dev;
534
535    if (!dev->vol) {
536       Dmsg2(dbglvl, "jid=%u vol_unused: no vol on %s\n", (int)dcr->jcr->JobId, dev->print_name());
537       debug_list_volumes("null vol cannot unreserve_volume");
538       return false;
539    }
540    if (dev->vol->is_swapping()) {
541       Dmsg1(dbglvl, "vol_unused: vol being swapped on %s\n", dev->print_name());
542       debug_list_volumes("swapping vol cannot unreserve_volume");
543       return false;
544    }
545
546 #ifdef xxx
547    if (dev->is_busy()) {
548       Dmsg2(dbglvl, "jid=%u vol_unused: busy on %s\n", (int)dcr->jcr->JobId, dev->print_name());
549       debug_list_volumes("dev busy cannot unreserve_volume");
550       return false;
551    }
552 #endif
553 #ifdef xxx
554    if (dev->num_writers > 0 || dev->num_reserved() > 0) {
555       ASSERT(0);
556    }
557 #endif
558
559    /*  
560     * If this is a tape, we do not free the volume, rather we wait
561     *  until the autoloader unloads it, or until another tape is
562     *  explicitly read in this drive. This allows the SD to remember
563     *  where the tapes are or last were.
564     */
565    Dmsg5(dbglvl, "jid=%u === set not reserved vol=%s num_writers=%d dev_reserved=%d dev=%s\n",
566       jid(), dev->vol->vol_name, dev->num_writers, dev->num_reserved(), dev->print_name());
567    dev->vol->clear_in_use();
568    if (dev->is_tape() || dev->is_autochanger()) {
569       return true;
570    } else {
571       /*
572        * Note, this frees the volume reservation entry, but the 
573        *   file descriptor remains open with the OS.
574        */
575       return free_volume(dev);
576    }
577 }
578
579 /*
580  * Unconditionally release the volume entry
581  */
582 bool free_volume(DEVICE *dev)
583 {
584    VOLRES *vol;
585
586    if (dev->vol == NULL) {
587       Dmsg2(dbglvl, "jid=%u No vol on dev %s\n", jid(), dev->print_name());
588       return false;
589    }
590    lock_volumes();
591    vol = dev->vol;
592    /* Don't free a volume while it is being swapped */
593    if (!vol->is_swapping()) {
594       dev->vol = NULL;
595       vol_list->remove(vol);
596       Dmsg3(dbglvl, "jid=%u === remove volume %s dev=%s\n", jid(), vol->vol_name, dev->print_name());
597       free_vol_item(vol);
598       debug_list_volumes("free_volume");
599    }
600    unlock_volumes();
601    return true;
602 }
603
604       
605 /* Create the Volume list */
606 void create_volume_list()
607 {
608    VOLRES *vol = NULL;
609    if (vol_list == NULL) {
610       vol_list = New(dlist(vol, &vol->link));
611    }
612 }
613
614 /* Release all Volumes from the list */
615 void free_volume_list()
616 {
617    VOLRES *vol;
618    if (!vol_list) {
619       return;
620    }
621    lock_volumes();
622    foreach_dlist(vol, vol_list) {
623       if (vol->dev) {
624          Dmsg3(dbglvl, "jid=%u free vol_list Volume=%s dev=%s\n", jid(),
625                vol->vol_name, vol->dev->print_name());
626       } else {
627          Dmsg3(dbglvl, "jid=%u free vol_list Volume=%s dev=%p\n", jid(), 
628                vol->vol_name, vol->dev);
629       }
630       free(vol->vol_name);
631       vol->vol_name = NULL;
632    }
633    delete vol_list;
634    vol_list = NULL;
635    unlock_volumes();
636 }
637
638 bool DCR::can_i_use_volume()
639 {
640    bool rtn = true;
641    VOLRES *vol;
642
643    lock_volumes();
644    vol = find_volume(VolumeName);
645    if (!vol) {
646       Dmsg2(dbglvl, "jid=%u Vol=%s not in use.\n", jid(), VolumeName);
647       goto get_out;                   /* vol not in list */
648    }
649    ASSERT(vol->dev != NULL);
650
651    if (dev == vol->dev) {        /* same device OK */
652       Dmsg2(dbglvl, "jid=%u Vol=%s on same dev.\n", jid(), VolumeName);
653       goto get_out;
654    } else {
655       Dmsg4(dbglvl, "jid=%u Vol=%s on %s we have %s\n", jid(), VolumeName,
656             vol->dev->print_name(), dev->print_name());
657    }
658    /* ***FIXME*** check this ... */
659    if (!vol->dev->is_busy()) {
660       Dmsg3(dbglvl, "jid=%u Vol=%s dev=%s not busy.\n", jid(), VolumeName, vol->dev->print_name());
661       goto get_out;
662    } else {
663       Dmsg3(dbglvl, "jid=%u Vol=%s dev=%s busy.\n", jid(), VolumeName, vol->dev->print_name());
664    }
665    Dmsg3(dbglvl, "jid=%u Vol=%s in use by %s.\n", jid(), VolumeName, vol->dev->print_name());
666    rtn = false;
667
668 get_out:
669    unlock_volumes();
670    return rtn;
671
672 }
673
674
675 /*
676  * We get the following type of information:
677  *
678  * use storage=xxx media_type=yyy pool_name=xxx pool_type=yyy append=1 copy=0 strip=0
679  *  use device=zzz
680  *  use device=aaa
681  *  use device=bbb
682  * use storage=xxx media_type=yyy pool_name=xxx pool_type=yyy append=0 copy=0 strip=0
683  *  use device=bbb
684  *
685  */
686 static bool use_storage_cmd(JCR *jcr)
687 {
688    POOL_MEM store_name, dev_name, media_type, pool_name, pool_type;
689    BSOCK *dir = jcr->dir_bsock;
690    int append;
691    bool ok;       
692    int Copy, Stripe;
693    DIRSTORE *store;
694    RCTX rctx;
695    alist *dirstore;
696
697    memset(&rctx, 0, sizeof(RCTX));
698    rctx.jcr = jcr;
699    /*
700     * If there are multiple devices, the director sends us
701     *   use_device for each device that it wants to use.
702     */
703    dirstore = New(alist(10, not_owned_by_alist));
704    jcr->reserve_msgs = New(alist(10, not_owned_by_alist));  
705    do {
706       Dmsg2(dbglvl, "jid=%u <dird: %s", jid(), dir->msg);
707       ok = sscanf(dir->msg, use_storage, store_name.c_str(), 
708                   media_type.c_str(), pool_name.c_str(), 
709                   pool_type.c_str(), &append, &Copy, &Stripe) == 7;
710       if (!ok) {
711          break;
712       }
713       if (append) {
714          jcr->write_store = dirstore;
715       } else {
716          jcr->read_store = dirstore;
717       }
718       rctx.append = append;
719       unbash_spaces(store_name);
720       unbash_spaces(media_type);
721       unbash_spaces(pool_name);
722       unbash_spaces(pool_type);
723       store = new DIRSTORE;
724       dirstore->append(store);
725       memset(store, 0, sizeof(DIRSTORE));
726       store->device = New(alist(10));
727       bstrncpy(store->name, store_name, sizeof(store->name));
728       bstrncpy(store->media_type, media_type, sizeof(store->media_type));
729       bstrncpy(store->pool_name, pool_name, sizeof(store->pool_name));
730       bstrncpy(store->pool_type, pool_type, sizeof(store->pool_type));
731       store->append = append;
732
733       /* Now get all devices */
734       while (dir->recv() >= 0) {
735          Dmsg2(dbglvl, "jid=%u <dird device: %s", jid(), dir->msg);
736          ok = sscanf(dir->msg, use_device, dev_name.c_str()) == 1;
737          if (!ok) {
738             break;
739          }
740          unbash_spaces(dev_name);
741          store->device->append(bstrdup(dev_name.c_str()));
742       }
743    }  while (ok && dir->recv() >= 0);
744
745    /* Developer debug code */
746    char *device_name;
747    if (debug_level >= dbglvl) {
748       foreach_alist(store, dirstore) {
749          Dmsg6(dbglvl, "jid=%u Storage=%s media_type=%s pool=%s pool_type=%s append=%d\n", 
750             (int)rctx.jcr->JobId,
751             store->name, store->media_type, store->pool_name, 
752             store->pool_type, store->append);
753          foreach_alist(device_name, store->device) {
754             Dmsg2(dbglvl, "jid=%u     Device=%s\n", jid(), device_name);
755          }
756       }
757    }
758
759    init_jcr_device_wait_timers(jcr);
760    jcr->dcr = new_dcr(jcr, NULL, NULL);         /* get a dcr */
761    if (!jcr->dcr) {
762       BSOCK *dir = jcr->dir_bsock;
763       dir->fsend(_("3939 Could not get dcr\n"));
764       Dmsg1(dbglvl, ">dird: %s", dir->msg);
765       ok = false;
766    }
767    /*                    
768     * At this point, we have a list of all the Director's Storage
769     *  resources indicated for this Job, which include Pool, PoolType,
770     *  storage name, and Media type.     
771     * Then for each of the Storage resources, we have a list of
772     *  device names that were given.
773     *
774     * Wiffle through them and find one that can do the backup.
775     */
776    if (ok) {
777       int wait_for_device_retries = 0;  
778       int repeat = 0;
779       bool fail = false;
780       rctx.notify_dir = true;
781
782       lock_reservations();
783       for ( ; !fail && !job_canceled(jcr); ) {
784          pop_reserve_messages(jcr);
785          rctx.suitable_device = false;
786          rctx.have_volume = false;
787          rctx.VolumeName[0] = 0;
788          rctx.any_drive = false;
789          if (!jcr->PreferMountedVols) {
790             /*
791              * Here we try to find a drive that is not used.
792              * This will maximize the use of available drives.
793              *
794              */
795             rctx.num_writers = 20000000;   /* start with impossible number */
796             rctx.low_use_drive = NULL;
797             rctx.PreferMountedVols = false;                
798             rctx.exact_match = false;
799             rctx.autochanger_only = true;
800             if ((ok = find_suitable_device_for_job(jcr, rctx))) {
801                break;
802             }
803             /* Look through all drives possibly for low_use drive */
804             if (rctx.low_use_drive) {
805                rctx.try_low_use_drive = true;
806                if ((ok = find_suitable_device_for_job(jcr, rctx))) {
807                   break;
808                }
809                rctx.try_low_use_drive = false;
810             }
811             rctx.autochanger_only = false;
812             if ((ok = find_suitable_device_for_job(jcr, rctx))) {
813                break;
814             }
815          }
816          /*
817           * Now we look for a drive that may or may not be in
818           *  use.
819           */
820          /* Look for an exact Volume match all drives */
821          rctx.PreferMountedVols = true;
822          rctx.exact_match = true;
823          rctx.autochanger_only = false;
824          if ((ok = find_suitable_device_for_job(jcr, rctx))) {
825             break;
826          }
827          /* Look for any mounted drive */
828          rctx.exact_match = false;
829          if ((ok = find_suitable_device_for_job(jcr, rctx))) {
830             break;
831          }
832          /* Try any drive */
833          rctx.any_drive = true;
834          if ((ok = find_suitable_device_for_job(jcr, rctx))) {
835             break;
836          }
837          /* Keep reservations locked *except* during wait_for_device() */
838          unlock_reservations();
839          /*     
840           * The idea of looping on repeat a few times it to ensure
841           * that if there is some subtle timing problem between two
842           * jobs, we will simply try again, and most likely succeed.
843           * This can happen if one job reserves a drive or finishes using
844           * a drive at the same time a second job wants it.
845           */
846          if (repeat++ > 1) {              /* try algorithm 3 times */
847             bmicrosleep(30, 0);           /* wait a bit */
848             Dmsg1(dbglvl, "jid=%u repeat reserve algorithm\n", (int)rctx.jcr->JobId);
849          } else if (!rctx.suitable_device || !wait_for_device(jcr, wait_for_device_retries)) {
850             Dmsg1(dbglvl, "jid=%u Fail. !suitable_device || !wait_for_device\n",
851                  (int)rctx.jcr->JobId);
852             fail = true;
853          }   
854          lock_reservations();
855          dir->signal(BNET_HEARTBEAT);  /* Inform Dir that we are alive */
856       }
857       unlock_reservations();
858       if (!ok) {
859          /*
860           * If we get here, there are no suitable devices available, which
861           *  means nothing configured.  If a device is suitable but busy
862           *  with another Volume, we will not come here.
863           */
864          unbash_spaces(dir->msg);
865          pm_strcpy(jcr->errmsg, dir->msg);
866          Jmsg(jcr, M_INFO, 0, _("Failed command: %s\n"), jcr->errmsg);
867          Jmsg(jcr, M_FATAL, 0, _("\n"
868             "     Device \"%s\" with MediaType \"%s\" requested by DIR not found in SD Device resources.\n"),
869               dev_name.c_str(), media_type.c_str());
870          dir->fsend(NO_device, dev_name.c_str());
871
872          Dmsg2(dbglvl, "jid=%u >dird: %s", jid(), dir->msg);
873       }
874    } else {
875       unbash_spaces(dir->msg);
876       pm_strcpy(jcr->errmsg, dir->msg);
877       Jmsg(jcr, M_FATAL, 0, _("Failed command: %s\n"), jcr->errmsg);
878       dir->fsend(BAD_use, jcr->errmsg);
879       Dmsg2(dbglvl, "jid=%u >dird: %s", jid(), dir->msg);
880    }
881
882    release_reserve_messages(jcr);
883    return ok;
884 }
885
886
887 /*
888  * Walk through the autochanger resources and check if
889  *  the volume is in one of them.
890  * 
891  * Returns:  true  if volume is in device
892  *           false otherwise
893  */
894 static bool is_vol_in_autochanger(RCTX &rctx, VOLRES *vol)
895 {
896    AUTOCHANGER *changer = vol->dev->device->changer_res;
897
898    /* Find resource, and make sure we were able to open it */
899    if (strcmp(rctx.device_name, changer->hdr.name) == 0) {
900       Dmsg2(dbglvl, "jid=%u Found changer device %s\n", (int)rctx.jcr->JobId, vol->dev->device->hdr.name);
901       return true;
902    }  
903    Dmsg2(dbglvl, "jid=%u Incorrect changer device %s\n", (int)rctx.jcr->JobId, changer->hdr.name);
904    return false;
905 }
906
907 /*
908  * Search for a device suitable for this job.
909  * Note, this routine sets sets rctx.suitable_device if any 
910  *   device exists within the SD.  The device may not be actually
911  *   useable.
912  * It also returns if it finds a useable device.  
913  */
914 bool find_suitable_device_for_job(JCR *jcr, RCTX &rctx)
915 {
916    bool ok = false;
917    DIRSTORE *store;
918    char *device_name;
919    alist *dirstore;
920    DCR *dcr = jcr->dcr;
921
922    if (rctx.append) {
923       dirstore = jcr->write_store;
924    } else {
925       dirstore = jcr->read_store;
926    }
927    Dmsg5(dbglvl, "jid=%u PrefMnt=%d exact=%d suitable=%d chgronly=%d\n",
928       (int)rctx.jcr->JobId,
929       rctx.PreferMountedVols, rctx.exact_match, rctx.suitable_device,
930       rctx.autochanger_only);
931
932    /* 
933     * If the appropriate conditions of this if are met, namely that
934     *  we are appending and the user wants mounted drive (or we
935     *  force try a mounted drive because they are all busy), we
936     *  start by looking at all the Volumes in the volume list.
937     */
938    if (!vol_list->empty() && rctx.append && rctx.PreferMountedVols) {
939       dlist *temp_vol_list, *save_vol_list;
940       VOLRES *vol = NULL;
941       lock_volumes();
942       Dmsg0(dbglvl, "lock volumes\n");                           
943
944       /*  
945        * Create a temporary copy of the volume list.  We do this,
946        *   to avoid having the volume list locked during the
947        *   call to reserve_device(), which would cause a deadlock.
948        * Note, we may want to add an update counter on the vol_list
949        *   so that if it is modified while we are traversing the copy
950        *   we can take note and act accordingly (probably redo the 
951        *   search at least a few times).
952        */
953       Dmsg1(dbglvl, "jid=%u duplicate vol list\n", (int)rctx.jcr->JobId);
954       temp_vol_list = New(dlist(vol, &vol->link));
955       foreach_dlist(vol, vol_list) {
956          VOLRES *nvol;
957          VOLRES *tvol = (VOLRES *)malloc(sizeof(VOLRES));
958          memset(tvol, 0, sizeof(VOLRES));
959          tvol->vol_name = bstrdup(vol->vol_name);
960          tvol->dev = vol->dev;
961          nvol = (VOLRES *)temp_vol_list->binary_insert(tvol, my_compare);
962          if (tvol != nvol) {
963             tvol->dev = NULL;                   /* don't zap dev entry */
964             free_vol_item(tvol);
965             Pmsg0(000, "Logic error. Duplicating vol list hit duplicate.\n");
966             Jmsg(jcr, M_WARNING, 0, "Logic error. Duplicating vol list hit duplicate.\n");
967          }
968       }
969       unlock_volumes();
970
971       /* Look through reserved volumes for one we can use */
972       Dmsg1(dbglvl, "jid=%u look for vol in vol list\n", (int)rctx.jcr->JobId);
973       foreach_dlist(vol, temp_vol_list) {
974          if (!vol->dev) {
975             Dmsg2(dbglvl, "jid=%u vol=%s no dev\n", (int)rctx.jcr->JobId, vol->vol_name);
976             continue;
977          }
978          /* Check with Director if this Volume is OK */
979          bstrncpy(dcr->VolumeName, vol->vol_name, sizeof(dcr->VolumeName));
980          if (!dir_get_volume_info(dcr, GET_VOL_INFO_FOR_WRITE)) {
981             continue;
982          }
983
984          Dmsg2(dbglvl, "jid=%u vol=%s OK for this job\n", (int)rctx.jcr->JobId, vol->vol_name);
985          foreach_alist(store, dirstore) {
986             int stat;
987             rctx.store = store;
988             foreach_alist(device_name, store->device) {
989                /* Found a device, try to use it */
990                rctx.device_name = device_name;
991                rctx.device = vol->dev->device;
992
993                if (vol->dev->is_autochanger()) {
994                   Dmsg2(dbglvl, "jid=%u vol=%s is in changer\n", (int)rctx.jcr->JobId, 
995                         vol->vol_name);
996                   if (!is_vol_in_autochanger(rctx, vol)) {
997                      continue;
998                   }
999                } else if (strcmp(device_name, vol->dev->device->hdr.name) != 0) {
1000                   Dmsg3(dbglvl, "jid=%u device=%s not suitable want %s\n", (int)rctx.jcr->JobId, 
1001                         vol->dev->device->hdr.name, device_name);
1002                   continue;
1003                }
1004
1005                bstrncpy(rctx.VolumeName, vol->vol_name, sizeof(rctx.VolumeName));
1006                rctx.have_volume = true;
1007                /* Try reserving this device and volume */
1008                Dmsg3(dbglvl, "jid=%u try vol=%s on device=%s\n", (int)rctx.jcr->JobId, 
1009                      rctx.VolumeName, device_name);
1010                stat = reserve_device(rctx);
1011                if (stat == 1) {             /* found available device */
1012                   Dmsg2(dbglvl, "jid=%u Suitable device found=%s\n", (int)rctx.jcr->JobId, 
1013                         device_name);
1014                   ok = true;
1015                   break;
1016                } else if (stat == 0) {      /* device busy */
1017                   Dmsg2(dbglvl, "jid=%u Suitable device=%s, busy: not use\n", 
1018                         (int)rctx.jcr->JobId, device_name);
1019                } else {
1020                   /* otherwise error */
1021                   Dmsg1(dbglvl, "jid=%u No suitable device found.\n", (int)rctx.jcr->JobId);
1022                }
1023                rctx.have_volume = false;
1024                rctx.VolumeName[0] = 0;
1025             }
1026             if (ok) {
1027                break;
1028             }
1029          }
1030          if (ok) {
1031             break;
1032          }
1033       } /* end for loop over reserved volumes */
1034
1035       Dmsg1(dbglvl, "%u lock volumes\n", jid());
1036       lock_volumes();
1037       save_vol_list = vol_list;
1038       vol_list = temp_vol_list;
1039       free_volume_list();                  /* release temp_vol_list */
1040       vol_list = save_vol_list;
1041       Dmsg1(dbglvl, "jid=%u deleted temp vol list\n", (int)rctx.jcr->JobId);
1042       Dmsg1(dbglvl, "jid=%u unlock volumes\n", (int)rctx.jcr->JobId);
1043       unlock_volumes();
1044    }
1045    if (ok) {
1046       Dmsg2(dbglvl, "jid=%u got vol %s from in-use vols list\n", (int)rctx.jcr->JobId,
1047             rctx.VolumeName);
1048       return true;
1049    }
1050
1051    /* 
1052     * No reserved volume we can use, so now search for an available device.  
1053     *
1054     * For each storage device that the user specified, we
1055     *  search and see if there is a resource for that device.
1056     */
1057    foreach_alist(store, dirstore) {
1058       rctx.store = store;
1059       foreach_alist(device_name, store->device) {
1060          int stat;
1061          rctx.device_name = device_name;
1062          stat = search_res_for_device(rctx); 
1063          if (stat == 1) {             /* found available device */
1064             Dmsg2(dbglvl, "jid=%u available device found=%s\n", (int)rctx.jcr->JobId,device_name);
1065             ok = true;
1066             break;
1067          } else if (stat == 0) {      /* device busy */
1068             Dmsg2(dbglvl, "jid=%u No usable device=%s, busy: not use\n", (int)rctx.jcr->JobId,device_name);
1069          } else {
1070             /* otherwise error */
1071             Dmsg1(dbglvl, "jid=%u No usable device found.\n", (int)rctx.jcr->JobId);
1072          }
1073       }
1074       if (ok) {
1075          break;
1076       }
1077    }
1078    if (ok) {
1079       Dmsg1(dbglvl, "OK dev found. Vol=%s\n", rctx.VolumeName);
1080    } else {
1081       Dmsg0(dbglvl, "Leave find_suit_dev: no dev found.\n");
1082    }
1083    return ok;
1084 }
1085
1086 /*
1087  * Search for a particular storage device with particular storage
1088  *  characteristics (MediaType).
1089  */
1090 int search_res_for_device(RCTX &rctx) 
1091 {
1092    AUTOCHANGER *changer;
1093    int stat;
1094
1095    Dmsg2(dbglvl, "jid=%u search res for %s\n", (int)rctx.jcr->JobId, rctx.device_name);
1096    /* Look through Autochangers first */
1097    foreach_res(changer, R_AUTOCHANGER) {
1098       Dmsg2(dbglvl, "jid=%u Try match changer res=%s\n", (int)rctx.jcr->JobId, changer->hdr.name);
1099       /* Find resource, and make sure we were able to open it */
1100       if (strcmp(rctx.device_name, changer->hdr.name) == 0) {
1101          /* Try each device in this AutoChanger */
1102          foreach_alist(rctx.device, changer->device) {
1103             Dmsg2(dbglvl, "jid=%u Try changer device %s\n", (int)rctx.jcr->JobId, 
1104                   rctx.device->hdr.name);
1105             stat = reserve_device(rctx);
1106             if (stat != 1) {             /* try another device */
1107                continue;
1108             }
1109             /* Debug code */
1110             if (rctx.store->append == SD_APPEND) {
1111                Dmsg3(dbglvl, "jid=%u Device %s reserved=%d for append.\n", 
1112                   (int)rctx.jcr->JobId, rctx.device->hdr.name,
1113                   rctx.jcr->dcr->dev->num_reserved());
1114             } else {
1115                Dmsg3(dbglvl, "jid=%u Device %s reserved=%d for read.\n", 
1116                   (int)rctx.jcr->JobId, rctx.device->hdr.name,
1117                   rctx.jcr->read_dcr->dev->num_reserved());
1118             }
1119             return stat;
1120          }
1121       }
1122    }
1123
1124    /* Now if requested look through regular devices */
1125    if (!rctx.autochanger_only) {
1126       foreach_res(rctx.device, R_DEVICE) {
1127          Dmsg2(dbglvl, "jid=%u Try match res=%s\n", (int)rctx.jcr->JobId, rctx.device->hdr.name);
1128          /* Find resource, and make sure we were able to open it */
1129          if (strcmp(rctx.device_name, rctx.device->hdr.name) == 0) {
1130             stat = reserve_device(rctx);
1131             if (stat != 1) {             /* try another device */
1132                continue;
1133             }
1134             /* Debug code */
1135             if (rctx.store->append == SD_APPEND) {
1136                Dmsg3(dbglvl, "jid=%u Device %s reserved=%d for append.\n", 
1137                   (int)rctx.jcr->JobId, rctx.device->hdr.name,
1138                   rctx.jcr->dcr->dev->num_reserved());
1139             } else {
1140                Dmsg3(dbglvl, "jid=%u Device %s reserved=%d for read.\n", 
1141                   (int)rctx.jcr->JobId, rctx.device->hdr.name,
1142                   rctx.jcr->read_dcr->dev->num_reserved());
1143             }
1144             return stat;
1145          }
1146       }
1147    }
1148    return -1;                    /* nothing found */
1149 }
1150
1151 /*
1152  *  Try to reserve a specific device.
1153  *
1154  *  Returns: 1 -- OK, have DCR
1155  *           0 -- must wait
1156  *          -1 -- fatal error
1157  */
1158 static int reserve_device(RCTX &rctx)
1159 {
1160    bool ok;
1161    DCR *dcr;
1162    const int name_len = MAX_NAME_LENGTH;
1163
1164    /* Make sure MediaType is OK */
1165    Dmsg3(dbglvl, "jid=%u chk MediaType device=%s request=%s\n",
1166          (int)rctx.jcr->JobId,
1167          rctx.device->media_type, rctx.store->media_type);
1168    if (strcmp(rctx.device->media_type, rctx.store->media_type) != 0) {
1169       return -1;
1170    }
1171
1172    /* Make sure device exists -- i.e. we can stat() it */
1173    if (!rctx.device->dev) {
1174       rctx.device->dev = init_dev(rctx.jcr, rctx.device);
1175    }
1176    if (!rctx.device->dev) {
1177       if (rctx.device->changer_res) {
1178         Jmsg(rctx.jcr, M_WARNING, 0, _("\n"
1179            "     Device \"%s\" in changer \"%s\" requested by DIR could not be opened or does not exist.\n"),
1180              rctx.device->hdr.name, rctx.device_name);
1181       } else {
1182          Jmsg(rctx.jcr, M_WARNING, 0, _("\n"
1183             "     Device \"%s\" requested by DIR could not be opened or does not exist.\n"),
1184               rctx.device_name);
1185       }
1186       return -1;  /* no use waiting */
1187    }  
1188
1189    rctx.suitable_device = true;
1190    Dmsg1(dbglvl, "try reserve %s\n", rctx.device->hdr.name);
1191    rctx.jcr->dcr = dcr = new_dcr(rctx.jcr, rctx.jcr->dcr, rctx.device->dev);
1192    if (!dcr) {
1193       BSOCK *dir = rctx.jcr->dir_bsock;
1194       dir->fsend(_("3926 Could not get dcr for device: %s\n"), rctx.device_name);
1195       Dmsg1(dbglvl, ">dird: %s", dir->msg);
1196       return -1;
1197    }
1198    bstrncpy(dcr->pool_name, rctx.store->pool_name, name_len);
1199    bstrncpy(dcr->pool_type, rctx.store->pool_type, name_len);
1200    bstrncpy(dcr->media_type, rctx.store->media_type, name_len);
1201    bstrncpy(dcr->dev_name, rctx.device_name, name_len);
1202    if (rctx.store->append == SD_APPEND) {
1203       Dmsg3(dbglvl, "jid=%u have_vol=%d vol=%s\n", (int)rctx.jcr->JobId,
1204           rctx.have_volume, rctx.VolumeName);                                   
1205       ok = reserve_device_for_append(dcr, rctx);
1206       if (!ok) {
1207          goto bail_out;
1208       }
1209
1210       rctx.jcr->dcr = dcr;
1211       Dmsg6(dbglvl, "jid=%u Reserved=%d dev_name=%s mediatype=%s pool=%s ok=%d\n",
1212                (int)rctx.jcr->JobId,
1213                dcr->dev->num_reserved(),
1214                dcr->dev_name, dcr->media_type, dcr->pool_name, ok);
1215       if (rctx.have_volume) {
1216          if (reserve_volume(dcr, rctx.VolumeName)) {
1217             Dmsg2(dbglvl, "jid=%u Reserved vol=%s\n", jid(), rctx.VolumeName);
1218          } else {
1219             Dmsg2(dbglvl, "jid=%u Could not reserve vol=%s\n", jid(), rctx.VolumeName);
1220             goto bail_out;
1221          }
1222       } else {
1223          dcr->any_volume = true;
1224          if (dir_find_next_appendable_volume(dcr)) {
1225             bstrncpy(rctx.VolumeName, dcr->VolumeName, sizeof(rctx.VolumeName));
1226             Dmsg2(dbglvl, "jid=%u looking for Volume=%s\n", (int)rctx.jcr->JobId, rctx.VolumeName);
1227             rctx.have_volume = true;
1228          } else {
1229             Dmsg1(dbglvl, "jid=%u No next volume found\n", (int)rctx.jcr->JobId);
1230             rctx.have_volume = false;
1231             rctx.VolumeName[0] = 0;
1232             /*
1233              * If there is at least one volume that is valid and in use,
1234              *   but we get here, check if we are running with prefers
1235              *   non-mounted drives.  In that case, we have selected a
1236              *   non-used drive and our one and only volume is mounted
1237              *   elsewhere, so we bail out and retry using that drive.
1238              */
1239             if (dcr->found_in_use() && !rctx.PreferMountedVols) {
1240                rctx.PreferMountedVols = true;
1241                if (dcr->VolumeName[0]) {
1242                   dcr->unreserve_device();
1243                }
1244                goto bail_out;
1245             }
1246             /*
1247              * Note. Under some circumstances, the Director can hand us
1248              *  a Volume name that is not the same as the one on the current
1249              *  drive, and in that case, the call above to find the next
1250              *  volume will fail because in attempting to reserve the Volume
1251              *  the code will realize that we already have a tape mounted,
1252              *  and it will fail.  This *should* only happen if there are 
1253              *  writers, thus the following test.  In that case, we simply
1254              *  bail out, and continue waiting, rather than plunging on
1255              *  and hoping that the operator can resolve the problem. 
1256              */
1257             if (dcr->dev->num_writers != 0) {
1258                if (dcr->VolumeName[0]) {
1259                   dcr->unreserve_device();
1260                }
1261                goto bail_out;
1262             }
1263          }
1264       }
1265    } else {
1266       ok = reserve_device_for_read(dcr);
1267       if (ok) {
1268          rctx.jcr->read_dcr = dcr;
1269          Dmsg6(dbglvl, "jid=%u Read reserved=%d dev_name=%s mediatype=%s pool=%s ok=%d\n",
1270                (int)rctx.jcr->JobId,
1271                dcr->dev->num_reserved(),
1272                dcr->dev_name, dcr->media_type, dcr->pool_name, ok);
1273       }
1274    }
1275    if (!ok) {
1276       goto bail_out;
1277    }
1278
1279    if (rctx.notify_dir) {
1280       POOL_MEM dev_name;
1281       BSOCK *dir = rctx.jcr->dir_bsock;
1282       pm_strcpy(dev_name, rctx.device->hdr.name);
1283       bash_spaces(dev_name);
1284       ok = dir->fsend(OK_device, dev_name.c_str());  /* Return real device name */
1285       Dmsg2(dbglvl, "jid=%u >dird changer: %s", jid(), dir->msg);
1286    } else {
1287       ok = true;
1288    }
1289    return ok ? 1 : -1;
1290
1291 bail_out:
1292    rctx.have_volume = false;
1293    Dmsg1(dbglvl, "jid=%u Not OK.\n", (int)rctx.jcr->JobId);
1294    rctx.VolumeName[0] = 0;
1295    return 0;
1296 }
1297
1298 /*
1299  * We "reserve" the drive by setting the ST_READ bit. No one else
1300  *  should touch the drive until that is cleared.
1301  *  This allows the DIR to "reserve" the device before actually
1302  *  starting the job. 
1303  */
1304 static bool reserve_device_for_read(DCR *dcr)
1305 {
1306    DEVICE *dev = dcr->dev;
1307    JCR *jcr = dcr->jcr;
1308    bool ok = false;
1309
1310    ASSERT(dcr);
1311
1312    dev->dlock();  
1313
1314    if (is_device_unmounted(dev)) {             
1315       Dmsg2(dbglvl, "jid=%u Device %s is BLOCKED due to user unmount.\n", 
1316          (int)jcr->JobId, dev->print_name());
1317       Mmsg(jcr->errmsg, _("3601 JobId=%u device %s is BLOCKED due to user unmount.\n"),
1318            jcr->JobId, dev->print_name());
1319       queue_reserve_message(jcr);
1320       goto bail_out;
1321    }
1322
1323    if (dev->is_busy()) {
1324       Dmsg5(dbglvl, "jid=%u Device %s is busy ST_READ=%d num_writers=%d reserved=%d.\n", 
1325          (int)jcr->JobId, dev->print_name(),
1326          dev->state & ST_READ?1:0, dev->num_writers, dev->num_reserved());
1327       Mmsg(jcr->errmsg, _("3602 JobId=%u device %s is busy (already reading/writing).\n"),
1328             jcr->JobId, dev->print_name());
1329       queue_reserve_message(jcr);
1330       goto bail_out;
1331    }
1332
1333    dev->clear_append();
1334    dev->set_read();
1335    ok = true;
1336    dcr->set_reserved();
1337
1338 bail_out:
1339    dev->dunlock();
1340    return ok;
1341 }
1342
1343
1344 /*
1345  * We reserve the device for appending by incrementing
1346  *  num_reserved(). We do virtually all the same work that
1347  *  is done in acquire_device_for_append(), but we do
1348  *  not attempt to mount the device. This routine allows
1349  *  the DIR to reserve multiple devices before *really* 
1350  *  starting the job. It also permits the SD to refuse 
1351  *  certain devices (not up, ...).
1352  *
1353  * Note, in reserving a device, if the device is for the
1354  *  same pool and the same pool type, then it is acceptable.
1355  *  The Media Type has already been checked. If we are
1356  *  the first tor reserve the device, we put the pool
1357  *  name and pool type in the device record.
1358  */
1359 static bool reserve_device_for_append(DCR *dcr, RCTX &rctx)
1360 {
1361    JCR *jcr = dcr->jcr;
1362    DEVICE *dev = dcr->dev;
1363    bool ok = false;
1364
1365    ASSERT(dcr);
1366
1367    dev->dlock();
1368
1369    /* If device is being read, we cannot write it */
1370    if (dev->can_read()) {
1371       Mmsg(jcr->errmsg, _("3603 JobId=%u device %s is busy reading.\n"), 
1372          jcr->JobId, dev->print_name());
1373       Dmsg2(dbglvl, "jid=%u %s", jid(), jcr->errmsg);
1374       queue_reserve_message(jcr);
1375       goto bail_out;
1376    }
1377
1378    /* If device is unmounted, we are out of luck */
1379    if (is_device_unmounted(dev)) {
1380       Mmsg(jcr->errmsg, _("3604 JobId=%u device %s is BLOCKED due to user unmount.\n"), 
1381          jcr->JobId, dev->print_name());
1382       Dmsg2(dbglvl, "jid=%u %s", jid(), jcr->errmsg);
1383       queue_reserve_message(jcr);
1384       goto bail_out;
1385    }
1386
1387    Dmsg2(dbglvl, "jid=%u reserve_append device is %s\n", jid(), dev->print_name());
1388
1389    /* Now do detailed tests ... */
1390    if (can_reserve_drive(dcr, rctx) != 1) {
1391       Dmsg1(dbglvl, "jid=%u can_reserve_drive!=1\n", (int)jcr->JobId);
1392       goto bail_out;
1393    }
1394
1395    dcr->set_reserved();
1396    ok = true;
1397
1398 bail_out:
1399    dev->dunlock();
1400    return ok;
1401 }
1402
1403 static int is_pool_ok(DCR *dcr)
1404 {
1405    DEVICE *dev = dcr->dev;
1406    JCR *jcr = dcr->jcr;
1407
1408    /* Now check if we want the same Pool and pool type */
1409    if (strcmp(dev->pool_name, dcr->pool_name) == 0 &&
1410        strcmp(dev->pool_type, dcr->pool_type) == 0) {
1411       /* OK, compatible device */
1412       Dmsg1(dbglvl, "OK dev: %s num_writers=0, reserved, pool matches\n", dev->print_name());
1413       return 1;
1414    } else {
1415       /* Drive Pool not suitable for us */
1416       Mmsg(jcr->errmsg, _(
1417 "3608 JobId=%u wants Pool=\"%s\" but have Pool=\"%s\" nreserve=%d on drive %s.\n"), 
1418             (uint32_t)jcr->JobId, dcr->pool_name, dev->pool_name,
1419             dev->num_reserved(), dev->print_name());
1420       queue_reserve_message(jcr);
1421       Dmsg2(dbglvl, "failed: busy num_writers=0, reserved, pool=%s wanted=%s\n",
1422          dev->pool_name, dcr->pool_name);
1423    }
1424    return 0;
1425 }
1426
1427 static bool is_max_jobs_ok(DCR *dcr) 
1428 {
1429    DEVICE *dev = dcr->dev;
1430    JCR *jcr = dcr->jcr;
1431
1432    Dmsg5(dbglvl, "MaxJobs=%d Jobs=%d reserves=%d Status=%s Vol=%s\n",
1433          dcr->VolCatInfo.VolCatMaxJobs,
1434          dcr->VolCatInfo.VolCatJobs, dev->num_reserved(),
1435          dcr->VolCatInfo.VolCatStatus,
1436          dcr->VolumeName);
1437    if (strcmp(dcr->VolCatInfo.VolCatStatus, "Recycle") == 0) {
1438       return true;
1439    }
1440    if (dcr->VolCatInfo.VolCatMaxJobs > 0 && dcr->VolCatInfo.VolCatMaxJobs <=
1441         (dcr->VolCatInfo.VolCatJobs + dev->num_reserved())) {
1442       /* Max Job Vols depassed or already reserved */
1443       Mmsg(jcr->errmsg, _("3610 JobId=%u Volume max jobs exceeded on drive %s.\n"), 
1444             (uint32_t)jcr->JobId, dev->print_name());
1445       queue_reserve_message(jcr);
1446       Dmsg1(dbglvl, "reserve dev failed: %s", jcr->errmsg);
1447       return false;                /* wait */
1448    }
1449    return true;
1450 }
1451
1452 /*
1453  * Returns: 1 if drive can be reserved
1454  *          0 if we should wait
1455  *         -1 on error or impossibility
1456  */
1457 static int can_reserve_drive(DCR *dcr, RCTX &rctx) 
1458 {
1459    DEVICE *dev = dcr->dev;
1460    JCR *jcr = dcr->jcr;
1461
1462    Dmsg6(dbglvl, "jid=%u PrefMnt=%d exact=%d suitable=%d chgronly=%d any=%d\n",
1463          (int)jcr->JobId,
1464          rctx.PreferMountedVols, rctx.exact_match, rctx.suitable_device,
1465          rctx.autochanger_only, rctx.any_drive);
1466
1467    /* Check for max jobs on this Volume */
1468    if (!is_max_jobs_ok(dcr)) {
1469       return 0;
1470    }
1471
1472    /* setting any_drive overrides PreferMountedVols flag */
1473    if (!rctx.any_drive) {
1474       /*
1475        * When PreferMountedVols is set, we keep track of the 
1476        *  drive in use that has the least number of writers, then if
1477        *  no unmounted drive is found, we try that drive. This   
1478        *  helps spread the load to the least used drives.  
1479        */
1480       if (rctx.try_low_use_drive && dev == rctx.low_use_drive) {
1481          Dmsg3(dbglvl, "jid=%u OK dev=%s == low_drive=%s.\n",
1482             jcr->JobId, dev->print_name(), rctx.low_use_drive->print_name());
1483          return 1;
1484       }
1485       /* If he wants a free drive, but this one is busy, no go */
1486       if (!rctx.PreferMountedVols && dev->is_busy()) {
1487          /* Save least used drive */
1488          if ((dev->num_writers + dev->num_reserved()) < rctx.num_writers) {
1489             rctx.num_writers = dev->num_writers + dev->num_reserved();
1490             rctx.low_use_drive = dev;
1491             Dmsg3(dbglvl, "jid=%u set low use drive=%s num_writers=%d\n", 
1492                (int)jcr->JobId, dev->print_name(), rctx.num_writers);
1493          } else {
1494             Dmsg2(dbglvl, "jid=%u not low use num_writers=%d\n", 
1495                (int)jcr->JobId, dev->num_writers+dev->num_reserved());
1496          }
1497          Dmsg1(dbglvl, "jid=%u failed: !prefMnt && busy.\n", jcr->JobId);
1498          Mmsg(jcr->errmsg, _("3605 JobId=%u wants free drive but device %s is busy.\n"), 
1499             jcr->JobId, dev->print_name());
1500          queue_reserve_message(jcr);
1501          return 0;
1502       }
1503
1504       /* Check for prefer mounted volumes */
1505       if (rctx.PreferMountedVols && !dev->vol && dev->is_tape()) {
1506          Mmsg(jcr->errmsg, _("3606 JobId=%u prefers mounted drives, but drive %s has no Volume.\n"), 
1507             jcr->JobId, dev->print_name());
1508          queue_reserve_message(jcr);
1509          Dmsg1(dbglvl, "jid=%u failed: want mounted -- no vol\n", (uint32_t)jcr->JobId);
1510          return 0;                 /* No volume mounted */
1511       }
1512
1513       /* Check for exact Volume name match */
1514       /* ***FIXME*** for Disk, we can accept any volume that goes with this
1515        *    drive.
1516        */
1517       if (rctx.exact_match && rctx.have_volume) {
1518          bool ok;
1519          Dmsg6(dbglvl, "jid=%u PrefMnt=%d exact=%d suitable=%d chgronly=%d any=%d\n",
1520                (int)jcr->JobId,
1521                rctx.PreferMountedVols, rctx.exact_match, rctx.suitable_device,
1522                rctx.autochanger_only, rctx.any_drive);
1523          Dmsg5(dbglvl, "jid=%u have_vol=%d have=%s resvol=%s want=%s\n",
1524                   (int)jcr->JobId, rctx.have_volume, dev->VolHdr.VolumeName, 
1525                   dev->vol?dev->vol->vol_name:"*none*", rctx.VolumeName);
1526          ok = strcmp(dev->VolHdr.VolumeName, rctx.VolumeName) == 0 ||
1527                  (dev->vol && strcmp(dev->vol->vol_name, rctx.VolumeName) == 0);
1528          if (!ok) {
1529             Mmsg(jcr->errmsg, _("3607 JobId=%u wants Vol=\"%s\" drive has Vol=\"%s\" on drive %s.\n"), 
1530                jcr->JobId, rctx.VolumeName, dev->VolHdr.VolumeName, 
1531                dev->print_name());
1532             queue_reserve_message(jcr);
1533             Dmsg4(dbglvl, "jid=%u not OK: dev have=%s resvol=%s want=%s\n", (int)jcr->JobId,
1534                   dev->VolHdr.VolumeName, dev->vol?dev->vol->vol_name:"*none*", rctx.VolumeName);
1535             return 0;
1536          }
1537          if (!dcr->can_i_use_volume()) {
1538             return 0;              /* fail if volume on another drive */
1539          }
1540       }
1541    }
1542
1543    /* Check for unused autochanger drive */
1544    if (rctx.autochanger_only && !dev->is_busy() &&
1545        dev->VolHdr.VolumeName[0] == 0) {
1546       /* Device is available but not yet reserved, reserve it for us */
1547       Dmsg2(dbglvl, "jid=%u OK Res Unused autochanger %s.\n",
1548          jcr->JobId, dev->print_name());
1549       bstrncpy(dev->pool_name, dcr->pool_name, sizeof(dev->pool_name));
1550       bstrncpy(dev->pool_type, dcr->pool_type, sizeof(dev->pool_type));
1551       return 1;                       /* reserve drive */
1552    }
1553
1554    /*
1555     * Handle the case that there are no writers
1556     */
1557    if (dev->num_writers == 0) {
1558       /* Now check if there are any reservations on the drive */
1559       if (dev->num_reserved()) {           
1560          return is_pool_ok(dcr);
1561       } else if (dev->can_append()) {
1562          if (is_pool_ok(dcr)) {
1563             return 1; 
1564          } else {
1565             /* Changing pool, unload old tape if any in drive */
1566             Dmsg1(dbglvl, "jid=%u OK dev: num_writers=0, not reserved, pool change, unload changer\n", (int)jcr->JobId);
1567             /* ***FIXME*** use set_unload() */
1568             unload_autochanger(dcr, -1);
1569          }
1570       }
1571       /* Device is available but not yet reserved, reserve it for us */
1572       Dmsg2(dbglvl, "jid=%u OK Dev avail reserved %s\n", (int)jcr->JobId, dev->print_name());
1573       bstrncpy(dev->pool_name, dcr->pool_name, sizeof(dev->pool_name));
1574       bstrncpy(dev->pool_type, dcr->pool_type, sizeof(dev->pool_type));
1575       return 1;                       /* reserve drive */
1576    }
1577
1578    /*
1579     * Check if the device is in append mode with writers (i.e.
1580     *  available if pool is the same).
1581     */
1582    if (dev->can_append() || dev->num_writers > 0) {
1583       return is_pool_ok(dcr);
1584    } else {
1585       Pmsg1(000, _("Logic error!!!! JobId=%u Should not get here.\n"), (int)jcr->JobId);
1586       Mmsg(jcr->errmsg, _("3910 JobId=%u Logic error!!!! drive %s Should not get here.\n"),
1587             jcr->JobId, dev->print_name());
1588       queue_reserve_message(jcr);
1589       Jmsg0(jcr, M_FATAL, 0, _("Logic error!!!! Should not get here.\n"));
1590       return -1;                      /* error, should not get here */
1591    }
1592    Mmsg(jcr->errmsg, _("3911 JobId=%u failed reserve drive %s.\n"), 
1593          jcr->JobId, dev->print_name());
1594    queue_reserve_message(jcr);
1595    Dmsg2(dbglvl, "jid=%u failed: No reserve %s\n", jcr->JobId, dev->print_name());
1596    return 0;
1597 }
1598
1599
1600
1601
1602 /*
1603  * Queue a reservation error or failure message for this jcr
1604  */
1605 static void queue_reserve_message(JCR *jcr)
1606 {
1607    int i;   
1608    alist *msgs;
1609    char *msg;
1610
1611    jcr->lock();
1612
1613    msgs = jcr->reserve_msgs;
1614    if (!msgs) {
1615       goto bail_out;
1616    }
1617    /*
1618     * Look for duplicate message.  If found, do
1619     * not insert
1620     */
1621    for (i=msgs->size()-1; i >= 0; i--) {
1622       msg = (char *)msgs->get(i);
1623       if (!msg) {
1624          goto bail_out;
1625       }
1626       /* Comparison based on 4 digit message number */
1627       if (strncmp(msg, jcr->errmsg, 4) == 0) {
1628          goto bail_out;
1629       }
1630    }      
1631    /* Message unique, so insert it */
1632    jcr->reserve_msgs->push(bstrdup(jcr->errmsg));
1633
1634 bail_out:
1635    jcr->unlock();
1636 }
1637
1638 /*
1639  * Send any reservation messages queued for this jcr
1640  */
1641 void send_drive_reserve_messages(JCR *jcr, void sendit(const char *msg, int len, void *sarg), void *arg)
1642 {
1643    int i;
1644    alist *msgs;
1645    char *msg;
1646
1647    jcr->lock();
1648    msgs = jcr->reserve_msgs;
1649    if (!msgs || msgs->size() == 0) {
1650       goto bail_out;
1651    }
1652    for (i=msgs->size()-1; i >= 0; i--) {
1653       msg = (char *)msgs->get(i);
1654       if (msg) {
1655          sendit("   ", 3, arg);
1656          sendit(msg, strlen(msg), arg);
1657       } else {
1658          break;
1659       }
1660    }
1661
1662 bail_out:
1663    jcr->unlock();
1664 }
1665
1666 /*
1667  * Pop and release any reservations messages
1668  */
1669 static void pop_reserve_messages(JCR *jcr)
1670 {
1671    alist *msgs;
1672    char *msg;
1673
1674    jcr->lock();
1675    msgs = jcr->reserve_msgs;
1676    if (!msgs) {
1677       goto bail_out;
1678    }
1679    while ((msg = (char *)msgs->pop())) {
1680       free(msg);
1681    }
1682 bail_out:
1683    jcr->unlock();
1684 }
1685
1686 /*
1687  * Also called from acquire.c 
1688  */
1689 void release_reserve_messages(JCR *jcr)
1690 {
1691    pop_reserve_messages(jcr);
1692    jcr->lock();
1693    if (!jcr->reserve_msgs) {
1694       goto bail_out;
1695    }
1696    delete jcr->reserve_msgs;
1697    jcr->reserve_msgs = NULL;
1698
1699 bail_out:
1700    jcr->unlock();
1701 }