Merge from vendor branch GROFF:
[dragonfly.git] / contrib / bind-9.2.4rc7 / lib / isc / quota.c
1 /*
2  * Copyright (C) 2004  Internet Systems Consortium, Inc. ("ISC")
3  * Copyright (C) 2000, 2001  Internet Software Consortium.
4  *
5  * Permission to use, copy, modify, and distribute this software for any
6  * purpose with or without fee is hereby granted, provided that the above
7  * copyright notice and this permission notice appear in all copies.
8  *
9  * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
10  * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
11  * AND FITNESS.  IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
12  * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13  * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
14  * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15  * PERFORMANCE OF THIS SOFTWARE.
16  */
17
18 /* $Id: quota.c,v 1.11.2.1 2004/03/09 06:11:50 marka Exp $ */
19
20 #include <config.h>
21
22 #include <stddef.h>
23
24 #include <isc/quota.h>
25 #include <isc/util.h>
26
27 isc_result_t
28 isc_quota_init(isc_quota_t *quota, int max) {
29         quota->max = max;
30         quota->used = 0;
31         return (isc_mutex_init(&quota->lock));
32 }
33
34 void
35 isc_quota_destroy(isc_quota_t *quota) {
36         INSIST(quota->used == 0);
37         quota->max = -1;
38         quota->used = -1;
39         DESTROYLOCK(&quota->lock);
40 }
41
42 isc_result_t
43 isc_quota_reserve(isc_quota_t *quota) {
44         isc_result_t result;
45         LOCK(&quota->lock);
46         if (quota->used < quota->max) {
47                 quota->used++;
48                 result = ISC_R_SUCCESS;
49         } else {
50                 result = ISC_R_QUOTA;
51         }
52         UNLOCK(&quota->lock);
53         return (result);
54 }
55
56 void
57 isc_quota_release(isc_quota_t *quota) {
58         LOCK(&quota->lock);
59         INSIST(quota->used > 0);
60         quota->used--;
61         UNLOCK(&quota->lock);
62 }
63
64 isc_result_t
65 isc_quota_attach(isc_quota_t *quota, isc_quota_t **p)
66 {
67         isc_result_t result;
68         INSIST(p != NULL && *p == NULL);
69         result = isc_quota_reserve(quota);
70         if (result != ISC_R_SUCCESS)
71                 return (result);
72         *p = quota;
73         return (ISC_R_SUCCESS);
74 }
75
76 void
77 isc_quota_detach(isc_quota_t **p)
78 {
79         INSIST(p != NULL && *p != NULL);
80         isc_quota_release(*p);
81         *p = NULL;
82 }