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