• Home
  • History
  • Annotate
  • Line#
  • Navigate
  • Raw
  • Download
  • only in /netgear-R7000-V1.0.7.12_1.2.5/components/opensource/linux/linux-2.6.36/drivers/atm/
1/*
2  Madge Horizon ATM Adapter driver.
3  Copyright (C) 1995-1999  Madge Networks Ltd.
4
5  This program is free software; you can redistribute it and/or modify
6  it under the terms of the GNU General Public License as published by
7  the Free Software Foundation; either version 2 of the License, or
8  (at your option) any later version.
9
10  This program is distributed in the hope that it will be useful,
11  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  GNU General Public License for more details.
14
15  You should have received a copy of the GNU General Public License
16  along with this program; if not, write to the Free Software
17  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18
19  The GNU GPL is contained in /usr/doc/copyright/GPL on a Debian
20  system and in the file COPYING in the Linux kernel source.
21*/
22
23/*
24  IMPORTANT NOTE: Madge Networks no longer makes the adapters
25  supported by this driver and makes no commitment to maintain it.
26*/
27
28#include <linux/module.h>
29#include <linux/kernel.h>
30#include <linux/mm.h>
31#include <linux/pci.h>
32#include <linux/errno.h>
33#include <linux/atm.h>
34#include <linux/atmdev.h>
35#include <linux/sonet.h>
36#include <linux/skbuff.h>
37#include <linux/time.h>
38#include <linux/delay.h>
39#include <linux/uio.h>
40#include <linux/init.h>
41#include <linux/ioport.h>
42#include <linux/wait.h>
43#include <linux/slab.h>
44
45#include <asm/system.h>
46#include <asm/io.h>
47#include <asm/atomic.h>
48#include <asm/uaccess.h>
49#include <asm/string.h>
50#include <asm/byteorder.h>
51
52#include "horizon.h"
53
54#define maintainer_string "Giuliano Procida at Madge Networks <gprocida@madge.com>"
55#define description_string "Madge ATM Horizon [Ultra] driver"
56#define version_string "1.2.1"
57
58static inline void __init show_version (void) {
59  printk ("%s version %s\n", description_string, version_string);
60}
61
62/*
63
64  CREDITS
65
66  Driver and documentation by:
67
68  Chris Aston        Madge Networks
69  Giuliano Procida   Madge Networks
70  Simon Benham       Madge Networks
71  Simon Johnson      Madge Networks
72  Various Others     Madge Networks
73
74  Some inspiration taken from other drivers by:
75
76  Alexandru Cucos    UTBv
77  Kari Mettinen      University of Helsinki
78  Werner Almesberger EPFL LRC
79
80  Theory of Operation
81
82  I Hardware, detection, initialisation and shutdown.
83
84  1. Supported Hardware
85
86  This driver should handle all variants of the PCI Madge ATM adapters
87  with the Horizon chipset. These are all PCI cards supporting PIO, BM
88  DMA and a form of MMIO (registers only, not internal RAM).
89
90  The driver is only known to work with SONET and UTP Horizon Ultra
91  cards at 155Mb/s. However, code is in place to deal with both the
92  original Horizon and 25Mb/s operation.
93
94  There are two revisions of the Horizon ASIC: the original and the
95  Ultra. Details of hardware bugs are in section III.
96
97  The ASIC version can be distinguished by chip markings but is NOT
98  indicated by the PCI revision (all adapters seem to have PCI rev 1).
99
100  I believe that:
101
102  Horizon       => Collage  25 PCI Adapter (UTP and STP)
103  Horizon Ultra => Collage 155 PCI Client (UTP or SONET)
104  Ambassador x  => Collage 155 PCI Server (completely different)
105
106  Horizon (25Mb/s) is fitted with UTP and STP connectors. It seems to
107  have a Madge B154 plus glue logic serializer. I have also found a
108  really ancient version of this with slightly different glue. It
109  comes with the revision 0 (140-025-01) ASIC.
110
111  Horizon Ultra (155Mb/s) is fitted with either a Pulse Medialink
112  output (UTP) or an HP HFBR 5205 output (SONET). It has either
113  Madge's SAMBA framer or a SUNI-lite device (early versions). It
114  comes with the revision 1 (140-027-01) ASIC.
115
116  2. Detection
117
118  All Horizon-based cards present with the same PCI Vendor and Device
119  IDs. The standard Linux 2.2 PCI API is used to locate any cards and
120  to enable bus-mastering (with appropriate latency).
121
122  ATM_LAYER_STATUS in the control register distinguishes between the
123  two possible physical layers (25 and 155). It is not clear whether
124  the 155 cards can also operate at 25Mbps. We rely on the fact that a
125  card operates at 155 if and only if it has the newer Horizon Ultra
126  ASIC.
127
128  For 155 cards the two possible framers are probed for and then set
129  up for loop-timing.
130
131  3. Initialisation
132
133  The card is reset and then put into a known state. The physical
134  layer is configured for normal operation at the appropriate speed;
135  in the case of the 155 cards, the framer is initialised with
136  line-based timing; the internal RAM is zeroed and the allocation of
137  buffers for RX and TX is made; the Burnt In Address is read and
138  copied to the ATM ESI; various policy settings for RX (VPI bits,
139  unknown VCs, oam cells) are made. Ideally all policy items should be
140  configurable at module load (if not actually on-demand), however,
141  only the vpi vs vci bit allocation can be specified at insmod.
142
143  4. Shutdown
144
145  This is in response to module_cleaup. No VCs are in use and the card
146  should be idle; it is reset.
147
148  II Driver software (as it should be)
149
150  0. Traffic Parameters
151
152  The traffic classes (not an enumeration) are currently: ATM_NONE (no
153  traffic), ATM_UBR, ATM_CBR, ATM_VBR and ATM_ABR, ATM_ANYCLASS
154  (compatible with everything). Together with (perhaps only some of)
155  the following items they make up the traffic specification.
156
157  struct atm_trafprm {
158    unsigned char traffic_class; traffic class (ATM_UBR, ...)
159    int           max_pcr;       maximum PCR in cells per second
160    int           pcr;           desired PCR in cells per second
161    int           min_pcr;       minimum PCR in cells per second
162    int           max_cdv;       maximum CDV in microseconds
163    int           max_sdu;       maximum SDU in bytes
164  };
165
166  Note that these denote bandwidth available not bandwidth used; the
167  possibilities according to ATMF are:
168
169  Real Time (cdv and max CDT given)
170
171  CBR(pcr)             pcr bandwidth always available
172  rtVBR(pcr,scr,mbs)   scr bandwidth always available, upto pcr at mbs too
173
174  Non Real Time
175
176  nrtVBR(pcr,scr,mbs)  scr bandwidth always available, upto pcr at mbs too
177  UBR()
178  ABR(mcr,pcr)         mcr bandwidth always available, upto pcr (depending) too
179
180  mbs is max burst size (bucket)
181  pcr and scr have associated cdvt values
182  mcr is like scr but has no cdtv
183  cdtv may differ at each hop
184
185  Some of the above items are qos items (as opposed to traffic
186  parameters). We have nothing to do with qos. All except ABR can have
187  their traffic parameters converted to GCRA parameters. The GCRA may
188  be implemented as a (real-number) leaky bucket. The GCRA can be used
189  in complicated ways by switches and in simpler ways by end-stations.
190  It can be used both to filter incoming cells and shape out-going
191  cells.
192
193  ATM Linux actually supports:
194
195  ATM_NONE() (no traffic in this direction)
196  ATM_UBR(max_frame_size)
197  ATM_CBR(max/min_pcr, max_cdv, max_frame_size)
198
199  0 or ATM_MAX_PCR are used to indicate maximum available PCR
200
201  A traffic specification consists of the AAL type and separate
202  traffic specifications for either direction. In ATM Linux it is:
203
204  struct atm_qos {
205  struct atm_trafprm txtp;
206  struct atm_trafprm rxtp;
207  unsigned char aal;
208  };
209
210  AAL types are:
211
212  ATM_NO_AAL    AAL not specified
213  ATM_AAL0      "raw" ATM cells
214  ATM_AAL1      AAL1 (CBR)
215  ATM_AAL2      AAL2 (VBR)
216  ATM_AAL34     AAL3/4 (data)
217  ATM_AAL5      AAL5 (data)
218  ATM_SAAL      signaling AAL
219
220  The Horizon has support for AAL frame types: 0, 3/4 and 5. However,
221  it does not implement AAL 3/4 SAR and it has a different notion of
222  "raw cell" to ATM Linux's (48 bytes vs. 52 bytes) so neither are
223  supported by this driver.
224
225  The Horizon has limited support for ABR (including UBR), VBR and
226  CBR. Each TX channel has a bucket (containing up to 31 cell units)
227  and two timers (PCR and SCR) associated with it that can be used to
228  govern cell emissions and host notification (in the case of ABR this
229  is presumably so that RM cells may be emitted at appropriate times).
230  The timers may either be disabled or may be set to any of 240 values
231  (determined by the clock crystal, a fixed (?) per-device divider, a
232  configurable divider and a configurable timer preload value).
233
234  At the moment only UBR and CBR are supported by the driver. VBR will
235  be supported as soon as ATM for Linux supports it. ABR support is
236  very unlikely as RM cell handling is completely up to the driver.
237
238  1. TX (TX channel setup and TX transfer)
239
240  The TX half of the driver owns the TX Horizon registers. The TX
241  component in the IRQ handler is the BM completion handler. This can
242  only be entered when tx_busy is true (enforced by hardware). The
243  other TX component can only be entered when tx_busy is false
244  (enforced by driver). So TX is single-threaded.
245
246  Apart from a minor optimisation to not re-select the last channel,
247  the TX send component works as follows:
248
249  Atomic test and set tx_busy until we succeed; we should implement
250  some sort of timeout so that tx_busy will never be stuck at true.
251
252  If no TX channel is set up for this VC we wait for an idle one (if
253  necessary) and set it up.
254
255  At this point we have a TX channel ready for use. We wait for enough
256  buffers to become available then start a TX transmit (set the TX
257  descriptor, schedule transfer, exit).
258
259  The IRQ component handles TX completion (stats, free buffer, tx_busy
260  unset, exit). We also re-schedule further transfers for the same
261  frame if needed.
262
263  TX setup in more detail:
264
265  TX open is a nop, the relevant information is held in the hrz_vcc
266  (vcc->dev_data) structure and is "cached" on the card.
267
268  TX close gets the TX lock and clears the channel from the "cache".
269
270  2. RX (Data Available and RX transfer)
271
272  The RX half of the driver owns the RX registers. There are two RX
273  components in the IRQ handler: the data available handler deals with
274  fresh data that has arrived on the card, the BM completion handler
275  is very similar to the TX completion handler. The data available
276  handler grabs the rx_lock and it is only released once the data has
277  been discarded or completely transferred to the host. The BM
278  completion handler only runs when the lock is held; the data
279  available handler is locked out over the same period.
280
281  Data available on the card triggers an interrupt. If the data is not
282  suitable for our existing RX channels or we cannot allocate a buffer
283  it is flushed. Otherwise an RX receive is scheduled. Multiple RX
284  transfers may be scheduled for the same frame.
285
286  RX setup in more detail:
287
288  RX open...
289  RX close...
290
291  III Hardware Bugs
292
293  0. Byte vs Word addressing of adapter RAM.
294
295  A design feature; see the .h file (especially the memory map).
296
297  1. Bus Master Data Transfers (original Horizon only, fixed in Ultra)
298
299  The host must not start a transmit direction transfer at a
300  non-four-byte boundary in host memory. Instead the host should
301  perform a byte, or a two byte, or one byte followed by two byte
302  transfer in order to start the rest of the transfer on a four byte
303  boundary. RX is OK.
304
305  Simultaneous transmit and receive direction bus master transfers are
306  not allowed.
307
308  The simplest solution to these two is to always do PIO (never DMA)
309  in the TX direction on the original Horizon. More complicated
310  solutions are likely to hurt my brain.
311
312  2. Loss of buffer on close VC
313
314  When a VC is being closed, the buffer associated with it is not
315  returned to the pool. The host must store the reference to this
316  buffer and when opening a new VC then give it to that new VC.
317
318  The host intervention currently consists of stacking such a buffer
319  pointer at VC close and checking the stack at VC open.
320
321  3. Failure to close a VC
322
323  If a VC is currently receiving a frame then closing the VC may fail
324  and the frame continues to be received.
325
326  The solution is to make sure any received frames are flushed when
327  ready. This is currently done just before the solution to 2.
328
329  4. PCI bus (original Horizon only, fixed in Ultra)
330
331  Reading from the data port prior to initialisation will hang the PCI
332  bus. Just don't do that then! We don't.
333
334  IV To Do List
335
336  . Timer code may be broken.
337
338  . Allow users to specify buffer allocation split for TX and RX.
339
340  . Deal once and for all with buggy VC close.
341
342  . Handle interrupted and/or non-blocking operations.
343
344  . Change some macros to functions and move from .h to .c.
345
346  . Try to limit the number of TX frames each VC may have queued, in
347    order to reduce the chances of TX buffer exhaustion.
348
349  . Implement VBR (bucket and timers not understood) and ABR (need to
350    do RM cells manually); also no Linux support for either.
351
352  . Implement QoS changes on open VCs (involves extracting parts of VC open
353    and close into separate functions and using them to make changes).
354
355*/
356
357/********** globals **********/
358
359static void do_housekeeping (unsigned long arg);
360
361static unsigned short debug = 0;
362static unsigned short vpi_bits = 0;
363static int max_tx_size = 9000;
364static int max_rx_size = 9000;
365static unsigned char pci_lat = 0;
366
367/********** access functions **********/
368
369/* Read / Write Horizon registers */
370static inline void wr_regl (const hrz_dev * dev, unsigned char reg, u32 data) {
371  outl (cpu_to_le32 (data), dev->iobase + reg);
372}
373
374static inline u32 rd_regl (const hrz_dev * dev, unsigned char reg) {
375  return le32_to_cpu (inl (dev->iobase + reg));
376}
377
378static inline void wr_regw (const hrz_dev * dev, unsigned char reg, u16 data) {
379  outw (cpu_to_le16 (data), dev->iobase + reg);
380}
381
382static inline u16 rd_regw (const hrz_dev * dev, unsigned char reg) {
383  return le16_to_cpu (inw (dev->iobase + reg));
384}
385
386static inline void wrs_regb (const hrz_dev * dev, unsigned char reg, void * addr, u32 len) {
387  outsb (dev->iobase + reg, addr, len);
388}
389
390static inline void rds_regb (const hrz_dev * dev, unsigned char reg, void * addr, u32 len) {
391  insb (dev->iobase + reg, addr, len);
392}
393
394/* Read / Write to a given address in Horizon buffer memory.
395   Interrupts must be disabled between the address register and data
396   port accesses as these must form an atomic operation. */
397static inline void wr_mem (const hrz_dev * dev, HDW * addr, u32 data) {
398  // wr_regl (dev, MEM_WR_ADDR_REG_OFF, (u32) addr);
399  wr_regl (dev, MEM_WR_ADDR_REG_OFF, (addr - (HDW *) 0) * sizeof(HDW));
400  wr_regl (dev, MEMORY_PORT_OFF, data);
401}
402
403static inline u32 rd_mem (const hrz_dev * dev, HDW * addr) {
404  // wr_regl (dev, MEM_RD_ADDR_REG_OFF, (u32) addr);
405  wr_regl (dev, MEM_RD_ADDR_REG_OFF, (addr - (HDW *) 0) * sizeof(HDW));
406  return rd_regl (dev, MEMORY_PORT_OFF);
407}
408
409static inline void wr_framer (const hrz_dev * dev, u32 addr, u32 data) {
410  wr_regl (dev, MEM_WR_ADDR_REG_OFF, (u32) addr | 0x80000000);
411  wr_regl (dev, MEMORY_PORT_OFF, data);
412}
413
414static inline u32 rd_framer (const hrz_dev * dev, u32 addr) {
415  wr_regl (dev, MEM_RD_ADDR_REG_OFF, (u32) addr | 0x80000000);
416  return rd_regl (dev, MEMORY_PORT_OFF);
417}
418
419/********** specialised access functions **********/
420
421/* RX */
422
423static inline void FLUSH_RX_CHANNEL (hrz_dev * dev, u16 channel) {
424  wr_regw (dev, RX_CHANNEL_PORT_OFF, FLUSH_CHANNEL | channel);
425  return;
426}
427
428static void WAIT_FLUSH_RX_COMPLETE (hrz_dev * dev) {
429  while (rd_regw (dev, RX_CHANNEL_PORT_OFF) & FLUSH_CHANNEL)
430    ;
431  return;
432}
433
434static inline void SELECT_RX_CHANNEL (hrz_dev * dev, u16 channel) {
435  wr_regw (dev, RX_CHANNEL_PORT_OFF, channel);
436  return;
437}
438
439static void WAIT_UPDATE_COMPLETE (hrz_dev * dev) {
440  while (rd_regw (dev, RX_CHANNEL_PORT_OFF) & RX_CHANNEL_UPDATE_IN_PROGRESS)
441    ;
442  return;
443}
444
445/* TX */
446
447static inline void SELECT_TX_CHANNEL (hrz_dev * dev, u16 tx_channel) {
448  wr_regl (dev, TX_CHANNEL_PORT_OFF, tx_channel);
449  return;
450}
451
452/* Update or query one configuration parameter of a particular channel. */
453
454static inline void update_tx_channel_config (hrz_dev * dev, short chan, u8 mode, u16 value) {
455  wr_regw (dev, TX_CHANNEL_CONFIG_COMMAND_OFF,
456	   chan * TX_CHANNEL_CONFIG_MULT | mode);
457    wr_regw (dev, TX_CHANNEL_CONFIG_DATA_OFF, value);
458    return;
459}
460
461static inline u16 query_tx_channel_config (hrz_dev * dev, short chan, u8 mode) {
462  wr_regw (dev, TX_CHANNEL_CONFIG_COMMAND_OFF,
463	   chan * TX_CHANNEL_CONFIG_MULT | mode);
464    return rd_regw (dev, TX_CHANNEL_CONFIG_DATA_OFF);
465}
466
467/********** dump functions **********/
468
469static inline void dump_skb (char * prefix, unsigned int vc, struct sk_buff * skb) {
470#ifdef DEBUG_HORIZON
471  unsigned int i;
472  unsigned char * data = skb->data;
473  PRINTDB (DBG_DATA, "%s(%u) ", prefix, vc);
474  for (i=0; i<skb->len && i < 256;i++)
475    PRINTDM (DBG_DATA, "%02x ", data[i]);
476  PRINTDE (DBG_DATA,"");
477#else
478  (void) prefix;
479  (void) vc;
480  (void) skb;
481#endif
482  return;
483}
484
485static inline void dump_regs (hrz_dev * dev) {
486#ifdef DEBUG_HORIZON
487  PRINTD (DBG_REGS, "CONTROL 0: %#x", rd_regl (dev, CONTROL_0_REG));
488  PRINTD (DBG_REGS, "RX CONFIG: %#x", rd_regw (dev, RX_CONFIG_OFF));
489  PRINTD (DBG_REGS, "TX CONFIG: %#x", rd_regw (dev, TX_CONFIG_OFF));
490  PRINTD (DBG_REGS, "TX STATUS: %#x", rd_regw (dev, TX_STATUS_OFF));
491  PRINTD (DBG_REGS, "IRQ ENBLE: %#x", rd_regl (dev, INT_ENABLE_REG_OFF));
492  PRINTD (DBG_REGS, "IRQ SORCE: %#x", rd_regl (dev, INT_SOURCE_REG_OFF));
493#else
494  (void) dev;
495#endif
496  return;
497}
498
499static inline void dump_framer (hrz_dev * dev) {
500#ifdef DEBUG_HORIZON
501  unsigned int i;
502  PRINTDB (DBG_REGS, "framer registers:");
503  for (i = 0; i < 0x10; ++i)
504    PRINTDM (DBG_REGS, " %02x", rd_framer (dev, i));
505  PRINTDE (DBG_REGS,"");
506#else
507  (void) dev;
508#endif
509  return;
510}
511
512/********** VPI/VCI <-> (RX) channel conversions **********/
513
514/* RX channels are 10 bit integers, these fns are quite paranoid */
515
516static inline int channel_to_vpivci (const u16 channel, short * vpi, int * vci) {
517  unsigned short vci_bits = 10 - vpi_bits;
518  if ((channel & RX_CHANNEL_MASK) == channel) {
519    *vci = channel & ((~0)<<vci_bits);
520    *vpi = channel >> vci_bits;
521    return channel ? 0 : -EINVAL;
522  }
523  return -EINVAL;
524}
525
526static inline int vpivci_to_channel (u16 * channel, const short vpi, const int vci) {
527  unsigned short vci_bits = 10 - vpi_bits;
528  if (0 <= vpi && vpi < 1<<vpi_bits && 0 <= vci && vci < 1<<vci_bits) {
529    *channel = vpi<<vci_bits | vci;
530    return *channel ? 0 : -EINVAL;
531  }
532  return -EINVAL;
533}
534
535/********** decode RX queue entries **********/
536
537static inline u16 rx_q_entry_to_length (u32 x) {
538  return x & RX_Q_ENTRY_LENGTH_MASK;
539}
540
541static inline u16 rx_q_entry_to_rx_channel (u32 x) {
542  return (x>>RX_Q_ENTRY_CHANNEL_SHIFT) & RX_CHANNEL_MASK;
543}
544
545/* Cell Transmit Rate Values
546 *
547 * the cell transmit rate (cells per sec) can be set to a variety of
548 * different values by specifying two parameters: a timer preload from
549 * 1 to 16 (stored as 0 to 15) and a clock divider (2 to the power of
550 * an exponent from 0 to 14; the special value 15 disables the timer).
551 *
552 * cellrate = baserate / (preload * 2^divider)
553 *
554 * The maximum cell rate that can be specified is therefore just the
555 * base rate. Halving the preload is equivalent to adding 1 to the
556 * divider and so values 1 to 8 of the preload are redundant except
557 * in the case of a maximal divider (14).
558 *
559 * Given a desired cell rate, an algorithm to determine the preload
560 * and divider is:
561 *
562 * a) x = baserate / cellrate, want p * 2^d = x (as far as possible)
563 * b) if x > 16 * 2^14 then set p = 16, d = 14 (min rate), done
564 *    if x <= 16 then set p = x, d = 0 (high rates), done
565 * c) now have 16 < x <= 2^18, or 1 < x/16 <= 2^14 and we want to
566 *    know n such that 2^(n-1) < x/16 <= 2^n, so slide a bit until
567 *    we find the range (n will be between 1 and 14), set d = n
568 * d) Also have 8 < x/2^n <= 16, so set p nearest x/2^n
569 *
570 * The algorithm used below is a minor variant of the above.
571 *
572 * The base rate is derived from the oscillator frequency (Hz) using a
573 * fixed divider:
574 *
575 * baserate = freq / 32 in the case of some Unknown Card
576 * baserate = freq / 8  in the case of the Horizon        25
577 * baserate = freq / 8  in the case of the Horizon Ultra 155
578 *
579 * The Horizon cards have oscillators and base rates as follows:
580 *
581 * Card               Oscillator  Base Rate
582 * Unknown Card       33 MHz      1.03125 MHz (33 MHz = PCI freq)
583 * Horizon        25  32 MHz      4       MHz
584 * Horizon Ultra 155  40 MHz      5       MHz
585 *
586 * The following defines give the base rates in Hz. These were
587 * previously a factor of 100 larger, no doubt someone was using
588 * cps*100.
589 */
590
591#define BR_UKN 1031250l
592#define BR_HRZ 4000000l
593#define BR_ULT 5000000l
594
595// d is an exponent
596#define CR_MIND 0
597#define CR_MAXD 14
598
599// p ranges from 1 to a power of 2
600#define CR_MAXPEXP 4
601
602static int make_rate (const hrz_dev * dev, u32 c, rounding r,
603		      u16 * bits, unsigned int * actual)
604{
605	// note: rounding the rate down means rounding 'p' up
606	const unsigned long br = test_bit(ultra, &dev->flags) ? BR_ULT : BR_HRZ;
607
608	u32 div = CR_MIND;
609	u32 pre;
610
611	// br_exp and br_man are used to avoid overflowing (c*maxp*2^d) in
612	// the tests below. We could think harder about exact possibilities
613	// of failure...
614
615	unsigned long br_man = br;
616	unsigned int br_exp = 0;
617
618	PRINTD (DBG_QOS|DBG_FLOW, "make_rate b=%lu, c=%u, %s", br, c,
619		r == round_up ? "up" : r == round_down ? "down" : "nearest");
620
621	// avoid div by zero
622	if (!c) {
623		PRINTD (DBG_QOS|DBG_ERR, "zero rate is not allowed!");
624		return -EINVAL;
625	}
626
627	while (br_exp < CR_MAXPEXP + CR_MIND && (br_man % 2 == 0)) {
628		br_man = br_man >> 1;
629		++br_exp;
630	}
631	// (br >>br_exp) <<br_exp == br and
632	// br_exp <= CR_MAXPEXP+CR_MIND
633
634	if (br_man <= (c << (CR_MAXPEXP+CR_MIND-br_exp))) {
635		// Equivalent to: B <= (c << (MAXPEXP+MIND))
636		// take care of rounding
637		switch (r) {
638			case round_down:
639				pre = DIV_ROUND_UP(br, c<<div);
640				// but p must be non-zero
641				if (!pre)
642					pre = 1;
643				break;
644			case round_nearest:
645				pre = DIV_ROUND_CLOSEST(br, c<<div);
646				// but p must be non-zero
647				if (!pre)
648					pre = 1;
649				break;
650			default:	/* round_up */
651				pre = br/(c<<div);
652				// but p must be non-zero
653				if (!pre)
654					return -EINVAL;
655		}
656		PRINTD (DBG_QOS, "A: p=%u, d=%u", pre, div);
657		goto got_it;
658	}
659
660	// at this point we have
661	// d == MIND and (c << (MAXPEXP+MIND)) < B
662	while (div < CR_MAXD) {
663		div++;
664		if (br_man <= (c << (CR_MAXPEXP+div-br_exp))) {
665			// Equivalent to: B <= (c << (MAXPEXP+d))
666			// c << (MAXPEXP+d-1) < B <= c << (MAXPEXP+d)
667			// 1 << (MAXPEXP-1) < B/2^d/c <= 1 << MAXPEXP
668			// MAXP/2 < B/c2^d <= MAXP
669			// take care of rounding
670			switch (r) {
671				case round_down:
672					pre = DIV_ROUND_UP(br, c<<div);
673					break;
674				case round_nearest:
675					pre = DIV_ROUND_CLOSEST(br, c<<div);
676					break;
677				default: /* round_up */
678					pre = br/(c<<div);
679			}
680			PRINTD (DBG_QOS, "B: p=%u, d=%u", pre, div);
681			goto got_it;
682		}
683	}
684	// at this point we have
685	// d == MAXD and (c << (MAXPEXP+MAXD)) < B
686	// but we cannot go any higher
687	// take care of rounding
688	if (r == round_down)
689		return -EINVAL;
690	pre = 1 << CR_MAXPEXP;
691	PRINTD (DBG_QOS, "C: p=%u, d=%u", pre, div);
692got_it:
693	// paranoia
694	if (div > CR_MAXD || (!pre) || pre > 1<<CR_MAXPEXP) {
695		PRINTD (DBG_QOS, "set_cr internal failure: d=%u p=%u",
696			div, pre);
697		return -EINVAL;
698	} else {
699		if (bits)
700			*bits = (div<<CLOCK_SELECT_SHIFT) | (pre-1);
701		if (actual) {
702			*actual = DIV_ROUND_UP(br, pre<<div);
703			PRINTD (DBG_QOS, "actual rate: %u", *actual);
704		}
705		return 0;
706	}
707}
708
709static int make_rate_with_tolerance (const hrz_dev * dev, u32 c, rounding r, unsigned int tol,
710				     u16 * bit_pattern, unsigned int * actual) {
711  unsigned int my_actual;
712
713  PRINTD (DBG_QOS|DBG_FLOW, "make_rate_with_tolerance c=%u, %s, tol=%u",
714	  c, (r == round_up) ? "up" : (r == round_down) ? "down" : "nearest", tol);
715
716  if (!actual)
717    // actual rate is not returned
718    actual = &my_actual;
719
720  if (make_rate (dev, c, round_nearest, bit_pattern, actual))
721    // should never happen as round_nearest always succeeds
722    return -1;
723
724  if (c - tol <= *actual && *actual <= c + tol)
725    // within tolerance
726    return 0;
727  else
728    // intolerant, try rounding instead
729    return make_rate (dev, c, r, bit_pattern, actual);
730}
731
732/********** Listen on a VC **********/
733
734static int hrz_open_rx (hrz_dev * dev, u16 channel) {
735  // is there any guarantee that we don't get two simulataneous
736  // identical calls of this function from different processes? yes
737  // rate_lock
738  unsigned long flags;
739  u32 channel_type; // u16?
740
741  u16 buf_ptr = RX_CHANNEL_IDLE;
742
743  rx_ch_desc * rx_desc = &memmap->rx_descs[channel];
744
745  PRINTD (DBG_FLOW, "hrz_open_rx %x", channel);
746
747  spin_lock_irqsave (&dev->mem_lock, flags);
748  channel_type = rd_mem (dev, &rx_desc->wr_buf_type) & BUFFER_PTR_MASK;
749  spin_unlock_irqrestore (&dev->mem_lock, flags);
750
751  // very serious error, should never occur
752  if (channel_type != RX_CHANNEL_DISABLED) {
753    PRINTD (DBG_ERR|DBG_VCC, "RX channel for VC already open");
754    return -EBUSY; // clean up?
755  }
756
757  // Give back spare buffer
758  if (dev->noof_spare_buffers) {
759    buf_ptr = dev->spare_buffers[--dev->noof_spare_buffers];
760    PRINTD (DBG_VCC, "using a spare buffer: %u", buf_ptr);
761    // should never occur
762    if (buf_ptr == RX_CHANNEL_DISABLED || buf_ptr == RX_CHANNEL_IDLE) {
763      // but easy to recover from
764      PRINTD (DBG_ERR|DBG_VCC, "bad spare buffer pointer, using IDLE");
765      buf_ptr = RX_CHANNEL_IDLE;
766    }
767  } else {
768    PRINTD (DBG_VCC, "using IDLE buffer pointer");
769  }
770
771  // Channel is currently disabled so change its status to idle
772
773  // do we really need to save the flags again?
774  spin_lock_irqsave (&dev->mem_lock, flags);
775
776  wr_mem (dev, &rx_desc->wr_buf_type,
777	  buf_ptr | CHANNEL_TYPE_AAL5 | FIRST_CELL_OF_AAL5_FRAME);
778  if (buf_ptr != RX_CHANNEL_IDLE)
779    wr_mem (dev, &rx_desc->rd_buf_type, buf_ptr);
780
781  spin_unlock_irqrestore (&dev->mem_lock, flags);
782
783  // rxer->rate = make_rate (qos->peak_cells);
784
785  PRINTD (DBG_FLOW, "hrz_open_rx ok");
786
787  return 0;
788}
789
790
791/********** free an skb (as per ATM device driver documentation) **********/
792
793static void hrz_kfree_skb (struct sk_buff * skb) {
794  if (ATM_SKB(skb)->vcc->pop) {
795    ATM_SKB(skb)->vcc->pop (ATM_SKB(skb)->vcc, skb);
796  } else {
797    dev_kfree_skb_any (skb);
798  }
799}
800
801/********** cancel listen on a VC **********/
802
803static void hrz_close_rx (hrz_dev * dev, u16 vc) {
804  unsigned long flags;
805
806  u32 value;
807
808  u32 r1, r2;
809
810  rx_ch_desc * rx_desc = &memmap->rx_descs[vc];
811
812  int was_idle = 0;
813
814  spin_lock_irqsave (&dev->mem_lock, flags);
815  value = rd_mem (dev, &rx_desc->wr_buf_type) & BUFFER_PTR_MASK;
816  spin_unlock_irqrestore (&dev->mem_lock, flags);
817
818  if (value == RX_CHANNEL_DISABLED) {
819    // I suppose this could happen once we deal with _NONE traffic properly
820    PRINTD (DBG_VCC, "closing VC: RX channel %u already disabled", vc);
821    return;
822  }
823  if (value == RX_CHANNEL_IDLE)
824    was_idle = 1;
825
826  spin_lock_irqsave (&dev->mem_lock, flags);
827
828  for (;;) {
829    wr_mem (dev, &rx_desc->wr_buf_type, RX_CHANNEL_DISABLED);
830
831    if ((rd_mem (dev, &rx_desc->wr_buf_type) & BUFFER_PTR_MASK) == RX_CHANNEL_DISABLED)
832      break;
833
834    was_idle = 0;
835  }
836
837  if (was_idle) {
838    spin_unlock_irqrestore (&dev->mem_lock, flags);
839    return;
840  }
841
842  WAIT_FLUSH_RX_COMPLETE(dev);
843
844  // handler to discard frames that remain queued for delivery. If the
845  // worry is that immediately reopening the channel (perhaps by a
846  // different process) may cause some data to be mis-delivered then
847  // there may still be a simpler solution (such as busy-waiting on
848  // rx_busy once the channel is disabled or before a new one is
849  // opened - does this leave any holes?). Arguably setting up and
850  // tearing down the TX and RX halves of each virtual circuit could
851  // most safely be done within ?x_busy protected regions.
852
853  // OK, current changes are that Simon's marker is disabled and we DO
854  // look for NULL rxer elsewhere. The code here seems flush frames
855  // and then remember the last dead cell belonging to the channel
856  // just disabled - the cell gets relinked at the next vc_open.
857  // However, when all VCs are closed or only a few opened there are a
858  // handful of buffers that are unusable.
859
860  // Does anyone feel like documenting spare_buffers properly?
861  // Does anyone feel like fixing this in a nicer way?
862
863  // Flush any data which is left in the channel
864  for (;;) {
865    // Change the rx channel port to something different to the RX
866    // channel we are trying to close to force Horizon to flush the rx
867    // channel read and write pointers.
868
869    u16 other = vc^(RX_CHANS/2);
870
871    SELECT_RX_CHANNEL (dev, other);
872    WAIT_UPDATE_COMPLETE (dev);
873
874    r1 = rd_mem (dev, &rx_desc->rd_buf_type);
875
876    // Select this RX channel. Flush doesn't seem to work unless we
877    // select an RX channel before hand
878
879    SELECT_RX_CHANNEL (dev, vc);
880    WAIT_UPDATE_COMPLETE (dev);
881
882    // Attempt to flush a frame on this RX channel
883
884    FLUSH_RX_CHANNEL (dev, vc);
885    WAIT_FLUSH_RX_COMPLETE (dev);
886
887    // Force Horizon to flush rx channel read and write pointers as before
888
889    SELECT_RX_CHANNEL (dev, other);
890    WAIT_UPDATE_COMPLETE (dev);
891
892    r2 = rd_mem (dev, &rx_desc->rd_buf_type);
893
894    PRINTD (DBG_VCC|DBG_RX, "r1 = %u, r2 = %u", r1, r2);
895
896    if (r1 == r2) {
897      dev->spare_buffers[dev->noof_spare_buffers++] = (u16)r1;
898      break;
899    }
900  }
901
902
903  spin_unlock_irqrestore (&dev->mem_lock, flags);
904
905  return;
906}
907
908/********** schedule RX transfers **********/
909
910// Note on tail recursion: a GCC developer said that it is not likely
911// to be fixed soon, so do not define TAILRECUSRIONWORKS unless you
912// are sure it does as you may otherwise overflow the kernel stack.
913
914// giving this fn a return value would help GCC, alledgedly
915
916static void rx_schedule (hrz_dev * dev, int irq) {
917  unsigned int rx_bytes;
918
919  int pio_instead = 0;
920#ifndef TAILRECURSIONWORKS
921  pio_instead = 1;
922  while (pio_instead) {
923#endif
924    // bytes waiting for RX transfer
925    rx_bytes = dev->rx_bytes;
926
927
928    // this code follows the TX code but (at the moment) there is only
929    // one region - the skb itself. I don't know if this will change,
930    // but it doesn't hurt to have the code here, disabled.
931
932    if (rx_bytes) {
933      // start next transfer within same region
934      if (rx_bytes <= MAX_PIO_COUNT) {
935	PRINTD (DBG_RX|DBG_BUS, "(pio)");
936	pio_instead = 1;
937      }
938      if (rx_bytes <= MAX_TRANSFER_COUNT) {
939	PRINTD (DBG_RX|DBG_BUS, "(simple or last multi)");
940	dev->rx_bytes = 0;
941      } else {
942	PRINTD (DBG_RX|DBG_BUS, "(continuing multi)");
943	dev->rx_bytes = rx_bytes - MAX_TRANSFER_COUNT;
944	rx_bytes = MAX_TRANSFER_COUNT;
945      }
946    } else {
947      // rx_bytes == 0 -- we're between regions
948      // regions remaining to transfer
949      unsigned int rx_regions = 0;
950
951      if (rx_regions) {
952      } else {
953	// rx_regions == 0
954	// that's all folks - end of frame
955	struct sk_buff * skb = dev->rx_skb;
956	// dev->rx_iovec = 0;
957
958	FLUSH_RX_CHANNEL (dev, dev->rx_channel);
959
960	dump_skb ("<<<", dev->rx_channel, skb);
961
962	PRINTD (DBG_RX|DBG_SKB, "push %p %u", skb->data, skb->len);
963
964	{
965	  struct atm_vcc * vcc = ATM_SKB(skb)->vcc;
966	  // VC layer stats
967	  atomic_inc(&vcc->stats->rx);
968	  __net_timestamp(skb);
969	  // end of our responsability
970	  vcc->push (vcc, skb);
971	}
972      }
973    }
974
975    // note: writing RX_COUNT clears any interrupt condition
976    if (rx_bytes) {
977      if (pio_instead) {
978	if (irq)
979	  wr_regl (dev, MASTER_RX_COUNT_REG_OFF, 0);
980	rds_regb (dev, DATA_PORT_OFF, dev->rx_addr, rx_bytes);
981      } else {
982	wr_regl (dev, MASTER_RX_ADDR_REG_OFF, virt_to_bus (dev->rx_addr));
983	wr_regl (dev, MASTER_RX_COUNT_REG_OFF, rx_bytes);
984      }
985      dev->rx_addr += rx_bytes;
986    } else {
987      if (irq)
988	wr_regl (dev, MASTER_RX_COUNT_REG_OFF, 0);
989      // allow another RX thread to start
990      YELLOW_LED_ON(dev);
991      clear_bit (rx_busy, &dev->flags);
992      PRINTD (DBG_RX, "cleared rx_busy for dev %p", dev);
993    }
994
995#ifdef TAILRECURSIONWORKS
996    // and we all bless optimised tail calls
997    if (pio_instead)
998      return rx_schedule (dev, 0);
999    return;
1000#else
1001    // grrrrrrr!
1002    irq = 0;
1003  }
1004  return;
1005#endif
1006}
1007
1008/********** handle RX bus master complete events **********/
1009
1010static void rx_bus_master_complete_handler (hrz_dev * dev) {
1011  if (test_bit (rx_busy, &dev->flags)) {
1012    rx_schedule (dev, 1);
1013  } else {
1014    PRINTD (DBG_RX|DBG_ERR, "unexpected RX bus master completion");
1015    // clear interrupt condition on adapter
1016    wr_regl (dev, MASTER_RX_COUNT_REG_OFF, 0);
1017  }
1018  return;
1019}
1020
1021/********** (queue to) become the next TX thread **********/
1022
1023static int tx_hold (hrz_dev * dev) {
1024  PRINTD (DBG_TX, "sleeping at tx lock %p %lu", dev, dev->flags);
1025  wait_event_interruptible(dev->tx_queue, (!test_and_set_bit(tx_busy, &dev->flags)));
1026  PRINTD (DBG_TX, "woken at tx lock %p %lu", dev, dev->flags);
1027  if (signal_pending (current))
1028    return -1;
1029  PRINTD (DBG_TX, "set tx_busy for dev %p", dev);
1030  return 0;
1031}
1032
1033/********** allow another TX thread to start **********/
1034
1035static inline void tx_release (hrz_dev * dev) {
1036  clear_bit (tx_busy, &dev->flags);
1037  PRINTD (DBG_TX, "cleared tx_busy for dev %p", dev);
1038  wake_up_interruptible (&dev->tx_queue);
1039}
1040
1041/********** schedule TX transfers **********/
1042
1043static void tx_schedule (hrz_dev * const dev, int irq) {
1044  unsigned int tx_bytes;
1045
1046  int append_desc = 0;
1047
1048  int pio_instead = 0;
1049#ifndef TAILRECURSIONWORKS
1050  pio_instead = 1;
1051  while (pio_instead) {
1052#endif
1053    // bytes in current region waiting for TX transfer
1054    tx_bytes = dev->tx_bytes;
1055
1056
1057    if (tx_bytes) {
1058      // start next transfer within same region
1059      if (!test_bit (ultra, &dev->flags) || tx_bytes <= MAX_PIO_COUNT) {
1060	PRINTD (DBG_TX|DBG_BUS, "(pio)");
1061	pio_instead = 1;
1062      }
1063      if (tx_bytes <= MAX_TRANSFER_COUNT) {
1064	PRINTD (DBG_TX|DBG_BUS, "(simple or last multi)");
1065	if (!dev->tx_iovec) {
1066	  // end of last region
1067	  append_desc = 1;
1068	}
1069	dev->tx_bytes = 0;
1070      } else {
1071	PRINTD (DBG_TX|DBG_BUS, "(continuing multi)");
1072	dev->tx_bytes = tx_bytes - MAX_TRANSFER_COUNT;
1073	tx_bytes = MAX_TRANSFER_COUNT;
1074      }
1075    } else {
1076      // tx_bytes == 0 -- we're between regions
1077      // regions remaining to transfer
1078      unsigned int tx_regions = dev->tx_regions;
1079
1080      if (tx_regions) {
1081	// start a new region
1082	dev->tx_addr = dev->tx_iovec->iov_base;
1083	tx_bytes = dev->tx_iovec->iov_len;
1084	++dev->tx_iovec;
1085	dev->tx_regions = tx_regions - 1;
1086
1087	if (!test_bit (ultra, &dev->flags) || tx_bytes <= MAX_PIO_COUNT) {
1088	  PRINTD (DBG_TX|DBG_BUS, "(pio)");
1089	  pio_instead = 1;
1090	}
1091	if (tx_bytes <= MAX_TRANSFER_COUNT) {
1092	  PRINTD (DBG_TX|DBG_BUS, "(full region)");
1093	  dev->tx_bytes = 0;
1094	} else {
1095	  PRINTD (DBG_TX|DBG_BUS, "(start multi region)");
1096	  dev->tx_bytes = tx_bytes - MAX_TRANSFER_COUNT;
1097	  tx_bytes = MAX_TRANSFER_COUNT;
1098	}
1099      } else {
1100	// tx_regions == 0
1101	// that's all folks - end of frame
1102	struct sk_buff * skb = dev->tx_skb;
1103	dev->tx_iovec = NULL;
1104
1105	// VC layer stats
1106	atomic_inc(&ATM_SKB(skb)->vcc->stats->tx);
1107
1108	// free the skb
1109	hrz_kfree_skb (skb);
1110      }
1111    }
1112
1113    // note: writing TX_COUNT clears any interrupt condition
1114    if (tx_bytes) {
1115      if (pio_instead) {
1116	if (irq)
1117	  wr_regl (dev, MASTER_TX_COUNT_REG_OFF, 0);
1118	wrs_regb (dev, DATA_PORT_OFF, dev->tx_addr, tx_bytes);
1119	if (append_desc)
1120	  wr_regl (dev, TX_DESCRIPTOR_PORT_OFF, cpu_to_be32 (dev->tx_skb->len));
1121      } else {
1122	wr_regl (dev, MASTER_TX_ADDR_REG_OFF, virt_to_bus (dev->tx_addr));
1123	if (append_desc)
1124	  wr_regl (dev, TX_DESCRIPTOR_REG_OFF, cpu_to_be32 (dev->tx_skb->len));
1125	wr_regl (dev, MASTER_TX_COUNT_REG_OFF,
1126		 append_desc
1127		 ? tx_bytes | MASTER_TX_AUTO_APPEND_DESC
1128		 : tx_bytes);
1129      }
1130      dev->tx_addr += tx_bytes;
1131    } else {
1132      if (irq)
1133	wr_regl (dev, MASTER_TX_COUNT_REG_OFF, 0);
1134      YELLOW_LED_ON(dev);
1135      tx_release (dev);
1136    }
1137
1138#ifdef TAILRECURSIONWORKS
1139    // and we all bless optimised tail calls
1140    if (pio_instead)
1141      return tx_schedule (dev, 0);
1142    return;
1143#else
1144    // grrrrrrr!
1145    irq = 0;
1146  }
1147  return;
1148#endif
1149}
1150
1151/********** handle TX bus master complete events **********/
1152
1153static void tx_bus_master_complete_handler (hrz_dev * dev) {
1154  if (test_bit (tx_busy, &dev->flags)) {
1155    tx_schedule (dev, 1);
1156  } else {
1157    PRINTD (DBG_TX|DBG_ERR, "unexpected TX bus master completion");
1158    // clear interrupt condition on adapter
1159    wr_regl (dev, MASTER_TX_COUNT_REG_OFF, 0);
1160  }
1161  return;
1162}
1163
1164/********** move RX Q pointer to next item in circular buffer **********/
1165
1166// called only from IRQ sub-handler
1167static u32 rx_queue_entry_next (hrz_dev * dev) {
1168  u32 rx_queue_entry;
1169  spin_lock (&dev->mem_lock);
1170  rx_queue_entry = rd_mem (dev, &dev->rx_q_entry->entry);
1171  if (dev->rx_q_entry == dev->rx_q_wrap)
1172    dev->rx_q_entry = dev->rx_q_reset;
1173  else
1174    dev->rx_q_entry++;
1175  wr_regw (dev, RX_QUEUE_RD_PTR_OFF, dev->rx_q_entry - dev->rx_q_reset);
1176  spin_unlock (&dev->mem_lock);
1177  return rx_queue_entry;
1178}
1179
1180/********** handle RX disabled by device **********/
1181
1182static inline void rx_disabled_handler (hrz_dev * dev) {
1183  wr_regw (dev, RX_CONFIG_OFF, rd_regw (dev, RX_CONFIG_OFF) | RX_ENABLE);
1184  // count me please
1185  PRINTK (KERN_WARNING, "RX was disabled!");
1186}
1187
1188/********** handle RX data received by device **********/
1189
1190// called from IRQ handler
1191static void rx_data_av_handler (hrz_dev * dev) {
1192  u32 rx_queue_entry;
1193  u32 rx_queue_entry_flags;
1194  u16 rx_len;
1195  u16 rx_channel;
1196
1197  PRINTD (DBG_FLOW, "hrz_data_av_handler");
1198
1199  // try to grab rx lock (not possible during RX bus mastering)
1200  if (test_and_set_bit (rx_busy, &dev->flags)) {
1201    PRINTD (DBG_RX, "locked out of rx lock");
1202    return;
1203  }
1204  PRINTD (DBG_RX, "set rx_busy for dev %p", dev);
1205  // lock is cleared if we fail now, o/w after bus master completion
1206
1207  YELLOW_LED_OFF(dev);
1208
1209  rx_queue_entry = rx_queue_entry_next (dev);
1210
1211  rx_len = rx_q_entry_to_length (rx_queue_entry);
1212  rx_channel = rx_q_entry_to_rx_channel (rx_queue_entry);
1213
1214  WAIT_FLUSH_RX_COMPLETE (dev);
1215
1216  SELECT_RX_CHANNEL (dev, rx_channel);
1217
1218  PRINTD (DBG_RX, "rx_queue_entry is: %#x", rx_queue_entry);
1219  rx_queue_entry_flags = rx_queue_entry & (RX_CRC_32_OK|RX_COMPLETE_FRAME|SIMONS_DODGEY_MARKER);
1220
1221  if (!rx_len) {
1222    // (at least) bus-mastering breaks if we try to handle a
1223    // zero-length frame, besides AAL5 does not support them
1224    PRINTK (KERN_ERR, "zero-length frame!");
1225    rx_queue_entry_flags &= ~RX_COMPLETE_FRAME;
1226  }
1227
1228  if (rx_queue_entry_flags & SIMONS_DODGEY_MARKER) {
1229    PRINTD (DBG_RX|DBG_ERR, "Simon's marker detected!");
1230  }
1231  if (rx_queue_entry_flags == (RX_CRC_32_OK | RX_COMPLETE_FRAME)) {
1232    struct atm_vcc * atm_vcc;
1233
1234    PRINTD (DBG_RX, "got a frame on rx_channel %x len %u", rx_channel, rx_len);
1235
1236    atm_vcc = dev->rxer[rx_channel];
1237    // if no vcc is assigned to this channel, we should drop the frame
1238    // (is this what SIMONS etc. was trying to achieve?)
1239
1240    if (atm_vcc) {
1241
1242      if (atm_vcc->qos.rxtp.traffic_class != ATM_NONE) {
1243
1244	if (rx_len <= atm_vcc->qos.rxtp.max_sdu) {
1245
1246	  struct sk_buff * skb = atm_alloc_charge (atm_vcc, rx_len, GFP_ATOMIC);
1247	  if (skb) {
1248	    // remember this so we can push it later
1249	    dev->rx_skb = skb;
1250	    // remember this so we can flush it later
1251	    dev->rx_channel = rx_channel;
1252
1253	    // prepare socket buffer
1254	    skb_put (skb, rx_len);
1255	    ATM_SKB(skb)->vcc = atm_vcc;
1256
1257	    // simple transfer
1258	    // dev->rx_regions = 0;
1259	    // dev->rx_iovec = 0;
1260	    dev->rx_bytes = rx_len;
1261	    dev->rx_addr = skb->data;
1262	    PRINTD (DBG_RX, "RX start simple transfer (addr %p, len %d)",
1263		    skb->data, rx_len);
1264
1265	    // do the business
1266	    rx_schedule (dev, 0);
1267	    return;
1268
1269	  } else {
1270	    PRINTD (DBG_SKB|DBG_WARN, "failed to get skb");
1271	  }
1272
1273	} else {
1274	  PRINTK (KERN_INFO, "frame received on TX-only VC %x", rx_channel);
1275	  // do we count this?
1276	}
1277
1278      } else {
1279	PRINTK (KERN_WARNING, "dropped over-size frame");
1280	// do we count this?
1281      }
1282
1283    } else {
1284      PRINTD (DBG_WARN|DBG_VCC|DBG_RX, "no VCC for this frame (VC closed)");
1285      // do we count this?
1286    }
1287
1288  } else {
1289    // Wait update complete ? SPONG
1290  }
1291
1292  // RX was aborted
1293  YELLOW_LED_ON(dev);
1294
1295  FLUSH_RX_CHANNEL (dev,rx_channel);
1296  clear_bit (rx_busy, &dev->flags);
1297
1298  return;
1299}
1300
1301/********** interrupt handler **********/
1302
1303static irqreturn_t interrupt_handler(int irq, void *dev_id)
1304{
1305  hrz_dev *dev = dev_id;
1306  u32 int_source;
1307  unsigned int irq_ok;
1308
1309  PRINTD (DBG_FLOW, "interrupt_handler: %p", dev_id);
1310
1311  // definitely for us
1312  irq_ok = 0;
1313  while ((int_source = rd_regl (dev, INT_SOURCE_REG_OFF)
1314	  & INTERESTING_INTERRUPTS)) {
1315    // In the interests of fairness, the handlers below are
1316    // called in sequence and without immediate return to the head of
1317    // the while loop. This is only of issue for slow hosts (or when
1318    // debugging messages are on). Really slow hosts may find a fast
1319    // sender keeps them permanently in the IRQ handler. :(
1320
1321    // (only an issue for slow hosts) RX completion goes before
1322    // rx_data_av as the former implies rx_busy and so the latter
1323    // would just abort. If it reschedules another transfer
1324    // (continuing the same frame) then it will not clear rx_busy.
1325
1326    // (only an issue for slow hosts) TX completion goes before RX
1327    // data available as it is a much shorter routine - there is the
1328    // chance that any further transfers it schedules will be complete
1329    // by the time of the return to the head of the while loop
1330
1331    if (int_source & RX_BUS_MASTER_COMPLETE) {
1332      ++irq_ok;
1333      PRINTD (DBG_IRQ|DBG_BUS|DBG_RX, "rx_bus_master_complete asserted");
1334      rx_bus_master_complete_handler (dev);
1335    }
1336    if (int_source & TX_BUS_MASTER_COMPLETE) {
1337      ++irq_ok;
1338      PRINTD (DBG_IRQ|DBG_BUS|DBG_TX, "tx_bus_master_complete asserted");
1339      tx_bus_master_complete_handler (dev);
1340    }
1341    if (int_source & RX_DATA_AV) {
1342      ++irq_ok;
1343      PRINTD (DBG_IRQ|DBG_RX, "rx_data_av asserted");
1344      rx_data_av_handler (dev);
1345    }
1346  }
1347  if (irq_ok) {
1348    PRINTD (DBG_IRQ, "work done: %u", irq_ok);
1349  } else {
1350    PRINTD (DBG_IRQ|DBG_WARN, "spurious interrupt source: %#x", int_source);
1351  }
1352
1353  PRINTD (DBG_IRQ|DBG_FLOW, "interrupt_handler done: %p", dev_id);
1354  if (irq_ok)
1355	return IRQ_HANDLED;
1356  return IRQ_NONE;
1357}
1358
1359/********** housekeeping **********/
1360
1361static void do_housekeeping (unsigned long arg) {
1362  // just stats at the moment
1363  hrz_dev * dev = (hrz_dev *) arg;
1364
1365  // collect device-specific (not driver/atm-linux) stats here
1366  dev->tx_cell_count += rd_regw (dev, TX_CELL_COUNT_OFF);
1367  dev->rx_cell_count += rd_regw (dev, RX_CELL_COUNT_OFF);
1368  dev->hec_error_count += rd_regw (dev, HEC_ERROR_COUNT_OFF);
1369  dev->unassigned_cell_count += rd_regw (dev, UNASSIGNED_CELL_COUNT_OFF);
1370
1371  mod_timer (&dev->housekeeping, jiffies + HZ/10);
1372
1373  return;
1374}
1375
1376/********** find an idle channel for TX and set it up **********/
1377
1378// called with tx_busy set
1379static short setup_idle_tx_channel (hrz_dev * dev, hrz_vcc * vcc) {
1380  unsigned short idle_channels;
1381  short tx_channel = -1;
1382  unsigned int spin_count;
1383  PRINTD (DBG_FLOW|DBG_TX, "setup_idle_tx_channel %p", dev);
1384
1385  // better would be to fail immediately, the caller can then decide whether
1386  // to wait or drop (depending on whether this is UBR etc.)
1387  spin_count = 0;
1388  while (!(idle_channels = rd_regw (dev, TX_STATUS_OFF) & IDLE_CHANNELS_MASK)) {
1389    PRINTD (DBG_TX|DBG_WARN, "waiting for idle TX channel");
1390    // delay a bit here
1391    if (++spin_count > 100) {
1392      PRINTD (DBG_TX|DBG_ERR, "spun out waiting for idle TX channel");
1393      return -EBUSY;
1394    }
1395  }
1396
1397  // got an idle channel
1398  {
1399    // tx_idle ensures we look for idle channels in RR order
1400    int chan = dev->tx_idle;
1401
1402    int keep_going = 1;
1403    while (keep_going) {
1404      if (idle_channels & (1<<chan)) {
1405	tx_channel = chan;
1406	keep_going = 0;
1407      }
1408      ++chan;
1409      if (chan == TX_CHANS)
1410	chan = 0;
1411    }
1412
1413    dev->tx_idle = chan;
1414  }
1415
1416  // set up the channel we found
1417  {
1418    // Initialise the cell header in the transmit channel descriptor
1419    // a.k.a. prepare the channel and remember that we have done so.
1420
1421    tx_ch_desc * tx_desc = &memmap->tx_descs[tx_channel];
1422    u32 rd_ptr;
1423    u32 wr_ptr;
1424    u16 channel = vcc->channel;
1425
1426    unsigned long flags;
1427    spin_lock_irqsave (&dev->mem_lock, flags);
1428
1429    // Update the transmit channel record.
1430    dev->tx_channel_record[tx_channel] = channel;
1431
1432    // xBR channel
1433    update_tx_channel_config (dev, tx_channel, RATE_TYPE_ACCESS,
1434			      vcc->tx_xbr_bits);
1435
1436    // Update the PCR counter preload value etc.
1437    update_tx_channel_config (dev, tx_channel, PCR_TIMER_ACCESS,
1438			      vcc->tx_pcr_bits);
1439
1440
1441    // Initialise the read and write buffer pointers
1442    rd_ptr = rd_mem (dev, &tx_desc->rd_buf_type) & BUFFER_PTR_MASK;
1443    wr_ptr = rd_mem (dev, &tx_desc->wr_buf_type) & BUFFER_PTR_MASK;
1444
1445    // idle TX channels should have identical pointers
1446    if (rd_ptr != wr_ptr) {
1447      PRINTD (DBG_TX|DBG_ERR, "TX buffer pointers are broken!");
1448      // spin_unlock... return -E...
1449      // I wonder if gcc would get rid of one of the pointer aliases
1450    }
1451    PRINTD (DBG_TX, "TX buffer pointers are: rd %x, wr %x.",
1452	    rd_ptr, wr_ptr);
1453
1454    switch (vcc->aal) {
1455      case aal0:
1456	PRINTD (DBG_QOS|DBG_TX, "tx_channel: aal0");
1457	rd_ptr |= CHANNEL_TYPE_RAW_CELLS;
1458	wr_ptr |= CHANNEL_TYPE_RAW_CELLS;
1459	break;
1460      case aal34:
1461	PRINTD (DBG_QOS|DBG_TX, "tx_channel: aal34");
1462	rd_ptr |= CHANNEL_TYPE_AAL3_4;
1463	wr_ptr |= CHANNEL_TYPE_AAL3_4;
1464	break;
1465      case aal5:
1466	rd_ptr |= CHANNEL_TYPE_AAL5;
1467	wr_ptr |= CHANNEL_TYPE_AAL5;
1468	// Initialise the CRC
1469	wr_mem (dev, &tx_desc->partial_crc, INITIAL_CRC);
1470	break;
1471    }
1472
1473    wr_mem (dev, &tx_desc->rd_buf_type, rd_ptr);
1474    wr_mem (dev, &tx_desc->wr_buf_type, wr_ptr);
1475
1476    // Write the Cell Header
1477    // Payload Type, CLP and GFC would go here if non-zero
1478    wr_mem (dev, &tx_desc->cell_header, channel);
1479
1480    spin_unlock_irqrestore (&dev->mem_lock, flags);
1481  }
1482
1483  return tx_channel;
1484}
1485
1486/********** send a frame **********/
1487
1488static int hrz_send (struct atm_vcc * atm_vcc, struct sk_buff * skb) {
1489  unsigned int spin_count;
1490  int free_buffers;
1491  hrz_dev * dev = HRZ_DEV(atm_vcc->dev);
1492  hrz_vcc * vcc = HRZ_VCC(atm_vcc);
1493  u16 channel = vcc->channel;
1494
1495  u32 buffers_required;
1496
1497  /* signed for error return */
1498  short tx_channel;
1499
1500  PRINTD (DBG_FLOW|DBG_TX, "hrz_send vc %x data %p len %u",
1501	  channel, skb->data, skb->len);
1502
1503  dump_skb (">>>", channel, skb);
1504
1505  if (atm_vcc->qos.txtp.traffic_class == ATM_NONE) {
1506    PRINTK (KERN_ERR, "attempt to send on RX-only VC %x", channel);
1507    hrz_kfree_skb (skb);
1508    return -EIO;
1509  }
1510
1511  // don't understand this
1512  ATM_SKB(skb)->vcc = atm_vcc;
1513
1514  if (skb->len > atm_vcc->qos.txtp.max_sdu) {
1515    PRINTK (KERN_ERR, "sk_buff length greater than agreed max_sdu, dropping...");
1516    hrz_kfree_skb (skb);
1517    return -EIO;
1518  }
1519
1520  if (!channel) {
1521    PRINTD (DBG_ERR|DBG_TX, "attempt to transmit on zero (rx_)channel");
1522    hrz_kfree_skb (skb);
1523    return -EIO;
1524  }
1525
1526
1527#ifdef DEBUG_HORIZON
1528  /* wey-hey! */
1529  if (channel == 1023) {
1530    unsigned int i;
1531    unsigned short d = 0;
1532    char * s = skb->data;
1533    if (*s++ == 'D') {
1534      for (i = 0; i < 4; ++i) {
1535	d = (d<<4) | ((*s <= '9') ? (*s - '0') : (*s - 'a' + 10));
1536	++s;
1537      }
1538      PRINTK (KERN_INFO, "debug bitmap is now %hx", debug = d);
1539    }
1540  }
1541#endif
1542
1543  // wait until TX is free and grab lock
1544  if (tx_hold (dev)) {
1545    hrz_kfree_skb (skb);
1546    return -ERESTARTSYS;
1547  }
1548
1549  // Wait for enough space to be available in transmit buffer memory.
1550
1551  // should be number of cells needed + 2 (according to hardware docs)
1552  // = ((framelen+8)+47) / 48 + 2
1553  buffers_required = (skb->len+(ATM_AAL5_TRAILER-1)) / ATM_CELL_PAYLOAD + 3;
1554
1555  // replace with timer and sleep, add dev->tx_buffers_queue (max 1 entry)
1556  spin_count = 0;
1557  while ((free_buffers = rd_regw (dev, TX_FREE_BUFFER_COUNT_OFF)) < buffers_required) {
1558    PRINTD (DBG_TX, "waiting for free TX buffers, got %d of %d",
1559	    free_buffers, buffers_required);
1560    // what is the appropriate delay? implement a timeout? (depending on line speed?)
1561    // mdelay (1);
1562    // what happens if we kill (current_pid, SIGKILL) ?
1563    schedule();
1564    if (++spin_count > 1000) {
1565      PRINTD (DBG_TX|DBG_ERR, "spun out waiting for tx buffers, got %d of %d",
1566	      free_buffers, buffers_required);
1567      tx_release (dev);
1568      hrz_kfree_skb (skb);
1569      return -ERESTARTSYS;
1570    }
1571  }
1572
1573  // Select a channel to transmit the frame on.
1574  if (channel == dev->last_vc) {
1575    PRINTD (DBG_TX, "last vc hack: hit");
1576    tx_channel = dev->tx_last;
1577  } else {
1578    PRINTD (DBG_TX, "last vc hack: miss");
1579    // Are we currently transmitting this VC on one of the channels?
1580    for (tx_channel = 0; tx_channel < TX_CHANS; ++tx_channel)
1581      if (dev->tx_channel_record[tx_channel] == channel) {
1582	PRINTD (DBG_TX, "vc already on channel: hit");
1583	break;
1584      }
1585    if (tx_channel == TX_CHANS) {
1586      PRINTD (DBG_TX, "vc already on channel: miss");
1587      // Find and set up an idle channel.
1588      tx_channel = setup_idle_tx_channel (dev, vcc);
1589      if (tx_channel < 0) {
1590	PRINTD (DBG_TX|DBG_ERR, "failed to get channel");
1591	tx_release (dev);
1592	return tx_channel;
1593      }
1594    }
1595
1596    PRINTD (DBG_TX, "got channel");
1597    SELECT_TX_CHANNEL(dev, tx_channel);
1598
1599    dev->last_vc = channel;
1600    dev->tx_last = tx_channel;
1601  }
1602
1603  PRINTD (DBG_TX, "using channel %u", tx_channel);
1604
1605  YELLOW_LED_OFF(dev);
1606
1607  // TX start transfer
1608
1609  {
1610    unsigned int tx_len = skb->len;
1611    unsigned int tx_iovcnt = skb_shinfo(skb)->nr_frags;
1612    // remember this so we can free it later
1613    dev->tx_skb = skb;
1614
1615    if (tx_iovcnt) {
1616      // scatter gather transfer
1617      dev->tx_regions = tx_iovcnt;
1618      dev->tx_iovec = NULL;		/* @@@ needs rewritten */
1619      dev->tx_bytes = 0;
1620      PRINTD (DBG_TX|DBG_BUS, "TX start scatter-gather transfer (iovec %p, len %d)",
1621	      skb->data, tx_len);
1622      tx_release (dev);
1623      hrz_kfree_skb (skb);
1624      return -EIO;
1625    } else {
1626      // simple transfer
1627      dev->tx_regions = 0;
1628      dev->tx_iovec = NULL;
1629      dev->tx_bytes = tx_len;
1630      dev->tx_addr = skb->data;
1631      PRINTD (DBG_TX|DBG_BUS, "TX start simple transfer (addr %p, len %d)",
1632	      skb->data, tx_len);
1633    }
1634
1635    // and do the business
1636    tx_schedule (dev, 0);
1637
1638  }
1639
1640  return 0;
1641}
1642
1643/********** reset a card **********/
1644
1645static void hrz_reset (const hrz_dev * dev) {
1646  u32 control_0_reg = rd_regl (dev, CONTROL_0_REG);
1647
1648  // why not set RESET_HORIZON to one and wait for the card to
1649  // reassert that bit as zero? Like so:
1650  control_0_reg = control_0_reg & RESET_HORIZON;
1651  wr_regl (dev, CONTROL_0_REG, control_0_reg);
1652  while (control_0_reg & RESET_HORIZON)
1653    control_0_reg = rd_regl (dev, CONTROL_0_REG);
1654
1655  // old reset code retained:
1656  wr_regl (dev, CONTROL_0_REG, control_0_reg |
1657	   RESET_ATM | RESET_RX | RESET_TX | RESET_HOST);
1658  // just guessing here
1659  udelay (1000);
1660
1661  wr_regl (dev, CONTROL_0_REG, control_0_reg);
1662}
1663
1664/********** read the burnt in address **********/
1665
1666static void WRITE_IT_WAIT (const hrz_dev *dev, u32 ctrl)
1667{
1668	wr_regl (dev, CONTROL_0_REG, ctrl);
1669	udelay (5);
1670}
1671
1672static void CLOCK_IT (const hrz_dev *dev, u32 ctrl)
1673{
1674	// DI must be valid around rising SK edge
1675	WRITE_IT_WAIT(dev, ctrl & ~SEEPROM_SK);
1676	WRITE_IT_WAIT(dev, ctrl | SEEPROM_SK);
1677}
1678
1679static u16 __devinit read_bia (const hrz_dev * dev, u16 addr)
1680{
1681  u32 ctrl = rd_regl (dev, CONTROL_0_REG);
1682
1683  const unsigned int addr_bits = 6;
1684  const unsigned int data_bits = 16;
1685
1686  unsigned int i;
1687
1688  u16 res;
1689
1690  ctrl &= ~(SEEPROM_CS | SEEPROM_SK | SEEPROM_DI);
1691  WRITE_IT_WAIT(dev, ctrl);
1692
1693  // wake Serial EEPROM and send 110 (READ) command
1694  ctrl |=  (SEEPROM_CS | SEEPROM_DI);
1695  CLOCK_IT(dev, ctrl);
1696
1697  ctrl |= SEEPROM_DI;
1698  CLOCK_IT(dev, ctrl);
1699
1700  ctrl &= ~SEEPROM_DI;
1701  CLOCK_IT(dev, ctrl);
1702
1703  for (i=0; i<addr_bits; i++) {
1704    if (addr & (1 << (addr_bits-1)))
1705      ctrl |= SEEPROM_DI;
1706    else
1707      ctrl &= ~SEEPROM_DI;
1708
1709    CLOCK_IT(dev, ctrl);
1710
1711    addr = addr << 1;
1712  }
1713
1714  // we could check that we have DO = 0 here
1715  ctrl &= ~SEEPROM_DI;
1716
1717  res = 0;
1718  for (i=0;i<data_bits;i++) {
1719    res = res >> 1;
1720
1721    CLOCK_IT(dev, ctrl);
1722
1723    if (rd_regl (dev, CONTROL_0_REG) & SEEPROM_DO)
1724      res |= (1 << (data_bits-1));
1725  }
1726
1727  ctrl &= ~(SEEPROM_SK | SEEPROM_CS);
1728  WRITE_IT_WAIT(dev, ctrl);
1729
1730  return res;
1731}
1732
1733/********** initialise a card **********/
1734
1735static int __devinit hrz_init (hrz_dev * dev) {
1736  int onefivefive;
1737
1738  u16 chan;
1739
1740  int buff_count;
1741
1742  HDW * mem;
1743
1744  cell_buf * tx_desc;
1745  cell_buf * rx_desc;
1746
1747  u32 ctrl;
1748
1749  ctrl = rd_regl (dev, CONTROL_0_REG);
1750  PRINTD (DBG_INFO, "ctrl0reg is %#x", ctrl);
1751  onefivefive = ctrl & ATM_LAYER_STATUS;
1752
1753  if (onefivefive)
1754    printk (DEV_LABEL ": Horizon Ultra (at 155.52 MBps)");
1755  else
1756    printk (DEV_LABEL ": Horizon (at 25 MBps)");
1757
1758  printk (":");
1759  // Reset the card to get everything in a known state
1760
1761  printk (" reset");
1762  hrz_reset (dev);
1763
1764  // Clear all the buffer memory
1765
1766  printk (" clearing memory");
1767
1768  for (mem = (HDW *) memmap; mem < (HDW *) (memmap + 1); ++mem)
1769    wr_mem (dev, mem, 0);
1770
1771  printk (" tx channels");
1772
1773  // All transmit eight channels are set up as AAL5 ABR channels with
1774  // a 16us cell spacing. Why?
1775
1776  // Channel 0 gets the free buffer at 100h, channel 1 gets the free
1777  // buffer at 110h etc.
1778
1779  for (chan = 0; chan < TX_CHANS; ++chan) {
1780    tx_ch_desc * tx_desc = &memmap->tx_descs[chan];
1781    cell_buf * buf = &memmap->inittxbufs[chan];
1782
1783    // initialise the read and write buffer pointers
1784    wr_mem (dev, &tx_desc->rd_buf_type, BUF_PTR(buf));
1785    wr_mem (dev, &tx_desc->wr_buf_type, BUF_PTR(buf));
1786
1787    // set the status of the initial buffers to empty
1788    wr_mem (dev, &buf->next, BUFF_STATUS_EMPTY);
1789  }
1790
1791  // Use space bufn3 at the moment for tx buffers
1792
1793  printk (" tx buffers");
1794
1795  tx_desc = memmap->bufn3;
1796
1797  wr_mem (dev, &memmap->txfreebufstart.next, BUF_PTR(tx_desc) | BUFF_STATUS_EMPTY);
1798
1799  for (buff_count = 0; buff_count < BUFN3_SIZE-1; buff_count++) {
1800    wr_mem (dev, &tx_desc->next, BUF_PTR(tx_desc+1) | BUFF_STATUS_EMPTY);
1801    tx_desc++;
1802  }
1803
1804  wr_mem (dev, &tx_desc->next, BUF_PTR(&memmap->txfreebufend) | BUFF_STATUS_EMPTY);
1805
1806  // Initialise the transmit free buffer count
1807  wr_regw (dev, TX_FREE_BUFFER_COUNT_OFF, BUFN3_SIZE);
1808
1809  printk (" rx channels");
1810
1811  // Initialise all of the receive channels to be AAL5 disabled with
1812  // an interrupt threshold of 0
1813
1814  for (chan = 0; chan < RX_CHANS; ++chan) {
1815    rx_ch_desc * rx_desc = &memmap->rx_descs[chan];
1816
1817    wr_mem (dev, &rx_desc->wr_buf_type, CHANNEL_TYPE_AAL5 | RX_CHANNEL_DISABLED);
1818  }
1819
1820  printk (" rx buffers");
1821
1822  // Use space bufn4 at the moment for rx buffers
1823
1824  rx_desc = memmap->bufn4;
1825
1826  wr_mem (dev, &memmap->rxfreebufstart.next, BUF_PTR(rx_desc) | BUFF_STATUS_EMPTY);
1827
1828  for (buff_count = 0; buff_count < BUFN4_SIZE-1; buff_count++) {
1829    wr_mem (dev, &rx_desc->next, BUF_PTR(rx_desc+1) | BUFF_STATUS_EMPTY);
1830
1831    rx_desc++;
1832  }
1833
1834  wr_mem (dev, &rx_desc->next, BUF_PTR(&memmap->rxfreebufend) | BUFF_STATUS_EMPTY);
1835
1836  // Initialise the receive free buffer count
1837  wr_regw (dev, RX_FREE_BUFFER_COUNT_OFF, BUFN4_SIZE);
1838
1839  // Initialize Horizons registers
1840
1841  // TX config
1842  wr_regw (dev, TX_CONFIG_OFF,
1843	   ABR_ROUND_ROBIN | TX_NORMAL_OPERATION | DRVR_DRVRBAR_ENABLE);
1844
1845  // RX config. Use 10-x VC bits, x VP bits, non user cells in channel 0.
1846  wr_regw (dev, RX_CONFIG_OFF,
1847	   DISCARD_UNUSED_VPI_VCI_BITS_SET | NON_USER_CELLS_IN_ONE_CHANNEL | vpi_bits);
1848
1849  // RX line config
1850  wr_regw (dev, RX_LINE_CONFIG_OFF,
1851	   LOCK_DETECT_ENABLE | FREQUENCY_DETECT_ENABLE | GXTALOUT_SELECT_DIV4);
1852
1853  // Set the max AAL5 cell count to be just enough to contain the
1854  // largest AAL5 frame that the user wants to receive
1855  wr_regw (dev, MAX_AAL5_CELL_COUNT_OFF,
1856	   DIV_ROUND_UP(max_rx_size + ATM_AAL5_TRAILER, ATM_CELL_PAYLOAD));
1857
1858  // Enable receive
1859  wr_regw (dev, RX_CONFIG_OFF, rd_regw (dev, RX_CONFIG_OFF) | RX_ENABLE);
1860
1861  printk (" control");
1862
1863  // Drive the OE of the LEDs then turn the green LED on
1864  ctrl |= GREEN_LED_OE | YELLOW_LED_OE | GREEN_LED | YELLOW_LED;
1865  wr_regl (dev, CONTROL_0_REG, ctrl);
1866
1867  // Test for a 155-capable card
1868
1869  if (onefivefive) {
1870    // Select 155 mode... make this a choice (or: how do we detect
1871    // external line speed and switch?)
1872    ctrl |= ATM_LAYER_SELECT;
1873    wr_regl (dev, CONTROL_0_REG, ctrl);
1874
1875    // test SUNI-lite vs SAMBA
1876
1877    // Register 0x00 in the SUNI will have some of bits 3-7 set, and
1878    // they will always be zero for the SAMBA.  Ha!  Bloody hardware
1879    // engineers.  It'll never work.
1880
1881    if (rd_framer (dev, 0) & 0x00f0) {
1882      // SUNI
1883      printk (" SUNI");
1884
1885      // Reset, just in case
1886      wr_framer (dev, 0x00, 0x0080);
1887      wr_framer (dev, 0x00, 0x0000);
1888
1889      // Configure transmit FIFO
1890      wr_framer (dev, 0x63, rd_framer (dev, 0x63) | 0x0002);
1891
1892      // Set line timed mode
1893      wr_framer (dev, 0x05, rd_framer (dev, 0x05) | 0x0001);
1894    } else {
1895      // SAMBA
1896      printk (" SAMBA");
1897
1898      // Reset, just in case
1899      wr_framer (dev, 0, rd_framer (dev, 0) | 0x0001);
1900      wr_framer (dev, 0, rd_framer (dev, 0) &~ 0x0001);
1901
1902      // Turn off diagnostic loopback and enable line-timed mode
1903      wr_framer (dev, 0, 0x0002);
1904
1905      // Turn on transmit outputs
1906      wr_framer (dev, 2, 0x0B80);
1907    }
1908  } else {
1909    // Select 25 mode
1910    ctrl &= ~ATM_LAYER_SELECT;
1911
1912    // Madge B154 setup
1913    // none required?
1914  }
1915
1916  printk (" LEDs");
1917
1918  GREEN_LED_ON(dev);
1919  YELLOW_LED_ON(dev);
1920
1921  printk (" ESI=");
1922
1923  {
1924    u16 b = 0;
1925    int i;
1926    u8 * esi = dev->atm_dev->esi;
1927
1928    // in the card I have, EEPROM
1929    // addresses 0, 1, 2 contain 0
1930    // addresess 5, 6 etc. contain ffff
1931    // NB: Madge prefix is 00 00 f6 (which is 00 00 6f in Ethernet bit order)
1932    // the read_bia routine gets the BIA in Ethernet bit order
1933
1934    for (i=0; i < ESI_LEN; ++i) {
1935      if (i % 2 == 0)
1936	b = read_bia (dev, i/2 + 2);
1937      else
1938	b = b >> 8;
1939      esi[i] = b & 0xFF;
1940      printk ("%02x", esi[i]);
1941    }
1942  }
1943
1944  // Enable RX_Q and ?X_COMPLETE interrupts only
1945  wr_regl (dev, INT_ENABLE_REG_OFF, INTERESTING_INTERRUPTS);
1946  printk (" IRQ on");
1947
1948  printk (".\n");
1949
1950  return onefivefive;
1951}
1952
1953/********** check max_sdu **********/
1954
1955static int check_max_sdu (hrz_aal aal, struct atm_trafprm * tp, unsigned int max_frame_size) {
1956  PRINTD (DBG_FLOW|DBG_QOS, "check_max_sdu");
1957
1958  switch (aal) {
1959    case aal0:
1960      if (!(tp->max_sdu)) {
1961	PRINTD (DBG_QOS, "defaulting max_sdu");
1962	tp->max_sdu = ATM_AAL0_SDU;
1963      } else if (tp->max_sdu != ATM_AAL0_SDU) {
1964	PRINTD (DBG_QOS|DBG_ERR, "rejecting max_sdu");
1965	return -EINVAL;
1966      }
1967      break;
1968    case aal34:
1969      if (tp->max_sdu == 0 || tp->max_sdu > ATM_MAX_AAL34_PDU) {
1970	PRINTD (DBG_QOS, "%sing max_sdu", tp->max_sdu ? "capp" : "default");
1971	tp->max_sdu = ATM_MAX_AAL34_PDU;
1972      }
1973      break;
1974    case aal5:
1975      if (tp->max_sdu == 0 || tp->max_sdu > max_frame_size) {
1976	PRINTD (DBG_QOS, "%sing max_sdu", tp->max_sdu ? "capp" : "default");
1977	tp->max_sdu = max_frame_size;
1978      }
1979      break;
1980  }
1981  return 0;
1982}
1983
1984/********** check pcr **********/
1985
1986// something like this should be part of ATM Linux
1987static int atm_pcr_check (struct atm_trafprm * tp, unsigned int pcr) {
1988  // we are assuming non-UBR, and non-special values of pcr
1989  if (tp->min_pcr == ATM_MAX_PCR)
1990    PRINTD (DBG_QOS, "luser gave min_pcr = ATM_MAX_PCR");
1991  else if (tp->min_pcr < 0)
1992    PRINTD (DBG_QOS, "luser gave negative min_pcr");
1993  else if (tp->min_pcr && tp->min_pcr > pcr)
1994    PRINTD (DBG_QOS, "pcr less than min_pcr");
1995  else
1996    // !! max_pcr = UNSPEC (0) is equivalent to max_pcr = MAX (-1)
1997    // easier to #define ATM_MAX_PCR 0 and have all rates unsigned?
1998    // [this would get rid of next two conditionals]
1999    if ((0) && tp->max_pcr == ATM_MAX_PCR)
2000      PRINTD (DBG_QOS, "luser gave max_pcr = ATM_MAX_PCR");
2001    else if ((tp->max_pcr != ATM_MAX_PCR) && tp->max_pcr < 0)
2002      PRINTD (DBG_QOS, "luser gave negative max_pcr");
2003    else if (tp->max_pcr && tp->max_pcr != ATM_MAX_PCR && tp->max_pcr < pcr)
2004      PRINTD (DBG_QOS, "pcr greater than max_pcr");
2005    else {
2006      // each limit unspecified or not violated
2007      PRINTD (DBG_QOS, "xBR(pcr) OK");
2008      return 0;
2009    }
2010  PRINTD (DBG_QOS, "pcr=%u, tp: min_pcr=%d, pcr=%d, max_pcr=%d",
2011	  pcr, tp->min_pcr, tp->pcr, tp->max_pcr);
2012  return -EINVAL;
2013}
2014
2015/********** open VC **********/
2016
2017static int hrz_open (struct atm_vcc *atm_vcc)
2018{
2019  int error;
2020  u16 channel;
2021
2022  struct atm_qos * qos;
2023  struct atm_trafprm * txtp;
2024  struct atm_trafprm * rxtp;
2025
2026  hrz_dev * dev = HRZ_DEV(atm_vcc->dev);
2027  hrz_vcc vcc;
2028  hrz_vcc * vccp; // allocated late
2029  short vpi = atm_vcc->vpi;
2030  int vci = atm_vcc->vci;
2031  PRINTD (DBG_FLOW|DBG_VCC, "hrz_open %x %x", vpi, vci);
2032
2033#ifdef ATM_VPI_UNSPEC
2034  // UNSPEC is deprecated, remove this code eventually
2035  if (vpi == ATM_VPI_UNSPEC || vci == ATM_VCI_UNSPEC) {
2036    PRINTK (KERN_WARNING, "rejecting open with unspecified VPI/VCI (deprecated)");
2037    return -EINVAL;
2038  }
2039#endif
2040
2041  error = vpivci_to_channel (&channel, vpi, vci);
2042  if (error) {
2043    PRINTD (DBG_WARN|DBG_VCC, "VPI/VCI out of range: %hd/%d", vpi, vci);
2044    return error;
2045  }
2046
2047  vcc.channel = channel;
2048  // max speed for the moment
2049  vcc.tx_rate = 0x0;
2050
2051  qos = &atm_vcc->qos;
2052
2053  // check AAL and remember it
2054  switch (qos->aal) {
2055    case ATM_AAL0:
2056      // we would if it were 48 bytes and not 52!
2057      PRINTD (DBG_QOS|DBG_VCC, "AAL0");
2058      vcc.aal = aal0;
2059      break;
2060    case ATM_AAL34:
2061      // we would if I knew how do the SAR!
2062      PRINTD (DBG_QOS|DBG_VCC, "AAL3/4");
2063      vcc.aal = aal34;
2064      break;
2065    case ATM_AAL5:
2066      PRINTD (DBG_QOS|DBG_VCC, "AAL5");
2067      vcc.aal = aal5;
2068      break;
2069    default:
2070      PRINTD (DBG_QOS|DBG_VCC, "Bad AAL!");
2071      return -EINVAL;
2072      break;
2073  }
2074
2075  // TX traffic parameters
2076
2077  // there are two, interrelated problems here: 1. the reservation of
2078  // PCR is not a binary choice, we are given bounds and/or a
2079  // desirable value; 2. the device is only capable of certain values,
2080  // most of which are not integers. It is almost certainly acceptable
2081  // to be off by a maximum of 1 to 10 cps.
2082
2083  // Pragmatic choice: always store an integral PCR as that which has
2084  // been allocated, even if we allocate a little (or a lot) less,
2085  // after rounding. The actual allocation depends on what we can
2086  // manage with our rate selection algorithm. The rate selection
2087  // algorithm is given an integral PCR and a tolerance and told
2088  // whether it should round the value up or down if the tolerance is
2089  // exceeded; it returns: a) the actual rate selected (rounded up to
2090  // the nearest integer), b) a bit pattern to feed to the timer
2091  // register, and c) a failure value if no applicable rate exists.
2092
2093  // Part of the job is done by atm_pcr_goal which gives us a PCR
2094  // specification which says: EITHER grab the maximum available PCR
2095  // (and perhaps a lower bound which we musn't pass), OR grab this
2096  // amount, rounding down if you have to (and perhaps a lower bound
2097  // which we musn't pass) OR grab this amount, rounding up if you
2098  // have to (and perhaps an upper bound which we musn't pass). If any
2099  // bounds ARE passed we fail. Note that rounding is only rounding to
2100  // match device limitations, we do not round down to satisfy
2101  // bandwidth availability even if this would not violate any given
2102  // lower bound.
2103
2104  // Note: telephony = 64kb/s = 48 byte cell payload @ 500/3 cells/s
2105  // (say) so this is not even a binary fixpoint cell rate (but this
2106  // device can do it). To avoid this sort of hassle we use a
2107  // tolerance parameter (currently fixed at 10 cps).
2108
2109  PRINTD (DBG_QOS, "TX:");
2110
2111  txtp = &qos->txtp;
2112
2113  // set up defaults for no traffic
2114  vcc.tx_rate = 0;
2115  // who knows what would actually happen if you try and send on this?
2116  vcc.tx_xbr_bits = IDLE_RATE_TYPE;
2117  vcc.tx_pcr_bits = CLOCK_DISABLE;
2118
2119  if (txtp->traffic_class != ATM_NONE) {
2120    error = check_max_sdu (vcc.aal, txtp, max_tx_size);
2121    if (error) {
2122      PRINTD (DBG_QOS, "TX max_sdu check failed");
2123      return error;
2124    }
2125
2126    switch (txtp->traffic_class) {
2127      case ATM_UBR: {
2128	// we take "the PCR" as a rate-cap
2129	// not reserved
2130	vcc.tx_rate = 0;
2131	make_rate (dev, 1<<30, round_nearest, &vcc.tx_pcr_bits, NULL);
2132	vcc.tx_xbr_bits = ABR_RATE_TYPE;
2133	break;
2134      }
2135      case ATM_CBR: {
2136	int pcr = atm_pcr_goal (txtp);
2137	rounding r;
2138	if (!pcr) {
2139	  // down vs. up, remaining bandwidth vs. unlimited bandwidth!!
2140	  // should really have: once someone gets unlimited bandwidth
2141	  // that no more non-UBR channels can be opened until the
2142	  // unlimited one closes?? For the moment, round_down means
2143	  // greedy people actually get something and not nothing
2144	  r = round_down;
2145	  // slight race (no locking) here so we may get -EAGAIN
2146	  // later; the greedy bastards would deserve it :)
2147	  PRINTD (DBG_QOS, "snatching all remaining TX bandwidth");
2148	  pcr = dev->tx_avail;
2149	} else if (pcr < 0) {
2150	  r = round_down;
2151	  pcr = -pcr;
2152	} else {
2153	  r = round_up;
2154	}
2155	error = make_rate_with_tolerance (dev, pcr, r, 10,
2156					  &vcc.tx_pcr_bits, &vcc.tx_rate);
2157	if (error) {
2158	  PRINTD (DBG_QOS, "could not make rate from TX PCR");
2159	  return error;
2160	}
2161	// not really clear what further checking is needed
2162	error = atm_pcr_check (txtp, vcc.tx_rate);
2163	if (error) {
2164	  PRINTD (DBG_QOS, "TX PCR failed consistency check");
2165	  return error;
2166	}
2167	vcc.tx_xbr_bits = CBR_RATE_TYPE;
2168	break;
2169      }
2170      default: {
2171	PRINTD (DBG_QOS, "unsupported TX traffic class");
2172	return -EINVAL;
2173	break;
2174      }
2175    }
2176  }
2177
2178  // RX traffic parameters
2179
2180  PRINTD (DBG_QOS, "RX:");
2181
2182  rxtp = &qos->rxtp;
2183
2184  // set up defaults for no traffic
2185  vcc.rx_rate = 0;
2186
2187  if (rxtp->traffic_class != ATM_NONE) {
2188    error = check_max_sdu (vcc.aal, rxtp, max_rx_size);
2189    if (error) {
2190      PRINTD (DBG_QOS, "RX max_sdu check failed");
2191      return error;
2192    }
2193    switch (rxtp->traffic_class) {
2194      case ATM_UBR: {
2195	// not reserved
2196	break;
2197      }
2198      case ATM_CBR: {
2199	int pcr = atm_pcr_goal (rxtp);
2200	if (!pcr) {
2201	  // slight race (no locking) here so we may get -EAGAIN
2202	  // later; the greedy bastards would deserve it :)
2203	  PRINTD (DBG_QOS, "snatching all remaining RX bandwidth");
2204	  pcr = dev->rx_avail;
2205	} else if (pcr < 0) {
2206	  pcr = -pcr;
2207	}
2208	vcc.rx_rate = pcr;
2209	// not really clear what further checking is needed
2210	error = atm_pcr_check (rxtp, vcc.rx_rate);
2211	if (error) {
2212	  PRINTD (DBG_QOS, "RX PCR failed consistency check");
2213	  return error;
2214	}
2215	break;
2216      }
2217      default: {
2218	PRINTD (DBG_QOS, "unsupported RX traffic class");
2219	return -EINVAL;
2220	break;
2221      }
2222    }
2223  }
2224
2225
2226  // late abort useful for diagnostics
2227  if (vcc.aal != aal5) {
2228    PRINTD (DBG_QOS, "AAL not supported");
2229    return -EINVAL;
2230  }
2231
2232  // get space for our vcc stuff and copy parameters into it
2233  vccp = kmalloc (sizeof(hrz_vcc), GFP_KERNEL);
2234  if (!vccp) {
2235    PRINTK (KERN_ERR, "out of memory!");
2236    return -ENOMEM;
2237  }
2238  *vccp = vcc;
2239
2240  // clear error and grab cell rate resource lock
2241  error = 0;
2242  spin_lock (&dev->rate_lock);
2243
2244  if (vcc.tx_rate > dev->tx_avail) {
2245    PRINTD (DBG_QOS, "not enough TX PCR left");
2246    error = -EAGAIN;
2247  }
2248
2249  if (vcc.rx_rate > dev->rx_avail) {
2250    PRINTD (DBG_QOS, "not enough RX PCR left");
2251    error = -EAGAIN;
2252  }
2253
2254  if (!error) {
2255    // really consume cell rates
2256    dev->tx_avail -= vcc.tx_rate;
2257    dev->rx_avail -= vcc.rx_rate;
2258    PRINTD (DBG_QOS|DBG_VCC, "reserving %u TX PCR and %u RX PCR",
2259	    vcc.tx_rate, vcc.rx_rate);
2260  }
2261
2262  // release lock and exit on error
2263  spin_unlock (&dev->rate_lock);
2264  if (error) {
2265    PRINTD (DBG_QOS|DBG_VCC, "insufficient cell rate resources");
2266    kfree (vccp);
2267    return error;
2268  }
2269
2270  // this is "immediately before allocating the connection identifier
2271  // in hardware" - so long as the next call does not fail :)
2272  set_bit(ATM_VF_ADDR,&atm_vcc->flags);
2273
2274  // any errors here are very serious and should never occur
2275
2276  if (rxtp->traffic_class != ATM_NONE) {
2277    if (dev->rxer[channel]) {
2278      PRINTD (DBG_ERR|DBG_VCC, "VC already open for RX");
2279      error = -EBUSY;
2280    }
2281    if (!error)
2282      error = hrz_open_rx (dev, channel);
2283    if (error) {
2284      kfree (vccp);
2285      return error;
2286    }
2287    // this link allows RX frames through
2288    dev->rxer[channel] = atm_vcc;
2289  }
2290
2291  // success, set elements of atm_vcc
2292  atm_vcc->dev_data = (void *) vccp;
2293
2294  // indicate readiness
2295  set_bit(ATM_VF_READY,&atm_vcc->flags);
2296
2297  return 0;
2298}
2299
2300/********** close VC **********/
2301
2302static void hrz_close (struct atm_vcc * atm_vcc) {
2303  hrz_dev * dev = HRZ_DEV(atm_vcc->dev);
2304  hrz_vcc * vcc = HRZ_VCC(atm_vcc);
2305  u16 channel = vcc->channel;
2306  PRINTD (DBG_VCC|DBG_FLOW, "hrz_close");
2307
2308  // indicate unreadiness
2309  clear_bit(ATM_VF_READY,&atm_vcc->flags);
2310
2311  if (atm_vcc->qos.txtp.traffic_class != ATM_NONE) {
2312    unsigned int i;
2313
2314    // let any TX on this channel that has started complete
2315    // no restart, just keep trying
2316    while (tx_hold (dev))
2317      ;
2318    // remove record of any tx_channel having been setup for this channel
2319    for (i = 0; i < TX_CHANS; ++i)
2320      if (dev->tx_channel_record[i] == channel) {
2321	dev->tx_channel_record[i] = -1;
2322	break;
2323      }
2324    if (dev->last_vc == channel)
2325      dev->tx_last = -1;
2326    tx_release (dev);
2327  }
2328
2329  if (atm_vcc->qos.rxtp.traffic_class != ATM_NONE) {
2330    // disable RXing - it tries quite hard
2331    hrz_close_rx (dev, channel);
2332    // forget the vcc - no more skbs will be pushed
2333    if (atm_vcc != dev->rxer[channel])
2334      PRINTK (KERN_ERR, "%s atm_vcc=%p rxer[channel]=%p",
2335	      "arghhh! we're going to die!",
2336	      atm_vcc, dev->rxer[channel]);
2337    dev->rxer[channel] = NULL;
2338  }
2339
2340  // atomically release our rate reservation
2341  spin_lock (&dev->rate_lock);
2342  PRINTD (DBG_QOS|DBG_VCC, "releasing %u TX PCR and %u RX PCR",
2343	  vcc->tx_rate, vcc->rx_rate);
2344  dev->tx_avail += vcc->tx_rate;
2345  dev->rx_avail += vcc->rx_rate;
2346  spin_unlock (&dev->rate_lock);
2347
2348  // free our structure
2349  kfree (vcc);
2350  // say the VPI/VCI is free again
2351  clear_bit(ATM_VF_ADDR,&atm_vcc->flags);
2352}
2353
2354
2355
2356/********** proc file contents **********/
2357
2358static int hrz_proc_read (struct atm_dev * atm_dev, loff_t * pos, char * page) {
2359  hrz_dev * dev = HRZ_DEV(atm_dev);
2360  int left = *pos;
2361  PRINTD (DBG_FLOW, "hrz_proc_read");
2362
2363  /* more diagnostics here? */
2364
2365
2366  if (!left--)
2367    return sprintf (page,
2368		    "cells: TX %lu, RX %lu, HEC errors %lu, unassigned %lu.\n",
2369		    dev->tx_cell_count, dev->rx_cell_count,
2370		    dev->hec_error_count, dev->unassigned_cell_count);
2371
2372  if (!left--)
2373    return sprintf (page,
2374		    "free cell buffers: TX %hu, RX %hu+%hu.\n",
2375		    rd_regw (dev, TX_FREE_BUFFER_COUNT_OFF),
2376		    rd_regw (dev, RX_FREE_BUFFER_COUNT_OFF),
2377		    dev->noof_spare_buffers);
2378
2379  if (!left--)
2380    return sprintf (page,
2381		    "cps remaining: TX %u, RX %u\n",
2382		    dev->tx_avail, dev->rx_avail);
2383
2384  return 0;
2385}
2386
2387static const struct atmdev_ops hrz_ops = {
2388  .open	= hrz_open,
2389  .close	= hrz_close,
2390  .send	= hrz_send,
2391  .proc_read	= hrz_proc_read,
2392  .owner	= THIS_MODULE,
2393};
2394
2395static int __devinit hrz_probe(struct pci_dev *pci_dev, const struct pci_device_id *pci_ent)
2396{
2397	hrz_dev * dev;
2398	int err = 0;
2399
2400	// adapter slot free, read resources from PCI configuration space
2401	u32 iobase = pci_resource_start (pci_dev, 0);
2402	u32 * membase = bus_to_virt (pci_resource_start (pci_dev, 1));
2403	unsigned int irq;
2404	unsigned char lat;
2405
2406	PRINTD (DBG_FLOW, "hrz_probe");
2407
2408	if (pci_enable_device(pci_dev))
2409		return -EINVAL;
2410
2411	if (!request_region(iobase, HRZ_IO_EXTENT, DEV_LABEL)) {
2412		err = -EINVAL;
2413		goto out_disable;
2414	}
2415
2416	dev = kzalloc(sizeof(hrz_dev), GFP_KERNEL);
2417	if (!dev) {
2418		// perhaps we should be nice: deregister all adapters and abort?
2419		PRINTD(DBG_ERR, "out of memory");
2420		err = -ENOMEM;
2421		goto out_release;
2422	}
2423
2424	pci_set_drvdata(pci_dev, dev);
2425
2426	// grab IRQ and install handler - move this someplace more sensible
2427	irq = pci_dev->irq;
2428	if (request_irq(irq,
2429			interrupt_handler,
2430			IRQF_SHARED, /* irqflags guess */
2431			DEV_LABEL, /* name guess */
2432			dev)) {
2433		PRINTD(DBG_WARN, "request IRQ failed!");
2434		err = -EINVAL;
2435		goto out_free;
2436	}
2437
2438	PRINTD(DBG_INFO, "found Madge ATM adapter (hrz) at: IO %x, IRQ %u, MEM %p",
2439	       iobase, irq, membase);
2440
2441	dev->atm_dev = atm_dev_register(DEV_LABEL, &hrz_ops, -1, NULL);
2442	if (!(dev->atm_dev)) {
2443		PRINTD(DBG_ERR, "failed to register Madge ATM adapter");
2444		err = -EINVAL;
2445		goto out_free_irq;
2446	}
2447
2448	PRINTD(DBG_INFO, "registered Madge ATM adapter (no. %d) (%p) at %p",
2449	       dev->atm_dev->number, dev, dev->atm_dev);
2450	dev->atm_dev->dev_data = (void *) dev;
2451	dev->pci_dev = pci_dev;
2452
2453	// enable bus master accesses
2454	pci_set_master(pci_dev);
2455
2456	// frobnicate latency (upwards, usually)
2457	pci_read_config_byte(pci_dev, PCI_LATENCY_TIMER, &lat);
2458	if (pci_lat) {
2459		PRINTD(DBG_INFO, "%s PCI latency timer from %hu to %hu",
2460		       "changing", lat, pci_lat);
2461		pci_write_config_byte(pci_dev, PCI_LATENCY_TIMER, pci_lat);
2462	} else if (lat < MIN_PCI_LATENCY) {
2463		PRINTK(KERN_INFO, "%s PCI latency timer from %hu to %hu",
2464		       "increasing", lat, MIN_PCI_LATENCY);
2465		pci_write_config_byte(pci_dev, PCI_LATENCY_TIMER, MIN_PCI_LATENCY);
2466	}
2467
2468	dev->iobase = iobase;
2469	dev->irq = irq;
2470	dev->membase = membase;
2471
2472	dev->rx_q_entry = dev->rx_q_reset = &memmap->rx_q_entries[0];
2473	dev->rx_q_wrap  = &memmap->rx_q_entries[RX_CHANS-1];
2474
2475	// these next three are performance hacks
2476	dev->last_vc = -1;
2477	dev->tx_last = -1;
2478	dev->tx_idle = 0;
2479
2480	dev->tx_regions = 0;
2481	dev->tx_bytes = 0;
2482	dev->tx_skb = NULL;
2483	dev->tx_iovec = NULL;
2484
2485	dev->tx_cell_count = 0;
2486	dev->rx_cell_count = 0;
2487	dev->hec_error_count = 0;
2488	dev->unassigned_cell_count = 0;
2489
2490	dev->noof_spare_buffers = 0;
2491
2492	{
2493		unsigned int i;
2494		for (i = 0; i < TX_CHANS; ++i)
2495			dev->tx_channel_record[i] = -1;
2496	}
2497
2498	dev->flags = 0;
2499
2500	// Allocate cell rates and remember ASIC version
2501	// Fibre: ATM_OC3_PCR = 1555200000/8/270*260/53 - 29/53
2502	// Copper: (WRONG) we want 6 into the above, close to 25Mb/s
2503	// Copper: (plagarise!) 25600000/8/270*260/53 - n/53
2504
2505	if (hrz_init(dev)) {
2506		// to be really pedantic, this should be ATM_OC3c_PCR
2507		dev->tx_avail = ATM_OC3_PCR;
2508		dev->rx_avail = ATM_OC3_PCR;
2509		set_bit(ultra, &dev->flags); // NOT "|= ultra" !
2510	} else {
2511		dev->tx_avail = ((25600000/8)*26)/(27*53);
2512		dev->rx_avail = ((25600000/8)*26)/(27*53);
2513		PRINTD(DBG_WARN, "Buggy ASIC: no TX bus-mastering.");
2514	}
2515
2516	// rate changes spinlock
2517	spin_lock_init(&dev->rate_lock);
2518
2519	// on-board memory access spinlock; we want atomic reads and
2520	// writes to adapter memory (handles IRQ and SMP)
2521	spin_lock_init(&dev->mem_lock);
2522
2523	init_waitqueue_head(&dev->tx_queue);
2524
2525	// vpi in 0..4, vci in 6..10
2526	dev->atm_dev->ci_range.vpi_bits = vpi_bits;
2527	dev->atm_dev->ci_range.vci_bits = 10-vpi_bits;
2528
2529	init_timer(&dev->housekeeping);
2530	dev->housekeeping.function = do_housekeeping;
2531	dev->housekeeping.data = (unsigned long) dev;
2532	mod_timer(&dev->housekeeping, jiffies);
2533
2534out:
2535	return err;
2536
2537out_free_irq:
2538	free_irq(dev->irq, dev);
2539out_free:
2540	kfree(dev);
2541out_release:
2542	release_region(iobase, HRZ_IO_EXTENT);
2543out_disable:
2544	pci_disable_device(pci_dev);
2545	goto out;
2546}
2547
2548static void __devexit hrz_remove_one(struct pci_dev *pci_dev)
2549{
2550	hrz_dev *dev;
2551
2552	dev = pci_get_drvdata(pci_dev);
2553
2554	PRINTD(DBG_INFO, "closing %p (atm_dev = %p)", dev, dev->atm_dev);
2555	del_timer_sync(&dev->housekeeping);
2556	hrz_reset(dev);
2557	atm_dev_deregister(dev->atm_dev);
2558	free_irq(dev->irq, dev);
2559	release_region(dev->iobase, HRZ_IO_EXTENT);
2560	kfree(dev);
2561
2562	pci_disable_device(pci_dev);
2563}
2564
2565static void __init hrz_check_args (void) {
2566#ifdef DEBUG_HORIZON
2567  PRINTK (KERN_NOTICE, "debug bitmap is %hx", debug &= DBG_MASK);
2568#else
2569  if (debug)
2570    PRINTK (KERN_NOTICE, "no debug support in this image");
2571#endif
2572
2573  if (vpi_bits > HRZ_MAX_VPI)
2574    PRINTK (KERN_ERR, "vpi_bits has been limited to %hu",
2575	    vpi_bits = HRZ_MAX_VPI);
2576
2577  if (max_tx_size < 0 || max_tx_size > TX_AAL5_LIMIT)
2578    PRINTK (KERN_NOTICE, "max_tx_size has been limited to %hu",
2579	    max_tx_size = TX_AAL5_LIMIT);
2580
2581  if (max_rx_size < 0 || max_rx_size > RX_AAL5_LIMIT)
2582    PRINTK (KERN_NOTICE, "max_rx_size has been limited to %hu",
2583	    max_rx_size = RX_AAL5_LIMIT);
2584
2585  return;
2586}
2587
2588MODULE_AUTHOR(maintainer_string);
2589MODULE_DESCRIPTION(description_string);
2590MODULE_LICENSE("GPL");
2591module_param(debug, ushort, 0644);
2592module_param(vpi_bits, ushort, 0);
2593module_param(max_tx_size, int, 0);
2594module_param(max_rx_size, int, 0);
2595module_param(pci_lat, byte, 0);
2596MODULE_PARM_DESC(debug, "debug bitmap, see .h file");
2597MODULE_PARM_DESC(vpi_bits, "number of bits (0..4) to allocate to VPIs");
2598MODULE_PARM_DESC(max_tx_size, "maximum size of TX AAL5 frames");
2599MODULE_PARM_DESC(max_rx_size, "maximum size of RX AAL5 frames");
2600MODULE_PARM_DESC(pci_lat, "PCI latency in bus cycles");
2601
2602static struct pci_device_id hrz_pci_tbl[] = {
2603	{ PCI_VENDOR_ID_MADGE, PCI_DEVICE_ID_MADGE_HORIZON, PCI_ANY_ID, PCI_ANY_ID,
2604	  0, 0, 0 },
2605	{ 0, }
2606};
2607
2608MODULE_DEVICE_TABLE(pci, hrz_pci_tbl);
2609
2610static struct pci_driver hrz_driver = {
2611	.name =		"horizon",
2612	.probe =	hrz_probe,
2613	.remove =	__devexit_p(hrz_remove_one),
2614	.id_table =	hrz_pci_tbl,
2615};
2616
2617/********** module entry **********/
2618
2619static int __init hrz_module_init (void) {
2620  // sanity check - cast is needed since printk does not support %Zu
2621  if (sizeof(struct MEMMAP) != 128*1024/4) {
2622    PRINTK (KERN_ERR, "Fix struct MEMMAP (is %lu fakewords).",
2623	    (unsigned long) sizeof(struct MEMMAP));
2624    return -ENOMEM;
2625  }
2626
2627  show_version();
2628
2629  // check arguments
2630  hrz_check_args();
2631
2632  // get the juice
2633  return pci_register_driver(&hrz_driver);
2634}
2635
2636/********** module exit **********/
2637
2638static void __exit hrz_module_exit (void) {
2639  PRINTD (DBG_FLOW, "cleanup_module");
2640
2641  pci_unregister_driver(&hrz_driver);
2642}
2643
2644module_init(hrz_module_init);
2645module_exit(hrz_module_exit);
2646