GNU Linux-libre 5.4.241-gnu1
[releases.git] / drivers / crypto / mxs-dcp.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Freescale i.MX23/i.MX28 Data Co-Processor driver
4  *
5  * Copyright (C) 2013 Marek Vasut <marex@denx.de>
6  */
7
8 #include <linux/dma-mapping.h>
9 #include <linux/interrupt.h>
10 #include <linux/io.h>
11 #include <linux/kernel.h>
12 #include <linux/kthread.h>
13 #include <linux/module.h>
14 #include <linux/of.h>
15 #include <linux/platform_device.h>
16 #include <linux/stmp_device.h>
17 #include <linux/clk.h>
18
19 #include <crypto/aes.h>
20 #include <crypto/sha.h>
21 #include <crypto/internal/hash.h>
22 #include <crypto/internal/skcipher.h>
23 #include <crypto/scatterwalk.h>
24
25 #define DCP_MAX_CHANS   4
26 #define DCP_BUF_SZ      PAGE_SIZE
27 #define DCP_SHA_PAY_SZ  64
28
29 #define DCP_ALIGNMENT   64
30
31 /*
32  * Null hashes to align with hw behavior on imx6sl and ull
33  * these are flipped for consistency with hw output
34  */
35 static const uint8_t sha1_null_hash[] =
36         "\x09\x07\xd8\xaf\x90\x18\x60\x95\xef\xbf"
37         "\x55\x32\x0d\x4b\x6b\x5e\xee\xa3\x39\xda";
38
39 static const uint8_t sha256_null_hash[] =
40         "\x55\xb8\x52\x78\x1b\x99\x95\xa4"
41         "\x4c\x93\x9b\x64\xe4\x41\xae\x27"
42         "\x24\xb9\x6f\x99\xc8\xf4\xfb\x9a"
43         "\x14\x1c\xfc\x98\x42\xc4\xb0\xe3";
44
45 /* DCP DMA descriptor. */
46 struct dcp_dma_desc {
47         uint32_t        next_cmd_addr;
48         uint32_t        control0;
49         uint32_t        control1;
50         uint32_t        source;
51         uint32_t        destination;
52         uint32_t        size;
53         uint32_t        payload;
54         uint32_t        status;
55 };
56
57 /* Coherent aligned block for bounce buffering. */
58 struct dcp_coherent_block {
59         uint8_t                 aes_in_buf[DCP_BUF_SZ];
60         uint8_t                 aes_out_buf[DCP_BUF_SZ];
61         uint8_t                 sha_in_buf[DCP_BUF_SZ];
62         uint8_t                 sha_out_buf[DCP_SHA_PAY_SZ];
63
64         uint8_t                 aes_key[2 * AES_KEYSIZE_128];
65
66         struct dcp_dma_desc     desc[DCP_MAX_CHANS];
67 };
68
69 struct dcp {
70         struct device                   *dev;
71         void __iomem                    *base;
72
73         uint32_t                        caps;
74
75         struct dcp_coherent_block       *coh;
76
77         struct completion               completion[DCP_MAX_CHANS];
78         spinlock_t                      lock[DCP_MAX_CHANS];
79         struct task_struct              *thread[DCP_MAX_CHANS];
80         struct crypto_queue             queue[DCP_MAX_CHANS];
81         struct clk                      *dcp_clk;
82 };
83
84 enum dcp_chan {
85         DCP_CHAN_HASH_SHA       = 0,
86         DCP_CHAN_CRYPTO         = 2,
87 };
88
89 struct dcp_async_ctx {
90         /* Common context */
91         enum dcp_chan   chan;
92         uint32_t        fill;
93
94         /* SHA Hash-specific context */
95         struct mutex                    mutex;
96         uint32_t                        alg;
97         unsigned int                    hot:1;
98
99         /* Crypto-specific context */
100         struct crypto_sync_skcipher     *fallback;
101         unsigned int                    key_len;
102         uint8_t                         key[AES_KEYSIZE_128];
103 };
104
105 struct dcp_aes_req_ctx {
106         unsigned int    enc:1;
107         unsigned int    ecb:1;
108 };
109
110 struct dcp_sha_req_ctx {
111         unsigned int    init:1;
112         unsigned int    fini:1;
113 };
114
115 struct dcp_export_state {
116         struct dcp_sha_req_ctx req_ctx;
117         struct dcp_async_ctx async_ctx;
118 };
119
120 /*
121  * There can even be only one instance of the MXS DCP due to the
122  * design of Linux Crypto API.
123  */
124 static struct dcp *global_sdcp;
125
126 /* DCP register layout. */
127 #define MXS_DCP_CTRL                            0x00
128 #define MXS_DCP_CTRL_GATHER_RESIDUAL_WRITES     (1 << 23)
129 #define MXS_DCP_CTRL_ENABLE_CONTEXT_CACHING     (1 << 22)
130
131 #define MXS_DCP_STAT                            0x10
132 #define MXS_DCP_STAT_CLR                        0x18
133 #define MXS_DCP_STAT_IRQ_MASK                   0xf
134
135 #define MXS_DCP_CHANNELCTRL                     0x20
136 #define MXS_DCP_CHANNELCTRL_ENABLE_CHANNEL_MASK 0xff
137
138 #define MXS_DCP_CAPABILITY1                     0x40
139 #define MXS_DCP_CAPABILITY1_SHA256              (4 << 16)
140 #define MXS_DCP_CAPABILITY1_SHA1                (1 << 16)
141 #define MXS_DCP_CAPABILITY1_AES128              (1 << 0)
142
143 #define MXS_DCP_CONTEXT                         0x50
144
145 #define MXS_DCP_CH_N_CMDPTR(n)                  (0x100 + ((n) * 0x40))
146
147 #define MXS_DCP_CH_N_SEMA(n)                    (0x110 + ((n) * 0x40))
148
149 #define MXS_DCP_CH_N_STAT(n)                    (0x120 + ((n) * 0x40))
150 #define MXS_DCP_CH_N_STAT_CLR(n)                (0x128 + ((n) * 0x40))
151
152 /* DMA descriptor bits. */
153 #define MXS_DCP_CONTROL0_HASH_TERM              (1 << 13)
154 #define MXS_DCP_CONTROL0_HASH_INIT              (1 << 12)
155 #define MXS_DCP_CONTROL0_PAYLOAD_KEY            (1 << 11)
156 #define MXS_DCP_CONTROL0_CIPHER_ENCRYPT         (1 << 8)
157 #define MXS_DCP_CONTROL0_CIPHER_INIT            (1 << 9)
158 #define MXS_DCP_CONTROL0_ENABLE_HASH            (1 << 6)
159 #define MXS_DCP_CONTROL0_ENABLE_CIPHER          (1 << 5)
160 #define MXS_DCP_CONTROL0_DECR_SEMAPHORE         (1 << 1)
161 #define MXS_DCP_CONTROL0_INTERRUPT              (1 << 0)
162
163 #define MXS_DCP_CONTROL1_HASH_SELECT_SHA256     (2 << 16)
164 #define MXS_DCP_CONTROL1_HASH_SELECT_SHA1       (0 << 16)
165 #define MXS_DCP_CONTROL1_CIPHER_MODE_CBC        (1 << 4)
166 #define MXS_DCP_CONTROL1_CIPHER_MODE_ECB        (0 << 4)
167 #define MXS_DCP_CONTROL1_CIPHER_SELECT_AES128   (0 << 0)
168
169 static int mxs_dcp_start_dma(struct dcp_async_ctx *actx)
170 {
171         int dma_err;
172         struct dcp *sdcp = global_sdcp;
173         const int chan = actx->chan;
174         uint32_t stat;
175         unsigned long ret;
176         struct dcp_dma_desc *desc = &sdcp->coh->desc[actx->chan];
177         dma_addr_t desc_phys = dma_map_single(sdcp->dev, desc, sizeof(*desc),
178                                               DMA_TO_DEVICE);
179
180         dma_err = dma_mapping_error(sdcp->dev, desc_phys);
181         if (dma_err)
182                 return dma_err;
183
184         reinit_completion(&sdcp->completion[chan]);
185
186         /* Clear status register. */
187         writel(0xffffffff, sdcp->base + MXS_DCP_CH_N_STAT_CLR(chan));
188
189         /* Load the DMA descriptor. */
190         writel(desc_phys, sdcp->base + MXS_DCP_CH_N_CMDPTR(chan));
191
192         /* Increment the semaphore to start the DMA transfer. */
193         writel(1, sdcp->base + MXS_DCP_CH_N_SEMA(chan));
194
195         ret = wait_for_completion_timeout(&sdcp->completion[chan],
196                                           msecs_to_jiffies(1000));
197         if (!ret) {
198                 dev_err(sdcp->dev, "Channel %i timeout (DCP_STAT=0x%08x)\n",
199                         chan, readl(sdcp->base + MXS_DCP_STAT));
200                 return -ETIMEDOUT;
201         }
202
203         stat = readl(sdcp->base + MXS_DCP_CH_N_STAT(chan));
204         if (stat & 0xff) {
205                 dev_err(sdcp->dev, "Channel %i error (CH_STAT=0x%08x)\n",
206                         chan, stat);
207                 return -EINVAL;
208         }
209
210         dma_unmap_single(sdcp->dev, desc_phys, sizeof(*desc), DMA_TO_DEVICE);
211
212         return 0;
213 }
214
215 /*
216  * Encryption (AES128)
217  */
218 static int mxs_dcp_run_aes(struct dcp_async_ctx *actx,
219                            struct ablkcipher_request *req, int init)
220 {
221         dma_addr_t key_phys, src_phys, dst_phys;
222         struct dcp *sdcp = global_sdcp;
223         struct dcp_dma_desc *desc = &sdcp->coh->desc[actx->chan];
224         struct dcp_aes_req_ctx *rctx = ablkcipher_request_ctx(req);
225         int ret;
226
227         key_phys = dma_map_single(sdcp->dev, sdcp->coh->aes_key,
228                                   2 * AES_KEYSIZE_128, DMA_TO_DEVICE);
229         ret = dma_mapping_error(sdcp->dev, key_phys);
230         if (ret)
231                 return ret;
232
233         src_phys = dma_map_single(sdcp->dev, sdcp->coh->aes_in_buf,
234                                   DCP_BUF_SZ, DMA_TO_DEVICE);
235         ret = dma_mapping_error(sdcp->dev, src_phys);
236         if (ret)
237                 goto err_src;
238
239         dst_phys = dma_map_single(sdcp->dev, sdcp->coh->aes_out_buf,
240                                   DCP_BUF_SZ, DMA_FROM_DEVICE);
241         ret = dma_mapping_error(sdcp->dev, dst_phys);
242         if (ret)
243                 goto err_dst;
244
245         if (actx->fill % AES_BLOCK_SIZE) {
246                 dev_err(sdcp->dev, "Invalid block size!\n");
247                 ret = -EINVAL;
248                 goto aes_done_run;
249         }
250
251         /* Fill in the DMA descriptor. */
252         desc->control0 = MXS_DCP_CONTROL0_DECR_SEMAPHORE |
253                     MXS_DCP_CONTROL0_INTERRUPT |
254                     MXS_DCP_CONTROL0_ENABLE_CIPHER;
255
256         /* Payload contains the key. */
257         desc->control0 |= MXS_DCP_CONTROL0_PAYLOAD_KEY;
258
259         if (rctx->enc)
260                 desc->control0 |= MXS_DCP_CONTROL0_CIPHER_ENCRYPT;
261         if (init)
262                 desc->control0 |= MXS_DCP_CONTROL0_CIPHER_INIT;
263
264         desc->control1 = MXS_DCP_CONTROL1_CIPHER_SELECT_AES128;
265
266         if (rctx->ecb)
267                 desc->control1 |= MXS_DCP_CONTROL1_CIPHER_MODE_ECB;
268         else
269                 desc->control1 |= MXS_DCP_CONTROL1_CIPHER_MODE_CBC;
270
271         desc->next_cmd_addr = 0;
272         desc->source = src_phys;
273         desc->destination = dst_phys;
274         desc->size = actx->fill;
275         desc->payload = key_phys;
276         desc->status = 0;
277
278         ret = mxs_dcp_start_dma(actx);
279
280 aes_done_run:
281         dma_unmap_single(sdcp->dev, dst_phys, DCP_BUF_SZ, DMA_FROM_DEVICE);
282 err_dst:
283         dma_unmap_single(sdcp->dev, src_phys, DCP_BUF_SZ, DMA_TO_DEVICE);
284 err_src:
285         dma_unmap_single(sdcp->dev, key_phys, 2 * AES_KEYSIZE_128,
286                          DMA_TO_DEVICE);
287
288         return ret;
289 }
290
291 static int mxs_dcp_aes_block_crypt(struct crypto_async_request *arq)
292 {
293         struct dcp *sdcp = global_sdcp;
294
295         struct ablkcipher_request *req = ablkcipher_request_cast(arq);
296         struct dcp_async_ctx *actx = crypto_tfm_ctx(arq->tfm);
297         struct dcp_aes_req_ctx *rctx = ablkcipher_request_ctx(req);
298
299         struct scatterlist *dst = req->dst;
300         struct scatterlist *src = req->src;
301         int dst_nents = sg_nents(dst);
302
303         const int out_off = DCP_BUF_SZ;
304         uint8_t *in_buf = sdcp->coh->aes_in_buf;
305         uint8_t *out_buf = sdcp->coh->aes_out_buf;
306
307         uint32_t dst_off = 0;
308         uint8_t *src_buf = NULL;
309         uint32_t last_out_len = 0;
310
311         uint8_t *key = sdcp->coh->aes_key;
312
313         int ret = 0;
314         unsigned int i, len, clen, tlen = 0;
315         int init = 0;
316         bool limit_hit = false;
317
318         actx->fill = 0;
319
320         /* Copy the key from the temporary location. */
321         memcpy(key, actx->key, actx->key_len);
322
323         if (!rctx->ecb) {
324                 /* Copy the CBC IV just past the key. */
325                 memcpy(key + AES_KEYSIZE_128, req->info, AES_KEYSIZE_128);
326                 /* CBC needs the INIT set. */
327                 init = 1;
328         } else {
329                 memset(key + AES_KEYSIZE_128, 0, AES_KEYSIZE_128);
330         }
331
332         for_each_sg(req->src, src, sg_nents(req->src), i) {
333                 src_buf = sg_virt(src);
334                 len = sg_dma_len(src);
335                 tlen += len;
336                 limit_hit = tlen > req->nbytes;
337
338                 if (limit_hit)
339                         len = req->nbytes - (tlen - len);
340
341                 do {
342                         if (actx->fill + len > out_off)
343                                 clen = out_off - actx->fill;
344                         else
345                                 clen = len;
346
347                         memcpy(in_buf + actx->fill, src_buf, clen);
348                         len -= clen;
349                         src_buf += clen;
350                         actx->fill += clen;
351
352                         /*
353                          * If we filled the buffer or this is the last SG,
354                          * submit the buffer.
355                          */
356                         if (actx->fill == out_off || sg_is_last(src) ||
357                             limit_hit) {
358                                 ret = mxs_dcp_run_aes(actx, req, init);
359                                 if (ret)
360                                         return ret;
361                                 init = 0;
362
363                                 sg_pcopy_from_buffer(dst, dst_nents, out_buf,
364                                                      actx->fill, dst_off);
365                                 dst_off += actx->fill;
366                                 last_out_len = actx->fill;
367                                 actx->fill = 0;
368                         }
369                 } while (len);
370
371                 if (limit_hit)
372                         break;
373         }
374
375         /* Copy the IV for CBC for chaining */
376         if (!rctx->ecb) {
377                 if (rctx->enc)
378                         memcpy(req->info, out_buf+(last_out_len-AES_BLOCK_SIZE),
379                                 AES_BLOCK_SIZE);
380                 else
381                         memcpy(req->info, in_buf+(last_out_len-AES_BLOCK_SIZE),
382                                 AES_BLOCK_SIZE);
383         }
384
385         return ret;
386 }
387
388 static int dcp_chan_thread_aes(void *data)
389 {
390         struct dcp *sdcp = global_sdcp;
391         const int chan = DCP_CHAN_CRYPTO;
392
393         struct crypto_async_request *backlog;
394         struct crypto_async_request *arq;
395
396         int ret;
397
398         while (!kthread_should_stop()) {
399                 set_current_state(TASK_INTERRUPTIBLE);
400
401                 spin_lock(&sdcp->lock[chan]);
402                 backlog = crypto_get_backlog(&sdcp->queue[chan]);
403                 arq = crypto_dequeue_request(&sdcp->queue[chan]);
404                 spin_unlock(&sdcp->lock[chan]);
405
406                 if (!backlog && !arq) {
407                         schedule();
408                         continue;
409                 }
410
411                 set_current_state(TASK_RUNNING);
412
413                 if (backlog)
414                         backlog->complete(backlog, -EINPROGRESS);
415
416                 if (arq) {
417                         ret = mxs_dcp_aes_block_crypt(arq);
418                         arq->complete(arq, ret);
419                 }
420         }
421
422         return 0;
423 }
424
425 static int mxs_dcp_block_fallback(struct ablkcipher_request *req, int enc)
426 {
427         struct crypto_ablkcipher *tfm = crypto_ablkcipher_reqtfm(req);
428         struct dcp_async_ctx *ctx = crypto_ablkcipher_ctx(tfm);
429         SYNC_SKCIPHER_REQUEST_ON_STACK(subreq, ctx->fallback);
430         int ret;
431
432         skcipher_request_set_sync_tfm(subreq, ctx->fallback);
433         skcipher_request_set_callback(subreq, req->base.flags, NULL, NULL);
434         skcipher_request_set_crypt(subreq, req->src, req->dst,
435                                    req->nbytes, req->info);
436
437         if (enc)
438                 ret = crypto_skcipher_encrypt(subreq);
439         else
440                 ret = crypto_skcipher_decrypt(subreq);
441
442         skcipher_request_zero(subreq);
443
444         return ret;
445 }
446
447 static int mxs_dcp_aes_enqueue(struct ablkcipher_request *req, int enc, int ecb)
448 {
449         struct dcp *sdcp = global_sdcp;
450         struct crypto_async_request *arq = &req->base;
451         struct dcp_async_ctx *actx = crypto_tfm_ctx(arq->tfm);
452         struct dcp_aes_req_ctx *rctx = ablkcipher_request_ctx(req);
453         int ret;
454
455         if (unlikely(actx->key_len != AES_KEYSIZE_128))
456                 return mxs_dcp_block_fallback(req, enc);
457
458         rctx->enc = enc;
459         rctx->ecb = ecb;
460         actx->chan = DCP_CHAN_CRYPTO;
461
462         spin_lock(&sdcp->lock[actx->chan]);
463         ret = crypto_enqueue_request(&sdcp->queue[actx->chan], &req->base);
464         spin_unlock(&sdcp->lock[actx->chan]);
465
466         wake_up_process(sdcp->thread[actx->chan]);
467
468         return ret;
469 }
470
471 static int mxs_dcp_aes_ecb_decrypt(struct ablkcipher_request *req)
472 {
473         return mxs_dcp_aes_enqueue(req, 0, 1);
474 }
475
476 static int mxs_dcp_aes_ecb_encrypt(struct ablkcipher_request *req)
477 {
478         return mxs_dcp_aes_enqueue(req, 1, 1);
479 }
480
481 static int mxs_dcp_aes_cbc_decrypt(struct ablkcipher_request *req)
482 {
483         return mxs_dcp_aes_enqueue(req, 0, 0);
484 }
485
486 static int mxs_dcp_aes_cbc_encrypt(struct ablkcipher_request *req)
487 {
488         return mxs_dcp_aes_enqueue(req, 1, 0);
489 }
490
491 static int mxs_dcp_aes_setkey(struct crypto_ablkcipher *tfm, const u8 *key,
492                               unsigned int len)
493 {
494         struct dcp_async_ctx *actx = crypto_ablkcipher_ctx(tfm);
495         unsigned int ret;
496
497         /*
498          * AES 128 is supposed by the hardware, store key into temporary
499          * buffer and exit. We must use the temporary buffer here, since
500          * there can still be an operation in progress.
501          */
502         actx->key_len = len;
503         if (len == AES_KEYSIZE_128) {
504                 memcpy(actx->key, key, len);
505                 return 0;
506         }
507
508         /*
509          * If the requested AES key size is not supported by the hardware,
510          * but is supported by in-kernel software implementation, we use
511          * software fallback.
512          */
513         crypto_sync_skcipher_clear_flags(actx->fallback, CRYPTO_TFM_REQ_MASK);
514         crypto_sync_skcipher_set_flags(actx->fallback,
515                                   tfm->base.crt_flags & CRYPTO_TFM_REQ_MASK);
516
517         ret = crypto_sync_skcipher_setkey(actx->fallback, key, len);
518         if (!ret)
519                 return 0;
520
521         tfm->base.crt_flags &= ~CRYPTO_TFM_RES_MASK;
522         tfm->base.crt_flags |= crypto_sync_skcipher_get_flags(actx->fallback) &
523                                CRYPTO_TFM_RES_MASK;
524
525         return ret;
526 }
527
528 static int mxs_dcp_aes_fallback_init(struct crypto_tfm *tfm)
529 {
530         const char *name = crypto_tfm_alg_name(tfm);
531         struct dcp_async_ctx *actx = crypto_tfm_ctx(tfm);
532         struct crypto_sync_skcipher *blk;
533
534         blk = crypto_alloc_sync_skcipher(name, 0, CRYPTO_ALG_NEED_FALLBACK);
535         if (IS_ERR(blk))
536                 return PTR_ERR(blk);
537
538         actx->fallback = blk;
539         tfm->crt_ablkcipher.reqsize = sizeof(struct dcp_aes_req_ctx);
540         return 0;
541 }
542
543 static void mxs_dcp_aes_fallback_exit(struct crypto_tfm *tfm)
544 {
545         struct dcp_async_ctx *actx = crypto_tfm_ctx(tfm);
546
547         crypto_free_sync_skcipher(actx->fallback);
548 }
549
550 /*
551  * Hashing (SHA1/SHA256)
552  */
553 static int mxs_dcp_run_sha(struct ahash_request *req)
554 {
555         struct dcp *sdcp = global_sdcp;
556         int ret;
557
558         struct crypto_ahash *tfm = crypto_ahash_reqtfm(req);
559         struct dcp_async_ctx *actx = crypto_ahash_ctx(tfm);
560         struct dcp_sha_req_ctx *rctx = ahash_request_ctx(req);
561         struct dcp_dma_desc *desc = &sdcp->coh->desc[actx->chan];
562
563         dma_addr_t digest_phys = 0;
564         dma_addr_t buf_phys = dma_map_single(sdcp->dev, sdcp->coh->sha_in_buf,
565                                              DCP_BUF_SZ, DMA_TO_DEVICE);
566
567         ret = dma_mapping_error(sdcp->dev, buf_phys);
568         if (ret)
569                 return ret;
570
571         /* Fill in the DMA descriptor. */
572         desc->control0 = MXS_DCP_CONTROL0_DECR_SEMAPHORE |
573                     MXS_DCP_CONTROL0_INTERRUPT |
574                     MXS_DCP_CONTROL0_ENABLE_HASH;
575         if (rctx->init)
576                 desc->control0 |= MXS_DCP_CONTROL0_HASH_INIT;
577
578         desc->control1 = actx->alg;
579         desc->next_cmd_addr = 0;
580         desc->source = buf_phys;
581         desc->destination = 0;
582         desc->size = actx->fill;
583         desc->payload = 0;
584         desc->status = 0;
585
586         /*
587          * Align driver with hw behavior when generating null hashes
588          */
589         if (rctx->init && rctx->fini && desc->size == 0) {
590                 struct hash_alg_common *halg = crypto_hash_alg_common(tfm);
591                 const uint8_t *sha_buf =
592                         (actx->alg == MXS_DCP_CONTROL1_HASH_SELECT_SHA1) ?
593                         sha1_null_hash : sha256_null_hash;
594                 memcpy(sdcp->coh->sha_out_buf, sha_buf, halg->digestsize);
595                 ret = 0;
596                 goto done_run;
597         }
598
599         /* Set HASH_TERM bit for last transfer block. */
600         if (rctx->fini) {
601                 digest_phys = dma_map_single(sdcp->dev, sdcp->coh->sha_out_buf,
602                                              DCP_SHA_PAY_SZ, DMA_FROM_DEVICE);
603                 ret = dma_mapping_error(sdcp->dev, digest_phys);
604                 if (ret)
605                         goto done_run;
606
607                 desc->control0 |= MXS_DCP_CONTROL0_HASH_TERM;
608                 desc->payload = digest_phys;
609         }
610
611         ret = mxs_dcp_start_dma(actx);
612
613         if (rctx->fini)
614                 dma_unmap_single(sdcp->dev, digest_phys, DCP_SHA_PAY_SZ,
615                                  DMA_FROM_DEVICE);
616
617 done_run:
618         dma_unmap_single(sdcp->dev, buf_phys, DCP_BUF_SZ, DMA_TO_DEVICE);
619
620         return ret;
621 }
622
623 static int dcp_sha_req_to_buf(struct crypto_async_request *arq)
624 {
625         struct dcp *sdcp = global_sdcp;
626
627         struct ahash_request *req = ahash_request_cast(arq);
628         struct crypto_ahash *tfm = crypto_ahash_reqtfm(req);
629         struct dcp_async_ctx *actx = crypto_ahash_ctx(tfm);
630         struct dcp_sha_req_ctx *rctx = ahash_request_ctx(req);
631         struct hash_alg_common *halg = crypto_hash_alg_common(tfm);
632
633         uint8_t *in_buf = sdcp->coh->sha_in_buf;
634         uint8_t *out_buf = sdcp->coh->sha_out_buf;
635
636         struct scatterlist *src;
637
638         unsigned int i, len, clen, oft = 0;
639         int ret;
640
641         int fin = rctx->fini;
642         if (fin)
643                 rctx->fini = 0;
644
645         src = req->src;
646         len = req->nbytes;
647
648         while (len) {
649                 if (actx->fill + len > DCP_BUF_SZ)
650                         clen = DCP_BUF_SZ - actx->fill;
651                 else
652                         clen = len;
653
654                 scatterwalk_map_and_copy(in_buf + actx->fill, src, oft, clen,
655                                          0);
656
657                 len -= clen;
658                 oft += clen;
659                 actx->fill += clen;
660
661                 /*
662                  * If we filled the buffer and still have some
663                  * more data, submit the buffer.
664                  */
665                 if (len && actx->fill == DCP_BUF_SZ) {
666                         ret = mxs_dcp_run_sha(req);
667                         if (ret)
668                                 return ret;
669                         actx->fill = 0;
670                         rctx->init = 0;
671                 }
672         }
673
674         if (fin) {
675                 rctx->fini = 1;
676
677                 /* Submit whatever is left. */
678                 if (!req->result)
679                         return -EINVAL;
680
681                 ret = mxs_dcp_run_sha(req);
682                 if (ret)
683                         return ret;
684
685                 actx->fill = 0;
686
687                 /* For some reason the result is flipped */
688                 for (i = 0; i < halg->digestsize; i++)
689                         req->result[i] = out_buf[halg->digestsize - i - 1];
690         }
691
692         return 0;
693 }
694
695 static int dcp_chan_thread_sha(void *data)
696 {
697         struct dcp *sdcp = global_sdcp;
698         const int chan = DCP_CHAN_HASH_SHA;
699
700         struct crypto_async_request *backlog;
701         struct crypto_async_request *arq;
702         int ret;
703
704         while (!kthread_should_stop()) {
705                 set_current_state(TASK_INTERRUPTIBLE);
706
707                 spin_lock(&sdcp->lock[chan]);
708                 backlog = crypto_get_backlog(&sdcp->queue[chan]);
709                 arq = crypto_dequeue_request(&sdcp->queue[chan]);
710                 spin_unlock(&sdcp->lock[chan]);
711
712                 if (!backlog && !arq) {
713                         schedule();
714                         continue;
715                 }
716
717                 set_current_state(TASK_RUNNING);
718
719                 if (backlog)
720                         backlog->complete(backlog, -EINPROGRESS);
721
722                 if (arq) {
723                         ret = dcp_sha_req_to_buf(arq);
724                         arq->complete(arq, ret);
725                 }
726         }
727
728         return 0;
729 }
730
731 static int dcp_sha_init(struct ahash_request *req)
732 {
733         struct crypto_ahash *tfm = crypto_ahash_reqtfm(req);
734         struct dcp_async_ctx *actx = crypto_ahash_ctx(tfm);
735
736         struct hash_alg_common *halg = crypto_hash_alg_common(tfm);
737
738         /*
739          * Start hashing session. The code below only inits the
740          * hashing session context, nothing more.
741          */
742         memset(actx, 0, sizeof(*actx));
743
744         if (strcmp(halg->base.cra_name, "sha1") == 0)
745                 actx->alg = MXS_DCP_CONTROL1_HASH_SELECT_SHA1;
746         else
747                 actx->alg = MXS_DCP_CONTROL1_HASH_SELECT_SHA256;
748
749         actx->fill = 0;
750         actx->hot = 0;
751         actx->chan = DCP_CHAN_HASH_SHA;
752
753         mutex_init(&actx->mutex);
754
755         return 0;
756 }
757
758 static int dcp_sha_update_fx(struct ahash_request *req, int fini)
759 {
760         struct dcp *sdcp = global_sdcp;
761
762         struct dcp_sha_req_ctx *rctx = ahash_request_ctx(req);
763         struct crypto_ahash *tfm = crypto_ahash_reqtfm(req);
764         struct dcp_async_ctx *actx = crypto_ahash_ctx(tfm);
765
766         int ret;
767
768         /*
769          * Ignore requests that have no data in them and are not
770          * the trailing requests in the stream of requests.
771          */
772         if (!req->nbytes && !fini)
773                 return 0;
774
775         mutex_lock(&actx->mutex);
776
777         rctx->fini = fini;
778
779         if (!actx->hot) {
780                 actx->hot = 1;
781                 rctx->init = 1;
782         }
783
784         spin_lock(&sdcp->lock[actx->chan]);
785         ret = crypto_enqueue_request(&sdcp->queue[actx->chan], &req->base);
786         spin_unlock(&sdcp->lock[actx->chan]);
787
788         wake_up_process(sdcp->thread[actx->chan]);
789         mutex_unlock(&actx->mutex);
790
791         return ret;
792 }
793
794 static int dcp_sha_update(struct ahash_request *req)
795 {
796         return dcp_sha_update_fx(req, 0);
797 }
798
799 static int dcp_sha_final(struct ahash_request *req)
800 {
801         ahash_request_set_crypt(req, NULL, req->result, 0);
802         req->nbytes = 0;
803         return dcp_sha_update_fx(req, 1);
804 }
805
806 static int dcp_sha_finup(struct ahash_request *req)
807 {
808         return dcp_sha_update_fx(req, 1);
809 }
810
811 static int dcp_sha_digest(struct ahash_request *req)
812 {
813         int ret;
814
815         ret = dcp_sha_init(req);
816         if (ret)
817                 return ret;
818
819         return dcp_sha_finup(req);
820 }
821
822 static int dcp_sha_import(struct ahash_request *req, const void *in)
823 {
824         struct dcp_sha_req_ctx *rctx = ahash_request_ctx(req);
825         struct crypto_ahash *tfm = crypto_ahash_reqtfm(req);
826         struct dcp_async_ctx *actx = crypto_ahash_ctx(tfm);
827         const struct dcp_export_state *export = in;
828
829         memset(rctx, 0, sizeof(struct dcp_sha_req_ctx));
830         memset(actx, 0, sizeof(struct dcp_async_ctx));
831         memcpy(rctx, &export->req_ctx, sizeof(struct dcp_sha_req_ctx));
832         memcpy(actx, &export->async_ctx, sizeof(struct dcp_async_ctx));
833
834         return 0;
835 }
836
837 static int dcp_sha_export(struct ahash_request *req, void *out)
838 {
839         struct dcp_sha_req_ctx *rctx_state = ahash_request_ctx(req);
840         struct crypto_ahash *tfm = crypto_ahash_reqtfm(req);
841         struct dcp_async_ctx *actx_state = crypto_ahash_ctx(tfm);
842         struct dcp_export_state *export = out;
843
844         memcpy(&export->req_ctx, rctx_state, sizeof(struct dcp_sha_req_ctx));
845         memcpy(&export->async_ctx, actx_state, sizeof(struct dcp_async_ctx));
846
847         return 0;
848 }
849
850 static int dcp_sha_cra_init(struct crypto_tfm *tfm)
851 {
852         crypto_ahash_set_reqsize(__crypto_ahash_cast(tfm),
853                                  sizeof(struct dcp_sha_req_ctx));
854         return 0;
855 }
856
857 static void dcp_sha_cra_exit(struct crypto_tfm *tfm)
858 {
859 }
860
861 /* AES 128 ECB and AES 128 CBC */
862 static struct crypto_alg dcp_aes_algs[] = {
863         {
864                 .cra_name               = "ecb(aes)",
865                 .cra_driver_name        = "ecb-aes-dcp",
866                 .cra_priority           = 400,
867                 .cra_alignmask          = 15,
868                 .cra_flags              = CRYPTO_ALG_TYPE_ABLKCIPHER |
869                                           CRYPTO_ALG_ASYNC |
870                                           CRYPTO_ALG_NEED_FALLBACK,
871                 .cra_init               = mxs_dcp_aes_fallback_init,
872                 .cra_exit               = mxs_dcp_aes_fallback_exit,
873                 .cra_blocksize          = AES_BLOCK_SIZE,
874                 .cra_ctxsize            = sizeof(struct dcp_async_ctx),
875                 .cra_type               = &crypto_ablkcipher_type,
876                 .cra_module             = THIS_MODULE,
877                 .cra_u  = {
878                         .ablkcipher = {
879                                 .min_keysize    = AES_MIN_KEY_SIZE,
880                                 .max_keysize    = AES_MAX_KEY_SIZE,
881                                 .setkey         = mxs_dcp_aes_setkey,
882                                 .encrypt        = mxs_dcp_aes_ecb_encrypt,
883                                 .decrypt        = mxs_dcp_aes_ecb_decrypt
884                         },
885                 },
886         }, {
887                 .cra_name               = "cbc(aes)",
888                 .cra_driver_name        = "cbc-aes-dcp",
889                 .cra_priority           = 400,
890                 .cra_alignmask          = 15,
891                 .cra_flags              = CRYPTO_ALG_TYPE_ABLKCIPHER |
892                                           CRYPTO_ALG_ASYNC |
893                                           CRYPTO_ALG_NEED_FALLBACK,
894                 .cra_init               = mxs_dcp_aes_fallback_init,
895                 .cra_exit               = mxs_dcp_aes_fallback_exit,
896                 .cra_blocksize          = AES_BLOCK_SIZE,
897                 .cra_ctxsize            = sizeof(struct dcp_async_ctx),
898                 .cra_type               = &crypto_ablkcipher_type,
899                 .cra_module             = THIS_MODULE,
900                 .cra_u = {
901                         .ablkcipher = {
902                                 .min_keysize    = AES_MIN_KEY_SIZE,
903                                 .max_keysize    = AES_MAX_KEY_SIZE,
904                                 .setkey         = mxs_dcp_aes_setkey,
905                                 .encrypt        = mxs_dcp_aes_cbc_encrypt,
906                                 .decrypt        = mxs_dcp_aes_cbc_decrypt,
907                                 .ivsize         = AES_BLOCK_SIZE,
908                         },
909                 },
910         },
911 };
912
913 /* SHA1 */
914 static struct ahash_alg dcp_sha1_alg = {
915         .init   = dcp_sha_init,
916         .update = dcp_sha_update,
917         .final  = dcp_sha_final,
918         .finup  = dcp_sha_finup,
919         .digest = dcp_sha_digest,
920         .import = dcp_sha_import,
921         .export = dcp_sha_export,
922         .halg   = {
923                 .digestsize     = SHA1_DIGEST_SIZE,
924                 .statesize      = sizeof(struct dcp_export_state),
925                 .base           = {
926                         .cra_name               = "sha1",
927                         .cra_driver_name        = "sha1-dcp",
928                         .cra_priority           = 400,
929                         .cra_alignmask          = 63,
930                         .cra_flags              = CRYPTO_ALG_ASYNC,
931                         .cra_blocksize          = SHA1_BLOCK_SIZE,
932                         .cra_ctxsize            = sizeof(struct dcp_async_ctx),
933                         .cra_module             = THIS_MODULE,
934                         .cra_init               = dcp_sha_cra_init,
935                         .cra_exit               = dcp_sha_cra_exit,
936                 },
937         },
938 };
939
940 /* SHA256 */
941 static struct ahash_alg dcp_sha256_alg = {
942         .init   = dcp_sha_init,
943         .update = dcp_sha_update,
944         .final  = dcp_sha_final,
945         .finup  = dcp_sha_finup,
946         .digest = dcp_sha_digest,
947         .import = dcp_sha_import,
948         .export = dcp_sha_export,
949         .halg   = {
950                 .digestsize     = SHA256_DIGEST_SIZE,
951                 .statesize      = sizeof(struct dcp_export_state),
952                 .base           = {
953                         .cra_name               = "sha256",
954                         .cra_driver_name        = "sha256-dcp",
955                         .cra_priority           = 400,
956                         .cra_alignmask          = 63,
957                         .cra_flags              = CRYPTO_ALG_ASYNC,
958                         .cra_blocksize          = SHA256_BLOCK_SIZE,
959                         .cra_ctxsize            = sizeof(struct dcp_async_ctx),
960                         .cra_module             = THIS_MODULE,
961                         .cra_init               = dcp_sha_cra_init,
962                         .cra_exit               = dcp_sha_cra_exit,
963                 },
964         },
965 };
966
967 static irqreturn_t mxs_dcp_irq(int irq, void *context)
968 {
969         struct dcp *sdcp = context;
970         uint32_t stat;
971         int i;
972
973         stat = readl(sdcp->base + MXS_DCP_STAT);
974         stat &= MXS_DCP_STAT_IRQ_MASK;
975         if (!stat)
976                 return IRQ_NONE;
977
978         /* Clear the interrupts. */
979         writel(stat, sdcp->base + MXS_DCP_STAT_CLR);
980
981         /* Complete the DMA requests that finished. */
982         for (i = 0; i < DCP_MAX_CHANS; i++)
983                 if (stat & (1 << i))
984                         complete(&sdcp->completion[i]);
985
986         return IRQ_HANDLED;
987 }
988
989 static int mxs_dcp_probe(struct platform_device *pdev)
990 {
991         struct device *dev = &pdev->dev;
992         struct dcp *sdcp = NULL;
993         int i, ret;
994         int dcp_vmi_irq, dcp_irq;
995
996         if (global_sdcp) {
997                 dev_err(dev, "Only one DCP instance allowed!\n");
998                 return -ENODEV;
999         }
1000
1001         dcp_vmi_irq = platform_get_irq(pdev, 0);
1002         if (dcp_vmi_irq < 0)
1003                 return dcp_vmi_irq;
1004
1005         dcp_irq = platform_get_irq(pdev, 1);
1006         if (dcp_irq < 0)
1007                 return dcp_irq;
1008
1009         sdcp = devm_kzalloc(dev, sizeof(*sdcp), GFP_KERNEL);
1010         if (!sdcp)
1011                 return -ENOMEM;
1012
1013         sdcp->dev = dev;
1014         sdcp->base = devm_platform_ioremap_resource(pdev, 0);
1015         if (IS_ERR(sdcp->base))
1016                 return PTR_ERR(sdcp->base);
1017
1018
1019         ret = devm_request_irq(dev, dcp_vmi_irq, mxs_dcp_irq, 0,
1020                                "dcp-vmi-irq", sdcp);
1021         if (ret) {
1022                 dev_err(dev, "Failed to claim DCP VMI IRQ!\n");
1023                 return ret;
1024         }
1025
1026         ret = devm_request_irq(dev, dcp_irq, mxs_dcp_irq, 0,
1027                                "dcp-irq", sdcp);
1028         if (ret) {
1029                 dev_err(dev, "Failed to claim DCP IRQ!\n");
1030                 return ret;
1031         }
1032
1033         /* Allocate coherent helper block. */
1034         sdcp->coh = devm_kzalloc(dev, sizeof(*sdcp->coh) + DCP_ALIGNMENT,
1035                                    GFP_KERNEL);
1036         if (!sdcp->coh)
1037                 return -ENOMEM;
1038
1039         /* Re-align the structure so it fits the DCP constraints. */
1040         sdcp->coh = PTR_ALIGN(sdcp->coh, DCP_ALIGNMENT);
1041
1042         /* DCP clock is optional, only used on some SOCs */
1043         sdcp->dcp_clk = devm_clk_get(dev, "dcp");
1044         if (IS_ERR(sdcp->dcp_clk)) {
1045                 if (sdcp->dcp_clk != ERR_PTR(-ENOENT))
1046                         return PTR_ERR(sdcp->dcp_clk);
1047                 sdcp->dcp_clk = NULL;
1048         }
1049         ret = clk_prepare_enable(sdcp->dcp_clk);
1050         if (ret)
1051                 return ret;
1052
1053         /* Restart the DCP block. */
1054         ret = stmp_reset_block(sdcp->base);
1055         if (ret) {
1056                 dev_err(dev, "Failed reset\n");
1057                 goto err_disable_unprepare_clk;
1058         }
1059
1060         /* Initialize control register. */
1061         writel(MXS_DCP_CTRL_GATHER_RESIDUAL_WRITES |
1062                MXS_DCP_CTRL_ENABLE_CONTEXT_CACHING | 0xf,
1063                sdcp->base + MXS_DCP_CTRL);
1064
1065         /* Enable all DCP DMA channels. */
1066         writel(MXS_DCP_CHANNELCTRL_ENABLE_CHANNEL_MASK,
1067                sdcp->base + MXS_DCP_CHANNELCTRL);
1068
1069         /*
1070          * We do not enable context switching. Give the context buffer a
1071          * pointer to an illegal address so if context switching is
1072          * inadvertantly enabled, the DCP will return an error instead of
1073          * trashing good memory. The DCP DMA cannot access ROM, so any ROM
1074          * address will do.
1075          */
1076         writel(0xffff0000, sdcp->base + MXS_DCP_CONTEXT);
1077         for (i = 0; i < DCP_MAX_CHANS; i++)
1078                 writel(0xffffffff, sdcp->base + MXS_DCP_CH_N_STAT_CLR(i));
1079         writel(0xffffffff, sdcp->base + MXS_DCP_STAT_CLR);
1080
1081         global_sdcp = sdcp;
1082
1083         platform_set_drvdata(pdev, sdcp);
1084
1085         for (i = 0; i < DCP_MAX_CHANS; i++) {
1086                 spin_lock_init(&sdcp->lock[i]);
1087                 init_completion(&sdcp->completion[i]);
1088                 crypto_init_queue(&sdcp->queue[i], 50);
1089         }
1090
1091         /* Create the SHA and AES handler threads. */
1092         sdcp->thread[DCP_CHAN_HASH_SHA] = kthread_run(dcp_chan_thread_sha,
1093                                                       NULL, "mxs_dcp_chan/sha");
1094         if (IS_ERR(sdcp->thread[DCP_CHAN_HASH_SHA])) {
1095                 dev_err(dev, "Error starting SHA thread!\n");
1096                 ret = PTR_ERR(sdcp->thread[DCP_CHAN_HASH_SHA]);
1097                 goto err_disable_unprepare_clk;
1098         }
1099
1100         sdcp->thread[DCP_CHAN_CRYPTO] = kthread_run(dcp_chan_thread_aes,
1101                                                     NULL, "mxs_dcp_chan/aes");
1102         if (IS_ERR(sdcp->thread[DCP_CHAN_CRYPTO])) {
1103                 dev_err(dev, "Error starting SHA thread!\n");
1104                 ret = PTR_ERR(sdcp->thread[DCP_CHAN_CRYPTO]);
1105                 goto err_destroy_sha_thread;
1106         }
1107
1108         /* Register the various crypto algorithms. */
1109         sdcp->caps = readl(sdcp->base + MXS_DCP_CAPABILITY1);
1110
1111         if (sdcp->caps & MXS_DCP_CAPABILITY1_AES128) {
1112                 ret = crypto_register_algs(dcp_aes_algs,
1113                                            ARRAY_SIZE(dcp_aes_algs));
1114                 if (ret) {
1115                         /* Failed to register algorithm. */
1116                         dev_err(dev, "Failed to register AES crypto!\n");
1117                         goto err_destroy_aes_thread;
1118                 }
1119         }
1120
1121         if (sdcp->caps & MXS_DCP_CAPABILITY1_SHA1) {
1122                 ret = crypto_register_ahash(&dcp_sha1_alg);
1123                 if (ret) {
1124                         dev_err(dev, "Failed to register %s hash!\n",
1125                                 dcp_sha1_alg.halg.base.cra_name);
1126                         goto err_unregister_aes;
1127                 }
1128         }
1129
1130         if (sdcp->caps & MXS_DCP_CAPABILITY1_SHA256) {
1131                 ret = crypto_register_ahash(&dcp_sha256_alg);
1132                 if (ret) {
1133                         dev_err(dev, "Failed to register %s hash!\n",
1134                                 dcp_sha256_alg.halg.base.cra_name);
1135                         goto err_unregister_sha1;
1136                 }
1137         }
1138
1139         return 0;
1140
1141 err_unregister_sha1:
1142         if (sdcp->caps & MXS_DCP_CAPABILITY1_SHA1)
1143                 crypto_unregister_ahash(&dcp_sha1_alg);
1144
1145 err_unregister_aes:
1146         if (sdcp->caps & MXS_DCP_CAPABILITY1_AES128)
1147                 crypto_unregister_algs(dcp_aes_algs, ARRAY_SIZE(dcp_aes_algs));
1148
1149 err_destroy_aes_thread:
1150         kthread_stop(sdcp->thread[DCP_CHAN_CRYPTO]);
1151
1152 err_destroy_sha_thread:
1153         kthread_stop(sdcp->thread[DCP_CHAN_HASH_SHA]);
1154
1155 err_disable_unprepare_clk:
1156         clk_disable_unprepare(sdcp->dcp_clk);
1157
1158         return ret;
1159 }
1160
1161 static int mxs_dcp_remove(struct platform_device *pdev)
1162 {
1163         struct dcp *sdcp = platform_get_drvdata(pdev);
1164
1165         if (sdcp->caps & MXS_DCP_CAPABILITY1_SHA256)
1166                 crypto_unregister_ahash(&dcp_sha256_alg);
1167
1168         if (sdcp->caps & MXS_DCP_CAPABILITY1_SHA1)
1169                 crypto_unregister_ahash(&dcp_sha1_alg);
1170
1171         if (sdcp->caps & MXS_DCP_CAPABILITY1_AES128)
1172                 crypto_unregister_algs(dcp_aes_algs, ARRAY_SIZE(dcp_aes_algs));
1173
1174         kthread_stop(sdcp->thread[DCP_CHAN_HASH_SHA]);
1175         kthread_stop(sdcp->thread[DCP_CHAN_CRYPTO]);
1176
1177         clk_disable_unprepare(sdcp->dcp_clk);
1178
1179         platform_set_drvdata(pdev, NULL);
1180
1181         global_sdcp = NULL;
1182
1183         return 0;
1184 }
1185
1186 static const struct of_device_id mxs_dcp_dt_ids[] = {
1187         { .compatible = "fsl,imx23-dcp", .data = NULL, },
1188         { .compatible = "fsl,imx28-dcp", .data = NULL, },
1189         { /* sentinel */ }
1190 };
1191
1192 MODULE_DEVICE_TABLE(of, mxs_dcp_dt_ids);
1193
1194 static struct platform_driver mxs_dcp_driver = {
1195         .probe  = mxs_dcp_probe,
1196         .remove = mxs_dcp_remove,
1197         .driver = {
1198                 .name           = "mxs-dcp",
1199                 .of_match_table = mxs_dcp_dt_ids,
1200         },
1201 };
1202
1203 module_platform_driver(mxs_dcp_driver);
1204
1205 MODULE_AUTHOR("Marek Vasut <marex@denx.de>");
1206 MODULE_DESCRIPTION("Freescale MXS DCP Driver");
1207 MODULE_LICENSE("GPL");
1208 MODULE_ALIAS("platform:mxs-dcp");