summaryrefslogtreecommitdiff
path: root/storage/tokudb/PerconaFT/portability/memory.cc
blob: 403abfe1d68dc159327605559b2f122c1ec2fd73 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*- */
// vim: ft=cpp:expandtab:ts=8:sw=4:softtabstop=4:
#ident "$Id$"
/*======
This file is part of PerconaFT.


Copyright (c) 2006, 2015, Percona and/or its affiliates. All rights reserved.

    PerconaFT is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License, version 2,
    as published by the Free Software Foundation.

    PerconaFT is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with PerconaFT.  If not, see <http://www.gnu.org/licenses/>.

----------------------------------------

    PerconaFT is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License, version 3,
    as published by the Free Software Foundation.

    PerconaFT is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with PerconaFT.  If not, see <http://www.gnu.org/licenses/>.
======= */

#ident "Copyright (c) 2006, 2015, Percona and/or its affiliates. All rights reserved."

#include <portability/toku_config.h>

#include <toku_portability.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#if defined(HAVE_MALLOC_H)
# include <malloc.h>
#elif defined(HAVE_SYS_MALLOC_H)
# include <sys/malloc.h>
#endif
#include <dlfcn.h>
#include <toku_race_tools.h>
#include "memory.h"
#include "toku_assert.h"
#include <portability/toku_atomic.h>

static malloc_fun_t  t_malloc  = 0;
static malloc_aligned_fun_t t_malloc_aligned = 0;
static malloc_fun_t  t_xmalloc = 0;
static malloc_aligned_fun_t t_xmalloc_aligned = 0;
static free_fun_t    t_free    = 0;
static realloc_fun_t t_realloc = 0;
static realloc_aligned_fun_t t_realloc_aligned = 0;
static realloc_fun_t t_xrealloc = 0;

static LOCAL_MEMORY_STATUS_S status;
int toku_memory_do_stats = 0;

static bool memory_startup_complete;

int
toku_memory_startup(void) {
    if (memory_startup_complete) {
        return 0;
    }
    memory_startup_complete = true;

    int result = 0;

#if defined(HAVE_M_MMAP_THRESHOLD)
    // initialize libc malloc
    size_t mmap_threshold = 64 * 1024; // 64K and larger should be malloced with mmap().
    int success = mallopt(M_MMAP_THRESHOLD, mmap_threshold);
    if (success) {
        status.mallocator_version = "libc";
        status.mmap_threshold = mmap_threshold;
    } else
        result = EINVAL;
#else
    // just a guess
    status.mallocator_version = "darwin";
    status.mmap_threshold = 16 * 1024;
#endif

    // jemalloc has a mallctl function, while libc malloc does not.  we can check if jemalloc 
    // is loaded by checking if the mallctl function can be found.  if it can, we call it 
    // to get version and mmap threshold configuration.
    typedef int (*mallctl_fun_t)(const char *, void *, size_t *, void *, size_t);
    mallctl_fun_t mallctl_f;
    mallctl_f = (mallctl_fun_t) dlsym(RTLD_DEFAULT, "mallctl");
    if (mallctl_f) { // jemalloc is loaded
        size_t version_length = sizeof status.mallocator_version;
        result = mallctl_f("version", &status.mallocator_version, &version_length, NULL, 0);
        if (result == 0) {
            size_t lg_chunk; // log2 of the mmap threshold
            size_t lg_chunk_length = sizeof lg_chunk;
            result  = mallctl_f("opt.lg_chunk", &lg_chunk, &lg_chunk_length, NULL, 0);
            if (result)
            {
                status.mmap_threshold = 1 << 21; // Default value.
                                                 // Incompatible jemalloc change.
                result = 0;
            }
            else
                status.mmap_threshold = 1 << lg_chunk;
        }
    }

    return result;
}

static bool memory_shutdown_complete;

void
toku_memory_shutdown(void) {
    if (memory_shutdown_complete) {
        return;
    }
    memory_shutdown_complete = true;
}

void 
toku_memory_get_status(LOCAL_MEMORY_STATUS s) {
    *s = status;
}

// jemalloc's malloc_usable_size does not work with a NULL pointer, so we implement a version that works
static size_t
my_malloc_usable_size(void *p) {
    return p == NULL ? 0 : os_malloc_usable_size(p);
}

// Note that max_in_use may be slightly off because use of max_in_use is not thread-safe.
// It is not worth the overhead to make it completely accurate, but
// this logic is intended to guarantee that it increases monotonically.
// Note that status.sum_used and status.sum_freed increase monotonically
// and that status.max_in_use is declared volatile.
static inline void 
set_max(uint64_t sum_used, uint64_t sum_freed) {
    if (sum_used >= sum_freed) {
        uint64_t in_use = sum_used - sum_freed;
        uint64_t old_max;
        do {
            old_max = status.max_in_use;
        } while (old_max < in_use &&
                 !toku_sync_bool_compare_and_swap(&status.max_in_use, old_max, in_use));
    }
}

// Effect: Like toku_memory_footprint, except instead of passing p,
//   we pass toku_malloc_usable_size(p).
size_t 
toku_memory_footprint_given_usable_size(size_t touched, size_t usable)
{
    size_t pagesize = toku_os_get_pagesize();
    if (usable >= status.mmap_threshold) {
        int num_pages = (touched + pagesize) / pagesize;
        return num_pages * pagesize;
    }
    return usable;
}

// Effect: Return an estimate how how much space an object is using, possibly by
//   using toku_malloc_usable_size(p).
//   If p is NULL then returns 0.
size_t
toku_memory_footprint(void * p, size_t touched)
{
    if (!p) return 0;
    return toku_memory_footprint_given_usable_size(touched,
                                                   my_malloc_usable_size(p));
}

void *
toku_malloc(size_t size) {
#if defined(__APPLE__)
    if (size == 0) {
        return nullptr;
    }
#endif

    if (size > status.max_requested_size) {
        status.max_requested_size = size;
    }
    void *p = t_malloc ? t_malloc(size) : os_malloc(size);
    if (p) {
        TOKU_ANNOTATE_NEW_MEMORY(p, size); // see #4671 and https://bugs.kde.org/show_bug.cgi?id=297147
        if (toku_memory_do_stats) {
            size_t used = my_malloc_usable_size(p);
            toku_sync_add_and_fetch(&status.malloc_count, 1);
            toku_sync_add_and_fetch(&status.requested,size);
            toku_sync_add_and_fetch(&status.used, used);
            set_max(status.used, status.freed);
        }
    } else {
        toku_sync_add_and_fetch(&status.malloc_fail, 1);
        status.last_failed_size = size;
    }
  return p;
}

void *toku_malloc_aligned(size_t alignment, size_t size) {
#if defined(__APPLE__)
    if (size == 0) {
        return nullptr;
    }
#endif

    if (size > status.max_requested_size) {
        status.max_requested_size = size;
    }
    void *p = t_malloc_aligned ? t_malloc_aligned(alignment, size) : os_malloc_aligned(alignment, size);
    if (p) {
        TOKU_ANNOTATE_NEW_MEMORY(p, size); // see #4671 and https://bugs.kde.org/show_bug.cgi?id=297147
        if (toku_memory_do_stats) {
            size_t used = my_malloc_usable_size(p);
            toku_sync_add_and_fetch(&status.malloc_count, 1);
            toku_sync_add_and_fetch(&status.requested,size);
            toku_sync_add_and_fetch(&status.used, used);
            set_max(status.used, status.freed);
        }
    } else {
        toku_sync_add_and_fetch(&status.malloc_fail, 1);
        status.last_failed_size = size;
    }
  return p;
}

void *
toku_calloc(size_t nmemb, size_t size) {
    size_t newsize = nmemb * size;
    void *p = toku_malloc(newsize);
    if (p) memset(p, 0, newsize);
    return p;
}

void *
toku_realloc(void *p, size_t size) {
#if defined(__APPLE__)
    if (size == 0) {
        if (p != nullptr) {
            toku_free(p);
        }
        return nullptr;
    }
#endif

    if (size > status.max_requested_size) {
        status.max_requested_size = size;
    }
    size_t used_orig = p ? my_malloc_usable_size(p) : 0;
    void *q = t_realloc ? t_realloc(p, size) : os_realloc(p, size);
    if (q) {
        if (toku_memory_do_stats) {
            size_t used = my_malloc_usable_size(q);
            toku_sync_add_and_fetch(&status.realloc_count, 1);
            toku_sync_add_and_fetch(&status.requested, size);
            toku_sync_add_and_fetch(&status.used, used);
            toku_sync_add_and_fetch(&status.freed, used_orig);
            set_max(status.used, status.freed);
        }
    } else {
        toku_sync_add_and_fetch(&status.realloc_fail, 1);
        status.last_failed_size = size;
    }
    return q;
}

void *toku_realloc_aligned(size_t alignment, void *p, size_t size) {
#if defined(__APPLE__)
    if (size == 0) {
        if (p != nullptr) {
            toku_free(p);
        }
        return nullptr;
    }
#endif

    if (size > status.max_requested_size) {
        status.max_requested_size = size;
    }
    size_t used_orig = p ? my_malloc_usable_size(p) : 0;
    void *q = t_realloc_aligned ? t_realloc_aligned(alignment, p, size) : os_realloc_aligned(alignment, p, size);
    if (q) {
        if (toku_memory_do_stats) {
            size_t used = my_malloc_usable_size(q);
            toku_sync_add_and_fetch(&status.realloc_count, 1);
            toku_sync_add_and_fetch(&status.requested, size);
            toku_sync_add_and_fetch(&status.used, used);
            toku_sync_add_and_fetch(&status.freed, used_orig);
            set_max(status.used, status.freed);
        }
    } else {
        toku_sync_add_and_fetch(&status.realloc_fail, 1);
        status.last_failed_size = size;
    }
    return q;
}


void *
toku_memdup(const void *v, size_t len) {
    void *p = toku_malloc(len);
    if (p) memcpy(p, v,len);
    return p;
}

char *
toku_strdup(const char *s) {
    return (char *) toku_memdup(s, strlen(s)+1);
}

char *toku_strndup(const char *s, size_t n) {
    size_t s_size = strlen(s);
    size_t bytes_to_copy = n > s_size ? s_size : n;
    ++bytes_to_copy;
    char *result = (char *)toku_memdup(s, bytes_to_copy);
    result[bytes_to_copy - 1] = 0;
    return result;
}

void
toku_free(void *p) {
    if (p) {
        if (toku_memory_do_stats) {
            size_t used = my_malloc_usable_size(p);
            toku_sync_add_and_fetch(&status.free_count, 1);
            toku_sync_add_and_fetch(&status.freed, used);
        }
        if (t_free)
            t_free(p);
        else
            os_free(p);
    }
}

void *
toku_xmalloc(size_t size) {
#if defined(__APPLE__)
    if (size == 0) {
        return nullptr;
    }
#endif

    if (size > status.max_requested_size) {
        status.max_requested_size = size;
    }
    void *p = t_xmalloc ? t_xmalloc(size) : os_malloc(size);
    if (p == NULL) {  // avoid function call in common case
        status.last_failed_size = size;
        resource_assert(p);
    }
    TOKU_ANNOTATE_NEW_MEMORY(p, size); // see #4671 and https://bugs.kde.org/show_bug.cgi?id=297147
    if (toku_memory_do_stats) {
        size_t used = my_malloc_usable_size(p);
        toku_sync_add_and_fetch(&status.malloc_count, 1);
        toku_sync_add_and_fetch(&status.requested, size);
        toku_sync_add_and_fetch(&status.used, used);
        set_max(status.used, status.freed);
    }
    return p;
}

void* toku_xmalloc_aligned(size_t alignment, size_t size)
// Effect: Perform a malloc(size) with the additional property that the returned pointer is a multiple of ALIGNMENT.
//  Fail with a resource_assert if the allocation fails (don't return an error code).
// Requires: alignment is a power of two.
{
#if defined(__APPLE__)
    if (size == 0) {
        return nullptr;
    }
#endif

    if (size > status.max_requested_size) {
        status.max_requested_size = size;
    }
    void *p = t_xmalloc_aligned ? t_xmalloc_aligned(alignment, size) : os_malloc_aligned(alignment,size);
    if (p == NULL && size != 0) {
        status.last_failed_size = size;
        resource_assert(p);
    }
    if (toku_memory_do_stats) {
        size_t used = my_malloc_usable_size(p);
        toku_sync_add_and_fetch(&status.malloc_count, 1);
        toku_sync_add_and_fetch(&status.requested, size);
        toku_sync_add_and_fetch(&status.used, used);
        set_max(status.used, status.freed);
    }
    return p;
}

void *
toku_xcalloc(size_t nmemb, size_t size) {
    size_t newsize = nmemb * size;
    void *vp = toku_xmalloc(newsize);
    if (vp) memset(vp, 0, newsize);
    return vp;
}

void *
toku_xrealloc(void *v, size_t size) {
#if defined(__APPLE__)
    if (size == 0) {
        if (v != nullptr) {
            toku_free(v);
        }
        return nullptr;
    }
#endif

    if (size > status.max_requested_size) {
        status.max_requested_size = size;
    }
    size_t used_orig = v ? my_malloc_usable_size(v) : 0;
    void *p = t_xrealloc ? t_xrealloc(v, size) : os_realloc(v, size);
    if (p == 0) {  // avoid function call in common case
        status.last_failed_size = size;
        resource_assert(p);
    }
    if (toku_memory_do_stats) {
        size_t used = my_malloc_usable_size(p);
        toku_sync_add_and_fetch(&status.realloc_count, 1);
        toku_sync_add_and_fetch(&status.requested, size);
        toku_sync_add_and_fetch(&status.used, used);
        toku_sync_add_and_fetch(&status.freed, used_orig);
        set_max(status.used, status.freed);
    }
    return p;
}

size_t 
toku_malloc_usable_size(void *p) {
    return my_malloc_usable_size(p);
}

void *
toku_xmemdup (const void *v, size_t len) {
    void *p = toku_xmalloc(len);
    memcpy(p, v, len);
    return p;
}

char *
toku_xstrdup (const char *s) {
    return (char *) toku_xmemdup(s, strlen(s)+1);
}

void
toku_set_func_malloc(malloc_fun_t f) {
    t_malloc = f;
    t_xmalloc = f;
}

void
toku_set_func_xmalloc_only(malloc_fun_t f) {
    t_xmalloc = f;
}

void
toku_set_func_malloc_only(malloc_fun_t f) {
    t_malloc = f;
}

void
toku_set_func_realloc(realloc_fun_t f) {
    t_realloc = f;
    t_xrealloc = f;
}

void
toku_set_func_xrealloc_only(realloc_fun_t f) {
    t_xrealloc = f;
}

void
toku_set_func_realloc_only(realloc_fun_t f) {
    t_realloc = f;

}

void
toku_set_func_free(free_fun_t f) {
    t_free = f;
}

#include <toku_race_tools.h>
void __attribute__((constructor)) toku_memory_helgrind_ignore(void);
void
toku_memory_helgrind_ignore(void) {
    TOKU_VALGRIND_HG_DISABLE_CHECKING(&status, sizeof status);
}