blob: 738cc5dadb7138a4a5da7c4016c2c954d7ac38be [file] [log] [blame]
Neels Hofmeyr0e8df1c2019-02-11 20:32:25 +01001/*! \file use_count.c
2 * Generic object usage counter Implementation (get, put and deallocate on zero count).
3 */
4/*
5 * (C) 2019 by sysmocom s.f.m.c. GmbH <info@sysmocom.de>
6 *
7 * All Rights Reserved
8 *
9 * Author: Neels Hofmeyr <neels@hofmeyr.de>
10 *
11 * SPDX-License-Identifier: GPL-2.0+
12 *
13 * This program is free software; you can redistribute it and/or modify
14 * it under the terms of the GNU General Public License as published by
15 * the Free Software Foundation; either version 2 of the License, or
16 * (at your option) any later version.
17 *
18 * This program is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU General Public License for more details.
22 *
23 * You should have received a copy of the GNU General Public License along
24 * with this program; if not, write to the Free Software Foundation, Inc.,
25 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
26 */
27
28#include <errno.h>
29#include <inttypes.h>
30#include <string.h>
31
32#include <osmocom/core/linuxlist.h>
33#include <osmocom/core/utils.h>
34#include <osmocom/core/use_count.h>
35
36/*! \addtogroup use_count
37 *
38 * Generic object usage counter (get, put and deallocate on zero count).
39 *
40 * For an example and a detailed description, see struct osmo_use_count.
41 *
42 * @{
43 * \file use_count.c
44 */
45
46/*! Add two int32_t but make sure to min- and max-clamp at INT32_MIN and INT32_MAX, respectively. */
47static inline bool count_safe(int32_t *val_p, int32_t add)
48{
49 int32_t val = *val_p;
50
51 /* A simpler implementation would just let the integer overflow and compare with previous value afterwards, but
52 * that causes runtime errors in the address sanitizer. So let's just do this without tricks. */
53 if (add < 0 && val < 0 && val - INT32_MIN < -add) {
54 *val_p = INT32_MIN;
55 return false;
56 }
57
58 if (add > 0 && val > 0 && INT32_MAX - val < add) {
59 *val_p = INT32_MAX;
60 return false;
61 }
62
63 *val_p = val + add;
64 return true;
65}
66
67/*! Return the sum of all use counts, min- and max-clamped at INT32_MIN and INT32_MAX.
68 * \param[in] uc Use counts to sum up.
69 * \return Accumulated counts, or 0 if uc is NULL.
70 */
71int32_t osmo_use_count_total(const struct osmo_use_count *uc)
72{
73 struct osmo_use_count_entry *e;
74 int32_t total = 0;
75
76 if (!uc || !uc->use_counts.next)
77 return 0;
78
79 llist_for_each_entry(e, &uc->use_counts, entry) {
80 count_safe(&total, e->count);
81 }
82 return total;
83}
84
85/*! Return use count by a single use token.
86 * \param[in] uc Use counts to look up in.
87 * \param[in] use Use token.
88 * \return Use count, or 0 if uc is NULL or use token is not present.
89 */
90int32_t osmo_use_count_by(const struct osmo_use_count *uc, const char *use)
91{
92 const struct osmo_use_count_entry *e;
93 if (!uc)
94 return 0;
95 e = osmo_use_count_find(uc, use);
96 if (!e)
97 return 0;
98 return e->count;
99}
100
101/*! Write a comprehensive listing of use counts to a string buffer.
102 * Reads like "12 (3*barring,fighting,8*kungfoo)".
103 * \param[inout] buf Destination buffer.
104 * \param[in] buf_len sizeof(buf).
105 * \param[in] uc Use counts to print.
106 * \return buf, always nul-terminated (except when buf_len < 1).
107 */
108const char *osmo_use_count_name_buf(char *buf, size_t buf_len, const struct osmo_use_count *uc)
109{
Neels Hofmeyr9277b972020-09-15 00:48:36 +0000110 osmo_use_count_to_str_buf(buf, buf_len, uc);
111 return buf;
112}
113
114/*! Write a comprehensive listing of use counts to a string buffer.
115 * Reads like "12 (3*barring,fighting,8*kungfoo)".
116 * \param[inout] buf Destination buffer.
117 * \param[in] buf_len sizeof(buf).
118 * \param[in] uc Use counts to print.
119 * \return number of bytes that would be written, like snprintf().
120 */
121int osmo_use_count_to_str_buf(char *buf, size_t buf_len, const struct osmo_use_count *uc)
122{
Neels Hofmeyr0e8df1c2019-02-11 20:32:25 +0100123 int32_t count = osmo_use_count_total(uc);
124 struct osmo_strbuf sb = { .buf = buf, .len = buf_len };
125 struct osmo_use_count_entry *e;
126 bool first;
127
128 OSMO_STRBUF_PRINTF(sb, "%" PRId32 " (", count);
129
130 first = true;
131 llist_for_each_entry(e, &uc->use_counts, entry) {
132 if (!e->count)
133 continue;
134 if (!first)
135 OSMO_STRBUF_PRINTF(sb, ",");
136 first = false;
137 if (e->count != 1)
138 OSMO_STRBUF_PRINTF(sb, "%" PRId32 "*", e->count);
139 OSMO_STRBUF_PRINTF(sb, "%s", e->use ? : "NULL");
140 }
141 if (first)
142 OSMO_STRBUF_PRINTF(sb, "-");
143 OSMO_STRBUF_PRINTF(sb, ")");
Neels Hofmeyr9277b972020-09-15 00:48:36 +0000144 return sb.chars_needed;
145}
146
147/*! Write a comprehensive listing of use counts to a talloc allocated string buffer.
148 * Reads like "12 (3*barring,fighting,8*kungfoo)".
149 * \param[in] ctx talloc pool to allocate from.
150 * \param[in] uc Use counts to print.
151 * \return buf, always nul-terminated.
152 */
153char *osmo_use_count_to_str_c(void *ctx, const struct osmo_use_count *uc)
154{
155 OSMO_NAME_C_IMPL(ctx, 32, "ERROR", osmo_use_count_to_str_buf, uc)
Neels Hofmeyr0e8df1c2019-02-11 20:32:25 +0100156}
157
158/* Return a use token's use count entry -- probably you want osmo_use_count_by() instead.
159 * \param[in] uc Use counts to look up in.
160 * \param[in] use Use token.
161 * \return matching entry, or NULL if not present.
162 */
163struct osmo_use_count_entry *osmo_use_count_find(const struct osmo_use_count *uc, const char *use)
164{
165 struct osmo_use_count_entry *e;
166 if (!uc->use_counts.next)
167 return NULL;
168 llist_for_each_entry(e, &uc->use_counts, entry) {
169 if (e->use == use || (use && e->use && !strcmp(e->use, use)))
170 return e;
171 }
172 return NULL;
173}
174
175/*! Find a use count entry that currently has zero count, and re-use that for this new use token. */
176static struct osmo_use_count_entry *osmo_use_count_repurpose_zero_entry(struct osmo_use_count *uc, const char *use)
177{
178 struct osmo_use_count_entry *e;
179 if (!uc->use_counts.next)
180 return NULL;
181 llist_for_each_entry(e, &uc->use_counts, entry) {
182 if (!e->count) {
183 e->use = use;
184 return e;
185 }
186 }
187 return NULL;
188}
189
190/*! Allocate a new use count entry, happens implicitly in osmo_use_count_get_put(). */
191static struct osmo_use_count_entry *osmo_use_count_create(struct osmo_use_count *uc, const char *use)
192{
193 struct osmo_use_count_entry *e = talloc_zero(uc->talloc_object, struct osmo_use_count_entry);
194 if (!e)
195 return NULL;
196 *e = (struct osmo_use_count_entry){
197 .use_count = uc,
198 .use = use,
199 };
200 if (!uc->use_counts.next)
201 INIT_LLIST_HEAD(&uc->use_counts);
202 llist_add_tail(&e->entry, &uc->use_counts);
203 return e;
204}
205
206/*! Deallocate a use count entry.
207 * Normally, this is not necessary -- it is ok and even desirable to leave use count entries around even when they reach
208 * a count of zero, until the use_count->talloc_object deallocates and removes all of them in one flush. This avoids
209 * repeated allocation and deallocation for use tokens, because use count entries that have reached zero count are
210 * repurposed for any other use tokens. A cleanup makes sense only if a very large number of differing use tokens surged
211 * at the same time, and the owning object will not be deallocated soon; if so, this should be done by the
212 * osmo_use_count_cb_t implementation.
213 *
214 * osmo_use_count_free() must *not* be called on use count entries that were added by
215 * osmo_use_count_make_static_entries(). This is the responsibility of the osmo_use_count_cb_t() implementation.
216 *
217 * \param[in] use_count_entry Use count entry to unlist and free.
218 */
219void osmo_use_count_free(struct osmo_use_count_entry *use_count_entry)
220{
221 if (!use_count_entry)
222 return;
223 llist_del(&use_count_entry->entry);
224 talloc_free(use_count_entry);
225}
226
227/*! Implementation for osmo_use_count_get_put(), which can also be directly invoked to pass source file information. For
228 * arguments besides file and line, see osmo_use_count_get_put().
229 * \param[in] file Source file path, as in __FILE__.
230 * \param[in] line Source file line, as in __LINE__.
231 */
232int _osmo_use_count_get_put(struct osmo_use_count *uc, const char *use, int32_t change,
233 const char *file, int line)
234{
235 struct osmo_use_count_entry *e;
236 int32_t old_use_count;
237 if (!change)
238 return 0;
239
240 e = osmo_use_count_find(uc, use);
241 if (!e)
242 e = osmo_use_count_repurpose_zero_entry(uc, use);
243 if (!e)
244 e = osmo_use_count_create(uc, use);
245 if (!e)
246 return -ENOMEM;
247
248 if (!e->count) {
249 /* move to end */
250 llist_del(&e->entry);
251 llist_add_tail(&e->entry, &uc->use_counts);
252 }
253
254 old_use_count = e->count;
255 if (!count_safe(&e->count, change)) {
256 e->count = old_use_count;
257 return -ERANGE;
258 }
259
260 if (uc->use_cb)
261 return uc->use_cb(e, old_use_count, file, line);
262 return 0;
263}
264
265/*! Add N static use token entries to avoid dynamic allocation of use count tokens.
266 * When not using this function, use count entries are talloc allocated from uc->talloc_object as talloc context. This
267 * means that there are small dynamic allocations for each use count token. osmo_use_count_get_put() normally leaves
268 * zero-count entries around and re-purposes them later, so the number of small allocations is at most the number of
269 * concurrent differently-named uses of the same object. If that is not enough, this function allows completely avoiding
270 * dynamic use count allocations, by adding N static entries with a zero count and a NULL use token. They will be used
271 * by osmo_use_count_get_put(), and, if the caller avoids using osmo_use_count_free(), the osmo_use_count implementation
272 * never deallocates them. The idea is that the entries are members of the uc->talloc_object, or that they will by other
273 * means be implicitly deallocated by the talloc_object. It is fine to call
274 * osmo_use_count_make_static_entries(buf_n_entries=N) and later have more than N concurrent uses, i.e. it is no problem
275 * to mix static and dynamic entries. To completely avoid dynamic use count entries, N has to >= the maximum number of
276 * concurrent differently-named uses that will occur in the lifetime of the talloc_object.
277 *
278 * struct my_object {
279 * struct osmo_use_count use_count;
280 * struct osmo_use_count_entry use_count_buf[3]; // planning for 3 concurrent users
281 * };
282 *
283 * void example() {
284 * struct my_object *o = talloc_zero(ctx, struct my_object);
285 * osmo_use_count_make_static_entries(&o->use_count, o->use_count_buf, ARRAY_SIZE(o->use_count_buf));
286 * }
287 */
288void osmo_use_count_make_static_entries(struct osmo_use_count *uc, struct osmo_use_count_entry *buf,
289 size_t buf_n_entries)
290{
291 size_t idx;
292 if (!uc->use_counts.next)
293 INIT_LLIST_HEAD(&uc->use_counts);
294 for (idx = 0; idx < buf_n_entries; idx++) {
295 struct osmo_use_count_entry *e = &buf[idx];
296 *e = (struct osmo_use_count_entry){
297 .use_count = uc,
298 };
299 llist_add_tail(&e->entry, &uc->use_counts);
300 }
301}
302
303/*! @} */