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