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