import of ftp.dlink.com/GPL/DSMG-600_reB/ppclinux.tar.gz
[linux-2.4.21-pre4.git] / drivers / net / xilinx_enet / adapter.c
1 /*
2  * adapter.c
3  *
4  * Xilinx Ethernet Adapter component to interface XEmac component to Linux
5  *
6  * Author: MontaVista Software, Inc.
7  *         source@mvista.com
8  *
9  * 2002 (c) MontaVista, Software, Inc.  This file is licensed under the terms
10  * of the GNU General Public License version 2.1.  This program is licensed
11  * "as is" without any warranty of any kind, whether express or implied.
12  */
13
14 /*
15  * This driver is a bit unusual in that it is composed of two logical
16  * parts where one part is the OS independent code and the other part is
17  * the OS dependent code.  Xilinx provides their drivers split in this
18  * fashion.  This file represents the Linux OS dependent part known as
19  * the Linux adapter.  The other files in this directory are the OS
20  * independent files as provided by Xilinx with no changes made to them.
21  * The names exported by those files begin with XEmac_.  All functions
22  * in this file that are called by Linux have names that begin with
23  * xenet_.  The functions in this file that have Handler in their name
24  * are registered as callbacks with the underlying Xilinx OS independent
25  * layer.  Any other functions are static helper functions.
26  */
27
28 #include <linux/module.h>
29 #include <linux/init.h>
30 #include <linux/netdevice.h>
31 #include <linux/etherdevice.h>
32 #include <linux/skbuff.h>
33 #include <linux/mii.h>
34 #include <asm/io.h>
35 #include <asm/irq.h>
36
37 #include <xbasic_types.h>
38 #include "xemac.h"
39 #include "xemac_i.h"
40
41 MODULE_AUTHOR("MontaVista Software, Inc. <source@mvista.com>");
42 MODULE_DESCRIPTION("Xilinx Ethernet Media Access Controller driver");
43 MODULE_LICENSE("GPL");
44
45 #define TX_TIMEOUT (60*HZ)      /* Transmission timeout is 60 seconds. */
46
47 /*
48  * Our private per device data.  When a net_device is allocated we will
49  * ask for enough extra space for this.
50  */
51 struct net_local {
52         struct net_device_stats stats;  /* Statistics for this device */
53         struct net_device *next_dev;    /* The next device in dev_list */
54         struct timer_list phy_timer;    /* PHY monitoring timer */
55         u32 index;              /* Which interface is this */
56         u32 save_BaseAddress;   /* Saved physical base address */
57         XInterruptHandler Isr;  /* Pointer to the XEmac ISR routine */
58         struct sk_buff *saved_skb;      /* skb being transmitted */
59         spinlock_t skb_lock;    /* For atomic access to saved_skb */
60         u8 mii_addr;            /* The MII address of the PHY */
61         /*
62          * The underlying OS independent code needs space as well.  A
63          * pointer to the following XEmac structure will be passed to
64          * any XEmac_ function that requires it.  However, we treat the
65          * data as an opaque object in this file (meaning that we never
66          * reference any of the fields inside of the structure).
67          */
68         XEmac Emac;
69 };
70
71 /* List of devices we're handling and a lock to give us atomic access. */
72 static struct net_device *dev_list = NULL;
73 static spinlock_t dev_lock = SPIN_LOCK_UNLOCKED;
74
75 /* SAATODO: This function will be moved into the Xilinx code. */
76 /*****************************************************************************/
77 /**
78 *
79 * Lookup the device configuration based on the emac instance.  The table
80 * EmacConfigTable contains the configuration info for each device in the system.
81 *
82 * @param Instance is the index of the emac being looked up.
83 *
84 * @return
85 *
86 * A pointer to the configuration table entry corresponding to the given
87 * device ID, or NULL if no match is found.
88 *
89 * @note
90 *
91 * None.
92 *
93 ******************************************************************************/
94 XEmac_Config *XEmac_GetConfig(int Instance)
95 {
96         if (Instance < 0 || Instance >= XPAR_XEMAC_NUM_INSTANCES)
97         {
98                 return NULL;
99         }
100
101         return &XEmac_ConfigTable[Instance];
102 }
103
104 /*
105  * The following are notes regarding the critical sections in this
106  * driver and how they are protected.
107  *
108  * saved_skb
109  * The pointer to the skb that is currently being transmitted is
110  * protected by a spinlock.  It is conceivable that the transmit timeout
111  * could fire in the middle of a transmit completion.  The spinlock
112  * protects the critical section of getting the pointer and NULLing it
113  * out.
114  *
115  * dev_list
116  * There is a spinlock protecting the device list.  It isn't really
117  * necessary yet because the list is only manipulated at init and
118  * cleanup, but it's there because it is basically free and if we start
119  * doing hot add and removal of ethernet devices when the FPGA is
120  * reprogrammed while the system is up, we'll need to protect the list.
121  *
122  * XEmac_Start, XEmac_Stop and XEmac_SetOptions are not thread safe.
123  * These functions are called from xenet_open(), xenet_close(), reset(),
124  * and xenet_set_multicast_list().  xenet_open() and xenet_close()
125  * should be safe because when they do start and stop, they don't have
126  * interrupts or timers enabled.  The other side is that they won't be
127  * called while a timer or interrupt is being handled.  Next covered is
128  * the interaction between reset() and xenet_set_multicast_list().  This
129  * is taken care of by disabling the ethernet IRQ and bottom half when
130  * the multicast list is being set.  The inverse case is covered because
131  * a call to xenet_set_multicast_list() will not happen in the middle of
132  * a timer or interrupt being serviced.  Finally, the interaction
133  * between reset() being called from various places needs to be
134  * considered.  reset() is called from poll_mii() and xenet_tx_timeout()
135  * which are timer bottom halves as well as FifoRecvHandler() and
136  * ErrorHandler() which are interrupt handlers.  The timer bottom halves
137  * won't interrupt an interrupt handler (or each other) so that is
138  * covered.  The interrupt handlers won't interrupt each other either.
139  * That leaves the case of interrupt handlers interrupting timer bottom
140  * halves.  This is handled simply by disabling the interrupt when the
141  * bottom half calls reset().
142  *
143  * XEmac_PhyRead and XEmac_PhyWrite are not thread safe.
144  * These functions are called from get_phy_status(), xenet_ioctl() and
145  * probe().  probe() is only called from xenet_init() so it is not an
146  * issue (nothing is really up and running yet).  get_phy_status() is
147  * called from both poll_mii() (a timer bottom half) and xenet_open().
148  * These shouldn't interfere with each other because xenet_open() is
149  * what starts the poll_mii() timer.  xenet_open() and xenet_ioctl()
150  * should be safe as well because they will be sequential.  That leaves
151  * the interaction between poll_mii() and xenet_ioctl().  While the
152  * timer bottom half is executing, a new ioctl won't come in so that is
153  * taken care of.  That leaves the one case of the poll_mii timer
154  * popping while handling an ioctl.  To take care of that case, the
155  * timer is deleted when the ioctl comes in and then added back in after
156  * the ioctl is finished.
157  */
158
159 /*
160  * Helper function to reset the underlying hardware.  This is called
161  * when we get into such deep trouble that we don't know how to handle
162  * otherwise.
163  */
164 typedef enum DUPLEX { UNKNOWN_DUPLEX, HALF_DUPLEX, FULL_DUPLEX } DUPLEX;
165 static void
166 reset(struct net_device *dev, DUPLEX duplex)
167 {
168         struct net_local *lp = (struct net_local *) dev->priv;
169         struct sk_buff *tskb;
170         u32 Options;
171         u8 IfgPart1;
172         u8 IfgPart2;
173         u8 SendThreshold;
174         u32 SendWaitBound;
175         u8 RecvThreshold;
176         u32 RecvWaitBound;
177
178         /* Shouldn't really be necessary, but shouldn't hurt. */
179         netif_stop_queue(dev);
180
181         /*
182          * XEmac_Reset puts the device back to the default state.  We need
183          * to save all the settings we don't already know, reset, restore
184          * the settings, and then restart the emac.
185          */
186         XEmac_GetInterframeGap(&lp->Emac, &IfgPart1, &IfgPart2);
187         Options = XEmac_GetOptions(&lp->Emac);
188         switch (duplex) {
189         case HALF_DUPLEX:
190                 Options &= ~XEM_FDUPLEX_OPTION;
191                 break;
192         case FULL_DUPLEX:
193                 Options |= XEM_FDUPLEX_OPTION;
194                 break;
195         case UNKNOWN_DUPLEX:
196                 break;
197         }
198
199         if (XEmac_mIsSgDma(&lp->Emac)) {
200                 /*
201                  * The following four functions will return an error if we are
202                  * not doing scatter-gather DMA.  We just checked that so we
203                  * can safely ignore the return values.  We cast them to void
204                  * to make that explicit.
205                  */
206                 (void) XEmac_GetPktThreshold(&lp->Emac, XEM_SEND,
207                                              &SendThreshold);
208                 (void) XEmac_GetPktWaitBound(&lp->Emac, XEM_SEND,
209                                              &SendWaitBound);
210                 (void) XEmac_GetPktThreshold(&lp->Emac, XEM_RECV,
211                                              &RecvThreshold);
212                 (void) XEmac_GetPktWaitBound(&lp->Emac, XEM_RECV,
213                                              &RecvWaitBound);
214         }
215
216         XEmac_Reset(&lp->Emac);
217
218         /*
219          * The following three functions will return an error if the
220          * EMAC is already started.  We just stopped it by calling
221          * XEmac_Reset() so we can safely ignore the return values.
222          * We cast them to void to make that explicit.
223          */
224         (void) XEmac_SetMacAddress(&lp->Emac, dev->dev_addr);
225         (void) XEmac_SetInterframeGap(&lp->Emac, IfgPart1, IfgPart2);
226         (void) XEmac_SetOptions(&lp->Emac, Options);
227         if (XEmac_mIsSgDma(&lp->Emac)) {
228                 /*
229                  * The following four functions will return an error if
230                  * we are not doing scatter-gather DMA or if the EMAC is
231                  * already started.  We just checked that we are indeed
232                  * doing scatter-gather and we just stopped the EMAC so
233                  * we can safely ignore the return values.  We cast them
234                  * to void to make that explicit.
235                  */
236                 (void) XEmac_SetPktThreshold(&lp->Emac, XEM_SEND,
237                                              SendThreshold);
238                 (void) XEmac_SetPktWaitBound(&lp->Emac, XEM_SEND,
239                                              SendWaitBound);
240                 (void) XEmac_SetPktThreshold(&lp->Emac, XEM_RECV,
241                                              RecvThreshold);
242                 (void) XEmac_SetPktWaitBound(&lp->Emac, XEM_RECV,
243                                              RecvWaitBound);
244         }
245
246         /*
247          * XEmac_Start returns an error when: it is already started, the send
248          * and receive handlers are not set, or a scatter-gather DMA list is
249          * missing.  None of these can happen at this point, so we cast the
250          * return to void to make that explicit.
251          */
252         (void) XEmac_Start(&lp->Emac);
253
254         /* Make sure that the send handler and we don't both free the skb. */
255         spin_lock_irq(&lp->skb_lock);
256         tskb = lp->saved_skb;
257         lp->saved_skb = NULL;
258         spin_unlock_irq(&lp->skb_lock);
259         if (tskb)
260                 dev_kfree_skb(tskb);
261
262         /* We're all ready to go.  Start the queue in case it was stopped. */
263         netif_wake_queue(dev);
264 }
265
266 static int
267 get_phy_status(struct net_device *dev, DUPLEX * duplex, int *linkup)
268 {
269         struct net_local *lp = (struct net_local *) dev->priv;
270         u16 reg;
271         XStatus xs;
272
273         xs = XEmac_PhyRead(&lp->Emac, lp->mii_addr, MII_BMCR, &reg);
274         if (xs != XST_SUCCESS) {
275                 printk(KERN_ERR
276                        "%s: Could not read PHY control register; error %d\n",
277                        dev->name, xs);
278                 return -1;
279         }
280
281         if (!(reg & BMCR_ANENABLE)) {
282                 /*
283                  * Auto-negotiation is disabled so the full duplex bit in
284                  * the control register tells us if the PHY is running
285                  * half or full duplex.
286                  */
287                 *duplex = (reg & BMCR_FULLDPLX) ? FULL_DUPLEX : HALF_DUPLEX;
288         } else {
289                 /*
290                  * Auto-negotiation is enabled.  Figure out what was
291                  * negotiated by looking for the best mode in the union
292                  * of what we and our partner advertise.
293                  */
294                 u16 advertise, partner, negotiated;
295
296                 xs = XEmac_PhyRead(&lp->Emac, lp->mii_addr,
297                                    MII_ADVERTISE, &advertise);
298                 if (xs != XST_SUCCESS) {
299                         printk(KERN_ERR
300                                "%s: Could not read PHY advertisement; error %d\n",
301                                dev->name, xs);
302                         return -1;
303                 }
304                 xs = XEmac_PhyRead(&lp->Emac, lp->mii_addr, MII_LPA, &partner);
305                 if (xs != XST_SUCCESS) {
306                         printk(KERN_ERR
307                                "%s: Could not read PHY LPA; error %d\n",
308                                dev->name, xs);
309                         return -1;
310                 }
311
312                 negotiated = advertise & partner & ADVERTISE_ALL;
313                 if (negotiated & ADVERTISE_100FULL)
314                         *duplex = FULL_DUPLEX;
315                 else if (negotiated & ADVERTISE_100HALF)
316                         *duplex = HALF_DUPLEX;
317                 else if (negotiated & ADVERTISE_10FULL)
318                         *duplex = FULL_DUPLEX;
319                 else
320                         *duplex = HALF_DUPLEX;
321         }
322
323         xs = XEmac_PhyRead(&lp->Emac, lp->mii_addr, MII_BMSR, &reg);
324         if (xs != XST_SUCCESS) {
325                 printk(KERN_ERR
326                        "%s: Could not read PHY status register; error %d\n",
327                        dev->name, xs);
328                 return -1;
329         }
330
331         *linkup = (reg & BMSR_LSTATUS) != 0;
332
333         return 0;
334 }
335
336 /*
337  * This routine is used for two purposes.  The first is to keep the
338  * EMAC's duplex setting in sync with the PHY's.  The second is to keep
339  * the system apprised of the state of the link.  Note that this driver
340  * does not configure the PHY.  Either the PHY should be configured for
341  * auto-negotiation or it should be handled by something like mii-tool.
342  */
343 static void
344 poll_mii(unsigned long data)
345 {
346         struct net_device *dev = (struct net_device *) data;
347         struct net_local *lp = (struct net_local *) dev->priv;
348         u32 Options;
349         DUPLEX phy_duplex, mac_duplex;
350         int phy_carrier, netif_carrier;
351
352         /* First, find out what's going on with the PHY. */
353         if (get_phy_status(dev, &phy_duplex, &phy_carrier)) {
354                 printk(KERN_ERR "%s: Terminating link monitoring.\n",
355                        dev->name);
356                 return;
357         }
358
359         /* Second, figure out if we have the EMAC in half or full duplex. */
360         Options = XEmac_GetOptions(&lp->Emac);
361         mac_duplex = (Options & XEM_FDUPLEX_OPTION) ? FULL_DUPLEX : HALF_DUPLEX;
362
363         /* Now see if there is a mismatch. */
364         if (mac_duplex != phy_duplex) {
365                 /*
366                  * Make sure that no interrupts come in that could cause
367                  * reentrancy problems in reset.
368                  */
369                 disable_irq(dev->irq);
370                 reset(dev, phy_duplex);
371                 enable_irq(dev->irq);
372         }
373
374         netif_carrier = netif_carrier_ok(dev) != 0;
375
376         if (phy_carrier != netif_carrier) {
377                 if (phy_carrier) {
378                         printk(KERN_INFO "%s: Link carrier restored.\n",
379                                dev->name);
380                         netif_carrier_on(dev);
381                 } else {
382                         printk(KERN_INFO "%s: Link carrier lost.\n", dev->name);
383                         netif_carrier_off(dev);
384                 }
385         }
386
387         /* Set up the timer so we'll get called again in 2 seconds. */
388         lp->phy_timer.expires = jiffies + 2 * HZ;
389         add_timer(&lp->phy_timer);
390 }
391
392 /*
393  * This routine is registered with the OS as the function to call when
394  * the EMAC interrupts.  It in turn, calls the Xilinx OS independent
395  * interrupt function.  There are different interrupt functions for FIFO
396  * and scatter-gather so we just set a pointer (Isr) into our private
397  * data so we don't have to figure it out here.  The Xilinx OS
398  * independent interrupt function will in turn call any callbacks that
399  * we have registered for various conditions.
400  */
401 static void
402 xenet_interrupt(int irq, void *dev_id, struct pt_regs *regs)
403 {
404         struct net_device *dev = dev_id;
405         struct net_local *lp = (struct net_local *) dev->priv;
406
407         /* Call it. */
408         (*(lp->Isr)) (&lp->Emac);
409 }
410
411 static int
412 xenet_open(struct net_device *dev)
413 {
414         struct net_local *lp = (struct net_local *) dev->priv;
415         u32 Options;
416         DUPLEX phy_duplex, mac_duplex;
417         int phy_carrier;
418
419         /*
420          * Just to be safe, stop the device first.  If the device is already
421          * stopped, an error will be returned.  In this case, we don't really
422          * care, so cast it to void to make it explicit.
423          */
424         (void) XEmac_Stop(&lp->Emac);
425
426         /* Set the MAC address each time opened. */
427         if (XEmac_SetMacAddress(&lp->Emac, dev->dev_addr) != XST_SUCCESS) {
428                 printk(KERN_ERR "%s: Could not set MAC address.\n", dev->name);
429                 return -EIO;
430         }
431
432         /*
433          * If the device is not configured for polled mode, connect to the
434          * interrupt controller and enable interrupts.  Currently, there
435          * isn't any code to set polled mode, so this check is probably
436          * superfluous.
437          */
438         Options = XEmac_GetOptions(&lp->Emac);
439         if ((Options & XEM_POLLED_OPTION) == 0) {
440                 int retval;
441                 /* Grab the IRQ */
442                 retval =
443                     request_irq(dev->irq, &xenet_interrupt, 0, dev->name, dev);
444                 if (retval) {
445                         printk(KERN_ERR
446                                "%s: Could not allocate interrupt %d.\n",
447                                dev->name, dev->irq);
448                         return retval;
449                 }
450         }
451
452         /* Set the EMAC's duplex setting based upon what the PHY says. */
453         if (!get_phy_status(dev, &phy_duplex, &phy_carrier)) {
454                 /* We successfully got the PHY status. */
455                 mac_duplex = ((Options & XEM_FDUPLEX_OPTION)
456                               ? FULL_DUPLEX : HALF_DUPLEX);
457                 if (mac_duplex != phy_duplex) {
458                         switch (phy_duplex) {
459                         case HALF_DUPLEX: Options &= ~XEM_FDUPLEX_OPTION; break;
460                         case FULL_DUPLEX: Options |=  XEM_FDUPLEX_OPTION; break;
461                         case UNKNOWN_DUPLEX: break;
462                         }
463                         /*
464                          * The following function will return an error
465                          * if the EMAC is already started.  We know it
466                          * isn't started so we can safely ignore the
467                          * return value.  We cast it to void to make
468                          * that explicit.
469                          */
470                         (void) XEmac_SetOptions(&lp->Emac, Options);
471                 }
472         }
473
474         if (XEmac_Start(&lp->Emac) != XST_SUCCESS) {
475                 printk(KERN_ERR "%s: Could not start device.\n", dev->name);
476                 free_irq(dev->irq, dev);
477                 return -EBUSY;
478         }
479
480         /* We're ready to go. */
481         MOD_INC_USE_COUNT;
482         netif_start_queue(dev);
483
484         /* Set up the PHY monitoring timer. */
485         lp->phy_timer.expires = jiffies + 2*HZ;
486         lp->phy_timer.data = (unsigned long)dev;
487         lp->phy_timer.function = &poll_mii;
488         add_timer(&lp->phy_timer);
489
490         return 0;
491 }
492 static int
493 xenet_close(struct net_device *dev)
494 {
495         struct net_local *lp = (struct net_local *) dev->priv;
496
497         /* Shut down the PHY monitoring timer. */
498         del_timer_sync(&lp->phy_timer);
499
500         netif_stop_queue(dev);
501
502         /*
503          * If not in polled mode, free the interrupt.  Currently, there
504          * isn't any code to set polled mode, so this check is probably
505          * superfluous.
506          */
507         if ((XEmac_GetOptions(&lp->Emac) & XEM_POLLED_OPTION) == 0)
508                 free_irq(dev->irq, dev);
509
510         if (XEmac_Stop(&lp->Emac) != XST_SUCCESS) {
511                 printk(KERN_ERR "%s: Could not stop device.\n", dev->name);
512                 return -EBUSY;
513         }
514
515         MOD_DEC_USE_COUNT;
516         return 0;
517 }
518 static struct net_device_stats *
519 xenet_get_stats(struct net_device *dev)
520 {
521         struct net_local *lp = (struct net_local *) dev->priv;
522         return &lp->stats;
523 }
524
525 /* Helper function to determine if a given XEmac error warrants a reset. */
526 extern inline int
527 status_requires_reset(XStatus s)
528 {
529         return (s == XST_DMA_ERROR || s == XST_FIFO_ERROR
530                 || s == XST_RESET_ERROR);
531 }
532
533 static int
534 xenet_FifoSend(struct sk_buff *orig_skb, struct net_device *dev)
535 {
536         struct net_local *lp = (struct net_local *) dev->priv;
537         struct sk_buff *new_skb;
538         unsigned int len, align;
539
540         /*
541          * The FIFO takes a single request at a time.  Stop the queue to
542          * accomplish this.  We'll wake the queue in FifoSendHandler once
543          * the skb has been sent or in xenet_tx_timeout if something goes
544          * horribly wrong.
545          */
546         netif_stop_queue(dev);
547
548         len = orig_skb->len;
549         /*
550          * The packet FIFO requires the buffers to be 32 bit aligned.
551          * The sk_buff data is not 32 bit aligned, so we have to do this
552          * copy.  As you probably well know, this is not optimal.
553          */
554         if (!(new_skb = dev_alloc_skb(len + 4))) {
555                 /* We couldn't get another skb. */
556                 dev_kfree_skb(orig_skb);
557                 lp->stats.tx_dropped++;
558                 printk(KERN_ERR "%s: Could not allocate transmit buffer.\n",
559                        dev->name);
560                 netif_wake_queue(dev);
561                 return -EBUSY;
562         }
563
564         /*
565          * A new skb should have the data word aligned, but this code is
566          * here just in case that isn't true...  Calculate how many
567          * bytes we should reserve to get the data to start on a word
568          * boundary.  */
569         align = 4 - ((unsigned long) new_skb->data & 3);
570         if (align != 4)
571                 skb_reserve(new_skb, align);
572
573         /* Copy the data from the original skb to the new one. */
574         skb_put(new_skb, len);
575         memcpy(new_skb->data, orig_skb->data, len);
576
577         /* Get rid of the original skb. */
578         dev_kfree_skb(orig_skb);
579
580         lp->saved_skb = new_skb;
581         if (XEmac_FifoSend(&lp->Emac, (u8 *) new_skb->data, len) != XST_SUCCESS) {
582                 /*
583                  * I don't think that we will be fighting FifoSendHandler or
584                  * xenet_tx_timeout, but it's cheap to guarantee it won't be a
585                  * problem.
586                  */
587                 spin_lock_irq(&lp->skb_lock);
588                 new_skb = lp->saved_skb;
589                 lp->saved_skb = NULL;
590                 spin_unlock_irq(&lp->skb_lock);
591
592                 dev_kfree_skb(new_skb);
593                 lp->stats.tx_errors++;
594                 printk(KERN_ERR "%s: Could not transmit buffer.\n", dev->name);
595                 netif_wake_queue(dev);
596                 return -EIO;
597         }
598         return 0;
599 }
600
601 /* The callback function for completed frames sent in FIFO mode. */
602 static void
603 FifoSendHandler(void *CallbackRef)
604 {
605         struct net_device *dev = (struct net_device *) CallbackRef;
606         struct net_local *lp = (struct net_local *) dev->priv;
607         struct sk_buff *tskb;
608
609         lp->stats.tx_bytes += lp->saved_skb->len;
610         lp->stats.tx_packets++;
611
612         /* Make sure that the timeout handler and we don't both free the skb. */
613         spin_lock_irq(&lp->skb_lock);
614         tskb = lp->saved_skb;
615         lp->saved_skb = NULL;
616         spin_unlock_irq(&lp->skb_lock);
617         if (tskb)
618                 dev_kfree_skb(tskb);
619
620         /* Start the queue back up to allow next request. */
621         netif_wake_queue(dev);
622 }
623 static void
624 xenet_tx_timeout(struct net_device *dev)
625 {
626         struct net_local *lp = (struct net_local *) dev->priv;
627         printk("%s: Exceeded transmit timeout of %lu ms.  Resetting emac.\n",
628                dev->name, TX_TIMEOUT * 1000UL / HZ);
629
630         lp->stats.tx_errors++;
631
632         /*
633          * Make sure that no interrupts come in that could cause reentrancy
634          * problems in reset.
635          */
636         disable_irq(dev->irq);
637         reset(dev, UNKNOWN_DUPLEX);
638         enable_irq(dev->irq);
639 }
640
641 /* The callback function for frames received when in FIFO mode. */
642 static void
643 FifoRecvHandler(void *CallbackRef)
644 {
645         struct net_device *dev = (struct net_device *) CallbackRef;
646         struct net_local *lp = (struct net_local *) dev->priv;
647         struct sk_buff *skb;
648         unsigned int align;
649         u32 len;
650         XStatus Result;
651
652         /*
653          * The OS independent Xilinx EMAC code does not provide a
654          * function to get the length of an incoming packet and a
655          * separate call to actually get the packet data.  It does this
656          * because they didn't add any code to keep the hardware's
657          * receive length and data FIFOs in sync.  Instead, they require
658          * that you send a maximal length buffer so that they can read
659          * the length and data FIFOs in a single chunk of code so that
660          * they can't get out of sync.  So, we need to allocate an skb
661          * that can hold a maximal sized packet.  The OS independent
662          * code needs to see the data 32-bit aligned, so we tack on an
663          * extra four just in case we need to do an skb_reserve to get
664          * it that way.
665          */
666         len = XEM_MAX_FRAME_SIZE;
667         if (!(skb = dev_alloc_skb(len + 4))) {
668                 /* Couldn't get memory. */
669                 lp->stats.rx_dropped++;
670                 printk(KERN_ERR "%s: Could not allocate receive buffer.\n",
671                        dev->name);
672                 return;
673         }
674
675         /*
676          * A new skb should have the data word aligned, but this code is
677          * here just in case that isn't true...  Calculate how many
678          * bytes we should reserve to get the data to start on a word
679          * boundary.  */
680         align = 4 - ((unsigned long) skb->data & 3);
681         if (align != 4)
682                 skb_reserve(skb, align);
683
684         Result = XEmac_FifoRecv(&lp->Emac, (u8 *) skb->data, &len);
685         if (Result != XST_SUCCESS) {
686                 int need_reset = status_requires_reset(Result);
687
688                 lp->stats.rx_errors++;
689                 dev_kfree_skb(skb);
690
691                 printk(KERN_ERR "%s: Could not receive buffer, error=%d%s.\n",
692                        dev->name, Result,
693                        need_reset ? ", resetting device." : "");
694                 if (need_reset)
695                         reset(dev, UNKNOWN_DUPLEX);
696                 return;
697         }
698
699         skb_put(skb, len);      /* Tell the skb how much data we got. */
700         skb->dev = dev;         /* Fill out required meta-data. */
701         skb->protocol = eth_type_trans(skb, dev);
702
703         lp->stats.rx_packets++;
704         lp->stats.rx_bytes += len;
705
706         netif_rx(skb);          /* Send the packet upstream. */
707 }
708
709 /* The callback function for errors. */
710 static void
711 ErrorHandler(void *CallbackRef, XStatus Code)
712 {
713         struct net_device *dev = (struct net_device *) CallbackRef;
714         int need_reset;
715         need_reset = status_requires_reset(Code);
716
717         printk(KERN_ERR "%s: device error %d%s\n",
718                dev->name, Code, need_reset ? ", resetting device." : "");
719         if (need_reset)
720                 reset(dev, UNKNOWN_DUPLEX);
721 }
722
723 static void
724 xenet_set_multicast_list(struct net_device *dev)
725 {
726         struct net_local *lp = (struct net_local *) dev->priv;
727         u32 Options;
728
729         /*
730          * XEmac_Start, XEmac_Stop and XEmac_SetOptions are supposed to
731          * be protected by a semaphore.  This Linux adapter doesn't have
732          * it as bad as the VxWorks adapter because the sequence of
733          * requests to us is much more sequential.  However, we do have
734          * one area in which this is a problem.
735          *
736          * xenet_set_multicast_list() is called while the link is up and
737          * interrupts are enabled, so at any point in time we could get
738          * an error that causes our reset() to be called.  reset() calls
739          * the aforementioned functions, and we need to call them from
740          * here as well.
741          *
742          * The solution is to make sure that we don't get interrupts or
743          * timers popping while we are in this function.
744          */
745         disable_irq(dev->irq);
746         local_bh_disable();
747
748         /*
749          * The dev's set_multicast_list function is only called when
750          * the device is up.  So, without checking, we know we need to
751          * Stop and Start the XEmac because it has already been
752          * started.  XEmac_Stop() will return an error if it is already
753          * stopped, but in this case we don't care so cast it to void
754          * to make it explicit
755          */
756         (void) XEmac_Stop(&lp->Emac);
757
758         Options = XEmac_GetOptions(&lp->Emac);
759
760         /* Clear out the bits we may set. */
761         Options &= ~(XEM_PROMISC_OPTION | XEM_MULTICAST_OPTION);
762
763         if (dev->flags & IFF_PROMISC)
764                 Options |= XEM_PROMISC_OPTION;
765 #if 0
766         else {
767                 /*
768                  * SAATODO: Xilinx is going to add multicast support to their
769                  * VxWorks adapter and OS independent layer.  After that is
770                  * done, this skeleton code should be fleshed out.  Note that
771                  * IFF_MULTICAST is being masked out from dev->flags in probe,
772                  * so that will need to be removed to actually do multidrop.
773                  */
774                 if ((dev->flags & IFF_ALLMULTI)
775                     || dev->mc_count > MAX_MULTICAST ? ? ?) {
776                         xemac_get_all_multicast ? ? ? ();
777                         Options |= XEM_MULTICAST_OPTION;
778                 } else if (dev->mc_count != 0) {
779                         struct dev_mc_list *mc;
780
781                         XEmac_MulticastClear(&lp->Emac);
782                         for (mc = dev->mc_list; mc; mc = mc->next)
783                                 XEmac_MulticastAdd(&lp->Emac, mc->dmi_addr);
784                         Options |= XEM_MULTICAST_OPTION;
785                 }
786         }
787 #endif
788
789         /*
790          * The following function will return an error if the EMAC is already
791          * started.  We know it isn't started so we can safely ignore the
792          * return value.  We cast it to void to make that explicit.
793          */
794         (void) XEmac_SetOptions(&lp->Emac, Options);
795
796         /*
797          * XEmac_Start returns an error when: it is already started, the send
798          * and receive handlers are not set, or a scatter-gather DMA list is
799          * missing.  None of these can happen at this point, so we cast the
800          * return to void to make that explicit.
801          */
802         (void) XEmac_Start(&lp->Emac);
803
804         /* All done, get those interrupts and timers going again. */
805         local_bh_enable();
806         enable_irq(dev->irq);
807 }
808
809 static int
810 xenet_ioctl(struct net_device *dev, struct ifreq *rq, int cmd)
811 {
812         struct net_local *lp = (struct net_local *) dev->priv;
813         /* mii_ioctl_data has 4 u16 fields: phy_id, reg_num, val_in & val_out */
814         struct mii_ioctl_data *data = (struct mii_ioctl_data *) &rq->ifr_data;
815
816         XStatus Result;
817
818         switch (cmd) {
819         case SIOCGMIIPHY:       /* Get address of MII PHY in use. */
820         case SIOCDEVPRIVATE:    /* for binary compat, remove in 2.5 */
821                 data->phy_id = lp->mii_addr;
822                 /* Fall Through */
823
824         case SIOCGMIIREG:       /* Read MII PHY register. */
825         case SIOCDEVPRIVATE + 1:        /* for binary compat, remove in 2.5 */
826                 if (data->phy_id > 31 || data->reg_num > 31)
827                         return -ENXIO;
828
829                 /* Stop the PHY timer to prevent reentrancy. */
830                 del_timer_sync(&lp->phy_timer);
831                 Result = XEmac_PhyRead(&lp->Emac, data->phy_id,
832                                        data->reg_num, &data->val_out);
833                 /* Start the PHY timer up again. */
834                 lp->phy_timer.expires = jiffies + 2*HZ;
835                 add_timer(&lp->phy_timer);
836
837                 if (Result != XST_SUCCESS) {
838                         printk(KERN_ERR
839                                "%s: Could not read from PHY, error=%d.\n",
840                                dev->name, Result);
841                         return (Result == XST_EMAC_MII_BUSY) ? -EBUSY : -EIO;
842                 }
843                 return 0;
844
845         case SIOCSMIIREG:       /* Write MII PHY register. */
846         case SIOCDEVPRIVATE + 2:        /* for binary compat, remove in 2.5 */
847                 if (!capable(CAP_NET_ADMIN))
848                         return -EPERM;
849
850                 if (data->phy_id > 31 || data->reg_num > 31)
851                         return -ENXIO;
852
853                 /* Stop the PHY timer to prevent reentrancy. */
854                 del_timer_sync(&lp->phy_timer);
855                 Result = XEmac_PhyWrite(&lp->Emac, data->phy_id,
856                                         data->reg_num, data->val_in);
857                 /* Start the PHY timer up again. */
858                 lp->phy_timer.expires = jiffies + 2*HZ;
859                 add_timer(&lp->phy_timer);
860
861                 if (Result != XST_SUCCESS) {
862                         printk(KERN_ERR
863                                "%s: Could not write to PHY, error=%d.\n",
864                                dev->name, Result);
865                         return (Result == XST_EMAC_MII_BUSY) ? -EBUSY : -EIO;
866                 }
867                 return 0;
868
869         default:
870                 return -EOPNOTSUPP;
871         }
872 }
873
874 static void
875 remove_head_dev(void)
876 {
877         struct net_local *lp;
878         struct net_device *dev;
879         XEmac_Config *cfg;
880
881         /* Pull the head off of dev_list. */
882         spin_lock(&dev_lock);
883         dev = dev_list;
884         lp = (struct net_local *) dev->priv;
885         dev_list = lp->next_dev;
886         spin_unlock(&dev_lock);
887
888         /* Put the base address back to the physical address. */
889         cfg = XEmac_GetConfig(lp->index);
890         iounmap((void *) cfg->BaseAddress);
891         cfg->BaseAddress = lp->save_BaseAddress;
892
893         /* Free up the memory. */
894         if (lp->saved_skb)
895                 dev_kfree_skb(lp->saved_skb);
896         kfree(lp);
897
898         unregister_netdev(dev);
899         kfree(dev);
900 }
901
902 static int __init
903 probe(int index)
904 {
905         static const unsigned long remap_size
906             = XPAR_EMAC_0_HIGHADDR - XPAR_EMAC_0_BASEADDR + 1;
907         struct net_device *dev;
908         struct net_local *lp;
909         XEmac_Config *cfg;
910         unsigned int irq;
911         u32 maddr;
912
913         switch (index) {
914 #if defined(XPAR_INTC_0_EMAC_0_VEC_ID)
915         case 0:
916                 irq = 31 - XPAR_INTC_0_EMAC_0_VEC_ID;
917                 break;
918 #if defined(XPAR_INTC_0_EMAC_1_VEC_ID)
919         case 1:
920                 irq = 31 - XPAR_INTC_0_EMAC_1_VEC_ID;
921                 break;
922 #if defined(XPAR_INTC_0_EMAC_2_VEC_ID)
923         case 2:
924                 irq = 31 - XPAR_INTC_0_EMAC_2_VEC_ID;
925                 break;
926 #if defined(XPAR_INTC_0_EMAC_3_VEC_ID)
927 #error Edit this file to add more devices.
928 #endif                          /* 3 */
929 #endif                          /* 2 */
930 #endif                          /* 1 */
931 #endif                          /* 0 */
932         default:
933                 return -ENODEV;
934         }
935
936         /* Find the config for our device. */
937         cfg = XEmac_GetConfig(index);
938         if (!cfg)
939                 return -ENODEV;
940
941         dev = init_etherdev(0, sizeof (struct net_local));
942         if (!dev) {
943                 printk(KERN_ERR "Could not allocate Xilinx enet device %d.\n",
944                        index);
945                 return -ENOMEM;
946         }
947         SET_MODULE_OWNER(dev);
948
949         ether_setup(dev);
950         dev->irq = irq;
951
952         /* Initialize our private data. */
953         lp = (struct net_local *) dev->priv;
954         memset(lp, 0, sizeof (struct net_local));
955         lp->index = index;
956         spin_lock_init(&lp->skb_lock);
957
958         /* Make it the head of dev_list. */
959         spin_lock(&dev_lock);
960         lp->next_dev = dev_list;
961         dev_list = dev;
962         spin_unlock(&dev_lock);
963
964         /* Change the addresses to be virtual; save the old ones to restore. */
965         lp->save_BaseAddress = cfg->BaseAddress;
966         cfg->BaseAddress = (u32) ioremap(lp->save_BaseAddress, remap_size);
967
968         if (XEmac_Initialize(&lp->Emac, cfg->DeviceId) != XST_SUCCESS) {
969                 printk(KERN_ERR "%s: Could not initialize device.\n",
970                        dev->name);
971                 remove_head_dev();
972                 return -ENODEV;
973         }
974
975         memcpy(dev->dev_addr, ((bd_t *) __res)->bi_enetaddr, 6);
976         if (XEmac_SetMacAddress(&lp->Emac, dev->dev_addr) != XST_SUCCESS) {
977                 /* should not fail right after an initialize */
978                 printk(KERN_ERR "%s: Could not set MAC address.\n", dev->name);
979                 remove_head_dev();
980                 return -EIO;
981         }
982
983         if (XEmac_mIsSgDma(&lp->Emac)) {
984                 /*
985                  * SAATODO: Currently scatter-gather DMA does not work.  At
986                  * some point Xilinx is going to get that working in their
987                  * code and then this driver should be enhanced in a similar
988                  * fashion.
989                  */
990                 printk(KERN_ERR "%s: Scatter gather not supported yet.\n",
991                        dev->name);
992                 remove_head_dev();
993                 return -EIO;
994                 /* lp->Isr = XEmac_IntrHandlerDma; */
995         } else {
996                 XEmac_SetFifoRecvHandler(&lp->Emac, dev, FifoRecvHandler);
997                 XEmac_SetFifoSendHandler(&lp->Emac, dev, FifoSendHandler);
998                 dev->hard_start_xmit = xenet_FifoSend;
999                 lp->Isr = XEmac_IntrHandlerFifo;
1000         }
1001         XEmac_SetErrorHandler(&lp->Emac, dev, ErrorHandler);
1002
1003
1004         /* Scan to find the PHY. */
1005         lp->mii_addr = 0xFF;
1006         for (maddr = 0; maddr < 31; maddr++) {
1007                 XStatus Result;
1008                 u16 reg;
1009
1010                 Result = XEmac_PhyRead(&lp->Emac, maddr, MII_BMCR, &reg);
1011                 /*
1012                  * XEmac_PhyRead is currently returning XST_SUCCESS even
1013                  * when reading from non-existent addresses.  Work
1014                  * around this by doing a primitive validation on the
1015                  * control word we get back.
1016                  */
1017                 if (Result == XST_SUCCESS && (reg & BMCR_RESV) == 0) {
1018                         lp->mii_addr = maddr;
1019                         break;
1020                 }
1021         }
1022         if (lp->mii_addr == 0xFF) {
1023                 lp->mii_addr = 0;
1024                 printk(KERN_WARNING
1025                        "%s: No PHY detected.  Assuming a PHY at address %d.\n",
1026                        dev->name, lp->mii_addr);
1027         }
1028
1029         dev->open = xenet_open;
1030         dev->stop = xenet_close;
1031         dev->get_stats = xenet_get_stats;
1032         dev->flags &= ~IFF_MULTICAST;
1033         dev->set_multicast_list = xenet_set_multicast_list;
1034         dev->do_ioctl = xenet_ioctl;
1035         dev->tx_timeout = xenet_tx_timeout;
1036         dev->watchdog_timeo = TX_TIMEOUT;
1037
1038         printk(KERN_INFO
1039                "%s: Xilinx EMAC #%d at 0x%08X mapped to 0x%08X, irq=%d\n",
1040                dev->name, index,
1041                lp->save_BaseAddress, cfg->BaseAddress, dev->irq);
1042         return 0;
1043 }
1044 static int __init
1045 xenet_init(void)
1046 {
1047         int index = 0;
1048
1049         while (probe(index++) == 0) ;
1050         /* If we found at least one, report success. */
1051         return (index > 1) ? 0 : -ENODEV;
1052 }
1053
1054 static void __exit
1055 xenet_cleanup(void)
1056 {
1057         while (dev_list)
1058                 remove_head_dev();
1059 }
1060
1061 EXPORT_NO_SYMBOLS;
1062
1063 module_init(xenet_init);
1064 module_exit(xenet_cleanup);