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