| 1 |
/* "pma", a persistent memory allocator (implementation) |
| 2 |
Copyright (C) 2019, 2022 Terence Kelly |
| 3 |
Contact: tpkelly @ { acm.org, cs.princeton.edu, eecs.umich.edu } |
| 4 |
Home: http://web.eecs.umich.edu/~tpkelly/pma/ [or "https"] |
| 5 |
Design: HTML: https://queue.acm.org/detail.cfm?id=3534855 |
| 6 |
PDF: https://dl.acm.org/doi/pdf/10.1145/3534855 |
| 7 |
|
| 8 |
This program is free software: you can redistribute it and/or modify |
| 9 |
it under the terms of the GNU Affero General Public License as published by |
| 10 |
the Free Software Foundation, either version 3 of the License, or |
| 11 |
(at your option) any later version. |
| 12 |
|
| 13 |
This program is distributed in the hope that it will be useful, |
| 14 |
but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 15 |
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 16 |
GNU Affero General Public License for more details. |
| 17 |
|
| 18 |
You should have received a copy of the GNU Affero General Public License |
| 19 |
along with this program. If not, see <https://www.gnu.org/licenses/>. |
| 20 |
|
| 21 |
Code is intended to be (mostly) C99 / POSIX 2017. |
| 22 |
|
| 23 |
Compile and link with your programs in the obvious way. If |
| 24 |
assertions are enabled (the default) extensive integrity checks |
| 25 |
are frequently performed; these checks may be slow, depending on |
| 26 |
the size and state of the persistent heap. |
| 27 |
*/ |
| 28 |
|
| 29 |
#define _DEFAULT_SOURCE // for MAP_ANONYMOUS |
| 30 |
#include <assert.h> |
| 31 |
#include <errno.h> |
| 32 |
#include <fcntl.h> |
| 33 |
#include <inttypes.h> |
| 34 |
#include <limits.h> |
| 35 |
#include <math.h> |
| 36 |
#include <stdio.h> |
| 37 |
#include <string.h> |
| 38 |
#include <stdlib.h> |
| 39 |
#include <unistd.h> |
| 40 |
#include <sys/mman.h> |
| 41 |
#include <sys/stat.h> |
| 42 |
#include <sys/types.h> |
| 43 |
|
| 44 |
#include "pma.h" |
| 45 |
|
| 46 |
// Software version; not the same as backing file format version. |
| 47 |
const char pma_version[] = "2022.10Oct.30.1667172241 (Avon 8-g1)"; |
| 48 |
|
| 49 |
#define S(s) #s |
| 50 |
#define S2(s) S(s) |
| 51 |
#define COORDS __FILE__ ":" S2(__LINE__) ": " |
| 52 |
#define FP(...) (void)fprintf(stderr, COORDS __VA_ARGS__) |
| 53 |
#define ERN " errno => '%s'\n", strerror(errno) |
| 54 |
#define ERR(...) do { if (0 < state.vrb) FP("ERROR: " __VA_ARGS__); } while (0) |
| 55 |
#define WRN(...) do { if (1 < state.vrb) FP("Warning: " __VA_ARGS__); } while (0) |
| 56 |
#define FYI(...) do { if (2 < state.vrb) FP("FYI: " __VA_ARGS__); } while (0) |
| 57 |
|
| 58 |
int pma_errno; |
| 59 |
#define SE pma_errno = __LINE__ |
| 60 |
#define RL return __LINE__ |
| 61 |
#define RN return NULL |
| 62 |
#define SERL do { SE; RL; } while (0) |
| 63 |
#define SERN do { SE; RN; } while (0) |
| 64 |
|
| 65 |
enum { |
| 66 |
VERS = 2, // backing file format version number |
| 67 |
WDSZ = 8, // word size (bytes) |
| 68 |
NFL = 422, // number of free lists / size classes |
| 69 |
ALGN = 1024 * 1024 * 1024 // alignment of in-memory image of heap file |
| 70 |
}; |
| 71 |
|
| 72 |
typedef struct ao { // alloc object |
| 73 |
struct ao *anext, // header; singly linked list of all aos in addr order |
| 74 |
*fprev, *fnext; // for doubly linked free list |
| 75 |
} ao_t; |
| 76 |
|
| 77 |
// We stash three flags in the least significant bits of a header: |
| 78 |
// bit 0: is this ao in use (i.e., live, as opposed to free)? |
| 79 |
// bit 1: is the previous ao on the state.anext list in use? |
| 80 |
// bit 2: has this ao ever grown via realloc? |
| 81 |
|
| 82 |
static const uintptr_t lomask = 0x7, // we should really say "himask = ~lomask", but... |
| 83 |
himask = ~ ((uintptr_t) 0x7); // for obsolete compilers |
| 84 |
|
| 85 |
// extract bits from header |
| 86 |
#define HIBH(ao_t_ptr) ((ao_t *)((uintptr_t)(ao_t_ptr) & himask)) |
| 87 |
#define LOBH(ao_t_ptr) ((ao_t *)((uintptr_t)(ao_t_ptr) & lomask)) |
| 88 |
|
| 89 |
// size of an ao is its memory footprint; capacity of ao is number of bytes |
| 90 |
// available to caller; difference is header overhead of live (in-use) ao |
| 91 |
#define AOSZ(ao_t_ptr) ((size_t)((uintptr_t)HIBH((ao_t_ptr)->anext) - (uintptr_t)HIBH(ao_t_ptr))) |
| 92 |
#define AOCAP(ao_t_ptr) (AOSZ(ao_t_ptr) - WDSZ) |
| 93 |
|
| 94 |
#define Z1(i) assert(0 == (i) || 1 == (i)) |
| 95 |
static void slobh(ao_t *p, int iu, int piu, int grown) { // set low bits of header to which p points |
| 96 |
uintptr_t h; |
| 97 |
assert(p); Z1(iu); Z1(piu); Z1(grown); |
| 98 |
h = (uintptr_t)p->anext; |
| 99 |
h &= himask; // clear low bits |
| 100 |
h |= (uintptr_t)(iu | piu << 1 | grown << 2); |
| 101 |
p->anext = (ao_t *)h; |
| 102 |
} |
| 103 |
|
| 104 |
// getters below could be re-written as simpler macros |
| 105 |
|
| 106 |
static void globh(const ao_t *p, int *iu, int *piu, int *grown) { // get low bits of header to which p points |
| 107 |
uintptr_t h; |
| 108 |
assert(p && iu && piu && grown); |
| 109 |
h = (uintptr_t)p->anext; |
| 110 |
*iu = !!(h & 0x1); Z1(*iu); |
| 111 |
*piu = !!(h & 0x2); Z1(*piu); |
| 112 |
*grown = !!(h & 0x4); Z1(*grown); |
| 113 |
} |
| 114 |
|
| 115 |
typedef struct { // header of backing file; contains allocator metadata |
| 116 |
void * mapaddr; // virtual address where backing file must be mapped |
| 117 |
uint64_t bf_vers, // version number of backing file format |
| 118 |
nallocs, // number of allocations |
| 119 |
nfrees, // number of de-allocations |
| 120 |
res_0; // reserved for possible future use |
| 121 |
void * root; // live persistent data must be reachable from root |
| 122 |
ao_t * afirst, // list of all alloc objects, both live & free, in addr order |
| 123 |
* abound; // one beyond end of allocatable area |
| 124 |
ao_t free[NFL]; // free lists; each has dummy header |
| 125 |
} pma_hdr_t; |
| 126 |
|
| 127 |
static struct { |
| 128 |
int init, // has persistent heap been initialized? |
| 129 |
vrb; // verbsity level |
| 130 |
const char * file; // name of backing file |
| 131 |
pma_hdr_t * hdr; // addr where backing file is mapped |
| 132 |
} state; |
| 133 |
|
| 134 |
// #define ASI assert(1 == state.init || 2 == state.init) // assert state initialization |
| 135 |
#define ASI(...) \ |
| 136 |
do { if (! (1 == state.init || 2 == state.init)) { ERR("not initialized\n"); SE; assert(0); return __VA_ARGS__ ; } } while(0) |
| 137 |
|
| 138 |
enum { IU = 0, PIU = 1, GROWN = 2 }; |
| 139 |
|
| 140 |
static int getbit(ao_t *p, int bit) { |
| 141 |
int iu, piu, grown; |
| 142 |
globh(p, &iu, &piu, &grown); |
| 143 |
switch (bit) { |
| 144 |
case IU: return iu; |
| 145 |
case PIU: return piu; |
| 146 |
case GROWN: return grown; |
| 147 |
default: |
| 148 |
ERR("bad bit: %d\n", bit); |
| 149 |
SE; |
| 150 |
assert(0); |
| 151 |
return INT_MIN; |
| 152 |
} |
| 153 |
} |
| 154 |
|
| 155 |
#define DP(...) (void)fprintf(stderr, __VA_ARGS__) |
| 156 |
#define VS (void *) |
| 157 |
|
| 158 |
// valid ao ptr: |
| 159 |
#define VAO(p) (VS state.hdr->afirst <= VS (p) && VS state.hdr->abound > VS (p)) |
| 160 |
#ifndef NDEBUG |
| 161 |
static int valid_footer(ao_t *p) { |
| 162 |
if (!getbit(p, IU)) { |
| 163 |
ao_t **ftr = (ao_t **)HIBH(p->anext) - 1; |
| 164 |
return *ftr == p; // footer should point to header |
| 165 |
} |
| 166 |
else |
| 167 |
return 1; |
| 168 |
} |
| 169 |
#define VAF(p) (VAO(p) && valid_footer(p)) |
| 170 |
#endif // NDEBUG |
| 171 |
|
| 172 |
static void pao(ao_t *p) { // print ao |
| 173 |
int iu, piu, grown; |
| 174 |
ao_t **footer = (ao_t **) ((char *)p + AOSZ(p)) - 1; // TODO: squelch alignment warning? |
| 175 |
assert(VAO(p)); |
| 176 |
assert(0 == AOSZ(p) % WDSZ); |
| 177 |
assert(0 == LOBH(p)); |
| 178 |
globh(p, &iu, &piu, &grown); |
| 179 |
DP(" AO at %p: size %lu B / %lu w\n" |
| 180 |
" hdr %p (H 0%lo L 0%lo) iu %d piu %d grown %d\n" |
| 181 |
" fp %p%s\n" |
| 182 |
" fn %p%s\n" |
| 183 |
" ft %p%s\n", |
| 184 |
VS p, AOSZ(p), AOSZ(p) / WDSZ, |
| 185 |
VS p->anext, (uintptr_t)HIBH(p->anext), (uintptr_t)LOBH(p->anext), iu, piu, grown, |
| 186 |
VS p->fprev, iu ? " (ignore)" : "", |
| 187 |
VS p->fnext, iu ? " (ignore)" : "", |
| 188 |
VS *footer, iu ? " (ignore)" : ""); |
| 189 |
} |
| 190 |
|
| 191 |
static size_t UB[NFL]; // UB[c] is upper bound of size class c in machine words |
| 192 |
|
| 193 |
#define IC integrity_check(__LINE__) |
| 194 |
static int integrity_check(int line) { // can be slow; intended for debugging small heaps |
| 195 |
pma_hdr_t *h = state.hdr; |
| 196 |
int nadd = 0, naddfree = 0, tiu = 0, tpiu = 0, tf = 0; // beware overflow if lists are long |
| 197 |
FYI("integrity_check called from line %d\n", line); |
| 198 |
#ifdef NDEBUG |
| 199 |
WRN("integrity check relies on assertions, which are disabled (call at line %d)\n", line); |
| 200 |
#endif |
| 201 |
assert(h && h == h->mapaddr); |
| 202 |
// check addr-ordered list |
| 203 |
for (ao_t *next, *a = h->afirst; a < h->abound; a = next) { |
| 204 |
next = HIBH(a->anext); |
| 205 |
assert(VAF(a)); |
| 206 |
assert(32 <= AOSZ(a)); // TODO: magic number here |
| 207 |
assert(next > a && next <= h->abound); |
| 208 |
if (1000000 < ++nadd) { |
| 209 |
WRN("integrity check discontinued; anext list too long (call at line %d)\n", line); |
| 210 |
SE; // if persistent heap contains too many aos/blocks, |
| 211 |
return 0; // integrity check will be too slow; therefore discontinue |
| 212 |
} |
| 213 |
if (0 == getbit(a, IU)) |
| 214 |
++naddfree; |
| 215 |
tiu += getbit(a, IU); // total number of aos with in-use bit set |
| 216 |
tpiu += getbit(a, PIU); // total number of aos with previous-ao-is-in-use bit set |
| 217 |
} |
| 218 |
assert(tpiu == tiu || 1 + tpiu == tiu); |
| 219 |
FYI("anext list length: %d tiu %d tpiu %d nallocs %" PRIu64 " nfrees %" PRIu64 "\n", |
| 220 |
nadd, tiu, tpiu, h->nallocs, h->nfrees); |
| 221 |
assert(h->nallocs >= h->nfrees); |
| 222 |
assert(h->nallocs - h->nfrees == (uint64_t)tiu); |
| 223 |
// check free lists |
| 224 |
for (int i = 0; i < NFL; i++) { |
| 225 |
ao_t *p, *f = &(h->free[i]); |
| 226 |
if (f->fprev == f) // empty list |
| 227 |
assert(f->fnext == f); |
| 228 |
else { |
| 229 |
int nfwd = 0, nrev = 0; // count how many we find going forward and reverse |
| 230 |
for (p = f->fnext; p != f; p = p->fnext) { nfwd++; assert(VAF(p)); assert(0 == getbit(p, IU)); } |
| 231 |
for (p = f->fprev; p != f; p = p->fprev) { nrev++; assert(VAF(p)); assert(0 == getbit(p, IU)); } |
| 232 |
assert(nfwd == nrev); // count should be the same in both directions |
| 233 |
tf += nfwd; |
| 234 |
// check ao sizes against UB |
| 235 |
for (p = f->fnext; p != f; p = p->fnext) { |
| 236 |
#ifndef NDEBUG |
| 237 |
size_t capwords = AOCAP(p) / WDSZ; |
| 238 |
#endif |
| 239 |
assert(capwords <= UB[i]); |
| 240 |
if (0 < i) |
| 241 |
assert(capwords > UB[i-1]); |
| 242 |
} |
| 243 |
} |
| 244 |
} |
| 245 |
FYI("total free aos: %d naddfree %d integrity check line %d\n", tf, naddfree, line); |
| 246 |
assert(tf == naddfree); |
| 247 |
return 0; |
| 248 |
} |
| 249 |
|
| 250 |
#define NM " not meaningful in fallback mode\n" |
| 251 |
|
| 252 |
void pma_check_and_dump(void) { |
| 253 |
pma_hdr_t *h = state.hdr; |
| 254 |
ASI(); |
| 255 |
if (2 == state.init) { ERR("check_and_dump" NM); SE; assert(0); return; } |
| 256 |
if (IC) ERR("integrity check failed\n"); // proceed with dump anyway (?) |
| 257 |
DP(COORDS "check data structures and dump\n"); |
| 258 |
DP("header version: %s\n", PMA_H_VERSION); |
| 259 |
DP("software version: %s\n", pma_version); |
| 260 |
DP("sizeof state: %lu\n", sizeof state); |
| 261 |
DP("sizeof header: %lu\n", sizeof(pma_hdr_t)); |
| 262 |
DP("state:\n"); |
| 263 |
DP(" init: %d\n", state.init); assert(0 == state.init || 1 == state.init || 2 == state.init); |
| 264 |
DP(" vrb: %d\n", state.vrb); assert(0 <= state.vrb && 3 >= state.vrb); |
| 265 |
DP(" file: %p \"%s\"\n", (const void *)state.file, state.file); |
| 266 |
DP(" hdr: %p\n", VS h); |
| 267 |
if (NULL != h) { |
| 268 |
DP("header:\n"); // nallocs & nfrees not printed; they'd add noise to initial/final state diff |
| 269 |
DP(" mapaddr: %p\n", h->mapaddr); |
| 270 |
DP(" bf_vers: %" PRIu64 "\n", h->bf_vers); |
| 271 |
DP(" root: %p\n", h->root); assert(NULL == h->root || (h->root >= VS h->afirst && h->root < VS h->abound)); |
| 272 |
DP(" afirst: %p\n", VS h->afirst); assert(VS h->afirst > h->mapaddr); |
| 273 |
DP(" abound: %p\n", VS h->abound); assert(h->abound > h->afirst); |
| 274 |
DP(" all allocated objects in addr order:\n"); |
| 275 |
for (ao_t *a = h->afirst; a < h->abound; a = HIBH(a->anext)) { |
| 276 |
assert(HIBH(a->anext) > a); |
| 277 |
pao(a); |
| 278 |
} |
| 279 |
for (int i = 0; i < NFL; i++) { |
| 280 |
ao_t *f = &(h->free[i]); |
| 281 |
if (f->fprev == f) // empty list |
| 282 |
assert(f->fnext == f); |
| 283 |
else { |
| 284 |
DP(" free list of size class %d UB %lu (prev %lu) list head %p:\n", i, UB[i], i > 0 ? UB[i-1] : 0, VS f); |
| 285 |
for (ao_t *p = f->fnext; p != f; p = p->fnext) |
| 286 |
pao(p); |
| 287 |
} |
| 288 |
} |
| 289 |
} |
| 290 |
} |
| 291 |
#undef DP |
| 292 |
|
| 293 |
static int sc(size_t nbytes) { // compute size class; nbytes is malloc() arg |
| 294 |
static int init; |
| 295 |
const size_t maxwords = (size_t)0x1 << 61; // 2^61 words == 2^64 bytes |
| 296 |
size_t nwords; |
| 297 |
int c; |
| 298 |
if (! init) { |
| 299 |
FYI("initializing UB[]\n"); |
| 300 |
UB[0] = 3; // smallest allocation has size (AOSZ) 4 words and capacity (AOCAP) 3 words |
| 301 |
for (c = 1; ; c++) { |
| 302 |
long double hi = floorl((long double)(1 + UB[c-1]) * 1.1L); |
| 303 |
assert(NFL > c); |
| 304 |
if (hi >= (long double)maxwords) { UB[c] = maxwords; break; } |
| 305 |
else UB[c] = (size_t)hi; |
| 306 |
} |
| 307 |
assert(NFL - 1 == c); |
| 308 |
init = 1; |
| 309 |
} |
| 310 |
nwords = (nbytes / WDSZ) + !!(nbytes % WDSZ); |
| 311 |
assert(nwords <= maxwords); |
| 312 |
for (c = 0; NFL > c; c++) |
| 313 |
if (nwords <= UB[c]) |
| 314 |
break; |
| 315 |
assert(NFL > c); |
| 316 |
return c; |
| 317 |
} |
| 318 |
|
| 319 |
static void fli(ao_t *p) { // insert given ao at head of appropriate free list |
| 320 |
ao_t *h; |
| 321 |
int fl; |
| 322 |
assert(NULL != p); |
| 323 |
assert(VAO(p)); |
| 324 |
fl = sc(AOCAP(p)); |
| 325 |
assert(0 <= fl && NFL > fl); |
| 326 |
h = &(state.hdr->free[fl]); // head of free list |
| 327 |
FYI("fli(%p) h == %p h->fn %p h->fp %p\n", VS p, VS h, VS h->fnext, VS h->fprev); |
| 328 |
p->fprev = h; |
| 329 |
p->fnext = h->fnext; |
| 330 |
h->fnext->fprev = p; |
| 331 |
h->fnext = p; |
| 332 |
} |
| 333 |
|
| 334 |
static void flr(ao_t *p) { // remove ao from free list |
| 335 |
p->fnext->fprev = p->fprev; |
| 336 |
p->fprev->fnext = p->fnext; |
| 337 |
p->fprev = p->fnext = NULL; |
| 338 |
} |
| 339 |
|
| 340 |
// MAP_NORESERVE is not available on all systems. It might be safe to simply remove this |
| 341 |
// flag below if your system lacks it, though this expedient has not been tested extensively. |
| 342 |
|
| 343 |
// Here in gawk, we like to live dangerously: |
| 344 |
#ifndef MAP_NORESERVE |
| 345 |
#define MAP_NORESERVE 0 |
| 346 |
#endif /* MAP_NORESERVE */ |
| 347 |
|
| 348 |
#define MMAP(N) mmap(NULL, (N), PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0) |
| 349 |
#define MUNMAP(A, N) do { if (0 != munmap((A), (N))) { ERR("munmap()" ERN); SERN; } } while (0) |
| 350 |
static void * addrgap(off_t n) { // find big gap in address space to map n bytes |
| 351 |
void *A, *Amax = NULL; size_t L, U, Max = 0, N = (size_t)n; char *r; |
| 352 |
FYI("addrgap(%jd)\n", (intmax_t)n); // TODO: better way to handle off_t |
| 353 |
if (N < sizeof(pma_hdr_t) + 40960) { ERR("file size %zu too small\n", N); SERN; } |
| 354 |
// Binary search to find max length of successfull mmap(). |
| 355 |
// Invariants: |
| 356 |
// Larger max might lie in range [L,U] inclusive. |
| 357 |
// If a previous max has been found, it must lie in [1,L-1]. |
| 358 |
// A larger max cannot lie in [U+1,UINT64_MAX]. |
| 359 |
L = 1; // mmap fails if length == 0 (SUSv3) |
| 360 |
U = UINT64_MAX; |
| 361 |
while (L <= U) { |
| 362 |
size_t M = L + (U - L) / 2; // avoid overflow |
| 363 |
if (MAP_FAILED != (A = MMAP(M))) { assert(Max < M); Max = M; Amax = A; MUNMAP(A, M); if (UINT64_MAX == M) break; L = M + 1; } |
| 364 |
else { assert(0 < M); U = M - 1; } |
| 365 |
} |
| 366 |
FYI("max gap: %zu bytes at %p\n", Max, Amax); |
| 367 |
if (Max < N + (size_t)ALGN * 2) { // safety margin |
| 368 |
ERR("max gap %zu too small for required %zu\n", Max, N); |
| 369 |
SERN; |
| 370 |
} |
| 371 |
r = (char *)Amax + (Max - N)/2; |
| 372 |
if ((uintptr_t)r % ALGN) // align on conservative boundary |
| 373 |
r += (uintptr_t)ALGN - ((uintptr_t)r % ALGN); |
| 374 |
assert(0 == (uintptr_t)r % ALGN); |
| 375 |
FYI("addrgap returns %p == %lu\n", VS r, (uintptr_t)r); |
| 376 |
return r; |
| 377 |
} |
| 378 |
#undef MMAP |
| 379 |
#undef MUNMAP |
| 380 |
|
| 381 |
#define MM(a,s,f) mmap((a), (size_t)(s), PROT_READ | PROT_WRITE, MAP_SHARED, (f), 0) |
| 382 |
int pma_init(int verbose, const char *file) { |
| 383 |
int fd, pwr2flag = 0; long ps, pwr2; void *a1, *a2; char *ev; |
| 384 |
size_t as = sizeof(a1); struct stat s; |
| 385 |
pma_hdr_t *h; |
| 386 |
if (! (0 <= verbose && 3 >= verbose)) { SE; assert(0); RL; } // ERR macro wouldn't work here |
| 387 |
state.vrb = verbose; |
| 388 |
FYI("pma_init(%d,\"%s\")\n", verbose, file); |
| 389 |
if (NULL != (ev = getenv("PMA_VERBOSITY"))) { |
| 390 |
int newvrb; |
| 391 |
if (1 != sscanf(ev, "%1d", &newvrb)) { ERR("parsing envar verbosity \"%s\"\n", ev); SERL; } |
| 392 |
if (! (0 <= newvrb && 3 >= newvrb)) { ERR("bad envar verbosity %d\n", newvrb); SERL; } |
| 393 |
state.vrb = newvrb; |
| 394 |
WRN("envar verbosity over-ride %d -> %d\n", verbose, newvrb); |
| 395 |
} |
| 396 |
if (state.init) { ERR("already initialized\n"); SE; assert(0); RL; } |
| 397 |
FYI("software version '%s' expects backing file format version %d\n", |
| 398 |
pma_version, VERS); |
| 399 |
if (strcmp(pma_version, PMA_H_VERSION)) { |
| 400 |
ERR("software version mismatch: '%s' / '%s'\n", pma_version, PMA_H_VERSION); |
| 401 |
SE; assert(0); RL; } |
| 402 |
// check assumptions |
| 403 |
assert((himask & lomask) == (uintptr_t)0 ); |
| 404 |
assert((himask | lomask) == ~((uintptr_t)0)); |
| 405 |
if (! (WDSZ == sizeof(void *) && // in C11 we'd static_assert() |
| 406 |
WDSZ == sizeof(size_t) && |
| 407 |
WDSZ == sizeof(off_t) && |
| 408 |
WDSZ == sizeof(unsigned long))) { ERR("word size not 64 bits\n"); SERL; } |
| 409 |
assert(0 == sizeof(pma_hdr_t) % WDSZ); |
| 410 |
if (NULL == file) { |
| 411 |
WRN("no backing file provided; falling back on standard malloc\n"); |
| 412 |
state.init = 2; |
| 413 |
state.file = NULL; |
| 414 |
state.hdr = NULL; |
| 415 |
return 0; |
| 416 |
} |
| 417 |
if (4096 > (ps = sysconf(_SC_PAGESIZE))) { |
| 418 |
ERR("bad page size %ld, errno '%s'\n", ps, strerror(errno)); SERL; } |
| 419 |
for (pwr2 = 4096; pwr2 <= ALGN; pwr2 *= 2) |
| 420 |
if (pwr2 == ps) { pwr2flag = 1; break; } |
| 421 |
if (0 == pwr2flag) { |
| 422 |
ERR("page size %ld not a reasonable power of two\n", ps); SERL; } |
| 423 |
// map backing file containing persistent heap |
| 424 |
if (0 > (fd = open(file, O_RDWR))) { ERR("open()" ERN); SERL; } |
| 425 |
if (0 != fstat(fd, &s)) { ERR("fstat()" ERN); SERL; } |
| 426 |
if (!S_ISREG(s.st_mode)) { ERR("%s not regular file\n", file); SERL; } |
| 427 |
if ((ssize_t)as != read(fd, &a1, as)) { ERR("read()" ERN); SERL; } |
| 428 |
if (NULL == a1) a1 = addrgap(s.st_size); |
| 429 |
if (NULL == a1) { ERR("addrgap()" ERN); RL; } |
| 430 |
FYI("map at %p\n", a1); |
| 431 |
if (a1 != (a2 = MM(a1, s.st_size, fd))) { ERR("mmap()" ERN); SERL; } |
| 432 |
if (0 != close(fd)) { ERR("close()" ERN); SE; } // carry on |
| 433 |
state.init = 1; |
| 434 |
state.file = file; |
| 435 |
state.hdr = h = (pma_hdr_t *)a2; |
| 436 |
if (NULL == h->mapaddr) { |
| 437 |
int i; |
| 438 |
ao_t *w, **ftr; // initial "wilderness", footer |
| 439 |
FYI("initializing persistent heap\n"); |
| 440 |
if (s.st_size % ps) { |
| 441 |
ERR("backing file size %jd not multiple of page size %ld\n", (intmax_t)s.st_size, ps); |
| 442 |
SERL; |
| 443 |
} |
| 444 |
assert( 0 == h->bf_vers |
| 445 |
&& 0 == h->nallocs |
| 446 |
&& 0 == h->nfrees |
| 447 |
&& 0 == h->res_0 |
| 448 |
&& NULL == h->root |
| 449 |
&& NULL == h->afirst |
| 450 |
&& NULL == h->abound); |
| 451 |
for (i = 0; i < NFL; i++) { |
| 452 |
assert( NULL == h->free[i].anext |
| 453 |
&& NULL == h->free[i].fprev |
| 454 |
&& NULL == h->free[i].fnext); |
| 455 |
// free[i] is dummy node in doubly-linked free list; this simplifies code to splice aos into & out of free list |
| 456 |
h->free[i].fprev = h->free[i].fnext = &(h->free[i]); |
| 457 |
} |
| 458 |
h->mapaddr = h; |
| 459 |
h->bf_vers = VERS; |
| 460 |
h->nallocs = 0; |
| 461 |
h->nfrees = 0; |
| 462 |
h->res_0 = 0; |
| 463 |
h->afirst = (ao_t *)(1 + h); |
| 464 |
h->abound = (ao_t *)((char *)h + s.st_size); // TODO: squelch alignment warning? |
| 465 |
// install "wilderness" free ao on all-object list; every free ao has a |
| 466 |
// footer pointing to its header, to facilitate coalescing adjacent frees; |
| 467 |
// header on final ao points beyond allocatable area |
| 468 |
w = h->afirst; |
| 469 |
w->anext = h->abound; |
| 470 |
assert(0 == AOSZ(w) % WDSZ && WDSZ < AOSZ(w)); |
| 471 |
ftr = (ao_t **)h->abound - 1; |
| 472 |
*ftr = w; |
| 473 |
fli(w); |
| 474 |
} |
| 475 |
else { |
| 476 |
FYI("persistent heap already initialized\n"); |
| 477 |
// Page size may change during life of heap. We insist that |
| 478 |
// backing file is multiple of page size at time of birth, but |
| 479 |
// for already-initialized heaps we issue warning only. |
| 480 |
if (s.st_size % ps) |
| 481 |
WRN("backing file size %jd not multiple of page size %ld\n", (intmax_t)s.st_size, ps); |
| 482 |
if (VERS != h->bf_vers) { |
| 483 |
ERR("backing file version mismatch: %d vs. %" PRIu64 "\n", VERS, h->bf_vers); |
| 484 |
SERL; |
| 485 |
} |
| 486 |
(void)sc(1); // to populate UB[] |
| 487 |
} |
| 488 |
assert(!IC); |
| 489 |
return 0; |
| 490 |
} |
| 491 |
#undef MM |
| 492 |
|
| 493 |
// bite off adequate prefix if ao is too large, return remainder to appropriate |
| 494 |
// free list; must handle two cases: given ao is free, versus given ao is live |
| 495 |
// and is being shrunk by realloc |
| 496 |
static ao_t * split_ao(ao_t *p, size_t s) { |
| 497 |
size_t c = AOCAP(p), Cw = c / WDSZ, Sw; int iu, piu, grown; ao_t *n; |
| 498 |
if (s < 24) s = 24; // increase request size to minimum allocation size if necessary; TODO: magic number here |
| 499 |
Sw = s / WDSZ + !!(s % WDSZ); |
| 500 |
assert(NULL == LOBH(p)); // lo bits of header (p->anext) might be set, but not lo bits of p |
| 501 |
assert(NULL == p->fprev && NULL == p->fnext); // *p should already be spliced out of free lists |
| 502 |
assert(c >= s && 0 == c % WDSZ); |
| 503 |
FYI("split_ao(%p,%zu) AOCAP %zu words req %zu words cap %zu\n", VS p, s, c, Sw, Cw); |
| 504 |
globh(p, &iu, &piu, &grown); |
| 505 |
if (4 <= Cw - Sw) { // split ao if remainder is large enough to be allocatable |
| 506 |
ao_t *rem = (ao_t *)(&(p->fprev) + Sw), // remainder |
| 507 |
**rft = (ao_t **)HIBH(p->anext) - 1; // footer of remainder |
| 508 |
FYI("splitting at %p\n", VS rem); |
| 509 |
rem->anext = HIBH(p->anext); // set header of remainder |
| 510 |
*rft = rem; // set footer of remainder |
| 511 |
fli(rem); |
| 512 |
p->anext = rem; // set header of *p |
| 513 |
} |
| 514 |
assert(AOCAP(p) >= s); |
| 515 |
slobh(p, 1, piu, grown); // in-use bit is set; values of prev-in-use and grown bits are preserved |
| 516 |
// set prev-in-use bit of next ao on anext list (if such exists), preserving iu and grown bits |
| 517 |
n = HIBH(p->anext); |
| 518 |
assert(n <= state.hdr->abound); |
| 519 |
if (n < state.hdr->abound) { |
| 520 |
globh(n, &iu, &piu, &grown); |
| 521 |
slobh(n, iu, 1, grown); |
| 522 |
} |
| 523 |
return p; |
| 524 |
} |
| 525 |
|
| 526 |
// TODO: add FYIs to consistently report return values of malloc, realloc, calloc |
| 527 |
|
| 528 |
void * pma_malloc(size_t size) { |
| 529 |
ao_t *r = NULL; |
| 530 |
FYI("malloc(%zu)\n", size); |
| 531 |
ASI(NULL); |
| 532 |
if (2 == state.init) return malloc(size); |
| 533 |
assert(!IC); |
| 534 |
if (0 >= size) { |
| 535 |
WRN("malloc(%zu) argument <= zero\n", size); SERN; } |
| 536 |
for (int c = sc(size); c < NFL; c++) { |
| 537 |
ao_t *h = &(state.hdr->free[c]); |
| 538 |
// FYI("check size class %d UB %zu\n", c, UB[c]); |
| 539 |
for (ao_t *f = h->fnext; f != h; f = f->fnext) { |
| 540 |
// FYI("free list contains ao with capacity %zu\n", AOCAP(f)); |
| 541 |
if (AOCAP(f) >= size) { |
| 542 |
r = f; |
| 543 |
goto end; |
| 544 |
} |
| 545 |
} |
| 546 |
} |
| 547 |
end: |
| 548 |
if (NULL != r) { |
| 549 |
flr(r); |
| 550 |
r = split_ao(r, size); |
| 551 |
FYI("malloc returning %p\n", VS &(r->fprev)); |
| 552 |
++(state.hdr->nallocs); |
| 553 |
assert(!IC); |
| 554 |
return &(r->fprev); |
| 555 |
} |
| 556 |
else { |
| 557 |
WRN("malloc(%zu) cannot satisfy request at this time\n", size); |
| 558 |
SERN; // conflates ENOMEM / EAGAIN (request might succeed after frees) |
| 559 |
} |
| 560 |
} |
| 561 |
|
| 562 |
void * pma_calloc(size_t nmemb, size_t size) { |
| 563 |
void *p; |
| 564 |
FYI("calloc(%zu,%zu)\n", nmemb, size); |
| 565 |
ASI(NULL); |
| 566 |
if (2 == state.init) return calloc(nmemb, size); |
| 567 |
if (0 >= nmemb || 0 >= size) { |
| 568 |
WRN("calloc(%zu,%zu) argument <= zero\n", nmemb, size); SERN; } |
| 569 |
// SSIZE_MAX exists but SIZE_MAX apparently doesn't; sheesh |
| 570 |
if (nmemb > UINT64_MAX / size) { |
| 571 |
WRN("calloc(%zu,%zu) arguments overflow\n", nmemb, size); SERN; } |
| 572 |
if (NULL != (p = pma_malloc(nmemb * size))) |
| 573 |
(void)memset(p, 0, nmemb * size); |
| 574 |
return p; |
| 575 |
} |
| 576 |
|
| 577 |
void * pma_realloc(void *ptr, size_t size) { |
| 578 |
ao_t *p; void *nu; // "new" is a C++ keyword |
| 579 |
FYI("realloc(%p,%zu)\n", ptr, size); |
| 580 |
ASI(NULL); |
| 581 |
if (2 == state.init) return realloc(ptr, size); |
| 582 |
if (NULL == ptr) return pma_malloc(size); |
| 583 |
if (0 >= size) { pma_free(ptr); RN; } |
| 584 |
p = (ao_t *)((ao_t **)ptr - 1); |
| 585 |
if (AOCAP(p) >= size) // no growth needed |
| 586 |
return ptr; |
| 587 |
nu = pma_malloc(size); |
| 588 |
if (NULL == nu) |
| 589 |
SERN; |
| 590 |
(void)memcpy(nu, ptr, AOCAP(p)); |
| 591 |
pma_free(ptr); |
| 592 |
return nu; |
| 593 |
} |
| 594 |
|
| 595 |
// Merge *p with next ao on anext list; returns 1 if coalesces, 0 otherwise. |
| 596 |
// Flag indicates which of the two aos is on the free list and must be removed. |
| 597 |
static int coalesce(ao_t *p, int flr_lo_hi) { |
| 598 |
ao_t *n = HIBH(p->anext), **ftr; int piu; |
| 599 |
assert(n > p && n <= state.hdr->abound); |
| 600 |
FYI("coalesce(%p)\n", VS p); |
| 601 |
if (n >= state.hdr->abound) // *p is final ao on anext list |
| 602 |
return 0; |
| 603 |
if (0 == getbit(n, IU)) { // next ao is not in use, therefore coalesce |
| 604 |
flr(flr_lo_hi ? n : p); // remove appropriate ao from free list |
| 605 |
piu = getbit(p, PIU); |
| 606 |
p->anext = HIBH(n->anext); |
| 607 |
ftr = (ao_t **)p->anext - 1; |
| 608 |
*ftr = p; |
| 609 |
slobh(p, 0, piu, 0); // preserve prev-in-use bit of header of *p |
| 610 |
return 1; |
| 611 |
} |
| 612 |
else // next ao is in use, therefore do not coalesce |
| 613 |
return 0; |
| 614 |
} |
| 615 |
|
| 616 |
void pma_free(void *ptr) { |
| 617 |
ao_t *p, *n, **ftr; int r; |
| 618 |
FYI("free(%p)\n", ptr); |
| 619 |
ASI(); |
| 620 |
if (2 == state.init) { free(ptr); return; } |
| 621 |
assert(!IC); |
| 622 |
if (NULL == ptr) return; // allowed by C & POSIX |
| 623 |
if (! (VS state.hdr->afirst <= ptr && VS state.hdr->abound > ptr)) { // e.g., p=strdup("foo") ... pma_free(p); |
| 624 |
ERR("freed ptr %p outside allocatable area bounds %p %p\n", |
| 625 |
ptr, VS state.hdr->afirst, VS state.hdr->abound); |
| 626 |
SE; |
| 627 |
assert(0); |
| 628 |
return; |
| 629 |
} |
| 630 |
assert(0 == (uintptr_t)ptr % WDSZ); |
| 631 |
p = (ao_t *)((ao_t **)ptr - 1); |
| 632 |
assert(VAO(p)); |
| 633 |
n = HIBH(p->anext); |
| 634 |
assert(p < n && n <= state.hdr->abound); |
| 635 |
assert(1 == getbit(p, IU)); |
| 636 |
slobh(p, 0, getbit(p, PIU), 0); // clear iu and grown bits of *p header |
| 637 |
if (n < state.hdr->abound) |
| 638 |
assert(1 == getbit(n, PIU)); |
| 639 |
FYI("merge with right/higher ao\n"); |
| 640 |
r = coalesce(p, 1); |
| 641 |
FYI("%s\n", r ? "yes" : "no"); |
| 642 |
if (0 == getbit(p, PIU) && p > state.hdr->afirst) { // if ao is not leftmost/lowest and previous/lower ao is not in use, merge |
| 643 |
ao_t *prev = *((ao_t **)p - 1); |
| 644 |
assert(prev < p); |
| 645 |
FYI("merge with left/lower ao\n"); |
| 646 |
r = coalesce(prev, 0); |
| 647 |
assert(r); |
| 648 |
p = prev; |
| 649 |
} |
| 650 |
#ifndef NDEBUG |
| 651 |
(void)memset(&(p->fprev), 0, AOCAP(p)); // for near-complete "reversibility" |
| 652 |
#endif |
| 653 |
n = HIBH(p->anext); |
| 654 |
assert(p < n && n <= state.hdr->abound); |
| 655 |
ftr = (ao_t **)n - 1; |
| 656 |
*ftr = p; |
| 657 |
if (n < state.hdr->abound) |
| 658 |
slobh(n, getbit(n, IU), 0, getbit(n, GROWN)); // clear prev-in-use bit of next |
| 659 |
fli(p); |
| 660 |
++(state.hdr->nfrees); |
| 661 |
assert(!IC); |
| 662 |
} |
| 663 |
|
| 664 |
void pma_set_root(void *p) { // TODO: return success/fail indicator? |
| 665 |
FYI("set_root(%p)\n", p); |
| 666 |
ASI(); |
| 667 |
if (2 == state.init) { ERR("set_root" NM); SE; assert(0); return; } |
| 668 |
if (! (NULL == p || VAO(p))) { ERR("bad root %p\n", p); SE; assert(0); return; } |
| 669 |
// could also check that p "looks like" pointer returned by pma_malloc, |
| 670 |
// e.g., header's in-use bit should be set and HIBH should be reasonable |
| 671 |
state.hdr->root = p; |
| 672 |
} |
| 673 |
|
| 674 |
void * pma_get_root(void) { |
| 675 |
void *p; |
| 676 |
FYI("get_root()\n"); |
| 677 |
ASI(NULL); |
| 678 |
if (2 == state.init) { ERR("get_root" NM); SE; assert(0); RN; } |
| 679 |
p = state.hdr->root; |
| 680 |
assert(NULL == p || VAO(p)); |
| 681 |
return p; |
| 682 |
} |
| 683 |
|
| 684 |
typedef unsigned long ul_t; |
| 685 |
void pma_set_avail_mem(const ul_t v) { |
| 686 |
FYI("set_avail_mem(0x%lx)\n", v); |
| 687 |
ASI(); |
| 688 |
if (2 == state.init) { ERR("set_avail_mem" NM); SE; assert(0); return; } |
| 689 |
assert(!IC); |
| 690 |
for (int i = 0; i < NFL; i++) { |
| 691 |
ao_t *p, *f = &(state.hdr->free[i]); |
| 692 |
if (f->fprev != f) |
| 693 |
for (p = f->fnext; p != f; p = p->fnext) { |
| 694 |
ul_t *q = (ul_t *)(1 + p), |
| 695 |
*e = (ul_t *)(HIBH(p->anext)) - 1; |
| 696 |
for ( ; q != e; q++) |
| 697 |
if (*q != v) // avoid over-writing same value; gratuitous modification is a Bad Thing for persistent memory |
| 698 |
*q = v; |
| 699 |
for ( ; q != e; q++) |
| 700 |
assert(*q == v); |
| 701 |
} |
| 702 |
} |
| 703 |
assert(!IC); |
| 704 |
} |
| 705 |
|