GCC Code Coverage Report
Directory: ./ Exec Total Coverage
File: usr.bin/ctfconv/pool.c Lines: 0 29 0.0 %
Date: 2017-11-13 Branches: 0 10 0.0 %

Line Branch Exec Source
1
/*	$OpenBSD: pool.c,v 1.3 2017/08/29 21:10:20 deraadt Exp $ */
2
3
/*
4
 * Copyright (c) 2017 Martin Pieuchot
5
 *
6
 * Permission to use, copy, modify, and distribute this software for any
7
 * purpose with or without fee is hereby granted, provided that the above
8
 * copyright notice and this permission notice appear in all copies.
9
 *
10
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17
 */
18
19
#ifndef NOPOOL
20
21
#include <sys/types.h>
22
#include <sys/types.h>
23
#include <sys/queue.h>
24
25
#include <assert.h>
26
#include <stdio.h>
27
#include <stdlib.h>
28
#include <string.h>
29
30
#include "xmalloc.h"
31
#include "pool.h"
32
33
#define MAXIMUM(a, b)	(((a) > (b)) ? (a) : (b))
34
35
struct pool_item {
36
	SLIST_ENTRY(pool_item) pi_list;
37
};
38
39
SIMPLEQ_HEAD(, pool) pool_head = SIMPLEQ_HEAD_INITIALIZER(pool_head);
40
41
void
42
pool_init(struct pool *pp, const char *name, size_t nmemb, size_t size)
43
{
44
	size = MAXIMUM(size, sizeof(struct pool_item));
45
46
	SLIST_INIT(&pp->pr_free);
47
	pp->pr_name = name;
48
	pp->pr_nmemb = nmemb;
49
	pp->pr_size = size;
50
	pp->pr_nitems = 0;
51
	pp->pr_nfree = 0;
52
53
	SIMPLEQ_INSERT_TAIL(&pool_head, pp, pr_list);
54
}
55
56
void *
57
pool_get(struct pool *pp)
58
{
59
	struct pool_item *pi;
60
61
	if (SLIST_EMPTY(&pp->pr_free)) {
62
		char *p;
63
		size_t i;
64
65
		p = xreallocarray(NULL, pp->pr_nmemb, pp->pr_size);
66
		for (i = 0; i < pp->pr_nmemb; i++) {
67
			pi = (struct pool_item *)p;
68
			SLIST_INSERT_HEAD(&pp->pr_free, pi, pi_list);
69
			p += pp->pr_size;
70
		}
71
		pp->pr_nitems += pp->pr_nmemb;
72
		pp->pr_nfree += pp->pr_nmemb;
73
	}
74
75
	pi = SLIST_FIRST(&pp->pr_free);
76
	SLIST_REMOVE_HEAD(&pp->pr_free, pi_list);
77
	pp->pr_nfree--;
78
79
	return pi;
80
}
81
82
void
83
pool_put(struct pool *pp, void *p)
84
{
85
	struct pool_item *pi = (struct pool_item *)p;
86
87
	if (pi == NULL)
88
		return;
89
90
	assert(pp->pr_nfree < pp->pr_nitems);
91
92
	SLIST_INSERT_HEAD(&pp->pr_free, pi, pi_list);
93
	pp->pr_nfree++;
94
}
95
96
void
97
pool_dump(void)
98
{
99
	struct pool *pp;
100
101
	SIMPLEQ_FOREACH(pp, &pool_head, pr_list)
102
		printf("%s: %zd items, %zd free\n", pp->pr_name, pp->pr_nitems,
103
		    pp->pr_nfree);
104
}
105
#endif /* NOPOOL */