oom: task->mm == NULL doesn't mean the memory was freed
[pandora-kernel.git] / drivers / staging / zcache / zcache.c
1 /*
2  * zcache.c
3  *
4  * Copyright (c) 2010,2011, Dan Magenheimer, Oracle Corp.
5  * Copyright (c) 2010,2011, Nitin Gupta
6  *
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.
17  *
18  * [1] For a definition of page-accessible memory (aka PAM), see:
19  *   http://marc.info/?l=linux-mm&m=127811271605009
20  */
21
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>
30 #include "tmem.h"
31
32 #include "../zram/xvmalloc.h" /* if built in drivers/staging */
33
34 #if (!defined(CONFIG_CLEANCACHE) && !defined(CONFIG_FRONTSWAP))
35 #error "zcache is useless without CONFIG_CLEANCACHE or CONFIG_FRONTSWAP"
36 #endif
37 #ifdef CONFIG_CLEANCACHE
38 #include <linux/cleancache.h>
39 #endif
40 #ifdef CONFIG_FRONTSWAP
41 #include <linux/frontswap.h>
42 #endif
43
44 #if 0
45 /* this is more aggressive but may cause other problems? */
46 #define ZCACHE_GFP_MASK (GFP_ATOMIC | __GFP_NORETRY | __GFP_NOWARN)
47 #else
48 #define ZCACHE_GFP_MASK \
49         (__GFP_FS | __GFP_NORETRY | __GFP_NOWARN | __GFP_NOMEMALLOC)
50 #endif
51
52 #define MAX_POOLS_PER_CLIENT 16
53
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;
59         bool allocated;
60         atomic_t refcount;
61 };
62
63 static struct zcache_client zcache_host;
64 static struct zcache_client zcache_clients[MAX_CLIENTS];
65
66 static inline uint16_t get_client_id_from_client(struct zcache_client *cli)
67 {
68         BUG_ON(cli == NULL);
69         if (cli == &zcache_host)
70                 return LOCAL_CLIENT;
71         return cli - &zcache_clients[0];
72 }
73
74 static inline bool is_local_client(struct zcache_client *cli)
75 {
76         return cli == &zcache_host;
77 }
78
79 /**********
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.
84  *
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.
94  */
95
96 #define ZBH_SENTINEL  0x43214321
97 #define ZBPG_SENTINEL  0xdeadbeef
98
99 #define ZBUD_MAX_BUDS 2
100
101 struct zbud_hdr {
102         uint16_t client_id;
103         uint16_t pool_id;
104         struct tmem_oid oid;
105         uint32_t index;
106         uint16_t size; /* compressed size in bytes, zero means unused */
107         DECL_SENTINEL
108 };
109
110 struct zbud_page {
111         struct list_head bud_list;
112         spinlock_t lock;
113         struct zbud_hdr buddy[ZBUD_MAX_BUDS];
114         DECL_SENTINEL
115         /* followed by NUM_CHUNK aligned CHUNK_SIZE-byte chunks */
116 };
117
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)
124
125 static struct {
126         struct list_head list;
127         unsigned count;
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];
132
133 struct list_head zbud_buddied_list;
134 static unsigned long zcache_zbud_buddied_count;
135
136 /* protects the buddied list and all unbuddied lists */
137 static DEFINE_SPINLOCK(zbud_budlists_spinlock);
138
139 static LIST_HEAD(zbpg_unused_list);
140 static unsigned long zcache_zbpg_unused_list_count;
141
142 /* protects the unused page list */
143 static DEFINE_SPINLOCK(zbpg_unused_list_spinlock);
144
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;
152
153 /* forward references */
154 static void *zcache_get_free_page(void);
155 static void zcache_free_page(void *p);
156
157 /*
158  * zbud helper functions
159  */
160
161 static inline unsigned zbud_max_buddy_size(void)
162 {
163         return MAX_CHUNK << CHUNK_SHIFT;
164 }
165
166 static inline unsigned zbud_size_to_chunks(unsigned size)
167 {
168         BUG_ON(size == 0 || size > zbud_max_buddy_size());
169         return (size + CHUNK_SIZE - 1) >> CHUNK_SHIFT;
170 }
171
172 static inline int zbud_budnum(struct zbud_hdr *zh)
173 {
174         unsigned offset = (unsigned long)zh & (PAGE_SIZE - 1);
175         struct zbud_page *zbpg = NULL;
176         unsigned budnum = -1U;
177         int i;
178
179         for (i = 0; i < ZBUD_MAX_BUDS; i++)
180                 if (offset == offsetof(typeof(*zbpg), buddy[i])) {
181                         budnum = i;
182                         break;
183                 }
184         BUG_ON(budnum == -1U);
185         return budnum;
186 }
187
188 static char *zbud_data(struct zbud_hdr *zh, unsigned size)
189 {
190         struct zbud_page *zbpg;
191         char *p;
192         unsigned budnum;
193
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);
199         p = (char *)zbpg;
200         if (budnum == 0)
201                 p += ((sizeof(struct zbud_page) + CHUNK_SIZE - 1) &
202                                                         CHUNK_MASK);
203         else if (budnum == 1)
204                 p += PAGE_SIZE - ((size + CHUNK_SIZE - 1) & CHUNK_MASK);
205         return p;
206 }
207
208 /*
209  * zbud raw page management
210  */
211
212 static struct zbud_page *zbud_alloc_raw_page(void)
213 {
214         struct zbud_page *zbpg = NULL;
215         struct zbud_hdr *zh0, *zh1;
216         bool recycled = 0;
217
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--;
225                 recycled = 1;
226         }
227         spin_unlock(&zbpg_unused_list_spinlock);
228         if (zbpg == NULL)
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);
235                 if (recycled) {
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));
240                 } else {
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);
247                 }
248         }
249         return zbpg;
250 }
251
252 static void zbud_free_raw_page(struct zbud_page *zbpg)
253 {
254         struct zbud_hdr *zh0 = &zbpg->buddy[0], *zh1 = &zbpg->buddy[1];
255
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);
267 }
268
269 /*
270  * core zbud handling routines
271  */
272
273 static unsigned zbud_free(struct zbud_hdr *zh)
274 {
275         unsigned size;
276
277         ASSERT_SENTINEL(zh, ZBH);
278         BUG_ON(!tmem_oid_valid(&zh->oid));
279         size = zh->size;
280         BUG_ON(zh->size == 0 || zh->size > zbud_max_buddy_size());
281         zh->size = 0;
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);
286         return size;
287 }
288
289 static void zbud_free_and_delist(struct zbud_hdr *zh)
290 {
291         unsigned chunks;
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]);
296
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);
301                 return;
302         }
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);
323         }
324 }
325
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)
330 {
331         struct zbud_hdr *zh0, *zh1, *zh = NULL;
332         struct zbud_page *zbpg = NULL, *ztmp;
333         unsigned nchunks;
334         char *to;
335         int i, found_good_buddy = 0;
336
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;
346                                 }
347                         }
348                 }
349                 spin_unlock(&zbud_budlists_spinlock);
350         }
351         /* didn't find a good buddy, try allocating a new page */
352         zbpg = zbud_alloc_raw_page();
353         if (unlikely(zbpg == NULL))
354                 goto out;
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];
361         goto init_zh;
362
363 found_unbuddied:
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);
369                 zh = zh1;
370         } else if (zh1->size != 0) { /* buddy1 in use, buddy0 is vacant */
371                 ASSERT_SENTINEL(zh1, ZBH);
372                 zh = zh0;
373         } else
374                 BUG();
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++;
379
380 init_zh:
381         SET_SENTINEL(zh, ZBH);
382         zh->size = size;
383         zh->index = index;
384         zh->oid = *oid;
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);
389
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;
398 out:
399         return zh;
400 }
401
402 static int zbud_decompress(struct page *page, struct zbud_hdr *zh)
403 {
404         struct zbud_page *zbpg;
405         unsigned budnum = zbud_budnum(zh);
406         size_t out_len = PAGE_SIZE;
407         char *to_va, *from_va;
408         unsigned size;
409         int ret = 0;
410
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() */
415                 ret = -EINVAL;
416                 goto out;
417         }
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);
421         size = zh->size;
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);
427 out:
428         spin_unlock(&zbpg->lock);
429         return ret;
430 }
431
432 /*
433  * The following routines handle shrinking of ephemeral pages by evicting
434  * pages "least valuable" first.
435  */
436
437 static unsigned long zcache_evicted_raw_pages;
438 static unsigned long zcache_evicted_buddied_pages;
439 static unsigned long zcache_evicted_unbuddied_pages;
440
441 static struct tmem_pool *zcache_get_pool_by_id(uint16_t cli_id,
442                                                 uint16_t poolid);
443 static void zcache_put_pool(struct tmem_pool *pool);
444
445 /*
446  * Flush and free all zbuds in a zbpg, then free the pageframe
447  */
448 static void zbud_evict_zbpg(struct zbud_page *zbpg)
449 {
450         struct zbud_hdr *zh;
451         int i, j;
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;
456
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];
461                 if (zh->size) {
462                         client_id[j] = zh->client_id;
463                         pool_id[j] = zh->pool_id;
464                         oid[j] = zh->oid;
465                         index[j] = zh->index;
466                         j++;
467                         zbud_free(zh);
468                 }
469         }
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]);
473                 if (pool != NULL) {
474                         tmem_flush_page(pool, &oid[i], index[i]);
475                         zcache_put_pool(pool);
476                 }
477         }
478         ASSERT_SENTINEL(zbpg, ZBPG);
479         spin_lock(&zbpg->lock);
480         zbud_free_raw_page(zbpg);
481 }
482
483 /*
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
489  * lock inversion.
490  */
491 static void zbud_evict_pages(int nr)
492 {
493         struct zbud_page *zbpg;
494         int i;
495
496         /* first try freeing any pages on unused list */
497 retry_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++;
509                 if (--nr <= 0)
510                         goto out;
511                 goto retry_unused_list;
512         }
513         spin_unlock_bh(&zbpg_unused_list_spinlock);
514
515         /* now try freeing unbuddied pages, starting with least space avail */
516         for (i = 0; i < MAX_CHUNK; i++) {
517 retry_unbud_list_i:
518                 spin_lock_bh(&zbud_budlists_spinlock);
519                 if (list_empty(&zbud_unbuddied[i].list)) {
520                         spin_unlock_bh(&zbud_budlists_spinlock);
521                         continue;
522                 }
523                 list_for_each_entry(zbpg, &zbud_unbuddied[i].list, bud_list) {
524                         if (unlikely(!spin_trylock(&zbpg->lock)))
525                                 continue;
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);
532                         local_bh_enable();
533                         if (--nr <= 0)
534                                 goto out;
535                         goto retry_unbud_list_i;
536                 }
537                 spin_unlock_bh(&zbud_budlists_spinlock);
538         }
539
540         /* as a last resort, free buddied pages */
541 retry_bud_list:
542         spin_lock_bh(&zbud_budlists_spinlock);
543         if (list_empty(&zbud_buddied_list)) {
544                 spin_unlock_bh(&zbud_budlists_spinlock);
545                 goto out;
546         }
547         list_for_each_entry(zbpg, &zbud_buddied_list, bud_list) {
548                 if (unlikely(!spin_trylock(&zbpg->lock)))
549                         continue;
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);
556                 local_bh_enable();
557                 if (--nr <= 0)
558                         goto out;
559                 goto retry_bud_list;
560         }
561         spin_unlock_bh(&zbud_budlists_spinlock);
562 out:
563         return;
564 }
565
566 static void zbud_init(void)
567 {
568         int i;
569
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;
575         }
576 }
577
578 #ifdef CONFIG_SYSFS
579 /*
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.
583  */
584 static int zbud_show_unbuddied_list_counts(char *buf)
585 {
586         int i;
587         char *p = buf;
588
589         for (i = 0; i < NCHUNKS; i++)
590                 p += sprintf(p, "%u ", zbud_unbuddied[i].count);
591         return p - buf;
592 }
593
594 static int zbud_show_cumul_chunk_counts(char *buf)
595 {
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;
599         char *p = buf;
600
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];
606                 if (i == 21)
607                         total_chunks_lte_21 = total_chunks;
608                 if (i == 32)
609                         total_chunks_lte_32 = total_chunks;
610                 if (i == 42)
611                         total_chunks_lte_42 = total_chunks;
612         }
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);
616         return p - buf;
617 }
618 #endif
619
620 /**********
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.
624  *
625  * Zv represents a PAM page with the index and object (plus a "size" value
626  * necessary for decompression) immediately preceding the compressed data.
627  */
628
629 #define ZVH_SENTINEL  0x43214321
630
631 struct zv_hdr {
632         uint32_t pool_id;
633         struct tmem_oid oid;
634         uint32_t index;
635         DECL_SENTINEL
636 };
637
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;
641 /*
642  * byte count defining poor compression; pages with greater zsize will be
643  * rejected
644  */
645 static unsigned int zv_max_zsize = (PAGE_SIZE / 8) * 7;
646 /*
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
650  */
651 static unsigned int zv_max_mean_zsize = (PAGE_SIZE / 8) * 5;
652
653 static unsigned long zv_curr_dist_counts[NCHUNKS];
654 static unsigned long zv_cumul_dist_counts[NCHUNKS];
655
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)
659 {
660         struct page *page;
661         struct zv_hdr *zv = NULL;
662         uint32_t offset;
663         int alloc_size = clen + sizeof(struct zv_hdr);
664         int chunks = (alloc_size + (CHUNK_SIZE - 1)) >> CHUNK_SHIFT;
665         int ret;
666
667         BUG_ON(!irqs_disabled());
668         BUG_ON(chunks >= NCHUNKS);
669         ret = xv_malloc(xvpool, alloc_size,
670                         &page, &offset, ZCACHE_GFP_MASK);
671         if (unlikely(ret))
672                 goto out;
673         zv_curr_dist_counts[chunks]++;
674         zv_cumul_dist_counts[chunks]++;
675         zv = kmap_atomic(page, KM_USER0) + offset;
676         zv->index = index;
677         zv->oid = *oid;
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);
682 out:
683         return zv;
684 }
685
686 static void zv_free(struct xv_pool *xvpool, struct zv_hdr *zv)
687 {
688         unsigned long flags;
689         struct page *page;
690         uint32_t offset;
691         uint16_t size = xv_get_object_size(zv);
692         int chunks = (size + (CHUNK_SIZE - 1)) >> CHUNK_SHIFT;
693
694         ASSERT_SENTINEL(zv, ZVH);
695         BUG_ON(chunks >= NCHUNKS);
696         zv_curr_dist_counts[chunks]--;
697         size -= sizeof(*zv);
698         BUG_ON(size == 0);
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);
705 }
706
707 static void zv_decompress(struct page *page, struct zv_hdr *zv)
708 {
709         size_t clen = PAGE_SIZE;
710         char *to_va;
711         unsigned size;
712         int ret;
713
714         ASSERT_SENTINEL(zv, ZVH);
715         size = xv_get_object_size(zv) - sizeof(*zv);
716         BUG_ON(size == 0);
717         to_va = kmap_atomic(page, KM_USER0);
718         ret = lzo1x_decompress_safe((char *)zv + sizeof(*zv),
719                                         size, to_va, &clen);
720         kunmap_atomic(to_va, KM_USER0);
721         BUG_ON(ret != LZO_E_OK);
722         BUG_ON(clen != PAGE_SIZE);
723 }
724
725 #ifdef CONFIG_SYSFS
726 /*
727  * show a distribution of compression stats for zv pages.
728  */
729
730 static int zv_curr_dist_counts_show(char *buf)
731 {
732         unsigned long i, n, chunks = 0, sum_total_chunks = 0;
733         char *p = buf;
734
735         for (i = 0; i < NCHUNKS; i++) {
736                 n = zv_curr_dist_counts[i];
737                 p += sprintf(p, "%lu ", n);
738                 chunks += n;
739                 sum_total_chunks += i * n;
740         }
741         p += sprintf(p, "mean:%lu\n",
742                 chunks == 0 ? 0 : sum_total_chunks / chunks);
743         return p - buf;
744 }
745
746 static int zv_cumul_dist_counts_show(char *buf)
747 {
748         unsigned long i, n, chunks = 0, sum_total_chunks = 0;
749         char *p = buf;
750
751         for (i = 0; i < NCHUNKS; i++) {
752                 n = zv_cumul_dist_counts[i];
753                 p += sprintf(p, "%lu ", n);
754                 chunks += n;
755                 sum_total_chunks += i * n;
756         }
757         p += sprintf(p, "mean:%lu\n",
758                 chunks == 0 ? 0 : sum_total_chunks / chunks);
759         return p - buf;
760 }
761
762 /*
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
766  * to PAGE_SIZE.
767  */
768 static ssize_t zv_max_zsize_show(struct kobject *kobj,
769                                     struct kobj_attribute *attr,
770                                     char *buf)
771 {
772         return sprintf(buf, "%u\n", zv_max_zsize);
773 }
774
775 static ssize_t zv_max_zsize_store(struct kobject *kobj,
776                                     struct kobj_attribute *attr,
777                                     const char *buf, size_t count)
778 {
779         unsigned long val;
780         int err;
781
782         if (!capable(CAP_SYS_ADMIN))
783                 return -EPERM;
784
785         err = strict_strtoul(buf, 10, &val);
786         if (err || (val == 0) || (val > (PAGE_SIZE / 8) * 7))
787                 return -EINVAL;
788         zv_max_zsize = val;
789         return count;
790 }
791
792 /*
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
798  * to PAGE_SIZE.
799  */
800 static ssize_t zv_max_mean_zsize_show(struct kobject *kobj,
801                                     struct kobj_attribute *attr,
802                                     char *buf)
803 {
804         return sprintf(buf, "%u\n", zv_max_mean_zsize);
805 }
806
807 static ssize_t zv_max_mean_zsize_store(struct kobject *kobj,
808                                     struct kobj_attribute *attr,
809                                     const char *buf, size_t count)
810 {
811         unsigned long val;
812         int err;
813
814         if (!capable(CAP_SYS_ADMIN))
815                 return -EPERM;
816
817         err = strict_strtoul(buf, 10, &val);
818         if (err || (val == 0) || (val > (PAGE_SIZE / 8) * 7))
819                 return -EINVAL;
820         zv_max_mean_zsize = val;
821         return count;
822 }
823
824 /*
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.
833  */
834 static ssize_t zv_page_count_policy_percent_show(struct kobject *kobj,
835                                                  struct kobj_attribute *attr,
836                                                  char *buf)
837 {
838         return sprintf(buf, "%u\n", zv_page_count_policy_percent);
839 }
840
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)
844 {
845         unsigned long val;
846         int err;
847
848         if (!capable(CAP_SYS_ADMIN))
849                 return -EPERM;
850
851         err = strict_strtoul(buf, 10, &val);
852         if (err || (val == 0) || (val > 150))
853                 return -EINVAL;
854         zv_page_count_policy_percent = val;
855         return count;
856 }
857
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,
862 };
863
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,
868 };
869
870 static struct kobj_attribute zcache_zv_page_count_policy_percent_attr = {
871                 .attr = { .name = "zv_page_count_policy_percent",
872                           .mode = 0644 },
873                 .show = zv_page_count_policy_percent_show,
874                 .store = zv_page_count_policy_percent_store,
875 };
876 #endif
877
878 /*
879  * zcache core code starts here
880  */
881
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;
889
890 /*
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
895  * have a poolid==N.
896  */
897 static struct tmem_pool *zcache_get_pool_by_id(uint16_t cli_id, uint16_t poolid)
898 {
899         struct tmem_pool *pool = NULL;
900         struct zcache_client *cli = NULL;
901
902         if (cli_id == LOCAL_CLIENT)
903                 cli = &zcache_host;
904         else {
905                 if (cli_id >= MAX_CLIENTS)
906                         goto out;
907                 cli = &zcache_clients[cli_id];
908                 if (cli == NULL)
909                         goto out;
910                 atomic_inc(&cli->refcount);
911         }
912         if (poolid < MAX_POOLS_PER_CLIENT) {
913                 pool = cli->tmem_pools[poolid];
914                 if (pool != NULL)
915                         atomic_inc(&pool->refcount);
916         }
917 out:
918         return pool;
919 }
920
921 static void zcache_put_pool(struct tmem_pool *pool)
922 {
923         struct zcache_client *cli = NULL;
924
925         if (pool == NULL)
926                 BUG();
927         cli = pool->client;
928         atomic_dec(&pool->refcount);
929         atomic_dec(&cli->refcount);
930 }
931
932 int zcache_new_client(uint16_t cli_id)
933 {
934         struct zcache_client *cli = NULL;
935         int ret = -1;
936
937         if (cli_id == LOCAL_CLIENT)
938                 cli = &zcache_host;
939         else if ((unsigned int)cli_id < MAX_CLIENTS)
940                 cli = &zcache_clients[cli_id];
941         if (cli == NULL)
942                 goto out;
943         if (cli->allocated)
944                 goto out;
945         cli->allocated = 1;
946 #ifdef CONFIG_FRONTSWAP
947         cli->xvpool = xv_create_pool();
948         if (cli->xvpool == NULL)
949                 goto out;
950 #endif
951         ret = 0;
952 out:
953         return ret;
954 }
955
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;
962
963 /*
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?
967  */
968 static DEFINE_SPINLOCK(zcache_direct_reclaim_lock);
969
970 /*
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
974  */
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;
981
982 /*
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
986  */
987 struct zcache_preload {
988         void *page;
989         struct tmem_obj *obj;
990         int nr;
991         struct tmem_objnode *objnodes[OBJNODE_TREE_MAX_PATH];
992 };
993 static DEFINE_PER_CPU(struct zcache_preload, zcache_preloads) = { 0, };
994
995 static int zcache_do_preload(struct tmem_pool *pool)
996 {
997         struct zcache_preload *kp;
998         struct tmem_objnode *objnode;
999         struct tmem_obj *obj;
1000         void *page;
1001         int ret = -ENOMEM;
1002
1003         if (unlikely(zcache_objnode_cache == NULL))
1004                 goto out;
1005         if (unlikely(zcache_obj_cache == NULL))
1006                 goto out;
1007         if (!spin_trylock(&zcache_direct_reclaim_lock)) {
1008                 zcache_aborted_preload++;
1009                 goto out;
1010         }
1011         preempt_disable();
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,
1016                                 ZCACHE_GFP_MASK);
1017                 if (unlikely(objnode == NULL)) {
1018                         zcache_failed_alloc++;
1019                         goto unlock_out;
1020                 }
1021                 preempt_disable();
1022                 kp = &__get_cpu_var(zcache_preloads);
1023                 if (kp->nr < ARRAY_SIZE(kp->objnodes))
1024                         kp->objnodes[kp->nr++] = objnode;
1025                 else
1026                         kmem_cache_free(zcache_objnode_cache, objnode);
1027         }
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++;
1032                 goto unlock_out;
1033         }
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);
1038                 goto unlock_out;
1039         }
1040         preempt_disable();
1041         kp = &__get_cpu_var(zcache_preloads);
1042         if (kp->obj == NULL)
1043                 kp->obj = obj;
1044         else
1045                 kmem_cache_free(zcache_obj_cache, obj);
1046         if (kp->page == NULL)
1047                 kp->page = page;
1048         else
1049                 free_page((unsigned long)page);
1050         ret = 0;
1051 unlock_out:
1052         spin_unlock(&zcache_direct_reclaim_lock);
1053 out:
1054         return ret;
1055 }
1056
1057 static void *zcache_get_free_page(void)
1058 {
1059         struct zcache_preload *kp;
1060         void *page;
1061
1062         kp = &__get_cpu_var(zcache_preloads);
1063         page = kp->page;
1064         BUG_ON(page == NULL);
1065         kp->page = NULL;
1066         return page;
1067 }
1068
1069 static void zcache_free_page(void *p)
1070 {
1071         free_page((unsigned long)p);
1072 }
1073
1074 /*
1075  * zcache implementation for tmem host ops
1076  */
1077
1078 static struct tmem_objnode *zcache_objnode_alloc(struct tmem_pool *pool)
1079 {
1080         struct tmem_objnode *objnode = NULL;
1081         unsigned long count;
1082         struct zcache_preload *kp;
1083
1084         kp = &__get_cpu_var(zcache_preloads);
1085         if (kp->nr <= 0)
1086                 goto out;
1087         objnode = kp->objnodes[kp->nr - 1];
1088         BUG_ON(objnode == NULL);
1089         kp->objnodes[kp->nr - 1] = NULL;
1090         kp->nr--;
1091         count = atomic_inc_return(&zcache_curr_objnode_count);
1092         if (count > zcache_curr_objnode_count_max)
1093                 zcache_curr_objnode_count_max = count;
1094 out:
1095         return objnode;
1096 }
1097
1098 static void zcache_objnode_free(struct tmem_objnode *objnode,
1099                                         struct tmem_pool *pool)
1100 {
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);
1104 }
1105
1106 static struct tmem_obj *zcache_obj_alloc(struct tmem_pool *pool)
1107 {
1108         struct tmem_obj *obj = NULL;
1109         unsigned long count;
1110         struct zcache_preload *kp;
1111
1112         kp = &__get_cpu_var(zcache_preloads);
1113         obj = kp->obj;
1114         BUG_ON(obj == NULL);
1115         kp->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;
1119         return obj;
1120 }
1121
1122 static void zcache_obj_free(struct tmem_obj *obj, struct tmem_pool *pool)
1123 {
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);
1127 }
1128
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,
1134 };
1135
1136 /*
1137  * zcache implementations for PAM page descriptor ops
1138  */
1139
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;
1144
1145 /* forward reference */
1146 static int zcache_compress(struct page *from, void **out_va, size_t *out_len);
1147
1148 static void *zcache_pampd_create(char *data, size_t size, bool raw, int eph,
1149                                 struct tmem_pool *pool, struct tmem_oid *oid,
1150                                  uint32_t index)
1151 {
1152         void *pampd = NULL, *cdata;
1153         size_t clen;
1154         int ret;
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;
1161
1162         if (eph) {
1163                 ret = zcache_compress(page, &cdata, &clen);
1164                 if (ret == 0)
1165                         goto out;
1166                 if (clen == 0 || clen > zbud_max_buddy_size()) {
1167                         zcache_compress_poor++;
1168                         goto out;
1169                 }
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;
1176                 }
1177         } else {
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)
1182                         goto out;
1183                 ret = zcache_compress(page, &cdata, &clen);
1184                 if (ret == 0)
1185                         goto out;
1186                 /* reject if compression is too poor */
1187                 if (clen > zv_max_zsize) {
1188                         zcache_compress_poor++;
1189                         goto out;
1190                 }
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++;
1197                                 goto out;
1198                         }
1199                 }
1200                 pampd = (void *)zv_create(cli->xvpool, pool->pool_id,
1201                                                 oid, index, cdata, clen);
1202                 if (pampd == NULL)
1203                         goto out;
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;
1207         }
1208 out:
1209         return pampd;
1210 }
1211
1212 /*
1213  * fill the pageframe corresponding to the struct page with the data
1214  * from the passed pampd
1215  */
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)
1219 {
1220         int ret = 0;
1221
1222         BUG_ON(is_ephemeral(pool));
1223         zv_decompress(virt_to_page(data), pampd);
1224         return ret;
1225 }
1226
1227 /*
1228  * fill the pageframe corresponding to the struct page with the data
1229  * from the passed pampd
1230  */
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)
1234 {
1235         int ret = 0;
1236
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);
1241         return ret;
1242 }
1243
1244 /*
1245  * free the pampd and remove it from any zcache lists
1246  * pampd must no longer be pointed to from any tmem data structures!
1247  */
1248 static void zcache_pampd_free(void *pampd, struct tmem_pool *pool,
1249                                 struct tmem_oid *oid, uint32_t index)
1250 {
1251         struct zcache_client *cli = pool->client;
1252
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);
1257         } else {
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);
1261         }
1262 }
1263
1264 static void zcache_pampd_free_obj(struct tmem_pool *pool, struct tmem_obj *obj)
1265 {
1266 }
1267
1268 static void zcache_pampd_new_obj(struct tmem_obj *obj)
1269 {
1270 }
1271
1272 static int zcache_pampd_replace_in_obj(void *pampd, struct tmem_obj *obj)
1273 {
1274         return -1;
1275 }
1276
1277 static bool zcache_pampd_is_remote(void *pampd)
1278 {
1279         return 0;
1280 }
1281
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,
1291 };
1292
1293 /*
1294  * zcache compression/decompression and related per-cpu stuff
1295  */
1296
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);
1301
1302 static int zcache_compress(struct page *from, void **out_va, size_t *out_len)
1303 {
1304         int ret = 0;
1305         unsigned char *dmem = __get_cpu_var(zcache_dstmem);
1306         unsigned char *wmem = __get_cpu_var(zcache_workmem);
1307         char *from_va;
1308
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);
1313         mb();
1314         ret = lzo1x_1_compress(from_va, PAGE_SIZE, dmem, out_len, wmem);
1315         BUG_ON(ret != LZO_E_OK);
1316         *out_va = dmem;
1317         kunmap_atomic(from_va, KM_USER0);
1318         ret = 1;
1319 out:
1320         return ret;
1321 }
1322
1323
1324 static int zcache_cpu_notifier(struct notifier_block *nb,
1325                                 unsigned long action, void *pcpu)
1326 {
1327         int cpu = (long)pcpu;
1328         struct zcache_preload *kp;
1329
1330         switch (action) {
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);
1338                 break;
1339         case CPU_DEAD:
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);
1347                 while (kp->nr) {
1348                         kmem_cache_free(zcache_objnode_cache,
1349                                         kp->objnodes[kp->nr - 1]);
1350                         kp->objnodes[kp->nr - 1] = NULL;
1351                         kp->nr--;
1352                 }
1353                 kmem_cache_free(zcache_obj_cache, kp->obj);
1354                 free_page((unsigned long)kp->page);
1355                 break;
1356         default:
1357                 break;
1358         }
1359         return NOTIFY_OK;
1360 }
1361
1362 static struct notifier_block zcache_cpu_notifier_block = {
1363         .notifier_call = zcache_cpu_notifier
1364 };
1365
1366 #ifdef CONFIG_SYSFS
1367 #define ZCACHE_SYSFS_RO(_name) \
1368         static ssize_t zcache_##_name##_show(struct kobject *kobj, \
1369                                 struct kobj_attribute *attr, char *buf) \
1370         { \
1371                 return sprintf(buf, "%lu\n", zcache_##_name); \
1372         } \
1373         static struct kobj_attribute zcache_##_name##_attr = { \
1374                 .attr = { .name = __stringify(_name), .mode = 0444 }, \
1375                 .show = zcache_##_name##_show, \
1376         }
1377
1378 #define ZCACHE_SYSFS_RO_ATOMIC(_name) \
1379         static ssize_t zcache_##_name##_show(struct kobject *kobj, \
1380                                 struct kobj_attribute *attr, char *buf) \
1381         { \
1382             return sprintf(buf, "%d\n", atomic_read(&zcache_##_name)); \
1383         } \
1384         static struct kobj_attribute zcache_##_name##_attr = { \
1385                 .attr = { .name = __stringify(_name), .mode = 0444 }, \
1386                 .show = zcache_##_name##_show, \
1387         }
1388
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) \
1392         { \
1393             return _func(buf); \
1394         } \
1395         static struct kobj_attribute zcache_##_name##_attr = { \
1396                 .attr = { .name = __stringify(_name), .mode = 0444 }, \
1397                 .show = zcache_##_name##_show, \
1398         }
1399
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);
1435
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,
1471         NULL,
1472 };
1473
1474 static struct attribute_group zcache_attr_group = {
1475         .attrs = zcache_attrs,
1476         .name = "zcache",
1477 };
1478
1479 #endif /* CONFIG_SYSFS */
1480 /*
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
1485  * flushes.
1486  */
1487 static bool zcache_freeze;
1488
1489 /*
1490  * zcache shrinker interface (only useful for ephemeral pages, so zbud only)
1491  */
1492 static int shrink_zcache_memory(struct shrinker *shrink,
1493                                 struct shrink_control *sc)
1494 {
1495         int ret = -1;
1496         int nr = sc->nr_to_scan;
1497         gfp_t gfp_mask = sc->gfp_mask;
1498
1499         if (nr >= 0) {
1500                 if (!(gfp_mask & __GFP_FS))
1501                         /* does this case really need to be skipped? */
1502                         goto out;
1503                 if (spin_trylock(&zcache_direct_reclaim_lock)) {
1504                         zbud_evict_pages(nr);
1505                         spin_unlock(&zcache_direct_reclaim_lock);
1506                 } else
1507                         zcache_aborted_shrink++;
1508         }
1509         ret = (int)atomic_read(&zcache_zbud_curr_raw_pages);
1510 out:
1511         return ret;
1512 }
1513
1514 static struct shrinker zcache_shrinker = {
1515         .shrink = shrink_zcache_memory,
1516         .seeks = DEFAULT_SEEKS,
1517 };
1518
1519 /*
1520  * zcache shims between cleancache/frontswap ops and tmem
1521  */
1522
1523 static int zcache_put_page(int cli_id, int pool_id, struct tmem_oid *oidp,
1524                                 uint32_t index, struct page *page)
1525 {
1526         struct tmem_pool *pool;
1527         int ret = -1;
1528
1529         BUG_ON(!irqs_disabled());
1530         pool = zcache_get_pool_by_id(cli_id, pool_id);
1531         if (unlikely(pool == NULL))
1532                 goto out;
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));
1537                 if (ret < 0) {
1538                         if (is_ephemeral(pool))
1539                                 zcache_failed_eph_puts++;
1540                         else
1541                                 zcache_failed_pers_puts++;
1542                 }
1543                 zcache_put_pool(pool);
1544                 preempt_enable_no_resched();
1545         } else {
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);
1551         }
1552 out:
1553         return ret;
1554 }
1555
1556 static int zcache_get_page(int cli_id, int pool_id, struct tmem_oid *oidp,
1557                                 uint32_t index, struct page *page)
1558 {
1559         struct tmem_pool *pool;
1560         int ret = -1;
1561         unsigned long flags;
1562         size_t size = PAGE_SIZE;
1563
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);
1571         }
1572         local_irq_restore(flags);
1573         return ret;
1574 }
1575
1576 static int zcache_flush_page(int cli_id, int pool_id,
1577                                 struct tmem_oid *oidp, uint32_t index)
1578 {
1579         struct tmem_pool *pool;
1580         int ret = -1;
1581         unsigned long flags;
1582
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);
1590         }
1591         if (ret >= 0)
1592                 zcache_flush_found++;
1593         local_irq_restore(flags);
1594         return ret;
1595 }
1596
1597 static int zcache_flush_object(int cli_id, int pool_id,
1598                                 struct tmem_oid *oidp)
1599 {
1600         struct tmem_pool *pool;
1601         int ret = -1;
1602         unsigned long flags;
1603
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);
1611         }
1612         if (ret >= 0)
1613                 zcache_flobj_found++;
1614         local_irq_restore(flags);
1615         return ret;
1616 }
1617
1618 static int zcache_destroy_pool(int cli_id, int pool_id)
1619 {
1620         struct tmem_pool *pool = NULL;
1621         struct zcache_client *cli = NULL;
1622         int ret = -1;
1623
1624         if (pool_id < 0)
1625                 goto out;
1626         if (cli_id == LOCAL_CLIENT)
1627                 cli = &zcache_host;
1628         else if ((unsigned int)cli_id < MAX_CLIENTS)
1629                 cli = &zcache_clients[cli_id];
1630         if (cli == NULL)
1631                 goto out;
1632         atomic_inc(&cli->refcount);
1633         pool = cli->tmem_pools[pool_id];
1634         if (pool == NULL)
1635                 goto out;
1636         cli->tmem_pools[pool_id] = NULL;
1637         /* wait for pool activity on other cpus to quiesce */
1638         while (atomic_read(&pool->refcount) != 0)
1639                 ;
1640         atomic_dec(&cli->refcount);
1641         local_bh_disable();
1642         ret = tmem_destroy_pool(pool);
1643         local_bh_enable();
1644         kfree(pool);
1645         pr_info("zcache: destroyed pool id=%d, cli_id=%d\n",
1646                         pool_id, cli_id);
1647 out:
1648         return ret;
1649 }
1650
1651 static int zcache_new_pool(uint16_t cli_id, uint32_t flags)
1652 {
1653         int poolid = -1;
1654         struct tmem_pool *pool;
1655         struct zcache_client *cli = NULL;
1656
1657         if (cli_id == LOCAL_CLIENT)
1658                 cli = &zcache_host;
1659         else if ((unsigned int)cli_id < MAX_CLIENTS)
1660                 cli = &zcache_clients[cli_id];
1661         if (cli == NULL)
1662                 goto out;
1663         atomic_inc(&cli->refcount);
1664         pool = kmalloc(sizeof(struct tmem_pool), GFP_KERNEL);
1665         if (pool == NULL) {
1666                 pr_info("zcache: pool creation failed: out of memory\n");
1667                 goto out;
1668         }
1669
1670         for (poolid = 0; poolid < MAX_POOLS_PER_CLIENT; poolid++)
1671                 if (cli->tmem_pools[poolid] == NULL)
1672                         break;
1673         if (poolid >= MAX_POOLS_PER_CLIENT) {
1674                 pr_info("zcache: pool creation failed: max exceeded\n");
1675                 kfree(pool);
1676                 poolid = -1;
1677                 goto out;
1678         }
1679         atomic_set(&pool->refcount, 0);
1680         pool->client = cli;
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",
1686                 poolid, cli_id);
1687 out:
1688         if (cli != NULL)
1689                 atomic_dec(&cli->refcount);
1690         return poolid;
1691 }
1692
1693 /**********
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.
1699  */
1700
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)
1705 {
1706         u32 ind = (u32) index;
1707         struct tmem_oid oid = *(struct tmem_oid *)&key;
1708
1709         if (likely(ind == index))
1710                 (void)zcache_put_page(LOCAL_CLIENT, pool_id, &oid, index, page);
1711 }
1712
1713 static int zcache_cleancache_get_page(int pool_id,
1714                                         struct cleancache_filekey key,
1715                                         pgoff_t index, struct page *page)
1716 {
1717         u32 ind = (u32) index;
1718         struct tmem_oid oid = *(struct tmem_oid *)&key;
1719         int ret = -1;
1720
1721         if (likely(ind == index))
1722                 ret = zcache_get_page(LOCAL_CLIENT, pool_id, &oid, index, page);
1723         return ret;
1724 }
1725
1726 static void zcache_cleancache_flush_page(int pool_id,
1727                                         struct cleancache_filekey key,
1728                                         pgoff_t index)
1729 {
1730         u32 ind = (u32) index;
1731         struct tmem_oid oid = *(struct tmem_oid *)&key;
1732
1733         if (likely(ind == index))
1734                 (void)zcache_flush_page(LOCAL_CLIENT, pool_id, &oid, ind);
1735 }
1736
1737 static void zcache_cleancache_flush_inode(int pool_id,
1738                                         struct cleancache_filekey key)
1739 {
1740         struct tmem_oid oid = *(struct tmem_oid *)&key;
1741
1742         (void)zcache_flush_object(LOCAL_CLIENT, pool_id, &oid);
1743 }
1744
1745 static void zcache_cleancache_flush_fs(int pool_id)
1746 {
1747         if (pool_id >= 0)
1748                 (void)zcache_destroy_pool(LOCAL_CLIENT, pool_id);
1749 }
1750
1751 static int zcache_cleancache_init_fs(size_t pagesize)
1752 {
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);
1757 }
1758
1759 static int zcache_cleancache_init_shared_fs(char *uuid, size_t pagesize)
1760 {
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);
1766 }
1767
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
1776 };
1777
1778 struct cleancache_ops zcache_cleancache_register_ops(void)
1779 {
1780         struct cleancache_ops old_ops =
1781                 cleancache_register_ops(&zcache_cleancache_ops);
1782
1783         return old_ops;
1784 }
1785 #endif
1786
1787 #ifdef CONFIG_FRONTSWAP
1788 /* a single tmem poolid is used for all frontswap "types" (swapfiles) */
1789 static int zcache_frontswap_poolid = -1;
1790
1791 /*
1792  * Swizzling increases objects per swaptype, increasing tmem concurrency
1793  * for heavy swaploads.  Later, larger nr_cpus -> larger SWIZ_BITS
1794  */
1795 #define SWIZ_BITS               4
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)
1799
1800 static inline struct tmem_oid oswiz(unsigned type, u32 ind)
1801 {
1802         struct tmem_oid oid = { .oid = { 0 } };
1803         oid.oid[0] = _oswiz(type, ind);
1804         return oid;
1805 }
1806
1807 static int zcache_frontswap_put_page(unsigned type, pgoff_t offset,
1808                                    struct page *page)
1809 {
1810         u64 ind64 = (u64)offset;
1811         u32 ind = (u32)offset;
1812         struct tmem_oid oid = oswiz(type, ind);
1813         int ret = -1;
1814         unsigned long flags;
1815
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);
1822         }
1823         return ret;
1824 }
1825
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,
1829                                    struct page *page)
1830 {
1831         u64 ind64 = (u64)offset;
1832         u32 ind = (u32)offset;
1833         struct tmem_oid oid = oswiz(type, ind);
1834         int ret = -1;
1835
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);
1840         return ret;
1841 }
1842
1843 /* flush a single page from frontswap */
1844 static void zcache_frontswap_flush_page(unsigned type, pgoff_t offset)
1845 {
1846         u64 ind64 = (u64)offset;
1847         u32 ind = (u32)offset;
1848         struct tmem_oid oid = oswiz(type, ind);
1849
1850         if (likely(ind64 == ind))
1851                 (void)zcache_flush_page(LOCAL_CLIENT, zcache_frontswap_poolid,
1852                                         &oid, iswiz(ind));
1853 }
1854
1855 /* flush all pages from the passed swaptype */
1856 static void zcache_frontswap_flush_area(unsigned type)
1857 {
1858         struct tmem_oid oid;
1859         int ind;
1860
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);
1865         }
1866 }
1867
1868 static void zcache_frontswap_init(unsigned ignored)
1869 {
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);
1874 }
1875
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
1882 };
1883
1884 struct frontswap_ops zcache_frontswap_register_ops(void)
1885 {
1886         struct frontswap_ops old_ops =
1887                 frontswap_register_ops(&zcache_frontswap_ops);
1888
1889         return old_ops;
1890 }
1891 #endif
1892
1893 /*
1894  * zcache initialization
1895  * NOTE FOR NOW zcache MUST BE PROVIDED AS A KERNEL BOOT PARAMETER OR
1896  * NOTHING HAPPENS!
1897  */
1898
1899 static int zcache_enabled;
1900
1901 static int __init enable_zcache(char *s)
1902 {
1903         zcache_enabled = 1;
1904         return 1;
1905 }
1906 __setup("zcache", enable_zcache);
1907
1908 /* allow independent dynamic disabling of cleancache and frontswap */
1909
1910 static int use_cleancache = 1;
1911
1912 static int __init no_cleancache(char *s)
1913 {
1914         use_cleancache = 0;
1915         return 1;
1916 }
1917
1918 __setup("nocleancache", no_cleancache);
1919
1920 static int use_frontswap = 1;
1921
1922 static int __init no_frontswap(char *s)
1923 {
1924         use_frontswap = 0;
1925         return 1;
1926 }
1927
1928 __setup("nofrontswap", no_frontswap);
1929
1930 static int __init zcache_init(void)
1931 {
1932 #ifdef CONFIG_SYSFS
1933         int ret = 0;
1934
1935         ret = sysfs_create_group(mm_kobj, &zcache_attr_group);
1936         if (ret) {
1937                 pr_err("zcache: can't create sysfs\n");
1938                 goto out;
1939         }
1940 #endif /* CONFIG_SYSFS */
1941 #if defined(CONFIG_CLEANCACHE) || defined(CONFIG_FRONTSWAP)
1942         if (zcache_enabled) {
1943                 unsigned int cpu;
1944
1945                 tmem_register_hostops(&zcache_hostops);
1946                 tmem_register_pamops(&zcache_pamops);
1947                 ret = register_cpu_notifier(&zcache_cpu_notifier_block);
1948                 if (ret) {
1949                         pr_err("zcache: can't register cpu notifier\n");
1950                         goto out;
1951                 }
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);
1956                 }
1957         }
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);
1963         if (ret) {
1964                 pr_err("zcache: can't create client\n");
1965                 goto out;
1966         }
1967 #endif
1968 #ifdef CONFIG_CLEANCACHE
1969         if (zcache_enabled && use_cleancache) {
1970                 struct cleancache_ops old_ops;
1971
1972                 zbud_init();
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");
1979         }
1980 #endif
1981 #ifdef CONFIG_FRONTSWAP
1982         if (zcache_enabled && use_frontswap) {
1983                 struct frontswap_ops old_ops;
1984
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");
1990         }
1991 #endif
1992 out:
1993         return ret;
1994 }
1995
1996 module_init(zcache_init)