]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/dev/en/midway.c
This commit was generated by cvs2svn to compensate for changes in r136136,
[FreeBSD/FreeBSD.git] / sys / dev / en / midway.c
1 /*      $NetBSD: midway.c,v 1.30 1997/09/29 17:40:38 chuck Exp $        */
2 /*      (sync'd to midway.c 1.68)       */
3
4 /*
5  *
6  * Copyright (c) 1996 Charles D. Cranor and Washington University.
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. All advertising materials mentioning features or use of this software
18  *    must display the following acknowledgement:
19  *      This product includes software developed by Charles D. Cranor and
20  *      Washington University.
21  * 4. The name of the author may not be used to endorse or promote products
22  *    derived from this software without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
25  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
26  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
27  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
28  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
29  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
30  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
31  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
33  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34  */
35 #include <sys/cdefs.h>
36 __FBSDID("$FreeBSD$");
37
38 /*
39  *
40  * m i d w a y . c   e n i 1 5 5   d r i v e r 
41  *
42  * author: Chuck Cranor <chuck@ccrc.wustl.edu>
43  * started: spring, 1996 (written from scratch).
44  *
45  * notes from the author:
46  *   Extra special thanks go to Werner Almesberger, EPFL LRC.   Werner's
47  *   ENI driver was especially useful in figuring out how this card works.
48  *   I would also like to thank Werner for promptly answering email and being
49  *   generally helpful.
50  */
51
52 #define EN_DIAG
53 #define EN_DDBHOOK      1       /* compile in ddb functions */
54
55 /*
56  * Note on EN_ENIDMAFIX: the byte aligner on the ENI version of the card
57  * appears to be broken.   it works just fine if there is no load... however
58  * when the card is loaded the data get corrupted.   to see this, one only
59  * has to use "telnet" over ATM.   do the following command in "telnet":
60  *      cat /usr/share/misc/termcap
61  * "telnet" seems to generate lots of 1023 byte mbufs (which make great
62  * use of the byte aligner).   watch "netstat -s" for checksum errors.
63  * 
64  * I further tested this by adding a function that compared the transmit 
65  * data on the card's SRAM with the data in the mbuf chain _after_ the 
66  * "transmit DMA complete" interrupt.   using the "telnet" test I got data
67  * mismatches where the byte-aligned data should have been.   using ddb
68  * and en_dumpmem() I verified that the DTQs fed into the card were 
69  * absolutely correct.   thus, we are forced to concluded that the ENI
70  * hardware is buggy.   note that the Adaptec version of the card works
71  * just fine with byte DMA.
72  *
73  * bottom line: we set EN_ENIDMAFIX to 1 to avoid byte DMAs on the ENI
74  * card.
75  */
76
77 #if defined(DIAGNOSTIC) && !defined(EN_DIAG)
78 #define EN_DIAG                 /* link in with master DIAG option */
79 #endif
80
81 #define EN_COUNT(X) (X)++
82
83 #ifdef EN_DEBUG
84
85 #undef  EN_DDBHOOK
86 #define EN_DDBHOOK      1
87
88 /*
89  * This macro removes almost all the EN_DEBUG conditionals in the code that make
90  * to code a good deal less readable.
91  */
92 #define DBG(SC, FL, PRINT) do {                                         \
93         if ((SC)->debug & DBG_##FL) {                                   \
94                 if_printf(&(SC)->ifatm.ifnet, "%s: "#FL": ", __func__); \
95                 printf PRINT;                                           \
96                 printf("\n");                                           \
97         }                                                               \
98     } while (0)
99
100 enum {
101         DBG_INIT        = 0x0001,       /* debug attach/detach */
102         DBG_TX          = 0x0002,       /* debug transmitting */
103         DBG_SERV        = 0x0004,       /* debug service interrupts */
104         DBG_IOCTL       = 0x0008,       /* debug ioctls */
105         DBG_VC          = 0x0010,       /* debug VC handling */
106         DBG_INTR        = 0x0020,       /* debug interrupts */
107         DBG_DMA         = 0x0040,       /* debug DMA probing */
108         DBG_IPACKETS    = 0x0080,       /* print input packets */
109         DBG_REG         = 0x0100,       /* print all register access */
110         DBG_LOCK        = 0x0200,       /* debug locking */
111 };
112
113 #else /* EN_DEBUG */
114
115 #define DBG(SC, FL, PRINT) do { } while (0)
116
117 #endif /* EN_DEBUG */
118
119 #include "opt_inet.h"
120 #include "opt_natm.h"
121 #include "opt_ddb.h"
122
123 #ifdef DDB
124 #undef  EN_DDBHOOK
125 #define EN_DDBHOOK      1
126 #endif
127
128 #include <sys/param.h>
129 #include <sys/systm.h>
130 #include <sys/kdb.h>
131 #include <sys/queue.h>
132 #include <sys/sockio.h>
133 #include <sys/socket.h>
134 #include <sys/mbuf.h>
135 #include <sys/endian.h>
136 #include <sys/stdint.h>
137 #include <sys/lock.h>
138 #include <sys/mutex.h>
139 #include <sys/condvar.h>
140 #include <vm/uma.h>
141
142 #include <net/if.h>
143 #include <net/if_media.h>
144 #include <net/if_atm.h>
145
146 #if defined(INET) || defined(INET6)
147 #include <netinet/in.h>
148 #include <netinet/if_atm.h>
149 #endif
150
151 #ifdef NATM
152 #include <netnatm/natm.h>
153 #endif
154
155 #include <sys/bus.h>
156 #include <machine/bus.h>
157 #include <sys/rman.h>
158 #include <sys/module.h>
159 #include <sys/sysctl.h>
160 #include <sys/malloc.h>
161 #include <machine/resource.h>
162 #include <dev/utopia/utopia.h>
163 #include <dev/en/midwayreg.h>
164 #include <dev/en/midwayvar.h>
165
166 #include <net/bpf.h>
167
168 /*
169  * params
170  */
171 #ifndef EN_TXHIWAT
172 #define EN_TXHIWAT      (64 * 1024)     /* max 64 KB waiting to be DMAd out */
173 #endif
174
175 SYSCTL_DECL(_hw_atm);
176
177 /*
178  * dma tables
179  *
180  * The plan is indexed by the number of words to transfer.
181  * The maximum index is 15 for 60 words.
182  */
183 struct en_dmatab {
184         uint8_t bcode;          /* code */
185         uint8_t divshift;       /* byte divisor */
186 };
187
188 static const struct en_dmatab en_dmaplan[] = {
189   { 0, 0 },             /* 0 */         { MIDDMA_WORD, 2},      /* 1 */
190   { MIDDMA_2WORD, 3},   /* 2 */         { MIDDMA_WORD, 2},      /* 3 */
191   { MIDDMA_4WORD, 4},   /* 4 */         { MIDDMA_WORD, 2},      /* 5 */
192   { MIDDMA_2WORD, 3},   /* 6 */         { MIDDMA_WORD, 2},      /* 7 */
193   { MIDDMA_8WORD, 5},   /* 8 */         { MIDDMA_WORD, 2},      /* 9 */
194   { MIDDMA_2WORD, 3},   /* 10 */        { MIDDMA_WORD, 2},      /* 11 */
195   { MIDDMA_4WORD, 4},   /* 12 */        { MIDDMA_WORD, 2},      /* 13 */
196   { MIDDMA_2WORD, 3},   /* 14 */        { MIDDMA_WORD, 2},      /* 15 */
197   { MIDDMA_16WORD,6},   /* 16 */
198 };
199
200 /*
201  * prototypes
202  */
203 #ifdef EN_DDBHOOK
204 int en_dump(int unit, int level);
205 int en_dumpmem(int,int,int);
206 #endif
207 static void en_close_finish(struct en_softc *sc, struct en_vcc *vc);
208
209 #define EN_LOCK(SC)     do {                            \
210         DBG(SC, LOCK, ("ENLOCK %d\n", __LINE__));       \
211         mtx_lock(&sc->en_mtx);                          \
212     } while (0)
213 #define EN_UNLOCK(SC)   do {                            \
214         DBG(SC, LOCK, ("ENUNLOCK %d\n", __LINE__));     \
215         mtx_unlock(&sc->en_mtx);                        \
216     } while (0)
217 #define EN_CHECKLOCK(sc)        mtx_assert(&sc->en_mtx, MA_OWNED)
218
219 /*
220  * While a transmit mbuf is waiting to get transmit DMA resources we
221  * need to keep some information with it. We don't want to allocate
222  * additional memory for this so we stuff it into free fields in the
223  * mbuf packet header. Neither the checksum fields nor the rcvif field are used
224  * so use these.
225  */
226 #define TX_AAL5         0x1     /* transmit AAL5 PDU */
227 #define TX_HAS_TBD      0x2     /* TBD did fit into mbuf */
228 #define TX_HAS_PAD      0x4     /* padding did fit into mbuf */
229 #define TX_HAS_PDU      0x8     /* PDU trailer did fit into mbuf */
230
231 #define MBUF_SET_TX(M, VCI, FLAGS, DATALEN, PAD, MAP) do {              \
232         (M)->m_pkthdr.csum_data = (VCI) | ((FLAGS) << MID_VCI_BITS);    \
233         (M)->m_pkthdr.csum_flags = ((DATALEN) & 0xffff) |               \
234             ((PAD & 0x3f) << 16);                                       \
235         (M)->m_pkthdr.rcvif = (void *)(MAP);                            \
236     } while (0)
237
238 #define MBUF_GET_TX(M, VCI, FLAGS, DATALEN, PAD, MAP) do {              \
239         (VCI) = (M)->m_pkthdr.csum_data & ((1 << MID_VCI_BITS) - 1);    \
240         (FLAGS) = ((M)->m_pkthdr.csum_data >> MID_VCI_BITS) & 0xf;      \
241         (DATALEN) = (M)->m_pkthdr.csum_flags & 0xffff;                  \
242         (PAD) = ((M)->m_pkthdr.csum_flags >> 16) & 0x3f;                \
243         (MAP) = (void *)((M)->m_pkthdr.rcvif);                          \
244     } while (0)
245
246
247 #define EN_WRAPADD(START, STOP, CUR, VAL) do {                  \
248         (CUR) = (CUR) + (VAL);                                  \
249         if ((CUR) >= (STOP))                                    \
250                 (CUR) = (START) + ((CUR) - (STOP));             \
251     } while (0)
252
253 #define WORD_IDX(START, X) (((X) - (START)) / sizeof(uint32_t))
254
255 #define SETQ_END(SC, VAL) ((SC)->is_adaptec ?                   \
256         ((VAL) | (MID_DMA_END >> 4)) :                          \
257         ((VAL) | (MID_DMA_END)))
258
259 /*
260  * The dtq and drq members are set for each END entry in the corresponding
261  * card queue entry. It is used to find out, when a buffer has been
262  * finished DMAing and can be freed.
263  *
264  * We store sc->dtq and sc->drq data in the following format...
265  * the 0x80000 ensures we != 0
266  */
267 #define EN_DQ_MK(SLOT, LEN)     (((SLOT) << 20) | (LEN) | (0x80000))
268 #define EN_DQ_SLOT(X)           ((X) >> 20)
269 #define EN_DQ_LEN(X)            ((X) & 0x3ffff)
270
271 /*
272  * Variables
273  */
274 static uma_zone_t en_vcc_zone;
275
276 /***********************************************************************/
277
278 /*
279  * en_read{x}: read a word from the card. These are the only functions
280  * that read from the card.
281  */
282 static __inline uint32_t
283 en_readx(struct en_softc *sc, uint32_t r)
284 {
285         uint32_t v;
286
287 #ifdef EN_DIAG
288         if (r > MID_MAXOFF || (r % 4))
289                 panic("en_read out of range, r=0x%x", r);
290 #endif
291         v = bus_space_read_4(sc->en_memt, sc->en_base, r);
292         return (v);
293 }
294
295 static __inline uint32_t
296 en_read(struct en_softc *sc, uint32_t r)
297 {
298         uint32_t v;
299
300 #ifdef EN_DIAG
301         if (r > MID_MAXOFF || (r % 4))
302                 panic("en_read out of range, r=0x%x", r);
303 #endif
304         v = bus_space_read_4(sc->en_memt, sc->en_base, r);
305         DBG(sc, REG, ("en_read(%#x) -> %08x", r, v));
306         return (v);
307 }
308
309 /*
310  * en_write: write a word to the card. This is the only function that
311  * writes to the card.
312  */
313 static __inline void
314 en_write(struct en_softc *sc, uint32_t r, uint32_t v)
315 {
316 #ifdef EN_DIAG
317         if (r > MID_MAXOFF || (r % 4))
318                 panic("en_write out of range, r=0x%x", r);
319 #endif
320         DBG(sc, REG, ("en_write(%#x) <- %08x", r, v));
321         bus_space_write_4(sc->en_memt, sc->en_base, r, v);
322 }
323
324 /*
325  * en_k2sz: convert KBytes to a size parameter (a log2)
326  */
327 static __inline int
328 en_k2sz(int k)
329 {
330         switch(k) {
331           case 1:   return (0);
332           case 2:   return (1);
333           case 4:   return (2);
334           case 8:   return (3);
335           case 16:  return (4);
336           case 32:  return (5);
337           case 64:  return (6);
338           case 128: return (7);
339           default:
340                 panic("en_k2sz");
341         }
342         return (0);
343 }
344 #define en_log2(X) en_k2sz(X)
345
346 /*
347  * en_b2sz: convert a DMA burst code to its byte size
348  */
349 static __inline int
350 en_b2sz(int b)
351 {
352         switch (b) {
353           case MIDDMA_WORD:   return (1*4);
354           case MIDDMA_2WMAYBE:
355           case MIDDMA_2WORD:  return (2*4);
356           case MIDDMA_4WMAYBE:
357           case MIDDMA_4WORD:  return (4*4);
358           case MIDDMA_8WMAYBE:
359           case MIDDMA_8WORD:  return (8*4);
360           case MIDDMA_16WMAYBE:
361           case MIDDMA_16WORD: return (16*4);
362           default:
363                 panic("en_b2sz");
364         }
365         return (0);
366 }
367
368 /*
369  * en_sz2b: convert a burst size (bytes) to DMA burst code
370  */
371 static __inline int
372 en_sz2b(int sz)
373 {
374         switch (sz) {
375           case 1*4:  return (MIDDMA_WORD);
376           case 2*4:  return (MIDDMA_2WORD);
377           case 4*4:  return (MIDDMA_4WORD);
378           case 8*4:  return (MIDDMA_8WORD);
379           case 16*4: return (MIDDMA_16WORD);
380           default:
381                 panic("en_sz2b");
382         }
383         return(0);
384 }
385
386 #ifdef EN_DEBUG
387 /*
388  * Dump a packet
389  */
390 static void
391 en_dump_packet(struct en_softc *sc, struct mbuf *m)
392 {
393         int plen = m->m_pkthdr.len;
394         u_int pos = 0;
395         u_int totlen = 0;
396         int len;
397         u_char *ptr;
398
399         if_printf(&sc->ifatm.ifnet, "packet len=%d", plen);
400         while (m != NULL) {
401                 totlen += m->m_len;
402                 ptr = mtod(m, u_char *);
403                 for (len = 0; len < m->m_len; len++, pos++, ptr++) {
404                         if (pos % 16 == 8)
405                                 printf(" ");
406                         if (pos % 16 == 0)
407                                 printf("\n");
408                         printf(" %02x", *ptr);
409                 }
410                 m = m->m_next;
411         }
412         printf("\n");
413         if (totlen != plen)
414                 printf("sum of m_len=%u\n", totlen);
415 }
416 #endif
417
418 /*********************************************************************/
419 /*
420  * DMA maps
421  */
422
423 /*
424  * Map constructor for a MAP.
425  *
426  * This is called each time when a map is allocated
427  * from the pool and about to be returned to the user. Here we actually
428  * allocate the map if there isn't one. The problem is that we may fail
429  * to allocate the DMA map yet have no means to signal this error. Therefor
430  * when allocating a map, the call must check that there is a map. An
431  * additional problem is, that i386 maps will be NULL, yet are ok and must
432  * be freed so let's use a flag to signal allocation.
433  *
434  * Caveat: we have no way to know that we are called from an interrupt context
435  * here. We rely on the fact, that bus_dmamap_create uses M_NOWAIT in all
436  * its allocations.
437  *
438  * LOCK: any, not needed
439  */
440 static int
441 en_map_ctor(void *mem, int size, void *arg, int flags)
442 {
443         struct en_softc *sc = arg;
444         struct en_map *map = mem;
445         int err;
446
447         err = bus_dmamap_create(sc->txtag, 0, &map->map);
448         if (err != 0) {
449                 if_printf(&sc->ifatm.ifnet, "cannot create DMA map %d\n", err);
450                 return (err);
451         }
452         map->flags = ENMAP_ALLOC;
453         map->sc = sc;
454         return (0);
455 }
456
457 /*
458  * Map destructor.
459  *
460  * Called when a map is disposed into the zone. If the map is loaded, unload
461  * it.
462  *
463  * LOCK: any, not needed
464  */
465 static void
466 en_map_dtor(void *mem, int size, void *arg)
467 {
468         struct en_map *map = mem;
469
470         if (map->flags & ENMAP_LOADED) {
471                 bus_dmamap_unload(map->sc->txtag, map->map);
472                 map->flags &= ~ENMAP_LOADED;
473         }
474 }
475
476 /*
477  * Map finializer.
478  *
479  * This is called each time a map is returned from the zone to the system.
480  * Get rid of the dmamap here.
481  *
482  * LOCK: any, not needed
483  */
484 static void
485 en_map_fini(void *mem, int size)
486 {
487         struct en_map *map = mem;
488
489         bus_dmamap_destroy(map->sc->txtag, map->map);
490 }
491
492 /*********************************************************************/
493 /*
494  * Transmission
495  */
496
497 /*
498  * Argument structure to load a transmit DMA map
499  */
500 struct txarg {
501         struct en_softc *sc;
502         struct mbuf *m;
503         u_int vci;
504         u_int chan;             /* transmit channel */
505         u_int datalen;          /* length of user data */
506         u_int flags;
507         u_int wait;             /* return: out of resources */
508 };
509
510 /*
511  * TX DMA map loader helper. This function is the callback when the map
512  * is loaded. It should fill the DMA segment descriptors into the hardware.
513  *
514  * LOCK: locked, needed
515  */
516 static void
517 en_txdma_load(void *uarg, bus_dma_segment_t *segs, int nseg, bus_size_t mapsize,
518     int error)
519 {
520         struct txarg *tx = uarg;
521         struct en_softc *sc = tx->sc;
522         struct en_txslot *slot = &sc->txslot[tx->chan];
523         uint32_t cur;           /* on-card buffer position (bytes offset) */
524         uint32_t dtq;           /* on-card queue position (byte offset) */
525         uint32_t last_dtq;      /* last DTQ we have written */
526         uint32_t tmp;
527         u_int free;             /* free queue entries on card */
528         u_int needalign, cnt;
529         bus_size_t rest;        /* remaining bytes in current segment */
530         bus_addr_t addr;
531         bus_dma_segment_t *s;
532         uint32_t count, bcode;
533         int i;
534
535         if (error != 0)
536                 return;
537
538         cur = slot->cur;
539         dtq = sc->dtq_us;
540         free = sc->dtq_free;
541
542         last_dtq = 0;           /* make gcc happy */
543
544         /*
545          * Local macro to add an entry to the transmit DMA area. If there
546          * are no entries left, return. Save the byte offset of the entry
547          * in last_dtq for later use.
548          */
549 #define PUT_DTQ_ENTRY(ENI, BCODE, COUNT, ADDR)                          \
550         if (free == 0) {                                                \
551                 EN_COUNT(sc->stats.txdtqout);                           \
552                 tx->wait = 1;                                           \
553                 return;                                                 \
554         }                                                               \
555         last_dtq = dtq;                                                 \
556         en_write(sc, dtq + 0, (ENI || !sc->is_adaptec) ?                \
557             MID_MK_TXQ_ENI(COUNT, tx->chan, 0, BCODE) :                 \
558             MID_MK_TXQ_ADP(COUNT, tx->chan, 0, BCODE));                 \
559         en_write(sc, dtq + 4, ADDR);                                    \
560                                                                         \
561         EN_WRAPADD(MID_DTQOFF, MID_DTQEND, dtq, 8);                     \
562         free--;
563
564         /*
565          * Local macro to generate a DMA entry to DMA cnt bytes. Updates
566          * the current buffer byte offset accordingly.
567          */
568 #define DO_DTQ(TYPE) do {                                               \
569         rest -= cnt;                                                    \
570         EN_WRAPADD(slot->start, slot->stop, cur, cnt);                  \
571         DBG(sc, TX, ("tx%d: "TYPE" %u bytes, %ju left, cur %#x",        \
572             tx->chan, cnt, (uintmax_t)rest, cur));                      \
573                                                                         \
574         PUT_DTQ_ENTRY(1, bcode, count, addr);                           \
575                                                                         \
576         addr += cnt;                                                    \
577     } while (0)
578
579         if (!(tx->flags & TX_HAS_TBD)) {
580                 /*
581                  * Prepend the TBD - it did not fit into the first mbuf
582                  */
583                 tmp = MID_TBD_MK1((tx->flags & TX_AAL5) ?
584                     MID_TBD_AAL5 : MID_TBD_NOAAL5,
585                     sc->vccs[tx->vci]->txspeed,
586                     tx->m->m_pkthdr.len / MID_ATMDATASZ);
587                 en_write(sc, cur, tmp);
588                 EN_WRAPADD(slot->start, slot->stop, cur, 4);
589
590                 tmp = MID_TBD_MK2(tx->vci, 0, 0);
591                 en_write(sc, cur, tmp);
592                 EN_WRAPADD(slot->start, slot->stop, cur, 4);
593
594                 /* update DMA address */
595                 PUT_DTQ_ENTRY(0, MIDDMA_JK, WORD_IDX(slot->start, cur), 0);
596         }
597
598         for (i = 0, s = segs; i < nseg; i++, s++) {
599                 rest = s->ds_len;
600                 addr = s->ds_addr;
601
602                 if (sc->is_adaptec) {
603                         /* adaptec card - simple */
604
605                         /* advance the on-card buffer pointer */
606                         EN_WRAPADD(slot->start, slot->stop, cur, rest);
607                         DBG(sc, TX, ("tx%d: adp %ju bytes %#jx (cur now 0x%x)",
608                             tx->chan, (uintmax_t)rest, (uintmax_t)addr, cur));
609
610                         PUT_DTQ_ENTRY(0, 0, rest, addr);
611
612                         continue;
613                 }
614
615                 /*
616                  * do we need to do a DMA op to align to the maximum
617                  * burst? Note, that we are alway 32-bit aligned.
618                  */
619                 if (sc->alburst &&
620                     (needalign = (addr & sc->bestburstmask)) != 0) {
621                         /* compute number of bytes, words and code */
622                         cnt = sc->bestburstlen - needalign;
623                         if (cnt > rest)
624                                 cnt = rest;
625                         count = cnt / sizeof(uint32_t);
626                         if (sc->noalbursts) {
627                                 bcode = MIDDMA_WORD;
628                         } else {
629                                 bcode = en_dmaplan[count].bcode;
630                                 count = cnt >> en_dmaplan[count].divshift;
631                         }
632                         DO_DTQ("al_dma");
633                 }
634
635                 /* do we need to do a max-sized burst? */
636                 if (rest >= sc->bestburstlen) {
637                         count = rest >> sc->bestburstshift;
638                         cnt = count << sc->bestburstshift;
639                         bcode = sc->bestburstcode;
640                         DO_DTQ("best_dma");
641                 }
642
643                 /* do we need to do a cleanup burst? */
644                 if (rest != 0) {
645                         cnt = rest;
646                         count = rest / sizeof(uint32_t);
647                         if (sc->noalbursts) {
648                                 bcode = MIDDMA_WORD;
649                         } else {
650                                 bcode = en_dmaplan[count].bcode;
651                                 count = cnt >> en_dmaplan[count].divshift;
652                         }
653                         DO_DTQ("clean_dma");
654                 }
655         }
656
657         KASSERT (tx->flags & TX_HAS_PAD, ("PDU not padded"));
658
659         if ((tx->flags & TX_AAL5) && !(tx->flags & TX_HAS_PDU)) {
660                 /*
661                  * Append the AAL5 PDU trailer
662                  */
663                 tmp = MID_PDU_MK1(0, 0, tx->datalen);
664                 en_write(sc, cur, tmp);
665                 EN_WRAPADD(slot->start, slot->stop, cur, 4);
666
667                 en_write(sc, cur, 0);
668                 EN_WRAPADD(slot->start, slot->stop, cur, 4);
669
670                 /* update DMA address */
671                 PUT_DTQ_ENTRY(0, MIDDMA_JK, WORD_IDX(slot->start, cur), 0);
672         }
673
674         /* record the end for the interrupt routine */
675         sc->dtq[MID_DTQ_A2REG(last_dtq)] =
676             EN_DQ_MK(tx->chan, tx->m->m_pkthdr.len);
677
678         /* set the end flag in the last descriptor */
679         en_write(sc, last_dtq + 0, SETQ_END(sc, en_read(sc, last_dtq + 0)));
680
681 #undef PUT_DTQ_ENTRY
682 #undef DO_DTQ
683
684         /* commit */
685         slot->cur = cur;
686         sc->dtq_free = free;
687         sc->dtq_us = dtq;
688
689         /* tell card */
690         en_write(sc, MID_DMA_WRTX, MID_DTQ_A2REG(sc->dtq_us));
691 }
692
693 /*
694  * en_txdma: start transmit DMA on the given channel, if possible
695  *
696  * This is called from two places: when we got new packets from the upper
697  * layer or when we found that buffer space has freed up during interrupt
698  * processing.
699  *
700  * LOCK: locked, needed
701  */
702 static void
703 en_txdma(struct en_softc *sc, struct en_txslot *slot)
704 {
705         struct en_map *map;
706         struct mbuf *lastm;
707         struct txarg tx;
708         u_int pad;
709         int error;
710
711         DBG(sc, TX, ("tx%td: starting ...", slot - sc->txslot));
712   again:
713         bzero(&tx, sizeof(tx));
714         tx.chan = slot - sc->txslot;
715         tx.sc = sc;
716
717         /*
718          * get an mbuf waiting for DMA
719          */
720         _IF_DEQUEUE(&slot->q, tx.m);
721         if (tx.m == NULL) {
722                 DBG(sc, TX, ("tx%td: ...done!", slot - sc->txslot));
723                 return;
724         }
725         MBUF_GET_TX(tx.m, tx.vci, tx.flags, tx.datalen, pad, map);
726
727         /*
728          * note: don't use the entire buffer space.  if WRTX becomes equal
729          * to RDTX, the transmitter stops assuming the buffer is empty!  --kjc
730          */
731         if (tx.m->m_pkthdr.len >= slot->bfree) {
732                 EN_COUNT(sc->stats.txoutspace);
733                 DBG(sc, TX, ("tx%td: out of transmit space", slot - sc->txslot));
734                 goto waitres;
735         }
736   
737         lastm = NULL;
738         if (!(tx.flags & TX_HAS_PAD)) {
739                 if (pad != 0) {
740                         /* Append the padding buffer */
741                         (void)m_length(tx.m, &lastm);
742                         lastm->m_next = sc->padbuf;
743                         sc->padbuf->m_len = pad;
744                 }
745                 tx.flags |= TX_HAS_PAD;
746         }
747
748         /*
749          * Try to load that map
750          */
751         error = bus_dmamap_load_mbuf(sc->txtag, map->map, tx.m,
752             en_txdma_load, &tx, BUS_DMA_NOWAIT);
753
754         if (lastm != NULL)
755                 lastm->m_next = NULL;
756
757         if (error != 0) {
758                 if_printf(&sc->ifatm.ifnet, "loading TX map failed %d\n",
759                     error);
760                 goto dequeue_drop;
761         }
762         map->flags |= ENMAP_LOADED;
763         if (tx.wait) {
764                 /* probably not enough space */
765                 bus_dmamap_unload(map->sc->txtag, map->map);
766                 map->flags &= ~ENMAP_LOADED;
767
768                 sc->need_dtqs = 1;
769                 DBG(sc, TX, ("tx%td: out of transmit DTQs", slot - sc->txslot));
770                 goto waitres;
771         }
772
773         EN_COUNT(sc->stats.launch);
774         sc->ifatm.ifnet.if_opackets++;
775
776         sc->vccs[tx.vci]->opackets++;
777         sc->vccs[tx.vci]->obytes += tx.datalen;
778
779 #ifdef ENABLE_BPF
780         if (sc->ifatm.ifnet.if_bpf != NULL) {
781                 /*
782                  * adjust the top of the mbuf to skip the TBD if present
783                  * before passing the packet to bpf.
784                  * Also remove padding and the PDU trailer. Assume both of
785                  * them to be in the same mbuf. pktlen, m_len and m_data
786                  * are not needed anymore so we can change them.
787                  */
788                 if (tx.flags & TX_HAS_TBD) {
789                         tx.m->m_data += MID_TBD_SIZE;
790                         tx.m->m_len -= MID_TBD_SIZE;
791                 }
792                 tx.m->m_pkthdr.len = m_length(tx.m, &lastm);
793                 if (tx.m->m_pkthdr.len > tx.datalen) {
794                         lastm->m_len -= tx.m->m_pkthdr.len - tx.datalen;
795                         tx.m->m_pkthdr.len = tx.datalen;
796                 }
797
798                 BPF_MTAP(&sc->ifatm.ifnet, tx.m);
799         }
800 #endif
801
802         /*
803          * do some housekeeping and get the next packet
804          */
805         slot->bfree -= tx.m->m_pkthdr.len;
806         _IF_ENQUEUE(&slot->indma, tx.m);
807
808         goto again;
809
810         /*
811          * error handling. This is jumped to when we just want to drop
812          * the packet. Must be unlocked here.
813          */
814   dequeue_drop:
815         if (map != NULL)
816                 uma_zfree(sc->map_zone, map);
817
818         slot->mbsize -= tx.m->m_pkthdr.len;
819
820         m_freem(tx.m);
821
822         goto again;
823
824   waitres:
825         _IF_PREPEND(&slot->q, tx.m);
826 }
827
828 /*
829  * Create a copy of a single mbuf. It can have either internal or
830  * external data, it may have a packet header. External data is really
831  * copied, so the new buffer is writeable.
832  *
833  * LOCK: any, not needed
834  */
835 static struct mbuf *
836 copy_mbuf(struct mbuf *m)
837 {
838         struct mbuf *new;
839
840         MGET(new, M_TRYWAIT, MT_DATA);
841         if (new == NULL)
842                 return (NULL);
843
844         if (m->m_flags & M_PKTHDR) {
845                 M_MOVE_PKTHDR(new, m);
846                 if (m->m_len > MHLEN) {
847                         MCLGET(new, M_TRYWAIT);
848                         if ((m->m_flags & M_EXT) == 0) {
849                                 m_free(new);
850                                 return (NULL);
851                         }
852                 }
853         } else {
854                 if (m->m_len > MLEN) {
855                         MCLGET(new, M_TRYWAIT);
856                         if ((m->m_flags & M_EXT) == 0) {
857                                 m_free(new);
858                                 return (NULL);
859                         }
860                 }
861         }
862
863         bcopy(m->m_data, new->m_data, m->m_len);
864         new->m_len = m->m_len;
865         new->m_flags &= ~M_RDONLY;
866
867         return (new);
868 }
869
870 /*
871  * This function is called when we have an ENI adapter. It fixes the
872  * mbuf chain, so that all addresses and lengths are 4 byte aligned.
873  * The overall length is already padded to multiple of cells plus the
874  * TBD so this must always succeed. The routine can fail, when it
875  * needs to copy an mbuf (this may happen if an mbuf is readonly).
876  *
877  * We assume here, that aligning the virtual addresses to 4 bytes also
878  * aligns the physical addresses.
879  *
880  * LOCK: locked, needed
881  */
882 static struct mbuf *
883 en_fix_mchain(struct en_softc *sc, struct mbuf *m0, u_int *pad)
884 {
885         struct mbuf **prev = &m0;
886         struct mbuf *m = m0;
887         struct mbuf *new;
888         u_char *d;
889         int off;
890
891         while (m != NULL) {
892                 d = mtod(m, u_char *);
893                 if ((off = (uintptr_t)d % sizeof(uint32_t)) != 0) {
894                         EN_COUNT(sc->stats.mfixaddr);
895                         if (M_WRITABLE(m)) {
896                                 bcopy(d, d - off, m->m_len);
897                                 m->m_data -= off;
898                         } else {
899                                 if ((new = copy_mbuf(m)) == NULL) {
900                                         EN_COUNT(sc->stats.mfixfail);
901                                         m_freem(m0);
902                                         return (NULL);
903                                 }
904                                 new->m_next = m_free(m);
905                                 *prev = m = new;
906                         }
907                 }
908
909                 if ((off = m->m_len % sizeof(uint32_t)) != 0) {
910                         EN_COUNT(sc->stats.mfixlen);
911                         if (!M_WRITABLE(m)) {
912                                 if ((new = copy_mbuf(m)) == NULL) {
913                                         EN_COUNT(sc->stats.mfixfail);
914                                         m_freem(m0);
915                                         return (NULL);
916                                 }
917                                 new->m_next = m_free(m);
918                                 *prev = m = new;
919                         }
920                         d = mtod(m, u_char *) + m->m_len;
921                         off = 4 - off;
922                         while (off) {
923                                 while (m->m_next && m->m_next->m_len == 0)
924                                         m->m_next = m_free(m->m_next);
925
926                                 if (m->m_next == NULL) {
927                                         *d++ = 0;
928                                         KASSERT(*pad > 0, ("no padding space"));
929                                         (*pad)--;
930                                 } else {
931                                         *d++ = *mtod(m->m_next, u_char *);
932                                         m->m_next->m_len--;
933                                         m->m_next->m_data++;
934                                 }
935                                 m->m_len++;
936                                 off--;
937                         }
938                 }
939
940                 prev = &m->m_next;
941                 m = m->m_next;
942         }
943
944         return (m0);
945 }
946
947 /*
948  * en_start: start transmitting the next packet that needs to go out
949  * if there is one. We take off all packets from the interface's queue and
950  * put them into the channels queue.
951  *
952  * Here we also prepend the transmit packet descriptor and append the padding
953  * and (for aal5) the PDU trailer. This is different from the original driver:
954  * we assume, that allocating one or two additional mbufs is actually cheaper
955  * than all this algorithmic fiddling we would need otherwise.
956  *
957  * While the packet is on the channels wait queue we use the csum_* fields
958  * in the packet header to hold the original datalen, the AAL5 flag and the
959  * VCI. The packet length field in the header holds the needed buffer space.
960  * This may actually be more than the length of the current mbuf chain (when
961  * one or more of TBD, padding and PDU do not fit).
962  *
963  * LOCK: unlocked, needed
964  */
965 static void
966 en_start(struct ifnet *ifp)
967 {
968         struct en_softc *sc = (struct en_softc *)ifp->if_softc;
969         struct mbuf *m, *lastm;
970         struct atm_pseudohdr *ap;
971         u_int pad;              /* 0-bytes to pad at PDU end */
972         u_int datalen;          /* length of user data */
973         u_int vci;              /* the VCI we are transmitting on */
974         u_int flags;
975         uint32_t tbd[2];
976         uint32_t pdu[2];
977         struct en_vcc *vc;
978         struct en_map *map;
979         struct en_txslot *tx;
980
981         while (1) {
982                 IF_DEQUEUE(&ifp->if_snd, m);
983                 if (m == NULL)
984                         return;
985
986                 flags = 0;
987
988                 ap = mtod(m, struct atm_pseudohdr *);
989                 vci = ATM_PH_VCI(ap);
990
991                 if (ATM_PH_VPI(ap) != 0 || vci >= MID_N_VC ||
992                     (vc = sc->vccs[vci]) == NULL ||
993                     (vc->vflags & VCC_CLOSE_RX)) {
994                         DBG(sc, TX, ("output vpi=%u, vci=%u -- drop",
995                             ATM_PH_VPI(ap), vci));
996                         m_freem(m);
997                         continue;
998                 }
999                 if (vc->vcc.aal == ATMIO_AAL_5)
1000                         flags |= TX_AAL5;
1001                 m_adj(m, sizeof(struct atm_pseudohdr));
1002
1003                 /*
1004                  * (re-)calculate size of packet (in bytes)
1005                  */
1006                 m->m_pkthdr.len = datalen = m_length(m, &lastm);
1007
1008                 /*
1009                  * computing how much padding we need on the end of the mbuf,
1010                  * then see if we can put the TBD at the front of the mbuf
1011                  * where the link header goes (well behaved protocols will
1012                  * reserve room for us). Last, check if room for PDU tail.
1013                  */
1014                 if (flags & TX_AAL5)
1015                         m->m_pkthdr.len += MID_PDU_SIZE;
1016                 m->m_pkthdr.len = roundup(m->m_pkthdr.len, MID_ATMDATASZ);
1017                 pad = m->m_pkthdr.len - datalen;
1018                 if (flags & TX_AAL5)
1019                         pad -= MID_PDU_SIZE;
1020                 m->m_pkthdr.len += MID_TBD_SIZE;
1021
1022                 DBG(sc, TX, ("txvci%d: buflen=%u datalen=%u lead=%d trail=%d",
1023                     vci, m->m_pkthdr.len, datalen, (int)M_LEADINGSPACE(m),
1024                     (int)M_TRAILINGSPACE(lastm)));
1025
1026                 /*
1027                  * From here on we need access to sc
1028                  */
1029                 EN_LOCK(sc);
1030
1031                 /*
1032                  * Allocate a map. We do this here rather then in en_txdma,
1033                  * because en_txdma is also called from the interrupt handler
1034                  * and we are going to have a locking problem then. We must
1035                  * use NOWAIT here, because the ip_output path holds various
1036                  * locks.
1037                  */
1038                 map = uma_zalloc_arg(sc->map_zone, sc, M_NOWAIT);
1039                 if (map == NULL) {
1040                         /* drop that packet */
1041                         EN_COUNT(sc->stats.txnomap);
1042                         EN_UNLOCK(sc);
1043                         m_freem(m);
1044                         continue;
1045                 }
1046
1047                 if ((ifp->if_flags & IFF_RUNNING) == 0) {
1048                         EN_UNLOCK(sc);
1049                         uma_zfree(sc->map_zone, map);
1050                         m_freem(m);
1051                         continue;
1052                 }
1053
1054                 /*
1055                  * Look, whether we can prepend the TBD (8 byte)
1056                  */
1057                 if (M_WRITABLE(m) && M_LEADINGSPACE(m) >= MID_TBD_SIZE) {
1058                         tbd[0] = htobe32(MID_TBD_MK1((flags & TX_AAL5) ?
1059                             MID_TBD_AAL5 : MID_TBD_NOAAL5,
1060                             vc->txspeed, m->m_pkthdr.len / MID_ATMDATASZ));
1061                         tbd[1] = htobe32(MID_TBD_MK2(vci, 0, 0));
1062
1063                         m->m_data -= MID_TBD_SIZE;
1064                         bcopy(tbd, m->m_data, MID_TBD_SIZE);
1065                         m->m_len += MID_TBD_SIZE;
1066                         flags |= TX_HAS_TBD;
1067                 }
1068
1069                 /*
1070                  * Check whether the padding fits (must be writeable -
1071                  * we pad with zero).
1072                  */
1073                 if (M_WRITABLE(lastm) && M_TRAILINGSPACE(lastm) >= pad) {
1074                         bzero(lastm->m_data + lastm->m_len, pad);
1075                         lastm->m_len += pad;
1076                         flags |= TX_HAS_PAD;
1077
1078                         if ((flags & TX_AAL5) &&
1079                             M_TRAILINGSPACE(lastm) > MID_PDU_SIZE) {
1080                                 pdu[0] = htobe32(MID_PDU_MK1(0, 0, datalen));
1081                                 pdu[1] = 0;
1082                                 bcopy(pdu, lastm->m_data + lastm->m_len,
1083                                     MID_PDU_SIZE);
1084                                 lastm->m_len += MID_PDU_SIZE;
1085                                 flags |= TX_HAS_PDU;
1086                         }
1087                 }
1088
1089                 if (!sc->is_adaptec &&
1090                     (m = en_fix_mchain(sc, m, &pad)) == NULL) {
1091                         EN_UNLOCK(sc);
1092                         uma_zfree(sc->map_zone, map);
1093                         continue;
1094                 }
1095
1096                 /*
1097                  * get assigned channel (will be zero unless txspeed is set)
1098                  */
1099                 tx = vc->txslot;
1100
1101                 if (m->m_pkthdr.len > EN_TXSZ * 1024) {
1102                         DBG(sc, TX, ("tx%zu: packet larger than xmit buffer "
1103                             "(%d > %d)\n", tx - sc->txslot, m->m_pkthdr.len,
1104                             EN_TXSZ * 1024));
1105                         EN_UNLOCK(sc);
1106                         m_freem(m);
1107                         uma_zfree(sc->map_zone, map);
1108                         continue;
1109                 }
1110
1111                 if (tx->mbsize > EN_TXHIWAT) {
1112                         EN_COUNT(sc->stats.txmbovr);
1113                         DBG(sc, TX, ("tx%d: buffer space shortage",
1114                             tx - sc->txslot));
1115                         EN_UNLOCK(sc);
1116                         m_freem(m);
1117                         uma_zfree(sc->map_zone, map);
1118                         continue;
1119                 }
1120
1121                 /* commit */
1122                 tx->mbsize += m->m_pkthdr.len;
1123
1124                 DBG(sc, TX, ("tx%zu: VCI=%d, speed=0x%x, buflen=%d, mbsize=%d",
1125                     tx - sc->txslot, vci, sc->vccs[vci]->txspeed,
1126                     m->m_pkthdr.len, tx->mbsize));
1127
1128                 MBUF_SET_TX(m, vci, flags, datalen, pad, map);
1129
1130                 _IF_ENQUEUE(&tx->q, m);
1131
1132                 en_txdma(sc, tx);
1133
1134                 EN_UNLOCK(sc);
1135         }
1136 }
1137
1138 /*********************************************************************/
1139 /*
1140  * VCs
1141  */
1142
1143 /*
1144  * en_loadvc: load a vc tab entry from a slot
1145  *
1146  * LOCK: locked, needed
1147  */
1148 static void
1149 en_loadvc(struct en_softc *sc, struct en_vcc *vc)
1150 {
1151         uint32_t reg = en_read(sc, MID_VC(vc->vcc.vci));
1152
1153         reg = MIDV_SETMODE(reg, MIDV_TRASH);
1154         en_write(sc, MID_VC(vc->vcc.vci), reg);
1155         DELAY(27);
1156
1157         /* no need to set CRC */
1158
1159         /* read pointer = 0, desc. start = 0 */
1160         en_write(sc, MID_DST_RP(vc->vcc.vci), 0);
1161         /* write pointer = 0 */
1162         en_write(sc, MID_WP_ST_CNT(vc->vcc.vci), 0);
1163         /* set mode, size, loc */
1164         en_write(sc, MID_VC(vc->vcc.vci), vc->rxslot->mode);
1165
1166         vc->rxslot->cur = vc->rxslot->start;
1167
1168         DBG(sc, VC, ("rx%d: assigned to VCI %d", vc->rxslot - sc->rxslot,
1169             vc->vcc.vci));
1170 }
1171
1172 /*
1173  * Open the given vcc.
1174  *
1175  * LOCK: unlocked, needed
1176  */
1177 static int
1178 en_open_vcc(struct en_softc *sc, struct atmio_openvcc *op)
1179 {
1180         uint32_t oldmode, newmode;
1181         struct en_rxslot *slot;
1182         struct en_vcc *vc;
1183         int error = 0;
1184
1185         DBG(sc, IOCTL, ("enable vpi=%d, vci=%d, flags=%#x",
1186             op->param.vpi, op->param.vci, op->param.flags));
1187
1188         if (op->param.vpi != 0 || op->param.vci >= MID_N_VC)
1189                 return (EINVAL);
1190
1191         vc = uma_zalloc(en_vcc_zone, M_NOWAIT | M_ZERO);
1192         if (vc == NULL)
1193                 return (ENOMEM);
1194
1195         EN_LOCK(sc);
1196
1197         if (sc->vccs[op->param.vci] != NULL) {
1198                 error = EBUSY;
1199                 goto done;
1200         }
1201
1202         /* find a free receive slot */
1203         for (slot = sc->rxslot; slot < &sc->rxslot[sc->en_nrx]; slot++)
1204                 if (slot->vcc == NULL)
1205                         break;
1206         if (slot == &sc->rxslot[sc->en_nrx]) {
1207                 error = ENOSPC;
1208                 goto done;
1209         }
1210
1211         vc->rxslot = slot;
1212         vc->rxhand = op->rxhand;
1213         vc->vcc = op->param;
1214
1215         oldmode = slot->mode;
1216         newmode = (op->param.aal == ATMIO_AAL_5) ? MIDV_AAL5 : MIDV_NOAAL;
1217         slot->mode = MIDV_SETMODE(oldmode, newmode);
1218         slot->vcc = vc;
1219
1220         KASSERT (_IF_QLEN(&slot->indma) == 0 && _IF_QLEN(&slot->q) == 0,
1221             ("en_rxctl: left over mbufs on enable slot=%tu",
1222             vc->rxslot - sc->rxslot));
1223
1224         vc->txspeed = 0;
1225         vc->txslot = sc->txslot;
1226         vc->txslot->nref++;     /* bump reference count */
1227
1228         en_loadvc(sc, vc);      /* does debug printf for us */
1229
1230         /* don't free below */
1231         sc->vccs[vc->vcc.vci] = vc;
1232         vc = NULL;
1233         sc->vccs_open++;
1234
1235   done:
1236         if (vc != NULL)
1237                 uma_zfree(en_vcc_zone, vc);
1238
1239         EN_UNLOCK(sc);
1240         return (error);
1241 }
1242
1243 /*
1244  * Close finished
1245  */
1246 static void
1247 en_close_finish(struct en_softc *sc, struct en_vcc *vc)
1248 {
1249
1250         if (vc->rxslot != NULL)
1251                 vc->rxslot->vcc = NULL;
1252
1253         DBG(sc, VC, ("vci: %u free (%p)", vc->vcc.vci, vc));
1254
1255         sc->vccs[vc->vcc.vci] = NULL;
1256         uma_zfree(en_vcc_zone, vc);
1257         sc->vccs_open--;
1258 }
1259
1260 /*
1261  * LOCK: unlocked, needed
1262  */
1263 static int
1264 en_close_vcc(struct en_softc *sc, struct atmio_closevcc *cl)
1265 {
1266         uint32_t oldmode, newmode;
1267         struct en_vcc *vc;
1268         int error = 0;
1269
1270         DBG(sc, IOCTL, ("disable vpi=%d, vci=%d", cl->vpi, cl->vci));
1271
1272         if (cl->vpi != 0 || cl->vci >= MID_N_VC)
1273                 return (EINVAL);
1274
1275         EN_LOCK(sc);
1276         if ((vc = sc->vccs[cl->vci]) == NULL) {
1277                 error = ENOTCONN;
1278                 goto done;
1279         }
1280
1281         /*
1282          * turn off VCI
1283          */
1284         if (vc->rxslot == NULL) {
1285                 error = ENOTCONN;
1286                 goto done;
1287         }
1288         if (vc->vflags & VCC_DRAIN) {
1289                 error = EINVAL;
1290                 goto done;
1291         }
1292
1293         oldmode = en_read(sc, MID_VC(cl->vci));
1294         newmode = MIDV_SETMODE(oldmode, MIDV_TRASH) & ~MIDV_INSERVICE;
1295         en_write(sc, MID_VC(cl->vci), (newmode | (oldmode & MIDV_INSERVICE)));
1296
1297         /* halt in tracks, be careful to preserve inservice bit */
1298         DELAY(27);
1299         vc->rxslot->mode = newmode;
1300
1301         vc->txslot->nref--;
1302
1303         /* if stuff is still going on we are going to have to drain it out */
1304         if (_IF_QLEN(&vc->rxslot->indma) == 0 &&
1305             _IF_QLEN(&vc->rxslot->q) == 0 &&
1306             (vc->vflags & VCC_SWSL) == 0) {
1307                 en_close_finish(sc, vc);
1308                 goto done;
1309         }
1310
1311         vc->vflags |= VCC_DRAIN;
1312         DBG(sc, IOCTL, ("VCI %u now draining", cl->vci));
1313
1314         if (vc->vcc.flags & ATMIO_FLAG_ASYNC)
1315                 goto done;
1316
1317         vc->vflags |= VCC_CLOSE_RX;
1318         while ((sc->ifatm.ifnet.if_flags & IFF_RUNNING) &&
1319             (vc->vflags & VCC_DRAIN))
1320                 cv_wait(&sc->cv_close, &sc->en_mtx);
1321
1322         en_close_finish(sc, vc);
1323         if (!(sc->ifatm.ifnet.if_flags & IFF_RUNNING)) {
1324                 error = EIO;
1325                 goto done;
1326         }
1327
1328
1329   done:
1330         EN_UNLOCK(sc);
1331         return (error);
1332 }
1333
1334 /*********************************************************************/
1335 /*
1336  * starting/stopping the card
1337  */
1338
1339 /*
1340  * en_reset_ul: reset the board, throw away work in progress.
1341  * must en_init to recover.
1342  *
1343  * LOCK: locked, needed
1344  */
1345 static void
1346 en_reset_ul(struct en_softc *sc)
1347 {
1348         struct en_map *map;
1349         struct mbuf *m;
1350         struct en_rxslot *rx;
1351         int lcv;
1352
1353         if_printf(&sc->ifatm.ifnet, "reset\n");
1354         sc->ifatm.ifnet.if_flags &= ~IFF_RUNNING;
1355
1356         if (sc->en_busreset)
1357                 sc->en_busreset(sc);
1358         en_write(sc, MID_RESID, 0x0);   /* reset hardware */
1359
1360         /*
1361          * recv: dump any mbufs we are dma'ing into, if DRAINing, then a reset
1362          * will free us! Don't release the rxslot from the channel.
1363          */
1364         for (lcv = 0 ; lcv < MID_N_VC ; lcv++) {
1365                 if (sc->vccs[lcv] == NULL)
1366                         continue;
1367                 rx = sc->vccs[lcv]->rxslot;
1368
1369                 for (;;) {
1370                         _IF_DEQUEUE(&rx->indma, m);
1371                         if (m == NULL)
1372                                 break;
1373                         map = (void *)m->m_pkthdr.rcvif;
1374                         uma_zfree(sc->map_zone, map);
1375                         m_freem(m);
1376                 }
1377                 for (;;) {
1378                         _IF_DEQUEUE(&rx->q, m);
1379                         if (m == NULL)
1380                                 break;
1381                         m_freem(m);
1382                 }
1383                 sc->vccs[lcv]->vflags = 0;
1384         }
1385
1386         /*
1387          * xmit: dump everything
1388          */
1389         for (lcv = 0 ; lcv < EN_NTX ; lcv++) {
1390                 for (;;) {
1391                         _IF_DEQUEUE(&sc->txslot[lcv].indma, m);
1392                         if (m == NULL)
1393                                 break;
1394                         map = (void *)m->m_pkthdr.rcvif;
1395                         uma_zfree(sc->map_zone, map);
1396                         m_freem(m);
1397                 }
1398                 for (;;) {
1399                         _IF_DEQUEUE(&sc->txslot[lcv].q, m);
1400                         if (m == NULL)
1401                                 break;
1402                         map = (void *)m->m_pkthdr.rcvif;
1403                         uma_zfree(sc->map_zone, map);
1404                         m_freem(m);
1405                 }
1406                 sc->txslot[lcv].mbsize = 0;
1407         }
1408
1409         /*
1410          * Unstop all waiters
1411          */
1412         cv_broadcast(&sc->cv_close);
1413 }
1414
1415 /*
1416  * en_reset: reset the board, throw away work in progress.
1417  * must en_init to recover.
1418  *
1419  * LOCK: unlocked, needed
1420  *
1421  * Use en_reset_ul if you alreay have the lock
1422  */
1423 void
1424 en_reset(struct en_softc *sc)
1425 {
1426         EN_LOCK(sc);
1427         en_reset_ul(sc);
1428         EN_UNLOCK(sc);
1429 }
1430
1431
1432 /*
1433  * en_init: init board and sync the card with the data in the softc.
1434  *
1435  * LOCK: locked, needed
1436  */
1437 static void
1438 en_init(struct en_softc *sc)
1439 {
1440         int vc, slot;
1441         uint32_t loc;
1442
1443         if ((sc->ifatm.ifnet.if_flags & IFF_UP) == 0) {
1444                 DBG(sc, INIT, ("going down"));
1445                 en_reset(sc);                           /* to be safe */
1446                 return;
1447         }
1448
1449         DBG(sc, INIT, ("going up"));
1450         sc->ifatm.ifnet.if_flags |= IFF_RUNNING;        /* enable */
1451
1452         if (sc->en_busreset)
1453                 sc->en_busreset(sc);
1454         en_write(sc, MID_RESID, 0x0);           /* reset */
1455
1456         /* zero memory */
1457         bus_space_set_region_4(sc->en_memt, sc->en_base,
1458             MID_RAMOFF, 0, sc->en_obmemsz / 4);
1459
1460         /*
1461          * init obmem data structures: vc tab, dma q's, slist.
1462          *
1463          * note that we set drq_free/dtq_free to one less than the total number
1464          * of DTQ/DRQs present.   we do this because the card uses the condition
1465          * (drq_chip == drq_us) to mean "list is empty"... but if you allow the
1466          * circular list to be completely full then (drq_chip == drq_us) [i.e.
1467          * the drq_us pointer will wrap all the way around].   by restricting
1468          * the number of active requests to (N - 1) we prevent the list from
1469          * becoming completely full.    note that the card will sometimes give
1470          * us an interrupt for a DTQ/DRQ we have already processes... this helps
1471          * keep that interrupt from messing us up.
1472          */
1473         bzero(&sc->drq, sizeof(sc->drq));
1474         sc->drq_free = MID_DRQ_N - 1;
1475         sc->drq_chip = MID_DRQ_REG2A(en_read(sc, MID_DMA_RDRX));
1476         en_write(sc, MID_DMA_WRRX, MID_DRQ_A2REG(sc->drq_chip)); 
1477         sc->drq_us = sc->drq_chip;
1478
1479         bzero(&sc->dtq, sizeof(sc->dtq));
1480         sc->dtq_free = MID_DTQ_N - 1;
1481         sc->dtq_chip = MID_DTQ_REG2A(en_read(sc, MID_DMA_RDTX));
1482         en_write(sc, MID_DMA_WRTX, MID_DRQ_A2REG(sc->dtq_chip)); 
1483         sc->dtq_us = sc->dtq_chip;
1484
1485         sc->hwslistp = MID_SL_REG2A(en_read(sc, MID_SERV_WRITE));
1486         sc->swsl_size = sc->swsl_head = sc->swsl_tail = 0;
1487
1488         DBG(sc, INIT, ("drq free/chip: %d/0x%x, dtq free/chip: %d/0x%x, "
1489             "hwslist: 0x%x", sc->drq_free, sc->drq_chip, sc->dtq_free,
1490             sc->dtq_chip, sc->hwslistp));
1491
1492         for (slot = 0 ; slot < EN_NTX ; slot++) {
1493                 sc->txslot[slot].bfree = EN_TXSZ * 1024;
1494                 en_write(sc, MIDX_READPTR(slot), 0);
1495                 en_write(sc, MIDX_DESCSTART(slot), 0);
1496                 loc = sc->txslot[slot].cur = sc->txslot[slot].start;
1497                 loc = loc - MID_RAMOFF;
1498                 /* mask, cvt to words */
1499                 loc = (loc & ~((EN_TXSZ * 1024) - 1)) >> 2;
1500                 /* top 11 bits */
1501                 loc = loc >> MIDV_LOCTOPSHFT;
1502                 en_write(sc, MIDX_PLACE(slot), MIDX_MKPLACE(en_k2sz(EN_TXSZ),
1503                     loc));
1504                 DBG(sc, INIT, ("tx%d: place 0x%x", slot,
1505                     (u_int)en_read(sc, MIDX_PLACE(slot))));
1506         }
1507
1508         for (vc = 0; vc < MID_N_VC; vc++) 
1509                 if (sc->vccs[vc] != NULL)
1510                         en_loadvc(sc, sc->vccs[vc]);
1511
1512         /*
1513          * enable!
1514          */
1515         en_write(sc, MID_INTENA, MID_INT_TX | MID_INT_DMA_OVR | MID_INT_IDENT |
1516             MID_INT_LERR | MID_INT_DMA_ERR | MID_INT_DMA_RX | MID_INT_DMA_TX |
1517             MID_INT_SERVICE | MID_INT_SUNI | MID_INT_STATS);
1518         en_write(sc, MID_MAST_CSR, MID_SETIPL(sc->ipl) | MID_MCSR_ENDMA |
1519             MID_MCSR_ENTX | MID_MCSR_ENRX);
1520 }
1521
1522 /*********************************************************************/
1523 /*
1524  * Ioctls
1525  */
1526 /*
1527  * en_ioctl: handle ioctl requests
1528  *
1529  * NOTE: if you add an ioctl to set txspeed, you should choose a new
1530  * TX channel/slot.   Choose the one with the lowest sc->txslot[slot].nref
1531  * value, subtract one from sc->txslot[0].nref, add one to the
1532  * sc->txslot[slot].nref, set sc->txvc2slot[vci] = slot, and then set
1533  * txspeed[vci].
1534  *
1535  * LOCK: unlocked, needed
1536  */
1537 static int
1538 en_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
1539 {
1540         struct en_softc *sc = (struct en_softc *)ifp->if_softc;
1541         struct ifaddr *ifa = (struct ifaddr *)data;
1542         struct ifreq *ifr = (struct ifreq *)data;
1543         struct atmio_vcctable *vtab;
1544         int error = 0;
1545
1546         switch (cmd) {
1547
1548           case SIOCSIFADDR: 
1549                 EN_LOCK(sc);
1550                 ifp->if_flags |= IFF_UP;
1551 #if defined(INET) || defined(INET6)
1552                 if (ifa->ifa_addr->sa_family == AF_INET
1553                     || ifa->ifa_addr->sa_family == AF_INET6) {
1554                         if (!(ifp->if_flags & IFF_RUNNING)) {
1555                                 en_reset_ul(sc);
1556                                 en_init(sc);
1557                         }
1558                         ifa->ifa_rtrequest = atm_rtrequest; /* ??? */
1559                         EN_UNLOCK(sc);
1560                         break;
1561                 }
1562 #endif /* INET */
1563                 if (!(ifp->if_flags & IFF_RUNNING)) {
1564                         en_reset_ul(sc);
1565                         en_init(sc);
1566                 }
1567                 EN_UNLOCK(sc);
1568                 break;
1569
1570         case SIOCSIFFLAGS: 
1571                 EN_LOCK(sc);
1572                 if (ifp->if_flags & IFF_UP) {
1573                         if (!(ifp->if_flags & IFF_RUNNING))
1574                                 en_init(sc);
1575                 } else {
1576                         if (ifp->if_flags & IFF_RUNNING)
1577                                 en_reset_ul(sc);
1578                 }
1579                 EN_UNLOCK(sc);
1580                 break;
1581
1582           case SIOCSIFMTU:
1583                 /*
1584                  * Set the interface MTU.
1585                  */
1586                 if (ifr->ifr_mtu > ATMMTU) {
1587                         error = EINVAL;
1588                         break;
1589                 }
1590                 ifp->if_mtu = ifr->ifr_mtu;
1591                 break;
1592
1593           case SIOCSIFMEDIA:
1594           case SIOCGIFMEDIA:
1595                 error = ifmedia_ioctl(ifp, ifr, &sc->media, cmd);
1596                 break;
1597
1598           case SIOCATMOPENVCC:          /* kernel internal use */
1599                 error = en_open_vcc(sc, (struct atmio_openvcc *)data);
1600                 break;
1601
1602           case SIOCATMCLOSEVCC:         /* kernel internal use */
1603                 error = en_close_vcc(sc, (struct atmio_closevcc *)data);
1604                 break;
1605
1606           case SIOCATMGETVCCS:  /* internal netgraph use */
1607                 vtab = atm_getvccs((struct atmio_vcc **)sc->vccs,
1608                     MID_N_VC, sc->vccs_open, &sc->en_mtx, 0);
1609                 if (vtab == NULL) {
1610                         error = ENOMEM;
1611                         break;
1612                 }
1613                 *(void **)data = vtab;
1614                 break;
1615
1616           case SIOCATMGVCCS:    /* return vcc table */
1617                 vtab = atm_getvccs((struct atmio_vcc **)sc->vccs,
1618                     MID_N_VC, sc->vccs_open, &sc->en_mtx, 1);
1619                 error = copyout(vtab, ifr->ifr_data, sizeof(*vtab) +
1620                     vtab->count * sizeof(vtab->vccs[0]));
1621                 free(vtab, M_DEVBUF);
1622                 break;
1623
1624           default: 
1625                 error = EINVAL;
1626                 break;
1627         }
1628         return (error);
1629 }
1630
1631 /*********************************************************************/
1632 /*
1633  * Sysctl's
1634  */
1635
1636 /*
1637  * Sysctl handler for internal statistics
1638  *
1639  * LOCK: unlocked, needed
1640  */
1641 static int
1642 en_sysctl_istats(SYSCTL_HANDLER_ARGS)
1643 {
1644         struct en_softc *sc = arg1;
1645         uint32_t *ret;
1646         int error;
1647
1648         ret = malloc(sizeof(sc->stats), M_TEMP, M_WAITOK);
1649
1650         EN_LOCK(sc);
1651         bcopy(&sc->stats, ret, sizeof(sc->stats));
1652         EN_UNLOCK(sc);
1653
1654         error = SYSCTL_OUT(req, ret, sizeof(sc->stats));
1655         free(ret, M_TEMP);
1656
1657         return (error);
1658 }
1659
1660 /*********************************************************************/
1661 /*
1662  * Interrupts
1663  */
1664
1665 /*
1666  * Transmit interrupt handler
1667  *
1668  * check for tx complete, if detected then this means that some space
1669  * has come free on the card.   we must account for it and arrange to
1670  * kick the channel to life (in case it is stalled waiting on the card).
1671  *
1672  * LOCK: locked, needed
1673  */
1674 static uint32_t
1675 en_intr_tx(struct en_softc *sc, uint32_t reg)
1676 {
1677         uint32_t kick;
1678         uint32_t mask;
1679         uint32_t val;
1680         int chan;
1681
1682         kick = 0;               /* bitmask of channels to kick */
1683
1684         for (mask = 1, chan = 0; chan < EN_NTX; chan++, mask *= 2) {
1685                 if (!(reg & MID_TXCHAN(chan)))
1686                         continue;
1687
1688                 kick = kick | mask;
1689
1690                 /* current read pointer */
1691                 val = en_read(sc, MIDX_READPTR(chan));
1692                 /* as offset */
1693                 val = (val * sizeof(uint32_t)) + sc->txslot[chan].start;
1694                 if (val > sc->txslot[chan].cur)
1695                         sc->txslot[chan].bfree = val - sc->txslot[chan].cur;
1696                 else
1697                         sc->txslot[chan].bfree = (val + (EN_TXSZ * 1024)) -
1698                             sc->txslot[chan].cur;
1699                 DBG(sc, INTR, ("tx%d: transmit done. %d bytes now free in "
1700                     "buffer", chan, sc->txslot[chan].bfree));
1701         }
1702         return (kick);
1703 }
1704
1705 /*
1706  * TX DMA interrupt
1707  *
1708  * check for TX DMA complete, if detected then this means
1709  * that some DTQs are now free.   it also means some indma
1710  * mbufs can be freed. if we needed DTQs, kick all channels.
1711  *
1712  * LOCK: locked, needed
1713  */
1714 static uint32_t
1715 en_intr_tx_dma(struct en_softc *sc)
1716 {
1717         uint32_t kick = 0;
1718         uint32_t val;
1719         uint32_t idx;
1720         uint32_t slot;
1721         uint32_t dtq;
1722         struct en_map *map;
1723         struct mbuf *m;
1724
1725         val = en_read(sc, MID_DMA_RDTX);        /* chip's current location */
1726         idx = MID_DTQ_A2REG(sc->dtq_chip);      /* where we last saw chip */
1727
1728         if (sc->need_dtqs) {
1729                 kick = MID_NTX_CH - 1;  /* assume power of 2, kick all! */
1730                 sc->need_dtqs = 0;      /* recalculated in "kick" loop below */
1731                 DBG(sc, INTR, ("cleared need DTQ condition"));
1732         }
1733
1734         while (idx != val) {
1735                 sc->dtq_free++;
1736                 if ((dtq = sc->dtq[idx]) != 0) {
1737                         /* don't forget to zero it out when done */
1738                         sc->dtq[idx] = 0;
1739                         slot = EN_DQ_SLOT(dtq);
1740
1741                         _IF_DEQUEUE(&sc->txslot[slot].indma, m);
1742                         if (m == NULL)
1743                                 panic("enintr: dtqsync");
1744                         map = (void *)m->m_pkthdr.rcvif;
1745                         uma_zfree(sc->map_zone, map);
1746                         m_freem(m);
1747
1748                         sc->txslot[slot].mbsize -= EN_DQ_LEN(dtq);
1749                         DBG(sc, INTR, ("tx%d: free %d dma bytes, mbsize now "
1750                             "%d", slot, EN_DQ_LEN(dtq), 
1751                             sc->txslot[slot].mbsize));
1752                 }
1753                 EN_WRAPADD(0, MID_DTQ_N, idx, 1);
1754         }
1755         sc->dtq_chip = MID_DTQ_REG2A(val);      /* sync softc */
1756
1757         return (kick);
1758 }
1759
1760 /*
1761  * Service interrupt
1762  *
1763  * LOCK: locked, needed
1764  */
1765 static int
1766 en_intr_service(struct en_softc *sc)
1767 {
1768         uint32_t chip;
1769         uint32_t vci;
1770         int need_softserv = 0;
1771         struct en_vcc *vc;
1772
1773         chip = MID_SL_REG2A(en_read(sc, MID_SERV_WRITE));
1774
1775         while (sc->hwslistp != chip) {
1776                 /* fetch and remove it from hardware service list */
1777                 vci = en_read(sc, sc->hwslistp);
1778                 EN_WRAPADD(MID_SLOFF, MID_SLEND, sc->hwslistp, 4);
1779
1780                 if ((vc = sc->vccs[vci]) == NULL ||
1781                     (vc->vcc.flags & ATMIO_FLAG_NORX)) {
1782                         DBG(sc, INTR, ("unexpected rx interrupt VCI %d", vci));
1783                         en_write(sc, MID_VC(vci), MIDV_TRASH);  /* rx off */
1784                         continue;
1785                 }
1786
1787                 /* remove from hwsl */
1788                 en_write(sc, MID_VC(vci), vc->rxslot->mode);
1789                 EN_COUNT(sc->stats.hwpull);
1790
1791                 DBG(sc, INTR, ("pulled VCI %d off hwslist", vci));
1792
1793                 /* add it to the software service list (if needed) */
1794                 if ((vc->vflags & VCC_SWSL) == 0) {
1795                         EN_COUNT(sc->stats.swadd);
1796                         need_softserv = 1;
1797                         vc->vflags |= VCC_SWSL;
1798                         sc->swslist[sc->swsl_tail] = vci;
1799                         EN_WRAPADD(0, MID_SL_N, sc->swsl_tail, 1);
1800                         sc->swsl_size++;
1801                         DBG(sc, INTR, ("added VCI %d to swslist", vci));
1802                 }
1803         }
1804         return (need_softserv);
1805 }
1806
1807 /*
1808  * Handle a receive DMA completion
1809  */
1810 static void
1811 en_rx_drain(struct en_softc *sc, u_int drq)
1812 {
1813         struct en_rxslot *slot;
1814         struct en_vcc *vc;
1815         struct mbuf *m;
1816         struct atm_pseudohdr ah;
1817
1818         slot = &sc->rxslot[EN_DQ_SLOT(drq)];
1819
1820         m = NULL;       /* assume "JK" trash DMA */
1821         if (EN_DQ_LEN(drq) != 0) {
1822                 _IF_DEQUEUE(&slot->indma, m);
1823                 KASSERT(m != NULL, ("drqsync: %s: lost mbuf in slot %zu!",
1824                     sc->ifatm.ifnet.if_xname, slot - sc->rxslot));
1825                 uma_zfree(sc->map_zone, (struct en_map *)m->m_pkthdr.rcvif);
1826         }
1827         if ((vc = slot->vcc) == NULL) {
1828                 /* ups */
1829                 if (m != NULL)
1830                         m_freem(m);
1831                 return;
1832         }
1833
1834         /* do something with this mbuf */
1835         if (vc->vflags & VCC_DRAIN) {
1836                 /* drain? */
1837                 if (m != NULL)
1838                         m_freem(m);
1839                 if (_IF_QLEN(&slot->indma) == 0 && _IF_QLEN(&slot->q) == 0 &&
1840                     (en_read(sc, MID_VC(vc->vcc.vci)) & MIDV_INSERVICE) == 0 &&
1841                     (vc->vflags & VCC_SWSL) == 0) {
1842                         vc->vflags &= ~VCC_CLOSE_RX;
1843                         if (vc->vcc.flags & ATMIO_FLAG_ASYNC)
1844                                 en_close_finish(sc, vc);
1845                         else
1846                                 cv_signal(&sc->cv_close);
1847                 }
1848                 return;
1849         }
1850
1851         if (m != NULL) {
1852                 ATM_PH_FLAGS(&ah) = vc->vcc.flags;
1853                 ATM_PH_VPI(&ah) = 0;
1854                 ATM_PH_SETVCI(&ah, vc->vcc.vci);
1855
1856                 DBG(sc, INTR, ("rx%zu: rxvci%d: atm_input, mbuf %p, len %d, "
1857                     "hand %p", slot - sc->rxslot, vc->vcc.vci, m,
1858                     EN_DQ_LEN(drq), vc->rxhand));
1859
1860                 m->m_pkthdr.rcvif = &sc->ifatm.ifnet;
1861                 sc->ifatm.ifnet.if_ipackets++;
1862
1863                 vc->ipackets++;
1864                 vc->ibytes += m->m_pkthdr.len;
1865
1866 #ifdef EN_DEBUG
1867                 if (sc->debug & DBG_IPACKETS)
1868                         en_dump_packet(sc, m);
1869 #endif
1870 #ifdef ENABLE_BPF
1871                 BPF_MTAP(&sc->ifatm.ifnet, m);
1872 #endif
1873                 atm_input(&sc->ifatm.ifnet, &ah, m, vc->rxhand);
1874         }
1875 }
1876
1877 /*
1878  * check for RX DMA complete, and pass the data "upstairs"
1879  *
1880  * LOCK: locked, needed
1881  */
1882 static int
1883 en_intr_rx_dma(struct en_softc *sc)
1884 {
1885         uint32_t val;
1886         uint32_t idx;
1887         uint32_t drq;
1888
1889         val = en_read(sc, MID_DMA_RDRX);        /* chip's current location */
1890         idx = MID_DRQ_A2REG(sc->drq_chip);      /* where we last saw chip */
1891
1892         while (idx != val) {
1893                 sc->drq_free++;
1894                 if ((drq = sc->drq[idx]) != 0) {
1895                         /* don't forget to zero it out when done */
1896                         sc->drq[idx] = 0;
1897                         en_rx_drain(sc, drq);
1898                 }
1899                 EN_WRAPADD(0, MID_DRQ_N, idx, 1);
1900         }
1901         sc->drq_chip = MID_DRQ_REG2A(val);      /* sync softc */
1902
1903         if (sc->need_drqs) {
1904                 /* true if we had a DRQ shortage */
1905                 sc->need_drqs = 0;
1906                 DBG(sc, INTR, ("cleared need DRQ condition"));
1907                 return (1);
1908         } else
1909                 return (0);
1910 }
1911
1912 /*
1913  * en_mget: get an mbuf chain that can hold totlen bytes and return it
1914  * (for recv). For the actual allocation totlen is rounded up to a multiple
1915  * of 4. We also ensure, that each mbuf has a multiple of 4 bytes.
1916  *
1917  * After this call the sum of all the m_len's in the chain will be totlen.
1918  * This is called at interrupt time, so we can't wait here.
1919  *
1920  * LOCK: any, not needed
1921  */
1922 static struct mbuf *
1923 en_mget(struct en_softc *sc, u_int pktlen)
1924 {
1925         struct mbuf *m, *tmp;
1926         u_int totlen, pad;
1927
1928         totlen = roundup(pktlen, sizeof(uint32_t));
1929         pad = totlen - pktlen;
1930
1931         /*
1932          * First get an mbuf with header. Keep space for a couple of
1933          * words at the begin.
1934          */
1935         /* called from interrupt context */
1936         MGETHDR(m, M_DONTWAIT, MT_DATA);
1937         if (m == NULL)
1938                 return (NULL);
1939
1940         m->m_pkthdr.rcvif = NULL;
1941         m->m_pkthdr.len = pktlen;
1942         m->m_len = EN_RX1BUF;
1943         MH_ALIGN(m, EN_RX1BUF);
1944         if (m->m_len >= totlen) {
1945                 m->m_len = totlen;
1946
1947         } else {
1948                 totlen -= m->m_len;
1949
1950                 /* called from interrupt context */
1951                 tmp = m_getm(m, totlen, M_DONTWAIT, MT_DATA);
1952                 if (tmp == NULL) {
1953                         m_free(m);
1954                         return (NULL);
1955                 }
1956                 tmp = m->m_next;
1957                 /* m_getm could do this for us */
1958                 while (tmp != NULL) {
1959                         tmp->m_len = min(MCLBYTES, totlen);
1960                         totlen -= tmp->m_len;
1961                         tmp = tmp->m_next;
1962                 }
1963         }
1964
1965         return (m);
1966 }
1967
1968 /*
1969  * Argument for RX DMAMAP loader.
1970  */
1971 struct rxarg {
1972         struct en_softc *sc;
1973         struct mbuf *m;
1974         u_int pre_skip;         /* number of bytes to skip at begin */
1975         u_int post_skip;        /* number of bytes to skip at end */
1976         struct en_vcc *vc;      /* vc we are receiving on */
1977         int wait;               /* wait for DRQ entries */
1978 };
1979
1980 /*
1981  * Copy the segment table to the buffer for later use. And compute the
1982  * number of dma queue entries we need.
1983  *
1984  * LOCK: locked, needed
1985  */
1986 static void
1987 en_rxdma_load(void *uarg, bus_dma_segment_t *segs, int nseg,
1988     bus_size_t mapsize, int error)
1989 {
1990         struct rxarg *rx = uarg;
1991         struct en_softc *sc = rx->sc;
1992         struct en_rxslot *slot = rx->vc->rxslot;
1993         u_int           free;           /* number of free DRQ entries */
1994         uint32_t        cur;            /* current buffer offset */
1995         uint32_t        drq;            /* DRQ entry pointer */
1996         uint32_t        last_drq;       /* where we have written last */
1997         u_int           needalign, cnt, count, bcode;
1998         bus_addr_t      addr;
1999         bus_size_t      rest;
2000         int             i;
2001
2002         if (error != 0)
2003                 return;
2004         if (nseg > EN_MAX_DMASEG)
2005                 panic("too many DMA segments");
2006
2007         rx->wait = 0;
2008
2009         free = sc->drq_free;
2010         drq = sc->drq_us;
2011         cur = slot->cur;
2012
2013         last_drq = 0;
2014
2015         /*
2016          * Local macro to add an entry to the receive DMA area. If there
2017          * are no entries left, return. Save the byte offset of the entry
2018          * in last_drq for later use.
2019          */
2020 #define PUT_DRQ_ENTRY(ENI, BCODE, COUNT, ADDR)                          \
2021         if (free == 0) {                                                \
2022                 EN_COUNT(sc->stats.rxdrqout);                           \
2023                 rx->wait = 1;                                           \
2024                 return;                                                 \
2025         }                                                               \
2026         last_drq = drq;                                                 \
2027         en_write(sc, drq + 0, (ENI || !sc->is_adaptec) ?                \
2028             MID_MK_RXQ_ENI(COUNT, rx->vc->vcc.vci, 0, BCODE) :          \
2029             MID_MK_RXQ_ADP(COUNT, rx->vc->vcc.vci, 0, BCODE));          \
2030         en_write(sc, drq + 4, ADDR);                                    \
2031                                                                         \
2032         EN_WRAPADD(MID_DRQOFF, MID_DRQEND, drq, 8);                     \
2033         free--;
2034
2035         /*
2036          * Local macro to generate a DMA entry to DMA cnt bytes. Updates
2037          * the current buffer byte offset accordingly.
2038          */
2039 #define DO_DRQ(TYPE) do {                                               \
2040         rest -= cnt;                                                    \
2041         EN_WRAPADD(slot->start, slot->stop, cur, cnt);                  \
2042         DBG(sc, SERV, ("rx%td: "TYPE" %u bytes, %ju left, cur %#x",     \
2043             slot - sc->rxslot, cnt, (uintmax_t)rest, cur));             \
2044                                                                         \
2045         PUT_DRQ_ENTRY(1, bcode, count, addr);                           \
2046                                                                         \
2047         addr += cnt;                                                    \
2048     } while (0)
2049
2050         /*
2051          * Skip the RBD at the beginning
2052          */
2053         if (rx->pre_skip > 0) {
2054                 /* update DMA address */
2055                 EN_WRAPADD(slot->start, slot->stop, cur, rx->pre_skip);
2056
2057                 PUT_DRQ_ENTRY(0, MIDDMA_JK, WORD_IDX(slot->start, cur), 0);
2058         }
2059
2060         for (i = 0; i < nseg; i++, segs++) {
2061                 addr = segs->ds_addr;
2062                 rest = segs->ds_len;
2063
2064                 if (sc->is_adaptec) {
2065                         /* adaptec card - simple */
2066
2067                         /* advance the on-card buffer pointer */
2068                         EN_WRAPADD(slot->start, slot->stop, cur, rest);
2069                         DBG(sc, SERV, ("rx%td: adp %ju bytes %#jx "
2070                             "(cur now 0x%x)", slot - sc->rxslot,
2071                             (uintmax_t)rest, (uintmax_t)addr, cur));
2072
2073                         PUT_DRQ_ENTRY(0, 0, rest, addr);
2074
2075                         continue;
2076                 }
2077
2078                 /*
2079                  * do we need to do a DMA op to align to the maximum
2080                  * burst? Note, that we are alway 32-bit aligned.
2081                  */
2082                 if (sc->alburst &&
2083                     (needalign = (addr & sc->bestburstmask)) != 0) {
2084                         /* compute number of bytes, words and code */
2085                         cnt = sc->bestburstlen - needalign;
2086                         if (cnt > rest)
2087                                 cnt = rest;
2088                         count = cnt / sizeof(uint32_t);
2089                         if (sc->noalbursts) {
2090                                 bcode = MIDDMA_WORD;
2091                         } else {
2092                                 bcode = en_dmaplan[count].bcode;
2093                                 count = cnt >> en_dmaplan[count].divshift;
2094                         }
2095                         DO_DRQ("al_dma");
2096                 }
2097
2098                 /* do we need to do a max-sized burst? */
2099                 if (rest >= sc->bestburstlen) {
2100                         count = rest >> sc->bestburstshift;
2101                         cnt = count << sc->bestburstshift;
2102                         bcode = sc->bestburstcode;
2103                         DO_DRQ("best_dma");
2104                 }
2105
2106                 /* do we need to do a cleanup burst? */
2107                 if (rest != 0) {
2108                         cnt = rest;
2109                         count = rest / sizeof(uint32_t);
2110                         if (sc->noalbursts) {
2111                                 bcode = MIDDMA_WORD;
2112                         } else {
2113                                 bcode = en_dmaplan[count].bcode;
2114                                 count = cnt >> en_dmaplan[count].divshift;
2115                         }
2116                         DO_DRQ("clean_dma");
2117                 }
2118         }
2119
2120         /*
2121          * Skip stuff at the end
2122          */
2123         if (rx->post_skip > 0) {
2124                 /* update DMA address */
2125                 EN_WRAPADD(slot->start, slot->stop, cur, rx->post_skip);
2126
2127                 PUT_DRQ_ENTRY(0, MIDDMA_JK, WORD_IDX(slot->start, cur), 0);
2128         }
2129
2130         /* record the end for the interrupt routine */
2131         sc->drq[MID_DRQ_A2REG(last_drq)] =
2132             EN_DQ_MK(slot - sc->rxslot, rx->m->m_pkthdr.len);
2133
2134         /* set the end flag in the last descriptor */
2135         en_write(sc, last_drq + 0, SETQ_END(sc, en_read(sc, last_drq + 0)));
2136
2137 #undef PUT_DRQ_ENTRY
2138 #undef DO_DRQ
2139
2140         /* commit */
2141         slot->cur = cur;
2142         sc->drq_free = free;
2143         sc->drq_us = drq;
2144
2145         /* signal to card */
2146         en_write(sc, MID_DMA_WRRX, MID_DRQ_A2REG(sc->drq_us));
2147 }
2148
2149 /*
2150  * en_service: handle a service interrupt
2151  *
2152  * Q: why do we need a software service list?
2153  *
2154  * A: if we remove a VCI from the hardware list and we find that we are
2155  *    out of DRQs we must defer processing until some DRQs become free.
2156  *    so we must remember to look at this RX VCI/slot later, but we can't
2157  *    put it back on the hardware service list (since that isn't allowed).
2158  *    so we instead save it on the software service list.   it would be nice 
2159  *    if we could peek at the VCI on top of the hwservice list without removing
2160  *    it, however this leads to a race condition: if we peek at it and
2161  *    decide we are done with it new data could come in before we have a 
2162  *    chance to remove it from the hwslist.   by the time we get it out of
2163  *    the list the interrupt for the new data will be lost.   oops!
2164  *
2165  * LOCK: locked, needed
2166  */
2167 static void
2168 en_service(struct en_softc *sc)
2169 {
2170         struct mbuf     *m, *lastm;
2171         struct en_map   *map;
2172         struct rxarg    rx;
2173         uint32_t        cur;
2174         uint32_t        dstart;         /* data start (as reported by card) */
2175         uint32_t        rbd;            /* receive buffer descriptor */
2176         uint32_t        pdu;            /* AAL5 trailer */
2177         int             mlen;
2178         int             error;
2179         struct en_rxslot *slot;
2180         struct en_vcc *vc;
2181
2182         rx.sc = sc;
2183
2184   next_vci:
2185         if (sc->swsl_size == 0) {
2186                 DBG(sc, SERV, ("en_service done"));
2187                 return;
2188         }
2189
2190         /*
2191          * get vcc to service
2192          */
2193         rx.vc = vc = sc->vccs[sc->swslist[sc->swsl_head]];
2194         slot = vc->rxslot;
2195         KASSERT (slot->vcc->rxslot == slot, ("en_service: rx slot/vci sync"));
2196
2197         /*
2198          * determine our mode and if we've got any work to do
2199          */
2200         DBG(sc, SERV, ("rx%td: service vci=%d start/stop/cur=0x%x 0x%x "
2201             "0x%x", slot - sc->rxslot, vc->vcc.vci, slot->start,
2202             slot->stop, slot->cur));
2203
2204   same_vci:
2205         cur = slot->cur;
2206
2207         dstart = MIDV_DSTART(en_read(sc, MID_DST_RP(vc->vcc.vci)));
2208         dstart = (dstart * sizeof(uint32_t)) + slot->start;
2209
2210         /* check to see if there is any data at all */
2211         if (dstart == cur) {
2212                 EN_WRAPADD(0, MID_SL_N, sc->swsl_head, 1); 
2213                 /* remove from swslist */
2214                 vc->vflags &= ~VCC_SWSL;
2215                 sc->swsl_size--;
2216                 DBG(sc, SERV, ("rx%td: remove vci %d from swslist",
2217                     slot - sc->rxslot, vc->vcc.vci));
2218                 goto next_vci;
2219         }
2220
2221         /*
2222          * figure out how many bytes we need
2223          * [mlen = # bytes to go in mbufs]
2224          */
2225         rbd = en_read(sc, cur);
2226         if (MID_RBD_ID(rbd) != MID_RBD_STDID) 
2227                 panic("en_service: id mismatch");
2228
2229         if (rbd & MID_RBD_T) {
2230                 mlen = 0;               /* we've got trash */
2231                 rx.pre_skip = MID_RBD_SIZE;
2232                 rx.post_skip = 0;
2233                 EN_COUNT(sc->stats.ttrash);
2234                 DBG(sc, SERV, ("RX overflow lost %d cells!", MID_RBD_CNT(rbd)));
2235
2236         } else if (vc->vcc.aal != ATMIO_AAL_5) {
2237                 /* 1 cell (ick!) */
2238                 mlen = MID_CHDR_SIZE + MID_ATMDATASZ;
2239                 rx.pre_skip = MID_RBD_SIZE;
2240                 rx.post_skip = 0;
2241
2242         } else {
2243                 rx.pre_skip = MID_RBD_SIZE;
2244
2245                 /* get PDU trailer in correct byte order */
2246                 pdu = cur + MID_RBD_CNT(rbd) * MID_ATMDATASZ +
2247                     MID_RBD_SIZE - MID_PDU_SIZE;
2248                 if (pdu >= slot->stop)
2249                         pdu -= EN_RXSZ * 1024;
2250                 pdu = en_read(sc, pdu);
2251
2252                 if (MID_RBD_CNT(rbd) * MID_ATMDATASZ <
2253                     MID_PDU_LEN(pdu)) {
2254                         if_printf(&sc->ifatm.ifnet, "invalid AAL5 length\n");
2255                         rx.post_skip = MID_RBD_CNT(rbd) * MID_ATMDATASZ;
2256                         mlen = 0;
2257                         sc->ifatm.ifnet.if_ierrors++;
2258
2259                 } else if (rbd & MID_RBD_CRCERR) {
2260                         if_printf(&sc->ifatm.ifnet, "CRC error\n");
2261                         rx.post_skip = MID_RBD_CNT(rbd) * MID_ATMDATASZ;
2262                         mlen = 0;
2263                         sc->ifatm.ifnet.if_ierrors++;
2264
2265                 } else {
2266                         mlen = MID_PDU_LEN(pdu);
2267                         rx.post_skip = MID_RBD_CNT(rbd) * MID_ATMDATASZ - mlen;
2268                 }
2269         }
2270
2271         /*
2272          * now allocate mbufs for mlen bytes of data, if out of mbufs, trash all
2273          *
2274          * notes:
2275          *  1. it is possible that we've already allocated an mbuf for this pkt
2276          *     but ran out of DRQs, in which case we saved the allocated mbuf
2277          *     on "q".
2278          *  2. if we save an buf in "q" we store the "cur" (pointer) in the
2279          *     buf as an identity (that we can check later).
2280          *  3. after this block of code, if m is still NULL then we ran out of
2281          *     mbufs
2282          */
2283         _IF_DEQUEUE(&slot->q, m);
2284         if (m != NULL) {
2285                 if (m->m_pkthdr.csum_data != cur) {
2286                         /* wasn't ours */
2287                         DBG(sc, SERV, ("rx%td: q'ed buf %p not ours",
2288                             slot - sc->rxslot, m));
2289                         _IF_PREPEND(&slot->q, m);
2290                         m = NULL;
2291                         EN_COUNT(sc->stats.rxqnotus);
2292                 } else {
2293                         EN_COUNT(sc->stats.rxqus);
2294                         DBG(sc, SERV, ("rx%td: recovered q'ed buf %p",
2295                             slot - sc->rxslot, m));
2296                 }
2297         }
2298         if (mlen == 0 && m != NULL) {
2299                 /* should not happen */
2300                 m_freem(m);
2301                 m = NULL;
2302         }
2303
2304         if (mlen != 0 && m == NULL) {
2305                 m = en_mget(sc, mlen);
2306                 if (m == NULL) {
2307                         rx.post_skip += mlen;
2308                         mlen = 0;
2309                         EN_COUNT(sc->stats.rxmbufout);
2310                         DBG(sc, SERV, ("rx%td: out of mbufs",
2311                             slot - sc->rxslot));
2312                 } else
2313                         rx.post_skip -= roundup(mlen, sizeof(uint32_t)) - mlen;
2314
2315                 DBG(sc, SERV, ("rx%td: allocate buf %p, mlen=%d",
2316                     slot - sc->rxslot, m, mlen));
2317         }
2318
2319         DBG(sc, SERV, ("rx%td: VCI %d, rbuf %p, mlen %d, skip %u/%u",
2320             slot - sc->rxslot, vc->vcc.vci, m, mlen, rx.pre_skip,
2321             rx.post_skip));
2322
2323         if (m != NULL) {
2324                 /* M_NOWAIT - called from interrupt context */
2325                 map = uma_zalloc_arg(sc->map_zone, sc, M_NOWAIT);
2326                 if (map == NULL) {
2327                         rx.post_skip += mlen;
2328                         m_freem(m);
2329                         DBG(sc, SERV, ("rx%td: out of maps",
2330                             slot - sc->rxslot));
2331                         goto skip;
2332                 }
2333                 rx.m = m;
2334                 error = bus_dmamap_load_mbuf(sc->txtag, map->map, m,
2335                     en_rxdma_load, &rx, BUS_DMA_NOWAIT);
2336
2337                 if (error != 0) {
2338                         if_printf(&sc->ifatm.ifnet, "loading RX map failed "
2339                             "%d\n", error);
2340                         uma_zfree(sc->map_zone, map);
2341                         m_freem(m);
2342                         rx.post_skip += mlen;
2343                         goto skip;
2344
2345                 }
2346                 map->flags |= ENMAP_LOADED;
2347
2348                 if (rx.wait) {
2349                         /* out of DRQs - wait */
2350                         uma_zfree(sc->map_zone, map);
2351
2352                         m->m_pkthdr.csum_data = cur;
2353                         _IF_ENQUEUE(&slot->q, m);
2354                         EN_COUNT(sc->stats.rxdrqout);
2355
2356                         sc->need_drqs = 1;      /* flag condition */
2357                         return;
2358
2359                 }
2360                 (void)m_length(m, &lastm);
2361                 lastm->m_len -= roundup(mlen, sizeof(uint32_t)) - mlen;
2362
2363                 m->m_pkthdr.rcvif = (void *)map;
2364                 _IF_ENQUEUE(&slot->indma, m);
2365
2366                 /* get next packet in this slot */
2367                 goto same_vci;
2368         }
2369   skip:
2370         /*
2371          * Here we end if we should drop the packet from the receive buffer.
2372          * The number of bytes to drop is in fill. We can do this with on
2373          * JK entry. If we don't even have that one - wait.
2374          */
2375         if (sc->drq_free == 0) {
2376                 sc->need_drqs = 1;      /* flag condition */
2377                 return;
2378         }
2379         rx.post_skip += rx.pre_skip;
2380         DBG(sc, SERV, ("rx%td: skipping %u", slot - sc->rxslot, rx.post_skip));
2381
2382         /* advance buffer address */
2383         EN_WRAPADD(slot->start, slot->stop, cur, rx.post_skip);
2384
2385         /* write DRQ entry */
2386         if (sc->is_adaptec)
2387                 en_write(sc, sc->drq_us,
2388                     MID_MK_RXQ_ADP(WORD_IDX(slot->start, cur),
2389                     vc->vcc.vci, MID_DMA_END, MIDDMA_JK));
2390         else
2391                 en_write(sc, sc->drq_us,
2392                     MID_MK_RXQ_ENI(WORD_IDX(slot->start, cur),
2393                     vc->vcc.vci, MID_DMA_END, MIDDMA_JK));
2394         en_write(sc, sc->drq_us + 4, 0);
2395         EN_WRAPADD(MID_DRQOFF, MID_DRQEND, sc->drq_us, 8);
2396         sc->drq_free--;
2397
2398         /* signal to RX interrupt */
2399         sc->drq[MID_DRQ_A2REG(sc->drq_us)] = EN_DQ_MK(slot - sc->rxslot, 0);
2400         slot->cur = cur;
2401
2402         /* signal to card */
2403         en_write(sc, MID_DMA_WRRX, MID_DRQ_A2REG(sc->drq_us));
2404
2405         goto same_vci;
2406 }
2407
2408 /*
2409  * interrupt handler
2410  *
2411  * LOCK: unlocked, needed
2412  */
2413 void
2414 en_intr(void *arg)
2415 {
2416         struct en_softc *sc = arg;
2417         uint32_t reg, kick, mask;
2418         int lcv, need_softserv;
2419
2420         EN_LOCK(sc);
2421
2422         reg = en_read(sc, MID_INTACK);
2423         DBG(sc, INTR, ("interrupt=0x%b", reg, MID_INTBITS));
2424
2425         if ((reg & MID_INT_ANY) == 0) {
2426                 EN_UNLOCK(sc);
2427                 return;
2428         }
2429
2430         /*
2431          * unexpected errors that need a reset
2432          */
2433         if ((reg & (MID_INT_IDENT | MID_INT_LERR | MID_INT_DMA_ERR)) != 0) {
2434                 if_printf(&sc->ifatm.ifnet, "unexpected interrupt=0x%b, "
2435                     "resetting\n", reg, MID_INTBITS);
2436 #ifdef EN_DEBUG
2437                 kdb_enter("en: unexpected error");
2438                 sc->ifatm.ifnet.if_flags &= ~IFF_RUNNING; /* FREEZE! */
2439 #else
2440                 en_reset_ul(sc);
2441                 en_init(sc);
2442 #endif
2443                 EN_UNLOCK(sc);
2444                 return;
2445         }
2446
2447         if (reg & MID_INT_SUNI)
2448                 utopia_intr(&sc->utopia);
2449
2450         kick = 0;
2451         if (reg & MID_INT_TX)
2452                 kick |= en_intr_tx(sc, reg);
2453
2454         if (reg & MID_INT_DMA_TX)
2455                 kick |= en_intr_tx_dma(sc);
2456
2457         /*
2458          * kick xmit channels as needed.
2459          */
2460         if (kick) {
2461                 DBG(sc, INTR, ("tx kick mask = 0x%x", kick));
2462                 for (mask = 1, lcv = 0 ; lcv < EN_NTX ; lcv++, mask = mask * 2)
2463                         if ((kick & mask) && _IF_QLEN(&sc->txslot[lcv].q) != 0)
2464                                 en_txdma(sc, &sc->txslot[lcv]);
2465         }
2466
2467         need_softserv = 0;
2468         if (reg & MID_INT_DMA_RX)
2469                 need_softserv |= en_intr_rx_dma(sc);
2470
2471         if (reg & MID_INT_SERVICE)
2472                 need_softserv |= en_intr_service(sc);
2473
2474         if (need_softserv)
2475                 en_service(sc);
2476
2477         /*
2478          * keep our stats
2479          */
2480         if (reg & MID_INT_DMA_OVR) {
2481                 EN_COUNT(sc->stats.dmaovr);
2482                 DBG(sc, INTR, ("MID_INT_DMA_OVR"));
2483         }
2484         reg = en_read(sc, MID_STAT);
2485         sc->stats.otrash += MID_OTRASH(reg);
2486         sc->stats.vtrash += MID_VTRASH(reg);
2487
2488         EN_UNLOCK(sc);
2489 }
2490
2491 /*
2492  * Read at most n SUNI regs starting at reg into val
2493  */
2494 static int
2495 en_utopia_readregs(struct ifatm *ifatm, u_int reg, uint8_t *val, u_int *n)
2496 {
2497         struct en_softc *sc = ifatm->ifnet.if_softc;
2498         u_int i;
2499
2500         EN_CHECKLOCK(sc);
2501         if (reg >= MID_NSUNI)
2502                 return (EINVAL);
2503         if (reg + *n > MID_NSUNI)
2504                 *n = MID_NSUNI - reg;
2505
2506         for (i = 0; i < *n; i++)
2507                 val[i] = en_read(sc, MID_SUNIOFF + 4 * (reg + i));
2508
2509         return (0);
2510 }
2511
2512 /*
2513  * change the bits given by mask to them in val in register reg
2514  */
2515 static int
2516 en_utopia_writereg(struct ifatm *ifatm, u_int reg, u_int mask, u_int val)
2517 {
2518         struct en_softc *sc = ifatm->ifnet.if_softc;
2519         uint32_t regval;
2520
2521         EN_CHECKLOCK(sc);
2522         if (reg >= MID_NSUNI)
2523                 return (EINVAL);
2524         regval = en_read(sc, MID_SUNIOFF + 4 * reg);
2525         regval = (regval & ~mask) | (val & mask);
2526         en_write(sc, MID_SUNIOFF + 4 * reg, regval);
2527         return (0);
2528 }
2529
2530 static const struct utopia_methods en_utopia_methods = {
2531         en_utopia_readregs,
2532         en_utopia_writereg
2533 };
2534
2535 /*********************************************************************/
2536 /*
2537  * Probing the DMA brokeness of the card
2538  */
2539
2540 /*
2541  * Physical address load helper function for DMA probe
2542  *
2543  * LOCK: unlocked, not needed
2544  */
2545 static void
2546 en_dmaprobe_load(void *uarg, bus_dma_segment_t *segs, int nseg, int error)
2547 {
2548         if (error == 0)
2549                 *(bus_addr_t *)uarg = segs[0].ds_addr;
2550 }
2551
2552 /*
2553  * en_dmaprobe: helper function for en_attach.
2554  *
2555  * see how the card handles DMA by running a few DMA tests.   we need
2556  * to figure out the largest number of bytes we can DMA in one burst
2557  * ("bestburstlen"), and if the starting address for a burst needs to
2558  * be aligned on any sort of boundary or not ("alburst").
2559  *
2560  * Things turn out more complex than that, because on my (harti) brand
2561  * new motherboard (2.4GHz) we can do 64byte aligned DMAs, but everything
2562  * we more than 4 bytes fails (with an RX DMA timeout) for physical
2563  * addresses that end with 0xc. Therefor we search not only the largest
2564  * burst that is supported (hopefully 64) but also check what is the largerst
2565  * unaligned supported size. If that appears to be lesser than 4 words,
2566  * set the noalbursts flag. That will be set only if also alburst is set.
2567  */
2568
2569 /*
2570  * en_dmaprobe_doit: do actual testing for the DMA test.
2571  * Cycle through all bursts sizes from 8 up to 64 and try whether it works.
2572  * Return the largest one that works.
2573  *
2574  * LOCK: unlocked, not needed
2575  */
2576 static int
2577 en_dmaprobe_doit(struct en_softc *sc, uint8_t *sp, bus_addr_t psp)
2578 {
2579         uint8_t *dp = sp + MIDDMA_MAXBURST;
2580         bus_addr_t pdp = psp + MIDDMA_MAXBURST;
2581         int lcv, retval = 4, cnt;
2582         uint32_t reg, bcode, midvloc;
2583
2584         if (sc->en_busreset)
2585                 sc->en_busreset(sc);
2586         en_write(sc, MID_RESID, 0x0);   /* reset card before touching RAM */
2587
2588         /*
2589          * set up a 1k buffer at MID_BUFOFF
2590          */
2591         midvloc = ((MID_BUFOFF - MID_RAMOFF) / sizeof(uint32_t))
2592             >> MIDV_LOCTOPSHFT;
2593         en_write(sc, MIDX_PLACE(0), MIDX_MKPLACE(en_k2sz(1), midvloc));
2594         en_write(sc, MID_VC(0), (midvloc << MIDV_LOCSHIFT) 
2595             | (en_k2sz(1) << MIDV_SZSHIFT) | MIDV_TRASH);
2596         en_write(sc, MID_DST_RP(0), 0);
2597         en_write(sc, MID_WP_ST_CNT(0), 0);
2598
2599         /* set up sample data */
2600         for (lcv = 0 ; lcv < MIDDMA_MAXBURST; lcv++)
2601                 sp[lcv] = lcv + 1;
2602
2603         /* enable DMA (only) */
2604         en_write(sc, MID_MAST_CSR, MID_MCSR_ENDMA);
2605
2606         sc->drq_chip = MID_DRQ_REG2A(en_read(sc, MID_DMA_RDRX));
2607         sc->dtq_chip = MID_DTQ_REG2A(en_read(sc, MID_DMA_RDTX));
2608
2609         /*
2610          * try it now . . .  DMA it out, then DMA it back in and compare
2611          *
2612          * note: in order to get the dma stuff to reverse directions it wants
2613          * the "end" flag set!   since we are not dma'ing valid data we may
2614          * get an ident mismatch interrupt (which we will ignore).
2615          */
2616         DBG(sc, DMA, ("test sp=%p/%#lx, dp=%p/%#lx", 
2617             sp, (u_long)psp, dp, (u_long)pdp));
2618         for (lcv = 8 ; lcv <= MIDDMA_MAXBURST ; lcv = lcv * 2) {
2619                 DBG(sc, DMA, ("test lcv=%d", lcv));
2620
2621                 /* zero SRAM and dest buffer */
2622                 bus_space_set_region_4(sc->en_memt, sc->en_base,
2623                     MID_BUFOFF, 0, 1024 / 4);
2624                 bzero(dp, MIDDMA_MAXBURST);
2625
2626                 bcode = en_sz2b(lcv);
2627
2628                 /* build lcv-byte-DMA x NBURSTS */
2629                 if (sc->is_adaptec)
2630                         en_write(sc, sc->dtq_chip,
2631                             MID_MK_TXQ_ADP(lcv, 0, MID_DMA_END, 0));
2632                 else
2633                         en_write(sc, sc->dtq_chip,
2634                             MID_MK_TXQ_ENI(1, 0, MID_DMA_END, bcode));
2635                 en_write(sc, sc->dtq_chip + 4, psp);
2636                 EN_WRAPADD(MID_DTQOFF, MID_DTQEND, sc->dtq_chip, 8);
2637                 en_write(sc, MID_DMA_WRTX, MID_DTQ_A2REG(sc->dtq_chip));
2638
2639                 cnt = 1000;
2640                 while ((reg = en_readx(sc, MID_DMA_RDTX)) !=
2641                     MID_DTQ_A2REG(sc->dtq_chip)) {
2642                         DELAY(1);
2643                         if (--cnt == 0) {
2644                                 DBG(sc, DMA, ("unexpected timeout in tx "
2645                                     "DMA test\n  alignment=0x%lx, burst size=%d"
2646                                     ", dma addr reg=%#x, rdtx=%#x, stat=%#x\n",
2647                                     (u_long)sp & 63, lcv,
2648                                     en_read(sc, MID_DMA_ADDR), reg,
2649                                     en_read(sc, MID_INTSTAT)));
2650                                 return (retval);
2651                         }
2652                 }
2653
2654                 reg = en_read(sc, MID_INTACK); 
2655                 if ((reg & MID_INT_DMA_TX) != MID_INT_DMA_TX) {
2656                         DBG(sc, DMA, ("unexpected status in tx DMA test: %#x\n",
2657                             reg));
2658                         return (retval);
2659                 }
2660                 /* re-enable DMA (only) */
2661                 en_write(sc, MID_MAST_CSR, MID_MCSR_ENDMA);
2662
2663                 /* "return to sender..."  address is known ... */
2664
2665                 /* build lcv-byte-DMA x NBURSTS */
2666                 if (sc->is_adaptec)
2667                         en_write(sc, sc->drq_chip,
2668                             MID_MK_RXQ_ADP(lcv, 0, MID_DMA_END, 0));
2669                 else
2670                         en_write(sc, sc->drq_chip,
2671                             MID_MK_RXQ_ENI(1, 0, MID_DMA_END, bcode));
2672                 en_write(sc, sc->drq_chip + 4, pdp);
2673                 EN_WRAPADD(MID_DRQOFF, MID_DRQEND, sc->drq_chip, 8);
2674                 en_write(sc, MID_DMA_WRRX, MID_DRQ_A2REG(sc->drq_chip));
2675                 cnt = 1000;
2676                 while ((reg = en_readx(sc, MID_DMA_RDRX)) !=
2677                     MID_DRQ_A2REG(sc->drq_chip)) {
2678                         DELAY(1);
2679                         cnt--;
2680                         if (--cnt == 0) {
2681                                 DBG(sc, DMA, ("unexpected timeout in rx "
2682                                     "DMA test, rdrx=%#x\n", reg));
2683                                 return (retval);
2684                         }
2685                 }
2686                 reg = en_read(sc, MID_INTACK); 
2687                 if ((reg & MID_INT_DMA_RX) != MID_INT_DMA_RX) {
2688                         DBG(sc, DMA, ("unexpected status in rx DMA "
2689                             "test: 0x%x\n", reg));
2690                         return (retval);
2691                 }
2692                 if (bcmp(sp, dp, lcv)) {
2693                         DBG(sc, DMA, ("DMA test failed! lcv=%d, sp=%p, "
2694                             "dp=%p", lcv, sp, dp));
2695                         return (retval);
2696                 }
2697
2698                 retval = lcv;
2699         }
2700         return (retval);        /* studly 64 byte DMA present!  oh baby!! */
2701 }
2702
2703 /*
2704  * Find the best DMA parameters
2705  *
2706  * LOCK: unlocked, not needed
2707  */
2708 static void
2709 en_dmaprobe(struct en_softc *sc)
2710 {
2711         bus_dma_tag_t tag;
2712         bus_dmamap_t map;
2713         int err;
2714         void *buffer;
2715         int bestalgn, lcv, try, bestnoalgn;
2716         bus_addr_t phys;
2717         uint8_t *addr;
2718
2719         sc->alburst = 0;
2720         sc->noalbursts = 0;
2721
2722         /*
2723          * Allocate some DMA-able memory.
2724          * We need 3 times the max burst size aligned to the max burst size.
2725          */
2726         err = bus_dma_tag_create(NULL, MIDDMA_MAXBURST, 0,
2727             BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL,
2728             3 * MIDDMA_MAXBURST, 1, 3 * MIDDMA_MAXBURST, 0,
2729             NULL, NULL, &tag);
2730         if (err)
2731                 panic("%s: cannot create test DMA tag %d", __func__, err);
2732
2733         err = bus_dmamem_alloc(tag, &buffer, 0, &map);
2734         if (err)
2735                 panic("%s: cannot allocate test DMA memory %d", __func__, err);
2736
2737         err = bus_dmamap_load(tag, map, buffer, 3 * MIDDMA_MAXBURST,
2738             en_dmaprobe_load, &phys, BUS_DMA_NOWAIT);
2739         if (err)
2740                 panic("%s: cannot load test DMA map %d", __func__, err);
2741         addr = buffer;
2742         DBG(sc, DMA, ("phys=%#lx addr=%p", (u_long)phys, addr));
2743
2744         /*
2745          * Now get the best burst size of the aligned case.
2746          */
2747         bestalgn = bestnoalgn = en_dmaprobe_doit(sc, addr, phys);
2748
2749         /*
2750          * Now try unaligned. 
2751          */
2752         for (lcv = 4; lcv < MIDDMA_MAXBURST; lcv += 4) {
2753                 try = en_dmaprobe_doit(sc, addr + lcv, phys + lcv);
2754
2755                 if (try < bestnoalgn)
2756                         bestnoalgn = try;
2757         }
2758
2759         if (bestnoalgn < bestalgn) {
2760                 sc->alburst = 1;
2761                 if (bestnoalgn < 32)
2762                         sc->noalbursts = 1;
2763         }
2764
2765         sc->bestburstlen = bestalgn;
2766         sc->bestburstshift = en_log2(bestalgn);
2767         sc->bestburstmask = sc->bestburstlen - 1; /* must be power of 2 */
2768         sc->bestburstcode = en_sz2b(bestalgn);
2769
2770         /*
2771          * Reset the chip before freeing the buffer. It may still be trying
2772          * to DMA.
2773          */
2774         if (sc->en_busreset)
2775                 sc->en_busreset(sc);
2776         en_write(sc, MID_RESID, 0x0);   /* reset card before touching RAM */
2777
2778         DELAY(10000);                   /* may still do DMA */
2779
2780         /*
2781          * Free the DMA stuff
2782          */
2783         bus_dmamap_unload(tag, map);
2784         bus_dmamem_free(tag, buffer, map);
2785         bus_dma_tag_destroy(tag);
2786 }
2787
2788 /*********************************************************************/
2789 /*
2790  * Attach/detach.
2791  */
2792
2793 /*
2794  * Attach to the card.
2795  *
2796  * LOCK: unlocked, not needed (but initialized)
2797  */
2798 int
2799 en_attach(struct en_softc *sc)
2800 {
2801         struct ifnet *ifp = &sc->ifatm.ifnet;
2802         int sz;
2803         uint32_t reg, lcv, check, ptr, sav, midvloc;
2804
2805 #ifdef EN_DEBUG
2806         sc->debug = EN_DEBUG;
2807 #endif
2808         /*
2809          * Probe card to determine memory size.
2810          *
2811          * The stupid ENI card always reports to PCI that it needs 4MB of
2812          * space (2MB regs and 2MB RAM). If it has less than 2MB RAM the
2813          * addresses wrap in the RAM address space (i.e. on a 512KB card
2814          * addresses 0x3ffffc, 0x37fffc, and 0x2ffffc are aliases for
2815          * 0x27fffc  [note that RAM starts at offset 0x200000]).
2816          */
2817
2818         /* reset card before touching RAM */
2819         if (sc->en_busreset)
2820                 sc->en_busreset(sc);
2821         en_write(sc, MID_RESID, 0x0);
2822
2823         for (lcv = MID_PROBEOFF; lcv <= MID_MAXOFF ; lcv += MID_PROBSIZE) {
2824                 en_write(sc, lcv, lcv); /* data[address] = address */
2825                 for (check = MID_PROBEOFF; check < lcv ;check += MID_PROBSIZE) {
2826                         reg = en_read(sc, check);
2827                         if (reg != check)
2828                                 /* found an alias! - quit */
2829                                 goto done_probe;
2830                 }
2831         }
2832   done_probe:
2833         lcv -= MID_PROBSIZE;                    /* take one step back */
2834         sc->en_obmemsz = (lcv + 4) - MID_RAMOFF;
2835
2836         /*
2837          * determine the largest DMA burst supported
2838          */
2839         en_dmaprobe(sc);
2840
2841         /*
2842          * "hello world"
2843          */
2844
2845         /* reset */
2846         if (sc->en_busreset)
2847                 sc->en_busreset(sc);
2848         en_write(sc, MID_RESID, 0x0);           /* reset */
2849
2850         /* zero memory */
2851         bus_space_set_region_4(sc->en_memt, sc->en_base,
2852             MID_RAMOFF, 0, sc->en_obmemsz / 4);
2853
2854         reg = en_read(sc, MID_RESID);
2855
2856         if_printf(&sc->ifatm.ifnet, "ATM midway v%d, board IDs %d.%d, %s%s%s, "
2857             "%ldKB on-board RAM\n", MID_VER(reg), MID_MID(reg), MID_DID(reg), 
2858             (MID_IS_SABRE(reg)) ? "sabre controller, " : "",
2859             (MID_IS_SUNI(reg)) ? "SUNI" : "Utopia",
2860             (!MID_IS_SUNI(reg) && MID_IS_UPIPE(reg)) ? " (pipelined)" : "",
2861             (long)sc->en_obmemsz / 1024);
2862
2863         /*
2864          * fill in common ATM interface stuff
2865          */
2866         sc->ifatm.mib.hw_version = (MID_VER(reg) << 16) |
2867             (MID_MID(reg) << 8) | MID_DID(reg);
2868         if (MID_DID(reg) & 0x4)
2869                 sc->ifatm.mib.media = IFM_ATM_UTP_155;
2870         else
2871                 sc->ifatm.mib.media = IFM_ATM_MM_155;
2872
2873         sc->ifatm.mib.pcr = ATM_RATE_155M;
2874         sc->ifatm.mib.vpi_bits = 0;
2875         sc->ifatm.mib.vci_bits = MID_VCI_BITS;
2876         sc->ifatm.mib.max_vccs = MID_N_VC;
2877         sc->ifatm.mib.max_vpcs = 0;
2878
2879         if (sc->is_adaptec) {
2880                 sc->ifatm.mib.device = ATM_DEVICE_ADP155P;
2881                 if (sc->bestburstlen == 64 && sc->alburst == 0)
2882                         if_printf(&sc->ifatm.ifnet,
2883                             "passed 64 byte DMA test\n");
2884                 else
2885                         if_printf(&sc->ifatm.ifnet, "FAILED DMA TEST: "
2886                             "burst=%d, alburst=%d\n", sc->bestburstlen,
2887                             sc->alburst);
2888         } else {
2889                 sc->ifatm.mib.device = ATM_DEVICE_ENI155P;
2890                 if_printf(&sc->ifatm.ifnet, "maximum DMA burst length = %d "
2891                     "bytes%s\n", sc->bestburstlen, sc->alburst ?
2892                     sc->noalbursts ?  " (no large bursts)" : " (must align)" :
2893                     "");
2894         }
2895
2896         /*
2897          * link into network subsystem and prepare card
2898          */
2899         sc->ifatm.ifnet.if_softc = sc;
2900         ifp->if_flags = IFF_SIMPLEX;
2901         ifp->if_ioctl = en_ioctl;
2902         ifp->if_start = en_start;
2903
2904         mtx_init(&sc->en_mtx, device_get_nameunit(sc->dev),
2905             MTX_NETWORK_LOCK, MTX_DEF);
2906         cv_init(&sc->cv_close, "VC close");
2907
2908         /*
2909          * Make the sysctl tree
2910          */
2911         sysctl_ctx_init(&sc->sysctl_ctx);
2912
2913         if ((sc->sysctl_tree = SYSCTL_ADD_NODE(&sc->sysctl_ctx,
2914             SYSCTL_STATIC_CHILDREN(_hw_atm), OID_AUTO,
2915             device_get_nameunit(sc->dev), CTLFLAG_RD, 0, "")) == NULL)
2916                 goto fail;
2917
2918         if (SYSCTL_ADD_PROC(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree),
2919             OID_AUTO, "istats", CTLFLAG_RD, sc, 0, en_sysctl_istats,
2920             "S", "internal statistics") == NULL)
2921                 goto fail;
2922
2923 #ifdef EN_DEBUG
2924         if (SYSCTL_ADD_UINT(&sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree),
2925             OID_AUTO, "debug", CTLFLAG_RW , &sc->debug, 0, "") == NULL)
2926                 goto fail;
2927 #endif
2928
2929         sc->ifatm.phy = &sc->utopia;
2930         utopia_attach(&sc->utopia, &sc->ifatm, &sc->media, &sc->en_mtx,
2931             &sc->sysctl_ctx, SYSCTL_CHILDREN(sc->sysctl_tree),
2932             &en_utopia_methods);
2933         utopia_init_media(&sc->utopia);
2934
2935         MGET(sc->padbuf, M_TRYWAIT, MT_DATA);
2936         if (sc->padbuf == NULL)
2937                 goto fail;
2938         bzero(sc->padbuf->m_data, MLEN);
2939
2940         if (bus_dma_tag_create(NULL, 1, 0,
2941             BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL,
2942             EN_TXSZ * 1024, EN_MAX_DMASEG, EN_TXSZ * 1024, 0,
2943             NULL, NULL, &sc->txtag))
2944                 goto fail;
2945
2946         sc->map_zone = uma_zcreate("en dma maps", sizeof(struct en_map),
2947             en_map_ctor, en_map_dtor, NULL, en_map_fini, UMA_ALIGN_PTR,
2948             UMA_ZONE_ZINIT);
2949         if (sc->map_zone == NULL)
2950                 goto fail;
2951         uma_zone_set_max(sc->map_zone, EN_MAX_MAPS);
2952
2953         /*
2954          * init softc
2955          */
2956         sc->vccs = malloc(MID_N_VC * sizeof(sc->vccs[0]),
2957             M_DEVBUF, M_ZERO | M_WAITOK);
2958
2959         sz = sc->en_obmemsz - (MID_BUFOFF - MID_RAMOFF);
2960         ptr = sav = MID_BUFOFF;
2961         ptr = roundup(ptr, EN_TXSZ * 1024);     /* align */
2962         sz = sz - (ptr - sav);
2963         if (EN_TXSZ*1024 * EN_NTX > sz) {
2964                 if_printf(&sc->ifatm.ifnet, "EN_NTX/EN_TXSZ too big\n");
2965                 goto fail;
2966         }
2967         for (lcv = 0 ;lcv < EN_NTX ;lcv++) {
2968                 sc->txslot[lcv].mbsize = 0;
2969                 sc->txslot[lcv].start = ptr;
2970                 ptr += (EN_TXSZ * 1024);
2971                 sz -= (EN_TXSZ * 1024);
2972                 sc->txslot[lcv].stop = ptr;
2973                 sc->txslot[lcv].nref = 0;
2974                 DBG(sc, INIT, ("tx%d: start 0x%x, stop 0x%x", lcv,
2975                     sc->txslot[lcv].start, sc->txslot[lcv].stop));
2976         }
2977
2978         sav = ptr;
2979         ptr = roundup(ptr, EN_RXSZ * 1024);     /* align */
2980         sz = sz - (ptr - sav);
2981         sc->en_nrx = sz / (EN_RXSZ * 1024);
2982         if (sc->en_nrx <= 0) {
2983                 if_printf(&sc->ifatm.ifnet, "EN_NTX/EN_TXSZ/EN_RXSZ too big\n");
2984                 goto fail;
2985         }
2986
2987         /* 
2988          * ensure that there is always one VC slot on the service list free
2989          * so that we can tell the difference between a full and empty list.
2990          */
2991         if (sc->en_nrx >= MID_N_VC)
2992                 sc->en_nrx = MID_N_VC - 1;
2993
2994         for (lcv = 0 ; lcv < sc->en_nrx ; lcv++) {
2995                 sc->rxslot[lcv].vcc = NULL;
2996                 midvloc = sc->rxslot[lcv].start = ptr;
2997                 ptr += (EN_RXSZ * 1024);
2998                 sz -= (EN_RXSZ * 1024);
2999                 sc->rxslot[lcv].stop = ptr;
3000                 midvloc = midvloc - MID_RAMOFF;
3001                 /* mask, cvt to words */
3002                 midvloc = (midvloc & ~((EN_RXSZ*1024) - 1)) >> 2;
3003                 /* we only want the top 11 bits */
3004                 midvloc = midvloc >> MIDV_LOCTOPSHFT;
3005                 midvloc = (midvloc & MIDV_LOCMASK) << MIDV_LOCSHIFT;
3006                 sc->rxslot[lcv].mode = midvloc | 
3007                     (en_k2sz(EN_RXSZ) << MIDV_SZSHIFT) | MIDV_TRASH;
3008
3009                 DBG(sc, INIT, ("rx%d: start 0x%x, stop 0x%x, mode 0x%x", lcv,
3010                     sc->rxslot[lcv].start, sc->rxslot[lcv].stop,
3011                     sc->rxslot[lcv].mode));
3012         }
3013
3014         if_printf(&sc->ifatm.ifnet, "%d %dKB receive buffers, %d %dKB transmit "
3015             "buffers\n", sc->en_nrx, EN_RXSZ, EN_NTX, EN_TXSZ);
3016         if_printf(&sc->ifatm.ifnet, "end station identifier (mac address) "
3017             "%6D\n", sc->ifatm.mib.esi, ":");
3018
3019         /*
3020          * Start SUNI stuff. This will call our readregs/writeregs
3021          * functions and these assume the lock to be held so we must get it
3022          * here.
3023          */
3024         EN_LOCK(sc);
3025         utopia_start(&sc->utopia);
3026         utopia_reset(&sc->utopia);
3027         EN_UNLOCK(sc);
3028
3029         /*
3030          * final commit
3031          */
3032         atm_ifattach(ifp); 
3033
3034 #ifdef ENABLE_BPF
3035         bpfattach(ifp, DLT_ATM_RFC1483, sizeof(struct atmllc));
3036 #endif
3037
3038         return (0);
3039
3040  fail:
3041         en_destroy(sc);
3042         return (-1);
3043 }
3044
3045 /*
3046  * Free all internal resources. No access to bus resources here.
3047  * No locking required here (interrupt is already disabled).
3048  *
3049  * LOCK: unlocked, needed (but destroyed)
3050  */
3051 void
3052 en_destroy(struct en_softc *sc)
3053 {
3054         u_int i;
3055
3056         if (sc->utopia.state & UTP_ST_ATTACHED) {
3057                 /* these assume the lock to be held */
3058                 EN_LOCK(sc);
3059                 utopia_stop(&sc->utopia);
3060                 utopia_detach(&sc->utopia);
3061                 EN_UNLOCK(sc);
3062         }
3063
3064         if (sc->vccs != NULL) {
3065                 /* get rid of sticky VCCs */
3066                 for (i = 0; i < MID_N_VC; i++)
3067                         if (sc->vccs[i] != NULL)
3068                                 uma_zfree(en_vcc_zone, sc->vccs[i]);
3069                 free(sc->vccs, M_DEVBUF);
3070         }
3071
3072         if (sc->padbuf != NULL)
3073                 m_free(sc->padbuf);
3074
3075         /*
3076          * Destroy the map zone before the tag (the fini function will
3077          * destroy the DMA maps using the tag)
3078          */
3079         if (sc->map_zone != NULL)
3080                 uma_zdestroy(sc->map_zone);
3081
3082         if (sc->txtag != NULL)
3083                 bus_dma_tag_destroy(sc->txtag);
3084
3085         (void)sysctl_ctx_free(&sc->sysctl_ctx);
3086
3087         cv_destroy(&sc->cv_close);
3088         mtx_destroy(&sc->en_mtx);
3089 }
3090
3091 /*
3092  * Module loaded/unloaded
3093  */
3094 int
3095 en_modevent(module_t mod __unused, int event, void *arg __unused)
3096 {
3097
3098         switch (event) {
3099
3100           case MOD_LOAD:
3101                 en_vcc_zone = uma_zcreate("EN vccs", sizeof(struct en_vcc),
3102                     NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
3103                 if (en_vcc_zone == NULL)
3104                         return (ENOMEM);
3105                 break;
3106
3107           case MOD_UNLOAD:
3108                 uma_zdestroy(en_vcc_zone);
3109                 break;
3110         }
3111         return (0);
3112 }
3113
3114 /*********************************************************************/
3115 /*
3116  * Debugging support
3117  */
3118
3119 #ifdef EN_DDBHOOK
3120 /*
3121  * functions we can call from ddb
3122  */
3123
3124 /*
3125  * en_dump: dump the state
3126  */
3127 #define END_SWSL        0x00000040              /* swsl state */
3128 #define END_DRQ         0x00000020              /* drq state */
3129 #define END_DTQ         0x00000010              /* dtq state */
3130 #define END_RX          0x00000008              /* rx state */
3131 #define END_TX          0x00000004              /* tx state */
3132 #define END_MREGS       0x00000002              /* registers */
3133 #define END_STATS       0x00000001              /* dump stats */
3134
3135 #define END_BITS "\20\7SWSL\6DRQ\5DTQ\4RX\3TX\2MREGS\1STATS"
3136
3137 static void
3138 en_dump_stats(const struct en_stats *s)
3139 {
3140         printf("en_stats:\n");
3141         printf("\t%d/%d mfix (%d failed)\n", s->mfixaddr, s->mfixlen,
3142             s->mfixfail);
3143         printf("\t%d rx dma overflow interrupts\n", s->dmaovr);
3144         printf("\t%d times out of TX space and stalled\n", s->txoutspace);
3145         printf("\t%d times out of DTQs\n", s->txdtqout);
3146         printf("\t%d times launched a packet\n", s->launch);
3147         printf("\t%d times pulled the hw service list\n", s->hwpull);
3148         printf("\t%d times pushed a vci on the sw service list\n", s->swadd);
3149         printf("\t%d times RX pulled an mbuf from Q that wasn't ours\n",
3150             s->rxqnotus);
3151         printf("\t%d times RX pulled a good mbuf from Q\n", s->rxqus);
3152         printf("\t%d times ran out of DRQs\n", s->rxdrqout);
3153         printf("\t%d transmit packets dropped due to mbsize\n", s->txmbovr);
3154         printf("\t%d cells trashed due to turned off rxvc\n", s->vtrash);
3155         printf("\t%d cells trashed due to totally full buffer\n", s->otrash);
3156         printf("\t%d cells trashed due almost full buffer\n", s->ttrash);
3157         printf("\t%d rx mbuf allocation failures\n", s->rxmbufout);
3158         printf("\t%d times out of tx maps\n", s->txnomap);
3159 #ifdef NATM
3160 #ifdef NATM_STAT
3161         printf("\tnatmintr so_rcv: ok/drop cnt: %d/%d, ok/drop bytes: %d/%d\n",
3162             natm_sookcnt, natm_sodropcnt, natm_sookbytes, natm_sodropbytes);
3163 #endif
3164 #endif
3165 }
3166
3167 static void
3168 en_dump_mregs(struct en_softc *sc)
3169 {
3170         u_int cnt;
3171
3172         printf("mregs:\n");
3173         printf("resid = 0x%x\n", en_read(sc, MID_RESID));
3174         printf("interrupt status = 0x%b\n",
3175             (int)en_read(sc, MID_INTSTAT), MID_INTBITS);
3176         printf("interrupt enable = 0x%b\n", 
3177              (int)en_read(sc, MID_INTENA), MID_INTBITS);
3178         printf("mcsr = 0x%b\n", (int)en_read(sc, MID_MAST_CSR), MID_MCSRBITS);
3179         printf("serv_write = [chip=%u] [us=%u]\n", en_read(sc, MID_SERV_WRITE),
3180              MID_SL_A2REG(sc->hwslistp));
3181         printf("dma addr = 0x%x\n", en_read(sc, MID_DMA_ADDR));
3182         printf("DRQ: chip[rd=0x%x,wr=0x%x], sc[chip=0x%x,us=0x%x]\n",
3183             MID_DRQ_REG2A(en_read(sc, MID_DMA_RDRX)), 
3184             MID_DRQ_REG2A(en_read(sc, MID_DMA_WRRX)), sc->drq_chip, sc->drq_us);
3185         printf("DTQ: chip[rd=0x%x,wr=0x%x], sc[chip=0x%x,us=0x%x]\n",
3186             MID_DTQ_REG2A(en_read(sc, MID_DMA_RDTX)), 
3187             MID_DTQ_REG2A(en_read(sc, MID_DMA_WRTX)), sc->dtq_chip, sc->dtq_us);
3188
3189         printf("  unusal txspeeds:");
3190         for (cnt = 0 ; cnt < MID_N_VC ; cnt++)
3191                 if (sc->vccs[cnt]->txspeed)
3192                         printf(" vci%d=0x%x", cnt, sc->vccs[cnt]->txspeed);
3193         printf("\n");
3194
3195         printf("  rxvc slot mappings:");
3196         for (cnt = 0 ; cnt < MID_N_VC ; cnt++)
3197                 if (sc->vccs[cnt]->rxslot != NULL)
3198                         printf("  %d->%zu", cnt,
3199                             sc->vccs[cnt]->rxslot - sc->rxslot);
3200         printf("\n");
3201 }
3202
3203 static void
3204 en_dump_tx(struct en_softc *sc)
3205 {
3206         u_int slot;
3207
3208         printf("tx:\n");
3209         for (slot = 0 ; slot < EN_NTX; slot++) {
3210                 printf("tx%d: start/stop/cur=0x%x/0x%x/0x%x [%d]  ", slot,
3211                     sc->txslot[slot].start, sc->txslot[slot].stop,
3212                     sc->txslot[slot].cur,
3213                     (sc->txslot[slot].cur - sc->txslot[slot].start) / 4);
3214                 printf("mbsize=%d, bfree=%d\n", sc->txslot[slot].mbsize,
3215                     sc->txslot[slot].bfree);
3216                 printf("txhw: base_address=0x%x, size=%u, read=%u, "
3217                     "descstart=%u\n",
3218                     (u_int)MIDX_BASE(en_read(sc, MIDX_PLACE(slot))), 
3219                     MIDX_SZ(en_read(sc, MIDX_PLACE(slot))),
3220                     en_read(sc, MIDX_READPTR(slot)),
3221                     en_read(sc, MIDX_DESCSTART(slot)));
3222         }
3223 }
3224
3225 static void
3226 en_dump_rx(struct en_softc *sc)
3227 {
3228         struct en_rxslot *slot;
3229
3230         printf("  recv slots:\n");
3231         for (slot = sc->rxslot ; slot < &sc->rxslot[sc->en_nrx]; slot++) {
3232                 printf("rx%zu: start/stop/cur=0x%x/0x%x/0x%x mode=0x%x ",
3233                     slot - sc->rxslot, slot->start, slot->stop, slot->cur,
3234                     slot->mode);
3235                 if (slot->vcc != NULL) {
3236                         printf("vci=%u\n", slot->vcc->vcc.vci);
3237                         printf("RXHW: mode=0x%x, DST_RP=0x%x, WP_ST_CNT=0x%x\n",
3238                             en_read(sc, MID_VC(slot->vcc->vcc.vci)),
3239                             en_read(sc, MID_DST_RP(slot->vcc->vcc.vci)),
3240                             en_read(sc, MID_WP_ST_CNT(slot->vcc->vcc.vci)));
3241                 }
3242         }
3243 }
3244
3245 /*
3246  * This is only correct for non-adaptec adapters
3247  */
3248 static void
3249 en_dump_dtqs(struct en_softc *sc)
3250 {
3251         uint32_t ptr, reg;
3252
3253         printf("  dtq [need_dtqs=%d,dtq_free=%d]:\n", sc->need_dtqs,
3254             sc->dtq_free);
3255         ptr = sc->dtq_chip;
3256         while (ptr != sc->dtq_us) {
3257                 reg = en_read(sc, ptr);
3258                 printf("\t0x%x=[%#x cnt=%d, chan=%d, end=%d, type=%d @ 0x%x]\n", 
3259                     sc->dtq[MID_DTQ_A2REG(ptr)], reg, MID_DMA_CNT(reg),
3260                     MID_DMA_TXCHAN(reg), (reg & MID_DMA_END) != 0,
3261                     MID_DMA_TYPE(reg), en_read(sc, ptr + 4));
3262                 EN_WRAPADD(MID_DTQOFF, MID_DTQEND, ptr, 8);
3263         }
3264 }
3265
3266 static void
3267 en_dump_drqs(struct en_softc *sc)
3268 {
3269         uint32_t ptr, reg;
3270
3271         printf("  drq [need_drqs=%d,drq_free=%d]:\n", sc->need_drqs,
3272             sc->drq_free);
3273         ptr = sc->drq_chip;
3274         while (ptr != sc->drq_us) {
3275                 reg = en_read(sc, ptr);
3276                 printf("\t0x%x=[cnt=%d, chan=%d, end=%d, type=%d @ 0x%x]\n", 
3277                     sc->drq[MID_DRQ_A2REG(ptr)], MID_DMA_CNT(reg),
3278                     MID_DMA_RXVCI(reg), (reg & MID_DMA_END) != 0,
3279                     MID_DMA_TYPE(reg), en_read(sc, ptr + 4));
3280                 EN_WRAPADD(MID_DRQOFF, MID_DRQEND, ptr, 8);
3281         }
3282 }
3283
3284 /* Do not staticize - meant for calling from DDB! */
3285 int
3286 en_dump(int unit, int level)
3287 {
3288         struct en_softc *sc;
3289         int lcv, cnt;
3290         devclass_t dc;
3291         int maxunit;
3292
3293         dc = devclass_find("en");
3294         if (dc == NULL) {
3295                 printf("%s: can't find devclass!\n", __func__);
3296                 return (0);
3297         }
3298         maxunit = devclass_get_maxunit(dc);
3299         for (lcv = 0 ; lcv < maxunit ; lcv++) {
3300                 sc = devclass_get_softc(dc, lcv);
3301                 if (sc == NULL)
3302                         continue;
3303                 if (unit != -1 && unit != lcv)
3304                         continue;
3305
3306                 if_printf(&sc->ifatm.ifnet, "dumping device at level 0x%b\n",
3307                     level, END_BITS);
3308
3309                 if (sc->dtq_us == 0) {
3310                         printf("<hasn't been en_init'd yet>\n");
3311                         continue;
3312                 }
3313
3314                 if (level & END_STATS)
3315                         en_dump_stats(&sc->stats);
3316                 if (level & END_MREGS)
3317                         en_dump_mregs(sc);
3318                 if (level & END_TX)
3319                         en_dump_tx(sc);
3320                 if (level & END_RX)
3321                         en_dump_rx(sc);
3322                 if (level & END_DTQ)
3323                         en_dump_dtqs(sc);
3324                 if (level & END_DRQ)
3325                         en_dump_drqs(sc);
3326
3327                 if (level & END_SWSL) {
3328                         printf(" swslist [size=%d]: ", sc->swsl_size);
3329                         for (cnt = sc->swsl_head ; cnt != sc->swsl_tail ; 
3330                             cnt = (cnt + 1) % MID_SL_N)
3331                                 printf("0x%x ", sc->swslist[cnt]);
3332                         printf("\n");
3333                 }
3334         }
3335         return (0);
3336 }
3337
3338 /*
3339  * en_dumpmem: dump the memory
3340  *
3341  * Do not staticize - meant for calling from DDB!
3342  */
3343 int
3344 en_dumpmem(int unit, int addr, int len)
3345 {
3346         struct en_softc *sc;
3347         uint32_t reg;
3348         devclass_t dc;
3349
3350         dc = devclass_find("en");
3351         if (dc == NULL) {
3352                 printf("%s: can't find devclass\n", __func__);
3353                 return (0);
3354         }
3355         sc = devclass_get_softc(dc, unit);
3356         if (sc == NULL) {
3357                 printf("%s: invalid unit number: %d\n", __func__, unit);
3358                 return (0);
3359         }
3360
3361         addr = addr & ~3;
3362         if (addr < MID_RAMOFF || addr + len * 4 > MID_MAXOFF || len <= 0) {
3363                 printf("invalid addr/len number: %d, %d\n", addr, len);
3364                 return (0);
3365         }
3366         printf("dumping %d words starting at offset 0x%x\n", len, addr);
3367         while (len--) {
3368                 reg = en_read(sc, addr);
3369                 printf("mem[0x%x] = 0x%x\n", addr, reg);
3370                 addr += 4;
3371         }
3372         return (0);
3373 }
3374 #endif