mm/z3fold.c: allow __GFP_HIGHMEM in z3fold_alloc
[sfrench/cifs-2.6.git] / mm / z3fold.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * z3fold.c
4  *
5  * Author: Vitaly Wool <vitaly.wool@konsulko.com>
6  * Copyright (C) 2016, Sony Mobile Communications Inc.
7  *
8  * This implementation is based on zbud written by Seth Jennings.
9  *
10  * z3fold is an special purpose allocator for storing compressed pages. It
11  * can store up to three compressed pages per page which improves the
12  * compression ratio of zbud while retaining its main concepts (e. g. always
13  * storing an integral number of objects per page) and simplicity.
14  * It still has simple and deterministic reclaim properties that make it
15  * preferable to a higher density approach (with no requirement on integral
16  * number of object per page) when reclaim is used.
17  *
18  * As in zbud, pages are divided into "chunks".  The size of the chunks is
19  * fixed at compile time and is determined by NCHUNKS_ORDER below.
20  *
21  * z3fold doesn't export any API and is meant to be used via zpool API.
22  */
23
24 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
25
26 #include <linux/atomic.h>
27 #include <linux/sched.h>
28 #include <linux/cpumask.h>
29 #include <linux/dcache.h>
30 #include <linux/list.h>
31 #include <linux/mm.h>
32 #include <linux/module.h>
33 #include <linux/page-flags.h>
34 #include <linux/migrate.h>
35 #include <linux/node.h>
36 #include <linux/compaction.h>
37 #include <linux/percpu.h>
38 #include <linux/mount.h>
39 #include <linux/fs.h>
40 #include <linux/preempt.h>
41 #include <linux/workqueue.h>
42 #include <linux/slab.h>
43 #include <linux/spinlock.h>
44 #include <linux/zpool.h>
45
46 /*
47  * NCHUNKS_ORDER determines the internal allocation granularity, effectively
48  * adjusting internal fragmentation.  It also determines the number of
49  * freelists maintained in each pool. NCHUNKS_ORDER of 6 means that the
50  * allocation granularity will be in chunks of size PAGE_SIZE/64. Some chunks
51  * in the beginning of an allocated page are occupied by z3fold header, so
52  * NCHUNKS will be calculated to 63 (or 62 in case CONFIG_DEBUG_SPINLOCK=y),
53  * which shows the max number of free chunks in z3fold page, also there will
54  * be 63, or 62, respectively, freelists per pool.
55  */
56 #define NCHUNKS_ORDER   6
57
58 #define CHUNK_SHIFT     (PAGE_SHIFT - NCHUNKS_ORDER)
59 #define CHUNK_SIZE      (1 << CHUNK_SHIFT)
60 #define ZHDR_SIZE_ALIGNED round_up(sizeof(struct z3fold_header), CHUNK_SIZE)
61 #define ZHDR_CHUNKS     (ZHDR_SIZE_ALIGNED >> CHUNK_SHIFT)
62 #define TOTAL_CHUNKS    (PAGE_SIZE >> CHUNK_SHIFT)
63 #define NCHUNKS         ((PAGE_SIZE - ZHDR_SIZE_ALIGNED) >> CHUNK_SHIFT)
64
65 #define BUDDY_MASK      (0x3)
66 #define BUDDY_SHIFT     2
67 #define SLOTS_ALIGN     (0x40)
68
69 /*****************
70  * Structures
71 *****************/
72 struct z3fold_pool;
73 struct z3fold_ops {
74         int (*evict)(struct z3fold_pool *pool, unsigned long handle);
75 };
76
77 enum buddy {
78         HEADLESS = 0,
79         FIRST,
80         MIDDLE,
81         LAST,
82         BUDDIES_MAX = LAST
83 };
84
85 struct z3fold_buddy_slots {
86         /*
87          * we are using BUDDY_MASK in handle_to_buddy etc. so there should
88          * be enough slots to hold all possible variants
89          */
90         unsigned long slot[BUDDY_MASK + 1];
91         unsigned long pool; /* back link + flags */
92 };
93 #define HANDLE_FLAG_MASK        (0x03)
94
95 /*
96  * struct z3fold_header - z3fold page metadata occupying first chunks of each
97  *                      z3fold page, except for HEADLESS pages
98  * @buddy:              links the z3fold page into the relevant list in the
99  *                      pool
100  * @page_lock:          per-page lock
101  * @refcount:           reference count for the z3fold page
102  * @work:               work_struct for page layout optimization
103  * @slots:              pointer to the structure holding buddy slots
104  * @pool:               pointer to the containing pool
105  * @cpu:                CPU which this page "belongs" to
106  * @first_chunks:       the size of the first buddy in chunks, 0 if free
107  * @middle_chunks:      the size of the middle buddy in chunks, 0 if free
108  * @last_chunks:        the size of the last buddy in chunks, 0 if free
109  * @first_num:          the starting number (for the first handle)
110  * @mapped_count:       the number of objects currently mapped
111  */
112 struct z3fold_header {
113         struct list_head buddy;
114         spinlock_t page_lock;
115         struct kref refcount;
116         struct work_struct work;
117         struct z3fold_buddy_slots *slots;
118         struct z3fold_pool *pool;
119         short cpu;
120         unsigned short first_chunks;
121         unsigned short middle_chunks;
122         unsigned short last_chunks;
123         unsigned short start_middle;
124         unsigned short first_num:2;
125         unsigned short mapped_count:2;
126 };
127
128 /**
129  * struct z3fold_pool - stores metadata for each z3fold pool
130  * @name:       pool name
131  * @lock:       protects pool unbuddied/lru lists
132  * @stale_lock: protects pool stale page list
133  * @unbuddied:  per-cpu array of lists tracking z3fold pages that contain 2-
134  *              buddies; the list each z3fold page is added to depends on
135  *              the size of its free region.
136  * @lru:        list tracking the z3fold pages in LRU order by most recently
137  *              added buddy.
138  * @stale:      list of pages marked for freeing
139  * @pages_nr:   number of z3fold pages in the pool.
140  * @c_handle:   cache for z3fold_buddy_slots allocation
141  * @ops:        pointer to a structure of user defined operations specified at
142  *              pool creation time.
143  * @compact_wq: workqueue for page layout background optimization
144  * @release_wq: workqueue for safe page release
145  * @work:       work_struct for safe page release
146  * @inode:      inode for z3fold pseudo filesystem
147  *
148  * This structure is allocated at pool creation time and maintains metadata
149  * pertaining to a particular z3fold pool.
150  */
151 struct z3fold_pool {
152         const char *name;
153         spinlock_t lock;
154         spinlock_t stale_lock;
155         struct list_head *unbuddied;
156         struct list_head lru;
157         struct list_head stale;
158         atomic64_t pages_nr;
159         struct kmem_cache *c_handle;
160         const struct z3fold_ops *ops;
161         struct zpool *zpool;
162         const struct zpool_ops *zpool_ops;
163         struct workqueue_struct *compact_wq;
164         struct workqueue_struct *release_wq;
165         struct work_struct work;
166         struct inode *inode;
167 };
168
169 /*
170  * Internal z3fold page flags
171  */
172 enum z3fold_page_flags {
173         PAGE_HEADLESS = 0,
174         MIDDLE_CHUNK_MAPPED,
175         NEEDS_COMPACTING,
176         PAGE_STALE,
177         PAGE_CLAIMED, /* by either reclaim or free */
178 };
179
180 /*****************
181  * Helpers
182 *****************/
183
184 /* Converts an allocation size in bytes to size in z3fold chunks */
185 static int size_to_chunks(size_t size)
186 {
187         return (size + CHUNK_SIZE - 1) >> CHUNK_SHIFT;
188 }
189
190 #define for_each_unbuddied_list(_iter, _begin) \
191         for ((_iter) = (_begin); (_iter) < NCHUNKS; (_iter)++)
192
193 static void compact_page_work(struct work_struct *w);
194
195 static inline struct z3fold_buddy_slots *alloc_slots(struct z3fold_pool *pool,
196                                                         gfp_t gfp)
197 {
198         struct z3fold_buddy_slots *slots;
199
200         slots = kmem_cache_alloc(pool->c_handle,
201                                  (gfp & ~(__GFP_HIGHMEM | __GFP_MOVABLE)));
202
203         if (slots) {
204                 memset(slots->slot, 0, sizeof(slots->slot));
205                 slots->pool = (unsigned long)pool;
206         }
207
208         return slots;
209 }
210
211 static inline struct z3fold_pool *slots_to_pool(struct z3fold_buddy_slots *s)
212 {
213         return (struct z3fold_pool *)(s->pool & ~HANDLE_FLAG_MASK);
214 }
215
216 static inline struct z3fold_buddy_slots *handle_to_slots(unsigned long handle)
217 {
218         return (struct z3fold_buddy_slots *)(handle & ~(SLOTS_ALIGN - 1));
219 }
220
221 static inline void free_handle(unsigned long handle)
222 {
223         struct z3fold_buddy_slots *slots;
224         int i;
225         bool is_free;
226
227         if (handle & (1 << PAGE_HEADLESS))
228                 return;
229
230         WARN_ON(*(unsigned long *)handle == 0);
231         *(unsigned long *)handle = 0;
232         slots = handle_to_slots(handle);
233         is_free = true;
234         for (i = 0; i <= BUDDY_MASK; i++) {
235                 if (slots->slot[i]) {
236                         is_free = false;
237                         break;
238                 }
239         }
240
241         if (is_free) {
242                 struct z3fold_pool *pool = slots_to_pool(slots);
243
244                 kmem_cache_free(pool->c_handle, slots);
245         }
246 }
247
248 static struct dentry *z3fold_do_mount(struct file_system_type *fs_type,
249                                 int flags, const char *dev_name, void *data)
250 {
251         static const struct dentry_operations ops = {
252                 .d_dname = simple_dname,
253         };
254
255         return mount_pseudo(fs_type, "z3fold:", NULL, &ops, 0x33);
256 }
257
258 static struct file_system_type z3fold_fs = {
259         .name           = "z3fold",
260         .mount          = z3fold_do_mount,
261         .kill_sb        = kill_anon_super,
262 };
263
264 static struct vfsmount *z3fold_mnt;
265 static int z3fold_mount(void)
266 {
267         int ret = 0;
268
269         z3fold_mnt = kern_mount(&z3fold_fs);
270         if (IS_ERR(z3fold_mnt))
271                 ret = PTR_ERR(z3fold_mnt);
272
273         return ret;
274 }
275
276 static void z3fold_unmount(void)
277 {
278         kern_unmount(z3fold_mnt);
279 }
280
281 static const struct address_space_operations z3fold_aops;
282 static int z3fold_register_migration(struct z3fold_pool *pool)
283 {
284         pool->inode = alloc_anon_inode(z3fold_mnt->mnt_sb);
285         if (IS_ERR(pool->inode)) {
286                 pool->inode = NULL;
287                 return 1;
288         }
289
290         pool->inode->i_mapping->private_data = pool;
291         pool->inode->i_mapping->a_ops = &z3fold_aops;
292         return 0;
293 }
294
295 static void z3fold_unregister_migration(struct z3fold_pool *pool)
296 {
297         if (pool->inode)
298                 iput(pool->inode);
299  }
300
301 /* Initializes the z3fold header of a newly allocated z3fold page */
302 static struct z3fold_header *init_z3fold_page(struct page *page,
303                                         struct z3fold_pool *pool, gfp_t gfp)
304 {
305         struct z3fold_header *zhdr = page_address(page);
306         struct z3fold_buddy_slots *slots = alloc_slots(pool, gfp);
307
308         if (!slots)
309                 return NULL;
310
311         INIT_LIST_HEAD(&page->lru);
312         clear_bit(PAGE_HEADLESS, &page->private);
313         clear_bit(MIDDLE_CHUNK_MAPPED, &page->private);
314         clear_bit(NEEDS_COMPACTING, &page->private);
315         clear_bit(PAGE_STALE, &page->private);
316         clear_bit(PAGE_CLAIMED, &page->private);
317
318         spin_lock_init(&zhdr->page_lock);
319         kref_init(&zhdr->refcount);
320         zhdr->first_chunks = 0;
321         zhdr->middle_chunks = 0;
322         zhdr->last_chunks = 0;
323         zhdr->first_num = 0;
324         zhdr->start_middle = 0;
325         zhdr->cpu = -1;
326         zhdr->slots = slots;
327         zhdr->pool = pool;
328         INIT_LIST_HEAD(&zhdr->buddy);
329         INIT_WORK(&zhdr->work, compact_page_work);
330         return zhdr;
331 }
332
333 /* Resets the struct page fields and frees the page */
334 static void free_z3fold_page(struct page *page, bool headless)
335 {
336         if (!headless) {
337                 lock_page(page);
338                 __ClearPageMovable(page);
339                 unlock_page(page);
340         }
341         ClearPagePrivate(page);
342         __free_page(page);
343 }
344
345 /* Lock a z3fold page */
346 static inline void z3fold_page_lock(struct z3fold_header *zhdr)
347 {
348         spin_lock(&zhdr->page_lock);
349 }
350
351 /* Try to lock a z3fold page */
352 static inline int z3fold_page_trylock(struct z3fold_header *zhdr)
353 {
354         return spin_trylock(&zhdr->page_lock);
355 }
356
357 /* Unlock a z3fold page */
358 static inline void z3fold_page_unlock(struct z3fold_header *zhdr)
359 {
360         spin_unlock(&zhdr->page_lock);
361 }
362
363 /* Helper function to build the index */
364 static inline int __idx(struct z3fold_header *zhdr, enum buddy bud)
365 {
366         return (bud + zhdr->first_num) & BUDDY_MASK;
367 }
368
369 /*
370  * Encodes the handle of a particular buddy within a z3fold page
371  * Pool lock should be held as this function accesses first_num
372  */
373 static unsigned long encode_handle(struct z3fold_header *zhdr, enum buddy bud)
374 {
375         struct z3fold_buddy_slots *slots;
376         unsigned long h = (unsigned long)zhdr;
377         int idx = 0;
378
379         /*
380          * For a headless page, its handle is its pointer with the extra
381          * PAGE_HEADLESS bit set
382          */
383         if (bud == HEADLESS)
384                 return h | (1 << PAGE_HEADLESS);
385
386         /* otherwise, return pointer to encoded handle */
387         idx = __idx(zhdr, bud);
388         h += idx;
389         if (bud == LAST)
390                 h |= (zhdr->last_chunks << BUDDY_SHIFT);
391
392         slots = zhdr->slots;
393         slots->slot[idx] = h;
394         return (unsigned long)&slots->slot[idx];
395 }
396
397 /* Returns the z3fold page where a given handle is stored */
398 static inline struct z3fold_header *handle_to_z3fold_header(unsigned long h)
399 {
400         unsigned long addr = h;
401
402         if (!(addr & (1 << PAGE_HEADLESS)))
403                 addr = *(unsigned long *)h;
404
405         return (struct z3fold_header *)(addr & PAGE_MASK);
406 }
407
408 /* only for LAST bud, returns zero otherwise */
409 static unsigned short handle_to_chunks(unsigned long handle)
410 {
411         unsigned long addr = *(unsigned long *)handle;
412
413         return (addr & ~PAGE_MASK) >> BUDDY_SHIFT;
414 }
415
416 /*
417  * (handle & BUDDY_MASK) < zhdr->first_num is possible in encode_handle
418  *  but that doesn't matter. because the masking will result in the
419  *  correct buddy number.
420  */
421 static enum buddy handle_to_buddy(unsigned long handle)
422 {
423         struct z3fold_header *zhdr;
424         unsigned long addr;
425
426         WARN_ON(handle & (1 << PAGE_HEADLESS));
427         addr = *(unsigned long *)handle;
428         zhdr = (struct z3fold_header *)(addr & PAGE_MASK);
429         return (addr - zhdr->first_num) & BUDDY_MASK;
430 }
431
432 static inline struct z3fold_pool *zhdr_to_pool(struct z3fold_header *zhdr)
433 {
434         return zhdr->pool;
435 }
436
437 static void __release_z3fold_page(struct z3fold_header *zhdr, bool locked)
438 {
439         struct page *page = virt_to_page(zhdr);
440         struct z3fold_pool *pool = zhdr_to_pool(zhdr);
441
442         WARN_ON(!list_empty(&zhdr->buddy));
443         set_bit(PAGE_STALE, &page->private);
444         clear_bit(NEEDS_COMPACTING, &page->private);
445         spin_lock(&pool->lock);
446         if (!list_empty(&page->lru))
447                 list_del_init(&page->lru);
448         spin_unlock(&pool->lock);
449         if (locked)
450                 z3fold_page_unlock(zhdr);
451         spin_lock(&pool->stale_lock);
452         list_add(&zhdr->buddy, &pool->stale);
453         queue_work(pool->release_wq, &pool->work);
454         spin_unlock(&pool->stale_lock);
455 }
456
457 static void __attribute__((__unused__))
458                         release_z3fold_page(struct kref *ref)
459 {
460         struct z3fold_header *zhdr = container_of(ref, struct z3fold_header,
461                                                 refcount);
462         __release_z3fold_page(zhdr, false);
463 }
464
465 static void release_z3fold_page_locked(struct kref *ref)
466 {
467         struct z3fold_header *zhdr = container_of(ref, struct z3fold_header,
468                                                 refcount);
469         WARN_ON(z3fold_page_trylock(zhdr));
470         __release_z3fold_page(zhdr, true);
471 }
472
473 static void release_z3fold_page_locked_list(struct kref *ref)
474 {
475         struct z3fold_header *zhdr = container_of(ref, struct z3fold_header,
476                                                refcount);
477         struct z3fold_pool *pool = zhdr_to_pool(zhdr);
478         spin_lock(&pool->lock);
479         list_del_init(&zhdr->buddy);
480         spin_unlock(&pool->lock);
481
482         WARN_ON(z3fold_page_trylock(zhdr));
483         __release_z3fold_page(zhdr, true);
484 }
485
486 static void free_pages_work(struct work_struct *w)
487 {
488         struct z3fold_pool *pool = container_of(w, struct z3fold_pool, work);
489
490         spin_lock(&pool->stale_lock);
491         while (!list_empty(&pool->stale)) {
492                 struct z3fold_header *zhdr = list_first_entry(&pool->stale,
493                                                 struct z3fold_header, buddy);
494                 struct page *page = virt_to_page(zhdr);
495
496                 list_del(&zhdr->buddy);
497                 if (WARN_ON(!test_bit(PAGE_STALE, &page->private)))
498                         continue;
499                 spin_unlock(&pool->stale_lock);
500                 cancel_work_sync(&zhdr->work);
501                 free_z3fold_page(page, false);
502                 cond_resched();
503                 spin_lock(&pool->stale_lock);
504         }
505         spin_unlock(&pool->stale_lock);
506 }
507
508 /*
509  * Returns the number of free chunks in a z3fold page.
510  * NB: can't be used with HEADLESS pages.
511  */
512 static int num_free_chunks(struct z3fold_header *zhdr)
513 {
514         int nfree;
515         /*
516          * If there is a middle object, pick up the bigger free space
517          * either before or after it. Otherwise just subtract the number
518          * of chunks occupied by the first and the last objects.
519          */
520         if (zhdr->middle_chunks != 0) {
521                 int nfree_before = zhdr->first_chunks ?
522                         0 : zhdr->start_middle - ZHDR_CHUNKS;
523                 int nfree_after = zhdr->last_chunks ?
524                         0 : TOTAL_CHUNKS -
525                                 (zhdr->start_middle + zhdr->middle_chunks);
526                 nfree = max(nfree_before, nfree_after);
527         } else
528                 nfree = NCHUNKS - zhdr->first_chunks - zhdr->last_chunks;
529         return nfree;
530 }
531
532 /* Add to the appropriate unbuddied list */
533 static inline void add_to_unbuddied(struct z3fold_pool *pool,
534                                 struct z3fold_header *zhdr)
535 {
536         if (zhdr->first_chunks == 0 || zhdr->last_chunks == 0 ||
537                         zhdr->middle_chunks == 0) {
538                 struct list_head *unbuddied = get_cpu_ptr(pool->unbuddied);
539
540                 int freechunks = num_free_chunks(zhdr);
541                 spin_lock(&pool->lock);
542                 list_add(&zhdr->buddy, &unbuddied[freechunks]);
543                 spin_unlock(&pool->lock);
544                 zhdr->cpu = smp_processor_id();
545                 put_cpu_ptr(pool->unbuddied);
546         }
547 }
548
549 static inline void *mchunk_memmove(struct z3fold_header *zhdr,
550                                 unsigned short dst_chunk)
551 {
552         void *beg = zhdr;
553         return memmove(beg + (dst_chunk << CHUNK_SHIFT),
554                        beg + (zhdr->start_middle << CHUNK_SHIFT),
555                        zhdr->middle_chunks << CHUNK_SHIFT);
556 }
557
558 #define BIG_CHUNK_GAP   3
559 /* Has to be called with lock held */
560 static int z3fold_compact_page(struct z3fold_header *zhdr)
561 {
562         struct page *page = virt_to_page(zhdr);
563
564         if (test_bit(MIDDLE_CHUNK_MAPPED, &page->private))
565                 return 0; /* can't move middle chunk, it's used */
566
567         if (unlikely(PageIsolated(page)))
568                 return 0;
569
570         if (zhdr->middle_chunks == 0)
571                 return 0; /* nothing to compact */
572
573         if (zhdr->first_chunks == 0 && zhdr->last_chunks == 0) {
574                 /* move to the beginning */
575                 mchunk_memmove(zhdr, ZHDR_CHUNKS);
576                 zhdr->first_chunks = zhdr->middle_chunks;
577                 zhdr->middle_chunks = 0;
578                 zhdr->start_middle = 0;
579                 zhdr->first_num++;
580                 return 1;
581         }
582
583         /*
584          * moving data is expensive, so let's only do that if
585          * there's substantial gain (at least BIG_CHUNK_GAP chunks)
586          */
587         if (zhdr->first_chunks != 0 && zhdr->last_chunks == 0 &&
588             zhdr->start_middle - (zhdr->first_chunks + ZHDR_CHUNKS) >=
589                         BIG_CHUNK_GAP) {
590                 mchunk_memmove(zhdr, zhdr->first_chunks + ZHDR_CHUNKS);
591                 zhdr->start_middle = zhdr->first_chunks + ZHDR_CHUNKS;
592                 return 1;
593         } else if (zhdr->last_chunks != 0 && zhdr->first_chunks == 0 &&
594                    TOTAL_CHUNKS - (zhdr->last_chunks + zhdr->start_middle
595                                         + zhdr->middle_chunks) >=
596                         BIG_CHUNK_GAP) {
597                 unsigned short new_start = TOTAL_CHUNKS - zhdr->last_chunks -
598                         zhdr->middle_chunks;
599                 mchunk_memmove(zhdr, new_start);
600                 zhdr->start_middle = new_start;
601                 return 1;
602         }
603
604         return 0;
605 }
606
607 static void do_compact_page(struct z3fold_header *zhdr, bool locked)
608 {
609         struct z3fold_pool *pool = zhdr_to_pool(zhdr);
610         struct page *page;
611
612         page = virt_to_page(zhdr);
613         if (locked)
614                 WARN_ON(z3fold_page_trylock(zhdr));
615         else
616                 z3fold_page_lock(zhdr);
617         if (WARN_ON(!test_and_clear_bit(NEEDS_COMPACTING, &page->private))) {
618                 z3fold_page_unlock(zhdr);
619                 return;
620         }
621         spin_lock(&pool->lock);
622         list_del_init(&zhdr->buddy);
623         spin_unlock(&pool->lock);
624
625         if (kref_put(&zhdr->refcount, release_z3fold_page_locked)) {
626                 atomic64_dec(&pool->pages_nr);
627                 return;
628         }
629
630         if (unlikely(PageIsolated(page) ||
631                      test_bit(PAGE_STALE, &page->private))) {
632                 z3fold_page_unlock(zhdr);
633                 return;
634         }
635
636         z3fold_compact_page(zhdr);
637         add_to_unbuddied(pool, zhdr);
638         z3fold_page_unlock(zhdr);
639 }
640
641 static void compact_page_work(struct work_struct *w)
642 {
643         struct z3fold_header *zhdr = container_of(w, struct z3fold_header,
644                                                 work);
645
646         do_compact_page(zhdr, false);
647 }
648
649 /* returns _locked_ z3fold page header or NULL */
650 static inline struct z3fold_header *__z3fold_alloc(struct z3fold_pool *pool,
651                                                 size_t size, bool can_sleep)
652 {
653         struct z3fold_header *zhdr = NULL;
654         struct page *page;
655         struct list_head *unbuddied;
656         int chunks = size_to_chunks(size), i;
657
658 lookup:
659         /* First, try to find an unbuddied z3fold page. */
660         unbuddied = get_cpu_ptr(pool->unbuddied);
661         for_each_unbuddied_list(i, chunks) {
662                 struct list_head *l = &unbuddied[i];
663
664                 zhdr = list_first_entry_or_null(READ_ONCE(l),
665                                         struct z3fold_header, buddy);
666
667                 if (!zhdr)
668                         continue;
669
670                 /* Re-check under lock. */
671                 spin_lock(&pool->lock);
672                 l = &unbuddied[i];
673                 if (unlikely(zhdr != list_first_entry(READ_ONCE(l),
674                                                 struct z3fold_header, buddy)) ||
675                     !z3fold_page_trylock(zhdr)) {
676                         spin_unlock(&pool->lock);
677                         zhdr = NULL;
678                         put_cpu_ptr(pool->unbuddied);
679                         if (can_sleep)
680                                 cond_resched();
681                         goto lookup;
682                 }
683                 list_del_init(&zhdr->buddy);
684                 zhdr->cpu = -1;
685                 spin_unlock(&pool->lock);
686
687                 page = virt_to_page(zhdr);
688                 if (test_bit(NEEDS_COMPACTING, &page->private)) {
689                         z3fold_page_unlock(zhdr);
690                         zhdr = NULL;
691                         put_cpu_ptr(pool->unbuddied);
692                         if (can_sleep)
693                                 cond_resched();
694                         goto lookup;
695                 }
696
697                 /*
698                  * this page could not be removed from its unbuddied
699                  * list while pool lock was held, and then we've taken
700                  * page lock so kref_put could not be called before
701                  * we got here, so it's safe to just call kref_get()
702                  */
703                 kref_get(&zhdr->refcount);
704                 break;
705         }
706         put_cpu_ptr(pool->unbuddied);
707
708         if (!zhdr) {
709                 int cpu;
710
711                 /* look for _exact_ match on other cpus' lists */
712                 for_each_online_cpu(cpu) {
713                         struct list_head *l;
714
715                         unbuddied = per_cpu_ptr(pool->unbuddied, cpu);
716                         spin_lock(&pool->lock);
717                         l = &unbuddied[chunks];
718
719                         zhdr = list_first_entry_or_null(READ_ONCE(l),
720                                                 struct z3fold_header, buddy);
721
722                         if (!zhdr || !z3fold_page_trylock(zhdr)) {
723                                 spin_unlock(&pool->lock);
724                                 zhdr = NULL;
725                                 continue;
726                         }
727                         list_del_init(&zhdr->buddy);
728                         zhdr->cpu = -1;
729                         spin_unlock(&pool->lock);
730
731                         page = virt_to_page(zhdr);
732                         if (test_bit(NEEDS_COMPACTING, &page->private)) {
733                                 z3fold_page_unlock(zhdr);
734                                 zhdr = NULL;
735                                 if (can_sleep)
736                                         cond_resched();
737                                 continue;
738                         }
739                         kref_get(&zhdr->refcount);
740                         break;
741                 }
742         }
743
744         return zhdr;
745 }
746
747 /*
748  * API Functions
749  */
750
751 /**
752  * z3fold_create_pool() - create a new z3fold pool
753  * @name:       pool name
754  * @gfp:        gfp flags when allocating the z3fold pool structure
755  * @ops:        user-defined operations for the z3fold pool
756  *
757  * Return: pointer to the new z3fold pool or NULL if the metadata allocation
758  * failed.
759  */
760 static struct z3fold_pool *z3fold_create_pool(const char *name, gfp_t gfp,
761                 const struct z3fold_ops *ops)
762 {
763         struct z3fold_pool *pool = NULL;
764         int i, cpu;
765
766         pool = kzalloc(sizeof(struct z3fold_pool), gfp);
767         if (!pool)
768                 goto out;
769         pool->c_handle = kmem_cache_create("z3fold_handle",
770                                 sizeof(struct z3fold_buddy_slots),
771                                 SLOTS_ALIGN, 0, NULL);
772         if (!pool->c_handle)
773                 goto out_c;
774         spin_lock_init(&pool->lock);
775         spin_lock_init(&pool->stale_lock);
776         pool->unbuddied = __alloc_percpu(sizeof(struct list_head)*NCHUNKS, 2);
777         if (!pool->unbuddied)
778                 goto out_pool;
779         for_each_possible_cpu(cpu) {
780                 struct list_head *unbuddied =
781                                 per_cpu_ptr(pool->unbuddied, cpu);
782                 for_each_unbuddied_list(i, 0)
783                         INIT_LIST_HEAD(&unbuddied[i]);
784         }
785         INIT_LIST_HEAD(&pool->lru);
786         INIT_LIST_HEAD(&pool->stale);
787         atomic64_set(&pool->pages_nr, 0);
788         pool->name = name;
789         pool->compact_wq = create_singlethread_workqueue(pool->name);
790         if (!pool->compact_wq)
791                 goto out_unbuddied;
792         pool->release_wq = create_singlethread_workqueue(pool->name);
793         if (!pool->release_wq)
794                 goto out_wq;
795         if (z3fold_register_migration(pool))
796                 goto out_rwq;
797         INIT_WORK(&pool->work, free_pages_work);
798         pool->ops = ops;
799         return pool;
800
801 out_rwq:
802         destroy_workqueue(pool->release_wq);
803 out_wq:
804         destroy_workqueue(pool->compact_wq);
805 out_unbuddied:
806         free_percpu(pool->unbuddied);
807 out_pool:
808         kmem_cache_destroy(pool->c_handle);
809 out_c:
810         kfree(pool);
811 out:
812         return NULL;
813 }
814
815 /**
816  * z3fold_destroy_pool() - destroys an existing z3fold pool
817  * @pool:       the z3fold pool to be destroyed
818  *
819  * The pool should be emptied before this function is called.
820  */
821 static void z3fold_destroy_pool(struct z3fold_pool *pool)
822 {
823         kmem_cache_destroy(pool->c_handle);
824         z3fold_unregister_migration(pool);
825         destroy_workqueue(pool->release_wq);
826         destroy_workqueue(pool->compact_wq);
827         kfree(pool);
828 }
829
830 /**
831  * z3fold_alloc() - allocates a region of a given size
832  * @pool:       z3fold pool from which to allocate
833  * @size:       size in bytes of the desired allocation
834  * @gfp:        gfp flags used if the pool needs to grow
835  * @handle:     handle of the new allocation
836  *
837  * This function will attempt to find a free region in the pool large enough to
838  * satisfy the allocation request.  A search of the unbuddied lists is
839  * performed first. If no suitable free region is found, then a new page is
840  * allocated and added to the pool to satisfy the request.
841  *
842  * gfp should not set __GFP_HIGHMEM as highmem pages cannot be used
843  * as z3fold pool pages.
844  *
845  * Return: 0 if success and handle is set, otherwise -EINVAL if the size or
846  * gfp arguments are invalid or -ENOMEM if the pool was unable to allocate
847  * a new page.
848  */
849 static int z3fold_alloc(struct z3fold_pool *pool, size_t size, gfp_t gfp,
850                         unsigned long *handle)
851 {
852         int chunks = size_to_chunks(size);
853         struct z3fold_header *zhdr = NULL;
854         struct page *page = NULL;
855         enum buddy bud;
856         bool can_sleep = gfpflags_allow_blocking(gfp);
857
858         if (!size)
859                 return -EINVAL;
860
861         if (size > PAGE_SIZE)
862                 return -ENOSPC;
863
864         if (size > PAGE_SIZE - ZHDR_SIZE_ALIGNED - CHUNK_SIZE)
865                 bud = HEADLESS;
866         else {
867 retry:
868                 zhdr = __z3fold_alloc(pool, size, can_sleep);
869                 if (zhdr) {
870                         if (zhdr->first_chunks == 0) {
871                                 if (zhdr->middle_chunks != 0 &&
872                                     chunks >= zhdr->start_middle)
873                                         bud = LAST;
874                                 else
875                                         bud = FIRST;
876                         } else if (zhdr->last_chunks == 0)
877                                 bud = LAST;
878                         else if (zhdr->middle_chunks == 0)
879                                 bud = MIDDLE;
880                         else {
881                                 if (kref_put(&zhdr->refcount,
882                                              release_z3fold_page_locked))
883                                         atomic64_dec(&pool->pages_nr);
884                                 else
885                                         z3fold_page_unlock(zhdr);
886                                 pr_err("No free chunks in unbuddied\n");
887                                 WARN_ON(1);
888                                 goto retry;
889                         }
890                         page = virt_to_page(zhdr);
891                         goto found;
892                 }
893                 bud = FIRST;
894         }
895
896         page = NULL;
897         if (can_sleep) {
898                 spin_lock(&pool->stale_lock);
899                 zhdr = list_first_entry_or_null(&pool->stale,
900                                                 struct z3fold_header, buddy);
901                 /*
902                  * Before allocating a page, let's see if we can take one from
903                  * the stale pages list. cancel_work_sync() can sleep so we
904                  * limit this case to the contexts where we can sleep
905                  */
906                 if (zhdr) {
907                         list_del(&zhdr->buddy);
908                         spin_unlock(&pool->stale_lock);
909                         cancel_work_sync(&zhdr->work);
910                         page = virt_to_page(zhdr);
911                 } else {
912                         spin_unlock(&pool->stale_lock);
913                 }
914         }
915         if (!page)
916                 page = alloc_page(gfp);
917
918         if (!page)
919                 return -ENOMEM;
920
921         zhdr = init_z3fold_page(page, pool, gfp);
922         if (!zhdr) {
923                 __free_page(page);
924                 return -ENOMEM;
925         }
926         atomic64_inc(&pool->pages_nr);
927
928         if (bud == HEADLESS) {
929                 set_bit(PAGE_HEADLESS, &page->private);
930                 goto headless;
931         }
932         if (can_sleep) {
933                 lock_page(page);
934                 __SetPageMovable(page, pool->inode->i_mapping);
935                 unlock_page(page);
936         } else {
937                 if (trylock_page(page)) {
938                         __SetPageMovable(page, pool->inode->i_mapping);
939                         unlock_page(page);
940                 }
941         }
942         z3fold_page_lock(zhdr);
943
944 found:
945         if (bud == FIRST)
946                 zhdr->first_chunks = chunks;
947         else if (bud == LAST)
948                 zhdr->last_chunks = chunks;
949         else {
950                 zhdr->middle_chunks = chunks;
951                 zhdr->start_middle = zhdr->first_chunks + ZHDR_CHUNKS;
952         }
953         add_to_unbuddied(pool, zhdr);
954
955 headless:
956         spin_lock(&pool->lock);
957         /* Add/move z3fold page to beginning of LRU */
958         if (!list_empty(&page->lru))
959                 list_del(&page->lru);
960
961         list_add(&page->lru, &pool->lru);
962
963         *handle = encode_handle(zhdr, bud);
964         spin_unlock(&pool->lock);
965         if (bud != HEADLESS)
966                 z3fold_page_unlock(zhdr);
967
968         return 0;
969 }
970
971 /**
972  * z3fold_free() - frees the allocation associated with the given handle
973  * @pool:       pool in which the allocation resided
974  * @handle:     handle associated with the allocation returned by z3fold_alloc()
975  *
976  * In the case that the z3fold page in which the allocation resides is under
977  * reclaim, as indicated by the PG_reclaim flag being set, this function
978  * only sets the first|last_chunks to 0.  The page is actually freed
979  * once both buddies are evicted (see z3fold_reclaim_page() below).
980  */
981 static void z3fold_free(struct z3fold_pool *pool, unsigned long handle)
982 {
983         struct z3fold_header *zhdr;
984         struct page *page;
985         enum buddy bud;
986
987         zhdr = handle_to_z3fold_header(handle);
988         page = virt_to_page(zhdr);
989
990         if (test_bit(PAGE_HEADLESS, &page->private)) {
991                 /* if a headless page is under reclaim, just leave.
992                  * NB: we use test_and_set_bit for a reason: if the bit
993                  * has not been set before, we release this page
994                  * immediately so we don't care about its value any more.
995                  */
996                 if (!test_and_set_bit(PAGE_CLAIMED, &page->private)) {
997                         spin_lock(&pool->lock);
998                         list_del(&page->lru);
999                         spin_unlock(&pool->lock);
1000                         free_z3fold_page(page, true);
1001                         atomic64_dec(&pool->pages_nr);
1002                 }
1003                 return;
1004         }
1005
1006         /* Non-headless case */
1007         z3fold_page_lock(zhdr);
1008         bud = handle_to_buddy(handle);
1009
1010         switch (bud) {
1011         case FIRST:
1012                 zhdr->first_chunks = 0;
1013                 break;
1014         case MIDDLE:
1015                 zhdr->middle_chunks = 0;
1016                 break;
1017         case LAST:
1018                 zhdr->last_chunks = 0;
1019                 break;
1020         default:
1021                 pr_err("%s: unknown bud %d\n", __func__, bud);
1022                 WARN_ON(1);
1023                 z3fold_page_unlock(zhdr);
1024                 return;
1025         }
1026
1027         free_handle(handle);
1028         if (kref_put(&zhdr->refcount, release_z3fold_page_locked_list)) {
1029                 atomic64_dec(&pool->pages_nr);
1030                 return;
1031         }
1032         if (test_bit(PAGE_CLAIMED, &page->private)) {
1033                 z3fold_page_unlock(zhdr);
1034                 return;
1035         }
1036         if (unlikely(PageIsolated(page)) ||
1037             test_and_set_bit(NEEDS_COMPACTING, &page->private)) {
1038                 z3fold_page_unlock(zhdr);
1039                 return;
1040         }
1041         if (zhdr->cpu < 0 || !cpu_online(zhdr->cpu)) {
1042                 spin_lock(&pool->lock);
1043                 list_del_init(&zhdr->buddy);
1044                 spin_unlock(&pool->lock);
1045                 zhdr->cpu = -1;
1046                 kref_get(&zhdr->refcount);
1047                 do_compact_page(zhdr, true);
1048                 return;
1049         }
1050         kref_get(&zhdr->refcount);
1051         queue_work_on(zhdr->cpu, pool->compact_wq, &zhdr->work);
1052         z3fold_page_unlock(zhdr);
1053 }
1054
1055 /**
1056  * z3fold_reclaim_page() - evicts allocations from a pool page and frees it
1057  * @pool:       pool from which a page will attempt to be evicted
1058  * @retries:    number of pages on the LRU list for which eviction will
1059  *              be attempted before failing
1060  *
1061  * z3fold reclaim is different from normal system reclaim in that it is done
1062  * from the bottom, up. This is because only the bottom layer, z3fold, has
1063  * information on how the allocations are organized within each z3fold page.
1064  * This has the potential to create interesting locking situations between
1065  * z3fold and the user, however.
1066  *
1067  * To avoid these, this is how z3fold_reclaim_page() should be called:
1068  *
1069  * The user detects a page should be reclaimed and calls z3fold_reclaim_page().
1070  * z3fold_reclaim_page() will remove a z3fold page from the pool LRU list and
1071  * call the user-defined eviction handler with the pool and handle as
1072  * arguments.
1073  *
1074  * If the handle can not be evicted, the eviction handler should return
1075  * non-zero. z3fold_reclaim_page() will add the z3fold page back to the
1076  * appropriate list and try the next z3fold page on the LRU up to
1077  * a user defined number of retries.
1078  *
1079  * If the handle is successfully evicted, the eviction handler should
1080  * return 0 _and_ should have called z3fold_free() on the handle. z3fold_free()
1081  * contains logic to delay freeing the page if the page is under reclaim,
1082  * as indicated by the setting of the PG_reclaim flag on the underlying page.
1083  *
1084  * If all buddies in the z3fold page are successfully evicted, then the
1085  * z3fold page can be freed.
1086  *
1087  * Returns: 0 if page is successfully freed, otherwise -EINVAL if there are
1088  * no pages to evict or an eviction handler is not registered, -EAGAIN if
1089  * the retry limit was hit.
1090  */
1091 static int z3fold_reclaim_page(struct z3fold_pool *pool, unsigned int retries)
1092 {
1093         int i, ret = 0;
1094         struct z3fold_header *zhdr = NULL;
1095         struct page *page = NULL;
1096         struct list_head *pos;
1097         unsigned long first_handle = 0, middle_handle = 0, last_handle = 0;
1098
1099         spin_lock(&pool->lock);
1100         if (!pool->ops || !pool->ops->evict || retries == 0) {
1101                 spin_unlock(&pool->lock);
1102                 return -EINVAL;
1103         }
1104         for (i = 0; i < retries; i++) {
1105                 if (list_empty(&pool->lru)) {
1106                         spin_unlock(&pool->lock);
1107                         return -EINVAL;
1108                 }
1109                 list_for_each_prev(pos, &pool->lru) {
1110                         page = list_entry(pos, struct page, lru);
1111
1112                         /* this bit could have been set by free, in which case
1113                          * we pass over to the next page in the pool.
1114                          */
1115                         if (test_and_set_bit(PAGE_CLAIMED, &page->private))
1116                                 continue;
1117
1118                         if (unlikely(PageIsolated(page)))
1119                                 continue;
1120                         if (test_bit(PAGE_HEADLESS, &page->private))
1121                                 break;
1122
1123                         zhdr = page_address(page);
1124                         if (!z3fold_page_trylock(zhdr)) {
1125                                 zhdr = NULL;
1126                                 continue; /* can't evict at this point */
1127                         }
1128                         kref_get(&zhdr->refcount);
1129                         list_del_init(&zhdr->buddy);
1130                         zhdr->cpu = -1;
1131                         break;
1132                 }
1133
1134                 if (!zhdr)
1135                         break;
1136
1137                 list_del_init(&page->lru);
1138                 spin_unlock(&pool->lock);
1139
1140                 if (!test_bit(PAGE_HEADLESS, &page->private)) {
1141                         /*
1142                          * We need encode the handles before unlocking, since
1143                          * we can race with free that will set
1144                          * (first|last)_chunks to 0
1145                          */
1146                         first_handle = 0;
1147                         last_handle = 0;
1148                         middle_handle = 0;
1149                         if (zhdr->first_chunks)
1150                                 first_handle = encode_handle(zhdr, FIRST);
1151                         if (zhdr->middle_chunks)
1152                                 middle_handle = encode_handle(zhdr, MIDDLE);
1153                         if (zhdr->last_chunks)
1154                                 last_handle = encode_handle(zhdr, LAST);
1155                         /*
1156                          * it's safe to unlock here because we hold a
1157                          * reference to this page
1158                          */
1159                         z3fold_page_unlock(zhdr);
1160                 } else {
1161                         first_handle = encode_handle(zhdr, HEADLESS);
1162                         last_handle = middle_handle = 0;
1163                 }
1164
1165                 /* Issue the eviction callback(s) */
1166                 if (middle_handle) {
1167                         ret = pool->ops->evict(pool, middle_handle);
1168                         if (ret)
1169                                 goto next;
1170                 }
1171                 if (first_handle) {
1172                         ret = pool->ops->evict(pool, first_handle);
1173                         if (ret)
1174                                 goto next;
1175                 }
1176                 if (last_handle) {
1177                         ret = pool->ops->evict(pool, last_handle);
1178                         if (ret)
1179                                 goto next;
1180                 }
1181 next:
1182                 if (test_bit(PAGE_HEADLESS, &page->private)) {
1183                         if (ret == 0) {
1184                                 free_z3fold_page(page, true);
1185                                 atomic64_dec(&pool->pages_nr);
1186                                 return 0;
1187                         }
1188                         spin_lock(&pool->lock);
1189                         list_add(&page->lru, &pool->lru);
1190                         spin_unlock(&pool->lock);
1191                 } else {
1192                         z3fold_page_lock(zhdr);
1193                         clear_bit(PAGE_CLAIMED, &page->private);
1194                         if (kref_put(&zhdr->refcount,
1195                                         release_z3fold_page_locked)) {
1196                                 atomic64_dec(&pool->pages_nr);
1197                                 return 0;
1198                         }
1199                         /*
1200                          * if we are here, the page is still not completely
1201                          * free. Take the global pool lock then to be able
1202                          * to add it back to the lru list
1203                          */
1204                         spin_lock(&pool->lock);
1205                         list_add(&page->lru, &pool->lru);
1206                         spin_unlock(&pool->lock);
1207                         z3fold_page_unlock(zhdr);
1208                 }
1209
1210                 /* We started off locked to we need to lock the pool back */
1211                 spin_lock(&pool->lock);
1212         }
1213         spin_unlock(&pool->lock);
1214         return -EAGAIN;
1215 }
1216
1217 /**
1218  * z3fold_map() - maps the allocation associated with the given handle
1219  * @pool:       pool in which the allocation resides
1220  * @handle:     handle associated with the allocation to be mapped
1221  *
1222  * Extracts the buddy number from handle and constructs the pointer to the
1223  * correct starting chunk within the page.
1224  *
1225  * Returns: a pointer to the mapped allocation
1226  */
1227 static void *z3fold_map(struct z3fold_pool *pool, unsigned long handle)
1228 {
1229         struct z3fold_header *zhdr;
1230         struct page *page;
1231         void *addr;
1232         enum buddy buddy;
1233
1234         zhdr = handle_to_z3fold_header(handle);
1235         addr = zhdr;
1236         page = virt_to_page(zhdr);
1237
1238         if (test_bit(PAGE_HEADLESS, &page->private))
1239                 goto out;
1240
1241         z3fold_page_lock(zhdr);
1242         buddy = handle_to_buddy(handle);
1243         switch (buddy) {
1244         case FIRST:
1245                 addr += ZHDR_SIZE_ALIGNED;
1246                 break;
1247         case MIDDLE:
1248                 addr += zhdr->start_middle << CHUNK_SHIFT;
1249                 set_bit(MIDDLE_CHUNK_MAPPED, &page->private);
1250                 break;
1251         case LAST:
1252                 addr += PAGE_SIZE - (handle_to_chunks(handle) << CHUNK_SHIFT);
1253                 break;
1254         default:
1255                 pr_err("unknown buddy id %d\n", buddy);
1256                 WARN_ON(1);
1257                 addr = NULL;
1258                 break;
1259         }
1260
1261         if (addr)
1262                 zhdr->mapped_count++;
1263         z3fold_page_unlock(zhdr);
1264 out:
1265         return addr;
1266 }
1267
1268 /**
1269  * z3fold_unmap() - unmaps the allocation associated with the given handle
1270  * @pool:       pool in which the allocation resides
1271  * @handle:     handle associated with the allocation to be unmapped
1272  */
1273 static void z3fold_unmap(struct z3fold_pool *pool, unsigned long handle)
1274 {
1275         struct z3fold_header *zhdr;
1276         struct page *page;
1277         enum buddy buddy;
1278
1279         zhdr = handle_to_z3fold_header(handle);
1280         page = virt_to_page(zhdr);
1281
1282         if (test_bit(PAGE_HEADLESS, &page->private))
1283                 return;
1284
1285         z3fold_page_lock(zhdr);
1286         buddy = handle_to_buddy(handle);
1287         if (buddy == MIDDLE)
1288                 clear_bit(MIDDLE_CHUNK_MAPPED, &page->private);
1289         zhdr->mapped_count--;
1290         z3fold_page_unlock(zhdr);
1291 }
1292
1293 /**
1294  * z3fold_get_pool_size() - gets the z3fold pool size in pages
1295  * @pool:       pool whose size is being queried
1296  *
1297  * Returns: size in pages of the given pool.
1298  */
1299 static u64 z3fold_get_pool_size(struct z3fold_pool *pool)
1300 {
1301         return atomic64_read(&pool->pages_nr);
1302 }
1303
1304 static bool z3fold_page_isolate(struct page *page, isolate_mode_t mode)
1305 {
1306         struct z3fold_header *zhdr;
1307         struct z3fold_pool *pool;
1308
1309         VM_BUG_ON_PAGE(!PageMovable(page), page);
1310         VM_BUG_ON_PAGE(PageIsolated(page), page);
1311
1312         if (test_bit(PAGE_HEADLESS, &page->private))
1313                 return false;
1314
1315         zhdr = page_address(page);
1316         z3fold_page_lock(zhdr);
1317         if (test_bit(NEEDS_COMPACTING, &page->private) ||
1318             test_bit(PAGE_STALE, &page->private))
1319                 goto out;
1320
1321         pool = zhdr_to_pool(zhdr);
1322
1323         if (zhdr->mapped_count == 0) {
1324                 kref_get(&zhdr->refcount);
1325                 if (!list_empty(&zhdr->buddy))
1326                         list_del_init(&zhdr->buddy);
1327                 spin_lock(&pool->lock);
1328                 if (!list_empty(&page->lru))
1329                         list_del(&page->lru);
1330                 spin_unlock(&pool->lock);
1331                 z3fold_page_unlock(zhdr);
1332                 return true;
1333         }
1334 out:
1335         z3fold_page_unlock(zhdr);
1336         return false;
1337 }
1338
1339 static int z3fold_page_migrate(struct address_space *mapping, struct page *newpage,
1340                                struct page *page, enum migrate_mode mode)
1341 {
1342         struct z3fold_header *zhdr, *new_zhdr;
1343         struct z3fold_pool *pool;
1344         struct address_space *new_mapping;
1345
1346         VM_BUG_ON_PAGE(!PageMovable(page), page);
1347         VM_BUG_ON_PAGE(!PageIsolated(page), page);
1348         VM_BUG_ON_PAGE(!PageLocked(newpage), newpage);
1349
1350         zhdr = page_address(page);
1351         pool = zhdr_to_pool(zhdr);
1352
1353         if (!trylock_page(page))
1354                 return -EAGAIN;
1355
1356         if (!z3fold_page_trylock(zhdr)) {
1357                 unlock_page(page);
1358                 return -EAGAIN;
1359         }
1360         if (zhdr->mapped_count != 0) {
1361                 z3fold_page_unlock(zhdr);
1362                 unlock_page(page);
1363                 return -EBUSY;
1364         }
1365         new_zhdr = page_address(newpage);
1366         memcpy(new_zhdr, zhdr, PAGE_SIZE);
1367         newpage->private = page->private;
1368         page->private = 0;
1369         z3fold_page_unlock(zhdr);
1370         spin_lock_init(&new_zhdr->page_lock);
1371         new_mapping = page_mapping(page);
1372         __ClearPageMovable(page);
1373         ClearPagePrivate(page);
1374
1375         get_page(newpage);
1376         z3fold_page_lock(new_zhdr);
1377         if (new_zhdr->first_chunks)
1378                 encode_handle(new_zhdr, FIRST);
1379         if (new_zhdr->last_chunks)
1380                 encode_handle(new_zhdr, LAST);
1381         if (new_zhdr->middle_chunks)
1382                 encode_handle(new_zhdr, MIDDLE);
1383         set_bit(NEEDS_COMPACTING, &newpage->private);
1384         new_zhdr->cpu = smp_processor_id();
1385         spin_lock(&pool->lock);
1386         list_add(&newpage->lru, &pool->lru);
1387         spin_unlock(&pool->lock);
1388         __SetPageMovable(newpage, new_mapping);
1389         z3fold_page_unlock(new_zhdr);
1390
1391         queue_work_on(new_zhdr->cpu, pool->compact_wq, &new_zhdr->work);
1392
1393         page_mapcount_reset(page);
1394         unlock_page(page);
1395         put_page(page);
1396         return 0;
1397 }
1398
1399 static void z3fold_page_putback(struct page *page)
1400 {
1401         struct z3fold_header *zhdr;
1402         struct z3fold_pool *pool;
1403
1404         zhdr = page_address(page);
1405         pool = zhdr_to_pool(zhdr);
1406
1407         z3fold_page_lock(zhdr);
1408         if (!list_empty(&zhdr->buddy))
1409                 list_del_init(&zhdr->buddy);
1410         INIT_LIST_HEAD(&page->lru);
1411         if (kref_put(&zhdr->refcount, release_z3fold_page_locked)) {
1412                 atomic64_dec(&pool->pages_nr);
1413                 return;
1414         }
1415         spin_lock(&pool->lock);
1416         list_add(&page->lru, &pool->lru);
1417         spin_unlock(&pool->lock);
1418         z3fold_page_unlock(zhdr);
1419 }
1420
1421 static const struct address_space_operations z3fold_aops = {
1422         .isolate_page = z3fold_page_isolate,
1423         .migratepage = z3fold_page_migrate,
1424         .putback_page = z3fold_page_putback,
1425 };
1426
1427 /*****************
1428  * zpool
1429  ****************/
1430
1431 static int z3fold_zpool_evict(struct z3fold_pool *pool, unsigned long handle)
1432 {
1433         if (pool->zpool && pool->zpool_ops && pool->zpool_ops->evict)
1434                 return pool->zpool_ops->evict(pool->zpool, handle);
1435         else
1436                 return -ENOENT;
1437 }
1438
1439 static const struct z3fold_ops z3fold_zpool_ops = {
1440         .evict =        z3fold_zpool_evict
1441 };
1442
1443 static void *z3fold_zpool_create(const char *name, gfp_t gfp,
1444                                const struct zpool_ops *zpool_ops,
1445                                struct zpool *zpool)
1446 {
1447         struct z3fold_pool *pool;
1448
1449         pool = z3fold_create_pool(name, gfp,
1450                                 zpool_ops ? &z3fold_zpool_ops : NULL);
1451         if (pool) {
1452                 pool->zpool = zpool;
1453                 pool->zpool_ops = zpool_ops;
1454         }
1455         return pool;
1456 }
1457
1458 static void z3fold_zpool_destroy(void *pool)
1459 {
1460         z3fold_destroy_pool(pool);
1461 }
1462
1463 static int z3fold_zpool_malloc(void *pool, size_t size, gfp_t gfp,
1464                         unsigned long *handle)
1465 {
1466         return z3fold_alloc(pool, size, gfp, handle);
1467 }
1468 static void z3fold_zpool_free(void *pool, unsigned long handle)
1469 {
1470         z3fold_free(pool, handle);
1471 }
1472
1473 static int z3fold_zpool_shrink(void *pool, unsigned int pages,
1474                         unsigned int *reclaimed)
1475 {
1476         unsigned int total = 0;
1477         int ret = -EINVAL;
1478
1479         while (total < pages) {
1480                 ret = z3fold_reclaim_page(pool, 8);
1481                 if (ret < 0)
1482                         break;
1483                 total++;
1484         }
1485
1486         if (reclaimed)
1487                 *reclaimed = total;
1488
1489         return ret;
1490 }
1491
1492 static void *z3fold_zpool_map(void *pool, unsigned long handle,
1493                         enum zpool_mapmode mm)
1494 {
1495         return z3fold_map(pool, handle);
1496 }
1497 static void z3fold_zpool_unmap(void *pool, unsigned long handle)
1498 {
1499         z3fold_unmap(pool, handle);
1500 }
1501
1502 static u64 z3fold_zpool_total_size(void *pool)
1503 {
1504         return z3fold_get_pool_size(pool) * PAGE_SIZE;
1505 }
1506
1507 static struct zpool_driver z3fold_zpool_driver = {
1508         .type =         "z3fold",
1509         .owner =        THIS_MODULE,
1510         .create =       z3fold_zpool_create,
1511         .destroy =      z3fold_zpool_destroy,
1512         .malloc =       z3fold_zpool_malloc,
1513         .free =         z3fold_zpool_free,
1514         .shrink =       z3fold_zpool_shrink,
1515         .map =          z3fold_zpool_map,
1516         .unmap =        z3fold_zpool_unmap,
1517         .total_size =   z3fold_zpool_total_size,
1518 };
1519
1520 MODULE_ALIAS("zpool-z3fold");
1521
1522 static int __init init_z3fold(void)
1523 {
1524         int ret;
1525
1526         /* Make sure the z3fold header is not larger than the page size */
1527         BUILD_BUG_ON(ZHDR_SIZE_ALIGNED > PAGE_SIZE);
1528         ret = z3fold_mount();
1529         if (ret)
1530                 return ret;
1531
1532         zpool_register_driver(&z3fold_zpool_driver);
1533
1534         return 0;
1535 }
1536
1537 static void __exit exit_z3fold(void)
1538 {
1539         z3fold_unmount();
1540         zpool_unregister_driver(&z3fold_zpool_driver);
1541 }
1542
1543 module_init(init_z3fold);
1544 module_exit(exit_z3fold);
1545
1546 MODULE_LICENSE("GPL");
1547 MODULE_AUTHOR("Vitaly Wool <vitalywool@gmail.com>");
1548 MODULE_DESCRIPTION("3-Fold Allocator for Compressed Pages");