tizen 2.4 release
[kernel/u-boot-tm1.git] / drivers / usb / gadget / fastboot.c
1 /*
2  * Copyright (c) 2009, Google Inc.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  *  * Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  *  * Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in
12  *    the documentation and/or other materials provided with the
13  *    distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
18  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
19  * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
21  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
22  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
23  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
25  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 //#define DEBUG
29 #include <config.h>
30 #include <common.h>
31 #include <asm/errno.h>
32 #include <linux/usb/ch9.h>
33 #include <linux/usb/gadget.h>
34 #include "gadget_chips.h"
35 #include <linux/ctype.h>
36 #include <malloc.h>
37 #include <command.h>
38 #include <nand.h>
39 #include <linux/mtd/mtd.h>
40 #include <linux/mtd/nand.h>
41 #include <jffs2/jffs2.h>
42 #include <asm/types.h>
43 #include <android_boot.h>
44 #include <android_bootimg.h>
45 #include <boot_mode.h>
46 #include <asm/arch/secure_boot.h>
47 #ifdef CONFIG_SECURE_BOOT
48 #include "secure_verify.h"
49 #endif
50 #include "../../mmc/sparse_format.h"
51
52 struct  dl_image_inf{
53         uint32_t base_address;
54         uint32_t max_size;
55         uint32_t data_size;
56 }ImageInfo[2];
57
58 #define NV_HEAD_LEN (512)
59 #define NV_HEAD_MAGIC   (0x00004e56)
60 #define NV_VERSION      (101)
61
62 typedef struct  _NV_HEADER {
63      uint32_t magic;
64      uint32_t len;
65      uint32_t checksum;
66      uint32_t version;
67 }nv_header_t;
68
69 #ifdef CONFIG_EMMC_BOOT
70 #include "../disk/part_uefi.h"
71 #include "../drivers/mmc/card_sdio.h"
72 #include "asm/arch/sci_types.h"
73 #include <ext_common.h>
74 #include <ext4fs.h>
75
76 #define MAGIC_DATA      0xAA55A5A5
77
78 #ifdef CONFIG_ROM_VERIFY_SPL
79 #define SPL_CHECKSUM_LEN        0x8000
80 #endif
81
82 #if defined(CONFIG_SPX30G) || defined(CONFIG_SC9630)
83 #define SPL_CHECKSUM_LEN        0x8000
84 #else
85 #define SPL_CHECKSUM_LEN        0x6000
86 #endif
87 #define CHECKSUM_START_OFFSET   0x28
88 #define MAGIC_DATA_SAVE_OFFSET  (0x20/4)
89 #define CHECKSUM_SAVE_OFFSET    (0x24/4)
90 PARTITION_CFG uefi_part_info[MAX_PARTITION_INFO];
91 #define EFI_SECTOR_SIZE                 (512)
92 #define ERASE_SECTOR_SIZE               ((64 * 1024) / EFI_SECTOR_SIZE)
93 #define EMMC_BUF_SIZE                   (((216 * 1024 * 1024) / EFI_SECTOR_SIZE) * EFI_SECTOR_SIZE)
94 #define FB_ERASE_ALIGN_LENGTH  (0x800)
95 #if defined (CONFIG_SC8825) || defined (CONFIG_TIGER)
96 unsigned char *g_eMMCBuf = (unsigned char*)0x82000000;
97 #else
98 unsigned char *g_eMMCBuf = (unsigned char*)0x2000000;
99 #endif
100
101 #if defined CONFIG_SC8825 || defined(CONFIG_SC8830) || defined(CONFIG_SC9630)
102 #define BOOTLOADER_HEADER_OFFSET 0x20
103 typedef struct{
104         uint32 version;
105         uint32 magicData;
106         uint32 checkSum;
107         uint32 hashLen;
108 }EMMC_BootHeader;
109 #endif
110
111 typedef enum
112 {
113         FB_IMG_RAW = 0,
114         FB_IMG_WITH_SPARSE = 1,
115         FB_IMG_TYPE_MAX
116 }FB_PARTITION_IMG_TYPE;
117
118 typedef enum
119 {
120         FB_PARTITION_PURPOSE_NORMAL,
121         FB_PARTITION_PURPOSE_NV,
122         FB_PARTITION_PURPOSE_PROD,
123         FB_PARTITION_PURPOSE_MAX
124 }FB_PARTITION_PURPOSE;
125
126 typedef struct
127 {
128         CARD_EMMC_PARTITION_TPYE type;
129         FB_PARTITION_PURPOSE purpose;
130         FB_PARTITION_IMG_TYPE img_format;
131         wchar_t* partition_name;
132 }FB_PARTITION_INFO;
133
134 static FB_PARTITION_INFO const s_fb_special_partition_cfg[]={
135         {PARTITION_BOOT1,FB_PARTITION_PURPOSE_NORMAL,FB_IMG_RAW,L"params"},
136         {PARTITION_BOOT2,FB_PARTITION_PURPOSE_NORMAL,FB_IMG_RAW,L"2ndbl"},
137         {PARTITION_USER,FB_PARTITION_PURPOSE_NORMAL,FB_IMG_RAW,L"system"},
138         {PARTITION_USER,FB_PARTITION_PURPOSE_NORMAL,FB_IMG_WITH_SPARSE,L"userdata"},
139         {PARTITION_USER,FB_PARTITION_PURPOSE_NORMAL,FB_IMG_WITH_SPARSE,L"cache"},
140         {PARTITION_USER,FB_PARTITION_PURPOSE_NORMAL,FB_IMG_RAW,L"prodnv"},
141         {PARTITION_USER,FB_PARTITION_PURPOSE_NV,FB_IMG_RAW,L"fixnv1"},
142         {PARTITION_USER,FB_PARTITION_PURPOSE_NV,FB_IMG_RAW,L"tdfixnv1"},
143         {PARTITION_USER,FB_PARTITION_PURPOSE_NV,FB_IMG_RAW,L"wfixnv1"},
144         {PARTITION_MAX,FB_PARTITION_PURPOSE_MAX,FB_IMG_TYPE_MAX,NULL}
145 };
146 #else
147
148 typedef struct {
149         char *vol;
150         char *bakvol;
151 }FB_NV_VOL_INFO;
152
153 static FB_NV_VOL_INFO s_nv_vol_info[]={
154         {"fixnv1","fixnv2"},
155         {"wfixnv1","wfixnv2"},
156         {"tdfixnv1","tdfixnv2"},
157         {NULL,NULL}
158 };
159
160 #endif
161
162 //#define FASTBOOT_DEBUG
163 #ifdef FASTBOOT_DEBUG
164 #define fb_printf(fmt, args...) printf(fmt, ##args)
165 #else
166 #define fb_printf(fmt, args...) do {} while(0)
167 #endif
168
169 #ifdef FLASH_PAGE_SIZE
170 #undef FLASH_PAGE_SIZE
171 #endif
172 #define FLASH_PAGE_SIZE 2048
173
174 #define ROUND_TO_PAGE(x,y) (((x) + (y)) & (~(y)))
175
176 #define GFP_ATOMIC ((gfp_t) 0)
177 static int current_write_position;
178
179 int get_end_write_pos(void)
180 {
181         return current_write_position;
182 }
183 void set_current_write_pos(int pos)
184 {
185         current_write_position = pos;
186 }
187 void move2goodblk(void)
188 {
189         while(1) fb_printf("suspend in move2goodblk\n");
190 }
191 /* todo: give lk strtoul and nuke this */
192 static unsigned hex2unsigned(const char *x)
193 {
194     unsigned n = 0;
195
196     while(*x) {
197         switch(*x) {
198         case '0': case '1': case '2': case '3': case '4':
199         case '5': case '6': case '7': case '8': case '9':
200             n = (n << 4) | (*x - '0');
201             break;
202         case 'a': case 'b': case 'c':
203         case 'd': case 'e': case 'f':
204             n = (n << 4) | (*x - 'a' + 10);
205             break;
206         case 'A': case 'B': case 'C':
207         case 'D': case 'E': case 'F':
208             n = (n << 4) | (*x - 'A' + 10);
209             break;
210         default:
211             return n;
212         }
213         x++;
214     }
215
216     return n;
217 }
218
219 struct fastboot_cmd {
220         struct fastboot_cmd *next;
221         const char *prefix;
222         unsigned prefix_len;
223         void (*handle)(const char *arg, void *data, unsigned sz);
224 };
225
226 struct fastboot_var {
227         struct fastboot_var *next;
228         const char *name;
229         const char *value;
230 };
231
232 static struct fastboot_cmd *cmdlist;
233
234 void fastboot_register(const char *prefix,
235                        void (*handle)(const char *arg, void *data, unsigned sz))
236 {
237         struct fastboot_cmd *cmd;
238         cmd = malloc(sizeof(*cmd));
239         if (cmd) {
240                 cmd->prefix = prefix;
241                 cmd->prefix_len = strlen(prefix);
242                 cmd->handle = handle;
243                 cmd->next = cmdlist;
244                 cmdlist = cmd;
245         }
246 }
247
248 static struct fastboot_var *varlist;
249
250 void fastboot_publish(const char *name, const char *value)
251 {
252         struct fastboot_var *var;
253         var = malloc(sizeof(*var));
254         if (var) {
255                 var->name = name;
256                 var->value = value;
257                 var->next = varlist;
258                 varlist = var;
259         }
260 }
261
262
263 //static event_t usb_online;
264 //static event_t txn_done;
265 static volatile int txn_done;
266 static unsigned char buffer[4096];
267 static struct usb_ep *in, *out;
268 //static struct udc_request *req;
269 static struct usb_request *tx_req, *rx_req;
270 int txn_status;
271
272 #define STATE_OFFLINE   0
273 #define STATE_COMMAND   1
274 #define STATE_COMPLETE  2
275 #define STATE_ERROR     3
276
277 static unsigned fastboot_state = STATE_OFFLINE;
278
279 //static void req_complete(struct udc_request *req, unsigned actual, int status)
280 static void req_complete(struct usb_ep *ep, struct usb_request *req)
281 {
282         if (req->status || req->actual != req->length)
283                 debug("req complete --> %d, %d/%d\n",
284                                 req->status, req->actual, req->length);
285
286         txn_status = req->status;
287         txn_done = 1;
288         /*
289         req->length = actual;
290         event_signal(&txn_done, 0);
291         */
292 }
293
294 static int usb_read(void *_buf, unsigned len)
295 {
296         int r;
297         unsigned xfer;
298         unsigned char *buf = _buf;
299         int count = 0;
300         struct usb_request * req = rx_req;
301
302         if (fastboot_state == STATE_ERROR)
303                 goto oops;
304
305         fb_printf("usb_read(address = 0x%x,len=0x%x)\n",_buf,len);
306         while (len > 0) {
307                 xfer = (len > 4096) ? 4096 : len;
308                 req->buf = buf;
309                 req->length = xfer;
310                 req->complete = req_complete;
311                 //r = udc_request_queue(out, req);
312                 r = usb_ep_queue(out, req, GFP_ATOMIC);
313                 if (r < 0) {
314                         fb_printf("usb_read() queue failed\n");
315                         goto oops;
316                 }
317                 //event_wait(&txn_done);
318                 txn_done = 0;
319                 while(!txn_done)
320                         usb_gadget_handle_interrupts();
321
322                 if (txn_status < 0) {
323                         fb_printf("usb_read() transaction failed\n");
324                         goto oops;
325                 }
326                 if((count % 0x100000) == 0)
327                 fb_printf("remained size = 0x%x\n",len);
328
329                 count += req->actual;
330                 buf += req->actual;
331                 len -= req->actual;
332
333                 /* short transfer? */
334                 if (req->actual != xfer) break;
335         }
336
337         return count;
338
339 oops:
340         fastboot_state = STATE_ERROR;
341         return -1;
342 }
343
344 static int usb_write(void *buf, unsigned len)
345 {
346         int r;
347         struct usb_request * req = tx_req;
348
349         if (fastboot_state == STATE_ERROR)
350                 goto oops;
351
352         req->buf = buf;
353         req->length = len;
354         req->complete = req_complete;
355         txn_done = 0;
356         //r = udc_request_queue(in, req);
357         r = usb_ep_queue(in, req, GFP_ATOMIC);
358         if (r < 0) {
359                 fb_printf("usb_write() queue failed\n");
360                 goto oops;
361         }
362         //event_wait(&txn_done);
363         while(!txn_done)
364                 usb_gadget_handle_interrupts();
365         if (txn_status < 0) {
366                 fb_printf("usb_write() transaction failed\n");
367                 goto oops;
368         }
369         return req->actual;
370
371 oops:
372         fastboot_state = STATE_ERROR;
373         return -1;
374 }
375
376 void fastboot_ack(const char *code, const char *reason)
377 {
378         char response[64] = {0};
379
380         if (fastboot_state != STATE_COMMAND)
381                 return;
382
383         if (reason == 0)
384                 reason = "";
385
386         //snprintf(response, 64, "%s%s", code, reason);
387         if(strlen(code) + strlen(reason) >= 64) {
388                 fb_printf("%s too long string\r\n", __func__);
389         }
390         sprintf(response, "%s%s", code, reason);
391         fastboot_state = STATE_COMPLETE;
392
393         usb_write(response, strlen(response));
394
395 }
396
397 void fastboot_fail(const char *reason)
398 {
399         fastboot_ack("FAIL", reason);
400 }
401
402 void fastboot_okay(const char *info)
403 {
404         fastboot_ack("OKAY", info);
405 }
406
407 static void cmd_getvar(const char *arg, void *data, unsigned sz)
408 {
409         struct fastboot_var *var;
410
411         for (var = varlist; var; var = var->next) {
412                 if (!strcmp(var->name, arg)) {
413                         fastboot_okay(var->value);
414                         return;
415                 }
416         }
417         fastboot_okay("");
418 }
419
420 static void dump_log(char * buf, int len)
421 {
422         int i = 0;
423
424         fb_printf("**dump log_buf ...addr:0x%08x, len:%d\r\n", buf, len);
425
426         for (i = 0; i < len; i++)       {
427                 fb_printf("%02x ", *((unsigned char*)buf+i) );
428                 if(i%0x20 == 0x1f)
429                         fb_printf("\n");
430         }
431 }
432 static void cmd_download(const char *arg, void *data, unsigned sz)
433 {
434         char response[64];
435         unsigned len = hex2unsigned(arg);
436         unsigned read_len,index,max_buffer_size;
437         int r;
438
439         fb_printf("%s\n", __func__);
440
441         fb_printf("arg'%s' data %p, %d,len=0x%x\n",arg, data,sz,len);
442         fb_printf("base0 0x%x size0 0x%x base1=0x%x size1=0x%x\n",\
443                 ImageInfo[0].base_address,ImageInfo[0].max_size,\
444                 ImageInfo[1].base_address,ImageInfo[1].max_size);
445         max_buffer_size = ImageInfo[0].max_size + ImageInfo[1].max_size;
446         if (len > max_buffer_size) {
447                 fastboot_fail("data too large");
448                 return;
449         }
450
451         sprintf(response,"DATA%08x", len);
452         if (usb_write(response, strlen(response)) < 0)
453                 return;
454
455         ImageInfo[0].data_size = 0;
456         ImageInfo[1].data_size = 0;
457         index = 0;
458         read_len = 0;
459         fb_printf("%s-start\n", __func__);
460         do{
461                 if(ImageInfo[index].max_size==0){
462                         fastboot_state = STATE_ERROR;
463                         fb_printf("%s- error1\n", __func__);
464                         return;
465                 }
466                 if(len > ImageInfo[index].max_size)
467                         read_len = ImageInfo[index].max_size;
468                 else
469                         read_len = len;
470                 fb_printf("save data to area[%d].address=0x%x read_len = 0x%x\n",index,ImageInfo[index].base_address,read_len);
471                 r = usb_read(ImageInfo[index].base_address, read_len);
472                 if ((r < 0) || (r != read_len)) {
473                         fastboot_state = STATE_ERROR;
474                         return;
475                 }
476                 len -= read_len;
477                 ImageInfo[index].data_size = read_len;
478                 index++;
479         }while(len > 0);
480         fastboot_okay("");
481 }
482
483 #ifdef CONFIG_EMMC_BOOT
484 unsigned short fastboot_eMMCCheckSum(const unsigned int *src, int len)
485 {
486         unsigned int   sum = 0;
487         unsigned short *src_short_ptr = PNULL;
488
489         while (len > 3){
490                 sum += *src++;
491                 len -= 4;
492         }
493         src_short_ptr = (unsigned short *) src;
494         if (0 != (len&0x2)){
495                 sum += * (src_short_ptr);
496                 src_short_ptr++;
497         }
498         if (0 != (len&0x1)){
499                 sum += * ( (unsigned char *) (src_short_ptr));
500         }
501         sum  = (sum >> 16) + (sum & 0x0FFFF);
502         sum += (sum >> 16);
503
504         return (unsigned short) (~sum);
505 }
506
507
508 void fastboot_splFillCheckData(unsigned int * splBuf,  int len)
509 {
510 #if   defined(CONFIG_SC8810)
511         *(splBuf + MAGIC_DATA_SAVE_OFFSET) = MAGIC_DATA;
512         *(splBuf + CHECKSUM_SAVE_OFFSET) = (unsigned int)fastboot_eMMCCheckSum((unsigned int *)&splBuf[CHECKSUM_START_OFFSET/4], SPL_CHECKSUM_LEN - CHECKSUM_START_OFFSET);
513
514 #elif defined(CONFIG_SC8825) || defined(CONFIG_SC7710G2) || defined(CONFIG_SC8830) || defined(CONFIG_SC9630)
515         EMMC_BootHeader *header;
516         header = (EMMC_BootHeader *)((unsigned char*)splBuf+BOOTLOADER_HEADER_OFFSET);
517         header->version  = 0;
518         header->magicData= MAGIC_DATA;
519         header->checkSum = (unsigned int)fastboot_eMMCCheckSum((unsigned char*)splBuf+BOOTLOADER_HEADER_OFFSET+sizeof(*header), SPL_CHECKSUM_LEN-(BOOTLOADER_HEADER_OFFSET+sizeof(*header)));
520 #ifdef CONFIG_SECURE_BOOT
521         header->hashLen  = CONFIG_SPL_HASH_LEN>>2;
522 #else
523         header->hashLen  = 0;
524 #endif
525 #endif
526 }
527
528 LOCAL void _makEcc(uint8* buf, uint32 size)
529 {
530         uint16 crc;
531         crc = calc_checksum(buf,size-4);
532         buf[size-4] = (uint8)(0xFF&crc);
533         buf[size-3] = (uint8)(0xFF&(crc>>8));
534         buf[size-2] = 0;
535         buf[size-1] = 0;
536
537         return;
538 }
539
540 /**
541         Erase the whole partition.
542 */
543 LOCAL int _fb_erase_partition(wchar_t *partition_name,unsigned int curArea,unsigned long base,unsigned long count)
544 {
545         if(NULL == partition_name)
546                 return 0;
547
548         if(count < FB_ERASE_ALIGN_LENGTH)
549         {
550                 unsigned char buf[FB_ERASE_ALIGN_LENGTH*EFI_SECTOR_SIZE] = {0xFF};
551                 if (!Emmc_Write(curArea, base,count,buf))
552                         return 0;
553         }
554         else
555         {
556                 if(base%FB_ERASE_ALIGN_LENGTH)
557                 {
558                         unsigned char buf[FB_ERASE_ALIGN_LENGTH*EFI_SECTOR_SIZE] = {0xFF};
559                         unsigned long base_sector_offset = 0;
560
561                         base_sector_offset = FB_ERASE_ALIGN_LENGTH - base%FB_ERASE_ALIGN_LENGTH;
562                         if (!Emmc_Write(curArea, base,base_sector_offset,buf))
563                                 return 0;
564                         count = ((count-base_sector_offset)/FB_ERASE_ALIGN_LENGTH)*FB_ERASE_ALIGN_LENGTH;
565                         base = base + base_sector_offset;
566                 }
567                 else
568                         count = (count/FB_ERASE_ALIGN_LENGTH)*FB_ERASE_ALIGN_LENGTH;
569
570                 if(count == 0)
571                         return 1;
572
573                 if (!Emmc_Erase(curArea, base,count))
574                         return 0;
575         }
576
577         return 1;
578 }
579
580 LOCAL BOOLEAN _fb_emmc_write(unsigned int part_type, uint32 startBlock,uint32 count,uint8* buf)
581 {
582         uint32 max_mutil_write = 0x8000;
583         uint32 each,saved =0;
584         uint32 base = startBlock;
585         while(count){
586                 each = MIN(count,max_mutil_write);
587                 if (!Emmc_Write(part_type, base,
588                                 each, buf+(saved*EFI_SECTOR_SIZE))) {
589                         fb_printf("emmc write error\n");
590                         return FALSE;
591                 }
592                 base += each;
593                 saved += each;
594                 count -= each;
595         }
596         return TRUE;
597 }
598
599 void cmd_flash(const char *arg, void *data, unsigned sz)
600 {
601         int i;
602         sparse_header_t sparse_header;
603         wchar_t partition_name[MAX_UTF_PARTITION_NAME_LEN];
604         unsigned int partition_type = PARTITION_USER;
605         unsigned int partition_purpose = FB_PARTITION_PURPOSE_NORMAL;
606         unsigned int img_format = FB_IMG_RAW;
607         uint32 startblock;
608         uint32 count;
609         disk_partition_t info;
610         block_dev_desc_t *dev = NULL;
611         uint32 total_sz = 0;
612         int32 retval = 0;
613         uint32 idx = 0;
614         uint32 size_left = 0;
615         uint8_t  *code_addr;
616
617         fb_printf("%s\n", __func__);
618         dev = get_dev("mmc", 1);
619         fb_printf("cmd_flash:data = 0x%x,ImageInfo[0].base_address = 0x%x,ImageInfo[1].base_address = 0x%x\n",data,ImageInfo[0].base_address,ImageInfo[1].base_address);
620         if(NULL == dev){
621                 fastboot_fail("Block device not supported!");
622                 return;
623         }
624
625         fb_printf("Cmd Flash partition:%s \n", arg);
626         for(i=0;i<MAX_UTF_PARTITION_NAME_LEN;i++)
627         {
628                 partition_name[i] = arg[i];
629                 if(0 == arg[i])
630                         break;
631         }
632         //get the special partition info
633         for(i=0;NULL != s_fb_special_partition_cfg[i].partition_name;i++)
634         {
635                 if(wcscmp(s_fb_special_partition_cfg[i].partition_name, partition_name) == 0)
636                 {
637                         partition_type = s_fb_special_partition_cfg[i].type;
638                         partition_purpose = s_fb_special_partition_cfg[i].purpose;
639                         img_format = s_fb_special_partition_cfg[i].img_format;
640                         break;
641                 }
642         }
643         memset(&sparse_header, 0, sizeof(sparse_header_t));
644         memcpy(&sparse_header, ImageInfo[0].base_address, sizeof(sparse_header));
645                 if ((sparse_header.magic == SPARSE_HEADER_MAGIC)&&(sparse_header.major_version == SPARSE_HEADER_MAJOR_VER)) {
646                         img_format = FB_IMG_WITH_SPARSE;
647                         printf("img_format =FB_IMG_WITH_SPARSE\n");
648                 }
649         count = ((sz +(EMMC_SECTOR_SIZE - 1)) & (~(EMMC_SECTOR_SIZE - 1)))/EMMC_SECTOR_SIZE;
650         switch(partition_type)
651         {
652                 case PARTITION_BOOT1:
653                         fastboot_splFillCheckData(data, sz);
654 #ifdef CONFIG_SECURE_BOOT
655                         secure_verify(L"splloader0",data,0);
656 #endif
657                         count = ((SPL_CHECKSUM_LEN +(EMMC_SECTOR_SIZE - 1)) & (~(EMMC_SECTOR_SIZE - 1)))/EMMC_SECTOR_SIZE;
658                         startblock = 0;
659                         goto emmc_write;
660                 case PARTITION_BOOT2:
661 #ifdef CONFIG_SECURE_BOOT
662                         secure_verify(L"splloader",data,0);
663 #endif
664                         startblock = 0x11000;
665                         partition_type = PARTITION_USER;
666                         goto emmc_write;
667                 case PARTITION_USER:
668                         {
669                                 //Check boot&recovery img's magic
670                                 if (!strcmp(arg, "boot") ||!strcmp(arg, "recovery")) {
671 #ifdef CONFIG_SECURE_BOOT
672 #ifdef CONFIG_ROM_VERIFY_SPL
673                 code_addr = get_code_addr(L"uboot", data);
674 #else
675                 code_addr = get_code_addr(NULL, data);
676 #endif
677                                 if (memcmp((void *)code_addr, BOOT_MAGIC, BOOT_MAGIC_SIZE)) {
678                                         fastboot_fail("image is not a boot image");
679                                         return;
680                                 }
681                                 secure_verify(L"uboot",data,0);
682 #else
683                                 if (memcmp((void *)data, BOOT_MAGIC, BOOT_MAGIC_SIZE)) {
684                                         fastboot_fail("image is not a boot image");
685                                         return;
686                                 }
687 #endif
688                                 }
689                                 //get partition info from emmc
690                                 if(0 != get_partition_info_by_name(dev, partition_name, &info))
691                                 {
692                                         fastboot_fail("eMMC get partition ERROR!");
693                                         return;
694                                 }
695
696                                 startblock = info.start;
697
698                                 if(FB_IMG_WITH_SPARSE == img_format)
699                                 {
700                                         int write_addr = ImageInfo[0].base_address;
701                                         int write_size = ImageInfo[0].data_size;
702                                         int move_size = 0;
703                                         int write_in = 0;
704
705                                         //1 move once
706                                         //2 block[1] is big enough
707                                         while (write_size > 0)
708                                         {
709                                                 fb_printf("cmd_flash: write_size %d\n",write_size);
710                                                 retval = write_simg2emmc("mmc", 1, partition_name, write_addr, write_size);
711
712                                                 if(-1 == retval){
713                                                         fb_printf("cmd_flash : retval =%d,idx = %d\n",retval,idx);
714                                                         fastboot_fail("eMMC WRITE_ERROR!");
715                                                         return;
716                                                 }
717                                                 if(0 == retval){
718                                                         fb_printf("cmd_flash : write end!\n");
719                                                         goto end;
720                                                 }
721
722                                                 size_left = write_size - retval;
723
724                                                 fb_printf("cmd flash:size = %d, retval = %d,size left %d\n", write_size, retval,size_left);
725
726                                                 write_in += retval;
727
728                                                 if (write_addr == ImageInfo[0].base_address)    {
729                                                         //move once
730                                                         move_size = size_left;
731                                                         fb_printf("flash second times size_left = %d!\n",size_left);
732
733                                                         if(move_size + ImageInfo[1].data_size > ImageInfo[1].max_size){
734                                                                 //error tips
735                                                                 fastboot_fail("eMMC imageinfo2 is too small!");
736                                                                 return;
737                                                         }
738
739                                                         if (move_size > 0){
740                                                                 memmove(ImageInfo[1].base_address + move_size,
741                                                                         ImageInfo[1].base_address,
742                                                                         ImageInfo[1].data_size);
743                                                                 memcpy(ImageInfo[1].base_address,
744                                                                         ImageInfo[0].base_address + retval, move_size);
745                                                         }
746                                                         write_addr = ImageInfo[1].base_address;
747                                                         write_size = move_size + ImageInfo[1].data_size;
748                                                 }
749                                                 else{
750                                                         fb_printf("flash third times size_left = %d!\n",size_left);
751                                                         write_addr = ImageInfo[1].base_address + write_in - (ImageInfo[0].data_size - move_size);
752                                                         write_size = size_left;
753                                                 }
754                                         }
755                                         goto end;
756                                 }
757                                 else if(FB_IMG_RAW == img_format){
758                                         uint32  data_left = 0;
759
760                                         fb_printf("cmd_flash: raw data\n");
761
762                                         if(FB_PARTITION_PURPOSE_NV == partition_purpose)
763                                         {
764                                                 nv_header_t *header_p = NULL;
765                                                 uint8  header_buf[EMMC_SECTOR_SIZE];
766
767                                                 memset(header_buf,0x00,EMMC_SECTOR_SIZE);
768                                                 header_p = header_buf;
769                                                 header_p->magic = NV_HEAD_MAGIC;
770                                                 header_p->len = FIXNV_SIZE;
771                                                 header_p->checksum =(uint32)calc_checksum((unsigned char *) data,FIXNV_SIZE);
772                                                 header_p->version = NV_VERSION;
773                                                 if(!_fb_emmc_write(partition_type, startblock, 1,header_buf)){
774                                                         fastboot_fail("eMMC WRITE_NVHEADER_ERROR!");
775                                                         return;
776                                                 }
777                                                 startblock++;
778                                                 count = ((FIXNV_SIZE +(EMMC_SECTOR_SIZE - 1)) & (~(EMMC_SECTOR_SIZE - 1)))/EMMC_SECTOR_SIZE;
779
780                                                 goto emmc_write;
781                                         }
782
783                                         //first part
784                                         data_left = ImageInfo[0].data_size%EMMC_SECTOR_SIZE;
785                                         count = ImageInfo[0].data_size/EMMC_SECTOR_SIZE;
786                                         if(!_fb_emmc_write(partition_type, startblock,count,(uint8*)ImageInfo[0].base_address)){
787                                                 fb_printf("cmd_flash: raw data write frist part error!\n");
788                                                 fastboot_fail("write frist part error!");
789                                                 return;
790                                         }
791                                         fb_printf("cmd_flash:raw data write first part success\n");
792                                         startblock += count;
793
794                                         if(0 == ImageInfo[1].data_size){
795                                                 //no data in second block
796                                                 if(0 == data_left){
797                                                         //write finish
798                                                         goto end;
799                                                 }
800                                                 else{
801                                                         if(!_fb_emmc_write(partition_type, startblock,1,ImageInfo[0].base_address+count*EMMC_SECTOR_SIZE)){
802                                                                 fb_printf("cmd_flash: raw data write tail part error!\n");
803                                                                 fastboot_fail("write tail part error!");
804                                                                 return;
805                                                         }
806                                                 }
807                                         }
808                                         else{
809                                                 if(data_left+ImageInfo[1].data_size > ImageInfo[1].max_size){
810                                                         //error tips
811                                                         fastboot_fail("eMMC raw data imageinfo2 is too small!\n");
812                                                         return;
813                                                 }
814                                                 memmove(ImageInfo[1].base_address+data_left,
815                                                         ImageInfo[1].base_address,
816                                                         ImageInfo[1].data_size);
817                                                 memcpy(ImageInfo[1].base_address,
818                                                         ImageInfo[0].base_address+ImageInfo[0].data_size-data_left,
819                                                         data_left);
820
821                                                 count = ((ImageInfo[1].data_size +(EMMC_SECTOR_SIZE - 1)) & (~(EMMC_SECTOR_SIZE - 1)))/EMMC_SECTOR_SIZE;
822                                                 if(!_fb_emmc_write(partition_type, startblock,count,(uint8*)ImageInfo[1].base_address)){
823                                                         fb_printf("cmd_flash: raw data write second part error!\n");
824                                                         fastboot_fail("write second part error!");
825                                                         return;
826                                                 }
827                                                 fb_printf("cmd_flash:raw data write second part success\n");
828                                         }
829                                         goto end;
830                                 }
831                                 else
832                                 {
833                                         fastboot_fail("Image Format Unkown!");
834                                         return;
835                                 }
836                         }
837                 default:
838                         fastboot_fail("Partition Type ERROR!");
839                         return;
840         }
841
842 emmc_write:
843         if(!_fb_emmc_write(partition_type, startblock, count,(uint8*)data)){
844                 fastboot_fail("eMMC WRITE_ERROR!");
845                 return;
846         }
847 end:
848         fastboot_okay("");
849 }
850
851 void cmd_erase(const char *arg, void *data, unsigned sz)
852 {
853         int i;
854         wchar_t partition_name[MAX_UTF_PARTITION_NAME_LEN];
855         unsigned long count=0, base_sector=0;
856         unsigned int curArea = 0;
857         disk_partition_t info;
858         block_dev_desc_t *dev = NULL;
859
860         dev = get_dev("mmc", 1);
861         if(NULL == dev){
862                 fastboot_fail("Block device not supported!");
863                 return;
864         }
865
866         fb_printf("Cmd Erase partition:%s \n", arg);
867
868         if (strcmp("params", arg) == 0){
869                 count = Emmc_GetCapacity(PARTITION_BOOT1);
870                 curArea = PARTITION_BOOT1;
871                 base_sector = 0;
872         }else if (strcmp("2ndbl", arg) == 0){
873                 count = Emmc_GetCapacity(PARTITION_BOOT2);
874                 curArea = PARTITION_BOOT2;
875                 base_sector = 0;
876         }
877         else{
878                 for(i=0;i<MAX_UTF_PARTITION_NAME_LEN;i++)
879                 {
880                         partition_name[i] = arg[i];
881                         if(0 == arg[i])
882                                 break;
883                 }
884                 //get partition info from emmc
885                 if(0 != get_partition_info_by_name(dev, partition_name, &info))
886                 {
887                         fastboot_fail("eMMC get partition ERROR!");
888                         return;
889                 }
890                 curArea = PARTITION_USER;
891                 count = info.size;
892                 base_sector = info.start;
893         }
894
895         if(!_fb_erase_partition(partition_name, curArea, base_sector, count))
896         {
897                 fastboot_fail("eMMC Erase Partition ERROR!");
898                 return;
899         }
900         fb_printf("Cmd Erase OK\n");
901         fastboot_okay("");
902         return;
903 }
904
905 #else
906 void cmd_flash(const char *arg, void *data, unsigned sz)
907 {
908         uint8_t  *code_addr;
909         int ret =-1;
910         int i;
911
912         fb_printf("%s, arg:%x date: 0x%x, sz 0x%x\n", __func__, arg, data, sz);
913
914         if (!strcmp(arg, "boot") || !strcmp(arg, "recovery")) {
915 #ifdef CONFIG_SECURE_BOOT
916                 code_addr = get_code_addr(NULL, data);
917                 if (memcmp((void *)code_addr, BOOT_MAGIC, BOOT_MAGIC_SIZE)) {
918                         fastboot_fail("image is not a boot image");
919                         return;
920                 }
921                 secure_verify(L"uboot",data,0);
922 #else
923                 if (memcmp((void *)data, BOOT_MAGIC, BOOT_MAGIC_SIZE)) {
924                         fastboot_fail("image is not a boot image");
925                         return;
926                 }
927 #endif
928         }
929
930 #ifdef CONFIG_SECURE_BOOT
931         if(strcmp(arg, "spl") == 0){
932                 secure_verify(L"splloader0",data,0);
933         }
934         else if (strcmp(arg, "2ndbl") == 0)
935         {
936                 secure_verify(L"splloader",data,0);
937         }
938 #endif
939
940         /**
941          *      FIX ME!
942          *      assume first image buffer is big enough for nv
943          */
944         for(i=0;s_nv_vol_info[i].vol != NULL;i++) {
945                 if(!strcmp(arg, s_nv_vol_info[i].vol)) {
946                         nv_header_t *header = NULL;
947                         uint8_t  tmp[NV_HEAD_LEN];
948
949                         memset(tmp,0x00,NV_HEAD_LEN);
950                         header = tmp;
951                         header->magic = NV_HEAD_MAGIC;
952                         header->len = FIXNV_SIZE;
953                         header->checksum =(uint32_t)calc_checksum((unsigned char *) data,FIXNV_SIZE);
954                         header->version = NV_VERSION;
955                         //write org nv
956                         ret = do_raw_data_write(arg, FIXNV_SIZE+NV_HEAD_LEN, NV_HEAD_LEN, 0, tmp);
957                         if(ret)
958                                 goto end;
959                         ret = do_raw_data_write(arg, 0, FIXNV_SIZE, NV_HEAD_LEN, data);
960                         if(ret)
961                                 goto end;
962                         //write bak nv
963                         ret = do_raw_data_write(s_nv_vol_info[i].bakvol, FIXNV_SIZE+NV_HEAD_LEN, NV_HEAD_LEN, 0, tmp);
964                         if(ret)
965                                 goto end;
966                         ret = do_raw_data_write(s_nv_vol_info[i].bakvol, 0, FIXNV_SIZE, NV_HEAD_LEN, data);
967                         goto end;
968                 }
969         }
970
971         if(ImageInfo[1].data_size) {
972                 uint32_t total_sz  = ImageInfo[0].data_size + ImageInfo[1].data_size;
973                 ret = do_raw_data_write(arg, total_sz, ImageInfo[0].data_size, 0, ImageInfo[0].base_address);
974                 if(ret)
975                         goto end;
976                 ret = do_raw_data_write(arg, 0, ImageInfo[1].data_size, ImageInfo[0].data_size, ImageInfo[1].base_address);
977         }
978         else {
979                 ret = do_raw_data_write(arg, ImageInfo[0].data_size, ImageInfo[0].data_size, 0, ImageInfo[0].base_address);
980         }
981
982 end:
983         if(!ret)
984                 fastboot_okay("");
985         else
986                 fastboot_fail("flash error");
987         return;
988 }
989
990 void cmd_erase(const char *arg, void *data, unsigned sz)
991 {
992         struct mtd_info *nand;
993         struct mtd_device *dev;
994         struct part_info *part;
995         nand_erase_options_t opts;
996         u8 pnum;
997         int ret;
998         char buf[1024];
999
1000         fb_printf("%s\n", __func__);
1001
1002         ret = find_dev_and_part(arg, &dev, &pnum, &part);
1003         if(!ret){
1004                 nand = &nand_info[dev->id->num];
1005                 memset(&opts, 0, sizeof(opts));
1006                 opts.offset = (loff_t)part->offset;
1007                 opts.length = (loff_t)part->size;
1008                 opts.jffs2 = 0;
1009                 opts.quiet = 1;
1010                 ret = nand_erase_opts(nand, &opts);
1011                 if(ret)
1012                         goto end;
1013         }
1014
1015         //just erase 1k now
1016         memset(buf, 0x0, 1024);
1017         ret = do_raw_data_write(arg, 1024, 1024, 0, buf);
1018
1019 end:
1020         if(ret)
1021                 fastboot_fail("nand erase error");
1022         else
1023                 fastboot_okay("");
1024         return;
1025 }
1026 #endif
1027
1028 extern void udc_power_off(void);
1029
1030 extern unsigned char raw_header[2048];
1031
1032 //void cmd_boot(const char *arg, void *data, unsigned sz)
1033 //{
1034 //      boot_img_hdr *hdr = raw_header;
1035 //      unsigned kernel_actual;
1036 //      unsigned ramdisk_actual;
1037 //      unsigned kernel_addr;
1038 //      unsigned ramdisk_addr;
1039 //      char * cmdline;
1040 //
1041 //      fb_printf("%s, arg: %s, data: %p, sz: 0x%x\n", __func__, arg, data, sz);
1042 //      memcpy(raw_header, data, 2048);
1043 //      if(memcmp(hdr->magic, BOOT_MAGIC, BOOT_MAGIC_SIZE)){
1044 //              fb_printf("boot image headr: %s\n", hdr->magic);
1045 //              fastboot_fail("bad boot image header");
1046 //              return;
1047 //      }
1048 //      kernel_actual= ROUND_TO_PAGE(hdr->kernel_size,(FLASH_PAGE_SIZE - 1));
1049 //      if(kernel_actual<=0){
1050 //              fastboot_fail("kernel image should not be zero");
1051 //              return;
1052 //      }
1053 //      ramdisk_actual= ROUND_TO_PAGE(hdr->ramdisk_size,(FLASH_PAGE_SIZE - 1));
1054 //      if(ramdisk_actual==0){
1055 //              fastboot_fail("ramdisk size error");
1056 //              return;
1057 //      }
1058 //
1059 //      memcpy((void*)hdr->kernel_addr, (void *)data + FLASH_PAGE_SIZE, kernel_actual);
1060 //      memcpy((void*)hdr->ramdisk_addr, (void *)data + FLASH_PAGE_SIZE + kernel_actual, ramdisk_actual);
1061 //
1062 //      fb_printf("kernel @0x%08x (0x%08x bytes)\n", hdr->kernel_addr, kernel_actual);
1063 //      fb_printf("ramdisk @0x%08x (0x%08x bytes)\n", hdr->ramdisk_addr, ramdisk_actual);
1064 //      //set boot environment
1065 //      if(hdr->cmdline[0]){
1066 //              cmdline = (char *)hdr->cmdline;
1067 //      }else{
1068 //              cmdline = getenv("bootargs");
1069 //      }
1070 //      fb_printf("cmdline %s\n", cmdline);
1071 //
1072 //      fastboot_okay("");
1073 //      udc_power_off();
1074 //      creat_atags(hdr->tags_addr, cmdline, hdr->ramdisk_addr, hdr->ramdisk_size);
1075 //      boot_linux(hdr->kernel_addr,hdr->tags_addr);
1076 //}
1077
1078 extern int do_cboot(cmd_tbl_t *cmdtp, int flag, int argc, char *const argv[]);
1079
1080 void cmd_continue(const char *arg, void *data, unsigned sz)
1081 {
1082         fastboot_okay("");
1083         udc_power_off();
1084         //do_cboot(NULL, 0, 1, NULL);
1085     normal_mode();
1086 }
1087
1088 void cmd_reboot(const char *arg, void *data, unsigned sz)
1089 {
1090         fastboot_okay("");
1091         //udc_power_off();
1092     reboot_devices(NORMAL_MODE);
1093 }
1094
1095 void cmd_reboot_bootloader(const char *arg, void *data, unsigned sz)
1096 {
1097         fastboot_okay("");
1098         udc_power_off();
1099     reboot_devices(FASTBOOT_MODE);
1100 }
1101
1102 void cmd_powerdown(const char *arg, void *data, unsigned sz)
1103 {
1104         fastboot_okay("");
1105     power_down_devices(0);
1106
1107 }
1108
1109 static void fastboot_command_loop(void)
1110 {
1111         struct fastboot_cmd *cmd;
1112         int r;
1113         fb_printf("fastboot: processing commands\n");
1114
1115 again:
1116         while (fastboot_state != STATE_ERROR) {
1117                 memset(buffer, 0 , 64);
1118                 r = usb_read(buffer, 64);
1119                 if (r < 0) break;
1120                 buffer[r] = 0;
1121                 fb_printf("fastboot: %s, r:%d\n", buffer, r);
1122
1123                 for (cmd = cmdlist; cmd; cmd = cmd->next) {
1124                         fb_printf("cmd list :%s \n", cmd->prefix);
1125                         if (memcmp(buffer, cmd->prefix, cmd->prefix_len))
1126                                 continue;
1127                         fastboot_state = STATE_COMMAND;
1128                         cmd->handle((const char*) buffer + cmd->prefix_len,
1129                                     (void*) ImageInfo[0].base_address, ImageInfo[0].data_size);
1130                         if (fastboot_state == STATE_COMMAND)
1131                                 fastboot_fail("unknown reason");
1132                         goto again;
1133                 }
1134
1135                 fastboot_fail("unknown command");
1136
1137         }
1138         fastboot_state = STATE_OFFLINE;
1139         fb_printf("fastboot: oops!\n");
1140 }
1141
1142 static int fastboot_handler(void *arg)
1143 {
1144         for (;;) {
1145                 fastboot_command_loop();
1146         }
1147         return 0;
1148 }
1149
1150 /*
1151 static void fastboot_notify(struct udc_gadget *gadget, unsigned event)
1152 {
1153         if (event == UDC_EVENT_ONLINE) {
1154                 event_signal(&usb_online, 0);
1155         }
1156 }
1157
1158 static struct udc_endpoint *fastboot_endpoints[2];
1159
1160 static struct udc_gadget fastboot_gadget = {
1161         .notify         = fastboot_notify,
1162         .ifc_class      = 0xff,
1163         .ifc_subclass   = 0x42,
1164         .ifc_protocol   = 0x03,
1165         .ifc_endpoints  = 2,
1166         .ifc_string     = "fastboot",
1167         .ept            = fastboot_endpoints,
1168 };
1169 */
1170 #if defined(CONFIG_CMD_FASTBOOT)
1171 int do_fastboot (cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
1172 {
1173         fb_printf("%s is alive\n", __func__);
1174         while(1){
1175                 usb_gadget_handle_interrupts();
1176         }
1177
1178         return 0;
1179 }
1180
1181 U_BOOT_CMD(
1182         fastboot,       1,      1,      do_fastboot,
1183         "android fastboot protocol",
1184 );
1185 #endif
1186
1187 int fastboot_init(void *base, unsigned size, struct usb_ep * ep_in, struct usb_ep *ep_out)
1188 {
1189         fb_printf("fastboot_init()\n");
1190
1191         ImageInfo[0].base_address = base;
1192         ImageInfo[0].max_size = size;
1193         ImageInfo[0].data_size = 0;
1194         ImageInfo[1].max_size =  0;
1195         ImageInfo[1].data_size = 0;
1196 #ifdef SCRATCH_ADDR_EXT1
1197         ImageInfo[1].base_address = SCRATCH_ADDR_EXT1;
1198         ImageInfo[1].max_size = FB_DOWNLOAD_BUF_EXT1_SIZE;
1199 #endif
1200         if(!ep_in) {
1201                 fb_printf("ep in is not alloc\r\n");
1202                 return -1;
1203         }
1204         in = ep_in;
1205
1206         if(!ep_out) {
1207                 fb_printf("ep out is not alloc\r\n");
1208                 return -1;
1209         }
1210         out = ep_out;
1211
1212         tx_req = usb_ep_alloc_request(in, 0);
1213         if(!tx_req)
1214         {
1215               fb_printf("ep tx request is not alloc\r\n");
1216               return -1;
1217         }
1218         rx_req =  usb_ep_alloc_request(out, 0);
1219         if(!rx_req)
1220         {
1221               fb_printf("ep rx request is not alloc\r\n");
1222               usb_ep_free_request(in,tx_req);
1223               return -1;
1224         }
1225 /*
1226         in = udc_endpoint_alloc(UDC_TYPE_BULK_IN, 512);
1227         if (!in)
1228                 goto fail_alloc_in;
1229         out = udc_endpoint_alloc(UDC_TYPE_BULK_OUT, 512);
1230         if (!out)
1231                 goto fail_alloc_out;
1232
1233         fastboot_endpoints[0] = in;
1234         fastboot_endpoints[1] = out;
1235
1236         req = udc_request_alloc();
1237         if (!req)
1238                 goto fail_alloc_req;
1239
1240         if (udc_register_gadget(&fastboot_gadget))
1241                 goto fail_udc_register;
1242 */
1243 /*
1244         static char cmd1[] = "getvar:";
1245         fastboot_register(cmd1, cmd_getvar);
1246 */
1247         fastboot_register("getvar:", cmd_getvar);
1248         fastboot_register("download:", cmd_download);
1249         fastboot_publish("version", "1.0");
1250
1251         fastboot_register("flash:", cmd_flash);
1252         fastboot_register("erase:", cmd_erase);
1253 //      fastboot_register("boot", cmd_boot);
1254         fastboot_register("reboot", cmd_reboot);
1255         fastboot_register("powerdown", cmd_powerdown);
1256         fastboot_register("continue", cmd_continue);
1257         fastboot_register("reboot-bootloader", cmd_reboot_bootloader);
1258
1259         fastboot_handler(0);
1260
1261         return 0;
1262 /*
1263 fail_udc_register:
1264         udc_request_free(req);
1265 fail_alloc_req:
1266         udc_endpoint_free(out);
1267 fail_alloc_out:
1268         udc_endpoint_free(in);
1269 fail_alloc_in:
1270         return -1;
1271 */
1272 }
1273