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