1/* $NetBSD$ */
2
3/*-
4 * Copyright (c) 2002-2006 David Boggs. <boggs@boggs.palo-alto.ca.us>
5 * All rights reserved.
6 *
7 * BSD LICENSE:
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 *
18 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
22 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28 * SUCH DAMAGE.
29 *
30 * GNU GENERAL PUBLIC LICENSE:
31 *
32 * This program is free software; you can redistribute it and/or modify it
33 * under the terms of the GNU General Public License as published by the Free
34 * Software Foundation; either version 2 of the License, or (at your option)
35 * any later version.
36 *
37 * This program is distributed in the hope that it will be useful, but WITHOUT
38 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
39 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
40 * more details.
41 *
42 * You should have received a copy of the GNU General Public License along with
43 * this program; if not, write to the Free Software Foundation, Inc., 59
44 * Temple Place - Suite 330, Boston, MA  02111-1307, USA.
45 *
46 * DESCRIPTION:
47 *
48 * This is an open-source Unix device driver for PCI-bus WAN interface cards.
49 * It sends and receives packets in HDLC frames over synchronous links.
50 * A generic PC plus Unix plus some LMC cards makes an OPEN router.
51 * This driver works with FreeBSD, NetBSD, OpenBSD, BSD/OS and Linux.
52 * It has been tested on i386 (32-bit little-end), PowerPC (32-bit
53 * big-end), Sparc (64-bit big-end), and Alpha (64-bit little-end)
54 * architectures.
55 *
56 * HISTORY AND AUTHORS:
57 *
58 * Ron Crane had the neat idea to use a Fast Ethernet chip as a PCI
59 * interface and add an Ethernet-to-HDLC gate array to make a WAN card.
60 * David Boggs designed the Ethernet-to-HDLC gate arrays and PC cards.
61 * We did this at our company, LAN Media Corporation (LMC).
62 * SBE Corp aquired LMC and continues to make the cards.
63 *
64 * Since the cards use Tulip Ethernet chips, we started with Matt Thomas'
65 * ubiquitous "de" driver.  Michael Graff stripped out the Ethernet stuff
66 * and added HSSI stuff.  Basil Gunn ported it to Solaris (lost) and
67 * Rob Braun ported it to Linux.  Andrew Stanley-Jones added support
68 * for three more cards and wrote the first version of lmcconfig.
69 * During 2002-5 David Boggs rewrote it and now feels responsible for it.
70 *
71 * RESPONSIBLE INDIVIDUAL:
72 *
73 * Send bug reports and improvements to <boggs@boggs.palo-alto.ca.us>.
74 */
75
76# include <sys/cdefs.h>
77__KERNEL_RCSID(0, "$NetBSD$");
78# include <sys/param.h>	/* OS version */
79# include "opt_inet.h"	/* INET6, INET */
80# include "opt_altq_enabled.h" /* ALTQ */
81# define IOREF_CSR 1	/* 1=IO refs; 0=MEM refs */
82# define IFNET 1
83# define NETDEV 0
84# define NAPI 0
85# define SPPP 1
86# define P2P 0
87# define GEN_HDLC 0
88# define SYNC_PPP 0
89# define NETGRAPH 0
90# define DEVICE_POLLING 0
91#
92# include <sys/systm.h>
93# include <sys/kernel.h>
94# include <sys/module.h>
95# include <sys/mbuf.h>
96# include <sys/socket.h>
97# include <sys/sockio.h>
98# include <sys/device.h>
99# include <sys/reboot.h>
100# include <sys/kauth.h>
101# include <sys/proc.h>
102# include <net/if.h>
103# include <net/if_types.h>
104# include <net/if_media.h>
105# include <net/netisr.h>
106# include <sys/bus.h>
107# include <sys/intr.h>
108# include <machine/lock.h>
109# include <machine/types.h>
110# include <dev/pci/pcivar.h>
111# if INET || INET6
112#  include <netinet/in.h>
113#  include <netinet/in_var.h>
114# endif
115# if SPPP
116#  include <net/if_spppvar.h>
117# endif
118#  include <net/bpf.h>
119# if !defined(ALTQ)
120#  define ALTQ 0
121# endif
122/* and finally... */
123# include "if_lmc.h"
124
125
126
127
128/* The SROM is a generic 93C46 serial EEPROM (64 words by 16 bits). */
129/* Data is set up before the RISING edge of CLK; CLK is parked low. */
130static void  /* context: process */
131srom_shift_bits(softc_t *sc, u_int32_t data, u_int32_t len)
132  {
133  u_int32_t csr = READ_CSR(sc, TLP_SROM_MII);
134  for (; len>0; len--)
135    {  /* MSB first */
136    if (data & (1<<(len-1)))
137      csr |=  TLP_SROM_DIN;	/* DIN setup */
138    else
139      csr &= ~TLP_SROM_DIN;	/* DIN setup */
140    WRITE_CSR(sc, TLP_SROM_MII, csr);
141    csr |=  TLP_SROM_CLK;	/* CLK rising edge */
142    WRITE_CSR(sc, TLP_SROM_MII, csr);
143    csr &= ~TLP_SROM_CLK;	/* CLK falling edge */
144    WRITE_CSR(sc, TLP_SROM_MII, csr);
145    }
146  }
147
148/* Data is sampled on the RISING edge of CLK; CLK is parked low. */
149static u_int16_t  /* context: process */
150srom_read(softc_t *sc, u_int8_t addr)
151  {
152  int i;
153  u_int32_t csr;
154  u_int16_t data;
155
156  /* Enable SROM access. */
157  csr = (TLP_SROM_SEL | TLP_SROM_RD | TLP_MII_MDOE);
158  WRITE_CSR(sc, TLP_SROM_MII, csr);
159  /* CS rising edge prepares SROM for a new cycle. */
160  csr |= TLP_SROM_CS;
161  WRITE_CSR(sc, TLP_SROM_MII, csr);	/* assert CS */
162  srom_shift_bits(sc,  6,   4);		/* issue read cmd */
163  srom_shift_bits(sc, addr, 6);		/* issue address */
164  for (data=0, i=16; i>=0; i--)		/* read ->17<- bits of data */
165    {  /* MSB first */
166    csr = READ_CSR(sc, TLP_SROM_MII);	/* DOUT sampled */
167    data = (data<<1) | ((csr & TLP_SROM_DOUT) ? 1:0);
168    csr |=  TLP_SROM_CLK;		/* CLK rising edge */
169    WRITE_CSR(sc, TLP_SROM_MII, csr);
170    csr &= ~TLP_SROM_CLK;		/* CLK falling edge */
171    WRITE_CSR(sc, TLP_SROM_MII, csr);
172    }
173  /* Disable SROM access. */
174  WRITE_CSR(sc, TLP_SROM_MII, TLP_MII_MDOE);
175
176  return data;
177  }
178
179/* The SROM is formatted by the mfgr and should NOT be written! */
180/* But lmcconfig can rewrite it in case it gets overwritten somehow. */
181static void  /* context: process */
182srom_write(softc_t *sc, u_int8_t addr, u_int16_t data)
183  {
184  u_int32_t csr;
185  int i;
186
187  /* Enable SROM access. */
188  csr = (TLP_SROM_SEL | TLP_SROM_RD | TLP_MII_MDOE);
189  WRITE_CSR(sc, TLP_SROM_MII, csr);
190
191  /* Issue write-enable command. */
192  csr |= TLP_SROM_CS;
193  WRITE_CSR(sc, TLP_SROM_MII, csr);	/* assert CS */
194  srom_shift_bits(sc,  4, 4);		/* issue write enable cmd */
195  srom_shift_bits(sc, 63, 6);		/* issue address */
196  csr &= ~TLP_SROM_CS;
197  WRITE_CSR(sc, TLP_SROM_MII, csr);	/* deassert CS */
198
199  /* Issue erase command. */
200  csr |= TLP_SROM_CS;
201  WRITE_CSR(sc, TLP_SROM_MII, csr);	/* assert CS */
202  srom_shift_bits(sc, 7, 4);		/* issue erase cmd */
203  srom_shift_bits(sc, addr, 6);		/* issue address */
204  csr &= ~TLP_SROM_CS;
205  WRITE_CSR(sc, TLP_SROM_MII, csr);	/* deassert CS */
206
207  /* Issue write command. */
208  csr |= TLP_SROM_CS;
209  WRITE_CSR(sc, TLP_SROM_MII, csr);	/* assert CS */
210  for (i=0; i<10; i++)  /* 100 ms max wait */
211    if ((READ_CSR(sc, TLP_SROM_MII) & TLP_SROM_DOUT)==0) SLEEP(10000);
212  srom_shift_bits(sc, 5, 4);		/* issue write cmd */
213  srom_shift_bits(sc, addr, 6);		/* issue address */
214  srom_shift_bits(sc, data, 16);	/* issue data */
215  csr &= ~TLP_SROM_CS;
216  WRITE_CSR(sc, TLP_SROM_MII, csr);	/* deassert CS */
217
218  /* Issue write-disable command. */
219  csr |= TLP_SROM_CS;
220  WRITE_CSR(sc, TLP_SROM_MII, csr);	/* assert CS */
221  for (i=0; i<10; i++)  /* 100 ms max wait */
222    if ((READ_CSR(sc, TLP_SROM_MII) & TLP_SROM_DOUT)==0) SLEEP(10000);
223  srom_shift_bits(sc, 4, 4);		/* issue write disable cmd */
224  srom_shift_bits(sc, 0, 6);		/* issue address */
225  csr &= ~TLP_SROM_CS;
226  WRITE_CSR(sc, TLP_SROM_MII, csr);	/* deassert CS */
227
228  /* Disable SROM access. */
229  WRITE_CSR(sc, TLP_SROM_MII, TLP_MII_MDOE);
230  }
231
232/* Not all cards have BIOS roms. */
233/* The BIOS ROM is an AMD 29F010 1Mbit (128K by 8) EEPROM. */
234static u_int8_t  /* context: process */
235bios_read(softc_t *sc, u_int32_t addr)
236  {
237  u_int32_t srom_mii;
238
239  /* Load the BIOS rom address register. */
240  WRITE_CSR(sc, TLP_BIOS_ROM, addr);
241
242  /* Enable the BIOS rom. */
243  srom_mii = TLP_BIOS_SEL | TLP_BIOS_RD | TLP_MII_MDOE;
244  WRITE_CSR(sc, TLP_SROM_MII, srom_mii);
245
246  /* Wait at least 20 PCI cycles. */
247  DELAY(20);
248
249  /* Read the BIOS rom data. */
250  srom_mii = READ_CSR(sc, TLP_SROM_MII);
251
252  /* Disable the BIOS rom. */
253  WRITE_CSR(sc, TLP_SROM_MII, TLP_MII_MDOE);
254
255  return (u_int8_t)srom_mii & 0xFF;
256  }
257
258static void  /* context: process */
259bios_write_phys(softc_t *sc, u_int32_t addr, u_int8_t data)
260  {
261  u_int32_t srom_mii;
262
263  /* Load the BIOS rom address register. */
264  WRITE_CSR(sc, TLP_BIOS_ROM, addr);
265
266  /* Enable the BIOS rom. */
267  srom_mii = TLP_BIOS_SEL | TLP_BIOS_WR | TLP_MII_MDOE;
268
269  /* Load the data into the data register. */
270  srom_mii = (srom_mii & 0xFFFFFF00) | (data & 0xFF);
271  WRITE_CSR(sc, TLP_SROM_MII, srom_mii);
272
273  /* Wait at least 20 PCI cycles. */
274  DELAY(20);
275
276  /* Disable the BIOS rom. */
277  WRITE_CSR(sc, TLP_SROM_MII, TLP_MII_MDOE);
278  }
279
280static void  /* context: process */
281bios_write(softc_t *sc, u_int32_t addr, u_int8_t data)
282  {
283  u_int8_t read_data;
284
285  /* this sequence enables writing */
286  bios_write_phys(sc, 0x5555, 0xAA);
287  bios_write_phys(sc, 0x2AAA, 0x55);
288  bios_write_phys(sc, 0x5555, 0xA0);
289  bios_write_phys(sc, addr,   data);
290
291  /* Wait for the write operation to complete. */
292  for (;;)  /* interruptible syscall */
293    {
294    for (;;)
295      {
296      read_data = bios_read(sc, addr);
297      if ((read_data & 0x80) == (data & 0x80)) break;
298      if  (read_data & 0x20)
299        {  /* Data sheet says read it again. */
300        read_data = bios_read(sc, addr);
301        if ((read_data & 0x80) == (data & 0x80)) break;
302        if (sc->config.debug)
303          printf("%s: bios_write() failed; rom addr=0x%x\n",
304           NAME_UNIT, addr);
305        return;
306        }
307      }
308    read_data = bios_read(sc, addr);
309    if (read_data == data) break;
310    }
311  }
312
313static void  /* context: process */
314bios_erase(softc_t *sc)
315  {
316  unsigned char read_data;
317
318  /* This sequence enables erasing: */
319  bios_write_phys(sc, 0x5555, 0xAA);
320  bios_write_phys(sc, 0x2AAA, 0x55);
321  bios_write_phys(sc, 0x5555, 0x80);
322  bios_write_phys(sc, 0x5555, 0xAA);
323  bios_write_phys(sc, 0x2AAA, 0x55);
324  bios_write_phys(sc, 0x5555, 0x10);
325
326  /* Wait for the erase operation to complete. */
327  for (;;) /* interruptible syscall */
328    {
329    for (;;)
330      {
331      read_data = bios_read(sc, 0);
332      if (read_data & 0x80) break;
333      if (read_data & 0x20)
334        {  /* Data sheet says read it again. */
335        read_data = bios_read(sc, 0);
336        if (read_data & 0x80) break;
337        if (sc->config.debug)
338          printf("%s: bios_erase() failed\n", NAME_UNIT);
339        return;
340        }
341      }
342    read_data = bios_read(sc, 0);
343    if (read_data == 0xFF) break;
344    }
345  }
346
347/* MDIO is 3-stated between tranactions. */
348/* MDIO is set up before the RISING edge of MDC; MDC is parked low. */
349static void  /* context: process */
350mii_shift_bits(softc_t *sc, u_int32_t data, u_int32_t len)
351  {
352  u_int32_t csr = READ_CSR(sc, TLP_SROM_MII);
353  for (; len>0; len--)
354    {  /* MSB first */
355    if (data & (1<<(len-1)))
356      csr |=  TLP_MII_MDOUT; /* MDOUT setup */
357    else
358      csr &= ~TLP_MII_MDOUT; /* MDOUT setup */
359    WRITE_CSR(sc, TLP_SROM_MII, csr);
360    csr |=  TLP_MII_MDC;     /* MDC rising edge */
361    WRITE_CSR(sc, TLP_SROM_MII, csr);
362    csr &= ~TLP_MII_MDC;     /* MDC falling edge */
363    WRITE_CSR(sc, TLP_SROM_MII, csr);
364    }
365  }
366
367/* The specification for the MII is IEEE Std 802.3 clause 22. */
368/* MDIO is sampled on the RISING edge of MDC; MDC is parked low. */
369static u_int16_t  /* context: process */
370mii_read(softc_t *sc, u_int8_t regad)
371  {
372  int i;
373  u_int32_t csr;
374  u_int16_t data = 0;
375
376  WRITE_CSR(sc, TLP_SROM_MII, TLP_MII_MDOUT);
377
378  mii_shift_bits(sc, 0xFFFFF, 20);	/* preamble */
379  mii_shift_bits(sc, 0xFFFFF, 20);	/* preamble */
380  mii_shift_bits(sc, 1, 2);		/* start symbol */
381  mii_shift_bits(sc, 2, 2);		/* read op */
382  mii_shift_bits(sc, 0, 5);		/* phyad=0 */
383  mii_shift_bits(sc, regad, 5);		/* regad */
384  csr = READ_CSR(sc, TLP_SROM_MII);
385  csr |= TLP_MII_MDOE;
386  WRITE_CSR(sc, TLP_SROM_MII, csr);
387  mii_shift_bits(sc, 0, 2);		/* turn-around */
388  for (i=15; i>=0; i--)			/* data */
389    {  /* MSB first */
390    csr = READ_CSR(sc, TLP_SROM_MII);	/* MDIN sampled */
391    data = (data<<1) | ((csr & TLP_MII_MDIN) ? 1:0);
392    csr |=  TLP_MII_MDC;		/* MDC rising edge */
393    WRITE_CSR(sc, TLP_SROM_MII, csr);
394    csr &= ~TLP_MII_MDC;		/* MDC falling edge */
395    WRITE_CSR(sc, TLP_SROM_MII, csr);
396    }
397  return data;
398  }
399
400static void  /* context: process */
401mii_write(softc_t *sc, u_int8_t regad, u_int16_t data)
402  {
403  WRITE_CSR(sc, TLP_SROM_MII, TLP_MII_MDOUT);
404  mii_shift_bits(sc, 0xFFFFF, 20);	/* preamble */
405  mii_shift_bits(sc, 0xFFFFF, 20);	/* preamble */
406  mii_shift_bits(sc, 1, 2);		/* start symbol */
407  mii_shift_bits(sc, 1, 2);		/* write op */
408  mii_shift_bits(sc, 0, 5);		/* phyad=0 */
409  mii_shift_bits(sc, regad, 5);		/* regad */
410  mii_shift_bits(sc, 2, 2);		/* turn-around */
411  mii_shift_bits(sc, data, 16);		/* data */
412  WRITE_CSR(sc, TLP_SROM_MII, TLP_MII_MDOE);
413  if (regad == 16) sc->led_state = data; /* a small optimization */
414  }
415
416static void
417mii16_set_bits(softc_t *sc, u_int16_t bits)
418  {
419  u_int16_t mii16 = mii_read(sc, 16);
420  mii16 |= bits;
421  mii_write(sc, 16, mii16);
422  }
423
424static void
425mii16_clr_bits(softc_t *sc, u_int16_t bits)
426  {
427  u_int16_t mii16 = mii_read(sc, 16);
428  mii16 &= ~bits;
429  mii_write(sc, 16, mii16);
430  }
431
432static void
433mii17_set_bits(softc_t *sc, u_int16_t bits)
434  {
435  u_int16_t mii17 = mii_read(sc, 17);
436  mii17 |= bits;
437  mii_write(sc, 17, mii17);
438  }
439
440static void
441mii17_clr_bits(softc_t *sc, u_int16_t bits)
442  {
443  u_int16_t mii17 = mii_read(sc, 17);
444  mii17 &= ~bits;
445  mii_write(sc, 17, mii17);
446  }
447
448/*
449 * Watchdog code is more readable if it refreshes LEDs
450 *  once a second whether they need it or not.
451 * But MII refs take 150 uSecs each, so remember the last value
452 *  written to MII16 and avoid LED writes that do nothing.
453 */
454
455static void
456led_off(softc_t *sc, u_int16_t led)
457  {
458  if ((led & sc->led_state) == led) return;
459  mii16_set_bits(sc, led);
460  }
461
462static void
463led_on(softc_t *sc, u_int16_t led)
464  {
465  if ((led & sc->led_state) == 0) return;
466  mii16_clr_bits(sc, led);
467  }
468
469static void
470led_inv(softc_t *sc, u_int16_t led)
471  {
472  u_int16_t mii16 = mii_read(sc, 16);
473  mii16 ^= led;
474  mii_write(sc, 16, mii16);
475  }
476
477/*
478 * T1 & T3 framer registers are accessed through MII regs 17 & 18.
479 * Write the address to MII reg 17 then R/W data through MII reg 18.
480 * The hardware interface is an Intel-style 8-bit muxed A/D bus.
481 */
482static void
483framer_write(softc_t *sc, u_int16_t addr, u_int8_t data)
484  {
485  mii_write(sc, 17, addr);
486  mii_write(sc, 18, data);
487  }
488
489static u_int8_t
490framer_read(softc_t *sc, u_int16_t addr)
491  {
492  mii_write(sc, 17, addr);
493  return (u_int8_t)mii_read(sc, 18);
494  }
495
496/* Tulip's hardware implementation of General Purpose IO
497 *   (GPIO) pins makes life difficult for software.
498 * Bits 7-0 in the Tulip GPIO CSR are used for two purposes
499 *   depending on the state of bit 8.
500 * If bit 8 is 0 then bits 7-0 are "data" bits.
501 * If bit 8 is 1 then bits 7-0 are "direction" bits.
502 * If a direction bit is one, the data bit is an output.
503 * The problem is that the direction bits are WRITE-ONLY.
504 * Software must remember the direction bits in a shadow copy.
505 * (sc->gpio_dir) in order to change some but not all of the bits.
506 * All accesses to the Tulip GPIO register use these five procedures.
507 */
508
509static void
510gpio_make_input(softc_t *sc, u_int32_t bits)
511  {
512  sc->gpio_dir &= ~bits;
513  WRITE_CSR(sc, TLP_GPIO, TLP_GPIO_DIR | (sc->gpio_dir));
514  }
515
516static void
517gpio_make_output(softc_t *sc, u_int32_t bits)
518  {
519  sc->gpio_dir |= bits;
520  WRITE_CSR(sc, TLP_GPIO, TLP_GPIO_DIR | (sc->gpio_dir));
521  }
522
523static u_int32_t
524gpio_read(softc_t *sc)
525  {
526  return READ_CSR(sc, TLP_GPIO);
527  }
528
529static void
530gpio_set_bits(softc_t *sc, u_int32_t bits)
531  {
532  WRITE_CSR(sc, TLP_GPIO, (gpio_read(sc) |  bits) & 0xFF);
533  }
534
535static void
536gpio_clr_bits(softc_t *sc, u_int32_t bits)
537  {
538  WRITE_CSR(sc, TLP_GPIO, (gpio_read(sc) & ~bits) & 0xFF);
539  }
540
541/* Reset ALL of the flip-flops in the gate array to zero. */
542/* This does NOT change the gate array programming. */
543/* Called during initialization so it must not sleep. */
544static void  /* context: kernel (boot) or process (syscall) */
545xilinx_reset(softc_t *sc)
546  {
547  /* Drive RESET low to force initialization. */
548  gpio_clr_bits(sc, GPIO_RESET);
549  gpio_make_output(sc, GPIO_RESET);
550
551  /* Hold RESET low for more than 10 uSec. */
552  DELAY(50);
553
554  /* Done with RESET; make it an input. */
555  gpio_make_input(sc,  GPIO_RESET);
556  }
557
558/* Load Xilinx gate array program from on-board rom. */
559/* This changes the gate array programming. */
560static void  /* context: process */
561xilinx_load_from_rom(softc_t *sc)
562  {
563  int i;
564
565  /* Drive MODE low to load from ROM rather than GPIO. */
566  gpio_clr_bits(sc, GPIO_MODE);
567  gpio_make_output(sc, GPIO_MODE);
568
569  /* Drive DP & RESET low to force configuration. */
570  gpio_clr_bits(sc, GPIO_RESET | GPIO_DP);
571  gpio_make_output(sc, GPIO_RESET | GPIO_DP);
572
573  /* Hold RESET & DP low for more than 10 uSec. */
574  DELAY(50);
575
576  /* Done with RESET & DP; make them inputs. */
577  gpio_make_input(sc, GPIO_DP | GPIO_RESET);
578
579  /* BUSY-WAIT for Xilinx chip to configure itself from ROM bits. */
580  for (i=0; i<100; i++) /* 1 sec max delay */
581    if ((gpio_read(sc) & GPIO_DP)==0) SLEEP(10000);
582
583  /* Done with MODE; make it an input. */
584  gpio_make_input(sc, GPIO_MODE);
585  }
586
587/* Load the Xilinx gate array program from userland bits. */
588/* This changes the gate array programming. */
589static int  /* context: process */
590xilinx_load_from_file(softc_t *sc, char *addr, u_int32_t len)
591  {
592  char *data;
593  int i, j, error;
594
595  /* Get some pages to hold the Xilinx bits; biggest file is < 6 KB. */
596  if (len > 8192) return EFBIG;  /* too big */
597  data = malloc(len, M_TEMP, M_WAITOK);
598  if (data == NULL) return ENOMEM;
599
600  /* Copy the Xilinx bits from userland. */
601  if ((error = copyin(addr, data, len)))
602    {
603    free(data, M_TEMP);
604    return error;
605    }
606
607  /* Drive MODE high to load from GPIO rather than ROM. */
608  gpio_set_bits(sc, GPIO_MODE);
609  gpio_make_output(sc, GPIO_MODE);
610
611  /* Drive DP & RESET low to force configuration. */
612  gpio_clr_bits(sc, GPIO_RESET | GPIO_DP);
613  gpio_make_output(sc, GPIO_RESET | GPIO_DP);
614
615  /* Hold RESET & DP low for more than 10 uSec. */
616  DELAY(50);
617
618  /* Done with RESET & DP; make them inputs. */
619  gpio_make_input(sc, GPIO_RESET | GPIO_DP);
620
621  /* BUSY-WAIT for Xilinx chip to clear its config memory. */
622  gpio_make_input(sc, GPIO_INIT);
623  for (i=0; i<10000; i++) /* 1 sec max delay */
624    if ((gpio_read(sc) & GPIO_INIT)==0) SLEEP(10000);
625
626  /* Configure CLK and DATA as outputs. */
627  gpio_set_bits(sc, GPIO_CLK);  /* park CLK high */
628  gpio_make_output(sc, GPIO_CLK | GPIO_DATA);
629
630  /* Write bits to Xilinx; CLK is parked HIGH. */
631  /* DATA is set up before the RISING edge of CLK. */
632  for (i=0; i<len; i++)
633    for (j=0; j<8; j++)
634      {  /* LSB first */
635      if (data[i] & (1<<j))
636        gpio_set_bits(sc, GPIO_DATA); /* DATA setup */
637      else
638        gpio_clr_bits(sc, GPIO_DATA); /* DATA setup */
639      gpio_clr_bits(sc, GPIO_CLK); /* CLK falling edge */
640      gpio_set_bits(sc, GPIO_CLK); /* CLK rising edge */
641      }
642
643  /* Stop driving all Xilinx-related signals. */
644  /* Pullup and pulldown resistors take over. */
645  gpio_make_input(sc, GPIO_CLK | GPIO_DATA | GPIO_MODE);
646
647  free(data, M_TEMP);
648
649  return 0;
650  }
651
652/* Write fragments of a command into the synthesized oscillator. */
653/* DATA is set up before the RISING edge of CLK.  CLK is parked low. */
654static void
655synth_shift_bits(softc_t *sc, u_int32_t data, u_int32_t len)
656  {
657  int i;
658
659  for (i=0; i<len; i++)
660    { /* LSB first */
661    if (data & (1<<i))
662      gpio_set_bits(sc, GPIO_DATA); /* DATA setup */
663    else
664      gpio_clr_bits(sc, GPIO_DATA); /* DATA setup */
665    gpio_set_bits(sc, GPIO_CLK);    /* CLK rising edge */
666    gpio_clr_bits(sc, GPIO_CLK);    /* CLK falling edge */
667    }
668  }
669
670/* Write a command to the synthesized oscillator on SSI and HSSIc. */
671static void  /* context: process */
672synth_write(softc_t *sc, struct synth *synth)
673  {
674  /* SSI cards have a programmable prescaler */
675  if (sc->status.card_type == CSID_LMC_SSI)
676    {
677    if (synth->prescale == 9) /* divide by 512 */
678      mii17_set_bits(sc, MII17_SSI_PRESCALE);
679    else                      /* divide by  32 */
680      mii17_clr_bits(sc, MII17_SSI_PRESCALE);
681    }
682
683  gpio_clr_bits(sc,    GPIO_DATA | GPIO_CLK);
684  gpio_make_output(sc, GPIO_DATA | GPIO_CLK);
685
686  /* SYNTH is a low-true chip enable for the AV9110 chip. */
687  gpio_set_bits(sc,    GPIO_SSI_SYNTH);
688  gpio_make_output(sc, GPIO_SSI_SYNTH);
689  gpio_clr_bits(sc,    GPIO_SSI_SYNTH);
690
691  /* Serially shift the command into the AV9110 chip. */
692  synth_shift_bits(sc, synth->n, 7);
693  synth_shift_bits(sc, synth->m, 7);
694  synth_shift_bits(sc, synth->v, 1);
695  synth_shift_bits(sc, synth->x, 2);
696  synth_shift_bits(sc, synth->r, 2);
697  synth_shift_bits(sc, 0x16, 5); /* enable clk/x output */
698
699  /* SYNTH (chip enable) going high ends the command. */
700  gpio_set_bits(sc,   GPIO_SSI_SYNTH);
701  gpio_make_input(sc, GPIO_SSI_SYNTH);
702
703  /* Stop driving serial-related signals; pullups/pulldowns take over. */
704  gpio_make_input(sc, GPIO_DATA | GPIO_CLK);
705
706  /* remember the new synthesizer parameters */
707  if (&sc->config.synth != synth) sc->config.synth = *synth;
708  }
709
710/* Write a command to the DAC controlling the VCXO on some T3 adapters. */
711/* The DAC is a TI-TLV5636: 12-bit resolution and a serial interface. */
712/* DATA is set up before the FALLING edge of CLK.  CLK is parked HIGH. */
713static void  /* context: process */
714dac_write(softc_t *sc, u_int16_t data)
715  {
716  int i;
717
718  /* Prepare to use DATA and CLK. */
719  gpio_set_bits(sc,    GPIO_DATA | GPIO_CLK);
720  gpio_make_output(sc, GPIO_DATA | GPIO_CLK);
721
722  /* High-to-low transition prepares DAC for new value. */
723  gpio_set_bits(sc,    GPIO_T3_DAC);
724  gpio_make_output(sc, GPIO_T3_DAC);
725  gpio_clr_bits(sc,    GPIO_T3_DAC);
726
727  /* Serially shift command bits into DAC. */
728  for (i=0; i<16; i++)
729    { /* MSB first */
730    if (data & (1<<(15-i)))
731      gpio_set_bits(sc, GPIO_DATA); /* DATA setup */
732    else
733      gpio_clr_bits(sc, GPIO_DATA); /* DATA setup */
734    gpio_clr_bits(sc, GPIO_CLK);    /* CLK falling edge */
735    gpio_set_bits(sc, GPIO_CLK);    /* CLK rising edge */
736    }
737
738  /* Done with DAC; make it an input; loads new value into DAC. */
739  gpio_set_bits(sc,   GPIO_T3_DAC);
740  gpio_make_input(sc, GPIO_T3_DAC);
741
742  /* Stop driving serial-related signals; pullups/pulldowns take over. */
743  gpio_make_input(sc, GPIO_DATA | GPIO_CLK);
744  }
745
746/* Begin HSSI card code */
747
748static struct card hssi_card =
749  {
750  .ident    = hssi_ident,
751  .watchdog = hssi_watchdog,
752  .ioctl    = hssi_ioctl,
753  .attach   = hssi_attach,
754  .detach   = hssi_detach,
755  };
756
757static void
758hssi_ident(softc_t *sc)
759  {
760  printf(", EIA-613");
761  }
762
763static void  /* context: softirq */
764hssi_watchdog(softc_t *sc)
765  {
766  u_int16_t mii16 = mii_read(sc, 16) & MII16_HSSI_MODEM;
767
768  sc->status.link_state = STATE_UP;
769
770  led_inv(sc, MII16_HSSI_LED_UL);  /* Software is alive. */
771  led_on(sc, MII16_HSSI_LED_LL);  /* always on (SSI cable) */
772
773  /* Check the transmit clock. */
774  if (sc->status.tx_speed == 0)
775    {
776    led_on(sc, MII16_HSSI_LED_UR);
777    sc->status.link_state = STATE_DOWN;
778    }
779  else
780    led_off(sc, MII16_HSSI_LED_UR);
781
782  /* Is the modem ready? */
783  if ((mii16 & MII16_HSSI_CA)==0)
784    {
785    led_off(sc, MII16_HSSI_LED_LR);
786    sc->status.link_state = STATE_DOWN;
787    }
788  else
789    led_on(sc, MII16_HSSI_LED_LR);
790
791  /* Print the modem control signals if they changed. */
792  if ((sc->config.debug) && (mii16 != sc->last_mii16))
793    {
794    const char *on = "ON ", *off = "OFF";
795    printf("%s: TA=%s CA=%s LA=%s LB=%s LC=%s TM=%s\n", NAME_UNIT,
796     (mii16 & MII16_HSSI_TA) ? on : off,
797     (mii16 & MII16_HSSI_CA) ? on : off,
798     (mii16 & MII16_HSSI_LA) ? on : off,
799     (mii16 & MII16_HSSI_LB) ? on : off,
800     (mii16 & MII16_HSSI_LC) ? on : off,
801     (mii16 & MII16_HSSI_TM) ? on : off);
802    }
803
804  /* SNMP one-second-report */
805  sc->status.snmp.hssi.sigs = mii16 & MII16_HSSI_MODEM;
806
807  /* Remember this state until next time. */
808  sc->last_mii16 = mii16;
809
810  /* If a loop back is in effect, link status is UP */
811  if (sc->config.loop_back != CFG_LOOP_NONE)
812    sc->status.link_state = STATE_UP;
813  }
814
815static int  /* context: process */
816hssi_ioctl(softc_t *sc, struct ioctl *ioctl)
817  {
818  int error = 0;
819
820  if (ioctl->cmd == IOCTL_SNMP_SIGS)
821    {
822    u_int16_t mii16 = mii_read(sc, 16);
823    mii16 &= ~MII16_HSSI_MODEM;
824    mii16 |= (MII16_HSSI_MODEM & ioctl->data);
825    mii_write(sc, 16, mii16);
826    }
827  else if (ioctl->cmd == IOCTL_SET_STATUS)
828    {
829    if (ioctl->data)
830      mii16_set_bits(sc, MII16_HSSI_TA);
831    else
832      mii16_clr_bits(sc, MII16_HSSI_TA);
833    }
834  else
835    error = EINVAL;
836
837  return error;
838  }
839
840/* Must not sleep. */
841static void
842hssi_attach(softc_t *sc, struct config *config)
843  {
844  if (config == NULL) /* startup config */
845    {
846    sc->status.card_type  = READ_PCI_CFG(sc, TLP_CSID);
847    sc->config.crc_len    = CFG_CRC_16;
848    sc->config.loop_back  = CFG_LOOP_NONE;
849    sc->config.tx_clk_src = CFG_CLKMUX_ST;
850    sc->config.dte_dce    = CFG_DTE;
851    sc->config.synth.n    = 52; /* 52.000 Mbs */
852    sc->config.synth.m    = 5;
853    sc->config.synth.v    = 0;
854    sc->config.synth.x    = 0;
855    sc->config.synth.r    = 0;
856    sc->config.synth.prescale = 2;
857    }
858  else if (config != &sc->config) /* change config */
859    {
860    u_int32_t *old_synth = (u_int32_t *)&sc->config.synth;
861    u_int32_t *new_synth = (u_int32_t *)&config->synth;
862    if ((sc->config.crc_len    == config->crc_len)    &&
863        (sc->config.loop_back  == config->loop_back)  &&
864        (sc->config.tx_clk_src == config->tx_clk_src) &&
865        (sc->config.dte_dce    == config->dte_dce)    &&
866        (*old_synth            == *new_synth))
867      return; /* nothing changed */
868    sc->config.crc_len    = config->crc_len;
869    sc->config.loop_back  = config->loop_back;
870    sc->config.tx_clk_src = config->tx_clk_src;
871    sc->config.dte_dce    = config->dte_dce;
872    *old_synth            = *new_synth;
873    }
874  /* If (config == &sc->config) then the FPGA microcode
875   * was just initialized and the current config should
876   * be reloaded into the card.
877   */
878
879  /* set CRC length */
880  if (sc->config.crc_len == CFG_CRC_32)
881    mii16_set_bits(sc, MII16_HSSI_CRC32);
882  else
883    mii16_clr_bits(sc, MII16_HSSI_CRC32);
884
885  /* Assert pin LA in HSSI conn: ask modem for local loop. */
886  if (sc->config.loop_back == CFG_LOOP_LL)
887    mii16_set_bits(sc, MII16_HSSI_LA);
888  else
889    mii16_clr_bits(sc, MII16_HSSI_LA);
890
891  /* Assert pin LB in HSSI conn: ask modem for remote loop. */
892  if (sc->config.loop_back == CFG_LOOP_RL)
893    mii16_set_bits(sc, MII16_HSSI_LB);
894  else
895    mii16_clr_bits(sc, MII16_HSSI_LB);
896
897  if (sc->status.card_type == CSID_LMC_HSSI)
898    {
899    /* set TXCLK src */
900    if (sc->config.tx_clk_src == CFG_CLKMUX_ST)
901      gpio_set_bits(sc, GPIO_HSSI_TXCLK);
902    else
903      gpio_clr_bits(sc, GPIO_HSSI_TXCLK);
904    gpio_make_output(sc, GPIO_HSSI_TXCLK);
905    }
906  else if (sc->status.card_type == CSID_LMC_HSSIc)
907    {  /* cPCI HSSI rev C has extra features */
908    /* Set TXCLK source. */
909    u_int16_t mii16 = mii_read(sc, 16);
910    mii16 &= ~MII16_HSSI_CLKMUX;
911    mii16 |= (sc->config.tx_clk_src&3)<<13;
912    mii_write(sc, 16, mii16);
913
914    /* cPCI HSSI implements loopback towards the net. */
915    if (sc->config.loop_back == CFG_LOOP_LINE)
916      mii16_set_bits(sc, MII16_HSSI_LOOP);
917    else
918      mii16_clr_bits(sc, MII16_HSSI_LOOP);
919
920    /* Set DTE/DCE mode. */
921    if (sc->config.dte_dce == CFG_DCE)
922      gpio_set_bits(sc, GPIO_HSSI_DCE);
923    else
924      gpio_clr_bits(sc, GPIO_HSSI_DCE);
925    gpio_make_output(sc, GPIO_HSSI_DCE);
926
927    /* Program the synthesized oscillator. */
928    synth_write(sc, &sc->config.synth);
929    }
930  }
931
932static void
933hssi_detach(softc_t *sc)
934  {
935  mii16_clr_bits(sc, MII16_HSSI_TA);
936  led_on(sc, MII16_LED_ALL);
937  }
938
939/* End HSSI card code */
940
941/* Begin DS3 card code */
942
943static struct card t3_card =
944  {
945  .ident    = t3_ident,
946  .watchdog = t3_watchdog,
947  .ioctl    = t3_ioctl,
948  .attach   = t3_attach,
949  .detach   = t3_detach,
950  };
951
952static void
953t3_ident(softc_t *sc)
954  {
955  printf(", TXC03401 rev B");
956  }
957
958static void  /* context: softirq */
959t3_watchdog(softc_t *sc)
960  {
961  u_int16_t CV;
962  u_int8_t CERR, PERR, MERR, FERR, FEBE;
963  u_int8_t ctl1, stat16, feac;
964  u_int16_t mii16;
965
966  sc->status.link_state = STATE_UP;
967
968  /* Read the alarm registers. */
969  ctl1   = framer_read(sc, T3CSR_CTL1);
970  stat16 = framer_read(sc, T3CSR_STAT16);
971  mii16  = mii_read(sc, 16);
972
973  /* Always ignore the RTLOC alarm bit. */
974  stat16 &= ~STAT16_RTLOC;
975
976  /* Software is alive. */
977  led_inv(sc, MII16_DS3_LED_GRN);
978
979  /* Receiving Alarm Indication Signal (AIS). */
980  if (stat16 & STAT16_RAIS) /* receiving ais */
981    led_on(sc, MII16_DS3_LED_BLU);
982  else if (ctl1 & CTL1_TXAIS) /* sending ais */
983    led_inv(sc, MII16_DS3_LED_BLU);
984  else
985    led_off(sc, MII16_DS3_LED_BLU);
986
987  /* Receiving Remote Alarm Indication (RAI). */
988  if (stat16 & STAT16_XERR) /* receiving rai */
989    led_on(sc, MII16_DS3_LED_YEL);
990  else if ((ctl1 & CTL1_XTX) == 0) /* sending rai */
991    led_inv(sc, MII16_DS3_LED_YEL);
992  else
993    led_off(sc, MII16_DS3_LED_YEL);
994
995  /* If certain status bits are set then the link is 'down'. */
996  /* The bad bits are: rxlos rxoof rxais rxidl xerr. */
997  if (stat16 & ~(STAT16_FEAC | STAT16_SEF))
998    sc->status.link_state = STATE_DOWN;
999
1000  /* Declare local Red Alarm if the link is down. */
1001  if (sc->status.link_state == STATE_DOWN)
1002    led_on(sc, MII16_DS3_LED_RED);
1003  else if (sc->loop_timer) /* loopback is active */
1004    led_inv(sc, MII16_DS3_LED_RED);
1005  else
1006    led_off(sc, MII16_DS3_LED_RED);
1007
1008  /* Print latched error bits if they changed. */
1009  if ((sc->config.debug) && ((stat16 & ~STAT16_FEAC) != sc->last_stat16))
1010    {
1011    const char *on = "ON ", *off = "OFF";
1012    printf("%s: RLOS=%s ROOF=%s RAIS=%s RIDL=%s SEF=%s XERR=%s\n",
1013     NAME_UNIT,
1014     (stat16 & STAT16_RLOS) ? on : off,
1015     (stat16 & STAT16_ROOF) ? on : off,
1016     (stat16 & STAT16_RAIS) ? on : off,
1017     (stat16 & STAT16_RIDL) ? on : off,
1018     (stat16 & STAT16_SEF)  ? on : off,
1019     (stat16 & STAT16_XERR) ? on : off);
1020    }
1021
1022  /* Check and print error counters if non-zero. */
1023  CV   = framer_read(sc, T3CSR_CVHI)<<8;
1024  CV  += framer_read(sc, T3CSR_CVLO);
1025  PERR = framer_read(sc, T3CSR_PERR);
1026  CERR = framer_read(sc, T3CSR_CERR);
1027  FERR = framer_read(sc, T3CSR_FERR);
1028  MERR = framer_read(sc, T3CSR_MERR);
1029  FEBE = framer_read(sc, T3CSR_FEBE);
1030
1031  /* CV is invalid during LOS. */
1032  if (stat16 & STAT16_RLOS) CV = 0;
1033  /* CERR & FEBE are invalid in M13 mode */
1034  if (sc->config.format == CFG_FORMAT_T3M13) CERR = FEBE = 0;
1035  /* FEBE is invalid during AIS. */
1036  if (stat16 & STAT16_RAIS) FEBE = 0;
1037  if (sc->config.debug && (CV || PERR || CERR || FERR || MERR || FEBE))
1038    printf("%s: CV=%u PERR=%u CERR=%u FERR=%u MERR=%u FEBE=%u\n",
1039     NAME_UNIT, CV,   PERR,   CERR,   FERR,   MERR,   FEBE);
1040
1041  /* Driver keeps crude link-level error counters (SNMP is better). */
1042  sc->status.cntrs.lcv_errs  += CV;
1043  sc->status.cntrs.par_errs  += PERR;
1044  sc->status.cntrs.cpar_errs += CERR;
1045  sc->status.cntrs.frm_errs  += FERR;
1046  sc->status.cntrs.mfrm_errs += MERR;
1047  sc->status.cntrs.febe_errs += FEBE;
1048
1049  /* Check for FEAC messages (FEAC not defined in M13 mode). */
1050  if (FORMAT_T3CPAR && (stat16 & STAT16_FEAC)) do
1051    {
1052    feac = framer_read(sc, T3CSR_FEAC_STK);
1053    if ((feac & FEAC_STK_VALID)==0) break;
1054    /* Ignore RxFEACs while a far end loopback has been requested. */
1055    if (sc->status.snmp.t3.line & TLOOP_FAR_LINE) continue;
1056    switch (feac & FEAC_STK_FEAC)
1057      {
1058      case T3BOP_LINE_UP:   break;
1059      case T3BOP_LINE_DOWN: break;
1060      case T3BOP_LOOP_DS3:
1061        {
1062        if (sc->last_FEAC == T3BOP_LINE_DOWN)
1063          {
1064          if (sc->config.debug)
1065            printf("%s: Received a 'line loopback deactivate' FEAC msg\n", NAME_UNIT);
1066          mii16_clr_bits(sc, MII16_DS3_LNLBK);
1067          sc->loop_timer = 0;
1068	  }
1069        if (sc->last_FEAC == T3BOP_LINE_UP)
1070          {
1071          if (sc->config.debug)
1072            printf("%s: Received a 'line loopback activate' FEAC msg\n", NAME_UNIT);
1073          mii16_set_bits(sc, MII16_DS3_LNLBK);
1074          sc->loop_timer = 300;
1075	  }
1076        break;
1077        }
1078      case T3BOP_OOF:
1079        {
1080        if (sc->config.debug)
1081          printf("%s: Received a 'far end LOF' FEAC msg\n", NAME_UNIT);
1082        break;
1083	}
1084      case T3BOP_IDLE:
1085        {
1086        if (sc->config.debug)
1087          printf("%s: Received a 'far end IDL' FEAC msg\n", NAME_UNIT);
1088        break;
1089	}
1090      case T3BOP_AIS:
1091        {
1092        if (sc->config.debug)
1093          printf("%s: Received a 'far end AIS' FEAC msg\n", NAME_UNIT);
1094        break;
1095	}
1096      case T3BOP_LOS:
1097        {
1098        if (sc->config.debug)
1099          printf("%s: Received a 'far end LOS' FEAC msg\n", NAME_UNIT);
1100        break;
1101	}
1102      default:
1103        {
1104        if (sc->config.debug)
1105          printf("%s: Received a 'type 0x%02X' FEAC msg\n", NAME_UNIT, feac & FEAC_STK_FEAC);
1106        break;
1107	}
1108      }
1109    sc->last_FEAC = feac & FEAC_STK_FEAC;
1110    } while (feac & FEAC_STK_MORE);
1111  stat16 &= ~STAT16_FEAC;
1112
1113  /* Send Service-Affecting priority FEAC messages */
1114  if (((sc->last_stat16 ^ stat16) & 0xF0) && (FORMAT_T3CPAR))
1115    {
1116    /* Transmit continuous FEACs */
1117    framer_write(sc, T3CSR_CTL14,
1118     framer_read(sc, T3CSR_CTL14) & ~CTL14_FEAC10);
1119    if      (stat16 & STAT16_RLOS)
1120      framer_write(sc, T3CSR_TX_FEAC, 0xC0 + T3BOP_LOS);
1121    else if (stat16 & STAT16_ROOF)
1122      framer_write(sc, T3CSR_TX_FEAC, 0xC0 + T3BOP_OOF);
1123    else if (stat16 & STAT16_RAIS)
1124      framer_write(sc, T3CSR_TX_FEAC, 0xC0 + T3BOP_AIS);
1125    else if (stat16 & STAT16_RIDL)
1126      framer_write(sc, T3CSR_TX_FEAC, 0xC0 + T3BOP_IDLE);
1127    else
1128      framer_write(sc, T3CSR_TX_FEAC, CTL5_EMODE);
1129    }
1130
1131  /* Start sending RAI, Remote Alarm Indication. */
1132  if ((stat16 & STAT16_ROOF) && !(stat16 & STAT16_RLOS) &&
1133   !(sc->last_stat16 & STAT16_ROOF))
1134    framer_write(sc, T3CSR_CTL1, ctl1 &= ~CTL1_XTX);
1135  /* Stop sending RAI, Remote Alarm Indication. */
1136  else if (!(stat16 & STAT16_ROOF) && (sc->last_stat16 & STAT16_ROOF))
1137    framer_write(sc, T3CSR_CTL1, ctl1 |=  CTL1_XTX);
1138
1139  /* Start sending AIS, Alarm Indication Signal */
1140  if ((stat16 & STAT16_RLOS) && !(sc->last_stat16 & STAT16_RLOS))
1141    {
1142    mii16_set_bits(sc, MII16_DS3_FRAME);
1143    framer_write(sc, T3CSR_CTL1, ctl1 |  CTL1_TXAIS);
1144    }
1145  /* Stop sending AIS, Alarm Indication Signal */
1146  else if (!(stat16 & STAT16_RLOS) && (sc->last_stat16 & STAT16_RLOS))
1147    {
1148    mii16_clr_bits(sc, MII16_DS3_FRAME);
1149    framer_write(sc, T3CSR_CTL1, ctl1 & ~CTL1_TXAIS);
1150    }
1151
1152  /* Time out loopback requests. */
1153  if (sc->loop_timer)
1154    if (--sc->loop_timer == 0)
1155      if (mii16 & MII16_DS3_LNLBK)
1156        {
1157        if (sc->config.debug)
1158          printf("%s: Timeout: Loop Down after 300 seconds\n", NAME_UNIT);
1159        mii16_clr_bits(sc, MII16_DS3_LNLBK); /* line loopback off */
1160        }
1161
1162  /* SNMP error counters */
1163  sc->status.snmp.t3.lcv  = CV;
1164  sc->status.snmp.t3.pcv  = PERR;
1165  sc->status.snmp.t3.ccv  = CERR;
1166  sc->status.snmp.t3.febe = FEBE;
1167
1168  /* SNMP Line Status */
1169  sc->status.snmp.t3.line = 0;
1170  if (!(ctl1 & CTL1_XTX))      sc->status.snmp.t3.line |= TLINE_TX_RAI;
1171  if (stat16 & STAT16_XERR)    sc->status.snmp.t3.line |= TLINE_RX_RAI;
1172  if (ctl1   & CTL1_TXAIS)     sc->status.snmp.t3.line |= TLINE_TX_AIS;
1173  if (stat16 & STAT16_RAIS)    sc->status.snmp.t3.line |= TLINE_RX_AIS;
1174  if (stat16 & STAT16_ROOF)    sc->status.snmp.t3.line |= TLINE_LOF;
1175  if (stat16 & STAT16_RLOS)    sc->status.snmp.t3.line |= TLINE_LOS;
1176  if (stat16 & STAT16_SEF)     sc->status.snmp.t3.line |= T3LINE_SEF;
1177
1178  /* SNMP Loopback Status */
1179  sc->status.snmp.t3.loop &= ~TLOOP_FAR_LINE;
1180  if (sc->config.loop_back == CFG_LOOP_TULIP)
1181                               sc->status.snmp.t3.loop |= TLOOP_NEAR_OTHER;
1182  if (ctl1  & CTL1_3LOOP)      sc->status.snmp.t3.loop |= TLOOP_NEAR_INWARD;
1183  if (mii16 & MII16_DS3_TRLBK) sc->status.snmp.t3.loop |= TLOOP_NEAR_OTHER;
1184  if (mii16 & MII16_DS3_LNLBK) sc->status.snmp.t3.loop |= TLOOP_NEAR_LINE;
1185/*if (ctl12 & CTL12_RTPLOOP)   sc->status.snmp.t3.loop |= TLOOP_NEAR_PAYLOAD; */
1186
1187  /* Remember this state until next time. */
1188  sc->last_stat16 = stat16;
1189
1190  /* If an INWARD loopback is in effect, link status is UP */
1191  if (sc->config.loop_back != CFG_LOOP_NONE) /* XXX INWARD ONLY */
1192    sc->status.link_state = STATE_UP;
1193  }
1194
1195static void  /* context: process */
1196t3_send_dbl_feac(softc_t *sc, int feac1, int feac2)
1197  {
1198  u_int8_t tx_feac;
1199  int i;
1200
1201  /* The FEAC transmitter could be sending a continuous */
1202  /*  FEAC msg when told to send a double FEAC message. */
1203  /* So save the current state of the FEAC transmitter. */
1204  tx_feac = framer_read(sc, T3CSR_TX_FEAC);
1205  /* Load second FEAC code and stop FEAC transmitter. */
1206  framer_write(sc, T3CSR_TX_FEAC,  CTL5_EMODE + feac2);
1207  /* FEAC transmitter sends 10 more FEACs and then stops. */
1208  SLEEP(20000); /* sending one FEAC takes 1700 uSecs */
1209  /* Load first FEAC code and start FEAC transmitter. */
1210  framer_write(sc, T3CSR_DBL_FEAC, CTL13_DFEXEC + feac1);
1211  /* Wait for double FEAC sequence to complete -- about 70 ms. */
1212  for (i=0; i<10; i++) /* max delay 100 ms */
1213    if (framer_read(sc, T3CSR_DBL_FEAC) & CTL13_DFEXEC) SLEEP(10000);
1214  /* Flush received FEACS; do not respond to our own loop cmd! */
1215  while (framer_read(sc, T3CSR_FEAC_STK) & FEAC_STK_VALID) DELAY(1);
1216  /* Restore previous state of the FEAC transmitter. */
1217  /* If it was sending a continous FEAC, it will resume. */
1218  framer_write(sc, T3CSR_TX_FEAC, tx_feac);
1219  }
1220
1221static int  /* context: process */
1222t3_ioctl(softc_t *sc, struct ioctl *ioctl)
1223  {
1224  int error = 0;
1225
1226  switch (ioctl->cmd)
1227    {
1228    case IOCTL_SNMP_SEND:  /* set opstatus? */
1229      {
1230      if (sc->config.format != CFG_FORMAT_T3CPAR)
1231        error = EINVAL;
1232      else if (ioctl->data == TSEND_LINE)
1233        {
1234        sc->status.snmp.t3.loop |= TLOOP_FAR_LINE;
1235        t3_send_dbl_feac(sc, T3BOP_LINE_UP, T3BOP_LOOP_DS3);
1236        }
1237      else if (ioctl->data == TSEND_RESET)
1238        {
1239        t3_send_dbl_feac(sc, T3BOP_LINE_DOWN, T3BOP_LOOP_DS3);
1240        sc->status.snmp.t3.loop &= ~TLOOP_FAR_LINE;
1241        }
1242      else
1243        error = EINVAL;
1244      break;
1245      }
1246    case IOCTL_SNMP_LOOP:  /* set opstatus = test? */
1247      {
1248      if (ioctl->data == CFG_LOOP_NONE)
1249        {
1250        mii16_clr_bits(sc, MII16_DS3_FRAME);
1251        mii16_clr_bits(sc, MII16_DS3_TRLBK);
1252        mii16_clr_bits(sc, MII16_DS3_LNLBK);
1253        framer_write(sc, T3CSR_CTL1,
1254         framer_read(sc, T3CSR_CTL1) & ~CTL1_3LOOP);
1255        framer_write(sc, T3CSR_CTL12,
1256         framer_read(sc, T3CSR_CTL12) & ~(CTL12_RTPLOOP | CTL12_RTPLLEN));
1257	}
1258      else if (ioctl->data == CFG_LOOP_LINE)
1259        mii16_set_bits(sc, MII16_DS3_LNLBK);
1260      else if (ioctl->data == CFG_LOOP_OTHER)
1261        mii16_set_bits(sc, MII16_DS3_TRLBK);
1262      else if (ioctl->data == CFG_LOOP_INWARD)
1263        framer_write(sc, T3CSR_CTL1,
1264         framer_read(sc, T3CSR_CTL1) | CTL1_3LOOP);
1265      else if (ioctl->data == CFG_LOOP_DUAL)
1266        {
1267        mii16_set_bits(sc, MII16_DS3_LNLBK);
1268        framer_write(sc, T3CSR_CTL1,
1269         framer_read(sc, T3CSR_CTL1) | CTL1_3LOOP);
1270	}
1271      else if (ioctl->data == CFG_LOOP_PAYLOAD)
1272        {
1273        mii16_set_bits(sc, MII16_DS3_FRAME);
1274        framer_write(sc, T3CSR_CTL12,
1275         framer_read(sc, T3CSR_CTL12) |  CTL12_RTPLOOP);
1276        framer_write(sc, T3CSR_CTL12,
1277         framer_read(sc, T3CSR_CTL12) |  CTL12_RTPLLEN);
1278        DELAY(25); /* at least two frames (22 uS) */
1279        framer_write(sc, T3CSR_CTL12,
1280         framer_read(sc, T3CSR_CTL12) & ~CTL12_RTPLLEN);
1281	}
1282      else
1283        error = EINVAL;
1284      break;
1285      }
1286    case IOCTL_SET_STATUS:
1287      {
1288#if 0
1289      if (ioctl->data)
1290        framer_write(sc, T3CSR_CTL1,
1291         framer_read(sc, T3CSR_CTL1) & ~CTL1_TXIDL);
1292      else /* off */
1293        framer_write(sc, T3CSR_CTL1,
1294         framer_read(sc, T3CSR_CTL1) |  CTL1_TXIDL);
1295#endif
1296      break;
1297      }
1298    default:
1299      error = EINVAL;
1300      break;
1301    }
1302
1303  return error;
1304  }
1305
1306/* Must not sleep. */
1307static void
1308t3_attach(softc_t *sc, struct config *config)
1309  {
1310  int i;
1311  u_int8_t ctl1;
1312
1313  if (config == NULL) /* startup config */
1314    {
1315    sc->status.card_type  = CSID_LMC_T3;
1316    sc->config.crc_len    = CFG_CRC_16;
1317    sc->config.loop_back  = CFG_LOOP_NONE;
1318    sc->config.format     = CFG_FORMAT_T3CPAR;
1319    sc->config.cable_len  = 10; /* meters */
1320    sc->config.scrambler  = CFG_SCRAM_DL_KEN;
1321    sc->config.tx_clk_src = CFG_CLKMUX_INT;
1322
1323    /* Center the VCXO -- get within 20 PPM of 44736000. */
1324    dac_write(sc, 0x9002); /* set Vref = 2.048 volts */
1325    dac_write(sc, 2048); /* range is 0..4095 */
1326    }
1327  else if (config != &sc->config) /* change config */
1328    {
1329    if ((sc->config.crc_len    == config->crc_len)   &&
1330        (sc->config.loop_back  == config->loop_back) &&
1331        (sc->config.format     == config->format)    &&
1332        (sc->config.cable_len  == config->cable_len) &&
1333        (sc->config.scrambler  == config->scrambler) &&
1334        (sc->config.tx_clk_src == config->tx_clk_src))
1335      return; /* nothing changed */
1336    sc->config.crc_len    = config->crc_len;
1337    sc->config.loop_back  = config->loop_back;
1338    sc->config.format     = config->format;
1339    sc->config.cable_len  = config->cable_len;
1340    sc->config.scrambler  = config->scrambler;
1341    sc->config.tx_clk_src = config->tx_clk_src;
1342    }
1343
1344  /* Set cable length. */
1345  if (sc->config.cable_len > 30)
1346    mii16_clr_bits(sc, MII16_DS3_ZERO);
1347  else
1348    mii16_set_bits(sc, MII16_DS3_ZERO);
1349
1350  /* Set payload scrambler polynomial. */
1351  if (sc->config.scrambler == CFG_SCRAM_LARS)
1352    mii16_set_bits(sc, MII16_DS3_POLY);
1353  else
1354    mii16_clr_bits(sc, MII16_DS3_POLY);
1355
1356  /* Set payload scrambler on/off. */
1357  if (sc->config.scrambler == CFG_SCRAM_OFF)
1358    mii16_clr_bits(sc, MII16_DS3_SCRAM);
1359  else
1360    mii16_set_bits(sc, MII16_DS3_SCRAM);
1361
1362  /* Set CRC length. */
1363  if (sc->config.crc_len == CFG_CRC_32)
1364    mii16_set_bits(sc, MII16_DS3_CRC32);
1365  else
1366    mii16_clr_bits(sc, MII16_DS3_CRC32);
1367
1368  /* Loopback towards host thru the line interface. */
1369  if (sc->config.loop_back == CFG_LOOP_OTHER)
1370    mii16_set_bits(sc, MII16_DS3_TRLBK);
1371  else
1372    mii16_clr_bits(sc, MII16_DS3_TRLBK);
1373
1374  /* Loopback towards network thru the line interface. */
1375  if (sc->config.loop_back == CFG_LOOP_LINE)
1376    mii16_set_bits(sc, MII16_DS3_LNLBK);
1377  else if (sc->config.loop_back == CFG_LOOP_DUAL)
1378    mii16_set_bits(sc, MII16_DS3_LNLBK);
1379  else
1380    mii16_clr_bits(sc, MII16_DS3_LNLBK);
1381
1382  /* Configure T3 framer chip; write EVERY writeable register. */
1383  ctl1 = CTL1_SER | CTL1_XTX;
1384  if (sc->config.format    == CFG_FORMAT_T3M13) ctl1 |= CTL1_M13MODE;
1385  if (sc->config.loop_back == CFG_LOOP_INWARD)  ctl1 |= CTL1_3LOOP;
1386  if (sc->config.loop_back == CFG_LOOP_DUAL)    ctl1 |= CTL1_3LOOP;
1387  framer_write(sc, T3CSR_CTL1,     ctl1);
1388  framer_write(sc, T3CSR_TX_FEAC,  CTL5_EMODE);
1389  framer_write(sc, T3CSR_CTL8,     CTL8_FBEC);
1390  framer_write(sc, T3CSR_CTL12,    CTL12_DLCB1 | CTL12_C21 | CTL12_MCB1);
1391  framer_write(sc, T3CSR_DBL_FEAC, 0);
1392  framer_write(sc, T3CSR_CTL14,    CTL14_RGCEN | CTL14_TGCEN);
1393  framer_write(sc, T3CSR_INTEN,    0);
1394  framer_write(sc, T3CSR_CTL20,    CTL20_CVEN);
1395
1396  /* Clear error counters and latched error bits */
1397  /*  that may have happened while initializing. */
1398  for (i=0; i<21; i++) framer_read(sc, i);
1399  }
1400
1401static void
1402t3_detach(softc_t *sc)
1403  {
1404  framer_write(sc, T3CSR_CTL1,
1405   framer_read(sc, T3CSR_CTL1) |  CTL1_TXIDL);
1406  led_on(sc, MII16_LED_ALL);
1407  }
1408
1409/* End DS3 card code */
1410
1411/* Begin SSI card code */
1412
1413static struct card ssi_card =
1414  {
1415  .ident    = ssi_ident,
1416  .watchdog = ssi_watchdog,
1417  .ioctl    = ssi_ioctl,
1418  .attach   = ssi_attach,
1419  .detach   = ssi_detach,
1420  };
1421
1422static void
1423ssi_ident(softc_t *sc)
1424  {
1425  printf(", LTC1343/44");
1426  }
1427
1428static void  /* context: softirq */
1429ssi_watchdog(softc_t *sc)
1430  {
1431  u_int16_t cable;
1432  u_int16_t mii16 = mii_read(sc, 16) & MII16_SSI_MODEM;
1433
1434  sc->status.link_state = STATE_UP;
1435
1436  /* Software is alive. */
1437  led_inv(sc, MII16_SSI_LED_UL);
1438
1439  /* Check the transmit clock. */
1440  if (sc->status.tx_speed == 0)
1441    {
1442    led_on(sc, MII16_SSI_LED_UR);
1443    sc->status.link_state = STATE_DOWN;
1444    }
1445  else
1446    led_off(sc, MII16_SSI_LED_UR);
1447
1448  /* Check the external cable. */
1449  cable = mii_read(sc, 17);
1450  cable = cable &  MII17_SSI_CABLE_MASK;
1451  cable = cable >> MII17_SSI_CABLE_SHIFT;
1452  if (cable == 7)
1453    {
1454    led_off(sc, MII16_SSI_LED_LL); /* no cable */
1455    sc->status.link_state = STATE_DOWN;
1456    }
1457  else
1458    led_on(sc, MII16_SSI_LED_LL);
1459
1460  /* The unit at the other end of the cable is ready if: */
1461  /*  DTE mode and DCD pin is asserted */
1462  /*  DCE mode and DSR pin is asserted */
1463  if (((sc->config.dte_dce == CFG_DTE) && !(mii16 & MII16_SSI_DCD)) ||
1464      ((sc->config.dte_dce == CFG_DCE) && !(mii16 & MII16_SSI_DSR)))
1465    {
1466    led_off(sc, MII16_SSI_LED_LR);
1467    sc->status.link_state = STATE_DOWN;
1468    }
1469  else
1470    led_on(sc, MII16_SSI_LED_LR);
1471
1472  if (sc->config.debug && (cable != sc->status.cable_type))
1473    printf("%s: SSI cable type changed to '%s'\n",
1474     NAME_UNIT, ssi_cables[cable]);
1475  sc->status.cable_type = cable;
1476
1477  /* Print the modem control signals if they changed. */
1478  if ((sc->config.debug) && (mii16 != sc->last_mii16))
1479    {
1480    const char *on = "ON ", *off = "OFF";
1481    printf("%s: DTR=%s DSR=%s RTS=%s CTS=%s DCD=%s RI=%s LL=%s RL=%s TM=%s\n",
1482     NAME_UNIT,
1483     (mii16 & MII16_SSI_DTR) ? on : off,
1484     (mii16 & MII16_SSI_DSR) ? on : off,
1485     (mii16 & MII16_SSI_RTS) ? on : off,
1486     (mii16 & MII16_SSI_CTS) ? on : off,
1487     (mii16 & MII16_SSI_DCD) ? on : off,
1488     (mii16 & MII16_SSI_RI)  ? on : off,
1489     (mii16 & MII16_SSI_LL)  ? on : off,
1490     (mii16 & MII16_SSI_RL)  ? on : off,
1491     (mii16 & MII16_SSI_TM)  ? on : off);
1492    }
1493
1494  /* SNMP one-second report */
1495  sc->status.snmp.ssi.sigs = mii16 & MII16_SSI_MODEM;
1496
1497  /* Remember this state until next time. */
1498  sc->last_mii16 = mii16;
1499
1500  /* If a loop back is in effect, link status is UP */
1501  if (sc->config.loop_back != CFG_LOOP_NONE)
1502    sc->status.link_state = STATE_UP;
1503  }
1504
1505static int  /* context: process */
1506ssi_ioctl(softc_t *sc, struct ioctl *ioctl)
1507  {
1508  int error = 0;
1509
1510  if (ioctl->cmd == IOCTL_SNMP_SIGS)
1511    {
1512    u_int16_t mii16 = mii_read(sc, 16);
1513    mii16 &= ~MII16_SSI_MODEM;
1514    mii16 |= (MII16_SSI_MODEM & ioctl->data);
1515    mii_write(sc, 16, mii16);
1516    }
1517  else if (ioctl->cmd == IOCTL_SET_STATUS)
1518    {
1519    if (ioctl->data)
1520      mii16_set_bits(sc, (MII16_SSI_DTR | MII16_SSI_RTS | MII16_SSI_DCD));
1521    else
1522      mii16_clr_bits(sc, (MII16_SSI_DTR | MII16_SSI_RTS | MII16_SSI_DCD));
1523    }
1524  else
1525    error = EINVAL;
1526
1527  return error;
1528  }
1529
1530/* Must not sleep. */
1531static void
1532ssi_attach(softc_t *sc, struct config *config)
1533  {
1534  if (config == NULL) /* startup config */
1535    {
1536    sc->status.card_type  = CSID_LMC_SSI;
1537    sc->config.crc_len    = CFG_CRC_16;
1538    sc->config.loop_back  = CFG_LOOP_NONE;
1539    sc->config.tx_clk_src = CFG_CLKMUX_ST;
1540    sc->config.dte_dce    = CFG_DTE;
1541    sc->config.synth.n    = 51; /* 1.536 MHz */
1542    sc->config.synth.m    = 83;
1543    sc->config.synth.v    =  1;
1544    sc->config.synth.x    =  1;
1545    sc->config.synth.r    =  1;
1546    sc->config.synth.prescale = 4;
1547    }
1548  else if (config != &sc->config) /* change config */
1549    {
1550    u_int32_t *old_synth = (u_int32_t *)&sc->config.synth;
1551    u_int32_t *new_synth = (u_int32_t *)&config->synth;
1552    if ((sc->config.crc_len    == config->crc_len)    &&
1553        (sc->config.loop_back  == config->loop_back)  &&
1554        (sc->config.tx_clk_src == config->tx_clk_src) &&
1555        (sc->config.dte_dce    == config->dte_dce)    &&
1556        (*old_synth            == *new_synth))
1557      return; /* nothing changed */
1558    sc->config.crc_len    = config->crc_len;
1559    sc->config.loop_back  = config->loop_back;
1560    sc->config.tx_clk_src = config->tx_clk_src;
1561    sc->config.dte_dce    = config->dte_dce;
1562    *old_synth            = *new_synth;
1563    }
1564
1565  /* Disable the TX clock driver while programming the oscillator. */
1566  gpio_clr_bits(sc, GPIO_SSI_DCE);
1567  gpio_make_output(sc, GPIO_SSI_DCE);
1568
1569  /* Program the synthesized oscillator. */
1570  synth_write(sc, &sc->config.synth);
1571
1572  /* Set DTE/DCE mode. */
1573  /* If DTE mode then DCD & TXC are received. */
1574  /* If DCE mode then DCD & TXC are driven. */
1575  /* Boards with MII rev=4.0 do not drive DCD. */
1576  if (sc->config.dte_dce == CFG_DCE)
1577    gpio_set_bits(sc, GPIO_SSI_DCE);
1578  else
1579    gpio_clr_bits(sc, GPIO_SSI_DCE);
1580  gpio_make_output(sc, GPIO_SSI_DCE);
1581
1582  /* Set CRC length. */
1583  if (sc->config.crc_len == CFG_CRC_32)
1584    mii16_set_bits(sc, MII16_SSI_CRC32);
1585  else
1586    mii16_clr_bits(sc, MII16_SSI_CRC32);
1587
1588  /* Loop towards host thru cable drivers and receivers. */
1589  /* Asserts DCD at the far end of a null modem cable. */
1590  if (sc->config.loop_back == CFG_LOOP_PINS)
1591    mii16_set_bits(sc, MII16_SSI_LOOP);
1592  else
1593    mii16_clr_bits(sc, MII16_SSI_LOOP);
1594
1595  /* Assert pin LL in modem conn: ask modem for local loop. */
1596  /* Asserts TM at the far end of a null modem cable. */
1597  if (sc->config.loop_back == CFG_LOOP_LL)
1598    mii16_set_bits(sc, MII16_SSI_LL);
1599  else
1600    mii16_clr_bits(sc, MII16_SSI_LL);
1601
1602  /* Assert pin RL in modem conn: ask modem for remote loop. */
1603  if (sc->config.loop_back == CFG_LOOP_RL)
1604    mii16_set_bits(sc, MII16_SSI_RL);
1605  else
1606    mii16_clr_bits(sc, MII16_SSI_RL);
1607  }
1608
1609static void
1610ssi_detach(softc_t *sc)
1611  {
1612  mii16_clr_bits(sc, (MII16_SSI_DTR | MII16_SSI_RTS | MII16_SSI_DCD));
1613  led_on(sc, MII16_LED_ALL);
1614  }
1615
1616/* End SSI card code */
1617
1618/* Begin T1E1 card code */
1619
1620static struct card t1_card =
1621  {
1622  .ident    = t1_ident,
1623  .watchdog = t1_watchdog,
1624  .ioctl    = t1_ioctl,
1625  .attach   = t1_attach,
1626  .detach   = t1_detach,
1627  };
1628
1629static void
1630t1_ident(softc_t *sc)
1631  {
1632  printf(", Bt837%x rev %x",
1633   framer_read(sc, Bt8370_DID)>>4,
1634   framer_read(sc, Bt8370_DID)&0x0F);
1635  }
1636
1637static void  /* context: softirq */
1638t1_watchdog(softc_t *sc)
1639  {
1640  u_int16_t LCV = 0, FERR = 0, CRC = 0, FEBE = 0;
1641  u_int8_t alm1, alm3, loop, isr0;
1642  int i;
1643
1644  sc->status.link_state = STATE_UP;
1645
1646  /* Read the alarm registers */
1647  alm1 = framer_read(sc, Bt8370_ALM1);
1648  alm3 = framer_read(sc, Bt8370_ALM3);
1649  loop = framer_read(sc, Bt8370_LOOP);
1650  isr0 = framer_read(sc, Bt8370_ISR0);
1651
1652  /* Always ignore the SIGFRZ alarm bit, */
1653  alm1 &= ~ALM1_SIGFRZ;
1654  if (FORMAT_T1ANY)  /* ignore RYEL in T1 modes */
1655    alm1 &= ~ALM1_RYEL;
1656  else if (FORMAT_E1NONE) /* ignore all alarms except LOS */
1657    alm1 &= ALM1_RLOS;
1658
1659  /* Software is alive. */
1660  led_inv(sc, MII16_T1_LED_GRN);
1661
1662  /* Receiving Alarm Indication Signal (AIS). */
1663  if      (alm1 & ALM1_RAIS) /* receiving ais */
1664    led_on(sc, MII16_T1_LED_BLU);
1665  else if (alm1 & ALM1_RLOS) /* sending ais */
1666    led_inv(sc, MII16_T1_LED_BLU);
1667  else
1668    led_off(sc, MII16_T1_LED_BLU);
1669
1670  /* Receiving Remote Alarm Indication (RAI). */
1671  if (alm1 & (ALM1_RMYEL | ALM1_RYEL)) /* receiving rai */
1672    led_on(sc, MII16_T1_LED_YEL);
1673  else if (alm1 & ALM1_RLOF) /* sending rai */
1674    led_inv(sc, MII16_T1_LED_YEL);
1675  else
1676    led_off(sc, MII16_T1_LED_YEL);
1677
1678  /* If any alarm bits are set then the link is 'down'. */
1679  /* The bad bits are: rmyel ryel rais ralos rlos rlof. */
1680  /* Some alarm bits have been masked by this point. */
1681  if (alm1) sc->status.link_state = STATE_DOWN;
1682
1683  /* Declare local Red Alarm if the link is down. */
1684  if (sc->status.link_state == STATE_DOWN)
1685    led_on(sc, MII16_T1_LED_RED);
1686  else if (sc->loop_timer) /* loopback is active */
1687    led_inv(sc, MII16_T1_LED_RED);
1688  else
1689    led_off(sc, MII16_T1_LED_RED);
1690
1691  /* Print latched error bits if they changed. */
1692  if ((sc->config.debug) && (alm1 != sc->last_alm1))
1693    {
1694    const char *on = "ON ", *off = "OFF";
1695    printf("%s: RLOF=%s RLOS=%s RALOS=%s RAIS=%s RYEL=%s RMYEL=%s\n",
1696     NAME_UNIT,
1697     (alm1 & ALM1_RLOF)  ? on : off,
1698     (alm1 & ALM1_RLOS)  ? on : off,
1699     (alm1 & ALM1_RALOS) ? on : off,
1700     (alm1 & ALM1_RAIS)  ? on : off,
1701     (alm1 & ALM1_RYEL)  ? on : off,
1702     (alm1 & ALM1_RMYEL) ? on : off);
1703    }
1704
1705  /* Check and print error counters if non-zero. */
1706  LCV = framer_read(sc, Bt8370_LCV_LO)  +
1707        (framer_read(sc, Bt8370_LCV_HI)<<8);
1708  if (!FORMAT_E1NONE)
1709    FERR = framer_read(sc, Bt8370_FERR_LO) +
1710          (framer_read(sc, Bt8370_FERR_HI)<<8);
1711  if (FORMAT_E1CRC || FORMAT_T1ESF)
1712    CRC  = framer_read(sc, Bt8370_CRC_LO)  +
1713          (framer_read(sc, Bt8370_CRC_HI)<<8);
1714  if (FORMAT_E1CRC)
1715    FEBE = framer_read(sc, Bt8370_FEBE_LO) +
1716          (framer_read(sc, Bt8370_FEBE_HI)<<8);
1717  /* Only LCV is valid if Out-Of-Frame */
1718  if (FORMAT_E1NONE) FERR = CRC = FEBE = 0;
1719  if ((sc->config.debug) && (LCV || FERR || CRC || FEBE))
1720    printf("%s: LCV=%u FERR=%u CRC=%u FEBE=%u\n",
1721     NAME_UNIT, LCV,   FERR,   CRC,   FEBE);
1722
1723  /* Driver keeps crude link-level error counters (SNMP is better). */
1724  sc->status.cntrs.lcv_errs  += LCV;
1725  sc->status.cntrs.frm_errs  += FERR;
1726  sc->status.cntrs.crc_errs  += CRC;
1727  sc->status.cntrs.febe_errs += FEBE;
1728
1729  /* Check for BOP messages in the ESF Facility Data Link. */
1730  if ((FORMAT_T1ESF) && (framer_read(sc, Bt8370_ISR1) & 0x80))
1731    {
1732    u_int8_t bop_code = framer_read(sc, Bt8370_RBOP) & 0x3F;
1733
1734    switch (bop_code)
1735      {
1736      case T1BOP_OOF:
1737        {
1738        if ((sc->config.debug) && !(sc->last_alm1 & ALM1_RMYEL))
1739          printf("%s: Receiving a 'yellow alarm' BOP msg\n", NAME_UNIT);
1740        break;
1741        }
1742      case T1BOP_LINE_UP:
1743        {
1744        if (sc->config.debug)
1745          printf("%s: Received a 'line loopback activate' BOP msg\n", NAME_UNIT);
1746        framer_write(sc, Bt8370_LOOP, LOOP_LINE);
1747        sc->loop_timer = 305;
1748        break;
1749        }
1750      case T1BOP_LINE_DOWN:
1751        {
1752        if (sc->config.debug)
1753          printf("%s: Received a 'line loopback deactivate' BOP msg\n", NAME_UNIT);
1754        framer_write(sc, Bt8370_LOOP,
1755         framer_read(sc, Bt8370_LOOP) & ~LOOP_LINE);
1756        sc->loop_timer = 0;
1757        break;
1758        }
1759      case T1BOP_PAY_UP:
1760        {
1761        if (sc->config.debug)
1762          printf("%s: Received a 'payload loopback activate' BOP msg\n", NAME_UNIT);
1763        framer_write(sc, Bt8370_LOOP, LOOP_PAYLOAD);
1764        sc->loop_timer = 305;
1765        break;
1766        }
1767      case T1BOP_PAY_DOWN:
1768        {
1769        if (sc->config.debug)
1770          printf("%s: Received a 'payload loopback deactivate' BOP msg\n", NAME_UNIT);
1771        framer_write(sc, Bt8370_LOOP,
1772         framer_read(sc, Bt8370_LOOP) & ~LOOP_PAYLOAD);
1773        sc->loop_timer = 0;
1774        break;
1775        }
1776      default:
1777        {
1778        if (sc->config.debug)
1779          printf("%s: Received a type 0x%02X BOP msg\n", NAME_UNIT, bop_code);
1780        break;
1781        }
1782      }
1783    }
1784
1785  /* Check for HDLC pkts in the ESF Facility Data Link. */
1786  if ((FORMAT_T1ESF) && (framer_read(sc, Bt8370_ISR2) & 0x70))
1787    {
1788    /* while (not fifo-empty && not start-of-msg) flush fifo */
1789    while ((framer_read(sc, Bt8370_RDL1_STAT) & 0x0C)==0)
1790      framer_read(sc, Bt8370_RDL1);
1791    /* If (not fifo-empty), then begin processing fifo contents. */
1792    if ((framer_read(sc, Bt8370_RDL1_STAT) & 0x0C) == 0x08)
1793      {
1794      u_int8_t msg[64];
1795      u_int8_t stat = framer_read(sc, Bt8370_RDL1);
1796      sc->status.cntrs.fdl_pkts++;
1797      for (i=0; i<(stat & 0x3F); i++)
1798        msg[i] = framer_read(sc, Bt8370_RDL1);
1799      /* Is this FDL message a T1.403 performance report? */
1800      if (((stat & 0x3F)==11) &&
1801          ((msg[0]==0x38) || (msg[0]==0x3A)) &&
1802           (msg[1]==1)   &&  (msg[2]==3))
1803        /* Copy 4 PRs from FDL pkt to SNMP struct. */
1804        memcpy(sc->status.snmp.t1.prm, msg+3, 8);
1805      }
1806    }
1807
1808  /* Check for inband loop up/down commands. */
1809  if (FORMAT_T1ANY)
1810    {
1811    u_int8_t isr6   = framer_read(sc, Bt8370_ISR6);
1812    u_int8_t alarm2 = framer_read(sc, Bt8370_ALM2);
1813    u_int8_t tlb    = framer_read(sc, Bt8370_TLB);
1814
1815    /* Inband Code == Loop Up && On Transition && Inband Tx Inactive */
1816    if ((isr6 & 0x40) && (alarm2 & 0x40) && !(tlb & 1))
1817      { /* CSU loop up is 10000 10000 ... */
1818      if (sc->config.debug)
1819        printf("%s: Received a 'CSU Loop Up' inband msg\n", NAME_UNIT);
1820      framer_write(sc, Bt8370_LOOP, LOOP_LINE); /* Loop up */
1821      sc->loop_timer = 305;
1822      }
1823    /* Inband Code == Loop Down && On Transition && Inband Tx Inactive */
1824    if ((isr6 & 0x80) && (alarm2 & 0x80) && !(tlb & 1))
1825      { /* CSU loop down is 100 100 100 ... */
1826      if (sc->config.debug)
1827        printf("%s: Received a 'CSU Loop Down' inband msg\n", NAME_UNIT);
1828      framer_write(sc, Bt8370_LOOP,
1829       framer_read(sc, Bt8370_LOOP) & ~LOOP_LINE); /* loop down */
1830      sc->loop_timer = 0;
1831      }
1832    }
1833
1834  /* Manually send Yellow Alarm BOP msgs. */
1835  if (FORMAT_T1ESF)
1836    {
1837    u_int8_t isr7 = framer_read(sc, Bt8370_ISR7);
1838
1839    if ((isr7 & 0x02) && (alm1 & 0x02)) /* RLOF on-transition */
1840      { /* Start sending continuous Yellow Alarm BOP messages. */
1841      framer_write(sc, Bt8370_BOP,  RBOP_25 | TBOP_CONT);
1842      framer_write(sc, Bt8370_TBOP, 0x00); /* send BOP; order matters */
1843      }
1844    else if ((isr7 & 0x02) && !(alm1 & 0x02)) /* RLOF off-transition */
1845      { /* Stop sending continuous Yellow Alarm BOP messages. */
1846      framer_write(sc, Bt8370_BOP,  RBOP_25 | TBOP_OFF);
1847      }
1848    }
1849
1850  /* Time out loopback requests. */
1851  if (sc->loop_timer)
1852    if (--sc->loop_timer == 0)
1853      if (loop)
1854        {
1855        if (sc->config.debug)
1856          printf("%s: Timeout: Loop Down after 300 seconds\n", NAME_UNIT);
1857        framer_write(sc, Bt8370_LOOP, loop & ~(LOOP_PAYLOAD | LOOP_LINE));
1858        }
1859
1860  /* RX Test Pattern status */
1861  if ((sc->config.debug) && (isr0 & 0x10))
1862    printf("%s: RX Test Pattern Sync\n", NAME_UNIT);
1863
1864  /* SNMP Error Counters */
1865  sc->status.snmp.t1.lcv  = LCV;
1866  sc->status.snmp.t1.fe   = FERR;
1867  sc->status.snmp.t1.crc  = CRC;
1868  sc->status.snmp.t1.febe = FEBE;
1869
1870  /* SNMP Line Status */
1871  sc->status.snmp.t1.line = 0;
1872  if  (alm1 & ALM1_RMYEL)  sc->status.snmp.t1.line |= TLINE_RX_RAI;
1873  if  (alm1 & ALM1_RYEL)   sc->status.snmp.t1.line |= TLINE_RX_RAI;
1874  if  (alm1 & ALM1_RLOF)   sc->status.snmp.t1.line |= TLINE_TX_RAI;
1875  if  (alm1 & ALM1_RAIS)   sc->status.snmp.t1.line |= TLINE_RX_AIS;
1876  if  (alm1 & ALM1_RLOS)   sc->status.snmp.t1.line |= TLINE_TX_AIS;
1877  if  (alm1 & ALM1_RLOF)   sc->status.snmp.t1.line |= TLINE_LOF;
1878  if  (alm1 & ALM1_RLOS)   sc->status.snmp.t1.line |= TLINE_LOS;
1879  if  (alm3 & ALM3_RMAIS)  sc->status.snmp.t1.line |= T1LINE_RX_TS16_AIS;
1880  if  (alm3 & ALM3_SRED)   sc->status.snmp.t1.line |= T1LINE_TX_TS16_LOMF;
1881  if  (alm3 & ALM3_SEF)    sc->status.snmp.t1.line |= T1LINE_SEF;
1882  if  (isr0 & 0x10)        sc->status.snmp.t1.line |= T1LINE_RX_TEST;
1883  if ((alm1 & ALM1_RMYEL) && (FORMAT_E1CAS))
1884                           sc->status.snmp.t1.line |= T1LINE_RX_TS16_LOMF;
1885
1886  /* SNMP Loopback Status */
1887  sc->status.snmp.t1.loop &= ~(TLOOP_FAR_LINE | TLOOP_FAR_PAYLOAD);
1888  if (sc->config.loop_back == CFG_LOOP_TULIP)
1889                           sc->status.snmp.t1.loop |= TLOOP_NEAR_OTHER;
1890  if (loop & LOOP_PAYLOAD) sc->status.snmp.t1.loop |= TLOOP_NEAR_PAYLOAD;
1891  if (loop & LOOP_LINE)    sc->status.snmp.t1.loop |= TLOOP_NEAR_LINE;
1892  if (loop & LOOP_ANALOG)  sc->status.snmp.t1.loop |= TLOOP_NEAR_OTHER;
1893  if (loop & LOOP_FRAMER)  sc->status.snmp.t1.loop |= TLOOP_NEAR_INWARD;
1894
1895  /* Remember this state until next time. */
1896  sc->last_alm1 = alm1;
1897
1898  /* If an INWARD loopback is in effect, link status is UP */
1899  if (sc->config.loop_back != CFG_LOOP_NONE) /* XXX INWARD ONLY */
1900    sc->status.link_state = STATE_UP;
1901  }
1902
1903static void  /* context: process */
1904t1_send_bop(softc_t *sc, int bop_code)
1905  {
1906  u_int8_t bop;
1907  int i;
1908
1909  /* The BOP transmitter could be sending a continuous */
1910  /*  BOP msg when told to send this BOP_25 message. */
1911  /* So save and restore the state of the BOP machine. */
1912  bop = framer_read(sc, Bt8370_BOP);
1913  framer_write(sc, Bt8370_BOP, RBOP_OFF | TBOP_OFF);
1914  for (i=0; i<40; i++) /* max delay 400 ms. */
1915    if (framer_read(sc, Bt8370_BOP_STAT) & 0x80) SLEEP(10000);
1916  /* send 25 repetitions of bop_code */
1917  framer_write(sc, Bt8370_BOP, RBOP_OFF | TBOP_25);
1918  framer_write(sc, Bt8370_TBOP, bop_code); /* order matters */
1919  /* wait for tx to stop */
1920  for (i=0; i<40; i++) /* max delay 400 ms. */
1921    if (framer_read(sc, Bt8370_BOP_STAT) & 0x80) SLEEP(10000);
1922  /* Restore previous state of the BOP machine. */
1923  framer_write(sc, Bt8370_BOP, bop);
1924  }
1925
1926static int  /* context: process */
1927t1_ioctl(softc_t *sc, struct ioctl *ioctl)
1928  {
1929  int error = 0;
1930
1931  switch (ioctl->cmd)
1932    {
1933    case IOCTL_SNMP_SEND:  /* set opstatus? */
1934      {
1935      switch (ioctl->data)
1936        {
1937        case TSEND_NORMAL:
1938          {
1939          framer_write(sc, Bt8370_TPATT, 0x00); /* tx pattern generator off */
1940          framer_write(sc, Bt8370_RPATT, 0x00); /* rx pattern detector off */
1941          framer_write(sc, Bt8370_TLB,   0x00); /* tx inband generator off */
1942          break;
1943	  }
1944        case TSEND_LINE:
1945          {
1946          if (FORMAT_T1ESF)
1947            t1_send_bop(sc, T1BOP_LINE_UP);
1948          else if (FORMAT_T1SF)
1949            {
1950            framer_write(sc, Bt8370_LBP, 0x08); /* 10000 10000 ... */
1951            framer_write(sc, Bt8370_TLB, 0x05); /* 5 bits, framed, start */
1952	    }
1953          sc->status.snmp.t1.loop |= TLOOP_FAR_LINE;
1954          break;
1955	  }
1956        case TSEND_PAYLOAD:
1957          {
1958          t1_send_bop(sc, T1BOP_PAY_UP);
1959          sc->status.snmp.t1.loop |= TLOOP_FAR_PAYLOAD;
1960          break;
1961	  }
1962        case TSEND_RESET:
1963          {
1964          if (sc->status.snmp.t1.loop == TLOOP_FAR_LINE)
1965            {
1966            if (FORMAT_T1ESF)
1967              t1_send_bop(sc, T1BOP_LINE_DOWN);
1968            else if (FORMAT_T1SF)
1969              {
1970              framer_write(sc, Bt8370_LBP, 0x24); /* 100100 100100 ... */
1971              framer_write(sc, Bt8370_TLB, 0x09); /* 6 bits, framed, start */
1972	      }
1973            sc->status.snmp.t1.loop &= ~TLOOP_FAR_LINE;
1974	    }
1975          if (sc->status.snmp.t1.loop == TLOOP_FAR_PAYLOAD)
1976            {
1977            t1_send_bop(sc, T1BOP_PAY_DOWN);
1978            sc->status.snmp.t1.loop &= ~TLOOP_FAR_PAYLOAD;
1979	    }
1980          break;
1981	  }
1982        case TSEND_QRS:
1983          {
1984          framer_write(sc, Bt8370_TPATT, 0x1E); /* framed QRSS */
1985          break;
1986	  }
1987        default:
1988          {
1989          error = EINVAL;
1990          break;
1991	  }
1992	}
1993      break;
1994      }
1995    case IOCTL_SNMP_LOOP:  /* set opstatus = test? */
1996      {
1997      u_int8_t new_loop = 0;
1998
1999      if      (ioctl->data == CFG_LOOP_NONE)
2000        new_loop = 0;
2001      else if (ioctl->data == CFG_LOOP_PAYLOAD)
2002        new_loop = LOOP_PAYLOAD;
2003      else if (ioctl->data == CFG_LOOP_LINE)
2004        new_loop = LOOP_LINE;
2005      else if (ioctl->data == CFG_LOOP_OTHER)
2006        new_loop = LOOP_ANALOG;
2007      else if (ioctl->data == CFG_LOOP_INWARD)
2008        new_loop = LOOP_FRAMER;
2009      else if (ioctl->data == CFG_LOOP_DUAL)
2010        new_loop = LOOP_DUAL;
2011      else
2012        error = EINVAL;
2013      if (!error)
2014        {
2015        framer_write(sc, Bt8370_LOOP, new_loop);
2016        sc->config.loop_back = ioctl->data;
2017	}
2018      break;
2019      }
2020    case IOCTL_SET_STATUS:
2021      {
2022#if 0
2023      if (ioctl->data)
2024        mii16_set_bits(sc, MII16_T1_XOE);
2025      else
2026        mii16_clr_bits(sc, MII16_T1_XOE);
2027#endif
2028      break;
2029      }
2030    default:
2031      error = EINVAL;
2032      break;
2033    }
2034
2035  return error;
2036  }
2037
2038/* Must not sleep. */
2039static void
2040t1_attach(softc_t *sc, struct config *config)
2041  {
2042  int i;
2043  u_int8_t pulse, lbo, gain;
2044
2045  if (config == NULL) /* startup config */
2046    {
2047    /* Disable transmitter output drivers. */
2048    mii16_clr_bits(sc, MII16_T1_XOE);
2049    /* Bt8370 occasionally powers up in a loopback mode. */
2050    /* Data sheet says zero LOOP reg and do a sw-reset. */
2051    framer_write(sc, Bt8370_LOOP, 0x00); /* no loopback */
2052    framer_write(sc, Bt8370_CR0,  0x80); /* sw-reset */
2053    for (i=0; i<10; i++) /* wait for sw-reset to clear; max 10 ms */
2054      if (framer_read(sc, Bt8370_CR0) & 0x80) DELAY(1000);
2055
2056    sc->status.card_type   = CSID_LMC_T1E1;
2057    sc->config.crc_len     = CFG_CRC_16;
2058    sc->config.loop_back   = CFG_LOOP_NONE;
2059    sc->config.tx_clk_src  = CFG_CLKMUX_RT; /* loop timed */
2060#if 1 /* USA */ /* decide using time zone? */
2061    sc->config.format      = CFG_FORMAT_T1ESF;
2062#else /* REST OF PLANET */
2063    sc->config.format      = CFG_FORMAT_E1FASCRC;
2064#endif
2065    sc->config.time_slots  = 0xFFFFFFFF;
2066    sc->config.cable_len   = 10;
2067    sc->config.tx_pulse    = CFG_PULSE_AUTO;
2068    sc->config.rx_gain_max = CFG_GAIN_AUTO;
2069    sc->config.tx_lbo      = CFG_LBO_AUTO;
2070    }
2071  else if (config != &sc->config) /* change config */
2072    {
2073    if ((sc->config.crc_len     == config->crc_len)     &&
2074        (sc->config.loop_back   == config->loop_back)   &&
2075        (sc->config.tx_clk_src  == config->tx_clk_src)  &&
2076        (sc->config.format      == config->format)      &&
2077        (sc->config.time_slots  == config->time_slots)  &&
2078        (sc->config.cable_len   == config->cable_len)   &&
2079        (sc->config.tx_pulse    == config->tx_pulse)    &&
2080        (sc->config.rx_gain_max == config->rx_gain_max) &&
2081        (sc->config.tx_lbo      == config->tx_lbo))
2082      return; /* nothing changed */
2083    sc->config.crc_len     = config->crc_len;
2084    sc->config.loop_back   = config->loop_back;
2085    sc->config.tx_clk_src  = config->tx_clk_src;
2086    sc->config.format      = config->format;
2087    sc->config.cable_len   = config->cable_len;
2088    sc->config.time_slots  = config->time_slots;
2089    sc->config.tx_pulse    = config->tx_pulse;
2090    sc->config.rx_gain_max = config->rx_gain_max;
2091    sc->config.tx_lbo      = config->tx_lbo;
2092    }
2093
2094  /* Set CRC length. */
2095  if (sc->config.crc_len == CFG_CRC_32)
2096    mii16_set_bits(sc, MII16_T1_CRC32);
2097  else
2098    mii16_clr_bits(sc, MII16_T1_CRC32);
2099
2100  /* Invert HDLC payload data in SF/AMI mode. */
2101  /* HDLC stuff bits satisfy T1 pulse density. */
2102  if (FORMAT_T1SF)
2103    mii16_set_bits(sc, MII16_T1_INVERT);
2104  else
2105    mii16_clr_bits(sc, MII16_T1_INVERT);
2106
2107  /* Set the transmitter output impedance. */
2108  if (FORMAT_E1ANY) mii16_set_bits(sc, MII16_T1_Z);
2109
2110  /* 001:CR0 -- Control Register 0 - T1/E1 and frame format */
2111  framer_write(sc, Bt8370_CR0, sc->config.format);
2112
2113  /* 002:JAT_CR -- Jitter Attenuator Control Register */
2114  if (sc->config.tx_clk_src == CFG_CLKMUX_RT) /* loop timing */
2115    framer_write(sc, Bt8370_JAT_CR, 0xA3); /* JAT in RX path */
2116  else
2117    { /* 64-bit elastic store; free-running JCLK and CLADO */
2118    framer_write(sc, Bt8370_JAT_CR, 0x4B); /* assert jcenter */
2119    framer_write(sc, Bt8370_JAT_CR, 0x43); /* release jcenter */
2120    }
2121
2122  /* 00C-013:IERn -- Interrupt Enable Registers */
2123  for (i=Bt8370_IER7; i<=Bt8370_IER0; i++)
2124    framer_write(sc, i, 0); /* no interrupts; polled */
2125
2126  /* 014:LOOP -- loopbacks */
2127  if      (sc->config.loop_back == CFG_LOOP_PAYLOAD)
2128    framer_write(sc, Bt8370_LOOP, LOOP_PAYLOAD);
2129  else if (sc->config.loop_back == CFG_LOOP_LINE)
2130    framer_write(sc, Bt8370_LOOP, LOOP_LINE);
2131  else if (sc->config.loop_back == CFG_LOOP_OTHER)
2132    framer_write(sc, Bt8370_LOOP, LOOP_ANALOG);
2133  else if (sc->config.loop_back == CFG_LOOP_INWARD)
2134    framer_write(sc, Bt8370_LOOP, LOOP_FRAMER);
2135  else if (sc->config.loop_back == CFG_LOOP_DUAL)
2136    framer_write(sc, Bt8370_LOOP, LOOP_DUAL);
2137  else
2138    framer_write(sc, Bt8370_LOOP, 0x00); /* no loopback */
2139
2140  /* 015:DL3_TS -- Data Link 3 */
2141  framer_write(sc, Bt8370_DL3_TS, 0x00); /* disabled */
2142
2143  /* 018:PIO -- Programmable I/O */
2144  framer_write(sc, Bt8370_PIO, 0xFF); /* all pins are outputs */
2145
2146  /* 019:POE -- Programmable Output Enable */
2147  framer_write(sc, Bt8370_POE, 0x00); /* all outputs are enabled */
2148
2149  /* 01A;CMUX -- Clock Input Mux */
2150  if (sc->config.tx_clk_src == CFG_CLKMUX_EXT)
2151    framer_write(sc, Bt8370_CMUX, 0x0C); /* external timing */
2152  else
2153    framer_write(sc, Bt8370_CMUX, 0x0F); /* internal timing */
2154
2155  /* 020:LIU_CR -- Line Interface Unit Config Register */
2156  framer_write(sc, Bt8370_LIU_CR, 0xC1); /* reset LIU, squelch */
2157
2158  /* 022:RLIU_CR -- RX Line Interface Unit Config Reg */
2159  /* Errata sheet says do not use freeze-short, but we do anyway! */
2160  framer_write(sc, Bt8370_RLIU_CR, 0xB1); /* AGC=2048, Long Eye */
2161
2162  /* Select Rx sensitivity based on cable length. */
2163  if ((gain = sc->config.rx_gain_max) == CFG_GAIN_AUTO)
2164    {
2165    if      (sc->config.cable_len > 2000)
2166      gain = CFG_GAIN_EXTEND;
2167    else if (sc->config.cable_len > 1000)
2168      gain = CFG_GAIN_LONG;
2169    else if (sc->config.cable_len > 100)
2170      gain = CFG_GAIN_MEDIUM;
2171    else
2172      gain = CFG_GAIN_SHORT;
2173    }
2174
2175  /* 024:VGA_MAX -- Variable Gain Amplifier Max gain */
2176  framer_write(sc, Bt8370_VGA_MAX, gain);
2177
2178  /* 028:PRE_EQ -- Pre Equalizer */
2179  if (gain == CFG_GAIN_EXTEND)
2180    framer_write(sc, Bt8370_PRE_EQ, 0xE6);  /* ON; thresh 6 */
2181  else
2182    framer_write(sc, Bt8370_PRE_EQ, 0xA6);  /* OFF; thresh 6 */
2183
2184  /* 038-03C:GAINn -- RX Equalizer gain thresholds */
2185  framer_write(sc, Bt8370_GAIN0, 0x24);
2186  framer_write(sc, Bt8370_GAIN1, 0x28);
2187  framer_write(sc, Bt8370_GAIN2, 0x2C);
2188  framer_write(sc, Bt8370_GAIN3, 0x30);
2189  framer_write(sc, Bt8370_GAIN4, 0x34);
2190
2191  /* 040:RCR0 -- Receiver Control Register 0 */
2192  if      (FORMAT_T1ESF)
2193    framer_write(sc, Bt8370_RCR0, 0x05); /* B8ZS, 2/5 FErrs */
2194  else if (FORMAT_T1SF)
2195    framer_write(sc, Bt8370_RCR0, 0x84); /* AMI,  2/5 FErrs */
2196  else if (FORMAT_E1NONE)
2197    framer_write(sc, Bt8370_RCR0, 0x41); /* HDB3, rabort */
2198  else if (FORMAT_E1CRC)
2199    framer_write(sc, Bt8370_RCR0, 0x09); /* HDB3, 3 FErrs or 915 CErrs */
2200  else  /* E1 no CRC */
2201    framer_write(sc, Bt8370_RCR0, 0x19); /* HDB3, 3 FErrs */
2202
2203  /* 041:RPATT -- Receive Test Pattern configuration */
2204  framer_write(sc, Bt8370_RPATT, 0x3E); /* looking for framed QRSS */
2205
2206  /* 042:RLB -- Receive Loop Back code detector config */
2207  framer_write(sc, Bt8370_RLB, 0x09); /* 6 bits down; 5 bits up */
2208
2209  /* 043:LBA -- Loop Back Activate code */
2210  framer_write(sc, Bt8370_LBA, 0x08); /* 10000 10000 10000 ... */
2211
2212  /* 044:LBD -- Loop Back Deactivate code */
2213  framer_write(sc, Bt8370_LBD, 0x24); /* 100100 100100 100100 ... */
2214
2215  /* 045:RALM -- Receive Alarm signal configuration */
2216  framer_write(sc, Bt8370_RALM, 0x0C); /* yel_intg rlof_intg */
2217
2218  /* 046:LATCH -- Alarm/Error/Counter Latch register */
2219  framer_write(sc, Bt8370_LATCH, 0x1F); /* stop_cnt latch_{cnt,err,alm} */
2220
2221  /* Select Pulse Shape based on cable length (T1 only). */
2222  if ((pulse = sc->config.tx_pulse) == CFG_PULSE_AUTO)
2223    {
2224    if (FORMAT_T1ANY)
2225      {
2226      if      (sc->config.cable_len > 200)
2227        pulse = CFG_PULSE_T1CSU;
2228      else if (sc->config.cable_len > 160)
2229        pulse = CFG_PULSE_T1DSX4;
2230      else if (sc->config.cable_len > 120)
2231        pulse = CFG_PULSE_T1DSX3;
2232      else if (sc->config.cable_len > 80)
2233        pulse = CFG_PULSE_T1DSX2;
2234      else if (sc->config.cable_len > 40)
2235        pulse = CFG_PULSE_T1DSX1;
2236      else
2237        pulse = CFG_PULSE_T1DSX0;
2238      }
2239    else
2240      pulse = CFG_PULSE_E1TWIST;
2241    }
2242
2243  /* Select Line Build Out based on cable length (T1CSU only). */
2244  if ((lbo = sc->config.tx_lbo) == CFG_LBO_AUTO)
2245    {
2246    if (pulse == CFG_PULSE_T1CSU)
2247      {
2248      if      (sc->config.cable_len > 1500)
2249        lbo = CFG_LBO_0DB;
2250      else if (sc->config.cable_len > 1000)
2251        lbo = CFG_LBO_7DB;
2252      else if (sc->config.cable_len >  500)
2253        lbo = CFG_LBO_15DB;
2254      else
2255        lbo = CFG_LBO_22DB;
2256      }
2257    else
2258      lbo = 0;
2259    }
2260
2261  /* 068:TLIU_CR -- Transmit LIU Control Register */
2262  framer_write(sc, Bt8370_TLIU_CR, (0x40 | (lbo & 0x30) | (pulse & 0x0E)));
2263
2264  /* 070:TCR0 -- Transmit Framer Configuration */
2265  framer_write(sc, Bt8370_TCR0, sc->config.format>>1);
2266
2267  /* 071:TCR1 -- Transmitter Configuration */
2268  if (FORMAT_T1SF)
2269    framer_write(sc, Bt8370_TCR1, 0x43); /* tabort, AMI PDV enforced */
2270  else
2271    framer_write(sc, Bt8370_TCR1, 0x41); /* tabort, B8ZS or HDB3 */
2272
2273  /* 072:TFRM -- Transmit Frame format       MYEL YEL MF FE CRC FBIT */
2274  if      (sc->config.format == CFG_FORMAT_T1ESF)
2275    framer_write(sc, Bt8370_TFRM, 0x0B); /*  -   YEL MF -  CRC FBIT */
2276  else if (sc->config.format == CFG_FORMAT_T1SF)
2277    framer_write(sc, Bt8370_TFRM, 0x19); /*  -   YEL MF -   -  FBIT */
2278  else if (sc->config.format == CFG_FORMAT_E1FAS)
2279    framer_write(sc, Bt8370_TFRM, 0x11); /*  -   YEL -  -   -  FBIT */
2280  else if (sc->config.format == CFG_FORMAT_E1FASCRC)
2281    framer_write(sc, Bt8370_TFRM, 0x1F); /*  -   YEL MF FE CRC FBIT */
2282  else if (sc->config.format == CFG_FORMAT_E1FASCAS)
2283    framer_write(sc, Bt8370_TFRM, 0x31); /* MYEL YEL -  -   -  FBIT */
2284  else if (sc->config.format == CFG_FORMAT_E1FASCRCCAS)
2285    framer_write(sc, Bt8370_TFRM, 0x3F); /* MYEL YEL MF FE CRC FBIT */
2286  else if (sc->config.format == CFG_FORMAT_E1NONE)
2287    framer_write(sc, Bt8370_TFRM, 0x00); /* NO FRAMING BITS AT ALL! */
2288
2289  /* 073:TERROR -- Transmit Error Insert */
2290  framer_write(sc, Bt8370_TERROR, 0x00); /* no errors, please! */
2291
2292  /* 074:TMAN -- Transmit Manual Sa-byte/FEBE configuration */
2293  framer_write(sc, Bt8370_TMAN, 0x00); /* none */
2294
2295  /* 075:TALM -- Transmit Alarm Signal Configuration */
2296  if (FORMAT_E1ANY)
2297    framer_write(sc, Bt8370_TALM, 0x38); /* auto_myel auto_yel auto_ais */
2298  else if (FORMAT_T1ANY)
2299    framer_write(sc, Bt8370_TALM, 0x18); /* auto_yel auto_ais */
2300
2301  /* 076:TPATT -- Transmit Test Pattern Configuration */
2302  framer_write(sc, Bt8370_TPATT, 0x00); /* disabled */
2303
2304  /* 077:TLB -- Transmit Inband Loopback Code Configuration */
2305  framer_write(sc, Bt8370_TLB, 0x00); /* disabled */
2306
2307  /* 090:CLAD_CR -- Clack Rate Adapter Configuration */
2308  if (FORMAT_T1ANY)
2309    framer_write(sc, Bt8370_CLAD_CR, 0x06); /* loop filter gain 1/2^6 */
2310  else
2311    framer_write(sc, Bt8370_CLAD_CR, 0x08); /* loop filter gain 1/2^8 */
2312
2313  /* 091:CSEL -- CLAD frequency Select */
2314  if (FORMAT_T1ANY)
2315    framer_write(sc, Bt8370_CSEL, 0x55); /* 1544 kHz */
2316  else
2317    framer_write(sc, Bt8370_CSEL, 0x11); /* 2048 kHz */
2318
2319  /* 092:CPHASE -- CLAD Phase detector */
2320  if (FORMAT_T1ANY)
2321    framer_write(sc, Bt8370_CPHASE, 0x22); /* phase compare @  386 kHz */
2322  else
2323    framer_write(sc, Bt8370_CPHASE, 0x00); /* phase compare @ 2048 kHz */
2324
2325  if (FORMAT_T1ESF) /* BOP & PRM are enabled in T1ESF mode only. */
2326    {
2327    /* 0A0:BOP -- Bit Oriented Protocol messages */
2328    framer_write(sc, Bt8370_BOP, RBOP_25 | TBOP_OFF);
2329    /* 0A4:DL1_TS -- Data Link 1 Time Slot Enable */
2330    framer_write(sc, Bt8370_DL1_TS, 0x40); /* FDL bits in odd frames */
2331    /* 0A6:DL1_CTL -- Data Link 1 Control */
2332    framer_write(sc, Bt8370_DL1_CTL, 0x03); /* FCS mode, TX on, RX on */
2333    /* 0A7:RDL1_FFC -- Rx Data Link 1 Fifo Fill Control */
2334    framer_write(sc, Bt8370_RDL1_FFC, 0x30); /* assert "near full" at 48 */
2335    /* 0AA:PRM -- Performance Report Messages */
2336    framer_write(sc, Bt8370_PRM, 0x80);
2337    }
2338
2339  /* 0D0:SBI_CR -- System Bus Interface Configuration Register */
2340  if (FORMAT_T1ANY)
2341    framer_write(sc, Bt8370_SBI_CR, 0x47); /* 1.544 with 24 TS +Fbits */
2342  else
2343    framer_write(sc, Bt8370_SBI_CR, 0x46); /* 2.048 with 32 TS */
2344
2345  /* 0D1:RSB_CR -- Receive System Bus Configuration Register */
2346  /* Change RINDO & RFSYNC on falling edge of RSBCLKI. */
2347  framer_write(sc, Bt8370_RSB_CR, 0x70);
2348
2349  /* 0D2,0D3:RSYNC_{TS,BIT} -- Receive frame Sync offset */
2350  framer_write(sc, Bt8370_RSYNC_BIT, 0x00);
2351  framer_write(sc, Bt8370_RSYNC_TS,  0x00);
2352
2353  /* 0D4:TSB_CR -- Transmit System Bus Configuration Register */
2354  /* Change TINDO & TFSYNC on falling edge of TSBCLKI. */
2355  framer_write(sc, Bt8370_TSB_CR, 0x30);
2356
2357  /* 0D5,0D6:TSYNC_{TS,BIT} -- Transmit frame Sync offset */
2358  framer_write(sc, Bt8370_TSYNC_BIT, 0x00);
2359  framer_write(sc, Bt8370_TSYNC_TS,  0x00);
2360
2361  /* 0D7:RSIG_CR -- Receive SIGnalling Configuration Register */
2362  framer_write(sc, Bt8370_RSIG_CR, 0x00);
2363
2364  /* Assign and configure 64Kb TIME SLOTS. */
2365  /* TS24..TS1 must be assigned for T1, TS31..TS0 for E1. */
2366  /* Timeslots with no user data have RINDO and TINDO off. */
2367  for (sc->status.time_slots = 0, i=0; i<32; i++)
2368    {
2369    /* 0E0-0FF:SBCn -- System Bus Per-Channel Control */
2370    if      (FORMAT_T1ANY && (i==0 || i>24))
2371      framer_write(sc, Bt8370_SBCn +i, 0x00); /* not assigned in T1 mode */
2372    else if (FORMAT_E1ANY && (i==0)  && !FORMAT_E1NONE)
2373      framer_write(sc, Bt8370_SBCn +i, 0x01); /* assigned, TS0  o/h bits */
2374    else if (FORMAT_E1CAS && (i==16) && !FORMAT_E1NONE)
2375      framer_write(sc, Bt8370_SBCn +i, 0x01); /* assigned, TS16 o/h bits */
2376    else if ((sc->status.time_slots |= (sc->config.time_slots & (1<<i))))
2377      framer_write(sc, Bt8370_SBCn +i, 0x0D); /* assigned, RINDO, TINDO */
2378    else
2379      framer_write(sc, Bt8370_SBCn +i, 0x01); /* assigned, idle */
2380
2381    /* 100-11F:TPCn -- Transmit Per-Channel Control */
2382    if      (FORMAT_E1CAS && (i==0))
2383      framer_write(sc, Bt8370_TPCn +i, 0x30); /* tidle, sig=0000 (MAS) */
2384    else if (FORMAT_E1CAS && (i==16))
2385      framer_write(sc, Bt8370_TPCn +i, 0x3B); /* tidle, sig=1011 (XYXX) */
2386    else if ((sc->config.time_slots & (1<<i)) == 0)
2387      framer_write(sc, Bt8370_TPCn +i, 0x20); /* tidle: use TSLIP_LOn */
2388    else
2389      framer_write(sc, Bt8370_TPCn +i, 0x00); /* nothing special */
2390
2391    /* 140-15F:TSLIP_LOn -- Transmit PCM Slip Buffer */
2392    framer_write(sc, Bt8370_TSLIP_LOn +i, 0x7F); /* idle chan data */
2393    /* 180-19F:RPCn -- Receive Per-Channel Control */
2394    framer_write(sc, Bt8370_RPCn +i, 0x00);   /* nothing special */
2395    }
2396
2397  /* Enable transmitter output drivers. */
2398  mii16_set_bits(sc, MII16_T1_XOE);
2399  }
2400
2401static void
2402t1_detach(softc_t *sc)
2403  {
2404  led_on(sc, MII16_LED_ALL);
2405  }
2406
2407/* End T1E1 card code */
2408
2409
2410#if SYNC_PPP  /* Linux */
2411
2412static struct stack sync_ppp_stack =
2413  {
2414  .ioctl    = sync_ppp_ioctl,
2415  .type     = sync_ppp_type,
2416  .mtu      = sync_ppp_mtu,
2417  .watchdog = sync_ppp_watchdog,
2418  .open     = sync_ppp_open,
2419  .attach   = sync_ppp_attach,
2420  .detach   = sync_ppp_detach,
2421  };
2422
2423static int  /* context: process */
2424sync_ppp_ioctl(softc_t *sc, struct ifreq *ifr, int cmd)
2425  {
2426  return sppp_do_ioctl(sc->netdev, ifr, cmd);
2427  }
2428
2429static int  /* context: interrupt */
2430sync_ppp_type(softc_t *sc, struct sk_buff *skb)
2431  {
2432  return htons(ETH_P_WAN_PPP);
2433  }
2434
2435static int  /* context: process */
2436sync_ppp_mtu(softc_t *sc, int mtu)
2437  {
2438  return ((mtu < 128) || (mtu > PPP_MTU)) ? -EINVAL : 0;
2439  }
2440
2441static void  /* context: softirq */
2442sync_ppp_watchdog(softc_t *sc)
2443  {
2444  /* Notice when the link comes up. */
2445  if ((sc->last_link_state != STATE_UP) &&
2446    (sc->status.link_state == STATE_UP))
2447    sppp_reopen(sc->netdev);
2448
2449  /* Notice when the link goes down. */
2450  if ((sc->last_link_state == STATE_UP) &&
2451    (sc->status.link_state != STATE_UP))
2452    sppp_close(sc->netdev);
2453
2454  /* Report current line protocol. */
2455  sc->status.stack = STACK_SYNC_PPP;
2456  if (sc->sppp->pp_flags & PP_CISCO)
2457    sc->status.proto = PROTO_C_HDLC;
2458  else
2459    sc->status.proto = PROTO_PPP;
2460
2461  /* Report keep-alive status. */
2462  sc->status.keep_alive = sc->sppp->pp_flags & PP_KEEPALIVE;
2463  }
2464
2465static int  /* never fails */
2466sync_ppp_open(softc_t *sc, struct config *config)
2467  {
2468  /* Refresh the keep_alive flag. */
2469  if (config->keep_alive)
2470    sc->sppp->pp_flags |=  PP_KEEPALIVE;
2471  else
2472    sc->sppp->pp_flags &= ~PP_KEEPALIVE;
2473  sc->config.keep_alive = config->keep_alive;
2474
2475  /* Done if proto is not changing. */
2476  if (config->proto == sc->config.proto)
2477    return 0;
2478
2479  /* Close */
2480  sppp_close(sc->netdev);
2481
2482  /* Change line protocol. */
2483  switch (config->proto)
2484    {
2485    case PROTO_PPP:
2486      sc->sppp->pp_flags  &= ~PP_CISCO;
2487      sc->netdev->type = ARPHRD_PPP;
2488      sc->config.proto = PROTO_PPP;
2489      break;
2490    default:
2491    case PROTO_C_HDLC:
2492      sc->sppp->pp_flags  |=  PP_CISCO;
2493      sc->netdev->type = ARPHRD_CISCO;
2494      sc->config.proto = PROTO_C_HDLC;
2495      break;
2496    }
2497
2498  /* Open */
2499  sppp_open(sc->netdev);
2500
2501  return 0;
2502  }
2503
2504static int  /* never fails */
2505sync_ppp_attach(softc_t *sc, struct config *config)
2506  {
2507  sc->ppd = &sc->ppp_dev;      /* struct ppp_device*  */
2508  sc->netdev->priv = &sc->ppd; /* struct ppp_device** */
2509  sc->ppp_dev.dev = sc->netdev;
2510  sc->sppp = &sc->ppp_dev.sppp;
2511
2512  sppp_attach(&sc->ppp_dev);
2513  sc->netdev->do_ioctl = netdev_ioctl;
2514  config->keep_alive = 1;
2515
2516  sc->config.stack = STACK_SYNC_PPP;
2517  sc->stack = &sync_ppp_stack;
2518
2519  return 0;
2520  }
2521
2522static int  /* never fails */
2523sync_ppp_detach(softc_t *sc)
2524  {
2525  sppp_close(sc->netdev);
2526  sppp_detach(sc->netdev);
2527
2528  netdev_setup(sc->netdev);
2529  sc->config.stack = STACK_NONE;
2530  sc->config.proto = PROTO_NONE;
2531  sc->stack = NULL;
2532
2533  return 0;
2534  }
2535
2536#endif /* SYNC_PPP */
2537
2538#if GEN_HDLC  /* Linux only */
2539
2540static struct stack gen_hdlc_stack =
2541  {
2542  .ioctl    = gen_hdlc_ioctl,
2543  .type     = gen_hdlc_type,
2544  .mtu      = gen_hdlc_mtu,
2545  .watchdog = gen_hdlc_watchdog,
2546  .open     = gen_hdlc_open,
2547  .attach   = gen_hdlc_attach,
2548  .detach   = gen_hdlc_detach,
2549  };
2550
2551static int  /* context: process */
2552gen_hdlc_ioctl(softc_t *sc, struct ifreq *ifr, int cmd)
2553  {
2554  te1_settings settings;
2555  int error = 0;
2556
2557  if (cmd == SIOCWANDEV)
2558    switch (ifr->ifr_settings.type)
2559      {
2560      case IF_GET_IFACE: /* get interface config */
2561        {
2562        unsigned int size;
2563
2564        /* NOTE: This assumes struct sync_serial_settings has the */
2565        /* same layout as the first part of struct te1_settings. */
2566        if (sc->status.card_type == CSID_LMC_T1E1)
2567          {
2568          if (FORMAT_T1ANY) ifr->ifr_settings.type = IF_IFACE_T1;
2569          if (FORMAT_E1ANY) ifr->ifr_settings.type = IF_IFACE_E1;
2570          size = sizeof(te1_settings);
2571	  }
2572        else
2573          {
2574          ifr->ifr_settings.type = IF_IFACE_SYNC_SERIAL;
2575          size = sizeof(sync_serial_settings);
2576	  }
2577        if (ifr->ifr_settings.size < size)
2578          {
2579          ifr->ifr_settings.size = size;
2580          return -ENOBUFS;
2581	  }
2582        ifr->ifr_settings.size = size;
2583
2584        if (sc->config.tx_clk_src == CFG_CLKMUX_ST)
2585          settings.clock_type = CLOCK_EXT;
2586        if (sc->config.tx_clk_src == CFG_CLKMUX_INT)
2587          settings.clock_type = CLOCK_TXINT;
2588        if (sc->config.tx_clk_src == CFG_CLKMUX_RT)
2589          settings.clock_type = CLOCK_TXFROMRX;
2590        settings.loopback = (sc->config.loop_back != CFG_LOOP_NONE) ? 1:0;
2591        settings.clock_rate = sc->status.tx_speed;
2592        if (sc->status.card_type == CSID_LMC_T1E1)
2593          settings.slot_map = sc->status.time_slots;
2594
2595        error = copy_to_user(ifr->ifr_settings.ifs_ifsu.te1,
2596         &settings, size);
2597        break;
2598        }
2599      case IF_IFACE_SYNC_SERIAL: /* set interface config */
2600      case IF_IFACE_T1:
2601      case IF_IFACE_E1:
2602        {
2603        struct config config = sc->config;
2604
2605        if (!capable(CAP_NET_ADMIN)) return -EPERM;
2606        if (ifr->ifr_settings.size > sizeof(te1_settings))
2607          return -ENOBUFS;
2608        error = copy_from_user(&settings,
2609         ifr->ifr_settings.ifs_ifsu.te1, sizeof(te1_settings));
2610
2611        if      (settings.clock_type == CLOCK_EXT)
2612          config.tx_clk_src = CFG_CLKMUX_ST;
2613        else if (settings.clock_type == CLOCK_TXINT)
2614          config.tx_clk_src = CFG_CLKMUX_INT;
2615        else if (settings.clock_type == CLOCK_TXFROMRX)
2616          config.tx_clk_src = CFG_CLKMUX_RT;
2617
2618        if (settings.loopback)
2619          config.loop_back = CFG_LOOP_TULIP;
2620        else
2621          config.loop_back = CFG_LOOP_NONE;
2622
2623        tulip_loop(sc, &config);
2624        sc->card->attach(sc, &config);
2625        break;
2626        }
2627      default:  /* Pass the rest to the line pkg. */
2628        {
2629        error = hdlc_ioctl(sc->netdev, ifr, cmd);
2630        break;
2631        }
2632      }
2633    else
2634      error = -EINVAL;
2635
2636  return error;
2637  }
2638
2639static int  /* context: interrupt */
2640gen_hdlc_type(softc_t *sc, struct sk_buff *skb)
2641  {
2642  return hdlc_type_trans(skb, sc->netdev);
2643  }
2644
2645static int  /* context: process */
2646gen_hdlc_mtu(softc_t *sc, int mtu)
2647  {
2648  return ((mtu < 68) || (mtu > HDLC_MAX_MTU)) ? -EINVAL : 0;
2649  }
2650
2651static void  /* context: softirq */
2652gen_hdlc_watchdog(softc_t *sc)
2653  {
2654  /* Notice when the link comes up. */
2655  if ((sc->last_link_state != STATE_UP) &&
2656    (sc->status.link_state == STATE_UP))
2657    hdlc_set_carrier(1, sc->netdev);
2658
2659  /* Notice when the link goes down. */
2660  if ((sc->last_link_state == STATE_UP) &&
2661    (sc->status.link_state != STATE_UP))
2662    hdlc_set_carrier(0, sc->netdev);
2663
2664  /* Report current line protocol. */
2665  sc->status.stack = STACK_GEN_HDLC;
2666  switch (sc->hdlcdev->proto.id)
2667    {
2668    case IF_PROTO_PPP:
2669      {
2670      struct sppp* sppp = &sc->hdlcdev->state.ppp.pppdev.sppp;
2671      sc->status.keep_alive = sppp->pp_flags & PP_KEEPALIVE;
2672      sc->status.proto = PROTO_PPP;
2673      break;
2674      }
2675    case IF_PROTO_CISCO:
2676      sc->status.proto = PROTO_C_HDLC;
2677      break;
2678    case IF_PROTO_FR:
2679      sc->status.proto = PROTO_FRM_RLY;
2680      break;
2681    case IF_PROTO_HDLC:
2682      sc->status.proto = PROTO_IP_HDLC;
2683      break;
2684    case IF_PROTO_X25:
2685      sc->status.proto = PROTO_X25;
2686      break;
2687    case IF_PROTO_HDLC_ETH:
2688      sc->status.proto = PROTO_ETH_HDLC;
2689      break;
2690    default:
2691      sc->status.proto = PROTO_NONE;
2692      break;
2693    }
2694  }
2695
2696static int
2697gen_hdlc_open(softc_t *sc, struct config *config)
2698  {
2699  int error = 0;
2700
2701  /* Refresh the keep_alive flag. */
2702  if (sc->hdlcdev->proto.id == IF_PROTO_PPP)
2703    {
2704    struct sppp* sppp = &sc->hdlcdev->state.ppp.pppdev.sppp;
2705    if (config->keep_alive)
2706      sppp->pp_flags |=  PP_KEEPALIVE;
2707    else
2708      sppp->pp_flags &= ~PP_KEEPALIVE;
2709    sc->config.keep_alive = config->keep_alive;
2710    }
2711
2712  /* Done if proto is not changing. */
2713  if (config->proto == sc->config.proto)
2714    return 0;
2715
2716  /* Close */
2717  hdlc_close(sc->netdev);
2718
2719  /* Generic-HDLC gets protocol params using copy_from_user().
2720   * This is a problem for a kernel-resident device driver.
2721   * Luckily, PPP does not need any params so no copy_from_user().
2722   */
2723
2724  /* Change line protocol. */
2725  if (config->proto == PROTO_PPP)
2726    {
2727    struct ifreq ifr;
2728    ifr.ifr_settings.size = 0;
2729    ifr.ifr_settings.type = IF_PROTO_PPP;
2730    hdlc_ioctl(sc->netdev, &ifr, SIOCWANDEV);
2731    }
2732  /* Changing to any protocol other than PPP */
2733  /*  requires using the 'sethdlc' program. */
2734
2735  /* Open */
2736  if ((error = hdlc_open(sc->netdev)))
2737    {
2738    if (sc->config.debug)
2739      printk("%s: hdlc_open(): error %d\n", NAME_UNIT, error);
2740    if (error == -ENOSYS)
2741      printk("%s: Try 'sethdlc %s hdlc|ppp|cisco|fr'\n",
2742       NAME_UNIT, NAME_UNIT);
2743    sc->config.proto = PROTO_NONE;
2744    }
2745  else
2746    sc->config.proto = config->proto;
2747
2748  return error;
2749  }
2750
2751static int  /* never fails */
2752gen_hdlc_attach(softc_t *sc, struct config *config)
2753  {
2754  sc->netdev->priv = sc->hdlcdev;
2755
2756  /* hdlc_attach(sc->netdev); */
2757  sc->netdev->mtu = HDLC_MAX_MTU;
2758  sc->hdlcdev->attach = gen_hdlc_card_params;
2759  sc->hdlcdev->xmit = netdev_start;
2760  config->keep_alive = 1;
2761
2762  sc->config.stack = STACK_GEN_HDLC;
2763  sc->stack = &gen_hdlc_stack;
2764
2765  return 0;
2766  }
2767
2768static int  /* never fails */
2769gen_hdlc_detach(softc_t *sc)
2770  {
2771  hdlc_close(sc->netdev);
2772  /* hdlc_detach(sc->netdev); */
2773  hdlc_proto_detach(sc->hdlcdev);
2774  memset(&sc->hdlcdev->proto, 0, sizeof sc->hdlcdev->proto);
2775
2776  netdev_setup(sc->netdev);
2777  sc->config.stack = STACK_NONE;
2778  sc->config.proto = PROTO_NONE;
2779  sc->stack = NULL;
2780
2781  return 0;
2782  }
2783
2784static int
2785gen_hdlc_card_params(struct net_device *netdev,
2786 unsigned short encoding, unsigned short parity)
2787  {
2788  softc_t *sc = NETDEV2SC(netdev);
2789  struct config config = sc->config;
2790
2791  /* Encoding does not seem to apply to synchronous interfaces, */
2792  /* but Parity seems to be generic-HDLC's name for CRC. */
2793  if (parity == PARITY_CRC32_PR1_CCITT)
2794    config.crc_len = CFG_CRC_32;
2795  if (parity == PARITY_CRC16_PR1_CCITT)
2796    config.crc_len = CFG_CRC_16;
2797  sc->card->attach(sc, &config);
2798
2799  return 0;
2800  }
2801
2802#endif /* GEN_HDLC */
2803
2804#if P2P  /* BSD/OS */
2805
2806static struct stack p2p_stack =
2807  {
2808  .ioctl    = p2p_stack_ioctl,
2809  .input    = p2p_stack_input,
2810  .output   = p2p_stack_output,
2811  .watchdog = p2p_stack_watchdog,
2812  .open     = p2p_stack_open,
2813  .attach   = p2p_stack_attach,
2814  .detach   = p2p_stack_detach,
2815  };
2816
2817static int  /* context: process */
2818p2p_stack_ioctl(softc_t *sc, u_long cmd, void *data)
2819  {
2820  return p2p_ioctl(sc->ifp, cmd, data);
2821  }
2822
2823static void  /* context: interrupt */
2824p2p_stack_input(softc_t *sc, struct mbuf *mbuf)
2825  {
2826  struct mbuf *new_mbuf = mbuf;
2827
2828  while (new_mbuf)
2829    {
2830    sc->p2p->p2p_hdrinput(sc->p2p, new_mbuf->m_data, new_mbuf->m_len);
2831    new_mbuf = new_mbuf->m_next;
2832    }
2833  sc->p2p->p2p_input(sc->p2p, NULL);
2834  m_freem(mbuf);
2835  }
2836
2837static void  /* context: interrupt */
2838p2p_stack_output(softc_t *sc)
2839  {
2840  if (!IFQ_IS_EMPTY(&sc->p2p->p2p_isnd))
2841    IFQ_DEQUEUE(&sc->p2p->p2p_isnd, sc->tx_mbuf);
2842  else
2843    IFQ_DEQUEUE(&sc->ifp->if_snd,   sc->tx_mbuf);
2844  }
2845
2846static void  /* context: softirq */
2847p2p_stack_watchdog(softc_t *sc)
2848  {
2849  /* Notice change in link status. */
2850  if ((sc->last_link_state != sc->status.link_state) &&
2851   /* if_slowtimo() can run before raw_init() has inited rawcb. */
2852   (sc->p2p->p2p_modem != NULL) && (rawcb.rcb_next != NULL))
2853    (*sc->p2p->p2p_modem)(sc->p2p, sc->status.link_state==STATE_UP);
2854
2855  /* Report current line protocol. */
2856  sc->status.stack = STACK_P2P;
2857  switch (sc->ifp->if_type)
2858    {
2859    case IFT_PPP:
2860      sc->status.proto = PROTO_PPP;
2861      break;
2862    case IFT_PTPSERIAL:
2863      sc->status.proto = PROTO_C_HDLC;
2864      break;
2865    case IFT_FRELAY:
2866      sc->status.proto = PROTO_FRM_RLY;
2867      break;
2868    default:
2869      sc->status.proto = PROTO_NONE;
2870      break;
2871    }
2872  }
2873
2874static int
2875p2p_stack_open(softc_t *sc, struct config *config)
2876  {
2877  int error = 0;
2878
2879  /* Done if proto is not changing. */
2880  if (config->proto == sc->config.proto)
2881    return 0;
2882
2883  if (error = p2p_stack_detach(sc))
2884    return error;
2885
2886  /* Change line protocol. */
2887  switch (config->proto)
2888    {
2889    case PROTO_PPP:
2890      sc->ifp->if_type = IFT_PPP;
2891      sc->config.proto = PROTO_PPP;
2892      break;
2893    case PROTO_C_HDLC:
2894      sc->ifp->if_type = IFT_PTPSERIAL;
2895      sc->config.proto = PROTO_C_HDLC;
2896      break;
2897    case PROTO_FRM_RLY:
2898      sc->ifp->if_type = IFT_FRELAY;
2899      sc->config.proto = PROTO_FRM_RLY;
2900      break;
2901    default:
2902    case PROTO_NONE:
2903      sc->ifp->if_type = IFT_NONE;
2904      sc->config.proto = PROTO_NONE;
2905      return 0;
2906    }
2907
2908  error = p2p_stack_attach(sc, config);
2909
2910  return error;
2911  }
2912
2913static int
2914p2p_stack_attach(softc_t *sc, struct config *config)
2915  {
2916  int error;
2917
2918  sc->p2p = &sc->p2pcom;
2919  sc->p2p->p2p_proto = 0; /* force p2p_attach to re-init */
2920
2921  if ((error = p2p_attach(sc->p2p))) /* calls bpfattach() */
2922    {
2923    if (sc->config.debug)
2924      printf("%s: p2p_attach(): error %d\n", NAME_UNIT, error);
2925    if (error == EPFNOSUPPORT)
2926      printf("%s: Try 'ifconfig %s linktype ppp|frelay|chdlc'\n",
2927       NAME_UNIT, NAME_UNIT);
2928    sc->config.stack = STACK_NONE; /* not attached to P2P */
2929    return error;
2930    }
2931  sc->p2p->p2p_mdmctl = p2p_mdmctl;
2932  sc->p2p->p2p_getmdm = p2p_getmdm;
2933
2934  sc->config.stack = STACK_P2P;
2935  sc->stack = &p2p_stack;
2936
2937  return 0;
2938  }
2939
2940static int
2941p2p_stack_detach(softc_t *sc)
2942  {
2943  int error = 0;
2944
2945  if ((error = p2p_detach(sc->p2p))) /* calls bfpdetach() */
2946    {
2947    if (sc->config.debug)
2948      printf("%s: p2p_detach(): error %d\n",  NAME_UNIT, error);
2949    if (error == EBUSY)
2950      printf("%s: Try 'ifconfig %s down -remove'\n",
2951       NAME_UNIT, NAME_UNIT);
2952    sc->config.stack = STACK_P2P; /* still attached to P2P */
2953    return error;
2954    }
2955
2956  ifnet_setup(sc->ifp);
2957  sc->config.stack = STACK_NONE;
2958  sc->config.proto = PROTO_NONE;
2959  sc->stack = NULL;
2960
2961  return error;
2962  }
2963
2964/* Callout from P2P: */
2965/* Get the state of DCD (Data Carrier Detect). */
2966static int  /* never fails */
2967p2p_getmdm(struct p2pcom *p2p, void *result)
2968  {
2969  softc_t *sc = IFP2SC(&p2p->p2p_if);
2970
2971  /* Non-zero is not good enough; TIOCM_CAR is 0x40. */
2972  *(int *)result = (sc->status.link_state==STATE_UP) ? TIOCM_CAR : 0;
2973
2974  return 0;
2975  }
2976
2977/* Callout from P2P: */
2978/* Set the state of DTR (Data Terminal Ready). */
2979static int  /* never fails */
2980p2p_mdmctl(struct p2pcom *p2p, int flag)
2981  {
2982  softc_t *sc = IFP2SC(&p2p->p2p_if);
2983
2984  set_ready(sc, flag);
2985
2986  return 0;
2987  }
2988
2989#endif /* P2P */
2990
2991#if SPPP  /* FreeBSD, NetBSD, OpenBSD */
2992
2993static struct stack sppp_stack =
2994  {
2995  .ioctl    = sppp_stack_ioctl,
2996  .input    = sppp_stack_input,
2997  .output   = sppp_stack_output,
2998  .watchdog = sppp_stack_watchdog,
2999  .open     = sppp_stack_open,
3000  .attach   = sppp_stack_attach,
3001  .detach   = sppp_stack_detach,
3002  };
3003
3004# if !defined(PP_FR)
3005#  define PP_FR 0
3006# endif
3007# if !defined(DLT_C_HDLC)
3008#  define DLT_C_HDLC DLT_PPP
3009# endif
3010# if !defined(DLT_FRELAY)
3011#  define DLT_FRELAY DLT_PPP
3012# endif
3013
3014static int  /* context: process */
3015sppp_stack_ioctl(softc_t *sc, u_long cmd, void *data)
3016  {
3017  return sppp_ioctl(sc->ifp, cmd, data);
3018  }
3019
3020static void  /* context: interrupt */
3021sppp_stack_input(softc_t *sc, struct mbuf *mbuf)
3022  {
3023  sppp_input(sc->ifp, mbuf);
3024  }
3025
3026static void  /* context: interrupt */
3027sppp_stack_output(softc_t *sc)
3028  {
3029  sc->tx_mbuf = sppp_dequeue(sc->ifp);
3030  }
3031
3032static void  /* context: softirq */
3033sppp_stack_watchdog(softc_t *sc)
3034  {
3035  /* Notice when the link comes up. */
3036  if ((sc->last_link_state != STATE_UP) &&
3037    (sc->status.link_state == STATE_UP))
3038    sppp_tls(sc->sppp);
3039
3040  /* Notice when the link goes down. */
3041  if ((sc->last_link_state == STATE_UP) &&
3042    (sc->status.link_state != STATE_UP))
3043    sppp_tlf(sc->sppp);
3044
3045  /* Report current line protocol. */
3046  sc->status.stack = STACK_SPPP;
3047  if (sc->sppp->pp_flags & PP_CISCO)
3048    sc->status.proto = PROTO_C_HDLC;
3049  else
3050    sc->status.proto = PROTO_PPP;
3051
3052  /* Report keep-alive status. */
3053  sc->status.keep_alive = sc->sppp->pp_flags & PP_KEEPALIVE;
3054  }
3055
3056static int  /* never fails */
3057sppp_stack_open(softc_t *sc, struct config *config)
3058  {
3059  /* Refresh the keep_alive flag. */
3060  if (config->keep_alive)
3061    sc->sppp->pp_flags |=  PP_KEEPALIVE;
3062  else
3063    sc->sppp->pp_flags &= ~PP_KEEPALIVE;
3064  sc->config.keep_alive = config->keep_alive;
3065
3066  /* Done if proto is not changing. */
3067  if (config->proto == sc->config.proto)
3068    return 0;
3069
3070  /* Close */
3071  sc->ifp->if_flags &= ~IFF_UP; /* down */
3072  sppp_ioctl(sc->ifp, SIOCSIFFLAGS, NULL);
3073
3074  /* Change line protocol. */
3075  LMC_BPF_DETACH(sc);
3076  switch (config->proto)
3077    {
3078    case PROTO_PPP:
3079      {
3080      sc->sppp->pp_flags &= ~PP_CISCO;
3081      LMC_BPF_ATTACH(sc, DLT_PPP, 4);
3082      sc->config.proto = PROTO_PPP;
3083      break;
3084      }
3085
3086    default:
3087    case PROTO_C_HDLC:
3088      {
3089      sc->sppp->pp_flags |=  PP_CISCO;
3090      LMC_BPF_ATTACH(sc, DLT_C_HDLC, 4);
3091      sc->config.proto = PROTO_C_HDLC;
3092      break;
3093      }
3094
3095    } /* switch(config->proto) */
3096
3097  /* Open */
3098  sc->ifp->if_flags |= IFF_UP; /* up and not running */
3099  sppp_ioctl(sc->ifp, SIOCSIFFLAGS, NULL);
3100
3101  return 0;
3102  }
3103
3104static int  /* never fails */
3105sppp_stack_attach(softc_t *sc, struct config *config)
3106  {
3107  sc->sppp = &sc->spppcom;
3108
3109  LMC_BPF_ATTACH(sc, DLT_RAW, 0);
3110  sppp_attach(sc->ifp);
3111  sc->sppp->pp_tls = sppp_tls;
3112  sc->sppp->pp_tlf = sppp_tlf;
3113  config->keep_alive = 1;
3114
3115  sc->config.stack = STACK_SPPP;
3116  sc->stack = &sppp_stack;
3117
3118  return 0;
3119  }
3120
3121static int  /* never fails */
3122sppp_stack_detach(softc_t *sc)
3123  {
3124  sc->ifp->if_flags &= ~IFF_UP; /* down */
3125  sppp_ioctl(sc->ifp, SIOCSIFFLAGS, NULL); /* close() */
3126  sppp_detach(sc->ifp);
3127  LMC_BPF_DETACH(sc);
3128
3129  ifnet_setup(sc->ifp);
3130  sc->config.stack = STACK_NONE;
3131  sc->config.proto = PROTO_NONE;
3132  sc->stack = NULL;
3133
3134  return 0;
3135  }
3136
3137/* Callout from SPPP: */
3138static void
3139sppp_tls(struct sppp *sppp)
3140  {
3141  /* Calling pp_up/down() required by PPP mode in OpenBSD. */
3142  /* Calling pp_up/down() panics      PPP mode in NetBSD. */
3143  /* Calling pp_up/down() breaks    Cisco mode in FreeBSD. */
3144  if (!(sppp->pp_flags & PP_CISCO))    /* not Cisco */
3145    sppp->pp_up(sppp);
3146  }
3147
3148/* Callout from SPPP: */
3149static void
3150sppp_tlf(struct sppp *sppp)
3151  {
3152  /* Calling pp_up/down() required by PPP mode in OpenBSD. */
3153  /* Calling pp_up/down() panics      PPP mode in NetBSD. */
3154  /* Calling pp_up/down() breaks    Cisco mode in FreeBSD. */
3155  if (!(sppp->pp_flags & PP_CISCO))    /* not Cisco */
3156    sppp->pp_down(sppp);
3157  }
3158
3159#endif /* SPPP */
3160
3161/* RawIP is built into the driver. */
3162
3163static struct stack rawip_stack =
3164  {
3165#if IFNET
3166  .ioctl    = rawip_ioctl,
3167  .input    = rawip_input,
3168  .output   = rawip_output,
3169#elif NETDEV
3170  .ioctl    = rawip_ioctl,
3171  .type     = rawip_type,
3172  .mtu      = rawip_mtu,
3173#endif
3174  .watchdog = rawip_watchdog,
3175  .open     = rawip_open,
3176  .attach   = rawip_attach,
3177  .detach   = rawip_detach,
3178  };
3179
3180#if IFNET
3181
3182static int  /* context: process */
3183rawip_ioctl(softc_t *sc, u_long cmd, void *data)
3184  {
3185  struct ifreq *ifr = (struct ifreq *) data;
3186  int error = 0;
3187
3188  switch (cmd)
3189    {
3190    case SIOCADDMULTI:
3191    case SIOCDELMULTI:
3192      if (sc->config.debug)
3193        printf("%s: rawip_ioctl: SIOCADD/DELMULTI\n", NAME_UNIT);
3194    case SIOCSIFFLAGS:
3195      error = ifioctl_common(sc->ifp, cmd, data);
3196      break;
3197    case SIOCAIFADDR:
3198    case SIOCSIFDSTADDR:
3199      break;
3200    case SIOCINITIFADDR:
3201      sc->ifp->if_flags |= IFF_UP; /* a Unix tradition */
3202      break;
3203    case SIOCSIFMTU:
3204      if ((ifr->ifr_mtu < 72) || (ifr->ifr_mtu > 65535))
3205        error = EINVAL;
3206      else if ((error = ifioctl_common(sc->ifp, cmd, data)) == ENETRESET)
3207        error = 0;
3208      break;
3209    default:
3210      error = EINVAL;
3211      break;
3212    }
3213
3214  return error;
3215  }
3216
3217static void  /* context: interrupt */
3218rawip_input(softc_t *sc, struct mbuf *mbuf)
3219  {
3220  ifnet_input(sc->ifp, mbuf);
3221  }
3222
3223static void  /* context: interrupt */
3224rawip_output(softc_t *sc)
3225  {
3226  IFQ_DEQUEUE(&sc->ifp->if_snd, sc->tx_mbuf);
3227  }
3228
3229#elif NETDEV
3230
3231static int  /* context: process */
3232rawip_ioctl(softc_t *sc, struct ifreq *ifr, int cmd)
3233  {
3234  if (sc->config.debug)
3235    printk("%s: rawip_ioctl; cmd=0x%08x\n", NAME_UNIT, cmd);
3236  return -EINVAL;
3237  }
3238
3239static int  /* context: interrupt */
3240rawip_type(softc_t *sc, struct sk_buff *skb)
3241  {
3242  if (skb->data[0]>>4 == 4)
3243    return htons(ETH_P_IP);
3244  else if (skb->data[0]>>4 == 6)
3245    return htons(ETH_P_IPV6);
3246  else
3247    return htons(ETH_P_HDLC);
3248  }
3249
3250static int  /* Process Context */
3251rawip_mtu(softc_t *sc, int mtu)
3252  {
3253  return ((mtu < 72) || (mtu > 65535)) ? -EINVAL : 0;
3254  }
3255
3256#endif /* IFNET */
3257
3258static void  /* context: softirq */
3259rawip_watchdog(softc_t *sc)
3260  {
3261#if IFNET
3262  if ((sc->status.link_state == STATE_UP) &&
3263      (sc->ifp->if_flags & IFF_UP))
3264    sc->ifp->if_flags |= IFF_RUNNING;
3265  if ((sc->status.link_state != STATE_UP) ||
3266     !(sc->ifp->if_flags & IFF_UP))
3267    sc->ifp->if_flags &= ~IFF_RUNNING;
3268#endif /* IFNET */
3269
3270  /* Report current line protocol. */
3271  sc->status.stack = STACK_RAWIP;
3272  sc->status.proto = PROTO_IP_HDLC;
3273  }
3274
3275static int
3276rawip_open(softc_t *sc, struct config *config)
3277  {
3278  sc->config.proto = PROTO_IP_HDLC;
3279
3280  return 0;
3281  }
3282
3283static int
3284rawip_attach(softc_t *sc, struct config *config)
3285  {
3286#if IFNET
3287  LMC_BPF_ATTACH(sc, DLT_RAW, 0);
3288#endif
3289
3290  sc->config.stack = STACK_RAWIP;
3291  sc->stack = &rawip_stack;
3292
3293  return 0;
3294  }
3295
3296static int
3297rawip_detach(softc_t *sc)
3298  {
3299#if IFNET
3300  LMC_BPF_DETACH(sc);
3301  ifnet_setup(sc->ifp);
3302#elif NETDEV
3303  netdev_setup(sc->netdev);
3304#endif
3305
3306  sc->config.stack = STACK_NONE;
3307  sc->config.proto = PROTO_NONE;
3308  sc->stack = NULL;
3309
3310  return 0;
3311  }
3312
3313#if IFNET
3314
3315/* Called to give a newly arrived pkt to higher levels. */
3316/* Called from rxintr_cleanup() with bottom_lock held. */
3317/* This is only used with rawip_stack on a BSD. */
3318static void
3319ifnet_input(struct ifnet *ifp, struct mbuf *mbuf)
3320  {
3321  softc_t *sc = IFP2SC(ifp);
3322  struct ifqueue *intrq;
3323  int isr = 0;
3324
3325  intrq = NULL; /* surpress compiler warning */
3326# if INET
3327  if (mbuf->m_data[0]>>4 == 4)
3328    {
3329    isr = NETISR_IP;
3330    intrq = &ipintrq;
3331    }
3332# endif /* INET */
3333
3334# if INET6
3335  if (mbuf->m_data[0]>>4 == 6)
3336    {
3337    isr = NETISR_IPV6;
3338    intrq = &ip6intrq;
3339    }
3340# endif /* INET6 */
3341
3342  if (isr)
3343    {
3344    if (!IF_QFULL(intrq))
3345      {
3346      /* ifnet_input() ENQUEUES in a hard interrupt. */
3347      /* ip_input() DEQUEUES in a soft interrupt. */
3348      /* Some BSD QUEUE routines are not interrupt-safe. */
3349      DISABLE_INTR; /* noop in FreeBSD */
3350      IF_ENQUEUE(intrq, mbuf);
3351      ENABLE_INTR;  /* noop in FreeBSD */
3352      schednetisr(isr); /* wake up the network code */
3353      }
3354    else /* intrq is full */
3355      {
3356      m_freem(mbuf);
3357      sc->status.cntrs.idrops++;
3358      if (sc->config.debug)
3359        printf("%s: ifnet_input: rx pkt dropped: intrq full\n", NAME_UNIT);
3360      }
3361    }
3362  else /* isr is zero */
3363    {
3364    m_freem(mbuf);
3365    sc->status.cntrs.idrops++;
3366    if (sc->config.debug)
3367      printf("%s: ifnet_input: rx pkt dropped: not IPv4 or IPv6\n", NAME_UNIT);
3368    }
3369  }
3370
3371/* sppp and p2p replace this with their own proc.
3372 * This is only used with rawip_stack on a BSD.
3373 * This procedure is very similar to ng_rcvdata().
3374 */
3375static int  /* context: process */
3376ifnet_output(struct ifnet *ifp, struct mbuf *m,
3377 const struct sockaddr *dst, struct rtentry *rt)
3378  {
3379  softc_t *sc = IFP2SC(ifp);
3380  int error = 0;
3381
3382  /* Fail if the link is down. */
3383  if (sc->status.link_state != STATE_UP)
3384    {
3385    m_freem(m);
3386    sc->status.cntrs.odrops++;
3387    if (sc->config.debug)
3388      printf("%s: ifnet_output: tx pkt dropped: link down\n", NAME_UNIT);
3389    return ENETDOWN;
3390    }
3391
3392  /* ifnet_output() ENQUEUEs in a syscall or softirq. */
3393  /* txintr_setup() DEQUEUEs in a hard interrupt. */
3394  /* Some BSD QUEUE routines are not interrupt-safe. */
3395  {
3396  DISABLE_INTR; /* noop in FreeBSD */
3397  IFQ_ENQUEUE(&ifp->if_snd, m, NULL, error);
3398  ENABLE_INTR; /* noop in FreeBSD */
3399  }
3400
3401  if (error)
3402    {
3403    sc->status.cntrs.odrops++;
3404    if (sc->config.debug)
3405      printf("%s: ifnet_output: tx pkt dropped: IFQ_ENQUEUE(): error %d\n",
3406       NAME_UNIT, error);
3407    }
3408  else
3409    /* Process tx pkts; do not process rx pkts. */
3410    lmc_interrupt(sc, 0, 0);
3411
3412  return error;
3413  }
3414
3415static int  /* context: process */
3416ifnet_ioctl(struct ifnet *ifp, u_long cmd, void *data)
3417  {
3418  softc_t *sc = IFP2SC(ifp);
3419  struct ifreq *ifr = (struct ifreq *) data;
3420  int error = 0;
3421
3422  /* Aquire ioctl/watchdog interlock. */
3423  if ((error = TOP_LOCK(sc))) return error;
3424
3425  switch (cmd)
3426    {
3427    /* Catch the IOCTLs used by lmcconfig. */
3428    case LMCIOCGSTAT:
3429    case LMCIOCGCFG:
3430    case LMCIOCSCFG:
3431    case LMCIOCREAD:
3432    case LMCIOCWRITE:
3433    case LMCIOCTL:
3434      error = lmc_ioctl(sc, cmd, data);
3435      break;
3436
3437    case SIOCSIFCAP:
3438#  if DEVICE_POLLING
3439      if ((ifr->ifr_reqcap & IFCAP_POLLING) &&
3440       !(ifp->if_capenable & IFCAP_POLLING) &&
3441       !(error = ether_poll_register(bsd_poll, ifp)))
3442        { /* enable polling */
3443        WRITE_CSR(sc, TLP_INT_ENBL, TLP_INT_DISABLE);
3444        ifp->if_capenable |= IFCAP_POLLING;
3445        }
3446      else if (!(ifr->ifr_reqcap & IFCAP_POLLING) &&
3447              (ifp->if_capenable & IFCAP_POLLING) &&
3448             !(error = ether_poll_deregister(ifp)))
3449        { /* disable polling */
3450        ifp->if_capenable &= ~IFCAP_POLLING;
3451        WRITE_CSR(sc, TLP_INT_ENBL, TLP_INT_TXRX);
3452        }
3453      else
3454        error = EINVAL;
3455#  endif /* DEVICE_POLLING */
3456      break;
3457
3458    case SIOCSIFMEDIA: /* calls lmc_ifmedia_change() */
3459    case SIOCGIFMEDIA: /* calls ifmedia_status() */
3460      error = ifmedia_ioctl(ifp, ifr, &sc->ifm, cmd);
3461      break;
3462
3463
3464    /* Pass the rest to the line protocol. */
3465    default:
3466      if (sc->stack)
3467        error = sc->stack->ioctl(sc, cmd, data);
3468      else
3469        error = ENOSYS;
3470      break;
3471    }
3472
3473  /* release ioctl/watchdog interlock */
3474  TOP_UNLOCK(sc);
3475
3476  if (error && sc->config.debug)
3477    printf("%s: ifnet_ioctl: op=IO%s%s len=%3lu grp='%c' num=%3lu err=%d\n",
3478     NAME_UNIT, cmd&IOC_IN ? "W":"", cmd&IOC_OUT ? "R":"",
3479     IOCPARM_LEN(cmd), (char)IOCGROUP(cmd), cmd&0xFF, error);
3480
3481  return error;
3482  }
3483
3484static void  /* context: process */
3485ifnet_start(struct ifnet *ifp)
3486  {
3487  softc_t *sc = IFP2SC(ifp);
3488
3489  /* Process tx pkts; do not process rx pkts. */
3490  lmc_interrupt(sc, 0, 0);
3491  }
3492
3493static void  /* context: softirq */
3494ifnet_watchdog(struct ifnet *ifp)
3495  {
3496  softc_t *sc = IFP2SC(ifp);
3497  struct cntrs *cntrs = &sc->status.cntrs;
3498
3499  lmc_watchdog(sc); /* updates link_state */
3500
3501  if (sc->status.link_state == STATE_UP)
3502    ifp->if_link_state = LINK_STATE_UP;
3503  else
3504    ifp->if_link_state = LINK_STATE_DOWN;
3505
3506  /* Copy statistics from sc to ifp. */
3507  ifp->if_baudrate = sc->status.tx_speed;
3508  ifp->if_ibytes   = cntrs->ibytes;
3509  ifp->if_obytes   = cntrs->obytes;
3510  ifp->if_ipackets = cntrs->ipackets;
3511  ifp->if_opackets = cntrs->opackets;
3512  ifp->if_ierrors  = cntrs->ierrors;
3513  ifp->if_oerrors  = cntrs->oerrors;
3514  ifp->if_iqdrops  = cntrs->idrops;
3515
3516  /* If the interface debug flag is set, set the driver debug flag. */
3517  if (sc->ifp->if_flags & IFF_DEBUG)
3518    sc->config.debug = 1;
3519
3520  /* Call this procedure again after one second. */
3521  ifp->if_timer = 1;
3522  }
3523
3524/* This setup is for RawIP; SPPP and P2P change many items. */
3525/* Note the similarity to linux's netdev_setup(). */
3526static void
3527ifnet_setup(struct ifnet *ifp)
3528  {
3529  ifp->if_flags    = IFF_POINTOPOINT;
3530  ifp->if_flags   |= IFF_SIMPLEX;
3531  ifp->if_flags   |= IFF_NOARP;
3532  ifp->if_input    = ifnet_input;
3533  ifp->if_output   = ifnet_output;
3534  ifp->if_start    = ifnet_start;
3535  ifp->if_ioctl    = ifnet_ioctl;
3536  ifp->if_watchdog = ifnet_watchdog;
3537  ifp->if_timer    = 1;
3538  ifp->if_type     = IFT_PTPSERIAL;
3539  ifp->if_addrlen  = 0;
3540  ifp->if_hdrlen   = 0;
3541  ifp->if_mtu      = MAX_DESC_LEN;
3542  }
3543
3544/* Attach the ifnet kernel interface. */
3545/* context: kernel (boot) or process (syscall) */
3546static int
3547ifnet_attach(softc_t *sc)
3548  {
3549# if   SPPP
3550  sc->ifp = &sc->spppcom.pp_if;
3551# elif P2P
3552  sc->ifp = &sc->p2pcom.p2p_if;
3553# else
3554  sc->ifp = &sc->ifnet;
3555# endif
3556
3557  sc->ifp->if_softc = sc;
3558  ifnet_setup(sc->ifp);
3559
3560# if DEVICE_POLLING
3561  sc->ifp->if_capabilities |= IFCAP_POLLING;
3562# endif
3563
3564  /* Every OS does it differently! */
3565  strlcpy(sc->ifp->if_xname, device_xname(&sc->dev), IFNAMSIZ);
3566
3567  IFQ_SET_MAXLEN(&sc->ifp->if_snd, SNDQ_MAXLEN);
3568  IFQ_SET_READY(&sc->ifp->if_snd);
3569
3570  if_attach(sc->ifp);
3571
3572  if_alloc_sadl(sc->ifp);
3573
3574  ifmedia_setup(sc);
3575
3576  return 0;
3577  }
3578
3579/* Detach the ifnet kernel interface. */
3580/* context: kernel (boot) or process (syscall). */
3581static void
3582ifnet_detach(softc_t *sc)
3583  {
3584  ifmedia_delete_instance(&sc->ifm, IFM_INST_ANY);
3585
3586# if DEVICE_POLLING
3587  if (sc->ifp->if_capenable & IFCAP_POLLING)
3588    ether_poll_deregister(sc->ifp);
3589# endif
3590
3591  IFQ_PURGE(&sc->ifp->if_snd);
3592
3593  if_free_sadl(sc->ifp);
3594
3595  if_detach(sc->ifp);
3596
3597  }
3598
3599static void
3600ifmedia_setup(softc_t *sc)
3601  {
3602  /* Initialize ifmedia mechanism. */
3603  ifmedia_init(&sc->ifm, IFM_OMASK | IFM_GMASK | IFM_IMASK,
3604   lmc_ifmedia_change, ifmedia_status);
3605
3606  ifmedia_add(&sc->ifm, IFM_ETHER | IFM_NONE, 0, NULL);
3607  ifmedia_set(&sc->ifm, IFM_ETHER | IFM_NONE);
3608  }
3609
3610/* SIOCSIFMEDIA: context: process. */
3611static int
3612lmc_ifmedia_change(struct ifnet *ifp)
3613  {
3614  softc_t *sc = IFP2SC(ifp);
3615  struct config config = sc->config;
3616  int media = sc->ifm.ifm_media;
3617  int error;
3618
3619
3620  /* ifconfig lmc0 mediaopt loopback */
3621  if (media & IFM_LOOP)
3622    config.loop_back = CFG_LOOP_TULIP;
3623  else
3624    config.loop_back = CFG_LOOP_NONE;
3625
3626  error = open_proto(sc, &config);
3627  tulip_loop(sc, &config);
3628  sc->card->attach(sc, &config);
3629
3630  return error;
3631  }
3632
3633/* SIOCGIFMEDIA: context: process. */
3634static void
3635ifmedia_status(struct ifnet *ifp, struct ifmediareq *ifmr)
3636  {
3637  softc_t *sc = IFP2SC(ifp);
3638
3639  ifmr->ifm_status = IFM_AVALID;
3640  if (sc->status.link_state == STATE_UP)
3641    ifmr->ifm_status |= IFM_ACTIVE;
3642
3643  if (sc->config.loop_back != CFG_LOOP_NONE)
3644    ifmr->ifm_active |= IFM_LOOP;
3645
3646  }
3647
3648#endif  /* IFNET */
3649
3650#if NETDEV
3651
3652/* This net_device method is called when IFF_UP goes true. */
3653static int  /* context: process */
3654netdev_open(struct net_device *netdev)
3655  {
3656  softc_t *sc = NETDEV2SC(netdev);
3657
3658  WRITE_CSR(sc, TLP_INT_ENBL, TLP_INT_TXRX);
3659  netif_start_queue(sc->netdev);
3660  set_ready(sc, 1);
3661
3662  return 0;
3663  }
3664
3665/* This net_device method is called when IFF_UP goes false. */
3666static int  /* context: process */
3667netdev_stop(struct net_device *netdev)
3668  {
3669  softc_t *sc = NETDEV2SC(netdev);
3670
3671  set_ready(sc, 0);
3672  netif_stop_queue(sc->netdev);
3673  WRITE_CSR(sc, TLP_INT_ENBL, TLP_INT_DISABLE);
3674
3675  return 0;
3676  }
3677
3678/* This net_device method hands outgoing packets to the transmitter. */
3679/* With txintr_setup(), it implements output flow control. */
3680static int  /* context: netdev->xmit_lock held; BHs disabled */
3681netdev_start(struct sk_buff *skb, struct net_device *netdev)
3682  {
3683  softc_t *sc = NETDEV2SC(netdev);
3684
3685  if (sc->tx_skb == NULL)
3686    {
3687    /* Put this skb where the transmitter will see it. */
3688    sc->tx_skb = skb;
3689
3690    /* Process tx pkts; do not process rx pkts. */
3691    lmc_interrupt(sc, 0, 0);
3692
3693    return NETDEV_TX_OK;
3694    }
3695  else
3696    {
3697    /* txintr_setup() calls netif_wake_queue(). */
3698    netif_stop_queue(netdev);
3699    return NETDEV_TX_BUSY;
3700    }
3701  }
3702
3703# if NAPI
3704
3705/* This net_device method services the card without interrupts. */
3706/* With rxintr_cleanup(), it implements input flow control. */
3707static int  /* context: softirq */
3708netdev_poll(struct net_device *netdev, int *budget)
3709  {
3710  softc_t *sc = NETDEV2SC(netdev);
3711  int received;
3712
3713  /* Handle the card interrupt with kernel ints enabled. */
3714  /* Allow processing up to netdev->quota incoming packets. */
3715  /* This is the ONLY time lmc_interrupt() may process rx pkts. */
3716  /* Otherwise (sc->quota == 0) and rxintr_cleanup() is a NOOP. */
3717  lmc_interrupt(sc, min(netdev->quota, *budget), 0);
3718
3719  /* Report number of rx packets processed. */
3720  received = netdev->quota - sc->quota;
3721  netdev->quota -= received;
3722  *budget       -= received;
3723
3724  /* If quota prevented processing all rx pkts, leave rx ints disabled. */
3725  if (sc->quota == 0)  /* this is off by one...but harmless */
3726    {
3727    WRITE_CSR(sc, TLP_INT_ENBL, TLP_INT_TX);
3728    return 1; /* more pkts to handle -- reschedule */
3729    }
3730
3731  /* Remove self from poll list. */
3732  netif_rx_complete(netdev);
3733
3734  /* Enable card interrupts. */
3735  WRITE_CSR(sc, TLP_INT_ENBL, TLP_INT_TXRX);
3736
3737  return 0; /* all pkts handled -- success */
3738  }
3739
3740# endif /* NAPI */
3741
3742/* This net_device method handles IOCTL syscalls. */
3743static int  /* context: process */
3744netdev_ioctl(struct net_device *netdev, struct ifreq *ifr, int cmd)
3745  {
3746  softc_t *sc = NETDEV2SC(netdev);
3747  int error = 0;
3748
3749  /* Aquire ioctl/watchdog interlock. */
3750  if ((error = TOP_LOCK(sc))) return error;
3751
3752  if ((cmd >= SIOCDEVPRIVATE) && (cmd <= SIOCDEVPRIVATE+15))
3753    {
3754    struct iohdr *iohdr = (struct iohdr *)ifr;
3755    u_int16_t direction = iohdr->direction;
3756    u_int16_t length = iohdr->length;
3757    char *user_addr = (char *)iohdr->iohdr;
3758    char *kern_addr = NULL;
3759
3760    if (iohdr->cookie != NGM_LMC_COOKIE)
3761      error = -EINVAL;
3762
3763    /* Emulate a BSD-style IOCTL syscall. */
3764    if (!error)
3765      error = (kern_addr = kmalloc(length, GFP_KERNEL)) ? 0: -ENOMEM;
3766    if (!error && (direction & DIR_IOW))
3767      error = copy_from_user(kern_addr, user_addr, length);
3768    if (!error)
3769      error = -lmc_ioctl(sc, (unsigned long)cmd, kern_addr);
3770    if (!error && (direction & DIR_IOR))
3771      error = copy_to_user(user_addr, kern_addr, length);
3772    kfree(kern_addr);
3773    }
3774  else if (sc->stack)
3775    error = sc->stack->ioctl(sc, ifr, cmd);
3776  else
3777    error = -ENOSYS;
3778# if GEN_HDLC
3779  /* If generic-HDLC is present but not the currently-attached
3780   * stack, call hdlc_ioctl() anyway because proto must
3781   * be set using SIOCWANDEV or hdlc_open() will fail.
3782   */
3783  if (sc->stack != &gen_hdlc_stack)
3784    hdlc_ioctl(sc->netdev, ifr, cmd); /* ignore error result */
3785# endif
3786
3787  /* Release ioctl/watchdog interlock. */
3788  TOP_UNLOCK(sc);
3789
3790  if (error && sc->config.debug)
3791    printk("%s: netdev_ioctl; cmd=0x%08x error=%d\n",
3792     NAME_UNIT, cmd, error);
3793
3794  return error;
3795  }
3796
3797/* This net_device method sets the Maximum Tranmit Unit. */
3798/* This driver does not limit MTU; stacks and protos do. */
3799static int
3800netdev_mtu(struct net_device *netdev, int mtu)
3801  {
3802  softc_t *sc = NETDEV2SC(netdev);
3803  int error = 0;
3804
3805  if (sc->stack)
3806    error = sc->stack->mtu(sc, mtu);
3807  else
3808    error = -ENOSYS;
3809
3810  if (!error)
3811     netdev->mtu = mtu;
3812
3813  return error;
3814  }
3815
3816/* This net_device method restarts the transmitter if it hangs. */
3817static void  /* BHs disabled */
3818netdev_timeout(struct net_device *netdev)
3819  {
3820  softc_t *sc = NETDEV2SC(netdev);
3821
3822  /* Process tx pkts; do not process rx pkts. */
3823  lmc_interrupt(sc, 0, 0);
3824  }
3825
3826/* This net_device method returns a pointer to device statistics. */
3827static struct net_device_stats *  /* context: process */
3828netdev_stats(struct net_device *netdev)
3829  {
3830  softc_t *sc = NETDEV2SC(netdev);
3831
3832# if GEN_HDLC
3833  return &sc->hdlcdev->stats;
3834# else
3835  return &sc->netdev_stats;
3836# endif
3837  }
3838
3839static void  /* context: softirq */
3840netdev_watchdog(unsigned long softc)
3841  {
3842  softc_t *sc = (softc_t *)softc;
3843  struct cntrs *cntrs = &sc->status.cntrs;
3844  struct net_device_stats *stats = netdev_stats(sc->netdev);
3845
3846  lmc_watchdog(sc); /* updates link_state */
3847
3848  /* Notice when the link comes up. */
3849  if ((sc->last_link_state != STATE_UP) &&
3850    (sc->status.link_state == STATE_UP))
3851    {
3852    netif_wake_queue(sc->netdev);
3853    netif_carrier_on(sc->netdev);
3854    }
3855
3856  /* Notice when the link goes down. */
3857  if ((sc->last_link_state == STATE_UP) &&
3858    (sc->status.link_state != STATE_UP))
3859    {
3860    netif_tx_disable(sc->netdev);
3861    netif_carrier_off(sc->netdev);
3862    }
3863
3864  /* Copy statistics from sc to netdev. */
3865  stats->rx_bytes         = cntrs->ibytes;
3866  stats->tx_bytes         = cntrs->obytes;
3867  stats->rx_packets       = cntrs->ipackets;
3868  stats->tx_packets       = cntrs->opackets;
3869  stats->rx_errors        = cntrs->ierrors;
3870  stats->tx_errors        = cntrs->oerrors;
3871  stats->rx_dropped       = cntrs->idrops;
3872  stats->rx_missed_errors = cntrs->missed;
3873  stats->tx_dropped       = cntrs->odrops;
3874  stats->rx_fifo_errors   = cntrs->fifo_over;
3875  stats->rx_over_errors   = cntrs->overruns;
3876  stats->tx_fifo_errors   = cntrs->fifo_under;
3877/*stats->tx_under_errors  = cntrs=>underruns; */
3878
3879  /* If the interface debug flag is set, set the driver debug flag. */
3880  if (sc->netdev->flags & IFF_DEBUG)
3881    sc->config.debug = 1;
3882
3883  /* Call this procedure again after one second. */
3884  sc->wd_timer.expires = jiffies + HZ -8; /* -8 is a FUDGE factor */
3885  add_timer(&sc->wd_timer);
3886  }
3887
3888/* This setup is for RawIP; Generic-HDLC changes many items. */
3889/* Note the similarity to BSD's ifnet_setup(). */
3890static void
3891netdev_setup(struct net_device *netdev)
3892  {
3893  netdev->flags           = IFF_POINTOPOINT;
3894  netdev->flags          |= IFF_NOARP;
3895  netdev->open            = netdev_open;
3896  netdev->stop            = netdev_stop;
3897  netdev->hard_start_xmit = netdev_start;
3898# if NAPI
3899  netdev->poll            = netdev_poll;
3900  netdev->weight          = 32; /* sc->rxring.num_descs; */
3901# endif
3902  netdev->rebuild_header  = NULL; /* no arp */
3903  netdev->hard_header     = NULL; /* no arp */
3904  netdev->do_ioctl        = netdev_ioctl;
3905  netdev->change_mtu      = netdev_mtu;
3906  netdev->tx_timeout      = netdev_timeout;
3907  netdev->get_stats       = netdev_stats;
3908  netdev->watchdog_timeo  = 1 * HZ;
3909  netdev->mtu             = MAX_DESC_LEN;
3910  netdev->type            = ARPHRD_HDLC;
3911  netdev->hard_header_len = 16;
3912  netdev->addr_len        = 0;
3913  netdev->tx_queue_len    = SNDQ_MAXLEN;
3914/* The receiver generates frag-lists for packets >4032 bytes.   */
3915/* The transmitter accepts scatter/gather lists and frag-lists. */
3916/* However Linux linearizes outgoing packets since our hardware */
3917/*  does not compute soft checksums.  All that work for nothing! */
3918/*netdev->features       |= NETIF_F_SG; */
3919/*netdev->features       |= NETIF_F_FRAGLIST; */
3920  }
3921
3922/* Attach the netdevice kernel interface. */
3923/* context: kernel (boot) or process (syscall). */
3924static int
3925netdev_attach(softc_t *sc)
3926  {
3927  int error;
3928
3929# if GEN_HDLC /* generic-hdlc line protocol pkg configured */
3930
3931  /* Allocate space for the HDLC network device struct. */
3932  /* Allocating a netdev and attaching to generic-HDLC should be separate. */
3933  if ((sc->netdev = alloc_hdlcdev(sc)) == NULL)
3934    {
3935    printk("%s: netdev_attach: alloc_hdlcdev() failed\n", DEVICE_NAME);
3936    return -ENOMEM;
3937    }
3938
3939  /* Initialize the basic network device struct. */
3940  /* This clobbers some netdev stuff set by alloc_hdlcdev(). */
3941  /* Our get_stats() and change_mtu() do the right thing. */
3942  netdev_setup(sc->netdev);
3943
3944  /* HACK: make the private eco-net pointer -> struct softc. */
3945  sc->netdev->ec_ptr = sc;
3946
3947  /* Cross-link pcidev and netdev. */
3948  SET_NETDEV_DEV(sc->netdev, &sc->pcidev->dev);
3949  sc->netdev->mem_end   = pci_resource_end(sc->pcidev, 1);
3950  sc->netdev->mem_start = pci_resource_start(sc->pcidev, 1);
3951  sc->netdev->base_addr = pci_resource_start(sc->pcidev, 0);
3952  sc->netdev->irq       = sc->pcidev->irq;
3953
3954  /* Initialize the HDLC extension to the network device. */
3955  sc->hdlcdev         = sc->netdev->priv;
3956  sc->hdlcdev->attach = gen_hdlc_card_params;
3957  sc->hdlcdev->xmit   = netdev_start; /* the REAL hard_start_xmit() */
3958
3959  if ((error = register_hdlc_device(sc->netdev)))
3960    {
3961    printk("%s: register_hdlc_device(): error %d\n", DEVICE_NAME, error);
3962    free_netdev(sc->netdev);
3963    return error;
3964    }
3965
3966# else
3967
3968  /* Allocate and initialize the basic network device struct. */
3969  if ((sc->netdev = alloc_netdev(0, DEVICE_NAME"%d", netdev_setup)) == NULL)
3970    {
3971    printk("%s: netdev_attach: alloc_netdev() failed\n", DEVICE_NAME);
3972    return -ENOMEM;
3973    }
3974
3975  /* HACK: make the private eco-net pointer -> struct softc. */
3976  sc->netdev->ec_ptr = sc;
3977
3978  /* Cross-link pcidev and netdev. */
3979  SET_NETDEV_DEV(sc->netdev, &sc->pcidev->dev);
3980  sc->netdev->mem_end   = pci_resource_end(sc->pcidev, 1);
3981  sc->netdev->mem_start = pci_resource_start(sc->pcidev, 1);
3982  sc->netdev->base_addr = pci_resource_start(sc->pcidev, 0);
3983  sc->netdev->irq       = sc->pcidev->irq;
3984
3985  if ((error = register_netdev(sc->netdev)))
3986    {
3987    printk("%s: register_netdev(): error %d\n", DEVICE_NAME, error);
3988    free_netdev(sc->netdev);
3989    return error;
3990    }
3991
3992# endif /* GEN_HDLC */
3993
3994  /* Arrange to call netdev_watchdog() once a second. */
3995  init_timer(&sc->wd_timer);
3996  sc->wd_timer.expires  = jiffies + HZ; /* now plus one second */
3997  sc->wd_timer.function = &netdev_watchdog;
3998  sc->wd_timer.data     = (unsigned long) sc;
3999  add_timer(&sc->wd_timer);
4000
4001  return 0; /* success */
4002  }
4003
4004/* Detach the netdevice kernel interface. */
4005/* context: kernel (boot) or process (syscall). */
4006static void
4007netdev_detach(softc_t *sc)
4008  {
4009  if (sc->pcidev == NULL) return;
4010  if (sc->netdev == NULL) return;
4011
4012  netdev_stop(sc->netdev); /* check for not inited */
4013  del_timer(&sc->wd_timer);
4014
4015# if GEN_HDLC
4016  unregister_hdlc_device(sc->netdev);
4017# else
4018  unregister_netdev(sc->netdev);
4019# endif
4020
4021  free_netdev(sc->netdev);
4022  }
4023
4024#endif /* NETDEV */
4025
4026
4027#if BSD
4028
4029/* There are TWO VERSIONS of interrupt/DMA code: Linux & BSD.
4030 * Handling Linux and the BSDs with CPP directives would
4031 *  make the code unreadable, so there are two versions.
4032 * Conceptually, the two versions do the same thing and
4033 *  lmc_interrupt() does not know they are different.
4034 *
4035 * We are "standing on the head of a pin" in these routines.
4036 * Tulip CSRs can be accessed, but nothing else is interrupt-safe!
4037 * Do NOT access: MII, GPIO, SROM, BIOSROM, XILINX, SYNTH, or DAC.
4038 */
4039
4040/* Initialize a DMA descriptor ring. */
4041/* context: kernel (boot) or process (syscall) */
4042static int  /* BSD version */
4043create_ring(softc_t *sc, struct desc_ring *ring, int num_descs)
4044  {
4045  struct dma_desc *descs;
4046  int size_descs = sizeof(struct dma_desc)*num_descs;
4047  int i, error = 0;
4048
4049  /* The DMA descriptor array must not cross a page boundary. */
4050  if (size_descs > PAGE_SIZE)
4051    {
4052    printf("%s: DMA descriptor array > PAGE_SIZE (%d)\n", NAME_UNIT,
4053     (u_int)PAGE_SIZE);
4054    return EINVAL;
4055    }
4056
4057
4058  /* Use the DMA tag passed to attach() for descriptors and buffers. */
4059  ring->tag = sc->pa_dmat;
4060
4061  /* Allocate wired physical memory for DMA descriptor array. */
4062  if ((error = bus_dmamem_alloc(ring->tag, size_descs, PAGE_SIZE, 0,
4063   ring->segs, 1, &ring->nsegs, BUS_DMA_NOWAIT)))
4064    {
4065    printf("%s: bus_dmamem_alloc(): error %d\n", NAME_UNIT, error);
4066    return error;
4067    }
4068
4069  /* Map physical address to kernel virtual address. */
4070  if ((error = bus_dmamem_map(ring->tag, ring->segs, ring->nsegs,
4071   size_descs, (void **)&ring->first, BUS_DMA_NOWAIT | BUS_DMA_COHERENT)))
4072    {
4073    printf("%s: bus_dmamem_map(): error %d\n", NAME_UNIT, error);
4074    return error;
4075    }
4076  descs = ring->first; /* suppress compiler warning about aliasing */
4077  memset(descs, 0, size_descs);
4078
4079  /* Allocate dmamap for PCI access to DMA descriptor array. */
4080  if ((error = bus_dmamap_create(ring->tag, size_descs, 1,
4081   size_descs, 0, BUS_DMA_NOWAIT | BUS_DMA_ALLOCNOW, &ring->map)))
4082    {
4083    printf("%s: bus_dmamap_create(): error %d\n", NAME_UNIT, error);
4084    return error;
4085    }
4086
4087  /* Map kernel virt addr to PCI bus addr for DMA descriptor array. */
4088  if ((error = bus_dmamap_load(ring->tag, ring->map, descs, size_descs,
4089   0, BUS_DMA_NOWAIT)))
4090    {
4091    printf("%s: bus_dmamap_load(): error %d\n", NAME_UNIT, error);
4092    return error;
4093    }
4094  ring->dma_addr = ring->map->dm_segs[0].ds_addr;
4095
4096  /* Allocate dmamaps for each DMA descriptor. */
4097  for (i=0; i<num_descs; i++)
4098    if ((error = bus_dmamap_create(ring->tag, MAX_DESC_LEN, 2,
4099     MAX_CHUNK_LEN, 0, BUS_DMA_NOWAIT | BUS_DMA_ALLOCNOW, &descs[i].map)))
4100      {
4101      printf("%s: bus_dmamap_create(): error %d\n", NAME_UNIT, error);
4102      return error;
4103      }
4104
4105
4106  ring->read  = descs;
4107  ring->write = descs;
4108  ring->first = descs;
4109  ring->last  = descs + num_descs -1;
4110  ring->last->control = TLP_DCTL_END_RING;
4111  ring->num_descs = num_descs;
4112  ring->size_descs = size_descs;
4113  ring->head = NULL;
4114  ring->tail = NULL;
4115
4116  return 0;
4117  }
4118
4119/* Destroy a DMA descriptor ring */
4120/* context: kernel (boot) or process (syscall) */
4121static void  /* BSD version */
4122destroy_ring(softc_t *sc, struct desc_ring *ring)
4123  {
4124  struct dma_desc *desc;
4125  struct mbuf *m;
4126
4127  /* Free queued mbufs. */
4128  while ((m = mbuf_dequeue(ring)))
4129    m_freem(m);
4130
4131  /* TX may have one pkt that is not on any queue. */
4132  if (sc->tx_mbuf)
4133    {
4134    m_freem(sc->tx_mbuf);
4135    sc->tx_mbuf = NULL;
4136    }
4137
4138  /* Unmap active DMA descriptors. */
4139  while (ring->read != ring->write)
4140    {
4141    bus_dmamap_unload(ring->tag, ring->read->map);
4142    if (ring->read++ == ring->last) ring->read = ring->first;
4143    }
4144
4145
4146  /* Free the dmamaps of all DMA descriptors. */
4147  for (desc=ring->first; desc!=ring->last+1; desc++)
4148    if (desc->map)
4149      bus_dmamap_destroy(ring->tag, desc->map);
4150  /* Unmap PCI address for DMA descriptor array. */
4151  if (ring->dma_addr)
4152    bus_dmamap_unload(ring->tag, ring->map);
4153  /* Free dmamap for DMA descriptor array. */
4154  if (ring->map)
4155    bus_dmamap_destroy(ring->tag, ring->map);
4156  /* Unmap kernel address for DMA descriptor array. */
4157  if (ring->first)
4158    bus_dmamem_unmap(ring->tag, (void *)ring->first, ring->size_descs);
4159  /* Free kernel memory for DMA descriptor array. */
4160  if (ring->segs[0].ds_addr)
4161    bus_dmamem_free(ring->tag, ring->segs, ring->nsegs);
4162
4163  }
4164
4165/* Singly-linked tail-queues hold mbufs with active DMA.
4166 * For RX, single mbuf clusters; for TX, mbuf chains are queued.
4167 * NB: mbufs are linked through their m_nextpkt field.
4168 * Callers must hold sc->bottom_lock; not otherwise locked.
4169 */
4170
4171/* Put an mbuf (chain) on the tail of the descriptor ring queue. */
4172static void  /* BSD version */
4173mbuf_enqueue(struct desc_ring *ring, struct mbuf *m)
4174  {
4175  m->m_nextpkt = NULL;
4176  if (ring->tail == NULL)
4177    ring->head = m;
4178  else
4179    ring->tail->m_nextpkt = m;
4180  ring->tail = m;
4181  }
4182
4183/* Get an mbuf (chain) from the head of the descriptor ring queue. */
4184static struct mbuf*  /* BSD version */
4185mbuf_dequeue(struct desc_ring *ring)
4186  {
4187  struct mbuf *m = ring->head;
4188  if (m)
4189    if ((ring->head = m->m_nextpkt) == NULL)
4190      ring->tail = NULL;
4191  return m;
4192  }
4193
4194/* Clean up after a packet has been received. */
4195static int  /* BSD version */
4196rxintr_cleanup(softc_t *sc)
4197  {
4198  struct desc_ring *ring = &sc->rxring;
4199  struct dma_desc *first_desc, *last_desc;
4200  struct mbuf *first_mbuf=NULL, *last_mbuf=NULL;
4201  struct mbuf *new_mbuf;
4202  int pkt_len, desc_len;
4203
4204  /* Input packet flow control (livelock prevention): */
4205  /* Give pkts to higher levels only if quota is > 0. */
4206  if (sc->quota <= 0) return 0;
4207
4208  /* This looks complicated, but remember: typically packets up */
4209  /*  to 2048 bytes long fit in one mbuf and use one descriptor. */
4210
4211  first_desc = last_desc = ring->read;
4212
4213  /* ASSERTION: If there is a descriptor in the ring and the hardware has */
4214  /*  finished with it, then that descriptor will have RX_FIRST_DESC set. */
4215  if ((ring->read != ring->write) && /* descriptor ring not empty */
4216     !(ring->read->status & TLP_DSTS_OWNER) && /* hardware done */
4217     !(ring->read->status & TLP_DSTS_RX_FIRST_DESC)) /* should be set */
4218    panic("%s: rxintr_cleanup: rx-first-descriptor not set.\n", NAME_UNIT);
4219
4220  /* First decide if a complete packet has arrived. */
4221  /* Run down DMA descriptors looking for one marked "last". */
4222  /* Bail out if an active descriptor is encountered. */
4223  /* Accumulate most significant bits of packet length. */
4224  pkt_len = 0;
4225  for (;;)
4226    {
4227    if (last_desc == ring->write) return 0;  /* no more descs */
4228    if (last_desc->status & TLP_DSTS_OWNER) return 0; /* still active */
4229    if (last_desc->status & TLP_DSTS_RX_LAST_DESC) break; /* end of packet */
4230    pkt_len += last_desc->length1 + last_desc->length2; /* entire desc filled */
4231    if (last_desc++->control & TLP_DCTL_END_RING) last_desc = ring->first; /* ring wrap */
4232    }
4233
4234  /* A complete packet has arrived; how long is it? */
4235  /* H/w ref man shows RX pkt length as a 14-bit field. */
4236  /* An experiment found that only the 12 LSBs work. */
4237  if (((last_desc->status>>16)&0xFFF) == 0) pkt_len += 4096; /* carry-bit */
4238  pkt_len = (pkt_len & 0xF000) + ((last_desc->status>>16) & 0x0FFF);
4239  /* Subtract the CRC length unless doing so would underflow. */
4240  if (pkt_len >= sc->config.crc_len) pkt_len -= sc->config.crc_len;
4241
4242  /* Run down DMA descriptors again doing the following:
4243   *  1) put pkt info in pkthdr of first mbuf,
4244   *  2) link mbufs,
4245   *  3) set mbuf lengths.
4246   */
4247  first_desc = ring->read;
4248  do
4249    {
4250    /* Read a DMA descriptor from the ring. */
4251    last_desc = ring->read;
4252    /* Advance the ring read pointer. */
4253    if (ring->read++ == ring->last) ring->read = ring->first;
4254
4255    /* Dequeue the corresponding cluster mbuf. */
4256    new_mbuf = mbuf_dequeue(ring);
4257    if (new_mbuf == NULL)
4258      panic("%s: rxintr_cleanup: expected an mbuf\n", NAME_UNIT);
4259
4260    desc_len = last_desc->length1 + last_desc->length2;
4261    /* If bouncing, copy bounce buf to mbuf. */
4262    DMA_SYNC(last_desc->map, desc_len, BUS_DMASYNC_POSTREAD);
4263    /* Unmap kernel virtual address to PCI bus address. */
4264    bus_dmamap_unload(ring->tag, last_desc->map);
4265
4266    /* 1) Put pkt info in pkthdr of first mbuf. */
4267    if (last_desc == first_desc)
4268      {
4269      first_mbuf = new_mbuf;
4270      first_mbuf->m_pkthdr.len   = pkt_len; /* total pkt length */
4271# if IFNET
4272      first_mbuf->m_pkthdr.rcvif = sc->ifp; /* how it got here */
4273# else
4274      first_mbuf->m_pkthdr.rcvif = NULL;
4275# endif
4276      }
4277    else /* 2) link mbufs. */
4278      {
4279      KASSERT(last_mbuf != NULL);
4280      last_mbuf->m_next = new_mbuf;
4281      /* M_PKTHDR should be set in the first mbuf only. */
4282      new_mbuf->m_flags &= ~M_PKTHDR;
4283      }
4284    last_mbuf = new_mbuf;
4285
4286    /* 3) Set mbuf lengths. */
4287    new_mbuf->m_len = (pkt_len >= desc_len) ? desc_len : pkt_len;
4288    pkt_len -= new_mbuf->m_len;
4289    } while ((last_desc->status & TLP_DSTS_RX_LAST_DESC)==0);
4290
4291  /* Decide whether to accept or to drop this packet. */
4292  /* RxHDLC sets MIIERR for bad CRC, abort and partial byte at pkt end. */
4293  if (!(last_desc->status & TLP_DSTS_RX_BAD) &&
4294   (sc->status.link_state == STATE_UP) &&
4295   (first_mbuf->m_pkthdr.len > 0))
4296    {
4297    /* Optimization: copy a small pkt into a small mbuf. */
4298    if (first_mbuf->m_pkthdr.len <= COPY_BREAK)
4299      {
4300      MGETHDR(new_mbuf, M_DONTWAIT, MT_DATA);
4301      if (new_mbuf)
4302        {
4303        new_mbuf->m_pkthdr.rcvif = first_mbuf->m_pkthdr.rcvif;
4304        new_mbuf->m_pkthdr.len   = first_mbuf->m_pkthdr.len;
4305        new_mbuf->m_len          = first_mbuf->m_len;
4306        memcpy(new_mbuf->m_data,   first_mbuf->m_data,
4307         first_mbuf->m_pkthdr.len);
4308        m_freem(first_mbuf);
4309        first_mbuf = new_mbuf;
4310        }
4311      }
4312
4313    /* Include CRC and one flag byte in input byte count. */
4314    sc->status.cntrs.ibytes += first_mbuf->m_pkthdr.len + sc->config.crc_len +1;
4315    sc->status.cntrs.ipackets++;
4316
4317    /* Berkeley Packet Filter */
4318    LMC_BPF_MTAP(sc, first_mbuf);
4319
4320    /* Give this good packet to the network stacks. */
4321    sc->quota--;
4322    if (sc->stack)
4323      sc->stack->input(sc, first_mbuf);
4324    else
4325      {
4326      m_freem(first_mbuf);
4327      sc->status.cntrs.idrops++;
4328      }
4329    }
4330  else if (sc->status.link_state != STATE_UP)
4331    {
4332    /* If the link is down, this packet is probably noise. */
4333    m_freem(first_mbuf);
4334    sc->status.cntrs.idrops++;
4335    if (sc->config.debug)
4336      printf("%s: rxintr_cleanup: rx pkt dropped: link down\n", NAME_UNIT);
4337    }
4338  else /* Log and drop this bad packet. */
4339    {
4340    if (sc->config.debug)
4341      printf("%s: RX bad pkt; len=%d %s%s%s%s\n",
4342       NAME_UNIT, first_mbuf->m_pkthdr.len,
4343       (last_desc->status & TLP_DSTS_RX_MII_ERR)  ? " miierr"  : "",
4344       (last_desc->status & TLP_DSTS_RX_DRIBBLE)  ? " dribble" : "",
4345       (last_desc->status & TLP_DSTS_RX_DESC_ERR) ? " descerr" : "",
4346       (last_desc->status & TLP_DSTS_RX_OVERRUN)  ? " overrun" : "");
4347    if (last_desc->status & TLP_DSTS_RX_OVERRUN)
4348      sc->status.cntrs.fifo_over++;
4349    else
4350      sc->status.cntrs.ierrors++;
4351    m_freem(first_mbuf);
4352    }
4353
4354  return 1; /* did something */
4355  }
4356
4357/* Setup (prepare) to receive a packet. */
4358/* Try to keep the RX descriptor ring full of empty buffers. */
4359static int  /* BSD version */
4360rxintr_setup(softc_t *sc)
4361  {
4362  struct desc_ring *ring = &sc->rxring;
4363  struct dma_desc *desc;
4364  struct mbuf *m;
4365  int desc_len;
4366  int error;
4367
4368  /* Ring is full if (wrap(write+1)==read) */
4369  if (((ring->write == ring->last) ? ring->first : ring->write+1) == ring->read)
4370    return 0;  /* ring is full; nothing to do */
4371
4372  /* Allocate a small mbuf and attach an mbuf cluster. */
4373  MGETHDR(m, M_DONTWAIT, MT_DATA);
4374  if (m == NULL)
4375    {
4376    sc->status.cntrs.rxbuf++;
4377    if (sc->config.debug)
4378      printf("%s: rxintr_setup: MGETHDR() failed\n", NAME_UNIT);
4379    return 0;
4380    }
4381  MCLGET(m, M_DONTWAIT);
4382  if ((m->m_flags & M_EXT)==0)
4383    {
4384    m_freem(m);
4385    sc->status.cntrs.rxbuf++;
4386    if (sc->config.debug)
4387      printf("%s: rxintr_setup: MCLGET() failed\n", NAME_UNIT);
4388    return 0;
4389    }
4390
4391  /* Queue the mbuf for later processing by rxintr_cleanup. */
4392  mbuf_enqueue(ring, m);
4393
4394  /* Write a DMA descriptor into the ring. */
4395  /* Hardware will not see it until the OWNER bit is set. */
4396  desc = ring->write;
4397  /* Advance the ring write pointer. */
4398  if (ring->write++ == ring->last) ring->write = ring->first;
4399
4400  desc_len = (MCLBYTES < MAX_DESC_LEN) ? MCLBYTES : MAX_DESC_LEN;
4401  /* Map kernel virt addr to PCI bus addr. */
4402  if ((error = DMA_LOAD(desc->map, m->m_data, desc_len)))
4403    printf("%s: bus_dmamap_load(rx): error %d\n", NAME_UNIT, error);
4404  /* Invalidate the cache for this mbuf. */
4405  DMA_SYNC(desc->map, desc_len, BUS_DMASYNC_PREREAD);
4406
4407  /* Set up the DMA descriptor. */
4408  desc->address1 = desc->map->dm_segs[0].ds_addr;
4409  desc->length1  = desc_len>>1;
4410  desc->address2 = desc->address1 + desc->length1;
4411  desc->length2  = desc_len>>1;
4412
4413  /* Before setting the OWNER bit, flush cache backing DMA descriptors. */
4414  DMA_SYNC(ring->map, ring->size_descs, BUS_DMASYNC_PREWRITE);
4415
4416  /* Commit the DMA descriptor to the hardware. */
4417  desc->status = TLP_DSTS_OWNER;
4418
4419  /* Notify the receiver that there is another buffer available. */
4420  WRITE_CSR(sc, TLP_RX_POLL, 1);
4421
4422  return 1; /* did something */
4423  }
4424
4425/* Clean up after a packet has been transmitted. */
4426/* Free the mbuf chain and update the DMA descriptor ring. */
4427static int  /* BSD version */
4428txintr_cleanup(softc_t *sc)
4429  {
4430  struct desc_ring *ring = &sc->txring;
4431  struct dma_desc *desc;
4432
4433  while ((ring->read != ring->write) && /* while ring is not empty */
4434        !(ring->read->status & TLP_DSTS_OWNER))
4435    {
4436    /* Read a DMA descriptor from the ring. */
4437    desc = ring->read;
4438    /* Advance the ring read pointer. */
4439    if (ring->read++ == ring->last) ring->read = ring->first;
4440
4441    /* This is a no-op on most architectures. */
4442    DMA_SYNC(desc->map, desc->length1 + desc->length2, BUS_DMASYNC_POSTWRITE);
4443    /* Unmap kernel virtual address to PCI bus address. */
4444    bus_dmamap_unload(ring->tag, desc->map);
4445
4446    /* If this descriptor is the last segment of a packet, */
4447    /*  then dequeue and free the corresponding mbuf chain. */
4448    if (desc->control & TLP_DCTL_TX_LAST_SEG)
4449      {
4450      struct mbuf *m;
4451
4452      if ((m = mbuf_dequeue(ring)) == NULL)
4453        panic("%s: txintr_cleanup: expected an mbuf\n", NAME_UNIT);
4454
4455      /* The only bad TX status is fifo underrun. */
4456      if (desc->status & TLP_DSTS_TX_UNDERRUN)
4457        {
4458        if (sc->config.debug)
4459          printf("%s: txintr_cleanup: tx fifo underrun\n", NAME_UNIT);
4460        sc->status.cntrs.fifo_under++;
4461        sc->status.cntrs.oerrors++;
4462	}
4463      else
4464        {
4465        /* Include CRC and one flag byte in output byte count. */
4466        sc->status.cntrs.obytes += m->m_pkthdr.len + sc->config.crc_len +1;
4467        sc->status.cntrs.opackets++;
4468
4469        /* Berkeley Packet Filter */
4470        LMC_BPF_MTAP(sc, m);
4471	}
4472
4473      m_freem(m);
4474      return 1;  /* did something */
4475      }
4476    }
4477
4478  return 0;
4479  }
4480
4481/* Build DMA descriptors for a transmit packet mbuf chain. */
4482static int  /* 0=success; 1=error */ /* BSD version */
4483txintr_setup_mbuf(softc_t *sc, struct mbuf *m)
4484  {
4485  struct desc_ring *ring = &sc->txring;
4486  struct dma_desc *desc;
4487  unsigned int desc_len;
4488
4489  /* build DMA descriptors for a chain of mbufs. */
4490  while (m)
4491    {
4492    char *data = m->m_data;
4493    int length = m->m_len; /* zero length mbufs happen! */
4494
4495    /* Build DMA descriptors for one mbuf. */
4496    while (length > 0)
4497      {
4498      int error;
4499
4500      /* Ring is full if (wrap(write+1)==read) */
4501      if (((ring->temp==ring->last) ? ring->first : ring->temp+1) == ring->read)
4502        { /* Not enough DMA descriptors; try later. */
4503        for (; ring->temp!=ring->write;
4504         ring->temp = (ring->temp==ring->first)? ring->last : ring->temp-1)
4505          bus_dmamap_unload(ring->tag, ring->temp->map);
4506        sc->status.cntrs.txdma++; /* IFF_OACTIVE? */
4507        return 1;
4508	}
4509
4510      /* Provisionally, write a descriptor into the ring. */
4511      /* But do not change the REAL ring write pointer. */
4512      /* Hardware will not see it until the OWNER bit is set. */
4513      desc = ring->temp;
4514      /* Advance the temporary ring write pointer. */
4515      if (ring->temp++ == ring->last) ring->temp = ring->first;
4516
4517      /* Clear all control bits except the END_RING bit. */
4518      desc->control &= TLP_DCTL_END_RING;
4519      /* Do not pad short packets up to 64 bytes. */
4520      desc->control |= TLP_DCTL_TX_NO_PAD;
4521      /* Use Tulip's CRC-32 generator, if appropriate. */
4522      if (sc->config.crc_len != CFG_CRC_32)
4523        desc->control |= TLP_DCTL_TX_NO_CRC;
4524      /* Set the OWNER bit, except in the first descriptor. */
4525      if (desc != ring->write)
4526        desc->status = TLP_DSTS_OWNER;
4527
4528      desc_len = (length > MAX_CHUNK_LEN) ? MAX_CHUNK_LEN : length;
4529      /* Map kernel virt addr to PCI bus addr. */
4530      if ((error = DMA_LOAD(desc->map, data, desc_len)))
4531        printf("%s: bus_dmamap_load(tx): error %d\n", NAME_UNIT, error);
4532      /* Flush the cache and if bouncing, copy mbuf to bounce buf. */
4533      DMA_SYNC(desc->map, desc_len, BUS_DMASYNC_PREWRITE);
4534
4535      /* Prevent wild fetches if mapping fails (nsegs==0). */
4536      desc->length1  = desc->length2  = 0;
4537      desc->address1 = desc->address2 = 0;
4538        {
4539        bus_dma_segment_t *segs = desc->map->dm_segs;
4540        int nsegs = desc->map->dm_nsegs;
4541        if (nsegs >= 1)
4542          {
4543          desc->address1 = segs[0].ds_addr;
4544          desc->length1  = segs[0].ds_len;
4545          }
4546        if (nsegs == 2)
4547          {
4548          desc->address2 = segs[1].ds_addr;
4549          desc->length2  = segs[1].ds_len;
4550          }
4551        }
4552
4553      data   += desc_len;
4554      length -= desc_len;
4555      } /* while (length > 0) */
4556
4557    m = m->m_next;
4558    } /* while (m) */
4559
4560  return 0; /* success */
4561  }
4562
4563/* Setup (prepare) to transmit a packet. */
4564/* Select a packet, build DMA descriptors and give packet to hardware. */
4565/* If DMA descriptors run out, abandon the attempt and return 0. */
4566static int  /* BSD version */
4567txintr_setup(softc_t *sc)
4568  {
4569  struct desc_ring *ring = &sc->txring;
4570  struct dma_desc *first_desc, *last_desc;
4571
4572  /* Protect against half-up links: Do not transmit */
4573  /*  if the receiver can not hear the far end. */
4574  if (sc->status.link_state != STATE_UP) return 0;
4575
4576  /* Pick a packet to transmit. */
4577  if ((sc->tx_mbuf == NULL) && sc->stack)
4578    sc->stack->output(sc);
4579  if  (sc->tx_mbuf == NULL) return 0;  /* no pkt to transmit */
4580
4581  /* Build DMA descriptors for an outgoing mbuf chain. */
4582  ring->temp = ring->write; /* temporary ring write pointer */
4583  if (txintr_setup_mbuf(sc, sc->tx_mbuf)) return 0;
4584
4585  /* Enqueue the mbuf; txintr_cleanup will free it. */
4586  mbuf_enqueue(ring, sc->tx_mbuf);
4587
4588  /* The transmitter has room for another packet. */
4589  sc->tx_mbuf = NULL;
4590
4591  /* Set first & last segment bits. */
4592  /* last_desc is the desc BEFORE the one pointed to by ring->temp. */
4593  first_desc = ring->write;
4594  first_desc->control |= TLP_DCTL_TX_FIRST_SEG;
4595  last_desc = (ring->temp==ring->first)? ring->last : ring->temp-1;
4596   last_desc->control |= TLP_DCTL_TX_LAST_SEG;
4597  /* Interrupt at end-of-transmission?  Why bother the poor computer! */
4598/* last_desc->control |= TLP_DCTL_TX_INTERRUPT; */
4599
4600  /* Make sure the OWNER bit is not set in the next descriptor. */
4601  /* The OWNER bit may have been set if a previous call aborted. */
4602  ring->temp->status = 0;
4603
4604  /* Commit the DMA descriptors to the software. */
4605  ring->write = ring->temp;
4606
4607  /* Before setting the OWNER bit, flush cache backing DMA descriptors. */
4608  DMA_SYNC(ring->map, ring->size_descs, BUS_DMASYNC_PREWRITE);
4609
4610  /* Commit the DMA descriptors to the hardware. */
4611  first_desc->status = TLP_DSTS_OWNER;
4612
4613  /* Notify the transmitter that there is another packet to send. */
4614  WRITE_CSR(sc, TLP_TX_POLL, 1);
4615
4616  return 1; /* did something */
4617  }
4618
4619/* BSD kernels call this when a hardware interrupt happens. */
4620static intr_return_t  /* context: interrupt */
4621bsd_interrupt(void *arg)
4622  {
4623  softc_t *sc = arg;
4624
4625# if DEVICE_POLLING
4626  if (sc->ifp->if_capenable & IFCAP_POLLING)
4627    return IRQ_NONE;
4628# endif
4629
4630  /* Cut losses early if this is not our interrupt. */
4631  if ((READ_CSR(sc, TLP_STATUS) & TLP_INT_TXRX)==0)
4632    return IRQ_NONE;
4633
4634  /* Process tx and rx pkts. */
4635  lmc_interrupt(sc, sc->rxring.num_descs, 0);
4636
4637  return IRQ_HANDLED;
4638  }
4639
4640#endif /* BSD */
4641
4642# if DEVICE_POLLING
4643
4644/* This procedure services the card without interrupts. */
4645/* With rxintr_cleanup(), it implements input flow control. */
4646static void  /* context: softirq */
4647bsd_poll(struct ifnet *ifp, enum poll_cmd cmd, int quota)
4648  {
4649  softc_t *sc = IFP2SC(ifp);
4650
4651  /* Cut losses early if this is not our interrupt. */
4652  if ((READ_CSR(sc, TLP_STATUS) & TLP_INT_TXRX)==0)
4653    return;
4654
4655  /* Process all tx pkts and up to quota rx pkts. */
4656  lmc_interrupt(sc, quota, (cmd==POLL_AND_CHECK_STATUS));
4657  }
4658
4659# endif /* DEVICE_POLLING */
4660
4661
4662/* Open a line protocol. */
4663/* context: kernel (boot) or process (syscall) */
4664static int
4665open_proto(softc_t *sc, struct config *config)
4666  {
4667  int error = 0;
4668
4669  if (sc->stack)
4670    error = sc->stack->open(sc, config);
4671  else
4672    error = BSD ? ENOSYS : -ENOSYS;
4673
4674  return error;
4675  }
4676
4677/* Attach a line protocol stack. */
4678/* context: kernel (boot) or process (syscall) */
4679static int
4680attach_stack(softc_t *sc, struct config *config)
4681  {
4682  int error = 0;
4683  struct stack *stack = NULL;
4684
4685  /* Done if stack is not changing. */
4686  if (sc->config.stack == config->stack)
4687    return 0;
4688
4689  /* Detach the current stack. */
4690  if (sc->stack && ((error = sc->stack->detach(sc))))
4691    return error;
4692
4693  switch (config->stack)
4694    {
4695    case STACK_RAWIP: /* built-in */
4696      stack = &rawip_stack;
4697      break;
4698
4699#if SPPP
4700    case STACK_SPPP:
4701      stack = &sppp_stack;
4702      break;
4703#endif
4704
4705#if P2P
4706    case STACK_P2P:
4707      stack = &p2p_stack;
4708      break;
4709#endif
4710
4711#if GEN_HDLC
4712    case STACK_GEN_HDLC:
4713      stack = &gen_hdlc_stack;
4714      break;
4715#endif
4716
4717#if SYNC_PPP
4718    case STACK_SYNC_PPP:
4719      stack = &sync_ppp_stack;
4720      break;
4721#endif
4722
4723
4724    default:
4725      stack = NULL;
4726      break;
4727    }
4728
4729  if (stack)
4730    error = stack->attach(sc, config);
4731  else
4732    error = BSD ? ENOSYS : -ENOSYS;
4733
4734  return error;
4735  }
4736
4737
4738/*
4739 * This handles IOCTLs from lmcconfig(8).
4740 * Must not run when card watchdogs run.
4741 * Always called with top_lock held.
4742 */
4743static int  /* context: process */
4744lmc_ioctl(softc_t *sc, u_long cmd, void *data)
4745  {
4746  struct iohdr  *iohdr  = (struct iohdr  *) data;
4747  struct ioctl  *ioctl  = (struct ioctl  *) data;
4748  struct status *status = (struct status *) data;
4749  struct config *config = (struct config *) data;
4750  int error = 0;
4751
4752  /* All structs start with a string and a cookie. */
4753  if (iohdr->cookie != NGM_LMC_COOKIE)
4754    return EINVAL;
4755
4756  switch (cmd)
4757    {
4758    case LMCIOCGSTAT:
4759      {
4760      *status = sc->status;
4761      iohdr->cookie = NGM_LMC_COOKIE;
4762      break;
4763      }
4764    case LMCIOCGCFG:
4765      {
4766      *config = sc->config;
4767      iohdr->cookie = NGM_LMC_COOKIE;
4768      break;
4769      }
4770    case LMCIOCSCFG:
4771      {
4772      if ((error = CHECK_CAP)) break;
4773      if ((error = attach_stack(sc, config)));
4774      else error = open_proto(sc, config);
4775      tulip_loop(sc, config);
4776      sc->card->attach(sc, config);
4777      sc->config.debug = config->debug;
4778      break;
4779      }
4780    case LMCIOCREAD:
4781      {
4782      if (ioctl->cmd == IOCTL_RW_PCI)
4783        {
4784        if (ioctl->address > 252) { error = EFAULT; break; }
4785        ioctl->data = READ_PCI_CFG(sc, ioctl->address);
4786	}
4787      else if (ioctl->cmd == IOCTL_RW_CSR)
4788        {
4789        if (ioctl->address >  15) { error = EFAULT; break; }
4790        ioctl->data = READ_CSR(sc, ioctl->address*TLP_CSR_STRIDE);
4791	}
4792      else if (ioctl->cmd == IOCTL_RW_SROM)
4793        {
4794        if (ioctl->address >  63) { error = EFAULT; break; }
4795        ioctl->data = srom_read(sc, ioctl->address);
4796	}
4797      else if (ioctl->cmd == IOCTL_RW_BIOS)
4798        ioctl->data = bios_read(sc, ioctl->address);
4799      else if (ioctl->cmd == IOCTL_RW_MII)
4800        ioctl->data = mii_read(sc, ioctl->address);
4801      else if (ioctl->cmd == IOCTL_RW_FRAME)
4802        ioctl->data = framer_read(sc, ioctl->address);
4803      else
4804        error = EINVAL;
4805      break;
4806      }
4807    case LMCIOCWRITE:
4808      {
4809      if ((error = CHECK_CAP)) break;
4810      if (ioctl->cmd == IOCTL_RW_PCI)
4811        {
4812        if (ioctl->address > 252) { error = EFAULT; break; }
4813        WRITE_PCI_CFG(sc, ioctl->address, ioctl->data);
4814	}
4815      else if (ioctl->cmd == IOCTL_RW_CSR)
4816        {
4817        if (ioctl->address >  15) { error = EFAULT; break; }
4818        WRITE_CSR(sc, ioctl->address*TLP_CSR_STRIDE, ioctl->data);
4819	}
4820      else if (ioctl->cmd == IOCTL_RW_SROM)
4821        {
4822        if (ioctl->address >  63) { error = EFAULT; break; }
4823        srom_write(sc, ioctl->address, ioctl->data); /* can sleep */
4824	}
4825      else if (ioctl->cmd == IOCTL_RW_BIOS)
4826        {
4827        if (ioctl->address == 0) bios_erase(sc);
4828        bios_write(sc, ioctl->address, ioctl->data); /* can sleep */
4829	}
4830      else if (ioctl->cmd == IOCTL_RW_MII)
4831        mii_write(sc, ioctl->address, ioctl->data);
4832      else if (ioctl->cmd == IOCTL_RW_FRAME)
4833        framer_write(sc, ioctl->address, ioctl->data);
4834      else if (ioctl->cmd == IOCTL_WO_SYNTH)
4835        synth_write(sc, (struct synth *)&ioctl->data);
4836      else if (ioctl->cmd == IOCTL_WO_DAC)
4837        {
4838        dac_write(sc, 0x9002); /* set Vref = 2.048 volts */
4839        dac_write(sc, ioctl->data & 0xFFF);
4840	}
4841      else
4842        error = EINVAL;
4843      break;
4844      }
4845    case LMCIOCTL:
4846      {
4847      if ((error = CHECK_CAP)) break;
4848      if (ioctl->cmd == IOCTL_XILINX_RESET)
4849        {
4850        xilinx_reset(sc);
4851        sc->card->attach(sc, &sc->config);
4852	}
4853      else if (ioctl->cmd == IOCTL_XILINX_ROM)
4854        {
4855        xilinx_load_from_rom(sc);
4856        sc->card->attach(sc, &sc->config);
4857	}
4858      else if (ioctl->cmd == IOCTL_XILINX_FILE)
4859        {
4860        error = xilinx_load_from_file(sc, ioctl->ucode, ioctl->data);
4861        if (error) xilinx_load_from_rom(sc); /* try the rom */
4862        sc->card->attach(sc, &sc->config);
4863	}
4864      else if (ioctl->cmd == IOCTL_RESET_CNTRS)
4865        reset_cntrs(sc);
4866      else
4867        error = sc->card->ioctl(sc, ioctl);
4868      break;
4869      }
4870    default:
4871      error = EINVAL;
4872      break;
4873    }
4874
4875  return error;
4876  }
4877
4878/* This is the core watchdog procedure.
4879 * ioctl syscalls and card watchdog routines must be interlocked.
4880 * Called by ng_watchdog(), ifnet_watchdog() and netdev_watchdog().
4881 */
4882static void  /* context: softirq */
4883lmc_watchdog(softc_t *sc)
4884  {
4885  /* Read and restart the Tulip timer. */
4886  u_int32_t tx_speed = READ_CSR(sc, TLP_TIMER);
4887  WRITE_CSR(sc, TLP_TIMER, 0xFFFF);
4888
4889  /* Measure MII clock using a timer in the Tulip chip.
4890   * This timer counts transmitter bits divided by 4096.
4891   * Since this is called once a second the math is easy.
4892   * This is only correct when the link is NOT sending pkts.
4893   * On a fully-loaded link, answer will be HALF actual rate.
4894   * Clock rate during pkt is HALF clk rate between pkts.
4895   * Measuring clock rate really measures link utilization!
4896   */
4897  sc->status.tx_speed = (0xFFFF - (tx_speed & 0xFFFF)) << 12;
4898
4899  /* Call the card-specific watchdog routine. */
4900  if (TOP_TRYLOCK(sc))
4901    {
4902    /* Remember link_state before updating it. */
4903    sc->last_link_state = sc->status.link_state;
4904    /* Update status.link_state. */
4905    sc->card->watchdog(sc);
4906
4907    /* Increment a counter which tells user-land */
4908    /*  observers that SNMP state has been updated. */
4909    sc->status.ticks++;
4910
4911    TOP_UNLOCK(sc);
4912    }
4913  else
4914    sc->status.cntrs.lck_watch++;
4915
4916  /* Kernel date/time can take up to 5 seconds to start running. */
4917  if ((sc->status.ticks > 3) && /* h/w should be stable by now */
4918      (sc->status.cntrs.reset_time.tv_sec < 1000))
4919    {
4920    microtime(&sc->status.cntrs.reset_time);
4921    if (sc->status.cntrs.reset_time.tv_sec > 1000)
4922      reset_cntrs(sc);
4923    }
4924
4925  /* Call the stack-specific watchdog routine. */
4926  if (sc->stack)
4927    sc->stack->watchdog(sc);
4928
4929  /* In case an interrupt gets lost, process tx and rx pkts */
4930  lmc_interrupt(sc, sc->rxring.num_descs, 1);
4931  }
4932
4933/* Administrative status of the driver (UP or DOWN) has changed.
4934 * A card-specific action is taken:
4935 *  HSSI: drop TA.
4936 * (T3:   send T3 idle ckt signal. )
4937 *  SSI:  drop RTS, DTR and DCD
4938 * (T1:   disable line interface tx; )
4939 */
4940static void
4941set_ready(softc_t *sc, int status)
4942  {
4943  struct ioctl ioctl;
4944
4945  ioctl.cmd = IOCTL_SET_STATUS;
4946  ioctl.data = status;
4947
4948  sc->card->ioctl(sc, &ioctl);
4949  }
4950
4951static void
4952reset_cntrs(softc_t *sc)
4953  {
4954  memset(&sc->status.cntrs, 0, sizeof(struct cntrs));
4955  microtime(&sc->status.cntrs.reset_time);
4956  }
4957
4958static void  /* context: process, softirq, interrupt! */
4959lmc_interrupt(void *arg, int quota, int check_status)
4960  {
4961  softc_t *sc = arg;
4962  int activity;
4963
4964  /* Do this FIRST!  Otherwise UPs deadlock and MPs spin. */
4965  WRITE_CSR(sc, TLP_STATUS, READ_CSR(sc, TLP_STATUS));
4966
4967  /* If any CPU is inside this critical section, then */
4968  /*  other CPUs should go away without doing anything. */
4969  if (BOTTOM_TRYLOCK(sc) == 0)
4970    {
4971    sc->status.cntrs.lck_intr++;
4972    return;
4973    }
4974
4975  /* In Linux, pci_alloc_consistent() means DMA */
4976  /*  descriptors do not need explicit syncing? */
4977#if BSD
4978  {
4979  struct desc_ring *ring = &sc->txring;
4980  DMA_SYNC(sc->txring.map, sc->txring.size_descs,
4981   BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
4982  ring = &sc->rxring;
4983  DMA_SYNC(sc->rxring.map, sc->rxring.size_descs,
4984   BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
4985  }
4986#endif
4987
4988  /* This is the main loop for interrupt processing. */
4989  sc->quota = quota;
4990  do
4991    {
4992    activity  = txintr_cleanup(sc);
4993    activity += txintr_setup(sc);
4994    activity += rxintr_cleanup(sc);
4995    activity += rxintr_setup(sc);
4996    } while (activity);
4997
4998#if BSD
4999  {
5000  struct desc_ring *ring = &sc->txring;
5001  DMA_SYNC(sc->txring.map, sc->txring.size_descs,
5002   BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
5003  ring = &sc->rxring;
5004  DMA_SYNC(sc->rxring.map, sc->rxring.size_descs,
5005   BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
5006  }
5007#endif
5008
5009  /* As the interrupt is dismissed, check for four unusual events. */
5010  if (check_status) check_intr_status(sc);
5011
5012  BOTTOM_UNLOCK(sc);
5013  }
5014
5015/* Check for four unusual events:
5016 *  1) fatal PCI bus errors       - some are recoverable
5017 *  2) transmitter FIFO underruns - increase fifo threshold
5018 *  3) receiver FIFO overruns     - clear potential hangup
5019 *  4) no receive descs or bufs   - count missed packets
5020 */
5021static void
5022check_intr_status(softc_t *sc)
5023  {
5024  u_int32_t status, cfcs, op_mode;
5025  u_int32_t missed, overruns;
5026
5027  /* 1) A fatal bus error causes a Tulip to stop initiating bus cycles.
5028   * Module unload/load or boot are the only fixes for Parity Errors.
5029   * Master and Target Aborts can be cleared and life may continue.
5030   */
5031  status = READ_CSR(sc, TLP_STATUS);
5032  if (status & TLP_STAT_FATAL_ERROR)
5033    {
5034    u_int32_t fatal = (status & TLP_STAT_FATAL_BITS)>>TLP_STAT_FATAL_SHIFT;
5035    printf("%s: FATAL PCI BUS ERROR: %s%s%s%s\n", NAME_UNIT,
5036     (fatal == 0) ? "PARITY ERROR" : "",
5037     (fatal == 1) ? "MASTER ABORT" : "",
5038     (fatal == 2) ? "TARGET ABORT" : "",
5039     (fatal >= 3) ? "RESERVED (?)" : "");
5040    cfcs = READ_PCI_CFG(sc, TLP_CFCS);  /* try to clear it */
5041    cfcs &= ~(TLP_CFCS_MSTR_ABORT | TLP_CFCS_TARG_ABORT);
5042    WRITE_PCI_CFG(sc, TLP_CFCS, cfcs);
5043    }
5044
5045  /* 2) If the transmitter fifo underruns, increase the transmit fifo
5046   *  threshold: the number of bytes required to be in the fifo
5047   *  before starting the transmitter (cost: increased tx delay).
5048   * The TX_FSM must be stopped to change this parameter.
5049   */
5050  if (status & TLP_STAT_TX_UNDERRUN)
5051    {
5052    op_mode = READ_CSR(sc, TLP_OP_MODE);
5053    /* enable store-and-forward mode if tx_threshold tops out? */
5054    if ((op_mode & TLP_OP_TX_THRESH) < TLP_OP_TX_THRESH)
5055      {
5056      op_mode += 0x4000;  /* increment TX_THRESH field; can not overflow */
5057      WRITE_CSR(sc, TLP_OP_MODE, op_mode & ~TLP_OP_TX_RUN);
5058      /* Wait for the TX FSM to stop; it might be processing a pkt. */
5059      while (READ_CSR(sc, TLP_STATUS) & TLP_STAT_TX_FSM); /* XXX HANG */
5060      WRITE_CSR(sc, TLP_OP_MODE, op_mode); /* restart tx */
5061
5062      if (sc->config.debug)
5063        printf("%s: tx fifo underrun; threshold now %d bytes\n",
5064         NAME_UNIT, 128<<((op_mode>>TLP_OP_TR_SHIFT)&3));
5065      sc->status.cntrs.underruns++;
5066      }
5067    }
5068
5069  /* 3) Errata memo from Digital Equipment Corp warns that 21140A
5070   *  receivers through rev 2.2 can hang if the fifo overruns.
5071   * Recommended fix: stop and start the RX FSM after an overrun.
5072   */
5073  missed = READ_CSR(sc, TLP_MISSED);
5074  if ((overruns = ((missed & TLP_MISS_OVERRUN)>>TLP_OVERRUN_SHIFT)))
5075    {
5076    if ((READ_PCI_CFG(sc, TLP_CFRV) & 0xFF) <= 0x22)
5077      {
5078      op_mode = READ_CSR(sc, TLP_OP_MODE);
5079      WRITE_CSR(sc, TLP_OP_MODE, op_mode & ~TLP_OP_RX_RUN);
5080      /* Wait for the RX FSM to stop; it might be processing a pkt. */
5081      while (READ_CSR(sc, TLP_STATUS) & TLP_STAT_RX_FSM); /* XXX HANG */
5082      WRITE_CSR(sc, TLP_OP_MODE, op_mode);  /* restart rx */
5083      }
5084    if (sc->config.debug)
5085      printf("%s: rx fifo overruns=%d\n", NAME_UNIT, overruns);
5086    sc->status.cntrs.overruns += overruns;
5087    }
5088
5089  /* 4) When the receiver is enabled and a packet arrives, but no DMA
5090   *  descriptor is available, the packet is counted as 'missed'.
5091   * The receiver should never miss packets; warn if it happens.
5092   */
5093  if ((missed = (missed & TLP_MISS_MISSED)))
5094    {
5095    if (sc->config.debug)
5096      printf("%s: rx missed %d pkts\n", NAME_UNIT, missed);
5097    sc->status.cntrs.missed += missed;
5098    }
5099  }
5100
5101/* Initialize the driver. */
5102/* context: kernel (boot) or process (syscall) */
5103static int
5104lmc_attach(softc_t *sc)
5105  {
5106  int error = 0;
5107  struct config config;
5108
5109  /* Attach the Tulip PCI bus interface. */
5110  if ((error = tulip_attach(sc))) return error;
5111
5112  /* Reset the Xilinx Field Programmable Gate Array. */
5113  xilinx_reset(sc); /* side effect: turns on all four LEDs */
5114
5115  /* Attach card-specific stuff. */
5116  sc->card->attach(sc, NULL); /* changes sc->config */
5117
5118  /* Reset the FIFOs between Gate array and Tulip chip. */
5119  mii16_set_bits(sc, MII16_FIFO);
5120  mii16_clr_bits(sc, MII16_FIFO);
5121
5122#if IFNET
5123  /* Attach the ifnet kernel interface. */
5124  if ((error = ifnet_attach(sc))) return error;
5125#endif
5126
5127#if NETDEV
5128  /* Attach the netdevice kernel interface. */
5129  if ((error = netdev_attach(sc))) return error;
5130#endif
5131
5132  /* Attach a protocol stack and open a line protocol. */
5133  config = sc->config;
5134  config.stack = STACK_RAWIP;
5135  attach_stack(sc, &config);
5136  config.proto = PROTO_IP_HDLC;
5137  open_proto(sc, &config);
5138
5139  /* Print obscure card information. */
5140  if (BOOT_VERBOSE)
5141    {
5142    u_int32_t cfrv = READ_PCI_CFG(sc, TLP_CFRV);
5143    u_int16_t mii3 = mii_read(sc, 3);
5144    u_int16_t srom[3];
5145    u_int8_t  *ieee = (u_int8_t *)srom;
5146    int i;
5147
5148    printf("%s", NAME_UNIT);
5149    printf(": PCI rev %d.%d", (cfrv>>4) & 0xF, cfrv & 0xF);
5150    printf(", MII rev %d.%d", (mii3>>4) & 0xF, mii3 & 0xF);
5151    for (i=0; i<3; i++) srom[i] = srom_read(sc, 10+i);
5152    printf(", IEEE addr %02x:%02x:%02x:%02x:%02x:%02x",
5153     ieee[0], ieee[1], ieee[2], ieee[3], ieee[4], ieee[5]);
5154    sc->card->ident(sc);
5155    }
5156
5157/* BSDs enable card interrupts and appear "ready" here. */
5158/* Linux does this in netdev_open(). */
5159#if BSD
5160  set_ready(sc, 1);
5161  WRITE_CSR(sc, TLP_INT_ENBL, TLP_INT_TXRX);
5162#endif
5163
5164  return 0;
5165  }
5166
5167/* context: kernel (boot) or process (syscall) */
5168static void
5169lmc_detach(softc_t *sc)
5170  {
5171  /* Disable card interrupts and appear "not ready". */
5172  set_ready(sc, 0);
5173  WRITE_CSR(sc, TLP_INT_ENBL, TLP_INT_DISABLE);
5174
5175  /* Detach the line protocol package. */
5176  if (sc->stack)
5177    sc->stack->detach(sc);
5178
5179#if IFNET
5180  /* Detach the ifnet kernel interface. */
5181  ifnet_detach(sc);
5182#endif
5183
5184#if NETDEV
5185  /* Detach the netdevice kernel interface. */
5186  netdev_detach(sc);
5187#endif
5188
5189  /* Detach framers, line interfaces, etc. on the card. */
5190  sc->card->detach(sc);
5191
5192  /* Detach the Tulip PCI bus interface. */
5193  tulip_detach(sc);
5194  }
5195
5196/* Loop back through the TULIP Ethernet chip; (no CRC).
5197 * Data sheet says stop DMA before changing OPMODE register.
5198 * But that's not as simple as it sounds; works anyway.
5199 */
5200static void
5201tulip_loop(softc_t *sc, struct config *config)
5202  {
5203  /* Check for enabling loopback thru Tulip chip. */
5204  if ((sc->config.loop_back != CFG_LOOP_TULIP) &&
5205         (config->loop_back == CFG_LOOP_TULIP))
5206    {
5207    u_int32_t op_mode = READ_CSR(sc, TLP_OP_MODE);
5208    op_mode |= TLP_OP_INT_LOOP;
5209    WRITE_CSR(sc, TLP_OP_MODE, op_mode);
5210    config->crc_len = CFG_CRC_0;
5211    }
5212
5213  /* Check for disabling loopback thru Tulip chip. */
5214  if ((sc->config.loop_back == CFG_LOOP_TULIP) &&
5215         (config->loop_back != CFG_LOOP_TULIP))
5216    {
5217    u_int32_t op_mode = READ_CSR(sc, TLP_OP_MODE);
5218    op_mode &= ~TLP_OP_LOOP_MODE;
5219    WRITE_CSR(sc, TLP_OP_MODE, op_mode);
5220    config->crc_len = CFG_CRC_16;
5221    }
5222
5223  sc->config.loop_back = config->loop_back;
5224  }
5225
5226/* Attach the Tulip PCI bus interface.
5227 * Allocate DMA descriptors and enable DMA.
5228 * Returns 0 on success; error code on failure.
5229 * context: kernel (boot) or process (syscall)
5230 */
5231static int
5232tulip_attach(softc_t *sc)
5233  {
5234  int num_rx_descs, error = 0;
5235  u_int32_t bus_pbl, bus_cal, op_tr;
5236  u_int32_t cfdd, cfcs, cflt, csid, cfit;
5237
5238  /* Make sure the COMMAND bits are reasonable. */
5239  cfcs = READ_PCI_CFG(sc, TLP_CFCS);
5240  cfcs &= ~TLP_CFCS_MWI_ENABLE;
5241  cfcs |=  TLP_CFCS_BUS_MASTER;
5242  cfcs |=  TLP_CFCS_MEM_ENABLE;
5243  cfcs |=  TLP_CFCS_IO_ENABLE;
5244  cfcs |=  TLP_CFCS_PAR_ERROR;
5245  cfcs |=  TLP_CFCS_SYS_ERROR;
5246  WRITE_PCI_CFG(sc, TLP_CFCS, cfcs);
5247
5248  /* Set the LATENCY TIMER to the recommended value, */
5249  /*  and make sure the CACHE LINE SIZE is reasonable. */
5250  cfit = READ_PCI_CFG(sc, TLP_CFIT);
5251  cflt = READ_PCI_CFG(sc, TLP_CFLT);
5252  cflt &= ~TLP_CFLT_LATENCY;
5253  cflt |= (cfit & TLP_CFIT_MAX_LAT)>>16;
5254  /* "prgmbl burst length" and "cache alignment" used below. */
5255  switch(cflt & TLP_CFLT_CACHE)
5256    {
5257    case 8: /* 8 bytes per cache line */
5258      { bus_pbl = 32; bus_cal = 1; break; }
5259    case 16:
5260      { bus_pbl = 32; bus_cal = 2; break; }
5261    case 32:
5262      { bus_pbl = 32; bus_cal = 3; break; }
5263    default:
5264      {
5265      bus_pbl = 32; bus_cal = 1;
5266      cflt &= ~TLP_CFLT_CACHE;
5267      cflt |= 8;
5268      break;
5269      }
5270    }
5271  WRITE_PCI_CFG(sc, TLP_CFLT, cflt);
5272
5273  /* Make sure SNOOZE and SLEEP modes are disabled. */
5274  cfdd = READ_PCI_CFG(sc, TLP_CFDD);
5275  cfdd &= ~TLP_CFDD_SLEEP;
5276  cfdd &= ~TLP_CFDD_SNOOZE;
5277  WRITE_PCI_CFG(sc, TLP_CFDD, cfdd);
5278  DELAY(11*1000); /* Tulip wakes up in 10 ms max */
5279
5280  /* Software Reset the Tulip chip; stops DMA and Interrupts. */
5281  /* This does not change the PCI config regs just set above. */
5282  WRITE_CSR(sc, TLP_BUS_MODE, TLP_BUS_RESET); /* self-clearing */
5283  DELAY(5);  /* Tulip is dead for 50 PCI cycles after reset. */
5284
5285  /* Initialize the PCI busmode register. */
5286  /* The PCI bus cycle type "Memory Write and Invalidate" does NOT */
5287  /*  work cleanly in any version of the 21140A, so do not enable it! */
5288  WRITE_CSR(sc, TLP_BUS_MODE,
5289        (bus_cal ? TLP_BUS_READ_LINE : 0) |
5290        (bus_cal ? TLP_BUS_READ_MULT : 0) |
5291        (bus_pbl<<TLP_BUS_PBL_SHIFT) |
5292        (bus_cal<<TLP_BUS_CAL_SHIFT) |
5293   ((BYTE_ORDER == BIG_ENDIAN) ? TLP_BUS_DESC_BIGEND : 0) |
5294   ((BYTE_ORDER == BIG_ENDIAN) ? TLP_BUS_DATA_BIGEND : 0) |
5295                TLP_BUS_DSL_VAL |
5296                TLP_BUS_ARB);
5297
5298  /* Pick number of RX descriptors and TX fifo threshold. */
5299  /* tx_threshold in bytes: 0=128, 1=256, 2=512, 3=1024 */
5300  csid = READ_PCI_CFG(sc, TLP_CSID);
5301  switch(csid)
5302    {
5303    case CSID_LMC_HSSI:		/* 52 Mb/s */
5304    case CSID_LMC_HSSIc:	/* 52 Mb/s */
5305    case CSID_LMC_T3:		/* 45 Mb/s */
5306      { num_rx_descs = 48; op_tr = 2; break; }
5307    case CSID_LMC_SSI:		/* 10 Mb/s */
5308      { num_rx_descs = 32; op_tr = 1; break; }
5309    case CSID_LMC_T1E1:		/*  2 Mb/s */
5310      { num_rx_descs = 16; op_tr = 0; break; }
5311    default:
5312      { num_rx_descs = 16; op_tr = 0; break; }
5313    }
5314
5315  /* Create DMA descriptors and initialize list head registers. */
5316  if ((error = create_ring(sc, &sc->txring, NUM_TX_DESCS))) return error;
5317  WRITE_CSR(sc, TLP_TX_LIST, sc->txring.dma_addr);
5318  if ((error = create_ring(sc, &sc->rxring, num_rx_descs))) return error;
5319  WRITE_CSR(sc, TLP_RX_LIST, sc->rxring.dma_addr);
5320
5321  /* Initialize the operating mode register. */
5322  WRITE_CSR(sc, TLP_OP_MODE, TLP_OP_INIT | (op_tr<<TLP_OP_TR_SHIFT));
5323
5324  /* Read the missed frame register (result ignored) to zero it. */
5325  error = READ_CSR(sc, TLP_MISSED); /* error is used as a bit-dump */
5326
5327  /* Disable rx watchdog and tx jabber features. */
5328  WRITE_CSR(sc, TLP_WDOG, TLP_WDOG_INIT);
5329
5330  return 0;
5331  }
5332
5333/* Detach the Tulip PCI bus interface. */
5334/* Disable DMA and free DMA descriptors. */
5335/* context: kernel (boot) or process (syscall) */
5336static void
5337tulip_detach(void *arg)
5338  {
5339  softc_t *sc = arg;
5340
5341  /* Software reset the Tulip chip; stops DMA and Interrupts. */
5342  WRITE_CSR(sc, TLP_BUS_MODE, TLP_BUS_RESET); /* self-clearing */
5343  DELAY(5);  /* Tulip is dead for 50 PCI cycles after reset. */
5344
5345  /* Disconnect from the PCI bus except for config cycles. */
5346  /* Hmmm; Linux syslogs a warning that IO and MEM are disabled. */
5347  WRITE_PCI_CFG(sc, TLP_CFCS, TLP_CFCS_MEM_ENABLE | TLP_CFCS_IO_ENABLE);
5348
5349  /* Free the DMA descriptor rings. */
5350  destroy_ring(sc, &sc->txring);
5351  destroy_ring(sc, &sc->rxring);
5352  }
5353
5354/* Called during config probing -- softc does not yet exist. */
5355static void
5356print_driver_info(void)
5357  {
5358  /* Print driver information once only. */
5359  if (driver_announced++ == 0)
5360    {
5361    printf("LMC driver version %d/%d/%d; options",
5362     VER_YEAR, VER_MONTH, VER_DAY);
5363    if (ALTQ)           printf(" ALTQ");
5364                        printf(" BPF"); /* always defined */
5365    if (NAPI)           printf(" NAPI");
5366    if (DEVICE_POLLING) printf(" POLL");
5367    if (P2P)            printf(" P2P");
5368    if (SPPP)           printf(" SPPP");
5369    if (GEN_HDLC)       printf(" GEN_HDLC");
5370    if (SYNC_PPP)       printf(" SYNC_PPP");
5371    if (NETGRAPH)       printf(" NETGRAPH");
5372    printf(".\n");
5373    }
5374  }
5375
5376
5377
5378/* This is the I/O configuration interface for NetBSD. */
5379
5380/* Looking for a DEC 21140A chip on any Lan Media Corp card. */
5381/* context: kernel (boot) or process (syscall) */
5382static int
5383nbsd_match(struct device *parent, cfdata_t match,
5384    void *aux)
5385  {
5386  struct pci_attach_args *pa = aux;
5387  u_int32_t cfid = pci_conf_read(pa->pa_pc, pa->pa_tag, TLP_CFID);
5388  u_int32_t csid = pci_conf_read(pa->pa_pc, pa->pa_tag, TLP_CSID);
5389
5390  if (cfid != TLP_CFID_TULIP) return 0;
5391  switch (csid)
5392    {
5393    case CSID_LMC_HSSI:
5394    case CSID_LMC_HSSIc:
5395    case CSID_LMC_T3:
5396    case CSID_LMC_SSI:
5397    case CSID_LMC_T1E1:
5398      print_driver_info();
5399      return 100;
5400    default:
5401      return 0;
5402    }
5403  }
5404
5405/* NetBSD bottom-half initialization. */
5406/* context: kernel (boot) or process (syscall) */
5407static void
5408nbsd_attach(struct device *parent, struct device *self, void *aux)
5409  {
5410  softc_t *sc = (softc_t *)self; /* device is first in softc */
5411  struct pci_attach_args *pa = aux;
5412  const char *intrstr;
5413  bus_addr_t csr_addr;
5414  int error;
5415
5416  /* for READ/WRITE_PCI_CFG() */
5417  sc->pa_pc   = pa->pa_pc;
5418  sc->pa_tag  = pa->pa_tag;
5419  sc->pa_dmat = pa->pa_dmat;
5420
5421  /* What kind of card are we driving? */
5422  switch (READ_PCI_CFG(sc, TLP_CSID))
5423    {
5424    case CSID_LMC_HSSI:
5425    case CSID_LMC_HSSIc:
5426      sc->dev_desc =  HSSI_DESC;
5427      sc->card     = &hssi_card;
5428      break;
5429    case CSID_LMC_T3:
5430      sc->dev_desc =    T3_DESC;
5431      sc->card     =   &t3_card;
5432      break;
5433    case CSID_LMC_SSI:
5434      sc->dev_desc =   SSI_DESC;
5435      sc->card     =  &ssi_card;
5436      break;
5437    case CSID_LMC_T1E1:
5438      sc->dev_desc =  T1E1_DESC;
5439      sc->card     =   &t1_card;
5440      break;
5441    default:
5442      return;
5443    }
5444
5445  /* Allocate PCI resources to access the Tulip chip CSRs. */
5446# if IOREF_CSR
5447  csr_addr = (bus_addr_t)READ_PCI_CFG(sc, TLP_CBIO) & -2;
5448  sc->csr_tag = pa->pa_iot;	/* bus_space tag for IO refs */
5449# else
5450  csr_addr = (bus_addr_t)READ_PCI_CFG(sc, TLP_CBMA);
5451  sc->csr_tag = pa->pa_memt;	/* bus_space tag for MEM refs */
5452# endif
5453  if ((error = bus_space_map(sc->csr_tag, csr_addr,
5454   TLP_CSR_SIZE, 0, &sc->csr_handle)))
5455    {
5456    aprint_error("%s: bus_space_map(): error %d\n", NAME_UNIT, error);
5457    return;
5458    }
5459
5460  /* Allocate PCI interrupt resources. */
5461  if (pci_intr_map(pa, &sc->intr_handle))
5462    {
5463    aprint_error("%s: pci_intr_map() failed\n", NAME_UNIT);
5464    nbsd_detach(self, 0);
5465    return;
5466    }
5467  if ((sc->irq_cookie = pci_intr_establish(pa->pa_pc, sc->intr_handle,
5468   IPL_NET, bsd_interrupt, sc)) == NULL)
5469    {
5470    aprint_error("%s: pci_intr_establish() failed\n", NAME_UNIT);
5471    nbsd_detach(self, 0);
5472    return;
5473    }
5474  intrstr = pci_intr_string(pa->pa_pc, sc->intr_handle);
5475  aprint_normal(" %s: %s\n", intrstr, sc->dev_desc);
5476  aprint_naive(": %s\n", sc->dev_desc);
5477
5478  /* Install a shutdown hook. */
5479  if ((sc->sdh_cookie = shutdownhook_establish(tulip_detach, sc)) == NULL)
5480    {
5481    aprint_error("%s: shutdown_hook_establish() failed\n", NAME_UNIT);
5482    nbsd_detach(self, 0);
5483    return;
5484    }
5485
5486  /* Initialize the top-half and bottom-half locks. */
5487  mutex_init(&sc->top_lock, MUTEX_DEFAULT, IPL_VM);
5488  __cpu_simple_lock_init(&sc->bottom_lock);
5489
5490  /* Initialize the driver. */
5491  if ((error = lmc_attach(sc))) nbsd_detach(self, 0);
5492  }
5493
5494/* context: kernel (boot) or process (syscall) */
5495static int
5496nbsd_detach(struct device *self, int flags)
5497  {
5498  softc_t *sc = (softc_t *)self; /* device is first in softc */
5499
5500  /* Detach from the bus and the kernel. */
5501  lmc_detach(sc);
5502
5503  /* Release resources. */
5504  if (sc->sdh_cookie)
5505    shutdownhook_disestablish(sc->sdh_cookie);
5506  if (sc->irq_cookie)
5507    pci_intr_disestablish(sc->pa_pc, sc->irq_cookie);
5508  if (sc->csr_handle)
5509    bus_space_unmap(sc->csr_tag, sc->csr_handle, TLP_CSR_SIZE);
5510
5511  /* Destroy locks. */
5512  mutex_destroy(&sc->top_lock);
5513
5514  return 0;
5515  }
5516
5517CFATTACH_DECL(lmc, sizeof(softc_t),		/* lmc_ca */
5518 nbsd_match, nbsd_attach, nbsd_detach, NULL);
5519
5520
5521
5522
5523