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