Do a major clean-up of the BUSDMA architecture. A large number of
[dragonfly.git] / sys / dev / netif / tl / if_tl.c
1 /*
2  * Copyright (c) 1997, 1998
3  *      Bill Paul <wpaul@ctr.columbia.edu>.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *      This product includes software developed by Bill Paul.
16  * 4. Neither the name of the author nor the names of any co-contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY Bill Paul AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL Bill Paul OR THE VOICES IN HIS HEAD
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
30  * THE POSSIBILITY OF SUCH DAMAGE.
31  *
32  * $FreeBSD: src/sys/pci/if_tl.c,v 1.51.2.5 2001/12/16 15:46:08 luigi Exp $
33  * $DragonFly: src/sys/dev/netif/tl/if_tl.c,v 1.37 2006/10/25 20:55:59 dillon Exp $
34  */
35
36 /*
37  * Texas Instruments ThunderLAN driver for FreeBSD 2.2.6 and 3.x.
38  * Supports many Compaq PCI NICs based on the ThunderLAN ethernet controller,
39  * the National Semiconductor DP83840A physical interface and the
40  * Microchip Technology 24Cxx series serial EEPROM.
41  *
42  * Written using the following four documents:
43  *
44  * Texas Instruments ThunderLAN Programmer's Guide (www.ti.com)
45  * National Semiconductor DP83840A data sheet (www.national.com)
46  * Microchip Technology 24C02C data sheet (www.microchip.com)
47  * Micro Linear ML6692 100BaseTX only PHY data sheet (www.microlinear.com)
48  * 
49  * Written by Bill Paul <wpaul@ctr.columbia.edu>
50  * Electrical Engineering Department
51  * Columbia University, New York City
52  */
53
54 /*
55  * Some notes about the ThunderLAN:
56  *
57  * The ThunderLAN controller is a single chip containing PCI controller
58  * logic, approximately 3K of on-board SRAM, a LAN controller, and media
59  * independent interface (MII) bus. The MII allows the ThunderLAN chip to
60  * control up to 32 different physical interfaces (PHYs). The ThunderLAN
61  * also has a built-in 10baseT PHY, allowing a single ThunderLAN controller
62  * to act as a complete ethernet interface.
63  *
64  * Other PHYs may be attached to the ThunderLAN; the Compaq 10/100 cards
65  * use a National Semiconductor DP83840A PHY that supports 10 or 100Mb/sec
66  * in full or half duplex. Some of the Compaq Deskpro machines use a
67  * Level 1 LXT970 PHY with the same capabilities. Certain Olicom adapters
68  * use a Micro Linear ML6692 100BaseTX only PHY, which can be used in
69  * concert with the ThunderLAN's internal PHY to provide full 10/100
70  * support. This is cheaper than using a standalone external PHY for both
71  * 10/100 modes and letting the ThunderLAN's internal PHY go to waste.
72  * A serial EEPROM is also attached to the ThunderLAN chip to provide
73  * power-up default register settings and for storing the adapter's
74  * station address. Although not supported by this driver, the ThunderLAN
75  * chip can also be connected to token ring PHYs.
76  *
77  * The ThunderLAN has a set of registers which can be used to issue
78  * commands, acknowledge interrupts, and to manipulate other internal
79  * registers on its DIO bus. The primary registers can be accessed
80  * using either programmed I/O (inb/outb) or via PCI memory mapping,
81  * depending on how the card is configured during the PCI probing
82  * phase. It is even possible to have both PIO and memory mapped
83  * access turned on at the same time.
84  * 
85  * Frame reception and transmission with the ThunderLAN chip is done
86  * using frame 'lists.' A list structure looks more or less like this:
87  *
88  * struct tl_frag {
89  *      u_int32_t               fragment_address;
90  *      u_int32_t               fragment_size;
91  * };
92  * struct tl_list {
93  *      u_int32_t               forward_pointer;
94  *      u_int16_t               cstat;
95  *      u_int16_t               frame_size;
96  *      struct tl_frag          fragments[10];
97  * };
98  *
99  * The forward pointer in the list header can be either a 0 or the address
100  * of another list, which allows several lists to be linked together. Each
101  * list contains up to 10 fragment descriptors. This means the chip allows
102  * ethernet frames to be broken up into up to 10 chunks for transfer to
103  * and from the SRAM. Note that the forward pointer and fragment buffer
104  * addresses are physical memory addresses, not virtual. Note also that
105  * a single ethernet frame can not span lists: if the host wants to
106  * transmit a frame and the frame data is split up over more than 10
107  * buffers, the frame has to collapsed before it can be transmitted.
108  *
109  * To receive frames, the driver sets up a number of lists and populates
110  * the fragment descriptors, then it sends an RX GO command to the chip.
111  * When a frame is received, the chip will DMA it into the memory regions
112  * specified by the fragment descriptors and then trigger an RX 'end of
113  * frame interrupt' when done. The driver may choose to use only one
114  * fragment per list; this may result is slighltly less efficient use
115  * of memory in exchange for improving performance.
116  *
117  * To transmit frames, the driver again sets up lists and fragment
118  * descriptors, only this time the buffers contain frame data that
119  * is to be DMA'ed into the chip instead of out of it. Once the chip
120  * has transfered the data into its on-board SRAM, it will trigger a
121  * TX 'end of frame' interrupt. It will also generate an 'end of channel'
122  * interrupt when it reaches the end of the list.
123  */
124
125 /*
126  * Some notes about this driver:
127  *
128  * The ThunderLAN chip provides a couple of different ways to organize
129  * reception, transmission and interrupt handling. The simplest approach
130  * is to use one list each for transmission and reception. In this mode,
131  * the ThunderLAN will generate two interrupts for every received frame
132  * (one RX EOF and one RX EOC) and two for each transmitted frame (one
133  * TX EOF and one TX EOC). This may make the driver simpler but it hurts
134  * performance to have to handle so many interrupts.
135  *
136  * Initially I wanted to create a circular list of receive buffers so
137  * that the ThunderLAN chip would think there was an infinitely long
138  * receive channel and never deliver an RXEOC interrupt. However this
139  * doesn't work correctly under heavy load: while the manual says the
140  * chip will trigger an RXEOF interrupt each time a frame is copied into
141  * memory, you can't count on the chip waiting around for you to acknowledge
142  * the interrupt before it starts trying to DMA the next frame. The result
143  * is that the chip might traverse the entire circular list and then wrap
144  * around before you have a chance to do anything about it. Consequently,
145  * the receive list is terminated (with a 0 in the forward pointer in the
146  * last element). Each time an RXEOF interrupt arrives, the used list
147  * is shifted to the end of the list. This gives the appearance of an
148  * infinitely large RX chain so long as the driver doesn't fall behind
149  * the chip and allow all of the lists to be filled up.
150  *
151  * If all the lists are filled, the adapter will deliver an RX 'end of
152  * channel' interrupt when it hits the 0 forward pointer at the end of
153  * the chain. The RXEOC handler then cleans out the RX chain and resets
154  * the list head pointer in the ch_parm register and restarts the receiver.
155  *
156  * For frame transmission, it is possible to program the ThunderLAN's
157  * transmit interrupt threshold so that the chip can acknowledge multiple
158  * lists with only a single TX EOF interrupt. This allows the driver to
159  * queue several frames in one shot, and only have to handle a total
160  * two interrupts (one TX EOF and one TX EOC) no matter how many frames
161  * are transmitted. Frame transmission is done directly out of the
162  * mbufs passed to the tl_start() routine via the interface send queue.
163  * The driver simply sets up the fragment descriptors in the transmit
164  * lists to point to the mbuf data regions and sends a TX GO command.
165  *
166  * Note that since the RX and TX lists themselves are always used
167  * only by the driver, the are malloc()ed once at driver initialization
168  * time and never free()ed.
169  *
170  * Also, in order to remain as platform independent as possible, this
171  * driver uses memory mapped register access to manipulate the card
172  * as opposed to programmed I/O. This avoids the use of the inb/outb
173  * (and related) instructions which are specific to the i386 platform.
174  *
175  * Using these techniques, this driver achieves very high performance
176  * by minimizing the amount of interrupts generated during large
177  * transfers and by completely avoiding buffer copies. Frame transfer
178  * to and from the ThunderLAN chip is performed entirely by the chip
179  * itself thereby reducing the load on the host CPU.
180  */
181
182 #include <sys/param.h>
183 #include <sys/systm.h>
184 #include <sys/sockio.h>
185 #include <sys/mbuf.h>
186 #include <sys/malloc.h>
187 #include <sys/kernel.h>
188 #include <sys/socket.h>
189 #include <sys/serialize.h>
190 #include <sys/bus.h>
191 #include <sys/rman.h>
192 #include <sys/thread2.h>
193
194 #include <net/if.h>
195 #include <net/ifq_var.h>
196 #include <net/if_arp.h>
197 #include <net/ethernet.h>
198 #include <net/if_dl.h>
199 #include <net/if_media.h>
200
201 #include <net/bpf.h>
202
203 #include <vm/vm.h>              /* for vtophys */
204 #include <vm/pmap.h>            /* for vtophys */
205
206 #include "../mii_layer/mii.h"
207 #include "../mii_layer/miivar.h"
208
209 #include <bus/pci/pcireg.h>
210 #include <bus/pci/pcivar.h>
211
212 /*
213  * Default to using PIO register access mode to pacify certain
214  * laptop docking stations with built-in ThunderLAN chips that
215  * don't seem to handle memory mapped mode properly.
216  */
217 #define TL_USEIOSPACE
218
219 #include "if_tlreg.h"
220
221 /* "controller miibus0" required.  See GENERIC if you get errors here. */
222 #include "miibus_if.h"
223
224 /*
225  * Various supported device vendors/types and their names.
226  */
227
228 static struct tl_type tl_devs[] = {
229         { TI_VENDORID,  TI_DEVICEID_THUNDERLAN,
230                 "Texas Instruments ThunderLAN" },
231         { COMPAQ_VENDORID, COMPAQ_DEVICEID_NETEL_10,
232                 "Compaq Netelligent 10" },
233         { COMPAQ_VENDORID, COMPAQ_DEVICEID_NETEL_10_100,
234                 "Compaq Netelligent 10/100" },
235         { COMPAQ_VENDORID, COMPAQ_DEVICEID_NETEL_10_100_PROLIANT,
236                 "Compaq Netelligent 10/100 Proliant" },
237         { COMPAQ_VENDORID, COMPAQ_DEVICEID_NETEL_10_100_DUAL,
238                 "Compaq Netelligent 10/100 Dual Port" },
239         { COMPAQ_VENDORID, COMPAQ_DEVICEID_NETFLEX_3P_INTEGRATED,
240                 "Compaq NetFlex-3/P Integrated" },
241         { COMPAQ_VENDORID, COMPAQ_DEVICEID_NETFLEX_3P,
242                 "Compaq NetFlex-3/P" },
243         { COMPAQ_VENDORID, COMPAQ_DEVICEID_NETFLEX_3P_BNC,
244                 "Compaq NetFlex 3/P w/ BNC" },
245         { COMPAQ_VENDORID, COMPAQ_DEVICEID_NETEL_10_100_EMBEDDED,
246                 "Compaq Netelligent 10/100 TX Embedded UTP" },
247         { COMPAQ_VENDORID, COMPAQ_DEVICEID_NETEL_10_T2_UTP_COAX,
248                 "Compaq Netelligent 10 T/2 PCI UTP/Coax" },
249         { COMPAQ_VENDORID, COMPAQ_DEVICEID_NETEL_10_100_TX_UTP,
250                 "Compaq Netelligent 10/100 TX UTP" },
251         { OLICOM_VENDORID, OLICOM_DEVICEID_OC2183,
252                 "Olicom OC-2183/2185" },
253         { OLICOM_VENDORID, OLICOM_DEVICEID_OC2325,
254                 "Olicom OC-2325" },
255         { OLICOM_VENDORID, OLICOM_DEVICEID_OC2326,
256                 "Olicom OC-2326 10/100 TX UTP" },
257         { 0, 0, NULL }
258 };
259
260 static int tl_probe             (device_t);
261 static int tl_attach            (device_t);
262 static int tl_detach            (device_t);
263 static int tl_intvec_rxeoc      (void *, u_int32_t);
264 static int tl_intvec_txeoc      (void *, u_int32_t);
265 static int tl_intvec_txeof      (void *, u_int32_t);
266 static int tl_intvec_rxeof      (void *, u_int32_t);
267 static int tl_intvec_adchk      (void *, u_int32_t);
268 static int tl_intvec_netsts     (void *, u_int32_t);
269
270 static int tl_newbuf            (struct tl_softc *,
271                                         struct tl_chain_onefrag *);
272 static void tl_stats_update     (void *);
273 static void tl_stats_update_serialized(void *);
274 static int tl_encap             (struct tl_softc *, struct tl_chain *,
275                                                 struct mbuf *);
276
277 static void tl_intr             (void *);
278 static void tl_start            (struct ifnet *);
279 static int tl_ioctl             (struct ifnet *, u_long, caddr_t,
280                                                 struct ucred *);
281 static void tl_init             (void *);
282 static void tl_stop             (struct tl_softc *);
283 static void tl_watchdog         (struct ifnet *);
284 static void tl_shutdown         (device_t);
285 static int tl_ifmedia_upd       (struct ifnet *);
286 static void tl_ifmedia_sts      (struct ifnet *, struct ifmediareq *);
287
288 static u_int8_t tl_eeprom_putbyte       (struct tl_softc *, int);
289 static u_int8_t tl_eeprom_getbyte       (struct tl_softc *,
290                                                 int, u_int8_t *);
291 static int tl_read_eeprom       (struct tl_softc *, caddr_t, int, int);
292
293 static void tl_mii_sync         (struct tl_softc *);
294 static void tl_mii_send         (struct tl_softc *, u_int32_t, int);
295 static int tl_mii_readreg       (struct tl_softc *, struct tl_mii_frame *);
296 static int tl_mii_writereg      (struct tl_softc *, struct tl_mii_frame *);
297 static int tl_miibus_readreg    (device_t, int, int);
298 static int tl_miibus_writereg   (device_t, int, int, int);
299 static void tl_miibus_statchg   (device_t);
300
301 static void tl_setmode          (struct tl_softc *, int);
302 static int tl_calchash          (caddr_t);
303 static void tl_setmulti         (struct tl_softc *);
304 static void tl_setfilt          (struct tl_softc *, caddr_t, int);
305 static void tl_softreset        (struct tl_softc *, int);
306 static void tl_hardreset        (device_t);
307 static int tl_list_rx_init      (struct tl_softc *);
308 static int tl_list_tx_init      (struct tl_softc *);
309
310 static u_int8_t tl_dio_read8    (struct tl_softc *, int);
311 static u_int16_t tl_dio_read16  (struct tl_softc *, int);
312 static u_int32_t tl_dio_read32  (struct tl_softc *, int);
313 static void tl_dio_write8       (struct tl_softc *, int, int);
314 static void tl_dio_write16      (struct tl_softc *, int, int);
315 static void tl_dio_write32      (struct tl_softc *, int, int);
316 static void tl_dio_setbit       (struct tl_softc *, int, int);
317 static void tl_dio_clrbit       (struct tl_softc *, int, int);
318 static void tl_dio_setbit16     (struct tl_softc *, int, int);
319 static void tl_dio_clrbit16     (struct tl_softc *, int, int);
320
321 #ifdef TL_USEIOSPACE
322 #define TL_RES          SYS_RES_IOPORT
323 #define TL_RID          TL_PCI_LOIO
324 #else
325 #define TL_RES          SYS_RES_MEMORY
326 #define TL_RID          TL_PCI_LOMEM
327 #endif
328
329 static device_method_t tl_methods[] = {
330         /* Device interface */
331         DEVMETHOD(device_probe,         tl_probe),
332         DEVMETHOD(device_attach,        tl_attach),
333         DEVMETHOD(device_detach,        tl_detach),
334         DEVMETHOD(device_shutdown,      tl_shutdown),
335
336         /* bus interface */
337         DEVMETHOD(bus_print_child,      bus_generic_print_child),
338         DEVMETHOD(bus_driver_added,     bus_generic_driver_added),
339
340         /* MII interface */
341         DEVMETHOD(miibus_readreg,       tl_miibus_readreg),
342         DEVMETHOD(miibus_writereg,      tl_miibus_writereg),
343         DEVMETHOD(miibus_statchg,       tl_miibus_statchg),
344
345         { 0, 0 }
346 };
347
348 static driver_t tl_driver = {
349         "tl",
350         tl_methods,
351         sizeof(struct tl_softc)
352 };
353
354 static devclass_t tl_devclass;
355
356 DECLARE_DUMMY_MODULE(if_tl);
357 DRIVER_MODULE(if_tl, pci, tl_driver, tl_devclass, 0, 0);
358 DRIVER_MODULE(miibus, tl, miibus_driver, miibus_devclass, 0, 0);
359
360 static u_int8_t
361 tl_dio_read8(struct tl_softc *sc, int reg)
362 {
363         CSR_WRITE_2(sc, TL_DIO_ADDR, reg);
364         return(CSR_READ_1(sc, TL_DIO_DATA + (reg & 3)));
365 }
366
367 static u_int16_t
368 tl_dio_read16(struct tl_softc *sc, int reg)
369 {
370         CSR_WRITE_2(sc, TL_DIO_ADDR, reg);
371         return(CSR_READ_2(sc, TL_DIO_DATA + (reg & 3)));
372 }
373
374 static u_int32_t
375 tl_dio_read32(struct tl_softc *sc, int reg)
376 {
377         CSR_WRITE_2(sc, TL_DIO_ADDR, reg);
378         return(CSR_READ_4(sc, TL_DIO_DATA + (reg & 3)));
379 }
380
381 static void
382 tl_dio_write8(struct tl_softc *sc, int reg, int val)
383 {
384         CSR_WRITE_2(sc, TL_DIO_ADDR, reg);
385         CSR_WRITE_1(sc, TL_DIO_DATA + (reg & 3), val);
386         return;
387 }
388
389 static void
390 tl_dio_write16(struct tl_softc *sc, int reg, int val)
391 {
392         CSR_WRITE_2(sc, TL_DIO_ADDR, reg);
393         CSR_WRITE_2(sc, TL_DIO_DATA + (reg & 3), val);
394         return;
395 }
396
397 static void
398 tl_dio_write32(struct tl_softc *sc, int reg, int val)
399 {
400         CSR_WRITE_2(sc, TL_DIO_ADDR, reg);
401         CSR_WRITE_4(sc, TL_DIO_DATA + (reg & 3), val);
402         return;
403 }
404
405 static void
406 tl_dio_setbit(struct tl_softc *sc, int reg, int bit)
407 {
408         u_int8_t                        f;
409
410         CSR_WRITE_2(sc, TL_DIO_ADDR, reg);
411         f = CSR_READ_1(sc, TL_DIO_DATA + (reg & 3));
412         f |= bit;
413         CSR_WRITE_1(sc, TL_DIO_DATA + (reg & 3), f);
414
415         return;
416 }
417
418 static void
419 tl_dio_clrbit(struct tl_softc *sc, int reg, int bit)
420 {
421         u_int8_t                        f;
422
423         CSR_WRITE_2(sc, TL_DIO_ADDR, reg);
424         f = CSR_READ_1(sc, TL_DIO_DATA + (reg & 3));
425         f &= ~bit;
426         CSR_WRITE_1(sc, TL_DIO_DATA + (reg & 3), f);
427
428         return;
429 }
430
431 static void
432 tl_dio_setbit16(struct tl_softc *sc, int reg, int bit)
433 {
434         u_int16_t                       f;
435
436         CSR_WRITE_2(sc, TL_DIO_ADDR, reg);
437         f = CSR_READ_2(sc, TL_DIO_DATA + (reg & 3));
438         f |= bit;
439         CSR_WRITE_2(sc, TL_DIO_DATA + (reg & 3), f);
440
441         return;
442 }
443
444 static void
445 tl_dio_clrbit16(struct tl_softc *sc, int reg, int bit)
446 {
447         u_int16_t                       f;
448
449         CSR_WRITE_2(sc, TL_DIO_ADDR, reg);
450         f = CSR_READ_2(sc, TL_DIO_DATA + (reg & 3));
451         f &= ~bit;
452         CSR_WRITE_2(sc, TL_DIO_DATA + (reg & 3), f);
453
454         return;
455 }
456
457 /*
458  * Send an instruction or address to the EEPROM, check for ACK.
459  */
460 static u_int8_t
461 tl_eeprom_putbyte(struct tl_softc *sc, int byte)
462 {
463         int             i, ack = 0;
464
465         /*
466          * Make sure we're in TX mode.
467          */
468         tl_dio_setbit(sc, TL_NETSIO, TL_SIO_ETXEN);
469
470         /*
471          * Feed in each bit and stobe the clock.
472          */
473         for (i = 0x80; i; i >>= 1) {
474                 if (byte & i) {
475                         tl_dio_setbit(sc, TL_NETSIO, TL_SIO_EDATA);
476                 } else {
477                         tl_dio_clrbit(sc, TL_NETSIO, TL_SIO_EDATA);
478                 }
479                 DELAY(1);
480                 tl_dio_setbit(sc, TL_NETSIO, TL_SIO_ECLOK);
481                 DELAY(1);
482                 tl_dio_clrbit(sc, TL_NETSIO, TL_SIO_ECLOK);
483         }
484
485         /*
486          * Turn off TX mode.
487          */
488         tl_dio_clrbit(sc, TL_NETSIO, TL_SIO_ETXEN);
489
490         /*
491          * Check for ack.
492          */
493         tl_dio_setbit(sc, TL_NETSIO, TL_SIO_ECLOK);
494         ack = tl_dio_read8(sc, TL_NETSIO) & TL_SIO_EDATA;
495         tl_dio_clrbit(sc, TL_NETSIO, TL_SIO_ECLOK);
496
497         return(ack);
498 }
499
500 /*
501  * Read a byte of data stored in the EEPROM at address 'addr.'
502  */
503 static u_int8_t
504 tl_eeprom_getbyte(struct tl_softc *sc, int addr, u_int8_t *dest)
505 {
506         int             i;
507         u_int8_t                byte = 0;
508
509         tl_dio_write8(sc, TL_NETSIO, 0);
510
511         EEPROM_START;
512
513         /*
514          * Send write control code to EEPROM.
515          */
516         if (tl_eeprom_putbyte(sc, EEPROM_CTL_WRITE)) {
517                 if_printf(&sc->arpcom.ac_if, "failed to send write command, "
518                           "status: %x\n", tl_dio_read8(sc, TL_NETSIO));
519                 return(1);
520         }
521
522         /*
523          * Send address of byte we want to read.
524          */
525         if (tl_eeprom_putbyte(sc, addr)) {
526                 if_printf(&sc->arpcom.ac_if, "failed to send address, "
527                           "status: %x\n", tl_dio_read8(sc, TL_NETSIO));
528                 return(1);
529         }
530
531         EEPROM_STOP;
532         EEPROM_START;
533         /*
534          * Send read control code to EEPROM.
535          */
536         if (tl_eeprom_putbyte(sc, EEPROM_CTL_READ)) {
537                 if_printf(&sc->arpcom.ac_if, "failed to send write command, "
538                           "status: %x\n", tl_dio_read8(sc, TL_NETSIO));
539                 return(1);
540         }
541
542         /*
543          * Start reading bits from EEPROM.
544          */
545         tl_dio_clrbit(sc, TL_NETSIO, TL_SIO_ETXEN);
546         for (i = 0x80; i; i >>= 1) {
547                 tl_dio_setbit(sc, TL_NETSIO, TL_SIO_ECLOK);
548                 DELAY(1);
549                 if (tl_dio_read8(sc, TL_NETSIO) & TL_SIO_EDATA)
550                         byte |= i;
551                 tl_dio_clrbit(sc, TL_NETSIO, TL_SIO_ECLOK);
552                 DELAY(1);
553         }
554
555         EEPROM_STOP;
556
557         /*
558          * No ACK generated for read, so just return byte.
559          */
560
561         *dest = byte;
562
563         return(0);
564 }
565
566 /*
567  * Read a sequence of bytes from the EEPROM.
568  */
569 static int
570 tl_read_eeprom(struct tl_softc *sc, caddr_t dest, int off, int cnt)
571 {
572         int                     err = 0, i;
573         u_int8_t                byte = 0;
574
575         for (i = 0; i < cnt; i++) {
576                 err = tl_eeprom_getbyte(sc, off + i, &byte);
577                 if (err)
578                         break;
579                 *(dest + i) = byte;
580         }
581
582         return(err ? 1 : 0);
583 }
584
585 static void
586 tl_mii_sync(struct tl_softc *sc)
587 {
588         int             i;
589
590         tl_dio_clrbit(sc, TL_NETSIO, TL_SIO_MTXEN);
591
592         for (i = 0; i < 32; i++) {
593                 tl_dio_setbit(sc, TL_NETSIO, TL_SIO_MCLK);
594                 tl_dio_clrbit(sc, TL_NETSIO, TL_SIO_MCLK);
595         }
596
597         return;
598 }
599
600 static void
601 tl_mii_send(struct tl_softc *sc, u_int32_t bits, int cnt)
602 {
603         int                     i;
604
605         for (i = (0x1 << (cnt - 1)); i; i >>= 1) {
606                 tl_dio_clrbit(sc, TL_NETSIO, TL_SIO_MCLK);
607                 if (bits & i) {
608                         tl_dio_setbit(sc, TL_NETSIO, TL_SIO_MDATA);
609                 } else {
610                         tl_dio_clrbit(sc, TL_NETSIO, TL_SIO_MDATA);
611                 }
612                 tl_dio_setbit(sc, TL_NETSIO, TL_SIO_MCLK);
613         }
614 }
615
616 static int
617 tl_mii_readreg(struct tl_softc *sc, struct tl_mii_frame *frame)
618 {
619         int                     i, ack;
620         int                     minten = 0;
621
622         tl_mii_sync(sc);
623
624         /*
625          * Set up frame for RX.
626          */
627         frame->mii_stdelim = TL_MII_STARTDELIM;
628         frame->mii_opcode = TL_MII_READOP;
629         frame->mii_turnaround = 0;
630         frame->mii_data = 0;
631         
632         /*
633          * Turn off MII interrupt by forcing MINTEN low.
634          */
635         minten = tl_dio_read8(sc, TL_NETSIO) & TL_SIO_MINTEN;
636         if (minten) {
637                 tl_dio_clrbit(sc, TL_NETSIO, TL_SIO_MINTEN);
638         }
639
640         /*
641          * Turn on data xmit.
642          */
643         tl_dio_setbit(sc, TL_NETSIO, TL_SIO_MTXEN);
644
645         /*
646          * Send command/address info.
647          */
648         tl_mii_send(sc, frame->mii_stdelim, 2);
649         tl_mii_send(sc, frame->mii_opcode, 2);
650         tl_mii_send(sc, frame->mii_phyaddr, 5);
651         tl_mii_send(sc, frame->mii_regaddr, 5);
652
653         /*
654          * Turn off xmit.
655          */
656         tl_dio_clrbit(sc, TL_NETSIO, TL_SIO_MTXEN);
657
658         /* Idle bit */
659         tl_dio_clrbit(sc, TL_NETSIO, TL_SIO_MCLK);
660         tl_dio_setbit(sc, TL_NETSIO, TL_SIO_MCLK);
661
662         /* Check for ack */
663         tl_dio_clrbit(sc, TL_NETSIO, TL_SIO_MCLK);
664         ack = tl_dio_read8(sc, TL_NETSIO) & TL_SIO_MDATA;
665
666         /* Complete the cycle */
667         tl_dio_setbit(sc, TL_NETSIO, TL_SIO_MCLK);
668
669         /*
670          * Now try reading data bits. If the ack failed, we still
671          * need to clock through 16 cycles to keep the PHYs in sync.
672          */
673         if (ack) {
674                 for(i = 0; i < 16; i++) {
675                         tl_dio_clrbit(sc, TL_NETSIO, TL_SIO_MCLK);
676                         tl_dio_setbit(sc, TL_NETSIO, TL_SIO_MCLK);
677                 }
678                 goto fail;
679         }
680
681         for (i = 0x8000; i; i >>= 1) {
682                 tl_dio_clrbit(sc, TL_NETSIO, TL_SIO_MCLK);
683                 if (!ack) {
684                         if (tl_dio_read8(sc, TL_NETSIO) & TL_SIO_MDATA)
685                                 frame->mii_data |= i;
686                 }
687                 tl_dio_setbit(sc, TL_NETSIO, TL_SIO_MCLK);
688         }
689
690 fail:
691
692         tl_dio_setbit(sc, TL_NETSIO, TL_SIO_MCLK);
693         tl_dio_clrbit(sc, TL_NETSIO, TL_SIO_MCLK);
694
695         /* Reenable interrupts */
696         if (minten) {
697                 tl_dio_setbit(sc, TL_NETSIO, TL_SIO_MINTEN);
698         }
699
700         if (ack)
701                 return(1);
702         return(0);
703 }
704
705 static int
706 tl_mii_writereg(struct tl_softc *sc, struct tl_mii_frame *frame)
707 {
708         int                     minten;
709
710         tl_mii_sync(sc);
711
712         /*
713          * Set up frame for TX.
714          */
715
716         frame->mii_stdelim = TL_MII_STARTDELIM;
717         frame->mii_opcode = TL_MII_WRITEOP;
718         frame->mii_turnaround = TL_MII_TURNAROUND;
719         
720         /*
721          * Turn off MII interrupt by forcing MINTEN low.
722          */
723         minten = tl_dio_read8(sc, TL_NETSIO) & TL_SIO_MINTEN;
724         if (minten) {
725                 tl_dio_clrbit(sc, TL_NETSIO, TL_SIO_MINTEN);
726         }
727
728         /*
729          * Turn on data output.
730          */
731         tl_dio_setbit(sc, TL_NETSIO, TL_SIO_MTXEN);
732
733         tl_mii_send(sc, frame->mii_stdelim, 2);
734         tl_mii_send(sc, frame->mii_opcode, 2);
735         tl_mii_send(sc, frame->mii_phyaddr, 5);
736         tl_mii_send(sc, frame->mii_regaddr, 5);
737         tl_mii_send(sc, frame->mii_turnaround, 2);
738         tl_mii_send(sc, frame->mii_data, 16);
739
740         tl_dio_setbit(sc, TL_NETSIO, TL_SIO_MCLK);
741         tl_dio_clrbit(sc, TL_NETSIO, TL_SIO_MCLK);
742
743         /*
744          * Turn off xmit.
745          */
746         tl_dio_clrbit(sc, TL_NETSIO, TL_SIO_MTXEN);
747
748         /* Reenable interrupts */
749         if (minten)
750                 tl_dio_setbit(sc, TL_NETSIO, TL_SIO_MINTEN);
751
752         return(0);
753 }
754
755 static int
756 tl_miibus_readreg(device_t dev, int phy, int reg)
757 {
758         struct tl_softc         *sc;
759         struct tl_mii_frame     frame;
760
761         sc = device_get_softc(dev);
762         bzero((char *)&frame, sizeof(frame));
763
764         frame.mii_phyaddr = phy;
765         frame.mii_regaddr = reg;
766         tl_mii_readreg(sc, &frame);
767
768         return(frame.mii_data);
769 }
770
771 static int
772 tl_miibus_writereg(device_t dev, int phy, int reg, int data)
773 {
774         struct tl_softc         *sc;
775         struct tl_mii_frame     frame;
776
777         sc = device_get_softc(dev);
778         bzero((char *)&frame, sizeof(frame));
779
780         frame.mii_phyaddr = phy;
781         frame.mii_regaddr = reg;
782         frame.mii_data = data;
783
784         tl_mii_writereg(sc, &frame);
785
786         return(0);
787 }
788
789 static void
790 tl_miibus_statchg(device_t dev)
791 {
792         struct tl_softc         *sc;
793         struct mii_data         *mii;
794
795         sc = device_get_softc(dev);
796         mii = device_get_softc(sc->tl_miibus);
797
798         if ((mii->mii_media_active & IFM_GMASK) == IFM_FDX) {
799                 tl_dio_setbit(sc, TL_NETCMD, TL_CMD_DUPLEX);
800         } else {
801                 tl_dio_clrbit(sc, TL_NETCMD, TL_CMD_DUPLEX);
802         }
803
804         return;
805 }
806
807 /*
808  * Set modes for bitrate devices.
809  */
810 static void
811 tl_setmode(struct tl_softc *sc, int media)
812 {
813         if (IFM_SUBTYPE(media) == IFM_10_5)
814                 tl_dio_setbit(sc, TL_ACOMMIT, TL_AC_MTXD1);
815         if (IFM_SUBTYPE(media) == IFM_10_T) {
816                 tl_dio_clrbit(sc, TL_ACOMMIT, TL_AC_MTXD1);
817                 if ((media & IFM_GMASK) == IFM_FDX) {
818                         tl_dio_clrbit(sc, TL_ACOMMIT, TL_AC_MTXD3);
819                         tl_dio_setbit(sc, TL_NETCMD, TL_CMD_DUPLEX);
820                 } else {
821                         tl_dio_setbit(sc, TL_ACOMMIT, TL_AC_MTXD3);
822                         tl_dio_clrbit(sc, TL_NETCMD, TL_CMD_DUPLEX);
823                 }
824         }
825
826         return;
827 }
828
829 /*
830  * Calculate the hash of a MAC address for programming the multicast hash
831  * table.  This hash is simply the address split into 6-bit chunks
832  * XOR'd, e.g.
833  * byte: 000000|00 1111|1111 22|222222|333333|33 4444|4444 55|555555
834  * bit:  765432|10 7654|3210 76|543210|765432|10 7654|3210 76|543210
835  * Bytes 0-2 and 3-5 are symmetrical, so are folded together.  Then
836  * the folded 24-bit value is split into 6-bit portions and XOR'd.
837  */
838 static int
839 tl_calchash(caddr_t addr)
840 {
841         int                     t;
842
843         t = (addr[0] ^ addr[3]) << 16 | (addr[1] ^ addr[4]) << 8 |
844                 (addr[2] ^ addr[5]);
845         return ((t >> 18) ^ (t >> 12) ^ (t >> 6) ^ t) & 0x3f;
846 }
847
848 /*
849  * The ThunderLAN has a perfect MAC address filter in addition to
850  * the multicast hash filter. The perfect filter can be programmed
851  * with up to four MAC addresses. The first one is always used to
852  * hold the station address, which leaves us free to use the other
853  * three for multicast addresses.
854  */
855 static void
856 tl_setfilt(struct tl_softc *sc, caddr_t addr, int slot)
857 {
858         int                     i;
859         u_int16_t               regaddr;
860
861         regaddr = TL_AREG0_B5 + (slot * ETHER_ADDR_LEN);
862
863         for (i = 0; i < ETHER_ADDR_LEN; i++)
864                 tl_dio_write8(sc, regaddr + i, *(addr + i));
865
866         return;
867 }
868
869 /*
870  * XXX In FreeBSD 3.0, multicast addresses are managed using a doubly
871  * linked list. This is fine, except addresses are added from the head
872  * end of the list. We want to arrange for 224.0.0.1 (the "all hosts")
873  * group to always be in the perfect filter, but as more groups are added,
874  * the 224.0.0.1 entry (which is always added first) gets pushed down
875  * the list and ends up at the tail. So after 3 or 4 multicast groups
876  * are added, the all-hosts entry gets pushed out of the perfect filter
877  * and into the hash table.
878  *
879  * Because the multicast list is a doubly-linked list as opposed to a
880  * circular queue, we don't have the ability to just grab the tail of
881  * the list and traverse it backwards. Instead, we have to traverse
882  * the list once to find the tail, then traverse it again backwards to
883  * update the multicast filter.
884  */
885 static void
886 tl_setmulti(struct tl_softc *sc)
887 {
888         struct ifnet            *ifp;
889         u_int32_t               hashes[2] = { 0, 0 };
890         int                     h, i;
891         struct ifmultiaddr      *ifma;
892         u_int8_t                dummy[] = { 0, 0, 0, 0, 0 ,0 };
893         ifp = &sc->arpcom.ac_if;
894
895         /* First, zot all the existing filters. */
896         for (i = 1; i < 4; i++)
897                 tl_setfilt(sc, (caddr_t)&dummy, i);
898         tl_dio_write32(sc, TL_HASH1, 0);
899         tl_dio_write32(sc, TL_HASH2, 0);
900
901         /* Now program new ones. */
902         if (ifp->if_flags & IFF_ALLMULTI) {
903                 hashes[0] = 0xFFFFFFFF;
904                 hashes[1] = 0xFFFFFFFF;
905         } else {
906                 i = 1;
907                 /* First find the tail of the list. */
908                 for (ifma = ifp->if_multiaddrs.lh_first; ifma != NULL;
909                                         ifma = ifma->ifma_link.le_next) {
910                         if (ifma->ifma_link.le_next == NULL)
911                                 break;
912                 }
913                 /* Now traverse the list backwards. */
914                 for (; ifma != NULL && ifma != (void *)&ifp->if_multiaddrs;
915                         ifma = (struct ifmultiaddr *)ifma->ifma_link.le_prev) {
916                         if (ifma->ifma_addr->sa_family != AF_LINK)
917                                 continue;
918                         /*
919                          * Program the first three multicast groups
920                          * into the perfect filter. For all others,
921                          * use the hash table.
922                          */
923                         if (i < 4) {
924                                 tl_setfilt(sc,
925                         LLADDR((struct sockaddr_dl *)ifma->ifma_addr), i);
926                                 i++;
927                                 continue;
928                         }
929
930                         h = tl_calchash(
931                                 LLADDR((struct sockaddr_dl *)ifma->ifma_addr));
932                         if (h < 32)
933                                 hashes[0] |= (1 << h);
934                         else
935                                 hashes[1] |= (1 << (h - 32));
936                 }
937         }
938
939         tl_dio_write32(sc, TL_HASH1, hashes[0]);
940         tl_dio_write32(sc, TL_HASH2, hashes[1]);
941
942         return;
943 }
944
945 /*
946  * This routine is recommended by the ThunderLAN manual to insure that
947  * the internal PHY is powered up correctly. It also recommends a one
948  * second pause at the end to 'wait for the clocks to start' but in my
949  * experience this isn't necessary.
950  */
951 static void
952 tl_hardreset(device_t dev)
953 {
954         struct tl_softc         *sc;
955         int                     i;
956         u_int16_t               flags;
957
958         sc = device_get_softc(dev);
959
960         tl_mii_sync(sc);
961
962         flags = BMCR_LOOP|BMCR_ISO|BMCR_PDOWN;
963
964         for (i = 0; i < MII_NPHY; i++)
965                 tl_miibus_writereg(dev, i, MII_BMCR, flags);
966
967         tl_miibus_writereg(dev, 31, MII_BMCR, BMCR_ISO);
968         DELAY(50000);
969         tl_miibus_writereg(dev, 31, MII_BMCR, BMCR_LOOP|BMCR_ISO);
970         tl_mii_sync(sc);
971         while(tl_miibus_readreg(dev, 31, MII_BMCR) & BMCR_RESET);
972
973         DELAY(50000);
974         return;
975 }
976
977 static void
978 tl_softreset(struct tl_softc *sc, int internal)
979 {
980         u_int32_t               cmd, dummy, i;
981
982         /* Assert the adapter reset bit. */
983         CMD_SET(sc, TL_CMD_ADRST);
984
985         /* Turn off interrupts */
986         CMD_SET(sc, TL_CMD_INTSOFF);
987
988         /* First, clear the stats registers. */
989         for (i = 0; i < 5; i++)
990                 dummy = tl_dio_read32(sc, TL_TXGOODFRAMES);
991
992         /* Clear Areg and Hash registers */
993         for (i = 0; i < 8; i++)
994                 tl_dio_write32(sc, TL_AREG0_B5, 0x00000000);
995
996         /*
997          * Set up Netconfig register. Enable one channel and
998          * one fragment mode.
999          */
1000         tl_dio_setbit16(sc, TL_NETCONFIG, TL_CFG_ONECHAN|TL_CFG_ONEFRAG);
1001         if (internal && !sc->tl_bitrate) {
1002                 tl_dio_setbit16(sc, TL_NETCONFIG, TL_CFG_PHYEN);
1003         } else {
1004                 tl_dio_clrbit16(sc, TL_NETCONFIG, TL_CFG_PHYEN);
1005         }
1006
1007         /* Handle cards with bitrate devices. */
1008         if (sc->tl_bitrate)
1009                 tl_dio_setbit16(sc, TL_NETCONFIG, TL_CFG_BITRATE);
1010
1011         /*
1012          * Load adapter irq pacing timer and tx threshold.
1013          * We make the transmit threshold 1 initially but we may
1014          * change that later.
1015          */
1016         cmd = CSR_READ_4(sc, TL_HOSTCMD);
1017         cmd |= TL_CMD_NES;
1018         cmd &= ~(TL_CMD_RT|TL_CMD_EOC|TL_CMD_ACK_MASK|TL_CMD_CHSEL_MASK);
1019         CMD_PUT(sc, cmd | (TL_CMD_LDTHR | TX_THR));
1020         CMD_PUT(sc, cmd | (TL_CMD_LDTMR | 0x00000003));
1021
1022         /* Unreset the MII */
1023         tl_dio_setbit(sc, TL_NETSIO, TL_SIO_NMRST);
1024
1025         /* Take the adapter out of reset */
1026         tl_dio_setbit(sc, TL_NETCMD, TL_CMD_NRESET|TL_CMD_NWRAP);
1027
1028         /* Wait for things to settle down a little. */
1029         DELAY(500);
1030
1031         return;
1032 }
1033
1034 /*
1035  * Probe for a ThunderLAN chip. Check the PCI vendor and device IDs
1036  * against our list and return its name if we find a match.
1037  */
1038 static int
1039 tl_probe(device_t dev)
1040 {
1041         struct tl_type          *t;
1042
1043         t = tl_devs;
1044
1045         while(t->tl_name != NULL) {
1046                 if ((pci_get_vendor(dev) == t->tl_vid) &&
1047                     (pci_get_device(dev) == t->tl_did)) {
1048                         device_set_desc(dev, t->tl_name);
1049                         return(0);
1050                 }
1051                 t++;
1052         }
1053
1054         return(ENXIO);
1055 }
1056
1057 static int
1058 tl_attach(device_t dev)
1059 {
1060         int                     i;
1061         u_int16_t               did, vid;
1062         struct tl_type          *t;
1063         struct ifnet            *ifp;
1064         struct tl_softc         *sc;
1065         int                     error = 0, rid;
1066         uint8_t                 eaddr[ETHER_ADDR_LEN];
1067
1068         vid = pci_get_vendor(dev);
1069         did = pci_get_device(dev);
1070         sc = device_get_softc(dev);
1071
1072         t = tl_devs;
1073         while(t->tl_name != NULL) {
1074                 if (vid == t->tl_vid && did == t->tl_did)
1075                         break;
1076                 t++;
1077         }
1078
1079         KKASSERT(t->tl_name != NULL);
1080
1081         pci_enable_busmaster(dev);
1082
1083 #ifdef TL_USEIOSPACE
1084         rid = TL_PCI_LOIO;
1085         sc->tl_res = bus_alloc_resource_any(dev, SYS_RES_IOPORT, &rid,
1086                 RF_ACTIVE);
1087
1088         /*
1089          * Some cards have the I/O and memory mapped address registers
1090          * reversed. Try both combinations before giving up.
1091          */
1092         if (sc->tl_res == NULL) {
1093                 rid = TL_PCI_LOMEM;
1094                 sc->tl_res = bus_alloc_resource_any(dev, SYS_RES_IOPORT, &rid,
1095                     RF_ACTIVE);
1096         }
1097 #else
1098         rid = TL_PCI_LOMEM;
1099         sc->tl_res = bus_alloc_resource_any(dev, SYS_RES_MEMORY, &rid,
1100             RF_ACTIVE);
1101         if (sc->tl_res == NULL) {
1102                 rid = TL_PCI_LOIO;
1103                 sc->tl_res = bus_alloc_resource_any(dev, SYS_RES_MEMORY, &rid,
1104                     RF_ACTIVE);
1105         }
1106 #endif
1107
1108         if (sc->tl_res == NULL) {
1109                 device_printf(dev, "couldn't map ports/memory\n");
1110                 error = ENXIO;
1111                 return(error);
1112         }
1113
1114         sc->tl_btag = rman_get_bustag(sc->tl_res);
1115         sc->tl_bhandle = rman_get_bushandle(sc->tl_res);
1116
1117 #ifdef notdef
1118         /*
1119          * The ThunderLAN manual suggests jacking the PCI latency
1120          * timer all the way up to its maximum value. I'm not sure
1121          * if this is really necessary, but what the manual wants,
1122          * the manual gets.
1123          */
1124         command = pci_read_config(dev, TL_PCI_LATENCY_TIMER, 4);
1125         command |= 0x0000FF00;
1126         pci_write_config(dev, TL_PCI_LATENCY_TIMER, command, 4);
1127 #endif
1128
1129         /* Allocate interrupt */
1130         rid = 0;
1131         sc->tl_irq = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid,
1132             RF_SHAREABLE | RF_ACTIVE);
1133
1134         if (sc->tl_irq == NULL) {
1135                 device_printf(dev, "couldn't map interrupt\n");
1136                 error = ENXIO;
1137                 goto fail;
1138         }
1139
1140         /*
1141          * Now allocate memory for the TX and RX lists.
1142          */
1143         sc->tl_ldata = contigmalloc(sizeof(struct tl_list_data), M_DEVBUF,
1144             M_WAITOK, 0, 0xffffffff, PAGE_SIZE, 0);
1145
1146         if (sc->tl_ldata == NULL) {
1147                 device_printf(dev, "no memory for list buffers!\n");
1148                 error = ENXIO;
1149                 goto fail;
1150         }
1151
1152         bzero(sc->tl_ldata, sizeof(struct tl_list_data));
1153
1154         sc->tl_dinfo = t;
1155         if (t->tl_vid == COMPAQ_VENDORID || t->tl_vid == TI_VENDORID)
1156                 sc->tl_eeaddr = TL_EEPROM_EADDR;
1157         if (t->tl_vid == OLICOM_VENDORID)
1158                 sc->tl_eeaddr = TL_EEPROM_EADDR_OC;
1159
1160         /* Reset the adapter. */
1161         tl_softreset(sc, 1);
1162         tl_hardreset(dev);
1163         tl_softreset(sc, 1);
1164
1165         ifp = &sc->arpcom.ac_if;
1166         if_initname(ifp, device_get_name(dev), device_get_unit(dev));
1167
1168         /*
1169          * Get station address from the EEPROM.
1170          */
1171         if (tl_read_eeprom(sc, eaddr, sc->tl_eeaddr, ETHER_ADDR_LEN)) {
1172                 device_printf(dev, "failed to read station address\n");
1173                 error = ENXIO;
1174                 goto fail;
1175         }
1176
1177         /*
1178          * XXX Olicom, in its desire to be different from the
1179          * rest of the world, has done strange things with the
1180          * encoding of the station address in the EEPROM. First
1181          * of all, they store the address at offset 0xF8 rather
1182          * than at 0x83 like the ThunderLAN manual suggests.
1183          * Second, they store the address in three 16-bit words in
1184          * network byte order, as opposed to storing it sequentially
1185          * like all the other ThunderLAN cards. In order to get
1186          * the station address in a form that matches what the Olicom
1187          * diagnostic utility specifies, we have to byte-swap each
1188          * word. To make things even more confusing, neither 00:00:28
1189          * nor 00:00:24 appear in the IEEE OUI database.
1190          */
1191         if (sc->tl_dinfo->tl_vid == OLICOM_VENDORID) {
1192                 for (i = 0; i < ETHER_ADDR_LEN; i += 2) {
1193                         u_int16_t               *p;
1194                         p = (u_int16_t *)&eaddr[i];
1195                         *p = ntohs(*p);
1196                 }
1197         }
1198
1199         ifp->if_softc = sc;
1200         ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
1201         ifp->if_ioctl = tl_ioctl;
1202         ifp->if_start = tl_start;
1203         ifp->if_watchdog = tl_watchdog;
1204         ifp->if_init = tl_init;
1205         ifp->if_mtu = ETHERMTU;
1206         ifq_set_maxlen(&ifp->if_snd, TL_TX_LIST_CNT - 1);
1207         ifq_set_ready(&ifp->if_snd);
1208         callout_init(&sc->tl_stat_timer);
1209
1210         /* Reset the adapter again. */
1211         tl_softreset(sc, 1);
1212         tl_hardreset(dev);
1213         tl_softreset(sc, 1);
1214
1215         /*
1216          * Do MII setup. If no PHYs are found, then this is a
1217          * bitrate ThunderLAN chip that only supports 10baseT
1218          * and AUI/BNC.
1219          */
1220         if (mii_phy_probe(dev, &sc->tl_miibus,
1221             tl_ifmedia_upd, tl_ifmedia_sts)) {
1222                 struct ifmedia          *ifm;
1223                 sc->tl_bitrate = 1;
1224                 ifmedia_init(&sc->ifmedia, 0, tl_ifmedia_upd, tl_ifmedia_sts);
1225                 ifmedia_add(&sc->ifmedia, IFM_ETHER|IFM_10_T, 0, NULL);
1226                 ifmedia_add(&sc->ifmedia, IFM_ETHER|IFM_10_T|IFM_HDX, 0, NULL);
1227                 ifmedia_add(&sc->ifmedia, IFM_ETHER|IFM_10_T|IFM_FDX, 0, NULL);
1228                 ifmedia_add(&sc->ifmedia, IFM_ETHER|IFM_10_5, 0, NULL);
1229                 ifmedia_set(&sc->ifmedia, IFM_ETHER|IFM_10_T);
1230                 /* Reset again, this time setting bitrate mode. */
1231                 tl_softreset(sc, 1);
1232                 ifm = &sc->ifmedia;
1233                 ifm->ifm_media = ifm->ifm_cur->ifm_media;
1234                 tl_ifmedia_upd(ifp);
1235         }
1236
1237         /*
1238          * Call MI attach routine.
1239          */
1240         ether_ifattach(ifp, eaddr, NULL);
1241
1242         error = bus_setup_intr(dev, sc->tl_irq, INTR_NETSAFE,
1243                                tl_intr, sc, &sc->tl_intrhand, 
1244                                ifp->if_serializer);
1245
1246         if (error) {
1247                 ether_ifdetach(ifp);
1248                 device_printf(dev, "couldn't set up irq\n");
1249                 goto fail;
1250         }
1251
1252         return(0);
1253
1254 fail:
1255         tl_detach(dev);
1256         return(error);
1257 }
1258
1259 static int
1260 tl_detach(device_t dev)
1261 {
1262         struct tl_softc *sc = device_get_softc(dev);
1263         struct ifnet *ifp = &sc->arpcom.ac_if;
1264
1265         if (device_is_attached(dev)) {
1266                 lwkt_serialize_enter(ifp->if_serializer);
1267                 tl_stop(sc);
1268                 bus_teardown_intr(dev, sc->tl_irq, sc->tl_intrhand);
1269                 lwkt_serialize_exit(ifp->if_serializer);
1270
1271                 ether_ifdetach(ifp);
1272         }
1273
1274         if (sc->tl_miibus)
1275                 device_delete_child(dev, sc->tl_miibus);
1276         bus_generic_detach(dev);
1277
1278         if (sc->tl_ldata)
1279                 contigfree(sc->tl_ldata, sizeof(struct tl_list_data), M_DEVBUF);
1280         if (sc->tl_bitrate)
1281                 ifmedia_removeall(&sc->ifmedia);
1282         if (sc->tl_irq)
1283                 bus_release_resource(dev, SYS_RES_IRQ, 0, sc->tl_irq);
1284         if (sc->tl_res)
1285                 bus_release_resource(dev, TL_RES, TL_RID, sc->tl_res);
1286
1287         return(0);
1288 }
1289
1290 /*
1291  * Initialize the transmit lists.
1292  */
1293 static int
1294 tl_list_tx_init(struct tl_softc *sc)
1295 {
1296         struct tl_chain_data    *cd;
1297         struct tl_list_data     *ld;
1298         int                     i;
1299
1300         cd = &sc->tl_cdata;
1301         ld = sc->tl_ldata;
1302         for (i = 0; i < TL_TX_LIST_CNT; i++) {
1303                 cd->tl_tx_chain[i].tl_ptr = &ld->tl_tx_list[i];
1304                 if (i == (TL_TX_LIST_CNT - 1))
1305                         cd->tl_tx_chain[i].tl_next = NULL;
1306                 else
1307                         cd->tl_tx_chain[i].tl_next = &cd->tl_tx_chain[i + 1];
1308         }
1309
1310         cd->tl_tx_free = &cd->tl_tx_chain[0];
1311         cd->tl_tx_tail = cd->tl_tx_head = NULL;
1312         sc->tl_txeoc = 1;
1313
1314         return(0);
1315 }
1316
1317 /*
1318  * Initialize the RX lists and allocate mbufs for them.
1319  */
1320 static int
1321 tl_list_rx_init(struct tl_softc *sc)
1322 {
1323         struct tl_chain_data    *cd;
1324         struct tl_list_data     *ld;
1325         int                     i;
1326
1327         cd = &sc->tl_cdata;
1328         ld = sc->tl_ldata;
1329
1330         for (i = 0; i < TL_RX_LIST_CNT; i++) {
1331                 cd->tl_rx_chain[i].tl_ptr =
1332                         (struct tl_list_onefrag *)&ld->tl_rx_list[i];
1333                 if (tl_newbuf(sc, &cd->tl_rx_chain[i]) == ENOBUFS)
1334                         return(ENOBUFS);
1335                 if (i == (TL_RX_LIST_CNT - 1)) {
1336                         cd->tl_rx_chain[i].tl_next = NULL;
1337                         ld->tl_rx_list[i].tlist_fptr = 0;
1338                 } else {
1339                         cd->tl_rx_chain[i].tl_next = &cd->tl_rx_chain[i + 1];
1340                         ld->tl_rx_list[i].tlist_fptr =
1341                                         vtophys(&ld->tl_rx_list[i + 1]);
1342                 }
1343         }
1344
1345         cd->tl_rx_head = &cd->tl_rx_chain[0];
1346         cd->tl_rx_tail = &cd->tl_rx_chain[TL_RX_LIST_CNT - 1];
1347
1348         return(0);
1349 }
1350
1351 static int
1352 tl_newbuf(struct tl_softc *sc, struct tl_chain_onefrag *c)
1353 {
1354         struct mbuf *m_new;
1355
1356         m_new = m_getcl(MB_DONTWAIT, MT_DATA, M_PKTHDR);
1357         if (m_new == NULL)
1358                 return (ENOBUFS);
1359
1360         c->tl_mbuf = m_new;
1361         c->tl_next = NULL;
1362         c->tl_ptr->tlist_frsize = MCLBYTES;
1363         c->tl_ptr->tlist_fptr = 0;
1364         c->tl_ptr->tl_frag.tlist_dadr = vtophys(mtod(m_new, caddr_t));
1365         c->tl_ptr->tl_frag.tlist_dcnt = MCLBYTES;
1366         c->tl_ptr->tlist_cstat = TL_CSTAT_READY;
1367
1368         return(0);
1369 }
1370
1371 /*
1372  * Interrupt handler for RX 'end of frame' condition (EOF). This
1373  * tells us that a full ethernet frame has been captured and we need
1374  * to handle it.
1375  *
1376  * Reception is done using 'lists' which consist of a header and a
1377  * series of 10 data count/data address pairs that point to buffers.
1378  * Initially you're supposed to create a list, populate it with pointers
1379  * to buffers, then load the physical address of the list into the
1380  * ch_parm register. The adapter is then supposed to DMA the received
1381  * frame into the buffers for you.
1382  *
1383  * To make things as fast as possible, we have the chip DMA directly
1384  * into mbufs. This saves us from having to do a buffer copy: we can
1385  * just hand the mbufs directly to ether_input(). Once the frame has
1386  * been sent on its way, the 'list' structure is assigned a new buffer
1387  * and moved to the end of the RX chain. As long we we stay ahead of
1388  * the chip, it will always think it has an endless receive channel.
1389  *
1390  * If we happen to fall behind and the chip manages to fill up all of
1391  * the buffers, it will generate an end of channel interrupt and wait
1392  * for us to empty the chain and restart the receiver.
1393  */
1394 static int
1395 tl_intvec_rxeof(void *xsc, u_int32_t type)
1396 {
1397         struct tl_softc         *sc;
1398         int                     r = 0, total_len = 0;
1399         struct ether_header     *eh;
1400         struct mbuf             *m;
1401         struct ifnet            *ifp;
1402         struct tl_chain_onefrag *cur_rx;
1403
1404         sc = xsc;
1405         ifp = &sc->arpcom.ac_if;
1406
1407         while(sc->tl_cdata.tl_rx_head != NULL) {
1408                 cur_rx = sc->tl_cdata.tl_rx_head;
1409                 if (!(cur_rx->tl_ptr->tlist_cstat & TL_CSTAT_FRAMECMP))
1410                         break;
1411                 r++;
1412                 sc->tl_cdata.tl_rx_head = cur_rx->tl_next;
1413                 m = cur_rx->tl_mbuf;
1414                 total_len = cur_rx->tl_ptr->tlist_frsize;
1415
1416                 if (tl_newbuf(sc, cur_rx) == ENOBUFS) {
1417                         ifp->if_ierrors++;
1418                         cur_rx->tl_ptr->tlist_frsize = MCLBYTES;
1419                         cur_rx->tl_ptr->tlist_cstat = TL_CSTAT_READY;
1420                         cur_rx->tl_ptr->tl_frag.tlist_dcnt = MCLBYTES;
1421                         continue;
1422                 }
1423
1424                 sc->tl_cdata.tl_rx_tail->tl_ptr->tlist_fptr =
1425                                                 vtophys(cur_rx->tl_ptr);
1426                 sc->tl_cdata.tl_rx_tail->tl_next = cur_rx;
1427                 sc->tl_cdata.tl_rx_tail = cur_rx;
1428
1429                 eh = mtod(m, struct ether_header *);
1430                 m->m_pkthdr.rcvif = ifp;
1431                 m->m_pkthdr.len = m->m_len = total_len;
1432
1433                 /*
1434                  * Note: when the ThunderLAN chip is in 'capture all
1435                  * frames' mode, it will receive its own transmissions.
1436                  * We drop don't need to process our own transmissions,
1437                  * so we drop them here and continue.
1438                  */
1439                 /*if (ifp->if_flags & IFF_PROMISC && */
1440                 if (!bcmp(eh->ether_shost, sc->arpcom.ac_enaddr,
1441                                                         ETHER_ADDR_LEN)) {
1442                                 m_freem(m);
1443                                 continue;
1444                 }
1445
1446                 ifp->if_input(ifp, m);
1447         }
1448
1449         return(r);
1450 }
1451
1452 /*
1453  * The RX-EOC condition hits when the ch_parm address hasn't been
1454  * initialized or the adapter reached a list with a forward pointer
1455  * of 0 (which indicates the end of the chain). In our case, this means
1456  * the card has hit the end of the receive buffer chain and we need to
1457  * empty out the buffers and shift the pointer back to the beginning again.
1458  */
1459 static int
1460 tl_intvec_rxeoc(void *xsc, u_int32_t type)
1461 {
1462         struct tl_softc         *sc;
1463         int                     r;
1464         struct tl_chain_data    *cd;
1465
1466
1467         sc = xsc;
1468         cd = &sc->tl_cdata;
1469
1470         /* Flush out the receive queue and ack RXEOF interrupts. */
1471         r = tl_intvec_rxeof(xsc, type);
1472         CMD_PUT(sc, TL_CMD_ACK | r | (type & ~(0x00100000)));
1473         r = 1;
1474         cd->tl_rx_head = &cd->tl_rx_chain[0];
1475         cd->tl_rx_tail = &cd->tl_rx_chain[TL_RX_LIST_CNT - 1];
1476         CSR_WRITE_4(sc, TL_CH_PARM, vtophys(sc->tl_cdata.tl_rx_head->tl_ptr));
1477         r |= (TL_CMD_GO|TL_CMD_RT);
1478         return(r);
1479 }
1480
1481 static int
1482 tl_intvec_txeof(void *xsc, u_int32_t type)
1483 {
1484         struct tl_softc         *sc;
1485         int                     r = 0;
1486         struct tl_chain         *cur_tx;
1487
1488         sc = xsc;
1489
1490         /*
1491          * Go through our tx list and free mbufs for those
1492          * frames that have been sent.
1493          */
1494         while (sc->tl_cdata.tl_tx_head != NULL) {
1495                 cur_tx = sc->tl_cdata.tl_tx_head;
1496                 if (!(cur_tx->tl_ptr->tlist_cstat & TL_CSTAT_FRAMECMP))
1497                         break;
1498                 sc->tl_cdata.tl_tx_head = cur_tx->tl_next;
1499
1500                 r++;
1501                 m_freem(cur_tx->tl_mbuf);
1502                 cur_tx->tl_mbuf = NULL;
1503
1504                 cur_tx->tl_next = sc->tl_cdata.tl_tx_free;
1505                 sc->tl_cdata.tl_tx_free = cur_tx;
1506                 if (!cur_tx->tl_ptr->tlist_fptr)
1507                         break;
1508         }
1509
1510         return(r);
1511 }
1512
1513 /*
1514  * The transmit end of channel interrupt. The adapter triggers this
1515  * interrupt to tell us it hit the end of the current transmit list.
1516  *
1517  * A note about this: it's possible for a condition to arise where
1518  * tl_start() may try to send frames between TXEOF and TXEOC interrupts.
1519  * You have to avoid this since the chip expects things to go in a
1520  * particular order: transmit, acknowledge TXEOF, acknowledge TXEOC.
1521  * When the TXEOF handler is called, it will free all of the transmitted
1522  * frames and reset the tx_head pointer to NULL. However, a TXEOC
1523  * interrupt should be received and acknowledged before any more frames
1524  * are queued for transmission. If tl_statrt() is called after TXEOF
1525  * resets the tx_head pointer but _before_ the TXEOC interrupt arrives,
1526  * it could attempt to issue a transmit command prematurely.
1527  *
1528  * To guard against this, tl_start() will only issue transmit commands
1529  * if the tl_txeoc flag is set, and only the TXEOC interrupt handler
1530  * can set this flag once tl_start() has cleared it.
1531  */
1532 static int
1533 tl_intvec_txeoc(void *xsc, u_int32_t type)
1534 {
1535         struct tl_softc         *sc;
1536         struct ifnet            *ifp;
1537         u_int32_t               cmd;
1538
1539         sc = xsc;
1540         ifp = &sc->arpcom.ac_if;
1541
1542         /* Clear the timeout timer. */
1543         ifp->if_timer = 0;
1544
1545         if (sc->tl_cdata.tl_tx_head == NULL) {
1546                 ifp->if_flags &= ~IFF_OACTIVE;
1547                 sc->tl_cdata.tl_tx_tail = NULL;
1548                 sc->tl_txeoc = 1;
1549         } else {
1550                 sc->tl_txeoc = 0;
1551                 /* First we have to ack the EOC interrupt. */
1552                 CMD_PUT(sc, TL_CMD_ACK | 0x00000001 | type);
1553                 /* Then load the address of the next TX list. */
1554                 CSR_WRITE_4(sc, TL_CH_PARM,
1555                     vtophys(sc->tl_cdata.tl_tx_head->tl_ptr));
1556                 /* Restart TX channel. */
1557                 cmd = CSR_READ_4(sc, TL_HOSTCMD);
1558                 cmd &= ~TL_CMD_RT;
1559                 cmd |= TL_CMD_GO|TL_CMD_INTSON;
1560                 CMD_PUT(sc, cmd);
1561                 return(0);
1562         }
1563
1564         return(1);
1565 }
1566
1567 static int
1568 tl_intvec_adchk(void *xsc, u_int32_t type)
1569 {
1570         struct tl_softc         *sc;
1571
1572         sc = xsc;
1573
1574         if (type) {
1575                 if_printf(&sc->arpcom.ac_if, "adapter check: %x\n",
1576                           (unsigned int)CSR_READ_4(sc, TL_CH_PARM));
1577         }
1578
1579         tl_softreset(sc, 1);
1580         tl_stop(sc);
1581         tl_init(sc);
1582         CMD_SET(sc, TL_CMD_INTSON);
1583
1584         return(0);
1585 }
1586
1587 static int
1588 tl_intvec_netsts(void *xsc, u_int32_t type)
1589 {
1590         struct tl_softc         *sc;
1591         u_int16_t               netsts;
1592
1593         sc = xsc;
1594
1595         netsts = tl_dio_read16(sc, TL_NETSTS);
1596         tl_dio_write16(sc, TL_NETSTS, netsts);
1597
1598         if_printf(&sc->arpcom.ac_if, "network status: %x\n", netsts);
1599
1600         return(1);
1601 }
1602
1603 static void
1604 tl_intr(void *xsc)
1605 {
1606         struct tl_softc         *sc;
1607         struct ifnet            *ifp;
1608         int                     r = 0;
1609         u_int32_t               type = 0;
1610         u_int16_t               ints = 0;
1611         u_int8_t                ivec = 0;
1612
1613         sc = xsc;
1614
1615         /* Disable interrupts */
1616         ints = CSR_READ_2(sc, TL_HOST_INT);
1617         CSR_WRITE_2(sc, TL_HOST_INT, ints);
1618         type = (ints << 16) & 0xFFFF0000;
1619         ivec = (ints & TL_VEC_MASK) >> 5;
1620         ints = (ints & TL_INT_MASK) >> 2;
1621
1622         ifp = &sc->arpcom.ac_if;
1623
1624         switch(ints) {
1625         case (TL_INTR_INVALID):
1626 #ifdef DIAGNOSTIC
1627                 if_printf(ifp, "got an invalid interrupt!\n");
1628 #endif
1629                 /* Re-enable interrupts but don't ack this one. */
1630                 CMD_PUT(sc, type);
1631                 r = 0;
1632                 break;
1633         case (TL_INTR_TXEOF):
1634                 r = tl_intvec_txeof((void *)sc, type);
1635                 break;
1636         case (TL_INTR_TXEOC):
1637                 r = tl_intvec_txeoc((void *)sc, type);
1638                 break;
1639         case (TL_INTR_STATOFLOW):
1640                 tl_stats_update_serialized(sc);
1641                 r = 1;
1642                 break;
1643         case (TL_INTR_RXEOF):
1644                 r = tl_intvec_rxeof((void *)sc, type);
1645                 break;
1646         case (TL_INTR_DUMMY):
1647                 if_printf(ifp, "got a dummy interrupt\n");
1648                 r = 1;
1649                 break;
1650         case (TL_INTR_ADCHK):
1651                 if (ivec)
1652                         r = tl_intvec_adchk((void *)sc, type);
1653                 else
1654                         r = tl_intvec_netsts((void *)sc, type);
1655                 break;
1656         case (TL_INTR_RXEOC):
1657                 r = tl_intvec_rxeoc((void *)sc, type);
1658                 break;
1659         default:
1660                 if_printf(ifp, "bogus interrupt type\n");
1661                 break;
1662         }
1663
1664         /* Re-enable interrupts */
1665         if (r) {
1666                 CMD_PUT(sc, TL_CMD_ACK | r | type);
1667         }
1668
1669         if (!ifq_is_empty(&ifp->if_snd))
1670                 tl_start(ifp);
1671
1672         return;
1673 }
1674
1675 static 
1676 void
1677 tl_stats_update(void *xsc)
1678 {
1679         struct tl_softc *sc = xsc;
1680         struct ifnet *ifp = &sc->arpcom.ac_if;
1681
1682         lwkt_serialize_enter(ifp->if_serializer);
1683         tl_stats_update_serialized(xsc);
1684         lwkt_serialize_exit(ifp->if_serializer);
1685 }
1686
1687 static 
1688 void
1689 tl_stats_update_serialized(void *xsc)
1690 {
1691         struct tl_softc         *sc;
1692         struct ifnet            *ifp;
1693         struct tl_stats         tl_stats;
1694         struct mii_data         *mii;
1695         u_int32_t               *p;
1696
1697         bzero((char *)&tl_stats, sizeof(struct tl_stats));
1698
1699         sc = xsc;
1700         ifp = &sc->arpcom.ac_if;
1701
1702         p = (u_int32_t *)&tl_stats;
1703
1704         CSR_WRITE_2(sc, TL_DIO_ADDR, TL_TXGOODFRAMES|TL_DIO_ADDR_INC);
1705         *p++ = CSR_READ_4(sc, TL_DIO_DATA);
1706         *p++ = CSR_READ_4(sc, TL_DIO_DATA);
1707         *p++ = CSR_READ_4(sc, TL_DIO_DATA);
1708         *p++ = CSR_READ_4(sc, TL_DIO_DATA);
1709         *p++ = CSR_READ_4(sc, TL_DIO_DATA);
1710
1711         ifp->if_opackets += tl_tx_goodframes(tl_stats);
1712         ifp->if_collisions += tl_stats.tl_tx_single_collision +
1713                                 tl_stats.tl_tx_multi_collision;
1714         ifp->if_ipackets += tl_rx_goodframes(tl_stats);
1715         ifp->if_ierrors += tl_stats.tl_crc_errors + tl_stats.tl_code_errors +
1716                             tl_rx_overrun(tl_stats);
1717         ifp->if_oerrors += tl_tx_underrun(tl_stats);
1718
1719         if (tl_tx_underrun(tl_stats)) {
1720                 u_int8_t                tx_thresh;
1721                 tx_thresh = tl_dio_read8(sc, TL_ACOMMIT) & TL_AC_TXTHRESH;
1722                 if (tx_thresh != TL_AC_TXTHRESH_WHOLEPKT) {
1723                         tx_thresh >>= 4;
1724                         tx_thresh++;
1725                         if_printf(ifp, "tx underrun -- increasing "
1726                                   "tx threshold to %d bytes\n",
1727                                   (64 * (tx_thresh * 4)));
1728                         tl_dio_clrbit(sc, TL_ACOMMIT, TL_AC_TXTHRESH);
1729                         tl_dio_setbit(sc, TL_ACOMMIT, tx_thresh << 4);
1730                 }
1731         }
1732
1733         callout_reset(&sc->tl_stat_timer, hz, tl_stats_update, sc);
1734
1735         if (!sc->tl_bitrate) {
1736                 mii = device_get_softc(sc->tl_miibus);
1737                 mii_tick(mii);
1738         }
1739 }
1740
1741 /*
1742  * Encapsulate an mbuf chain in a list by coupling the mbuf data
1743  * pointers to the fragment pointers.
1744  */
1745 static int
1746 tl_encap(struct tl_softc *sc, struct tl_chain *c, struct mbuf *m_head)
1747 {
1748         int                     frag = 0;
1749         struct tl_frag          *f = NULL;
1750         int                     total_len;
1751         struct mbuf             *m;
1752
1753         /*
1754          * Start packing the mbufs in this chain into
1755          * the fragment pointers. Stop when we run out
1756          * of fragments or hit the end of the mbuf chain.
1757          */
1758         m = m_head;
1759         total_len = 0;
1760
1761         for (m = m_head, frag = 0; m != NULL; m = m->m_next) {
1762                 if (m->m_len != 0) {
1763                         if (frag == TL_MAXFRAGS)
1764                                 break;
1765                         total_len+= m->m_len;
1766                         c->tl_ptr->tl_frag[frag].tlist_dadr =
1767                                 vtophys(mtod(m, vm_offset_t));
1768                         c->tl_ptr->tl_frag[frag].tlist_dcnt = m->m_len;
1769                         frag++;
1770                 }
1771         }
1772
1773         /*
1774          * Handle special cases.
1775          * Special case #1: we used up all 10 fragments, but
1776          * we have more mbufs left in the chain. Copy the
1777          * data into an mbuf cluster. Note that we don't
1778          * bother clearing the values in the other fragment
1779          * pointers/counters; it wouldn't gain us anything,
1780          * and would waste cycles.
1781          */
1782         if (m != NULL) {
1783                 struct mbuf *m_new;
1784
1785                 m_new = m_getl(m_head->m_pkthdr.len, MB_DONTWAIT, MT_DATA,
1786                                M_PKTHDR, NULL);
1787                 if (m_new == NULL) {
1788                         if_printf(&sc->arpcom.ac_if, "no memory for tx list\n");
1789                         return (1);
1790                 }
1791                 m_copydata(m_head, 0, m_head->m_pkthdr.len,     
1792                                         mtod(m_new, caddr_t));
1793                 m_new->m_pkthdr.len = m_new->m_len = m_head->m_pkthdr.len;
1794                 m_freem(m_head);
1795                 m_head = m_new;
1796                 f = &c->tl_ptr->tl_frag[0];
1797                 f->tlist_dadr = vtophys(mtod(m_new, caddr_t));
1798                 f->tlist_dcnt = total_len = m_new->m_len;
1799                 frag = 1;
1800         }
1801
1802         /*
1803          * Special case #2: the frame is smaller than the minimum
1804          * frame size. We have to pad it to make the chip happy.
1805          */
1806         if (total_len < TL_MIN_FRAMELEN) {
1807                 if (frag == TL_MAXFRAGS) {
1808                         if_printf(&sc->arpcom.ac_if, "all frags filled but "
1809                                   "frame still to small!\n");
1810                 }
1811                 f = &c->tl_ptr->tl_frag[frag];
1812                 f->tlist_dcnt = TL_MIN_FRAMELEN - total_len;
1813                 f->tlist_dadr = vtophys(&sc->tl_ldata->tl_pad);
1814                 total_len += f->tlist_dcnt;
1815                 frag++;
1816         }
1817
1818         c->tl_mbuf = m_head;
1819         c->tl_ptr->tl_frag[frag - 1].tlist_dcnt |= TL_LAST_FRAG;
1820         c->tl_ptr->tlist_frsize = total_len;
1821         c->tl_ptr->tlist_cstat = TL_CSTAT_READY;
1822         c->tl_ptr->tlist_fptr = 0;
1823
1824         return(0);
1825 }
1826
1827 /*
1828  * Main transmit routine. To avoid having to do mbuf copies, we put pointers
1829  * to the mbuf data regions directly in the transmit lists. We also save a
1830  * copy of the pointers since the transmit list fragment pointers are
1831  * physical addresses.
1832  */
1833 static void
1834 tl_start(struct ifnet *ifp)
1835 {
1836         struct tl_softc         *sc;
1837         struct mbuf             *m_head = NULL;
1838         u_int32_t               cmd;
1839         struct tl_chain         *prev = NULL, *cur_tx = NULL, *start_tx;
1840
1841         sc = ifp->if_softc;
1842
1843         /*
1844          * Check for an available queue slot. If there are none,
1845          * punt.
1846          */
1847         if (sc->tl_cdata.tl_tx_free == NULL) {
1848                 ifp->if_flags |= IFF_OACTIVE;
1849                 return;
1850         }
1851
1852         start_tx = sc->tl_cdata.tl_tx_free;
1853
1854         while(sc->tl_cdata.tl_tx_free != NULL) {
1855                 m_head = ifq_dequeue(&ifp->if_snd, NULL);
1856                 if (m_head == NULL)
1857                         break;
1858
1859                 /* Pick a chain member off the free list. */
1860                 cur_tx = sc->tl_cdata.tl_tx_free;
1861                 sc->tl_cdata.tl_tx_free = cur_tx->tl_next;
1862
1863                 cur_tx->tl_next = NULL;
1864
1865                 /* Pack the data into the list. */
1866                 tl_encap(sc, cur_tx, m_head);
1867
1868                 /* Chain it together */
1869                 if (prev != NULL) {
1870                         prev->tl_next = cur_tx;
1871                         prev->tl_ptr->tlist_fptr = vtophys(cur_tx->tl_ptr);
1872                 }
1873                 prev = cur_tx;
1874
1875                 BPF_MTAP(ifp, cur_tx->tl_mbuf);
1876         }
1877
1878         /*
1879          * If there are no packets queued, bail.
1880          */
1881         if (cur_tx == NULL)
1882                 return;
1883
1884         /*
1885          * That's all we can stands, we can't stands no more.
1886          * If there are no other transfers pending, then issue the
1887          * TX GO command to the adapter to start things moving.
1888          * Otherwise, just leave the data in the queue and let
1889          * the EOF/EOC interrupt handler send.
1890          */
1891         if (sc->tl_cdata.tl_tx_head == NULL) {
1892                 sc->tl_cdata.tl_tx_head = start_tx;
1893                 sc->tl_cdata.tl_tx_tail = cur_tx;
1894
1895                 if (sc->tl_txeoc) {
1896                         sc->tl_txeoc = 0;
1897                         CSR_WRITE_4(sc, TL_CH_PARM, vtophys(start_tx->tl_ptr));
1898                         cmd = CSR_READ_4(sc, TL_HOSTCMD);
1899                         cmd &= ~TL_CMD_RT;
1900                         cmd |= TL_CMD_GO|TL_CMD_INTSON;
1901                         CMD_PUT(sc, cmd);
1902                 }
1903         } else {
1904                 sc->tl_cdata.tl_tx_tail->tl_next = start_tx;
1905                 sc->tl_cdata.tl_tx_tail = cur_tx;
1906         }
1907
1908         /*
1909          * Set a timeout in case the chip goes out to lunch.
1910          */
1911         ifp->if_timer = 5;
1912
1913         return;
1914 }
1915
1916 static void
1917 tl_init(void *xsc)
1918 {
1919         struct tl_softc         *sc = xsc;
1920         struct ifnet            *ifp = &sc->arpcom.ac_if;
1921         struct mii_data         *mii;
1922
1923         /*
1924          * Cancel pending I/O.
1925          */
1926         tl_stop(sc);
1927
1928         /* Initialize TX FIFO threshold */
1929         tl_dio_clrbit(sc, TL_ACOMMIT, TL_AC_TXTHRESH);
1930         tl_dio_setbit(sc, TL_ACOMMIT, TL_AC_TXTHRESH_16LONG);
1931
1932         /* Set PCI burst size */
1933         tl_dio_write8(sc, TL_BSIZEREG, TL_RXBURST_16LONG|TL_TXBURST_16LONG);
1934
1935         /*
1936          * Set 'capture all frames' bit for promiscuous mode.
1937          */
1938         if (ifp->if_flags & IFF_PROMISC)
1939                 tl_dio_setbit(sc, TL_NETCMD, TL_CMD_CAF);
1940         else
1941                 tl_dio_clrbit(sc, TL_NETCMD, TL_CMD_CAF);
1942
1943         /*
1944          * Set capture broadcast bit to capture broadcast frames.
1945          */
1946         if (ifp->if_flags & IFF_BROADCAST)
1947                 tl_dio_clrbit(sc, TL_NETCMD, TL_CMD_NOBRX);
1948         else
1949                 tl_dio_setbit(sc, TL_NETCMD, TL_CMD_NOBRX);
1950
1951         tl_dio_write16(sc, TL_MAXRX, MCLBYTES);
1952
1953         /* Init our MAC address */
1954         tl_setfilt(sc, (caddr_t)&sc->arpcom.ac_enaddr, 0);
1955
1956         /* Init multicast filter, if needed. */
1957         tl_setmulti(sc);
1958
1959         /* Init circular RX list. */
1960         if (tl_list_rx_init(sc) == ENOBUFS) {
1961                 if_printf(ifp, "initialization failed: no "
1962                           "memory for rx buffers\n");
1963                 tl_stop(sc);
1964                 return;
1965         }
1966
1967         /* Init TX pointers. */
1968         tl_list_tx_init(sc);
1969
1970         /* Enable PCI interrupts. */
1971         CMD_SET(sc, TL_CMD_INTSON);
1972
1973         /* Load the address of the rx list */
1974         CMD_SET(sc, TL_CMD_RT);
1975         CSR_WRITE_4(sc, TL_CH_PARM, vtophys(&sc->tl_ldata->tl_rx_list[0]));
1976
1977         if (!sc->tl_bitrate) {
1978                 if (sc->tl_miibus != NULL) {
1979                         mii = device_get_softc(sc->tl_miibus);
1980                         mii_mediachg(mii);
1981                 }
1982         }
1983
1984         /* Send the RX go command */
1985         CMD_SET(sc, TL_CMD_GO|TL_CMD_NES|TL_CMD_RT);
1986
1987         ifp->if_flags |= IFF_RUNNING;
1988         ifp->if_flags &= ~IFF_OACTIVE;
1989
1990         /* Start the stats update counter */
1991         callout_reset(&sc->tl_stat_timer, hz, tl_stats_update, sc);
1992 }
1993
1994 /*
1995  * Set media options.
1996  */
1997 static int
1998 tl_ifmedia_upd(struct ifnet *ifp)
1999 {
2000         struct tl_softc         *sc;
2001         struct mii_data         *mii = NULL;
2002
2003         sc = ifp->if_softc;
2004
2005         if (sc->tl_bitrate)
2006                 tl_setmode(sc, sc->ifmedia.ifm_media);
2007         else {
2008                 mii = device_get_softc(sc->tl_miibus);
2009                 mii_mediachg(mii);
2010         }
2011
2012         return(0);
2013 }
2014
2015 /*
2016  * Report current media status.
2017  */
2018 static void
2019 tl_ifmedia_sts(struct ifnet *ifp, struct ifmediareq *ifmr)
2020 {
2021         struct tl_softc         *sc;
2022         struct mii_data         *mii;
2023
2024         sc = ifp->if_softc;
2025
2026         ifmr->ifm_active = IFM_ETHER;
2027
2028         if (sc->tl_bitrate) {
2029                 if (tl_dio_read8(sc, TL_ACOMMIT) & TL_AC_MTXD1)
2030                         ifmr->ifm_active = IFM_ETHER|IFM_10_5;
2031                 else
2032                         ifmr->ifm_active = IFM_ETHER|IFM_10_T;
2033                 if (tl_dio_read8(sc, TL_ACOMMIT) & TL_AC_MTXD3)
2034                         ifmr->ifm_active |= IFM_HDX;
2035                 else
2036                         ifmr->ifm_active |= IFM_FDX;
2037                 return;
2038         } else {
2039                 mii = device_get_softc(sc->tl_miibus);
2040                 mii_pollstat(mii);
2041                 ifmr->ifm_active = mii->mii_media_active;
2042                 ifmr->ifm_status = mii->mii_media_status;
2043         }
2044
2045         return;
2046 }
2047
2048 static int
2049 tl_ioctl(struct ifnet *ifp, u_long command, caddr_t data, struct ucred *cr)
2050 {
2051         struct tl_softc         *sc = ifp->if_softc;
2052         struct ifreq            *ifr = (struct ifreq *) data;
2053         int                     error = 0;
2054
2055         switch(command) {
2056         case SIOCSIFFLAGS:
2057                 if (ifp->if_flags & IFF_UP) {
2058                         if (ifp->if_flags & IFF_RUNNING &&
2059                             ifp->if_flags & IFF_PROMISC &&
2060                             !(sc->tl_if_flags & IFF_PROMISC)) {
2061                                 tl_dio_setbit(sc, TL_NETCMD, TL_CMD_CAF);
2062                                 tl_setmulti(sc);
2063                         } else if (ifp->if_flags & IFF_RUNNING &&
2064                             !(ifp->if_flags & IFF_PROMISC) &&
2065                             sc->tl_if_flags & IFF_PROMISC) {
2066                                 tl_dio_clrbit(sc, TL_NETCMD, TL_CMD_CAF);
2067                                 tl_setmulti(sc);
2068                         } else
2069                                 tl_init(sc);
2070                 } else {
2071                         if (ifp->if_flags & IFF_RUNNING) {
2072                                 tl_stop(sc);
2073                         }
2074                 }
2075                 sc->tl_if_flags = ifp->if_flags;
2076                 error = 0;
2077                 break;
2078         case SIOCADDMULTI:
2079         case SIOCDELMULTI:
2080                 tl_setmulti(sc);
2081                 error = 0;
2082                 break;
2083         case SIOCSIFMEDIA:
2084         case SIOCGIFMEDIA:
2085                 if (sc->tl_bitrate)
2086                         error = ifmedia_ioctl(ifp, ifr, &sc->ifmedia, command);
2087                 else {
2088                         struct mii_data         *mii;
2089                         mii = device_get_softc(sc->tl_miibus);
2090                         error = ifmedia_ioctl(ifp, ifr,
2091                             &mii->mii_media, command);
2092                 }
2093                 break;
2094         default:
2095                 error = ether_ioctl(ifp, command, data);
2096                 break;
2097         }
2098         return(error);
2099 }
2100
2101 static void
2102 tl_watchdog(struct ifnet *ifp)
2103 {
2104         struct tl_softc         *sc;
2105
2106         sc = ifp->if_softc;
2107
2108         if_printf(ifp, "device timeout\n");
2109
2110         ifp->if_oerrors++;
2111
2112         tl_softreset(sc, 1);
2113         tl_init(sc);
2114
2115         return;
2116 }
2117
2118 /*
2119  * Stop the adapter and free any mbufs allocated to the
2120  * RX and TX lists.
2121  */
2122 static void
2123 tl_stop(struct tl_softc *sc)
2124 {
2125         int             i;
2126         struct ifnet            *ifp;
2127
2128         ifp = &sc->arpcom.ac_if;
2129
2130         /* Stop the stats updater. */
2131         callout_stop(&sc->tl_stat_timer);
2132
2133         /* Stop the transmitter */
2134         CMD_CLR(sc, TL_CMD_RT);
2135         CMD_SET(sc, TL_CMD_STOP);
2136         CSR_WRITE_4(sc, TL_CH_PARM, 0);
2137
2138         /* Stop the receiver */
2139         CMD_SET(sc, TL_CMD_RT);
2140         CMD_SET(sc, TL_CMD_STOP);
2141         CSR_WRITE_4(sc, TL_CH_PARM, 0);
2142
2143         /*
2144          * Disable host interrupts.
2145          */
2146         CMD_SET(sc, TL_CMD_INTSOFF);
2147
2148         /*
2149          * Clear list pointer.
2150          */
2151         CSR_WRITE_4(sc, TL_CH_PARM, 0);
2152
2153         /*
2154          * Free the RX lists.
2155          */
2156         for (i = 0; i < TL_RX_LIST_CNT; i++) {
2157                 if (sc->tl_cdata.tl_rx_chain[i].tl_mbuf != NULL) {
2158                         m_freem(sc->tl_cdata.tl_rx_chain[i].tl_mbuf);
2159                         sc->tl_cdata.tl_rx_chain[i].tl_mbuf = NULL;
2160                 }
2161         }
2162         bzero((char *)&sc->tl_ldata->tl_rx_list,
2163                 sizeof(sc->tl_ldata->tl_rx_list));
2164
2165         /*
2166          * Free the TX list buffers.
2167          */
2168         for (i = 0; i < TL_TX_LIST_CNT; i++) {
2169                 if (sc->tl_cdata.tl_tx_chain[i].tl_mbuf != NULL) {
2170                         m_freem(sc->tl_cdata.tl_tx_chain[i].tl_mbuf);
2171                         sc->tl_cdata.tl_tx_chain[i].tl_mbuf = NULL;
2172                 }
2173         }
2174         bzero((char *)&sc->tl_ldata->tl_tx_list,
2175                 sizeof(sc->tl_ldata->tl_tx_list));
2176
2177         ifp->if_flags &= ~(IFF_RUNNING | IFF_OACTIVE);
2178
2179         return;
2180 }
2181
2182 /*
2183  * Stop all chip I/O so that the kernel's probe routines don't
2184  * get confused by errant DMAs when rebooting.
2185  */
2186 static void
2187 tl_shutdown(device_t dev)
2188 {
2189         struct tl_softc         *sc;
2190
2191         sc = device_get_softc(dev);
2192
2193         tl_stop(sc);
2194
2195         return;
2196 }