xref: /freebsd/sys/dev/hifn/hifn7751.c (revision aeaed508982227551b2748339033bb2483382b4d)
1 /*	$OpenBSD: hifn7751.c,v 1.120 2002/05/17 00:33:34 deraadt Exp $	*/
2 
3 /*-
4  * Invertex AEON / Hifn 7751 driver
5  * Copyright (c) 1999 Invertex Inc. All rights reserved.
6  * Copyright (c) 1999 Theo de Raadt
7  * Copyright (c) 2000-2001 Network Security Technologies, Inc.
8  *			http://www.netsec.net
9  * Copyright (c) 2003 Hifn Inc.
10  *
11  * This driver is based on a previous driver by Invertex, for which they
12  * requested:  Please send any comments, feedback, bug-fixes, or feature
13  * requests to software@invertex.com.
14  *
15  * Redistribution and use in source and binary forms, with or without
16  * modification, are permitted provided that the following conditions
17  * are met:
18  *
19  * 1. Redistributions of source code must retain the above copyright
20  *   notice, this list of conditions and the following disclaimer.
21  * 2. Redistributions in binary form must reproduce the above copyright
22  *   notice, this list of conditions and the following disclaimer in the
23  *   documentation and/or other materials provided with the distribution.
24  * 3. The name of the author may not be used to endorse or promote products
25  *   derived from this software without specific prior written permission.
26  *
27  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
28  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
29  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
30  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
31  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
32  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
33  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
34  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
35  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
36  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37  *
38  * Effort sponsored in part by the Defense Advanced Research Projects
39  * Agency (DARPA) and Air Force Research Laboratory, Air Force
40  * Materiel Command, USAF, under agreement number F30602-01-2-0537.
41  */
42 
43 #include <sys/cdefs.h>
44 __FBSDID("$FreeBSD$");
45 
46 /*
47  * Driver for various Hifn encryption processors.
48  */
49 #include "opt_hifn.h"
50 
51 #include <sys/param.h>
52 #include <sys/systm.h>
53 #include <sys/proc.h>
54 #include <sys/errno.h>
55 #include <sys/malloc.h>
56 #include <sys/kernel.h>
57 #include <sys/module.h>
58 #include <sys/mbuf.h>
59 #include <sys/lock.h>
60 #include <sys/mutex.h>
61 #include <sys/sysctl.h>
62 
63 #include <vm/vm.h>
64 #include <vm/pmap.h>
65 
66 #include <machine/bus.h>
67 #include <machine/resource.h>
68 #include <sys/bus.h>
69 #include <sys/rman.h>
70 
71 #include <opencrypto/cryptodev.h>
72 #include <sys/random.h>
73 #include <sys/kobj.h>
74 
75 #include "cryptodev_if.h"
76 
77 #include <dev/pci/pcivar.h>
78 #include <dev/pci/pcireg.h>
79 
80 #ifdef HIFN_RNDTEST
81 #include <dev/rndtest/rndtest.h>
82 #endif
83 #include <dev/hifn/hifn7751reg.h>
84 #include <dev/hifn/hifn7751var.h>
85 
86 #ifdef HIFN_VULCANDEV
87 #include <sys/conf.h>
88 #include <sys/uio.h>
89 
90 static struct cdevsw vulcanpk_cdevsw; /* forward declaration */
91 #endif
92 
93 /*
94  * Prototypes and count for the pci_device structure
95  */
96 static	int hifn_probe(device_t);
97 static	int hifn_attach(device_t);
98 static	int hifn_detach(device_t);
99 static	int hifn_suspend(device_t);
100 static	int hifn_resume(device_t);
101 static	int hifn_shutdown(device_t);
102 
103 static	int hifn_newsession(device_t, u_int32_t *, struct cryptoini *);
104 static	int hifn_freesession(device_t, u_int64_t);
105 static	int hifn_process(device_t, struct cryptop *, int);
106 
107 static device_method_t hifn_methods[] = {
108 	/* Device interface */
109 	DEVMETHOD(device_probe,		hifn_probe),
110 	DEVMETHOD(device_attach,	hifn_attach),
111 	DEVMETHOD(device_detach,	hifn_detach),
112 	DEVMETHOD(device_suspend,	hifn_suspend),
113 	DEVMETHOD(device_resume,	hifn_resume),
114 	DEVMETHOD(device_shutdown,	hifn_shutdown),
115 
116 	/* crypto device methods */
117 	DEVMETHOD(cryptodev_newsession,	hifn_newsession),
118 	DEVMETHOD(cryptodev_freesession,hifn_freesession),
119 	DEVMETHOD(cryptodev_process,	hifn_process),
120 
121 	DEVMETHOD_END
122 };
123 static driver_t hifn_driver = {
124 	"hifn",
125 	hifn_methods,
126 	sizeof (struct hifn_softc)
127 };
128 static devclass_t hifn_devclass;
129 
130 DRIVER_MODULE(hifn, pci, hifn_driver, hifn_devclass, 0, 0);
131 MODULE_DEPEND(hifn, crypto, 1, 1, 1);
132 #ifdef HIFN_RNDTEST
133 MODULE_DEPEND(hifn, rndtest, 1, 1, 1);
134 #endif
135 
136 static	void hifn_reset_board(struct hifn_softc *, int);
137 static	void hifn_reset_puc(struct hifn_softc *);
138 static	void hifn_puc_wait(struct hifn_softc *);
139 static	int hifn_enable_crypto(struct hifn_softc *);
140 static	void hifn_set_retry(struct hifn_softc *sc);
141 static	void hifn_init_dma(struct hifn_softc *);
142 static	void hifn_init_pci_registers(struct hifn_softc *);
143 static	int hifn_sramsize(struct hifn_softc *);
144 static	int hifn_dramsize(struct hifn_softc *);
145 static	int hifn_ramtype(struct hifn_softc *);
146 static	void hifn_sessions(struct hifn_softc *);
147 static	void hifn_intr(void *);
148 static	u_int hifn_write_command(struct hifn_command *, u_int8_t *);
149 static	u_int32_t hifn_next_signature(u_int32_t a, u_int cnt);
150 static	void hifn_callback(struct hifn_softc *, struct hifn_command *, u_int8_t *);
151 static	int hifn_crypto(struct hifn_softc *, struct hifn_command *, struct cryptop *, int);
152 static	int hifn_readramaddr(struct hifn_softc *, int, u_int8_t *);
153 static	int hifn_writeramaddr(struct hifn_softc *, int, u_int8_t *);
154 static	int hifn_dmamap_load_src(struct hifn_softc *, struct hifn_command *);
155 static	int hifn_dmamap_load_dst(struct hifn_softc *, struct hifn_command *);
156 static	int hifn_init_pubrng(struct hifn_softc *);
157 static	void hifn_rng(void *);
158 static	void hifn_tick(void *);
159 static	void hifn_abort(struct hifn_softc *);
160 static	void hifn_alloc_slot(struct hifn_softc *, int *, int *, int *, int *);
161 
162 static	void hifn_write_reg_0(struct hifn_softc *, bus_size_t, u_int32_t);
163 static	void hifn_write_reg_1(struct hifn_softc *, bus_size_t, u_int32_t);
164 
165 static __inline u_int32_t
166 READ_REG_0(struct hifn_softc *sc, bus_size_t reg)
167 {
168     u_int32_t v = bus_space_read_4(sc->sc_st0, sc->sc_sh0, reg);
169     sc->sc_bar0_lastreg = (bus_size_t) -1;
170     return (v);
171 }
172 #define	WRITE_REG_0(sc, reg, val)	hifn_write_reg_0(sc, reg, val)
173 
174 static __inline u_int32_t
175 READ_REG_1(struct hifn_softc *sc, bus_size_t reg)
176 {
177     u_int32_t v = bus_space_read_4(sc->sc_st1, sc->sc_sh1, reg);
178     sc->sc_bar1_lastreg = (bus_size_t) -1;
179     return (v);
180 }
181 #define	WRITE_REG_1(sc, reg, val)	hifn_write_reg_1(sc, reg, val)
182 
183 static SYSCTL_NODE(_hw, OID_AUTO, hifn, CTLFLAG_RD, 0,
184 	    "Hifn driver parameters");
185 
186 #ifdef HIFN_DEBUG
187 static	int hifn_debug = 0;
188 SYSCTL_INT(_hw_hifn, OID_AUTO, debug, CTLFLAG_RW, &hifn_debug,
189 	    0, "control debugging msgs");
190 #endif
191 
192 static	struct hifn_stats hifnstats;
193 SYSCTL_STRUCT(_hw_hifn, OID_AUTO, stats, CTLFLAG_RD, &hifnstats,
194 	    hifn_stats, "driver statistics");
195 static	int hifn_maxbatch = 1;
196 SYSCTL_INT(_hw_hifn, OID_AUTO, maxbatch, CTLFLAG_RW, &hifn_maxbatch,
197 	    0, "max ops to batch w/o interrupt");
198 
199 /*
200  * Probe for a supported device.  The PCI vendor and device
201  * IDs are used to detect devices we know how to handle.
202  */
203 static int
204 hifn_probe(device_t dev)
205 {
206 	if (pci_get_vendor(dev) == PCI_VENDOR_INVERTEX &&
207 	    pci_get_device(dev) == PCI_PRODUCT_INVERTEX_AEON)
208 		return (BUS_PROBE_DEFAULT);
209 	if (pci_get_vendor(dev) == PCI_VENDOR_HIFN &&
210 	    (pci_get_device(dev) == PCI_PRODUCT_HIFN_7751 ||
211 	     pci_get_device(dev) == PCI_PRODUCT_HIFN_7951 ||
212 	     pci_get_device(dev) == PCI_PRODUCT_HIFN_7955 ||
213 	     pci_get_device(dev) == PCI_PRODUCT_HIFN_7956 ||
214 	     pci_get_device(dev) == PCI_PRODUCT_HIFN_7811))
215 		return (BUS_PROBE_DEFAULT);
216 	if (pci_get_vendor(dev) == PCI_VENDOR_NETSEC &&
217 	    pci_get_device(dev) == PCI_PRODUCT_NETSEC_7751)
218 		return (BUS_PROBE_DEFAULT);
219 	return (ENXIO);
220 }
221 
222 static void
223 hifn_dmamap_cb(void *arg, bus_dma_segment_t *segs, int nseg, int error)
224 {
225 	bus_addr_t *paddr = (bus_addr_t*) arg;
226 	*paddr = segs->ds_addr;
227 }
228 
229 static const char*
230 hifn_partname(struct hifn_softc *sc)
231 {
232 	/* XXX sprintf numbers when not decoded */
233 	switch (pci_get_vendor(sc->sc_dev)) {
234 	case PCI_VENDOR_HIFN:
235 		switch (pci_get_device(sc->sc_dev)) {
236 		case PCI_PRODUCT_HIFN_6500:	return "Hifn 6500";
237 		case PCI_PRODUCT_HIFN_7751:	return "Hifn 7751";
238 		case PCI_PRODUCT_HIFN_7811:	return "Hifn 7811";
239 		case PCI_PRODUCT_HIFN_7951:	return "Hifn 7951";
240 		case PCI_PRODUCT_HIFN_7955:	return "Hifn 7955";
241 		case PCI_PRODUCT_HIFN_7956:	return "Hifn 7956";
242 		}
243 		return "Hifn unknown-part";
244 	case PCI_VENDOR_INVERTEX:
245 		switch (pci_get_device(sc->sc_dev)) {
246 		case PCI_PRODUCT_INVERTEX_AEON:	return "Invertex AEON";
247 		}
248 		return "Invertex unknown-part";
249 	case PCI_VENDOR_NETSEC:
250 		switch (pci_get_device(sc->sc_dev)) {
251 		case PCI_PRODUCT_NETSEC_7751:	return "NetSec 7751";
252 		}
253 		return "NetSec unknown-part";
254 	}
255 	return "Unknown-vendor unknown-part";
256 }
257 
258 static void
259 default_harvest(struct rndtest_state *rsp, void *buf, u_int count)
260 {
261 	random_harvest(buf, count, count*NBBY/2, RANDOM_PURE_HIFN);
262 }
263 
264 static u_int
265 checkmaxmin(device_t dev, const char *what, u_int v, u_int min, u_int max)
266 {
267 	if (v > max) {
268 		device_printf(dev, "Warning, %s %u out of range, "
269 			"using max %u\n", what, v, max);
270 		v = max;
271 	} else if (v < min) {
272 		device_printf(dev, "Warning, %s %u out of range, "
273 			"using min %u\n", what, v, min);
274 		v = min;
275 	}
276 	return v;
277 }
278 
279 /*
280  * Select PLL configuration for 795x parts.  This is complicated in
281  * that we cannot determine the optimal parameters without user input.
282  * The reference clock is derived from an external clock through a
283  * multiplier.  The external clock is either the host bus (i.e. PCI)
284  * or an external clock generator.  When using the PCI bus we assume
285  * the clock is either 33 or 66 MHz; for an external source we cannot
286  * tell the speed.
287  *
288  * PLL configuration is done with a string: "pci" for PCI bus, or "ext"
289  * for an external source, followed by the frequency.  We calculate
290  * the appropriate multiplier and PLL register contents accordingly.
291  * When no configuration is given we default to "pci66" since that
292  * always will allow the card to work.  If a card is using the PCI
293  * bus clock and in a 33MHz slot then it will be operating at half
294  * speed until the correct information is provided.
295  *
296  * We use a default setting of "ext66" because according to Mike Ham
297  * of HiFn, almost every board in existence has an external crystal
298  * populated at 66Mhz. Using PCI can be a problem on modern motherboards,
299  * because PCI33 can have clocks from 0 to 33Mhz, and some have
300  * non-PCI-compliant spread-spectrum clocks, which can confuse the pll.
301  */
302 static void
303 hifn_getpllconfig(device_t dev, u_int *pll)
304 {
305 	const char *pllspec;
306 	u_int freq, mul, fl, fh;
307 	u_int32_t pllconfig;
308 	char *nxt;
309 
310 	if (resource_string_value("hifn", device_get_unit(dev),
311 	    "pllconfig", &pllspec))
312 		pllspec = "ext66";
313 	fl = 33, fh = 66;
314 	pllconfig = 0;
315 	if (strncmp(pllspec, "ext", 3) == 0) {
316 		pllspec += 3;
317 		pllconfig |= HIFN_PLL_REF_SEL;
318 		switch (pci_get_device(dev)) {
319 		case PCI_PRODUCT_HIFN_7955:
320 		case PCI_PRODUCT_HIFN_7956:
321 			fl = 20, fh = 100;
322 			break;
323 #ifdef notyet
324 		case PCI_PRODUCT_HIFN_7954:
325 			fl = 20, fh = 66;
326 			break;
327 #endif
328 		}
329 	} else if (strncmp(pllspec, "pci", 3) == 0)
330 		pllspec += 3;
331 	freq = strtoul(pllspec, &nxt, 10);
332 	if (nxt == pllspec)
333 		freq = 66;
334 	else
335 		freq = checkmaxmin(dev, "frequency", freq, fl, fh);
336 	/*
337 	 * Calculate multiplier.  We target a Fck of 266 MHz,
338 	 * allowing only even values, possibly rounded down.
339 	 * Multipliers > 8 must set the charge pump current.
340 	 */
341 	mul = checkmaxmin(dev, "PLL divisor", (266 / freq) &~ 1, 2, 12);
342 	pllconfig |= (mul / 2 - 1) << HIFN_PLL_ND_SHIFT;
343 	if (mul > 8)
344 		pllconfig |= HIFN_PLL_IS;
345 	*pll = pllconfig;
346 }
347 
348 /*
349  * Attach an interface that successfully probed.
350  */
351 static int
352 hifn_attach(device_t dev)
353 {
354 	struct hifn_softc *sc = device_get_softc(dev);
355 	caddr_t kva;
356 	int rseg, rid;
357 	char rbase;
358 	u_int16_t ena, rev;
359 
360 	sc->sc_dev = dev;
361 
362 	mtx_init(&sc->sc_mtx, device_get_nameunit(dev), "hifn driver", MTX_DEF);
363 
364 	/* XXX handle power management */
365 
366 	/*
367 	 * The 7951 and 795x have a random number generator and
368 	 * public key support; note this.
369 	 */
370 	if (pci_get_vendor(dev) == PCI_VENDOR_HIFN &&
371 	    (pci_get_device(dev) == PCI_PRODUCT_HIFN_7951 ||
372 	     pci_get_device(dev) == PCI_PRODUCT_HIFN_7955 ||
373 	     pci_get_device(dev) == PCI_PRODUCT_HIFN_7956))
374 		sc->sc_flags = HIFN_HAS_RNG | HIFN_HAS_PUBLIC;
375 	/*
376 	 * The 7811 has a random number generator and
377 	 * we also note it's identity 'cuz of some quirks.
378 	 */
379 	if (pci_get_vendor(dev) == PCI_VENDOR_HIFN &&
380 	    pci_get_device(dev) == PCI_PRODUCT_HIFN_7811)
381 		sc->sc_flags |= HIFN_IS_7811 | HIFN_HAS_RNG;
382 
383 	/*
384 	 * The 795x parts support AES.
385 	 */
386 	if (pci_get_vendor(dev) == PCI_VENDOR_HIFN &&
387 	    (pci_get_device(dev) == PCI_PRODUCT_HIFN_7955 ||
388 	     pci_get_device(dev) == PCI_PRODUCT_HIFN_7956)) {
389 		sc->sc_flags |= HIFN_IS_7956 | HIFN_HAS_AES;
390 		/*
391 		 * Select PLL configuration.  This depends on the
392 		 * bus and board design and must be manually configured
393 		 * if the default setting is unacceptable.
394 		 */
395 		hifn_getpllconfig(dev, &sc->sc_pllconfig);
396 	}
397 
398 	/*
399 	 * Setup PCI resources. Note that we record the bus
400 	 * tag and handle for each register mapping, this is
401 	 * used by the READ_REG_0, WRITE_REG_0, READ_REG_1,
402 	 * and WRITE_REG_1 macros throughout the driver.
403 	 */
404 	pci_enable_busmaster(dev);
405 
406 	rid = HIFN_BAR0;
407 	sc->sc_bar0res = bus_alloc_resource_any(dev, SYS_RES_MEMORY, &rid,
408 			 			RF_ACTIVE);
409 	if (sc->sc_bar0res == NULL) {
410 		device_printf(dev, "cannot map bar%d register space\n", 0);
411 		goto fail_pci;
412 	}
413 	sc->sc_st0 = rman_get_bustag(sc->sc_bar0res);
414 	sc->sc_sh0 = rman_get_bushandle(sc->sc_bar0res);
415 	sc->sc_bar0_lastreg = (bus_size_t) -1;
416 
417 	rid = HIFN_BAR1;
418 	sc->sc_bar1res = bus_alloc_resource_any(dev, SYS_RES_MEMORY, &rid,
419 						RF_ACTIVE);
420 	if (sc->sc_bar1res == NULL) {
421 		device_printf(dev, "cannot map bar%d register space\n", 1);
422 		goto fail_io0;
423 	}
424 	sc->sc_st1 = rman_get_bustag(sc->sc_bar1res);
425 	sc->sc_sh1 = rman_get_bushandle(sc->sc_bar1res);
426 	sc->sc_bar1_lastreg = (bus_size_t) -1;
427 
428 	hifn_set_retry(sc);
429 
430 	/*
431 	 * Setup the area where the Hifn DMA's descriptors
432 	 * and associated data structures.
433 	 */
434 	if (bus_dma_tag_create(bus_get_dma_tag(dev),	/* PCI parent */
435 			       1, 0,			/* alignment,boundary */
436 			       BUS_SPACE_MAXADDR_32BIT,	/* lowaddr */
437 			       BUS_SPACE_MAXADDR,	/* highaddr */
438 			       NULL, NULL,		/* filter, filterarg */
439 			       HIFN_MAX_DMALEN,		/* maxsize */
440 			       MAX_SCATTER,		/* nsegments */
441 			       HIFN_MAX_SEGLEN,		/* maxsegsize */
442 			       BUS_DMA_ALLOCNOW,	/* flags */
443 			       NULL,			/* lockfunc */
444 			       NULL,			/* lockarg */
445 			       &sc->sc_dmat)) {
446 		device_printf(dev, "cannot allocate DMA tag\n");
447 		goto fail_io1;
448 	}
449 	if (bus_dmamap_create(sc->sc_dmat, BUS_DMA_NOWAIT, &sc->sc_dmamap)) {
450 		device_printf(dev, "cannot create dma map\n");
451 		bus_dma_tag_destroy(sc->sc_dmat);
452 		goto fail_io1;
453 	}
454 	if (bus_dmamem_alloc(sc->sc_dmat, (void**) &kva, BUS_DMA_NOWAIT, &sc->sc_dmamap)) {
455 		device_printf(dev, "cannot alloc dma buffer\n");
456 		bus_dmamap_destroy(sc->sc_dmat, sc->sc_dmamap);
457 		bus_dma_tag_destroy(sc->sc_dmat);
458 		goto fail_io1;
459 	}
460 	if (bus_dmamap_load(sc->sc_dmat, sc->sc_dmamap, kva,
461 			     sizeof (*sc->sc_dma),
462 			     hifn_dmamap_cb, &sc->sc_dma_physaddr,
463 			     BUS_DMA_NOWAIT)) {
464 		device_printf(dev, "cannot load dma map\n");
465 		bus_dmamem_free(sc->sc_dmat, kva, sc->sc_dmamap);
466 		bus_dma_tag_destroy(sc->sc_dmat);
467 		goto fail_io1;
468 	}
469 	sc->sc_dma = (struct hifn_dma *)kva;
470 	bzero(sc->sc_dma, sizeof(*sc->sc_dma));
471 
472 	KASSERT(sc->sc_st0 != 0, ("hifn_attach: null bar0 tag!"));
473 	KASSERT(sc->sc_sh0 != 0, ("hifn_attach: null bar0 handle!"));
474 	KASSERT(sc->sc_st1 != 0, ("hifn_attach: null bar1 tag!"));
475 	KASSERT(sc->sc_sh1 != 0, ("hifn_attach: null bar1 handle!"));
476 
477 	/*
478 	 * Reset the board and do the ``secret handshake''
479 	 * to enable the crypto support.  Then complete the
480 	 * initialization procedure by setting up the interrupt
481 	 * and hooking in to the system crypto support so we'll
482 	 * get used for system services like the crypto device,
483 	 * IPsec, RNG device, etc.
484 	 */
485 	hifn_reset_board(sc, 0);
486 
487 	if (hifn_enable_crypto(sc) != 0) {
488 		device_printf(dev, "crypto enabling failed\n");
489 		goto fail_mem;
490 	}
491 	hifn_reset_puc(sc);
492 
493 	hifn_init_dma(sc);
494 	hifn_init_pci_registers(sc);
495 
496 	/* XXX can't dynamically determine ram type for 795x; force dram */
497 	if (sc->sc_flags & HIFN_IS_7956)
498 		sc->sc_drammodel = 1;
499 	else if (hifn_ramtype(sc))
500 		goto fail_mem;
501 
502 	if (sc->sc_drammodel == 0)
503 		hifn_sramsize(sc);
504 	else
505 		hifn_dramsize(sc);
506 
507 	/*
508 	 * Workaround for NetSec 7751 rev A: half ram size because two
509 	 * of the address lines were left floating
510 	 */
511 	if (pci_get_vendor(dev) == PCI_VENDOR_NETSEC &&
512 	    pci_get_device(dev) == PCI_PRODUCT_NETSEC_7751 &&
513 	    pci_get_revid(dev) == 0x61)	/*XXX???*/
514 		sc->sc_ramsize >>= 1;
515 
516 	/*
517 	 * Arrange the interrupt line.
518 	 */
519 	rid = 0;
520 	sc->sc_irq = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid,
521 					    RF_SHAREABLE|RF_ACTIVE);
522 	if (sc->sc_irq == NULL) {
523 		device_printf(dev, "could not map interrupt\n");
524 		goto fail_mem;
525 	}
526 	/*
527 	 * NB: Network code assumes we are blocked with splimp()
528 	 *     so make sure the IRQ is marked appropriately.
529 	 */
530 	if (bus_setup_intr(dev, sc->sc_irq, INTR_TYPE_NET | INTR_MPSAFE,
531 			   NULL, hifn_intr, sc, &sc->sc_intrhand)) {
532 		device_printf(dev, "could not setup interrupt\n");
533 		goto fail_intr2;
534 	}
535 
536 	hifn_sessions(sc);
537 
538 	/*
539 	 * NB: Keep only the low 16 bits; this masks the chip id
540 	 *     from the 7951.
541 	 */
542 	rev = READ_REG_1(sc, HIFN_1_REVID) & 0xffff;
543 
544 	rseg = sc->sc_ramsize / 1024;
545 	rbase = 'K';
546 	if (sc->sc_ramsize >= (1024 * 1024)) {
547 		rbase = 'M';
548 		rseg /= 1024;
549 	}
550 	device_printf(sc->sc_dev, "%s, rev %u, %d%cB %cram",
551 		hifn_partname(sc), rev,
552 		rseg, rbase, sc->sc_drammodel ? 'd' : 's');
553 	if (sc->sc_flags & HIFN_IS_7956)
554 		printf(", pll=0x%x<%s clk, %ux mult>",
555 			sc->sc_pllconfig,
556 			sc->sc_pllconfig & HIFN_PLL_REF_SEL ? "ext" : "pci",
557 			2 + 2*((sc->sc_pllconfig & HIFN_PLL_ND) >> 11));
558 	printf("\n");
559 
560 	sc->sc_cid = crypto_get_driverid(dev, CRYPTOCAP_F_HARDWARE);
561 	if (sc->sc_cid < 0) {
562 		device_printf(dev, "could not get crypto driver id\n");
563 		goto fail_intr;
564 	}
565 
566 	WRITE_REG_0(sc, HIFN_0_PUCNFG,
567 	    READ_REG_0(sc, HIFN_0_PUCNFG) | HIFN_PUCNFG_CHIPID);
568 	ena = READ_REG_0(sc, HIFN_0_PUSTAT) & HIFN_PUSTAT_CHIPENA;
569 
570 	switch (ena) {
571 	case HIFN_PUSTAT_ENA_2:
572 		crypto_register(sc->sc_cid, CRYPTO_3DES_CBC, 0, 0);
573 		crypto_register(sc->sc_cid, CRYPTO_ARC4, 0, 0);
574 		if (sc->sc_flags & HIFN_HAS_AES)
575 			crypto_register(sc->sc_cid, CRYPTO_AES_CBC, 0, 0);
576 		/*FALLTHROUGH*/
577 	case HIFN_PUSTAT_ENA_1:
578 		crypto_register(sc->sc_cid, CRYPTO_MD5, 0, 0);
579 		crypto_register(sc->sc_cid, CRYPTO_SHA1, 0, 0);
580 		crypto_register(sc->sc_cid, CRYPTO_MD5_HMAC, 0, 0);
581 		crypto_register(sc->sc_cid, CRYPTO_SHA1_HMAC, 0, 0);
582 		crypto_register(sc->sc_cid, CRYPTO_DES_CBC, 0, 0);
583 		break;
584 	}
585 
586 	bus_dmamap_sync(sc->sc_dmat, sc->sc_dmamap,
587 	    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
588 
589 	if (sc->sc_flags & (HIFN_HAS_PUBLIC | HIFN_HAS_RNG))
590 		hifn_init_pubrng(sc);
591 
592 	callout_init(&sc->sc_tickto, CALLOUT_MPSAFE);
593 	callout_reset(&sc->sc_tickto, hz, hifn_tick, sc);
594 
595 	return (0);
596 
597 fail_intr:
598 	bus_teardown_intr(dev, sc->sc_irq, sc->sc_intrhand);
599 fail_intr2:
600 	/* XXX don't store rid */
601 	bus_release_resource(dev, SYS_RES_IRQ, 0, sc->sc_irq);
602 fail_mem:
603 	bus_dmamap_unload(sc->sc_dmat, sc->sc_dmamap);
604 	bus_dmamem_free(sc->sc_dmat, sc->sc_dma, sc->sc_dmamap);
605 	bus_dma_tag_destroy(sc->sc_dmat);
606 
607 	/* Turn off DMA polling */
608 	WRITE_REG_1(sc, HIFN_1_DMA_CNFG, HIFN_DMACNFG_MSTRESET |
609 	    HIFN_DMACNFG_DMARESET | HIFN_DMACNFG_MODE);
610 fail_io1:
611 	bus_release_resource(dev, SYS_RES_MEMORY, HIFN_BAR1, sc->sc_bar1res);
612 fail_io0:
613 	bus_release_resource(dev, SYS_RES_MEMORY, HIFN_BAR0, sc->sc_bar0res);
614 fail_pci:
615 	mtx_destroy(&sc->sc_mtx);
616 	return (ENXIO);
617 }
618 
619 /*
620  * Detach an interface that successfully probed.
621  */
622 static int
623 hifn_detach(device_t dev)
624 {
625 	struct hifn_softc *sc = device_get_softc(dev);
626 
627 	KASSERT(sc != NULL, ("hifn_detach: null software carrier!"));
628 
629 	/* disable interrupts */
630 	WRITE_REG_1(sc, HIFN_1_DMA_IER, 0);
631 
632 	/*XXX other resources */
633 	callout_stop(&sc->sc_tickto);
634 	callout_stop(&sc->sc_rngto);
635 #ifdef HIFN_RNDTEST
636 	if (sc->sc_rndtest)
637 		rndtest_detach(sc->sc_rndtest);
638 #endif
639 
640 	/* Turn off DMA polling */
641 	WRITE_REG_1(sc, HIFN_1_DMA_CNFG, HIFN_DMACNFG_MSTRESET |
642 	    HIFN_DMACNFG_DMARESET | HIFN_DMACNFG_MODE);
643 
644 	crypto_unregister_all(sc->sc_cid);
645 
646 	bus_generic_detach(dev);	/*XXX should be no children, right? */
647 
648 	bus_teardown_intr(dev, sc->sc_irq, sc->sc_intrhand);
649 	/* XXX don't store rid */
650 	bus_release_resource(dev, SYS_RES_IRQ, 0, sc->sc_irq);
651 
652 	bus_dmamap_unload(sc->sc_dmat, sc->sc_dmamap);
653 	bus_dmamem_free(sc->sc_dmat, sc->sc_dma, sc->sc_dmamap);
654 	bus_dma_tag_destroy(sc->sc_dmat);
655 
656 	bus_release_resource(dev, SYS_RES_MEMORY, HIFN_BAR1, sc->sc_bar1res);
657 	bus_release_resource(dev, SYS_RES_MEMORY, HIFN_BAR0, sc->sc_bar0res);
658 
659 	mtx_destroy(&sc->sc_mtx);
660 
661 	return (0);
662 }
663 
664 /*
665  * Stop all chip I/O so that the kernel's probe routines don't
666  * get confused by errant DMAs when rebooting.
667  */
668 static int
669 hifn_shutdown(device_t dev)
670 {
671 #ifdef notyet
672 	hifn_stop(device_get_softc(dev));
673 #endif
674 	return (0);
675 }
676 
677 /*
678  * Device suspend routine.  Stop the interface and save some PCI
679  * settings in case the BIOS doesn't restore them properly on
680  * resume.
681  */
682 static int
683 hifn_suspend(device_t dev)
684 {
685 	struct hifn_softc *sc = device_get_softc(dev);
686 #ifdef notyet
687 	hifn_stop(sc);
688 #endif
689 	sc->sc_suspended = 1;
690 
691 	return (0);
692 }
693 
694 /*
695  * Device resume routine.  Restore some PCI settings in case the BIOS
696  * doesn't, re-enable busmastering, and restart the interface if
697  * appropriate.
698  */
699 static int
700 hifn_resume(device_t dev)
701 {
702 	struct hifn_softc *sc = device_get_softc(dev);
703 #ifdef notyet
704         /* reinitialize interface if necessary */
705         if (ifp->if_flags & IFF_UP)
706                 rl_init(sc);
707 #endif
708 	sc->sc_suspended = 0;
709 
710 	return (0);
711 }
712 
713 static int
714 hifn_init_pubrng(struct hifn_softc *sc)
715 {
716 	u_int32_t r;
717 	int i;
718 
719 #ifdef HIFN_RNDTEST
720 	sc->sc_rndtest = rndtest_attach(sc->sc_dev);
721 	if (sc->sc_rndtest)
722 		sc->sc_harvest = rndtest_harvest;
723 	else
724 		sc->sc_harvest = default_harvest;
725 #else
726 	sc->sc_harvest = default_harvest;
727 #endif
728 	if ((sc->sc_flags & HIFN_IS_7811) == 0) {
729 		/* Reset 7951 public key/rng engine */
730 		WRITE_REG_1(sc, HIFN_1_PUB_RESET,
731 		    READ_REG_1(sc, HIFN_1_PUB_RESET) | HIFN_PUBRST_RESET);
732 
733 		for (i = 0; i < 100; i++) {
734 			DELAY(1000);
735 			if ((READ_REG_1(sc, HIFN_1_PUB_RESET) &
736 			    HIFN_PUBRST_RESET) == 0)
737 				break;
738 		}
739 
740 		if (i == 100) {
741 			device_printf(sc->sc_dev, "public key init failed\n");
742 			return (1);
743 		}
744 	}
745 
746 	/* Enable the rng, if available */
747 	if (sc->sc_flags & HIFN_HAS_RNG) {
748 		if (sc->sc_flags & HIFN_IS_7811) {
749 			r = READ_REG_1(sc, HIFN_1_7811_RNGENA);
750 			if (r & HIFN_7811_RNGENA_ENA) {
751 				r &= ~HIFN_7811_RNGENA_ENA;
752 				WRITE_REG_1(sc, HIFN_1_7811_RNGENA, r);
753 			}
754 			WRITE_REG_1(sc, HIFN_1_7811_RNGCFG,
755 			    HIFN_7811_RNGCFG_DEFL);
756 			r |= HIFN_7811_RNGENA_ENA;
757 			WRITE_REG_1(sc, HIFN_1_7811_RNGENA, r);
758 		} else
759 			WRITE_REG_1(sc, HIFN_1_RNG_CONFIG,
760 			    READ_REG_1(sc, HIFN_1_RNG_CONFIG) |
761 			    HIFN_RNGCFG_ENA);
762 
763 		sc->sc_rngfirst = 1;
764 		if (hz >= 100)
765 			sc->sc_rnghz = hz / 100;
766 		else
767 			sc->sc_rnghz = 1;
768 		callout_init(&sc->sc_rngto, CALLOUT_MPSAFE);
769 		callout_reset(&sc->sc_rngto, sc->sc_rnghz, hifn_rng, sc);
770 	}
771 
772 	/* Enable public key engine, if available */
773 	if (sc->sc_flags & HIFN_HAS_PUBLIC) {
774 		WRITE_REG_1(sc, HIFN_1_PUB_IEN, HIFN_PUBIEN_DONE);
775 		sc->sc_dmaier |= HIFN_DMAIER_PUBDONE;
776 		WRITE_REG_1(sc, HIFN_1_DMA_IER, sc->sc_dmaier);
777 #ifdef HIFN_VULCANDEV
778 		sc->sc_pkdev = make_dev(&vulcanpk_cdevsw, 0,
779 					UID_ROOT, GID_WHEEL, 0666,
780 					"vulcanpk");
781 		sc->sc_pkdev->si_drv1 = sc;
782 #endif
783 	}
784 
785 	return (0);
786 }
787 
788 static void
789 hifn_rng(void *vsc)
790 {
791 #define	RANDOM_BITS(n)	(n)*sizeof (u_int32_t), (n)*sizeof (u_int32_t)*NBBY, 0
792 	struct hifn_softc *sc = vsc;
793 	u_int32_t sts, num[2];
794 	int i;
795 
796 	if (sc->sc_flags & HIFN_IS_7811) {
797 		/* ONLY VALID ON 7811!!!! */
798 		for (i = 0; i < 5; i++) {
799 			sts = READ_REG_1(sc, HIFN_1_7811_RNGSTS);
800 			if (sts & HIFN_7811_RNGSTS_UFL) {
801 				device_printf(sc->sc_dev,
802 					      "RNG underflow: disabling\n");
803 				return;
804 			}
805 			if ((sts & HIFN_7811_RNGSTS_RDY) == 0)
806 				break;
807 
808 			/*
809 			 * There are at least two words in the RNG FIFO
810 			 * at this point.
811 			 */
812 			num[0] = READ_REG_1(sc, HIFN_1_7811_RNGDAT);
813 			num[1] = READ_REG_1(sc, HIFN_1_7811_RNGDAT);
814 			/* NB: discard first data read */
815 			if (sc->sc_rngfirst)
816 				sc->sc_rngfirst = 0;
817 			else
818 				(*sc->sc_harvest)(sc->sc_rndtest,
819 					num, sizeof (num));
820 		}
821 	} else {
822 		num[0] = READ_REG_1(sc, HIFN_1_RNG_DATA);
823 
824 		/* NB: discard first data read */
825 		if (sc->sc_rngfirst)
826 			sc->sc_rngfirst = 0;
827 		else
828 			(*sc->sc_harvest)(sc->sc_rndtest,
829 				num, sizeof (num[0]));
830 	}
831 
832 	callout_reset(&sc->sc_rngto, sc->sc_rnghz, hifn_rng, sc);
833 #undef RANDOM_BITS
834 }
835 
836 static void
837 hifn_puc_wait(struct hifn_softc *sc)
838 {
839 	int i;
840 	int reg = HIFN_0_PUCTRL;
841 
842 	if (sc->sc_flags & HIFN_IS_7956) {
843 		reg = HIFN_0_PUCTRL2;
844 	}
845 
846 	for (i = 5000; i > 0; i--) {
847 		DELAY(1);
848 		if (!(READ_REG_0(sc, reg) & HIFN_PUCTRL_RESET))
849 			break;
850 	}
851 	if (!i)
852 		device_printf(sc->sc_dev, "proc unit did not reset\n");
853 }
854 
855 /*
856  * Reset the processing unit.
857  */
858 static void
859 hifn_reset_puc(struct hifn_softc *sc)
860 {
861 	/* Reset processing unit */
862 	int reg = HIFN_0_PUCTRL;
863 
864 	if (sc->sc_flags & HIFN_IS_7956) {
865 		reg = HIFN_0_PUCTRL2;
866 	}
867 	WRITE_REG_0(sc, reg, HIFN_PUCTRL_DMAENA);
868 
869 	hifn_puc_wait(sc);
870 }
871 
872 /*
873  * Set the Retry and TRDY registers; note that we set them to
874  * zero because the 7811 locks up when forced to retry (section
875  * 3.6 of "Specification Update SU-0014-04".  Not clear if we
876  * should do this for all Hifn parts, but it doesn't seem to hurt.
877  */
878 static void
879 hifn_set_retry(struct hifn_softc *sc)
880 {
881 	/* NB: RETRY only responds to 8-bit reads/writes */
882 	pci_write_config(sc->sc_dev, HIFN_RETRY_TIMEOUT, 0, 1);
883 	pci_write_config(sc->sc_dev, HIFN_TRDY_TIMEOUT, 0, 1);
884 }
885 
886 /*
887  * Resets the board.  Values in the regesters are left as is
888  * from the reset (i.e. initial values are assigned elsewhere).
889  */
890 static void
891 hifn_reset_board(struct hifn_softc *sc, int full)
892 {
893 	u_int32_t reg;
894 
895 	/*
896 	 * Set polling in the DMA configuration register to zero.  0x7 avoids
897 	 * resetting the board and zeros out the other fields.
898 	 */
899 	WRITE_REG_1(sc, HIFN_1_DMA_CNFG, HIFN_DMACNFG_MSTRESET |
900 	    HIFN_DMACNFG_DMARESET | HIFN_DMACNFG_MODE);
901 
902 	/*
903 	 * Now that polling has been disabled, we have to wait 1 ms
904 	 * before resetting the board.
905 	 */
906 	DELAY(1000);
907 
908 	/* Reset the DMA unit */
909 	if (full) {
910 		WRITE_REG_1(sc, HIFN_1_DMA_CNFG, HIFN_DMACNFG_MODE);
911 		DELAY(1000);
912 	} else {
913 		WRITE_REG_1(sc, HIFN_1_DMA_CNFG,
914 		    HIFN_DMACNFG_MODE | HIFN_DMACNFG_MSTRESET);
915 		hifn_reset_puc(sc);
916 	}
917 
918 	KASSERT(sc->sc_dma != NULL, ("hifn_reset_board: null DMA tag!"));
919 	bzero(sc->sc_dma, sizeof(*sc->sc_dma));
920 
921 	/* Bring dma unit out of reset */
922 	WRITE_REG_1(sc, HIFN_1_DMA_CNFG, HIFN_DMACNFG_MSTRESET |
923 	    HIFN_DMACNFG_DMARESET | HIFN_DMACNFG_MODE);
924 
925 	hifn_puc_wait(sc);
926 	hifn_set_retry(sc);
927 
928 	if (sc->sc_flags & HIFN_IS_7811) {
929 		for (reg = 0; reg < 1000; reg++) {
930 			if (READ_REG_1(sc, HIFN_1_7811_MIPSRST) &
931 			    HIFN_MIPSRST_CRAMINIT)
932 				break;
933 			DELAY(1000);
934 		}
935 		if (reg == 1000)
936 			printf(": cram init timeout\n");
937 	} else {
938 	  /* set up DMA configuration register #2 */
939 	  /* turn off all PK and BAR0 swaps */
940 	  WRITE_REG_1(sc, HIFN_1_DMA_CNFG2,
941 		      (3 << HIFN_DMACNFG2_INIT_WRITE_BURST_SHIFT)|
942 		      (3 << HIFN_DMACNFG2_INIT_READ_BURST_SHIFT)|
943 		      (2 << HIFN_DMACNFG2_TGT_WRITE_BURST_SHIFT)|
944 		      (2 << HIFN_DMACNFG2_TGT_READ_BURST_SHIFT));
945 	}
946 
947 }
948 
949 static u_int32_t
950 hifn_next_signature(u_int32_t a, u_int cnt)
951 {
952 	int i;
953 	u_int32_t v;
954 
955 	for (i = 0; i < cnt; i++) {
956 
957 		/* get the parity */
958 		v = a & 0x80080125;
959 		v ^= v >> 16;
960 		v ^= v >> 8;
961 		v ^= v >> 4;
962 		v ^= v >> 2;
963 		v ^= v >> 1;
964 
965 		a = (v & 1) ^ (a << 1);
966 	}
967 
968 	return a;
969 }
970 
971 struct pci2id {
972 	u_short		pci_vendor;
973 	u_short		pci_prod;
974 	char		card_id[13];
975 };
976 static struct pci2id pci2id[] = {
977 	{
978 		PCI_VENDOR_HIFN,
979 		PCI_PRODUCT_HIFN_7951,
980 		{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
981 		  0x00, 0x00, 0x00, 0x00, 0x00 }
982 	}, {
983 		PCI_VENDOR_HIFN,
984 		PCI_PRODUCT_HIFN_7955,
985 		{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
986 		  0x00, 0x00, 0x00, 0x00, 0x00 }
987 	}, {
988 		PCI_VENDOR_HIFN,
989 		PCI_PRODUCT_HIFN_7956,
990 		{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
991 		  0x00, 0x00, 0x00, 0x00, 0x00 }
992 	}, {
993 		PCI_VENDOR_NETSEC,
994 		PCI_PRODUCT_NETSEC_7751,
995 		{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
996 		  0x00, 0x00, 0x00, 0x00, 0x00 }
997 	}, {
998 		PCI_VENDOR_INVERTEX,
999 		PCI_PRODUCT_INVERTEX_AEON,
1000 		{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1001 		  0x00, 0x00, 0x00, 0x00, 0x00 }
1002 	}, {
1003 		PCI_VENDOR_HIFN,
1004 		PCI_PRODUCT_HIFN_7811,
1005 		{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1006 		  0x00, 0x00, 0x00, 0x00, 0x00 }
1007 	}, {
1008 		/*
1009 		 * Other vendors share this PCI ID as well, such as
1010 		 * http://www.powercrypt.com, and obviously they also
1011 		 * use the same key.
1012 		 */
1013 		PCI_VENDOR_HIFN,
1014 		PCI_PRODUCT_HIFN_7751,
1015 		{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1016 		  0x00, 0x00, 0x00, 0x00, 0x00 }
1017 	},
1018 };
1019 
1020 /*
1021  * Checks to see if crypto is already enabled.  If crypto isn't enable,
1022  * "hifn_enable_crypto" is called to enable it.  The check is important,
1023  * as enabling crypto twice will lock the board.
1024  */
1025 static int
1026 hifn_enable_crypto(struct hifn_softc *sc)
1027 {
1028 	u_int32_t dmacfg, ramcfg, encl, addr, i;
1029 	char *offtbl = NULL;
1030 
1031 	for (i = 0; i < sizeof(pci2id)/sizeof(pci2id[0]); i++) {
1032 		if (pci2id[i].pci_vendor == pci_get_vendor(sc->sc_dev) &&
1033 		    pci2id[i].pci_prod == pci_get_device(sc->sc_dev)) {
1034 			offtbl = pci2id[i].card_id;
1035 			break;
1036 		}
1037 	}
1038 	if (offtbl == NULL) {
1039 		device_printf(sc->sc_dev, "Unknown card!\n");
1040 		return (1);
1041 	}
1042 
1043 	ramcfg = READ_REG_0(sc, HIFN_0_PUCNFG);
1044 	dmacfg = READ_REG_1(sc, HIFN_1_DMA_CNFG);
1045 
1046 	/*
1047 	 * The RAM config register's encrypt level bit needs to be set before
1048 	 * every read performed on the encryption level register.
1049 	 */
1050 	WRITE_REG_0(sc, HIFN_0_PUCNFG, ramcfg | HIFN_PUCNFG_CHIPID);
1051 
1052 	encl = READ_REG_0(sc, HIFN_0_PUSTAT) & HIFN_PUSTAT_CHIPENA;
1053 
1054 	/*
1055 	 * Make sure we don't re-unlock.  Two unlocks kills chip until the
1056 	 * next reboot.
1057 	 */
1058 	if (encl == HIFN_PUSTAT_ENA_1 || encl == HIFN_PUSTAT_ENA_2) {
1059 #ifdef HIFN_DEBUG
1060 		if (hifn_debug)
1061 			device_printf(sc->sc_dev,
1062 			    "Strong crypto already enabled!\n");
1063 #endif
1064 		goto report;
1065 	}
1066 
1067 	if (encl != 0 && encl != HIFN_PUSTAT_ENA_0) {
1068 #ifdef HIFN_DEBUG
1069 		if (hifn_debug)
1070 			device_printf(sc->sc_dev,
1071 			      "Unknown encryption level 0x%x\n", encl);
1072 #endif
1073 		return 1;
1074 	}
1075 
1076 	WRITE_REG_1(sc, HIFN_1_DMA_CNFG, HIFN_DMACNFG_UNLOCK |
1077 	    HIFN_DMACNFG_MSTRESET | HIFN_DMACNFG_DMARESET | HIFN_DMACNFG_MODE);
1078 	DELAY(1000);
1079 	addr = READ_REG_1(sc, HIFN_UNLOCK_SECRET1);
1080 	DELAY(1000);
1081 	WRITE_REG_1(sc, HIFN_UNLOCK_SECRET2, 0);
1082 	DELAY(1000);
1083 
1084 	for (i = 0; i <= 12; i++) {
1085 		addr = hifn_next_signature(addr, offtbl[i] + 0x101);
1086 		WRITE_REG_1(sc, HIFN_UNLOCK_SECRET2, addr);
1087 
1088 		DELAY(1000);
1089 	}
1090 
1091 	WRITE_REG_0(sc, HIFN_0_PUCNFG, ramcfg | HIFN_PUCNFG_CHIPID);
1092 	encl = READ_REG_0(sc, HIFN_0_PUSTAT) & HIFN_PUSTAT_CHIPENA;
1093 
1094 #ifdef HIFN_DEBUG
1095 	if (hifn_debug) {
1096 		if (encl != HIFN_PUSTAT_ENA_1 && encl != HIFN_PUSTAT_ENA_2)
1097 			device_printf(sc->sc_dev, "Engine is permanently "
1098 				"locked until next system reset!\n");
1099 		else
1100 			device_printf(sc->sc_dev, "Engine enabled "
1101 				"successfully!\n");
1102 	}
1103 #endif
1104 
1105 report:
1106 	WRITE_REG_0(sc, HIFN_0_PUCNFG, ramcfg);
1107 	WRITE_REG_1(sc, HIFN_1_DMA_CNFG, dmacfg);
1108 
1109 	switch (encl) {
1110 	case HIFN_PUSTAT_ENA_1:
1111 	case HIFN_PUSTAT_ENA_2:
1112 		break;
1113 	case HIFN_PUSTAT_ENA_0:
1114 	default:
1115 		device_printf(sc->sc_dev, "disabled");
1116 		break;
1117 	}
1118 
1119 	return 0;
1120 }
1121 
1122 /*
1123  * Give initial values to the registers listed in the "Register Space"
1124  * section of the HIFN Software Development reference manual.
1125  */
1126 static void
1127 hifn_init_pci_registers(struct hifn_softc *sc)
1128 {
1129 	/* write fixed values needed by the Initialization registers */
1130 	WRITE_REG_0(sc, HIFN_0_PUCTRL, HIFN_PUCTRL_DMAENA);
1131 	WRITE_REG_0(sc, HIFN_0_FIFOCNFG, HIFN_FIFOCNFG_THRESHOLD);
1132 	WRITE_REG_0(sc, HIFN_0_PUIER, HIFN_PUIER_DSTOVER);
1133 
1134 	/* write all 4 ring address registers */
1135 	WRITE_REG_1(sc, HIFN_1_DMA_CRAR, sc->sc_dma_physaddr +
1136 	    offsetof(struct hifn_dma, cmdr[0]));
1137 	WRITE_REG_1(sc, HIFN_1_DMA_SRAR, sc->sc_dma_physaddr +
1138 	    offsetof(struct hifn_dma, srcr[0]));
1139 	WRITE_REG_1(sc, HIFN_1_DMA_DRAR, sc->sc_dma_physaddr +
1140 	    offsetof(struct hifn_dma, dstr[0]));
1141 	WRITE_REG_1(sc, HIFN_1_DMA_RRAR, sc->sc_dma_physaddr +
1142 	    offsetof(struct hifn_dma, resr[0]));
1143 
1144 	DELAY(2000);
1145 
1146 	/* write status register */
1147 	WRITE_REG_1(sc, HIFN_1_DMA_CSR,
1148 	    HIFN_DMACSR_D_CTRL_DIS | HIFN_DMACSR_R_CTRL_DIS |
1149 	    HIFN_DMACSR_S_CTRL_DIS | HIFN_DMACSR_C_CTRL_DIS |
1150 	    HIFN_DMACSR_D_ABORT | HIFN_DMACSR_D_DONE | HIFN_DMACSR_D_LAST |
1151 	    HIFN_DMACSR_D_WAIT | HIFN_DMACSR_D_OVER |
1152 	    HIFN_DMACSR_R_ABORT | HIFN_DMACSR_R_DONE | HIFN_DMACSR_R_LAST |
1153 	    HIFN_DMACSR_R_WAIT | HIFN_DMACSR_R_OVER |
1154 	    HIFN_DMACSR_S_ABORT | HIFN_DMACSR_S_DONE | HIFN_DMACSR_S_LAST |
1155 	    HIFN_DMACSR_S_WAIT |
1156 	    HIFN_DMACSR_C_ABORT | HIFN_DMACSR_C_DONE | HIFN_DMACSR_C_LAST |
1157 	    HIFN_DMACSR_C_WAIT |
1158 	    HIFN_DMACSR_ENGINE |
1159 	    ((sc->sc_flags & HIFN_HAS_PUBLIC) ?
1160 		HIFN_DMACSR_PUBDONE : 0) |
1161 	    ((sc->sc_flags & HIFN_IS_7811) ?
1162 		HIFN_DMACSR_ILLW | HIFN_DMACSR_ILLR : 0));
1163 
1164 	sc->sc_d_busy = sc->sc_r_busy = sc->sc_s_busy = sc->sc_c_busy = 0;
1165 	sc->sc_dmaier |= HIFN_DMAIER_R_DONE | HIFN_DMAIER_C_ABORT |
1166 	    HIFN_DMAIER_D_OVER | HIFN_DMAIER_R_OVER |
1167 	    HIFN_DMAIER_S_ABORT | HIFN_DMAIER_D_ABORT | HIFN_DMAIER_R_ABORT |
1168 	    ((sc->sc_flags & HIFN_IS_7811) ?
1169 		HIFN_DMAIER_ILLW | HIFN_DMAIER_ILLR : 0);
1170 	sc->sc_dmaier &= ~HIFN_DMAIER_C_WAIT;
1171 	WRITE_REG_1(sc, HIFN_1_DMA_IER, sc->sc_dmaier);
1172 
1173 
1174 	if (sc->sc_flags & HIFN_IS_7956) {
1175 		u_int32_t pll;
1176 
1177 		WRITE_REG_0(sc, HIFN_0_PUCNFG, HIFN_PUCNFG_COMPSING |
1178 		    HIFN_PUCNFG_TCALLPHASES |
1179 		    HIFN_PUCNFG_TCDRVTOTEM | HIFN_PUCNFG_BUS32);
1180 
1181 		/* turn off the clocks and insure bypass is set */
1182 		pll = READ_REG_1(sc, HIFN_1_PLL);
1183 		pll = (pll &~ (HIFN_PLL_PK_CLK_SEL | HIFN_PLL_PE_CLK_SEL))
1184 		  | HIFN_PLL_BP | HIFN_PLL_MBSET;
1185 		WRITE_REG_1(sc, HIFN_1_PLL, pll);
1186 		DELAY(10*1000);		/* 10ms */
1187 
1188 		/* change configuration */
1189 		pll = (pll &~ HIFN_PLL_CONFIG) | sc->sc_pllconfig;
1190 		WRITE_REG_1(sc, HIFN_1_PLL, pll);
1191 		DELAY(10*1000);		/* 10ms */
1192 
1193 		/* disable bypass */
1194 		pll &= ~HIFN_PLL_BP;
1195 		WRITE_REG_1(sc, HIFN_1_PLL, pll);
1196 		/* enable clocks with new configuration */
1197 		pll |= HIFN_PLL_PK_CLK_SEL | HIFN_PLL_PE_CLK_SEL;
1198 		WRITE_REG_1(sc, HIFN_1_PLL, pll);
1199 	} else {
1200 		WRITE_REG_0(sc, HIFN_0_PUCNFG, HIFN_PUCNFG_COMPSING |
1201 		    HIFN_PUCNFG_DRFR_128 | HIFN_PUCNFG_TCALLPHASES |
1202 		    HIFN_PUCNFG_TCDRVTOTEM | HIFN_PUCNFG_BUS32 |
1203 		    (sc->sc_drammodel ? HIFN_PUCNFG_DRAM : HIFN_PUCNFG_SRAM));
1204 	}
1205 
1206 	WRITE_REG_0(sc, HIFN_0_PUISR, HIFN_PUISR_DSTOVER);
1207 	WRITE_REG_1(sc, HIFN_1_DMA_CNFG, HIFN_DMACNFG_MSTRESET |
1208 	    HIFN_DMACNFG_DMARESET | HIFN_DMACNFG_MODE | HIFN_DMACNFG_LAST |
1209 	    ((HIFN_POLL_FREQUENCY << 16 ) & HIFN_DMACNFG_POLLFREQ) |
1210 	    ((HIFN_POLL_SCALAR << 8) & HIFN_DMACNFG_POLLINVAL));
1211 }
1212 
1213 /*
1214  * The maximum number of sessions supported by the card
1215  * is dependent on the amount of context ram, which
1216  * encryption algorithms are enabled, and how compression
1217  * is configured.  This should be configured before this
1218  * routine is called.
1219  */
1220 static void
1221 hifn_sessions(struct hifn_softc *sc)
1222 {
1223 	u_int32_t pucnfg;
1224 	int ctxsize;
1225 
1226 	pucnfg = READ_REG_0(sc, HIFN_0_PUCNFG);
1227 
1228 	if (pucnfg & HIFN_PUCNFG_COMPSING) {
1229 		if (pucnfg & HIFN_PUCNFG_ENCCNFG)
1230 			ctxsize = 128;
1231 		else
1232 			ctxsize = 512;
1233 		/*
1234 		 * 7955/7956 has internal context memory of 32K
1235 		 */
1236 		if (sc->sc_flags & HIFN_IS_7956)
1237 			sc->sc_maxses = 32768 / ctxsize;
1238 		else
1239 			sc->sc_maxses = 1 +
1240 			    ((sc->sc_ramsize - 32768) / ctxsize);
1241 	} else
1242 		sc->sc_maxses = sc->sc_ramsize / 16384;
1243 
1244 	if (sc->sc_maxses > 2048)
1245 		sc->sc_maxses = 2048;
1246 }
1247 
1248 /*
1249  * Determine ram type (sram or dram).  Board should be just out of a reset
1250  * state when this is called.
1251  */
1252 static int
1253 hifn_ramtype(struct hifn_softc *sc)
1254 {
1255 	u_int8_t data[8], dataexpect[8];
1256 	int i;
1257 
1258 	for (i = 0; i < sizeof(data); i++)
1259 		data[i] = dataexpect[i] = 0x55;
1260 	if (hifn_writeramaddr(sc, 0, data))
1261 		return (-1);
1262 	if (hifn_readramaddr(sc, 0, data))
1263 		return (-1);
1264 	if (bcmp(data, dataexpect, sizeof(data)) != 0) {
1265 		sc->sc_drammodel = 1;
1266 		return (0);
1267 	}
1268 
1269 	for (i = 0; i < sizeof(data); i++)
1270 		data[i] = dataexpect[i] = 0xaa;
1271 	if (hifn_writeramaddr(sc, 0, data))
1272 		return (-1);
1273 	if (hifn_readramaddr(sc, 0, data))
1274 		return (-1);
1275 	if (bcmp(data, dataexpect, sizeof(data)) != 0) {
1276 		sc->sc_drammodel = 1;
1277 		return (0);
1278 	}
1279 
1280 	return (0);
1281 }
1282 
1283 #define	HIFN_SRAM_MAX		(32 << 20)
1284 #define	HIFN_SRAM_STEP_SIZE	16384
1285 #define	HIFN_SRAM_GRANULARITY	(HIFN_SRAM_MAX / HIFN_SRAM_STEP_SIZE)
1286 
1287 static int
1288 hifn_sramsize(struct hifn_softc *sc)
1289 {
1290 	u_int32_t a;
1291 	u_int8_t data[8];
1292 	u_int8_t dataexpect[sizeof(data)];
1293 	int32_t i;
1294 
1295 	for (i = 0; i < sizeof(data); i++)
1296 		data[i] = dataexpect[i] = i ^ 0x5a;
1297 
1298 	for (i = HIFN_SRAM_GRANULARITY - 1; i >= 0; i--) {
1299 		a = i * HIFN_SRAM_STEP_SIZE;
1300 		bcopy(&i, data, sizeof(i));
1301 		hifn_writeramaddr(sc, a, data);
1302 	}
1303 
1304 	for (i = 0; i < HIFN_SRAM_GRANULARITY; i++) {
1305 		a = i * HIFN_SRAM_STEP_SIZE;
1306 		bcopy(&i, dataexpect, sizeof(i));
1307 		if (hifn_readramaddr(sc, a, data) < 0)
1308 			return (0);
1309 		if (bcmp(data, dataexpect, sizeof(data)) != 0)
1310 			return (0);
1311 		sc->sc_ramsize = a + HIFN_SRAM_STEP_SIZE;
1312 	}
1313 
1314 	return (0);
1315 }
1316 
1317 /*
1318  * XXX For dram boards, one should really try all of the
1319  * HIFN_PUCNFG_DSZ_*'s.  This just assumes that PUCNFG
1320  * is already set up correctly.
1321  */
1322 static int
1323 hifn_dramsize(struct hifn_softc *sc)
1324 {
1325 	u_int32_t cnfg;
1326 
1327 	if (sc->sc_flags & HIFN_IS_7956) {
1328 		/*
1329 		 * 7955/7956 have a fixed internal ram of only 32K.
1330 		 */
1331 		sc->sc_ramsize = 32768;
1332 	} else {
1333 		cnfg = READ_REG_0(sc, HIFN_0_PUCNFG) &
1334 		    HIFN_PUCNFG_DRAMMASK;
1335 		sc->sc_ramsize = 1 << ((cnfg >> 13) + 18);
1336 	}
1337 	return (0);
1338 }
1339 
1340 static void
1341 hifn_alloc_slot(struct hifn_softc *sc, int *cmdp, int *srcp, int *dstp, int *resp)
1342 {
1343 	struct hifn_dma *dma = sc->sc_dma;
1344 
1345 	if (sc->sc_cmdi == HIFN_D_CMD_RSIZE) {
1346 		sc->sc_cmdi = 0;
1347 		dma->cmdr[HIFN_D_CMD_RSIZE].l = htole32(HIFN_D_VALID |
1348 		    HIFN_D_JUMP | HIFN_D_MASKDONEIRQ);
1349 		HIFN_CMDR_SYNC(sc, HIFN_D_CMD_RSIZE,
1350 		    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
1351 	}
1352 	*cmdp = sc->sc_cmdi++;
1353 	sc->sc_cmdk = sc->sc_cmdi;
1354 
1355 	if (sc->sc_srci == HIFN_D_SRC_RSIZE) {
1356 		sc->sc_srci = 0;
1357 		dma->srcr[HIFN_D_SRC_RSIZE].l = htole32(HIFN_D_VALID |
1358 		    HIFN_D_JUMP | HIFN_D_MASKDONEIRQ);
1359 		HIFN_SRCR_SYNC(sc, HIFN_D_SRC_RSIZE,
1360 		    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
1361 	}
1362 	*srcp = sc->sc_srci++;
1363 	sc->sc_srck = sc->sc_srci;
1364 
1365 	if (sc->sc_dsti == HIFN_D_DST_RSIZE) {
1366 		sc->sc_dsti = 0;
1367 		dma->dstr[HIFN_D_DST_RSIZE].l = htole32(HIFN_D_VALID |
1368 		    HIFN_D_JUMP | HIFN_D_MASKDONEIRQ);
1369 		HIFN_DSTR_SYNC(sc, HIFN_D_DST_RSIZE,
1370 		    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
1371 	}
1372 	*dstp = sc->sc_dsti++;
1373 	sc->sc_dstk = sc->sc_dsti;
1374 
1375 	if (sc->sc_resi == HIFN_D_RES_RSIZE) {
1376 		sc->sc_resi = 0;
1377 		dma->resr[HIFN_D_RES_RSIZE].l = htole32(HIFN_D_VALID |
1378 		    HIFN_D_JUMP | HIFN_D_MASKDONEIRQ);
1379 		HIFN_RESR_SYNC(sc, HIFN_D_RES_RSIZE,
1380 		    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
1381 	}
1382 	*resp = sc->sc_resi++;
1383 	sc->sc_resk = sc->sc_resi;
1384 }
1385 
1386 static int
1387 hifn_writeramaddr(struct hifn_softc *sc, int addr, u_int8_t *data)
1388 {
1389 	struct hifn_dma *dma = sc->sc_dma;
1390 	hifn_base_command_t wc;
1391 	const u_int32_t masks = HIFN_D_VALID | HIFN_D_LAST | HIFN_D_MASKDONEIRQ;
1392 	int r, cmdi, resi, srci, dsti;
1393 
1394 	wc.masks = htole16(3 << 13);
1395 	wc.session_num = htole16(addr >> 14);
1396 	wc.total_source_count = htole16(8);
1397 	wc.total_dest_count = htole16(addr & 0x3fff);
1398 
1399 	hifn_alloc_slot(sc, &cmdi, &srci, &dsti, &resi);
1400 
1401 	WRITE_REG_1(sc, HIFN_1_DMA_CSR,
1402 	    HIFN_DMACSR_C_CTRL_ENA | HIFN_DMACSR_S_CTRL_ENA |
1403 	    HIFN_DMACSR_D_CTRL_ENA | HIFN_DMACSR_R_CTRL_ENA);
1404 
1405 	/* build write command */
1406 	bzero(dma->command_bufs[cmdi], HIFN_MAX_COMMAND);
1407 	*(hifn_base_command_t *)dma->command_bufs[cmdi] = wc;
1408 	bcopy(data, &dma->test_src, sizeof(dma->test_src));
1409 
1410 	dma->srcr[srci].p = htole32(sc->sc_dma_physaddr
1411 	    + offsetof(struct hifn_dma, test_src));
1412 	dma->dstr[dsti].p = htole32(sc->sc_dma_physaddr
1413 	    + offsetof(struct hifn_dma, test_dst));
1414 
1415 	dma->cmdr[cmdi].l = htole32(16 | masks);
1416 	dma->srcr[srci].l = htole32(8 | masks);
1417 	dma->dstr[dsti].l = htole32(4 | masks);
1418 	dma->resr[resi].l = htole32(4 | masks);
1419 
1420 	bus_dmamap_sync(sc->sc_dmat, sc->sc_dmamap,
1421 	    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
1422 
1423 	for (r = 10000; r >= 0; r--) {
1424 		DELAY(10);
1425 		bus_dmamap_sync(sc->sc_dmat, sc->sc_dmamap,
1426 		    BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
1427 		if ((dma->resr[resi].l & htole32(HIFN_D_VALID)) == 0)
1428 			break;
1429 		bus_dmamap_sync(sc->sc_dmat, sc->sc_dmamap,
1430 		    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
1431 	}
1432 	if (r == 0) {
1433 		device_printf(sc->sc_dev, "writeramaddr -- "
1434 		    "result[%d](addr %d) still valid\n", resi, addr);
1435 		r = -1;
1436 		return (-1);
1437 	} else
1438 		r = 0;
1439 
1440 	WRITE_REG_1(sc, HIFN_1_DMA_CSR,
1441 	    HIFN_DMACSR_C_CTRL_DIS | HIFN_DMACSR_S_CTRL_DIS |
1442 	    HIFN_DMACSR_D_CTRL_DIS | HIFN_DMACSR_R_CTRL_DIS);
1443 
1444 	return (r);
1445 }
1446 
1447 static int
1448 hifn_readramaddr(struct hifn_softc *sc, int addr, u_int8_t *data)
1449 {
1450 	struct hifn_dma *dma = sc->sc_dma;
1451 	hifn_base_command_t rc;
1452 	const u_int32_t masks = HIFN_D_VALID | HIFN_D_LAST | HIFN_D_MASKDONEIRQ;
1453 	int r, cmdi, srci, dsti, resi;
1454 
1455 	rc.masks = htole16(2 << 13);
1456 	rc.session_num = htole16(addr >> 14);
1457 	rc.total_source_count = htole16(addr & 0x3fff);
1458 	rc.total_dest_count = htole16(8);
1459 
1460 	hifn_alloc_slot(sc, &cmdi, &srci, &dsti, &resi);
1461 
1462 	WRITE_REG_1(sc, HIFN_1_DMA_CSR,
1463 	    HIFN_DMACSR_C_CTRL_ENA | HIFN_DMACSR_S_CTRL_ENA |
1464 	    HIFN_DMACSR_D_CTRL_ENA | HIFN_DMACSR_R_CTRL_ENA);
1465 
1466 	bzero(dma->command_bufs[cmdi], HIFN_MAX_COMMAND);
1467 	*(hifn_base_command_t *)dma->command_bufs[cmdi] = rc;
1468 
1469 	dma->srcr[srci].p = htole32(sc->sc_dma_physaddr +
1470 	    offsetof(struct hifn_dma, test_src));
1471 	dma->test_src = 0;
1472 	dma->dstr[dsti].p =  htole32(sc->sc_dma_physaddr +
1473 	    offsetof(struct hifn_dma, test_dst));
1474 	dma->test_dst = 0;
1475 	dma->cmdr[cmdi].l = htole32(8 | masks);
1476 	dma->srcr[srci].l = htole32(8 | masks);
1477 	dma->dstr[dsti].l = htole32(8 | masks);
1478 	dma->resr[resi].l = htole32(HIFN_MAX_RESULT | masks);
1479 
1480 	bus_dmamap_sync(sc->sc_dmat, sc->sc_dmamap,
1481 	    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
1482 
1483 	for (r = 10000; r >= 0; r--) {
1484 		DELAY(10);
1485 		bus_dmamap_sync(sc->sc_dmat, sc->sc_dmamap,
1486 		    BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
1487 		if ((dma->resr[resi].l & htole32(HIFN_D_VALID)) == 0)
1488 			break;
1489 		bus_dmamap_sync(sc->sc_dmat, sc->sc_dmamap,
1490 		    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
1491 	}
1492 	if (r == 0) {
1493 		device_printf(sc->sc_dev, "readramaddr -- "
1494 		    "result[%d](addr %d) still valid\n", resi, addr);
1495 		r = -1;
1496 	} else {
1497 		r = 0;
1498 		bcopy(&dma->test_dst, data, sizeof(dma->test_dst));
1499 	}
1500 
1501 	WRITE_REG_1(sc, HIFN_1_DMA_CSR,
1502 	    HIFN_DMACSR_C_CTRL_DIS | HIFN_DMACSR_S_CTRL_DIS |
1503 	    HIFN_DMACSR_D_CTRL_DIS | HIFN_DMACSR_R_CTRL_DIS);
1504 
1505 	return (r);
1506 }
1507 
1508 /*
1509  * Initialize the descriptor rings.
1510  */
1511 static void
1512 hifn_init_dma(struct hifn_softc *sc)
1513 {
1514 	struct hifn_dma *dma = sc->sc_dma;
1515 	int i;
1516 
1517 	hifn_set_retry(sc);
1518 
1519 	/* initialize static pointer values */
1520 	for (i = 0; i < HIFN_D_CMD_RSIZE; i++)
1521 		dma->cmdr[i].p = htole32(sc->sc_dma_physaddr +
1522 		    offsetof(struct hifn_dma, command_bufs[i][0]));
1523 	for (i = 0; i < HIFN_D_RES_RSIZE; i++)
1524 		dma->resr[i].p = htole32(sc->sc_dma_physaddr +
1525 		    offsetof(struct hifn_dma, result_bufs[i][0]));
1526 
1527 	dma->cmdr[HIFN_D_CMD_RSIZE].p =
1528 	    htole32(sc->sc_dma_physaddr + offsetof(struct hifn_dma, cmdr[0]));
1529 	dma->srcr[HIFN_D_SRC_RSIZE].p =
1530 	    htole32(sc->sc_dma_physaddr + offsetof(struct hifn_dma, srcr[0]));
1531 	dma->dstr[HIFN_D_DST_RSIZE].p =
1532 	    htole32(sc->sc_dma_physaddr + offsetof(struct hifn_dma, dstr[0]));
1533 	dma->resr[HIFN_D_RES_RSIZE].p =
1534 	    htole32(sc->sc_dma_physaddr + offsetof(struct hifn_dma, resr[0]));
1535 
1536 	sc->sc_cmdu = sc->sc_srcu = sc->sc_dstu = sc->sc_resu = 0;
1537 	sc->sc_cmdi = sc->sc_srci = sc->sc_dsti = sc->sc_resi = 0;
1538 	sc->sc_cmdk = sc->sc_srck = sc->sc_dstk = sc->sc_resk = 0;
1539 }
1540 
1541 /*
1542  * Writes out the raw command buffer space.  Returns the
1543  * command buffer size.
1544  */
1545 static u_int
1546 hifn_write_command(struct hifn_command *cmd, u_int8_t *buf)
1547 {
1548 	u_int8_t *buf_pos;
1549 	hifn_base_command_t *base_cmd;
1550 	hifn_mac_command_t *mac_cmd;
1551 	hifn_crypt_command_t *cry_cmd;
1552 	int using_mac, using_crypt, len, ivlen;
1553 	u_int32_t dlen, slen;
1554 
1555 	buf_pos = buf;
1556 	using_mac = cmd->base_masks & HIFN_BASE_CMD_MAC;
1557 	using_crypt = cmd->base_masks & HIFN_BASE_CMD_CRYPT;
1558 
1559 	base_cmd = (hifn_base_command_t *)buf_pos;
1560 	base_cmd->masks = htole16(cmd->base_masks);
1561 	slen = cmd->src_mapsize;
1562 	if (cmd->sloplen)
1563 		dlen = cmd->dst_mapsize - cmd->sloplen + sizeof(u_int32_t);
1564 	else
1565 		dlen = cmd->dst_mapsize;
1566 	base_cmd->total_source_count = htole16(slen & HIFN_BASE_CMD_LENMASK_LO);
1567 	base_cmd->total_dest_count = htole16(dlen & HIFN_BASE_CMD_LENMASK_LO);
1568 	dlen >>= 16;
1569 	slen >>= 16;
1570 	base_cmd->session_num = htole16(
1571 	    ((slen << HIFN_BASE_CMD_SRCLEN_S) & HIFN_BASE_CMD_SRCLEN_M) |
1572 	    ((dlen << HIFN_BASE_CMD_DSTLEN_S) & HIFN_BASE_CMD_DSTLEN_M));
1573 	buf_pos += sizeof(hifn_base_command_t);
1574 
1575 	if (using_mac) {
1576 		mac_cmd = (hifn_mac_command_t *)buf_pos;
1577 		dlen = cmd->maccrd->crd_len;
1578 		mac_cmd->source_count = htole16(dlen & 0xffff);
1579 		dlen >>= 16;
1580 		mac_cmd->masks = htole16(cmd->mac_masks |
1581 		    ((dlen << HIFN_MAC_CMD_SRCLEN_S) & HIFN_MAC_CMD_SRCLEN_M));
1582 		mac_cmd->header_skip = htole16(cmd->maccrd->crd_skip);
1583 		mac_cmd->reserved = 0;
1584 		buf_pos += sizeof(hifn_mac_command_t);
1585 	}
1586 
1587 	if (using_crypt) {
1588 		cry_cmd = (hifn_crypt_command_t *)buf_pos;
1589 		dlen = cmd->enccrd->crd_len;
1590 		cry_cmd->source_count = htole16(dlen & 0xffff);
1591 		dlen >>= 16;
1592 		cry_cmd->masks = htole16(cmd->cry_masks |
1593 		    ((dlen << HIFN_CRYPT_CMD_SRCLEN_S) & HIFN_CRYPT_CMD_SRCLEN_M));
1594 		cry_cmd->header_skip = htole16(cmd->enccrd->crd_skip);
1595 		cry_cmd->reserved = 0;
1596 		buf_pos += sizeof(hifn_crypt_command_t);
1597 	}
1598 
1599 	if (using_mac && cmd->mac_masks & HIFN_MAC_CMD_NEW_KEY) {
1600 		bcopy(cmd->mac, buf_pos, HIFN_MAC_KEY_LENGTH);
1601 		buf_pos += HIFN_MAC_KEY_LENGTH;
1602 	}
1603 
1604 	if (using_crypt && cmd->cry_masks & HIFN_CRYPT_CMD_NEW_KEY) {
1605 		switch (cmd->cry_masks & HIFN_CRYPT_CMD_ALG_MASK) {
1606 		case HIFN_CRYPT_CMD_ALG_3DES:
1607 			bcopy(cmd->ck, buf_pos, HIFN_3DES_KEY_LENGTH);
1608 			buf_pos += HIFN_3DES_KEY_LENGTH;
1609 			break;
1610 		case HIFN_CRYPT_CMD_ALG_DES:
1611 			bcopy(cmd->ck, buf_pos, HIFN_DES_KEY_LENGTH);
1612 			buf_pos += HIFN_DES_KEY_LENGTH;
1613 			break;
1614 		case HIFN_CRYPT_CMD_ALG_RC4:
1615 			len = 256;
1616 			do {
1617 				int clen;
1618 
1619 				clen = MIN(cmd->cklen, len);
1620 				bcopy(cmd->ck, buf_pos, clen);
1621 				len -= clen;
1622 				buf_pos += clen;
1623 			} while (len > 0);
1624 			bzero(buf_pos, 4);
1625 			buf_pos += 4;
1626 			break;
1627 		case HIFN_CRYPT_CMD_ALG_AES:
1628 			/*
1629 			 * AES keys are variable 128, 192 and
1630 			 * 256 bits (16, 24 and 32 bytes).
1631 			 */
1632 			bcopy(cmd->ck, buf_pos, cmd->cklen);
1633 			buf_pos += cmd->cklen;
1634 			break;
1635 		}
1636 	}
1637 
1638 	if (using_crypt && cmd->cry_masks & HIFN_CRYPT_CMD_NEW_IV) {
1639 		switch (cmd->cry_masks & HIFN_CRYPT_CMD_ALG_MASK) {
1640 		case HIFN_CRYPT_CMD_ALG_AES:
1641 			ivlen = HIFN_AES_IV_LENGTH;
1642 			break;
1643 		default:
1644 			ivlen = HIFN_IV_LENGTH;
1645 			break;
1646 		}
1647 		bcopy(cmd->iv, buf_pos, ivlen);
1648 		buf_pos += ivlen;
1649 	}
1650 
1651 	if ((cmd->base_masks & (HIFN_BASE_CMD_MAC|HIFN_BASE_CMD_CRYPT)) == 0) {
1652 		bzero(buf_pos, 8);
1653 		buf_pos += 8;
1654 	}
1655 
1656 	return (buf_pos - buf);
1657 }
1658 
1659 static int
1660 hifn_dmamap_aligned(struct hifn_operand *op)
1661 {
1662 	int i;
1663 
1664 	for (i = 0; i < op->nsegs; i++) {
1665 		if (op->segs[i].ds_addr & 3)
1666 			return (0);
1667 		if ((i != (op->nsegs - 1)) && (op->segs[i].ds_len & 3))
1668 			return (0);
1669 	}
1670 	return (1);
1671 }
1672 
1673 static __inline int
1674 hifn_dmamap_dstwrap(struct hifn_softc *sc, int idx)
1675 {
1676 	struct hifn_dma *dma = sc->sc_dma;
1677 
1678 	if (++idx == HIFN_D_DST_RSIZE) {
1679 		dma->dstr[idx].l = htole32(HIFN_D_VALID | HIFN_D_JUMP |
1680 		    HIFN_D_MASKDONEIRQ);
1681 		HIFN_DSTR_SYNC(sc, idx,
1682 		    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
1683 		idx = 0;
1684 	}
1685 	return (idx);
1686 }
1687 
1688 static int
1689 hifn_dmamap_load_dst(struct hifn_softc *sc, struct hifn_command *cmd)
1690 {
1691 	struct hifn_dma *dma = sc->sc_dma;
1692 	struct hifn_operand *dst = &cmd->dst;
1693 	u_int32_t p, l;
1694 	int idx, used = 0, i;
1695 
1696 	idx = sc->sc_dsti;
1697 	for (i = 0; i < dst->nsegs - 1; i++) {
1698 		dma->dstr[idx].p = htole32(dst->segs[i].ds_addr);
1699 		dma->dstr[idx].l = htole32(HIFN_D_VALID |
1700 		    HIFN_D_MASKDONEIRQ | dst->segs[i].ds_len);
1701 		HIFN_DSTR_SYNC(sc, idx,
1702 		    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
1703 		used++;
1704 
1705 		idx = hifn_dmamap_dstwrap(sc, idx);
1706 	}
1707 
1708 	if (cmd->sloplen == 0) {
1709 		p = dst->segs[i].ds_addr;
1710 		l = HIFN_D_VALID | HIFN_D_MASKDONEIRQ | HIFN_D_LAST |
1711 		    dst->segs[i].ds_len;
1712 	} else {
1713 		p = sc->sc_dma_physaddr +
1714 		    offsetof(struct hifn_dma, slop[cmd->slopidx]);
1715 		l = HIFN_D_VALID | HIFN_D_MASKDONEIRQ | HIFN_D_LAST |
1716 		    sizeof(u_int32_t);
1717 
1718 		if ((dst->segs[i].ds_len - cmd->sloplen) != 0) {
1719 			dma->dstr[idx].p = htole32(dst->segs[i].ds_addr);
1720 			dma->dstr[idx].l = htole32(HIFN_D_VALID |
1721 			    HIFN_D_MASKDONEIRQ |
1722 			    (dst->segs[i].ds_len - cmd->sloplen));
1723 			HIFN_DSTR_SYNC(sc, idx,
1724 			    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
1725 			used++;
1726 
1727 			idx = hifn_dmamap_dstwrap(sc, idx);
1728 		}
1729 	}
1730 	dma->dstr[idx].p = htole32(p);
1731 	dma->dstr[idx].l = htole32(l);
1732 	HIFN_DSTR_SYNC(sc, idx, BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
1733 	used++;
1734 
1735 	idx = hifn_dmamap_dstwrap(sc, idx);
1736 
1737 	sc->sc_dsti = idx;
1738 	sc->sc_dstu += used;
1739 	return (idx);
1740 }
1741 
1742 static __inline int
1743 hifn_dmamap_srcwrap(struct hifn_softc *sc, int idx)
1744 {
1745 	struct hifn_dma *dma = sc->sc_dma;
1746 
1747 	if (++idx == HIFN_D_SRC_RSIZE) {
1748 		dma->srcr[idx].l = htole32(HIFN_D_VALID |
1749 		    HIFN_D_JUMP | HIFN_D_MASKDONEIRQ);
1750 		HIFN_SRCR_SYNC(sc, HIFN_D_SRC_RSIZE,
1751 		    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
1752 		idx = 0;
1753 	}
1754 	return (idx);
1755 }
1756 
1757 static int
1758 hifn_dmamap_load_src(struct hifn_softc *sc, struct hifn_command *cmd)
1759 {
1760 	struct hifn_dma *dma = sc->sc_dma;
1761 	struct hifn_operand *src = &cmd->src;
1762 	int idx, i;
1763 	u_int32_t last = 0;
1764 
1765 	idx = sc->sc_srci;
1766 	for (i = 0; i < src->nsegs; i++) {
1767 		if (i == src->nsegs - 1)
1768 			last = HIFN_D_LAST;
1769 
1770 		dma->srcr[idx].p = htole32(src->segs[i].ds_addr);
1771 		dma->srcr[idx].l = htole32(src->segs[i].ds_len |
1772 		    HIFN_D_VALID | HIFN_D_MASKDONEIRQ | last);
1773 		HIFN_SRCR_SYNC(sc, idx,
1774 		    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
1775 
1776 		idx = hifn_dmamap_srcwrap(sc, idx);
1777 	}
1778 	sc->sc_srci = idx;
1779 	sc->sc_srcu += src->nsegs;
1780 	return (idx);
1781 }
1782 
1783 static void
1784 hifn_op_cb(void* arg, bus_dma_segment_t *seg, int nsegs, bus_size_t mapsize, int error)
1785 {
1786 	struct hifn_operand *op = arg;
1787 
1788 	KASSERT(nsegs <= MAX_SCATTER,
1789 		("hifn_op_cb: too many DMA segments (%u > %u) "
1790 		 "returned when mapping operand", nsegs, MAX_SCATTER));
1791 	op->mapsize = mapsize;
1792 	op->nsegs = nsegs;
1793 	bcopy(seg, op->segs, nsegs * sizeof (seg[0]));
1794 }
1795 
1796 static int
1797 hifn_crypto(
1798 	struct hifn_softc *sc,
1799 	struct hifn_command *cmd,
1800 	struct cryptop *crp,
1801 	int hint)
1802 {
1803 	struct	hifn_dma *dma = sc->sc_dma;
1804 	u_int32_t cmdlen, csr;
1805 	int cmdi, resi, err = 0;
1806 
1807 	/*
1808 	 * need 1 cmd, and 1 res
1809 	 *
1810 	 * NB: check this first since it's easy.
1811 	 */
1812 	HIFN_LOCK(sc);
1813 	if ((sc->sc_cmdu + 1) > HIFN_D_CMD_RSIZE ||
1814 	    (sc->sc_resu + 1) > HIFN_D_RES_RSIZE) {
1815 #ifdef HIFN_DEBUG
1816 		if (hifn_debug) {
1817 			device_printf(sc->sc_dev,
1818 				"cmd/result exhaustion, cmdu %u resu %u\n",
1819 				sc->sc_cmdu, sc->sc_resu);
1820 		}
1821 #endif
1822 		hifnstats.hst_nomem_cr++;
1823 		HIFN_UNLOCK(sc);
1824 		return (ERESTART);
1825 	}
1826 
1827 	if (bus_dmamap_create(sc->sc_dmat, BUS_DMA_NOWAIT, &cmd->src_map)) {
1828 		hifnstats.hst_nomem_map++;
1829 		HIFN_UNLOCK(sc);
1830 		return (ENOMEM);
1831 	}
1832 
1833 	if (crp->crp_flags & CRYPTO_F_IMBUF) {
1834 		if (bus_dmamap_load_mbuf(sc->sc_dmat, cmd->src_map,
1835 		    cmd->src_m, hifn_op_cb, &cmd->src, BUS_DMA_NOWAIT)) {
1836 			hifnstats.hst_nomem_load++;
1837 			err = ENOMEM;
1838 			goto err_srcmap1;
1839 		}
1840 	} else if (crp->crp_flags & CRYPTO_F_IOV) {
1841 		if (bus_dmamap_load_uio(sc->sc_dmat, cmd->src_map,
1842 		    cmd->src_io, hifn_op_cb, &cmd->src, BUS_DMA_NOWAIT)) {
1843 			hifnstats.hst_nomem_load++;
1844 			err = ENOMEM;
1845 			goto err_srcmap1;
1846 		}
1847 	} else {
1848 		err = EINVAL;
1849 		goto err_srcmap1;
1850 	}
1851 
1852 	if (hifn_dmamap_aligned(&cmd->src)) {
1853 		cmd->sloplen = cmd->src_mapsize & 3;
1854 		cmd->dst = cmd->src;
1855 	} else {
1856 		if (crp->crp_flags & CRYPTO_F_IOV) {
1857 			err = EINVAL;
1858 			goto err_srcmap;
1859 		} else if (crp->crp_flags & CRYPTO_F_IMBUF) {
1860 			int totlen, len;
1861 			struct mbuf *m, *m0, *mlast;
1862 
1863 			KASSERT(cmd->dst_m == cmd->src_m,
1864 				("hifn_crypto: dst_m initialized improperly"));
1865 			hifnstats.hst_unaligned++;
1866 			/*
1867 			 * Source is not aligned on a longword boundary.
1868 			 * Copy the data to insure alignment.  If we fail
1869 			 * to allocate mbufs or clusters while doing this
1870 			 * we return ERESTART so the operation is requeued
1871 			 * at the crypto later, but only if there are
1872 			 * ops already posted to the hardware; otherwise we
1873 			 * have no guarantee that we'll be re-entered.
1874 			 */
1875 			totlen = cmd->src_mapsize;
1876 			if (cmd->src_m->m_flags & M_PKTHDR) {
1877 				len = MHLEN;
1878 				MGETHDR(m0, M_NOWAIT, MT_DATA);
1879 				if (m0 && !m_dup_pkthdr(m0, cmd->src_m, M_NOWAIT)) {
1880 					m_free(m0);
1881 					m0 = NULL;
1882 				}
1883 			} else {
1884 				len = MLEN;
1885 				MGET(m0, M_NOWAIT, MT_DATA);
1886 			}
1887 			if (m0 == NULL) {
1888 				hifnstats.hst_nomem_mbuf++;
1889 				err = sc->sc_cmdu ? ERESTART : ENOMEM;
1890 				goto err_srcmap;
1891 			}
1892 			if (totlen >= MINCLSIZE) {
1893 				MCLGET(m0, M_NOWAIT);
1894 				if ((m0->m_flags & M_EXT) == 0) {
1895 					hifnstats.hst_nomem_mcl++;
1896 					err = sc->sc_cmdu ? ERESTART : ENOMEM;
1897 					m_freem(m0);
1898 					goto err_srcmap;
1899 				}
1900 				len = MCLBYTES;
1901 			}
1902 			totlen -= len;
1903 			m0->m_pkthdr.len = m0->m_len = len;
1904 			mlast = m0;
1905 
1906 			while (totlen > 0) {
1907 				MGET(m, M_NOWAIT, MT_DATA);
1908 				if (m == NULL) {
1909 					hifnstats.hst_nomem_mbuf++;
1910 					err = sc->sc_cmdu ? ERESTART : ENOMEM;
1911 					m_freem(m0);
1912 					goto err_srcmap;
1913 				}
1914 				len = MLEN;
1915 				if (totlen >= MINCLSIZE) {
1916 					MCLGET(m, M_NOWAIT);
1917 					if ((m->m_flags & M_EXT) == 0) {
1918 						hifnstats.hst_nomem_mcl++;
1919 						err = sc->sc_cmdu ? ERESTART : ENOMEM;
1920 						mlast->m_next = m;
1921 						m_freem(m0);
1922 						goto err_srcmap;
1923 					}
1924 					len = MCLBYTES;
1925 				}
1926 
1927 				m->m_len = len;
1928 				m0->m_pkthdr.len += len;
1929 				totlen -= len;
1930 
1931 				mlast->m_next = m;
1932 				mlast = m;
1933 			}
1934 			cmd->dst_m = m0;
1935 		}
1936 	}
1937 
1938 	if (cmd->dst_map == NULL) {
1939 		if (bus_dmamap_create(sc->sc_dmat, BUS_DMA_NOWAIT, &cmd->dst_map)) {
1940 			hifnstats.hst_nomem_map++;
1941 			err = ENOMEM;
1942 			goto err_srcmap;
1943 		}
1944 		if (crp->crp_flags & CRYPTO_F_IMBUF) {
1945 			if (bus_dmamap_load_mbuf(sc->sc_dmat, cmd->dst_map,
1946 			    cmd->dst_m, hifn_op_cb, &cmd->dst, BUS_DMA_NOWAIT)) {
1947 				hifnstats.hst_nomem_map++;
1948 				err = ENOMEM;
1949 				goto err_dstmap1;
1950 			}
1951 		} else if (crp->crp_flags & CRYPTO_F_IOV) {
1952 			if (bus_dmamap_load_uio(sc->sc_dmat, cmd->dst_map,
1953 			    cmd->dst_io, hifn_op_cb, &cmd->dst, BUS_DMA_NOWAIT)) {
1954 				hifnstats.hst_nomem_load++;
1955 				err = ENOMEM;
1956 				goto err_dstmap1;
1957 			}
1958 		}
1959 	}
1960 
1961 #ifdef HIFN_DEBUG
1962 	if (hifn_debug) {
1963 		device_printf(sc->sc_dev,
1964 		    "Entering cmd: stat %8x ien %8x u %d/%d/%d/%d n %d/%d\n",
1965 		    READ_REG_1(sc, HIFN_1_DMA_CSR),
1966 		    READ_REG_1(sc, HIFN_1_DMA_IER),
1967 		    sc->sc_cmdu, sc->sc_srcu, sc->sc_dstu, sc->sc_resu,
1968 		    cmd->src_nsegs, cmd->dst_nsegs);
1969 	}
1970 #endif
1971 
1972 	if (cmd->src_map == cmd->dst_map) {
1973 		bus_dmamap_sync(sc->sc_dmat, cmd->src_map,
1974 		    BUS_DMASYNC_PREWRITE|BUS_DMASYNC_PREREAD);
1975 	} else {
1976 		bus_dmamap_sync(sc->sc_dmat, cmd->src_map,
1977 		    BUS_DMASYNC_PREWRITE);
1978 		bus_dmamap_sync(sc->sc_dmat, cmd->dst_map,
1979 		    BUS_DMASYNC_PREREAD);
1980 	}
1981 
1982 	/*
1983 	 * need N src, and N dst
1984 	 */
1985 	if ((sc->sc_srcu + cmd->src_nsegs) > HIFN_D_SRC_RSIZE ||
1986 	    (sc->sc_dstu + cmd->dst_nsegs + 1) > HIFN_D_DST_RSIZE) {
1987 #ifdef HIFN_DEBUG
1988 		if (hifn_debug) {
1989 			device_printf(sc->sc_dev,
1990 				"src/dst exhaustion, srcu %u+%u dstu %u+%u\n",
1991 				sc->sc_srcu, cmd->src_nsegs,
1992 				sc->sc_dstu, cmd->dst_nsegs);
1993 		}
1994 #endif
1995 		hifnstats.hst_nomem_sd++;
1996 		err = ERESTART;
1997 		goto err_dstmap;
1998 	}
1999 
2000 	if (sc->sc_cmdi == HIFN_D_CMD_RSIZE) {
2001 		sc->sc_cmdi = 0;
2002 		dma->cmdr[HIFN_D_CMD_RSIZE].l = htole32(HIFN_D_VALID |
2003 		    HIFN_D_JUMP | HIFN_D_MASKDONEIRQ);
2004 		HIFN_CMDR_SYNC(sc, HIFN_D_CMD_RSIZE,
2005 		    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
2006 	}
2007 	cmdi = sc->sc_cmdi++;
2008 	cmdlen = hifn_write_command(cmd, dma->command_bufs[cmdi]);
2009 	HIFN_CMD_SYNC(sc, cmdi, BUS_DMASYNC_PREWRITE);
2010 
2011 	/* .p for command/result already set */
2012 	dma->cmdr[cmdi].l = htole32(cmdlen | HIFN_D_VALID | HIFN_D_LAST |
2013 	    HIFN_D_MASKDONEIRQ);
2014 	HIFN_CMDR_SYNC(sc, cmdi,
2015 	    BUS_DMASYNC_PREWRITE | BUS_DMASYNC_PREREAD);
2016 	sc->sc_cmdu++;
2017 
2018 	/*
2019 	 * We don't worry about missing an interrupt (which a "command wait"
2020 	 * interrupt salvages us from), unless there is more than one command
2021 	 * in the queue.
2022 	 */
2023 	if (sc->sc_cmdu > 1) {
2024 		sc->sc_dmaier |= HIFN_DMAIER_C_WAIT;
2025 		WRITE_REG_1(sc, HIFN_1_DMA_IER, sc->sc_dmaier);
2026 	}
2027 
2028 	hifnstats.hst_ipackets++;
2029 	hifnstats.hst_ibytes += cmd->src_mapsize;
2030 
2031 	hifn_dmamap_load_src(sc, cmd);
2032 
2033 	/*
2034 	 * Unlike other descriptors, we don't mask done interrupt from
2035 	 * result descriptor.
2036 	 */
2037 #ifdef HIFN_DEBUG
2038 	if (hifn_debug)
2039 		printf("load res\n");
2040 #endif
2041 	if (sc->sc_resi == HIFN_D_RES_RSIZE) {
2042 		sc->sc_resi = 0;
2043 		dma->resr[HIFN_D_RES_RSIZE].l = htole32(HIFN_D_VALID |
2044 		    HIFN_D_JUMP | HIFN_D_MASKDONEIRQ);
2045 		HIFN_RESR_SYNC(sc, HIFN_D_RES_RSIZE,
2046 		    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
2047 	}
2048 	resi = sc->sc_resi++;
2049 	KASSERT(sc->sc_hifn_commands[resi] == NULL,
2050 		("hifn_crypto: command slot %u busy", resi));
2051 	sc->sc_hifn_commands[resi] = cmd;
2052 	HIFN_RES_SYNC(sc, resi, BUS_DMASYNC_PREREAD);
2053 	if ((hint & CRYPTO_HINT_MORE) && sc->sc_curbatch < hifn_maxbatch) {
2054 		dma->resr[resi].l = htole32(HIFN_MAX_RESULT |
2055 		    HIFN_D_VALID | HIFN_D_LAST | HIFN_D_MASKDONEIRQ);
2056 		sc->sc_curbatch++;
2057 		if (sc->sc_curbatch > hifnstats.hst_maxbatch)
2058 			hifnstats.hst_maxbatch = sc->sc_curbatch;
2059 		hifnstats.hst_totbatch++;
2060 	} else {
2061 		dma->resr[resi].l = htole32(HIFN_MAX_RESULT |
2062 		    HIFN_D_VALID | HIFN_D_LAST);
2063 		sc->sc_curbatch = 0;
2064 	}
2065 	HIFN_RESR_SYNC(sc, resi,
2066 	    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
2067 	sc->sc_resu++;
2068 
2069 	if (cmd->sloplen)
2070 		cmd->slopidx = resi;
2071 
2072 	hifn_dmamap_load_dst(sc, cmd);
2073 
2074 	csr = 0;
2075 	if (sc->sc_c_busy == 0) {
2076 		csr |= HIFN_DMACSR_C_CTRL_ENA;
2077 		sc->sc_c_busy = 1;
2078 	}
2079 	if (sc->sc_s_busy == 0) {
2080 		csr |= HIFN_DMACSR_S_CTRL_ENA;
2081 		sc->sc_s_busy = 1;
2082 	}
2083 	if (sc->sc_r_busy == 0) {
2084 		csr |= HIFN_DMACSR_R_CTRL_ENA;
2085 		sc->sc_r_busy = 1;
2086 	}
2087 	if (sc->sc_d_busy == 0) {
2088 		csr |= HIFN_DMACSR_D_CTRL_ENA;
2089 		sc->sc_d_busy = 1;
2090 	}
2091 	if (csr)
2092 		WRITE_REG_1(sc, HIFN_1_DMA_CSR, csr);
2093 
2094 #ifdef HIFN_DEBUG
2095 	if (hifn_debug) {
2096 		device_printf(sc->sc_dev, "command: stat %8x ier %8x\n",
2097 		    READ_REG_1(sc, HIFN_1_DMA_CSR),
2098 		    READ_REG_1(sc, HIFN_1_DMA_IER));
2099 	}
2100 #endif
2101 
2102 	sc->sc_active = 5;
2103 	HIFN_UNLOCK(sc);
2104 	KASSERT(err == 0, ("hifn_crypto: success with error %u", err));
2105 	return (err);		/* success */
2106 
2107 err_dstmap:
2108 	if (cmd->src_map != cmd->dst_map)
2109 		bus_dmamap_unload(sc->sc_dmat, cmd->dst_map);
2110 err_dstmap1:
2111 	if (cmd->src_map != cmd->dst_map)
2112 		bus_dmamap_destroy(sc->sc_dmat, cmd->dst_map);
2113 err_srcmap:
2114 	if (crp->crp_flags & CRYPTO_F_IMBUF) {
2115 		if (cmd->src_m != cmd->dst_m)
2116 			m_freem(cmd->dst_m);
2117 	}
2118 	bus_dmamap_unload(sc->sc_dmat, cmd->src_map);
2119 err_srcmap1:
2120 	bus_dmamap_destroy(sc->sc_dmat, cmd->src_map);
2121 	HIFN_UNLOCK(sc);
2122 	return (err);
2123 }
2124 
2125 static void
2126 hifn_tick(void* vsc)
2127 {
2128 	struct hifn_softc *sc = vsc;
2129 
2130 	HIFN_LOCK(sc);
2131 	if (sc->sc_active == 0) {
2132 		u_int32_t r = 0;
2133 
2134 		if (sc->sc_cmdu == 0 && sc->sc_c_busy) {
2135 			sc->sc_c_busy = 0;
2136 			r |= HIFN_DMACSR_C_CTRL_DIS;
2137 		}
2138 		if (sc->sc_srcu == 0 && sc->sc_s_busy) {
2139 			sc->sc_s_busy = 0;
2140 			r |= HIFN_DMACSR_S_CTRL_DIS;
2141 		}
2142 		if (sc->sc_dstu == 0 && sc->sc_d_busy) {
2143 			sc->sc_d_busy = 0;
2144 			r |= HIFN_DMACSR_D_CTRL_DIS;
2145 		}
2146 		if (sc->sc_resu == 0 && sc->sc_r_busy) {
2147 			sc->sc_r_busy = 0;
2148 			r |= HIFN_DMACSR_R_CTRL_DIS;
2149 		}
2150 		if (r)
2151 			WRITE_REG_1(sc, HIFN_1_DMA_CSR, r);
2152 	} else
2153 		sc->sc_active--;
2154 	HIFN_UNLOCK(sc);
2155 	callout_reset(&sc->sc_tickto, hz, hifn_tick, sc);
2156 }
2157 
2158 static void
2159 hifn_intr(void *arg)
2160 {
2161 	struct hifn_softc *sc = arg;
2162 	struct hifn_dma *dma;
2163 	u_int32_t dmacsr, restart;
2164 	int i, u;
2165 
2166 	dmacsr = READ_REG_1(sc, HIFN_1_DMA_CSR);
2167 
2168 	/* Nothing in the DMA unit interrupted */
2169 	if ((dmacsr & sc->sc_dmaier) == 0)
2170 		return;
2171 
2172 	HIFN_LOCK(sc);
2173 
2174 	dma = sc->sc_dma;
2175 
2176 #ifdef HIFN_DEBUG
2177 	if (hifn_debug) {
2178 		device_printf(sc->sc_dev,
2179 		    "irq: stat %08x ien %08x damier %08x i %d/%d/%d/%d k %d/%d/%d/%d u %d/%d/%d/%d\n",
2180 		    dmacsr, READ_REG_1(sc, HIFN_1_DMA_IER), sc->sc_dmaier,
2181 		    sc->sc_cmdi, sc->sc_srci, sc->sc_dsti, sc->sc_resi,
2182 		    sc->sc_cmdk, sc->sc_srck, sc->sc_dstk, sc->sc_resk,
2183 		    sc->sc_cmdu, sc->sc_srcu, sc->sc_dstu, sc->sc_resu);
2184 	}
2185 #endif
2186 
2187 	WRITE_REG_1(sc, HIFN_1_DMA_CSR, dmacsr & sc->sc_dmaier);
2188 
2189 	if ((sc->sc_flags & HIFN_HAS_PUBLIC) &&
2190 	    (dmacsr & HIFN_DMACSR_PUBDONE))
2191 		WRITE_REG_1(sc, HIFN_1_PUB_STATUS,
2192 		    READ_REG_1(sc, HIFN_1_PUB_STATUS) | HIFN_PUBSTS_DONE);
2193 
2194 	restart = dmacsr & (HIFN_DMACSR_D_OVER | HIFN_DMACSR_R_OVER);
2195 	if (restart)
2196 		device_printf(sc->sc_dev, "overrun %x\n", dmacsr);
2197 
2198 	if (sc->sc_flags & HIFN_IS_7811) {
2199 		if (dmacsr & HIFN_DMACSR_ILLR)
2200 			device_printf(sc->sc_dev, "illegal read\n");
2201 		if (dmacsr & HIFN_DMACSR_ILLW)
2202 			device_printf(sc->sc_dev, "illegal write\n");
2203 	}
2204 
2205 	restart = dmacsr & (HIFN_DMACSR_C_ABORT | HIFN_DMACSR_S_ABORT |
2206 	    HIFN_DMACSR_D_ABORT | HIFN_DMACSR_R_ABORT);
2207 	if (restart) {
2208 		device_printf(sc->sc_dev, "abort, resetting.\n");
2209 		hifnstats.hst_abort++;
2210 		hifn_abort(sc);
2211 		HIFN_UNLOCK(sc);
2212 		return;
2213 	}
2214 
2215 	if ((dmacsr & HIFN_DMACSR_C_WAIT) && (sc->sc_cmdu == 0)) {
2216 		/*
2217 		 * If no slots to process and we receive a "waiting on
2218 		 * command" interrupt, we disable the "waiting on command"
2219 		 * (by clearing it).
2220 		 */
2221 		sc->sc_dmaier &= ~HIFN_DMAIER_C_WAIT;
2222 		WRITE_REG_1(sc, HIFN_1_DMA_IER, sc->sc_dmaier);
2223 	}
2224 
2225 	/* clear the rings */
2226 	i = sc->sc_resk; u = sc->sc_resu;
2227 	while (u != 0) {
2228 		HIFN_RESR_SYNC(sc, i,
2229 		    BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
2230 		if (dma->resr[i].l & htole32(HIFN_D_VALID)) {
2231 			HIFN_RESR_SYNC(sc, i,
2232 			    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
2233 			break;
2234 		}
2235 
2236 		if (i != HIFN_D_RES_RSIZE) {
2237 			struct hifn_command *cmd;
2238 			u_int8_t *macbuf = NULL;
2239 
2240 			HIFN_RES_SYNC(sc, i, BUS_DMASYNC_POSTREAD);
2241 			cmd = sc->sc_hifn_commands[i];
2242 			KASSERT(cmd != NULL,
2243 				("hifn_intr: null command slot %u", i));
2244 			sc->sc_hifn_commands[i] = NULL;
2245 
2246 			if (cmd->base_masks & HIFN_BASE_CMD_MAC) {
2247 				macbuf = dma->result_bufs[i];
2248 				macbuf += 12;
2249 			}
2250 
2251 			hifn_callback(sc, cmd, macbuf);
2252 			hifnstats.hst_opackets++;
2253 			u--;
2254 		}
2255 
2256 		if (++i == (HIFN_D_RES_RSIZE + 1))
2257 			i = 0;
2258 	}
2259 	sc->sc_resk = i; sc->sc_resu = u;
2260 
2261 	i = sc->sc_srck; u = sc->sc_srcu;
2262 	while (u != 0) {
2263 		if (i == HIFN_D_SRC_RSIZE)
2264 			i = 0;
2265 		HIFN_SRCR_SYNC(sc, i,
2266 		    BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
2267 		if (dma->srcr[i].l & htole32(HIFN_D_VALID)) {
2268 			HIFN_SRCR_SYNC(sc, i,
2269 			    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
2270 			break;
2271 		}
2272 		i++, u--;
2273 	}
2274 	sc->sc_srck = i; sc->sc_srcu = u;
2275 
2276 	i = sc->sc_cmdk; u = sc->sc_cmdu;
2277 	while (u != 0) {
2278 		HIFN_CMDR_SYNC(sc, i,
2279 		    BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
2280 		if (dma->cmdr[i].l & htole32(HIFN_D_VALID)) {
2281 			HIFN_CMDR_SYNC(sc, i,
2282 			    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
2283 			break;
2284 		}
2285 		if (i != HIFN_D_CMD_RSIZE) {
2286 			u--;
2287 			HIFN_CMD_SYNC(sc, i, BUS_DMASYNC_POSTWRITE);
2288 		}
2289 		if (++i == (HIFN_D_CMD_RSIZE + 1))
2290 			i = 0;
2291 	}
2292 	sc->sc_cmdk = i; sc->sc_cmdu = u;
2293 
2294 	HIFN_UNLOCK(sc);
2295 
2296 	if (sc->sc_needwakeup) {		/* XXX check high watermark */
2297 		int wakeup = sc->sc_needwakeup & (CRYPTO_SYMQ|CRYPTO_ASYMQ);
2298 #ifdef HIFN_DEBUG
2299 		if (hifn_debug)
2300 			device_printf(sc->sc_dev,
2301 				"wakeup crypto (%x) u %d/%d/%d/%d\n",
2302 				sc->sc_needwakeup,
2303 				sc->sc_cmdu, sc->sc_srcu, sc->sc_dstu, sc->sc_resu);
2304 #endif
2305 		sc->sc_needwakeup &= ~wakeup;
2306 		crypto_unblock(sc->sc_cid, wakeup);
2307 	}
2308 }
2309 
2310 /*
2311  * Allocate a new 'session' and return an encoded session id.  'sidp'
2312  * contains our registration id, and should contain an encoded session
2313  * id on successful allocation.
2314  */
2315 static int
2316 hifn_newsession(device_t dev, u_int32_t *sidp, struct cryptoini *cri)
2317 {
2318 	struct hifn_softc *sc = device_get_softc(dev);
2319 	struct cryptoini *c;
2320 	int mac = 0, cry = 0, sesn;
2321 	struct hifn_session *ses = NULL;
2322 
2323 	KASSERT(sc != NULL, ("hifn_newsession: null softc"));
2324 	if (sidp == NULL || cri == NULL || sc == NULL)
2325 		return (EINVAL);
2326 
2327 	HIFN_LOCK(sc);
2328 	if (sc->sc_sessions == NULL) {
2329 		ses = sc->sc_sessions = (struct hifn_session *)malloc(
2330 		    sizeof(*ses), M_DEVBUF, M_NOWAIT);
2331 		if (ses == NULL) {
2332 			HIFN_UNLOCK(sc);
2333 			return (ENOMEM);
2334 		}
2335 		sesn = 0;
2336 		sc->sc_nsessions = 1;
2337 	} else {
2338 		for (sesn = 0; sesn < sc->sc_nsessions; sesn++) {
2339 			if (!sc->sc_sessions[sesn].hs_used) {
2340 				ses = &sc->sc_sessions[sesn];
2341 				break;
2342 			}
2343 		}
2344 
2345 		if (ses == NULL) {
2346 			sesn = sc->sc_nsessions;
2347 			ses = (struct hifn_session *)malloc((sesn + 1) *
2348 			    sizeof(*ses), M_DEVBUF, M_NOWAIT);
2349 			if (ses == NULL) {
2350 				HIFN_UNLOCK(sc);
2351 				return (ENOMEM);
2352 			}
2353 			bcopy(sc->sc_sessions, ses, sesn * sizeof(*ses));
2354 			bzero(sc->sc_sessions, sesn * sizeof(*ses));
2355 			free(sc->sc_sessions, M_DEVBUF);
2356 			sc->sc_sessions = ses;
2357 			ses = &sc->sc_sessions[sesn];
2358 			sc->sc_nsessions++;
2359 		}
2360 	}
2361 	HIFN_UNLOCK(sc);
2362 
2363 	bzero(ses, sizeof(*ses));
2364 	ses->hs_used = 1;
2365 
2366 	for (c = cri; c != NULL; c = c->cri_next) {
2367 		switch (c->cri_alg) {
2368 		case CRYPTO_MD5:
2369 		case CRYPTO_SHA1:
2370 		case CRYPTO_MD5_HMAC:
2371 		case CRYPTO_SHA1_HMAC:
2372 			if (mac)
2373 				return (EINVAL);
2374 			mac = 1;
2375 			ses->hs_mlen = c->cri_mlen;
2376 			if (ses->hs_mlen == 0) {
2377 				switch (c->cri_alg) {
2378 				case CRYPTO_MD5:
2379 				case CRYPTO_MD5_HMAC:
2380 					ses->hs_mlen = 16;
2381 					break;
2382 				case CRYPTO_SHA1:
2383 				case CRYPTO_SHA1_HMAC:
2384 					ses->hs_mlen = 20;
2385 					break;
2386 				}
2387 			}
2388 			break;
2389 		case CRYPTO_DES_CBC:
2390 		case CRYPTO_3DES_CBC:
2391 		case CRYPTO_AES_CBC:
2392 			/* XXX this may read fewer, does it matter? */
2393 			read_random(ses->hs_iv,
2394 				c->cri_alg == CRYPTO_AES_CBC ?
2395 					HIFN_AES_IV_LENGTH : HIFN_IV_LENGTH);
2396 			/*FALLTHROUGH*/
2397 		case CRYPTO_ARC4:
2398 			if (cry)
2399 				return (EINVAL);
2400 			cry = 1;
2401 			break;
2402 		default:
2403 			return (EINVAL);
2404 		}
2405 	}
2406 	if (mac == 0 && cry == 0)
2407 		return (EINVAL);
2408 
2409 	*sidp = HIFN_SID(device_get_unit(sc->sc_dev), sesn);
2410 
2411 	return (0);
2412 }
2413 
2414 /*
2415  * Deallocate a session.
2416  * XXX this routine should run a zero'd mac/encrypt key into context ram.
2417  * XXX to blow away any keys already stored there.
2418  */
2419 static int
2420 hifn_freesession(device_t dev, u_int64_t tid)
2421 {
2422 	struct hifn_softc *sc = device_get_softc(dev);
2423 	int session, error;
2424 	u_int32_t sid = CRYPTO_SESID2LID(tid);
2425 
2426 	KASSERT(sc != NULL, ("hifn_freesession: null softc"));
2427 	if (sc == NULL)
2428 		return (EINVAL);
2429 
2430 	HIFN_LOCK(sc);
2431 	session = HIFN_SESSION(sid);
2432 	if (session < sc->sc_nsessions) {
2433 		bzero(&sc->sc_sessions[session], sizeof(struct hifn_session));
2434 		error = 0;
2435 	} else
2436 		error = EINVAL;
2437 	HIFN_UNLOCK(sc);
2438 
2439 	return (error);
2440 }
2441 
2442 static int
2443 hifn_process(device_t dev, struct cryptop *crp, int hint)
2444 {
2445 	struct hifn_softc *sc = device_get_softc(dev);
2446 	struct hifn_command *cmd = NULL;
2447 	int session, err, ivlen;
2448 	struct cryptodesc *crd1, *crd2, *maccrd, *enccrd;
2449 
2450 	if (crp == NULL || crp->crp_callback == NULL) {
2451 		hifnstats.hst_invalid++;
2452 		return (EINVAL);
2453 	}
2454 	session = HIFN_SESSION(crp->crp_sid);
2455 
2456 	if (sc == NULL || session >= sc->sc_nsessions) {
2457 		err = EINVAL;
2458 		goto errout;
2459 	}
2460 
2461 	cmd = malloc(sizeof(struct hifn_command), M_DEVBUF, M_NOWAIT | M_ZERO);
2462 	if (cmd == NULL) {
2463 		hifnstats.hst_nomem++;
2464 		err = ENOMEM;
2465 		goto errout;
2466 	}
2467 
2468 	if (crp->crp_flags & CRYPTO_F_IMBUF) {
2469 		cmd->src_m = (struct mbuf *)crp->crp_buf;
2470 		cmd->dst_m = (struct mbuf *)crp->crp_buf;
2471 	} else if (crp->crp_flags & CRYPTO_F_IOV) {
2472 		cmd->src_io = (struct uio *)crp->crp_buf;
2473 		cmd->dst_io = (struct uio *)crp->crp_buf;
2474 	} else {
2475 		err = EINVAL;
2476 		goto errout;	/* XXX we don't handle contiguous buffers! */
2477 	}
2478 
2479 	crd1 = crp->crp_desc;
2480 	if (crd1 == NULL) {
2481 		err = EINVAL;
2482 		goto errout;
2483 	}
2484 	crd2 = crd1->crd_next;
2485 
2486 	if (crd2 == NULL) {
2487 		if (crd1->crd_alg == CRYPTO_MD5_HMAC ||
2488 		    crd1->crd_alg == CRYPTO_SHA1_HMAC ||
2489 		    crd1->crd_alg == CRYPTO_SHA1 ||
2490 		    crd1->crd_alg == CRYPTO_MD5) {
2491 			maccrd = crd1;
2492 			enccrd = NULL;
2493 		} else if (crd1->crd_alg == CRYPTO_DES_CBC ||
2494 		    crd1->crd_alg == CRYPTO_3DES_CBC ||
2495 		    crd1->crd_alg == CRYPTO_AES_CBC ||
2496 		    crd1->crd_alg == CRYPTO_ARC4) {
2497 			if ((crd1->crd_flags & CRD_F_ENCRYPT) == 0)
2498 				cmd->base_masks |= HIFN_BASE_CMD_DECODE;
2499 			maccrd = NULL;
2500 			enccrd = crd1;
2501 		} else {
2502 			err = EINVAL;
2503 			goto errout;
2504 		}
2505 	} else {
2506 		if ((crd1->crd_alg == CRYPTO_MD5_HMAC ||
2507                      crd1->crd_alg == CRYPTO_SHA1_HMAC ||
2508                      crd1->crd_alg == CRYPTO_MD5 ||
2509                      crd1->crd_alg == CRYPTO_SHA1) &&
2510 		    (crd2->crd_alg == CRYPTO_DES_CBC ||
2511 		     crd2->crd_alg == CRYPTO_3DES_CBC ||
2512 		     crd2->crd_alg == CRYPTO_AES_CBC ||
2513 		     crd2->crd_alg == CRYPTO_ARC4) &&
2514 		    ((crd2->crd_flags & CRD_F_ENCRYPT) == 0)) {
2515 			cmd->base_masks = HIFN_BASE_CMD_DECODE;
2516 			maccrd = crd1;
2517 			enccrd = crd2;
2518 		} else if ((crd1->crd_alg == CRYPTO_DES_CBC ||
2519 		     crd1->crd_alg == CRYPTO_ARC4 ||
2520 		     crd1->crd_alg == CRYPTO_3DES_CBC ||
2521 		     crd1->crd_alg == CRYPTO_AES_CBC) &&
2522 		    (crd2->crd_alg == CRYPTO_MD5_HMAC ||
2523                      crd2->crd_alg == CRYPTO_SHA1_HMAC ||
2524                      crd2->crd_alg == CRYPTO_MD5 ||
2525                      crd2->crd_alg == CRYPTO_SHA1) &&
2526 		    (crd1->crd_flags & CRD_F_ENCRYPT)) {
2527 			enccrd = crd1;
2528 			maccrd = crd2;
2529 		} else {
2530 			/*
2531 			 * We cannot order the 7751 as requested
2532 			 */
2533 			err = EINVAL;
2534 			goto errout;
2535 		}
2536 	}
2537 
2538 	if (enccrd) {
2539 		cmd->enccrd = enccrd;
2540 		cmd->base_masks |= HIFN_BASE_CMD_CRYPT;
2541 		switch (enccrd->crd_alg) {
2542 		case CRYPTO_ARC4:
2543 			cmd->cry_masks |= HIFN_CRYPT_CMD_ALG_RC4;
2544 			break;
2545 		case CRYPTO_DES_CBC:
2546 			cmd->cry_masks |= HIFN_CRYPT_CMD_ALG_DES |
2547 			    HIFN_CRYPT_CMD_MODE_CBC |
2548 			    HIFN_CRYPT_CMD_NEW_IV;
2549 			break;
2550 		case CRYPTO_3DES_CBC:
2551 			cmd->cry_masks |= HIFN_CRYPT_CMD_ALG_3DES |
2552 			    HIFN_CRYPT_CMD_MODE_CBC |
2553 			    HIFN_CRYPT_CMD_NEW_IV;
2554 			break;
2555 		case CRYPTO_AES_CBC:
2556 			cmd->cry_masks |= HIFN_CRYPT_CMD_ALG_AES |
2557 			    HIFN_CRYPT_CMD_MODE_CBC |
2558 			    HIFN_CRYPT_CMD_NEW_IV;
2559 			break;
2560 		default:
2561 			err = EINVAL;
2562 			goto errout;
2563 		}
2564 		if (enccrd->crd_alg != CRYPTO_ARC4) {
2565 			ivlen = ((enccrd->crd_alg == CRYPTO_AES_CBC) ?
2566 				HIFN_AES_IV_LENGTH : HIFN_IV_LENGTH);
2567 			if (enccrd->crd_flags & CRD_F_ENCRYPT) {
2568 				if (enccrd->crd_flags & CRD_F_IV_EXPLICIT)
2569 					bcopy(enccrd->crd_iv, cmd->iv, ivlen);
2570 				else
2571 					bcopy(sc->sc_sessions[session].hs_iv,
2572 					    cmd->iv, ivlen);
2573 
2574 				if ((enccrd->crd_flags & CRD_F_IV_PRESENT)
2575 				    == 0) {
2576 					crypto_copyback(crp->crp_flags,
2577 					    crp->crp_buf, enccrd->crd_inject,
2578 					    ivlen, cmd->iv);
2579 				}
2580 			} else {
2581 				if (enccrd->crd_flags & CRD_F_IV_EXPLICIT)
2582 					bcopy(enccrd->crd_iv, cmd->iv, ivlen);
2583 				else {
2584 					crypto_copydata(crp->crp_flags,
2585 					    crp->crp_buf, enccrd->crd_inject,
2586 					    ivlen, cmd->iv);
2587 				}
2588 			}
2589 		}
2590 
2591 		if (enccrd->crd_flags & CRD_F_KEY_EXPLICIT)
2592 			cmd->cry_masks |= HIFN_CRYPT_CMD_NEW_KEY;
2593 		cmd->ck = enccrd->crd_key;
2594 		cmd->cklen = enccrd->crd_klen >> 3;
2595 		cmd->cry_masks |= HIFN_CRYPT_CMD_NEW_KEY;
2596 
2597 		/*
2598 		 * Need to specify the size for the AES key in the masks.
2599 		 */
2600 		if ((cmd->cry_masks & HIFN_CRYPT_CMD_ALG_MASK) ==
2601 		    HIFN_CRYPT_CMD_ALG_AES) {
2602 			switch (cmd->cklen) {
2603 			case 16:
2604 				cmd->cry_masks |= HIFN_CRYPT_CMD_KSZ_128;
2605 				break;
2606 			case 24:
2607 				cmd->cry_masks |= HIFN_CRYPT_CMD_KSZ_192;
2608 				break;
2609 			case 32:
2610 				cmd->cry_masks |= HIFN_CRYPT_CMD_KSZ_256;
2611 				break;
2612 			default:
2613 				err = EINVAL;
2614 				goto errout;
2615 			}
2616 		}
2617 	}
2618 
2619 	if (maccrd) {
2620 		cmd->maccrd = maccrd;
2621 		cmd->base_masks |= HIFN_BASE_CMD_MAC;
2622 
2623 		switch (maccrd->crd_alg) {
2624 		case CRYPTO_MD5:
2625 			cmd->mac_masks |= HIFN_MAC_CMD_ALG_MD5 |
2626 			    HIFN_MAC_CMD_RESULT | HIFN_MAC_CMD_MODE_HASH |
2627 			    HIFN_MAC_CMD_POS_IPSEC;
2628                        break;
2629 		case CRYPTO_MD5_HMAC:
2630 			cmd->mac_masks |= HIFN_MAC_CMD_ALG_MD5 |
2631 			    HIFN_MAC_CMD_RESULT | HIFN_MAC_CMD_MODE_HMAC |
2632 			    HIFN_MAC_CMD_POS_IPSEC | HIFN_MAC_CMD_TRUNC;
2633 			break;
2634 		case CRYPTO_SHA1:
2635 			cmd->mac_masks |= HIFN_MAC_CMD_ALG_SHA1 |
2636 			    HIFN_MAC_CMD_RESULT | HIFN_MAC_CMD_MODE_HASH |
2637 			    HIFN_MAC_CMD_POS_IPSEC;
2638 			break;
2639 		case CRYPTO_SHA1_HMAC:
2640 			cmd->mac_masks |= HIFN_MAC_CMD_ALG_SHA1 |
2641 			    HIFN_MAC_CMD_RESULT | HIFN_MAC_CMD_MODE_HMAC |
2642 			    HIFN_MAC_CMD_POS_IPSEC | HIFN_MAC_CMD_TRUNC;
2643 			break;
2644 		}
2645 
2646 		if (maccrd->crd_alg == CRYPTO_SHA1_HMAC ||
2647 		     maccrd->crd_alg == CRYPTO_MD5_HMAC) {
2648 			cmd->mac_masks |= HIFN_MAC_CMD_NEW_KEY;
2649 			bcopy(maccrd->crd_key, cmd->mac, maccrd->crd_klen >> 3);
2650 			bzero(cmd->mac + (maccrd->crd_klen >> 3),
2651 			    HIFN_MAC_KEY_LENGTH - (maccrd->crd_klen >> 3));
2652 		}
2653 	}
2654 
2655 	cmd->crp = crp;
2656 	cmd->session_num = session;
2657 	cmd->softc = sc;
2658 
2659 	err = hifn_crypto(sc, cmd, crp, hint);
2660 	if (!err) {
2661 		return 0;
2662 	} else if (err == ERESTART) {
2663 		/*
2664 		 * There weren't enough resources to dispatch the request
2665 		 * to the part.  Notify the caller so they'll requeue this
2666 		 * request and resubmit it again soon.
2667 		 */
2668 #ifdef HIFN_DEBUG
2669 		if (hifn_debug)
2670 			device_printf(sc->sc_dev, "requeue request\n");
2671 #endif
2672 		free(cmd, M_DEVBUF);
2673 		sc->sc_needwakeup |= CRYPTO_SYMQ;
2674 		return (err);
2675 	}
2676 
2677 errout:
2678 	if (cmd != NULL)
2679 		free(cmd, M_DEVBUF);
2680 	if (err == EINVAL)
2681 		hifnstats.hst_invalid++;
2682 	else
2683 		hifnstats.hst_nomem++;
2684 	crp->crp_etype = err;
2685 	crypto_done(crp);
2686 	return (err);
2687 }
2688 
2689 static void
2690 hifn_abort(struct hifn_softc *sc)
2691 {
2692 	struct hifn_dma *dma = sc->sc_dma;
2693 	struct hifn_command *cmd;
2694 	struct cryptop *crp;
2695 	int i, u;
2696 
2697 	i = sc->sc_resk; u = sc->sc_resu;
2698 	while (u != 0) {
2699 		cmd = sc->sc_hifn_commands[i];
2700 		KASSERT(cmd != NULL, ("hifn_abort: null command slot %u", i));
2701 		sc->sc_hifn_commands[i] = NULL;
2702 		crp = cmd->crp;
2703 
2704 		if ((dma->resr[i].l & htole32(HIFN_D_VALID)) == 0) {
2705 			/* Salvage what we can. */
2706 			u_int8_t *macbuf;
2707 
2708 			if (cmd->base_masks & HIFN_BASE_CMD_MAC) {
2709 				macbuf = dma->result_bufs[i];
2710 				macbuf += 12;
2711 			} else
2712 				macbuf = NULL;
2713 			hifnstats.hst_opackets++;
2714 			hifn_callback(sc, cmd, macbuf);
2715 		} else {
2716 			if (cmd->src_map == cmd->dst_map) {
2717 				bus_dmamap_sync(sc->sc_dmat, cmd->src_map,
2718 				    BUS_DMASYNC_POSTREAD|BUS_DMASYNC_POSTWRITE);
2719 			} else {
2720 				bus_dmamap_sync(sc->sc_dmat, cmd->src_map,
2721 				    BUS_DMASYNC_POSTWRITE);
2722 				bus_dmamap_sync(sc->sc_dmat, cmd->dst_map,
2723 				    BUS_DMASYNC_POSTREAD);
2724 			}
2725 
2726 			if (cmd->src_m != cmd->dst_m) {
2727 				m_freem(cmd->src_m);
2728 				crp->crp_buf = (caddr_t)cmd->dst_m;
2729 			}
2730 
2731 			/* non-shared buffers cannot be restarted */
2732 			if (cmd->src_map != cmd->dst_map) {
2733 				/*
2734 				 * XXX should be EAGAIN, delayed until
2735 				 * after the reset.
2736 				 */
2737 				crp->crp_etype = ENOMEM;
2738 				bus_dmamap_unload(sc->sc_dmat, cmd->dst_map);
2739 				bus_dmamap_destroy(sc->sc_dmat, cmd->dst_map);
2740 			} else
2741 				crp->crp_etype = ENOMEM;
2742 
2743 			bus_dmamap_unload(sc->sc_dmat, cmd->src_map);
2744 			bus_dmamap_destroy(sc->sc_dmat, cmd->src_map);
2745 
2746 			free(cmd, M_DEVBUF);
2747 			if (crp->crp_etype != EAGAIN)
2748 				crypto_done(crp);
2749 		}
2750 
2751 		if (++i == HIFN_D_RES_RSIZE)
2752 			i = 0;
2753 		u--;
2754 	}
2755 	sc->sc_resk = i; sc->sc_resu = u;
2756 
2757 	hifn_reset_board(sc, 1);
2758 	hifn_init_dma(sc);
2759 	hifn_init_pci_registers(sc);
2760 }
2761 
2762 static void
2763 hifn_callback(struct hifn_softc *sc, struct hifn_command *cmd, u_int8_t *macbuf)
2764 {
2765 	struct hifn_dma *dma = sc->sc_dma;
2766 	struct cryptop *crp = cmd->crp;
2767 	struct cryptodesc *crd;
2768 	struct mbuf *m;
2769 	int totlen, i, u, ivlen;
2770 
2771 	if (cmd->src_map == cmd->dst_map) {
2772 		bus_dmamap_sync(sc->sc_dmat, cmd->src_map,
2773 		    BUS_DMASYNC_POSTWRITE | BUS_DMASYNC_POSTREAD);
2774 	} else {
2775 		bus_dmamap_sync(sc->sc_dmat, cmd->src_map,
2776 		    BUS_DMASYNC_POSTWRITE);
2777 		bus_dmamap_sync(sc->sc_dmat, cmd->dst_map,
2778 		    BUS_DMASYNC_POSTREAD);
2779 	}
2780 
2781 	if (crp->crp_flags & CRYPTO_F_IMBUF) {
2782 		if (cmd->src_m != cmd->dst_m) {
2783 			crp->crp_buf = (caddr_t)cmd->dst_m;
2784 			totlen = cmd->src_mapsize;
2785 			for (m = cmd->dst_m; m != NULL; m = m->m_next) {
2786 				if (totlen < m->m_len) {
2787 					m->m_len = totlen;
2788 					totlen = 0;
2789 				} else
2790 					totlen -= m->m_len;
2791 			}
2792 			cmd->dst_m->m_pkthdr.len = cmd->src_m->m_pkthdr.len;
2793 			m_freem(cmd->src_m);
2794 		}
2795 	}
2796 
2797 	if (cmd->sloplen != 0) {
2798 		crypto_copyback(crp->crp_flags, crp->crp_buf,
2799 		    cmd->src_mapsize - cmd->sloplen, cmd->sloplen,
2800 		    (caddr_t)&dma->slop[cmd->slopidx]);
2801 	}
2802 
2803 	i = sc->sc_dstk; u = sc->sc_dstu;
2804 	while (u != 0) {
2805 		if (i == HIFN_D_DST_RSIZE)
2806 			i = 0;
2807 		bus_dmamap_sync(sc->sc_dmat, sc->sc_dmamap,
2808 		    BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
2809 		if (dma->dstr[i].l & htole32(HIFN_D_VALID)) {
2810 			bus_dmamap_sync(sc->sc_dmat, sc->sc_dmamap,
2811 			    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
2812 			break;
2813 		}
2814 		i++, u--;
2815 	}
2816 	sc->sc_dstk = i; sc->sc_dstu = u;
2817 
2818 	hifnstats.hst_obytes += cmd->dst_mapsize;
2819 
2820 	if ((cmd->base_masks & (HIFN_BASE_CMD_CRYPT | HIFN_BASE_CMD_DECODE)) ==
2821 	    HIFN_BASE_CMD_CRYPT) {
2822 		for (crd = crp->crp_desc; crd; crd = crd->crd_next) {
2823 			if (crd->crd_alg != CRYPTO_DES_CBC &&
2824 			    crd->crd_alg != CRYPTO_3DES_CBC &&
2825 			    crd->crd_alg != CRYPTO_AES_CBC)
2826 				continue;
2827 			ivlen = ((crd->crd_alg == CRYPTO_AES_CBC) ?
2828 				HIFN_AES_IV_LENGTH : HIFN_IV_LENGTH);
2829 			crypto_copydata(crp->crp_flags, crp->crp_buf,
2830 			    crd->crd_skip + crd->crd_len - ivlen, ivlen,
2831 			    cmd->softc->sc_sessions[cmd->session_num].hs_iv);
2832 			break;
2833 		}
2834 	}
2835 
2836 	if (macbuf != NULL) {
2837 		for (crd = crp->crp_desc; crd; crd = crd->crd_next) {
2838                         int len;
2839 
2840 			if (crd->crd_alg != CRYPTO_MD5 &&
2841 			    crd->crd_alg != CRYPTO_SHA1 &&
2842 			    crd->crd_alg != CRYPTO_MD5_HMAC &&
2843 			    crd->crd_alg != CRYPTO_SHA1_HMAC) {
2844 				continue;
2845 			}
2846 			len = cmd->softc->sc_sessions[cmd->session_num].hs_mlen;
2847 			crypto_copyback(crp->crp_flags, crp->crp_buf,
2848 			    crd->crd_inject, len, macbuf);
2849 			break;
2850 		}
2851 	}
2852 
2853 	if (cmd->src_map != cmd->dst_map) {
2854 		bus_dmamap_unload(sc->sc_dmat, cmd->dst_map);
2855 		bus_dmamap_destroy(sc->sc_dmat, cmd->dst_map);
2856 	}
2857 	bus_dmamap_unload(sc->sc_dmat, cmd->src_map);
2858 	bus_dmamap_destroy(sc->sc_dmat, cmd->src_map);
2859 	free(cmd, M_DEVBUF);
2860 	crypto_done(crp);
2861 }
2862 
2863 /*
2864  * 7811 PB3 rev/2 parts lock-up on burst writes to Group 0
2865  * and Group 1 registers; avoid conditions that could create
2866  * burst writes by doing a read in between the writes.
2867  *
2868  * NB: The read we interpose is always to the same register;
2869  *     we do this because reading from an arbitrary (e.g. last)
2870  *     register may not always work.
2871  */
2872 static void
2873 hifn_write_reg_0(struct hifn_softc *sc, bus_size_t reg, u_int32_t val)
2874 {
2875 	if (sc->sc_flags & HIFN_IS_7811) {
2876 		if (sc->sc_bar0_lastreg == reg - 4)
2877 			bus_space_read_4(sc->sc_st0, sc->sc_sh0, HIFN_0_PUCNFG);
2878 		sc->sc_bar0_lastreg = reg;
2879 	}
2880 	bus_space_write_4(sc->sc_st0, sc->sc_sh0, reg, val);
2881 }
2882 
2883 static void
2884 hifn_write_reg_1(struct hifn_softc *sc, bus_size_t reg, u_int32_t val)
2885 {
2886 	if (sc->sc_flags & HIFN_IS_7811) {
2887 		if (sc->sc_bar1_lastreg == reg - 4)
2888 			bus_space_read_4(sc->sc_st1, sc->sc_sh1, HIFN_1_REVID);
2889 		sc->sc_bar1_lastreg = reg;
2890 	}
2891 	bus_space_write_4(sc->sc_st1, sc->sc_sh1, reg, val);
2892 }
2893 
2894 #ifdef HIFN_VULCANDEV
2895 /*
2896  * this code provides support for mapping the PK engine's register
2897  * into a userspace program.
2898  *
2899  */
2900 static int
2901 vulcanpk_mmap(struct cdev *dev, vm_ooffset_t offset,
2902 	      vm_paddr_t *paddr, int nprot, vm_memattr_t *memattr)
2903 {
2904 	struct hifn_softc *sc;
2905 	vm_paddr_t pd;
2906 	void *b;
2907 
2908 	sc = dev->si_drv1;
2909 
2910 	pd = rman_get_start(sc->sc_bar1res);
2911 	b = rman_get_virtual(sc->sc_bar1res);
2912 
2913 #if 0
2914 	printf("vpk mmap: %p(%016llx) offset=%lld\n", b,
2915 	    (unsigned long long)pd, offset);
2916 	hexdump(b, HIFN_1_PUB_MEMEND, "vpk", 0);
2917 #endif
2918 
2919 	if (offset == 0) {
2920 		*paddr = pd;
2921 		return (0);
2922 	}
2923 	return (-1);
2924 }
2925 
2926 static struct cdevsw vulcanpk_cdevsw = {
2927 	.d_version =	D_VERSION,
2928 	.d_mmap =	vulcanpk_mmap,
2929 	.d_name =	"vulcanpk",
2930 };
2931 #endif /* HIFN_VULCANDEV */
2932