2 * Copyright 1994, 1995, 2000 Neil Russell.
4 * Copyright 2000, 2001 DENX Software Engineering, Wolfgang Denk, wd@denx.de
13 /* Well known TFTP port # */
14 #define WELL_KNOWN_PORT 69
15 /* Millisecs to timeout for lost pkt */
16 #define TIMEOUT 5000UL
17 #ifndef CONFIG_NET_RETRY_COUNT
18 /* # of timeouts before giving up */
19 # define TIMEOUT_COUNT 10
21 # define TIMEOUT_COUNT (CONFIG_NET_RETRY_COUNT * 2)
23 /* Number of "loading" hashes per line (for checking the image size) */
24 #define HASHES_PER_LINE 65
36 static ulong TftpTimeoutMSecs = TIMEOUT;
37 static int TftpTimeoutCountMax = TIMEOUT_COUNT;
40 * These globals govern the timeout behavior when attempting a connection to a
41 * TFTP server. TftpRRQTimeoutMSecs specifies the number of milliseconds to
42 * wait for the server to respond to initial connection. Second global,
43 * TftpRRQTimeoutCountMax, gives the number of such connection retries.
44 * TftpRRQTimeoutCountMax must be non-negative and TftpRRQTimeoutMSecs must be
45 * positive. The globals are meant to be set (and restored) by code needing
46 * non-standard timeout behavior when initiating a TFTP transfer.
48 ulong TftpRRQTimeoutMSecs = TIMEOUT;
49 int TftpRRQTimeoutCountMax = TIMEOUT_COUNT;
52 TFTP_ERR_UNDEFINED = 0,
53 TFTP_ERR_FILE_NOT_FOUND = 1,
54 TFTP_ERR_ACCESS_DENIED = 2,
55 TFTP_ERR_DISK_FULL = 3,
56 TFTP_ERR_UNEXPECTED_OPCODE = 4,
57 TFTP_ERR_UNKNOWN_TRANSFER_ID = 5,
58 TFTP_ERR_FILE_ALREADY_EXISTS = 6,
61 static IPaddr_t TftpRemoteIP;
62 /* The UDP port at their end */
63 static int TftpRemotePort;
64 /* The UDP port at our end */
65 static int TftpOurPort;
66 static int TftpTimeoutCount;
67 /* packet sequence number */
68 static ulong TftpBlock;
69 /* last packet sequence number received */
70 static ulong TftpLastBlock;
71 /* count of sequence number wraparounds */
72 static ulong TftpBlockWrap;
73 /* memory offset due to wrapping */
74 static ulong TftpBlockWrapOffset;
76 #ifdef CONFIG_TFTP_TSIZE
77 /* The file size reported by the server */
79 /* The number of hashes we printed */
80 static short TftpNumchars;
85 #define STATE_TOO_LARGE 3
86 #define STATE_BAD_MAGIC 4
89 /* default TFTP block size */
90 #define TFTP_BLOCK_SIZE 512
91 /* sequence number is 16 bit */
92 #define TFTP_SEQUENCE_SIZE ((ulong)(1<<16))
94 #define DEFAULT_NAME_LEN (8 + 4 + 1)
95 static char default_filename[DEFAULT_NAME_LEN];
97 #ifndef CONFIG_TFTP_FILE_NAME_MAX_LEN
100 #define MAX_LEN CONFIG_TFTP_FILE_NAME_MAX_LEN
103 static char tftp_filename[MAX_LEN];
105 #ifdef CONFIG_SYS_DIRECT_FLASH_TFTP
106 extern flash_info_t flash_info[];
109 /* 512 is poor choice for ethernet, MTU is typically 1500.
110 * Minus eth.hdrs thats 1468. Can get 2x better throughput with
111 * almost-MTU block sizes. At least try... fall back to 512 if need be.
112 * (but those using CONFIG_IP_DEFRAG may want to set a larger block in cfg file)
114 #ifdef CONFIG_TFTP_BLOCKSIZE
115 #define TFTP_MTU_BLOCKSIZE CONFIG_TFTP_BLOCKSIZE
117 #define TFTP_MTU_BLOCKSIZE 1468
120 static unsigned short TftpBlkSize = TFTP_BLOCK_SIZE;
121 static unsigned short TftpBlkSizeOption = TFTP_MTU_BLOCKSIZE;
123 #ifdef CONFIG_MCAST_TFTP
125 #define MTFTP_BITMAPSIZE 0x1000
126 static unsigned *Bitmap;
127 static int PrevBitmapHole, Mapsize = MTFTP_BITMAPSIZE;
128 static uchar ProhibitMcast, MasterClient;
129 static uchar Multicast;
130 extern IPaddr_t Mcast_addr;
131 static int Mcast_port;
132 static ulong TftpEndingBlock; /* can get 'last' block before done..*/
134 static void parse_multicast_oack(char *pkt, int len);
140 eth_mcast_join(Mcast_addr, 0);
144 Mcast_addr = Multicast = Mcast_port = 0;
145 TftpEndingBlock = -1;
148 #endif /* CONFIG_MCAST_TFTP */
150 static __inline__ void
151 store_block(unsigned block, uchar *src, unsigned len)
153 ulong offset = block * TftpBlkSize + TftpBlockWrapOffset;
154 ulong newsize = offset + len;
155 #ifdef CONFIG_SYS_DIRECT_FLASH_TFTP
158 for (i = 0; i < CONFIG_SYS_MAX_FLASH_BANKS; i++) {
159 /* start address in flash? */
160 if (flash_info[i].flash_id == FLASH_UNKNOWN)
162 if (load_addr + offset >= flash_info[i].start[0]) {
168 if (rc) { /* Flash is destination for this packet */
169 rc = flash_write((char *)src, (ulong)(load_addr+offset), len);
172 NetState = NETLOOP_FAIL;
177 #endif /* CONFIG_SYS_DIRECT_FLASH_TFTP */
179 (void)memcpy((void *)(load_addr + offset), src, len);
181 #ifdef CONFIG_MCAST_TFTP
183 ext2_set_bit(block, Bitmap);
186 if (NetBootFileXferSize < newsize)
187 NetBootFileXferSize = newsize;
190 static void TftpSend(void);
191 static void TftpTimeout(void);
193 /**********************************************************************/
203 #ifdef CONFIG_MCAST_TFTP
204 /* Multicast TFTP.. non-MasterClients do not ACK data. */
206 && (TftpState == STATE_DATA)
207 && (MasterClient == 0))
211 * We will always be sending some sort of packet, so
212 * cobble together the packet headers now.
214 pkt = NetTxPacket + NetEthHdrSize() + IP_HDR_SIZE;
221 *s++ = htons(TFTP_RRQ);
223 strcpy((char *)pkt, tftp_filename);
224 pkt += strlen(tftp_filename) + 1;
225 strcpy((char *)pkt, "octet");
226 pkt += 5 /*strlen("octet")*/ + 1;
227 strcpy((char *)pkt, "timeout");
228 pkt += 7 /*strlen("timeout")*/ + 1;
229 sprintf((char *)pkt, "%lu", TftpTimeoutMSecs / 1000);
230 debug("send option \"timeout %s\"\n", (char *)pkt);
231 pkt += strlen((char *)pkt) + 1;
232 #ifdef CONFIG_TFTP_TSIZE
233 memcpy((char *)pkt, "tsize\0000\0", 8);
236 /* try for more effic. blk size */
237 pkt += sprintf((char *)pkt, "blksize%c%d%c",
238 0, TftpBlkSizeOption, 0);
239 #ifdef CONFIG_MCAST_TFTP
240 /* Check all preconditions before even trying the option */
242 && (Bitmap = malloc(Mapsize))
243 && eth_get_dev()->mcast) {
246 pkt += sprintf((char *)pkt, "multicast%c%c", 0, 0);
248 #endif /* CONFIG_MCAST_TFTP */
253 #ifdef CONFIG_MCAST_TFTP
254 /* My turn! Start at where I need blocks I missed.*/
256 TftpBlock = ext2_find_next_zero_bit(Bitmap,
263 *s++ = htons(TFTP_ACK);
264 *s++ = htons(TftpBlock);
269 case STATE_TOO_LARGE:
272 *s++ = htons(TFTP_ERROR);
275 strcpy((char *)pkt, "File too large");
276 pkt += 14 /*strlen("File too large")*/ + 1;
280 case STATE_BAD_MAGIC:
283 *s++ = htons(TFTP_ERROR);
286 strcpy((char *)pkt, "File has bad magic");
287 pkt += 18 /*strlen("File has bad magic")*/ + 1;
292 NetSendUDPPacket(NetServerEther, TftpRemoteIP, TftpRemotePort,
298 TftpHandler(uchar *pkt, unsigned dest, IPaddr_t sip, unsigned src,
305 if (dest != TftpOurPort) {
306 #ifdef CONFIG_MCAST_TFTP
308 && (!Mcast_port || (dest != Mcast_port)))
312 if (TftpState != STATE_RRQ && src != TftpRemotePort)
318 /* warning: don't use increment (++) in ntohs() macros!! */
322 switch (ntohs(proto)) {
332 debug("Got OACK: %s %s\n",
334 pkt + strlen((char *)pkt) + 1);
335 TftpState = STATE_OACK;
336 TftpRemotePort = src;
338 * Check for 'blksize' option.
339 * Careful: "i" is signed, "len" is unsigned, thus
340 * something like "len-8" may give a *huge* number
342 for (i = 0; i+8 < len; i++) {
343 if (strcmp((char *)pkt+i, "blksize") == 0) {
344 TftpBlkSize = (unsigned short)
345 simple_strtoul((char *)pkt+i+8, NULL,
347 debug("Blocksize ack: %s, %d\n",
348 (char *)pkt+i+8, TftpBlkSize);
350 #ifdef CONFIG_TFTP_TSIZE
351 if (strcmp((char *)pkt+i, "tsize") == 0) {
352 TftpTsize = simple_strtoul((char *)pkt+i+6,
354 debug("size = %s, %d\n",
355 (char *)pkt+i+6, TftpTsize);
359 #ifdef CONFIG_MCAST_TFTP
360 parse_multicast_oack((char *)pkt, len-1);
361 if ((Multicast) && (!MasterClient))
362 TftpState = STATE_DATA; /* passive.. */
365 TftpSend(); /* Send ACK */
371 TftpBlock = ntohs(*(ushort *)pkt);
374 * RFC1350 specifies that the first data packet will
375 * have sequence number 1. If we receive a sequence
376 * number of 0 this means that there was a wrap
377 * around of the (16 bit) counter.
379 if (TftpBlock == 0) {
381 TftpBlockWrapOffset +=
382 TftpBlkSize * TFTP_SEQUENCE_SIZE;
383 printf("\n\t %lu MB received\n\t ",
384 TftpBlockWrapOffset>>20);
386 #ifdef CONFIG_TFTP_TSIZE
387 else if (TftpTsize) {
388 while (TftpNumchars <
389 NetBootFileXferSize * 50 / TftpTsize) {
396 if (((TftpBlock - 1) % 10) == 0)
398 else if ((TftpBlock % (10 * HASHES_PER_LINE)) == 0)
402 if (TftpState == STATE_RRQ)
403 debug("Server did not acknowledge timeout option!\n");
405 if (TftpState == STATE_RRQ || TftpState == STATE_OACK) {
406 /* first block received */
407 TftpState = STATE_DATA;
408 TftpRemotePort = src;
411 TftpBlockWrapOffset = 0;
413 #ifdef CONFIG_MCAST_TFTP
414 if (Multicast) { /* start!=1 common if mcast */
415 TftpLastBlock = TftpBlock - 1;
418 if (TftpBlock != 1) { /* Assertion */
419 printf("\nTFTP error: "
420 "First block is not block 1 (%ld)\n"
421 "Starting again\n\n",
428 if (TftpBlock == TftpLastBlock) {
430 * Same block again; ignore it.
435 TftpLastBlock = TftpBlock;
436 TftpTimeoutCountMax = TIMEOUT_COUNT;
437 NetSetTimeout(TftpTimeoutMSecs, TftpTimeout);
439 store_block(TftpBlock - 1, pkt + 2, len);
442 * Acknoledge the block just received, which will prompt
443 * the remote for the next one.
445 #ifdef CONFIG_MCAST_TFTP
446 /* if I am the MasterClient, actively calculate what my next
447 * needed block is; else I'm passive; not ACKING
450 if (len < TftpBlkSize) {
451 TftpEndingBlock = TftpBlock;
452 } else if (MasterClient) {
453 TftpBlock = PrevBitmapHole =
454 ext2_find_next_zero_bit(
458 if (TftpBlock > ((Mapsize*8) - 1)) {
459 printf("tftpfile too big\n");
460 /* try to double it and retry */
466 TftpLastBlock = TftpBlock;
472 #ifdef CONFIG_MCAST_TFTP
474 if (MasterClient && (TftpBlock >= TftpEndingBlock)) {
475 puts("\nMulticast tftp done\n");
477 NetState = NETLOOP_SUCCESS;
482 if (len < TftpBlkSize) {
484 * We received the whole thing. Try to
487 #ifdef CONFIG_TFTP_TSIZE
488 /* Print hash marks for the last packet received */
489 while (TftpTsize && TftpNumchars < 49) {
495 NetState = NETLOOP_SUCCESS;
500 printf("\nTFTP error: '%s' (%d)\n",
501 pkt + 2, ntohs(*(ushort *)pkt));
503 switch (ntohs(*(ushort *)pkt)) {
504 case TFTP_ERR_FILE_NOT_FOUND:
505 case TFTP_ERR_ACCESS_DENIED:
506 puts("Not retrying...\n");
508 NetState = NETLOOP_FAIL;
510 case TFTP_ERR_UNDEFINED:
511 case TFTP_ERR_DISK_FULL:
512 case TFTP_ERR_UNEXPECTED_OPCODE:
513 case TFTP_ERR_UNKNOWN_TRANSFER_ID:
514 case TFTP_ERR_FILE_ALREADY_EXISTS:
516 puts("Starting again\n\n");
517 #ifdef CONFIG_MCAST_TFTP
531 if (++TftpTimeoutCount > TftpTimeoutCountMax) {
532 puts("\nRetry count exceeded; starting again\n");
533 #ifdef CONFIG_MCAST_TFTP
539 NetSetTimeout(TftpTimeoutMSecs, TftpTimeout);
548 char *ep; /* Environment pointer */
551 * Allow the user to choose TFTP blocksize and timeout.
552 * TFTP protocol has a minimal timeout of 1 second.
554 ep = getenv("tftpblocksize");
556 TftpBlkSizeOption = simple_strtol(ep, NULL, 10);
558 ep = getenv("tftptimeout");
560 TftpTimeoutMSecs = simple_strtol(ep, NULL, 10);
562 if (TftpTimeoutMSecs < 1000) {
563 printf("TFTP timeout (%ld ms) too low, "
564 "set minimum = 1000 ms\n",
566 TftpTimeoutMSecs = 1000;
569 debug("TFTP blocksize = %i, timeout = %ld ms\n",
570 TftpBlkSizeOption, TftpTimeoutMSecs);
572 TftpRemoteIP = NetServerIP;
573 if (BootFile[0] == '\0') {
574 sprintf(default_filename, "%02lX%02lX%02lX%02lX.img",
576 (NetOurIP >> 8) & 0xFF,
577 (NetOurIP >> 16) & 0xFF,
578 (NetOurIP >> 24) & 0xFF);
580 strncpy(tftp_filename, default_filename, MAX_LEN);
581 tftp_filename[MAX_LEN-1] = 0;
583 printf("*** Warning: no boot file name; using '%s'\n",
586 char *p = strchr(BootFile, ':');
589 strncpy(tftp_filename, BootFile, MAX_LEN);
590 tftp_filename[MAX_LEN-1] = 0;
592 TftpRemoteIP = string_to_ip(BootFile);
593 strncpy(tftp_filename, p + 1, MAX_LEN);
594 tftp_filename[MAX_LEN-1] = 0;
598 #if defined(CONFIG_NET_MULTI)
599 printf("Using %s device\n", eth_get_name());
601 printf("TFTP from server %pI4"
602 "; our IP address is %pI4", &TftpRemoteIP, &NetOurIP);
604 /* Check if we need to send across this subnet */
605 if (NetOurGatewayIP && NetOurSubnetMask) {
606 IPaddr_t OurNet = NetOurIP & NetOurSubnetMask;
607 IPaddr_t RemoteNet = TftpRemoteIP & NetOurSubnetMask;
609 if (OurNet != RemoteNet)
610 printf("; sending through gateway %pI4",
615 printf("Filename '%s'.", tftp_filename);
617 if (NetBootFileSize) {
618 printf(" Size is 0x%x Bytes = ", NetBootFileSize<<9);
619 print_size(NetBootFileSize<<9, "");
624 printf("Load address: 0x%lx\n", load_addr);
626 puts("Loading: *\b");
628 TftpTimeoutCountMax = TftpRRQTimeoutCountMax;
630 NetSetTimeout(TftpTimeoutMSecs, TftpTimeout);
631 NetSetHandler(TftpHandler);
633 TftpRemotePort = WELL_KNOWN_PORT;
634 TftpTimeoutCount = 0;
635 TftpState = STATE_RRQ;
636 /* Use a pseudo-random port unless a specific port is set */
637 TftpOurPort = 1024 + (get_timer(0) % 3072);
639 #ifdef CONFIG_TFTP_PORT
640 ep = getenv("tftpdstp");
642 TftpRemotePort = simple_strtol(ep, NULL, 10);
643 ep = getenv("tftpsrcp");
645 TftpOurPort = simple_strtol(ep, NULL, 10);
649 /* zero out server ether in case the server ip has changed */
650 memset(NetServerEther, 0, 6);
651 /* Revert TftpBlkSize to dflt */
652 TftpBlkSize = TFTP_BLOCK_SIZE;
653 #ifdef CONFIG_MCAST_TFTP
656 #ifdef CONFIG_TFTP_TSIZE
664 #ifdef CONFIG_MCAST_TFTP
665 /* Credits: atftp project.
668 /* pick up BcastAddr, Port, and whether I am [now] the master-client. *
670 * +-------+-----------+---+-------~~-------+---+
671 * | opc | multicast | 0 | addr, port, mc | 0 |
672 * +-------+-----------+---+-------~~-------+---+
673 * The multicast addr/port becomes what I listen to, and if 'mc' is '1' then
674 * I am the new master-client so must send ACKs to DataBlocks. If I am not
675 * master-client, I'm a passive client, gathering what DataBlocks I may and
676 * making note of which ones I got in my bitmask.
677 * In theory, I never go from master->passive..
678 * .. this comes in with pkt already pointing just past opc
680 static void parse_multicast_oack(char *pkt, int len)
684 char *mc_adr, *port, *mc;
686 mc_adr = port = mc = NULL;
687 /* march along looking for 'multicast\0', which has to start at least
688 * 14 bytes back from the end.
690 for (i = 0; i < len-14; i++)
691 if (strcmp(pkt+i, "multicast") == 0)
693 if (i >= (len-14)) /* non-Multicast OACK, ign. */
696 i += 10; /* strlen multicast */
698 for (; i < len; i++) {
699 if (*(pkt+i) == ',') {
709 if (!port || !mc_adr || !mc)
711 if (Multicast && MasterClient) {
712 printf("I got a OACK as master Client, WRONG!\n");
715 /* ..I now accept packets destined for this MCAST addr, port */
718 printf("Internal failure! no mcast.\n");
724 /* I malloc instead of pre-declare; so that if the file ends
725 * up being too big for this bitmap I can retry
727 Bitmap = malloc(Mapsize);
729 printf("No Bitmap, no multicast. Sorry.\n");
733 memset(Bitmap, 0, Mapsize);
737 addr = string_to_ip(mc_adr);
738 if (Mcast_addr != addr) {
740 eth_mcast_join(Mcast_addr, 0);
742 if (eth_mcast_join(Mcast_addr, 1)) {
743 printf("Fail to set mcast, revert to TFTP\n");
749 MasterClient = (unsigned char)simple_strtoul((char *)mc, NULL, 10);
750 Mcast_port = (unsigned short)simple_strtoul(port, NULL, 10);
751 printf("Multicast: %s:%d [%d]\n", mc_adr, Mcast_port, MasterClient);
755 #endif /* Multicast TFTP */