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