quota.c 2.26 KB
Newer Older
1
/*
2
 * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
3
 *
4 5 6
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
7 8 9
 *
 * See the COPYRIGHT file distributed with this work for additional
 * information regarding copyright ownership.
10
 */
11

12 13

/*! \file */
David Lawrence's avatar
David Lawrence committed
14

15
#include <config.h>
16

Brian Wellington's avatar
Brian Wellington committed
17 18
#include <stddef.h>

19
#include <isc/atomic.h>
20 21 22
#include <isc/quota.h>
#include <isc/util.h>

23

24
void
25 26 27 28
isc_quota_init(isc_quota_t *quota, unsigned int max) {
	atomic_store(&quota->__max, max);
	atomic_store(&quota->__used, 0);
	atomic_store(&quota->__soft, 0);
29 30 31 32
}

void
isc_quota_destroy(isc_quota_t *quota) {
33 34 35 36
	INSIST(atomic_load(&quota->__used) == 0);
	atomic_store(&quota->__max, 0);
	atomic_store(&quota->__used, 0);
	atomic_store(&quota->__soft, 0);
37 38
}

39
void
40 41
isc_quota_soft(isc_quota_t *quota, unsigned int soft) {
	atomic_store(&quota->__soft, soft);
42 43 44
}

void
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
isc_quota_max(isc_quota_t *quota, unsigned int max) {
	atomic_store(&quota->__max, max);
}

unsigned int
isc_quota_getmax(isc_quota_t *quota) {
	return (atomic_load_relaxed(&quota->__max));
}

unsigned int
isc_quota_getsoft(isc_quota_t *quota) {
	return (atomic_load_relaxed(&quota->__soft));
}

unsigned int
isc_quota_getused(isc_quota_t *quota) {
	return (atomic_load_relaxed(&quota->__used));
62 63
}

64 65 66
isc_result_t
isc_quota_reserve(isc_quota_t *quota) {
	isc_result_t result;
67 68 69 70 71
	uint32_t max = atomic_load(&quota->__max);
	uint32_t soft = atomic_load(&quota->__soft);
	uint32_t used = atomic_fetch_add(&quota->__used, 1);
	if (max == 0 || used < max) {
		if (soft == 0 || used < soft) {
72
			result = ISC_R_SUCCESS;
73
		} else {
74
			result = ISC_R_SOFTQUOTA;
75 76 77
		}
	} else {
		INSIST(atomic_fetch_sub(&quota->__used, 1) > 0);
78
		result = ISC_R_QUOTA;
79
	}
80 81 82 83 84
	return (result);
}

void
isc_quota_release(isc_quota_t *quota) {
85
	INSIST(atomic_fetch_sub(&quota->__used, 1) > 0);
86 87
}

88 89 90 91 92 93
isc_result_t
isc_quota_attach(isc_quota_t *quota, isc_quota_t **p)
{
	isc_result_t result;
	INSIST(p != NULL && *p == NULL);
	result = isc_quota_reserve(quota);
94 95 96
	if (result == ISC_R_SUCCESS || result == ISC_R_SOFTQUOTA)
		*p = quota;
	return (result);
97
}
98

99 100 101 102 103 104 105
void
isc_quota_detach(isc_quota_t **p)
{
	INSIST(p != NULL && *p != NULL);
	isc_quota_release(*p);
	*p = NULL;
}