]> git.sur5r.net Git - bacula/bacula/blob - bacula/src/stored/reserve.c
Create patch that may fix bug #1298 and bug #1304, which causes
[bacula/bacula] / bacula / src / stored / reserve.c
1 /*
2    Bacula® - The Network Backup Solution
3
4    Copyright (C) 2000-2009 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 Kern Sibbald.
24    The licensor of Bacula is the Free Software Foundation Europe
25    (FSFE), Fiduciary Program, Sumatrastrasse 25, 8006 Zürich,
26    Switzerland, email:ftf@fsfeurope.org.
27 */
28 /*
29  *   Drive reservation functions for Storage Daemon
30  *
31  *   Kern Sibbald, MM
32  *
33  *   Split from job.c and acquire.c June 2005
34  *
35  *   Version $Id$
36  *
37  */
38
39 #include "bacula.h"
40 #include "stored.h"
41
42 const int dbglvl = 150;
43
44 static brwlock_t reservation_lock;
45
46 /* Forward referenced functions */
47 static int can_reserve_drive(DCR *dcr, RCTX &rctx);
48 static int reserve_device(RCTX &rctx);
49 static bool reserve_device_for_read(DCR *dcr);
50 static bool reserve_device_for_append(DCR *dcr, RCTX &rctx);
51 static bool use_storage_cmd(JCR *jcr);
52 static void queue_reserve_message(JCR *jcr);
53 static void pop_reserve_messages(JCR *jcr);
54 //void switch_device(DCR *dcr, DEVICE *dev);
55
56 /* Requests from the Director daemon */
57 static char use_storage[]  = "use storage=%127s media_type=%127s "
58    "pool_name=%127s pool_type=%127s append=%d copy=%d stripe=%d\n";
59 static char use_device[]  = "use device=%127s\n";
60
61 /* Responses sent to Director daemon */
62 static char OK_device[] = "3000 OK use device device=%s\n";
63 static char NO_device[] = "3924 Device \"%s\" not in SD Device resources.\n";
64 static char BAD_use[]   = "3913 Bad use command: %s\n";
65
66 bool use_cmd(JCR *jcr) 
67 {
68    /*
69     * Get the device, media, and pool information
70     */
71    if (!use_storage_cmd(jcr)) {
72       set_jcr_job_status(jcr, JS_ErrorTerminated);
73       memset(jcr->sd_auth_key, 0, strlen(jcr->sd_auth_key));
74       return false;
75    }
76    return true;
77 }
78
79 /*
80  * This allows a given thread to recursively call lock_reservations.
81  *   It must, of course, call unlock_... the same number of times.
82  */
83 void init_reservations_lock()
84 {
85    int errstat;
86    if ((errstat=rwl_init(&reservation_lock)) != 0) {
87       berrno be;
88       Emsg1(M_ABORT, 0, _("Unable to initialize reservation lock. ERR=%s\n"),
89             be.bstrerror(errstat));
90    }
91
92    init_vol_list_lock();
93 }
94
95 void term_reservations_lock()
96 {
97    rwl_destroy(&reservation_lock);
98    term_vol_list_lock();
99 }
100
101 int reservations_lock_count = 0;
102
103 /* This applies to a drive and to Volumes */
104 void _lock_reservations()
105 {
106    int errstat;
107    reservations_lock_count++;
108    if ((errstat=rwl_writelock(&reservation_lock)) != 0) {
109       berrno be;
110       Emsg2(M_ABORT, 0, "rwl_writelock failure. stat=%d: ERR=%s\n",
111            errstat, be.bstrerror(errstat));
112    }
113 }
114
115 void _unlock_reservations()
116 {
117    int errstat;
118    reservations_lock_count--;
119    if ((errstat=rwl_writeunlock(&reservation_lock)) != 0) {
120       berrno be;
121       Emsg2(M_ABORT, 0, "rwl_writeunlock failure. stat=%d: ERR=%s\n",
122            errstat, be.bstrerror(errstat));
123    }
124 }
125
126 void DCR::set_reserved()
127 {
128    m_reserved = true;
129    Dmsg2(dbglvl, "Inc reserve=%d dev=%s\n", dev->num_reserved(), dev->print_name());
130    dev->inc_reserved();
131 }
132
133 void DCR::clear_reserved()
134 {
135    if (m_reserved) {
136       m_reserved = false;
137       dev->dec_reserved();
138       Dmsg2(dbglvl, "Dec reserve=%d dev=%s\n", dev->num_reserved(), dev->print_name());
139    }
140 }
141
142 /* 
143  * Remove any reservation from a drive and tell the system
144  *  that the volume is unused at least by us.
145  */
146 void DCR::unreserve_device()
147 {
148    lock_volumes();
149    if (is_reserved()) {
150       clear_reserved();
151       reserved_volume = false;
152       /* If we set read mode in reserving, remove it */
153       if (dev->can_read()) {
154          dev->clear_read();
155       }
156       if (dev->num_writers < 0) {
157          Jmsg1(jcr, M_ERROR, 0, _("Hey! num_writers=%d!!!!\n"), dev->num_writers);
158          dev->num_writers = 0;
159       }
160       if (dev->num_reserved() == 0 && dev->num_writers == 0) {
161          volume_unused(this);
162       }
163    }
164    unlock_volumes();
165 }
166
167 /*
168  * We get the following type of information:
169  *
170  * use storage=xxx media_type=yyy pool_name=xxx pool_type=yyy append=1 copy=0 strip=0
171  *  use device=zzz
172  *  use device=aaa
173  *  use device=bbb
174  * use storage=xxx media_type=yyy pool_name=xxx pool_type=yyy append=0 copy=0 strip=0
175  *  use device=bbb
176  *
177  */
178 static bool use_storage_cmd(JCR *jcr)
179 {
180    POOL_MEM store_name, dev_name, media_type, pool_name, pool_type;
181    BSOCK *dir = jcr->dir_bsock;
182    int append;
183    bool ok;       
184    int Copy, Stripe;
185    DIRSTORE *store;
186    RCTX rctx;
187    alist *dirstore;
188
189    memset(&rctx, 0, sizeof(RCTX));
190    rctx.jcr = jcr;
191    /*
192     * If there are multiple devices, the director sends us
193     *   use_device for each device that it wants to use.
194     */
195    dirstore = New(alist(10, not_owned_by_alist));
196    jcr->reserve_msgs = New(alist(10, not_owned_by_alist));  
197    do {
198       Dmsg1(dbglvl, "<dird: %s", dir->msg);
199       ok = sscanf(dir->msg, use_storage, store_name.c_str(), 
200                   media_type.c_str(), pool_name.c_str(), 
201                   pool_type.c_str(), &append, &Copy, &Stripe) == 7;
202       if (!ok) {
203          break;
204       }
205       if (append) {
206          jcr->write_store = dirstore;
207       } else {
208          jcr->read_store = dirstore;
209       }
210       rctx.append = append;
211       unbash_spaces(store_name);
212       unbash_spaces(media_type);
213       unbash_spaces(pool_name);
214       unbash_spaces(pool_type);
215       store = new DIRSTORE;
216       dirstore->append(store);
217       memset(store, 0, sizeof(DIRSTORE));
218       store->device = New(alist(10));
219       bstrncpy(store->name, store_name, sizeof(store->name));
220       bstrncpy(store->media_type, media_type, sizeof(store->media_type));
221       bstrncpy(store->pool_name, pool_name, sizeof(store->pool_name));
222       bstrncpy(store->pool_type, pool_type, sizeof(store->pool_type));
223       store->append = append;
224
225       /* Now get all devices */
226       while (dir->recv() >= 0) {
227          Dmsg1(dbglvl, "<dird device: %s", dir->msg);
228          ok = sscanf(dir->msg, use_device, dev_name.c_str()) == 1;
229          if (!ok) {
230             break;
231          }
232          unbash_spaces(dev_name);
233          store->device->append(bstrdup(dev_name.c_str()));
234       }
235    }  while (ok && dir->recv() >= 0);
236
237    /* Developer debug code */
238    char *device_name;
239    if (debug_level >= dbglvl) {
240       foreach_alist(store, dirstore) {
241          Dmsg5(dbglvl, "Storage=%s media_type=%s pool=%s pool_type=%s append=%d\n", 
242             store->name, store->media_type, store->pool_name, 
243             store->pool_type, store->append);
244          foreach_alist(device_name, store->device) {
245             Dmsg1(dbglvl, "     Device=%s\n", device_name);
246          }
247       }
248    }
249
250    init_jcr_device_wait_timers(jcr);
251    jcr->dcr = new_dcr(jcr, NULL, NULL);         /* get a dcr */
252    if (!jcr->dcr) {
253       BSOCK *dir = jcr->dir_bsock;
254       dir->fsend(_("3939 Could not get dcr\n"));
255       Dmsg1(dbglvl, ">dird: %s", dir->msg);
256       ok = false;
257    }
258    /*                    
259     * At this point, we have a list of all the Director's Storage
260     *  resources indicated for this Job, which include Pool, PoolType,
261     *  storage name, and Media type.     
262     * Then for each of the Storage resources, we have a list of
263     *  device names that were given.
264     *
265     * Wiffle through them and find one that can do the backup.
266     */
267    if (ok) {
268       int wait_for_device_retries = 0;  
269       int repeat = 0;
270       bool fail = false;
271       rctx.notify_dir = true;
272
273       lock_reservations();
274       for ( ; !fail && !job_canceled(jcr); ) {
275          pop_reserve_messages(jcr);
276          rctx.suitable_device = false;
277          rctx.have_volume = false;
278          rctx.VolumeName[0] = 0;
279          rctx.any_drive = false;
280          if (!jcr->PreferMountedVols) {
281             /*
282              * Here we try to find a drive that is not used.
283              * This will maximize the use of available drives.
284              *
285              */
286             rctx.num_writers = 20000000;   /* start with impossible number */
287             rctx.low_use_drive = NULL;
288             rctx.PreferMountedVols = false;                
289             rctx.exact_match = false;
290             rctx.autochanger_only = true;
291             if ((ok = find_suitable_device_for_job(jcr, rctx))) {
292                break;
293             }
294             /* Look through all drives possibly for low_use drive */
295             if (rctx.low_use_drive) {
296                rctx.try_low_use_drive = true;
297                if ((ok = find_suitable_device_for_job(jcr, rctx))) {
298                   break;
299                }
300                rctx.try_low_use_drive = false;
301             }
302             rctx.autochanger_only = false;
303             if ((ok = find_suitable_device_for_job(jcr, rctx))) {
304                break;
305             }
306          }
307          /*
308           * Now we look for a drive that may or may not be in
309           *  use.
310           */
311          /* Look for an exact Volume match all drives */
312          rctx.PreferMountedVols = true;
313          rctx.exact_match = true;
314          rctx.autochanger_only = false;
315          if ((ok = find_suitable_device_for_job(jcr, rctx))) {
316             break;
317          }
318          /* Look for any mounted drive */
319          rctx.exact_match = false;
320          if ((ok = find_suitable_device_for_job(jcr, rctx))) {
321             break;
322          }
323          /* Try any drive */
324          rctx.any_drive = true;
325          if ((ok = find_suitable_device_for_job(jcr, rctx))) {
326             break;
327          }
328          /* Keep reservations locked *except* during wait_for_device() */
329          unlock_reservations();
330          /*     
331           * The idea of looping on repeat a few times it to ensure
332           * that if there is some subtle timing problem between two
333           * jobs, we will simply try again, and most likely succeed.
334           * This can happen if one job reserves a drive or finishes using
335           * a drive at the same time a second job wants it.
336           */
337          if (repeat++ > 1) {              /* try algorithm 3 times */
338             bmicrosleep(30, 0);           /* wait a bit */
339             Dmsg0(dbglvl, "repeat reserve algorithm\n");
340          } else if (!rctx.suitable_device || !wait_for_device(jcr, wait_for_device_retries)) {
341             Dmsg0(dbglvl, "Fail. !suitable_device || !wait_for_device\n");
342             fail = true;
343          }   
344          lock_reservations();
345          dir->signal(BNET_HEARTBEAT);  /* Inform Dir that we are alive */
346       }
347       unlock_reservations();
348       if (!ok) {
349          /*
350           * If we get here, there are no suitable devices available, which
351           *  means nothing configured.  If a device is suitable but busy
352           *  with another Volume, we will not come here.
353           */
354          unbash_spaces(dir->msg);
355          pm_strcpy(jcr->errmsg, dir->msg);
356          Jmsg(jcr, M_FATAL, 0, _("Device reservation failed for JobId=%d: %s\n"), 
357               jcr->JobId, jcr->errmsg);
358          dir->fsend(NO_device, dev_name.c_str());
359
360          Dmsg1(dbglvl, ">dird: %s", dir->msg);
361       }
362    } else {
363       unbash_spaces(dir->msg);
364       pm_strcpy(jcr->errmsg, dir->msg);
365       Jmsg(jcr, M_FATAL, 0, _("Failed command: %s\n"), jcr->errmsg);
366       dir->fsend(BAD_use, jcr->errmsg);
367       Dmsg1(dbglvl, ">dird: %s", dir->msg);
368    }
369
370    release_reserve_messages(jcr);
371    return ok;
372 }
373
374
375 /*
376  * Walk through the autochanger resources and check if
377  *  the volume is in one of them.
378  * 
379  * Returns:  true  if volume is in device
380  *           false otherwise
381  */
382 static bool is_vol_in_autochanger(RCTX &rctx, VOLRES *vol)
383 {
384    AUTOCHANGER *changer = vol->dev->device->changer_res;
385
386    /* Find resource, and make sure we were able to open it */
387    if (strcmp(rctx.device_name, changer->hdr.name) == 0) {
388       Dmsg1(dbglvl, "Found changer device %s\n", vol->dev->device->hdr.name);
389       return true;
390    }  
391    Dmsg1(dbglvl, "Incorrect changer device %s\n", changer->hdr.name);
392    return false;
393 }
394
395 /*
396  * Search for a device suitable for this job.
397  * Note, this routine sets sets rctx.suitable_device if any 
398  *   device exists within the SD.  The device may not be actually
399  *   useable.
400  * It also returns if it finds a useable device.  
401  */
402 bool find_suitable_device_for_job(JCR *jcr, RCTX &rctx)
403 {
404    bool ok = false;
405    DIRSTORE *store;
406    char *device_name;
407    alist *dirstore;
408    DCR *dcr = jcr->dcr;
409
410    if (rctx.append) {
411       dirstore = jcr->write_store;
412    } else {
413       dirstore = jcr->read_store;
414    }
415    Dmsg5(dbglvl, "Start find_suit_dev PrefMnt=%d exact=%d suitable=%d chgronly=%d any=%d\n",
416          rctx.PreferMountedVols, rctx.exact_match, rctx.suitable_device,
417          rctx.autochanger_only, rctx.any_drive);
418
419    /* 
420     * If the appropriate conditions of this if are met, namely that
421     *  we are appending and the user wants mounted drive (or we
422     *  force try a mounted drive because they are all busy), we
423     *  start by looking at all the Volumes in the volume list.
424     */
425    if (!is_vol_list_empty() && rctx.append && rctx.PreferMountedVols) {
426       dlist *temp_vol_list;
427       VOLRES *vol = NULL;
428       temp_vol_list = dup_vol_list(jcr);
429
430       /* Look through reserved volumes for one we can use */
431       Dmsg0(dbglvl, "look for vol in vol list\n");
432       foreach_dlist(vol, temp_vol_list) {
433          if (!vol->dev) {
434             Dmsg1(dbglvl, "vol=%s no dev\n", vol->vol_name);
435             continue;
436          }
437          /* Check with Director if this Volume is OK */
438          bstrncpy(dcr->VolumeName, vol->vol_name, sizeof(dcr->VolumeName));
439          if (!dir_get_volume_info(dcr, GET_VOL_INFO_FOR_WRITE)) {
440             continue;
441          }
442
443          Dmsg1(dbglvl, "vol=%s OK for this job\n", vol->vol_name);
444          foreach_alist(store, dirstore) {
445             int stat;
446             rctx.store = store;
447             foreach_alist(device_name, store->device) {
448                /* Found a device, try to use it */
449                rctx.device_name = device_name;
450                rctx.device = vol->dev->device;
451
452                if (vol->dev->is_autochanger()) {
453                   Dmsg1(dbglvl, "vol=%s is in changer\n", vol->vol_name);
454                   if (!is_vol_in_autochanger(rctx, vol)) {
455                      continue;
456                   }
457                } else if (strcmp(device_name, vol->dev->device->hdr.name) != 0) {
458                   Dmsg2(dbglvl, "device=%s not suitable want %s\n",
459                         vol->dev->device->hdr.name, device_name);
460                   continue;
461                }
462
463                bstrncpy(rctx.VolumeName, vol->vol_name, sizeof(rctx.VolumeName));
464                rctx.have_volume = true;
465                /* Try reserving this device and volume */
466                Dmsg2(dbglvl, "try vol=%s on device=%s\n", rctx.VolumeName, device_name);
467                stat = reserve_device(rctx);
468                if (stat == 1) {             /* found available device */
469                   Dmsg1(dbglvl, "Suitable device found=%s\n", device_name);
470                   ok = true;
471                   break;
472                } else if (stat == 0) {      /* device busy */
473                   Dmsg1(dbglvl, "Suitable device=%s, busy: not use\n", device_name);
474                } else {
475                   /* otherwise error */
476                   Dmsg0(dbglvl, "No suitable device found.\n");
477                }
478                rctx.have_volume = false;
479                rctx.VolumeName[0] = 0;
480             }
481             if (ok) {
482                break;
483             }
484          }
485          if (ok) {
486             break;
487          }
488       } /* end for loop over reserved volumes */
489
490       Dmsg0(dbglvl, "lock volumes\n");
491       free_temp_vol_list(temp_vol_list);
492    }
493    if (ok) {
494       Dmsg1(dbglvl, "OK dev found. Vol=%s from in-use vols list\n", rctx.VolumeName);
495       return true;
496    }
497
498    /* 
499     * No reserved volume we can use, so now search for an available device.  
500     *
501     * For each storage device that the user specified, we
502     *  search and see if there is a resource for that device.
503     */
504    foreach_alist(store, dirstore) {
505       rctx.store = store;
506       foreach_alist(device_name, store->device) {
507          int stat;
508          rctx.device_name = device_name;
509          stat = search_res_for_device(rctx); 
510          if (stat == 1) {             /* found available device */
511             Dmsg1(dbglvl, "available device found=%s\n", device_name);
512             ok = true;
513             break;
514          } else if (stat == 0) {      /* device busy */
515             Dmsg1(dbglvl, "No usable device=%s, busy: not use\n", device_name);
516          } else {
517             /* otherwise error */
518             Dmsg0(dbglvl, "No usable device found.\n");
519          }
520       }
521       if (ok) {
522          break;
523       }
524    }
525    if (ok) {
526       Dmsg1(dbglvl, "OK dev found. Vol=%s\n", rctx.VolumeName);
527    } else {
528       Dmsg0(dbglvl, "Leave find_suit_dev: no dev found.\n");
529    }
530    return ok;
531 }
532
533 /*
534  * Search for a particular storage device with particular storage
535  *  characteristics (MediaType).
536  */
537 int search_res_for_device(RCTX &rctx) 
538 {
539    AUTOCHANGER *changer;
540    int stat;
541
542    Dmsg1(dbglvl, "search res for %s\n", rctx.device_name);
543    /* Look through Autochangers first */
544    foreach_res(changer, R_AUTOCHANGER) {
545       Dmsg1(dbglvl, "Try match changer res=%s\n", changer->hdr.name);
546       /* Find resource, and make sure we were able to open it */
547       if (strcmp(rctx.device_name, changer->hdr.name) == 0) {
548          /* Try each device in this AutoChanger */
549          foreach_alist(rctx.device, changer->device) {
550             Dmsg1(dbglvl, "Try changer device %s\n", rctx.device->hdr.name);
551             if (!rctx.device->autoselect) {
552                Dmsg1(100, "Device %s not autoselect skipped.\n",
553                rctx.device->hdr.name);
554                continue;              /* device is not available */
555             }
556             stat = reserve_device(rctx);
557             if (stat != 1) {             /* try another device */
558                continue;
559             }
560             /* Debug code */
561             if (rctx.store->append == SD_APPEND) {
562                Dmsg2(dbglvl, "Device %s reserved=%d for append.\n", 
563                   rctx.device->hdr.name, rctx.jcr->dcr->dev->num_reserved());
564             } else {
565                Dmsg2(dbglvl, "Device %s reserved=%d for read.\n", 
566                   rctx.device->hdr.name, rctx.jcr->read_dcr->dev->num_reserved());
567             }
568             return stat;
569          }
570       }
571    }
572
573    /* Now if requested look through regular devices */
574    if (!rctx.autochanger_only) {
575       foreach_res(rctx.device, R_DEVICE) {
576          Dmsg1(dbglvl, "Try match res=%s\n", rctx.device->hdr.name);
577          /* Find resource, and make sure we were able to open it */
578          if (strcmp(rctx.device_name, rctx.device->hdr.name) == 0) {
579             stat = reserve_device(rctx);
580             if (stat != 1) {             /* try another device */
581                continue;
582             }
583             /* Debug code */
584             if (rctx.store->append == SD_APPEND) {
585                Dmsg2(dbglvl, "Device %s reserved=%d for append.\n", 
586                   rctx.device->hdr.name, rctx.jcr->dcr->dev->num_reserved());
587             } else {
588                Dmsg2(dbglvl, "Device %s reserved=%d for read.\n", 
589                   rctx.device->hdr.name, rctx.jcr->read_dcr->dev->num_reserved());
590             }
591             return stat;
592          }
593       }
594    }
595    return -1;                    /* nothing found */
596 }
597
598 /*
599  *  Try to reserve a specific device.
600  *
601  *  Returns: 1 -- OK, have DCR
602  *           0 -- must wait
603  *          -1 -- fatal error
604  */
605 static int reserve_device(RCTX &rctx)
606 {
607    bool ok;
608    DCR *dcr;
609    const int name_len = MAX_NAME_LENGTH;
610
611    /* Make sure MediaType is OK */
612    Dmsg2(dbglvl, "chk MediaType device=%s request=%s\n",
613          rctx.device->media_type, rctx.store->media_type);
614    if (strcmp(rctx.device->media_type, rctx.store->media_type) != 0) {
615       return -1;
616    }
617
618    /* Make sure device exists -- i.e. we can stat() it */
619    if (!rctx.device->dev) {
620       rctx.device->dev = init_dev(rctx.jcr, rctx.device);
621    }
622    if (!rctx.device->dev) {
623       if (rctx.device->changer_res) {
624         Jmsg(rctx.jcr, M_WARNING, 0, _("\n"
625            "     Device \"%s\" in changer \"%s\" requested by DIR could not be opened or does not exist.\n"),
626              rctx.device->hdr.name, rctx.device_name);
627       } else {
628          Jmsg(rctx.jcr, M_WARNING, 0, _("\n"
629             "     Device \"%s\" requested by DIR could not be opened or does not exist.\n"),
630               rctx.device_name);
631       }
632       return -1;  /* no use waiting */
633    }  
634
635    rctx.suitable_device = true;
636    Dmsg1(dbglvl, "try reserve %s\n", rctx.device->hdr.name);
637    rctx.jcr->dcr = dcr = new_dcr(rctx.jcr, rctx.jcr->dcr, rctx.device->dev);
638    if (!dcr) {
639       BSOCK *dir = rctx.jcr->dir_bsock;
640       dir->fsend(_("3926 Could not get dcr for device: %s\n"), rctx.device_name);
641       Dmsg1(dbglvl, ">dird: %s", dir->msg);
642       return -1;
643    }
644    bstrncpy(dcr->pool_name, rctx.store->pool_name, name_len);
645    bstrncpy(dcr->pool_type, rctx.store->pool_type, name_len);
646    bstrncpy(dcr->media_type, rctx.store->media_type, name_len);
647    bstrncpy(dcr->dev_name, rctx.device_name, name_len);
648    if (rctx.store->append == SD_APPEND) {
649       Dmsg2(dbglvl, "call reserve for append: have_vol=%d vol=%s\n", rctx.have_volume, rctx.VolumeName);                                   
650       ok = reserve_device_for_append(dcr, rctx);
651       if (!ok) {
652          goto bail_out;
653       }
654
655       rctx.jcr->dcr = dcr;
656       Dmsg5(dbglvl, "Reserved=%d dev_name=%s mediatype=%s pool=%s ok=%d\n",
657                dcr->dev->num_reserved(),
658                dcr->dev_name, dcr->media_type, dcr->pool_name, ok);
659       Dmsg3(dbglvl, "Vol=%s num_writers=%d, have_vol=%d\n", 
660          rctx.VolumeName, dcr->dev->num_writers, rctx.have_volume);
661       if (rctx.have_volume) {
662          Dmsg0(dbglvl, "Call reserve_volume\n");
663          if (reserve_volume(dcr, rctx.VolumeName)) {
664             Dmsg1(dbglvl, "Reserved vol=%s\n", rctx.VolumeName);
665          } else {
666             Dmsg1(dbglvl, "Could not reserve vol=%s\n", rctx.VolumeName);
667             goto bail_out;
668          }
669       } else {
670          dcr->any_volume = true;
671          Dmsg0(dbglvl, "no vol, call find_next_appendable_vol.\n");
672          if (dir_find_next_appendable_volume(dcr)) {
673             bstrncpy(rctx.VolumeName, dcr->VolumeName, sizeof(rctx.VolumeName));
674             rctx.have_volume = true;
675             Dmsg1(dbglvl, "looking for Volume=%s\n", rctx.VolumeName);
676          } else {
677             Dmsg0(dbglvl, "No next volume found\n");
678             rctx.have_volume = false;
679             rctx.VolumeName[0] = 0;
680             /*
681              * If there is at least one volume that is valid and in use,
682              *   but we get here, check if we are running with prefers
683              *   non-mounted drives.  In that case, we have selected a
684              *   non-used drive and our one and only volume is mounted
685              *   elsewhere, so we bail out and retry using that drive.
686              */
687             if (dcr->found_in_use() && !rctx.PreferMountedVols) {
688                rctx.PreferMountedVols = true;
689                if (dcr->VolumeName[0]) {
690                   dcr->unreserve_device();
691                }
692                goto bail_out;
693             }
694             /*
695              * Note. Under some circumstances, the Director can hand us
696              *  a Volume name that is not the same as the one on the current
697              *  drive, and in that case, the call above to find the next
698              *  volume will fail because in attempting to reserve the Volume
699              *  the code will realize that we already have a tape mounted,
700              *  and it will fail.  This *should* only happen if there are 
701              *  writers, thus the following test.  In that case, we simply
702              *  bail out, and continue waiting, rather than plunging on
703              *  and hoping that the operator can resolve the problem. 
704              */
705             if (dcr->dev->num_writers != 0) {
706                if (dcr->VolumeName[0]) {
707                   dcr->unreserve_device();
708                }
709                goto bail_out;
710             }
711          }
712       }
713    } else {
714       ok = reserve_device_for_read(dcr);
715       if (ok) {
716          rctx.jcr->read_dcr = dcr;
717          Dmsg5(dbglvl, "Read reserved=%d dev_name=%s mediatype=%s pool=%s ok=%d\n",
718                dcr->dev->num_reserved(),
719                dcr->dev_name, dcr->media_type, dcr->pool_name, ok);
720       }
721    }
722    if (!ok) {
723       goto bail_out;
724    }
725
726    if (rctx.notify_dir) {
727       POOL_MEM dev_name;
728       BSOCK *dir = rctx.jcr->dir_bsock;
729       pm_strcpy(dev_name, rctx.device->hdr.name);
730       bash_spaces(dev_name);
731       ok = dir->fsend(OK_device, dev_name.c_str());  /* Return real device name */
732       Dmsg1(dbglvl, ">dird: %s", dir->msg);
733    } else {
734       ok = true;
735    }
736    return ok ? 1 : -1;
737
738 bail_out:
739    rctx.have_volume = false;
740    rctx.VolumeName[0] = 0;
741    Dmsg0(dbglvl, "Not OK.\n");
742    return 0;
743 }
744
745 /*
746  * We "reserve" the drive by setting the ST_READ bit. No one else
747  *  should touch the drive until that is cleared.
748  *  This allows the DIR to "reserve" the device before actually
749  *  starting the job. 
750  */
751 static bool reserve_device_for_read(DCR *dcr)
752 {
753    DEVICE *dev = dcr->dev;
754    JCR *jcr = dcr->jcr;
755    bool ok = false;
756
757    ASSERT(dcr);
758    if (job_canceled(jcr)) {
759       return false;
760    }
761
762    dev->dlock();  
763
764    if (is_device_unmounted(dev)) {             
765       Dmsg1(dbglvl, "Device %s is BLOCKED due to user unmount.\n", dev->print_name());
766       Mmsg(jcr->errmsg, _("3601 JobId=%u device %s is BLOCKED due to user unmount.\n"),
767            jcr->JobId, dev->print_name());
768       queue_reserve_message(jcr);
769       goto bail_out;
770    }
771
772    if (dev->is_busy()) {
773       Dmsg4(dbglvl, "Device %s is busy ST_READ=%d num_writers=%d reserved=%d.\n", 
774          dev->print_name(),
775          dev->state & ST_READ?1:0, dev->num_writers, dev->num_reserved());
776       Mmsg(jcr->errmsg, _("3602 JobId=%u device %s is busy (already reading/writing).\n"),
777             jcr->JobId, dev->print_name());
778       queue_reserve_message(jcr);
779       goto bail_out;
780    }
781
782    dev->clear_append();
783    dev->set_read();
784    ok = true;
785    dcr->set_reserved();
786
787 bail_out:
788    dev->dunlock();
789    return ok;
790 }
791
792
793 /*
794  * We reserve the device for appending by incrementing
795  *  num_reserved(). We do virtually all the same work that
796  *  is done in acquire_device_for_append(), but we do
797  *  not attempt to mount the device. This routine allows
798  *  the DIR to reserve multiple devices before *really* 
799  *  starting the job. It also permits the SD to refuse 
800  *  certain devices (not up, ...).
801  *
802  * Note, in reserving a device, if the device is for the
803  *  same pool and the same pool type, then it is acceptable.
804  *  The Media Type has already been checked. If we are
805  *  the first tor reserve the device, we put the pool
806  *  name and pool type in the device record.
807  */
808 static bool reserve_device_for_append(DCR *dcr, RCTX &rctx)
809 {
810    JCR *jcr = dcr->jcr;
811    DEVICE *dev = dcr->dev;
812    bool ok = false;
813
814    ASSERT(dcr);
815    if (job_canceled(jcr)) {
816       return false;
817    }
818
819    dev->dlock();
820
821    /* If device is being read, we cannot write it */
822    if (dev->can_read()) {
823       Mmsg(jcr->errmsg, _("3603 JobId=%u device %s is busy reading.\n"), 
824          jcr->JobId, dev->print_name());
825       Dmsg1(dbglvl, "%s", jcr->errmsg);
826       queue_reserve_message(jcr);
827       goto bail_out;
828    }
829
830    /* If device is unmounted, we are out of luck */
831    if (is_device_unmounted(dev)) {
832       Mmsg(jcr->errmsg, _("3604 JobId=%u device %s is BLOCKED due to user unmount.\n"), 
833          jcr->JobId, dev->print_name());
834       Dmsg1(dbglvl, "%s", jcr->errmsg);
835       queue_reserve_message(jcr);
836       goto bail_out;
837    }
838
839    Dmsg1(dbglvl, "reserve_append device is %s\n", dev->print_name());
840
841    /* Now do detailed tests ... */
842    if (can_reserve_drive(dcr, rctx) != 1) {
843       Dmsg0(dbglvl, "can_reserve_drive!=1\n");
844       goto bail_out;
845    }
846
847    dcr->set_reserved();
848    ok = true;
849
850 bail_out:
851    dev->dunlock();
852    return ok;
853 }
854
855 static int is_pool_ok(DCR *dcr)
856 {
857    DEVICE *dev = dcr->dev;
858    JCR *jcr = dcr->jcr;
859
860    /* Now check if we want the same Pool and pool type */
861    if (strcmp(dev->pool_name, dcr->pool_name) == 0 &&
862        strcmp(dev->pool_type, dcr->pool_type) == 0) {
863       /* OK, compatible device */
864       Dmsg1(dbglvl, "OK dev: %s num_writers=0, reserved, pool matches\n", dev->print_name());
865       return 1;
866    } else {
867       /* Drive Pool not suitable for us */
868       Mmsg(jcr->errmsg, _(
869 "3608 JobId=%u wants Pool=\"%s\" but have Pool=\"%s\" nreserve=%d on drive %s.\n"), 
870             (uint32_t)jcr->JobId, dcr->pool_name, dev->pool_name,
871             dev->num_reserved(), dev->print_name());
872       queue_reserve_message(jcr);
873       Dmsg2(dbglvl, "failed: busy num_writers=0, reserved, pool=%s wanted=%s\n",
874          dev->pool_name, dcr->pool_name);
875    }
876    return 0;
877 }
878
879 static bool is_max_jobs_ok(DCR *dcr) 
880 {
881    DEVICE *dev = dcr->dev;
882    JCR *jcr = dcr->jcr;
883
884    Dmsg5(dbglvl, "MaxJobs=%d Jobs=%d reserves=%d Status=%s Vol=%s\n",
885          dcr->VolCatInfo.VolCatMaxJobs,
886          dcr->VolCatInfo.VolCatJobs, dev->num_reserved(),
887          dcr->VolCatInfo.VolCatStatus,
888          dcr->VolumeName);
889    if (strcmp(dcr->VolCatInfo.VolCatStatus, "Recycle") == 0) {
890       return true;
891    }
892    if (dcr->VolCatInfo.VolCatMaxJobs > 0 && dcr->VolCatInfo.VolCatMaxJobs <=
893         (dcr->VolCatInfo.VolCatJobs + dev->num_reserved())) {
894       /* Max Job Vols depassed or already reserved */
895       Mmsg(jcr->errmsg, _("3610 JobId=%u Volume max jobs exceeded on drive %s.\n"), 
896             (uint32_t)jcr->JobId, dev->print_name());
897       queue_reserve_message(jcr);
898       Dmsg1(dbglvl, "reserve dev failed: %s", jcr->errmsg);
899       return false;                /* wait */
900    }
901    return true;
902 }
903
904 /*
905  * Returns: 1 if drive can be reserved
906  *          0 if we should wait
907  *         -1 on error or impossibility
908  */
909 static int can_reserve_drive(DCR *dcr, RCTX &rctx) 
910 {
911    DEVICE *dev = dcr->dev;
912    JCR *jcr = dcr->jcr;
913
914    Dmsg5(dbglvl, "PrefMnt=%d exact=%d suitable=%d chgronly=%d any=%d\n",
915          rctx.PreferMountedVols, rctx.exact_match, rctx.suitable_device,
916          rctx.autochanger_only, rctx.any_drive);
917
918    /* Check for max jobs on this Volume */
919    if (!is_max_jobs_ok(dcr)) {
920       return 0;
921    }
922
923    /* setting any_drive overrides PreferMountedVols flag */
924    if (!rctx.any_drive) {
925       /*
926        * When PreferMountedVols is set, we keep track of the 
927        *  drive in use that has the least number of writers, then if
928        *  no unmounted drive is found, we try that drive. This   
929        *  helps spread the load to the least used drives.  
930        */
931       if (rctx.try_low_use_drive && dev == rctx.low_use_drive) {
932          Dmsg2(dbglvl, "OK dev=%s == low_drive=%s.\n",
933             dev->print_name(), rctx.low_use_drive->print_name());
934          return 1;
935       }
936       /* If he wants a free drive, but this one is busy, no go */
937       if (!rctx.PreferMountedVols && dev->is_busy()) {
938          /* Save least used drive */
939          if ((dev->num_writers + dev->num_reserved()) < rctx.num_writers) {
940             rctx.num_writers = dev->num_writers + dev->num_reserved();
941             rctx.low_use_drive = dev;
942             Dmsg2(dbglvl, "set low use drive=%s num_writers=%d\n", 
943                dev->print_name(), rctx.num_writers);
944          } else {
945             Dmsg1(dbglvl, "not low use num_writers=%d\n", dev->num_writers+dev->num_reserved());
946          }
947          Dmsg0(dbglvl, "failed: !prefMnt && busy.\n");
948          Mmsg(jcr->errmsg, _("3605 JobId=%u wants free drive but device %s is busy.\n"), 
949             jcr->JobId, dev->print_name());
950          queue_reserve_message(jcr);
951          return 0;
952       }
953
954       /* Check for prefer mounted volumes */
955       if (rctx.PreferMountedVols && !dev->vol && dev->is_tape()) {
956          Mmsg(jcr->errmsg, _("3606 JobId=%u prefers mounted drives, but drive %s has no Volume.\n"), 
957             jcr->JobId, dev->print_name());
958          queue_reserve_message(jcr);
959          Dmsg0(dbglvl, "failed: want mounted -- no vol\n");
960          return 0;                 /* No volume mounted */
961       }
962
963       /* Check for exact Volume name match */
964       /* ***FIXME*** for Disk, we can accept any volume that goes with this
965        *    drive.
966        */
967       if (rctx.exact_match && rctx.have_volume) {
968          bool ok;
969          Dmsg5(dbglvl, "PrefMnt=%d exact=%d suitable=%d chgronly=%d any=%d\n",
970                rctx.PreferMountedVols, rctx.exact_match, rctx.suitable_device,
971                rctx.autochanger_only, rctx.any_drive);
972          Dmsg4(dbglvl, "have_vol=%d have=%s resvol=%s want=%s\n",
973                   rctx.have_volume, dev->VolHdr.VolumeName, 
974                   dev->vol?dev->vol->vol_name:"*none*", rctx.VolumeName);
975          ok = strcmp(dev->VolHdr.VolumeName, rctx.VolumeName) == 0 ||
976                  (dev->vol && strcmp(dev->vol->vol_name, rctx.VolumeName) == 0);
977          if (!ok) {
978             Mmsg(jcr->errmsg, _("3607 JobId=%u wants Vol=\"%s\" drive has Vol=\"%s\" on drive %s.\n"), 
979                jcr->JobId, rctx.VolumeName, dev->VolHdr.VolumeName, 
980                dev->print_name());
981             queue_reserve_message(jcr);
982             Dmsg3(dbglvl, "not OK: dev have=%s resvol=%s want=%s\n",
983                   dev->VolHdr.VolumeName, dev->vol?dev->vol->vol_name:"*none*", rctx.VolumeName);
984             return 0;
985          }
986          if (!dcr->can_i_use_volume()) {
987             return 0;              /* fail if volume on another drive */
988          }
989       }
990    }
991
992    /* Check for unused autochanger drive */
993    if (rctx.autochanger_only && !dev->is_busy() &&
994        dev->VolHdr.VolumeName[0] == 0) {
995       /* Device is available but not yet reserved, reserve it for us */
996       Dmsg1(dbglvl, "OK Res Unused autochanger %s.\n", dev->print_name());
997       bstrncpy(dev->pool_name, dcr->pool_name, sizeof(dev->pool_name));
998       bstrncpy(dev->pool_type, dcr->pool_type, sizeof(dev->pool_type));
999       return 1;                       /* reserve drive */
1000    }
1001
1002    /*
1003     * Handle the case that there are no writers
1004     */
1005    if (dev->num_writers == 0) {
1006       /* Now check if there are any reservations on the drive */
1007       if (dev->num_reserved()) {           
1008          return is_pool_ok(dcr);
1009       } else if (dev->can_append()) {
1010          if (is_pool_ok(dcr)) {
1011             return 1; 
1012          } else {
1013             /* Changing pool, unload old tape if any in drive */
1014             Dmsg0(dbglvl, "OK dev: num_writers=0, not reserved, pool change, unload changer\n");
1015             /* ***FIXME*** use set_unload() */
1016             unload_autochanger(dcr, -1);
1017          }
1018       }
1019       /* Device is available but not yet reserved, reserve it for us */
1020       Dmsg1(dbglvl, "OK Dev avail reserved %s\n", dev->print_name());
1021       bstrncpy(dev->pool_name, dcr->pool_name, sizeof(dev->pool_name));
1022       bstrncpy(dev->pool_type, dcr->pool_type, sizeof(dev->pool_type));
1023       return 1;                       /* reserve drive */
1024    }
1025
1026    /*
1027     * Check if the device is in append mode with writers (i.e.
1028     *  available if pool is the same).
1029     */
1030    if (dev->can_append() || dev->num_writers > 0) {
1031       return is_pool_ok(dcr);
1032    } else {
1033       Pmsg1(000, _("Logic error!!!! JobId=%u Should not get here.\n"), (int)jcr->JobId);
1034       Mmsg(jcr->errmsg, _("3910 JobId=%u Logic error!!!! drive %s Should not get here.\n"),
1035             jcr->JobId, dev->print_name());
1036       queue_reserve_message(jcr);
1037       Jmsg0(jcr, M_FATAL, 0, _("Logic error!!!! Should not get here.\n"));
1038       return -1;                      /* error, should not get here */
1039    }
1040    Mmsg(jcr->errmsg, _("3911 JobId=%u failed reserve drive %s.\n"), 
1041          jcr->JobId, dev->print_name());
1042    queue_reserve_message(jcr);
1043    Dmsg1(dbglvl, "failed: No reserve %s\n", dev->print_name());
1044    return 0;
1045 }
1046
1047
1048
1049
1050 /*
1051  * Queue a reservation error or failure message for this jcr
1052  */
1053 static void queue_reserve_message(JCR *jcr)
1054 {
1055    int i;   
1056    alist *msgs;
1057    char *msg;
1058
1059    jcr->lock();
1060
1061    msgs = jcr->reserve_msgs;
1062    if (!msgs) {
1063       goto bail_out;
1064    }
1065    /*
1066     * Look for duplicate message.  If found, do
1067     * not insert
1068     */
1069    for (i=msgs->size()-1; i >= 0; i--) {
1070       msg = (char *)msgs->get(i);
1071       if (!msg) {
1072          goto bail_out;
1073       }
1074       /* Comparison based on 4 digit message number */
1075       if (strncmp(msg, jcr->errmsg, 4) == 0) {
1076          goto bail_out;
1077       }
1078    }      
1079    /* Message unique, so insert it */
1080    jcr->reserve_msgs->push(bstrdup(jcr->errmsg));
1081
1082 bail_out:
1083    jcr->unlock();
1084 }
1085
1086 /*
1087  * Send any reservation messages queued for this jcr
1088  */
1089 void send_drive_reserve_messages(JCR *jcr, void sendit(const char *msg, int len, void *sarg), void *arg)
1090 {
1091    int i;
1092    alist *msgs;
1093    char *msg;
1094
1095    jcr->lock();
1096    msgs = jcr->reserve_msgs;
1097    if (!msgs || msgs->size() == 0) {
1098       goto bail_out;
1099    }
1100    for (i=msgs->size()-1; i >= 0; i--) {
1101       msg = (char *)msgs->get(i);
1102       if (msg) {
1103          sendit("   ", 3, arg);
1104          sendit(msg, strlen(msg), arg);
1105       } else {
1106          break;
1107       }
1108    }
1109
1110 bail_out:
1111    jcr->unlock();
1112 }
1113
1114 /*
1115  * Pop and release any reservations messages
1116  */
1117 static void pop_reserve_messages(JCR *jcr)
1118 {
1119    alist *msgs;
1120    char *msg;
1121
1122    jcr->lock();
1123    msgs = jcr->reserve_msgs;
1124    if (!msgs) {
1125       goto bail_out;
1126    }
1127    while ((msg = (char *)msgs->pop())) {
1128       free(msg);
1129    }
1130 bail_out:
1131    jcr->unlock();
1132 }
1133
1134 /*
1135  * Also called from acquire.c 
1136  */
1137 void release_reserve_messages(JCR *jcr)
1138 {
1139    pop_reserve_messages(jcr);
1140    jcr->lock();
1141    if (!jcr->reserve_msgs) {
1142       goto bail_out;
1143    }
1144    delete jcr->reserve_msgs;
1145    jcr->reserve_msgs = NULL;
1146
1147 bail_out:
1148    jcr->unlock();
1149 }