GNU Linux-libre 4.14.290-gnu1
[releases.git] / drivers / crypto / ux500 / hash / hash_core.c
1 /*
2  * Cryptographic API.
3  * Support for Nomadik hardware crypto engine.
4
5  * Copyright (C) ST-Ericsson SA 2010
6  * Author: Shujuan Chen <shujuan.chen@stericsson.com> for ST-Ericsson
7  * Author: Joakim Bech <joakim.xx.bech@stericsson.com> for ST-Ericsson
8  * Author: Berne Hebark <berne.herbark@stericsson.com> for ST-Ericsson.
9  * Author: Niklas Hernaeus <niklas.hernaeus@stericsson.com> for ST-Ericsson.
10  * Author: Andreas Westin <andreas.westin@stericsson.com> for ST-Ericsson.
11  * License terms: GNU General Public License (GPL) version 2
12  */
13
14 #define pr_fmt(fmt) "hashX hashX: " fmt
15
16 #include <linux/clk.h>
17 #include <linux/device.h>
18 #include <linux/err.h>
19 #include <linux/init.h>
20 #include <linux/io.h>
21 #include <linux/klist.h>
22 #include <linux/kernel.h>
23 #include <linux/module.h>
24 #include <linux/platform_device.h>
25 #include <linux/crypto.h>
26
27 #include <linux/regulator/consumer.h>
28 #include <linux/dmaengine.h>
29 #include <linux/bitops.h>
30
31 #include <crypto/internal/hash.h>
32 #include <crypto/sha.h>
33 #include <crypto/scatterwalk.h>
34 #include <crypto/algapi.h>
35
36 #include <linux/platform_data/crypto-ux500.h>
37
38 #include "hash_alg.h"
39
40 static int hash_mode;
41 module_param(hash_mode, int, 0);
42 MODULE_PARM_DESC(hash_mode, "CPU or DMA mode. CPU = 0 (default), DMA = 1");
43
44 /* HMAC-SHA1, no key */
45 static const u8 zero_message_hmac_sha1[SHA1_DIGEST_SIZE] = {
46         0xfb, 0xdb, 0x1d, 0x1b, 0x18, 0xaa, 0x6c, 0x08,
47         0x32, 0x4b, 0x7d, 0x64, 0xb7, 0x1f, 0xb7, 0x63,
48         0x70, 0x69, 0x0e, 0x1d
49 };
50
51 /* HMAC-SHA256, no key */
52 static const u8 zero_message_hmac_sha256[SHA256_DIGEST_SIZE] = {
53         0xb6, 0x13, 0x67, 0x9a, 0x08, 0x14, 0xd9, 0xec,
54         0x77, 0x2f, 0x95, 0xd7, 0x78, 0xc3, 0x5f, 0xc5,
55         0xff, 0x16, 0x97, 0xc4, 0x93, 0x71, 0x56, 0x53,
56         0xc6, 0xc7, 0x12, 0x14, 0x42, 0x92, 0xc5, 0xad
57 };
58
59 /**
60  * struct hash_driver_data - data specific to the driver.
61  *
62  * @device_list:        A list of registered devices to choose from.
63  * @device_allocation:  A semaphore initialized with number of devices.
64  */
65 struct hash_driver_data {
66         struct klist            device_list;
67         struct semaphore        device_allocation;
68 };
69
70 static struct hash_driver_data  driver_data;
71
72 /* Declaration of functions */
73 /**
74  * hash_messagepad - Pads a message and write the nblw bits.
75  * @device_data:        Structure for the hash device.
76  * @message:            Last word of a message
77  * @index_bytes:        The number of bytes in the last message
78  *
79  * This function manages the final part of the digest calculation, when less
80  * than 512 bits (64 bytes) remain in message. This means index_bytes < 64.
81  *
82  */
83 static void hash_messagepad(struct hash_device_data *device_data,
84                             const u32 *message, u8 index_bytes);
85
86 /**
87  * release_hash_device - Releases a previously allocated hash device.
88  * @device_data:        Structure for the hash device.
89  *
90  */
91 static void release_hash_device(struct hash_device_data *device_data)
92 {
93         spin_lock(&device_data->ctx_lock);
94         device_data->current_ctx->device = NULL;
95         device_data->current_ctx = NULL;
96         spin_unlock(&device_data->ctx_lock);
97
98         /*
99          * The down_interruptible part for this semaphore is called in
100          * cryp_get_device_data.
101          */
102         up(&driver_data.device_allocation);
103 }
104
105 static void hash_dma_setup_channel(struct hash_device_data *device_data,
106                                    struct device *dev)
107 {
108         struct hash_platform_data *platform_data = dev->platform_data;
109         struct dma_slave_config conf = {
110                 .direction = DMA_MEM_TO_DEV,
111                 .dst_addr = device_data->phybase + HASH_DMA_FIFO,
112                 .dst_addr_width = DMA_SLAVE_BUSWIDTH_2_BYTES,
113                 .dst_maxburst = 16,
114         };
115
116         dma_cap_zero(device_data->dma.mask);
117         dma_cap_set(DMA_SLAVE, device_data->dma.mask);
118
119         device_data->dma.cfg_mem2hash = platform_data->mem_to_engine;
120         device_data->dma.chan_mem2hash =
121                 dma_request_channel(device_data->dma.mask,
122                                     platform_data->dma_filter,
123                                     device_data->dma.cfg_mem2hash);
124
125         dmaengine_slave_config(device_data->dma.chan_mem2hash, &conf);
126
127         init_completion(&device_data->dma.complete);
128 }
129
130 static void hash_dma_callback(void *data)
131 {
132         struct hash_ctx *ctx = data;
133
134         complete(&ctx->device->dma.complete);
135 }
136
137 static int hash_set_dma_transfer(struct hash_ctx *ctx, struct scatterlist *sg,
138                                  int len, enum dma_data_direction direction)
139 {
140         struct dma_async_tx_descriptor *desc = NULL;
141         struct dma_chan *channel = NULL;
142         dma_cookie_t cookie;
143
144         if (direction != DMA_TO_DEVICE) {
145                 dev_err(ctx->device->dev, "%s: Invalid DMA direction\n",
146                         __func__);
147                 return -EFAULT;
148         }
149
150         sg->length = ALIGN(sg->length, HASH_DMA_ALIGN_SIZE);
151
152         channel = ctx->device->dma.chan_mem2hash;
153         ctx->device->dma.sg = sg;
154         ctx->device->dma.sg_len = dma_map_sg(channel->device->dev,
155                         ctx->device->dma.sg, ctx->device->dma.nents,
156                         direction);
157
158         if (!ctx->device->dma.sg_len) {
159                 dev_err(ctx->device->dev, "%s: Could not map the sg list (TO_DEVICE)\n",
160                         __func__);
161                 return -EFAULT;
162         }
163
164         dev_dbg(ctx->device->dev, "%s: Setting up DMA for buffer (TO_DEVICE)\n",
165                 __func__);
166         desc = dmaengine_prep_slave_sg(channel,
167                         ctx->device->dma.sg, ctx->device->dma.sg_len,
168                         DMA_MEM_TO_DEV, DMA_CTRL_ACK | DMA_PREP_INTERRUPT);
169         if (!desc) {
170                 dev_err(ctx->device->dev,
171                         "%s: dmaengine_prep_slave_sg() failed!\n", __func__);
172                 return -EFAULT;
173         }
174
175         desc->callback = hash_dma_callback;
176         desc->callback_param = ctx;
177
178         cookie = dmaengine_submit(desc);
179         dma_async_issue_pending(channel);
180
181         return 0;
182 }
183
184 static void hash_dma_done(struct hash_ctx *ctx)
185 {
186         struct dma_chan *chan;
187
188         chan = ctx->device->dma.chan_mem2hash;
189         dmaengine_terminate_all(chan);
190         dma_unmap_sg(chan->device->dev, ctx->device->dma.sg,
191                      ctx->device->dma.sg_len, DMA_TO_DEVICE);
192 }
193
194 static int hash_dma_write(struct hash_ctx *ctx,
195                           struct scatterlist *sg, int len)
196 {
197         int error = hash_set_dma_transfer(ctx, sg, len, DMA_TO_DEVICE);
198         if (error) {
199                 dev_dbg(ctx->device->dev,
200                         "%s: hash_set_dma_transfer() failed\n", __func__);
201                 return error;
202         }
203
204         return len;
205 }
206
207 /**
208  * get_empty_message_digest - Returns a pre-calculated digest for
209  * the empty message.
210  * @device_data:        Structure for the hash device.
211  * @zero_hash:          Buffer to return the empty message digest.
212  * @zero_hash_size:     Hash size of the empty message digest.
213  * @zero_digest:        True if zero_digest returned.
214  */
215 static int get_empty_message_digest(
216                 struct hash_device_data *device_data,
217                 u8 *zero_hash, u32 *zero_hash_size, bool *zero_digest)
218 {
219         int ret = 0;
220         struct hash_ctx *ctx = device_data->current_ctx;
221         *zero_digest = false;
222
223         /**
224          * Caller responsible for ctx != NULL.
225          */
226
227         if (HASH_OPER_MODE_HASH == ctx->config.oper_mode) {
228                 if (HASH_ALGO_SHA1 == ctx->config.algorithm) {
229                         memcpy(zero_hash, &sha1_zero_message_hash[0],
230                                SHA1_DIGEST_SIZE);
231                         *zero_hash_size = SHA1_DIGEST_SIZE;
232                         *zero_digest = true;
233                 } else if (HASH_ALGO_SHA256 ==
234                                 ctx->config.algorithm) {
235                         memcpy(zero_hash, &sha256_zero_message_hash[0],
236                                SHA256_DIGEST_SIZE);
237                         *zero_hash_size = SHA256_DIGEST_SIZE;
238                         *zero_digest = true;
239                 } else {
240                         dev_err(device_data->dev, "%s: Incorrect algorithm!\n",
241                                 __func__);
242                         ret = -EINVAL;
243                         goto out;
244                 }
245         } else if (HASH_OPER_MODE_HMAC == ctx->config.oper_mode) {
246                 if (!ctx->keylen) {
247                         if (HASH_ALGO_SHA1 == ctx->config.algorithm) {
248                                 memcpy(zero_hash, &zero_message_hmac_sha1[0],
249                                        SHA1_DIGEST_SIZE);
250                                 *zero_hash_size = SHA1_DIGEST_SIZE;
251                                 *zero_digest = true;
252                         } else if (HASH_ALGO_SHA256 == ctx->config.algorithm) {
253                                 memcpy(zero_hash, &zero_message_hmac_sha256[0],
254                                        SHA256_DIGEST_SIZE);
255                                 *zero_hash_size = SHA256_DIGEST_SIZE;
256                                 *zero_digest = true;
257                         } else {
258                                 dev_err(device_data->dev, "%s: Incorrect algorithm!\n",
259                                         __func__);
260                                 ret = -EINVAL;
261                                 goto out;
262                         }
263                 } else {
264                         dev_dbg(device_data->dev,
265                                 "%s: Continue hash calculation, since hmac key available\n",
266                                 __func__);
267                 }
268         }
269 out:
270
271         return ret;
272 }
273
274 /**
275  * hash_disable_power - Request to disable power and clock.
276  * @device_data:        Structure for the hash device.
277  * @save_device_state:  If true, saves the current hw state.
278  *
279  * This function request for disabling power (regulator) and clock,
280  * and could also save current hw state.
281  */
282 static int hash_disable_power(struct hash_device_data *device_data,
283                               bool save_device_state)
284 {
285         int ret = 0;
286         struct device *dev = device_data->dev;
287
288         spin_lock(&device_data->power_state_lock);
289         if (!device_data->power_state)
290                 goto out;
291
292         if (save_device_state) {
293                 hash_save_state(device_data,
294                                 &device_data->state);
295                 device_data->restore_dev_state = true;
296         }
297
298         clk_disable(device_data->clk);
299         ret = regulator_disable(device_data->regulator);
300         if (ret)
301                 dev_err(dev, "%s: regulator_disable() failed!\n", __func__);
302
303         device_data->power_state = false;
304
305 out:
306         spin_unlock(&device_data->power_state_lock);
307
308         return ret;
309 }
310
311 /**
312  * hash_enable_power - Request to enable power and clock.
313  * @device_data:                Structure for the hash device.
314  * @restore_device_state:       If true, restores a previous saved hw state.
315  *
316  * This function request for enabling power (regulator) and clock,
317  * and could also restore a previously saved hw state.
318  */
319 static int hash_enable_power(struct hash_device_data *device_data,
320                              bool restore_device_state)
321 {
322         int ret = 0;
323         struct device *dev = device_data->dev;
324
325         spin_lock(&device_data->power_state_lock);
326         if (!device_data->power_state) {
327                 ret = regulator_enable(device_data->regulator);
328                 if (ret) {
329                         dev_err(dev, "%s: regulator_enable() failed!\n",
330                                 __func__);
331                         goto out;
332                 }
333                 ret = clk_enable(device_data->clk);
334                 if (ret) {
335                         dev_err(dev, "%s: clk_enable() failed!\n", __func__);
336                         ret = regulator_disable(
337                                         device_data->regulator);
338                         goto out;
339                 }
340                 device_data->power_state = true;
341         }
342
343         if (device_data->restore_dev_state) {
344                 if (restore_device_state) {
345                         device_data->restore_dev_state = false;
346                         hash_resume_state(device_data, &device_data->state);
347                 }
348         }
349 out:
350         spin_unlock(&device_data->power_state_lock);
351
352         return ret;
353 }
354
355 /**
356  * hash_get_device_data - Checks for an available hash device and return it.
357  * @hash_ctx:           Structure for the hash context.
358  * @device_data:        Structure for the hash device.
359  *
360  * This function check for an available hash device and return it to
361  * the caller.
362  * Note! Caller need to release the device, calling up().
363  */
364 static int hash_get_device_data(struct hash_ctx *ctx,
365                                 struct hash_device_data **device_data)
366 {
367         int                     ret;
368         struct klist_iter       device_iterator;
369         struct klist_node       *device_node;
370         struct hash_device_data *local_device_data = NULL;
371
372         /* Wait until a device is available */
373         ret = down_interruptible(&driver_data.device_allocation);
374         if (ret)
375                 return ret;  /* Interrupted */
376
377         /* Select a device */
378         klist_iter_init(&driver_data.device_list, &device_iterator);
379         device_node = klist_next(&device_iterator);
380         while (device_node) {
381                 local_device_data = container_of(device_node,
382                                            struct hash_device_data, list_node);
383                 spin_lock(&local_device_data->ctx_lock);
384                 /* current_ctx allocates a device, NULL = unallocated */
385                 if (local_device_data->current_ctx) {
386                         device_node = klist_next(&device_iterator);
387                 } else {
388                         local_device_data->current_ctx = ctx;
389                         ctx->device = local_device_data;
390                         spin_unlock(&local_device_data->ctx_lock);
391                         break;
392                 }
393                 spin_unlock(&local_device_data->ctx_lock);
394         }
395         klist_iter_exit(&device_iterator);
396
397         if (!device_node) {
398                 /**
399                  * No free device found.
400                  * Since we allocated a device with down_interruptible, this
401                  * should not be able to happen.
402                  * Number of available devices, which are contained in
403                  * device_allocation, is therefore decremented by not doing
404                  * an up(device_allocation).
405                  */
406                 return -EBUSY;
407         }
408
409         *device_data = local_device_data;
410
411         return 0;
412 }
413
414 /**
415  * hash_hw_write_key - Writes the key to the hardware registries.
416  *
417  * @device_data:        Structure for the hash device.
418  * @key:                Key to be written.
419  * @keylen:             The lengt of the key.
420  *
421  * Note! This function DOES NOT write to the NBLW registry, even though
422  * specified in the the hw design spec. Either due to incorrect info in the
423  * spec or due to a bug in the hw.
424  */
425 static void hash_hw_write_key(struct hash_device_data *device_data,
426                               const u8 *key, unsigned int keylen)
427 {
428         u32 word = 0;
429         int nwords = 1;
430
431         HASH_CLEAR_BITS(&device_data->base->str, HASH_STR_NBLW_MASK);
432
433         while (keylen >= 4) {
434                 u32 *key_word = (u32 *)key;
435
436                 HASH_SET_DIN(key_word, nwords);
437                 keylen -= 4;
438                 key += 4;
439         }
440
441         /* Take care of the remaining bytes in the last word */
442         if (keylen) {
443                 word = 0;
444                 while (keylen) {
445                         word |= (key[keylen - 1] << (8 * (keylen - 1)));
446                         keylen--;
447                 }
448
449                 HASH_SET_DIN(&word, nwords);
450         }
451
452         while (readl(&device_data->base->str) & HASH_STR_DCAL_MASK)
453                 cpu_relax();
454
455         HASH_SET_DCAL;
456
457         while (readl(&device_data->base->str) & HASH_STR_DCAL_MASK)
458                 cpu_relax();
459 }
460
461 /**
462  * init_hash_hw - Initialise the hash hardware for a new calculation.
463  * @device_data:        Structure for the hash device.
464  * @ctx:                The hash context.
465  *
466  * This function will enable the bits needed to clear and start a new
467  * calculation.
468  */
469 static int init_hash_hw(struct hash_device_data *device_data,
470                         struct hash_ctx *ctx)
471 {
472         int ret = 0;
473
474         ret = hash_setconfiguration(device_data, &ctx->config);
475         if (ret) {
476                 dev_err(device_data->dev, "%s: hash_setconfiguration() failed!\n",
477                         __func__);
478                 return ret;
479         }
480
481         hash_begin(device_data, ctx);
482
483         if (ctx->config.oper_mode == HASH_OPER_MODE_HMAC)
484                 hash_hw_write_key(device_data, ctx->key, ctx->keylen);
485
486         return ret;
487 }
488
489 /**
490  * hash_get_nents - Return number of entries (nents) in scatterlist (sg).
491  *
492  * @sg:         Scatterlist.
493  * @size:       Size in bytes.
494  * @aligned:    True if sg data aligned to work in DMA mode.
495  *
496  */
497 static int hash_get_nents(struct scatterlist *sg, int size, bool *aligned)
498 {
499         int nents = 0;
500         bool aligned_data = true;
501
502         while (size > 0 && sg) {
503                 nents++;
504                 size -= sg->length;
505
506                 /* hash_set_dma_transfer will align last nent */
507                 if ((aligned && !IS_ALIGNED(sg->offset, HASH_DMA_ALIGN_SIZE)) ||
508                     (!IS_ALIGNED(sg->length, HASH_DMA_ALIGN_SIZE) && size > 0))
509                         aligned_data = false;
510
511                 sg = sg_next(sg);
512         }
513
514         if (aligned)
515                 *aligned = aligned_data;
516
517         if (size != 0)
518                 return -EFAULT;
519
520         return nents;
521 }
522
523 /**
524  * hash_dma_valid_data - checks for dma valid sg data.
525  * @sg:         Scatterlist.
526  * @datasize:   Datasize in bytes.
527  *
528  * NOTE! This function checks for dma valid sg data, since dma
529  * only accept datasizes of even wordsize.
530  */
531 static bool hash_dma_valid_data(struct scatterlist *sg, int datasize)
532 {
533         bool aligned;
534
535         /* Need to include at least one nent, else error */
536         if (hash_get_nents(sg, datasize, &aligned) < 1)
537                 return false;
538
539         return aligned;
540 }
541
542 /**
543  * hash_init - Common hash init function for SHA1/SHA2 (SHA256).
544  * @req: The hash request for the job.
545  *
546  * Initialize structures.
547  */
548 static int hash_init(struct ahash_request *req)
549 {
550         struct crypto_ahash *tfm = crypto_ahash_reqtfm(req);
551         struct hash_ctx *ctx = crypto_ahash_ctx(tfm);
552         struct hash_req_ctx *req_ctx = ahash_request_ctx(req);
553
554         if (!ctx->key)
555                 ctx->keylen = 0;
556
557         memset(&req_ctx->state, 0, sizeof(struct hash_state));
558         req_ctx->updated = 0;
559         if (hash_mode == HASH_MODE_DMA) {
560                 if (req->nbytes < HASH_DMA_ALIGN_SIZE) {
561                         req_ctx->dma_mode = false; /* Don't use DMA */
562
563                         pr_debug("%s: DMA mode, but direct to CPU mode for data size < %d\n",
564                                  __func__, HASH_DMA_ALIGN_SIZE);
565                 } else {
566                         if (req->nbytes >= HASH_DMA_PERFORMANCE_MIN_SIZE &&
567                             hash_dma_valid_data(req->src, req->nbytes)) {
568                                 req_ctx->dma_mode = true;
569                         } else {
570                                 req_ctx->dma_mode = false;
571                                 pr_debug("%s: DMA mode, but use CPU mode for datalength < %d or non-aligned data, except in last nent\n",
572                                          __func__,
573                                          HASH_DMA_PERFORMANCE_MIN_SIZE);
574                         }
575                 }
576         }
577         return 0;
578 }
579
580 /**
581  * hash_processblock - This function processes a single block of 512 bits (64
582  *                     bytes), word aligned, starting at message.
583  * @device_data:        Structure for the hash device.
584  * @message:            Block (512 bits) of message to be written to
585  *                      the HASH hardware.
586  *
587  */
588 static void hash_processblock(struct hash_device_data *device_data,
589                               const u32 *message, int length)
590 {
591         int len = length / HASH_BYTES_PER_WORD;
592         /*
593          * NBLW bits. Reset the number of bits in last word (NBLW).
594          */
595         HASH_CLEAR_BITS(&device_data->base->str, HASH_STR_NBLW_MASK);
596
597         /*
598          * Write message data to the HASH_DIN register.
599          */
600         HASH_SET_DIN(message, len);
601 }
602
603 /**
604  * hash_messagepad - Pads a message and write the nblw bits.
605  * @device_data:        Structure for the hash device.
606  * @message:            Last word of a message.
607  * @index_bytes:        The number of bytes in the last message.
608  *
609  * This function manages the final part of the digest calculation, when less
610  * than 512 bits (64 bytes) remain in message. This means index_bytes < 64.
611  *
612  */
613 static void hash_messagepad(struct hash_device_data *device_data,
614                             const u32 *message, u8 index_bytes)
615 {
616         int nwords = 1;
617
618         /*
619          * Clear hash str register, only clear NBLW
620          * since DCAL will be reset by hardware.
621          */
622         HASH_CLEAR_BITS(&device_data->base->str, HASH_STR_NBLW_MASK);
623
624         /* Main loop */
625         while (index_bytes >= 4) {
626                 HASH_SET_DIN(message, nwords);
627                 index_bytes -= 4;
628                 message++;
629         }
630
631         if (index_bytes)
632                 HASH_SET_DIN(message, nwords);
633
634         while (readl(&device_data->base->str) & HASH_STR_DCAL_MASK)
635                 cpu_relax();
636
637         /* num_of_bytes == 0 => NBLW <- 0 (32 bits valid in DATAIN) */
638         HASH_SET_NBLW(index_bytes * 8);
639         dev_dbg(device_data->dev, "%s: DIN=0x%08x NBLW=%lu\n",
640                 __func__, readl_relaxed(&device_data->base->din),
641                 readl_relaxed(&device_data->base->str) & HASH_STR_NBLW_MASK);
642         HASH_SET_DCAL;
643         dev_dbg(device_data->dev, "%s: after dcal -> DIN=0x%08x NBLW=%lu\n",
644                 __func__, readl_relaxed(&device_data->base->din),
645                 readl_relaxed(&device_data->base->str) & HASH_STR_NBLW_MASK);
646
647         while (readl(&device_data->base->str) & HASH_STR_DCAL_MASK)
648                 cpu_relax();
649 }
650
651 /**
652  * hash_incrementlength - Increments the length of the current message.
653  * @ctx: Hash context
654  * @incr: Length of message processed already
655  *
656  * Overflow cannot occur, because conditions for overflow are checked in
657  * hash_hw_update.
658  */
659 static void hash_incrementlength(struct hash_req_ctx *ctx, u32 incr)
660 {
661         ctx->state.length.low_word += incr;
662
663         /* Check for wrap-around */
664         if (ctx->state.length.low_word < incr)
665                 ctx->state.length.high_word++;
666 }
667
668 /**
669  * hash_setconfiguration - Sets the required configuration for the hash
670  *                         hardware.
671  * @device_data:        Structure for the hash device.
672  * @config:             Pointer to a configuration structure.
673  */
674 int hash_setconfiguration(struct hash_device_data *device_data,
675                           struct hash_config *config)
676 {
677         int ret = 0;
678
679         if (config->algorithm != HASH_ALGO_SHA1 &&
680             config->algorithm != HASH_ALGO_SHA256)
681                 return -EPERM;
682
683         /*
684          * DATAFORM bits. Set the DATAFORM bits to 0b11, which means the data
685          * to be written to HASH_DIN is considered as 32 bits.
686          */
687         HASH_SET_DATA_FORMAT(config->data_format);
688
689         /*
690          * ALGO bit. Set to 0b1 for SHA-1 and 0b0 for SHA-256
691          */
692         switch (config->algorithm) {
693         case HASH_ALGO_SHA1:
694                 HASH_SET_BITS(&device_data->base->cr, HASH_CR_ALGO_MASK);
695                 break;
696
697         case HASH_ALGO_SHA256:
698                 HASH_CLEAR_BITS(&device_data->base->cr, HASH_CR_ALGO_MASK);
699                 break;
700
701         default:
702                 dev_err(device_data->dev, "%s: Incorrect algorithm\n",
703                         __func__);
704                 return -EPERM;
705         }
706
707         /*
708          * MODE bit. This bit selects between HASH or HMAC mode for the
709          * selected algorithm. 0b0 = HASH and 0b1 = HMAC.
710          */
711         if (HASH_OPER_MODE_HASH == config->oper_mode)
712                 HASH_CLEAR_BITS(&device_data->base->cr,
713                                 HASH_CR_MODE_MASK);
714         else if (HASH_OPER_MODE_HMAC == config->oper_mode) {
715                 HASH_SET_BITS(&device_data->base->cr, HASH_CR_MODE_MASK);
716                 if (device_data->current_ctx->keylen > HASH_BLOCK_SIZE) {
717                         /* Truncate key to blocksize */
718                         dev_dbg(device_data->dev, "%s: LKEY set\n", __func__);
719                         HASH_SET_BITS(&device_data->base->cr,
720                                       HASH_CR_LKEY_MASK);
721                 } else {
722                         dev_dbg(device_data->dev, "%s: LKEY cleared\n",
723                                 __func__);
724                         HASH_CLEAR_BITS(&device_data->base->cr,
725                                         HASH_CR_LKEY_MASK);
726                 }
727         } else {        /* Wrong hash mode */
728                 ret = -EPERM;
729                 dev_err(device_data->dev, "%s: HASH_INVALID_PARAMETER!\n",
730                         __func__);
731         }
732         return ret;
733 }
734
735 /**
736  * hash_begin - This routine resets some globals and initializes the hash
737  *              hardware.
738  * @device_data:        Structure for the hash device.
739  * @ctx:                Hash context.
740  */
741 void hash_begin(struct hash_device_data *device_data, struct hash_ctx *ctx)
742 {
743         /* HW and SW initializations */
744         /* Note: there is no need to initialize buffer and digest members */
745
746         while (readl(&device_data->base->str) & HASH_STR_DCAL_MASK)
747                 cpu_relax();
748
749         /*
750          * INIT bit. Set this bit to 0b1 to reset the HASH processor core and
751          * prepare the initialize the HASH accelerator to compute the message
752          * digest of a new message.
753          */
754         HASH_INITIALIZE;
755
756         /*
757          * NBLW bits. Reset the number of bits in last word (NBLW).
758          */
759         HASH_CLEAR_BITS(&device_data->base->str, HASH_STR_NBLW_MASK);
760 }
761
762 static int hash_process_data(struct hash_device_data *device_data,
763                              struct hash_ctx *ctx, struct hash_req_ctx *req_ctx,
764                              int msg_length, u8 *data_buffer, u8 *buffer,
765                              u8 *index)
766 {
767         int ret = 0;
768         u32 count;
769
770         do {
771                 if ((*index + msg_length) < HASH_BLOCK_SIZE) {
772                         for (count = 0; count < msg_length; count++) {
773                                 buffer[*index + count] =
774                                         *(data_buffer + count);
775                         }
776                         *index += msg_length;
777                         msg_length = 0;
778                 } else {
779                         if (req_ctx->updated) {
780                                 ret = hash_resume_state(device_data,
781                                                 &device_data->state);
782                                 memmove(req_ctx->state.buffer,
783                                         device_data->state.buffer,
784                                         HASH_BLOCK_SIZE);
785                                 if (ret) {
786                                         dev_err(device_data->dev,
787                                                 "%s: hash_resume_state() failed!\n",
788                                                 __func__);
789                                         goto out;
790                                 }
791                         } else {
792                                 ret = init_hash_hw(device_data, ctx);
793                                 if (ret) {
794                                         dev_err(device_data->dev,
795                                                 "%s: init_hash_hw() failed!\n",
796                                                 __func__);
797                                         goto out;
798                                 }
799                                 req_ctx->updated = 1;
800                         }
801                         /*
802                          * If 'data_buffer' is four byte aligned and
803                          * local buffer does not have any data, we can
804                          * write data directly from 'data_buffer' to
805                          * HW peripheral, otherwise we first copy data
806                          * to a local buffer
807                          */
808                         if ((0 == (((u32)data_buffer) % 4)) &&
809                             (0 == *index))
810                                 hash_processblock(device_data,
811                                                   (const u32 *)data_buffer,
812                                                   HASH_BLOCK_SIZE);
813                         else {
814                                 for (count = 0;
815                                      count < (u32)(HASH_BLOCK_SIZE - *index);
816                                      count++) {
817                                         buffer[*index + count] =
818                                                 *(data_buffer + count);
819                                 }
820                                 hash_processblock(device_data,
821                                                   (const u32 *)buffer,
822                                                   HASH_BLOCK_SIZE);
823                         }
824                         hash_incrementlength(req_ctx, HASH_BLOCK_SIZE);
825                         data_buffer += (HASH_BLOCK_SIZE - *index);
826
827                         msg_length -= (HASH_BLOCK_SIZE - *index);
828                         *index = 0;
829
830                         ret = hash_save_state(device_data,
831                                         &device_data->state);
832
833                         memmove(device_data->state.buffer,
834                                 req_ctx->state.buffer,
835                                 HASH_BLOCK_SIZE);
836                         if (ret) {
837                                 dev_err(device_data->dev, "%s: hash_save_state() failed!\n",
838                                         __func__);
839                                 goto out;
840                         }
841                 }
842         } while (msg_length != 0);
843 out:
844
845         return ret;
846 }
847
848 /**
849  * hash_dma_final - The hash dma final function for SHA1/SHA256.
850  * @req:        The hash request for the job.
851  */
852 static int hash_dma_final(struct ahash_request *req)
853 {
854         int ret = 0;
855         struct crypto_ahash *tfm = crypto_ahash_reqtfm(req);
856         struct hash_ctx *ctx = crypto_ahash_ctx(tfm);
857         struct hash_req_ctx *req_ctx = ahash_request_ctx(req);
858         struct hash_device_data *device_data;
859         u8 digest[SHA256_DIGEST_SIZE];
860         int bytes_written = 0;
861
862         ret = hash_get_device_data(ctx, &device_data);
863         if (ret)
864                 return ret;
865
866         dev_dbg(device_data->dev, "%s: (ctx=0x%x)!\n", __func__, (u32) ctx);
867
868         if (req_ctx->updated) {
869                 ret = hash_resume_state(device_data, &device_data->state);
870
871                 if (ret) {
872                         dev_err(device_data->dev, "%s: hash_resume_state() failed!\n",
873                                 __func__);
874                         goto out;
875                 }
876         }
877
878         if (!req_ctx->updated) {
879                 ret = hash_setconfiguration(device_data, &ctx->config);
880                 if (ret) {
881                         dev_err(device_data->dev,
882                                 "%s: hash_setconfiguration() failed!\n",
883                                 __func__);
884                         goto out;
885                 }
886
887                 /* Enable DMA input */
888                 if (hash_mode != HASH_MODE_DMA || !req_ctx->dma_mode) {
889                         HASH_CLEAR_BITS(&device_data->base->cr,
890                                         HASH_CR_DMAE_MASK);
891                 } else {
892                         HASH_SET_BITS(&device_data->base->cr,
893                                       HASH_CR_DMAE_MASK);
894                         HASH_SET_BITS(&device_data->base->cr,
895                                       HASH_CR_PRIVN_MASK);
896                 }
897
898                 HASH_INITIALIZE;
899
900                 if (ctx->config.oper_mode == HASH_OPER_MODE_HMAC)
901                         hash_hw_write_key(device_data, ctx->key, ctx->keylen);
902
903                 /* Number of bits in last word = (nbytes * 8) % 32 */
904                 HASH_SET_NBLW((req->nbytes * 8) % 32);
905                 req_ctx->updated = 1;
906         }
907
908         /* Store the nents in the dma struct. */
909         ctx->device->dma.nents = hash_get_nents(req->src, req->nbytes, NULL);
910         if (!ctx->device->dma.nents) {
911                 dev_err(device_data->dev, "%s: ctx->device->dma.nents = 0\n",
912                         __func__);
913                 ret = ctx->device->dma.nents;
914                 goto out;
915         }
916
917         bytes_written = hash_dma_write(ctx, req->src, req->nbytes);
918         if (bytes_written != req->nbytes) {
919                 dev_err(device_data->dev, "%s: hash_dma_write() failed!\n",
920                         __func__);
921                 ret = bytes_written;
922                 goto out;
923         }
924
925         wait_for_completion(&ctx->device->dma.complete);
926         hash_dma_done(ctx);
927
928         while (readl(&device_data->base->str) & HASH_STR_DCAL_MASK)
929                 cpu_relax();
930
931         if (ctx->config.oper_mode == HASH_OPER_MODE_HMAC && ctx->key) {
932                 unsigned int keylen = ctx->keylen;
933                 u8 *key = ctx->key;
934
935                 dev_dbg(device_data->dev, "%s: keylen: %d\n",
936                         __func__, ctx->keylen);
937                 hash_hw_write_key(device_data, key, keylen);
938         }
939
940         hash_get_digest(device_data, digest, ctx->config.algorithm);
941         memcpy(req->result, digest, ctx->digestsize);
942
943 out:
944         release_hash_device(device_data);
945
946         /**
947          * Allocated in setkey, and only used in HMAC.
948          */
949         kfree(ctx->key);
950
951         return ret;
952 }
953
954 /**
955  * hash_hw_final - The final hash calculation function
956  * @req:        The hash request for the job.
957  */
958 static int hash_hw_final(struct ahash_request *req)
959 {
960         int ret = 0;
961         struct crypto_ahash *tfm = crypto_ahash_reqtfm(req);
962         struct hash_ctx *ctx = crypto_ahash_ctx(tfm);
963         struct hash_req_ctx *req_ctx = ahash_request_ctx(req);
964         struct hash_device_data *device_data;
965         u8 digest[SHA256_DIGEST_SIZE];
966
967         ret = hash_get_device_data(ctx, &device_data);
968         if (ret)
969                 return ret;
970
971         dev_dbg(device_data->dev, "%s: (ctx=0x%x)!\n", __func__, (u32) ctx);
972
973         if (req_ctx->updated) {
974                 ret = hash_resume_state(device_data, &device_data->state);
975
976                 if (ret) {
977                         dev_err(device_data->dev,
978                                 "%s: hash_resume_state() failed!\n", __func__);
979                         goto out;
980                 }
981         } else if (req->nbytes == 0 && ctx->keylen == 0) {
982                 u8 zero_hash[SHA256_DIGEST_SIZE];
983                 u32 zero_hash_size = 0;
984                 bool zero_digest = false;
985                 /**
986                  * Use a pre-calculated empty message digest
987                  * (workaround since hw return zeroes, hw bug!?)
988                  */
989                 ret = get_empty_message_digest(device_data, &zero_hash[0],
990                                 &zero_hash_size, &zero_digest);
991                 if (!ret && likely(zero_hash_size == ctx->digestsize) &&
992                     zero_digest) {
993                         memcpy(req->result, &zero_hash[0], ctx->digestsize);
994                         goto out;
995                 } else if (!ret && !zero_digest) {
996                         dev_dbg(device_data->dev,
997                                 "%s: HMAC zero msg with key, continue...\n",
998                                 __func__);
999                 } else {
1000                         dev_err(device_data->dev,
1001                                 "%s: ret=%d, or wrong digest size? %s\n",
1002                                 __func__, ret,
1003                                 zero_hash_size == ctx->digestsize ?
1004                                 "true" : "false");
1005                         /* Return error */
1006                         goto out;
1007                 }
1008         } else if (req->nbytes == 0 && ctx->keylen > 0) {
1009                 ret = -EPERM;
1010                 dev_err(device_data->dev, "%s: Empty message with keylength > 0, NOT supported\n",
1011                         __func__);
1012                 goto out;
1013         }
1014
1015         if (!req_ctx->updated) {
1016                 ret = init_hash_hw(device_data, ctx);
1017                 if (ret) {
1018                         dev_err(device_data->dev,
1019                                 "%s: init_hash_hw() failed!\n", __func__);
1020                         goto out;
1021                 }
1022         }
1023
1024         if (req_ctx->state.index) {
1025                 hash_messagepad(device_data, req_ctx->state.buffer,
1026                                 req_ctx->state.index);
1027         } else {
1028                 HASH_SET_DCAL;
1029                 while (readl(&device_data->base->str) & HASH_STR_DCAL_MASK)
1030                         cpu_relax();
1031         }
1032
1033         if (ctx->config.oper_mode == HASH_OPER_MODE_HMAC && ctx->key) {
1034                 unsigned int keylen = ctx->keylen;
1035                 u8 *key = ctx->key;
1036
1037                 dev_dbg(device_data->dev, "%s: keylen: %d\n",
1038                         __func__, ctx->keylen);
1039                 hash_hw_write_key(device_data, key, keylen);
1040         }
1041
1042         hash_get_digest(device_data, digest, ctx->config.algorithm);
1043         memcpy(req->result, digest, ctx->digestsize);
1044
1045 out:
1046         release_hash_device(device_data);
1047
1048         /**
1049          * Allocated in setkey, and only used in HMAC.
1050          */
1051         kfree(ctx->key);
1052
1053         return ret;
1054 }
1055
1056 /**
1057  * hash_hw_update - Updates current HASH computation hashing another part of
1058  *                  the message.
1059  * @req:        Byte array containing the message to be hashed (caller
1060  *              allocated).
1061  */
1062 int hash_hw_update(struct ahash_request *req)
1063 {
1064         int ret = 0;
1065         u8 index = 0;
1066         u8 *buffer;
1067         struct hash_device_data *device_data;
1068         u8 *data_buffer;
1069         struct crypto_ahash *tfm = crypto_ahash_reqtfm(req);
1070         struct hash_ctx *ctx = crypto_ahash_ctx(tfm);
1071         struct hash_req_ctx *req_ctx = ahash_request_ctx(req);
1072         struct crypto_hash_walk walk;
1073         int msg_length = crypto_hash_walk_first(req, &walk);
1074
1075         /* Empty message ("") is correct indata */
1076         if (msg_length == 0)
1077                 return ret;
1078
1079         index = req_ctx->state.index;
1080         buffer = (u8 *)req_ctx->state.buffer;
1081
1082         /* Check if ctx->state.length + msg_length
1083            overflows */
1084         if (msg_length > (req_ctx->state.length.low_word + msg_length) &&
1085             HASH_HIGH_WORD_MAX_VAL == req_ctx->state.length.high_word) {
1086                 pr_err("%s: HASH_MSG_LENGTH_OVERFLOW!\n", __func__);
1087                 return -EPERM;
1088         }
1089
1090         ret = hash_get_device_data(ctx, &device_data);
1091         if (ret)
1092                 return ret;
1093
1094         /* Main loop */
1095         while (0 != msg_length) {
1096                 data_buffer = walk.data;
1097                 ret = hash_process_data(device_data, ctx, req_ctx, msg_length,
1098                                 data_buffer, buffer, &index);
1099
1100                 if (ret) {
1101                         dev_err(device_data->dev, "%s: hash_internal_hw_update() failed!\n",
1102                                 __func__);
1103                         goto out;
1104                 }
1105
1106                 msg_length = crypto_hash_walk_done(&walk, 0);
1107         }
1108
1109         req_ctx->state.index = index;
1110         dev_dbg(device_data->dev, "%s: indata length=%d, bin=%d\n",
1111                 __func__, req_ctx->state.index, req_ctx->state.bit_index);
1112
1113 out:
1114         release_hash_device(device_data);
1115
1116         return ret;
1117 }
1118
1119 /**
1120  * hash_resume_state - Function that resumes the state of an calculation.
1121  * @device_data:        Pointer to the device structure.
1122  * @device_state:       The state to be restored in the hash hardware
1123  */
1124 int hash_resume_state(struct hash_device_data *device_data,
1125                       const struct hash_state *device_state)
1126 {
1127         u32 temp_cr;
1128         s32 count;
1129         int hash_mode = HASH_OPER_MODE_HASH;
1130
1131         if (NULL == device_state) {
1132                 dev_err(device_data->dev, "%s: HASH_INVALID_PARAMETER!\n",
1133                         __func__);
1134                 return -EPERM;
1135         }
1136
1137         /* Check correctness of index and length members */
1138         if (device_state->index > HASH_BLOCK_SIZE ||
1139             (device_state->length.low_word % HASH_BLOCK_SIZE) != 0) {
1140                 dev_err(device_data->dev, "%s: HASH_INVALID_PARAMETER!\n",
1141                         __func__);
1142                 return -EPERM;
1143         }
1144
1145         /*
1146          * INIT bit. Set this bit to 0b1 to reset the HASH processor core and
1147          * prepare the initialize the HASH accelerator to compute the message
1148          * digest of a new message.
1149          */
1150         HASH_INITIALIZE;
1151
1152         temp_cr = device_state->temp_cr;
1153         writel_relaxed(temp_cr & HASH_CR_RESUME_MASK, &device_data->base->cr);
1154
1155         if (readl(&device_data->base->cr) & HASH_CR_MODE_MASK)
1156                 hash_mode = HASH_OPER_MODE_HMAC;
1157         else
1158                 hash_mode = HASH_OPER_MODE_HASH;
1159
1160         for (count = 0; count < HASH_CSR_COUNT; count++) {
1161                 if ((count >= 36) && (hash_mode == HASH_OPER_MODE_HASH))
1162                         break;
1163
1164                 writel_relaxed(device_state->csr[count],
1165                                &device_data->base->csrx[count]);
1166         }
1167
1168         writel_relaxed(device_state->csfull, &device_data->base->csfull);
1169         writel_relaxed(device_state->csdatain, &device_data->base->csdatain);
1170
1171         writel_relaxed(device_state->str_reg, &device_data->base->str);
1172         writel_relaxed(temp_cr, &device_data->base->cr);
1173
1174         return 0;
1175 }
1176
1177 /**
1178  * hash_save_state - Function that saves the state of hardware.
1179  * @device_data:        Pointer to the device structure.
1180  * @device_state:       The strucure where the hardware state should be saved.
1181  */
1182 int hash_save_state(struct hash_device_data *device_data,
1183                     struct hash_state *device_state)
1184 {
1185         u32 temp_cr;
1186         u32 count;
1187         int hash_mode = HASH_OPER_MODE_HASH;
1188
1189         if (NULL == device_state) {
1190                 dev_err(device_data->dev, "%s: HASH_INVALID_PARAMETER!\n",
1191                         __func__);
1192                 return -ENOTSUPP;
1193         }
1194
1195         /* Write dummy value to force digest intermediate calculation. This
1196          * actually makes sure that there isn't any ongoing calculation in the
1197          * hardware.
1198          */
1199         while (readl(&device_data->base->str) & HASH_STR_DCAL_MASK)
1200                 cpu_relax();
1201
1202         temp_cr = readl_relaxed(&device_data->base->cr);
1203
1204         device_state->str_reg = readl_relaxed(&device_data->base->str);
1205
1206         device_state->din_reg = readl_relaxed(&device_data->base->din);
1207
1208         if (readl(&device_data->base->cr) & HASH_CR_MODE_MASK)
1209                 hash_mode = HASH_OPER_MODE_HMAC;
1210         else
1211                 hash_mode = HASH_OPER_MODE_HASH;
1212
1213         for (count = 0; count < HASH_CSR_COUNT; count++) {
1214                 if ((count >= 36) && (hash_mode == HASH_OPER_MODE_HASH))
1215                         break;
1216
1217                 device_state->csr[count] =
1218                         readl_relaxed(&device_data->base->csrx[count]);
1219         }
1220
1221         device_state->csfull = readl_relaxed(&device_data->base->csfull);
1222         device_state->csdatain = readl_relaxed(&device_data->base->csdatain);
1223
1224         device_state->temp_cr = temp_cr;
1225
1226         return 0;
1227 }
1228
1229 /**
1230  * hash_check_hw - This routine checks for peripheral Ids and PCell Ids.
1231  * @device_data:
1232  *
1233  */
1234 int hash_check_hw(struct hash_device_data *device_data)
1235 {
1236         /* Checking Peripheral Ids  */
1237         if (HASH_P_ID0 == readl_relaxed(&device_data->base->periphid0) &&
1238             HASH_P_ID1 == readl_relaxed(&device_data->base->periphid1) &&
1239             HASH_P_ID2 == readl_relaxed(&device_data->base->periphid2) &&
1240             HASH_P_ID3 == readl_relaxed(&device_data->base->periphid3) &&
1241             HASH_CELL_ID0 == readl_relaxed(&device_data->base->cellid0) &&
1242             HASH_CELL_ID1 == readl_relaxed(&device_data->base->cellid1) &&
1243             HASH_CELL_ID2 == readl_relaxed(&device_data->base->cellid2) &&
1244             HASH_CELL_ID3 == readl_relaxed(&device_data->base->cellid3)) {
1245                 return 0;
1246         }
1247
1248         dev_err(device_data->dev, "%s: HASH_UNSUPPORTED_HW!\n", __func__);
1249         return -ENOTSUPP;
1250 }
1251
1252 /**
1253  * hash_get_digest - Gets the digest.
1254  * @device_data:        Pointer to the device structure.
1255  * @digest:             User allocated byte array for the calculated digest.
1256  * @algorithm:          The algorithm in use.
1257  */
1258 void hash_get_digest(struct hash_device_data *device_data,
1259                      u8 *digest, int algorithm)
1260 {
1261         u32 temp_hx_val, count;
1262         int loop_ctr;
1263
1264         if (algorithm != HASH_ALGO_SHA1 && algorithm != HASH_ALGO_SHA256) {
1265                 dev_err(device_data->dev, "%s: Incorrect algorithm %d\n",
1266                         __func__, algorithm);
1267                 return;
1268         }
1269
1270         if (algorithm == HASH_ALGO_SHA1)
1271                 loop_ctr = SHA1_DIGEST_SIZE / sizeof(u32);
1272         else
1273                 loop_ctr = SHA256_DIGEST_SIZE / sizeof(u32);
1274
1275         dev_dbg(device_data->dev, "%s: digest array:(0x%x)\n",
1276                 __func__, (u32) digest);
1277
1278         /* Copy result into digest array */
1279         for (count = 0; count < loop_ctr; count++) {
1280                 temp_hx_val = readl_relaxed(&device_data->base->hx[count]);
1281                 digest[count * 4] = (u8) ((temp_hx_val >> 24) & 0xFF);
1282                 digest[count * 4 + 1] = (u8) ((temp_hx_val >> 16) & 0xFF);
1283                 digest[count * 4 + 2] = (u8) ((temp_hx_val >> 8) & 0xFF);
1284                 digest[count * 4 + 3] = (u8) ((temp_hx_val >> 0) & 0xFF);
1285         }
1286 }
1287
1288 /**
1289  * hash_update - The hash update function for SHA1/SHA2 (SHA256).
1290  * @req: The hash request for the job.
1291  */
1292 static int ahash_update(struct ahash_request *req)
1293 {
1294         int ret = 0;
1295         struct hash_req_ctx *req_ctx = ahash_request_ctx(req);
1296
1297         if (hash_mode != HASH_MODE_DMA || !req_ctx->dma_mode)
1298                 ret = hash_hw_update(req);
1299         /* Skip update for DMA, all data will be passed to DMA in final */
1300
1301         if (ret) {
1302                 pr_err("%s: hash_hw_update() failed!\n", __func__);
1303         }
1304
1305         return ret;
1306 }
1307
1308 /**
1309  * hash_final - The hash final function for SHA1/SHA2 (SHA256).
1310  * @req:        The hash request for the job.
1311  */
1312 static int ahash_final(struct ahash_request *req)
1313 {
1314         int ret = 0;
1315         struct hash_req_ctx *req_ctx = ahash_request_ctx(req);
1316
1317         pr_debug("%s: data size: %d\n", __func__, req->nbytes);
1318
1319         if ((hash_mode == HASH_MODE_DMA) && req_ctx->dma_mode)
1320                 ret = hash_dma_final(req);
1321         else
1322                 ret = hash_hw_final(req);
1323
1324         if (ret) {
1325                 pr_err("%s: hash_hw/dma_final() failed\n", __func__);
1326         }
1327
1328         return ret;
1329 }
1330
1331 static int hash_setkey(struct crypto_ahash *tfm,
1332                        const u8 *key, unsigned int keylen, int alg)
1333 {
1334         int ret = 0;
1335         struct hash_ctx *ctx = crypto_ahash_ctx(tfm);
1336
1337         /**
1338          * Freed in final.
1339          */
1340         ctx->key = kmemdup(key, keylen, GFP_KERNEL);
1341         if (!ctx->key) {
1342                 pr_err("%s: Failed to allocate ctx->key for %d\n",
1343                        __func__, alg);
1344                 return -ENOMEM;
1345         }
1346         ctx->keylen = keylen;
1347
1348         return ret;
1349 }
1350
1351 static int ahash_sha1_init(struct ahash_request *req)
1352 {
1353         struct crypto_ahash *tfm = crypto_ahash_reqtfm(req);
1354         struct hash_ctx *ctx = crypto_ahash_ctx(tfm);
1355
1356         ctx->config.data_format = HASH_DATA_8_BITS;
1357         ctx->config.algorithm = HASH_ALGO_SHA1;
1358         ctx->config.oper_mode = HASH_OPER_MODE_HASH;
1359         ctx->digestsize = SHA1_DIGEST_SIZE;
1360
1361         return hash_init(req);
1362 }
1363
1364 static int ahash_sha256_init(struct ahash_request *req)
1365 {
1366         struct crypto_ahash *tfm = crypto_ahash_reqtfm(req);
1367         struct hash_ctx *ctx = crypto_ahash_ctx(tfm);
1368
1369         ctx->config.data_format = HASH_DATA_8_BITS;
1370         ctx->config.algorithm = HASH_ALGO_SHA256;
1371         ctx->config.oper_mode = HASH_OPER_MODE_HASH;
1372         ctx->digestsize = SHA256_DIGEST_SIZE;
1373
1374         return hash_init(req);
1375 }
1376
1377 static int ahash_sha1_digest(struct ahash_request *req)
1378 {
1379         int ret2, ret1;
1380
1381         ret1 = ahash_sha1_init(req);
1382         if (ret1)
1383                 goto out;
1384
1385         ret1 = ahash_update(req);
1386         ret2 = ahash_final(req);
1387
1388 out:
1389         return ret1 ? ret1 : ret2;
1390 }
1391
1392 static int ahash_sha256_digest(struct ahash_request *req)
1393 {
1394         int ret2, ret1;
1395
1396         ret1 = ahash_sha256_init(req);
1397         if (ret1)
1398                 goto out;
1399
1400         ret1 = ahash_update(req);
1401         ret2 = ahash_final(req);
1402
1403 out:
1404         return ret1 ? ret1 : ret2;
1405 }
1406
1407 static int hmac_sha1_init(struct ahash_request *req)
1408 {
1409         struct crypto_ahash *tfm = crypto_ahash_reqtfm(req);
1410         struct hash_ctx *ctx = crypto_ahash_ctx(tfm);
1411
1412         ctx->config.data_format = HASH_DATA_8_BITS;
1413         ctx->config.algorithm   = HASH_ALGO_SHA1;
1414         ctx->config.oper_mode   = HASH_OPER_MODE_HMAC;
1415         ctx->digestsize         = SHA1_DIGEST_SIZE;
1416
1417         return hash_init(req);
1418 }
1419
1420 static int hmac_sha256_init(struct ahash_request *req)
1421 {
1422         struct crypto_ahash *tfm = crypto_ahash_reqtfm(req);
1423         struct hash_ctx *ctx = crypto_ahash_ctx(tfm);
1424
1425         ctx->config.data_format = HASH_DATA_8_BITS;
1426         ctx->config.algorithm   = HASH_ALGO_SHA256;
1427         ctx->config.oper_mode   = HASH_OPER_MODE_HMAC;
1428         ctx->digestsize         = SHA256_DIGEST_SIZE;
1429
1430         return hash_init(req);
1431 }
1432
1433 static int hmac_sha1_digest(struct ahash_request *req)
1434 {
1435         int ret2, ret1;
1436
1437         ret1 = hmac_sha1_init(req);
1438         if (ret1)
1439                 goto out;
1440
1441         ret1 = ahash_update(req);
1442         ret2 = ahash_final(req);
1443
1444 out:
1445         return ret1 ? ret1 : ret2;
1446 }
1447
1448 static int hmac_sha256_digest(struct ahash_request *req)
1449 {
1450         int ret2, ret1;
1451
1452         ret1 = hmac_sha256_init(req);
1453         if (ret1)
1454                 goto out;
1455
1456         ret1 = ahash_update(req);
1457         ret2 = ahash_final(req);
1458
1459 out:
1460         return ret1 ? ret1 : ret2;
1461 }
1462
1463 static int hmac_sha1_setkey(struct crypto_ahash *tfm,
1464                             const u8 *key, unsigned int keylen)
1465 {
1466         return hash_setkey(tfm, key, keylen, HASH_ALGO_SHA1);
1467 }
1468
1469 static int hmac_sha256_setkey(struct crypto_ahash *tfm,
1470                               const u8 *key, unsigned int keylen)
1471 {
1472         return hash_setkey(tfm, key, keylen, HASH_ALGO_SHA256);
1473 }
1474
1475 struct hash_algo_template {
1476         struct hash_config conf;
1477         struct ahash_alg hash;
1478 };
1479
1480 static int hash_cra_init(struct crypto_tfm *tfm)
1481 {
1482         struct hash_ctx *ctx = crypto_tfm_ctx(tfm);
1483         struct crypto_alg *alg = tfm->__crt_alg;
1484         struct hash_algo_template *hash_alg;
1485
1486         hash_alg = container_of(__crypto_ahash_alg(alg),
1487                         struct hash_algo_template,
1488                         hash);
1489
1490         crypto_ahash_set_reqsize(__crypto_ahash_cast(tfm),
1491                                  sizeof(struct hash_req_ctx));
1492
1493         ctx->config.data_format = HASH_DATA_8_BITS;
1494         ctx->config.algorithm = hash_alg->conf.algorithm;
1495         ctx->config.oper_mode = hash_alg->conf.oper_mode;
1496
1497         ctx->digestsize = hash_alg->hash.halg.digestsize;
1498
1499         return 0;
1500 }
1501
1502 static struct hash_algo_template hash_algs[] = {
1503         {
1504                 .conf.algorithm = HASH_ALGO_SHA1,
1505                 .conf.oper_mode = HASH_OPER_MODE_HASH,
1506                 .hash = {
1507                         .init = hash_init,
1508                         .update = ahash_update,
1509                         .final = ahash_final,
1510                         .digest = ahash_sha1_digest,
1511                         .halg.digestsize = SHA1_DIGEST_SIZE,
1512                         .halg.statesize = sizeof(struct hash_ctx),
1513                         .halg.base = {
1514                                 .cra_name = "sha1",
1515                                 .cra_driver_name = "sha1-ux500",
1516                                 .cra_flags = (CRYPTO_ALG_TYPE_AHASH |
1517                                               CRYPTO_ALG_ASYNC),
1518                                 .cra_blocksize = SHA1_BLOCK_SIZE,
1519                                 .cra_ctxsize = sizeof(struct hash_ctx),
1520                                 .cra_init = hash_cra_init,
1521                                 .cra_module = THIS_MODULE,
1522                         }
1523                 }
1524         },
1525         {
1526                 .conf.algorithm = HASH_ALGO_SHA256,
1527                 .conf.oper_mode = HASH_OPER_MODE_HASH,
1528                 .hash = {
1529                         .init = hash_init,
1530                         .update = ahash_update,
1531                         .final = ahash_final,
1532                         .digest = ahash_sha256_digest,
1533                         .halg.digestsize = SHA256_DIGEST_SIZE,
1534                         .halg.statesize = sizeof(struct hash_ctx),
1535                         .halg.base = {
1536                                 .cra_name = "sha256",
1537                                 .cra_driver_name = "sha256-ux500",
1538                                 .cra_flags = (CRYPTO_ALG_TYPE_AHASH |
1539                                               CRYPTO_ALG_ASYNC),
1540                                 .cra_blocksize = SHA256_BLOCK_SIZE,
1541                                 .cra_ctxsize = sizeof(struct hash_ctx),
1542                                 .cra_type = &crypto_ahash_type,
1543                                 .cra_init = hash_cra_init,
1544                                 .cra_module = THIS_MODULE,
1545                         }
1546                 }
1547         },
1548         {
1549                 .conf.algorithm = HASH_ALGO_SHA1,
1550                 .conf.oper_mode = HASH_OPER_MODE_HMAC,
1551                         .hash = {
1552                         .init = hash_init,
1553                         .update = ahash_update,
1554                         .final = ahash_final,
1555                         .digest = hmac_sha1_digest,
1556                         .setkey = hmac_sha1_setkey,
1557                         .halg.digestsize = SHA1_DIGEST_SIZE,
1558                         .halg.statesize = sizeof(struct hash_ctx),
1559                         .halg.base = {
1560                                 .cra_name = "hmac(sha1)",
1561                                 .cra_driver_name = "hmac-sha1-ux500",
1562                                 .cra_flags = (CRYPTO_ALG_TYPE_AHASH |
1563                                               CRYPTO_ALG_ASYNC),
1564                                 .cra_blocksize = SHA1_BLOCK_SIZE,
1565                                 .cra_ctxsize = sizeof(struct hash_ctx),
1566                                 .cra_type = &crypto_ahash_type,
1567                                 .cra_init = hash_cra_init,
1568                                 .cra_module = THIS_MODULE,
1569                         }
1570                 }
1571         },
1572         {
1573                 .conf.algorithm = HASH_ALGO_SHA256,
1574                 .conf.oper_mode = HASH_OPER_MODE_HMAC,
1575                 .hash = {
1576                         .init = hash_init,
1577                         .update = ahash_update,
1578                         .final = ahash_final,
1579                         .digest = hmac_sha256_digest,
1580                         .setkey = hmac_sha256_setkey,
1581                         .halg.digestsize = SHA256_DIGEST_SIZE,
1582                         .halg.statesize = sizeof(struct hash_ctx),
1583                         .halg.base = {
1584                                 .cra_name = "hmac(sha256)",
1585                                 .cra_driver_name = "hmac-sha256-ux500",
1586                                 .cra_flags = (CRYPTO_ALG_TYPE_AHASH |
1587                                               CRYPTO_ALG_ASYNC),
1588                                 .cra_blocksize = SHA256_BLOCK_SIZE,
1589                                 .cra_ctxsize = sizeof(struct hash_ctx),
1590                                 .cra_type = &crypto_ahash_type,
1591                                 .cra_init = hash_cra_init,
1592                                 .cra_module = THIS_MODULE,
1593                         }
1594                 }
1595         }
1596 };
1597
1598 /**
1599  * hash_algs_register_all -
1600  */
1601 static int ahash_algs_register_all(struct hash_device_data *device_data)
1602 {
1603         int ret;
1604         int i;
1605         int count;
1606
1607         for (i = 0; i < ARRAY_SIZE(hash_algs); i++) {
1608                 ret = crypto_register_ahash(&hash_algs[i].hash);
1609                 if (ret) {
1610                         count = i;
1611                         dev_err(device_data->dev, "%s: alg registration failed\n",
1612                                 hash_algs[i].hash.halg.base.cra_driver_name);
1613                         goto unreg;
1614                 }
1615         }
1616         return 0;
1617 unreg:
1618         for (i = 0; i < count; i++)
1619                 crypto_unregister_ahash(&hash_algs[i].hash);
1620         return ret;
1621 }
1622
1623 /**
1624  * hash_algs_unregister_all -
1625  */
1626 static void ahash_algs_unregister_all(struct hash_device_data *device_data)
1627 {
1628         int i;
1629
1630         for (i = 0; i < ARRAY_SIZE(hash_algs); i++)
1631                 crypto_unregister_ahash(&hash_algs[i].hash);
1632 }
1633
1634 /**
1635  * ux500_hash_probe - Function that probes the hash hardware.
1636  * @pdev: The platform device.
1637  */
1638 static int ux500_hash_probe(struct platform_device *pdev)
1639 {
1640         int                     ret = 0;
1641         struct resource         *res = NULL;
1642         struct hash_device_data *device_data;
1643         struct device           *dev = &pdev->dev;
1644
1645         device_data = devm_kzalloc(dev, sizeof(*device_data), GFP_ATOMIC);
1646         if (!device_data) {
1647                 ret = -ENOMEM;
1648                 goto out;
1649         }
1650
1651         device_data->dev = dev;
1652         device_data->current_ctx = NULL;
1653
1654         res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
1655         if (!res) {
1656                 dev_dbg(dev, "%s: platform_get_resource() failed!\n", __func__);
1657                 ret = -ENODEV;
1658                 goto out;
1659         }
1660
1661         device_data->phybase = res->start;
1662         device_data->base = devm_ioremap_resource(dev, res);
1663         if (IS_ERR(device_data->base)) {
1664                 dev_err(dev, "%s: ioremap() failed!\n", __func__);
1665                 ret = PTR_ERR(device_data->base);
1666                 goto out;
1667         }
1668         spin_lock_init(&device_data->ctx_lock);
1669         spin_lock_init(&device_data->power_state_lock);
1670
1671         /* Enable power for HASH1 hardware block */
1672         device_data->regulator = regulator_get(dev, "v-ape");
1673         if (IS_ERR(device_data->regulator)) {
1674                 dev_err(dev, "%s: regulator_get() failed!\n", __func__);
1675                 ret = PTR_ERR(device_data->regulator);
1676                 device_data->regulator = NULL;
1677                 goto out;
1678         }
1679
1680         /* Enable the clock for HASH1 hardware block */
1681         device_data->clk = devm_clk_get(dev, NULL);
1682         if (IS_ERR(device_data->clk)) {
1683                 dev_err(dev, "%s: clk_get() failed!\n", __func__);
1684                 ret = PTR_ERR(device_data->clk);
1685                 goto out_regulator;
1686         }
1687
1688         ret = clk_prepare(device_data->clk);
1689         if (ret) {
1690                 dev_err(dev, "%s: clk_prepare() failed!\n", __func__);
1691                 goto out_regulator;
1692         }
1693
1694         /* Enable device power (and clock) */
1695         ret = hash_enable_power(device_data, false);
1696         if (ret) {
1697                 dev_err(dev, "%s: hash_enable_power() failed!\n", __func__);
1698                 goto out_clk_unprepare;
1699         }
1700
1701         ret = hash_check_hw(device_data);
1702         if (ret) {
1703                 dev_err(dev, "%s: hash_check_hw() failed!\n", __func__);
1704                 goto out_power;
1705         }
1706
1707         if (hash_mode == HASH_MODE_DMA)
1708                 hash_dma_setup_channel(device_data, dev);
1709
1710         platform_set_drvdata(pdev, device_data);
1711
1712         /* Put the new device into the device list... */
1713         klist_add_tail(&device_data->list_node, &driver_data.device_list);
1714         /* ... and signal that a new device is available. */
1715         up(&driver_data.device_allocation);
1716
1717         ret = ahash_algs_register_all(device_data);
1718         if (ret) {
1719                 dev_err(dev, "%s: ahash_algs_register_all() failed!\n",
1720                         __func__);
1721                 goto out_power;
1722         }
1723
1724         dev_info(dev, "successfully registered\n");
1725         return 0;
1726
1727 out_power:
1728         hash_disable_power(device_data, false);
1729
1730 out_clk_unprepare:
1731         clk_unprepare(device_data->clk);
1732
1733 out_regulator:
1734         regulator_put(device_data->regulator);
1735
1736 out:
1737         return ret;
1738 }
1739
1740 /**
1741  * ux500_hash_remove - Function that removes the hash device from the platform.
1742  * @pdev: The platform device.
1743  */
1744 static int ux500_hash_remove(struct platform_device *pdev)
1745 {
1746         struct hash_device_data *device_data;
1747         struct device           *dev = &pdev->dev;
1748
1749         device_data = platform_get_drvdata(pdev);
1750         if (!device_data) {
1751                 dev_err(dev, "%s: platform_get_drvdata() failed!\n", __func__);
1752                 return -ENOMEM;
1753         }
1754
1755         /* Try to decrease the number of available devices. */
1756         if (down_trylock(&driver_data.device_allocation))
1757                 return -EBUSY;
1758
1759         /* Check that the device is free */
1760         spin_lock(&device_data->ctx_lock);
1761         /* current_ctx allocates a device, NULL = unallocated */
1762         if (device_data->current_ctx) {
1763                 /* The device is busy */
1764                 spin_unlock(&device_data->ctx_lock);
1765                 /* Return the device to the pool. */
1766                 up(&driver_data.device_allocation);
1767                 return -EBUSY;
1768         }
1769
1770         spin_unlock(&device_data->ctx_lock);
1771
1772         /* Remove the device from the list */
1773         if (klist_node_attached(&device_data->list_node))
1774                 klist_remove(&device_data->list_node);
1775
1776         /* If this was the last device, remove the services */
1777         if (list_empty(&driver_data.device_list.k_list))
1778                 ahash_algs_unregister_all(device_data);
1779
1780         if (hash_disable_power(device_data, false))
1781                 dev_err(dev, "%s: hash_disable_power() failed\n",
1782                         __func__);
1783
1784         clk_unprepare(device_data->clk);
1785         regulator_put(device_data->regulator);
1786
1787         return 0;
1788 }
1789
1790 /**
1791  * ux500_hash_shutdown - Function that shutdown the hash device.
1792  * @pdev: The platform device
1793  */
1794 static void ux500_hash_shutdown(struct platform_device *pdev)
1795 {
1796         struct hash_device_data *device_data;
1797
1798         device_data = platform_get_drvdata(pdev);
1799         if (!device_data) {
1800                 dev_err(&pdev->dev, "%s: platform_get_drvdata() failed!\n",
1801                         __func__);
1802                 return;
1803         }
1804
1805         /* Check that the device is free */
1806         spin_lock(&device_data->ctx_lock);
1807         /* current_ctx allocates a device, NULL = unallocated */
1808         if (!device_data->current_ctx) {
1809                 if (down_trylock(&driver_data.device_allocation))
1810                         dev_dbg(&pdev->dev, "%s: Cryp still in use! Shutting down anyway...\n",
1811                                 __func__);
1812                 /**
1813                  * (Allocate the device)
1814                  * Need to set this to non-null (dummy) value,
1815                  * to avoid usage if context switching.
1816                  */
1817                 device_data->current_ctx++;
1818         }
1819         spin_unlock(&device_data->ctx_lock);
1820
1821         /* Remove the device from the list */
1822         if (klist_node_attached(&device_data->list_node))
1823                 klist_remove(&device_data->list_node);
1824
1825         /* If this was the last device, remove the services */
1826         if (list_empty(&driver_data.device_list.k_list))
1827                 ahash_algs_unregister_all(device_data);
1828
1829         if (hash_disable_power(device_data, false))
1830                 dev_err(&pdev->dev, "%s: hash_disable_power() failed\n",
1831                         __func__);
1832 }
1833
1834 #ifdef CONFIG_PM_SLEEP
1835 /**
1836  * ux500_hash_suspend - Function that suspends the hash device.
1837  * @dev:        Device to suspend.
1838  */
1839 static int ux500_hash_suspend(struct device *dev)
1840 {
1841         int ret;
1842         struct hash_device_data *device_data;
1843         struct hash_ctx *temp_ctx = NULL;
1844
1845         device_data = dev_get_drvdata(dev);
1846         if (!device_data) {
1847                 dev_err(dev, "%s: platform_get_drvdata() failed!\n", __func__);
1848                 return -ENOMEM;
1849         }
1850
1851         spin_lock(&device_data->ctx_lock);
1852         if (!device_data->current_ctx)
1853                 device_data->current_ctx++;
1854         spin_unlock(&device_data->ctx_lock);
1855
1856         if (device_data->current_ctx == ++temp_ctx) {
1857                 if (down_interruptible(&driver_data.device_allocation))
1858                         dev_dbg(dev, "%s: down_interruptible() failed\n",
1859                                 __func__);
1860                 ret = hash_disable_power(device_data, false);
1861
1862         } else {
1863                 ret = hash_disable_power(device_data, true);
1864         }
1865
1866         if (ret)
1867                 dev_err(dev, "%s: hash_disable_power()\n", __func__);
1868
1869         return ret;
1870 }
1871
1872 /**
1873  * ux500_hash_resume - Function that resume the hash device.
1874  * @dev:        Device to resume.
1875  */
1876 static int ux500_hash_resume(struct device *dev)
1877 {
1878         int ret = 0;
1879         struct hash_device_data *device_data;
1880         struct hash_ctx *temp_ctx = NULL;
1881
1882         device_data = dev_get_drvdata(dev);
1883         if (!device_data) {
1884                 dev_err(dev, "%s: platform_get_drvdata() failed!\n", __func__);
1885                 return -ENOMEM;
1886         }
1887
1888         spin_lock(&device_data->ctx_lock);
1889         if (device_data->current_ctx == ++temp_ctx)
1890                 device_data->current_ctx = NULL;
1891         spin_unlock(&device_data->ctx_lock);
1892
1893         if (!device_data->current_ctx)
1894                 up(&driver_data.device_allocation);
1895         else
1896                 ret = hash_enable_power(device_data, true);
1897
1898         if (ret)
1899                 dev_err(dev, "%s: hash_enable_power() failed!\n", __func__);
1900
1901         return ret;
1902 }
1903 #endif
1904
1905 static SIMPLE_DEV_PM_OPS(ux500_hash_pm, ux500_hash_suspend, ux500_hash_resume);
1906
1907 static const struct of_device_id ux500_hash_match[] = {
1908         { .compatible = "stericsson,ux500-hash" },
1909         { },
1910 };
1911 MODULE_DEVICE_TABLE(of, ux500_hash_match);
1912
1913 static struct platform_driver hash_driver = {
1914         .probe  = ux500_hash_probe,
1915         .remove = ux500_hash_remove,
1916         .shutdown = ux500_hash_shutdown,
1917         .driver = {
1918                 .name  = "hash1",
1919                 .of_match_table = ux500_hash_match,
1920                 .pm    = &ux500_hash_pm,
1921         }
1922 };
1923
1924 /**
1925  * ux500_hash_mod_init - The kernel module init function.
1926  */
1927 static int __init ux500_hash_mod_init(void)
1928 {
1929         klist_init(&driver_data.device_list, NULL, NULL);
1930         /* Initialize the semaphore to 0 devices (locked state) */
1931         sema_init(&driver_data.device_allocation, 0);
1932
1933         return platform_driver_register(&hash_driver);
1934 }
1935
1936 /**
1937  * ux500_hash_mod_fini - The kernel module exit function.
1938  */
1939 static void __exit ux500_hash_mod_fini(void)
1940 {
1941         platform_driver_unregister(&hash_driver);
1942 }
1943
1944 module_init(ux500_hash_mod_init);
1945 module_exit(ux500_hash_mod_fini);
1946
1947 MODULE_DESCRIPTION("Driver for ST-Ericsson UX500 HASH engine.");
1948 MODULE_LICENSE("GPL");
1949
1950 MODULE_ALIAS_CRYPTO("sha1-all");
1951 MODULE_ALIAS_CRYPTO("sha256-all");
1952 MODULE_ALIAS_CRYPTO("hmac-sha1-all");
1953 MODULE_ALIAS_CRYPTO("hmac-sha256-all");