Merge branch '2022-08-04-Kconfig-migrations'
[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 #include <common.h>
9 #include <command.h>
10 #include <efi_loader.h>
11 #include <env.h>
12 #include <image.h>
13 #include <lmb.h>
14 #include <log.h>
15 #include <mapmem.h>
16 #include <net.h>
17 #include <asm/global_data.h>
18 #include <net/tftp.h>
19 #include "bootp.h"
20
21 DECLARE_GLOBAL_DATA_PTR;
22
23 /* Well known TFTP port # */
24 #define WELL_KNOWN_PORT 69
25 /* Millisecs to timeout for lost pkt */
26 #define TIMEOUT         5000UL
27 /* Number of "loading" hashes per line (for checking the image size) */
28 #define HASHES_PER_LINE 65
29
30 /*
31  *      TFTP operations.
32  */
33 #define TFTP_RRQ        1
34 #define TFTP_WRQ        2
35 #define TFTP_DATA       3
36 #define TFTP_ACK        4
37 #define TFTP_ERROR      5
38 #define TFTP_OACK       6
39
40 static ulong timeout_ms = TIMEOUT;
41 static int timeout_count_max = (CONFIG_NET_RETRY_COUNT * 2);
42 static ulong time_start;   /* Record time we started tftp */
43
44 /*
45  * These globals govern the timeout behavior when attempting a connection to a
46  * TFTP server. tftp_timeout_ms specifies the number of milliseconds to
47  * wait for the server to respond to initial connection. Second global,
48  * tftp_timeout_count_max, gives the number of such connection retries.
49  * tftp_timeout_count_max must be non-negative and tftp_timeout_ms must be
50  * positive. The globals are meant to be set (and restored) by code needing
51  * non-standard timeout behavior when initiating a TFTP transfer.
52  */
53 ulong tftp_timeout_ms = TIMEOUT;
54 int tftp_timeout_count_max = (CONFIG_NET_RETRY_COUNT * 2);
55
56 enum {
57         TFTP_ERR_UNDEFINED           = 0,
58         TFTP_ERR_FILE_NOT_FOUND      = 1,
59         TFTP_ERR_ACCESS_DENIED       = 2,
60         TFTP_ERR_DISK_FULL           = 3,
61         TFTP_ERR_UNEXPECTED_OPCODE   = 4,
62         TFTP_ERR_UNKNOWN_TRANSFER_ID  = 5,
63         TFTP_ERR_FILE_ALREADY_EXISTS = 6,
64         TFTP_ERR_OPTION_NEGOTIATION = 8,
65 };
66
67 static struct in_addr tftp_remote_ip;
68 /* The UDP port at their end */
69 static int      tftp_remote_port;
70 /* The UDP port at our end */
71 static int      tftp_our_port;
72 static int      timeout_count;
73 /* packet sequence number */
74 static ulong    tftp_cur_block;
75 /* last packet sequence number received */
76 static ulong    tftp_prev_block;
77 /* count of sequence number wraparounds */
78 static ulong    tftp_block_wrap;
79 /* memory offset due to wrapping */
80 static ulong    tftp_block_wrap_offset;
81 static int      tftp_state;
82 static ulong    tftp_load_addr;
83 #ifdef CONFIG_LMB
84 static ulong    tftp_load_size;
85 #endif
86 #ifdef CONFIG_TFTP_TSIZE
87 /* The file size reported by the server */
88 static int      tftp_tsize;
89 /* The number of hashes we printed */
90 static short    tftp_tsize_num_hash;
91 #endif
92 /* The window size negotiated */
93 static ushort   tftp_windowsize;
94 /* Next block to send ack to */
95 static ushort   tftp_next_ack;
96 /* Last nack block we send */
97 static ushort   tftp_last_nack;
98 #ifdef CONFIG_CMD_TFTPPUT
99 /* 1 if writing, else 0 */
100 static int      tftp_put_active;
101 /* 1 if we have sent the last block */
102 static int      tftp_put_final_block_sent;
103 #else
104 #define tftp_put_active 0
105 #endif
106
107 #define STATE_SEND_RRQ  1
108 #define STATE_DATA      2
109 #define STATE_TOO_LARGE 3
110 #define STATE_BAD_MAGIC 4
111 #define STATE_OACK      5
112 #define STATE_RECV_WRQ  6
113 #define STATE_SEND_WRQ  7
114 #define STATE_INVALID_OPTION    8
115
116 /* default TFTP block size */
117 #define TFTP_BLOCK_SIZE         512
118 /* sequence number is 16 bit */
119 #define TFTP_SEQUENCE_SIZE      ((ulong)(1<<16))
120
121 #define DEFAULT_NAME_LEN        (8 + 4 + 1)
122 static char default_filename[DEFAULT_NAME_LEN];
123
124 #ifndef CONFIG_TFTP_FILE_NAME_MAX_LEN
125 #define MAX_LEN 128
126 #else
127 #define MAX_LEN CONFIG_TFTP_FILE_NAME_MAX_LEN
128 #endif
129
130 static char tftp_filename[MAX_LEN];
131
132 /* 512 is poor choice for ethernet, MTU is typically 1500.
133  * Minus eth.hdrs thats 1468.  Can get 2x better throughput with
134  * almost-MTU block sizes.  At least try... fall back to 512 if need be.
135  * (but those using CONFIG_IP_DEFRAG may want to set a larger block in cfg file)
136  */
137
138 /* When windowsize is defined to 1,
139  * tftp behaves the same way as it was
140  * never declared
141  */
142 #ifdef CONFIG_TFTP_WINDOWSIZE
143 #define TFTP_WINDOWSIZE CONFIG_TFTP_WINDOWSIZE
144 #else
145 #define TFTP_WINDOWSIZE 1
146 #endif
147
148 static unsigned short tftp_block_size = TFTP_BLOCK_SIZE;
149 static unsigned short tftp_block_size_option = CONFIG_TFTP_BLOCKSIZE;
150 static unsigned short tftp_window_size_option = TFTP_WINDOWSIZE;
151
152 static inline int store_block(int block, uchar *src, unsigned int len)
153 {
154         ulong offset = block * tftp_block_size + tftp_block_wrap_offset -
155                         tftp_block_size;
156         ulong newsize = offset + len;
157         ulong store_addr = tftp_load_addr + offset;
158         void *ptr;
159
160 #ifdef CONFIG_LMB
161         ulong end_addr = tftp_load_addr + tftp_load_size;
162
163         if (!end_addr)
164                 end_addr = ULONG_MAX;
165
166         if (store_addr < tftp_load_addr ||
167             store_addr + len > end_addr) {
168                 puts("\nTFTP error: ");
169                 puts("trying to overwrite reserved memory...\n");
170                 return -1;
171         }
172 #endif
173         ptr = map_sysmem(store_addr, len);
174         memcpy(ptr, src, len);
175         unmap_sysmem(ptr);
176
177         if (net_boot_file_size < newsize)
178                 net_boot_file_size = newsize;
179
180         return 0;
181 }
182
183 /* Clear our state ready for a new transfer */
184 static void new_transfer(void)
185 {
186         tftp_prev_block = 0;
187         tftp_block_wrap = 0;
188         tftp_block_wrap_offset = 0;
189 #ifdef CONFIG_CMD_TFTPPUT
190         tftp_put_final_block_sent = 0;
191 #endif
192 }
193
194 #ifdef CONFIG_CMD_TFTPPUT
195 /**
196  * Load the next block from memory to be sent over tftp.
197  *
198  * @param block Block number to send
199  * @param dst   Destination buffer for data
200  * @param len   Number of bytes in block (this one and every other)
201  * Return: number of bytes loaded
202  */
203 static int load_block(unsigned block, uchar *dst, unsigned len)
204 {
205         /* We may want to get the final block from the previous set */
206         ulong offset = block * tftp_block_size + tftp_block_wrap_offset -
207                        tftp_block_size;
208         ulong tosend = len;
209
210         tosend = min(net_boot_file_size - offset, tosend);
211         (void)memcpy(dst, (void *)(image_save_addr + offset), tosend);
212         debug("%s: block=%u, offset=%lu, len=%u, tosend=%lu\n", __func__,
213               block, offset, len, tosend);
214         return tosend;
215 }
216 #endif
217
218 static void tftp_send(void);
219 static void tftp_timeout_handler(void);
220
221 /**********************************************************************/
222
223 static void show_block_marker(void)
224 {
225         ulong pos;
226
227 #ifdef CONFIG_TFTP_TSIZE
228         if (tftp_tsize) {
229                 pos = tftp_cur_block * tftp_block_size +
230                         tftp_block_wrap_offset;
231                 if (pos > tftp_tsize)
232                         pos = tftp_tsize;
233
234                 while (tftp_tsize_num_hash < pos * 50 / tftp_tsize) {
235                         putc('#');
236                         tftp_tsize_num_hash++;
237                 }
238         } else
239 #endif
240         {
241                 pos = (tftp_cur_block - 1) +
242                         (tftp_block_wrap * TFTP_SEQUENCE_SIZE);
243                 if ((pos % 10) == 0)
244                         putc('#');
245                 else if (((pos + 1) % (10 * HASHES_PER_LINE)) == 0)
246                         puts("\n\t ");
247         }
248 }
249
250 /**
251  * restart the current transfer due to an error
252  *
253  * @param msg   Message to print for user
254  */
255 static void restart(const char *msg)
256 {
257         printf("\n%s; starting again\n", msg);
258         net_start_again();
259 }
260
261 /*
262  * Check if the block number has wrapped, and update progress
263  *
264  * TODO: The egregious use of global variables in this file should be tidied.
265  */
266 static void update_block_number(void)
267 {
268         /*
269          * RFC1350 specifies that the first data packet will
270          * have sequence number 1. If we receive a sequence
271          * number of 0 this means that there was a wrap
272          * around of the (16 bit) counter.
273          */
274         if (tftp_cur_block == 0 && tftp_prev_block != 0) {
275                 tftp_block_wrap++;
276                 tftp_block_wrap_offset += tftp_block_size * TFTP_SEQUENCE_SIZE;
277                 timeout_count = 0; /* we've done well, reset the timeout */
278         }
279         show_block_marker();
280 }
281
282 /* The TFTP get or put is complete */
283 static void tftp_complete(void)
284 {
285 #ifdef CONFIG_TFTP_TSIZE
286         /* Print hash marks for the last packet received */
287         while (tftp_tsize && tftp_tsize_num_hash < 49) {
288                 putc('#');
289                 tftp_tsize_num_hash++;
290         }
291         puts("  ");
292         print_size(tftp_tsize, "");
293 #endif
294         time_start = get_timer(time_start);
295         if (time_start > 0) {
296                 puts("\n\t ");  /* Line up with "Loading: " */
297                 print_size(net_boot_file_size /
298                         time_start * 1000, "/s");
299         }
300         puts("\ndone\n");
301         if (IS_ENABLED(CONFIG_CMD_BOOTEFI)) {
302                 if (!tftp_put_active)
303                         efi_set_bootdev("Net", "", tftp_filename,
304                                         map_sysmem(tftp_load_addr, 0),
305                                         net_boot_file_size);
306         }
307         net_set_state(NETLOOP_SUCCESS);
308 }
309
310 static void tftp_send(void)
311 {
312         uchar *pkt;
313         uchar *xp;
314         int len = 0;
315         ushort *s;
316         bool err_pkt = false;
317
318         /*
319          *      We will always be sending some sort of packet, so
320          *      cobble together the packet headers now.
321          */
322         pkt = net_tx_packet + net_eth_hdr_size() + IP_UDP_HDR_SIZE;
323
324         switch (tftp_state) {
325         case STATE_SEND_RRQ:
326         case STATE_SEND_WRQ:
327                 xp = pkt;
328                 s = (ushort *)pkt;
329 #ifdef CONFIG_CMD_TFTPPUT
330                 *s++ = htons(tftp_state == STATE_SEND_RRQ ? TFTP_RRQ :
331                         TFTP_WRQ);
332 #else
333                 *s++ = htons(TFTP_RRQ);
334 #endif
335                 pkt = (uchar *)s;
336                 strcpy((char *)pkt, tftp_filename);
337                 pkt += strlen(tftp_filename) + 1;
338                 strcpy((char *)pkt, "octet");
339                 pkt += 5 /*strlen("octet")*/ + 1;
340                 strcpy((char *)pkt, "timeout");
341                 pkt += 7 /*strlen("timeout")*/ + 1;
342                 sprintf((char *)pkt, "%lu", timeout_ms / 1000);
343                 debug("send option \"timeout %s\"\n", (char *)pkt);
344                 pkt += strlen((char *)pkt) + 1;
345 #ifdef CONFIG_TFTP_TSIZE
346                 pkt += sprintf((char *)pkt, "tsize%c%u%c",
347                                 0, net_boot_file_size, 0);
348 #endif
349                 /* try for more effic. blk size */
350                 pkt += sprintf((char *)pkt, "blksize%c%d%c",
351                                 0, tftp_block_size_option, 0);
352
353                 /* try for more effic. window size.
354                  * Implemented only for tftp get.
355                  * Don't bother sending if it's 1
356                  */
357                 if (tftp_state == STATE_SEND_RRQ && tftp_window_size_option > 1)
358                         pkt += sprintf((char *)pkt, "windowsize%c%d%c",
359                                         0, tftp_window_size_option, 0);
360                 len = pkt - xp;
361                 break;
362
363         case STATE_OACK:
364
365         case STATE_RECV_WRQ:
366         case STATE_DATA:
367                 xp = pkt;
368                 s = (ushort *)pkt;
369                 s[0] = htons(TFTP_ACK);
370                 s[1] = htons(tftp_cur_block);
371                 pkt = (uchar *)(s + 2);
372 #ifdef CONFIG_CMD_TFTPPUT
373                 if (tftp_put_active) {
374                         int toload = tftp_block_size;
375                         int loaded = load_block(tftp_cur_block, pkt, toload);
376
377                         s[0] = htons(TFTP_DATA);
378                         pkt += loaded;
379                         tftp_put_final_block_sent = (loaded < toload);
380                 }
381 #endif
382                 len = pkt - xp;
383                 break;
384
385         case STATE_TOO_LARGE:
386                 xp = pkt;
387                 s = (ushort *)pkt;
388                 *s++ = htons(TFTP_ERROR);
389                         *s++ = htons(3);
390
391                 pkt = (uchar *)s;
392                 strcpy((char *)pkt, "File too large");
393                 pkt += 14 /*strlen("File too large")*/ + 1;
394                 len = pkt - xp;
395                 err_pkt = true;
396                 break;
397
398         case STATE_BAD_MAGIC:
399                 xp = pkt;
400                 s = (ushort *)pkt;
401                 *s++ = htons(TFTP_ERROR);
402                 *s++ = htons(2);
403                 pkt = (uchar *)s;
404                 strcpy((char *)pkt, "File has bad magic");
405                 pkt += 18 /*strlen("File has bad magic")*/ + 1;
406                 len = pkt - xp;
407                 err_pkt = true;
408                 break;
409
410         case STATE_INVALID_OPTION:
411                 xp = pkt;
412                 s = (ushort *)pkt;
413                 *s++ = htons(TFTP_ERROR);
414                 *s++ = htons(TFTP_ERR_OPTION_NEGOTIATION);
415                 pkt = (uchar *)s;
416                 strcpy((char *)pkt, "Option Negotiation Failed");
417                 /* strlen("Option Negotiation Failed") + NULL*/
418                 pkt += 25 + 1;
419                 len = pkt - xp;
420                 err_pkt = true;
421                 break;
422         }
423
424         net_send_udp_packet(net_server_ethaddr, tftp_remote_ip,
425                             tftp_remote_port, tftp_our_port, len);
426
427         if (err_pkt)
428                 net_set_state(NETLOOP_FAIL);
429 }
430
431 #ifdef CONFIG_CMD_TFTPPUT
432 static void icmp_handler(unsigned type, unsigned code, unsigned dest,
433                          struct in_addr sip, unsigned src, uchar *pkt,
434                          unsigned len)
435 {
436         if (type == ICMP_NOT_REACH && code == ICMP_NOT_REACH_PORT) {
437                 /* Oh dear the other end has gone away */
438                 restart("TFTP server died");
439         }
440 }
441 #endif
442
443 static void tftp_handler(uchar *pkt, unsigned dest, struct in_addr sip,
444                          unsigned src, unsigned len)
445 {
446         __be16 proto;
447         __be16 *s;
448         int i;
449         u16 timeout_val_rcvd;
450
451         if (dest != tftp_our_port) {
452                         return;
453         }
454         if (tftp_state != STATE_SEND_RRQ && src != tftp_remote_port &&
455             tftp_state != STATE_RECV_WRQ && tftp_state != STATE_SEND_WRQ)
456                 return;
457
458         if (len < 2)
459                 return;
460         len -= 2;
461         /* warning: don't use increment (++) in ntohs() macros!! */
462         s = (__be16 *)pkt;
463         proto = *s++;
464         pkt = (uchar *)s;
465         switch (ntohs(proto)) {
466         case TFTP_RRQ:
467                 break;
468
469         case TFTP_ACK:
470 #ifdef CONFIG_CMD_TFTPPUT
471                 if (tftp_put_active) {
472                         if (tftp_put_final_block_sent) {
473                                 tftp_complete();
474                         } else {
475                                 /*
476                                  * Move to the next block. We want our block
477                                  * count to wrap just like the other end!
478                                  */
479                                 int block = ntohs(*s);
480                                 int ack_ok = (tftp_cur_block == block);
481
482                                 tftp_prev_block = tftp_cur_block;
483                                 tftp_cur_block = (unsigned short)(block + 1);
484                                 update_block_number();
485                                 if (ack_ok)
486                                         tftp_send(); /* Send next data block */
487                         }
488                 }
489 #endif
490                 break;
491
492         default:
493                 break;
494
495 #ifdef CONFIG_CMD_TFTPSRV
496         case TFTP_WRQ:
497                 debug("Got WRQ\n");
498                 tftp_remote_ip = sip;
499                 tftp_remote_port = src;
500                 tftp_our_port = 1024 + (get_timer(0) % 3072);
501                 new_transfer();
502                 tftp_send(); /* Send ACK(0) */
503                 break;
504 #endif
505
506         case TFTP_OACK:
507                 debug("Got OACK: ");
508                 for (i = 0; i < len; i++) {
509                         if (pkt[i] == '\0')
510                                 debug(" ");
511                         else
512                                 debug("%c", pkt[i]);
513                 }
514                 debug("\n");
515                 tftp_state = STATE_OACK;
516                 tftp_remote_port = src;
517                 /*
518                  * Check for 'blksize' option.
519                  * Careful: "i" is signed, "len" is unsigned, thus
520                  * something like "len-8" may give a *huge* number
521                  */
522                 for (i = 0; i+8 < len; i++) {
523                         if (strcasecmp((char *)pkt + i, "blksize") == 0) {
524                                 tftp_block_size = (unsigned short)
525                                         dectoul((char *)pkt + i + 8, NULL);
526                                 debug("Blocksize oack: %s, %d\n",
527                                       (char *)pkt + i + 8, tftp_block_size);
528                                 if (tftp_block_size > tftp_block_size_option) {
529                                         printf("Invalid blk size(=%d)\n",
530                                                tftp_block_size);
531                                         tftp_state = STATE_INVALID_OPTION;
532                                 }
533                         }
534                         if (strcasecmp((char *)pkt + i, "timeout") == 0) {
535                                 timeout_val_rcvd = (unsigned short)
536                                         dectoul((char *)pkt + i + 8, NULL);
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 = dectoul((char *)pkt + i + 6,
548                                                      NULL);
549                                 debug("size = %s, %d\n",
550                                       (char *)pkt + i + 6, tftp_tsize);
551                         }
552 #endif
553                         if (strcasecmp((char *)pkt + i,  "windowsize") == 0) {
554                                 tftp_windowsize =
555                                         dectoul((char *)pkt + i + 11, NULL);
556                                 debug("windowsize = %s, %d\n",
557                                       (char *)pkt + i + 11, tftp_windowsize);
558                         }
559                 }
560
561                 tftp_next_ack = tftp_windowsize;
562
563 #ifdef CONFIG_CMD_TFTPPUT
564                 if (tftp_put_active && tftp_state == STATE_OACK) {
565                         /* Get ready to send the first block */
566                         tftp_state = STATE_DATA;
567                         tftp_cur_block++;
568                 }
569 #endif
570                 tftp_send(); /* Send ACK or first data block */
571                 break;
572         case TFTP_DATA:
573                 if (len < 2)
574                         return;
575                 len -= 2;
576
577                 if (ntohs(*(__be16 *)pkt) != (ushort)(tftp_cur_block + 1)) {
578                         debug("Received unexpected block: %d, expected: %d\n",
579                               ntohs(*(__be16 *)pkt),
580                               (ushort)(tftp_cur_block + 1));
581                         /*
582                          * If one packet is dropped most likely
583                          * all other buffers in the window
584                          * that will arrive will cause a sending NACK.
585                          * This just overwellms the server, let's just send one.
586                          */
587                         if (tftp_last_nack != tftp_cur_block) {
588                                 tftp_send();
589                                 tftp_last_nack = tftp_cur_block;
590                                 tftp_next_ack = (ushort)(tftp_cur_block +
591                                                          tftp_windowsize);
592                         }
593                         break;
594                 }
595
596                 tftp_cur_block++;
597                 tftp_cur_block %= TFTP_SEQUENCE_SIZE;
598
599                 if (tftp_state == STATE_SEND_RRQ) {
600                         debug("Server did not acknowledge any options!\n");
601                         tftp_next_ack = tftp_windowsize;
602                 }
603
604                 if (tftp_state == STATE_SEND_RRQ || tftp_state == STATE_OACK ||
605                     tftp_state == STATE_RECV_WRQ) {
606                         /* first block received */
607                         tftp_state = STATE_DATA;
608                         tftp_remote_port = src;
609                         new_transfer();
610
611                         if (tftp_cur_block != 1) {      /* Assertion */
612                                 puts("\nTFTP error: ");
613                                 printf("First block is not block 1 (%ld)\n",
614                                        tftp_cur_block);
615                                 puts("Starting again\n\n");
616                                 net_start_again();
617                                 break;
618                         }
619                 }
620
621                 if (tftp_cur_block == tftp_prev_block) {
622                         /* Same block again; ignore it. */
623                         break;
624                 }
625
626                 update_block_number();
627                 tftp_prev_block = tftp_cur_block;
628                 timeout_count_max = tftp_timeout_count_max;
629                 net_set_timeout_handler(timeout_ms, tftp_timeout_handler);
630
631                 if (store_block(tftp_cur_block, pkt + 2, len)) {
632                         eth_halt();
633                         net_set_state(NETLOOP_FAIL);
634                         break;
635                 }
636
637                 if (len < tftp_block_size) {
638                         tftp_send();
639                         tftp_complete();
640                         break;
641                 }
642
643                 /*
644                  *      Acknowledge the block just received, which will prompt
645                  *      the remote for the next one.
646                  */
647                 if (tftp_cur_block == tftp_next_ack) {
648                         tftp_send();
649                         tftp_next_ack += tftp_windowsize;
650                 }
651                 break;
652
653         case TFTP_ERROR:
654                 printf("\nTFTP error: '%s' (%d)\n",
655                        pkt + 2, ntohs(*(__be16 *)pkt));
656
657                 switch (ntohs(*(__be16 *)pkt)) {
658                 case TFTP_ERR_FILE_NOT_FOUND:
659                 case TFTP_ERR_ACCESS_DENIED:
660                         puts("Not retrying...\n");
661                         eth_halt();
662                         net_set_state(NETLOOP_FAIL);
663                         break;
664                 case TFTP_ERR_UNDEFINED:
665                 case TFTP_ERR_DISK_FULL:
666                 case TFTP_ERR_UNEXPECTED_OPCODE:
667                 case TFTP_ERR_UNKNOWN_TRANSFER_ID:
668                 case TFTP_ERR_FILE_ALREADY_EXISTS:
669                 default:
670                         puts("Starting again\n\n");
671                         net_start_again();
672                         break;
673                 }
674                 break;
675         }
676 }
677
678
679 static void tftp_timeout_handler(void)
680 {
681         if (++timeout_count > timeout_count_max) {
682                 restart("Retry count exceeded");
683         } else {
684                 puts("T ");
685                 net_set_timeout_handler(timeout_ms, tftp_timeout_handler);
686                 if (tftp_state != STATE_RECV_WRQ)
687                         tftp_send();
688         }
689 }
690
691 /* Initialize tftp_load_addr and tftp_load_size from image_load_addr and lmb */
692 static int tftp_init_load_addr(void)
693 {
694 #ifdef CONFIG_LMB
695         struct lmb lmb;
696         phys_size_t max_size;
697
698         lmb_init_and_reserve(&lmb, gd->bd, (void *)gd->fdt_blob);
699
700         max_size = lmb_get_free_size(&lmb, image_load_addr);
701         if (!max_size)
702                 return -1;
703
704         tftp_load_size = max_size;
705 #endif
706         tftp_load_addr = image_load_addr;
707         return 0;
708 }
709
710 void tftp_start(enum proto_t protocol)
711 {
712 #if CONFIG_NET_TFTP_VARS
713         char *ep;             /* Environment pointer */
714
715         /*
716          * Allow the user to choose TFTP blocksize and timeout.
717          * TFTP protocol has a minimal timeout of 1 second.
718          */
719
720         ep = env_get("tftpblocksize");
721         if (ep != NULL)
722                 tftp_block_size_option = simple_strtol(ep, NULL, 10);
723
724         ep = env_get("tftpwindowsize");
725         if (ep != NULL)
726                 tftp_window_size_option = simple_strtol(ep, NULL, 10);
727
728         ep = env_get("tftptimeout");
729         if (ep != NULL)
730                 timeout_ms = simple_strtol(ep, NULL, 10);
731
732         if (timeout_ms < 1000) {
733                 printf("TFTP timeout (%ld ms) too low, set min = 1000 ms\n",
734                        timeout_ms);
735                 timeout_ms = 1000;
736         }
737
738         ep = env_get("tftptimeoutcountmax");
739         if (ep != NULL)
740                 tftp_timeout_count_max = simple_strtol(ep, NULL, 10);
741
742         if (tftp_timeout_count_max < 0) {
743                 printf("TFTP timeout count max (%d ms) negative, set to 0\n",
744                        tftp_timeout_count_max);
745                 tftp_timeout_count_max = 0;
746         }
747 #endif
748
749         debug("TFTP blocksize = %i, TFTP windowsize = %d timeout = %ld ms\n",
750               tftp_block_size_option, tftp_window_size_option, timeout_ms);
751
752         tftp_remote_ip = net_server_ip;
753         if (!net_parse_bootfile(&tftp_remote_ip, tftp_filename, MAX_LEN)) {
754                 sprintf(default_filename, "%02X%02X%02X%02X.img",
755                         net_ip.s_addr & 0xFF,
756                         (net_ip.s_addr >>  8) & 0xFF,
757                         (net_ip.s_addr >> 16) & 0xFF,
758                         (net_ip.s_addr >> 24) & 0xFF);
759
760                 strncpy(tftp_filename, default_filename, DEFAULT_NAME_LEN);
761                 tftp_filename[DEFAULT_NAME_LEN - 1] = 0;
762
763                 printf("*** Warning: no boot file name; using '%s'\n",
764                        tftp_filename);
765         }
766
767         printf("Using %s device\n", eth_get_name());
768         printf("TFTP %s server %pI4; our IP address is %pI4",
769 #ifdef CONFIG_CMD_TFTPPUT
770                protocol == TFTPPUT ? "to" : "from",
771 #else
772                "from",
773 #endif
774                &tftp_remote_ip, &net_ip);
775
776         /* Check if we need to send across this subnet */
777         if (net_gateway.s_addr && net_netmask.s_addr) {
778                 struct in_addr our_net;
779                 struct in_addr remote_net;
780
781                 our_net.s_addr = net_ip.s_addr & net_netmask.s_addr;
782                 remote_net.s_addr = tftp_remote_ip.s_addr & net_netmask.s_addr;
783                 if (our_net.s_addr != remote_net.s_addr)
784                         printf("; sending through gateway %pI4", &net_gateway);
785         }
786         putc('\n');
787
788         printf("Filename '%s'.", tftp_filename);
789
790         if (net_boot_file_expected_size_in_blocks) {
791                 printf(" Size is 0x%x Bytes = ",
792                        net_boot_file_expected_size_in_blocks << 9);
793                 print_size(net_boot_file_expected_size_in_blocks << 9, "");
794         }
795
796         putc('\n');
797 #ifdef CONFIG_CMD_TFTPPUT
798         tftp_put_active = (protocol == TFTPPUT);
799         if (tftp_put_active) {
800                 printf("Save address: 0x%lx\n", image_save_addr);
801                 printf("Save size:    0x%lx\n", image_save_size);
802                 net_boot_file_size = image_save_size;
803                 puts("Saving: *\b");
804                 tftp_state = STATE_SEND_WRQ;
805                 new_transfer();
806         } else
807 #endif
808         {
809                 if (tftp_init_load_addr()) {
810                         eth_halt();
811                         net_set_state(NETLOOP_FAIL);
812                         puts("\nTFTP error: ");
813                         puts("trying to overwrite reserved memory...\n");
814                         return;
815                 }
816                 printf("Load address: 0x%lx\n", tftp_load_addr);
817                 puts("Loading: *\b");
818                 tftp_state = STATE_SEND_RRQ;
819         }
820
821         time_start = get_timer(0);
822         timeout_count_max = tftp_timeout_count_max;
823
824         net_set_timeout_handler(timeout_ms, tftp_timeout_handler);
825         net_set_udp_handler(tftp_handler);
826 #ifdef CONFIG_CMD_TFTPPUT
827         net_set_icmp_handler(icmp_handler);
828 #endif
829         tftp_remote_port = WELL_KNOWN_PORT;
830         timeout_count = 0;
831         /* Use a pseudo-random port unless a specific port is set */
832         tftp_our_port = 1024 + (get_timer(0) % 3072);
833
834 #ifdef CONFIG_TFTP_PORT
835         ep = env_get("tftpdstp");
836         if (ep != NULL)
837                 tftp_remote_port = simple_strtol(ep, NULL, 10);
838         ep = env_get("tftpsrcp");
839         if (ep != NULL)
840                 tftp_our_port = simple_strtol(ep, NULL, 10);
841 #endif
842         tftp_cur_block = 0;
843         tftp_windowsize = 1;
844         tftp_last_nack = 0;
845         /* zero out server ether in case the server ip has changed */
846         memset(net_server_ethaddr, 0, 6);
847         /* Revert tftp_block_size to dflt */
848         tftp_block_size = TFTP_BLOCK_SIZE;
849 #ifdef CONFIG_TFTP_TSIZE
850         tftp_tsize = 0;
851         tftp_tsize_num_hash = 0;
852 #endif
853
854         tftp_send();
855 }
856
857 #ifdef CONFIG_CMD_TFTPSRV
858 void tftp_start_server(void)
859 {
860         tftp_filename[0] = 0;
861
862         if (tftp_init_load_addr()) {
863                 eth_halt();
864                 net_set_state(NETLOOP_FAIL);
865                 puts("\nTFTP error: trying to overwrite reserved memory...\n");
866                 return;
867         }
868         printf("Using %s device\n", eth_get_name());
869         printf("Listening for TFTP transfer on %pI4\n", &net_ip);
870         printf("Load address: 0x%lx\n", tftp_load_addr);
871
872         puts("Loading: *\b");
873
874         timeout_count_max = tftp_timeout_count_max;
875         timeout_count = 0;
876         timeout_ms = TIMEOUT;
877         net_set_timeout_handler(timeout_ms, tftp_timeout_handler);
878
879         /* Revert tftp_block_size to dflt */
880         tftp_block_size = TFTP_BLOCK_SIZE;
881         tftp_cur_block = 0;
882         tftp_our_port = WELL_KNOWN_PORT;
883         tftp_windowsize = 1;
884         tftp_next_ack = tftp_windowsize;
885
886 #ifdef CONFIG_TFTP_TSIZE
887         tftp_tsize = 0;
888         tftp_tsize_num_hash = 0;
889 #endif
890
891         tftp_state = STATE_RECV_WRQ;
892         net_set_udp_handler(tftp_handler);
893
894         /* zero out server ether in case the server ip has changed */
895         memset(net_server_ethaddr, 0, 6);
896 }
897 #endif /* CONFIG_CMD_TFTPSRV */