Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Merge branch 'master' of https://framagit.org/simgrid/simgrid
[simgrid.git] / src / xbt / mallocator.c
1 /* mallocator - recycle objects to avoid malloc() / free()                  */
2
3 /* Copyright (c) 2006-2021. The SimGrid Team. All rights reserved.          */
4
5 /* This program is free software; you can redistribute it and/or modify it
6  * under the terms of the license (GNU LGPL) which comes with this package. */
7
8 #include "xbt/mallocator.h"
9 #include "mallocator_private.h"
10 #include "simgrid/modelchecker.h" /* kill mallocators when model-checking is enabled */
11 #include "src/internal_config.h"
12 #include "xbt/asserts.h"
13 #include "xbt/sysdep.h"
14
15 #ifndef MIN
16 #define MIN(a, b) ((a) < (b) ? (a) : (b))
17 #endif
18 #ifndef MAX
19 #define MAX(a, b) ((a) > (b) ? (a) : (b))
20 #endif
21
22 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(xbt_mallocator, xbt, "Mallocators");
23
24 /** Implementation note on the mallocators:
25  *
26  * Mallocators and memory mess introduced by model-checking do not mix well  together: the mallocator will give
27  * standard memory when we are using raw memory (so these blocks are killed on restore) and the contrary (so these
28  * blocks will leak across restores).
29  *
30  * In addition, model-checking is activated when the command-line arguments are parsed, at the beginning of main, while
31  * most of the mallocators are created during the constructor functions launched from xbt_preinit, before the beginning
32  * of the main function.
33  *
34  * We want the code as fast as possible when they are active while we can deal with a little slow-down when they are
35  * inactive. So we start the mallocators as inactive. When they are so, they check at each use whether they should
36  * switch to the fast active mode or should stay in inactive mode. Finally, we give external elements a way to switch
37  * them  all to the active mode (through xbt_mallocator_initialization_is_done).
38  *
39  * This design avoids to store all mallocators somewhere for later conversion, which would be hard to achieve provided
40  * that all our data structures use some mallocators internally...
41  */
42
43 /* Value != 0 when the framework configuration is done.  Value > 1 if the
44  * mallocators should be protected from concurrent accesses.  */
45 static int initialization_done = 0;
46
47 static inline void lock_reset(xbt_mallocator_t m)
48 {
49   atomic_flag_clear(&m->lock);
50 }
51
52 static inline void lock_acquire(xbt_mallocator_t m)
53 {
54   if (initialization_done > 1) {
55     while (atomic_flag_test_and_set(&m->lock))
56       /* nop */;
57   }
58 }
59
60 static inline void lock_release(xbt_mallocator_t m)
61 {
62   if (initialization_done > 1)
63     atomic_flag_clear(&m->lock);
64 }
65
66 /**
67  * This function must be called once the framework configuration is done. If not, mallocators will never get used.
68  * Check the implementation notes in src/xbt/mallocator.c for the justification of this.
69  *
70  * For example, surf_config uses this function to tell to the mallocators that the simgrid configuration is now
71  * finished and that it can create them if not done yet */
72 void xbt_mallocator_initialization_is_done(int protect)
73 {
74   initialization_done = protect ? 2 : 1;
75 }
76
77 /** used by the module to know if it's time to activate the mallocators yet */
78 static inline int xbt_mallocator_is_active(void) {
79 #if SIMGRID_HAVE_MALLOCATOR
80   return initialization_done && !MC_is_active();
81 #else
82   return 0;
83 #endif
84 }
85
86 /**
87  * @brief Constructor
88  * @param size size of the internal stack: number of objects the mallocator will be able to store
89  * @param new_f function to allocate a new object of your datatype, called in @a xbt_mallocator_get() when the
90  *              mallocator is empty
91  * @param free_f function to free an object of your datatype, called in @a xbt_mallocator_release() when the stack is
92  *                full, and when the mallocator is freed.
93  * @param reset_f function to reinitialize an object of your datatype, called when you extract an object from the
94  *                mallocator (can be NULL)
95  *
96  * Create and initialize a new mallocator for a given datatype.
97  *
98  * @return pointer to the created mallocator
99  * @see xbt_mallocator_free()
100  */
101 xbt_mallocator_t xbt_mallocator_new(int size, pvoid_f_void_t new_f, void_f_pvoid_t free_f, void_f_pvoid_t reset_f)
102 {
103   xbt_mallocator_t m;
104
105   xbt_assert(size > 0, "size must be positive");
106   xbt_assert(new_f != NULL && free_f != NULL, "invalid parameter");
107
108   m = xbt_new0(s_xbt_mallocator_t, 1);
109   XBT_VERB("Create mallocator %p (%s)", m, xbt_mallocator_is_active() ? "enabled" : "disabled");
110   m->current_size = 0;
111   m->new_f = new_f;
112   m->free_f = free_f;
113   m->reset_f = reset_f;
114   m->max_size = size;
115
116   return m;
117 }
118
119 /** @brief Destructor
120  * @param m the mallocator you want to destroy
121  *
122  * Destroy the mallocator and all its data. The function free_f is called on each object in the mallocator.
123  *
124  * @see xbt_mallocator_new()
125  */
126 void xbt_mallocator_free(xbt_mallocator_t m)
127 {
128   xbt_assert(m != NULL, "Invalid parameter");
129
130   XBT_VERB("Frees mallocator %p (size:%d/%d)", m, m->current_size, m->max_size);
131   for (int i = 0; i < m->current_size; i++) {
132     m->free_f(m->objects[i]);
133   }
134   xbt_free(m->objects);
135   xbt_free(m);
136 }
137
138 /**
139  * @brief Extract an object from a mallocator
140  * @param m a mallocator
141  *
142  * Remove an object from the mallocator and return it.
143  * This function is designed to be used instead of malloc().
144  * If the mallocator is not empty, an object is extracted from the mallocator and no malloc is done.
145  *
146  * If the mallocator is empty, a new object is created, by calling the function new_f().
147  *
148  * In both cases, the function reset_f() (if defined) is called on the object.
149  *
150  * @see xbt_mallocator_release()
151  */
152 void *xbt_mallocator_get(xbt_mallocator_t m)
153 {
154   void *object;
155
156   if (m->objects != NULL) { // this mallocator is active, stop thinking and go for it!
157     lock_acquire(m);
158     if (m->current_size <= 0) {
159       /* No object is ready yet. Create a bunch of them to try to group the
160        * mallocs on the same memory pages (to help the cache lines) */
161       int amount = MIN(m->max_size / 2, 1000);
162       for (int i = 0; i < amount; i++)
163         m->objects[i] = m->new_f();
164       m->current_size = amount;
165     }
166
167     /* there is at least an available object, now */
168     object = m->objects[--m->current_size];
169     lock_release(m);
170   } else {
171     if (xbt_mallocator_is_active()) {
172       // We have to switch this mallocator from inactive to active (and then get an object)
173       m->objects = xbt_new0(void *, m->max_size);
174       lock_reset(m);
175       return xbt_mallocator_get(m);
176     } else {
177       object = m->new_f();
178     }
179   }
180
181   if (m->reset_f)
182     m->reset_f(object);
183   return object;
184 }
185
186 /** @brief Push an object into a mallocator
187  * @param m a mallocator
188  * @param object an object you don't need anymore
189  *
190  * Push into the mallocator an object you don't need anymore.
191  * This function is designed to be used instead of free().
192  * If the mallocator is not full, your object if stored into the mallocator and no free is done.
193  * If the mallocator is full, the object is freed by calling the function free_f().
194  *
195  * @see xbt_mallocator_get()
196  */
197 void xbt_mallocator_release(xbt_mallocator_t m, void *object)
198 {
199   if (m == NULL) // The mallocators are already destroyed. Bail out ASAP.
200      return;
201   if (m->objects != NULL) { // Go for it
202     lock_acquire(m);
203     if (m->current_size < m->max_size) {
204       /* there is enough place to push the object */
205       m->objects[m->current_size++] = object;
206       lock_release(m);
207     } else {
208       lock_release(m);
209       /* otherwise we don't have a choice, we must free the object */
210       m->free_f(object);
211     }
212   } else {
213     if (xbt_mallocator_is_active()) {
214       // We have to switch this mallocator from inactive to active (and then store that object)
215       m->objects = xbt_new0(void *, m->max_size);
216       lock_reset(m);
217       xbt_mallocator_release(m,object);
218     } else {
219       m->free_f(object);
220     }
221   }
222 }