1 // SPDX-License-Identifier: GPL-2.0-or-later
4 * zsmalloc memory allocator
6 * Copyright (C) 2011 Nitin Gupta
7 * Copyright (C) 2012, 2013 Minchan Kim
9 * This code is released using a dual license strategy: BSD/GPL
10 * You can choose the license that better fits your requirements.
12 * Released under the terms of 3-clause BSD License
13 * Released under the terms of GNU General Public License Version 2.0
16 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
26 #include <linux/module.h>
27 #include <linux/kernel.h>
28 #include <linux/sched.h>
29 #include <linux/bitops.h>
30 #include <linux/errno.h>
31 #include <linux/highmem.h>
32 #include <linux/string.h>
33 #include <linux/slab.h>
34 #include <linux/pgtable.h>
35 #include <asm/tlbflush.h>
36 #include <linux/cpumask.h>
37 #include <linux/cpu.h>
38 #include <linux/vmalloc.h>
39 #include <linux/preempt.h>
40 #include <linux/spinlock.h>
41 #include <linux/sprintf.h>
42 #include <linux/shrinker.h>
43 #include <linux/types.h>
44 #include <linux/debugfs.h>
45 #include <linux/zsmalloc.h>
46 #include <linux/zpool.h>
47 #include <linux/migrate.h>
48 #include <linux/wait.h>
49 #include <linux/pagemap.h>
51 #include <linux/local_lock.h>
54 #define ZSPAGE_MAGIC 0x58
57 * This must be power of 2 and greater than or equal to sizeof(link_free).
58 * These two conditions ensure that any 'struct link_free' itself doesn't
59 * span more than 1 page which avoids complex case of mapping 2 pages simply
60 * to restore link_free pointer values.
64 #define ZS_HANDLE_SIZE (sizeof(unsigned long))
67 * Object location (<PFN>, <obj_idx>) is encoded as
68 * a single (unsigned long) handle value.
70 * Note that object index <obj_idx> starts from 0.
72 * This is made more complicated by various memory models and PAE.
75 #ifndef MAX_POSSIBLE_PHYSMEM_BITS
76 #ifdef MAX_PHYSMEM_BITS
77 #define MAX_POSSIBLE_PHYSMEM_BITS MAX_PHYSMEM_BITS
80 * If this definition of MAX_PHYSMEM_BITS is used, OBJ_INDEX_BITS will just
83 #define MAX_POSSIBLE_PHYSMEM_BITS BITS_PER_LONG
87 #define _PFN_BITS (MAX_POSSIBLE_PHYSMEM_BITS - PAGE_SHIFT)
90 * Head in allocated object should have OBJ_ALLOCATED_TAG
91 * to identify the object was allocated or not.
92 * It's okay to add the status bit in the least bit because
93 * header keeps handle which is 4byte-aligned address so we
94 * have room for two bit at least.
96 #define OBJ_ALLOCATED_TAG 1
98 #define OBJ_TAG_BITS 1
99 #define OBJ_TAG_MASK OBJ_ALLOCATED_TAG
101 #define OBJ_INDEX_BITS (BITS_PER_LONG - _PFN_BITS)
102 #define OBJ_INDEX_MASK ((_AC(1, UL) << OBJ_INDEX_BITS) - 1)
105 #define FULLNESS_BITS 4
107 #define MAGIC_VAL_BITS 8
109 #define ZS_MAX_PAGES_PER_ZSPAGE (_AC(CONFIG_ZSMALLOC_CHAIN_SIZE, UL))
111 /* ZS_MIN_ALLOC_SIZE must be multiple of ZS_ALIGN */
112 #define ZS_MIN_ALLOC_SIZE \
113 MAX(32, (ZS_MAX_PAGES_PER_ZSPAGE << PAGE_SHIFT >> OBJ_INDEX_BITS))
114 /* each chunk includes extra space to keep handle */
115 #define ZS_MAX_ALLOC_SIZE PAGE_SIZE
118 * On systems with 4K page size, this gives 255 size classes! There is a
120 * - Large number of size classes is potentially wasteful as free page are
121 * spread across these classes
122 * - Small number of size classes causes large internal fragmentation
123 * - Probably its better to use specific size classes (empirically
124 * determined). NOTE: all those class sizes must be set as multiple of
125 * ZS_ALIGN to make sure link_free itself never has to span 2 pages.
127 * ZS_MIN_ALLOC_SIZE and ZS_SIZE_CLASS_DELTA must be multiple of ZS_ALIGN
130 #define ZS_SIZE_CLASS_DELTA (PAGE_SIZE >> CLASS_BITS)
131 #define ZS_SIZE_CLASSES (DIV_ROUND_UP(ZS_MAX_ALLOC_SIZE - ZS_MIN_ALLOC_SIZE, \
132 ZS_SIZE_CLASS_DELTA) + 1)
135 * Pages are distinguished by the ratio of used memory (that is the ratio
136 * of ->inuse objects to all objects that page can store). For example,
137 * INUSE_RATIO_10 means that the ratio of used objects is > 0% and <= 10%.
139 * The number of fullness groups is not random. It allows us to keep
140 * difference between the least busy page in the group (minimum permitted
141 * number of ->inuse objects) and the most busy page (maximum permitted
142 * number of ->inuse objects) at a reasonable value.
144 enum fullness_group
{
147 /* NOTE: 8 more fullness groups here */
148 ZS_INUSE_RATIO_99
= 10,
153 enum class_stat_type
{
154 /* NOTE: stats for 12 fullness groups here: from inuse 0 to 100 */
155 ZS_OBJS_ALLOCATED
= NR_FULLNESS_GROUPS
,
160 struct zs_size_stat
{
161 unsigned long objs
[NR_CLASS_STAT_TYPES
];
164 #ifdef CONFIG_ZSMALLOC_STAT
165 static struct dentry
*zs_stat_root
;
168 static size_t huge_class_size
;
172 struct list_head fullness_list
[NR_FULLNESS_GROUPS
];
174 * Size of objects stored in this class. Must be multiple
179 /* Number of PAGE_SIZE sized pages to combine to form a 'zspage' */
180 int pages_per_zspage
;
183 struct zs_size_stat stats
;
187 * Placed within free objects to form a singly linked list.
188 * For every zspage, zspage->freeobj gives head of this list.
190 * This must be power of 2 and less than or equal to ZS_ALIGN
196 * It's valid for non-allocated object
200 * Handle of allocated object.
202 unsigned long handle
;
209 struct size_class
*size_class
[ZS_SIZE_CLASSES
];
210 struct kmem_cache
*handle_cachep
;
211 struct kmem_cache
*zspage_cachep
;
213 atomic_long_t pages_allocated
;
215 struct zs_pool_stats stats
;
217 /* Compact classes */
218 struct shrinker
*shrinker
;
220 #ifdef CONFIG_ZSMALLOC_STAT
221 struct dentry
*stat_dentry
;
223 #ifdef CONFIG_COMPACTION
224 struct work_struct free_work
;
226 /* protect page/zspage migration */
227 rwlock_t migrate_lock
;
228 atomic_t compaction_in_progress
;
231 static inline void zpdesc_set_first(struct zpdesc
*zpdesc
)
233 SetPagePrivate(zpdesc_page(zpdesc
));
236 static inline void zpdesc_inc_zone_page_state(struct zpdesc
*zpdesc
)
238 inc_zone_page_state(zpdesc_page(zpdesc
), NR_ZSPAGES
);
241 static inline void zpdesc_dec_zone_page_state(struct zpdesc
*zpdesc
)
243 dec_zone_page_state(zpdesc_page(zpdesc
), NR_ZSPAGES
);
246 static inline struct zpdesc
*alloc_zpdesc(gfp_t gfp
)
248 struct page
*page
= alloc_page(gfp
);
250 return page_zpdesc(page
);
253 static inline void free_zpdesc(struct zpdesc
*zpdesc
)
255 struct page
*page
= zpdesc_page(zpdesc
);
262 unsigned int huge
:HUGE_BITS
;
263 unsigned int fullness
:FULLNESS_BITS
;
264 unsigned int class:CLASS_BITS
+ 1;
265 unsigned int magic
:MAGIC_VAL_BITS
;
268 unsigned int freeobj
;
269 struct zpdesc
*first_zpdesc
;
270 struct list_head list
; /* fullness list */
271 struct zs_pool
*pool
;
275 struct mapping_area
{
277 char *vm_buf
; /* copy buffer for objects that span pages */
278 char *vm_addr
; /* address of kmap_local_page()'ed pages */
279 enum zs_mapmode vm_mm
; /* mapping mode */
282 /* huge object: pages_per_zspage == 1 && maxobj_per_zspage == 1 */
283 static void SetZsHugePage(struct zspage
*zspage
)
288 static bool ZsHugePage(struct zspage
*zspage
)
293 static void migrate_lock_init(struct zspage
*zspage
);
294 static void migrate_read_lock(struct zspage
*zspage
);
295 static void migrate_read_unlock(struct zspage
*zspage
);
296 static void migrate_write_lock(struct zspage
*zspage
);
297 static void migrate_write_unlock(struct zspage
*zspage
);
299 #ifdef CONFIG_COMPACTION
300 static void kick_deferred_free(struct zs_pool
*pool
);
301 static void init_deferred_free(struct zs_pool
*pool
);
302 static void SetZsPageMovable(struct zs_pool
*pool
, struct zspage
*zspage
);
304 static void kick_deferred_free(struct zs_pool
*pool
) {}
305 static void init_deferred_free(struct zs_pool
*pool
) {}
306 static void SetZsPageMovable(struct zs_pool
*pool
, struct zspage
*zspage
) {}
309 static int create_cache(struct zs_pool
*pool
)
313 name
= kasprintf(GFP_KERNEL
, "zs_handle-%s", pool
->name
);
316 pool
->handle_cachep
= kmem_cache_create(name
, ZS_HANDLE_SIZE
,
319 if (!pool
->handle_cachep
)
322 name
= kasprintf(GFP_KERNEL
, "zspage-%s", pool
->name
);
325 pool
->zspage_cachep
= kmem_cache_create(name
, sizeof(struct zspage
),
328 if (!pool
->zspage_cachep
) {
329 kmem_cache_destroy(pool
->handle_cachep
);
330 pool
->handle_cachep
= NULL
;
337 static void destroy_cache(struct zs_pool
*pool
)
339 kmem_cache_destroy(pool
->handle_cachep
);
340 kmem_cache_destroy(pool
->zspage_cachep
);
343 static unsigned long cache_alloc_handle(struct zs_pool
*pool
, gfp_t gfp
)
345 return (unsigned long)kmem_cache_alloc(pool
->handle_cachep
,
346 gfp
& ~(__GFP_HIGHMEM
|__GFP_MOVABLE
));
349 static void cache_free_handle(struct zs_pool
*pool
, unsigned long handle
)
351 kmem_cache_free(pool
->handle_cachep
, (void *)handle
);
354 static struct zspage
*cache_alloc_zspage(struct zs_pool
*pool
, gfp_t flags
)
356 return kmem_cache_zalloc(pool
->zspage_cachep
,
357 flags
& ~(__GFP_HIGHMEM
|__GFP_MOVABLE
));
360 static void cache_free_zspage(struct zs_pool
*pool
, struct zspage
*zspage
)
362 kmem_cache_free(pool
->zspage_cachep
, zspage
);
365 /* class->lock(which owns the handle) synchronizes races */
366 static void record_obj(unsigned long handle
, unsigned long obj
)
368 *(unsigned long *)handle
= obj
;
375 static void *zs_zpool_create(const char *name
, gfp_t gfp
)
378 * Ignore global gfp flags: zs_malloc() may be invoked from
379 * different contexts and its caller must provide a valid
382 return zs_create_pool(name
);
385 static void zs_zpool_destroy(void *pool
)
387 zs_destroy_pool(pool
);
390 static int zs_zpool_malloc(void *pool
, size_t size
, gfp_t gfp
,
391 unsigned long *handle
)
393 *handle
= zs_malloc(pool
, size
, gfp
);
395 if (IS_ERR_VALUE(*handle
))
396 return PTR_ERR((void *)*handle
);
399 static void zs_zpool_free(void *pool
, unsigned long handle
)
401 zs_free(pool
, handle
);
404 static void *zs_zpool_map(void *pool
, unsigned long handle
,
405 enum zpool_mapmode mm
)
407 enum zs_mapmode zs_mm
;
422 return zs_map_object(pool
, handle
, zs_mm
);
424 static void zs_zpool_unmap(void *pool
, unsigned long handle
)
426 zs_unmap_object(pool
, handle
);
429 static u64
zs_zpool_total_pages(void *pool
)
431 return zs_get_total_pages(pool
);
434 static struct zpool_driver zs_zpool_driver
= {
436 .owner
= THIS_MODULE
,
437 .create
= zs_zpool_create
,
438 .destroy
= zs_zpool_destroy
,
439 .malloc_support_movable
= true,
440 .malloc
= zs_zpool_malloc
,
441 .free
= zs_zpool_free
,
443 .unmap
= zs_zpool_unmap
,
444 .total_pages
= zs_zpool_total_pages
,
447 MODULE_ALIAS("zpool-zsmalloc");
448 #endif /* CONFIG_ZPOOL */
450 /* per-cpu VM mapping areas for zspage accesses that cross page boundaries */
451 static DEFINE_PER_CPU(struct mapping_area
, zs_map_area
) = {
452 .lock
= INIT_LOCAL_LOCK(lock
),
455 static inline bool __maybe_unused
is_first_zpdesc(struct zpdesc
*zpdesc
)
457 return PagePrivate(zpdesc_page(zpdesc
));
460 /* Protected by class->lock */
461 static inline int get_zspage_inuse(struct zspage
*zspage
)
463 return zspage
->inuse
;
466 static inline void mod_zspage_inuse(struct zspage
*zspage
, int val
)
468 zspage
->inuse
+= val
;
471 static struct zpdesc
*get_first_zpdesc(struct zspage
*zspage
)
473 struct zpdesc
*first_zpdesc
= zspage
->first_zpdesc
;
475 VM_BUG_ON_PAGE(!is_first_zpdesc(first_zpdesc
), zpdesc_page(first_zpdesc
));
479 #define FIRST_OBJ_PAGE_TYPE_MASK 0xffffff
481 static inline unsigned int get_first_obj_offset(struct zpdesc
*zpdesc
)
483 VM_WARN_ON_ONCE(!PageZsmalloc(zpdesc_page(zpdesc
)));
484 return zpdesc
->first_obj_offset
& FIRST_OBJ_PAGE_TYPE_MASK
;
487 static inline void set_first_obj_offset(struct zpdesc
*zpdesc
, unsigned int offset
)
489 /* With 24 bits available, we can support offsets into 16 MiB pages. */
490 BUILD_BUG_ON(PAGE_SIZE
> SZ_16M
);
491 VM_WARN_ON_ONCE(!PageZsmalloc(zpdesc_page(zpdesc
)));
492 VM_WARN_ON_ONCE(offset
& ~FIRST_OBJ_PAGE_TYPE_MASK
);
493 zpdesc
->first_obj_offset
&= ~FIRST_OBJ_PAGE_TYPE_MASK
;
494 zpdesc
->first_obj_offset
|= offset
& FIRST_OBJ_PAGE_TYPE_MASK
;
497 static inline unsigned int get_freeobj(struct zspage
*zspage
)
499 return zspage
->freeobj
;
502 static inline void set_freeobj(struct zspage
*zspage
, unsigned int obj
)
504 zspage
->freeobj
= obj
;
507 static struct size_class
*zspage_class(struct zs_pool
*pool
,
508 struct zspage
*zspage
)
510 return pool
->size_class
[zspage
->class];
514 * zsmalloc divides the pool into various size classes where each
515 * class maintains a list of zspages where each zspage is divided
516 * into equal sized chunks. Each allocation falls into one of these
517 * classes depending on its size. This function returns index of the
518 * size class which has chunk size big enough to hold the given size.
520 static int get_size_class_index(int size
)
524 if (likely(size
> ZS_MIN_ALLOC_SIZE
))
525 idx
= DIV_ROUND_UP(size
- ZS_MIN_ALLOC_SIZE
,
526 ZS_SIZE_CLASS_DELTA
);
528 return min_t(int, ZS_SIZE_CLASSES
- 1, idx
);
531 static inline void class_stat_add(struct size_class
*class, int type
,
534 class->stats
.objs
[type
] += cnt
;
537 static inline void class_stat_sub(struct size_class
*class, int type
,
540 class->stats
.objs
[type
] -= cnt
;
543 static inline unsigned long class_stat_read(struct size_class
*class, int type
)
545 return class->stats
.objs
[type
];
548 #ifdef CONFIG_ZSMALLOC_STAT
550 static void __init
zs_stat_init(void)
552 if (!debugfs_initialized()) {
553 pr_warn("debugfs not available, stat dir not created\n");
557 zs_stat_root
= debugfs_create_dir("zsmalloc", NULL
);
560 static void __exit
zs_stat_exit(void)
562 debugfs_remove_recursive(zs_stat_root
);
565 static unsigned long zs_can_compact(struct size_class
*class);
567 static int zs_stats_size_show(struct seq_file
*s
, void *v
)
570 struct zs_pool
*pool
= s
->private;
571 struct size_class
*class;
573 unsigned long obj_allocated
, obj_used
, pages_used
, freeable
;
574 unsigned long total_objs
= 0, total_used_objs
= 0, total_pages
= 0;
575 unsigned long total_freeable
= 0;
576 unsigned long inuse_totals
[NR_FULLNESS_GROUPS
] = {0, };
578 seq_printf(s
, " %5s %5s %9s %9s %9s %9s %9s %9s %9s %9s %9s %9s %9s %13s %10s %10s %16s %8s\n",
579 "class", "size", "10%", "20%", "30%", "40%",
580 "50%", "60%", "70%", "80%", "90%", "99%", "100%",
581 "obj_allocated", "obj_used", "pages_used",
582 "pages_per_zspage", "freeable");
584 for (i
= 0; i
< ZS_SIZE_CLASSES
; i
++) {
586 class = pool
->size_class
[i
];
588 if (class->index
!= i
)
591 spin_lock(&class->lock
);
593 seq_printf(s
, " %5u %5u ", i
, class->size
);
594 for (fg
= ZS_INUSE_RATIO_10
; fg
< NR_FULLNESS_GROUPS
; fg
++) {
595 inuse_totals
[fg
] += class_stat_read(class, fg
);
596 seq_printf(s
, "%9lu ", class_stat_read(class, fg
));
599 obj_allocated
= class_stat_read(class, ZS_OBJS_ALLOCATED
);
600 obj_used
= class_stat_read(class, ZS_OBJS_INUSE
);
601 freeable
= zs_can_compact(class);
602 spin_unlock(&class->lock
);
604 objs_per_zspage
= class->objs_per_zspage
;
605 pages_used
= obj_allocated
/ objs_per_zspage
*
606 class->pages_per_zspage
;
608 seq_printf(s
, "%13lu %10lu %10lu %16d %8lu\n",
609 obj_allocated
, obj_used
, pages_used
,
610 class->pages_per_zspage
, freeable
);
612 total_objs
+= obj_allocated
;
613 total_used_objs
+= obj_used
;
614 total_pages
+= pages_used
;
615 total_freeable
+= freeable
;
619 seq_printf(s
, " %5s %5s ", "Total", "");
621 for (fg
= ZS_INUSE_RATIO_10
; fg
< NR_FULLNESS_GROUPS
; fg
++)
622 seq_printf(s
, "%9lu ", inuse_totals
[fg
]);
624 seq_printf(s
, "%13lu %10lu %10lu %16s %8lu\n",
625 total_objs
, total_used_objs
, total_pages
, "",
630 DEFINE_SHOW_ATTRIBUTE(zs_stats_size
);
632 static void zs_pool_stat_create(struct zs_pool
*pool
, const char *name
)
635 pr_warn("no root stat dir, not creating <%s> stat dir\n", name
);
639 pool
->stat_dentry
= debugfs_create_dir(name
, zs_stat_root
);
641 debugfs_create_file("classes", S_IFREG
| 0444, pool
->stat_dentry
, pool
,
642 &zs_stats_size_fops
);
645 static void zs_pool_stat_destroy(struct zs_pool
*pool
)
647 debugfs_remove_recursive(pool
->stat_dentry
);
650 #else /* CONFIG_ZSMALLOC_STAT */
651 static void __init
zs_stat_init(void)
655 static void __exit
zs_stat_exit(void)
659 static inline void zs_pool_stat_create(struct zs_pool
*pool
, const char *name
)
663 static inline void zs_pool_stat_destroy(struct zs_pool
*pool
)
670 * For each size class, zspages are divided into different groups
671 * depending on their usage ratio. This function returns fullness
672 * status of the given page.
674 static int get_fullness_group(struct size_class
*class, struct zspage
*zspage
)
676 int inuse
, objs_per_zspage
, ratio
;
678 inuse
= get_zspage_inuse(zspage
);
679 objs_per_zspage
= class->objs_per_zspage
;
682 return ZS_INUSE_RATIO_0
;
683 if (inuse
== objs_per_zspage
)
684 return ZS_INUSE_RATIO_100
;
686 ratio
= 100 * inuse
/ objs_per_zspage
;
688 * Take integer division into consideration: a page with one inuse
689 * object out of 127 possible, will end up having 0 usage ratio,
690 * which is wrong as it belongs in ZS_INUSE_RATIO_10 fullness group.
692 return ratio
/ 10 + 1;
696 * Each size class maintains various freelists and zspages are assigned
697 * to one of these freelists based on the number of live objects they
698 * have. This functions inserts the given zspage into the freelist
699 * identified by <class, fullness_group>.
701 static void insert_zspage(struct size_class
*class,
702 struct zspage
*zspage
,
705 class_stat_add(class, fullness
, 1);
706 list_add(&zspage
->list
, &class->fullness_list
[fullness
]);
707 zspage
->fullness
= fullness
;
711 * This function removes the given zspage from the freelist identified
712 * by <class, fullness_group>.
714 static void remove_zspage(struct size_class
*class, struct zspage
*zspage
)
716 int fullness
= zspage
->fullness
;
718 VM_BUG_ON(list_empty(&class->fullness_list
[fullness
]));
720 list_del_init(&zspage
->list
);
721 class_stat_sub(class, fullness
, 1);
725 * Each size class maintains zspages in different fullness groups depending
726 * on the number of live objects they contain. When allocating or freeing
727 * objects, the fullness status of the page can change, for instance, from
728 * INUSE_RATIO_80 to INUSE_RATIO_70 when freeing an object. This function
729 * checks if such a status change has occurred for the given page and
730 * accordingly moves the page from the list of the old fullness group to that
731 * of the new fullness group.
733 static int fix_fullness_group(struct size_class
*class, struct zspage
*zspage
)
737 newfg
= get_fullness_group(class, zspage
);
738 if (newfg
== zspage
->fullness
)
741 remove_zspage(class, zspage
);
742 insert_zspage(class, zspage
, newfg
);
747 static struct zspage
*get_zspage(struct zpdesc
*zpdesc
)
749 struct zspage
*zspage
= zpdesc
->zspage
;
751 BUG_ON(zspage
->magic
!= ZSPAGE_MAGIC
);
755 static struct zpdesc
*get_next_zpdesc(struct zpdesc
*zpdesc
)
757 struct zspage
*zspage
= get_zspage(zpdesc
);
759 if (unlikely(ZsHugePage(zspage
)))
766 * obj_to_location - get (<zpdesc>, <obj_idx>) from encoded object value
767 * @obj: the encoded object value
768 * @zpdesc: zpdesc object resides in zspage
769 * @obj_idx: object index
771 static void obj_to_location(unsigned long obj
, struct zpdesc
**zpdesc
,
772 unsigned int *obj_idx
)
774 *zpdesc
= pfn_zpdesc(obj
>> OBJ_INDEX_BITS
);
775 *obj_idx
= (obj
& OBJ_INDEX_MASK
);
778 static void obj_to_zpdesc(unsigned long obj
, struct zpdesc
**zpdesc
)
780 *zpdesc
= pfn_zpdesc(obj
>> OBJ_INDEX_BITS
);
784 * location_to_obj - get obj value encoded from (<zpdesc>, <obj_idx>)
785 * @zpdesc: zpdesc object resides in zspage
786 * @obj_idx: object index
788 static unsigned long location_to_obj(struct zpdesc
*zpdesc
, unsigned int obj_idx
)
792 obj
= zpdesc_pfn(zpdesc
) << OBJ_INDEX_BITS
;
793 obj
|= obj_idx
& OBJ_INDEX_MASK
;
798 static unsigned long handle_to_obj(unsigned long handle
)
800 return *(unsigned long *)handle
;
803 static inline bool obj_allocated(struct zpdesc
*zpdesc
, void *obj
,
804 unsigned long *phandle
)
806 unsigned long handle
;
807 struct zspage
*zspage
= get_zspage(zpdesc
);
809 if (unlikely(ZsHugePage(zspage
))) {
810 VM_BUG_ON_PAGE(!is_first_zpdesc(zpdesc
), zpdesc_page(zpdesc
));
811 handle
= zpdesc
->handle
;
813 handle
= *(unsigned long *)obj
;
815 if (!(handle
& OBJ_ALLOCATED_TAG
))
818 /* Clear all tags before returning the handle */
819 *phandle
= handle
& ~OBJ_TAG_MASK
;
823 static void reset_zpdesc(struct zpdesc
*zpdesc
)
825 struct page
*page
= zpdesc_page(zpdesc
);
827 __ClearPageMovable(page
);
828 ClearPagePrivate(page
);
829 zpdesc
->zspage
= NULL
;
831 __ClearPageZsmalloc(page
);
834 static int trylock_zspage(struct zspage
*zspage
)
836 struct zpdesc
*cursor
, *fail
;
838 for (cursor
= get_first_zpdesc(zspage
); cursor
!= NULL
; cursor
=
839 get_next_zpdesc(cursor
)) {
840 if (!zpdesc_trylock(cursor
)) {
848 for (cursor
= get_first_zpdesc(zspage
); cursor
!= fail
; cursor
=
849 get_next_zpdesc(cursor
))
850 zpdesc_unlock(cursor
);
855 static void __free_zspage(struct zs_pool
*pool
, struct size_class
*class,
856 struct zspage
*zspage
)
858 struct zpdesc
*zpdesc
, *next
;
860 assert_spin_locked(&class->lock
);
862 VM_BUG_ON(get_zspage_inuse(zspage
));
863 VM_BUG_ON(zspage
->fullness
!= ZS_INUSE_RATIO_0
);
865 next
= zpdesc
= get_first_zpdesc(zspage
);
867 VM_BUG_ON_PAGE(!zpdesc_is_locked(zpdesc
), zpdesc_page(zpdesc
));
868 next
= get_next_zpdesc(zpdesc
);
869 reset_zpdesc(zpdesc
);
870 zpdesc_unlock(zpdesc
);
871 zpdesc_dec_zone_page_state(zpdesc
);
874 } while (zpdesc
!= NULL
);
876 cache_free_zspage(pool
, zspage
);
878 class_stat_sub(class, ZS_OBJS_ALLOCATED
, class->objs_per_zspage
);
879 atomic_long_sub(class->pages_per_zspage
, &pool
->pages_allocated
);
882 static void free_zspage(struct zs_pool
*pool
, struct size_class
*class,
883 struct zspage
*zspage
)
885 VM_BUG_ON(get_zspage_inuse(zspage
));
886 VM_BUG_ON(list_empty(&zspage
->list
));
889 * Since zs_free couldn't be sleepable, this function cannot call
890 * lock_page. The page locks trylock_zspage got will be released
893 if (!trylock_zspage(zspage
)) {
894 kick_deferred_free(pool
);
898 remove_zspage(class, zspage
);
899 __free_zspage(pool
, class, zspage
);
902 /* Initialize a newly allocated zspage */
903 static void init_zspage(struct size_class
*class, struct zspage
*zspage
)
905 unsigned int freeobj
= 1;
906 unsigned long off
= 0;
907 struct zpdesc
*zpdesc
= get_first_zpdesc(zspage
);
910 struct zpdesc
*next_zpdesc
;
911 struct link_free
*link
;
914 set_first_obj_offset(zpdesc
, off
);
916 vaddr
= kmap_local_zpdesc(zpdesc
);
917 link
= (struct link_free
*)vaddr
+ off
/ sizeof(*link
);
919 while ((off
+= class->size
) < PAGE_SIZE
) {
920 link
->next
= freeobj
++ << OBJ_TAG_BITS
;
921 link
+= class->size
/ sizeof(*link
);
925 * We now come to the last (full or partial) object on this
926 * page, which must point to the first object on the next
929 next_zpdesc
= get_next_zpdesc(zpdesc
);
931 link
->next
= freeobj
++ << OBJ_TAG_BITS
;
934 * Reset OBJ_TAG_BITS bit to last link to tell
935 * whether it's allocated object or not.
937 link
->next
= -1UL << OBJ_TAG_BITS
;
940 zpdesc
= next_zpdesc
;
944 set_freeobj(zspage
, 0);
947 static void create_page_chain(struct size_class
*class, struct zspage
*zspage
,
948 struct zpdesc
*zpdescs
[])
951 struct zpdesc
*zpdesc
;
952 struct zpdesc
*prev_zpdesc
= NULL
;
953 int nr_zpdescs
= class->pages_per_zspage
;
956 * Allocate individual pages and link them together as:
957 * 1. all pages are linked together using zpdesc->next
958 * 2. each sub-page point to zspage using zpdesc->zspage
960 * we set PG_private to identify the first zpdesc (i.e. no other zpdesc
961 * has this flag set).
963 for (i
= 0; i
< nr_zpdescs
; i
++) {
965 zpdesc
->zspage
= zspage
;
968 zspage
->first_zpdesc
= zpdesc
;
969 zpdesc_set_first(zpdesc
);
970 if (unlikely(class->objs_per_zspage
== 1 &&
971 class->pages_per_zspage
== 1))
972 SetZsHugePage(zspage
);
974 prev_zpdesc
->next
= zpdesc
;
976 prev_zpdesc
= zpdesc
;
981 * Allocate a zspage for the given size class
983 static struct zspage
*alloc_zspage(struct zs_pool
*pool
,
984 struct size_class
*class,
988 struct zpdesc
*zpdescs
[ZS_MAX_PAGES_PER_ZSPAGE
];
989 struct zspage
*zspage
= cache_alloc_zspage(pool
, gfp
);
994 zspage
->magic
= ZSPAGE_MAGIC
;
995 migrate_lock_init(zspage
);
997 for (i
= 0; i
< class->pages_per_zspage
; i
++) {
998 struct zpdesc
*zpdesc
;
1000 zpdesc
= alloc_zpdesc(gfp
);
1003 zpdesc_dec_zone_page_state(zpdescs
[i
]);
1004 __zpdesc_clear_zsmalloc(zpdescs
[i
]);
1005 free_zpdesc(zpdescs
[i
]);
1007 cache_free_zspage(pool
, zspage
);
1010 __zpdesc_set_zsmalloc(zpdesc
);
1012 zpdesc_inc_zone_page_state(zpdesc
);
1013 zpdescs
[i
] = zpdesc
;
1016 create_page_chain(class, zspage
, zpdescs
);
1017 init_zspage(class, zspage
);
1018 zspage
->pool
= pool
;
1019 zspage
->class = class->index
;
1024 static struct zspage
*find_get_zspage(struct size_class
*class)
1027 struct zspage
*zspage
;
1029 for (i
= ZS_INUSE_RATIO_99
; i
>= ZS_INUSE_RATIO_0
; i
--) {
1030 zspage
= list_first_entry_or_null(&class->fullness_list
[i
],
1031 struct zspage
, list
);
1039 static inline int __zs_cpu_up(struct mapping_area
*area
)
1042 * Make sure we don't leak memory if a cpu UP notification
1043 * and zs_init() race and both call zs_cpu_up() on the same cpu
1047 area
->vm_buf
= kmalloc(ZS_MAX_ALLOC_SIZE
, GFP_KERNEL
);
1053 static inline void __zs_cpu_down(struct mapping_area
*area
)
1055 kfree(area
->vm_buf
);
1056 area
->vm_buf
= NULL
;
1059 static void *__zs_map_object(struct mapping_area
*area
,
1060 struct zpdesc
*zpdescs
[2], int off
, int size
)
1063 char *buf
= area
->vm_buf
;
1065 /* disable page faults to match kmap_local_page() return conditions */
1066 pagefault_disable();
1068 /* no read fastpath */
1069 if (area
->vm_mm
== ZS_MM_WO
)
1072 sizes
[0] = PAGE_SIZE
- off
;
1073 sizes
[1] = size
- sizes
[0];
1075 /* copy object to per-cpu buffer */
1076 memcpy_from_page(buf
, zpdesc_page(zpdescs
[0]), off
, sizes
[0]);
1077 memcpy_from_page(buf
+ sizes
[0], zpdesc_page(zpdescs
[1]), 0, sizes
[1]);
1079 return area
->vm_buf
;
1082 static void __zs_unmap_object(struct mapping_area
*area
,
1083 struct zpdesc
*zpdescs
[2], int off
, int size
)
1088 /* no write fastpath */
1089 if (area
->vm_mm
== ZS_MM_RO
)
1093 buf
= buf
+ ZS_HANDLE_SIZE
;
1094 size
-= ZS_HANDLE_SIZE
;
1095 off
+= ZS_HANDLE_SIZE
;
1097 sizes
[0] = PAGE_SIZE
- off
;
1098 sizes
[1] = size
- sizes
[0];
1100 /* copy per-cpu buffer to object */
1101 memcpy_to_page(zpdesc_page(zpdescs
[0]), off
, buf
, sizes
[0]);
1102 memcpy_to_page(zpdesc_page(zpdescs
[1]), 0, buf
+ sizes
[0], sizes
[1]);
1105 /* enable page faults to match kunmap_local() return conditions */
1109 static int zs_cpu_prepare(unsigned int cpu
)
1111 struct mapping_area
*area
;
1113 area
= &per_cpu(zs_map_area
, cpu
);
1114 return __zs_cpu_up(area
);
1117 static int zs_cpu_dead(unsigned int cpu
)
1119 struct mapping_area
*area
;
1121 area
= &per_cpu(zs_map_area
, cpu
);
1122 __zs_cpu_down(area
);
1126 static bool can_merge(struct size_class
*prev
, int pages_per_zspage
,
1127 int objs_per_zspage
)
1129 if (prev
->pages_per_zspage
== pages_per_zspage
&&
1130 prev
->objs_per_zspage
== objs_per_zspage
)
1136 static bool zspage_full(struct size_class
*class, struct zspage
*zspage
)
1138 return get_zspage_inuse(zspage
) == class->objs_per_zspage
;
1141 static bool zspage_empty(struct zspage
*zspage
)
1143 return get_zspage_inuse(zspage
) == 0;
1147 * zs_lookup_class_index() - Returns index of the zsmalloc &size_class
1148 * that hold objects of the provided size.
1149 * @pool: zsmalloc pool to use
1150 * @size: object size
1152 * Context: Any context.
1154 * Return: the index of the zsmalloc &size_class that hold objects of the
1157 unsigned int zs_lookup_class_index(struct zs_pool
*pool
, unsigned int size
)
1159 struct size_class
*class;
1161 class = pool
->size_class
[get_size_class_index(size
)];
1163 return class->index
;
1165 EXPORT_SYMBOL_GPL(zs_lookup_class_index
);
1167 unsigned long zs_get_total_pages(struct zs_pool
*pool
)
1169 return atomic_long_read(&pool
->pages_allocated
);
1171 EXPORT_SYMBOL_GPL(zs_get_total_pages
);
1174 * zs_map_object - get address of allocated object from handle.
1175 * @pool: pool from which the object was allocated
1176 * @handle: handle returned from zs_malloc
1177 * @mm: mapping mode to use
1179 * Before using an object allocated from zs_malloc, it must be mapped using
1180 * this function. When done with the object, it must be unmapped using
1183 * Only one object can be mapped per cpu at a time. There is no protection
1184 * against nested mappings.
1186 * This function returns with preemption and page faults disabled.
1188 void *zs_map_object(struct zs_pool
*pool
, unsigned long handle
,
1191 struct zspage
*zspage
;
1192 struct zpdesc
*zpdesc
;
1193 unsigned long obj
, off
;
1194 unsigned int obj_idx
;
1196 struct size_class
*class;
1197 struct mapping_area
*area
;
1198 struct zpdesc
*zpdescs
[2];
1202 * Because we use per-cpu mapping areas shared among the
1203 * pools/users, we can't allow mapping in interrupt context
1204 * because it can corrupt another users mappings.
1206 BUG_ON(in_interrupt());
1208 /* It guarantees it can get zspage from handle safely */
1209 read_lock(&pool
->migrate_lock
);
1210 obj
= handle_to_obj(handle
);
1211 obj_to_location(obj
, &zpdesc
, &obj_idx
);
1212 zspage
= get_zspage(zpdesc
);
1215 * migration cannot move any zpages in this zspage. Here, class->lock
1216 * is too heavy since callers would take some time until they calls
1217 * zs_unmap_object API so delegate the locking from class to zspage
1218 * which is smaller granularity.
1220 migrate_read_lock(zspage
);
1221 read_unlock(&pool
->migrate_lock
);
1223 class = zspage_class(pool
, zspage
);
1224 off
= offset_in_page(class->size
* obj_idx
);
1226 local_lock(&zs_map_area
.lock
);
1227 area
= this_cpu_ptr(&zs_map_area
);
1229 if (off
+ class->size
<= PAGE_SIZE
) {
1230 /* this object is contained entirely within a page */
1231 area
->vm_addr
= kmap_local_zpdesc(zpdesc
);
1232 ret
= area
->vm_addr
+ off
;
1236 /* this object spans two pages */
1237 zpdescs
[0] = zpdesc
;
1238 zpdescs
[1] = get_next_zpdesc(zpdesc
);
1239 BUG_ON(!zpdescs
[1]);
1241 ret
= __zs_map_object(area
, zpdescs
, off
, class->size
);
1243 if (likely(!ZsHugePage(zspage
)))
1244 ret
+= ZS_HANDLE_SIZE
;
1248 EXPORT_SYMBOL_GPL(zs_map_object
);
1250 void zs_unmap_object(struct zs_pool
*pool
, unsigned long handle
)
1252 struct zspage
*zspage
;
1253 struct zpdesc
*zpdesc
;
1254 unsigned long obj
, off
;
1255 unsigned int obj_idx
;
1257 struct size_class
*class;
1258 struct mapping_area
*area
;
1260 obj
= handle_to_obj(handle
);
1261 obj_to_location(obj
, &zpdesc
, &obj_idx
);
1262 zspage
= get_zspage(zpdesc
);
1263 class = zspage_class(pool
, zspage
);
1264 off
= offset_in_page(class->size
* obj_idx
);
1266 area
= this_cpu_ptr(&zs_map_area
);
1267 if (off
+ class->size
<= PAGE_SIZE
)
1268 kunmap_local(area
->vm_addr
);
1270 struct zpdesc
*zpdescs
[2];
1272 zpdescs
[0] = zpdesc
;
1273 zpdescs
[1] = get_next_zpdesc(zpdesc
);
1274 BUG_ON(!zpdescs
[1]);
1276 __zs_unmap_object(area
, zpdescs
, off
, class->size
);
1278 local_unlock(&zs_map_area
.lock
);
1280 migrate_read_unlock(zspage
);
1282 EXPORT_SYMBOL_GPL(zs_unmap_object
);
1285 * zs_huge_class_size() - Returns the size (in bytes) of the first huge
1286 * zsmalloc &size_class.
1287 * @pool: zsmalloc pool to use
1289 * The function returns the size of the first huge class - any object of equal
1290 * or bigger size will be stored in zspage consisting of a single physical
1293 * Context: Any context.
1295 * Return: the size (in bytes) of the first huge zsmalloc &size_class.
1297 size_t zs_huge_class_size(struct zs_pool
*pool
)
1299 return huge_class_size
;
1301 EXPORT_SYMBOL_GPL(zs_huge_class_size
);
1303 static unsigned long obj_malloc(struct zs_pool
*pool
,
1304 struct zspage
*zspage
, unsigned long handle
)
1306 int i
, nr_zpdesc
, offset
;
1308 struct link_free
*link
;
1309 struct size_class
*class;
1311 struct zpdesc
*m_zpdesc
;
1312 unsigned long m_offset
;
1315 class = pool
->size_class
[zspage
->class];
1316 obj
= get_freeobj(zspage
);
1318 offset
= obj
* class->size
;
1319 nr_zpdesc
= offset
>> PAGE_SHIFT
;
1320 m_offset
= offset_in_page(offset
);
1321 m_zpdesc
= get_first_zpdesc(zspage
);
1323 for (i
= 0; i
< nr_zpdesc
; i
++)
1324 m_zpdesc
= get_next_zpdesc(m_zpdesc
);
1326 vaddr
= kmap_local_zpdesc(m_zpdesc
);
1327 link
= (struct link_free
*)vaddr
+ m_offset
/ sizeof(*link
);
1328 set_freeobj(zspage
, link
->next
>> OBJ_TAG_BITS
);
1329 if (likely(!ZsHugePage(zspage
)))
1330 /* record handle in the header of allocated chunk */
1331 link
->handle
= handle
| OBJ_ALLOCATED_TAG
;
1333 zspage
->first_zpdesc
->handle
= handle
| OBJ_ALLOCATED_TAG
;
1335 kunmap_local(vaddr
);
1336 mod_zspage_inuse(zspage
, 1);
1338 obj
= location_to_obj(m_zpdesc
, obj
);
1339 record_obj(handle
, obj
);
1346 * zs_malloc - Allocate block of given size from pool.
1347 * @pool: pool to allocate from
1348 * @size: size of block to allocate
1349 * @gfp: gfp flags when allocating object
1351 * On success, handle to the allocated object is returned,
1352 * otherwise an ERR_PTR().
1353 * Allocation requests with size > ZS_MAX_ALLOC_SIZE will fail.
1355 unsigned long zs_malloc(struct zs_pool
*pool
, size_t size
, gfp_t gfp
)
1357 unsigned long handle
;
1358 struct size_class
*class;
1360 struct zspage
*zspage
;
1362 if (unlikely(!size
))
1363 return (unsigned long)ERR_PTR(-EINVAL
);
1365 if (unlikely(size
> ZS_MAX_ALLOC_SIZE
))
1366 return (unsigned long)ERR_PTR(-ENOSPC
);
1368 handle
= cache_alloc_handle(pool
, gfp
);
1370 return (unsigned long)ERR_PTR(-ENOMEM
);
1372 /* extra space in chunk to keep the handle */
1373 size
+= ZS_HANDLE_SIZE
;
1374 class = pool
->size_class
[get_size_class_index(size
)];
1376 /* class->lock effectively protects the zpage migration */
1377 spin_lock(&class->lock
);
1378 zspage
= find_get_zspage(class);
1379 if (likely(zspage
)) {
1380 obj_malloc(pool
, zspage
, handle
);
1381 /* Now move the zspage to another fullness group, if required */
1382 fix_fullness_group(class, zspage
);
1383 class_stat_add(class, ZS_OBJS_INUSE
, 1);
1388 spin_unlock(&class->lock
);
1390 zspage
= alloc_zspage(pool
, class, gfp
);
1392 cache_free_handle(pool
, handle
);
1393 return (unsigned long)ERR_PTR(-ENOMEM
);
1396 spin_lock(&class->lock
);
1397 obj_malloc(pool
, zspage
, handle
);
1398 newfg
= get_fullness_group(class, zspage
);
1399 insert_zspage(class, zspage
, newfg
);
1400 atomic_long_add(class->pages_per_zspage
, &pool
->pages_allocated
);
1401 class_stat_add(class, ZS_OBJS_ALLOCATED
, class->objs_per_zspage
);
1402 class_stat_add(class, ZS_OBJS_INUSE
, 1);
1404 /* We completely set up zspage so mark them as movable */
1405 SetZsPageMovable(pool
, zspage
);
1407 spin_unlock(&class->lock
);
1411 EXPORT_SYMBOL_GPL(zs_malloc
);
1413 static void obj_free(int class_size
, unsigned long obj
)
1415 struct link_free
*link
;
1416 struct zspage
*zspage
;
1417 struct zpdesc
*f_zpdesc
;
1418 unsigned long f_offset
;
1419 unsigned int f_objidx
;
1423 obj_to_location(obj
, &f_zpdesc
, &f_objidx
);
1424 f_offset
= offset_in_page(class_size
* f_objidx
);
1425 zspage
= get_zspage(f_zpdesc
);
1427 vaddr
= kmap_local_zpdesc(f_zpdesc
);
1428 link
= (struct link_free
*)(vaddr
+ f_offset
);
1430 /* Insert this object in containing zspage's freelist */
1431 if (likely(!ZsHugePage(zspage
)))
1432 link
->next
= get_freeobj(zspage
) << OBJ_TAG_BITS
;
1434 f_zpdesc
->handle
= 0;
1435 set_freeobj(zspage
, f_objidx
);
1437 kunmap_local(vaddr
);
1438 mod_zspage_inuse(zspage
, -1);
1441 void zs_free(struct zs_pool
*pool
, unsigned long handle
)
1443 struct zspage
*zspage
;
1444 struct zpdesc
*f_zpdesc
;
1446 struct size_class
*class;
1449 if (IS_ERR_OR_NULL((void *)handle
))
1453 * The pool->migrate_lock protects the race with zpage's migration
1454 * so it's safe to get the page from handle.
1456 read_lock(&pool
->migrate_lock
);
1457 obj
= handle_to_obj(handle
);
1458 obj_to_zpdesc(obj
, &f_zpdesc
);
1459 zspage
= get_zspage(f_zpdesc
);
1460 class = zspage_class(pool
, zspage
);
1461 spin_lock(&class->lock
);
1462 read_unlock(&pool
->migrate_lock
);
1464 class_stat_sub(class, ZS_OBJS_INUSE
, 1);
1465 obj_free(class->size
, obj
);
1467 fullness
= fix_fullness_group(class, zspage
);
1468 if (fullness
== ZS_INUSE_RATIO_0
)
1469 free_zspage(pool
, class, zspage
);
1471 spin_unlock(&class->lock
);
1472 cache_free_handle(pool
, handle
);
1474 EXPORT_SYMBOL_GPL(zs_free
);
1476 static void zs_object_copy(struct size_class
*class, unsigned long dst
,
1479 struct zpdesc
*s_zpdesc
, *d_zpdesc
;
1480 unsigned int s_objidx
, d_objidx
;
1481 unsigned long s_off
, d_off
;
1482 void *s_addr
, *d_addr
;
1483 int s_size
, d_size
, size
;
1486 s_size
= d_size
= class->size
;
1488 obj_to_location(src
, &s_zpdesc
, &s_objidx
);
1489 obj_to_location(dst
, &d_zpdesc
, &d_objidx
);
1491 s_off
= offset_in_page(class->size
* s_objidx
);
1492 d_off
= offset_in_page(class->size
* d_objidx
);
1494 if (s_off
+ class->size
> PAGE_SIZE
)
1495 s_size
= PAGE_SIZE
- s_off
;
1497 if (d_off
+ class->size
> PAGE_SIZE
)
1498 d_size
= PAGE_SIZE
- d_off
;
1500 s_addr
= kmap_local_zpdesc(s_zpdesc
);
1501 d_addr
= kmap_local_zpdesc(d_zpdesc
);
1504 size
= min(s_size
, d_size
);
1505 memcpy(d_addr
+ d_off
, s_addr
+ s_off
, size
);
1508 if (written
== class->size
)
1517 * Calling kunmap_local(d_addr) is necessary. kunmap_local()
1518 * calls must occurs in reverse order of calls to kmap_local_page().
1519 * So, to call kunmap_local(s_addr) we should first call
1520 * kunmap_local(d_addr). For more details see
1521 * Documentation/mm/highmem.rst.
1523 if (s_off
>= PAGE_SIZE
) {
1524 kunmap_local(d_addr
);
1525 kunmap_local(s_addr
);
1526 s_zpdesc
= get_next_zpdesc(s_zpdesc
);
1527 s_addr
= kmap_local_zpdesc(s_zpdesc
);
1528 d_addr
= kmap_local_zpdesc(d_zpdesc
);
1529 s_size
= class->size
- written
;
1533 if (d_off
>= PAGE_SIZE
) {
1534 kunmap_local(d_addr
);
1535 d_zpdesc
= get_next_zpdesc(d_zpdesc
);
1536 d_addr
= kmap_local_zpdesc(d_zpdesc
);
1537 d_size
= class->size
- written
;
1542 kunmap_local(d_addr
);
1543 kunmap_local(s_addr
);
1547 * Find alloced object in zspage from index object and
1550 static unsigned long find_alloced_obj(struct size_class
*class,
1551 struct zpdesc
*zpdesc
, int *obj_idx
)
1553 unsigned int offset
;
1554 int index
= *obj_idx
;
1555 unsigned long handle
= 0;
1556 void *addr
= kmap_local_zpdesc(zpdesc
);
1558 offset
= get_first_obj_offset(zpdesc
);
1559 offset
+= class->size
* index
;
1561 while (offset
< PAGE_SIZE
) {
1562 if (obj_allocated(zpdesc
, addr
+ offset
, &handle
))
1565 offset
+= class->size
;
1576 static void migrate_zspage(struct zs_pool
*pool
, struct zspage
*src_zspage
,
1577 struct zspage
*dst_zspage
)
1579 unsigned long used_obj
, free_obj
;
1580 unsigned long handle
;
1582 struct zpdesc
*s_zpdesc
= get_first_zpdesc(src_zspage
);
1583 struct size_class
*class = pool
->size_class
[src_zspage
->class];
1586 handle
= find_alloced_obj(class, s_zpdesc
, &obj_idx
);
1588 s_zpdesc
= get_next_zpdesc(s_zpdesc
);
1595 used_obj
= handle_to_obj(handle
);
1596 free_obj
= obj_malloc(pool
, dst_zspage
, handle
);
1597 zs_object_copy(class, free_obj
, used_obj
);
1599 obj_free(class->size
, used_obj
);
1601 /* Stop if there is no more space */
1602 if (zspage_full(class, dst_zspage
))
1605 /* Stop if there are no more objects to migrate */
1606 if (zspage_empty(src_zspage
))
1611 static struct zspage
*isolate_src_zspage(struct size_class
*class)
1613 struct zspage
*zspage
;
1616 for (fg
= ZS_INUSE_RATIO_10
; fg
<= ZS_INUSE_RATIO_99
; fg
++) {
1617 zspage
= list_first_entry_or_null(&class->fullness_list
[fg
],
1618 struct zspage
, list
);
1620 remove_zspage(class, zspage
);
1628 static struct zspage
*isolate_dst_zspage(struct size_class
*class)
1630 struct zspage
*zspage
;
1633 for (fg
= ZS_INUSE_RATIO_99
; fg
>= ZS_INUSE_RATIO_10
; fg
--) {
1634 zspage
= list_first_entry_or_null(&class->fullness_list
[fg
],
1635 struct zspage
, list
);
1637 remove_zspage(class, zspage
);
1646 * putback_zspage - add @zspage into right class's fullness list
1647 * @class: destination class
1648 * @zspage: target page
1650 * Return @zspage's fullness status
1652 static int putback_zspage(struct size_class
*class, struct zspage
*zspage
)
1656 fullness
= get_fullness_group(class, zspage
);
1657 insert_zspage(class, zspage
, fullness
);
1662 #ifdef CONFIG_COMPACTION
1664 * To prevent zspage destroy during migration, zspage freeing should
1665 * hold locks of all pages in the zspage.
1667 static void lock_zspage(struct zspage
*zspage
)
1669 struct zpdesc
*curr_zpdesc
, *zpdesc
;
1672 * Pages we haven't locked yet can be migrated off the list while we're
1673 * trying to lock them, so we need to be careful and only attempt to
1674 * lock each page under migrate_read_lock(). Otherwise, the page we lock
1675 * may no longer belong to the zspage. This means that we may wait for
1676 * the wrong page to unlock, so we must take a reference to the page
1677 * prior to waiting for it to unlock outside migrate_read_lock().
1680 migrate_read_lock(zspage
);
1681 zpdesc
= get_first_zpdesc(zspage
);
1682 if (zpdesc_trylock(zpdesc
))
1685 migrate_read_unlock(zspage
);
1686 zpdesc_wait_locked(zpdesc
);
1690 curr_zpdesc
= zpdesc
;
1691 while ((zpdesc
= get_next_zpdesc(curr_zpdesc
))) {
1692 if (zpdesc_trylock(zpdesc
)) {
1693 curr_zpdesc
= zpdesc
;
1696 migrate_read_unlock(zspage
);
1697 zpdesc_wait_locked(zpdesc
);
1699 migrate_read_lock(zspage
);
1702 migrate_read_unlock(zspage
);
1704 #endif /* CONFIG_COMPACTION */
1706 static void migrate_lock_init(struct zspage
*zspage
)
1708 rwlock_init(&zspage
->lock
);
1711 static void migrate_read_lock(struct zspage
*zspage
) __acquires(&zspage
->lock
)
1713 read_lock(&zspage
->lock
);
1716 static void migrate_read_unlock(struct zspage
*zspage
) __releases(&zspage
->lock
)
1718 read_unlock(&zspage
->lock
);
1721 static void migrate_write_lock(struct zspage
*zspage
)
1723 write_lock(&zspage
->lock
);
1726 static void migrate_write_unlock(struct zspage
*zspage
)
1728 write_unlock(&zspage
->lock
);
1731 #ifdef CONFIG_COMPACTION
1733 static const struct movable_operations zsmalloc_mops
;
1735 static void replace_sub_page(struct size_class
*class, struct zspage
*zspage
,
1736 struct zpdesc
*newzpdesc
, struct zpdesc
*oldzpdesc
)
1738 struct zpdesc
*zpdesc
;
1739 struct zpdesc
*zpdescs
[ZS_MAX_PAGES_PER_ZSPAGE
] = {NULL
, };
1740 unsigned int first_obj_offset
;
1743 zpdesc
= get_first_zpdesc(zspage
);
1745 if (zpdesc
== oldzpdesc
)
1746 zpdescs
[idx
] = newzpdesc
;
1748 zpdescs
[idx
] = zpdesc
;
1750 } while ((zpdesc
= get_next_zpdesc(zpdesc
)) != NULL
);
1752 create_page_chain(class, zspage
, zpdescs
);
1753 first_obj_offset
= get_first_obj_offset(oldzpdesc
);
1754 set_first_obj_offset(newzpdesc
, first_obj_offset
);
1755 if (unlikely(ZsHugePage(zspage
)))
1756 newzpdesc
->handle
= oldzpdesc
->handle
;
1757 __zpdesc_set_movable(newzpdesc
, &zsmalloc_mops
);
1760 static bool zs_page_isolate(struct page
*page
, isolate_mode_t mode
)
1763 * Page is locked so zspage couldn't be destroyed. For detail, look at
1764 * lock_zspage in free_zspage.
1766 VM_BUG_ON_PAGE(PageIsolated(page
), page
);
1771 static int zs_page_migrate(struct page
*newpage
, struct page
*page
,
1772 enum migrate_mode mode
)
1774 struct zs_pool
*pool
;
1775 struct size_class
*class;
1776 struct zspage
*zspage
;
1777 struct zpdesc
*dummy
;
1778 struct zpdesc
*newzpdesc
= page_zpdesc(newpage
);
1779 struct zpdesc
*zpdesc
= page_zpdesc(page
);
1780 void *s_addr
, *d_addr
, *addr
;
1781 unsigned int offset
;
1782 unsigned long handle
;
1783 unsigned long old_obj
, new_obj
;
1784 unsigned int obj_idx
;
1786 VM_BUG_ON_PAGE(!zpdesc_is_isolated(zpdesc
), zpdesc_page(zpdesc
));
1788 /* We're committed, tell the world that this is a Zsmalloc page. */
1789 __zpdesc_set_zsmalloc(newzpdesc
);
1791 /* The page is locked, so this pointer must remain valid */
1792 zspage
= get_zspage(zpdesc
);
1793 pool
= zspage
->pool
;
1796 * The pool migrate_lock protects the race between zpage migration
1799 write_lock(&pool
->migrate_lock
);
1800 class = zspage_class(pool
, zspage
);
1803 * the class lock protects zpage alloc/free in the zspage.
1805 spin_lock(&class->lock
);
1806 /* the migrate_write_lock protects zpage access via zs_map_object */
1807 migrate_write_lock(zspage
);
1809 offset
= get_first_obj_offset(zpdesc
);
1810 s_addr
= kmap_local_zpdesc(zpdesc
);
1813 * Here, any user cannot access all objects in the zspage so let's move.
1815 d_addr
= kmap_local_zpdesc(newzpdesc
);
1816 copy_page(d_addr
, s_addr
);
1817 kunmap_local(d_addr
);
1819 for (addr
= s_addr
+ offset
; addr
< s_addr
+ PAGE_SIZE
;
1820 addr
+= class->size
) {
1821 if (obj_allocated(zpdesc
, addr
, &handle
)) {
1823 old_obj
= handle_to_obj(handle
);
1824 obj_to_location(old_obj
, &dummy
, &obj_idx
);
1825 new_obj
= (unsigned long)location_to_obj(newzpdesc
, obj_idx
);
1826 record_obj(handle
, new_obj
);
1829 kunmap_local(s_addr
);
1831 replace_sub_page(class, zspage
, newzpdesc
, zpdesc
);
1833 * Since we complete the data copy and set up new zspage structure,
1834 * it's okay to release migration_lock.
1836 write_unlock(&pool
->migrate_lock
);
1837 spin_unlock(&class->lock
);
1838 migrate_write_unlock(zspage
);
1840 zpdesc_get(newzpdesc
);
1841 if (zpdesc_zone(newzpdesc
) != zpdesc_zone(zpdesc
)) {
1842 zpdesc_dec_zone_page_state(zpdesc
);
1843 zpdesc_inc_zone_page_state(newzpdesc
);
1846 reset_zpdesc(zpdesc
);
1849 return MIGRATEPAGE_SUCCESS
;
1852 static void zs_page_putback(struct page
*page
)
1854 VM_BUG_ON_PAGE(!PageIsolated(page
), page
);
1857 static const struct movable_operations zsmalloc_mops
= {
1858 .isolate_page
= zs_page_isolate
,
1859 .migrate_page
= zs_page_migrate
,
1860 .putback_page
= zs_page_putback
,
1864 * Caller should hold page_lock of all pages in the zspage
1865 * In here, we cannot use zspage meta data.
1867 static void async_free_zspage(struct work_struct
*work
)
1870 struct size_class
*class;
1871 struct zspage
*zspage
, *tmp
;
1872 LIST_HEAD(free_pages
);
1873 struct zs_pool
*pool
= container_of(work
, struct zs_pool
,
1876 for (i
= 0; i
< ZS_SIZE_CLASSES
; i
++) {
1877 class = pool
->size_class
[i
];
1878 if (class->index
!= i
)
1881 spin_lock(&class->lock
);
1882 list_splice_init(&class->fullness_list
[ZS_INUSE_RATIO_0
],
1884 spin_unlock(&class->lock
);
1887 list_for_each_entry_safe(zspage
, tmp
, &free_pages
, list
) {
1888 list_del(&zspage
->list
);
1889 lock_zspage(zspage
);
1891 class = zspage_class(pool
, zspage
);
1892 spin_lock(&class->lock
);
1893 class_stat_sub(class, ZS_INUSE_RATIO_0
, 1);
1894 __free_zspage(pool
, class, zspage
);
1895 spin_unlock(&class->lock
);
1899 static void kick_deferred_free(struct zs_pool
*pool
)
1901 schedule_work(&pool
->free_work
);
1904 static void zs_flush_migration(struct zs_pool
*pool
)
1906 flush_work(&pool
->free_work
);
1909 static void init_deferred_free(struct zs_pool
*pool
)
1911 INIT_WORK(&pool
->free_work
, async_free_zspage
);
1914 static void SetZsPageMovable(struct zs_pool
*pool
, struct zspage
*zspage
)
1916 struct zpdesc
*zpdesc
= get_first_zpdesc(zspage
);
1919 WARN_ON(!zpdesc_trylock(zpdesc
));
1920 __zpdesc_set_movable(zpdesc
, &zsmalloc_mops
);
1921 zpdesc_unlock(zpdesc
);
1922 } while ((zpdesc
= get_next_zpdesc(zpdesc
)) != NULL
);
1925 static inline void zs_flush_migration(struct zs_pool
*pool
) { }
1930 * Based on the number of unused allocated objects calculate
1931 * and return the number of pages that we can free.
1933 static unsigned long zs_can_compact(struct size_class
*class)
1935 unsigned long obj_wasted
;
1936 unsigned long obj_allocated
= class_stat_read(class, ZS_OBJS_ALLOCATED
);
1937 unsigned long obj_used
= class_stat_read(class, ZS_OBJS_INUSE
);
1939 if (obj_allocated
<= obj_used
)
1942 obj_wasted
= obj_allocated
- obj_used
;
1943 obj_wasted
/= class->objs_per_zspage
;
1945 return obj_wasted
* class->pages_per_zspage
;
1948 static unsigned long __zs_compact(struct zs_pool
*pool
,
1949 struct size_class
*class)
1951 struct zspage
*src_zspage
= NULL
;
1952 struct zspage
*dst_zspage
= NULL
;
1953 unsigned long pages_freed
= 0;
1956 * protect the race between zpage migration and zs_free
1957 * as well as zpage allocation/free
1959 write_lock(&pool
->migrate_lock
);
1960 spin_lock(&class->lock
);
1961 while (zs_can_compact(class)) {
1965 dst_zspage
= isolate_dst_zspage(class);
1970 src_zspage
= isolate_src_zspage(class);
1974 migrate_write_lock(src_zspage
);
1975 migrate_zspage(pool
, src_zspage
, dst_zspage
);
1976 migrate_write_unlock(src_zspage
);
1978 fg
= putback_zspage(class, src_zspage
);
1979 if (fg
== ZS_INUSE_RATIO_0
) {
1980 free_zspage(pool
, class, src_zspage
);
1981 pages_freed
+= class->pages_per_zspage
;
1985 if (get_fullness_group(class, dst_zspage
) == ZS_INUSE_RATIO_100
1986 || rwlock_is_contended(&pool
->migrate_lock
)) {
1987 putback_zspage(class, dst_zspage
);
1990 spin_unlock(&class->lock
);
1991 write_unlock(&pool
->migrate_lock
);
1993 write_lock(&pool
->migrate_lock
);
1994 spin_lock(&class->lock
);
1999 putback_zspage(class, src_zspage
);
2002 putback_zspage(class, dst_zspage
);
2004 spin_unlock(&class->lock
);
2005 write_unlock(&pool
->migrate_lock
);
2010 unsigned long zs_compact(struct zs_pool
*pool
)
2013 struct size_class
*class;
2014 unsigned long pages_freed
= 0;
2017 * Pool compaction is performed under pool->migrate_lock so it is basically
2018 * single-threaded. Having more than one thread in __zs_compact()
2019 * will increase pool->migrate_lock contention, which will impact other
2020 * zsmalloc operations that need pool->migrate_lock.
2022 if (atomic_xchg(&pool
->compaction_in_progress
, 1))
2025 for (i
= ZS_SIZE_CLASSES
- 1; i
>= 0; i
--) {
2026 class = pool
->size_class
[i
];
2027 if (class->index
!= i
)
2029 pages_freed
+= __zs_compact(pool
, class);
2031 atomic_long_add(pages_freed
, &pool
->stats
.pages_compacted
);
2032 atomic_set(&pool
->compaction_in_progress
, 0);
2036 EXPORT_SYMBOL_GPL(zs_compact
);
2038 void zs_pool_stats(struct zs_pool
*pool
, struct zs_pool_stats
*stats
)
2040 memcpy(stats
, &pool
->stats
, sizeof(struct zs_pool_stats
));
2042 EXPORT_SYMBOL_GPL(zs_pool_stats
);
2044 static unsigned long zs_shrinker_scan(struct shrinker
*shrinker
,
2045 struct shrink_control
*sc
)
2047 unsigned long pages_freed
;
2048 struct zs_pool
*pool
= shrinker
->private_data
;
2051 * Compact classes and calculate compaction delta.
2052 * Can run concurrently with a manually triggered
2053 * (by user) compaction.
2055 pages_freed
= zs_compact(pool
);
2057 return pages_freed
? pages_freed
: SHRINK_STOP
;
2060 static unsigned long zs_shrinker_count(struct shrinker
*shrinker
,
2061 struct shrink_control
*sc
)
2064 struct size_class
*class;
2065 unsigned long pages_to_free
= 0;
2066 struct zs_pool
*pool
= shrinker
->private_data
;
2068 for (i
= ZS_SIZE_CLASSES
- 1; i
>= 0; i
--) {
2069 class = pool
->size_class
[i
];
2070 if (class->index
!= i
)
2073 pages_to_free
+= zs_can_compact(class);
2076 return pages_to_free
;
2079 static void zs_unregister_shrinker(struct zs_pool
*pool
)
2081 shrinker_free(pool
->shrinker
);
2084 static int zs_register_shrinker(struct zs_pool
*pool
)
2086 pool
->shrinker
= shrinker_alloc(0, "mm-zspool:%s", pool
->name
);
2087 if (!pool
->shrinker
)
2090 pool
->shrinker
->scan_objects
= zs_shrinker_scan
;
2091 pool
->shrinker
->count_objects
= zs_shrinker_count
;
2092 pool
->shrinker
->batch
= 0;
2093 pool
->shrinker
->private_data
= pool
;
2095 shrinker_register(pool
->shrinker
);
2100 static int calculate_zspage_chain_size(int class_size
)
2102 int i
, min_waste
= INT_MAX
;
2105 if (is_power_of_2(class_size
))
2108 for (i
= 1; i
<= ZS_MAX_PAGES_PER_ZSPAGE
; i
++) {
2111 waste
= (i
* PAGE_SIZE
) % class_size
;
2112 if (waste
< min_waste
) {
2122 * zs_create_pool - Creates an allocation pool to work from.
2123 * @name: pool name to be created
2125 * This function must be called before anything when using
2126 * the zsmalloc allocator.
2128 * On success, a pointer to the newly created pool is returned,
2131 struct zs_pool
*zs_create_pool(const char *name
)
2134 struct zs_pool
*pool
;
2135 struct size_class
*prev_class
= NULL
;
2137 pool
= kzalloc(sizeof(*pool
), GFP_KERNEL
);
2141 init_deferred_free(pool
);
2142 rwlock_init(&pool
->migrate_lock
);
2143 atomic_set(&pool
->compaction_in_progress
, 0);
2145 pool
->name
= kstrdup(name
, GFP_KERNEL
);
2149 if (create_cache(pool
))
2153 * Iterate reversely, because, size of size_class that we want to use
2154 * for merging should be larger or equal to current size.
2156 for (i
= ZS_SIZE_CLASSES
- 1; i
>= 0; i
--) {
2158 int pages_per_zspage
;
2159 int objs_per_zspage
;
2160 struct size_class
*class;
2163 size
= ZS_MIN_ALLOC_SIZE
+ i
* ZS_SIZE_CLASS_DELTA
;
2164 if (size
> ZS_MAX_ALLOC_SIZE
)
2165 size
= ZS_MAX_ALLOC_SIZE
;
2166 pages_per_zspage
= calculate_zspage_chain_size(size
);
2167 objs_per_zspage
= pages_per_zspage
* PAGE_SIZE
/ size
;
2170 * We iterate from biggest down to smallest classes,
2171 * so huge_class_size holds the size of the first huge
2172 * class. Any object bigger than or equal to that will
2173 * endup in the huge class.
2175 if (pages_per_zspage
!= 1 && objs_per_zspage
!= 1 &&
2177 huge_class_size
= size
;
2179 * The object uses ZS_HANDLE_SIZE bytes to store the
2180 * handle. We need to subtract it, because zs_malloc()
2181 * unconditionally adds handle size before it performs
2182 * size class search - so object may be smaller than
2183 * huge class size, yet it still can end up in the huge
2184 * class because it grows by ZS_HANDLE_SIZE extra bytes
2185 * right before class lookup.
2187 huge_class_size
-= (ZS_HANDLE_SIZE
- 1);
2191 * size_class is used for normal zsmalloc operation such
2192 * as alloc/free for that size. Although it is natural that we
2193 * have one size_class for each size, there is a chance that we
2194 * can get more memory utilization if we use one size_class for
2195 * many different sizes whose size_class have same
2196 * characteristics. So, we makes size_class point to
2197 * previous size_class if possible.
2200 if (can_merge(prev_class
, pages_per_zspage
, objs_per_zspage
)) {
2201 pool
->size_class
[i
] = prev_class
;
2206 class = kzalloc(sizeof(struct size_class
), GFP_KERNEL
);
2212 class->pages_per_zspage
= pages_per_zspage
;
2213 class->objs_per_zspage
= objs_per_zspage
;
2214 spin_lock_init(&class->lock
);
2215 pool
->size_class
[i
] = class;
2217 fullness
= ZS_INUSE_RATIO_0
;
2218 while (fullness
< NR_FULLNESS_GROUPS
) {
2219 INIT_LIST_HEAD(&class->fullness_list
[fullness
]);
2226 /* debug only, don't abort if it fails */
2227 zs_pool_stat_create(pool
, name
);
2230 * Not critical since shrinker is only used to trigger internal
2231 * defragmentation of the pool which is pretty optional thing. If
2232 * registration fails we still can use the pool normally and user can
2233 * trigger compaction manually. Thus, ignore return code.
2235 zs_register_shrinker(pool
);
2240 zs_destroy_pool(pool
);
2243 EXPORT_SYMBOL_GPL(zs_create_pool
);
2245 void zs_destroy_pool(struct zs_pool
*pool
)
2249 zs_unregister_shrinker(pool
);
2250 zs_flush_migration(pool
);
2251 zs_pool_stat_destroy(pool
);
2253 for (i
= 0; i
< ZS_SIZE_CLASSES
; i
++) {
2255 struct size_class
*class = pool
->size_class
[i
];
2260 if (class->index
!= i
)
2263 for (fg
= ZS_INUSE_RATIO_0
; fg
< NR_FULLNESS_GROUPS
; fg
++) {
2264 if (list_empty(&class->fullness_list
[fg
]))
2267 pr_err("Class-%d fullness group %d is not empty\n",
2273 destroy_cache(pool
);
2277 EXPORT_SYMBOL_GPL(zs_destroy_pool
);
2279 static int __init
zs_init(void)
2283 ret
= cpuhp_setup_state(CPUHP_MM_ZS_PREPARE
, "mm/zsmalloc:prepare",
2284 zs_cpu_prepare
, zs_cpu_dead
);
2289 zpool_register_driver(&zs_zpool_driver
);
2300 static void __exit
zs_exit(void)
2303 zpool_unregister_driver(&zs_zpool_driver
);
2305 cpuhp_remove_state(CPUHP_MM_ZS_PREPARE
);
2310 module_init(zs_init
);
2311 module_exit(zs_exit
);
2313 MODULE_LICENSE("Dual BSD/GPL");
2314 MODULE_AUTHOR("Nitin Gupta <ngupta@vflare.org>");
2315 MODULE_DESCRIPTION("zsmalloc memory allocator");