ftp://ftp.kernel.org/pub/linux/kernel/v2.6/linux-2.6.6.tar.bz2
[linux-2.6.git] / drivers / atm / ambassador.c
1 /*
2   Madge Ambassador 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 /* * dedicated to the memory of Graham Gordon 1971-1998 * */
24
25 #include <linux/module.h>
26 #include <linux/types.h>
27 #include <linux/pci.h>
28 #include <linux/kernel.h>
29 #include <linux/init.h>
30 #include <linux/ioport.h>
31 #include <linux/atmdev.h>
32 #include <linux/delay.h>
33 #include <linux/interrupt.h>
34
35 #include <asm/atomic.h>
36 #include <asm/io.h>
37 #include <asm/byteorder.h>
38
39 #include "ambassador.h"
40
41 #define maintainer_string "Giuliano Procida at Madge Networks <gprocida@madge.com>"
42 #define description_string "Madge ATM Ambassador driver"
43 #define version_string "1.2.4"
44
45 static inline void __init show_version (void) {
46   printk ("%s version %s\n", description_string, version_string);
47 }
48
49 /*
50   
51   Theory of Operation
52   
53   I Hardware, detection, initialisation and shutdown.
54   
55   1. Supported Hardware
56   
57   This driver is for the PCI ATMizer-based Ambassador card (except
58   very early versions). It is not suitable for the similar EISA "TR7"
59   card. Commercially, both cards are known as Collage Server ATM
60   adapters.
61   
62   The loader supports image transfer to the card, image start and few
63   other miscellaneous commands.
64   
65   Only AAL5 is supported with vpi = 0 and vci in the range 0 to 1023.
66   
67   The cards are big-endian.
68   
69   2. Detection
70   
71   Standard PCI stuff, the early cards are detected and rejected.
72   
73   3. Initialisation
74   
75   The cards are reset and the self-test results are checked. The
76   microcode image is then transferred and started. This waits for a
77   pointer to a descriptor containing details of the host-based queues
78   and buffers and various parameters etc. Once they are processed
79   normal operations may begin. The BIA is read using a microcode
80   command.
81   
82   4. Shutdown
83   
84   This may be accomplished either by a card reset or via the microcode
85   shutdown command. Further investigation required.
86   
87   5. Persistent state
88   
89   The card reset does not affect PCI configuration (good) or the
90   contents of several other "shared run-time registers" (bad) which
91   include doorbell and interrupt control as well as EEPROM and PCI
92   control. The driver must be careful when modifying these registers
93   not to touch bits it does not use and to undo any changes at exit.
94   
95   II Driver software
96   
97   0. Generalities
98   
99   The adapter is quite intelligent (fast) and has a simple interface
100   (few features). VPI is always zero, 1024 VCIs are supported. There
101   is limited cell rate support. UBR channels can be capped and ABR
102   (explicit rate, but not EFCI) is supported. There is no CBR or VBR
103   support.
104   
105   1. Driver <-> Adapter Communication
106   
107   Apart from the basic loader commands, the driver communicates
108   through three entities: the command queue (CQ), the transmit queue
109   pair (TXQ) and the receive queue pairs (RXQ). These three entities
110   are set up by the host and passed to the microcode just after it has
111   been started.
112   
113   All queues are host-based circular queues. They are contiguous and
114   (due to hardware limitations) have some restrictions as to their
115   locations in (bus) memory. They are of the "full means the same as
116   empty so don't do that" variety since the adapter uses pointers
117   internally.
118   
119   The queue pairs work as follows: one queue is for supply to the
120   adapter, items in it are pending and are owned by the adapter; the
121   other is the queue for return from the adapter, items in it have
122   been dealt with by the adapter. The host adds items to the supply
123   (TX descriptors and free RX buffer descriptors) and removes items
124   from the return (TX and RX completions). The adapter deals with out
125   of order completions.
126   
127   Interrupts (card to host) and the doorbell (host to card) are used
128   for signalling.
129   
130   1. CQ
131   
132   This is to communicate "open VC", "close VC", "get stats" etc. to
133   the adapter. At most one command is retired every millisecond by the
134   card. There is no out of order completion or notification. The
135   driver needs to check the return code of the command, waiting as
136   appropriate.
137   
138   2. TXQ
139   
140   TX supply items are of variable length (scatter gather support) and
141   so the queue items are (more or less) pointers to the real thing.
142   Each TX supply item contains a unique, host-supplied handle (the skb
143   bus address seems most sensible as this works for Alphas as well,
144   there is no need to do any endian conversions on the handles).
145   
146   TX return items consist of just the handles above.
147   
148   3. RXQ (up to 4 of these with different lengths and buffer sizes)
149   
150   RX supply items consist of a unique, host-supplied handle (the skb
151   bus address again) and a pointer to the buffer data area.
152   
153   RX return items consist of the handle above, the VC, length and a
154   status word. This just screams "oh so easy" doesn't it?
155
156   Note on RX pool sizes:
157    
158   Each pool should have enough buffers to handle a back-to-back stream
159   of minimum sized frames on a single VC. For example:
160   
161     frame spacing = 3us (about right)
162     
163     delay = IRQ lat + RX handling + RX buffer replenish = 20 (us)  (a guess)
164     
165     min number of buffers for one VC = 1 + delay/spacing (buffers)
166
167     delay/spacing = latency = (20+2)/3 = 7 (buffers)  (rounding up)
168     
169   The 20us delay assumes that there is no need to sleep; if we need to
170   sleep to get buffers we are going to drop frames anyway.
171   
172   In fact, each pool should have enough buffers to support the
173   simultaneous reassembly of a separate frame on each VC and cope with
174   the case in which frames complete in round robin cell fashion on
175   each VC.
176   
177   Only one frame can complete at each cell arrival, so if "n" VCs are
178   open, the worst case is to have them all complete frames together
179   followed by all starting new frames together.
180   
181     desired number of buffers = n + delay/spacing
182     
183   These are the extreme requirements, however, they are "n+k" for some
184   "k" so we have only the constant to choose. This is the argument
185   rx_lats which current defaults to 7.
186   
187   Actually, "n ? n+k : 0" is better and this is what is implemented,
188   subject to the limit given by the pool size.
189   
190   4. Driver locking
191   
192   Simple spinlocks are used around the TX and RX queue mechanisms.
193   Anyone with a faster, working method is welcome to implement it.
194   
195   The adapter command queue is protected with a spinlock. We always
196   wait for commands to complete.
197   
198   A more complex form of locking is used around parts of the VC open
199   and close functions. There are three reasons for a lock: 1. we need
200   to do atomic rate reservation and release (not used yet), 2. Opening
201   sometimes involves two adapter commands which must not be separated
202   by another command on the same VC, 3. the changes to RX pool size
203   must be atomic. The lock needs to work over context switches, so we
204   use a semaphore.
205   
206   III Hardware Features and Microcode Bugs
207   
208   1. Byte Ordering
209   
210   *%^"$&%^$*&^"$(%^$#&^%$(&#%$*(&^#%!"!"!*!
211   
212   2. Memory access
213   
214   All structures that are not accessed using DMA must be 4-byte
215   aligned (not a problem) and must not cross 4MB boundaries.
216   
217   There is a DMA memory hole at E0000000-E00000FF (groan).
218   
219   TX fragments (DMA read) must not cross 4MB boundaries (would be 16MB
220   but for a hardware bug).
221   
222   RX buffers (DMA write) must not cross 16MB boundaries and must
223   include spare trailing bytes up to the next 4-byte boundary; they
224   will be written with rubbish.
225   
226   The PLX likes to prefetch; if reading up to 4 u32 past the end of
227   each TX fragment is not a problem, then TX can be made to go a
228   little faster by passing a flag at init that disables a prefetch
229   workaround. We do not pass this flag. (new microcode only)
230   
231   Now we:
232   . Note that alloc_skb rounds up size to a 16byte boundary.  
233   . Ensure all areas do not traverse 4MB boundaries.
234   . Ensure all areas do not start at a E00000xx bus address.
235   (I cannot be certain, but this may always hold with Linux)
236   . Make all failures cause a loud message.
237   . Discard non-conforming SKBs (causes TX failure or RX fill delay).
238   . Discard non-conforming TX fragment descriptors (the TX fails).
239   In the future we could:
240   . Allow RX areas that traverse 4MB (but not 16MB) boundaries.
241   . Segment TX areas into some/more fragments, when necessary.
242   . Relax checks for non-DMA items (ignore hole).
243   . Give scatter-gather (iovec) requirements using ???. (?)
244   
245   3. VC close is broken (only for new microcode)
246   
247   The VC close adapter microcode command fails to do anything if any
248   frames have been received on the VC but none have been transmitted.
249   Frames continue to be reassembled and passed (with IRQ) to the
250   driver.
251   
252   IV To Do List
253   
254   . Fix bugs!
255   
256   . Timer code may be broken.
257   
258   . Deal with buggy VC close (somehow) in microcode 12.
259   
260   . Handle interrupted and/or non-blocking writes - is this a job for
261     the protocol layer?
262   
263   . Add code to break up TX fragments when they span 4MB boundaries.
264   
265   . Add SUNI phy layer (need to know where SUNI lives on card).
266   
267   . Implement a tx_alloc fn to (a) satisfy TX alignment etc. and (b)
268     leave extra headroom space for Ambassador TX descriptors.
269   
270   . Understand these elements of struct atm_vcc: recvq (proto?),
271     sleep, callback, listenq, backlog_quota, reply and user_back.
272   
273   . Adjust TX/RX skb allocation to favour IP with LANE/CLIP (configurable).
274   
275   . Impose a TX-pending limit (2?) on each VC, help avoid TX q overflow.
276   
277   . Decide whether RX buffer recycling is or can be made completely safe;
278     turn it back on. It looks like Werner is going to axe this.
279   
280   . Implement QoS changes on open VCs (involves extracting parts of VC open
281     and close into separate functions and using them to make changes).
282   
283   . Hack on command queue so that someone can issue multiple commands and wait
284     on the last one (OR only "no-op" or "wait" commands are waited for).
285   
286   . Eliminate need for while-schedule around do_command.
287   
288 */
289
290 /********** microcode **********/
291
292 #ifdef AMB_NEW_MICROCODE
293 #define UCODE(x) UCODE2(atmsar12.x)
294 #else
295 #define UCODE(x) UCODE2(atmsar11.x)
296 #endif
297 #define UCODE2(x) #x
298
299 static u32 __initdata ucode_start = 
300 #include UCODE(start)
301 ;
302
303 static region __initdata ucode_regions[] = {
304 #include UCODE(regions)
305   { 0, 0 }
306 };
307
308 static u32 __initdata ucode_data[] = {
309 #include UCODE(data)
310   0xdeadbeef
311 };
312
313 static void do_housekeeping (unsigned long arg);
314 /********** globals **********/
315
316 static amb_dev * amb_devs = NULL;
317 static struct timer_list housekeeping = TIMER_INITIALIZER(do_housekeeping, 0, 1);
318
319 static unsigned short debug = 0;
320 static unsigned int cmds = 8;
321 static unsigned int txs = 32;
322 static unsigned int rxs[NUM_RX_POOLS] = { 64, 64, 64, 64 };
323 static unsigned int rxs_bs[NUM_RX_POOLS] = { 4080, 12240, 36720, 65535 };
324 static unsigned int rx_lats = 7;
325 static unsigned char pci_lat = 0;
326
327 static const unsigned long onegigmask = -1 << 30;
328
329 /********** access to adapter **********/
330
331 static inline void wr_plain (const amb_dev * dev, size_t addr, u32 data) {
332   PRINTD (DBG_FLOW|DBG_REGS, "wr: %08zx <- %08x", addr, data);
333 #ifdef AMB_MMIO
334   dev->membase[addr / sizeof(u32)] = data;
335 #else
336   outl (data, dev->iobase + addr);
337 #endif
338 }
339
340 static inline u32 rd_plain (const amb_dev * dev, size_t addr) {
341 #ifdef AMB_MMIO
342   u32 data = dev->membase[addr / sizeof(u32)];
343 #else
344   u32 data = inl (dev->iobase + addr);
345 #endif
346   PRINTD (DBG_FLOW|DBG_REGS, "rd: %08zx -> %08x", addr, data);
347   return data;
348 }
349
350 static inline void wr_mem (const amb_dev * dev, size_t addr, u32 data) {
351   u32 be = cpu_to_be32 (data);
352   PRINTD (DBG_FLOW|DBG_REGS, "wr: %08zx <- %08x b[%08x]", addr, data, be);
353 #ifdef AMB_MMIO
354   dev->membase[addr / sizeof(u32)] = be;
355 #else
356   outl (be, dev->iobase + addr);
357 #endif
358 }
359
360 static inline u32 rd_mem (const amb_dev * dev, size_t addr) {
361 #ifdef AMB_MMIO
362   u32 be = dev->membase[addr / sizeof(u32)];
363 #else
364   u32 be = inl (dev->iobase + addr);
365 #endif
366   u32 data = be32_to_cpu (be);
367   PRINTD (DBG_FLOW|DBG_REGS, "rd: %08zx -> %08x b[%08x]", addr, data, be);
368   return data;
369 }
370
371 /********** dump routines **********/
372
373 static inline void dump_registers (const amb_dev * dev) {
374 #ifdef DEBUG_AMBASSADOR
375   if (debug & DBG_REGS) {
376     size_t i;
377     PRINTD (DBG_REGS, "reading PLX control: ");
378     for (i = 0x00; i < 0x30; i += sizeof(u32))
379       rd_mem (dev, i);
380     PRINTD (DBG_REGS, "reading mailboxes: ");
381     for (i = 0x40; i < 0x60; i += sizeof(u32))
382       rd_mem (dev, i);
383     PRINTD (DBG_REGS, "reading doorb irqev irqen reset:");
384     for (i = 0x60; i < 0x70; i += sizeof(u32))
385       rd_mem (dev, i);
386   }
387 #else
388   (void) dev;
389 #endif
390   return;
391 }
392
393 static inline void dump_loader_block (volatile loader_block * lb) {
394 #ifdef DEBUG_AMBASSADOR
395   unsigned int i;
396   PRINTDB (DBG_LOAD, "lb @ %p; res: %d, cmd: %d, pay:",
397            lb, be32_to_cpu (lb->result), be32_to_cpu (lb->command));
398   for (i = 0; i < MAX_COMMAND_DATA; ++i)
399     PRINTDM (DBG_LOAD, " %08x", be32_to_cpu (lb->payload.data[i]));
400   PRINTDE (DBG_LOAD, ", vld: %08x", be32_to_cpu (lb->valid));
401 #else
402   (void) lb;
403 #endif
404   return;
405 }
406
407 static inline void dump_command (command * cmd) {
408 #ifdef DEBUG_AMBASSADOR
409   unsigned int i;
410   PRINTDB (DBG_CMD, "cmd @ %p, req: %08x, pars:",
411            cmd, /*be32_to_cpu*/ (cmd->request));
412   for (i = 0; i < 3; ++i)
413     PRINTDM (DBG_CMD, " %08x", /*be32_to_cpu*/ (cmd->args.par[i]));
414   PRINTDE (DBG_CMD, "");
415 #else
416   (void) cmd;
417 #endif
418   return;
419 }
420
421 static inline void dump_skb (char * prefix, unsigned int vc, struct sk_buff * skb) {
422 #ifdef DEBUG_AMBASSADOR
423   unsigned int i;
424   unsigned char * data = skb->data;
425   PRINTDB (DBG_DATA, "%s(%u) ", prefix, vc);
426   for (i=0; i<skb->len && i < 256;i++)
427     PRINTDM (DBG_DATA, "%02x ", data[i]);
428   PRINTDE (DBG_DATA,"");
429 #else
430   (void) prefix;
431   (void) vc;
432   (void) skb;
433 #endif
434   return;
435 }
436
437 /********** check memory areas for use by Ambassador **********/
438
439 /* see limitations under Hardware Features */
440
441 static inline int check_area (void * start, size_t length) {
442   // assumes length > 0
443   const u32 fourmegmask = -1 << 22;
444   const u32 twofivesixmask = -1 << 8;
445   const u32 starthole = 0xE0000000;
446   u32 startaddress = virt_to_bus (start);
447   u32 lastaddress = startaddress+length-1;
448   if ((startaddress ^ lastaddress) & fourmegmask ||
449       (startaddress & twofivesixmask) == starthole) {
450     PRINTK (KERN_ERR, "check_area failure: [%x,%x] - mail maintainer!",
451             startaddress, lastaddress);
452     return -1;
453   } else {
454     return 0;
455   }
456 }
457
458 /********** free an skb (as per ATM device driver documentation) **********/
459
460 static inline void amb_kfree_skb (struct sk_buff * skb) {
461   if (ATM_SKB(skb)->vcc->pop) {
462     ATM_SKB(skb)->vcc->pop (ATM_SKB(skb)->vcc, skb);
463   } else {
464     dev_kfree_skb_any (skb);
465   }
466 }
467
468 /********** TX completion **********/
469
470 static inline void tx_complete (amb_dev * dev, tx_out * tx) {
471   tx_simple * tx_descr = bus_to_virt (tx->handle);
472   struct sk_buff * skb = tx_descr->skb;
473   
474   PRINTD (DBG_FLOW|DBG_TX, "tx_complete %p %p", dev, tx);
475   
476   // VC layer stats
477   atomic_inc(&ATM_SKB(skb)->vcc->stats->tx);
478   
479   // free the descriptor
480   kfree (tx_descr);
481   
482   // free the skb
483   amb_kfree_skb (skb);
484   
485   dev->stats.tx_ok++;
486   return;
487 }
488
489 /********** RX completion **********/
490
491 static void rx_complete (amb_dev * dev, rx_out * rx) {
492   struct sk_buff * skb = bus_to_virt (rx->handle);
493   u16 vc = be16_to_cpu (rx->vc);
494   // unused: u16 lec_id = be16_to_cpu (rx->lec_id);
495   u16 status = be16_to_cpu (rx->status);
496   u16 rx_len = be16_to_cpu (rx->length);
497   
498   PRINTD (DBG_FLOW|DBG_RX, "rx_complete %p %p (len=%hu)", dev, rx, rx_len);
499   
500   // XXX move this in and add to VC stats ???
501   if (!status) {
502     struct atm_vcc * atm_vcc = dev->rxer[vc];
503     dev->stats.rx.ok++;
504     
505     if (atm_vcc) {
506       
507       if (rx_len <= atm_vcc->qos.rxtp.max_sdu) {
508         
509         if (atm_charge (atm_vcc, skb->truesize)) {
510           
511           // prepare socket buffer
512           ATM_SKB(skb)->vcc = atm_vcc;
513           skb_put (skb, rx_len);
514           
515           dump_skb ("<<<", vc, skb);
516           
517           // VC layer stats
518           atomic_inc(&atm_vcc->stats->rx);
519           do_gettimeofday(&skb->stamp);
520           // end of our responsability
521           atm_vcc->push (atm_vcc, skb);
522           return;
523           
524         } else {
525           // someone fix this (message), please!
526           PRINTD (DBG_INFO|DBG_RX, "dropped thanks to atm_charge (vc %hu, truesize %u)", vc, skb->truesize);
527           // drop stats incremented in atm_charge
528         }
529         
530       } else {
531         PRINTK (KERN_INFO, "dropped over-size frame");
532         // should we count this?
533         atomic_inc(&atm_vcc->stats->rx_drop);
534       }
535       
536     } else {
537       PRINTD (DBG_WARN|DBG_RX, "got frame but RX closed for channel %hu", vc);
538       // this is an adapter bug, only in new version of microcode
539     }
540     
541   } else {
542     dev->stats.rx.error++;
543     if (status & CRC_ERR)
544       dev->stats.rx.badcrc++;
545     if (status & LEN_ERR)
546       dev->stats.rx.toolong++;
547     if (status & ABORT_ERR)
548       dev->stats.rx.aborted++;
549     if (status & UNUSED_ERR)
550       dev->stats.rx.unused++;
551   }
552   
553   dev_kfree_skb_any (skb);
554   return;
555 }
556
557 /*
558   
559   Note on queue handling.
560   
561   Here "give" and "take" refer to queue entries and a queue (pair)
562   rather than frames to or from the host or adapter. Empty frame
563   buffers are given to the RX queue pair and returned unused or
564   containing RX frames. TX frames (well, pointers to TX fragment
565   lists) are given to the TX queue pair, completions are returned.
566   
567 */
568
569 /********** command queue **********/
570
571 // I really don't like this, but it's the best I can do at the moment
572
573 // also, the callers are responsible for byte order as the microcode
574 // sometimes does 16-bit accesses (yuk yuk yuk)
575
576 static int command_do (amb_dev * dev, command * cmd) {
577   amb_cq * cq = &dev->cq;
578   volatile amb_cq_ptrs * ptrs = &cq->ptrs;
579   command * my_slot;
580   unsigned long timeout;
581   
582   PRINTD (DBG_FLOW|DBG_CMD, "command_do %p", dev);
583   
584   if (test_bit (dead, &dev->flags))
585     return 0;
586   
587   spin_lock (&cq->lock);
588   
589   // if not full...
590   if (cq->pending < cq->maximum) {
591     // remember my slot for later
592     my_slot = ptrs->in;
593     PRINTD (DBG_CMD, "command in slot %p", my_slot);
594     
595     dump_command (cmd);
596     
597     // copy command in
598     *ptrs->in = *cmd;
599     cq->pending++;
600     ptrs->in = NEXTQ (ptrs->in, ptrs->start, ptrs->limit);
601     
602     // mail the command
603     wr_mem (dev, offsetof(amb_mem, mb.adapter.cmd_address), virt_to_bus (ptrs->in));
604     
605     // prepare to wait for cq->pending milliseconds
606     // effectively one centisecond on i386
607     timeout = (cq->pending*HZ+999)/1000;
608     
609     if (cq->pending > cq->high)
610       cq->high = cq->pending;
611     spin_unlock (&cq->lock);
612     
613     while (timeout) {
614       // go to sleep
615       // PRINTD (DBG_CMD, "wait: sleeping %lu for command", timeout);
616       set_current_state(TASK_UNINTERRUPTIBLE);
617       timeout = schedule_timeout (timeout);
618     }
619     
620     // wait for my slot to be reached (all waiters are here or above, until...)
621     while (ptrs->out != my_slot) {
622       PRINTD (DBG_CMD, "wait: command slot (now at %p)", ptrs->out);
623       set_current_state(TASK_UNINTERRUPTIBLE);
624       schedule();
625     }
626     
627     // wait on my slot (... one gets to its slot, and... )
628     while (ptrs->out->request != cpu_to_be32 (SRB_COMPLETE)) {
629       PRINTD (DBG_CMD, "wait: command slot completion");
630       set_current_state(TASK_UNINTERRUPTIBLE);
631       schedule();
632     }
633     
634     PRINTD (DBG_CMD, "command complete");
635     // update queue (... moves the queue along to the next slot)
636     spin_lock (&cq->lock);
637     cq->pending--;
638     // copy command out
639     *cmd = *ptrs->out;
640     ptrs->out = NEXTQ (ptrs->out, ptrs->start, ptrs->limit);
641     spin_unlock (&cq->lock);
642     
643     return 0;
644   } else {
645     cq->filled++;
646     spin_unlock (&cq->lock);
647     return -EAGAIN;
648   }
649   
650 }
651
652 /********** TX queue pair **********/
653
654 static inline int tx_give (amb_dev * dev, tx_in * tx) {
655   amb_txq * txq = &dev->txq;
656   unsigned long flags;
657   
658   PRINTD (DBG_FLOW|DBG_TX, "tx_give %p", dev);
659
660   if (test_bit (dead, &dev->flags))
661     return 0;
662   
663   spin_lock_irqsave (&txq->lock, flags);
664   
665   if (txq->pending < txq->maximum) {
666     PRINTD (DBG_TX, "TX in slot %p", txq->in.ptr);
667
668     *txq->in.ptr = *tx;
669     txq->pending++;
670     txq->in.ptr = NEXTQ (txq->in.ptr, txq->in.start, txq->in.limit);
671     // hand over the TX and ring the bell
672     wr_mem (dev, offsetof(amb_mem, mb.adapter.tx_address), virt_to_bus (txq->in.ptr));
673     wr_mem (dev, offsetof(amb_mem, doorbell), TX_FRAME);
674     
675     if (txq->pending > txq->high)
676       txq->high = txq->pending;
677     spin_unlock_irqrestore (&txq->lock, flags);
678     return 0;
679   } else {
680     txq->filled++;
681     spin_unlock_irqrestore (&txq->lock, flags);
682     return -EAGAIN;
683   }
684 }
685
686 static inline int tx_take (amb_dev * dev) {
687   amb_txq * txq = &dev->txq;
688   unsigned long flags;
689   
690   PRINTD (DBG_FLOW|DBG_TX, "tx_take %p", dev);
691   
692   spin_lock_irqsave (&txq->lock, flags);
693   
694   if (txq->pending && txq->out.ptr->handle) {
695     // deal with TX completion
696     tx_complete (dev, txq->out.ptr);
697     // mark unused again
698     txq->out.ptr->handle = 0;
699     // remove item
700     txq->pending--;
701     txq->out.ptr = NEXTQ (txq->out.ptr, txq->out.start, txq->out.limit);
702     
703     spin_unlock_irqrestore (&txq->lock, flags);
704     return 0;
705   } else {
706     
707     spin_unlock_irqrestore (&txq->lock, flags);
708     return -1;
709   }
710 }
711
712 /********** RX queue pairs **********/
713
714 static inline int rx_give (amb_dev * dev, rx_in * rx, unsigned char pool) {
715   amb_rxq * rxq = &dev->rxq[pool];
716   unsigned long flags;
717   
718   PRINTD (DBG_FLOW|DBG_RX, "rx_give %p[%hu]", dev, pool);
719   
720   spin_lock_irqsave (&rxq->lock, flags);
721   
722   if (rxq->pending < rxq->maximum) {
723     PRINTD (DBG_RX, "RX in slot %p", rxq->in.ptr);
724
725     *rxq->in.ptr = *rx;
726     rxq->pending++;
727     rxq->in.ptr = NEXTQ (rxq->in.ptr, rxq->in.start, rxq->in.limit);
728     // hand over the RX buffer
729     wr_mem (dev, offsetof(amb_mem, mb.adapter.rx_address[pool]), virt_to_bus (rxq->in.ptr));
730     
731     spin_unlock_irqrestore (&rxq->lock, flags);
732     return 0;
733   } else {
734     spin_unlock_irqrestore (&rxq->lock, flags);
735     return -1;
736   }
737 }
738
739 static inline int rx_take (amb_dev * dev, unsigned char pool) {
740   amb_rxq * rxq = &dev->rxq[pool];
741   unsigned long flags;
742   
743   PRINTD (DBG_FLOW|DBG_RX, "rx_take %p[%hu]", dev, pool);
744   
745   spin_lock_irqsave (&rxq->lock, flags);
746   
747   if (rxq->pending && (rxq->out.ptr->status || rxq->out.ptr->length)) {
748     // deal with RX completion
749     rx_complete (dev, rxq->out.ptr);
750     // mark unused again
751     rxq->out.ptr->status = 0;
752     rxq->out.ptr->length = 0;
753     // remove item
754     rxq->pending--;
755     rxq->out.ptr = NEXTQ (rxq->out.ptr, rxq->out.start, rxq->out.limit);
756     
757     if (rxq->pending < rxq->low)
758       rxq->low = rxq->pending;
759     spin_unlock_irqrestore (&rxq->lock, flags);
760     return 0;
761   } else {
762     if (!rxq->pending && rxq->buffers_wanted)
763       rxq->emptied++;
764     spin_unlock_irqrestore (&rxq->lock, flags);
765     return -1;
766   }
767 }
768
769 /********** RX Pool handling **********/
770
771 /* pre: buffers_wanted = 0, post: pending = 0 */
772 static inline void drain_rx_pool (amb_dev * dev, unsigned char pool) {
773   amb_rxq * rxq = &dev->rxq[pool];
774   
775   PRINTD (DBG_FLOW|DBG_POOL, "drain_rx_pool %p %hu", dev, pool);
776   
777   if (test_bit (dead, &dev->flags))
778     return;
779   
780   /* we are not quite like the fill pool routines as we cannot just
781      remove one buffer, we have to remove all of them, but we might as
782      well pretend... */
783   if (rxq->pending > rxq->buffers_wanted) {
784     command cmd;
785     cmd.request = cpu_to_be32 (SRB_FLUSH_BUFFER_Q);
786     cmd.args.flush.flags = cpu_to_be32 (pool << SRB_POOL_SHIFT);
787     while (command_do (dev, &cmd))
788       schedule();
789     /* the pool may also be emptied via the interrupt handler */
790     while (rxq->pending > rxq->buffers_wanted)
791       if (rx_take (dev, pool))
792         schedule();
793   }
794   
795   return;
796 }
797
798 static void drain_rx_pools (amb_dev * dev) {
799   unsigned char pool;
800   
801   PRINTD (DBG_FLOW|DBG_POOL, "drain_rx_pools %p", dev);
802   
803   for (pool = 0; pool < NUM_RX_POOLS; ++pool)
804     drain_rx_pool (dev, pool);
805 }
806
807 static inline void fill_rx_pool (amb_dev * dev, unsigned char pool, int priority) {
808   rx_in rx;
809   amb_rxq * rxq;
810   
811   PRINTD (DBG_FLOW|DBG_POOL, "fill_rx_pool %p %hu %x", dev, pool, priority);
812   
813   if (test_bit (dead, &dev->flags))
814     return;
815   
816   rxq = &dev->rxq[pool];
817   while (rxq->pending < rxq->maximum && rxq->pending < rxq->buffers_wanted) {
818     
819     struct sk_buff * skb = alloc_skb (rxq->buffer_size, priority);
820     if (!skb) {
821       PRINTD (DBG_SKB|DBG_POOL, "failed to allocate skb for RX pool %hu", pool);
822       return;
823     }
824     if (check_area (skb->data, skb->truesize)) {
825       dev_kfree_skb_any (skb);
826       return;
827     }
828     // cast needed as there is no %? for pointer differences
829     PRINTD (DBG_SKB, "allocated skb at %p, head %p, area %li",
830             skb, skb->head, (long) (skb->end - skb->head));
831     rx.handle = virt_to_bus (skb);
832     rx.host_address = cpu_to_be32 (virt_to_bus (skb->data));
833     if (rx_give (dev, &rx, pool))
834       dev_kfree_skb_any (skb);
835     
836   }
837   
838   return;
839 }
840
841 // top up all RX pools (can also be called as a bottom half)
842 static void fill_rx_pools (amb_dev * dev) {
843   unsigned char pool;
844   
845   PRINTD (DBG_FLOW|DBG_POOL, "fill_rx_pools %p", dev);
846   
847   for (pool = 0; pool < NUM_RX_POOLS; ++pool)
848     fill_rx_pool (dev, pool, GFP_ATOMIC);
849   
850   return;
851 }
852
853 /********** enable host interrupts **********/
854
855 static inline void interrupts_on (amb_dev * dev) {
856   wr_plain (dev, offsetof(amb_mem, interrupt_control),
857             rd_plain (dev, offsetof(amb_mem, interrupt_control))
858             | AMB_INTERRUPT_BITS);
859 }
860
861 /********** disable host interrupts **********/
862
863 static inline void interrupts_off (amb_dev * dev) {
864   wr_plain (dev, offsetof(amb_mem, interrupt_control),
865             rd_plain (dev, offsetof(amb_mem, interrupt_control))
866             &~ AMB_INTERRUPT_BITS);
867 }
868
869 /********** interrupt handling **********/
870
871 static irqreturn_t interrupt_handler(int irq, void *dev_id,
872                                         struct pt_regs *pt_regs) {
873   amb_dev * dev = amb_devs;
874   (void) pt_regs;
875   
876   PRINTD (DBG_IRQ|DBG_FLOW, "interrupt_handler: %p", dev_id);
877   
878   if (!dev_id) {
879     PRINTD (DBG_IRQ|DBG_ERR, "irq with NULL dev_id: %d", irq);
880     return IRQ_NONE;
881   }
882   // Did one of our cards generate the interrupt?
883   while (dev) {
884     if (dev == dev_id)
885       break;
886     dev = dev->prev;
887   }
888   // impossible - unless we add the device to our list after both
889   // registering the IRQ handler for it and enabling interrupts, AND
890   // the card generates an IRQ at startup - should not happen again
891   if (!dev) {
892     PRINTD (DBG_IRQ, "irq for unknown device: %d", irq);
893     return IRQ_NONE;
894   }
895   // impossible - unless we have memory corruption of dev or kernel
896   if (irq != dev->irq) {
897     PRINTD (DBG_IRQ|DBG_ERR, "irq mismatch: %d", irq);
898     return IRQ_NONE;
899   }
900   
901   {
902     u32 interrupt = rd_plain (dev, offsetof(amb_mem, interrupt));
903   
904     // for us or someone else sharing the same interrupt
905     if (!interrupt) {
906       PRINTD (DBG_IRQ, "irq not for me: %d", irq);
907       return IRQ_NONE;
908     }
909     
910     // definitely for us
911     PRINTD (DBG_IRQ, "FYI: interrupt was %08x", interrupt);
912     wr_plain (dev, offsetof(amb_mem, interrupt), -1);
913   }
914   
915   {
916     unsigned int irq_work = 0;
917     unsigned char pool;
918     for (pool = 0; pool < NUM_RX_POOLS; ++pool)
919       while (!rx_take (dev, pool))
920         ++irq_work;
921     while (!tx_take (dev))
922       ++irq_work;
923   
924     if (irq_work) {
925 #ifdef FILL_RX_POOLS_IN_BH
926       schedule_work (&dev->bh);
927 #else
928       fill_rx_pools (dev);
929 #endif
930
931       PRINTD (DBG_IRQ, "work done: %u", irq_work);
932     } else {
933       PRINTD (DBG_IRQ|DBG_WARN, "no work done");
934     }
935   }
936   
937   PRINTD (DBG_IRQ|DBG_FLOW, "interrupt_handler done: %p", dev_id);
938   return IRQ_HANDLED;
939 }
940
941 /********** make rate (not quite as much fun as Horizon) **********/
942
943 static unsigned int make_rate (unsigned int rate, rounding r,
944                                u16 * bits, unsigned int * actual) {
945   unsigned char exp = -1; // hush gcc
946   unsigned int man = -1;  // hush gcc
947   
948   PRINTD (DBG_FLOW|DBG_QOS, "make_rate %u", rate);
949   
950   // rates in cells per second, ITU format (nasty 16-bit floating-point)
951   // given 5-bit e and 9-bit m:
952   // rate = EITHER (1+m/2^9)*2^e    OR 0
953   // bits = EITHER 1<<14 | e<<9 | m OR 0
954   // (bit 15 is "reserved", bit 14 "non-zero")
955   // smallest rate is 0 (special representation)
956   // largest rate is (1+511/512)*2^31 = 4290772992 (< 2^32-1)
957   // smallest non-zero rate is (1+0/512)*2^0 = 1 (> 0)
958   // simple algorithm:
959   // find position of top bit, this gives e
960   // remove top bit and shift (rounding if feeling clever) by 9-e
961   
962   // ucode bug: please don't set bit 14! so 0 rate not representable
963   
964   if (rate > 0xffc00000U) {
965     // larger than largest representable rate
966     
967     if (r == round_up) {
968         return -EINVAL;
969     } else {
970       exp = 31;
971       man = 511;
972     }
973     
974   } else if (rate) {
975     // representable rate
976     
977     exp = 31;
978     man = rate;
979     
980     // invariant: rate = man*2^(exp-31)
981     while (!(man & (1<<31))) {
982       exp = exp - 1;
983       man = man<<1;
984     }
985     
986     // man has top bit set
987     // rate = (2^31+(man-2^31))*2^(exp-31)
988     // rate = (1+(man-2^31)/2^31)*2^exp
989     man = man<<1;
990     man &= 0xffffffffU; // a nop on 32-bit systems
991     // rate = (1+man/2^32)*2^exp
992     
993     // exp is in the range 0 to 31, man is in the range 0 to 2^32-1
994     // time to lose significance... we want m in the range 0 to 2^9-1
995     // rounding presents a minor problem... we first decide which way
996     // we are rounding (based on given rounding direction and possibly
997     // the bits of the mantissa that are to be discarded).
998     
999     switch (r) {
1000       case round_down: {
1001         // just truncate
1002         man = man>>(32-9);
1003         break;
1004       }
1005       case round_up: {
1006         // check all bits that we are discarding
1007         if (man & (-1>>9)) {
1008           man = (man>>(32-9)) + 1;
1009           if (man == (1<<9)) {
1010             // no need to check for round up outside of range
1011             man = 0;
1012             exp += 1;
1013           }
1014         } else {
1015           man = (man>>(32-9));
1016         }
1017         break;
1018       }
1019       case round_nearest: {
1020         // check msb that we are discarding
1021         if (man & (1<<(32-9-1))) {
1022           man = (man>>(32-9)) + 1;
1023           if (man == (1<<9)) {
1024             // no need to check for round up outside of range
1025             man = 0;
1026             exp += 1;
1027           }
1028         } else {
1029           man = (man>>(32-9));
1030         }
1031         break;
1032       }
1033     }
1034     
1035   } else {
1036     // zero rate - not representable
1037     
1038     if (r == round_down) {
1039       return -EINVAL;
1040     } else {
1041       exp = 0;
1042       man = 0;
1043     }
1044     
1045   }
1046   
1047   PRINTD (DBG_QOS, "rate: man=%u, exp=%hu", man, exp);
1048   
1049   if (bits)
1050     *bits = /* (1<<14) | */ (exp<<9) | man;
1051   
1052   if (actual)
1053     *actual = (exp >= 9)
1054       ? (1 << exp) + (man << (exp-9))
1055       : (1 << exp) + ((man + (1<<(9-exp-1))) >> (9-exp));
1056   
1057   return 0;
1058 }
1059
1060 /********** Linux ATM Operations **********/
1061
1062 // some are not yet implemented while others do not make sense for
1063 // this device
1064
1065 /********** Open a VC **********/
1066
1067 static int amb_open (struct atm_vcc * atm_vcc)
1068 {
1069   int error;
1070   
1071   struct atm_qos * qos;
1072   struct atm_trafprm * txtp;
1073   struct atm_trafprm * rxtp;
1074   u16 tx_rate_bits;
1075   u16 tx_vc_bits = -1; // hush gcc
1076   u16 tx_frame_bits = -1; // hush gcc
1077   
1078   amb_dev * dev = AMB_DEV(atm_vcc->dev);
1079   amb_vcc * vcc;
1080   unsigned char pool = -1; // hush gcc
1081   short vpi = atm_vcc->vpi;
1082   int vci = atm_vcc->vci;
1083   
1084   PRINTD (DBG_FLOW|DBG_VCC, "amb_open %x %x", vpi, vci);
1085   
1086 #ifdef ATM_VPI_UNSPEC
1087   // UNSPEC is deprecated, remove this code eventually
1088   if (vpi == ATM_VPI_UNSPEC || vci == ATM_VCI_UNSPEC) {
1089     PRINTK (KERN_WARNING, "rejecting open with unspecified VPI/VCI (deprecated)");
1090     return -EINVAL;
1091   }
1092 #endif
1093   
1094   if (!(0 <= vpi && vpi < (1<<NUM_VPI_BITS) &&
1095         0 <= vci && vci < (1<<NUM_VCI_BITS))) {
1096     PRINTD (DBG_WARN|DBG_VCC, "VPI/VCI out of range: %hd/%d", vpi, vci);
1097     return -EINVAL;
1098   }
1099   
1100   qos = &atm_vcc->qos;
1101   
1102   if (qos->aal != ATM_AAL5) {
1103     PRINTD (DBG_QOS, "AAL not supported");
1104     return -EINVAL;
1105   }
1106   
1107   // traffic parameters
1108   
1109   PRINTD (DBG_QOS, "TX:");
1110   txtp = &qos->txtp;
1111   if (txtp->traffic_class != ATM_NONE) {
1112     switch (txtp->traffic_class) {
1113       case ATM_UBR: {
1114         // we take "the PCR" as a rate-cap
1115         int pcr = atm_pcr_goal (txtp);
1116         if (!pcr) {
1117           // no rate cap
1118           tx_rate_bits = 0;
1119           tx_vc_bits = TX_UBR;
1120           tx_frame_bits = TX_FRAME_NOTCAP;
1121         } else {
1122           rounding r;
1123           if (pcr < 0) {
1124             r = round_down;
1125             pcr = -pcr;
1126           } else {
1127             r = round_up;
1128           }
1129           error = make_rate (pcr, r, &tx_rate_bits, 0);
1130           tx_vc_bits = TX_UBR_CAPPED;
1131           tx_frame_bits = TX_FRAME_CAPPED;
1132         }
1133         break;
1134       }
1135 #if 0
1136       case ATM_ABR: {
1137         pcr = atm_pcr_goal (txtp);
1138         PRINTD (DBG_QOS, "pcr goal = %d", pcr);
1139         break;
1140       }
1141 #endif
1142       default: {
1143         // PRINTD (DBG_QOS, "request for non-UBR/ABR denied");
1144         PRINTD (DBG_QOS, "request for non-UBR denied");
1145         return -EINVAL;
1146       }
1147     }
1148     PRINTD (DBG_QOS, "tx_rate_bits=%hx, tx_vc_bits=%hx",
1149             tx_rate_bits, tx_vc_bits);
1150   }
1151   
1152   PRINTD (DBG_QOS, "RX:");
1153   rxtp = &qos->rxtp;
1154   if (rxtp->traffic_class == ATM_NONE) {
1155     // do nothing
1156   } else {
1157     // choose an RX pool (arranged in increasing size)
1158     for (pool = 0; pool < NUM_RX_POOLS; ++pool)
1159       if ((unsigned int) rxtp->max_sdu <= dev->rxq[pool].buffer_size) {
1160         PRINTD (DBG_VCC|DBG_QOS|DBG_POOL, "chose pool %hu (max_sdu %u <= %u)",
1161                 pool, rxtp->max_sdu, dev->rxq[pool].buffer_size);
1162         break;
1163       }
1164     if (pool == NUM_RX_POOLS) {
1165       PRINTD (DBG_WARN|DBG_VCC|DBG_QOS|DBG_POOL,
1166               "no pool suitable for VC (RX max_sdu %d is too large)",
1167               rxtp->max_sdu);
1168       return -EINVAL;
1169     }
1170     
1171     switch (rxtp->traffic_class) {
1172       case ATM_UBR: {
1173         break;
1174       }
1175 #if 0
1176       case ATM_ABR: {
1177         pcr = atm_pcr_goal (rxtp);
1178         PRINTD (DBG_QOS, "pcr goal = %d", pcr);
1179         break;
1180       }
1181 #endif
1182       default: {
1183         // PRINTD (DBG_QOS, "request for non-UBR/ABR denied");
1184         PRINTD (DBG_QOS, "request for non-UBR denied");
1185         return -EINVAL;
1186       }
1187     }
1188   }
1189   
1190   // get space for our vcc stuff
1191   vcc = kmalloc (sizeof(amb_vcc), GFP_KERNEL);
1192   if (!vcc) {
1193     PRINTK (KERN_ERR, "out of memory!");
1194     return -ENOMEM;
1195   }
1196   atm_vcc->dev_data = (void *) vcc;
1197   
1198   // no failures beyond this point
1199   
1200   // we are not really "immediately before allocating the connection
1201   // identifier in hardware", but it will just have to do!
1202   set_bit(ATM_VF_ADDR,&atm_vcc->flags);
1203   
1204   if (txtp->traffic_class != ATM_NONE) {
1205     command cmd;
1206     
1207     vcc->tx_frame_bits = tx_frame_bits;
1208     
1209     down (&dev->vcc_sf);
1210     if (dev->rxer[vci]) {
1211       // RXer on the channel already, just modify rate...
1212       cmd.request = cpu_to_be32 (SRB_MODIFY_VC_RATE);
1213       cmd.args.modify_rate.vc = cpu_to_be32 (vci);  // vpi 0
1214       cmd.args.modify_rate.rate = cpu_to_be32 (tx_rate_bits << SRB_RATE_SHIFT);
1215       while (command_do (dev, &cmd))
1216         schedule();
1217       // ... and TX flags, preserving the RX pool
1218       cmd.request = cpu_to_be32 (SRB_MODIFY_VC_FLAGS);
1219       cmd.args.modify_flags.vc = cpu_to_be32 (vci);  // vpi 0
1220       cmd.args.modify_flags.flags = cpu_to_be32
1221         ( (AMB_VCC(dev->rxer[vci])->rx_info.pool << SRB_POOL_SHIFT)
1222           | (tx_vc_bits << SRB_FLAGS_SHIFT) );
1223       while (command_do (dev, &cmd))
1224         schedule();
1225     } else {
1226       // no RXer on the channel, just open (with pool zero)
1227       cmd.request = cpu_to_be32 (SRB_OPEN_VC);
1228       cmd.args.open.vc = cpu_to_be32 (vci);  // vpi 0
1229       cmd.args.open.flags = cpu_to_be32 (tx_vc_bits << SRB_FLAGS_SHIFT);
1230       cmd.args.open.rate = cpu_to_be32 (tx_rate_bits << SRB_RATE_SHIFT);
1231       while (command_do (dev, &cmd))
1232         schedule();
1233     }
1234     dev->txer[vci].tx_present = 1;
1235     up (&dev->vcc_sf);
1236   }
1237   
1238   if (rxtp->traffic_class != ATM_NONE) {
1239     command cmd;
1240     
1241     vcc->rx_info.pool = pool;
1242     
1243     down (&dev->vcc_sf); 
1244     /* grow RX buffer pool */
1245     if (!dev->rxq[pool].buffers_wanted)
1246       dev->rxq[pool].buffers_wanted = rx_lats;
1247     dev->rxq[pool].buffers_wanted += 1;
1248     fill_rx_pool (dev, pool, GFP_KERNEL);
1249     
1250     if (dev->txer[vci].tx_present) {
1251       // TXer on the channel already
1252       // switch (from pool zero) to this pool, preserving the TX bits
1253       cmd.request = cpu_to_be32 (SRB_MODIFY_VC_FLAGS);
1254       cmd.args.modify_flags.vc = cpu_to_be32 (vci);  // vpi 0
1255       cmd.args.modify_flags.flags = cpu_to_be32
1256         ( (pool << SRB_POOL_SHIFT)
1257           | (dev->txer[vci].tx_vc_bits << SRB_FLAGS_SHIFT) );
1258     } else {
1259       // no TXer on the channel, open the VC (with no rate info)
1260       cmd.request = cpu_to_be32 (SRB_OPEN_VC);
1261       cmd.args.open.vc = cpu_to_be32 (vci);  // vpi 0
1262       cmd.args.open.flags = cpu_to_be32 (pool << SRB_POOL_SHIFT);
1263       cmd.args.open.rate = cpu_to_be32 (0);
1264     }
1265     while (command_do (dev, &cmd))
1266       schedule();
1267     // this link allows RX frames through
1268     dev->rxer[vci] = atm_vcc;
1269     up (&dev->vcc_sf);
1270   }
1271   
1272   // indicate readiness
1273   set_bit(ATM_VF_READY,&atm_vcc->flags);
1274   
1275   return 0;
1276 }
1277
1278 /********** Close a VC **********/
1279
1280 static void amb_close (struct atm_vcc * atm_vcc) {
1281   amb_dev * dev = AMB_DEV (atm_vcc->dev);
1282   amb_vcc * vcc = AMB_VCC (atm_vcc);
1283   u16 vci = atm_vcc->vci;
1284   
1285   PRINTD (DBG_VCC|DBG_FLOW, "amb_close");
1286   
1287   // indicate unreadiness
1288   clear_bit(ATM_VF_READY,&atm_vcc->flags);
1289   
1290   // disable TXing
1291   if (atm_vcc->qos.txtp.traffic_class != ATM_NONE) {
1292     command cmd;
1293     
1294     down (&dev->vcc_sf);
1295     if (dev->rxer[vci]) {
1296       // RXer still on the channel, just modify rate... XXX not really needed
1297       cmd.request = cpu_to_be32 (SRB_MODIFY_VC_RATE);
1298       cmd.args.modify_rate.vc = cpu_to_be32 (vci);  // vpi 0
1299       cmd.args.modify_rate.rate = cpu_to_be32 (0);
1300       // ... and clear TX rate flags (XXX to stop RM cell output?), preserving RX pool
1301     } else {
1302       // no RXer on the channel, close channel
1303       cmd.request = cpu_to_be32 (SRB_CLOSE_VC);
1304       cmd.args.close.vc = cpu_to_be32 (vci); // vpi 0
1305     }
1306     dev->txer[vci].tx_present = 0;
1307     while (command_do (dev, &cmd))
1308       schedule();
1309     up (&dev->vcc_sf);
1310   }
1311   
1312   // disable RXing
1313   if (atm_vcc->qos.rxtp.traffic_class != ATM_NONE) {
1314     command cmd;
1315     
1316     // this is (the?) one reason why we need the amb_vcc struct
1317     unsigned char pool = vcc->rx_info.pool;
1318     
1319     down (&dev->vcc_sf);
1320     if (dev->txer[vci].tx_present) {
1321       // TXer still on the channel, just go to pool zero XXX not really needed
1322       cmd.request = cpu_to_be32 (SRB_MODIFY_VC_FLAGS);
1323       cmd.args.modify_flags.vc = cpu_to_be32 (vci);  // vpi 0
1324       cmd.args.modify_flags.flags = cpu_to_be32
1325         (dev->txer[vci].tx_vc_bits << SRB_FLAGS_SHIFT);
1326     } else {
1327       // no TXer on the channel, close the VC
1328       cmd.request = cpu_to_be32 (SRB_CLOSE_VC);
1329       cmd.args.close.vc = cpu_to_be32 (vci); // vpi 0
1330     }
1331     // forget the rxer - no more skbs will be pushed
1332     if (atm_vcc != dev->rxer[vci])
1333       PRINTK (KERN_ERR, "%s vcc=%p rxer[vci]=%p",
1334               "arghhh! we're going to die!",
1335               vcc, dev->rxer[vci]);
1336     dev->rxer[vci] = 0;
1337     while (command_do (dev, &cmd))
1338       schedule();
1339     
1340     /* shrink RX buffer pool */
1341     dev->rxq[pool].buffers_wanted -= 1;
1342     if (dev->rxq[pool].buffers_wanted == rx_lats) {
1343       dev->rxq[pool].buffers_wanted = 0;
1344       drain_rx_pool (dev, pool);
1345     }
1346     up (&dev->vcc_sf);
1347   }
1348   
1349   // free our structure
1350   kfree (vcc);
1351   
1352   // say the VPI/VCI is free again
1353   clear_bit(ATM_VF_ADDR,&atm_vcc->flags);
1354
1355   return;
1356 }
1357
1358 /********** Set socket options for a VC **********/
1359
1360 // int amb_getsockopt (struct atm_vcc * atm_vcc, int level, int optname, void * optval, int optlen);
1361
1362 /********** Set socket options for a VC **********/
1363
1364 // int amb_setsockopt (struct atm_vcc * atm_vcc, int level, int optname, void * optval, int optlen);
1365
1366 /********** Send **********/
1367
1368 static int amb_send (struct atm_vcc * atm_vcc, struct sk_buff * skb) {
1369   amb_dev * dev = AMB_DEV(atm_vcc->dev);
1370   amb_vcc * vcc = AMB_VCC(atm_vcc);
1371   u16 vc = atm_vcc->vci;
1372   unsigned int tx_len = skb->len;
1373   unsigned char * tx_data = skb->data;
1374   tx_simple * tx_descr;
1375   tx_in tx;
1376   
1377   if (test_bit (dead, &dev->flags))
1378     return -EIO;
1379   
1380   PRINTD (DBG_FLOW|DBG_TX, "amb_send vc %x data %p len %u",
1381           vc, tx_data, tx_len);
1382   
1383   dump_skb (">>>", vc, skb);
1384   
1385   if (!dev->txer[vc].tx_present) {
1386     PRINTK (KERN_ERR, "attempt to send on RX-only VC %x", vc);
1387     return -EBADFD;
1388   }
1389   
1390   // this is a driver private field so we have to set it ourselves,
1391   // despite the fact that we are _required_ to use it to check for a
1392   // pop function
1393   ATM_SKB(skb)->vcc = atm_vcc;
1394   
1395   if (skb->len > (size_t) atm_vcc->qos.txtp.max_sdu) {
1396     PRINTK (KERN_ERR, "sk_buff length greater than agreed max_sdu, dropping...");
1397     return -EIO;
1398   }
1399   
1400   if (check_area (skb->data, skb->len)) {
1401     atomic_inc(&atm_vcc->stats->tx_err);
1402     return -ENOMEM; // ?
1403   }
1404   
1405   // allocate memory for fragments
1406   tx_descr = kmalloc (sizeof(tx_simple), GFP_KERNEL);
1407   if (!tx_descr) {
1408     PRINTK (KERN_ERR, "could not allocate TX descriptor");
1409     return -ENOMEM;
1410   }
1411   if (check_area (tx_descr, sizeof(tx_simple))) {
1412     kfree (tx_descr);
1413     return -ENOMEM;
1414   }
1415   PRINTD (DBG_TX, "fragment list allocated at %p", tx_descr);
1416   
1417   tx_descr->skb = skb;
1418   
1419   tx_descr->tx_frag.bytes = cpu_to_be32 (tx_len);
1420   tx_descr->tx_frag.address = cpu_to_be32 (virt_to_bus (tx_data));
1421   
1422   tx_descr->tx_frag_end.handle = virt_to_bus (tx_descr);
1423   tx_descr->tx_frag_end.vc = 0;
1424   tx_descr->tx_frag_end.next_descriptor_length = 0;
1425   tx_descr->tx_frag_end.next_descriptor = 0;
1426 #ifdef AMB_NEW_MICROCODE
1427   tx_descr->tx_frag_end.cpcs_uu = 0;
1428   tx_descr->tx_frag_end.cpi = 0;
1429   tx_descr->tx_frag_end.pad = 0;
1430 #endif
1431   
1432   tx.vc = cpu_to_be16 (vcc->tx_frame_bits | vc);
1433   tx.tx_descr_length = cpu_to_be16 (sizeof(tx_frag)+sizeof(tx_frag_end));
1434   tx.tx_descr_addr = cpu_to_be32 (virt_to_bus (&tx_descr->tx_frag));
1435   
1436   while (tx_give (dev, &tx))
1437     schedule();
1438   return 0;
1439 }
1440
1441 /********** Change QoS on a VC **********/
1442
1443 // int amb_change_qos (struct atm_vcc * atm_vcc, struct atm_qos * qos, int flags);
1444
1445 /********** Free RX Socket Buffer **********/
1446
1447 #if 0
1448 static void amb_free_rx_skb (struct atm_vcc * atm_vcc, struct sk_buff * skb) {
1449   amb_dev * dev = AMB_DEV (atm_vcc->dev);
1450   amb_vcc * vcc = AMB_VCC (atm_vcc);
1451   unsigned char pool = vcc->rx_info.pool;
1452   rx_in rx;
1453   
1454   // This may be unsafe for various reasons that I cannot really guess
1455   // at. However, I note that the ATM layer calls kfree_skb rather
1456   // than dev_kfree_skb at this point so we are least covered as far
1457   // as buffer locking goes. There may be bugs if pcap clones RX skbs.
1458
1459   PRINTD (DBG_FLOW|DBG_SKB, "amb_rx_free skb %p (atm_vcc %p, vcc %p)",
1460           skb, atm_vcc, vcc);
1461   
1462   rx.handle = virt_to_bus (skb);
1463   rx.host_address = cpu_to_be32 (virt_to_bus (skb->data));
1464   
1465   skb->data = skb->head;
1466   skb->tail = skb->head;
1467   skb->len = 0;
1468   
1469   if (!rx_give (dev, &rx, pool)) {
1470     // success
1471     PRINTD (DBG_SKB|DBG_POOL, "recycled skb for pool %hu", pool);
1472     return;
1473   }
1474   
1475   // just do what the ATM layer would have done
1476   dev_kfree_skb_any (skb);
1477   
1478   return;
1479 }
1480 #endif
1481
1482 /********** Proc File Output **********/
1483
1484 static int amb_proc_read (struct atm_dev * atm_dev, loff_t * pos, char * page) {
1485   amb_dev * dev = AMB_DEV (atm_dev);
1486   int left = *pos;
1487   unsigned char pool;
1488   
1489   PRINTD (DBG_FLOW, "amb_proc_read");
1490   
1491   /* more diagnostics here? */
1492   
1493   if (!left--) {
1494     amb_stats * s = &dev->stats;
1495     return sprintf (page,
1496                     "frames: TX OK %lu, RX OK %lu, RX bad %lu "
1497                     "(CRC %lu, long %lu, aborted %lu, unused %lu).\n",
1498                     s->tx_ok, s->rx.ok, s->rx.error,
1499                     s->rx.badcrc, s->rx.toolong,
1500                     s->rx.aborted, s->rx.unused);
1501   }
1502   
1503   if (!left--) {
1504     amb_cq * c = &dev->cq;
1505     return sprintf (page, "cmd queue [cur/hi/max]: %u/%u/%u. ",
1506                     c->pending, c->high, c->maximum);
1507   }
1508   
1509   if (!left--) {
1510     amb_txq * t = &dev->txq;
1511     return sprintf (page, "TX queue [cur/max high full]: %u/%u %u %u.\n",
1512                     t->pending, t->maximum, t->high, t->filled);
1513   }
1514   
1515   if (!left--) {
1516     unsigned int count = sprintf (page, "RX queues [cur/max/req low empty]:");
1517     for (pool = 0; pool < NUM_RX_POOLS; ++pool) {
1518       amb_rxq * r = &dev->rxq[pool];
1519       count += sprintf (page+count, " %u/%u/%u %u %u",
1520                         r->pending, r->maximum, r->buffers_wanted, r->low, r->emptied);
1521     }
1522     count += sprintf (page+count, ".\n");
1523     return count;
1524   }
1525   
1526   if (!left--) {
1527     unsigned int count = sprintf (page, "RX buffer sizes:");
1528     for (pool = 0; pool < NUM_RX_POOLS; ++pool) {
1529       amb_rxq * r = &dev->rxq[pool];
1530       count += sprintf (page+count, " %u", r->buffer_size);
1531     }
1532     count += sprintf (page+count, ".\n");
1533     return count;
1534   }
1535   
1536 #if 0
1537   if (!left--) {
1538     // suni block etc?
1539   }
1540 #endif
1541   
1542   return 0;
1543 }
1544
1545 /********** Operation Structure **********/
1546
1547 static const struct atmdev_ops amb_ops = {
1548   .open         = amb_open,
1549   .close        = amb_close,
1550   .send         = amb_send,
1551   .proc_read    = amb_proc_read,
1552   .owner        = THIS_MODULE,
1553 };
1554
1555 /********** housekeeping **********/
1556 static void do_housekeeping (unsigned long arg) {
1557   amb_dev * dev = amb_devs;
1558   // data is set to zero at module unload
1559   (void) arg;
1560   
1561   if (housekeeping.data) {
1562     while (dev) {
1563       
1564       // could collect device-specific (not driver/atm-linux) stats here
1565       
1566       // last resort refill once every ten seconds
1567       fill_rx_pools (dev);
1568       
1569       dev = dev->prev;
1570     }
1571     mod_timer(&housekeeping, jiffies + 10*HZ);
1572   }
1573   
1574   return;
1575 }
1576
1577 /********** creation of communication queues **********/
1578
1579 static int __init create_queues (amb_dev * dev, unsigned int cmds,
1580                                  unsigned int txs, unsigned int * rxs,
1581                                  unsigned int * rx_buffer_sizes) {
1582   unsigned char pool;
1583   size_t total = 0;
1584   void * memory;
1585   void * limit;
1586   
1587   PRINTD (DBG_FLOW, "create_queues %p", dev);
1588   
1589   total += cmds * sizeof(command);
1590   
1591   total += txs * (sizeof(tx_in) + sizeof(tx_out));
1592   
1593   for (pool = 0; pool < NUM_RX_POOLS; ++pool)
1594     total += rxs[pool] * (sizeof(rx_in) + sizeof(rx_out));
1595   
1596   memory = kmalloc (total, GFP_KERNEL);
1597   if (!memory) {
1598     PRINTK (KERN_ERR, "could not allocate queues");
1599     return -ENOMEM;
1600   }
1601   if (check_area (memory, total)) {
1602     PRINTK (KERN_ERR, "queues allocated in nasty area");
1603     kfree (memory);
1604     return -ENOMEM;
1605   }
1606   
1607   limit = memory + total;
1608   PRINTD (DBG_INIT, "queues from %p to %p", memory, limit);
1609   
1610   PRINTD (DBG_CMD, "command queue at %p", memory);
1611   
1612   {
1613     command * cmd = memory;
1614     amb_cq * cq = &dev->cq;
1615     
1616     cq->pending = 0;
1617     cq->high = 0;
1618     cq->maximum = cmds - 1;
1619     
1620     cq->ptrs.start = cmd;
1621     cq->ptrs.in = cmd;
1622     cq->ptrs.out = cmd;
1623     cq->ptrs.limit = cmd + cmds;
1624     
1625     memory = cq->ptrs.limit;
1626   }
1627   
1628   PRINTD (DBG_TX, "TX queue pair at %p", memory);
1629   
1630   {
1631     tx_in * in = memory;
1632     tx_out * out;
1633     amb_txq * txq = &dev->txq;
1634     
1635     txq->pending = 0;
1636     txq->high = 0;
1637     txq->filled = 0;
1638     txq->maximum = txs - 1;
1639     
1640     txq->in.start = in;
1641     txq->in.ptr = in;
1642     txq->in.limit = in + txs;
1643     
1644     memory = txq->in.limit;
1645     out = memory;
1646     
1647     txq->out.start = out;
1648     txq->out.ptr = out;
1649     txq->out.limit = out + txs;
1650     
1651     memory = txq->out.limit;
1652   }
1653   
1654   PRINTD (DBG_RX, "RX queue pairs at %p", memory);
1655   
1656   for (pool = 0; pool < NUM_RX_POOLS; ++pool) {
1657     rx_in * in = memory;
1658     rx_out * out;
1659     amb_rxq * rxq = &dev->rxq[pool];
1660     
1661     rxq->buffer_size = rx_buffer_sizes[pool];
1662     rxq->buffers_wanted = 0;
1663     
1664     rxq->pending = 0;
1665     rxq->low = rxs[pool] - 1;
1666     rxq->emptied = 0;
1667     rxq->maximum = rxs[pool] - 1;
1668     
1669     rxq->in.start = in;
1670     rxq->in.ptr = in;
1671     rxq->in.limit = in + rxs[pool];
1672     
1673     memory = rxq->in.limit;
1674     out = memory;
1675     
1676     rxq->out.start = out;
1677     rxq->out.ptr = out;
1678     rxq->out.limit = out + rxs[pool];
1679     
1680     memory = rxq->out.limit;
1681   }
1682   
1683   if (memory == limit) {
1684     return 0;
1685   } else {
1686     PRINTK (KERN_ERR, "bad queue alloc %p != %p (tell maintainer)", memory, limit);
1687     kfree (limit - total);
1688     return -ENOMEM;
1689   }
1690   
1691 }
1692
1693 /********** destruction of communication queues **********/
1694
1695 static void destroy_queues (amb_dev * dev) {
1696   // all queues assumed empty
1697   void * memory = dev->cq.ptrs.start;
1698   // includes txq.in, txq.out, rxq[].in and rxq[].out
1699   
1700   PRINTD (DBG_FLOW, "destroy_queues %p", dev);
1701   
1702   PRINTD (DBG_INIT, "freeing queues at %p", memory);
1703   kfree (memory);
1704   
1705   return;
1706 }
1707
1708 /********** basic loader commands and error handling **********/
1709
1710 static int __init do_loader_command (volatile loader_block * lb,
1711                                      const amb_dev * dev, loader_command cmd) {
1712   // centisecond timeouts - guessing away here
1713   unsigned int command_timeouts [] = {
1714     [host_memory_test]     = 15,
1715     [read_adapter_memory]  = 2,
1716     [write_adapter_memory] = 2,
1717     [adapter_start]        = 50,
1718     [get_version_number]   = 10,
1719     [interrupt_host]       = 1,
1720     [flash_erase_sector]   = 1,
1721     [adap_download_block]  = 1,
1722     [adap_erase_flash]     = 1,
1723     [adap_run_in_iram]     = 1,
1724     [adap_end_download]    = 1
1725   };
1726   
1727   unsigned int command_successes [] = {
1728     [host_memory_test]     = COMMAND_PASSED_TEST,
1729     [read_adapter_memory]  = COMMAND_READ_DATA_OK,
1730     [write_adapter_memory] = COMMAND_WRITE_DATA_OK,
1731     [adapter_start]        = COMMAND_COMPLETE,
1732     [get_version_number]   = COMMAND_COMPLETE,
1733     [interrupt_host]       = COMMAND_COMPLETE,
1734     [flash_erase_sector]   = COMMAND_COMPLETE,
1735     [adap_download_block]  = COMMAND_COMPLETE,
1736     [adap_erase_flash]     = COMMAND_COMPLETE,
1737     [adap_run_in_iram]     = COMMAND_COMPLETE,
1738     [adap_end_download]    = COMMAND_COMPLETE
1739   };
1740   
1741   int decode_loader_result (loader_command cmd, u32 result) {
1742     int res;
1743     const char * msg;
1744     
1745     if (result == command_successes[cmd])
1746       return 0;
1747     
1748     switch (result) {
1749       case BAD_COMMAND:
1750         res = -EINVAL;
1751         msg = "bad command";
1752         break;
1753       case COMMAND_IN_PROGRESS:
1754         res = -ETIMEDOUT;
1755         msg = "command in progress";
1756         break;
1757       case COMMAND_PASSED_TEST:
1758         res = 0;
1759         msg = "command passed test";
1760         break;
1761       case COMMAND_FAILED_TEST:
1762         res = -EIO;
1763         msg = "command failed test";
1764         break;
1765       case COMMAND_READ_DATA_OK:
1766         res = 0;
1767         msg = "command read data ok";
1768         break;
1769       case COMMAND_READ_BAD_ADDRESS:
1770         res = -EINVAL;
1771         msg = "command read bad address";
1772         break;
1773       case COMMAND_WRITE_DATA_OK:
1774         res = 0;
1775         msg = "command write data ok";
1776         break;
1777       case COMMAND_WRITE_BAD_ADDRESS:
1778         res = -EINVAL;
1779         msg = "command write bad address";
1780         break;
1781       case COMMAND_WRITE_FLASH_FAILURE:
1782         res = -EIO;
1783         msg = "command write flash failure";
1784         break;
1785       case COMMAND_COMPLETE:
1786         res = 0;
1787         msg = "command complete";
1788         break;
1789       case COMMAND_FLASH_ERASE_FAILURE:
1790         res = -EIO;
1791         msg = "command flash erase failure";
1792         break;
1793       case COMMAND_WRITE_BAD_DATA:
1794         res = -EINVAL;
1795         msg = "command write bad data";
1796         break;
1797       default:
1798         res = -EINVAL;
1799         msg = "unknown error";
1800         PRINTD (DBG_LOAD|DBG_ERR, "decode_loader_result got %d=%x !",
1801                 result, result);
1802         break;
1803     }
1804     
1805     PRINTK (KERN_ERR, "%s", msg);
1806     return res;
1807   }
1808   
1809   unsigned long timeout;
1810   
1811   PRINTD (DBG_FLOW|DBG_LOAD, "do_loader_command");
1812   
1813   /* do a command
1814      
1815      Set the return value to zero, set the command type and set the
1816      valid entry to the right magic value. The payload is already
1817      correctly byte-ordered so we leave it alone. Hit the doorbell
1818      with the bus address of this structure.
1819      
1820   */
1821   
1822   lb->result = 0;
1823   lb->command = cpu_to_be32 (cmd);
1824   lb->valid = cpu_to_be32 (DMA_VALID);
1825   // dump_registers (dev);
1826   // dump_loader_block (lb);
1827   wr_mem (dev, offsetof(amb_mem, doorbell), virt_to_bus (lb) & ~onegigmask);
1828   
1829   timeout = command_timeouts[cmd] * HZ/100;
1830   
1831   while (!lb->result || lb->result == cpu_to_be32 (COMMAND_IN_PROGRESS))
1832     if (timeout) {
1833       set_current_state(TASK_UNINTERRUPTIBLE);
1834       timeout = schedule_timeout (timeout);
1835     } else {
1836       PRINTD (DBG_LOAD|DBG_ERR, "command %d timed out", cmd);
1837       dump_registers (dev);
1838       dump_loader_block (lb);
1839       return -ETIMEDOUT;
1840     }
1841   
1842   if (cmd == adapter_start) {
1843     // wait for start command to acknowledge...
1844     timeout = HZ/10;
1845     while (rd_plain (dev, offsetof(amb_mem, doorbell)))
1846       if (timeout) {
1847         timeout = schedule_timeout (timeout);
1848       } else {
1849         PRINTD (DBG_LOAD|DBG_ERR, "start command did not clear doorbell, res=%08x",
1850                 be32_to_cpu (lb->result));
1851         dump_registers (dev);
1852         return -ETIMEDOUT;
1853       }
1854     return 0;
1855   } else {
1856     return decode_loader_result (cmd, be32_to_cpu (lb->result));
1857   }
1858   
1859 }
1860
1861 /* loader: determine loader version */
1862
1863 static int __init get_loader_version (loader_block * lb,
1864                                       const amb_dev * dev, u32 * version) {
1865   int res;
1866   
1867   PRINTD (DBG_FLOW|DBG_LOAD, "get_loader_version");
1868   
1869   res = do_loader_command (lb, dev, get_version_number);
1870   if (res)
1871     return res;
1872   if (version)
1873     *version = be32_to_cpu (lb->payload.version);
1874   return 0;
1875 }
1876
1877 /* loader: write memory data blocks */
1878
1879 static int __init loader_write (loader_block * lb,
1880                                 const amb_dev * dev, const u32 * data,
1881                                 u32 address, unsigned int count) {
1882   unsigned int i;
1883   transfer_block * tb = &lb->payload.transfer;
1884   
1885   PRINTD (DBG_FLOW|DBG_LOAD, "loader_write");
1886   
1887   if (count > MAX_TRANSFER_DATA)
1888     return -EINVAL;
1889   tb->address = cpu_to_be32 (address);
1890   tb->count = cpu_to_be32 (count);
1891   for (i = 0; i < count; ++i)
1892     tb->data[i] = cpu_to_be32 (data[i]);
1893   return do_loader_command (lb, dev, write_adapter_memory);
1894 }
1895
1896 /* loader: verify memory data blocks */
1897
1898 static int __init loader_verify (loader_block * lb,
1899                                  const amb_dev * dev, const u32 * data,
1900                                  u32 address, unsigned int count) {
1901   unsigned int i;
1902   transfer_block * tb = &lb->payload.transfer;
1903   int res;
1904   
1905   PRINTD (DBG_FLOW|DBG_LOAD, "loader_verify");
1906   
1907   if (count > MAX_TRANSFER_DATA)
1908     return -EINVAL;
1909   tb->address = cpu_to_be32 (address);
1910   tb->count = cpu_to_be32 (count);
1911   res = do_loader_command (lb, dev, read_adapter_memory);
1912   if (!res)
1913     for (i = 0; i < count; ++i)
1914       if (tb->data[i] != cpu_to_be32 (data[i])) {
1915         res = -EINVAL;
1916         break;
1917       }
1918   return res;
1919 }
1920
1921 /* loader: start microcode */
1922
1923 static int __init loader_start (loader_block * lb,
1924                                 const amb_dev * dev, u32 address) {
1925   PRINTD (DBG_FLOW|DBG_LOAD, "loader_start");
1926   
1927   lb->payload.start = cpu_to_be32 (address);
1928   return do_loader_command (lb, dev, adapter_start);
1929 }
1930
1931 /********** reset card **********/
1932
1933 static int amb_reset (amb_dev * dev, int diags) {
1934   u32 word;
1935   
1936   PRINTD (DBG_FLOW|DBG_LOAD, "amb_reset");
1937   
1938   word = rd_plain (dev, offsetof(amb_mem, reset_control));
1939   // put card into reset state
1940   wr_plain (dev, offsetof(amb_mem, reset_control), word | AMB_RESET_BITS);
1941   // wait a short while
1942   udelay (10);
1943 #if 1
1944   // put card into known good state
1945   wr_plain (dev, offsetof(amb_mem, interrupt_control), AMB_DOORBELL_BITS);
1946   // clear all interrupts just in case
1947   wr_plain (dev, offsetof(amb_mem, interrupt), -1);
1948 #endif
1949   // clear self-test done flag
1950   wr_plain (dev, offsetof(amb_mem, mb.loader.ready), 0);
1951   // take card out of reset state
1952   wr_plain (dev, offsetof(amb_mem, reset_control), word &~ AMB_RESET_BITS);
1953   
1954   if (diags) { 
1955     unsigned long timeout;
1956     // 4.2 second wait
1957     timeout = HZ*42/10;
1958     while (timeout) {
1959       set_current_state(TASK_UNINTERRUPTIBLE);
1960       timeout = schedule_timeout (timeout);
1961     }
1962     // half second time-out
1963     timeout = HZ/2;
1964     while (!rd_plain (dev, offsetof(amb_mem, mb.loader.ready)))
1965       if (timeout) {
1966         set_current_state(TASK_UNINTERRUPTIBLE);
1967         timeout = schedule_timeout (timeout);
1968       } else {
1969         PRINTD (DBG_LOAD|DBG_ERR, "reset timed out");
1970         return -ETIMEDOUT;
1971       }
1972     
1973     // get results of self-test
1974     // XXX double check byte-order
1975     word = rd_mem (dev, offsetof(amb_mem, mb.loader.result));
1976     if (word & SELF_TEST_FAILURE) {
1977       void sf (const char * msg) {
1978         PRINTK (KERN_ERR, "self-test failed: %s", msg);
1979       }
1980       if (word & GPINT_TST_FAILURE)
1981         sf ("interrupt");
1982       if (word & SUNI_DATA_PATTERN_FAILURE)
1983         sf ("SUNI data pattern");
1984       if (word & SUNI_DATA_BITS_FAILURE)
1985         sf ("SUNI data bits");
1986       if (word & SUNI_UTOPIA_FAILURE)
1987         sf ("SUNI UTOPIA interface");
1988       if (word & SUNI_FIFO_FAILURE)
1989         sf ("SUNI cell buffer FIFO");
1990       if (word & SRAM_FAILURE)
1991         sf ("bad SRAM");
1992       // better return value?
1993       return -EIO;
1994     }
1995     
1996   }
1997   return 0;
1998 }
1999
2000 /********** transfer and start the microcode **********/
2001
2002 static int __init ucode_init (loader_block * lb, amb_dev * dev) {
2003   unsigned int i = 0;
2004   unsigned int total = 0;
2005   const u32 * pointer = ucode_data;
2006   u32 address;
2007   unsigned int count;
2008   int res;
2009   
2010   PRINTD (DBG_FLOW|DBG_LOAD, "ucode_init");
2011   
2012   while (address = ucode_regions[i].start,
2013          count = ucode_regions[i].count) {
2014     PRINTD (DBG_LOAD, "starting region (%x, %u)", address, count);
2015     while (count) {
2016       unsigned int words;
2017       if (count <= MAX_TRANSFER_DATA)
2018         words = count;
2019       else
2020         words = MAX_TRANSFER_DATA;
2021       total += words;
2022       res = loader_write (lb, dev, pointer, address, words);
2023       if (res)
2024         return res;
2025       res = loader_verify (lb, dev, pointer, address, words);
2026       if (res)
2027         return res;
2028       count -= words;
2029       address += sizeof(u32) * words;
2030       pointer += words;
2031     }
2032     i += 1;
2033   }
2034   if (*pointer == 0xdeadbeef) {
2035     return loader_start (lb, dev, ucode_start);
2036   } else {
2037     // cast needed as there is no %? for pointer differnces
2038     PRINTD (DBG_LOAD|DBG_ERR,
2039             "offset=%li, *pointer=%x, address=%x, total=%u",
2040             (long) (pointer - ucode_data), *pointer, address, total);
2041     PRINTK (KERN_ERR, "incorrect microcode data");
2042     return -ENOMEM;
2043   }
2044 }
2045
2046 /********** give adapter parameters **********/
2047
2048 static int __init amb_talk (amb_dev * dev) {
2049   adap_talk_block a;
2050   unsigned char pool;
2051   unsigned long timeout;
2052   
2053   u32 x (void * addr) {
2054     return cpu_to_be32 (virt_to_bus (addr));
2055   }
2056   
2057   PRINTD (DBG_FLOW, "amb_talk %p", dev);
2058   
2059   a.command_start = x (dev->cq.ptrs.start);
2060   a.command_end   = x (dev->cq.ptrs.limit);
2061   a.tx_start      = x (dev->txq.in.start);
2062   a.tx_end        = x (dev->txq.in.limit);
2063   a.txcom_start   = x (dev->txq.out.start);
2064   a.txcom_end     = x (dev->txq.out.limit);
2065   
2066   for (pool = 0; pool < NUM_RX_POOLS; ++pool) {
2067     // the other "a" items are set up by the adapter
2068     a.rec_struct[pool].buffer_start = x (dev->rxq[pool].in.start);
2069     a.rec_struct[pool].buffer_end   = x (dev->rxq[pool].in.limit);
2070     a.rec_struct[pool].rx_start     = x (dev->rxq[pool].out.start);
2071     a.rec_struct[pool].rx_end       = x (dev->rxq[pool].out.limit);
2072     a.rec_struct[pool].buffer_size = cpu_to_be32 (dev->rxq[pool].buffer_size);
2073   }
2074   
2075 #ifdef AMB_NEW_MICROCODE
2076   // disable fast PLX prefetching
2077   a.init_flags = 0;
2078 #endif
2079   
2080   // pass the structure
2081   wr_mem (dev, offsetof(amb_mem, doorbell), virt_to_bus (&a));
2082   
2083   // 2.2 second wait (must not touch doorbell during 2 second DMA test)
2084   timeout = HZ*22/10;
2085   while (timeout)
2086     timeout = schedule_timeout (timeout);
2087   // give the adapter another half second?
2088   timeout = HZ/2;
2089   while (rd_plain (dev, offsetof(amb_mem, doorbell)))
2090     if (timeout) {
2091       timeout = schedule_timeout (timeout);
2092     } else {
2093       PRINTD (DBG_INIT|DBG_ERR, "adapter init timed out");
2094       return -ETIMEDOUT;
2095     }
2096   
2097   return 0;
2098 }
2099
2100 // get microcode version
2101 static void __init amb_ucode_version (amb_dev * dev) {
2102   u32 major;
2103   u32 minor;
2104   command cmd;
2105   cmd.request = cpu_to_be32 (SRB_GET_VERSION);
2106   while (command_do (dev, &cmd)) {
2107     set_current_state(TASK_UNINTERRUPTIBLE);
2108     schedule();
2109   }
2110   major = be32_to_cpu (cmd.args.version.major);
2111   minor = be32_to_cpu (cmd.args.version.minor);
2112   PRINTK (KERN_INFO, "microcode version is %u.%u", major, minor);
2113 }
2114
2115 // get end station address
2116 static void __init amb_esi (amb_dev * dev, u8 * esi) {
2117   u32 lower4;
2118   u16 upper2;
2119   command cmd;
2120   
2121   // swap bits within byte to get Ethernet ordering
2122   u8 bit_swap (u8 byte) {
2123     const u8 swap[] = {
2124       0x0, 0x8, 0x4, 0xc,
2125       0x2, 0xa, 0x6, 0xe,
2126       0x1, 0x9, 0x5, 0xd,
2127       0x3, 0xb, 0x7, 0xf
2128     };
2129     return ((swap[byte & 0xf]<<4) | swap[byte>>4]);
2130   }
2131   
2132   cmd.request = cpu_to_be32 (SRB_GET_BIA);
2133   while (command_do (dev, &cmd)) {
2134     set_current_state(TASK_UNINTERRUPTIBLE);
2135     schedule();
2136   }
2137   lower4 = be32_to_cpu (cmd.args.bia.lower4);
2138   upper2 = be32_to_cpu (cmd.args.bia.upper2);
2139   PRINTD (DBG_LOAD, "BIA: lower4: %08x, upper2 %04x", lower4, upper2);
2140   
2141   if (esi) {
2142     unsigned int i;
2143     
2144     PRINTDB (DBG_INIT, "ESI:");
2145     for (i = 0; i < ESI_LEN; ++i) {
2146       if (i < 4)
2147           esi[i] = bit_swap (lower4>>(8*i));
2148       else
2149           esi[i] = bit_swap (upper2>>(8*(i-4)));
2150       PRINTDM (DBG_INIT, " %02x", esi[i]);
2151     }
2152     
2153     PRINTDE (DBG_INIT, "");
2154   }
2155   
2156   return;
2157 }
2158
2159 static int __init amb_init (amb_dev * dev) {
2160   loader_block lb;
2161   
2162   void fixup_plx_window (void) {
2163     // fix up the PLX-mapped window base address to match the block
2164     unsigned long blb;
2165     u32 mapreg;
2166     blb = virt_to_bus (&lb);
2167     // the kernel stack had better not ever cross a 1Gb boundary!
2168     mapreg = rd_plain (dev, offsetof(amb_mem, stuff[10]));
2169     mapreg &= ~onegigmask;
2170     mapreg |= blb & onegigmask;
2171     wr_plain (dev, offsetof(amb_mem, stuff[10]), mapreg);
2172     return;
2173   }
2174   
2175   u32 version;
2176   
2177   if (amb_reset (dev, 1)) {
2178     PRINTK (KERN_ERR, "card reset failed!");
2179   } else {
2180     fixup_plx_window ();
2181     
2182     if (get_loader_version (&lb, dev, &version)) {
2183       PRINTK (KERN_INFO, "failed to get loader version");
2184     } else {
2185       PRINTK (KERN_INFO, "loader version is %08x", version);
2186       
2187       if (ucode_init (&lb, dev)) {
2188         PRINTK (KERN_ERR, "microcode failure");
2189       } else if (create_queues (dev, cmds, txs, rxs, rxs_bs)) {
2190         PRINTK (KERN_ERR, "failed to get memory for queues");
2191       } else {
2192         
2193         if (amb_talk (dev)) {
2194           PRINTK (KERN_ERR, "adapter did not accept queues");
2195         } else {
2196           
2197           amb_ucode_version (dev);
2198           return 0;
2199           
2200         } /* amb_talk */
2201         
2202         destroy_queues (dev);
2203       } /* create_queues, ucode_init */
2204       
2205       amb_reset (dev, 0);
2206     } /* get_loader_version */
2207     
2208   } /* amb_reset */
2209   
2210   return -1;
2211 }
2212
2213 static int __init amb_probe (void) {
2214   struct pci_dev * pci_dev;
2215   int devs;
2216   
2217   void __init do_pci_device (void) {
2218     amb_dev * dev;
2219     
2220     // read resources from PCI configuration space
2221     u8 irq = pci_dev->irq;
2222     u32 * membase = bus_to_virt (pci_resource_start (pci_dev, 0));
2223     u32 iobase = pci_resource_start (pci_dev, 1);
2224     
2225     void setup_dev (void) {
2226       unsigned char pool;
2227       memset (dev, 0, sizeof(amb_dev));
2228       
2229       // set up known dev items straight away
2230       dev->pci_dev = pci_dev; 
2231       
2232       dev->iobase = iobase;
2233       dev->irq = irq; 
2234       dev->membase = membase;
2235       
2236       // flags (currently only dead)
2237       dev->flags = 0;
2238       
2239       // Allocate cell rates (fibre)
2240       // ATM_OC3_PCR = 1555200000/8/270*260/53 - 29/53
2241       // to be really pedantic, this should be ATM_OC3c_PCR
2242       dev->tx_avail = ATM_OC3_PCR;
2243       dev->rx_avail = ATM_OC3_PCR;
2244       
2245 #ifdef FILL_RX_POOLS_IN_BH
2246       // initialise bottom half
2247       INIT_WORK(&dev->bh, (void (*)(void *)) fill_rx_pools, dev);
2248 #endif
2249       
2250       // semaphore for txer/rxer modifications - we cannot use a
2251       // spinlock as the critical region needs to switch processes
2252       init_MUTEX (&dev->vcc_sf);
2253       // queue manipulation spinlocks; we want atomic reads and
2254       // writes to the queue descriptors (handles IRQ and SMP)
2255       // consider replacing "int pending" -> "atomic_t available"
2256       // => problem related to who gets to move queue pointers
2257       spin_lock_init (&dev->cq.lock);
2258       spin_lock_init (&dev->txq.lock);
2259       for (pool = 0; pool < NUM_RX_POOLS; ++pool)
2260         spin_lock_init (&dev->rxq[pool].lock);
2261     }
2262     
2263     void setup_pci_dev (void) {
2264       unsigned char lat;
2265       
2266       /* XXX check return value */
2267       pci_enable_device (pci_dev);
2268
2269       // enable bus master accesses
2270       pci_set_master (pci_dev);
2271       
2272       // frobnicate latency (upwards, usually)
2273       pci_read_config_byte (pci_dev, PCI_LATENCY_TIMER, &lat);
2274       if (pci_lat) {
2275         PRINTD (DBG_INIT, "%s PCI latency timer from %hu to %hu",
2276                 "changing", lat, pci_lat);
2277         pci_write_config_byte (pci_dev, PCI_LATENCY_TIMER, pci_lat);
2278       } else if (lat < MIN_PCI_LATENCY) {
2279         PRINTK (KERN_INFO, "%s PCI latency timer from %hu to %hu",
2280                 "increasing", lat, MIN_PCI_LATENCY);
2281         pci_write_config_byte (pci_dev, PCI_LATENCY_TIMER, MIN_PCI_LATENCY);
2282       }
2283     }
2284     
2285     PRINTD (DBG_INFO, "found Madge ATM adapter (amb) at"
2286             " IO %x, IRQ %u, MEM %p", iobase, irq, membase);
2287     
2288     // check IO region
2289     if (!request_region (iobase, AMB_EXTENT, DEV_LABEL)) {
2290       PRINTK (KERN_ERR, "IO range already in use!");
2291       return;
2292     }
2293     
2294     dev = kmalloc (sizeof(amb_dev), GFP_KERNEL);
2295     if (!dev) {
2296       // perhaps we should be nice: deregister all adapters and abort?
2297       PRINTK (KERN_ERR, "out of memory!");
2298       release_region (iobase, AMB_EXTENT);
2299       return;
2300     }
2301     
2302     setup_dev();
2303     
2304     if (amb_init (dev)) {
2305       PRINTK (KERN_ERR, "adapter initialisation failure");
2306     } else {
2307       
2308       setup_pci_dev();
2309       
2310       // grab (but share) IRQ and install handler
2311       if (request_irq (irq, interrupt_handler, SA_SHIRQ, DEV_LABEL, dev)) {
2312         PRINTK (KERN_ERR, "request IRQ failed!");
2313         // free_irq is at "endif"
2314       } else {
2315         
2316         dev->atm_dev = atm_dev_register (DEV_LABEL, &amb_ops, -1, NULL);
2317         if (!dev->atm_dev) {
2318           PRINTD (DBG_ERR, "failed to register Madge ATM adapter");
2319         } else {
2320           
2321           PRINTD (DBG_INFO, "registered Madge ATM adapter (no. %d) (%p) at %p",
2322                   dev->atm_dev->number, dev, dev->atm_dev);
2323           dev->atm_dev->dev_data = (void *) dev;
2324           
2325           // register our address
2326           amb_esi (dev, dev->atm_dev->esi);
2327           
2328           // 0 bits for vpi, 10 bits for vci
2329           dev->atm_dev->ci_range.vpi_bits = NUM_VPI_BITS;
2330           dev->atm_dev->ci_range.vci_bits = NUM_VCI_BITS;
2331           
2332           // update count and linked list
2333           ++devs;
2334           dev->prev = amb_devs;
2335           amb_devs = dev;
2336           
2337           // enable host interrupts
2338           interrupts_on (dev);
2339           
2340           // success
2341           return;
2342           
2343           // not currently reached
2344           atm_dev_deregister (dev->atm_dev);
2345         } /* atm_dev_register */
2346         
2347         free_irq (irq, dev);
2348       } /* request_irq */
2349       
2350       amb_reset (dev, 0);
2351     } /* amb_init */
2352     
2353     kfree (dev);
2354     release_region (iobase, AMB_EXTENT);
2355   } /* kmalloc, end-of-fn */
2356   
2357   PRINTD (DBG_FLOW, "amb_probe");
2358   
2359   devs = 0;
2360   pci_dev = NULL;
2361   while ((pci_dev = pci_find_device
2362           (PCI_VENDOR_ID_MADGE, PCI_DEVICE_ID_MADGE_AMBASSADOR, pci_dev)
2363           ))
2364     do_pci_device();
2365   
2366   pci_dev = NULL;
2367   while ((pci_dev = pci_find_device
2368           (PCI_VENDOR_ID_MADGE, PCI_DEVICE_ID_MADGE_AMBASSADOR_BAD, pci_dev)
2369           ))
2370     PRINTK (KERN_ERR, "skipped broken (PLX rev 2) card");
2371   
2372   return devs;
2373 }
2374
2375 static void __init amb_check_args (void) {
2376   unsigned char pool;
2377   unsigned int max_rx_size;
2378   
2379 #ifdef DEBUG_AMBASSADOR
2380   PRINTK (KERN_NOTICE, "debug bitmap is %hx", debug &= DBG_MASK);
2381 #else
2382   if (debug)
2383     PRINTK (KERN_NOTICE, "no debugging support");
2384 #endif
2385   
2386   if (cmds < MIN_QUEUE_SIZE)
2387     PRINTK (KERN_NOTICE, "cmds has been raised to %u",
2388             cmds = MIN_QUEUE_SIZE);
2389   
2390   if (txs < MIN_QUEUE_SIZE)
2391     PRINTK (KERN_NOTICE, "txs has been raised to %u",
2392             txs = MIN_QUEUE_SIZE);
2393   
2394   for (pool = 0; pool < NUM_RX_POOLS; ++pool)
2395     if (rxs[pool] < MIN_QUEUE_SIZE)
2396       PRINTK (KERN_NOTICE, "rxs[%hu] has been raised to %u",
2397               pool, rxs[pool] = MIN_QUEUE_SIZE);
2398   
2399   // buffers sizes should be greater than zero and strictly increasing
2400   max_rx_size = 0;
2401   for (pool = 0; pool < NUM_RX_POOLS; ++pool)
2402     if (rxs_bs[pool] <= max_rx_size)
2403       PRINTK (KERN_NOTICE, "useless pool (rxs_bs[%hu] = %u)",
2404               pool, rxs_bs[pool]);
2405     else
2406       max_rx_size = rxs_bs[pool];
2407   
2408   if (rx_lats < MIN_RX_BUFFERS)
2409     PRINTK (KERN_NOTICE, "rx_lats has been raised to %u",
2410             rx_lats = MIN_RX_BUFFERS);
2411   
2412   return;
2413 }
2414
2415 /********** module stuff **********/
2416
2417 MODULE_AUTHOR(maintainer_string);
2418 MODULE_DESCRIPTION(description_string);
2419 MODULE_LICENSE("GPL");
2420 MODULE_PARM(debug,   "h");
2421 MODULE_PARM(cmds,    "i");
2422 MODULE_PARM(txs,     "i");
2423 MODULE_PARM(rxs,     __MODULE_STRING(NUM_RX_POOLS) "i");
2424 MODULE_PARM(rxs_bs,  __MODULE_STRING(NUM_RX_POOLS) "i");
2425 MODULE_PARM(rx_lats, "i");
2426 MODULE_PARM(pci_lat, "b");
2427 MODULE_PARM_DESC(debug,   "debug bitmap, see .h file");
2428 MODULE_PARM_DESC(cmds,    "number of command queue entries");
2429 MODULE_PARM_DESC(txs,     "number of TX queue entries");
2430 MODULE_PARM_DESC(rxs,     "number of RX queue entries [" __MODULE_STRING(NUM_RX_POOLS) "]");
2431 MODULE_PARM_DESC(rxs_bs,  "size of RX buffers [" __MODULE_STRING(NUM_RX_POOLS) "]");
2432 MODULE_PARM_DESC(rx_lats, "number of extra buffers to cope with RX latencies");
2433 MODULE_PARM_DESC(pci_lat, "PCI latency in bus cycles");
2434
2435 /********** module entry **********/
2436
2437 static int __init amb_module_init (void) {
2438   int devs;
2439   
2440   PRINTD (DBG_FLOW|DBG_INIT, "init_module");
2441   
2442   // sanity check - cast needed as printk does not support %Zu
2443   if (sizeof(amb_mem) != 4*16 + 4*12) {
2444     PRINTK (KERN_ERR, "Fix amb_mem (is %lu words).",
2445             (unsigned long) sizeof(amb_mem));
2446     return -ENOMEM;
2447   }
2448   
2449   show_version();
2450   
2451   amb_check_args();
2452   
2453   // get the juice
2454   devs = amb_probe();
2455   
2456   if (devs) {
2457     mod_timer (&housekeeping, jiffies);
2458   } else {
2459     PRINTK (KERN_INFO, "no (usable) adapters found");
2460   }
2461   
2462   return devs ? 0 : -ENODEV;
2463 }
2464
2465 /********** module exit **********/
2466
2467 static void __exit amb_module_exit (void) {
2468   amb_dev * dev;
2469   
2470   PRINTD (DBG_FLOW|DBG_INIT, "cleanup_module");
2471   
2472   // paranoia
2473   housekeeping.data = 0;
2474   del_timer_sync(&housekeeping);
2475   
2476   while (amb_devs) {
2477     dev = amb_devs;
2478     amb_devs = dev->prev;
2479     
2480     PRINTD (DBG_INFO|DBG_INIT, "closing %p (atm_dev = %p)", dev, dev->atm_dev);
2481     // the drain should not be necessary
2482     drain_rx_pools (dev);
2483     interrupts_off (dev);
2484     amb_reset (dev, 0);
2485     destroy_queues (dev);
2486     atm_dev_deregister (dev->atm_dev);
2487     free_irq (dev->irq, dev);
2488     release_region (dev->iobase, AMB_EXTENT);
2489     kfree (dev);
2490   }
2491   
2492   return;
2493 }
2494
2495 module_init(amb_module_init);
2496 module_exit(amb_module_exit);