Remove spl*() in src/sys/dev/netif/{ste,ti,tl,tx,txp,vr,vx,wb,wl,xe}
[dragonfly.git] / sys / dev / netif / tx / if_tx.c
1 /*-
2  * Copyright (c) 1997 Semen Ustimenko (semenu@FreeBSD.org)
3  * 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  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  *
26  * $FreeBSD: src/sys/dev/tx/if_tx.c,v 1.61.2.1 2002/10/29 01:43:49 semenu Exp $
27  * $DragonFly: src/sys/dev/netif/tx/if_tx.c,v 1.20 2005/06/06 23:12:07 okumoto Exp $
28  */
29
30 /*
31  * EtherPower II 10/100 Fast Ethernet (SMC 9432 serie)
32  *
33  * These cards are based on SMC83c17x (EPIC) chip and one of the various
34  * PHYs (QS6612, AC101 and LXT970 were seen). The media support depends on
35  * card model. All cards support 10baseT/UTP and 100baseTX half- and full-
36  * duplex (SMB9432TX). SMC9432BTX also supports 10baseT/BNC. SMC9432FTX also
37  * supports fibre optics.
38  *
39  * Thanks are going to Steve Bauer and Jason Wright.
40  */
41
42 #include <sys/param.h>
43 #include <sys/systm.h>
44 #include <sys/sockio.h>
45 #include <sys/mbuf.h>
46 #include <sys/malloc.h>
47 #include <sys/kernel.h>
48 #include <sys/socket.h>
49 #include <sys/queue.h>
50 #include <sys/thread2.h>
51
52 #include <net/if.h>
53 #include <net/ifq_var.h>
54 #include <net/if_arp.h>
55 #include <net/ethernet.h>
56 #include <net/if_dl.h>
57 #include <net/if_media.h>
58
59 #include <net/bpf.h>
60
61 #include <net/vlan/if_vlan_var.h>
62
63 #include <vm/vm.h>              /* for vtophys */
64 #include <vm/pmap.h>            /* for vtophys */
65 #include <machine/bus_memio.h>
66 #include <machine/bus_pio.h>
67 #include <machine/bus.h>
68 #include <machine/resource.h>
69 #include <machine/clock.h>      /* for DELAY */
70 #include <sys/bus.h>
71 #include <sys/rman.h>
72
73 #include <bus/pci/pcireg.h>
74 #include <bus/pci/pcivar.h>
75
76 #include "../mii_layer/mii.h"
77 #include "../mii_layer/miivar.h"
78 #include "../mii_layer/miidevs.h"
79 #include "../mii_layer/lxtphyreg.h"
80
81 #include "miibus_if.h"
82
83 #include "if_txreg.h"
84 #include "if_txvar.h"
85
86 static int epic_ifioctl(struct ifnet *, u_long, caddr_t, struct ucred *);
87 static void epic_intr(void *);
88 static void epic_tx_underrun(epic_softc_t *);
89 static int epic_common_attach(epic_softc_t *);
90 static void epic_ifstart(struct ifnet *);
91 static void epic_ifwatchdog(struct ifnet *);
92 static void epic_stats_update(void *);
93 static int epic_init(epic_softc_t *);
94 static void epic_stop(epic_softc_t *);
95 static void epic_rx_done(epic_softc_t *);
96 static void epic_tx_done(epic_softc_t *);
97 static int epic_init_rings(epic_softc_t *);
98 static void epic_free_rings(epic_softc_t *);
99 static void epic_stop_activity(epic_softc_t *);
100 static int epic_queue_last_packet(epic_softc_t *);
101 static void epic_start_activity(epic_softc_t *);
102 static void epic_set_rx_mode(epic_softc_t *);
103 static void epic_set_tx_mode(epic_softc_t *);
104 static void epic_set_mc_table(epic_softc_t *);
105 static u_int8_t epic_calchash(caddr_t);
106 static int epic_read_eeprom(epic_softc_t *,u_int16_t);
107 static void epic_output_eepromw(epic_softc_t *, u_int16_t);
108 static u_int16_t epic_input_eepromw(epic_softc_t *);
109 static u_int8_t epic_eeprom_clock(epic_softc_t *,u_int8_t);
110 static void epic_write_eepromreg(epic_softc_t *,u_int8_t);
111 static u_int8_t epic_read_eepromreg(epic_softc_t *);
112
113 static int epic_read_phy_reg(epic_softc_t *, int, int);
114 static void epic_write_phy_reg(epic_softc_t *, int, int, int);
115
116 static int epic_miibus_readreg(device_t, int, int);
117 static int epic_miibus_writereg(device_t, int, int, int);
118 static void epic_miibus_statchg(device_t);
119 static void epic_miibus_mediainit(device_t);
120
121 static int epic_ifmedia_upd(struct ifnet *);
122 static void epic_ifmedia_sts(struct ifnet *, struct ifmediareq *);
123
124 static int epic_probe(device_t);
125 static int epic_attach(device_t);
126 static void epic_shutdown(device_t);
127 static int epic_detach(device_t);
128 static struct epic_type *epic_devtype(device_t);
129
130 static device_method_t epic_methods[] = {
131         /* Device interface */
132         DEVMETHOD(device_probe,         epic_probe),
133         DEVMETHOD(device_attach,        epic_attach),
134         DEVMETHOD(device_detach,        epic_detach),
135         DEVMETHOD(device_shutdown,      epic_shutdown),
136
137         /* MII interface */
138         DEVMETHOD(miibus_readreg,       epic_miibus_readreg),
139         DEVMETHOD(miibus_writereg,      epic_miibus_writereg),
140         DEVMETHOD(miibus_statchg,       epic_miibus_statchg),
141         DEVMETHOD(miibus_mediainit,     epic_miibus_mediainit),
142
143         { 0, 0 }
144 };
145
146 static driver_t epic_driver = {
147         "tx",
148         epic_methods,
149         sizeof(epic_softc_t)
150 };
151
152 static devclass_t epic_devclass;
153
154 DECLARE_DUMMY_MODULE(if_tx);
155 MODULE_DEPEND(if_tx, miibus, 1, 1, 1);
156 DRIVER_MODULE(if_tx, pci, epic_driver, epic_devclass, 0, 0);
157 DRIVER_MODULE(miibus, tx, miibus_driver, miibus_devclass, 0, 0);
158
159 static struct epic_type epic_devs[] = {
160         { SMC_VENDORID, SMC_DEVICEID_83C170,
161                 "SMC EtherPower II 10/100" },
162         { 0, 0, NULL }
163 };
164
165 static int
166 epic_probe(dev)
167         device_t dev;
168 {
169         struct epic_type *t;
170
171         t = epic_devtype(dev);
172
173         if (t != NULL) {
174                 device_set_desc(dev, t->name);
175                 return(0);
176         }
177
178         return(ENXIO);
179 }
180
181 static struct epic_type *
182 epic_devtype(dev)
183         device_t dev;
184 {
185         struct epic_type *t;
186
187         t = epic_devs;
188
189         while(t->name != NULL) {
190                 if ((pci_get_vendor(dev) == t->ven_id) &&
191                     (pci_get_device(dev) == t->dev_id)) {
192                         return(t);
193                 }
194                 t++;
195         }
196         return (NULL);
197 }
198
199 #if defined(EPIC_USEIOSPACE)
200 #define EPIC_RES        SYS_RES_IOPORT
201 #define EPIC_RID        PCIR_BASEIO
202 #else
203 #define EPIC_RES        SYS_RES_MEMORY
204 #define EPIC_RID        PCIR_BASEMEM
205 #endif
206
207 /*
208  * Attach routine: map registers, allocate softc, rings and descriptors.
209  * Reset to known state.
210  */
211 static int
212 epic_attach(dev)
213         device_t dev;
214 {
215         struct ifnet *ifp;
216         epic_softc_t *sc;
217         u_int32_t command;
218         int unit, error;
219         int i, rid, tmp;
220
221         crit_enter();
222
223         sc = device_get_softc(dev);
224         unit = device_get_unit(dev);
225
226         /* Preinitialize softc structure */
227         bzero(sc, sizeof(epic_softc_t));                
228         sc->unit = unit;
229         sc->dev = dev;
230         callout_init(&sc->tx_stat_timer);
231
232         /* Fill ifnet structure */
233         ifp = &sc->sc_if;
234         if_initname(ifp, "tx", unit);
235         ifp->if_softc = sc;
236         ifp->if_flags = IFF_BROADCAST|IFF_SIMPLEX|IFF_MULTICAST;
237         ifp->if_ioctl = epic_ifioctl;
238         ifp->if_start = epic_ifstart;
239         ifp->if_watchdog = epic_ifwatchdog;
240         ifp->if_init = (if_init_f_t*)epic_init;
241         ifp->if_timer = 0;
242         ifp->if_baudrate = 10000000;
243         ifq_set_maxlen(&ifp->if_snd, TX_RING_SIZE - 1);
244         ifq_set_ready(&ifp->if_snd);
245
246         /* Enable ports, memory and busmastering */
247         command = pci_read_config(dev, PCIR_COMMAND, 4);
248         command |= PCIM_CMD_PORTEN | PCIM_CMD_MEMEN | PCIM_CMD_BUSMASTEREN;
249         pci_write_config(dev, PCIR_COMMAND, command, 4);
250         command = pci_read_config(dev, PCIR_COMMAND, 4);
251
252 #if defined(EPIC_USEIOSPACE)
253         if ((command & PCIM_CMD_PORTEN) == 0) {
254                 device_printf(dev, "failed to enable I/O mapping!\n");
255                 error = ENXIO;
256                 goto fail;
257         }
258 #else
259         if ((command & PCIM_CMD_MEMEN) == 0) {
260                 device_printf(dev, "failed to enable memory mapping!\n");
261                 error = ENXIO;
262                 goto fail;
263         }
264 #endif
265
266         rid = EPIC_RID;
267         sc->res = bus_alloc_resource_any(dev, EPIC_RES, &rid, RF_ACTIVE);
268
269         if (sc->res == NULL) {
270                 device_printf(dev, "couldn't map ports/memory\n");
271                 error = ENXIO;
272                 goto fail;
273         }
274
275         sc->sc_st = rman_get_bustag(sc->res);
276         sc->sc_sh = rman_get_bushandle(sc->res);
277
278         /* Allocate interrupt */
279         rid = 0;
280         sc->irq = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid,
281             RF_SHAREABLE | RF_ACTIVE);
282
283         if (sc->irq == NULL) {
284                 device_printf(dev, "couldn't map interrupt\n");
285                 bus_release_resource(dev, EPIC_RES, EPIC_RID, sc->res);
286                 error = ENXIO;
287                 goto fail;
288         }
289
290         error = bus_setup_intr(dev, sc->irq, INTR_TYPE_NET,
291                                epic_intr, sc, &sc->sc_ih, NULL);
292
293         if (error) {
294                 bus_release_resource(dev, SYS_RES_IRQ, 0, sc->irq);
295                 bus_release_resource(dev, EPIC_RES, EPIC_RID, sc->res);
296                 device_printf(dev, "couldn't set up irq\n");
297                 goto fail;
298         }
299
300         /* Do OS independent part, including chip wakeup and reset */
301         error = epic_common_attach(sc);
302         if (error) {
303                 bus_teardown_intr(dev, sc->irq, sc->sc_ih);
304                 bus_release_resource(dev, SYS_RES_IRQ, 0, sc->irq);
305                 bus_release_resource(dev, EPIC_RES, EPIC_RID, sc->res);
306                 error = ENXIO;
307                 goto fail;
308         }
309
310         /* Do ifmedia setup */
311         if (mii_phy_probe(dev, &sc->miibus,
312             epic_ifmedia_upd, epic_ifmedia_sts)) {
313                 device_printf(dev, "ERROR! MII without any PHY!?\n");
314                 bus_teardown_intr(dev, sc->irq, sc->sc_ih);
315                 bus_release_resource(dev, SYS_RES_IRQ, 0, sc->irq);
316                 bus_release_resource(dev, EPIC_RES, EPIC_RID, sc->res);
317                 error = ENXIO;
318                 goto fail;
319         }
320
321         /* board type and ... */
322         printf(" type ");
323         for(i=0x2c;i<0x32;i++) {
324                 tmp = epic_read_eeprom(sc, i);
325                 if (' ' == (u_int8_t)tmp) break;
326                 printf("%c", (u_int8_t)tmp);
327                 tmp >>= 8;
328                 if (' ' == (u_int8_t)tmp) break;
329                 printf("%c", (u_int8_t)tmp);
330         }
331         printf("\n");
332
333         /* Attach to OS's managers */
334         ether_ifattach(ifp, sc->sc_macaddr);
335         ifp->if_hdrlen = sizeof(struct ether_vlan_header);
336
337 fail:
338         crit_exit();
339
340         return(error);
341 }
342
343 /*
344  * Detach driver and free resources
345  */
346 static int
347 epic_detach(dev)
348         device_t dev;
349 {
350         struct ifnet *ifp;
351         epic_softc_t *sc;
352
353         crit_enter();
354
355         sc = device_get_softc(dev);
356         ifp = &sc->arpcom.ac_if;
357
358         ether_ifdetach(ifp);
359
360         epic_stop(sc);
361
362         bus_generic_detach(dev);
363         device_delete_child(dev, sc->miibus);
364
365         bus_teardown_intr(dev, sc->irq, sc->sc_ih);
366         bus_release_resource(dev, SYS_RES_IRQ, 0, sc->irq);
367         bus_release_resource(dev, EPIC_RES, EPIC_RID, sc->res);
368
369         free(sc->tx_flist, M_DEVBUF);
370         free(sc->tx_desc, M_DEVBUF);
371         free(sc->rx_desc, M_DEVBUF);
372
373         crit_exit();
374
375         return(0);
376 }
377
378 #undef  EPIC_RES
379 #undef  EPIC_RID
380
381 /*
382  * Stop all chip I/O so that the kernel's probe routines don't
383  * get confused by errant DMAs when rebooting.
384  */
385 static void
386 epic_shutdown(dev)
387         device_t dev;
388 {
389         epic_softc_t *sc;
390
391         sc = device_get_softc(dev);
392
393         epic_stop(sc);
394
395         return;
396 }
397
398 /*
399  * This is if_ioctl handler.
400  */
401 static int
402 epic_ifioctl(ifp, command, data, cr)
403         struct ifnet *ifp;
404         u_long command;
405         caddr_t data;
406         struct ucred *cr;
407 {
408         epic_softc_t *sc = ifp->if_softc;
409         struct mii_data *mii;
410         struct ifreq *ifr = (struct ifreq *) data;
411         int error = 0;
412
413         crit_enter();
414
415         switch (command) {
416         case SIOCSIFMTU:
417                 if (ifp->if_mtu == ifr->ifr_mtu)
418                         break;
419
420                 /* XXX Though the datasheet doesn't imply any
421                  * limitations on RX and TX sizes beside max 64Kb
422                  * DMA transfer, seems we can't send more then 1600
423                  * data bytes per ethernet packet. (Transmitter hangs
424                  * up if more data is sent)
425                  */
426                 if (ifr->ifr_mtu + ifp->if_hdrlen <= EPIC_MAX_MTU) {
427                         ifp->if_mtu = ifr->ifr_mtu;
428                         epic_stop(sc);
429                         epic_init(sc);
430                 } else
431                         error = EINVAL;
432                 break;
433
434         case SIOCSIFFLAGS:
435                 /*
436                  * If the interface is marked up and stopped, then start it.
437                  * If it is marked down and running, then stop it.
438                  */
439                 if (ifp->if_flags & IFF_UP) {
440                         if ((ifp->if_flags & IFF_RUNNING) == 0) {
441                                 epic_init(sc);
442                                 break;
443                         }
444                 } else {
445                         if (ifp->if_flags & IFF_RUNNING) {
446                                 epic_stop(sc);
447                                 break;
448                         }
449                 }
450
451                 /* Handle IFF_PROMISC and IFF_ALLMULTI flags */
452                 epic_stop_activity(sc); 
453                 epic_set_mc_table(sc);
454                 epic_set_rx_mode(sc);
455                 epic_start_activity(sc);        
456                 break;
457
458         case SIOCADDMULTI:
459         case SIOCDELMULTI:
460                 epic_set_mc_table(sc);
461                 error = 0;
462                 break;
463
464         case SIOCSIFMEDIA:
465         case SIOCGIFMEDIA:
466                 mii = device_get_softc(sc->miibus);
467                 error = ifmedia_ioctl(ifp, ifr, &mii->mii_media, command);
468                 break;
469
470         default:
471                 error = ether_ioctl(ifp, command, data);
472                 break;
473         }
474         crit_exit();
475
476         return error;
477 }
478
479 /*
480  * OS-independed part of attach process. allocate memory for descriptors
481  * and frag lists, wake up chip, read MAC address and PHY identyfier.
482  * Return -1 on failure.
483  */
484 static int
485 epic_common_attach(sc)
486         epic_softc_t *sc;
487 {
488         int i;
489
490         sc->tx_flist = malloc(sizeof(struct epic_frag_list)*TX_RING_SIZE,
491             M_DEVBUF, M_WAITOK | M_ZERO);
492         sc->tx_desc = malloc(sizeof(struct epic_tx_desc)*TX_RING_SIZE,
493             M_DEVBUF, M_WAITOK | M_ZERO);
494         sc->rx_desc = malloc(sizeof(struct epic_rx_desc)*RX_RING_SIZE,
495             M_DEVBUF, M_WAITOK | M_ZERO);
496
497         /* Bring the chip out of low-power mode. */
498         CSR_WRITE_4(sc, GENCTL, GENCTL_SOFT_RESET);
499         DELAY(500);
500
501         /* Workaround for Application Note 7-15 */
502         for (i=0; i<16; i++) CSR_WRITE_4(sc, TEST1, TEST1_CLOCK_TEST);
503
504         /* Read mac address from EEPROM */
505         for (i = 0; i < ETHER_ADDR_LEN / sizeof(u_int16_t); i++)
506                 ((u_int16_t *)sc->sc_macaddr)[i] = epic_read_eeprom(sc,i);
507
508         /* Set Non-Volatile Control Register from EEPROM */
509         CSR_WRITE_4(sc, NVCTL, epic_read_eeprom(sc, EEPROM_NVCTL) & 0x1F);
510
511         /* Set defaults */
512         sc->tx_threshold = TRANSMIT_THRESHOLD;
513         sc->txcon = TXCON_DEFAULT;
514         sc->miicfg = MIICFG_SMI_ENABLE;
515         sc->phyid = EPIC_UNKN_PHY;
516         sc->serinst = -1;
517
518         /* Fetch card id */
519         sc->cardvend = pci_read_config(sc->dev, PCIR_SUBVEND_0, 2);
520         sc->cardid = pci_read_config(sc->dev, PCIR_SUBDEV_0, 2);
521
522         if (sc->cardvend != SMC_VENDORID)
523                 device_printf(sc->dev, "unknown card vendor %04xh\n", sc->cardvend);
524
525         return 0;
526 }
527
528 /*
529  * This is if_start handler. It takes mbufs from if_snd queue
530  * and queue them for transmit, one by one, until TX ring become full
531  * or queue become empty.
532  */
533 static void
534 epic_ifstart(ifp)
535         struct ifnet * ifp;
536 {
537         epic_softc_t *sc = ifp->if_softc;
538         struct epic_tx_buffer *buf;
539         struct epic_tx_desc *desc;
540         struct epic_frag_list *flist;
541         struct mbuf *m0;
542         struct mbuf *m;
543         int i;
544
545         while (sc->pending_txs < TX_RING_SIZE) {
546                 buf = sc->tx_buffer + sc->cur_tx;
547                 desc = sc->tx_desc + sc->cur_tx;
548                 flist = sc->tx_flist + sc->cur_tx;
549
550                 /* Get next packet to send */
551                 m0 = ifq_dequeue(&ifp->if_snd);
552
553                 /* If nothing to send, return */
554                 if (m0 == NULL)
555                         return;
556
557                 /* Fill fragments list */
558                 for (m = m0, i = 0;
559                     (NULL != m) && (i < EPIC_MAX_FRAGS);
560                     m = m->m_next, i++) {
561                         flist->frag[i].fraglen = m->m_len;
562                         flist->frag[i].fragaddr = vtophys(mtod(m, caddr_t));
563                 }
564                 flist->numfrags = i;
565
566                 /* If packet was more than EPIC_MAX_FRAGS parts, */
567                 /* recopy packet to new allocated mbuf cluster */
568                 if (NULL != m) {
569                         EPIC_MGETCLUSTER(m);
570                         if (NULL == m) {
571                                 m_freem(m0);
572                                 ifp->if_oerrors++;
573                                 continue;
574                         }
575
576                         m_copydata(m0, 0, m0->m_pkthdr.len, mtod(m, caddr_t));
577                         flist->frag[0].fraglen =
578                              m->m_pkthdr.len = m->m_len = m0->m_pkthdr.len;
579                         m->m_pkthdr.rcvif = ifp;
580
581                         flist->numfrags = 1;
582                         flist->frag[0].fragaddr = vtophys(mtod(m, caddr_t));
583                         m_freem(m0);
584                         m0 = m;
585                 }
586
587                 buf->mbuf = m0;
588                 sc->pending_txs++;
589                 sc->cur_tx = (sc->cur_tx + 1) & TX_RING_MASK;
590                 desc->control = 0x01;
591                 desc->txlength =
592                     max(m0->m_pkthdr.len,ETHER_MIN_LEN-ETHER_CRC_LEN);
593                 desc->status = 0x8000;
594                 CSR_WRITE_4(sc, COMMAND, COMMAND_TXQUEUED);
595
596                 /* Set watchdog timer */
597                 ifp->if_timer = 8;
598
599                 BPF_MTAP(ifp, m0);
600         }
601
602         ifp->if_flags |= IFF_OACTIVE;
603
604         return;
605         
606 }
607
608 /*
609  * Synopsis: Finish all received frames.
610  */
611 static void
612 epic_rx_done(sc)
613         epic_softc_t *sc;
614 {
615         u_int16_t len;
616         struct ifnet *ifp = &sc->sc_if;
617         struct epic_rx_buffer *buf;
618         struct epic_rx_desc *desc;
619         struct mbuf *m;
620
621         while ((sc->rx_desc[sc->cur_rx].status & 0x8000) == 0) {
622                 buf = sc->rx_buffer + sc->cur_rx;
623                 desc = sc->rx_desc + sc->cur_rx;
624
625                 /* Switch to next descriptor */
626                 sc->cur_rx = (sc->cur_rx+1) & RX_RING_MASK;
627
628                 /*
629                  * Check for RX errors. This should only happen if
630                  * SAVE_ERRORED_PACKETS is set. RX errors generate
631                  * RXE interrupt usually.
632                  */
633                 if ((desc->status & 1) == 0) {
634                         sc->sc_if.if_ierrors++;
635                         desc->status = 0x8000;
636                         continue;
637                 }
638
639                 /* Save packet length and mbuf contained packet */
640                 len = desc->rxlength - ETHER_CRC_LEN;
641                 m = buf->mbuf;
642
643                 /* Try to get mbuf cluster */
644                 EPIC_MGETCLUSTER(buf->mbuf);
645                 if (NULL == buf->mbuf) {
646                         buf->mbuf = m;
647                         desc->status = 0x8000;
648                         ifp->if_ierrors++;
649                         continue;
650                 }
651
652                 /* Point to new mbuf, and give descriptor to chip */
653                 desc->bufaddr = vtophys(mtod(buf->mbuf, caddr_t));
654                 desc->status = 0x8000;
655                 
656                 /* First mbuf in packet holds the ethernet and packet headers */
657                 m->m_pkthdr.rcvif = ifp;
658                 m->m_pkthdr.len = m->m_len = len;
659
660                 /* Give mbuf to OS */
661                 (*ifp->if_input)(ifp, m);
662
663                 /* Successfuly received frame */
664                 ifp->if_ipackets++;
665         }
666
667         return;
668 }
669
670 /*
671  * Synopsis: Do last phase of transmission. I.e. if desc is
672  * transmitted, decrease pending_txs counter, free mbuf contained
673  * packet, switch to next descriptor and repeat until no packets
674  * are pending or descriptor is not transmitted yet.
675  */
676 static void
677 epic_tx_done(sc)
678         epic_softc_t *sc;
679 {
680         struct epic_tx_buffer *buf;
681         struct epic_tx_desc *desc;
682         u_int16_t status;
683
684         while (sc->pending_txs > 0) {
685                 buf = sc->tx_buffer + sc->dirty_tx;
686                 desc = sc->tx_desc + sc->dirty_tx;
687                 status = desc->status;
688
689                 /* If packet is not transmitted, thou followed */
690                 /* packets are not transmitted too */
691                 if (status & 0x8000) break;
692
693                 /* Packet is transmitted. Switch to next and */
694                 /* free mbuf */
695                 sc->pending_txs--;
696                 sc->dirty_tx = (sc->dirty_tx + 1) & TX_RING_MASK;
697                 m_freem(buf->mbuf);
698                 buf->mbuf = NULL;
699
700                 /* Check for errors and collisions */
701                 if (status & 0x0001) sc->sc_if.if_opackets++;
702                 else sc->sc_if.if_oerrors++;
703                 sc->sc_if.if_collisions += (status >> 8) & 0x1F;
704 #if defined(EPIC_DIAG)
705                 if ((status & 0x1001) == 0x1001)
706                         device_printf(sc->dev,  "Tx ERROR: excessive coll. number\n");
707 #endif
708         }
709
710         if (sc->pending_txs < TX_RING_SIZE)
711                 sc->sc_if.if_flags &= ~IFF_OACTIVE;
712 }
713
714 /*
715  * Interrupt function
716  */
717 static void
718 epic_intr(arg)
719     void *arg;
720 {
721     epic_softc_t * sc = (epic_softc_t *) arg;
722     int status, i = 4;
723
724     while (i-- && ((status = CSR_READ_4(sc, INTSTAT)) & INTSTAT_INT_ACTV)) {
725         CSR_WRITE_4(sc, INTSTAT, status);
726
727         if (status & (INTSTAT_RQE|INTSTAT_RCC|INTSTAT_OVW)) {
728             epic_rx_done(sc);
729             if (status & (INTSTAT_RQE|INTSTAT_OVW)) {
730 #if defined(EPIC_DIAG)
731                 if (status & INTSTAT_OVW)
732                     device_printf(sc->dev, "RX buffer overflow\n");
733                 if (status & INTSTAT_RQE)
734                     device_printf(sc->dev, "RX FIFO overflow\n");
735 #endif
736                 if ((CSR_READ_4(sc, COMMAND) & COMMAND_RXQUEUED) == 0)
737                     CSR_WRITE_4(sc, COMMAND, COMMAND_RXQUEUED);
738                 sc->sc_if.if_ierrors++;
739             }
740         }
741
742         if (status & (INTSTAT_TXC|INTSTAT_TCC|INTSTAT_TQE)) {
743             epic_tx_done(sc);
744             if (!ifq_is_empty(&sc->sc_if.if_snd))
745                     epic_ifstart(&sc->sc_if);
746         }
747
748         /* Check for rare errors */
749         if (status & (INTSTAT_FATAL|INTSTAT_PMA|INTSTAT_PTA|
750                       INTSTAT_APE|INTSTAT_DPE|INTSTAT_TXU|INTSTAT_RXE)) {
751             if (status & (INTSTAT_FATAL|INTSTAT_PMA|INTSTAT_PTA|
752                           INTSTAT_APE|INTSTAT_DPE)) {
753                 device_printf(sc->dev, "PCI fatal errors occured: %s%s%s%s\n",
754                     (status&INTSTAT_PMA)?"PMA ":"",
755                     (status&INTSTAT_PTA)?"PTA ":"",
756                     (status&INTSTAT_APE)?"APE ":"",
757                     (status&INTSTAT_DPE)?"DPE":""
758                 );
759
760                 epic_stop(sc);
761                 epic_init(sc);
762                 
763                 break;
764             }
765
766             if (status & INTSTAT_RXE) {
767 #if defined(EPIC_DIAG)
768                 device_printf(sc->dev, "CRC/Alignment error\n");
769 #endif
770                 sc->sc_if.if_ierrors++;
771             }
772
773             if (status & INTSTAT_TXU) {
774                 epic_tx_underrun(sc);
775                 sc->sc_if.if_oerrors++;
776             }
777         }
778     }
779
780     /* If no packets are pending, then no timeouts */
781     if (sc->pending_txs == 0) sc->sc_if.if_timer = 0;
782
783     return;
784 }
785
786 /*
787  * Handle the TX underrun error: increase the TX threshold
788  * and restart the transmitter.
789  */
790 static void
791 epic_tx_underrun(sc)
792         epic_softc_t *sc;
793 {
794         if (sc->tx_threshold > TRANSMIT_THRESHOLD_MAX) {
795                 sc->txcon &= ~TXCON_EARLY_TRANSMIT_ENABLE;
796 #if defined(EPIC_DIAG)
797                 device_printf(sc->dev, "Tx UNDERRUN: early TX disabled\n");
798 #endif
799         } else {
800                 sc->tx_threshold += 0x40;
801 #if defined(EPIC_DIAG)
802                 device_printf(sc->dev, "Tx UNDERRUN: TX threshold increased to %d\n",
803                     sc->tx_threshold);
804 #endif
805         }
806
807         /* We must set TXUGO to reset the stuck transmitter */
808         CSR_WRITE_4(sc, COMMAND, COMMAND_TXUGO);
809
810         /* Update the TX threshold */
811         epic_stop_activity(sc);
812         epic_set_tx_mode(sc);
813         epic_start_activity(sc);
814
815         return;
816 }
817
818 /*
819  * Synopsis: This one is called if packets wasn't transmitted
820  * during timeout. Try to deallocate transmitted packets, and
821  * if success continue to work.
822  */
823 static void
824 epic_ifwatchdog(ifp)
825         struct ifnet *ifp;
826 {
827         epic_softc_t *sc = ifp->if_softc;
828
829         crit_enter();
830
831         device_printf(sc->dev, "device timeout %d packets\n", sc->pending_txs);
832
833         /* Try to finish queued packets */
834         epic_tx_done(sc);
835
836         /* If not successful */
837         if (sc->pending_txs > 0) {
838
839                 ifp->if_oerrors+=sc->pending_txs;
840
841                 /* Reinitialize board */
842                 device_printf(sc->dev, "reinitialization\n");
843                 epic_stop(sc);
844                 epic_init(sc);
845
846         } else
847                 device_printf(sc->dev, "seems we can continue normaly\n");
848
849         /* Start output */
850         if (!ifq_is_empty(&ifp->if_snd))
851                 epic_ifstart(ifp);
852
853         crit_exit();
854 }
855
856 /*
857  * Despite the name of this function, it doesn't update statistics, it only
858  * helps in autonegotiation process.
859  */
860 static void
861 epic_stats_update(void *xsc)
862 {
863         epic_softc_t *sc = xsc;
864         struct mii_data * mii;
865
866         crit_enter();
867
868         mii = device_get_softc(sc->miibus);
869         mii_tick(mii);
870
871         callout_reset(&sc->tx_stat_timer, hz, epic_stats_update, sc);
872
873         crit_exit();
874 }
875
876 /*
877  * Set media options.
878  */
879 static int
880 epic_ifmedia_upd(ifp)
881         struct ifnet *ifp;
882 {
883         epic_softc_t *sc;
884         struct mii_data *mii;
885         struct ifmedia *ifm;
886         struct mii_softc *miisc;
887         int cfg, media;
888
889         sc = ifp->if_softc;
890         mii = device_get_softc(sc->miibus);
891         ifm = &mii->mii_media;
892         media = ifm->ifm_cur->ifm_media;
893
894         /* Do not do anything if interface is not up */
895         if ((ifp->if_flags & IFF_UP) == 0)
896                 return (0);
897
898         /*
899          * Lookup current selected PHY
900          */
901         if (IFM_INST(media) == sc->serinst) {
902                 sc->phyid = EPIC_SERIAL;
903                 sc->physc = NULL;
904         } else {
905                 /* If we're not selecting serial interface, select MII mode */
906                 sc->miicfg &= ~MIICFG_SERIAL_ENABLE;
907                 CSR_WRITE_4(sc, MIICFG, sc->miicfg);
908
909                 /* Default to unknown PHY */
910                 sc->phyid = EPIC_UNKN_PHY;
911
912                 /* Lookup selected PHY */
913                 for (miisc = LIST_FIRST(&mii->mii_phys); miisc != NULL;
914                      miisc = LIST_NEXT(miisc, mii_list)) {
915                         if (IFM_INST(media) == miisc->mii_inst) {
916                                 sc->physc = miisc;
917                                 break;
918                         }
919                 }
920
921                 /* Identify selected PHY */
922                 if (sc->physc) {
923                         int id1, id2, model, oui;
924
925                         id1 = PHY_READ(sc->physc, MII_PHYIDR1);
926                         id2 = PHY_READ(sc->physc, MII_PHYIDR2);
927
928                         oui = MII_OUI(id1, id2);
929                         model = MII_MODEL(id2);
930                         switch (oui) {
931                         case MII_OUI_QUALSEMI:
932                                 if (model == MII_MODEL_QUALSEMI_QS6612)
933                                         sc->phyid = EPIC_QS6612_PHY;
934                                 break;
935                         case MII_OUI_xxALTIMA:
936                                 if (model == MII_MODEL_xxALTIMA_AC101)
937                                         sc->phyid = EPIC_AC101_PHY;
938                                 break;
939                         case MII_OUI_xxLEVEL1:
940                                 if (model == MII_MODEL_xxLEVEL1_LXT970)
941                                         sc->phyid = EPIC_LXT970_PHY;
942                                 break;
943                         }
944                 }
945         }
946
947         /*
948          * Do PHY specific card setup
949          */
950
951         /* Call this, to isolate all not selected PHYs and
952          * set up selected
953          */
954         mii_mediachg(mii);
955
956         /* Do our own setup */
957         switch (sc->phyid) {
958         case EPIC_QS6612_PHY:
959                 break;
960         case EPIC_AC101_PHY:
961                 /* We have to powerup fiber tranceivers */
962                 if (IFM_SUBTYPE(media) == IFM_100_FX)
963                         sc->miicfg |= MIICFG_694_ENABLE;
964                 else
965                         sc->miicfg &= ~MIICFG_694_ENABLE;
966                 CSR_WRITE_4(sc, MIICFG, sc->miicfg);
967         
968                 break;
969         case EPIC_LXT970_PHY:
970                 /* We have to powerup fiber tranceivers */
971                 cfg = PHY_READ(sc->physc, MII_LXTPHY_CONFIG);
972                 if (IFM_SUBTYPE(media) == IFM_100_FX)
973                         cfg |= CONFIG_LEDC1 | CONFIG_LEDC0;
974                 else
975                         cfg &= ~(CONFIG_LEDC1 | CONFIG_LEDC0);
976                 PHY_WRITE(sc->physc, MII_LXTPHY_CONFIG, cfg);
977
978                 break;
979         case EPIC_SERIAL:
980                 /* Select serial PHY, (10base2/BNC usually) */
981                 sc->miicfg |= MIICFG_694_ENABLE | MIICFG_SERIAL_ENABLE;
982                 CSR_WRITE_4(sc, MIICFG, sc->miicfg);
983
984                 /* There is no driver to fill this */
985                 mii->mii_media_active = media;
986                 mii->mii_media_status = 0;
987
988                 /* We need to call this manualy as i wasn't called
989                  * in mii_mediachg()
990                  */
991                 epic_miibus_statchg(sc->dev);
992
993                 break;
994         default:
995                 device_printf(sc->dev, "ERROR! Unknown PHY selected\n");
996                 return (EINVAL);
997         }
998
999         return(0);
1000 }
1001
1002 /*
1003  * Report current media status.
1004  */
1005 static void
1006 epic_ifmedia_sts(ifp, ifmr)
1007         struct ifnet *ifp;
1008         struct ifmediareq *ifmr;
1009 {
1010         epic_softc_t *sc;
1011         struct mii_data *mii;
1012         struct ifmedia *ifm;
1013
1014         sc = ifp->if_softc;
1015         mii = device_get_softc(sc->miibus);
1016         ifm = &mii->mii_media;
1017
1018         /* Nothing should be selected if interface is down */
1019         if ((ifp->if_flags & IFF_UP) == 0) {
1020                 ifmr->ifm_active = IFM_NONE;
1021                 ifmr->ifm_status = 0;
1022
1023                 return;
1024         }
1025
1026         /* Call underlying pollstat, if not serial PHY */
1027         if (sc->phyid != EPIC_SERIAL)
1028                 mii_pollstat(mii);
1029
1030         /* Simply copy media info */
1031         ifmr->ifm_active = mii->mii_media_active;
1032         ifmr->ifm_status = mii->mii_media_status;
1033
1034         return;
1035 }
1036
1037 /*
1038  * Callback routine, called on media change.
1039  */
1040 static void
1041 epic_miibus_statchg(dev)
1042         device_t dev;
1043 {
1044         epic_softc_t *sc;
1045         struct mii_data *mii;
1046         int media;
1047
1048         sc = device_get_softc(dev);
1049         mii = device_get_softc(sc->miibus);
1050         media = mii->mii_media_active;
1051
1052         sc->txcon &= ~(TXCON_LOOPBACK_MODE | TXCON_FULL_DUPLEX);
1053
1054         /* If we are in full-duplex mode or loopback operation,
1055          * we need to decouple receiver and transmitter.
1056          */
1057         if (IFM_OPTIONS(media) & (IFM_FDX | IFM_LOOP))
1058                 sc->txcon |= TXCON_FULL_DUPLEX;
1059
1060         /* On some cards we need manualy set fullduplex led */
1061         if (sc->cardid == SMC9432FTX ||
1062             sc->cardid == SMC9432FTX_SC) {
1063                 if (IFM_OPTIONS(media) & IFM_FDX)
1064                         sc->miicfg |= MIICFG_694_ENABLE;
1065                 else
1066                         sc->miicfg &= ~MIICFG_694_ENABLE;
1067
1068                 CSR_WRITE_4(sc, MIICFG, sc->miicfg);
1069         }
1070
1071         /* Update baudrate */
1072         if (IFM_SUBTYPE(media) == IFM_100_TX ||
1073             IFM_SUBTYPE(media) == IFM_100_FX)
1074                 sc->sc_if.if_baudrate = 100000000;
1075         else
1076                 sc->sc_if.if_baudrate = 10000000;
1077
1078         epic_stop_activity(sc);
1079         epic_set_tx_mode(sc);
1080         epic_start_activity(sc);
1081
1082         return;
1083 }
1084
1085 static void
1086 epic_miibus_mediainit(dev)
1087         device_t dev;
1088 {
1089         epic_softc_t *sc;
1090         struct mii_data *mii;
1091         struct ifmedia *ifm;
1092         int media;
1093
1094         sc = device_get_softc(dev);
1095         mii = device_get_softc(sc->miibus);
1096         ifm = &mii->mii_media;
1097
1098         /* Add Serial Media Interface if present, this applies to
1099          * SMC9432BTX serie
1100          */
1101         if (CSR_READ_4(sc, MIICFG) & MIICFG_PHY_PRESENT) {
1102                 /* Store its instance */
1103                 sc->serinst = mii->mii_instance++;
1104
1105                 /* Add as 10base2/BNC media */
1106                 media = IFM_MAKEWORD(IFM_ETHER, IFM_10_2, 0, sc->serinst);
1107                 ifmedia_add(ifm, media, 0, NULL);
1108
1109                 /* Report to user */
1110                 device_printf(sc->dev, "serial PHY detected (10Base2/BNC)\n");
1111         }
1112
1113         return;
1114 }
1115
1116 /*
1117  * Reset chip, allocate rings, and update media.
1118  */
1119 static int
1120 epic_init(sc)
1121         epic_softc_t *sc;
1122 {
1123         struct ifnet *ifp = &sc->sc_if;
1124         int     i;
1125
1126         crit_enter();
1127
1128         /* If interface is already running, then we need not do anything */
1129         if (ifp->if_flags & IFF_RUNNING) {
1130                 crit_exit();
1131                 return 0;
1132         }
1133
1134         /* Soft reset the chip (we have to power up card before) */
1135         CSR_WRITE_4(sc, GENCTL, 0);
1136         CSR_WRITE_4(sc, GENCTL, GENCTL_SOFT_RESET);
1137
1138         /*
1139          * Reset takes 15 pci ticks which depends on PCI bus speed.
1140          * Assuming it >= 33000000 hz, we have wait at least 495e-6 sec.
1141          */
1142         DELAY(500);
1143
1144         /* Wake up */
1145         CSR_WRITE_4(sc, GENCTL, 0);
1146
1147         /* Workaround for Application Note 7-15 */
1148         for (i=0; i<16; i++) CSR_WRITE_4(sc, TEST1, TEST1_CLOCK_TEST);
1149
1150         /* Initialize rings */
1151         if (epic_init_rings(sc)) {
1152                 device_printf(sc->dev, "failed to init rings\n");
1153                 crit_exit();
1154                 return -1;
1155         }       
1156
1157         /* Give rings to EPIC */
1158         CSR_WRITE_4(sc, PRCDAR, vtophys(sc->rx_desc));
1159         CSR_WRITE_4(sc, PTCDAR, vtophys(sc->tx_desc));
1160
1161         /* Put node address to EPIC */
1162         CSR_WRITE_4(sc, LAN0, ((u_int16_t *)sc->sc_macaddr)[0]);
1163         CSR_WRITE_4(sc, LAN1, ((u_int16_t *)sc->sc_macaddr)[1]);
1164         CSR_WRITE_4(sc, LAN2, ((u_int16_t *)sc->sc_macaddr)[2]);
1165
1166         /* Set tx mode, includeing transmit threshold */
1167         epic_set_tx_mode(sc);
1168
1169         /* Compute and set RXCON. */
1170         epic_set_rx_mode(sc);
1171
1172         /* Set multicast table */
1173         epic_set_mc_table(sc);
1174
1175         /* Enable interrupts by setting the interrupt mask. */
1176         CSR_WRITE_4(sc, INTMASK,
1177                 INTSTAT_RCC  | /* INTSTAT_RQE | INTSTAT_OVW | INTSTAT_RXE | */
1178                 /* INTSTAT_TXC | */ INTSTAT_TCC | INTSTAT_TQE | INTSTAT_TXU |
1179                 INTSTAT_FATAL);
1180
1181         /* Acknowledge all pending interrupts */
1182         CSR_WRITE_4(sc, INTSTAT, CSR_READ_4(sc, INTSTAT));
1183
1184         /* Enable interrupts,  set for PCI read multiple and etc */
1185         CSR_WRITE_4(sc, GENCTL,
1186                 GENCTL_ENABLE_INTERRUPT | GENCTL_MEMORY_READ_MULTIPLE |
1187                 GENCTL_ONECOPY | GENCTL_RECEIVE_FIFO_THRESHOLD64);
1188
1189         /* Mark interface running ... */
1190         if (ifp->if_flags & IFF_UP) ifp->if_flags |= IFF_RUNNING;
1191         else ifp->if_flags &= ~IFF_RUNNING;
1192
1193         /* ... and free */
1194         ifp->if_flags &= ~IFF_OACTIVE;
1195
1196         /* Start Rx process */
1197         epic_start_activity(sc);
1198
1199         /* Set appropriate media */
1200         epic_ifmedia_upd(ifp);
1201
1202         callout_reset(&sc->tx_stat_timer, hz, epic_stats_update, sc);
1203
1204         crit_exit();
1205
1206         return 0;
1207 }
1208
1209 /*
1210  * Synopsis: calculate and set Rx mode. Chip must be in idle state to
1211  * access RXCON.
1212  */
1213 static void
1214 epic_set_rx_mode(sc)
1215         epic_softc_t *sc;
1216 {
1217         u_int32_t               flags = sc->sc_if.if_flags;
1218         u_int32_t               rxcon = RXCON_DEFAULT;
1219
1220 #if defined(EPIC_EARLY_RX)
1221         rxcon |= RXCON_EARLY_RX;
1222 #endif
1223
1224         rxcon |= (flags & IFF_PROMISC) ? RXCON_PROMISCUOUS_MODE : 0;
1225
1226         CSR_WRITE_4(sc, RXCON, rxcon);
1227
1228         return;
1229 }
1230
1231 /*
1232  * Synopsis: Set transmit control register. Chip must be in idle state to
1233  * access TXCON.
1234  */
1235 static void
1236 epic_set_tx_mode(sc)
1237         epic_softc_t *sc;
1238 {
1239         if (sc->txcon & TXCON_EARLY_TRANSMIT_ENABLE)
1240                 CSR_WRITE_4(sc, ETXTHR, sc->tx_threshold);
1241
1242         CSR_WRITE_4(sc, TXCON, sc->txcon);
1243 }
1244
1245 /*
1246  * Synopsis: Program multicast filter honoring IFF_ALLMULTI and IFF_PROMISC
1247  * flags. (Note, that setting PROMISC bit in EPIC's RXCON will only touch
1248  * individual frames, multicast filter must be manually programmed)
1249  *
1250  * Note: EPIC must be in idle state.
1251  */
1252 static void
1253 epic_set_mc_table(sc)
1254         epic_softc_t *sc;
1255 {
1256         struct ifnet *ifp = &sc->sc_if;
1257         struct ifmultiaddr *ifma;
1258         u_int16_t filter[4];
1259         u_int8_t h;
1260
1261         if (ifp->if_flags & (IFF_ALLMULTI | IFF_PROMISC)) {
1262                 CSR_WRITE_4(sc, MC0, 0xFFFF);
1263                 CSR_WRITE_4(sc, MC1, 0xFFFF);
1264                 CSR_WRITE_4(sc, MC2, 0xFFFF);
1265                 CSR_WRITE_4(sc, MC3, 0xFFFF);
1266
1267                 return;
1268         }
1269
1270         filter[0] = 0;
1271         filter[1] = 0;
1272         filter[2] = 0;
1273         filter[3] = 0;
1274
1275 #if defined(__DragonFly__) || __FreeBSD_version < 500000
1276         LIST_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
1277 #else
1278         TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
1279 #endif
1280                 if (ifma->ifma_addr->sa_family != AF_LINK)
1281                         continue;
1282                 h = epic_calchash(LLADDR((struct sockaddr_dl *)ifma->ifma_addr));
1283                 filter[h >> 4] |= 1 << (h & 0xF);
1284         }
1285
1286         CSR_WRITE_4(sc, MC0, filter[0]);
1287         CSR_WRITE_4(sc, MC1, filter[1]);
1288         CSR_WRITE_4(sc, MC2, filter[2]);
1289         CSR_WRITE_4(sc, MC3, filter[3]);
1290
1291         return;
1292 }
1293
1294 /*
1295  * Synopsis: calculate EPIC's hash of multicast address.
1296  */
1297 static u_int8_t
1298 epic_calchash(addr)
1299         caddr_t addr;
1300 {
1301         u_int32_t crc, carry;
1302         int i, j;
1303         u_int8_t c;
1304
1305         /* Compute CRC for the address value. */
1306         crc = 0xFFFFFFFF; /* initial value */
1307
1308         for (i = 0; i < 6; i++) {
1309                 c = *(addr + i);
1310                 for (j = 0; j < 8; j++) {
1311                         carry = ((crc & 0x80000000) ? 1 : 0) ^ (c & 0x01);
1312                         crc <<= 1;
1313                         c >>= 1;
1314                         if (carry)
1315                                 crc = (crc ^ 0x04c11db6) | carry;
1316                 }
1317         }
1318
1319         return ((crc >> 26) & 0x3F);
1320 }
1321
1322
1323 /*
1324  * Synopsis: Start receive process and transmit one, if they need.
1325  */
1326 static void
1327 epic_start_activity(sc)
1328         epic_softc_t *sc;
1329 {
1330         /* Start rx process */
1331         CSR_WRITE_4(sc, COMMAND,
1332                 COMMAND_RXQUEUED | COMMAND_START_RX |
1333                 (sc->pending_txs?COMMAND_TXQUEUED:0));
1334 }
1335
1336 /*
1337  * Synopsis: Completely stop Rx and Tx processes. If TQE is set additional
1338  * packet needs to be queued to stop Tx DMA.
1339  */
1340 static void
1341 epic_stop_activity(sc)
1342         epic_softc_t *sc;
1343 {
1344         int status, i;
1345
1346         /* Stop Tx and Rx DMA */
1347         CSR_WRITE_4(sc, COMMAND,
1348             COMMAND_STOP_RX | COMMAND_STOP_RDMA | COMMAND_STOP_TDMA);
1349
1350         /* Wait Rx and Tx DMA to stop (why 1 ms ??? XXX) */
1351         for (i=0; i<0x1000; i++) {
1352                 status = CSR_READ_4(sc, INTSTAT) & (INTSTAT_TXIDLE | INTSTAT_RXIDLE);
1353                 if (status == (INTSTAT_TXIDLE | INTSTAT_RXIDLE))
1354                         break;
1355                 DELAY(1);
1356         }
1357
1358         /* Catch all finished packets */
1359         epic_rx_done(sc);
1360         epic_tx_done(sc);
1361
1362         status = CSR_READ_4(sc, INTSTAT);
1363
1364         if ((status & INTSTAT_RXIDLE) == 0)
1365                 device_printf(sc->dev, "ERROR! Can't stop Rx DMA\n");
1366
1367         if ((status & INTSTAT_TXIDLE) == 0)
1368                 device_printf(sc->dev, "ERROR! Can't stop Tx DMA\n");
1369
1370         /*
1371          * May need to queue one more packet if TQE, this is rare
1372          * but existing case.
1373          */
1374         if ((status & INTSTAT_TQE) && !(status & INTSTAT_TXIDLE))
1375                 (void) epic_queue_last_packet(sc);
1376
1377 }
1378
1379 /*
1380  * The EPIC transmitter may stuck in TQE state. It will not go IDLE until
1381  * a packet from current descriptor will be copied to internal RAM. We
1382  * compose a dummy packet here and queue it for transmission.
1383  *
1384  * XXX the packet will then be actually sent over network...
1385  */
1386 static int
1387 epic_queue_last_packet(sc)
1388         epic_softc_t *sc;
1389 {
1390         struct epic_tx_desc *desc;
1391         struct epic_frag_list *flist;
1392         struct epic_tx_buffer *buf;
1393         struct mbuf *m0;
1394         int i;
1395
1396         device_printf(sc->dev, "queue last packet\n");
1397
1398         desc = sc->tx_desc + sc->cur_tx;
1399         flist = sc->tx_flist + sc->cur_tx;
1400         buf = sc->tx_buffer + sc->cur_tx;
1401
1402         if ((desc->status & 0x8000) || (buf->mbuf != NULL))
1403                 return (EBUSY);
1404
1405         MGETHDR(m0, MB_DONTWAIT, MT_DATA);
1406         if (NULL == m0)
1407                 return (ENOBUFS);
1408
1409         /* Prepare mbuf */
1410         m0->m_len = min(MHLEN, ETHER_MIN_LEN-ETHER_CRC_LEN);
1411         flist->frag[0].fraglen = m0->m_len;
1412         m0->m_pkthdr.len = m0->m_len;
1413         m0->m_pkthdr.rcvif = &sc->sc_if;
1414         bzero(mtod(m0,caddr_t), m0->m_len);
1415
1416         /* Fill fragments list */
1417         flist->frag[0].fraglen = m0->m_len;
1418         flist->frag[0].fragaddr = vtophys(mtod(m0, caddr_t));
1419         flist->numfrags = 1;
1420
1421         /* Fill in descriptor */
1422         buf->mbuf = m0;
1423         sc->pending_txs++;
1424         sc->cur_tx = (sc->cur_tx + 1) & TX_RING_MASK;
1425         desc->control = 0x01;
1426         desc->txlength = max(m0->m_pkthdr.len,ETHER_MIN_LEN-ETHER_CRC_LEN);
1427         desc->status = 0x8000;
1428
1429         /* Launch transmition */
1430         CSR_WRITE_4(sc, COMMAND, COMMAND_STOP_TDMA | COMMAND_TXQUEUED);
1431
1432         /* Wait Tx DMA to stop (for how long??? XXX) */
1433         for (i=0; i<1000; i++) {
1434                 if (CSR_READ_4(sc, INTSTAT) & INTSTAT_TXIDLE)
1435                         break;
1436                 DELAY(1);
1437         }
1438
1439         if ((CSR_READ_4(sc, INTSTAT) & INTSTAT_TXIDLE) == 0)
1440                 device_printf(sc->dev, "ERROR! can't stop Tx DMA (2)\n");
1441         else
1442                 epic_tx_done(sc);
1443
1444         return 0;
1445 }
1446
1447 /*
1448  *  Synopsis: Shut down board and deallocates rings.
1449  */
1450 static void
1451 epic_stop(sc)
1452         epic_softc_t *sc;
1453 {
1454
1455         crit_enter();
1456
1457         sc->sc_if.if_timer = 0;
1458
1459         callout_stop(&sc->tx_stat_timer);
1460
1461         /* Disable interrupts */
1462         CSR_WRITE_4(sc, INTMASK, 0);
1463         CSR_WRITE_4(sc, GENCTL, 0);
1464
1465         /* Try to stop Rx and TX processes */
1466         epic_stop_activity(sc);
1467
1468         /* Reset chip */
1469         CSR_WRITE_4(sc, GENCTL, GENCTL_SOFT_RESET);
1470         DELAY(1000);
1471
1472         /* Make chip go to bed */
1473         CSR_WRITE_4(sc, GENCTL, GENCTL_POWER_DOWN);
1474
1475         /* Free memory allocated for rings */
1476         epic_free_rings(sc);
1477
1478         /* Mark as stoped */
1479         sc->sc_if.if_flags &= ~IFF_RUNNING;
1480
1481         crit_exit();
1482         return;
1483 }
1484
1485 /*
1486  * Synopsis: This function should free all memory allocated for rings.
1487  */
1488 static void
1489 epic_free_rings(sc)
1490         epic_softc_t *sc;
1491 {
1492         int i;
1493
1494         for (i=0; i<RX_RING_SIZE; i++) {
1495                 struct epic_rx_buffer *buf = sc->rx_buffer + i;
1496                 struct epic_rx_desc *desc = sc->rx_desc + i;
1497                 
1498                 desc->status = 0;
1499                 desc->buflength = 0;
1500                 desc->bufaddr = 0;
1501
1502                 if (buf->mbuf) m_freem(buf->mbuf);
1503                 buf->mbuf = NULL;
1504         }
1505
1506         for (i=0; i<TX_RING_SIZE; i++) {
1507                 struct epic_tx_buffer *buf = sc->tx_buffer + i;
1508                 struct epic_tx_desc *desc = sc->tx_desc + i;
1509
1510                 desc->status = 0;
1511                 desc->buflength = 0;
1512                 desc->bufaddr = 0;
1513
1514                 if (buf->mbuf) m_freem(buf->mbuf);
1515                 buf->mbuf = NULL;
1516         }
1517 }
1518
1519 /*
1520  * Synopsis:  Allocates mbufs for Rx ring and point Rx descs to them.
1521  * Point Tx descs to fragment lists. Check that all descs and fraglists
1522  * are bounded and aligned properly.
1523  */
1524 static int
1525 epic_init_rings(sc)
1526         epic_softc_t *sc;
1527 {
1528         int i;
1529
1530         sc->cur_rx = sc->cur_tx = sc->dirty_tx = sc->pending_txs = 0;
1531
1532         for (i = 0; i < RX_RING_SIZE; i++) {
1533                 struct epic_rx_buffer *buf = sc->rx_buffer + i;
1534                 struct epic_rx_desc *desc = sc->rx_desc + i;
1535
1536                 desc->status = 0;               /* Owned by driver */
1537                 desc->next = vtophys(sc->rx_desc + ((i+1) & RX_RING_MASK));
1538
1539                 if ((desc->next & 3) ||
1540                     ((desc->next & PAGE_MASK) + sizeof *desc) > PAGE_SIZE) {
1541                         epic_free_rings(sc);
1542                         return EFAULT;
1543                 }
1544
1545                 EPIC_MGETCLUSTER(buf->mbuf);
1546                 if (NULL == buf->mbuf) {
1547                         epic_free_rings(sc);
1548                         return ENOBUFS;
1549                 }
1550                 desc->bufaddr = vtophys(mtod(buf->mbuf, caddr_t));
1551
1552                 desc->buflength = MCLBYTES;     /* Max RX buffer length */
1553                 desc->status = 0x8000;          /* Set owner bit to NIC */
1554         }
1555
1556         for (i = 0; i < TX_RING_SIZE; i++) {
1557                 struct epic_tx_buffer *buf = sc->tx_buffer + i;
1558                 struct epic_tx_desc *desc = sc->tx_desc + i;
1559
1560                 desc->status = 0;
1561                 desc->next = vtophys(sc->tx_desc + ((i+1) & TX_RING_MASK));
1562
1563                 if ((desc->next & 3) ||
1564                     ((desc->next & PAGE_MASK) + sizeof *desc) > PAGE_SIZE) {
1565                         epic_free_rings(sc);
1566                         return EFAULT;
1567                 }
1568
1569                 buf->mbuf = NULL;
1570                 desc->bufaddr = vtophys(sc->tx_flist + i);
1571
1572                 if ((desc->bufaddr & 3) ||
1573                     ((desc->bufaddr & PAGE_MASK) + sizeof(struct epic_frag_list)) > PAGE_SIZE) {
1574                         epic_free_rings(sc);
1575                         return EFAULT;
1576                 }
1577         }
1578
1579         return 0;
1580 }
1581
1582 /*
1583  * EEPROM operation functions
1584  */
1585 static void
1586 epic_write_eepromreg(sc, val)
1587         epic_softc_t *sc;
1588         u_int8_t val;
1589 {
1590         u_int16_t i;
1591
1592         CSR_WRITE_1(sc, EECTL, val);
1593
1594         for (i=0; i<0xFF; i++)
1595                 if ((CSR_READ_1(sc, EECTL) & 0x20) == 0) break;
1596
1597         return;
1598 }
1599
1600 static u_int8_t
1601 epic_read_eepromreg(sc)
1602         epic_softc_t *sc;
1603 {
1604         return CSR_READ_1(sc, EECTL);
1605 }
1606
1607 static u_int8_t
1608 epic_eeprom_clock(sc, val)
1609         epic_softc_t *sc;
1610         u_int8_t val;
1611 {
1612         epic_write_eepromreg(sc, val);
1613         epic_write_eepromreg(sc, (val | 0x4));
1614         epic_write_eepromreg(sc, val);
1615         
1616         return epic_read_eepromreg(sc);
1617 }
1618
1619 static void
1620 epic_output_eepromw(sc, val)
1621         epic_softc_t *sc;
1622         u_int16_t val;
1623 {
1624         int i;
1625
1626         for (i = 0xF; i >= 0; i--) {
1627                 if (val & (1 << i))
1628                         epic_eeprom_clock(sc, 0x0B);
1629                 else
1630                         epic_eeprom_clock(sc, 0x03);
1631         }
1632 }
1633
1634 static u_int16_t
1635 epic_input_eepromw(sc)
1636         epic_softc_t *sc;
1637 {
1638         u_int16_t retval = 0;
1639         int i;
1640
1641         for (i = 0xF; i >= 0; i--) {    
1642                 if (epic_eeprom_clock(sc, 0x3) & 0x10)
1643                         retval |= (1 << i);
1644         }
1645
1646         return retval;
1647 }
1648
1649 static int
1650 epic_read_eeprom(sc, loc)
1651         epic_softc_t *sc;
1652         u_int16_t loc;
1653 {
1654         u_int16_t dataval;
1655         u_int16_t read_cmd;
1656
1657         epic_write_eepromreg(sc, 3);
1658
1659         if (epic_read_eepromreg(sc) & 0x40)
1660                 read_cmd = (loc & 0x3F) | 0x180;
1661         else
1662                 read_cmd = (loc & 0xFF) | 0x600;
1663
1664         epic_output_eepromw(sc, read_cmd);
1665
1666         dataval = epic_input_eepromw(sc);
1667
1668         epic_write_eepromreg(sc, 1);
1669         
1670         return dataval;
1671 }
1672
1673 /*
1674  * Here goes MII read/write routines
1675  */
1676 static int
1677 epic_read_phy_reg(sc, phy, reg)
1678         epic_softc_t *sc;
1679         int phy, reg;
1680 {
1681         int i;
1682
1683         CSR_WRITE_4(sc, MIICTL, ((reg << 4) | (phy << 9) | 0x01));
1684
1685         for (i = 0; i < 0x100; i++) {
1686                 if ((CSR_READ_4(sc, MIICTL) & 0x01) == 0) break;
1687                 DELAY(1);
1688         }
1689
1690         return (CSR_READ_4(sc, MIIDATA));
1691 }
1692
1693 static void
1694 epic_write_phy_reg(sc, phy, reg, val)
1695         epic_softc_t *sc;
1696         int phy, reg, val;
1697 {
1698         int i;
1699
1700         CSR_WRITE_4(sc, MIIDATA, val);
1701         CSR_WRITE_4(sc, MIICTL, ((reg << 4) | (phy << 9) | 0x02));
1702
1703         for(i=0;i<0x100;i++) {
1704                 if ((CSR_READ_4(sc, MIICTL) & 0x02) == 0) break;
1705                 DELAY(1);
1706         }
1707
1708         return;
1709 }
1710
1711 static int
1712 epic_miibus_readreg(dev, phy, reg)
1713         device_t dev;
1714         int phy, reg;
1715 {
1716         epic_softc_t *sc;
1717
1718         sc = device_get_softc(dev);
1719
1720         return (PHY_READ_2(sc, phy, reg));
1721 }
1722
1723 static int
1724 epic_miibus_writereg(dev, phy, reg, data)
1725         device_t dev;
1726         int phy, reg, data;
1727 {
1728         epic_softc_t *sc;
1729
1730         sc = device_get_softc(dev);
1731
1732         PHY_WRITE_2(sc, phy, reg, data);
1733
1734         return (0);
1735 }