2 * Copyright 1994, 1995, 2000 Neil Russell.
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>
11 #include <efi_loader.h>
18 #ifdef CONFIG_SYS_DIRECT_FLASH_TFTP
22 DECLARE_GLOBAL_DATA_PTR;
24 /* Well known TFTP port # */
25 #define WELL_KNOWN_PORT 69
26 /* Millisecs to timeout for lost pkt */
27 #define TIMEOUT 5000UL
28 #ifndef CONFIG_NET_RETRY_COUNT
29 /* # of timeouts before giving up */
30 # define TIMEOUT_COUNT 10
32 # define TIMEOUT_COUNT (CONFIG_NET_RETRY_COUNT * 2)
34 /* Number of "loading" hashes per line (for checking the image size) */
35 #define HASHES_PER_LINE 65
47 static ulong timeout_ms = TIMEOUT;
48 static int timeout_count_max = TIMEOUT_COUNT;
49 static ulong time_start; /* Record time we started tftp */
52 * These globals govern the timeout behavior when attempting a connection to a
53 * TFTP server. tftp_timeout_ms specifies the number of milliseconds to
54 * wait for the server to respond to initial connection. Second global,
55 * tftp_timeout_count_max, gives the number of such connection retries.
56 * tftp_timeout_count_max must be non-negative and tftp_timeout_ms must be
57 * positive. The globals are meant to be set (and restored) by code needing
58 * non-standard timeout behavior when initiating a TFTP transfer.
60 ulong tftp_timeout_ms = TIMEOUT;
61 int tftp_timeout_count_max = TIMEOUT_COUNT;
64 TFTP_ERR_UNDEFINED = 0,
65 TFTP_ERR_FILE_NOT_FOUND = 1,
66 TFTP_ERR_ACCESS_DENIED = 2,
67 TFTP_ERR_DISK_FULL = 3,
68 TFTP_ERR_UNEXPECTED_OPCODE = 4,
69 TFTP_ERR_UNKNOWN_TRANSFER_ID = 5,
70 TFTP_ERR_FILE_ALREADY_EXISTS = 6,
73 static struct in_addr tftp_remote_ip;
74 /* The UDP port at their end */
75 static int tftp_remote_port;
76 /* The UDP port at our end */
77 static int tftp_our_port;
78 static int timeout_count;
79 /* packet sequence number */
80 static ulong tftp_cur_block;
81 /* last packet sequence number received */
82 static ulong tftp_prev_block;
83 /* count of sequence number wraparounds */
84 static ulong tftp_block_wrap;
85 /* memory offset due to wrapping */
86 static ulong tftp_block_wrap_offset;
87 static int tftp_state;
88 static ulong tftp_load_addr;
90 static ulong tftp_load_size;
92 #ifdef CONFIG_TFTP_TSIZE
93 /* The file size reported by the server */
94 static int tftp_tsize;
95 /* The number of hashes we printed */
96 static short tftp_tsize_num_hash;
98 #ifdef CONFIG_CMD_TFTPPUT
99 /* 1 if writing, else 0 */
100 static int tftp_put_active;
101 /* 1 if we have sent the last block */
102 static int tftp_put_final_block_sent;
104 #define tftp_put_active 0
107 #define STATE_SEND_RRQ 1
109 #define STATE_TOO_LARGE 3
110 #define STATE_BAD_MAGIC 4
112 #define STATE_RECV_WRQ 6
113 #define STATE_SEND_WRQ 7
115 /* default TFTP block size */
116 #define TFTP_BLOCK_SIZE 512
117 /* sequence number is 16 bit */
118 #define TFTP_SEQUENCE_SIZE ((ulong)(1<<16))
120 #define DEFAULT_NAME_LEN (8 + 4 + 1)
121 static char default_filename[DEFAULT_NAME_LEN];
123 #ifndef CONFIG_TFTP_FILE_NAME_MAX_LEN
126 #define MAX_LEN CONFIG_TFTP_FILE_NAME_MAX_LEN
129 static char tftp_filename[MAX_LEN];
131 /* 512 is poor choice for ethernet, MTU is typically 1500.
132 * Minus eth.hdrs thats 1468. Can get 2x better throughput with
133 * almost-MTU block sizes. At least try... fall back to 512 if need be.
134 * (but those using CONFIG_IP_DEFRAG may want to set a larger block in cfg file)
137 static unsigned short tftp_block_size = TFTP_BLOCK_SIZE;
138 static unsigned short tftp_block_size_option = CONFIG_TFTP_BLOCKSIZE;
140 static inline int store_block(int block, uchar *src, unsigned int len)
142 ulong offset = block * tftp_block_size + tftp_block_wrap_offset;
143 ulong newsize = offset + len;
144 ulong store_addr = tftp_load_addr + offset;
145 #ifdef CONFIG_SYS_DIRECT_FLASH_TFTP
148 for (i = 0; i < CONFIG_SYS_MAX_FLASH_BANKS; i++) {
149 /* start address in flash? */
150 if (flash_info[i].flash_id == FLASH_UNKNOWN)
152 if (store_addr >= flash_info[i].start[0]) {
158 if (rc) { /* Flash is destination for this packet */
159 rc = flash_write((char *)src, store_addr, len);
165 #endif /* CONFIG_SYS_DIRECT_FLASH_TFTP */
170 ulong end_addr = tftp_load_addr + tftp_load_size;
173 end_addr = ULONG_MAX;
175 if (store_addr < tftp_load_addr ||
176 store_addr + len > end_addr) {
177 puts("\nTFTP error: ");
178 puts("trying to overwrite reserved memory...\n");
182 ptr = map_sysmem(store_addr, len);
183 memcpy(ptr, src, len);
187 if (net_boot_file_size < newsize)
188 net_boot_file_size = newsize;
193 /* Clear our state ready for a new transfer */
194 static void new_transfer(void)
198 tftp_block_wrap_offset = 0;
199 #ifdef CONFIG_CMD_TFTPPUT
200 tftp_put_final_block_sent = 0;
204 #ifdef CONFIG_CMD_TFTPPUT
206 * Load the next block from memory to be sent over tftp.
208 * @param block Block number to send
209 * @param dst Destination buffer for data
210 * @param len Number of bytes in block (this one and every other)
211 * @return number of bytes loaded
213 static int load_block(unsigned block, uchar *dst, unsigned len)
215 /* We may want to get the final block from the previous set */
216 ulong offset = ((int)block - 1) * len + tftp_block_wrap_offset;
219 tosend = min(net_boot_file_size - offset, tosend);
220 (void)memcpy(dst, (void *)(image_save_addr + offset), tosend);
221 debug("%s: block=%u, offset=%lu, len=%u, tosend=%lu\n", __func__,
222 block, offset, len, tosend);
227 static void tftp_send(void);
228 static void tftp_timeout_handler(void);
230 /**********************************************************************/
232 static void show_block_marker(void)
234 #ifdef CONFIG_TFTP_TSIZE
236 ulong pos = tftp_cur_block * tftp_block_size +
237 tftp_block_wrap_offset;
238 if (pos > tftp_tsize)
241 while (tftp_tsize_num_hash < pos * 50 / tftp_tsize) {
243 tftp_tsize_num_hash++;
248 if (((tftp_cur_block - 1) % 10) == 0)
250 else if ((tftp_cur_block % (10 * HASHES_PER_LINE)) == 0)
256 * restart the current transfer due to an error
258 * @param msg Message to print for user
260 static void restart(const char *msg)
262 printf("\n%s; starting again\n", msg);
267 * Check if the block number has wrapped, and update progress
269 * TODO: The egregious use of global variables in this file should be tidied.
271 static void update_block_number(void)
274 * RFC1350 specifies that the first data packet will
275 * have sequence number 1. If we receive a sequence
276 * number of 0 this means that there was a wrap
277 * around of the (16 bit) counter.
279 if (tftp_cur_block == 0 && tftp_prev_block != 0) {
281 tftp_block_wrap_offset += tftp_block_size * TFTP_SEQUENCE_SIZE;
282 timeout_count = 0; /* we've done well, reset the timeout */
288 /* The TFTP get or put is complete */
289 static void tftp_complete(void)
291 #ifdef CONFIG_TFTP_TSIZE
292 /* Print hash marks for the last packet received */
293 while (tftp_tsize && tftp_tsize_num_hash < 49) {
295 tftp_tsize_num_hash++;
298 print_size(tftp_tsize, "");
300 time_start = get_timer(time_start);
301 if (time_start > 0) {
302 puts("\n\t "); /* Line up with "Loading: " */
303 print_size(net_boot_file_size /
304 time_start * 1000, "/s");
307 net_set_state(NETLOOP_SUCCESS);
310 static void tftp_send(void)
318 * We will always be sending some sort of packet, so
319 * cobble together the packet headers now.
321 pkt = net_tx_packet + net_eth_hdr_size() + IP_UDP_HDR_SIZE;
323 switch (tftp_state) {
328 #ifdef CONFIG_CMD_TFTPPUT
329 *s++ = htons(tftp_state == STATE_SEND_RRQ ? TFTP_RRQ :
332 *s++ = htons(TFTP_RRQ);
335 strcpy((char *)pkt, tftp_filename);
336 pkt += strlen(tftp_filename) + 1;
337 strcpy((char *)pkt, "octet");
338 pkt += 5 /*strlen("octet")*/ + 1;
339 strcpy((char *)pkt, "timeout");
340 pkt += 7 /*strlen("timeout")*/ + 1;
341 sprintf((char *)pkt, "%lu", timeout_ms / 1000);
342 debug("send option \"timeout %s\"\n", (char *)pkt);
343 pkt += strlen((char *)pkt) + 1;
344 #ifdef CONFIG_TFTP_TSIZE
345 pkt += sprintf((char *)pkt, "tsize%c%u%c",
346 0, net_boot_file_size, 0);
348 /* try for more effic. blk size */
349 pkt += sprintf((char *)pkt, "blksize%c%d%c",
350 0, tftp_block_size_option, 0);
360 s[0] = htons(TFTP_ACK);
361 s[1] = htons(tftp_cur_block);
362 pkt = (uchar *)(s + 2);
363 #ifdef CONFIG_CMD_TFTPPUT
364 if (tftp_put_active) {
365 int toload = tftp_block_size;
366 int loaded = load_block(tftp_cur_block, pkt, toload);
368 s[0] = htons(TFTP_DATA);
370 tftp_put_final_block_sent = (loaded < toload);
376 case STATE_TOO_LARGE:
379 *s++ = htons(TFTP_ERROR);
383 strcpy((char *)pkt, "File too large");
384 pkt += 14 /*strlen("File too large")*/ + 1;
388 case STATE_BAD_MAGIC:
391 *s++ = htons(TFTP_ERROR);
394 strcpy((char *)pkt, "File has bad magic");
395 pkt += 18 /*strlen("File has bad magic")*/ + 1;
400 net_send_udp_packet(net_server_ethaddr, tftp_remote_ip,
401 tftp_remote_port, tftp_our_port, len);
404 #ifdef CONFIG_CMD_TFTPPUT
405 static void icmp_handler(unsigned type, unsigned code, unsigned dest,
406 struct in_addr sip, unsigned src, uchar *pkt,
409 if (type == ICMP_NOT_REACH && code == ICMP_NOT_REACH_PORT) {
410 /* Oh dear the other end has gone away */
411 restart("TFTP server died");
416 static void tftp_handler(uchar *pkt, unsigned dest, struct in_addr sip,
417 unsigned src, unsigned len)
423 if (dest != tftp_our_port) {
426 if (tftp_state != STATE_SEND_RRQ && src != tftp_remote_port &&
427 tftp_state != STATE_RECV_WRQ && tftp_state != STATE_SEND_WRQ)
433 /* warning: don't use increment (++) in ntohs() macros!! */
437 switch (ntohs(proto)) {
442 #ifdef CONFIG_CMD_TFTPPUT
443 if (tftp_put_active) {
444 if (tftp_put_final_block_sent) {
448 * Move to the next block. We want our block
449 * count to wrap just like the other end!
451 int block = ntohs(*s);
452 int ack_ok = (tftp_cur_block == block);
454 tftp_cur_block = (unsigned short)(block + 1);
455 update_block_number();
457 tftp_send(); /* Send next data block */
466 #ifdef CONFIG_CMD_TFTPSRV
469 tftp_remote_ip = sip;
470 tftp_remote_port = src;
471 tftp_our_port = 1024 + (get_timer(0) % 3072);
473 tftp_send(); /* Send ACK(0) */
478 debug("Got OACK: %s %s\n",
479 pkt, pkt + strlen((char *)pkt) + 1);
480 tftp_state = STATE_OACK;
481 tftp_remote_port = src;
483 * Check for 'blksize' option.
484 * Careful: "i" is signed, "len" is unsigned, thus
485 * something like "len-8" may give a *huge* number
487 for (i = 0; i+8 < len; i++) {
488 if (strcmp((char *)pkt + i, "blksize") == 0) {
489 tftp_block_size = (unsigned short)
490 simple_strtoul((char *)pkt + i + 8,
492 debug("Blocksize ack: %s, %d\n",
493 (char *)pkt + i + 8, tftp_block_size);
495 #ifdef CONFIG_TFTP_TSIZE
496 if (strcmp((char *)pkt+i, "tsize") == 0) {
497 tftp_tsize = simple_strtoul((char *)pkt + i + 6,
499 debug("size = %s, %d\n",
500 (char *)pkt + i + 6, tftp_tsize);
504 #ifdef CONFIG_CMD_TFTPPUT
505 if (tftp_put_active) {
506 /* Get ready to send the first block */
507 tftp_state = STATE_DATA;
511 tftp_send(); /* Send ACK or first data block */
517 tftp_cur_block = ntohs(*(__be16 *)pkt);
519 update_block_number();
521 if (tftp_state == STATE_SEND_RRQ)
522 debug("Server did not acknowledge timeout option!\n");
524 if (tftp_state == STATE_SEND_RRQ || tftp_state == STATE_OACK ||
525 tftp_state == STATE_RECV_WRQ) {
526 /* first block received */
527 tftp_state = STATE_DATA;
528 tftp_remote_port = src;
531 if (tftp_cur_block != 1) { /* Assertion */
532 puts("\nTFTP error: ");
533 printf("First block is not block 1 (%ld)\n",
535 puts("Starting again\n\n");
541 if (tftp_cur_block == tftp_prev_block) {
542 /* Same block again; ignore it. */
546 tftp_prev_block = tftp_cur_block;
547 timeout_count_max = tftp_timeout_count_max;
548 net_set_timeout_handler(timeout_ms, tftp_timeout_handler);
550 if (store_block(tftp_cur_block - 1, pkt + 2, len)) {
552 net_set_state(NETLOOP_FAIL);
557 * Acknowledge the block just received, which will prompt
558 * the remote for the next one.
562 if (len < tftp_block_size)
567 printf("\nTFTP error: '%s' (%d)\n",
568 pkt + 2, ntohs(*(__be16 *)pkt));
570 switch (ntohs(*(__be16 *)pkt)) {
571 case TFTP_ERR_FILE_NOT_FOUND:
572 case TFTP_ERR_ACCESS_DENIED:
573 puts("Not retrying...\n");
575 net_set_state(NETLOOP_FAIL);
577 case TFTP_ERR_UNDEFINED:
578 case TFTP_ERR_DISK_FULL:
579 case TFTP_ERR_UNEXPECTED_OPCODE:
580 case TFTP_ERR_UNKNOWN_TRANSFER_ID:
581 case TFTP_ERR_FILE_ALREADY_EXISTS:
583 puts("Starting again\n\n");
592 static void tftp_timeout_handler(void)
594 if (++timeout_count > timeout_count_max) {
595 restart("Retry count exceeded");
598 net_set_timeout_handler(timeout_ms, tftp_timeout_handler);
599 if (tftp_state != STATE_RECV_WRQ)
604 /* Initialize tftp_load_addr and tftp_load_size from image_load_addr and lmb */
605 static int tftp_init_load_addr(void)
609 phys_size_t max_size;
611 lmb_init_and_reserve(&lmb, gd->bd, (void *)gd->fdt_blob);
613 max_size = lmb_get_free_size(&lmb, image_load_addr);
617 tftp_load_size = max_size;
619 tftp_load_addr = image_load_addr;
623 void tftp_start(enum proto_t protocol)
625 #if CONFIG_NET_TFTP_VARS
626 char *ep; /* Environment pointer */
629 * Allow the user to choose TFTP blocksize and timeout.
630 * TFTP protocol has a minimal timeout of 1 second.
633 ep = env_get("tftpblocksize");
635 tftp_block_size_option = simple_strtol(ep, NULL, 10);
637 ep = env_get("tftptimeout");
639 timeout_ms = simple_strtol(ep, NULL, 10);
641 if (timeout_ms < 1000) {
642 printf("TFTP timeout (%ld ms) too low, set min = 1000 ms\n",
647 ep = env_get("tftptimeoutcountmax");
649 tftp_timeout_count_max = simple_strtol(ep, NULL, 10);
651 if (tftp_timeout_count_max < 0) {
652 printf("TFTP timeout count max (%d ms) negative, set to 0\n",
653 tftp_timeout_count_max);
654 tftp_timeout_count_max = 0;
658 debug("TFTP blocksize = %i, timeout = %ld ms\n",
659 tftp_block_size_option, timeout_ms);
661 tftp_remote_ip = net_server_ip;
662 if (!net_parse_bootfile(&tftp_remote_ip, tftp_filename, MAX_LEN)) {
663 sprintf(default_filename, "%02X%02X%02X%02X.img",
664 net_ip.s_addr & 0xFF,
665 (net_ip.s_addr >> 8) & 0xFF,
666 (net_ip.s_addr >> 16) & 0xFF,
667 (net_ip.s_addr >> 24) & 0xFF);
669 strncpy(tftp_filename, default_filename, DEFAULT_NAME_LEN);
670 tftp_filename[DEFAULT_NAME_LEN - 1] = 0;
672 printf("*** Warning: no boot file name; using '%s'\n",
676 printf("Using %s device\n", eth_get_name());
677 printf("TFTP %s server %pI4; our IP address is %pI4",
678 #ifdef CONFIG_CMD_TFTPPUT
679 protocol == TFTPPUT ? "to" : "from",
683 &tftp_remote_ip, &net_ip);
685 /* Check if we need to send across this subnet */
686 if (net_gateway.s_addr && net_netmask.s_addr) {
687 struct in_addr our_net;
688 struct in_addr remote_net;
690 our_net.s_addr = net_ip.s_addr & net_netmask.s_addr;
691 remote_net.s_addr = tftp_remote_ip.s_addr & net_netmask.s_addr;
692 if (our_net.s_addr != remote_net.s_addr)
693 printf("; sending through gateway %pI4", &net_gateway);
697 printf("Filename '%s'.", tftp_filename);
699 if (net_boot_file_expected_size_in_blocks) {
700 printf(" Size is 0x%x Bytes = ",
701 net_boot_file_expected_size_in_blocks << 9);
702 print_size(net_boot_file_expected_size_in_blocks << 9, "");
706 #ifdef CONFIG_CMD_TFTPPUT
707 tftp_put_active = (protocol == TFTPPUT);
708 if (tftp_put_active) {
709 printf("Save address: 0x%lx\n", image_save_addr);
710 printf("Save size: 0x%lx\n", image_save_size);
711 net_boot_file_size = image_save_size;
713 tftp_state = STATE_SEND_WRQ;
718 if (tftp_init_load_addr()) {
720 net_set_state(NETLOOP_FAIL);
721 puts("\nTFTP error: ");
722 puts("trying to overwrite reserved memory...\n");
725 printf("Load address: 0x%lx\n", tftp_load_addr);
726 puts("Loading: *\b");
727 tftp_state = STATE_SEND_RRQ;
728 #ifdef CONFIG_CMD_BOOTEFI
729 efi_set_bootdev("Net", "", tftp_filename);
733 time_start = get_timer(0);
734 timeout_count_max = tftp_timeout_count_max;
736 net_set_timeout_handler(timeout_ms, tftp_timeout_handler);
737 net_set_udp_handler(tftp_handler);
738 #ifdef CONFIG_CMD_TFTPPUT
739 net_set_icmp_handler(icmp_handler);
741 tftp_remote_port = WELL_KNOWN_PORT;
743 /* Use a pseudo-random port unless a specific port is set */
744 tftp_our_port = 1024 + (get_timer(0) % 3072);
746 #ifdef CONFIG_TFTP_PORT
747 ep = env_get("tftpdstp");
749 tftp_remote_port = simple_strtol(ep, NULL, 10);
750 ep = env_get("tftpsrcp");
752 tftp_our_port = simple_strtol(ep, NULL, 10);
756 /* zero out server ether in case the server ip has changed */
757 memset(net_server_ethaddr, 0, 6);
758 /* Revert tftp_block_size to dflt */
759 tftp_block_size = TFTP_BLOCK_SIZE;
760 #ifdef CONFIG_TFTP_TSIZE
762 tftp_tsize_num_hash = 0;
768 #ifdef CONFIG_CMD_TFTPSRV
769 void tftp_start_server(void)
771 tftp_filename[0] = 0;
773 if (tftp_init_load_addr()) {
775 net_set_state(NETLOOP_FAIL);
776 puts("\nTFTP error: trying to overwrite reserved memory...\n");
779 printf("Using %s device\n", eth_get_name());
780 printf("Listening for TFTP transfer on %pI4\n", &net_ip);
781 printf("Load address: 0x%lx\n", tftp_load_addr);
783 puts("Loading: *\b");
785 timeout_count_max = tftp_timeout_count_max;
787 timeout_ms = TIMEOUT;
788 net_set_timeout_handler(timeout_ms, tftp_timeout_handler);
790 /* Revert tftp_block_size to dflt */
791 tftp_block_size = TFTP_BLOCK_SIZE;
793 tftp_our_port = WELL_KNOWN_PORT;
795 #ifdef CONFIG_TFTP_TSIZE
797 tftp_tsize_num_hash = 0;
800 tftp_state = STATE_RECV_WRQ;
801 net_set_udp_handler(tftp_handler);
803 /* zero out server ether in case the server ip has changed */
804 memset(net_server_ethaddr, 0, 6);
806 #endif /* CONFIG_CMD_TFTPSRV */