1/*
2 * Copyright 1994, 1995, 2000 Neil Russell.
3 * (See License)
4 * Copyright 2000, 2001 DENX Software Engineering, Wolfgang Denk, wd@denx.de
5 * Copyright 2011 Comelit Group SpA,
6 *                Luca Ceresoli <luca.ceresoli@comelit.it>
7 */
8#include <common.h>
9#include <command.h>
10#include <display_options.h>
11#include <efi_loader.h>
12#include <env.h>
13#include <image.h>
14#include <lmb.h>
15#include <log.h>
16#include <mapmem.h>
17#include <net.h>
18#include <net6.h>
19#include <asm/global_data.h>
20#include <net/tftp.h>
21#include "bootp.h"
22
23DECLARE_GLOBAL_DATA_PTR;
24
25/* Well known TFTP port # */
26#define WELL_KNOWN_PORT	69
27/* Millisecs to timeout for lost pkt */
28#define TIMEOUT		5000UL
29/* Number of "loading" hashes per line (for checking the image size) */
30#define HASHES_PER_LINE	65
31
32/*
33 *	TFTP operations.
34 */
35#define TFTP_RRQ	1
36#define TFTP_WRQ	2
37#define TFTP_DATA	3
38#define TFTP_ACK	4
39#define TFTP_ERROR	5
40#define TFTP_OACK	6
41
42static ulong timeout_ms = TIMEOUT;
43static int timeout_count_max = (CONFIG_NET_RETRY_COUNT * 2);
44static ulong time_start;   /* Record time we started tftp */
45static struct in6_addr tftp_remote_ip6;
46
47/*
48 * These globals govern the timeout behavior when attempting a connection to a
49 * TFTP server. tftp_timeout_ms specifies the number of milliseconds to
50 * wait for the server to respond to initial connection. Second global,
51 * tftp_timeout_count_max, gives the number of such connection retries.
52 * tftp_timeout_count_max must be non-negative and tftp_timeout_ms must be
53 * positive. The globals are meant to be set (and restored) by code needing
54 * non-standard timeout behavior when initiating a TFTP transfer.
55 */
56ulong tftp_timeout_ms = TIMEOUT;
57int tftp_timeout_count_max = (CONFIG_NET_RETRY_COUNT * 2);
58
59enum {
60	TFTP_ERR_UNDEFINED           = 0,
61	TFTP_ERR_FILE_NOT_FOUND      = 1,
62	TFTP_ERR_ACCESS_DENIED       = 2,
63	TFTP_ERR_DISK_FULL           = 3,
64	TFTP_ERR_UNEXPECTED_OPCODE   = 4,
65	TFTP_ERR_UNKNOWN_TRANSFER_ID  = 5,
66	TFTP_ERR_FILE_ALREADY_EXISTS = 6,
67	TFTP_ERR_OPTION_NEGOTIATION = 8,
68};
69
70static struct in_addr tftp_remote_ip;
71/* The UDP port at their end */
72static int	tftp_remote_port;
73/* The UDP port at our end */
74static int	tftp_our_port;
75static int	timeout_count;
76/* packet sequence number */
77static ulong	tftp_cur_block;
78/* last packet sequence number received */
79static ulong	tftp_prev_block;
80/* count of sequence number wraparounds */
81static ulong	tftp_block_wrap;
82/* memory offset due to wrapping */
83static ulong	tftp_block_wrap_offset;
84static int	tftp_state;
85static ulong	tftp_load_addr;
86#ifdef CONFIG_LMB
87static ulong	tftp_load_size;
88#endif
89#ifdef CONFIG_TFTP_TSIZE
90/* The file size reported by the server */
91static int	tftp_tsize;
92/* The number of hashes we printed */
93static short	tftp_tsize_num_hash;
94#endif
95/* The window size negotiated */
96static ushort	tftp_windowsize;
97/* Next block to send ack to */
98static ushort	tftp_next_ack;
99/* Last nack block we send */
100static ushort	tftp_last_nack;
101#ifdef CONFIG_CMD_TFTPPUT
102/* 1 if writing, else 0 */
103static int	tftp_put_active;
104/* 1 if we have sent the last block */
105static int	tftp_put_final_block_sent;
106#else
107#define tftp_put_active	0
108#endif
109
110#define STATE_SEND_RRQ	1
111#define STATE_DATA	2
112#define STATE_TOO_LARGE	3
113#define STATE_BAD_MAGIC	4
114#define STATE_OACK	5
115#define STATE_RECV_WRQ	6
116#define STATE_SEND_WRQ	7
117#define STATE_INVALID_OPTION	8
118
119/* default TFTP block size */
120#define TFTP_BLOCK_SIZE		512
121#define TFTP_MTU_BLOCKSIZE6 (CONFIG_TFTP_BLOCKSIZE - 20)
122/* sequence number is 16 bit */
123#define TFTP_SEQUENCE_SIZE	((ulong)(1<<16))
124
125#define DEFAULT_NAME_LEN	(8 + 4 + 1)
126static char default_filename[DEFAULT_NAME_LEN];
127
128#ifndef CONFIG_TFTP_FILE_NAME_MAX_LEN
129#define MAX_LEN 128
130#else
131#define MAX_LEN CONFIG_TFTP_FILE_NAME_MAX_LEN
132#endif
133
134static char tftp_filename[MAX_LEN];
135
136/* 512 is poor choice for ethernet, MTU is typically 1500.
137 * Minus eth.hdrs thats 1468.  Can get 2x better throughput with
138 * almost-MTU block sizes.  At least try... fall back to 512 if need be.
139 * (but those using CONFIG_IP_DEFRAG may want to set a larger block in cfg file)
140 */
141
142/* When windowsize is defined to 1,
143 * tftp behaves the same way as it was
144 * never declared
145 */
146#ifdef CONFIG_TFTP_WINDOWSIZE
147#define TFTP_WINDOWSIZE CONFIG_TFTP_WINDOWSIZE
148#else
149#define TFTP_WINDOWSIZE 1
150#endif
151
152static unsigned short tftp_block_size = TFTP_BLOCK_SIZE;
153static unsigned short tftp_block_size_option = CONFIG_TFTP_BLOCKSIZE;
154static unsigned short tftp_window_size_option = TFTP_WINDOWSIZE;
155
156static inline int store_block(int block, uchar *src, unsigned int len)
157{
158	ulong offset = block * tftp_block_size + tftp_block_wrap_offset -
159			tftp_block_size;
160	ulong newsize = offset + len;
161	ulong store_addr = tftp_load_addr + offset;
162	void *ptr;
163
164#ifdef CONFIG_LMB
165	ulong end_addr = tftp_load_addr + tftp_load_size;
166
167	if (!end_addr)
168		end_addr = ULONG_MAX;
169
170	if (store_addr < tftp_load_addr ||
171	    store_addr + len > end_addr) {
172		puts("\nTFTP error: ");
173		puts("trying to overwrite reserved memory...\n");
174		return -1;
175	}
176#endif
177	ptr = map_sysmem(store_addr, len);
178	memcpy(ptr, src, len);
179	unmap_sysmem(ptr);
180
181	if (net_boot_file_size < newsize)
182		net_boot_file_size = newsize;
183
184	return 0;
185}
186
187/* Clear our state ready for a new transfer */
188static void new_transfer(void)
189{
190	tftp_prev_block = 0;
191	tftp_block_wrap = 0;
192	tftp_block_wrap_offset = 0;
193#ifdef CONFIG_CMD_TFTPPUT
194	tftp_put_final_block_sent = 0;
195#endif
196}
197
198#ifdef CONFIG_CMD_TFTPPUT
199/**
200 * Load the next block from memory to be sent over tftp.
201 *
202 * @param block	Block number to send
203 * @param dst	Destination buffer for data
204 * @param len	Number of bytes in block (this one and every other)
205 * Return: number of bytes loaded
206 */
207static int load_block(unsigned block, uchar *dst, unsigned len)
208{
209	/* We may want to get the final block from the previous set */
210	ulong offset = block * tftp_block_size + tftp_block_wrap_offset -
211		       tftp_block_size;
212	ulong tosend = len;
213
214	tosend = min(net_boot_file_size - offset, tosend);
215	(void)memcpy(dst, (void *)(image_save_addr + offset), tosend);
216	debug("%s: block=%u, offset=%lu, len=%u, tosend=%lu\n", __func__,
217	      block, offset, len, tosend);
218	return tosend;
219}
220#endif
221
222static void tftp_send(void);
223static void tftp_timeout_handler(void);
224
225/**********************************************************************/
226
227static void show_block_marker(void)
228{
229	ulong pos;
230
231#ifdef CONFIG_TFTP_TSIZE
232	if (tftp_tsize) {
233		pos = tftp_cur_block * tftp_block_size +
234			tftp_block_wrap_offset;
235		if (pos > tftp_tsize)
236			pos = tftp_tsize;
237
238		while (tftp_tsize_num_hash < pos * 50 / tftp_tsize) {
239			putc('#');
240			tftp_tsize_num_hash++;
241		}
242	} else
243#endif
244	{
245		pos = (tftp_cur_block - 1) +
246			(tftp_block_wrap * TFTP_SEQUENCE_SIZE);
247		if ((pos % 10) == 0)
248			putc('#');
249		else if (((pos + 1) % (10 * HASHES_PER_LINE)) == 0)
250			puts("\n\t ");
251	}
252}
253
254/**
255 * restart the current transfer due to an error
256 *
257 * @param msg	Message to print for user
258 */
259static void restart(const char *msg)
260{
261	printf("\n%s; starting again\n", msg);
262	net_start_again();
263}
264
265/*
266 * Check if the block number has wrapped, and update progress
267 *
268 * TODO: The egregious use of global variables in this file should be tidied.
269 */
270static void update_block_number(void)
271{
272	/*
273	 * RFC1350 specifies that the first data packet will
274	 * have sequence number 1. If we receive a sequence
275	 * number of 0 this means that there was a wrap
276	 * around of the (16 bit) counter.
277	 */
278	if (tftp_cur_block == 0 && tftp_prev_block != 0) {
279		tftp_block_wrap++;
280		tftp_block_wrap_offset += tftp_block_size * TFTP_SEQUENCE_SIZE;
281		timeout_count = 0; /* we've done well, reset the timeout */
282	}
283	show_block_marker();
284}
285
286/* The TFTP get or put is complete */
287static void tftp_complete(void)
288{
289#ifdef CONFIG_TFTP_TSIZE
290	/* Print hash marks for the last packet received */
291	while (tftp_tsize && tftp_tsize_num_hash < 49) {
292		putc('#');
293		tftp_tsize_num_hash++;
294	}
295	puts("  ");
296	print_size(tftp_tsize, "");
297#endif
298	time_start = get_timer(time_start);
299	if (time_start > 0) {
300		puts("\n\t ");	/* Line up with "Loading: " */
301		print_size(net_boot_file_size /
302			time_start * 1000, "/s");
303	}
304	puts("\ndone\n");
305	if (!tftp_put_active)
306		efi_set_bootdev("Net", "", tftp_filename,
307				map_sysmem(tftp_load_addr, 0),
308				net_boot_file_size);
309	net_set_state(NETLOOP_SUCCESS);
310}
311
312static void tftp_send(void)
313{
314	uchar *pkt;
315	uchar *xp;
316	int len = 0;
317	ushort *s;
318	bool err_pkt = false;
319
320	/*
321	 *	We will always be sending some sort of packet, so
322	 *	cobble together the packet headers now.
323	 */
324	if (IS_ENABLED(CONFIG_IPV6) && use_ip6)
325		pkt = net_tx_packet + net_eth_hdr_size() +
326		      IP6_HDR_SIZE + UDP_HDR_SIZE;
327	else
328		pkt = net_tx_packet + net_eth_hdr_size() + IP_UDP_HDR_SIZE;
329
330	switch (tftp_state) {
331	case STATE_SEND_RRQ:
332	case STATE_SEND_WRQ:
333		xp = pkt;
334		s = (ushort *)pkt;
335#ifdef CONFIG_CMD_TFTPPUT
336		*s++ = htons(tftp_state == STATE_SEND_RRQ ? TFTP_RRQ :
337			TFTP_WRQ);
338#else
339		*s++ = htons(TFTP_RRQ);
340#endif
341		pkt = (uchar *)s;
342		strcpy((char *)pkt, tftp_filename);
343		pkt += strlen(tftp_filename) + 1;
344		strcpy((char *)pkt, "octet");
345		pkt += 5 /*strlen("octet")*/ + 1;
346		strcpy((char *)pkt, "timeout");
347		pkt += 7 /*strlen("timeout")*/ + 1;
348		sprintf((char *)pkt, "%lu", timeout_ms / 1000);
349		debug("send option \"timeout %s\"\n", (char *)pkt);
350		pkt += strlen((char *)pkt) + 1;
351#ifdef CONFIG_TFTP_TSIZE
352		pkt += sprintf((char *)pkt, "tsize%c%u%c",
353				0, net_boot_file_size, 0);
354#endif
355		/* try for more effic. blk size */
356		pkt += sprintf((char *)pkt, "blksize%c%d%c",
357				0, tftp_block_size_option, 0);
358
359		/* try for more effic. window size.
360		 * Implemented only for tftp get.
361		 * Don't bother sending if it's 1
362		 */
363		if (tftp_state == STATE_SEND_RRQ && tftp_window_size_option > 1)
364			pkt += sprintf((char *)pkt, "windowsize%c%d%c",
365					0, tftp_window_size_option, 0);
366		len = pkt - xp;
367		break;
368
369	case STATE_OACK:
370
371	case STATE_RECV_WRQ:
372	case STATE_DATA:
373		xp = pkt;
374		s = (ushort *)pkt;
375		s[0] = htons(TFTP_ACK);
376		s[1] = htons(tftp_cur_block);
377		pkt = (uchar *)(s + 2);
378#ifdef CONFIG_CMD_TFTPPUT
379		if (tftp_put_active) {
380			int toload = tftp_block_size;
381			int loaded = load_block(tftp_cur_block, pkt, toload);
382
383			s[0] = htons(TFTP_DATA);
384			pkt += loaded;
385			tftp_put_final_block_sent = (loaded < toload);
386		}
387#endif
388		len = pkt - xp;
389		break;
390
391	case STATE_TOO_LARGE:
392		xp = pkt;
393		s = (ushort *)pkt;
394		*s++ = htons(TFTP_ERROR);
395			*s++ = htons(3);
396
397		pkt = (uchar *)s;
398		strcpy((char *)pkt, "File too large");
399		pkt += 14 /*strlen("File too large")*/ + 1;
400		len = pkt - xp;
401		err_pkt = true;
402		break;
403
404	case STATE_BAD_MAGIC:
405		xp = pkt;
406		s = (ushort *)pkt;
407		*s++ = htons(TFTP_ERROR);
408		*s++ = htons(2);
409		pkt = (uchar *)s;
410		strcpy((char *)pkt, "File has bad magic");
411		pkt += 18 /*strlen("File has bad magic")*/ + 1;
412		len = pkt - xp;
413		err_pkt = true;
414		break;
415
416	case STATE_INVALID_OPTION:
417		xp = pkt;
418		s = (ushort *)pkt;
419		*s++ = htons(TFTP_ERROR);
420		*s++ = htons(TFTP_ERR_OPTION_NEGOTIATION);
421		pkt = (uchar *)s;
422		strcpy((char *)pkt, "Option Negotiation Failed");
423		/* strlen("Option Negotiation Failed") + NULL*/
424		pkt += 25 + 1;
425		len = pkt - xp;
426		err_pkt = true;
427		break;
428	}
429
430	if (IS_ENABLED(CONFIG_IPV6) && use_ip6)
431		net_send_udp_packet6(net_server_ethaddr,
432				     &tftp_remote_ip6,
433				     tftp_remote_port,
434				     tftp_our_port, len);
435	else
436		net_send_udp_packet(net_server_ethaddr, tftp_remote_ip,
437				    tftp_remote_port, tftp_our_port, len);
438
439	if (err_pkt)
440		net_set_state(NETLOOP_FAIL);
441}
442
443#ifdef CONFIG_CMD_TFTPPUT
444static void icmp_handler(unsigned type, unsigned code, unsigned dest,
445			 struct in_addr sip, unsigned src, uchar *pkt,
446			 unsigned len)
447{
448	if (type == ICMP_NOT_REACH && code == ICMP_NOT_REACH_PORT) {
449		/* Oh dear the other end has gone away */
450		restart("TFTP server died");
451	}
452}
453#endif
454
455static void tftp_handler(uchar *pkt, unsigned dest, struct in_addr sip,
456			 unsigned src, unsigned len)
457{
458	__be16 proto;
459	__be16 *s;
460	int i;
461	u16 timeout_val_rcvd;
462
463	if (dest != tftp_our_port) {
464			return;
465	}
466	if (tftp_state != STATE_SEND_RRQ && src != tftp_remote_port &&
467	    tftp_state != STATE_RECV_WRQ && tftp_state != STATE_SEND_WRQ)
468		return;
469
470	if (len < 2)
471		return;
472	len -= 2;
473	/* warning: don't use increment (++) in ntohs() macros!! */
474	s = (__be16 *)pkt;
475	proto = *s++;
476	pkt = (uchar *)s;
477	switch (ntohs(proto)) {
478	case TFTP_RRQ:
479		break;
480
481	case TFTP_ACK:
482#ifdef CONFIG_CMD_TFTPPUT
483		if (tftp_put_active) {
484			if (tftp_put_final_block_sent) {
485				tftp_complete();
486			} else {
487				/*
488				 * Move to the next block. We want our block
489				 * count to wrap just like the other end!
490				 */
491				int block = ntohs(*s);
492				int ack_ok = (tftp_cur_block == block);
493
494				tftp_prev_block = tftp_cur_block;
495				tftp_cur_block = (unsigned short)(block + 1);
496				update_block_number();
497				if (ack_ok)
498					tftp_send(); /* Send next data block */
499			}
500		}
501#endif
502		break;
503
504	default:
505		break;
506
507#ifdef CONFIG_CMD_TFTPSRV
508	case TFTP_WRQ:
509		debug("Got WRQ\n");
510		tftp_remote_ip = sip;
511		tftp_remote_port = src;
512		tftp_our_port = 1024 + (get_timer(0) % 3072);
513		new_transfer();
514		tftp_send(); /* Send ACK(0) */
515		break;
516#endif
517
518	case TFTP_OACK:
519		debug("Got OACK: ");
520		for (i = 0; i < len; i++) {
521			if (pkt[i] == '\0')
522				debug(" ");
523			else
524				debug("%c", pkt[i]);
525		}
526		debug("\n");
527		tftp_state = STATE_OACK;
528		tftp_remote_port = src;
529		/*
530		 * Check for 'blksize' option.
531		 * Careful: "i" is signed, "len" is unsigned, thus
532		 * something like "len-8" may give a *huge* number
533		 */
534		for (i = 0; i+8 < len; i++) {
535			if (strcasecmp((char *)pkt + i, "blksize") == 0) {
536				tftp_block_size = (unsigned short)
537					dectoul((char *)pkt + i + 8, NULL);
538				debug("Blocksize oack: %s, %d\n",
539				      (char *)pkt + i + 8, tftp_block_size);
540				if (tftp_block_size > tftp_block_size_option) {
541					printf("Invalid blk size(=%d)\n",
542					       tftp_block_size);
543					tftp_state = STATE_INVALID_OPTION;
544				}
545			}
546			if (strcasecmp((char *)pkt + i, "timeout") == 0) {
547				timeout_val_rcvd = (unsigned short)
548					dectoul((char *)pkt + i + 8, NULL);
549				debug("Timeout oack: %s, %d\n",
550				      (char *)pkt + i + 8, timeout_val_rcvd);
551				if (timeout_val_rcvd != (timeout_ms / 1000)) {
552					printf("Invalid timeout val(=%d s)\n",
553					       timeout_val_rcvd);
554					tftp_state = STATE_INVALID_OPTION;
555				}
556			}
557#ifdef CONFIG_TFTP_TSIZE
558			if (strcasecmp((char *)pkt + i, "tsize") == 0) {
559				tftp_tsize = dectoul((char *)pkt + i + 6,
560						     NULL);
561				debug("size = %s, %d\n",
562				      (char *)pkt + i + 6, tftp_tsize);
563			}
564#endif
565			if (strcasecmp((char *)pkt + i,  "windowsize") == 0) {
566				tftp_windowsize =
567					dectoul((char *)pkt + i + 11, NULL);
568				debug("windowsize = %s, %d\n",
569				      (char *)pkt + i + 11, tftp_windowsize);
570			}
571		}
572
573		tftp_next_ack = tftp_windowsize;
574
575#ifdef CONFIG_CMD_TFTPPUT
576		if (tftp_put_active && tftp_state == STATE_OACK) {
577			/* Get ready to send the first block */
578			tftp_state = STATE_DATA;
579			tftp_cur_block++;
580		}
581#endif
582		tftp_send(); /* Send ACK or first data block */
583		break;
584	case TFTP_DATA:
585		if (len < 2)
586			return;
587		len -= 2;
588
589		if (ntohs(*(__be16 *)pkt) != (ushort)(tftp_cur_block + 1)) {
590			debug("Received unexpected block: %d, expected: %d\n",
591			      ntohs(*(__be16 *)pkt),
592			      (ushort)(tftp_cur_block + 1));
593			/*
594			 * Only ACK if the block count received is greater than
595			 * the expected block count, otherwise skip ACK.
596			 * (required to properly handle the server retransmitting
597			 *  the window)
598			 */
599			if ((ushort)(tftp_cur_block + 1) - (short)(ntohs(*(__be16 *)pkt)) > 0)
600				break;
601			/*
602			 * If one packet is dropped most likely
603			 * all other buffers in the window
604			 * that will arrive will cause a sending NACK.
605			 * This just overwellms the server, let's just send one.
606			 */
607			if (tftp_last_nack != tftp_cur_block) {
608				tftp_send();
609				tftp_last_nack = tftp_cur_block;
610				tftp_next_ack = (ushort)(tftp_cur_block +
611							 tftp_windowsize);
612			}
613			break;
614		}
615
616		tftp_cur_block++;
617		tftp_cur_block %= TFTP_SEQUENCE_SIZE;
618
619		if (tftp_state == STATE_SEND_RRQ) {
620			debug("Server did not acknowledge any options!\n");
621			tftp_next_ack = tftp_windowsize;
622		}
623
624		if (tftp_state == STATE_SEND_RRQ || tftp_state == STATE_OACK ||
625		    tftp_state == STATE_RECV_WRQ) {
626			/* first block received */
627			tftp_state = STATE_DATA;
628			tftp_remote_port = src;
629			new_transfer();
630
631			if (tftp_cur_block != 1) {	/* Assertion */
632				puts("\nTFTP error: ");
633				printf("First block is not block 1 (%ld)\n",
634				       tftp_cur_block);
635				puts("Starting again\n\n");
636				net_start_again();
637				break;
638			}
639		}
640
641		if (tftp_cur_block == tftp_prev_block) {
642			/* Same block again; ignore it. */
643			break;
644		}
645
646		update_block_number();
647		tftp_prev_block = tftp_cur_block;
648		timeout_count_max = tftp_timeout_count_max;
649		net_set_timeout_handler(timeout_ms, tftp_timeout_handler);
650
651		if (store_block(tftp_cur_block, pkt + 2, len)) {
652			eth_halt();
653			net_set_state(NETLOOP_FAIL);
654			break;
655		}
656
657		if (len < tftp_block_size) {
658			tftp_send();
659			tftp_complete();
660			break;
661		}
662
663		/*
664		 *	Acknowledge the block just received, which will prompt
665		 *	the remote for the next one.
666		 */
667		if (tftp_cur_block == tftp_next_ack) {
668			tftp_send();
669			tftp_next_ack += tftp_windowsize;
670		}
671		break;
672
673	case TFTP_ERROR:
674		printf("\nTFTP error: '%s' (%d)\n",
675		       pkt + 2, ntohs(*(__be16 *)pkt));
676
677		switch (ntohs(*(__be16 *)pkt)) {
678		case TFTP_ERR_FILE_NOT_FOUND:
679		case TFTP_ERR_ACCESS_DENIED:
680			puts("Not retrying...\n");
681			eth_halt();
682			net_set_state(NETLOOP_FAIL);
683			break;
684		case TFTP_ERR_UNDEFINED:
685		case TFTP_ERR_DISK_FULL:
686		case TFTP_ERR_UNEXPECTED_OPCODE:
687		case TFTP_ERR_UNKNOWN_TRANSFER_ID:
688		case TFTP_ERR_FILE_ALREADY_EXISTS:
689		default:
690			puts("Starting again\n\n");
691			net_start_again();
692			break;
693		}
694		break;
695	}
696}
697
698
699static void tftp_timeout_handler(void)
700{
701	if (++timeout_count > timeout_count_max) {
702		restart("Retry count exceeded");
703	} else {
704		puts("T ");
705		net_set_timeout_handler(timeout_ms, tftp_timeout_handler);
706		if (tftp_state != STATE_RECV_WRQ)
707			tftp_send();
708	}
709}
710
711/* Initialize tftp_load_addr and tftp_load_size from image_load_addr and lmb */
712static int tftp_init_load_addr(void)
713{
714#ifdef CONFIG_LMB
715	struct lmb lmb;
716	phys_size_t max_size;
717
718	lmb_init_and_reserve(&lmb, gd->bd, (void *)gd->fdt_blob);
719
720	max_size = lmb_get_free_size(&lmb, image_load_addr);
721	if (!max_size)
722		return -1;
723
724	tftp_load_size = max_size;
725#endif
726	tftp_load_addr = image_load_addr;
727	return 0;
728}
729
730static int saved_tftp_block_size_option;
731static void sanitize_tftp_block_size_option(enum proto_t protocol)
732{
733	int cap, max_defrag;
734
735	switch (protocol) {
736	case TFTPGET:
737		max_defrag = config_opt_enabled(CONFIG_IP_DEFRAG, CONFIG_NET_MAXDEFRAG, 0);
738		if (max_defrag) {
739			/* Account for IP, UDP and TFTP headers. */
740			cap = max_defrag - (20 + 8 + 4);
741			/* RFC2348 sets a hard upper limit. */
742			cap = min(cap, 65464);
743			break;
744		}
745		/*
746		 * If not CONFIG_IP_DEFRAG, cap at the same value as
747		 * for tftp put, namely normal MTU minus protocol
748		 * overhead.
749		 */
750		fallthrough;
751	case TFTPPUT:
752	default:
753		/*
754		 * U-Boot does not support IP fragmentation on TX, so
755		 * this must be small enough that it fits normal MTU
756		 * (and small enough that it fits net_tx_packet which
757		 * has room for PKTSIZE_ALIGN bytes).
758		 */
759		cap = 1468;
760	}
761	if (tftp_block_size_option > cap) {
762		printf("Capping tftp block size option to %d (was %d)\n",
763		       cap, tftp_block_size_option);
764		saved_tftp_block_size_option = tftp_block_size_option;
765		tftp_block_size_option = cap;
766	}
767}
768
769void tftp_start(enum proto_t protocol)
770{
771	__maybe_unused char *ep;             /* Environment pointer */
772
773	if (saved_tftp_block_size_option) {
774		tftp_block_size_option = saved_tftp_block_size_option;
775		saved_tftp_block_size_option = 0;
776	}
777
778	if (IS_ENABLED(CONFIG_NET_TFTP_VARS)) {
779
780		/*
781		 * Allow the user to choose TFTP blocksize and timeout.
782		 * TFTP protocol has a minimal timeout of 1 second.
783		 */
784
785		ep = env_get("tftpblocksize");
786		if (ep != NULL)
787			tftp_block_size_option = simple_strtol(ep, NULL, 10);
788
789		ep = env_get("tftpwindowsize");
790		if (ep != NULL)
791			tftp_window_size_option = simple_strtol(ep, NULL, 10);
792
793		ep = env_get("tftptimeout");
794		if (ep != NULL)
795			timeout_ms = simple_strtol(ep, NULL, 10);
796
797		if (timeout_ms < 1000) {
798			printf("TFTP timeout (%ld ms) too low, set min = 1000 ms\n",
799			       timeout_ms);
800			timeout_ms = 1000;
801		}
802
803		ep = env_get("tftptimeoutcountmax");
804		if (ep != NULL)
805			tftp_timeout_count_max = simple_strtol(ep, NULL, 10);
806
807		if (tftp_timeout_count_max < 0) {
808			printf("TFTP timeout count max (%d ms) negative, set to 0\n",
809			       tftp_timeout_count_max);
810			tftp_timeout_count_max = 0;
811		}
812	}
813
814	sanitize_tftp_block_size_option(protocol);
815
816	debug("TFTP blocksize = %i, TFTP windowsize = %d timeout = %ld ms\n",
817	      tftp_block_size_option, tftp_window_size_option, timeout_ms);
818
819	if (IS_ENABLED(CONFIG_IPV6))
820		tftp_remote_ip6 = net_server_ip6;
821
822	tftp_remote_ip = net_server_ip;
823	if (!net_parse_bootfile(&tftp_remote_ip, tftp_filename, MAX_LEN)) {
824		sprintf(default_filename, "%02X%02X%02X%02X.img",
825			net_ip.s_addr & 0xFF,
826			(net_ip.s_addr >>  8) & 0xFF,
827			(net_ip.s_addr >> 16) & 0xFF,
828			(net_ip.s_addr >> 24) & 0xFF);
829
830		strncpy(tftp_filename, default_filename, DEFAULT_NAME_LEN);
831		tftp_filename[DEFAULT_NAME_LEN - 1] = 0;
832
833		printf("*** Warning: no boot file name; using '%s'\n",
834		       tftp_filename);
835	}
836
837	if (IS_ENABLED(CONFIG_IPV6)) {
838		if (use_ip6) {
839			char *s, *e;
840			size_t len;
841
842			s = strchr(net_boot_file_name, '[');
843			e = strchr(net_boot_file_name, ']');
844			len = e - s;
845			if (s && e) {
846				string_to_ip6(s + 1, len - 1, &tftp_remote_ip6);
847				strlcpy(tftp_filename, e + 2, MAX_LEN);
848			} else {
849				strlcpy(tftp_filename, net_boot_file_name, MAX_LEN);
850				tftp_filename[MAX_LEN - 1] = 0;
851			}
852		}
853	}
854
855	printf("Using %s device\n", eth_get_name());
856
857	if (IS_ENABLED(CONFIG_IPV6) && use_ip6) {
858		printf("TFTP from server %pI6c; our IP address is %pI6c",
859		       &tftp_remote_ip6, &net_ip6);
860
861		if (tftp_block_size_option > TFTP_MTU_BLOCKSIZE6)
862			tftp_block_size_option = TFTP_MTU_BLOCKSIZE6;
863	} else {
864		printf("TFTP %s server %pI4; our IP address is %pI4",
865#ifdef CONFIG_CMD_TFTPPUT
866	       protocol == TFTPPUT ? "to" : "from",
867#else
868	       "from",
869#endif
870	       &tftp_remote_ip, &net_ip);
871	}
872
873	/* Check if we need to send across this subnet */
874	if (IS_ENABLED(CONFIG_IPV6) && use_ip6) {
875		if (!ip6_addr_in_subnet(&net_ip6, &tftp_remote_ip6,
876					net_prefix_length))
877			printf("; sending through gateway %pI6c",
878			       &net_gateway6);
879	} else if (net_gateway.s_addr && net_netmask.s_addr) {
880		struct in_addr our_net;
881		struct in_addr remote_net;
882
883		our_net.s_addr = net_ip.s_addr & net_netmask.s_addr;
884		remote_net.s_addr = tftp_remote_ip.s_addr & net_netmask.s_addr;
885		if (our_net.s_addr != remote_net.s_addr)
886			printf("; sending through gateway %pI4", &net_gateway);
887	}
888	putc('\n');
889
890	printf("Filename '%s'.", tftp_filename);
891
892	if (net_boot_file_expected_size_in_blocks) {
893		printf(" Size is 0x%x Bytes = ",
894		       net_boot_file_expected_size_in_blocks << 9);
895		print_size(net_boot_file_expected_size_in_blocks << 9, "");
896	}
897
898	putc('\n');
899#ifdef CONFIG_CMD_TFTPPUT
900	tftp_put_active = (protocol == TFTPPUT);
901	if (tftp_put_active) {
902		printf("Save address: 0x%lx\n", image_save_addr);
903		printf("Save size:    0x%lx\n", image_save_size);
904		net_boot_file_size = image_save_size;
905		puts("Saving: *\b");
906		tftp_state = STATE_SEND_WRQ;
907		new_transfer();
908	} else
909#endif
910	{
911		if (tftp_init_load_addr()) {
912			eth_halt();
913			net_set_state(NETLOOP_FAIL);
914			puts("\nTFTP error: ");
915			puts("trying to overwrite reserved memory...\n");
916			return;
917		}
918		printf("Load address: 0x%lx\n", tftp_load_addr);
919		puts("Loading: *\b");
920		tftp_state = STATE_SEND_RRQ;
921	}
922
923	time_start = get_timer(0);
924	timeout_count_max = tftp_timeout_count_max;
925
926	net_set_timeout_handler(timeout_ms, tftp_timeout_handler);
927	net_set_udp_handler(tftp_handler);
928#ifdef CONFIG_CMD_TFTPPUT
929	net_set_icmp_handler(icmp_handler);
930#endif
931	tftp_remote_port = WELL_KNOWN_PORT;
932	timeout_count = 0;
933	/* Use a pseudo-random port unless a specific port is set */
934	tftp_our_port = 1024 + (get_timer(0) % 3072);
935
936#ifdef CONFIG_TFTP_PORT
937	ep = env_get("tftpdstp");
938	if (ep != NULL)
939		tftp_remote_port = simple_strtol(ep, NULL, 10);
940	ep = env_get("tftpsrcp");
941	if (ep != NULL)
942		tftp_our_port = simple_strtol(ep, NULL, 10);
943#endif
944	tftp_cur_block = 0;
945	tftp_windowsize = 1;
946	tftp_last_nack = 0;
947	/* zero out server ether in case the server ip has changed */
948	memset(net_server_ethaddr, 0, 6);
949	/* Revert tftp_block_size to dflt */
950	tftp_block_size = TFTP_BLOCK_SIZE;
951#ifdef CONFIG_TFTP_TSIZE
952	tftp_tsize = 0;
953	tftp_tsize_num_hash = 0;
954#endif
955
956	tftp_send();
957}
958
959#ifdef CONFIG_CMD_TFTPSRV
960void tftp_start_server(void)
961{
962	tftp_filename[0] = 0;
963
964	if (tftp_init_load_addr()) {
965		eth_halt();
966		net_set_state(NETLOOP_FAIL);
967		puts("\nTFTP error: trying to overwrite reserved memory...\n");
968		return;
969	}
970	printf("Using %s device\n", eth_get_name());
971	printf("Listening for TFTP transfer on %pI4\n", &net_ip);
972	printf("Load address: 0x%lx\n", tftp_load_addr);
973
974	puts("Loading: *\b");
975
976	timeout_count_max = tftp_timeout_count_max;
977	timeout_count = 0;
978	timeout_ms = TIMEOUT;
979	net_set_timeout_handler(timeout_ms, tftp_timeout_handler);
980
981	/* Revert tftp_block_size to dflt */
982	tftp_block_size = TFTP_BLOCK_SIZE;
983	tftp_cur_block = 0;
984	tftp_our_port = WELL_KNOWN_PORT;
985	tftp_windowsize = 1;
986	tftp_next_ack = tftp_windowsize;
987
988#ifdef CONFIG_TFTP_TSIZE
989	tftp_tsize = 0;
990	tftp_tsize_num_hash = 0;
991#endif
992
993	tftp_state = STATE_RECV_WRQ;
994	net_set_udp_handler(tftp_handler);
995
996	/* zero out server ether in case the server ip has changed */
997	memset(net_server_ethaddr, 0, 6);
998}
999#endif /* CONFIG_CMD_TFTPSRV */
1000