blob: b1d30f11d3acc205e3368639690ca2454f5defcb [file] [log] [blame]
Willy Tarreau50e608d2007-05-13 18:26:08 +02001/*
2 * Memory management functions.
3 *
4 * Copyright 2000-2007 Willy Tarreau <w@1wt.eu>
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version
9 * 2 of the License, or (at your option) any later version.
10 *
11 */
Willy Tarreauf14d1902021-10-05 18:14:11 +020012
13#include <sys/mman.h>
Willy Tarreau7107c8b2018-11-26 11:44:35 +010014#include <errno.h>
Willy Tarreau50e608d2007-05-13 18:26:08 +020015
Willy Tarreau5d9ddc52021-10-06 19:54:09 +020016#include <haproxy/activity.h>
Willy Tarreau4c7e4b72020-05-27 12:58:42 +020017#include <haproxy/api.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020018#include <haproxy/applet-t.h>
Willy Tarreau6be78492020-06-05 00:00:29 +020019#include <haproxy/cfgparse.h>
Willy Tarreauf1d32c42020-06-04 21:07:02 +020020#include <haproxy/channel.h>
Willy Tarreau83487a82020-06-04 20:19:54 +020021#include <haproxy/cli.h>
Christopher Faulet908628c2022-03-25 16:43:49 +010022#include <haproxy/conn_stream.h>
23#include <haproxy/cs_utils.h>
Willy Tarreau36979d92020-06-05 17:27:29 +020024#include <haproxy/errors.h>
Willy Tarreauf268ee82020-06-04 17:05:57 +020025#include <haproxy/global.h>
Willy Tarreau853b2972020-05-27 18:01:47 +020026#include <haproxy/list.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020027#include <haproxy/pool.h>
Willy Tarreau2eec9b52020-06-04 19:58:55 +020028#include <haproxy/stats-t.h>
Willy Tarreau5e539c92020-06-04 20:45:39 +020029#include <haproxy/stream_interface.h>
Willy Tarreaub2551052020-06-09 09:07:15 +020030#include <haproxy/thread.h>
Willy Tarreau48fbcae2020-06-03 18:09:46 +020031#include <haproxy/tools.h>
Willy Tarreau50e608d2007-05-13 18:26:08 +020032
Willy Tarreau50e608d2007-05-13 18:26:08 +020033
Willy Tarreau7f0165e2018-11-26 17:09:46 +010034/* These ones are initialized per-thread on startup by init_pools() */
Willy Tarreaue18db9e2018-10-16 10:28:54 +020035THREAD_LOCAL size_t pool_cache_bytes = 0; /* total cache size */
36THREAD_LOCAL size_t pool_cache_count = 0; /* #cache objects */
37
Willy Tarreau9f699952022-02-18 18:31:53 +010038static struct list pools __read_mostly = LIST_HEAD_INIT(pools);
Willy Tarreauef301b72022-02-23 14:15:18 +010039int mem_poison_byte __read_mostly = 'P';
Willy Tarreau8d0273e2022-02-21 17:16:22 +010040uint pool_debugging __read_mostly = /* set of POOL_DBG_* flags */
Olivier Houcharddc21ff72019-01-29 15:20:16 +010041#ifdef DEBUG_FAIL_ALLOC
Willy Tarreau8d0273e2022-02-21 17:16:22 +010042 POOL_DBG_FAIL_ALLOC |
Olivier Houcharddc21ff72019-01-29 15:20:16 +010043#endif
Willy Tarreaufd8b7372022-02-21 17:31:50 +010044#ifdef DEBUG_DONT_SHARE_POOLS
45 POOL_DBG_DONT_MERGE |
46#endif
Willy Tarreaud3470e12022-02-21 18:30:25 +010047#ifdef DEBUG_POOL_INTEGRITY
48 POOL_DBG_COLD_FIRST |
49#endif
Willy Tarreau6f3c7f62022-02-21 18:42:53 +010050#ifdef DEBUG_POOL_INTEGRITY
51 POOL_DBG_INTEGRITY |
52#endif
Willy Tarreaudff3b062022-02-22 09:21:13 +010053#ifdef CONFIG_HAP_NO_GLOBAL_POOLS
54 POOL_DBG_NO_GLOBAL |
55#endif
Willy Tarreaue9816312022-02-22 16:23:09 +010056#ifndef CONFIG_HAP_POOLS
57 POOL_DBG_NO_CACHE |
58#endif
Willy Tarreau02718222022-02-23 10:10:33 +010059#if defined(DEBUG_POOL_TRACING)
60 POOL_DBG_CALLER |
61#endif
Willy Tarreau13d77752022-02-23 10:20:37 +010062#if defined(DEBUG_MEMORY_POOLS)
63 POOL_DBG_TAG |
64#endif
Willy Tarreau8d0273e2022-02-21 17:16:22 +010065 0;
Olivier Houcharddc21ff72019-01-29 15:20:16 +010066
Willy Tarreauf4b79c42022-02-23 15:20:53 +010067static const struct {
68 uint flg;
69 const char *set;
70 const char *clr;
71 const char *hlp;
72} dbg_options[] = {
73 /* flg, set, clr, hlp */
74 { POOL_DBG_FAIL_ALLOC, "fail", "no-fail", "randomly fail allocations" },
75 { POOL_DBG_DONT_MERGE, "no-merge", "merge", "disable merging of similar pools" },
76 { POOL_DBG_COLD_FIRST, "cold-first", "hot-first", "pick cold objects first" },
77 { POOL_DBG_INTEGRITY, "integrity", "no-integrity", "enable cache integrity checks" },
78 { POOL_DBG_NO_GLOBAL, "no-global", "global", "disable global shared cache" },
79 { POOL_DBG_NO_CACHE, "no-cache", "cache", "disable thread-local cache" },
80 { POOL_DBG_CALLER, "caller", "no-caller", "save caller information in cache" },
81 { POOL_DBG_TAG, "tag", "no-tag", "add tag at end of allocated objects" },
82 { POOL_DBG_POISON, "poison", "no-poison", "poison newly allocated objects" },
83 { 0 /* end */ }
84};
85
Willy Tarreau8d0273e2022-02-21 17:16:22 +010086static int mem_fail_rate __read_mostly = 0;
Willy Tarreau9f699952022-02-18 18:31:53 +010087static int using_default_allocator __read_mostly = 1;
Willy Tarreauc4e56dc2022-03-08 10:41:40 +010088static int disable_trim __read_mostly = 0;
David Carliered232142021-11-25 16:09:45 +000089static int(*my_mallctl)(const char *, void *, size_t *, void *, size_t) = NULL;
Willy Tarreau157e3932021-09-15 10:05:48 +020090
Willy Tarreau0d93a812021-12-23 09:26:30 +010091/* ask the allocator to trim memory pools.
92 * This must run under thread isolation so that competing threads trying to
93 * allocate or release memory do not prevent the allocator from completing
94 * its job. We just have to be careful as callers might already be isolated
95 * themselves.
96 */
Willy Tarreauea3323f2021-09-15 10:38:21 +020097static void trim_all_pools(void)
98{
Willy Tarreau0d93a812021-12-23 09:26:30 +010099 int isolated = thread_isolated();
100
Willy Tarreauc4e56dc2022-03-08 10:41:40 +0100101 if (disable_trim)
102 return;
103
Willy Tarreau0d93a812021-12-23 09:26:30 +0100104 if (!isolated)
105 thread_isolate();
106
David Carlierd450ff62021-11-25 16:14:38 +0000107 if (my_mallctl) {
108 unsigned int i, narenas = 0;
109 size_t len = sizeof(narenas);
110
111 if (my_mallctl("arenas.narenas", &narenas, &len, NULL, 0) == 0) {
112 for (i = 0; i < narenas; i ++) {
113 char mib[32] = {0};
114 snprintf(mib, sizeof(mib), "arena.%u.purge", i);
115 (void)my_mallctl(mib, NULL, NULL, NULL, 0);
116 }
117 }
118 } else {
David Carliered232142021-11-25 16:09:45 +0000119#if defined(HA_HAVE_MALLOC_TRIM)
David Carlierd450ff62021-11-25 16:14:38 +0000120 if (using_default_allocator)
121 malloc_trim(0);
David CARLIERb1e190a2021-11-26 20:44:44 +0000122#elif defined(HA_HAVE_MALLOC_ZONE)
123 if (using_default_allocator) {
124 vm_address_t *zones;
125 unsigned int i, nzones;
126
127 if (malloc_get_all_zones(0, NULL, &zones, &nzones) == KERN_SUCCESS) {
128 for (i = 0; i < nzones; i ++) {
129 malloc_zone_t *zone = (malloc_zone_t *)zones[i];
130
131 /* we cannot purge anonymous zones */
132 if (zone->zone_name)
133 malloc_zone_pressure_relief(zone, 0);
134 }
135 }
136 }
David Carliered232142021-11-25 16:09:45 +0000137#endif
David Carlierd450ff62021-11-25 16:14:38 +0000138 }
Willy Tarreau0d93a812021-12-23 09:26:30 +0100139
140 if (!isolated)
141 thread_release();
Willy Tarreauea3323f2021-09-15 10:38:21 +0200142}
143
Willy Tarreau157e3932021-09-15 10:05:48 +0200144/* check if we're using the same allocator as the one that provides
145 * malloc_trim() and mallinfo(). The principle is that on glibc, both
146 * malloc_trim() and mallinfo() are provided, and using mallinfo() we
147 * can check if malloc() is performed through glibc or any other one
David Carliered232142021-11-25 16:09:45 +0000148 * the executable was linked against (e.g. jemalloc). Prior to this we
149 * have to check whether we're running on jemalloc by verifying if the
150 * mallctl() function is provided. Its pointer will be used later.
Willy Tarreau157e3932021-09-15 10:05:48 +0200151 */
152static void detect_allocator(void)
153{
Willy Tarreau781f07a2021-11-26 15:55:55 +0100154#if defined(__ELF__)
David Carliered232142021-11-25 16:09:45 +0000155 extern int mallctl(const char *, void *, size_t *, void *, size_t) __attribute__((weak));
156
157 my_mallctl = mallctl;
Willy Tarreau781f07a2021-11-26 15:55:55 +0100158#endif
David Carliered232142021-11-25 16:09:45 +0000159
160 if (!my_mallctl) {
161 my_mallctl = get_sym_curr_addr("mallctl");
162 using_default_allocator = (my_mallctl == NULL);
163 }
164
165 if (!my_mallctl) {
166#if defined(HA_HAVE_MALLOC_TRIM)
Willy Tarreauc2afb862021-09-16 09:18:21 +0200167#ifdef HA_HAVE_MALLINFO2
David Carliered232142021-11-25 16:09:45 +0000168 struct mallinfo2 mi1, mi2;
Willy Tarreauc2afb862021-09-16 09:18:21 +0200169#else
David Carliered232142021-11-25 16:09:45 +0000170 struct mallinfo mi1, mi2;
Willy Tarreauc2afb862021-09-16 09:18:21 +0200171#endif
David Carliered232142021-11-25 16:09:45 +0000172 void *ptr;
Willy Tarreau157e3932021-09-15 10:05:48 +0200173
Willy Tarreauc2afb862021-09-16 09:18:21 +0200174#ifdef HA_HAVE_MALLINFO2
David Carliered232142021-11-25 16:09:45 +0000175 mi1 = mallinfo2();
Willy Tarreauc2afb862021-09-16 09:18:21 +0200176#else
David Carliered232142021-11-25 16:09:45 +0000177 mi1 = mallinfo();
Willy Tarreauc2afb862021-09-16 09:18:21 +0200178#endif
David Carliered232142021-11-25 16:09:45 +0000179 ptr = DISGUISE(malloc(1));
Willy Tarreauc2afb862021-09-16 09:18:21 +0200180#ifdef HA_HAVE_MALLINFO2
David Carliered232142021-11-25 16:09:45 +0000181 mi2 = mallinfo2();
Willy Tarreauc2afb862021-09-16 09:18:21 +0200182#else
David Carliered232142021-11-25 16:09:45 +0000183 mi2 = mallinfo();
Willy Tarreauc2afb862021-09-16 09:18:21 +0200184#endif
David Carliered232142021-11-25 16:09:45 +0000185 free(DISGUISE(ptr));
Willy Tarreauea3323f2021-09-15 10:38:21 +0200186
David Carliered232142021-11-25 16:09:45 +0000187 using_default_allocator = !!memcmp(&mi1, &mi2, sizeof(mi1));
David CARLIERb1e190a2021-11-26 20:44:44 +0000188#elif defined(HA_HAVE_MALLOC_ZONE)
189 using_default_allocator = (malloc_default_zone() != NULL);
David Carliered232142021-11-25 16:09:45 +0000190#endif
191 }
Willy Tarreau845b5602021-09-15 10:41:24 +0200192}
193
194static int is_trim_enabled(void)
195{
David Carliered232142021-11-25 16:09:45 +0000196 return using_default_allocator;
Willy Tarreau157e3932021-09-15 10:05:48 +0200197}
Willy Tarreauea3323f2021-09-15 10:38:21 +0200198
Willy Tarreau8d0273e2022-02-21 17:16:22 +0100199static int mem_should_fail(const struct pool_head *pool)
200{
201 int ret = 0;
202
203 if (mem_fail_rate > 0 && !(global.mode & MODE_STARTING)) {
204 if (mem_fail_rate > statistical_prng_range(100))
205 ret = 1;
206 else
207 ret = 0;
208 }
209 return ret;
210}
211
Willy Tarreau50e608d2007-05-13 18:26:08 +0200212/* Try to find an existing shared pool with the same characteristics and
213 * returns it, otherwise creates this one. NULL is returned if no memory
Willy Tarreau581bf812016-01-25 02:19:13 +0100214 * is available for a new creation. Two flags are supported :
215 * - MEM_F_SHARED to indicate that the pool may be shared with other users
216 * - MEM_F_EXACT to indicate that the size must not be rounded up
Willy Tarreau50e608d2007-05-13 18:26:08 +0200217 */
218struct pool_head *create_pool(char *name, unsigned int size, unsigned int flags)
219{
Willy Tarreau42705d02022-02-23 10:03:11 +0100220 unsigned int extra_mark, extra_caller, extra;
Willy Tarreau50e608d2007-05-13 18:26:08 +0200221 struct pool_head *pool;
Willy Tarreau7dcd46d2007-05-14 00:16:13 +0200222 struct pool_head *entry;
223 struct list *start;
Willy Tarreau50e608d2007-05-13 18:26:08 +0200224 unsigned int align;
Willy Tarreau9f3129e2021-04-17 00:31:38 +0200225 int thr __maybe_unused;
Willy Tarreau50e608d2007-05-13 18:26:08 +0200226
Willy Tarreauac421112015-10-28 15:09:29 +0100227 /* We need to store a (void *) at the end of the chunks. Since we know
Willy Tarreau50e608d2007-05-13 18:26:08 +0200228 * that the malloc() function will never return such a small size,
229 * let's round the size up to something slightly bigger, in order to
230 * ease merging of entries. Note that the rounding is a power of two.
Willy Tarreauac421112015-10-28 15:09:29 +0100231 * This extra (void *) is not accounted for in the size computation
232 * so that the visible parts outside are not affected.
Willy Tarreau30f931e2018-10-23 14:40:23 +0200233 *
234 * Note: for the LRU cache, we need to store 2 doubly-linked lists.
Willy Tarreau50e608d2007-05-13 18:26:08 +0200235 */
236
Willy Tarreau13d77752022-02-23 10:20:37 +0100237 extra_mark = (pool_debugging & POOL_DBG_TAG) ? POOL_EXTRA_MARK : 0;
Willy Tarreau02718222022-02-23 10:10:33 +0100238 extra_caller = (pool_debugging & POOL_DBG_CALLER) ? POOL_EXTRA_CALLER : 0;
Willy Tarreau42705d02022-02-23 10:03:11 +0100239 extra = extra_mark + extra_caller;
240
Willy Tarreau581bf812016-01-25 02:19:13 +0100241 if (!(flags & MEM_F_EXACT)) {
Willy Tarreau30f931e2018-10-23 14:40:23 +0200242 align = 4 * sizeof(void *); // 2 lists = 4 pointers min
Willy Tarreau42705d02022-02-23 10:03:11 +0100243 size = ((size + extra + align - 1) & -align) - extra;
Willy Tarreau581bf812016-01-25 02:19:13 +0100244 }
Willy Tarreau50e608d2007-05-13 18:26:08 +0200245
Willy Tarreaue9816312022-02-22 16:23:09 +0100246 if (!(pool_debugging & POOL_DBG_NO_CACHE)) {
247 /* we'll store two lists there, we need the room for this. This is
248 * guaranteed by the test above, except if MEM_F_EXACT is set, or if
249 * the only EXTRA part is in fact the one that's stored in the cache
250 * in addition to the pci struct.
251 */
Willy Tarreau42705d02022-02-23 10:03:11 +0100252 if (size + extra - extra_caller < sizeof(struct pool_cache_item))
253 size = sizeof(struct pool_cache_item) + extra_caller - extra;
Willy Tarreaue9816312022-02-22 16:23:09 +0100254 }
255
Christopher Fauletb349e482017-08-29 09:52:38 +0200256 /* TODO: thread: we do not lock pool list for now because all pools are
257 * created during HAProxy startup (so before threads creation) */
Willy Tarreau7dcd46d2007-05-14 00:16:13 +0200258 start = &pools;
Willy Tarreau50e608d2007-05-13 18:26:08 +0200259 pool = NULL;
Willy Tarreau7dcd46d2007-05-14 00:16:13 +0200260
261 list_for_each_entry(entry, &pools, list) {
262 if (entry->size == size) {
263 /* either we can share this place and we take it, or
Ilya Shipitsin47d17182020-06-21 21:42:57 +0500264 * we look for a shareable one or for the next position
Willy Tarreau7dcd46d2007-05-14 00:16:13 +0200265 * before which we will insert a new one.
266 */
Willy Tarreaufd8b7372022-02-21 17:31:50 +0100267 if ((flags & entry->flags & MEM_F_SHARED) &&
268 (!(pool_debugging & POOL_DBG_DONT_MERGE) ||
269 strcmp(name, entry->name) == 0)) {
Willy Tarreau7dcd46d2007-05-14 00:16:13 +0200270 /* we can share this one */
Willy Tarreau50e608d2007-05-13 18:26:08 +0200271 pool = entry;
Krzysztof Piotr Oledzkia643baf2008-05-29 23:53:44 +0200272 DPRINTF(stderr, "Sharing %s with %s\n", name, pool->name);
Willy Tarreau50e608d2007-05-13 18:26:08 +0200273 break;
274 }
275 }
Willy Tarreau7dcd46d2007-05-14 00:16:13 +0200276 else if (entry->size > size) {
277 /* insert before this one */
278 start = &entry->list;
279 break;
280 }
Willy Tarreau50e608d2007-05-13 18:26:08 +0200281 }
282
283 if (!pool) {
Willy Tarreaue81248c2022-03-02 17:59:04 +0100284 void *pool_addr;
Willy Tarreau0a93b642018-10-16 07:58:39 +0200285
Willy Tarreaue81248c2022-03-02 17:59:04 +0100286 pool_addr = calloc(1, sizeof(*pool) + __alignof__(*pool));
287 if (!pool_addr)
Willy Tarreau50e608d2007-05-13 18:26:08 +0200288 return NULL;
Willy Tarreaue81248c2022-03-02 17:59:04 +0100289
290 /* always provide an aligned pool */
291 pool = (struct pool_head*)((((size_t)pool_addr) + __alignof__(*pool)) & -(size_t)__alignof__(*pool));
292 pool->base_addr = pool_addr; // keep it, it's the address to free later
293
Willy Tarreau50e608d2007-05-13 18:26:08 +0200294 if (name)
295 strlcpy2(pool->name, name, sizeof(pool->name));
Willy Tarreau42705d02022-02-23 10:03:11 +0100296 pool->alloc_sz = size + extra;
Willy Tarreau50e608d2007-05-13 18:26:08 +0200297 pool->size = size;
298 pool->flags = flags;
Willy Tarreau2b718102021-04-21 07:32:39 +0200299 LIST_APPEND(start, &pool->list);
Christopher Faulet2f6d3c02019-06-25 21:45:59 +0200300
Willy Tarreaue9816312022-02-22 16:23:09 +0100301 if (!(pool_debugging & POOL_DBG_NO_CACHE)) {
302 /* update per-thread pool cache if necessary */
303 for (thr = 0; thr < MAX_THREADS; thr++) {
304 LIST_INIT(&pool->cache[thr].list);
305 pool->cache[thr].tid = thr;
306 pool->cache[thr].pool = pool;
307 }
Christopher Faulet2f6d3c02019-06-25 21:45:59 +0200308 }
Olivier Houchard8af97eb2020-02-01 17:45:32 +0100309 }
310 pool->users++;
Willy Tarreau50e608d2007-05-13 18:26:08 +0200311 return pool;
312}
Olivier Houchardcf975d42018-01-24 18:38:31 +0100313
Willy Tarreau13843642021-04-17 16:57:25 +0200314/* Tries to allocate an object for the pool <pool> using the system's allocator
315 * and directly returns it. The pool's allocated counter is checked and updated,
Willy Tarreau8715dec2021-06-10 17:31:48 +0200316 * but no other checks are performed.
Willy Tarreau13843642021-04-17 16:57:25 +0200317 */
318void *pool_get_from_os(struct pool_head *pool)
319{
320 if (!pool->limit || pool->allocated < pool->limit) {
Willy Tarreau96d5bc72022-02-23 08:57:59 +0100321 void *ptr = pool_alloc_area(pool->alloc_sz);
Willy Tarreau13843642021-04-17 16:57:25 +0200322 if (ptr) {
323 _HA_ATOMIC_INC(&pool->allocated);
324 return ptr;
325 }
326 _HA_ATOMIC_INC(&pool->failed);
327 }
328 activity[tid].pool_fail++;
329 return NULL;
330
331}
332
Willy Tarreau45e4e282021-04-17 17:48:40 +0200333/* Releases a pool item back to the operating system and atomically updates
334 * the allocation counter.
335 */
336void pool_put_to_os(struct pool_head *pool, void *ptr)
337{
Willy Tarreau9a7aa3b2021-06-10 17:20:19 +0200338#ifdef DEBUG_UAF
339 /* This object will be released for real in order to detect a use after
340 * free. We also force a write to the area to ensure we crash on double
341 * free or free of a const area.
342 */
343 *(uint32_t *)ptr = 0xDEADADD4;
344#endif /* DEBUG_UAF */
345
Willy Tarreau96d5bc72022-02-23 08:57:59 +0100346 pool_free_area(ptr, pool->alloc_sz);
Willy Tarreau45e4e282021-04-17 17:48:40 +0200347 _HA_ATOMIC_DEC(&pool->allocated);
348}
349
Willy Tarreau8fe726f2021-04-15 18:20:12 +0200350/* Tries to allocate an object for the pool <pool> using the system's allocator
351 * and directly returns it. The pool's counters are updated but the object is
352 * never cached, so this is usable with and without local or shared caches.
Willy Tarreau8fe726f2021-04-15 18:20:12 +0200353 */
354void *pool_alloc_nocache(struct pool_head *pool)
Willy Tarreau0bae0752021-03-02 20:05:09 +0100355{
Willy Tarreau0bae0752021-03-02 20:05:09 +0100356 void *ptr = NULL;
357
Willy Tarreau13843642021-04-17 16:57:25 +0200358 ptr = pool_get_from_os(pool);
359 if (!ptr)
Willy Tarreau0bae0752021-03-02 20:05:09 +0100360 return NULL;
Willy Tarreau0bae0752021-03-02 20:05:09 +0100361
Willy Tarreau13843642021-04-17 16:57:25 +0200362 swrate_add_scaled(&pool->needed_avg, POOL_AVG_SAMPLES, pool->used, POOL_AVG_SAMPLES/4);
Willy Tarreau4781b152021-04-06 13:53:36 +0200363 _HA_ATOMIC_INC(&pool->used);
Willy Tarreau0bae0752021-03-02 20:05:09 +0100364
Willy Tarreau0bae0752021-03-02 20:05:09 +0100365 /* keep track of where the element was allocated from */
Willy Tarreau8c492702022-01-01 17:10:50 +0100366 POOL_DEBUG_SET_MARK(pool, ptr);
Willy Tarreauf70fdde2022-01-25 15:56:50 +0100367 POOL_DEBUG_TRACE_CALLER(pool, (struct pool_cache_item *)ptr, NULL);
Willy Tarreau0bae0752021-03-02 20:05:09 +0100368 return ptr;
369}
370
Willy Tarreau45e4e282021-04-17 17:48:40 +0200371/* Release a pool item back to the OS and keeps the pool's counters up to date.
372 * This is always defined even when pools are not enabled (their usage stats
373 * are maintained).
374 */
375void pool_free_nocache(struct pool_head *pool, void *ptr)
376{
377 _HA_ATOMIC_DEC(&pool->used);
378 swrate_add(&pool->needed_avg, POOL_AVG_SAMPLES, pool->used);
379 pool_put_to_os(pool, ptr);
380}
381
Willy Tarreaub8498e92021-04-18 10:23:02 +0200382
Willy Tarreau6f3c7f62022-02-21 18:42:53 +0100383/* Updates <pch>'s fill_pattern and fills the free area after <item> with it,
384 * up to <size> bytes. The item part is left untouched.
385 */
386void pool_fill_pattern(struct pool_cache_head *pch, struct pool_cache_item *item, uint size)
387{
388 ulong *ptr = (ulong *)item;
389 uint ofs;
390 ulong u;
391
392 if (size <= sizeof(*item))
393 return;
394
395 /* Upgrade the fill_pattern to change about half of the bits
396 * (to be sure to catch static flag corruption), and apply it.
397 */
398 u = pch->fill_pattern += ~0UL / 3; // 0x55...55
399 ofs = sizeof(*item) / sizeof(*ptr);
400 while (ofs < size / sizeof(*ptr))
401 ptr[ofs++] = u;
402}
403
404/* check for a pool_cache_item integrity after extracting it from the cache. It
405 * must have been previously initialized using pool_fill_pattern(). If any
406 * corruption is detected, the function provokes an immediate crash.
407 */
408void pool_check_pattern(struct pool_cache_head *pch, struct pool_cache_item *item, uint size)
409{
410 const ulong *ptr = (const ulong *)item;
411 uint ofs;
412 ulong u;
413
414 if (size <= sizeof(*item))
415 return;
416
417 /* let's check that all words past *item are equal */
418 ofs = sizeof(*item) / sizeof(*ptr);
419 u = ptr[ofs++];
420 while (ofs < size / sizeof(*ptr)) {
421 if (unlikely(ptr[ofs] != u))
422 ABORT_NOW();
423 ofs++;
424 }
425}
426
Willy Tarreaua0b58312022-01-02 17:19:14 +0100427/* removes up to <count> items from the end of the local pool cache <ph> for
428 * pool <pool>. The shared pool is refilled with these objects in the limit
429 * of the number of acceptable objects, and the rest will be released to the
430 * OS. It is not a problem is <count> is larger than the number of objects in
Willy Tarreaue9816312022-02-22 16:23:09 +0100431 * the local cache. The counters are automatically updated. Must not be used
432 * with pools disabled.
Willy Tarreau87212032021-04-19 08:14:03 +0200433 */
Willy Tarreaua0b58312022-01-02 17:19:14 +0100434static void pool_evict_last_items(struct pool_head *pool, struct pool_cache_head *ph, uint count)
Willy Tarreau87212032021-04-19 08:14:03 +0200435{
Willy Tarreau87212032021-04-19 08:14:03 +0200436 struct pool_cache_item *item;
Willy Tarreau1513c542022-01-02 17:53:02 +0100437 struct pool_item *pi, *head = NULL;
Willy Tarreaua0b58312022-01-02 17:19:14 +0100438 uint released = 0;
Willy Tarreau1513c542022-01-02 17:53:02 +0100439 uint cluster = 0;
Willy Tarreau361e31e2022-01-02 00:27:06 +0100440 uint to_free_max;
441
Willy Tarreaue9816312022-02-22 16:23:09 +0100442 BUG_ON(pool_debugging & POOL_DBG_NO_CACHE);
443
Willy Tarreaudff3b062022-02-22 09:21:13 +0100444 /* Note: this will be zero when global pools are disabled */
Willy Tarreau361e31e2022-01-02 00:27:06 +0100445 to_free_max = pool_releasable(pool);
Willy Tarreau87212032021-04-19 08:14:03 +0200446
Willy Tarreaua0b58312022-01-02 17:19:14 +0100447 while (released < count && !LIST_ISEMPTY(&ph->list)) {
Willy Tarreaud5ec1002022-01-02 12:40:14 +0100448 item = LIST_PREV(&ph->list, typeof(item), by_pool);
Willy Tarreaue2830ad2022-02-09 16:23:55 +0100449 BUG_ON(&item->by_pool == &ph->list);
Willy Tarreau6f3c7f62022-02-21 18:42:53 +0100450 if (unlikely(pool_debugging & POOL_DBG_INTEGRITY))
451 pool_check_pattern(ph, item, pool->size);
Willy Tarreau2b718102021-04-21 07:32:39 +0200452 LIST_DELETE(&item->by_pool);
453 LIST_DELETE(&item->by_lru);
Willy Tarreaub46674a2021-12-30 17:37:33 +0100454
Willy Tarreau1513c542022-01-02 17:53:02 +0100455 if (to_free_max > released || cluster) {
Willy Tarreaudff3b062022-02-22 09:21:13 +0100456 /* will never match when global pools are disabled */
Willy Tarreau361e31e2022-01-02 00:27:06 +0100457 pi = (struct pool_item *)item;
Willy Tarreau1513c542022-01-02 17:53:02 +0100458 pi->next = NULL;
459 pi->down = head;
460 head = pi;
461 cluster++;
462 if (cluster >= CONFIG_HAP_POOL_CLUSTER_SIZE) {
463 /* enough to make a cluster */
464 pool_put_to_shared_cache(pool, head, cluster);
465 cluster = 0;
466 head = NULL;
467 }
Willy Tarreau361e31e2022-01-02 00:27:06 +0100468 } else
Willy Tarreaub46674a2021-12-30 17:37:33 +0100469 pool_free_nocache(pool, item);
Willy Tarreau1513c542022-01-02 17:53:02 +0100470
471 released++;
Willy Tarreau361e31e2022-01-02 00:27:06 +0100472 }
473
Willy Tarreau1513c542022-01-02 17:53:02 +0100474 /* incomplete cluster left */
475 if (cluster)
476 pool_put_to_shared_cache(pool, head, cluster);
477
Willy Tarreaua0b58312022-01-02 17:19:14 +0100478 ph->count -= released;
479 pool_cache_count -= released;
480 pool_cache_bytes -= released * pool->size;
481}
482
483/* Evicts some of the oldest objects from one local cache, until its number of
484 * objects is no more than 16+1/8 of the total number of locally cached objects
485 * or the total size of the local cache is no more than 75% of its maximum (i.e.
486 * we don't want a single cache to use all the cache for itself). For this, the
Willy Tarreauc895c442022-02-09 16:19:24 +0100487 * list is scanned in reverse. If <full> is non-null, all objects are evicted.
Willy Tarreaue9816312022-02-22 16:23:09 +0100488 * Must not be used when pools are disabled.
Willy Tarreaua0b58312022-01-02 17:19:14 +0100489 */
Willy Tarreauc895c442022-02-09 16:19:24 +0100490void pool_evict_from_local_cache(struct pool_head *pool, int full)
Willy Tarreaua0b58312022-01-02 17:19:14 +0100491{
492 struct pool_cache_head *ph = &pool->cache[tid];
493
Willy Tarreaue9816312022-02-22 16:23:09 +0100494 BUG_ON(pool_debugging & POOL_DBG_NO_CACHE);
495
Willy Tarreauc895c442022-02-09 16:19:24 +0100496 while ((ph->count && full) ||
497 (ph->count >= CONFIG_HAP_POOL_CLUSTER_SIZE &&
498 ph->count >= 16 + pool_cache_count / 8 &&
499 pool_cache_bytes > CONFIG_HAP_POOL_CACHE_SIZE * 3 / 4)) {
Willy Tarreau43937e92022-01-02 17:24:55 +0100500 pool_evict_last_items(pool, ph, CONFIG_HAP_POOL_CLUSTER_SIZE);
Willy Tarreau87212032021-04-19 08:14:03 +0200501 }
502}
503
Willy Tarreaub8498e92021-04-18 10:23:02 +0200504/* Evicts some of the oldest objects from the local cache, pushing them to the
Willy Tarreaue9816312022-02-22 16:23:09 +0100505 * global pool. Must not be used when pools are disabled.
Willy Tarreaub8498e92021-04-18 10:23:02 +0200506 */
507void pool_evict_from_local_caches()
508{
509 struct pool_cache_item *item;
510 struct pool_cache_head *ph;
511 struct pool_head *pool;
512
Willy Tarreaue9816312022-02-22 16:23:09 +0100513 BUG_ON(pool_debugging & POOL_DBG_NO_CACHE);
514
Willy Tarreaub8498e92021-04-18 10:23:02 +0200515 do {
Willy Tarreaub4e34762021-09-30 19:02:18 +0200516 item = LIST_PREV(&th_ctx->pool_lru_head, struct pool_cache_item *, by_lru);
Willy Tarreaue2830ad2022-02-09 16:23:55 +0100517 BUG_ON(&item->by_lru == &th_ctx->pool_lru_head);
Willy Tarreaub8498e92021-04-18 10:23:02 +0200518 /* note: by definition we remove oldest objects so they also are the
519 * oldest in their own pools, thus their next is the pool's head.
520 */
521 ph = LIST_NEXT(&item->by_pool, struct pool_cache_head *, list);
Willy Tarreau49bb5d42022-02-09 16:33:22 +0100522 BUG_ON(ph->tid != tid);
523
Willy Tarreaub8498e92021-04-18 10:23:02 +0200524 pool = container_of(ph - tid, struct pool_head, cache);
Willy Tarreau49bb5d42022-02-09 16:33:22 +0100525 BUG_ON(pool != ph->pool);
526
Willy Tarreau43937e92022-01-02 17:24:55 +0100527 pool_evict_last_items(pool, ph, CONFIG_HAP_POOL_CLUSTER_SIZE);
Willy Tarreaub8498e92021-04-18 10:23:02 +0200528 } while (pool_cache_bytes > CONFIG_HAP_POOL_CACHE_SIZE * 7 / 8);
529}
Willy Tarreau0bae0752021-03-02 20:05:09 +0100530
Willy Tarreaub2a853d2021-04-19 11:49:26 +0200531/* Frees an object to the local cache, possibly pushing oldest objects to the
532 * shared cache, which itself may decide to release some of them to the OS.
533 * While it is unspecified what the object becomes past this point, it is
Willy Tarreauadd43fa2022-01-24 15:52:51 +0100534 * guaranteed to be released from the users' perpective. A caller address may
Willy Tarreaue9816312022-02-22 16:23:09 +0100535 * be passed and stored into the area when DEBUG_POOL_TRACING is set. Must not
536 * be used with pools disabled.
Willy Tarreaub2a853d2021-04-19 11:49:26 +0200537 */
Willy Tarreau0e2a5b42022-01-24 15:51:50 +0100538void pool_put_to_cache(struct pool_head *pool, void *ptr, const void *caller)
Willy Tarreaub2a853d2021-04-19 11:49:26 +0200539{
540 struct pool_cache_item *item = (struct pool_cache_item *)ptr;
541 struct pool_cache_head *ph = &pool->cache[tid];
542
Willy Tarreaue9816312022-02-22 16:23:09 +0100543 BUG_ON(pool_debugging & POOL_DBG_NO_CACHE);
544
Willy Tarreau2b718102021-04-21 07:32:39 +0200545 LIST_INSERT(&ph->list, &item->by_pool);
Willy Tarreaub4e34762021-09-30 19:02:18 +0200546 LIST_INSERT(&th_ctx->pool_lru_head, &item->by_lru);
Willy Tarreauadd43fa2022-01-24 15:52:51 +0100547 POOL_DEBUG_TRACE_CALLER(pool, item, caller);
Willy Tarreaub2a853d2021-04-19 11:49:26 +0200548 ph->count++;
Willy Tarreau6f3c7f62022-02-21 18:42:53 +0100549 if (unlikely(pool_debugging & POOL_DBG_INTEGRITY))
550 pool_fill_pattern(ph, item, pool->size);
Willy Tarreaub2a853d2021-04-19 11:49:26 +0200551 pool_cache_count++;
552 pool_cache_bytes += pool->size;
553
554 if (unlikely(pool_cache_bytes > CONFIG_HAP_POOL_CACHE_SIZE * 3 / 4)) {
Willy Tarreau43937e92022-01-02 17:24:55 +0100555 if (ph->count >= 16 + pool_cache_count / 8 + CONFIG_HAP_POOL_CLUSTER_SIZE)
Willy Tarreauc895c442022-02-09 16:19:24 +0100556 pool_evict_from_local_cache(pool, 0);
Willy Tarreaub2a853d2021-04-19 11:49:26 +0200557 if (pool_cache_bytes > CONFIG_HAP_POOL_CACHE_SIZE)
558 pool_evict_from_local_caches();
559 }
560}
561
Willy Tarreauafe2c4a2021-12-30 17:09:31 +0100562/* Tries to refill the local cache <pch> from the shared one for pool <pool>.
563 * This is only used when pools are in use and shared pools are enabled. No
564 * malloc() is attempted, and poisonning is never performed. The purpose is to
565 * get the fastest possible refilling so that the caller can easily check if
Willy Tarreaue9816312022-02-22 16:23:09 +0100566 * the cache has enough objects for its use. Must not be used when pools are
567 * disabled.
Willy Tarreauafe2c4a2021-12-30 17:09:31 +0100568 */
569void pool_refill_local_from_shared(struct pool_head *pool, struct pool_cache_head *pch)
570{
571 struct pool_cache_item *item;
Willy Tarreau148160b2022-01-02 14:35:57 +0100572 struct pool_item *ret, *down;
573 uint count;
Willy Tarreauafe2c4a2021-12-30 17:09:31 +0100574
Willy Tarreaue9816312022-02-22 16:23:09 +0100575 BUG_ON(pool_debugging & POOL_DBG_NO_CACHE);
576
Willy Tarreauafe2c4a2021-12-30 17:09:31 +0100577 /* we'll need to reference the first element to figure the next one. We
578 * must temporarily lock it so that nobody allocates then releases it,
579 * or the dereference could fail.
580 */
581 ret = _HA_ATOMIC_LOAD(&pool->free_list);
582 do {
583 while (unlikely(ret == POOL_BUSY)) {
584 __ha_cpu_relax();
585 ret = _HA_ATOMIC_LOAD(&pool->free_list);
586 }
587 if (ret == NULL)
588 return;
589 } while (unlikely((ret = _HA_ATOMIC_XCHG(&pool->free_list, POOL_BUSY)) == POOL_BUSY));
590
591 if (unlikely(ret == NULL)) {
592 HA_ATOMIC_STORE(&pool->free_list, NULL);
593 return;
594 }
595
596 /* this releases the lock */
Willy Tarreauc16ed3b2022-01-01 18:22:20 +0100597 HA_ATOMIC_STORE(&pool->free_list, ret->next);
Willy Tarreauafe2c4a2021-12-30 17:09:31 +0100598
Willy Tarreau148160b2022-01-02 14:35:57 +0100599 /* now store the retrieved object(s) into the local cache */
600 count = 0;
601 for (; ret; ret = down) {
602 down = ret->down;
Willy Tarreau148160b2022-01-02 14:35:57 +0100603 item = (struct pool_cache_item *)ret;
Willy Tarreauf70fdde2022-01-25 15:56:50 +0100604 POOL_DEBUG_TRACE_CALLER(pool, item, NULL);
Willy Tarreau148160b2022-01-02 14:35:57 +0100605 LIST_INSERT(&pch->list, &item->by_pool);
606 LIST_INSERT(&th_ctx->pool_lru_head, &item->by_lru);
607 count++;
Willy Tarreau6f3c7f62022-02-21 18:42:53 +0100608 if (unlikely(pool_debugging & POOL_DBG_INTEGRITY))
609 pool_fill_pattern(pch, item, pool->size);
Willy Tarreau148160b2022-01-02 14:35:57 +0100610 }
611 HA_ATOMIC_ADD(&pool->used, count);
612 pch->count += count;
613 pool_cache_count += count;
614 pool_cache_bytes += count * pool->size;
Willy Tarreauafe2c4a2021-12-30 17:09:31 +0100615}
616
Willy Tarreau337410c2022-01-02 15:15:54 +0100617/* Adds pool item cluster <item> to the shared cache, which contains <count>
618 * elements. The caller is advised to first check using pool_releasable() if
619 * it's wise to add this series of objects there. Both the pool and the item's
620 * head must be valid.
Willy Tarreaub46674a2021-12-30 17:37:33 +0100621 */
Willy Tarreau337410c2022-01-02 15:15:54 +0100622void pool_put_to_shared_cache(struct pool_head *pool, struct pool_item *item, uint count)
Willy Tarreaub46674a2021-12-30 17:37:33 +0100623{
Willy Tarreauc16ed3b2022-01-01 18:22:20 +0100624 struct pool_item *free_list;
Willy Tarreaub46674a2021-12-30 17:37:33 +0100625
Willy Tarreau337410c2022-01-02 15:15:54 +0100626 _HA_ATOMIC_SUB(&pool->used, count);
Willy Tarreaub46674a2021-12-30 17:37:33 +0100627 free_list = _HA_ATOMIC_LOAD(&pool->free_list);
628 do {
629 while (unlikely(free_list == POOL_BUSY)) {
630 __ha_cpu_relax();
631 free_list = _HA_ATOMIC_LOAD(&pool->free_list);
632 }
Willy Tarreauc16ed3b2022-01-01 18:22:20 +0100633 _HA_ATOMIC_STORE(&item->next, free_list);
Willy Tarreaub46674a2021-12-30 17:37:33 +0100634 __ha_barrier_atomic_store();
635 } while (!_HA_ATOMIC_CAS(&pool->free_list, &free_list, item));
636 __ha_barrier_atomic_store();
637 swrate_add(&pool->needed_avg, POOL_AVG_SAMPLES, pool->used);
638}
639
Olivier Houchardcf975d42018-01-24 18:38:31 +0100640/*
641 * This function frees whatever can be freed in pool <pool>.
642 */
643void pool_flush(struct pool_head *pool)
644{
Willy Tarreau148160b2022-01-02 14:35:57 +0100645 struct pool_item *next, *temp, *down;
Olivier Houchardcf975d42018-01-24 18:38:31 +0100646
Willy Tarreaue9816312022-02-22 16:23:09 +0100647 if (!pool || (pool_debugging & (POOL_DBG_NO_CACHE|POOL_DBG_NO_GLOBAL)))
Olivier Houchardcf975d42018-01-24 18:38:31 +0100648 return;
Willy Tarreau2a4523f2021-06-09 18:59:58 +0200649
650 /* The loop below atomically detaches the head of the free list and
651 * replaces it with a NULL. Then the list can be released.
652 */
653 next = pool->free_list;
Olivier Houchardcf975d42018-01-24 18:38:31 +0100654 do {
Willy Tarreau2a4523f2021-06-09 18:59:58 +0200655 while (unlikely(next == POOL_BUSY)) {
656 __ha_cpu_relax();
657 next = _HA_ATOMIC_LOAD(&pool->free_list);
658 }
659 if (next == NULL)
660 return;
661 } while (unlikely((next = _HA_ATOMIC_XCHG(&pool->free_list, POOL_BUSY)) == POOL_BUSY));
662 _HA_ATOMIC_STORE(&pool->free_list, NULL);
Olivier Houchard20872762019-03-08 18:53:35 +0100663 __ha_barrier_atomic_store();
Willy Tarreau2a4523f2021-06-09 18:59:58 +0200664
Olivier Houchardcf975d42018-01-24 18:38:31 +0100665 while (next) {
666 temp = next;
Willy Tarreauc16ed3b2022-01-01 18:22:20 +0100667 next = temp->next;
Willy Tarreau148160b2022-01-02 14:35:57 +0100668 for (; temp; temp = down) {
669 down = temp->down;
670 pool_put_to_os(pool, temp);
671 }
Olivier Houchardcf975d42018-01-24 18:38:31 +0100672 }
Willy Tarreauc239cde2021-06-10 06:54:22 +0200673 /* here, we should have pool->allocated == pool->used */
Olivier Houchardcf975d42018-01-24 18:38:31 +0100674}
675
Willy Tarreaue6ce59d2007-05-13 19:38:49 +0200676/*
Willy Tarreaue6ce59d2007-05-13 19:38:49 +0200677 * This function frees whatever can be freed in all pools, but respecting
Willy Tarreauc0e2ff22020-04-24 06:15:24 +0200678 * the minimum thresholds imposed by owners. It makes sure to be alone to
679 * run by using thread_isolate(). <pool_ctx> is unused.
Willy Tarreaue6ce59d2007-05-13 19:38:49 +0200680 */
Willy Tarreaubafbe012017-11-24 17:34:44 +0100681void pool_gc(struct pool_head *pool_ctx)
Willy Tarreaue6ce59d2007-05-13 19:38:49 +0200682{
683 struct pool_head *entry;
Willy Tarreauc0e2ff22020-04-24 06:15:24 +0200684 int isolated = thread_isolated();
Willy Tarreaub7f9d122009-04-21 02:17:45 +0200685
Willy Tarreauc0e2ff22020-04-24 06:15:24 +0200686 if (!isolated)
687 thread_isolate();
Willy Tarreaub7f9d122009-04-21 02:17:45 +0200688
Willy Tarreaue6ce59d2007-05-13 19:38:49 +0200689 list_for_each_entry(entry, &pools, list) {
Willy Tarreau148160b2022-01-02 14:35:57 +0100690 struct pool_item *temp, *down;
Willy Tarreauc16ed3b2022-01-01 18:22:20 +0100691
Olivier Houchard51d93392020-03-12 19:05:39 +0100692 while (entry->free_list &&
Willy Tarreau57767b82014-12-22 21:40:55 +0100693 (int)(entry->allocated - entry->used) > (int)entry->minavail) {
Olivier Houchard51d93392020-03-12 19:05:39 +0100694 temp = entry->free_list;
Willy Tarreauc16ed3b2022-01-01 18:22:20 +0100695 entry->free_list = temp->next;
Willy Tarreau148160b2022-01-02 14:35:57 +0100696 for (; temp; temp = down) {
697 down = temp->down;
698 pool_put_to_os(entry, temp);
699 }
Willy Tarreaue6ce59d2007-05-13 19:38:49 +0200700 }
Willy Tarreaue6ce59d2007-05-13 19:38:49 +0200701 }
Christopher Fauletb349e482017-08-29 09:52:38 +0200702
Willy Tarreauea3323f2021-09-15 10:38:21 +0200703 trim_all_pools();
Willy Tarreau26ed1832021-06-10 08:40:16 +0200704
Willy Tarreauc0e2ff22020-04-24 06:15:24 +0200705 if (!isolated)
706 thread_release();
Willy Tarreaue6ce59d2007-05-13 19:38:49 +0200707}
Willy Tarreaub8498e92021-04-18 10:23:02 +0200708
Willy Tarreau15c322c2022-01-24 11:51:43 +0100709/*
Willy Tarreaud3929732022-01-24 16:09:29 +0100710 * Returns a pointer to type <type> taken from the pool <pool_type> or
711 * dynamically allocated. In the first case, <pool_type> is updated to point to
712 * the next element in the list. <flags> is a binary-OR of POOL_F_* flags.
713 * Prefer using pool_alloc() which does the right thing without flags.
714 */
715void *__pool_alloc(struct pool_head *pool, unsigned int flags)
716{
717 void *p = NULL;
Willy Tarreau02718222022-02-23 10:10:33 +0100718 void *caller = __builtin_return_address(0);
Willy Tarreaud3929732022-01-24 16:09:29 +0100719
Willy Tarreau8d0273e2022-02-21 17:16:22 +0100720 if (unlikely(pool_debugging & POOL_DBG_FAIL_ALLOC))
721 if (!(flags & POOL_F_NO_FAIL) && mem_should_fail(pool))
722 return NULL;
Willy Tarreaud3929732022-01-24 16:09:29 +0100723
Willy Tarreaue9816312022-02-22 16:23:09 +0100724 if (likely(!(pool_debugging & POOL_DBG_NO_CACHE)) && !p)
Willy Tarreau0e2a5b42022-01-24 15:51:50 +0100725 p = pool_get_from_cache(pool, caller);
Willy Tarreaue9816312022-02-22 16:23:09 +0100726
Willy Tarreaud3929732022-01-24 16:09:29 +0100727 if (unlikely(!p))
728 p = pool_alloc_nocache(pool);
729
730 if (likely(p)) {
731 if (unlikely(flags & POOL_F_MUST_ZERO))
732 memset(p, 0, pool->size);
Willy Tarreauef301b72022-02-23 14:15:18 +0100733 else if (unlikely(!(flags & POOL_F_NO_POISON) && (pool_debugging & POOL_DBG_POISON)))
Willy Tarreaud3929732022-01-24 16:09:29 +0100734 memset(p, mem_poison_byte, pool->size);
735 }
736 return p;
737}
738
739/*
Willy Tarreau15c322c2022-01-24 11:51:43 +0100740 * Puts a memory area back to the corresponding pool. <ptr> be valid. Using
741 * pool_free() is preferred.
742 */
743void __pool_free(struct pool_head *pool, void *ptr)
744{
Willy Tarreau02718222022-02-23 10:10:33 +0100745 const void *caller = __builtin_return_address(0);
Willy Tarreau0e2a5b42022-01-24 15:51:50 +0100746
Willy Tarreau15c322c2022-01-24 11:51:43 +0100747 /* we'll get late corruption if we refill to the wrong pool or double-free */
748 POOL_DEBUG_CHECK_MARK(pool, ptr);
Willy Tarreau27c8da12022-02-09 16:49:16 +0100749 POOL_DEBUG_RESET_MARK(pool, ptr);
Willy Tarreaue9816312022-02-22 16:23:09 +0100750
751 if (unlikely(pool_debugging & POOL_DBG_NO_CACHE)) {
752 pool_free_nocache(pool, ptr);
753 return;
754 }
755
Willy Tarreau0e2a5b42022-01-24 15:51:50 +0100756 pool_put_to_cache(pool, ptr, caller);
Willy Tarreau15c322c2022-01-24 11:51:43 +0100757}
758
Willy Tarreauf14d1902021-10-05 18:14:11 +0200759
760#ifdef DEBUG_UAF
761
762/************* use-after-free allocator *************/
763
764/* allocates an area of size <size> and returns it. The semantics are similar
765 * to those of malloc(). However the allocation is rounded up to 4kB so that a
766 * full page is allocated. This ensures the object can be freed alone so that
767 * future dereferences are easily detected. The returned object is always
768 * 16-bytes aligned to avoid issues with unaligned structure objects. In case
769 * some padding is added, the area's start address is copied at the end of the
770 * padding to help detect underflows.
771 */
772void *pool_alloc_area_uaf(size_t size)
773{
774 size_t pad = (4096 - size) & 0xFF0;
Willy Tarreauf14d1902021-10-05 18:14:11 +0200775 void *ret;
776
Willy Tarreauf14d1902021-10-05 18:14:11 +0200777 ret = mmap(NULL, (size + 4095) & -4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
778 if (ret != MAP_FAILED) {
779 /* let's dereference the page before returning so that the real
780 * allocation in the system is performed without holding the lock.
781 */
782 *(int *)ret = 0;
783 if (pad >= sizeof(void *))
784 *(void **)(ret + pad - sizeof(void *)) = ret + pad;
785 ret += pad;
786 } else {
787 ret = NULL;
788 }
Willy Tarreauf14d1902021-10-05 18:14:11 +0200789 return ret;
790}
791
792/* frees an area <area> of size <size> allocated by pool_alloc_area(). The
793 * semantics are identical to free() except that the size must absolutely match
794 * the one passed to pool_alloc_area(). In case some padding is added, the
795 * area's start address is compared to the one at the end of the padding, and
796 * a segfault is triggered if they don't match, indicating an underflow.
797 */
798void pool_free_area_uaf(void *area, size_t size)
799{
800 size_t pad = (4096 - size) & 0xFF0;
801
802 if (pad >= sizeof(void *) && *(void **)(area - sizeof(void *)) != area)
803 ABORT_NOW();
804
Willy Tarreauf14d1902021-10-05 18:14:11 +0200805 munmap(area - pad, (size + 4095) & -4096);
Willy Tarreauf14d1902021-10-05 18:14:11 +0200806}
807
808#endif /* DEBUG_UAF */
809
Willy Tarreaue6ce59d2007-05-13 19:38:49 +0200810/*
Willy Tarreaudae4aa82007-06-16 23:19:53 +0200811 * This function destroys a pool by freeing it completely, unless it's still
812 * in use. This should be called only under extreme circumstances. It always
813 * returns NULL if the resulting pool is empty, easing the clearing of the old
814 * pointer, otherwise it returns the pool.
815 * .
Willy Tarreaue6ce59d2007-05-13 19:38:49 +0200816 */
Willy Tarreaubafbe012017-11-24 17:34:44 +0100817void *pool_destroy(struct pool_head *pool)
Willy Tarreaue6ce59d2007-05-13 19:38:49 +0200818{
Willy Tarreau4d2d0982007-05-14 00:39:29 +0200819 if (pool) {
Willy Tarreaue9816312022-02-22 16:23:09 +0100820 if (!(pool_debugging & POOL_DBG_NO_CACHE))
821 pool_evict_from_local_cache(pool, 1);
822
Willy Tarreaubafbe012017-11-24 17:34:44 +0100823 pool_flush(pool);
Willy Tarreaudae4aa82007-06-16 23:19:53 +0200824 if (pool->used)
825 return pool;
826 pool->users--;
827 if (!pool->users) {
Willy Tarreau2b718102021-04-21 07:32:39 +0200828 LIST_DELETE(&pool->list);
Willy Tarreau9f3129e2021-04-17 00:31:38 +0200829 /* note that if used == 0, the cache is empty */
Willy Tarreauf9eba782022-03-03 18:31:54 +0100830 free(pool->base_addr);
Willy Tarreaudae4aa82007-06-16 23:19:53 +0200831 }
Willy Tarreau4d2d0982007-05-14 00:39:29 +0200832 }
833 return NULL;
Willy Tarreaue6ce59d2007-05-13 19:38:49 +0200834}
835
Willy Tarreau2455ceb2018-11-26 15:57:34 +0100836/* This destroys all pools on exit. It is *not* thread safe. */
837void pool_destroy_all()
838{
839 struct pool_head *entry, *back;
840
841 list_for_each_entry_safe(entry, back, &pools, list)
842 pool_destroy(entry);
843}
844
Willy Tarreau12833bb2014-01-28 16:49:56 +0100845/* This function dumps memory usage information into the trash buffer. */
846void dump_pools_to_trash()
Willy Tarreau50e608d2007-05-13 18:26:08 +0200847{
848 struct pool_head *entry;
849 unsigned long allocated, used;
850 int nbpools;
Willy Tarreau1b4a7142021-10-07 16:29:31 +0200851 unsigned long cached_bytes = 0;
852 uint cached = 0;
Willy Tarreau50e608d2007-05-13 18:26:08 +0200853
854 allocated = used = nbpools = 0;
Willy Tarreau12833bb2014-01-28 16:49:56 +0100855 chunk_printf(&trash, "Dumping pools usage. Use SIGQUIT to flush them.\n");
Willy Tarreau50e608d2007-05-13 18:26:08 +0200856 list_for_each_entry(entry, &pools, list) {
Willy Tarreaue9816312022-02-22 16:23:09 +0100857 if (!(pool_debugging & POOL_DBG_NO_CACHE)) {
858 int i;
859 for (cached = i = 0; i < global.nbthread; i++)
860 cached += entry->cache[i].count;
861 cached_bytes += cached * entry->size;
862 }
Willy Tarreau1b4a7142021-10-07 16:29:31 +0200863 chunk_appendf(&trash, " - Pool %s (%u bytes) : %u allocated (%u bytes), %u used"
Willy Tarreau1b4a7142021-10-07 16:29:31 +0200864 " (~%u by thread caches)"
Willy Tarreau1b4a7142021-10-07 16:29:31 +0200865 ", needed_avg %u, %u failures, %u users, @%p%s\n",
866 entry->name, entry->size, entry->allocated,
867 entry->size * entry->allocated, entry->used,
Willy Tarreau1b4a7142021-10-07 16:29:31 +0200868 cached,
Willy Tarreau1b4a7142021-10-07 16:29:31 +0200869 swrate_avg(entry->needed_avg, POOL_AVG_SAMPLES), entry->failed,
870 entry->users, entry,
871 (entry->flags & MEM_F_SHARED) ? " [SHARED]" : "");
Willy Tarreau50e608d2007-05-13 18:26:08 +0200872
873 allocated += entry->allocated * entry->size;
874 used += entry->used * entry->size;
875 nbpools++;
876 }
Willy Tarreau1b4a7142021-10-07 16:29:31 +0200877 chunk_appendf(&trash, "Total: %d pools, %lu bytes allocated, %lu used"
Willy Tarreau1b4a7142021-10-07 16:29:31 +0200878 " (~%lu by thread caches)"
Willy Tarreau1b4a7142021-10-07 16:29:31 +0200879 ".\n",
Willy Tarreaue9816312022-02-22 16:23:09 +0100880 nbpools, allocated, used, cached_bytes
Willy Tarreau1b4a7142021-10-07 16:29:31 +0200881 );
Willy Tarreau50e608d2007-05-13 18:26:08 +0200882}
883
Willy Tarreau12833bb2014-01-28 16:49:56 +0100884/* Dump statistics on pools usage. */
885void dump_pools(void)
886{
887 dump_pools_to_trash();
Willy Tarreau843b7cb2018-07-13 10:54:26 +0200888 qfprintf(stderr, "%s", trash.area);
Willy Tarreau12833bb2014-01-28 16:49:56 +0100889}
890
Willy Tarreau58102cf2015-10-28 16:24:21 +0100891/* This function returns the total number of failed pool allocations */
892int pool_total_failures()
893{
894 struct pool_head *entry;
895 int failed = 0;
896
897 list_for_each_entry(entry, &pools, list)
898 failed += entry->failed;
899 return failed;
900}
901
902/* This function returns the total amount of memory allocated in pools (in bytes) */
903unsigned long pool_total_allocated()
904{
905 struct pool_head *entry;
906 unsigned long allocated = 0;
907
908 list_for_each_entry(entry, &pools, list)
909 allocated += entry->allocated * entry->size;
910 return allocated;
911}
912
913/* This function returns the total amount of memory used in pools (in bytes) */
914unsigned long pool_total_used()
915{
916 struct pool_head *entry;
917 unsigned long used = 0;
918
919 list_for_each_entry(entry, &pools, list)
920 used += entry->used * entry->size;
921 return used;
922}
923
Willy Tarreau1408b1f2022-02-18 18:54:40 +0100924/* This function parses a string made of a set of debugging features as
925 * specified after -dM on the command line, and will set pool_debugging
926 * accordingly. On success it returns a strictly positive value. It may zero
927 * with the first warning in <err>, -1 with a help message in <err>, or -2 with
928 * the first error in <err> return the first error in <err>. <err> is undefined
929 * on success, and will be non-null and locally allocated on help/error/warning.
930 * The caller must free it. Warnings are used to report features that were not
931 * enabled at build time, and errors are used to report unknown features.
932 */
933int pool_parse_debugging(const char *str, char **err)
934{
Willy Tarreauf4b79c42022-02-23 15:20:53 +0100935 struct ist args;
Willy Tarreau1408b1f2022-02-18 18:54:40 +0100936 char *end;
Willy Tarreauf4b79c42022-02-23 15:20:53 +0100937 uint new_dbg;
Willy Tarreau1408b1f2022-02-18 18:54:40 +0100938 int v;
939
940
941 /* if it's empty or starts with a number, it's the mem poisonning byte */
942 v = strtol(str, &end, 0);
943 if (!*end || *end == ',') {
944 mem_poison_byte = *str ? v : 'P';
945 if (mem_poison_byte >= 0)
946 pool_debugging |= POOL_DBG_POISON;
947 else
948 pool_debugging &= ~POOL_DBG_POISON;
949 str = end;
950 }
Willy Tarreauf4b79c42022-02-23 15:20:53 +0100951
952 new_dbg = pool_debugging;
953
954 for (args = ist(str); istlen(args); args = istadv(istfind(args, ','), 1)) {
955 struct ist feat = iststop(args, ',');
956
957 if (!istlen(feat))
958 continue;
959
960 if (isteq(feat, ist("help"))) {
961 ha_free(err);
962 memprintf(err,
963 "-dM alone enables memory poisonning with byte 0x50 on allocation. A numeric\n"
964 "value may be appended immediately after -dM to use another value (0 supported).\n"
965 "Then an optional list of comma-delimited keywords may be appended to set or\n"
966 "clear some debugging options ('*' marks the current setting):\n\n"
967 " set clear description\n"
968 " -----------------+-----------------+-----------------------------------------\n");
969
970 for (v = 0; dbg_options[v].flg; v++) {
971 memprintf(err, "%s %c %-15s|%c %-15s| %s\n",
972 *err,
973 (pool_debugging & dbg_options[v].flg) ? '*' : ' ',
974 dbg_options[v].set,
975 (pool_debugging & dbg_options[v].flg) ? ' ' : '*',
976 dbg_options[v].clr,
977 dbg_options[v].hlp);
978 }
979 return -1;
980 }
981
982 for (v = 0; dbg_options[v].flg; v++) {
983 if (isteq(feat, ist(dbg_options[v].set))) {
984 new_dbg |= dbg_options[v].flg;
985 break;
986 }
987 else if (isteq(feat, ist(dbg_options[v].clr))) {
988 new_dbg &= ~dbg_options[v].flg;
989 break;
990 }
991 }
992
993 if (!dbg_options[v].flg) {
994 memprintf(err, "unknown pool debugging feature <%.*s>", (int)istlen(feat), istptr(feat));
995 return -2;
996 }
997 }
998
999 pool_debugging = new_dbg;
Willy Tarreau1408b1f2022-02-18 18:54:40 +01001000 return 1;
1001}
1002
William Lallemande7ed8852016-11-19 02:25:36 +01001003/* This function dumps memory usage information onto the stream interface's
1004 * read buffer. It returns 0 as long as it does not complete, non-zero upon
1005 * completion. No state is used.
1006 */
1007static int cli_io_handler_dump_pools(struct appctx *appctx)
1008{
Christopher Faulet908628c2022-03-25 16:43:49 +01001009 struct conn_stream *cs = appctx->owner;
William Lallemande7ed8852016-11-19 02:25:36 +01001010
1011 dump_pools_to_trash();
Christopher Faulet908628c2022-03-25 16:43:49 +01001012 if (ci_putchk(cs_ic(cs), &trash) == -1) {
Christopher Fauleta0bdec32022-04-04 07:51:21 +02001013 cs_rx_room_blk(cs);
William Lallemande7ed8852016-11-19 02:25:36 +01001014 return 0;
1015 }
1016 return 1;
1017}
1018
Willy Tarreau7107c8b2018-11-26 11:44:35 +01001019/* callback used to create early pool <name> of size <size> and store the
1020 * resulting pointer into <ptr>. If the allocation fails, it quits with after
1021 * emitting an error message.
1022 */
1023void create_pool_callback(struct pool_head **ptr, char *name, unsigned int size)
1024{
1025 *ptr = create_pool(name, size, MEM_F_SHARED);
1026 if (!*ptr) {
1027 ha_alert("Failed to allocate pool '%s' of size %u : %s. Aborting.\n",
1028 name, size, strerror(errno));
1029 exit(1);
1030 }
1031}
1032
Willy Tarreau7f0165e2018-11-26 17:09:46 +01001033/* Initializes all per-thread arrays on startup */
1034static void init_pools()
1035{
Willy Tarreau9f3129e2021-04-17 00:31:38 +02001036 int thr;
Willy Tarreau7f0165e2018-11-26 17:09:46 +01001037
1038 for (thr = 0; thr < MAX_THREADS; thr++) {
Willy Tarreaub4e34762021-09-30 19:02:18 +02001039 LIST_INIT(&ha_thread_ctx[thr].pool_lru_head);
Willy Tarreau7f0165e2018-11-26 17:09:46 +01001040 }
Willy Tarreaue9816312022-02-22 16:23:09 +01001041
Willy Tarreau157e3932021-09-15 10:05:48 +02001042 detect_allocator();
Willy Tarreau7f0165e2018-11-26 17:09:46 +01001043}
1044
1045INITCALL0(STG_PREPARE, init_pools);
Willy Tarreau7107c8b2018-11-26 11:44:35 +01001046
Willy Tarreau845b5602021-09-15 10:41:24 +02001047/* Report in build options if trim is supported */
1048static void pools_register_build_options(void)
1049{
1050 if (is_trim_enabled()) {
1051 char *ptr = NULL;
1052 memprintf(&ptr, "Support for malloc_trim() is enabled.");
1053 hap_register_build_opts(ptr, 1);
1054 }
1055}
1056INITCALL0(STG_REGISTER, pools_register_build_options);
1057
William Lallemande7ed8852016-11-19 02:25:36 +01001058/* register cli keywords */
1059static struct cli_kw_list cli_kws = {{ },{
Willy Tarreaub205bfd2021-05-07 11:38:37 +02001060 { { "show", "pools", NULL }, "show pools : report information about the memory pools usage", NULL, cli_io_handler_dump_pools },
William Lallemande7ed8852016-11-19 02:25:36 +01001061 {{},}
1062}};
1063
Willy Tarreau0108d902018-11-25 19:14:37 +01001064INITCALL1(STG_REGISTER, cli_register_kw, &cli_kws);
William Lallemande7ed8852016-11-19 02:25:36 +01001065
Olivier Houcharddc21ff72019-01-29 15:20:16 +01001066
1067/* config parser for global "tune.fail-alloc" */
1068static int mem_parse_global_fail_alloc(char **args, int section_type, struct proxy *curpx,
Amaury Denoyelle3b1c9a32021-03-22 11:21:36 +01001069 const struct proxy *defpx, const char *file, int line,
1070 char **err)
Olivier Houcharddc21ff72019-01-29 15:20:16 +01001071{
1072 if (too_many_args(1, args, err, NULL))
1073 return -1;
1074 mem_fail_rate = atoi(args[1]);
1075 if (mem_fail_rate < 0 || mem_fail_rate > 100) {
1076 memprintf(err, "'%s' expects a numeric value between 0 and 100.", args[0]);
1077 return -1;
1078 }
1079 return 0;
1080}
Olivier Houcharddc21ff72019-01-29 15:20:16 +01001081
Willy Tarreauc4e56dc2022-03-08 10:41:40 +01001082/* config parser for global "no-memory-trimming" */
1083static int mem_parse_global_no_mem_trim(char **args, int section_type, struct proxy *curpx,
1084 const struct proxy *defpx, const char *file, int line,
1085 char **err)
1086{
1087 if (too_many_args(0, args, err, NULL))
1088 return -1;
1089 disable_trim = 1;
1090 return 0;
1091}
1092
Olivier Houcharddc21ff72019-01-29 15:20:16 +01001093/* register global config keywords */
1094static struct cfg_kw_list mem_cfg_kws = {ILH, {
Olivier Houcharddc21ff72019-01-29 15:20:16 +01001095 { CFG_GLOBAL, "tune.fail-alloc", mem_parse_global_fail_alloc },
Willy Tarreauc4e56dc2022-03-08 10:41:40 +01001096 { CFG_GLOBAL, "no-memory-trimming", mem_parse_global_no_mem_trim },
Olivier Houcharddc21ff72019-01-29 15:20:16 +01001097 { 0, NULL, NULL }
1098}};
1099
1100INITCALL1(STG_REGISTER, cfg_register_keywords, &mem_cfg_kws);
1101
Willy Tarreau50e608d2007-05-13 18:26:08 +02001102/*
1103 * Local variables:
1104 * c-indent-level: 8
1105 * c-basic-offset: 8
1106 * End:
1107 */