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