]> git.kernelconcepts.de Git - karo-tx-uboot.git/blob - net/net.c
f98877db7926cb8d7a13334c43fa403c80a4453c
[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         bd_t *bd = gd->bd;
328         int ret = -1;
329
330         NetRestarted = 0;
331         NetDevExists = 0;
332         NetTryCount = 1;
333         debug_cond(DEBUG_INT_STATE, "--- NetLoop Entry\n");
334
335         bootstage_mark_name(BOOTSTAGE_ID_ETH_START, "eth_start");
336         net_init();
337         if (eth_is_on_demand_init() || protocol != NETCONS) {
338                 eth_halt();
339                 eth_set_current();
340                 if (eth_init(bd) < 0) {
341                         eth_halt();
342                         return -1;
343                 }
344         } else
345                 eth_init_state_only(bd);
346
347 restart:
348 #ifdef CONFIG_USB_KEYBOARD
349         net_busy_flag = 0;
350 #endif
351         net_set_state(NETLOOP_CONTINUE);
352
353         /*
354          *      Start the ball rolling with the given start function.  From
355          *      here on, this code is a state machine driven by received
356          *      packets and timer events.
357          */
358         debug_cond(DEBUG_INT_STATE, "--- NetLoop Init\n");
359         NetInitLoop();
360
361         switch (net_check_prereq(protocol)) {
362         case 1:
363                 /* network not configured */
364                 eth_halt();
365                 return -1;
366
367         case 2:
368                 /* network device not configured */
369                 break;
370
371         case 0:
372                 NetDevExists = 1;
373                 NetBootFileXferSize = 0;
374                 switch (protocol) {
375                 case TFTPGET:
376 #ifdef CONFIG_CMD_TFTPPUT
377                 case TFTPPUT:
378 #endif
379                         /* always use ARP to get server ethernet address */
380                         TftpStart(protocol);
381                         break;
382 #ifdef CONFIG_CMD_TFTPSRV
383                 case TFTPSRV:
384                         TftpStartServer();
385                         break;
386 #endif
387 #if defined(CONFIG_CMD_DHCP)
388                 case DHCP:
389                         BootpReset();
390                         NetOurIP = 0;
391                         DhcpRequest();          /* Basically same as BOOTP */
392                         break;
393 #endif
394
395                 case BOOTP:
396                         BootpReset();
397                         NetOurIP = 0;
398                         BootpRequest();
399                         break;
400
401 #if defined(CONFIG_CMD_RARP)
402                 case RARP:
403                         RarpTry = 0;
404                         NetOurIP = 0;
405                         RarpRequest();
406                         break;
407 #endif
408 #if defined(CONFIG_CMD_PING)
409                 case PING:
410                         ping_start();
411                         break;
412 #endif
413 #if defined(CONFIG_CMD_NFS)
414                 case NFS:
415                         NfsStart();
416                         break;
417 #endif
418 #if defined(CONFIG_CMD_CDP)
419                 case CDP:
420                         CDPStart();
421                         break;
422 #endif
423 #if defined (CONFIG_NETCONSOLE) && !(CONFIG_SPL_BUILD)
424                 case NETCONS:
425                         NcStart();
426                         break;
427 #endif
428 #if defined(CONFIG_CMD_SNTP)
429                 case SNTP:
430                         SntpStart();
431                         break;
432 #endif
433 #if defined(CONFIG_CMD_DNS)
434                 case DNS:
435                         DnsStart();
436                         break;
437 #endif
438 #if defined(CONFIG_CMD_LINK_LOCAL)
439                 case LINKLOCAL:
440                         link_local_start();
441                         break;
442 #endif
443 #if defined(CONFIG_CMD_BOOTCE)
444                 case BOOTME:
445                         BootmeStart();
446                         break;
447 #endif
448                 default:
449                         break;
450                 }
451
452                 break;
453         }
454
455 #if defined(CONFIG_MII) || defined(CONFIG_CMD_MII)
456 #if     defined(CONFIG_SYS_FAULT_ECHO_LINK_DOWN)        && \
457         defined(CONFIG_STATUS_LED)                      && \
458         defined(STATUS_LED_RED)
459         /*
460          * Echo the inverted link state to the fault LED.
461          */
462         if (miiphy_link(eth_get_dev()->name, CONFIG_SYS_FAULT_MII_ADDR))
463                 status_led_set(STATUS_LED_RED, STATUS_LED_OFF);
464         else
465                 status_led_set(STATUS_LED_RED, STATUS_LED_ON);
466 #endif /* CONFIG_SYS_FAULT_ECHO_LINK_DOWN, ... */
467 #endif /* CONFIG_MII, ... */
468 #ifdef CONFIG_USB_KEYBOARD
469         net_busy_flag = 1;
470 #endif
471
472         /*
473          *      Main packet reception loop.  Loop receiving packets until
474          *      someone sets `net_state' to a state that terminates.
475          */
476         for (;;) {
477                 WATCHDOG_RESET();
478 #ifdef CONFIG_SHOW_ACTIVITY
479                 show_activity(1);
480 #endif
481                 /*
482                  *      Check the ethernet for a new packet.  The ethernet
483                  *      receive routine will process it.
484                  */
485                 eth_rx();
486
487                 /*
488                  *      Abort if ctrl-c was pressed.
489                  */
490                 if (ctrlc()) {
491                         /* cancel any ARP that may not have completed */
492                         NetArpWaitPacketIP = 0;
493
494                         net_cleanup_loop();
495                         eth_halt();
496                         /* Invalidate the last protocol */
497                         eth_set_last_protocol(BOOTP);
498
499                         puts("\nAbort\n");
500                         /* include a debug print as well incase the debug
501                            messages are directed to stderr */
502                         debug_cond(DEBUG_INT_STATE, "--- NetLoop Abort!\n");
503                         goto done;
504                 }
505
506                 ArpTimeoutCheck();
507
508                 /*
509                  *      Check for a timeout, and run the timeout handler
510                  *      if we have one.
511                  */
512                 if (timeHandler && ((get_timer(timeStart)) > timeDelta)) {
513                         thand_f *x;
514
515 #if defined(CONFIG_MII) || defined(CONFIG_CMD_MII)
516 #if     defined(CONFIG_SYS_FAULT_ECHO_LINK_DOWN)        && \
517         defined(CONFIG_STATUS_LED)                      && \
518         defined(STATUS_LED_RED)
519                         /*
520                          * Echo the inverted link state to the fault LED.
521                          */
522                         if (miiphy_link(eth_get_dev()->name,
523                                        CONFIG_SYS_FAULT_MII_ADDR)) {
524                                 status_led_set(STATUS_LED_RED, STATUS_LED_OFF);
525                         } else {
526                                 status_led_set(STATUS_LED_RED, STATUS_LED_ON);
527                         }
528 #endif /* CONFIG_SYS_FAULT_ECHO_LINK_DOWN, ... */
529 #endif /* CONFIG_MII, ... */
530                         debug_cond(DEBUG_INT_STATE, "--- NetLoop timeout\n");
531                         x = timeHandler;
532                         timeHandler = (thand_f *)0;
533                         (*x)();
534                 }
535
536
537                 switch (net_state) {
538
539                 case NETLOOP_RESTART:
540                         NetRestarted = 1;
541                         goto restart;
542
543                 case NETLOOP_SUCCESS:
544                         net_cleanup_loop();
545                         if (NetBootFileXferSize > 0) {
546                                 printf("Bytes transferred = %ld (%lx hex)\n",
547                                         NetBootFileXferSize,
548                                         NetBootFileXferSize);
549                                 setenv_hex("filesize", NetBootFileXferSize);
550                                 setenv_hex("fileaddr", load_addr);
551                         }
552                         if (protocol != NETCONS) {
553                                 eth_halt();
554                         } else {
555                                 eth_halt_state_only();
556                         }
557
558                         eth_set_last_protocol(protocol);
559
560                         ret = NetBootFileXferSize;
561                         debug_cond(DEBUG_INT_STATE, "--- NetLoop Success!\n");
562                         goto done;
563
564                 case NETLOOP_FAIL:
565                         net_cleanup_loop();
566                         /* Invalidate the last protocol */
567                         eth_set_last_protocol(BOOTP);
568                         debug_cond(DEBUG_INT_STATE, "--- NetLoop Fail!\n");
569                         goto done;
570
571                 case NETLOOP_CONTINUE:
572                         continue;
573                 }
574         }
575
576 done:
577 #ifdef CONFIG_USB_KEYBOARD
578         net_busy_flag = 0;
579 #endif
580 #ifdef CONFIG_CMD_TFTPPUT
581         /* Clear out the handlers */
582         net_set_udp_handler(NULL);
583         net_set_icmp_handler(NULL);
584 #endif
585         return ret;
586 }
587
588 /**********************************************************************/
589
590 static void
591 startAgainTimeout(void)
592 {
593         net_set_state(NETLOOP_RESTART);
594 }
595
596 void NetStartAgain(void)
597 {
598         char *nretry;
599         int retry_forever = 0;
600         unsigned long retrycnt = 0;
601
602         nretry = getenv("netretry");
603         if (nretry) {
604                 if (!strcmp(nretry, "yes"))
605                         retry_forever = 1;
606                 else if (!strcmp(nretry, "no"))
607                         retrycnt = 0;
608                 else if (!strcmp(nretry, "once"))
609                         retrycnt = 1;
610                 else
611                         retrycnt = simple_strtoul(nretry, NULL, 0);
612         } else
613                 retry_forever = 1;
614
615         if ((!retry_forever) && (NetTryCount >= retrycnt)) {
616                 eth_halt();
617                 net_set_state(NETLOOP_FAIL);
618                 return;
619         }
620
621         NetTryCount++;
622
623         eth_halt();
624 #if !defined(CONFIG_NET_DO_NOT_TRY_ANOTHER)
625         eth_try_another(!NetRestarted);
626 #endif
627         eth_init(gd->bd);
628         if (NetRestartWrap) {
629                 NetRestartWrap = 0;
630                 if (NetDevExists) {
631                         NetSetTimeout(10000UL, startAgainTimeout);
632                         net_set_udp_handler(NULL);
633                 } else {
634                         net_set_state(NETLOOP_FAIL);
635                 }
636         } else {
637                 net_set_state(NETLOOP_RESTART);
638         }
639 }
640
641 /**********************************************************************/
642 /*
643  *      Miscelaneous bits.
644  */
645
646 static void dummy_handler(uchar *pkt, unsigned dport,
647                         IPaddr_t sip, unsigned sport,
648                         unsigned len)
649 {
650 }
651
652 rxhand_f *net_get_udp_handler(void)
653 {
654         return udp_packet_handler;
655 }
656
657 void net_set_udp_handler(rxhand_f *f)
658 {
659         debug_cond(DEBUG_INT_STATE, "--- NetLoop UDP handler set (%p)\n", f);
660         if (f == NULL)
661                 udp_packet_handler = dummy_handler;
662         else
663                 udp_packet_handler = f;
664 }
665
666 rxhand_f *net_get_arp_handler(void)
667 {
668         return arp_packet_handler;
669 }
670
671 void net_set_arp_handler(rxhand_f *f)
672 {
673         debug_cond(DEBUG_INT_STATE, "--- NetLoop ARP handler set (%p)\n", f);
674         if (f == NULL)
675                 arp_packet_handler = dummy_handler;
676         else
677                 arp_packet_handler = f;
678 }
679
680 #ifdef CONFIG_CMD_TFTPPUT
681 void net_set_icmp_handler(rxhand_icmp_f *f)
682 {
683         packet_icmp_handler = f;
684 }
685 #endif
686
687 void
688 NetSetTimeout(ulong iv, thand_f *f)
689 {
690         if (iv == 0) {
691                 debug_cond(DEBUG_INT_STATE,
692                         "--- NetLoop timeout handler cancelled\n");
693                 timeHandler = (thand_f *)0;
694         } else {
695                 debug_cond(DEBUG_INT_STATE,
696                         "--- NetLoop timeout handler set (%p)\n", f);
697                 timeHandler = f;
698                 timeStart = get_timer(0);
699                 timeDelta = iv * CONFIG_SYS_HZ / 1000;
700         }
701 }
702
703 int NetSendUDPPacket(uchar *ether, IPaddr_t dest, int dport, int sport,
704                 int payload_len)
705 {
706         uchar *pkt;
707         int eth_hdr_size;
708         int pkt_hdr_size;
709
710         /* make sure the NetTxPacket is initialized (NetInit() was called) */
711         assert(NetTxPacket != NULL);
712         if (NetTxPacket == NULL)
713                 return -1;
714
715         /* convert to new style broadcast */
716         if (dest == 0)
717                 dest = 0xFFFFFFFF;
718
719         /* if broadcast, make the ether address a broadcast and don't do ARP */
720         if (dest == 0xFFFFFFFF)
721                 ether = NetBcastAddr;
722
723         pkt = (uchar *)NetTxPacket;
724
725         eth_hdr_size = NetSetEther(pkt, ether, PROT_IP);
726         pkt += eth_hdr_size;
727         net_set_udp_header(pkt, dest, dport, sport, payload_len);
728         pkt_hdr_size = eth_hdr_size + IP_UDP_HDR_SIZE;
729
730         /* if MAC address was not discovered yet, do an ARP request */
731         if (memcmp(ether, NetEtherNullAddr, 6) == 0) {
732                 debug_cond(DEBUG_DEV_PKT, "sending ARP for %pI4\n", &dest);
733
734                 /* save the ip and eth addr for the packet to send after arp */
735                 NetArpWaitPacketIP = dest;
736                 NetArpWaitPacketMAC = ether;
737
738                 /* size of the waiting packet */
739                 NetArpWaitTxPacketSize = pkt_hdr_size + payload_len;
740
741                 /* and do the ARP request */
742                 NetArpWaitTry = 1;
743                 NetArpWaitTimerStart = get_timer(0);
744                 ArpRequest();
745                 return 1;       /* waiting */
746         } else {
747                 debug_cond(DEBUG_DEV_PKT, "sending UDP to %pI4/%pM\n",
748                         &dest, ether);
749                 NetSendPacket(NetTxPacket, pkt_hdr_size + payload_len);
750                 return 0;       /* transmitted */
751         }
752 }
753
754 #ifdef CONFIG_IP_DEFRAG
755 /*
756  * This function collects fragments in a single packet, according
757  * to the algorithm in RFC815. It returns NULL or the pointer to
758  * a complete packet, in static storage
759  */
760 #ifndef CONFIG_NET_MAXDEFRAG
761 #define CONFIG_NET_MAXDEFRAG 16384
762 #endif
763 /*
764  * MAXDEFRAG, above, is chosen in the config file and  is real data
765  * so we need to add the NFS overhead, which is more than TFTP.
766  * To use sizeof in the internal unnamed structures, we need a real
767  * instance (can't do "sizeof(struct rpc_t.u.reply))", unfortunately).
768  * The compiler doesn't complain nor allocates the actual structure
769  */
770 static struct rpc_t rpc_specimen;
771 #define IP_PKTSIZE (CONFIG_NET_MAXDEFRAG + sizeof(rpc_specimen.u.reply))
772
773 #define IP_MAXUDP (IP_PKTSIZE - IP_HDR_SIZE)
774
775 /*
776  * this is the packet being assembled, either data or frag control.
777  * Fragments go by 8 bytes, so this union must be 8 bytes long
778  */
779 struct hole {
780         /* first_byte is address of this structure */
781         u16 last_byte;  /* last byte in this hole + 1 (begin of next hole) */
782         u16 next_hole;  /* index of next (in 8-b blocks), 0 == none */
783         u16 prev_hole;  /* index of prev, 0 == none */
784         u16 unused;
785 };
786
787 static struct ip_udp_hdr *__NetDefragment(struct ip_udp_hdr *ip, int *lenp)
788 {
789         static uchar pkt_buff[IP_PKTSIZE] __aligned(PKTALIGN);
790         static u16 first_hole, total_len;
791         struct hole *payload, *thisfrag, *h, *newh;
792         struct ip_udp_hdr *localip = (struct ip_udp_hdr *)pkt_buff;
793         uchar *indata = (uchar *)ip;
794         int offset8, start, len, done = 0;
795         u16 ip_off = ntohs(ip->ip_off);
796
797         /* payload starts after IP header, this fragment is in there */
798         payload = (struct hole *)(pkt_buff + IP_HDR_SIZE);
799         offset8 =  (ip_off & IP_OFFS);
800         thisfrag = payload + offset8;
801         start = offset8 * 8;
802         len = ntohs(ip->ip_len) - IP_HDR_SIZE;
803
804         if (start + len > IP_MAXUDP) /* fragment extends too far */
805                 return NULL;
806
807         if (!total_len || localip->ip_id != ip->ip_id) {
808                 /* new (or different) packet, reset structs */
809                 total_len = 0xffff;
810                 payload[0].last_byte = ~0;
811                 payload[0].next_hole = 0;
812                 payload[0].prev_hole = 0;
813                 first_hole = 0;
814                 /* any IP header will work, copy the first we received */
815                 memcpy(localip, ip, IP_HDR_SIZE);
816         }
817
818         /*
819          * What follows is the reassembly algorithm. We use the payload
820          * array as a linked list of hole descriptors, as each hole starts
821          * at a multiple of 8 bytes. However, last byte can be whatever value,
822          * so it is represented as byte count, not as 8-byte blocks.
823          */
824
825         h = payload + first_hole;
826         while (h->last_byte < start) {
827                 if (!h->next_hole) {
828                         /* no hole that far away */
829                         return NULL;
830                 }
831                 h = payload + h->next_hole;
832         }
833
834         /* last fragment may be 1..7 bytes, the "+7" forces acceptance */
835         if (offset8 + ((len + 7) / 8) <= h - payload) {
836                 /* no overlap with holes (dup fragment?) */
837                 return NULL;
838         }
839
840         if (!(ip_off & IP_FLAGS_MFRAG)) {
841                 /* no more fragmentss: truncate this (last) hole */
842                 total_len = start + len;
843                 h->last_byte = start + len;
844         }
845
846         /*
847          * There is some overlap: fix the hole list. This code doesn't
848          * deal with a fragment that overlaps with two different holes
849          * (thus being a superset of a previously-received fragment).
850          */
851
852         if ((h >= thisfrag) && (h->last_byte <= start + len)) {
853                 /* complete overlap with hole: remove hole */
854                 if (!h->prev_hole && !h->next_hole) {
855                         /* last remaining hole */
856                         done = 1;
857                 } else if (!h->prev_hole) {
858                         /* first hole */
859                         first_hole = h->next_hole;
860                         payload[h->next_hole].prev_hole = 0;
861                 } else if (!h->next_hole) {
862                         /* last hole */
863                         payload[h->prev_hole].next_hole = 0;
864                 } else {
865                         /* in the middle of the list */
866                         payload[h->next_hole].prev_hole = h->prev_hole;
867                         payload[h->prev_hole].next_hole = h->next_hole;
868                 }
869
870         } else if (h->last_byte <= start + len) {
871                 /* overlaps with final part of the hole: shorten this hole */
872                 h->last_byte = start;
873
874         } else if (h >= thisfrag) {
875                 /* overlaps with initial part of the hole: move this hole */
876                 newh = thisfrag + (len / 8);
877                 *newh = *h;
878                 h = newh;
879                 if (h->next_hole)
880                         payload[h->next_hole].prev_hole = (h - payload);
881                 if (h->prev_hole)
882                         payload[h->prev_hole].next_hole = (h - payload);
883                 else
884                         first_hole = (h - payload);
885
886         } else {
887                 /* fragment sits in the middle: split the hole */
888                 newh = thisfrag + (len / 8);
889                 *newh = *h;
890                 h->last_byte = start;
891                 h->next_hole = (newh - payload);
892                 newh->prev_hole = (h - payload);
893                 if (newh->next_hole)
894                         payload[newh->next_hole].prev_hole = (newh - payload);
895         }
896
897         /* finally copy this fragment and possibly return whole packet */
898         memcpy((uchar *)thisfrag, indata + IP_HDR_SIZE, len);
899         if (!done)
900                 return NULL;
901
902         localip->ip_len = htons(total_len);
903         *lenp = total_len + IP_HDR_SIZE;
904         return localip;
905 }
906
907 static inline struct ip_udp_hdr *NetDefragment(struct ip_udp_hdr *ip, int *lenp)
908 {
909         u16 ip_off = ntohs(ip->ip_off);
910         if (!(ip_off & (IP_OFFS | IP_FLAGS_MFRAG)))
911                 return ip; /* not a fragment */
912         return __NetDefragment(ip, lenp);
913 }
914
915 #else /* !CONFIG_IP_DEFRAG */
916
917 static inline struct ip_udp_hdr *NetDefragment(struct ip_udp_hdr *ip, int *lenp)
918 {
919         u16 ip_off = ntohs(ip->ip_off);
920         if (!(ip_off & (IP_OFFS | IP_FLAGS_MFRAG)))
921                 return ip; /* not a fragment */
922         return NULL;
923 }
924 #endif
925
926 /**
927  * Receive an ICMP packet. We deal with REDIRECT and PING here, and silently
928  * drop others.
929  *
930  * @parma ip    IP packet containing the ICMP
931  */
932 static void receive_icmp(struct ip_udp_hdr *ip, int len,
933                         IPaddr_t src_ip, struct ethernet_hdr *et)
934 {
935         struct icmp_hdr *icmph = (struct icmp_hdr *)&ip->udp_src;
936
937         switch (icmph->type) {
938         case ICMP_REDIRECT:
939                 if (icmph->code != ICMP_REDIR_HOST)
940                         return;
941                 printf(" ICMP Host Redirect to %pI4 ",
942                         &icmph->un.gateway);
943                 break;
944         default:
945 #if defined(CONFIG_CMD_PING)
946                 ping_receive(et, ip, len);
947 #endif
948 #ifdef CONFIG_CMD_TFTPPUT
949                 if (packet_icmp_handler)
950                         packet_icmp_handler(icmph->type, icmph->code,
951                                 ntohs(ip->udp_dst), src_ip, ntohs(ip->udp_src),
952                                 icmph->un.data, ntohs(ip->udp_len));
953 #endif
954                 break;
955         }
956 }
957
958 void
959 NetReceive(uchar *inpkt, int len)
960 {
961         struct ethernet_hdr *et;
962         struct ip_udp_hdr *ip;
963         IPaddr_t dst_ip;
964         IPaddr_t src_ip;
965         int eth_proto;
966 #if defined(CONFIG_CMD_CDP)
967         int iscdp;
968 #endif
969         ushort cti = 0, vlanid = VLAN_NONE, myvlanid, mynvlanid;
970
971         debug_cond(DEBUG_NET_PKT, "packet received\n");
972
973         NetRxPacket = inpkt;
974         NetRxPacketLen = len;
975         et = (struct ethernet_hdr *)inpkt;
976
977         /* too small packet? */
978         if (len < ETHER_HDR_SIZE)
979                 return;
980
981 #ifdef CONFIG_API
982         if (push_packet) {
983                 (*push_packet)(inpkt, len);
984                 return;
985         }
986 #endif
987
988 #if defined(CONFIG_CMD_CDP)
989         /* keep track if packet is CDP */
990         iscdp = is_cdp_packet(et->et_dest);
991 #endif
992
993         myvlanid = ntohs(NetOurVLAN);
994         if (myvlanid == (ushort)-1)
995                 myvlanid = VLAN_NONE;
996         mynvlanid = ntohs(NetOurNativeVLAN);
997         if (mynvlanid == (ushort)-1)
998                 mynvlanid = VLAN_NONE;
999
1000         eth_proto = ntohs(et->et_protlen);
1001
1002         if (eth_proto < 1514) {
1003                 struct e802_hdr *et802 = (struct e802_hdr *)et;
1004                 /*
1005                  *      Got a 802.2 packet.  Check the other protocol field.
1006                  *      XXX VLAN over 802.2+SNAP not implemented!
1007                  */
1008                 eth_proto = ntohs(et802->et_prot);
1009
1010                 ip = (struct ip_udp_hdr *)(inpkt + E802_HDR_SIZE);
1011                 len -= E802_HDR_SIZE;
1012
1013         } else if (eth_proto != PROT_VLAN) {    /* normal packet */
1014                 ip = (struct ip_udp_hdr *)(inpkt + ETHER_HDR_SIZE);
1015                 len -= ETHER_HDR_SIZE;
1016
1017         } else {                        /* VLAN packet */
1018                 struct vlan_ethernet_hdr *vet =
1019                         (struct vlan_ethernet_hdr *)et;
1020
1021                 debug_cond(DEBUG_NET_PKT, "VLAN packet received\n");
1022
1023                 /* too small packet? */
1024                 if (len < VLAN_ETHER_HDR_SIZE)
1025                         return;
1026
1027                 /* if no VLAN active */
1028                 if ((ntohs(NetOurVLAN) & VLAN_IDMASK) == VLAN_NONE
1029 #if defined(CONFIG_CMD_CDP)
1030                                 && iscdp == 0
1031 #endif
1032                                 )
1033                         return;
1034
1035                 cti = ntohs(vet->vet_tag);
1036                 vlanid = cti & VLAN_IDMASK;
1037                 eth_proto = ntohs(vet->vet_type);
1038
1039                 ip = (struct ip_udp_hdr *)(inpkt + VLAN_ETHER_HDR_SIZE);
1040                 len -= VLAN_ETHER_HDR_SIZE;
1041         }
1042
1043         debug_cond(DEBUG_NET_PKT, "Receive from protocol 0x%x\n", eth_proto);
1044
1045 #if defined(CONFIG_CMD_CDP)
1046         if (iscdp) {
1047                 cdp_receive((uchar *)ip, len);
1048                 return;
1049         }
1050 #endif
1051
1052         if ((myvlanid & VLAN_IDMASK) != VLAN_NONE) {
1053                 if (vlanid == VLAN_NONE)
1054                         vlanid = (mynvlanid & VLAN_IDMASK);
1055                 /* not matched? */
1056                 if (vlanid != (myvlanid & VLAN_IDMASK))
1057                         return;
1058         }
1059
1060         switch (eth_proto) {
1061
1062         case PROT_ARP:
1063                 ArpReceive(et, ip, len);
1064                 break;
1065
1066 #ifdef CONFIG_CMD_RARP
1067         case PROT_RARP:
1068                 rarp_receive(ip, len);
1069                 break;
1070 #endif
1071         case PROT_IP:
1072                 debug_cond(DEBUG_NET_PKT, "Got IP\n");
1073                 /* Before we start poking the header, make sure it is there */
1074                 if (len < IP_UDP_HDR_SIZE) {
1075                         debug("len bad %d < %lu\n", len,
1076                                 (ulong)IP_UDP_HDR_SIZE);
1077                         return;
1078                 }
1079                 /* Check the packet length */
1080                 if (len < ntohs(ip->ip_len)) {
1081                         debug("len bad %d < %d\n", len, ntohs(ip->ip_len));
1082                         return;
1083                 }
1084                 len = ntohs(ip->ip_len);
1085                 debug_cond(DEBUG_NET_PKT, "len=%d, v=%02x\n",
1086                         len, ip->ip_hl_v & 0xff);
1087
1088                 /* Can't deal with anything except IPv4 */
1089                 if ((ip->ip_hl_v & 0xf0) != 0x40)
1090                         return;
1091                 /* Can't deal with IP options (headers != 20 bytes) */
1092                 if ((ip->ip_hl_v & 0x0f) > 0x05)
1093                         return;
1094                 /* Check the Checksum of the header */
1095                 if (!ip_checksum_ok((uchar *)ip, IP_HDR_SIZE)) {
1096                         debug("checksum bad\n");
1097                         return;
1098                 }
1099                 /* If it is not for us, ignore it */
1100                 dst_ip = NetReadIP(&ip->ip_dst);
1101                 if (NetOurIP && dst_ip != NetOurIP && dst_ip != 0xFFFFFFFF) {
1102 #ifdef CONFIG_MCAST_TFTP
1103                         if (Mcast_addr != dst_ip)
1104 #endif
1105                                 return;
1106                 }
1107                 /* Read source IP address for later use */
1108                 src_ip = NetReadIP(&ip->ip_src);
1109                 /*
1110                  * The function returns the unchanged packet if it's not
1111                  * a fragment, and either the complete packet or NULL if
1112                  * it is a fragment (if !CONFIG_IP_DEFRAG, it returns NULL)
1113                  */
1114                 ip = NetDefragment(ip, &len);
1115                 if (!ip)
1116                         return;
1117                 /*
1118                  * watch for ICMP host redirects
1119                  *
1120                  * There is no real handler code (yet). We just watch
1121                  * for ICMP host redirect messages. In case anybody
1122                  * sees these messages: please contact me
1123                  * (wd@denx.de), or - even better - send me the
1124                  * necessary fixes :-)
1125                  *
1126                  * Note: in all cases where I have seen this so far
1127                  * it was a problem with the router configuration,
1128                  * for instance when a router was configured in the
1129                  * BOOTP reply, but the TFTP server was on the same
1130                  * subnet. So this is probably a warning that your
1131                  * configuration might be wrong. But I'm not really
1132                  * sure if there aren't any other situations.
1133                  *
1134                  * Simon Glass <sjg@chromium.org>: We get an ICMP when
1135                  * we send a tftp packet to a dead connection, or when
1136                  * there is no server at the other end.
1137                  */
1138                 if (ip->ip_p == IPPROTO_ICMP) {
1139                         receive_icmp(ip, len, src_ip, et);
1140                         return;
1141                 } else if (ip->ip_p != IPPROTO_UDP) {   /* Only UDP packets */
1142                         return;
1143                 }
1144
1145                 debug_cond(DEBUG_DEV_PKT,
1146                         "received UDP (to=%pI4, from=%pI4, len=%d)\n",
1147                         &dst_ip, &src_ip, len);
1148
1149 #ifdef CONFIG_UDP_CHECKSUM
1150                 if (ip->udp_xsum != 0) {
1151                         ulong   xsum;
1152                         ushort *sumptr;
1153                         ushort  sumlen;
1154
1155                         xsum  = ip->ip_p;
1156                         xsum += (ntohs(ip->udp_len));
1157                         xsum += (ntohl(ip->ip_src) >> 16) & 0x0000ffff;
1158                         xsum += (ntohl(ip->ip_src) >>  0) & 0x0000ffff;
1159                         xsum += (ntohl(ip->ip_dst) >> 16) & 0x0000ffff;
1160                         xsum += (ntohl(ip->ip_dst) >>  0) & 0x0000ffff;
1161
1162                         sumlen = ntohs(ip->udp_len);
1163                         sumptr = (ushort *) &(ip->udp_src);
1164
1165                         while (sumlen > 1) {
1166                                 ushort sumdata;
1167
1168                                 sumdata = *sumptr++;
1169                                 xsum += ntohs(sumdata);
1170                                 sumlen -= 2;
1171                         }
1172                         if (sumlen > 0) {
1173                                 ushort sumdata;
1174
1175                                 sumdata = *(unsigned char *) sumptr;
1176                                 sumdata = (sumdata << 8) & 0xff00;
1177                                 xsum += sumdata;
1178                         }
1179                         while ((xsum >> 16) != 0) {
1180                                 xsum = (xsum & 0x0000ffff) +
1181                                        ((xsum >> 16) & 0x0000ffff);
1182                         }
1183                         if ((xsum != 0x00000000) && (xsum != 0x0000ffff)) {
1184                                 printf(" UDP wrong checksum %08lx %08x\n",
1185                                         xsum, ntohs(ip->udp_xsum));
1186                                 return;
1187                         }
1188                 }
1189 #endif
1190
1191
1192 #if defined (CONFIG_NETCONSOLE) && !(CONFIG_SPL_BUILD)
1193                 nc_input_packet((uchar *)ip + IP_UDP_HDR_SIZE,
1194                                         src_ip,
1195                                         ntohs(ip->udp_dst),
1196                                         ntohs(ip->udp_src),
1197                                         ntohs(ip->udp_len) - UDP_HDR_SIZE);
1198 #endif
1199                 /*
1200                  *      IP header OK.  Pass the packet to the current handler.
1201                  */
1202                 (*udp_packet_handler)((uchar *)ip + IP_UDP_HDR_SIZE,
1203                                 ntohs(ip->udp_dst),
1204                                 src_ip,
1205                                 ntohs(ip->udp_src),
1206                                 ntohs(ip->udp_len) - UDP_HDR_SIZE);
1207                 break;
1208         }
1209 }
1210
1211
1212 /**********************************************************************/
1213
1214 static int net_check_prereq(enum proto_t protocol)
1215 {
1216         switch (protocol) {
1217 #if defined(CONFIG_CMD_PING)
1218         case PING:
1219                 if (NetPingIP == 0) {
1220                         puts("*** ERROR: ping address not given\n");
1221                         return 1;
1222                 }
1223                 goto common;
1224 #endif
1225 #if defined(CONFIG_CMD_SNTP)
1226         case SNTP:
1227                 if (NetNtpServerIP == 0) {
1228                         puts("*** ERROR: NTP server address not given\n");
1229                         return 1;
1230                 }
1231                 goto common;
1232 #endif
1233 #if defined(CONFIG_CMD_DNS)
1234         case DNS:
1235                 if (NetOurDNSIP == 0) {
1236                         puts("*** ERROR: DNS server address not given\n");
1237                         return 1;
1238                 }
1239                 goto common;
1240 #endif
1241 #if defined(CONFIG_CMD_NFS)
1242         case NFS:
1243 #endif
1244         case TFTPGET:
1245         case TFTPPUT:
1246                 if (NetServerIP == 0) {
1247                         puts("*** ERROR: `serverip' not set\n");
1248                         return 1;
1249                 }
1250 #if     defined(CONFIG_CMD_PING) || defined(CONFIG_CMD_SNTP) || \
1251         defined(CONFIG_CMD_DNS)
1252 common:
1253 #endif
1254                 /* Fall through */
1255
1256         case BOOTME:
1257         case NETCONS:
1258         case TFTPSRV:
1259                 if (NetOurIP == 0) {
1260                         puts("*** ERROR: `ipaddr' not set\n");
1261                         return 1;
1262                 }
1263                 /* Fall through */
1264
1265 #ifdef CONFIG_CMD_RARP
1266         case RARP:
1267 #endif
1268         case BOOTP:
1269         case CDP:
1270         case DHCP:
1271         case LINKLOCAL:
1272                 if (memcmp(NetOurEther, "\0\0\0\0\0\0", 6) == 0) {
1273                         int num = eth_get_dev_index();
1274
1275                         switch (num) {
1276                         case -1:
1277                                 puts("*** ERROR: No ethernet found.\n");
1278                                 return 1;
1279                         case 0:
1280                                 puts("*** ERROR: `ethaddr' not set\n");
1281                                 break;
1282                         default:
1283                                 printf("*** ERROR: `eth%daddr' not set\n",
1284                                         num);
1285                                 break;
1286                         }
1287
1288                         NetStartAgain();
1289                         return 2;
1290                 }
1291                 /* Fall through */
1292         default:
1293                 return 0;
1294         }
1295         return 0;               /* OK */
1296 }
1297 /**********************************************************************/
1298
1299 int
1300 NetEthHdrSize(void)
1301 {
1302         ushort myvlanid;
1303
1304         myvlanid = ntohs(NetOurVLAN);
1305         if (myvlanid == (ushort)-1)
1306                 myvlanid = VLAN_NONE;
1307
1308         return ((myvlanid & VLAN_IDMASK) == VLAN_NONE) ? ETHER_HDR_SIZE :
1309                 VLAN_ETHER_HDR_SIZE;
1310 }
1311
1312 int
1313 NetSetEther(uchar *xet, uchar * addr, uint prot)
1314 {
1315         struct ethernet_hdr *et = (struct ethernet_hdr *)xet;
1316         ushort myvlanid;
1317
1318         myvlanid = ntohs(NetOurVLAN);
1319         if (myvlanid == (ushort)-1)
1320                 myvlanid = VLAN_NONE;
1321
1322         memcpy(et->et_dest, addr, 6);
1323         memcpy(et->et_src, NetOurEther, 6);
1324         if ((myvlanid & VLAN_IDMASK) == VLAN_NONE) {
1325                 et->et_protlen = htons(prot);
1326                 return ETHER_HDR_SIZE;
1327         } else {
1328                 struct vlan_ethernet_hdr *vet =
1329                         (struct vlan_ethernet_hdr *)xet;
1330
1331                 vet->vet_vlan_type = htons(PROT_VLAN);
1332                 vet->vet_tag = htons((0 << 5) | (myvlanid & VLAN_IDMASK));
1333                 vet->vet_type = htons(prot);
1334                 return VLAN_ETHER_HDR_SIZE;
1335         }
1336 }
1337
1338 int net_update_ether(struct ethernet_hdr *et, uchar *addr, uint prot)
1339 {
1340         ushort protlen;
1341
1342         memcpy(et->et_dest, addr, 6);
1343         memcpy(et->et_src, NetOurEther, 6);
1344         protlen = ntohs(et->et_protlen);
1345         if (protlen == PROT_VLAN) {
1346                 struct vlan_ethernet_hdr *vet =
1347                         (struct vlan_ethernet_hdr *)et;
1348                 vet->vet_type = htons(prot);
1349                 return VLAN_ETHER_HDR_SIZE;
1350         } else if (protlen > 1514) {
1351                 et->et_protlen = htons(prot);
1352                 return ETHER_HDR_SIZE;
1353         } else {
1354                 /* 802.2 + SNAP */
1355                 struct e802_hdr *et802 = (struct e802_hdr *)et;
1356                 et802->et_prot = htons(prot);
1357                 return E802_HDR_SIZE;
1358         }
1359 }
1360
1361 void net_set_ip_header(uchar *pkt, IPaddr_t dest, IPaddr_t source)
1362 {
1363         struct ip_udp_hdr *ip = (struct ip_udp_hdr *)pkt;
1364
1365         /*
1366          *      Construct an IP header.
1367          */
1368         /* IP_HDR_SIZE / 4 (not including UDP) */
1369         ip->ip_hl_v  = 0x45;
1370         ip->ip_tos   = 0;
1371         ip->ip_len   = htons(IP_HDR_SIZE);
1372         ip->ip_id    = htons(NetIPID++);
1373         ip->ip_off   = htons(IP_FLAGS_DFRAG);   /* Don't fragment */
1374         ip->ip_ttl   = 255;
1375         ip->ip_sum   = 0;
1376         /* already in network byte order */
1377         NetCopyIP((void *)&ip->ip_src, &source);
1378         /* already in network byte order */
1379         NetCopyIP((void *)&ip->ip_dst, &dest);
1380 }
1381
1382 void net_set_udp_header(uchar *pkt, IPaddr_t dest, int dport, int sport,
1383                         int len)
1384 {
1385         struct ip_udp_hdr *ip = (struct ip_udp_hdr *)pkt;
1386
1387         /*
1388          *      If the data is an odd number of bytes, zero the
1389          *      byte after the last byte so that the checksum
1390          *      will work.
1391          */
1392         if (len & 1)
1393                 pkt[IP_UDP_HDR_SIZE + len] = 0;
1394
1395         net_set_ip_header(pkt, dest, NetOurIP);
1396         ip->ip_len   = htons(IP_UDP_HDR_SIZE + len);
1397         ip->ip_p     = IPPROTO_UDP;
1398         ip->ip_sum   = compute_ip_checksum(ip, IP_HDR_SIZE);
1399
1400         ip->udp_src  = htons(sport);
1401         ip->udp_dst  = htons(dport);
1402         ip->udp_len  = htons(UDP_HDR_SIZE + len);
1403         ip->udp_xsum = 0;
1404 }
1405
1406 void copy_filename(char *dst, const char *src, int size)
1407 {
1408         if (*src && (*src == '"')) {
1409                 ++src;
1410                 --size;
1411         }
1412
1413         while ((--size > 0) && *src && (*src != '"'))
1414                 *dst++ = *src++;
1415         *dst = '\0';
1416 }
1417
1418 #if     defined(CONFIG_CMD_NFS)         || \
1419         defined(CONFIG_CMD_SNTP)        || \
1420         defined(CONFIG_CMD_DNS)
1421 /*
1422  * make port a little random (1024-17407)
1423  * This keeps the math somewhat trivial to compute, and seems to work with
1424  * all supported protocols/clients/servers
1425  */
1426 unsigned int random_port(void)
1427 {
1428         return 1024 + (get_timer(0) % 0x4000);
1429 }
1430 #endif
1431
1432 void ip_to_string(IPaddr_t x, char *s)
1433 {
1434         x = ntohl(x);
1435         sprintf(s, "%d.%d.%d.%d",
1436                 (int) ((x >> 24) & 0xff),
1437                 (int) ((x >> 16) & 0xff),
1438                 (int) ((x >> 8) & 0xff), (int) ((x >> 0) & 0xff)
1439         );
1440 }
1441
1442 void VLAN_to_string(ushort x, char *s)
1443 {
1444         x = ntohs(x);
1445
1446         if (x == (ushort)-1)
1447                 x = VLAN_NONE;
1448
1449         if (x == VLAN_NONE)
1450                 strcpy(s, "none");
1451         else
1452                 sprintf(s, "%d", x & VLAN_IDMASK);
1453 }
1454
1455 ushort string_to_VLAN(const char *s)
1456 {
1457         ushort id;
1458
1459         if (s == NULL)
1460                 return htons(VLAN_NONE);
1461
1462         if (*s < '0' || *s > '9')
1463                 id = VLAN_NONE;
1464         else
1465                 id = (ushort)simple_strtoul(s, NULL, 10);
1466
1467         return htons(id);
1468 }
1469
1470 ushort getenv_VLAN(char *var)
1471 {
1472         return string_to_VLAN(getenv(var));
1473 }