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