blob: d07e47fc8fcf15c20761f80c37cccb685bab9678 [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
Neels Hofmeyr6b5f1de2020-09-29 01:32:28 +0000130 if (!uc->use_counts.next)
131 goto uninitialized;
132
Neels Hofmeyr0e8df1c2019-02-11 20:32:25 +0100133 first = true;
134 llist_for_each_entry(e, &uc->use_counts, entry) {
135 if (!e->count)
136 continue;
137 if (!first)
138 OSMO_STRBUF_PRINTF(sb, ",");
139 first = false;
140 if (e->count != 1)
141 OSMO_STRBUF_PRINTF(sb, "%" PRId32 "*", e->count);
142 OSMO_STRBUF_PRINTF(sb, "%s", e->use ? : "NULL");
143 }
144 if (first)
145 OSMO_STRBUF_PRINTF(sb, "-");
Neels Hofmeyr6b5f1de2020-09-29 01:32:28 +0000146
147uninitialized:
Neels Hofmeyr0e8df1c2019-02-11 20:32:25 +0100148 OSMO_STRBUF_PRINTF(sb, ")");
Neels Hofmeyr9277b972020-09-15 00:48:36 +0000149 return sb.chars_needed;
150}
151
152/*! Write a comprehensive listing of use counts to a talloc allocated string buffer.
153 * Reads like "12 (3*barring,fighting,8*kungfoo)".
154 * \param[in] ctx talloc pool to allocate from.
155 * \param[in] uc Use counts to print.
156 * \return buf, always nul-terminated.
157 */
158char *osmo_use_count_to_str_c(void *ctx, const struct osmo_use_count *uc)
159{
160 OSMO_NAME_C_IMPL(ctx, 32, "ERROR", osmo_use_count_to_str_buf, uc)
Neels Hofmeyr0e8df1c2019-02-11 20:32:25 +0100161}
162
163/* Return a use token's use count entry -- probably you want osmo_use_count_by() instead.
164 * \param[in] uc Use counts to look up in.
165 * \param[in] use Use token.
166 * \return matching entry, or NULL if not present.
167 */
168struct osmo_use_count_entry *osmo_use_count_find(const struct osmo_use_count *uc, const char *use)
169{
170 struct osmo_use_count_entry *e;
171 if (!uc->use_counts.next)
172 return NULL;
173 llist_for_each_entry(e, &uc->use_counts, entry) {
174 if (e->use == use || (use && e->use && !strcmp(e->use, use)))
175 return e;
176 }
177 return NULL;
178}
179
180/*! Find a use count entry that currently has zero count, and re-use that for this new use token. */
181static struct osmo_use_count_entry *osmo_use_count_repurpose_zero_entry(struct osmo_use_count *uc, const char *use)
182{
183 struct osmo_use_count_entry *e;
184 if (!uc->use_counts.next)
185 return NULL;
186 llist_for_each_entry(e, &uc->use_counts, entry) {
187 if (!e->count) {
188 e->use = use;
189 return e;
190 }
191 }
192 return NULL;
193}
194
195/*! Allocate a new use count entry, happens implicitly in osmo_use_count_get_put(). */
196static struct osmo_use_count_entry *osmo_use_count_create(struct osmo_use_count *uc, const char *use)
197{
198 struct osmo_use_count_entry *e = talloc_zero(uc->talloc_object, struct osmo_use_count_entry);
199 if (!e)
200 return NULL;
201 *e = (struct osmo_use_count_entry){
202 .use_count = uc,
203 .use = use,
204 };
205 if (!uc->use_counts.next)
206 INIT_LLIST_HEAD(&uc->use_counts);
207 llist_add_tail(&e->entry, &uc->use_counts);
208 return e;
209}
210
211/*! Deallocate a use count entry.
212 * Normally, this is not necessary -- it is ok and even desirable to leave use count entries around even when they reach
213 * a count of zero, until the use_count->talloc_object deallocates and removes all of them in one flush. This avoids
214 * repeated allocation and deallocation for use tokens, because use count entries that have reached zero count are
215 * repurposed for any other use tokens. A cleanup makes sense only if a very large number of differing use tokens surged
216 * at the same time, and the owning object will not be deallocated soon; if so, this should be done by the
217 * osmo_use_count_cb_t implementation.
218 *
219 * osmo_use_count_free() must *not* be called on use count entries that were added by
220 * osmo_use_count_make_static_entries(). This is the responsibility of the osmo_use_count_cb_t() implementation.
221 *
222 * \param[in] use_count_entry Use count entry to unlist and free.
223 */
224void osmo_use_count_free(struct osmo_use_count_entry *use_count_entry)
225{
226 if (!use_count_entry)
227 return;
228 llist_del(&use_count_entry->entry);
229 talloc_free(use_count_entry);
230}
231
232/*! Implementation for osmo_use_count_get_put(), which can also be directly invoked to pass source file information. For
233 * arguments besides file and line, see osmo_use_count_get_put().
234 * \param[in] file Source file path, as in __FILE__.
235 * \param[in] line Source file line, as in __LINE__.
236 */
237int _osmo_use_count_get_put(struct osmo_use_count *uc, const char *use, int32_t change,
238 const char *file, int line)
239{
240 struct osmo_use_count_entry *e;
241 int32_t old_use_count;
242 if (!change)
243 return 0;
244
245 e = osmo_use_count_find(uc, use);
246 if (!e)
247 e = osmo_use_count_repurpose_zero_entry(uc, use);
248 if (!e)
249 e = osmo_use_count_create(uc, use);
250 if (!e)
251 return -ENOMEM;
252
253 if (!e->count) {
254 /* move to end */
255 llist_del(&e->entry);
256 llist_add_tail(&e->entry, &uc->use_counts);
257 }
258
259 old_use_count = e->count;
260 if (!count_safe(&e->count, change)) {
261 e->count = old_use_count;
262 return -ERANGE;
263 }
264
265 if (uc->use_cb)
266 return uc->use_cb(e, old_use_count, file, line);
267 return 0;
268}
269
270/*! Add N static use token entries to avoid dynamic allocation of use count tokens.
271 * When not using this function, use count entries are talloc allocated from uc->talloc_object as talloc context. This
272 * means that there are small dynamic allocations for each use count token. osmo_use_count_get_put() normally leaves
273 * zero-count entries around and re-purposes them later, so the number of small allocations is at most the number of
274 * concurrent differently-named uses of the same object. If that is not enough, this function allows completely avoiding
275 * dynamic use count allocations, by adding N static entries with a zero count and a NULL use token. They will be used
276 * by osmo_use_count_get_put(), and, if the caller avoids using osmo_use_count_free(), the osmo_use_count implementation
277 * never deallocates them. The idea is that the entries are members of the uc->talloc_object, or that they will by other
278 * means be implicitly deallocated by the talloc_object. It is fine to call
279 * osmo_use_count_make_static_entries(buf_n_entries=N) and later have more than N concurrent uses, i.e. it is no problem
280 * to mix static and dynamic entries. To completely avoid dynamic use count entries, N has to >= the maximum number of
281 * concurrent differently-named uses that will occur in the lifetime of the talloc_object.
282 *
283 * struct my_object {
284 * struct osmo_use_count use_count;
285 * struct osmo_use_count_entry use_count_buf[3]; // planning for 3 concurrent users
286 * };
287 *
288 * void example() {
289 * struct my_object *o = talloc_zero(ctx, struct my_object);
290 * osmo_use_count_make_static_entries(&o->use_count, o->use_count_buf, ARRAY_SIZE(o->use_count_buf));
291 * }
292 */
293void osmo_use_count_make_static_entries(struct osmo_use_count *uc, struct osmo_use_count_entry *buf,
294 size_t buf_n_entries)
295{
296 size_t idx;
297 if (!uc->use_counts.next)
298 INIT_LLIST_HEAD(&uc->use_counts);
299 for (idx = 0; idx < buf_n_entries; idx++) {
300 struct osmo_use_count_entry *e = &buf[idx];
301 *e = (struct osmo_use_count_entry){
302 .use_count = uc,
303 };
304 llist_add_tail(&e->entry, &uc->use_counts);
305 }
306}
307
308/*! @} */