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