tftp.c: fix CONFIG_TFTP_TSIZE for small files
[karo-tx-uboot.git] / net / tftp.c
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
9 #include <common.h>
10 #include <command.h>
11 #include <mapmem.h>
12 #include <net.h>
13 #include "tftp.h"
14 #include "bootp.h"
15 #ifdef CONFIG_SYS_DIRECT_FLASH_TFTP
16 #include <flash.h>
17 #endif
18
19 /* Well known TFTP port # */
20 #define WELL_KNOWN_PORT 69
21 /* Millisecs to timeout for lost pkt */
22 #define TIMEOUT         5000UL
23 #ifndef CONFIG_NET_RETRY_COUNT
24 /* # of timeouts before giving up */
25 # define TIMEOUT_COUNT  10
26 #else
27 # define TIMEOUT_COUNT  (CONFIG_NET_RETRY_COUNT * 2)
28 #endif
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
42 static ulong timeout_ms = TIMEOUT;
43 static int timeout_count_max = TIMEOUT_COUNT;
44 static ulong time_start;   /* Record time we started tftp */
45
46 /*
47  * These globals govern the timeout behavior when attempting a connection to a
48  * TFTP server. tftp_timeout_ms specifies the number of milliseconds to
49  * wait for the server to respond to initial connection. Second global,
50  * tftp_timeout_count_max, gives the number of such connection retries.
51  * tftp_timeout_count_max must be non-negative and tftp_timeout_ms must be
52  * positive. The globals are meant to be set (and restored) by code needing
53  * non-standard timeout behavior when initiating a TFTP transfer.
54  */
55 ulong tftp_timeout_ms = TIMEOUT;
56 int tftp_timeout_count_max = TIMEOUT_COUNT;
57
58 enum {
59         TFTP_ERR_UNDEFINED           = 0,
60         TFTP_ERR_FILE_NOT_FOUND      = 1,
61         TFTP_ERR_ACCESS_DENIED       = 2,
62         TFTP_ERR_DISK_FULL           = 3,
63         TFTP_ERR_UNEXPECTED_OPCODE   = 4,
64         TFTP_ERR_UNKNOWN_TRANSFER_ID  = 5,
65         TFTP_ERR_FILE_ALREADY_EXISTS = 6,
66 };
67
68 static struct in_addr tftp_remote_ip;
69 /* The UDP port at their end */
70 static int      tftp_remote_port;
71 /* The UDP port at our end */
72 static int      tftp_our_port;
73 static int      timeout_count;
74 /* packet sequence number */
75 static ulong    tftp_cur_block;
76 /* last packet sequence number received */
77 static ulong    tftp_prev_block;
78 /* count of sequence number wraparounds */
79 static ulong    tftp_block_wrap;
80 /* memory offset due to wrapping */
81 static ulong    tftp_block_wrap_offset;
82 static int      tftp_state;
83 #ifdef CONFIG_TFTP_TSIZE
84 /* The file size reported by the server */
85 static int      tftp_tsize;
86 /* The number of hashes we printed */
87 static short    tftp_tsize_num_hash;
88 #endif
89 #ifdef CONFIG_CMD_TFTPPUT
90 /* 1 if writing, else 0 */
91 static int      tftp_put_active;
92 /* 1 if we have sent the last block */
93 static int      tftp_put_final_block_sent;
94 #else
95 #define tftp_put_active 0
96 #endif
97
98 #define STATE_SEND_RRQ  1
99 #define STATE_DATA      2
100 #define STATE_TOO_LARGE 3
101 #define STATE_BAD_MAGIC 4
102 #define STATE_OACK      5
103 #define STATE_RECV_WRQ  6
104 #define STATE_SEND_WRQ  7
105
106 /* default TFTP block size */
107 #define TFTP_BLOCK_SIZE         512
108 /* sequence number is 16 bit */
109 #define TFTP_SEQUENCE_SIZE      ((ulong)(1<<16))
110
111 #define DEFAULT_NAME_LEN        (8 + 4 + 1)
112 static char default_filename[DEFAULT_NAME_LEN];
113
114 #ifndef CONFIG_TFTP_FILE_NAME_MAX_LEN
115 #define MAX_LEN 128
116 #else
117 #define MAX_LEN CONFIG_TFTP_FILE_NAME_MAX_LEN
118 #endif
119
120 static char tftp_filename[MAX_LEN];
121
122 /* 512 is poor choice for ethernet, MTU is typically 1500.
123  * Minus eth.hdrs thats 1468.  Can get 2x better throughput with
124  * almost-MTU block sizes.  At least try... fall back to 512 if need be.
125  * (but those using CONFIG_IP_DEFRAG may want to set a larger block in cfg file)
126  */
127 #ifdef CONFIG_TFTP_BLOCKSIZE
128 #define TFTP_MTU_BLOCKSIZE CONFIG_TFTP_BLOCKSIZE
129 #else
130 #define TFTP_MTU_BLOCKSIZE 1468
131 #endif
132
133 static unsigned short tftp_block_size = TFTP_BLOCK_SIZE;
134 static unsigned short tftp_block_size_option = TFTP_MTU_BLOCKSIZE;
135
136 #ifdef CONFIG_MCAST_TFTP
137 #include <malloc.h>
138 #define MTFTP_BITMAPSIZE        0x1000
139 static unsigned *tftp_mcast_bitmap;
140 static int tftp_mcast_prev_hole;
141 static int tftp_mcast_bitmap_size = MTFTP_BITMAPSIZE;
142 static int tftp_mcast_disabled;
143 static int tftp_mcast_master_client;
144 static int tftp_mcast_active;
145 static int tftp_mcast_port;
146 /* can get 'last' block before done..*/
147 static ulong tftp_mcast_ending_block;
148
149 static void parse_multicast_oack(char *pkt, int len);
150
151 static void mcast_cleanup(void)
152 {
153         if (net_mcast_addr)
154                 eth_mcast_join(net_mcast_addr, 0);
155         if (tftp_mcast_bitmap)
156                 free(tftp_mcast_bitmap);
157         tftp_mcast_bitmap = NULL;
158         net_mcast_addr.s_addr = 0;
159         tftp_mcast_active = 0;
160         tftp_mcast_port = 0;
161         tftp_mcast_ending_block = -1;
162 }
163
164 #endif  /* CONFIG_MCAST_TFTP */
165
166 static inline void store_block(int block, uchar *src, unsigned len)
167 {
168         ulong offset = block * tftp_block_size + tftp_block_wrap_offset;
169         ulong newsize = offset + len;
170 #ifdef CONFIG_SYS_DIRECT_FLASH_TFTP
171         int i, rc = 0;
172
173         for (i = 0; i < CONFIG_SYS_MAX_FLASH_BANKS; i++) {
174                 /* start address in flash? */
175                 if (flash_info[i].flash_id == FLASH_UNKNOWN)
176                         continue;
177                 if (load_addr + offset >= flash_info[i].start[0]) {
178                         rc = 1;
179                         break;
180                 }
181         }
182
183         if (rc) { /* Flash is destination for this packet */
184                 rc = flash_write((char *)src, (ulong)(load_addr+offset), len);
185                 if (rc) {
186                         flash_perror(rc);
187                         net_set_state(NETLOOP_FAIL);
188                         return;
189                 }
190         } else
191 #endif /* CONFIG_SYS_DIRECT_FLASH_TFTP */
192         {
193                 void *ptr = map_sysmem(load_addr + offset, len);
194
195                 memcpy(ptr, src, len);
196                 unmap_sysmem(ptr);
197         }
198 #ifdef CONFIG_MCAST_TFTP
199         if (tftp_mcast_active)
200                 ext2_set_bit(block, tftp_mcast_bitmap);
201 #endif
202
203         if (net_boot_file_size < newsize)
204                 net_boot_file_size = newsize;
205 }
206
207 /* Clear our state ready for a new transfer */
208 static void new_transfer(void)
209 {
210         tftp_prev_block = 0;
211         tftp_block_wrap = 0;
212         tftp_block_wrap_offset = 0;
213 #ifdef CONFIG_CMD_TFTPPUT
214         tftp_put_final_block_sent = 0;
215 #endif
216 }
217
218 #ifdef CONFIG_CMD_TFTPPUT
219 /**
220  * Load the next block from memory to be sent over tftp.
221  *
222  * @param block Block number to send
223  * @param dst   Destination buffer for data
224  * @param len   Number of bytes in block (this one and every other)
225  * @return number of bytes loaded
226  */
227 static int load_block(unsigned block, uchar *dst, unsigned len)
228 {
229         /* We may want to get the final block from the previous set */
230         ulong offset = ((int)block - 1) * len + tftp_block_wrap_offset;
231         ulong tosend = len;
232
233         tosend = min(net_boot_file_size - offset, tosend);
234         (void)memcpy(dst, (void *)(save_addr + offset), tosend);
235         debug("%s: block=%d, offset=%ld, len=%d, tosend=%ld\n", __func__,
236               block, offset, len, tosend);
237         return tosend;
238 }
239 #endif
240
241 static void tftp_send(void);
242 static void tftp_timeout_handler(void);
243
244 /**********************************************************************/
245
246 static void show_block_marker(void)
247 {
248 #ifdef CONFIG_TFTP_TSIZE
249         if (tftp_tsize) {
250                 ulong pos = tftp_cur_block * tftp_block_size +
251                         tftp_block_wrap_offset;
252                 if (pos > tftp_tsize)
253                         pos = tftp_tsize;
254
255                 while (tftp_tsize_num_hash < pos * 50 / tftp_tsize) {
256                         putc('#');
257                         tftp_tsize_num_hash++;
258                 }
259         } else
260 #endif
261         {
262                 if (((tftp_cur_block - 1) % 10) == 0)
263                         putc('#');
264                 else if ((tftp_cur_block % (10 * HASHES_PER_LINE)) == 0)
265                         puts("\n\t ");
266         }
267 }
268
269 /**
270  * restart the current transfer due to an error
271  *
272  * @param msg   Message to print for user
273  */
274 static void restart(const char *msg)
275 {
276         printf("\n%s; starting again\n", msg);
277 #ifdef CONFIG_MCAST_TFTP
278         mcast_cleanup();
279 #endif
280         net_start_again();
281 }
282
283 /*
284  * Check if the block number has wrapped, and update progress
285  *
286  * TODO: The egregious use of global variables in this file should be tidied.
287  */
288 static void update_block_number(void)
289 {
290         /*
291          * RFC1350 specifies that the first data packet will
292          * have sequence number 1. If we receive a sequence
293          * number of 0 this means that there was a wrap
294          * around of the (16 bit) counter.
295          */
296         if (tftp_cur_block == 0 && tftp_prev_block != 0) {
297                 tftp_block_wrap++;
298                 tftp_block_wrap_offset += tftp_block_size * TFTP_SEQUENCE_SIZE;
299                 timeout_count = 0; /* we've done well, reset the timeout */
300         } else {
301                 show_block_marker();
302         }
303 }
304
305 /* The TFTP get or put is complete */
306 static void tftp_complete(void)
307 {
308 #ifdef CONFIG_TFTP_TSIZE
309         /* Print hash marks for the last packet received */
310         while (tftp_tsize && tftp_tsize_num_hash < 49) {
311                 putc('#');
312                 tftp_tsize_num_hash++;
313         }
314         puts("  ");
315         print_size(tftp_tsize, "");
316 #endif
317         time_start = get_timer(time_start);
318         if (time_start > 0) {
319                 puts("\n\t ");  /* Line up with "Loading: " */
320                 print_size(net_boot_file_size /
321                         time_start * 1000, "/s");
322         }
323         puts("\ndone\n");
324         net_set_state(NETLOOP_SUCCESS);
325 }
326
327 static void tftp_send(void)
328 {
329         uchar *pkt;
330         uchar *xp;
331         int len = 0;
332         ushort *s;
333
334 #ifdef CONFIG_MCAST_TFTP
335         /* Multicast TFTP.. non-MasterClients do not ACK data. */
336         if (tftp_mcast_active && tftp_state == STATE_DATA &&
337             tftp_mcast_master_client == 0)
338                 return;
339 #endif
340         /*
341          *      We will always be sending some sort of packet, so
342          *      cobble together the packet headers now.
343          */
344         pkt = net_tx_packet + net_eth_hdr_size() + IP_UDP_HDR_SIZE;
345
346         switch (tftp_state) {
347         case STATE_SEND_RRQ:
348         case STATE_SEND_WRQ:
349                 xp = pkt;
350                 s = (ushort *)pkt;
351 #ifdef CONFIG_CMD_TFTPPUT
352                 *s++ = htons(tftp_state == STATE_SEND_RRQ ? TFTP_RRQ :
353                         TFTP_WRQ);
354 #else
355                 *s++ = htons(TFTP_RRQ);
356 #endif
357                 pkt = (uchar *)s;
358                 strcpy((char *)pkt, tftp_filename);
359                 pkt += strlen(tftp_filename) + 1;
360                 strcpy((char *)pkt, "octet");
361                 pkt += 5 /*strlen("octet")*/ + 1;
362                 strcpy((char *)pkt, "timeout");
363                 pkt += 7 /*strlen("timeout")*/ + 1;
364                 sprintf((char *)pkt, "%lu", timeout_ms / 1000);
365                 debug("send option \"timeout %s\"\n", (char *)pkt);
366                 pkt += strlen((char *)pkt) + 1;
367 #ifdef CONFIG_TFTP_TSIZE
368                 pkt += sprintf((char *)pkt, "tsize%c%u%c",
369                                 0, net_boot_file_size, 0);
370 #endif
371                 /* try for more effic. blk size */
372                 pkt += sprintf((char *)pkt, "blksize%c%d%c",
373                                 0, tftp_block_size_option, 0);
374 #ifdef CONFIG_MCAST_TFTP
375                 /* Check all preconditions before even trying the option */
376                 if (!tftp_mcast_disabled) {
377                         tftp_mcast_bitmap = malloc(tftp_mcast_bitmap_size);
378                         if (tftp_mcast_bitmap && eth_get_dev()->mcast) {
379                                 free(tftp_mcast_bitmap);
380                                 tftp_mcast_bitmap = NULL;
381                                 pkt += sprintf((char *)pkt, "multicast%c%c",
382                                         0, 0);
383                         }
384                 }
385 #endif /* CONFIG_MCAST_TFTP */
386                 len = pkt - xp;
387                 break;
388
389         case STATE_OACK:
390 #ifdef CONFIG_MCAST_TFTP
391                 /* My turn!  Start at where I need blocks I missed. */
392                 if (tftp_mcast_active)
393                         tftp_cur_block = ext2_find_next_zero_bit(
394                                 tftp_mcast_bitmap,
395                                 tftp_mcast_bitmap_size * 8, 0);
396                 /* fall through */
397 #endif
398
399         case STATE_RECV_WRQ:
400         case STATE_DATA:
401                 xp = pkt;
402                 s = (ushort *)pkt;
403                 s[0] = htons(TFTP_ACK);
404                 s[1] = htons(tftp_cur_block);
405                 pkt = (uchar *)(s + 2);
406 #ifdef CONFIG_CMD_TFTPPUT
407                 if (tftp_put_active) {
408                         int toload = tftp_block_size;
409                         int loaded = load_block(tftp_cur_block, pkt, toload);
410
411                         s[0] = htons(TFTP_DATA);
412                         pkt += loaded;
413                         tftp_put_final_block_sent = (loaded < toload);
414                 }
415 #endif
416                 len = pkt - xp;
417                 break;
418
419         case STATE_TOO_LARGE:
420                 xp = pkt;
421                 s = (ushort *)pkt;
422                 *s++ = htons(TFTP_ERROR);
423                         *s++ = htons(3);
424
425                 pkt = (uchar *)s;
426                 strcpy((char *)pkt, "File too large");
427                 pkt += 14 /*strlen("File too large")*/ + 1;
428                 len = pkt - xp;
429                 break;
430
431         case STATE_BAD_MAGIC:
432                 xp = pkt;
433                 s = (ushort *)pkt;
434                 *s++ = htons(TFTP_ERROR);
435                 *s++ = htons(2);
436                 pkt = (uchar *)s;
437                 strcpy((char *)pkt, "File has bad magic");
438                 pkt += 18 /*strlen("File has bad magic")*/ + 1;
439                 len = pkt - xp;
440                 break;
441         }
442
443         net_send_udp_packet(net_server_ethaddr, tftp_remote_ip,
444                             tftp_remote_port, tftp_our_port, len);
445 }
446
447 #ifdef CONFIG_CMD_TFTPPUT
448 static void icmp_handler(unsigned type, unsigned code, unsigned dest,
449                          struct in_addr sip, unsigned src, uchar *pkt,
450                          unsigned len)
451 {
452         if (type == ICMP_NOT_REACH && code == ICMP_NOT_REACH_PORT) {
453                 /* Oh dear the other end has gone away */
454                 restart("TFTP server died");
455         }
456 }
457 #endif
458
459 static void tftp_handler(uchar *pkt, unsigned dest, struct in_addr sip,
460                          unsigned src, unsigned len)
461 {
462         __be16 proto;
463         __be16 *s;
464         int i;
465
466         if (dest != tftp_our_port) {
467 #ifdef CONFIG_MCAST_TFTP
468                 if (tftp_mcast_active &&
469                     (!tftp_mcast_port || dest != tftp_mcast_port))
470 #endif
471                         return;
472         }
473         if (tftp_state != STATE_SEND_RRQ && src != tftp_remote_port &&
474             tftp_state != STATE_RECV_WRQ && tftp_state != STATE_SEND_WRQ)
475                 return;
476
477         if (len < 2)
478                 return;
479         len -= 2;
480         /* warning: don't use increment (++) in ntohs() macros!! */
481         s = (__be16 *)pkt;
482         proto = *s++;
483         pkt = (uchar *)s;
484         switch (ntohs(proto)) {
485         case TFTP_RRQ:
486                 break;
487
488         case TFTP_ACK:
489 #ifdef CONFIG_CMD_TFTPPUT
490                 if (tftp_put_active) {
491                         if (tftp_put_final_block_sent) {
492                                 tftp_complete();
493                         } else {
494                                 /*
495                                  * Move to the next block. We want our block
496                                  * count to wrap just like the other end!
497                                  */
498                                 int block = ntohs(*s);
499                                 int ack_ok = (tftp_cur_block == block);
500
501                                 tftp_cur_block = (unsigned short)(block + 1);
502                                 update_block_number();
503                                 if (ack_ok)
504                                         tftp_send(); /* Send next data block */
505                         }
506                 }
507 #endif
508                 break;
509
510         default:
511                 break;
512
513 #ifdef CONFIG_CMD_TFTPSRV
514         case TFTP_WRQ:
515                 debug("Got WRQ\n");
516                 tftp_remote_ip = sip;
517                 tftp_remote_port = src;
518                 tftp_our_port = 1024 + (get_timer(0) % 3072);
519                 new_transfer();
520                 tftp_send(); /* Send ACK(0) */
521                 break;
522 #endif
523
524         case TFTP_OACK:
525                 debug("Got OACK: %s %s\n",
526                       pkt, pkt + strlen((char *)pkt) + 1);
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 (strcmp((char *)pkt + i, "blksize") == 0) {
536                                 tftp_block_size = (unsigned short)
537                                         simple_strtoul((char *)pkt + i + 8,
538                                                        NULL, 10);
539                                 debug("Blocksize ack: %s, %d\n",
540                                       (char *)pkt + i + 8, tftp_block_size);
541                         }
542 #ifdef CONFIG_TFTP_TSIZE
543                         if (strcmp((char *)pkt+i, "tsize") == 0) {
544                                 tftp_tsize = simple_strtoul((char *)pkt + i + 6,
545                                                            NULL, 10);
546                                 debug("size = %s, %d\n",
547                                       (char *)pkt + i + 6, tftp_tsize);
548                         }
549 #endif
550                 }
551 #ifdef CONFIG_MCAST_TFTP
552                 parse_multicast_oack((char *)pkt, len - 1);
553                 if ((tftp_mcast_active) && (!tftp_mcast_master_client))
554                         tftp_state = STATE_DATA;        /* passive.. */
555                 else
556 #endif
557 #ifdef CONFIG_CMD_TFTPPUT
558                 if (tftp_put_active) {
559                         /* Get ready to send the first block */
560                         tftp_state = STATE_DATA;
561                         tftp_cur_block++;
562                 }
563 #endif
564                 tftp_send(); /* Send ACK or first data block */
565                 break;
566         case TFTP_DATA:
567                 if (len < 2)
568                         return;
569                 len -= 2;
570                 tftp_cur_block = ntohs(*(__be16 *)pkt);
571
572                 update_block_number();
573
574                 if (tftp_state == STATE_SEND_RRQ)
575                         debug("Server did not acknowledge timeout option!\n");
576
577                 if (tftp_state == STATE_SEND_RRQ || tftp_state == STATE_OACK ||
578                     tftp_state == STATE_RECV_WRQ) {
579                         /* first block received */
580                         tftp_state = STATE_DATA;
581                         tftp_remote_port = src;
582                         new_transfer();
583
584 #ifdef CONFIG_MCAST_TFTP
585                         if (tftp_mcast_active) { /* start!=1 common if mcast */
586                                 tftp_prev_block = tftp_cur_block - 1;
587                         } else
588 #endif
589                         if (tftp_cur_block != 1) {      /* Assertion */
590                                 puts("\nTFTP error: ");
591                                 printf("First block is not block 1 (%ld)\n",
592                                        tftp_cur_block);
593                                 puts("Starting again\n\n");
594                                 net_start_again();
595                                 break;
596                         }
597                 }
598
599                 if (tftp_cur_block == tftp_prev_block) {
600                         /* Same block again; ignore it. */
601                         break;
602                 }
603
604                 tftp_prev_block = tftp_cur_block;
605                 timeout_count_max = TIMEOUT_COUNT;
606                 net_set_timeout_handler(timeout_ms, tftp_timeout_handler);
607
608                 store_block(tftp_cur_block - 1, pkt + 2, len);
609
610                 /*
611                  *      Acknowledge the block just received, which will prompt
612                  *      the remote for the next one.
613                  */
614 #ifdef CONFIG_MCAST_TFTP
615                 /* if I am the MasterClient, actively calculate what my next
616                  * needed block is; else I'm passive; not ACKING
617                  */
618                 if (tftp_mcast_active) {
619                         if (len < tftp_block_size)  {
620                                 tftp_mcast_ending_block = tftp_cur_block;
621                         } else if (tftp_mcast_master_client) {
622                                 tftp_mcast_prev_hole = ext2_find_next_zero_bit(
623                                         tftp_mcast_bitmap,
624                                         tftp_mcast_bitmap_size * 8,
625                                         tftp_mcast_prev_hole);
626                                 tftp_cur_block = tftp_mcast_prev_hole;
627                                 if (tftp_cur_block >
628                                     ((tftp_mcast_bitmap_size * 8) - 1)) {
629                                         debug("tftpfile too big\n");
630                                         /* try to double it and retry */
631                                         tftp_mcast_bitmap_size <<= 1;
632                                         mcast_cleanup();
633                                         net_start_again();
634                                         return;
635                                 }
636                                 tftp_prev_block = tftp_cur_block;
637                         }
638                 }
639 #endif
640                 tftp_send();
641
642 #ifdef CONFIG_MCAST_TFTP
643                 if (tftp_mcast_active) {
644                         if (tftp_mcast_master_client &&
645                             (tftp_cur_block >= tftp_mcast_ending_block)) {
646                                 puts("\nMulticast tftp done\n");
647                                 mcast_cleanup();
648                                 net_set_state(NETLOOP_SUCCESS);
649                         }
650                 } else
651 #endif
652                 if (len < tftp_block_size)
653                         tftp_complete();
654                 break;
655
656         case TFTP_ERROR:
657                 printf("\nTFTP error: '%s' (%d)\n",
658                        pkt + 2, ntohs(*(__be16 *)pkt));
659
660                 switch (ntohs(*(__be16 *)pkt)) {
661                 case TFTP_ERR_FILE_NOT_FOUND:
662                 case TFTP_ERR_ACCESS_DENIED:
663                         puts("Not retrying...\n");
664                         eth_halt();
665                         net_set_state(NETLOOP_FAIL);
666                         break;
667                 case TFTP_ERR_UNDEFINED:
668                 case TFTP_ERR_DISK_FULL:
669                 case TFTP_ERR_UNEXPECTED_OPCODE:
670                 case TFTP_ERR_UNKNOWN_TRANSFER_ID:
671                 case TFTP_ERR_FILE_ALREADY_EXISTS:
672                 default:
673                         puts("Starting again\n\n");
674 #ifdef CONFIG_MCAST_TFTP
675                         mcast_cleanup();
676 #endif
677                         net_start_again();
678                         break;
679                 }
680                 break;
681         }
682 }
683
684
685 static void tftp_timeout_handler(void)
686 {
687         if (++timeout_count > timeout_count_max) {
688                 restart("Retry count exceeded");
689         } else {
690                 puts("T ");
691                 net_set_timeout_handler(timeout_ms, tftp_timeout_handler);
692                 if (tftp_state != STATE_RECV_WRQ)
693                         tftp_send();
694         }
695 }
696
697
698 void tftp_start(enum proto_t protocol)
699 {
700         char *ep;             /* Environment pointer */
701
702         /*
703          * Allow the user to choose TFTP blocksize and timeout.
704          * TFTP protocol has a minimal timeout of 1 second.
705          */
706         ep = getenv("tftpblocksize");
707         if (ep != NULL)
708                 tftp_block_size_option = simple_strtol(ep, NULL, 10);
709
710         ep = getenv("tftptimeout");
711         if (ep != NULL)
712                 timeout_ms = simple_strtol(ep, NULL, 10);
713
714         if (timeout_ms < 1000) {
715                 printf("TFTP timeout (%ld ms) too low, set min = 1000 ms\n",
716                        timeout_ms);
717                 timeout_ms = 1000;
718         }
719
720         debug("TFTP blocksize = %i, timeout = %ld ms\n",
721               tftp_block_size_option, timeout_ms);
722
723         tftp_remote_ip = net_server_ip;
724         if (net_boot_file_name[0] == '\0') {
725                 sprintf(default_filename, "%02X%02X%02X%02X.img",
726                         net_ip.s_addr & 0xFF,
727                         (net_ip.s_addr >>  8) & 0xFF,
728                         (net_ip.s_addr >> 16) & 0xFF,
729                         (net_ip.s_addr >> 24) & 0xFF);
730
731                 strncpy(tftp_filename, default_filename, MAX_LEN);
732                 tftp_filename[MAX_LEN - 1] = 0;
733
734                 printf("*** Warning: no boot file name; using '%s'\n",
735                        tftp_filename);
736         } else {
737                 char *p = strchr(net_boot_file_name, ':');
738
739                 if (p == NULL) {
740                         strncpy(tftp_filename, net_boot_file_name, MAX_LEN);
741                         tftp_filename[MAX_LEN - 1] = 0;
742                 } else {
743                         tftp_remote_ip = string_to_ip(net_boot_file_name);
744                         strncpy(tftp_filename, p + 1, MAX_LEN);
745                         tftp_filename[MAX_LEN - 1] = 0;
746                 }
747         }
748
749         printf("Using %s device\n", eth_get_name());
750         printf("TFTP %s server %pI4; our IP address is %pI4",
751 #ifdef CONFIG_CMD_TFTPPUT
752                protocol == TFTPPUT ? "to" : "from",
753 #else
754                "from",
755 #endif
756                &tftp_remote_ip, &net_ip);
757
758         /* Check if we need to send across this subnet */
759         if (net_gateway.s_addr && net_netmask.s_addr) {
760                 struct in_addr our_net;
761                 struct in_addr remote_net;
762
763                 our_net.s_addr = net_ip.s_addr & net_netmask.s_addr;
764                 remote_net.s_addr = tftp_remote_ip.s_addr & net_netmask.s_addr;
765                 if (our_net.s_addr != remote_net.s_addr)
766                         printf("; sending through gateway %pI4", &net_gateway);
767         }
768         putc('\n');
769
770         printf("Filename '%s'.", tftp_filename);
771
772         if (net_boot_file_expected_size_in_blocks) {
773                 printf(" Size is 0x%x Bytes = ",
774                        net_boot_file_expected_size_in_blocks << 9);
775                 print_size(net_boot_file_expected_size_in_blocks << 9, "");
776         }
777
778         putc('\n');
779 #ifdef CONFIG_CMD_TFTPPUT
780         tftp_put_active = (protocol == TFTPPUT);
781         if (tftp_put_active) {
782                 printf("Save address: 0x%lx\n", save_addr);
783                 printf("Save size:    0x%lx\n", save_size);
784                 net_boot_file_size = save_size;
785                 puts("Saving: *\b");
786                 tftp_state = STATE_SEND_WRQ;
787                 new_transfer();
788         } else
789 #endif
790         {
791                 printf("Load address: 0x%lx\n", load_addr);
792                 puts("Loading: *\b");
793                 tftp_state = STATE_SEND_RRQ;
794         }
795
796         time_start = get_timer(0);
797         timeout_count_max = tftp_timeout_count_max;
798
799         net_set_timeout_handler(timeout_ms, tftp_timeout_handler);
800         net_set_udp_handler(tftp_handler);
801 #ifdef CONFIG_CMD_TFTPPUT
802         net_set_icmp_handler(icmp_handler);
803 #endif
804         tftp_remote_port = WELL_KNOWN_PORT;
805         timeout_count = 0;
806         /* Use a pseudo-random port unless a specific port is set */
807         tftp_our_port = 1024 + (get_timer(0) % 3072);
808
809 #ifdef CONFIG_TFTP_PORT
810         ep = getenv("tftpdstp");
811         if (ep != NULL)
812                 tftp_remote_port = simple_strtol(ep, NULL, 10);
813         ep = getenv("tftpsrcp");
814         if (ep != NULL)
815                 tftp_our_port = simple_strtol(ep, NULL, 10);
816 #endif
817         tftp_cur_block = 0;
818
819         /* zero out server ether in case the server ip has changed */
820         memset(net_server_ethaddr, 0, 6);
821         /* Revert tftp_block_size to dflt */
822         tftp_block_size = TFTP_BLOCK_SIZE;
823 #ifdef CONFIG_MCAST_TFTP
824         mcast_cleanup();
825 #endif
826 #ifdef CONFIG_TFTP_TSIZE
827         tftp_tsize = 0;
828         tftp_tsize_num_hash = 0;
829 #endif
830
831         tftp_send();
832 }
833
834 #ifdef CONFIG_CMD_TFTPSRV
835 void tftp_start_server(void)
836 {
837         tftp_filename[0] = 0;
838
839         printf("Using %s device\n", eth_get_name());
840         printf("Listening for TFTP transfer on %pI4\n", &net_ip);
841         printf("Load address: 0x%lx\n", load_addr);
842
843         puts("Loading: *\b");
844
845         timeout_count_max = TIMEOUT_COUNT;
846         timeout_count = 0;
847         timeout_ms = TIMEOUT;
848         net_set_timeout_handler(timeout_ms, tftp_timeout_handler);
849
850         /* Revert tftp_block_size to dflt */
851         tftp_block_size = TFTP_BLOCK_SIZE;
852         tftp_cur_block = 0;
853         tftp_our_port = WELL_KNOWN_PORT;
854
855 #ifdef CONFIG_TFTP_TSIZE
856         tftp_tsize = 0;
857         tftp_tsize_num_hash = 0;
858 #endif
859
860         tftp_state = STATE_RECV_WRQ;
861         net_set_udp_handler(tftp_handler);
862
863         /* zero out server ether in case the server ip has changed */
864         memset(net_server_ethaddr, 0, 6);
865 }
866 #endif /* CONFIG_CMD_TFTPSRV */
867
868 #ifdef CONFIG_MCAST_TFTP
869 /*
870  * Credits: atftp project.
871  */
872
873 /*
874  * Pick up BcastAddr, Port, and whether I am [now] the master-client.
875  * Frame:
876  *    +-------+-----------+---+-------~~-------+---+
877  *    |  opc  | multicast | 0 | addr, port, mc | 0 |
878  *    +-------+-----------+---+-------~~-------+---+
879  * The multicast addr/port becomes what I listen to, and if 'mc' is '1' then
880  * I am the new master-client so must send ACKs to DataBlocks.  If I am not
881  * master-client, I'm a passive client, gathering what DataBlocks I may and
882  * making note of which ones I got in my bitmask.
883  * In theory, I never go from master->passive..
884  * .. this comes in with pkt already pointing just past opc
885  */
886 static void parse_multicast_oack(char *pkt, int len)
887 {
888         int i;
889         struct in_addr addr;
890         char *mc_adr;
891         char *port;
892         char *mc;
893
894         mc_adr = NULL;
895         port = NULL;
896         mc = NULL;
897         /* march along looking for 'multicast\0', which has to start at least
898          * 14 bytes back from the end.
899          */
900         for (i = 0; i < len - 14; i++)
901                 if (strcmp(pkt + i, "multicast") == 0)
902                         break;
903         if (i >= (len - 14)) /* non-Multicast OACK, ign. */
904                 return;
905
906         i += 10; /* strlen multicast */
907         mc_adr = pkt + i;
908         for (; i < len; i++) {
909                 if (*(pkt + i) == ',') {
910                         *(pkt + i) = '\0';
911                         if (port) {
912                                 mc = pkt + i + 1;
913                                 break;
914                         } else {
915                                 port = pkt + i + 1;
916                         }
917                 }
918         }
919         if (!port || !mc_adr || !mc)
920                 return;
921         if (tftp_mcast_active && tftp_mcast_master_client) {
922                 printf("I got a OACK as master Client, WRONG!\n");
923                 return;
924         }
925         /* ..I now accept packets destined for this MCAST addr, port */
926         if (!tftp_mcast_active) {
927                 if (tftp_mcast_bitmap) {
928                         printf("Internal failure! no mcast.\n");
929                         free(tftp_mcast_bitmap);
930                         tftp_mcast_bitmap = NULL;
931                         tftp_mcast_disabled = 1;
932                         return;
933                 }
934                 /* I malloc instead of pre-declare; so that if the file ends
935                  * up being too big for this bitmap I can retry
936                  */
937                 tftp_mcast_bitmap = malloc(tftp_mcast_bitmap_size);
938                 if (!tftp_mcast_bitmap) {
939                         printf("No bitmap, no multicast. Sorry.\n");
940                         tftp_mcast_disabled = 1;
941                         return;
942                 }
943                 memset(tftp_mcast_bitmap, 0, tftp_mcast_bitmap_size);
944                 tftp_mcast_prev_hole = 0;
945                 tftp_mcast_active = 1;
946         }
947         addr = string_to_ip(mc_adr);
948         if (net_mcast_addr.s_addr != addr.s_addr) {
949                 if (net_mcast_addr.s_addr)
950                         eth_mcast_join(net_mcast_addr, 0);
951                 net_mcast_addr = addr;
952                 if (eth_mcast_join(net_mcast_addr, 1)) {
953                         printf("Fail to set mcast, revert to TFTP\n");
954                         tftp_mcast_disabled = 1;
955                         mcast_cleanup();
956                         net_start_again();
957                 }
958         }
959         tftp_mcast_master_client = simple_strtoul((char *)mc, NULL, 10);
960         tftp_mcast_port = (unsigned short)simple_strtoul(port, NULL, 10);
961         printf("Multicast: %s:%d [%d]\n", mc_adr, tftp_mcast_port,
962                tftp_mcast_master_client);
963         return;
964 }
965
966 #endif /* Multicast TFTP */