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