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