Welcome to mirror list, hosted at ThFree Co, Russian Federation.

mallocn_lockfree_impl.c « intern « guardedalloc « intern - git.blender.org/blender.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: ce8a5b29eceb898507076b5d209f099caf9f3b8a (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
/*
 * ***** BEGIN GPL LICENSE BLOCK *****
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program 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 this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 * Contributor(s): Brecht Van Lommel
 *                 Campbell Barton
 *                 Sergey Sharybin
 *
 * ***** END GPL LICENSE BLOCK *****
 */

/** \file guardedalloc/intern/mallocn.c
 *  \ingroup MEM
 *
 * Memory allocation which keeps track on allocated memory counters
 */

#include <stdlib.h>
#include <string.h> /* memcpy */
#include <stdarg.h>
#include <sys/types.h>

#include "MEM_guardedalloc.h"

/* to ensure strict conversions */
#include "../../source/blender/blenlib/BLI_strict_flags.h"

#include "atomic_ops.h"
#include "mallocn_intern.h"

typedef struct MemHead {
	/* Length of allocated memory block. */
	size_t len;
} MemHead;

typedef struct MemHeadAligned {
	short alignment;
	size_t len;
} MemHeadAligned;

static unsigned int totblock = 0;
static size_t mem_in_use = 0, mmap_in_use = 0, peak_mem = 0;
static bool malloc_debug_memset = false;

static void (*error_callback)(const char *) = NULL;
static void (*thread_lock_callback)(void) = NULL;
static void (*thread_unlock_callback)(void) = NULL;

enum {
	MEMHEAD_MMAP_FLAG = 1,
	MEMHEAD_ALIGN_FLAG = 2,
};

#define MEMHEAD_FROM_PTR(ptr) (((MemHead*) vmemh) - 1)
#define PTR_FROM_MEMHEAD(memhead) (memhead + 1)
#define MEMHEAD_ALIGNED_FROM_PTR(ptr) (((MemHeadAligned*) vmemh) - 1)
#define MEMHEAD_IS_MMAP(memhead) ((memhead)->len & (size_t) MEMHEAD_MMAP_FLAG)
#define MEMHEAD_IS_ALIGNED(memhead) ((memhead)->len & (size_t) MEMHEAD_ALIGN_FLAG)

/* Uncomment this to have proper peak counter. */
#define USE_ATOMIC_MAX

MEM_INLINE void update_maximum(size_t *maximum_value, size_t value)
{
#ifdef USE_ATOMIC_MAX
	size_t prev_value = *maximum_value;
	while (prev_value < value) {
		if (atomic_cas_z(maximum_value, prev_value, value) != prev_value) {
			break;
		}
	}
#else
	*maximum_value = value > *maximum_value ? value : *maximum_value;
#endif
}

#ifdef __GNUC__
__attribute__ ((format(printf, 1, 2)))
#endif
static void print_error(const char *str, ...)
{
	char buf[512];
	va_list ap;

	va_start(ap, str);
	vsnprintf(buf, sizeof(buf), str, ap);
	va_end(ap);
	buf[sizeof(buf) - 1] = '\0';

	if (error_callback) {
		error_callback(buf);
	}
}

#if defined(WIN32)
static void mem_lock_thread(void)
{
	if (thread_lock_callback)
		thread_lock_callback();
}

static void mem_unlock_thread(void)
{
	if (thread_unlock_callback)
		thread_unlock_callback();
}
#endif

size_t MEM_lockfree_allocN_len(const void *vmemh)
{
	if (vmemh) {
		return MEMHEAD_FROM_PTR(vmemh)->len & ~((size_t) (MEMHEAD_MMAP_FLAG | MEMHEAD_ALIGN_FLAG));
	}
	else {
		return 0;
	}
}

void MEM_lockfree_freeN(void *vmemh)
{
	MemHead *memh = MEMHEAD_FROM_PTR(vmemh);
	size_t len = MEM_lockfree_allocN_len(vmemh);

	if (vmemh == NULL) {
		print_error("Attempt to free NULL pointer\n");
#ifdef WITH_ASSERT_ABORT
		abort();
#endif
		return;
	}

	atomic_sub_and_fetch_u(&totblock, 1);
	atomic_sub_and_fetch_z(&mem_in_use, len);

	if (MEMHEAD_IS_MMAP(memh)) {
		atomic_sub_and_fetch_z(&mmap_in_use, len);
#if defined(WIN32)
		/* our windows mmap implementation is not thread safe */
		mem_lock_thread();
#endif
		if (munmap(memh, len + sizeof(MemHead)))
			printf("Couldn't unmap memory\n");
#if defined(WIN32)
		mem_unlock_thread();
#endif
	}
	else {
		if (UNLIKELY(malloc_debug_memset && len)) {
			memset(memh + 1, 255, len);
		}
		if (UNLIKELY(MEMHEAD_IS_ALIGNED(memh))) {
			MemHeadAligned *memh_aligned = MEMHEAD_ALIGNED_FROM_PTR(vmemh);
			aligned_free(MEMHEAD_REAL_PTR(memh_aligned));
		}
		else {
			free(memh);
		}
	}
}

void *MEM_lockfree_dupallocN(const void *vmemh)
{
	void *newp = NULL;
	if (vmemh) {
		MemHead *memh = MEMHEAD_FROM_PTR(vmemh);
		const size_t prev_size = MEM_allocN_len(vmemh);
		if (UNLIKELY(MEMHEAD_IS_MMAP(memh))) {
			newp = MEM_lockfree_mapallocN(prev_size, "dupli_mapalloc");
		}
		else if (UNLIKELY(MEMHEAD_IS_ALIGNED(memh))) {
			MemHeadAligned *memh_aligned = MEMHEAD_ALIGNED_FROM_PTR(vmemh);
			newp = MEM_lockfree_mallocN_aligned(
				prev_size,
				(size_t)memh_aligned->alignment,
				"dupli_malloc");
		}
		else {
			newp = MEM_lockfree_mallocN(prev_size, "dupli_malloc");
		}
		memcpy(newp, vmemh, prev_size);
	}
	return newp;
}

void *MEM_lockfree_reallocN_id(void *vmemh, size_t len, const char *str)
{
	void *newp = NULL;

	if (vmemh) {
		MemHead *memh = MEMHEAD_FROM_PTR(vmemh);
		size_t old_len = MEM_allocN_len(vmemh);

		if (LIKELY(!MEMHEAD_IS_ALIGNED(memh))) {
			newp = MEM_lockfree_mallocN(len, "realloc");
		}
		else {
			MemHeadAligned *memh_aligned = MEMHEAD_ALIGNED_FROM_PTR(vmemh);
			newp = MEM_lockfree_mallocN_aligned(
				old_len,
				(size_t)memh_aligned->alignment,
				"realloc");
		}

		if (newp) {
			if (len < old_len) {
				/* shrink */
				memcpy(newp, vmemh, len);
			}
			else {
				/* grow (or remain same size) */
				memcpy(newp, vmemh, old_len);
			}
		}

		MEM_lockfree_freeN(vmemh);
	}
	else {
		newp = MEM_lockfree_mallocN(len, str);
	}

	return newp;
}

void *MEM_lockfree_recallocN_id(void *vmemh, size_t len, const char *str)
{
	void *newp = NULL;

	if (vmemh) {
		MemHead *memh = MEMHEAD_FROM_PTR(vmemh);
		size_t old_len = MEM_allocN_len(vmemh);

		if (LIKELY(!MEMHEAD_IS_ALIGNED(memh))) {
			newp = MEM_lockfree_mallocN(len, "recalloc");
		}
		else {
			MemHeadAligned *memh_aligned = MEMHEAD_ALIGNED_FROM_PTR(vmemh);
			newp = MEM_lockfree_mallocN_aligned(old_len,
			                                    (size_t)memh_aligned->alignment,
			                                    "recalloc");
		}

		if (newp) {
			if (len < old_len) {
				/* shrink */
				memcpy(newp, vmemh, len);
			}
			else {
				memcpy(newp, vmemh, old_len);

				if (len > old_len) {
					/* grow */
					/* zero new bytes */
					memset(((char *)newp) + old_len, 0, len - old_len);
				}
			}
		}

		MEM_lockfree_freeN(vmemh);
	}
	else {
		newp = MEM_lockfree_callocN(len, str);
	}

	return newp;
}

void *MEM_lockfree_callocN(size_t len, const char *str)
{
	MemHead *memh;

	len = SIZET_ALIGN_4(len);

	memh = (MemHead *)calloc(1, len + sizeof(MemHead));

	if (LIKELY(memh)) {
		memh->len = len;
		atomic_add_and_fetch_u(&totblock, 1);
		atomic_add_and_fetch_z(&mem_in_use, len);
		update_maximum(&peak_mem, mem_in_use);

		return PTR_FROM_MEMHEAD(memh);
	}
	print_error("Calloc returns null: len=" SIZET_FORMAT " in %s, total %u\n",
	            SIZET_ARG(len), str, (unsigned int) mem_in_use);
	return NULL;
}

void *MEM_lockfree_mallocN(size_t len, const char *str)
{
	MemHead *memh;

	len = SIZET_ALIGN_4(len);

	memh = (MemHead *)malloc(len + sizeof(MemHead));

	if (LIKELY(memh)) {
		if (UNLIKELY(malloc_debug_memset && len)) {
			memset(memh + 1, 255, len);
		}

		memh->len = len;
		atomic_add_and_fetch_u(&totblock, 1);
		atomic_add_and_fetch_z(&mem_in_use, len);
		update_maximum(&peak_mem, mem_in_use);

		return PTR_FROM_MEMHEAD(memh);
	}
	print_error("Malloc returns null: len=" SIZET_FORMAT " in %s, total %u\n",
	            SIZET_ARG(len), str, (unsigned int) mem_in_use);
	return NULL;
}

void *MEM_lockfree_mallocN_aligned(size_t len, size_t alignment, const char *str)
{
	MemHeadAligned *memh;

	/* It's possible that MemHead's size is not properly aligned,
	 * do extra padding to deal with this.
	 *
	 * We only support small alignments which fits into short in
	 * order to save some bits in MemHead structure.
	 */
	size_t extra_padding = MEMHEAD_ALIGN_PADDING(alignment);

	/* Huge alignment values doesn't make sense and they
	 * wouldn't fit into 'short' used in the MemHead.
	 */
	assert(alignment < 1024);

	/* We only support alignment to a power of two. */
	assert(IS_POW2(alignment));

	len = SIZET_ALIGN_4(len);

	memh = (MemHeadAligned *)aligned_malloc(
		len + extra_padding + sizeof(MemHeadAligned), alignment);

	if (LIKELY(memh)) {
		/* We keep padding in the beginning of MemHead,
		 * this way it's always possible to get MemHead
		 * from the data pointer.
		 */
		memh = (MemHeadAligned *)((char *)memh + extra_padding);

		if (UNLIKELY(malloc_debug_memset && len)) {
			memset(memh + 1, 255, len);
		}

		memh->len = len | (size_t) MEMHEAD_ALIGN_FLAG;
		memh->alignment = (short) alignment;
		atomic_add_and_fetch_u(&totblock, 1);
		atomic_add_and_fetch_z(&mem_in_use, len);
		update_maximum(&peak_mem, mem_in_use);

		return PTR_FROM_MEMHEAD(memh);
	}
	print_error("Malloc returns null: len=" SIZET_FORMAT " in %s, total %u\n",
	            SIZET_ARG(len), str, (unsigned int) mem_in_use);
	return NULL;
}

void *MEM_lockfree_mapallocN(size_t len, const char *str)
{
	MemHead *memh;

	/* on 64 bit, simply use calloc instead, as mmap does not support
	 * allocating > 4 GB on Windows. the only reason mapalloc exists
	 * is to get around address space limitations in 32 bit OSes. */
	if (sizeof(void *) >= 8)
		return MEM_lockfree_callocN(len, str);

	len = SIZET_ALIGN_4(len);

#if defined(WIN32)
	/* our windows mmap implementation is not thread safe */
	mem_lock_thread();
#endif
	memh = mmap(NULL, len + sizeof(MemHead),
	            PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANON, -1, 0);
#if defined(WIN32)
	mem_unlock_thread();
#endif

	if (memh != (MemHead *)-1) {
		memh->len = len | (size_t) MEMHEAD_MMAP_FLAG;
		atomic_add_and_fetch_u(&totblock, 1);
		atomic_add_and_fetch_z(&mem_in_use, len);
		atomic_add_and_fetch_z(&mmap_in_use, len);

		update_maximum(&peak_mem, mem_in_use);
		update_maximum(&peak_mem, mmap_in_use);

		return PTR_FROM_MEMHEAD(memh);
	}
	print_error("Mapalloc returns null, fallback to regular malloc: "
	            "len=" SIZET_FORMAT " in %s, total %u\n",
	            SIZET_ARG(len), str, (unsigned int) mmap_in_use);
	return MEM_lockfree_callocN(len, str);
}

void MEM_lockfree_printmemlist_pydict(void)
{
}

void MEM_lockfree_printmemlist(void)
{
}

/* unused */
void MEM_lockfree_callbackmemlist(void (*func)(void *))
{
	(void) func;  /* Ignored. */
}

void MEM_lockfree_printmemlist_stats(void)
{
	printf("\ntotal memory len: %.3f MB\n",
	       (double)mem_in_use / (double)(1024 * 1024));
	printf("peak memory len: %.3f MB\n",
	       (double)peak_mem / (double)(1024 * 1024));
	printf("\nFor more detailed per-block statistics run Blender with memory debugging command line argument.\n");

#ifdef HAVE_MALLOC_STATS
	printf("System Statistics:\n");
	malloc_stats();
#endif
}

void MEM_lockfree_set_error_callback(void (*func)(const char *))
{
	error_callback = func;
}

bool MEM_lockfree_check_memory_integrity(void)
{
	return true;
}

void MEM_lockfree_set_lock_callback(void (*lock)(void), void (*unlock)(void))
{
	thread_lock_callback = lock;
	thread_unlock_callback = unlock;
}

void MEM_lockfree_set_memory_debug(void)
{
	malloc_debug_memset = true;
}

size_t MEM_lockfree_get_memory_in_use(void)
{
	return mem_in_use;
}

size_t MEM_lockfree_get_mapped_memory_in_use(void)
{
	return mmap_in_use;
}

unsigned int MEM_lockfree_get_memory_blocks_in_use(void)
{
	return totblock;
}

/* dummy */
void MEM_lockfree_reset_peak_memory(void)
{
	peak_mem = mem_in_use;
}

size_t MEM_lockfree_get_peak_memory(void)
{
	return peak_mem;
}

#ifndef NDEBUG
const char *MEM_lockfree_name_ptr(void *vmemh)
{
	if (vmemh) {
		return "unknown block name ptr";
	}
	else {
		return "MEM_lockfree_name_ptr(NULL)";
	}
}
#endif  /* NDEBUG */