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