net: Refactor to use NetSendPacket instead of eth_send directly
[oweals/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 <command.h>
79 #include <net.h>
80 #if defined(CONFIG_STATUS_LED)
81 #include <miiphy.h>
82 #include <status_led.h>
83 #endif
84 #include <watchdog.h>
85 #include <linux/compiler.h>
86 #include "arp.h"
87 #include "bootp.h"
88 #include "cdp.h"
89 #if defined(CONFIG_CMD_DNS)
90 #include "dns.h"
91 #endif
92 #include "nfs.h"
93 #include "ping.h"
94 #include "rarp.h"
95 #if defined(CONFIG_CMD_SNTP)
96 #include "sntp.h"
97 #endif
98 #include "tftp.h"
99
100 DECLARE_GLOBAL_DATA_PTR;
101
102 /** BOOTP EXTENTIONS **/
103
104 /* Our subnet mask (0=unknown) */
105 IPaddr_t        NetOurSubnetMask;
106 /* Our gateways IP address */
107 IPaddr_t        NetOurGatewayIP;
108 /* Our DNS IP address */
109 IPaddr_t        NetOurDNSIP;
110 #if defined(CONFIG_BOOTP_DNS2)
111 /* Our 2nd DNS IP address */
112 IPaddr_t        NetOurDNS2IP;
113 #endif
114 /* Our NIS domain */
115 char            NetOurNISDomain[32] = {0,};
116 /* Our hostname */
117 char            NetOurHostName[32] = {0,};
118 /* Our bootpath */
119 char            NetOurRootPath[64] = {0,};
120 /* Our bootfile size in blocks */
121 ushort          NetBootFileSize;
122
123 #ifdef CONFIG_MCAST_TFTP        /* Multicast TFTP */
124 IPaddr_t Mcast_addr;
125 #endif
126
127 /** END OF BOOTP EXTENTIONS **/
128
129 /* The actual transferred size of the bootfile (in bytes) */
130 ulong           NetBootFileXferSize;
131 /* Our ethernet address */
132 uchar           NetOurEther[6];
133 /* Boot server enet address */
134 uchar           NetServerEther[6];
135 /* Our IP addr (0 = unknown) */
136 IPaddr_t        NetOurIP;
137 /* Server IP addr (0 = unknown) */
138 IPaddr_t        NetServerIP;
139 /* Current receive packet */
140 uchar *NetRxPacket;
141 /* Current rx packet length */
142 int             NetRxPacketLen;
143 /* IP packet ID */
144 unsigned        NetIPID;
145 /* Ethernet bcast address */
146 uchar           NetBcastAddr[6] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
147 uchar           NetEtherNullAddr[6];
148 #ifdef CONFIG_API
149 void            (*push_packet)(void *, int len) = 0;
150 #endif
151 /* Network loop state */
152 int             NetState;
153 /* Tried all network devices */
154 int             NetRestartWrap;
155 /* Network loop restarted */
156 static int      NetRestarted;
157 /* At least one device configured */
158 static int      NetDevExists;
159
160 /* XXX in both little & big endian machines 0xFFFF == ntohs(-1) */
161 /* default is without VLAN */
162 ushort          NetOurVLAN = 0xFFFF;
163 /* ditto */
164 ushort          NetOurNativeVLAN = 0xFFFF;
165
166 /* Boot File name */
167 char            BootFile[128];
168
169 #if defined(CONFIG_CMD_SNTP)
170 /* NTP server IP address */
171 IPaddr_t        NetNtpServerIP;
172 /* offset time from UTC */
173 int             NetTimeOffset;
174 #endif
175
176 uchar PktBuf[(PKTBUFSRX+1) * PKTSIZE_ALIGN + PKTALIGN];
177
178 /* Receive packet */
179 uchar *NetRxPackets[PKTBUFSRX];
180
181 /* Current RX packet handler */
182 static rxhand_f *packetHandler;
183 #ifdef CONFIG_CMD_TFTPPUT
184 static rxhand_icmp_f *packet_icmp_handler;      /* Current ICMP rx handler */
185 #endif
186 /* Current timeout handler */
187 static thand_f *timeHandler;
188 /* Time base value */
189 static ulong    timeStart;
190 /* Current timeout value */
191 static ulong    timeDelta;
192 /* THE transmit packet */
193 uchar *NetTxPacket;
194
195 static int net_check_prereq(enum proto_t protocol);
196
197 static int NetTryCount;
198
199 /**********************************************************************/
200
201 /*
202  * Check if autoload is enabled. If so, use either NFS or TFTP to download
203  * the boot file.
204  */
205 void net_auto_load(void)
206 {
207         const char *s = getenv("autoload");
208
209         if (s != NULL) {
210                 if (*s == 'n') {
211                         /*
212                          * Just use BOOTP/RARP to configure system;
213                          * Do not use TFTP to load the bootfile.
214                          */
215                         NetState = NETLOOP_SUCCESS;
216                         return;
217                 }
218 #if defined(CONFIG_CMD_NFS)
219                 if (strcmp(s, "NFS") == 0) {
220                         /*
221                          * Use NFS to load the bootfile.
222                          */
223                         NfsStart();
224                         return;
225                 }
226 #endif
227         }
228         TftpStart(TFTPGET);
229 }
230
231 static void NetInitLoop(enum proto_t protocol)
232 {
233         static int env_changed_id;
234         int env_id = get_env_id();
235
236         /* update only when the environment has changed */
237         if (env_changed_id != env_id) {
238                 NetOurIP = getenv_IPaddr("ipaddr");
239                 NetOurGatewayIP = getenv_IPaddr("gatewayip");
240                 NetOurSubnetMask = getenv_IPaddr("netmask");
241                 NetServerIP = getenv_IPaddr("serverip");
242                 NetOurNativeVLAN = getenv_VLAN("nvlan");
243                 NetOurVLAN = getenv_VLAN("vlan");
244 #if defined(CONFIG_CMD_DNS)
245                 NetOurDNSIP = getenv_IPaddr("dnsip");
246 #endif
247                 env_changed_id = env_id;
248         }
249
250         return;
251 }
252
253 /**********************************************************************/
254 /*
255  *      Main network processing loop.
256  */
257
258 int NetLoop(enum proto_t protocol)
259 {
260         bd_t *bd = gd->bd;
261         int ret = -1;
262
263         NetRestarted = 0;
264         NetDevExists = 0;
265
266         NetTxPacket = NULL;
267         NetTryCount = 1;
268
269         ArpInit();
270
271         if (!NetTxPacket) {
272                 int     i;
273                 /*
274                  *      Setup packet buffers, aligned correctly.
275                  */
276                 NetTxPacket = &PktBuf[0] + (PKTALIGN - 1);
277                 NetTxPacket -= (ulong)NetTxPacket % PKTALIGN;
278                 for (i = 0; i < PKTBUFSRX; i++)
279                         NetRxPackets[i] = NetTxPacket + (i+1)*PKTSIZE_ALIGN;
280         }
281
282         bootstage_mark_name(BOOTSTAGE_ID_ETH_START, "eth_start");
283         eth_halt();
284         eth_set_current();
285         if (eth_init(bd) < 0) {
286                 eth_halt();
287                 return -1;
288         }
289
290 restart:
291         memcpy(NetOurEther, eth_get_dev()->enetaddr, 6);
292
293         NetState = NETLOOP_CONTINUE;
294
295         /*
296          *      Start the ball rolling with the given start function.  From
297          *      here on, this code is a state machine driven by received
298          *      packets and timer events.
299          */
300         NetInitLoop(protocol);
301
302         switch (net_check_prereq(protocol)) {
303         case 1:
304                 /* network not configured */
305                 eth_halt();
306                 return -1;
307
308         case 2:
309                 /* network device not configured */
310                 break;
311
312         case 0:
313                 NetDevExists = 1;
314                 NetBootFileXferSize = 0;
315                 switch (protocol) {
316                 case TFTPGET:
317 #ifdef CONFIG_CMD_TFTPPUT
318                 case TFTPPUT:
319 #endif
320                         /* always use ARP to get server ethernet address */
321                         TftpStart(protocol);
322                         break;
323 #ifdef CONFIG_CMD_TFTPSRV
324                 case TFTPSRV:
325                         TftpStartServer();
326                         break;
327 #endif
328 #if defined(CONFIG_CMD_DHCP)
329                 case DHCP:
330                         BootpTry = 0;
331                         NetOurIP = 0;
332                         DhcpRequest();          /* Basically same as BOOTP */
333                         break;
334 #endif
335
336                 case BOOTP:
337                         BootpTry = 0;
338                         NetOurIP = 0;
339                         BootpRequest();
340                         break;
341
342 #if defined(CONFIG_CMD_RARP)
343                 case RARP:
344                         RarpTry = 0;
345                         NetOurIP = 0;
346                         RarpRequest();
347                         break;
348 #endif
349 #if defined(CONFIG_CMD_PING)
350                 case PING:
351                         ping_start();
352                         break;
353 #endif
354 #if defined(CONFIG_CMD_NFS)
355                 case NFS:
356                         NfsStart();
357                         break;
358 #endif
359 #if defined(CONFIG_CMD_CDP)
360                 case CDP:
361                         CDPStart();
362                         break;
363 #endif
364 #ifdef CONFIG_NETCONSOLE
365                 case NETCONS:
366                         NcStart();
367                         break;
368 #endif
369 #if defined(CONFIG_CMD_SNTP)
370                 case SNTP:
371                         SntpStart();
372                         break;
373 #endif
374 #if defined(CONFIG_CMD_DNS)
375                 case DNS:
376                         DnsStart();
377                         break;
378 #endif
379                 default:
380                         break;
381                 }
382
383                 break;
384         }
385
386 #if defined(CONFIG_MII) || defined(CONFIG_CMD_MII)
387 #if     defined(CONFIG_SYS_FAULT_ECHO_LINK_DOWN)        && \
388         defined(CONFIG_STATUS_LED)                      && \
389         defined(STATUS_LED_RED)
390         /*
391          * Echo the inverted link state to the fault LED.
392          */
393         if (miiphy_link(eth_get_dev()->name, CONFIG_SYS_FAULT_MII_ADDR))
394                 status_led_set(STATUS_LED_RED, STATUS_LED_OFF);
395         else
396                 status_led_set(STATUS_LED_RED, STATUS_LED_ON);
397 #endif /* CONFIG_SYS_FAULT_ECHO_LINK_DOWN, ... */
398 #endif /* CONFIG_MII, ... */
399
400         /*
401          *      Main packet reception loop.  Loop receiving packets until
402          *      someone sets `NetState' to a state that terminates.
403          */
404         for (;;) {
405                 WATCHDOG_RESET();
406 #ifdef CONFIG_SHOW_ACTIVITY
407                 show_activity(1);
408 #endif
409                 /*
410                  *      Check the ethernet for a new packet.  The ethernet
411                  *      receive routine will process it.
412                  */
413                 eth_rx();
414
415                 /*
416                  *      Abort if ctrl-c was pressed.
417                  */
418                 if (ctrlc()) {
419                         eth_halt();
420                         puts("\nAbort\n");
421                         goto done;
422                 }
423
424                 ArpTimeoutCheck();
425
426                 /*
427                  *      Check for a timeout, and run the timeout handler
428                  *      if we have one.
429                  */
430                 if (timeHandler && ((get_timer(0) - timeStart) > timeDelta)) {
431                         thand_f *x;
432
433 #if defined(CONFIG_MII) || defined(CONFIG_CMD_MII)
434 #if     defined(CONFIG_SYS_FAULT_ECHO_LINK_DOWN)        && \
435         defined(CONFIG_STATUS_LED)                      && \
436         defined(STATUS_LED_RED)
437                         /*
438                          * Echo the inverted link state to the fault LED.
439                          */
440                         if (miiphy_link(eth_get_dev()->name,
441                                        CONFIG_SYS_FAULT_MII_ADDR)) {
442                                 status_led_set(STATUS_LED_RED, STATUS_LED_OFF);
443                         } else {
444                                 status_led_set(STATUS_LED_RED, STATUS_LED_ON);
445                         }
446 #endif /* CONFIG_SYS_FAULT_ECHO_LINK_DOWN, ... */
447 #endif /* CONFIG_MII, ... */
448                         x = timeHandler;
449                         timeHandler = (thand_f *)0;
450                         (*x)();
451                 }
452
453
454                 switch (NetState) {
455
456                 case NETLOOP_RESTART:
457                         NetRestarted = 1;
458                         goto restart;
459
460                 case NETLOOP_SUCCESS:
461                         if (NetBootFileXferSize > 0) {
462                                 char buf[20];
463                                 printf("Bytes transferred = %ld (%lx hex)\n",
464                                         NetBootFileXferSize,
465                                         NetBootFileXferSize);
466                                 sprintf(buf, "%lX", NetBootFileXferSize);
467                                 setenv("filesize", buf);
468
469                                 sprintf(buf, "%lX", (unsigned long)load_addr);
470                                 setenv("fileaddr", buf);
471                         }
472                         eth_halt();
473                         ret = NetBootFileXferSize;
474                         goto done;
475
476                 case NETLOOP_FAIL:
477                         goto done;
478                 }
479         }
480
481 done:
482 #ifdef CONFIG_CMD_TFTPPUT
483         /* Clear out the handlers */
484         NetSetHandler(NULL);
485         net_set_icmp_handler(NULL);
486 #endif
487         return ret;
488 }
489
490 /**********************************************************************/
491
492 static void
493 startAgainTimeout(void)
494 {
495         NetState = NETLOOP_RESTART;
496 }
497
498 static void
499 startAgainHandler(uchar *pkt, unsigned dest, IPaddr_t sip,
500                   unsigned src, unsigned len)
501 {
502         /* Totally ignore the packet */
503 }
504
505 void NetStartAgain(void)
506 {
507         char *nretry;
508         int retry_forever = 0;
509         unsigned long retrycnt = 0;
510
511         nretry = getenv("netretry");
512         if (nretry) {
513                 if (!strcmp(nretry, "yes"))
514                         retry_forever = 1;
515                 else if (!strcmp(nretry, "no"))
516                         retrycnt = 0;
517                 else if (!strcmp(nretry, "once"))
518                         retrycnt = 1;
519                 else
520                         retrycnt = simple_strtoul(nretry, NULL, 0);
521         } else
522                 retry_forever = 1;
523
524         if ((!retry_forever) && (NetTryCount >= retrycnt)) {
525                 eth_halt();
526                 NetState = NETLOOP_FAIL;
527                 return;
528         }
529
530         NetTryCount++;
531
532         eth_halt();
533 #if !defined(CONFIG_NET_DO_NOT_TRY_ANOTHER)
534         eth_try_another(!NetRestarted);
535 #endif
536         eth_init(gd->bd);
537         if (NetRestartWrap) {
538                 NetRestartWrap = 0;
539                 if (NetDevExists) {
540                         NetSetTimeout(10000UL, startAgainTimeout);
541                         NetSetHandler(startAgainHandler);
542                 } else {
543                         NetState = NETLOOP_FAIL;
544                 }
545         } else {
546                 NetState = NETLOOP_RESTART;
547         }
548 }
549
550 /**********************************************************************/
551 /*
552  *      Miscelaneous bits.
553  */
554
555 rxhand_f *
556 NetGetHandler(void)
557 {
558         return packetHandler;
559 }
560
561
562 void
563 NetSetHandler(rxhand_f *f)
564 {
565         packetHandler = f;
566 }
567
568 #ifdef CONFIG_CMD_TFTPPUT
569 void net_set_icmp_handler(rxhand_icmp_f *f)
570 {
571         packet_icmp_handler = f;
572 }
573 #endif
574
575 void
576 NetSetTimeout(ulong iv, thand_f *f)
577 {
578         if (iv == 0) {
579                 timeHandler = (thand_f *)0;
580         } else {
581                 timeHandler = f;
582                 timeStart = get_timer(0);
583                 timeDelta = iv;
584         }
585 }
586
587 int NetSendUDPPacket(uchar *ether, IPaddr_t dest, int dport, int sport,
588                 int payload_len)
589 {
590         uchar *pkt;
591         int need_arp = 0;
592         int eth_hdr_size;
593         int pkt_hdr_size;
594
595         /* convert to new style broadcast */
596         if (dest == 0)
597                 dest = 0xFFFFFFFF;
598
599         /* if broadcast, make the ether address a broadcast and don't do ARP */
600         if (dest == 0xFFFFFFFF)
601                 ether = NetBcastAddr;
602
603         /*
604          * if MAC address was not discovered yet, save the packet and do
605          * an ARP request
606          */
607         if (memcmp(ether, NetEtherNullAddr, 6) == 0) {
608                 need_arp = 1;
609                 pkt = NetArpWaitTxPacket;
610         } else
611                 pkt = (uchar *)NetTxPacket;
612
613         eth_hdr_size = NetSetEther(pkt, ether, PROT_IP);
614         pkt += eth_hdr_size;
615         net_set_udp_header(pkt, dest, dport, sport, payload_len);
616         pkt_hdr_size = eth_hdr_size + IP_UDP_HDR_SIZE;
617
618         if (need_arp) {
619                 debug("sending ARP for %pI4\n", &dest);
620
621                 /* save the ip and eth addr for the packet to send after arp */
622                 NetArpWaitPacketIP = dest;
623                 NetArpWaitPacketMAC = ether;
624
625                 /*
626                  * Copy the packet data from the NetTxPacket into the
627                  *   NetArpWaitTxPacket to send after arp
628                  */
629                 memcpy(pkt + IP_UDP_HDR_SIZE, (uchar *)NetTxPacket +
630                         pkt_hdr_size, payload_len);
631
632                 /* size of the waiting packet */
633                 NetArpWaitTxPacketSize = pkt_hdr_size + payload_len;
634
635                 /* and do the ARP request */
636                 NetArpWaitTry = 1;
637                 NetArpWaitTimerStart = get_timer(0);
638                 ArpRequest();
639                 return 1;       /* waiting */
640         } else {
641                 debug("sending UDP to %pI4/%pM\n", &dest, ether);
642                 NetSendPacket(NetTxPacket, pkt_hdr_size + payload_len);
643                 return 0;       /* transmitted */
644         }
645 }
646
647 #ifdef CONFIG_IP_DEFRAG
648 /*
649  * This function collects fragments in a single packet, according
650  * to the algorithm in RFC815. It returns NULL or the pointer to
651  * a complete packet, in static storage
652  */
653 #ifndef CONFIG_NET_MAXDEFRAG
654 #define CONFIG_NET_MAXDEFRAG 16384
655 #endif
656 /*
657  * MAXDEFRAG, above, is chosen in the config file and  is real data
658  * so we need to add the NFS overhead, which is more than TFTP.
659  * To use sizeof in the internal unnamed structures, we need a real
660  * instance (can't do "sizeof(struct rpc_t.u.reply))", unfortunately).
661  * The compiler doesn't complain nor allocates the actual structure
662  */
663 static struct rpc_t rpc_specimen;
664 #define IP_PKTSIZE (CONFIG_NET_MAXDEFRAG + sizeof(rpc_specimen.u.reply))
665
666 #define IP_MAXUDP (IP_PKTSIZE - IP_HDR_SIZE)
667
668 /*
669  * this is the packet being assembled, either data or frag control.
670  * Fragments go by 8 bytes, so this union must be 8 bytes long
671  */
672 struct hole {
673         /* first_byte is address of this structure */
674         u16 last_byte;  /* last byte in this hole + 1 (begin of next hole) */
675         u16 next_hole;  /* index of next (in 8-b blocks), 0 == none */
676         u16 prev_hole;  /* index of prev, 0 == none */
677         u16 unused;
678 };
679
680 static struct ip_udp_hdr *__NetDefragment(struct ip_udp_hdr *ip, int *lenp)
681 {
682         static uchar pkt_buff[IP_PKTSIZE] __aligned(PKTALIGN);
683         static u16 first_hole, total_len;
684         struct hole *payload, *thisfrag, *h, *newh;
685         struct ip_udp_hdr *localip = (struct ip_udp_hdr *)pkt_buff;
686         uchar *indata = (uchar *)ip;
687         int offset8, start, len, done = 0;
688         u16 ip_off = ntohs(ip->ip_off);
689
690         /* payload starts after IP header, this fragment is in there */
691         payload = (struct hole *)(pkt_buff + IP_HDR_SIZE);
692         offset8 =  (ip_off & IP_OFFS);
693         thisfrag = payload + offset8;
694         start = offset8 * 8;
695         len = ntohs(ip->ip_len) - IP_HDR_SIZE;
696
697         if (start + len > IP_MAXUDP) /* fragment extends too far */
698                 return NULL;
699
700         if (!total_len || localip->ip_id != ip->ip_id) {
701                 /* new (or different) packet, reset structs */
702                 total_len = 0xffff;
703                 payload[0].last_byte = ~0;
704                 payload[0].next_hole = 0;
705                 payload[0].prev_hole = 0;
706                 first_hole = 0;
707                 /* any IP header will work, copy the first we received */
708                 memcpy(localip, ip, IP_HDR_SIZE);
709         }
710
711         /*
712          * What follows is the reassembly algorithm. We use the payload
713          * array as a linked list of hole descriptors, as each hole starts
714          * at a multiple of 8 bytes. However, last byte can be whatever value,
715          * so it is represented as byte count, not as 8-byte blocks.
716          */
717
718         h = payload + first_hole;
719         while (h->last_byte < start) {
720                 if (!h->next_hole) {
721                         /* no hole that far away */
722                         return NULL;
723                 }
724                 h = payload + h->next_hole;
725         }
726
727         /* last fragment may be 1..7 bytes, the "+7" forces acceptance */
728         if (offset8 + ((len + 7) / 8) <= h - payload) {
729                 /* no overlap with holes (dup fragment?) */
730                 return NULL;
731         }
732
733         if (!(ip_off & IP_FLAGS_MFRAG)) {
734                 /* no more fragmentss: truncate this (last) hole */
735                 total_len = start + len;
736                 h->last_byte = start + len;
737         }
738
739         /*
740          * There is some overlap: fix the hole list. This code doesn't
741          * deal with a fragment that overlaps with two different holes
742          * (thus being a superset of a previously-received fragment).
743          */
744
745         if ((h >= thisfrag) && (h->last_byte <= start + len)) {
746                 /* complete overlap with hole: remove hole */
747                 if (!h->prev_hole && !h->next_hole) {
748                         /* last remaining hole */
749                         done = 1;
750                 } else if (!h->prev_hole) {
751                         /* first hole */
752                         first_hole = h->next_hole;
753                         payload[h->next_hole].prev_hole = 0;
754                 } else if (!h->next_hole) {
755                         /* last hole */
756                         payload[h->prev_hole].next_hole = 0;
757                 } else {
758                         /* in the middle of the list */
759                         payload[h->next_hole].prev_hole = h->prev_hole;
760                         payload[h->prev_hole].next_hole = h->next_hole;
761                 }
762
763         } else if (h->last_byte <= start + len) {
764                 /* overlaps with final part of the hole: shorten this hole */
765                 h->last_byte = start;
766
767         } else if (h >= thisfrag) {
768                 /* overlaps with initial part of the hole: move this hole */
769                 newh = thisfrag + (len / 8);
770                 *newh = *h;
771                 h = newh;
772                 if (h->next_hole)
773                         payload[h->next_hole].prev_hole = (h - payload);
774                 if (h->prev_hole)
775                         payload[h->prev_hole].next_hole = (h - payload);
776                 else
777                         first_hole = (h - payload);
778
779         } else {
780                 /* fragment sits in the middle: split the hole */
781                 newh = thisfrag + (len / 8);
782                 *newh = *h;
783                 h->last_byte = start;
784                 h->next_hole = (newh - payload);
785                 newh->prev_hole = (h - payload);
786                 if (newh->next_hole)
787                         payload[newh->next_hole].prev_hole = (newh - payload);
788         }
789
790         /* finally copy this fragment and possibly return whole packet */
791         memcpy((uchar *)thisfrag, indata + IP_HDR_SIZE, len);
792         if (!done)
793                 return NULL;
794
795         localip->ip_len = htons(total_len);
796         *lenp = total_len + IP_HDR_SIZE;
797         return localip;
798 }
799
800 static inline struct ip_udp_hdr *NetDefragment(struct ip_udp_hdr *ip, int *lenp)
801 {
802         u16 ip_off = ntohs(ip->ip_off);
803         if (!(ip_off & (IP_OFFS | IP_FLAGS_MFRAG)))
804                 return ip; /* not a fragment */
805         return __NetDefragment(ip, lenp);
806 }
807
808 #else /* !CONFIG_IP_DEFRAG */
809
810 static inline struct ip_udp_hdr *NetDefragment(struct ip_udp_hdr *ip, int *lenp)
811 {
812         u16 ip_off = ntohs(ip->ip_off);
813         if (!(ip_off & (IP_OFFS | IP_FLAGS_MFRAG)))
814                 return ip; /* not a fragment */
815         return NULL;
816 }
817 #endif
818
819 /**
820  * Receive an ICMP packet. We deal with REDIRECT and PING here, and silently
821  * drop others.
822  *
823  * @parma ip    IP packet containing the ICMP
824  */
825 static void receive_icmp(struct ip_udp_hdr *ip, int len,
826                         IPaddr_t src_ip, struct ethernet_hdr *et)
827 {
828         struct icmp_hdr *icmph = (struct icmp_hdr *)&ip->udp_src;
829
830         switch (icmph->type) {
831         case ICMP_REDIRECT:
832                 if (icmph->code != ICMP_REDIR_HOST)
833                         return;
834                 printf(" ICMP Host Redirect to %pI4 ",
835                         &icmph->un.gateway);
836                 break;
837         default:
838 #if defined(CONFIG_CMD_PING)
839                 ping_receive(et, ip, len);
840 #endif
841 #ifdef CONFIG_CMD_TFTPPUT
842                 if (packet_icmp_handler)
843                         packet_icmp_handler(icmph->type, icmph->code,
844                                 ntohs(ip->udp_dst), src_ip, ntohs(ip->udp_src),
845                                 icmph->un.data, ntohs(ip->udp_len));
846 #endif
847                 break;
848         }
849 }
850
851 void
852 NetReceive(uchar *inpkt, int len)
853 {
854         struct ethernet_hdr *et;
855         struct ip_udp_hdr *ip;
856         IPaddr_t dst_ip;
857         IPaddr_t src_ip;
858         int eth_proto;
859 #if defined(CONFIG_CMD_CDP)
860         int iscdp;
861 #endif
862         ushort cti = 0, vlanid = VLAN_NONE, myvlanid, mynvlanid;
863
864         debug("packet received\n");
865
866         NetRxPacket = inpkt;
867         NetRxPacketLen = len;
868         et = (struct ethernet_hdr *)inpkt;
869
870         /* too small packet? */
871         if (len < ETHER_HDR_SIZE)
872                 return;
873
874 #ifdef CONFIG_API
875         if (push_packet) {
876                 (*push_packet)(inpkt, len);
877                 return;
878         }
879 #endif
880
881 #if defined(CONFIG_CMD_CDP)
882         /* keep track if packet is CDP */
883         iscdp = is_cdp_packet(et->et_dest);
884 #endif
885
886         myvlanid = ntohs(NetOurVLAN);
887         if (myvlanid == (ushort)-1)
888                 myvlanid = VLAN_NONE;
889         mynvlanid = ntohs(NetOurNativeVLAN);
890         if (mynvlanid == (ushort)-1)
891                 mynvlanid = VLAN_NONE;
892
893         eth_proto = ntohs(et->et_protlen);
894
895         debug("packet received\n");
896
897         if (eth_proto < 1514) {
898                 struct e802_hdr *et802 = (struct e802_hdr *)et;
899                 /*
900                  *      Got a 802.2 packet.  Check the other protocol field.
901                  *      XXX VLAN over 802.2+SNAP not implemented!
902                  */
903                 eth_proto = ntohs(et802->et_prot);
904
905                 ip = (struct ip_udp_hdr *)(inpkt + E802_HDR_SIZE);
906                 len -= E802_HDR_SIZE;
907
908         } else if (eth_proto != PROT_VLAN) {    /* normal packet */
909                 ip = (struct ip_udp_hdr *)(inpkt + ETHER_HDR_SIZE);
910                 len -= ETHER_HDR_SIZE;
911
912         } else {                        /* VLAN packet */
913                 struct vlan_ethernet_hdr *vet =
914                         (struct vlan_ethernet_hdr *)et;
915
916                 debug("VLAN packet received\n");
917
918                 /* too small packet? */
919                 if (len < VLAN_ETHER_HDR_SIZE)
920                         return;
921
922                 /* if no VLAN active */
923                 if ((ntohs(NetOurVLAN) & VLAN_IDMASK) == VLAN_NONE
924 #if defined(CONFIG_CMD_CDP)
925                                 && iscdp == 0
926 #endif
927                                 )
928                         return;
929
930                 cti = ntohs(vet->vet_tag);
931                 vlanid = cti & VLAN_IDMASK;
932                 eth_proto = ntohs(vet->vet_type);
933
934                 ip = (struct ip_udp_hdr *)(inpkt + VLAN_ETHER_HDR_SIZE);
935                 len -= VLAN_ETHER_HDR_SIZE;
936         }
937
938         debug("Receive from protocol 0x%x\n", eth_proto);
939
940 #if defined(CONFIG_CMD_CDP)
941         if (iscdp) {
942                 cdp_receive((uchar *)ip, len);
943                 return;
944         }
945 #endif
946
947         if ((myvlanid & VLAN_IDMASK) != VLAN_NONE) {
948                 if (vlanid == VLAN_NONE)
949                         vlanid = (mynvlanid & VLAN_IDMASK);
950                 /* not matched? */
951                 if (vlanid != (myvlanid & VLAN_IDMASK))
952                         return;
953         }
954
955         switch (eth_proto) {
956
957         case PROT_ARP:
958                 ArpReceive(et, ip, len);
959                 break;
960
961 #ifdef CONFIG_CMD_RARP
962         case PROT_RARP:
963                 rarp_receive(ip, len);
964                 break;
965 #endif
966         case PROT_IP:
967                 debug("Got IP\n");
968                 /* Before we start poking the header, make sure it is there */
969                 if (len < IP_UDP_HDR_SIZE) {
970                         debug("len bad %d < %lu\n", len,
971                                 (ulong)IP_UDP_HDR_SIZE);
972                         return;
973                 }
974                 /* Check the packet length */
975                 if (len < ntohs(ip->ip_len)) {
976                         printf("len bad %d < %d\n", len, ntohs(ip->ip_len));
977                         return;
978                 }
979                 len = ntohs(ip->ip_len);
980                 debug("len=%d, v=%02x\n", len, ip->ip_hl_v & 0xff);
981
982                 /* Can't deal with anything except IPv4 */
983                 if ((ip->ip_hl_v & 0xf0) != 0x40)
984                         return;
985                 /* Can't deal with IP options (headers != 20 bytes) */
986                 if ((ip->ip_hl_v & 0x0f) > 0x05)
987                         return;
988                 /* Check the Checksum of the header */
989                 if (!NetCksumOk((uchar *)ip, IP_HDR_SIZE / 2)) {
990                         puts("checksum bad\n");
991                         return;
992                 }
993                 /* If it is not for us, ignore it */
994                 dst_ip = NetReadIP(&ip->ip_dst);
995                 if (NetOurIP && dst_ip != NetOurIP && dst_ip != 0xFFFFFFFF) {
996 #ifdef CONFIG_MCAST_TFTP
997                         if (Mcast_addr != dst_ip)
998 #endif
999                                 return;
1000                 }
1001                 /* Read source IP address for later use */
1002                 src_ip = NetReadIP(&ip->ip_src);
1003                 /*
1004                  * The function returns the unchanged packet if it's not
1005                  * a fragment, and either the complete packet or NULL if
1006                  * it is a fragment (if !CONFIG_IP_DEFRAG, it returns NULL)
1007                  */
1008                 ip = NetDefragment(ip, &len);
1009                 if (!ip)
1010                         return;
1011                 /*
1012                  * watch for ICMP host redirects
1013                  *
1014                  * There is no real handler code (yet). We just watch
1015                  * for ICMP host redirect messages. In case anybody
1016                  * sees these messages: please contact me
1017                  * (wd@denx.de), or - even better - send me the
1018                  * necessary fixes :-)
1019                  *
1020                  * Note: in all cases where I have seen this so far
1021                  * it was a problem with the router configuration,
1022                  * for instance when a router was configured in the
1023                  * BOOTP reply, but the TFTP server was on the same
1024                  * subnet. So this is probably a warning that your
1025                  * configuration might be wrong. But I'm not really
1026                  * sure if there aren't any other situations.
1027                  *
1028                  * Simon Glass <sjg@chromium.org>: We get an ICMP when
1029                  * we send a tftp packet to a dead connection, or when
1030                  * there is no server at the other end.
1031                  */
1032                 if (ip->ip_p == IPPROTO_ICMP) {
1033                         receive_icmp(ip, len, src_ip, et);
1034                         return;
1035                 } else if (ip->ip_p != IPPROTO_UDP) {   /* Only UDP packets */
1036                         return;
1037                 }
1038
1039 #ifdef CONFIG_UDP_CHECKSUM
1040                 if (ip->udp_xsum != 0) {
1041                         ulong   xsum;
1042                         ushort *sumptr;
1043                         ushort  sumlen;
1044
1045                         xsum  = ip->ip_p;
1046                         xsum += (ntohs(ip->udp_len));
1047                         xsum += (ntohl(ip->ip_src) >> 16) & 0x0000ffff;
1048                         xsum += (ntohl(ip->ip_src) >>  0) & 0x0000ffff;
1049                         xsum += (ntohl(ip->ip_dst) >> 16) & 0x0000ffff;
1050                         xsum += (ntohl(ip->ip_dst) >>  0) & 0x0000ffff;
1051
1052                         sumlen = ntohs(ip->udp_len);
1053                         sumptr = (ushort *) &(ip->udp_src);
1054
1055                         while (sumlen > 1) {
1056                                 ushort sumdata;
1057
1058                                 sumdata = *sumptr++;
1059                                 xsum += ntohs(sumdata);
1060                                 sumlen -= 2;
1061                         }
1062                         if (sumlen > 0) {
1063                                 ushort sumdata;
1064
1065                                 sumdata = *(unsigned char *) sumptr;
1066                                 sumdata = (sumdata << 8) & 0xff00;
1067                                 xsum += sumdata;
1068                         }
1069                         while ((xsum >> 16) != 0) {
1070                                 xsum = (xsum & 0x0000ffff) +
1071                                        ((xsum >> 16) & 0x0000ffff);
1072                         }
1073                         if ((xsum != 0x00000000) && (xsum != 0x0000ffff)) {
1074                                 printf(" UDP wrong checksum %08lx %08x\n",
1075                                         xsum, ntohs(ip->udp_xsum));
1076                                 return;
1077                         }
1078                 }
1079 #endif
1080
1081
1082 #ifdef CONFIG_NETCONSOLE
1083                 nc_input_packet((uchar *)ip + IP_UDP_HDR_SIZE,
1084                                         ntohs(ip->udp_dst),
1085                                         ntohs(ip->udp_src),
1086                                         ntohs(ip->udp_len) - UDP_HDR_SIZE);
1087 #endif
1088                 /*
1089                  *      IP header OK.  Pass the packet to the current handler.
1090                  */
1091                 (*packetHandler)((uchar *)ip + IP_UDP_HDR_SIZE,
1092                                         ntohs(ip->udp_dst),
1093                                         src_ip,
1094                                         ntohs(ip->udp_src),
1095                                         ntohs(ip->udp_len) - UDP_HDR_SIZE);
1096                 break;
1097         }
1098 }
1099
1100
1101 /**********************************************************************/
1102
1103 static int net_check_prereq(enum proto_t protocol)
1104 {
1105         switch (protocol) {
1106                 /* Fall through */
1107 #if defined(CONFIG_CMD_PING)
1108         case PING:
1109                 if (NetPingIP == 0) {
1110                         puts("*** ERROR: ping address not given\n");
1111                         return 1;
1112                 }
1113                 goto common;
1114 #endif
1115 #if defined(CONFIG_CMD_SNTP)
1116         case SNTP:
1117                 if (NetNtpServerIP == 0) {
1118                         puts("*** ERROR: NTP server address not given\n");
1119                         return 1;
1120                 }
1121                 goto common;
1122 #endif
1123 #if defined(CONFIG_CMD_DNS)
1124         case DNS:
1125                 if (NetOurDNSIP == 0) {
1126                         puts("*** ERROR: DNS server address not given\n");
1127                         return 1;
1128                 }
1129                 goto common;
1130 #endif
1131 #if defined(CONFIG_CMD_NFS)
1132         case NFS:
1133 #endif
1134         case TFTPGET:
1135         case TFTPPUT:
1136                 if (NetServerIP == 0) {
1137                         puts("*** ERROR: `serverip' not set\n");
1138                         return 1;
1139                 }
1140 #if     defined(CONFIG_CMD_PING) || defined(CONFIG_CMD_SNTP) || \
1141         defined(CONFIG_CMD_DNS)
1142 common:
1143 #endif
1144                 /* Fall through */
1145
1146         case NETCONS:
1147         case TFTPSRV:
1148                 if (NetOurIP == 0) {
1149                         puts("*** ERROR: `ipaddr' not set\n");
1150                         return 1;
1151                 }
1152                 /* Fall through */
1153
1154 #ifdef CONFIG_CMD_RARP
1155         case RARP:
1156 #endif
1157         case BOOTP:
1158         case CDP:
1159         case DHCP:
1160                 if (memcmp(NetOurEther, "\0\0\0\0\0\0", 6) == 0) {
1161                         int num = eth_get_dev_index();
1162
1163                         switch (num) {
1164                         case -1:
1165                                 puts("*** ERROR: No ethernet found.\n");
1166                                 return 1;
1167                         case 0:
1168                                 puts("*** ERROR: `ethaddr' not set\n");
1169                                 break;
1170                         default:
1171                                 printf("*** ERROR: `eth%daddr' not set\n",
1172                                         num);
1173                                 break;
1174                         }
1175
1176                         NetStartAgain();
1177                         return 2;
1178                 }
1179                 /* Fall through */
1180         default:
1181                 return 0;
1182         }
1183         return 0;               /* OK */
1184 }
1185 /**********************************************************************/
1186
1187 int
1188 NetCksumOk(uchar *ptr, int len)
1189 {
1190         return !((NetCksum(ptr, len) + 1) & 0xfffe);
1191 }
1192
1193
1194 unsigned
1195 NetCksum(uchar *ptr, int len)
1196 {
1197         ulong   xsum;
1198         ushort *p = (ushort *)ptr;
1199
1200         xsum = 0;
1201         while (len-- > 0)
1202                 xsum += *p++;
1203         xsum = (xsum & 0xffff) + (xsum >> 16);
1204         xsum = (xsum & 0xffff) + (xsum >> 16);
1205         return xsum & 0xffff;
1206 }
1207
1208 int
1209 NetEthHdrSize(void)
1210 {
1211         ushort myvlanid;
1212
1213         myvlanid = ntohs(NetOurVLAN);
1214         if (myvlanid == (ushort)-1)
1215                 myvlanid = VLAN_NONE;
1216
1217         return ((myvlanid & VLAN_IDMASK) == VLAN_NONE) ? ETHER_HDR_SIZE :
1218                 VLAN_ETHER_HDR_SIZE;
1219 }
1220
1221 int
1222 NetSetEther(uchar *xet, uchar * addr, uint prot)
1223 {
1224         struct ethernet_hdr *et = (struct ethernet_hdr *)xet;
1225         ushort myvlanid;
1226
1227         myvlanid = ntohs(NetOurVLAN);
1228         if (myvlanid == (ushort)-1)
1229                 myvlanid = VLAN_NONE;
1230
1231         memcpy(et->et_dest, addr, 6);
1232         memcpy(et->et_src, NetOurEther, 6);
1233         if ((myvlanid & VLAN_IDMASK) == VLAN_NONE) {
1234                 et->et_protlen = htons(prot);
1235                 return ETHER_HDR_SIZE;
1236         } else {
1237                 struct vlan_ethernet_hdr *vet =
1238                         (struct vlan_ethernet_hdr *)xet;
1239
1240                 vet->vet_vlan_type = htons(PROT_VLAN);
1241                 vet->vet_tag = htons((0 << 5) | (myvlanid & VLAN_IDMASK));
1242                 vet->vet_type = htons(prot);
1243                 return VLAN_ETHER_HDR_SIZE;
1244         }
1245 }
1246
1247 void net_set_ip_header(uchar *pkt, IPaddr_t dest, IPaddr_t source)
1248 {
1249         struct ip_udp_hdr *ip = (struct ip_udp_hdr *)pkt;
1250
1251         /*
1252          *      Construct an IP header.
1253          */
1254         /* IP_HDR_SIZE / 4 (not including UDP) */
1255         ip->ip_hl_v  = 0x45;
1256         ip->ip_tos   = 0;
1257         ip->ip_len   = htons(IP_HDR_SIZE);
1258         ip->ip_id    = htons(NetIPID++);
1259         ip->ip_off   = htons(IP_FLAGS_DFRAG);   /* Don't fragment */
1260         ip->ip_ttl   = 255;
1261         ip->ip_sum   = 0;
1262         /* already in network byte order */
1263         NetCopyIP((void *)&ip->ip_src, &source);
1264         /* already in network byte order */
1265         NetCopyIP((void *)&ip->ip_dst, &dest);
1266 }
1267
1268 void net_set_udp_header(uchar *pkt, IPaddr_t dest, int dport, int sport,
1269                         int len)
1270 {
1271         struct ip_udp_hdr *ip = (struct ip_udp_hdr *)pkt;
1272
1273         /*
1274          *      If the data is an odd number of bytes, zero the
1275          *      byte after the last byte so that the checksum
1276          *      will work.
1277          */
1278         if (len & 1)
1279                 pkt[IP_UDP_HDR_SIZE + len] = 0;
1280
1281         net_set_ip_header(pkt, dest, NetOurIP);
1282         ip->ip_len   = htons(IP_UDP_HDR_SIZE + len);
1283         ip->ip_p     = IPPROTO_UDP;
1284         ip->ip_sum   = ~NetCksum((uchar *)ip, IP_HDR_SIZE >> 1);
1285
1286         ip->udp_src  = htons(sport);
1287         ip->udp_dst  = htons(dport);
1288         ip->udp_len  = htons(UDP_HDR_SIZE + len);
1289         ip->udp_xsum = 0;
1290 }
1291
1292 void copy_filename(char *dst, const char *src, int size)
1293 {
1294         if (*src && (*src == '"')) {
1295                 ++src;
1296                 --size;
1297         }
1298
1299         while ((--size > 0) && *src && (*src != '"'))
1300                 *dst++ = *src++;
1301         *dst = '\0';
1302 }
1303
1304 #if     defined(CONFIG_CMD_NFS)         || \
1305         defined(CONFIG_CMD_SNTP)        || \
1306         defined(CONFIG_CMD_DNS)
1307 /*
1308  * make port a little random (1024-17407)
1309  * This keeps the math somewhat trivial to compute, and seems to work with
1310  * all supported protocols/clients/servers
1311  */
1312 unsigned int random_port(void)
1313 {
1314         return 1024 + (get_timer(0) % 0x4000);
1315 }
1316 #endif
1317
1318 void ip_to_string(IPaddr_t x, char *s)
1319 {
1320         x = ntohl(x);
1321         sprintf(s, "%d.%d.%d.%d",
1322                 (int) ((x >> 24) & 0xff),
1323                 (int) ((x >> 16) & 0xff),
1324                 (int) ((x >> 8) & 0xff), (int) ((x >> 0) & 0xff)
1325         );
1326 }
1327
1328 void VLAN_to_string(ushort x, char *s)
1329 {
1330         x = ntohs(x);
1331
1332         if (x == (ushort)-1)
1333                 x = VLAN_NONE;
1334
1335         if (x == VLAN_NONE)
1336                 strcpy(s, "none");
1337         else
1338                 sprintf(s, "%d", x & VLAN_IDMASK);
1339 }
1340
1341 ushort string_to_VLAN(const char *s)
1342 {
1343         ushort id;
1344
1345         if (s == NULL)
1346                 return htons(VLAN_NONE);
1347
1348         if (*s < '0' || *s > '9')
1349                 id = VLAN_NONE;
1350         else
1351                 id = (ushort)simple_strtoul(s, NULL, 10);
1352
1353         return htons(id);
1354 }
1355
1356 ushort getenv_VLAN(char *var)
1357 {
1358         return string_to_VLAN(getenv(var));
1359 }