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