Merge branch 'master' of git://git.denx.de/u-boot-at91
[platform/kernel/u-boot.git] / net / net.c
1 /*
2  *      Copied from Linux Monitor (LiMon) - Networking.
3  *
4  *      Copyright 1994 - 2000 Neil Russell.
5  *      (See License)
6  *      Copyright 2000 Roland Borde
7  *      Copyright 2000 Paolo Scaffardi
8  *      Copyright 2000-2002 Wolfgang Denk, wd@denx.de
9  */
10
11 /*
12  * General Desription:
13  *
14  * The user interface supports commands for BOOTP, RARP, and TFTP.
15  * Also, we support ARP internally. Depending on available data,
16  * these interact as follows:
17  *
18  * BOOTP:
19  *
20  *      Prerequisites:  - own ethernet address
21  *      We want:        - own IP address
22  *                      - TFTP server IP address
23  *                      - name of bootfile
24  *      Next step:      ARP
25  *
26  * RARP:
27  *
28  *      Prerequisites:  - own ethernet address
29  *      We want:        - own IP address
30  *                      - TFTP server IP address
31  *      Next step:      ARP
32  *
33  * ARP:
34  *
35  *      Prerequisites:  - own ethernet address
36  *                      - own IP address
37  *                      - TFTP server IP address
38  *      We want:        - TFTP server ethernet address
39  *      Next step:      TFTP
40  *
41  * DHCP:
42  *
43  *     Prerequisites:   - own ethernet address
44  *     We want:         - IP, Netmask, ServerIP, Gateway IP
45  *                      - bootfilename, lease time
46  *     Next step:       - TFTP
47  *
48  * TFTP:
49  *
50  *      Prerequisites:  - own ethernet address
51  *                      - own IP address
52  *                      - TFTP server IP address
53  *                      - TFTP server ethernet address
54  *                      - name of bootfile (if unknown, we use a default name
55  *                        derived from our own IP address)
56  *      We want:        - load the boot file
57  *      Next step:      none
58  *
59  * NFS:
60  *
61  *      Prerequisites:  - own ethernet address
62  *                      - own IP address
63  *                      - name of bootfile (if unknown, we use a default name
64  *                        derived from our own IP address)
65  *      We want:        - load the boot file
66  *      Next step:      none
67  *
68  * SNTP:
69  *
70  *      Prerequisites:  - own ethernet address
71  *                      - own IP address
72  *      We want:        - network time
73  *      Next step:      none
74  */
75
76
77 #include <common.h>
78 #include <watchdog.h>
79 #include <command.h>
80 #include <net.h>
81 #include "bootp.h"
82 #include "tftp.h"
83 #include "rarp.h"
84 #include "nfs.h"
85 #ifdef CONFIG_STATUS_LED
86 #include <status_led.h>
87 #include <miiphy.h>
88 #endif
89 #if defined(CONFIG_CMD_SNTP)
90 #include "sntp.h"
91 #endif
92 #if defined(CONFIG_CDP_VERSION)
93 #include <timestamp.h>
94 #endif
95
96 #if defined(CONFIG_CMD_NET)
97
98 DECLARE_GLOBAL_DATA_PTR;
99
100 #ifndef CONFIG_ARP_TIMEOUT
101 # define ARP_TIMEOUT            5000UL  /* Milliseconds before trying ARP again */
102 #else
103 # define ARP_TIMEOUT            CONFIG_ARP_TIMEOUT
104 #endif
105
106
107 #ifndef CONFIG_NET_RETRY_COUNT
108 # define ARP_TIMEOUT_COUNT      5       /* # of timeouts before giving up  */
109 #else
110 # define ARP_TIMEOUT_COUNT      CONFIG_NET_RETRY_COUNT
111 #endif
112
113 #if 0
114 #define ET_DEBUG
115 #endif
116
117 /** BOOTP EXTENTIONS **/
118
119 IPaddr_t        NetOurSubnetMask=0;             /* Our subnet mask (0=unknown)  */
120 IPaddr_t        NetOurGatewayIP=0;              /* Our gateways IP address      */
121 IPaddr_t        NetOurDNSIP=0;                  /* Our DNS IP address           */
122 #if defined(CONFIG_BOOTP_DNS2)
123 IPaddr_t        NetOurDNS2IP=0;                 /* Our 2nd DNS IP address       */
124 #endif
125 char            NetOurNISDomain[32]={0,};       /* Our NIS domain               */
126 char            NetOurHostName[32]={0,};        /* Our hostname                 */
127 char            NetOurRootPath[64]={0,};        /* Our bootpath                 */
128 ushort          NetBootFileSize=0;              /* Our bootfile size in blocks  */
129
130 #ifdef CONFIG_MCAST_TFTP        /* Multicast TFTP */
131 IPaddr_t Mcast_addr;
132 #endif
133
134 /** END OF BOOTP EXTENTIONS **/
135
136 ulong           NetBootFileXferSize;    /* The actual transferred size of the bootfile (in bytes) */
137 uchar           NetOurEther[6];         /* Our ethernet address                 */
138 uchar           NetServerEther[6] =     /* Boot server enet address             */
139                         { 0, 0, 0, 0, 0, 0 };
140 IPaddr_t        NetOurIP;               /* Our IP addr (0 = unknown)            */
141 IPaddr_t        NetServerIP;            /* Server IP addr (0 = unknown)         */
142 volatile uchar *NetRxPkt;               /* Current receive packet               */
143 int             NetRxPktLen;            /* Current rx packet length             */
144 unsigned        NetIPID;                /* IP packet ID                         */
145 uchar           NetBcastAddr[6] =       /* Ethernet bcast address               */
146                         { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
147 uchar           NetEtherNullAddr[6] =
148                         { 0, 0, 0, 0, 0, 0 };
149 #ifdef CONFIG_API
150 void            (*push_packet)(volatile void *, int len) = 0;
151 #endif
152 #if defined(CONFIG_CMD_CDP)
153 uchar           NetCDPAddr[6] =         /* Ethernet bcast address               */
154                         { 0x01, 0x00, 0x0c, 0xcc, 0xcc, 0xcc };
155 #endif
156 int             NetState;               /* Network loop state                   */
157 #ifdef CONFIG_NET_MULTI
158 int             NetRestartWrap = 0;     /* Tried all network devices            */
159 static int      NetRestarted = 0;       /* Network loop restarted               */
160 static int      NetDevExists = 0;       /* At least one device configured       */
161 #endif
162
163 /* XXX in both little & big endian machines 0xFFFF == ntohs(-1) */
164 ushort          NetOurVLAN = 0xFFFF;            /* default is without VLAN      */
165 ushort          NetOurNativeVLAN = 0xFFFF;      /* ditto                        */
166
167 char            BootFile[128];          /* Boot File name                       */
168
169 #if defined(CONFIG_CMD_PING)
170 IPaddr_t        NetPingIP;              /* the ip address to ping               */
171
172 static void PingStart(void);
173 #endif
174
175 #if defined(CONFIG_CMD_CDP)
176 static void CDPStart(void);
177 #endif
178
179 #if defined(CONFIG_CMD_SNTP)
180 IPaddr_t        NetNtpServerIP;         /* NTP server IP address                */
181 int             NetTimeOffset=0;        /* offset time from UTC                 */
182 #endif
183
184 #ifdef CONFIG_NETCONSOLE
185 void NcStart(void);
186 int nc_input_packet(uchar *pkt, unsigned dest, unsigned src, unsigned len);
187 #endif
188
189 volatile uchar  PktBuf[(PKTBUFSRX+1) * PKTSIZE_ALIGN + PKTALIGN];
190
191 volatile uchar *NetRxPackets[PKTBUFSRX]; /* Receive packets                     */
192
193 static rxhand_f *packetHandler;         /* Current RX packet handler            */
194 static thand_f *timeHandler;            /* Current timeout handler              */
195 static ulong    timeStart;              /* Time base value                      */
196 static ulong    timeDelta;              /* Current timeout value                */
197 volatile uchar *NetTxPacket = 0;        /* THE transmit packet                  */
198
199 static int net_check_prereq (proto_t protocol);
200
201 /**********************************************************************/
202
203 IPaddr_t        NetArpWaitPacketIP;
204 IPaddr_t        NetArpWaitReplyIP;
205 uchar          *NetArpWaitPacketMAC;    /* MAC address of waiting packet's destination  */
206 uchar          *NetArpWaitTxPacket;     /* THE transmit packet                  */
207 int             NetArpWaitTxPacketSize;
208 uchar           NetArpWaitPacketBuf[PKTSIZE_ALIGN + PKTALIGN];
209 ulong           NetArpWaitTimerStart;
210 int             NetArpWaitTry;
211
212 void ArpRequest (void)
213 {
214         int i;
215         volatile uchar *pkt;
216         ARP_t *arp;
217
218 #ifdef ET_DEBUG
219         printf ("ARP broadcast %d\n", NetArpWaitTry);
220 #endif
221         pkt = NetTxPacket;
222
223         pkt += NetSetEther (pkt, NetBcastAddr, PROT_ARP);
224
225         arp = (ARP_t *) pkt;
226
227         arp->ar_hrd = htons (ARP_ETHER);
228         arp->ar_pro = htons (PROT_IP);
229         arp->ar_hln = 6;
230         arp->ar_pln = 4;
231         arp->ar_op = htons (ARPOP_REQUEST);
232
233         memcpy (&arp->ar_data[0], NetOurEther, 6);              /* source ET addr       */
234         NetWriteIP ((uchar *) & arp->ar_data[6], NetOurIP);     /* source IP addr       */
235         for (i = 10; i < 16; ++i) {
236                 arp->ar_data[i] = 0;                            /* dest ET addr = 0     */
237         }
238
239         if ((NetArpWaitPacketIP & NetOurSubnetMask) !=
240             (NetOurIP & NetOurSubnetMask)) {
241                 if (NetOurGatewayIP == 0) {
242                         puts ("## Warning: gatewayip needed but not set\n");
243                         NetArpWaitReplyIP = NetArpWaitPacketIP;
244                 } else {
245                         NetArpWaitReplyIP = NetOurGatewayIP;
246                 }
247         } else {
248                 NetArpWaitReplyIP = NetArpWaitPacketIP;
249         }
250
251         NetWriteIP ((uchar *) & arp->ar_data[16], NetArpWaitReplyIP);
252         (void) eth_send (NetTxPacket, (pkt - NetTxPacket) + ARP_HDR_SIZE);
253 }
254
255 void ArpTimeoutCheck(void)
256 {
257         ulong t;
258
259         if (!NetArpWaitPacketIP)
260                 return;
261
262         t = get_timer(0);
263
264         /* check for arp timeout */
265         if ((t - NetArpWaitTimerStart) > ARP_TIMEOUT) {
266                 NetArpWaitTry++;
267
268                 if (NetArpWaitTry >= ARP_TIMEOUT_COUNT) {
269                         puts ("\nARP Retry count exceeded; starting again\n");
270                         NetArpWaitTry = 0;
271                         NetStartAgain();
272                 } else {
273                         NetArpWaitTimerStart = t;
274                         ArpRequest();
275                 }
276         }
277 }
278
279 /**********************************************************************/
280 /*
281  *      Main network processing loop.
282  */
283
284 int
285 NetLoop(proto_t protocol)
286 {
287         bd_t *bd = gd->bd;
288
289 #ifdef CONFIG_NET_MULTI
290         NetRestarted = 0;
291         NetDevExists = 0;
292 #endif
293
294         /* XXX problem with bss workaround */
295         NetArpWaitPacketMAC = NULL;
296         NetArpWaitTxPacket = NULL;
297         NetArpWaitPacketIP = 0;
298         NetArpWaitReplyIP = 0;
299         NetArpWaitTxPacket = NULL;
300         NetTxPacket = NULL;
301
302         if (!NetTxPacket) {
303                 int     i;
304                 /*
305                  *      Setup packet buffers, aligned correctly.
306                  */
307                 NetTxPacket = &PktBuf[0] + (PKTALIGN - 1);
308                 NetTxPacket -= (ulong)NetTxPacket % PKTALIGN;
309                 for (i = 0; i < PKTBUFSRX; i++) {
310                         NetRxPackets[i] = NetTxPacket + (i+1)*PKTSIZE_ALIGN;
311                 }
312         }
313
314         if (!NetArpWaitTxPacket) {
315                 NetArpWaitTxPacket = &NetArpWaitPacketBuf[0] + (PKTALIGN - 1);
316                 NetArpWaitTxPacket -= (ulong)NetArpWaitTxPacket % PKTALIGN;
317                 NetArpWaitTxPacketSize = 0;
318         }
319
320         eth_halt();
321 #ifdef CONFIG_NET_MULTI
322         eth_set_current();
323 #endif
324         if (eth_init(bd) < 0) {
325                 eth_halt();
326                 return(-1);
327         }
328
329 restart:
330 #ifdef CONFIG_NET_MULTI
331         memcpy (NetOurEther, eth_get_dev()->enetaddr, 6);
332 #else
333         memcpy (NetOurEther, bd->bi_enetaddr, 6);
334 #endif
335
336         NetState = NETLOOP_CONTINUE;
337
338         /*
339          *      Start the ball rolling with the given start function.  From
340          *      here on, this code is a state machine driven by received
341          *      packets and timer events.
342          */
343
344         switch (protocol) {
345 #if defined(CONFIG_CMD_NFS)
346         case NFS:
347 #endif
348 #if defined(CONFIG_CMD_PING)
349         case PING:
350 #endif
351 #if defined(CONFIG_CMD_SNTP)
352         case SNTP:
353 #endif
354         case NETCONS:
355         case TFTP:
356                 NetCopyIP(&NetOurIP, &bd->bi_ip_addr);
357                 NetOurGatewayIP = getenv_IPaddr ("gatewayip");
358                 NetOurSubnetMask= getenv_IPaddr ("netmask");
359                 NetOurVLAN = getenv_VLAN("vlan");
360                 NetOurNativeVLAN = getenv_VLAN("nvlan");
361
362                 switch (protocol) {
363 #if defined(CONFIG_CMD_NFS)
364                 case NFS:
365 #endif
366                 case NETCONS:
367                 case TFTP:
368                         NetServerIP = getenv_IPaddr ("serverip");
369                         break;
370 #if defined(CONFIG_CMD_PING)
371                 case PING:
372                         /* nothing */
373                         break;
374 #endif
375 #if defined(CONFIG_CMD_SNTP)
376                 case SNTP:
377                         /* nothing */
378                         break;
379 #endif
380                 default:
381                         break;
382                 }
383
384                 break;
385         case BOOTP:
386         case RARP:
387                 /*
388                  * initialize our IP addr to 0 in order to accept ANY
389                  * IP addr assigned to us by the BOOTP / RARP server
390                  */
391                 NetOurIP = 0;
392                 NetServerIP = getenv_IPaddr ("serverip");
393                 NetOurVLAN = getenv_VLAN("vlan");       /* VLANs must be read */
394                 NetOurNativeVLAN = getenv_VLAN("nvlan");
395         case CDP:
396                 NetOurVLAN = getenv_VLAN("vlan");       /* VLANs must be read */
397                 NetOurNativeVLAN = getenv_VLAN("nvlan");
398                 break;
399         default:
400                 break;
401         }
402
403         switch (net_check_prereq (protocol)) {
404         case 1:
405                 /* network not configured */
406                 eth_halt();
407                 return (-1);
408
409 #ifdef CONFIG_NET_MULTI
410         case 2:
411                 /* network device not configured */
412                 break;
413 #endif /* CONFIG_NET_MULTI */
414
415         case 0:
416 #ifdef CONFIG_NET_MULTI
417                 NetDevExists = 1;
418 #endif
419                 switch (protocol) {
420                 case TFTP:
421                         /* always use ARP to get server ethernet address */
422                         TftpStart();
423                         break;
424
425 #if defined(CONFIG_CMD_DHCP)
426                 case DHCP:
427                         /* Start with a clean slate... */
428                         BootpTry = 0;
429                         NetOurIP = 0;
430                         NetServerIP = getenv_IPaddr ("serverip");
431                         DhcpRequest();          /* Basically same as BOOTP */
432                         break;
433 #endif
434
435                 case BOOTP:
436                         BootpTry = 0;
437                         BootpRequest ();
438                         break;
439
440                 case RARP:
441                         RarpTry = 0;
442                         RarpRequest ();
443                         break;
444 #if defined(CONFIG_CMD_PING)
445                 case PING:
446                         PingStart();
447                         break;
448 #endif
449 #if defined(CONFIG_CMD_NFS)
450                 case NFS:
451                         NfsStart();
452                         break;
453 #endif
454 #if defined(CONFIG_CMD_CDP)
455                 case CDP:
456                         CDPStart();
457                         break;
458 #endif
459 #ifdef CONFIG_NETCONSOLE
460                 case NETCONS:
461                         NcStart();
462                         break;
463 #endif
464 #if defined(CONFIG_CMD_SNTP)
465                 case SNTP:
466                         SntpStart();
467                         break;
468 #endif
469                 default:
470                         break;
471                 }
472
473                 NetBootFileXferSize = 0;
474                 break;
475         }
476
477 #if defined(CONFIG_MII) || defined(CONFIG_CMD_MII)
478 #if defined(CONFIG_SYS_FAULT_ECHO_LINK_DOWN) && defined(CONFIG_STATUS_LED) && defined(STATUS_LED_RED)
479         /*
480          * Echo the inverted link state to the fault LED.
481          */
482         if(miiphy_link(eth_get_dev()->name, CONFIG_SYS_FAULT_MII_ADDR)) {
483                 status_led_set (STATUS_LED_RED, STATUS_LED_OFF);
484         } else {
485                 status_led_set (STATUS_LED_RED, STATUS_LED_ON);
486         }
487 #endif /* CONFIG_SYS_FAULT_ECHO_LINK_DOWN, ... */
488 #endif /* CONFIG_MII, ... */
489
490         /*
491          *      Main packet reception loop.  Loop receiving packets until
492          *      someone sets `NetState' to a state that terminates.
493          */
494         for (;;) {
495                 WATCHDOG_RESET();
496 #ifdef CONFIG_SHOW_ACTIVITY
497                 {
498                         extern void show_activity(int arg);
499                         show_activity(1);
500                 }
501 #endif
502                 /*
503                  *      Check the ethernet for a new packet.  The ethernet
504                  *      receive routine will process it.
505                  */
506                 eth_rx();
507
508                 /*
509                  *      Abort if ctrl-c was pressed.
510                  */
511                 if (ctrlc()) {
512                         eth_halt();
513                         puts ("\nAbort\n");
514                         return (-1);
515                 }
516
517                 ArpTimeoutCheck();
518
519                 /*
520                  *      Check for a timeout, and run the timeout handler
521                  *      if we have one.
522                  */
523                 if (timeHandler && ((get_timer(0) - timeStart) > timeDelta)) {
524                         thand_f *x;
525
526 #if defined(CONFIG_MII) || defined(CONFIG_CMD_MII)
527 #  if defined(CONFIG_SYS_FAULT_ECHO_LINK_DOWN) && \
528       defined(CONFIG_STATUS_LED) &&        \
529       defined(STATUS_LED_RED)
530                         /*
531                          * Echo the inverted link state to the fault LED.
532                          */
533                         if(miiphy_link(eth_get_dev()->name, CONFIG_SYS_FAULT_MII_ADDR)) {
534                                 status_led_set (STATUS_LED_RED, STATUS_LED_OFF);
535                         } else {
536                                 status_led_set (STATUS_LED_RED, STATUS_LED_ON);
537                         }
538 #  endif /* CONFIG_SYS_FAULT_ECHO_LINK_DOWN, ... */
539 #endif /* CONFIG_MII, ... */
540                         x = timeHandler;
541                         timeHandler = (thand_f *)0;
542                         (*x)();
543                 }
544
545
546                 switch (NetState) {
547
548                 case NETLOOP_RESTART:
549 #ifdef CONFIG_NET_MULTI
550                         NetRestarted = 1;
551 #endif
552                         goto restart;
553
554                 case NETLOOP_SUCCESS:
555                         if (NetBootFileXferSize > 0) {
556                                 char buf[20];
557                                 printf("Bytes transferred = %ld (%lx hex)\n",
558                                         NetBootFileXferSize,
559                                         NetBootFileXferSize);
560                                 sprintf(buf, "%lX", NetBootFileXferSize);
561                                 setenv("filesize", buf);
562
563                                 sprintf(buf, "%lX", (unsigned long)load_addr);
564                                 setenv("fileaddr", buf);
565                         }
566                         eth_halt();
567                         return NetBootFileXferSize;
568
569                 case NETLOOP_FAIL:
570                         return (-1);
571                 }
572         }
573 }
574
575 /**********************************************************************/
576
577 static void
578 startAgainTimeout(void)
579 {
580         NetState = NETLOOP_RESTART;
581 }
582
583 static void
584 startAgainHandler(uchar * pkt, unsigned dest, unsigned src, unsigned len)
585 {
586         /* Totally ignore the packet */
587 }
588
589 void NetStartAgain (void)
590 {
591         char *nretry;
592         int noretry = 0, once = 0;
593
594         if ((nretry = getenv ("netretry")) != NULL) {
595                 noretry = (strcmp (nretry, "no") == 0);
596                 once = (strcmp (nretry, "once") == 0);
597         }
598         if (noretry) {
599                 eth_halt ();
600                 NetState = NETLOOP_FAIL;
601                 return;
602         }
603 #ifndef CONFIG_NET_MULTI
604         NetSetTimeout (10000UL, startAgainTimeout);
605         NetSetHandler (startAgainHandler);
606 #else   /* !CONFIG_NET_MULTI*/
607         eth_halt ();
608 #if !defined(CONFIG_NET_DO_NOT_TRY_ANOTHER)
609         eth_try_another (!NetRestarted);
610 #endif
611         eth_init (gd->bd);
612         if (NetRestartWrap) {
613                 NetRestartWrap = 0;
614                 if (NetDevExists && !once) {
615                         NetSetTimeout (10000UL, startAgainTimeout);
616                         NetSetHandler (startAgainHandler);
617                 } else {
618                         NetState = NETLOOP_FAIL;
619                 }
620         } else {
621                 NetState = NETLOOP_RESTART;
622         }
623 #endif  /* CONFIG_NET_MULTI */
624 }
625
626 /**********************************************************************/
627 /*
628  *      Miscelaneous bits.
629  */
630
631 void
632 NetSetHandler(rxhand_f * f)
633 {
634         packetHandler = f;
635 }
636
637
638 void
639 NetSetTimeout(ulong iv, thand_f * f)
640 {
641         if (iv == 0) {
642                 timeHandler = (thand_f *)0;
643         } else {
644                 timeHandler = f;
645                 timeStart = get_timer(0);
646                 timeDelta = iv;
647         }
648 }
649
650
651 void
652 NetSendPacket(volatile uchar * pkt, int len)
653 {
654         (void) eth_send(pkt, len);
655 }
656
657 int
658 NetSendUDPPacket(uchar *ether, IPaddr_t dest, int dport, int sport, int len)
659 {
660         uchar *pkt;
661
662         /* convert to new style broadcast */
663         if (dest == 0)
664                 dest = 0xFFFFFFFF;
665
666         /* if broadcast, make the ether address a broadcast and don't do ARP */
667         if (dest == 0xFFFFFFFF)
668                 ether = NetBcastAddr;
669
670         /* if MAC address was not discovered yet, save the packet and do an ARP request */
671         if (memcmp(ether, NetEtherNullAddr, 6) == 0) {
672
673 #ifdef ET_DEBUG
674                 printf("sending ARP for %08lx\n", dest);
675 #endif
676                 NetArpWaitPacketIP = dest;
677                 NetArpWaitPacketMAC = ether;
678
679                 pkt = NetArpWaitTxPacket;
680                 pkt += NetSetEther (pkt, NetArpWaitPacketMAC, PROT_IP);
681
682                 NetSetIP (pkt, dest, dport, sport, len);
683                 memcpy(pkt + IP_HDR_SIZE, (uchar *)NetTxPacket + (pkt - (uchar *)NetArpWaitTxPacket) + IP_HDR_SIZE, len);
684
685                 /* size of the waiting packet */
686                 NetArpWaitTxPacketSize = (pkt - NetArpWaitTxPacket) + IP_HDR_SIZE + len;
687
688                 /* and do the ARP request */
689                 NetArpWaitTry = 1;
690                 NetArpWaitTimerStart = get_timer(0);
691                 ArpRequest();
692                 return 1;       /* waiting */
693         }
694
695 #ifdef ET_DEBUG
696         printf("sending UDP to %08lx/%02x:%02x:%02x:%02x:%02x:%02x\n",
697                 dest, ether[0], ether[1], ether[2], ether[3], ether[4], ether[5]);
698 #endif
699
700         pkt = (uchar *)NetTxPacket;
701         pkt += NetSetEther (pkt, ether, PROT_IP);
702         NetSetIP (pkt, dest, dport, sport, len);
703         (void) eth_send(NetTxPacket, (pkt - NetTxPacket) + IP_HDR_SIZE + len);
704
705         return 0;       /* transmitted */
706 }
707
708 #if defined(CONFIG_CMD_PING)
709 static ushort PingSeqNo;
710
711 int PingSend(void)
712 {
713         static uchar mac[6];
714         volatile IP_t *ip;
715         volatile ushort *s;
716         uchar *pkt;
717
718         /* XXX always send arp request */
719
720         memcpy(mac, NetEtherNullAddr, 6);
721
722 #ifdef ET_DEBUG
723         printf("sending ARP for %08lx\n", NetPingIP);
724 #endif
725
726         NetArpWaitPacketIP = NetPingIP;
727         NetArpWaitPacketMAC = mac;
728
729         pkt = NetArpWaitTxPacket;
730         pkt += NetSetEther(pkt, mac, PROT_IP);
731
732         ip = (volatile IP_t *)pkt;
733
734         /*
735          *      Construct an IP and ICMP header.  (need to set no fragment bit - XXX)
736          */
737         ip->ip_hl_v  = 0x45;            /* IP_HDR_SIZE / 4 (not including UDP) */
738         ip->ip_tos   = 0;
739         ip->ip_len   = htons(IP_HDR_SIZE_NO_UDP + 8);
740         ip->ip_id    = htons(NetIPID++);
741         ip->ip_off   = htons(IP_FLAGS_DFRAG);   /* Don't fragment */
742         ip->ip_ttl   = 255;
743         ip->ip_p     = 0x01;            /* ICMP */
744         ip->ip_sum   = 0;
745         NetCopyIP((void*)&ip->ip_src, &NetOurIP); /* already in network byte order */
746         NetCopyIP((void*)&ip->ip_dst, &NetPingIP);         /* - "" - */
747         ip->ip_sum   = ~NetCksum((uchar *)ip, IP_HDR_SIZE_NO_UDP / 2);
748
749         s = &ip->udp_src;               /* XXX ICMP starts here */
750         s[0] = htons(0x0800);           /* echo-request, code */
751         s[1] = 0;                       /* checksum */
752         s[2] = 0;                       /* identifier */
753         s[3] = htons(PingSeqNo++);      /* sequence number */
754         s[1] = ~NetCksum((uchar *)s, 8/2);
755
756         /* size of the waiting packet */
757         NetArpWaitTxPacketSize = (pkt - NetArpWaitTxPacket) + IP_HDR_SIZE_NO_UDP + 8;
758
759         /* and do the ARP request */
760         NetArpWaitTry = 1;
761         NetArpWaitTimerStart = get_timer(0);
762         ArpRequest();
763         return 1;       /* waiting */
764 }
765
766 static void
767 PingTimeout (void)
768 {
769         eth_halt();
770         NetState = NETLOOP_FAIL;        /* we did not get the reply */
771 }
772
773 static void
774 PingHandler (uchar * pkt, unsigned dest, unsigned src, unsigned len)
775 {
776         IPaddr_t tmp;
777         volatile IP_t *ip = (volatile IP_t *)pkt;
778
779         tmp = NetReadIP((void *)&ip->ip_src);
780         if (tmp != NetPingIP)
781                 return;
782
783         NetState = NETLOOP_SUCCESS;
784 }
785
786 static void PingStart(void)
787 {
788 #if defined(CONFIG_NET_MULTI)
789         printf ("Using %s device\n", eth_get_name());
790 #endif  /* CONFIG_NET_MULTI */
791         NetSetTimeout (10000UL, PingTimeout);
792         NetSetHandler (PingHandler);
793
794         PingSend();
795 }
796 #endif
797
798 #if defined(CONFIG_CMD_CDP)
799
800 #define CDP_DEVICE_ID_TLV               0x0001
801 #define CDP_ADDRESS_TLV                 0x0002
802 #define CDP_PORT_ID_TLV                 0x0003
803 #define CDP_CAPABILITIES_TLV            0x0004
804 #define CDP_VERSION_TLV                 0x0005
805 #define CDP_PLATFORM_TLV                0x0006
806 #define CDP_NATIVE_VLAN_TLV             0x000a
807 #define CDP_APPLIANCE_VLAN_TLV          0x000e
808 #define CDP_TRIGGER_TLV                 0x000f
809 #define CDP_POWER_CONSUMPTION_TLV       0x0010
810 #define CDP_SYSNAME_TLV                 0x0014
811 #define CDP_SYSOBJECT_TLV               0x0015
812 #define CDP_MANAGEMENT_ADDRESS_TLV      0x0016
813
814 #define CDP_TIMEOUT                     250UL   /* one packet every 250ms */
815
816 static int CDPSeq;
817 static int CDPOK;
818
819 ushort CDPNativeVLAN;
820 ushort CDPApplianceVLAN;
821
822 static const uchar CDP_SNAP_hdr[8] = { 0xAA, 0xAA, 0x03, 0x00, 0x00, 0x0C, 0x20, 0x00 };
823
824 static ushort CDP_compute_csum(const uchar *buff, ushort len)
825 {
826         ushort csum;
827         int     odd;
828         ulong   result = 0;
829         ushort  leftover;
830         ushort *p;
831
832         if (len > 0) {
833                 odd = 1 & (ulong)buff;
834                 if (odd) {
835                         result = *buff << 8;
836                         len--;
837                         buff++;
838                 }
839                 while (len > 1) {
840                         p = (ushort *)buff;
841                         result += *p++;
842                         buff = (uchar *)p;
843                         if (result & 0x80000000)
844                                 result = (result & 0xFFFF) + (result >> 16);
845                         len -= 2;
846                 }
847                 if (len) {
848                         leftover = (signed short)(*(const signed char *)buff);
849                         /* CISCO SUCKS big time! (and blows too):
850                          * CDP uses the IP checksum algorithm with a twist;
851                          * for the last byte it *sign* extends and sums.
852                          */
853                         result = (result & 0xffff0000) | ((result + leftover) & 0x0000ffff);
854                 }
855                 while (result >> 16)
856                         result = (result & 0xFFFF) + (result >> 16);
857
858                 if (odd)
859                         result = ((result >> 8) & 0xff) | ((result & 0xff) << 8);
860         }
861
862         /* add up 16-bit and 17-bit words for 17+c bits */
863         result = (result & 0xffff) + (result >> 16);
864         /* add up 16-bit and 2-bit for 16+c bit */
865         result = (result & 0xffff) + (result >> 16);
866         /* add up carry.. */
867         result = (result & 0xffff) + (result >> 16);
868
869         /* negate */
870         csum = ~(ushort)result;
871
872         /* run time endian detection */
873         if (csum != htons(csum))        /* little endian */
874                 csum = htons(csum);
875
876         return csum;
877 }
878
879 int CDPSendTrigger(void)
880 {
881         volatile uchar *pkt;
882         volatile ushort *s;
883         volatile ushort *cp;
884         Ethernet_t *et;
885         int len;
886         ushort chksum;
887 #if defined(CONFIG_CDP_DEVICE_ID) || defined(CONFIG_CDP_PORT_ID)   || \
888     defined(CONFIG_CDP_VERSION)   || defined(CONFIG_CDP_PLATFORM)
889         char buf[32];
890 #endif
891
892         pkt = NetTxPacket;
893         et = (Ethernet_t *)pkt;
894
895         /* NOTE: trigger sent not on any VLAN */
896
897         /* form ethernet header */
898         memcpy(et->et_dest, NetCDPAddr, 6);
899         memcpy(et->et_src, NetOurEther, 6);
900
901         pkt += ETHER_HDR_SIZE;
902
903         /* SNAP header */
904         memcpy((uchar *)pkt, CDP_SNAP_hdr, sizeof(CDP_SNAP_hdr));
905         pkt += sizeof(CDP_SNAP_hdr);
906
907         /* CDP header */
908         *pkt++ = 0x02;                          /* CDP version 2 */
909         *pkt++ = 180;                           /* TTL */
910         s = (volatile ushort *)pkt;
911         cp = s;
912         *s++ = htons(0);                        /* checksum (0 for later calculation) */
913
914         /* CDP fields */
915 #ifdef CONFIG_CDP_DEVICE_ID
916         *s++ = htons(CDP_DEVICE_ID_TLV);
917         *s++ = htons(CONFIG_CDP_DEVICE_ID);
918         memset(buf, 0, sizeof(buf));
919         sprintf(buf, CONFIG_CDP_DEVICE_ID_PREFIX "%02X%02X%02X%02X%02X%02X",
920                 NetOurEther[0] & 0xff, NetOurEther[1] & 0xff,
921                 NetOurEther[2] & 0xff, NetOurEther[3] & 0xff,
922                 NetOurEther[4] & 0xff, NetOurEther[5] & 0xff);
923         memcpy((uchar *)s, buf, 16);
924         s += 16 / 2;
925 #endif
926
927 #ifdef CONFIG_CDP_PORT_ID
928         *s++ = htons(CDP_PORT_ID_TLV);
929         memset(buf, 0, sizeof(buf));
930         sprintf(buf, CONFIG_CDP_PORT_ID, eth_get_dev_index());
931         len = strlen(buf);
932         if (len & 1)    /* make it even */
933                 len++;
934         *s++ = htons(len + 4);
935         memcpy((uchar *)s, buf, len);
936         s += len / 2;
937 #endif
938
939 #ifdef CONFIG_CDP_CAPABILITIES
940         *s++ = htons(CDP_CAPABILITIES_TLV);
941         *s++ = htons(8);
942         *(ulong *)s = htonl(CONFIG_CDP_CAPABILITIES);
943         s += 2;
944 #endif
945
946 #ifdef CONFIG_CDP_VERSION
947         *s++ = htons(CDP_VERSION_TLV);
948         memset(buf, 0, sizeof(buf));
949         strcpy(buf, CONFIG_CDP_VERSION);
950         len = strlen(buf);
951         if (len & 1)    /* make it even */
952                 len++;
953         *s++ = htons(len + 4);
954         memcpy((uchar *)s, buf, len);
955         s += len / 2;
956 #endif
957
958 #ifdef CONFIG_CDP_PLATFORM
959         *s++ = htons(CDP_PLATFORM_TLV);
960         memset(buf, 0, sizeof(buf));
961         strcpy(buf, CONFIG_CDP_PLATFORM);
962         len = strlen(buf);
963         if (len & 1)    /* make it even */
964                 len++;
965         *s++ = htons(len + 4);
966         memcpy((uchar *)s, buf, len);
967         s += len / 2;
968 #endif
969
970 #ifdef CONFIG_CDP_TRIGGER
971         *s++ = htons(CDP_TRIGGER_TLV);
972         *s++ = htons(8);
973         *(ulong *)s = htonl(CONFIG_CDP_TRIGGER);
974         s += 2;
975 #endif
976
977 #ifdef CONFIG_CDP_POWER_CONSUMPTION
978         *s++ = htons(CDP_POWER_CONSUMPTION_TLV);
979         *s++ = htons(6);
980         *s++ = htons(CONFIG_CDP_POWER_CONSUMPTION);
981 #endif
982
983         /* length of ethernet packet */
984         len = (uchar *)s - ((uchar *)NetTxPacket + ETHER_HDR_SIZE);
985         et->et_protlen = htons(len);
986
987         len = ETHER_HDR_SIZE + sizeof(CDP_SNAP_hdr);
988         chksum = CDP_compute_csum((uchar *)NetTxPacket + len, (uchar *)s - (NetTxPacket + len));
989         if (chksum == 0)
990                 chksum = 0xFFFF;
991         *cp = htons(chksum);
992
993         (void) eth_send(NetTxPacket, (uchar *)s - NetTxPacket);
994         return 0;
995 }
996
997 static void
998 CDPTimeout (void)
999 {
1000         CDPSeq++;
1001
1002         if (CDPSeq < 3) {
1003                 NetSetTimeout (CDP_TIMEOUT, CDPTimeout);
1004                 CDPSendTrigger();
1005                 return;
1006         }
1007
1008         /* if not OK try again */
1009         if (!CDPOK)
1010                 NetStartAgain();
1011         else
1012                 NetState = NETLOOP_SUCCESS;
1013 }
1014
1015 static void
1016 CDPDummyHandler (uchar * pkt, unsigned dest, unsigned src, unsigned len)
1017 {
1018         /* nothing */
1019 }
1020
1021 static void
1022 CDPHandler(const uchar * pkt, unsigned len)
1023 {
1024         const uchar *t;
1025         const ushort *ss;
1026         ushort type, tlen;
1027         uchar applid;
1028         ushort vlan, nvlan;
1029
1030         /* minimum size? */
1031         if (len < sizeof(CDP_SNAP_hdr) + 4)
1032                 goto pkt_short;
1033
1034         /* check for valid CDP SNAP header */
1035         if (memcmp(pkt, CDP_SNAP_hdr, sizeof(CDP_SNAP_hdr)) != 0)
1036                 return;
1037
1038         pkt += sizeof(CDP_SNAP_hdr);
1039         len -= sizeof(CDP_SNAP_hdr);
1040
1041         /* Version of CDP protocol must be >= 2 and TTL != 0 */
1042         if (pkt[0] < 0x02 || pkt[1] == 0)
1043                 return;
1044
1045         /* if version is greater than 0x02 maybe we'll have a problem; output a warning */
1046         if (pkt[0] != 0x02)
1047                 printf("** WARNING: CDP packet received with a protocol version %d > 2\n",
1048                                 pkt[0] & 0xff);
1049
1050         if (CDP_compute_csum(pkt, len) != 0)
1051                 return;
1052
1053         pkt += 4;
1054         len -= 4;
1055
1056         vlan = htons(-1);
1057         nvlan = htons(-1);
1058         while (len > 0) {
1059                 if (len < 4)
1060                         goto pkt_short;
1061
1062                 ss = (const ushort *)pkt;
1063                 type = ntohs(ss[0]);
1064                 tlen = ntohs(ss[1]);
1065                 if (tlen > len) {
1066                         goto pkt_short;
1067                 }
1068
1069                 pkt += tlen;
1070                 len -= tlen;
1071
1072                 ss += 2;        /* point ss to the data of the TLV */
1073                 tlen -= 4;
1074
1075                 switch (type) {
1076                         case CDP_DEVICE_ID_TLV:
1077                                 break;
1078                         case CDP_ADDRESS_TLV:
1079                                 break;
1080                         case CDP_PORT_ID_TLV:
1081                                 break;
1082                         case CDP_CAPABILITIES_TLV:
1083                                 break;
1084                         case CDP_VERSION_TLV:
1085                                 break;
1086                         case CDP_PLATFORM_TLV:
1087                                 break;
1088                         case CDP_NATIVE_VLAN_TLV:
1089                                 nvlan = *ss;
1090                                 break;
1091                         case CDP_APPLIANCE_VLAN_TLV:
1092                                 t = (const uchar *)ss;
1093                                 while (tlen > 0) {
1094                                         if (tlen < 3)
1095                                                 goto pkt_short;
1096
1097                                         applid = t[0];
1098                                         ss = (const ushort *)(t + 1);
1099
1100 #ifdef CONFIG_CDP_APPLIANCE_VLAN_TYPE
1101                                         if (applid == CONFIG_CDP_APPLIANCE_VLAN_TYPE)
1102                                                 vlan = *ss;
1103 #else
1104                                         vlan = ntohs(*ss);      /* XXX will this work; dunno */
1105 #endif
1106                                         t += 3; tlen -= 3;
1107                                 }
1108                                 break;
1109                         case CDP_TRIGGER_TLV:
1110                                 break;
1111                         case CDP_POWER_CONSUMPTION_TLV:
1112                                 break;
1113                         case CDP_SYSNAME_TLV:
1114                                 break;
1115                         case CDP_SYSOBJECT_TLV:
1116                                 break;
1117                         case CDP_MANAGEMENT_ADDRESS_TLV:
1118                                 break;
1119                 }
1120         }
1121
1122         CDPApplianceVLAN = vlan;
1123         CDPNativeVLAN = nvlan;
1124
1125         CDPOK = 1;
1126         return;
1127
1128  pkt_short:
1129         printf("** CDP packet is too short\n");
1130         return;
1131 }
1132
1133 static void CDPStart(void)
1134 {
1135 #if defined(CONFIG_NET_MULTI)
1136         printf ("Using %s device\n", eth_get_name());
1137 #endif
1138         CDPSeq = 0;
1139         CDPOK = 0;
1140
1141         CDPNativeVLAN = htons(-1);
1142         CDPApplianceVLAN = htons(-1);
1143
1144         NetSetTimeout (CDP_TIMEOUT, CDPTimeout);
1145         NetSetHandler (CDPDummyHandler);
1146
1147         CDPSendTrigger();
1148 }
1149 #endif
1150
1151
1152 void
1153 NetReceive(volatile uchar * inpkt, int len)
1154 {
1155         Ethernet_t *et;
1156         IP_t    *ip;
1157         ARP_t   *arp;
1158         IPaddr_t tmp;
1159         int     x;
1160         uchar *pkt;
1161 #if defined(CONFIG_CMD_CDP)
1162         int iscdp;
1163 #endif
1164         ushort cti = 0, vlanid = VLAN_NONE, myvlanid, mynvlanid;
1165
1166 #ifdef ET_DEBUG
1167         printf("packet received\n");
1168 #endif
1169
1170         NetRxPkt = inpkt;
1171         NetRxPktLen = len;
1172         et = (Ethernet_t *)inpkt;
1173
1174         /* too small packet? */
1175         if (len < ETHER_HDR_SIZE)
1176                 return;
1177
1178 #ifdef CONFIG_API
1179         if (push_packet) {
1180                 (*push_packet)(inpkt, len);
1181                 return;
1182         }
1183 #endif
1184
1185 #if defined(CONFIG_CMD_CDP)
1186         /* keep track if packet is CDP */
1187         iscdp = memcmp(et->et_dest, NetCDPAddr, 6) == 0;
1188 #endif
1189
1190         myvlanid = ntohs(NetOurVLAN);
1191         if (myvlanid == (ushort)-1)
1192                 myvlanid = VLAN_NONE;
1193         mynvlanid = ntohs(NetOurNativeVLAN);
1194         if (mynvlanid == (ushort)-1)
1195                 mynvlanid = VLAN_NONE;
1196
1197         x = ntohs(et->et_protlen);
1198
1199 #ifdef ET_DEBUG
1200         printf("packet received\n");
1201 #endif
1202
1203         if (x < 1514) {
1204                 /*
1205                  *      Got a 802 packet.  Check the other protocol field.
1206                  */
1207                 x = ntohs(et->et_prot);
1208
1209                 ip = (IP_t *)(inpkt + E802_HDR_SIZE);
1210                 len -= E802_HDR_SIZE;
1211
1212         } else if (x != PROT_VLAN) {    /* normal packet */
1213                 ip = (IP_t *)(inpkt + ETHER_HDR_SIZE);
1214                 len -= ETHER_HDR_SIZE;
1215
1216         } else {                        /* VLAN packet */
1217                 VLAN_Ethernet_t *vet = (VLAN_Ethernet_t *)et;
1218
1219 #ifdef ET_DEBUG
1220                 printf("VLAN packet received\n");
1221 #endif
1222                 /* too small packet? */
1223                 if (len < VLAN_ETHER_HDR_SIZE)
1224                         return;
1225
1226                 /* if no VLAN active */
1227                 if ((ntohs(NetOurVLAN) & VLAN_IDMASK) == VLAN_NONE
1228 #if defined(CONFIG_CMD_CDP)
1229                                 && iscdp == 0
1230 #endif
1231                                 )
1232                         return;
1233
1234                 cti = ntohs(vet->vet_tag);
1235                 vlanid = cti & VLAN_IDMASK;
1236                 x = ntohs(vet->vet_type);
1237
1238                 ip = (IP_t *)(inpkt + VLAN_ETHER_HDR_SIZE);
1239                 len -= VLAN_ETHER_HDR_SIZE;
1240         }
1241
1242 #ifdef ET_DEBUG
1243         printf("Receive from protocol 0x%x\n", x);
1244 #endif
1245
1246 #if defined(CONFIG_CMD_CDP)
1247         if (iscdp) {
1248                 CDPHandler((uchar *)ip, len);
1249                 return;
1250         }
1251 #endif
1252
1253         if ((myvlanid & VLAN_IDMASK) != VLAN_NONE) {
1254                 if (vlanid == VLAN_NONE)
1255                         vlanid = (mynvlanid & VLAN_IDMASK);
1256                 /* not matched? */
1257                 if (vlanid != (myvlanid & VLAN_IDMASK))
1258                         return;
1259         }
1260
1261         switch (x) {
1262
1263         case PROT_ARP:
1264                 /*
1265                  * We have to deal with two types of ARP packets:
1266                  * - REQUEST packets will be answered by sending  our
1267                  *   IP address - if we know it.
1268                  * - REPLY packates are expected only after we asked
1269                  *   for the TFTP server's or the gateway's ethernet
1270                  *   address; so if we receive such a packet, we set
1271                  *   the server ethernet address
1272                  */
1273 #ifdef ET_DEBUG
1274                 puts ("Got ARP\n");
1275 #endif
1276                 arp = (ARP_t *)ip;
1277                 if (len < ARP_HDR_SIZE) {
1278                         printf("bad length %d < %d\n", len, ARP_HDR_SIZE);
1279                         return;
1280                 }
1281                 if (ntohs(arp->ar_hrd) != ARP_ETHER) {
1282                         return;
1283                 }
1284                 if (ntohs(arp->ar_pro) != PROT_IP) {
1285                         return;
1286                 }
1287                 if (arp->ar_hln != 6) {
1288                         return;
1289                 }
1290                 if (arp->ar_pln != 4) {
1291                         return;
1292                 }
1293
1294                 if (NetOurIP == 0) {
1295                         return;
1296                 }
1297
1298                 if (NetReadIP(&arp->ar_data[16]) != NetOurIP) {
1299                         return;
1300                 }
1301
1302                 switch (ntohs(arp->ar_op)) {
1303                 case ARPOP_REQUEST:             /* reply with our IP address    */
1304 #ifdef ET_DEBUG
1305                         puts ("Got ARP REQUEST, return our IP\n");
1306 #endif
1307                         pkt = (uchar *)et;
1308                         pkt += NetSetEther(pkt, et->et_src, PROT_ARP);
1309                         arp->ar_op = htons(ARPOP_REPLY);
1310                         memcpy   (&arp->ar_data[10], &arp->ar_data[0], 6);
1311                         NetCopyIP(&arp->ar_data[16], &arp->ar_data[6]);
1312                         memcpy   (&arp->ar_data[ 0], NetOurEther, 6);
1313                         NetCopyIP(&arp->ar_data[ 6], &NetOurIP);
1314                         (void) eth_send((uchar *)et, (pkt - (uchar *)et) + ARP_HDR_SIZE);
1315                         return;
1316
1317                 case ARPOP_REPLY:               /* arp reply */
1318                         /* are we waiting for a reply */
1319                         if (!NetArpWaitPacketIP || !NetArpWaitPacketMAC)
1320                                 break;
1321 #ifdef ET_DEBUG
1322                         printf("Got ARP REPLY, set server/gtwy eth addr (%02x:%02x:%02x:%02x:%02x:%02x)\n",
1323                                 arp->ar_data[0], arp->ar_data[1],
1324                                 arp->ar_data[2], arp->ar_data[3],
1325                                 arp->ar_data[4], arp->ar_data[5]);
1326 #endif
1327
1328                         tmp = NetReadIP(&arp->ar_data[6]);
1329
1330                         /* matched waiting packet's address */
1331                         if (tmp == NetArpWaitReplyIP) {
1332 #ifdef ET_DEBUG
1333                                 puts ("Got it\n");
1334 #endif
1335                                 /* save address for later use */
1336                                 memcpy(NetArpWaitPacketMAC, &arp->ar_data[0], 6);
1337
1338 #ifdef CONFIG_NETCONSOLE
1339                                 (*packetHandler)(0,0,0,0);
1340 #endif
1341                                 /* modify header, and transmit it */
1342                                 memcpy(((Ethernet_t *)NetArpWaitTxPacket)->et_dest, NetArpWaitPacketMAC, 6);
1343                                 (void) eth_send(NetArpWaitTxPacket, NetArpWaitTxPacketSize);
1344
1345                                 /* no arp request pending now */
1346                                 NetArpWaitPacketIP = 0;
1347                                 NetArpWaitTxPacketSize = 0;
1348                                 NetArpWaitPacketMAC = NULL;
1349
1350                         }
1351                         return;
1352                 default:
1353 #ifdef ET_DEBUG
1354                         printf("Unexpected ARP opcode 0x%x\n", ntohs(arp->ar_op));
1355 #endif
1356                         return;
1357                 }
1358                 break;
1359
1360         case PROT_RARP:
1361 #ifdef ET_DEBUG
1362                 puts ("Got RARP\n");
1363 #endif
1364                 arp = (ARP_t *)ip;
1365                 if (len < ARP_HDR_SIZE) {
1366                         printf("bad length %d < %d\n", len, ARP_HDR_SIZE);
1367                         return;
1368                 }
1369
1370                 if ((ntohs(arp->ar_op) != RARPOP_REPLY) ||
1371                         (ntohs(arp->ar_hrd) != ARP_ETHER)   ||
1372                         (ntohs(arp->ar_pro) != PROT_IP)     ||
1373                         (arp->ar_hln != 6) || (arp->ar_pln != 4)) {
1374
1375                         puts ("invalid RARP header\n");
1376                 } else {
1377                         NetCopyIP(&NetOurIP,    &arp->ar_data[16]);
1378                         if (NetServerIP == 0)
1379                                 NetCopyIP(&NetServerIP, &arp->ar_data[ 6]);
1380                         memcpy (NetServerEther, &arp->ar_data[ 0], 6);
1381
1382                         (*packetHandler)(0,0,0,0);
1383                 }
1384                 break;
1385
1386         case PROT_IP:
1387 #ifdef ET_DEBUG
1388                 puts ("Got IP\n");
1389 #endif
1390                 if (len < IP_HDR_SIZE) {
1391                         debug ("len bad %d < %lu\n", len, (ulong)IP_HDR_SIZE);
1392                         return;
1393                 }
1394                 if (len < ntohs(ip->ip_len)) {
1395                         printf("len bad %d < %d\n", len, ntohs(ip->ip_len));
1396                         return;
1397                 }
1398                 len = ntohs(ip->ip_len);
1399 #ifdef ET_DEBUG
1400                 printf("len=%d, v=%02x\n", len, ip->ip_hl_v & 0xff);
1401 #endif
1402                 if ((ip->ip_hl_v & 0xf0) != 0x40) {
1403                         return;
1404                 }
1405                 /* Can't deal with fragments */
1406                 if (ip->ip_off & htons(IP_OFFS | IP_FLAGS_MFRAG)) {
1407                         return;
1408                 }
1409                 /* can't deal with headers > 20 bytes */
1410                 if ((ip->ip_hl_v & 0x0f) > 0x05) {
1411                         return;
1412                 }
1413                 if (!NetCksumOk((uchar *)ip, IP_HDR_SIZE_NO_UDP / 2)) {
1414                         puts ("checksum bad\n");
1415                         return;
1416                 }
1417                 tmp = NetReadIP(&ip->ip_dst);
1418                 if (NetOurIP && tmp != NetOurIP && tmp != 0xFFFFFFFF) {
1419 #ifdef CONFIG_MCAST_TFTP
1420                         if (Mcast_addr != tmp)
1421 #endif
1422                         return;
1423                 }
1424                 /*
1425                  * watch for ICMP host redirects
1426                  *
1427                  * There is no real handler code (yet). We just watch
1428                  * for ICMP host redirect messages. In case anybody
1429                  * sees these messages: please contact me
1430                  * (wd@denx.de), or - even better - send me the
1431                  * necessary fixes :-)
1432                  *
1433                  * Note: in all cases where I have seen this so far
1434                  * it was a problem with the router configuration,
1435                  * for instance when a router was configured in the
1436                  * BOOTP reply, but the TFTP server was on the same
1437                  * subnet. So this is probably a warning that your
1438                  * configuration might be wrong. But I'm not really
1439                  * sure if there aren't any other situations.
1440                  */
1441                 if (ip->ip_p == IPPROTO_ICMP) {
1442                         ICMP_t *icmph = (ICMP_t *)&(ip->udp_src);
1443
1444                         switch (icmph->type) {
1445                         case ICMP_REDIRECT:
1446                                 if (icmph->code != ICMP_REDIR_HOST)
1447                                         return;
1448                                 puts (" ICMP Host Redirect to ");
1449                                 print_IPaddr(icmph->un.gateway);
1450                                 putc(' ');
1451                                 return;
1452 #if defined(CONFIG_CMD_PING)
1453                         case ICMP_ECHO_REPLY:
1454                                 /*
1455                                  *      IP header OK.  Pass the packet to the current handler.
1456                                  */
1457                                 /* XXX point to ip packet */
1458                                 (*packetHandler)((uchar *)ip, 0, 0, 0);
1459                                 return;
1460                         case ICMP_ECHO_REQUEST:
1461 #ifdef ET_DEBUG
1462                                 printf ("Got ICMP ECHO REQUEST, return %d bytes \n",
1463                                         ETHER_HDR_SIZE + len);
1464 #endif
1465                                 memcpy (&et->et_dest[0], &et->et_src[0], 6);
1466                                 memcpy (&et->et_src[ 0], NetOurEther, 6);
1467
1468                                 ip->ip_sum = 0;
1469                                 ip->ip_off = 0;
1470                                 NetCopyIP((void*)&ip->ip_dst, &ip->ip_src);
1471                                 NetCopyIP((void*)&ip->ip_src, &NetOurIP);
1472                                 ip->ip_sum = ~NetCksum((uchar *)ip, IP_HDR_SIZE_NO_UDP >> 1);
1473
1474                                 icmph->type = ICMP_ECHO_REPLY;
1475                                 icmph->checksum = 0;
1476                                 icmph->checksum = ~NetCksum((uchar *)icmph,
1477                                                 (len - IP_HDR_SIZE_NO_UDP) >> 1);
1478                                 (void) eth_send((uchar *)et, ETHER_HDR_SIZE + len);
1479                                 return;
1480 #endif
1481                         default:
1482                                 return;
1483                         }
1484                 } else if (ip->ip_p != IPPROTO_UDP) {   /* Only UDP packets */
1485                         return;
1486                 }
1487
1488 #ifdef CONFIG_UDP_CHECKSUM
1489                 if (ip->udp_xsum != 0) {
1490                         ulong   xsum;
1491                         ushort *sumptr;
1492                         ushort  sumlen;
1493
1494                         xsum  = ip->ip_p;
1495                         xsum += (ntohs(ip->udp_len));
1496                         xsum += (ntohl(ip->ip_src) >> 16) & 0x0000ffff;
1497                         xsum += (ntohl(ip->ip_src) >>  0) & 0x0000ffff;
1498                         xsum += (ntohl(ip->ip_dst) >> 16) & 0x0000ffff;
1499                         xsum += (ntohl(ip->ip_dst) >>  0) & 0x0000ffff;
1500
1501                         sumlen = ntohs(ip->udp_len);
1502                         sumptr = (ushort *) &(ip->udp_src);
1503
1504                         while (sumlen > 1) {
1505                                 ushort sumdata;
1506
1507                                 sumdata = *sumptr++;
1508                                 xsum += ntohs(sumdata);
1509                                 sumlen -= 2;
1510                         }
1511                         if (sumlen > 0) {
1512                                 ushort sumdata;
1513
1514                                 sumdata = *(unsigned char *) sumptr;
1515                                 sumdata = (sumdata << 8) & 0xff00;
1516                                 xsum += sumdata;
1517                         }
1518                         while ((xsum >> 16) != 0) {
1519                                 xsum = (xsum & 0x0000ffff) + ((xsum >> 16) & 0x0000ffff);
1520                         }
1521                         if ((xsum != 0x00000000) && (xsum != 0x0000ffff)) {
1522                                 printf(" UDP wrong checksum %08lx %08x\n",
1523                                         xsum, ntohs(ip->udp_xsum));
1524                                 return;
1525                         }
1526                 }
1527 #endif
1528
1529
1530 #ifdef CONFIG_NETCONSOLE
1531                 nc_input_packet((uchar *)ip +IP_HDR_SIZE,
1532                                                 ntohs(ip->udp_dst),
1533                                                 ntohs(ip->udp_src),
1534                                                 ntohs(ip->udp_len) - 8);
1535 #endif
1536                 /*
1537                  *      IP header OK.  Pass the packet to the current handler.
1538                  */
1539                 (*packetHandler)((uchar *)ip +IP_HDR_SIZE,
1540                                                 ntohs(ip->udp_dst),
1541                                                 ntohs(ip->udp_src),
1542                                                 ntohs(ip->udp_len) - 8);
1543                 break;
1544         }
1545 }
1546
1547
1548 /**********************************************************************/
1549
1550 static int net_check_prereq (proto_t protocol)
1551 {
1552         switch (protocol) {
1553                 /* Fall through */
1554 #if defined(CONFIG_CMD_PING)
1555         case PING:
1556                 if (NetPingIP == 0) {
1557                         puts ("*** ERROR: ping address not given\n");
1558                         return (1);
1559                 }
1560                 goto common;
1561 #endif
1562 #if defined(CONFIG_CMD_SNTP)
1563         case SNTP:
1564                 if (NetNtpServerIP == 0) {
1565                         puts ("*** ERROR: NTP server address not given\n");
1566                         return (1);
1567                 }
1568                 goto common;
1569 #endif
1570 #if defined(CONFIG_CMD_NFS)
1571         case NFS:
1572 #endif
1573         case NETCONS:
1574         case TFTP:
1575                 if (NetServerIP == 0) {
1576                         puts ("*** ERROR: `serverip' not set\n");
1577                         return (1);
1578                 }
1579 #if defined(CONFIG_CMD_PING) || defined(CONFIG_CMD_SNTP)
1580     common:
1581 #endif
1582
1583                 if (NetOurIP == 0) {
1584                         puts ("*** ERROR: `ipaddr' not set\n");
1585                         return (1);
1586                 }
1587                 /* Fall through */
1588
1589         case DHCP:
1590         case RARP:
1591         case BOOTP:
1592         case CDP:
1593                 if (memcmp (NetOurEther, "\0\0\0\0\0\0", 6) == 0) {
1594 #ifdef CONFIG_NET_MULTI
1595                         extern int eth_get_dev_index (void);
1596                         int num = eth_get_dev_index ();
1597
1598                         switch (num) {
1599                         case -1:
1600                                 puts ("*** ERROR: No ethernet found.\n");
1601                                 return (1);
1602                         case 0:
1603                                 puts ("*** ERROR: `ethaddr' not set\n");
1604                                 break;
1605                         default:
1606                                 printf ("*** ERROR: `eth%daddr' not set\n",
1607                                         num);
1608                                 break;
1609                         }
1610
1611                         NetStartAgain ();
1612                         return (2);
1613 #else
1614                         puts ("*** ERROR: `ethaddr' not set\n");
1615                         return (1);
1616 #endif
1617                 }
1618                 /* Fall through */
1619         default:
1620                 return (0);
1621         }
1622         return (0);             /* OK */
1623 }
1624 /**********************************************************************/
1625
1626 int
1627 NetCksumOk(uchar * ptr, int len)
1628 {
1629         return !((NetCksum(ptr, len) + 1) & 0xfffe);
1630 }
1631
1632
1633 unsigned
1634 NetCksum(uchar * ptr, int len)
1635 {
1636         ulong   xsum;
1637         ushort *p = (ushort *)ptr;
1638
1639         xsum = 0;
1640         while (len-- > 0)
1641                 xsum += *p++;
1642         xsum = (xsum & 0xffff) + (xsum >> 16);
1643         xsum = (xsum & 0xffff) + (xsum >> 16);
1644         return (xsum & 0xffff);
1645 }
1646
1647 int
1648 NetEthHdrSize(void)
1649 {
1650         ushort myvlanid;
1651
1652         myvlanid = ntohs(NetOurVLAN);
1653         if (myvlanid == (ushort)-1)
1654                 myvlanid = VLAN_NONE;
1655
1656         return ((myvlanid & VLAN_IDMASK) == VLAN_NONE) ? ETHER_HDR_SIZE : VLAN_ETHER_HDR_SIZE;
1657 }
1658
1659 int
1660 NetSetEther(volatile uchar * xet, uchar * addr, uint prot)
1661 {
1662         Ethernet_t *et = (Ethernet_t *)xet;
1663         ushort myvlanid;
1664
1665         myvlanid = ntohs(NetOurVLAN);
1666         if (myvlanid == (ushort)-1)
1667                 myvlanid = VLAN_NONE;
1668
1669         memcpy (et->et_dest, addr, 6);
1670         memcpy (et->et_src, NetOurEther, 6);
1671         if ((myvlanid & VLAN_IDMASK) == VLAN_NONE) {
1672         et->et_protlen = htons(prot);
1673                 return ETHER_HDR_SIZE;
1674         } else {
1675                 VLAN_Ethernet_t *vet = (VLAN_Ethernet_t *)xet;
1676
1677                 vet->vet_vlan_type = htons(PROT_VLAN);
1678                 vet->vet_tag = htons((0 << 5) | (myvlanid & VLAN_IDMASK));
1679                 vet->vet_type = htons(prot);
1680                 return VLAN_ETHER_HDR_SIZE;
1681         }
1682 }
1683
1684 void
1685 NetSetIP(volatile uchar * xip, IPaddr_t dest, int dport, int sport, int len)
1686 {
1687         volatile IP_t *ip = (IP_t *)xip;
1688
1689         /*
1690          *      If the data is an odd number of bytes, zero the
1691          *      byte after the last byte so that the checksum
1692          *      will work.
1693          */
1694         if (len & 1)
1695                 xip[IP_HDR_SIZE + len] = 0;
1696
1697         /*
1698          *      Construct an IP and UDP header.
1699          *      (need to set no fragment bit - XXX)
1700          */
1701         ip->ip_hl_v  = 0x45;            /* IP_HDR_SIZE / 4 (not including UDP) */
1702         ip->ip_tos   = 0;
1703         ip->ip_len   = htons(IP_HDR_SIZE + len);
1704         ip->ip_id    = htons(NetIPID++);
1705         ip->ip_off   = htons(IP_FLAGS_DFRAG);   /* Don't fragment */
1706         ip->ip_ttl   = 255;
1707         ip->ip_p     = 17;              /* UDP */
1708         ip->ip_sum   = 0;
1709         NetCopyIP((void*)&ip->ip_src, &NetOurIP); /* already in network byte order */
1710         NetCopyIP((void*)&ip->ip_dst, &dest);      /* - "" - */
1711         ip->udp_src  = htons(sport);
1712         ip->udp_dst  = htons(dport);
1713         ip->udp_len  = htons(8 + len);
1714         ip->udp_xsum = 0;
1715         ip->ip_sum   = ~NetCksum((uchar *)ip, IP_HDR_SIZE_NO_UDP / 2);
1716 }
1717
1718 void copy_filename (char *dst, char *src, int size)
1719 {
1720         if (*src && (*src == '"')) {
1721                 ++src;
1722                 --size;
1723         }
1724
1725         while ((--size > 0) && *src && (*src != '"')) {
1726                 *dst++ = *src++;
1727         }
1728         *dst = '\0';
1729 }
1730
1731 #endif
1732
1733 void ip_to_string (IPaddr_t x, char *s)
1734 {
1735         x = ntohl (x);
1736         sprintf (s, "%d.%d.%d.%d",
1737                  (int) ((x >> 24) & 0xff),
1738                  (int) ((x >> 16) & 0xff),
1739                  (int) ((x >> 8) & 0xff), (int) ((x >> 0) & 0xff)
1740         );
1741 }
1742
1743 IPaddr_t string_to_ip(char *s)
1744 {
1745         IPaddr_t addr;
1746         char *e;
1747         int i;
1748
1749         if (s == NULL)
1750                 return(0);
1751
1752         for (addr=0, i=0; i<4; ++i) {
1753                 ulong val = s ? simple_strtoul(s, &e, 10) : 0;
1754                 addr <<= 8;
1755                 addr |= (val & 0xFF);
1756                 if (s) {
1757                         s = (*e) ? e+1 : e;
1758                 }
1759         }
1760
1761         return (htonl(addr));
1762 }
1763
1764 void VLAN_to_string(ushort x, char *s)
1765 {
1766         x = ntohs(x);
1767
1768         if (x == (ushort)-1)
1769                 x = VLAN_NONE;
1770
1771         if (x == VLAN_NONE)
1772                 strcpy(s, "none");
1773         else
1774                 sprintf(s, "%d", x & VLAN_IDMASK);
1775 }
1776
1777 ushort string_to_VLAN(char *s)
1778 {
1779         ushort id;
1780
1781         if (s == NULL)
1782                 return htons(VLAN_NONE);
1783
1784         if (*s < '0' || *s > '9')
1785                 id = VLAN_NONE;
1786         else
1787                 id = (ushort)simple_strtoul(s, NULL, 10);
1788
1789         return htons(id);
1790 }
1791
1792 void print_IPaddr (IPaddr_t x)
1793 {
1794         char tmp[16];
1795
1796         ip_to_string (x, tmp);
1797
1798         puts (tmp);
1799 }
1800
1801 IPaddr_t getenv_IPaddr (char *var)
1802 {
1803         return (string_to_ip(getenv(var)));
1804 }
1805
1806 ushort getenv_VLAN(char *var)
1807 {
1808         return (string_to_VLAN(getenv(var)));
1809 }