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