Merge branch 'linus' into timers/hpet
[linux-2.6] / drivers / crypto / talitos.c
1 /*
2  * talitos - Freescale Integrated Security Engine (SEC) device driver
3  *
4  * Copyright (c) 2008 Freescale Semiconductor, Inc.
5  *
6  * Scatterlist Crypto API glue code copied from files with the following:
7  * Copyright (c) 2006-2007 Herbert Xu <herbert@gondor.apana.org.au>
8  *
9  * Crypto algorithm registration code copied from hifn driver:
10  * 2007+ Copyright (c) Evgeniy Polyakov <johnpol@2ka.mipt.ru>
11  * All rights reserved.
12  *
13  * This program is free software; you can redistribute it and/or modify
14  * it under the terms of the GNU General Public License as published by
15  * the Free Software Foundation; either version 2 of the License, or
16  * (at your option) any later version.
17  *
18  * This program is distributed in the hope that it will be useful,
19  * but WITHOUT ANY WARRANTY; without even the implied warranty of
20  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
21  * GNU General Public License for more details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with this program; if not, write to the Free Software
25  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
26  */
27
28 #include <linux/kernel.h>
29 #include <linux/module.h>
30 #include <linux/mod_devicetable.h>
31 #include <linux/device.h>
32 #include <linux/interrupt.h>
33 #include <linux/crypto.h>
34 #include <linux/hw_random.h>
35 #include <linux/of_platform.h>
36 #include <linux/dma-mapping.h>
37 #include <linux/io.h>
38 #include <linux/spinlock.h>
39 #include <linux/rtnetlink.h>
40
41 #include <crypto/algapi.h>
42 #include <crypto/aes.h>
43 #include <crypto/des.h>
44 #include <crypto/sha.h>
45 #include <crypto/aead.h>
46 #include <crypto/authenc.h>
47
48 #include "talitos.h"
49
50 #define TALITOS_TIMEOUT 100000
51 #define TALITOS_MAX_DATA_LEN 65535
52
53 #define DESC_TYPE(desc_hdr) ((be32_to_cpu(desc_hdr) >> 3) & 0x1f)
54 #define PRIMARY_EU(desc_hdr) ((be32_to_cpu(desc_hdr) >> 28) & 0xf)
55 #define SECONDARY_EU(desc_hdr) ((be32_to_cpu(desc_hdr) >> 16) & 0xf)
56
57 /* descriptor pointer entry */
58 struct talitos_ptr {
59         __be16 len;     /* length */
60         u8 j_extent;    /* jump to sg link table and/or extent */
61         u8 eptr;        /* extended address */
62         __be32 ptr;     /* address */
63 };
64
65 /* descriptor */
66 struct talitos_desc {
67         __be32 hdr;                     /* header high bits */
68         __be32 hdr_lo;                  /* header low bits */
69         struct talitos_ptr ptr[7];      /* ptr/len pair array */
70 };
71
72 /**
73  * talitos_request - descriptor submission request
74  * @desc: descriptor pointer (kernel virtual)
75  * @dma_desc: descriptor's physical bus address
76  * @callback: whom to call when descriptor processing is done
77  * @context: caller context (optional)
78  */
79 struct talitos_request {
80         struct talitos_desc *desc;
81         dma_addr_t dma_desc;
82         void (*callback) (struct device *dev, struct talitos_desc *desc,
83                           void *context, int error);
84         void *context;
85 };
86
87 struct talitos_private {
88         struct device *dev;
89         struct of_device *ofdev;
90         void __iomem *reg;
91         int irq;
92
93         /* SEC version geometry (from device tree node) */
94         unsigned int num_channels;
95         unsigned int chfifo_len;
96         unsigned int exec_units;
97         unsigned int desc_types;
98
99         /* next channel to be assigned next incoming descriptor */
100         atomic_t last_chan;
101
102         /* per-channel number of requests pending in channel h/w fifo */
103         atomic_t *submit_count;
104
105         /* per-channel request fifo */
106         struct talitos_request **fifo;
107
108         /*
109          * length of the request fifo
110          * fifo_len is chfifo_len rounded up to next power of 2
111          * so we can use bitwise ops to wrap
112          */
113         unsigned int fifo_len;
114
115         /* per-channel index to next free descriptor request */
116         int *head;
117
118         /* per-channel index to next in-progress/done descriptor request */
119         int *tail;
120
121         /* per-channel request submission (head) and release (tail) locks */
122         spinlock_t *head_lock;
123         spinlock_t *tail_lock;
124
125         /* request callback tasklet */
126         struct tasklet_struct done_task;
127         struct tasklet_struct error_task;
128
129         /* list of registered algorithms */
130         struct list_head alg_list;
131
132         /* hwrng device */
133         struct hwrng rng;
134 };
135
136 /*
137  * map virtual single (contiguous) pointer to h/w descriptor pointer
138  */
139 static void map_single_talitos_ptr(struct device *dev,
140                                    struct talitos_ptr *talitos_ptr,
141                                    unsigned short len, void *data,
142                                    unsigned char extent,
143                                    enum dma_data_direction dir)
144 {
145         talitos_ptr->len = cpu_to_be16(len);
146         talitos_ptr->ptr = cpu_to_be32(dma_map_single(dev, data, len, dir));
147         talitos_ptr->j_extent = extent;
148 }
149
150 /*
151  * unmap bus single (contiguous) h/w descriptor pointer
152  */
153 static void unmap_single_talitos_ptr(struct device *dev,
154                                      struct talitos_ptr *talitos_ptr,
155                                      enum dma_data_direction dir)
156 {
157         dma_unmap_single(dev, be32_to_cpu(talitos_ptr->ptr),
158                          be16_to_cpu(talitos_ptr->len), dir);
159 }
160
161 static int reset_channel(struct device *dev, int ch)
162 {
163         struct talitos_private *priv = dev_get_drvdata(dev);
164         unsigned int timeout = TALITOS_TIMEOUT;
165
166         setbits32(priv->reg + TALITOS_CCCR(ch), TALITOS_CCCR_RESET);
167
168         while ((in_be32(priv->reg + TALITOS_CCCR(ch)) & TALITOS_CCCR_RESET)
169                && --timeout)
170                 cpu_relax();
171
172         if (timeout == 0) {
173                 dev_err(dev, "failed to reset channel %d\n", ch);
174                 return -EIO;
175         }
176
177         /* set done writeback and IRQ */
178         setbits32(priv->reg + TALITOS_CCCR_LO(ch), TALITOS_CCCR_LO_CDWE |
179                   TALITOS_CCCR_LO_CDIE);
180
181         return 0;
182 }
183
184 static int reset_device(struct device *dev)
185 {
186         struct talitos_private *priv = dev_get_drvdata(dev);
187         unsigned int timeout = TALITOS_TIMEOUT;
188
189         setbits32(priv->reg + TALITOS_MCR, TALITOS_MCR_SWR);
190
191         while ((in_be32(priv->reg + TALITOS_MCR) & TALITOS_MCR_SWR)
192                && --timeout)
193                 cpu_relax();
194
195         if (timeout == 0) {
196                 dev_err(dev, "failed to reset device\n");
197                 return -EIO;
198         }
199
200         return 0;
201 }
202
203 /*
204  * Reset and initialize the device
205  */
206 static int init_device(struct device *dev)
207 {
208         struct talitos_private *priv = dev_get_drvdata(dev);
209         int ch, err;
210
211         /*
212          * Master reset
213          * errata documentation: warning: certain SEC interrupts
214          * are not fully cleared by writing the MCR:SWR bit,
215          * set bit twice to completely reset
216          */
217         err = reset_device(dev);
218         if (err)
219                 return err;
220
221         err = reset_device(dev);
222         if (err)
223                 return err;
224
225         /* reset channels */
226         for (ch = 0; ch < priv->num_channels; ch++) {
227                 err = reset_channel(dev, ch);
228                 if (err)
229                         return err;
230         }
231
232         /* enable channel done and error interrupts */
233         setbits32(priv->reg + TALITOS_IMR, TALITOS_IMR_INIT);
234         setbits32(priv->reg + TALITOS_IMR_LO, TALITOS_IMR_LO_INIT);
235
236         return 0;
237 }
238
239 /**
240  * talitos_submit - submits a descriptor to the device for processing
241  * @dev:        the SEC device to be used
242  * @desc:       the descriptor to be processed by the device
243  * @callback:   whom to call when processing is complete
244  * @context:    a handle for use by caller (optional)
245  *
246  * desc must contain valid dma-mapped (bus physical) address pointers.
247  * callback must check err and feedback in descriptor header
248  * for device processing status.
249  */
250 static int talitos_submit(struct device *dev, struct talitos_desc *desc,
251                           void (*callback)(struct device *dev,
252                                            struct talitos_desc *desc,
253                                            void *context, int error),
254                           void *context)
255 {
256         struct talitos_private *priv = dev_get_drvdata(dev);
257         struct talitos_request *request;
258         unsigned long flags, ch;
259         int head;
260
261         /* select done notification */
262         desc->hdr |= DESC_HDR_DONE_NOTIFY;
263
264         /* emulate SEC's round-robin channel fifo polling scheme */
265         ch = atomic_inc_return(&priv->last_chan) & (priv->num_channels - 1);
266
267         spin_lock_irqsave(&priv->head_lock[ch], flags);
268
269         if (!atomic_inc_not_zero(&priv->submit_count[ch])) {
270                 /* h/w fifo is full */
271                 spin_unlock_irqrestore(&priv->head_lock[ch], flags);
272                 return -EAGAIN;
273         }
274
275         head = priv->head[ch];
276         request = &priv->fifo[ch][head];
277
278         /* map descriptor and save caller data */
279         request->dma_desc = dma_map_single(dev, desc, sizeof(*desc),
280                                            DMA_BIDIRECTIONAL);
281         request->callback = callback;
282         request->context = context;
283
284         /* increment fifo head */
285         priv->head[ch] = (priv->head[ch] + 1) & (priv->fifo_len - 1);
286
287         smp_wmb();
288         request->desc = desc;
289
290         /* GO! */
291         wmb();
292         out_be32(priv->reg + TALITOS_FF_LO(ch), request->dma_desc);
293
294         spin_unlock_irqrestore(&priv->head_lock[ch], flags);
295
296         return -EINPROGRESS;
297 }
298
299 /*
300  * process what was done, notify callback of error if not
301  */
302 static void flush_channel(struct device *dev, int ch, int error, int reset_ch)
303 {
304         struct talitos_private *priv = dev_get_drvdata(dev);
305         struct talitos_request *request, saved_req;
306         unsigned long flags;
307         int tail, status;
308
309         spin_lock_irqsave(&priv->tail_lock[ch], flags);
310
311         tail = priv->tail[ch];
312         while (priv->fifo[ch][tail].desc) {
313                 request = &priv->fifo[ch][tail];
314
315                 /* descriptors with their done bits set don't get the error */
316                 rmb();
317                 if ((request->desc->hdr & DESC_HDR_DONE) == DESC_HDR_DONE)
318                         status = 0;
319                 else
320                         if (!error)
321                                 break;
322                         else
323                                 status = error;
324
325                 dma_unmap_single(dev, request->dma_desc,
326                         sizeof(struct talitos_desc), DMA_BIDIRECTIONAL);
327
328                 /* copy entries so we can call callback outside lock */
329                 saved_req.desc = request->desc;
330                 saved_req.callback = request->callback;
331                 saved_req.context = request->context;
332
333                 /* release request entry in fifo */
334                 smp_wmb();
335                 request->desc = NULL;
336
337                 /* increment fifo tail */
338                 priv->tail[ch] = (tail + 1) & (priv->fifo_len - 1);
339
340                 spin_unlock_irqrestore(&priv->tail_lock[ch], flags);
341
342                 atomic_dec(&priv->submit_count[ch]);
343
344                 saved_req.callback(dev, saved_req.desc, saved_req.context,
345                                    status);
346                 /* channel may resume processing in single desc error case */
347                 if (error && !reset_ch && status == error)
348                         return;
349                 spin_lock_irqsave(&priv->tail_lock[ch], flags);
350                 tail = priv->tail[ch];
351         }
352
353         spin_unlock_irqrestore(&priv->tail_lock[ch], flags);
354 }
355
356 /*
357  * process completed requests for channels that have done status
358  */
359 static void talitos_done(unsigned long data)
360 {
361         struct device *dev = (struct device *)data;
362         struct talitos_private *priv = dev_get_drvdata(dev);
363         int ch;
364
365         for (ch = 0; ch < priv->num_channels; ch++)
366                 flush_channel(dev, ch, 0, 0);
367 }
368
369 /*
370  * locate current (offending) descriptor
371  */
372 static struct talitos_desc *current_desc(struct device *dev, int ch)
373 {
374         struct talitos_private *priv = dev_get_drvdata(dev);
375         int tail = priv->tail[ch];
376         dma_addr_t cur_desc;
377
378         cur_desc = in_be32(priv->reg + TALITOS_CDPR_LO(ch));
379
380         while (priv->fifo[ch][tail].dma_desc != cur_desc) {
381                 tail = (tail + 1) & (priv->fifo_len - 1);
382                 if (tail == priv->tail[ch]) {
383                         dev_err(dev, "couldn't locate current descriptor\n");
384                         return NULL;
385                 }
386         }
387
388         return priv->fifo[ch][tail].desc;
389 }
390
391 /*
392  * user diagnostics; report root cause of error based on execution unit status
393  */
394 static void report_eu_error(struct device *dev, int ch, struct talitos_desc *desc)
395 {
396         struct talitos_private *priv = dev_get_drvdata(dev);
397         int i;
398
399         switch (desc->hdr & DESC_HDR_SEL0_MASK) {
400         case DESC_HDR_SEL0_AFEU:
401                 dev_err(dev, "AFEUISR 0x%08x_%08x\n",
402                         in_be32(priv->reg + TALITOS_AFEUISR),
403                         in_be32(priv->reg + TALITOS_AFEUISR_LO));
404                 break;
405         case DESC_HDR_SEL0_DEU:
406                 dev_err(dev, "DEUISR 0x%08x_%08x\n",
407                         in_be32(priv->reg + TALITOS_DEUISR),
408                         in_be32(priv->reg + TALITOS_DEUISR_LO));
409                 break;
410         case DESC_HDR_SEL0_MDEUA:
411         case DESC_HDR_SEL0_MDEUB:
412                 dev_err(dev, "MDEUISR 0x%08x_%08x\n",
413                         in_be32(priv->reg + TALITOS_MDEUISR),
414                         in_be32(priv->reg + TALITOS_MDEUISR_LO));
415                 break;
416         case DESC_HDR_SEL0_RNG:
417                 dev_err(dev, "RNGUISR 0x%08x_%08x\n",
418                         in_be32(priv->reg + TALITOS_RNGUISR),
419                         in_be32(priv->reg + TALITOS_RNGUISR_LO));
420                 break;
421         case DESC_HDR_SEL0_PKEU:
422                 dev_err(dev, "PKEUISR 0x%08x_%08x\n",
423                         in_be32(priv->reg + TALITOS_PKEUISR),
424                         in_be32(priv->reg + TALITOS_PKEUISR_LO));
425                 break;
426         case DESC_HDR_SEL0_AESU:
427                 dev_err(dev, "AESUISR 0x%08x_%08x\n",
428                         in_be32(priv->reg + TALITOS_AESUISR),
429                         in_be32(priv->reg + TALITOS_AESUISR_LO));
430                 break;
431         case DESC_HDR_SEL0_CRCU:
432                 dev_err(dev, "CRCUISR 0x%08x_%08x\n",
433                         in_be32(priv->reg + TALITOS_CRCUISR),
434                         in_be32(priv->reg + TALITOS_CRCUISR_LO));
435                 break;
436         case DESC_HDR_SEL0_KEU:
437                 dev_err(dev, "KEUISR 0x%08x_%08x\n",
438                         in_be32(priv->reg + TALITOS_KEUISR),
439                         in_be32(priv->reg + TALITOS_KEUISR_LO));
440                 break;
441         }
442
443         switch (desc->hdr & DESC_HDR_SEL1_MASK) {
444         case DESC_HDR_SEL1_MDEUA:
445         case DESC_HDR_SEL1_MDEUB:
446                 dev_err(dev, "MDEUISR 0x%08x_%08x\n",
447                         in_be32(priv->reg + TALITOS_MDEUISR),
448                         in_be32(priv->reg + TALITOS_MDEUISR_LO));
449                 break;
450         case DESC_HDR_SEL1_CRCU:
451                 dev_err(dev, "CRCUISR 0x%08x_%08x\n",
452                         in_be32(priv->reg + TALITOS_CRCUISR),
453                         in_be32(priv->reg + TALITOS_CRCUISR_LO));
454                 break;
455         }
456
457         for (i = 0; i < 8; i++)
458                 dev_err(dev, "DESCBUF 0x%08x_%08x\n",
459                         in_be32(priv->reg + TALITOS_DESCBUF(ch) + 8*i),
460                         in_be32(priv->reg + TALITOS_DESCBUF_LO(ch) + 8*i));
461 }
462
463 /*
464  * recover from error interrupts
465  */
466 static void talitos_error(unsigned long data)
467 {
468         struct device *dev = (struct device *)data;
469         struct talitos_private *priv = dev_get_drvdata(dev);
470         unsigned int timeout = TALITOS_TIMEOUT;
471         int ch, error, reset_dev = 0, reset_ch = 0;
472         u32 isr, isr_lo, v, v_lo;
473
474         isr = in_be32(priv->reg + TALITOS_ISR);
475         isr_lo = in_be32(priv->reg + TALITOS_ISR_LO);
476
477         for (ch = 0; ch < priv->num_channels; ch++) {
478                 /* skip channels without errors */
479                 if (!(isr & (1 << (ch * 2 + 1))))
480                         continue;
481
482                 error = -EINVAL;
483
484                 v = in_be32(priv->reg + TALITOS_CCPSR(ch));
485                 v_lo = in_be32(priv->reg + TALITOS_CCPSR_LO(ch));
486
487                 if (v_lo & TALITOS_CCPSR_LO_DOF) {
488                         dev_err(dev, "double fetch fifo overflow error\n");
489                         error = -EAGAIN;
490                         reset_ch = 1;
491                 }
492                 if (v_lo & TALITOS_CCPSR_LO_SOF) {
493                         /* h/w dropped descriptor */
494                         dev_err(dev, "single fetch fifo overflow error\n");
495                         error = -EAGAIN;
496                 }
497                 if (v_lo & TALITOS_CCPSR_LO_MDTE)
498                         dev_err(dev, "master data transfer error\n");
499                 if (v_lo & TALITOS_CCPSR_LO_SGDLZ)
500                         dev_err(dev, "s/g data length zero error\n");
501                 if (v_lo & TALITOS_CCPSR_LO_FPZ)
502                         dev_err(dev, "fetch pointer zero error\n");
503                 if (v_lo & TALITOS_CCPSR_LO_IDH)
504                         dev_err(dev, "illegal descriptor header error\n");
505                 if (v_lo & TALITOS_CCPSR_LO_IEU)
506                         dev_err(dev, "invalid execution unit error\n");
507                 if (v_lo & TALITOS_CCPSR_LO_EU)
508                         report_eu_error(dev, ch, current_desc(dev, ch));
509                 if (v_lo & TALITOS_CCPSR_LO_GB)
510                         dev_err(dev, "gather boundary error\n");
511                 if (v_lo & TALITOS_CCPSR_LO_GRL)
512                         dev_err(dev, "gather return/length error\n");
513                 if (v_lo & TALITOS_CCPSR_LO_SB)
514                         dev_err(dev, "scatter boundary error\n");
515                 if (v_lo & TALITOS_CCPSR_LO_SRL)
516                         dev_err(dev, "scatter return/length error\n");
517
518                 flush_channel(dev, ch, error, reset_ch);
519
520                 if (reset_ch) {
521                         reset_channel(dev, ch);
522                 } else {
523                         setbits32(priv->reg + TALITOS_CCCR(ch),
524                                   TALITOS_CCCR_CONT);
525                         setbits32(priv->reg + TALITOS_CCCR_LO(ch), 0);
526                         while ((in_be32(priv->reg + TALITOS_CCCR(ch)) &
527                                TALITOS_CCCR_CONT) && --timeout)
528                                 cpu_relax();
529                         if (timeout == 0) {
530                                 dev_err(dev, "failed to restart channel %d\n",
531                                         ch);
532                                 reset_dev = 1;
533                         }
534                 }
535         }
536         if (reset_dev || isr & ~TALITOS_ISR_CHERR || isr_lo) {
537                 dev_err(dev, "done overflow, internal time out, or rngu error: "
538                         "ISR 0x%08x_%08x\n", isr, isr_lo);
539
540                 /* purge request queues */
541                 for (ch = 0; ch < priv->num_channels; ch++)
542                         flush_channel(dev, ch, -EIO, 1);
543
544                 /* reset and reinitialize the device */
545                 init_device(dev);
546         }
547 }
548
549 static irqreturn_t talitos_interrupt(int irq, void *data)
550 {
551         struct device *dev = data;
552         struct talitos_private *priv = dev_get_drvdata(dev);
553         u32 isr, isr_lo;
554
555         isr = in_be32(priv->reg + TALITOS_ISR);
556         isr_lo = in_be32(priv->reg + TALITOS_ISR_LO);
557
558         /* ack */
559         out_be32(priv->reg + TALITOS_ICR, isr);
560         out_be32(priv->reg + TALITOS_ICR_LO, isr_lo);
561
562         if (unlikely((isr & ~TALITOS_ISR_CHDONE) || isr_lo))
563                 talitos_error((unsigned long)data);
564         else
565                 if (likely(isr & TALITOS_ISR_CHDONE))
566                         tasklet_schedule(&priv->done_task);
567
568         return (isr || isr_lo) ? IRQ_HANDLED : IRQ_NONE;
569 }
570
571 /*
572  * hwrng
573  */
574 static int talitos_rng_data_present(struct hwrng *rng, int wait)
575 {
576         struct device *dev = (struct device *)rng->priv;
577         struct talitos_private *priv = dev_get_drvdata(dev);
578         u32 ofl;
579         int i;
580
581         for (i = 0; i < 20; i++) {
582                 ofl = in_be32(priv->reg + TALITOS_RNGUSR_LO) &
583                       TALITOS_RNGUSR_LO_OFL;
584                 if (ofl || !wait)
585                         break;
586                 udelay(10);
587         }
588
589         return !!ofl;
590 }
591
592 static int talitos_rng_data_read(struct hwrng *rng, u32 *data)
593 {
594         struct device *dev = (struct device *)rng->priv;
595         struct talitos_private *priv = dev_get_drvdata(dev);
596
597         /* rng fifo requires 64-bit accesses */
598         *data = in_be32(priv->reg + TALITOS_RNGU_FIFO);
599         *data = in_be32(priv->reg + TALITOS_RNGU_FIFO_LO);
600
601         return sizeof(u32);
602 }
603
604 static int talitos_rng_init(struct hwrng *rng)
605 {
606         struct device *dev = (struct device *)rng->priv;
607         struct talitos_private *priv = dev_get_drvdata(dev);
608         unsigned int timeout = TALITOS_TIMEOUT;
609
610         setbits32(priv->reg + TALITOS_RNGURCR_LO, TALITOS_RNGURCR_LO_SR);
611         while (!(in_be32(priv->reg + TALITOS_RNGUSR_LO) & TALITOS_RNGUSR_LO_RD)
612                && --timeout)
613                 cpu_relax();
614         if (timeout == 0) {
615                 dev_err(dev, "failed to reset rng hw\n");
616                 return -ENODEV;
617         }
618
619         /* start generating */
620         setbits32(priv->reg + TALITOS_RNGUDSR_LO, 0);
621
622         return 0;
623 }
624
625 static int talitos_register_rng(struct device *dev)
626 {
627         struct talitos_private *priv = dev_get_drvdata(dev);
628
629         priv->rng.name          = dev_driver_string(dev),
630         priv->rng.init          = talitos_rng_init,
631         priv->rng.data_present  = talitos_rng_data_present,
632         priv->rng.data_read     = talitos_rng_data_read,
633         priv->rng.priv          = (unsigned long)dev;
634
635         return hwrng_register(&priv->rng);
636 }
637
638 static void talitos_unregister_rng(struct device *dev)
639 {
640         struct talitos_private *priv = dev_get_drvdata(dev);
641
642         hwrng_unregister(&priv->rng);
643 }
644
645 /*
646  * crypto alg
647  */
648 #define TALITOS_CRA_PRIORITY            3000
649 #define TALITOS_MAX_KEY_SIZE            64
650 #define TALITOS_MAX_IV_LENGTH           16 /* max of AES_BLOCK_SIZE, DES3_EDE_BLOCK_SIZE */
651
652 #define MD5_DIGEST_SIZE   16
653
654 struct talitos_ctx {
655         struct device *dev;
656         __be32 desc_hdr_template;
657         u8 key[TALITOS_MAX_KEY_SIZE];
658         u8 iv[TALITOS_MAX_IV_LENGTH];
659         unsigned int keylen;
660         unsigned int enckeylen;
661         unsigned int authkeylen;
662         unsigned int authsize;
663 };
664
665 static int aead_authenc_setauthsize(struct crypto_aead *authenc,
666                                                  unsigned int authsize)
667 {
668         struct talitos_ctx *ctx = crypto_aead_ctx(authenc);
669
670         ctx->authsize = authsize;
671
672         return 0;
673 }
674
675 static int aead_authenc_setkey(struct crypto_aead *authenc,
676                                             const u8 *key, unsigned int keylen)
677 {
678         struct talitos_ctx *ctx = crypto_aead_ctx(authenc);
679         struct rtattr *rta = (void *)key;
680         struct crypto_authenc_key_param *param;
681         unsigned int authkeylen;
682         unsigned int enckeylen;
683
684         if (!RTA_OK(rta, keylen))
685                 goto badkey;
686
687         if (rta->rta_type != CRYPTO_AUTHENC_KEYA_PARAM)
688                 goto badkey;
689
690         if (RTA_PAYLOAD(rta) < sizeof(*param))
691                 goto badkey;
692
693         param = RTA_DATA(rta);
694         enckeylen = be32_to_cpu(param->enckeylen);
695
696         key += RTA_ALIGN(rta->rta_len);
697         keylen -= RTA_ALIGN(rta->rta_len);
698
699         if (keylen < enckeylen)
700                 goto badkey;
701
702         authkeylen = keylen - enckeylen;
703
704         if (keylen > TALITOS_MAX_KEY_SIZE)
705                 goto badkey;
706
707         memcpy(&ctx->key, key, keylen);
708
709         ctx->keylen = keylen;
710         ctx->enckeylen = enckeylen;
711         ctx->authkeylen = authkeylen;
712
713         return 0;
714
715 badkey:
716         crypto_aead_set_flags(authenc, CRYPTO_TFM_RES_BAD_KEY_LEN);
717         return -EINVAL;
718 }
719
720 /*
721  * ipsec_esp_edesc - s/w-extended ipsec_esp descriptor
722  * @src_nents: number of segments in input scatterlist
723  * @dst_nents: number of segments in output scatterlist
724  * @dma_len: length of dma mapped link_tbl space
725  * @dma_link_tbl: bus physical address of link_tbl
726  * @desc: h/w descriptor
727  * @link_tbl: input and output h/w link tables (if {src,dst}_nents > 1)
728  *
729  * if decrypting (with authcheck), or either one of src_nents or dst_nents
730  * is greater than 1, an integrity check value is concatenated to the end
731  * of link_tbl data
732  */
733 struct ipsec_esp_edesc {
734         int src_nents;
735         int dst_nents;
736         int dma_len;
737         dma_addr_t dma_link_tbl;
738         struct talitos_desc desc;
739         struct talitos_ptr link_tbl[0];
740 };
741
742 static void ipsec_esp_unmap(struct device *dev,
743                             struct ipsec_esp_edesc *edesc,
744                             struct aead_request *areq)
745 {
746         unmap_single_talitos_ptr(dev, &edesc->desc.ptr[6], DMA_FROM_DEVICE);
747         unmap_single_talitos_ptr(dev, &edesc->desc.ptr[3], DMA_TO_DEVICE);
748         unmap_single_talitos_ptr(dev, &edesc->desc.ptr[2], DMA_TO_DEVICE);
749         unmap_single_talitos_ptr(dev, &edesc->desc.ptr[0], DMA_TO_DEVICE);
750
751         dma_unmap_sg(dev, areq->assoc, 1, DMA_TO_DEVICE);
752
753         if (areq->src != areq->dst) {
754                 dma_unmap_sg(dev, areq->src, edesc->src_nents ? : 1,
755                              DMA_TO_DEVICE);
756                 dma_unmap_sg(dev, areq->dst, edesc->dst_nents ? : 1,
757                              DMA_FROM_DEVICE);
758         } else {
759                 dma_unmap_sg(dev, areq->src, edesc->src_nents ? : 1,
760                              DMA_BIDIRECTIONAL);
761         }
762
763         if (edesc->dma_len)
764                 dma_unmap_single(dev, edesc->dma_link_tbl, edesc->dma_len,
765                                  DMA_BIDIRECTIONAL);
766 }
767
768 /*
769  * ipsec_esp descriptor callbacks
770  */
771 static void ipsec_esp_encrypt_done(struct device *dev,
772                                    struct talitos_desc *desc, void *context,
773                                    int err)
774 {
775         struct aead_request *areq = context;
776         struct ipsec_esp_edesc *edesc =
777                  container_of(desc, struct ipsec_esp_edesc, desc);
778         struct crypto_aead *authenc = crypto_aead_reqtfm(areq);
779         struct talitos_ctx *ctx = crypto_aead_ctx(authenc);
780         struct scatterlist *sg;
781         void *icvdata;
782
783         ipsec_esp_unmap(dev, edesc, areq);
784
785         /* copy the generated ICV to dst */
786         if (edesc->dma_len) {
787                 icvdata = &edesc->link_tbl[edesc->src_nents +
788                                            edesc->dst_nents + 1];
789                 sg = sg_last(areq->dst, edesc->dst_nents);
790                 memcpy((char *)sg_virt(sg) + sg->length - ctx->authsize,
791                        icvdata, ctx->authsize);
792         }
793
794         kfree(edesc);
795
796         aead_request_complete(areq, err);
797 }
798
799 static void ipsec_esp_decrypt_done(struct device *dev,
800                                    struct talitos_desc *desc, void *context,
801                                    int err)
802 {
803         struct aead_request *req = context;
804         struct ipsec_esp_edesc *edesc =
805                  container_of(desc, struct ipsec_esp_edesc, desc);
806         struct crypto_aead *authenc = crypto_aead_reqtfm(req);
807         struct talitos_ctx *ctx = crypto_aead_ctx(authenc);
808         struct scatterlist *sg;
809         void *icvdata;
810
811         ipsec_esp_unmap(dev, edesc, req);
812
813         if (!err) {
814                 /* auth check */
815                 if (edesc->dma_len)
816                         icvdata = &edesc->link_tbl[edesc->src_nents +
817                                                    edesc->dst_nents + 1];
818                 else
819                         icvdata = &edesc->link_tbl[0];
820
821                 sg = sg_last(req->dst, edesc->dst_nents ? : 1);
822                 err = memcmp(icvdata, (char *)sg_virt(sg) + sg->length -
823                              ctx->authsize, ctx->authsize) ? -EBADMSG : 0;
824         }
825
826         kfree(edesc);
827
828         aead_request_complete(req, err);
829 }
830
831 /*
832  * convert scatterlist to SEC h/w link table format
833  * stop at cryptlen bytes
834  */
835 static int sg_to_link_tbl(struct scatterlist *sg, int sg_count,
836                            int cryptlen, struct talitos_ptr *link_tbl_ptr)
837 {
838         int n_sg = sg_count;
839
840         while (n_sg--) {
841                 link_tbl_ptr->ptr = cpu_to_be32(sg_dma_address(sg));
842                 link_tbl_ptr->len = cpu_to_be16(sg_dma_len(sg));
843                 link_tbl_ptr->j_extent = 0;
844                 link_tbl_ptr++;
845                 cryptlen -= sg_dma_len(sg);
846                 sg = sg_next(sg);
847         }
848
849         /* adjust (decrease) last one (or two) entry's len to cryptlen */
850         link_tbl_ptr--;
851         while (be16_to_cpu(link_tbl_ptr->len) <= (-cryptlen)) {
852                 /* Empty this entry, and move to previous one */
853                 cryptlen += be16_to_cpu(link_tbl_ptr->len);
854                 link_tbl_ptr->len = 0;
855                 sg_count--;
856                 link_tbl_ptr--;
857         }
858         link_tbl_ptr->len = cpu_to_be16(be16_to_cpu(link_tbl_ptr->len)
859                                         + cryptlen);
860
861         /* tag end of link table */
862         link_tbl_ptr->j_extent = DESC_PTR_LNKTBL_RETURN;
863
864         return sg_count;
865 }
866
867 /*
868  * fill in and submit ipsec_esp descriptor
869  */
870 static int ipsec_esp(struct ipsec_esp_edesc *edesc, struct aead_request *areq,
871                      u8 *giv, u64 seq,
872                      void (*callback) (struct device *dev,
873                                        struct talitos_desc *desc,
874                                        void *context, int error))
875 {
876         struct crypto_aead *aead = crypto_aead_reqtfm(areq);
877         struct talitos_ctx *ctx = crypto_aead_ctx(aead);
878         struct device *dev = ctx->dev;
879         struct talitos_desc *desc = &edesc->desc;
880         unsigned int cryptlen = areq->cryptlen;
881         unsigned int authsize = ctx->authsize;
882         unsigned int ivsize;
883         int sg_count, ret;
884
885         /* hmac key */
886         map_single_talitos_ptr(dev, &desc->ptr[0], ctx->authkeylen, &ctx->key,
887                                0, DMA_TO_DEVICE);
888         /* hmac data */
889         map_single_talitos_ptr(dev, &desc->ptr[1], sg_virt(areq->src) -
890                                sg_virt(areq->assoc), sg_virt(areq->assoc), 0,
891                                DMA_TO_DEVICE);
892         /* cipher iv */
893         ivsize = crypto_aead_ivsize(aead);
894         map_single_talitos_ptr(dev, &desc->ptr[2], ivsize, giv ?: areq->iv, 0,
895                                DMA_TO_DEVICE);
896
897         /* cipher key */
898         map_single_talitos_ptr(dev, &desc->ptr[3], ctx->enckeylen,
899                                (char *)&ctx->key + ctx->authkeylen, 0,
900                                DMA_TO_DEVICE);
901
902         /*
903          * cipher in
904          * map and adjust cipher len to aead request cryptlen.
905          * extent is bytes of HMAC postpended to ciphertext,
906          * typically 12 for ipsec
907          */
908         desc->ptr[4].len = cpu_to_be16(cryptlen);
909         desc->ptr[4].j_extent = authsize;
910
911         if (areq->src == areq->dst)
912                 sg_count = dma_map_sg(dev, areq->src, edesc->src_nents ? : 1,
913                                       DMA_BIDIRECTIONAL);
914         else
915                 sg_count = dma_map_sg(dev, areq->src, edesc->src_nents ? : 1,
916                                       DMA_TO_DEVICE);
917
918         if (sg_count == 1) {
919                 desc->ptr[4].ptr = cpu_to_be32(sg_dma_address(areq->src));
920         } else {
921                 sg_count = sg_to_link_tbl(areq->src, sg_count, cryptlen,
922                                           &edesc->link_tbl[0]);
923                 if (sg_count > 1) {
924                         desc->ptr[4].j_extent |= DESC_PTR_LNKTBL_JUMP;
925                         desc->ptr[4].ptr = cpu_to_be32(edesc->dma_link_tbl);
926                         dma_sync_single_for_device(ctx->dev, edesc->dma_link_tbl,
927                                                    edesc->dma_len, DMA_BIDIRECTIONAL);
928                 } else {
929                         /* Only one segment now, so no link tbl needed */
930                         desc->ptr[4].ptr = cpu_to_be32(sg_dma_address(areq->src));
931                 }
932         }
933
934         /* cipher out */
935         desc->ptr[5].len = cpu_to_be16(cryptlen);
936         desc->ptr[5].j_extent = authsize;
937
938         if (areq->src != areq->dst) {
939                 sg_count = dma_map_sg(dev, areq->dst, edesc->dst_nents ? : 1,
940                                       DMA_FROM_DEVICE);
941         }
942
943         if (sg_count == 1) {
944                 desc->ptr[5].ptr = cpu_to_be32(sg_dma_address(areq->dst));
945         } else {
946                 struct talitos_ptr *link_tbl_ptr =
947                         &edesc->link_tbl[edesc->src_nents];
948                 struct scatterlist *sg;
949
950                 desc->ptr[5].ptr = cpu_to_be32((struct talitos_ptr *)
951                                                edesc->dma_link_tbl +
952                                                edesc->src_nents);
953                 if (areq->src == areq->dst) {
954                         memcpy(link_tbl_ptr, &edesc->link_tbl[0],
955                                edesc->src_nents * sizeof(struct talitos_ptr));
956                 } else {
957                         sg_count = sg_to_link_tbl(areq->dst, sg_count, cryptlen,
958                                                   link_tbl_ptr);
959                 }
960                 link_tbl_ptr += sg_count - 1;
961
962                 /* handle case where sg_last contains the ICV exclusively */
963                 sg = sg_last(areq->dst, edesc->dst_nents);
964                 if (sg->length == ctx->authsize)
965                         link_tbl_ptr--;
966
967                 link_tbl_ptr->j_extent = 0;
968                 link_tbl_ptr++;
969                 link_tbl_ptr->j_extent = DESC_PTR_LNKTBL_RETURN;
970                 link_tbl_ptr->len = cpu_to_be16(authsize);
971
972                 /* icv data follows link tables */
973                 link_tbl_ptr->ptr = cpu_to_be32((struct talitos_ptr *)
974                                                 edesc->dma_link_tbl +
975                                                 edesc->src_nents +
976                                                 edesc->dst_nents + 1);
977
978                 desc->ptr[5].j_extent |= DESC_PTR_LNKTBL_JUMP;
979                 dma_sync_single_for_device(ctx->dev, edesc->dma_link_tbl,
980                                            edesc->dma_len, DMA_BIDIRECTIONAL);
981         }
982
983         /* iv out */
984         map_single_talitos_ptr(dev, &desc->ptr[6], ivsize, ctx->iv, 0,
985                                DMA_FROM_DEVICE);
986
987         ret = talitos_submit(dev, desc, callback, areq);
988         if (ret != -EINPROGRESS) {
989                 ipsec_esp_unmap(dev, edesc, areq);
990                 kfree(edesc);
991         }
992         return ret;
993 }
994
995
996 /*
997  * derive number of elements in scatterlist
998  */
999 static int sg_count(struct scatterlist *sg_list, int nbytes)
1000 {
1001         struct scatterlist *sg = sg_list;
1002         int sg_nents = 0;
1003
1004         while (nbytes) {
1005                 sg_nents++;
1006                 nbytes -= sg->length;
1007                 sg = sg_next(sg);
1008         }
1009
1010         return sg_nents;
1011 }
1012
1013 /*
1014  * allocate and map the ipsec_esp extended descriptor
1015  */
1016 static struct ipsec_esp_edesc *ipsec_esp_edesc_alloc(struct aead_request *areq,
1017                                                      int icv_stashing)
1018 {
1019         struct crypto_aead *authenc = crypto_aead_reqtfm(areq);
1020         struct talitos_ctx *ctx = crypto_aead_ctx(authenc);
1021         struct ipsec_esp_edesc *edesc;
1022         int src_nents, dst_nents, alloc_len, dma_len;
1023         gfp_t flags = areq->base.flags & CRYPTO_TFM_REQ_MAY_SLEEP ? GFP_KERNEL :
1024                       GFP_ATOMIC;
1025
1026         if (areq->cryptlen + ctx->authsize > TALITOS_MAX_DATA_LEN) {
1027                 dev_err(ctx->dev, "cryptlen exceeds h/w max limit\n");
1028                 return ERR_PTR(-EINVAL);
1029         }
1030
1031         src_nents = sg_count(areq->src, areq->cryptlen + ctx->authsize);
1032         src_nents = (src_nents == 1) ? 0 : src_nents;
1033
1034         if (areq->dst == areq->src) {
1035                 dst_nents = src_nents;
1036         } else {
1037                 dst_nents = sg_count(areq->dst, areq->cryptlen + ctx->authsize);
1038                 dst_nents = (dst_nents == 1) ? 0 : dst_nents;
1039         }
1040
1041         /*
1042          * allocate space for base edesc plus the link tables,
1043          * allowing for a separate entry for the generated ICV (+ 1),
1044          * and the ICV data itself
1045          */
1046         alloc_len = sizeof(struct ipsec_esp_edesc);
1047         if (src_nents || dst_nents) {
1048                 dma_len = (src_nents + dst_nents + 1) *
1049                                  sizeof(struct talitos_ptr) + ctx->authsize;
1050                 alloc_len += dma_len;
1051         } else {
1052                 dma_len = 0;
1053                 alloc_len += icv_stashing ? ctx->authsize : 0;
1054         }
1055
1056         edesc = kmalloc(alloc_len, GFP_DMA | flags);
1057         if (!edesc) {
1058                 dev_err(ctx->dev, "could not allocate edescriptor\n");
1059                 return ERR_PTR(-ENOMEM);
1060         }
1061
1062         edesc->src_nents = src_nents;
1063         edesc->dst_nents = dst_nents;
1064         edesc->dma_len = dma_len;
1065         edesc->dma_link_tbl = dma_map_single(ctx->dev, &edesc->link_tbl[0],
1066                                              edesc->dma_len, DMA_BIDIRECTIONAL);
1067
1068         return edesc;
1069 }
1070
1071 static int aead_authenc_encrypt(struct aead_request *req)
1072 {
1073         struct crypto_aead *authenc = crypto_aead_reqtfm(req);
1074         struct talitos_ctx *ctx = crypto_aead_ctx(authenc);
1075         struct ipsec_esp_edesc *edesc;
1076
1077         /* allocate extended descriptor */
1078         edesc = ipsec_esp_edesc_alloc(req, 0);
1079         if (IS_ERR(edesc))
1080                 return PTR_ERR(edesc);
1081
1082         /* set encrypt */
1083         edesc->desc.hdr = ctx->desc_hdr_template | DESC_HDR_MODE0_ENCRYPT;
1084
1085         return ipsec_esp(edesc, req, NULL, 0, ipsec_esp_encrypt_done);
1086 }
1087
1088 static int aead_authenc_decrypt(struct aead_request *req)
1089 {
1090         struct crypto_aead *authenc = crypto_aead_reqtfm(req);
1091         struct talitos_ctx *ctx = crypto_aead_ctx(authenc);
1092         unsigned int authsize = ctx->authsize;
1093         struct ipsec_esp_edesc *edesc;
1094         struct scatterlist *sg;
1095         void *icvdata;
1096
1097         req->cryptlen -= authsize;
1098
1099         /* allocate extended descriptor */
1100         edesc = ipsec_esp_edesc_alloc(req, 1);
1101         if (IS_ERR(edesc))
1102                 return PTR_ERR(edesc);
1103
1104         /* stash incoming ICV for later cmp with ICV generated by the h/w */
1105         if (edesc->dma_len)
1106                 icvdata = &edesc->link_tbl[edesc->src_nents +
1107                                            edesc->dst_nents + 1];
1108         else
1109                 icvdata = &edesc->link_tbl[0];
1110
1111         sg = sg_last(req->src, edesc->src_nents ? : 1);
1112
1113         memcpy(icvdata, (char *)sg_virt(sg) + sg->length - ctx->authsize,
1114                ctx->authsize);
1115
1116         /* decrypt */
1117         edesc->desc.hdr = ctx->desc_hdr_template | DESC_HDR_DIR_INBOUND;
1118
1119         return ipsec_esp(edesc, req, NULL, 0, ipsec_esp_decrypt_done);
1120 }
1121
1122 static int aead_authenc_givencrypt(
1123         struct aead_givcrypt_request *req)
1124 {
1125         struct aead_request *areq = &req->areq;
1126         struct crypto_aead *authenc = crypto_aead_reqtfm(areq);
1127         struct talitos_ctx *ctx = crypto_aead_ctx(authenc);
1128         struct ipsec_esp_edesc *edesc;
1129
1130         /* allocate extended descriptor */
1131         edesc = ipsec_esp_edesc_alloc(areq, 0);
1132         if (IS_ERR(edesc))
1133                 return PTR_ERR(edesc);
1134
1135         /* set encrypt */
1136         edesc->desc.hdr = ctx->desc_hdr_template | DESC_HDR_MODE0_ENCRYPT;
1137
1138         memcpy(req->giv, ctx->iv, crypto_aead_ivsize(authenc));
1139
1140         return ipsec_esp(edesc, areq, req->giv, req->seq,
1141                          ipsec_esp_encrypt_done);
1142 }
1143
1144 struct talitos_alg_template {
1145         char name[CRYPTO_MAX_ALG_NAME];
1146         char driver_name[CRYPTO_MAX_ALG_NAME];
1147         unsigned int blocksize;
1148         struct aead_alg aead;
1149         struct device *dev;
1150         __be32 desc_hdr_template;
1151 };
1152
1153 static struct talitos_alg_template driver_algs[] = {
1154         /* single-pass ipsec_esp descriptor */
1155         {
1156                 .name = "authenc(hmac(sha1),cbc(aes))",
1157                 .driver_name = "authenc-hmac-sha1-cbc-aes-talitos",
1158                 .blocksize = AES_BLOCK_SIZE,
1159                 .aead = {
1160                         .setkey = aead_authenc_setkey,
1161                         .setauthsize = aead_authenc_setauthsize,
1162                         .encrypt = aead_authenc_encrypt,
1163                         .decrypt = aead_authenc_decrypt,
1164                         .givencrypt = aead_authenc_givencrypt,
1165                         .geniv = "<built-in>",
1166                         .ivsize = AES_BLOCK_SIZE,
1167                         .maxauthsize = SHA1_DIGEST_SIZE,
1168                         },
1169                 .desc_hdr_template = DESC_HDR_TYPE_IPSEC_ESP |
1170                                      DESC_HDR_SEL0_AESU |
1171                                      DESC_HDR_MODE0_AESU_CBC |
1172                                      DESC_HDR_SEL1_MDEUA |
1173                                      DESC_HDR_MODE1_MDEU_INIT |
1174                                      DESC_HDR_MODE1_MDEU_PAD |
1175                                      DESC_HDR_MODE1_MDEU_SHA1_HMAC,
1176         },
1177         {
1178                 .name = "authenc(hmac(sha1),cbc(des3_ede))",
1179                 .driver_name = "authenc-hmac-sha1-cbc-3des-talitos",
1180                 .blocksize = DES3_EDE_BLOCK_SIZE,
1181                 .aead = {
1182                         .setkey = aead_authenc_setkey,
1183                         .setauthsize = aead_authenc_setauthsize,
1184                         .encrypt = aead_authenc_encrypt,
1185                         .decrypt = aead_authenc_decrypt,
1186                         .givencrypt = aead_authenc_givencrypt,
1187                         .geniv = "<built-in>",
1188                         .ivsize = DES3_EDE_BLOCK_SIZE,
1189                         .maxauthsize = SHA1_DIGEST_SIZE,
1190                         },
1191                 .desc_hdr_template = DESC_HDR_TYPE_IPSEC_ESP |
1192                                      DESC_HDR_SEL0_DEU |
1193                                      DESC_HDR_MODE0_DEU_CBC |
1194                                      DESC_HDR_MODE0_DEU_3DES |
1195                                      DESC_HDR_SEL1_MDEUA |
1196                                      DESC_HDR_MODE1_MDEU_INIT |
1197                                      DESC_HDR_MODE1_MDEU_PAD |
1198                                      DESC_HDR_MODE1_MDEU_SHA1_HMAC,
1199         },
1200         {
1201                 .name = "authenc(hmac(sha256),cbc(aes))",
1202                 .driver_name = "authenc-hmac-sha256-cbc-aes-talitos",
1203                 .blocksize = AES_BLOCK_SIZE,
1204                 .aead = {
1205                         .setkey = aead_authenc_setkey,
1206                         .setauthsize = aead_authenc_setauthsize,
1207                         .encrypt = aead_authenc_encrypt,
1208                         .decrypt = aead_authenc_decrypt,
1209                         .givencrypt = aead_authenc_givencrypt,
1210                         .geniv = "<built-in>",
1211                         .ivsize = AES_BLOCK_SIZE,
1212                         .maxauthsize = SHA256_DIGEST_SIZE,
1213                         },
1214                 .desc_hdr_template = DESC_HDR_TYPE_IPSEC_ESP |
1215                                      DESC_HDR_SEL0_AESU |
1216                                      DESC_HDR_MODE0_AESU_CBC |
1217                                      DESC_HDR_SEL1_MDEUA |
1218                                      DESC_HDR_MODE1_MDEU_INIT |
1219                                      DESC_HDR_MODE1_MDEU_PAD |
1220                                      DESC_HDR_MODE1_MDEU_SHA256_HMAC,
1221         },
1222         {
1223                 .name = "authenc(hmac(sha256),cbc(des3_ede))",
1224                 .driver_name = "authenc-hmac-sha256-cbc-3des-talitos",
1225                 .blocksize = DES3_EDE_BLOCK_SIZE,
1226                 .aead = {
1227                         .setkey = aead_authenc_setkey,
1228                         .setauthsize = aead_authenc_setauthsize,
1229                         .encrypt = aead_authenc_encrypt,
1230                         .decrypt = aead_authenc_decrypt,
1231                         .givencrypt = aead_authenc_givencrypt,
1232                         .geniv = "<built-in>",
1233                         .ivsize = DES3_EDE_BLOCK_SIZE,
1234                         .maxauthsize = SHA256_DIGEST_SIZE,
1235                         },
1236                 .desc_hdr_template = DESC_HDR_TYPE_IPSEC_ESP |
1237                                      DESC_HDR_SEL0_DEU |
1238                                      DESC_HDR_MODE0_DEU_CBC |
1239                                      DESC_HDR_MODE0_DEU_3DES |
1240                                      DESC_HDR_SEL1_MDEUA |
1241                                      DESC_HDR_MODE1_MDEU_INIT |
1242                                      DESC_HDR_MODE1_MDEU_PAD |
1243                                      DESC_HDR_MODE1_MDEU_SHA256_HMAC,
1244         },
1245         {
1246                 .name = "authenc(hmac(md5),cbc(aes))",
1247                 .driver_name = "authenc-hmac-md5-cbc-aes-talitos",
1248                 .blocksize = AES_BLOCK_SIZE,
1249                 .aead = {
1250                         .setkey = aead_authenc_setkey,
1251                         .setauthsize = aead_authenc_setauthsize,
1252                         .encrypt = aead_authenc_encrypt,
1253                         .decrypt = aead_authenc_decrypt,
1254                         .givencrypt = aead_authenc_givencrypt,
1255                         .geniv = "<built-in>",
1256                         .ivsize = AES_BLOCK_SIZE,
1257                         .maxauthsize = MD5_DIGEST_SIZE,
1258                         },
1259                 .desc_hdr_template = DESC_HDR_TYPE_IPSEC_ESP |
1260                                      DESC_HDR_SEL0_AESU |
1261                                      DESC_HDR_MODE0_AESU_CBC |
1262                                      DESC_HDR_SEL1_MDEUA |
1263                                      DESC_HDR_MODE1_MDEU_INIT |
1264                                      DESC_HDR_MODE1_MDEU_PAD |
1265                                      DESC_HDR_MODE1_MDEU_MD5_HMAC,
1266         },
1267         {
1268                 .name = "authenc(hmac(md5),cbc(des3_ede))",
1269                 .driver_name = "authenc-hmac-md5-cbc-3des-talitos",
1270                 .blocksize = DES3_EDE_BLOCK_SIZE,
1271                 .aead = {
1272                         .setkey = aead_authenc_setkey,
1273                         .setauthsize = aead_authenc_setauthsize,
1274                         .encrypt = aead_authenc_encrypt,
1275                         .decrypt = aead_authenc_decrypt,
1276                         .givencrypt = aead_authenc_givencrypt,
1277                         .geniv = "<built-in>",
1278                         .ivsize = DES3_EDE_BLOCK_SIZE,
1279                         .maxauthsize = MD5_DIGEST_SIZE,
1280                         },
1281                 .desc_hdr_template = DESC_HDR_TYPE_IPSEC_ESP |
1282                                      DESC_HDR_SEL0_DEU |
1283                                      DESC_HDR_MODE0_DEU_CBC |
1284                                      DESC_HDR_MODE0_DEU_3DES |
1285                                      DESC_HDR_SEL1_MDEUA |
1286                                      DESC_HDR_MODE1_MDEU_INIT |
1287                                      DESC_HDR_MODE1_MDEU_PAD |
1288                                      DESC_HDR_MODE1_MDEU_MD5_HMAC,
1289         }
1290 };
1291
1292 struct talitos_crypto_alg {
1293         struct list_head entry;
1294         struct device *dev;
1295         __be32 desc_hdr_template;
1296         struct crypto_alg crypto_alg;
1297 };
1298
1299 static int talitos_cra_init(struct crypto_tfm *tfm)
1300 {
1301         struct crypto_alg *alg = tfm->__crt_alg;
1302         struct talitos_crypto_alg *talitos_alg =
1303                  container_of(alg, struct talitos_crypto_alg, crypto_alg);
1304         struct talitos_ctx *ctx = crypto_tfm_ctx(tfm);
1305
1306         /* update context with ptr to dev */
1307         ctx->dev = talitos_alg->dev;
1308         /* copy descriptor header template value */
1309         ctx->desc_hdr_template = talitos_alg->desc_hdr_template;
1310
1311         /* random first IV */
1312         get_random_bytes(ctx->iv, TALITOS_MAX_IV_LENGTH);
1313
1314         return 0;
1315 }
1316
1317 /*
1318  * given the alg's descriptor header template, determine whether descriptor
1319  * type and primary/secondary execution units required match the hw
1320  * capabilities description provided in the device tree node.
1321  */
1322 static int hw_supports(struct device *dev, __be32 desc_hdr_template)
1323 {
1324         struct talitos_private *priv = dev_get_drvdata(dev);
1325         int ret;
1326
1327         ret = (1 << DESC_TYPE(desc_hdr_template) & priv->desc_types) &&
1328               (1 << PRIMARY_EU(desc_hdr_template) & priv->exec_units);
1329
1330         if (SECONDARY_EU(desc_hdr_template))
1331                 ret = ret && (1 << SECONDARY_EU(desc_hdr_template)
1332                               & priv->exec_units);
1333
1334         return ret;
1335 }
1336
1337 static int __devexit talitos_remove(struct of_device *ofdev)
1338 {
1339         struct device *dev = &ofdev->dev;
1340         struct talitos_private *priv = dev_get_drvdata(dev);
1341         struct talitos_crypto_alg *t_alg, *n;
1342         int i;
1343
1344         list_for_each_entry_safe(t_alg, n, &priv->alg_list, entry) {
1345                 crypto_unregister_alg(&t_alg->crypto_alg);
1346                 list_del(&t_alg->entry);
1347                 kfree(t_alg);
1348         }
1349
1350         if (hw_supports(dev, DESC_HDR_SEL0_RNG))
1351                 talitos_unregister_rng(dev);
1352
1353         kfree(priv->submit_count);
1354         kfree(priv->tail);
1355         kfree(priv->head);
1356
1357         if (priv->fifo)
1358                 for (i = 0; i < priv->num_channels; i++)
1359                         kfree(priv->fifo[i]);
1360
1361         kfree(priv->fifo);
1362         kfree(priv->head_lock);
1363         kfree(priv->tail_lock);
1364
1365         if (priv->irq != NO_IRQ) {
1366                 free_irq(priv->irq, dev);
1367                 irq_dispose_mapping(priv->irq);
1368         }
1369
1370         tasklet_kill(&priv->done_task);
1371         tasklet_kill(&priv->error_task);
1372
1373         iounmap(priv->reg);
1374
1375         dev_set_drvdata(dev, NULL);
1376
1377         kfree(priv);
1378
1379         return 0;
1380 }
1381
1382 static struct talitos_crypto_alg *talitos_alg_alloc(struct device *dev,
1383                                                     struct talitos_alg_template
1384                                                            *template)
1385 {
1386         struct talitos_crypto_alg *t_alg;
1387         struct crypto_alg *alg;
1388
1389         t_alg = kzalloc(sizeof(struct talitos_crypto_alg), GFP_KERNEL);
1390         if (!t_alg)
1391                 return ERR_PTR(-ENOMEM);
1392
1393         alg = &t_alg->crypto_alg;
1394
1395         snprintf(alg->cra_name, CRYPTO_MAX_ALG_NAME, "%s", template->name);
1396         snprintf(alg->cra_driver_name, CRYPTO_MAX_ALG_NAME, "%s",
1397                  template->driver_name);
1398         alg->cra_module = THIS_MODULE;
1399         alg->cra_init = talitos_cra_init;
1400         alg->cra_priority = TALITOS_CRA_PRIORITY;
1401         alg->cra_flags = CRYPTO_ALG_TYPE_AEAD | CRYPTO_ALG_ASYNC;
1402         alg->cra_blocksize = template->blocksize;
1403         alg->cra_alignmask = 0;
1404         alg->cra_type = &crypto_aead_type;
1405         alg->cra_ctxsize = sizeof(struct talitos_ctx);
1406         alg->cra_u.aead = template->aead;
1407
1408         t_alg->desc_hdr_template = template->desc_hdr_template;
1409         t_alg->dev = dev;
1410
1411         return t_alg;
1412 }
1413
1414 static int talitos_probe(struct of_device *ofdev,
1415                          const struct of_device_id *match)
1416 {
1417         struct device *dev = &ofdev->dev;
1418         struct device_node *np = ofdev->node;
1419         struct talitos_private *priv;
1420         const unsigned int *prop;
1421         int i, err;
1422
1423         priv = kzalloc(sizeof(struct talitos_private), GFP_KERNEL);
1424         if (!priv)
1425                 return -ENOMEM;
1426
1427         dev_set_drvdata(dev, priv);
1428
1429         priv->ofdev = ofdev;
1430
1431         tasklet_init(&priv->done_task, talitos_done, (unsigned long)dev);
1432         tasklet_init(&priv->error_task, talitos_error, (unsigned long)dev);
1433
1434         priv->irq = irq_of_parse_and_map(np, 0);
1435
1436         if (priv->irq == NO_IRQ) {
1437                 dev_err(dev, "failed to map irq\n");
1438                 err = -EINVAL;
1439                 goto err_out;
1440         }
1441
1442         /* get the irq line */
1443         err = request_irq(priv->irq, talitos_interrupt, 0,
1444                           dev_driver_string(dev), dev);
1445         if (err) {
1446                 dev_err(dev, "failed to request irq %d\n", priv->irq);
1447                 irq_dispose_mapping(priv->irq);
1448                 priv->irq = NO_IRQ;
1449                 goto err_out;
1450         }
1451
1452         priv->reg = of_iomap(np, 0);
1453         if (!priv->reg) {
1454                 dev_err(dev, "failed to of_iomap\n");
1455                 err = -ENOMEM;
1456                 goto err_out;
1457         }
1458
1459         /* get SEC version capabilities from device tree */
1460         prop = of_get_property(np, "fsl,num-channels", NULL);
1461         if (prop)
1462                 priv->num_channels = *prop;
1463
1464         prop = of_get_property(np, "fsl,channel-fifo-len", NULL);
1465         if (prop)
1466                 priv->chfifo_len = *prop;
1467
1468         prop = of_get_property(np, "fsl,exec-units-mask", NULL);
1469         if (prop)
1470                 priv->exec_units = *prop;
1471
1472         prop = of_get_property(np, "fsl,descriptor-types-mask", NULL);
1473         if (prop)
1474                 priv->desc_types = *prop;
1475
1476         if (!is_power_of_2(priv->num_channels) || !priv->chfifo_len ||
1477             !priv->exec_units || !priv->desc_types) {
1478                 dev_err(dev, "invalid property data in device tree node\n");
1479                 err = -EINVAL;
1480                 goto err_out;
1481         }
1482
1483         priv->head_lock = kmalloc(sizeof(spinlock_t) * priv->num_channels,
1484                                   GFP_KERNEL);
1485         priv->tail_lock = kmalloc(sizeof(spinlock_t) * priv->num_channels,
1486                                   GFP_KERNEL);
1487         if (!priv->head_lock || !priv->tail_lock) {
1488                 dev_err(dev, "failed to allocate fifo locks\n");
1489                 err = -ENOMEM;
1490                 goto err_out;
1491         }
1492
1493         for (i = 0; i < priv->num_channels; i++) {
1494                 spin_lock_init(&priv->head_lock[i]);
1495                 spin_lock_init(&priv->tail_lock[i]);
1496         }
1497
1498         priv->fifo = kmalloc(sizeof(struct talitos_request *) *
1499                              priv->num_channels, GFP_KERNEL);
1500         if (!priv->fifo) {
1501                 dev_err(dev, "failed to allocate request fifo\n");
1502                 err = -ENOMEM;
1503                 goto err_out;
1504         }
1505
1506         priv->fifo_len = roundup_pow_of_two(priv->chfifo_len);
1507
1508         for (i = 0; i < priv->num_channels; i++) {
1509                 priv->fifo[i] = kzalloc(sizeof(struct talitos_request) *
1510                                         priv->fifo_len, GFP_KERNEL);
1511                 if (!priv->fifo[i]) {
1512                         dev_err(dev, "failed to allocate request fifo %d\n", i);
1513                         err = -ENOMEM;
1514                         goto err_out;
1515                 }
1516         }
1517
1518         priv->submit_count = kmalloc(sizeof(atomic_t) * priv->num_channels,
1519                                      GFP_KERNEL);
1520         if (!priv->submit_count) {
1521                 dev_err(dev, "failed to allocate fifo submit count space\n");
1522                 err = -ENOMEM;
1523                 goto err_out;
1524         }
1525         for (i = 0; i < priv->num_channels; i++)
1526                 atomic_set(&priv->submit_count[i], -priv->chfifo_len);
1527
1528         priv->head = kzalloc(sizeof(int) * priv->num_channels, GFP_KERNEL);
1529         priv->tail = kzalloc(sizeof(int) * priv->num_channels, GFP_KERNEL);
1530         if (!priv->head || !priv->tail) {
1531                 dev_err(dev, "failed to allocate request index space\n");
1532                 err = -ENOMEM;
1533                 goto err_out;
1534         }
1535
1536         /* reset and initialize the h/w */
1537         err = init_device(dev);
1538         if (err) {
1539                 dev_err(dev, "failed to initialize device\n");
1540                 goto err_out;
1541         }
1542
1543         /* register the RNG, if available */
1544         if (hw_supports(dev, DESC_HDR_SEL0_RNG)) {
1545                 err = talitos_register_rng(dev);
1546                 if (err) {
1547                         dev_err(dev, "failed to register hwrng: %d\n", err);
1548                         goto err_out;
1549                 } else
1550                         dev_info(dev, "hwrng\n");
1551         }
1552
1553         /* register crypto algorithms the device supports */
1554         INIT_LIST_HEAD(&priv->alg_list);
1555
1556         for (i = 0; i < ARRAY_SIZE(driver_algs); i++) {
1557                 if (hw_supports(dev, driver_algs[i].desc_hdr_template)) {
1558                         struct talitos_crypto_alg *t_alg;
1559
1560                         t_alg = talitos_alg_alloc(dev, &driver_algs[i]);
1561                         if (IS_ERR(t_alg)) {
1562                                 err = PTR_ERR(t_alg);
1563                                 goto err_out;
1564                         }
1565
1566                         err = crypto_register_alg(&t_alg->crypto_alg);
1567                         if (err) {
1568                                 dev_err(dev, "%s alg registration failed\n",
1569                                         t_alg->crypto_alg.cra_driver_name);
1570                                 kfree(t_alg);
1571                         } else {
1572                                 list_add_tail(&t_alg->entry, &priv->alg_list);
1573                                 dev_info(dev, "%s\n",
1574                                          t_alg->crypto_alg.cra_driver_name);
1575                         }
1576                 }
1577         }
1578
1579         return 0;
1580
1581 err_out:
1582         talitos_remove(ofdev);
1583
1584         return err;
1585 }
1586
1587 static struct of_device_id talitos_match[] = {
1588         {
1589                 .compatible = "fsl,sec2.0",
1590         },
1591         {},
1592 };
1593 MODULE_DEVICE_TABLE(of, talitos_match);
1594
1595 static struct of_platform_driver talitos_driver = {
1596         .name = "talitos",
1597         .match_table = talitos_match,
1598         .probe = talitos_probe,
1599         .remove = __devexit_p(talitos_remove),
1600 };
1601
1602 static int __init talitos_init(void)
1603 {
1604         return of_register_platform_driver(&talitos_driver);
1605 }
1606 module_init(talitos_init);
1607
1608 static void __exit talitos_exit(void)
1609 {
1610         of_unregister_platform_driver(&talitos_driver);
1611 }
1612 module_exit(talitos_exit);
1613
1614 MODULE_LICENSE("GPL");
1615 MODULE_AUTHOR("Kim Phillips <kim.phillips@freescale.com>");
1616 MODULE_DESCRIPTION("Freescale integrated security engine (SEC) driver");