Merge https://gitlab.denx.de/u-boot/custodians/u-boot-spi into next
[platform/kernel/u-boot.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 <efi_loader.h>
12 #include <env.h>
13 #include <image.h>
14 #include <lmb.h>
15 #include <log.h>
16 #include <mapmem.h>
17 #include <net.h>
18 #include <net/tftp.h>
19 #include "bootp.h"
20 #ifdef CONFIG_SYS_DIRECT_FLASH_TFTP
21 #include <flash.h>
22 #endif
23
24 DECLARE_GLOBAL_DATA_PTR;
25
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
33 #else
34 # define TIMEOUT_COUNT  (CONFIG_NET_RETRY_COUNT * 2)
35 #endif
36 /* Number of "loading" hashes per line (for checking the image size) */
37 #define HASHES_PER_LINE 65
38
39 /*
40  *      TFTP operations.
41  */
42 #define TFTP_RRQ        1
43 #define TFTP_WRQ        2
44 #define TFTP_DATA       3
45 #define TFTP_ACK        4
46 #define TFTP_ERROR      5
47 #define TFTP_OACK       6
48
49 static ulong timeout_ms = TIMEOUT;
50 static int timeout_count_max = TIMEOUT_COUNT;
51 static ulong time_start;   /* Record time we started tftp */
52
53 /*
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.
61  */
62 ulong tftp_timeout_ms = TIMEOUT;
63 int tftp_timeout_count_max = TIMEOUT_COUNT;
64
65 enum {
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,
74 };
75
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;
92 #ifdef CONFIG_LMB
93 static ulong    tftp_load_size;
94 #endif
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;
100 #endif
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;
106 #else
107 #define tftp_put_active 0
108 #endif
109
110 #define STATE_SEND_RRQ  1
111 #define STATE_DATA      2
112 #define STATE_TOO_LARGE 3
113 #define STATE_BAD_MAGIC 4
114 #define STATE_OACK      5
115 #define STATE_RECV_WRQ  6
116 #define STATE_SEND_WRQ  7
117 #define STATE_INVALID_OPTION    8
118
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))
123
124 #define DEFAULT_NAME_LEN        (8 + 4 + 1)
125 static char default_filename[DEFAULT_NAME_LEN];
126
127 #ifndef CONFIG_TFTP_FILE_NAME_MAX_LEN
128 #define MAX_LEN 128
129 #else
130 #define MAX_LEN CONFIG_TFTP_FILE_NAME_MAX_LEN
131 #endif
132
133 static char tftp_filename[MAX_LEN];
134
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)
139  */
140
141 static unsigned short tftp_block_size = TFTP_BLOCK_SIZE;
142 static unsigned short tftp_block_size_option = CONFIG_TFTP_BLOCKSIZE;
143
144 static inline int store_block(int block, uchar *src, unsigned int len)
145 {
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
150         int i, rc = 0;
151
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)
155                         continue;
156                 if (store_addr >= flash_info[i].start[0]) {
157                         rc = 1;
158                         break;
159                 }
160         }
161
162         if (rc) { /* Flash is destination for this packet */
163                 rc = flash_write((char *)src, store_addr, len);
164                 if (rc) {
165                         flash_perror(rc);
166                         return rc;
167                 }
168         } else
169 #endif /* CONFIG_SYS_DIRECT_FLASH_TFTP */
170         {
171                 void *ptr;
172
173 #ifdef CONFIG_LMB
174                 ulong end_addr = tftp_load_addr + tftp_load_size;
175
176                 if (!end_addr)
177                         end_addr = ULONG_MAX;
178
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");
183                         return -1;
184                 }
185 #endif
186                 ptr = map_sysmem(store_addr, len);
187                 memcpy(ptr, src, len);
188                 unmap_sysmem(ptr);
189         }
190
191         if (net_boot_file_size < newsize)
192                 net_boot_file_size = newsize;
193
194         return 0;
195 }
196
197 /* Clear our state ready for a new transfer */
198 static void new_transfer(void)
199 {
200         tftp_prev_block = 0;
201         tftp_block_wrap = 0;
202         tftp_block_wrap_offset = 0;
203 #ifdef CONFIG_CMD_TFTPPUT
204         tftp_put_final_block_sent = 0;
205 #endif
206 }
207
208 #ifdef CONFIG_CMD_TFTPPUT
209 /**
210  * Load the next block from memory to be sent over tftp.
211  *
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
216  */
217 static int load_block(unsigned block, uchar *dst, unsigned len)
218 {
219         /* We may want to get the final block from the previous set */
220         ulong offset = ((int)block - 1) * len + tftp_block_wrap_offset;
221         ulong tosend = len;
222
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);
227         return tosend;
228 }
229 #endif
230
231 static void tftp_send(void);
232 static void tftp_timeout_handler(void);
233
234 /**********************************************************************/
235
236 static void show_block_marker(void)
237 {
238         ulong pos;
239
240 #ifdef CONFIG_TFTP_TSIZE
241         if (tftp_tsize) {
242                 pos = tftp_cur_block * tftp_block_size +
243                         tftp_block_wrap_offset;
244                 if (pos > tftp_tsize)
245                         pos = tftp_tsize;
246
247                 while (tftp_tsize_num_hash < pos * 50 / tftp_tsize) {
248                         putc('#');
249                         tftp_tsize_num_hash++;
250                 }
251         } else
252 #endif
253         {
254                 pos = (tftp_cur_block - 1) +
255                         (tftp_block_wrap * TFTP_SEQUENCE_SIZE);
256                 if ((pos % 10) == 0)
257                         putc('#');
258                 else if (((pos + 1) % (10 * HASHES_PER_LINE)) == 0)
259                         puts("\n\t ");
260         }
261 }
262
263 /**
264  * restart the current transfer due to an error
265  *
266  * @param msg   Message to print for user
267  */
268 static void restart(const char *msg)
269 {
270         printf("\n%s; starting again\n", msg);
271         net_start_again();
272 }
273
274 /*
275  * Check if the block number has wrapped, and update progress
276  *
277  * TODO: The egregious use of global variables in this file should be tidied.
278  */
279 static void update_block_number(void)
280 {
281         /*
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.
286          */
287         if (tftp_cur_block == 0 && tftp_prev_block != 0) {
288                 tftp_block_wrap++;
289                 tftp_block_wrap_offset += tftp_block_size * TFTP_SEQUENCE_SIZE;
290                 timeout_count = 0; /* we've done well, reset the timeout */
291         }
292         show_block_marker();
293 }
294
295 /* The TFTP get or put is complete */
296 static void tftp_complete(void)
297 {
298 #ifdef CONFIG_TFTP_TSIZE
299         /* Print hash marks for the last packet received */
300         while (tftp_tsize && tftp_tsize_num_hash < 49) {
301                 putc('#');
302                 tftp_tsize_num_hash++;
303         }
304         puts("  ");
305         print_size(tftp_tsize, "");
306 #endif
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");
312         }
313         puts("\ndone\n");
314         net_set_state(NETLOOP_SUCCESS);
315 }
316
317 static void tftp_send(void)
318 {
319         uchar *pkt;
320         uchar *xp;
321         int len = 0;
322         ushort *s;
323         bool err_pkt = false;
324
325         /*
326          *      We will always be sending some sort of packet, so
327          *      cobble together the packet headers now.
328          */
329         pkt = net_tx_packet + net_eth_hdr_size() + IP_UDP_HDR_SIZE;
330
331         switch (tftp_state) {
332         case STATE_SEND_RRQ:
333         case STATE_SEND_WRQ:
334                 xp = pkt;
335                 s = (ushort *)pkt;
336 #ifdef CONFIG_CMD_TFTPPUT
337                 *s++ = htons(tftp_state == STATE_SEND_RRQ ? TFTP_RRQ :
338                         TFTP_WRQ);
339 #else
340                 *s++ = htons(TFTP_RRQ);
341 #endif
342                 pkt = (uchar *)s;
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);
355 #endif
356                 /* try for more effic. blk size */
357                 pkt += sprintf((char *)pkt, "blksize%c%d%c",
358                                 0, tftp_block_size_option, 0);
359                 len = pkt - xp;
360                 break;
361
362         case STATE_OACK:
363
364         case STATE_RECV_WRQ:
365         case STATE_DATA:
366                 xp = pkt;
367                 s = (ushort *)pkt;
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);
375
376                         s[0] = htons(TFTP_DATA);
377                         pkt += loaded;
378                         tftp_put_final_block_sent = (loaded < toload);
379                 }
380 #endif
381                 len = pkt - xp;
382                 break;
383
384         case STATE_TOO_LARGE:
385                 xp = pkt;
386                 s = (ushort *)pkt;
387                 *s++ = htons(TFTP_ERROR);
388                         *s++ = htons(3);
389
390                 pkt = (uchar *)s;
391                 strcpy((char *)pkt, "File too large");
392                 pkt += 14 /*strlen("File too large")*/ + 1;
393                 len = pkt - xp;
394                 err_pkt = true;
395                 break;
396
397         case STATE_BAD_MAGIC:
398                 xp = pkt;
399                 s = (ushort *)pkt;
400                 *s++ = htons(TFTP_ERROR);
401                 *s++ = htons(2);
402                 pkt = (uchar *)s;
403                 strcpy((char *)pkt, "File has bad magic");
404                 pkt += 18 /*strlen("File has bad magic")*/ + 1;
405                 len = pkt - xp;
406                 err_pkt = true;
407                 break;
408
409         case STATE_INVALID_OPTION:
410                 xp = pkt;
411                 s = (ushort *)pkt;
412                 *s++ = htons(TFTP_ERROR);
413                 *s++ = htons(TFTP_ERR_OPTION_NEGOTIATION);
414                 pkt = (uchar *)s;
415                 strcpy((char *)pkt, "Option Negotiation Failed");
416                 /* strlen("Option Negotiation Failed") + NULL*/
417                 pkt += 25 + 1;
418                 len = pkt - xp;
419                 err_pkt = true;
420                 break;
421         }
422
423         net_send_udp_packet(net_server_ethaddr, tftp_remote_ip,
424                             tftp_remote_port, tftp_our_port, len);
425
426         if (err_pkt)
427                 net_set_state(NETLOOP_FAIL);
428 }
429
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,
433                          unsigned len)
434 {
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");
438         }
439 }
440 #endif
441
442 static void tftp_handler(uchar *pkt, unsigned dest, struct in_addr sip,
443                          unsigned src, unsigned len)
444 {
445         __be16 proto;
446         __be16 *s;
447         int i;
448         u16 timeout_val_rcvd;
449
450         if (dest != tftp_our_port) {
451                         return;
452         }
453         if (tftp_state != STATE_SEND_RRQ && src != tftp_remote_port &&
454             tftp_state != STATE_RECV_WRQ && tftp_state != STATE_SEND_WRQ)
455                 return;
456
457         if (len < 2)
458                 return;
459         len -= 2;
460         /* warning: don't use increment (++) in ntohs() macros!! */
461         s = (__be16 *)pkt;
462         proto = *s++;
463         pkt = (uchar *)s;
464         switch (ntohs(proto)) {
465         case TFTP_RRQ:
466                 break;
467
468         case TFTP_ACK:
469 #ifdef CONFIG_CMD_TFTPPUT
470                 if (tftp_put_active) {
471                         if (tftp_put_final_block_sent) {
472                                 tftp_complete();
473                         } else {
474                                 /*
475                                  * Move to the next block. We want our block
476                                  * count to wrap just like the other end!
477                                  */
478                                 int block = ntohs(*s);
479                                 int ack_ok = (tftp_cur_block == block);
480
481                                 tftp_cur_block = (unsigned short)(block + 1);
482                                 update_block_number();
483                                 if (ack_ok)
484                                         tftp_send(); /* Send next data block */
485                         }
486                 }
487 #endif
488                 break;
489
490         default:
491                 break;
492
493 #ifdef CONFIG_CMD_TFTPSRV
494         case TFTP_WRQ:
495                 debug("Got WRQ\n");
496                 tftp_remote_ip = sip;
497                 tftp_remote_port = src;
498                 tftp_our_port = 1024 + (get_timer(0) % 3072);
499                 new_transfer();
500                 tftp_send(); /* Send ACK(0) */
501                 break;
502 #endif
503
504         case TFTP_OACK:
505                 debug("Got OACK: ");
506                 for (i = 0; i < len; i++) {
507                         if (pkt[i] == '\0')
508                                 debug(" ");
509                         else
510                                 debug("%c", pkt[i]);
511                 }
512                 debug("\n");
513                 tftp_state = STATE_OACK;
514                 tftp_remote_port = src;
515                 /*
516                  * Check for 'blksize' option.
517                  * Careful: "i" is signed, "len" is unsigned, thus
518                  * something like "len-8" may give a *huge* number
519                  */
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,
524                                                        NULL, 10);
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",
529                                                tftp_block_size);
530                                         tftp_state = STATE_INVALID_OPTION;
531                                 }
532                         }
533                         if (strcasecmp((char *)pkt + i, "timeout") == 0) {
534                                 timeout_val_rcvd = (unsigned short)
535                                         simple_strtoul((char *)pkt + i + 8,
536                                                        NULL, 10);
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",
541                                                timeout_val_rcvd);
542                                         tftp_state = STATE_INVALID_OPTION;
543                                 }
544                         }
545 #ifdef CONFIG_TFTP_TSIZE
546                         if (strcasecmp((char *)pkt + i, "tsize") == 0) {
547                                 tftp_tsize = simple_strtoul((char *)pkt + i + 6,
548                                                            NULL, 10);
549                                 debug("size = %s, %d\n",
550                                       (char *)pkt + i + 6, tftp_tsize);
551                         }
552 #endif
553                 }
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;
558                         tftp_cur_block++;
559                 }
560 #endif
561                 tftp_send(); /* Send ACK or first data block */
562                 break;
563         case TFTP_DATA:
564                 if (len < 2)
565                         return;
566                 len -= 2;
567                 tftp_cur_block = ntohs(*(__be16 *)pkt);
568
569                 if (tftp_state == STATE_SEND_RRQ)
570                         debug("Server did not acknowledge any options!\n");
571
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;
577                         new_transfer();
578
579                         if (tftp_cur_block != 1) {      /* Assertion */
580                                 puts("\nTFTP error: ");
581                                 printf("First block is not block 1 (%ld)\n",
582                                        tftp_cur_block);
583                                 puts("Starting again\n\n");
584                                 net_start_again();
585                                 break;
586                         }
587                 }
588
589                 if (tftp_cur_block == tftp_prev_block) {
590                         /* Same block again; ignore it. */
591                         break;
592                 }
593
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);
598
599                 if (store_block(tftp_cur_block - 1, pkt + 2, len)) {
600                         eth_halt();
601                         net_set_state(NETLOOP_FAIL);
602                         break;
603                 }
604
605                 /*
606                  *      Acknowledge the block just received, which will prompt
607                  *      the remote for the next one.
608                  */
609                 tftp_send();
610
611                 if (len < tftp_block_size)
612                         tftp_complete();
613                 break;
614
615         case TFTP_ERROR:
616                 printf("\nTFTP error: '%s' (%d)\n",
617                        pkt + 2, ntohs(*(__be16 *)pkt));
618
619                 switch (ntohs(*(__be16 *)pkt)) {
620                 case TFTP_ERR_FILE_NOT_FOUND:
621                 case TFTP_ERR_ACCESS_DENIED:
622                         puts("Not retrying...\n");
623                         eth_halt();
624                         net_set_state(NETLOOP_FAIL);
625                         break;
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:
631                 default:
632                         puts("Starting again\n\n");
633                         net_start_again();
634                         break;
635                 }
636                 break;
637         }
638 }
639
640
641 static void tftp_timeout_handler(void)
642 {
643         if (++timeout_count > timeout_count_max) {
644                 restart("Retry count exceeded");
645         } else {
646                 puts("T ");
647                 net_set_timeout_handler(timeout_ms, tftp_timeout_handler);
648                 if (tftp_state != STATE_RECV_WRQ)
649                         tftp_send();
650         }
651 }
652
653 /* Initialize tftp_load_addr and tftp_load_size from image_load_addr and lmb */
654 static int tftp_init_load_addr(void)
655 {
656 #ifdef CONFIG_LMB
657         struct lmb lmb;
658         phys_size_t max_size;
659
660         lmb_init_and_reserve(&lmb, gd->bd, (void *)gd->fdt_blob);
661
662         max_size = lmb_get_free_size(&lmb, image_load_addr);
663         if (!max_size)
664                 return -1;
665
666         tftp_load_size = max_size;
667 #endif
668         tftp_load_addr = image_load_addr;
669         return 0;
670 }
671
672 void tftp_start(enum proto_t protocol)
673 {
674 #if CONFIG_NET_TFTP_VARS
675         char *ep;             /* Environment pointer */
676
677         /*
678          * Allow the user to choose TFTP blocksize and timeout.
679          * TFTP protocol has a minimal timeout of 1 second.
680          */
681
682         ep = env_get("tftpblocksize");
683         if (ep != NULL)
684                 tftp_block_size_option = simple_strtol(ep, NULL, 10);
685
686         ep = env_get("tftptimeout");
687         if (ep != NULL)
688                 timeout_ms = simple_strtol(ep, NULL, 10);
689
690         if (timeout_ms < 1000) {
691                 printf("TFTP timeout (%ld ms) too low, set min = 1000 ms\n",
692                        timeout_ms);
693                 timeout_ms = 1000;
694         }
695
696         ep = env_get("tftptimeoutcountmax");
697         if (ep != NULL)
698                 tftp_timeout_count_max = simple_strtol(ep, NULL, 10);
699
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;
704         }
705 #endif
706
707         debug("TFTP blocksize = %i, timeout = %ld ms\n",
708               tftp_block_size_option, timeout_ms);
709
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);
717
718                 strncpy(tftp_filename, default_filename, DEFAULT_NAME_LEN);
719                 tftp_filename[DEFAULT_NAME_LEN - 1] = 0;
720
721                 printf("*** Warning: no boot file name; using '%s'\n",
722                        tftp_filename);
723         }
724
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",
729 #else
730                "from",
731 #endif
732                &tftp_remote_ip, &net_ip);
733
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;
738
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);
743         }
744         putc('\n');
745
746         printf("Filename '%s'.", tftp_filename);
747
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, "");
752         }
753
754         putc('\n');
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;
761                 puts("Saving: *\b");
762                 tftp_state = STATE_SEND_WRQ;
763                 new_transfer();
764         } else
765 #endif
766         {
767                 if (tftp_init_load_addr()) {
768                         eth_halt();
769                         net_set_state(NETLOOP_FAIL);
770                         puts("\nTFTP error: ");
771                         puts("trying to overwrite reserved memory...\n");
772                         return;
773                 }
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);
779 #endif
780         }
781
782         time_start = get_timer(0);
783         timeout_count_max = tftp_timeout_count_max;
784
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);
789 #endif
790         tftp_remote_port = WELL_KNOWN_PORT;
791         timeout_count = 0;
792         /* Use a pseudo-random port unless a specific port is set */
793         tftp_our_port = 1024 + (get_timer(0) % 3072);
794
795 #ifdef CONFIG_TFTP_PORT
796         ep = env_get("tftpdstp");
797         if (ep != NULL)
798                 tftp_remote_port = simple_strtol(ep, NULL, 10);
799         ep = env_get("tftpsrcp");
800         if (ep != NULL)
801                 tftp_our_port = simple_strtol(ep, NULL, 10);
802 #endif
803         tftp_cur_block = 0;
804
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
810         tftp_tsize = 0;
811         tftp_tsize_num_hash = 0;
812 #endif
813
814         tftp_send();
815 }
816
817 #ifdef CONFIG_CMD_TFTPSRV
818 void tftp_start_server(void)
819 {
820         tftp_filename[0] = 0;
821
822         if (tftp_init_load_addr()) {
823                 eth_halt();
824                 net_set_state(NETLOOP_FAIL);
825                 puts("\nTFTP error: trying to overwrite reserved memory...\n");
826                 return;
827         }
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);
831
832         puts("Loading: *\b");
833
834         timeout_count_max = tftp_timeout_count_max;
835         timeout_count = 0;
836         timeout_ms = TIMEOUT;
837         net_set_timeout_handler(timeout_ms, tftp_timeout_handler);
838
839         /* Revert tftp_block_size to dflt */
840         tftp_block_size = TFTP_BLOCK_SIZE;
841         tftp_cur_block = 0;
842         tftp_our_port = WELL_KNOWN_PORT;
843
844 #ifdef CONFIG_TFTP_TSIZE
845         tftp_tsize = 0;
846         tftp_tsize_num_hash = 0;
847 #endif
848
849         tftp_state = STATE_RECV_WRQ;
850         net_set_udp_handler(tftp_handler);
851
852         /* zero out server ether in case the server ip has changed */
853         memset(net_server_ethaddr, 0, 6);
854 }
855 #endif /* CONFIG_CMD_TFTPSRV */
856