temp revert rk change
[firefly-linux-kernel-4.4.55.git] / drivers / crypto / tegra-aes.c
1 /*
2  * drivers/crypto/tegra-aes.c
3  *
4  * aes driver for NVIDIA tegra aes hardware
5  *
6  * Copyright (c) 2010, NVIDIA Corporation.
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful, but WITHOUT
14  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
15  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
16  * more details.
17  *
18  * You should have received a copy of the GNU General Public License along
19  * with this program; if not, write to the Free Software Foundation, Inc.,
20  * 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21  */
22
23 #include <linux/module.h>
24 #include <linux/init.h>
25 #include <linux/errno.h>
26 #include <linux/kernel.h>
27 #include <linux/clk.h>
28 #include <linux/platform_device.h>
29 #include <linux/scatterlist.h>
30 #include <linux/dma-mapping.h>
31 #include <linux/io.h>
32 #include <linux/mutex.h>
33 #include <linux/interrupt.h>
34 #include <linux/completion.h>
35 #include <linux/workqueue.h>
36
37 #include <mach/arb_sema.h>
38 #include <mach/clk.h>
39
40 #include <crypto/scatterwalk.h>
41 #include <crypto/aes.h>
42 #include <crypto/internal/rng.h>
43
44 #include "tegra-aes.h"
45
46 #define FLAGS_MODE_MASK         0x000f
47 #define FLAGS_ENCRYPT           BIT(0)
48 #define FLAGS_CBC               BIT(1)
49 #define FLAGS_GIV               BIT(2)
50 #define FLAGS_RNG               BIT(3)
51 #define FLAGS_NEW_KEY           BIT(4)
52 #define FLAGS_NEW_IV            BIT(5)
53 #define FLAGS_INIT              BIT(6)
54 #define FLAGS_FAST              BIT(7)
55 #define FLAGS_BUSY              8
56
57 /*
58  * Defines AES engine Max process bytes size in one go, which takes 1 msec.
59  * AES engine spends about 176 cycles/16-bytes or 11 cycles/byte
60  * The duration CPU can use the BSE to 1 msec, then the number of available
61  * cycles of AVP/BSE is 216K. In this duration, AES can process 216/11 ~= 19KB
62  * Based on this AES_HW_DMA_BUFFER_SIZE_BYTES is configured to 16KB.
63  */
64 #define AES_HW_DMA_BUFFER_SIZE_BYTES 0x4000
65
66 /*
67  * The key table length is 64 bytes
68  * (This includes first upto 32 bytes key + 16 bytes original initial vector
69  * and 16 bytes updated initial vector)
70  */
71 #define AES_HW_KEY_TABLE_LENGTH_BYTES 64
72
73 #define AES_HW_IV_SIZE 16
74 #define AES_HW_KEYSCHEDULE_LEN 256
75 #define ARB_SEMA_TIMEOUT 500
76
77 /*
78  * The memory being used is divides as follows:
79  * 1. Key - 32 bytes
80  * 2. Original IV - 16 bytes
81  * 3. Updated IV - 16 bytes
82  * 4. Key schedule - 256 bytes
83  *
84  * 1+2+3 constitute the hw key table.
85  */
86 #define AES_IVKEY_SIZE (AES_HW_KEY_TABLE_LENGTH_BYTES + AES_HW_KEYSCHEDULE_LEN)
87
88 #define DEFAULT_RNG_BLK_SZ 16
89
90 /* As of now only 5 commands are USED for AES encryption/Decryption */
91 #define AES_HW_MAX_ICQ_LENGTH 5
92
93 #define ICQBITSHIFT_BLKCNT 0
94
95 /* memdma_vd command */
96 #define MEMDMA_DIR_DTOVRAM      0
97 #define MEMDMA_DIR_VTODRAM      1
98 #define MEMDMABITSHIFT_DIR      25
99 #define MEMDMABITSHIFT_NUM_WORDS        12
100
101 /* Define AES Interactive command Queue commands Bit positions */
102 enum {
103         ICQBITSHIFT_KEYTABLEADDR = 0,
104         ICQBITSHIFT_KEYTABLEID = 17,
105         ICQBITSHIFT_VRAMSEL = 23,
106         ICQBITSHIFT_TABLESEL = 24,
107         ICQBITSHIFT_OPCODE = 26,
108 };
109
110 /* Define Ucq opcodes required for AES operation */
111 enum {
112         UCQOPCODE_BLKSTARTENGINE = 0x0E,
113         UCQOPCODE_DMASETUP = 0x10,
114         UCQOPCODE_DMACOMPLETE = 0x11,
115         UCQOPCODE_SETTABLE = 0x15,
116         UCQOPCODE_MEMDMAVD = 0x22,
117 };
118
119 /* Define Aes command values */
120 enum {
121         UCQCMD_VRAM_SEL = 0x1,
122         UCQCMD_CRYPTO_TABLESEL = 0x3,
123         UCQCMD_KEYSCHEDTABLESEL = 0x4,
124         UCQCMD_KEYTABLESEL = 0x8,
125 };
126
127 #define UCQCMD_KEYTABLEADDRMASK 0x1FFFF
128
129 #define AES_NR_KEYSLOTS 8
130 #define SSK_SLOT_NUM    4
131
132 struct tegra_aes_slot {
133         struct list_head node;
134         int slot_num;
135         bool available;
136 };
137
138 static struct tegra_aes_slot ssk = {
139         .slot_num = SSK_SLOT_NUM,
140         .available = true,
141 };
142
143 struct tegra_aes_reqctx {
144         unsigned long mode;
145 };
146
147 #define TEGRA_AES_QUEUE_LENGTH 50
148
149 struct tegra_aes_dev {
150         struct device *dev;
151         unsigned long phys_base;
152         void __iomem *io_base;
153         dma_addr_t ivkey_phys_base;
154         void __iomem *ivkey_base;
155         struct clk *iclk;
156         struct clk *pclk;
157         struct tegra_aes_ctx *ctx;
158         unsigned long flags;
159         struct completion op_complete;
160         u32 *buf_in;
161         dma_addr_t dma_buf_in;
162         u32 *buf_out;
163         dma_addr_t dma_buf_out;
164         u8 *iv;
165         u8 dt[DEFAULT_RNG_BLK_SZ];
166         int ivlen;
167         u64 ctr;
168         int res_id;
169         spinlock_t lock;
170         struct crypto_queue queue;
171         struct tegra_aes_slot *slots;
172         struct ablkcipher_request *req;
173         size_t total;
174         struct scatterlist *in_sg;
175         size_t in_offset;
176         struct scatterlist *out_sg;
177         size_t out_offset;
178 };
179
180 static struct tegra_aes_dev *aes_dev;
181
182 struct tegra_aes_ctx {
183         struct tegra_aes_dev *dd;
184         unsigned long flags;
185         struct tegra_aes_slot *slot;
186         int keylen;
187 };
188
189 static struct tegra_aes_ctx rng_ctx = {
190         .flags = FLAGS_NEW_KEY,
191         .keylen = AES_KEYSIZE_128,
192 };
193
194 /* keep registered devices data here */
195 static LIST_HEAD(dev_list);
196 static DEFINE_SPINLOCK(list_lock);
197 static DEFINE_MUTEX(aes_lock);
198
199 static void aes_workqueue_handler(struct work_struct *work);
200 static DECLARE_WORK(aes_work, aes_workqueue_handler);
201 static struct workqueue_struct *aes_wq;
202
203 extern unsigned long long tegra_chip_uid(void);
204
205 static inline u32 aes_readl(struct tegra_aes_dev *dd, u32 offset)
206 {
207         return readl(dd->io_base + offset);
208 }
209
210 static inline void aes_writel(struct tegra_aes_dev *dd, u32 val, u32 offset)
211 {
212         writel(val, dd->io_base + offset);
213 }
214
215 static int aes_hw_init(struct tegra_aes_dev *dd)
216 {
217         int ret = 0;
218
219         ret = clk_enable(dd->pclk);
220         if (ret < 0) {
221                 dev_err(dd->dev, "%s: pclock enable fail(%d)\n", __func__, ret);
222                 return ret;
223         }
224
225         ret = clk_enable(dd->iclk);
226         if (ret < 0) {
227                 dev_err(dd->dev, "%s: iclock enable fail(%d)\n", __func__, ret);
228                 clk_disable(dd->pclk);
229                 return ret;
230         }
231
232         ret = clk_set_rate(dd->iclk, 240000000);
233         if (ret) {
234                 dev_err(dd->dev, "%s: iclk set_rate fail(%d)\n", __func__, ret);
235                 clk_disable(dd->iclk);
236                 clk_disable(dd->pclk);
237                 return ret;
238         }
239
240         aes_writel(dd, 0x33, INT_ENB);
241         return ret;
242 }
243
244 static void aes_hw_deinit(struct tegra_aes_dev *dd)
245 {
246         clk_disable(dd->iclk);
247         clk_disable(dd->pclk);
248 }
249
250 static int aes_start_crypt(struct tegra_aes_dev *dd, u32 in_addr, u32 out_addr,
251         int nblocks, int mode, bool upd_iv)
252 {
253         u32 cmdq[AES_HW_MAX_ICQ_LENGTH];
254         int qlen = 0, i, eng_busy, icq_empty, dma_busy, ret = 0;
255         u32 value;
256
257         cmdq[qlen++] = UCQOPCODE_DMASETUP << ICQBITSHIFT_OPCODE;
258         cmdq[qlen++] = in_addr;
259         cmdq[qlen++] = UCQOPCODE_BLKSTARTENGINE << ICQBITSHIFT_OPCODE |
260                 (nblocks-1) << ICQBITSHIFT_BLKCNT;
261         cmdq[qlen++] = UCQOPCODE_DMACOMPLETE << ICQBITSHIFT_OPCODE;
262
263         value = aes_readl(dd, CMDQUE_CONTROL);
264         /* access SDRAM through AHB */
265         value &= ~CMDQ_CTRL_SRC_STM_SEL_FIELD;
266         value &= ~CMDQ_CTRL_DST_STM_SEL_FIELD;
267         value |= (CMDQ_CTRL_SRC_STM_SEL_FIELD | CMDQ_CTRL_DST_STM_SEL_FIELD |
268                 CMDQ_CTRL_ICMDQEN_FIELD);
269         aes_writel(dd, value, CMDQUE_CONTROL);
270         dev_dbg(dd->dev, "cmd_q_ctrl=0x%x", value);
271
272         value = 0;
273         value |= CONFIG_ENDIAN_ENB_FIELD;
274         aes_writel(dd, value, CONFIG);
275         dev_dbg(dd->dev, "config=0x%x", value);
276
277         value = aes_readl(dd, SECURE_CONFIG_EXT);
278         value &= ~SECURE_OFFSET_CNT_FIELD;
279         aes_writel(dd, value, SECURE_CONFIG_EXT);
280         dev_dbg(dd->dev, "secure_cfg_xt=0x%x", value);
281
282         if (mode & FLAGS_CBC) {
283                 value = ((0x1 << SECURE_INPUT_ALG_SEL_SHIFT) |
284                         ((dd->ctx->keylen * 8) << SECURE_INPUT_KEY_LEN_SHIFT) |
285                         ((u32)upd_iv << SECURE_IV_SELECT_SHIFT) |
286                         (((mode & FLAGS_ENCRYPT) ? 2 : 3)
287                                 << SECURE_XOR_POS_SHIFT) |
288                         (0 << SECURE_INPUT_SEL_SHIFT) |
289                         (((mode & FLAGS_ENCRYPT) ? 2 : 3)
290                                 << SECURE_VCTRAM_SEL_SHIFT) |
291                         ((mode & FLAGS_ENCRYPT) ? 1 : 0)
292                                 << SECURE_CORE_SEL_SHIFT |
293                         (0 << SECURE_RNG_ENB_SHIFT) |
294                         (0 << SECURE_HASH_ENB_SHIFT));
295         } else if (mode & FLAGS_RNG){
296                 value = ((0x1 << SECURE_INPUT_ALG_SEL_SHIFT) |
297                         ((dd->ctx->keylen * 8) << SECURE_INPUT_KEY_LEN_SHIFT) |
298                         ((u32)upd_iv << SECURE_IV_SELECT_SHIFT) |
299                         (0 << SECURE_XOR_POS_SHIFT) |
300                         (0 << SECURE_INPUT_SEL_SHIFT) |
301                         ((mode & FLAGS_ENCRYPT) ? 1 : 0)
302                                 << SECURE_CORE_SEL_SHIFT |
303                         (1 << SECURE_RNG_ENB_SHIFT) |
304                         (0 << SECURE_HASH_ENB_SHIFT));
305         } else {
306                 value = ((0x1 << SECURE_INPUT_ALG_SEL_SHIFT) |
307                         ((dd->ctx->keylen * 8) << SECURE_INPUT_KEY_LEN_SHIFT) |
308                         ((u32)upd_iv << SECURE_IV_SELECT_SHIFT) |
309                         (0 << SECURE_XOR_POS_SHIFT) |
310                         (0 << SECURE_INPUT_SEL_SHIFT) |
311                         (((mode & FLAGS_ENCRYPT) ? 1 : 0)
312                                 << SECURE_CORE_SEL_SHIFT) |
313                         (0 << SECURE_RNG_ENB_SHIFT) |
314                                 (0 << SECURE_HASH_ENB_SHIFT));
315         }
316         dev_dbg(dd->dev, "secure_in_sel=0x%x", value);
317         aes_writel(dd, value, SECURE_INPUT_SELECT);
318
319         aes_writel(dd, out_addr, SECURE_DEST_ADDR);
320         INIT_COMPLETION(dd->op_complete);
321
322         for (i = 0; i < qlen - 1; i++) {
323                 do {
324                         value = aes_readl(dd, INTR_STATUS);
325                         eng_busy = value & (0x1);
326                         icq_empty = value & (0x1<<3);
327                         dma_busy = value & (0x1<<23);
328                 } while (eng_busy & (!icq_empty) & dma_busy);
329                 aes_writel(dd, cmdq[i], ICMDQUE_WR);
330         }
331
332         ret = wait_for_completion_timeout(&dd->op_complete, msecs_to_jiffies(150));
333         if (ret == 0) {
334                 dev_err(dd->dev, "timed out (0x%x)\n",
335                         aes_readl(dd, INTR_STATUS));
336                 return -ETIMEDOUT;
337         }
338
339         aes_writel(dd, cmdq[qlen - 1], ICMDQUE_WR);
340         return 0;
341 }
342
343 static void aes_release_key_slot(struct tegra_aes_dev *dd)
344 {
345         spin_lock(&list_lock);
346         dd->ctx->slot->available = true;
347         dd->ctx->slot = NULL;
348         spin_unlock(&list_lock);
349 }
350
351 static struct tegra_aes_slot *aes_find_key_slot(struct tegra_aes_dev *dd)
352 {
353         struct tegra_aes_slot *slot = NULL;
354         bool found = false;
355
356         spin_lock(&list_lock);
357         list_for_each_entry(slot, &dev_list, node) {
358                 dev_dbg(dd->dev, "empty:%d, num:%d\n", slot->available,
359                         slot->slot_num);
360                 if (slot->available) {
361                         slot->available = false;
362                         found = true;
363                         break;
364                 }
365         }
366         spin_unlock(&list_lock);
367         return found ? slot : NULL;
368 }
369
370 static int aes_set_key(struct tegra_aes_dev *dd)
371 {
372         u32 value, cmdq[2];
373         struct tegra_aes_ctx *ctx = dd->ctx;
374         int i, eng_busy, icq_empty, dma_busy;
375         bool use_ssk = false;
376
377         if (!ctx) {
378                 dev_err(dd->dev, "%s: context invalid\n", __func__);
379                 return -EINVAL;
380         }
381
382         /* use ssk? */
383         if (!dd->ctx->slot) {
384                 dev_dbg(dd->dev, "using ssk");
385                 dd->ctx->slot = &ssk;
386                 use_ssk = true;
387         }
388
389         /* disable key read from hw */
390         value = aes_readl(dd, SECURE_SEC_SEL0+(ctx->slot->slot_num*4));
391         value &= ~SECURE_SEL0_KEYREAD_ENB0_FIELD;
392         aes_writel(dd, value, SECURE_SEC_SEL0+(ctx->slot->slot_num*4));
393
394         /* enable key schedule generation in hardware */
395         value = aes_readl(dd, SECURE_CONFIG_EXT);
396         value &= ~SECURE_KEY_SCH_DIS_FIELD;
397         aes_writel(dd, value, SECURE_CONFIG_EXT);
398
399         /* select the key slot */
400         value = aes_readl(dd, SECURE_CONFIG);
401         value &= ~SECURE_KEY_INDEX_FIELD;
402         value |= (ctx->slot->slot_num << SECURE_KEY_INDEX_SHIFT);
403         aes_writel(dd, value, SECURE_CONFIG);
404
405         if (use_ssk)
406                 goto out;
407
408         /* copy the key table from sdram to vram */
409         cmdq[0] = 0;
410         cmdq[0] = UCQOPCODE_MEMDMAVD << ICQBITSHIFT_OPCODE |
411                 (MEMDMA_DIR_DTOVRAM << MEMDMABITSHIFT_DIR) |
412                 (AES_HW_KEY_TABLE_LENGTH_BYTES/sizeof(u32))
413                         << MEMDMABITSHIFT_NUM_WORDS;
414         cmdq[1] = (u32)dd->ivkey_phys_base;
415
416         for (i = 0; i < ARRAY_SIZE(cmdq); i++)
417                 aes_writel(dd, cmdq[i], ICMDQUE_WR);
418
419         do {
420                 value = aes_readl(dd, INTR_STATUS);
421                 eng_busy = value & (0x1);
422                 icq_empty = value & (0x1<<3);
423                 dma_busy = value & (0x1<<23);
424         } while (eng_busy & (!icq_empty) & dma_busy);
425
426         /* settable command to get key into internal registers */
427         value = 0;
428         value = UCQOPCODE_SETTABLE << ICQBITSHIFT_OPCODE |
429                 UCQCMD_CRYPTO_TABLESEL << ICQBITSHIFT_TABLESEL |
430                 UCQCMD_VRAM_SEL << ICQBITSHIFT_VRAMSEL |
431                 (UCQCMD_KEYTABLESEL | ctx->slot->slot_num)
432                         << ICQBITSHIFT_KEYTABLEID;
433         aes_writel(dd, value, ICMDQUE_WR);
434         do {
435                 value = aes_readl(dd, INTR_STATUS);
436                 eng_busy = value & (0x1);
437                 icq_empty = value & (0x1<<3);
438         } while (eng_busy & (!icq_empty));
439
440 out:
441         return 0;
442 }
443
444 static int tegra_aes_handle_req(struct tegra_aes_dev *dd)
445 {
446         struct crypto_async_request *async_req, *backlog;
447         struct tegra_aes_ctx *ctx;
448         struct tegra_aes_reqctx *rctx;
449         struct ablkcipher_request *req;
450         unsigned long flags;
451         int dma_max = AES_HW_DMA_BUFFER_SIZE_BYTES;
452         int ret = 0, nblocks, total;
453         int count = 0;
454         dma_addr_t addr_in, addr_out;
455         struct scatterlist *in_sg, *out_sg;
456
457         if (!dd)
458                 return -EINVAL;
459
460         spin_lock_irqsave(&dd->lock, flags);
461         backlog = crypto_get_backlog(&dd->queue);
462         async_req = crypto_dequeue_request(&dd->queue);
463         if (!async_req)
464                 clear_bit(FLAGS_BUSY, &dd->flags);
465         spin_unlock_irqrestore(&dd->lock, flags);
466
467         if (!async_req)
468                 return -ENODATA;
469
470         if (backlog)
471                 backlog->complete(backlog, -EINPROGRESS);
472
473         req = ablkcipher_request_cast(async_req);
474
475         dev_dbg(dd->dev, "%s: get new req\n", __func__);
476
477         /* take mutex to access the aes hw */
478         mutex_lock(&aes_lock);
479
480         /* assign new request to device */
481         dd->req = req;
482         dd->total = req->nbytes;
483         dd->in_offset = 0;
484         dd->in_sg = req->src;
485         dd->out_offset = 0;
486         dd->out_sg = req->dst;
487
488         in_sg = dd->in_sg;
489         out_sg = dd->out_sg;
490
491         if (!in_sg || !out_sg) {
492                 mutex_unlock(&aes_lock);
493                 return -EINVAL;
494         }
495
496         total = dd->total;
497         rctx = ablkcipher_request_ctx(req);
498         ctx = crypto_ablkcipher_ctx(crypto_ablkcipher_reqtfm(req));
499         rctx->mode &= FLAGS_MODE_MASK;
500         dd->flags = (dd->flags & ~FLAGS_MODE_MASK) | rctx->mode;
501
502         dd->iv = (u8 *)req->info;
503         dd->ivlen = AES_BLOCK_SIZE;
504
505         if ((dd->flags & FLAGS_CBC) && dd->iv)
506                 dd->flags |= FLAGS_NEW_IV;
507         else
508                 dd->flags &= ~FLAGS_NEW_IV;
509
510         ctx->dd = dd;
511         if (dd->ctx != ctx) {
512                 /* assign new context to device */
513                 dd->ctx = ctx;
514                 ctx->flags |= FLAGS_NEW_KEY;
515         }
516
517         /* take the hardware semaphore */
518         if (tegra_arb_mutex_lock_timeout(dd->res_id, ARB_SEMA_TIMEOUT) < 0) {
519                 dev_err(dd->dev, "aes hardware not available\n");
520                 mutex_unlock(&aes_lock);
521                 return -EBUSY;
522         }
523
524         ret = aes_hw_init(dd);
525         if (ret < 0) {
526                 dev_err(dd->dev, "%s: hw init fail(%d)\n", __func__, ret);
527                 goto fail;
528         }
529
530         aes_set_key(dd);
531
532         /* set iv to the aes hw slot */
533         memset(dd->buf_in, 0 , AES_BLOCK_SIZE);
534         memcpy(dd->buf_in, dd->iv, dd->ivlen);
535
536         ret = aes_start_crypt(dd, (u32)dd->dma_buf_in,
537           (u32)dd->dma_buf_out, 1, FLAGS_CBC, false);
538         if (ret < 0) {
539                 dev_err(dd->dev, "aes_start_crypt fail(%d)\n", ret);
540                 goto out;
541         }
542
543         while (total) {
544                 dev_dbg(dd->dev, "remain: 0x%x\n", total);
545
546                 ret = dma_map_sg(dd->dev, in_sg, 1, DMA_TO_DEVICE);
547                 if (!ret) {
548                         dev_err(dd->dev, "dma_map_sg() error\n");
549                         goto out;
550                 }
551
552                 ret = dma_map_sg(dd->dev, out_sg, 1, DMA_FROM_DEVICE);
553                 if (!ret) {
554                                 dev_err(dd->dev, "dma_map_sg() error\n");
555                                 dma_unmap_sg(dd->dev, dd->in_sg,
556                                         1, DMA_TO_DEVICE);
557                                 goto out;
558                         }
559
560                 addr_in = sg_dma_address(in_sg);
561                 addr_out = sg_dma_address(out_sg);
562                 dd->flags |= FLAGS_FAST;
563                 count = min((int)sg_dma_len(in_sg), (int)dma_max);
564                 WARN_ON(sg_dma_len(in_sg) != sg_dma_len(out_sg));
565                 nblocks = DIV_ROUND_UP(count, AES_BLOCK_SIZE);
566
567                 ret = aes_start_crypt(dd, addr_in, addr_out, nblocks,
568                         dd->flags, true);
569
570                 dma_unmap_sg(dd->dev, out_sg, 1, DMA_FROM_DEVICE);
571                 dma_unmap_sg(dd->dev, in_sg, 1, DMA_TO_DEVICE);
572
573                 if (ret < 0) {
574                         dev_err(dd->dev, "aes_start_crypt fail(%d)\n", ret);
575                         goto out;
576                 }
577                 dd->flags &= ~FLAGS_FAST;
578
579                 dev_dbg(dd->dev, "out: copied 0x%x\n", count);
580                 total -= count;
581                 in_sg = sg_next(in_sg);
582                 out_sg = sg_next(out_sg);
583                 WARN_ON(((total != 0) && (!in_sg || !out_sg)));
584         }
585
586 out:
587         aes_hw_deinit(dd);
588
589 fail:
590         /* release the hardware semaphore */
591         tegra_arb_mutex_unlock(dd->res_id);
592
593         dd->total = total;
594
595         /* release the mutex */
596         mutex_unlock(&aes_lock);
597
598         if (dd->req->base.complete)
599                 dd->req->base.complete(&dd->req->base, ret);
600
601         dev_dbg(dd->dev, "%s: exit\n", __func__);
602         return ret;
603 }
604
605 static int tegra_aes_setkey(struct crypto_ablkcipher *tfm, const u8 *key,
606         unsigned int keylen)
607 {
608         struct tegra_aes_ctx *ctx = crypto_ablkcipher_ctx(tfm);
609         struct tegra_aes_dev *dd = aes_dev;
610         struct tegra_aes_slot *key_slot;
611
612         if (!ctx || !dd) {
613                 dev_err(dd->dev, "ctx=0x%x, dd=0x%x\n",
614                         (unsigned int)ctx, (unsigned int)dd);
615                 return -EINVAL;
616         }
617
618         if ((keylen != AES_KEYSIZE_128) && (keylen != AES_KEYSIZE_192) &&
619                 (keylen != AES_KEYSIZE_256)) {
620                 dev_err(dd->dev, "unsupported key size\n");
621                 return -EINVAL;
622         }
623
624         dev_dbg(dd->dev, "keylen: %d\n", keylen);
625
626         ctx->dd = dd;
627         dd->ctx = ctx;
628
629         if (ctx->slot)
630                 aes_release_key_slot(dd);
631
632         key_slot = aes_find_key_slot(dd);
633         if (!key_slot) {
634                 dev_err(dd->dev, "no empty slot\n");
635                 return -ENOMEM;
636         }
637
638         ctx->slot = key_slot;
639         ctx->keylen = keylen;
640         ctx->flags |= FLAGS_NEW_KEY;
641
642         /* copy the key */
643         memset(dd->ivkey_base, 0, AES_HW_KEY_TABLE_LENGTH_BYTES);
644         memcpy(dd->ivkey_base, key, keylen);
645
646         dev_dbg(dd->dev, "done\n");
647         return 0;
648 }
649
650 static void aes_workqueue_handler(struct work_struct *work)
651 {
652         struct tegra_aes_dev *dd = aes_dev;
653         int ret;
654
655         set_bit(FLAGS_BUSY, &dd->flags);
656
657         do {
658                 ret = tegra_aes_handle_req(dd);
659         } while (!ret);
660 }
661
662 static irqreturn_t aes_irq(int irq, void *dev_id)
663 {
664         struct tegra_aes_dev *dd = (struct tegra_aes_dev *)dev_id;
665         u32 value = aes_readl(dd, INTR_STATUS);
666
667         dev_dbg(dd->dev, "irq_stat: 0x%x", value);
668         if (!((value & ENGINE_BUSY_FIELD) & !(value & ICQ_EMPTY_FIELD)))
669                 complete(&dd->op_complete);
670
671         return IRQ_HANDLED;
672 }
673
674 static int tegra_aes_crypt(struct ablkcipher_request *req, unsigned long mode)
675 {
676         struct tegra_aes_reqctx *rctx = ablkcipher_request_ctx(req);
677         struct tegra_aes_dev *dd = aes_dev;
678         unsigned long flags;
679         int err = 0;
680         int busy;
681
682         dev_dbg(dd->dev, "nbytes: %d, enc: %d, cbc: %d\n", req->nbytes,
683                 !!(mode & FLAGS_ENCRYPT),
684                 !!(mode & FLAGS_CBC));
685
686         rctx->mode = mode;
687
688         spin_lock_irqsave(&dd->lock, flags);
689         err = ablkcipher_enqueue_request(&dd->queue, req);
690         busy = test_and_set_bit(FLAGS_BUSY, &dd->flags);
691         spin_unlock_irqrestore(&dd->lock, flags);
692
693         if (!busy)
694                 queue_work(aes_wq, &aes_work);
695
696         return err;
697 }
698
699 static int tegra_aes_ecb_encrypt(struct ablkcipher_request *req)
700 {
701         return tegra_aes_crypt(req, FLAGS_ENCRYPT);
702 }
703
704 static int tegra_aes_ecb_decrypt(struct ablkcipher_request *req)
705 {
706         return tegra_aes_crypt(req, 0);
707 }
708
709 static int tegra_aes_cbc_encrypt(struct ablkcipher_request *req)
710 {
711         return tegra_aes_crypt(req, FLAGS_ENCRYPT | FLAGS_CBC);
712 }
713
714 static int tegra_aes_cbc_decrypt(struct ablkcipher_request *req)
715 {
716         return tegra_aes_crypt(req, FLAGS_CBC);
717 }
718
719 static int tegra_aes_get_random(struct crypto_rng *tfm, u8 *rdata,
720         unsigned int dlen)
721 {
722         struct tegra_aes_dev *dd = aes_dev;
723         struct tegra_aes_ctx *ctx = &rng_ctx;
724         int ret, i;
725         u8 *dest = rdata, *dt = dd->dt;
726
727         /* take mutex to access the aes hw */
728         mutex_lock(&aes_lock);
729
730         /* take the hardware semaphore */
731         if (tegra_arb_mutex_lock_timeout(dd->res_id, ARB_SEMA_TIMEOUT) < 0) {
732                 dev_err(dd->dev, "aes hardware not available\n");
733                 mutex_unlock(&aes_lock);
734                 return -EBUSY;
735         }
736
737         ret = aes_hw_init(dd);
738         if (ret < 0) {
739                 dev_err(dd->dev, "%s: hw init fail(%d)\n", __func__, ret);
740                 dlen = ret;
741                 goto fail;
742         }
743
744         ctx->dd = dd;
745         dd->ctx = ctx;
746         dd->flags = FLAGS_ENCRYPT | FLAGS_RNG;
747
748         memset(dd->buf_in, 0, AES_BLOCK_SIZE);
749         memcpy(dd->buf_in, dt, DEFAULT_RNG_BLK_SZ);
750
751         ret = aes_start_crypt(dd, (u32)dd->dma_buf_in,
752                 (u32)dd->dma_buf_out, 1, dd->flags, true);
753         if (ret < 0) {
754                 dev_err(dd->dev, "aes_start_crypt fail(%d)\n", ret);
755                 dlen = ret;
756                 goto out;
757         }
758         memcpy(dest, dd->buf_out, dlen);
759
760         /* update the DT */
761         for (i = DEFAULT_RNG_BLK_SZ - 1; i >= 0; i--) {
762                 dt[i] += 1;
763                 if (dt[i] != 0)
764                         break;
765         }
766
767 out:
768         aes_hw_deinit(dd);
769
770 fail:
771         /* release the hardware semaphore */
772         tegra_arb_mutex_unlock(dd->res_id);
773         mutex_unlock(&aes_lock);
774         dev_dbg(dd->dev, "%s: done\n", __func__);
775         return dlen;
776 }
777
778 static int tegra_aes_rng_reset(struct crypto_rng *tfm, u8 *seed,
779         unsigned int slen)
780 {
781         struct tegra_aes_dev *dd = aes_dev;
782         struct tegra_aes_ctx *ctx = &rng_ctx;
783         struct tegra_aes_slot *key_slot;
784         struct timespec ts;
785         int ret = 0;
786         u64 nsec, tmp[2];
787         u8 *dt;
788
789         if (!ctx || !dd) {
790                 dev_err(dd->dev, "ctx=0x%x, dd=0x%x\n",
791                         (unsigned int)ctx, (unsigned int)dd);
792                 return -EINVAL;
793         }
794
795         if (slen < (DEFAULT_RNG_BLK_SZ + AES_KEYSIZE_128)) {
796                 dev_err(dd->dev, "seed size invalid");
797                 return -ENOMEM;
798         }
799
800         /* take mutex to access the aes hw */
801         mutex_lock(&aes_lock);
802
803         if (!ctx->slot) {
804                 key_slot = aes_find_key_slot(dd);
805                 if (!key_slot) {
806                         dev_err(dd->dev, "no empty slot\n");
807                         mutex_unlock(&aes_lock);
808                         return -ENOMEM;
809                 }
810                 ctx->slot = key_slot;
811         }
812
813         ctx->dd = dd;
814         dd->ctx = ctx;
815         dd->ctr = 0;
816
817         ctx->keylen = AES_KEYSIZE_128;
818         ctx->flags |= FLAGS_NEW_KEY;
819
820         /* copy the key to the key slot */
821         memset(dd->ivkey_base, 0, AES_HW_KEY_TABLE_LENGTH_BYTES);
822         memcpy(dd->ivkey_base, seed + DEFAULT_RNG_BLK_SZ, AES_KEYSIZE_128);
823
824         dd->iv = seed;
825         dd->ivlen = slen;
826
827         dd->flags = FLAGS_ENCRYPT | FLAGS_RNG;
828
829         /* take the hardware semaphore */
830         if (tegra_arb_mutex_lock_timeout(dd->res_id, ARB_SEMA_TIMEOUT) < 0) {
831                 dev_err(dd->dev, "aes hardware not available\n");
832                 mutex_unlock(&aes_lock);
833                 return -EBUSY;
834         }
835
836         ret = aes_hw_init(dd);
837         if (ret < 0) {
838                 dev_err(dd->dev, "%s: hw init fail(%d)\n", __func__, ret);
839                 goto fail;
840         }
841
842         aes_set_key(dd);
843
844         /* set seed to the aes hw slot */
845         memset(dd->buf_in, 0, AES_BLOCK_SIZE);
846         memcpy(dd->buf_in, dd->iv, DEFAULT_RNG_BLK_SZ);
847         ret = aes_start_crypt(dd, (u32)dd->dma_buf_in,
848           (u32)dd->dma_buf_out, 1, FLAGS_CBC, false);
849         if (ret < 0) {
850                 dev_err(dd->dev, "aes_start_crypt fail(%d)\n", ret);
851                 goto out;
852         }
853
854         if (dd->ivlen >= (2 * DEFAULT_RNG_BLK_SZ + AES_KEYSIZE_128)) {
855                 dt = dd->iv + DEFAULT_RNG_BLK_SZ + AES_KEYSIZE_128;
856         } else {
857                 getnstimeofday(&ts);
858                 nsec = timespec_to_ns(&ts);
859                 do_div(nsec, 1000);
860                 nsec ^= dd->ctr << 56;
861                 dd->ctr++;
862                 tmp[0] = nsec;
863                 tmp[1] = tegra_chip_uid();
864                 dt = (u8 *)tmp;
865         }
866         memcpy(dd->dt, dt, DEFAULT_RNG_BLK_SZ);
867
868 out:
869         aes_hw_deinit(dd);
870
871 fail:
872         /* release the hardware semaphore */
873         tegra_arb_mutex_unlock(dd->res_id);
874         mutex_unlock(&aes_lock);
875
876         dev_dbg(dd->dev, "%s: done\n", __func__);
877         return ret;
878 }
879
880 static int tegra_aes_cra_init(struct crypto_tfm *tfm)
881 {
882         tfm->crt_ablkcipher.reqsize = sizeof(struct tegra_aes_reqctx);
883
884         return 0;
885 }
886
887 static struct crypto_alg algs[] = {
888         {
889                 .cra_name = "disabled_ecb(aes)",
890                 .cra_driver_name = "ecb-aes-tegra",
891                 .cra_priority = 100,
892                 .cra_flags = CRYPTO_ALG_TYPE_ABLKCIPHER | CRYPTO_ALG_ASYNC,
893                 .cra_blocksize = AES_BLOCK_SIZE,
894                 .cra_ctxsize = sizeof(struct tegra_aes_ctx),
895                 .cra_alignmask = 3,
896                 .cra_type = &crypto_ablkcipher_type,
897                 .cra_module = THIS_MODULE,
898                 .cra_init = tegra_aes_cra_init,
899                 .cra_u.ablkcipher = {
900                         .min_keysize = AES_MIN_KEY_SIZE,
901                         .max_keysize = AES_MAX_KEY_SIZE,
902                         .setkey = tegra_aes_setkey,
903                         .encrypt = tegra_aes_ecb_encrypt,
904                         .decrypt = tegra_aes_ecb_decrypt,
905                 },
906         }, {
907                 .cra_name = "disabled_cbc(aes)",
908                 .cra_driver_name = "cbc-aes-tegra",
909                 .cra_priority = 100,
910                 .cra_flags = CRYPTO_ALG_TYPE_ABLKCIPHER | CRYPTO_ALG_ASYNC,
911                 .cra_blocksize = AES_BLOCK_SIZE,
912                 .cra_ctxsize  = sizeof(struct tegra_aes_ctx),
913                 .cra_alignmask = 3,
914                 .cra_type = &crypto_ablkcipher_type,
915                 .cra_module = THIS_MODULE,
916                 .cra_init = tegra_aes_cra_init,
917                 .cra_u.ablkcipher = {
918                         .min_keysize = AES_MIN_KEY_SIZE,
919                         .max_keysize = AES_MAX_KEY_SIZE,
920                         .ivsize = AES_MIN_KEY_SIZE,
921                         .setkey = tegra_aes_setkey,
922                         .encrypt = tegra_aes_cbc_encrypt,
923                         .decrypt = tegra_aes_cbc_decrypt,
924                 }
925         }, {
926                 .cra_name = "disabled_ansi_cprng",
927                 .cra_driver_name = "rng-aes-tegra",
928                 .cra_priority = 100,
929                 .cra_flags = CRYPTO_ALG_TYPE_RNG,
930                 .cra_ctxsize = sizeof(struct tegra_aes_ctx),
931                 .cra_type = &crypto_rng_type,
932                 .cra_module = THIS_MODULE,
933                 .cra_init = tegra_aes_cra_init,
934                 .cra_u.rng = {
935                         .rng_make_random = tegra_aes_get_random,
936                         .rng_reset = tegra_aes_rng_reset,
937                         .seedsize = AES_KEYSIZE_128 + (2 * DEFAULT_RNG_BLK_SZ),
938                 }
939         }
940 };
941
942 static int tegra_aes_probe(struct platform_device *pdev)
943 {
944         struct device *dev = &pdev->dev;
945         struct tegra_aes_dev *dd;
946         struct resource *res;
947         int err = -ENOMEM, i = 0, j;
948
949         if (aes_dev)
950                 return -EEXIST;
951
952         dd = kzalloc(sizeof(struct tegra_aes_dev), GFP_KERNEL);
953         if (dd == NULL) {
954                 dev_err(dev, "unable to alloc data struct.\n");
955                 return -ENOMEM;;
956         }
957         dd->dev = dev;
958         platform_set_drvdata(pdev, dd);
959
960         dd->slots = kzalloc(sizeof(struct tegra_aes_slot) * AES_NR_KEYSLOTS,
961                 GFP_KERNEL);
962         if (dd->slots == NULL) {
963                 dev_err(dev, "unable to alloc slot struct.\n");
964                 goto out;
965         }
966
967         spin_lock_init(&dd->lock);
968         crypto_init_queue(&dd->queue, TEGRA_AES_QUEUE_LENGTH);
969
970         /* Get the module base address */
971         res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
972         if (!res) {
973                 dev_err(dev, "invalid resource type: base\n");
974                 err = -ENODEV;
975                 goto out;
976         }
977         dd->phys_base = res->start;
978
979         dd->io_base = ioremap(dd->phys_base, resource_size(res));
980         if (!dd->io_base) {
981                 dev_err(dev, "can't ioremap phys_base\n");
982                 err = -ENOMEM;
983                 goto out;
984         }
985
986         dd->res_id = TEGRA_ARB_AES;
987
988         /* Initialise the master bsev clock */
989         dd->pclk = clk_get(dev, "bsev");
990         if (!dd->pclk) {
991                 dev_err(dev, "pclock intialization failed.\n");
992                 err = -ENODEV;
993                 goto out;
994         }
995
996         /* Initialize the vde clock */
997         dd->iclk = clk_get(dev, "vde");
998         if (!dd->iclk) {
999                 dev_err(dev, "iclock intialization failed.\n");
1000                 err = -ENODEV;
1001                 goto out;
1002         }
1003
1004         /*
1005          * the foll contiguous memory is allocated as follows -
1006          * - hardware key table
1007          * - key schedule
1008          */
1009         dd->ivkey_base = dma_alloc_coherent(dev, SZ_512, &dd->ivkey_phys_base,
1010                 GFP_KERNEL);
1011         if (!dd->ivkey_base) {
1012                 dev_err(dev, "can not allocate iv/key buffer\n");
1013                 err = -ENOMEM;
1014                 goto out;
1015         }
1016
1017         dd->buf_in = dma_alloc_coherent(dev, AES_HW_DMA_BUFFER_SIZE_BYTES,
1018                 &dd->dma_buf_in, GFP_KERNEL);
1019         if (!dd->buf_in) {
1020                 dev_err(dev, "can not allocate dma-in buffer\n");
1021                 err = -ENOMEM;
1022                 goto out;
1023         }
1024
1025         dd->buf_out = dma_alloc_coherent(dev, AES_HW_DMA_BUFFER_SIZE_BYTES,
1026                 &dd->dma_buf_out, GFP_KERNEL);
1027         if (!dd->buf_out) {
1028                 dev_err(dev, "can not allocate dma-out buffer\n");
1029                 err = -ENOMEM;
1030                 goto out;
1031         }
1032
1033         init_completion(&dd->op_complete);
1034         aes_wq = alloc_workqueue("aes_wq", WQ_HIGHPRI, 16);
1035         if (!aes_wq) {
1036                 dev_err(dev, "alloc_workqueue failed\n");
1037                 goto out;
1038         }
1039
1040         /* get the irq */
1041         err = request_irq(INT_VDE_BSE_V, aes_irq, IRQF_TRIGGER_HIGH,
1042                 "tegra-aes", dd);
1043         if (err) {
1044                 dev_err(dev, "request_irq failed\n");
1045                 goto out;
1046         }
1047
1048         spin_lock_init(&list_lock);
1049         spin_lock(&list_lock);
1050         for (i = 0; i < AES_NR_KEYSLOTS; i++) {
1051                 dd->slots[i].available = true;
1052                 dd->slots[i].slot_num = i;
1053                 INIT_LIST_HEAD(&dd->slots[i].node);
1054                 list_add_tail(&dd->slots[i].node, &dev_list);
1055         }
1056         spin_unlock(&list_lock);
1057
1058         aes_dev = dd;
1059         for (i = 0; i < ARRAY_SIZE(algs); i++) {
1060                 INIT_LIST_HEAD(&algs[i].cra_list);
1061                 err = crypto_register_alg(&algs[i]);
1062                 if (err)
1063                         goto out;
1064         }
1065
1066         dev_info(dev, "registered");
1067         return 0;
1068
1069 out:
1070         for (j = 0; j < i; j++)
1071                 crypto_unregister_alg(&algs[j]);
1072         if (dd->ivkey_base)
1073                 dma_free_coherent(dev, SZ_512, dd->ivkey_base,
1074                         dd->ivkey_phys_base);
1075         if (dd->buf_in)
1076                 dma_free_coherent(dev, AES_HW_DMA_BUFFER_SIZE_BYTES,
1077                         dd->buf_in, dd->dma_buf_in);
1078         if (dd->buf_out)
1079                 dma_free_coherent(dev, AES_HW_DMA_BUFFER_SIZE_BYTES,
1080                         dd->buf_out, dd->dma_buf_out);
1081         if (dd->io_base)
1082                 iounmap(dd->io_base);
1083         if (dd->iclk)
1084                 clk_put(dd->iclk);
1085         if (dd->pclk)
1086                 clk_put(dd->pclk);
1087         if (aes_wq)
1088                 destroy_workqueue(aes_wq);
1089         free_irq(INT_VDE_BSE_V, dd);
1090         spin_lock(&list_lock);
1091         list_del(&dev_list);
1092         spin_unlock(&list_lock);
1093
1094         kfree(dd->slots);
1095         kfree(dd);
1096         aes_dev = NULL;
1097         dev_err(dev, "%s: initialization failed.\n", __func__);
1098         return err;
1099 }
1100
1101 static int __devexit tegra_aes_remove(struct platform_device *pdev)
1102 {
1103         struct device *dev = &pdev->dev;
1104         struct tegra_aes_dev *dd = platform_get_drvdata(pdev);
1105         int i;
1106
1107         if (!dd)
1108                 return -ENODEV;
1109
1110         cancel_work_sync(&aes_work);
1111         destroy_workqueue(aes_wq);
1112         free_irq(INT_VDE_BSE_V, dd);
1113         spin_lock(&list_lock);
1114         list_del(&dev_list);
1115         spin_unlock(&list_lock);
1116
1117         for (i = 0; i < ARRAY_SIZE(algs); i++)
1118                 crypto_unregister_alg(&algs[i]);
1119
1120         dma_free_coherent(dev, SZ_512, dd->ivkey_base,
1121                 dd->ivkey_phys_base);
1122         dma_free_coherent(dev, AES_HW_DMA_BUFFER_SIZE_BYTES,
1123                 dd->buf_in, dd->dma_buf_in);
1124         dma_free_coherent(dev, AES_HW_DMA_BUFFER_SIZE_BYTES,
1125                 dd->buf_out, dd->dma_buf_out);
1126         iounmap(dd->io_base);
1127         clk_put(dd->iclk);
1128         clk_put(dd->pclk);
1129         kfree(dd->slots);
1130         kfree(dd);
1131         aes_dev = NULL;
1132
1133         return 0;
1134 }
1135
1136 static struct platform_driver tegra_aes_driver = {
1137         .probe  = tegra_aes_probe,
1138         .remove = __devexit_p(tegra_aes_remove),
1139         .driver = {
1140                 .name   = "tegra-aes",
1141                 .owner  = THIS_MODULE,
1142         },
1143 };
1144
1145 static int __init tegra_aes_mod_init(void)
1146 {
1147         mutex_init(&aes_lock);
1148         INIT_LIST_HEAD(&dev_list);
1149         return  platform_driver_register(&tegra_aes_driver);
1150 }
1151
1152 static void __exit tegra_aes_mod_exit(void)
1153 {
1154         platform_driver_unregister(&tegra_aes_driver);
1155 }
1156
1157 module_init(tegra_aes_mod_init);
1158 module_exit(tegra_aes_mod_exit);
1159
1160 MODULE_DESCRIPTION("Tegra AES hw acceleration support.");
1161 MODULE_AUTHOR("NVIDIA Corporation");
1162 MODULE_LICENSE("GPLv2");