Whamcloud - gitweb
LU-8602 libcfs: call proper crypto algo when keys are passed in
[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 HAVE_CRYPTO_HASH_HELPERS
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
42 static inline const char *crypto_ahash_driver_name(struct crypto_ahash *tfm)
43 {
44         return crypto_tfm_alg_driver_name(crypto_ahash_tfm(tfm));
45 }
46 #endif
47
48 /**
49  *  Array of hash algorithm speed in MByte per second
50  */
51 static int cfs_crypto_hash_speeds[CFS_HASH_ALG_MAX];
52
53 /**
54  * Initialize the state descriptor for the specified hash algorithm.
55  *
56  * An internal routine to allocate the hash-specific state in \a hdesc for
57  * use with cfs_crypto_hash_digest() to compute the hash of a single message,
58  * though possibly in multiple chunks.  The descriptor internal state should
59  * be freed with cfs_crypto_hash_final().
60  *
61  * \param[in]  hash_alg hash algorithm id (CFS_HASH_ALG_*)
62  * \param[out] type     pointer to the hash description in hash_types[] array
63  * \param[in,out] req   ahash request to be initialized
64  * \param[in]  key      initial hash value/state, NULL to use default value
65  * \param[in]  key_len  length of \a key
66  *
67  * \retval              0 on success
68  * \retval              negative errno on failure
69  */
70 static int cfs_crypto_hash_alloc(enum cfs_crypto_hash_alg hash_alg,
71                                  const struct cfs_crypto_hash_type **type,
72                                  struct ahash_request **req,
73                                  unsigned char *key,
74                                  unsigned int key_len)
75 {
76         struct crypto_ahash *tfm;
77         int err = 0;
78
79         *type = cfs_crypto_hash_type(hash_alg);
80         if (!*type) {
81                 CWARN("Unsupported hash algorithm id = %d, max id is %d\n",
82                       hash_alg, CFS_HASH_ALG_MAX);
83                 return -EINVAL;
84         }
85
86         /* Keys are only supported for the hmac version */
87         if (key && key_len > 0) {
88                 char *algo_name;
89
90                 algo_name = kasprintf(GFP_KERNEL, "hmac(%s)",
91                                       (*type)->cht_name);
92                 if (!algo_name)
93                         return -ENOMEM;
94
95                 tfm = crypto_alloc_ahash(algo_name, 0, CRYPTO_ALG_ASYNC);
96                 kfree(algo_name);
97         } else {
98                 tfm = crypto_alloc_ahash((*type)->cht_name, 0,
99                                          CRYPTO_ALG_ASYNC);
100         }
101         if (IS_ERR(tfm)) {
102                 CDEBUG(D_INFO, "Failed to alloc crypto hash %s\n",
103                        (*type)->cht_name);
104                 return PTR_ERR(tfm);
105         }
106
107         *req = ahash_request_alloc(tfm, GFP_KERNEL);
108         if (!*req) {
109                 CDEBUG(D_INFO, "Failed to alloc ahash_request for %s\n",
110                        (*type)->cht_name);
111                 GOTO(out_free_tfm, err = -ENOMEM);
112         }
113
114         ahash_request_set_callback(*req, 0, NULL, NULL);
115
116         if (key)
117                 err = crypto_ahash_setkey(tfm, key, key_len);
118         else if ((*type)->cht_key != 0)
119                 err = crypto_ahash_setkey(tfm,
120                                          (unsigned char *)&((*type)->cht_key),
121                                          (*type)->cht_size);
122         if (err)
123                 GOTO(out_free_req, err);
124
125         CDEBUG(D_INFO, "Using crypto hash: %s (%s) speed %d MB/s\n",
126                crypto_ahash_alg_name(tfm), crypto_ahash_driver_name(tfm),
127                cfs_crypto_hash_speeds[hash_alg]);
128
129         err = crypto_ahash_init(*req);
130         if (err) {
131 out_free_req:
132                 ahash_request_free(*req);
133 out_free_tfm:
134                 crypto_free_ahash(tfm);
135         }
136         return err;
137 }
138
139 /**
140  * Calculate hash digest for the passed buffer.
141  *
142  * This should be used when computing the hash on a single contiguous buffer.
143  * It combines the hash initialization, computation, and cleanup.
144  *
145  * \param[in] hash_alg  id of hash algorithm (CFS_HASH_ALG_*)
146  * \param[in] buf       data buffer on which to compute hash
147  * \param[in] buf_len   length of \a buf in bytes
148  * \param[in] key       initial value/state for algorithm, if \a key = NULL
149  *                      use default initial value
150  * \param[in] key_len   length of \a key in bytes
151  * \param[out] hash     pointer to computed hash value, if \a hash = NULL then
152  *                      \a hash_len is to digest size in bytes, retval -ENOSPC
153  * \param[in,out] hash_len size of \a hash buffer
154  *
155  * \retval -EINVAL       \a buf, \a buf_len, \a hash_len, \a hash_alg invalid
156  * \retval -ENOENT       \a hash_alg is unsupported
157  * \retval -ENOSPC       \a hash is NULL, or \a hash_len less than digest size
158  * \retval              0 for success
159  * \retval              negative errno for other errors from lower layers.
160  */
161 int cfs_crypto_hash_digest(enum cfs_crypto_hash_alg hash_alg,
162                            const void *buf, unsigned int buf_len,
163                            unsigned char *key, unsigned int key_len,
164                            unsigned char *hash, unsigned int *hash_len)
165 {
166         struct scatterlist      sl;
167         struct ahash_request *req;
168         int                     err;
169         const struct cfs_crypto_hash_type       *type;
170
171         if (!buf || buf_len == 0 || !hash_len)
172                 return -EINVAL;
173
174         err = cfs_crypto_hash_alloc(hash_alg, &type, &req, key, key_len);
175         if (err != 0)
176                 return err;
177
178         if (!hash || *hash_len < type->cht_size) {
179                 *hash_len = type->cht_size;
180                 crypto_free_ahash(crypto_ahash_reqtfm(req));
181                 ahash_request_free(req);
182                 return -ENOSPC;
183         }
184         sg_init_one(&sl, (void *)buf, buf_len);
185
186         ahash_request_set_crypt(req, &sl, hash, sl.length);
187         err = crypto_ahash_digest(req);
188         crypto_free_ahash(crypto_ahash_reqtfm(req));
189         ahash_request_free(req);
190
191         return err;
192 }
193 EXPORT_SYMBOL(cfs_crypto_hash_digest);
194
195 /**
196  * Allocate and initialize desriptor for hash algorithm.
197  *
198  * This should be used to initialize a hash descriptor for multiple calls
199  * to a single hash function when computing the hash across multiple
200  * separate buffers or pages using cfs_crypto_hash_update{,_page}().
201  *
202  * The hash descriptor should be freed with cfs_crypto_hash_final().
203  *
204  * \param[in] hash_alg  algorithm id (CFS_HASH_ALG_*)
205  * \param[in] key       initial value/state for algorithm, if \a key = NULL
206  *                      use default initial value
207  * \param[in] key_len   length of \a key in bytes
208  *
209  * \retval              pointer to descriptor of hash instance
210  * \retval              ERR_PTR(errno) in case of error
211  */
212 struct cfs_crypto_hash_desc *
213         cfs_crypto_hash_init(enum cfs_crypto_hash_alg hash_alg,
214                              unsigned char *key, unsigned int key_len)
215 {
216         struct ahash_request *req;
217         int                                     err;
218         const struct cfs_crypto_hash_type       *type;
219
220         err = cfs_crypto_hash_alloc(hash_alg, &type, &req, key, key_len);
221         if (err)
222                 return ERR_PTR(err);
223         return (struct cfs_crypto_hash_desc *)req;
224 }
225 EXPORT_SYMBOL(cfs_crypto_hash_init);
226
227 /**
228  * Update hash digest computed on data within the given \a page
229  *
230  * \param[in] hdesc     hash state descriptor
231  * \param[in] page      data page on which to compute the hash
232  * \param[in] offset    offset within \a page at which to start hash
233  * \param[in] len       length of data on which to compute hash
234  *
235  * \retval              0 for success
236  * \retval              negative errno on failure
237  */
238 int cfs_crypto_hash_update_page(struct cfs_crypto_hash_desc *hdesc,
239                                 struct page *page, unsigned int offset,
240                                 unsigned int len)
241 {
242         struct ahash_request *req = (void *)hdesc;
243         struct scatterlist sl;
244
245         sg_init_table(&sl, 1);
246         sg_set_page(&sl, page, len, offset & ~PAGE_MASK);
247
248         ahash_request_set_crypt(req, &sl, NULL, sl.length);
249         return crypto_ahash_update(req);
250 }
251 EXPORT_SYMBOL(cfs_crypto_hash_update_page);
252
253 /**
254  * Update hash digest computed on the specified data
255  *
256  * \param[in] hdesc     hash state descriptor
257  * \param[in] buf       data buffer on which to compute the hash
258  * \param[in] buf_len   length of \buf on which to compute hash
259  *
260  * \retval              0 for success
261  * \retval              negative errno on failure
262  */
263 int cfs_crypto_hash_update(struct cfs_crypto_hash_desc *hdesc,
264                            const void *buf, unsigned int buf_len)
265 {
266         struct ahash_request *req = (void *)hdesc;
267         struct scatterlist sl;
268
269         sg_init_one(&sl, (void *)buf, buf_len);
270
271         ahash_request_set_crypt(req, &sl, NULL, sl.length);
272         return crypto_ahash_update(req);
273 }
274 EXPORT_SYMBOL(cfs_crypto_hash_update);
275
276 /**
277  * Finish hash calculation, copy hash digest to buffer, clean up hash descriptor
278  *
279  * \param[in]   hdesc           hash descriptor
280  * \param[out]  hash            pointer to hash buffer to store hash digest
281  * \param[in,out] hash_len      pointer to hash buffer size, if \a hash == NULL
282  *                              or hash_len == NULL only free \a hdesc instead
283  *                              of computing the hash
284  *
285  * \retval              0 for success
286  * \retval              -EOVERFLOW if hash_len is too small for the hash digest
287  * \retval              negative errno for other errors from lower layers
288  */
289 int cfs_crypto_hash_final(struct cfs_crypto_hash_desc *hdesc,
290                           unsigned char *hash, unsigned int *hash_len)
291 {
292         struct ahash_request *req = (void *)hdesc;
293         int size = crypto_ahash_digestsize(crypto_ahash_reqtfm(req));
294         int err;
295
296         if (!hash || !hash_len) {
297                 err = 0;
298                 goto free;
299         }
300         if (*hash_len < size) {
301                 err = -EOVERFLOW;
302                 goto free;
303         }
304
305         ahash_request_set_crypt(req, NULL, hash, 0);
306         err = crypto_ahash_final(req);
307         if (err == 0)
308                 *hash_len = size;
309 free:
310         crypto_free_ahash(crypto_ahash_reqtfm(req));
311         ahash_request_free(req);
312
313         return err;
314 }
315 EXPORT_SYMBOL(cfs_crypto_hash_final);
316
317 /**
318  * Compute the speed of specified hash function
319  *
320  * Run a speed test on the given hash algorithm on buffer using a 1MB buffer
321  * size.  This is a reasonable buffer size for Lustre RPCs, even if the actual
322  * RPC size is larger or smaller.
323  *
324  * The speed is stored internally in the cfs_crypto_hash_speeds[] array, and
325  * is available through the cfs_crypto_hash_speed() function.
326  *
327  * \param[in] hash_alg  hash algorithm id (CFS_HASH_ALG_*)
328  * \param[in] buf       data buffer on which to compute the hash
329  * \param[in] buf_len   length of \buf on which to compute hash
330  */
331 static void cfs_crypto_performance_test(enum cfs_crypto_hash_alg hash_alg)
332 {
333         int                     buf_len = max(PAGE_SIZE, 1048576UL);
334         void                    *buf;
335         unsigned long           start, end;
336         int                     err = 0;
337         unsigned long           bcount;
338         struct page             *page;
339         unsigned char           hash[CFS_CRYPTO_HASH_DIGESTSIZE_MAX];
340         unsigned int            hash_len = sizeof(hash);
341
342         page = alloc_page(GFP_KERNEL);
343         if (page == NULL) {
344                 err = -ENOMEM;
345                 goto out_err;
346         }
347
348         buf = kmap(page);
349         memset(buf, 0xAD, PAGE_SIZE);
350         kunmap(page);
351
352         for (start = jiffies, end = start + msecs_to_jiffies(MSEC_PER_SEC / 4),
353              bcount = 0; time_before(jiffies, end) && err == 0; bcount++) {
354                 struct cfs_crypto_hash_desc *hdesc;
355                 int i;
356
357                 hdesc = cfs_crypto_hash_init(hash_alg, NULL, 0);
358                 if (IS_ERR(hdesc)) {
359                         err = PTR_ERR(hdesc);
360                         break;
361                 }
362
363                 for (i = 0; i < buf_len / PAGE_SIZE; i++) {
364                         err = cfs_crypto_hash_update_page(hdesc, page, 0,
365                                                           PAGE_SIZE);
366                         if (err != 0)
367                                 break;
368                 }
369
370                 err = cfs_crypto_hash_final(hdesc, hash, &hash_len);
371                 if (err != 0)
372                         break;
373         }
374         end = jiffies;
375         __free_page(page);
376 out_err:
377         if (err != 0) {
378                 cfs_crypto_hash_speeds[hash_alg] = err;
379                 CDEBUG(D_INFO, "Crypto hash algorithm %s test error: rc = %d\n",
380                        cfs_crypto_hash_name(hash_alg), err);
381         } else {
382                 unsigned long   tmp;
383
384                 tmp = ((bcount * buf_len / jiffies_to_msecs(end - start)) *
385                        1000) / (1024 * 1024);
386                 cfs_crypto_hash_speeds[hash_alg] = (int)tmp;
387                 CDEBUG(D_CONFIG, "Crypto hash algorithm %s speed = %d MB/s\n",
388                        cfs_crypto_hash_name(hash_alg),
389                        cfs_crypto_hash_speeds[hash_alg]);
390         }
391 }
392
393 /**
394  * hash speed in Mbytes per second for valid hash algorithm
395  *
396  * Return the performance of the specified \a hash_alg that was
397  * computed using cfs_crypto_performance_test().  If the performance
398  * has not yet been computed, do that when it is first requested.
399  * That avoids computing the speed when it is not actually needed.
400  * To avoid competing threads computing the checksum speed at the
401  * same time, only compute a single checksum speed at one time.
402  *
403  * \param[in] hash_alg  hash algorithm id (CFS_HASH_ALG_*)
404  *
405  * \retval              positive speed of the hash function in MB/s
406  * \retval              -ENOENT if \a hash_alg is unsupported
407  * \retval              negative errno if \a hash_alg speed is unavailable
408  */
409 int cfs_crypto_hash_speed(enum cfs_crypto_hash_alg hash_alg)
410 {
411         if (hash_alg < CFS_HASH_ALG_MAX) {
412                 if (unlikely(cfs_crypto_hash_speeds[hash_alg] == 0)) {
413                         static DEFINE_MUTEX(crypto_hash_speed_mutex);
414
415                         mutex_lock(&crypto_hash_speed_mutex);
416                         if (cfs_crypto_hash_speeds[hash_alg] == 0)
417                                 cfs_crypto_performance_test(hash_alg);
418                         mutex_unlock(&crypto_hash_speed_mutex);
419                 }
420                 return cfs_crypto_hash_speeds[hash_alg];
421         }
422
423         return -ENOENT;
424 }
425 EXPORT_SYMBOL(cfs_crypto_hash_speed);
426
427 /**
428  * Run the performance test for all hash algorithms.
429  *
430  * Run the cfs_crypto_performance_test() benchmark for some of the available
431  * hash functions at module load time.  This can't be reliably done at runtime
432  * since the CPUs may be under load from thousands of connecting clients when
433  * the first client connects and the checksum speeds are needed.
434  *
435  * Since the setup cost and computation speed of various hash algorithms is
436  * a function of the buffer size (and possibly internal contention of offload
437  * engines), this speed only represents an estimate of the actual speed under
438  * actual usage, but is reasonable for comparing available algorithms.
439  *
440  * The actual speeds are available via cfs_crypto_hash_speed() for later
441  * comparison.
442  *
443  * \retval              0 on success
444  * \retval              -ENOMEM if no memory is available for test buffer
445  */
446 static int cfs_crypto_test_hashes(void)
447 {
448         enum cfs_crypto_hash_alg hash_alg;
449
450         for (hash_alg = 1; hash_alg < CFS_HASH_ALG_SPEED_MAX; hash_alg++)
451                 cfs_crypto_performance_test(hash_alg);
452
453         return 0;
454 }
455
456 static int adler32;
457
458 #ifdef HAVE_CRC32
459 static int crc32;
460 #endif
461 #ifdef HAVE_PCLMULQDQ
462 #ifdef NEED_CRC32_ACCEL
463 static int crc32_pclmul;
464 #endif
465 #ifdef NEED_CRC32C_ACCEL
466 static int crc32c_pclmul;
467 #endif
468 #endif /* HAVE_PCLMULQDQ */
469
470 /**
471  * Register available hash functions
472  *
473  * \retval              0
474  */
475 int cfs_crypto_register(void)
476 {
477         request_module("crc32c");
478
479         adler32 = cfs_crypto_adler32_register();
480
481 #ifdef HAVE_CRC32
482         crc32 = cfs_crypto_crc32_register();
483 #endif
484 #ifdef HAVE_PCLMULQDQ
485 #ifdef NEED_CRC32_ACCEL
486         crc32_pclmul = cfs_crypto_crc32_pclmul_register();
487 #endif
488 #ifdef NEED_CRC32C_ACCEL
489         crc32c_pclmul = cfs_crypto_crc32c_pclmul_register();
490 #endif
491 #endif /* HAVE_PCLMULQDQ */
492
493         /* check all algorithms and do performance test */
494         cfs_crypto_test_hashes();
495
496         return 0;
497 }
498
499 /**
500  * Unregister previously registered hash functions
501  */
502 void cfs_crypto_unregister(void)
503 {
504         if (adler32 == 0)
505                 cfs_crypto_adler32_unregister();
506
507 #ifdef HAVE_CRC32
508         if (crc32 == 0)
509                 cfs_crypto_crc32_unregister();
510 #endif
511 #ifdef HAVE_PCLMULQDQ
512 #ifdef NEED_CRC32_ACCEL
513         if (crc32_pclmul == 0)
514                 cfs_crypto_crc32_pclmul_unregister();
515 #endif
516 #ifdef NEED_CRC32C_ACCEL
517         if (crc32c_pclmul == 0)
518                 cfs_crypto_crc32c_pclmul_unregister();
519 #endif
520 #endif /* HAVE_PCLMULQDQ */
521 }