Update from 2.3.14.
[kopensolaris-gnu/glibc.git] / db2 / lock / lock.c
1 /*-
2  * See the file LICENSE for redistribution information.
3  *
4  * Copyright (c) 1996, 1997
5  *      Sleepycat Software.  All rights reserved.
6  */
7
8 #include "config.h"
9
10 #ifndef lint
11 static const char sccsid[] = "@(#)lock.c        10.41 (Sleepycat) 11/28/97";
12 #endif /* not lint */
13
14 #ifndef NO_SYSTEM_INCLUDES
15 #include <sys/types.h>
16 #include <sys/mman.h>
17 #include <sys/stat.h>
18
19 #include <errno.h>
20 #include <fcntl.h>
21 #include <stddef.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <unistd.h>
26 #endif
27
28 #include "db_int.h"
29 #include "shqueue.h"
30 #include "db_page.h"
31 #include "db_shash.h"
32 #include "lock.h"
33 #include "common_ext.h"
34 #include "db_am.h"
35
36 static void __lock_checklocker __P((DB_LOCKTAB *, struct __db_lock *, int));
37 static int  __lock_count_locks __P((DB_LOCKREGION *));
38 static int  __lock_count_objs __P((DB_LOCKREGION *));
39 static int  __lock_create __P((const char *, int, DB_ENV *));
40 static void __lock_freeobj __P((DB_LOCKTAB *, DB_LOCKOBJ *));
41 static int  __lock_get_internal __P((DB_LOCKTAB *, u_int32_t, int, const DBT *,
42     db_lockmode_t, struct __db_lock **));
43 static int  __lock_grow_region __P((DB_LOCKTAB *, int, size_t));
44 static int  __lock_put_internal __P((DB_LOCKTAB *, struct __db_lock *, int));
45 static void __lock_remove_waiter
46     __P((DB_LOCKTAB *, DB_LOCKOBJ *, struct __db_lock *, db_status_t));
47 static void __lock_reset_region __P((DB_LOCKTAB *));
48 static int  __lock_validate_region __P((DB_LOCKTAB *));
49 #ifdef DEBUG
50 static void __lock_dump_locker __P((DB_LOCKTAB *, DB_LOCKOBJ *));
51 static void __lock_dump_object __P((DB_LOCKTAB *, DB_LOCKOBJ *));
52 static void __lock_printlock __P((DB_LOCKTAB *, struct __db_lock *, int));
53 #endif
54
55 /*
56  * Create and initialize a lock region in shared memory.
57  */
58
59 /*
60  * __lock_create --
61  *      Create the lock region.  Returns an errno.  In most cases,
62  * the errno should be that returned by __db_ropen, in which case
63  * an EAGAIN means that we should retry, and an EEXIST means that
64  * the region exists and we didn't need to create it.  Any other
65  * sort of errno should be treated as a system error, leading to a
66  * failure of the original interface call.
67  */
68 static int
69 __lock_create(path, mode, dbenv)
70         const char *path;
71         int mode;
72         DB_ENV *dbenv;
73 {
74         struct __db_lock *lp;
75         struct lock_header *tq_head;
76         struct obj_header *obj_head;
77         DB_LOCKOBJ *op;
78         DB_LOCKREGION *lrp;
79         u_int maxlocks;
80         u_int32_t i;
81         int fd, lock_modes, nelements, ret;
82         u_int8_t *conflicts, *curaddr;
83
84         maxlocks = dbenv == NULL || dbenv->lk_max == 0 ?
85             DB_LOCK_DEFAULT_N : dbenv->lk_max;
86         lock_modes = dbenv == NULL || dbenv->lk_modes == 0 ?
87             DB_LOCK_RW_N : dbenv->lk_modes;
88         conflicts = dbenv == NULL || dbenv->lk_conflicts == NULL ?
89             (u_int8_t *)db_rw_conflicts : dbenv->lk_conflicts;
90
91         if ((ret =
92             __db_rcreate(dbenv, DB_APP_NONE, path, DB_DEFAULT_LOCK_FILE, mode,
93             LOCK_REGION_SIZE(lock_modes, maxlocks, __db_tablesize(maxlocks)),
94             0, &fd, &lrp)) != 0)
95                 return (ret);
96
97         /* Region exists; now initialize it. */
98         lrp->table_size = __db_tablesize(maxlocks);
99         lrp->magic = DB_LOCKMAGIC;
100         lrp->version = DB_LOCKVERSION;
101         lrp->id = 0;
102         lrp->maxlocks = maxlocks;
103         lrp->need_dd = 0;
104         lrp->detect = DB_LOCK_NORUN;
105         lrp->numobjs = maxlocks;
106         lrp->nlockers = 0;
107         lrp->mem_bytes = ALIGN(STRING_SIZE(maxlocks), sizeof(size_t));
108         lrp->increment = lrp->hdr.size / 2;
109         lrp->nmodes = lock_modes;
110         lrp->nconflicts = 0;
111         lrp->nrequests = 0;
112         lrp->nreleases = 0;
113         lrp->ndeadlocks = 0;
114
115         /*
116          * As we write the region, we've got to maintain the alignment
117          * for the structures that follow each chunk.  This information
118          * ends up being encapsulated both in here as well as in the
119          * lock.h file for the XXX_SIZE macros.
120          */
121         /* Initialize conflict matrix. */
122         curaddr = (u_int8_t *)lrp + sizeof(DB_LOCKREGION);
123         memcpy(curaddr, conflicts, lock_modes * lock_modes);
124         curaddr += lock_modes * lock_modes;
125
126         /*
127          * Initialize hash table.
128          */
129         curaddr = (u_int8_t *)ALIGNP(curaddr, LOCK_HASH_ALIGN);
130         lrp->hash_off = curaddr - (u_int8_t *)lrp;
131         nelements = lrp->table_size;
132         __db_hashinit(curaddr, nelements);
133         curaddr += nelements * sizeof(DB_HASHTAB);
134
135         /*
136          * Initialize locks onto a free list. Since locks contains mutexes,
137          * we need to make sure that each lock is aligned on a MUTEX_ALIGNMENT
138          * boundary.
139          */
140         curaddr = (u_int8_t *)ALIGNP(curaddr, MUTEX_ALIGNMENT);
141         tq_head = &lrp->free_locks;
142         SH_TAILQ_INIT(tq_head);
143
144         for (i = 0; i++ < maxlocks;
145             curaddr += ALIGN(sizeof(struct __db_lock), MUTEX_ALIGNMENT)) {
146                 lp = (struct __db_lock *)curaddr;
147                 lp->status = DB_LSTAT_FREE;
148                 SH_TAILQ_INSERT_HEAD(tq_head, lp, links, __db_lock);
149         }
150
151         /* Initialize objects onto a free list.  */
152         obj_head = &lrp->free_objs;
153         SH_TAILQ_INIT(obj_head);
154
155         for (i = 0; i++ < maxlocks; curaddr += sizeof(DB_LOCKOBJ)) {
156                 op = (DB_LOCKOBJ *)curaddr;
157                 SH_TAILQ_INSERT_HEAD(obj_head, op, links, __db_lockobj);
158         }
159
160         /*
161          * Initialize the string space; as for all shared memory allocation
162          * regions, this requires size_t alignment, since we store the
163          * lengths of malloc'd areas in the area..
164          */
165         curaddr = (u_int8_t *)ALIGNP(curaddr, sizeof(size_t));
166         lrp->mem_off = curaddr - (u_int8_t *)lrp;
167         __db_shalloc_init(curaddr, lrp->mem_bytes);
168
169         /* Release the lock. */
170         (void)__db_mutex_unlock(&lrp->hdr.lock, fd);
171
172         /* Now unmap the region. */
173         if ((ret = __db_rclose(dbenv, fd, lrp)) != 0) {
174                 (void)lock_unlink(path, 1 /* force */, dbenv);
175                 return (ret);
176         }
177
178         return (0);
179 }
180
181 int
182 lock_open(path, flags, mode, dbenv, ltp)
183         const char *path;
184         int flags, mode;
185         DB_ENV *dbenv;
186         DB_LOCKTAB **ltp;
187 {
188         DB_LOCKTAB *lt;
189         int ret, retry_cnt;
190
191         /* Validate arguments. */
192 #ifdef HAVE_SPINLOCKS
193 #define OKFLAGS (DB_CREATE | DB_THREAD)
194 #else
195 #define OKFLAGS (DB_CREATE)
196 #endif
197         if ((ret = __db_fchk(dbenv, "lock_open", flags, OKFLAGS)) != 0)
198                 return (ret);
199
200         /*
201          * Create the lock table structure.
202          */
203         if ((lt = (DB_LOCKTAB *)__db_calloc(1, sizeof(DB_LOCKTAB))) == NULL) {
204                 __db_err(dbenv, "%s", strerror(ENOMEM));
205                 return (ENOMEM);
206         }
207         lt->dbenv = dbenv;
208
209         /*
210          * Now, create the lock region if it doesn't already exist.
211          */
212         retry_cnt = 0;
213 retry:  if (LF_ISSET(DB_CREATE) &&
214             (ret = __lock_create(path, mode, dbenv)) != 0)
215                 if (ret == EAGAIN && ++retry_cnt < 3) {
216                         (void)__db_sleep(1, 0);
217                         goto retry;
218                 } else if (ret == EEXIST) /* We did not create the region */
219                         LF_CLR(DB_CREATE);
220                 else
221                         goto out;
222
223         /*
224          * Finally, open the region, map it in, and increment the
225          * reference count.
226          */
227         retry_cnt = 0;
228 retry1: if ((ret = __db_ropen(dbenv, DB_APP_NONE, path, DB_DEFAULT_LOCK_FILE,
229             LF_ISSET(~(DB_CREATE | DB_THREAD)), &lt->fd, &lt->region)) != 0) {
230                 if (ret == EAGAIN && ++retry_cnt < 3) {
231                         (void)__db_sleep(1, 0);
232                         goto retry1;
233                 }
234                 goto out;
235          }
236
237         if (lt->region->magic != DB_LOCKMAGIC) {
238                 __db_err(dbenv, "lock_open: Bad magic number");
239                 ret = EINVAL;
240                 goto out;
241         }
242
243         /* Check for automatic deadlock detection. */
244         if (dbenv->lk_detect != DB_LOCK_NORUN) {
245                 if (lt->region->detect != DB_LOCK_NORUN &&
246                     dbenv->lk_detect != DB_LOCK_DEFAULT &&
247                     lt->region->detect != dbenv->lk_detect) {
248                         __db_err(dbenv,
249                             "lock_open: incompatible deadlock detector mode");
250                         ret = EINVAL;
251                         goto out;
252                 }
253                 if (lt->region->detect == DB_LOCK_NORUN)
254                         lt->region->detect = dbenv->lk_detect;
255         }
256
257         /* Set up remaining pointers into region. */
258         lt->conflicts = (u_int8_t *)lt->region + sizeof(DB_LOCKREGION);
259         lt->hashtab =
260             (DB_HASHTAB *)((u_int8_t *)lt->region + lt->region->hash_off);
261         lt->mem = (void *)((u_int8_t *)lt->region + lt->region->mem_off);
262         lt->reg_size = lt->region->hdr.size;
263
264         *ltp = lt;
265         return (0);
266
267 /* Error handling. */
268 out:    if (lt->region != NULL)
269                 (void)__db_rclose(lt->dbenv, lt->fd, lt->region);
270         if (LF_ISSET(DB_CREATE))
271                 (void)lock_unlink(path, 1, lt->dbenv);
272         __db_free(lt);
273         return (ret);
274 }
275
276 int
277 lock_id (lt, idp)
278         DB_LOCKTAB *lt;
279         u_int32_t *idp;
280 {
281         u_int32_t id;
282
283         LOCK_LOCKREGION(lt);
284         if (lt->region->id >= DB_LOCK_MAXID)
285                 lt->region->id = 0;
286         id = ++lt->region->id;
287         UNLOCK_LOCKREGION(lt);
288
289         *idp = id;
290         return (0);
291 }
292
293 int
294 lock_vec(lt, locker, flags, list, nlist, elistp)
295         DB_LOCKTAB *lt;
296         u_int32_t locker;
297         int flags, nlist;
298         DB_LOCKREQ *list, **elistp;
299 {
300         struct __db_lock *lp;
301         DB_LOCKOBJ *sh_obj, *sh_locker;
302         int i, ret, run_dd;
303
304         /* Validate arguments. */
305         if ((ret =
306             __db_fchk(lt->dbenv, "lock_vec", flags, DB_LOCK_NOWAIT)) != 0)
307                 return (ret);
308
309         LOCK_LOCKREGION(lt);
310
311         if ((ret = __lock_validate_region(lt)) != 0) {
312                 UNLOCK_LOCKREGION(lt);
313                 return (ret);
314         }
315
316         ret = 0;
317         for (i = 0; i < nlist && ret == 0; i++) {
318                 switch (list[i].op) {
319                 case DB_LOCK_GET:
320                         ret = __lock_get_internal(lt, locker, flags,
321                             list[i].obj, list[i].mode, &lp);
322                         if (ret == 0) {
323                                 list[i].lock = LOCK_TO_OFFSET(lt, lp);
324                                 lt->region->nrequests++;
325                         }
326                         break;
327                 case DB_LOCK_PUT:
328                         lp = OFFSET_TO_LOCK(lt, list[i].lock);
329                         if (lp->holder != locker) {
330                                 ret = DB_LOCK_NOTHELD;
331                                 break;
332                         }
333                         list[i].mode = lp->mode;
334
335                         /* XXX Need to copy the object. ??? */
336                         ret = __lock_put_internal(lt, lp, 0);
337                         break;
338                 case DB_LOCK_PUT_ALL:
339                         /* Find the locker. */
340                         if ((ret = __lock_getobj(lt, locker,
341                             NULL, DB_LOCK_LOCKER, &sh_locker)) != 0)
342                                 break;
343
344                         for (lp = SH_LIST_FIRST(&sh_locker->heldby, __db_lock);
345                             lp != NULL;
346                             lp = SH_LIST_FIRST(&sh_locker->heldby, __db_lock)) {
347                                 if ((ret = __lock_put_internal(lt, lp, 0)) != 0)
348                                         break;
349                         }
350                         __lock_freeobj(lt, sh_locker);
351                         lt->region->nlockers--;
352                         break;
353                 case DB_LOCK_PUT_OBJ:
354
355                         /* Look up the object in the hash table. */
356                         HASHLOOKUP(lt->hashtab, __db_lockobj, links,
357                             list[i].obj, sh_obj, lt->region->table_size,
358                             __lock_ohash, __lock_cmp);
359                         if (sh_obj == NULL) {
360                                 ret = EINVAL;
361                                 break;
362                         }
363                         /*
364                          * Release waiters first, because they won't cause
365                          * anyone else to be awakened.  If we release the
366                          * lockers first, all the waiters get awakened
367                          * needlessly.
368                          */
369                         for (lp = SH_TAILQ_FIRST(&sh_obj->waiters, __db_lock);
370                             lp != NULL;
371                             lp = SH_TAILQ_FIRST(&sh_obj->waiters, __db_lock)) {
372                                 lt->region->nreleases += lp->refcount;
373                                 __lock_remove_waiter(lt, sh_obj, lp,
374                                     DB_LSTAT_NOGRANT);
375                                 __lock_checklocker(lt, lp, 1);
376                         }
377
378                         for (lp = SH_TAILQ_FIRST(&sh_obj->holders, __db_lock);
379                             lp != NULL;
380                             lp = SH_TAILQ_FIRST(&sh_obj->holders, __db_lock)) {
381
382                                 lt->region->nreleases += lp->refcount;
383                                 SH_LIST_REMOVE(lp, locker_links, __db_lock);
384                                 SH_TAILQ_REMOVE(&sh_obj->holders, lp, links,
385                                     __db_lock);
386                                 lp->status = DB_LSTAT_FREE;
387                                 SH_TAILQ_INSERT_HEAD(&lt->region->free_locks,
388                                     lp, links, __db_lock);
389                         }
390
391                         /* Now free the object. */
392                         __lock_freeobj(lt, sh_obj);
393                         break;
394 #ifdef DEBUG
395                 case DB_LOCK_DUMP:
396                         /* Find the locker. */
397                         if ((ret = __lock_getobj(lt, locker,
398                             NULL, DB_LOCK_LOCKER, &sh_locker)) != 0)
399                                 break;
400
401                         for (lp = SH_LIST_FIRST(&sh_locker->heldby, __db_lock);
402                             lp != NULL;
403                             lp = SH_LIST_NEXT(lp, locker_links, __db_lock)) {
404                                 __lock_printlock(lt, lp, 1);
405                                 ret = EINVAL;
406                         }
407                         if (ret == 0) {
408                                 __lock_freeobj(lt, sh_locker);
409                                 lt->region->nlockers--;
410                         }
411                         break;
412 #endif
413                 default:
414                         ret = EINVAL;
415                         break;
416                 }
417         }
418
419         if (lt->region->need_dd && lt->region->detect != DB_LOCK_NORUN) {
420                 run_dd = 1;
421                 lt->region->need_dd = 0;
422         } else
423                 run_dd = 0;
424
425         UNLOCK_LOCKREGION(lt);
426
427         if (ret == 0 && run_dd)
428                 lock_detect(lt, 0, lt->region->detect);
429
430         if (elistp && ret != 0)
431                 *elistp = &list[i - 1];
432         return (ret);
433 }
434
435 int
436 lock_get(lt, locker, flags, obj, lock_mode, lock)
437         DB_LOCKTAB *lt;
438         u_int32_t locker;
439         int flags;
440         const DBT *obj;
441         db_lockmode_t lock_mode;
442         DB_LOCK *lock;
443 {
444         struct __db_lock *lockp;
445         int ret;
446
447         /* Validate arguments. */
448         if ((ret =
449             __db_fchk(lt->dbenv, "lock_get", flags, DB_LOCK_NOWAIT)) != 0)
450                 return (ret);
451
452         LOCK_LOCKREGION(lt);
453
454         ret = __lock_validate_region(lt);
455         if (ret == 0 && (ret = __lock_get_internal(lt,
456             locker, flags, obj, lock_mode, &lockp)) == 0) {
457                 *lock = LOCK_TO_OFFSET(lt, lockp);
458                 lt->region->nrequests++;
459         }
460
461         UNLOCK_LOCKREGION(lt);
462         return (ret);
463 }
464
465 int
466 lock_put(lt, lock)
467         DB_LOCKTAB *lt;
468         DB_LOCK lock;
469 {
470         struct __db_lock *lockp;
471         int ret, run_dd;
472
473         LOCK_LOCKREGION(lt);
474
475         if ((ret = __lock_validate_region(lt)) != 0)
476                 return (ret);
477         else {
478                 lockp = OFFSET_TO_LOCK(lt, lock);
479                 ret = __lock_put_internal(lt, lockp, 0);
480         }
481
482         __lock_checklocker(lt, lockp, 0);
483
484         if (lt->region->need_dd && lt->region->detect != DB_LOCK_NORUN) {
485                 run_dd = 1;
486                 lt->region->need_dd = 0;
487         } else
488                 run_dd = 0;
489
490         UNLOCK_LOCKREGION(lt);
491
492         if (ret == 0 && run_dd)
493                 lock_detect(lt, 0, lt->region->detect);
494
495         return (ret);
496 }
497
498 int
499 lock_close(lt)
500         DB_LOCKTAB *lt;
501 {
502         int ret;
503
504         if ((ret = __db_rclose(lt->dbenv, lt->fd, lt->region)) != 0)
505                 return (ret);
506
507         /* Free lock table. */
508         __db_free(lt);
509         return (0);
510 }
511
512 int
513 lock_unlink(path, force, dbenv)
514         const char *path;
515         int force;
516         DB_ENV *dbenv;
517 {
518         return (__db_runlink(dbenv,
519             DB_APP_NONE, path, DB_DEFAULT_LOCK_FILE, force));
520 }
521
522 /*
523  * XXX This looks like it could be void, but I'm leaving it returning
524  * an int because I think it will have to when we go through and add
525  * the appropriate error checking for the EINTR on mutexes.
526  */
527 static int
528 __lock_put_internal(lt, lockp, do_all)
529         DB_LOCKTAB *lt;
530         struct __db_lock *lockp;
531         int do_all;
532 {
533         struct __db_lock *lp_w, *lp_h, *next_waiter;
534         DB_LOCKOBJ *sh_obj;
535         int state_changed;
536
537         if (lockp->refcount == 0 || (lockp->status != DB_LSTAT_HELD &&
538             lockp->status != DB_LSTAT_WAITING) || lockp->obj == 0) {
539                 __db_err(lt->dbenv, "lock_put: invalid lock %lu",
540                     (u_long)((u_int8_t *)lockp - (u_int8_t *)lt->region));
541                 return (EINVAL);
542         }
543
544         if (do_all)
545                 lt->region->nreleases += lockp->refcount;
546         else
547                 lt->region->nreleases++;
548         if (do_all == 0 && lockp->refcount > 1) {
549                 lockp->refcount--;
550                 return (0);
551         }
552
553         /* Get the object associated with this lock. */
554         sh_obj = (DB_LOCKOBJ *)((u_int8_t *)lockp + lockp->obj);
555
556         /* Remove lock from locker list. */
557         SH_LIST_REMOVE(lockp, locker_links, __db_lock);
558
559         /* Remove this lock from its holders/waitlist. */
560         if (lockp->status != DB_LSTAT_HELD)
561                 __lock_remove_waiter(lt, sh_obj, lockp, DB_LSTAT_FREE);
562         else
563                 SH_TAILQ_REMOVE(&sh_obj->holders, lockp, links, __db_lock);
564
565         /*
566          * We need to do lock promotion.  We also need to determine if
567          * we're going to need to run the deadlock detector again.  If
568          * we release locks, and there are waiters, but no one gets promoted,
569          * then we haven't fundamentally changed the lockmgr state, so
570          * we may still have a deadlock and we have to run again.  However,
571          * if there were no waiters, or we actually promoted someone, then
572          * we are OK and we don't have to run it immediately.
573          */
574         for (lp_w = SH_TAILQ_FIRST(&sh_obj->waiters, __db_lock),
575             state_changed = lp_w == NULL;
576             lp_w != NULL;
577             lp_w = next_waiter) {
578                 next_waiter = SH_TAILQ_NEXT(lp_w, links, __db_lock);
579                 for (lp_h = SH_TAILQ_FIRST(&sh_obj->holders, __db_lock);
580                     lp_h != NULL;
581                     lp_h = SH_TAILQ_NEXT(lp_h, links, __db_lock)) {
582                         if (CONFLICTS(lt, lp_h->mode, lp_w->mode) &&
583                             lp_h->holder != lp_w->holder)
584                                 break;
585                 }
586                 if (lp_h != NULL)       /* Found a conflict. */
587                         break;
588
589                 /* No conflict, promote the waiting lock. */
590                 SH_TAILQ_REMOVE(&sh_obj->waiters, lp_w, links, __db_lock);
591                 lp_w->status = DB_LSTAT_PENDING;
592                 SH_TAILQ_INSERT_TAIL(&sh_obj->holders, lp_w, links);
593
594                 /* Wake up waiter. */
595                 (void)__db_mutex_unlock(&lp_w->mutex, lt->fd);
596                 state_changed = 1;
597         }
598
599         /* Check if object should be reclaimed. */
600         if (SH_TAILQ_FIRST(&sh_obj->holders, __db_lock) == NULL) {
601                 HASHREMOVE_EL(lt->hashtab, __db_lockobj,
602                     links, sh_obj, lt->region->table_size, __lock_lhash);
603                 if (sh_obj->lockobj.size > sizeof(sh_obj->objdata))
604                         __db_shalloc_free(lt->mem,
605                             SH_DBT_PTR(&sh_obj->lockobj));
606                 SH_TAILQ_INSERT_HEAD(&lt->region->free_objs, sh_obj, links,
607                     __db_lockobj);
608                 state_changed = 1;
609         }
610
611         /* Free lock. */
612         lockp->status = DB_LSTAT_FREE;
613         SH_TAILQ_INSERT_HEAD(&lt->region->free_locks, lockp, links, __db_lock);
614
615         /*
616          * If we did not promote anyone; we need to run the deadlock
617          * detector again.
618          */
619         if (state_changed == 0)
620                 lt->region->need_dd = 1;
621
622         return (0);
623 }
624
625 static int
626 __lock_get_internal(lt, locker, flags, obj, lock_mode, lockp)
627         DB_LOCKTAB *lt;
628         u_int32_t locker;
629         int flags;
630         const DBT *obj;
631         db_lockmode_t lock_mode;
632         struct __db_lock **lockp;
633 {
634         struct __db_lock *newl, *lp;
635         DB_LOCKOBJ *sh_obj, *sh_locker;
636         DB_LOCKREGION *lrp;
637         size_t newl_off;
638         int ihold, ret;
639
640         ret = 0;
641         /*
642          * Check that lock mode is valid.
643          */
644
645         lrp = lt->region;
646         if ((u_int32_t)lock_mode >= lrp->nmodes) {
647                 __db_err(lt->dbenv,
648                     "lock_get: invalid lock mode %lu\n", (u_long)lock_mode);
649                 return (EINVAL);
650         }
651
652         /* Allocate a new lock.  Optimize for the common case of a grant. */
653         if ((newl = SH_TAILQ_FIRST(&lrp->free_locks, __db_lock)) == NULL) {
654                 if ((ret = __lock_grow_region(lt, DB_LOCK_LOCK, 0)) != 0)
655                         return (ret);
656                 lrp = lt->region;
657                 newl = SH_TAILQ_FIRST(&lrp->free_locks, __db_lock);
658         }
659         newl_off = LOCK_TO_OFFSET(lt, newl);
660
661         /* Optimize for common case of granting a lock. */
662         SH_TAILQ_REMOVE(&lrp->free_locks, newl, links, __db_lock);
663
664         newl->mode = lock_mode;
665         newl->status = DB_LSTAT_HELD;
666         newl->holder = locker;
667         newl->refcount = 1;
668
669         if ((ret =
670             __lock_getobj(lt, 0, (DBT *)obj, DB_LOCK_OBJTYPE, &sh_obj)) != 0)
671                 return (ret);
672
673         lrp = lt->region;                       /* getobj might have grown */
674         newl = OFFSET_TO_LOCK(lt, newl_off);
675
676         /* Now make new lock point to object */
677         newl->obj = SH_PTR_TO_OFF(newl, sh_obj);
678
679         /*
680          * Now we have a lock and an object and we need to see if we should
681          * grant the lock.  We use a FIFO ordering so we can only grant a
682          * new lock if it does not conflict with anyone on the holders list
683          * OR anyone on the waiters list.  The reason that we don't grant if
684          * there's a conflict is that this can lead to starvation (a writer
685          * waiting on a popularly read item will never be granted).  The
686          * downside of this is that a waiting reader can prevent an upgrade
687          * from reader to writer, which is not uncommon.
688          *
689          * There is one exception to the no-conflict rule.  If a lock is held
690          * by the requesting locker AND the new lock does not conflict with
691          * any other holders, then we grant the lock.  The most common place
692          * this happens is when the holder has a WRITE lock and a READ lock
693          * request comes in for the same locker.  If we do not grant the read
694          * lock, then we guarantee deadlock.
695          *
696          * In case of conflict, we put the new lock on the end of the waiters
697          * list.
698          */
699         ihold = 0;
700         for (lp = SH_TAILQ_FIRST(&sh_obj->holders, __db_lock);
701             lp != NULL;
702             lp = SH_TAILQ_NEXT(lp, links, __db_lock)) {
703                 if (locker == lp->holder) {
704                         if (lp->mode == lock_mode &&
705                             lp->status == DB_LSTAT_HELD) {
706                                 /* Lock is held, just inc the ref count. */
707                                 lp->refcount++;
708                                 SH_TAILQ_INSERT_HEAD(&lrp->free_locks,
709                                     newl, links, __db_lock);
710                                 *lockp = lp;
711                                 return (0);
712                         } else
713                                 ihold = 1;
714                 } else if (CONFLICTS(lt, lp->mode, lock_mode))
715                         break;
716         }
717
718         if (lp == NULL && !ihold)
719                 for (lp = SH_TAILQ_FIRST(&sh_obj->waiters, __db_lock);
720                     lp != NULL;
721                     lp = SH_TAILQ_NEXT(lp, links, __db_lock)) {
722                         if (CONFLICTS(lt, lp->mode, lock_mode) &&
723                             locker != lp->holder)
724                                 break;
725                 }
726         if (lp == NULL)
727                 SH_TAILQ_INSERT_TAIL(&sh_obj->holders, newl, links);
728         else if (!(flags & DB_LOCK_NOWAIT))
729                 SH_TAILQ_INSERT_TAIL(&sh_obj->waiters, newl, links);
730         else {
731                 /* Free the lock and return an error. */
732                 newl->status = DB_LSTAT_FREE;
733                 SH_TAILQ_INSERT_HEAD(&lrp->free_locks, newl, links, __db_lock);
734                 return (DB_LOCK_NOTGRANTED);
735         }
736
737         /*
738          * This is really a blocker for the process, so initialize it
739          * set.  That way the current process will block when it tries
740          * to get it and the waking process will release it.
741          */
742         (void)__db_mutex_init(&newl->mutex,
743             MUTEX_LOCK_OFFSET(lt->region, &newl->mutex));
744         (void)__db_mutex_lock(&newl->mutex, lt->fd);
745
746         /*
747          * Now, insert the lock onto its locker's list.
748          */
749         if ((ret =
750             __lock_getobj(lt, locker, NULL, DB_LOCK_LOCKER, &sh_locker)) != 0)
751                 return (ret);
752
753         lrp = lt->region;
754         SH_LIST_INSERT_HEAD(&sh_locker->heldby, newl, locker_links, __db_lock);
755
756         if (lp != NULL) {
757                 newl->status = DB_LSTAT_WAITING;
758                 lrp->nconflicts++;
759                 /*
760                  * We are about to wait; must release the region mutex.
761                  * Then, when we wakeup, we need to reacquire the region
762                  * mutex before continuing.
763                  */
764                 if (lrp->detect == DB_LOCK_NORUN)
765                         lt->region->need_dd = 1;
766                 UNLOCK_LOCKREGION(lt);
767
768                 /*
769                  * We are about to wait; before waiting, see if the deadlock
770                  * detector should be run.
771                  */
772                 if (lrp->detect != DB_LOCK_NORUN)
773                         ret = lock_detect(lt, 0, lrp->detect);
774
775                 (void)__db_mutex_lock(&newl->mutex, lt->fd);
776
777                 LOCK_LOCKREGION(lt);
778                 if (newl->status != DB_LSTAT_PENDING) {
779                         /* Return to free list. */
780                         __lock_checklocker(lt, newl, 0);
781                         SH_TAILQ_INSERT_HEAD(&lrp->free_locks, newl, links,
782                             __db_lock);
783                         switch (newl->status) {
784                                 case DB_LSTAT_ABORTED:
785                                         ret = DB_LOCK_DEADLOCK;
786                                         break;
787                                 case DB_LSTAT_NOGRANT:
788                                         ret = DB_LOCK_NOTGRANTED;
789                                         break;
790                                 default:
791                                         ret = EINVAL;
792                                         break;
793                         }
794                         newl->status = DB_LSTAT_FREE;
795                         newl = NULL;
796                 } else
797                         newl->status = DB_LSTAT_HELD;
798         }
799
800         *lockp = newl;
801         return (ret);
802 }
803
804 /*
805  * This is called at every interface to verify if the region
806  * has changed size, and if so, to remap the region in and
807  * reset the process pointers.
808  */
809 static int
810 __lock_validate_region(lt)
811         DB_LOCKTAB *lt;
812 {
813         int ret;
814
815         if (lt->reg_size == lt->region->hdr.size)
816                 return (0);
817
818         /* Grow the region. */
819         if ((ret = __db_rremap(lt->dbenv, lt->region,
820             lt->reg_size, lt->region->hdr.size, lt->fd, &lt->region)) != 0)
821                 return (ret);
822
823         __lock_reset_region(lt);
824
825         return (0);
826 }
827
828 /*
829  * We have run out of space; time to grow the region.
830  */
831 static int
832 __lock_grow_region(lt, which, howmuch)
833         DB_LOCKTAB *lt;
834         int which;
835         size_t howmuch;
836 {
837         struct __db_lock *newl;
838         struct lock_header *lock_head;
839         struct obj_header *obj_head;
840         DB_LOCKOBJ *op;
841         DB_LOCKREGION *lrp;
842         float lock_ratio, obj_ratio;
843         size_t incr, oldsize, used;
844         u_int32_t i, newlocks, newmem, newobjs;
845         int ret, usedlocks, usedmem, usedobjs;
846         u_int8_t *curaddr;
847
848         lrp = lt->region;
849         oldsize = lrp->hdr.size;
850         incr = lrp->increment;
851
852         /* Figure out how much of each sort of space we have. */
853         usedmem = lrp->mem_bytes - __db_shalloc_count(lt->mem);
854         usedobjs = lrp->numobjs - __lock_count_objs(lrp);
855         usedlocks = lrp->maxlocks - __lock_count_locks(lrp);
856
857         /*
858          * Figure out what fraction of the used space belongs to each
859          * different type of "thing" in the region.  Then partition the
860          * new space up according to this ratio.
861          */
862         used = usedmem +
863             usedlocks * ALIGN(sizeof(struct __db_lock), MUTEX_ALIGNMENT) +
864             usedobjs * sizeof(DB_LOCKOBJ);
865
866         lock_ratio = usedlocks *
867             ALIGN(sizeof(struct __db_lock), MUTEX_ALIGNMENT) / (float)used;
868         obj_ratio = usedobjs * sizeof(DB_LOCKOBJ) / (float)used;
869
870         newlocks = (u_int32_t)(lock_ratio *
871             incr / ALIGN(sizeof(struct __db_lock), MUTEX_ALIGNMENT));
872         newobjs = (u_int32_t)(obj_ratio * incr / sizeof(DB_LOCKOBJ));
873         newmem = incr -
874             (newobjs * sizeof(DB_LOCKOBJ) +
875             newlocks * ALIGN(sizeof(struct __db_lock), MUTEX_ALIGNMENT));
876
877         /*
878          * Make sure we allocate enough memory for the object being
879          * requested.
880          */
881         switch (which) {
882                 case DB_LOCK_LOCK:
883                         if (newlocks == 0) {
884                                 newlocks = 10;
885                                 incr += newlocks * sizeof(struct __db_lock);
886                         }
887                         break;
888                 case DB_LOCK_OBJ:
889                         if (newobjs == 0) {
890                                 newobjs = 10;
891                                 incr += newobjs * sizeof(DB_LOCKOBJ);
892                         }
893                         break;
894                 case DB_LOCK_MEM:
895                         if (newmem < howmuch * 2) {
896                                 incr += howmuch * 2 - newmem;
897                                 newmem = howmuch * 2;
898                         }
899                         break;
900         }
901
902         newmem += ALIGN(incr, sizeof(size_t)) - incr;
903         incr = ALIGN(incr, sizeof(size_t));
904
905         /*
906          * Since we are going to be allocating locks at the beginning of the
907          * new chunk, we need to make sure that the chunk is MUTEX_ALIGNMENT
908          * aligned.  We did not guarantee this when we created the region, so
909          * we may need to pad the old region by extra bytes to ensure this
910          * alignment.
911          */
912         incr += ALIGN(oldsize, MUTEX_ALIGNMENT) - oldsize;
913
914         __db_err(lt->dbenv,
915             "Growing lock region: %lu locks %lu objs %lu bytes",
916             (u_long)newlocks, (u_long)newobjs, (u_long)newmem);
917
918         if ((ret = __db_rgrow(lt->dbenv, lt->fd, incr)) != 0)
919                 return (ret);
920         if ((ret = __db_rremap(lt->dbenv,
921             lt->region, oldsize, oldsize + incr, lt->fd, &lt->region)) != 0)
922                 return (ret);
923         __lock_reset_region(lt);
924
925         /* Update region parameters. */
926         lrp = lt->region;
927         lrp->increment = incr << 1;
928         lrp->maxlocks += newlocks;
929         lrp->numobjs += newobjs;
930         lrp->mem_bytes += newmem;
931
932         curaddr = (u_int8_t *)lrp + oldsize;
933         curaddr = (u_int8_t *)ALIGNP(curaddr, MUTEX_ALIGNMENT);
934
935         /* Put new locks onto the free list. */
936         lock_head = &lrp->free_locks;
937         for (i = 0; i++ < newlocks;
938             curaddr += ALIGN(sizeof(struct __db_lock), MUTEX_ALIGNMENT)) {
939                 newl = (struct __db_lock *)curaddr;
940                 SH_TAILQ_INSERT_HEAD(lock_head, newl, links, __db_lock);
941         }
942
943         /* Put new objects onto the free list.  */
944         obj_head = &lrp->free_objs;
945         for (i = 0; i++ < newobjs; curaddr += sizeof(DB_LOCKOBJ)) {
946                 op = (DB_LOCKOBJ *)curaddr;
947                 SH_TAILQ_INSERT_HEAD(obj_head, op, links, __db_lockobj);
948         }
949
950         *((size_t *)curaddr) = newmem - sizeof(size_t);
951         curaddr += sizeof(size_t);
952         __db_shalloc_free(lt->mem, curaddr);
953
954         return (0);
955 }
956
957 #ifdef DEBUG
958 void
959 __lock_dump_region(lt, flags)
960         DB_LOCKTAB *lt;
961         unsigned long flags;
962 {
963         struct __db_lock *lp;
964         DB_LOCKOBJ *op;
965         DB_LOCKREGION *lrp;
966         u_int32_t i, j;
967
968         lrp = lt->region;
969
970         printf("Lock region parameters\n");
971         printf("%s:0x%x\t%s:%lu\t%s:%lu\t%s:%lu\n%s:%lu\t%s:%lu\t%s:%lu\t\n",
972             "magic      ", lrp->magic,
973             "version    ", (u_long)lrp->version,
974             "processes  ", (u_long)lrp->hdr.refcnt,
975             "maxlocks   ", (u_long)lrp->maxlocks,
976             "table size ", (u_long)lrp->table_size,
977             "nmodes     ", (u_long)lrp->nmodes,
978             "numobjs    ", (u_long)lrp->numobjs);
979         printf("%s:%lu\t%s:%lu\t%s:%lu\n%s:%lu\t%s:%lu\t%s:%lu\n",
980             "size       ", (u_long)lrp->hdr.size,
981             "nlockers   ", (u_long)lrp->nlockers,
982             "hash_off   ", (u_long)lrp->hash_off,
983             "increment  ", (u_long)lrp->increment,
984             "mem_off    ", (u_long)lrp->mem_off,
985             "mem_bytes  ", (u_long)lrp->mem_bytes);
986 #ifndef HAVE_SPINLOCKS
987         printf("Mutex: off %lu", (u_long)lrp->hdr.lock.off);
988 #endif
989         printf(" waits %lu nowaits %lu",
990             (u_long)lrp->hdr.lock.mutex_set_wait,
991             (u_long)lrp->hdr.lock.mutex_set_nowait);
992         printf("\n%s:%lu\t%s:%lu\t%s:%lu\t%s:%lu\n",
993             "nconflicts ", (u_long)lrp->nconflicts,
994             "nrequests  ", (u_long)lrp->nrequests,
995             "nreleases  ", (u_long)lrp->nreleases,
996             "ndeadlocks ", (u_long)lrp->ndeadlocks);
997         printf("need_dd    %lu\n", (u_long)lrp->need_dd);
998         if (flags & LOCK_DEBUG_CONF) {
999                 printf("\nConflict matrix\n");
1000
1001                 for (i = 0; i < lrp->nmodes; i++) {
1002                         for (j = 0; j < lrp->nmodes; j++)
1003                                 printf("%lu\t",
1004                                     (u_long)lt->conflicts[i * lrp->nmodes + j]);
1005                         printf("\n");
1006                 }
1007         }
1008
1009         for (i = 0; i < lrp->table_size; i++) {
1010                 op = SH_TAILQ_FIRST(&lt->hashtab[i], __db_lockobj);
1011                 if (op != NULL && flags & LOCK_DEBUG_BUCKET)
1012                         printf("Bucket %lu:\n", (unsigned long)i);
1013                 while (op != NULL) {
1014                         if (op->type == DB_LOCK_LOCKER &&
1015                             flags & LOCK_DEBUG_LOCKERS)
1016                                 __lock_dump_locker(lt, op);
1017                         else if (flags & LOCK_DEBUG_OBJECTS &&
1018                             op->type == DB_LOCK_OBJTYPE)
1019                                 __lock_dump_object(lt, op);
1020                         op = SH_TAILQ_NEXT(op, links, __db_lockobj);
1021                 }
1022         }
1023
1024         if (flags & LOCK_DEBUG_LOCK) {
1025                 printf("\nLock Free List\n");
1026                 for (lp = SH_TAILQ_FIRST(&lrp->free_locks, __db_lock);
1027                     lp != NULL;
1028                     lp = SH_TAILQ_NEXT(lp, links, __db_lock)) {
1029                         printf("0x%x: %lu\t%lu\t%lu\t0x%x\n", (u_int)lp,
1030                             (u_long)lp->holder, (u_long)lp->mode,
1031                             (u_long)lp->status, (u_int)lp->obj);
1032                 }
1033         }
1034
1035         if (flags & LOCK_DEBUG_LOCK) {
1036                 printf("\nObject Free List\n");
1037                 for (op = SH_TAILQ_FIRST(&lrp->free_objs, __db_lockobj);
1038                     op != NULL;
1039                     op = SH_TAILQ_NEXT(op, links, __db_lockobj))
1040                         printf("0x%x\n", (u_int)op);
1041         }
1042
1043         if (flags & LOCK_DEBUG_MEM) {
1044                 printf("\nMemory Free List\n");
1045                 __db_shalloc_dump(stdout, lt->mem);
1046         }
1047 }
1048
1049 static void
1050 __lock_dump_locker(lt, op)
1051         DB_LOCKTAB *lt;
1052         DB_LOCKOBJ *op;
1053 {
1054         struct __db_lock *lp;
1055         u_int32_t locker;
1056         void *ptr;
1057
1058         ptr = SH_DBT_PTR(&op->lockobj);
1059         memcpy(&locker, ptr, sizeof(u_int32_t));
1060         printf("L %lx", (u_long)locker);
1061
1062         lp = SH_LIST_FIRST(&op->heldby, __db_lock);
1063         if (lp == NULL) {
1064                 printf("\n");
1065                 return;
1066         }
1067         for (; lp != NULL; lp = SH_LIST_NEXT(lp, locker_links, __db_lock))
1068                 __lock_printlock(lt, lp, 0);
1069 }
1070
1071 static void
1072 __lock_dump_object(lt, op)
1073         DB_LOCKTAB *lt;
1074         DB_LOCKOBJ *op;
1075 {
1076         struct __db_lock *lp;
1077         u_int32_t j;
1078         char *ptr;
1079
1080         ptr = SH_DBT_PTR(&op->lockobj);
1081         for (j = 0; j < op->lockobj.size; ptr++, j++)
1082                 printf("%c", (int)*ptr);
1083         printf("\n");
1084
1085         printf("H:");
1086         for (lp =
1087             SH_TAILQ_FIRST(&op->holders, __db_lock);
1088             lp != NULL;
1089             lp = SH_TAILQ_NEXT(lp, links, __db_lock))
1090                 __lock_printlock(lt, lp, 0);
1091         lp = SH_TAILQ_FIRST(&op->waiters, __db_lock);
1092         if (lp != NULL) {
1093                 printf("\nW:");
1094                 for (; lp != NULL; lp = SH_TAILQ_NEXT(lp, links, __db_lock))
1095                         __lock_printlock(lt, lp, 0);
1096         }
1097 }
1098
1099 int
1100 __lock_is_locked(lt, locker, dbt, mode)
1101         DB_LOCKTAB *lt;
1102         u_int32_t locker;
1103         DBT *dbt;
1104         db_lockmode_t mode;
1105 {
1106         struct __db_lock *lp;
1107         DB_LOCKOBJ *sh_obj;
1108         DB_LOCKREGION *lrp;
1109
1110         lrp = lt->region;
1111
1112         /* Look up the object in the hash table. */
1113         HASHLOOKUP(lt->hashtab, __db_lockobj, links,
1114             dbt, sh_obj, lrp->table_size, __lock_ohash, __lock_cmp);
1115         if (sh_obj == NULL)
1116                 return (0);
1117
1118         for (lp = SH_TAILQ_FIRST(&sh_obj->holders, __db_lock);
1119             lp != NULL;
1120             lp = SH_TAILQ_FIRST(&sh_obj->holders, __db_lock)) {
1121                 if (lp->holder == locker && lp->mode == mode)
1122                         return (1);
1123         }
1124
1125         return (0);
1126 }
1127
1128 static void
1129 __lock_printlock(lt, lp, ispgno)
1130         DB_LOCKTAB *lt;
1131         struct __db_lock *lp;
1132         int ispgno;
1133 {
1134         DB_LOCKOBJ *lockobj;
1135         db_pgno_t pgno;
1136         size_t obj;
1137         u_int8_t *ptr;
1138         char *mode, *stat;
1139
1140         switch (lp->mode) {
1141         case DB_LOCK_IREAD:
1142                 mode = "IREAD";
1143                 break;
1144         case DB_LOCK_IWR:
1145                 mode = "IWR";
1146                 break;
1147         case DB_LOCK_IWRITE:
1148                 mode = "IWRITE";
1149                 break;
1150         case DB_LOCK_NG:
1151                 mode = "NG";
1152                 break;
1153         case DB_LOCK_READ:
1154                 mode = "READ";
1155                 break;
1156         case DB_LOCK_WRITE:
1157                 mode = "WRITE";
1158                 break;
1159         default:
1160                 mode = "UNKNOWN";
1161                 break;
1162         }
1163         switch (lp->status) {
1164         case DB_LSTAT_ABORTED:
1165                 stat = "ABORT";
1166                 break;
1167         case DB_LSTAT_ERR:
1168                 stat = "ERROR";
1169                 break;
1170         case DB_LSTAT_FREE:
1171                 stat = "FREE";
1172                 break;
1173         case DB_LSTAT_HELD:
1174                 stat = "HELD";
1175                 break;
1176         case DB_LSTAT_NOGRANT:
1177                 stat = "NONE";
1178                 break;
1179         case DB_LSTAT_WAITING:
1180                 stat = "WAIT";
1181                 break;
1182         case DB_LSTAT_PENDING:
1183                 stat = "PENDING";
1184                 break;
1185         default:
1186                 stat = "UNKNOWN";
1187                 break;
1188         }
1189         printf("\t%lx\t%s\t%lu\t%s\t",
1190             (u_long)lp->holder, mode, (u_long)lp->refcount, stat);
1191
1192         lockobj = (DB_LOCKOBJ *)((u_int8_t *)lp + lp->obj);
1193         ptr = SH_DBT_PTR(&lockobj->lockobj);
1194         if (ispgno) {
1195                 /* Assume this is a DBT lock. */
1196                 memcpy(&pgno, ptr, sizeof(db_pgno_t));
1197                 printf("page %lu\n", (u_long)pgno);
1198         } else {
1199                 obj = (u_int8_t *)lp + lp->obj - (u_int8_t *)lt->region;
1200                 printf("0x%lx ", (u_long)obj);
1201                 __db_pr(ptr, lockobj->lockobj.size);
1202                 printf("\n");
1203         }
1204 }
1205
1206 #endif
1207
1208 static int
1209 __lock_count_locks(lrp)
1210         DB_LOCKREGION *lrp;
1211 {
1212         struct __db_lock *newl;
1213         int count;
1214
1215         count = 0;
1216         for (newl = SH_TAILQ_FIRST(&lrp->free_locks, __db_lock);
1217             newl != NULL;
1218             newl = SH_TAILQ_NEXT(newl, links, __db_lock))
1219                 count++;
1220
1221         return (count);
1222 }
1223
1224 static int
1225 __lock_count_objs(lrp)
1226         DB_LOCKREGION *lrp;
1227 {
1228         DB_LOCKOBJ *obj;
1229         int count;
1230
1231         count = 0;
1232         for (obj = SH_TAILQ_FIRST(&lrp->free_objs, __db_lockobj);
1233             obj != NULL;
1234             obj = SH_TAILQ_NEXT(obj, links, __db_lockobj))
1235                 count++;
1236
1237         return (count);
1238 }
1239
1240 /*
1241  * PUBLIC: int __lock_getobj  __P((DB_LOCKTAB *,
1242  * PUBLIC:     u_int32_t, DBT *, u_int32_t type, DB_LOCKOBJ **));
1243  */
1244 int
1245 __lock_getobj(lt, locker, dbt, type, objp)
1246         DB_LOCKTAB *lt;
1247         u_int32_t locker, type;
1248         DBT *dbt;
1249         DB_LOCKOBJ **objp;
1250 {
1251         DB_LOCKREGION *lrp;
1252         DB_LOCKOBJ *sh_obj;
1253         u_int32_t obj_size;
1254         int ret;
1255         void *p, *src;
1256
1257         lrp = lt->region;
1258
1259         /* Look up the object in the hash table. */
1260         if (type == DB_LOCK_OBJTYPE) {
1261                 HASHLOOKUP(lt->hashtab, __db_lockobj, links, dbt, sh_obj,
1262                     lrp->table_size, __lock_ohash, __lock_cmp);
1263                 obj_size = dbt->size;
1264         } else {
1265                 HASHLOOKUP(lt->hashtab, __db_lockobj, links, locker,
1266                     sh_obj, lrp->table_size, __lock_locker_hash,
1267                     __lock_locker_cmp);
1268                 obj_size = sizeof(locker);
1269         }
1270
1271         /*
1272          * If we found the object, then we can just return it.  If
1273          * we didn't find the object, then we need to create it.
1274          */
1275         if (sh_obj == NULL) {
1276                 /* Create new object and then insert it into hash table. */
1277                 if ((sh_obj =
1278                     SH_TAILQ_FIRST(&lrp->free_objs, __db_lockobj)) == NULL) {
1279                         if ((ret = __lock_grow_region(lt, DB_LOCK_OBJ, 0)) != 0)
1280                                 return (ret);
1281                         lrp = lt->region;
1282                         sh_obj = SH_TAILQ_FIRST(&lrp->free_objs, __db_lockobj);
1283                 }
1284
1285                 /*
1286                  * If we can fit this object in the structure, do so instead
1287                  * of shalloc-ing space for it.
1288                  */
1289                 if (obj_size <= sizeof(sh_obj->objdata))
1290                         p = sh_obj->objdata;
1291                 else
1292                         if ((ret =
1293                             __db_shalloc(lt->mem, obj_size, 0, &p)) != 0) {
1294                                 if ((ret = __lock_grow_region(lt,
1295                                     DB_LOCK_MEM, obj_size)) != 0)
1296                                         return (ret);
1297                                 lrp = lt->region;
1298                                 /* Reacquire the head of the list. */
1299                                 sh_obj = SH_TAILQ_FIRST(&lrp->free_objs,
1300                                     __db_lockobj);
1301                                 (void)__db_shalloc(lt->mem, obj_size, 0, &p);
1302                         }
1303
1304                 src = type == DB_LOCK_OBJTYPE ? dbt->data : (void *)&locker;
1305                 memcpy(p, src, obj_size);
1306
1307                 sh_obj->type = type;
1308                 SH_TAILQ_REMOVE(&lrp->free_objs, sh_obj, links, __db_lockobj);
1309
1310                 SH_TAILQ_INIT(&sh_obj->waiters);
1311                 if (type == DB_LOCK_LOCKER)
1312                         SH_LIST_INIT(&sh_obj->heldby);
1313                 else
1314                         SH_TAILQ_INIT(&sh_obj->holders);
1315                 sh_obj->lockobj.size = obj_size;
1316                 sh_obj->lockobj.off = SH_PTR_TO_OFF(&sh_obj->lockobj, p);
1317
1318                 HASHINSERT(lt->hashtab,
1319                     __db_lockobj, links, sh_obj, lrp->table_size, __lock_lhash);
1320
1321                 if (type == DB_LOCK_LOCKER)
1322                         lrp->nlockers++;
1323         }
1324
1325         *objp = sh_obj;
1326         return (0);
1327 }
1328
1329 /*
1330  * Any lock on the waitlist has a process waiting for it.  Therefore, we
1331  * can't return the lock to the freelist immediately.  Instead, we can
1332  * remove the lock from the list of waiters, set the status field of the
1333  * lock, and then let the process waking up return the lock to the
1334  * free list.
1335  */
1336 static void
1337 __lock_remove_waiter(lt, sh_obj, lockp, status)
1338         DB_LOCKTAB *lt;
1339         DB_LOCKOBJ *sh_obj;
1340         struct __db_lock *lockp;
1341         db_status_t status;
1342 {
1343         SH_TAILQ_REMOVE(&sh_obj->waiters, lockp, links, __db_lock);
1344         lockp->status = status;
1345
1346         /* Wake whoever is waiting on this lock. */
1347         (void)__db_mutex_unlock(&lockp->mutex, lt->fd);
1348 }
1349
1350 static void
1351 __lock_freeobj(lt, obj)
1352         DB_LOCKTAB *lt;
1353         DB_LOCKOBJ *obj;
1354 {
1355         HASHREMOVE_EL(lt->hashtab,
1356             __db_lockobj, links, obj, lt->region->table_size, __lock_lhash);
1357         if (obj->lockobj.size > sizeof(obj->objdata))
1358                 __db_shalloc_free(lt->mem, SH_DBT_PTR(&obj->lockobj));
1359         SH_TAILQ_INSERT_HEAD(&lt->region->free_objs, obj, links, __db_lockobj);
1360 }
1361
1362 static void
1363 __lock_checklocker(lt, lockp, do_remove)
1364         DB_LOCKTAB *lt;
1365         struct __db_lock *lockp;
1366         int do_remove;
1367 {
1368         DB_LOCKOBJ *sh_locker;
1369
1370         if (do_remove)
1371                 SH_LIST_REMOVE(lockp, locker_links, __db_lock);
1372
1373         /* if the locker list is NULL, free up the object. */
1374         if (__lock_getobj(lt, lockp->holder, NULL, DB_LOCK_LOCKER, &sh_locker)
1375             == 0 && SH_LIST_FIRST(&sh_locker->heldby, __db_lock) == NULL) {
1376                 __lock_freeobj(lt, sh_locker);
1377                 lt->region->nlockers--;
1378         }
1379 }
1380
1381 static void
1382 __lock_reset_region(lt)
1383         DB_LOCKTAB *lt;
1384 {
1385         lt->conflicts = (u_int8_t *)lt->region + sizeof(DB_LOCKREGION);
1386         lt->hashtab =
1387             (DB_HASHTAB *)((u_int8_t *)lt->region + lt->region->hash_off);
1388         lt->mem = (void *)((u_int8_t *)lt->region + lt->region->mem_off);
1389         lt->reg_size = lt->region->hdr.size;
1390 }