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