]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/stored/reserve.c
Fix possible seg fault in SD when freeing a volume entry.
[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    if (dcr->reserved_device) {
468       dcr->reserved_device = false;
469       dev->reserved_device--;
470       Dmsg3(dbglvl, "jid=%u Dec reserve=%d dev=%s\n", jid(), dev->reserved_device, dev->print_name());
471       dcr->reserved_device = false;
472       /* If we set read mode in reserving, remove it */
473       if (dev->can_read()) {
474          dev->clear_read();
475       }
476       if (dev->num_writers < 0) {
477          Jmsg1(dcr->jcr, M_ERROR, 0, _("Hey! num_writers=%d!!!!\n"), dev->num_writers);
478          dev->num_writers = 0;
479       }
480       if (dev->reserved_device == 0 && dev->num_writers == 0) {
481          volume_unused(dcr);
482       }
483    }
484 }
485
486 /*  
487  * Free a Volume from the Volume list if it is no longer used
488  *   Note, for tape drives we want to remember where the Volume
489  *   was when last used, so rather than free the volume entry,
490  *   we simply mark it "released" so when the drive is really
491  *   needed for another volume, we can reuse it.
492  *
493  *  Returns: true if the Volume found and "removed" from the list
494  *           false if the Volume is not in the list or is in use
495  */
496 bool volume_unused(DCR *dcr)
497 {
498    DEVICE *dev = dcr->dev;
499
500    if (dev->vol == NULL) {
501       Dmsg2(dbglvl, "jid=%u vol_unused: no vol on %s\n", (int)dcr->jcr->JobId, dev->print_name());
502       debug_list_volumes("null vol cannot unreserve_volume");
503       return false;
504    }
505
506 #ifdef xxx
507    if (dev->is_busy()) {
508       Dmsg2(dbglvl, "jid=%u vol_unused: no vol on %s\n", (int)dcr->jcr->JobId, dev->print_name());
509       debug_list_volumes("dev busy cannot unreserve_volume");
510       return false;
511    }
512 #endif
513 #ifdef xxx
514    if (dev->num_writers > 0 || dev->reserved_device > 0) {
515       ASSERT(0);
516    }
517 #endif
518
519    /*  
520     * If this is a tape, we do not free the volume, rather we wait
521     *  until the autoloader unloads it, or until another tape is
522     *  explicitly read in this drive. This allows the SD to remember
523     *  where the tapes are or last were.
524     */
525    dev->vol->released = true;
526    if (dev->is_tape() || dev->is_autochanger()) {
527       return true;
528    } else {
529       /*
530        * Note, this frees the volume reservation entry, but the
531        *   file descriptor remains open with the OS.
532        */
533       return free_volume(dev);
534    }
535 }
536
537 /*
538  * Unconditionally release the volume entry
539  */
540 bool free_volume(DEVICE *dev)
541 {
542    VOLRES *vol;
543
544    if (dev->vol == NULL) {
545       Dmsg2(dbglvl, "jid=%u No vol on dev %s\n", jid(), dev->print_name());
546       return false;
547    }
548    lock_volumes();
549    vol = dev->vol;
550    dev->vol = NULL;
551    vol_list->remove(vol);
552    Dmsg3(dbglvl, "jid=%u free_volume %s dev=%s\n", jid(), vol->vol_name, dev->print_name());
553    free_vol_item(vol);
554    debug_list_volumes("free_volume");
555    unlock_volumes();
556    return vol != NULL;
557 }
558
559       
560 /* Create the Volume list */
561 void create_volume_list()
562 {
563    VOLRES *vol = NULL;
564    if (vol_list == NULL) {
565       vol_list = New(dlist(vol, &vol->link));
566    }
567 }
568
569 /* Release all Volumes from the list */
570 void free_volume_list()
571 {
572    VOLRES *vol;
573    if (!vol_list) {
574       return;
575    }
576    lock_volumes();
577    foreach_dlist(vol, vol_list) {
578       if (vol->dev) {
579          Dmsg3(dbglvl, "jid=%u free vol_list Volume=%s dev=%s\n", jid(),
580                vol->vol_name, vol->dev->print_name());
581       } else {
582          Dmsg3(dbglvl, "jid=%u free vol_list Volume=%s dev=%p\n", jid(), 
583                vol->vol_name, vol->dev);
584       }
585       free(vol->vol_name);
586       vol->vol_name = NULL;
587    }
588    delete vol_list;
589    vol_list = NULL;
590    unlock_volumes();
591 }
592
593 bool is_volume_in_use(DCR *dcr)
594 {
595    bool rtn = false;
596    VOLRES *vol;
597
598    lock_volumes();
599    vol = find_volume(dcr);
600    if (!vol) {
601       Dmsg2(dbglvl, "jid=%u Vol=%s not in use.\n", jid(), dcr->VolumeName);
602       goto get_out;                   /* vol not in list */
603    }
604    ASSERT(vol->dev != NULL);
605
606    if (dcr->dev == vol->dev) {        /* same device OK */
607       Dmsg2(dbglvl, "jid=%u Vol=%s on same dev.\n", jid(), dcr->VolumeName);
608       goto get_out;
609    } else {
610       Dmsg4(dbglvl, "jid=%u Vol=%s on %s we have %s\n", jid(), dcr->VolumeName,
611             vol->dev->print_name(), dcr->dev->print_name());
612    }
613    if (!vol->dev->is_busy()) {
614       Dmsg3(dbglvl, "jid=%u Vol=%s dev=%s not busy.\n", jid(), dcr->VolumeName, vol->dev->print_name());
615       goto get_out;
616    } else {
617       Dmsg3(dbglvl, "jid=%u Vol=%s dev=%s busy.\n", jid(), dcr->VolumeName, vol->dev->print_name());
618    }
619    Dmsg3(dbglvl, "jid=%u Vol=%s in use by %s.\n", jid(), dcr->VolumeName, vol->dev->print_name());
620    rtn = true;
621
622 get_out:
623    unlock_volumes();
624    return rtn;
625 }
626
627
628 /*
629  * We get the following type of information:
630  *
631  * use storage=xxx media_type=yyy pool_name=xxx pool_type=yyy append=1 copy=0 strip=0
632  *  use device=zzz
633  *  use device=aaa
634  *  use device=bbb
635  * use storage=xxx media_type=yyy pool_name=xxx pool_type=yyy append=0 copy=0 strip=0
636  *  use device=bbb
637  *
638  */
639 static bool use_storage_cmd(JCR *jcr)
640 {
641    POOL_MEM store_name, dev_name, media_type, pool_name, pool_type;
642    BSOCK *dir = jcr->dir_bsock;
643    int append;
644    bool ok;       
645    int Copy, Stripe;
646    DIRSTORE *store;
647    RCTX rctx;
648    alist *dirstore;
649
650    memset(&rctx, 0, sizeof(RCTX));
651    rctx.jcr = jcr;
652    /*
653     * If there are multiple devices, the director sends us
654     *   use_device for each device that it wants to use.
655     */
656    dirstore = New(alist(10, not_owned_by_alist));
657    jcr->reserve_msgs = New(alist(10, not_owned_by_alist));  
658    do {
659       Dmsg2(dbglvl, "jid=%u <dird: %s", jid(), dir->msg);
660       ok = sscanf(dir->msg, use_storage, store_name.c_str(), 
661                   media_type.c_str(), pool_name.c_str(), 
662                   pool_type.c_str(), &append, &Copy, &Stripe) == 7;
663       if (!ok) {
664          break;
665       }
666       if (append) {
667          jcr->write_store = dirstore;
668       } else {
669          jcr->read_store = dirstore;
670       }
671       rctx.append = append;
672       unbash_spaces(store_name);
673       unbash_spaces(media_type);
674       unbash_spaces(pool_name);
675       unbash_spaces(pool_type);
676       store = new DIRSTORE;
677       dirstore->append(store);
678       memset(store, 0, sizeof(DIRSTORE));
679       store->device = New(alist(10));
680       bstrncpy(store->name, store_name, sizeof(store->name));
681       bstrncpy(store->media_type, media_type, sizeof(store->media_type));
682       bstrncpy(store->pool_name, pool_name, sizeof(store->pool_name));
683       bstrncpy(store->pool_type, pool_type, sizeof(store->pool_type));
684       store->append = append;
685
686       /* Now get all devices */
687       while (dir->recv() >= 0) {
688          Dmsg2(dbglvl, "jid=%u <dird device: %s", jid(), dir->msg);
689          ok = sscanf(dir->msg, use_device, dev_name.c_str()) == 1;
690          if (!ok) {
691             break;
692          }
693          unbash_spaces(dev_name);
694          store->device->append(bstrdup(dev_name.c_str()));
695       }
696    }  while (ok && dir->recv() >= 0);
697
698    /* Developer debug code */
699    char *device_name;
700    if (debug_level >= dbglvl) {
701       foreach_alist(store, dirstore) {
702          Dmsg6(dbglvl, "jid=%u Storage=%s media_type=%s pool=%s pool_type=%s append=%d\n", 
703             (int)rctx.jcr->JobId,
704             store->name, store->media_type, store->pool_name, 
705             store->pool_type, store->append);
706          foreach_alist(device_name, store->device) {
707             Dmsg2(dbglvl, "jid=%u     Device=%s\n", jid(), device_name);
708          }
709       }
710    }
711
712    init_jcr_device_wait_timers(jcr);
713    jcr->dcr = new_dcr(jcr, NULL, NULL);         /* get a dcr */
714    if (!jcr->dcr) {
715       BSOCK *dir = jcr->dir_bsock;
716       dir->fsend(_("3939 Could not get dcr\n"));
717       Dmsg1(dbglvl, ">dird: %s", dir->msg);
718       ok = false;
719    }
720    /*                    
721     * At this point, we have a list of all the Director's Storage
722     *  resources indicated for this Job, which include Pool, PoolType,
723     *  storage name, and Media type.     
724     * Then for each of the Storage resources, we have a list of
725     *  device names that were given.
726     *
727     * Wiffle through them and find one that can do the backup.
728     */
729    if (ok) {
730       int wait_for_device_retries = 0;  
731       int repeat = 0;
732       bool fail = false;
733       rctx.notify_dir = true;
734
735       lock_reservations();
736       for ( ; !fail && !job_canceled(jcr); ) {
737          pop_reserve_messages(jcr);
738          rctx.suitable_device = false;
739          rctx.have_volume = false;
740          rctx.VolumeName[0] = 0;
741          rctx.any_drive = false;
742          if (!jcr->PreferMountedVols) {
743             /*
744              * Here we try to find a drive that is not used.
745              * This will maximize the use of available drives.
746              *
747              */
748             rctx.num_writers = 20000000;   /* start with impossible number */
749             rctx.low_use_drive = NULL;
750             rctx.PreferMountedVols = false;                
751             rctx.exact_match = false;
752             rctx.autochanger_only = true;
753             Dmsg6(dbglvl, "jid=%u PrefMnt=%d exact=%d suitable=%d chgronly=%d any=%d\n",
754                (int)rctx.jcr->JobId,
755                rctx.PreferMountedVols, rctx.exact_match, rctx.suitable_device,
756                rctx.autochanger_only, rctx.any_drive);
757             if ((ok = find_suitable_device_for_job(jcr, rctx))) {
758                break;
759             }
760             /* Look through all drives possibly for low_use drive */
761             if (rctx.low_use_drive) {
762                rctx.try_low_use_drive = true;
763                if ((ok = find_suitable_device_for_job(jcr, rctx))) {
764                   break;
765                }
766                rctx.try_low_use_drive = false;
767             }
768             rctx.autochanger_only = false;
769             Dmsg6(dbglvl, "jid=%u PrefMnt=%d exact=%d suitable=%d chgronly=%d any=%d\n",
770                (int)rctx.jcr->JobId,
771                rctx.PreferMountedVols, rctx.exact_match, rctx.suitable_device,
772                rctx.autochanger_only, rctx.any_drive);
773             if ((ok = find_suitable_device_for_job(jcr, rctx))) {
774                break;
775             }
776          }
777          /*
778           * Now we look for a drive that may or may not be in
779           *  use.
780           */
781          /* Look for an exact Volume match all drives */
782          rctx.PreferMountedVols = true;
783          rctx.exact_match = true;
784          rctx.autochanger_only = false;
785          Dmsg6(dbglvl, "jid=%u PrefMnt=%d exact=%d suitable=%d chgronly=%d any=%d\n",
786             (int)rctx.jcr->JobId,
787             rctx.PreferMountedVols, rctx.exact_match, rctx.suitable_device,
788             rctx.autochanger_only, rctx.any_drive);
789          if ((ok = find_suitable_device_for_job(jcr, rctx))) {
790             break;
791          }
792          /* Look for any mounted drive */
793          rctx.exact_match = false;
794          Dmsg6(dbglvl, "jid=%u PrefMnt=%d exact=%d suitable=%d chgronly=%d any=%d\n",
795             (int)rctx.jcr->JobId,
796             rctx.PreferMountedVols, rctx.exact_match, rctx.suitable_device,
797             rctx.autochanger_only, rctx.any_drive);
798          if ((ok = find_suitable_device_for_job(jcr, rctx))) {
799             break;
800          }
801          /* Try any drive */
802          rctx.any_drive = true;
803          Dmsg6(dbglvl, "jid=%u PrefMnt=%d exact=%d suitable=%d chgronly=%d any=%d\n",
804             (int)rctx.jcr->JobId,
805             rctx.PreferMountedVols, rctx.exact_match, rctx.suitable_device,
806             rctx.autochanger_only, rctx.any_drive);
807          if ((ok = find_suitable_device_for_job(jcr, rctx))) {
808             break;
809          }
810          /* Keep reservations locked *except* during wait_for_device() */
811          unlock_reservations();
812          /*     
813           * The idea of looping on repeat a few times it to ensure
814           * that if there is some subtle timing problem between two
815           * jobs, we will simply try again, and most likely succeed.
816           * This can happen if one job reserves a drive or finishes using
817           * a drive at the same time a second job wants it.
818           */
819          if (repeat++ > 1) {              /* try algorithm 3 times */
820             bmicrosleep(30, 0);           /* wait a bit */
821             Dmsg1(dbglvl, "jid=%u repeat reserve algorithm\n", (int)rctx.jcr->JobId);
822          } else if (!rctx.suitable_device || !wait_for_device(jcr, wait_for_device_retries)) {
823             Dmsg1(dbglvl, "jid=%u Fail. !suitable_device || !wait_for_device\n",
824                  (int)rctx.jcr->JobId);
825             fail = true;
826          }   
827          lock_reservations();
828          dir->signal(BNET_HEARTBEAT);  /* Inform Dir that we are alive */
829       }
830       unlock_reservations();
831       if (!ok) {
832          /*
833           * If we get here, there are no suitable devices available, which
834           *  means nothing configured.  If a device is suitable but busy
835           *  with another Volume, we will not come here.
836           */
837          unbash_spaces(dir->msg);
838          pm_strcpy(jcr->errmsg, dir->msg);
839          Jmsg(jcr, M_INFO, 0, _("Failed command: %s\n"), jcr->errmsg);
840          Jmsg(jcr, M_FATAL, 0, _("\n"
841             "     Device \"%s\" with MediaType \"%s\" requested by DIR not found in SD Device resources.\n"),
842               dev_name.c_str(), media_type.c_str());
843          dir->fsend(NO_device, dev_name.c_str());
844
845          Dmsg2(dbglvl, "jid=%u >dird: %s", jid(), dir->msg);
846       }
847    } else {
848       unbash_spaces(dir->msg);
849       pm_strcpy(jcr->errmsg, dir->msg);
850       Jmsg(jcr, M_FATAL, 0, _("Failed command: %s\n"), jcr->errmsg);
851       dir->fsend(BAD_use, jcr->errmsg);
852       Dmsg2(dbglvl, "jid=%u >dird: %s", jid(), dir->msg);
853    }
854
855    release_reserve_messages(jcr);
856    return ok;
857 }
858
859
860 /*
861  * Walk through the autochanger resources and check if
862  *  the volume is in one of them.
863  * 
864  * Returns:  true  if volume is in device
865  *           false otherwise
866  */
867 static bool is_vol_in_autochanger(RCTX &rctx, VOLRES *vol)
868 {
869    AUTOCHANGER *changer = vol->dev->device->changer_res;
870
871    /* Find resource, and make sure we were able to open it */
872    if (strcmp(rctx.device_name, changer->hdr.name) == 0) {
873       Dmsg2(dbglvl, "jid=%u Found changer device %s\n",
874                      (int)rctx.jcr->JobId, vol->dev->device->hdr.name);
875       return true;
876    }  
877    Dmsg2(dbglvl, "jid=%u Incorrect changer device %s\n", 
878                   (int)rctx.jcr->JobId, changer->hdr.name);
879    return false;
880 }
881
882 /*
883  * Search for a device suitable for this job.
884  */
885 bool find_suitable_device_for_job(JCR *jcr, RCTX &rctx)
886 {
887    bool ok = false;
888    DIRSTORE *store;
889    char *device_name;
890    alist *dirstore;
891    DCR *dcr = jcr->dcr;
892
893    if (rctx.append) {
894       dirstore = jcr->write_store;
895    } else {
896       dirstore = jcr->read_store;
897    }
898    Dmsg5(dbglvl, "jid=%u PrefMnt=%d exact=%d suitable=%d chgronly=%d\n",
899       (int)rctx.jcr->JobId,
900       rctx.PreferMountedVols, rctx.exact_match, rctx.suitable_device,
901       rctx.autochanger_only);
902
903    /* 
904     * If the appropriate conditions of this if are met, namely that
905     *  we are appending and the user wants mounted drive (or we
906     *  force try a mounted drive because they are all busy), we
907     *  start by looking at all the Volumes in the volume list.
908     */
909    if (!vol_list->empty() && rctx.append && rctx.PreferMountedVols) {
910       dlist *temp_vol_list, *save_vol_list;
911       VOLRES *vol = NULL;
912       lock_volumes();
913       Dmsg0(dbglvl, "lock volumes\n");                           
914
915       /*  
916        * Create a temporary copy of the volume list.  We do this,
917        *   to avoid having the volume list locked during the
918        *   call to reserve_device(), which would cause a deadlock.
919        * Note, we may want to add an update counter on the vol_list
920        *   so that if it is modified while we are traversing the copy
921        *   we can take note and act accordingly (probably redo the 
922        *   search at least a few times).
923        */
924       Dmsg1(dbglvl, "jid=%u duplicate vol list\n", (int)rctx.jcr->JobId);
925       temp_vol_list = New(dlist(vol, &vol->link));
926       foreach_dlist(vol, vol_list) {
927          VOLRES *nvol;
928          VOLRES *tvol = (VOLRES *)malloc(sizeof(VOLRES));
929          memset(tvol, 0, sizeof(VOLRES));
930          tvol->vol_name = bstrdup(vol->vol_name);
931          tvol->dev = vol->dev;
932          nvol = (VOLRES *)temp_vol_list->binary_insert(tvol, my_compare);
933          if (tvol != nvol) {
934             tvol->dev = NULL;                   /* don't zap dev entry */
935             free_vol_item(tvol);
936             Pmsg0(000, "Logic error. Duplicating vol list hit duplicate.\n");
937             Jmsg(jcr, M_WARNING, 0, "Logic error. Duplicating vol list hit duplicate.\n");
938          }
939       }
940       unlock_volumes();
941
942       /* Look through reserved volumes for one we can use */
943       Dmsg1(dbglvl, "jid=%u look for vol in vol list\n", (int)rctx.jcr->JobId);
944       foreach_dlist(vol, temp_vol_list) {
945          if (!vol->dev) {
946             Dmsg2(dbglvl, "jid=%u vol=%s no dev\n", (int)rctx.jcr->JobId, vol->vol_name);
947             continue;
948          }
949          /* Check with Director if this Volume is OK */
950          bstrncpy(dcr->VolumeName, vol->vol_name, sizeof(dcr->VolumeName));
951          if (!dir_get_volume_info(dcr, GET_VOL_INFO_FOR_WRITE)) {
952             continue;
953          }
954
955          Dmsg2(dbglvl, "jid=%u vol=%s OK for this job\n", (int)rctx.jcr->JobId, vol->vol_name);
956          foreach_alist(store, dirstore) {
957             int stat;
958             rctx.store = store;
959             foreach_alist(device_name, store->device) {
960                /* Found a device, try to use it */
961                rctx.device_name = device_name;
962                rctx.device = vol->dev->device;
963
964                if (vol->dev->is_autochanger()) {
965                   Dmsg2(dbglvl, "jid=%u vol=%s is in changer\n", (int)rctx.jcr->JobId, 
966                         vol->vol_name);
967                   if (!is_vol_in_autochanger(rctx, vol)) {
968                      continue;
969                   }
970                } else if (strcmp(device_name, vol->dev->device->hdr.name) != 0) {
971                   Dmsg3(dbglvl, "jid=%u device=%s not suitable want %s\n", (int)rctx.jcr->JobId, 
972                         vol->dev->device->hdr.name, device_name);
973                   continue;
974                }
975
976                bstrncpy(rctx.VolumeName, vol->vol_name, sizeof(rctx.VolumeName));
977                rctx.have_volume = true;
978                /* Try reserving this device and volume */
979                Dmsg3(dbglvl, "jid=%u try vol=%s on device=%s\n", (int)rctx.jcr->JobId, 
980                      rctx.VolumeName, device_name);
981                stat = reserve_device(rctx);
982                if (stat == 1) {             /* found available device */
983                   Dmsg2(dbglvl, "jid=%u Suitable device found=%s\n", (int)rctx.jcr->JobId, 
984                         device_name);
985                   ok = true;
986                   break;
987                } else if (stat == 0) {      /* device busy */
988                   Dmsg2(dbglvl, "jid=%u Suitable device=%s, busy: not use\n", 
989                         (int)rctx.jcr->JobId, device_name);
990                } else {
991                   /* otherwise error */
992                   Dmsg1(dbglvl, "jid=%u No suitable device found.\n", (int)rctx.jcr->JobId);
993                }
994                rctx.have_volume = false;
995                rctx.VolumeName[0] = 0;
996             }
997             if (ok) {
998                break;
999             }
1000          }
1001          if (ok) {
1002             break;
1003          }
1004       } /* end for loop over reserved volumes */
1005
1006       Dmsg1(dbglvl, "%u lock volumes\n", jid());
1007       lock_volumes();
1008       save_vol_list = vol_list;
1009       vol_list = temp_vol_list;
1010       free_volume_list();                  /* release temp_vol_list */
1011       vol_list = save_vol_list;
1012       Dmsg1(dbglvl, "jid=%u deleted temp vol list\n", (int)rctx.jcr->JobId);
1013       Dmsg1(dbglvl, "jid=%u unlock volumes\n", (int)rctx.jcr->JobId);
1014       unlock_volumes();
1015    }
1016    if (ok) {
1017       Dmsg2(dbglvl, "jid=%u got vol %s from in-use vols list\n", (int)rctx.jcr->JobId,
1018             rctx.VolumeName);
1019       return true;
1020    }
1021
1022    /* 
1023     * No reserved volume we can use, so now search for an available device.  
1024     *
1025     * For each storage device that the user specified, we
1026     *  search and see if there is a resource for that device.
1027     */
1028    foreach_alist(store, dirstore) {
1029       rctx.store = store;
1030       foreach_alist(device_name, store->device) {
1031          int stat;
1032          rctx.device_name = device_name;
1033          stat = search_res_for_device(rctx); 
1034          if (stat == 1) {             /* found available device */
1035             Dmsg2(dbglvl, "jid=%u available device found=%s\n", (int)rctx.jcr->JobId, 
1036                   device_name);
1037             ok = true;
1038             break;
1039          } else if (stat == 0) {      /* device busy */
1040             Dmsg2(dbglvl, "jid=%u Suitable device=%s, busy: not use\n", 
1041                   (int)rctx.jcr->JobId, device_name);
1042          } else {
1043             /* otherwise error */
1044             Dmsg1(dbglvl, "jid=%u No suitable device found.\n", (int)rctx.jcr->JobId);
1045          }
1046       }
1047       if (ok) {
1048          break;
1049       }
1050    }
1051    return ok;
1052 }
1053
1054 /*
1055  * Search for a particular storage device with particular storage
1056  *  characteristics (MediaType).
1057  */
1058 int search_res_for_device(RCTX &rctx) 
1059 {
1060    AUTOCHANGER *changer;
1061    int stat;
1062
1063    Dmsg2(dbglvl, "jid=%u search res for %s\n", (int)rctx.jcr->JobId, rctx.device_name);
1064    /* Look through Autochangers first */
1065    foreach_res(changer, R_AUTOCHANGER) {
1066       Dmsg2(dbglvl, "jid=%u Try match changer res=%s\n", (int)rctx.jcr->JobId, changer->hdr.name);
1067       /* Find resource, and make sure we were able to open it */
1068       if (strcmp(rctx.device_name, changer->hdr.name) == 0) {
1069          /* Try each device in this AutoChanger */
1070          foreach_alist(rctx.device, changer->device) {
1071             Dmsg2(dbglvl, "jid=%u Try changer device %s\n", (int)rctx.jcr->JobId, 
1072                   rctx.device->hdr.name);
1073             stat = reserve_device(rctx);
1074             if (stat != 1) {             /* try another device */
1075                continue;
1076             }
1077             /* Debug code */
1078             if (rctx.store->append == SD_APPEND) {
1079                Dmsg3(dbglvl, "jid=%u Device %s reserved=%d for append.\n", 
1080                   (int)rctx.jcr->JobId, rctx.device->hdr.name,
1081                   rctx.jcr->dcr->dev->reserved_device);
1082             } else {
1083                Dmsg3(dbglvl, "jid=%u Device %s reserved=%d for read.\n", 
1084                   (int)rctx.jcr->JobId, rctx.device->hdr.name,
1085                   rctx.jcr->read_dcr->dev->reserved_device);
1086             }
1087             return stat;
1088          }
1089       }
1090    }
1091
1092    /* Now if requested look through regular devices */
1093    if (!rctx.autochanger_only) {
1094       foreach_res(rctx.device, R_DEVICE) {
1095          Dmsg2(dbglvl, "jid=%u Try match res=%s\n", (int)rctx.jcr->JobId, rctx.device->hdr.name);
1096          /* Find resource, and make sure we were able to open it */
1097          if (strcmp(rctx.device_name, rctx.device->hdr.name) == 0) {
1098             stat = reserve_device(rctx);
1099             if (stat != 1) {             /* try another device */
1100                continue;
1101             }
1102             /* Debug code */
1103             if (rctx.store->append == SD_APPEND) {
1104                Dmsg3(dbglvl, "jid=%u Device %s reserved=%d for append.\n", 
1105                   (int)rctx.jcr->JobId, rctx.device->hdr.name,
1106                   rctx.jcr->dcr->dev->reserved_device);
1107             } else {
1108                Dmsg3(dbglvl, "jid=%u Device %s reserved=%d for read.\n", 
1109                   (int)rctx.jcr->JobId, rctx.device->hdr.name,
1110                   rctx.jcr->read_dcr->dev->reserved_device);
1111             }
1112             return stat;
1113          }
1114       }
1115    }
1116    return -1;                    /* nothing found */
1117 }
1118
1119 /*
1120  *  Try to reserve a specific device.
1121  *
1122  *  Returns: 1 -- OK, have DCR
1123  *           0 -- must wait
1124  *          -1 -- fatal error
1125  */
1126 static int reserve_device(RCTX &rctx)
1127 {
1128    bool ok;
1129    DCR *dcr;
1130    const int name_len = MAX_NAME_LENGTH;
1131
1132    /* Make sure MediaType is OK */
1133    Dmsg3(dbglvl, "jid=%u chk MediaType device=%s request=%s\n",
1134          (int)rctx.jcr->JobId,
1135          rctx.device->media_type, rctx.store->media_type);
1136    if (strcmp(rctx.device->media_type, rctx.store->media_type) != 0) {
1137       return -1;
1138    }
1139
1140    /* Make sure device exists -- i.e. we can stat() it */
1141    if (!rctx.device->dev) {
1142       rctx.device->dev = init_dev(rctx.jcr, rctx.device);
1143    }
1144    if (!rctx.device->dev) {
1145       if (rctx.device->changer_res) {
1146         Jmsg(rctx.jcr, M_WARNING, 0, _("\n"
1147            "     Device \"%s\" in changer \"%s\" requested by DIR could not be opened or does not exist.\n"),
1148              rctx.device->hdr.name, rctx.device_name);
1149       } else {
1150          Jmsg(rctx.jcr, M_WARNING, 0, _("\n"
1151             "     Device \"%s\" requested by DIR could not be opened or does not exist.\n"),
1152               rctx.device_name);
1153       }
1154       return -1;  /* no use waiting */
1155    }  
1156
1157    rctx.suitable_device = true;
1158    Dmsg2(dbglvl, "jid=%u try reserve %s\n", rctx.jcr->JobId, rctx.device->hdr.name);
1159    rctx.jcr->dcr = dcr = new_dcr(rctx.jcr, rctx.jcr->dcr, rctx.device->dev);
1160    if (!dcr) {
1161       BSOCK *dir = rctx.jcr->dir_bsock;
1162       dir->fsend(_("3926 Could not get dcr for device: %s\n"), rctx.device_name);
1163       Dmsg1(dbglvl, ">dird: %s", dir->msg);
1164       return -1;
1165    }
1166    bstrncpy(dcr->pool_name, rctx.store->pool_name, name_len);
1167    bstrncpy(dcr->pool_type, rctx.store->pool_type, name_len);
1168    bstrncpy(dcr->media_type, rctx.store->media_type, name_len);
1169    bstrncpy(dcr->dev_name, rctx.device_name, name_len);
1170    if (rctx.store->append == SD_APPEND) {
1171       Dmsg3(dbglvl, "jid=%u have_vol=%d vol=%s\n", (int)rctx.jcr->JobId,
1172           rctx.have_volume, rctx.VolumeName);                                   
1173       ok = reserve_device_for_append(dcr, rctx);
1174       if (!ok) {
1175          goto bail_out;
1176       }
1177
1178       rctx.jcr->dcr = dcr;
1179       Dmsg6(dbglvl, "jid=%u Reserved=%d dev_name=%s mediatype=%s pool=%s ok=%d\n",
1180                (int)rctx.jcr->JobId,
1181                dcr->dev->reserved_device,
1182                dcr->dev_name, dcr->media_type, dcr->pool_name, ok);
1183       if (rctx.have_volume) {
1184          if (reserve_volume(dcr, rctx.VolumeName)) {
1185             Dmsg2(dbglvl, "jid=%u Reserved vol=%s\n", jid(), rctx.VolumeName);
1186          } else {
1187             Dmsg2(dbglvl, "jid=%u Could not reserve vol=%s\n", jid(), rctx.VolumeName);
1188             goto bail_out;
1189          }
1190       } else {
1191          dcr->any_volume = true;
1192          if (dir_find_next_appendable_volume(dcr)) {
1193             bstrncpy(rctx.VolumeName, dcr->VolumeName, sizeof(rctx.VolumeName));
1194             Dmsg2(dbglvl, "jid=%u looking for Volume=%s\n", (int)rctx.jcr->JobId, rctx.VolumeName);
1195             rctx.have_volume = true;
1196          } else {
1197             Dmsg1(dbglvl, "jid=%u No next volume found\n", (int)rctx.jcr->JobId);
1198             rctx.have_volume = false;
1199             rctx.VolumeName[0] = 0;
1200             /*
1201              * If there is at least one volume that is valid and in use,
1202              *   but we get here, check if we are running with prefers
1203              *   non-mounted drives.  In that case, we have selected a
1204              *   non-used drive and our one and only volume is mounted
1205              *   elsewhere, so we bail out and retry using that drive.
1206              */
1207             if (dcr->volume_in_use && !rctx.PreferMountedVols) {
1208                rctx.PreferMountedVols = true;
1209                if (dcr->VolumeName[0]) {
1210                   unreserve_device(dcr);
1211                }
1212                goto bail_out;
1213             }
1214             /*
1215              * Note. Under some circumstances, the Director can hand us
1216              *  a Volume name that is not the same as the one on the current
1217              *  drive, and in that case, the call above to find the next
1218              *  volume will fail because in attempting to reserve the Volume
1219              *  the code will realize that we already have a tape mounted,
1220              *  and it will fail.  This *should* only happen if there are 
1221              *  writers, thus the following test.  In that case, we simply
1222              *  bail out, and continue waiting, rather than plunging on
1223              *  and hoping that the operator can resolve the problem. 
1224              */
1225             if (dcr->dev->num_writers != 0) {
1226                if (dcr->VolumeName[0]) {
1227                   unreserve_device(dcr);
1228                }
1229                goto bail_out;
1230             }
1231          }
1232       }
1233    } else {
1234       ok = reserve_device_for_read(dcr);
1235       if (ok) {
1236          rctx.jcr->read_dcr = dcr;
1237          Dmsg6(dbglvl, "jid=%u Read reserved=%d dev_name=%s mediatype=%s pool=%s ok=%d\n",
1238                (int)rctx.jcr->JobId,
1239                dcr->dev->reserved_device,
1240                dcr->dev_name, dcr->media_type, dcr->pool_name, ok);
1241       }
1242    }
1243    if (!ok) {
1244       goto bail_out;
1245    }
1246
1247    if (rctx.notify_dir) {
1248       POOL_MEM dev_name;
1249       BSOCK *dir = rctx.jcr->dir_bsock;
1250       pm_strcpy(dev_name, rctx.device->hdr.name);
1251       bash_spaces(dev_name);
1252       ok = dir->fsend(OK_device, dev_name.c_str());  /* Return real device name */
1253       Dmsg2(dbglvl, "jid=%u >dird changer: %s", jid(), dir->msg);
1254    } else {
1255       ok = true;
1256    }
1257    return ok ? 1 : -1;
1258
1259 bail_out:
1260    rctx.have_volume = false;
1261    Dmsg1(dbglvl, "jid=%u Not OK.\n", (int)rctx.jcr->JobId);
1262    rctx.VolumeName[0] = 0;
1263    return 0;
1264 }
1265
1266 /*
1267  * We "reserve" the drive by setting the ST_READ bit. No one else
1268  *  should touch the drive until that is cleared.
1269  *  This allows the DIR to "reserve" the device before actually
1270  *  starting the job. 
1271  */
1272 static bool reserve_device_for_read(DCR *dcr)
1273 {
1274    DEVICE *dev = dcr->dev;
1275    JCR *jcr = dcr->jcr;
1276    bool ok = false;
1277
1278    ASSERT(dcr);
1279
1280    dev->dlock();  
1281
1282    if (is_device_unmounted(dev)) {             
1283       Dmsg2(dbglvl, "jid=%u Device %s is BLOCKED due to user unmount.\n", 
1284          (int)jcr->JobId, dev->print_name());
1285       Mmsg(jcr->errmsg, _("3601 JobId=%u device %s is BLOCKED due to user unmount.\n"),
1286            jcr->JobId, dev->print_name());
1287       queue_reserve_message(jcr);
1288       goto bail_out;
1289    }
1290
1291    if (dev->is_busy()) {
1292       Dmsg5(dbglvl, "jid=%u Device %s is busy ST_READ=%d num_writers=%d reserved=%d.\n", 
1293          (int)jcr->JobId, dev->print_name(),
1294          dev->state & ST_READ?1:0, dev->num_writers, dev->reserved_device);
1295       Mmsg(jcr->errmsg, _("3602 JobId=%u device %s is busy (already reading/writing).\n"),
1296             jcr->JobId, dev->print_name());
1297       queue_reserve_message(jcr);
1298       goto bail_out;
1299    }
1300
1301    dev->clear_append();
1302    dev->set_read();
1303    ok = true;
1304    dev->reserved_device++;
1305    Dmsg4(dbglvl, "jid=%u Inc reserve=%d dev=%s %p\n", (int)jcr->JobId,
1306       dev->reserved_device, dev->print_name(), dev);
1307    dcr->reserved_device = true;
1308
1309 bail_out:
1310    dev->dunlock();
1311    return ok;
1312 }
1313
1314
1315 /*
1316  * We reserve the device for appending by incrementing the 
1317  *  reserved_device. We do virtually all the same work that
1318  *  is done in acquire_device_for_append(), but we do
1319  *  not attempt to mount the device. This routine allows
1320  *  the DIR to reserve multiple devices before *really* 
1321  *  starting the job. It also permits the SD to refuse 
1322  *  certain devices (not up, ...).
1323  *
1324  * Note, in reserving a device, if the device is for the
1325  *  same pool and the same pool type, then it is acceptable.
1326  *  The Media Type has already been checked. If we are
1327  *  the first tor reserve the device, we put the pool
1328  *  name and pool type in the device record.
1329  */
1330 static bool reserve_device_for_append(DCR *dcr, RCTX &rctx)
1331 {
1332    JCR *jcr = dcr->jcr;
1333    DEVICE *dev = dcr->dev;
1334    bool ok = false;
1335
1336    ASSERT(dcr);
1337
1338    dev->dlock();
1339
1340    /* If device is being read, we cannot write it */
1341    if (dev->can_read()) {
1342       Mmsg(jcr->errmsg, _("3603 JobId=%u device %s is busy reading.\n"), 
1343          jcr->JobId, dev->print_name());
1344       Dmsg2(dbglvl, "jid=%u %s", jid(), jcr->errmsg);
1345       queue_reserve_message(jcr);
1346       goto bail_out;
1347    }
1348
1349    /* If device is unmounted, we are out of luck */
1350    if (is_device_unmounted(dev)) {
1351       Mmsg(jcr->errmsg, _("3604 JobId=%u device %s is BLOCKED due to user unmount.\n"), 
1352          jcr->JobId, dev->print_name());
1353       Dmsg2(dbglvl, "jid=%u %s", jid(), jcr->errmsg);
1354       queue_reserve_message(jcr);
1355       goto bail_out;
1356    }
1357
1358    Dmsg2(dbglvl, "jid=%u reserve_append device is %s\n", 
1359        (int)jcr->JobId, dev->print_name());
1360
1361    /* Now do detailed tests ... */
1362    if (can_reserve_drive(dcr, rctx) != 1) {
1363       Dmsg1(dbglvl, "jid=%u can_reserve_drive!=1\n", (int)jcr->JobId);
1364       goto bail_out;
1365    }
1366
1367    dev->reserved_device++;
1368    Dmsg4(dbglvl, "jid=%u Inc reserve=%d dev=%s %p\n", (int)jcr->JobId, dev->reserved_device, 
1369       dev->print_name(), dev);
1370    dcr->reserved_device = true;
1371    ok = true;
1372
1373 bail_out:
1374    dev->dunlock();
1375    return ok;
1376 }
1377
1378 static int is_pool_ok(DCR *dcr)
1379 {
1380    DEVICE *dev = dcr->dev;
1381    JCR *jcr = dcr->jcr;
1382
1383    /* Now check if we want the same Pool and pool type */
1384    if (strcmp(dev->pool_name, dcr->pool_name) == 0 &&
1385        strcmp(dev->pool_type, dcr->pool_type) == 0) {
1386       /* OK, compatible device */
1387       Dmsg1(dbglvl, "OK dev: %s num_writers=0, reserved, pool matches\n", dev->print_name());
1388       return 1;
1389    } else {
1390       /* Drive Pool not suitable for us */
1391       Mmsg(jcr->errmsg, _(
1392 "3608 JobId=%u wants Pool=\"%s\" but have Pool=\"%s\" nreserve=%d on drive %s.\n"), 
1393             (uint32_t)jcr->JobId, dcr->pool_name, dev->pool_name,
1394             dev->reserved_device, dev->print_name());
1395       queue_reserve_message(jcr);
1396       Dmsg2(dbglvl, "failed: busy num_writers=0, reserved, pool=%s wanted=%s\n",
1397          dev->pool_name, dcr->pool_name);
1398    }
1399    return 0;
1400 }
1401
1402 static bool is_max_jobs_ok(DCR *dcr) 
1403 {
1404    DEVICE *dev = dcr->dev;
1405    JCR *jcr = dcr->jcr;
1406
1407    Dmsg4(dbglvl, "MaxJobs=%d Jobs=%d reserves=%d Vol=%s\n",
1408          dcr->VolCatInfo.VolCatMaxJobs,
1409          dcr->VolCatInfo.VolCatJobs, dev->reserved_device,
1410          dcr->VolumeName);
1411    if (dcr->VolCatInfo.VolCatMaxJobs > 0 && dcr->VolCatInfo.VolCatMaxJobs <=
1412         (dcr->VolCatInfo.VolCatJobs + dev->reserved_device)) {
1413       /* Max Job Vols depassed or already reserved */
1414       Mmsg(jcr->errmsg, _("3610 JobId=%u Volume max jobs exceeded on drive %s.\n"), 
1415             (uint32_t)jcr->JobId, dev->print_name());
1416       queue_reserve_message(jcr);
1417       Dmsg1(dbglvl, "reserve dev failed: %s", jcr->errmsg);
1418       return false;                /* wait */
1419    }
1420    return true;
1421 }
1422
1423 /*
1424  * Returns: 1 if drive can be reserved
1425  *          0 if we should wait
1426  *         -1 on error or impossibility
1427  */
1428 static int can_reserve_drive(DCR *dcr, RCTX &rctx) 
1429 {
1430    DEVICE *dev = dcr->dev;
1431    JCR *jcr = dcr->jcr;
1432
1433    Dmsg6(dbglvl, "jid=%u PrefMnt=%d exact=%d suitable=%d chgronly=%d any=%d\n",
1434          (int)jcr->JobId,
1435          rctx.PreferMountedVols, rctx.exact_match, rctx.suitable_device,
1436          rctx.autochanger_only, rctx.any_drive);
1437
1438    /* Check for max jobs on this Volume */
1439    if (!is_max_jobs_ok(dcr)) {
1440       return 0;
1441    }
1442
1443    /* setting any_drive overrides PreferMountedVols flag */
1444    if (!rctx.any_drive) {
1445       /*
1446        * When PreferMountedVols is set, we keep track of the 
1447        *  drive in use that has the least number of writers, then if
1448        *  no unmounted drive is found, we try that drive. This   
1449        *  helps spread the load to the least used drives.  
1450        */
1451       if (rctx.try_low_use_drive && dev == rctx.low_use_drive) {
1452          Dmsg3(dbglvl, "jid=%u OK dev=%s == low_drive=%s.\n",
1453             jcr->JobId, dev->print_name(), rctx.low_use_drive->print_name());
1454          return 1;
1455       }
1456       /* If he wants a free drive, but this one is busy, no go */
1457       if (!rctx.PreferMountedVols && dev->is_busy()) {
1458          /* Save least used drive */
1459          if ((dev->num_writers + dev->reserved_device) < rctx.num_writers) {
1460             rctx.num_writers = dev->num_writers + dev->reserved_device;
1461             rctx.low_use_drive = dev;
1462             Dmsg3(dbglvl, "jid=%u set low use drive=%s num_writers=%d\n", 
1463                (int)jcr->JobId, dev->print_name(), rctx.num_writers);
1464          } else {
1465             Dmsg2(dbglvl, "jid=%u not low use num_writers=%d\n", 
1466                (int)jcr->JobId, dev->num_writers+dev->reserved_device);
1467          }
1468          Dmsg1(dbglvl, "jid=%u failed: !prefMnt && busy.\n", jcr->JobId);
1469          Mmsg(jcr->errmsg, _("3605 JobId=%u wants free drive but device %s is busy.\n"), 
1470             jcr->JobId, dev->print_name());
1471          queue_reserve_message(jcr);
1472          return 0;
1473       }
1474
1475       /* Check for prefer mounted volumes */
1476       if (rctx.PreferMountedVols && !dev->vol && dev->is_tape()) {
1477          Mmsg(jcr->errmsg, _("3606 JobId=%u prefers mounted drives, but drive %s has no Volume.\n"), 
1478             jcr->JobId, dev->print_name());
1479          queue_reserve_message(jcr);
1480          Dmsg1(dbglvl, "jid=%u failed: want mounted -- no vol\n", (uint32_t)jcr->JobId);
1481          return 0;                 /* No volume mounted */
1482       }
1483
1484       /* Check for exact Volume name match */
1485       /* ***FIXME*** for Disk, we can accept any volume that goes with this
1486        *    drive.
1487        */
1488       if (rctx.exact_match && rctx.have_volume) {
1489          bool ok;
1490          Dmsg6(dbglvl, "jid=%u PrefMnt=%d exact=%d suitable=%d chgronly=%d any=%d\n",
1491                (int)jcr->JobId,
1492                rctx.PreferMountedVols, rctx.exact_match, rctx.suitable_device,
1493                rctx.autochanger_only, rctx.any_drive);
1494          Dmsg5(dbglvl, "jid=%u have_vol=%d have=%s resvol=%s want=%s\n",
1495                   (int)jcr->JobId, rctx.have_volume, dev->VolHdr.VolumeName, 
1496                   dev->vol?dev->vol->vol_name:"*none*", rctx.VolumeName);
1497          ok = strcmp(dev->VolHdr.VolumeName, rctx.VolumeName) == 0 ||
1498                  (dev->vol && strcmp(dev->vol->vol_name, rctx.VolumeName) == 0);
1499          if (!ok) {
1500             Mmsg(jcr->errmsg, _("3607 JobId=%u wants Vol=\"%s\" drive has Vol=\"%s\" on drive %s.\n"), 
1501                jcr->JobId, rctx.VolumeName, dev->VolHdr.VolumeName, 
1502                dev->print_name());
1503             queue_reserve_message(jcr);
1504             Dmsg4(dbglvl, "jid=%u not OK: dev have=%s resvol=%s want=%s\n",
1505                   (int)jcr->JobId, dev->VolHdr.VolumeName, 
1506                   dev->vol?dev->vol->vol_name:"*none*", rctx.VolumeName);
1507             return 0;
1508          }
1509          if (is_volume_in_use(dcr)) {
1510             return 0;              /* fail if volume on another drive */
1511          }
1512       }
1513    }
1514
1515    /* Check for unused autochanger drive */
1516    if (rctx.autochanger_only && !dev->is_busy() &&
1517        dev->VolHdr.VolumeName[0] == 0) {
1518       /* Device is available but not yet reserved, reserve it for us */
1519       Dmsg2(dbglvl, "jid=%u OK Res Unused autochanger %s.\n",
1520          jcr->JobId, dev->print_name());
1521       bstrncpy(dev->pool_name, dcr->pool_name, sizeof(dev->pool_name));
1522       bstrncpy(dev->pool_type, dcr->pool_type, sizeof(dev->pool_type));
1523       return 1;                       /* reserve drive */
1524    }
1525
1526    /*
1527     * Handle the case that there are no writers
1528     */
1529    if (dev->num_writers == 0) {
1530       /* Now check if there are any reservations on the drive */
1531       if (dev->reserved_device) {           
1532          return is_pool_ok(dcr);
1533       } else if (dev->can_append()) {
1534          if (is_pool_ok(dcr)) {
1535             return 1; 
1536          } else {
1537             /* Changing pool, unload old tape if any in drive */
1538             Dmsg1(dbglvl, "jid=%u OK dev: num_writers=0, not reserved, pool change, unload changer\n",
1539                 (int)jcr->JobId);
1540             unload_autochanger(dcr, 0);
1541          }
1542       }
1543       /* Device is available but not yet reserved, reserve it for us */
1544       Dmsg2(dbglvl, "jid=%u OK Dev avail reserved %s\n", jcr->JobId, dev->print_name());
1545       bstrncpy(dev->pool_name, dcr->pool_name, sizeof(dev->pool_name));
1546       bstrncpy(dev->pool_type, dcr->pool_type, sizeof(dev->pool_type));
1547       return 1;                       /* reserve drive */
1548    }
1549
1550    /*
1551     * Check if the device is in append mode with writers (i.e.
1552     *  available if pool is the same).
1553     */
1554    if (dev->can_append() || dev->num_writers > 0) {
1555       return is_pool_ok(dcr);
1556    } else {
1557       Pmsg1(000, _("Logic error!!!! JobId=%u Should not get here.\n"), (int)jcr->JobId);
1558       Mmsg(jcr->errmsg, _("3910 JobId=%u Logic error!!!! drive %s Should not get here.\n"),
1559             jcr->JobId, dev->print_name());
1560       queue_reserve_message(jcr);
1561       Jmsg0(jcr, M_FATAL, 0, _("Logic error!!!! Should not get here.\n"));
1562       return -1;                      /* error, should not get here */
1563    }
1564    Mmsg(jcr->errmsg, _("3911 JobId=%u failed reserve drive %s.\n"), 
1565          jcr->JobId, dev->print_name());
1566    queue_reserve_message(jcr);
1567    Dmsg2(dbglvl, "jid=%u failed: No reserve %s\n", jcr->JobId, dev->print_name());
1568    return 0;
1569 }
1570
1571
1572
1573
1574 /*
1575  * Queue a reservation error or failure message for this jcr
1576  */
1577 static void queue_reserve_message(JCR *jcr)
1578 {
1579    int i;   
1580    alist *msgs;
1581    char *msg;
1582
1583    jcr->lock();
1584
1585    msgs = jcr->reserve_msgs;
1586    if (!msgs) {
1587       goto bail_out;
1588    }
1589    /*
1590     * Look for duplicate message.  If found, do
1591     * not insert
1592     */
1593    for (i=msgs->size()-1; i >= 0; i--) {
1594       msg = (char *)msgs->get(i);
1595       if (!msg) {
1596          goto bail_out;
1597       }
1598       /* Comparison based on 4 digit message number */
1599       if (strncmp(msg, jcr->errmsg, 4) == 0) {
1600          goto bail_out;
1601       }
1602    }      
1603    /* Message unique, so insert it */
1604    jcr->reserve_msgs->push(bstrdup(jcr->errmsg));
1605
1606 bail_out:
1607    jcr->unlock();
1608 }
1609
1610 /*
1611  * Send any reservation messages queued for this jcr
1612  */
1613 void send_drive_reserve_messages(JCR *jcr, void sendit(const char *msg, int len, void *sarg), void *arg)
1614 {
1615    int i;
1616    alist *msgs;
1617    char *msg;
1618
1619    jcr->lock();
1620    msgs = jcr->reserve_msgs;
1621    if (!msgs || msgs->size() == 0) {
1622       goto bail_out;
1623    }
1624    for (i=msgs->size()-1; i >= 0; i--) {
1625       msg = (char *)msgs->get(i);
1626       if (msg) {
1627          sendit("   ", 3, arg);
1628          sendit(msg, strlen(msg), arg);
1629       } else {
1630          break;
1631       }
1632    }
1633
1634 bail_out:
1635    jcr->unlock();
1636 }
1637
1638 /*
1639  * Pop and release any reservations messages
1640  */
1641 static void pop_reserve_messages(JCR *jcr)
1642 {
1643    alist *msgs;
1644    char *msg;
1645
1646    jcr->lock();
1647    msgs = jcr->reserve_msgs;
1648    if (!msgs) {
1649       goto bail_out;
1650    }
1651    while ((msg = (char *)msgs->pop())) {
1652       free(msg);
1653    }
1654 bail_out:
1655    jcr->unlock();
1656 }
1657
1658 /*
1659  * Also called from acquire.c 
1660  */
1661 void release_reserve_messages(JCR *jcr)
1662 {
1663    pop_reserve_messages(jcr);
1664    jcr->lock();
1665    if (!jcr->reserve_msgs) {
1666       goto bail_out;
1667    }
1668    delete jcr->reserve_msgs;
1669    jcr->reserve_msgs = NULL;
1670
1671 bail_out:
1672    jcr->unlock();
1673 }