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>
20 #ifdef CONFIG_SYS_DIRECT_FLASH_TFTP
24 DECLARE_GLOBAL_DATA_PTR;
26 /* Well known TFTP port # */
27 #define WELL_KNOWN_PORT 69
28 /* Millisecs to timeout for lost pkt */
29 #define TIMEOUT 5000UL
30 #ifndef CONFIG_NET_RETRY_COUNT
31 /* # of timeouts before giving up */
32 # define TIMEOUT_COUNT 10
34 # define TIMEOUT_COUNT (CONFIG_NET_RETRY_COUNT * 2)
36 /* Number of "loading" hashes per line (for checking the image size) */
37 #define HASHES_PER_LINE 65
49 static ulong timeout_ms = TIMEOUT;
50 static int timeout_count_max = TIMEOUT_COUNT;
51 static ulong time_start; /* Record time we started tftp */
54 * These globals govern the timeout behavior when attempting a connection to a
55 * TFTP server. tftp_timeout_ms specifies the number of milliseconds to
56 * wait for the server to respond to initial connection. Second global,
57 * tftp_timeout_count_max, gives the number of such connection retries.
58 * tftp_timeout_count_max must be non-negative and tftp_timeout_ms must be
59 * positive. The globals are meant to be set (and restored) by code needing
60 * non-standard timeout behavior when initiating a TFTP transfer.
62 ulong tftp_timeout_ms = TIMEOUT;
63 int tftp_timeout_count_max = TIMEOUT_COUNT;
66 TFTP_ERR_UNDEFINED = 0,
67 TFTP_ERR_FILE_NOT_FOUND = 1,
68 TFTP_ERR_ACCESS_DENIED = 2,
69 TFTP_ERR_DISK_FULL = 3,
70 TFTP_ERR_UNEXPECTED_OPCODE = 4,
71 TFTP_ERR_UNKNOWN_TRANSFER_ID = 5,
72 TFTP_ERR_FILE_ALREADY_EXISTS = 6,
73 TFTP_ERR_OPTION_NEGOTIATION = 8,
76 static struct in_addr tftp_remote_ip;
77 /* The UDP port at their end */
78 static int tftp_remote_port;
79 /* The UDP port at our end */
80 static int tftp_our_port;
81 static int timeout_count;
82 /* packet sequence number */
83 static ulong tftp_cur_block;
84 /* last packet sequence number received */
85 static ulong tftp_prev_block;
86 /* count of sequence number wraparounds */
87 static ulong tftp_block_wrap;
88 /* memory offset due to wrapping */
89 static ulong tftp_block_wrap_offset;
90 static int tftp_state;
91 static ulong tftp_load_addr;
93 static ulong tftp_load_size;
95 #ifdef CONFIG_TFTP_TSIZE
96 /* The file size reported by the server */
97 static int tftp_tsize;
98 /* The number of hashes we printed */
99 static short tftp_tsize_num_hash;
101 #ifdef CONFIG_CMD_TFTPPUT
102 /* 1 if writing, else 0 */
103 static int tftp_put_active;
104 /* 1 if we have sent the last block */
105 static int tftp_put_final_block_sent;
107 #define tftp_put_active 0
110 #define STATE_SEND_RRQ 1
112 #define STATE_TOO_LARGE 3
113 #define STATE_BAD_MAGIC 4
115 #define STATE_RECV_WRQ 6
116 #define STATE_SEND_WRQ 7
117 #define STATE_INVALID_OPTION 8
119 /* default TFTP block size */
120 #define TFTP_BLOCK_SIZE 512
121 /* sequence number is 16 bit */
122 #define TFTP_SEQUENCE_SIZE ((ulong)(1<<16))
124 #define DEFAULT_NAME_LEN (8 + 4 + 1)
125 static char default_filename[DEFAULT_NAME_LEN];
127 #ifndef CONFIG_TFTP_FILE_NAME_MAX_LEN
130 #define MAX_LEN CONFIG_TFTP_FILE_NAME_MAX_LEN
133 static char tftp_filename[MAX_LEN];
135 /* 512 is poor choice for ethernet, MTU is typically 1500.
136 * Minus eth.hdrs thats 1468. Can get 2x better throughput with
137 * almost-MTU block sizes. At least try... fall back to 512 if need be.
138 * (but those using CONFIG_IP_DEFRAG may want to set a larger block in cfg file)
141 static unsigned short tftp_block_size = TFTP_BLOCK_SIZE;
142 static unsigned short tftp_block_size_option = CONFIG_TFTP_BLOCKSIZE;
144 static inline int store_block(int block, uchar *src, unsigned int len)
146 ulong offset = block * tftp_block_size + tftp_block_wrap_offset;
147 ulong newsize = offset + len;
148 ulong store_addr = tftp_load_addr + offset;
149 #ifdef CONFIG_SYS_DIRECT_FLASH_TFTP
152 for (i = 0; i < CONFIG_SYS_MAX_FLASH_BANKS; i++) {
153 /* start address in flash? */
154 if (flash_info[i].flash_id == FLASH_UNKNOWN)
156 if (store_addr >= flash_info[i].start[0]) {
162 if (rc) { /* Flash is destination for this packet */
163 rc = flash_write((char *)src, store_addr, len);
169 #endif /* CONFIG_SYS_DIRECT_FLASH_TFTP */
174 ulong end_addr = tftp_load_addr + tftp_load_size;
177 end_addr = ULONG_MAX;
179 if (store_addr < tftp_load_addr ||
180 store_addr + len > end_addr) {
181 puts("\nTFTP error: ");
182 puts("trying to overwrite reserved memory...\n");
186 ptr = map_sysmem(store_addr, len);
187 memcpy(ptr, src, len);
191 if (net_boot_file_size < newsize)
192 net_boot_file_size = newsize;
197 /* Clear our state ready for a new transfer */
198 static void new_transfer(void)
202 tftp_block_wrap_offset = 0;
203 #ifdef CONFIG_CMD_TFTPPUT
204 tftp_put_final_block_sent = 0;
208 #ifdef CONFIG_CMD_TFTPPUT
210 * Load the next block from memory to be sent over tftp.
212 * @param block Block number to send
213 * @param dst Destination buffer for data
214 * @param len Number of bytes in block (this one and every other)
215 * @return number of bytes loaded
217 static int load_block(unsigned block, uchar *dst, unsigned len)
219 /* We may want to get the final block from the previous set */
220 ulong offset = ((int)block - 1) * len + tftp_block_wrap_offset;
223 tosend = min(net_boot_file_size - offset, tosend);
224 (void)memcpy(dst, (void *)(image_save_addr + offset), tosend);
225 debug("%s: block=%u, offset=%lu, len=%u, tosend=%lu\n", __func__,
226 block, offset, len, tosend);
231 static void tftp_send(void);
232 static void tftp_timeout_handler(void);
234 /**********************************************************************/
236 static void show_block_marker(void)
240 #ifdef CONFIG_TFTP_TSIZE
242 pos = tftp_cur_block * tftp_block_size +
243 tftp_block_wrap_offset;
244 if (pos > tftp_tsize)
247 while (tftp_tsize_num_hash < pos * 50 / tftp_tsize) {
249 tftp_tsize_num_hash++;
254 pos = (tftp_cur_block - 1) +
255 (tftp_block_wrap * TFTP_SEQUENCE_SIZE);
258 else if (((pos + 1) % (10 * HASHES_PER_LINE)) == 0)
264 * restart the current transfer due to an error
266 * @param msg Message to print for user
268 static void restart(const char *msg)
270 printf("\n%s; starting again\n", msg);
275 * Check if the block number has wrapped, and update progress
277 * TODO: The egregious use of global variables in this file should be tidied.
279 static void update_block_number(void)
282 * RFC1350 specifies that the first data packet will
283 * have sequence number 1. If we receive a sequence
284 * number of 0 this means that there was a wrap
285 * around of the (16 bit) counter.
287 if (tftp_cur_block == 0 && tftp_prev_block != 0) {
289 tftp_block_wrap_offset += tftp_block_size * TFTP_SEQUENCE_SIZE;
290 timeout_count = 0; /* we've done well, reset the timeout */
295 /* The TFTP get or put is complete */
296 static void tftp_complete(void)
298 #ifdef CONFIG_TFTP_TSIZE
299 /* Print hash marks for the last packet received */
300 while (tftp_tsize && tftp_tsize_num_hash < 49) {
302 tftp_tsize_num_hash++;
305 print_size(tftp_tsize, "");
307 time_start = get_timer(time_start);
308 if (time_start > 0) {
309 puts("\n\t "); /* Line up with "Loading: " */
310 print_size(net_boot_file_size /
311 time_start * 1000, "/s");
314 net_set_state(NETLOOP_SUCCESS);
317 static void tftp_send(void)
323 bool err_pkt = false;
326 * We will always be sending some sort of packet, so
327 * cobble together the packet headers now.
329 pkt = net_tx_packet + net_eth_hdr_size() + IP_UDP_HDR_SIZE;
331 switch (tftp_state) {
336 #ifdef CONFIG_CMD_TFTPPUT
337 *s++ = htons(tftp_state == STATE_SEND_RRQ ? TFTP_RRQ :
340 *s++ = htons(TFTP_RRQ);
343 strcpy((char *)pkt, tftp_filename);
344 pkt += strlen(tftp_filename) + 1;
345 strcpy((char *)pkt, "octet");
346 pkt += 5 /*strlen("octet")*/ + 1;
347 strcpy((char *)pkt, "timeout");
348 pkt += 7 /*strlen("timeout")*/ + 1;
349 sprintf((char *)pkt, "%lu", timeout_ms / 1000);
350 debug("send option \"timeout %s\"\n", (char *)pkt);
351 pkt += strlen((char *)pkt) + 1;
352 #ifdef CONFIG_TFTP_TSIZE
353 pkt += sprintf((char *)pkt, "tsize%c%u%c",
354 0, net_boot_file_size, 0);
356 /* try for more effic. blk size */
357 pkt += sprintf((char *)pkt, "blksize%c%d%c",
358 0, tftp_block_size_option, 0);
368 s[0] = htons(TFTP_ACK);
369 s[1] = htons(tftp_cur_block);
370 pkt = (uchar *)(s + 2);
371 #ifdef CONFIG_CMD_TFTPPUT
372 if (tftp_put_active) {
373 int toload = tftp_block_size;
374 int loaded = load_block(tftp_cur_block, pkt, toload);
376 s[0] = htons(TFTP_DATA);
378 tftp_put_final_block_sent = (loaded < toload);
384 case STATE_TOO_LARGE:
387 *s++ = htons(TFTP_ERROR);
391 strcpy((char *)pkt, "File too large");
392 pkt += 14 /*strlen("File too large")*/ + 1;
397 case STATE_BAD_MAGIC:
400 *s++ = htons(TFTP_ERROR);
403 strcpy((char *)pkt, "File has bad magic");
404 pkt += 18 /*strlen("File has bad magic")*/ + 1;
409 case STATE_INVALID_OPTION:
412 *s++ = htons(TFTP_ERROR);
413 *s++ = htons(TFTP_ERR_OPTION_NEGOTIATION);
415 strcpy((char *)pkt, "Option Negotiation Failed");
416 /* strlen("Option Negotiation Failed") + NULL*/
423 net_send_udp_packet(net_server_ethaddr, tftp_remote_ip,
424 tftp_remote_port, tftp_our_port, len);
427 net_set_state(NETLOOP_FAIL);
430 #ifdef CONFIG_CMD_TFTPPUT
431 static void icmp_handler(unsigned type, unsigned code, unsigned dest,
432 struct in_addr sip, unsigned src, uchar *pkt,
435 if (type == ICMP_NOT_REACH && code == ICMP_NOT_REACH_PORT) {
436 /* Oh dear the other end has gone away */
437 restart("TFTP server died");
442 static void tftp_handler(uchar *pkt, unsigned dest, struct in_addr sip,
443 unsigned src, unsigned len)
448 u16 timeout_val_rcvd;
450 if (dest != tftp_our_port) {
453 if (tftp_state != STATE_SEND_RRQ && src != tftp_remote_port &&
454 tftp_state != STATE_RECV_WRQ && tftp_state != STATE_SEND_WRQ)
460 /* warning: don't use increment (++) in ntohs() macros!! */
464 switch (ntohs(proto)) {
469 #ifdef CONFIG_CMD_TFTPPUT
470 if (tftp_put_active) {
471 if (tftp_put_final_block_sent) {
475 * Move to the next block. We want our block
476 * count to wrap just like the other end!
478 int block = ntohs(*s);
479 int ack_ok = (tftp_cur_block == block);
481 tftp_cur_block = (unsigned short)(block + 1);
482 update_block_number();
484 tftp_send(); /* Send next data block */
493 #ifdef CONFIG_CMD_TFTPSRV
496 tftp_remote_ip = sip;
497 tftp_remote_port = src;
498 tftp_our_port = 1024 + (get_timer(0) % 3072);
500 tftp_send(); /* Send ACK(0) */
506 for (i = 0; i < len; i++) {
513 tftp_state = STATE_OACK;
514 tftp_remote_port = src;
516 * Check for 'blksize' option.
517 * Careful: "i" is signed, "len" is unsigned, thus
518 * something like "len-8" may give a *huge* number
520 for (i = 0; i+8 < len; i++) {
521 if (strcasecmp((char *)pkt + i, "blksize") == 0) {
522 tftp_block_size = (unsigned short)
523 simple_strtoul((char *)pkt + i + 8,
525 debug("Blocksize oack: %s, %d\n",
526 (char *)pkt + i + 8, tftp_block_size);
527 if (tftp_block_size > tftp_block_size_option) {
528 printf("Invalid blk size(=%d)\n",
530 tftp_state = STATE_INVALID_OPTION;
533 if (strcasecmp((char *)pkt + i, "timeout") == 0) {
534 timeout_val_rcvd = (unsigned short)
535 simple_strtoul((char *)pkt + i + 8,
537 debug("Timeout oack: %s, %d\n",
538 (char *)pkt + i + 8, timeout_val_rcvd);
539 if (timeout_val_rcvd != (timeout_ms / 1000)) {
540 printf("Invalid timeout val(=%d s)\n",
542 tftp_state = STATE_INVALID_OPTION;
545 #ifdef CONFIG_TFTP_TSIZE
546 if (strcasecmp((char *)pkt + i, "tsize") == 0) {
547 tftp_tsize = simple_strtoul((char *)pkt + i + 6,
549 debug("size = %s, %d\n",
550 (char *)pkt + i + 6, tftp_tsize);
554 #ifdef CONFIG_CMD_TFTPPUT
555 if (tftp_put_active && tftp_state == STATE_OACK) {
556 /* Get ready to send the first block */
557 tftp_state = STATE_DATA;
561 tftp_send(); /* Send ACK or first data block */
567 tftp_cur_block = ntohs(*(__be16 *)pkt);
569 if (tftp_state == STATE_SEND_RRQ)
570 debug("Server did not acknowledge any options!\n");
572 if (tftp_state == STATE_SEND_RRQ || tftp_state == STATE_OACK ||
573 tftp_state == STATE_RECV_WRQ) {
574 /* first block received */
575 tftp_state = STATE_DATA;
576 tftp_remote_port = src;
579 if (tftp_cur_block != 1) { /* Assertion */
580 puts("\nTFTP error: ");
581 printf("First block is not block 1 (%ld)\n",
583 puts("Starting again\n\n");
589 if (tftp_cur_block == tftp_prev_block) {
590 /* Same block again; ignore it. */
594 update_block_number();
595 tftp_prev_block = tftp_cur_block;
596 timeout_count_max = tftp_timeout_count_max;
597 net_set_timeout_handler(timeout_ms, tftp_timeout_handler);
599 if (store_block(tftp_cur_block - 1, pkt + 2, len)) {
601 net_set_state(NETLOOP_FAIL);
606 * Acknowledge the block just received, which will prompt
607 * the remote for the next one.
611 if (len < tftp_block_size)
616 printf("\nTFTP error: '%s' (%d)\n",
617 pkt + 2, ntohs(*(__be16 *)pkt));
619 switch (ntohs(*(__be16 *)pkt)) {
620 case TFTP_ERR_FILE_NOT_FOUND:
621 case TFTP_ERR_ACCESS_DENIED:
622 puts("Not retrying...\n");
624 net_set_state(NETLOOP_FAIL);
626 case TFTP_ERR_UNDEFINED:
627 case TFTP_ERR_DISK_FULL:
628 case TFTP_ERR_UNEXPECTED_OPCODE:
629 case TFTP_ERR_UNKNOWN_TRANSFER_ID:
630 case TFTP_ERR_FILE_ALREADY_EXISTS:
632 puts("Starting again\n\n");
641 static void tftp_timeout_handler(void)
643 if (++timeout_count > timeout_count_max) {
644 restart("Retry count exceeded");
647 net_set_timeout_handler(timeout_ms, tftp_timeout_handler);
648 if (tftp_state != STATE_RECV_WRQ)
653 /* Initialize tftp_load_addr and tftp_load_size from image_load_addr and lmb */
654 static int tftp_init_load_addr(void)
658 phys_size_t max_size;
660 lmb_init_and_reserve(&lmb, gd->bd, (void *)gd->fdt_blob);
662 max_size = lmb_get_free_size(&lmb, image_load_addr);
666 tftp_load_size = max_size;
668 tftp_load_addr = image_load_addr;
672 void tftp_start(enum proto_t protocol)
674 #if CONFIG_NET_TFTP_VARS
675 char *ep; /* Environment pointer */
678 * Allow the user to choose TFTP blocksize and timeout.
679 * TFTP protocol has a minimal timeout of 1 second.
682 ep = env_get("tftpblocksize");
684 tftp_block_size_option = simple_strtol(ep, NULL, 10);
686 ep = env_get("tftptimeout");
688 timeout_ms = simple_strtol(ep, NULL, 10);
690 if (timeout_ms < 1000) {
691 printf("TFTP timeout (%ld ms) too low, set min = 1000 ms\n",
696 ep = env_get("tftptimeoutcountmax");
698 tftp_timeout_count_max = simple_strtol(ep, NULL, 10);
700 if (tftp_timeout_count_max < 0) {
701 printf("TFTP timeout count max (%d ms) negative, set to 0\n",
702 tftp_timeout_count_max);
703 tftp_timeout_count_max = 0;
707 debug("TFTP blocksize = %i, timeout = %ld ms\n",
708 tftp_block_size_option, timeout_ms);
710 tftp_remote_ip = net_server_ip;
711 if (!net_parse_bootfile(&tftp_remote_ip, tftp_filename, MAX_LEN)) {
712 sprintf(default_filename, "%02X%02X%02X%02X.img",
713 net_ip.s_addr & 0xFF,
714 (net_ip.s_addr >> 8) & 0xFF,
715 (net_ip.s_addr >> 16) & 0xFF,
716 (net_ip.s_addr >> 24) & 0xFF);
718 strncpy(tftp_filename, default_filename, DEFAULT_NAME_LEN);
719 tftp_filename[DEFAULT_NAME_LEN - 1] = 0;
721 printf("*** Warning: no boot file name; using '%s'\n",
725 printf("Using %s device\n", eth_get_name());
726 printf("TFTP %s server %pI4; our IP address is %pI4",
727 #ifdef CONFIG_CMD_TFTPPUT
728 protocol == TFTPPUT ? "to" : "from",
732 &tftp_remote_ip, &net_ip);
734 /* Check if we need to send across this subnet */
735 if (net_gateway.s_addr && net_netmask.s_addr) {
736 struct in_addr our_net;
737 struct in_addr remote_net;
739 our_net.s_addr = net_ip.s_addr & net_netmask.s_addr;
740 remote_net.s_addr = tftp_remote_ip.s_addr & net_netmask.s_addr;
741 if (our_net.s_addr != remote_net.s_addr)
742 printf("; sending through gateway %pI4", &net_gateway);
746 printf("Filename '%s'.", tftp_filename);
748 if (net_boot_file_expected_size_in_blocks) {
749 printf(" Size is 0x%x Bytes = ",
750 net_boot_file_expected_size_in_blocks << 9);
751 print_size(net_boot_file_expected_size_in_blocks << 9, "");
755 #ifdef CONFIG_CMD_TFTPPUT
756 tftp_put_active = (protocol == TFTPPUT);
757 if (tftp_put_active) {
758 printf("Save address: 0x%lx\n", image_save_addr);
759 printf("Save size: 0x%lx\n", image_save_size);
760 net_boot_file_size = image_save_size;
762 tftp_state = STATE_SEND_WRQ;
767 if (tftp_init_load_addr()) {
769 net_set_state(NETLOOP_FAIL);
770 puts("\nTFTP error: ");
771 puts("trying to overwrite reserved memory...\n");
774 printf("Load address: 0x%lx\n", tftp_load_addr);
775 puts("Loading: *\b");
776 tftp_state = STATE_SEND_RRQ;
777 #ifdef CONFIG_CMD_BOOTEFI
778 efi_set_bootdev("Net", "", tftp_filename);
782 time_start = get_timer(0);
783 timeout_count_max = tftp_timeout_count_max;
785 net_set_timeout_handler(timeout_ms, tftp_timeout_handler);
786 net_set_udp_handler(tftp_handler);
787 #ifdef CONFIG_CMD_TFTPPUT
788 net_set_icmp_handler(icmp_handler);
790 tftp_remote_port = WELL_KNOWN_PORT;
792 /* Use a pseudo-random port unless a specific port is set */
793 tftp_our_port = 1024 + (get_timer(0) % 3072);
795 #ifdef CONFIG_TFTP_PORT
796 ep = env_get("tftpdstp");
798 tftp_remote_port = simple_strtol(ep, NULL, 10);
799 ep = env_get("tftpsrcp");
801 tftp_our_port = simple_strtol(ep, NULL, 10);
805 /* zero out server ether in case the server ip has changed */
806 memset(net_server_ethaddr, 0, 6);
807 /* Revert tftp_block_size to dflt */
808 tftp_block_size = TFTP_BLOCK_SIZE;
809 #ifdef CONFIG_TFTP_TSIZE
811 tftp_tsize_num_hash = 0;
817 #ifdef CONFIG_CMD_TFTPSRV
818 void tftp_start_server(void)
820 tftp_filename[0] = 0;
822 if (tftp_init_load_addr()) {
824 net_set_state(NETLOOP_FAIL);
825 puts("\nTFTP error: trying to overwrite reserved memory...\n");
828 printf("Using %s device\n", eth_get_name());
829 printf("Listening for TFTP transfer on %pI4\n", &net_ip);
830 printf("Load address: 0x%lx\n", tftp_load_addr);
832 puts("Loading: *\b");
834 timeout_count_max = tftp_timeout_count_max;
836 timeout_ms = TIMEOUT;
837 net_set_timeout_handler(timeout_ms, tftp_timeout_handler);
839 /* Revert tftp_block_size to dflt */
840 tftp_block_size = TFTP_BLOCK_SIZE;
842 tftp_our_port = WELL_KNOWN_PORT;
844 #ifdef CONFIG_TFTP_TSIZE
846 tftp_tsize_num_hash = 0;
849 tftp_state = STATE_RECV_WRQ;
850 net_set_udp_handler(tftp_handler);
852 /* zero out server ether in case the server ip has changed */
853 memset(net_server_ethaddr, 0, 6);
855 #endif /* CONFIG_CMD_TFTPSRV */