1 /*
2  * Copyright 2016 Advanced Micro Devices, Inc.
3  * All Rights Reserved.
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining
6  * a copy of this software and associated documentation files (the
7  * "Software"), to deal in the Software without restriction, including
8  * without limitation the rights to use, copy, modify, merge, publish,
9  * distribute, sub license, and/or sell copies of the Software, and to
10  * permit persons to whom the Software is furnished to do so, subject to
11  * the following conditions:
12  *
13  * The above copyright notice and this permission notice (including the
14  * next paragraph) shall be included in all copies or substantial portions
15  * of the Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
19  * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
20  * NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS, AUTHORS
21  * AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
23  * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
24  * USE OR OTHER DEALINGS IN THE SOFTWARE.
25  *
26  */
27 
28 #include "pb_slab.h"
29 
30 #include "util/u_math.h"
31 #include "util/u_memory.h"
32 
33 /* All slab allocations from the same heap and with the same size belong
34  * to the same group.
35  */
36 struct pb_slab_group
37 {
38    /* Slabs with allocation candidates. Typically, slabs in this list should
39     * have some free entries.
40     *
41     * However, when the head becomes full we purposefully keep it around
42     * until the next allocation attempt, at which time we try a reclaim.
43     * The intention is to keep serving allocations from the same slab as long
44     * as possible for better locality.
45     *
46     * Due to a race in new slab allocation, additional slabs in this list
47     * can be fully allocated as well.
48     */
49    struct list_head slabs;
50 };
51 
52 
53 static void
pb_slab_reclaim(struct pb_slabs * slabs,struct pb_slab_entry * entry)54 pb_slab_reclaim(struct pb_slabs *slabs, struct pb_slab_entry *entry)
55 {
56    struct pb_slab *slab = entry->slab;
57 
58    list_del(&entry->head); /* remove from reclaim list */
59    list_add(&entry->head, &slab->free);
60    slab->num_free++;
61 
62    /* Add slab to the group's list if it isn't already linked. */
63    if (!list_is_linked(&slab->head)) {
64       struct pb_slab_group *group = &slabs->groups[entry->group_index];
65       list_addtail(&slab->head, &group->slabs);
66    }
67 
68    if (slab->num_free >= slab->num_entries) {
69       list_del(&slab->head);
70       slabs->slab_free(slabs->priv, slab);
71    }
72 }
73 
74 #define MAX_FAILED_RECLAIMS 2
75 
76 static void
pb_slabs_reclaim_locked(struct pb_slabs * slabs)77 pb_slabs_reclaim_locked(struct pb_slabs *slabs)
78 {
79    struct pb_slab_entry *entry, *next;
80    unsigned num_failed_reclaims = 0;
81    LIST_FOR_EACH_ENTRY_SAFE(entry, next, &slabs->reclaim, head) {
82       if (slabs->can_reclaim(slabs->priv, entry)) {
83          pb_slab_reclaim(slabs, entry);
84       /* there are typically three possible scenarios when reclaiming:
85        * - all entries reclaimed
86        * - no entries reclaimed
87        * - all but one entry reclaimed
88        * in the scenario where a slab contains many (10+) unused entries,
89        * the driver should not walk the entire list, as this is likely to
90        * result in zero reclaims if the first few entries fail to reclaim
91        */
92       } else if (++num_failed_reclaims >= MAX_FAILED_RECLAIMS) {
93          break;
94       }
95    }
96 }
97 
98 /* Allocate a slab entry of the given size from the given heap.
99  *
100  * This will try to re-use entries that have previously been freed. However,
101  * if no entries are free (or all free entries are still "in flight" as
102  * determined by the can_reclaim fallback function), a new slab will be
103  * requested via the slab_alloc callback.
104  *
105  * Note that slab_free can also be called by this function.
106  */
107 struct pb_slab_entry *
pb_slab_alloc(struct pb_slabs * slabs,unsigned size,unsigned heap)108 pb_slab_alloc(struct pb_slabs *slabs, unsigned size, unsigned heap)
109 {
110    unsigned order = MAX2(slabs->min_order, util_logbase2_ceil(size));
111    unsigned group_index;
112    struct pb_slab_group *group;
113    struct pb_slab *slab;
114    struct pb_slab_entry *entry;
115    unsigned entry_size = 1 << order;
116    bool three_fourths = false;
117 
118    /* If the size is <= 3/4 of the entry size, use a slab with entries using
119     * 3/4 sizes to reduce overallocation.
120     */
121    if (slabs->allow_three_fourths_allocations && size <= entry_size * 3 / 4) {
122       entry_size = entry_size * 3 / 4;
123       three_fourths = true;
124    }
125 
126    assert(order < slabs->min_order + slabs->num_orders);
127    assert(heap < slabs->num_heaps);
128 
129    group_index = (heap * slabs->num_orders + (order - slabs->min_order)) *
130                  (1 + slabs->allow_three_fourths_allocations) + three_fourths;
131    group = &slabs->groups[group_index];
132 
133    simple_mtx_lock(&slabs->mutex);
134 
135    /* If there is no candidate slab at all, or the first slab has no free
136     * entries, try reclaiming entries.
137     */
138    if (list_is_empty(&group->slabs) ||
139        list_is_empty(&LIST_ENTRY(struct pb_slab, group->slabs.next, head)->free))
140       pb_slabs_reclaim_locked(slabs);
141 
142    /* Remove slabs without free entries. */
143    while (!list_is_empty(&group->slabs)) {
144       slab = LIST_ENTRY(struct pb_slab, group->slabs.next, head);
145       if (!list_is_empty(&slab->free))
146          break;
147 
148       list_del(&slab->head);
149    }
150 
151    if (list_is_empty(&group->slabs)) {
152       /* Drop the mutex temporarily to prevent a deadlock where the allocation
153        * calls back into slab functions (most likely to happen for
154        * pb_slab_reclaim if memory is low).
155        *
156        * There's a chance that racing threads will end up allocating multiple
157        * slabs for the same group, but that doesn't hurt correctness.
158        */
159       simple_mtx_unlock(&slabs->mutex);
160       slab = slabs->slab_alloc(slabs->priv, heap, entry_size, group_index);
161       if (!slab)
162          return NULL;
163       simple_mtx_lock(&slabs->mutex);
164 
165       list_add(&slab->head, &group->slabs);
166    }
167 
168    entry = LIST_ENTRY(struct pb_slab_entry, slab->free.next, head);
169    list_del(&entry->head);
170    slab->num_free--;
171 
172    simple_mtx_unlock(&slabs->mutex);
173 
174    return entry;
175 }
176 
177 /* Free the given slab entry.
178  *
179  * The entry may still be in use e.g. by in-flight command submissions. The
180  * can_reclaim callback function will be called to determine whether the entry
181  * can be handed out again by pb_slab_alloc.
182  */
183 void
pb_slab_free(struct pb_slabs * slabs,struct pb_slab_entry * entry)184 pb_slab_free(struct pb_slabs* slabs, struct pb_slab_entry *entry)
185 {
186    simple_mtx_lock(&slabs->mutex);
187    list_addtail(&entry->head, &slabs->reclaim);
188    simple_mtx_unlock(&slabs->mutex);
189 }
190 
191 /* Check if any of the entries handed to pb_slab_free are ready to be re-used.
192  *
193  * This may end up freeing some slabs and is therefore useful to try to reclaim
194  * some no longer used memory. However, calling this function is not strictly
195  * required since pb_slab_alloc will eventually do the same thing.
196  */
197 void
pb_slabs_reclaim(struct pb_slabs * slabs)198 pb_slabs_reclaim(struct pb_slabs *slabs)
199 {
200    simple_mtx_lock(&slabs->mutex);
201    pb_slabs_reclaim_locked(slabs);
202    simple_mtx_unlock(&slabs->mutex);
203 }
204 
205 /* Initialize the slabs manager.
206  *
207  * The minimum and maximum size of slab entries are 2^min_order and
208  * 2^max_order, respectively.
209  *
210  * priv will be passed to the given callback functions.
211  */
212 bool
pb_slabs_init(struct pb_slabs * slabs,unsigned min_order,unsigned max_order,unsigned num_heaps,bool allow_three_fourth_allocations,void * priv,slab_can_reclaim_fn * can_reclaim,slab_alloc_fn * slab_alloc,slab_free_fn * slab_free)213 pb_slabs_init(struct pb_slabs *slabs,
214               unsigned min_order, unsigned max_order,
215               unsigned num_heaps, bool allow_three_fourth_allocations,
216               void *priv,
217               slab_can_reclaim_fn *can_reclaim,
218               slab_alloc_fn *slab_alloc,
219               slab_free_fn *slab_free)
220 {
221    unsigned num_groups;
222    unsigned i;
223 
224    assert(min_order <= max_order);
225    assert(max_order < sizeof(unsigned) * 8 - 1);
226 
227    slabs->min_order = min_order;
228    slabs->num_orders = max_order - min_order + 1;
229    slabs->num_heaps = num_heaps;
230    slabs->allow_three_fourths_allocations = allow_three_fourth_allocations;
231 
232    slabs->priv = priv;
233    slabs->can_reclaim = can_reclaim;
234    slabs->slab_alloc = slab_alloc;
235    slabs->slab_free = slab_free;
236 
237    list_inithead(&slabs->reclaim);
238 
239    num_groups = slabs->num_orders * slabs->num_heaps *
240                 (1 + allow_three_fourth_allocations);
241    slabs->groups = CALLOC(num_groups, sizeof(*slabs->groups));
242    if (!slabs->groups)
243       return false;
244 
245    for (i = 0; i < num_groups; ++i) {
246       struct pb_slab_group *group = &slabs->groups[i];
247       list_inithead(&group->slabs);
248    }
249 
250    (void) simple_mtx_init(&slabs->mutex, mtx_plain);
251 
252    return true;
253 }
254 
255 /* Shutdown the slab manager.
256  *
257  * This will free all allocated slabs and internal structures, even if some
258  * of the slab entries are still in flight (i.e. if can_reclaim would return
259  * false).
260  */
261 void
pb_slabs_deinit(struct pb_slabs * slabs)262 pb_slabs_deinit(struct pb_slabs *slabs)
263 {
264    /* Reclaim all slab entries (even those that are still in flight). This
265     * implicitly calls slab_free for everything.
266     */
267    while (!list_is_empty(&slabs->reclaim)) {
268       struct pb_slab_entry *entry =
269          LIST_ENTRY(struct pb_slab_entry, slabs->reclaim.next, head);
270       pb_slab_reclaim(slabs, entry);
271    }
272 
273    FREE(slabs->groups);
274    simple_mtx_destroy(&slabs->mutex);
275 }
276