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