Debian Codegraph @

storage/innobase/include/mem0mem.h

raw
1 /*****************************************************************************
2
3 Copyright (c) 1994, 2026, Oracle and/or its affiliates.
4
5 This program is free software; you can redistribute it and/or modify it under
6 the terms of the GNU General Public License, version 2.0, as published by the
7 Free Software Foundation.
8
9 This program is designed to work with certain software (including
10 but not limited to OpenSSL) that is licensed under separate terms,
11 as designated in a particular file or component or in included license
12 documentation. The authors of MySQL hereby grant you an additional
13 permission to link the program and your derivative works with the
14 separately licensed software that they have either included with
15 the program or referenced in the documentation.
16
17 This program is distributed in the hope that it will be useful, but WITHOUT
18 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
19 FOR A PARTICULAR PURPOSE. See the GNU General Public License, version 2.0,
20 for more details.
21
22 You should have received a copy of the GNU General Public License along with
23 this program; if not, write to the Free Software Foundation, Inc.,
24 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
25
26 *****************************************************************************/
27
28 /** @file include/mem0mem.h
29 The memory management
30
31 Created 6/9/1994 Heikki Tuuri
32 *******************************************************/
33
34 #ifndef mem0mem_h
35 #define mem0mem_h
36
37 #include "mach0data.h"
38 #include "ut0byte.h"
39 #include "ut0mem.h"
40 #include "ut0rnd.h"
41
42 #include <limits.h>
43
44 #include <functional>
45 #include <memory>
46 #include <type_traits>
47
48 /* -------------------- MEMORY HEAPS ----------------------------- */
49
50 /** A block of a memory heap consists of the info structure
51 followed by an area of memory */
52 typedef struct mem_block_info_t mem_block_t;
53
54 /** A memory heap is a nonempty linear list of memory blocks */
55 typedef mem_block_t mem_heap_t;
56
57 /** Types of allocation for memory heaps: DYNAMIC means allocation from the
58 dynamic memory pool of the C compiler, BUFFER means allocation from the
59 buffer pool; the latter method is used for very big heaps */
60
61 /** the most common type */
62 constexpr uint32_t MEM_HEAP_DYNAMIC = 0;
63 constexpr uint32_t MEM_HEAP_BUFFER = 1;
64 /** this flag can optionally be ORed to MEM_HEAP_BUFFER, in which case
65 heap->free_block is used in some cases for memory allocations, and if it's
66 NULL, the memory allocation functions can return NULL. */
67 constexpr uint32_t MEM_HEAP_BTR_SEARCH = 2;
68
69 /** Different type of heaps in terms of which data structure is using them */
70 constexpr uint32_t MEM_HEAP_FOR_BTR_SEARCH =
71 MEM_HEAP_BTR_SEARCH | MEM_HEAP_BUFFER;
72 constexpr uint32_t MEM_HEAP_FOR_PAGE_HASH = MEM_HEAP_DYNAMIC;
73 constexpr uint32_t MEM_HEAP_FOR_RECV_SYS = MEM_HEAP_BUFFER;
74 constexpr uint32_t MEM_HEAP_FOR_LOCK_HEAP = MEM_HEAP_BUFFER;
75
76 /** The following start size is used for the first block in the memory heap if
77 the size is not specified, i.e., 0 is given as the parameter in the call of
78 create. The standard size is the maximum (payload) size of the blocks used for
79 allocations of small buffers. */
80 constexpr uint32_t MEM_BLOCK_START_SIZE = 64;
81
82 #define MEM_BLOCK_STANDARD_SIZE \
83 (UNIV_PAGE_SIZE >= 16384 ? 8000 : MEM_MAX_ALLOC_IN_BUF)
84
85 /** If a memory heap is allowed to grow into the buffer pool, the following
86 is the maximum size for a single allocated buffer
87 (from UNIV_PAGE_SIZE we subtract MEM_BLOCK_HEADER_SIZE and 2*MEM_NO_MANS_LAND
88 since it's something we always need to put. Since in MEM_SPACE_NEEDED we round
89 n to the next multiple of UNIV_MEM_ALINGMENT, we need to cut from the rest the
90 part that cannot be divided by UNIV_MEM_ALINGMENT): */
91 #define MEM_MAX_ALLOC_IN_BUF \
92 ((UNIV_PAGE_SIZE - MEM_BLOCK_HEADER_SIZE - 2 * MEM_NO_MANS_LAND) & \
93 ~(UNIV_MEM_ALIGNMENT - 1))
94
95 /* Before and after any allocated object we will put MEM_NO_MANS_LAND bytes of
96 some data (different before and after) which is supposed not to be modified by
97 anyone. This way it would be much easier to determine whether anyone was
98 writing on not his memory, especially that Valgrind can assure there was no
99 reads or writes to this memory. */
100 #ifdef UNIV_DEBUG
101 constexpr int MEM_NO_MANS_LAND = 16;
102 #else
103 constexpr int MEM_NO_MANS_LAND = 0;
104 #endif
105
106 /* Byte that we would put before allocated object MEM_NO_MANS_LAND times.*/
107 const byte MEM_NO_MANS_LAND_BEFORE_BYTE = 0xCE;
108 /* Byte that we would put after allocated object MEM_NO_MANS_LAND times.*/
109 const byte MEM_NO_MANS_LAND_AFTER_BYTE = 0xDF;
110
111 /** Space needed when allocating for a user a field of length N.
112 The space is allocated only in multiples of UNIV_MEM_ALIGNMENT. In debug mode
113 contains two areas of no mans lands before and after the buffer requested. */
114 static inline uint64_t MEM_SPACE_NEEDED(uint64_t N) {
115 return ut_calc_align(N + 2 * MEM_NO_MANS_LAND, UNIV_MEM_ALIGNMENT);
116 }
117
118 /** Creates a memory heap.
119 A single user buffer of 'size' will fit in the block.
120 0 creates a default size block.
121 @param[in] size Desired start block size.
122 @param[in] loc Location where created
123 @param[in] type Heap type
124 @return own: memory heap, NULL if did not succeed (only possible for
125 MEM_HEAP_BTR_SEARCH type heaps) */
126 static inline mem_heap_t *mem_heap_create(ulint size, ut::Location loc,
127 ulint type = MEM_HEAP_DYNAMIC);
128
129 /** Frees the space occupied by a memory heap.
130 @param[in] heap Heap to be freed */
131 static inline void mem_heap_free(mem_heap_t *heap);
132
133 /** Allocates and zero-fills n bytes of memory from a memory heap.
134 @param[in] heap memory heap
135 @param[in] n number of bytes; if the heap is allowed to grow into
136 the buffer pool, this must be <= MEM_MAX_ALLOC_IN_BUF
137 @return allocated, zero-filled storage */
138 static inline void *mem_heap_zalloc(mem_heap_t *heap, ulint n);
139
140 /** Allocates n bytes of memory from a memory heap.
141 @param[in] heap memory heap
142 @param[in] n number of bytes; if the heap is allowed to grow into
143 the buffer pool, this must be <= MEM_MAX_ALLOC_IN_BUF
144 @return allocated storage, NULL if did not succeed (only possible for
145 MEM_HEAP_BTR_SEARCH type heaps) */
146 static inline void *mem_heap_alloc(mem_heap_t *heap, ulint n);
147
148 /** Returns a pointer to the heap top.
149 @param[in] heap memory heap
150 @return pointer to the heap top */
151 static inline byte *mem_heap_get_heap_top(mem_heap_t *heap);
152
153 /** Frees the space in a memory heap exceeding the pointer given.
154 The pointer must have been acquired from mem_heap_get_heap_top.
155 The first memory block of the heap is not freed.
156 @param[in] heap heap from which to free
157 @param[in] old_top pointer to old top of heap */
158 static inline void mem_heap_free_heap_top(mem_heap_t *heap, byte *old_top);
159
160 /** Empties a memory heap.
161 The first memory block of the heap is not freed.
162 @param[in] heap heap to empty */
163 static inline void mem_heap_empty(mem_heap_t *heap);
164
165 /** Returns a pointer to the topmost element in a memory heap.
166 The size of the element must be given.
167 @param[in] heap memory heap
168 @param[in] n size of the topmost element
169 @return pointer to the topmost element */
170 static inline void *mem_heap_get_top(mem_heap_t *heap, ulint n);
171
172 /** Checks if a given chunk of memory is the topmost element stored in the
173 heap. If this is the case, then calling mem_heap_free_top() would free
174 that element from the heap.
175 @param[in] heap memory heap
176 @param[in] buf presumed topmost element
177 @param[in] buf_sz size of buf in bytes
178 @return true if topmost */
179 [[nodiscard]] static inline bool mem_heap_is_top(mem_heap_t *heap,
180 const void *buf, ulint buf_sz);
181
182 /** Allocate a new chunk of memory from a memory heap, possibly discarding the
183 topmost element. If the memory chunk specified with (top, top_sz) is the
184 topmost element, then it will be discarded, otherwise it will be left untouched
185 and this function will be equivallent to mem_heap_alloc().
186 @param[in,out] heap memory heap
187 @param[in] top chunk to discard if possible
188 @param[in] top_sz size of top in bytes
189 @param[in] new_sz desired size of the new chunk
190 @return allocated storage, NULL if did not succeed (only possible for
191 MEM_HEAP_BTR_SEARCH type heaps) */
192 static inline void *mem_heap_replace(mem_heap_t *heap, const void *top,
193 ulint top_sz, ulint new_sz);
194
195 /** Allocate a new chunk of memory from a memory heap, possibly discarding the
196 topmost element and then copy the specified data to it. If the memory chunk
197 specified with (top, top_sz) is the topmost element, then it will be discarded,
198 otherwise it will be left untouched and this function will be equivalent to
199 mem_heap_dup().
200 @param[in,out] heap memory heap
201 @param[in] top chunk to discard if possible
202 @param[in] top_sz size of top in bytes
203 @param[in] data new data to duplicate
204 @param[in] data_sz size of data in bytes
205 @return allocated storage, NULL if did not succeed (only possible for
206 MEM_HEAP_BTR_SEARCH type heaps) */
207 static inline void *mem_heap_dup_replace(mem_heap_t *heap, const void *top,
208 ulint top_sz, const void *data,
209 ulint data_sz);
210
211 /** Allocate a new chunk of memory from a memory heap, possibly discarding the
212 topmost element and then copy the specified string to it. If the memory chunk
213 specified with (top, top_sz) is the topmost element, then it will be discarded,
214 otherwise it will be left untouched and this function will be equivalent to
215 mem_heap_strdup().
216 @param[in,out] heap memory heap
217 @param[in] top chunk to discard if possible
218 @param[in] top_sz size of top in bytes
219 @param[in] str new data to duplicate
220 @return allocated string, NULL if did not succeed (only possible for
221 MEM_HEAP_BTR_SEARCH type heaps) */
222 static inline char *mem_heap_strdup_replace(mem_heap_t *heap, const void *top,
223 ulint top_sz, const char *str);
224
225 /** Frees the topmost element in a memory heap.
226 @param[in] heap memory heap
227 @param[in] n size of the topmost element
228 The size of the element must be given. */
229 static inline void mem_heap_free_top(mem_heap_t *heap, ulint n);
230
231 /** Returns the space in bytes occupied by a memory heap. */
232 static inline size_t mem_heap_get_size(mem_heap_t *heap); /*!< in: heap */
233
234 /** Duplicates a NUL-terminated string.
235 @param[in] str string to be copied
236 @return own: a copy of the string, must be deallocated with ut_free */
237 static inline char *mem_strdup(const char *str);
238
239 /** Makes a NUL-terminated copy of a nonterminated string.
240 @param[in] str string to be copied
241 @param[in] len length of str, in bytes
242 @return own: a copy of the string, must be deallocated with ut_free */
243 static inline char *mem_strdupl(const char *str, ulint len);
244
245 /** Duplicates a NUL-terminated string, allocated from a memory heap.
246 @param[in] heap memory heap where string is allocated
247 @param[in] str string to be copied
248 @return own: a copy of the string */
249 char *mem_heap_strdup(mem_heap_t *heap, const char *str);
250
251 /** Makes a NUL-terminated copy of a nonterminated string, allocated from a
252 memory heap.
253 @param[in] heap memory heap where string is allocated
254 @param[in] str string to be copied
255 @param[in] len length of str, in bytes
256 @return own: a copy of the string */
257 static inline char *mem_heap_strdupl(mem_heap_t *heap, const char *str,
258 ulint len);
259
260 /** Concatenate two strings and return the result, using a memory heap.
261 @return own: the result */
262 char *mem_heap_strcat(
263 mem_heap_t *heap, /*!< in: memory heap where string is allocated */
264 const char *s1, /*!< in: string 1 */
265 const char *s2); /*!< in: string 2 */
266
267 /** Duplicate a block of data, allocated from a memory heap.
268 @return own: a copy of the data */
269 void *mem_heap_dup(
270 mem_heap_t *heap, /*!< in: memory heap where copy is allocated */
271 const void *data, /*!< in: data to be copied */
272 ulint len); /*!< in: length of data, in bytes */
273
274 /** A simple sprintf replacement that dynamically allocates the space for the
275 formatted string from the given heap. This supports a very limited set of
276 the printf syntax: types 's' and 'u' and length modifier 'l' (which is
277 required for the 'u' type).
278 @return heap-allocated formatted string */
279 char *mem_heap_printf(mem_heap_t *heap, /*!< in: memory heap */
280 const char *format, /*!< in: format string */
281 ...) MY_ATTRIBUTE((format(printf, 2, 3)));
282
283 /** Checks that an object is a memory heap (or a block of it)
284 @param[in] heap Memory heap to check */
285 static inline void mem_block_validate(const mem_heap_t *heap);
286
287 #ifdef UNIV_DEBUG
288
289 /** Validates the contents of a memory heap.
290 Checks a memory heap for consistency, prints the contents if any error
291 is detected. A fatal error is logged if an error is detected.
292 @param[in] heap Memory heap to validate. */
293 void mem_heap_validate(const mem_heap_t *heap);
294
295 #endif /* UNIV_DEBUG */
296
297 /*#######################################################################*/
298
299 struct buf_block_t;
300
301 /** The info structure stored at the beginning of a heap block */
302 struct mem_block_info_t {
303 /** Magic number for debugging. */
304 uint64_t magic_n;
305 #ifdef UNIV_DEBUG
306 /** File name where the mem heap was created. */
307 char file_name[16];
308 /** Line number where the mem heap was created. */
309 ulint line;
310 #endif /* UNIV_DEBUG */
311 /** This contains pointers to next and prev in the list. The first block
312 allocated to the heap is also the first block in this list,
313 though it also contains the base node of the list. */
314 UT_LIST_NODE_T(mem_block_t) list;
315 /** In the first block of the list this is the base node of the list of
316 blocks; in subsequent blocks this is undefined. */
317 UT_LIST_BASE_NODE_T_EXTERN(mem_block_t, list) base;
318 /** Physical length of this block in bytes. */
319 ulint len;
320 /** Physical length in bytes of all blocks in the heap. This is defined only
321 in the base node and is set to ULINT_UNDEFINED in others. */
322 ulint total_size;
323 /** Type of heap: MEM_HEAP_DYNAMIC, or MEM_HEAP_BUF possibly ORed to
324 MEM_HEAP_BTR_SEARCH. */
325 ulint type;
326 /** Offset in bytes of the first free position for user data in the block. */
327 ulint free;
328 /** The value of the struct field 'free' at the creation of the block. */
329 ulint start;
330 /* This is not null iff the MEM_HEAP_BTR_SEARCH bit is set in type, and this
331 is the heap root. This leads to a atomic pointer that can contain an allocated
332 buffer frame, which can be appended as a free block to the heap, if we need
333 more space. */
334 std::atomic<buf_block_t *> *free_block_ptr;
335
336 /* if this block has been allocated from the buffer pool, this contains the
337 buf_block_t handle; otherwise, this is NULL */
338 buf_block_t *buf_block;
339 };
340 /* We use the UT_LIST_BASE_NODE_T_EXTERN instead of simpler UT_LIST_BASE_NODE_T
341 because DevStudio12.6 initializes the pointer-to-member offset to 0 otherwise.*/
342 UT_LIST_NODE_GETTER_DEFINITION(mem_block_t, list)
343
344 constexpr uint64_t MEM_BLOCK_MAGIC_N = 0x445566778899AABB;
345 constexpr uint64_t MEM_FREED_BLOCK_MAGIC_N = 0xBBAA998877665544;
346
347 /* Header size for a memory heap block */
348 #define MEM_BLOCK_HEADER_SIZE \
349 ut_calc_align(sizeof(mem_block_info_t), UNIV_MEM_ALIGNMENT)
350
351 #include "mem0mem.ic"
352
353 /** A C++ wrapper class to the mem_heap_t routines, so that it can be used
354 as an STL allocator */
355 template <typename T>
356 class mem_heap_allocator {
357 public:
358 typedef T value_type;
359 typedef size_t size_type;
360 typedef ptrdiff_t difference_type;
361 typedef T *pointer;
362 typedef const T *const_pointer;
363 typedef T &reference;
364 typedef const T &const_reference;
365
366 mem_heap_allocator(mem_heap_t *heap) : m_heap(heap) {}
367
368 mem_heap_allocator(const mem_heap_allocator &other) : m_heap(other.m_heap) {
369 // Do nothing
370 }
371
372 template <typename U>
373 mem_heap_allocator(const mem_heap_allocator<U> &other)
374 : m_heap(other.m_heap) {
375 // Do nothing
376 }
377
378 ~mem_heap_allocator() { m_heap = nullptr; }
379
380 size_type max_size() const { return (ULONG_MAX / sizeof(T)); }
381
382 /** This function returns a pointer to the first element of a newly
383 allocated array large enough to contain n objects of type T; only the
384 memory is allocated, and the objects are not constructed. Moreover,
385 an optional pointer argument (that points to an object already
386 allocated by mem_heap_allocator) can be used as a hint to the
387 implementation about where the new memory should be allocated in
388 order to improve locality. */
389 pointer allocate(size_type n, const_pointer hint [[maybe_unused]] = nullptr) {
390 return (reinterpret_cast<pointer>(mem_heap_alloc(m_heap, n * sizeof(T))));
391 }
392
393 void deallocate(pointer, size_type) {}
394
395 pointer address(reference r) const { return (&r); }
396
397 const_pointer address(const_reference r) const { return (&r); }
398
399 void construct(pointer p, const_reference t) {
400 new (reinterpret_cast<void *>(p)) T(t);
401 }
402
403 void destroy(pointer p) { (reinterpret_cast<T *>(p))->~T(); }
404
405 /** Allocators are required to supply the below template class member
406 which enables the possibility of obtaining a related allocator,
407 parametrized in terms of a different type. For example, given an
408 allocator type IntAllocator for objects of type int, a related
409 allocator type for objects of type long could be obtained using
410 IntAllocator::rebind<long>::other */
411 template <typename U>
412 struct rebind {
413 typedef mem_heap_allocator<U> other;
414 };
415
416 /** Get the underlying memory heap object.
417 @return the underlying memory heap object. */
418 mem_heap_t *get_mem_heap() const { return (m_heap); }
419
420 private:
421 mem_heap_t *m_heap;
422 template <typename U>
423 friend class mem_heap_allocator;
424 };
425
426 template <class T>
427 bool operator==(const mem_heap_allocator<T> &left,
428 const mem_heap_allocator<T> &right) {
429 return (left.get_mem_heap() == right.get_mem_heap());
430 }
431
432 template <class T>
433 bool operator!=(const mem_heap_allocator<T> &left,
434 const mem_heap_allocator<T> &right) {
435 return (left.get_mem_heap() != right.get_mem_heap());
436 }
437
438 /** Heap wrapper that destroys the heap instance when it goes out of scope. */
439 struct Scoped_heap {
440 using Type = mem_heap_t;
441
442 /** Default constructor. */
443 Scoped_heap() : m_ptr(nullptr) {}
444
445 /** Constructs heap with a free space of specified size.
446 @param[in] n Initial size of the heap to allocate.
447 @param[in] location Location from where called. */
448 Scoped_heap(size_t n, ut::Location location) noexcept
449 : m_ptr(mem_heap_create(n, location, MEM_HEAP_DYNAMIC)) {}
450
451 /** Destructor. */
452 ~Scoped_heap() = default;
453
454 /** Create the heap, it must not already be created.
455 @param[in] n Initial size of the heap to allocate.
456 @param[in] location Location from where called. */
457 void create(size_t n, ut::Location location) noexcept {
458 ut_a(get() == nullptr);
459 auto ptr = mem_heap_create(n, location, MEM_HEAP_DYNAMIC);
460 reset(ptr);
461 }
462
463 /** @return the heap pointer. */
464 Type *get() noexcept { return m_ptr.get(); }
465
466 /** Set the pointer to p.
467 @param[in] p New pointer value. */
468 void reset(Type *p) {
469 if (get() != p) {
470 m_ptr.reset(p);
471 }
472 }
473
474 /** Empty the heap. */
475 void clear() noexcept {
476 if (get() != nullptr) {
477 mem_heap_empty(get());
478 }
479 }
480
481 /** Allocate memory in the heap.
482 @param[in] n_bytes Number of bytes to allocate.
483 @return pointer to allocated memory. */
484 void *alloc(size_t n_bytes) noexcept {
485 ut_ad(n_bytes > 0);
486 return mem_heap_alloc(get(), n_bytes);
487 }
488
489 private:
490 /** A functor with no state to be used for mem_heap destruction. */
491 struct mem_heap_free_functor {
492 void operator()(mem_heap_t *heap) { mem_heap_free(heap); }
493 };
494
495 using Ptr = std::unique_ptr<Type, mem_heap_free_functor>;
496
497 /** Heap to use. */
498 Ptr m_ptr{};
499
500 Scoped_heap(Scoped_heap &&) = delete;
501 Scoped_heap(const Scoped_heap &) = delete;
502 Scoped_heap &operator=(Scoped_heap &&) = delete;
503 Scoped_heap &operator=(const Scoped_heap &) = delete;
504 };
505
506 #endif