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