xref: /freebsd/sys/dev/safe/safe.c (revision 47dd1d1b619cc035b82b49a91a25544309ff95ae)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2003 Sam Leffler, Errno Consulting
5  * Copyright (c) 2003 Global Technology Associates, Inc.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
32 
33 /*
34  * SafeNet SafeXcel-1141 hardware crypto accelerator
35  */
36 #include "opt_safe.h"
37 
38 #include <sys/param.h>
39 #include <sys/systm.h>
40 #include <sys/proc.h>
41 #include <sys/errno.h>
42 #include <sys/malloc.h>
43 #include <sys/kernel.h>
44 #include <sys/mbuf.h>
45 #include <sys/module.h>
46 #include <sys/lock.h>
47 #include <sys/mutex.h>
48 #include <sys/sysctl.h>
49 #include <sys/endian.h>
50 
51 #include <vm/vm.h>
52 #include <vm/pmap.h>
53 
54 #include <machine/bus.h>
55 #include <machine/resource.h>
56 #include <sys/bus.h>
57 #include <sys/rman.h>
58 
59 #include <crypto/sha1.h>
60 #include <opencrypto/cryptodev.h>
61 #include <opencrypto/cryptosoft.h>
62 #include <sys/md5.h>
63 #include <sys/random.h>
64 #include <sys/kobj.h>
65 
66 #include "cryptodev_if.h"
67 
68 #include <dev/pci/pcivar.h>
69 #include <dev/pci/pcireg.h>
70 
71 #ifdef SAFE_RNDTEST
72 #include <dev/rndtest/rndtest.h>
73 #endif
74 #include <dev/safe/safereg.h>
75 #include <dev/safe/safevar.h>
76 
77 #ifndef bswap32
78 #define	bswap32	NTOHL
79 #endif
80 
81 /*
82  * Prototypes and count for the pci_device structure
83  */
84 static	int safe_probe(device_t);
85 static	int safe_attach(device_t);
86 static	int safe_detach(device_t);
87 static	int safe_suspend(device_t);
88 static	int safe_resume(device_t);
89 static	int safe_shutdown(device_t);
90 
91 static	int safe_newsession(device_t, u_int32_t *, struct cryptoini *);
92 static	int safe_freesession(device_t, u_int64_t);
93 static	int safe_process(device_t, struct cryptop *, int);
94 
95 static device_method_t safe_methods[] = {
96 	/* Device interface */
97 	DEVMETHOD(device_probe,		safe_probe),
98 	DEVMETHOD(device_attach,	safe_attach),
99 	DEVMETHOD(device_detach,	safe_detach),
100 	DEVMETHOD(device_suspend,	safe_suspend),
101 	DEVMETHOD(device_resume,	safe_resume),
102 	DEVMETHOD(device_shutdown,	safe_shutdown),
103 
104 	/* crypto device methods */
105 	DEVMETHOD(cryptodev_newsession,	safe_newsession),
106 	DEVMETHOD(cryptodev_freesession,safe_freesession),
107 	DEVMETHOD(cryptodev_process,	safe_process),
108 
109 	DEVMETHOD_END
110 };
111 static driver_t safe_driver = {
112 	"safe",
113 	safe_methods,
114 	sizeof (struct safe_softc)
115 };
116 static devclass_t safe_devclass;
117 
118 DRIVER_MODULE(safe, pci, safe_driver, safe_devclass, 0, 0);
119 MODULE_DEPEND(safe, crypto, 1, 1, 1);
120 #ifdef SAFE_RNDTEST
121 MODULE_DEPEND(safe, rndtest, 1, 1, 1);
122 #endif
123 
124 static	void safe_intr(void *);
125 static	void safe_callback(struct safe_softc *, struct safe_ringentry *);
126 static	void safe_feed(struct safe_softc *, struct safe_ringentry *);
127 static	void safe_mcopy(struct mbuf *, struct mbuf *, u_int);
128 #ifndef SAFE_NO_RNG
129 static	void safe_rng_init(struct safe_softc *);
130 static	void safe_rng(void *);
131 #endif /* SAFE_NO_RNG */
132 static	int safe_dma_malloc(struct safe_softc *, bus_size_t,
133 	        struct safe_dma_alloc *, int);
134 #define	safe_dma_sync(_dma, _flags) \
135 	bus_dmamap_sync((_dma)->dma_tag, (_dma)->dma_map, (_flags))
136 static	void safe_dma_free(struct safe_softc *, struct safe_dma_alloc *);
137 static	int safe_dmamap_aligned(const struct safe_operand *);
138 static	int safe_dmamap_uniform(const struct safe_operand *);
139 
140 static	void safe_reset_board(struct safe_softc *);
141 static	void safe_init_board(struct safe_softc *);
142 static	void safe_init_pciregs(device_t dev);
143 static	void safe_cleanchip(struct safe_softc *);
144 static	void safe_totalreset(struct safe_softc *);
145 
146 static	int safe_free_entry(struct safe_softc *, struct safe_ringentry *);
147 
148 static SYSCTL_NODE(_hw, OID_AUTO, safe, CTLFLAG_RD, 0,
149     "SafeNet driver parameters");
150 
151 #ifdef SAFE_DEBUG
152 static	void safe_dump_dmastatus(struct safe_softc *, const char *);
153 static	void safe_dump_ringstate(struct safe_softc *, const char *);
154 static	void safe_dump_intrstate(struct safe_softc *, const char *);
155 static	void safe_dump_request(struct safe_softc *, const char *,
156 		struct safe_ringentry *);
157 
158 static	struct safe_softc *safec;		/* for use by hw.safe.dump */
159 
160 static	int safe_debug = 0;
161 SYSCTL_INT(_hw_safe, OID_AUTO, debug, CTLFLAG_RW, &safe_debug,
162 	    0, "control debugging msgs");
163 #define	DPRINTF(_x)	if (safe_debug) printf _x
164 #else
165 #define	DPRINTF(_x)
166 #endif
167 
168 #define	READ_REG(sc,r) \
169 	bus_space_read_4((sc)->sc_st, (sc)->sc_sh, (r))
170 
171 #define WRITE_REG(sc,reg,val) \
172 	bus_space_write_4((sc)->sc_st, (sc)->sc_sh, reg, val)
173 
174 struct safe_stats safestats;
175 SYSCTL_STRUCT(_hw_safe, OID_AUTO, stats, CTLFLAG_RD, &safestats,
176 	    safe_stats, "driver statistics");
177 #ifndef SAFE_NO_RNG
178 static	int safe_rnginterval = 1;		/* poll once a second */
179 SYSCTL_INT(_hw_safe, OID_AUTO, rnginterval, CTLFLAG_RW, &safe_rnginterval,
180 	    0, "RNG polling interval (secs)");
181 static	int safe_rngbufsize = 16;		/* 64 bytes each poll  */
182 SYSCTL_INT(_hw_safe, OID_AUTO, rngbufsize, CTLFLAG_RW, &safe_rngbufsize,
183 	    0, "RNG polling buffer size (32-bit words)");
184 static	int safe_rngmaxalarm = 8;		/* max alarms before reset */
185 SYSCTL_INT(_hw_safe, OID_AUTO, rngmaxalarm, CTLFLAG_RW, &safe_rngmaxalarm,
186 	    0, "RNG max alarms before reset");
187 #endif /* SAFE_NO_RNG */
188 
189 static int
190 safe_probe(device_t dev)
191 {
192 	if (pci_get_vendor(dev) == PCI_VENDOR_SAFENET &&
193 	    pci_get_device(dev) == PCI_PRODUCT_SAFEXCEL)
194 		return (BUS_PROBE_DEFAULT);
195 	return (ENXIO);
196 }
197 
198 static const char*
199 safe_partname(struct safe_softc *sc)
200 {
201 	/* XXX sprintf numbers when not decoded */
202 	switch (pci_get_vendor(sc->sc_dev)) {
203 	case PCI_VENDOR_SAFENET:
204 		switch (pci_get_device(sc->sc_dev)) {
205 		case PCI_PRODUCT_SAFEXCEL: return "SafeNet SafeXcel-1141";
206 		}
207 		return "SafeNet unknown-part";
208 	}
209 	return "Unknown-vendor unknown-part";
210 }
211 
212 #ifndef SAFE_NO_RNG
213 static void
214 default_harvest(struct rndtest_state *rsp, void *buf, u_int count)
215 {
216 	/* MarkM: FIX!! Check that this does not swamp the harvester! */
217 	random_harvest_queue(buf, count, count*NBBY/2, RANDOM_PURE_SAFE);
218 }
219 #endif /* SAFE_NO_RNG */
220 
221 static int
222 safe_attach(device_t dev)
223 {
224 	struct safe_softc *sc = device_get_softc(dev);
225 	u_int32_t raddr;
226 	u_int32_t i, devinfo;
227 	int rid;
228 
229 	bzero(sc, sizeof (*sc));
230 	sc->sc_dev = dev;
231 
232 	/* XXX handle power management */
233 
234 	pci_enable_busmaster(dev);
235 
236 	/*
237 	 * Setup memory-mapping of PCI registers.
238 	 */
239 	rid = BS_BAR;
240 	sc->sc_sr = bus_alloc_resource_any(dev, SYS_RES_MEMORY, &rid,
241 					   RF_ACTIVE);
242 	if (sc->sc_sr == NULL) {
243 		device_printf(dev, "cannot map register space\n");
244 		goto bad;
245 	}
246 	sc->sc_st = rman_get_bustag(sc->sc_sr);
247 	sc->sc_sh = rman_get_bushandle(sc->sc_sr);
248 
249 	/*
250 	 * Arrange interrupt line.
251 	 */
252 	rid = 0;
253 	sc->sc_irq = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid,
254 					    RF_SHAREABLE|RF_ACTIVE);
255 	if (sc->sc_irq == NULL) {
256 		device_printf(dev, "could not map interrupt\n");
257 		goto bad1;
258 	}
259 	/*
260 	 * NB: Network code assumes we are blocked with splimp()
261 	 *     so make sure the IRQ is mapped appropriately.
262 	 */
263 	if (bus_setup_intr(dev, sc->sc_irq, INTR_TYPE_NET | INTR_MPSAFE,
264 			   NULL, safe_intr, sc, &sc->sc_ih)) {
265 		device_printf(dev, "could not establish interrupt\n");
266 		goto bad2;
267 	}
268 
269 	sc->sc_cid = crypto_get_driverid(dev, CRYPTOCAP_F_HARDWARE);
270 	if (sc->sc_cid < 0) {
271 		device_printf(dev, "could not get crypto driver id\n");
272 		goto bad3;
273 	}
274 
275 	sc->sc_chiprev = READ_REG(sc, SAFE_DEVINFO) &
276 		(SAFE_DEVINFO_REV_MAJ | SAFE_DEVINFO_REV_MIN);
277 
278 	/*
279 	 * Setup DMA descriptor area.
280 	 */
281 	if (bus_dma_tag_create(bus_get_dma_tag(dev),	/* parent */
282 			       1,			/* alignment */
283 			       SAFE_DMA_BOUNDARY,	/* boundary */
284 			       BUS_SPACE_MAXADDR_32BIT,	/* lowaddr */
285 			       BUS_SPACE_MAXADDR,	/* highaddr */
286 			       NULL, NULL,		/* filter, filterarg */
287 			       SAFE_MAX_DMA,		/* maxsize */
288 			       SAFE_MAX_PART,		/* nsegments */
289 			       SAFE_MAX_SSIZE,		/* maxsegsize */
290 			       BUS_DMA_ALLOCNOW,	/* flags */
291 			       NULL, NULL,		/* locking */
292 			       &sc->sc_srcdmat)) {
293 		device_printf(dev, "cannot allocate DMA tag\n");
294 		goto bad4;
295 	}
296 	if (bus_dma_tag_create(bus_get_dma_tag(dev),	/* parent */
297 			       1,			/* alignment */
298 			       SAFE_MAX_DSIZE,		/* boundary */
299 			       BUS_SPACE_MAXADDR_32BIT,	/* lowaddr */
300 			       BUS_SPACE_MAXADDR,	/* highaddr */
301 			       NULL, NULL,		/* filter, filterarg */
302 			       SAFE_MAX_DMA,		/* maxsize */
303 			       SAFE_MAX_PART,		/* nsegments */
304 			       SAFE_MAX_DSIZE,		/* maxsegsize */
305 			       BUS_DMA_ALLOCNOW,	/* flags */
306 			       NULL, NULL,		/* locking */
307 			       &sc->sc_dstdmat)) {
308 		device_printf(dev, "cannot allocate DMA tag\n");
309 		goto bad4;
310 	}
311 
312 	/*
313 	 * Allocate packet engine descriptors.
314 	 */
315 	if (safe_dma_malloc(sc,
316 	    SAFE_MAX_NQUEUE * sizeof (struct safe_ringentry),
317 	    &sc->sc_ringalloc, 0)) {
318 		device_printf(dev, "cannot allocate PE descriptor ring\n");
319 		bus_dma_tag_destroy(sc->sc_srcdmat);
320 		goto bad4;
321 	}
322 	/*
323 	 * Hookup the static portion of all our data structures.
324 	 */
325 	sc->sc_ring = (struct safe_ringentry *) sc->sc_ringalloc.dma_vaddr;
326 	sc->sc_ringtop = sc->sc_ring + SAFE_MAX_NQUEUE;
327 	sc->sc_front = sc->sc_ring;
328 	sc->sc_back = sc->sc_ring;
329 	raddr = sc->sc_ringalloc.dma_paddr;
330 	bzero(sc->sc_ring, SAFE_MAX_NQUEUE * sizeof(struct safe_ringentry));
331 	for (i = 0; i < SAFE_MAX_NQUEUE; i++) {
332 		struct safe_ringentry *re = &sc->sc_ring[i];
333 
334 		re->re_desc.d_sa = raddr +
335 			offsetof(struct safe_ringentry, re_sa);
336 		re->re_sa.sa_staterec = raddr +
337 			offsetof(struct safe_ringentry, re_sastate);
338 
339 		raddr += sizeof (struct safe_ringentry);
340 	}
341 	mtx_init(&sc->sc_ringmtx, device_get_nameunit(dev),
342 		"packet engine ring", MTX_DEF);
343 
344 	/*
345 	 * Allocate scatter and gather particle descriptors.
346 	 */
347 	if (safe_dma_malloc(sc, SAFE_TOTAL_SPART * sizeof (struct safe_pdesc),
348 	    &sc->sc_spalloc, 0)) {
349 		device_printf(dev, "cannot allocate source particle "
350 			"descriptor ring\n");
351 		mtx_destroy(&sc->sc_ringmtx);
352 		safe_dma_free(sc, &sc->sc_ringalloc);
353 		bus_dma_tag_destroy(sc->sc_srcdmat);
354 		goto bad4;
355 	}
356 	sc->sc_spring = (struct safe_pdesc *) sc->sc_spalloc.dma_vaddr;
357 	sc->sc_springtop = sc->sc_spring + SAFE_TOTAL_SPART;
358 	sc->sc_spfree = sc->sc_spring;
359 	bzero(sc->sc_spring, SAFE_TOTAL_SPART * sizeof(struct safe_pdesc));
360 
361 	if (safe_dma_malloc(sc, SAFE_TOTAL_DPART * sizeof (struct safe_pdesc),
362 	    &sc->sc_dpalloc, 0)) {
363 		device_printf(dev, "cannot allocate destination particle "
364 			"descriptor ring\n");
365 		mtx_destroy(&sc->sc_ringmtx);
366 		safe_dma_free(sc, &sc->sc_spalloc);
367 		safe_dma_free(sc, &sc->sc_ringalloc);
368 		bus_dma_tag_destroy(sc->sc_dstdmat);
369 		goto bad4;
370 	}
371 	sc->sc_dpring = (struct safe_pdesc *) sc->sc_dpalloc.dma_vaddr;
372 	sc->sc_dpringtop = sc->sc_dpring + SAFE_TOTAL_DPART;
373 	sc->sc_dpfree = sc->sc_dpring;
374 	bzero(sc->sc_dpring, SAFE_TOTAL_DPART * sizeof(struct safe_pdesc));
375 
376 	device_printf(sc->sc_dev, "%s", safe_partname(sc));
377 
378 	devinfo = READ_REG(sc, SAFE_DEVINFO);
379 	if (devinfo & SAFE_DEVINFO_RNG) {
380 		sc->sc_flags |= SAFE_FLAGS_RNG;
381 		printf(" rng");
382 	}
383 	if (devinfo & SAFE_DEVINFO_PKEY) {
384 #if 0
385 		printf(" key");
386 		sc->sc_flags |= SAFE_FLAGS_KEY;
387 		crypto_kregister(sc->sc_cid, CRK_MOD_EXP, 0);
388 		crypto_kregister(sc->sc_cid, CRK_MOD_EXP_CRT, 0);
389 #endif
390 	}
391 	if (devinfo & SAFE_DEVINFO_DES) {
392 		printf(" des/3des");
393 		crypto_register(sc->sc_cid, CRYPTO_3DES_CBC, 0, 0);
394 		crypto_register(sc->sc_cid, CRYPTO_DES_CBC, 0, 0);
395 	}
396 	if (devinfo & SAFE_DEVINFO_AES) {
397 		printf(" aes");
398 		crypto_register(sc->sc_cid, CRYPTO_AES_CBC, 0, 0);
399 	}
400 	if (devinfo & SAFE_DEVINFO_MD5) {
401 		printf(" md5");
402 		crypto_register(sc->sc_cid, CRYPTO_MD5_HMAC, 0, 0);
403 	}
404 	if (devinfo & SAFE_DEVINFO_SHA1) {
405 		printf(" sha1");
406 		crypto_register(sc->sc_cid, CRYPTO_SHA1_HMAC, 0, 0);
407 	}
408 	printf(" null");
409 	crypto_register(sc->sc_cid, CRYPTO_NULL_CBC, 0, 0);
410 	crypto_register(sc->sc_cid, CRYPTO_NULL_HMAC, 0, 0);
411 	/* XXX other supported algorithms */
412 	printf("\n");
413 
414 	safe_reset_board(sc);		/* reset h/w */
415 	safe_init_pciregs(dev);		/* init pci settings */
416 	safe_init_board(sc);		/* init h/w */
417 
418 #ifndef SAFE_NO_RNG
419 	if (sc->sc_flags & SAFE_FLAGS_RNG) {
420 #ifdef SAFE_RNDTEST
421 		sc->sc_rndtest = rndtest_attach(dev);
422 		if (sc->sc_rndtest)
423 			sc->sc_harvest = rndtest_harvest;
424 		else
425 			sc->sc_harvest = default_harvest;
426 #else
427 		sc->sc_harvest = default_harvest;
428 #endif
429 		safe_rng_init(sc);
430 
431 		callout_init(&sc->sc_rngto, 1);
432 		callout_reset(&sc->sc_rngto, hz*safe_rnginterval, safe_rng, sc);
433 	}
434 #endif /* SAFE_NO_RNG */
435 #ifdef SAFE_DEBUG
436 	safec = sc;			/* for use by hw.safe.dump */
437 #endif
438 	return (0);
439 bad4:
440 	crypto_unregister_all(sc->sc_cid);
441 bad3:
442 	bus_teardown_intr(dev, sc->sc_irq, sc->sc_ih);
443 bad2:
444 	bus_release_resource(dev, SYS_RES_IRQ, 0, sc->sc_irq);
445 bad1:
446 	bus_release_resource(dev, SYS_RES_MEMORY, BS_BAR, sc->sc_sr);
447 bad:
448 	return (ENXIO);
449 }
450 
451 /*
452  * Detach a device that successfully probed.
453  */
454 static int
455 safe_detach(device_t dev)
456 {
457 	struct safe_softc *sc = device_get_softc(dev);
458 
459 	/* XXX wait/abort active ops */
460 
461 	WRITE_REG(sc, SAFE_HI_MASK, 0);		/* disable interrupts */
462 
463 	callout_stop(&sc->sc_rngto);
464 
465 	crypto_unregister_all(sc->sc_cid);
466 
467 #ifdef SAFE_RNDTEST
468 	if (sc->sc_rndtest)
469 		rndtest_detach(sc->sc_rndtest);
470 #endif
471 
472 	safe_cleanchip(sc);
473 	safe_dma_free(sc, &sc->sc_dpalloc);
474 	safe_dma_free(sc, &sc->sc_spalloc);
475 	mtx_destroy(&sc->sc_ringmtx);
476 	safe_dma_free(sc, &sc->sc_ringalloc);
477 
478 	bus_generic_detach(dev);
479 	bus_teardown_intr(dev, sc->sc_irq, sc->sc_ih);
480 	bus_release_resource(dev, SYS_RES_IRQ, 0, sc->sc_irq);
481 
482 	bus_dma_tag_destroy(sc->sc_srcdmat);
483 	bus_dma_tag_destroy(sc->sc_dstdmat);
484 	bus_release_resource(dev, SYS_RES_MEMORY, BS_BAR, sc->sc_sr);
485 
486 	return (0);
487 }
488 
489 /*
490  * Stop all chip i/o so that the kernel's probe routines don't
491  * get confused by errant DMAs when rebooting.
492  */
493 static int
494 safe_shutdown(device_t dev)
495 {
496 #ifdef notyet
497 	safe_stop(device_get_softc(dev));
498 #endif
499 	return (0);
500 }
501 
502 /*
503  * Device suspend routine.
504  */
505 static int
506 safe_suspend(device_t dev)
507 {
508 	struct safe_softc *sc = device_get_softc(dev);
509 
510 #ifdef notyet
511 	/* XXX stop the device and save PCI settings */
512 #endif
513 	sc->sc_suspended = 1;
514 
515 	return (0);
516 }
517 
518 static int
519 safe_resume(device_t dev)
520 {
521 	struct safe_softc *sc = device_get_softc(dev);
522 
523 #ifdef notyet
524 	/* XXX retore PCI settings and start the device */
525 #endif
526 	sc->sc_suspended = 0;
527 	return (0);
528 }
529 
530 /*
531  * SafeXcel Interrupt routine
532  */
533 static void
534 safe_intr(void *arg)
535 {
536 	struct safe_softc *sc = arg;
537 	volatile u_int32_t stat;
538 
539 	stat = READ_REG(sc, SAFE_HM_STAT);
540 	if (stat == 0)			/* shared irq, not for us */
541 		return;
542 
543 	WRITE_REG(sc, SAFE_HI_CLR, stat);	/* IACK */
544 
545 	if ((stat & SAFE_INT_PE_DDONE)) {
546 		/*
547 		 * Descriptor(s) done; scan the ring and
548 		 * process completed operations.
549 		 */
550 		mtx_lock(&sc->sc_ringmtx);
551 		while (sc->sc_back != sc->sc_front) {
552 			struct safe_ringentry *re = sc->sc_back;
553 #ifdef SAFE_DEBUG
554 			if (safe_debug) {
555 				safe_dump_ringstate(sc, __func__);
556 				safe_dump_request(sc, __func__, re);
557 			}
558 #endif
559 			/*
560 			 * safe_process marks ring entries that were allocated
561 			 * but not used with a csr of zero.  This insures the
562 			 * ring front pointer never needs to be set backwards
563 			 * in the event that an entry is allocated but not used
564 			 * because of a setup error.
565 			 */
566 			if (re->re_desc.d_csr != 0) {
567 				if (!SAFE_PE_CSR_IS_DONE(re->re_desc.d_csr))
568 					break;
569 				if (!SAFE_PE_LEN_IS_DONE(re->re_desc.d_len))
570 					break;
571 				sc->sc_nqchip--;
572 				safe_callback(sc, re);
573 			}
574 			if (++(sc->sc_back) == sc->sc_ringtop)
575 				sc->sc_back = sc->sc_ring;
576 		}
577 		mtx_unlock(&sc->sc_ringmtx);
578 	}
579 
580 	/*
581 	 * Check to see if we got any DMA Error
582 	 */
583 	if (stat & SAFE_INT_PE_ERROR) {
584 		DPRINTF(("dmaerr dmastat %08x\n",
585 			READ_REG(sc, SAFE_PE_DMASTAT)));
586 		safestats.st_dmaerr++;
587 		safe_totalreset(sc);
588 #if 0
589 		safe_feed(sc);
590 #endif
591 	}
592 
593 	if (sc->sc_needwakeup) {		/* XXX check high watermark */
594 		int wakeup = sc->sc_needwakeup & (CRYPTO_SYMQ|CRYPTO_ASYMQ);
595 		DPRINTF(("%s: wakeup crypto %x\n", __func__,
596 			sc->sc_needwakeup));
597 		sc->sc_needwakeup &= ~wakeup;
598 		crypto_unblock(sc->sc_cid, wakeup);
599 	}
600 }
601 
602 /*
603  * safe_feed() - post a request to chip
604  */
605 static void
606 safe_feed(struct safe_softc *sc, struct safe_ringentry *re)
607 {
608 	bus_dmamap_sync(sc->sc_srcdmat, re->re_src_map, BUS_DMASYNC_PREWRITE);
609 	if (re->re_dst_map != NULL)
610 		bus_dmamap_sync(sc->sc_dstdmat, re->re_dst_map,
611 			BUS_DMASYNC_PREREAD);
612 	/* XXX have no smaller granularity */
613 	safe_dma_sync(&sc->sc_ringalloc,
614 		BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
615 	safe_dma_sync(&sc->sc_spalloc, BUS_DMASYNC_PREWRITE);
616 	safe_dma_sync(&sc->sc_dpalloc, BUS_DMASYNC_PREWRITE);
617 
618 #ifdef SAFE_DEBUG
619 	if (safe_debug) {
620 		safe_dump_ringstate(sc, __func__);
621 		safe_dump_request(sc, __func__, re);
622 	}
623 #endif
624 	sc->sc_nqchip++;
625 	if (sc->sc_nqchip > safestats.st_maxqchip)
626 		safestats.st_maxqchip = sc->sc_nqchip;
627 	/* poke h/w to check descriptor ring, any value can be written */
628 	WRITE_REG(sc, SAFE_HI_RD_DESCR, 0);
629 }
630 
631 #define	N(a)	(sizeof(a) / sizeof (a[0]))
632 static void
633 safe_setup_enckey(struct safe_session *ses, caddr_t key)
634 {
635 	int i;
636 
637 	bcopy(key, ses->ses_key, ses->ses_klen / 8);
638 
639 	/* PE is little-endian, insure proper byte order */
640 	for (i = 0; i < N(ses->ses_key); i++)
641 		ses->ses_key[i] = htole32(ses->ses_key[i]);
642 }
643 
644 static void
645 safe_setup_mackey(struct safe_session *ses, int algo, caddr_t key, int klen)
646 {
647 	MD5_CTX md5ctx;
648 	SHA1_CTX sha1ctx;
649 	int i;
650 
651 
652 	for (i = 0; i < klen; i++)
653 		key[i] ^= HMAC_IPAD_VAL;
654 
655 	if (algo == CRYPTO_MD5_HMAC) {
656 		MD5Init(&md5ctx);
657 		MD5Update(&md5ctx, key, klen);
658 		MD5Update(&md5ctx, hmac_ipad_buffer, MD5_HMAC_BLOCK_LEN - klen);
659 		bcopy(md5ctx.state, ses->ses_hminner, sizeof(md5ctx.state));
660 	} else {
661 		SHA1Init(&sha1ctx);
662 		SHA1Update(&sha1ctx, key, klen);
663 		SHA1Update(&sha1ctx, hmac_ipad_buffer,
664 		    SHA1_HMAC_BLOCK_LEN - klen);
665 		bcopy(sha1ctx.h.b32, ses->ses_hminner, sizeof(sha1ctx.h.b32));
666 	}
667 
668 	for (i = 0; i < klen; i++)
669 		key[i] ^= (HMAC_IPAD_VAL ^ HMAC_OPAD_VAL);
670 
671 	if (algo == CRYPTO_MD5_HMAC) {
672 		MD5Init(&md5ctx);
673 		MD5Update(&md5ctx, key, klen);
674 		MD5Update(&md5ctx, hmac_opad_buffer, MD5_HMAC_BLOCK_LEN - klen);
675 		bcopy(md5ctx.state, ses->ses_hmouter, sizeof(md5ctx.state));
676 	} else {
677 		SHA1Init(&sha1ctx);
678 		SHA1Update(&sha1ctx, key, klen);
679 		SHA1Update(&sha1ctx, hmac_opad_buffer,
680 		    SHA1_HMAC_BLOCK_LEN - klen);
681 		bcopy(sha1ctx.h.b32, ses->ses_hmouter, sizeof(sha1ctx.h.b32));
682 	}
683 
684 	for (i = 0; i < klen; i++)
685 		key[i] ^= HMAC_OPAD_VAL;
686 
687 	/* PE is little-endian, insure proper byte order */
688 	for (i = 0; i < N(ses->ses_hminner); i++) {
689 		ses->ses_hminner[i] = htole32(ses->ses_hminner[i]);
690 		ses->ses_hmouter[i] = htole32(ses->ses_hmouter[i]);
691 	}
692 }
693 #undef N
694 
695 /*
696  * Allocate a new 'session' and return an encoded session id.  'sidp'
697  * contains our registration id, and should contain an encoded session
698  * id on successful allocation.
699  */
700 static int
701 safe_newsession(device_t dev, u_int32_t *sidp, struct cryptoini *cri)
702 {
703 	struct safe_softc *sc = device_get_softc(dev);
704 	struct cryptoini *c, *encini = NULL, *macini = NULL;
705 	struct safe_session *ses = NULL;
706 	int sesn;
707 
708 	if (sidp == NULL || cri == NULL || sc == NULL)
709 		return (EINVAL);
710 
711 	for (c = cri; c != NULL; c = c->cri_next) {
712 		if (c->cri_alg == CRYPTO_MD5_HMAC ||
713 		    c->cri_alg == CRYPTO_SHA1_HMAC ||
714 		    c->cri_alg == CRYPTO_NULL_HMAC) {
715 			if (macini)
716 				return (EINVAL);
717 			macini = c;
718 		} else if (c->cri_alg == CRYPTO_DES_CBC ||
719 		    c->cri_alg == CRYPTO_3DES_CBC ||
720 		    c->cri_alg == CRYPTO_AES_CBC ||
721 		    c->cri_alg == CRYPTO_NULL_CBC) {
722 			if (encini)
723 				return (EINVAL);
724 			encini = c;
725 		} else
726 			return (EINVAL);
727 	}
728 	if (encini == NULL && macini == NULL)
729 		return (EINVAL);
730 	if (encini) {			/* validate key length */
731 		switch (encini->cri_alg) {
732 		case CRYPTO_DES_CBC:
733 			if (encini->cri_klen != 64)
734 				return (EINVAL);
735 			break;
736 		case CRYPTO_3DES_CBC:
737 			if (encini->cri_klen != 192)
738 				return (EINVAL);
739 			break;
740 		case CRYPTO_AES_CBC:
741 			if (encini->cri_klen != 128 &&
742 			    encini->cri_klen != 192 &&
743 			    encini->cri_klen != 256)
744 				return (EINVAL);
745 			break;
746 		}
747 	}
748 
749 	if (sc->sc_sessions == NULL) {
750 		ses = sc->sc_sessions = (struct safe_session *)malloc(
751 		    sizeof(struct safe_session), M_DEVBUF, M_NOWAIT);
752 		if (ses == NULL)
753 			return (ENOMEM);
754 		sesn = 0;
755 		sc->sc_nsessions = 1;
756 	} else {
757 		for (sesn = 0; sesn < sc->sc_nsessions; sesn++) {
758 			if (sc->sc_sessions[sesn].ses_used == 0) {
759 				ses = &sc->sc_sessions[sesn];
760 				break;
761 			}
762 		}
763 
764 		if (ses == NULL) {
765 			sesn = sc->sc_nsessions;
766 			ses = (struct safe_session *)malloc((sesn + 1) *
767 			    sizeof(struct safe_session), M_DEVBUF, M_NOWAIT);
768 			if (ses == NULL)
769 				return (ENOMEM);
770 			bcopy(sc->sc_sessions, ses, sesn *
771 			    sizeof(struct safe_session));
772 			bzero(sc->sc_sessions, sesn *
773 			    sizeof(struct safe_session));
774 			free(sc->sc_sessions, M_DEVBUF);
775 			sc->sc_sessions = ses;
776 			ses = &sc->sc_sessions[sesn];
777 			sc->sc_nsessions++;
778 		}
779 	}
780 
781 	bzero(ses, sizeof(struct safe_session));
782 	ses->ses_used = 1;
783 
784 	if (encini) {
785 		/* get an IV */
786 		/* XXX may read fewer than requested */
787 		read_random(ses->ses_iv, sizeof(ses->ses_iv));
788 
789 		ses->ses_klen = encini->cri_klen;
790 		if (encini->cri_key != NULL)
791 			safe_setup_enckey(ses, encini->cri_key);
792 	}
793 
794 	if (macini) {
795 		ses->ses_mlen = macini->cri_mlen;
796 		if (ses->ses_mlen == 0) {
797 			if (macini->cri_alg == CRYPTO_MD5_HMAC)
798 				ses->ses_mlen = MD5_HASH_LEN;
799 			else
800 				ses->ses_mlen = SHA1_HASH_LEN;
801 		}
802 
803 		if (macini->cri_key != NULL) {
804 			safe_setup_mackey(ses, macini->cri_alg, macini->cri_key,
805 			    macini->cri_klen / 8);
806 		}
807 	}
808 
809 	*sidp = SAFE_SID(device_get_unit(sc->sc_dev), sesn);
810 	return (0);
811 }
812 
813 /*
814  * Deallocate a session.
815  */
816 static int
817 safe_freesession(device_t dev, u_int64_t tid)
818 {
819 	struct safe_softc *sc = device_get_softc(dev);
820 	int session, ret;
821 	u_int32_t sid = ((u_int32_t) tid) & 0xffffffff;
822 
823 	if (sc == NULL)
824 		return (EINVAL);
825 
826 	session = SAFE_SESSION(sid);
827 	if (session < sc->sc_nsessions) {
828 		bzero(&sc->sc_sessions[session], sizeof(sc->sc_sessions[session]));
829 		ret = 0;
830 	} else
831 		ret = EINVAL;
832 	return (ret);
833 }
834 
835 static void
836 safe_op_cb(void *arg, bus_dma_segment_t *seg, int nsegs, bus_size_t mapsize, int error)
837 {
838 	struct safe_operand *op = arg;
839 
840 	DPRINTF(("%s: mapsize %u nsegs %d error %d\n", __func__,
841 		(u_int) mapsize, nsegs, error));
842 	if (error != 0)
843 		return;
844 	op->mapsize = mapsize;
845 	op->nsegs = nsegs;
846 	bcopy(seg, op->segs, nsegs * sizeof (seg[0]));
847 }
848 
849 static int
850 safe_process(device_t dev, struct cryptop *crp, int hint)
851 {
852 	struct safe_softc *sc = device_get_softc(dev);
853 	int err = 0, i, nicealign, uniform;
854 	struct cryptodesc *crd1, *crd2, *maccrd, *enccrd;
855 	int bypass, oplen, ivsize;
856 	caddr_t iv;
857 	int16_t coffset;
858 	struct safe_session *ses;
859 	struct safe_ringentry *re;
860 	struct safe_sarec *sa;
861 	struct safe_pdesc *pd;
862 	u_int32_t cmd0, cmd1, staterec;
863 
864 	if (crp == NULL || crp->crp_callback == NULL || sc == NULL) {
865 		safestats.st_invalid++;
866 		return (EINVAL);
867 	}
868 	if (SAFE_SESSION(crp->crp_sid) >= sc->sc_nsessions) {
869 		safestats.st_badsession++;
870 		return (EINVAL);
871 	}
872 
873 	mtx_lock(&sc->sc_ringmtx);
874 	if (sc->sc_front == sc->sc_back && sc->sc_nqchip != 0) {
875 		safestats.st_ringfull++;
876 		sc->sc_needwakeup |= CRYPTO_SYMQ;
877 		mtx_unlock(&sc->sc_ringmtx);
878 		return (ERESTART);
879 	}
880 	re = sc->sc_front;
881 
882 	staterec = re->re_sa.sa_staterec;	/* save */
883 	/* NB: zero everything but the PE descriptor */
884 	bzero(&re->re_sa, sizeof(struct safe_ringentry) - sizeof(re->re_desc));
885 	re->re_sa.sa_staterec = staterec;	/* restore */
886 
887 	re->re_crp = crp;
888 	re->re_sesn = SAFE_SESSION(crp->crp_sid);
889 
890 	if (crp->crp_flags & CRYPTO_F_IMBUF) {
891 		re->re_src_m = (struct mbuf *)crp->crp_buf;
892 		re->re_dst_m = (struct mbuf *)crp->crp_buf;
893 	} else if (crp->crp_flags & CRYPTO_F_IOV) {
894 		re->re_src_io = (struct uio *)crp->crp_buf;
895 		re->re_dst_io = (struct uio *)crp->crp_buf;
896 	} else {
897 		safestats.st_badflags++;
898 		err = EINVAL;
899 		goto errout;	/* XXX we don't handle contiguous blocks! */
900 	}
901 
902 	sa = &re->re_sa;
903 	ses = &sc->sc_sessions[re->re_sesn];
904 
905 	crd1 = crp->crp_desc;
906 	if (crd1 == NULL) {
907 		safestats.st_nodesc++;
908 		err = EINVAL;
909 		goto errout;
910 	}
911 	crd2 = crd1->crd_next;
912 
913 	cmd0 = SAFE_SA_CMD0_BASIC;		/* basic group operation */
914 	cmd1 = 0;
915 	if (crd2 == NULL) {
916 		if (crd1->crd_alg == CRYPTO_MD5_HMAC ||
917 		    crd1->crd_alg == CRYPTO_SHA1_HMAC ||
918 		    crd1->crd_alg == CRYPTO_NULL_HMAC) {
919 			maccrd = crd1;
920 			enccrd = NULL;
921 			cmd0 |= SAFE_SA_CMD0_OP_HASH;
922 		} else if (crd1->crd_alg == CRYPTO_DES_CBC ||
923 		    crd1->crd_alg == CRYPTO_3DES_CBC ||
924 		    crd1->crd_alg == CRYPTO_AES_CBC ||
925 		    crd1->crd_alg == CRYPTO_NULL_CBC) {
926 			maccrd = NULL;
927 			enccrd = crd1;
928 			cmd0 |= SAFE_SA_CMD0_OP_CRYPT;
929 		} else {
930 			safestats.st_badalg++;
931 			err = EINVAL;
932 			goto errout;
933 		}
934 	} else {
935 		if ((crd1->crd_alg == CRYPTO_MD5_HMAC ||
936 		    crd1->crd_alg == CRYPTO_SHA1_HMAC ||
937 		    crd1->crd_alg == CRYPTO_NULL_HMAC) &&
938 		    (crd2->crd_alg == CRYPTO_DES_CBC ||
939 			crd2->crd_alg == CRYPTO_3DES_CBC ||
940 		        crd2->crd_alg == CRYPTO_AES_CBC ||
941 		        crd2->crd_alg == CRYPTO_NULL_CBC) &&
942 		    ((crd2->crd_flags & CRD_F_ENCRYPT) == 0)) {
943 			maccrd = crd1;
944 			enccrd = crd2;
945 		} else if ((crd1->crd_alg == CRYPTO_DES_CBC ||
946 		    crd1->crd_alg == CRYPTO_3DES_CBC ||
947 		    crd1->crd_alg == CRYPTO_AES_CBC ||
948 		    crd1->crd_alg == CRYPTO_NULL_CBC) &&
949 		    (crd2->crd_alg == CRYPTO_MD5_HMAC ||
950 			crd2->crd_alg == CRYPTO_SHA1_HMAC ||
951 			crd2->crd_alg == CRYPTO_NULL_HMAC) &&
952 		    (crd1->crd_flags & CRD_F_ENCRYPT)) {
953 			enccrd = crd1;
954 			maccrd = crd2;
955 		} else {
956 			safestats.st_badalg++;
957 			err = EINVAL;
958 			goto errout;
959 		}
960 		cmd0 |= SAFE_SA_CMD0_OP_BOTH;
961 	}
962 
963 	if (enccrd) {
964 		if (enccrd->crd_flags & CRD_F_KEY_EXPLICIT)
965 			safe_setup_enckey(ses, enccrd->crd_key);
966 
967 		if (enccrd->crd_alg == CRYPTO_DES_CBC) {
968 			cmd0 |= SAFE_SA_CMD0_DES;
969 			cmd1 |= SAFE_SA_CMD1_CBC;
970 			ivsize = 2*sizeof(u_int32_t);
971 		} else if (enccrd->crd_alg == CRYPTO_3DES_CBC) {
972 			cmd0 |= SAFE_SA_CMD0_3DES;
973 			cmd1 |= SAFE_SA_CMD1_CBC;
974 			ivsize = 2*sizeof(u_int32_t);
975 		} else if (enccrd->crd_alg == CRYPTO_AES_CBC) {
976 			cmd0 |= SAFE_SA_CMD0_AES;
977 			cmd1 |= SAFE_SA_CMD1_CBC;
978 			if (ses->ses_klen == 128)
979 			     cmd1 |=  SAFE_SA_CMD1_AES128;
980 			else if (ses->ses_klen == 192)
981 			     cmd1 |=  SAFE_SA_CMD1_AES192;
982 			else
983 			     cmd1 |=  SAFE_SA_CMD1_AES256;
984 			ivsize = 4*sizeof(u_int32_t);
985 		} else {
986 			cmd0 |= SAFE_SA_CMD0_CRYPT_NULL;
987 			ivsize = 0;
988 		}
989 
990 		/*
991 		 * Setup encrypt/decrypt state.  When using basic ops
992 		 * we can't use an inline IV because hash/crypt offset
993 		 * must be from the end of the IV to the start of the
994 		 * crypt data and this leaves out the preceding header
995 		 * from the hash calculation.  Instead we place the IV
996 		 * in the state record and set the hash/crypt offset to
997 		 * copy both the header+IV.
998 		 */
999 		if (enccrd->crd_flags & CRD_F_ENCRYPT) {
1000 			cmd0 |= SAFE_SA_CMD0_OUTBOUND;
1001 
1002 			if (enccrd->crd_flags & CRD_F_IV_EXPLICIT)
1003 				iv = enccrd->crd_iv;
1004 			else
1005 				iv = (caddr_t) ses->ses_iv;
1006 			if ((enccrd->crd_flags & CRD_F_IV_PRESENT) == 0) {
1007 				crypto_copyback(crp->crp_flags, crp->crp_buf,
1008 				    enccrd->crd_inject, ivsize, iv);
1009 			}
1010 			bcopy(iv, re->re_sastate.sa_saved_iv, ivsize);
1011 			cmd0 |= SAFE_SA_CMD0_IVLD_STATE | SAFE_SA_CMD0_SAVEIV;
1012 			re->re_flags |= SAFE_QFLAGS_COPYOUTIV;
1013 		} else {
1014 			cmd0 |= SAFE_SA_CMD0_INBOUND;
1015 
1016 			if (enccrd->crd_flags & CRD_F_IV_EXPLICIT) {
1017 				bcopy(enccrd->crd_iv,
1018 					re->re_sastate.sa_saved_iv, ivsize);
1019 			} else {
1020 				crypto_copydata(crp->crp_flags, crp->crp_buf,
1021 				    enccrd->crd_inject, ivsize,
1022 				    (caddr_t)re->re_sastate.sa_saved_iv);
1023 			}
1024 			cmd0 |= SAFE_SA_CMD0_IVLD_STATE;
1025 		}
1026 		/*
1027 		 * For basic encryption use the zero pad algorithm.
1028 		 * This pads results to an 8-byte boundary and
1029 		 * suppresses padding verification for inbound (i.e.
1030 		 * decrypt) operations.
1031 		 *
1032 		 * NB: Not sure if the 8-byte pad boundary is a problem.
1033 		 */
1034 		cmd0 |= SAFE_SA_CMD0_PAD_ZERO;
1035 
1036 		/* XXX assert key bufs have the same size */
1037 		bcopy(ses->ses_key, sa->sa_key, sizeof(sa->sa_key));
1038 	}
1039 
1040 	if (maccrd) {
1041 		if (maccrd->crd_flags & CRD_F_KEY_EXPLICIT) {
1042 			safe_setup_mackey(ses, maccrd->crd_alg,
1043 			    maccrd->crd_key, maccrd->crd_klen / 8);
1044 		}
1045 
1046 		if (maccrd->crd_alg == CRYPTO_MD5_HMAC) {
1047 			cmd0 |= SAFE_SA_CMD0_MD5;
1048 			cmd1 |= SAFE_SA_CMD1_HMAC;	/* NB: enable HMAC */
1049 		} else if (maccrd->crd_alg == CRYPTO_SHA1_HMAC) {
1050 			cmd0 |= SAFE_SA_CMD0_SHA1;
1051 			cmd1 |= SAFE_SA_CMD1_HMAC;	/* NB: enable HMAC */
1052 		} else {
1053 			cmd0 |= SAFE_SA_CMD0_HASH_NULL;
1054 		}
1055 		/*
1056 		 * Digest data is loaded from the SA and the hash
1057 		 * result is saved to the state block where we
1058 		 * retrieve it for return to the caller.
1059 		 */
1060 		/* XXX assert digest bufs have the same size */
1061 		bcopy(ses->ses_hminner, sa->sa_indigest,
1062 			sizeof(sa->sa_indigest));
1063 		bcopy(ses->ses_hmouter, sa->sa_outdigest,
1064 			sizeof(sa->sa_outdigest));
1065 
1066 		cmd0 |= SAFE_SA_CMD0_HSLD_SA | SAFE_SA_CMD0_SAVEHASH;
1067 		re->re_flags |= SAFE_QFLAGS_COPYOUTICV;
1068 	}
1069 
1070 	if (enccrd && maccrd) {
1071 		/*
1072 		 * The offset from hash data to the start of
1073 		 * crypt data is the difference in the skips.
1074 		 */
1075 		bypass = maccrd->crd_skip;
1076 		coffset = enccrd->crd_skip - maccrd->crd_skip;
1077 		if (coffset < 0) {
1078 			DPRINTF(("%s: hash does not precede crypt; "
1079 				"mac skip %u enc skip %u\n",
1080 				__func__, maccrd->crd_skip, enccrd->crd_skip));
1081 			safestats.st_skipmismatch++;
1082 			err = EINVAL;
1083 			goto errout;
1084 		}
1085 		oplen = enccrd->crd_skip + enccrd->crd_len;
1086 		if (maccrd->crd_skip + maccrd->crd_len != oplen) {
1087 			DPRINTF(("%s: hash amount %u != crypt amount %u\n",
1088 				__func__, maccrd->crd_skip + maccrd->crd_len,
1089 				oplen));
1090 			safestats.st_lenmismatch++;
1091 			err = EINVAL;
1092 			goto errout;
1093 		}
1094 #ifdef SAFE_DEBUG
1095 		if (safe_debug) {
1096 			printf("mac: skip %d, len %d, inject %d\n",
1097 			    maccrd->crd_skip, maccrd->crd_len,
1098 			    maccrd->crd_inject);
1099 			printf("enc: skip %d, len %d, inject %d\n",
1100 			    enccrd->crd_skip, enccrd->crd_len,
1101 			    enccrd->crd_inject);
1102 			printf("bypass %d coffset %d oplen %d\n",
1103 				bypass, coffset, oplen);
1104 		}
1105 #endif
1106 		if (coffset & 3) {	/* offset must be 32-bit aligned */
1107 			DPRINTF(("%s: coffset %u misaligned\n",
1108 				__func__, coffset));
1109 			safestats.st_coffmisaligned++;
1110 			err = EINVAL;
1111 			goto errout;
1112 		}
1113 		coffset >>= 2;
1114 		if (coffset > 255) {	/* offset must be <256 dwords */
1115 			DPRINTF(("%s: coffset %u too big\n",
1116 				__func__, coffset));
1117 			safestats.st_cofftoobig++;
1118 			err = EINVAL;
1119 			goto errout;
1120 		}
1121 		/*
1122 		 * Tell the hardware to copy the header to the output.
1123 		 * The header is defined as the data from the end of
1124 		 * the bypass to the start of data to be encrypted.
1125 		 * Typically this is the inline IV.  Note that you need
1126 		 * to do this even if src+dst are the same; it appears
1127 		 * that w/o this bit the crypted data is written
1128 		 * immediately after the bypass data.
1129 		 */
1130 		cmd1 |= SAFE_SA_CMD1_HDRCOPY;
1131 		/*
1132 		 * Disable IP header mutable bit handling.  This is
1133 		 * needed to get correct HMAC calculations.
1134 		 */
1135 		cmd1 |= SAFE_SA_CMD1_MUTABLE;
1136 	} else {
1137 		if (enccrd) {
1138 			bypass = enccrd->crd_skip;
1139 			oplen = bypass + enccrd->crd_len;
1140 		} else {
1141 			bypass = maccrd->crd_skip;
1142 			oplen = bypass + maccrd->crd_len;
1143 		}
1144 		coffset = 0;
1145 	}
1146 	/* XXX verify multiple of 4 when using s/g */
1147 	if (bypass > 96) {		/* bypass offset must be <= 96 bytes */
1148 		DPRINTF(("%s: bypass %u too big\n", __func__, bypass));
1149 		safestats.st_bypasstoobig++;
1150 		err = EINVAL;
1151 		goto errout;
1152 	}
1153 
1154 	if (bus_dmamap_create(sc->sc_srcdmat, BUS_DMA_NOWAIT, &re->re_src_map)) {
1155 		safestats.st_nomap++;
1156 		err = ENOMEM;
1157 		goto errout;
1158 	}
1159 	if (crp->crp_flags & CRYPTO_F_IMBUF) {
1160 		if (bus_dmamap_load_mbuf(sc->sc_srcdmat, re->re_src_map,
1161 		    re->re_src_m, safe_op_cb,
1162 		    &re->re_src, BUS_DMA_NOWAIT) != 0) {
1163 			bus_dmamap_destroy(sc->sc_srcdmat, re->re_src_map);
1164 			re->re_src_map = NULL;
1165 			safestats.st_noload++;
1166 			err = ENOMEM;
1167 			goto errout;
1168 		}
1169 	} else if (crp->crp_flags & CRYPTO_F_IOV) {
1170 		if (bus_dmamap_load_uio(sc->sc_srcdmat, re->re_src_map,
1171 		    re->re_src_io, safe_op_cb,
1172 		    &re->re_src, BUS_DMA_NOWAIT) != 0) {
1173 			bus_dmamap_destroy(sc->sc_srcdmat, re->re_src_map);
1174 			re->re_src_map = NULL;
1175 			safestats.st_noload++;
1176 			err = ENOMEM;
1177 			goto errout;
1178 		}
1179 	}
1180 	nicealign = safe_dmamap_aligned(&re->re_src);
1181 	uniform = safe_dmamap_uniform(&re->re_src);
1182 
1183 	DPRINTF(("src nicealign %u uniform %u nsegs %u\n",
1184 		nicealign, uniform, re->re_src.nsegs));
1185 	if (re->re_src.nsegs > 1) {
1186 		re->re_desc.d_src = sc->sc_spalloc.dma_paddr +
1187 			((caddr_t) sc->sc_spfree - (caddr_t) sc->sc_spring);
1188 		for (i = 0; i < re->re_src_nsegs; i++) {
1189 			/* NB: no need to check if there's space */
1190 			pd = sc->sc_spfree;
1191 			if (++(sc->sc_spfree) == sc->sc_springtop)
1192 				sc->sc_spfree = sc->sc_spring;
1193 
1194 			KASSERT((pd->pd_flags&3) == 0 ||
1195 				(pd->pd_flags&3) == SAFE_PD_DONE,
1196 				("bogus source particle descriptor; flags %x",
1197 				pd->pd_flags));
1198 			pd->pd_addr = re->re_src_segs[i].ds_addr;
1199 			pd->pd_size = re->re_src_segs[i].ds_len;
1200 			pd->pd_flags = SAFE_PD_READY;
1201 		}
1202 		cmd0 |= SAFE_SA_CMD0_IGATHER;
1203 	} else {
1204 		/*
1205 		 * No need for gather, reference the operand directly.
1206 		 */
1207 		re->re_desc.d_src = re->re_src_segs[0].ds_addr;
1208 	}
1209 
1210 	if (enccrd == NULL && maccrd != NULL) {
1211 		/*
1212 		 * Hash op; no destination needed.
1213 		 */
1214 	} else {
1215 		if (crp->crp_flags & CRYPTO_F_IOV) {
1216 			if (!nicealign) {
1217 				safestats.st_iovmisaligned++;
1218 				err = EINVAL;
1219 				goto errout;
1220 			}
1221 			if (uniform != 1) {
1222 				/*
1223 				 * Source is not suitable for direct use as
1224 				 * the destination.  Create a new scatter/gather
1225 				 * list based on the destination requirements
1226 				 * and check if that's ok.
1227 				 */
1228 				if (bus_dmamap_create(sc->sc_dstdmat,
1229 				    BUS_DMA_NOWAIT, &re->re_dst_map)) {
1230 					safestats.st_nomap++;
1231 					err = ENOMEM;
1232 					goto errout;
1233 				}
1234 				if (bus_dmamap_load_uio(sc->sc_dstdmat,
1235 				    re->re_dst_map, re->re_dst_io,
1236 				    safe_op_cb, &re->re_dst,
1237 				    BUS_DMA_NOWAIT) != 0) {
1238 					bus_dmamap_destroy(sc->sc_dstdmat,
1239 						re->re_dst_map);
1240 					re->re_dst_map = NULL;
1241 					safestats.st_noload++;
1242 					err = ENOMEM;
1243 					goto errout;
1244 				}
1245 				uniform = safe_dmamap_uniform(&re->re_dst);
1246 				if (!uniform) {
1247 					/*
1248 					 * There's no way to handle the DMA
1249 					 * requirements with this uio.  We
1250 					 * could create a separate DMA area for
1251 					 * the result and then copy it back,
1252 					 * but for now we just bail and return
1253 					 * an error.  Note that uio requests
1254 					 * > SAFE_MAX_DSIZE are handled because
1255 					 * the DMA map and segment list for the
1256 					 * destination wil result in a
1257 					 * destination particle list that does
1258 					 * the necessary scatter DMA.
1259 					 */
1260 					safestats.st_iovnotuniform++;
1261 					err = EINVAL;
1262 					goto errout;
1263 				}
1264 			} else
1265 				re->re_dst = re->re_src;
1266 		} else if (crp->crp_flags & CRYPTO_F_IMBUF) {
1267 			if (nicealign && uniform == 1) {
1268 				/*
1269 				 * Source layout is suitable for direct
1270 				 * sharing of the DMA map and segment list.
1271 				 */
1272 				re->re_dst = re->re_src;
1273 			} else if (nicealign && uniform == 2) {
1274 				/*
1275 				 * The source is properly aligned but requires a
1276 				 * different particle list to handle DMA of the
1277 				 * result.  Create a new map and do the load to
1278 				 * create the segment list.  The particle
1279 				 * descriptor setup code below will handle the
1280 				 * rest.
1281 				 */
1282 				if (bus_dmamap_create(sc->sc_dstdmat,
1283 				    BUS_DMA_NOWAIT, &re->re_dst_map)) {
1284 					safestats.st_nomap++;
1285 					err = ENOMEM;
1286 					goto errout;
1287 				}
1288 				if (bus_dmamap_load_mbuf(sc->sc_dstdmat,
1289 				    re->re_dst_map, re->re_dst_m,
1290 				    safe_op_cb, &re->re_dst,
1291 				    BUS_DMA_NOWAIT) != 0) {
1292 					bus_dmamap_destroy(sc->sc_dstdmat,
1293 						re->re_dst_map);
1294 					re->re_dst_map = NULL;
1295 					safestats.st_noload++;
1296 					err = ENOMEM;
1297 					goto errout;
1298 				}
1299 			} else {		/* !(aligned and/or uniform) */
1300 				int totlen, len;
1301 				struct mbuf *m, *top, **mp;
1302 
1303 				/*
1304 				 * DMA constraints require that we allocate a
1305 				 * new mbuf chain for the destination.  We
1306 				 * allocate an entire new set of mbufs of
1307 				 * optimal/required size and then tell the
1308 				 * hardware to copy any bits that are not
1309 				 * created as a byproduct of the operation.
1310 				 */
1311 				if (!nicealign)
1312 					safestats.st_unaligned++;
1313 				if (!uniform)
1314 					safestats.st_notuniform++;
1315 				totlen = re->re_src_mapsize;
1316 				if (re->re_src_m->m_flags & M_PKTHDR) {
1317 					len = MHLEN;
1318 					MGETHDR(m, M_NOWAIT, MT_DATA);
1319 					if (m && !m_dup_pkthdr(m, re->re_src_m,
1320 					    M_NOWAIT)) {
1321 						m_free(m);
1322 						m = NULL;
1323 					}
1324 				} else {
1325 					len = MLEN;
1326 					MGET(m, M_NOWAIT, MT_DATA);
1327 				}
1328 				if (m == NULL) {
1329 					safestats.st_nombuf++;
1330 					err = sc->sc_nqchip ? ERESTART : ENOMEM;
1331 					goto errout;
1332 				}
1333 				if (totlen >= MINCLSIZE) {
1334 					if (!(MCLGET(m, M_NOWAIT))) {
1335 						m_free(m);
1336 						safestats.st_nomcl++;
1337 						err = sc->sc_nqchip ?
1338 							ERESTART : ENOMEM;
1339 						goto errout;
1340 					}
1341 					len = MCLBYTES;
1342 				}
1343 				m->m_len = len;
1344 				top = NULL;
1345 				mp = &top;
1346 
1347 				while (totlen > 0) {
1348 					if (top) {
1349 						MGET(m, M_NOWAIT, MT_DATA);
1350 						if (m == NULL) {
1351 							m_freem(top);
1352 							safestats.st_nombuf++;
1353 							err = sc->sc_nqchip ?
1354 							    ERESTART : ENOMEM;
1355 							goto errout;
1356 						}
1357 						len = MLEN;
1358 					}
1359 					if (top && totlen >= MINCLSIZE) {
1360 						if (!(MCLGET(m, M_NOWAIT))) {
1361 							*mp = m;
1362 							m_freem(top);
1363 							safestats.st_nomcl++;
1364 							err = sc->sc_nqchip ?
1365 							    ERESTART : ENOMEM;
1366 							goto errout;
1367 						}
1368 						len = MCLBYTES;
1369 					}
1370 					m->m_len = len = min(totlen, len);
1371 					totlen -= len;
1372 					*mp = m;
1373 					mp = &m->m_next;
1374 				}
1375 				re->re_dst_m = top;
1376 				if (bus_dmamap_create(sc->sc_dstdmat,
1377 				    BUS_DMA_NOWAIT, &re->re_dst_map) != 0) {
1378 					safestats.st_nomap++;
1379 					err = ENOMEM;
1380 					goto errout;
1381 				}
1382 				if (bus_dmamap_load_mbuf(sc->sc_dstdmat,
1383 				    re->re_dst_map, re->re_dst_m,
1384 				    safe_op_cb, &re->re_dst,
1385 				    BUS_DMA_NOWAIT) != 0) {
1386 					bus_dmamap_destroy(sc->sc_dstdmat,
1387 					re->re_dst_map);
1388 					re->re_dst_map = NULL;
1389 					safestats.st_noload++;
1390 					err = ENOMEM;
1391 					goto errout;
1392 				}
1393 				if (re->re_src.mapsize > oplen) {
1394 					/*
1395 					 * There's data following what the
1396 					 * hardware will copy for us.  If this
1397 					 * isn't just the ICV (that's going to
1398 					 * be written on completion), copy it
1399 					 * to the new mbufs
1400 					 */
1401 					if (!(maccrd &&
1402 					    (re->re_src.mapsize-oplen) == 12 &&
1403 					    maccrd->crd_inject == oplen))
1404 						safe_mcopy(re->re_src_m,
1405 							   re->re_dst_m,
1406 							   oplen);
1407 					else
1408 						safestats.st_noicvcopy++;
1409 				}
1410 			}
1411 		} else {
1412 			safestats.st_badflags++;
1413 			err = EINVAL;
1414 			goto errout;
1415 		}
1416 
1417 		if (re->re_dst.nsegs > 1) {
1418 			re->re_desc.d_dst = sc->sc_dpalloc.dma_paddr +
1419 			    ((caddr_t) sc->sc_dpfree - (caddr_t) sc->sc_dpring);
1420 			for (i = 0; i < re->re_dst_nsegs; i++) {
1421 				pd = sc->sc_dpfree;
1422 				KASSERT((pd->pd_flags&3) == 0 ||
1423 					(pd->pd_flags&3) == SAFE_PD_DONE,
1424 					("bogus dest particle descriptor; flags %x",
1425 						pd->pd_flags));
1426 				if (++(sc->sc_dpfree) == sc->sc_dpringtop)
1427 					sc->sc_dpfree = sc->sc_dpring;
1428 				pd->pd_addr = re->re_dst_segs[i].ds_addr;
1429 				pd->pd_flags = SAFE_PD_READY;
1430 			}
1431 			cmd0 |= SAFE_SA_CMD0_OSCATTER;
1432 		} else {
1433 			/*
1434 			 * No need for scatter, reference the operand directly.
1435 			 */
1436 			re->re_desc.d_dst = re->re_dst_segs[0].ds_addr;
1437 		}
1438 	}
1439 
1440 	/*
1441 	 * All done with setup; fillin the SA command words
1442 	 * and the packet engine descriptor.  The operation
1443 	 * is now ready for submission to the hardware.
1444 	 */
1445 	sa->sa_cmd0 = cmd0 | SAFE_SA_CMD0_IPCI | SAFE_SA_CMD0_OPCI;
1446 	sa->sa_cmd1 = cmd1
1447 		    | (coffset << SAFE_SA_CMD1_OFFSET_S)
1448 		    | SAFE_SA_CMD1_SAREV1	/* Rev 1 SA data structure */
1449 		    | SAFE_SA_CMD1_SRPCI
1450 		    ;
1451 	/*
1452 	 * NB: the order of writes is important here.  In case the
1453 	 * chip is scanning the ring because of an outstanding request
1454 	 * it might nab this one too.  In that case we need to make
1455 	 * sure the setup is complete before we write the length
1456 	 * field of the descriptor as it signals the descriptor is
1457 	 * ready for processing.
1458 	 */
1459 	re->re_desc.d_csr = SAFE_PE_CSR_READY | SAFE_PE_CSR_SAPCI;
1460 	if (maccrd)
1461 		re->re_desc.d_csr |= SAFE_PE_CSR_LOADSA | SAFE_PE_CSR_HASHFINAL;
1462 	re->re_desc.d_len = oplen
1463 			  | SAFE_PE_LEN_READY
1464 			  | (bypass << SAFE_PE_LEN_BYPASS_S)
1465 			  ;
1466 
1467 	safestats.st_ipackets++;
1468 	safestats.st_ibytes += oplen;
1469 
1470 	if (++(sc->sc_front) == sc->sc_ringtop)
1471 		sc->sc_front = sc->sc_ring;
1472 
1473 	/* XXX honor batching */
1474 	safe_feed(sc, re);
1475 	mtx_unlock(&sc->sc_ringmtx);
1476 	return (0);
1477 
1478 errout:
1479 	if ((re->re_dst_m != NULL) && (re->re_src_m != re->re_dst_m))
1480 		m_freem(re->re_dst_m);
1481 
1482 	if (re->re_dst_map != NULL && re->re_dst_map != re->re_src_map) {
1483 		bus_dmamap_unload(sc->sc_dstdmat, re->re_dst_map);
1484 		bus_dmamap_destroy(sc->sc_dstdmat, re->re_dst_map);
1485 	}
1486 	if (re->re_src_map != NULL) {
1487 		bus_dmamap_unload(sc->sc_srcdmat, re->re_src_map);
1488 		bus_dmamap_destroy(sc->sc_srcdmat, re->re_src_map);
1489 	}
1490 	mtx_unlock(&sc->sc_ringmtx);
1491 	if (err != ERESTART) {
1492 		crp->crp_etype = err;
1493 		crypto_done(crp);
1494 	} else {
1495 		sc->sc_needwakeup |= CRYPTO_SYMQ;
1496 	}
1497 	return (err);
1498 }
1499 
1500 static void
1501 safe_callback(struct safe_softc *sc, struct safe_ringentry *re)
1502 {
1503 	struct cryptop *crp = (struct cryptop *)re->re_crp;
1504 	struct cryptodesc *crd;
1505 
1506 	safestats.st_opackets++;
1507 	safestats.st_obytes += re->re_dst.mapsize;
1508 
1509 	safe_dma_sync(&sc->sc_ringalloc,
1510 		BUS_DMASYNC_POSTREAD|BUS_DMASYNC_POSTWRITE);
1511 	if (re->re_desc.d_csr & SAFE_PE_CSR_STATUS) {
1512 		device_printf(sc->sc_dev, "csr 0x%x cmd0 0x%x cmd1 0x%x\n",
1513 			re->re_desc.d_csr,
1514 			re->re_sa.sa_cmd0, re->re_sa.sa_cmd1);
1515 		safestats.st_peoperr++;
1516 		crp->crp_etype = EIO;		/* something more meaningful? */
1517 	}
1518 	if (re->re_dst_map != NULL && re->re_dst_map != re->re_src_map) {
1519 		bus_dmamap_sync(sc->sc_dstdmat, re->re_dst_map,
1520 		    BUS_DMASYNC_POSTREAD);
1521 		bus_dmamap_unload(sc->sc_dstdmat, re->re_dst_map);
1522 		bus_dmamap_destroy(sc->sc_dstdmat, re->re_dst_map);
1523 	}
1524 	bus_dmamap_sync(sc->sc_srcdmat, re->re_src_map, BUS_DMASYNC_POSTWRITE);
1525 	bus_dmamap_unload(sc->sc_srcdmat, re->re_src_map);
1526 	bus_dmamap_destroy(sc->sc_srcdmat, re->re_src_map);
1527 
1528 	/*
1529 	 * If result was written to a differet mbuf chain, swap
1530 	 * it in as the return value and reclaim the original.
1531 	 */
1532 	if ((crp->crp_flags & CRYPTO_F_IMBUF) && re->re_src_m != re->re_dst_m) {
1533 		m_freem(re->re_src_m);
1534 		crp->crp_buf = (caddr_t)re->re_dst_m;
1535 	}
1536 
1537 	if (re->re_flags & SAFE_QFLAGS_COPYOUTIV) {
1538 		/* copy out IV for future use */
1539 		for (crd = crp->crp_desc; crd; crd = crd->crd_next) {
1540 			int ivsize;
1541 
1542 			if (crd->crd_alg == CRYPTO_DES_CBC ||
1543 			    crd->crd_alg == CRYPTO_3DES_CBC) {
1544 				ivsize = 2*sizeof(u_int32_t);
1545 			} else if (crd->crd_alg == CRYPTO_AES_CBC) {
1546 				ivsize = 4*sizeof(u_int32_t);
1547 			} else
1548 				continue;
1549 			crypto_copydata(crp->crp_flags, crp->crp_buf,
1550 			    crd->crd_skip + crd->crd_len - ivsize, ivsize,
1551 			    (caddr_t)sc->sc_sessions[re->re_sesn].ses_iv);
1552 			break;
1553 		}
1554 	}
1555 
1556 	if (re->re_flags & SAFE_QFLAGS_COPYOUTICV) {
1557 		/* copy out ICV result */
1558 		for (crd = crp->crp_desc; crd; crd = crd->crd_next) {
1559 			if (!(crd->crd_alg == CRYPTO_MD5_HMAC ||
1560 			    crd->crd_alg == CRYPTO_SHA1_HMAC ||
1561 			    crd->crd_alg == CRYPTO_NULL_HMAC))
1562 				continue;
1563 			if (crd->crd_alg == CRYPTO_SHA1_HMAC) {
1564 				/*
1565 				 * SHA-1 ICV's are byte-swapped; fix 'em up
1566 				 * before copy them to their destination.
1567 				 */
1568 				re->re_sastate.sa_saved_indigest[0] =
1569 				    bswap32(re->re_sastate.sa_saved_indigest[0]);
1570 				re->re_sastate.sa_saved_indigest[1] =
1571 				    bswap32(re->re_sastate.sa_saved_indigest[1]);
1572 				re->re_sastate.sa_saved_indigest[2] =
1573 				    bswap32(re->re_sastate.sa_saved_indigest[2]);
1574 			}
1575 			crypto_copyback(crp->crp_flags, crp->crp_buf,
1576 			    crd->crd_inject,
1577 			    sc->sc_sessions[re->re_sesn].ses_mlen,
1578 			    (caddr_t)re->re_sastate.sa_saved_indigest);
1579 			break;
1580 		}
1581 	}
1582 	crypto_done(crp);
1583 }
1584 
1585 /*
1586  * Copy all data past offset from srcm to dstm.
1587  */
1588 static void
1589 safe_mcopy(struct mbuf *srcm, struct mbuf *dstm, u_int offset)
1590 {
1591 	u_int j, dlen, slen;
1592 	caddr_t dptr, sptr;
1593 
1594 	/*
1595 	 * Advance src and dst to offset.
1596 	 */
1597 	j = offset;
1598 	while (j >= srcm->m_len) {
1599 		j -= srcm->m_len;
1600 		srcm = srcm->m_next;
1601 		if (srcm == NULL)
1602 			return;
1603 	}
1604 	sptr = mtod(srcm, caddr_t) + j;
1605 	slen = srcm->m_len - j;
1606 
1607 	j = offset;
1608 	while (j >= dstm->m_len) {
1609 		j -= dstm->m_len;
1610 		dstm = dstm->m_next;
1611 		if (dstm == NULL)
1612 			return;
1613 	}
1614 	dptr = mtod(dstm, caddr_t) + j;
1615 	dlen = dstm->m_len - j;
1616 
1617 	/*
1618 	 * Copy everything that remains.
1619 	 */
1620 	for (;;) {
1621 		j = min(slen, dlen);
1622 		bcopy(sptr, dptr, j);
1623 		if (slen == j) {
1624 			srcm = srcm->m_next;
1625 			if (srcm == NULL)
1626 				return;
1627 			sptr = srcm->m_data;
1628 			slen = srcm->m_len;
1629 		} else
1630 			sptr += j, slen -= j;
1631 		if (dlen == j) {
1632 			dstm = dstm->m_next;
1633 			if (dstm == NULL)
1634 				return;
1635 			dptr = dstm->m_data;
1636 			dlen = dstm->m_len;
1637 		} else
1638 			dptr += j, dlen -= j;
1639 	}
1640 }
1641 
1642 #ifndef SAFE_NO_RNG
1643 #define	SAFE_RNG_MAXWAIT	1000
1644 
1645 static void
1646 safe_rng_init(struct safe_softc *sc)
1647 {
1648 	u_int32_t w, v;
1649 	int i;
1650 
1651 	WRITE_REG(sc, SAFE_RNG_CTRL, 0);
1652 	/* use default value according to the manual */
1653 	WRITE_REG(sc, SAFE_RNG_CNFG, 0x834);	/* magic from SafeNet */
1654 	WRITE_REG(sc, SAFE_RNG_ALM_CNT, 0);
1655 
1656 	/*
1657 	 * There is a bug in rev 1.0 of the 1140 that when the RNG
1658 	 * is brought out of reset the ready status flag does not
1659 	 * work until the RNG has finished its internal initialization.
1660 	 *
1661 	 * So in order to determine the device is through its
1662 	 * initialization we must read the data register, using the
1663 	 * status reg in the read in case it is initialized.  Then read
1664 	 * the data register until it changes from the first read.
1665 	 * Once it changes read the data register until it changes
1666 	 * again.  At this time the RNG is considered initialized.
1667 	 * This could take between 750ms - 1000ms in time.
1668 	 */
1669 	i = 0;
1670 	w = READ_REG(sc, SAFE_RNG_OUT);
1671 	do {
1672 		v = READ_REG(sc, SAFE_RNG_OUT);
1673 		if (v != w) {
1674 			w = v;
1675 			break;
1676 		}
1677 		DELAY(10);
1678 	} while (++i < SAFE_RNG_MAXWAIT);
1679 
1680 	/* Wait Until data changes again */
1681 	i = 0;
1682 	do {
1683 		v = READ_REG(sc, SAFE_RNG_OUT);
1684 		if (v != w)
1685 			break;
1686 		DELAY(10);
1687 	} while (++i < SAFE_RNG_MAXWAIT);
1688 }
1689 
1690 static __inline void
1691 safe_rng_disable_short_cycle(struct safe_softc *sc)
1692 {
1693 	WRITE_REG(sc, SAFE_RNG_CTRL,
1694 		READ_REG(sc, SAFE_RNG_CTRL) &~ SAFE_RNG_CTRL_SHORTEN);
1695 }
1696 
1697 static __inline void
1698 safe_rng_enable_short_cycle(struct safe_softc *sc)
1699 {
1700 	WRITE_REG(sc, SAFE_RNG_CTRL,
1701 		READ_REG(sc, SAFE_RNG_CTRL) | SAFE_RNG_CTRL_SHORTEN);
1702 }
1703 
1704 static __inline u_int32_t
1705 safe_rng_read(struct safe_softc *sc)
1706 {
1707 	int i;
1708 
1709 	i = 0;
1710 	while (READ_REG(sc, SAFE_RNG_STAT) != 0 && ++i < SAFE_RNG_MAXWAIT)
1711 		;
1712 	return READ_REG(sc, SAFE_RNG_OUT);
1713 }
1714 
1715 static void
1716 safe_rng(void *arg)
1717 {
1718 	struct safe_softc *sc = arg;
1719 	u_int32_t buf[SAFE_RNG_MAXBUFSIZ];	/* NB: maybe move to softc */
1720 	u_int maxwords;
1721 	int i;
1722 
1723 	safestats.st_rng++;
1724 	/*
1725 	 * Fetch the next block of data.
1726 	 */
1727 	maxwords = safe_rngbufsize;
1728 	if (maxwords > SAFE_RNG_MAXBUFSIZ)
1729 		maxwords = SAFE_RNG_MAXBUFSIZ;
1730 retry:
1731 	for (i = 0; i < maxwords; i++)
1732 		buf[i] = safe_rng_read(sc);
1733 	/*
1734 	 * Check the comparator alarm count and reset the h/w if
1735 	 * it exceeds our threshold.  This guards against the
1736 	 * hardware oscillators resonating with external signals.
1737 	 */
1738 	if (READ_REG(sc, SAFE_RNG_ALM_CNT) > safe_rngmaxalarm) {
1739 		u_int32_t freq_inc, w;
1740 
1741 		DPRINTF(("%s: alarm count %u exceeds threshold %u\n", __func__,
1742 			READ_REG(sc, SAFE_RNG_ALM_CNT), safe_rngmaxalarm));
1743 		safestats.st_rngalarm++;
1744 		safe_rng_enable_short_cycle(sc);
1745 		freq_inc = 18;
1746 		for (i = 0; i < 64; i++) {
1747 			w = READ_REG(sc, SAFE_RNG_CNFG);
1748 			freq_inc = ((w + freq_inc) & 0x3fL);
1749 			w = ((w & ~0x3fL) | freq_inc);
1750 			WRITE_REG(sc, SAFE_RNG_CNFG, w);
1751 
1752 			WRITE_REG(sc, SAFE_RNG_ALM_CNT, 0);
1753 
1754 			(void) safe_rng_read(sc);
1755 			DELAY(25);
1756 
1757 			if (READ_REG(sc, SAFE_RNG_ALM_CNT) == 0) {
1758 				safe_rng_disable_short_cycle(sc);
1759 				goto retry;
1760 			}
1761 			freq_inc = 1;
1762 		}
1763 		safe_rng_disable_short_cycle(sc);
1764 	} else
1765 		WRITE_REG(sc, SAFE_RNG_ALM_CNT, 0);
1766 
1767 	(*sc->sc_harvest)(sc->sc_rndtest, buf, maxwords*sizeof (u_int32_t));
1768 	callout_reset(&sc->sc_rngto,
1769 		hz * (safe_rnginterval ? safe_rnginterval : 1), safe_rng, sc);
1770 }
1771 #endif /* SAFE_NO_RNG */
1772 
1773 static void
1774 safe_dmamap_cb(void *arg, bus_dma_segment_t *segs, int nseg, int error)
1775 {
1776 	bus_addr_t *paddr = (bus_addr_t*) arg;
1777 	*paddr = segs->ds_addr;
1778 }
1779 
1780 static int
1781 safe_dma_malloc(
1782 	struct safe_softc *sc,
1783 	bus_size_t size,
1784 	struct safe_dma_alloc *dma,
1785 	int mapflags
1786 )
1787 {
1788 	int r;
1789 
1790 	r = bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev),	/* parent */
1791 			       sizeof(u_int32_t), 0,	/* alignment, bounds */
1792 			       BUS_SPACE_MAXADDR_32BIT,	/* lowaddr */
1793 			       BUS_SPACE_MAXADDR,	/* highaddr */
1794 			       NULL, NULL,		/* filter, filterarg */
1795 			       size,			/* maxsize */
1796 			       1,			/* nsegments */
1797 			       size,			/* maxsegsize */
1798 			       BUS_DMA_ALLOCNOW,	/* flags */
1799 			       NULL, NULL,		/* locking */
1800 			       &dma->dma_tag);
1801 	if (r != 0) {
1802 		device_printf(sc->sc_dev, "safe_dma_malloc: "
1803 			"bus_dma_tag_create failed; error %u\n", r);
1804 		goto fail_0;
1805 	}
1806 
1807 	r = bus_dmamem_alloc(dma->dma_tag, (void**) &dma->dma_vaddr,
1808 			     BUS_DMA_NOWAIT, &dma->dma_map);
1809 	if (r != 0) {
1810 		device_printf(sc->sc_dev, "safe_dma_malloc: "
1811 			"bus_dmammem_alloc failed; size %ju, error %u\n",
1812 			(uintmax_t)size, r);
1813 		goto fail_1;
1814 	}
1815 
1816 	r = bus_dmamap_load(dma->dma_tag, dma->dma_map, dma->dma_vaddr,
1817 		            size,
1818 			    safe_dmamap_cb,
1819 			    &dma->dma_paddr,
1820 			    mapflags | BUS_DMA_NOWAIT);
1821 	if (r != 0) {
1822 		device_printf(sc->sc_dev, "safe_dma_malloc: "
1823 			"bus_dmamap_load failed; error %u\n", r);
1824 		goto fail_2;
1825 	}
1826 
1827 	dma->dma_size = size;
1828 	return (0);
1829 
1830 	bus_dmamap_unload(dma->dma_tag, dma->dma_map);
1831 fail_2:
1832 	bus_dmamem_free(dma->dma_tag, dma->dma_vaddr, dma->dma_map);
1833 fail_1:
1834 	bus_dma_tag_destroy(dma->dma_tag);
1835 fail_0:
1836 	dma->dma_tag = NULL;
1837 	return (r);
1838 }
1839 
1840 static void
1841 safe_dma_free(struct safe_softc *sc, struct safe_dma_alloc *dma)
1842 {
1843 	bus_dmamap_unload(dma->dma_tag, dma->dma_map);
1844 	bus_dmamem_free(dma->dma_tag, dma->dma_vaddr, dma->dma_map);
1845 	bus_dma_tag_destroy(dma->dma_tag);
1846 }
1847 
1848 /*
1849  * Resets the board.  Values in the regesters are left as is
1850  * from the reset (i.e. initial values are assigned elsewhere).
1851  */
1852 static void
1853 safe_reset_board(struct safe_softc *sc)
1854 {
1855 	u_int32_t v;
1856 	/*
1857 	 * Reset the device.  The manual says no delay
1858 	 * is needed between marking and clearing reset.
1859 	 */
1860 	v = READ_REG(sc, SAFE_PE_DMACFG) &~
1861 		(SAFE_PE_DMACFG_PERESET | SAFE_PE_DMACFG_PDRRESET |
1862 		 SAFE_PE_DMACFG_SGRESET);
1863 	WRITE_REG(sc, SAFE_PE_DMACFG, v
1864 				    | SAFE_PE_DMACFG_PERESET
1865 				    | SAFE_PE_DMACFG_PDRRESET
1866 				    | SAFE_PE_DMACFG_SGRESET);
1867 	WRITE_REG(sc, SAFE_PE_DMACFG, v);
1868 }
1869 
1870 /*
1871  * Initialize registers we need to touch only once.
1872  */
1873 static void
1874 safe_init_board(struct safe_softc *sc)
1875 {
1876 	u_int32_t v, dwords;
1877 
1878 	v = READ_REG(sc, SAFE_PE_DMACFG);
1879 	v &=~ SAFE_PE_DMACFG_PEMODE;
1880 	v |= SAFE_PE_DMACFG_FSENA		/* failsafe enable */
1881 	  |  SAFE_PE_DMACFG_GPRPCI		/* gather ring on PCI */
1882 	  |  SAFE_PE_DMACFG_SPRPCI		/* scatter ring on PCI */
1883 	  |  SAFE_PE_DMACFG_ESDESC		/* endian-swap descriptors */
1884 	  |  SAFE_PE_DMACFG_ESSA		/* endian-swap SA's */
1885 	  |  SAFE_PE_DMACFG_ESPDESC		/* endian-swap part. desc's */
1886 	  ;
1887 	WRITE_REG(sc, SAFE_PE_DMACFG, v);
1888 #if 0
1889 	/* XXX select byte swap based on host byte order */
1890 	WRITE_REG(sc, SAFE_ENDIAN, 0x1b);
1891 #endif
1892 	if (sc->sc_chiprev == SAFE_REV(1,0)) {
1893 		/*
1894 		 * Avoid large PCI DMA transfers.  Rev 1.0 has a bug where
1895 		 * "target mode transfers" done while the chip is DMA'ing
1896 		 * >1020 bytes cause the hardware to lockup.  To avoid this
1897 		 * we reduce the max PCI transfer size and use small source
1898 		 * particle descriptors (<= 256 bytes).
1899 		 */
1900 		WRITE_REG(sc, SAFE_DMA_CFG, 256);
1901 		device_printf(sc->sc_dev,
1902 			"Reduce max DMA size to %u words for rev %u.%u WAR\n",
1903 			(READ_REG(sc, SAFE_DMA_CFG)>>2) & 0xff,
1904 			SAFE_REV_MAJ(sc->sc_chiprev),
1905 			SAFE_REV_MIN(sc->sc_chiprev));
1906 	}
1907 
1908 	/* NB: operands+results are overlaid */
1909 	WRITE_REG(sc, SAFE_PE_PDRBASE, sc->sc_ringalloc.dma_paddr);
1910 	WRITE_REG(sc, SAFE_PE_RDRBASE, sc->sc_ringalloc.dma_paddr);
1911 	/*
1912 	 * Configure ring entry size and number of items in the ring.
1913 	 */
1914 	KASSERT((sizeof(struct safe_ringentry) % sizeof(u_int32_t)) == 0,
1915 		("PE ring entry not 32-bit aligned!"));
1916 	dwords = sizeof(struct safe_ringentry) / sizeof(u_int32_t);
1917 	WRITE_REG(sc, SAFE_PE_RINGCFG,
1918 		(dwords << SAFE_PE_RINGCFG_OFFSET_S) | SAFE_MAX_NQUEUE);
1919 	WRITE_REG(sc, SAFE_PE_RINGPOLL, 0);	/* disable polling */
1920 
1921 	WRITE_REG(sc, SAFE_PE_GRNGBASE, sc->sc_spalloc.dma_paddr);
1922 	WRITE_REG(sc, SAFE_PE_SRNGBASE, sc->sc_dpalloc.dma_paddr);
1923 	WRITE_REG(sc, SAFE_PE_PARTSIZE,
1924 		(SAFE_TOTAL_DPART<<16) | SAFE_TOTAL_SPART);
1925 	/*
1926 	 * NB: destination particles are fixed size.  We use
1927 	 *     an mbuf cluster and require all results go to
1928 	 *     clusters or smaller.
1929 	 */
1930 	WRITE_REG(sc, SAFE_PE_PARTCFG, SAFE_MAX_DSIZE);
1931 
1932 	/* it's now safe to enable PE mode, do it */
1933 	WRITE_REG(sc, SAFE_PE_DMACFG, v | SAFE_PE_DMACFG_PEMODE);
1934 
1935 	/*
1936 	 * Configure hardware to use level-triggered interrupts and
1937 	 * to interrupt after each descriptor is processed.
1938 	 */
1939 	WRITE_REG(sc, SAFE_HI_CFG, SAFE_HI_CFG_LEVEL);
1940 	WRITE_REG(sc, SAFE_HI_DESC_CNT, 1);
1941 	WRITE_REG(sc, SAFE_HI_MASK, SAFE_INT_PE_DDONE | SAFE_INT_PE_ERROR);
1942 }
1943 
1944 /*
1945  * Init PCI registers
1946  */
1947 static void
1948 safe_init_pciregs(device_t dev)
1949 {
1950 }
1951 
1952 /*
1953  * Clean up after a chip crash.
1954  * It is assumed that the caller in splimp()
1955  */
1956 static void
1957 safe_cleanchip(struct safe_softc *sc)
1958 {
1959 
1960 	if (sc->sc_nqchip != 0) {
1961 		struct safe_ringentry *re = sc->sc_back;
1962 
1963 		while (re != sc->sc_front) {
1964 			if (re->re_desc.d_csr != 0)
1965 				safe_free_entry(sc, re);
1966 			if (++re == sc->sc_ringtop)
1967 				re = sc->sc_ring;
1968 		}
1969 		sc->sc_back = re;
1970 		sc->sc_nqchip = 0;
1971 	}
1972 }
1973 
1974 /*
1975  * free a safe_q
1976  * It is assumed that the caller is within splimp().
1977  */
1978 static int
1979 safe_free_entry(struct safe_softc *sc, struct safe_ringentry *re)
1980 {
1981 	struct cryptop *crp;
1982 
1983 	/*
1984 	 * Free header MCR
1985 	 */
1986 	if ((re->re_dst_m != NULL) && (re->re_src_m != re->re_dst_m))
1987 		m_freem(re->re_dst_m);
1988 
1989 	crp = (struct cryptop *)re->re_crp;
1990 
1991 	re->re_desc.d_csr = 0;
1992 
1993 	crp->crp_etype = EFAULT;
1994 	crypto_done(crp);
1995 	return(0);
1996 }
1997 
1998 /*
1999  * Routine to reset the chip and clean up.
2000  * It is assumed that the caller is in splimp()
2001  */
2002 static void
2003 safe_totalreset(struct safe_softc *sc)
2004 {
2005 	safe_reset_board(sc);
2006 	safe_init_board(sc);
2007 	safe_cleanchip(sc);
2008 }
2009 
2010 /*
2011  * Is the operand suitable aligned for direct DMA.  Each
2012  * segment must be aligned on a 32-bit boundary and all
2013  * but the last segment must be a multiple of 4 bytes.
2014  */
2015 static int
2016 safe_dmamap_aligned(const struct safe_operand *op)
2017 {
2018 	int i;
2019 
2020 	for (i = 0; i < op->nsegs; i++) {
2021 		if (op->segs[i].ds_addr & 3)
2022 			return (0);
2023 		if (i != (op->nsegs - 1) && (op->segs[i].ds_len & 3))
2024 			return (0);
2025 	}
2026 	return (1);
2027 }
2028 
2029 /*
2030  * Is the operand suitable for direct DMA as the destination
2031  * of an operation.  The hardware requires that each ``particle''
2032  * but the last in an operation result have the same size.  We
2033  * fix that size at SAFE_MAX_DSIZE bytes.  This routine returns
2034  * 0 if some segment is not a multiple of of this size, 1 if all
2035  * segments are exactly this size, or 2 if segments are at worst
2036  * a multple of this size.
2037  */
2038 static int
2039 safe_dmamap_uniform(const struct safe_operand *op)
2040 {
2041 	int result = 1;
2042 
2043 	if (op->nsegs > 0) {
2044 		int i;
2045 
2046 		for (i = 0; i < op->nsegs-1; i++) {
2047 			if (op->segs[i].ds_len % SAFE_MAX_DSIZE)
2048 				return (0);
2049 			if (op->segs[i].ds_len != SAFE_MAX_DSIZE)
2050 				result = 2;
2051 		}
2052 	}
2053 	return (result);
2054 }
2055 
2056 #ifdef SAFE_DEBUG
2057 static void
2058 safe_dump_dmastatus(struct safe_softc *sc, const char *tag)
2059 {
2060 	printf("%s: ENDIAN 0x%x SRC 0x%x DST 0x%x STAT 0x%x\n"
2061 		, tag
2062 		, READ_REG(sc, SAFE_DMA_ENDIAN)
2063 		, READ_REG(sc, SAFE_DMA_SRCADDR)
2064 		, READ_REG(sc, SAFE_DMA_DSTADDR)
2065 		, READ_REG(sc, SAFE_DMA_STAT)
2066 	);
2067 }
2068 
2069 static void
2070 safe_dump_intrstate(struct safe_softc *sc, const char *tag)
2071 {
2072 	printf("%s: HI_CFG 0x%x HI_MASK 0x%x HI_DESC_CNT 0x%x HU_STAT 0x%x HM_STAT 0x%x\n"
2073 		, tag
2074 		, READ_REG(sc, SAFE_HI_CFG)
2075 		, READ_REG(sc, SAFE_HI_MASK)
2076 		, READ_REG(sc, SAFE_HI_DESC_CNT)
2077 		, READ_REG(sc, SAFE_HU_STAT)
2078 		, READ_REG(sc, SAFE_HM_STAT)
2079 	);
2080 }
2081 
2082 static void
2083 safe_dump_ringstate(struct safe_softc *sc, const char *tag)
2084 {
2085 	u_int32_t estat = READ_REG(sc, SAFE_PE_ERNGSTAT);
2086 
2087 	/* NB: assume caller has lock on ring */
2088 	printf("%s: ERNGSTAT %x (next %u) back %lu front %lu\n",
2089 		tag,
2090 		estat, (estat >> SAFE_PE_ERNGSTAT_NEXT_S),
2091 		(unsigned long)(sc->sc_back - sc->sc_ring),
2092 		(unsigned long)(sc->sc_front - sc->sc_ring));
2093 }
2094 
2095 static void
2096 safe_dump_request(struct safe_softc *sc, const char* tag, struct safe_ringentry *re)
2097 {
2098 	int ix, nsegs;
2099 
2100 	ix = re - sc->sc_ring;
2101 	printf("%s: %p (%u): csr %x src %x dst %x sa %x len %x\n"
2102 		, tag
2103 		, re, ix
2104 		, re->re_desc.d_csr
2105 		, re->re_desc.d_src
2106 		, re->re_desc.d_dst
2107 		, re->re_desc.d_sa
2108 		, re->re_desc.d_len
2109 	);
2110 	if (re->re_src.nsegs > 1) {
2111 		ix = (re->re_desc.d_src - sc->sc_spalloc.dma_paddr) /
2112 			sizeof(struct safe_pdesc);
2113 		for (nsegs = re->re_src.nsegs; nsegs; nsegs--) {
2114 			printf(" spd[%u] %p: %p size %u flags %x"
2115 				, ix, &sc->sc_spring[ix]
2116 				, (caddr_t)(uintptr_t) sc->sc_spring[ix].pd_addr
2117 				, sc->sc_spring[ix].pd_size
2118 				, sc->sc_spring[ix].pd_flags
2119 			);
2120 			if (sc->sc_spring[ix].pd_size == 0)
2121 				printf(" (zero!)");
2122 			printf("\n");
2123 			if (++ix == SAFE_TOTAL_SPART)
2124 				ix = 0;
2125 		}
2126 	}
2127 	if (re->re_dst.nsegs > 1) {
2128 		ix = (re->re_desc.d_dst - sc->sc_dpalloc.dma_paddr) /
2129 			sizeof(struct safe_pdesc);
2130 		for (nsegs = re->re_dst.nsegs; nsegs; nsegs--) {
2131 			printf(" dpd[%u] %p: %p flags %x\n"
2132 				, ix, &sc->sc_dpring[ix]
2133 				, (caddr_t)(uintptr_t) sc->sc_dpring[ix].pd_addr
2134 				, sc->sc_dpring[ix].pd_flags
2135 			);
2136 			if (++ix == SAFE_TOTAL_DPART)
2137 				ix = 0;
2138 		}
2139 	}
2140 	printf("sa: cmd0 %08x cmd1 %08x staterec %x\n",
2141 		re->re_sa.sa_cmd0, re->re_sa.sa_cmd1, re->re_sa.sa_staterec);
2142 	printf("sa: key %x %x %x %x %x %x %x %x\n"
2143 		, re->re_sa.sa_key[0]
2144 		, re->re_sa.sa_key[1]
2145 		, re->re_sa.sa_key[2]
2146 		, re->re_sa.sa_key[3]
2147 		, re->re_sa.sa_key[4]
2148 		, re->re_sa.sa_key[5]
2149 		, re->re_sa.sa_key[6]
2150 		, re->re_sa.sa_key[7]
2151 	);
2152 	printf("sa: indigest %x %x %x %x %x\n"
2153 		, re->re_sa.sa_indigest[0]
2154 		, re->re_sa.sa_indigest[1]
2155 		, re->re_sa.sa_indigest[2]
2156 		, re->re_sa.sa_indigest[3]
2157 		, re->re_sa.sa_indigest[4]
2158 	);
2159 	printf("sa: outdigest %x %x %x %x %x\n"
2160 		, re->re_sa.sa_outdigest[0]
2161 		, re->re_sa.sa_outdigest[1]
2162 		, re->re_sa.sa_outdigest[2]
2163 		, re->re_sa.sa_outdigest[3]
2164 		, re->re_sa.sa_outdigest[4]
2165 	);
2166 	printf("sr: iv %x %x %x %x\n"
2167 		, re->re_sastate.sa_saved_iv[0]
2168 		, re->re_sastate.sa_saved_iv[1]
2169 		, re->re_sastate.sa_saved_iv[2]
2170 		, re->re_sastate.sa_saved_iv[3]
2171 	);
2172 	printf("sr: hashbc %u indigest %x %x %x %x %x\n"
2173 		, re->re_sastate.sa_saved_hashbc
2174 		, re->re_sastate.sa_saved_indigest[0]
2175 		, re->re_sastate.sa_saved_indigest[1]
2176 		, re->re_sastate.sa_saved_indigest[2]
2177 		, re->re_sastate.sa_saved_indigest[3]
2178 		, re->re_sastate.sa_saved_indigest[4]
2179 	);
2180 }
2181 
2182 static void
2183 safe_dump_ring(struct safe_softc *sc, const char *tag)
2184 {
2185 	mtx_lock(&sc->sc_ringmtx);
2186 	printf("\nSafeNet Ring State:\n");
2187 	safe_dump_intrstate(sc, tag);
2188 	safe_dump_dmastatus(sc, tag);
2189 	safe_dump_ringstate(sc, tag);
2190 	if (sc->sc_nqchip) {
2191 		struct safe_ringentry *re = sc->sc_back;
2192 		do {
2193 			safe_dump_request(sc, tag, re);
2194 			if (++re == sc->sc_ringtop)
2195 				re = sc->sc_ring;
2196 		} while (re != sc->sc_front);
2197 	}
2198 	mtx_unlock(&sc->sc_ringmtx);
2199 }
2200 
2201 static int
2202 sysctl_hw_safe_dump(SYSCTL_HANDLER_ARGS)
2203 {
2204 	char dmode[64];
2205 	int error;
2206 
2207 	strncpy(dmode, "", sizeof(dmode) - 1);
2208 	dmode[sizeof(dmode) - 1] = '\0';
2209 	error = sysctl_handle_string(oidp, &dmode[0], sizeof(dmode), req);
2210 
2211 	if (error == 0 && req->newptr != NULL) {
2212 		struct safe_softc *sc = safec;
2213 
2214 		if (!sc)
2215 			return EINVAL;
2216 		if (strncmp(dmode, "dma", 3) == 0)
2217 			safe_dump_dmastatus(sc, "safe0");
2218 		else if (strncmp(dmode, "int", 3) == 0)
2219 			safe_dump_intrstate(sc, "safe0");
2220 		else if (strncmp(dmode, "ring", 4) == 0)
2221 			safe_dump_ring(sc, "safe0");
2222 		else
2223 			return EINVAL;
2224 	}
2225 	return error;
2226 }
2227 SYSCTL_PROC(_hw_safe, OID_AUTO, dump, CTLTYPE_STRING | CTLFLAG_RW,
2228 	0, 0, sysctl_hw_safe_dump, "A", "Dump driver state");
2229 #endif /* SAFE_DEBUG */
2230