xref: /openbsd/sys/dev/pci/if_stge.c (revision fc61954a)
1 /*	$OpenBSD: if_stge.c,v 1.67 2016/04/13 10:34:32 mpi Exp $	*/
2 /*	$NetBSD: if_stge.c,v 1.27 2005/05/16 21:35:32 bouyer Exp $	*/
3 
4 /*-
5  * Copyright (c) 2001 The NetBSD Foundation, Inc.
6  * All rights reserved.
7  *
8  * This code is derived from software contributed to The NetBSD Foundation
9  * by Jason R. Thorpe.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
22  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
23  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
24  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30  * POSSIBILITY OF SUCH DAMAGE.
31  */
32 
33 /*
34  * Device driver for the Sundance Tech. TC9021 10/100/1000
35  * Ethernet controller.
36  */
37 
38 #include "bpfilter.h"
39 #include "vlan.h"
40 
41 #include <sys/param.h>
42 #include <sys/systm.h>
43 #include <sys/timeout.h>
44 #include <sys/mbuf.h>
45 #include <sys/malloc.h>
46 #include <sys/kernel.h>
47 #include <sys/socket.h>
48 #include <sys/ioctl.h>
49 #include <sys/errno.h>
50 #include <sys/device.h>
51 #include <sys/queue.h>
52 
53 #include <net/if.h>
54 
55 #include <netinet/in.h>
56 #include <netinet/if_ether.h>
57 
58 #include <net/if_media.h>
59 
60 #if NBPFILTER > 0
61 #include <net/bpf.h>
62 #endif
63 
64 #include <machine/bus.h>
65 #include <machine/intr.h>
66 
67 #include <dev/mii/miivar.h>
68 #include <dev/mii/mii_bitbang.h>
69 
70 #include <dev/pci/pcireg.h>
71 #include <dev/pci/pcivar.h>
72 #include <dev/pci/pcidevs.h>
73 
74 #include <dev/pci/if_stgereg.h>
75 
76 void	stge_start(struct ifnet *);
77 void	stge_watchdog(struct ifnet *);
78 int	stge_ioctl(struct ifnet *, u_long, caddr_t);
79 int	stge_init(struct ifnet *);
80 void	stge_stop(struct ifnet *, int);
81 
82 void	stge_reset(struct stge_softc *);
83 void	stge_rxdrain(struct stge_softc *);
84 int	stge_add_rxbuf(struct stge_softc *, int);
85 void	stge_read_eeprom(struct stge_softc *, int, uint16_t *);
86 void	stge_tick(void *);
87 
88 void	stge_stats_update(struct stge_softc *);
89 
90 void	stge_iff(struct stge_softc *);
91 
92 int	stge_intr(void *);
93 void	stge_txintr(struct stge_softc *);
94 void	stge_rxintr(struct stge_softc *);
95 
96 int	stge_mii_readreg(struct device *, int, int);
97 void	stge_mii_writereg(struct device *, int, int, int);
98 void	stge_mii_statchg(struct device *);
99 
100 int	stge_mediachange(struct ifnet *);
101 void	stge_mediastatus(struct ifnet *, struct ifmediareq *);
102 
103 int	stge_match(struct device *, void *, void *);
104 void	stge_attach(struct device *, struct device *, void *);
105 
106 int	stge_copy_small = 0;
107 
108 struct cfattach stge_ca = {
109 	sizeof(struct stge_softc), stge_match, stge_attach,
110 };
111 
112 struct cfdriver stge_cd = {
113 	NULL, "stge", DV_IFNET
114 };
115 
116 uint32_t stge_mii_bitbang_read(struct device *);
117 void	stge_mii_bitbang_write(struct device *, uint32_t);
118 
119 const struct mii_bitbang_ops stge_mii_bitbang_ops = {
120 	stge_mii_bitbang_read,
121 	stge_mii_bitbang_write,
122 	{
123 		PC_MgmtData,		/* MII_BIT_MDO */
124 		PC_MgmtData,		/* MII_BIT_MDI */
125 		PC_MgmtClk,		/* MII_BIT_MDC */
126 		PC_MgmtDir,		/* MII_BIT_DIR_HOST_PHY */
127 		0,			/* MII_BIT_DIR_PHY_HOST */
128 	}
129 };
130 
131 /*
132  * Devices supported by this driver.
133  */
134 const struct pci_matchid stge_devices[] = {
135 	{ PCI_VENDOR_ANTARES, PCI_PRODUCT_ANTARES_TC9021 },
136 	{ PCI_VENDOR_DLINK, PCI_PRODUCT_DLINK_DGE550T },
137 	{ PCI_VENDOR_SUNDANCE, PCI_PRODUCT_SUNDANCE_ST1023 },
138 	{ PCI_VENDOR_SUNDANCE, PCI_PRODUCT_SUNDANCE_ST2021 },
139 	{ PCI_VENDOR_SUNDANCE, PCI_PRODUCT_SUNDANCE_TC9021 },
140 	{ PCI_VENDOR_SUNDANCE, PCI_PRODUCT_SUNDANCE_TC9021_ALT },
141 	{ PCI_VENDOR_TAMARACK, PCI_PRODUCT_TAMARACK_TC9021 },
142 	{ PCI_VENDOR_TAMARACK, PCI_PRODUCT_TAMARACK_TC9021_ALT }
143 };
144 
145 int
146 stge_match(struct device *parent, void *match, void *aux)
147 {
148 	return (pci_matchbyid((struct pci_attach_args *)aux, stge_devices,
149 	    sizeof(stge_devices) / sizeof(stge_devices[0])));
150 }
151 
152 void
153 stge_attach(struct device *parent, struct device *self, void *aux)
154 {
155 	struct stge_softc *sc = (struct stge_softc *) self;
156 	struct pci_attach_args *pa = aux;
157 	struct ifnet *ifp = &sc->sc_arpcom.ac_if;
158 	pci_chipset_tag_t pc = pa->pa_pc;
159 	pci_intr_handle_t ih;
160 	const char *intrstr = NULL;
161 	bus_space_tag_t iot, memt;
162 	bus_space_handle_t ioh, memh;
163 	bus_dma_segment_t seg;
164 	bus_size_t iosize;
165 	int ioh_valid, memh_valid;
166 	int i, rseg, error;
167 
168 	timeout_set(&sc->sc_timeout, stge_tick, sc);
169 
170 	sc->sc_rev = PCI_REVISION(pa->pa_class);
171 
172 	/*
173 	 * Map the device.
174 	 */
175 	ioh_valid = (pci_mapreg_map(pa, STGE_PCI_IOBA,
176 	    PCI_MAPREG_TYPE_IO, 0,
177 	    &iot, &ioh, NULL, &iosize, 0) == 0);
178 	memh_valid = (pci_mapreg_map(pa, STGE_PCI_MMBA,
179 	    PCI_MAPREG_TYPE_MEM|PCI_MAPREG_MEM_TYPE_32BIT, 0,
180 	    &memt, &memh, NULL, &iosize, 0) == 0);
181 
182 	if (memh_valid) {
183 		sc->sc_st = memt;
184 		sc->sc_sh = memh;
185 	} else if (ioh_valid) {
186 		sc->sc_st = iot;
187 		sc->sc_sh = ioh;
188 	} else {
189 		printf(": unable to map device registers\n");
190 		return;
191 	}
192 
193 	sc->sc_dmat = pa->pa_dmat;
194 
195 	/* Get it out of power save mode if needed. */
196 	pci_set_powerstate(pc, pa->pa_tag, PCI_PMCSR_STATE_D0);
197 
198 	/*
199 	 * Map and establish our interrupt.
200 	 */
201 	if (pci_intr_map(pa, &ih)) {
202 		printf(": unable to map interrupt\n");
203 		goto fail_0;
204 	}
205 	intrstr = pci_intr_string(pc, ih);
206 	sc->sc_ih = pci_intr_establish(pc, ih, IPL_NET, stge_intr, sc,
207 				       sc->sc_dev.dv_xname);
208 	if (sc->sc_ih == NULL) {
209 		printf(": unable to establish interrupt");
210 		if (intrstr != NULL)
211 			printf(" at %s", intrstr);
212 		printf("\n");
213 		goto fail_0;
214 	}
215 	printf(": %s", intrstr);
216 
217 	/*
218 	 * Allocate the control data structures, and create and load the
219 	 * DMA map for it.
220 	 */
221 	if ((error = bus_dmamem_alloc(sc->sc_dmat,
222 	    sizeof(struct stge_control_data), PAGE_SIZE, 0, &seg, 1, &rseg,
223 	    0)) != 0) {
224 		printf("%s: unable to allocate control data, error = %d\n",
225 		    sc->sc_dev.dv_xname, error);
226 		goto fail_0;
227 	}
228 
229 	if ((error = bus_dmamem_map(sc->sc_dmat, &seg, rseg,
230 	    sizeof(struct stge_control_data), (caddr_t *)&sc->sc_control_data,
231 	    BUS_DMA_COHERENT)) != 0) {
232 		printf("%s: unable to map control data, error = %d\n",
233 		    sc->sc_dev.dv_xname, error);
234 		goto fail_1;
235 	}
236 
237 	if ((error = bus_dmamap_create(sc->sc_dmat,
238 	    sizeof(struct stge_control_data), 1,
239 	    sizeof(struct stge_control_data), 0, 0, &sc->sc_cddmamap)) != 0) {
240 		printf("%s: unable to create control data DMA map, "
241 		    "error = %d\n", sc->sc_dev.dv_xname, error);
242 		goto fail_2;
243 	}
244 
245 	if ((error = bus_dmamap_load(sc->sc_dmat, sc->sc_cddmamap,
246 	    sc->sc_control_data, sizeof(struct stge_control_data), NULL,
247 	    0)) != 0) {
248 		printf("%s: unable to load control data DMA map, error = %d\n",
249 		    sc->sc_dev.dv_xname, error);
250 		goto fail_3;
251 	}
252 
253 	/*
254 	 * Create the transmit buffer DMA maps.  Note that rev B.3
255 	 * and earlier seem to have a bug regarding multi-fragment
256 	 * packets.  We need to limit the number of Tx segments on
257 	 * such chips to 1.
258 	 */
259 	for (i = 0; i < STGE_NTXDESC; i++) {
260 		if ((error = bus_dmamap_create(sc->sc_dmat,
261 		    STGE_JUMBO_FRAMELEN, STGE_NTXFRAGS, MCLBYTES, 0, 0,
262 		    &sc->sc_txsoft[i].ds_dmamap)) != 0) {
263 			printf("%s: unable to create tx DMA map %d, "
264 			    "error = %d\n", sc->sc_dev.dv_xname, i, error);
265 			goto fail_4;
266 		}
267 	}
268 
269 	/*
270 	 * Create the receive buffer DMA maps.
271 	 */
272 	for (i = 0; i < STGE_NRXDESC; i++) {
273 		if ((error = bus_dmamap_create(sc->sc_dmat, MCLBYTES, 1,
274 		    MCLBYTES, 0, 0, &sc->sc_rxsoft[i].ds_dmamap)) != 0) {
275 			printf("%s: unable to create rx DMA map %d, "
276 			    "error = %d\n", sc->sc_dev.dv_xname, i, error);
277 			goto fail_5;
278 		}
279 		sc->sc_rxsoft[i].ds_mbuf = NULL;
280 	}
281 
282 	/*
283 	 * Determine if we're copper or fiber.  It affects how we
284 	 * reset the card.
285 	 */
286 	if (CSR_READ_4(sc, STGE_AsicCtrl) & AC_PhyMedia)
287 		sc->sc_usefiber = 1;
288 	else
289 		sc->sc_usefiber = 0;
290 
291 	/*
292 	 * Reset the chip to a known state.
293 	 */
294 	stge_reset(sc);
295 
296 	/*
297 	 * Reading the station address from the EEPROM doesn't seem
298 	 * to work, at least on my sample boards.  Instead, since
299 	 * the reset sequence does AutoInit, read it from the station
300 	 * address registers. For Sundance 1023 you can only read it
301 	 * from EEPROM.
302 	 */
303 	if (PCI_PRODUCT(pa->pa_id) != PCI_PRODUCT_SUNDANCE_ST1023) {
304 		sc->sc_arpcom.ac_enaddr[0] = CSR_READ_2(sc,
305 		    STGE_StationAddress0) & 0xff;
306 		sc->sc_arpcom.ac_enaddr[1] = CSR_READ_2(sc,
307 		    STGE_StationAddress0) >> 8;
308 		sc->sc_arpcom.ac_enaddr[2] = CSR_READ_2(sc,
309 		    STGE_StationAddress1) & 0xff;
310 		sc->sc_arpcom.ac_enaddr[3] = CSR_READ_2(sc,
311 		    STGE_StationAddress1) >> 8;
312 		sc->sc_arpcom.ac_enaddr[4] = CSR_READ_2(sc,
313 		    STGE_StationAddress2) & 0xff;
314 		sc->sc_arpcom.ac_enaddr[5] = CSR_READ_2(sc,
315 		    STGE_StationAddress2) >> 8;
316 		sc->sc_stge1023 = 0;
317 	} else {
318 		uint16_t myaddr[ETHER_ADDR_LEN / 2];
319 		for (i = 0; i < ETHER_ADDR_LEN / 2; i++) {
320 			stge_read_eeprom(sc, STGE_EEPROM_StationAddress0 + i,
321 			    &myaddr[i]);
322 			myaddr[i] = letoh16(myaddr[i]);
323 		}
324 		(void)memcpy(sc->sc_arpcom.ac_enaddr, myaddr,
325 		    sizeof(sc->sc_arpcom.ac_enaddr));
326 		sc->sc_stge1023 = 1;
327 	}
328 
329 	printf(", address %s\n", ether_sprintf(sc->sc_arpcom.ac_enaddr));
330 
331 	/*
332 	 * Read some important bits from the PhyCtrl register.
333 	 */
334 	sc->sc_PhyCtrl = CSR_READ_1(sc, STGE_PhyCtrl) &
335 	    (PC_PhyDuplexPolarity | PC_PhyLnkPolarity);
336 
337 	/*
338 	 * Initialize our media structures and probe the MII.
339 	 */
340 	sc->sc_mii.mii_ifp = ifp;
341 	sc->sc_mii.mii_readreg = stge_mii_readreg;
342 	sc->sc_mii.mii_writereg = stge_mii_writereg;
343 	sc->sc_mii.mii_statchg = stge_mii_statchg;
344 	ifmedia_init(&sc->sc_mii.mii_media, 0, stge_mediachange,
345 	    stge_mediastatus);
346 	mii_attach(&sc->sc_dev, &sc->sc_mii, 0xffffffff, MII_PHY_ANY,
347 	    MII_OFFSET_ANY, MIIF_DOPAUSE);
348 	if (LIST_FIRST(&sc->sc_mii.mii_phys) == NULL) {
349 		ifmedia_add(&sc->sc_mii.mii_media, IFM_ETHER|IFM_NONE, 0, NULL);
350 		ifmedia_set(&sc->sc_mii.mii_media, IFM_ETHER|IFM_NONE);
351 	} else
352 		ifmedia_set(&sc->sc_mii.mii_media, IFM_ETHER|IFM_AUTO);
353 
354 	ifp = &sc->sc_arpcom.ac_if;
355 	strlcpy(ifp->if_xname, sc->sc_dev.dv_xname, sizeof ifp->if_xname);
356 	ifp->if_softc = sc;
357 	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
358 	ifp->if_ioctl = stge_ioctl;
359 	ifp->if_start = stge_start;
360 	ifp->if_watchdog = stge_watchdog;
361 #ifdef STGE_JUMBO
362 	ifp->if_hardmtu = STGE_JUMBO_MTU;
363 #endif
364 	IFQ_SET_MAXLEN(&ifp->if_snd, STGE_NTXDESC - 1);
365 
366 	ifp->if_capabilities = IFCAP_VLAN_MTU;
367 
368 #if NVLAN > 0
369 	ifp->if_capabilities |= IFCAP_VLAN_HWTAGGING;
370 #endif
371 
372 	/*
373 	 * The manual recommends disabling early transmit, so we
374 	 * do.  It's disabled anyway, if using IP checksumming,
375 	 * since the entire packet must be in the FIFO in order
376 	 * for the chip to perform the checksum.
377 	 */
378 	sc->sc_txthresh = 0x0fff;
379 
380 	/*
381 	 * Disable MWI if the PCI layer tells us to.
382 	 */
383 	sc->sc_DMACtrl = 0;
384 #ifdef fake
385 	if ((pa->pa_flags & PCI_FLAGS_MWI_OKAY) == 0)
386 		sc->sc_DMACtrl |= DMAC_MWIDisable;
387 #endif
388 
389 #ifdef STGE_CHECKSUM
390 	/*
391 	 * We can do IPv4/TCPv4/UDPv4 checksums in hardware.
392 	 */
393 	sc->sc_arpcom.ac_if.if_capabilities |= IFCAP_CSUM_IPv4 |
394 	    IFCAP_CSUM_TCPv4 | IFCAP_CSUM_UDPv4;
395 #endif
396 
397 	/*
398 	 * Attach the interface.
399 	 */
400 	if_attach(ifp);
401 	ether_ifattach(ifp);
402 	return;
403 
404 	/*
405 	 * Free any resources we've allocated during the failed attach
406 	 * attempt.  Do this in reverse order and fall through.
407 	 */
408  fail_5:
409 	for (i = 0; i < STGE_NRXDESC; i++) {
410 		if (sc->sc_rxsoft[i].ds_dmamap != NULL)
411 			bus_dmamap_destroy(sc->sc_dmat,
412 			    sc->sc_rxsoft[i].ds_dmamap);
413 	}
414  fail_4:
415 	for (i = 0; i < STGE_NTXDESC; i++) {
416 		if (sc->sc_txsoft[i].ds_dmamap != NULL)
417 			bus_dmamap_destroy(sc->sc_dmat,
418 			    sc->sc_txsoft[i].ds_dmamap);
419 	}
420 	bus_dmamap_unload(sc->sc_dmat, sc->sc_cddmamap);
421  fail_3:
422 	bus_dmamap_destroy(sc->sc_dmat, sc->sc_cddmamap);
423  fail_2:
424 	bus_dmamem_unmap(sc->sc_dmat, (caddr_t)sc->sc_control_data,
425 	    sizeof(struct stge_control_data));
426  fail_1:
427 	bus_dmamem_free(sc->sc_dmat, &seg, rseg);
428  fail_0:
429 	bus_space_unmap(sc->sc_st, sc->sc_sh, iosize);
430 	return;
431 }
432 
433 static void
434 stge_dma_wait(struct stge_softc *sc)
435 {
436 	int i;
437 
438 	for (i = 0; i < STGE_TIMEOUT; i++) {
439 		delay(2);
440 		if ((CSR_READ_4(sc, STGE_DMACtrl) & DMAC_TxDMAInProg) == 0)
441 			break;
442 	}
443 
444 	if (i == STGE_TIMEOUT)
445 		printf("%s: DMA wait timed out\n", sc->sc_dev.dv_xname);
446 }
447 
448 /*
449  * stge_start:		[ifnet interface function]
450  *
451  *	Start packet transmission on the interface.
452  */
453 void
454 stge_start(struct ifnet *ifp)
455 {
456 	struct stge_softc *sc = ifp->if_softc;
457 	struct mbuf *m0;
458 	struct stge_descsoft *ds;
459 	struct stge_tfd *tfd;
460 	bus_dmamap_t dmamap;
461 	int error, firsttx, nexttx, opending, seg, totlen;
462 	uint64_t csum_flags = 0, tfc;
463 
464 	if (!(ifp->if_flags & IFF_RUNNING) || ifq_is_oactive(&ifp->if_snd))
465 		return;
466 
467 	/*
468 	 * Remember the previous number of pending transmissions
469 	 * and the first descriptor we will use.
470 	 */
471 	opending = sc->sc_txpending;
472 	firsttx = STGE_NEXTTX(sc->sc_txlast);
473 
474 	/*
475 	 * Loop through the send queue, setting up transmit descriptors
476 	 * until we drain the queue, or use up all available transmit
477 	 * descriptors.
478 	 */
479 	for (;;) {
480 		/*
481 		 * Grab a packet off the queue.
482 		 */
483 		m0 = ifq_deq_begin(&ifp->if_snd);
484 		if (m0 == NULL)
485 			break;
486 
487 		/*
488 		 * Leave one unused descriptor at the end of the
489 		 * list to prevent wrapping completely around.
490 		 */
491 		if (sc->sc_txpending == (STGE_NTXDESC - 1)) {
492 			ifq_deq_rollback(&ifp->if_snd, m0);
493 			break;
494 		}
495 
496 		/*
497 		 * Get the last and next available transmit descriptor.
498 		 */
499 		nexttx = STGE_NEXTTX(sc->sc_txlast);
500 		tfd = &sc->sc_txdescs[nexttx];
501 		ds = &sc->sc_txsoft[nexttx];
502 
503 		dmamap = ds->ds_dmamap;
504 
505 		/*
506 		 * Load the DMA map.  If this fails, the packet either
507 		 * didn't fit in the alloted number of segments, or we
508 		 * were short on resources.  For the too-many-segments
509 		 * case, we simply report an error and drop the packet,
510 		 * since we can't sanely copy a jumbo packet to a single
511 		 * buffer.
512 		 */
513 		error = bus_dmamap_load_mbuf(sc->sc_dmat, dmamap, m0,
514 		    BUS_DMA_NOWAIT);
515 		if (error) {
516 			if (error == EFBIG) {
517 				printf("%s: Tx packet consumes too many "
518 				    "DMA segments (%u), dropping...\n",
519 				    sc->sc_dev.dv_xname, dmamap->dm_nsegs);
520 				ifq_deq_commit(&ifp->if_snd, m0);
521 				m_freem(m0);
522 				continue;
523 			}
524 			/*
525 			 * Short on resources, just stop for now.
526 			 */
527 			ifq_deq_rollback(&ifp->if_snd, m0);
528 			break;
529 		}
530 
531 		ifq_deq_commit(&ifp->if_snd, m0);
532 
533 		/*
534 		 * WE ARE NOW COMMITTED TO TRANSMITTING THE PACKET.
535 		 */
536 
537 		/* Sync the DMA map. */
538 		bus_dmamap_sync(sc->sc_dmat, dmamap, 0, dmamap->dm_mapsize,
539 		    BUS_DMASYNC_PREWRITE);
540 
541 		/* Initialize the fragment list. */
542 		for (totlen = 0, seg = 0; seg < dmamap->dm_nsegs; seg++) {
543 			tfd->tfd_frags[seg].frag_word0 =
544 			    htole64(FRAG_ADDR(dmamap->dm_segs[seg].ds_addr) |
545 			    FRAG_LEN(dmamap->dm_segs[seg].ds_len));
546 			totlen += dmamap->dm_segs[seg].ds_len;
547 		}
548 
549 #ifdef STGE_CHECKSUM
550 		/*
551 		 * Initialize checksumming flags in the descriptor.
552 		 * Byte-swap constants so the compiler can optimize.
553 		 */
554 		if (m0->m_pkthdr.csum_flags & M_IPV4_CSUM_OUT)
555 			csum_flags |= TFD_IPChecksumEnable;
556 
557 		if (m0->m_pkthdr.csum_flags & M_TCP_CSUM_OUT)
558 			csum_flags |= TFD_TCPChecksumEnable;
559 		else if (m0->m_pkthdr.csum_flags & M_UDP_CSUM_OUT)
560 			csum_flags |= TFD_UDPChecksumEnable;
561 #endif
562 
563 		/*
564 		 * Initialize the descriptor and give it to the chip.
565 		 */
566 		tfc = TFD_FrameId(nexttx) | TFD_WordAlign(/*totlen & */3) |
567 		    TFD_FragCount(seg) | csum_flags;
568 		if ((nexttx & STGE_TXINTR_SPACING_MASK) == 0)
569 			tfc |= TFD_TxDMAIndicate;
570 
571 #if NVLAN > 0
572 		/* Check if we have a VLAN tag to insert. */
573 		if (m0->m_flags & M_VLANTAG)
574 			tfc |= (TFD_VLANTagInsert |
575 			    TFD_VID(m0->m_pkthdr.ether_vtag));
576 #endif
577 
578 		tfd->tfd_control = htole64(tfc);
579 
580 		/* Sync the descriptor. */
581 		STGE_CDTXSYNC(sc, nexttx,
582 		    BUS_DMASYNC_PREREAD|BUS_DMASYNC_PREWRITE);
583 
584 		/*
585 		 * Kick the transmit DMA logic.
586 		 */
587 		CSR_WRITE_4(sc, STGE_DMACtrl,
588 		    sc->sc_DMACtrl | DMAC_TxDMAPollNow);
589 
590 		/*
591 		 * Store a pointer to the packet so we can free it later.
592 		 */
593 		ds->ds_mbuf = m0;
594 
595 		/* Advance the tx pointer. */
596 		sc->sc_txpending++;
597 		sc->sc_txlast = nexttx;
598 
599 #if NBPFILTER > 0
600 		/*
601 		 * Pass the packet to any BPF listeners.
602 		 */
603 		if (ifp->if_bpf)
604 			bpf_mtap_ether(ifp->if_bpf, m0, BPF_DIRECTION_OUT);
605 #endif /* NBPFILTER > 0 */
606 	}
607 
608 	if (sc->sc_txpending == (STGE_NTXDESC - 1)) {
609 		/* No more slots left; notify upper layer. */
610 		ifq_set_oactive(&ifp->if_snd);
611 	}
612 
613 	if (sc->sc_txpending != opending) {
614 		/*
615 		 * We enqueued packets.  If the transmitter was idle,
616 		 * reset the txdirty pointer.
617 		 */
618 		if (opending == 0)
619 			sc->sc_txdirty = firsttx;
620 
621 		/* Set a watchdog timer in case the chip flakes out. */
622 		ifp->if_timer = 5;
623 	}
624 }
625 
626 /*
627  * stge_watchdog:	[ifnet interface function]
628  *
629  *	Watchdog timer handler.
630  */
631 void
632 stge_watchdog(struct ifnet *ifp)
633 {
634 	struct stge_softc *sc = ifp->if_softc;
635 
636 	/*
637 	 * Sweep up first, since we don't interrupt every frame.
638 	 */
639 	stge_txintr(sc);
640 	if (sc->sc_txpending != 0) {
641 		printf("%s: device timeout\n", sc->sc_dev.dv_xname);
642 		ifp->if_oerrors++;
643 
644 		(void) stge_init(ifp);
645 
646 		/* Try to get more packets going. */
647 		stge_start(ifp);
648 	}
649 }
650 
651 /*
652  * stge_ioctl:		[ifnet interface function]
653  *
654  *	Handle control requests from the operator.
655  */
656 int
657 stge_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
658 {
659 	struct stge_softc *sc = ifp->if_softc;
660 	struct ifreq *ifr = (struct ifreq *)data;
661 	int s, error = 0;
662 
663 	s = splnet();
664 
665 	switch (cmd) {
666 	case SIOCSIFADDR:
667 		ifp->if_flags |= IFF_UP;
668 		if (!(ifp->if_flags & IFF_RUNNING))
669 			stge_init(ifp);
670 		break;
671 
672 	case SIOCSIFFLAGS:
673 		if (ifp->if_flags & IFF_UP) {
674 			if (ifp->if_flags & IFF_RUNNING)
675 				error = ENETRESET;
676 			else
677 				stge_init(ifp);
678 		} else {
679 			if (ifp->if_flags & IFF_RUNNING)
680 				stge_stop(ifp, 1);
681 		}
682 		break;
683 
684 	case SIOCSIFMEDIA:
685 	case SIOCGIFMEDIA:
686 		error = ifmedia_ioctl(ifp, ifr, &sc->sc_mii.mii_media, cmd);
687 		break;
688 
689 	default:
690 		error = ether_ioctl(ifp, &sc->sc_arpcom, cmd, data);
691 	}
692 
693 	if (error == ENETRESET) {
694 		if (ifp->if_flags & IFF_RUNNING)
695 			stge_iff(sc);
696 		error = 0;
697 	}
698 
699 	splx(s);
700 	return (error);
701 }
702 
703 /*
704  * stge_intr:
705  *
706  *	Interrupt service routine.
707  */
708 int
709 stge_intr(void *arg)
710 {
711 	struct stge_softc *sc = arg;
712 	struct ifnet *ifp = &sc->sc_arpcom.ac_if;
713 	uint32_t txstat;
714 	int wantinit;
715 	uint16_t isr;
716 
717 	if ((CSR_READ_2(sc, STGE_IntStatus) & IS_InterruptStatus) == 0)
718 		return (0);
719 
720 	for (wantinit = 0; wantinit == 0;) {
721 		isr = CSR_READ_2(sc, STGE_IntStatusAck);
722 		if ((isr & sc->sc_IntEnable) == 0)
723 			break;
724 
725 		/* Host interface errors. */
726 		if (isr & IS_HostError) {
727 			printf("%s: Host interface error\n",
728 			    sc->sc_dev.dv_xname);
729 			wantinit = 1;
730 			continue;
731 		}
732 
733 		/* Receive interrupts. */
734 		if (isr & (IS_RxDMAComplete|IS_RFDListEnd)) {
735 			stge_rxintr(sc);
736 			if (isr & IS_RFDListEnd) {
737 				printf("%s: receive ring overflow\n",
738 				    sc->sc_dev.dv_xname);
739 				/*
740 				 * XXX Should try to recover from this
741 				 * XXX more gracefully.
742 				 */
743 				wantinit = 1;
744 			}
745 		}
746 
747 		/* Transmit interrupts. */
748 		if (isr & (IS_TxDMAComplete|IS_TxComplete))
749 			stge_txintr(sc);
750 
751 		/* Statistics overflow. */
752 		if (isr & IS_UpdateStats)
753 			stge_stats_update(sc);
754 
755 		/* Transmission errors. */
756 		if (isr & IS_TxComplete) {
757 			for (;;) {
758 				txstat = CSR_READ_4(sc, STGE_TxStatus);
759 				if ((txstat & TS_TxComplete) == 0)
760 					break;
761 				if (txstat & TS_TxUnderrun) {
762 					sc->sc_txthresh++;
763 					if (sc->sc_txthresh > 0x0fff)
764 						sc->sc_txthresh = 0x0fff;
765 					printf("%s: transmit underrun, new "
766 					    "threshold: %d bytes\n",
767 					    sc->sc_dev.dv_xname,
768 					    sc->sc_txthresh << 5);
769 				}
770 				if (txstat & TS_MaxCollisions)
771 					printf("%s: excessive collisions\n",
772 					    sc->sc_dev.dv_xname);
773 			}
774 			wantinit = 1;
775 		}
776 
777 	}
778 
779 	if (wantinit)
780 		stge_init(ifp);
781 
782 	CSR_WRITE_2(sc, STGE_IntEnable, sc->sc_IntEnable);
783 
784 	/* Try to get more packets going. */
785 	stge_start(ifp);
786 
787 	return (1);
788 }
789 
790 /*
791  * stge_txintr:
792  *
793  *	Helper; handle transmit interrupts.
794  */
795 void
796 stge_txintr(struct stge_softc *sc)
797 {
798 	struct ifnet *ifp = &sc->sc_arpcom.ac_if;
799 	struct stge_descsoft *ds;
800 	uint64_t control;
801 	int i;
802 
803 	ifq_clr_oactive(&ifp->if_snd);
804 
805 	/*
806 	 * Go through our Tx list and free mbufs for those
807 	 * frames which have been transmitted.
808 	 */
809 	for (i = sc->sc_txdirty; sc->sc_txpending != 0;
810 	     i = STGE_NEXTTX(i), sc->sc_txpending--) {
811 		ds = &sc->sc_txsoft[i];
812 
813 		STGE_CDTXSYNC(sc, i,
814 		    BUS_DMASYNC_POSTREAD|BUS_DMASYNC_POSTWRITE);
815 
816 		control = letoh64(sc->sc_txdescs[i].tfd_control);
817 		if ((control & TFD_TFDDone) == 0)
818 			break;
819 
820 		bus_dmamap_sync(sc->sc_dmat, ds->ds_dmamap,
821 		    0, ds->ds_dmamap->dm_mapsize, BUS_DMASYNC_POSTWRITE);
822 		bus_dmamap_unload(sc->sc_dmat, ds->ds_dmamap);
823 		m_freem(ds->ds_mbuf);
824 		ds->ds_mbuf = NULL;
825 	}
826 
827 	/* Update the dirty transmit buffer pointer. */
828 	sc->sc_txdirty = i;
829 
830 	/*
831 	 * If there are no more pending transmissions, cancel the watchdog
832 	 * timer.
833 	 */
834 	if (sc->sc_txpending == 0)
835 		ifp->if_timer = 0;
836 }
837 
838 /*
839  * stge_rxintr:
840  *
841  *	Helper; handle receive interrupts.
842  */
843 void
844 stge_rxintr(struct stge_softc *sc)
845 {
846 	struct ifnet *ifp = &sc->sc_arpcom.ac_if;
847 	struct stge_descsoft *ds;
848 	struct mbuf *m, *tailm;
849 	struct mbuf_list ml = MBUF_LIST_INITIALIZER();
850 	uint64_t status;
851 	int i, len;
852 
853 	for (i = sc->sc_rxptr;; i = STGE_NEXTRX(i)) {
854 		ds = &sc->sc_rxsoft[i];
855 
856 		STGE_CDRXSYNC(sc, i,
857 		    BUS_DMASYNC_POSTREAD|BUS_DMASYNC_POSTWRITE);
858 
859 		status = letoh64(sc->sc_rxdescs[i].rfd_status);
860 
861 		if ((status & RFD_RFDDone) == 0)
862 			break;
863 
864 		if (__predict_false(sc->sc_rxdiscard)) {
865 			STGE_INIT_RXDESC(sc, i);
866 			if (status & RFD_FrameEnd) {
867 				/* Reset our state. */
868 				sc->sc_rxdiscard = 0;
869 			}
870 			continue;
871 		}
872 
873 		bus_dmamap_sync(sc->sc_dmat, ds->ds_dmamap, 0,
874 		    ds->ds_dmamap->dm_mapsize, BUS_DMASYNC_POSTREAD);
875 
876 		m = ds->ds_mbuf;
877 
878 		/*
879 		 * Add a new receive buffer to the ring.
880 		 */
881 		if (stge_add_rxbuf(sc, i) != 0) {
882 			/*
883 			 * Failed, throw away what we've done so
884 			 * far, and discard the rest of the packet.
885 			 */
886 			ifp->if_ierrors++;
887 			bus_dmamap_sync(sc->sc_dmat, ds->ds_dmamap, 0,
888 			    ds->ds_dmamap->dm_mapsize, BUS_DMASYNC_POSTREAD);
889 			STGE_INIT_RXDESC(sc, i);
890 			if ((status & RFD_FrameEnd) == 0)
891 				sc->sc_rxdiscard = 1;
892 			if (sc->sc_rxhead != NULL)
893 				m_freem(sc->sc_rxhead);
894 			STGE_RXCHAIN_RESET(sc);
895 			continue;
896 		}
897 
898 #ifdef DIAGNOSTIC
899 		if (status & RFD_FrameStart) {
900 			KASSERT(sc->sc_rxhead == NULL);
901 			KASSERT(sc->sc_rxtailp == &sc->sc_rxhead);
902 		}
903 #endif
904 
905 		STGE_RXCHAIN_LINK(sc, m);
906 
907 		/*
908 		 * If this is not the end of the packet, keep
909 		 * looking.
910 		 */
911 		if ((status & RFD_FrameEnd) == 0) {
912 			sc->sc_rxlen += m->m_len;
913 			continue;
914 		}
915 
916 		/*
917 		 * Okay, we have the entire packet now...
918 		 */
919 		*sc->sc_rxtailp = NULL;
920 		m = sc->sc_rxhead;
921 		tailm = sc->sc_rxtail;
922 
923 		STGE_RXCHAIN_RESET(sc);
924 
925 		/*
926 		 * If the packet had an error, drop it.  Note we
927 		 * count the error later in the periodic stats update.
928 		 */
929 		if (status & (RFD_RxFIFOOverrun | RFD_RxRuntFrame |
930 			      RFD_RxAlignmentError | RFD_RxFCSError |
931 			      RFD_RxLengthError)) {
932 			m_freem(m);
933 			continue;
934 		}
935 
936 		/*
937 		 * No errors.
938 		 *
939 		 * Note we have configured the chip to not include
940 		 * the CRC at the end of the packet.
941 		 */
942 		len = RFD_RxDMAFrameLen(status);
943 		tailm->m_len = len - sc->sc_rxlen;
944 
945 		/*
946 		 * If the packet is small enough to fit in a
947 		 * single header mbuf, allocate one and copy
948 		 * the data into it.  This greatly reduces
949 		 * memory consumption when we receive lots
950 		 * of small packets.
951 		 */
952 		if (stge_copy_small != 0 && len <= (MHLEN - 2)) {
953 			struct mbuf *nm;
954 			MGETHDR(nm, M_DONTWAIT, MT_DATA);
955 			if (nm == NULL) {
956 				ifp->if_ierrors++;
957 				m_freem(m);
958 				continue;
959 			}
960 			nm->m_data += 2;
961 			nm->m_pkthdr.len = nm->m_len = len;
962 			m_copydata(m, 0, len, mtod(nm, caddr_t));
963 			m_freem(m);
964 			m = nm;
965 		}
966 
967 		/*
968 		 * Set the incoming checksum information for the packet.
969 		 */
970 		if ((status & RFD_IPDetected) &&
971 		    (!(status & RFD_IPError)))
972 			m->m_pkthdr.csum_flags |= M_IPV4_CSUM_IN_OK;
973 		if ((status & RFD_TCPDetected) &&
974 		    (!(status & RFD_TCPError)))
975 			m->m_pkthdr.csum_flags |= M_TCP_CSUM_IN_OK;
976 		else if ((status & RFD_UDPDetected) &&
977 		    (!(status & RFD_UDPError)))
978 			m->m_pkthdr.csum_flags |= M_UDP_CSUM_IN_OK;
979 
980 #if NVLAN > 0
981 		/* Check for VLAN tagged packets. */
982 		if (status & RFD_VLANDetected) {
983 			m->m_pkthdr.ether_vtag = RFD_TCI(status);
984 			m->m_flags |= M_VLANTAG;
985 		}
986 #endif
987 
988 		m->m_pkthdr.len = len;
989 
990 		ml_enqueue(&ml, m);
991 	}
992 
993 	/* Update the receive pointer. */
994 	sc->sc_rxptr = i;
995 
996 	if_input(ifp, &ml);
997 }
998 
999 /*
1000  * stge_tick:
1001  *
1002  *	One second timer, used to tick the MII.
1003  */
1004 void
1005 stge_tick(void *arg)
1006 {
1007 	struct stge_softc *sc = arg;
1008 	int s;
1009 
1010 	s = splnet();
1011 	mii_tick(&sc->sc_mii);
1012 	stge_stats_update(sc);
1013 	splx(s);
1014 
1015 	timeout_add_sec(&sc->sc_timeout, 1);
1016 }
1017 
1018 /*
1019  * stge_stats_update:
1020  *
1021  *	Read the TC9021 statistics counters.
1022  */
1023 void
1024 stge_stats_update(struct stge_softc *sc)
1025 {
1026 	struct ifnet *ifp = &sc->sc_arpcom.ac_if;
1027 
1028 	(void) CSR_READ_4(sc, STGE_OctetRcvOk);
1029 
1030 	ifp->if_ierrors +=
1031 	    (u_int) CSR_READ_2(sc, STGE_FramesLostRxErrors);
1032 
1033 	(void) CSR_READ_4(sc, STGE_OctetXmtdOk);
1034 
1035 	ifp->if_opackets +=
1036 	    CSR_READ_4(sc, STGE_FramesXmtdOk);
1037 
1038 	ifp->if_collisions +=
1039 	    CSR_READ_4(sc, STGE_LateCollisions) +
1040 	    CSR_READ_4(sc, STGE_MultiColFrames) +
1041 	    CSR_READ_4(sc, STGE_SingleColFrames);
1042 
1043 	ifp->if_oerrors +=
1044 	    (u_int) CSR_READ_2(sc, STGE_FramesAbortXSColls) +
1045 	    (u_int) CSR_READ_2(sc, STGE_FramesWEXDeferal);
1046 }
1047 
1048 /*
1049  * stge_reset:
1050  *
1051  *	Perform a soft reset on the TC9021.
1052  */
1053 void
1054 stge_reset(struct stge_softc *sc)
1055 {
1056 	uint32_t ac;
1057 	int i;
1058 
1059 	ac = CSR_READ_4(sc, STGE_AsicCtrl);
1060 
1061 	/*
1062 	 * Only assert RstOut if we're fiber.  We need GMII clocks
1063 	 * to be present in order for the reset to complete on fiber
1064 	 * cards.
1065 	 */
1066 	CSR_WRITE_4(sc, STGE_AsicCtrl,
1067 	    ac | AC_GlobalReset | AC_RxReset | AC_TxReset |
1068 	    AC_DMA | AC_FIFO | AC_Network | AC_Host | AC_AutoInit |
1069 	    (sc->sc_usefiber ? AC_RstOut : 0));
1070 
1071 	delay(50000);
1072 
1073 	for (i = 0; i < STGE_TIMEOUT; i++) {
1074 		delay(5000);
1075 		if ((CSR_READ_4(sc, STGE_AsicCtrl) & AC_ResetBusy) == 0)
1076 			break;
1077 	}
1078 
1079 	if (i == STGE_TIMEOUT)
1080 		printf("%s: reset failed to complete\n", sc->sc_dev.dv_xname);
1081 
1082 	delay(1000);
1083 }
1084 
1085 /*
1086  * stge_init:		[ ifnet interface function ]
1087  *
1088  *	Initialize the interface.  Must be called at splnet().
1089  */
1090 int
1091 stge_init(struct ifnet *ifp)
1092 {
1093 	struct stge_softc *sc = ifp->if_softc;
1094 	struct stge_descsoft *ds;
1095 	int i, error = 0;
1096 
1097 	/*
1098 	 * Cancel any pending I/O.
1099 	 */
1100 	stge_stop(ifp, 0);
1101 
1102 	/*
1103 	 * Reset the chip to a known state.
1104 	 */
1105 	stge_reset(sc);
1106 
1107 	/*
1108 	 * Initialize the transmit descriptor ring.
1109 	 */
1110 	memset(sc->sc_txdescs, 0, sizeof(sc->sc_txdescs));
1111 	for (i = 0; i < STGE_NTXDESC; i++) {
1112 		sc->sc_txdescs[i].tfd_next = htole64(
1113 		    STGE_CDTXADDR(sc, STGE_NEXTTX(i)));
1114 		sc->sc_txdescs[i].tfd_control = htole64(TFD_TFDDone);
1115 	}
1116 	sc->sc_txpending = 0;
1117 	sc->sc_txdirty = 0;
1118 	sc->sc_txlast = STGE_NTXDESC - 1;
1119 
1120 	/*
1121 	 * Initialize the receive descriptor and receive job
1122 	 * descriptor rings.
1123 	 */
1124 	for (i = 0; i < STGE_NRXDESC; i++) {
1125 		ds = &sc->sc_rxsoft[i];
1126 		if (ds->ds_mbuf == NULL) {
1127 			if ((error = stge_add_rxbuf(sc, i)) != 0) {
1128 				printf("%s: unable to allocate or map rx "
1129 				    "buffer %d, error = %d\n",
1130 				    sc->sc_dev.dv_xname, i, error);
1131 				/*
1132 				 * XXX Should attempt to run with fewer receive
1133 				 * XXX buffers instead of just failing.
1134 				 */
1135 				stge_rxdrain(sc);
1136 				goto out;
1137 			}
1138 		} else
1139 			STGE_INIT_RXDESC(sc, i);
1140 	}
1141 	sc->sc_rxptr = 0;
1142 	sc->sc_rxdiscard = 0;
1143 	STGE_RXCHAIN_RESET(sc);
1144 
1145 	/* Set the station address. */
1146 	if (sc->sc_stge1023) {
1147 		CSR_WRITE_2(sc, STGE_StationAddress0,
1148 		    sc->sc_arpcom.ac_enaddr[0] | sc->sc_arpcom.ac_enaddr[1] << 8);
1149 		CSR_WRITE_2(sc, STGE_StationAddress1,
1150 		    sc->sc_arpcom.ac_enaddr[2] | sc->sc_arpcom.ac_enaddr[3] << 8);
1151 		CSR_WRITE_2(sc, STGE_StationAddress2,
1152 		    sc->sc_arpcom.ac_enaddr[4] | sc->sc_arpcom.ac_enaddr[5] << 8);
1153 	} else {
1154 		for (i = 0; i < ETHER_ADDR_LEN; i++)
1155 			CSR_WRITE_1(sc, STGE_StationAddress0 + i,
1156 			    sc->sc_arpcom.ac_enaddr[i]);
1157 	}
1158 
1159 	/*
1160 	 * Set the statistics masks.  Disable all the RMON stats,
1161 	 * and disable selected stats in the non-RMON stats registers.
1162 	 */
1163 	CSR_WRITE_4(sc, STGE_RMONStatisticsMask, 0xffffffff);
1164 	CSR_WRITE_4(sc, STGE_StatisticsMask,
1165 	    (1U << 1) | (1U << 2) | (1U << 3) | (1U << 4) | (1U << 5) |
1166 	    (1U << 6) | (1U << 7) | (1U << 8) | (1U << 9) | (1U << 10) |
1167 	    (1U << 13) | (1U << 14) | (1U << 15) | (1U << 19) | (1U << 20) |
1168 	    (1U << 21));
1169 
1170 	/* Program promiscuous mode and multicast filters. */
1171 	stge_iff(sc);
1172 
1173 	/*
1174 	 * Give the transmit and receive ring to the chip.
1175 	 */
1176 	CSR_WRITE_4(sc, STGE_TFDListPtrHi, 0); /* NOTE: 32-bit DMA */
1177 	CSR_WRITE_4(sc, STGE_TFDListPtrLo,
1178 	    STGE_CDTXADDR(sc, sc->sc_txdirty));
1179 
1180 	CSR_WRITE_4(sc, STGE_RFDListPtrHi, 0); /* NOTE: 32-bit DMA */
1181 	CSR_WRITE_4(sc, STGE_RFDListPtrLo,
1182 	    STGE_CDRXADDR(sc, sc->sc_rxptr));
1183 
1184 	/*
1185 	 * Initialize the Tx auto-poll period.  It's OK to make this number
1186 	 * large (255 is the max, but we use 127) -- we explicitly kick the
1187 	 * transmit engine when there's actually a packet.
1188 	 */
1189 	CSR_WRITE_1(sc, STGE_TxDMAPollPeriod, 127);
1190 
1191 	/* ..and the Rx auto-poll period. */
1192 	CSR_WRITE_1(sc, STGE_RxDMAPollPeriod, 64);
1193 
1194 	/* Initialize the Tx start threshold. */
1195 	CSR_WRITE_2(sc, STGE_TxStartThresh, sc->sc_txthresh);
1196 
1197 	/* RX DMA thresholds, from linux */
1198 	CSR_WRITE_1(sc, STGE_RxDMABurstThresh, 0x30);
1199 	CSR_WRITE_1(sc, STGE_RxDMAUrgentThresh, 0x30);
1200 
1201 	/* Rx early threhold, from Linux */
1202 	CSR_WRITE_2(sc, STGE_RxEarlyThresh, 0x7ff);
1203 
1204 	/* Tx DMA thresholds, from Linux */
1205 	CSR_WRITE_1(sc, STGE_TxDMABurstThresh, 0x30);
1206 	CSR_WRITE_1(sc, STGE_TxDMAUrgentThresh, 0x04);
1207 
1208 	/*
1209 	 * Initialize the Rx DMA interrupt control register.  We
1210 	 * request an interrupt after every incoming packet, but
1211 	 * defer it for 32us (64 * 512 ns).  When the number of
1212 	 * interrupts pending reaches 8, we stop deferring the
1213 	 * interrupt, and signal it immediately.
1214 	 */
1215 	CSR_WRITE_4(sc, STGE_RxDMAIntCtrl,
1216 	    RDIC_RxFrameCount(8) | RDIC_RxDMAWaitTime(512));
1217 
1218 	/*
1219 	 * Initialize the interrupt mask.
1220 	 */
1221 	sc->sc_IntEnable = IS_HostError | IS_TxComplete | IS_UpdateStats |
1222 	    IS_TxDMAComplete | IS_RxDMAComplete | IS_RFDListEnd;
1223 	CSR_WRITE_2(sc, STGE_IntStatus, 0xffff);
1224 	CSR_WRITE_2(sc, STGE_IntEnable, sc->sc_IntEnable);
1225 
1226 	/*
1227 	 * Configure the DMA engine.
1228 	 * XXX Should auto-tune TxBurstLimit.
1229 	 */
1230 	CSR_WRITE_4(sc, STGE_DMACtrl, sc->sc_DMACtrl |
1231 	    DMAC_TxBurstLimit(3));
1232 
1233 	/*
1234 	 * Send a PAUSE frame when we reach 29,696 bytes in the Rx
1235 	 * FIFO, and send an un-PAUSE frame when we reach 3056 bytes
1236 	 * in the Rx FIFO.
1237 	 */
1238 	CSR_WRITE_2(sc, STGE_FlowOnTresh, 29696 / 16);
1239 	CSR_WRITE_2(sc, STGE_FlowOffThresh, 3056 / 16);
1240 
1241 	/*
1242 	 * Set the maximum frame size.
1243 	 */
1244 #ifdef STGE_JUMBO
1245 	CSR_WRITE_2(sc, STGE_MaxFrameSize, STGE_JUMBO_FRAMELEN);
1246 #else
1247 	CSR_WRITE_2(sc, STGE_MaxFrameSize, ETHER_MAX_LEN);
1248 #endif
1249 
1250 	/*
1251 	 * Initialize MacCtrl -- do it before setting the media,
1252 	 * as setting the media will actually program the register.
1253 	 *
1254 	 * Note: We have to poke the IFS value before poking
1255 	 * anything else.
1256 	 */
1257 	sc->sc_MACCtrl = MC_IFSSelect(0);
1258 	CSR_WRITE_4(sc, STGE_MACCtrl, sc->sc_MACCtrl);
1259 
1260 	if (ifp->if_capabilities & IFCAP_VLAN_HWTAGGING)
1261 		sc->sc_MACCtrl |= MC_AutoVLANuntagging;
1262 
1263 	sc->sc_MACCtrl |= MC_StatisticsEnable | MC_TxEnable | MC_RxEnable;
1264 
1265 	if (sc->sc_rev >= 6) {		/* >= B.2 */
1266 		/* Multi-frag frame bug work-around. */
1267 		CSR_WRITE_2(sc, STGE_DebugCtrl,
1268 		    CSR_READ_2(sc, STGE_DebugCtrl) | 0x0200);
1269 
1270 		/* Tx Poll Now bug work-around. */
1271 		CSR_WRITE_2(sc, STGE_DebugCtrl,
1272 		    CSR_READ_2(sc, STGE_DebugCtrl) | 0x0010);
1273 
1274 		/* Rx Poll Now bug work-around. */
1275 		CSR_WRITE_2(sc, STGE_DebugCtrl,
1276 		    CSR_READ_2(sc, STGE_DebugCtrl) | 0x0020);
1277 	}
1278 
1279 	/*
1280 	 * Set the current media.
1281 	 */
1282 	mii_mediachg(&sc->sc_mii);
1283 
1284 	/*
1285 	 * Start the one second MII clock.
1286 	 */
1287 	timeout_add_sec(&sc->sc_timeout, 1);
1288 
1289 	/*
1290 	 * ...all done!
1291 	 */
1292 	ifp->if_flags |= IFF_RUNNING;
1293 	ifq_clr_oactive(&ifp->if_snd);
1294 
1295  out:
1296 	if (error)
1297 		printf("%s: interface not running\n", sc->sc_dev.dv_xname);
1298 	return (error);
1299 }
1300 
1301 /*
1302  * stge_drain:
1303  *
1304  *	Drain the receive queue.
1305  */
1306 void
1307 stge_rxdrain(struct stge_softc *sc)
1308 {
1309 	struct stge_descsoft *ds;
1310 	int i;
1311 
1312 	for (i = 0; i < STGE_NRXDESC; i++) {
1313 		ds = &sc->sc_rxsoft[i];
1314 		if (ds->ds_mbuf != NULL) {
1315 			bus_dmamap_unload(sc->sc_dmat, ds->ds_dmamap);
1316 			ds->ds_mbuf->m_next = NULL;
1317 			m_freem(ds->ds_mbuf);
1318 			ds->ds_mbuf = NULL;
1319 		}
1320 	}
1321 }
1322 
1323 /*
1324  * stge_stop:		[ ifnet interface function ]
1325  *
1326  *	Stop transmission on the interface.
1327  */
1328 void
1329 stge_stop(struct ifnet *ifp, int disable)
1330 {
1331 	struct stge_softc *sc = ifp->if_softc;
1332 	struct stge_descsoft *ds;
1333 	int i;
1334 
1335 	/*
1336 	 * Stop the one second clock.
1337 	 */
1338 	timeout_del(&sc->sc_timeout);
1339 
1340 	/*
1341 	 * Mark the interface down and cancel the watchdog timer.
1342 	 */
1343 	ifp->if_flags &= ~IFF_RUNNING;
1344 	ifq_clr_oactive(&ifp->if_snd);
1345 	ifp->if_timer = 0;
1346 
1347 	/* Down the MII. */
1348 	mii_down(&sc->sc_mii);
1349 
1350 	/*
1351 	 * Disable interrupts.
1352 	 */
1353 	CSR_WRITE_2(sc, STGE_IntEnable, 0);
1354 
1355 	/*
1356 	 * Stop receiver, transmitter, and stats update.
1357 	 */
1358 	CSR_WRITE_4(sc, STGE_MACCtrl,
1359 	    MC_StatisticsDisable | MC_TxDisable | MC_RxDisable);
1360 
1361 	/*
1362 	 * Stop the transmit and receive DMA.
1363 	 */
1364 	stge_dma_wait(sc);
1365 	CSR_WRITE_4(sc, STGE_TFDListPtrHi, 0);
1366 	CSR_WRITE_4(sc, STGE_TFDListPtrLo, 0);
1367 	CSR_WRITE_4(sc, STGE_RFDListPtrHi, 0);
1368 	CSR_WRITE_4(sc, STGE_RFDListPtrLo, 0);
1369 
1370 	/*
1371 	 * Release any queued transmit buffers.
1372 	 */
1373 	for (i = 0; i < STGE_NTXDESC; i++) {
1374 		ds = &sc->sc_txsoft[i];
1375 		if (ds->ds_mbuf != NULL) {
1376 			bus_dmamap_unload(sc->sc_dmat, ds->ds_dmamap);
1377 			m_freem(ds->ds_mbuf);
1378 			ds->ds_mbuf = NULL;
1379 		}
1380 	}
1381 
1382 	if (disable)
1383 		stge_rxdrain(sc);
1384 }
1385 
1386 static int
1387 stge_eeprom_wait(struct stge_softc *sc)
1388 {
1389 	int i;
1390 
1391 	for (i = 0; i < STGE_TIMEOUT; i++) {
1392 		delay(1000);
1393 		if ((CSR_READ_2(sc, STGE_EepromCtrl) & EC_EepromBusy) == 0)
1394 			return (0);
1395 	}
1396 	return (1);
1397 }
1398 
1399 /*
1400  * stge_read_eeprom:
1401  *
1402  *	Read data from the serial EEPROM.
1403  */
1404 void
1405 stge_read_eeprom(struct stge_softc *sc, int offset, uint16_t *data)
1406 {
1407 
1408 	if (stge_eeprom_wait(sc))
1409 		printf("%s: EEPROM failed to come ready\n",
1410 		    sc->sc_dev.dv_xname);
1411 
1412 	CSR_WRITE_2(sc, STGE_EepromCtrl,
1413 	    EC_EepromAddress(offset) | EC_EepromOpcode(EC_OP_RR));
1414 	if (stge_eeprom_wait(sc))
1415 		printf("%s: EEPROM read timed out\n",
1416 		    sc->sc_dev.dv_xname);
1417 	*data = CSR_READ_2(sc, STGE_EepromData);
1418 }
1419 
1420 /*
1421  * stge_add_rxbuf:
1422  *
1423  *	Add a receive buffer to the indicated descriptor.
1424  */
1425 int
1426 stge_add_rxbuf(struct stge_softc *sc, int idx)
1427 {
1428 	struct stge_descsoft *ds = &sc->sc_rxsoft[idx];
1429 	struct mbuf *m;
1430 	int error;
1431 
1432 	MGETHDR(m, M_DONTWAIT, MT_DATA);
1433 	if (m == NULL)
1434 		return (ENOBUFS);
1435 
1436 	MCLGET(m, M_DONTWAIT);
1437 	if ((m->m_flags & M_EXT) == 0) {
1438 		m_freem(m);
1439 		return (ENOBUFS);
1440 	}
1441 
1442 	m->m_data = m->m_ext.ext_buf + 2;
1443 	m->m_len = MCLBYTES - 2;
1444 
1445 	if (ds->ds_mbuf != NULL)
1446 		bus_dmamap_unload(sc->sc_dmat, ds->ds_dmamap);
1447 
1448 	ds->ds_mbuf = m;
1449 
1450 	error = bus_dmamap_load(sc->sc_dmat, ds->ds_dmamap,
1451 	    m->m_ext.ext_buf, m->m_ext.ext_size, NULL, BUS_DMA_NOWAIT);
1452 	if (error) {
1453 		printf("%s: can't load rx DMA map %d, error = %d\n",
1454 		    sc->sc_dev.dv_xname, idx, error);
1455 		panic("stge_add_rxbuf");	/* XXX */
1456 	}
1457 
1458 	bus_dmamap_sync(sc->sc_dmat, ds->ds_dmamap, 0,
1459 	    ds->ds_dmamap->dm_mapsize, BUS_DMASYNC_PREREAD);
1460 
1461 	STGE_INIT_RXDESC(sc, idx);
1462 
1463 	return (0);
1464 }
1465 
1466 /*
1467  * stge_iff:
1468  *
1469  *	Set up the receive filter.
1470  */
1471 void
1472 stge_iff(struct stge_softc *sc)
1473 {
1474 	struct arpcom *ac = &sc->sc_arpcom;
1475 	struct ifnet *ifp = &sc->sc_arpcom.ac_if;
1476 	struct ether_multi *enm;
1477 	struct ether_multistep step;
1478 	uint32_t crc;
1479 	uint32_t mchash[2];
1480 
1481 	memset(mchash, 0, sizeof(mchash));
1482 	ifp->if_flags &= ~IFF_ALLMULTI;
1483 
1484 	/*
1485 	 * Always accept broadcast packets.
1486 	 * Always accept frames destined to our station address.
1487 	 */
1488 	sc->sc_ReceiveMode = RM_ReceiveBroadcast | RM_ReceiveUnicast;
1489 
1490 	if (ifp->if_flags & IFF_PROMISC || ac->ac_multirangecnt > 0) {
1491 		ifp->if_flags |= IFF_ALLMULTI;
1492 		if (ifp->if_flags & IFF_PROMISC)
1493 			sc->sc_ReceiveMode |= RM_ReceiveAllFrames;
1494 		else
1495 			sc->sc_ReceiveMode |= RM_ReceiveMulticast;
1496 	} else {
1497 		/*
1498 		 * Set up the multicast address filter by passing all
1499 		 * multicast addresses through a CRC generator, and then
1500 		 * using the low-order 6 bits as an index into the 64 bit
1501 		 * multicast hash table.  The high order bits select the
1502 		 * register, while the rest of the bits select the bit
1503 		 * within the register.
1504 		 */
1505 		sc->sc_ReceiveMode |= RM_ReceiveMulticastHash;
1506 
1507 		ETHER_FIRST_MULTI(step, ac, enm);
1508 		while (enm != NULL) {
1509 			crc = ether_crc32_be(enm->enm_addrlo,
1510 			    ETHER_ADDR_LEN);
1511 
1512 			/* Just want the 6 least significant bits. */
1513 			crc &= 0x3f;
1514 
1515 			/* Set the corresponding bit in the hash table. */
1516 			mchash[crc >> 5] |= 1 << (crc & 0x1f);
1517 
1518 			ETHER_NEXT_MULTI(step, enm);
1519 		}
1520 	}
1521 
1522 	CSR_WRITE_4(sc, STGE_HashTable0, mchash[0]);
1523 	CSR_WRITE_4(sc, STGE_HashTable1, mchash[1]);
1524 	CSR_WRITE_2(sc, STGE_ReceiveMode, sc->sc_ReceiveMode);
1525 }
1526 
1527 /*
1528  * stge_mii_readreg:	[mii interface function]
1529  *
1530  *	Read a PHY register on the MII of the TC9021.
1531  */
1532 int
1533 stge_mii_readreg(struct device *self, int phy, int reg)
1534 {
1535 
1536 	return (mii_bitbang_readreg(self, &stge_mii_bitbang_ops, phy, reg));
1537 }
1538 
1539 /*
1540  * stge_mii_writereg:	[mii interface function]
1541  *
1542  *	Write a PHY register on the MII of the TC9021.
1543  */
1544 void
1545 stge_mii_writereg(struct device *self, int phy, int reg, int val)
1546 {
1547 
1548 	mii_bitbang_writereg(self, &stge_mii_bitbang_ops, phy, reg, val);
1549 }
1550 
1551 /*
1552  * stge_mii_statchg:	[mii interface function]
1553  *
1554  *	Callback from MII layer when media changes.
1555  */
1556 void
1557 stge_mii_statchg(struct device *self)
1558 {
1559 	struct stge_softc *sc = (struct stge_softc *) self;
1560 	struct mii_data *mii = &sc->sc_mii;
1561 
1562 	sc->sc_MACCtrl &= ~(MC_DuplexSelect | MC_RxFlowControlEnable |
1563 	    MC_TxFlowControlEnable);
1564 
1565 	if (((mii->mii_media_active & IFM_GMASK) & IFM_FDX) != 0)
1566 		sc->sc_MACCtrl |= MC_DuplexSelect;
1567 
1568 	if (((mii->mii_media_active & IFM_GMASK) & IFM_ETH_RXPAUSE) != 0)
1569 		sc->sc_MACCtrl |= MC_RxFlowControlEnable;
1570 	if (((mii->mii_media_active & IFM_GMASK) & IFM_ETH_TXPAUSE) != 0)
1571 		sc->sc_MACCtrl |= MC_TxFlowControlEnable;
1572 
1573 	CSR_WRITE_4(sc, STGE_MACCtrl, sc->sc_MACCtrl);
1574 }
1575 
1576 /*
1577  * sste_mii_bitbang_read: [mii bit-bang interface function]
1578  *
1579  *	Read the MII serial port for the MII bit-bang module.
1580  */
1581 uint32_t
1582 stge_mii_bitbang_read(struct device *self)
1583 {
1584 	struct stge_softc *sc = (void *) self;
1585 
1586 	return (CSR_READ_1(sc, STGE_PhyCtrl));
1587 }
1588 
1589 /*
1590  * stge_mii_bitbang_write: [mii big-bang interface function]
1591  *
1592  *	Write the MII serial port for the MII bit-bang module.
1593  */
1594 void
1595 stge_mii_bitbang_write(struct device *self, uint32_t val)
1596 {
1597 	struct stge_softc *sc = (void *) self;
1598 
1599 	CSR_WRITE_1(sc, STGE_PhyCtrl, val | sc->sc_PhyCtrl);
1600 }
1601 
1602 /*
1603  * stge_mediastatus:	[ifmedia interface function]
1604  *
1605  *	Get the current interface media status.
1606  */
1607 void
1608 stge_mediastatus(struct ifnet *ifp, struct ifmediareq *ifmr)
1609 {
1610 	struct stge_softc *sc = ifp->if_softc;
1611 
1612 	mii_pollstat(&sc->sc_mii);
1613 	ifmr->ifm_status = sc->sc_mii.mii_media_status;
1614 	ifmr->ifm_active = sc->sc_mii.mii_media_active;
1615 }
1616 
1617 /*
1618  * stge_mediachange:	[ifmedia interface function]
1619  *
1620  *	Set hardware to newly-selected media.
1621  */
1622 int
1623 stge_mediachange(struct ifnet *ifp)
1624 {
1625 	struct stge_softc *sc = ifp->if_softc;
1626 
1627 	if (ifp->if_flags & IFF_UP)
1628 		mii_mediachg(&sc->sc_mii);
1629 	return (0);
1630 }
1631