Whamcloud - gitweb
2928637337f50bf0e10dead12394f3d4cc49d35d
[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_PTR_ARRAY(pools, npools);
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_PTR_ARRAY(pools, npools);
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(desc->bd_iov_count > 0);
542         LASSERT(desc->bd_iov_count <= page_pools.epp_max_pages);
543
544         /* resent bulk, enc iov might have been allocated previously */
545         if (desc->bd_enc_vec != NULL)
546                 return 0;
547
548         OBD_ALLOC_LARGE(desc->bd_enc_vec,
549                   desc->bd_iov_count * sizeof(*desc->bd_enc_vec));
550         if (desc->bd_enc_vec == NULL)
551                 return -ENOMEM;
552
553         spin_lock(&page_pools.epp_lock);
554
555         page_pools.epp_st_access++;
556 again:
557         if (unlikely(page_pools.epp_free_pages < desc->bd_iov_count)) {
558                 if (tick_ns == 0)
559                         tick_ns = ktime_get_ns();
560
561                 now = ktime_get_real_seconds();
562
563                 page_pools.epp_st_missings++;
564                 page_pools.epp_pages_short += desc->bd_iov_count;
565
566                 if (enc_pools_should_grow(desc->bd_iov_count, now)) {
567                         page_pools.epp_growing = 1;
568
569                         spin_unlock(&page_pools.epp_lock);
570                         enc_pools_add_pages(page_pools.epp_pages_short / 2);
571                         spin_lock(&page_pools.epp_lock);
572
573                         page_pools.epp_growing = 0;
574
575                         enc_pools_wakeup();
576                 } else {
577                         if (page_pools.epp_growing) {
578                                 if (++page_pools.epp_waitqlen >
579                                     page_pools.epp_st_max_wqlen)
580                                         page_pools.epp_st_max_wqlen =
581                                                         page_pools.epp_waitqlen;
582
583                                 set_current_state(TASK_UNINTERRUPTIBLE);
584                                 init_wait(&waitlink);
585                                 add_wait_queue(&page_pools.epp_waitq,
586                                                &waitlink);
587
588                                 spin_unlock(&page_pools.epp_lock);
589                                 schedule();
590                                 remove_wait_queue(&page_pools.epp_waitq,
591                                                   &waitlink);
592                                 LASSERT(page_pools.epp_waitqlen > 0);
593                                 spin_lock(&page_pools.epp_lock);
594                                 page_pools.epp_waitqlen--;
595                         } else {
596                                 /*
597                                  * ptlrpcd thread should not sleep in that case,
598                                  * or deadlock may occur!
599                                  * Instead, return -ENOMEM so that upper layers
600                                  * will put request back in queue.
601                                  */
602                                 page_pools.epp_st_outofmem++;
603                                 spin_unlock(&page_pools.epp_lock);
604                                 OBD_FREE_LARGE(desc->bd_enc_vec,
605                                                desc->bd_iov_count *
606                                                 sizeof(*desc->bd_enc_vec));
607                                 desc->bd_enc_vec = NULL;
608                                 return -ENOMEM;
609                         }
610                 }
611
612                 LASSERT(page_pools.epp_pages_short >= desc->bd_iov_count);
613                 page_pools.epp_pages_short -= desc->bd_iov_count;
614
615                 this_idle = 0;
616                 goto again;
617         }
618
619         /* record max wait time */
620         if (unlikely(tick_ns)) {
621                 ktime_t tick = ktime_sub_ns(ktime_get(), tick_ns);
622
623                 if (ktime_after(tick, page_pools.epp_st_max_wait))
624                         page_pools.epp_st_max_wait = tick;
625         }
626
627         /* proceed with rest of allocation */
628         page_pools.epp_free_pages -= desc->bd_iov_count;
629
630         p_idx = page_pools.epp_free_pages / PAGES_PER_POOL;
631         g_idx = page_pools.epp_free_pages % PAGES_PER_POOL;
632
633         for (i = 0; i < desc->bd_iov_count; i++) {
634                 LASSERT(page_pools.epp_pools[p_idx][g_idx] != NULL);
635                 desc->bd_enc_vec[i].bv_page =
636                        page_pools.epp_pools[p_idx][g_idx];
637                 page_pools.epp_pools[p_idx][g_idx] = NULL;
638
639                 if (++g_idx == PAGES_PER_POOL) {
640                         p_idx++;
641                         g_idx = 0;
642                 }
643         }
644
645         if (page_pools.epp_free_pages < page_pools.epp_st_lowfree)
646                 page_pools.epp_st_lowfree = page_pools.epp_free_pages;
647
648         /*
649          * new idle index = (old * weight + new) / (weight + 1)
650          */
651         if (this_idle == -1) {
652                 this_idle = page_pools.epp_free_pages * IDLE_IDX_MAX /
653                         page_pools.epp_total_pages;
654         }
655         page_pools.epp_idle_idx = (page_pools.epp_idle_idx * IDLE_IDX_WEIGHT +
656                                    this_idle) /
657                                    (IDLE_IDX_WEIGHT + 1);
658
659         page_pools.epp_last_access = ktime_get_seconds();
660
661         spin_unlock(&page_pools.epp_lock);
662         return 0;
663 }
664 EXPORT_SYMBOL(sptlrpc_enc_pool_get_pages);
665
666 void sptlrpc_enc_pool_put_pages(struct ptlrpc_bulk_desc *desc)
667 {
668         int p_idx, g_idx;
669         int i;
670
671         if (desc->bd_enc_vec == NULL)
672                 return;
673
674         LASSERT(desc->bd_iov_count > 0);
675
676         spin_lock(&page_pools.epp_lock);
677
678         p_idx = page_pools.epp_free_pages / PAGES_PER_POOL;
679         g_idx = page_pools.epp_free_pages % PAGES_PER_POOL;
680
681         LASSERT(page_pools.epp_free_pages + desc->bd_iov_count <=
682                 page_pools.epp_total_pages);
683         LASSERT(page_pools.epp_pools[p_idx]);
684
685         for (i = 0; i < desc->bd_iov_count; i++) {
686                 LASSERT(desc->bd_enc_vec[i].bv_page);
687                 LASSERT(g_idx != 0 || page_pools.epp_pools[p_idx]);
688                 LASSERT(page_pools.epp_pools[p_idx][g_idx] == NULL);
689
690                 page_pools.epp_pools[p_idx][g_idx] =
691                         desc->bd_enc_vec[i].bv_page;
692
693                 if (++g_idx == PAGES_PER_POOL) {
694                         p_idx++;
695                         g_idx = 0;
696                 }
697         }
698
699         page_pools.epp_free_pages += desc->bd_iov_count;
700
701         enc_pools_wakeup();
702
703         spin_unlock(&page_pools.epp_lock);
704
705         OBD_FREE_LARGE(desc->bd_enc_vec,
706                  desc->bd_iov_count * sizeof(*desc->bd_enc_vec));
707         desc->bd_enc_vec = NULL;
708 }
709
710 /*
711  * we don't do much stuff for add_user/del_user anymore, except adding some
712  * initial pages in add_user() if current pools are empty, rest would be
713  * handled by the pools's self-adaption.
714  */
715 int sptlrpc_enc_pool_add_user(void)
716 {
717         int need_grow = 0;
718
719         spin_lock(&page_pools.epp_lock);
720         if (page_pools.epp_growing == 0 && page_pools.epp_total_pages == 0) {
721                 page_pools.epp_growing = 1;
722                 need_grow = 1;
723         }
724         spin_unlock(&page_pools.epp_lock);
725
726         if (need_grow) {
727                 enc_pools_add_pages(PTLRPC_MAX_BRW_PAGES +
728                                     PTLRPC_MAX_BRW_PAGES);
729
730                 spin_lock(&page_pools.epp_lock);
731                 page_pools.epp_growing = 0;
732                 enc_pools_wakeup();
733                 spin_unlock(&page_pools.epp_lock);
734         }
735         return 0;
736 }
737 EXPORT_SYMBOL(sptlrpc_enc_pool_add_user);
738
739 int sptlrpc_enc_pool_del_user(void)
740 {
741         return 0;
742 }
743 EXPORT_SYMBOL(sptlrpc_enc_pool_del_user);
744
745 static inline void enc_pools_alloc(void)
746 {
747         LASSERT(page_pools.epp_max_pools);
748         OBD_ALLOC_LARGE(page_pools.epp_pools,
749                         page_pools.epp_max_pools *
750                         sizeof(*page_pools.epp_pools));
751 }
752
753 static inline void enc_pools_free(void)
754 {
755         LASSERT(page_pools.epp_max_pools);
756         LASSERT(page_pools.epp_pools);
757
758         OBD_FREE_LARGE(page_pools.epp_pools,
759                        page_pools.epp_max_pools *
760                        sizeof(*page_pools.epp_pools));
761 }
762
763 int sptlrpc_enc_pool_init(void)
764 {
765         DEF_SHRINKER_VAR(shvar, enc_pools_shrink,
766                          enc_pools_shrink_count, enc_pools_shrink_scan);
767
768         page_pools.epp_max_pages = cfs_totalram_pages() / 8;
769         if (enc_pool_max_memory_mb > 0 &&
770             enc_pool_max_memory_mb <= (cfs_totalram_pages() >> mult))
771                 page_pools.epp_max_pages = enc_pool_max_memory_mb << mult;
772
773         page_pools.epp_max_pools = npages_to_npools(page_pools.epp_max_pages);
774
775         init_waitqueue_head(&page_pools.epp_waitq);
776         page_pools.epp_waitqlen = 0;
777         page_pools.epp_pages_short = 0;
778
779         page_pools.epp_growing = 0;
780
781         page_pools.epp_idle_idx = 0;
782         page_pools.epp_last_shrink = ktime_get_seconds();
783         page_pools.epp_last_access = ktime_get_seconds();
784
785         spin_lock_init(&page_pools.epp_lock);
786         page_pools.epp_total_pages = 0;
787         page_pools.epp_free_pages = 0;
788
789         page_pools.epp_st_max_pages = 0;
790         page_pools.epp_st_grows = 0;
791         page_pools.epp_st_grow_fails = 0;
792         page_pools.epp_st_shrinks = 0;
793         page_pools.epp_st_access = 0;
794         page_pools.epp_st_missings = 0;
795         page_pools.epp_st_lowfree = 0;
796         page_pools.epp_st_max_wqlen = 0;
797         page_pools.epp_st_max_wait = ktime_set(0, 0);
798         page_pools.epp_st_outofmem = 0;
799
800         enc_pools_alloc();
801         if (page_pools.epp_pools == NULL)
802                 return -ENOMEM;
803
804         pools_shrinker = set_shrinker(pools_shrinker_seeks, &shvar);
805         if (pools_shrinker == NULL) {
806                 enc_pools_free();
807                 return -ENOMEM;
808         }
809
810         return 0;
811 }
812
813 void sptlrpc_enc_pool_fini(void)
814 {
815         unsigned long cleaned, npools;
816
817         LASSERT(pools_shrinker);
818         LASSERT(page_pools.epp_pools);
819         LASSERT(page_pools.epp_total_pages == page_pools.epp_free_pages);
820
821         remove_shrinker(pools_shrinker);
822
823         npools = npages_to_npools(page_pools.epp_total_pages);
824         cleaned = enc_pools_cleanup(page_pools.epp_pools, npools);
825         LASSERT(cleaned == page_pools.epp_total_pages);
826
827         enc_pools_free();
828
829         if (page_pools.epp_st_access > 0) {
830                 CDEBUG(D_SEC,
831                        "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",
832                        page_pools.epp_st_max_pages, page_pools.epp_st_grows,
833                        page_pools.epp_st_grow_fails,
834                        page_pools.epp_st_shrinks, page_pools.epp_st_access,
835                        page_pools.epp_st_missings, page_pools.epp_st_max_wqlen,
836                        ktime_to_ms(page_pools.epp_st_max_wait),
837                        page_pools.epp_st_outofmem);
838         }
839 }
840
841
842 static int cfs_hash_alg_id[] = {
843         [BULK_HASH_ALG_NULL]    = CFS_HASH_ALG_NULL,
844         [BULK_HASH_ALG_ADLER32] = CFS_HASH_ALG_ADLER32,
845         [BULK_HASH_ALG_CRC32]   = CFS_HASH_ALG_CRC32,
846         [BULK_HASH_ALG_MD5]     = CFS_HASH_ALG_MD5,
847         [BULK_HASH_ALG_SHA1]    = CFS_HASH_ALG_SHA1,
848         [BULK_HASH_ALG_SHA256]  = CFS_HASH_ALG_SHA256,
849         [BULK_HASH_ALG_SHA384]  = CFS_HASH_ALG_SHA384,
850         [BULK_HASH_ALG_SHA512]  = CFS_HASH_ALG_SHA512,
851 };
852 const char *sptlrpc_get_hash_name(__u8 hash_alg)
853 {
854         return cfs_crypto_hash_name(cfs_hash_alg_id[hash_alg]);
855 }
856
857 __u8 sptlrpc_get_hash_alg(const char *algname)
858 {
859         return cfs_crypto_hash_alg(algname);
860 }
861
862 int bulk_sec_desc_unpack(struct lustre_msg *msg, int offset, int swabbed)
863 {
864         struct ptlrpc_bulk_sec_desc *bsd;
865         int size = msg->lm_buflens[offset];
866
867         bsd = lustre_msg_buf(msg, offset, sizeof(*bsd));
868         if (bsd == NULL) {
869                 CERROR("Invalid bulk sec desc: size %d\n", size);
870                 return -EINVAL;
871         }
872
873         if (swabbed)
874                 __swab32s(&bsd->bsd_nob);
875
876         if (unlikely(bsd->bsd_version != 0)) {
877                 CERROR("Unexpected version %u\n", bsd->bsd_version);
878                 return -EPROTO;
879         }
880
881         if (unlikely(bsd->bsd_type >= SPTLRPC_BULK_MAX)) {
882                 CERROR("Invalid type %u\n", bsd->bsd_type);
883                 return -EPROTO;
884         }
885
886         /* FIXME more sanity check here */
887
888         if (unlikely(bsd->bsd_svc != SPTLRPC_BULK_SVC_NULL &&
889                      bsd->bsd_svc != SPTLRPC_BULK_SVC_INTG &&
890                      bsd->bsd_svc != SPTLRPC_BULK_SVC_PRIV)) {
891                 CERROR("Invalid svc %u\n", bsd->bsd_svc);
892                 return -EPROTO;
893         }
894
895         return 0;
896 }
897 EXPORT_SYMBOL(bulk_sec_desc_unpack);
898
899 /*
900  * Compute the checksum of an RPC buffer payload.  If the return \a buflen
901  * is not large enough, truncate the result to fit so that it is possible
902  * to use a hash function with a large hash space, but only use a part of
903  * the resulting hash.
904  */
905 int sptlrpc_get_bulk_checksum(struct ptlrpc_bulk_desc *desc, __u8 alg,
906                               void *buf, int buflen)
907 {
908         struct ahash_request *req;
909         int hashsize;
910         unsigned int bufsize;
911         int i, err;
912
913         LASSERT(alg > BULK_HASH_ALG_NULL && alg < BULK_HASH_ALG_MAX);
914         LASSERT(buflen >= 4);
915
916         req = cfs_crypto_hash_init(cfs_hash_alg_id[alg], NULL, 0);
917         if (IS_ERR(req)) {
918                 CERROR("Unable to initialize checksum hash %s\n",
919                        cfs_crypto_hash_name(cfs_hash_alg_id[alg]));
920                 return PTR_ERR(req);
921         }
922
923         hashsize = cfs_crypto_hash_digestsize(cfs_hash_alg_id[alg]);
924
925         for (i = 0; i < desc->bd_iov_count; i++) {
926                 cfs_crypto_hash_update_page(req,
927                                   desc->bd_vec[i].bv_page,
928                                   desc->bd_vec[i].bv_offset &
929                                               ~PAGE_MASK,
930                                   desc->bd_vec[i].bv_len);
931         }
932
933         if (hashsize > buflen) {
934                 unsigned char hashbuf[CFS_CRYPTO_HASH_DIGESTSIZE_MAX];
935
936                 bufsize = sizeof(hashbuf);
937                 LASSERTF(bufsize >= hashsize, "bufsize = %u < hashsize %u\n",
938                          bufsize, hashsize);
939                 err = cfs_crypto_hash_final(req, hashbuf, &bufsize);
940                 memcpy(buf, hashbuf, buflen);
941         } else {
942                 bufsize = buflen;
943                 err = cfs_crypto_hash_final(req, buf, &bufsize);
944         }
945
946         return err;
947 }