]> git.kernelconcepts.de Git - karo-tx-uboot.git/blob - common/cmd_bootce.c
tpm: Convert drivers to use SPDX
[karo-tx-uboot.git] / common / cmd_bootce.c
1 /*
2  * Copyright (C) 2012 Lothar Waßmann <LW@KARO-electronics.de>
3  * based on: code from RedBoot (C) Uwe Steinkohl <US@KARO-electronics.de>
4  *
5  * See file CREDITS for list of people who contributed to this
6  * project.
7  *
8  * This program is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License as
10  * published by the Free Software Foundation; either version 2 of
11  * the License, or (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
21  * MA 02111-1307 USA
22  */
23
24 #include <common.h>
25 #include <command.h>
26 #include <net.h>
27 #include <wince.h>
28 #include <nand.h>
29 #include <malloc.h>
30 #include <asm/errno.h>
31 #include <jffs2/load_kernel.h>
32
33 DECLARE_GLOBAL_DATA_PTR;
34
35 #define WINCE_VRAM_BASE         0x80000000
36 #define CE_FIX_ADDRESS(a)       ((void *)((a) - WINCE_VRAM_BASE + CONFIG_SYS_SDRAM_BASE))
37
38 #ifndef INT_MAX
39 #define INT_MAX                 ((int)(~0U >> 1))
40 #endif
41
42 /* Bin image parse states */
43 #define CE_PS_RTI_ADDR          0
44 #define CE_PS_RTI_LEN           1
45 #define CE_PS_E_ADDR            2
46 #define CE_PS_E_LEN             3
47 #define CE_PS_E_CHKSUM          4
48 #define CE_PS_E_DATA            5
49
50 #define CE_MIN(a, b)            (((a) < (b)) ? (a) : (b))
51 #define CE_MAX(a, b)            (((a) > (b)) ? (a) : (b))
52
53 static ce_bin __attribute__ ((aligned (32))) g_bin;
54 static ce_net __attribute__ ((aligned (32))) g_net;
55 static struct in_addr server_ip;
56
57 static void ce_init_bin(ce_bin *bin, unsigned char *dataBuffer)
58 {
59         memset(bin, 0, sizeof(*bin));
60
61         bin->data = dataBuffer;
62         bin->parseState = CE_PS_RTI_ADDR;
63         bin->parsePtr = (unsigned char *)bin;
64 }
65
66 static int ce_is_bin_image(void *image, int imglen)
67 {
68         if (imglen < CE_BIN_SIGN_LEN) {
69                 return 0;
70         }
71
72         return memcmp(image, CE_BIN_SIGN, CE_BIN_SIGN_LEN) == 0;
73 }
74
75 static const struct ce_magic {
76         char magic[8];
77         size_t size;
78         ce_std_driver_globals drv_glb;
79 } ce_magic_template = {
80         .magic = "KARO_CE6",
81         .size = sizeof(ce_std_driver_globals),
82         .drv_glb = {
83                 .header = {
84                         .signature = STD_DRV_GLB_SIGNATURE,
85                         .oalVersion = 1,
86                         .bspVersion = 2,
87                 },
88         },
89 };
90
91 #ifdef DEBUG
92 static void __attribute__((unused)) ce_dump_block(void *ptr, int length)
93 {
94         char *p = ptr;
95         int i;
96         int j;
97
98         for (i = 0; i < length; i++) {
99                 if (!(i % 16)) {
100                         printf("\n%p: ", ptr + i);
101                 }
102
103                 printf("%02x ", p[i]);
104                 if (!((i + 1) % 16)){
105                         printf("      ");
106                         for (j = i - 15; j <= i; j++){
107                                 if((p[j] > 0x1f) && (p[j] < 0x7f)) {
108                                         printf("%c", p[j]);
109                                 } else {
110                                         printf(".");
111                                 }
112                         }
113                 }
114         }
115         printf("\n");
116 }
117 #else
118 static inline void ce_dump_block(void *ptr, int length)
119 {
120 }
121 #endif
122
123 static void ce_setup_std_drv_globals(ce_std_driver_globals *std_drv_glb)
124 {
125         char *mtdparts = getenv("mtdparts");
126         size_t max_len = ALIGN((unsigned long)std_drv_glb, SZ_4K) -
127                 (unsigned long)&std_drv_glb->mtdparts;
128
129         if (eth_get_dev()) {
130                 memcpy(&std_drv_glb->kitl.mac, eth_get_dev()->enetaddr,
131                         sizeof(std_drv_glb->kitl.mac));
132         }
133         snprintf(std_drv_glb->deviceId, sizeof(std_drv_glb->deviceId),
134                 "Triton%02X", eth_get_dev()->enetaddr[5]);
135
136         net_copy_ip(&std_drv_glb->kitl.ipAddress, &net_ip);
137         std_drv_glb->kitl.ipMask = getenv_ip("netmask");
138         std_drv_glb->kitl.ipRoute = getenv_ip("gatewayip");
139
140         if (mtdparts) {
141                 strncpy(std_drv_glb->mtdparts, mtdparts, max_len);
142                 std_drv_glb->mtdparts[max_len - 1] = '\0';
143         } else {
144                 printf("Failed to get mtdparts environment variable\n");
145         }
146 }
147
148 static void ce_init_drv_globals(void)
149 {
150         struct ce_magic *ce_magic = (void *)CONFIG_SYS_SDRAM_BASE + 0x160;
151         ce_std_driver_globals *std_drv_glb = &ce_magic->drv_glb;
152
153         debug("Copying CE MAGIC from %p to %p..%p\n",
154                 &ce_magic_template, ce_magic,
155                 (void *)ce_magic + sizeof(*ce_magic) - 1);
156         memcpy(ce_magic, &ce_magic_template, sizeof(*ce_magic));
157
158         ce_setup_std_drv_globals(std_drv_glb);
159         ce_magic->size = sizeof(*std_drv_glb) +
160                 strlen(std_drv_glb->mtdparts) + 1;
161         ce_dump_block(ce_magic, offsetof(struct ce_magic, drv_glb) +
162                 ce_magic->size);
163 }
164
165 static void ce_prepare_run_bin(ce_bin *bin)
166 {
167         /* Clear os RAM area (if needed) */
168         if (bin->edbgConfig.flags & EDBG_FL_CLEANBOOT) {
169                 debug("cleaning memory from %p to %p\n",
170                         bin->eRamStart, bin->eRamStart + bin->eRamLen);
171
172                 printf("Preparing clean boot ... ");
173                 memset(bin->eRamStart, 0, bin->eRamLen);
174                 printf("ok\n");
175         }
176
177         ce_init_drv_globals();
178
179         /*
180          * Make sure, all the above makes it into SDRAM because
181          * WinCE switches the cache & MMU off, obviously without
182          * flushing it first!
183          */
184         flush_dcache_all();
185 }
186
187 static int ce_lookup_ep_bin(ce_bin *bin)
188 {
189         ce_rom_hdr *header;
190         ce_toc_entry *tentry;
191         e32_rom *e32;
192         unsigned int i;
193         uint32_t *sig = (uint32_t *)(bin->rtiPhysAddr + ROM_SIGNATURE_OFFSET);
194
195         debug("Looking for TOC signature at %p\n", sig);
196
197         /* Check image Table Of Contents (TOC) signature */
198         if (*sig != ROM_SIGNATURE) {
199                 printf("Error: Did not find image TOC signature!\n");
200                 printf("Expected %08x at address %p; found %08x instead\n",
201                         ROM_SIGNATURE, sig, *sig);
202                 return 0;
203         }
204
205         /* Lookup entry point */
206         header = CE_FIX_ADDRESS(*(unsigned int *)(bin->rtiPhysAddr +
207                                                 ROM_SIGNATURE_OFFSET +
208                                                 sizeof(unsigned int)));
209         tentry = (ce_toc_entry *)(header + 1);
210
211         for (i = 0; i < header->nummods; i++) {
212                 // Look for 'nk.exe' module
213                 if (strcmp(CE_FIX_ADDRESS(tentry[i].fileName), "nk.exe") == 0) {
214                         // Save entry point and RAM addresses
215
216                         e32 = CE_FIX_ADDRESS(tentry[i].e32Offset);
217
218                         bin->eEntryPoint = CE_FIX_ADDRESS(tentry[i].loadOffset) +
219                                 e32->e32_entryrva;
220                         bin->eRamStart = CE_FIX_ADDRESS(header->ramStart);
221                         bin->eRamLen = header->ramEnd - header->ramStart;
222                         return 1;
223                 }
224         }
225
226         // Error: Did not find 'nk.exe' module
227         return 0;
228 }
229
230 static int ce_parse_bin(ce_bin *bin)
231 {
232         unsigned char *pbData = bin->data;
233         int len = bin->dataLen;
234         int copyLen;
235
236         debug("starting ce image parsing:\n\tbin->binLen: 0x%08X\n", bin->binLen);
237
238         if (len) {
239                 if (bin->binLen == 0) {
240                         // Check for the .BIN signature first
241                         if (!ce_is_bin_image(pbData, len)) {
242                                 printf("Error: Invalid or corrupted .BIN image!\n");
243                                 return CE_PR_ERROR;
244                         }
245
246                         printf("Loading Windows CE .BIN image ...\n");
247                         // Skip signature
248                         len -= CE_BIN_SIGN_LEN;
249                         pbData += CE_BIN_SIGN_LEN;
250                 }
251
252                 while (len) {
253                         switch (bin->parseState) {
254                         case CE_PS_RTI_ADDR:
255                         case CE_PS_RTI_LEN:
256                         case CE_PS_E_ADDR:
257                         case CE_PS_E_LEN:
258                         case CE_PS_E_CHKSUM:
259                                 copyLen = CE_MIN(sizeof(unsigned int) - bin->parseLen, len);
260                                 memcpy(&bin->parsePtr[bin->parseLen], pbData, copyLen);
261
262                                 bin->parseLen += copyLen;
263                                 len -= copyLen;
264                                 pbData += copyLen;
265
266                                 if (bin->parseLen == sizeof(unsigned int)) {
267                                         if (bin->parseState == CE_PS_RTI_ADDR)
268                                                 bin->rtiPhysAddr = CE_FIX_ADDRESS(bin->rtiPhysAddr);
269                                         else if (bin->parseState == CE_PS_E_ADDR &&
270                                                 bin->ePhysAddr)
271                                                 bin->ePhysAddr = CE_FIX_ADDRESS(bin->ePhysAddr);
272
273                                         bin->parseState++;
274                                         bin->parseLen = 0;
275                                         bin->parsePtr += sizeof(unsigned int);
276
277                                         if (bin->parseState == CE_PS_E_DATA) {
278                                                 if (bin->ePhysAddr) {
279                                                         bin->parsePtr = bin->ePhysAddr;
280                                                         bin->parseChkSum = 0;
281                                                 } else {
282                                                         /* EOF */
283                                                         len = 0;
284                                                         bin->endOfBin = 1;
285                                                 }
286                                         }
287                                 }
288                                 break;
289
290                         case CE_PS_E_DATA:
291                                 debug("ePhysAddr=%p physlen=%08x parselen=%08x\n",
292                                         bin->ePhysAddr, bin->ePhysLen, bin->parseLen);
293                                 if (bin->ePhysAddr) {
294                                         copyLen = CE_MIN(bin->ePhysLen - bin->parseLen, len);
295                                         bin->parseLen += copyLen;
296                                         len -= copyLen;
297
298                                         while (copyLen--) {
299                                                 bin->parseChkSum += *pbData;
300                                                 *bin->parsePtr++ = *pbData++;
301                                         }
302
303                                         if (bin->parseLen == bin->ePhysLen) {
304                                                 printf("Section [%02d]: address %p, size 0x%08X, checksum %s\n",
305                                                         bin->section,
306                                                         bin->ePhysAddr,
307                                                         bin->ePhysLen,
308                                                         (bin->eChkSum == bin->parseChkSum) ? "ok" : "fail");
309
310                                                 if (bin->eChkSum != bin->parseChkSum) {
311                                                         printf("Error: Checksum error, corrupted .BIN file!\n");
312                                                         printf("checksum calculated: 0x%08x from file: 0x%08x\n",
313                                                                 bin->parseChkSum, bin->eChkSum);
314                                                         bin->binLen = 0;
315                                                         return CE_PR_ERROR;
316                                                 }
317
318                                                 bin->section++;
319                                                 bin->parseState = CE_PS_E_ADDR;
320                                                 bin->parseLen = 0;
321                                                 bin->parsePtr = (unsigned char *)&bin->ePhysAddr;
322                                         }
323                                 } else {
324                                         bin->parseLen = 0;
325                                         bin->endOfBin = 1;
326                                         len = 0;
327                                 }
328                                 break;
329                         }
330                 }
331         }
332
333         if (bin->endOfBin) {
334                 if (!ce_lookup_ep_bin(bin)) {
335                         printf("Error: entry point not found!\n");
336                         bin->binLen = 0;
337                         return CE_PR_ERROR;
338                 }
339
340                 printf("Entry point: %p, address range: %p-%p\n",
341                         bin->eEntryPoint,
342                         bin->rtiPhysAddr,
343                         bin->rtiPhysAddr + bin->rtiPhysLen);
344
345                 return CE_PR_EOF;
346         }
347
348         /* Need more data */
349         bin->binLen += bin->dataLen;
350         return CE_PR_MORE;
351 }
352
353 static int ce_bin_load(void *image, int imglen)
354 {
355         ce_init_bin(&g_bin, image);
356         g_bin.dataLen = imglen;
357         if (ce_parse_bin(&g_bin) == CE_PR_EOF) {
358                 ce_prepare_run_bin(&g_bin);
359                 return 1;
360         }
361
362         return 0;
363 }
364
365 static void ce_run_bin(void (*entry)(void))
366 {
367         printf("Launching Windows CE ...\n");
368 #ifdef TEST_LAUNCH
369 return;
370 #endif
371         entry();
372 }
373
374 static int do_bootce(cmd_tbl_t *cmdtp, int flag, int argc, char *const argv[])
375 {
376         void *addr;
377         size_t image_size;
378
379         if (argc > 1) {
380                 if (strcmp(argv[1], "-i") == 0) {
381                         ce_init_drv_globals();
382                         return CMD_RET_SUCCESS;
383                 }
384                 addr = (void *)simple_strtoul(argv[1], NULL, 16);
385                 image_size = INT_MAX;           /* actually we do not know the image size */
386         } else if (getenv("fileaddr") != NULL) {
387                 addr = (void *)getenv_ulong("fileaddr", 16, 0);
388                 image_size = getenv_ulong("filesize", 16, INT_MAX);
389         } else {
390                 return CMD_RET_USAGE;
391         }
392
393         printf ("## Booting Windows CE Image from address %p ...\n", addr);
394
395         /* check if there is a valid windows CE image */
396         if (ce_is_bin_image(addr, image_size)) {
397                 if (!ce_bin_load(addr, image_size)) {
398                         /* Ops! Corrupted .BIN image! */
399                         /* Handle error here ...      */
400                         printf("corrupted .BIN image !!!\n");
401                         return CMD_RET_FAILURE;
402                 }
403                 if (getenv_yesno("autostart") != 1) {
404                         /*
405                          * just use bootce to load the image to SDRAM;
406                          * Do not start it automatically.
407                          */
408                         setenv_addr("fileaddr", g_bin.eEntryPoint);
409                         return CMD_RET_SUCCESS;
410                 }
411                 ce_run_bin(g_bin.eEntryPoint);          /* start the image */
412         } else {
413                 printf("Image does not seem to be a valid Windows CE image!\n");
414                 return CMD_RET_FAILURE;
415         }
416         return CMD_RET_FAILURE; /* never reached - just to keep compiler happy */
417 }
418 U_BOOT_CMD(
419         bootce, 2, 0, do_bootce,
420         "Boot a Windows CE image from RAM",
421         "[addr]\n"
422         "\taddr\t\tboot image from address addr (default ${fileaddr})\n"
423         "or\n"
424         "\t-i\t\tinitialize the WinCE globals data structure (before loading a .nb0 image)"
425 );
426
427 #ifdef CONFIG_CMD_NAND
428 static int ce_nand_load(ce_bin *bin, loff_t *offset, void *buf, size_t max_len)
429 {
430         int ret;
431         size_t len = max_len;
432         nand_info_t *nand = &nand_info[0];
433
434         while (nand_block_isbad(nand, *offset & ~(max_len - 1))) {
435                 printf("Skipping bad block 0x%08llx\n",
436                         *offset & ~(max_len - 1));
437                 *offset += max_len;
438                 if (*offset + max_len > nand->size)
439                         return -EINVAL;
440         }
441
442         ret = nand_read(nand, *offset, &len, buf);
443         if (ret < 0)
444                 return ret;
445
446         bin->dataLen = len;
447         return len;
448 }
449
450 static int do_nbootce(cmd_tbl_t *cmdtp, int flag, int argc, char *const argv[])
451 {
452         int ret;
453         struct mtd_device *dev;
454         struct part_info *part_info;
455         u8 part_num;
456         loff_t offset;
457         char *end;
458         void *buffer;
459         size_t bufsize = nand_info[0].erasesize, len;
460
461         if (argc < 2 || argc > 3)
462                 return CMD_RET_USAGE;
463
464         ret = mtdparts_init();
465         if (ret)
466                 return CMD_RET_FAILURE;
467
468         offset = simple_strtoul(argv[1], &end, 16);
469         if (*end != '\0') {
470                 ret = find_dev_and_part(argv[1], &dev, &part_num,
471                                         &part_info);
472                 if (ret != 0) {
473                         printf("Partition '%s' not found\n", argv[1]);
474                         return CMD_RET_FAILURE;
475                 }
476                 offset = part_info->offset;
477                 printf ("## Booting Windows CE Image from NAND partition %s at offset %08llx\n",
478                         argv[1], offset);
479         } else {
480                 printf ("## Booting Windows CE Image from NAND offset %08llx\n",
481                         offset);
482         }
483
484         buffer = malloc(bufsize);
485         if (buffer == NULL) {
486                 printf("Failed to allocate %u byte buffer\n", bufsize);
487                 return CMD_RET_FAILURE;
488         }
489
490         ce_init_bin(&g_bin, buffer);
491
492         ret = ce_nand_load(&g_bin, &offset, buffer, bufsize);
493         if (ret < 0) {
494                 printf("Failed to read NAND: %d\n", ret);
495                 goto err;
496         }
497         len = ret;
498         /* check if there is a valid windows CE image header */
499         if (ce_is_bin_image(buffer, len)) {
500                 do {
501                         ret = ce_parse_bin(&g_bin);
502                         switch (ret) {
503                         case CE_PR_MORE:
504                         {
505                                 if (ctrlc()) {
506                                         printf("NBOOTCE - canceled by user\n");
507                                         goto err;
508                                 }
509                                 offset += len;
510                                 len = ce_nand_load(&g_bin, &offset, buffer,
511                                                 bufsize);
512                                 if (len < 0) {
513                                         printf("Nand read error: %d\n", len);
514                                         ret = len;
515                                         goto err;
516                                 }
517                         }
518                         break;
519
520                         case CE_PR_EOF:
521                                 ce_prepare_run_bin(&g_bin);
522                                 break;
523
524                         case CE_PR_ERROR:
525                                 break;
526                         }
527                 } while (ret == CE_PR_MORE);
528                 free(buffer);
529                 if (ret != CE_PR_EOF)
530                         return CMD_RET_FAILURE;
531
532                 if (getenv_yesno("autostart") != 1) {
533                         /*
534                          * just use bootce to load the image to SDRAM;
535                          * Do not start it automatically.
536                          */
537                         setenv_addr("fileaddr", g_bin.eEntryPoint);
538                         return CMD_RET_SUCCESS;
539                 }
540                 ce_run_bin(g_bin.eEntryPoint);          /* start the image */
541         } else {
542                 printf("Image does not seem to be a valid Windows CE image!\n");
543         }
544 err:
545         free(buffer);
546         return CMD_RET_FAILURE;
547 }
548 U_BOOT_CMD(
549         nbootce, 2, 0, do_nbootce,
550         "Boot a Windows CE image from NAND",
551         "off|partitition\n"
552         "\toff\t\t- flash offset (hex)\n"
553         "\tpartition\t- partition name"
554 );
555 #endif
556
557 static int ce_send_write_ack(ce_net *net)
558 {
559         int ret;
560         unsigned short wdata[2];
561         int retries = 0;
562
563         wdata[0] = htons(EDBG_CMD_WRITE_ACK);
564         wdata[1] = htons(net->blockNum);
565         net->dataLen = sizeof(wdata);
566         memcpy(net->data, wdata, net->dataLen);
567
568         do {
569                 ret = bootme_send_frame(net->data, net->dataLen);
570                 if (ret) {
571                         printf("Failed to send write ack %d; retries=%d\n",
572                                 ret, retries);
573                 }
574         } while (ret != 0 && retries-- > 0);
575         return ret;
576 }
577
578 static enum bootme_state ce_process_download(ce_net *net, ce_bin *bin)
579 {
580         int ret = net->state;
581
582         if (net->dataLen >= 4) {
583                 unsigned short command;
584                 unsigned short blknum;
585
586                 memcpy(&command, net->data, sizeof(command));
587                 command = ntohs(command);
588                 debug("command found: 0x%04X\n", command);
589
590                 if (net->state == BOOTME_DOWNLOAD) {
591                         unsigned short nxt = net->blockNum + 1;
592
593                         memcpy(&blknum, &net->data[2], sizeof(blknum));
594                         blknum = ntohs(blknum);
595                         if (blknum == nxt) {
596                                 net->blockNum = blknum;
597                         } else {
598                                 int rc = ce_send_write_ack(net);
599
600                                 if (net->verbose)
601                                         printf("Dropping out of sequence packet with ID %d (expected %d)\n",
602                                                 blknum, nxt);
603                                 if (rc != 0)
604                                         return rc;
605
606                                 return ret;
607                         }
608                 }
609
610                 switch (command) {
611                 case EDBG_CMD_WRITE_REQ:
612                         if (net->state == BOOTME_INIT) {
613                                 // Check file name for WRITE request
614                                 // CE EShell uses "boot.bin" file name
615                                 if (strncmp((char *)&net->data[2],
616                                                 "boot.bin", 8) == 0) {
617                                         // Some diag output
618                                         if (net->verbose) {
619                                                 printf("Locked Down download link, IP: %pI4\n",
620                                                         &net_server_ip);
621                                                 printf("Sending BOOTME request [%d] to %pI4\n",
622                                                         net->seqNum, &net_server_ip);
623                                         }
624
625                                         // Lock down EShell download link
626                                         ret = BOOTME_DOWNLOAD;
627                                 } else {
628                                         // Unknown link
629                                         printf("Unknown link\n");
630                                 }
631
632                                 if (ret == BOOTME_DOWNLOAD) {
633                                         int rc = ce_send_write_ack(net);
634                                         if (rc != 0)
635                                                 return rc;
636                                 }
637                         }
638                         break;
639
640                 case EDBG_CMD_WRITE:
641                         /* Fixup data len */
642                         bin->data = &net->data[4];
643                         bin->dataLen = net->dataLen - 4;
644                         ret = ce_parse_bin(bin);
645                         if (ret != CE_PR_ERROR) {
646                                 int rc = ce_send_write_ack(net);
647                                 if (rc)
648                                         return rc;
649                                 if (ret == CE_PR_EOF)
650                                         ret = BOOTME_DONE;
651                         } else {
652                                 ret = BOOTME_ERROR;
653                         }
654                         break;
655
656                 case EDBG_CMD_READ_REQ:
657                         printf("Ignoring EDBG_CMD_READ_REQ\n");
658                         /* Read requests are not supported
659                          * Do nothing ...
660                          */
661                         break;
662
663                 case EDBG_CMD_ERROR:
664                         printf("Error: unknown error on the host side\n");
665
666                         bin->binLen = 0;
667                         ret = BOOTME_ERROR;
668                         break;
669
670                 default:
671                         printf("unknown command 0x%04X\n", command);
672                         net->state = BOOTME_ERROR;
673                 }
674         }
675         return ret;
676 }
677
678 static enum bootme_state ce_process_edbg(ce_net *net, ce_bin *bin)
679 {
680         enum bootme_state ret = net->state;
681         eth_dbg_hdr header;
682
683         if (net->dataLen < sizeof(header)) {
684                 /* Bad packet */
685                 printf("Invalid packet size %u\n", net->dataLen);
686                 net->dataLen = 0;
687                 return ret;
688         }
689         memcpy(&header, net->data, sizeof(header));
690         if (header.id != EDBG_ID) {
691                 /* Bad packet */
692                 printf("Bad EDBG ID %08x\n", header.id);
693                 net->dataLen = 0;
694                 return ret;
695         }
696
697         if (header.service != EDBG_SVC_ADMIN) {
698                 /* Unknown service */
699                 printf("Bad EDBG service %02x\n", header.service);
700                 net->dataLen = 0;
701                 return ret;
702         }
703
704         if (net->state == BOOTME_INIT) {
705                 /* Some diag output */
706                 if (net->verbose) {
707                         printf("Locked Down EDBG service link, IP: %pI4\n",
708                                 &net_server_ip);
709                 }
710
711                 /* Lock down EDBG link */
712                 net->state = BOOTME_DEBUG;
713         }
714
715         switch (header.cmd) {
716         case EDBG_CMD_JUMPIMG:
717                 net->gotJumpingRequest = 1;
718
719                 if (net->verbose) {
720                         printf("Received JUMPING command\n");
721                 }
722                 /* Just pass through and copy CONFIG structure */
723                 ret = BOOTME_DONE;
724         case EDBG_CMD_OS_CONFIG:
725                 /* Copy config structure */
726                 memcpy(&bin->edbgConfig, &net->data[sizeof(header)],
727                         sizeof(edbg_os_config_data));
728                 if (net->verbose) {
729                         printf("Received CONFIG command\n");
730                         if (bin->edbgConfig.flags & EDBG_FL_DBGMSG) {
731                                 printf("--> Enabling DBGMSG service, IP: %pI4, port: %d\n",
732                                         &bin->edbgConfig.dbgMsgIPAddr,
733                                         ntohs(bin->edbgConfig.dbgMsgPort));
734                         }
735
736                         if (bin->edbgConfig.flags & EDBG_FL_PPSH) {
737                                 printf("--> Enabling PPSH service, IP: %pI4, port: %d\n",
738                                         &bin->edbgConfig.ppshIPAddr,
739                                         ntohs(bin->edbgConfig.ppshPort));
740                         }
741
742                         if (bin->edbgConfig.flags & EDBG_FL_KDBG) {
743                                 printf("--> Enabling KDBG service, IP: %pI4, port: %d\n",
744                                         &bin->edbgConfig.kdbgIPAddr,
745                                         ntohs(bin->edbgConfig.kdbgPort));
746                         }
747
748                         if (bin->edbgConfig.flags & EDBG_FL_CLEANBOOT) {
749                                 printf("--> Force clean boot\n");
750                         }
751                 }
752                 break;
753
754         default:
755                 if (net->verbose) {
756                         printf("Received unknown command: %08X\n", header.cmd);
757                 }
758                 return BOOTME_ERROR;
759         }
760
761         /* Respond with ack */
762         header.flags = EDBG_FL_FROM_DEV | EDBG_FL_ACK;
763         memcpy(net->data, &header, sizeof(header));
764         net->dataLen = EDBG_DATA_OFFSET;
765
766         int retries = 10;
767         int rc;
768         do {
769                 rc = bootme_send_frame(net->data, net->dataLen);
770                 if (rc != 0) {
771                         printf("Failed to send ACK: %d\n", rc);
772                 }
773         } while (rc && retries-- > 0);
774         return rc ?: ret;
775 }
776
777 static enum bootme_state ce_edbg_handler(const void *buf, size_t len)
778 {
779         if (len == 0)
780                 return BOOTME_DONE;
781
782         g_net.data = (void *)buf;
783         g_net.dataLen = len;
784
785         return ce_process_edbg(&g_net, &g_bin);
786 }
787
788 static void ce_init_edbg_link(ce_net *net)
789 {
790         /* Initialize EDBG link for commands */
791         net->state = BOOTME_INIT;
792 }
793
794 static enum bootme_state ce_download_handler(const void *buf, size_t len)
795 {
796         g_net.data = (void *)buf;
797         g_net.dataLen = len;
798
799         g_net.state = ce_process_download(&g_net, &g_bin);
800         return g_net.state;
801 }
802
803 static int ce_send_bootme(ce_net *net)
804 {
805         eth_dbg_hdr *header;
806         edbg_bootme_data *data;
807         unsigned char txbuf[PKTSIZE_ALIGN];
808 #ifdef DEBUG
809         int     i;
810         unsigned char   *pkt;
811 #endif
812         /* Fill out BOOTME packet */
813         net->data = txbuf;
814
815         memset(net->data, 0, PKTSIZE);
816         header = (eth_dbg_hdr *)net->data;
817         data = (edbg_bootme_data *)header->data;
818
819         header->id = EDBG_ID;
820         header->service = EDBG_SVC_ADMIN;
821         header->flags = EDBG_FL_FROM_DEV;
822         header->seqNum = net->seqNum++;
823         header->cmd = EDBG_CMD_BOOTME;
824
825         data->versionMajor = 0;
826         data->versionMinor = 0;
827         data->cpuId = EDBG_CPU_TYPE_ARM;
828         data->bootmeVer = EDBG_CURRENT_BOOTME_VERSION;
829         data->bootFlags = 0;
830         data->downloadPort = 0;
831         data->svcPort = 0;
832
833         /* MAC address from environment*/
834         if (!eth_getenv_enetaddr("ethaddr", data->macAddr)) {
835                 printf("'ethaddr' is not set or invalid\n");
836                 memset(data->macAddr, 0, sizeof(data->macAddr));
837         }
838
839         /* IP address from active config */
840         net_copy_ip(&data->ipAddr, &net_ip);
841
842         // Device name string (NULL terminated). Should include
843         // platform and number based on Ether address (e.g. Odo42, CEPCLS2346, etc)
844
845         // We will use lower MAC address segment to create device name
846         // eg. MAC '00-0C-C6-69-09-05', device name 'Triton05'
847
848         strncpy(data->platformId, "Triton", sizeof(data->platformId));
849         snprintf(data->deviceName, sizeof(data->deviceName), "%s%02X",
850                 data->platformId, data->macAddr[5]);
851
852 #ifdef DEBUG
853         printf("header->id: %08X\n", header->id);
854         printf("header->service: %08X\n", header->service);
855         printf("header->flags: %08X\n", header->flags);
856         printf("header->seqNum: %08X\n", header->seqNum);
857         printf("header->cmd: %08X\n\n", header->cmd);
858
859         printf("data->versionMajor: %08X\n", data->versionMajor);
860         printf("data->versionMinor: %08X\n", data->versionMinor);
861         printf("data->cpuId: %08X\n", data->cpuId);
862         printf("data->bootmeVer: %08X\n", data->bootmeVer);
863         printf("data->bootFlags: %08X\n", data->bootFlags);
864         printf("data->svcPort: %08X\n\n", ntohs(data->svcPort));
865
866         printf("data->macAddr: %pM\n", data->macAddr);
867         printf("data->ipAddr: %pI4\n", &data->ipAddr);
868         printf("data->platformId: %s\n", data->platformId);
869         printf("data->deviceName: %s\n", data->deviceName);
870 #endif
871         // Some diag output ...
872         if (net->verbose) {
873                 printf("Sending BOOTME request [%d] to %pI4\n", net->seqNum,
874                         &server_ip);
875         }
876
877         net->dataLen = BOOTME_PKT_SIZE;
878 //      net->status = CE_PR_MORE;
879         net->state = BOOTME_INIT;
880 #ifdef DEBUG
881         debug("Start of buffer:      %p\n", net->data);
882         debug("Start of ethernet buffer:   %p\n", net->data);
883         debug("Start of CE header:         %p\n", header);
884         debug("Start of CE data:           %p\n", data);
885
886         pkt = net->data;
887         debug("packet to send (ceconnect): \n");
888         for (i = 0; i < net->dataLen; i++) {
889                 debug("0x%02X ", pkt[i]);
890                 if (!((i + 1) % 16))
891                         debug("\n");
892         }
893         debug("\n");
894 #endif
895         return BootMeRequest(server_ip, net->data, net->dataLen, 1);
896 }
897
898 static inline int ce_init_download_link(ce_net *net, ce_bin *bin, int verbose)
899 {
900         if (!eth_get_dev()) {
901                 printf("No network interface available\n");
902                 return -ENODEV;
903         }
904         printf("Using device '%s'\n", eth_get_name());
905
906         /* Initialize EDBG link for download */
907         memset(net, 0, sizeof(*net));
908
909         net->verbose = verbose;
910
911         /* buffer will be dynamically assigned in ce_download_handler() */
912         ce_init_bin(bin, NULL);
913         return 0;
914 }
915
916 static inline int ce_download_file(ce_net *net, ulong timeout)
917 {
918         ulong start = get_timer_masked();
919
920         while (net->state == BOOTME_INIT) {
921                 int ret;
922
923                 if (timeout && get_timer(start) > timeout) {
924                         printf("CELOAD - Canceled, timeout\n");
925                         return 1;
926                 }
927
928                 if (ctrlc()) {
929                         printf("CELOAD - canceled by user\n");
930                         return 1;
931                 }
932
933                 if (ce_send_bootme(&g_net)) {
934                         printf("CELOAD - error while sending BOOTME request\n");
935                         return 1;
936                 }
937                 if (net->verbose) {
938                         if (timeout) {
939                                 printf("Waiting for connection, timeout %lu sec\n",
940                                         DIV_ROUND_UP(timeout - get_timer(start),
941                                                 CONFIG_SYS_HZ));
942                         } else {
943                                 printf("Waiting for connection, enter ^C to abort\n");
944                         }
945                 }
946
947                 ret = BootMeDownload(ce_download_handler);
948                 if (ret == BOOTME_ERROR) {
949                         printf("CELOAD - aborted\n");
950                         return 1;
951                 }
952         }
953         return 0;
954 }
955
956 static void ce_disconnect(void)
957 {
958         net_set_udp_handler(NULL);
959         eth_halt();
960 }
961
962 static int do_ceconnect(cmd_tbl_t *cmdtp, int flag, int argc, char *const argv[])
963 {
964         int verbose = 0;
965         ulong timeout = 0;
966         int ret = 1;
967         int i;
968
969         server_ip.s_addr = 0;
970
971         for (i = 1; i < argc; i++){
972                 if (*argv[i] != '-')
973                         break;
974                 if (argv[i][1] == 'v') {
975                         verbose = 1;
976                 } else if (argv[i][1] == 't') {
977                         i++;
978                         if (argc > i) {
979                                 timeout = simple_strtoul(argv[i],
980                                                         NULL, 0);
981                                 if (timeout >= UINT_MAX / CONFIG_SYS_HZ) {
982                                         printf("Timeout value %lu out of range (max.: %u)\n",
983                                                 timeout, UINT_MAX / CONFIG_SYS_HZ - 1);
984                                         return CMD_RET_USAGE;
985                                 }
986                                 timeout *= CONFIG_SYS_HZ;
987                         } else {
988                                 printf("Option requires an argument - t\n");
989                                 return CMD_RET_USAGE;
990                         }
991                 } else if (argv[i][1] == 'h') {
992                         i++;
993                         if (argc > i) {
994                                 server_ip = string_to_ip(argv[i]);
995                                 printf("Using server %pI4\n", &server_ip);
996                         } else {
997                                 printf("Option requires an argument - h\n");
998                                 return CMD_RET_USAGE;
999                         }
1000                 }
1001         }
1002
1003         if (ce_init_download_link(&g_net, &g_bin, verbose) != 0)
1004                 goto err;
1005
1006         if (ce_download_file(&g_net, timeout))
1007                 goto err;
1008
1009         if (g_bin.binLen) {
1010                 // Try to receive edbg commands from host
1011                 ce_init_edbg_link(&g_net);
1012                 if (verbose)
1013                         printf("Waiting for EDBG commands ...\n");
1014
1015                 ret = BootMeDebugStart(ce_edbg_handler);
1016                 if (ret != BOOTME_DONE)
1017                         goto err;
1018
1019                 // Prepare WinCE image for execution
1020                 ce_prepare_run_bin(&g_bin);
1021
1022                 // Launch WinCE, if necessary
1023                 if (g_net.gotJumpingRequest)
1024                         ce_run_bin(g_bin.eEntryPoint);
1025         }
1026         ret = 0;
1027 err:
1028         ce_disconnect();
1029         return ret == 0 ? CMD_RET_SUCCESS : CMD_RET_FAILURE;
1030 }
1031 U_BOOT_CMD(
1032         ceconnect, 6, 1, do_ceconnect,
1033         "Set up a connection to the CE host PC over TCP/IP and download the run-time image",
1034         "[-v] [-t <timeout>] [-h host]\n"
1035         "  -v            - verbose operation\n"
1036         "  -t <timeout>  - max wait time (#sec) for the connection\n"
1037         "  -h <host>     - send BOOTME requests to <host> (default: broadcast address 255.255.255.255)"
1038 );