xref: /rk3399_rockchip-uboot/net/net.c (revision 48522bb5035561556042b74bfa8f1f8dd314e340)
1 /*
2  *	Copied from Linux Monitor (LiMon) - Networking.
3  *
4  *	Copyright 1994 - 2000 Neil Russell.
5  *	(See License)
6  *	Copyright 2000 Roland Borde
7  *	Copyright 2000 Paolo Scaffardi
8  *	Copyright 2000-2002 Wolfgang Denk, wd@denx.de
9  */
10 
11 /*
12  * General Desription:
13  *
14  * The user interface supports commands for BOOTP, RARP, and TFTP.
15  * Also, we support ARP internally. Depending on available data,
16  * these interact as follows:
17  *
18  * BOOTP:
19  *
20  *	Prerequisites:	- own ethernet address
21  *	We want:	- own IP address
22  *			- TFTP server IP address
23  *			- name of bootfile
24  *	Next step:	ARP
25  *
26  * RARP:
27  *
28  *	Prerequisites:	- own ethernet address
29  *	We want:	- own IP address
30  *			- TFTP server IP address
31  *	Next step:	ARP
32  *
33  * ARP:
34  *
35  *	Prerequisites:	- own ethernet address
36  *			- own IP address
37  *			- TFTP server IP address
38  *	We want:	- TFTP server ethernet address
39  *	Next step:	TFTP
40  *
41  * DHCP:
42  *
43  *     Prerequisites:	- own ethernet address
44  *     We want:		- IP, Netmask, ServerIP, Gateway IP
45  *			- bootfilename, lease time
46  *     Next step:	- TFTP
47  *
48  * TFTP:
49  *
50  *	Prerequisites:	- own ethernet address
51  *			- own IP address
52  *			- TFTP server IP address
53  *			- TFTP server ethernet address
54  *			- name of bootfile (if unknown, we use a default name
55  *			  derived from our own IP address)
56  *	We want:	- load the boot file
57  *	Next step:	none
58  *
59  * NFS:
60  *
61  *	Prerequisites:	- own ethernet address
62  *			- own IP address
63  *			- name of bootfile (if unknown, we use a default name
64  *			  derived from our own IP address)
65  *	We want:	- load the boot file
66  *	Next step:	none
67  *
68  * SNTP:
69  *
70  *	Prerequisites:	- own ethernet address
71  *			- own IP address
72  *	We want:	- network time
73  *	Next step:	none
74  */
75 
76 
77 #include <common.h>
78 #include <watchdog.h>
79 #include <command.h>
80 #include <linux/compiler.h>
81 #include <net.h>
82 #include "bootp.h"
83 #include "tftp.h"
84 #ifdef CONFIG_CMD_RARP
85 #include "rarp.h"
86 #endif
87 #include "nfs.h"
88 #ifdef CONFIG_STATUS_LED
89 #include <status_led.h>
90 #include <miiphy.h>
91 #endif
92 #if defined(CONFIG_CMD_SNTP)
93 #include "sntp.h"
94 #endif
95 #if defined(CONFIG_CDP_VERSION)
96 #include <timestamp.h>
97 #endif
98 #if defined(CONFIG_CMD_DNS)
99 #include "dns.h"
100 #endif
101 
102 DECLARE_GLOBAL_DATA_PTR;
103 
104 #ifndef	CONFIG_ARP_TIMEOUT
105 /* Milliseconds before trying ARP again */
106 # define ARP_TIMEOUT		5000UL
107 #else
108 # define ARP_TIMEOUT		CONFIG_ARP_TIMEOUT
109 #endif
110 
111 
112 #ifndef	CONFIG_NET_RETRY_COUNT
113 # define ARP_TIMEOUT_COUNT	5	/* # of timeouts before giving up  */
114 #else
115 # define ARP_TIMEOUT_COUNT	CONFIG_NET_RETRY_COUNT
116 #endif
117 
118 /** BOOTP EXTENTIONS **/
119 
120 /* Our subnet mask (0=unknown) */
121 IPaddr_t	NetOurSubnetMask;
122 /* Our gateways IP address */
123 IPaddr_t	NetOurGatewayIP;
124 /* Our DNS IP address */
125 IPaddr_t	NetOurDNSIP;
126 #if defined(CONFIG_BOOTP_DNS2)
127 /* Our 2nd DNS IP address */
128 IPaddr_t	NetOurDNS2IP;
129 #endif
130 /* Our NIS domain */
131 char		NetOurNISDomain[32] = {0,};
132 /* Our hostname */
133 char		NetOurHostName[32] = {0,};
134 /* Our bootpath */
135 char		NetOurRootPath[64] = {0,};
136 /* Our bootfile size in blocks */
137 ushort		NetBootFileSize;
138 
139 #ifdef CONFIG_MCAST_TFTP	/* Multicast TFTP */
140 IPaddr_t Mcast_addr;
141 #endif
142 
143 /** END OF BOOTP EXTENTIONS **/
144 
145 /* The actual transferred size of the bootfile (in bytes) */
146 ulong		NetBootFileXferSize;
147 /* Our ethernet address */
148 uchar		NetOurEther[6];
149 /* Boot server enet address */
150 uchar		NetServerEther[6];
151 /* Our IP addr (0 = unknown) */
152 IPaddr_t	NetOurIP;
153 /* Server IP addr (0 = unknown) */
154 IPaddr_t	NetServerIP;
155 /* Current receive packet */
156 uchar *NetRxPacket;
157 /* Current rx packet length */
158 int		NetRxPacketLen;
159 /* IP packet ID */
160 unsigned	NetIPID;
161 /* Ethernet bcast address */
162 uchar		NetBcastAddr[6] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
163 uchar		NetEtherNullAddr[6];
164 #ifdef CONFIG_API
165 void		(*push_packet)(void *, int len) = 0;
166 #endif
167 #if defined(CONFIG_CMD_CDP)
168 /* Ethernet bcast address */
169 uchar		NetCDPAddr[6] = { 0x01, 0x00, 0x0c, 0xcc, 0xcc, 0xcc };
170 #endif
171 /* Network loop state */
172 int		NetState;
173 /* Tried all network devices */
174 int		NetRestartWrap;
175 /* Network loop restarted */
176 static int	NetRestarted;
177 /* At least one device configured */
178 static int	NetDevExists;
179 
180 /* XXX in both little & big endian machines 0xFFFF == ntohs(-1) */
181 /* default is without VLAN */
182 ushort		NetOurVLAN = 0xFFFF;
183 /* ditto */
184 ushort		NetOurNativeVLAN = 0xFFFF;
185 
186 /* Boot File name */
187 char		BootFile[128];
188 
189 #if defined(CONFIG_CMD_PING)
190 /* the ip address to ping */
191 IPaddr_t	NetPingIP;
192 
193 static void PingStart(void);
194 #endif
195 
196 #if defined(CONFIG_CMD_CDP)
197 static void CDPStart(void);
198 #endif
199 
200 #if defined(CONFIG_CMD_SNTP)
201 /* NTP server IP address */
202 IPaddr_t	NetNtpServerIP;
203 /* offset time from UTC */
204 int		NetTimeOffset;
205 #endif
206 
207 uchar PktBuf[(PKTBUFSRX+1) * PKTSIZE_ALIGN + PKTALIGN];
208 
209 /* Receive packet */
210 uchar *NetRxPackets[PKTBUFSRX];
211 
212 /* Current RX packet handler */
213 static rxhand_f *packetHandler;
214 #ifdef CONFIG_CMD_TFTPPUT
215 static rxhand_icmp_f *packet_icmp_handler;	/* Current ICMP rx handler */
216 #endif
217 /* Current timeout handler */
218 static thand_f *timeHandler;
219 /* Time base value */
220 static ulong	timeStart;
221 /* Current timeout value */
222 static ulong	timeDelta;
223 /* THE transmit packet */
224 uchar *NetTxPacket;
225 
226 static int net_check_prereq(enum proto_t protocol);
227 
228 static int NetTryCount;
229 
230 /**********************************************************************/
231 
232 IPaddr_t	NetArpWaitPacketIP;
233 IPaddr_t	NetArpWaitReplyIP;
234 /* MAC address of waiting packet's destination */
235 uchar	       *NetArpWaitPacketMAC;
236 /* THE transmit packet */
237 uchar	       *NetArpWaitTxPacket;
238 int		NetArpWaitTxPacketSize;
239 uchar		NetArpWaitPacketBuf[PKTSIZE_ALIGN + PKTALIGN];
240 ulong		NetArpWaitTimerStart;
241 int		NetArpWaitTry;
242 
243 void ArpRequest(void)
244 {
245 	uchar *pkt;
246 	ARP_t *arp;
247 
248 	debug("ARP broadcast %d\n", NetArpWaitTry);
249 
250 	pkt = NetTxPacket;
251 
252 	pkt += NetSetEther(pkt, NetBcastAddr, PROT_ARP);
253 
254 	arp = (ARP_t *) pkt;
255 
256 	arp->ar_hrd = htons(ARP_ETHER);
257 	arp->ar_pro = htons(PROT_IP);
258 	arp->ar_hln = 6;
259 	arp->ar_pln = 4;
260 	arp->ar_op = htons(ARPOP_REQUEST);
261 
262 	/* source ET addr */
263 	memcpy(&arp->ar_data[0], NetOurEther, 6);
264 	/* source IP addr */
265 	NetWriteIP((uchar *) &arp->ar_data[6], NetOurIP);
266 	/* dest ET addr = 0 */
267 	memset(&arp->ar_data[10], '\0', 6);
268 	if ((NetArpWaitPacketIP & NetOurSubnetMask) !=
269 	    (NetOurIP & NetOurSubnetMask)) {
270 		if (NetOurGatewayIP == 0) {
271 			puts("## Warning: gatewayip needed but not set\n");
272 			NetArpWaitReplyIP = NetArpWaitPacketIP;
273 		} else {
274 			NetArpWaitReplyIP = NetOurGatewayIP;
275 		}
276 	} else {
277 		NetArpWaitReplyIP = NetArpWaitPacketIP;
278 	}
279 
280 	NetWriteIP((uchar *) &arp->ar_data[16], NetArpWaitReplyIP);
281 	(void) eth_send(NetTxPacket, (pkt - NetTxPacket) + ARP_HDR_SIZE);
282 }
283 
284 void ArpTimeoutCheck(void)
285 {
286 	ulong t;
287 
288 	if (!NetArpWaitPacketIP)
289 		return;
290 
291 	t = get_timer(0);
292 
293 	/* check for arp timeout */
294 	if ((t - NetArpWaitTimerStart) > ARP_TIMEOUT) {
295 		NetArpWaitTry++;
296 
297 		if (NetArpWaitTry >= ARP_TIMEOUT_COUNT) {
298 			puts("\nARP Retry count exceeded; starting again\n");
299 			NetArpWaitTry = 0;
300 			NetStartAgain();
301 		} else {
302 			NetArpWaitTimerStart = t;
303 			ArpRequest();
304 		}
305 	}
306 }
307 
308 /*
309  * Check if autoload is enabled. If so, use either NFS or TFTP to download
310  * the boot file.
311  */
312 void net_auto_load(void)
313 {
314 	const char *s = getenv("autoload");
315 
316 	if (s != NULL) {
317 		if (*s == 'n') {
318 			/*
319 			 * Just use BOOTP/RARP to configure system;
320 			 * Do not use TFTP to load the bootfile.
321 			 */
322 			NetState = NETLOOP_SUCCESS;
323 			return;
324 		}
325 #if defined(CONFIG_CMD_NFS)
326 		if (strcmp(s, "NFS") == 0) {
327 			/*
328 			 * Use NFS to load the bootfile.
329 			 */
330 			NfsStart();
331 			return;
332 		}
333 #endif
334 	}
335 	TftpStart(TFTPGET);
336 }
337 
338 static void NetInitLoop(enum proto_t protocol)
339 {
340 	static int env_changed_id;
341 	bd_t *bd = gd->bd;
342 	int env_id = get_env_id();
343 
344 	/* update only when the environment has changed */
345 	if (env_changed_id != env_id) {
346 		NetOurIP = getenv_IPaddr("ipaddr");
347 		NetCopyIP(&bd->bi_ip_addr, &NetOurIP);
348 		NetOurGatewayIP = getenv_IPaddr("gatewayip");
349 		NetOurSubnetMask = getenv_IPaddr("netmask");
350 		NetServerIP = getenv_IPaddr("serverip");
351 		NetOurNativeVLAN = getenv_VLAN("nvlan");
352 		NetOurVLAN = getenv_VLAN("vlan");
353 #if defined(CONFIG_CMD_DNS)
354 		NetOurDNSIP = getenv_IPaddr("dnsip");
355 #endif
356 		env_changed_id = env_id;
357 	}
358 
359 	return;
360 }
361 
362 /**********************************************************************/
363 /*
364  *	Main network processing loop.
365  */
366 
367 int NetLoop(enum proto_t protocol)
368 {
369 	bd_t *bd = gd->bd;
370 	int ret = -1;
371 
372 	NetRestarted = 0;
373 	NetDevExists = 0;
374 
375 	/* XXX problem with bss workaround */
376 	NetArpWaitPacketMAC = NULL;
377 	NetArpWaitTxPacket = NULL;
378 	NetArpWaitPacketIP = 0;
379 	NetArpWaitReplyIP = 0;
380 	NetArpWaitTxPacket = NULL;
381 	NetTxPacket = NULL;
382 	NetTryCount = 1;
383 
384 	if (!NetTxPacket) {
385 		int	i;
386 		/*
387 		 *	Setup packet buffers, aligned correctly.
388 		 */
389 		NetTxPacket = &PktBuf[0] + (PKTALIGN - 1);
390 		NetTxPacket -= (ulong)NetTxPacket % PKTALIGN;
391 		for (i = 0; i < PKTBUFSRX; i++)
392 			NetRxPackets[i] = NetTxPacket + (i+1)*PKTSIZE_ALIGN;
393 	}
394 
395 	if (!NetArpWaitTxPacket) {
396 		NetArpWaitTxPacket = &NetArpWaitPacketBuf[0] + (PKTALIGN - 1);
397 		NetArpWaitTxPacket -= (ulong)NetArpWaitTxPacket % PKTALIGN;
398 		NetArpWaitTxPacketSize = 0;
399 	}
400 
401 	bootstage_mark_name(BOOTSTAGE_ID_ETH_START, "eth_start");
402 	eth_halt();
403 	eth_set_current();
404 	if (eth_init(bd) < 0) {
405 		eth_halt();
406 		return -1;
407 	}
408 
409 restart:
410 	memcpy(NetOurEther, eth_get_dev()->enetaddr, 6);
411 
412 	NetState = NETLOOP_CONTINUE;
413 
414 	/*
415 	 *	Start the ball rolling with the given start function.  From
416 	 *	here on, this code is a state machine driven by received
417 	 *	packets and timer events.
418 	 */
419 	NetInitLoop(protocol);
420 
421 	switch (net_check_prereq(protocol)) {
422 	case 1:
423 		/* network not configured */
424 		eth_halt();
425 		return -1;
426 
427 	case 2:
428 		/* network device not configured */
429 		break;
430 
431 	case 0:
432 		NetDevExists = 1;
433 		NetBootFileXferSize = 0;
434 		switch (protocol) {
435 		case TFTPGET:
436 #ifdef CONFIG_CMD_TFTPPUT
437 		case TFTPPUT:
438 #endif
439 			/* always use ARP to get server ethernet address */
440 			TftpStart(protocol);
441 			break;
442 #ifdef CONFIG_CMD_TFTPSRV
443 		case TFTPSRV:
444 			TftpStartServer();
445 			break;
446 #endif
447 #if defined(CONFIG_CMD_DHCP)
448 		case DHCP:
449 			BootpTry = 0;
450 			NetOurIP = 0;
451 			DhcpRequest();		/* Basically same as BOOTP */
452 			break;
453 #endif
454 
455 		case BOOTP:
456 			BootpTry = 0;
457 			NetOurIP = 0;
458 			BootpRequest();
459 			break;
460 
461 #if defined(CONFIG_CMD_RARP)
462 		case RARP:
463 			RarpTry = 0;
464 			NetOurIP = 0;
465 			RarpRequest();
466 			break;
467 #endif
468 #if defined(CONFIG_CMD_PING)
469 		case PING:
470 			PingStart();
471 			break;
472 #endif
473 #if defined(CONFIG_CMD_NFS)
474 		case NFS:
475 			NfsStart();
476 			break;
477 #endif
478 #if defined(CONFIG_CMD_CDP)
479 		case CDP:
480 			CDPStart();
481 			break;
482 #endif
483 #ifdef CONFIG_NETCONSOLE
484 		case NETCONS:
485 			NcStart();
486 			break;
487 #endif
488 #if defined(CONFIG_CMD_SNTP)
489 		case SNTP:
490 			SntpStart();
491 			break;
492 #endif
493 #if defined(CONFIG_CMD_DNS)
494 		case DNS:
495 			DnsStart();
496 			break;
497 #endif
498 		default:
499 			break;
500 		}
501 
502 		break;
503 	}
504 
505 #if defined(CONFIG_MII) || defined(CONFIG_CMD_MII)
506 #if	defined(CONFIG_SYS_FAULT_ECHO_LINK_DOWN)	&& \
507 	defined(CONFIG_STATUS_LED)			&& \
508 	defined(STATUS_LED_RED)
509 	/*
510 	 * Echo the inverted link state to the fault LED.
511 	 */
512 	if (miiphy_link(eth_get_dev()->name, CONFIG_SYS_FAULT_MII_ADDR))
513 		status_led_set(STATUS_LED_RED, STATUS_LED_OFF);
514 	else
515 		status_led_set(STATUS_LED_RED, STATUS_LED_ON);
516 #endif /* CONFIG_SYS_FAULT_ECHO_LINK_DOWN, ... */
517 #endif /* CONFIG_MII, ... */
518 
519 	/*
520 	 *	Main packet reception loop.  Loop receiving packets until
521 	 *	someone sets `NetState' to a state that terminates.
522 	 */
523 	for (;;) {
524 		WATCHDOG_RESET();
525 #ifdef CONFIG_SHOW_ACTIVITY
526 		show_activity(1);
527 #endif
528 		/*
529 		 *	Check the ethernet for a new packet.  The ethernet
530 		 *	receive routine will process it.
531 		 */
532 		eth_rx();
533 
534 		/*
535 		 *	Abort if ctrl-c was pressed.
536 		 */
537 		if (ctrlc()) {
538 			eth_halt();
539 			puts("\nAbort\n");
540 			goto done;
541 		}
542 
543 		ArpTimeoutCheck();
544 
545 		/*
546 		 *	Check for a timeout, and run the timeout handler
547 		 *	if we have one.
548 		 */
549 		if (timeHandler && ((get_timer(0) - timeStart) > timeDelta)) {
550 			thand_f *x;
551 
552 #if defined(CONFIG_MII) || defined(CONFIG_CMD_MII)
553 #if	defined(CONFIG_SYS_FAULT_ECHO_LINK_DOWN)	&& \
554 	defined(CONFIG_STATUS_LED)			&& \
555 	defined(STATUS_LED_RED)
556 			/*
557 			 * Echo the inverted link state to the fault LED.
558 			 */
559 			if (miiphy_link(eth_get_dev()->name,
560 				       CONFIG_SYS_FAULT_MII_ADDR)) {
561 				status_led_set(STATUS_LED_RED, STATUS_LED_OFF);
562 			} else {
563 				status_led_set(STATUS_LED_RED, STATUS_LED_ON);
564 			}
565 #endif /* CONFIG_SYS_FAULT_ECHO_LINK_DOWN, ... */
566 #endif /* CONFIG_MII, ... */
567 			x = timeHandler;
568 			timeHandler = (thand_f *)0;
569 			(*x)();
570 		}
571 
572 
573 		switch (NetState) {
574 
575 		case NETLOOP_RESTART:
576 			NetRestarted = 1;
577 			goto restart;
578 
579 		case NETLOOP_SUCCESS:
580 			if (NetBootFileXferSize > 0) {
581 				char buf[20];
582 				printf("Bytes transferred = %ld (%lx hex)\n",
583 					NetBootFileXferSize,
584 					NetBootFileXferSize);
585 				sprintf(buf, "%lX", NetBootFileXferSize);
586 				setenv("filesize", buf);
587 
588 				sprintf(buf, "%lX", (unsigned long)load_addr);
589 				setenv("fileaddr", buf);
590 			}
591 			eth_halt();
592 			ret = NetBootFileXferSize;
593 			goto done;
594 
595 		case NETLOOP_FAIL:
596 			goto done;
597 		}
598 	}
599 
600 done:
601 #ifdef CONFIG_CMD_TFTPPUT
602 	/* Clear out the handlers */
603 	NetSetHandler(NULL);
604 	net_set_icmp_handler(NULL);
605 #endif
606 	return ret;
607 }
608 
609 /**********************************************************************/
610 
611 static void
612 startAgainTimeout(void)
613 {
614 	NetState = NETLOOP_RESTART;
615 }
616 
617 static void
618 startAgainHandler(uchar *pkt, unsigned dest, IPaddr_t sip,
619 		  unsigned src, unsigned len)
620 {
621 	/* Totally ignore the packet */
622 }
623 
624 void NetStartAgain(void)
625 {
626 	char *nretry;
627 	int retry_forever = 0;
628 	unsigned long retrycnt = 0;
629 
630 	nretry = getenv("netretry");
631 	if (nretry) {
632 		if (!strcmp(nretry, "yes"))
633 			retry_forever = 1;
634 		else if (!strcmp(nretry, "no"))
635 			retrycnt = 0;
636 		else if (!strcmp(nretry, "once"))
637 			retrycnt = 1;
638 		else
639 			retrycnt = simple_strtoul(nretry, NULL, 0);
640 	} else
641 		retry_forever = 1;
642 
643 	if ((!retry_forever) && (NetTryCount >= retrycnt)) {
644 		eth_halt();
645 		NetState = NETLOOP_FAIL;
646 		return;
647 	}
648 
649 	NetTryCount++;
650 
651 	eth_halt();
652 #if !defined(CONFIG_NET_DO_NOT_TRY_ANOTHER)
653 	eth_try_another(!NetRestarted);
654 #endif
655 	eth_init(gd->bd);
656 	if (NetRestartWrap) {
657 		NetRestartWrap = 0;
658 		if (NetDevExists) {
659 			NetSetTimeout(10000UL, startAgainTimeout);
660 			NetSetHandler(startAgainHandler);
661 		} else {
662 			NetState = NETLOOP_FAIL;
663 		}
664 	} else {
665 		NetState = NETLOOP_RESTART;
666 	}
667 }
668 
669 /**********************************************************************/
670 /*
671  *	Miscelaneous bits.
672  */
673 
674 void
675 NetSetHandler(rxhand_f *f)
676 {
677 	packetHandler = f;
678 }
679 
680 #ifdef CONFIG_CMD_TFTPPUT
681 void net_set_icmp_handler(rxhand_icmp_f *f)
682 {
683 	packet_icmp_handler = f;
684 }
685 #endif
686 
687 void
688 NetSetTimeout(ulong iv, thand_f *f)
689 {
690 	if (iv == 0) {
691 		timeHandler = (thand_f *)0;
692 	} else {
693 		timeHandler = f;
694 		timeStart = get_timer(0);
695 		timeDelta = iv;
696 	}
697 }
698 
699 
700 void
701 NetSendPacket(uchar *pkt, int len)
702 {
703 	(void) eth_send(pkt, len);
704 }
705 
706 int
707 NetSendUDPPacket(uchar *ether, IPaddr_t dest, int dport, int sport, int len)
708 {
709 	uchar *pkt;
710 
711 	/* convert to new style broadcast */
712 	if (dest == 0)
713 		dest = 0xFFFFFFFF;
714 
715 	/* if broadcast, make the ether address a broadcast and don't do ARP */
716 	if (dest == 0xFFFFFFFF)
717 		ether = NetBcastAddr;
718 
719 	/*
720 	 * if MAC address was not discovered yet, save the packet and do
721 	 * an ARP request
722 	 */
723 	if (memcmp(ether, NetEtherNullAddr, 6) == 0) {
724 
725 		debug("sending ARP for %08x\n", dest);
726 
727 		NetArpWaitPacketIP = dest;
728 		NetArpWaitPacketMAC = ether;
729 
730 		pkt = NetArpWaitTxPacket;
731 		pkt += NetSetEther(pkt, NetArpWaitPacketMAC, PROT_IP);
732 
733 		NetSetIP(pkt, dest, dport, sport, len);
734 		memcpy(pkt + IP_HDR_SIZE, (uchar *)NetTxPacket +
735 		       (pkt - (uchar *)NetArpWaitTxPacket) + IP_HDR_SIZE, len);
736 
737 		/* size of the waiting packet */
738 		NetArpWaitTxPacketSize = (pkt - NetArpWaitTxPacket) +
739 			IP_HDR_SIZE + len;
740 
741 		/* and do the ARP request */
742 		NetArpWaitTry = 1;
743 		NetArpWaitTimerStart = get_timer(0);
744 		ArpRequest();
745 		return 1;	/* waiting */
746 	}
747 
748 	debug("sending UDP to %08x/%pM\n", dest, ether);
749 
750 	pkt = (uchar *)NetTxPacket;
751 	pkt += NetSetEther(pkt, ether, PROT_IP);
752 	NetSetIP(pkt, dest, dport, sport, len);
753 	(void) eth_send(NetTxPacket, (pkt - NetTxPacket) + IP_HDR_SIZE + len);
754 
755 	return 0;	/* transmitted */
756 }
757 
758 #if defined(CONFIG_CMD_PING)
759 static ushort PingSeqNo;
760 
761 int PingSend(void)
762 {
763 	static uchar mac[6];
764 	IP_t *ip;
765 	ushort *s;
766 	uchar *pkt;
767 
768 	/* XXX always send arp request */
769 
770 	memcpy(mac, NetEtherNullAddr, 6);
771 
772 	debug("sending ARP for %08x\n", NetPingIP);
773 
774 	NetArpWaitPacketIP = NetPingIP;
775 	NetArpWaitPacketMAC = mac;
776 
777 	pkt = NetArpWaitTxPacket;
778 	pkt += NetSetEther(pkt, mac, PROT_IP);
779 
780 	ip = (IP_t *)pkt;
781 
782 	/*
783 	 * Construct an IP and ICMP header.
784 	 * (need to set no fragment bit - XXX)
785 	 */
786 	/* IP_HDR_SIZE / 4 (not including UDP) */
787 	ip->ip_hl_v  = 0x45;
788 	ip->ip_tos   = 0;
789 	ip->ip_len   = htons(IP_HDR_SIZE_NO_UDP + 8);
790 	ip->ip_id    = htons(NetIPID++);
791 	ip->ip_off   = htons(IP_FLAGS_DFRAG);	/* Don't fragment */
792 	ip->ip_ttl   = 255;
793 	ip->ip_p     = 0x01;		/* ICMP */
794 	ip->ip_sum   = 0;
795 	/* already in network byte order */
796 	NetCopyIP((void *)&ip->ip_src, &NetOurIP);
797 	/* - "" - */
798 	NetCopyIP((void *)&ip->ip_dst, &NetPingIP);
799 	ip->ip_sum   = ~NetCksum((uchar *)ip, IP_HDR_SIZE_NO_UDP / 2);
800 
801 	s = &ip->udp_src;		/* XXX ICMP starts here */
802 	s[0] = htons(0x0800);		/* echo-request, code */
803 	s[1] = 0;			/* checksum */
804 	s[2] = 0;			/* identifier */
805 	s[3] = htons(PingSeqNo++);	/* sequence number */
806 	s[1] = ~NetCksum((uchar *)s, 8/2);
807 
808 	/* size of the waiting packet */
809 	NetArpWaitTxPacketSize =
810 		(pkt - NetArpWaitTxPacket) + IP_HDR_SIZE_NO_UDP + 8;
811 
812 	/* and do the ARP request */
813 	NetArpWaitTry = 1;
814 	NetArpWaitTimerStart = get_timer(0);
815 	ArpRequest();
816 	return 1;	/* waiting */
817 }
818 
819 static void
820 PingTimeout(void)
821 {
822 	eth_halt();
823 	NetState = NETLOOP_FAIL;	/* we did not get the reply */
824 }
825 
826 static void
827 PingHandler(uchar *pkt, unsigned dest, IPaddr_t sip, unsigned src,
828 	    unsigned len)
829 {
830 	if (sip != NetPingIP)
831 		return;
832 
833 	NetState = NETLOOP_SUCCESS;
834 }
835 
836 static void PingStart(void)
837 {
838 	printf("Using %s device\n", eth_get_name());
839 	NetSetTimeout(10000UL, PingTimeout);
840 	NetSetHandler(PingHandler);
841 
842 	PingSend();
843 }
844 #endif
845 
846 #if defined(CONFIG_CMD_CDP)
847 
848 #define CDP_DEVICE_ID_TLV		0x0001
849 #define CDP_ADDRESS_TLV			0x0002
850 #define CDP_PORT_ID_TLV			0x0003
851 #define CDP_CAPABILITIES_TLV		0x0004
852 #define CDP_VERSION_TLV			0x0005
853 #define CDP_PLATFORM_TLV		0x0006
854 #define CDP_NATIVE_VLAN_TLV		0x000a
855 #define CDP_APPLIANCE_VLAN_TLV		0x000e
856 #define CDP_TRIGGER_TLV			0x000f
857 #define CDP_POWER_CONSUMPTION_TLV	0x0010
858 #define CDP_SYSNAME_TLV			0x0014
859 #define CDP_SYSOBJECT_TLV		0x0015
860 #define CDP_MANAGEMENT_ADDRESS_TLV	0x0016
861 
862 #define CDP_TIMEOUT			250UL	/* one packet every 250ms */
863 
864 static int CDPSeq;
865 static int CDPOK;
866 
867 ushort CDPNativeVLAN;
868 ushort CDPApplianceVLAN;
869 
870 static const uchar CDP_SNAP_hdr[8] = { 0xAA, 0xAA, 0x03, 0x00, 0x00, 0x0C, 0x20,
871 				       0x00 };
872 
873 static ushort CDP_compute_csum(const uchar *buff, ushort len)
874 {
875 	ushort csum;
876 	int     odd;
877 	ulong   result = 0;
878 	ushort  leftover;
879 	ushort *p;
880 
881 	if (len > 0) {
882 		odd = 1 & (ulong)buff;
883 		if (odd) {
884 			result = *buff << 8;
885 			len--;
886 			buff++;
887 		}
888 		while (len > 1) {
889 			p = (ushort *)buff;
890 			result += *p++;
891 			buff = (uchar *)p;
892 			if (result & 0x80000000)
893 				result = (result & 0xFFFF) + (result >> 16);
894 			len -= 2;
895 		}
896 		if (len) {
897 			leftover = (signed short)(*(const signed char *)buff);
898 			/* CISCO SUCKS big time! (and blows too):
899 			 * CDP uses the IP checksum algorithm with a twist;
900 			 * for the last byte it *sign* extends and sums.
901 			 */
902 			result = (result & 0xffff0000) |
903 				 ((result + leftover) & 0x0000ffff);
904 		}
905 		while (result >> 16)
906 			result = (result & 0xFFFF) + (result >> 16);
907 
908 		if (odd)
909 			result = ((result >> 8) & 0xff) |
910 				 ((result & 0xff) << 8);
911 	}
912 
913 	/* add up 16-bit and 17-bit words for 17+c bits */
914 	result = (result & 0xffff) + (result >> 16);
915 	/* add up 16-bit and 2-bit for 16+c bit */
916 	result = (result & 0xffff) + (result >> 16);
917 	/* add up carry.. */
918 	result = (result & 0xffff) + (result >> 16);
919 
920 	/* negate */
921 	csum = ~(ushort)result;
922 
923 	/* run time endian detection */
924 	if (csum != htons(csum))	/* little endian */
925 		csum = htons(csum);
926 
927 	return csum;
928 }
929 
930 int CDPSendTrigger(void)
931 {
932 	uchar *pkt;
933 	ushort *s;
934 	ushort *cp;
935 	Ethernet_t *et;
936 	int len;
937 	ushort chksum;
938 #if	defined(CONFIG_CDP_DEVICE_ID) || defined(CONFIG_CDP_PORT_ID)   || \
939 	defined(CONFIG_CDP_VERSION)   || defined(CONFIG_CDP_PLATFORM)
940 	char buf[32];
941 #endif
942 
943 	pkt = NetTxPacket;
944 	et = (Ethernet_t *)pkt;
945 
946 	/* NOTE: trigger sent not on any VLAN */
947 
948 	/* form ethernet header */
949 	memcpy(et->et_dest, NetCDPAddr, 6);
950 	memcpy(et->et_src, NetOurEther, 6);
951 
952 	pkt += ETHER_HDR_SIZE;
953 
954 	/* SNAP header */
955 	memcpy((uchar *)pkt, CDP_SNAP_hdr, sizeof(CDP_SNAP_hdr));
956 	pkt += sizeof(CDP_SNAP_hdr);
957 
958 	/* CDP header */
959 	*pkt++ = 0x02;				/* CDP version 2 */
960 	*pkt++ = 180;				/* TTL */
961 	s = (ushort *)pkt;
962 	cp = s;
963 	/* checksum (0 for later calculation) */
964 	*s++ = htons(0);
965 
966 	/* CDP fields */
967 #ifdef CONFIG_CDP_DEVICE_ID
968 	*s++ = htons(CDP_DEVICE_ID_TLV);
969 	*s++ = htons(CONFIG_CDP_DEVICE_ID);
970 	sprintf(buf, CONFIG_CDP_DEVICE_ID_PREFIX "%pm", NetOurEther);
971 	memcpy((uchar *)s, buf, 16);
972 	s += 16 / 2;
973 #endif
974 
975 #ifdef CONFIG_CDP_PORT_ID
976 	*s++ = htons(CDP_PORT_ID_TLV);
977 	memset(buf, 0, sizeof(buf));
978 	sprintf(buf, CONFIG_CDP_PORT_ID, eth_get_dev_index());
979 	len = strlen(buf);
980 	if (len & 1)	/* make it even */
981 		len++;
982 	*s++ = htons(len + 4);
983 	memcpy((uchar *)s, buf, len);
984 	s += len / 2;
985 #endif
986 
987 #ifdef CONFIG_CDP_CAPABILITIES
988 	*s++ = htons(CDP_CAPABILITIES_TLV);
989 	*s++ = htons(8);
990 	*(ulong *)s = htonl(CONFIG_CDP_CAPABILITIES);
991 	s += 2;
992 #endif
993 
994 #ifdef CONFIG_CDP_VERSION
995 	*s++ = htons(CDP_VERSION_TLV);
996 	memset(buf, 0, sizeof(buf));
997 	strcpy(buf, CONFIG_CDP_VERSION);
998 	len = strlen(buf);
999 	if (len & 1)	/* make it even */
1000 		len++;
1001 	*s++ = htons(len + 4);
1002 	memcpy((uchar *)s, buf, len);
1003 	s += len / 2;
1004 #endif
1005 
1006 #ifdef CONFIG_CDP_PLATFORM
1007 	*s++ = htons(CDP_PLATFORM_TLV);
1008 	memset(buf, 0, sizeof(buf));
1009 	strcpy(buf, CONFIG_CDP_PLATFORM);
1010 	len = strlen(buf);
1011 	if (len & 1)	/* make it even */
1012 		len++;
1013 	*s++ = htons(len + 4);
1014 	memcpy((uchar *)s, buf, len);
1015 	s += len / 2;
1016 #endif
1017 
1018 #ifdef CONFIG_CDP_TRIGGER
1019 	*s++ = htons(CDP_TRIGGER_TLV);
1020 	*s++ = htons(8);
1021 	*(ulong *)s = htonl(CONFIG_CDP_TRIGGER);
1022 	s += 2;
1023 #endif
1024 
1025 #ifdef CONFIG_CDP_POWER_CONSUMPTION
1026 	*s++ = htons(CDP_POWER_CONSUMPTION_TLV);
1027 	*s++ = htons(6);
1028 	*s++ = htons(CONFIG_CDP_POWER_CONSUMPTION);
1029 #endif
1030 
1031 	/* length of ethernet packet */
1032 	len = (uchar *)s - ((uchar *)NetTxPacket + ETHER_HDR_SIZE);
1033 	et->et_protlen = htons(len);
1034 
1035 	len = ETHER_HDR_SIZE + sizeof(CDP_SNAP_hdr);
1036 	chksum = CDP_compute_csum((uchar *)NetTxPacket + len,
1037 				  (uchar *)s - (NetTxPacket + len));
1038 	if (chksum == 0)
1039 		chksum = 0xFFFF;
1040 	*cp = htons(chksum);
1041 
1042 	(void) eth_send(NetTxPacket, (uchar *)s - NetTxPacket);
1043 	return 0;
1044 }
1045 
1046 static void
1047 CDPTimeout(void)
1048 {
1049 	CDPSeq++;
1050 
1051 	if (CDPSeq < 3) {
1052 		NetSetTimeout(CDP_TIMEOUT, CDPTimeout);
1053 		CDPSendTrigger();
1054 		return;
1055 	}
1056 
1057 	/* if not OK try again */
1058 	if (!CDPOK)
1059 		NetStartAgain();
1060 	else
1061 		NetState = NETLOOP_SUCCESS;
1062 }
1063 
1064 static void
1065 CDPDummyHandler(uchar *pkt, unsigned dest, IPaddr_t sip, unsigned src,
1066 		unsigned len)
1067 {
1068 	/* nothing */
1069 }
1070 
1071 static void
1072 CDPHandler(const uchar *pkt, unsigned len)
1073 {
1074 	const uchar *t;
1075 	const ushort *ss;
1076 	ushort type, tlen;
1077 	ushort vlan, nvlan;
1078 
1079 	/* minimum size? */
1080 	if (len < sizeof(CDP_SNAP_hdr) + 4)
1081 		goto pkt_short;
1082 
1083 	/* check for valid CDP SNAP header */
1084 	if (memcmp(pkt, CDP_SNAP_hdr, sizeof(CDP_SNAP_hdr)) != 0)
1085 		return;
1086 
1087 	pkt += sizeof(CDP_SNAP_hdr);
1088 	len -= sizeof(CDP_SNAP_hdr);
1089 
1090 	/* Version of CDP protocol must be >= 2 and TTL != 0 */
1091 	if (pkt[0] < 0x02 || pkt[1] == 0)
1092 		return;
1093 
1094 	/*
1095 	 * if version is greater than 0x02 maybe we'll have a problem;
1096 	 * output a warning
1097 	 */
1098 	if (pkt[0] != 0x02)
1099 		printf("**WARNING: CDP packet received with a protocol version "
1100 				"%d > 2\n", pkt[0] & 0xff);
1101 
1102 	if (CDP_compute_csum(pkt, len) != 0)
1103 		return;
1104 
1105 	pkt += 4;
1106 	len -= 4;
1107 
1108 	vlan = htons(-1);
1109 	nvlan = htons(-1);
1110 	while (len > 0) {
1111 		if (len < 4)
1112 			goto pkt_short;
1113 
1114 		ss = (const ushort *)pkt;
1115 		type = ntohs(ss[0]);
1116 		tlen = ntohs(ss[1]);
1117 		if (tlen > len)
1118 			goto pkt_short;
1119 
1120 		pkt += tlen;
1121 		len -= tlen;
1122 
1123 		ss += 2;	/* point ss to the data of the TLV */
1124 		tlen -= 4;
1125 
1126 		switch (type) {
1127 		case CDP_DEVICE_ID_TLV:
1128 			break;
1129 		case CDP_ADDRESS_TLV:
1130 			break;
1131 		case CDP_PORT_ID_TLV:
1132 			break;
1133 		case CDP_CAPABILITIES_TLV:
1134 			break;
1135 		case CDP_VERSION_TLV:
1136 			break;
1137 		case CDP_PLATFORM_TLV:
1138 			break;
1139 		case CDP_NATIVE_VLAN_TLV:
1140 			nvlan = *ss;
1141 			break;
1142 		case CDP_APPLIANCE_VLAN_TLV:
1143 			t = (const uchar *)ss;
1144 			while (tlen > 0) {
1145 				if (tlen < 3)
1146 					goto pkt_short;
1147 
1148 				ss = (const ushort *)(t + 1);
1149 
1150 #ifdef CONFIG_CDP_APPLIANCE_VLAN_TYPE
1151 				if (t[0] == CONFIG_CDP_APPLIANCE_VLAN_TYPE)
1152 					vlan = *ss;
1153 #else
1154 				/* XXX will this work; dunno */
1155 				vlan = ntohs(*ss);
1156 #endif
1157 				t += 3; tlen -= 3;
1158 			}
1159 			break;
1160 		case CDP_TRIGGER_TLV:
1161 			break;
1162 		case CDP_POWER_CONSUMPTION_TLV:
1163 			break;
1164 		case CDP_SYSNAME_TLV:
1165 			break;
1166 		case CDP_SYSOBJECT_TLV:
1167 			break;
1168 		case CDP_MANAGEMENT_ADDRESS_TLV:
1169 			break;
1170 		}
1171 	}
1172 
1173 	CDPApplianceVLAN = vlan;
1174 	CDPNativeVLAN = nvlan;
1175 
1176 	CDPOK = 1;
1177 	return;
1178 
1179  pkt_short:
1180 	printf("** CDP packet is too short\n");
1181 	return;
1182 }
1183 
1184 static void CDPStart(void)
1185 {
1186 	printf("Using %s device\n", eth_get_name());
1187 	CDPSeq = 0;
1188 	CDPOK = 0;
1189 
1190 	CDPNativeVLAN = htons(-1);
1191 	CDPApplianceVLAN = htons(-1);
1192 
1193 	NetSetTimeout(CDP_TIMEOUT, CDPTimeout);
1194 	NetSetHandler(CDPDummyHandler);
1195 
1196 	CDPSendTrigger();
1197 }
1198 #endif
1199 
1200 #ifdef CONFIG_IP_DEFRAG
1201 /*
1202  * This function collects fragments in a single packet, according
1203  * to the algorithm in RFC815. It returns NULL or the pointer to
1204  * a complete packet, in static storage
1205  */
1206 #ifndef CONFIG_NET_MAXDEFRAG
1207 #define CONFIG_NET_MAXDEFRAG 16384
1208 #endif
1209 /*
1210  * MAXDEFRAG, above, is chosen in the config file and  is real data
1211  * so we need to add the NFS overhead, which is more than TFTP.
1212  * To use sizeof in the internal unnamed structures, we need a real
1213  * instance (can't do "sizeof(struct rpc_t.u.reply))", unfortunately).
1214  * The compiler doesn't complain nor allocates the actual structure
1215  */
1216 static struct rpc_t rpc_specimen;
1217 #define IP_PKTSIZE (CONFIG_NET_MAXDEFRAG + sizeof(rpc_specimen.u.reply))
1218 
1219 #define IP_MAXUDP (IP_PKTSIZE - IP_HDR_SIZE_NO_UDP)
1220 
1221 /*
1222  * this is the packet being assembled, either data or frag control.
1223  * Fragments go by 8 bytes, so this union must be 8 bytes long
1224  */
1225 struct hole {
1226 	/* first_byte is address of this structure */
1227 	u16 last_byte;	/* last byte in this hole + 1 (begin of next hole) */
1228 	u16 next_hole;	/* index of next (in 8-b blocks), 0 == none */
1229 	u16 prev_hole;	/* index of prev, 0 == none */
1230 	u16 unused;
1231 };
1232 
1233 static IP_t *__NetDefragment(IP_t *ip, int *lenp)
1234 {
1235 	static uchar pkt_buff[IP_PKTSIZE] __aligned(PKTALIGN);
1236 	static u16 first_hole, total_len;
1237 	struct hole *payload, *thisfrag, *h, *newh;
1238 	IP_t *localip = (IP_t *)pkt_buff;
1239 	uchar *indata = (uchar *)ip;
1240 	int offset8, start, len, done = 0;
1241 	u16 ip_off = ntohs(ip->ip_off);
1242 
1243 	/* payload starts after IP header, this fragment is in there */
1244 	payload = (struct hole *)(pkt_buff + IP_HDR_SIZE_NO_UDP);
1245 	offset8 =  (ip_off & IP_OFFS);
1246 	thisfrag = payload + offset8;
1247 	start = offset8 * 8;
1248 	len = ntohs(ip->ip_len) - IP_HDR_SIZE_NO_UDP;
1249 
1250 	if (start + len > IP_MAXUDP) /* fragment extends too far */
1251 		return NULL;
1252 
1253 	if (!total_len || localip->ip_id != ip->ip_id) {
1254 		/* new (or different) packet, reset structs */
1255 		total_len = 0xffff;
1256 		payload[0].last_byte = ~0;
1257 		payload[0].next_hole = 0;
1258 		payload[0].prev_hole = 0;
1259 		first_hole = 0;
1260 		/* any IP header will work, copy the first we received */
1261 		memcpy(localip, ip, IP_HDR_SIZE_NO_UDP);
1262 	}
1263 
1264 	/*
1265 	 * What follows is the reassembly algorithm. We use the payload
1266 	 * array as a linked list of hole descriptors, as each hole starts
1267 	 * at a multiple of 8 bytes. However, last byte can be whatever value,
1268 	 * so it is represented as byte count, not as 8-byte blocks.
1269 	 */
1270 
1271 	h = payload + first_hole;
1272 	while (h->last_byte < start) {
1273 		if (!h->next_hole) {
1274 			/* no hole that far away */
1275 			return NULL;
1276 		}
1277 		h = payload + h->next_hole;
1278 	}
1279 
1280 	/* last fragment may be 1..7 bytes, the "+7" forces acceptance */
1281 	if (offset8 + ((len + 7) / 8) <= h - payload) {
1282 		/* no overlap with holes (dup fragment?) */
1283 		return NULL;
1284 	}
1285 
1286 	if (!(ip_off & IP_FLAGS_MFRAG)) {
1287 		/* no more fragmentss: truncate this (last) hole */
1288 		total_len = start + len;
1289 		h->last_byte = start + len;
1290 	}
1291 
1292 	/*
1293 	 * There is some overlap: fix the hole list. This code doesn't
1294 	 * deal with a fragment that overlaps with two different holes
1295 	 * (thus being a superset of a previously-received fragment).
1296 	 */
1297 
1298 	if ((h >= thisfrag) && (h->last_byte <= start + len)) {
1299 		/* complete overlap with hole: remove hole */
1300 		if (!h->prev_hole && !h->next_hole) {
1301 			/* last remaining hole */
1302 			done = 1;
1303 		} else if (!h->prev_hole) {
1304 			/* first hole */
1305 			first_hole = h->next_hole;
1306 			payload[h->next_hole].prev_hole = 0;
1307 		} else if (!h->next_hole) {
1308 			/* last hole */
1309 			payload[h->prev_hole].next_hole = 0;
1310 		} else {
1311 			/* in the middle of the list */
1312 			payload[h->next_hole].prev_hole = h->prev_hole;
1313 			payload[h->prev_hole].next_hole = h->next_hole;
1314 		}
1315 
1316 	} else if (h->last_byte <= start + len) {
1317 		/* overlaps with final part of the hole: shorten this hole */
1318 		h->last_byte = start;
1319 
1320 	} else if (h >= thisfrag) {
1321 		/* overlaps with initial part of the hole: move this hole */
1322 		newh = thisfrag + (len / 8);
1323 		*newh = *h;
1324 		h = newh;
1325 		if (h->next_hole)
1326 			payload[h->next_hole].prev_hole = (h - payload);
1327 		if (h->prev_hole)
1328 			payload[h->prev_hole].next_hole = (h - payload);
1329 		else
1330 			first_hole = (h - payload);
1331 
1332 	} else {
1333 		/* fragment sits in the middle: split the hole */
1334 		newh = thisfrag + (len / 8);
1335 		*newh = *h;
1336 		h->last_byte = start;
1337 		h->next_hole = (newh - payload);
1338 		newh->prev_hole = (h - payload);
1339 		if (newh->next_hole)
1340 			payload[newh->next_hole].prev_hole = (newh - payload);
1341 	}
1342 
1343 	/* finally copy this fragment and possibly return whole packet */
1344 	memcpy((uchar *)thisfrag, indata + IP_HDR_SIZE_NO_UDP, len);
1345 	if (!done)
1346 		return NULL;
1347 
1348 	localip->ip_len = htons(total_len);
1349 	*lenp = total_len + IP_HDR_SIZE_NO_UDP;
1350 	return localip;
1351 }
1352 
1353 static inline IP_t *NetDefragment(IP_t *ip, int *lenp)
1354 {
1355 	u16 ip_off = ntohs(ip->ip_off);
1356 	if (!(ip_off & (IP_OFFS | IP_FLAGS_MFRAG)))
1357 		return ip; /* not a fragment */
1358 	return __NetDefragment(ip, lenp);
1359 }
1360 
1361 #else /* !CONFIG_IP_DEFRAG */
1362 
1363 static inline IP_t *NetDefragment(IP_t *ip, int *lenp)
1364 {
1365 	u16 ip_off = ntohs(ip->ip_off);
1366 	if (!(ip_off & (IP_OFFS | IP_FLAGS_MFRAG)))
1367 		return ip; /* not a fragment */
1368 	return NULL;
1369 }
1370 #endif
1371 
1372 /**
1373  * Receive an ICMP packet. We deal with REDIRECT and PING here, and silently
1374  * drop others.
1375  *
1376  * @parma ip	IP packet containing the ICMP
1377  */
1378 static void receive_icmp(IP_t *ip, int len, IPaddr_t src_ip, Ethernet_t *et)
1379 {
1380 	ICMP_t *icmph = (ICMP_t *)&ip->udp_src;
1381 
1382 	switch (icmph->type) {
1383 	case ICMP_REDIRECT:
1384 		if (icmph->code != ICMP_REDIR_HOST)
1385 			return;
1386 		printf(" ICMP Host Redirect to %pI4 ",
1387 			&icmph->un.gateway);
1388 		break;
1389 #if defined(CONFIG_CMD_PING)
1390 	case ICMP_ECHO_REPLY:
1391 		/*
1392 			* IP header OK.  Pass the packet to the
1393 			* current handler.
1394 			*/
1395 		/*
1396 		 * XXX point to ip packet - should this use
1397 		 * packet_icmp_handler?
1398 		 */
1399 		(*packetHandler)((uchar *)ip, 0, src_ip, 0, 0);
1400 		break;
1401 	case ICMP_ECHO_REQUEST:
1402 		debug("Got ICMP ECHO REQUEST, return %d bytes\n",
1403 			ETHER_HDR_SIZE + len);
1404 
1405 		memcpy(&et->et_dest[0], &et->et_src[0], 6);
1406 		memcpy(&et->et_src[0], NetOurEther, 6);
1407 
1408 		ip->ip_sum = 0;
1409 		ip->ip_off = 0;
1410 		NetCopyIP((void *)&ip->ip_dst, &ip->ip_src);
1411 		NetCopyIP((void *)&ip->ip_src, &NetOurIP);
1412 		ip->ip_sum = ~NetCksum((uchar *)ip,
1413 					IP_HDR_SIZE_NO_UDP >> 1);
1414 
1415 		icmph->type = ICMP_ECHO_REPLY;
1416 		icmph->checksum = 0;
1417 		icmph->checksum = ~NetCksum((uchar *)icmph,
1418 			(len - IP_HDR_SIZE_NO_UDP) >> 1);
1419 		(void) eth_send((uchar *)et,
1420 				ETHER_HDR_SIZE + len);
1421 		break;
1422 #endif
1423 	default:
1424 #ifdef CONFIG_CMD_TFTPPUT
1425 		if (packet_icmp_handler)
1426 			packet_icmp_handler(icmph->type, icmph->code,
1427 				ntohs(ip->udp_dst), src_ip, ntohs(ip->udp_src),
1428 				icmph->un.data, ntohs(ip->udp_len));
1429 #endif
1430 		break;
1431 	}
1432 }
1433 
1434 void
1435 NetReceive(uchar *inpkt, int len)
1436 {
1437 	Ethernet_t *et;
1438 	IP_t	*ip;
1439 	ARP_t	*arp;
1440 	IPaddr_t tmp;
1441 	IPaddr_t src_ip;
1442 	int	x;
1443 	uchar *pkt;
1444 #if defined(CONFIG_CMD_CDP)
1445 	int iscdp;
1446 #endif
1447 	ushort cti = 0, vlanid = VLAN_NONE, myvlanid, mynvlanid;
1448 
1449 	debug("packet received\n");
1450 
1451 	NetRxPacket = inpkt;
1452 	NetRxPacketLen = len;
1453 	et = (Ethernet_t *)inpkt;
1454 
1455 	/* too small packet? */
1456 	if (len < ETHER_HDR_SIZE)
1457 		return;
1458 
1459 #ifdef CONFIG_API
1460 	if (push_packet) {
1461 		(*push_packet)(inpkt, len);
1462 		return;
1463 	}
1464 #endif
1465 
1466 #if defined(CONFIG_CMD_CDP)
1467 	/* keep track if packet is CDP */
1468 	iscdp = memcmp(et->et_dest, NetCDPAddr, 6) == 0;
1469 #endif
1470 
1471 	myvlanid = ntohs(NetOurVLAN);
1472 	if (myvlanid == (ushort)-1)
1473 		myvlanid = VLAN_NONE;
1474 	mynvlanid = ntohs(NetOurNativeVLAN);
1475 	if (mynvlanid == (ushort)-1)
1476 		mynvlanid = VLAN_NONE;
1477 
1478 	x = ntohs(et->et_protlen);
1479 
1480 	debug("packet received\n");
1481 
1482 	if (x < 1514) {
1483 		/*
1484 		 *	Got a 802 packet.  Check the other protocol field.
1485 		 */
1486 		x = ntohs(et->et_prot);
1487 
1488 		ip = (IP_t *)(inpkt + E802_HDR_SIZE);
1489 		len -= E802_HDR_SIZE;
1490 
1491 	} else if (x != PROT_VLAN) {	/* normal packet */
1492 		ip = (IP_t *)(inpkt + ETHER_HDR_SIZE);
1493 		len -= ETHER_HDR_SIZE;
1494 
1495 	} else {			/* VLAN packet */
1496 		VLAN_Ethernet_t *vet = (VLAN_Ethernet_t *)et;
1497 
1498 		debug("VLAN packet received\n");
1499 
1500 		/* too small packet? */
1501 		if (len < VLAN_ETHER_HDR_SIZE)
1502 			return;
1503 
1504 		/* if no VLAN active */
1505 		if ((ntohs(NetOurVLAN) & VLAN_IDMASK) == VLAN_NONE
1506 #if defined(CONFIG_CMD_CDP)
1507 				&& iscdp == 0
1508 #endif
1509 				)
1510 			return;
1511 
1512 		cti = ntohs(vet->vet_tag);
1513 		vlanid = cti & VLAN_IDMASK;
1514 		x = ntohs(vet->vet_type);
1515 
1516 		ip = (IP_t *)(inpkt + VLAN_ETHER_HDR_SIZE);
1517 		len -= VLAN_ETHER_HDR_SIZE;
1518 	}
1519 
1520 	debug("Receive from protocol 0x%x\n", x);
1521 
1522 #if defined(CONFIG_CMD_CDP)
1523 	if (iscdp) {
1524 		CDPHandler((uchar *)ip, len);
1525 		return;
1526 	}
1527 #endif
1528 
1529 	if ((myvlanid & VLAN_IDMASK) != VLAN_NONE) {
1530 		if (vlanid == VLAN_NONE)
1531 			vlanid = (mynvlanid & VLAN_IDMASK);
1532 		/* not matched? */
1533 		if (vlanid != (myvlanid & VLAN_IDMASK))
1534 			return;
1535 	}
1536 
1537 	switch (x) {
1538 
1539 	case PROT_ARP:
1540 		/*
1541 		 * We have to deal with two types of ARP packets:
1542 		 * - REQUEST packets will be answered by sending  our
1543 		 *   IP address - if we know it.
1544 		 * - REPLY packates are expected only after we asked
1545 		 *   for the TFTP server's or the gateway's ethernet
1546 		 *   address; so if we receive such a packet, we set
1547 		 *   the server ethernet address
1548 		 */
1549 		debug("Got ARP\n");
1550 
1551 		arp = (ARP_t *)ip;
1552 		if (len < ARP_HDR_SIZE) {
1553 			printf("bad length %d < %d\n", len, ARP_HDR_SIZE);
1554 			return;
1555 		}
1556 		if (ntohs(arp->ar_hrd) != ARP_ETHER)
1557 			return;
1558 		if (ntohs(arp->ar_pro) != PROT_IP)
1559 			return;
1560 		if (arp->ar_hln != 6)
1561 			return;
1562 		if (arp->ar_pln != 4)
1563 			return;
1564 
1565 		if (NetOurIP == 0)
1566 			return;
1567 
1568 		if (NetReadIP(&arp->ar_data[16]) != NetOurIP)
1569 			return;
1570 
1571 		switch (ntohs(arp->ar_op)) {
1572 		case ARPOP_REQUEST:
1573 			/* reply with our IP address */
1574 			debug("Got ARP REQUEST, return our IP\n");
1575 			pkt = (uchar *)et;
1576 			pkt += NetSetEther(pkt, et->et_src, PROT_ARP);
1577 			arp->ar_op = htons(ARPOP_REPLY);
1578 			memcpy(&arp->ar_data[10], &arp->ar_data[0], 6);
1579 			NetCopyIP(&arp->ar_data[16], &arp->ar_data[6]);
1580 			memcpy(&arp->ar_data[0], NetOurEther, 6);
1581 			NetCopyIP(&arp->ar_data[6], &NetOurIP);
1582 			(void) eth_send((uchar *)et,
1583 					(pkt - (uchar *)et) + ARP_HDR_SIZE);
1584 			return;
1585 
1586 		case ARPOP_REPLY:		/* arp reply */
1587 			/* are we waiting for a reply */
1588 			if (!NetArpWaitPacketIP || !NetArpWaitPacketMAC)
1589 				break;
1590 
1591 #ifdef CONFIG_KEEP_SERVERADDR
1592 			if (NetServerIP == NetArpWaitPacketIP) {
1593 				char buf[20];
1594 				sprintf(buf, "%pM", arp->ar_data);
1595 				setenv("serveraddr", buf);
1596 			}
1597 #endif
1598 
1599 			debug("Got ARP REPLY, set server/gtwy eth addr (%pM)\n",
1600 				arp->ar_data);
1601 
1602 			tmp = NetReadIP(&arp->ar_data[6]);
1603 
1604 			/* matched waiting packet's address */
1605 			if (tmp == NetArpWaitReplyIP) {
1606 				debug("Got it\n");
1607 
1608 				/* save address for later use */
1609 				memcpy(NetArpWaitPacketMAC,
1610 				       &arp->ar_data[0], 6);
1611 
1612 #ifdef CONFIG_NETCONSOLE
1613 				(*packetHandler)(0, 0, 0, 0, 0);
1614 #endif
1615 				/* modify header, and transmit it */
1616 				memcpy(((Ethernet_t *)NetArpWaitTxPacket)->
1617 					et_dest, NetArpWaitPacketMAC, 6);
1618 				(void) eth_send(NetArpWaitTxPacket,
1619 						NetArpWaitTxPacketSize);
1620 
1621 				/* no arp request pending now */
1622 				NetArpWaitPacketIP = 0;
1623 				NetArpWaitTxPacketSize = 0;
1624 				NetArpWaitPacketMAC = NULL;
1625 
1626 			}
1627 			return;
1628 		default:
1629 			debug("Unexpected ARP opcode 0x%x\n",
1630 			      ntohs(arp->ar_op));
1631 			return;
1632 		}
1633 		break;
1634 
1635 #ifdef CONFIG_CMD_RARP
1636 	case PROT_RARP:
1637 		debug("Got RARP\n");
1638 		arp = (ARP_t *)ip;
1639 		if (len < ARP_HDR_SIZE) {
1640 			printf("bad length %d < %d\n", len, ARP_HDR_SIZE);
1641 			return;
1642 		}
1643 
1644 		if ((ntohs(arp->ar_op) != RARPOP_REPLY) ||
1645 			(ntohs(arp->ar_hrd) != ARP_ETHER)   ||
1646 			(ntohs(arp->ar_pro) != PROT_IP)     ||
1647 			(arp->ar_hln != 6) || (arp->ar_pln != 4)) {
1648 
1649 			puts("invalid RARP header\n");
1650 		} else {
1651 			NetCopyIP(&NetOurIP, &arp->ar_data[16]);
1652 			if (NetServerIP == 0)
1653 				NetCopyIP(&NetServerIP, &arp->ar_data[6]);
1654 			memcpy(NetServerEther, &arp->ar_data[0], 6);
1655 
1656 			(*packetHandler)(0, 0, 0, 0, 0);
1657 		}
1658 		break;
1659 #endif
1660 	case PROT_IP:
1661 		debug("Got IP\n");
1662 		/* Before we start poking the header, make sure it is there */
1663 		if (len < IP_HDR_SIZE) {
1664 			debug("len bad %d < %lu\n", len, (ulong)IP_HDR_SIZE);
1665 			return;
1666 		}
1667 		/* Check the packet length */
1668 		if (len < ntohs(ip->ip_len)) {
1669 			printf("len bad %d < %d\n", len, ntohs(ip->ip_len));
1670 			return;
1671 		}
1672 		len = ntohs(ip->ip_len);
1673 		debug("len=%d, v=%02x\n", len, ip->ip_hl_v & 0xff);
1674 
1675 		/* Can't deal with anything except IPv4 */
1676 		if ((ip->ip_hl_v & 0xf0) != 0x40)
1677 			return;
1678 		/* Can't deal with IP options (headers != 20 bytes) */
1679 		if ((ip->ip_hl_v & 0x0f) > 0x05)
1680 			return;
1681 		/* Check the Checksum of the header */
1682 		if (!NetCksumOk((uchar *)ip, IP_HDR_SIZE_NO_UDP / 2)) {
1683 			puts("checksum bad\n");
1684 			return;
1685 		}
1686 		/* If it is not for us, ignore it */
1687 		tmp = NetReadIP(&ip->ip_dst);
1688 		if (NetOurIP && tmp != NetOurIP && tmp != 0xFFFFFFFF) {
1689 #ifdef CONFIG_MCAST_TFTP
1690 			if (Mcast_addr != tmp)
1691 #endif
1692 				return;
1693 		}
1694 		/* Read source IP address for later use */
1695 		src_ip = NetReadIP(&ip->ip_src);
1696 		/*
1697 		 * The function returns the unchanged packet if it's not
1698 		 * a fragment, and either the complete packet or NULL if
1699 		 * it is a fragment (if !CONFIG_IP_DEFRAG, it returns NULL)
1700 		 */
1701 		ip = NetDefragment(ip, &len);
1702 		if (!ip)
1703 			return;
1704 		/*
1705 		 * watch for ICMP host redirects
1706 		 *
1707 		 * There is no real handler code (yet). We just watch
1708 		 * for ICMP host redirect messages. In case anybody
1709 		 * sees these messages: please contact me
1710 		 * (wd@denx.de), or - even better - send me the
1711 		 * necessary fixes :-)
1712 		 *
1713 		 * Note: in all cases where I have seen this so far
1714 		 * it was a problem with the router configuration,
1715 		 * for instance when a router was configured in the
1716 		 * BOOTP reply, but the TFTP server was on the same
1717 		 * subnet. So this is probably a warning that your
1718 		 * configuration might be wrong. But I'm not really
1719 		 * sure if there aren't any other situations.
1720 		 *
1721 		 * Simon Glass <sjg@chromium.org>: We get an ICMP when
1722 		 * we send a tftp packet to a dead connection, or when
1723 		 * there is no server at the other end.
1724 		 */
1725 		if (ip->ip_p == IPPROTO_ICMP) {
1726 			receive_icmp(ip, len, src_ip, et);
1727 			return;
1728 		} else if (ip->ip_p != IPPROTO_UDP) {	/* Only UDP packets */
1729 			return;
1730 		}
1731 
1732 #ifdef CONFIG_UDP_CHECKSUM
1733 		if (ip->udp_xsum != 0) {
1734 			ulong   xsum;
1735 			ushort *sumptr;
1736 			ushort  sumlen;
1737 
1738 			xsum  = ip->ip_p;
1739 			xsum += (ntohs(ip->udp_len));
1740 			xsum += (ntohl(ip->ip_src) >> 16) & 0x0000ffff;
1741 			xsum += (ntohl(ip->ip_src) >>  0) & 0x0000ffff;
1742 			xsum += (ntohl(ip->ip_dst) >> 16) & 0x0000ffff;
1743 			xsum += (ntohl(ip->ip_dst) >>  0) & 0x0000ffff;
1744 
1745 			sumlen = ntohs(ip->udp_len);
1746 			sumptr = (ushort *) &(ip->udp_src);
1747 
1748 			while (sumlen > 1) {
1749 				ushort sumdata;
1750 
1751 				sumdata = *sumptr++;
1752 				xsum += ntohs(sumdata);
1753 				sumlen -= 2;
1754 			}
1755 			if (sumlen > 0) {
1756 				ushort sumdata;
1757 
1758 				sumdata = *(unsigned char *) sumptr;
1759 				sumdata = (sumdata << 8) & 0xff00;
1760 				xsum += sumdata;
1761 			}
1762 			while ((xsum >> 16) != 0) {
1763 				xsum = (xsum & 0x0000ffff) +
1764 				       ((xsum >> 16) & 0x0000ffff);
1765 			}
1766 			if ((xsum != 0x00000000) && (xsum != 0x0000ffff)) {
1767 				printf(" UDP wrong checksum %08lx %08x\n",
1768 					xsum, ntohs(ip->udp_xsum));
1769 				return;
1770 			}
1771 		}
1772 #endif
1773 
1774 
1775 #ifdef CONFIG_NETCONSOLE
1776 		nc_input_packet((uchar *)ip + IP_HDR_SIZE,
1777 						ntohs(ip->udp_dst),
1778 						ntohs(ip->udp_src),
1779 						ntohs(ip->udp_len) - 8);
1780 #endif
1781 		/*
1782 		 *	IP header OK.  Pass the packet to the current handler.
1783 		 */
1784 		(*packetHandler)((uchar *)ip + IP_HDR_SIZE,
1785 						ntohs(ip->udp_dst),
1786 						src_ip,
1787 						ntohs(ip->udp_src),
1788 						ntohs(ip->udp_len) - 8);
1789 		break;
1790 	}
1791 }
1792 
1793 
1794 /**********************************************************************/
1795 
1796 static int net_check_prereq(enum proto_t protocol)
1797 {
1798 	switch (protocol) {
1799 		/* Fall through */
1800 #if defined(CONFIG_CMD_PING)
1801 	case PING:
1802 		if (NetPingIP == 0) {
1803 			puts("*** ERROR: ping address not given\n");
1804 			return 1;
1805 		}
1806 		goto common;
1807 #endif
1808 #if defined(CONFIG_CMD_SNTP)
1809 	case SNTP:
1810 		if (NetNtpServerIP == 0) {
1811 			puts("*** ERROR: NTP server address not given\n");
1812 			return 1;
1813 		}
1814 		goto common;
1815 #endif
1816 #if defined(CONFIG_CMD_DNS)
1817 	case DNS:
1818 		if (NetOurDNSIP == 0) {
1819 			puts("*** ERROR: DNS server address not given\n");
1820 			return 1;
1821 		}
1822 		goto common;
1823 #endif
1824 #if defined(CONFIG_CMD_NFS)
1825 	case NFS:
1826 #endif
1827 	case TFTPGET:
1828 	case TFTPPUT:
1829 		if (NetServerIP == 0) {
1830 			puts("*** ERROR: `serverip' not set\n");
1831 			return 1;
1832 		}
1833 #if	defined(CONFIG_CMD_PING) || defined(CONFIG_CMD_SNTP) || \
1834 	defined(CONFIG_CMD_DNS)
1835 common:
1836 #endif
1837 		/* Fall through */
1838 
1839 	case NETCONS:
1840 	case TFTPSRV:
1841 		if (NetOurIP == 0) {
1842 			puts("*** ERROR: `ipaddr' not set\n");
1843 			return 1;
1844 		}
1845 		/* Fall through */
1846 
1847 #ifdef CONFIG_CMD_RARP
1848 	case RARP:
1849 #endif
1850 	case BOOTP:
1851 	case CDP:
1852 	case DHCP:
1853 		if (memcmp(NetOurEther, "\0\0\0\0\0\0", 6) == 0) {
1854 			int num = eth_get_dev_index();
1855 
1856 			switch (num) {
1857 			case -1:
1858 				puts("*** ERROR: No ethernet found.\n");
1859 				return 1;
1860 			case 0:
1861 				puts("*** ERROR: `ethaddr' not set\n");
1862 				break;
1863 			default:
1864 				printf("*** ERROR: `eth%daddr' not set\n",
1865 					num);
1866 				break;
1867 			}
1868 
1869 			NetStartAgain();
1870 			return 2;
1871 		}
1872 		/* Fall through */
1873 	default:
1874 		return 0;
1875 	}
1876 	return 0;		/* OK */
1877 }
1878 /**********************************************************************/
1879 
1880 int
1881 NetCksumOk(uchar *ptr, int len)
1882 {
1883 	return !((NetCksum(ptr, len) + 1) & 0xfffe);
1884 }
1885 
1886 
1887 unsigned
1888 NetCksum(uchar *ptr, int len)
1889 {
1890 	ulong	xsum;
1891 	ushort *p = (ushort *)ptr;
1892 
1893 	xsum = 0;
1894 	while (len-- > 0)
1895 		xsum += *p++;
1896 	xsum = (xsum & 0xffff) + (xsum >> 16);
1897 	xsum = (xsum & 0xffff) + (xsum >> 16);
1898 	return xsum & 0xffff;
1899 }
1900 
1901 int
1902 NetEthHdrSize(void)
1903 {
1904 	ushort myvlanid;
1905 
1906 	myvlanid = ntohs(NetOurVLAN);
1907 	if (myvlanid == (ushort)-1)
1908 		myvlanid = VLAN_NONE;
1909 
1910 	return ((myvlanid & VLAN_IDMASK) == VLAN_NONE) ? ETHER_HDR_SIZE :
1911 		VLAN_ETHER_HDR_SIZE;
1912 }
1913 
1914 int
1915 NetSetEther(uchar *xet, uchar * addr, uint prot)
1916 {
1917 	Ethernet_t *et = (Ethernet_t *)xet;
1918 	ushort myvlanid;
1919 
1920 	myvlanid = ntohs(NetOurVLAN);
1921 	if (myvlanid == (ushort)-1)
1922 		myvlanid = VLAN_NONE;
1923 
1924 	memcpy(et->et_dest, addr, 6);
1925 	memcpy(et->et_src, NetOurEther, 6);
1926 	if ((myvlanid & VLAN_IDMASK) == VLAN_NONE) {
1927 		et->et_protlen = htons(prot);
1928 		return ETHER_HDR_SIZE;
1929 	} else {
1930 		VLAN_Ethernet_t *vet = (VLAN_Ethernet_t *)xet;
1931 
1932 		vet->vet_vlan_type = htons(PROT_VLAN);
1933 		vet->vet_tag = htons((0 << 5) | (myvlanid & VLAN_IDMASK));
1934 		vet->vet_type = htons(prot);
1935 		return VLAN_ETHER_HDR_SIZE;
1936 	}
1937 }
1938 
1939 void
1940 NetSetIP(uchar *xip, IPaddr_t dest, int dport, int sport, int len)
1941 {
1942 	IP_t *ip = (IP_t *)xip;
1943 
1944 	/*
1945 	 *	If the data is an odd number of bytes, zero the
1946 	 *	byte after the last byte so that the checksum
1947 	 *	will work.
1948 	 */
1949 	if (len & 1)
1950 		xip[IP_HDR_SIZE + len] = 0;
1951 
1952 	/*
1953 	 *	Construct an IP and UDP header.
1954 	 *	(need to set no fragment bit - XXX)
1955 	 */
1956 	/* IP_HDR_SIZE / 4 (not including UDP) */
1957 	ip->ip_hl_v  = 0x45;
1958 	ip->ip_tos   = 0;
1959 	ip->ip_len   = htons(IP_HDR_SIZE + len);
1960 	ip->ip_id    = htons(NetIPID++);
1961 	ip->ip_off   = htons(IP_FLAGS_DFRAG);	/* Don't fragment */
1962 	ip->ip_ttl   = 255;
1963 	ip->ip_p     = 17;		/* UDP */
1964 	ip->ip_sum   = 0;
1965 	/* already in network byte order */
1966 	NetCopyIP((void *)&ip->ip_src, &NetOurIP);
1967 	/* - "" - */
1968 	NetCopyIP((void *)&ip->ip_dst, &dest);
1969 	ip->udp_src  = htons(sport);
1970 	ip->udp_dst  = htons(dport);
1971 	ip->udp_len  = htons(8 + len);
1972 	ip->udp_xsum = 0;
1973 	ip->ip_sum   = ~NetCksum((uchar *)ip, IP_HDR_SIZE_NO_UDP / 2);
1974 }
1975 
1976 void copy_filename(char *dst, const char *src, int size)
1977 {
1978 	if (*src && (*src == '"')) {
1979 		++src;
1980 		--size;
1981 	}
1982 
1983 	while ((--size > 0) && *src && (*src != '"'))
1984 		*dst++ = *src++;
1985 	*dst = '\0';
1986 }
1987 
1988 #if	defined(CONFIG_CMD_NFS)		|| \
1989 	defined(CONFIG_CMD_SNTP)	|| \
1990 	defined(CONFIG_CMD_DNS)
1991 /*
1992  * make port a little random (1024-17407)
1993  * This keeps the math somewhat trivial to compute, and seems to work with
1994  * all supported protocols/clients/servers
1995  */
1996 unsigned int random_port(void)
1997 {
1998 	return 1024 + (get_timer(0) % 0x4000);
1999 }
2000 #endif
2001 
2002 void ip_to_string(IPaddr_t x, char *s)
2003 {
2004 	x = ntohl(x);
2005 	sprintf(s, "%d.%d.%d.%d",
2006 		(int) ((x >> 24) & 0xff),
2007 		(int) ((x >> 16) & 0xff),
2008 		(int) ((x >> 8) & 0xff), (int) ((x >> 0) & 0xff)
2009 	);
2010 }
2011 
2012 void VLAN_to_string(ushort x, char *s)
2013 {
2014 	x = ntohs(x);
2015 
2016 	if (x == (ushort)-1)
2017 		x = VLAN_NONE;
2018 
2019 	if (x == VLAN_NONE)
2020 		strcpy(s, "none");
2021 	else
2022 		sprintf(s, "%d", x & VLAN_IDMASK);
2023 }
2024 
2025 ushort string_to_VLAN(const char *s)
2026 {
2027 	ushort id;
2028 
2029 	if (s == NULL)
2030 		return htons(VLAN_NONE);
2031 
2032 	if (*s < '0' || *s > '9')
2033 		id = VLAN_NONE;
2034 	else
2035 		id = (ushort)simple_strtoul(s, NULL, 10);
2036 
2037 	return htons(id);
2038 }
2039 
2040 ushort getenv_VLAN(char *var)
2041 {
2042 	return string_to_VLAN(getenv(var));
2043 }
2044