xref: /freebsd/sys/dev/altera/atse/if_atse.c (revision 5d3e7166)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2012, 2013 Bjoern A. Zeeb
5  * Copyright (c) 2014 Robert N. M. Watson
6  * Copyright (c) 2016-2017 Ruslan Bukin <br@bsdpad.com>
7  * All rights reserved.
8  *
9  * This software was developed by SRI International and the University of
10  * Cambridge Computer Laboratory under DARPA/AFRL contract (FA8750-11-C-0249)
11  * ("MRC2"), as part of the DARPA MRC research programme.
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  * 1. Redistributions of source code must retain the above copyright
17  *    notice, this list of conditions and the following disclaimer.
18  * 2. Redistributions in binary form must reproduce the above copyright
19  *    notice, this list of conditions and the following disclaimer in the
20  *    documentation and/or other materials provided with the distribution.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 /*
35  * Altera Triple-Speed Ethernet MegaCore, Function User Guide
36  * UG-01008-3.0, Software Version: 12.0, June 2012.
37  * Available at the time of writing at:
38  * http://www.altera.com/literature/ug/ug_ethernet.pdf
39  *
40  * We are using an Marvell E1111 (Alaska) PHY on the DE4.  See mii/e1000phy.c.
41  */
42 /*
43  * XXX-BZ NOTES:
44  * - ifOutBroadcastPkts are only counted if both ether dst and src are all-1s;
45  *   seems an IP core bug, they count ether broadcasts as multicast.  Is this
46  *   still the case?
47  * - figure out why the TX FIFO fill status and intr did not work as expected.
48  * - test 100Mbit/s and 10Mbit/s
49  * - blacklist the one special factory programmed ethernet address (for now
50  *   hardcoded, later from loader?)
51  * - resolve all XXX, left as reminders to shake out details later
52  * - Jumbo frame support
53  */
54 
55 #include <sys/cdefs.h>
56 __FBSDID("$FreeBSD$");
57 
58 #include "opt_device_polling.h"
59 
60 #include <sys/param.h>
61 #include <sys/systm.h>
62 #include <sys/kernel.h>
63 #include <sys/bus.h>
64 #include <sys/endian.h>
65 #include <sys/jail.h>
66 #include <sys/lock.h>
67 #include <sys/module.h>
68 #include <sys/mutex.h>
69 #include <sys/proc.h>
70 #include <sys/socket.h>
71 #include <sys/sockio.h>
72 #include <sys/types.h>
73 
74 #include <net/ethernet.h>
75 #include <net/if.h>
76 #include <net/if_var.h>
77 #include <net/if_dl.h>
78 #include <net/if_media.h>
79 #include <net/if_types.h>
80 #include <net/if_vlan_var.h>
81 
82 #include <net/bpf.h>
83 
84 #include <machine/bus.h>
85 #include <machine/resource.h>
86 #include <sys/rman.h>
87 
88 #include <dev/mii/mii.h>
89 #include <dev/mii/miivar.h>
90 
91 #include <dev/altera/atse/if_atsereg.h>
92 #include <dev/xdma/xdma.h>
93 
94 #define	RX_QUEUE_SIZE		4096
95 #define	TX_QUEUE_SIZE		4096
96 #define	NUM_RX_MBUF		512
97 #define	BUFRING_SIZE		8192
98 
99 #include <machine/cache.h>
100 
101 /* XXX once we'd do parallel attach, we need a global lock for this. */
102 #define	ATSE_ETHERNET_OPTION_BITS_UNDEF	0
103 #define	ATSE_ETHERNET_OPTION_BITS_READ	1
104 static int atse_ethernet_option_bits_flag = ATSE_ETHERNET_OPTION_BITS_UNDEF;
105 static uint8_t atse_ethernet_option_bits[ALTERA_ETHERNET_OPTION_BITS_LEN];
106 
107 /*
108  * Softc and critical resource locking.
109  */
110 #define	ATSE_LOCK(_sc)		mtx_lock(&(_sc)->atse_mtx)
111 #define	ATSE_UNLOCK(_sc)	mtx_unlock(&(_sc)->atse_mtx)
112 #define	ATSE_LOCK_ASSERT(_sc)	mtx_assert(&(_sc)->atse_mtx, MA_OWNED)
113 
114 #define ATSE_DEBUG
115 #undef ATSE_DEBUG
116 
117 #ifdef ATSE_DEBUG
118 #define	DPRINTF(format, ...)	printf(format, __VA_ARGS__)
119 #else
120 #define	DPRINTF(format, ...)
121 #endif
122 
123 /*
124  * Register space access macros.
125  */
126 static inline void
127 csr_write_4(struct atse_softc *sc, uint32_t reg, uint32_t val4,
128     const char *f, const int l)
129 {
130 
131 	val4 = htole32(val4);
132 	DPRINTF("[%s:%d] CSR W %s 0x%08x (0x%08x) = 0x%08x\n", f, l,
133 	    "atse_mem_res", reg, reg * 4, val4);
134 	bus_write_4(sc->atse_mem_res, reg * 4, val4);
135 }
136 
137 static inline uint32_t
138 csr_read_4(struct atse_softc *sc, uint32_t reg, const char *f, const int l)
139 {
140 	uint32_t val4;
141 
142 	val4 = le32toh(bus_read_4(sc->atse_mem_res, reg * 4));
143 	DPRINTF("[%s:%d] CSR R %s 0x%08x (0x%08x) = 0x%08x\n", f, l,
144 	    "atse_mem_res", reg, reg * 4, val4);
145 
146 	return (val4);
147 }
148 
149 /*
150  * See page 5-2 that it's all dword offsets and the MS 16 bits need to be zero
151  * on write and ignored on read.
152  */
153 static inline void
154 pxx_write_2(struct atse_softc *sc, bus_addr_t bmcr, uint32_t reg, uint16_t val,
155     const char *f, const int l, const char *s)
156 {
157 	uint32_t val4;
158 
159 	val4 = htole32(val & 0x0000ffff);
160 	DPRINTF("[%s:%d] %s W %s 0x%08x (0x%08jx) = 0x%08x\n", f, l, s,
161 	    "atse_mem_res", reg, (bmcr + reg) * 4, val4);
162 	bus_write_4(sc->atse_mem_res, (bmcr + reg) * 4, val4);
163 }
164 
165 static inline uint16_t
166 pxx_read_2(struct atse_softc *sc, bus_addr_t bmcr, uint32_t reg, const char *f,
167     const int l, const char *s)
168 {
169 	uint32_t val4;
170 	uint16_t val;
171 
172 	val4 = bus_read_4(sc->atse_mem_res, (bmcr + reg) * 4);
173 	val = le32toh(val4) & 0x0000ffff;
174 	DPRINTF("[%s:%d] %s R %s 0x%08x (0x%08jx) = 0x%04x\n", f, l, s,
175 	    "atse_mem_res", reg, (bmcr + reg) * 4, val);
176 
177 	return (val);
178 }
179 
180 #define	CSR_WRITE_4(sc, reg, val)	\
181 	csr_write_4((sc), (reg), (val), __func__, __LINE__)
182 #define	CSR_READ_4(sc, reg)		\
183 	csr_read_4((sc), (reg), __func__, __LINE__)
184 #define	PCS_WRITE_2(sc, reg, val)	\
185 	pxx_write_2((sc), sc->atse_bmcr0, (reg), (val), __func__, __LINE__, \
186 	    "PCS")
187 #define	PCS_READ_2(sc, reg)		\
188 	pxx_read_2((sc), sc->atse_bmcr0, (reg), __func__, __LINE__, "PCS")
189 #define	PHY_WRITE_2(sc, reg, val)	\
190 	pxx_write_2((sc), sc->atse_bmcr1, (reg), (val), __func__, __LINE__, \
191 	    "PHY")
192 #define	PHY_READ_2(sc, reg)		\
193 	pxx_read_2((sc), sc->atse_bmcr1, (reg), __func__, __LINE__, "PHY")
194 
195 static void atse_tick(void *);
196 static int atse_detach(device_t);
197 
198 static int
199 atse_rx_enqueue(struct atse_softc *sc, uint32_t n)
200 {
201 	struct mbuf *m;
202 	int i;
203 
204 	for (i = 0; i < n; i++) {
205 		m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
206 		if (m == NULL) {
207 			device_printf(sc->dev,
208 			    "%s: Can't alloc rx mbuf\n", __func__);
209 			return (-1);
210 		}
211 
212 		m->m_pkthdr.len = m->m_len = m->m_ext.ext_size;
213 		xdma_enqueue_mbuf(sc->xchan_rx, &m, 0, 4, 4, XDMA_DEV_TO_MEM);
214 	}
215 
216 	return (0);
217 }
218 
219 static int
220 atse_xdma_tx_intr(void *arg, xdma_transfer_status_t *status)
221 {
222 	xdma_transfer_status_t st;
223 	struct atse_softc *sc;
224 	if_t ifp;
225 	struct mbuf *m;
226 	int err;
227 
228 	sc = arg;
229 
230 	ATSE_LOCK(sc);
231 
232 	ifp = sc->atse_ifp;
233 
234 	for (;;) {
235 		err = xdma_dequeue_mbuf(sc->xchan_tx, &m, &st);
236 		if (err != 0) {
237 			break;
238 		}
239 
240 		if (st.error != 0) {
241 			if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
242 		}
243 
244 		m_freem(m);
245 		sc->txcount--;
246 	}
247 
248 	if_setdrvflagbits(ifp, 0, IFF_DRV_OACTIVE);
249 
250 	ATSE_UNLOCK(sc);
251 
252 	return (0);
253 }
254 
255 static int
256 atse_xdma_rx_intr(void *arg, xdma_transfer_status_t *status)
257 {
258 	xdma_transfer_status_t st;
259 	struct atse_softc *sc;
260 	if_t ifp;
261 	struct mbuf *m;
262 	int err;
263 	uint32_t cnt_processed;
264 
265 	sc = arg;
266 
267 	ATSE_LOCK(sc);
268 
269 	ifp = sc->atse_ifp;
270 
271 	cnt_processed = 0;
272 	for (;;) {
273 		err = xdma_dequeue_mbuf(sc->xchan_rx, &m, &st);
274 		if (err != 0) {
275 			break;
276 		}
277 		cnt_processed++;
278 
279 		if (st.error != 0) {
280 			if_inc_counter(ifp, IFCOUNTER_IERRORS, 1);
281 			m_freem(m);
282 			continue;
283 		}
284 
285 		m->m_pkthdr.len = m->m_len = st.transferred;
286 		m->m_pkthdr.rcvif = ifp;
287 		m_adj(m, ETHER_ALIGN);
288 		ATSE_UNLOCK(sc);
289 		if_input(ifp, m);
290 		ATSE_LOCK(sc);
291 	}
292 
293 	atse_rx_enqueue(sc, cnt_processed);
294 
295 	ATSE_UNLOCK(sc);
296 
297 	return (0);
298 }
299 
300 static int
301 atse_transmit_locked(if_t ifp)
302 {
303 	struct atse_softc *sc;
304 	struct mbuf *m;
305 	struct buf_ring *br;
306 	int error;
307 	int enq;
308 
309 	sc = if_getsoftc(ifp);
310 	br = sc->br;
311 
312 	enq = 0;
313 
314 	while ((m = drbr_peek(ifp, br)) != NULL) {
315 		error = xdma_enqueue_mbuf(sc->xchan_tx, &m, 0, 4, 4, XDMA_MEM_TO_DEV);
316 		if (error != 0) {
317 			/* No space in request queue available yet. */
318 			drbr_putback(ifp, br, m);
319 			break;
320 		}
321 
322 		drbr_advance(ifp, br);
323 
324 		sc->txcount++;
325 		enq++;
326 
327 		/* If anyone is interested give them a copy. */
328 		ETHER_BPF_MTAP(ifp, m);
329         }
330 
331 	if (enq > 0)
332 		xdma_queue_submit(sc->xchan_tx);
333 
334 	return (0);
335 }
336 
337 static int
338 atse_transmit(if_t ifp, struct mbuf *m)
339 {
340 	struct atse_softc *sc;
341 	struct buf_ring *br;
342 	int error;
343 
344 	sc = if_getsoftc(ifp);
345 	br = sc->br;
346 
347 	ATSE_LOCK(sc);
348 
349 	mtx_lock(&sc->br_mtx);
350 
351 	if ((if_getdrvflags(ifp) & (IFF_DRV_RUNNING | IFF_DRV_OACTIVE)) != IFF_DRV_RUNNING) {
352 		error = drbr_enqueue(ifp, sc->br, m);
353 		mtx_unlock(&sc->br_mtx);
354 		ATSE_UNLOCK(sc);
355 		return (error);
356 	}
357 
358 	if ((sc->atse_flags & ATSE_FLAGS_LINK) == 0) {
359 		error = drbr_enqueue(ifp, sc->br, m);
360 		mtx_unlock(&sc->br_mtx);
361 		ATSE_UNLOCK(sc);
362 		return (error);
363 	}
364 
365 	error = drbr_enqueue(ifp, br, m);
366 	if (error) {
367 		mtx_unlock(&sc->br_mtx);
368 		ATSE_UNLOCK(sc);
369 		return (error);
370 	}
371 	error = atse_transmit_locked(ifp);
372 
373 	mtx_unlock(&sc->br_mtx);
374 	ATSE_UNLOCK(sc);
375 
376 	return (error);
377 }
378 
379 static void
380 atse_qflush(if_t ifp)
381 {
382 	struct atse_softc *sc;
383 
384 	sc = if_getsoftc(ifp);
385 
386 	printf("%s\n", __func__);
387 }
388 
389 static int
390 atse_stop_locked(struct atse_softc *sc)
391 {
392 	uint32_t mask, val4;
393 	if_t ifp;
394 	int i;
395 
396 	ATSE_LOCK_ASSERT(sc);
397 
398 	callout_stop(&sc->atse_tick);
399 
400 	ifp = sc->atse_ifp;
401 	if_setdrvflagbits(ifp, 0, (IFF_DRV_RUNNING | IFF_DRV_OACTIVE));
402 
403 	/* Disable MAC transmit and receive datapath. */
404 	mask = BASE_CFG_COMMAND_CONFIG_TX_ENA|BASE_CFG_COMMAND_CONFIG_RX_ENA;
405 	val4 = CSR_READ_4(sc, BASE_CFG_COMMAND_CONFIG);
406 	val4 &= ~mask;
407 	CSR_WRITE_4(sc, BASE_CFG_COMMAND_CONFIG, val4);
408 
409 	/* Wait for bits to be cleared; i=100 is excessive. */
410 	for (i = 0; i < 100; i++) {
411 		val4 = CSR_READ_4(sc, BASE_CFG_COMMAND_CONFIG);
412 		if ((val4 & mask) == 0) {
413 			break;
414 		}
415 		DELAY(10);
416 	}
417 
418 	if ((val4 & mask) != 0) {
419 		device_printf(sc->atse_dev, "Disabling MAC TX/RX timed out.\n");
420 		/* Punt. */
421 	}
422 
423 	sc->atse_flags &= ~ATSE_FLAGS_LINK;
424 
425 	return (0);
426 }
427 
428 static u_int
429 atse_hash_maddr(void *arg, struct sockaddr_dl *sdl, u_int cnt)
430 {
431 	uint64_t *h = arg;
432 	uint8_t *addr, x, y;
433 	int i, j;
434 
435 	addr = LLADDR(sdl);
436 	x = 0;
437 	for (i = 0; i < ETHER_ADDR_LEN; i++) {
438 		y = addr[i] & 0x01;
439 		for (j = 1; j < 8; j++)
440 			y ^= (addr[i] >> j) & 0x01;
441 		x |= (y << i);
442 	}
443 	*h |= (1 << x);
444 
445 	return (1);
446 }
447 
448 static int
449 atse_rxfilter_locked(struct atse_softc *sc)
450 {
451 	if_t ifp;
452 	uint32_t val4;
453 	int i;
454 
455 	/* XXX-BZ can we find out if we have the MHASH synthesized? */
456 	val4 = CSR_READ_4(sc, BASE_CFG_COMMAND_CONFIG);
457 	/* For simplicity always hash full 48 bits of addresses. */
458 	if ((val4 & BASE_CFG_COMMAND_CONFIG_MHASH_SEL) != 0)
459 		val4 &= ~BASE_CFG_COMMAND_CONFIG_MHASH_SEL;
460 
461 	ifp = sc->atse_ifp;
462 	if (if_getflags(ifp) & IFF_PROMISC) {
463 		val4 |= BASE_CFG_COMMAND_CONFIG_PROMIS_EN;
464 	} else {
465 		val4 &= ~BASE_CFG_COMMAND_CONFIG_PROMIS_EN;
466 	}
467 
468 	CSR_WRITE_4(sc, BASE_CFG_COMMAND_CONFIG, val4);
469 
470 	if (if_getflags(ifp) & IFF_ALLMULTI) {
471 		/* Accept all multicast addresses. */
472 		for (i = 0; i <= MHASH_LEN; i++)
473 			CSR_WRITE_4(sc, MHASH_START + i, 0x1);
474 	} else {
475 		/*
476 		 * Can hold MHASH_LEN entries.
477 		 * XXX-BZ bitstring.h would be more general.
478 		 */
479 		uint64_t h;
480 
481 		/*
482 		 * Re-build and re-program hash table.  First build the
483 		 * bit-field "yes" or "no" for each slot per address, then
484 		 * do all the programming afterwards.
485 		 */
486 		h = 0;
487 		(void)if_foreach_llmaddr(ifp, atse_hash_maddr, &h);
488 		for (i = 0; i <= MHASH_LEN; i++) {
489 			CSR_WRITE_4(sc, MHASH_START + i,
490 			    (h & (1 << i)) ? 0x01 : 0x00);
491 		}
492 	}
493 
494 	return (0);
495 }
496 
497 static int
498 atse_ethernet_option_bits_read_fdt(device_t dev)
499 {
500 	struct resource *res;
501 	device_t fdev;
502 	int i, rid;
503 
504 	if (atse_ethernet_option_bits_flag & ATSE_ETHERNET_OPTION_BITS_READ) {
505 		return (0);
506 	}
507 
508 	fdev = device_find_child(device_get_parent(dev), "cfi", 0);
509 	if (fdev == NULL) {
510 		return (ENOENT);
511 	}
512 
513 	rid = 0;
514 	res = bus_alloc_resource_any(fdev, SYS_RES_MEMORY, &rid,
515 	    RF_ACTIVE | RF_SHAREABLE);
516 	if (res == NULL) {
517 		return (ENXIO);
518 	}
519 
520 	for (i = 0; i < ALTERA_ETHERNET_OPTION_BITS_LEN; i++) {
521 		atse_ethernet_option_bits[i] = bus_read_1(res,
522 		    ALTERA_ETHERNET_OPTION_BITS_OFF + i);
523 	}
524 
525 	bus_release_resource(fdev, SYS_RES_MEMORY, rid, res);
526 	atse_ethernet_option_bits_flag |= ATSE_ETHERNET_OPTION_BITS_READ;
527 
528 	return (0);
529 }
530 
531 static int
532 atse_ethernet_option_bits_read(device_t dev)
533 {
534 	int error;
535 
536 	error = atse_ethernet_option_bits_read_fdt(dev);
537 	if (error == 0)
538 		return (0);
539 
540 	device_printf(dev, "Cannot read Ethernet addresses from flash.\n");
541 
542 	return (error);
543 }
544 
545 static int
546 atse_get_eth_address(struct atse_softc *sc)
547 {
548 	unsigned long hostid;
549 	uint32_t val4;
550 	int unit;
551 
552 	/*
553 	 * Make sure to only ever do this once.  Otherwise a reset would
554 	 * possibly change our ethernet address, which is not good at all.
555 	 */
556 	if (sc->atse_eth_addr[0] != 0x00 || sc->atse_eth_addr[1] != 0x00 ||
557 	    sc->atse_eth_addr[2] != 0x00) {
558 		return (0);
559 	}
560 
561 	if ((atse_ethernet_option_bits_flag &
562 	    ATSE_ETHERNET_OPTION_BITS_READ) == 0) {
563 		goto get_random;
564 	}
565 
566 	val4 = atse_ethernet_option_bits[0] << 24;
567 	val4 |= atse_ethernet_option_bits[1] << 16;
568 	val4 |= atse_ethernet_option_bits[2] << 8;
569 	val4 |= atse_ethernet_option_bits[3];
570 	/* They chose "safe". */
571 	if (val4 != le32toh(0x00005afe)) {
572 		device_printf(sc->atse_dev, "Magic '5afe' is not safe: 0x%08x. "
573 		    "Falling back to random numbers for hardware address.\n",
574 		     val4);
575 		goto get_random;
576 	}
577 
578 	sc->atse_eth_addr[0] = atse_ethernet_option_bits[4];
579 	sc->atse_eth_addr[1] = atse_ethernet_option_bits[5];
580 	sc->atse_eth_addr[2] = atse_ethernet_option_bits[6];
581 	sc->atse_eth_addr[3] = atse_ethernet_option_bits[7];
582 	sc->atse_eth_addr[4] = atse_ethernet_option_bits[8];
583 	sc->atse_eth_addr[5] = atse_ethernet_option_bits[9];
584 
585 	/* Handle factory default ethernet addresss: 00:07:ed:ff:ed:15 */
586 	if (sc->atse_eth_addr[0] == 0x00 && sc->atse_eth_addr[1] == 0x07 &&
587 	    sc->atse_eth_addr[2] == 0xed && sc->atse_eth_addr[3] == 0xff &&
588 	    sc->atse_eth_addr[4] == 0xed && sc->atse_eth_addr[5] == 0x15) {
589 		device_printf(sc->atse_dev, "Factory programmed Ethernet "
590 		    "hardware address blacklisted.  Falling back to random "
591 		    "address to avoid collisions.\n");
592 		device_printf(sc->atse_dev, "Please re-program your flash.\n");
593 		goto get_random;
594 	}
595 
596 	if (sc->atse_eth_addr[0] == 0x00 && sc->atse_eth_addr[1] == 0x00 &&
597 	    sc->atse_eth_addr[2] == 0x00 && sc->atse_eth_addr[3] == 0x00 &&
598 	    sc->atse_eth_addr[4] == 0x00 && sc->atse_eth_addr[5] == 0x00) {
599 		device_printf(sc->atse_dev, "All zero's Ethernet hardware "
600 		    "address blacklisted.  Falling back to random address.\n");
601 		device_printf(sc->atse_dev, "Please re-program your flash.\n");
602 		goto get_random;
603 	}
604 
605 	if (ETHER_IS_MULTICAST(sc->atse_eth_addr)) {
606 		device_printf(sc->atse_dev, "Multicast Ethernet hardware "
607 		    "address blacklisted.  Falling back to random address.\n");
608 		device_printf(sc->atse_dev, "Please re-program your flash.\n");
609 		goto get_random;
610 	}
611 
612 	/*
613 	 * If we find an Altera prefixed address with a 0x0 ending
614 	 * adjust by device unit.  If not and this is not the first
615 	 * Ethernet, go to random.
616 	 */
617 	unit = device_get_unit(sc->atse_dev);
618 	if (unit == 0x00) {
619 		return (0);
620 	}
621 
622 	if (unit > 0x0f) {
623 		device_printf(sc->atse_dev, "We do not support Ethernet "
624 		    "addresses for more than 16 MACs. Falling back to "
625 		    "random hadware address.\n");
626 		goto get_random;
627 	}
628 	if ((sc->atse_eth_addr[0] & ~0x2) != 0 ||
629 	    sc->atse_eth_addr[1] != 0x07 || sc->atse_eth_addr[2] != 0xed ||
630 	    (sc->atse_eth_addr[5] & 0x0f) != 0x0) {
631 		device_printf(sc->atse_dev, "Ethernet address not meeting our "
632 		    "multi-MAC standards. Falling back to random hadware "
633 		    "address.\n");
634 		goto get_random;
635 	}
636 	sc->atse_eth_addr[5] |= (unit & 0x0f);
637 
638 	return (0);
639 
640 get_random:
641 	/*
642 	 * Fall back to random code we also use on bridge(4).
643 	 */
644 	getcredhostid(curthread->td_ucred, &hostid);
645 	if (hostid == 0) {
646 		arc4rand(sc->atse_eth_addr, ETHER_ADDR_LEN, 1);
647 		sc->atse_eth_addr[0] &= ~1;/* clear multicast bit */
648 		sc->atse_eth_addr[0] |= 2; /* set the LAA bit */
649 	} else {
650 		sc->atse_eth_addr[0] = 0x2;
651 		sc->atse_eth_addr[1] = (hostid >> 24)	& 0xff;
652 		sc->atse_eth_addr[2] = (hostid >> 16)	& 0xff;
653 		sc->atse_eth_addr[3] = (hostid >> 8 )	& 0xff;
654 		sc->atse_eth_addr[4] = hostid		& 0xff;
655 		sc->atse_eth_addr[5] = sc->atse_unit	& 0xff;
656 	}
657 
658 	return (0);
659 }
660 
661 static int
662 atse_set_eth_address(struct atse_softc *sc, int n)
663 {
664 	uint32_t v0, v1;
665 
666 	v0 = (sc->atse_eth_addr[3] << 24) | (sc->atse_eth_addr[2] << 16) |
667 	    (sc->atse_eth_addr[1] << 8) | sc->atse_eth_addr[0];
668 	v1 = (sc->atse_eth_addr[5] << 8) | sc->atse_eth_addr[4];
669 
670 	if (n & ATSE_ETH_ADDR_DEF) {
671 		CSR_WRITE_4(sc, BASE_CFG_MAC_0, v0);
672 		CSR_WRITE_4(sc, BASE_CFG_MAC_1, v1);
673 	}
674 	if (n & ATSE_ETH_ADDR_SUPP1) {
675 		CSR_WRITE_4(sc, SUPPL_ADDR_SMAC_0_0, v0);
676 		CSR_WRITE_4(sc, SUPPL_ADDR_SMAC_0_1, v1);
677 	}
678 	if (n & ATSE_ETH_ADDR_SUPP2) {
679 		CSR_WRITE_4(sc, SUPPL_ADDR_SMAC_1_0, v0);
680 		CSR_WRITE_4(sc, SUPPL_ADDR_SMAC_1_1, v1);
681 	}
682 	if (n & ATSE_ETH_ADDR_SUPP3) {
683 		CSR_WRITE_4(sc, SUPPL_ADDR_SMAC_2_0, v0);
684 		CSR_WRITE_4(sc, SUPPL_ADDR_SMAC_2_1, v1);
685 	}
686 	if (n & ATSE_ETH_ADDR_SUPP4) {
687 		CSR_WRITE_4(sc, SUPPL_ADDR_SMAC_3_0, v0);
688 		CSR_WRITE_4(sc, SUPPL_ADDR_SMAC_3_1, v1);
689 	}
690 
691 	return (0);
692 }
693 
694 static int
695 atse_reset(struct atse_softc *sc)
696 {
697 	uint32_t val4, mask;
698 	uint16_t val;
699 	int i;
700 
701 	/* 1. External PHY Initialization using MDIO. */
702 	/*
703 	 * We select the right MDIO space in atse_attach() and let MII do
704 	 * anything else.
705 	 */
706 
707 	/* 2. PCS Configuration Register Initialization. */
708 	/* a. Set auto negotiation link timer to 1.6ms for SGMII. */
709 	PCS_WRITE_2(sc, PCS_EXT_LINK_TIMER_0, 0x0D40);
710 	PCS_WRITE_2(sc, PCS_EXT_LINK_TIMER_1, 0x0003);
711 
712 	/* b. Configure SGMII. */
713 	val = PCS_EXT_IF_MODE_SGMII_ENA|PCS_EXT_IF_MODE_USE_SGMII_AN;
714 	PCS_WRITE_2(sc, PCS_EXT_IF_MODE, val);
715 
716 	/* c. Enable auto negotiation. */
717 	/* Ignore Bits 6,8,13; should be set,set,unset. */
718 	val = PCS_READ_2(sc, PCS_CONTROL);
719 	val &= ~(PCS_CONTROL_ISOLATE|PCS_CONTROL_POWERDOWN);
720 	val &= ~PCS_CONTROL_LOOPBACK;		/* Make this a -link1 option? */
721 	val |= PCS_CONTROL_AUTO_NEGOTIATION_ENABLE;
722 	PCS_WRITE_2(sc, PCS_CONTROL, val);
723 
724 	/* d. PCS reset. */
725 	val = PCS_READ_2(sc, PCS_CONTROL);
726 	val |= PCS_CONTROL_RESET;
727 	PCS_WRITE_2(sc, PCS_CONTROL, val);
728 
729 	/* Wait for reset bit to clear; i=100 is excessive. */
730 	for (i = 0; i < 100; i++) {
731 		val = PCS_READ_2(sc, PCS_CONTROL);
732 		if ((val & PCS_CONTROL_RESET) == 0) {
733 			break;
734 		}
735 		DELAY(10);
736 	}
737 
738 	if ((val & PCS_CONTROL_RESET) != 0) {
739 		device_printf(sc->atse_dev, "PCS reset timed out.\n");
740 		return (ENXIO);
741 	}
742 
743 	/* 3. MAC Configuration Register Initialization. */
744 	/* a. Disable MAC transmit and receive datapath. */
745 	mask = BASE_CFG_COMMAND_CONFIG_TX_ENA|BASE_CFG_COMMAND_CONFIG_RX_ENA;
746 	val4 = CSR_READ_4(sc, BASE_CFG_COMMAND_CONFIG);
747 	val4 &= ~mask;
748 	/* Samples in the manual do have the SW_RESET bit set here, why? */
749 	CSR_WRITE_4(sc, BASE_CFG_COMMAND_CONFIG, val4);
750 	/* Wait for bits to be cleared; i=100 is excessive. */
751 	for (i = 0; i < 100; i++) {
752 		val4 = CSR_READ_4(sc, BASE_CFG_COMMAND_CONFIG);
753 		if ((val4 & mask) == 0) {
754 			break;
755 		}
756 		DELAY(10);
757 	}
758 	if ((val4 & mask) != 0) {
759 		device_printf(sc->atse_dev, "Disabling MAC TX/RX timed out.\n");
760 		return (ENXIO);
761 	}
762 	/* b. MAC FIFO configuration. */
763 	CSR_WRITE_4(sc, BASE_CFG_TX_SECTION_EMPTY, FIFO_DEPTH_TX - 16);
764 	CSR_WRITE_4(sc, BASE_CFG_TX_ALMOST_FULL, 3);
765 	CSR_WRITE_4(sc, BASE_CFG_TX_ALMOST_EMPTY, 8);
766 	CSR_WRITE_4(sc, BASE_CFG_RX_SECTION_EMPTY, FIFO_DEPTH_RX - 16);
767 	CSR_WRITE_4(sc, BASE_CFG_RX_ALMOST_FULL, 8);
768 	CSR_WRITE_4(sc, BASE_CFG_RX_ALMOST_EMPTY, 8);
769 #if 0
770 	CSR_WRITE_4(sc, BASE_CFG_TX_SECTION_FULL, 16);
771 	CSR_WRITE_4(sc, BASE_CFG_RX_SECTION_FULL, 16);
772 #else
773 	/* For store-and-forward mode, set this threshold to 0. */
774 	CSR_WRITE_4(sc, BASE_CFG_TX_SECTION_FULL, 0);
775 	CSR_WRITE_4(sc, BASE_CFG_RX_SECTION_FULL, 0);
776 #endif
777 	/* c. MAC address configuration. */
778 	/* Also intialize supplementary addresses to our primary one. */
779 	/* XXX-BZ FreeBSD really needs to grow and API for using these. */
780 	atse_get_eth_address(sc);
781 	atse_set_eth_address(sc, ATSE_ETH_ADDR_ALL);
782 
783 	/* d. MAC function configuration. */
784 	CSR_WRITE_4(sc, BASE_CFG_FRM_LENGTH, 1518);	/* Default. */
785 	CSR_WRITE_4(sc, BASE_CFG_TX_IPG_LENGTH, 12);
786 	CSR_WRITE_4(sc, BASE_CFG_PAUSE_QUANT, 0xFFFF);
787 
788 	val4 = CSR_READ_4(sc, BASE_CFG_COMMAND_CONFIG);
789 	/*
790 	 * If 1000BASE-X/SGMII PCS is initialized, set the ETH_SPEED (bit 3)
791 	 * and ENA_10 (bit 25) in command_config register to 0.  If half duplex
792 	 * is reported in the PHY/PCS status register, set the HD_ENA (bit 10)
793 	 * to 1 in command_config register.
794 	 * BZ: We shoot for 1000 instead.
795 	 */
796 #if 0
797 	val4 |= BASE_CFG_COMMAND_CONFIG_ETH_SPEED;
798 #else
799 	val4 &= ~BASE_CFG_COMMAND_CONFIG_ETH_SPEED;
800 #endif
801 	val4 &= ~BASE_CFG_COMMAND_CONFIG_ENA_10;
802 #if 0
803 	/*
804 	 * We do not want to set this, otherwise, we could not even send
805 	 * random raw ethernet frames for various other research.  By default
806 	 * FreeBSD will use the right ether source address.
807 	 */
808 	val4 |= BASE_CFG_COMMAND_CONFIG_TX_ADDR_INS;
809 #endif
810 	val4 |= BASE_CFG_COMMAND_CONFIG_PAD_EN;
811 	val4 &= ~BASE_CFG_COMMAND_CONFIG_CRC_FWD;
812 #if 0
813 	val4 |= BASE_CFG_COMMAND_CONFIG_CNTL_FRM_ENA;
814 #endif
815 #if 1
816 	val4 |= BASE_CFG_COMMAND_CONFIG_RX_ERR_DISC;
817 #endif
818 	val &= ~BASE_CFG_COMMAND_CONFIG_LOOP_ENA;		/* link0? */
819 	CSR_WRITE_4(sc, BASE_CFG_COMMAND_CONFIG, val4);
820 
821 	/*
822 	 * Make sure we do not enable 32bit alignment;  FreeBSD cannot
823 	 * cope with the additional padding (though we should!?).
824 	 * Also make sure we get the CRC appended.
825 	 */
826 	val4 = CSR_READ_4(sc, TX_CMD_STAT);
827 	val4 &= ~(TX_CMD_STAT_OMIT_CRC|TX_CMD_STAT_TX_SHIFT16);
828 	CSR_WRITE_4(sc, TX_CMD_STAT, val4);
829 
830 	val4 = CSR_READ_4(sc, RX_CMD_STAT);
831 	val4 &= ~RX_CMD_STAT_RX_SHIFT16;
832 	val4 |= RX_CMD_STAT_RX_SHIFT16;
833 	CSR_WRITE_4(sc, RX_CMD_STAT, val4);
834 
835 	/* e. Reset MAC. */
836 	val4 = CSR_READ_4(sc, BASE_CFG_COMMAND_CONFIG);
837 	val4 |= BASE_CFG_COMMAND_CONFIG_SW_RESET;
838 	CSR_WRITE_4(sc, BASE_CFG_COMMAND_CONFIG, val4);
839 	/* Wait for bits to be cleared; i=100 is excessive. */
840 	for (i = 0; i < 100; i++) {
841 		val4 = CSR_READ_4(sc, BASE_CFG_COMMAND_CONFIG);
842 		if ((val4 & BASE_CFG_COMMAND_CONFIG_SW_RESET) == 0) {
843 			break;
844 		}
845 		DELAY(10);
846 	}
847 	if ((val4 & BASE_CFG_COMMAND_CONFIG_SW_RESET) != 0) {
848 		device_printf(sc->atse_dev, "MAC reset timed out.\n");
849 		return (ENXIO);
850 	}
851 
852 	/* f. Enable MAC transmit and receive datapath. */
853 	mask = BASE_CFG_COMMAND_CONFIG_TX_ENA|BASE_CFG_COMMAND_CONFIG_RX_ENA;
854 	val4 = CSR_READ_4(sc, BASE_CFG_COMMAND_CONFIG);
855 	val4 |= mask;
856 	CSR_WRITE_4(sc, BASE_CFG_COMMAND_CONFIG, val4);
857 	/* Wait for bits to be cleared; i=100 is excessive. */
858 	for (i = 0; i < 100; i++) {
859 		val4 = CSR_READ_4(sc, BASE_CFG_COMMAND_CONFIG);
860 		if ((val4 & mask) == mask) {
861 			break;
862 		}
863 		DELAY(10);
864 	}
865 	if ((val4 & mask) != mask) {
866 		device_printf(sc->atse_dev, "Enabling MAC TX/RX timed out.\n");
867 		return (ENXIO);
868 	}
869 
870 	return (0);
871 }
872 
873 static void
874 atse_init_locked(struct atse_softc *sc)
875 {
876 	if_t ifp;
877 	struct mii_data *mii;
878 	uint8_t *eaddr;
879 
880 	ATSE_LOCK_ASSERT(sc);
881 	ifp = sc->atse_ifp;
882 
883 	if ((if_getdrvflags(ifp) & IFF_DRV_RUNNING) != 0) {
884 		return;
885 	}
886 
887 	/*
888 	 * Must update the ether address if changed.  Given we do not handle
889 	 * in atse_ioctl() but it's in the general framework, just always
890 	 * do it here before atse_reset().
891 	 */
892 	eaddr = if_getlladdr(sc->atse_ifp);
893 	bcopy(eaddr, &sc->atse_eth_addr, ETHER_ADDR_LEN);
894 
895 	/* Make things frind to halt, cleanup, ... */
896 	atse_stop_locked(sc);
897 
898 	atse_reset(sc);
899 
900 	/* ... and fire up the engine again. */
901 	atse_rxfilter_locked(sc);
902 
903 	sc->atse_flags &= ATSE_FLAGS_LINK;	/* Preserve. */
904 
905 	mii = device_get_softc(sc->atse_miibus);
906 
907 	sc->atse_flags &= ~ATSE_FLAGS_LINK;
908 	mii_mediachg(mii);
909 
910 	if_setdrvflagbits(ifp, IFF_DRV_RUNNING, 0);
911 	if_setdrvflagbits(ifp, 0, IFF_DRV_OACTIVE);
912 
913 	callout_reset(&sc->atse_tick, hz, atse_tick, sc);
914 }
915 
916 static void
917 atse_init(void *xsc)
918 {
919 	struct atse_softc *sc;
920 
921 	/*
922 	 * XXXRW: There is some argument that we should immediately do RX
923 	 * processing after enabling interrupts, or one may not fire if there
924 	 * are buffered packets.
925 	 */
926 	sc = (struct atse_softc *)xsc;
927 	ATSE_LOCK(sc);
928 	atse_init_locked(sc);
929 	ATSE_UNLOCK(sc);
930 }
931 
932 static int
933 atse_ioctl(if_t ifp, u_long command, caddr_t data)
934 {
935 	struct atse_softc *sc;
936 	struct ifreq *ifr;
937 	int error, mask;
938 
939 	error = 0;
940 	sc = if_getsoftc(ifp);
941 	ifr = (struct ifreq *)data;
942 
943 	switch (command) {
944 	case SIOCSIFFLAGS:
945 		ATSE_LOCK(sc);
946 		if (if_getflags(ifp) & IFF_UP) {
947 			if ((if_getdrvflags(ifp) & IFF_DRV_RUNNING) != 0 &&
948 			    ((if_getflags(ifp) ^ sc->atse_if_flags) &
949 			    (IFF_PROMISC | IFF_ALLMULTI)) != 0)
950 				atse_rxfilter_locked(sc);
951 			else
952 				atse_init_locked(sc);
953 		} else if (if_getdrvflags(ifp) & IFF_DRV_RUNNING)
954 			atse_stop_locked(sc);
955 		sc->atse_if_flags = if_getflags(ifp);
956 		ATSE_UNLOCK(sc);
957 		break;
958 	case SIOCSIFCAP:
959 		ATSE_LOCK(sc);
960 		mask = ifr->ifr_reqcap ^ if_getcapenable(ifp);
961 		ATSE_UNLOCK(sc);
962 		break;
963 	case SIOCADDMULTI:
964 	case SIOCDELMULTI:
965 		ATSE_LOCK(sc);
966 		atse_rxfilter_locked(sc);
967 		ATSE_UNLOCK(sc);
968 		break;
969 	case SIOCGIFMEDIA:
970 	case SIOCSIFMEDIA:
971 	{
972 		struct mii_data *mii;
973 		struct ifreq *ifr;
974 
975 		mii = device_get_softc(sc->atse_miibus);
976 		ifr = (struct ifreq *)data;
977 		error = ifmedia_ioctl(ifp, ifr, &mii->mii_media, command);
978 		break;
979 	}
980 	default:
981 		error = ether_ioctl(ifp, command, data);
982 		break;
983 	}
984 
985 	return (error);
986 }
987 
988 static void
989 atse_tick(void *xsc)
990 {
991 	struct atse_softc *sc;
992 	struct mii_data *mii;
993 	if_t ifp;
994 
995 	sc = (struct atse_softc *)xsc;
996 	ATSE_LOCK_ASSERT(sc);
997 	ifp = sc->atse_ifp;
998 
999 	mii = device_get_softc(sc->atse_miibus);
1000 	mii_tick(mii);
1001 	if ((sc->atse_flags & ATSE_FLAGS_LINK) == 0) {
1002 		atse_miibus_statchg(sc->atse_dev);
1003 	}
1004 
1005 	callout_reset(&sc->atse_tick, hz, atse_tick, sc);
1006 }
1007 
1008 /*
1009  * Set media options.
1010  */
1011 static int
1012 atse_ifmedia_upd(if_t ifp)
1013 {
1014 	struct atse_softc *sc;
1015 	struct mii_data *mii;
1016 	struct mii_softc *miisc;
1017 	int error;
1018 
1019 	sc = if_getsoftc(ifp);
1020 
1021 	ATSE_LOCK(sc);
1022 	mii = device_get_softc(sc->atse_miibus);
1023 	LIST_FOREACH(miisc, &mii->mii_phys, mii_list) {
1024 		PHY_RESET(miisc);
1025 	}
1026 	error = mii_mediachg(mii);
1027 	ATSE_UNLOCK(sc);
1028 
1029 	return (error);
1030 }
1031 
1032 /*
1033  * Report current media status.
1034  */
1035 static void
1036 atse_ifmedia_sts(if_t ifp, struct ifmediareq *ifmr)
1037 {
1038 	struct atse_softc *sc;
1039 	struct mii_data *mii;
1040 
1041 	sc = if_getsoftc(ifp);
1042 
1043 	ATSE_LOCK(sc);
1044 	mii = device_get_softc(sc->atse_miibus);
1045 	mii_pollstat(mii);
1046 	ifmr->ifm_active = mii->mii_media_active;
1047 	ifmr->ifm_status = mii->mii_media_status;
1048 	ATSE_UNLOCK(sc);
1049 }
1050 
1051 static struct atse_mac_stats_regs {
1052 	const char *name;
1053 	const char *descr;	/* Mostly copied from Altera datasheet. */
1054 } atse_mac_stats_regs[] = {
1055 	[0x1a] =
1056 	{ "aFramesTransmittedOK",
1057 	    "The number of frames that are successfully transmitted including "
1058 	    "the pause frames." },
1059 	{ "aFramesReceivedOK",
1060 	    "The number of frames that are successfully received including the "
1061 	    "pause frames." },
1062 	{ "aFrameCheckSequenceErrors",
1063 	    "The number of receive frames with CRC error." },
1064 	{ "aAlignmentErrors",
1065 	    "The number of receive frames with alignment error." },
1066 	{ "aOctetsTransmittedOK",
1067 	    "The lower 32 bits of the number of data and padding octets that "
1068 	    "are successfully transmitted." },
1069 	{ "aOctetsReceivedOK",
1070 	    "The lower 32 bits of the number of data and padding octets that "
1071 	    " are successfully received." },
1072 	{ "aTxPAUSEMACCtrlFrames",
1073 	    "The number of pause frames transmitted." },
1074 	{ "aRxPAUSEMACCtrlFrames",
1075 	    "The number received pause frames received." },
1076 	{ "ifInErrors",
1077 	    "The number of errored frames received." },
1078 	{ "ifOutErrors",
1079 	    "The number of transmit frames with either a FIFO overflow error, "
1080 	    "a FIFO underflow error, or a error defined by the user "
1081 	    "application." },
1082 	{ "ifInUcastPkts",
1083 	    "The number of valid unicast frames received." },
1084 	{ "ifInMulticastPkts",
1085 	    "The number of valid multicast frames received. The count does "
1086 	    "not include pause frames." },
1087 	{ "ifInBroadcastPkts",
1088 	    "The number of valid broadcast frames received." },
1089 	{ "ifOutDiscards",
1090 	    "This statistics counter is not in use.  The MAC function does not "
1091 	    "discard frames that are written to the FIFO buffer by the user "
1092 	    "application." },
1093 	{ "ifOutUcastPkts",
1094 	    "The number of valid unicast frames transmitted." },
1095 	{ "ifOutMulticastPkts",
1096 	    "The number of valid multicast frames transmitted, excluding pause "
1097 	    "frames." },
1098 	{ "ifOutBroadcastPkts",
1099 	    "The number of valid broadcast frames transmitted." },
1100 	{ "etherStatsDropEvents",
1101 	    "The number of frames that are dropped due to MAC internal errors "
1102 	    "when FIFO buffer overflow persists." },
1103 	{ "etherStatsOctets",
1104 	    "The lower 32 bits of the total number of octets received. This "
1105 	    "count includes both good and errored frames." },
1106 	{ "etherStatsPkts",
1107 	    "The total number of good and errored frames received." },
1108 	{ "etherStatsUndersizePkts",
1109 	    "The number of frames received with length less than 64 bytes. "
1110 	    "This count does not include errored frames." },
1111 	{ "etherStatsOversizePkts",
1112 	    "The number of frames received that are longer than the value "
1113 	    "configured in the frm_length register. This count does not "
1114 	    "include errored frames." },
1115 	{ "etherStatsPkts64Octets",
1116 	    "The number of 64-byte frames received. This count includes good "
1117 	    "and errored frames." },
1118 	{ "etherStatsPkts65to127Octets",
1119 	    "The number of received good and errored frames between the length "
1120 	    "of 65 and 127 bytes." },
1121 	{ "etherStatsPkts128to255Octets",
1122 	    "The number of received good and errored frames between the length "
1123 	    "of 128 and 255 bytes." },
1124 	{ "etherStatsPkts256to511Octets",
1125 	    "The number of received good and errored frames between the length "
1126 	    "of 256 and 511 bytes." },
1127 	{ "etherStatsPkts512to1023Octets",
1128 	    "The number of received good and errored frames between the length "
1129 	    "of 512 and 1023 bytes." },
1130 	{ "etherStatsPkts1024to1518Octets",
1131 	    "The number of received good and errored frames between the length "
1132 	    "of 1024 and 1518 bytes." },
1133 	{ "etherStatsPkts1519toXOctets",
1134 	    "The number of received good and errored frames between the length "
1135 	    "of 1519 and the maximum frame length configured in the frm_length "
1136 	    "register." },
1137 	{ "etherStatsJabbers",
1138 	    "Too long frames with CRC error." },
1139 	{ "etherStatsFragments",
1140 	    "Too short frames with CRC error." },
1141 	/* 0x39 unused, 0x3a/b non-stats. */
1142 	[0x3c] =
1143 	/* Extended Statistics Counters */
1144 	{ "msb_aOctetsTransmittedOK",
1145 	    "Upper 32 bits of the number of data and padding octets that are "
1146 	    "successfully transmitted." },
1147 	{ "msb_aOctetsReceivedOK",
1148 	    "Upper 32 bits of the number of data and padding octets that are "
1149 	    "successfully received." },
1150 	{ "msb_etherStatsOctets",
1151 	    "Upper 32 bits of the total number of octets received. This count "
1152 	    "includes both good and errored frames." }
1153 };
1154 
1155 static int
1156 sysctl_atse_mac_stats_proc(SYSCTL_HANDLER_ARGS)
1157 {
1158 	struct atse_softc *sc;
1159 	int error, offset, s;
1160 
1161 	sc = arg1;
1162 	offset = arg2;
1163 
1164 	s = CSR_READ_4(sc, offset);
1165 	error = sysctl_handle_int(oidp, &s, 0, req);
1166 	if (error || !req->newptr) {
1167 		return (error);
1168 	}
1169 
1170 	return (0);
1171 }
1172 
1173 static struct atse_rx_err_stats_regs {
1174 	const char *name;
1175 	const char *descr;
1176 } atse_rx_err_stats_regs[] = {
1177 #define	ATSE_RX_ERR_FIFO_THRES_EOP	0 /* FIFO threshold reached, on EOP. */
1178 #define	ATSE_RX_ERR_ELEN		1 /* Frame/payload length not valid. */
1179 #define	ATSE_RX_ERR_CRC32		2 /* CRC-32 error. */
1180 #define	ATSE_RX_ERR_FIFO_THRES_TRUNC	3 /* FIFO thresh., truncated frame. */
1181 #define	ATSE_RX_ERR_4			4 /* ? */
1182 #define	ATSE_RX_ERR_5			5 /* / */
1183 
1184 	{ "rx_err_fifo_thres_eop",
1185 	    "FIFO threshold reached, reported on EOP." },
1186 	{ "rx_err_fifo_elen",
1187 	    "Frame or payload length not valid." },
1188 	{ "rx_err_fifo_crc32",
1189 	    "CRC-32 error." },
1190 	{ "rx_err_fifo_thres_trunc",
1191 	    "FIFO threshold reached, truncated frame" },
1192 	{ "rx_err_4",
1193 	    "?" },
1194 	{ "rx_err_5",
1195 	    "?" },
1196 };
1197 
1198 static int
1199 sysctl_atse_rx_err_stats_proc(SYSCTL_HANDLER_ARGS)
1200 {
1201 	struct atse_softc *sc;
1202 	int error, offset, s;
1203 
1204 	sc = arg1;
1205 	offset = arg2;
1206 
1207 	s = sc->atse_rx_err[offset];
1208 	error = sysctl_handle_int(oidp, &s, 0, req);
1209 	if (error || !req->newptr) {
1210 		return (error);
1211 	}
1212 
1213 	return (0);
1214 }
1215 
1216 static void
1217 atse_sysctl_stats_attach(device_t dev)
1218 {
1219 	struct sysctl_ctx_list *sctx;
1220 	struct sysctl_oid *soid;
1221 	struct atse_softc *sc;
1222 	int i;
1223 
1224 	sc = device_get_softc(dev);
1225 	sctx = device_get_sysctl_ctx(dev);
1226 	soid = device_get_sysctl_tree(dev);
1227 
1228 	/* MAC statistics. */
1229 	for (i = 0; i < nitems(atse_mac_stats_regs); i++) {
1230 		if (atse_mac_stats_regs[i].name == NULL ||
1231 		    atse_mac_stats_regs[i].descr == NULL) {
1232 			continue;
1233 		}
1234 
1235 		SYSCTL_ADD_PROC(sctx, SYSCTL_CHILDREN(soid), OID_AUTO,
1236 		    atse_mac_stats_regs[i].name,
1237 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_NEEDGIANT,
1238 		    sc, i, sysctl_atse_mac_stats_proc, "IU",
1239 		    atse_mac_stats_regs[i].descr);
1240 	}
1241 
1242 	/* rx_err[]. */
1243 	for (i = 0; i < ATSE_RX_ERR_MAX; i++) {
1244 		if (atse_rx_err_stats_regs[i].name == NULL ||
1245 		    atse_rx_err_stats_regs[i].descr == NULL) {
1246 			continue;
1247 		}
1248 
1249 		SYSCTL_ADD_PROC(sctx, SYSCTL_CHILDREN(soid), OID_AUTO,
1250 		    atse_rx_err_stats_regs[i].name,
1251 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_NEEDGIANT,
1252 		    sc, i, sysctl_atse_rx_err_stats_proc, "IU",
1253 		    atse_rx_err_stats_regs[i].descr);
1254 	}
1255 }
1256 
1257 /*
1258  * Generic device handling routines.
1259  */
1260 int
1261 atse_attach(device_t dev)
1262 {
1263 	struct atse_softc *sc;
1264 	if_t ifp;
1265 	uint32_t caps;
1266 	int error;
1267 
1268 	sc = device_get_softc(dev);
1269 	sc->dev = dev;
1270 
1271 	/* Get xDMA controller */
1272 	sc->xdma_tx = xdma_ofw_get(sc->dev, "tx");
1273 	if (sc->xdma_tx == NULL) {
1274 		device_printf(dev, "Can't find DMA controller.\n");
1275 		return (ENXIO);
1276 	}
1277 
1278 	/*
1279 	 * Only final (EOP) write can be less than "symbols per beat" value
1280 	 * so we have to defrag mbuf chain.
1281 	 * Chapter 15. On-Chip FIFO Memory Core.
1282 	 * Embedded Peripherals IP User Guide.
1283 	 */
1284 	caps = XCHAN_CAP_NOSEG;
1285 
1286 	/* Alloc xDMA virtual channel. */
1287 	sc->xchan_tx = xdma_channel_alloc(sc->xdma_tx, caps);
1288 	if (sc->xchan_tx == NULL) {
1289 		device_printf(dev, "Can't alloc virtual DMA channel.\n");
1290 		return (ENXIO);
1291 	}
1292 
1293 	/* Setup interrupt handler. */
1294 	error = xdma_setup_intr(sc->xchan_tx, 0,
1295 	    atse_xdma_tx_intr, sc, &sc->ih_tx);
1296 	if (error) {
1297 		device_printf(sc->dev,
1298 		    "Can't setup xDMA interrupt handler.\n");
1299 		return (ENXIO);
1300 	}
1301 
1302 	xdma_prep_sg(sc->xchan_tx,
1303 	    TX_QUEUE_SIZE,	/* xchan requests queue size */
1304 	    MCLBYTES,	/* maxsegsize */
1305 	    8,		/* maxnsegs */
1306 	    16,		/* alignment */
1307 	    0,		/* boundary */
1308 	    BUS_SPACE_MAXADDR_32BIT,
1309 	    BUS_SPACE_MAXADDR);
1310 
1311 	/* Get RX xDMA controller */
1312 	sc->xdma_rx = xdma_ofw_get(sc->dev, "rx");
1313 	if (sc->xdma_rx == NULL) {
1314 		device_printf(dev, "Can't find DMA controller.\n");
1315 		return (ENXIO);
1316 	}
1317 
1318 	/* Alloc xDMA virtual channel. */
1319 	sc->xchan_rx = xdma_channel_alloc(sc->xdma_rx, caps);
1320 	if (sc->xchan_rx == NULL) {
1321 		device_printf(dev, "Can't alloc virtual DMA channel.\n");
1322 		return (ENXIO);
1323 	}
1324 
1325 	/* Setup interrupt handler. */
1326 	error = xdma_setup_intr(sc->xchan_rx, XDMA_INTR_NET,
1327 	    atse_xdma_rx_intr, sc, &sc->ih_rx);
1328 	if (error) {
1329 		device_printf(sc->dev,
1330 		    "Can't setup xDMA interrupt handler.\n");
1331 		return (ENXIO);
1332 	}
1333 
1334 	xdma_prep_sg(sc->xchan_rx,
1335 	    RX_QUEUE_SIZE,	/* xchan requests queue size */
1336 	    MCLBYTES,		/* maxsegsize */
1337 	    1,			/* maxnsegs */
1338 	    16,			/* alignment */
1339 	    0,			/* boundary */
1340 	    BUS_SPACE_MAXADDR_32BIT,
1341 	    BUS_SPACE_MAXADDR);
1342 
1343 	mtx_init(&sc->br_mtx, "buf ring mtx", NULL, MTX_DEF);
1344 	sc->br = buf_ring_alloc(BUFRING_SIZE, M_DEVBUF,
1345 	    M_NOWAIT, &sc->br_mtx);
1346 	if (sc->br == NULL) {
1347 		return (ENOMEM);
1348 	}
1349 
1350 	atse_ethernet_option_bits_read(dev);
1351 
1352 	mtx_init(&sc->atse_mtx, device_get_nameunit(dev), MTX_NETWORK_LOCK,
1353 	    MTX_DEF);
1354 
1355 	callout_init_mtx(&sc->atse_tick, &sc->atse_mtx, 0);
1356 
1357 	/*
1358 	 * We are only doing single-PHY with this driver currently.  The
1359 	 * defaults would be right so that BASE_CFG_MDIO_ADDR0 points to the
1360 	 * 1st PHY address (0) apart from the fact that BMCR0 is always
1361 	 * the PCS mapping, so we always use BMCR1. See Table 5-1 0xA0-0xBF.
1362 	 */
1363 #if 0	/* Always PCS. */
1364 	sc->atse_bmcr0 = MDIO_0_START;
1365 	CSR_WRITE_4(sc, BASE_CFG_MDIO_ADDR0, 0x00);
1366 #endif
1367 	/* Always use matching PHY for atse[0..]. */
1368 	sc->atse_phy_addr = device_get_unit(dev);
1369 	sc->atse_bmcr1 = MDIO_1_START;
1370 	CSR_WRITE_4(sc, BASE_CFG_MDIO_ADDR1, sc->atse_phy_addr);
1371 
1372 	/* Reset the adapter. */
1373 	atse_reset(sc);
1374 
1375 	/* Setup interface. */
1376 	ifp = sc->atse_ifp = if_alloc(IFT_ETHER);
1377 	if (ifp == NULL) {
1378 		device_printf(dev, "if_alloc() failed\n");
1379 		error = ENOSPC;
1380 		goto err;
1381 	}
1382 	if_setsoftc(ifp, sc);
1383 	if_initname(ifp, device_get_name(dev), device_get_unit(dev));
1384 	if_setflags(ifp, IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST);
1385 	if_setioctlfn(ifp, atse_ioctl);
1386 	if_settransmitfn(ifp, atse_transmit);
1387 	if_setqflushfn(ifp, atse_qflush);
1388 	if_setinitfn(ifp, atse_init);
1389 	if_setsendqlen(ifp, ATSE_TX_LIST_CNT - 1);
1390 	if_setsendqready(ifp);
1391 
1392 	/* MII setup. */
1393 	error = mii_attach(dev, &sc->atse_miibus, ifp, atse_ifmedia_upd,
1394 	    atse_ifmedia_sts, BMSR_DEFCAPMASK, MII_PHY_ANY, MII_OFFSET_ANY, 0);
1395 	if (error != 0) {
1396 		device_printf(dev, "attaching PHY failed: %d\n", error);
1397 		goto err;
1398 	}
1399 
1400 	/* Call media-indepedent attach routine. */
1401 	ether_ifattach(ifp, sc->atse_eth_addr);
1402 
1403 	/* Tell the upper layer(s) about vlan mtu support. */
1404 	if_setifheaderlen(ifp, sizeof(struct ether_vlan_header));
1405 	if_setcapabilitiesbit(ifp, IFCAP_VLAN_MTU, 0);
1406 	if_setcapenable(ifp, if_getcapabilities(ifp));
1407 
1408 err:
1409 	if (error != 0) {
1410 		atse_detach(dev);
1411 	}
1412 
1413 	if (error == 0) {
1414 		atse_sysctl_stats_attach(dev);
1415 	}
1416 
1417 	atse_rx_enqueue(sc, NUM_RX_MBUF);
1418 	xdma_queue_submit(sc->xchan_rx);
1419 
1420 	return (error);
1421 }
1422 
1423 static int
1424 atse_detach(device_t dev)
1425 {
1426 	struct atse_softc *sc;
1427 	if_t ifp;
1428 
1429 	sc = device_get_softc(dev);
1430 	KASSERT(mtx_initialized(&sc->atse_mtx), ("%s: mutex not initialized",
1431 	    device_get_nameunit(dev)));
1432 	ifp = sc->atse_ifp;
1433 
1434 	/* Only cleanup if attach succeeded. */
1435 	if (device_is_attached(dev)) {
1436 		ATSE_LOCK(sc);
1437 		atse_stop_locked(sc);
1438 		ATSE_UNLOCK(sc);
1439 		callout_drain(&sc->atse_tick);
1440 		ether_ifdetach(ifp);
1441 	}
1442 	if (sc->atse_miibus != NULL) {
1443 		device_delete_child(dev, sc->atse_miibus);
1444 	}
1445 
1446 	if (ifp != NULL) {
1447 		if_free(ifp);
1448 	}
1449 
1450 	mtx_destroy(&sc->atse_mtx);
1451 
1452 	xdma_channel_free(sc->xchan_tx);
1453 	xdma_channel_free(sc->xchan_rx);
1454 	xdma_put(sc->xdma_tx);
1455 	xdma_put(sc->xdma_rx);
1456 
1457 	return (0);
1458 }
1459 
1460 /* Shared between nexus and fdt implementation. */
1461 void
1462 atse_detach_resources(device_t dev)
1463 {
1464 	struct atse_softc *sc;
1465 
1466 	sc = device_get_softc(dev);
1467 
1468 	if (sc->atse_mem_res != NULL) {
1469 		bus_release_resource(dev, SYS_RES_MEMORY, sc->atse_mem_rid,
1470 		    sc->atse_mem_res);
1471 		sc->atse_mem_res = NULL;
1472 	}
1473 }
1474 
1475 int
1476 atse_detach_dev(device_t dev)
1477 {
1478 	int error;
1479 
1480 	error = atse_detach(dev);
1481 	if (error) {
1482 		/* We are basically in undefined state now. */
1483 		device_printf(dev, "atse_detach() failed: %d\n", error);
1484 		return (error);
1485 	}
1486 
1487 	atse_detach_resources(dev);
1488 
1489 	return (0);
1490 }
1491 
1492 int
1493 atse_miibus_readreg(device_t dev, int phy, int reg)
1494 {
1495 	struct atse_softc *sc;
1496 	int val;
1497 
1498 	sc = device_get_softc(dev);
1499 
1500 	/*
1501 	 * We currently do not support re-mapping of MDIO space on-the-fly
1502 	 * but de-facto hard-code the phy#.
1503 	 */
1504 	if (phy != sc->atse_phy_addr) {
1505 		return (0);
1506 	}
1507 
1508 	val = PHY_READ_2(sc, reg);
1509 
1510 	return (val);
1511 }
1512 
1513 int
1514 atse_miibus_writereg(device_t dev, int phy, int reg, int data)
1515 {
1516 	struct atse_softc *sc;
1517 
1518 	sc = device_get_softc(dev);
1519 
1520 	/*
1521 	 * We currently do not support re-mapping of MDIO space on-the-fly
1522 	 * but de-facto hard-code the phy#.
1523 	 */
1524 	if (phy != sc->atse_phy_addr) {
1525 		return (0);
1526 	}
1527 
1528 	PHY_WRITE_2(sc, reg, data);
1529 	return (0);
1530 }
1531 
1532 void
1533 atse_miibus_statchg(device_t dev)
1534 {
1535 	struct atse_softc *sc;
1536 	struct mii_data *mii;
1537 	if_t ifp;
1538 	uint32_t val4;
1539 
1540 	sc = device_get_softc(dev);
1541 	ATSE_LOCK_ASSERT(sc);
1542 
1543 	mii = device_get_softc(sc->atse_miibus);
1544 	ifp = sc->atse_ifp;
1545 	if (mii == NULL || ifp == NULL ||
1546 	    (if_getdrvflags(ifp) & IFF_DRV_RUNNING) == 0) {
1547 		return;
1548 	}
1549 
1550 	val4 = CSR_READ_4(sc, BASE_CFG_COMMAND_CONFIG);
1551 
1552 	/* Assume no link. */
1553 	sc->atse_flags &= ~ATSE_FLAGS_LINK;
1554 
1555 	if ((mii->mii_media_status & (IFM_ACTIVE | IFM_AVALID)) ==
1556 	    (IFM_ACTIVE | IFM_AVALID)) {
1557 		switch (IFM_SUBTYPE(mii->mii_media_active)) {
1558 		case IFM_10_T:
1559 			val4 |= BASE_CFG_COMMAND_CONFIG_ENA_10;
1560 			val4 &= ~BASE_CFG_COMMAND_CONFIG_ETH_SPEED;
1561 			sc->atse_flags |= ATSE_FLAGS_LINK;
1562 			break;
1563 		case IFM_100_TX:
1564 			val4 &= ~BASE_CFG_COMMAND_CONFIG_ENA_10;
1565 			val4 &= ~BASE_CFG_COMMAND_CONFIG_ETH_SPEED;
1566 			sc->atse_flags |= ATSE_FLAGS_LINK;
1567 			break;
1568 		case IFM_1000_T:
1569 			val4 &= ~BASE_CFG_COMMAND_CONFIG_ENA_10;
1570 			val4 |= BASE_CFG_COMMAND_CONFIG_ETH_SPEED;
1571 			sc->atse_flags |= ATSE_FLAGS_LINK;
1572 			break;
1573 		default:
1574 			break;
1575 		}
1576 	}
1577 
1578 	if ((sc->atse_flags & ATSE_FLAGS_LINK) == 0) {
1579 		/* Need to stop the MAC? */
1580 		return;
1581 	}
1582 
1583 	if (IFM_OPTIONS(mii->mii_media_active & IFM_FDX) != 0) {
1584 		val4 &= ~BASE_CFG_COMMAND_CONFIG_HD_ENA;
1585 	} else {
1586 		val4 |= BASE_CFG_COMMAND_CONFIG_HD_ENA;
1587 	}
1588 
1589 	/* flow control? */
1590 
1591 	/* Make sure the MAC is activated. */
1592 	val4 |= BASE_CFG_COMMAND_CONFIG_TX_ENA;
1593 	val4 |= BASE_CFG_COMMAND_CONFIG_RX_ENA;
1594 
1595 	CSR_WRITE_4(sc, BASE_CFG_COMMAND_CONFIG, val4);
1596 }
1597 
1598 MODULE_DEPEND(atse, ether, 1, 1, 1);
1599 MODULE_DEPEND(atse, miibus, 1, 1, 1);
1600