Whamcloud - gitweb
8e84243628e6e329249ee9f62ec5c155355dcc85
[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  * /proc/fs/lustre/sptlrpc/encrypt_page_pools
119  */
120 int sptlrpc_proc_enc_pool_seq_show(struct seq_file *m, void *v)
121 {
122         spin_lock(&page_pools.epp_lock);
123
124         seq_printf(m, "physical pages:          %lu\n"
125                    "pages per pool:          %lu\n"
126                    "max pages:               %lu\n"
127                    "max pools:               %u\n"
128                    "total pages:             %lu\n"
129                    "total free:              %lu\n"
130                    "idle index:              %lu/100\n"
131                    "last shrink:             %llds\n"
132                    "last access:             %llds\n"
133                    "max pages reached:       %lu\n"
134                    "grows:                   %u\n"
135                    "grows failure:           %u\n"
136                    "shrinks:                 %u\n"
137                    "cache access:            %lu\n"
138                    "cache missing:           %lu\n"
139                    "low free mark:           %lu\n"
140                    "max waitqueue depth:     %u\n"
141                    "max wait time ms:        %lld\n"
142                    "out of mem:              %lu\n",
143                    cfs_totalram_pages(), PAGES_PER_POOL,
144                    page_pools.epp_max_pages,
145                    page_pools.epp_max_pools,
146                    page_pools.epp_total_pages,
147                    page_pools.epp_free_pages,
148                    page_pools.epp_idle_idx,
149                    ktime_get_seconds() - page_pools.epp_last_shrink,
150                    ktime_get_seconds() - page_pools.epp_last_access,
151                    page_pools.epp_st_max_pages,
152                    page_pools.epp_st_grows,
153                    page_pools.epp_st_grow_fails,
154                    page_pools.epp_st_shrinks,
155                    page_pools.epp_st_access,
156                    page_pools.epp_st_missings,
157                    page_pools.epp_st_lowfree,
158                    page_pools.epp_st_max_wqlen,
159                    ktime_to_ms(page_pools.epp_st_max_wait),
160                    page_pools.epp_st_outofmem);
161
162         spin_unlock(&page_pools.epp_lock);
163         return 0;
164 }
165
166 static void enc_pools_release_free_pages(long npages)
167 {
168         int p_idx, g_idx;
169         int p_idx_max1, p_idx_max2;
170
171         LASSERT(npages > 0);
172         LASSERT(npages <= page_pools.epp_free_pages);
173         LASSERT(page_pools.epp_free_pages <= page_pools.epp_total_pages);
174
175         /* max pool index before the release */
176         p_idx_max2 = (page_pools.epp_total_pages - 1) / PAGES_PER_POOL;
177
178         page_pools.epp_free_pages -= npages;
179         page_pools.epp_total_pages -= npages;
180
181         /* max pool index after the release */
182         p_idx_max1 = page_pools.epp_total_pages == 0 ? -1 :
183                 ((page_pools.epp_total_pages - 1) / PAGES_PER_POOL);
184
185         p_idx = page_pools.epp_free_pages / PAGES_PER_POOL;
186         g_idx = page_pools.epp_free_pages % PAGES_PER_POOL;
187         LASSERT(page_pools.epp_pools[p_idx]);
188
189         while (npages--) {
190                 LASSERT(page_pools.epp_pools[p_idx]);
191                 LASSERT(page_pools.epp_pools[p_idx][g_idx] != NULL);
192
193                 __free_page(page_pools.epp_pools[p_idx][g_idx]);
194                 page_pools.epp_pools[p_idx][g_idx] = NULL;
195
196                 if (++g_idx == PAGES_PER_POOL) {
197                         p_idx++;
198                         g_idx = 0;
199                 }
200         }
201
202         /* free unused pools */
203         while (p_idx_max1 < p_idx_max2) {
204                 LASSERT(page_pools.epp_pools[p_idx_max2]);
205                 OBD_FREE(page_pools.epp_pools[p_idx_max2], PAGE_SIZE);
206                 page_pools.epp_pools[p_idx_max2] = NULL;
207                 p_idx_max2--;
208         }
209 }
210
211 /*
212  * we try to keep at least PTLRPC_MAX_BRW_PAGES pages in the pool.
213  */
214 static unsigned long enc_pools_shrink_count(struct shrinker *s,
215                                             struct shrink_control *sc)
216 {
217         /*
218          * if no pool access for a long time, we consider it's fully idle.
219          * a little race here is fine.
220          */
221         if (unlikely(ktime_get_seconds() - page_pools.epp_last_access >
222                      CACHE_QUIESCENT_PERIOD)) {
223                 spin_lock(&page_pools.epp_lock);
224                 page_pools.epp_idle_idx = IDLE_IDX_MAX;
225                 spin_unlock(&page_pools.epp_lock);
226         }
227
228         LASSERT(page_pools.epp_idle_idx <= IDLE_IDX_MAX);
229         return (page_pools.epp_free_pages <= PTLRPC_MAX_BRW_PAGES) ? 0 :
230                 (page_pools.epp_free_pages - PTLRPC_MAX_BRW_PAGES) *
231                 (IDLE_IDX_MAX - page_pools.epp_idle_idx) / IDLE_IDX_MAX;
232 }
233
234 /*
235  * we try to keep at least PTLRPC_MAX_BRW_PAGES pages in the pool.
236  */
237 static unsigned long enc_pools_shrink_scan(struct shrinker *s,
238                                            struct shrink_control *sc)
239 {
240         spin_lock(&page_pools.epp_lock);
241         if (page_pools.epp_free_pages <= PTLRPC_MAX_BRW_PAGES)
242                 sc->nr_to_scan = 0;
243         else
244                 sc->nr_to_scan = min_t(unsigned long, sc->nr_to_scan,
245                               page_pools.epp_free_pages - PTLRPC_MAX_BRW_PAGES);
246         if (sc->nr_to_scan > 0) {
247                 enc_pools_release_free_pages(sc->nr_to_scan);
248                 CDEBUG(D_SEC, "released %ld pages, %ld left\n",
249                        (long)sc->nr_to_scan, page_pools.epp_free_pages);
250
251                 page_pools.epp_st_shrinks++;
252                 page_pools.epp_last_shrink = ktime_get_seconds();
253         }
254         spin_unlock(&page_pools.epp_lock);
255
256         /*
257          * if no pool access for a long time, we consider it's fully idle.
258          * a little race here is fine.
259          */
260         if (unlikely(ktime_get_seconds() - page_pools.epp_last_access >
261                      CACHE_QUIESCENT_PERIOD)) {
262                 spin_lock(&page_pools.epp_lock);
263                 page_pools.epp_idle_idx = IDLE_IDX_MAX;
264                 spin_unlock(&page_pools.epp_lock);
265         }
266
267         LASSERT(page_pools.epp_idle_idx <= IDLE_IDX_MAX);
268         return sc->nr_to_scan;
269 }
270
271 #ifdef HAVE_SHRINKER_COUNT
272 static struct shrinker pools_shrinker = {
273         .count_objects  = enc_pools_shrink_count,
274         .scan_objects   = enc_pools_shrink_scan,
275         .seeks          = DEFAULT_SEEKS,
276 };
277 #else
278 /*
279  * could be called frequently for query (@nr_to_scan == 0).
280  * we try to keep at least PTLRPC_MAX_BRW_PAGES pages in the pool.
281  */
282 static int enc_pools_shrink(struct shrinker *shrinker,
283                             struct shrink_control *sc)
284 {
285         enc_pools_shrink_scan(shrinker, sc);
286
287         return enc_pools_shrink_count(shrinker, sc);
288 }
289
290 static struct shrinker pools_shrinker = {
291         .shrink  = enc_pools_shrink,
292         .seeks   = DEFAULT_SEEKS,
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(&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         int rc;
766
767         page_pools.epp_max_pages = cfs_totalram_pages() / 8;
768         if (enc_pool_max_memory_mb > 0 &&
769             enc_pool_max_memory_mb <= (cfs_totalram_pages() >> mult))
770                 page_pools.epp_max_pages = enc_pool_max_memory_mb << mult;
771
772         page_pools.epp_max_pools = npages_to_npools(page_pools.epp_max_pages);
773
774         init_waitqueue_head(&page_pools.epp_waitq);
775         page_pools.epp_waitqlen = 0;
776         page_pools.epp_pages_short = 0;
777
778         page_pools.epp_growing = 0;
779
780         page_pools.epp_idle_idx = 0;
781         page_pools.epp_last_shrink = ktime_get_seconds();
782         page_pools.epp_last_access = ktime_get_seconds();
783
784         spin_lock_init(&page_pools.epp_lock);
785         page_pools.epp_total_pages = 0;
786         page_pools.epp_free_pages = 0;
787
788         page_pools.epp_st_max_pages = 0;
789         page_pools.epp_st_grows = 0;
790         page_pools.epp_st_grow_fails = 0;
791         page_pools.epp_st_shrinks = 0;
792         page_pools.epp_st_access = 0;
793         page_pools.epp_st_missings = 0;
794         page_pools.epp_st_lowfree = 0;
795         page_pools.epp_st_max_wqlen = 0;
796         page_pools.epp_st_max_wait = ktime_set(0, 0);
797         page_pools.epp_st_outofmem = 0;
798
799         enc_pools_alloc();
800         if (page_pools.epp_pools == NULL)
801                 return -ENOMEM;
802
803         rc = register_shrinker(&pools_shrinker);
804         if (rc)
805                 enc_pools_free();
806
807         return rc;
808 }
809
810 void sptlrpc_enc_pool_fini(void)
811 {
812         unsigned long cleaned, npools;
813
814         LASSERT(page_pools.epp_pools);
815         LASSERT(page_pools.epp_total_pages == page_pools.epp_free_pages);
816
817         unregister_shrinker(&pools_shrinker);
818
819         npools = npages_to_npools(page_pools.epp_total_pages);
820         cleaned = enc_pools_cleanup(page_pools.epp_pools, npools);
821         LASSERT(cleaned == page_pools.epp_total_pages);
822
823         enc_pools_free();
824
825         if (page_pools.epp_st_access > 0) {
826                 CDEBUG(D_SEC,
827                        "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",
828                        page_pools.epp_st_max_pages, page_pools.epp_st_grows,
829                        page_pools.epp_st_grow_fails,
830                        page_pools.epp_st_shrinks, page_pools.epp_st_access,
831                        page_pools.epp_st_missings, page_pools.epp_st_max_wqlen,
832                        ktime_to_ms(page_pools.epp_st_max_wait),
833                        page_pools.epp_st_outofmem);
834         }
835 }
836
837
838 static int cfs_hash_alg_id[] = {
839         [BULK_HASH_ALG_NULL]    = CFS_HASH_ALG_NULL,
840         [BULK_HASH_ALG_ADLER32] = CFS_HASH_ALG_ADLER32,
841         [BULK_HASH_ALG_CRC32]   = CFS_HASH_ALG_CRC32,
842         [BULK_HASH_ALG_MD5]     = CFS_HASH_ALG_MD5,
843         [BULK_HASH_ALG_SHA1]    = CFS_HASH_ALG_SHA1,
844         [BULK_HASH_ALG_SHA256]  = CFS_HASH_ALG_SHA256,
845         [BULK_HASH_ALG_SHA384]  = CFS_HASH_ALG_SHA384,
846         [BULK_HASH_ALG_SHA512]  = CFS_HASH_ALG_SHA512,
847 };
848 const char *sptlrpc_get_hash_name(__u8 hash_alg)
849 {
850         return cfs_crypto_hash_name(cfs_hash_alg_id[hash_alg]);
851 }
852
853 __u8 sptlrpc_get_hash_alg(const char *algname)
854 {
855         return cfs_crypto_hash_alg(algname);
856 }
857
858 int bulk_sec_desc_unpack(struct lustre_msg *msg, int offset, int swabbed)
859 {
860         struct ptlrpc_bulk_sec_desc *bsd;
861         int size = msg->lm_buflens[offset];
862
863         bsd = lustre_msg_buf(msg, offset, sizeof(*bsd));
864         if (bsd == NULL) {
865                 CERROR("Invalid bulk sec desc: size %d\n", size);
866                 return -EINVAL;
867         }
868
869         if (swabbed)
870                 __swab32s(&bsd->bsd_nob);
871
872         if (unlikely(bsd->bsd_version != 0)) {
873                 CERROR("Unexpected version %u\n", bsd->bsd_version);
874                 return -EPROTO;
875         }
876
877         if (unlikely(bsd->bsd_type >= SPTLRPC_BULK_MAX)) {
878                 CERROR("Invalid type %u\n", bsd->bsd_type);
879                 return -EPROTO;
880         }
881
882         /* FIXME more sanity check here */
883
884         if (unlikely(bsd->bsd_svc != SPTLRPC_BULK_SVC_NULL &&
885                      bsd->bsd_svc != SPTLRPC_BULK_SVC_INTG &&
886                      bsd->bsd_svc != SPTLRPC_BULK_SVC_PRIV)) {
887                 CERROR("Invalid svc %u\n", bsd->bsd_svc);
888                 return -EPROTO;
889         }
890
891         return 0;
892 }
893 EXPORT_SYMBOL(bulk_sec_desc_unpack);
894
895 /*
896  * Compute the checksum of an RPC buffer payload.  If the return \a buflen
897  * is not large enough, truncate the result to fit so that it is possible
898  * to use a hash function with a large hash space, but only use a part of
899  * the resulting hash.
900  */
901 int sptlrpc_get_bulk_checksum(struct ptlrpc_bulk_desc *desc, __u8 alg,
902                               void *buf, int buflen)
903 {
904         struct ahash_request *req;
905         int hashsize;
906         unsigned int bufsize;
907         int i, err;
908
909         LASSERT(alg > BULK_HASH_ALG_NULL && alg < BULK_HASH_ALG_MAX);
910         LASSERT(buflen >= 4);
911
912         req = cfs_crypto_hash_init(cfs_hash_alg_id[alg], NULL, 0);
913         if (IS_ERR(req)) {
914                 CERROR("Unable to initialize checksum hash %s\n",
915                        cfs_crypto_hash_name(cfs_hash_alg_id[alg]));
916                 return PTR_ERR(req);
917         }
918
919         hashsize = cfs_crypto_hash_digestsize(cfs_hash_alg_id[alg]);
920
921         for (i = 0; i < desc->bd_iov_count; i++) {
922                 cfs_crypto_hash_update_page(req,
923                                   desc->bd_vec[i].bv_page,
924                                   desc->bd_vec[i].bv_offset &
925                                               ~PAGE_MASK,
926                                   desc->bd_vec[i].bv_len);
927         }
928
929         if (hashsize > buflen) {
930                 unsigned char hashbuf[CFS_CRYPTO_HASH_DIGESTSIZE_MAX];
931
932                 bufsize = sizeof(hashbuf);
933                 LASSERTF(bufsize >= hashsize, "bufsize = %u < hashsize %u\n",
934                          bufsize, hashsize);
935                 err = cfs_crypto_hash_final(req, hashbuf, &bufsize);
936                 memcpy(buf, hashbuf, buflen);
937         } else {
938                 bufsize = buflen;
939                 err = cfs_crypto_hash_final(req, buf, &bufsize);
940         }
941
942         return err;
943 }