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