Home | History | Annotate | Line # | Download | only in isc
quota.c revision 1.3
      1 /*	$NetBSD: quota.c,v 1.3 2019/01/09 16:55:14 christos Exp $	*/
      2 
      3 /*
      4  * Copyright (C) Internet Systems Consortium, Inc. ("ISC")
      5  *
      6  * This Source Code Form is subject to the terms of the Mozilla Public
      7  * License, v. 2.0. If a copy of the MPL was not distributed with this
      8  * file, You can obtain one at http://mozilla.org/MPL/2.0/.
      9  *
     10  * See the COPYRIGHT file distributed with this work for additional
     11  * information regarding copyright ownership.
     12  */
     13 
     14 
     15 /*! \file */
     16 
     17 #include <config.h>
     18 
     19 #include <stddef.h>
     20 
     21 #include <isc/quota.h>
     22 #include <isc/util.h>
     23 
     24 void
     25 isc_quota_init(isc_quota_t *quota, int max) {
     26 	quota->max = max;
     27 	quota->used = 0;
     28 	quota->soft = 0;
     29 	isc_mutex_init(&quota->lock);
     30 }
     31 
     32 void
     33 isc_quota_destroy(isc_quota_t *quota) {
     34 	INSIST(quota->used == 0);
     35 	quota->max = 0;
     36 	quota->used = 0;
     37 	quota->soft = 0;
     38 	isc_mutex_destroy(&quota->lock);
     39 }
     40 
     41 void
     42 isc_quota_soft(isc_quota_t *quota, int soft) {
     43 	LOCK(&quota->lock);
     44 	quota->soft = soft;
     45 	UNLOCK(&quota->lock);
     46 }
     47 
     48 void
     49 isc_quota_max(isc_quota_t *quota, int max) {
     50 	LOCK(&quota->lock);
     51 	quota->max = max;
     52 	UNLOCK(&quota->lock);
     53 }
     54 
     55 isc_result_t
     56 isc_quota_reserve(isc_quota_t *quota) {
     57 	isc_result_t result;
     58 	LOCK(&quota->lock);
     59 	if (quota->max == 0 || quota->used < quota->max) {
     60 		if (quota->soft == 0 || quota->used < quota->soft)
     61 			result = ISC_R_SUCCESS;
     62 		else
     63 			result = ISC_R_SOFTQUOTA;
     64 		quota->used++;
     65 	} else
     66 		result = ISC_R_QUOTA;
     67 	UNLOCK(&quota->lock);
     68 	return (result);
     69 }
     70 
     71 void
     72 isc_quota_release(isc_quota_t *quota) {
     73 	LOCK(&quota->lock);
     74 	INSIST(quota->used > 0);
     75 	quota->used--;
     76 	UNLOCK(&quota->lock);
     77 }
     78 
     79 isc_result_t
     80 isc_quota_attach(isc_quota_t *quota, isc_quota_t **p)
     81 {
     82 	isc_result_t result;
     83 	INSIST(p != NULL && *p == NULL);
     84 	result = isc_quota_reserve(quota);
     85 	if (result == ISC_R_SUCCESS || result == ISC_R_SOFTQUOTA)
     86 		*p = quota;
     87 	return (result);
     88 }
     89 
     90 void
     91 isc_quota_detach(isc_quota_t **p)
     92 {
     93 	INSIST(p != NULL && *p != NULL);
     94 	isc_quota_release(*p);
     95 	*p = NULL;
     96 }
     97