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