2 * Copyright (C) 2014 Internet Systems Consortium, Inc. ("ISC")
4 * Permission to use, copy, modify, and/or distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
8 * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
9 * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
10 * AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
11 * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
12 * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
13 * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
14 * PERFORMANCE OF THIS SOFTWARE.
23 #include <isc/counter.h>
24 #include <isc/magic.h>
28 #define COUNTER_MAGIC ISC_MAGIC('C', 'n', 't', 'r')
29 #define VALID_COUNTER(r) ISC_MAGIC_VALID(r, COUNTER_MAGIC)
35 unsigned int references;
41 isc_counter_create(isc_mem_t *mctx, int limit, isc_counter_t **counterp) {
43 isc_counter_t *counter;
45 REQUIRE(counterp != NULL && *counterp == NULL);
47 counter = isc_mem_get(mctx, sizeof(*counter));
49 return (ISC_R_NOMEMORY);
51 result = isc_mutex_init(&counter->lock);
52 if (result != ISC_R_SUCCESS) {
53 isc_mem_put(mctx, counter, sizeof(*counter));
58 isc_mem_attach(mctx, &counter->mctx);
60 counter->references = 1;
61 counter->limit = limit;
64 counter->magic = COUNTER_MAGIC;
66 return (ISC_R_SUCCESS);
70 isc_counter_increment(isc_counter_t *counter) {
71 isc_result_t result = ISC_R_SUCCESS;
75 if (counter->limit != 0 && counter->used >= counter->limit)
77 UNLOCK(&counter->lock);
83 isc_counter_used(isc_counter_t *counter) {
84 REQUIRE(VALID_COUNTER(counter));
86 return (counter->used);
90 isc_counter_setlimit(isc_counter_t *counter, int limit) {
91 REQUIRE(VALID_COUNTER(counter));
94 counter->limit = limit;
95 UNLOCK(&counter->lock);
99 isc_counter_attach(isc_counter_t *source, isc_counter_t **targetp) {
100 REQUIRE(VALID_COUNTER(source));
101 REQUIRE(targetp != NULL && *targetp == NULL);
104 source->references++;
105 INSIST(source->references > 0);
106 UNLOCK(&source->lock);
112 destroy(isc_counter_t *counter) {
114 isc_mutex_destroy(&counter->lock);
115 isc_mem_putanddetach(&counter->mctx, counter, sizeof(*counter));
119 isc_counter_detach(isc_counter_t **counterp) {
120 isc_counter_t *counter;
121 isc_boolean_t want_destroy = ISC_FALSE;
123 REQUIRE(counterp != NULL && *counterp != NULL);
125 REQUIRE(VALID_COUNTER(counter));
129 LOCK(&counter->lock);
130 INSIST(counter->references > 0);
131 counter->references--;
132 if (counter->references == 0)
133 want_destroy = ISC_TRUE;
134 UNLOCK(&counter->lock);