vinix-ports / musl / patches / malloc-retain.patch
492 lines · 470 sloc · 15.02 KB · 2162768ec3548cc7332b9437368a97b5728b2cad
Raw
1--- a/src/malloc/mallocng/meta.h
2+++ b/src/malloc/mallocng/meta.h
3@@ -10,6 +10,17 @@
4 extern const uint16_t size_classes[];
5
6 #define MMAP_THRESHOLD 131052
7+
8+/* Vinix anonymous mappings cost page tables, zeroing and TLB maintenance.
9+ * Reuse a bounded number of ordinary groups and large mappings. Set this
10+ * to zero at build time to retain upstream release policy. */
11+#ifndef VINIX_MALLOC_RETAIN
12+#define VINIX_MALLOC_RETAIN 1
13+#endif
14+#define LARGE_CACHE_COUNT 5
15+#define LARGE_CACHE_MAX_PAGES 512
16+#define RETAIN_GROUP_MAX_BYTES (128UL*1024)
17+
18
19 #define UNIT 16
20 #define IB 4
21@@ -51,6 +62,7 @@
22 struct meta_area *meta_area_head, *meta_area_tail;
23 unsigned char *avail_meta_areas;
24 struct meta *active[48];
25+ struct meta *large_cache[LARGE_CACHE_COUNT];
26 size_t usage_by_class[48];
27 uint8_t unmap_seq[32], bounces[32];
28 uint8_t seq;
29@@ -116,8 +128,14 @@
30 {
31 assert(!m->avail_mask);
32 uint32_t mask, act = (2u<<m->mem->active_idx)-1;
33- do mask = m->freed_mask;
34- while (a_cas(&m->freed_mask, mask, mask&~act)!=mask);
35+ /* No other thread can publish frees while need_locks is zero. */
36+ if (!MT) {
37+ mask = m->freed_mask;
38+ m->freed_mask = mask & ~act;
39+ } else {
40+ do mask = m->freed_mask;
41+ while (a_cas(&m->freed_mask, mask, mask&~act)!=mask);
42+ }
43 return m->avail_mask = mask & act;
44 }
45
46@@ -126,7 +144,14 @@
47 return p[-3] & 31;
48 }
49
50-static inline struct meta *get_meta(const unsigned char *p)
51+struct slot_info {
52+ size_t stride, class_stride;
53+ int index;
54+};
55+
56+/* Share values already needed for header validation with free(). Other
57+ * callers keep the same pointer-only get_meta interface. */
58+static inline struct meta *get_meta_with_info(const unsigned char *p, struct slot_info *info)
59 {
60 assert(!((uintptr_t)p & 15));
61 int offset = *(const uint16_t *)(p - 2);
62@@ -144,16 +169,35 @@
63 assert(!(meta->freed_mask & (1u<<index)));
64 const struct meta_area *area = (void *)((uintptr_t)meta & -4096);
65 assert(area->check == ctx.secret);
66- if (meta->sizeclass < 48) {
67- assert(offset >= size_classes[meta->sizeclass]*index);
68- assert(offset < size_classes[meta->sizeclass]*(index+1));
69- } else {
70- assert(meta->sizeclass == 63);
71- }
72- if (meta->maplen) {
73- assert(offset <= meta->maplen*4096UL/UNIT - 1);
74+ size_t class_stride = 0;
75+ int sc = meta->sizeclass;
76+ if (sc < 48) {
77+ int units = size_classes[sc];
78+ assert(offset >= units*index);
79+ assert(offset < units*(index+1));
80+ class_stride = UNIT*units;
81+ } else {
82+ assert(sc == 63);
83+ /* Direct mappings always own one slot and a nonempty map. */
84+ assert(!meta->last_idx);
85+ assert(meta->maplen);
86+ }
87+ size_t maplen = meta->maplen;
88+ if (maplen) {
89+ assert(offset <= maplen*4096UL/UNIT - 1);
90+ }
91+ if (info) {
92+ info->index = index;
93+ info->class_stride = class_stride;
94+ info->stride = !meta->last_idx && maplen ? maplen*4096UL-UNIT :
95+ class_stride;
96 }
97 return (struct meta *)meta;
98+}
99+
100+static inline struct meta *get_meta(const unsigned char *p)
101+{
102+ return get_meta_with_info(p, 0);
103 }
104
105 static inline size_t get_nominal_size(const unsigned char *p, const unsigned char *end)
106@@ -181,7 +225,7 @@
107 }
108 }
109
110-static inline void set_size(unsigned char *p, unsigned char *end, size_t n)
111+static inline void set_size_at(unsigned char *p, unsigned char *end, size_t n, int idx)
112 {
113 int reserved = end-p-n;
114 if (reserved) end[-reserved] = 0;
115@@ -190,7 +234,12 @@
116 end[-5] = 0;
117 reserved = 5;
118 }
119- p[-3] = (p[-3]&31) + (reserved<<5);
120+ p[-3] = idx + (reserved<<5);
121+}
122+
123+static inline void set_size(unsigned char *p, unsigned char *end, size_t n)
124+{
125+ set_size_at(p, end, n, p[-3]&31);
126 }
127
128 static inline void *enframe(struct meta *g, int idx, size_t n, int ctr)
129@@ -201,14 +250,20 @@
130 unsigned char *end = p+stride-IB;
131 // cycle offset within slot to increase interval to address
132 // reuse, facilitate trapping double-free.
133- int off = (p[-3] ? *(uint16_t *)(p-2) + 1 : ctr) & 255;
134+ int off = 0;
135 assert(!p[-4]);
136- if (off > slack) {
137- size_t m = slack;
138- m |= m>>1; m |= m>>2; m |= m>>4;
139- off &= m;
140- if (off > slack) off -= slack+1;
141- assert(off <= slack);
142+ /* With no whole unit of slack, clamping always chooses offset zero.
143+ * Skip reading and cycling the old offset in that case. Slot selection
144+ * still rotates, and positive-slack slots keep upstream offset cycling. */
145+ if (slack) {
146+ off = (p[-3] ? *(uint16_t *)(p-2) + 1 : ctr) & 255;
147+ if (off > slack) {
148+ size_t m = slack;
149+ m |= m>>1; m |= m>>2; m |= m>>4;
150+ off &= m;
151+ if (off > slack) off -= slack+1;
152+ assert(off <= slack);
153+ }
154 }
155 if (off) {
156 // store offset in unused header at offset zero
157@@ -221,8 +276,8 @@
158 p[-4] = 0;
159 }
160 *(uint16_t *)(p-2) = (size_t)(p-g->mem->storage)/UNIT;
161- p[-3] = idx;
162- set_size(p, end, n);
163+ /* idx is already known here; preserve it in the single final stamp. */
164+ set_size_at(p, end, n, idx);
165 return p;
166 }
167
168@@ -231,7 +286,7 @@
169 n = (n+IB-1)>>4;
170 if (n<10) return n;
171 n++;
172- int i = (28-a_clz_32(n))*4 + 8;
173+ int i = (28-__builtin_clz(n))*4 + 8;
174 if (n>size_classes[i+1]) i+=2;
175 if (n>size_classes[i]) i++;
176 return i;
177@@ -244,6 +299,18 @@
178 return 1;
179 }
180 return 0;
181+}
182+
183+/* One mapping in each power-of-two bucket, from 128 KiB to 2 MiB.
184+ * Their combined upper bounds total 3968 KiB. A larger mapping is never
185+ * cached. Metadata stays owned by the cache until it is reused or trimmed. */
186+static inline int large_cache_index(size_t maplen)
187+{
188+ if (!VINIX_MALLOC_RETAIN || maplen < 32 || maplen > LARGE_CACHE_MAX_PAGES)
189+ return -1;
190+ int i = 0;
191+ for (size_t upper = 32; maplen > upper; upper <<= 1) i++;
192+ return i;
193 }
194
195 static inline void step_seq(void)
196--- a/src/malloc/mallocng/malloc.c
197+++ b/src/malloc/mallocng/malloc.c
198@@ -201,6 +201,13 @@
199 cnt >>= 1;
200 }
201
202+ /* A cache should cover a modest burst before allocating another map.
203+ * Keep upstream's larger usage-driven groups; only raise small groups.
204+ * The storage budget caps both the minimum and retained map footprint. */
205+ int retain_cnt = VINIX_MALLOC_RETAIN ? (RETAIN_GROUP_MAX_BYTES-UNIT)/size : 0;
206+ if (retain_cnt > 8) retain_cnt = 8;
207+ if (cnt < retain_cnt) cnt = retain_cnt;
208+
209 // If we selected a count of 1 above but it's not sufficient to use
210 // mmap, increase to 2. Then it might be; if not it will nest.
211 if (cnt==1 && size*cnt+UNIT <= pagesize/2) cnt = 2;
212@@ -211,7 +218,7 @@
213 // check/update bounce counter to start/increase retention
214 // of freed maps, and inhibit use of low-count, odd-size
215 // small mappings and single-slot groups if activated.
216- int nosmall = is_bouncing(sc);
217+ int nosmall = retain_cnt || is_bouncing(sc);
218 account_bounce(sc);
219 step_seq();
220
221@@ -286,7 +293,7 @@
222 static int alloc_slot(int sc, size_t req)
223 {
224 uint32_t first = try_avail(&ctx.active[sc]);
225- if (first) return a_ctz_32(first);
226+ if (first) return __builtin_ctz(first);
227
228 struct meta *g = alloc_group(sc, req);
229 if (!g) return -1;
230@@ -296,7 +303,7 @@
231 return 0;
232 }
233
234-void *malloc(size_t n)
235+static __attribute__((noinline)) void *malloc_slow(size_t n)
236 {
237 if (size_overflows(n)) return 0;
238 struct meta *g;
239@@ -307,6 +314,20 @@
240
241 if (n >= MMAP_THRESHOLD) {
242 size_t needed = n + IB + UNIT;
243+ int bucket = large_cache_index((needed+4095)/4096);
244+ if (bucket >= 0) {
245+ wrlock();
246+ g = ctx.large_cache[bucket];
247+ if (g && g->maplen*4096UL >= needed) {
248+ ctx.large_cache[bucket] = 0;
249+ g->freed_mask = 0;
250+ step_seq();
251+ ctx.mmap_counter++;
252+ idx = 0;
253+ goto success;
254+ }
255+ unlock();
256+ }
257 void *p = mmap(0, needed, PROT_READ|PROT_WRITE,
258 MAP_PRIVATE|MAP_ANON, -1, 0);
259 if (p==MAP_FAILED) return 0;
260@@ -341,7 +362,11 @@
261 // any groups of desired size. this allows counts of 2 or 3
262 // to be allocated at first rather than having to start with
263 // 7 or 5, the min counts for even size classes.
264- if (!g && sc>=4 && sc<32 && sc!=6 && !(sc&1) && !ctx.usage_by_class[sc]) {
265+ /* Every coarse-eligible class is below 32, with stride at most
266+ * 8176 bytes. The 128 KiB retained budget gives each at least eight
267+ * slots, so coarsening saves no storage under this policy. */
268+ if (!VINIX_MALLOC_RETAIN && !g && sc>=4 && sc<32 && sc!=6 && !(sc&1)
269+ && !ctx.usage_by_class[sc]) {
270 size_t usage = ctx.usage_by_class[sc|1];
271 // if a new group may be allocated, count it toward
272 // usage in deciding if we can use coarse class.
273@@ -361,7 +386,7 @@
274 g->avail_mask = mask-first;
275 else if (a_cas(&g->avail_mask, mask, mask-first)!=mask)
276 continue;
277- idx = a_ctz_32(first);
278+ idx = __builtin_ctz(first);
279 goto success;
280 }
281 upgradelock();
282@@ -379,9 +404,40 @@
283 return enframe(g, idx, n, ctr);
284 }
285
286+void *malloc(size_t n)
287+{
288+ /* Keep the ordinary single-thread path free of mapping and lock calls.
289+ * Negative need_locks transitions and any held/congested malloc lock
290+ * use the original path, including its actual-state unlock. */
291+ if (n < MMAP_THRESHOLD && !MT && !*(volatile int *)__malloc_lock) {
292+ int sc = size_to_class(n);
293+ struct meta *g = ctx.active[sc];
294+ if (g) {
295+ uint32_t mask = g->avail_mask;
296+ /* Refilling the sole group needs no queue changes when some
297+ * freed slots are already active. Grow inactive pages and
298+ * traverse other groups through the unchanged slow path. */
299+ if (!mask && g->next == g &&
300+ (g->freed_mask & ((2u<<g->mem->active_idx)-1))) {
301+ mask = activate_group(g);
302+ assert(mask);
303+ decay_bounces(g->sizeclass);
304+ }
305+ if (mask) {
306+ uint32_t first = mask & -mask;
307+ g->avail_mask = mask-first;
308+ return enframe(g, __builtin_ctz(first), n, ctx.mmap_counter);
309+ }
310+ }
311+ }
312+ return malloc_slow(n);
313+}
314+
315 int is_allzero(void *p)
316 {
317 struct meta *g = get_meta(p);
318- return g->sizeclass >= 48 ||
319- get_stride(g) < UNIT*size_classes[g->sizeclass];
320-}
321+ /* Cached large mappings contain the previous caller's data. calloc
322+ * must clear them; fresh large mappings take the same safe path. */
323+ return (!VINIX_MALLOC_RETAIN && g->sizeclass >= 48) ||
324+ (g->sizeclass < 48 && get_stride(g) < UNIT*size_classes[g->sizeclass]);
325+}
326--- a/src/malloc/mallocng/free.c
327+++ b/src/malloc/mallocng/free.c
328@@ -15,6 +15,26 @@
329 {
330 struct mapinfo mi = { 0 };
331 int sc = g->sizeclass;
332+ if (sc == 63) {
333+ int bucket = large_cache_index(g->maplen);
334+ if (bucket >= 0) {
335+ struct meta *old = ctx.large_cache[bucket];
336+ if (!old || old->maplen < g->maplen) {
337+ /* Keep the larger map so smaller prior requests cannot
338+ * cause permanent misses within this size bucket. */
339+ if (old) {
340+ mi.base = old->mem;
341+ mi.len = old->maplen*4096UL;
342+ free_meta(old);
343+ }
344+ /* free() validated and invalidated the caller's header.
345+ * Keep its metadata and mark the sole slot free. */
346+ g->freed_mask = 1;
347+ ctx.large_cache[bucket] = g;
348+ return mi; /* old mapping is unmapped after unlock */
349+ }
350+ }
351+ }
352 if (sc < 48) {
353 ctx.usage_by_class[sc] -= g->last_idx+1;
354 }
355@@ -45,6 +65,14 @@
356 if (sc >= 48 || get_stride(g) < UNIT*size_classes[sc])
357 return 1;
358
359+ /* Keep only the final ordinary group in a class. Nested small groups
360+ * are cheap in bytes but rebuilding their metadata on every free is
361+ * expensive. Multiple groups still consolidate via upstream policy. */
362+ if (VINIX_MALLOC_RETAIN && (g->next == g || (!g->next && !ctx.active[sc])) &&
363+ (g->maplen ? g->maplen*4096UL :
364+ UNIT + UNIT*size_classes[sc]*(g->last_idx+1)) <= RETAIN_GROUP_MAX_BYTES)
365+ return 0;
366+
367 // always free groups allocated inside another group's slot
368 // since recreating them should not be expensive and they
369 // might be blocking freeing of a much larger group.
370@@ -94,7 +122,8 @@
371 queue(&ctx.active[sc], g);
372 }
373 }
374- a_or(&g->freed_mask, self);
375+ if (!MT) g->freed_mask |= self;
376+ else a_or(&g->freed_mask, self);
377 return (struct mapinfo){ 0 };
378 }
379
380@@ -102,9 +131,10 @@
381 {
382 if (!p) return;
383
384- struct meta *g = get_meta(p);
385- int idx = get_slot_index(p);
386- size_t stride = get_stride(g);
387+ struct slot_info info;
388+ struct meta *g = get_meta_with_info(p, &info);
389+ int idx = info.index;
390+ size_t stride = info.stride;
391 unsigned char *start = g->mem->storage + stride*idx;
392 unsigned char *end = start + stride - IB;
393 get_nominal_size(p, end);
394@@ -113,6 +143,18 @@
395 // invalidate offset to group header, and cycle offset of
396 // used region within slot if current offset is zero.
397 *(uint16_t *)((char *)p-2) = 0;
398+
399+ /* With one thread, the sole retained ordinary group cannot need
400+ * queue maintenance or reclamation. Keep the normal freed-mask
401+ * publication so activation still rotates through all its slots.
402+ * Metadata, redzones and the caller header were checked above. */
403+ if (VINIX_MALLOC_RETAIN && !MT && g->sizeclass < 48 && g->next == g &&
404+ stride >= info.class_stride &&
405+ (g->maplen ? g->maplen*4096UL : UNIT + stride*(g->last_idx+1))
406+ <= RETAIN_GROUP_MAX_BYTES) {
407+ g->freed_mask |= self;
408+ return;
409+ }
410
411 // release any whole pages contained in the slot to be freed
412 // unless it's a single-slot group that will be unmapped.
413@@ -149,3 +191,45 @@
414 errno = e;
415 }
416 }
417+
418+/* Compatible with the GNU extension: release free groups and cached direct
419+ * mappings, preserving every live allocation. The padding hint is ignored.
420+ * The existing malloc lock also participates in musl's fork protocol. */
421+int malloc_trim(size_t pad)
422+{
423+ (void)pad;
424+ int released = 0, saved_errno = errno;
425+ wrlock();
426+ for (int i=0; i<LARGE_CACHE_COUNT; i++) {
427+ struct meta *g = ctx.large_cache[i];
428+ if (!g) continue;
429+ ctx.large_cache[i] = 0;
430+ void *base = g->mem;
431+ size_t len = g->maplen*4096UL;
432+ free_meta(g);
433+ if (!munmap(base, len)) released = 1;
434+ }
435+ /* Nested groups have a larger parent class, so release children first.
436+ * free_group() can make their parent free during this traversal. */
437+ for (int sc=0; sc<48; sc++) {
438+ for (;;) {
439+ struct meta *head = ctx.active[sc], *g = head;
440+ if (!head) break;
441+ do {
442+ if (g->freeable && (g->avail_mask|g->freed_mask)
443+ == (2u<<g->last_idx)-1) break;
444+ g = g->next;
445+ } while (g != head);
446+ if (!g->freeable || (g->avail_mask|g->freed_mask)
447+ != (2u<<g->last_idx)-1) break;
448+ dequeue(&ctx.active[sc], g);
449+ if (ctx.active[sc] && !ctx.active[sc]->avail_mask)
450+ activate_group(ctx.active[sc]);
451+ struct mapinfo mi = free_group(g);
452+ if (mi.len && !munmap(mi.base, mi.len)) released = 1;
453+ }
454+ }
455+ unlock();
456+ errno = saved_errno;
457+ return released;
458+}
459--- a/src/malloc/mallocng/glue.h
460+++ b/src/malloc/mallocng/glue.h
461@@ -30,7 +30,9 @@
462 #include <assert.h>
463 #else
464 #undef assert
465-#define assert(x) do { if (!(x)) a_crash(); } while(0)
466+/* Generic a_crash uses a null store, whose undefined behavior lets GCC
467+ * discard unused-result validation. A defined trap keeps every check. */
468+#define assert(x) do { if (!(x)) __builtin_trap(); } while(0)
469 #endif
470
471 #define brk(p) ((uintptr_t)__syscall(SYS_brk, p))
472@@ -75,7 +77,9 @@
473 }
474 static inline void unlock()
475 {
476- UNLOCK(__malloc_lock);
477+/* LOCK can turn negative need_locks into zero while still taking
478+ * this lock. Its actual state, not MT, decides whether to unlock. */
479+ if (*(volatile int *)__malloc_lock < 0) UNLOCK(__malloc_lock);
480 }
481 static inline void upgradelock()
482 {
483--- a/include/malloc.h
484+++ b/include/malloc.h
485@@ -17,6 +17,7 @@
486 void *memalign(size_t, size_t);
487
488 size_t malloc_usable_size(void *);
489+int malloc_trim(size_t);
490
491 #ifdef __cplusplus
492 }
493