1 /* SPDX-License-Identifier: GPL-2.0+ */
2 
3 #ifndef __NET_COMMON_H__
4 #define __NET_COMMON_H__
5 
6 #include <asm/cache.h>
7 #include <command.h>
8 #include <hexdump.h>
9 #include <linux/if_ether.h>
10 #include <linux/sizes.h>
11 #include <linux/types.h>
12 #include <rand.h>
13 #include <time.h>
14 
15 #define DEBUG_NET_PKT_TRACE 0	/* Trace all packet data */
16 
17 /*
18  *	The number of receive packet buffers, and the required packet buffer
19  *	alignment in memory.
20  *
21  */
22 #define PKTBUFSRX	CONFIG_SYS_RX_ETH_BUFFER
23 #define PKTALIGN	ARCH_DMA_MINALIGN
24 
25 /* IPv4 addresses are always 32 bits in size */
26 struct in_addr {
27 	__be32 s_addr;
28 };
29 
30 #define PROT_IP		0x0800		/* IP protocol			*/
31 #define PROT_ARP	0x0806		/* IP ARP protocol		*/
32 #define PROT_WOL	0x0842		/* ether-wake WoL protocol	*/
33 #define PROT_RARP	0x8035		/* IP ARP protocol		*/
34 #define PROT_VLAN	0x8100		/* IEEE 802.1q protocol		*/
35 #define PROT_IPV6	0x86dd		/* IPv6 over bluebook		*/
36 #define PROT_PPP_SES	0x8864		/* PPPoE session messages	*/
37 #define PROT_NCSI	0x88f8		/* NC-SI control packets        */
38 
39 #define IPPROTO_ICMP	 1	/* Internet Control Message Protocol	*/
40 #define IPPROTO_TCP	6	/* Transmission Control Protocol	*/
41 #define IPPROTO_UDP	17	/* User Datagram Protocol		*/
42 
43 #define IP_OFFS		0x1fff /* ip offset *= 8 */
44 #define IP_FLAGS	0xe000 /* first 3 bits */
45 #define IP_FLAGS_RES	0x8000 /* reserved */
46 #define IP_FLAGS_DFRAG	0x4000 /* don't fragments */
47 #define IP_FLAGS_MFRAG	0x2000 /* more fragments */
48 
49 #define IP_HDR_SIZE		(sizeof(struct ip_hdr))
50 
51 #define IP_MIN_FRAG_DATAGRAM_SIZE	(IP_HDR_SIZE + 8)
52 
53 /*
54  *	Internet Protocol (IP) + UDP header.
55  */
56 struct ip_udp_hdr {
57 	u8		ip_hl_v;	/* header length and version	*/
58 	u8		ip_tos;		/* type of service		*/
59 	u16		ip_len;		/* total length			*/
60 	u16		ip_id;		/* identification		*/
61 	u16		ip_off;		/* fragment offset field	*/
62 	u8		ip_ttl;		/* time to live			*/
63 	u8		ip_p;		/* protocol			*/
64 	u16		ip_sum;		/* checksum			*/
65 	struct in_addr	ip_src;		/* Source IP address		*/
66 	struct in_addr	ip_dst;		/* Destination IP address	*/
67 	u16		udp_src;	/* UDP source port		*/
68 	u16		udp_dst;	/* UDP destination port		*/
69 	u16		udp_len;	/* Length of UDP packet		*/
70 	u16		udp_xsum;	/* Checksum			*/
71 } __packed;
72 
73 #define IP_UDP_HDR_SIZE		(sizeof(struct ip_udp_hdr))
74 #define UDP_HDR_SIZE		(IP_UDP_HDR_SIZE - IP_HDR_SIZE)
75 
76 /* Number of packets processed together */
77 #define ETH_PACKETS_BATCH_RECV	32
78 
79 /* ARP hardware address length */
80 #define ARP_HLEN 6
81 /*
82  * The size of a MAC address in string form, each digit requires two chars
83  * and five separator characters to form '00:00:00:00:00:00'.
84  */
85 #define ARP_HLEN_ASCII (ARP_HLEN * 2) + (ARP_HLEN - 1)
86 
87 #define ARP_HDR_SIZE	(8 + 20)	/* Size assuming ethernet	*/
88 
89 #   define ARP_ETHER	    1		/* Ethernet  hardware address	*/
90 
91 /*
92  * Maximum packet size; used to allocate packet storage. Use
93  * the maximum Ethernet frame size as specified by the Ethernet
94  * standard including the 802.1Q tag (VLAN tagging).
95  * maximum packet size =  1522
96  * maximum packet size and multiple of 32 bytes =  1536
97  */
98 #define PKTSIZE			1522
99 #ifndef CONFIG_DM_DSA
100 #define PKTSIZE_ALIGN		1536
101 #else
102 /* Maximum DSA tagging overhead (headroom and/or tailroom) */
103 #define DSA_MAX_OVR		256
104 #define PKTSIZE_ALIGN		(1536 + DSA_MAX_OVR)
105 #endif
106 
107 /*
108  * Maximum receive ring size; that is, the number of packets
109  * we can buffer before overflow happens. Basically, this just
110  * needs to be enough to prevent a packet being discarded while
111  * we are processing the previous one.
112  * Used only in drivers/net/mvgbe.c.
113  */
114 #define RINGSZ		4
115 #define RINGSZ_LOG2	2
116 
117 extern int		net_restart_wrap;	/* Tried all network devices */
118 extern uchar               *net_rx_packets[PKTBUFSRX]; /* Receive packets */
119 extern const u8		net_bcast_ethaddr[ARP_HLEN];	/* Ethernet broadcast address */
120 extern char	net_boot_file_name[1024];/* Boot File name */
121 extern struct in_addr	net_ip;		/* Our    IP addr (0 = unknown) */
122 /* Indicates whether the pxe path prefix / config file was specified in dhcp option */
123 extern char *pxelinux_configfile;
124 
125 /**
126  * compute_ip_checksum() - Compute IP checksum
127  *
128  * @addr:	Address to check (must be 16-bit aligned)
129  * @nbytes:	Number of bytes to check (normally a multiple of 2)
130  * Return: 16-bit IP checksum
131  */
132 unsigned compute_ip_checksum(const void *addr, unsigned int nbytes);
133 
134 /**
135  * ip_checksum_ok() - check if a checksum is correct
136  *
137  * This works by making sure the checksum sums to 0
138  *
139  * @addr:	Address to check (must be 16-bit aligned)
140  * @nbytes:	Number of bytes to check (normally a multiple of 2)
141  * Return: true if the checksum matches, false if not
142  */
143 int ip_checksum_ok(const void *addr, unsigned int nbytes);
144 
145 /**
146  * add_ip_checksums() - add two IP checksums
147  *
148  * @offset:	Offset of first sum (if odd we do a byte-swap)
149  * @sum:	First checksum
150  * @new_sum:	New checksum to add
151  * Return: updated 16-bit IP checksum
152  */
153 unsigned add_ip_checksums(unsigned offset, unsigned sum, unsigned int new_sum);
154 
155 /*
156  * The devname can be either an exact name given by the driver or device tree
157  * or it can be an alias of the form "eth%d"
158  */
159 struct udevice *eth_get_dev_by_name(const char *devname);
160 int eth_is_active(struct udevice *dev); /* Test device for active state */
161 
162 /*
163  * Get the hardware address for an ethernet interface .
164  * Args:
165  *	base_name - base name for device (normally "eth")
166  *	index - device index number (0 for first)
167  *	enetaddr - returns 6 byte hardware address
168  * Returns:
169  *	Return true if the address is valid.
170  */
171 int eth_env_get_enetaddr_by_index(const char *base_name, int index,
172 				 uchar *enetaddr);
173 
174 /**
175  * eth_env_set_enetaddr_by_index() - set the MAC address environment variable
176  *
177  * This sets up an environment variable with the given MAC address (@enetaddr).
178  * The environment variable to be set is defined by <@base_name><@index>addr.
179  * If @index is 0 it is omitted. For common Ethernet this means ethaddr,
180  * eth1addr, etc.
181  *
182  * @base_name:  Base name for variable, typically "eth"
183  * @index:      Index of interface being updated (>=0)
184  * @enetaddr:   Pointer to MAC address to put into the variable
185  * Return: 0 if OK, other value on error
186  */
187 int eth_env_set_enetaddr_by_index(const char *base_name, int index,
188 				  uchar *enetaddr);
189 
190 /*
191  * Initialize USB ethernet device with CONFIG_DM_ETH
192  * Returns:
193  *	0 is success, non-zero is error status.
194  */
195 int usb_ether_init(void);
196 
197 int eth_init(void);			/* Initialize the device */
198 int eth_start_udev(struct udevice *dev); /* ->start() if not already running */
199 int eth_send(void *packet, int length);	   /* Send a packet */
200 #if defined(CONFIG_API) || defined(CONFIG_EFI_LOADER)
201 int eth_receive(void *packet, int length); /* Receive a packet*/
202 extern void (*push_packet)(void *packet, int length);
203 #endif
204 int eth_rx(void);			/* Check for received packets */
205 
206 /**
207  * reset_phy() - Reset the Ethernet PHY
208  *
209  * This should be implemented by boards if CONFIG_RESET_PHY_R is enabled
210  */
211 void reset_phy(void);
212 
213 #if CONFIG_IS_ENABLED(NET) || CONFIG_IS_ENABLED(NET_LWIP)
214 /**
215  * eth_set_enable_bootdevs() - Enable or disable binding of Ethernet bootdevs
216  *
217  * These get in the way of bootstd testing, so are normally disabled by tests.
218  * This provide control of this setting. It only affects binding of Ethernet
219  * devices, so if that has already happened, this flag does nothing.
220  *
221  * @enable: true to enable binding of bootdevs when binding new Ethernet
222  * devices, false to disable it
223  */
224 void eth_set_enable_bootdevs(bool enable);
225 #else
eth_set_enable_bootdevs(bool enable)226 static inline void eth_set_enable_bootdevs(bool enable) {}
227 #endif
228 
net_send_packet(uchar * pkt,int len)229 static inline void net_send_packet(uchar *pkt, int len)
230 {
231 	if (DEBUG_NET_PKT_TRACE)
232 		print_hex_dump_bytes("tx: ", DUMP_PREFIX_OFFSET, pkt, len);
233 	/* Currently no way to return errors from eth_send() */
234 	(void)eth_send(pkt, len);
235 }
236 
237 enum eth_recv_flags {
238 	/*
239 	 * Check hardware device for new packets (otherwise only return those
240 	 * which are already in the memory buffer ready to process)
241 	 */
242 	ETH_RECV_CHECK_DEVICE		= 1 << 0,
243 };
244 
245 /**
246  * struct eth_ops - functions of Ethernet MAC controllers
247  *
248  * start: Prepare the hardware to send and receive packets
249  * send: Send the bytes passed in "packet" as a packet on the wire
250  * recv: Check if the hardware received a packet. If so, set the pointer to the
251  *	 packet buffer in the packetp parameter. If not, return an error or 0 to
252  *	 indicate that the hardware receive FIFO is empty. If 0 is returned, the
253  *	 network stack will not process the empty packet, but free_pkt() will be
254  *	 called if supplied
255  * free_pkt: Give the driver an opportunity to manage its packet buffer memory
256  *	     when the network stack is finished processing it. This will only be
257  *	     called when no error was returned from recv - optional
258  * stop: Stop the hardware from looking for packets - may be called even if
259  *	 state == PASSIVE
260  * mcast: Join or leave a multicast group (for TFTP) - optional
261  * write_hwaddr: Write a MAC address to the hardware (used to pass it to Linux
262  *		 on some platforms like ARM). This function expects the
263  *		 eth_pdata::enetaddr field to be populated. The method can
264  *		 return -ENOSYS to indicate that this is not implemented for
265 		 this hardware - optional.
266  * read_rom_hwaddr: Some devices have a backup of the MAC address stored in a
267  *		    ROM on the board. This is how the driver should expose it
268  *		    to the network stack. This function should fill in the
269  *		    eth_pdata::enetaddr field - optional
270  * set_promisc: Enable or Disable promiscuous mode
271  * get_sset_count: Number of statistics counters
272  * get_string: Names of the statistic counters
273  * get_stats: The values of the statistic counters
274  */
275 struct eth_ops {
276 	int (*start)(struct udevice *dev);
277 	int (*send)(struct udevice *dev, void *packet, int length);
278 	int (*recv)(struct udevice *dev, int flags, uchar **packetp);
279 	int (*free_pkt)(struct udevice *dev, uchar *packet, int length);
280 	void (*stop)(struct udevice *dev);
281 	int (*mcast)(struct udevice *dev, const u8 *enetaddr, int join);
282 	int (*write_hwaddr)(struct udevice *dev);
283 	int (*read_rom_hwaddr)(struct udevice *dev);
284 	int (*set_promisc)(struct udevice *dev, bool enable);
285 	int (*get_sset_count)(struct udevice *dev);
286 	void (*get_strings)(struct udevice *dev, u8 *data);
287 	void (*get_stats)(struct udevice *dev, u64 *data);
288 };
289 
290 #define eth_get_ops(dev) ((struct eth_ops *)(dev)->driver->ops)
291 
292 struct udevice *eth_get_dev(void); /* get the current device */
293 void eth_set_dev(struct udevice *dev); /* set a device */
294 unsigned char *eth_get_ethaddr(void); /* get the current device MAC */
295 int eth_rx(void);                      /* Check for received packets */
296 void eth_halt(void);			/* stop SCC */
297 const char *eth_get_name(void);		/* get name of current device */
298 int eth_get_dev_index(void);
299 
300 int eth_initialize(void);		/* Initialize network subsystem */
301 void eth_try_another(int first_restart);	/* Change the device */
302 void eth_set_current(void);		/* set nterface to ethcur var */
303 
304 enum eth_state_t {
305 	ETH_STATE_INIT,
306 	ETH_STATE_PASSIVE,
307 	ETH_STATE_ACTIVE
308 };
309 
310 /**
311  * struct eth_pdata - Platform data for Ethernet MAC controllers
312  *
313  * @iobase: The base address of the hardware registers
314  * @enetaddr: The Ethernet MAC address that is loaded from EEPROM or env
315  * @phy_interface: PHY interface to use - see PHY_INTERFACE_MODE_...
316  * @max_speed: Maximum speed of Ethernet connection supported by MAC
317  * @priv_pdata: device specific plat
318  */
319 struct eth_pdata {
320 	phys_addr_t iobase;
321 	unsigned char enetaddr[ARP_HLEN];
322 	int phy_interface;
323 	int max_speed;
324 	void *priv_pdata;
325 };
326 
327 struct ethernet_hdr {
328 	u8		et_dest[ARP_HLEN];	/* Destination node	*/
329 	u8		et_src[ARP_HLEN];	/* Source node		*/
330 	u16		et_protlen;		/* Protocol or length	*/
331 } __packed;
332 
333 /* Ethernet header size */
334 #define ETHER_HDR_SIZE	(sizeof(struct ethernet_hdr))
335 
336 /**
337  * net_random_ethaddr - Generate software assigned random Ethernet address
338  * @addr: Pointer to a six-byte array containing the Ethernet address
339  *
340  * Generate a random Ethernet address (MAC) that is not multicast
341  * and has the local assigned bit set.
342  */
net_random_ethaddr(uchar * addr)343 static inline void net_random_ethaddr(uchar *addr)
344 {
345 	int i;
346 	unsigned int seed = get_ticks();
347 
348 	for (i = 0; i < 6; i++)
349 		addr[i] = rand_r(&seed);
350 
351 	addr[0] &= 0xfe;	/* clear multicast bit */
352 	addr[0] |= 0x02;	/* set local assignment bit (IEEE802) */
353 }
354 
355 /**
356  * is_zero_ethaddr - Determine if give Ethernet address is all zeros.
357  * @addr: Pointer to a six-byte array containing the Ethernet address
358  *
359  * Return true if the address is all zeroes.
360  */
is_zero_ethaddr(const u8 * addr)361 static inline int is_zero_ethaddr(const u8 *addr)
362 {
363 	return !(addr[0] | addr[1] | addr[2] | addr[3] | addr[4] | addr[5]);
364 }
365 
366 /**
367  * is_multicast_ethaddr - Determine if the Ethernet address is a multicast.
368  * @addr: Pointer to a six-byte array containing the Ethernet address
369  *
370  * Return true if the address is a multicast address.
371  * By definition the broadcast address is also a multicast address.
372  */
is_multicast_ethaddr(const u8 * addr)373 static inline int is_multicast_ethaddr(const u8 *addr)
374 {
375 	return 0x01 & addr[0];
376 }
377 
378 /*
379  * is_broadcast_ethaddr - Determine if the Ethernet address is broadcast
380  * @addr: Pointer to a six-byte array containing the Ethernet address
381  *
382  * Return true if the address is the broadcast address.
383  */
is_broadcast_ethaddr(const u8 * addr)384 static inline int is_broadcast_ethaddr(const u8 *addr)
385 {
386 	return (addr[0] & addr[1] & addr[2] & addr[3] & addr[4] & addr[5]) ==
387 		0xff;
388 }
389 
390 /*
391  * is_valid_ethaddr - Determine if the given Ethernet address is valid
392  * @addr: Pointer to a six-byte array containing the Ethernet address
393  *
394  * Check that the Ethernet address (MAC) is not 00:00:00:00:00:00, is not
395  * a multicast address, and is not FF:FF:FF:FF:FF:FF.
396  *
397  * Return true if the address is valid.
398  */
is_valid_ethaddr(const u8 * addr)399 static inline int is_valid_ethaddr(const u8 *addr)
400 {
401 	/* FF:FF:FF:FF:FF:FF is a multicast address so we don't need to
402 	 * explicitly check for it here. */
403 	return !is_multicast_ethaddr(addr) && !is_zero_ethaddr(addr);
404 }
405 
406 /**
407  * string_to_enetaddr() - Parse a MAC address
408  *
409  * Convert a string MAC address
410  *
411  * Implemented in lib/net_utils.c (built unconditionally)
412  *
413  * @addr: MAC address in aa:bb:cc:dd:ee:ff format, where each part is a 2-digit
414  *	hex value
415  * @enetaddr: Place to put MAC address (6 bytes)
416  */
417 void string_to_enetaddr(const char *addr, uint8_t *enetaddr);
418 
419 /**
420  * string_to_ip() - Convert a string to ip address
421  *
422  * Implemented in lib/net_utils.c (built unconditionally)
423  *
424  * @s: Input string to parse
425  * @return: in_addr struct containing the parsed IP address
426  */
427 struct in_addr string_to_ip(const char *s);
428 
429 /**
430  * ip_to_string() - Convert an IPv4 address to a string
431  *
432  * Implemented in lib/net_utils.c (built unconditionally)
433  *
434  * @x: Input ip to parse
435  * @s: string containing the parsed ip address
436  */
437 void ip_to_string(struct in_addr x, char *s);
438 
439 /* copy a filename (allow for "..." notation, limit length) */
440 void copy_filename(char *dst, const char *src, int size);
441 
442 /* Processes a received packet */
443 void net_process_received_packet(uchar *in_packet, int len);
444 
445 /**
446  * update_tftp - Update firmware over TFTP (via DFU)
447  *
448  * This function updates board's firmware via TFTP
449  *
450  * @param addr - memory address where data is stored
451  * @param interface - the DFU medium name - e.g. "mmc"
452  * @param devstring - the DFU medium number - e.g. "1"
453  *
454  * Return: - 0 on success, other value on failure
455  */
456 int update_tftp(ulong addr, char *interface, char *devstring);
457 
458 int net_init(void);
459 
460 /* Called when a network operation fails to know if it should be re-tried */
461 int net_start_again(void);
462 
463 /* NET compatibility */
464 enum proto_t;
465 int net_loop(enum proto_t protocol);
466 
467 /**
468  * dhcp_run() - Run DHCP on the current ethernet device
469  *
470  * This sets the autoload variable, then puts it back to similar to its original
471  * state (y, n or unset).
472  *
473  * @addr: Address to load the file into (0 if @autoload is false)
474  * @fname: Filename of file to load (NULL if @autoload is false or to use the
475  * default filename)
476  * @autoload: true to load the file, false to just get the network IP
477  * @return 0 if OK, -EINVAL if the environment failed, -ENOENT if ant file was
478  * not found
479  */
480 int dhcp_run(ulong addr, const char *fname, bool autoload);
481 
482 
483 /**
484  * do_ping - Run the ping command
485  *
486  * @cmdtp: Unused
487  * @flag: Command flags (CMD_FLAG_...)
488  * @argc: Number of arguments
489  * @argv: List of arguments
490  * Return: result (see enum command_ret_t)
491  */
492 int do_ping(struct cmd_tbl *cmdtp, int flag, int argc, char *const argv[]);
493 
494 /**
495  * do_sntp - Run the sntp command
496  *
497  * @cmdtp: Unused
498  * @flag: Command flags (CMD_FLAG_...)
499  * @argc: Number of arguments
500  * @argv: List of arguments
501  * Return: result (see enum command_ret_t)
502  */
503 int do_sntp(struct cmd_tbl *cmdtp, int flag, int argc, char *const argv[]);
504 
505 /**
506  * do_tftpb - Run the tftpboot command
507  *
508  * @cmdtp: Command information for tftpboot
509  * @flag: Command flags (CMD_FLAG_...)
510  * @argc: Number of arguments
511  * @argv: List of arguments
512  * Return: result (see enum command_ret_t)
513  */
514 int do_tftpb(struct cmd_tbl *cmdtp, int flag, int argc, char *const argv[]);
515 
516 /**
517  * wget_do_request() - sends a wget request
518  *
519  * Sends a wget request, if DNS resolution is enabled it resolves the
520  * given uri.
521  *
522  * @dst_addr:	destination address to download the file
523  * @uri:	uri string of target file of wget
524  * Return:	zero on success, negative if failed
525  */
526 int wget_do_request(ulong dst_addr, char *uri);
527 /**
528  * wget_validate_uri() - varidate the uri
529  *
530  * @uri:	uri string of target file of wget
531  * Return:	true if uri is valid, false if uri is invalid
532  */
533 bool wget_validate_uri(char *uri);
534 
535 /**
536  * enum wget_http_method - http method
537  */
538 enum wget_http_method {
539 	WGET_HTTP_METHOD_GET,
540 	WGET_HTTP_METHOD_POST,
541 	WGET_HTTP_METHOD_PATCH,
542 	WGET_HTTP_METHOD_OPTIONS,
543 	WGET_HTTP_METHOD_CONNECT,
544 	WGET_HTTP_METHOD_HEAD,
545 	WGET_HTTP_METHOD_PUT,
546 	WGET_HTTP_METHOD_DELETE,
547 	WGET_HTTP_METHOD_TRACE,
548 	WGET_HTTP_METHOD_MAX
549 };
550 
551 /**
552  * define MAX_HTTP_HEADERS_SIZE - maximum headers buffer size
553  *
554  * When receiving http headers, wget fills a buffer with up
555  * to MAX_HTTP_HEADERS_SIZE bytes of header information.
556  */
557 #define MAX_HTTP_HEADERS_SIZE SZ_64K
558 
559 /**
560  * struct wget_http_info - wget parameters
561  * @method:		HTTP Method. Filled by client.
562  * @status_code:	HTTP status code. Filled by wget.
563  * @file_size:		download size. Filled by wget.
564  * @buffer_size:	size of client-provided buffer. Filled by client.
565  * @set_bootdev:	set boot device with download. Filled by client.
566  * @check_buffer_size:	check download does not exceed buffer size.
567  *			Filled by client.
568  * @hdr_cont_len:	content length according to headers. Filled by wget
569  * @headers:		buffer for headers. Filled by wget.
570  * @silent:		do not print anything to the console. Filled by client.
571  */
572 struct wget_http_info {
573 	enum wget_http_method method;
574 	u32 status_code;
575 	ulong file_size;
576 	ulong buffer_size;
577 	bool set_bootdev;
578 	bool check_buffer_size;
579 	u32 hdr_cont_len;
580 	char *headers;
581 	bool silent;
582 };
583 
584 extern struct wget_http_info default_wget_info;
585 extern struct wget_http_info *wget_info;
586 int wget_request(ulong dst_addr, char *uri, struct wget_http_info *info);
587 
588 void net_sntp_set_rtc(u32 seconds);
589 
590 #endif /* __NET_COMMON_H__ */
591