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