2 * Copyright 1994, 1995, 2000 Neil Russell.
4 * Copyright 2000, 2001 DENX Software Engineering, Wolfgang Denk, wd@denx.de
13 #if defined(CONFIG_CMD_NET)
15 #define WELL_KNOWN_PORT 69 /* Well known TFTP port # */
16 #define TIMEOUT 5000UL /* Millisecs to timeout for lost pkt */
17 #ifndef CONFIG_NET_RETRY_COUNT
18 # define TIMEOUT_COUNT 10 /* # of timeouts before giving up */
20 # define TIMEOUT_COUNT (CONFIG_NET_RETRY_COUNT * 2)
22 /* (for checking the image size) */
23 #define HASHES_PER_LINE 65 /* Number of "loading" hashes per line */
35 static ulong TftpTimeoutMSecs = TIMEOUT;
36 static int TftpTimeoutCountMax = TIMEOUT_COUNT;
39 * These globals govern the timeout behavior when attempting a connection to a
40 * TFTP server. TftpRRQTimeoutMSecs specifies the number of milliseconds to
41 * wait for the server to respond to initial connection. Second global,
42 * TftpRRQTimeoutCountMax, gives the number of such connection retries.
43 * TftpRRQTimeoutCountMax must be non-negative and TftpRRQTimeoutMSecs must be
44 * positive. The globals are meant to be set (and restored) by code needing
45 * non-standard timeout behavior when initiating a TFTP transfer.
47 ulong TftpRRQTimeoutMSecs = TIMEOUT;
48 int TftpRRQTimeoutCountMax = TIMEOUT_COUNT;
50 static IPaddr_t TftpServerIP;
51 static int TftpServerPort; /* The UDP port at their end */
52 static int TftpOurPort; /* The UDP port at our end */
53 static int TftpTimeoutCount;
54 static ulong TftpBlock; /* packet sequence number */
55 static ulong TftpLastBlock; /* last packet sequence number received */
56 static ulong TftpBlockWrap; /* count of sequence number wraparounds */
57 static ulong TftpBlockWrapOffset; /* memory offset due to wrapping */
62 #define STATE_TOO_LARGE 3
63 #define STATE_BAD_MAGIC 4
66 #define TFTP_BLOCK_SIZE 512 /* default TFTP block size */
67 #define TFTP_SEQUENCE_SIZE ((ulong)(1<<16)) /* sequence number is 16 bit */
69 #define DEFAULT_NAME_LEN (8 + 4 + 1)
70 static char default_filename[DEFAULT_NAME_LEN];
72 #ifndef CONFIG_TFTP_FILE_NAME_MAX_LEN
75 #define MAX_LEN CONFIG_TFTP_FILE_NAME_MAX_LEN
78 static char tftp_filename[MAX_LEN];
80 #ifdef CONFIG_SYS_DIRECT_FLASH_TFTP
81 extern flash_info_t flash_info[];
84 /* 512 is poor choice for ethernet, MTU is typically 1500.
85 * Minus eth.hdrs thats 1468. Can get 2x better throughput with
86 * almost-MTU block sizes. At least try... fall back to 512 if need be.
87 * (but those using CONFIG_IP_DEFRAG may want to set a larger block in cfg file)
89 #ifdef CONFIG_TFTP_BLOCKSIZE
90 #define TFTP_MTU_BLOCKSIZE CONFIG_TFTP_BLOCKSIZE
92 #define TFTP_MTU_BLOCKSIZE 1468
95 static unsigned short TftpBlkSize=TFTP_BLOCK_SIZE;
96 static unsigned short TftpBlkSizeOption=TFTP_MTU_BLOCKSIZE;
98 #ifdef CONFIG_MCAST_TFTP
100 #define MTFTP_BITMAPSIZE 0x1000
101 static unsigned *Bitmap;
102 static int PrevBitmapHole,Mapsize=MTFTP_BITMAPSIZE;
103 static uchar ProhibitMcast=0, MasterClient=0;
104 static uchar Multicast=0;
105 extern IPaddr_t Mcast_addr;
106 static int Mcast_port;
107 static ulong TftpEndingBlock; /* can get 'last' block before done..*/
109 static void parse_multicast_oack(char *pkt,int len);
114 if (Mcast_addr) eth_mcast_join(Mcast_addr, 0);
115 if (Bitmap) free(Bitmap);
117 Mcast_addr = Multicast = Mcast_port = 0;
118 TftpEndingBlock = -1;
121 #endif /* CONFIG_MCAST_TFTP */
123 static __inline__ void
124 store_block (unsigned block, uchar * src, unsigned len)
126 ulong offset = block * TftpBlkSize + TftpBlockWrapOffset;
127 ulong newsize = offset + len;
128 #ifdef CONFIG_SYS_DIRECT_FLASH_TFTP
131 for (i=0; i<CONFIG_SYS_MAX_FLASH_BANKS; i++) {
132 /* start address in flash? */
133 if (flash_info[i].flash_id == FLASH_UNKNOWN)
135 if (load_addr + offset >= flash_info[i].start[0]) {
141 if (rc) { /* Flash is destination for this packet */
142 rc = flash_write ((char *)src, (ulong)(load_addr+offset), len);
145 NetState = NETLOOP_FAIL;
150 #endif /* CONFIG_SYS_DIRECT_FLASH_TFTP */
152 (void)memcpy((void *)(load_addr + offset), src, len);
154 #ifdef CONFIG_MCAST_TFTP
156 ext2_set_bit(block, Bitmap);
159 if (NetBootFileXferSize < newsize)
160 NetBootFileXferSize = newsize;
163 static void TftpSend (void);
164 static void TftpTimeout (void);
166 /**********************************************************************/
171 volatile uchar * pkt;
176 #ifdef CONFIG_MCAST_TFTP
177 /* Multicast TFTP.. non-MasterClients do not ACK data. */
179 && (TftpState == STATE_DATA)
180 && (MasterClient == 0))
184 * We will always be sending some sort of packet, so
185 * cobble together the packet headers now.
187 pkt = NetTxPacket + NetEthHdrSize() + IP_HDR_SIZE;
194 *s++ = htons(TFTP_RRQ);
196 strcpy ((char *)pkt, tftp_filename);
197 pkt += strlen(tftp_filename) + 1;
198 strcpy ((char *)pkt, "octet");
199 pkt += 5 /*strlen("octet")*/ + 1;
200 strcpy ((char *)pkt, "timeout");
201 pkt += 7 /*strlen("timeout")*/ + 1;
202 sprintf((char *)pkt, "%lu", TIMEOUT / 1000);
203 debug("send option \"timeout %s\"\n", (char *)pkt);
204 pkt += strlen((char *)pkt) + 1;
205 /* try for more effic. blk size */
206 pkt += sprintf((char *)pkt,"blksize%c%d%c",
207 0,TftpBlkSizeOption,0);
208 #ifdef CONFIG_MCAST_TFTP
209 /* Check all preconditions before even trying the option */
211 && (Bitmap=malloc(Mapsize))
212 && eth_get_dev()->mcast) {
215 pkt += sprintf((char *)pkt,"multicast%c%c",0,0);
217 #endif /* CONFIG_MCAST_TFTP */
222 #ifdef CONFIG_MCAST_TFTP
223 /* My turn! Start at where I need blocks I missed.*/
225 TftpBlock=ext2_find_next_zero_bit(Bitmap,(Mapsize*8),0);
231 *s++ = htons(TFTP_ACK);
232 *s++ = htons(TftpBlock);
237 case STATE_TOO_LARGE:
240 *s++ = htons(TFTP_ERROR);
243 strcpy ((char *)pkt, "File too large");
244 pkt += 14 /*strlen("File too large")*/ + 1;
248 case STATE_BAD_MAGIC:
251 *s++ = htons(TFTP_ERROR);
254 strcpy ((char *)pkt, "File has bad magic");
255 pkt += 18 /*strlen("File has bad magic")*/ + 1;
260 NetSendUDPPacket(NetServerEther, TftpServerIP, TftpServerPort, TftpOurPort, len);
265 TftpHandler (uchar * pkt, unsigned dest, unsigned src, unsigned len)
271 if (dest != TftpOurPort) {
272 #ifdef CONFIG_MCAST_TFTP
274 && (!Mcast_port || (dest != Mcast_port)))
278 if (TftpState != STATE_RRQ && src != TftpServerPort) {
286 /* warning: don't use increment (++) in ntohs() macros!! */
290 switch (ntohs(proto)) {
300 debug("Got OACK: %s %s\n",
302 pkt + strlen((char *)pkt) + 1);
303 TftpState = STATE_OACK;
304 TftpServerPort = src;
306 * Check for 'blksize' option.
307 * Careful: "i" is signed, "len" is unsigned, thus
308 * something like "len-8" may give a *huge* number
310 for (i=0; i+8<len; i++) {
311 if (strcmp ((char*)pkt+i,"blksize") == 0) {
312 TftpBlkSize = (unsigned short)
313 simple_strtoul((char*)pkt+i+8,NULL,10);
314 debug("Blocksize ack: %s, %d\n",
315 (char*)pkt+i+8,TftpBlkSize);
319 #ifdef CONFIG_MCAST_TFTP
320 parse_multicast_oack((char *)pkt,len-1);
321 if ((Multicast) && (!MasterClient))
322 TftpState = STATE_DATA; /* passive.. */
325 TftpSend (); /* Send ACK */
331 TftpBlock = ntohs(*(ushort *)pkt);
334 * RFC1350 specifies that the first data packet will
335 * have sequence number 1. If we receive a sequence
336 * number of 0 this means that there was a wrap
337 * around of the (16 bit) counter.
339 if (TftpBlock == 0) {
341 TftpBlockWrapOffset += TftpBlkSize * TFTP_SEQUENCE_SIZE;
342 printf ("\n\t %lu MB received\n\t ", TftpBlockWrapOffset>>20);
344 if (((TftpBlock - 1) % 10) == 0) {
346 } else if ((TftpBlock % (10 * HASHES_PER_LINE)) == 0) {
351 if (TftpState == STATE_RRQ)
352 debug("Server did not acknowledge timeout option!\n");
354 if (TftpState == STATE_RRQ || TftpState == STATE_OACK) {
355 /* first block received */
356 TftpState = STATE_DATA;
357 TftpServerPort = src;
360 TftpBlockWrapOffset = 0;
362 #ifdef CONFIG_MCAST_TFTP
363 if (Multicast) { /* start!=1 common if mcast */
364 TftpLastBlock = TftpBlock - 1;
367 if (TftpBlock != 1) { /* Assertion */
368 printf ("\nTFTP error: "
369 "First block is not block 1 (%ld)\n"
370 "Starting again\n\n",
377 if (TftpBlock == TftpLastBlock) {
379 * Same block again; ignore it.
384 TftpLastBlock = TftpBlock;
385 TftpTimeoutMSecs = TIMEOUT;
386 TftpTimeoutCountMax = TIMEOUT_COUNT;
387 NetSetTimeout (TftpTimeoutMSecs, TftpTimeout);
389 store_block (TftpBlock - 1, pkt + 2, len);
392 * Acknoledge the block just received, which will prompt
393 * the server for the next one.
395 #ifdef CONFIG_MCAST_TFTP
396 /* if I am the MasterClient, actively calculate what my next
397 * needed block is; else I'm passive; not ACKING
400 if (len < TftpBlkSize) {
401 TftpEndingBlock = TftpBlock;
402 } else if (MasterClient) {
403 TftpBlock = PrevBitmapHole =
404 ext2_find_next_zero_bit(
408 if (TftpBlock > ((Mapsize*8) - 1)) {
409 printf ("tftpfile too big\n");
410 /* try to double it and retry */
416 TftpLastBlock = TftpBlock;
422 #ifdef CONFIG_MCAST_TFTP
424 if (MasterClient && (TftpBlock >= TftpEndingBlock)) {
425 puts ("\nMulticast tftp done\n");
427 NetState = NETLOOP_SUCCESS;
432 if (len < TftpBlkSize) {
434 * We received the whole thing. Try to
438 NetState = NETLOOP_SUCCESS;
443 printf ("\nTFTP error: '%s' (%d)\n",
444 pkt + 2, ntohs(*(ushort *)pkt));
445 puts ("Starting again\n\n");
446 #ifdef CONFIG_MCAST_TFTP
458 if (++TftpTimeoutCount > TftpTimeoutCountMax) {
459 puts ("\nRetry count exceeded; starting again\n");
460 #ifdef CONFIG_MCAST_TFTP
466 NetSetTimeout (TftpTimeoutMSecs, TftpTimeout);
475 char *ep; /* Environment pointer */
477 /* Allow the user to choose tftpblocksize */
478 if ((ep = getenv("tftpblocksize")) != NULL)
479 TftpBlkSizeOption = simple_strtol(ep, NULL, 10);
480 debug("tftp block size is %i\n", TftpBlkSizeOption);
482 TftpServerIP = NetServerIP;
483 if (BootFile[0] == '\0') {
484 sprintf(default_filename, "%02lX%02lX%02lX%02lX.img",
486 (NetOurIP >> 8) & 0xFF,
487 (NetOurIP >> 16) & 0xFF,
488 (NetOurIP >> 24) & 0xFF );
490 strncpy(tftp_filename, default_filename, MAX_LEN);
491 tftp_filename[MAX_LEN-1] = 0;
493 printf ("*** Warning: no boot file name; using '%s'\n",
496 char *p = strchr (BootFile, ':');
499 strncpy(tftp_filename, BootFile, MAX_LEN);
500 tftp_filename[MAX_LEN-1] = 0;
502 TftpServerIP = string_to_ip (BootFile);
503 strncpy(tftp_filename, p + 1, MAX_LEN);
504 tftp_filename[MAX_LEN-1] = 0;
508 #if defined(CONFIG_NET_MULTI)
509 printf ("Using %s device\n", eth_get_name());
511 printf("TFTP from server %pI4"
512 "; our IP address is %pI4", &TftpServerIP, &NetOurIP);
514 /* Check if we need to send across this subnet */
515 if (NetOurGatewayIP && NetOurSubnetMask) {
516 IPaddr_t OurNet = NetOurIP & NetOurSubnetMask;
517 IPaddr_t ServerNet = TftpServerIP & NetOurSubnetMask;
519 if (OurNet != ServerNet)
520 printf("; sending through gateway %pI4", &NetOurGatewayIP);
524 printf ("Filename '%s'.", tftp_filename);
526 if (NetBootFileSize) {
527 printf (" Size is 0x%x Bytes = ", NetBootFileSize<<9);
528 print_size (NetBootFileSize<<9, "");
533 printf ("Load address: 0x%lx\n", load_addr);
535 puts ("Loading: *\b");
537 TftpTimeoutMSecs = TftpRRQTimeoutMSecs;
538 TftpTimeoutCountMax = TftpRRQTimeoutCountMax;
540 NetSetTimeout (TftpTimeoutMSecs, TftpTimeout);
541 NetSetHandler (TftpHandler);
543 TftpServerPort = WELL_KNOWN_PORT;
544 TftpTimeoutCount = 0;
545 TftpState = STATE_RRQ;
546 /* Use a pseudo-random port unless a specific port is set */
547 TftpOurPort = 1024 + (get_timer(0) % 3072);
549 #ifdef CONFIG_TFTP_PORT
550 if ((ep = getenv("tftpdstp")) != NULL) {
551 TftpServerPort = simple_strtol(ep, NULL, 10);
553 if ((ep = getenv("tftpsrcp")) != NULL) {
554 TftpOurPort= simple_strtol(ep, NULL, 10);
559 /* zero out server ether in case the server ip has changed */
560 memset(NetServerEther, 0, 6);
561 /* Revert TftpBlkSize to dflt */
562 TftpBlkSize = TFTP_BLOCK_SIZE;
563 #ifdef CONFIG_MCAST_TFTP
570 #ifdef CONFIG_MCAST_TFTP
571 /* Credits: atftp project.
574 /* pick up BcastAddr, Port, and whether I am [now] the master-client. *
576 * +-------+-----------+---+-------~~-------+---+
577 * | opc | multicast | 0 | addr, port, mc | 0 |
578 * +-------+-----------+---+-------~~-------+---+
579 * The multicast addr/port becomes what I listen to, and if 'mc' is '1' then
580 * I am the new master-client so must send ACKs to DataBlocks. If I am not
581 * master-client, I'm a passive client, gathering what DataBlocks I may and
582 * making note of which ones I got in my bitmask.
583 * In theory, I never go from master->passive..
584 * .. this comes in with pkt already pointing just past opc
586 static void parse_multicast_oack(char *pkt, int len)
590 char *mc_adr, *port, *mc;
593 /* march along looking for 'multicast\0', which has to start at least
594 * 14 bytes back from the end.
596 for (i=0;i<len-14;i++)
597 if (strcmp (pkt+i,"multicast") == 0)
599 if (i >= (len-14)) /* non-Multicast OACK, ign. */
602 i+=10; /* strlen multicast */
605 if (*(pkt+i) == ',') {
615 if (!port || !mc_adr || !mc ) return;
616 if (Multicast && MasterClient) {
617 printf ("I got a OACK as master Client, WRONG!\n");
620 /* ..I now accept packets destined for this MCAST addr, port */
623 printf ("Internal failure! no mcast.\n");
629 /* I malloc instead of pre-declare; so that if the file ends
630 * up being too big for this bitmap I can retry
632 if (!(Bitmap = malloc (Mapsize))) {
633 printf ("No Bitmap, no multicast. Sorry.\n");
637 memset (Bitmap,0,Mapsize);
641 addr = string_to_ip(mc_adr);
642 if (Mcast_addr != addr) {
644 eth_mcast_join(Mcast_addr, 0);
645 if (eth_mcast_join(Mcast_addr=addr, 1)) {
646 printf ("Fail to set mcast, revert to TFTP\n");
652 MasterClient = (unsigned char)simple_strtoul((char *)mc,NULL,10);
653 Mcast_port = (unsigned short)simple_strtoul(port,NULL,10);
654 printf ("Multicast: %s:%d [%d]\n", mc_adr, Mcast_port, MasterClient);
658 #endif /* Multicast TFTP */