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