4 * Copyright (c) 2010,2011, Dan Magenheimer, Oracle Corp.
5 * Copyright (c) 2010,2011, Nitin Gupta
7 * Zcache provides an in-kernel "host implementation" for transcendent memory
8 * and, thus indirectly, for cleancache and frontswap. Zcache includes two
9 * page-accessible memory [1] interfaces, both utilizing lzo1x compression:
10 * 1) "compression buddies" ("zbud") is used for ephemeral pages
11 * 2) xvmalloc is used for persistent pages.
12 * Xvmalloc (based on the TLSF allocator) has very low fragmentation
13 * so maximizes space efficiency, while zbud allows pairs (and potentially,
14 * in the future, more than a pair of) compressed pages to be closely linked
15 * so that reclaiming can be done via the kernel's physical-page-oriented
16 * "shrinker" interface.
18 * [1] For a definition of page-accessible memory (aka PAM), see:
19 * http://marc.info/?l=linux-mm&m=127811271605009
22 #include <linux/cpu.h>
23 #include <linux/highmem.h>
24 #include <linux/list.h>
25 #include <linux/lzo.h>
26 #include <linux/slab.h>
27 #include <linux/spinlock.h>
28 #include <linux/types.h>
29 #include <linux/atomic.h>
32 #include "../zram/xvmalloc.h" /* if built in drivers/staging */
34 #if (!defined(CONFIG_CLEANCACHE) && !defined(CONFIG_FRONTSWAP))
35 #error "zcache is useless without CONFIG_CLEANCACHE or CONFIG_FRONTSWAP"
37 #ifdef CONFIG_CLEANCACHE
38 #include <linux/cleancache.h>
40 #ifdef CONFIG_FRONTSWAP
41 #include <linux/frontswap.h>
45 /* this is more aggressive but may cause other problems? */
46 #define ZCACHE_GFP_MASK (GFP_ATOMIC | __GFP_NORETRY | __GFP_NOWARN)
48 #define ZCACHE_GFP_MASK \
49 (__GFP_FS | __GFP_NORETRY | __GFP_NOWARN | __GFP_NOMEMALLOC)
52 #define MAX_POOLS_PER_CLIENT 16
54 #define MAX_CLIENTS 16
55 #define LOCAL_CLIENT ((uint16_t)-1)
56 struct zcache_client {
57 struct tmem_pool *tmem_pools[MAX_POOLS_PER_CLIENT];
58 struct xv_pool *xvpool;
63 static struct zcache_client zcache_host;
64 static struct zcache_client zcache_clients[MAX_CLIENTS];
66 static inline uint16_t get_client_id_from_client(struct zcache_client *cli)
69 if (cli == &zcache_host)
71 return cli - &zcache_clients[0];
74 static inline bool is_local_client(struct zcache_client *cli)
76 return cli == &zcache_host;
80 * Compression buddies ("zbud") provides for packing two (or, possibly
81 * in the future, more) compressed ephemeral pages into a single "raw"
82 * (physical) page and tracking them with data structures so that
83 * the raw pages can be easily reclaimed.
85 * A zbud page ("zbpg") is an aligned page containing a list_head,
86 * a lock, and two "zbud headers". The remainder of the physical
87 * page is divided up into aligned 64-byte "chunks" which contain
88 * the compressed data for zero, one, or two zbuds. Each zbpg
89 * resides on: (1) an "unused list" if it has no zbuds; (2) a
90 * "buddied" list if it is fully populated with two zbuds; or
91 * (3) one of PAGE_SIZE/64 "unbuddied" lists indexed by how many chunks
92 * the one unbuddied zbud uses. The data inside a zbpg cannot be
93 * read or written unless the zbpg's lock is held.
96 #define ZBH_SENTINEL 0x43214321
97 #define ZBPG_SENTINEL 0xdeadbeef
99 #define ZBUD_MAX_BUDS 2
106 uint16_t size; /* compressed size in bytes, zero means unused */
111 struct list_head bud_list;
113 struct zbud_hdr buddy[ZBUD_MAX_BUDS];
115 /* followed by NUM_CHUNK aligned CHUNK_SIZE-byte chunks */
118 #define CHUNK_SHIFT 6
119 #define CHUNK_SIZE (1 << CHUNK_SHIFT)
120 #define CHUNK_MASK (~(CHUNK_SIZE-1))
121 #define NCHUNKS (((PAGE_SIZE - sizeof(struct zbud_page)) & \
122 CHUNK_MASK) >> CHUNK_SHIFT)
123 #define MAX_CHUNK (NCHUNKS-1)
126 struct list_head list;
128 } zbud_unbuddied[NCHUNKS];
129 /* list N contains pages with N chunks USED and NCHUNKS-N unused */
130 /* element 0 is never used but optimizing that isn't worth it */
131 static unsigned long zbud_cumul_chunk_counts[NCHUNKS];
133 struct list_head zbud_buddied_list;
134 static unsigned long zcache_zbud_buddied_count;
136 /* protects the buddied list and all unbuddied lists */
137 static DEFINE_SPINLOCK(zbud_budlists_spinlock);
139 static LIST_HEAD(zbpg_unused_list);
140 static unsigned long zcache_zbpg_unused_list_count;
142 /* protects the unused page list */
143 static DEFINE_SPINLOCK(zbpg_unused_list_spinlock);
145 static atomic_t zcache_zbud_curr_raw_pages;
146 static atomic_t zcache_zbud_curr_zpages;
147 static unsigned long zcache_zbud_curr_zbytes;
148 static unsigned long zcache_zbud_cumul_zpages;
149 static unsigned long zcache_zbud_cumul_zbytes;
150 static unsigned long zcache_compress_poor;
151 static unsigned long zcache_mean_compress_poor;
153 /* forward references */
154 static void *zcache_get_free_page(void);
155 static void zcache_free_page(void *p);
158 * zbud helper functions
161 static inline unsigned zbud_max_buddy_size(void)
163 return MAX_CHUNK << CHUNK_SHIFT;
166 static inline unsigned zbud_size_to_chunks(unsigned size)
168 BUG_ON(size == 0 || size > zbud_max_buddy_size());
169 return (size + CHUNK_SIZE - 1) >> CHUNK_SHIFT;
172 static inline int zbud_budnum(struct zbud_hdr *zh)
174 unsigned offset = (unsigned long)zh & (PAGE_SIZE - 1);
175 struct zbud_page *zbpg = NULL;
176 unsigned budnum = -1U;
179 for (i = 0; i < ZBUD_MAX_BUDS; i++)
180 if (offset == offsetof(typeof(*zbpg), buddy[i])) {
184 BUG_ON(budnum == -1U);
188 static char *zbud_data(struct zbud_hdr *zh, unsigned size)
190 struct zbud_page *zbpg;
194 ASSERT_SENTINEL(zh, ZBH);
195 budnum = zbud_budnum(zh);
196 BUG_ON(size == 0 || size > zbud_max_buddy_size());
197 zbpg = container_of(zh, struct zbud_page, buddy[budnum]);
198 ASSERT_SPINLOCK(&zbpg->lock);
201 p += ((sizeof(struct zbud_page) + CHUNK_SIZE - 1) &
203 else if (budnum == 1)
204 p += PAGE_SIZE - ((size + CHUNK_SIZE - 1) & CHUNK_MASK);
209 * zbud raw page management
212 static struct zbud_page *zbud_alloc_raw_page(void)
214 struct zbud_page *zbpg = NULL;
215 struct zbud_hdr *zh0, *zh1;
218 /* if any pages on the zbpg list, use one */
219 spin_lock(&zbpg_unused_list_spinlock);
220 if (!list_empty(&zbpg_unused_list)) {
221 zbpg = list_first_entry(&zbpg_unused_list,
222 struct zbud_page, bud_list);
223 list_del_init(&zbpg->bud_list);
224 zcache_zbpg_unused_list_count--;
227 spin_unlock(&zbpg_unused_list_spinlock);
229 /* none on zbpg list, try to get a kernel page */
230 zbpg = zcache_get_free_page();
231 if (likely(zbpg != NULL)) {
232 INIT_LIST_HEAD(&zbpg->bud_list);
233 zh0 = &zbpg->buddy[0]; zh1 = &zbpg->buddy[1];
234 spin_lock_init(&zbpg->lock);
236 ASSERT_INVERTED_SENTINEL(zbpg, ZBPG);
237 SET_SENTINEL(zbpg, ZBPG);
238 BUG_ON(zh0->size != 0 || tmem_oid_valid(&zh0->oid));
239 BUG_ON(zh1->size != 0 || tmem_oid_valid(&zh1->oid));
241 atomic_inc(&zcache_zbud_curr_raw_pages);
242 INIT_LIST_HEAD(&zbpg->bud_list);
243 SET_SENTINEL(zbpg, ZBPG);
244 zh0->size = 0; zh1->size = 0;
245 tmem_oid_set_invalid(&zh0->oid);
246 tmem_oid_set_invalid(&zh1->oid);
252 static void zbud_free_raw_page(struct zbud_page *zbpg)
254 struct zbud_hdr *zh0 = &zbpg->buddy[0], *zh1 = &zbpg->buddy[1];
256 ASSERT_SENTINEL(zbpg, ZBPG);
257 BUG_ON(!list_empty(&zbpg->bud_list));
258 ASSERT_SPINLOCK(&zbpg->lock);
259 BUG_ON(zh0->size != 0 || tmem_oid_valid(&zh0->oid));
260 BUG_ON(zh1->size != 0 || tmem_oid_valid(&zh1->oid));
261 INVERT_SENTINEL(zbpg, ZBPG);
262 spin_unlock(&zbpg->lock);
263 spin_lock(&zbpg_unused_list_spinlock);
264 list_add(&zbpg->bud_list, &zbpg_unused_list);
265 zcache_zbpg_unused_list_count++;
266 spin_unlock(&zbpg_unused_list_spinlock);
270 * core zbud handling routines
273 static unsigned zbud_free(struct zbud_hdr *zh)
277 ASSERT_SENTINEL(zh, ZBH);
278 BUG_ON(!tmem_oid_valid(&zh->oid));
280 BUG_ON(zh->size == 0 || zh->size > zbud_max_buddy_size());
282 tmem_oid_set_invalid(&zh->oid);
283 INVERT_SENTINEL(zh, ZBH);
284 zcache_zbud_curr_zbytes -= size;
285 atomic_dec(&zcache_zbud_curr_zpages);
289 static void zbud_free_and_delist(struct zbud_hdr *zh)
292 struct zbud_hdr *zh_other;
293 unsigned budnum = zbud_budnum(zh), size;
294 struct zbud_page *zbpg =
295 container_of(zh, struct zbud_page, buddy[budnum]);
297 spin_lock(&zbpg->lock);
298 if (list_empty(&zbpg->bud_list)) {
299 /* ignore zombie page... see zbud_evict_pages() */
300 spin_unlock(&zbpg->lock);
303 size = zbud_free(zh);
304 ASSERT_SPINLOCK(&zbpg->lock);
305 zh_other = &zbpg->buddy[(budnum == 0) ? 1 : 0];
306 if (zh_other->size == 0) { /* was unbuddied: unlist and free */
307 chunks = zbud_size_to_chunks(size) ;
308 spin_lock(&zbud_budlists_spinlock);
309 BUG_ON(list_empty(&zbud_unbuddied[chunks].list));
310 list_del_init(&zbpg->bud_list);
311 zbud_unbuddied[chunks].count--;
312 spin_unlock(&zbud_budlists_spinlock);
313 zbud_free_raw_page(zbpg);
314 } else { /* was buddied: move remaining buddy to unbuddied list */
315 chunks = zbud_size_to_chunks(zh_other->size) ;
316 spin_lock(&zbud_budlists_spinlock);
317 list_del_init(&zbpg->bud_list);
318 zcache_zbud_buddied_count--;
319 list_add_tail(&zbpg->bud_list, &zbud_unbuddied[chunks].list);
320 zbud_unbuddied[chunks].count++;
321 spin_unlock(&zbud_budlists_spinlock);
322 spin_unlock(&zbpg->lock);
326 static struct zbud_hdr *zbud_create(uint16_t client_id, uint16_t pool_id,
327 struct tmem_oid *oid,
328 uint32_t index, struct page *page,
329 void *cdata, unsigned size)
331 struct zbud_hdr *zh0, *zh1, *zh = NULL;
332 struct zbud_page *zbpg = NULL, *ztmp;
335 int i, found_good_buddy = 0;
337 nchunks = zbud_size_to_chunks(size) ;
338 for (i = MAX_CHUNK - nchunks + 1; i > 0; i--) {
339 spin_lock(&zbud_budlists_spinlock);
340 if (!list_empty(&zbud_unbuddied[i].list)) {
341 list_for_each_entry_safe(zbpg, ztmp,
342 &zbud_unbuddied[i].list, bud_list) {
343 if (spin_trylock(&zbpg->lock)) {
344 found_good_buddy = i;
345 goto found_unbuddied;
349 spin_unlock(&zbud_budlists_spinlock);
351 /* didn't find a good buddy, try allocating a new page */
352 zbpg = zbud_alloc_raw_page();
353 if (unlikely(zbpg == NULL))
355 /* ok, have a page, now compress the data before taking locks */
356 spin_lock(&zbpg->lock);
357 spin_lock(&zbud_budlists_spinlock);
358 list_add_tail(&zbpg->bud_list, &zbud_unbuddied[nchunks].list);
359 zbud_unbuddied[nchunks].count++;
360 zh = &zbpg->buddy[0];
364 ASSERT_SPINLOCK(&zbpg->lock);
365 zh0 = &zbpg->buddy[0]; zh1 = &zbpg->buddy[1];
366 BUG_ON(!((zh0->size == 0) ^ (zh1->size == 0)));
367 if (zh0->size != 0) { /* buddy0 in use, buddy1 is vacant */
368 ASSERT_SENTINEL(zh0, ZBH);
370 } else if (zh1->size != 0) { /* buddy1 in use, buddy0 is vacant */
371 ASSERT_SENTINEL(zh1, ZBH);
375 list_del_init(&zbpg->bud_list);
376 zbud_unbuddied[found_good_buddy].count--;
377 list_add_tail(&zbpg->bud_list, &zbud_buddied_list);
378 zcache_zbud_buddied_count++;
381 SET_SENTINEL(zh, ZBH);
385 zh->pool_id = pool_id;
386 zh->client_id = client_id;
387 /* can wait to copy the data until the list locks are dropped */
388 spin_unlock(&zbud_budlists_spinlock);
390 to = zbud_data(zh, size);
391 memcpy(to, cdata, size);
392 spin_unlock(&zbpg->lock);
393 zbud_cumul_chunk_counts[nchunks]++;
394 atomic_inc(&zcache_zbud_curr_zpages);
395 zcache_zbud_cumul_zpages++;
396 zcache_zbud_curr_zbytes += size;
397 zcache_zbud_cumul_zbytes += size;
402 static int zbud_decompress(struct page *page, struct zbud_hdr *zh)
404 struct zbud_page *zbpg;
405 unsigned budnum = zbud_budnum(zh);
406 size_t out_len = PAGE_SIZE;
407 char *to_va, *from_va;
411 zbpg = container_of(zh, struct zbud_page, buddy[budnum]);
412 spin_lock(&zbpg->lock);
413 if (list_empty(&zbpg->bud_list)) {
414 /* ignore zombie page... see zbud_evict_pages() */
418 ASSERT_SENTINEL(zh, ZBH);
419 BUG_ON(zh->size == 0 || zh->size > zbud_max_buddy_size());
420 to_va = kmap_atomic(page, KM_USER0);
422 from_va = zbud_data(zh, size);
423 ret = lzo1x_decompress_safe(from_va, size, to_va, &out_len);
424 BUG_ON(ret != LZO_E_OK);
425 BUG_ON(out_len != PAGE_SIZE);
426 kunmap_atomic(to_va, KM_USER0);
428 spin_unlock(&zbpg->lock);
433 * The following routines handle shrinking of ephemeral pages by evicting
434 * pages "least valuable" first.
437 static unsigned long zcache_evicted_raw_pages;
438 static unsigned long zcache_evicted_buddied_pages;
439 static unsigned long zcache_evicted_unbuddied_pages;
441 static struct tmem_pool *zcache_get_pool_by_id(uint16_t cli_id,
443 static void zcache_put_pool(struct tmem_pool *pool);
446 * Flush and free all zbuds in a zbpg, then free the pageframe
448 static void zbud_evict_zbpg(struct zbud_page *zbpg)
452 uint32_t pool_id[ZBUD_MAX_BUDS], client_id[ZBUD_MAX_BUDS];
453 uint32_t index[ZBUD_MAX_BUDS];
454 struct tmem_oid oid[ZBUD_MAX_BUDS];
455 struct tmem_pool *pool;
457 ASSERT_SPINLOCK(&zbpg->lock);
458 BUG_ON(!list_empty(&zbpg->bud_list));
459 for (i = 0, j = 0; i < ZBUD_MAX_BUDS; i++) {
460 zh = &zbpg->buddy[i];
462 client_id[j] = zh->client_id;
463 pool_id[j] = zh->pool_id;
465 index[j] = zh->index;
470 spin_unlock(&zbpg->lock);
471 for (i = 0; i < j; i++) {
472 pool = zcache_get_pool_by_id(client_id[i], pool_id[i]);
474 tmem_flush_page(pool, &oid[i], index[i]);
475 zcache_put_pool(pool);
478 ASSERT_SENTINEL(zbpg, ZBPG);
479 spin_lock(&zbpg->lock);
480 zbud_free_raw_page(zbpg);
484 * Free nr pages. This code is funky because we want to hold the locks
485 * protecting various lists for as short a time as possible, and in some
486 * circumstances the list may change asynchronously when the list lock is
487 * not held. In some cases we also trylock not only to avoid waiting on a
488 * page in use by another cpu, but also to avoid potential deadlock due to
491 static void zbud_evict_pages(int nr)
493 struct zbud_page *zbpg;
496 /* first try freeing any pages on unused list */
498 spin_lock_bh(&zbpg_unused_list_spinlock);
499 if (!list_empty(&zbpg_unused_list)) {
500 /* can't walk list here, since it may change when unlocked */
501 zbpg = list_first_entry(&zbpg_unused_list,
502 struct zbud_page, bud_list);
503 list_del_init(&zbpg->bud_list);
504 zcache_zbpg_unused_list_count--;
505 atomic_dec(&zcache_zbud_curr_raw_pages);
506 spin_unlock_bh(&zbpg_unused_list_spinlock);
507 zcache_free_page(zbpg);
508 zcache_evicted_raw_pages++;
511 goto retry_unused_list;
513 spin_unlock_bh(&zbpg_unused_list_spinlock);
515 /* now try freeing unbuddied pages, starting with least space avail */
516 for (i = 0; i < MAX_CHUNK; i++) {
518 spin_lock_bh(&zbud_budlists_spinlock);
519 if (list_empty(&zbud_unbuddied[i].list)) {
520 spin_unlock_bh(&zbud_budlists_spinlock);
523 list_for_each_entry(zbpg, &zbud_unbuddied[i].list, bud_list) {
524 if (unlikely(!spin_trylock(&zbpg->lock)))
526 list_del_init(&zbpg->bud_list);
527 zbud_unbuddied[i].count--;
528 spin_unlock(&zbud_budlists_spinlock);
529 zcache_evicted_unbuddied_pages++;
530 /* want budlists unlocked when doing zbpg eviction */
531 zbud_evict_zbpg(zbpg);
535 goto retry_unbud_list_i;
537 spin_unlock_bh(&zbud_budlists_spinlock);
540 /* as a last resort, free buddied pages */
542 spin_lock_bh(&zbud_budlists_spinlock);
543 if (list_empty(&zbud_buddied_list)) {
544 spin_unlock_bh(&zbud_budlists_spinlock);
547 list_for_each_entry(zbpg, &zbud_buddied_list, bud_list) {
548 if (unlikely(!spin_trylock(&zbpg->lock)))
550 list_del_init(&zbpg->bud_list);
551 zcache_zbud_buddied_count--;
552 spin_unlock(&zbud_budlists_spinlock);
553 zcache_evicted_buddied_pages++;
554 /* want budlists unlocked when doing zbpg eviction */
555 zbud_evict_zbpg(zbpg);
561 spin_unlock_bh(&zbud_budlists_spinlock);
566 static void zbud_init(void)
570 INIT_LIST_HEAD(&zbud_buddied_list);
571 zcache_zbud_buddied_count = 0;
572 for (i = 0; i < NCHUNKS; i++) {
573 INIT_LIST_HEAD(&zbud_unbuddied[i].list);
574 zbud_unbuddied[i].count = 0;
580 * These sysfs routines show a nice distribution of how many zbpg's are
581 * currently (and have ever been placed) in each unbuddied list. It's fun
582 * to watch but can probably go away before final merge.
584 static int zbud_show_unbuddied_list_counts(char *buf)
589 for (i = 0; i < NCHUNKS; i++)
590 p += sprintf(p, "%u ", zbud_unbuddied[i].count);
594 static int zbud_show_cumul_chunk_counts(char *buf)
596 unsigned long i, chunks = 0, total_chunks = 0, sum_total_chunks = 0;
597 unsigned long total_chunks_lte_21 = 0, total_chunks_lte_32 = 0;
598 unsigned long total_chunks_lte_42 = 0;
601 for (i = 0; i < NCHUNKS; i++) {
602 p += sprintf(p, "%lu ", zbud_cumul_chunk_counts[i]);
603 chunks += zbud_cumul_chunk_counts[i];
604 total_chunks += zbud_cumul_chunk_counts[i];
605 sum_total_chunks += i * zbud_cumul_chunk_counts[i];
607 total_chunks_lte_21 = total_chunks;
609 total_chunks_lte_32 = total_chunks;
611 total_chunks_lte_42 = total_chunks;
613 p += sprintf(p, "<=21:%lu <=32:%lu <=42:%lu, mean:%lu\n",
614 total_chunks_lte_21, total_chunks_lte_32, total_chunks_lte_42,
615 chunks == 0 ? 0 : sum_total_chunks / chunks);
621 * This "zv" PAM implementation combines the TLSF-based xvMalloc
622 * with lzo1x compression to maximize the amount of data that can
623 * be packed into a physical page.
625 * Zv represents a PAM page with the index and object (plus a "size" value
626 * necessary for decompression) immediately preceding the compressed data.
629 #define ZVH_SENTINEL 0x43214321
638 /* rudimentary policy limits */
639 /* total number of persistent pages may not exceed this percentage */
640 static unsigned int zv_page_count_policy_percent = 75;
642 * byte count defining poor compression; pages with greater zsize will be
645 static unsigned int zv_max_zsize = (PAGE_SIZE / 8) * 7;
647 * byte count defining poor *mean* compression; pages with greater zsize
648 * will be rejected until sufficient better-compressed pages are accepted
649 * driving the man below this threshold
651 static unsigned int zv_max_mean_zsize = (PAGE_SIZE / 8) * 5;
653 static unsigned long zv_curr_dist_counts[NCHUNKS];
654 static unsigned long zv_cumul_dist_counts[NCHUNKS];
656 static struct zv_hdr *zv_create(struct xv_pool *xvpool, uint32_t pool_id,
657 struct tmem_oid *oid, uint32_t index,
658 void *cdata, unsigned clen)
661 struct zv_hdr *zv = NULL;
663 int alloc_size = clen + sizeof(struct zv_hdr);
664 int chunks = (alloc_size + (CHUNK_SIZE - 1)) >> CHUNK_SHIFT;
667 BUG_ON(!irqs_disabled());
668 BUG_ON(chunks >= NCHUNKS);
669 ret = xv_malloc(xvpool, alloc_size,
670 &page, &offset, ZCACHE_GFP_MASK);
673 zv_curr_dist_counts[chunks]++;
674 zv_cumul_dist_counts[chunks]++;
675 zv = kmap_atomic(page, KM_USER0) + offset;
678 zv->pool_id = pool_id;
679 SET_SENTINEL(zv, ZVH);
680 memcpy((char *)zv + sizeof(struct zv_hdr), cdata, clen);
681 kunmap_atomic(zv, KM_USER0);
686 static void zv_free(struct xv_pool *xvpool, struct zv_hdr *zv)
691 uint16_t size = xv_get_object_size(zv);
692 int chunks = (size + (CHUNK_SIZE - 1)) >> CHUNK_SHIFT;
694 ASSERT_SENTINEL(zv, ZVH);
695 BUG_ON(chunks >= NCHUNKS);
696 zv_curr_dist_counts[chunks]--;
699 INVERT_SENTINEL(zv, ZVH);
700 page = virt_to_page(zv);
701 offset = (unsigned long)zv & ~PAGE_MASK;
702 local_irq_save(flags);
703 xv_free(xvpool, page, offset);
704 local_irq_restore(flags);
707 static void zv_decompress(struct page *page, struct zv_hdr *zv)
709 size_t clen = PAGE_SIZE;
714 ASSERT_SENTINEL(zv, ZVH);
715 size = xv_get_object_size(zv) - sizeof(*zv);
717 to_va = kmap_atomic(page, KM_USER0);
718 ret = lzo1x_decompress_safe((char *)zv + sizeof(*zv),
720 kunmap_atomic(to_va, KM_USER0);
721 BUG_ON(ret != LZO_E_OK);
722 BUG_ON(clen != PAGE_SIZE);
727 * show a distribution of compression stats for zv pages.
730 static int zv_curr_dist_counts_show(char *buf)
732 unsigned long i, n, chunks = 0, sum_total_chunks = 0;
735 for (i = 0; i < NCHUNKS; i++) {
736 n = zv_curr_dist_counts[i];
737 p += sprintf(p, "%lu ", n);
739 sum_total_chunks += i * n;
741 p += sprintf(p, "mean:%lu\n",
742 chunks == 0 ? 0 : sum_total_chunks / chunks);
746 static int zv_cumul_dist_counts_show(char *buf)
748 unsigned long i, n, chunks = 0, sum_total_chunks = 0;
751 for (i = 0; i < NCHUNKS; i++) {
752 n = zv_cumul_dist_counts[i];
753 p += sprintf(p, "%lu ", n);
755 sum_total_chunks += i * n;
757 p += sprintf(p, "mean:%lu\n",
758 chunks == 0 ? 0 : sum_total_chunks / chunks);
763 * setting zv_max_zsize via sysfs causes all persistent (e.g. swap)
764 * pages that don't compress to less than this value (including metadata
765 * overhead) to be rejected. We don't allow the value to get too close
768 static ssize_t zv_max_zsize_show(struct kobject *kobj,
769 struct kobj_attribute *attr,
772 return sprintf(buf, "%u\n", zv_max_zsize);
775 static ssize_t zv_max_zsize_store(struct kobject *kobj,
776 struct kobj_attribute *attr,
777 const char *buf, size_t count)
782 if (!capable(CAP_SYS_ADMIN))
785 err = strict_strtoul(buf, 10, &val);
786 if (err || (val == 0) || (val > (PAGE_SIZE / 8) * 7))
793 * setting zv_max_mean_zsize via sysfs causes all persistent (e.g. swap)
794 * pages that don't compress to less than this value (including metadata
795 * overhead) to be rejected UNLESS the mean compression is also smaller
796 * than this value. In other words, we are load-balancing-by-zsize the
797 * accepted pages. Again, we don't allow the value to get too close
800 static ssize_t zv_max_mean_zsize_show(struct kobject *kobj,
801 struct kobj_attribute *attr,
804 return sprintf(buf, "%u\n", zv_max_mean_zsize);
807 static ssize_t zv_max_mean_zsize_store(struct kobject *kobj,
808 struct kobj_attribute *attr,
809 const char *buf, size_t count)
814 if (!capable(CAP_SYS_ADMIN))
817 err = strict_strtoul(buf, 10, &val);
818 if (err || (val == 0) || (val > (PAGE_SIZE / 8) * 7))
820 zv_max_mean_zsize = val;
825 * setting zv_page_count_policy_percent via sysfs sets an upper bound of
826 * persistent (e.g. swap) pages that will be retained according to:
827 * (zv_page_count_policy_percent * totalram_pages) / 100)
828 * when that limit is reached, further puts will be rejected (until
829 * some pages have been flushed). Note that, due to compression,
830 * this number may exceed 100; it defaults to 75 and we set an
831 * arbitary limit of 150. A poor choice will almost certainly result
832 * in OOM's, so this value should only be changed prudently.
834 static ssize_t zv_page_count_policy_percent_show(struct kobject *kobj,
835 struct kobj_attribute *attr,
838 return sprintf(buf, "%u\n", zv_page_count_policy_percent);
841 static ssize_t zv_page_count_policy_percent_store(struct kobject *kobj,
842 struct kobj_attribute *attr,
843 const char *buf, size_t count)
848 if (!capable(CAP_SYS_ADMIN))
851 err = strict_strtoul(buf, 10, &val);
852 if (err || (val == 0) || (val > 150))
854 zv_page_count_policy_percent = val;
858 static struct kobj_attribute zcache_zv_max_zsize_attr = {
859 .attr = { .name = "zv_max_zsize", .mode = 0644 },
860 .show = zv_max_zsize_show,
861 .store = zv_max_zsize_store,
864 static struct kobj_attribute zcache_zv_max_mean_zsize_attr = {
865 .attr = { .name = "zv_max_mean_zsize", .mode = 0644 },
866 .show = zv_max_mean_zsize_show,
867 .store = zv_max_mean_zsize_store,
870 static struct kobj_attribute zcache_zv_page_count_policy_percent_attr = {
871 .attr = { .name = "zv_page_count_policy_percent",
873 .show = zv_page_count_policy_percent_show,
874 .store = zv_page_count_policy_percent_store,
879 * zcache core code starts here
882 /* useful stats not collected by cleancache or frontswap */
883 static unsigned long zcache_flush_total;
884 static unsigned long zcache_flush_found;
885 static unsigned long zcache_flobj_total;
886 static unsigned long zcache_flobj_found;
887 static unsigned long zcache_failed_eph_puts;
888 static unsigned long zcache_failed_pers_puts;
891 * Tmem operations assume the poolid implies the invoking client.
892 * Zcache only has one client (the kernel itself): LOCAL_CLIENT.
893 * RAMster has each client numbered by cluster node, and a KVM version
894 * of zcache would have one client per guest and each client might
897 static struct tmem_pool *zcache_get_pool_by_id(uint16_t cli_id, uint16_t poolid)
899 struct tmem_pool *pool = NULL;
900 struct zcache_client *cli = NULL;
902 if (cli_id == LOCAL_CLIENT)
905 if (cli_id >= MAX_CLIENTS)
907 cli = &zcache_clients[cli_id];
910 atomic_inc(&cli->refcount);
912 if (poolid < MAX_POOLS_PER_CLIENT) {
913 pool = cli->tmem_pools[poolid];
915 atomic_inc(&pool->refcount);
921 static void zcache_put_pool(struct tmem_pool *pool)
923 struct zcache_client *cli = NULL;
928 atomic_dec(&pool->refcount);
929 atomic_dec(&cli->refcount);
932 int zcache_new_client(uint16_t cli_id)
934 struct zcache_client *cli = NULL;
937 if (cli_id == LOCAL_CLIENT)
939 else if ((unsigned int)cli_id < MAX_CLIENTS)
940 cli = &zcache_clients[cli_id];
946 #ifdef CONFIG_FRONTSWAP
947 cli->xvpool = xv_create_pool();
948 if (cli->xvpool == NULL)
956 /* counters for debugging */
957 static unsigned long zcache_failed_get_free_pages;
958 static unsigned long zcache_failed_alloc;
959 static unsigned long zcache_put_to_flush;
960 static unsigned long zcache_aborted_preload;
961 static unsigned long zcache_aborted_shrink;
964 * Ensure that memory allocation requests in zcache don't result
965 * in direct reclaim requests via the shrinker, which would cause
966 * an infinite loop. Maybe a GFP flag would be better?
968 static DEFINE_SPINLOCK(zcache_direct_reclaim_lock);
971 * for now, used named slabs so can easily track usage; later can
972 * either just use kmalloc, or perhaps add a slab-like allocator
973 * to more carefully manage total memory utilization
975 static struct kmem_cache *zcache_objnode_cache;
976 static struct kmem_cache *zcache_obj_cache;
977 static atomic_t zcache_curr_obj_count = ATOMIC_INIT(0);
978 static unsigned long zcache_curr_obj_count_max;
979 static atomic_t zcache_curr_objnode_count = ATOMIC_INIT(0);
980 static unsigned long zcache_curr_objnode_count_max;
983 * to avoid memory allocation recursion (e.g. due to direct reclaim), we
984 * preload all necessary data structures so the hostops callbacks never
985 * actually do a malloc
987 struct zcache_preload {
989 struct tmem_obj *obj;
991 struct tmem_objnode *objnodes[OBJNODE_TREE_MAX_PATH];
993 static DEFINE_PER_CPU(struct zcache_preload, zcache_preloads) = { 0, };
995 static int zcache_do_preload(struct tmem_pool *pool)
997 struct zcache_preload *kp;
998 struct tmem_objnode *objnode;
999 struct tmem_obj *obj;
1003 if (unlikely(zcache_objnode_cache == NULL))
1005 if (unlikely(zcache_obj_cache == NULL))
1007 if (!spin_trylock(&zcache_direct_reclaim_lock)) {
1008 zcache_aborted_preload++;
1012 kp = &__get_cpu_var(zcache_preloads);
1013 while (kp->nr < ARRAY_SIZE(kp->objnodes)) {
1014 preempt_enable_no_resched();
1015 objnode = kmem_cache_alloc(zcache_objnode_cache,
1017 if (unlikely(objnode == NULL)) {
1018 zcache_failed_alloc++;
1022 kp = &__get_cpu_var(zcache_preloads);
1023 if (kp->nr < ARRAY_SIZE(kp->objnodes))
1024 kp->objnodes[kp->nr++] = objnode;
1026 kmem_cache_free(zcache_objnode_cache, objnode);
1028 preempt_enable_no_resched();
1029 obj = kmem_cache_alloc(zcache_obj_cache, ZCACHE_GFP_MASK);
1030 if (unlikely(obj == NULL)) {
1031 zcache_failed_alloc++;
1034 page = (void *)__get_free_page(ZCACHE_GFP_MASK);
1035 if (unlikely(page == NULL)) {
1036 zcache_failed_get_free_pages++;
1037 kmem_cache_free(zcache_obj_cache, obj);
1041 kp = &__get_cpu_var(zcache_preloads);
1042 if (kp->obj == NULL)
1045 kmem_cache_free(zcache_obj_cache, obj);
1046 if (kp->page == NULL)
1049 free_page((unsigned long)page);
1052 spin_unlock(&zcache_direct_reclaim_lock);
1057 static void *zcache_get_free_page(void)
1059 struct zcache_preload *kp;
1062 kp = &__get_cpu_var(zcache_preloads);
1064 BUG_ON(page == NULL);
1069 static void zcache_free_page(void *p)
1071 free_page((unsigned long)p);
1075 * zcache implementation for tmem host ops
1078 static struct tmem_objnode *zcache_objnode_alloc(struct tmem_pool *pool)
1080 struct tmem_objnode *objnode = NULL;
1081 unsigned long count;
1082 struct zcache_preload *kp;
1084 kp = &__get_cpu_var(zcache_preloads);
1087 objnode = kp->objnodes[kp->nr - 1];
1088 BUG_ON(objnode == NULL);
1089 kp->objnodes[kp->nr - 1] = NULL;
1091 count = atomic_inc_return(&zcache_curr_objnode_count);
1092 if (count > zcache_curr_objnode_count_max)
1093 zcache_curr_objnode_count_max = count;
1098 static void zcache_objnode_free(struct tmem_objnode *objnode,
1099 struct tmem_pool *pool)
1101 atomic_dec(&zcache_curr_objnode_count);
1102 BUG_ON(atomic_read(&zcache_curr_objnode_count) < 0);
1103 kmem_cache_free(zcache_objnode_cache, objnode);
1106 static struct tmem_obj *zcache_obj_alloc(struct tmem_pool *pool)
1108 struct tmem_obj *obj = NULL;
1109 unsigned long count;
1110 struct zcache_preload *kp;
1112 kp = &__get_cpu_var(zcache_preloads);
1114 BUG_ON(obj == NULL);
1116 count = atomic_inc_return(&zcache_curr_obj_count);
1117 if (count > zcache_curr_obj_count_max)
1118 zcache_curr_obj_count_max = count;
1122 static void zcache_obj_free(struct tmem_obj *obj, struct tmem_pool *pool)
1124 atomic_dec(&zcache_curr_obj_count);
1125 BUG_ON(atomic_read(&zcache_curr_obj_count) < 0);
1126 kmem_cache_free(zcache_obj_cache, obj);
1129 static struct tmem_hostops zcache_hostops = {
1130 .obj_alloc = zcache_obj_alloc,
1131 .obj_free = zcache_obj_free,
1132 .objnode_alloc = zcache_objnode_alloc,
1133 .objnode_free = zcache_objnode_free,
1137 * zcache implementations for PAM page descriptor ops
1140 static atomic_t zcache_curr_eph_pampd_count = ATOMIC_INIT(0);
1141 static unsigned long zcache_curr_eph_pampd_count_max;
1142 static atomic_t zcache_curr_pers_pampd_count = ATOMIC_INIT(0);
1143 static unsigned long zcache_curr_pers_pampd_count_max;
1145 /* forward reference */
1146 static int zcache_compress(struct page *from, void **out_va, size_t *out_len);
1148 static void *zcache_pampd_create(char *data, size_t size, bool raw, int eph,
1149 struct tmem_pool *pool, struct tmem_oid *oid,
1152 void *pampd = NULL, *cdata;
1155 unsigned long count;
1156 struct page *page = virt_to_page(data);
1157 struct zcache_client *cli = pool->client;
1158 uint16_t client_id = get_client_id_from_client(cli);
1159 unsigned long zv_mean_zsize;
1160 unsigned long curr_pers_pampd_count;
1163 ret = zcache_compress(page, &cdata, &clen);
1166 if (clen == 0 || clen > zbud_max_buddy_size()) {
1167 zcache_compress_poor++;
1170 pampd = (void *)zbud_create(client_id, pool->pool_id, oid,
1171 index, page, cdata, clen);
1172 if (pampd != NULL) {
1173 count = atomic_inc_return(&zcache_curr_eph_pampd_count);
1174 if (count > zcache_curr_eph_pampd_count_max)
1175 zcache_curr_eph_pampd_count_max = count;
1178 curr_pers_pampd_count =
1179 atomic_read(&zcache_curr_pers_pampd_count);
1180 if (curr_pers_pampd_count >
1181 (zv_page_count_policy_percent * totalram_pages) / 100)
1183 ret = zcache_compress(page, &cdata, &clen);
1186 /* reject if compression is too poor */
1187 if (clen > zv_max_zsize) {
1188 zcache_compress_poor++;
1191 /* reject if mean compression is too poor */
1192 if ((clen > zv_max_mean_zsize) && (curr_pers_pampd_count > 0)) {
1193 zv_mean_zsize = xv_get_total_size_bytes(cli->xvpool) /
1194 curr_pers_pampd_count;
1195 if (zv_mean_zsize > zv_max_mean_zsize) {
1196 zcache_mean_compress_poor++;
1200 pampd = (void *)zv_create(cli->xvpool, pool->pool_id,
1201 oid, index, cdata, clen);
1204 count = atomic_inc_return(&zcache_curr_pers_pampd_count);
1205 if (count > zcache_curr_pers_pampd_count_max)
1206 zcache_curr_pers_pampd_count_max = count;
1213 * fill the pageframe corresponding to the struct page with the data
1214 * from the passed pampd
1216 static int zcache_pampd_get_data(char *data, size_t *bufsize, bool raw,
1217 void *pampd, struct tmem_pool *pool,
1218 struct tmem_oid *oid, uint32_t index)
1222 BUG_ON(is_ephemeral(pool));
1223 zv_decompress(virt_to_page(data), pampd);
1228 * fill the pageframe corresponding to the struct page with the data
1229 * from the passed pampd
1231 static int zcache_pampd_get_data_and_free(char *data, size_t *bufsize, bool raw,
1232 void *pampd, struct tmem_pool *pool,
1233 struct tmem_oid *oid, uint32_t index)
1237 BUG_ON(!is_ephemeral(pool));
1238 zbud_decompress(virt_to_page(data), pampd);
1239 zbud_free_and_delist((struct zbud_hdr *)pampd);
1240 atomic_dec(&zcache_curr_eph_pampd_count);
1245 * free the pampd and remove it from any zcache lists
1246 * pampd must no longer be pointed to from any tmem data structures!
1248 static void zcache_pampd_free(void *pampd, struct tmem_pool *pool,
1249 struct tmem_oid *oid, uint32_t index)
1251 struct zcache_client *cli = pool->client;
1253 if (is_ephemeral(pool)) {
1254 zbud_free_and_delist((struct zbud_hdr *)pampd);
1255 atomic_dec(&zcache_curr_eph_pampd_count);
1256 BUG_ON(atomic_read(&zcache_curr_eph_pampd_count) < 0);
1258 zv_free(cli->xvpool, (struct zv_hdr *)pampd);
1259 atomic_dec(&zcache_curr_pers_pampd_count);
1260 BUG_ON(atomic_read(&zcache_curr_pers_pampd_count) < 0);
1264 static void zcache_pampd_free_obj(struct tmem_pool *pool, struct tmem_obj *obj)
1268 static void zcache_pampd_new_obj(struct tmem_obj *obj)
1272 static int zcache_pampd_replace_in_obj(void *pampd, struct tmem_obj *obj)
1277 static bool zcache_pampd_is_remote(void *pampd)
1282 static struct tmem_pamops zcache_pamops = {
1283 .create = zcache_pampd_create,
1284 .get_data = zcache_pampd_get_data,
1285 .get_data_and_free = zcache_pampd_get_data_and_free,
1286 .free = zcache_pampd_free,
1287 .free_obj = zcache_pampd_free_obj,
1288 .new_obj = zcache_pampd_new_obj,
1289 .replace_in_obj = zcache_pampd_replace_in_obj,
1290 .is_remote = zcache_pampd_is_remote,
1294 * zcache compression/decompression and related per-cpu stuff
1297 #define LZO_WORKMEM_BYTES LZO1X_1_MEM_COMPRESS
1298 #define LZO_DSTMEM_PAGE_ORDER 1
1299 static DEFINE_PER_CPU(unsigned char *, zcache_workmem);
1300 static DEFINE_PER_CPU(unsigned char *, zcache_dstmem);
1302 static int zcache_compress(struct page *from, void **out_va, size_t *out_len)
1305 unsigned char *dmem = __get_cpu_var(zcache_dstmem);
1306 unsigned char *wmem = __get_cpu_var(zcache_workmem);
1309 BUG_ON(!irqs_disabled());
1310 if (unlikely(dmem == NULL || wmem == NULL))
1311 goto out; /* no buffer, so can't compress */
1312 from_va = kmap_atomic(from, KM_USER0);
1314 ret = lzo1x_1_compress(from_va, PAGE_SIZE, dmem, out_len, wmem);
1315 BUG_ON(ret != LZO_E_OK);
1317 kunmap_atomic(from_va, KM_USER0);
1324 static int zcache_cpu_notifier(struct notifier_block *nb,
1325 unsigned long action, void *pcpu)
1327 int cpu = (long)pcpu;
1328 struct zcache_preload *kp;
1331 case CPU_UP_PREPARE:
1332 per_cpu(zcache_dstmem, cpu) = (void *)__get_free_pages(
1333 GFP_KERNEL | __GFP_REPEAT,
1334 LZO_DSTMEM_PAGE_ORDER),
1335 per_cpu(zcache_workmem, cpu) =
1336 kzalloc(LZO1X_MEM_COMPRESS,
1337 GFP_KERNEL | __GFP_REPEAT);
1340 case CPU_UP_CANCELED:
1341 free_pages((unsigned long)per_cpu(zcache_dstmem, cpu),
1342 LZO_DSTMEM_PAGE_ORDER);
1343 per_cpu(zcache_dstmem, cpu) = NULL;
1344 kfree(per_cpu(zcache_workmem, cpu));
1345 per_cpu(zcache_workmem, cpu) = NULL;
1346 kp = &per_cpu(zcache_preloads, cpu);
1348 kmem_cache_free(zcache_objnode_cache,
1349 kp->objnodes[kp->nr - 1]);
1350 kp->objnodes[kp->nr - 1] = NULL;
1353 kmem_cache_free(zcache_obj_cache, kp->obj);
1354 free_page((unsigned long)kp->page);
1362 static struct notifier_block zcache_cpu_notifier_block = {
1363 .notifier_call = zcache_cpu_notifier
1367 #define ZCACHE_SYSFS_RO(_name) \
1368 static ssize_t zcache_##_name##_show(struct kobject *kobj, \
1369 struct kobj_attribute *attr, char *buf) \
1371 return sprintf(buf, "%lu\n", zcache_##_name); \
1373 static struct kobj_attribute zcache_##_name##_attr = { \
1374 .attr = { .name = __stringify(_name), .mode = 0444 }, \
1375 .show = zcache_##_name##_show, \
1378 #define ZCACHE_SYSFS_RO_ATOMIC(_name) \
1379 static ssize_t zcache_##_name##_show(struct kobject *kobj, \
1380 struct kobj_attribute *attr, char *buf) \
1382 return sprintf(buf, "%d\n", atomic_read(&zcache_##_name)); \
1384 static struct kobj_attribute zcache_##_name##_attr = { \
1385 .attr = { .name = __stringify(_name), .mode = 0444 }, \
1386 .show = zcache_##_name##_show, \
1389 #define ZCACHE_SYSFS_RO_CUSTOM(_name, _func) \
1390 static ssize_t zcache_##_name##_show(struct kobject *kobj, \
1391 struct kobj_attribute *attr, char *buf) \
1393 return _func(buf); \
1395 static struct kobj_attribute zcache_##_name##_attr = { \
1396 .attr = { .name = __stringify(_name), .mode = 0444 }, \
1397 .show = zcache_##_name##_show, \
1400 ZCACHE_SYSFS_RO(curr_obj_count_max);
1401 ZCACHE_SYSFS_RO(curr_objnode_count_max);
1402 ZCACHE_SYSFS_RO(flush_total);
1403 ZCACHE_SYSFS_RO(flush_found);
1404 ZCACHE_SYSFS_RO(flobj_total);
1405 ZCACHE_SYSFS_RO(flobj_found);
1406 ZCACHE_SYSFS_RO(failed_eph_puts);
1407 ZCACHE_SYSFS_RO(failed_pers_puts);
1408 ZCACHE_SYSFS_RO(zbud_curr_zbytes);
1409 ZCACHE_SYSFS_RO(zbud_cumul_zpages);
1410 ZCACHE_SYSFS_RO(zbud_cumul_zbytes);
1411 ZCACHE_SYSFS_RO(zbud_buddied_count);
1412 ZCACHE_SYSFS_RO(zbpg_unused_list_count);
1413 ZCACHE_SYSFS_RO(evicted_raw_pages);
1414 ZCACHE_SYSFS_RO(evicted_unbuddied_pages);
1415 ZCACHE_SYSFS_RO(evicted_buddied_pages);
1416 ZCACHE_SYSFS_RO(failed_get_free_pages);
1417 ZCACHE_SYSFS_RO(failed_alloc);
1418 ZCACHE_SYSFS_RO(put_to_flush);
1419 ZCACHE_SYSFS_RO(aborted_preload);
1420 ZCACHE_SYSFS_RO(aborted_shrink);
1421 ZCACHE_SYSFS_RO(compress_poor);
1422 ZCACHE_SYSFS_RO(mean_compress_poor);
1423 ZCACHE_SYSFS_RO_ATOMIC(zbud_curr_raw_pages);
1424 ZCACHE_SYSFS_RO_ATOMIC(zbud_curr_zpages);
1425 ZCACHE_SYSFS_RO_ATOMIC(curr_obj_count);
1426 ZCACHE_SYSFS_RO_ATOMIC(curr_objnode_count);
1427 ZCACHE_SYSFS_RO_CUSTOM(zbud_unbuddied_list_counts,
1428 zbud_show_unbuddied_list_counts);
1429 ZCACHE_SYSFS_RO_CUSTOM(zbud_cumul_chunk_counts,
1430 zbud_show_cumul_chunk_counts);
1431 ZCACHE_SYSFS_RO_CUSTOM(zv_curr_dist_counts,
1432 zv_curr_dist_counts_show);
1433 ZCACHE_SYSFS_RO_CUSTOM(zv_cumul_dist_counts,
1434 zv_cumul_dist_counts_show);
1436 static struct attribute *zcache_attrs[] = {
1437 &zcache_curr_obj_count_attr.attr,
1438 &zcache_curr_obj_count_max_attr.attr,
1439 &zcache_curr_objnode_count_attr.attr,
1440 &zcache_curr_objnode_count_max_attr.attr,
1441 &zcache_flush_total_attr.attr,
1442 &zcache_flobj_total_attr.attr,
1443 &zcache_flush_found_attr.attr,
1444 &zcache_flobj_found_attr.attr,
1445 &zcache_failed_eph_puts_attr.attr,
1446 &zcache_failed_pers_puts_attr.attr,
1447 &zcache_compress_poor_attr.attr,
1448 &zcache_mean_compress_poor_attr.attr,
1449 &zcache_zbud_curr_raw_pages_attr.attr,
1450 &zcache_zbud_curr_zpages_attr.attr,
1451 &zcache_zbud_curr_zbytes_attr.attr,
1452 &zcache_zbud_cumul_zpages_attr.attr,
1453 &zcache_zbud_cumul_zbytes_attr.attr,
1454 &zcache_zbud_buddied_count_attr.attr,
1455 &zcache_zbpg_unused_list_count_attr.attr,
1456 &zcache_evicted_raw_pages_attr.attr,
1457 &zcache_evicted_unbuddied_pages_attr.attr,
1458 &zcache_evicted_buddied_pages_attr.attr,
1459 &zcache_failed_get_free_pages_attr.attr,
1460 &zcache_failed_alloc_attr.attr,
1461 &zcache_put_to_flush_attr.attr,
1462 &zcache_aborted_preload_attr.attr,
1463 &zcache_aborted_shrink_attr.attr,
1464 &zcache_zbud_unbuddied_list_counts_attr.attr,
1465 &zcache_zbud_cumul_chunk_counts_attr.attr,
1466 &zcache_zv_curr_dist_counts_attr.attr,
1467 &zcache_zv_cumul_dist_counts_attr.attr,
1468 &zcache_zv_max_zsize_attr.attr,
1469 &zcache_zv_max_mean_zsize_attr.attr,
1470 &zcache_zv_page_count_policy_percent_attr.attr,
1474 static struct attribute_group zcache_attr_group = {
1475 .attrs = zcache_attrs,
1479 #endif /* CONFIG_SYSFS */
1481 * When zcache is disabled ("frozen"), pools can be created and destroyed,
1482 * but all puts (and thus all other operations that require memory allocation)
1483 * must fail. If zcache is unfrozen, accepts puts, then frozen again,
1484 * data consistency requires all puts while frozen to be converted into
1487 static bool zcache_freeze;
1490 * zcache shrinker interface (only useful for ephemeral pages, so zbud only)
1492 static int shrink_zcache_memory(struct shrinker *shrink,
1493 struct shrink_control *sc)
1496 int nr = sc->nr_to_scan;
1497 gfp_t gfp_mask = sc->gfp_mask;
1500 if (!(gfp_mask & __GFP_FS))
1501 /* does this case really need to be skipped? */
1503 if (spin_trylock(&zcache_direct_reclaim_lock)) {
1504 zbud_evict_pages(nr);
1505 spin_unlock(&zcache_direct_reclaim_lock);
1507 zcache_aborted_shrink++;
1509 ret = (int)atomic_read(&zcache_zbud_curr_raw_pages);
1514 static struct shrinker zcache_shrinker = {
1515 .shrink = shrink_zcache_memory,
1516 .seeks = DEFAULT_SEEKS,
1520 * zcache shims between cleancache/frontswap ops and tmem
1523 static int zcache_put_page(int cli_id, int pool_id, struct tmem_oid *oidp,
1524 uint32_t index, struct page *page)
1526 struct tmem_pool *pool;
1529 BUG_ON(!irqs_disabled());
1530 pool = zcache_get_pool_by_id(cli_id, pool_id);
1531 if (unlikely(pool == NULL))
1533 if (!zcache_freeze && zcache_do_preload(pool) == 0) {
1534 /* preload does preempt_disable on success */
1535 ret = tmem_put(pool, oidp, index, page_address(page),
1536 PAGE_SIZE, 0, is_ephemeral(pool));
1538 if (is_ephemeral(pool))
1539 zcache_failed_eph_puts++;
1541 zcache_failed_pers_puts++;
1543 zcache_put_pool(pool);
1544 preempt_enable_no_resched();
1546 zcache_put_to_flush++;
1547 if (atomic_read(&pool->obj_count) > 0)
1548 /* the put fails whether the flush succeeds or not */
1549 (void)tmem_flush_page(pool, oidp, index);
1550 zcache_put_pool(pool);
1556 static int zcache_get_page(int cli_id, int pool_id, struct tmem_oid *oidp,
1557 uint32_t index, struct page *page)
1559 struct tmem_pool *pool;
1561 unsigned long flags;
1562 size_t size = PAGE_SIZE;
1564 local_irq_save(flags);
1565 pool = zcache_get_pool_by_id(cli_id, pool_id);
1566 if (likely(pool != NULL)) {
1567 if (atomic_read(&pool->obj_count) > 0)
1568 ret = tmem_get(pool, oidp, index, page_address(page),
1569 &size, 0, is_ephemeral(pool));
1570 zcache_put_pool(pool);
1572 local_irq_restore(flags);
1576 static int zcache_flush_page(int cli_id, int pool_id,
1577 struct tmem_oid *oidp, uint32_t index)
1579 struct tmem_pool *pool;
1581 unsigned long flags;
1583 local_irq_save(flags);
1584 zcache_flush_total++;
1585 pool = zcache_get_pool_by_id(cli_id, pool_id);
1586 if (likely(pool != NULL)) {
1587 if (atomic_read(&pool->obj_count) > 0)
1588 ret = tmem_flush_page(pool, oidp, index);
1589 zcache_put_pool(pool);
1592 zcache_flush_found++;
1593 local_irq_restore(flags);
1597 static int zcache_flush_object(int cli_id, int pool_id,
1598 struct tmem_oid *oidp)
1600 struct tmem_pool *pool;
1602 unsigned long flags;
1604 local_irq_save(flags);
1605 zcache_flobj_total++;
1606 pool = zcache_get_pool_by_id(cli_id, pool_id);
1607 if (likely(pool != NULL)) {
1608 if (atomic_read(&pool->obj_count) > 0)
1609 ret = tmem_flush_object(pool, oidp);
1610 zcache_put_pool(pool);
1613 zcache_flobj_found++;
1614 local_irq_restore(flags);
1618 static int zcache_destroy_pool(int cli_id, int pool_id)
1620 struct tmem_pool *pool = NULL;
1621 struct zcache_client *cli = NULL;
1626 if (cli_id == LOCAL_CLIENT)
1628 else if ((unsigned int)cli_id < MAX_CLIENTS)
1629 cli = &zcache_clients[cli_id];
1632 atomic_inc(&cli->refcount);
1633 pool = cli->tmem_pools[pool_id];
1636 cli->tmem_pools[pool_id] = NULL;
1637 /* wait for pool activity on other cpus to quiesce */
1638 while (atomic_read(&pool->refcount) != 0)
1640 atomic_dec(&cli->refcount);
1642 ret = tmem_destroy_pool(pool);
1645 pr_info("zcache: destroyed pool id=%d, cli_id=%d\n",
1651 static int zcache_new_pool(uint16_t cli_id, uint32_t flags)
1654 struct tmem_pool *pool;
1655 struct zcache_client *cli = NULL;
1657 if (cli_id == LOCAL_CLIENT)
1659 else if ((unsigned int)cli_id < MAX_CLIENTS)
1660 cli = &zcache_clients[cli_id];
1663 atomic_inc(&cli->refcount);
1664 pool = kmalloc(sizeof(struct tmem_pool), GFP_KERNEL);
1666 pr_info("zcache: pool creation failed: out of memory\n");
1670 for (poolid = 0; poolid < MAX_POOLS_PER_CLIENT; poolid++)
1671 if (cli->tmem_pools[poolid] == NULL)
1673 if (poolid >= MAX_POOLS_PER_CLIENT) {
1674 pr_info("zcache: pool creation failed: max exceeded\n");
1679 atomic_set(&pool->refcount, 0);
1681 pool->pool_id = poolid;
1682 tmem_new_pool(pool, flags);
1683 cli->tmem_pools[poolid] = pool;
1684 pr_info("zcache: created %s tmem pool, id=%d, client=%d\n",
1685 flags & TMEM_POOL_PERSIST ? "persistent" : "ephemeral",
1689 atomic_dec(&cli->refcount);
1694 * Two kernel functionalities currently can be layered on top of tmem.
1695 * These are "cleancache" which is used as a second-chance cache for clean
1696 * page cache pages; and "frontswap" which is used for swap pages
1697 * to avoid writes to disk. A generic "shim" is provided here for each
1698 * to translate in-kernel semantics to zcache semantics.
1701 #ifdef CONFIG_CLEANCACHE
1702 static void zcache_cleancache_put_page(int pool_id,
1703 struct cleancache_filekey key,
1704 pgoff_t index, struct page *page)
1706 u32 ind = (u32) index;
1707 struct tmem_oid oid = *(struct tmem_oid *)&key;
1709 if (likely(ind == index))
1710 (void)zcache_put_page(LOCAL_CLIENT, pool_id, &oid, index, page);
1713 static int zcache_cleancache_get_page(int pool_id,
1714 struct cleancache_filekey key,
1715 pgoff_t index, struct page *page)
1717 u32 ind = (u32) index;
1718 struct tmem_oid oid = *(struct tmem_oid *)&key;
1721 if (likely(ind == index))
1722 ret = zcache_get_page(LOCAL_CLIENT, pool_id, &oid, index, page);
1726 static void zcache_cleancache_flush_page(int pool_id,
1727 struct cleancache_filekey key,
1730 u32 ind = (u32) index;
1731 struct tmem_oid oid = *(struct tmem_oid *)&key;
1733 if (likely(ind == index))
1734 (void)zcache_flush_page(LOCAL_CLIENT, pool_id, &oid, ind);
1737 static void zcache_cleancache_flush_inode(int pool_id,
1738 struct cleancache_filekey key)
1740 struct tmem_oid oid = *(struct tmem_oid *)&key;
1742 (void)zcache_flush_object(LOCAL_CLIENT, pool_id, &oid);
1745 static void zcache_cleancache_flush_fs(int pool_id)
1748 (void)zcache_destroy_pool(LOCAL_CLIENT, pool_id);
1751 static int zcache_cleancache_init_fs(size_t pagesize)
1753 BUG_ON(sizeof(struct cleancache_filekey) !=
1754 sizeof(struct tmem_oid));
1755 BUG_ON(pagesize != PAGE_SIZE);
1756 return zcache_new_pool(LOCAL_CLIENT, 0);
1759 static int zcache_cleancache_init_shared_fs(char *uuid, size_t pagesize)
1761 /* shared pools are unsupported and map to private */
1762 BUG_ON(sizeof(struct cleancache_filekey) !=
1763 sizeof(struct tmem_oid));
1764 BUG_ON(pagesize != PAGE_SIZE);
1765 return zcache_new_pool(LOCAL_CLIENT, 0);
1768 static struct cleancache_ops zcache_cleancache_ops = {
1769 .put_page = zcache_cleancache_put_page,
1770 .get_page = zcache_cleancache_get_page,
1771 .flush_page = zcache_cleancache_flush_page,
1772 .flush_inode = zcache_cleancache_flush_inode,
1773 .flush_fs = zcache_cleancache_flush_fs,
1774 .init_shared_fs = zcache_cleancache_init_shared_fs,
1775 .init_fs = zcache_cleancache_init_fs
1778 struct cleancache_ops zcache_cleancache_register_ops(void)
1780 struct cleancache_ops old_ops =
1781 cleancache_register_ops(&zcache_cleancache_ops);
1787 #ifdef CONFIG_FRONTSWAP
1788 /* a single tmem poolid is used for all frontswap "types" (swapfiles) */
1789 static int zcache_frontswap_poolid = -1;
1792 * Swizzling increases objects per swaptype, increasing tmem concurrency
1793 * for heavy swaploads. Later, larger nr_cpus -> larger SWIZ_BITS
1796 #define SWIZ_MASK ((1 << SWIZ_BITS) - 1)
1797 #define _oswiz(_type, _ind) ((_type << SWIZ_BITS) | (_ind & SWIZ_MASK))
1798 #define iswiz(_ind) (_ind >> SWIZ_BITS)
1800 static inline struct tmem_oid oswiz(unsigned type, u32 ind)
1802 struct tmem_oid oid = { .oid = { 0 } };
1803 oid.oid[0] = _oswiz(type, ind);
1807 static int zcache_frontswap_put_page(unsigned type, pgoff_t offset,
1810 u64 ind64 = (u64)offset;
1811 u32 ind = (u32)offset;
1812 struct tmem_oid oid = oswiz(type, ind);
1814 unsigned long flags;
1816 BUG_ON(!PageLocked(page));
1817 if (likely(ind64 == ind)) {
1818 local_irq_save(flags);
1819 ret = zcache_put_page(LOCAL_CLIENT, zcache_frontswap_poolid,
1820 &oid, iswiz(ind), page);
1821 local_irq_restore(flags);
1826 /* returns 0 if the page was successfully gotten from frontswap, -1 if
1827 * was not present (should never happen!) */
1828 static int zcache_frontswap_get_page(unsigned type, pgoff_t offset,
1831 u64 ind64 = (u64)offset;
1832 u32 ind = (u32)offset;
1833 struct tmem_oid oid = oswiz(type, ind);
1836 BUG_ON(!PageLocked(page));
1837 if (likely(ind64 == ind))
1838 ret = zcache_get_page(LOCAL_CLIENT, zcache_frontswap_poolid,
1839 &oid, iswiz(ind), page);
1843 /* flush a single page from frontswap */
1844 static void zcache_frontswap_flush_page(unsigned type, pgoff_t offset)
1846 u64 ind64 = (u64)offset;
1847 u32 ind = (u32)offset;
1848 struct tmem_oid oid = oswiz(type, ind);
1850 if (likely(ind64 == ind))
1851 (void)zcache_flush_page(LOCAL_CLIENT, zcache_frontswap_poolid,
1855 /* flush all pages from the passed swaptype */
1856 static void zcache_frontswap_flush_area(unsigned type)
1858 struct tmem_oid oid;
1861 for (ind = SWIZ_MASK; ind >= 0; ind--) {
1862 oid = oswiz(type, ind);
1863 (void)zcache_flush_object(LOCAL_CLIENT,
1864 zcache_frontswap_poolid, &oid);
1868 static void zcache_frontswap_init(unsigned ignored)
1870 /* a single tmem poolid is used for all frontswap "types" (swapfiles) */
1871 if (zcache_frontswap_poolid < 0)
1872 zcache_frontswap_poolid =
1873 zcache_new_pool(LOCAL_CLIENT, TMEM_POOL_PERSIST);
1876 static struct frontswap_ops zcache_frontswap_ops = {
1877 .put_page = zcache_frontswap_put_page,
1878 .get_page = zcache_frontswap_get_page,
1879 .flush_page = zcache_frontswap_flush_page,
1880 .flush_area = zcache_frontswap_flush_area,
1881 .init = zcache_frontswap_init
1884 struct frontswap_ops zcache_frontswap_register_ops(void)
1886 struct frontswap_ops old_ops =
1887 frontswap_register_ops(&zcache_frontswap_ops);
1894 * zcache initialization
1895 * NOTE FOR NOW zcache MUST BE PROVIDED AS A KERNEL BOOT PARAMETER OR
1899 static int zcache_enabled;
1901 static int __init enable_zcache(char *s)
1906 __setup("zcache", enable_zcache);
1908 /* allow independent dynamic disabling of cleancache and frontswap */
1910 static int use_cleancache = 1;
1912 static int __init no_cleancache(char *s)
1918 __setup("nocleancache", no_cleancache);
1920 static int use_frontswap = 1;
1922 static int __init no_frontswap(char *s)
1928 __setup("nofrontswap", no_frontswap);
1930 static int __init zcache_init(void)
1935 ret = sysfs_create_group(mm_kobj, &zcache_attr_group);
1937 pr_err("zcache: can't create sysfs\n");
1940 #endif /* CONFIG_SYSFS */
1941 #if defined(CONFIG_CLEANCACHE) || defined(CONFIG_FRONTSWAP)
1942 if (zcache_enabled) {
1945 tmem_register_hostops(&zcache_hostops);
1946 tmem_register_pamops(&zcache_pamops);
1947 ret = register_cpu_notifier(&zcache_cpu_notifier_block);
1949 pr_err("zcache: can't register cpu notifier\n");
1952 for_each_online_cpu(cpu) {
1953 void *pcpu = (void *)(long)cpu;
1954 zcache_cpu_notifier(&zcache_cpu_notifier_block,
1955 CPU_UP_PREPARE, pcpu);
1958 zcache_objnode_cache = kmem_cache_create("zcache_objnode",
1959 sizeof(struct tmem_objnode), 0, 0, NULL);
1960 zcache_obj_cache = kmem_cache_create("zcache_obj",
1961 sizeof(struct tmem_obj), 0, 0, NULL);
1962 ret = zcache_new_client(LOCAL_CLIENT);
1964 pr_err("zcache: can't create client\n");
1968 #ifdef CONFIG_CLEANCACHE
1969 if (zcache_enabled && use_cleancache) {
1970 struct cleancache_ops old_ops;
1973 register_shrinker(&zcache_shrinker);
1974 old_ops = zcache_cleancache_register_ops();
1975 pr_info("zcache: cleancache enabled using kernel "
1976 "transcendent memory and compression buddies\n");
1977 if (old_ops.init_fs != NULL)
1978 pr_warning("zcache: cleancache_ops overridden");
1981 #ifdef CONFIG_FRONTSWAP
1982 if (zcache_enabled && use_frontswap) {
1983 struct frontswap_ops old_ops;
1985 old_ops = zcache_frontswap_register_ops();
1986 pr_info("zcache: frontswap enabled using kernel "
1987 "transcendent memory and xvmalloc\n");
1988 if (old_ops.init != NULL)
1989 pr_warning("ktmem: frontswap_ops overridden");
1996 module_init(zcache_init)