ftp://ftp.kernel.org/pub/linux/kernel/v2.6/linux-2.6.6.tar.bz2
[linux-2.6.git] / drivers / net / isa-skeleton.c
1 /* isa-skeleton.c: A network driver outline for linux.
2  *
3  *      Written 1993-94 by Donald Becker.
4  *
5  *      Copyright 1993 United States Government as represented by the
6  *      Director, National Security Agency.
7  *
8  *      This software may be used and distributed according to the terms
9  *      of the GNU General Public License, incorporated herein by reference.
10  *
11  *      The author may be reached as becker@scyld.com, or C/O
12  *      Scyld Computing Corporation
13  *      410 Severn Ave., Suite 210
14  *      Annapolis MD 21403
15  *
16  *      This file is an outline for writing a network device driver for the
17  *      the Linux operating system.
18  *
19  *      To write (or understand) a driver, have a look at the "loopback.c" file to
20  *      get a feel of what is going on, and then use the code below as a skeleton
21  *      for the new driver.
22  *
23  */
24
25 static const char *version =
26         "isa-skeleton.c:v1.51 9/24/94 Donald Becker (becker@cesdis.gsfc.nasa.gov)\n";
27
28 /*
29  *  Sources:
30  *      List your sources of programming information to document that
31  *      the driver is your own creation, and give due credit to others
32  *      that contributed to the work. Remember that GNU project code
33  *      cannot use proprietary or trade secret information. Interface
34  *      definitions are generally considered non-copyrightable to the
35  *      extent that the same names and structures must be used to be
36  *      compatible.
37  *
38  *      Finally, keep in mind that the Linux kernel is has an API, not
39  *      ABI. Proprietary object-code-only distributions are not permitted
40  *      under the GPL.
41  */
42
43 #include <linux/module.h>
44 #include <linux/kernel.h>
45 #include <linux/types.h>
46 #include <linux/fcntl.h>
47 #include <linux/interrupt.h>
48 #include <linux/ioport.h>
49 #include <linux/in.h>
50 #include <linux/slab.h>
51 #include <linux/string.h>
52 #include <linux/spinlock.h>
53 #include <linux/errno.h>
54 #include <linux/init.h>
55 #include <linux/netdevice.h>
56 #include <linux/etherdevice.h>
57 #include <linux/skbuff.h>
58
59 #include <asm/system.h>
60 #include <asm/bitops.h>
61 #include <asm/io.h>
62 #include <asm/dma.h>
63
64 /*
65  * The name of the card. Is used for messages and in the requests for
66  * io regions, irqs and dma channels
67  */
68 static const char* cardname = "netcard";
69
70 /* First, a few definitions that the brave might change. */
71
72 /* A zero-terminated list of I/O addresses to be probed. */
73 static unsigned int netcard_portlist[] __initdata =
74    { 0x200, 0x240, 0x280, 0x2C0, 0x300, 0x320, 0x340, 0};
75
76 /* use 0 for production, 1 for verification, >2 for debug */
77 #ifndef NET_DEBUG
78 #define NET_DEBUG 2
79 #endif
80 static unsigned int net_debug = NET_DEBUG;
81
82 /* The number of low I/O ports used by the ethercard. */
83 #define NETCARD_IO_EXTENT       32
84
85 #define MY_TX_TIMEOUT  ((400*HZ)/1000)
86
87 /* Information that need to be kept for each board. */
88 struct net_local {
89         struct net_device_stats stats;
90         long open_time;                 /* Useless example local info. */
91
92         /* Tx control lock.  This protects the transmit buffer ring
93          * state along with the "tx full" state of the driver.  This
94          * means all netif_queue flow control actions are protected
95          * by this lock as well.
96          */
97         spinlock_t lock;
98 };
99
100 /* The station (ethernet) address prefix, used for IDing the board. */
101 #define SA_ADDR0 0x00
102 #define SA_ADDR1 0x42
103 #define SA_ADDR2 0x65
104
105 /* Index to functions, as function prototypes. */
106
107 static int      netcard_probe1(struct net_device *dev, int ioaddr);
108 static int      net_open(struct net_device *dev);
109 static int      net_send_packet(struct sk_buff *skb, struct net_device *dev);
110 static irqreturn_t net_interrupt(int irq, void *dev_id, struct pt_regs *regs);
111 static void     net_rx(struct net_device *dev);
112 static int      net_close(struct net_device *dev);
113 static struct   net_device_stats *net_get_stats(struct net_device *dev);
114 static void     set_multicast_list(struct net_device *dev);
115 static void     net_tx_timeout(struct net_device *dev);
116
117
118 /* Example routines you must write ;->. */
119 #define tx_done(dev) 1
120 static void     hardware_send_packet(short ioaddr, char *buf, int length);
121 static void     chipset_init(struct net_device *dev, int startp);
122
123 /*
124  * Check for a network adaptor of this type, and return '0' iff one exists.
125  * If dev->base_addr == 0, probe all likely locations.
126  * If dev->base_addr == 1, always return failure.
127  * If dev->base_addr == 2, allocate space for the device and return success
128  * (detachable devices only).
129  */
130 static int __init do_netcard_probe(struct net_device *dev)
131 {
132         int i;
133         int base_addr = dev->base_addr;
134         int irq = dev->irq;
135
136         SET_MODULE_OWNER(dev);
137
138         if (base_addr > 0x1ff)    /* Check a single specified location. */
139                 return netcard_probe1(dev, base_addr);
140         else if (base_addr != 0)  /* Don't probe at all. */
141                 return -ENXIO;
142
143         for (i = 0; netcard_portlist[i]; i++) {
144                 int ioaddr = netcard_portlist[i];
145                 if (netcard_probe1(dev, ioaddr) == 0)
146                         return 0;
147                 dev->irq = irq;
148         }
149
150         return -ENODEV;
151 }
152  
153 static void cleanup_card(struct net_device *dev)
154 {
155 #ifdef jumpered_dma
156         free_dma(dev->dma);
157 #endif
158 #ifdef jumpered_interrupts
159         free_irq(dev->irq, dev);
160 #endif
161         release_region(dev->base_addr, NETCARD_IO_EXTENT);
162 }
163
164 struct net_device * __init netcard_probe(int unit)
165 {
166         struct net_device *dev = alloc_etherdev(sizeof(struct net_local));
167         int err;
168
169         if (!dev)
170                 return ERR_PTR(-ENOMEM);
171
172         sprintf(dev->name, "eth%d", unit);
173         netdev_boot_setup_check(dev);
174
175         err = do_netcard_probe(dev);
176         if (err)
177                 goto out;
178         err = register_netdev(dev);
179         if (err)
180                 goto out1;
181         return dev;
182 out1:
183         cleanup_card(dev);
184 out:
185         free_netdev(dev);
186         return ERR_PTR(err);
187 }
188
189 /*
190  * This is the real probe routine. Linux has a history of friendly device
191  * probes on the ISA bus. A good device probes avoids doing writes, and
192  * verifies that the correct device exists and functions.
193  */
194 static int __init netcard_probe1(struct net_device *dev, int ioaddr)
195 {
196         struct net_local *np;
197         static unsigned version_printed;
198         int i;
199         int err = -ENODEV;
200
201         /* Grab the region so that no one else tries to probe our ioports. */
202         if (!request_region(ioaddr, NETCARD_IO_EXTENT, cardname))
203                 return -EBUSY;
204
205         /*
206          * For ethernet adaptors the first three octets of the station address 
207          * contains the manufacturer's unique code. That might be a good probe
208          * method. Ideally you would add additional checks.
209          */ 
210         if (inb(ioaddr + 0) != SA_ADDR0
211                 ||       inb(ioaddr + 1) != SA_ADDR1
212                 ||       inb(ioaddr + 2) != SA_ADDR2)
213                 goto out;
214
215         if (net_debug  &&  version_printed++ == 0)
216                 printk(KERN_DEBUG "%s", version);
217
218         printk(KERN_INFO "%s: %s found at %#3x, ", dev->name, cardname, ioaddr);
219
220         /* Fill in the 'dev' fields. */
221         dev->base_addr = ioaddr;
222
223         /* Retrieve and print the ethernet address. */
224         for (i = 0; i < 6; i++)
225                 printk(" %2.2x", dev->dev_addr[i] = inb(ioaddr + i));
226
227         err = -EAGAIN;
228 #ifdef jumpered_interrupts
229         /*
230          * If this board has jumpered interrupts, allocate the interrupt
231          * vector now. There is no point in waiting since no other device
232          * can use the interrupt, and this marks the irq as busy. Jumpered
233          * interrupts are typically not reported by the boards, and we must
234          * used autoIRQ to find them.
235          */
236
237         if (dev->irq == -1)
238                 ;       /* Do nothing: a user-level program will set it. */
239         else if (dev->irq < 2) {        /* "Auto-IRQ" */
240                 unsigned long irq_mask = probe_irq_on();
241                 /* Trigger an interrupt here. */
242
243                 dev->irq = probe_irq_off(irq_mask);
244                 if (net_debug >= 2)
245                         printk(" autoirq is %d", dev->irq);
246         } else if (dev->irq == 2)
247                 /*
248                  * Fixup for users that don't know that IRQ 2 is really
249                  * IRQ9, or don't know which one to set.
250                  */
251                 dev->irq = 9;
252
253         {
254                 int irqval = request_irq(dev->irq, &net_interrupt, 0, cardname, dev);
255                 if (irqval) {
256                         printk("%s: unable to get IRQ %d (irqval=%d).\n",
257                                    dev->name, dev->irq, irqval);
258                         goto out;
259                 }
260         }
261 #endif  /* jumpered interrupt */
262 #ifdef jumpered_dma
263         /*
264          * If we use a jumpered DMA channel, that should be probed for and
265          * allocated here as well. See lance.c for an example.
266          */
267         if (dev->dma == 0) {
268                 if (request_dma(dev->dma, cardname)) {
269                         printk("DMA %d allocation failed.\n", dev->dma);
270                         goto out1;
271                 } else
272                         printk(", assigned DMA %d.\n", dev->dma);
273         } else {
274                 short dma_status, new_dma_status;
275
276                 /* Read the DMA channel status registers. */
277                 dma_status = ((inb(DMA1_STAT_REG) >> 4) & 0x0f) |
278                         (inb(DMA2_STAT_REG) & 0xf0);
279                 /* Trigger a DMA request, perhaps pause a bit. */
280                 outw(0x1234, ioaddr + 8);
281                 /* Re-read the DMA status registers. */
282                 new_dma_status = ((inb(DMA1_STAT_REG) >> 4) & 0x0f) |
283                         (inb(DMA2_STAT_REG) & 0xf0);
284                 /*
285                  * Eliminate the old and floating requests,
286                  * and DMA4 the cascade.
287                  */
288                 new_dma_status ^= dma_status;
289                 new_dma_status &= ~0x10;
290                 for (i = 7; i > 0; i--)
291                         if (test_bit(i, &new_dma_status)) {
292                                 dev->dma = i;
293                                 break;
294                         }
295                 if (i <= 0) {
296                         printk("DMA probe failed.\n");
297                         goto out1;
298                 } 
299                 if (request_dma(dev->dma, cardname)) {
300                         printk("probed DMA %d allocation failed.\n", dev->dma);
301                         goto out1;
302                 }
303         }
304 #endif  /* jumpered DMA */
305
306         np = netdev_priv(dev);
307         spin_lock_init(&np->lock);
308
309         dev->open               = net_open;
310         dev->stop               = net_close;
311         dev->hard_start_xmit    = net_send_packet;
312         dev->get_stats          = net_get_stats;
313         dev->set_multicast_list = &set_multicast_list;
314
315         dev->tx_timeout         = &net_tx_timeout;
316         dev->watchdog_timeo     = MY_TX_TIMEOUT; 
317         return 0;
318 out1:
319 #ifdef jumpered_interrupts
320         free_irq(dev->irq, dev);
321 #endif
322 out:
323         release_region(base_addr, NETCARD_IO_EXTENT);
324         return err;
325 }
326
327 static void net_tx_timeout(struct net_device *dev)
328 {
329         struct net_local *np = netdev_priv(dev);
330
331         printk(KERN_WARNING "%s: transmit timed out, %s?\n", dev->name,
332                tx_done(dev) ? "IRQ conflict" : "network cable problem");
333
334         /* Try to restart the adaptor. */
335         chipset_init(dev, 1);
336
337         np->stats.tx_errors++;
338
339         /* If we have space available to accept new transmit
340          * requests, wake up the queueing layer.  This would
341          * be the case if the chipset_init() call above just
342          * flushes out the tx queue and empties it.
343          *
344          * If instead, the tx queue is retained then the
345          * netif_wake_queue() call should be placed in the
346          * TX completion interrupt handler of the driver instead
347          * of here.
348          */
349         if (!tx_full(dev))
350                 netif_wake_queue(dev);
351 }
352
353 /*
354  * Open/initialize the board. This is called (in the current kernel)
355  * sometime after booting when the 'ifconfig' program is run.
356  *
357  * This routine should set everything up anew at each open, even
358  * registers that "should" only need to be set once at boot, so that
359  * there is non-reboot way to recover if something goes wrong.
360  */
361 static int
362 net_open(struct net_device *dev)
363 {
364         struct net_local *np = netdev_priv(dev);
365         int ioaddr = dev->base_addr;
366         /*
367          * This is used if the interrupt line can turned off (shared).
368          * See 3c503.c for an example of selecting the IRQ at config-time.
369          */
370         if (request_irq(dev->irq, &net_interrupt, 0, cardname, dev)) {
371                 return -EAGAIN;
372         }
373         /*
374          * Always allocate the DMA channel after the IRQ,
375          * and clean up on failure.
376          */
377         if (request_dma(dev->dma, cardname)) {
378                 free_irq(dev->irq, dev);
379                 return -EAGAIN;
380         }
381
382         /* Reset the hardware here. Don't forget to set the station address. */
383         chipset_init(dev, 1);
384         outb(0x00, ioaddr);
385         np->open_time = jiffies;
386
387         /* We are now ready to accept transmit requeusts from
388          * the queueing layer of the networking.
389          */
390         netif_start_queue(dev);
391
392         return 0;
393 }
394
395 /* This will only be invoked if your driver is _not_ in XOFF state.
396  * What this means is that you need not check it, and that this
397  * invariant will hold if you make sure that the netif_*_queue()
398  * calls are done at the proper times.
399  */
400 static int net_send_packet(struct sk_buff *skb, struct net_device *dev)
401 {
402         struct net_local *np = netdev_priv(dev);
403         int ioaddr = dev->base_addr;
404         short length = ETH_ZLEN < skb->len ? skb->len : ETH_ZLEN;
405         unsigned char *buf = skb->data;
406
407         /* If some error occurs while trying to transmit this
408          * packet, you should return '1' from this function.
409          * In such a case you _may not_ do anything to the
410          * SKB, it is still owned by the network queueing
411          * layer when an error is returned.  This means you
412          * may not modify any SKB fields, you may not free
413          * the SKB, etc.
414          */
415
416 #if TX_RING
417         /* This is the most common case for modern hardware.
418          * The spinlock protects this code from the TX complete
419          * hardware interrupt handler.  Queue flow control is
420          * thus managed under this lock as well.
421          */
422         spin_lock_irq(&np->lock);
423
424         add_to_tx_ring(np, skb, length);
425         dev->trans_start = jiffies;
426
427         /* If we just used up the very last entry in the
428          * TX ring on this device, tell the queueing
429          * layer to send no more.
430          */
431         if (tx_full(dev))
432                 netif_stop_queue(dev);
433
434         /* When the TX completion hw interrupt arrives, this
435          * is when the transmit statistics are updated.
436          */
437
438         spin_unlock_irq(&np->lock);
439 #else
440         /* This is the case for older hardware which takes
441          * a single transmit buffer at a time, and it is
442          * just written to the device via PIO.
443          *
444          * No spin locking is needed since there is no TX complete
445          * event.  If by chance your card does have a TX complete
446          * hardware IRQ then you may need to utilize np->lock here.
447          */
448         hardware_send_packet(ioaddr, buf, length);
449         np->stats.tx_bytes += skb->len;
450
451         dev->trans_start = jiffies;
452
453         /* You might need to clean up and record Tx statistics here. */
454         if (inw(ioaddr) == /*RU*/81)
455                 np->stats.tx_aborted_errors++;
456         dev_kfree_skb (skb);
457 #endif
458
459         return 0;
460 }
461
462 #if TX_RING
463 /* This handles TX complete events posted by the device
464  * via interrupts.
465  */
466 void net_tx(struct net_device *dev)
467 {
468         struct net_local *np = netdev_priv(dev);
469         int entry;
470
471         /* This protects us from concurrent execution of
472          * our dev->hard_start_xmit function above.
473          */
474         spin_lock(&np->lock);
475
476         entry = np->tx_old;
477         while (tx_entry_is_sent(np, entry)) {
478                 struct sk_buff *skb = np->skbs[entry];
479
480                 np->stats.tx_bytes += skb->len;
481                 dev_kfree_skb_irq (skb);
482
483                 entry = next_tx_entry(np, entry);
484         }
485         np->tx_old = entry;
486
487         /* If we had stopped the queue due to a "tx full"
488          * condition, and space has now been made available,
489          * wake up the queue.
490          */
491         if (netif_queue_stopped(dev) && ! tx_full(dev))
492                 netif_wake_queue(dev);
493
494         spin_unlock(&np->lock);
495 }
496 #endif
497
498 /*
499  * The typical workload of the driver:
500  * Handle the network interface interrupts.
501  */
502 static irqreturn_t net_interrupt(int irq, void *dev_id, struct pt_regs * regs)
503 {
504         struct net_device *dev = dev_id;
505         struct net_local *np;
506         int ioaddr, status;
507         int handled = 0;
508
509         ioaddr = dev->base_addr;
510
511         np = netdev_priv(dev);
512         status = inw(ioaddr + 0);
513
514         if (status == 0)
515                 goto out;
516         handled = 1;
517
518         if (status & RX_INTR) {
519                 /* Got a packet(s). */
520                 net_rx(dev);
521         }
522 #if TX_RING
523         if (status & TX_INTR) {
524                 /* Transmit complete. */
525                 net_tx(dev);
526                 np->stats.tx_packets++;
527                 netif_wake_queue(dev);
528         }
529 #endif
530         if (status & COUNTERS_INTR) {
531                 /* Increment the appropriate 'localstats' field. */
532                 np->stats.tx_window_errors++;
533         }
534 out:
535         return IRQ_RETVAL(handled);
536 }
537
538 /* We have a good packet(s), get it/them out of the buffers. */
539 static void
540 net_rx(struct net_device *dev)
541 {
542         struct net_local *lp = netdev_priv(dev);
543         int ioaddr = dev->base_addr;
544         int boguscount = 10;
545
546         do {
547                 int status = inw(ioaddr);
548                 int pkt_len = inw(ioaddr);
549           
550                 if (pkt_len == 0)               /* Read all the frames? */
551                         break;                  /* Done for now */
552
553                 if (status & 0x40) {    /* There was an error. */
554                         lp->stats.rx_errors++;
555                         if (status & 0x20) lp->stats.rx_frame_errors++;
556                         if (status & 0x10) lp->stats.rx_over_errors++;
557                         if (status & 0x08) lp->stats.rx_crc_errors++;
558                         if (status & 0x04) lp->stats.rx_fifo_errors++;
559                 } else {
560                         /* Malloc up new buffer. */
561                         struct sk_buff *skb;
562
563                         lp->stats.rx_bytes+=pkt_len;
564                         
565                         skb = dev_alloc_skb(pkt_len);
566                         if (skb == NULL) {
567                                 printk(KERN_NOTICE "%s: Memory squeeze, dropping packet.\n",
568                                            dev->name);
569                                 lp->stats.rx_dropped++;
570                                 break;
571                         }
572                         skb->dev = dev;
573
574                         /* 'skb->data' points to the start of sk_buff data area. */
575                         memcpy(skb_put(skb,pkt_len), (void*)dev->rmem_start,
576                                    pkt_len);
577                         /* or */
578                         insw(ioaddr, skb->data, (pkt_len + 1) >> 1);
579
580                         netif_rx(skb);
581                         dev->last_rx = jiffies;
582                         lp->stats.rx_packets++;
583                         lp->stats.rx_bytes += pkt_len;
584                 }
585         } while (--boguscount);
586
587         return;
588 }
589
590 /* The inverse routine to net_open(). */
591 static int
592 net_close(struct net_device *dev)
593 {
594         struct net_local *lp = netdev_priv(dev);
595         int ioaddr = dev->base_addr;
596
597         lp->open_time = 0;
598
599         netif_stop_queue(dev);
600
601         /* Flush the Tx and disable Rx here. */
602
603         disable_dma(dev->dma);
604
605         /* If not IRQ or DMA jumpered, free up the line. */
606         outw(0x00, ioaddr+0);   /* Release the physical interrupt line. */
607
608         free_irq(dev->irq, dev);
609         free_dma(dev->dma);
610
611         /* Update the statistics here. */
612
613         return 0;
614
615 }
616
617 /*
618  * Get the current statistics.
619  * This may be called with the card open or closed.
620  */
621 static struct net_device_stats *net_get_stats(struct net_device *dev)
622 {
623         struct net_local *lp = netdev_priv(dev);
624         short ioaddr = dev->base_addr;
625
626         /* Update the statistics from the device registers. */
627         lp->stats.rx_missed_errors = inw(ioaddr+1);
628         return &lp->stats;
629 }
630
631 /*
632  * Set or clear the multicast filter for this adaptor.
633  * num_addrs == -1      Promiscuous mode, receive all packets
634  * num_addrs == 0       Normal mode, clear multicast list
635  * num_addrs > 0        Multicast mode, receive normal and MC packets,
636  *                      and do best-effort filtering.
637  */
638 static void
639 set_multicast_list(struct net_device *dev)
640 {
641         short ioaddr = dev->base_addr;
642         if (dev->flags&IFF_PROMISC)
643         {
644                 /* Enable promiscuous mode */
645                 outw(MULTICAST|PROMISC, ioaddr);
646         }
647         else if((dev->flags&IFF_ALLMULTI) || dev->mc_count > HW_MAX_ADDRS)
648         {
649                 /* Disable promiscuous mode, use normal mode. */
650                 hardware_set_filter(NULL);
651
652                 outw(MULTICAST, ioaddr);
653         }
654         else if(dev->mc_count)
655         {
656                 /* Walk the address list, and load the filter */
657                 hardware_set_filter(dev->mc_list);
658
659                 outw(MULTICAST, ioaddr);
660         }
661         else 
662                 outw(0, ioaddr);
663 }
664
665 #ifdef MODULE
666
667 static struct net_device *this_device;
668 static int io = 0x300;
669 static int irq;
670 static int dma;
671 static int mem;
672 MODULE_LICENSE("GPL");
673
674 int init_module(void)
675 {
676         struct net_device *dev;
677         int result;
678
679         if (io == 0)
680                 printk(KERN_WARNING "%s: You shouldn't use auto-probing with insmod!\n",
681                            cardname);
682         dev = alloc_etherdev(sizeof(struct net_local));
683         if (!dev)
684                 return -ENOMEM;
685
686         /* Copy the parameters from insmod into the device structure. */
687         dev->base_addr = io;
688         dev->irq       = irq;
689         dev->dma       = dma;
690         dev->mem_start = mem;
691         if (do_netcard_probe(dev) == 0) {
692                 if (register_netdev(dev) == 0)
693                         this_device = dev;
694                         return 0;
695                 }
696                 cleanup_card(dev);
697         }
698         free_netdev(dev);
699         return -ENXIO;
700 }
701
702 void
703 cleanup_module(void)
704 {
705         unregister_netdev(this_device);
706         cleanup_card(this_device);
707         free_netdev(this_device);
708 }
709
710 #endif /* MODULE */
711
712 /*
713  * Local variables:
714  *  compile-command:
715  *      gcc -D__KERNEL__ -Wall -Wstrict-prototypes -Wwrite-strings
716  *      -Wredundant-decls -O2 -m486 -c skeleton.c
717  *  version-control: t
718  *  kept-new-versions: 5
719  *  tab-width: 4
720  *  c-indent-level: 4
721  * End:
722  */