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