Whamcloud - gitweb
6d01de35d3584894f74f6eaa5eed07672190f0c8
[fs/lustre-release.git] / libcfs / libcfs / linux / linux-crypto.c
1 /* GPL HEADER START
2  *
3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License version 2 only,
7  * as published by the Free Software Foundation.
8  *
9  * This program is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * General Public License version 2 for more details (a copy is included
13  * in the LICENSE file that accompanied this code).
14  *
15  * You should have received a copy of the GNU General Public License
16  * version 2 along with this program; If not, see http://www.gnu.org/licenses
17  *
18  * Please  visit http://www.xyratex.com/contact if you need additional
19  * information or have any questions.
20  *
21  * GPL HEADER END
22  */
23
24 /*
25  * Copyright 2012 Xyratex Technology Limited
26  *
27  * Copyright (c) 2012, 2014, Intel Corporation.
28  */
29
30 #include <crypto/hash.h>
31 #include <linux/scatterlist.h>
32 #include <libcfs/libcfs.h>
33 #include <libcfs/libcfs_crypto.h>
34 #include <libcfs/linux/linux-crypto.h>
35
36 #ifndef crypto_ahash_alg_name
37 static inline const char *crypto_ahash_alg_name(struct crypto_ahash *tfm)
38 {
39         return crypto_tfm_alg_name(crypto_ahash_tfm(tfm));
40 }
41 #endif
42
43 #ifndef crypto_ahash_driver_name
44 static inline const char *crypto_ahash_driver_name(struct crypto_ahash *tfm)
45 {
46         return crypto_tfm_alg_driver_name(crypto_ahash_tfm(tfm));
47 }
48 #endif
49
50 /**
51  *  Array of hash algorithm speed in MByte per second
52  */
53 static int cfs_crypto_hash_speeds[CFS_HASH_ALG_MAX];
54
55 /**
56  * Initialize the state descriptor for the specified hash algorithm.
57  *
58  * An internal routine to allocate the hash-specific state in \a hdesc for
59  * use with cfs_crypto_hash_digest() to compute the hash of a single message,
60  * though possibly in multiple chunks.  The descriptor internal state should
61  * be freed with cfs_crypto_hash_final().
62  *
63  * \param[in]  hash_alg hash algorithm id (CFS_HASH_ALG_*)
64  * \param[out] type     pointer to the hash description in hash_types[] array
65  * \param[in,out] req   ahash request to be initialized
66  * \param[in]  key      initial hash value/state, NULL to use default value
67  * \param[in]  key_len  length of \a key
68  *
69  * \retval              0 on success
70  * \retval              negative errno on failure
71  */
72 static int cfs_crypto_hash_alloc(enum cfs_crypto_hash_alg hash_alg,
73                                  const struct cfs_crypto_hash_type **type,
74                                  struct ahash_request **req,
75                                  unsigned char *key,
76                                  unsigned int key_len)
77 {
78         struct crypto_ahash *tfm;
79         int err = 0;
80
81         *type = cfs_crypto_hash_type(hash_alg);
82
83         if (*type == NULL) {
84                 CWARN("Unsupported hash algorithm id = %d, max id is %d\n",
85                       hash_alg, CFS_HASH_ALG_MAX);
86                 return -EINVAL;
87         }
88         tfm = crypto_alloc_ahash((*type)->cht_name, 0, CRYPTO_ALG_ASYNC);
89         if (IS_ERR(tfm)) {
90                 CDEBUG(D_INFO, "Failed to alloc crypto hash %s\n",
91                        (*type)->cht_name);
92                 return PTR_ERR(tfm);
93         }
94
95         *req = ahash_request_alloc(tfm, GFP_KERNEL);
96         if (!*req) {
97                 CDEBUG(D_INFO, "Failed to alloc ahash_request for %s\n",
98                        (*type)->cht_name);
99                 crypto_free_ahash(tfm);
100                 return -ENOMEM;
101         }
102
103         ahash_request_set_callback(*req, 0, NULL, NULL);
104
105         if (key)
106                 err = crypto_ahash_setkey(tfm, key, key_len);
107         else if ((*type)->cht_key != 0)
108                 err = crypto_ahash_setkey(tfm,
109                                          (unsigned char *)&((*type)->cht_key),
110                                          (*type)->cht_size);
111
112         if (err != 0) {
113                 ahash_request_free(*req);
114                 crypto_free_ahash(tfm);
115                 return err;
116         }
117
118         CDEBUG(D_INFO, "Using crypto hash: %s (%s) speed %d MB/s\n",
119                crypto_ahash_alg_name(tfm), crypto_ahash_driver_name(tfm),
120                cfs_crypto_hash_speeds[hash_alg]);
121
122         err = crypto_ahash_init(*req);
123         if (err) {
124                 ahash_request_free(*req);
125                 crypto_free_ahash(tfm);
126         }
127         return err;
128 }
129
130 /**
131  * Calculate hash digest for the passed buffer.
132  *
133  * This should be used when computing the hash on a single contiguous buffer.
134  * It combines the hash initialization, computation, and cleanup.
135  *
136  * \param[in] hash_alg  id of hash algorithm (CFS_HASH_ALG_*)
137  * \param[in] buf       data buffer on which to compute hash
138  * \param[in] buf_len   length of \a buf in bytes
139  * \param[in] key       initial value/state for algorithm, if \a key = NULL
140  *                      use default initial value
141  * \param[in] key_len   length of \a key in bytes
142  * \param[out] hash     pointer to computed hash value, if \a hash = NULL then
143  *                      \a hash_len is to digest size in bytes, retval -ENOSPC
144  * \param[in,out] hash_len size of \a hash buffer
145  *
146  * \retval -EINVAL       \a buf, \a buf_len, \a hash_len, \a hash_alg invalid
147  * \retval -ENOENT       \a hash_alg is unsupported
148  * \retval -ENOSPC       \a hash is NULL, or \a hash_len less than digest size
149  * \retval              0 for success
150  * \retval              negative errno for other errors from lower layers.
151  */
152 int cfs_crypto_hash_digest(enum cfs_crypto_hash_alg hash_alg,
153                            const void *buf, unsigned int buf_len,
154                            unsigned char *key, unsigned int key_len,
155                            unsigned char *hash, unsigned int *hash_len)
156 {
157         struct scatterlist      sl;
158         struct ahash_request *req;
159         int                     err;
160         const struct cfs_crypto_hash_type       *type;
161
162         if (!buf || buf_len == 0 || !hash_len)
163                 return -EINVAL;
164
165         err = cfs_crypto_hash_alloc(hash_alg, &type, &req, key, key_len);
166         if (err != 0)
167                 return err;
168
169         if (!hash || *hash_len < type->cht_size) {
170                 *hash_len = type->cht_size;
171                 crypto_free_ahash(crypto_ahash_reqtfm(req));
172                 ahash_request_free(req);
173                 return -ENOSPC;
174         }
175         sg_init_one(&sl, (void *)buf, buf_len);
176
177         ahash_request_set_crypt(req, &sl, hash, sl.length);
178         err = crypto_ahash_digest(req);
179         crypto_free_ahash(crypto_ahash_reqtfm(req));
180         ahash_request_free(req);
181
182         return err;
183 }
184 EXPORT_SYMBOL(cfs_crypto_hash_digest);
185
186 /**
187  * Allocate and initialize desriptor for hash algorithm.
188  *
189  * This should be used to initialize a hash descriptor for multiple calls
190  * to a single hash function when computing the hash across multiple
191  * separate buffers or pages using cfs_crypto_hash_update{,_page}().
192  *
193  * The hash descriptor should be freed with cfs_crypto_hash_final().
194  *
195  * \param[in] hash_alg  algorithm id (CFS_HASH_ALG_*)
196  * \param[in] key       initial value/state for algorithm, if \a key = NULL
197  *                      use default initial value
198  * \param[in] key_len   length of \a key in bytes
199  *
200  * \retval              pointer to descriptor of hash instance
201  * \retval              ERR_PTR(errno) in case of error
202  */
203 struct cfs_crypto_hash_desc *
204         cfs_crypto_hash_init(enum cfs_crypto_hash_alg hash_alg,
205                              unsigned char *key, unsigned int key_len)
206 {
207         struct ahash_request *req;
208         int                                     err;
209         const struct cfs_crypto_hash_type       *type;
210
211         err = cfs_crypto_hash_alloc(hash_alg, &type, &req, key, key_len);
212         if (err)
213                 return ERR_PTR(err);
214         return (struct cfs_crypto_hash_desc *)req;
215 }
216 EXPORT_SYMBOL(cfs_crypto_hash_init);
217
218 /**
219  * Update hash digest computed on data within the given \a page
220  *
221  * \param[in] hdesc     hash state descriptor
222  * \param[in] page      data page on which to compute the hash
223  * \param[in] offset    offset within \a page at which to start hash
224  * \param[in] len       length of data on which to compute hash
225  *
226  * \retval              0 for success
227  * \retval              negative errno on failure
228  */
229 int cfs_crypto_hash_update_page(struct cfs_crypto_hash_desc *hdesc,
230                                 struct page *page, unsigned int offset,
231                                 unsigned int len)
232 {
233         struct ahash_request *req = (void *)hdesc;
234         struct scatterlist sl;
235
236         sg_init_table(&sl, 1);
237         sg_set_page(&sl, page, len, offset & ~PAGE_MASK);
238
239         ahash_request_set_crypt(req, &sl, NULL, sl.length);
240         return crypto_ahash_update(req);
241 }
242 EXPORT_SYMBOL(cfs_crypto_hash_update_page);
243
244 /**
245  * Update hash digest computed on the specified data
246  *
247  * \param[in] hdesc     hash state descriptor
248  * \param[in] buf       data buffer on which to compute the hash
249  * \param[in] buf_len   length of \buf on which to compute hash
250  *
251  * \retval              0 for success
252  * \retval              negative errno on failure
253  */
254 int cfs_crypto_hash_update(struct cfs_crypto_hash_desc *hdesc,
255                            const void *buf, unsigned int buf_len)
256 {
257         struct ahash_request *req = (void *)hdesc;
258         struct scatterlist sl;
259
260         sg_init_one(&sl, (void *)buf, buf_len);
261
262         ahash_request_set_crypt(req, &sl, NULL, sl.length);
263         return crypto_ahash_update(req);
264 }
265 EXPORT_SYMBOL(cfs_crypto_hash_update);
266
267 /**
268  * Finish hash calculation, copy hash digest to buffer, clean up hash descriptor
269  *
270  * \param[in]   hdesc           hash descriptor
271  * \param[out]  hash            pointer to hash buffer to store hash digest
272  * \param[in,out] hash_len      pointer to hash buffer size, if \a hash == NULL
273  *                              or hash_len == NULL only free \a hdesc instead
274  *                              of computing the hash
275  *
276  * \retval              0 for success
277  * \retval              -EOVERFLOW if hash_len is too small for the hash digest
278  * \retval              negative errno for other errors from lower layers
279  */
280 int cfs_crypto_hash_final(struct cfs_crypto_hash_desc *hdesc,
281                           unsigned char *hash, unsigned int *hash_len)
282 {
283         struct ahash_request *req = (void *)hdesc;
284         int size = crypto_ahash_digestsize(crypto_ahash_reqtfm(req));
285         int err;
286
287         if (!hash || !hash_len) {
288                 err = 0;
289                 goto free;
290         }
291         if (*hash_len < size) {
292                 err = -EOVERFLOW;
293                 goto free;
294         }
295
296         ahash_request_set_crypt(req, NULL, hash, 0);
297         err = crypto_ahash_final(req);
298         if (err == 0)
299                 *hash_len = size;
300 free:
301         crypto_free_ahash(crypto_ahash_reqtfm(req));
302         ahash_request_free(req);
303
304         return err;
305 }
306 EXPORT_SYMBOL(cfs_crypto_hash_final);
307
308 /**
309  * Compute the speed of specified hash function
310  *
311  * Run a speed test on the given hash algorithm on buffer of the given size.
312  * The speed is stored internally in the cfs_crypto_hash_speeds[] array, and
313  * is available through the cfs_crypto_hash_speed() function.
314  *
315  * \param[in] hash_alg  hash algorithm id (CFS_HASH_ALG_*)
316  * \param[in] buf       data buffer on which to compute the hash
317  * \param[in] buf_len   length of \buf on which to compute hash
318  */
319 static void cfs_crypto_performance_test(enum cfs_crypto_hash_alg hash_alg)
320 {
321         int                     buf_len = max(PAGE_SIZE, 1048576UL);
322         void                    *buf;
323         unsigned long           start, end;
324         int                     bcount, err = 0;
325         struct page             *page;
326         unsigned char           hash[CFS_CRYPTO_HASH_DIGESTSIZE_MAX];
327         unsigned int            hash_len = sizeof(hash);
328
329         page = alloc_page(GFP_KERNEL);
330         if (page == NULL) {
331                 err = -ENOMEM;
332                 goto out_err;
333         }
334
335         buf = kmap(page);
336         memset(buf, 0xAD, PAGE_SIZE);
337         kunmap(page);
338
339         for (start = jiffies, end = start + msecs_to_jiffies(MSEC_PER_SEC),
340              bcount = 0;
341              time_before(jiffies, end) && err == 0; bcount++) {
342                 struct cfs_crypto_hash_desc *hdesc;
343                 int i;
344
345                 hdesc = cfs_crypto_hash_init(hash_alg, NULL, 0);
346                 if (IS_ERR(hdesc)) {
347                         err = PTR_ERR(hdesc);
348                         break;
349                 }
350
351                 for (i = 0; i < buf_len / PAGE_SIZE; i++) {
352                         err = cfs_crypto_hash_update_page(hdesc, page, 0,
353                                                           PAGE_SIZE);
354                         if (err != 0)
355                                 break;
356                 }
357
358                 err = cfs_crypto_hash_final(hdesc, hash, &hash_len);
359                 if (err != 0)
360                         break;
361         }
362         end = jiffies;
363         __free_page(page);
364 out_err:
365         if (err != 0) {
366                 cfs_crypto_hash_speeds[hash_alg] = err;
367                 CDEBUG(D_INFO, "Crypto hash algorithm %s test error: rc = %d\n",
368                        cfs_crypto_hash_name(hash_alg), err);
369         } else {
370                 unsigned long   tmp;
371
372                 tmp = ((bcount * buf_len / jiffies_to_msecs(end - start)) *
373                        1000) / (1024 * 1024);
374                 cfs_crypto_hash_speeds[hash_alg] = (int)tmp;
375                 CDEBUG(D_CONFIG, "Crypto hash algorithm %s speed = %d MB/s\n",
376                        cfs_crypto_hash_name(hash_alg),
377                        cfs_crypto_hash_speeds[hash_alg]);
378         }
379 }
380
381 /**
382  * hash speed in Mbytes per second for valid hash algorithm
383  *
384  * Return the performance of the specified \a hash_alg that was previously
385  * computed using cfs_crypto_performance_test().
386  *
387  * \param[in] hash_alg  hash algorithm id (CFS_HASH_ALG_*)
388  *
389  * \retval              positive speed of the hash function in MB/s
390  * \retval              -ENOENT if \a hash_alg is unsupported
391  * \retval              negative errno if \a hash_alg speed is unavailable
392  */
393 int cfs_crypto_hash_speed(enum cfs_crypto_hash_alg hash_alg)
394 {
395         if (hash_alg < CFS_HASH_ALG_MAX)
396                 return cfs_crypto_hash_speeds[hash_alg];
397
398         return -ENOENT;
399 }
400 EXPORT_SYMBOL(cfs_crypto_hash_speed);
401
402 /**
403  * Run the performance test for all hash algorithms.
404  *
405  * Run the cfs_crypto_performance_test() benchmark for all of the available
406  * hash functions using a 1MB buffer size.  This is a reasonable buffer size
407  * for Lustre RPCs, even if the actual RPC size is larger or smaller.
408  *
409  * Since the setup cost and computation speed of various hash algorithms is
410  * a function of the buffer size (and possibly internal contention of offload
411  * engines), this speed only represents an estimate of the actual speed under
412  * actual usage, but is reasonable for comparing available algorithms.
413  *
414  * The actual speeds are available via cfs_crypto_hash_speed() for later
415  * comparison.
416  *
417  * \retval              0 on success
418  * \retval              -ENOMEM if no memory is available for test buffer
419  */
420 static int cfs_crypto_test_hashes(void)
421 {
422         enum cfs_crypto_hash_alg hash_alg;
423
424         for (hash_alg = 0; hash_alg < CFS_HASH_ALG_MAX; hash_alg++)
425                 cfs_crypto_performance_test(hash_alg);
426
427         return 0;
428 }
429
430 static int adler32;
431
432 #ifdef HAVE_CRC32
433 static int crc32;
434 #endif
435 #ifdef HAVE_PCLMULQDQ
436 #ifdef NEED_CRC32_ACCEL
437 static int crc32_pclmul;
438 #endif
439 #ifdef NEED_CRC32C_ACCEL
440 static int crc32c_pclmul;
441 #endif
442 #endif /* HAVE_PCLMULQDQ */
443
444 /**
445  * Register available hash functions
446  *
447  * \retval              0
448  */
449 int cfs_crypto_register(void)
450 {
451         request_module("crc32c");
452
453         adler32 = cfs_crypto_adler32_register();
454
455 #ifdef HAVE_CRC32
456         crc32 = cfs_crypto_crc32_register();
457 #endif
458 #ifdef HAVE_PCLMULQDQ
459 #ifdef NEED_CRC32_ACCEL
460         crc32_pclmul = cfs_crypto_crc32_pclmul_register();
461 #endif
462 #ifdef NEED_CRC32C_ACCEL
463         crc32c_pclmul = cfs_crypto_crc32c_pclmul_register();
464 #endif
465 #endif /* HAVE_PCLMULQDQ */
466
467         /* check all algorithms and do performance test */
468         cfs_crypto_test_hashes();
469
470         return 0;
471 }
472
473 /**
474  * Unregister previously registered hash functions
475  */
476 void cfs_crypto_unregister(void)
477 {
478         if (adler32 == 0)
479                 cfs_crypto_adler32_unregister();
480
481 #ifdef HAVE_CRC32
482         if (crc32 == 0)
483                 cfs_crypto_crc32_unregister();
484 #endif
485 #ifdef HAVE_PCLMULQDQ
486 #ifdef NEED_CRC32_ACCEL
487         if (crc32_pclmul == 0)
488                 cfs_crypto_crc32_pclmul_unregister();
489 #endif
490 #ifdef NEED_CRC32C_ACCEL
491         if (crc32c_pclmul == 0)
492                 cfs_crypto_crc32c_pclmul_unregister();
493 #endif
494 #endif /* HAVE_PCLMULQDQ */
495 }