1 // SPDX-License-Identifier: GPL-2.0-only
5 * Copyright (C) 2013, Seth Jennings, IBM
7 * Concepts based on zcache internal zbud allocator by Dan Magenheimer.
9 * zbud is an special purpose allocator for storing compressed pages. Contrary
10 * to what its name may suggest, zbud is not a buddy allocator, but rather an
11 * allocator that "buddies" two compressed pages together in a single memory
14 * While this design limits storage density, it has simple and deterministic
15 * reclaim properties that make it preferable to a higher density approach when
16 * reclaim will be used.
18 * zbud works by storing compressed pages, or "zpages", together in pairs in a
19 * single memory page called a "zbud page". The first buddy is "left
20 * justified" at the beginning of the zbud page, and the last buddy is "right
21 * justified" at the end of the zbud page. The benefit is that if either
22 * buddy is freed, the freed buddy space, coalesced with whatever slack space
23 * that existed between the buddies, results in the largest possible free region
24 * within the zbud page.
26 * zbud also provides an attractive lower bound on density. The ratio of zpages
27 * to zbud pages can not be less than 1. This ensures that zbud can never "do
28 * harm" by using more pages to store zpages than the uncompressed zpages would
29 * have used on their own.
31 * zbud pages are divided into "chunks". The size of the chunks is fixed at
32 * compile time and determined by NCHUNKS_ORDER below. Dividing zbud pages
33 * into chunks allows organizing unbuddied zbud pages into a manageable number
34 * of unbuddied lists according to the number of free chunks available in the
37 * The zbud API differs from that of conventional allocators in that the
38 * allocation function, zbud_alloc(), returns an opaque handle to the user,
39 * not a dereferenceable pointer. The user must map the handle using
40 * zbud_map() in order to get a usable pointer by which to access the
41 * allocation data and unmap the handle with zbud_unmap() when operations
42 * on the allocation data are complete.
45 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
47 #include <linux/atomic.h>
48 #include <linux/list.h>
50 #include <linux/module.h>
51 #include <linux/preempt.h>
52 #include <linux/slab.h>
53 #include <linux/spinlock.h>
54 #include <linux/zbud.h>
55 #include <linux/zpool.h>
61 * NCHUNKS_ORDER determines the internal allocation granularity, effectively
62 * adjusting internal fragmentation. It also determines the number of
63 * freelists maintained in each pool. NCHUNKS_ORDER of 6 means that the
64 * allocation granularity will be in chunks of size PAGE_SIZE/64. As one chunk
65 * in allocated page is occupied by zbud header, NCHUNKS will be calculated to
66 * 63 which shows the max number of free chunks in zbud page, also there will be
67 * 63 freelists per pool.
69 #define NCHUNKS_ORDER 6
71 #define CHUNK_SHIFT (PAGE_SHIFT - NCHUNKS_ORDER)
72 #define CHUNK_SIZE (1 << CHUNK_SHIFT)
73 #define ZHDR_SIZE_ALIGNED CHUNK_SIZE
74 #define NCHUNKS ((PAGE_SIZE - ZHDR_SIZE_ALIGNED) >> CHUNK_SHIFT)
77 * struct zbud_pool - stores metadata for each zbud pool
78 * @lock: protects all pool fields and first|last_chunk fields of any
79 * zbud page in the pool
80 * @unbuddied: array of lists tracking zbud pages that only contain one buddy;
81 * the lists each zbud page is added to depends on the size of
83 * @buddied: list tracking the zbud pages that contain two buddies;
84 * these zbud pages are full
85 * @lru: list tracking the zbud pages in LRU order by most recently
87 * @pages_nr: number of zbud pages in the pool.
88 * @ops: pointer to a structure of user defined operations specified at
91 * This structure is allocated at pool creation time and maintains metadata
92 * pertaining to a particular zbud pool.
96 struct list_head unbuddied
[NCHUNKS
];
97 struct list_head buddied
;
100 const struct zbud_ops
*ops
;
103 const struct zpool_ops
*zpool_ops
;
108 * struct zbud_header - zbud page metadata occupying the first chunk of each
110 * @buddy: links the zbud page into the unbuddied/buddied lists in the pool
111 * @lru: links the zbud page into the lru list in the pool
112 * @first_chunks: the size of the first buddy in chunks, 0 if free
113 * @last_chunks: the size of the last buddy in chunks, 0 if free
116 struct list_head buddy
;
117 struct list_head lru
;
118 unsigned int first_chunks
;
119 unsigned int last_chunks
;
129 static int zbud_zpool_evict(struct zbud_pool
*pool
, unsigned long handle
)
131 if (pool
->zpool
&& pool
->zpool_ops
&& pool
->zpool_ops
->evict
)
132 return pool
->zpool_ops
->evict(pool
->zpool
, handle
);
137 static const struct zbud_ops zbud_zpool_ops
= {
138 .evict
= zbud_zpool_evict
141 static void *zbud_zpool_create(const char *name
, gfp_t gfp
,
142 const struct zpool_ops
*zpool_ops
,
145 struct zbud_pool
*pool
;
147 pool
= zbud_create_pool(gfp
, zpool_ops
? &zbud_zpool_ops
: NULL
);
150 pool
->zpool_ops
= zpool_ops
;
155 static void zbud_zpool_destroy(void *pool
)
157 zbud_destroy_pool(pool
);
160 static int zbud_zpool_malloc(void *pool
, size_t size
, gfp_t gfp
,
161 unsigned long *handle
)
163 return zbud_alloc(pool
, size
, gfp
, handle
);
165 static void zbud_zpool_free(void *pool
, unsigned long handle
)
167 zbud_free(pool
, handle
);
170 static int zbud_zpool_shrink(void *pool
, unsigned int pages
,
171 unsigned int *reclaimed
)
173 unsigned int total
= 0;
176 while (total
< pages
) {
177 ret
= zbud_reclaim_page(pool
, 8);
189 static void *zbud_zpool_map(void *pool
, unsigned long handle
,
190 enum zpool_mapmode mm
)
192 return zbud_map(pool
, handle
);
194 static void zbud_zpool_unmap(void *pool
, unsigned long handle
)
196 zbud_unmap(pool
, handle
);
199 static u64
zbud_zpool_total_size(void *pool
)
201 return zbud_get_pool_size(pool
) * PAGE_SIZE
;
204 static struct zpool_driver zbud_zpool_driver
= {
206 .owner
= THIS_MODULE
,
207 .create
= zbud_zpool_create
,
208 .destroy
= zbud_zpool_destroy
,
209 .malloc
= zbud_zpool_malloc
,
210 .free
= zbud_zpool_free
,
211 .shrink
= zbud_zpool_shrink
,
212 .map
= zbud_zpool_map
,
213 .unmap
= zbud_zpool_unmap
,
214 .total_size
= zbud_zpool_total_size
,
217 MODULE_ALIAS("zpool-zbud");
218 #endif /* CONFIG_ZPOOL */
223 /* Just to make the code easier to read */
229 /* Converts an allocation size in bytes to size in zbud chunks */
230 static int size_to_chunks(size_t size
)
232 return (size
+ CHUNK_SIZE
- 1) >> CHUNK_SHIFT
;
235 #define for_each_unbuddied_list(_iter, _begin) \
236 for ((_iter) = (_begin); (_iter) < NCHUNKS; (_iter)++)
238 /* Initializes the zbud header of a newly allocated zbud page */
239 static struct zbud_header
*init_zbud_page(struct page
*page
)
241 struct zbud_header
*zhdr
= page_address(page
);
242 zhdr
->first_chunks
= 0;
243 zhdr
->last_chunks
= 0;
244 INIT_LIST_HEAD(&zhdr
->buddy
);
245 INIT_LIST_HEAD(&zhdr
->lru
);
246 zhdr
->under_reclaim
= false;
250 /* Resets the struct page fields and frees the page */
251 static void free_zbud_page(struct zbud_header
*zhdr
)
253 __free_page(virt_to_page(zhdr
));
257 * Encodes the handle of a particular buddy within a zbud page
258 * Pool lock should be held as this function accesses first|last_chunks
260 static unsigned long encode_handle(struct zbud_header
*zhdr
, enum buddy bud
)
262 unsigned long handle
;
265 * For now, the encoded handle is actually just the pointer to the data
266 * but this might not always be the case. A little information hiding.
267 * Add CHUNK_SIZE to the handle if it is the first allocation to jump
268 * over the zbud header in the first chunk.
270 handle
= (unsigned long)zhdr
;
272 /* skip over zbud header */
273 handle
+= ZHDR_SIZE_ALIGNED
;
274 else /* bud == LAST */
275 handle
+= PAGE_SIZE
- (zhdr
->last_chunks
<< CHUNK_SHIFT
);
279 /* Returns the zbud page where a given handle is stored */
280 static struct zbud_header
*handle_to_zbud_header(unsigned long handle
)
282 return (struct zbud_header
*)(handle
& PAGE_MASK
);
285 /* Returns the number of free chunks in a zbud page */
286 static int num_free_chunks(struct zbud_header
*zhdr
)
289 * Rather than branch for different situations, just use the fact that
290 * free buddies have a length of zero to simplify everything.
292 return NCHUNKS
- zhdr
->first_chunks
- zhdr
->last_chunks
;
299 * zbud_create_pool() - create a new zbud pool
300 * @gfp: gfp flags when allocating the zbud pool structure
301 * @ops: user-defined operations for the zbud pool
303 * Return: pointer to the new zbud pool or NULL if the metadata allocation
306 struct zbud_pool
*zbud_create_pool(gfp_t gfp
, const struct zbud_ops
*ops
)
308 struct zbud_pool
*pool
;
311 pool
= kzalloc(sizeof(struct zbud_pool
), gfp
);
314 spin_lock_init(&pool
->lock
);
315 for_each_unbuddied_list(i
, 0)
316 INIT_LIST_HEAD(&pool
->unbuddied
[i
]);
317 INIT_LIST_HEAD(&pool
->buddied
);
318 INIT_LIST_HEAD(&pool
->lru
);
325 * zbud_destroy_pool() - destroys an existing zbud pool
326 * @pool: the zbud pool to be destroyed
328 * The pool should be emptied before this function is called.
330 void zbud_destroy_pool(struct zbud_pool
*pool
)
336 * zbud_alloc() - allocates a region of a given size
337 * @pool: zbud pool from which to allocate
338 * @size: size in bytes of the desired allocation
339 * @gfp: gfp flags used if the pool needs to grow
340 * @handle: handle of the new allocation
342 * This function will attempt to find a free region in the pool large enough to
343 * satisfy the allocation request. A search of the unbuddied lists is
344 * performed first. If no suitable free region is found, then a new page is
345 * allocated and added to the pool to satisfy the request.
347 * gfp should not set __GFP_HIGHMEM as highmem pages cannot be used
348 * as zbud pool pages.
350 * Return: 0 if success and handle is set, otherwise -EINVAL if the size or
351 * gfp arguments are invalid or -ENOMEM if the pool was unable to allocate
354 int zbud_alloc(struct zbud_pool
*pool
, size_t size
, gfp_t gfp
,
355 unsigned long *handle
)
357 int chunks
, i
, freechunks
;
358 struct zbud_header
*zhdr
= NULL
;
362 if (!size
|| (gfp
& __GFP_HIGHMEM
))
364 if (size
> PAGE_SIZE
- ZHDR_SIZE_ALIGNED
- CHUNK_SIZE
)
366 chunks
= size_to_chunks(size
);
367 spin_lock(&pool
->lock
);
369 /* First, try to find an unbuddied zbud page. */
370 for_each_unbuddied_list(i
, chunks
) {
371 if (!list_empty(&pool
->unbuddied
[i
])) {
372 zhdr
= list_first_entry(&pool
->unbuddied
[i
],
373 struct zbud_header
, buddy
);
374 list_del(&zhdr
->buddy
);
375 if (zhdr
->first_chunks
== 0)
383 /* Couldn't find unbuddied zbud page, create new one */
384 spin_unlock(&pool
->lock
);
385 page
= alloc_page(gfp
);
388 spin_lock(&pool
->lock
);
390 zhdr
= init_zbud_page(page
);
395 zhdr
->first_chunks
= chunks
;
397 zhdr
->last_chunks
= chunks
;
399 if (zhdr
->first_chunks
== 0 || zhdr
->last_chunks
== 0) {
400 /* Add to unbuddied list */
401 freechunks
= num_free_chunks(zhdr
);
402 list_add(&zhdr
->buddy
, &pool
->unbuddied
[freechunks
]);
404 /* Add to buddied list */
405 list_add(&zhdr
->buddy
, &pool
->buddied
);
408 /* Add/move zbud page to beginning of LRU */
409 if (!list_empty(&zhdr
->lru
))
410 list_del(&zhdr
->lru
);
411 list_add(&zhdr
->lru
, &pool
->lru
);
413 *handle
= encode_handle(zhdr
, bud
);
414 spin_unlock(&pool
->lock
);
420 * zbud_free() - frees the allocation associated with the given handle
421 * @pool: pool in which the allocation resided
422 * @handle: handle associated with the allocation returned by zbud_alloc()
424 * In the case that the zbud page in which the allocation resides is under
425 * reclaim, as indicated by the PG_reclaim flag being set, this function
426 * only sets the first|last_chunks to 0. The page is actually freed
427 * once both buddies are evicted (see zbud_reclaim_page() below).
429 void zbud_free(struct zbud_pool
*pool
, unsigned long handle
)
431 struct zbud_header
*zhdr
;
434 spin_lock(&pool
->lock
);
435 zhdr
= handle_to_zbud_header(handle
);
437 /* If first buddy, handle will be page aligned */
438 if ((handle
- ZHDR_SIZE_ALIGNED
) & ~PAGE_MASK
)
439 zhdr
->last_chunks
= 0;
441 zhdr
->first_chunks
= 0;
443 if (zhdr
->under_reclaim
) {
444 /* zbud page is under reclaim, reclaim will free */
445 spin_unlock(&pool
->lock
);
449 /* Remove from existing buddy list */
450 list_del(&zhdr
->buddy
);
452 if (zhdr
->first_chunks
== 0 && zhdr
->last_chunks
== 0) {
453 /* zbud page is empty, free */
454 list_del(&zhdr
->lru
);
455 free_zbud_page(zhdr
);
458 /* Add to unbuddied list */
459 freechunks
= num_free_chunks(zhdr
);
460 list_add(&zhdr
->buddy
, &pool
->unbuddied
[freechunks
]);
463 spin_unlock(&pool
->lock
);
467 * zbud_reclaim_page() - evicts allocations from a pool page and frees it
468 * @pool: pool from which a page will attempt to be evicted
469 * @retries: number of pages on the LRU list for which eviction will
470 * be attempted before failing
472 * zbud reclaim is different from normal system reclaim in that the reclaim is
473 * done from the bottom, up. This is because only the bottom layer, zbud, has
474 * information on how the allocations are organized within each zbud page. This
475 * has the potential to create interesting locking situations between zbud and
478 * To avoid these, this is how zbud_reclaim_page() should be called:
480 * The user detects a page should be reclaimed and calls zbud_reclaim_page().
481 * zbud_reclaim_page() will remove a zbud page from the pool LRU list and call
482 * the user-defined eviction handler with the pool and handle as arguments.
484 * If the handle can not be evicted, the eviction handler should return
485 * non-zero. zbud_reclaim_page() will add the zbud page back to the
486 * appropriate list and try the next zbud page on the LRU up to
487 * a user defined number of retries.
489 * If the handle is successfully evicted, the eviction handler should
490 * return 0 _and_ should have called zbud_free() on the handle. zbud_free()
491 * contains logic to delay freeing the page if the page is under reclaim,
492 * as indicated by the setting of the PG_reclaim flag on the underlying page.
494 * If all buddies in the zbud page are successfully evicted, then the
495 * zbud page can be freed.
497 * Returns: 0 if page is successfully freed, otherwise -EINVAL if there are
498 * no pages to evict or an eviction handler is not registered, -EAGAIN if
499 * the retry limit was hit.
501 int zbud_reclaim_page(struct zbud_pool
*pool
, unsigned int retries
)
503 int i
, ret
, freechunks
;
504 struct zbud_header
*zhdr
;
505 unsigned long first_handle
= 0, last_handle
= 0;
507 spin_lock(&pool
->lock
);
508 if (!pool
->ops
|| !pool
->ops
->evict
|| list_empty(&pool
->lru
) ||
510 spin_unlock(&pool
->lock
);
513 for (i
= 0; i
< retries
; i
++) {
514 zhdr
= list_last_entry(&pool
->lru
, struct zbud_header
, lru
);
515 list_del(&zhdr
->lru
);
516 list_del(&zhdr
->buddy
);
517 /* Protect zbud page against free */
518 zhdr
->under_reclaim
= true;
520 * We need encode the handles before unlocking, since we can
521 * race with free that will set (first|last)_chunks to 0
525 if (zhdr
->first_chunks
)
526 first_handle
= encode_handle(zhdr
, FIRST
);
527 if (zhdr
->last_chunks
)
528 last_handle
= encode_handle(zhdr
, LAST
);
529 spin_unlock(&pool
->lock
);
531 /* Issue the eviction callback(s) */
533 ret
= pool
->ops
->evict(pool
, first_handle
);
538 ret
= pool
->ops
->evict(pool
, last_handle
);
543 spin_lock(&pool
->lock
);
544 zhdr
->under_reclaim
= false;
545 if (zhdr
->first_chunks
== 0 && zhdr
->last_chunks
== 0) {
547 * Both buddies are now free, free the zbud page and
550 free_zbud_page(zhdr
);
552 spin_unlock(&pool
->lock
);
554 } else if (zhdr
->first_chunks
== 0 ||
555 zhdr
->last_chunks
== 0) {
556 /* add to unbuddied list */
557 freechunks
= num_free_chunks(zhdr
);
558 list_add(&zhdr
->buddy
, &pool
->unbuddied
[freechunks
]);
560 /* add to buddied list */
561 list_add(&zhdr
->buddy
, &pool
->buddied
);
564 /* add to beginning of LRU */
565 list_add(&zhdr
->lru
, &pool
->lru
);
567 spin_unlock(&pool
->lock
);
572 * zbud_map() - maps the allocation associated with the given handle
573 * @pool: pool in which the allocation resides
574 * @handle: handle associated with the allocation to be mapped
576 * While trivial for zbud, the mapping functions for others allocators
577 * implementing this allocation API could have more complex information encoded
578 * in the handle and could create temporary mappings to make the data
579 * accessible to the user.
581 * Returns: a pointer to the mapped allocation
583 void *zbud_map(struct zbud_pool
*pool
, unsigned long handle
)
585 return (void *)(handle
);
589 * zbud_unmap() - maps the allocation associated with the given handle
590 * @pool: pool in which the allocation resides
591 * @handle: handle associated with the allocation to be unmapped
593 void zbud_unmap(struct zbud_pool
*pool
, unsigned long handle
)
598 * zbud_get_pool_size() - gets the zbud pool size in pages
599 * @pool: pool whose size is being queried
601 * Returns: size in pages of the given pool. The pool lock need not be
602 * taken to access pages_nr.
604 u64
zbud_get_pool_size(struct zbud_pool
*pool
)
606 return pool
->pages_nr
;
609 static int __init
init_zbud(void)
611 /* Make sure the zbud header will fit in one chunk */
612 BUILD_BUG_ON(sizeof(struct zbud_header
) > ZHDR_SIZE_ALIGNED
);
616 zpool_register_driver(&zbud_zpool_driver
);
622 static void __exit
exit_zbud(void)
625 zpool_unregister_driver(&zbud_zpool_driver
);
628 pr_info("unloaded\n");
631 module_init(init_zbud
);
632 module_exit(exit_zbud
);
634 MODULE_LICENSE("GPL");
635 MODULE_AUTHOR("Seth Jennings <sjennings@variantweb.net>");
636 MODULE_DESCRIPTION("Buddy Allocator for Compressed Pages");