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