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