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