4 * Author: Vitaly Wool <vitaly.wool@konsulko.com>
5 * Copyright (C) 2016, Sony Mobile Communications Inc.
7 * This implementation is based on zbud written by Seth Jennings.
9 * z3fold is an special purpose allocator for storing compressed pages. It
10 * can store up to three compressed pages per page which improves the
11 * compression ratio of zbud while retaining its main concepts (e. g. always
12 * storing an integral number of objects per page) and simplicity.
13 * It still has simple and deterministic reclaim properties that make it
14 * preferable to a higher density approach (with no requirement on integral
15 * number of object per page) when reclaim is used.
17 * As in zbud, pages are divided into "chunks". The size of the chunks is
18 * fixed at compile time and is determined by NCHUNKS_ORDER below.
20 * z3fold doesn't export any API and is meant to be used via zpool API.
23 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
25 #include <linux/atomic.h>
26 #include <linux/list.h>
28 #include <linux/module.h>
29 #include <linux/preempt.h>
30 #include <linux/slab.h>
31 #include <linux/spinlock.h>
32 #include <linux/zpool.h>
38 * NCHUNKS_ORDER determines the internal allocation granularity, effectively
39 * adjusting internal fragmentation. It also determines the number of
40 * freelists maintained in each pool. NCHUNKS_ORDER of 6 means that the
41 * allocation granularity will be in chunks of size PAGE_SIZE/64. As one chunk
42 * in allocated page is occupied by z3fold header, NCHUNKS will be calculated
43 * to 63 which shows the max number of free chunks in z3fold page, also there
44 * will be 63 freelists per pool.
46 #define NCHUNKS_ORDER 6
48 #define CHUNK_SHIFT (PAGE_SHIFT - NCHUNKS_ORDER)
49 #define CHUNK_SIZE (1 << CHUNK_SHIFT)
50 #define ZHDR_SIZE_ALIGNED CHUNK_SIZE
51 #define NCHUNKS ((PAGE_SIZE - ZHDR_SIZE_ALIGNED) >> CHUNK_SHIFT)
53 #define BUDDY_MASK (0x3)
57 int (*evict
)(struct z3fold_pool
*pool
, unsigned long handle
);
61 * struct z3fold_pool - stores metadata for each z3fold pool
62 * @lock: protects all pool fields and first|last_chunk fields of any
63 * z3fold page in the pool
64 * @unbuddied: array of lists tracking z3fold pages that contain 2- buddies;
65 * the lists each z3fold page is added to depends on the size of
67 * @buddied: list tracking the z3fold pages that contain 3 buddies;
68 * these z3fold pages are full
69 * @lru: list tracking the z3fold pages in LRU order by most recently
71 * @pages_nr: number of z3fold pages in the pool.
72 * @ops: pointer to a structure of user defined operations specified at
75 * This structure is allocated at pool creation time and maintains metadata
76 * pertaining to a particular z3fold pool.
80 struct list_head unbuddied
[NCHUNKS
];
81 struct list_head buddied
;
84 const struct z3fold_ops
*ops
;
86 const struct zpool_ops
*zpool_ops
;
98 * struct z3fold_header - z3fold page metadata occupying the first chunk of each
99 * z3fold page, except for HEADLESS pages
100 * @buddy: links the z3fold page into the relevant list in the pool
101 * @first_chunks: the size of the first buddy in chunks, 0 if free
102 * @middle_chunks: the size of the middle buddy in chunks, 0 if free
103 * @last_chunks: the size of the last buddy in chunks, 0 if free
104 * @first_num: the starting number (for the first handle)
106 struct z3fold_header
{
107 struct list_head buddy
;
108 unsigned short first_chunks
;
109 unsigned short middle_chunks
;
110 unsigned short last_chunks
;
111 unsigned short start_middle
;
112 unsigned short first_num
:2;
116 * Internal z3fold page flags
118 enum z3fold_page_flags
{
128 /* Converts an allocation size in bytes to size in z3fold chunks */
129 static int size_to_chunks(size_t size
)
131 return (size
+ CHUNK_SIZE
- 1) >> CHUNK_SHIFT
;
134 #define for_each_unbuddied_list(_iter, _begin) \
135 for ((_iter) = (_begin); (_iter) < NCHUNKS; (_iter)++)
137 /* Initializes the z3fold header of a newly allocated z3fold page */
138 static struct z3fold_header
*init_z3fold_page(struct page
*page
)
140 struct z3fold_header
*zhdr
= page_address(page
);
142 INIT_LIST_HEAD(&page
->lru
);
143 clear_bit(UNDER_RECLAIM
, &page
->private);
144 clear_bit(PAGE_HEADLESS
, &page
->private);
145 clear_bit(MIDDLE_CHUNK_MAPPED
, &page
->private);
147 zhdr
->first_chunks
= 0;
148 zhdr
->middle_chunks
= 0;
149 zhdr
->last_chunks
= 0;
151 zhdr
->start_middle
= 0;
152 INIT_LIST_HEAD(&zhdr
->buddy
);
156 /* Resets the struct page fields and frees the page */
157 static void free_z3fold_page(struct z3fold_header
*zhdr
)
159 __free_page(virt_to_page(zhdr
));
163 * Encodes the handle of a particular buddy within a z3fold page
164 * Pool lock should be held as this function accesses first_num
166 static unsigned long encode_handle(struct z3fold_header
*zhdr
, enum buddy bud
)
168 unsigned long handle
;
170 handle
= (unsigned long)zhdr
;
172 handle
+= (bud
+ zhdr
->first_num
) & BUDDY_MASK
;
176 /* Returns the z3fold page where a given handle is stored */
177 static struct z3fold_header
*handle_to_z3fold_header(unsigned long handle
)
179 return (struct z3fold_header
*)(handle
& PAGE_MASK
);
183 * (handle & BUDDY_MASK) < zhdr->first_num is possible in encode_handle
184 * but that doesn't matter. because the masking will result in the
185 * correct buddy number.
187 static enum buddy
handle_to_buddy(unsigned long handle
)
189 struct z3fold_header
*zhdr
= handle_to_z3fold_header(handle
);
190 return (handle
- zhdr
->first_num
) & BUDDY_MASK
;
194 * Returns the number of free chunks in a z3fold page.
195 * NB: can't be used with HEADLESS pages.
197 static int num_free_chunks(struct z3fold_header
*zhdr
)
201 * If there is a middle object, pick up the bigger free space
202 * either before or after it. Otherwise just subtract the number
203 * of chunks occupied by the first and the last objects.
205 if (zhdr
->middle_chunks
!= 0) {
206 int nfree_before
= zhdr
->first_chunks
?
207 0 : zhdr
->start_middle
- 1;
208 int nfree_after
= zhdr
->last_chunks
?
209 0 : NCHUNKS
- zhdr
->start_middle
- zhdr
->middle_chunks
;
210 nfree
= max(nfree_before
, nfree_after
);
212 nfree
= NCHUNKS
- zhdr
->first_chunks
- zhdr
->last_chunks
;
220 * z3fold_create_pool() - create a new z3fold pool
221 * @gfp: gfp flags when allocating the z3fold pool structure
222 * @ops: user-defined operations for the z3fold pool
224 * Return: pointer to the new z3fold pool or NULL if the metadata allocation
227 static struct z3fold_pool
*z3fold_create_pool(gfp_t gfp
,
228 const struct z3fold_ops
*ops
)
230 struct z3fold_pool
*pool
;
233 pool
= kzalloc(sizeof(struct z3fold_pool
), gfp
);
236 spin_lock_init(&pool
->lock
);
237 for_each_unbuddied_list(i
, 0)
238 INIT_LIST_HEAD(&pool
->unbuddied
[i
]);
239 INIT_LIST_HEAD(&pool
->buddied
);
240 INIT_LIST_HEAD(&pool
->lru
);
247 * z3fold_destroy_pool() - destroys an existing z3fold pool
248 * @pool: the z3fold pool to be destroyed
250 * The pool should be emptied before this function is called.
252 static void z3fold_destroy_pool(struct z3fold_pool
*pool
)
257 /* Has to be called with lock held */
258 static int z3fold_compact_page(struct z3fold_header
*zhdr
)
260 struct page
*page
= virt_to_page(zhdr
);
264 if (!test_bit(MIDDLE_CHUNK_MAPPED
, &page
->private) &&
265 zhdr
->middle_chunks
!= 0 &&
266 zhdr
->first_chunks
== 0 && zhdr
->last_chunks
== 0) {
267 memmove(beg
+ ZHDR_SIZE_ALIGNED
,
268 beg
+ (zhdr
->start_middle
<< CHUNK_SHIFT
),
269 zhdr
->middle_chunks
<< CHUNK_SHIFT
);
270 zhdr
->first_chunks
= zhdr
->middle_chunks
;
271 zhdr
->middle_chunks
= 0;
272 zhdr
->start_middle
= 0;
280 * z3fold_alloc() - allocates a region of a given size
281 * @pool: z3fold pool from which to allocate
282 * @size: size in bytes of the desired allocation
283 * @gfp: gfp flags used if the pool needs to grow
284 * @handle: handle of the new allocation
286 * This function will attempt to find a free region in the pool large enough to
287 * satisfy the allocation request. A search of the unbuddied lists is
288 * performed first. If no suitable free region is found, then a new page is
289 * allocated and added to the pool to satisfy the request.
291 * gfp should not set __GFP_HIGHMEM as highmem pages cannot be used
292 * as z3fold pool pages.
294 * Return: 0 if success and handle is set, otherwise -EINVAL if the size or
295 * gfp arguments are invalid or -ENOMEM if the pool was unable to allocate
298 static int z3fold_alloc(struct z3fold_pool
*pool
, size_t size
, gfp_t gfp
,
299 unsigned long *handle
)
301 int chunks
= 0, i
, freechunks
;
302 struct z3fold_header
*zhdr
= NULL
;
306 if (!size
|| (gfp
& __GFP_HIGHMEM
))
309 if (size
> PAGE_SIZE
)
312 if (size
> PAGE_SIZE
- ZHDR_SIZE_ALIGNED
- CHUNK_SIZE
)
315 chunks
= size_to_chunks(size
);
316 spin_lock(&pool
->lock
);
318 /* First, try to find an unbuddied z3fold page. */
320 for_each_unbuddied_list(i
, chunks
) {
321 if (!list_empty(&pool
->unbuddied
[i
])) {
322 zhdr
= list_first_entry(&pool
->unbuddied
[i
],
323 struct z3fold_header
, buddy
);
324 page
= virt_to_page(zhdr
);
325 if (zhdr
->first_chunks
== 0) {
326 if (zhdr
->middle_chunks
!= 0 &&
327 chunks
>= zhdr
->start_middle
)
331 } else if (zhdr
->last_chunks
== 0)
333 else if (zhdr
->middle_chunks
== 0)
336 pr_err("No free chunks in unbuddied\n");
340 list_del(&zhdr
->buddy
);
345 spin_unlock(&pool
->lock
);
348 /* Couldn't find unbuddied z3fold page, create new one */
349 page
= alloc_page(gfp
);
352 spin_lock(&pool
->lock
);
354 zhdr
= init_z3fold_page(page
);
356 if (bud
== HEADLESS
) {
357 set_bit(PAGE_HEADLESS
, &page
->private);
363 zhdr
->first_chunks
= chunks
;
364 else if (bud
== LAST
)
365 zhdr
->last_chunks
= chunks
;
367 zhdr
->middle_chunks
= chunks
;
368 zhdr
->start_middle
= zhdr
->first_chunks
+ 1;
371 if (zhdr
->first_chunks
== 0 || zhdr
->last_chunks
== 0 ||
372 zhdr
->middle_chunks
== 0) {
373 /* Add to unbuddied list */
374 freechunks
= num_free_chunks(zhdr
);
375 list_add(&zhdr
->buddy
, &pool
->unbuddied
[freechunks
]);
377 /* Add to buddied list */
378 list_add(&zhdr
->buddy
, &pool
->buddied
);
382 /* Add/move z3fold page to beginning of LRU */
383 if (!list_empty(&page
->lru
))
384 list_del(&page
->lru
);
386 list_add(&page
->lru
, &pool
->lru
);
388 *handle
= encode_handle(zhdr
, bud
);
389 spin_unlock(&pool
->lock
);
395 * z3fold_free() - frees the allocation associated with the given handle
396 * @pool: pool in which the allocation resided
397 * @handle: handle associated with the allocation returned by z3fold_alloc()
399 * In the case that the z3fold page in which the allocation resides is under
400 * reclaim, as indicated by the PG_reclaim flag being set, this function
401 * only sets the first|last_chunks to 0. The page is actually freed
402 * once both buddies are evicted (see z3fold_reclaim_page() below).
404 static void z3fold_free(struct z3fold_pool
*pool
, unsigned long handle
)
406 struct z3fold_header
*zhdr
;
411 spin_lock(&pool
->lock
);
412 zhdr
= handle_to_z3fold_header(handle
);
413 page
= virt_to_page(zhdr
);
415 if (test_bit(PAGE_HEADLESS
, &page
->private)) {
416 /* HEADLESS page stored */
419 bud
= handle_to_buddy(handle
);
423 zhdr
->first_chunks
= 0;
426 zhdr
->middle_chunks
= 0;
427 zhdr
->start_middle
= 0;
430 zhdr
->last_chunks
= 0;
433 pr_err("%s: unknown bud %d\n", __func__
, bud
);
435 spin_unlock(&pool
->lock
);
440 if (test_bit(UNDER_RECLAIM
, &page
->private)) {
441 /* z3fold page is under reclaim, reclaim will free */
442 spin_unlock(&pool
->lock
);
446 if (bud
!= HEADLESS
) {
447 /* Remove from existing buddy list */
448 list_del(&zhdr
->buddy
);
451 if (bud
== HEADLESS
||
452 (zhdr
->first_chunks
== 0 && zhdr
->middle_chunks
== 0 &&
453 zhdr
->last_chunks
== 0)) {
454 /* z3fold page is empty, free */
455 list_del(&page
->lru
);
456 clear_bit(PAGE_HEADLESS
, &page
->private);
457 free_z3fold_page(zhdr
);
460 z3fold_compact_page(zhdr
);
461 /* Add to the unbuddied list */
462 freechunks
= num_free_chunks(zhdr
);
463 list_add(&zhdr
->buddy
, &pool
->unbuddied
[freechunks
]);
466 spin_unlock(&pool
->lock
);
470 * z3fold_reclaim_page() - evicts allocations from a pool page and frees it
471 * @pool: pool from which a page will attempt to be evicted
472 * @retires: number of pages on the LRU list for which eviction will
473 * be attempted before failing
475 * z3fold reclaim is different from normal system reclaim in that it is done
476 * from the bottom, up. This is because only the bottom layer, z3fold, has
477 * information on how the allocations are organized within each z3fold page.
478 * This has the potential to create interesting locking situations between
479 * z3fold and the user, however.
481 * To avoid these, this is how z3fold_reclaim_page() should be called:
483 * The user detects a page should be reclaimed and calls z3fold_reclaim_page().
484 * z3fold_reclaim_page() will remove a z3fold page from the pool LRU list and
485 * call the user-defined eviction handler with the pool and handle as
488 * If the handle can not be evicted, the eviction handler should return
489 * non-zero. z3fold_reclaim_page() will add the z3fold page back to the
490 * appropriate list and try the next z3fold page on the LRU up to
491 * a user defined number of retries.
493 * If the handle is successfully evicted, the eviction handler should
494 * return 0 _and_ should have called z3fold_free() on the handle. z3fold_free()
495 * contains logic to delay freeing the page if the page is under reclaim,
496 * as indicated by the setting of the PG_reclaim flag on the underlying page.
498 * If all buddies in the z3fold page are successfully evicted, then the
499 * z3fold page can be freed.
501 * Returns: 0 if page is successfully freed, otherwise -EINVAL if there are
502 * no pages to evict or an eviction handler is not registered, -EAGAIN if
503 * the retry limit was hit.
505 static int z3fold_reclaim_page(struct z3fold_pool
*pool
, unsigned int retries
)
507 int i
, ret
= 0, freechunks
;
508 struct z3fold_header
*zhdr
;
510 unsigned long first_handle
= 0, middle_handle
= 0, last_handle
= 0;
512 spin_lock(&pool
->lock
);
513 if (!pool
->ops
|| !pool
->ops
->evict
|| list_empty(&pool
->lru
) ||
515 spin_unlock(&pool
->lock
);
518 for (i
= 0; i
< retries
; i
++) {
519 page
= list_last_entry(&pool
->lru
, struct page
, lru
);
520 list_del(&page
->lru
);
522 /* Protect z3fold page against free */
523 set_bit(UNDER_RECLAIM
, &page
->private);
524 zhdr
= page_address(page
);
525 if (!test_bit(PAGE_HEADLESS
, &page
->private)) {
526 list_del(&zhdr
->buddy
);
528 * We need encode the handles before unlocking, since
529 * we can race with free that will set
530 * (first|last)_chunks to 0
535 if (zhdr
->first_chunks
)
536 first_handle
= encode_handle(zhdr
, FIRST
);
537 if (zhdr
->middle_chunks
)
538 middle_handle
= encode_handle(zhdr
, MIDDLE
);
539 if (zhdr
->last_chunks
)
540 last_handle
= encode_handle(zhdr
, LAST
);
542 first_handle
= encode_handle(zhdr
, HEADLESS
);
543 last_handle
= middle_handle
= 0;
546 spin_unlock(&pool
->lock
);
548 /* Issue the eviction callback(s) */
550 ret
= pool
->ops
->evict(pool
, middle_handle
);
555 ret
= pool
->ops
->evict(pool
, first_handle
);
560 ret
= pool
->ops
->evict(pool
, last_handle
);
565 spin_lock(&pool
->lock
);
566 clear_bit(UNDER_RECLAIM
, &page
->private);
567 if ((test_bit(PAGE_HEADLESS
, &page
->private) && ret
== 0) ||
568 (zhdr
->first_chunks
== 0 && zhdr
->last_chunks
== 0 &&
569 zhdr
->middle_chunks
== 0)) {
571 * All buddies are now free, free the z3fold page and
574 clear_bit(PAGE_HEADLESS
, &page
->private);
575 free_z3fold_page(zhdr
);
577 spin_unlock(&pool
->lock
);
579 } else if (!test_bit(PAGE_HEADLESS
, &page
->private)) {
580 if (zhdr
->first_chunks
!= 0 &&
581 zhdr
->last_chunks
!= 0 &&
582 zhdr
->middle_chunks
!= 0) {
583 /* Full, add to buddied list */
584 list_add(&zhdr
->buddy
, &pool
->buddied
);
586 z3fold_compact_page(zhdr
);
587 /* add to unbuddied list */
588 freechunks
= num_free_chunks(zhdr
);
589 list_add(&zhdr
->buddy
,
590 &pool
->unbuddied
[freechunks
]);
594 /* add to beginning of LRU */
595 list_add(&page
->lru
, &pool
->lru
);
597 spin_unlock(&pool
->lock
);
602 * z3fold_map() - maps the allocation associated with the given handle
603 * @pool: pool in which the allocation resides
604 * @handle: handle associated with the allocation to be mapped
606 * Extracts the buddy number from handle and constructs the pointer to the
607 * correct starting chunk within the page.
609 * Returns: a pointer to the mapped allocation
611 static void *z3fold_map(struct z3fold_pool
*pool
, unsigned long handle
)
613 struct z3fold_header
*zhdr
;
618 spin_lock(&pool
->lock
);
619 zhdr
= handle_to_z3fold_header(handle
);
621 page
= virt_to_page(zhdr
);
623 if (test_bit(PAGE_HEADLESS
, &page
->private))
626 buddy
= handle_to_buddy(handle
);
629 addr
+= ZHDR_SIZE_ALIGNED
;
632 addr
+= zhdr
->start_middle
<< CHUNK_SHIFT
;
633 set_bit(MIDDLE_CHUNK_MAPPED
, &page
->private);
636 addr
+= PAGE_SIZE
- (zhdr
->last_chunks
<< CHUNK_SHIFT
);
639 pr_err("unknown buddy id %d\n", buddy
);
645 spin_unlock(&pool
->lock
);
650 * z3fold_unmap() - unmaps the allocation associated with the given handle
651 * @pool: pool in which the allocation resides
652 * @handle: handle associated with the allocation to be unmapped
654 static void z3fold_unmap(struct z3fold_pool
*pool
, unsigned long handle
)
656 struct z3fold_header
*zhdr
;
660 spin_lock(&pool
->lock
);
661 zhdr
= handle_to_z3fold_header(handle
);
662 page
= virt_to_page(zhdr
);
664 if (test_bit(PAGE_HEADLESS
, &page
->private)) {
665 spin_unlock(&pool
->lock
);
669 buddy
= handle_to_buddy(handle
);
671 clear_bit(MIDDLE_CHUNK_MAPPED
, &page
->private);
672 spin_unlock(&pool
->lock
);
676 * z3fold_get_pool_size() - gets the z3fold pool size in pages
677 * @pool: pool whose size is being queried
679 * Returns: size in pages of the given pool. The pool lock need not be
680 * taken to access pages_nr.
682 static u64
z3fold_get_pool_size(struct z3fold_pool
*pool
)
684 return pool
->pages_nr
;
691 static int z3fold_zpool_evict(struct z3fold_pool
*pool
, unsigned long handle
)
693 if (pool
->zpool
&& pool
->zpool_ops
&& pool
->zpool_ops
->evict
)
694 return pool
->zpool_ops
->evict(pool
->zpool
, handle
);
699 static const struct z3fold_ops z3fold_zpool_ops
= {
700 .evict
= z3fold_zpool_evict
703 static void *z3fold_zpool_create(const char *name
, gfp_t gfp
,
704 const struct zpool_ops
*zpool_ops
,
707 struct z3fold_pool
*pool
;
709 pool
= z3fold_create_pool(gfp
, zpool_ops
? &z3fold_zpool_ops
: NULL
);
712 pool
->zpool_ops
= zpool_ops
;
717 static void z3fold_zpool_destroy(void *pool
)
719 z3fold_destroy_pool(pool
);
722 static int z3fold_zpool_malloc(void *pool
, size_t size
, gfp_t gfp
,
723 unsigned long *handle
)
725 return z3fold_alloc(pool
, size
, gfp
, handle
);
727 static void z3fold_zpool_free(void *pool
, unsigned long handle
)
729 z3fold_free(pool
, handle
);
732 static int z3fold_zpool_shrink(void *pool
, unsigned int pages
,
733 unsigned int *reclaimed
)
735 unsigned int total
= 0;
738 while (total
< pages
) {
739 ret
= z3fold_reclaim_page(pool
, 8);
751 static void *z3fold_zpool_map(void *pool
, unsigned long handle
,
752 enum zpool_mapmode mm
)
754 return z3fold_map(pool
, handle
);
756 static void z3fold_zpool_unmap(void *pool
, unsigned long handle
)
758 z3fold_unmap(pool
, handle
);
761 static u64
z3fold_zpool_total_size(void *pool
)
763 return z3fold_get_pool_size(pool
) * PAGE_SIZE
;
766 static struct zpool_driver z3fold_zpool_driver
= {
768 .owner
= THIS_MODULE
,
769 .create
= z3fold_zpool_create
,
770 .destroy
= z3fold_zpool_destroy
,
771 .malloc
= z3fold_zpool_malloc
,
772 .free
= z3fold_zpool_free
,
773 .shrink
= z3fold_zpool_shrink
,
774 .map
= z3fold_zpool_map
,
775 .unmap
= z3fold_zpool_unmap
,
776 .total_size
= z3fold_zpool_total_size
,
779 MODULE_ALIAS("zpool-z3fold");
781 static int __init
init_z3fold(void)
783 /* Make sure the z3fold header will fit in one chunk */
784 BUILD_BUG_ON(sizeof(struct z3fold_header
) > ZHDR_SIZE_ALIGNED
);
785 zpool_register_driver(&z3fold_zpool_driver
);
790 static void __exit
exit_z3fold(void)
792 zpool_unregister_driver(&z3fold_zpool_driver
);
795 module_init(init_z3fold
);
796 module_exit(exit_z3fold
);
798 MODULE_LICENSE("GPL");
799 MODULE_AUTHOR("Vitaly Wool <vitalywool@gmail.com>");
800 MODULE_DESCRIPTION("3-Fold Allocator for Compressed Pages");