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