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