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