Whamcloud - gitweb
f8d3222c4826037deb2976b21d48718352f670d2
[fs/lustre-release.git] / lustre / ptlrpc / sec_bulk.c
1 /*
2  * GPL HEADER START
3  *
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License version 2 only,
8  * as published by the Free Software Foundation.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License version 2 for more details (a copy is included
14  * in the LICENSE file that accompanied this code).
15  *
16  * You should have received a copy of the GNU General Public License
17  * version 2 along with this program; If not, see
18  * http://www.gnu.org/licenses/gpl-2.0.html
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2011, 2017, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  * Lustre is a trademark of Sun Microsystems, Inc.
31  *
32  * lustre/ptlrpc/sec_bulk.c
33  *
34  * Author: Eric Mei <ericm@clusterfs.com>
35  */
36
37 #define DEBUG_SUBSYSTEM S_SEC
38
39 #include <libcfs/linux/linux-mem.h>
40
41 #include <obd.h>
42 #include <obd_cksum.h>
43 #include <obd_class.h>
44 #include <obd_support.h>
45 #include <lustre_net.h>
46 #include <lustre_import.h>
47 #include <lustre_dlm.h>
48 #include <lustre_sec.h>
49
50 #include "ptlrpc_internal.h"
51
52 static int mult = 20 - PAGE_SHIFT;
53 static int enc_pool_max_memory_mb;
54 module_param(enc_pool_max_memory_mb, int, 0644);
55 MODULE_PARM_DESC(enc_pool_max_memory_mb,
56                  "Encoding pool max memory (MB), 1/8 of total physical memory by default");
57
58 /****************************************
59  * bulk encryption page pools           *
60  ****************************************/
61
62
63 #define PTRS_PER_PAGE   (PAGE_SIZE / sizeof(void *))
64 #define PAGES_PER_POOL  (PTRS_PER_PAGE)
65
66 #define IDLE_IDX_MAX            (100)
67 #define IDLE_IDX_WEIGHT         (3)
68
69 #define CACHE_QUIESCENT_PERIOD  (20)
70
71 static struct ptlrpc_enc_page_pool {
72         /*
73          * constants
74          */
75         unsigned long    epp_max_pages;   /* maximum pages can hold, const */
76         unsigned int     epp_max_pools;   /* number of pools, const */
77
78         /*
79          * wait queue in case of not enough free pages.
80          */
81         wait_queue_head_t    epp_waitq;       /* waiting threads */
82         unsigned int     epp_waitqlen;    /* wait queue length */
83         unsigned long    epp_pages_short; /* # of pages wanted of in-q users */
84         unsigned int     epp_growing:1;   /* during adding pages */
85
86         /*
87          * indicating how idle the pools are, from 0 to MAX_IDLE_IDX
88          * this is counted based on each time when getting pages from
89          * the pools, not based on time. which means in case that system
90          * is idled for a while but the idle_idx might still be low if no
91          * activities happened in the pools.
92          */
93         unsigned long    epp_idle_idx;
94
95         /* last shrink time due to mem tight */
96         time64_t        epp_last_shrink;
97         time64_t        epp_last_access;
98
99         /*
100          * in-pool pages bookkeeping
101          */
102         spinlock_t       epp_lock;         /* protect following fields */
103         unsigned long    epp_total_pages; /* total pages in pools */
104         unsigned long    epp_free_pages;  /* current pages available */
105
106         /*
107          * statistics
108          */
109         unsigned long    epp_st_max_pages;      /* # of pages ever reached */
110         unsigned int     epp_st_grows;          /* # of grows */
111         unsigned int     epp_st_grow_fails;     /* # of add pages failures */
112         unsigned int     epp_st_shrinks;        /* # of shrinks */
113         unsigned long    epp_st_access;         /* # of access */
114         unsigned long    epp_st_missings;       /* # of cache missing */
115         unsigned long    epp_st_lowfree;        /* lowest free pages reached */
116         unsigned int     epp_st_max_wqlen;      /* highest waitqueue length */
117         ktime_t         epp_st_max_wait;        /* in nanoseconds */
118         unsigned long    epp_st_outofmem;       /* # of out of mem requests */
119         /*
120          * pointers to pools, may be vmalloc'd
121          */
122         struct page    ***epp_pools;
123 } page_pools;
124
125 /*
126  * memory shrinker
127  */
128 static const int pools_shrinker_seeks = DEFAULT_SEEKS;
129 static struct shrinker *pools_shrinker;
130
131
132 /*
133  * /proc/fs/lustre/sptlrpc/encrypt_page_pools
134  */
135 int sptlrpc_proc_enc_pool_seq_show(struct seq_file *m, void *v)
136 {
137         spin_lock(&page_pools.epp_lock);
138
139         seq_printf(m, "physical pages:          %lu\n"
140                    "pages per pool:          %lu\n"
141                    "max pages:               %lu\n"
142                    "max pools:               %u\n"
143                    "total pages:             %lu\n"
144                    "total free:              %lu\n"
145                    "idle index:              %lu/100\n"
146                    "last shrink:             %llds\n"
147                    "last access:             %llds\n"
148                    "max pages reached:       %lu\n"
149                    "grows:                   %u\n"
150                    "grows failure:           %u\n"
151                    "shrinks:                 %u\n"
152                    "cache access:            %lu\n"
153                    "cache missing:           %lu\n"
154                    "low free mark:           %lu\n"
155                    "max waitqueue depth:     %u\n"
156                    "max wait time ms:        %lld\n"
157                    "out of mem:              %lu\n",
158                    totalram_pages, PAGES_PER_POOL,
159                    page_pools.epp_max_pages,
160                    page_pools.epp_max_pools,
161                    page_pools.epp_total_pages,
162                    page_pools.epp_free_pages,
163                    page_pools.epp_idle_idx,
164                    ktime_get_seconds() - page_pools.epp_last_shrink,
165                    ktime_get_seconds() - page_pools.epp_last_access,
166                    page_pools.epp_st_max_pages,
167                    page_pools.epp_st_grows,
168                    page_pools.epp_st_grow_fails,
169                    page_pools.epp_st_shrinks,
170                    page_pools.epp_st_access,
171                    page_pools.epp_st_missings,
172                    page_pools.epp_st_lowfree,
173                    page_pools.epp_st_max_wqlen,
174                    ktime_to_ms(page_pools.epp_st_max_wait),
175                    page_pools.epp_st_outofmem);
176
177         spin_unlock(&page_pools.epp_lock);
178         return 0;
179 }
180
181 static void enc_pools_release_free_pages(long npages)
182 {
183         int     p_idx, g_idx;
184         int     p_idx_max1, p_idx_max2;
185
186         LASSERT(npages > 0);
187         LASSERT(npages <= page_pools.epp_free_pages);
188         LASSERT(page_pools.epp_free_pages <= page_pools.epp_total_pages);
189
190         /* max pool index before the release */
191         p_idx_max2 = (page_pools.epp_total_pages - 1) / PAGES_PER_POOL;
192
193         page_pools.epp_free_pages -= npages;
194         page_pools.epp_total_pages -= npages;
195
196         /* max pool index after the release */
197         p_idx_max1 = page_pools.epp_total_pages == 0 ? -1 :
198                      ((page_pools.epp_total_pages - 1) / PAGES_PER_POOL);
199
200         p_idx = page_pools.epp_free_pages / PAGES_PER_POOL;
201         g_idx = page_pools.epp_free_pages % PAGES_PER_POOL;
202         LASSERT(page_pools.epp_pools[p_idx]);
203
204         while (npages--) {
205                 LASSERT(page_pools.epp_pools[p_idx]);
206                 LASSERT(page_pools.epp_pools[p_idx][g_idx] != NULL);
207
208                 __free_page(page_pools.epp_pools[p_idx][g_idx]);
209                 page_pools.epp_pools[p_idx][g_idx] = NULL;
210
211                 if (++g_idx == PAGES_PER_POOL) {
212                         p_idx++;
213                         g_idx = 0;
214                 }
215         }
216
217         /* free unused pools */
218         while (p_idx_max1 < p_idx_max2) {
219                 LASSERT(page_pools.epp_pools[p_idx_max2]);
220                 OBD_FREE(page_pools.epp_pools[p_idx_max2], PAGE_SIZE);
221                 page_pools.epp_pools[p_idx_max2] = NULL;
222                 p_idx_max2--;
223         }
224 }
225
226 /*
227  * we try to keep at least PTLRPC_MAX_BRW_PAGES pages in the pool.
228  */
229 static unsigned long enc_pools_shrink_count(struct shrinker *s,
230                                             struct shrink_control *sc)
231 {
232         /*
233          * if no pool access for a long time, we consider it's fully idle.
234          * a little race here is fine.
235          */
236         if (unlikely(ktime_get_seconds() - page_pools.epp_last_access >
237                      CACHE_QUIESCENT_PERIOD)) {
238                 spin_lock(&page_pools.epp_lock);
239                 page_pools.epp_idle_idx = IDLE_IDX_MAX;
240                 spin_unlock(&page_pools.epp_lock);
241         }
242
243         LASSERT(page_pools.epp_idle_idx <= IDLE_IDX_MAX);
244         return (page_pools.epp_free_pages <= PTLRPC_MAX_BRW_PAGES) ? 0 :
245                 (page_pools.epp_free_pages - PTLRPC_MAX_BRW_PAGES) *
246                 (IDLE_IDX_MAX - page_pools.epp_idle_idx) / IDLE_IDX_MAX;
247 }
248
249 /*
250  * we try to keep at least PTLRPC_MAX_BRW_PAGES pages in the pool.
251  */
252 static unsigned long enc_pools_shrink_scan(struct shrinker *s,
253                                            struct shrink_control *sc)
254 {
255         spin_lock(&page_pools.epp_lock);
256         if (page_pools.epp_free_pages <= PTLRPC_MAX_BRW_PAGES)
257                 sc->nr_to_scan = 0;
258         else
259                 sc->nr_to_scan = min_t(unsigned long, sc->nr_to_scan,
260                               page_pools.epp_free_pages - PTLRPC_MAX_BRW_PAGES);
261         if (sc->nr_to_scan > 0) {
262                 enc_pools_release_free_pages(sc->nr_to_scan);
263                 CDEBUG(D_SEC, "released %ld pages, %ld left\n",
264                        (long)sc->nr_to_scan, page_pools.epp_free_pages);
265
266                 page_pools.epp_st_shrinks++;
267                 page_pools.epp_last_shrink = ktime_get_seconds();
268         }
269         spin_unlock(&page_pools.epp_lock);
270
271         /*
272          * if no pool access for a long time, we consider it's fully idle.
273          * a little race here is fine.
274          */
275         if (unlikely(ktime_get_seconds() - page_pools.epp_last_access >
276                      CACHE_QUIESCENT_PERIOD)) {
277                 spin_lock(&page_pools.epp_lock);
278                 page_pools.epp_idle_idx = IDLE_IDX_MAX;
279                 spin_unlock(&page_pools.epp_lock);
280         }
281
282         LASSERT(page_pools.epp_idle_idx <= IDLE_IDX_MAX);
283         return sc->nr_to_scan;
284 }
285
286 #ifndef HAVE_SHRINKER_COUNT
287 /*
288  * could be called frequently for query (@nr_to_scan == 0).
289  * we try to keep at least PTLRPC_MAX_BRW_PAGES pages in the pool.
290  */
291 static int enc_pools_shrink(SHRINKER_ARGS(sc, nr_to_scan, gfp_mask))
292 {
293         struct shrink_control scv = {
294                 .nr_to_scan = shrink_param(sc, nr_to_scan),
295                 .gfp_mask   = shrink_param(sc, gfp_mask)
296         };
297 #if !defined(HAVE_SHRINKER_WANT_SHRINK_PTR) && !defined(HAVE_SHRINK_CONTROL)
298         struct shrinker* shrinker = NULL;
299 #endif
300
301         enc_pools_shrink_scan(shrinker, &scv);
302
303         return enc_pools_shrink_count(shrinker, &scv);
304 }
305
306 #endif /* HAVE_SHRINKER_COUNT */
307
308 static inline
309 int npages_to_npools(unsigned long npages)
310 {
311         return (int) ((npages + PAGES_PER_POOL - 1) / PAGES_PER_POOL);
312 }
313
314 /*
315  * return how many pages cleaned up.
316  */
317 static unsigned long enc_pools_cleanup(struct page ***pools, int npools)
318 {
319         unsigned long cleaned = 0;
320         int           i, j;
321
322         for (i = 0; i < npools; i++) {
323                 if (pools[i]) {
324                         for (j = 0; j < PAGES_PER_POOL; j++) {
325                                 if (pools[i][j]) {
326                                         __free_page(pools[i][j]);
327                                         cleaned++;
328                                 }
329                         }
330                         OBD_FREE(pools[i], PAGE_SIZE);
331                         pools[i] = NULL;
332                 }
333         }
334
335         return cleaned;
336 }
337
338 /*
339  * merge @npools pointed by @pools which contains @npages new pages
340  * into current pools.
341  *
342  * we have options to avoid most memory copy with some tricks. but we choose
343  * the simplest way to avoid complexity. It's not frequently called.
344  */
345 static void enc_pools_insert(struct page ***pools, int npools, int npages)
346 {
347         int     freeslot;
348         int     op_idx, np_idx, og_idx, ng_idx;
349         int     cur_npools, end_npools;
350
351         LASSERT(npages > 0);
352         LASSERT(page_pools.epp_total_pages+npages <= page_pools.epp_max_pages);
353         LASSERT(npages_to_npools(npages) == npools);
354         LASSERT(page_pools.epp_growing);
355
356         spin_lock(&page_pools.epp_lock);
357
358         /*
359          * (1) fill all the free slots of current pools.
360          */
361         /* free slots are those left by rent pages, and the extra ones with
362          * index >= total_pages, locate at the tail of last pool. */
363         freeslot = page_pools.epp_total_pages % PAGES_PER_POOL;
364         if (freeslot != 0)
365                 freeslot = PAGES_PER_POOL - freeslot;
366         freeslot += page_pools.epp_total_pages - page_pools.epp_free_pages;
367
368         op_idx = page_pools.epp_free_pages / PAGES_PER_POOL;
369         og_idx = page_pools.epp_free_pages % PAGES_PER_POOL;
370         np_idx = npools - 1;
371         ng_idx = (npages - 1) % PAGES_PER_POOL;
372
373         while (freeslot) {
374                 LASSERT(page_pools.epp_pools[op_idx][og_idx] == NULL);
375                 LASSERT(pools[np_idx][ng_idx] != NULL);
376
377                 page_pools.epp_pools[op_idx][og_idx] = pools[np_idx][ng_idx];
378                 pools[np_idx][ng_idx] = NULL;
379
380                 freeslot--;
381
382                 if (++og_idx == PAGES_PER_POOL) {
383                         op_idx++;
384                         og_idx = 0;
385                 }
386                 if (--ng_idx < 0) {
387                         if (np_idx == 0)
388                                 break;
389                         np_idx--;
390                         ng_idx = PAGES_PER_POOL - 1;
391                 }
392         }
393
394         /*
395          * (2) add pools if needed.
396          */
397         cur_npools = (page_pools.epp_total_pages + PAGES_PER_POOL - 1) /
398                      PAGES_PER_POOL;
399         end_npools = (page_pools.epp_total_pages + npages + PAGES_PER_POOL -1) /
400                      PAGES_PER_POOL;
401         LASSERT(end_npools <= page_pools.epp_max_pools);
402
403         np_idx = 0;
404         while (cur_npools < end_npools) {
405                 LASSERT(page_pools.epp_pools[cur_npools] == NULL);
406                 LASSERT(np_idx < npools);
407                 LASSERT(pools[np_idx] != NULL);
408
409                 page_pools.epp_pools[cur_npools++] = pools[np_idx];
410                 pools[np_idx++] = NULL;
411         }
412
413         page_pools.epp_total_pages += npages;
414         page_pools.epp_free_pages += npages;
415         page_pools.epp_st_lowfree = page_pools.epp_free_pages;
416
417         if (page_pools.epp_total_pages > page_pools.epp_st_max_pages)
418                 page_pools.epp_st_max_pages = page_pools.epp_total_pages;
419
420         CDEBUG(D_SEC, "add %d pages to total %lu\n", npages,
421                page_pools.epp_total_pages);
422
423         spin_unlock(&page_pools.epp_lock);
424 }
425
426 static int enc_pools_add_pages(int npages)
427 {
428         static DEFINE_MUTEX(add_pages_mutex);
429         struct page   ***pools;
430         int             npools, alloced = 0;
431         int             i, j, rc = -ENOMEM;
432
433         if (npages < PTLRPC_MAX_BRW_PAGES)
434                 npages = PTLRPC_MAX_BRW_PAGES;
435
436         mutex_lock(&add_pages_mutex);
437
438         if (npages + page_pools.epp_total_pages > page_pools.epp_max_pages)
439                 npages = page_pools.epp_max_pages - page_pools.epp_total_pages;
440         LASSERT(npages > 0);
441
442         page_pools.epp_st_grows++;
443
444         npools = npages_to_npools(npages);
445         OBD_ALLOC(pools, npools * sizeof(*pools));
446         if (pools == NULL)
447                 goto out;
448
449         for (i = 0; i < npools; i++) {
450                 OBD_ALLOC(pools[i], PAGE_SIZE);
451                 if (pools[i] == NULL)
452                         goto out_pools;
453
454                 for (j = 0; j < PAGES_PER_POOL && alloced < npages; j++) {
455                         pools[i][j] = alloc_page(GFP_NOFS |
456                                                  __GFP_HIGHMEM);
457                         if (pools[i][j] == NULL)
458                                 goto out_pools;
459
460                         alloced++;
461                 }
462         }
463         LASSERT(alloced == npages);
464
465         enc_pools_insert(pools, npools, npages);
466         CDEBUG(D_SEC, "added %d pages into pools\n", npages);
467         rc = 0;
468
469 out_pools:
470         enc_pools_cleanup(pools, npools);
471         OBD_FREE(pools, npools * sizeof(*pools));
472 out:
473         if (rc) {
474                 page_pools.epp_st_grow_fails++;
475                 CERROR("Failed to allocate %d enc pages\n", npages);
476         }
477
478         mutex_unlock(&add_pages_mutex);
479         return rc;
480 }
481
482 static inline void enc_pools_wakeup(void)
483 {
484         assert_spin_locked(&page_pools.epp_lock);
485
486         if (unlikely(page_pools.epp_waitqlen)) {
487                 LASSERT(waitqueue_active(&page_pools.epp_waitq));
488                 wake_up_all(&page_pools.epp_waitq);
489         }
490 }
491
492 static int enc_pools_should_grow(int page_needed, time64_t now)
493 {
494         /* don't grow if someone else is growing the pools right now,
495          * or the pools has reached its full capacity
496          */
497         if (page_pools.epp_growing ||
498             page_pools.epp_total_pages == page_pools.epp_max_pages)
499                 return 0;
500
501         /* if total pages is not enough, we need to grow */
502         if (page_pools.epp_total_pages < page_needed)
503                 return 1;
504
505         /*
506          * we wanted to return 0 here if there was a shrink just
507          * happened a moment ago, but this may cause deadlock if both
508          * client and ost live on single node.
509          */
510
511         /*
512          * here we perhaps need consider other factors like wait queue
513          * length, idle index, etc. ?
514          */
515
516         /* grow the pools in any other cases */
517         return 1;
518 }
519
520 /*
521  * Export the number of free pages in the pool
522  */
523 int get_free_pages_in_pool(void)
524 {
525         return page_pools.epp_free_pages;
526 }
527 EXPORT_SYMBOL(get_free_pages_in_pool);
528
529 /*
530  * Let outside world know if enc_pool full capacity is reached
531  */
532 int pool_is_at_full_capacity(void)
533 {
534         return (page_pools.epp_total_pages == page_pools.epp_max_pages);
535 }
536 EXPORT_SYMBOL(pool_is_at_full_capacity);
537
538 /*
539  * we allocate the requested pages atomically.
540  */
541 int sptlrpc_enc_pool_get_pages(struct ptlrpc_bulk_desc *desc)
542 {
543         wait_queue_entry_t waitlink;
544         unsigned long this_idle = -1;
545         u64 tick_ns = 0;
546         time64_t now;
547         int p_idx, g_idx;
548         int i;
549
550         LASSERT(ptlrpc_is_bulk_desc_kiov(desc->bd_type));
551         LASSERT(desc->bd_iov_count > 0);
552         LASSERT(desc->bd_iov_count <= page_pools.epp_max_pages);
553
554         /* resent bulk, enc iov might have been allocated previously */
555         if (GET_ENC_KIOV(desc) != NULL)
556                 return 0;
557
558         OBD_ALLOC_LARGE(GET_ENC_KIOV(desc),
559                   desc->bd_iov_count * sizeof(*GET_ENC_KIOV(desc)));
560         if (GET_ENC_KIOV(desc) == NULL)
561                 return -ENOMEM;
562
563         spin_lock(&page_pools.epp_lock);
564
565         page_pools.epp_st_access++;
566 again:
567         if (unlikely(page_pools.epp_free_pages < desc->bd_iov_count)) {
568                 if (tick_ns == 0)
569                         tick_ns = ktime_get_ns();
570
571                 now = ktime_get_real_seconds();
572
573                 page_pools.epp_st_missings++;
574                 page_pools.epp_pages_short += desc->bd_iov_count;
575
576                 if (enc_pools_should_grow(desc->bd_iov_count, now)) {
577                         page_pools.epp_growing = 1;
578
579                         spin_unlock(&page_pools.epp_lock);
580                         enc_pools_add_pages(page_pools.epp_pages_short / 2);
581                         spin_lock(&page_pools.epp_lock);
582
583                         page_pools.epp_growing = 0;
584
585                         enc_pools_wakeup();
586                 } else {
587                         if (page_pools.epp_growing) {
588                                 if (++page_pools.epp_waitqlen >
589                                     page_pools.epp_st_max_wqlen)
590                                         page_pools.epp_st_max_wqlen =
591                                                         page_pools.epp_waitqlen;
592
593                                 set_current_state(TASK_UNINTERRUPTIBLE);
594                                 init_waitqueue_entry(&waitlink, current);
595                                 add_wait_queue(&page_pools.epp_waitq,
596                                                &waitlink);
597
598                                 spin_unlock(&page_pools.epp_lock);
599                                 schedule();
600                                 remove_wait_queue(&page_pools.epp_waitq,
601                                                   &waitlink);
602                                 LASSERT(page_pools.epp_waitqlen > 0);
603                                 spin_lock(&page_pools.epp_lock);
604                                 page_pools.epp_waitqlen--;
605                         } else {
606                                 /* ptlrpcd thread should not sleep in that case,
607                                  * or deadlock may occur!
608                                  * Instead, return -ENOMEM so that upper layers
609                                  * will put request back in queue. */
610                                 page_pools.epp_st_outofmem++;
611                                 spin_unlock(&page_pools.epp_lock);
612                                 OBD_FREE_LARGE(GET_ENC_KIOV(desc),
613                                                desc->bd_iov_count *
614                                                 sizeof(*GET_ENC_KIOV(desc)));
615                                 GET_ENC_KIOV(desc) = NULL;
616                                 return -ENOMEM;
617                         }
618                 }
619
620                 LASSERT(page_pools.epp_pages_short >= desc->bd_iov_count);
621                 page_pools.epp_pages_short -= desc->bd_iov_count;
622
623                 this_idle = 0;
624                 goto again;
625         }
626
627         /* record max wait time */
628         if (unlikely(tick_ns)) {
629                 ktime_t tick = ktime_sub_ns(ktime_get(), tick_ns);
630
631                 if (ktime_after(tick, page_pools.epp_st_max_wait))
632                         page_pools.epp_st_max_wait = tick;
633         }
634
635         /* proceed with rest of allocation */
636         page_pools.epp_free_pages -= desc->bd_iov_count;
637
638         p_idx = page_pools.epp_free_pages / PAGES_PER_POOL;
639         g_idx = page_pools.epp_free_pages % PAGES_PER_POOL;
640
641         for (i = 0; i < desc->bd_iov_count; i++) {
642                 LASSERT(page_pools.epp_pools[p_idx][g_idx] != NULL);
643                 BD_GET_ENC_KIOV(desc, i).kiov_page =
644                        page_pools.epp_pools[p_idx][g_idx];
645                 page_pools.epp_pools[p_idx][g_idx] = NULL;
646
647                 if (++g_idx == PAGES_PER_POOL) {
648                         p_idx++;
649                         g_idx = 0;
650                 }
651         }
652
653         if (page_pools.epp_free_pages < page_pools.epp_st_lowfree)
654                 page_pools.epp_st_lowfree = page_pools.epp_free_pages;
655
656         /*
657          * new idle index = (old * weight + new) / (weight + 1)
658          */
659         if (this_idle == -1) {
660                 this_idle = page_pools.epp_free_pages * IDLE_IDX_MAX /
661                             page_pools.epp_total_pages;
662         }
663         page_pools.epp_idle_idx = (page_pools.epp_idle_idx * IDLE_IDX_WEIGHT +
664                                    this_idle) /
665                                   (IDLE_IDX_WEIGHT + 1);
666
667         page_pools.epp_last_access = ktime_get_seconds();
668
669         spin_unlock(&page_pools.epp_lock);
670         return 0;
671 }
672 EXPORT_SYMBOL(sptlrpc_enc_pool_get_pages);
673
674 void sptlrpc_enc_pool_put_pages(struct ptlrpc_bulk_desc *desc)
675 {
676         int     p_idx, g_idx;
677         int     i;
678
679         LASSERT(ptlrpc_is_bulk_desc_kiov(desc->bd_type));
680
681         if (GET_ENC_KIOV(desc) == NULL)
682                 return;
683
684         LASSERT(desc->bd_iov_count > 0);
685
686         spin_lock(&page_pools.epp_lock);
687
688         p_idx = page_pools.epp_free_pages / PAGES_PER_POOL;
689         g_idx = page_pools.epp_free_pages % PAGES_PER_POOL;
690
691         LASSERT(page_pools.epp_free_pages + desc->bd_iov_count <=
692                 page_pools.epp_total_pages);
693         LASSERT(page_pools.epp_pools[p_idx]);
694
695         for (i = 0; i < desc->bd_iov_count; i++) {
696                 LASSERT(BD_GET_ENC_KIOV(desc, i).kiov_page != NULL);
697                 LASSERT(g_idx != 0 || page_pools.epp_pools[p_idx]);
698                 LASSERT(page_pools.epp_pools[p_idx][g_idx] == NULL);
699
700                 page_pools.epp_pools[p_idx][g_idx] =
701                         BD_GET_ENC_KIOV(desc, i).kiov_page;
702
703                 if (++g_idx == PAGES_PER_POOL) {
704                         p_idx++;
705                         g_idx = 0;
706                 }
707         }
708
709         page_pools.epp_free_pages += desc->bd_iov_count;
710
711         enc_pools_wakeup();
712
713         spin_unlock(&page_pools.epp_lock);
714
715         OBD_FREE_LARGE(GET_ENC_KIOV(desc),
716                  desc->bd_iov_count * sizeof(*GET_ENC_KIOV(desc)));
717         GET_ENC_KIOV(desc) = NULL;
718 }
719
720 /*
721  * we don't do much stuff for add_user/del_user anymore, except adding some
722  * initial pages in add_user() if current pools are empty, rest would be
723  * handled by the pools's self-adaption.
724  */
725 int sptlrpc_enc_pool_add_user(void)
726 {
727         int     need_grow = 0;
728
729         spin_lock(&page_pools.epp_lock);
730         if (page_pools.epp_growing == 0 && page_pools.epp_total_pages == 0) {
731                 page_pools.epp_growing = 1;
732                 need_grow = 1;
733         }
734         spin_unlock(&page_pools.epp_lock);
735
736         if (need_grow) {
737                 enc_pools_add_pages(PTLRPC_MAX_BRW_PAGES +
738                                     PTLRPC_MAX_BRW_PAGES);
739
740                 spin_lock(&page_pools.epp_lock);
741                 page_pools.epp_growing = 0;
742                 enc_pools_wakeup();
743                 spin_unlock(&page_pools.epp_lock);
744         }
745         return 0;
746 }
747 EXPORT_SYMBOL(sptlrpc_enc_pool_add_user);
748
749 int sptlrpc_enc_pool_del_user(void)
750 {
751         return 0;
752 }
753 EXPORT_SYMBOL(sptlrpc_enc_pool_del_user);
754
755 static inline void enc_pools_alloc(void)
756 {
757         LASSERT(page_pools.epp_max_pools);
758         OBD_ALLOC_LARGE(page_pools.epp_pools,
759                         page_pools.epp_max_pools *
760                         sizeof(*page_pools.epp_pools));
761 }
762
763 static inline void enc_pools_free(void)
764 {
765         LASSERT(page_pools.epp_max_pools);
766         LASSERT(page_pools.epp_pools);
767
768         OBD_FREE_LARGE(page_pools.epp_pools,
769                        page_pools.epp_max_pools *
770                        sizeof(*page_pools.epp_pools));
771 }
772
773 int sptlrpc_enc_pool_init(void)
774 {
775         DEF_SHRINKER_VAR(shvar, enc_pools_shrink,
776                          enc_pools_shrink_count, enc_pools_shrink_scan);
777
778         page_pools.epp_max_pages = totalram_pages / 8;
779         if (enc_pool_max_memory_mb > 0 &&
780             enc_pool_max_memory_mb <= (totalram_pages >> mult))
781                 page_pools.epp_max_pages = enc_pool_max_memory_mb << mult;
782
783         page_pools.epp_max_pools = npages_to_npools(page_pools.epp_max_pages);
784
785         init_waitqueue_head(&page_pools.epp_waitq);
786         page_pools.epp_waitqlen = 0;
787         page_pools.epp_pages_short = 0;
788
789         page_pools.epp_growing = 0;
790
791         page_pools.epp_idle_idx = 0;
792         page_pools.epp_last_shrink = ktime_get_seconds();
793         page_pools.epp_last_access = ktime_get_seconds();
794
795         spin_lock_init(&page_pools.epp_lock);
796         page_pools.epp_total_pages = 0;
797         page_pools.epp_free_pages = 0;
798
799         page_pools.epp_st_max_pages = 0;
800         page_pools.epp_st_grows = 0;
801         page_pools.epp_st_grow_fails = 0;
802         page_pools.epp_st_shrinks = 0;
803         page_pools.epp_st_access = 0;
804         page_pools.epp_st_missings = 0;
805         page_pools.epp_st_lowfree = 0;
806         page_pools.epp_st_max_wqlen = 0;
807         page_pools.epp_st_max_wait = ktime_set(0, 0);
808         page_pools.epp_st_outofmem = 0;
809
810         enc_pools_alloc();
811         if (page_pools.epp_pools == NULL)
812                 return -ENOMEM;
813
814         pools_shrinker = set_shrinker(pools_shrinker_seeks, &shvar);
815         if (pools_shrinker == NULL) {
816                 enc_pools_free();
817                 return -ENOMEM;
818         }
819
820         return 0;
821 }
822
823 void sptlrpc_enc_pool_fini(void)
824 {
825         unsigned long cleaned, npools;
826
827         LASSERT(pools_shrinker);
828         LASSERT(page_pools.epp_pools);
829         LASSERT(page_pools.epp_total_pages == page_pools.epp_free_pages);
830
831         remove_shrinker(pools_shrinker);
832
833         npools = npages_to_npools(page_pools.epp_total_pages);
834         cleaned = enc_pools_cleanup(page_pools.epp_pools, npools);
835         LASSERT(cleaned == page_pools.epp_total_pages);
836
837         enc_pools_free();
838
839         if (page_pools.epp_st_access > 0) {
840                 CDEBUG(D_SEC,
841                        "max pages %lu, grows %u, grow fails %u, shrinks %u, access %lu, missing %lu, max qlen %u, max wait ms %lld, out of mem %lu\n",
842                        page_pools.epp_st_max_pages, page_pools.epp_st_grows,
843                        page_pools.epp_st_grow_fails,
844                        page_pools.epp_st_shrinks, page_pools.epp_st_access,
845                        page_pools.epp_st_missings, page_pools.epp_st_max_wqlen,
846                        ktime_to_ms(page_pools.epp_st_max_wait),
847                        page_pools.epp_st_outofmem);
848         }
849 }
850
851
852 static int cfs_hash_alg_id[] = {
853         [BULK_HASH_ALG_NULL]    = CFS_HASH_ALG_NULL,
854         [BULK_HASH_ALG_ADLER32] = CFS_HASH_ALG_ADLER32,
855         [BULK_HASH_ALG_CRC32]   = CFS_HASH_ALG_CRC32,
856         [BULK_HASH_ALG_MD5]     = CFS_HASH_ALG_MD5,
857         [BULK_HASH_ALG_SHA1]    = CFS_HASH_ALG_SHA1,
858         [BULK_HASH_ALG_SHA256]  = CFS_HASH_ALG_SHA256,
859         [BULK_HASH_ALG_SHA384]  = CFS_HASH_ALG_SHA384,
860         [BULK_HASH_ALG_SHA512]  = CFS_HASH_ALG_SHA512,
861 };
862 const char * sptlrpc_get_hash_name(__u8 hash_alg)
863 {
864         return cfs_crypto_hash_name(cfs_hash_alg_id[hash_alg]);
865 }
866
867 __u8 sptlrpc_get_hash_alg(const char *algname)
868 {
869         return cfs_crypto_hash_alg(algname);
870 }
871
872 int bulk_sec_desc_unpack(struct lustre_msg *msg, int offset, int swabbed)
873 {
874         struct ptlrpc_bulk_sec_desc *bsd;
875         int                          size = msg->lm_buflens[offset];
876
877         bsd = lustre_msg_buf(msg, offset, sizeof(*bsd));
878         if (bsd == NULL) {
879                 CERROR("Invalid bulk sec desc: size %d\n", size);
880                 return -EINVAL;
881         }
882
883         if (swabbed) {
884                 __swab32s(&bsd->bsd_nob);
885         }
886
887         if (unlikely(bsd->bsd_version != 0)) {
888                 CERROR("Unexpected version %u\n", bsd->bsd_version);
889                 return -EPROTO;
890         }
891
892         if (unlikely(bsd->bsd_type >= SPTLRPC_BULK_MAX)) {
893                 CERROR("Invalid type %u\n", bsd->bsd_type);
894                 return -EPROTO;
895         }
896
897         /* FIXME more sanity check here */
898
899         if (unlikely(bsd->bsd_svc != SPTLRPC_BULK_SVC_NULL &&
900                      bsd->bsd_svc != SPTLRPC_BULK_SVC_INTG &&
901                      bsd->bsd_svc != SPTLRPC_BULK_SVC_PRIV)) {
902                 CERROR("Invalid svc %u\n", bsd->bsd_svc);
903                 return -EPROTO;
904         }
905
906         return 0;
907 }
908 EXPORT_SYMBOL(bulk_sec_desc_unpack);
909
910 /*
911  * Compute the checksum of an RPC buffer payload.  If the return \a buflen
912  * is not large enough, truncate the result to fit so that it is possible
913  * to use a hash function with a large hash space, but only use a part of
914  * the resulting hash.
915  */
916 int sptlrpc_get_bulk_checksum(struct ptlrpc_bulk_desc *desc, __u8 alg,
917                               void *buf, int buflen)
918 {
919         struct cfs_crypto_hash_desc     *hdesc;
920         int                             hashsize;
921         unsigned int                    bufsize;
922         int                             i, err;
923
924         LASSERT(ptlrpc_is_bulk_desc_kiov(desc->bd_type));
925         LASSERT(alg > BULK_HASH_ALG_NULL && alg < BULK_HASH_ALG_MAX);
926         LASSERT(buflen >= 4);
927
928         hdesc = cfs_crypto_hash_init(cfs_hash_alg_id[alg], NULL, 0);
929         if (IS_ERR(hdesc)) {
930                 CERROR("Unable to initialize checksum hash %s\n",
931                        cfs_crypto_hash_name(cfs_hash_alg_id[alg]));
932                 return PTR_ERR(hdesc);
933         }
934
935         hashsize = cfs_crypto_hash_digestsize(cfs_hash_alg_id[alg]);
936
937         for (i = 0; i < desc->bd_iov_count; i++) {
938                 cfs_crypto_hash_update_page(hdesc,
939                                   BD_GET_KIOV(desc, i).kiov_page,
940                                   BD_GET_KIOV(desc, i).kiov_offset &
941                                               ~PAGE_MASK,
942                                   BD_GET_KIOV(desc, i).kiov_len);
943         }
944
945         if (hashsize > buflen) {
946                 unsigned char hashbuf[CFS_CRYPTO_HASH_DIGESTSIZE_MAX];
947
948                 bufsize = sizeof(hashbuf);
949                 LASSERTF(bufsize >= hashsize, "bufsize = %u < hashsize %u\n",
950                          bufsize, hashsize);
951                 err = cfs_crypto_hash_final(hdesc, hashbuf, &bufsize);
952                 memcpy(buf, hashbuf, buflen);
953         } else {
954                 bufsize = buflen;
955                 err = cfs_crypto_hash_final(hdesc, buf, &bufsize);
956         }
957
958         return err;
959 }