1f0bf889imp/*-
24736ccfpfg * SPDX-License-Identifier: BSD-3-Clause
34736ccfpfg *
48fb65cergrimes * Copyright (c) 1987, 1993
57035f9frwatson *	The Regents of the University of California.
685f0248rwatson * Copyright (c) 2005, 2009 Robert N. M. Watson
77035f9frwatson * All rights reserved.
88fb65cergrimes *
98fb65cergrimes * Redistribution and use in source and binary forms, with or without
108fb65cergrimes * modification, are permitted provided that the following conditions
118fb65cergrimes * are met:
128fb65cergrimes * 1. Redistributions of source code must retain the above copyright
138fb65cergrimes *    notice, this list of conditions and the following disclaimer.
148fb65cergrimes * 2. Redistributions in binary form must reproduce the above copyright
158fb65cergrimes *    notice, this list of conditions and the following disclaimer in the
168fb65cergrimes *    documentation and/or other materials provided with the distribution.
177e6cabdimp * 3. Neither the name of the University nor the names of its contributors
188fb65cergrimes *    may be used to endorse or promote products derived from this software
198fb65cergrimes *    without specific prior written permission.
208fb65cergrimes *
218fb65cergrimes * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
228fb65cergrimes * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
238fb65cergrimes * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
248fb65cergrimes * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
258fb65cergrimes * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
268fb65cergrimes * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
278fb65cergrimes * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
288fb65cergrimes * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
298fb65cergrimes * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
308fb65cergrimes * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
318fb65cergrimes * SUCH DAMAGE.
328fb65cergrimes *
33a95231ahsu *	@(#)malloc.h	8.5 (Berkeley) 5/3/95
343b842d3peter * $FreeBSD$
358fb65cergrimes */
368fb65cergrimes
378fb65cergrimes#ifndef _SYS_MALLOC_H_
388fb65cergrimes#define	_SYS_MALLOC_H_
398fb65cergrimes
40e34fac8imp#ifndef _STANDALONE
4175c0ea0rwatson#include <sys/param.h>
42fe4195fmjg#ifdef _KERNEL
43fe4195fmjg#include <sys/systm.h>
44fe4195fmjg#endif
45486bc9dbde#include <sys/queue.h>
46486bc9dbde#include <sys/_lock.h>
47486bc9dbde#include <sys/_mutex.h>
482c9ae23cem#include <machine/_limits.h>
492923687jeff
5066a17c6bde#define	MINALLOCSIZE	UMA_SMALLEST_UNIT
512923687jeff
528fb65cergrimes/*
538222f5cjtl * Flags to memory allocation functions.
548fb65cergrimes */
55a229a63bde#define	M_NOWAIT	0x0001		/* do not block */
56923b177sam#define	M_WAITOK	0x0002		/* ok to block */
57b3deffbphk#define	M_ZERO		0x0100		/* bzero the allocation */
58b3deffbphk#define	M_NOVM		0x0200		/* don't ask VM for pages */
59b3deffbphk#define	M_USE_RESERVE	0x0400		/* can alloc out of reserve memory */
6084d4349kmacy#define	M_NODUMP	0x0800		/* don't dump pages in this allocation */
617d39a49markj#define	M_FIRSTFIT	0x1000		/* only for vmem, fast fit */
627d39a49markj#define	M_BESTFIT	0x2000		/* only for vmem, low fragmentation */
637d39a49markj#define	M_EXEC		0x4000		/* allocate executable space */
647d39a49markj#define	M_NEXTFIT	0x8000		/* only for vmem, follow cursor */
658fb65cergrimes
6640c3cb0bde#define	M_MAGIC		877983977	/* time when first defined :-) */
67349f4dfphk
687035f9frwatson/*
697035f9frwatson * Two malloc type structures are present: malloc_type, which is used by a
707035f9frwatson * type owner to declare the type, and malloc_type_internal, which holds
717035f9frwatson * malloc-owned statistics and other ABI-sensitive fields, such as the set of
727035f9frwatson * malloc statistics indexed by the compile-time MAXCPU constant.
737035f9frwatson * Applications should avoid introducing dependence on the allocator private
747035f9frwatson * data layout and size.
757035f9frwatson *
767035f9frwatson * The malloc_type ks_next field is protected by malloc_mtx.  Other fields in
777035f9frwatson * malloc_type are static after initialization so unsynchronized.
787035f9frwatson *
797035f9frwatson * Statistics in malloc_type_stats are written only when holding a critical
807035f9frwatson * section and running on the CPU associated with the index into the stat
817035f9frwatson * array, but read lock-free resulting in possible (minor) races, which the
827035f9frwatson * monitoring app should take into account.
837035f9frwatson */
847035f9frwatsonstruct malloc_type_stats {
857a35a61rwatson	uint64_t	mts_memalloced;	/* Bytes allocated on CPU. */
867a35a61rwatson	uint64_t	mts_memfreed;	/* Bytes freed on CPU. */
877a35a61rwatson	uint64_t	mts_numallocs;	/* Number of allocates on CPU. */
887a35a61rwatson	uint64_t	mts_numfrees;	/* number of frees on CPU. */
897a35a61rwatson	uint64_t	mts_size;	/* Bitmask of sizes allocated on CPU. */
907a35a61rwatson	uint64_t	_mts_reserved1;	/* Reserved field. */
917a35a61rwatson	uint64_t	_mts_reserved2;	/* Reserved field. */
927a35a61rwatson	uint64_t	_mts_reserved3;	/* Reserved field. */
937035f9frwatson};
947035f9frwatson
958c4eed9jb/*
968c4eed9jb * Index definitions for the mti_probes[] array.
978c4eed9jb */
988c4eed9jb#define DTMALLOC_PROBE_MALLOC		0
998c4eed9jb#define DTMALLOC_PROBE_FREE		1
1008c4eed9jb#define DTMALLOC_PROBE_MAX		2
1018c4eed9jb
1027035f9frwatsonstruct malloc_type_internal {
1038c4eed9jb	uint32_t	mti_probes[DTMALLOC_PROBE_MAX];
1048c4eed9jb					/* DTrace probe ID array. */
1056857471mdf	u_char		mti_zone;
106e3c2d3amjg	struct malloc_type_stats	*mti_stats;
1077035f9frwatson};
1087035f9frwatson
1097035f9frwatson/*
11085f0248rwatson * Public data structure describing a malloc type.  Private data is hung off
11185f0248rwatson * of ks_handle to avoid encoding internal malloc(9) data structures in
11285f0248rwatson * modules, which will statically allocate struct malloc_type.
1137035f9frwatson */
114c574a18phkstruct malloc_type {
1157035f9frwatson	struct malloc_type *ks_next;	/* Next in global chain. */
1167035f9frwatson	u_long		 ks_magic;	/* Detect programmer error. */
1177035f9frwatson	const char	*ks_shortdesc;	/* Printable type name. */
1187035f9frwatson	void		*ks_handle;	/* Priv. data, was lo_class. */
1198fb65cergrimes};
1208fb65cergrimes
1217a35a61rwatson/*
1227a35a61rwatson * Statistics structure headers for user space.  The kern.malloc sysctl
1237a35a61rwatson * exposes a structure stream consisting of a stream header, then a series of
1247a35a61rwatson * malloc type headers and statistics structures (quantity maxcpus).  For
1257a35a61rwatson * convenience, the kernel will provide the current value of maxcpus at the
1267a35a61rwatson * head of the stream.
1277a35a61rwatson */
1287a35a61rwatson#define	MALLOC_TYPE_STREAM_VERSION	0x00000001
1297a35a61rwatsonstruct malloc_type_stream_header {
1307a35a61rwatson	uint32_t	mtsh_version;	/* Stream format version. */
1317a35a61rwatson	uint32_t	mtsh_maxcpus;	/* Value of MAXCPU for stream. */
1327a35a61rwatson	uint32_t	mtsh_count;	/* Number of records. */
1337a35a61rwatson	uint32_t	_mtsh_pad;	/* Pad/reserved field. */
1347a35a61rwatson};
1357a35a61rwatson
1367a35a61rwatson#define	MALLOC_MAX_NAME	32
1377a35a61rwatsonstruct malloc_type_header {
1387a35a61rwatson	char				mth_name[MALLOC_MAX_NAME];
1397a35a61rwatson};
1407a35a61rwatson
14115b9bcbpeter#ifdef _KERNEL
1427035f9frwatson#define	MALLOC_DEFINE(type, shortdesc, longdesc)			\
1437035f9frwatson	struct malloc_type type[1] = {					\
14485f0248rwatson		{ NULL, M_MAGIC, shortdesc, NULL }			\
1457035f9frwatson	};								\
14635b126ehselasky	SYSINIT(type##_init, SI_SUB_KMEM, SI_ORDER_THIRD, malloc_init,	\
1477035f9frwatson	    type);							\
1487035f9frwatson	SYSUNINIT(type##_uninit, SI_SUB_KMEM, SI_ORDER_ANY,		\
149be7673cphk	    malloc_uninit, type)
150645e7b2phk
151645e7b2phk#define	MALLOC_DECLARE(type) \
1520f95240peter	extern struct malloc_type type[1]
1537c874afphk
154ec1ed33bdeMALLOC_DECLARE(M_CACHE);
155ec1ed33bdeMALLOC_DECLARE(M_DEVBUF);
156ec1ed33bdeMALLOC_DECLARE(M_TEMP);
1577efc91cshin
1588fb65cergrimes/*
1598ee98babde * XXX this should be declared in <sys/uio.h>, but that tends to fail
1608ee98babde * because <sys/uio.h> is included in a header before the source file
1618ee98babde * has a chance to include <sys/malloc.h> to get MALLOC_DECLARE() defined.
1628ee98babde */
1638ee98babdeMALLOC_DECLARE(M_IOV);
1648ee98babde
165f931b75markjstruct domainset;
16666a17c6bdeextern struct mtx malloc_mtx;
16766a17c6bde
1688c4eed9jb/*
1698c4eed9jb * Function type used when iterating over the list of malloc types.
1708c4eed9jb */
1718c4eed9jbtypedef void malloc_type_list_func_t(struct malloc_type *, void *);
1728c4eed9jb
173d27d5e3bdevoid	contigfree(void *addr, unsigned long size, struct malloc_type *type);
174d27d5e3bdevoid	*contigmalloc(unsigned long size, struct malloc_type *type, int flags,
175783ae53jake	    vm_paddr_t low, vm_paddr_t high, unsigned long alignment,
176ae235f9pfg	    vm_paddr_t boundary) __malloc_like __result_use_check
177db5663cpfg	    __alloc_size(1) __alloc_align(6);
178f931b75markjvoid	*contigmalloc_domainset(unsigned long size, struct malloc_type *type,
179f931b75markj	    struct domainset *ds, int flags, vm_paddr_t low, vm_paddr_t high,
180f375b4djeff	    unsigned long alignment, vm_paddr_t boundary)
18181515d0andrew	    __malloc_like __result_use_check __alloc_size(1) __alloc_align(7);
1823b2d03balfredvoid	free(void *addr, struct malloc_type *type);
1837bee496mmacyvoid	zfree(void *addr, struct malloc_type *type);
1842b1bc67cemvoid	*malloc(size_t size, struct malloc_type *type, int flags) __malloc_like
1852b1bc67cem	    __result_use_check __alloc_size(1);
1862defad5mjg/*
1872defad5mjg * Try to optimize malloc(..., ..., M_ZERO) allocations by doing zeroing in
1882defad5mjg * place if the size is known at compilation time.
1892defad5mjg *
1902defad5mjg * Passing the flag down requires malloc to blindly zero the entire object.
1912defad5mjg * In practice a lot of the zeroing can be avoided if most of the object
1922defad5mjg * gets explicitly initialized after the allocation. Letting the compiler
1932defad5mjg * zero in place gives it the opportunity to take advantage of this state.
1942defad5mjg *
1952defad5mjg * Note that the operation is only applicable if both flags and size are
1962defad5mjg * known at compilation time. If M_ZERO is passed but M_WAITOK is not, the
1972defad5mjg * allocation can fail and a NULL check is needed. However, if M_WAITOK is
1982defad5mjg * passed we know the allocation must succeed and the check can be elided.
1992defad5mjg *
2002defad5mjg *	_malloc_item = malloc(_size, type, (flags) &~ M_ZERO);
2012defad5mjg *	if (((flags) & M_WAITOK) != 0 || _malloc_item != NULL)
2022defad5mjg *		bzero(_malloc_item, _size);
2032defad5mjg *
2042defad5mjg * If the flag is set, the compiler knows the left side is always true,
2052defad5mjg * therefore the entire statement is true and the callsite is:
2062defad5mjg *
2072defad5mjg *	_malloc_item = malloc(_size, type, (flags) &~ M_ZERO);
2082defad5mjg *	bzero(_malloc_item, _size);
2092defad5mjg *
2102defad5mjg * If the flag is not set, the compiler knows the left size is always false
2112defad5mjg * and the NULL check is needed, therefore the callsite is:
2122defad5mjg *
2132defad5mjg * 	_malloc_item = malloc(_size, type, (flags) &~ M_ZERO);
2142defad5mjg *	if (_malloc_item != NULL)
2152defad5mjg *		bzero(_malloc_item, _size);
2162defad5mjg *
2172defad5mjg * The implementation is a macro because of what appears to be a clang 6 bug:
2182defad5mjg * an inline function variant ended up being compiled to a mere malloc call
2192defad5mjg * regardless of argument. gcc generates expected code (like the above).
2202defad5mjg */
221fe4195fmjg#define	malloc(size, type, flags) ({					\
222fe4195fmjg	void *_malloc_item;						\
223fe4195fmjg	size_t _size = (size);						\
224fe4195fmjg	if (__builtin_constant_p(size) && __builtin_constant_p(flags) &&\
225515692dvangyzen	    ((flags) & M_ZERO) != 0) {					\
226fe4195fmjg		_malloc_item = malloc(_size, type, (flags) &~ M_ZERO);	\
2272defad5mjg		if (((flags) & M_WAITOK) != 0 ||			\
2282defad5mjg		    __predict_true(_malloc_item != NULL))		\
229fe4195fmjg			bzero(_malloc_item, _size);			\
230fe4195fmjg	} else {							\
231fe4195fmjg		_malloc_item = malloc(_size, type, flags);		\
232fe4195fmjg	}								\
233fe4195fmjg	_malloc_item;							\
234fe4195fmjg})
235fe4195fmjg
236f931b75markjvoid	*malloc_domainset(size_t size, struct malloc_type *type,
237f931b75markj	    struct domainset *ds, int flags) __malloc_like __result_use_check
238f931b75markj	    __alloc_size(1);
2396929182kpvoid	*mallocarray(size_t nmemb, size_t size, struct malloc_type *type,
2406929182kp	    int flags) __malloc_like __result_use_check
24135335c1pfg	    __alloc_size2(1, 2);
2423b2d03balfredvoid	malloc_init(void *);
24327173bdphkint	malloc_last_fail(void);
244c4b4a8fgreenvoid	malloc_type_allocated(struct malloc_type *type, unsigned long size);
245c4b4a8fgreenvoid	malloc_type_freed(struct malloc_type *type, unsigned long size);
2468c4eed9jbvoid	malloc_type_list(malloc_type_list_func_t *, void *);
2473b2d03balfredvoid	malloc_uninit(void *);
2481ba6953wulfsize_t	malloc_usable_size(const void *);
2492b1bc67cemvoid	*realloc(void *addr, size_t size, struct malloc_type *type, int flags)
2502b1bc67cem	    __result_use_check __alloc_size(2);
2512b1bc67cemvoid	*reallocf(void *addr, size_t size, struct malloc_type *type, int flags)
2522b1bc67cem	    __result_use_check __alloc_size(2);
2533cc29e6pjd
2543cc29e6pjdstruct malloc_type *malloc_desc2type(const char *desc);
2552c9ae23cem
2562c9ae23cem/*
2572c9ae23cem * This is sqrt(SIZE_MAX+1), as s1*s2 <= SIZE_MAX
2582c9ae23cem * if both s1 < MUL_NO_OVERFLOW and s2 < MUL_NO_OVERFLOW
2592c9ae23cem */
2602c9ae23cem#define MUL_NO_OVERFLOW		(1UL << (sizeof(size_t) * 8 / 2))
2612c9ae23cemstatic inline bool
2622c9ae23cemWOULD_OVERFLOW(size_t nmemb, size_t size)
2632c9ae23cem{
2642c9ae23cem
2652c9ae23cem	return ((nmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) &&
2662c9ae23cem	    nmemb > 0 && __SIZE_T_MAX / nmemb < size);
2672c9ae23cem}
2682c9ae23cem#undef MUL_NO_OVERFLOW
26915b9bcbpeter#endif /* _KERNEL */
2700f99c67bde
271e34fac8imp#else
272e34fac8imp/*
273e34fac8imp * The native stand malloc / free interface we're mapping to
274e34fac8imp */
275e34fac8impextern void Free(void *p, const char *file, int line);
276e34fac8impextern void *Malloc(size_t bytes, const char *file, int line);
277e34fac8imp
278e34fac8imp/*
279e34fac8imp * Minimal standalone malloc implementation / environment. None of the
280e34fac8imp * flags mean anything and there's no need declare malloc types.
281e34fac8imp * Define the simple alloc / free routines in terms of Malloc and
282e34fac8imp * Free. None of the kernel features that this stuff disables are needed.
283e34fac8imp *
284e34fac8imp * XXX we are setting ourselves up for a potential crash if we can't allocate
285e34fac8imp * memory for a M_WAITOK call.
286e34fac8imp */
287e34fac8imp#define M_WAITOK 0
288e34fac8imp#define M_ZERO 0
289e34fac8imp#define M_NOWAIT 0
290e34fac8imp#define MALLOC_DECLARE(x)
291e34fac8imp
292e34fac8imp#define kmem_zalloc(size, flags) Malloc((size), __FILE__, __LINE__)
293e34fac8imp#define kmem_free(p, size) Free(p, __FILE__, __LINE__)
294e34fac8imp
295e34fac8imp/*
296e34fac8imp * ZFS mem.h define that's the OpenZFS porting layer way of saying
297e34fac8imp * M_WAITOK. Given the above, it will also be a nop.
298e34fac8imp */
299e34fac8imp#define KM_SLEEP M_WAITOK
300e34fac8imp#endif /* _STANDALONE */
3018fb65cergrimes#endif /* !_SYS_MALLOC_H_ */
302