crypto: sahara - remove 'active' flag from sahara_aes_reqctx struct
[linux-block.git] / drivers / crypto / sahara.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Cryptographic API.
4  *
5  * Support for SAHARA cryptographic accelerator.
6  *
7  * Copyright (c) 2014 Steffen Trumtrar <s.trumtrar@pengutronix.de>
8  * Copyright (c) 2013 Vista Silicon S.L.
9  * Author: Javier Martin <javier.martin@vista-silicon.com>
10  *
11  * Based on omap-aes.c and tegra-aes.c
12  */
13
14 #include <crypto/aes.h>
15 #include <crypto/internal/hash.h>
16 #include <crypto/internal/skcipher.h>
17 #include <crypto/scatterwalk.h>
18 #include <crypto/sha1.h>
19 #include <crypto/sha2.h>
20
21 #include <linux/clk.h>
22 #include <linux/dma-mapping.h>
23 #include <linux/interrupt.h>
24 #include <linux/io.h>
25 #include <linux/irq.h>
26 #include <linux/kernel.h>
27 #include <linux/kthread.h>
28 #include <linux/module.h>
29 #include <linux/of.h>
30 #include <linux/platform_device.h>
31 #include <linux/spinlock.h>
32
33 #define SHA_BUFFER_LEN                          PAGE_SIZE
34 #define SAHARA_MAX_SHA_BLOCK_SIZE               SHA256_BLOCK_SIZE
35
36 #define SAHARA_NAME                             "sahara"
37 #define SAHARA_VERSION_3                        3
38 #define SAHARA_VERSION_4                        4
39 #define SAHARA_TIMEOUT_MS                       1000
40 #define SAHARA_MAX_HW_DESC                      2
41 #define SAHARA_MAX_HW_LINK                      20
42
43 #define FLAGS_MODE_MASK                         0x000f
44 #define FLAGS_ENCRYPT                           BIT(0)
45 #define FLAGS_CBC                               BIT(1)
46
47 #define SAHARA_HDR_BASE                         0x00800000
48 #define SAHARA_HDR_SKHA_ALG_AES                 0
49 #define SAHARA_HDR_SKHA_MODE_ECB                0
50 #define SAHARA_HDR_SKHA_OP_ENC                  BIT(2)
51 #define SAHARA_HDR_SKHA_MODE_CBC                BIT(3)
52 #define SAHARA_HDR_FORM_DATA                    (5 << 16)
53 #define SAHARA_HDR_FORM_KEY                     BIT(19)
54 #define SAHARA_HDR_LLO                          BIT(24)
55 #define SAHARA_HDR_CHA_SKHA                     BIT(28)
56 #define SAHARA_HDR_CHA_MDHA                     BIT(29)
57 #define SAHARA_HDR_PARITY_BIT                   BIT(31)
58
59 #define SAHARA_HDR_MDHA_SET_MODE_MD_KEY         0x20880000
60 #define SAHARA_HDR_MDHA_SET_MODE_HASH           0x208D0000
61 #define SAHARA_HDR_MDHA_HASH                    0xA0850000
62 #define SAHARA_HDR_MDHA_STORE_DIGEST            0x20820000
63 #define SAHARA_HDR_MDHA_ALG_SHA1                0
64 #define SAHARA_HDR_MDHA_ALG_MD5                 1
65 #define SAHARA_HDR_MDHA_ALG_SHA256              2
66 #define SAHARA_HDR_MDHA_ALG_SHA224              3
67 #define SAHARA_HDR_MDHA_PDATA                   BIT(2)
68 #define SAHARA_HDR_MDHA_HMAC                    BIT(3)
69 #define SAHARA_HDR_MDHA_INIT                    BIT(5)
70 #define SAHARA_HDR_MDHA_IPAD                    BIT(6)
71 #define SAHARA_HDR_MDHA_OPAD                    BIT(7)
72 #define SAHARA_HDR_MDHA_SWAP                    BIT(8)
73 #define SAHARA_HDR_MDHA_MAC_FULL                BIT(9)
74 #define SAHARA_HDR_MDHA_SSL                     BIT(10)
75
76 /* SAHARA can only process one request at a time */
77 #define SAHARA_QUEUE_LENGTH                     1
78
79 #define SAHARA_REG_VERSION                      0x00
80 #define SAHARA_REG_DAR                          0x04
81 #define SAHARA_REG_CONTROL                      0x08
82 #define SAHARA_CONTROL_SET_THROTTLE(x)          (((x) & 0xff) << 24)
83 #define SAHARA_CONTROL_SET_MAXBURST(x)          (((x) & 0xff) << 16)
84 #define SAHARA_CONTROL_RNG_AUTORSD              BIT(7)
85 #define SAHARA_CONTROL_ENABLE_INT               BIT(4)
86 #define SAHARA_REG_CMD                          0x0C
87 #define SAHARA_CMD_RESET                        BIT(0)
88 #define SAHARA_CMD_CLEAR_INT                    BIT(8)
89 #define SAHARA_CMD_CLEAR_ERR                    BIT(9)
90 #define SAHARA_CMD_SINGLE_STEP                  BIT(10)
91 #define SAHARA_CMD_MODE_BATCH                   BIT(16)
92 #define SAHARA_CMD_MODE_DEBUG                   BIT(18)
93 #define SAHARA_REG_STATUS                       0x10
94 #define SAHARA_STATUS_GET_STATE(x)              ((x) & 0x7)
95 #define SAHARA_STATE_IDLE                       0
96 #define SAHARA_STATE_BUSY                       1
97 #define SAHARA_STATE_ERR                        2
98 #define SAHARA_STATE_FAULT                      3
99 #define SAHARA_STATE_COMPLETE                   4
100 #define SAHARA_STATE_COMP_FLAG                  BIT(2)
101 #define SAHARA_STATUS_DAR_FULL                  BIT(3)
102 #define SAHARA_STATUS_ERROR                     BIT(4)
103 #define SAHARA_STATUS_SECURE                    BIT(5)
104 #define SAHARA_STATUS_FAIL                      BIT(6)
105 #define SAHARA_STATUS_INIT                      BIT(7)
106 #define SAHARA_STATUS_RNG_RESEED                BIT(8)
107 #define SAHARA_STATUS_ACTIVE_RNG                BIT(9)
108 #define SAHARA_STATUS_ACTIVE_MDHA               BIT(10)
109 #define SAHARA_STATUS_ACTIVE_SKHA               BIT(11)
110 #define SAHARA_STATUS_MODE_BATCH                BIT(16)
111 #define SAHARA_STATUS_MODE_DEDICATED            BIT(17)
112 #define SAHARA_STATUS_MODE_DEBUG                BIT(18)
113 #define SAHARA_STATUS_GET_ISTATE(x)             (((x) >> 24) & 0xff)
114 #define SAHARA_REG_ERRSTATUS                    0x14
115 #define SAHARA_ERRSTATUS_GET_SOURCE(x)          ((x) & 0xf)
116 #define SAHARA_ERRSOURCE_CHA                    14
117 #define SAHARA_ERRSOURCE_DMA                    15
118 #define SAHARA_ERRSTATUS_DMA_DIR                BIT(8)
119 #define SAHARA_ERRSTATUS_GET_DMASZ(x)           (((x) >> 9) & 0x3)
120 #define SAHARA_ERRSTATUS_GET_DMASRC(x)          (((x) >> 13) & 0x7)
121 #define SAHARA_ERRSTATUS_GET_CHASRC(x)          (((x) >> 16) & 0xfff)
122 #define SAHARA_ERRSTATUS_GET_CHAERR(x)          (((x) >> 28) & 0x3)
123 #define SAHARA_REG_FADDR                        0x18
124 #define SAHARA_REG_CDAR                         0x1C
125 #define SAHARA_REG_IDAR                         0x20
126
127 struct sahara_hw_desc {
128         u32     hdr;
129         u32     len1;
130         u32     p1;
131         u32     len2;
132         u32     p2;
133         u32     next;
134 };
135
136 struct sahara_hw_link {
137         u32     len;
138         u32     p;
139         u32     next;
140 };
141
142 struct sahara_ctx {
143         /* AES-specific context */
144         int keylen;
145         u8 key[AES_KEYSIZE_128];
146         struct crypto_skcipher *fallback;
147 };
148
149 struct sahara_aes_reqctx {
150         unsigned long mode;
151         u8 iv_out[AES_BLOCK_SIZE];
152         struct skcipher_request fallback_req;   // keep at the end
153 };
154
155 /*
156  * struct sahara_sha_reqctx - private data per request
157  * @buf: holds data for requests smaller than block_size
158  * @rembuf: used to prepare one block_size-aligned request
159  * @context: hw-specific context for request. Digest is extracted from this
160  * @mode: specifies what type of hw-descriptor needs to be built
161  * @digest_size: length of digest for this request
162  * @context_size: length of hw-context for this request.
163  *                Always digest_size + 4
164  * @buf_cnt: number of bytes saved in buf
165  * @sg_in_idx: number of hw links
166  * @in_sg: scatterlist for input data
167  * @in_sg_chain: scatterlists for chained input data
168  * @total: total number of bytes for transfer
169  * @last: is this the last block
170  * @first: is this the first block
171  */
172 struct sahara_sha_reqctx {
173         u8                      buf[SAHARA_MAX_SHA_BLOCK_SIZE];
174         u8                      rembuf[SAHARA_MAX_SHA_BLOCK_SIZE];
175         u8                      context[SHA256_DIGEST_SIZE + 4];
176         unsigned int            mode;
177         unsigned int            digest_size;
178         unsigned int            context_size;
179         unsigned int            buf_cnt;
180         unsigned int            sg_in_idx;
181         struct scatterlist      *in_sg;
182         struct scatterlist      in_sg_chain[2];
183         size_t                  total;
184         unsigned int            last;
185         unsigned int            first;
186 };
187
188 struct sahara_dev {
189         struct device           *device;
190         unsigned int            version;
191         void __iomem            *regs_base;
192         struct clk              *clk_ipg;
193         struct clk              *clk_ahb;
194         spinlock_t              queue_spinlock;
195         struct task_struct      *kthread;
196         struct completion       dma_completion;
197
198         struct sahara_ctx       *ctx;
199         struct crypto_queue     queue;
200         unsigned long           flags;
201
202         struct sahara_hw_desc   *hw_desc[SAHARA_MAX_HW_DESC];
203         dma_addr_t              hw_phys_desc[SAHARA_MAX_HW_DESC];
204
205         u8                      *key_base;
206         dma_addr_t              key_phys_base;
207
208         u8                      *iv_base;
209         dma_addr_t              iv_phys_base;
210
211         u8                      *context_base;
212         dma_addr_t              context_phys_base;
213
214         struct sahara_hw_link   *hw_link[SAHARA_MAX_HW_LINK];
215         dma_addr_t              hw_phys_link[SAHARA_MAX_HW_LINK];
216
217         size_t                  total;
218         struct scatterlist      *in_sg;
219         int             nb_in_sg;
220         struct scatterlist      *out_sg;
221         int             nb_out_sg;
222 };
223
224 static struct sahara_dev *dev_ptr;
225
226 static inline void sahara_write(struct sahara_dev *dev, u32 data, u32 reg)
227 {
228         writel(data, dev->regs_base + reg);
229 }
230
231 static inline unsigned int sahara_read(struct sahara_dev *dev, u32 reg)
232 {
233         return readl(dev->regs_base + reg);
234 }
235
236 static u32 sahara_aes_key_hdr(struct sahara_dev *dev)
237 {
238         u32 hdr = SAHARA_HDR_BASE | SAHARA_HDR_SKHA_ALG_AES |
239                         SAHARA_HDR_FORM_KEY | SAHARA_HDR_LLO |
240                         SAHARA_HDR_CHA_SKHA | SAHARA_HDR_PARITY_BIT;
241
242         if (dev->flags & FLAGS_CBC) {
243                 hdr |= SAHARA_HDR_SKHA_MODE_CBC;
244                 hdr ^= SAHARA_HDR_PARITY_BIT;
245         }
246
247         if (dev->flags & FLAGS_ENCRYPT) {
248                 hdr |= SAHARA_HDR_SKHA_OP_ENC;
249                 hdr ^= SAHARA_HDR_PARITY_BIT;
250         }
251
252         return hdr;
253 }
254
255 static u32 sahara_aes_data_link_hdr(struct sahara_dev *dev)
256 {
257         return SAHARA_HDR_BASE | SAHARA_HDR_FORM_DATA |
258                         SAHARA_HDR_CHA_SKHA | SAHARA_HDR_PARITY_BIT;
259 }
260
261 static const char *sahara_err_src[16] = {
262         "No error",
263         "Header error",
264         "Descriptor length error",
265         "Descriptor length or pointer error",
266         "Link length error",
267         "Link pointer error",
268         "Input buffer error",
269         "Output buffer error",
270         "Output buffer starvation",
271         "Internal state fault",
272         "General descriptor problem",
273         "Reserved",
274         "Descriptor address error",
275         "Link address error",
276         "CHA error",
277         "DMA error"
278 };
279
280 static const char *sahara_err_dmasize[4] = {
281         "Byte transfer",
282         "Half-word transfer",
283         "Word transfer",
284         "Reserved"
285 };
286
287 static const char *sahara_err_dmasrc[8] = {
288         "No error",
289         "AHB bus error",
290         "Internal IP bus error",
291         "Parity error",
292         "DMA crosses 256 byte boundary",
293         "DMA is busy",
294         "Reserved",
295         "DMA HW error"
296 };
297
298 static const char *sahara_cha_errsrc[12] = {
299         "Input buffer non-empty",
300         "Illegal address",
301         "Illegal mode",
302         "Illegal data size",
303         "Illegal key size",
304         "Write during processing",
305         "CTX read during processing",
306         "HW error",
307         "Input buffer disabled/underflow",
308         "Output buffer disabled/overflow",
309         "DES key parity error",
310         "Reserved"
311 };
312
313 static const char *sahara_cha_err[4] = { "No error", "SKHA", "MDHA", "RNG" };
314
315 static void sahara_decode_error(struct sahara_dev *dev, unsigned int error)
316 {
317         u8 source = SAHARA_ERRSTATUS_GET_SOURCE(error);
318         u16 chasrc = ffs(SAHARA_ERRSTATUS_GET_CHASRC(error));
319
320         dev_err(dev->device, "%s: Error Register = 0x%08x\n", __func__, error);
321
322         dev_err(dev->device, "  - %s.\n", sahara_err_src[source]);
323
324         if (source == SAHARA_ERRSOURCE_DMA) {
325                 if (error & SAHARA_ERRSTATUS_DMA_DIR)
326                         dev_err(dev->device, "          * DMA read.\n");
327                 else
328                         dev_err(dev->device, "          * DMA write.\n");
329
330                 dev_err(dev->device, "          * %s.\n",
331                        sahara_err_dmasize[SAHARA_ERRSTATUS_GET_DMASZ(error)]);
332                 dev_err(dev->device, "          * %s.\n",
333                        sahara_err_dmasrc[SAHARA_ERRSTATUS_GET_DMASRC(error)]);
334         } else if (source == SAHARA_ERRSOURCE_CHA) {
335                 dev_err(dev->device, "          * %s.\n",
336                         sahara_cha_errsrc[chasrc]);
337                 dev_err(dev->device, "          * %s.\n",
338                        sahara_cha_err[SAHARA_ERRSTATUS_GET_CHAERR(error)]);
339         }
340         dev_err(dev->device, "\n");
341 }
342
343 static const char *sahara_state[4] = { "Idle", "Busy", "Error", "HW Fault" };
344
345 static void sahara_decode_status(struct sahara_dev *dev, unsigned int status)
346 {
347         u8 state;
348
349         if (!__is_defined(DEBUG))
350                 return;
351
352         state = SAHARA_STATUS_GET_STATE(status);
353
354         dev_dbg(dev->device, "%s: Status Register = 0x%08x\n",
355                 __func__, status);
356
357         dev_dbg(dev->device, "  - State = %d:\n", state);
358         if (state & SAHARA_STATE_COMP_FLAG)
359                 dev_dbg(dev->device, "          * Descriptor completed. IRQ pending.\n");
360
361         dev_dbg(dev->device, "          * %s.\n",
362                sahara_state[state & ~SAHARA_STATE_COMP_FLAG]);
363
364         if (status & SAHARA_STATUS_DAR_FULL)
365                 dev_dbg(dev->device, "  - DAR Full.\n");
366         if (status & SAHARA_STATUS_ERROR)
367                 dev_dbg(dev->device, "  - Error.\n");
368         if (status & SAHARA_STATUS_SECURE)
369                 dev_dbg(dev->device, "  - Secure.\n");
370         if (status & SAHARA_STATUS_FAIL)
371                 dev_dbg(dev->device, "  - Fail.\n");
372         if (status & SAHARA_STATUS_RNG_RESEED)
373                 dev_dbg(dev->device, "  - RNG Reseed Request.\n");
374         if (status & SAHARA_STATUS_ACTIVE_RNG)
375                 dev_dbg(dev->device, "  - RNG Active.\n");
376         if (status & SAHARA_STATUS_ACTIVE_MDHA)
377                 dev_dbg(dev->device, "  - MDHA Active.\n");
378         if (status & SAHARA_STATUS_ACTIVE_SKHA)
379                 dev_dbg(dev->device, "  - SKHA Active.\n");
380
381         if (status & SAHARA_STATUS_MODE_BATCH)
382                 dev_dbg(dev->device, "  - Batch Mode.\n");
383         else if (status & SAHARA_STATUS_MODE_DEDICATED)
384                 dev_dbg(dev->device, "  - Dedicated Mode.\n");
385         else if (status & SAHARA_STATUS_MODE_DEBUG)
386                 dev_dbg(dev->device, "  - Debug Mode.\n");
387
388         dev_dbg(dev->device, "  - Internal state = 0x%02x\n",
389                SAHARA_STATUS_GET_ISTATE(status));
390
391         dev_dbg(dev->device, "Current DAR: 0x%08x\n",
392                 sahara_read(dev, SAHARA_REG_CDAR));
393         dev_dbg(dev->device, "Initial DAR: 0x%08x\n\n",
394                 sahara_read(dev, SAHARA_REG_IDAR));
395 }
396
397 static void sahara_dump_descriptors(struct sahara_dev *dev)
398 {
399         int i;
400
401         if (!__is_defined(DEBUG))
402                 return;
403
404         for (i = 0; i < SAHARA_MAX_HW_DESC; i++) {
405                 dev_dbg(dev->device, "Descriptor (%d) (%pad):\n",
406                         i, &dev->hw_phys_desc[i]);
407                 dev_dbg(dev->device, "\thdr = 0x%08x\n", dev->hw_desc[i]->hdr);
408                 dev_dbg(dev->device, "\tlen1 = %u\n", dev->hw_desc[i]->len1);
409                 dev_dbg(dev->device, "\tp1 = 0x%08x\n", dev->hw_desc[i]->p1);
410                 dev_dbg(dev->device, "\tlen2 = %u\n", dev->hw_desc[i]->len2);
411                 dev_dbg(dev->device, "\tp2 = 0x%08x\n", dev->hw_desc[i]->p2);
412                 dev_dbg(dev->device, "\tnext = 0x%08x\n",
413                         dev->hw_desc[i]->next);
414         }
415         dev_dbg(dev->device, "\n");
416 }
417
418 static void sahara_dump_links(struct sahara_dev *dev)
419 {
420         int i;
421
422         if (!__is_defined(DEBUG))
423                 return;
424
425         for (i = 0; i < SAHARA_MAX_HW_LINK; i++) {
426                 dev_dbg(dev->device, "Link (%d) (%pad):\n",
427                         i, &dev->hw_phys_link[i]);
428                 dev_dbg(dev->device, "\tlen = %u\n", dev->hw_link[i]->len);
429                 dev_dbg(dev->device, "\tp = 0x%08x\n", dev->hw_link[i]->p);
430                 dev_dbg(dev->device, "\tnext = 0x%08x\n",
431                         dev->hw_link[i]->next);
432         }
433         dev_dbg(dev->device, "\n");
434 }
435
436 static int sahara_hw_descriptor_create(struct sahara_dev *dev)
437 {
438         struct sahara_ctx *ctx = dev->ctx;
439         struct scatterlist *sg;
440         int ret;
441         int i, j;
442         int idx = 0;
443         u32 len;
444
445         memcpy(dev->key_base, ctx->key, ctx->keylen);
446
447         if (dev->flags & FLAGS_CBC) {
448                 dev->hw_desc[idx]->len1 = AES_BLOCK_SIZE;
449                 dev->hw_desc[idx]->p1 = dev->iv_phys_base;
450         } else {
451                 dev->hw_desc[idx]->len1 = 0;
452                 dev->hw_desc[idx]->p1 = 0;
453         }
454         dev->hw_desc[idx]->len2 = ctx->keylen;
455         dev->hw_desc[idx]->p2 = dev->key_phys_base;
456         dev->hw_desc[idx]->next = dev->hw_phys_desc[1];
457         dev->hw_desc[idx]->hdr = sahara_aes_key_hdr(dev);
458
459         idx++;
460
461
462         dev->nb_in_sg = sg_nents_for_len(dev->in_sg, dev->total);
463         if (dev->nb_in_sg < 0) {
464                 dev_err(dev->device, "Invalid numbers of src SG.\n");
465                 return dev->nb_in_sg;
466         }
467         dev->nb_out_sg = sg_nents_for_len(dev->out_sg, dev->total);
468         if (dev->nb_out_sg < 0) {
469                 dev_err(dev->device, "Invalid numbers of dst SG.\n");
470                 return dev->nb_out_sg;
471         }
472         if ((dev->nb_in_sg + dev->nb_out_sg) > SAHARA_MAX_HW_LINK) {
473                 dev_err(dev->device, "not enough hw links (%d)\n",
474                         dev->nb_in_sg + dev->nb_out_sg);
475                 return -EINVAL;
476         }
477
478         ret = dma_map_sg(dev->device, dev->in_sg, dev->nb_in_sg,
479                          DMA_TO_DEVICE);
480         if (!ret) {
481                 dev_err(dev->device, "couldn't map in sg\n");
482                 return -EINVAL;
483         }
484
485         ret = dma_map_sg(dev->device, dev->out_sg, dev->nb_out_sg,
486                          DMA_FROM_DEVICE);
487         if (!ret) {
488                 dev_err(dev->device, "couldn't map out sg\n");
489                 goto unmap_in;
490         }
491
492         /* Create input links */
493         dev->hw_desc[idx]->p1 = dev->hw_phys_link[0];
494         sg = dev->in_sg;
495         len = dev->total;
496         for (i = 0; i < dev->nb_in_sg; i++) {
497                 dev->hw_link[i]->len = min(len, sg->length);
498                 dev->hw_link[i]->p = sg->dma_address;
499                 if (i == (dev->nb_in_sg - 1)) {
500                         dev->hw_link[i]->next = 0;
501                 } else {
502                         len -= min(len, sg->length);
503                         dev->hw_link[i]->next = dev->hw_phys_link[i + 1];
504                         sg = sg_next(sg);
505                 }
506         }
507
508         /* Create output links */
509         dev->hw_desc[idx]->p2 = dev->hw_phys_link[i];
510         sg = dev->out_sg;
511         len = dev->total;
512         for (j = i; j < dev->nb_out_sg + i; j++) {
513                 dev->hw_link[j]->len = min(len, sg->length);
514                 dev->hw_link[j]->p = sg->dma_address;
515                 if (j == (dev->nb_out_sg + i - 1)) {
516                         dev->hw_link[j]->next = 0;
517                 } else {
518                         len -= min(len, sg->length);
519                         dev->hw_link[j]->next = dev->hw_phys_link[j + 1];
520                         sg = sg_next(sg);
521                 }
522         }
523
524         /* Fill remaining fields of hw_desc[1] */
525         dev->hw_desc[idx]->hdr = sahara_aes_data_link_hdr(dev);
526         dev->hw_desc[idx]->len1 = dev->total;
527         dev->hw_desc[idx]->len2 = dev->total;
528         dev->hw_desc[idx]->next = 0;
529
530         sahara_dump_descriptors(dev);
531         sahara_dump_links(dev);
532
533         sahara_write(dev, dev->hw_phys_desc[0], SAHARA_REG_DAR);
534
535         return 0;
536
537 unmap_in:
538         dma_unmap_sg(dev->device, dev->in_sg, dev->nb_in_sg,
539                 DMA_TO_DEVICE);
540
541         return -EINVAL;
542 }
543
544 static void sahara_aes_cbc_update_iv(struct skcipher_request *req)
545 {
546         struct crypto_skcipher *skcipher = crypto_skcipher_reqtfm(req);
547         struct sahara_aes_reqctx *rctx = skcipher_request_ctx(req);
548         unsigned int ivsize = crypto_skcipher_ivsize(skcipher);
549
550         /* Update IV buffer to contain the last ciphertext block */
551         if (rctx->mode & FLAGS_ENCRYPT) {
552                 sg_pcopy_to_buffer(req->dst, sg_nents(req->dst), req->iv,
553                                    ivsize, req->cryptlen - ivsize);
554         } else {
555                 memcpy(req->iv, rctx->iv_out, ivsize);
556         }
557 }
558
559 static int sahara_aes_process(struct skcipher_request *req)
560 {
561         struct crypto_skcipher *skcipher = crypto_skcipher_reqtfm(req);
562         struct sahara_dev *dev = dev_ptr;
563         struct sahara_ctx *ctx;
564         struct sahara_aes_reqctx *rctx;
565         int ret;
566         unsigned long timeout;
567
568         /* Request is ready to be dispatched by the device */
569         dev_dbg(dev->device,
570                 "dispatch request (nbytes=%d, src=%p, dst=%p)\n",
571                 req->cryptlen, req->src, req->dst);
572
573         /* assign new request to device */
574         dev->total = req->cryptlen;
575         dev->in_sg = req->src;
576         dev->out_sg = req->dst;
577
578         rctx = skcipher_request_ctx(req);
579         ctx = crypto_skcipher_ctx(crypto_skcipher_reqtfm(req));
580         rctx->mode &= FLAGS_MODE_MASK;
581         dev->flags = (dev->flags & ~FLAGS_MODE_MASK) | rctx->mode;
582
583         if ((dev->flags & FLAGS_CBC) && req->iv) {
584                 unsigned int ivsize = crypto_skcipher_ivsize(skcipher);
585
586                 memcpy(dev->iv_base, req->iv, ivsize);
587
588                 if (!(dev->flags & FLAGS_ENCRYPT)) {
589                         sg_pcopy_to_buffer(req->src, sg_nents(req->src),
590                                            rctx->iv_out, ivsize,
591                                            req->cryptlen - ivsize);
592                 }
593         }
594
595         /* assign new context to device */
596         dev->ctx = ctx;
597
598         reinit_completion(&dev->dma_completion);
599
600         ret = sahara_hw_descriptor_create(dev);
601         if (ret)
602                 return -EINVAL;
603
604         timeout = wait_for_completion_timeout(&dev->dma_completion,
605                                 msecs_to_jiffies(SAHARA_TIMEOUT_MS));
606
607         dma_unmap_sg(dev->device, dev->out_sg, dev->nb_out_sg,
608                 DMA_FROM_DEVICE);
609         dma_unmap_sg(dev->device, dev->in_sg, dev->nb_in_sg,
610                 DMA_TO_DEVICE);
611
612         if (!timeout) {
613                 dev_err(dev->device, "AES timeout\n");
614                 return -ETIMEDOUT;
615         }
616
617         if ((dev->flags & FLAGS_CBC) && req->iv)
618                 sahara_aes_cbc_update_iv(req);
619
620         return 0;
621 }
622
623 static int sahara_aes_setkey(struct crypto_skcipher *tfm, const u8 *key,
624                              unsigned int keylen)
625 {
626         struct sahara_ctx *ctx = crypto_skcipher_ctx(tfm);
627
628         ctx->keylen = keylen;
629
630         /* SAHARA only supports 128bit keys */
631         if (keylen == AES_KEYSIZE_128) {
632                 memcpy(ctx->key, key, keylen);
633                 return 0;
634         }
635
636         if (keylen != AES_KEYSIZE_192 && keylen != AES_KEYSIZE_256)
637                 return -EINVAL;
638
639         /*
640          * The requested key size is not supported by HW, do a fallback.
641          */
642         crypto_skcipher_clear_flags(ctx->fallback, CRYPTO_TFM_REQ_MASK);
643         crypto_skcipher_set_flags(ctx->fallback, tfm->base.crt_flags &
644                                                  CRYPTO_TFM_REQ_MASK);
645         return crypto_skcipher_setkey(ctx->fallback, key, keylen);
646 }
647
648 static int sahara_aes_fallback(struct skcipher_request *req, unsigned long mode)
649 {
650         struct sahara_aes_reqctx *rctx = skcipher_request_ctx(req);
651         struct sahara_ctx *ctx = crypto_skcipher_ctx(
652                 crypto_skcipher_reqtfm(req));
653
654         skcipher_request_set_tfm(&rctx->fallback_req, ctx->fallback);
655         skcipher_request_set_callback(&rctx->fallback_req,
656                                       req->base.flags,
657                                       req->base.complete,
658                                       req->base.data);
659         skcipher_request_set_crypt(&rctx->fallback_req, req->src,
660                                    req->dst, req->cryptlen, req->iv);
661
662         if (mode & FLAGS_ENCRYPT)
663                 return crypto_skcipher_encrypt(&rctx->fallback_req);
664
665         return crypto_skcipher_decrypt(&rctx->fallback_req);
666 }
667
668 static int sahara_aes_crypt(struct skcipher_request *req, unsigned long mode)
669 {
670         struct sahara_aes_reqctx *rctx = skcipher_request_ctx(req);
671         struct sahara_ctx *ctx = crypto_skcipher_ctx(
672                 crypto_skcipher_reqtfm(req));
673         struct sahara_dev *dev = dev_ptr;
674         int err = 0;
675
676         if (!req->cryptlen)
677                 return 0;
678
679         if (unlikely(ctx->keylen != AES_KEYSIZE_128))
680                 return sahara_aes_fallback(req, mode);
681
682         dev_dbg(dev->device, "nbytes: %d, enc: %d, cbc: %d\n",
683                 req->cryptlen, !!(mode & FLAGS_ENCRYPT), !!(mode & FLAGS_CBC));
684
685         if (!IS_ALIGNED(req->cryptlen, AES_BLOCK_SIZE)) {
686                 dev_err(dev->device,
687                         "request size is not exact amount of AES blocks\n");
688                 return -EINVAL;
689         }
690
691         rctx->mode = mode;
692
693         spin_lock_bh(&dev->queue_spinlock);
694         err = crypto_enqueue_request(&dev->queue, &req->base);
695         spin_unlock_bh(&dev->queue_spinlock);
696
697         wake_up_process(dev->kthread);
698
699         return err;
700 }
701
702 static int sahara_aes_ecb_encrypt(struct skcipher_request *req)
703 {
704         return sahara_aes_crypt(req, FLAGS_ENCRYPT);
705 }
706
707 static int sahara_aes_ecb_decrypt(struct skcipher_request *req)
708 {
709         return sahara_aes_crypt(req, 0);
710 }
711
712 static int sahara_aes_cbc_encrypt(struct skcipher_request *req)
713 {
714         return sahara_aes_crypt(req, FLAGS_ENCRYPT | FLAGS_CBC);
715 }
716
717 static int sahara_aes_cbc_decrypt(struct skcipher_request *req)
718 {
719         return sahara_aes_crypt(req, FLAGS_CBC);
720 }
721
722 static int sahara_aes_init_tfm(struct crypto_skcipher *tfm)
723 {
724         const char *name = crypto_tfm_alg_name(&tfm->base);
725         struct sahara_ctx *ctx = crypto_skcipher_ctx(tfm);
726
727         ctx->fallback = crypto_alloc_skcipher(name, 0,
728                                               CRYPTO_ALG_NEED_FALLBACK);
729         if (IS_ERR(ctx->fallback)) {
730                 pr_err("Error allocating fallback algo %s\n", name);
731                 return PTR_ERR(ctx->fallback);
732         }
733
734         crypto_skcipher_set_reqsize(tfm, sizeof(struct sahara_aes_reqctx) +
735                                          crypto_skcipher_reqsize(ctx->fallback));
736
737         return 0;
738 }
739
740 static void sahara_aes_exit_tfm(struct crypto_skcipher *tfm)
741 {
742         struct sahara_ctx *ctx = crypto_skcipher_ctx(tfm);
743
744         crypto_free_skcipher(ctx->fallback);
745 }
746
747 static u32 sahara_sha_init_hdr(struct sahara_dev *dev,
748                               struct sahara_sha_reqctx *rctx)
749 {
750         u32 hdr = 0;
751
752         hdr = rctx->mode;
753
754         if (rctx->first) {
755                 hdr |= SAHARA_HDR_MDHA_SET_MODE_HASH;
756                 hdr |= SAHARA_HDR_MDHA_INIT;
757         } else {
758                 hdr |= SAHARA_HDR_MDHA_SET_MODE_MD_KEY;
759         }
760
761         if (rctx->last)
762                 hdr |= SAHARA_HDR_MDHA_PDATA;
763
764         if (hweight_long(hdr) % 2 == 0)
765                 hdr |= SAHARA_HDR_PARITY_BIT;
766
767         return hdr;
768 }
769
770 static int sahara_sha_hw_links_create(struct sahara_dev *dev,
771                                        struct sahara_sha_reqctx *rctx,
772                                        int start)
773 {
774         struct scatterlist *sg;
775         unsigned int len;
776         unsigned int i;
777         int ret;
778
779         dev->in_sg = rctx->in_sg;
780
781         dev->nb_in_sg = sg_nents_for_len(dev->in_sg, rctx->total);
782         if (dev->nb_in_sg < 0) {
783                 dev_err(dev->device, "Invalid numbers of src SG.\n");
784                 return dev->nb_in_sg;
785         }
786         if ((dev->nb_in_sg) > SAHARA_MAX_HW_LINK) {
787                 dev_err(dev->device, "not enough hw links (%d)\n",
788                         dev->nb_in_sg + dev->nb_out_sg);
789                 return -EINVAL;
790         }
791
792         sg = dev->in_sg;
793         ret = dma_map_sg(dev->device, dev->in_sg, dev->nb_in_sg, DMA_TO_DEVICE);
794         if (!ret)
795                 return -EFAULT;
796
797         len = rctx->total;
798         for (i = start; i < dev->nb_in_sg + start; i++) {
799                 dev->hw_link[i]->len = min(len, sg->length);
800                 dev->hw_link[i]->p = sg->dma_address;
801                 if (i == (dev->nb_in_sg + start - 1)) {
802                         dev->hw_link[i]->next = 0;
803                 } else {
804                         len -= min(len, sg->length);
805                         dev->hw_link[i]->next = dev->hw_phys_link[i + 1];
806                         sg = sg_next(sg);
807                 }
808         }
809
810         return i;
811 }
812
813 static int sahara_sha_hw_data_descriptor_create(struct sahara_dev *dev,
814                                                 struct sahara_sha_reqctx *rctx,
815                                                 struct ahash_request *req,
816                                                 int index)
817 {
818         unsigned result_len;
819         int i = index;
820
821         if (rctx->first)
822                 /* Create initial descriptor: #8*/
823                 dev->hw_desc[index]->hdr = sahara_sha_init_hdr(dev, rctx);
824         else
825                 /* Create hash descriptor: #10. Must follow #6. */
826                 dev->hw_desc[index]->hdr = SAHARA_HDR_MDHA_HASH;
827
828         dev->hw_desc[index]->len1 = rctx->total;
829         if (dev->hw_desc[index]->len1 == 0) {
830                 /* if len1 is 0, p1 must be 0, too */
831                 dev->hw_desc[index]->p1 = 0;
832                 rctx->sg_in_idx = 0;
833         } else {
834                 /* Create input links */
835                 dev->hw_desc[index]->p1 = dev->hw_phys_link[index];
836                 i = sahara_sha_hw_links_create(dev, rctx, index);
837
838                 rctx->sg_in_idx = index;
839                 if (i < 0)
840                         return i;
841         }
842
843         dev->hw_desc[index]->p2 = dev->hw_phys_link[i];
844
845         /* Save the context for the next operation */
846         result_len = rctx->context_size;
847         dev->hw_link[i]->p = dev->context_phys_base;
848
849         dev->hw_link[i]->len = result_len;
850         dev->hw_desc[index]->len2 = result_len;
851
852         dev->hw_link[i]->next = 0;
853
854         return 0;
855 }
856
857 /*
858  * Load descriptor aka #6
859  *
860  * To load a previously saved context back to the MDHA unit
861  *
862  * p1: Saved Context
863  * p2: NULL
864  *
865  */
866 static int sahara_sha_hw_context_descriptor_create(struct sahara_dev *dev,
867                                                 struct sahara_sha_reqctx *rctx,
868                                                 struct ahash_request *req,
869                                                 int index)
870 {
871         dev->hw_desc[index]->hdr = sahara_sha_init_hdr(dev, rctx);
872
873         dev->hw_desc[index]->len1 = rctx->context_size;
874         dev->hw_desc[index]->p1 = dev->hw_phys_link[index];
875         dev->hw_desc[index]->len2 = 0;
876         dev->hw_desc[index]->p2 = 0;
877
878         dev->hw_link[index]->len = rctx->context_size;
879         dev->hw_link[index]->p = dev->context_phys_base;
880         dev->hw_link[index]->next = 0;
881
882         return 0;
883 }
884
885 static int sahara_sha_prepare_request(struct ahash_request *req)
886 {
887         struct crypto_ahash *tfm = crypto_ahash_reqtfm(req);
888         struct sahara_sha_reqctx *rctx = ahash_request_ctx(req);
889         unsigned int hash_later;
890         unsigned int block_size;
891         unsigned int len;
892
893         block_size = crypto_tfm_alg_blocksize(crypto_ahash_tfm(tfm));
894
895         /* append bytes from previous operation */
896         len = rctx->buf_cnt + req->nbytes;
897
898         /* only the last transfer can be padded in hardware */
899         if (!rctx->last && (len < block_size)) {
900                 /* to few data, save for next operation */
901                 scatterwalk_map_and_copy(rctx->buf + rctx->buf_cnt, req->src,
902                                          0, req->nbytes, 0);
903                 rctx->buf_cnt += req->nbytes;
904
905                 return 0;
906         }
907
908         /* add data from previous operation first */
909         if (rctx->buf_cnt)
910                 memcpy(rctx->rembuf, rctx->buf, rctx->buf_cnt);
911
912         /* data must always be a multiple of block_size */
913         hash_later = rctx->last ? 0 : len & (block_size - 1);
914         if (hash_later) {
915                 unsigned int offset = req->nbytes - hash_later;
916                 /* Save remaining bytes for later use */
917                 scatterwalk_map_and_copy(rctx->buf, req->src, offset,
918                                         hash_later, 0);
919         }
920
921         rctx->total = len - hash_later;
922         /* have data from previous operation and current */
923         if (rctx->buf_cnt && req->nbytes) {
924                 sg_init_table(rctx->in_sg_chain, 2);
925                 sg_set_buf(rctx->in_sg_chain, rctx->rembuf, rctx->buf_cnt);
926                 sg_chain(rctx->in_sg_chain, 2, req->src);
927                 rctx->in_sg = rctx->in_sg_chain;
928         /* only data from previous operation */
929         } else if (rctx->buf_cnt) {
930                 rctx->in_sg = rctx->in_sg_chain;
931                 sg_init_one(rctx->in_sg, rctx->rembuf, rctx->buf_cnt);
932         /* no data from previous operation */
933         } else {
934                 rctx->in_sg = req->src;
935         }
936
937         /* on next call, we only have the remaining data in the buffer */
938         rctx->buf_cnt = hash_later;
939
940         return -EINPROGRESS;
941 }
942
943 static int sahara_sha_process(struct ahash_request *req)
944 {
945         struct sahara_dev *dev = dev_ptr;
946         struct sahara_sha_reqctx *rctx = ahash_request_ctx(req);
947         int ret;
948         unsigned long timeout;
949
950         ret = sahara_sha_prepare_request(req);
951         if (!ret)
952                 return ret;
953
954         if (rctx->first) {
955                 ret = sahara_sha_hw_data_descriptor_create(dev, rctx, req, 0);
956                 if (ret)
957                         return ret;
958
959                 dev->hw_desc[0]->next = 0;
960                 rctx->first = 0;
961         } else {
962                 memcpy(dev->context_base, rctx->context, rctx->context_size);
963
964                 sahara_sha_hw_context_descriptor_create(dev, rctx, req, 0);
965                 dev->hw_desc[0]->next = dev->hw_phys_desc[1];
966                 ret = sahara_sha_hw_data_descriptor_create(dev, rctx, req, 1);
967                 if (ret)
968                         return ret;
969
970                 dev->hw_desc[1]->next = 0;
971         }
972
973         sahara_dump_descriptors(dev);
974         sahara_dump_links(dev);
975
976         reinit_completion(&dev->dma_completion);
977
978         sahara_write(dev, dev->hw_phys_desc[0], SAHARA_REG_DAR);
979
980         timeout = wait_for_completion_timeout(&dev->dma_completion,
981                                 msecs_to_jiffies(SAHARA_TIMEOUT_MS));
982
983         if (rctx->sg_in_idx)
984                 dma_unmap_sg(dev->device, dev->in_sg, dev->nb_in_sg,
985                              DMA_TO_DEVICE);
986
987         if (!timeout) {
988                 dev_err(dev->device, "SHA timeout\n");
989                 return -ETIMEDOUT;
990         }
991
992         memcpy(rctx->context, dev->context_base, rctx->context_size);
993
994         if (req->result && rctx->last)
995                 memcpy(req->result, rctx->context, rctx->digest_size);
996
997         return 0;
998 }
999
1000 static int sahara_queue_manage(void *data)
1001 {
1002         struct sahara_dev *dev = data;
1003         struct crypto_async_request *async_req;
1004         struct crypto_async_request *backlog;
1005         int ret = 0;
1006
1007         do {
1008                 __set_current_state(TASK_INTERRUPTIBLE);
1009
1010                 spin_lock_bh(&dev->queue_spinlock);
1011                 backlog = crypto_get_backlog(&dev->queue);
1012                 async_req = crypto_dequeue_request(&dev->queue);
1013                 spin_unlock_bh(&dev->queue_spinlock);
1014
1015                 if (backlog)
1016                         crypto_request_complete(backlog, -EINPROGRESS);
1017
1018                 if (async_req) {
1019                         if (crypto_tfm_alg_type(async_req->tfm) ==
1020                             CRYPTO_ALG_TYPE_AHASH) {
1021                                 struct ahash_request *req =
1022                                         ahash_request_cast(async_req);
1023
1024                                 ret = sahara_sha_process(req);
1025                         } else {
1026                                 struct skcipher_request *req =
1027                                         skcipher_request_cast(async_req);
1028
1029                                 ret = sahara_aes_process(req);
1030                         }
1031
1032                         crypto_request_complete(async_req, ret);
1033
1034                         continue;
1035                 }
1036
1037                 schedule();
1038         } while (!kthread_should_stop());
1039
1040         return 0;
1041 }
1042
1043 static int sahara_sha_enqueue(struct ahash_request *req, int last)
1044 {
1045         struct sahara_sha_reqctx *rctx = ahash_request_ctx(req);
1046         struct sahara_dev *dev = dev_ptr;
1047         int ret;
1048
1049         if (!req->nbytes && !last)
1050                 return 0;
1051
1052         rctx->last = last;
1053
1054         spin_lock_bh(&dev->queue_spinlock);
1055         ret = crypto_enqueue_request(&dev->queue, &req->base);
1056         spin_unlock_bh(&dev->queue_spinlock);
1057
1058         wake_up_process(dev->kthread);
1059
1060         return ret;
1061 }
1062
1063 static int sahara_sha_init(struct ahash_request *req)
1064 {
1065         struct crypto_ahash *tfm = crypto_ahash_reqtfm(req);
1066         struct sahara_sha_reqctx *rctx = ahash_request_ctx(req);
1067
1068         memset(rctx, 0, sizeof(*rctx));
1069
1070         switch (crypto_ahash_digestsize(tfm)) {
1071         case SHA1_DIGEST_SIZE:
1072                 rctx->mode |= SAHARA_HDR_MDHA_ALG_SHA1;
1073                 rctx->digest_size = SHA1_DIGEST_SIZE;
1074                 break;
1075         case SHA256_DIGEST_SIZE:
1076                 rctx->mode |= SAHARA_HDR_MDHA_ALG_SHA256;
1077                 rctx->digest_size = SHA256_DIGEST_SIZE;
1078                 break;
1079         default:
1080                 return -EINVAL;
1081         }
1082
1083         rctx->context_size = rctx->digest_size + 4;
1084         rctx->first = 1;
1085
1086         return 0;
1087 }
1088
1089 static int sahara_sha_update(struct ahash_request *req)
1090 {
1091         return sahara_sha_enqueue(req, 0);
1092 }
1093
1094 static int sahara_sha_final(struct ahash_request *req)
1095 {
1096         req->nbytes = 0;
1097         return sahara_sha_enqueue(req, 1);
1098 }
1099
1100 static int sahara_sha_finup(struct ahash_request *req)
1101 {
1102         return sahara_sha_enqueue(req, 1);
1103 }
1104
1105 static int sahara_sha_digest(struct ahash_request *req)
1106 {
1107         sahara_sha_init(req);
1108
1109         return sahara_sha_finup(req);
1110 }
1111
1112 static int sahara_sha_export(struct ahash_request *req, void *out)
1113 {
1114         struct sahara_sha_reqctx *rctx = ahash_request_ctx(req);
1115
1116         memcpy(out, rctx, sizeof(struct sahara_sha_reqctx));
1117
1118         return 0;
1119 }
1120
1121 static int sahara_sha_import(struct ahash_request *req, const void *in)
1122 {
1123         struct sahara_sha_reqctx *rctx = ahash_request_ctx(req);
1124
1125         memcpy(rctx, in, sizeof(struct sahara_sha_reqctx));
1126
1127         return 0;
1128 }
1129
1130 static int sahara_sha_cra_init(struct crypto_tfm *tfm)
1131 {
1132         crypto_ahash_set_reqsize(__crypto_ahash_cast(tfm),
1133                                  sizeof(struct sahara_sha_reqctx));
1134
1135         return 0;
1136 }
1137
1138 static struct skcipher_alg aes_algs[] = {
1139 {
1140         .base.cra_name          = "ecb(aes)",
1141         .base.cra_driver_name   = "sahara-ecb-aes",
1142         .base.cra_priority      = 300,
1143         .base.cra_flags         = CRYPTO_ALG_ASYNC | CRYPTO_ALG_NEED_FALLBACK,
1144         .base.cra_blocksize     = AES_BLOCK_SIZE,
1145         .base.cra_ctxsize       = sizeof(struct sahara_ctx),
1146         .base.cra_alignmask     = 0x0,
1147         .base.cra_module        = THIS_MODULE,
1148
1149         .init                   = sahara_aes_init_tfm,
1150         .exit                   = sahara_aes_exit_tfm,
1151         .min_keysize            = AES_MIN_KEY_SIZE ,
1152         .max_keysize            = AES_MAX_KEY_SIZE,
1153         .setkey                 = sahara_aes_setkey,
1154         .encrypt                = sahara_aes_ecb_encrypt,
1155         .decrypt                = sahara_aes_ecb_decrypt,
1156 }, {
1157         .base.cra_name          = "cbc(aes)",
1158         .base.cra_driver_name   = "sahara-cbc-aes",
1159         .base.cra_priority      = 300,
1160         .base.cra_flags         = CRYPTO_ALG_ASYNC | CRYPTO_ALG_NEED_FALLBACK,
1161         .base.cra_blocksize     = AES_BLOCK_SIZE,
1162         .base.cra_ctxsize       = sizeof(struct sahara_ctx),
1163         .base.cra_alignmask     = 0x0,
1164         .base.cra_module        = THIS_MODULE,
1165
1166         .init                   = sahara_aes_init_tfm,
1167         .exit                   = sahara_aes_exit_tfm,
1168         .min_keysize            = AES_MIN_KEY_SIZE ,
1169         .max_keysize            = AES_MAX_KEY_SIZE,
1170         .ivsize                 = AES_BLOCK_SIZE,
1171         .setkey                 = sahara_aes_setkey,
1172         .encrypt                = sahara_aes_cbc_encrypt,
1173         .decrypt                = sahara_aes_cbc_decrypt,
1174 }
1175 };
1176
1177 static struct ahash_alg sha_v3_algs[] = {
1178 {
1179         .init           = sahara_sha_init,
1180         .update         = sahara_sha_update,
1181         .final          = sahara_sha_final,
1182         .finup          = sahara_sha_finup,
1183         .digest         = sahara_sha_digest,
1184         .export         = sahara_sha_export,
1185         .import         = sahara_sha_import,
1186         .halg.digestsize        = SHA1_DIGEST_SIZE,
1187         .halg.statesize         = sizeof(struct sahara_sha_reqctx),
1188         .halg.base      = {
1189                 .cra_name               = "sha1",
1190                 .cra_driver_name        = "sahara-sha1",
1191                 .cra_priority           = 300,
1192                 .cra_flags              = CRYPTO_ALG_ASYNC |
1193                                                 CRYPTO_ALG_NEED_FALLBACK,
1194                 .cra_blocksize          = SHA1_BLOCK_SIZE,
1195                 .cra_ctxsize            = sizeof(struct sahara_ctx),
1196                 .cra_alignmask          = 0,
1197                 .cra_module             = THIS_MODULE,
1198                 .cra_init               = sahara_sha_cra_init,
1199         }
1200 },
1201 };
1202
1203 static struct ahash_alg sha_v4_algs[] = {
1204 {
1205         .init           = sahara_sha_init,
1206         .update         = sahara_sha_update,
1207         .final          = sahara_sha_final,
1208         .finup          = sahara_sha_finup,
1209         .digest         = sahara_sha_digest,
1210         .export         = sahara_sha_export,
1211         .import         = sahara_sha_import,
1212         .halg.digestsize        = SHA256_DIGEST_SIZE,
1213         .halg.statesize         = sizeof(struct sahara_sha_reqctx),
1214         .halg.base      = {
1215                 .cra_name               = "sha256",
1216                 .cra_driver_name        = "sahara-sha256",
1217                 .cra_priority           = 300,
1218                 .cra_flags              = CRYPTO_ALG_ASYNC |
1219                                                 CRYPTO_ALG_NEED_FALLBACK,
1220                 .cra_blocksize          = SHA256_BLOCK_SIZE,
1221                 .cra_ctxsize            = sizeof(struct sahara_ctx),
1222                 .cra_alignmask          = 0,
1223                 .cra_module             = THIS_MODULE,
1224                 .cra_init               = sahara_sha_cra_init,
1225         }
1226 },
1227 };
1228
1229 static irqreturn_t sahara_irq_handler(int irq, void *data)
1230 {
1231         struct sahara_dev *dev = data;
1232         unsigned int stat = sahara_read(dev, SAHARA_REG_STATUS);
1233         unsigned int err = sahara_read(dev, SAHARA_REG_ERRSTATUS);
1234
1235         sahara_write(dev, SAHARA_CMD_CLEAR_INT | SAHARA_CMD_CLEAR_ERR,
1236                      SAHARA_REG_CMD);
1237
1238         sahara_decode_status(dev, stat);
1239
1240         if (SAHARA_STATUS_GET_STATE(stat) == SAHARA_STATE_BUSY)
1241                 return IRQ_NONE;
1242
1243         if (SAHARA_STATUS_GET_STATE(stat) != SAHARA_STATE_COMPLETE)
1244                 sahara_decode_error(dev, err);
1245
1246         complete(&dev->dma_completion);
1247
1248         return IRQ_HANDLED;
1249 }
1250
1251
1252 static int sahara_register_algs(struct sahara_dev *dev)
1253 {
1254         int err;
1255         unsigned int i, j, k, l;
1256
1257         for (i = 0; i < ARRAY_SIZE(aes_algs); i++) {
1258                 err = crypto_register_skcipher(&aes_algs[i]);
1259                 if (err)
1260                         goto err_aes_algs;
1261         }
1262
1263         for (k = 0; k < ARRAY_SIZE(sha_v3_algs); k++) {
1264                 err = crypto_register_ahash(&sha_v3_algs[k]);
1265                 if (err)
1266                         goto err_sha_v3_algs;
1267         }
1268
1269         if (dev->version > SAHARA_VERSION_3)
1270                 for (l = 0; l < ARRAY_SIZE(sha_v4_algs); l++) {
1271                         err = crypto_register_ahash(&sha_v4_algs[l]);
1272                         if (err)
1273                                 goto err_sha_v4_algs;
1274                 }
1275
1276         return 0;
1277
1278 err_sha_v4_algs:
1279         for (j = 0; j < l; j++)
1280                 crypto_unregister_ahash(&sha_v4_algs[j]);
1281
1282 err_sha_v3_algs:
1283         for (j = 0; j < k; j++)
1284                 crypto_unregister_ahash(&sha_v3_algs[j]);
1285
1286 err_aes_algs:
1287         for (j = 0; j < i; j++)
1288                 crypto_unregister_skcipher(&aes_algs[j]);
1289
1290         return err;
1291 }
1292
1293 static void sahara_unregister_algs(struct sahara_dev *dev)
1294 {
1295         unsigned int i;
1296
1297         for (i = 0; i < ARRAY_SIZE(aes_algs); i++)
1298                 crypto_unregister_skcipher(&aes_algs[i]);
1299
1300         for (i = 0; i < ARRAY_SIZE(sha_v3_algs); i++)
1301                 crypto_unregister_ahash(&sha_v3_algs[i]);
1302
1303         if (dev->version > SAHARA_VERSION_3)
1304                 for (i = 0; i < ARRAY_SIZE(sha_v4_algs); i++)
1305                         crypto_unregister_ahash(&sha_v4_algs[i]);
1306 }
1307
1308 static const struct of_device_id sahara_dt_ids[] = {
1309         { .compatible = "fsl,imx53-sahara" },
1310         { .compatible = "fsl,imx27-sahara" },
1311         { /* sentinel */ }
1312 };
1313 MODULE_DEVICE_TABLE(of, sahara_dt_ids);
1314
1315 static int sahara_probe(struct platform_device *pdev)
1316 {
1317         struct sahara_dev *dev;
1318         u32 version;
1319         int irq;
1320         int err;
1321         int i;
1322
1323         dev = devm_kzalloc(&pdev->dev, sizeof(*dev), GFP_KERNEL);
1324         if (!dev)
1325                 return -ENOMEM;
1326
1327         dev->device = &pdev->dev;
1328         platform_set_drvdata(pdev, dev);
1329
1330         /* Get the base address */
1331         dev->regs_base = devm_platform_ioremap_resource(pdev, 0);
1332         if (IS_ERR(dev->regs_base))
1333                 return PTR_ERR(dev->regs_base);
1334
1335         /* Get the IRQ */
1336         irq = platform_get_irq(pdev,  0);
1337         if (irq < 0)
1338                 return irq;
1339
1340         err = devm_request_irq(&pdev->dev, irq, sahara_irq_handler,
1341                                0, dev_name(&pdev->dev), dev);
1342         if (err)
1343                 return dev_err_probe(&pdev->dev, err,
1344                                      "failed to request irq\n");
1345
1346         /* clocks */
1347         dev->clk_ipg = devm_clk_get_enabled(&pdev->dev, "ipg");
1348         if (IS_ERR(dev->clk_ipg))
1349                 return dev_err_probe(&pdev->dev, PTR_ERR(dev->clk_ipg),
1350                                      "Could not get ipg clock\n");
1351
1352         dev->clk_ahb = devm_clk_get_enabled(&pdev->dev, "ahb");
1353         if (IS_ERR(dev->clk_ahb))
1354                 return dev_err_probe(&pdev->dev, PTR_ERR(dev->clk_ahb),
1355                                      "Could not get ahb clock\n");
1356
1357         /* Allocate HW descriptors */
1358         dev->hw_desc[0] = dmam_alloc_coherent(&pdev->dev,
1359                         SAHARA_MAX_HW_DESC * sizeof(struct sahara_hw_desc),
1360                         &dev->hw_phys_desc[0], GFP_KERNEL);
1361         if (!dev->hw_desc[0])
1362                 return -ENOMEM;
1363         dev->hw_desc[1] = dev->hw_desc[0] + 1;
1364         dev->hw_phys_desc[1] = dev->hw_phys_desc[0] +
1365                                 sizeof(struct sahara_hw_desc);
1366
1367         /* Allocate space for iv and key */
1368         dev->key_base = dmam_alloc_coherent(&pdev->dev, 2 * AES_KEYSIZE_128,
1369                                 &dev->key_phys_base, GFP_KERNEL);
1370         if (!dev->key_base)
1371                 return -ENOMEM;
1372         dev->iv_base = dev->key_base + AES_KEYSIZE_128;
1373         dev->iv_phys_base = dev->key_phys_base + AES_KEYSIZE_128;
1374
1375         /* Allocate space for context: largest digest + message length field */
1376         dev->context_base = dmam_alloc_coherent(&pdev->dev,
1377                                         SHA256_DIGEST_SIZE + 4,
1378                                         &dev->context_phys_base, GFP_KERNEL);
1379         if (!dev->context_base)
1380                 return -ENOMEM;
1381
1382         /* Allocate space for HW links */
1383         dev->hw_link[0] = dmam_alloc_coherent(&pdev->dev,
1384                         SAHARA_MAX_HW_LINK * sizeof(struct sahara_hw_link),
1385                         &dev->hw_phys_link[0], GFP_KERNEL);
1386         if (!dev->hw_link[0])
1387                 return -ENOMEM;
1388         for (i = 1; i < SAHARA_MAX_HW_LINK; i++) {
1389                 dev->hw_phys_link[i] = dev->hw_phys_link[i - 1] +
1390                                         sizeof(struct sahara_hw_link);
1391                 dev->hw_link[i] = dev->hw_link[i - 1] + 1;
1392         }
1393
1394         crypto_init_queue(&dev->queue, SAHARA_QUEUE_LENGTH);
1395
1396         spin_lock_init(&dev->queue_spinlock);
1397
1398         dev_ptr = dev;
1399
1400         dev->kthread = kthread_run(sahara_queue_manage, dev, "sahara_crypto");
1401         if (IS_ERR(dev->kthread)) {
1402                 return PTR_ERR(dev->kthread);
1403         }
1404
1405         init_completion(&dev->dma_completion);
1406
1407         version = sahara_read(dev, SAHARA_REG_VERSION);
1408         if (of_device_is_compatible(pdev->dev.of_node, "fsl,imx27-sahara")) {
1409                 if (version != SAHARA_VERSION_3)
1410                         err = -ENODEV;
1411         } else if (of_device_is_compatible(pdev->dev.of_node,
1412                         "fsl,imx53-sahara")) {
1413                 if (((version >> 8) & 0xff) != SAHARA_VERSION_4)
1414                         err = -ENODEV;
1415                 version = (version >> 8) & 0xff;
1416         }
1417         if (err == -ENODEV) {
1418                 dev_err_probe(&pdev->dev, err,
1419                               "SAHARA version %d not supported\n", version);
1420                 goto err_algs;
1421         }
1422
1423         dev->version = version;
1424
1425         sahara_write(dev, SAHARA_CMD_RESET | SAHARA_CMD_MODE_BATCH,
1426                      SAHARA_REG_CMD);
1427         sahara_write(dev, SAHARA_CONTROL_SET_THROTTLE(0) |
1428                         SAHARA_CONTROL_SET_MAXBURST(8) |
1429                         SAHARA_CONTROL_RNG_AUTORSD |
1430                         SAHARA_CONTROL_ENABLE_INT,
1431                         SAHARA_REG_CONTROL);
1432
1433         err = sahara_register_algs(dev);
1434         if (err)
1435                 goto err_algs;
1436
1437         dev_info(&pdev->dev, "SAHARA version %d initialized\n", version);
1438
1439         return 0;
1440
1441 err_algs:
1442         kthread_stop(dev->kthread);
1443         dev_ptr = NULL;
1444
1445         return err;
1446 }
1447
1448 static void sahara_remove(struct platform_device *pdev)
1449 {
1450         struct sahara_dev *dev = platform_get_drvdata(pdev);
1451
1452         kthread_stop(dev->kthread);
1453
1454         sahara_unregister_algs(dev);
1455
1456         dev_ptr = NULL;
1457 }
1458
1459 static struct platform_driver sahara_driver = {
1460         .probe          = sahara_probe,
1461         .remove_new     = sahara_remove,
1462         .driver         = {
1463                 .name   = SAHARA_NAME,
1464                 .of_match_table = sahara_dt_ids,
1465         },
1466 };
1467
1468 module_platform_driver(sahara_driver);
1469
1470 MODULE_LICENSE("GPL");
1471 MODULE_AUTHOR("Javier Martin <javier.martin@vista-silicon.com>");
1472 MODULE_AUTHOR("Steffen Trumtrar <s.trumtrar@pengutronix.de>");
1473 MODULE_DESCRIPTION("SAHARA2 HW crypto accelerator");