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