Don't use the same completion_event for both directions. This could cause problems...
[kugel-rb.git] / bootloader / main-pp.c
blobef0e199e3a233849f3d3876e290000faffc0c21a
1 /***************************************************************************
2 * __________ __ ___.
3 * Open \______ \ ____ ____ | | _\_ |__ _______ ___
4 * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
5 * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
6 * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
7 * \/ \/ \/ \/ \/
8 * $Id$
10 * Copyright (C) 2006 by Barry Wardell
12 * Based on Rockbox iriver bootloader by Linus Nielsen Feltzing
13 * and the ipodlinux bootloader by Daniel Palffy and Bernard Leach
15 * This program is free software; you can redistribute it and/or
16 * modify it under the terms of the GNU General Public License
17 * as published by the Free Software Foundation; either version 2
18 * of the License, or (at your option) any later version.
20 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
21 * KIND, either express or implied.
23 ****************************************************************************/
24 #include <stdio.h>
25 #include <stdlib.h>
27 #include "config.h"
28 #include "common.h"
29 #include "cpu.h"
30 #include "file.h"
31 #include "system.h"
32 #include "kernel.h"
33 #include "lcd.h"
34 #include "font.h"
35 #include "storage.h"
36 #include "adc.h"
37 #include "button.h"
38 #include "disk.h"
39 #include "crc32-mi4.h"
40 #include <string.h>
41 #include "power.h"
42 #if defined(SANSA_E200) || defined(PHILIPS_SA9200)
43 #include "i2c.h"
44 #include "backlight-target.h"
45 #endif
46 #if defined(SANSA_E200) || defined(SANSA_C200) || defined(PHILIPS_SA9200)
47 #include "usb.h"
48 #include "usb_drv.h"
49 #endif
50 #if defined(SAMSUNG_YH925)
51 /* this function (in lcd-yh925.c) resets the screen orientation for the OF
52 * for use with dualbooting */
53 void lcd_reset(void);
54 #endif
56 /* Show the Rockbox logo - in show_logo.c */
57 extern int show_logo(void);
59 /* Button definitions */
60 #if CONFIG_KEYPAD == IRIVER_H10_PAD
61 #define BOOTLOADER_BOOT_OF BUTTON_LEFT
63 #elif CONFIG_KEYPAD == SANSA_E200_PAD
64 #define BOOTLOADER_BOOT_OF BUTTON_LEFT
66 #elif CONFIG_KEYPAD == SANSA_C200_PAD
67 #define BOOTLOADER_BOOT_OF BUTTON_LEFT
69 #elif CONFIG_KEYPAD == MROBE100_PAD
70 #define BOOTLOADER_BOOT_OF BUTTON_POWER
72 #elif CONFIG_KEYPAD == PHILIPS_SA9200_PAD
73 #define BOOTLOADER_BOOT_OF BUTTON_VOL_UP
75 #elif CONFIG_KEYPAD == PHILIPS_HDD1630_PAD
76 #define BOOTLOADER_BOOT_OF BUTTON_MENU
78 #elif CONFIG_KEYPAD == SAMSUNG_YH_PAD
79 #define BOOTLOADER_BOOT_OF BUTTON_LEFT
81 #elif CONFIG_KEYPAD == SANSA_FUZE_PAD
82 #define BOOTLOADER_BOOT_OF BUTTON_LEFT
84 #endif
86 /* Maximum allowed firmware image size. 10MB is more than enough */
87 #define MAX_LOADSIZE (10*1024*1024)
89 /* A buffer to load the original firmware or Rockbox into */
90 unsigned char *loadbuffer = (unsigned char *)DRAM_START;
92 /* Bootloader version */
93 char version[] = APPSVERSION;
95 /* Locations and sizes in hidden partition on Sansa */
96 #if (CONFIG_STORAGE & STORAGE_SD)
97 #define PPMI_SECTOR_OFFSET 1024
98 #define PPMI_SECTORS 1
99 #define MI4_HEADER_SECTORS 1
100 #define NUM_PARTITIONS 2
102 #else
103 #define NUM_PARTITIONS 1
105 #endif
107 #define MI4_HEADER_SIZE 0x200
109 /* mi4 header structure */
110 struct mi4header_t {
111 unsigned char magic[4];
112 uint32_t version;
113 uint32_t length;
114 uint32_t crc32;
115 uint32_t enctype;
116 uint32_t mi4size;
117 uint32_t plaintext;
118 uint32_t dsa_key[10];
119 uint32_t pad[109];
120 unsigned char type[4];
121 unsigned char model[4];
124 /* PPMI header structure */
125 struct ppmi_header_t {
126 unsigned char magic[4];
127 uint32_t length;
128 uint32_t pad[126];
131 inline unsigned int le2int(unsigned char* buf)
133 int32_t res = (buf[3] << 24) | (buf[2] << 16) | (buf[1] << 8) | buf[0];
135 return res;
138 inline void int2le(unsigned int val, unsigned char* addr)
140 addr[0] = val & 0xFF;
141 addr[1] = (val >> 8) & 0xff;
142 addr[2] = (val >> 16) & 0xff;
143 addr[3] = (val >> 24) & 0xff;
146 struct tea_key {
147 const char * name;
148 uint32_t key[4];
151 #define NUM_KEYS (sizeof(tea_keytable)/sizeof(tea_keytable[0]))
152 struct tea_key tea_keytable[] = {
153 { "default" , { 0x20d36cc0, 0x10e8c07d, 0xc0e7dcaa, 0x107eb080 } },
154 { "sansa", { 0xe494e96e, 0x3ee32966, 0x6f48512b, 0xa93fbb42 } },
155 { "sansa_gh", { 0xd7b10538, 0xc662945b, 0x1b3fce68, 0xf389c0e6 } },
156 { "sansa_103", { 0x1d29ddc0, 0x2579c2cd, 0xce339e1a, 0x75465dfe } },
157 { "rhapsody", { 0x7aa9c8dc, 0xbed0a82a, 0x16204cc7, 0x5904ef38 } },
158 { "p610", { 0x950e83dc, 0xec4907f9, 0x023734b9, 0x10cfb7c7 } },
159 { "p640", { 0x220c5f23, 0xd04df68e, 0x431b5e25, 0x4dcc1fa1 } },
160 { "virgin", { 0xe83c29a1, 0x04862973, 0xa9b3f0d4, 0x38be2a9c } },
161 { "20gc_eng", { 0x0240772c, 0x6f3329b5, 0x3ec9a6c5, 0xb0c9e493 } },
162 { "20gc_fre", { 0xbede8817, 0xb23bfe4f, 0x80aa682d, 0xd13f598c } },
163 { "elio_p722", { 0x6af3b9f8, 0x777483f5, 0xae8181cc, 0xfa6d8a84 } },
164 { "c200", { 0xbf2d06fa, 0xf0e23d59, 0x29738132, 0xe2d04ca7 } },
165 { "c200_103", { 0x2a7968de, 0x15127979, 0x142e60a7, 0xe49c1893 } },
166 { "c200_106", { 0xa913d139, 0xf842f398, 0x3e03f1a6, 0x060ee012 } },
167 { "view", { 0x70e19bda, 0x0c69ea7d, 0x2b8b1ad1, 0xe9767ced } },
168 { "sa9200", { 0x33ea0236, 0x9247bdc5, 0xdfaedf9f, 0xd67c9d30 } },
169 { "hdd1630", { 0x04543ced, 0xcebfdbad, 0xf7477872, 0x0d12342e } },
174 tea_decrypt() from http://en.wikipedia.org/wiki/Tiny_Encryption_Algorithm
176 "Following is an adaptation of the reference encryption and decryption
177 routines in C, released into the public domain by David Wheeler and
178 Roger Needham:"
182 /* NOTE: The mi4 version of TEA uses a different initial value to sum compared
183 to the reference implementation and the main loop is 8 iterations, not
187 static void tea_decrypt(uint32_t* v0, uint32_t* v1, uint32_t* k) {
188 uint32_t sum=0xF1BBCDC8, i; /* set up */
189 uint32_t delta=0x9E3779B9; /* a key schedule constant */
190 uint32_t k0=k[0], k1=k[1], k2=k[2], k3=k[3]; /* cache key */
191 for(i=0; i<8; i++) { /* basic cycle start */
192 *v1 -= ((*v0<<4) + k2) ^ (*v0 + sum) ^ ((*v0>>5) + k3);
193 *v0 -= ((*v1<<4) + k0) ^ (*v1 + sum) ^ ((*v1>>5) + k1);
194 sum -= delta; /* end cycle */
198 /* mi4 files are encrypted in 64-bit blocks (two little-endian 32-bit
199 integers) and the key is incremented after each block
202 static void tea_decrypt_buf(unsigned char* src, unsigned char* dest, size_t n, uint32_t * key)
204 uint32_t v0, v1;
205 unsigned int i;
207 for (i = 0; i < (n / 8); i++) {
208 v0 = le2int(src);
209 v1 = le2int(src+4);
211 tea_decrypt(&v0, &v1, key);
213 int2le(v0, dest);
214 int2le(v1, dest+4);
216 src += 8;
217 dest += 8;
219 /* Now increment the key */
220 key[0]++;
221 if (key[0]==0) {
222 key[1]++;
223 if (key[1]==0) {
224 key[2]++;
225 if (key[2]==0) {
226 key[3]++;
233 static inline bool tea_test_key(unsigned char magic_enc[8], uint32_t * key, int unaligned)
235 unsigned char magic_dec[8];
236 tea_decrypt_buf(magic_enc, magic_dec, 8, key);
238 return (le2int(&magic_dec[4*unaligned]) == 0xaa55aa55);
241 static int tea_find_key(struct mi4header_t *mi4header, int fd)
243 unsigned int i;
244 int rc;
245 unsigned int j;
246 uint32_t key[4];
247 unsigned char magic_enc[8];
248 int key_found = -1;
249 unsigned int magic_location = mi4header->length-4;
250 int unaligned = 0;
252 if ( (magic_location % 8) != 0 )
254 unaligned = 1;
255 magic_location -= 4;
258 /* Load encrypted magic 0xaa55aa55 to check key */
259 lseek(fd, MI4_HEADER_SIZE + magic_location, SEEK_SET);
260 rc = read(fd, magic_enc, 8);
261 if(rc < 8 )
262 return EREAD_IMAGE_FAILED;
264 printf("Searching for key:");
266 for (i=0; i < NUM_KEYS && (key_found<0) ; i++) {
267 key[0] = tea_keytable[i].key[0];
268 key[1] = tea_keytable[i].key[1];
269 key[2] = tea_keytable[i].key[2];
270 key[3] = tea_keytable[i].key[3];
272 /* Now increment the key */
273 for(j=0; j<((magic_location-mi4header->plaintext)/8); j++){
274 key[0]++;
275 if (key[0]==0) {
276 key[1]++;
277 if (key[1]==0) {
278 key[2]++;
279 if (key[2]==0) {
280 key[3]++;
286 if (tea_test_key(magic_enc,key,unaligned))
288 key_found = i;
289 printf("%s...found", tea_keytable[i].name);
290 } else {
291 /* printf("%s...failed", tea_keytable[i].name); */
295 return key_found;
299 /* Load mi4 format firmware image */
300 int load_mi4(unsigned char* buf, char* firmware, unsigned int buffer_size)
302 int fd;
303 struct mi4header_t mi4header;
304 int rc;
305 unsigned long sum;
306 char filename[MAX_PATH];
308 snprintf(filename,sizeof(filename), BOOTDIR "/%s",firmware);
309 fd = open(filename, O_RDONLY);
310 if(fd < 0)
312 snprintf(filename,sizeof(filename),"/%s",firmware);
313 fd = open(filename, O_RDONLY);
314 if(fd < 0)
315 return EFILE_NOT_FOUND;
318 read(fd, &mi4header, MI4_HEADER_SIZE);
320 /* MI4 file size */
321 printf("mi4 size: %x", mi4header.mi4size);
323 if ((mi4header.mi4size-MI4_HEADER_SIZE) > buffer_size)
324 return EFILE_TOO_BIG;
326 /* CRC32 */
327 printf("CRC32: %x", mi4header.crc32);
329 /* Rockbox model id */
330 printf("Model id: %.4s", mi4header.model);
332 /* Read binary type (RBOS, RBBL) */
333 printf("Binary type: %.4s", mi4header.type);
335 /* Load firmware file */
336 lseek(fd, MI4_HEADER_SIZE, SEEK_SET);
337 rc = read(fd, buf, mi4header.mi4size-MI4_HEADER_SIZE);
338 if(rc < (int)mi4header.mi4size-MI4_HEADER_SIZE)
339 return EREAD_IMAGE_FAILED;
341 /* Check CRC32 to see if we have a valid file */
342 sum = chksum_crc32 (buf, mi4header.mi4size - MI4_HEADER_SIZE);
344 printf("Calculated CRC32: %x", sum);
346 if(sum != mi4header.crc32)
347 return EBAD_CHKSUM;
349 if( (mi4header.plaintext + MI4_HEADER_SIZE) != mi4header.mi4size)
351 /* Load encrypted firmware */
352 int key_index = tea_find_key(&mi4header, fd);
354 if (key_index < 0)
355 return EINVALID_FORMAT;
357 /* Plaintext part is already loaded */
358 buf += mi4header.plaintext;
360 /* Decrypt in-place */
361 tea_decrypt_buf(buf, buf,
362 mi4header.mi4size-(mi4header.plaintext+MI4_HEADER_SIZE),
363 tea_keytable[key_index].key);
365 printf("%s key used", tea_keytable[key_index].name);
367 /* Check decryption was successfull */
368 if(le2int(&buf[mi4header.length-mi4header.plaintext-4]) != 0xaa55aa55)
370 return EREAD_IMAGE_FAILED;
374 return EOK;
377 #if (CONFIG_STORAGE & STORAGE_SD)
378 /* Load mi4 firmware from a hidden disk partition */
379 int load_mi4_part(unsigned char* buf, struct partinfo* pinfo,
380 unsigned int buffer_size, bool disable_rebuild)
382 struct mi4header_t mi4header;
383 struct ppmi_header_t ppmi_header;
384 unsigned long sum;
386 /* Read header to find out how long the mi4 file is. */
387 storage_read_sectors(0, pinfo->start + PPMI_SECTOR_OFFSET,
388 PPMI_SECTORS, &ppmi_header);
390 /* The first four characters at 0x80000 (sector 1024) should be PPMI*/
391 if( memcmp(ppmi_header.magic, "PPMI", 4) )
392 return EFILE_NOT_FOUND;
394 printf("BL mi4 size: %x", ppmi_header.length);
396 /* Read mi4 header of the OF */
397 storage_read_sectors(0, pinfo->start + PPMI_SECTOR_OFFSET + PPMI_SECTORS
398 + (ppmi_header.length/512), MI4_HEADER_SECTORS, &mi4header);
400 /* We don't support encrypted mi4 files yet */
401 if( (mi4header.plaintext) != (mi4header.mi4size-MI4_HEADER_SIZE))
402 return EINVALID_FORMAT;
404 /* MI4 file size */
405 printf("OF mi4 size: %x", mi4header.mi4size);
407 if ((mi4header.mi4size-MI4_HEADER_SIZE) > buffer_size)
408 return EFILE_TOO_BIG;
410 /* CRC32 */
411 printf("CRC32: %x", mi4header.crc32);
413 /* Rockbox model id */
414 printf("Model id: %.4s", mi4header.model);
416 /* Read binary type (RBOS, RBBL) */
417 printf("Binary type: %.4s", mi4header.type);
419 /* Load firmware */
420 storage_read_sectors(0, pinfo->start + PPMI_SECTOR_OFFSET + PPMI_SECTORS
421 + (ppmi_header.length/512) + MI4_HEADER_SECTORS,
422 (mi4header.mi4size-MI4_HEADER_SIZE)/512, buf);
424 /* Check CRC32 to see if we have a valid file */
425 sum = chksum_crc32 (buf,mi4header.mi4size-MI4_HEADER_SIZE);
427 printf("Calculated CRC32: %x", sum);
429 if(sum != mi4header.crc32)
430 return EBAD_CHKSUM;
432 #ifdef SANSA_E200
433 if (disable_rebuild)
435 char block[512];
437 printf("Disabling database rebuild");
439 storage_read_sectors(0, pinfo->start + 0x3c08, 1, block);
440 block[0xe1] = 0;
441 storage_write_sectors(0, pinfo->start + 0x3c08, 1, block);
443 #else
444 (void) disable_rebuild;
445 #endif
447 return EOK;
449 #endif
451 void* main(void)
453 int i;
454 int btn;
455 int rc;
456 int num_partitions;
457 struct partinfo* pinfo;
458 #if defined(SANSA_E200) || defined(SANSA_C200) || defined(PHILIPS_SA9200) \
459 || defined (SANSA_VIEW)
460 #if !defined(USE_ROCKBOX_USB)
461 int usb_retry = 0;
462 #endif
463 bool usb = false;
464 #else
465 char buf[256];
466 unsigned short* identify_info;
467 #endif
469 chksum_crc32gentab ();
471 system_init();
472 kernel_init();
474 lcd_init();
476 font_init();
477 show_logo();
479 adc_init();
480 button_init();
481 #if defined(SANSA_E200) || defined(PHILIPS_SA9200)
482 i2c_init();
483 _backlight_on();
484 #endif
486 if (button_hold())
488 verbose = true;
489 lcd_clear_display();
490 printf("Hold switch on");
491 printf("Shutting down...");
492 sleep(HZ);
493 power_off();
496 btn = button_read_device();
498 /* Enable bootloader messages if any button is pressed */
499 if (btn) {
500 lcd_clear_display();
501 verbose = true;
504 #if defined(SANSA_E200) || defined(SANSA_C200) || defined(PHILIPS_SA9200)
505 #if !defined(USE_ROCKBOX_USB)
506 usb_init();
507 while (usb_drv_powered() && usb_retry < 5 && !usb)
509 usb_retry++;
510 sleep(HZ/4);
511 usb = (usb_detect() == USB_INSERTED);
513 if (usb)
514 btn |= BOOTLOADER_BOOT_OF;
515 #endif /* USE_ROCKBOX_USB */
516 #endif
518 lcd_setfont(FONT_SYSFIXED);
520 printf("Rockbox boot loader");
521 printf("Version: %s", version);
522 printf(MODEL_NAME);
524 i=storage_init();
525 #if !(CONFIG_STORAGE & STORAGE_SD)
526 if (i==0) {
527 identify_info=ata_get_identify();
528 /* Show model */
529 for (i=0; i < 20; i++) {
530 ((unsigned short*)buf)[i]=htobe16(identify_info[i+27]);
532 buf[40]=0;
533 for (i=39; i && buf[i]==' '; i--) {
534 buf[i]=0;
536 printf(buf);
537 } else {
538 error(EATA, i);
540 #endif
542 disk_init(IF_MV(0));
543 num_partitions = disk_mount_all();
544 if (num_partitions<=0)
546 error(EDISK,num_partitions);
549 /* Just list the first 2 partitions since we don't have any devices yet
550 that have more than that */
551 for(i=0; i<NUM_PARTITIONS; i++)
553 pinfo = disk_partinfo(i);
554 printf("Partition %d: 0x%02x %ld MB",
555 i, pinfo->type, pinfo->size / 2048);
558 /* Try loading Rockbox, if that fails, fall back to the OF */
559 if((btn & BOOTLOADER_BOOT_OF) == 0)
561 printf("Loading Rockbox...");
562 rc = load_mi4(loadbuffer, BOOTFILE, MAX_LOADSIZE);
563 if (rc < EOK)
565 bool old_verbose = verbose;
566 verbose = true;
567 printf("Can't load " BOOTFILE ": ");
568 printf(strerror(rc));
569 verbose = old_verbose;
570 btn |= BOOTLOADER_BOOT_OF;
571 sleep(5*HZ);
573 else
574 return (void*)loadbuffer;
577 if(btn & BOOTLOADER_BOOT_OF)
579 /* Load original mi4 firmware in to a memory buffer called loadbuffer.
580 The rest of the loading is done in crt0.S.
581 1) First try reading from the hidden partition (on Sansa only).
582 2) Next try a decrypted mi4 file in /System/OF.mi4
583 3) Finally, try a raw firmware binary in /System/OF.bin. It should be
584 a mi4 firmware decrypted and header stripped using mi4code.
586 printf("Loading original firmware...");
588 #if (CONFIG_STORAGE & STORAGE_SD)
589 /* First try a (hidden) firmware partition */
590 printf("Trying firmware partition");
591 pinfo = disk_partinfo(1);
592 if(pinfo->type == PARTITION_TYPE_OS2_HIDDEN_C_DRIVE)
594 rc = load_mi4_part(loadbuffer, pinfo, MAX_LOADSIZE, usb);
595 if (rc < EOK) {
596 printf("Can't load from partition");
597 printf(strerror(rc));
598 } else {
599 return (void*)loadbuffer;
601 } else {
602 printf("No hidden partition found.");
604 #endif
606 #if defined(PHILIPS_HDD1630)
607 printf("Trying /System/OF.ebn");
608 rc=load_mi4(loadbuffer, "/System/OF.ebn", MAX_LOADSIZE);
609 if (rc < EOK) {
610 printf("Can't load /System/OF.ebn");
611 printf(strerror(rc));
612 } else {
613 return (void*)loadbuffer;
615 #endif
617 printf("Trying /System/OF.mi4");
618 rc=load_mi4(loadbuffer, "/System/OF.mi4", MAX_LOADSIZE);
619 if (rc < EOK) {
620 printf("Can't load /System/OF.mi4");
621 printf(strerror(rc));
622 } else {
623 #if defined(SAMSUNG_YH925)
624 lcd_reset();
625 #endif
626 return (void*)loadbuffer;
629 printf("Trying /System/OF.bin");
630 rc=load_raw_firmware(loadbuffer, "/System/OF.bin", MAX_LOADSIZE);
631 if (rc < EOK) {
632 printf("Can't load /System/OF.bin");
633 printf(strerror(rc));
634 } else {
635 #if defined(SAMSUNG_YH925)
636 lcd_reset();
637 #endif
638 return (void*)loadbuffer;
641 error(0, 0);
643 return (void*)loadbuffer;