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